diff --git a/.gitignore b/.gitignore index f310f32921..0e71c973d8 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,5 @@ *~ -plan/ +/plan/ /target target/ /dist diff --git a/apps/photocraft/src/app_dirs.rs b/apps/photocraft/src/app_dirs.rs index a75520f3c4..ef1fa438c0 100644 --- a/apps/photocraft/src/app_dirs.rs +++ b/apps/photocraft/src/app_dirs.rs @@ -502,450 +502,4 @@ fn ensure_writable(dir: &Path) -> std::io::Result<()> { } #[cfg(test)] -mod tests { - use super::*; - use std::collections::HashMap; - use std::sync::atomic::{AtomicUsize, Ordering}; - - fn temp(tag: &str) -> PathBuf { - static N: AtomicUsize = AtomicUsize::new(0); - let d = std::env::temp_dir().join(format!("photocraft-app-dirs-{tag}-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed))); - let _ = std::fs::remove_dir_all(&d); - std::fs::create_dir_all(&d).unwrap(); - d - } - - fn env_of(pairs: &[(&str, &Path)]) -> impl Fn(&str) -> Option + use<> { - let m: HashMap = pairs.iter().map(|(k, v)| (k.to_string(), v.as_os_str().to_owned())).collect(); - move |k| m.get(k).cloned() - } - - /// A fake user folder that every platform's convention resolves under. - fn fake_home(root: &Path) -> impl Fn(&str) -> Option + use<> { - let home = root.join("home"); - let appdata = root.join("appdata"); - env_of(&[("HOME", &home), ("APPDATA", &appdata)]) - } - - #[test] - fn no_marker_uses_the_platform_dir() { - let root = temp("platform"); - let exe = root.join("bin"); - std::fs::create_dir_all(&exe).unwrap(); - let env = fake_home(&root); - let d = resolve(&env, Some(&exe)); - assert_eq!(d.mode, Mode::Platform); - assert!(d.warning.is_none()); - let dir = d.dir.unwrap(); - assert_eq!(Some(dir.clone()), platform_dir(&env)); - assert!(!dir.starts_with(&exe)); - assert!(!exe.join(PORTABLE_DATA_DIR).exists(), "no portable folder without a marker"); - // The convention per platform. - if cfg!(target_os = "macos") { - assert_eq!(dir, root.join("home/Library/Application Support/Photocraft")); - } else if cfg!(windows) { - assert_eq!(dir, root.join("appdata").join("Photocraft")); - } else { - assert_eq!(dir, root.join("home/.config/photocraft")); - } - let _ = std::fs::remove_dir_all(&root); - } - - #[test] - fn either_marker_keeps_everything_beside_the_exe() { - for marker in PORTABLE_MARKERS { - let root = temp("portable"); - let exe = root.join("PhotoCraft"); - std::fs::create_dir_all(&exe).unwrap(); - std::fs::write(exe.join(marker), b"").unwrap(); - let d = resolve(fake_home(&root), Some(&exe)); - assert_eq!(d.mode, Mode::Portable, "{marker}"); - assert!(d.warning.is_none()); - let dir = d.dir.unwrap(); - assert_eq!(dir, exe.join(PORTABLE_DATA_DIR)); - assert!(dir.is_dir(), "the data folder is created"); - assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0, "the write probe is removed"); - // Every derived path sits under the exe dir. - for sub in ["preferences.json", "Presets", "Recovery", crate::gpu_startup::MARKER_FILE] { - assert!(dir.join(sub).starts_with(&exe)); - } - assert!(!root.join("home").exists() && !root.join("appdata").exists(), "nothing written to the user folder"); - let _ = std::fs::remove_dir_all(&root); - } - } - - #[test] - fn a_marker_folder_is_not_a_marker() { - let root = temp("dir-marker"); - let exe = root.join("bin"); - std::fs::create_dir_all(exe.join("portable.txt")).unwrap(); - assert_eq!(resolve(fake_home(&root), Some(&exe)).mode, Mode::Platform); - let _ = std::fs::remove_dir_all(&root); - } - - #[test] - fn unwritable_portable_folder_falls_back_with_a_warning() { - let root = temp("unwritable"); - let exe = root.join("bin"); - std::fs::create_dir_all(&exe).unwrap(); - std::fs::write(exe.join("portable.txt"), b"").unwrap(); - // A file where the data folder should go: it can't be created, on every platform. - std::fs::write(exe.join(PORTABLE_DATA_DIR), b"in the way").unwrap(); - let env = fake_home(&root); - let d = resolve(&env, Some(&exe)); - assert_eq!(d.mode, Mode::Platform); - assert_eq!(d.dir, platform_dir(&env)); - let w = d.warning.unwrap(); - assert!(w.contains("portable") && w.contains("isn't writable"), "{w}"); - // No user folder at all: still no panic, just no directory. - let d = resolve(|_| None, Some(&exe)); - assert!(d.dir.is_none() && d.warning.is_some()); - let _ = std::fs::remove_dir_all(&root); - } - - #[test] - fn override_wins_over_portable() { - let root = temp("override"); - let exe = root.join("bin"); - std::fs::create_dir_all(&exe).unwrap(); - std::fs::write(exe.join("portable.txt"), b"").unwrap(); - let custom = root.join("custom"); - let d = resolve(env_of(&[("PHOTOCRAFT_CONFIG_DIR", &custom)]), Some(&exe)); - assert_eq!((d.mode, d.dir), (Mode::Override, Some(custom))); - assert!(!exe.join(PORTABLE_DATA_DIR).exists()); - let _ = std::fs::remove_dir_all(&root); - } - - /// #5648: on Windows, autosaves go to the machine-local `%LOCALAPPDATA%`, not the roaming - /// profile; an override or portable folder keeps them inside itself. - #[test] - fn autosaves_stay_out_of_the_roaming_profile() { - let root = temp("recovery-local"); - let settings = root.join("appdata").join("Photocraft"); - let local = root.join("local"); - let env = env_of(&[("LOCALAPPDATA", &local)]); - let platform = DataDir { dir: Some(settings.clone()), mode: Mode::Platform, warning: None }; - let expected = if cfg!(windows) { local.join("Photocraft").join("Recovery") } else { settings.join("Recovery") }; - assert_eq!(resolve_recovery(&platform, &env), Some(expected)); - for mode in [Mode::Override, Mode::Portable] { - let d = DataDir { dir: Some(settings.clone()), mode, warning: None }; - assert_eq!(resolve_recovery(&d, &env), Some(settings.join("Recovery")), "{mode:?}"); - } - // No (or an empty) LOCALAPPDATA: beside the settings, as before. - let empty = PathBuf::new(); - assert_eq!(resolve_recovery(&platform, env_of(&[("LOCALAPPDATA", &empty)])), Some(settings.join("Recovery"))); - assert_eq!(resolve_recovery(&platform, |_| None), Some(settings.join("Recovery"))); - let nowhere = DataDir { dir: None, mode: Mode::Platform, warning: None }; - assert_eq!(resolve_recovery(&nowhere, |_| None), None); - let _ = std::fs::remove_dir_all(&root); - } - - /// #6612: on Linux (and other XDG systems) autosaves go to `$XDG_STATE_HOME`, by default - /// `~/.local/state`, not the config folder; a relative `XDG_STATE_HOME` is ignored. Windows - /// and macOS don't read it, and an override or portable folder keeps them inside itself. - #[test] - fn autosaves_go_to_the_xdg_state_folder() { - let root = temp("recovery-xdg"); - let settings = root.join("home").join(".config").join("photocraft"); - let home = root.join("home"); - let state = root.join("state"); - let platform = DataDir { dir: Some(settings.clone()), mode: Mode::Platform, warning: None }; - let xdg = !cfg!(windows) && !cfg!(target_os = "macos"); - let expect = |xdg_path: PathBuf| Some(if xdg { xdg_path } else { settings.join("Recovery") }); - assert_eq!(resolve_recovery(&platform, env_of(&[("XDG_STATE_HOME", &state), ("HOME", &home)])), expect(state.join("photocraft").join("Recovery"))); - let default = home.join(".local").join("state").join("photocraft").join("Recovery"); - assert_eq!(resolve_recovery(&platform, env_of(&[("HOME", &home)])), expect(default.clone())); - let relative = PathBuf::from("relative/state"); - assert_eq!(resolve_recovery(&platform, env_of(&[("XDG_STATE_HOME", &relative), ("HOME", &home)])), expect(default.clone())); - let empty = PathBuf::new(); - assert_eq!(resolve_recovery(&platform, env_of(&[("XDG_STATE_HOME", &empty), ("HOME", &home)])), expect(default)); - // No home at all: beside the settings, as before. - assert_eq!(resolve_recovery(&platform, |_| None), Some(settings.join("Recovery"))); - for mode in [Mode::Override, Mode::Portable] { - let d = DataDir { dir: Some(settings.clone()), mode, warning: None }; - assert_eq!(resolve_recovery(&d, env_of(&[("XDG_STATE_HOME", &state), ("HOME", &home)])), Some(settings.join("Recovery")), "{mode:?}"); - } - let _ = std::fs::remove_dir_all(&root); - } - - /// An autosave bundle and its sidecar, as `format::Autosaver` writes them. - fn autosave(dir: &Path, key: &str) { - std::fs::create_dir_all(dir.join(format!("{key}.pcraft"))).unwrap(); - std::fs::write(dir.join(format!("{key}.pcraft")).join("manifest.json"), key).unwrap(); - std::fs::write(dir.join(format!("{key}.json")), key).unwrap(); - } - - #[test] - fn autosaves_from_the_old_folder_move_to_the_new_one() { - let root = temp("recovery-move"); - let legacy = root.join("roaming").join("Recovery"); - let dir = root.join("local").join("Photocraft").join("Recovery"); - autosave(&legacy, "a"); - assert_eq!(adopt_legacy_recovery(&legacy, &dir), dir); - assert!(!legacy.exists(), "the old folder is gone"); - assert_eq!(std::fs::read_to_string(dir.join("a.pcraft").join("manifest.json")).unwrap(), "a"); - assert!(dir.join("a.json").is_file()); - let _ = std::fs::remove_dir_all(&root); - } - - #[test] - fn autosaves_merge_into_an_existing_folder_without_overwriting() { - let root = temp("recovery-merge"); - let legacy = root.join("roaming").join("Recovery"); - let dir = root.join("local").join("Recovery"); - autosave(&legacy, "old"); - autosave(&legacy, "both"); - // A temp file of an interrupted write moves along, for the recovery store's sweep. - let temp_file = ".old.json.4294967294-0.pcsave.tmp"; - std::fs::write(legacy.join(temp_file), b"partial").unwrap(); - std::fs::create_dir_all(&dir).unwrap(); - std::fs::write(dir.join("both.json"), "newer").unwrap(); - assert_eq!(adopt_legacy_recovery(&legacy, &dir), dir); - assert!(dir.join(temp_file).is_file() && !legacy.join(temp_file).exists()); - assert!(dir.join("old.pcraft").is_dir() && dir.join("old.json").is_file(), "a whole autosave moves"); - assert_eq!(std::fs::read_to_string(dir.join("both.json")).unwrap(), "newer", "never overwritten"); - assert!(!dir.join("both.pcraft").exists(), "a clashing autosave isn't split"); - assert!(legacy.join("both.pcraft").is_dir() && legacy.join("both.json").is_file(), "it stays behind whole"); - let _ = std::fs::remove_dir_all(&root); - } - - #[test] - fn autosaves_that_cannot_move_keep_being_used_where_they_are() { - let root = temp("recovery-stuck"); - let legacy = root.join("roaming").join("Recovery"); - autosave(&legacy, "a"); - // A file where the new folder's parent should be: nothing can be created there. - std::fs::write(root.join("blocked"), b"in the way").unwrap(); - let dir = root.join("blocked").join("Recovery"); - assert_eq!(adopt_legacy_recovery(&legacy, &dir), legacy); - assert!(legacy.join("a.json").is_file(), "nothing lost"); - let _ = std::fs::remove_dir_all(&root); - } - - #[test] - fn an_empty_old_folder_is_removed_even_where_it_cannot_move() { - let root = temp("recovery-empty"); - let legacy = root.join("roaming").join("Recovery"); - std::fs::create_dir_all(&legacy).unwrap(); - std::fs::write(root.join("blocked"), b"in the way").unwrap(); - let dir = root.join("blocked").join("Recovery"); - assert_eq!(adopt_legacy_recovery(&legacy, &dir), dir, "nothing to keep listed"); - assert!(!legacy.exists(), "the empty old folder is gone"); - let _ = std::fs::remove_dir_all(&root); - } - - /// Where a rename can't cross volumes (a roaming profile on a network share), an autosave - /// is copied whole, nested folders included, and only then removed. - #[test] - fn a_move_across_volumes_copies_then_removes() { - let root = temp("recovery-copy"); - let legacy = root.join("roaming").join("Recovery"); - autosave(&legacy, "a"); - std::fs::create_dir_all(legacy.join("a.pcraft").join("tiles")).unwrap(); - std::fs::write(legacy.join("a.pcraft").join("tiles").join("t0.zst"), b"tile").unwrap(); - let dir = root.join("local").join("Recovery"); - std::fs::create_dir_all(root.join("local")).unwrap(); - move_across(&legacy, &dir).unwrap(); - assert!(!legacy.exists(), "the original is removed after the copy"); - assert_eq!(side_leftovers(&root.join("roaming")), 0, "nothing is left held aside"); - assert_eq!(std::fs::read_to_string(dir.join("a.pcraft").join("manifest.json")).unwrap(), "a"); - assert_eq!(std::fs::read(dir.join("a.pcraft").join("tiles").join("t0.zst")).unwrap(), b"tile"); - assert_eq!(std::fs::read_to_string(dir.join("a.json")).unwrap(), "a"); - // One file on its own, as the per-autosave moves do. - move_across(&dir.join("a.json"), &root.join("a.json")).unwrap(); - assert!(!dir.join("a.json").exists() && root.join("a.json").is_file()); - assert_eq!(side_leftovers(&dir) + side_leftovers(&root), 0); - let _ = std::fs::remove_dir_all(&root); - } - - #[test] - fn a_failed_copy_puts_the_original_back_and_leaves_no_partial_copy() { - let root = temp("recovery-copy-fail"); - let legacy = root.join("Recovery"); - autosave(&legacy, "a"); - // Deeper than any bundle: the copy gives up part way. - let mut deep = legacy.join("a.pcraft"); - for _ in 0..=MAX_COPY_DEPTH { - deep = deep.join("d"); - } - std::fs::create_dir_all(&deep).unwrap(); - let dir = root.join("Local"); - assert!(move_across(&legacy, &dir).is_err()); - assert!(!dir.exists(), "nothing is published"); - assert_eq!(side_leftovers(&root), 0, "no staged copy, nothing left held aside"); - assert!(legacy.join("a.json").is_file() && deep.is_dir(), "the original is back in place"); - // A target that already exists is never copied into or removed. - std::fs::create_dir_all(&dir).unwrap(); - std::fs::write(dir.join("keep"), b"mine").unwrap(); - assert!(move_across(&legacy.join("a.json"), &dir).is_err()); - assert_eq!(std::fs::read(dir.join("keep")).unwrap(), b"mine"); - assert!(legacy.join("a.json").is_file()); - assert_eq!(side_leftovers(&root) + side_leftovers(&legacy), 0); - let _ = std::fs::remove_dir_all(&root); - } - - /// Staged (`.moving`) and held (`.held`) side paths left in `dir`. - fn side_leftovers(dir: &Path) -> usize { - std::fs::read_dir(dir) - .unwrap() - .flatten() - .filter(|e| e.file_name().to_str().is_some_and(|n| side_of(n, STAGED).is_some() || side_of(n, HELD).is_some())) - .count() - } - - /// The target appears after the copy is staged (another process got there first): publishing - /// fails, that process's target keeps its contents, the staged copy is removed and the - /// original is left as it was. Folder and file alike. - #[test] - fn a_target_that_appears_while_copying_is_never_replaced_or_removed() { - let root = temp("recovery-race"); - let legacy = root.join("roaming").join("Recovery"); - autosave(&legacy, "a"); - let local = root.join("local"); - std::fs::create_dir_all(&local).unwrap(); - // A whole folder. - let dir = local.join("Recovery"); - let staged = stage_copy(&legacy, &dir).unwrap(); - autosave(&dir, "theirs"); - let e = publish(&staged, &dir).unwrap_err(); - assert_eq!(e.kind(), std::io::ErrorKind::AlreadyExists); - assert_eq!(std::fs::read_to_string(dir.join("theirs.json")).unwrap(), "theirs", "their folder is intact"); - assert!(!dir.join("a.json").exists(), "nothing was copied into it"); - assert!(!staged.exists() && side_leftovers(&local) == 0, "only the staged copy is removed"); - assert!(legacy.join("a.json").is_file(), "the original is untouched"); - // One file. - let to = dir.join("a.json"); - let staged = stage_copy(&legacy.join("a.json"), &to).unwrap(); - std::fs::write(&to, "theirs").unwrap(); - assert_eq!(publish(&staged, &to).unwrap_err().kind(), std::io::ErrorKind::AlreadyExists); - assert_eq!(std::fs::read_to_string(&to).unwrap(), "theirs"); - assert!(!staged.exists() && legacy.join("a.json").is_file()); - let _ = std::fs::remove_dir_all(&root); - } - - /// A process holds the lock and is copying the old folder (held aside, copy staged) when a - /// second launch gives up waiting. The second launch must get the new folder, never the old - /// one, and what it writes there survives the first one finishing: the publish refuses the - /// now-existing folder and the original is put back, so both autosaves stay (#6412 review). - #[test] - fn a_launch_that_times_out_never_writes_where_a_move_removes() { - let _spawns = crate::no_child_spawns(); - let root = temp("recovery-timeout"); - let legacy = root.join("roaming").join("Recovery"); - autosave(&legacy, "old"); - let local = root.join("local"); - std::fs::create_dir_all(&local).unwrap(); - let dir = local.join("Recovery"); - // First process: takes the lock, sets the original aside and stages its copy, then pauses. - let first = std::fs::OpenOptions::new().create(true).truncate(false).write(true).open(local.join(MIGRATION_LOCK)).unwrap(); - first.lock().unwrap(); - let held = hold(&legacy).unwrap(); - let staged = stage_copy(&held, &dir).unwrap(); - // Second launch: times out and writes a newer autosave where it was told to. - let chosen = adopt_legacy_recovery_waiting(&legacy, &dir, std::time::Duration::ZERO); - assert_eq!(chosen, dir, "a launch that couldn't get the lock never uses the old folder"); - autosave(&chosen, "new"); - // First process resumes: publish, and on failure put the original back (as `move_across`). - assert_eq!(publish(&staged, &dir).unwrap_err().kind(), std::io::ErrorKind::AlreadyExists); - put_back(&held, &legacy); - drop(first); - assert_eq!(std::fs::read_to_string(dir.join("new.json")).unwrap(), "new", "the newer autosave survives"); - assert_eq!(std::fs::read_to_string(legacy.join("old.json")).unwrap(), "old", "the old one is back in place"); - assert_eq!(side_leftovers(&local) + side_leftovers(&root.join("roaming")), 0); - // The next launch merges them. - assert_eq!(adopt_legacy_recovery_waiting(&legacy, &dir, std::time::Duration::ZERO), dir); - assert!(dir.join("old.json").is_file() && dir.join("new.json").is_file() && !legacy.exists()); - let _ = std::fs::remove_dir_all(&root); - } - - /// A writer that still uses the old path while it is being copied (an older PhotoCraft) - /// starts a new folder there; the move removes only the original it held aside. - #[test] - fn a_write_to_the_old_path_during_a_copy_is_not_removed() { - let root = temp("recovery-old-writer"); - let legacy = root.join("roaming").join("Recovery"); - autosave(&legacy, "old"); - let local = root.join("local"); - std::fs::create_dir_all(&local).unwrap(); - let dir = local.join("Recovery"); - let held = hold(&legacy).unwrap(); - let staged = stage_copy(&held, &dir).unwrap(); - autosave(&legacy, "new"); - publish(&staged, &dir).unwrap(); - std::fs::remove_dir_all(&held).unwrap(); - assert_eq!(std::fs::read_to_string(dir.join("old.json")).unwrap(), "old"); - assert_eq!(std::fs::read_to_string(legacy.join("new.json")).unwrap(), "new", "the new write is untouched"); - let _ = std::fs::remove_dir_all(&root); - } - - /// What a process killed mid-move left is tidied at the next move: a held original is put - /// back (it may be the only copy) and moved, a staged copy is removed; other dot-files and - /// look-alike names are not touched. - #[test] - fn a_killed_move_is_tidied_next_time() { - let root = temp("recovery-stale"); - let roaming = root.join("roaming"); - let legacy = roaming.join("Recovery"); - autosave(&legacy, "a"); - let held = hold(&legacy).unwrap(); - assert!(!legacy.exists() && held.is_dir()); - let local = root.join("local"); - let dir = local.join("Recovery"); - let stale = local.join(".Recovery.4294967294-3.moving"); - autosave(&stale, "half"); - let kept = [local.join(".Recovery.moving"), local.join(".keep.1-x.moving"), local.join("notes.txt")]; - for k in &kept { - std::fs::write(k, b"x").unwrap(); - } - assert_eq!(adopt_legacy_recovery_waiting(&legacy, &dir, std::time::Duration::ZERO), dir); - assert_eq!(std::fs::read_to_string(dir.join("a.json")).unwrap(), "a", "the held original was put back and moved"); - assert!(!stale.exists(), "the stale staged copy is gone"); - assert_eq!(side_leftovers(&roaming), 0); - assert!(kept.iter().all(|k| k.is_file()), "only side names are touched"); - assert_eq!(side_of(".a.json.12-0.moving", STAGED), Some("a.json")); - assert!(side_of("a.json.12-0.moving", STAGED).is_none() && side_of(".a.json.-0.moving", STAGED).is_none()); - assert!(side_of(".a.json.12-0.held", STAGED).is_none() && side_of(".a.json.12-0.held", HELD) == Some("a.json")); - let _ = std::fs::remove_dir_all(&root); - } - - /// While another process holds the move lock, a launch moves nothing and uses the new folder; - /// once the lock is released, the move happens. - #[test] - fn a_move_waits_for_another_process_holding_the_lock() { - let _spawns = crate::no_child_spawns(); - let root = temp("recovery-lock"); - let legacy = root.join("roaming").join("Recovery"); - autosave(&legacy, "a"); - let dir = root.join("local").join("Recovery"); - std::fs::create_dir_all(root.join("local")).unwrap(); - let held = std::fs::OpenOptions::new().create(true).truncate(false).write(true).open(root.join("local").join(MIGRATION_LOCK)).unwrap(); - held.lock().unwrap(); - assert_eq!(adopt_legacy_recovery_waiting(&legacy, &dir, std::time::Duration::ZERO), dir); - assert!(legacy.join("a.json").is_file() && !dir.exists(), "nothing moved under another's lock"); - drop(held); - assert_eq!(adopt_legacy_recovery_waiting(&legacy, &dir, std::time::Duration::ZERO), dir); - assert!(dir.join("a.json").is_file() && !legacy.exists()); - let _ = std::fs::remove_dir_all(&root); - } - - #[test] - fn no_old_folder_or_the_same_folder_changes_nothing() { - let root = temp("recovery-noop"); - let dir = root.join("Recovery"); - assert_eq!(adopt_legacy_recovery(&root.join("missing"), &dir), dir); - assert!(!dir.exists(), "nothing is created up front"); - autosave(&dir, "a"); - assert_eq!(adopt_legacy_recovery(&dir, &dir), dir); - assert!(dir.join("a.json").is_file()); - let _ = std::fs::remove_dir_all(&root); - } - - #[test] - fn missing_exe_dir_or_env_never_panics() { - let d = resolve(|_| None, None); - assert_eq!((d.mode, d.dir), (Mode::Platform, None)); - let empty = PathBuf::new(); - let d = resolve(env_of(&[("PHOTOCRAFT_CONFIG_DIR", &empty), ("HOME", &empty), ("APPDATA", &empty)]), None); - assert_eq!(d.dir, None, "empty variables are ignored"); - } -} +mod tests; diff --git a/apps/photocraft/src/app_dirs/tests.rs b/apps/photocraft/src/app_dirs/tests.rs new file mode 100644 index 0000000000..c54299fb58 --- /dev/null +++ b/apps/photocraft/src/app_dirs/tests.rs @@ -0,0 +1,445 @@ +use super::*; +use std::collections::HashMap; +use std::sync::atomic::{AtomicUsize, Ordering}; + +fn temp(tag: &str) -> PathBuf { + static N: AtomicUsize = AtomicUsize::new(0); + let d = std::env::temp_dir().join(format!("photocraft-app-dirs-{tag}-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed))); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d +} + +fn env_of(pairs: &[(&str, &Path)]) -> impl Fn(&str) -> Option + use<> { + let m: HashMap = pairs.iter().map(|(k, v)| (k.to_string(), v.as_os_str().to_owned())).collect(); + move |k| m.get(k).cloned() +} + +/// A fake user folder that every platform's convention resolves under. +fn fake_home(root: &Path) -> impl Fn(&str) -> Option + use<> { + let home = root.join("home"); + let appdata = root.join("appdata"); + env_of(&[("HOME", &home), ("APPDATA", &appdata)]) +} + +#[test] +fn no_marker_uses_the_platform_dir() { + let root = temp("platform"); + let exe = root.join("bin"); + std::fs::create_dir_all(&exe).unwrap(); + let env = fake_home(&root); + let d = resolve(&env, Some(&exe)); + assert_eq!(d.mode, Mode::Platform); + assert!(d.warning.is_none()); + let dir = d.dir.unwrap(); + assert_eq!(Some(dir.clone()), platform_dir(&env)); + assert!(!dir.starts_with(&exe)); + assert!(!exe.join(PORTABLE_DATA_DIR).exists(), "no portable folder without a marker"); + // The convention per platform. + if cfg!(target_os = "macos") { + assert_eq!(dir, root.join("home/Library/Application Support/Photocraft")); + } else if cfg!(windows) { + assert_eq!(dir, root.join("appdata").join("Photocraft")); + } else { + assert_eq!(dir, root.join("home/.config/photocraft")); + } + let _ = std::fs::remove_dir_all(&root); +} + +#[test] +fn either_marker_keeps_everything_beside_the_exe() { + for marker in PORTABLE_MARKERS { + let root = temp("portable"); + let exe = root.join("PhotoCraft"); + std::fs::create_dir_all(&exe).unwrap(); + std::fs::write(exe.join(marker), b"").unwrap(); + let d = resolve(fake_home(&root), Some(&exe)); + assert_eq!(d.mode, Mode::Portable, "{marker}"); + assert!(d.warning.is_none()); + let dir = d.dir.unwrap(); + assert_eq!(dir, exe.join(PORTABLE_DATA_DIR)); + assert!(dir.is_dir(), "the data folder is created"); + assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0, "the write probe is removed"); + // Every derived path sits under the exe dir. + for sub in ["preferences.json", "Presets", "Recovery", crate::gpu_startup::MARKER_FILE] { + assert!(dir.join(sub).starts_with(&exe)); + } + assert!(!root.join("home").exists() && !root.join("appdata").exists(), "nothing written to the user folder"); + let _ = std::fs::remove_dir_all(&root); + } +} + +#[test] +fn a_marker_folder_is_not_a_marker() { + let root = temp("dir-marker"); + let exe = root.join("bin"); + std::fs::create_dir_all(exe.join("portable.txt")).unwrap(); + assert_eq!(resolve(fake_home(&root), Some(&exe)).mode, Mode::Platform); + let _ = std::fs::remove_dir_all(&root); +} + +#[test] +fn unwritable_portable_folder_falls_back_with_a_warning() { + let root = temp("unwritable"); + let exe = root.join("bin"); + std::fs::create_dir_all(&exe).unwrap(); + std::fs::write(exe.join("portable.txt"), b"").unwrap(); + // A file where the data folder should go: it can't be created, on every platform. + std::fs::write(exe.join(PORTABLE_DATA_DIR), b"in the way").unwrap(); + let env = fake_home(&root); + let d = resolve(&env, Some(&exe)); + assert_eq!(d.mode, Mode::Platform); + assert_eq!(d.dir, platform_dir(&env)); + let w = d.warning.unwrap(); + assert!(w.contains("portable") && w.contains("isn't writable"), "{w}"); + // No user folder at all: still no panic, just no directory. + let d = resolve(|_| None, Some(&exe)); + assert!(d.dir.is_none() && d.warning.is_some()); + let _ = std::fs::remove_dir_all(&root); +} + +#[test] +fn override_wins_over_portable() { + let root = temp("override"); + let exe = root.join("bin"); + std::fs::create_dir_all(&exe).unwrap(); + std::fs::write(exe.join("portable.txt"), b"").unwrap(); + let custom = root.join("custom"); + let d = resolve(env_of(&[("PHOTOCRAFT_CONFIG_DIR", &custom)]), Some(&exe)); + assert_eq!((d.mode, d.dir), (Mode::Override, Some(custom))); + assert!(!exe.join(PORTABLE_DATA_DIR).exists()); + let _ = std::fs::remove_dir_all(&root); +} + +/// #5648: on Windows, autosaves go to the machine-local `%LOCALAPPDATA%`, not the roaming +/// profile; an override or portable folder keeps them inside itself. +#[test] +fn autosaves_stay_out_of_the_roaming_profile() { + let root = temp("recovery-local"); + let settings = root.join("appdata").join("Photocraft"); + let local = root.join("local"); + let env = env_of(&[("LOCALAPPDATA", &local)]); + let platform = DataDir { dir: Some(settings.clone()), mode: Mode::Platform, warning: None }; + let expected = if cfg!(windows) { local.join("Photocraft").join("Recovery") } else { settings.join("Recovery") }; + assert_eq!(resolve_recovery(&platform, &env), Some(expected)); + for mode in [Mode::Override, Mode::Portable] { + let d = DataDir { dir: Some(settings.clone()), mode, warning: None }; + assert_eq!(resolve_recovery(&d, &env), Some(settings.join("Recovery")), "{mode:?}"); + } + // No (or an empty) LOCALAPPDATA: beside the settings, as before. + let empty = PathBuf::new(); + assert_eq!(resolve_recovery(&platform, env_of(&[("LOCALAPPDATA", &empty)])), Some(settings.join("Recovery"))); + assert_eq!(resolve_recovery(&platform, |_| None), Some(settings.join("Recovery"))); + let nowhere = DataDir { dir: None, mode: Mode::Platform, warning: None }; + assert_eq!(resolve_recovery(&nowhere, |_| None), None); + let _ = std::fs::remove_dir_all(&root); +} + +/// #6612: on Linux (and other XDG systems) autosaves go to `$XDG_STATE_HOME`, by default +/// `~/.local/state`, not the config folder; a relative `XDG_STATE_HOME` is ignored. Windows +/// and macOS don't read it, and an override or portable folder keeps them inside itself. +#[test] +fn autosaves_go_to_the_xdg_state_folder() { + let root = temp("recovery-xdg"); + let settings = root.join("home").join(".config").join("photocraft"); + let home = root.join("home"); + let state = root.join("state"); + let platform = DataDir { dir: Some(settings.clone()), mode: Mode::Platform, warning: None }; + let xdg = !cfg!(windows) && !cfg!(target_os = "macos"); + let expect = |xdg_path: PathBuf| Some(if xdg { xdg_path } else { settings.join("Recovery") }); + assert_eq!(resolve_recovery(&platform, env_of(&[("XDG_STATE_HOME", &state), ("HOME", &home)])), expect(state.join("photocraft").join("Recovery"))); + let default = home.join(".local").join("state").join("photocraft").join("Recovery"); + assert_eq!(resolve_recovery(&platform, env_of(&[("HOME", &home)])), expect(default.clone())); + let relative = PathBuf::from("relative/state"); + assert_eq!(resolve_recovery(&platform, env_of(&[("XDG_STATE_HOME", &relative), ("HOME", &home)])), expect(default.clone())); + let empty = PathBuf::new(); + assert_eq!(resolve_recovery(&platform, env_of(&[("XDG_STATE_HOME", &empty), ("HOME", &home)])), expect(default)); + // No home at all: beside the settings, as before. + assert_eq!(resolve_recovery(&platform, |_| None), Some(settings.join("Recovery"))); + for mode in [Mode::Override, Mode::Portable] { + let d = DataDir { dir: Some(settings.clone()), mode, warning: None }; + assert_eq!(resolve_recovery(&d, env_of(&[("XDG_STATE_HOME", &state), ("HOME", &home)])), Some(settings.join("Recovery")), "{mode:?}"); + } + let _ = std::fs::remove_dir_all(&root); +} + +/// An autosave bundle and its sidecar, as `format::Autosaver` writes them. +fn autosave(dir: &Path, key: &str) { + std::fs::create_dir_all(dir.join(format!("{key}.pcraft"))).unwrap(); + std::fs::write(dir.join(format!("{key}.pcraft")).join("manifest.json"), key).unwrap(); + std::fs::write(dir.join(format!("{key}.json")), key).unwrap(); +} + +#[test] +fn autosaves_from_the_old_folder_move_to_the_new_one() { + let root = temp("recovery-move"); + let legacy = root.join("roaming").join("Recovery"); + let dir = root.join("local").join("Photocraft").join("Recovery"); + autosave(&legacy, "a"); + assert_eq!(adopt_legacy_recovery(&legacy, &dir), dir); + assert!(!legacy.exists(), "the old folder is gone"); + assert_eq!(std::fs::read_to_string(dir.join("a.pcraft").join("manifest.json")).unwrap(), "a"); + assert!(dir.join("a.json").is_file()); + let _ = std::fs::remove_dir_all(&root); +} + +#[test] +fn autosaves_merge_into_an_existing_folder_without_overwriting() { + let root = temp("recovery-merge"); + let legacy = root.join("roaming").join("Recovery"); + let dir = root.join("local").join("Recovery"); + autosave(&legacy, "old"); + autosave(&legacy, "both"); + // A temp file of an interrupted write moves along, for the recovery store's sweep. + let temp_file = ".old.json.4294967294-0.pcsave.tmp"; + std::fs::write(legacy.join(temp_file), b"partial").unwrap(); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("both.json"), "newer").unwrap(); + assert_eq!(adopt_legacy_recovery(&legacy, &dir), dir); + assert!(dir.join(temp_file).is_file() && !legacy.join(temp_file).exists()); + assert!(dir.join("old.pcraft").is_dir() && dir.join("old.json").is_file(), "a whole autosave moves"); + assert_eq!(std::fs::read_to_string(dir.join("both.json")).unwrap(), "newer", "never overwritten"); + assert!(!dir.join("both.pcraft").exists(), "a clashing autosave isn't split"); + assert!(legacy.join("both.pcraft").is_dir() && legacy.join("both.json").is_file(), "it stays behind whole"); + let _ = std::fs::remove_dir_all(&root); +} + +#[test] +fn autosaves_that_cannot_move_keep_being_used_where_they_are() { + let root = temp("recovery-stuck"); + let legacy = root.join("roaming").join("Recovery"); + autosave(&legacy, "a"); + // A file where the new folder's parent should be: nothing can be created there. + std::fs::write(root.join("blocked"), b"in the way").unwrap(); + let dir = root.join("blocked").join("Recovery"); + assert_eq!(adopt_legacy_recovery(&legacy, &dir), legacy); + assert!(legacy.join("a.json").is_file(), "nothing lost"); + let _ = std::fs::remove_dir_all(&root); +} + +#[test] +fn an_empty_old_folder_is_removed_even_where_it_cannot_move() { + let root = temp("recovery-empty"); + let legacy = root.join("roaming").join("Recovery"); + std::fs::create_dir_all(&legacy).unwrap(); + std::fs::write(root.join("blocked"), b"in the way").unwrap(); + let dir = root.join("blocked").join("Recovery"); + assert_eq!(adopt_legacy_recovery(&legacy, &dir), dir, "nothing to keep listed"); + assert!(!legacy.exists(), "the empty old folder is gone"); + let _ = std::fs::remove_dir_all(&root); +} + +/// Where a rename can't cross volumes (a roaming profile on a network share), an autosave +/// is copied whole, nested folders included, and only then removed. +#[test] +fn a_move_across_volumes_copies_then_removes() { + let root = temp("recovery-copy"); + let legacy = root.join("roaming").join("Recovery"); + autosave(&legacy, "a"); + std::fs::create_dir_all(legacy.join("a.pcraft").join("tiles")).unwrap(); + std::fs::write(legacy.join("a.pcraft").join("tiles").join("t0.zst"), b"tile").unwrap(); + let dir = root.join("local").join("Recovery"); + std::fs::create_dir_all(root.join("local")).unwrap(); + move_across(&legacy, &dir).unwrap(); + assert!(!legacy.exists(), "the original is removed after the copy"); + assert_eq!(side_leftovers(&root.join("roaming")), 0, "nothing is left held aside"); + assert_eq!(std::fs::read_to_string(dir.join("a.pcraft").join("manifest.json")).unwrap(), "a"); + assert_eq!(std::fs::read(dir.join("a.pcraft").join("tiles").join("t0.zst")).unwrap(), b"tile"); + assert_eq!(std::fs::read_to_string(dir.join("a.json")).unwrap(), "a"); + // One file on its own, as the per-autosave moves do. + move_across(&dir.join("a.json"), &root.join("a.json")).unwrap(); + assert!(!dir.join("a.json").exists() && root.join("a.json").is_file()); + assert_eq!(side_leftovers(&dir) + side_leftovers(&root), 0); + let _ = std::fs::remove_dir_all(&root); +} + +#[test] +fn a_failed_copy_puts_the_original_back_and_leaves_no_partial_copy() { + let root = temp("recovery-copy-fail"); + let legacy = root.join("Recovery"); + autosave(&legacy, "a"); + // Deeper than any bundle: the copy gives up part way. + let mut deep = legacy.join("a.pcraft"); + for _ in 0..=MAX_COPY_DEPTH { + deep = deep.join("d"); + } + std::fs::create_dir_all(&deep).unwrap(); + let dir = root.join("Local"); + assert!(move_across(&legacy, &dir).is_err()); + assert!(!dir.exists(), "nothing is published"); + assert_eq!(side_leftovers(&root), 0, "no staged copy, nothing left held aside"); + assert!(legacy.join("a.json").is_file() && deep.is_dir(), "the original is back in place"); + // A target that already exists is never copied into or removed. + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("keep"), b"mine").unwrap(); + assert!(move_across(&legacy.join("a.json"), &dir).is_err()); + assert_eq!(std::fs::read(dir.join("keep")).unwrap(), b"mine"); + assert!(legacy.join("a.json").is_file()); + assert_eq!(side_leftovers(&root) + side_leftovers(&legacy), 0); + let _ = std::fs::remove_dir_all(&root); +} + +/// Staged (`.moving`) and held (`.held`) side paths left in `dir`. +fn side_leftovers(dir: &Path) -> usize { + std::fs::read_dir(dir) + .unwrap() + .flatten() + .filter(|e| e.file_name().to_str().is_some_and(|n| side_of(n, STAGED).is_some() || side_of(n, HELD).is_some())) + .count() +} + +/// The target appears after the copy is staged (another process got there first): publishing +/// fails, that process's target keeps its contents, the staged copy is removed and the +/// original is left as it was. Folder and file alike. +#[test] +fn a_target_that_appears_while_copying_is_never_replaced_or_removed() { + let root = temp("recovery-race"); + let legacy = root.join("roaming").join("Recovery"); + autosave(&legacy, "a"); + let local = root.join("local"); + std::fs::create_dir_all(&local).unwrap(); + // A whole folder. + let dir = local.join("Recovery"); + let staged = stage_copy(&legacy, &dir).unwrap(); + autosave(&dir, "theirs"); + let e = publish(&staged, &dir).unwrap_err(); + assert_eq!(e.kind(), std::io::ErrorKind::AlreadyExists); + assert_eq!(std::fs::read_to_string(dir.join("theirs.json")).unwrap(), "theirs", "their folder is intact"); + assert!(!dir.join("a.json").exists(), "nothing was copied into it"); + assert!(!staged.exists() && side_leftovers(&local) == 0, "only the staged copy is removed"); + assert!(legacy.join("a.json").is_file(), "the original is untouched"); + // One file. + let to = dir.join("a.json"); + let staged = stage_copy(&legacy.join("a.json"), &to).unwrap(); + std::fs::write(&to, "theirs").unwrap(); + assert_eq!(publish(&staged, &to).unwrap_err().kind(), std::io::ErrorKind::AlreadyExists); + assert_eq!(std::fs::read_to_string(&to).unwrap(), "theirs"); + assert!(!staged.exists() && legacy.join("a.json").is_file()); + let _ = std::fs::remove_dir_all(&root); +} + +/// A process holds the lock and is copying the old folder (held aside, copy staged) when a +/// second launch gives up waiting. The second launch must get the new folder, never the old +/// one, and what it writes there survives the first one finishing: the publish refuses the +/// now-existing folder and the original is put back, so both autosaves stay (#6412 review). +#[test] +fn a_launch_that_times_out_never_writes_where_a_move_removes() { + let _spawns = crate::no_child_spawns(); + let root = temp("recovery-timeout"); + let legacy = root.join("roaming").join("Recovery"); + autosave(&legacy, "old"); + let local = root.join("local"); + std::fs::create_dir_all(&local).unwrap(); + let dir = local.join("Recovery"); + // First process: takes the lock, sets the original aside and stages its copy, then pauses. + let first = std::fs::OpenOptions::new().create(true).truncate(false).write(true).open(local.join(MIGRATION_LOCK)).unwrap(); + first.lock().unwrap(); + let held = hold(&legacy).unwrap(); + let staged = stage_copy(&held, &dir).unwrap(); + // Second launch: times out and writes a newer autosave where it was told to. + let chosen = adopt_legacy_recovery_waiting(&legacy, &dir, std::time::Duration::ZERO); + assert_eq!(chosen, dir, "a launch that couldn't get the lock never uses the old folder"); + autosave(&chosen, "new"); + // First process resumes: publish, and on failure put the original back (as `move_across`). + assert_eq!(publish(&staged, &dir).unwrap_err().kind(), std::io::ErrorKind::AlreadyExists); + put_back(&held, &legacy); + drop(first); + assert_eq!(std::fs::read_to_string(dir.join("new.json")).unwrap(), "new", "the newer autosave survives"); + assert_eq!(std::fs::read_to_string(legacy.join("old.json")).unwrap(), "old", "the old one is back in place"); + assert_eq!(side_leftovers(&local) + side_leftovers(&root.join("roaming")), 0); + // The next launch merges them. + assert_eq!(adopt_legacy_recovery_waiting(&legacy, &dir, std::time::Duration::ZERO), dir); + assert!(dir.join("old.json").is_file() && dir.join("new.json").is_file() && !legacy.exists()); + let _ = std::fs::remove_dir_all(&root); +} + +/// A writer that still uses the old path while it is being copied (an older PhotoCraft) +/// starts a new folder there; the move removes only the original it held aside. +#[test] +fn a_write_to_the_old_path_during_a_copy_is_not_removed() { + let root = temp("recovery-old-writer"); + let legacy = root.join("roaming").join("Recovery"); + autosave(&legacy, "old"); + let local = root.join("local"); + std::fs::create_dir_all(&local).unwrap(); + let dir = local.join("Recovery"); + let held = hold(&legacy).unwrap(); + let staged = stage_copy(&held, &dir).unwrap(); + autosave(&legacy, "new"); + publish(&staged, &dir).unwrap(); + std::fs::remove_dir_all(&held).unwrap(); + assert_eq!(std::fs::read_to_string(dir.join("old.json")).unwrap(), "old"); + assert_eq!(std::fs::read_to_string(legacy.join("new.json")).unwrap(), "new", "the new write is untouched"); + let _ = std::fs::remove_dir_all(&root); +} + +/// What a process killed mid-move left is tidied at the next move: a held original is put +/// back (it may be the only copy) and moved, a staged copy is removed; other dot-files and +/// look-alike names are not touched. +#[test] +fn a_killed_move_is_tidied_next_time() { + let root = temp("recovery-stale"); + let roaming = root.join("roaming"); + let legacy = roaming.join("Recovery"); + autosave(&legacy, "a"); + let held = hold(&legacy).unwrap(); + assert!(!legacy.exists() && held.is_dir()); + let local = root.join("local"); + let dir = local.join("Recovery"); + let stale = local.join(".Recovery.4294967294-3.moving"); + autosave(&stale, "half"); + let kept = [local.join(".Recovery.moving"), local.join(".keep.1-x.moving"), local.join("notes.txt")]; + for k in &kept { + std::fs::write(k, b"x").unwrap(); + } + assert_eq!(adopt_legacy_recovery_waiting(&legacy, &dir, std::time::Duration::ZERO), dir); + assert_eq!(std::fs::read_to_string(dir.join("a.json")).unwrap(), "a", "the held original was put back and moved"); + assert!(!stale.exists(), "the stale staged copy is gone"); + assert_eq!(side_leftovers(&roaming), 0); + assert!(kept.iter().all(|k| k.is_file()), "only side names are touched"); + assert_eq!(side_of(".a.json.12-0.moving", STAGED), Some("a.json")); + assert!(side_of("a.json.12-0.moving", STAGED).is_none() && side_of(".a.json.-0.moving", STAGED).is_none()); + assert!(side_of(".a.json.12-0.held", STAGED).is_none() && side_of(".a.json.12-0.held", HELD) == Some("a.json")); + let _ = std::fs::remove_dir_all(&root); +} + +/// While another process holds the move lock, a launch moves nothing and uses the new folder; +/// once the lock is released, the move happens. +#[test] +fn a_move_waits_for_another_process_holding_the_lock() { + let _spawns = crate::no_child_spawns(); + let root = temp("recovery-lock"); + let legacy = root.join("roaming").join("Recovery"); + autosave(&legacy, "a"); + let dir = root.join("local").join("Recovery"); + std::fs::create_dir_all(root.join("local")).unwrap(); + let held = std::fs::OpenOptions::new().create(true).truncate(false).write(true).open(root.join("local").join(MIGRATION_LOCK)).unwrap(); + held.lock().unwrap(); + assert_eq!(adopt_legacy_recovery_waiting(&legacy, &dir, std::time::Duration::ZERO), dir); + assert!(legacy.join("a.json").is_file() && !dir.exists(), "nothing moved under another's lock"); + drop(held); + assert_eq!(adopt_legacy_recovery_waiting(&legacy, &dir, std::time::Duration::ZERO), dir); + assert!(dir.join("a.json").is_file() && !legacy.exists()); + let _ = std::fs::remove_dir_all(&root); +} + +#[test] +fn no_old_folder_or_the_same_folder_changes_nothing() { + let root = temp("recovery-noop"); + let dir = root.join("Recovery"); + assert_eq!(adopt_legacy_recovery(&root.join("missing"), &dir), dir); + assert!(!dir.exists(), "nothing is created up front"); + autosave(&dir, "a"); + assert_eq!(adopt_legacy_recovery(&dir, &dir), dir); + assert!(dir.join("a.json").is_file()); + let _ = std::fs::remove_dir_all(&root); +} + +#[test] +fn missing_exe_dir_or_env_never_panics() { + let d = resolve(|_| None, None); + assert_eq!((d.mode, d.dir), (Mode::Platform, None)); + let empty = PathBuf::new(); + let d = resolve(env_of(&[("PHOTOCRAFT_CONFIG_DIR", &empty), ("HOME", &empty), ("APPDATA", &empty)]), None); + assert_eq!(d.dir, None, "empty variables are ignored"); +} diff --git a/apps/photocraft/src/gpu_startup.rs b/apps/photocraft/src/gpu_startup.rs index 9b08d4d292..56d721e495 100644 --- a/apps/photocraft/src/gpu_startup.rs +++ b/apps/photocraft/src/gpu_startup.rs @@ -569,605 +569,4 @@ pub fn read_rendering_prefs(path: Option<&Path>) -> (GpuBackend, RenderingMode) } #[cfg(test)] -mod tests { - use super::*; - use GpuBackend::*; - - fn crashed(backend: &str, adapter_backend: &str) -> Marker { - Marker { backend: backend.into(), adapter: "Intel(R) UHD Graphics".into(), adapter_backend: adapter_backend.into(), ..Default::default() } - } - - #[test] - fn low_latency_drawing_is_read_before_the_window_opens_and_defaults_off() { - let dir = std::env::temp_dir().join(format!("photocraft-low-latency-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let file = dir.join("preferences.json"); - let read = |json: &str| { - std::fs::write(&file, json).unwrap(); - read_low_latency(Some(&file)) - }; - assert!(read(r#"{"performance":{"lowLatencyDrawing":true}}"#)); - assert!(!read(r#"{"performance":{"lowLatencyDrawing":false}}"#)); - assert!(!read(r#"{"performance":{"lowLatencyDrawing":"nope"}}"#), "garbage keeps the default (off)"); - assert!(!read("not json")); - assert!(!read_low_latency(None), "no settings file: the default (off)"); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn display_server_preference_is_read_before_the_window_opens() { - use photocraft_engine::prefs::LinuxDisplayServer; - let dir = std::env::temp_dir().join(format!("photocraft-display-server-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let file = dir.join("preferences.json"); - let read = |json: &str| { - std::fs::write(&file, json).unwrap(); - read_display_server(Some(&file)) - }; - assert_eq!(read(r#"{"performance":{"linuxDisplayServer":"x11"}}"#), LinuxDisplayServer::X11); - assert_eq!(read(r#"{"performance":{"linuxDisplayServer":"auto","gpuBackend":"vulkan"}}"#), LinuxDisplayServer::Auto); - // Unknown values, other types, broken JSON and a missing file all start as Auto. - assert_eq!(read(r#"{"performance":{"linuxDisplayServer":"wayland"}}"#), LinuxDisplayServer::Auto); - assert_eq!(read(r#"{"performance":{"linuxDisplayServer":11}}"#), LinuxDisplayServer::Auto); - assert_eq!(read("{not json"), LinuxDisplayServer::Auto); - assert_eq!(read_display_server(Some(&dir.join("missing.json"))), LinuxDisplayServer::Auto); - assert_eq!(read_display_server(None), LinuxDisplayServer::Auto); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn cpu_policy_ignores_hardware_backend_override() { - let p = plan_with_mode(Vulkan, RenderingMode::Cpu, None, Some("vulkan"), false, Os::Windows); - assert_eq!(p.backend, Cpu); - assert!(p.env.is_none()); - assert_eq!(plan_with_mode(Vulkan, RenderingMode::Cpu, Some(&crashed("vulkan", "vulkan")), None, false, Os::Windows).backend, Cpu); - let p = plan_with_mode(Auto, RenderingMode::Gpu, None, Some("vulkan"), true, Os::Windows); - assert_eq!(p.backend, Cpu); - assert!(p.env.is_none()); - } - - #[test] - fn no_marker_uses_the_preference() { - for os in [Os::Windows, Os::Mac, Os::Other] { - let p = plan(Auto, None, None, false, os); - assert_eq!(p, Plan { backend: Auto, env: None, reason: None, remember: false }); - } - assert_eq!(plan(Dx12, None, None, false, Os::Windows).backend, Dx12); - assert_eq!(plan(Gl, None, None, false, Os::Other).backend, Gl); - // A backend the platform lacks is `auto`. - assert_eq!(plan(Metal, None, None, false, Os::Windows).backend, Auto); - assert_eq!(plan(Dx12, None, None, false, Os::Mac).backend, Auto); - assert_eq!(plan(Dx12, None, None, false, Os::Other).backend, Auto); - } - - #[test] - fn a_crash_moves_down_each_chain_and_is_remembered() { - // Windows: Vulkan → DX12 → CPU. - let p = plan(Auto, Some(&crashed("auto", "vulkan")), None, false, Os::Windows); - assert_eq!((p.backend, p.remember), (Dx12, true)); - assert!(p.reason.as_deref().unwrap_or("").contains("vulkan (Intel(R) UHD Graphics)"), "{p:?}"); - assert_eq!(plan(Dx12, Some(&crashed("dx12", "dx12")), None, false, Os::Windows).backend, Cpu); - // Crashed before the adapter was chosen (enumeration): from `auto`. - assert_eq!(plan(Auto, Some(&crashed("auto", "")), None, false, Os::Windows).backend, Dx12); - // `auto` that had already picked DX12 (the Intel default) goes to the CPU. - assert_eq!(plan(Auto, Some(&crashed("auto", "dx12")), None, false, Os::Windows).backend, Cpu); - // Linux: Vulkan → GL → CPU. - assert_eq!(plan(Auto, Some(&crashed("auto", "vulkan")), None, false, Os::Other).backend, Gl); - assert_eq!(plan(Gl, Some(&crashed("gl", "gl")), None, false, Os::Other).backend, Cpu); - // macOS: Metal → CPU. - assert_eq!(plan(Auto, Some(&crashed("auto", "metal")), None, false, Os::Mac).backend, Cpu); - // The CPU path stays there, and isn't "remembered" again. - let p = plan(Cpu, Some(&crashed("cpu", "dx12")), None, false, Os::Windows); - assert_eq!((p.backend, p.remember), (Cpu, false)); - // An unreadable marker still counts as a crash. - assert_eq!(plan(Auto, Some(&Marker::parse("{garbage")), None, false, Os::Windows).backend, Dx12); - } - - #[test] - fn env_override_beats_everything() { - let p = plan(Cpu, Some(&crashed("auto", "vulkan")), Some("vulkan"), false, Os::Windows); - assert_eq!(p.env.as_deref(), Some("vulkan")); - assert_eq!(p.backend, Auto); - assert!(!p.remember); - assert_eq!(backends(&p, Os::Windows), None, "egui reads WGPU_BACKEND itself"); - // A crash under the override doesn't count against `auto` later. - let p = plan(Auto, Some(&Marker { backend: "env:vulkan".into(), ..Default::default() }), None, false, Os::Windows); - assert_eq!(p.backend, Auto); - // Empty means unset. - assert_eq!(plan(Auto, None, Some(" "), false, Os::Windows).env, None); - // --safe-gpu with the override: CPU canvas, the override's backends. - assert_eq!(plan(Auto, None, Some("dx12"), true, Os::Windows).backend, Cpu); - } - - /// #3483: A temporary CPU recovery must not change the next launch. - #[test] - fn cpu_recovery_requires_explicit_confirmation_to_persist() { - let gl_crash = crashed("gl", "gl"); - let cpu = plan_with_mode(Auto, RenderingMode::Auto, Some(&gl_crash), None, false, Os::Other); - assert_eq!((cpu.backend, cpu.remember), (Cpu, true)); - assert_eq!(backend_to_remember(&cpu), None); - - let safe = plan_with_mode(Auto, RenderingMode::Auto, None, None, true, Os::Other); - assert_eq!(safe.backend, Cpu); - assert_eq!(backend_to_remember(&safe), None); - // An unconfirmed fallback leaves the original automatic selection intact. - assert_eq!(plan_with_mode(Auto, RenderingMode::Auto, None, None, false, Os::Other).backend, Auto); - // A working hardware fallback can still be remembered. - let vk_crash = crashed("auto", "vulkan"); - let gl = plan_with_mode(Auto, RenderingMode::Auto, Some(&vk_crash), None, false, Os::Other); - assert_eq!(backend_to_remember(&gl), Some(Gl)); - // CPU explicitly selected in preferences still works. - assert_eq!(plan_with_mode(Auto, RenderingMode::Cpu, None, None, false, Os::Other).backend, Cpu); - } - - #[test] - fn safe_gpu_forces_the_cpu_for_one_launch() { - let p = plan(Vulkan, Some(&crashed("vulkan", "vulkan")), None, true, Os::Other); - assert_eq!((p.backend, p.remember), (Cpu, false)); - assert_eq!(backends(&p, Os::Windows), Some(wgpu::Backends::DX12)); - assert_eq!(backends(&p, Os::Other), Some(wgpu::Backends::GL | wgpu::Backends::VULKAN)); - assert_eq!(backends(&p, Os::Mac), Some(wgpu::Backends::METAL)); - } - - fn cand(vendor: u32, device_type: wgpu::DeviceType, backend: wgpu::Backend) -> Candidate { - Candidate { vendor, device_type, backend, surface_ok: true, wanted: false } - } - - #[test] - fn a_requested_adapter_beats_the_automatic_ranking() { - use wgpu::{Backend as B, DeviceType as T}; - // The order Vulkan lists this machine's GPUs in: iGPU, dGPU, eGPU. - let mut a = [cand(INTEL, T::IntegratedGpu, B::Vulkan), cand(INTEL, T::DiscreteGpu, B::Vulkan), cand(0x10de, T::DiscreteGpu, B::Vulkan)]; - assert_eq!(pick(&a, Auto, Os::Other), Some(1), "automatic takes the first discrete adapter, the Arc"); - a[2].wanted = true; - assert_eq!(pick(&a, Auto, Os::Other), Some(2)); - a[2].wanted = false; - a[0].wanted = true; - assert_eq!(pick(&a, Auto, Os::Other), Some(0), "even the iGPU, when asked for"); - // A wanted adapter that can't present is skipped, not an error. - a[0].surface_ok = false; - assert_eq!(pick(&a, Auto, Os::Other), Some(1)); - assert!(wanted_missed(&a, Some("iris"))); - assert!(!wanted_missed(&a, None)); - a[0].surface_ok = true; - assert!(!wanted_missed(&a, Some("iris"))); - // Among several wanted ones (same GPU on Vulkan and GL) the usual ranking decides. - let mut gl = [cand(0x10de, T::DiscreteGpu, B::Gl), cand(0x10de, T::DiscreteGpu, B::Vulkan)]; - gl.iter_mut().for_each(|c| c.wanted = true); - assert_eq!(pick(&gl, Auto, Os::Other), Some(1)); - } - - #[test] - fn an_adapter_request_applies_on_linux_outside_cpu_mode() { - let w = || Some("nvidia".to_string()); - assert_eq!(applicable_adapter(w(), Auto, true), w()); - assert_eq!(applicable_adapter(w(), Vulkan, true), w()); - assert_eq!(applicable_adapter(w(), Cpu, true), None); - assert_eq!(applicable_adapter(w(), Auto, false), None, "Windows and macOS keep their own selection"); - assert_eq!(applicable_adapter(None, Auto, true), None); - } - - #[test] - fn an_adapter_override_keeps_its_own_process_only_when_it_applies() { - let on = |env, mode, linux| adapter_override_is_process_specific(env, mode, linux); - assert!(on(Some("nvidia"), RenderingMode::Auto, true)); - assert!(on(Some("nvidia"), RenderingMode::Gpu, true)); - assert!(!on(Some("nvidia"), RenderingMode::Cpu, true), "ignored in CPU mode"); - assert!(!on(Some("nvidia"), RenderingMode::Auto, false), "ignored off Linux"); - assert!(!on(Some(" "), RenderingMode::Auto, true)); - assert!(!on(None, RenderingMode::Auto, true)); - } - - #[test] - fn adapter_names_match_loosely_and_the_environment_wins() { - assert!(adapter_matches("NVIDIA GeForce RTX 5060 Ti", "nvidia")); - assert!(adapter_matches("Intel(R) Arc(tm) A370M Graphics (DG2)", " ARC A370M ")); - assert!(!adapter_matches("Intel(R) Iris(R) Xe Graphics (ADL GT2)", "arc")); - assert!(!adapter_matches("anything", "")); - assert!(!adapter_matches("anything", " ")); - assert_eq!(wanted_adapter(None, ""), None); - assert_eq!(wanted_adapter(Some(" "), "iris"), Some("iris".into())); - assert_eq!(wanted_adapter(Some("nvidia"), "iris"), Some("nvidia".into())); - assert_eq!(wanted_adapter(Some(&"x".repeat(1000)), "").map(|w| w.len()), Some(256)); - } - - #[test] - fn gpu_adapter_is_read_before_the_window_opens() { - let dir = std::env::temp_dir().join(format!("photocraft-gpu-adapter-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let file = dir.join("preferences.json"); - let read = |json: &str| { - std::fs::write(&file, json).unwrap(); - read_gpu_adapter(Some(&file)) - }; - assert_eq!(read(r#"{"performance":{"gpuAdapter":"nvidia"}}"#), "nvidia"); - assert_eq!(read(r#"{"performance":{"gpuAdapter":7}}"#), ""); - assert_eq!(read(r#"{"performance":{}}"#), ""); - assert_eq!(read("not json"), ""); - assert_eq!(read_gpu_adapter(None), ""); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn intel_on_windows_defaults_to_dx12() { - use wgpu::{Backend as B, DeviceType as T}; - let intel = [cand(INTEL, T::IntegratedGpu, B::Vulkan), cand(INTEL, T::IntegratedGpu, B::Dx12), cand(INTEL, T::IntegratedGpu, B::Gl)]; - let i = pick(&intel, Auto, Os::Windows).unwrap(); - assert_eq!(intel[i].backend, B::Dx12); - assert_eq!(dx12_default_applied(&intel, i, Os::Windows, false), Some("Intel")); - // Elsewhere (and for other vendors) Vulkan stays first. - assert_eq!(intel[pick(&intel, Auto, Os::Other).unwrap()].backend, B::Vulkan); - let nv = [cand(0x10de, T::DiscreteGpu, B::Dx12), cand(0x10de, T::DiscreteGpu, B::Vulkan)]; - let i = pick(&nv, Auto, Os::Windows).unwrap(); - assert_eq!(nv[i].backend, B::Vulkan); - assert_eq!(dx12_default_applied(&nv, i, Os::Windows, false), None); - // Intel iGPU + discrete GPU: the discrete one wins (high performance), on Vulkan. - let hybrid = [intel[0], intel[1], nv[1]]; - assert_eq!(pick(&hybrid, Auto, Os::Windows), Some(2)); - // Adapters that can't present lose to ones that can. - let mut only = [cand(0x10de, T::DiscreteGpu, B::Vulkan), intel[1]]; - only[0].surface_ok = false; - assert_eq!(pick(&only, Auto, Os::Windows), Some(1)); - assert_eq!(pick(&[], Auto, Os::Windows), None); - } - - /// #7537: on Windows on ARM the Adreno Vulkan driver lost the device mid-session and took the - /// window with it; DX12 on the same machine didn't. DXGI and Vulkan report different vendor ids. - #[test] - fn qualcomm_on_windows_defaults_to_dx12() { - use wgpu::{Backend as B, DeviceType as T}; - let adreno = [cand(QUALCOMM, T::IntegratedGpu, B::Vulkan), cand(QUALCOMM_DXGI, T::IntegratedGpu, B::Dx12)]; - let i = pick(&adreno, Auto, Os::Windows).unwrap(); - assert_eq!(adreno[i].backend, B::Dx12); - assert_eq!(dx12_default_applied(&adreno, i, Os::Windows, false), Some("Qualcomm")); - // Only Vulkan offered: still Vulkan, and no note. - assert_eq!(pick(&adreno[..1], Auto, Os::Windows), Some(0)); - assert_eq!(dx12_default_applied(&adreno, 0, Os::Windows, false), None); - // An Intel Vulkan adapter doesn't make a Qualcomm DX12 pick "the default". - let mixed = [cand(INTEL, T::IntegratedGpu, B::Vulkan), adreno[1]]; - assert_eq!(dx12_default_applied(&mixed, 1, Os::Windows, false), None); - // Vulkan left out of the instance (an Intel adapter was listed) speaks only for Intel. - assert_eq!(dx12_default_applied(&adreno[1..], 0, Os::Windows, true), None); - // Elsewhere Vulkan stays first. - assert_eq!(adreno[pick(&adreno, Auto, Os::Other).unwrap()].backend, B::Vulkan); - } - - /// #4: an instance with Vulkan loads the Intel Vulkan driver, which crashed at startup, before - /// the selector picks Intel's DX12 adapter. With an Intel adapter in the DX12 list, `auto` on - /// Windows creates the instance without Vulkan. - #[test] - fn auto_on_windows_with_an_intel_adapter_leaves_vulkan_out_of_the_instance() { - use wgpu::{Backend as B, DeviceType as T}; - const NVIDIA: u32 = 0x10de; - const AMD: u32 = 0x1002; - const WARP: u32 = 0x1414; - let auto = plan(Auto, None, None, false, Os::Windows); - let dx12_gl = Some(wgpu::Backends::DX12 | wgpu::Backends::GL); - assert_eq!(windows_auto_backends(&auto, Os::Windows, || vec![INTEL, WARP]), dx12_gl); - // Intel iGPU + discrete GPU: the discrete GPU is then used on DX12. - assert_eq!(windows_auto_backends(&auto, Os::Windows, || vec![NVIDIA, INTEL, WARP]), dx12_gl); - // No Intel adapter: egui's default backends, Vulkan included. - assert_eq!(windows_auto_backends(&auto, Os::Windows, || vec![NVIDIA, WARP]), None); - assert_eq!(windows_auto_backends(&auto, Os::Windows, || vec![AMD]), None); - assert_eq!(windows_auto_backends(&auto, Os::Windows, Vec::new), None); - // `WGPU_BACKEND`, `--safe-gpu`, a chosen backend, a crash fallback and other platforms - // don't list the DX12 adapters at all. - let not_listed = || -> Vec { panic!("DX12 adapters listed") }; - for (p, os) in [ - (plan(Auto, None, Some("vulkan"), false, Os::Windows), Os::Windows), - (plan(Auto, None, None, true, Os::Windows), Os::Windows), - (plan(Vulkan, None, None, false, Os::Windows), Os::Windows), - (plan(Auto, Some(&crashed("auto", "vulkan")), None, false, Os::Windows), Os::Windows), - (plan(Auto, None, None, false, Os::Other), Os::Other), - (plan(Auto, None, None, false, Os::Mac), Os::Mac), - ] { - assert_eq!(windows_auto_backends(&p, os, not_listed), None, "{p:?}"); - } - // Without Vulkan adapters to compare with, System Info still names the Intel default. - let listed = [cand(INTEL, T::IntegratedGpu, B::Dx12), cand(WARP, T::Cpu, B::Dx12), cand(INTEL, T::IntegratedGpu, B::Gl)]; - let i = pick(&listed, Auto, Os::Windows).unwrap(); - assert_eq!(i, 0); - assert_eq!(dx12_default_applied(&listed, i, Os::Windows, true), Some("Intel")); - assert_eq!(dx12_default_applied(&listed, i, Os::Windows, false), None); - } - - #[test] - fn cpu_prefers_software_adapters() { - use wgpu::{Backend as B, DeviceType as T}; - let a = [cand(INTEL, T::IntegratedGpu, B::Dx12), cand(0x1414, T::Cpu, B::Dx12)]; - assert_eq!(pick(&a, Cpu, Os::Windows), Some(1)); - // No software adapter: still something. - assert_eq!(pick(&a[..1], Cpu, Os::Windows), Some(0)); - } - - /// #1337: on Linux with NVIDIA, the only GL adapter (NVIDIA's EGL) can't present, so CPU mode - /// found no adapter and never started. GL still wins whenever it can present. - #[test] - fn cpu_on_linux_falls_back_to_vulkan_only_when_gl_cannot_present() { - use wgpu::{Backend as B, DeviceType as T}; - const NVIDIA: u32 = 0x10de; - let llvmpipe = cand(0x10005, T::Cpu, B::Gl); - let nvidia_gl = cand(NVIDIA, T::DiscreteGpu, B::Gl); - let nvidia_vk = cand(NVIDIA, T::DiscreteGpu, B::Vulkan); - let lavapipe = cand(0x10005, T::Cpu, B::Vulkan); - // GL presents: same choice as GL-only, software first, then hardware GL over any Vulkan. - assert_eq!(pick(&[nvidia_vk, lavapipe, llvmpipe], Cpu, Os::Other), Some(2)); - assert_eq!(pick(&[nvidia_vk, lavapipe, nvidia_gl], Cpu, Os::Other), Some(2)); - // GL can't present: Vulkan for the window, software first. - let mut gl = nvidia_gl; - gl.surface_ok = false; - assert_eq!(pick(&[gl, nvidia_vk, lavapipe], Cpu, Os::Other), Some(2)); - assert_eq!(pick(&[gl, nvidia_vk], Cpu, Os::Other), Some(1)); - // Other backends rank as before. - assert_eq!(pick(&[nvidia_gl, nvidia_vk], Auto, Os::Other), Some(1)); - } - - /// #5191, #1788: a Windows VM offers VMware's SVGA3D over GL (`Other`) and WARP (`Cpu`, DX12). - /// GL drew a black window; WARP works. GL stays the last resort. - #[test] - fn windows_auto_prefers_warp_over_gl() { - use wgpu::{Backend as B, DeviceType as T}; - let svga_gl = cand(0x15ad, T::Other, B::Gl); - let warp = cand(0x1414, T::Cpu, B::Dx12); - assert_eq!(pick(&[svga_gl, warp], Auto, Os::Windows), Some(1)); - assert_eq!(pick(&[cand(INTEL, T::IntegratedGpu, B::Gl), warp], Auto, Os::Windows), Some(1)); - assert_eq!(pick(&[svga_gl], Auto, Os::Windows), Some(0)); - // Elsewhere GL keeps its rank. - assert_eq!(pick(&[svga_gl, warp], Auto, Os::Other), Some(0)); - } - - #[test] - fn adapters_must_present_even_when_none_support_the_surface() { - let mut a = cand(INTEL, wgpu::DeviceType::IntegratedGpu, wgpu::Backend::Dx12); - a.surface_ok = false; - assert_eq!(pick(&[a], Auto, Os::Windows), None); - assert_eq!(pick(&[a], Cpu, Os::Windows), None); - } - - #[test] - fn explicit_policy_overrides_legacy_cpu_backend() { - assert_eq!(plan_with_mode(Cpu, RenderingMode::Gpu, None, None, false, Os::Mac).backend, Auto); - assert_eq!(plan_with_mode(Metal, RenderingMode::Cpu, None, None, false, Os::Mac).backend, Cpu); - assert_eq!(plan_with_mode(Auto, RenderingMode::Gpu, None, None, true, Os::Mac).backend, Cpu); - } - - #[test] - fn marker_round_trip_and_lenient_parse() { - let m = Marker { - backend: "auto".into(), - adapter: "A \"quoted\" GPU".into(), - adapter_backend: "vulkan".into(), - driver: "1.2".into(), - version: "0.1".into(), - }; - assert_eq!(Marker::parse(&m.to_json()), m); - assert_eq!(Marker::parse(""), Marker::default()); - assert_eq!(Marker::parse("[1,2]").tried(), Some(Auto)); - assert_eq!(Marker::parse(r#"{"backend": 7}"#).tried(), Some(Auto)); - assert_eq!(Marker::parse(r#"{"backend": "env:dx12"}"#).tried(), None); - let long = format!(r#"{{"adapter": "{}"}}"#, "x".repeat(10_000)); - assert_eq!(Marker::parse(&long).adapter.len(), 256); - } - - #[test] - fn a_failed_start_keeps_its_marker_only_when_a_safer_backend_exists() { - // GPU backends move down the chain on the next start. - assert!(keep_marker_after_error(&plan(Auto, None, None, false, Os::Other), Os::Other)); - assert!(keep_marker_after_error(&plan(Gl, None, None, false, Os::Other), Os::Other)); - assert!(keep_marker_after_error(&plan(Dx12, None, None, false, Os::Windows), Os::Windows)); - assert!(keep_marker_after_error(&plan(Auto, None, None, false, Os::Mac), Os::Mac)); - // The CPU path is the end of every chain, including the `--safe-gpu` retry. - for os in [Os::Windows, Os::Mac, Os::Other] { - assert!(!keep_marker_after_error(&plan(Cpu, None, None, false, os), os)); - assert!(!keep_marker_after_error(&plan(Auto, None, None, true, os), os)); - } - // `WGPU_BACKEND` is the user's choice; no plan reads its marker. - assert!(!keep_marker_after_error(&plan(Auto, None, Some("vulkan"), false, Os::Other), Os::Other)); - } - - /// A failed CPU start (no usable GL adapter under XWayland) left a `cpu` marker, so every - /// later start was planned on CPU and failed the same way until the marker was deleted by hand. - #[test] - fn a_failed_cpu_start_does_not_pin_later_starts() { - let dir = temp_dir("cpu-error"); - let (_, s) = Sentinel::begin(&dir); - let mut s = s.expect("sentinel"); - let failed = plan(Auto, None, None, true, Os::Other); - s.write(Marker { backend: failed.backend.name().into(), ..Default::default() }).unwrap(); - // eframe returned an error: what `main` does with the marker. - if keep_marker_after_error(&failed, Os::Other) { - drop(s); - } else { - s.finish(); - } - let (prev, _s) = begin_when_unlocked(&dir); - assert_eq!(prev, Previous::Clean); - assert_eq!(plan(Auto, prev.crashed(), None, false, Os::Other).backend, Auto); - let _ = std::fs::remove_dir_all(&dir); - } - - fn temp_dir(name: &str) -> PathBuf { - let d = std::env::temp_dir().join(format!("photocraft-gpu-startup-{name}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&d); - d - } - - /// `Sentinel::begin`, called again up to 50 times, 10 ms apart, while it returns - /// `Previous::Busy`. Other tests in this binary spawn processes: between fork and exec a child - /// briefly shares the marker's flock, so `begin` can see the lock as busy just after a test - /// drops its sentinel. - fn begin_when_unlocked(dir: &Path) -> (Previous, Option) { - let (mut prev, mut s) = Sentinel::begin(dir); - for _ in 0..50 { - if prev != Previous::Busy { - break; - } - std::thread::sleep(std::time::Duration::from_millis(10)); - (prev, s) = Sentinel::begin(dir); - } - (prev, s) - } - - #[test] - fn sentinel_detects_a_crash_and_clears_on_success() { - let dir = temp_dir("cycle"); - // First launch: nothing left behind. - let (prev, s) = Sentinel::begin(&dir); - assert_eq!(prev, Previous::Clean); - let mut s = s.expect("sentinel"); - s.write(Marker { backend: "auto".into(), ..Default::default() }).unwrap(); - s.write(Marker { backend: "auto".into(), adapter: "GPU".into(), adapter_backend: "vulkan".into(), ..Default::default() }).unwrap(); - // While it is starting, a second instance sees it busy, not crashed. - let (busy, none) = Sentinel::begin(&dir); - assert_eq!(busy, Previous::Busy); - assert!(none.is_none()); - // The process dies in the driver: the lock goes, the marker stays. - drop(s); - let (prev, s) = begin_when_unlocked(&dir); - let m = prev.crashed().cloned().expect("crash detected"); - assert_eq!((m.adapter.as_str(), m.tried()), ("GPU", Some(Vulkan))); - // This start succeeds: the next one finds nothing. - let mut s = s.expect("sentinel"); - s.write(Marker { backend: "dx12".into(), ..Default::default() }).unwrap(); - s.finish(); - assert!(!dir.join(MARKER_FILE).exists()); - let (prev, _s) = Sentinel::begin(&dir); - assert_eq!(prev, Previous::Clean); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn begin_when_unlocked_waits_for_a_briefly_held_lock() { - let dir = temp_dir("shared-lock"); - let (_, s) = Sentinel::begin(&dir); - let mut s = s.expect("sentinel"); - s.write(Marker { backend: "vulkan".into(), ..Default::default() }).unwrap(); - // After the start dies, a second handle on the marker holds the lock for 50 ms, as a - // spawned child's copy of the descriptor does until the child calls exec. - let held = File::open(dir.join(MARKER_FILE)).unwrap(); - drop(s); - held.lock().unwrap(); - assert_eq!(Sentinel::begin(&dir).0, Previous::Busy); - let release = std::thread::spawn(move || { - std::thread::sleep(std::time::Duration::from_millis(50)); - held.unlock().unwrap(); - }); - let (prev, s) = begin_when_unlocked(&dir); - release.join().unwrap(); - assert_eq!(prev.crashed().map(|m| m.backend.as_str()), Some("vulkan")); - s.expect("sentinel").finish(); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn returned_non_graphics_errors_do_not_trigger_backend_recovery() { - let cases = [ - ("success", Ok(()), false), - ("app-error", Err(eframe::Error::AppCreation(Box::new(std::io::Error::other("app setup failed")))), false), - ("gpu-error", Err(eframe::Error::Wgpu(egui_wgpu::WgpuError::CustomNativeAdapterSelectionError("no adapter".into()))), true), - ]; - for (name, result, keep) in cases { - let dir = temp_dir(name); - let (_, s) = Sentinel::begin(&dir); - let mut s = s.expect("sentinel"); - s.write(Marker { backend: "vulkan".into(), ..Default::default() }).unwrap(); - if keep_marker_after_run(&result) { - drop(s); - } else { - s.finish(); - } - let (previous, s) = begin_when_unlocked(&dir); - assert_eq!(previous.crashed().is_some(), keep, "{name}: {result:?}"); - if !keep { - assert_eq!(plan(Vulkan, previous.crashed(), None, false, Os::Other).backend, Vulkan); - } - s.expect("sentinel").finish(); - let _ = std::fs::remove_dir_all(&dir); - } - } - - #[test] - fn unwritable_config_dir_is_not_fatal() { - let dir = temp_dir("file"); - std::fs::create_dir_all(dir.parent().unwrap()).unwrap(); - std::fs::write(&dir, b"not a directory").unwrap(); - let (prev, s) = Sentinel::begin(&dir.join("sub")); - assert_eq!(prev, Previous::Clean); - assert!(s.is_none()); - let _ = std::fs::remove_file(&dir); - } - - #[test] - fn prefs_are_read_leniently() { - let dir = temp_dir("prefs"); - std::fs::create_dir_all(&dir).unwrap(); - let p = dir.join("preferences.json"); - assert_eq!(read_rendering_prefs(None), (Auto, RenderingMode::Auto)); - assert_eq!(read_rendering_prefs(Some(&p)), (Auto, RenderingMode::Auto)); - std::fs::write(&p, r#"{"performance": {"gpuBackend": "dx12", "useGpu": false}, "interface": {}}"#).unwrap(); - assert_eq!(read_rendering_prefs(Some(&p)), (Dx12, RenderingMode::Cpu)); - std::fs::write(&p, r#"{"performance": {"gpuBackend": "quantum"}}"#).unwrap(); - assert_eq!(read_rendering_prefs(Some(&p)), (Auto, RenderingMode::Auto)); - std::fs::write(&p, r#"{"performance": {"useGpu": false, "renderingMode": "gpu"}}"#).unwrap(); - assert_eq!(read_rendering_prefs(Some(&p)), (Auto, RenderingMode::Gpu)); - std::fs::write(&p, "{not json").unwrap(); - assert_eq!(read_rendering_prefs(Some(&p)), (Auto, RenderingMode::Auto)); - let _ = std::fs::remove_dir_all(&dir); - } - - /// #712: never a `dxcompiler.dll` found through the DLL search path (current directory, PATH). - #[test] - fn dx12_compiler_is_fxc_or_dxc_beside_the_exe() { - use wgpu::Dx12Compiler as C; - let dir = temp_dir("dxc"); - std::fs::create_dir_all(&dir).unwrap(); - assert!(matches!(dx12_compiler(None, None), C::Fxc)); - assert!(matches!(dx12_compiler(None, Some(&dir)), C::Fxc)); - std::fs::write(dir.join("dxcompiler.dll"), b"MZ").unwrap(); - let expected = dir.join("dxcompiler.dll"); - assert!(matches!(dx12_compiler(None, Some(&dir)), C::DynamicDxc { dxc_path } if Path::new(&dxc_path) == expected)); - // An explicit WGPU_DX12_COMPILER wins; an unknown value is ignored. - assert!(matches!(dx12_compiler(Some(" FXC "), Some(&dir)), C::Fxc)); - assert!(matches!(dx12_compiler(Some("dxc"), None), C::DynamicDxc { dxc_path } if dxc_path == "dxcompiler.dll")); - assert!(matches!(dx12_compiler(Some("quantum"), None), C::Fxc)); - let _ = std::fs::remove_dir_all(&dir); - - // The app's setup replaces wgpu's default (`Auto`: DXC by name from the search path). - let mut setup = egui_wgpu::WgpuSetup::without_display_handle(); - let plan = plan(Auto, None, None, false, Os::Windows); - configure(&mut setup, &plan, Os::Windows, None, Arc::new(Mutex::new(None)), Arc::default()); - let egui_wgpu::WgpuSetup::CreateNew(create) = &setup else { panic!("a new instance") }; - if std::env::var_os("WGPU_DX12_COMPILER").is_none() { - let safe = match &create.instance_descriptor.backend_options.dx12.shader_compiler { - C::Fxc => true, - C::DynamicDxc { dxc_path } => Path::new(dxc_path).is_absolute(), - C::StaticDxc | C::Auto => false, - }; - assert!(safe, "{:?}", create.instance_descriptor.backend_options.dx12.shader_compiler); - } - } - - #[test] - fn intel_macs_skip_the_indirect_validation_shaders() { - // Metal's compiler crashed on them on Intel Iris Pro, losing the device in every mode (#3107). - assert!(skips_indirect_validation(Os::Mac, true)); - // Apple silicon, Windows and Linux keep wgpu's validation. - for (os, intel) in [(Os::Mac, false), (Os::Windows, true), (Os::Other, true), (Os::Other, false)] { - assert!(!skips_indirect_validation(os, intel), "{os:?} intel={intel}"); - } - for (os, safe_gpu) in [(Os::Windows, false), (Os::Other, true), (Os::Other, false)] { - let mut setup = egui_wgpu::WgpuSetup::without_display_handle(); - let egui_wgpu::WgpuSetup::CreateNew(before) = &setup else { panic!("a new instance") }; - let before = before.instance_descriptor.flags; - configure(&mut setup, &plan(Auto, None, None, safe_gpu, os), os, None, Arc::new(Mutex::new(None)), Arc::default()); - let egui_wgpu::WgpuSetup::CreateNew(create) = &setup else { panic!("a new instance") }; - assert_eq!(create.instance_descriptor.flags, before, "{os:?}: flags untouched"); - } - if cfg!(target_arch = "x86_64") && std::env::var_os("WGPU_VALIDATION_INDIRECT_CALL").is_none() { - let mut setup = egui_wgpu::WgpuSetup::without_display_handle(); - configure(&mut setup, &plan(Auto, None, None, false, Os::Mac), Os::Mac, None, Arc::new(Mutex::new(None)), Arc::default()); - let egui_wgpu::WgpuSetup::CreateNew(create) = &setup else { panic!("a new instance") }; - assert!(!create.instance_descriptor.flags.contains(wgpu::InstanceFlags::VALIDATION_INDIRECT_CALL)); - } - } -} +mod tests; diff --git a/apps/photocraft/src/gpu_startup/tests.rs b/apps/photocraft/src/gpu_startup/tests.rs new file mode 100644 index 0000000000..ee1f0ce1e6 --- /dev/null +++ b/apps/photocraft/src/gpu_startup/tests.rs @@ -0,0 +1,595 @@ +use super::*; +use GpuBackend::*; + +fn crashed(backend: &str, adapter_backend: &str) -> Marker { + Marker { backend: backend.into(), adapter: "Intel(R) UHD Graphics".into(), adapter_backend: adapter_backend.into(), ..Default::default() } +} + +#[test] +fn low_latency_drawing_is_read_before_the_window_opens_and_defaults_off() { + let dir = std::env::temp_dir().join(format!("photocraft-low-latency-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("preferences.json"); + let read = |json: &str| { + std::fs::write(&file, json).unwrap(); + read_low_latency(Some(&file)) + }; + assert!(read(r#"{"performance":{"lowLatencyDrawing":true}}"#)); + assert!(!read(r#"{"performance":{"lowLatencyDrawing":false}}"#)); + assert!(!read(r#"{"performance":{"lowLatencyDrawing":"nope"}}"#), "garbage keeps the default (off)"); + assert!(!read("not json")); + assert!(!read_low_latency(None), "no settings file: the default (off)"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn display_server_preference_is_read_before_the_window_opens() { + use photocraft_engine::prefs::LinuxDisplayServer; + let dir = std::env::temp_dir().join(format!("photocraft-display-server-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("preferences.json"); + let read = |json: &str| { + std::fs::write(&file, json).unwrap(); + read_display_server(Some(&file)) + }; + assert_eq!(read(r#"{"performance":{"linuxDisplayServer":"x11"}}"#), LinuxDisplayServer::X11); + assert_eq!(read(r#"{"performance":{"linuxDisplayServer":"auto","gpuBackend":"vulkan"}}"#), LinuxDisplayServer::Auto); + // Unknown values, other types, broken JSON and a missing file all start as Auto. + assert_eq!(read(r#"{"performance":{"linuxDisplayServer":"wayland"}}"#), LinuxDisplayServer::Auto); + assert_eq!(read(r#"{"performance":{"linuxDisplayServer":11}}"#), LinuxDisplayServer::Auto); + assert_eq!(read("{not json"), LinuxDisplayServer::Auto); + assert_eq!(read_display_server(Some(&dir.join("missing.json"))), LinuxDisplayServer::Auto); + assert_eq!(read_display_server(None), LinuxDisplayServer::Auto); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn cpu_policy_ignores_hardware_backend_override() { + let p = plan_with_mode(Vulkan, RenderingMode::Cpu, None, Some("vulkan"), false, Os::Windows); + assert_eq!(p.backend, Cpu); + assert!(p.env.is_none()); + assert_eq!(plan_with_mode(Vulkan, RenderingMode::Cpu, Some(&crashed("vulkan", "vulkan")), None, false, Os::Windows).backend, Cpu); + let p = plan_with_mode(Auto, RenderingMode::Gpu, None, Some("vulkan"), true, Os::Windows); + assert_eq!(p.backend, Cpu); + assert!(p.env.is_none()); +} + +#[test] +fn no_marker_uses_the_preference() { + for os in [Os::Windows, Os::Mac, Os::Other] { + let p = plan(Auto, None, None, false, os); + assert_eq!(p, Plan { backend: Auto, env: None, reason: None, remember: false }); + } + assert_eq!(plan(Dx12, None, None, false, Os::Windows).backend, Dx12); + assert_eq!(plan(Gl, None, None, false, Os::Other).backend, Gl); + // A backend the platform lacks is `auto`. + assert_eq!(plan(Metal, None, None, false, Os::Windows).backend, Auto); + assert_eq!(plan(Dx12, None, None, false, Os::Mac).backend, Auto); + assert_eq!(plan(Dx12, None, None, false, Os::Other).backend, Auto); +} + +#[test] +fn a_crash_moves_down_each_chain_and_is_remembered() { + // Windows: Vulkan → DX12 → CPU. + let p = plan(Auto, Some(&crashed("auto", "vulkan")), None, false, Os::Windows); + assert_eq!((p.backend, p.remember), (Dx12, true)); + assert!(p.reason.as_deref().unwrap_or("").contains("vulkan (Intel(R) UHD Graphics)"), "{p:?}"); + assert_eq!(plan(Dx12, Some(&crashed("dx12", "dx12")), None, false, Os::Windows).backend, Cpu); + // Crashed before the adapter was chosen (enumeration): from `auto`. + assert_eq!(plan(Auto, Some(&crashed("auto", "")), None, false, Os::Windows).backend, Dx12); + // `auto` that had already picked DX12 (the Intel default) goes to the CPU. + assert_eq!(plan(Auto, Some(&crashed("auto", "dx12")), None, false, Os::Windows).backend, Cpu); + // Linux: Vulkan → GL → CPU. + assert_eq!(plan(Auto, Some(&crashed("auto", "vulkan")), None, false, Os::Other).backend, Gl); + assert_eq!(plan(Gl, Some(&crashed("gl", "gl")), None, false, Os::Other).backend, Cpu); + // macOS: Metal → CPU. + assert_eq!(plan(Auto, Some(&crashed("auto", "metal")), None, false, Os::Mac).backend, Cpu); + // The CPU path stays there, and isn't "remembered" again. + let p = plan(Cpu, Some(&crashed("cpu", "dx12")), None, false, Os::Windows); + assert_eq!((p.backend, p.remember), (Cpu, false)); + // An unreadable marker still counts as a crash. + assert_eq!(plan(Auto, Some(&Marker::parse("{garbage")), None, false, Os::Windows).backend, Dx12); +} + +#[test] +fn env_override_beats_everything() { + let p = plan(Cpu, Some(&crashed("auto", "vulkan")), Some("vulkan"), false, Os::Windows); + assert_eq!(p.env.as_deref(), Some("vulkan")); + assert_eq!(p.backend, Auto); + assert!(!p.remember); + assert_eq!(backends(&p, Os::Windows), None, "egui reads WGPU_BACKEND itself"); + // A crash under the override doesn't count against `auto` later. + let p = plan(Auto, Some(&Marker { backend: "env:vulkan".into(), ..Default::default() }), None, false, Os::Windows); + assert_eq!(p.backend, Auto); + // Empty means unset. + assert_eq!(plan(Auto, None, Some(" "), false, Os::Windows).env, None); + // --safe-gpu with the override: CPU canvas, the override's backends. + assert_eq!(plan(Auto, None, Some("dx12"), true, Os::Windows).backend, Cpu); +} + +/// #3483: A temporary CPU recovery must not change the next launch. +#[test] +fn cpu_recovery_requires_explicit_confirmation_to_persist() { + let gl_crash = crashed("gl", "gl"); + let cpu = plan_with_mode(Auto, RenderingMode::Auto, Some(&gl_crash), None, false, Os::Other); + assert_eq!((cpu.backend, cpu.remember), (Cpu, true)); + assert_eq!(backend_to_remember(&cpu), None); + + let safe = plan_with_mode(Auto, RenderingMode::Auto, None, None, true, Os::Other); + assert_eq!(safe.backend, Cpu); + assert_eq!(backend_to_remember(&safe), None); + // An unconfirmed fallback leaves the original automatic selection intact. + assert_eq!(plan_with_mode(Auto, RenderingMode::Auto, None, None, false, Os::Other).backend, Auto); + // A working hardware fallback can still be remembered. + let vk_crash = crashed("auto", "vulkan"); + let gl = plan_with_mode(Auto, RenderingMode::Auto, Some(&vk_crash), None, false, Os::Other); + assert_eq!(backend_to_remember(&gl), Some(Gl)); + // CPU explicitly selected in preferences still works. + assert_eq!(plan_with_mode(Auto, RenderingMode::Cpu, None, None, false, Os::Other).backend, Cpu); +} + +#[test] +fn safe_gpu_forces_the_cpu_for_one_launch() { + let p = plan(Vulkan, Some(&crashed("vulkan", "vulkan")), None, true, Os::Other); + assert_eq!((p.backend, p.remember), (Cpu, false)); + assert_eq!(backends(&p, Os::Windows), Some(wgpu::Backends::DX12)); + assert_eq!(backends(&p, Os::Other), Some(wgpu::Backends::GL | wgpu::Backends::VULKAN)); + assert_eq!(backends(&p, Os::Mac), Some(wgpu::Backends::METAL)); +} + +fn cand(vendor: u32, device_type: wgpu::DeviceType, backend: wgpu::Backend) -> Candidate { + Candidate { vendor, device_type, backend, surface_ok: true, wanted: false } +} + +#[test] +fn a_requested_adapter_beats_the_automatic_ranking() { + use wgpu::{Backend as B, DeviceType as T}; + // The order Vulkan lists this machine's GPUs in: iGPU, dGPU, eGPU. + let mut a = [cand(INTEL, T::IntegratedGpu, B::Vulkan), cand(INTEL, T::DiscreteGpu, B::Vulkan), cand(0x10de, T::DiscreteGpu, B::Vulkan)]; + assert_eq!(pick(&a, Auto, Os::Other), Some(1), "automatic takes the first discrete adapter, the Arc"); + a[2].wanted = true; + assert_eq!(pick(&a, Auto, Os::Other), Some(2)); + a[2].wanted = false; + a[0].wanted = true; + assert_eq!(pick(&a, Auto, Os::Other), Some(0), "even the iGPU, when asked for"); + // A wanted adapter that can't present is skipped, not an error. + a[0].surface_ok = false; + assert_eq!(pick(&a, Auto, Os::Other), Some(1)); + assert!(wanted_missed(&a, Some("iris"))); + assert!(!wanted_missed(&a, None)); + a[0].surface_ok = true; + assert!(!wanted_missed(&a, Some("iris"))); + // Among several wanted ones (same GPU on Vulkan and GL) the usual ranking decides. + let mut gl = [cand(0x10de, T::DiscreteGpu, B::Gl), cand(0x10de, T::DiscreteGpu, B::Vulkan)]; + gl.iter_mut().for_each(|c| c.wanted = true); + assert_eq!(pick(&gl, Auto, Os::Other), Some(1)); +} + +#[test] +fn an_adapter_request_applies_on_linux_outside_cpu_mode() { + let w = || Some("nvidia".to_string()); + assert_eq!(applicable_adapter(w(), Auto, true), w()); + assert_eq!(applicable_adapter(w(), Vulkan, true), w()); + assert_eq!(applicable_adapter(w(), Cpu, true), None); + assert_eq!(applicable_adapter(w(), Auto, false), None, "Windows and macOS keep their own selection"); + assert_eq!(applicable_adapter(None, Auto, true), None); +} + +#[test] +fn an_adapter_override_keeps_its_own_process_only_when_it_applies() { + let on = |env, mode, linux| adapter_override_is_process_specific(env, mode, linux); + assert!(on(Some("nvidia"), RenderingMode::Auto, true)); + assert!(on(Some("nvidia"), RenderingMode::Gpu, true)); + assert!(!on(Some("nvidia"), RenderingMode::Cpu, true), "ignored in CPU mode"); + assert!(!on(Some("nvidia"), RenderingMode::Auto, false), "ignored off Linux"); + assert!(!on(Some(" "), RenderingMode::Auto, true)); + assert!(!on(None, RenderingMode::Auto, true)); +} + +#[test] +fn adapter_names_match_loosely_and_the_environment_wins() { + assert!(adapter_matches("NVIDIA GeForce RTX 5060 Ti", "nvidia")); + assert!(adapter_matches("Intel(R) Arc(tm) A370M Graphics (DG2)", " ARC A370M ")); + assert!(!adapter_matches("Intel(R) Iris(R) Xe Graphics (ADL GT2)", "arc")); + assert!(!adapter_matches("anything", "")); + assert!(!adapter_matches("anything", " ")); + assert_eq!(wanted_adapter(None, ""), None); + assert_eq!(wanted_adapter(Some(" "), "iris"), Some("iris".into())); + assert_eq!(wanted_adapter(Some("nvidia"), "iris"), Some("nvidia".into())); + assert_eq!(wanted_adapter(Some(&"x".repeat(1000)), "").map(|w| w.len()), Some(256)); +} + +#[test] +fn gpu_adapter_is_read_before_the_window_opens() { + let dir = std::env::temp_dir().join(format!("photocraft-gpu-adapter-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("preferences.json"); + let read = |json: &str| { + std::fs::write(&file, json).unwrap(); + read_gpu_adapter(Some(&file)) + }; + assert_eq!(read(r#"{"performance":{"gpuAdapter":"nvidia"}}"#), "nvidia"); + assert_eq!(read(r#"{"performance":{"gpuAdapter":7}}"#), ""); + assert_eq!(read(r#"{"performance":{}}"#), ""); + assert_eq!(read("not json"), ""); + assert_eq!(read_gpu_adapter(None), ""); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn intel_on_windows_defaults_to_dx12() { + use wgpu::{Backend as B, DeviceType as T}; + let intel = [cand(INTEL, T::IntegratedGpu, B::Vulkan), cand(INTEL, T::IntegratedGpu, B::Dx12), cand(INTEL, T::IntegratedGpu, B::Gl)]; + let i = pick(&intel, Auto, Os::Windows).unwrap(); + assert_eq!(intel[i].backend, B::Dx12); + assert_eq!(dx12_default_applied(&intel, i, Os::Windows, false), Some("Intel")); + // Elsewhere (and for other vendors) Vulkan stays first. + assert_eq!(intel[pick(&intel, Auto, Os::Other).unwrap()].backend, B::Vulkan); + let nv = [cand(0x10de, T::DiscreteGpu, B::Dx12), cand(0x10de, T::DiscreteGpu, B::Vulkan)]; + let i = pick(&nv, Auto, Os::Windows).unwrap(); + assert_eq!(nv[i].backend, B::Vulkan); + assert_eq!(dx12_default_applied(&nv, i, Os::Windows, false), None); + // Intel iGPU + discrete GPU: the discrete one wins (high performance), on Vulkan. + let hybrid = [intel[0], intel[1], nv[1]]; + assert_eq!(pick(&hybrid, Auto, Os::Windows), Some(2)); + // Adapters that can't present lose to ones that can. + let mut only = [cand(0x10de, T::DiscreteGpu, B::Vulkan), intel[1]]; + only[0].surface_ok = false; + assert_eq!(pick(&only, Auto, Os::Windows), Some(1)); + assert_eq!(pick(&[], Auto, Os::Windows), None); +} + +/// #7537: on Windows on ARM the Adreno Vulkan driver lost the device mid-session and took the +/// window with it; DX12 on the same machine didn't. DXGI and Vulkan report different vendor ids. +#[test] +fn qualcomm_on_windows_defaults_to_dx12() { + use wgpu::{Backend as B, DeviceType as T}; + let adreno = [cand(QUALCOMM, T::IntegratedGpu, B::Vulkan), cand(QUALCOMM_DXGI, T::IntegratedGpu, B::Dx12)]; + let i = pick(&adreno, Auto, Os::Windows).unwrap(); + assert_eq!(adreno[i].backend, B::Dx12); + assert_eq!(dx12_default_applied(&adreno, i, Os::Windows, false), Some("Qualcomm")); + // Only Vulkan offered: still Vulkan, and no note. + assert_eq!(pick(&adreno[..1], Auto, Os::Windows), Some(0)); + assert_eq!(dx12_default_applied(&adreno, 0, Os::Windows, false), None); + // An Intel Vulkan adapter doesn't make a Qualcomm DX12 pick "the default". + let mixed = [cand(INTEL, T::IntegratedGpu, B::Vulkan), adreno[1]]; + assert_eq!(dx12_default_applied(&mixed, 1, Os::Windows, false), None); + // Vulkan left out of the instance (an Intel adapter was listed) speaks only for Intel. + assert_eq!(dx12_default_applied(&adreno[1..], 0, Os::Windows, true), None); + // Elsewhere Vulkan stays first. + assert_eq!(adreno[pick(&adreno, Auto, Os::Other).unwrap()].backend, B::Vulkan); +} + +/// #4: an instance with Vulkan loads the Intel Vulkan driver, which crashed at startup, before +/// the selector picks Intel's DX12 adapter. With an Intel adapter in the DX12 list, `auto` on +/// Windows creates the instance without Vulkan. +#[test] +fn auto_on_windows_with_an_intel_adapter_leaves_vulkan_out_of_the_instance() { + use wgpu::{Backend as B, DeviceType as T}; + const NVIDIA: u32 = 0x10de; + const AMD: u32 = 0x1002; + const WARP: u32 = 0x1414; + let auto = plan(Auto, None, None, false, Os::Windows); + let dx12_gl = Some(wgpu::Backends::DX12 | wgpu::Backends::GL); + assert_eq!(windows_auto_backends(&auto, Os::Windows, || vec![INTEL, WARP]), dx12_gl); + // Intel iGPU + discrete GPU: the discrete GPU is then used on DX12. + assert_eq!(windows_auto_backends(&auto, Os::Windows, || vec![NVIDIA, INTEL, WARP]), dx12_gl); + // No Intel adapter: egui's default backends, Vulkan included. + assert_eq!(windows_auto_backends(&auto, Os::Windows, || vec![NVIDIA, WARP]), None); + assert_eq!(windows_auto_backends(&auto, Os::Windows, || vec![AMD]), None); + assert_eq!(windows_auto_backends(&auto, Os::Windows, Vec::new), None); + // `WGPU_BACKEND`, `--safe-gpu`, a chosen backend, a crash fallback and other platforms + // don't list the DX12 adapters at all. + let not_listed = || -> Vec { panic!("DX12 adapters listed") }; + for (p, os) in [ + (plan(Auto, None, Some("vulkan"), false, Os::Windows), Os::Windows), + (plan(Auto, None, None, true, Os::Windows), Os::Windows), + (plan(Vulkan, None, None, false, Os::Windows), Os::Windows), + (plan(Auto, Some(&crashed("auto", "vulkan")), None, false, Os::Windows), Os::Windows), + (plan(Auto, None, None, false, Os::Other), Os::Other), + (plan(Auto, None, None, false, Os::Mac), Os::Mac), + ] { + assert_eq!(windows_auto_backends(&p, os, not_listed), None, "{p:?}"); + } + // Without Vulkan adapters to compare with, System Info still names the Intel default. + let listed = [cand(INTEL, T::IntegratedGpu, B::Dx12), cand(WARP, T::Cpu, B::Dx12), cand(INTEL, T::IntegratedGpu, B::Gl)]; + let i = pick(&listed, Auto, Os::Windows).unwrap(); + assert_eq!(i, 0); + assert_eq!(dx12_default_applied(&listed, i, Os::Windows, true), Some("Intel")); + assert_eq!(dx12_default_applied(&listed, i, Os::Windows, false), None); +} + +#[test] +fn cpu_prefers_software_adapters() { + use wgpu::{Backend as B, DeviceType as T}; + let a = [cand(INTEL, T::IntegratedGpu, B::Dx12), cand(0x1414, T::Cpu, B::Dx12)]; + assert_eq!(pick(&a, Cpu, Os::Windows), Some(1)); + // No software adapter: still something. + assert_eq!(pick(&a[..1], Cpu, Os::Windows), Some(0)); +} + +/// #1337: on Linux with NVIDIA, the only GL adapter (NVIDIA's EGL) can't present, so CPU mode +/// found no adapter and never started. GL still wins whenever it can present. +#[test] +fn cpu_on_linux_falls_back_to_vulkan_only_when_gl_cannot_present() { + use wgpu::{Backend as B, DeviceType as T}; + const NVIDIA: u32 = 0x10de; + let llvmpipe = cand(0x10005, T::Cpu, B::Gl); + let nvidia_gl = cand(NVIDIA, T::DiscreteGpu, B::Gl); + let nvidia_vk = cand(NVIDIA, T::DiscreteGpu, B::Vulkan); + let lavapipe = cand(0x10005, T::Cpu, B::Vulkan); + // GL presents: same choice as GL-only, software first, then hardware GL over any Vulkan. + assert_eq!(pick(&[nvidia_vk, lavapipe, llvmpipe], Cpu, Os::Other), Some(2)); + assert_eq!(pick(&[nvidia_vk, lavapipe, nvidia_gl], Cpu, Os::Other), Some(2)); + // GL can't present: Vulkan for the window, software first. + let mut gl = nvidia_gl; + gl.surface_ok = false; + assert_eq!(pick(&[gl, nvidia_vk, lavapipe], Cpu, Os::Other), Some(2)); + assert_eq!(pick(&[gl, nvidia_vk], Cpu, Os::Other), Some(1)); + // Other backends rank as before. + assert_eq!(pick(&[nvidia_gl, nvidia_vk], Auto, Os::Other), Some(1)); +} + +/// #5191, #1788: a Windows VM offers VMware's SVGA3D over GL (`Other`) and WARP (`Cpu`, DX12). +/// GL drew a black window; WARP works. GL stays the last resort. +#[test] +fn windows_auto_prefers_warp_over_gl() { + use wgpu::{Backend as B, DeviceType as T}; + let svga_gl = cand(0x15ad, T::Other, B::Gl); + let warp = cand(0x1414, T::Cpu, B::Dx12); + assert_eq!(pick(&[svga_gl, warp], Auto, Os::Windows), Some(1)); + assert_eq!(pick(&[cand(INTEL, T::IntegratedGpu, B::Gl), warp], Auto, Os::Windows), Some(1)); + assert_eq!(pick(&[svga_gl], Auto, Os::Windows), Some(0)); + // Elsewhere GL keeps its rank. + assert_eq!(pick(&[svga_gl, warp], Auto, Os::Other), Some(0)); +} + +#[test] +fn adapters_must_present_even_when_none_support_the_surface() { + let mut a = cand(INTEL, wgpu::DeviceType::IntegratedGpu, wgpu::Backend::Dx12); + a.surface_ok = false; + assert_eq!(pick(&[a], Auto, Os::Windows), None); + assert_eq!(pick(&[a], Cpu, Os::Windows), None); +} + +#[test] +fn explicit_policy_overrides_legacy_cpu_backend() { + assert_eq!(plan_with_mode(Cpu, RenderingMode::Gpu, None, None, false, Os::Mac).backend, Auto); + assert_eq!(plan_with_mode(Metal, RenderingMode::Cpu, None, None, false, Os::Mac).backend, Cpu); + assert_eq!(plan_with_mode(Auto, RenderingMode::Gpu, None, None, true, Os::Mac).backend, Cpu); +} + +#[test] +fn marker_round_trip_and_lenient_parse() { + let m = + Marker { backend: "auto".into(), adapter: "A \"quoted\" GPU".into(), adapter_backend: "vulkan".into(), driver: "1.2".into(), version: "0.1".into() }; + assert_eq!(Marker::parse(&m.to_json()), m); + assert_eq!(Marker::parse(""), Marker::default()); + assert_eq!(Marker::parse("[1,2]").tried(), Some(Auto)); + assert_eq!(Marker::parse(r#"{"backend": 7}"#).tried(), Some(Auto)); + assert_eq!(Marker::parse(r#"{"backend": "env:dx12"}"#).tried(), None); + let long = format!(r#"{{"adapter": "{}"}}"#, "x".repeat(10_000)); + assert_eq!(Marker::parse(&long).adapter.len(), 256); +} + +#[test] +fn a_failed_start_keeps_its_marker_only_when_a_safer_backend_exists() { + // GPU backends move down the chain on the next start. + assert!(keep_marker_after_error(&plan(Auto, None, None, false, Os::Other), Os::Other)); + assert!(keep_marker_after_error(&plan(Gl, None, None, false, Os::Other), Os::Other)); + assert!(keep_marker_after_error(&plan(Dx12, None, None, false, Os::Windows), Os::Windows)); + assert!(keep_marker_after_error(&plan(Auto, None, None, false, Os::Mac), Os::Mac)); + // The CPU path is the end of every chain, including the `--safe-gpu` retry. + for os in [Os::Windows, Os::Mac, Os::Other] { + assert!(!keep_marker_after_error(&plan(Cpu, None, None, false, os), os)); + assert!(!keep_marker_after_error(&plan(Auto, None, None, true, os), os)); + } + // `WGPU_BACKEND` is the user's choice; no plan reads its marker. + assert!(!keep_marker_after_error(&plan(Auto, None, Some("vulkan"), false, Os::Other), Os::Other)); +} + +/// A failed CPU start (no usable GL adapter under XWayland) left a `cpu` marker, so every +/// later start was planned on CPU and failed the same way until the marker was deleted by hand. +#[test] +fn a_failed_cpu_start_does_not_pin_later_starts() { + let dir = temp_dir("cpu-error"); + let (_, s) = Sentinel::begin(&dir); + let mut s = s.expect("sentinel"); + let failed = plan(Auto, None, None, true, Os::Other); + s.write(Marker { backend: failed.backend.name().into(), ..Default::default() }).unwrap(); + // eframe returned an error: what `main` does with the marker. + if keep_marker_after_error(&failed, Os::Other) { + drop(s); + } else { + s.finish(); + } + let (prev, _s) = begin_when_unlocked(&dir); + assert_eq!(prev, Previous::Clean); + assert_eq!(plan(Auto, prev.crashed(), None, false, Os::Other).backend, Auto); + let _ = std::fs::remove_dir_all(&dir); +} + +fn temp_dir(name: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("photocraft-gpu-startup-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + d +} + +/// `Sentinel::begin`, called again up to 50 times, 10 ms apart, while it returns +/// `Previous::Busy`. Other tests in this binary spawn processes: between fork and exec a child +/// briefly shares the marker's flock, so `begin` can see the lock as busy just after a test +/// drops its sentinel. +fn begin_when_unlocked(dir: &Path) -> (Previous, Option) { + let (mut prev, mut s) = Sentinel::begin(dir); + for _ in 0..50 { + if prev != Previous::Busy { + break; + } + std::thread::sleep(std::time::Duration::from_millis(10)); + (prev, s) = Sentinel::begin(dir); + } + (prev, s) +} + +#[test] +fn sentinel_detects_a_crash_and_clears_on_success() { + let dir = temp_dir("cycle"); + // First launch: nothing left behind. + let (prev, s) = Sentinel::begin(&dir); + assert_eq!(prev, Previous::Clean); + let mut s = s.expect("sentinel"); + s.write(Marker { backend: "auto".into(), ..Default::default() }).unwrap(); + s.write(Marker { backend: "auto".into(), adapter: "GPU".into(), adapter_backend: "vulkan".into(), ..Default::default() }).unwrap(); + // While it is starting, a second instance sees it busy, not crashed. + let (busy, none) = Sentinel::begin(&dir); + assert_eq!(busy, Previous::Busy); + assert!(none.is_none()); + // The process dies in the driver: the lock goes, the marker stays. + drop(s); + let (prev, s) = begin_when_unlocked(&dir); + let m = prev.crashed().cloned().expect("crash detected"); + assert_eq!((m.adapter.as_str(), m.tried()), ("GPU", Some(Vulkan))); + // This start succeeds: the next one finds nothing. + let mut s = s.expect("sentinel"); + s.write(Marker { backend: "dx12".into(), ..Default::default() }).unwrap(); + s.finish(); + assert!(!dir.join(MARKER_FILE).exists()); + let (prev, _s) = Sentinel::begin(&dir); + assert_eq!(prev, Previous::Clean); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn begin_when_unlocked_waits_for_a_briefly_held_lock() { + let dir = temp_dir("shared-lock"); + let (_, s) = Sentinel::begin(&dir); + let mut s = s.expect("sentinel"); + s.write(Marker { backend: "vulkan".into(), ..Default::default() }).unwrap(); + // After the start dies, a second handle on the marker holds the lock for 50 ms, as a + // spawned child's copy of the descriptor does until the child calls exec. + let held = File::open(dir.join(MARKER_FILE)).unwrap(); + drop(s); + held.lock().unwrap(); + assert_eq!(Sentinel::begin(&dir).0, Previous::Busy); + let release = std::thread::spawn(move || { + std::thread::sleep(std::time::Duration::from_millis(50)); + held.unlock().unwrap(); + }); + let (prev, s) = begin_when_unlocked(&dir); + release.join().unwrap(); + assert_eq!(prev.crashed().map(|m| m.backend.as_str()), Some("vulkan")); + s.expect("sentinel").finish(); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn returned_non_graphics_errors_do_not_trigger_backend_recovery() { + let cases = [ + ("success", Ok(()), false), + ("app-error", Err(eframe::Error::AppCreation(Box::new(std::io::Error::other("app setup failed")))), false), + ("gpu-error", Err(eframe::Error::Wgpu(egui_wgpu::WgpuError::CustomNativeAdapterSelectionError("no adapter".into()))), true), + ]; + for (name, result, keep) in cases { + let dir = temp_dir(name); + let (_, s) = Sentinel::begin(&dir); + let mut s = s.expect("sentinel"); + s.write(Marker { backend: "vulkan".into(), ..Default::default() }).unwrap(); + if keep_marker_after_run(&result) { + drop(s); + } else { + s.finish(); + } + let (previous, s) = begin_when_unlocked(&dir); + assert_eq!(previous.crashed().is_some(), keep, "{name}: {result:?}"); + if !keep { + assert_eq!(plan(Vulkan, previous.crashed(), None, false, Os::Other).backend, Vulkan); + } + s.expect("sentinel").finish(); + let _ = std::fs::remove_dir_all(&dir); + } +} + +#[test] +fn unwritable_config_dir_is_not_fatal() { + let dir = temp_dir("file"); + std::fs::create_dir_all(dir.parent().unwrap()).unwrap(); + std::fs::write(&dir, b"not a directory").unwrap(); + let (prev, s) = Sentinel::begin(&dir.join("sub")); + assert_eq!(prev, Previous::Clean); + assert!(s.is_none()); + let _ = std::fs::remove_file(&dir); +} + +#[test] +fn prefs_are_read_leniently() { + let dir = temp_dir("prefs"); + std::fs::create_dir_all(&dir).unwrap(); + let p = dir.join("preferences.json"); + assert_eq!(read_rendering_prefs(None), (Auto, RenderingMode::Auto)); + assert_eq!(read_rendering_prefs(Some(&p)), (Auto, RenderingMode::Auto)); + std::fs::write(&p, r#"{"performance": {"gpuBackend": "dx12", "useGpu": false}, "interface": {}}"#).unwrap(); + assert_eq!(read_rendering_prefs(Some(&p)), (Dx12, RenderingMode::Cpu)); + std::fs::write(&p, r#"{"performance": {"gpuBackend": "quantum"}}"#).unwrap(); + assert_eq!(read_rendering_prefs(Some(&p)), (Auto, RenderingMode::Auto)); + std::fs::write(&p, r#"{"performance": {"useGpu": false, "renderingMode": "gpu"}}"#).unwrap(); + assert_eq!(read_rendering_prefs(Some(&p)), (Auto, RenderingMode::Gpu)); + std::fs::write(&p, "{not json").unwrap(); + assert_eq!(read_rendering_prefs(Some(&p)), (Auto, RenderingMode::Auto)); + let _ = std::fs::remove_dir_all(&dir); +} + +/// #712: never a `dxcompiler.dll` found through the DLL search path (current directory, PATH). +#[test] +fn dx12_compiler_is_fxc_or_dxc_beside_the_exe() { + use wgpu::Dx12Compiler as C; + let dir = temp_dir("dxc"); + std::fs::create_dir_all(&dir).unwrap(); + assert!(matches!(dx12_compiler(None, None), C::Fxc)); + assert!(matches!(dx12_compiler(None, Some(&dir)), C::Fxc)); + std::fs::write(dir.join("dxcompiler.dll"), b"MZ").unwrap(); + let expected = dir.join("dxcompiler.dll"); + assert!(matches!(dx12_compiler(None, Some(&dir)), C::DynamicDxc { dxc_path } if Path::new(&dxc_path) == expected)); + // An explicit WGPU_DX12_COMPILER wins; an unknown value is ignored. + assert!(matches!(dx12_compiler(Some(" FXC "), Some(&dir)), C::Fxc)); + assert!(matches!(dx12_compiler(Some("dxc"), None), C::DynamicDxc { dxc_path } if dxc_path == "dxcompiler.dll")); + assert!(matches!(dx12_compiler(Some("quantum"), None), C::Fxc)); + let _ = std::fs::remove_dir_all(&dir); + + // The app's setup replaces wgpu's default (`Auto`: DXC by name from the search path). + let mut setup = egui_wgpu::WgpuSetup::without_display_handle(); + let plan = plan(Auto, None, None, false, Os::Windows); + configure(&mut setup, &plan, Os::Windows, None, Arc::new(Mutex::new(None)), Arc::default()); + let egui_wgpu::WgpuSetup::CreateNew(create) = &setup else { panic!("a new instance") }; + if std::env::var_os("WGPU_DX12_COMPILER").is_none() { + let safe = match &create.instance_descriptor.backend_options.dx12.shader_compiler { + C::Fxc => true, + C::DynamicDxc { dxc_path } => Path::new(dxc_path).is_absolute(), + C::StaticDxc | C::Auto => false, + }; + assert!(safe, "{:?}", create.instance_descriptor.backend_options.dx12.shader_compiler); + } +} + +#[test] +fn intel_macs_skip_the_indirect_validation_shaders() { + // Metal's compiler crashed on them on Intel Iris Pro, losing the device in every mode (#3107). + assert!(skips_indirect_validation(Os::Mac, true)); + // Apple silicon, Windows and Linux keep wgpu's validation. + for (os, intel) in [(Os::Mac, false), (Os::Windows, true), (Os::Other, true), (Os::Other, false)] { + assert!(!skips_indirect_validation(os, intel), "{os:?} intel={intel}"); + } + for (os, safe_gpu) in [(Os::Windows, false), (Os::Other, true), (Os::Other, false)] { + let mut setup = egui_wgpu::WgpuSetup::without_display_handle(); + let egui_wgpu::WgpuSetup::CreateNew(before) = &setup else { panic!("a new instance") }; + let before = before.instance_descriptor.flags; + configure(&mut setup, &plan(Auto, None, None, safe_gpu, os), os, None, Arc::new(Mutex::new(None)), Arc::default()); + let egui_wgpu::WgpuSetup::CreateNew(create) = &setup else { panic!("a new instance") }; + assert_eq!(create.instance_descriptor.flags, before, "{os:?}: flags untouched"); + } + if cfg!(target_arch = "x86_64") && std::env::var_os("WGPU_VALIDATION_INDIRECT_CALL").is_none() { + let mut setup = egui_wgpu::WgpuSetup::without_display_handle(); + configure(&mut setup, &plan(Auto, None, None, false, Os::Mac), Os::Mac, None, Arc::new(Mutex::new(None)), Arc::default()); + let egui_wgpu::WgpuSetup::CreateNew(create) = &setup else { panic!("a new instance") }; + assert!(!create.instance_descriptor.flags.contains(wgpu::InstanceFlags::VALIDATION_INDIRECT_CALL)); + } +} diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rs index 2966eee8ed..47b4bbd34a 100644 --- a/apps/photocraft/src/services.rs +++ b/apps/photocraft/src/services.rs @@ -725,694 +725,4 @@ fn platform_beep() { } #[cfg(test)] -mod tests { - use super::*; - use photocraft_engine::Session; - use photocraft_format::list_recovery; - use photocraft_ui_egui::{PhotocraftApp, prefs_ui}; - use serde_json::{Value, json}; - - /// #6601: a chosen path whose name isn't valid Unicode is reported, never handed on lossily - /// (Open would fail with "No such file", Save would write a second, renamed file). - #[test] - fn a_chosen_path_that_is_not_valid_unicode_is_an_error_not_another_name() { - #[cfg(unix)] - let bad = { - use std::os::unix::ffi::OsStrExt; - std::env::temp_dir().join(std::ffi::OsStr::from_bytes(b"img\xFF.png")) - }; - #[cfg(windows)] - let bad = { - use std::os::windows::ffi::OsStringExt; - let mut wide: Vec = "img".encode_utf16().collect(); - wide.push(0xD800); - wide.extend(".png".encode_utf16()); - std::env::temp_dir().join(std::ffi::OsString::from_wide(&wide)) - }; - let good = std::env::temp_dir().join("ok.png"); - let save = |path: &Path| answer_one(path, true, FileDialogAnswer::SaveTo); - assert!(matches!(save(&bad), FileDialogAnswer::Unavailable(e) if e.contains("not valid Unicode") && e.contains("another name"))); - assert!(matches!(save(&good), FileDialogAnswer::SaveTo(p) if p == good.to_str().unwrap())); - let open = answer([good.as_path(), bad.as_path()], false, FileDialogAnswer::Paths); - assert!(matches!(open, FileDialogAnswer::Unavailable(e) if e.contains("open it again"))); - } - - /// #6121: the file type picked in the save dialog gives the name its extension where the - /// dialog left the one it opened with, and only there. - #[test] - fn the_picked_file_type_gives_the_name_its_extension() { - let exts = |e: &[&str]| e.iter().map(|s| s.to_string()).collect::>(); - let (png, psd) = (exts(&["png"]), exts(&["psd", "psb"])); - let opened = Some("Untitled-1.psd"); - let cases = [ - // PNG picked, the name as the dialog opened (or renamed, its extension kept). - ("/pics/Untitled-1.psd", opened, &png, "/pics/Untitled-1.png"), - ("/pics/art.psd", opened, &png, "/pics/art.png"), - ("/pics/ART.PSD", opened, &png, "/pics/ART.png"), - // No extension: the type's. One PhotoCraft doesn't save is part of the name. - ("/pics/art", opened, &png, "/pics/art.png"), - ("/pics/scan.2024", opened, &png, "/pics/scan.2024.png"), - // Typed, an extension PhotoCraft saves is the user's: kept, whatever the type says - // (the PSD type untouched, or PNG picked and .jpg typed). - ("/pics/art.png", opened, &psd, "/pics/art.png"), - ("/pics/art.jpg", opened, &png, "/pics/art.jpg"), - ("/pics/art.pcraft", opened, &png, "/pics/art.pcraft"), - // Already the type's: kept, including its other extensions. - ("/pics/art.png", opened, &png, "/pics/art.png"), - ("/pics/art.PNG", opened, &png, "/pics/art.PNG"), - ("/pics/big.psb", opened, &psd, "/pics/big.psb"), - // The dialog opened on a .pcraft: that is the extension the type replaces. - ("/pics/art.pcraft", Some("art.pcraft"), &png, "/pics/art.png"), - ("/pics/art.psd", Some("art.pcraft"), &png, "/pics/art.psd"), - ]; - for (typed, opened, chosen, want) in cases { - assert_eq!(with_chosen_type(Path::new(typed), opened, chosen), PathBuf::from(want), "{typed} (opened {opened:?})"); - } - // No type picked: the name as typed. - assert_eq!(with_chosen_type(Path::new("/pics/art.psd"), opened, &[]), PathBuf::from("/pics/art.psd")); - } - - /// Regression using the real clipboard on an isolated Windows CI runner. - #[cfg(target_os = "windows")] - #[test] - #[ignore = "requires exclusive use of the Windows clipboard"] - fn busy_native_clipboard_preserves_copied_shape() { - for id in ["edit.paste", "edit.pasteSpecial.pasteInPlace"] { - let mut native = native(None); - let services = Services { - clipboard_set_image: native.clipboard_set_image.take(), - clipboard_get_image: native.clipboard_get_image.take(), - ..Default::default() - }; - let mut app = PhotocraftApp::new(Session::new(), services); - app.run("file.new", json!({"width": 80, "height": 60})).unwrap(); - app.run("shape.create", json!({"kind": "rect", "rect": [10, 10, 40, 20], "fill": "#ff0000"})).unwrap(); - app.run("edit.copy", json!({})).unwrap(); - assert!(app.session.clipboard.as_ref().unwrap().layers.is_some()); - assert!(app.services.clipboard_get_image.as_mut().unwrap()().unwrap().is_some(), "native export succeeded"); - app.run("file.new", json!({"width": 80, "height": 60})).unwrap(); - - // Another thread holds the OS clipboard open beyond arboard's bounded retry window. - let (ready_tx, ready_rx) = std::sync::mpsc::channel(); - let (release_tx, release_rx) = std::sync::mpsc::channel(); - let holder = std::thread::spawn(move || { - // A non-null window distinguishes this owner from arboard's null-window opens. - let guard = winsafe::HWND::GetDesktopWindow().OpenClipboard().unwrap(); - ready_tx.send(()).unwrap(); - release_rx.recv_timeout(std::time::Duration::from_secs(10)).unwrap(); - drop(guard); - }); - ready_rx.recv_timeout(std::time::Duration::from_secs(10)).unwrap(); - let contention = arboard::Clipboard::new().unwrap().get_image().err(); - let first = app.run(id, json!({})); - release_tx.send(()).unwrap(); - holder.join().unwrap(); - assert!(matches!(contention, Some(arboard::Error::ClipboardOccupied)), "diagnostic must actually occupy the clipboard: {contention:?}"); - eprintln!("paste while clipboard occupied: {first:?}"); - assert!(first.is_err(), "report contention rather than a successful no-op"); - assert!( - app.session.clipboard.as_ref().is_some_and(|clip| clip.layers.is_some()), - "a temporary OS read failure must not discard the copied editable shape" - ); - app.run(id, json!({})).unwrap(); - let state = app.session.active().unwrap(); - assert!( - matches!(state.doc.layer(state.active_layer.unwrap()).unwrap().content, photocraft_doc::LayerContent::Shape(_)), - "retry keeps the shape editable" - ); - } - } - - #[cfg(all(unix, not(target_os = "macos")))] - #[test] - fn open_filters_cover_uppercase_and_mixed_case_extensions() { - // Matches `text` against a glob of literals and `[..]` classes, as the portal would after `*.`. - fn matches(glob: &str, text: &str) -> bool { - let mut text = text.chars(); - let mut glob = glob.chars(); - while let Some(g) = glob.next() { - let class: String = if g == '[' { glob.by_ref().take_while(|&c| c != ']').collect() } else { g.to_string() }; - if !text.next().is_some_and(|t| class.contains(t)) { - return false; - } - } - text.next().is_none() - } - assert_eq!(open_filter_extensions(&["cr2", "pcraft"]), ["[cC][rR]2", "[pP][cC][rR][aA][fF][tT]"]); - let globs = open_filter_extensions(OPEN_EXTS); - assert_eq!(globs.len(), OPEN_EXTS.len()); - for (ext, glob) in OPEN_EXTS.iter().zip(&globs) { - // Every casing: lower, UPPER, and alternating both ways (JpG, jPg). - let alternating = |upper_first: bool| -> String { - ext.chars().enumerate().map(|(i, c)| if (i % 2 == 0) == upper_first { c.to_ascii_uppercase() } else { c }).collect() - }; - for name in [ext.to_string(), ext.to_ascii_uppercase(), alternating(true), alternating(false)] { - assert!(matches(glob, &name), "{glob} should match .{name}"); - } - assert!(!matches(glob, &format!("{ext}x")) && !matches(glob, &ext[..ext.len() - 1]), "{glob} matches only .{ext}"); - } - assert!(!globs.iter().any(|glob| matches(glob, "txt"))); - let svg_filter = open_filters().into_iter().find(|(name, _)| *name == "SVG").map(|(_, exts)| exts).unwrap_or_default(); - assert_eq!(svg_filter, open_filter_extensions(SVG_EXTS)); - let psd_filter = open_filters().into_iter().find(|(name, _)| *name == "Photoshop").map(|(_, exts)| exts).unwrap_or_default(); - assert_eq!(psd_filter, open_filter_extensions(&["psd", "psb", "psdt"])); - assert!(psd_filter.iter().any(|glob| matches(glob, "psd")) && psd_filter.iter().any(|glob| matches(glob, "PSD"))); - assert!(svg_filter.iter().any(|glob| matches(glob, "svg")) && svg_filter.iter().any(|glob| matches(glob, "svgz"))); - } - - /// #6337: after All Formats, every format File › Open reads has its own filter, and no filter - /// offers an extension All Formats doesn't. - #[test] - fn every_open_format_has_its_own_filter() { - let filters = open_filters(); - assert_eq!(filters[0], ("All Formats", open_filter_extensions(OPEN_EXTS)), "All Formats comes first"); - let mut named: Vec<&str> = OPEN_FILTERS.iter().flat_map(|(_, exts)| exts.iter().copied()).collect(); - let total = named.len(); - named.sort_unstable(); - named.dedup(); - assert_eq!(named.len(), total, "an extension is listed under two filters"); - let mut all = OPEN_EXTS.to_vec(); - all.sort_unstable(); - assert_eq!(named, all, "the named filters cover All Formats exactly"); - let names: Vec<&str> = filters.iter().map(|(name, _)| *name).collect(); - for name in ["Photoshop", "Affinity", "HEIF", "PNG", "JPEG", "TIFF", "Portable Bitmap", "OpenEXR", "Radiance HDR", "Paint.NET"] { - assert!(names.contains(&name), "{name}"); - } - } - - #[cfg(not(all(unix, not(target_os = "macos"))))] - #[test] - fn open_filters_keep_literal_extensions_on_windows_and_macos() { - assert_eq!(open_filter_extensions(OPEN_EXTS), OPEN_EXTS); - assert_eq!(open_filter_extensions(&["pcraft"]), ["pcraft"]); - assert_eq!(open_filters().into_iter().find(|(name, _)| *name == "SVG").map(|(_, exts)| exts), Some(vec!["svg".to_string(), "svgz".to_string()])); - assert_eq!( - open_filters().into_iter().find(|(name, _)| *name == "Photoshop").map(|(_, exts)| exts), - Some(vec!["psd".to_string(), "psb".to_string(), "psdt".to_string()]) - ); - } - - #[test] - fn flatpak_builds_have_no_update_transport() { - assert!(update_transport(Some(std::ffi::OsStr::new("ai.storyteller.photocraft"))).is_none()); - assert!(update_transport(None).is_some()); - } - - #[test] - fn xwayland_command_matches_how_photocraft_was_installed() { - // Flatpak: WAYLAND_DISPLAY doesn't reach the sandbox's socket choice; flatpak's flags do. - let flatpak = xwayland_command(Some("ai.storyteller.photocraft"), None, false); - assert_eq!(flatpak.as_deref(), Some("flatpak run --nosocket=wayland --socket=x11 ai.storyteller.photocraft")); - // AppImage: its own path, quoted for the shell (spaces, quotes). - let appimage = xwayland_command(None, Some("/home/me/My Apps/it's.AppImage"), true); - assert_eq!(appimage.as_deref(), Some(r"WAYLAND_DISPLAY= '/home/me/My Apps/it'\''s.AppImage'")); - let bare = xwayland_command(None, Some("/opt/photocraft-0.3.0-linux-x86_64.AppImage"), true); - assert_eq!(bare.as_deref(), Some("WAYLAND_DISPLAY= /opt/photocraft-0.3.0-linux-x86_64.AppImage")); - // deb, rpm, AUR, tarball: the binary on the PATH. - assert_eq!(xwayland_command(None, None, true).as_deref(), Some("WAYLAND_DISPLAY= photocraft")); - assert_eq!(xwayland_command(Some(""), Some(""), true).as_deref(), Some("WAYLAND_DISPLAY= photocraft")); - // No X server (XWayland disabled): nothing to suggest. - assert_eq!(xwayland_command(None, Some("/opt/p.AppImage"), false), None); - } - - /// Tests every native save dialog and records the suggested file name. Each name's file type must come first - /// in the save panel, or the panel appends the first type's extension (`photo.webp.psd`, `photo.gif.psd`). - #[test] - fn every_save_dialog_leads_with_its_own_extension() { - let asked: Rc>> = Rc::default(); - let log = asked.clone(); - // Record each save dialog's suggested name and cancel it, as the user would. - let services = Services { - file_dialog: Some(Box::new(move |request, _parent, reply| { - if let FileDialogRequest::Save { suggested } = request { - log.borrow_mut().push(suggested); - } - reply.send(None); - })), - ..Default::default() - }; - let mut app = PhotocraftApp::new(Session::new(), services); - let ctx = egui::Context::default(); - // Dialogs are shown on the next frame: poll once so each is answered before the next asks. - let invoke = |app: &mut PhotocraftApp, id: &str| { - let r = photocraft_ui_egui::menus::invoke(app, &ctx, id, json!({})); - app.poll_file_dialog(&ctx, None); - r - }; - let dialog = |app: &mut PhotocraftApp, id: &str, fields: Value| { - let d = invoke(app, id).unwrap()["dialog"].as_u64().unwrap(); - for (k, v) in fields.as_object().unwrap() { - app.ui.dialog_mut(d).unwrap().fields.insert(k.clone(), v.clone()); - } - let _ = photocraft_ui_egui::dialogs::confirm(app, d); - app.poll_file_dialog(&ctx, None); - }; - new_doc(&mut app, "#ff0000"); - // Save As, Save a Copy. - // Files in a format Save As can't write, like .dng, should suggest .psd instead. - let _ = invoke(&mut app, "file.saveAs"); - for name in ["cat.pcraft", "cat.jpeg", "cat.gif", "cat.bmp", "cat.dng"] { - app.session.active_mut().unwrap().path = Some(name.into()); - let _ = invoke(&mut app, "file.saveAs"); - } - let _ = invoke(&mut app, "file.saveACopy"); - // Export As, Quick Export, Save for Web (with and without slices). - for format in ["png", "jpg", "webp", "tif", "tga"] { - dialog(&mut app, "file.export.exportAs", json!({"format": format})); - } - for format in ["png", "jpg", "gif", "webp"] { - app.run("prefs.set", json!({"path": "export.quickExportFormat", "value": format})).unwrap(); - let _ = invoke(&mut app, "file.export.quickExportAsPng"); - } - for format in ["gif", "png8", "png24", "jpeg", "wbmp"] { - dialog(&mut app, "file.export.saveForWebLegacy", json!({"format": format})); - } - app.run("slice.new", json!({"x": 0, "y": 0, "width": 2, "height": 2})).unwrap(); - dialog(&mut app, "file.export.saveForWebLegacy", json!({"html": true})); - // Measurement Log, Export/Import Presets. - app.run("image.analysis.recordMeasurements", json!({})).unwrap(); - let _ = invoke(&mut app, "measurementLog.export"); - dialog(&mut app, "edit.presets.exportImportPresets", json!({"action": "export"})); - let asked = asked.borrow(); - let exts: Vec<&str> = asked.iter().filter_map(|s| s.rsplit_once('.').map(|(_, e)| e)).collect(); - // The extension each save above should suggest, in order. - let want = [ - "psd", // Save As untitled - "pcraft jpeg gif bmp psd", // Save As opened .pcraft .jpeg .gif .bmp .dng - "psd", // Save a Copy - "png jpg webp tif tga", // Export As - "png jpg gif webp", // Quick Export - "gif png png jpg wbmp html", // Save for Web: gif png8 png24 jpeg wbmp, then with slices - "csv pcpresets", // Measurement Log, Export Presets - ] - .join(" "); - assert_eq!(exts, want.split(' ').collect::>()); - for (name, ext) in asked.iter().zip(exts) { - // The first type's first extension is the one Windows adds to the bare name. - assert_eq!(save_filters(name)[0].1.first().map(String::as_str), Some(ext), "{name}: {:?}", save_filters(name)[0]); - } - assert_eq!(save_filters("Untitled")[0].0, "PSD Document", "no extension keeps the default"); - } - - /// Every flat format Save As offers is one PhotoCraft writes, and ICO is among them (#4357). - #[test] - fn save_as_offers_only_writable_formats_including_ico() { - // Layered formats, and PDF, are written by `photocraft-io`, not a codec. - let layered = ["psd", "psb", "pcraft", "ora", "pdf"]; - for (name, exts) in SAVE_FILTERS { - for ext in exts.iter().filter(|e| !layered.contains(e)) { - let format = photocraft_codecs::from_extension(ext).unwrap_or_else(|| panic!("{name}: .{ext} is no known format")); - assert!(format.caps().write, "{name}: .{ext} can't be written"); - } - } - for ext in ["ico", "gif", "bmp", "dds"] { - assert!(save_filters("Untitled-1.psd").iter().any(|(_, exts)| exts.iter().any(|e| e == ext)), ".{ext} is offered"); - } - assert_eq!(save_filters("icon.ico")[0].0, "ICO", "an .ico name leads with its own type"); - // What Save As writes there: an icon up to 256×256, and a clear error past that. - let doc = |side: u32| { - let mut s = Session::new(); - s.execute("file.new", json!({"width": side, "height": side})).unwrap(); - s.active().unwrap().doc.clone() - }; - let opts = export_options(&photocraft_ui_egui::ExportSettings::default()); - let icon = photocraft_io::export(&doc(256), "icon.ico", &opts).unwrap(); - assert_eq!(icon.bytes[..4], [0, 0, 1, 0], "an ICO header"); - let err = photocraft_io::export(&doc(300), "icon.ico", &opts).map(|_| ()).unwrap_err().to_string(); - assert!(err.contains("256"), "{err}"); - } - - /// #4394: with File name extensions shown, Windows kept `image.psd` when the type was changed to - /// PhotoCraft. Given the bare `image`, it adds the extension of whichever type is picked - /// (checked by hand with rfd 0.17.2 on Windows 11), defaulting to the first type's. - #[test] - fn the_windows_save_dialog_gets_a_bare_name_so_the_type_picks_the_extension() { - for (suggested, name, first) in [ - ("/pics/image.psd", "image", "psd"), - ("/pics/image.psb", "image", "psb"), - ("/pics/image.pcraft", "image", "pcraft"), - ("/pics/sky.fit", "sky", "fit"), - ("cat.jpeg", "cat", "jpeg"), - ("swatches.aco", "swatches", "aco"), - ] { - assert_eq!(dialog_file_name(suggested, true).as_deref(), Some(name), "{suggested}"); - assert_eq!(save_filters(suggested)[0].1[0], first, "{suggested}"); - // Elsewhere the dialogs keep the whole name (see `dialog_file_name`). - let whole = Path::new(suggested).file_name().unwrap().to_string_lossy().into_owned(); - assert_eq!(dialog_file_name(suggested, false), Some(whole), "{suggested}"); - } - // Kept whole: a second dot (Windows could keep `scan.jpg`), the user's upper case, no - // extension, and a dotfile. - for name in ["scan.jpg.psd", "my.photo.psd", "transparent.PNG", "Untitled", ".psd"] { - assert_eq!(dialog_file_name(name, true).as_deref(), Some(name)); - } - assert_eq!(dialog_file_name("", true), None); - } - - /// A name in another letter case reaches the same file where the file system ignores case - /// (Windows, and macOS by default), and only there. Two files with the same contents are two. - #[test] - fn same_file_follows_the_file_system() { - let dir = std::env::temp_dir().join(format!("photocraft-same-file-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let (cat, dog, upper) = (dir.join("CAT.psd"), dir.join("dog.psd"), dir.join("CAT.PSD")); - std::fs::write(&cat, b"same").unwrap(); - std::fs::write(&dog, b"same").unwrap(); - assert!(same_file(&cat, &cat)); - assert!(!same_file(&cat, &dog)); - assert_eq!(same_file(&upper, &cat), upper.exists(), "the same file only where letter case is ignored"); - assert!(!same_file(&dir.join("missing.psd"), &cat)); - std::fs::remove_dir_all(&dir).unwrap(); - } - - /// A hard link is another entry in the folder, though it reaches the same file: a save to it - /// replaces that entry and leaves the other name on the old file. Another spelling of a name, - /// where letter case is ignored, is the same entry. - #[test] - fn a_hard_link_is_another_entry() { - let dir = std::env::temp_dir().join(format!("photocraft-same-entry-{}", std::process::id())); - std::fs::create_dir_all(dir.join("other")).unwrap(); - let (cat, bare, upper, other) = (dir.join("CAT.psd"), dir.join("CAT"), dir.join("CAT.PSD"), dir.join("other").join("CAT.psd")); - std::fs::write(&cat, b"cat").unwrap(); - std::fs::hard_link(&cat, &bare).unwrap(); - std::fs::hard_link(&cat, &other).unwrap(); - // Where both names reach one file (one inode on Unix), the folder still lists both. - let one_file = |_: &Path, _: &Path| true; - assert!(!same_entry(&bare, &cat, one_file)); - assert!(!same_entry(&bare, &cat, same_file)); - assert!(!same_entry(&other, &cat, same_file), "another folder"); - assert!(same_entry(&cat, &cat, one_file)); - assert!(same_entry(&cat, &cat, same_file)); - if upper.exists() { - assert!(same_entry(&upper, &cat, same_file), "one entry where letter case is ignored"); - } else { - std::fs::hard_link(&cat, &upper).unwrap(); - assert!(!same_entry(&upper, &cat, same_file), "two entries where letter case tells names apart"); - } - assert!(!same_entry(&dir.join("missing.psd"), &cat, same_file)); - std::fs::remove_dir_all(&dir).unwrap(); - } - - #[test] - fn block_on_waits_for_a_wake_from_another_thread() { - let (tx, rx) = std::sync::mpsc::channel::(); - let mut woken = false; - let ready = std::future::poll_fn(move |cx| { - if woken { - return std::task::Poll::Ready(7); - } - woken = true; - let _ = tx.send(cx.waker().clone()); - std::task::Poll::Pending - }); - let waker = std::thread::spawn(move || rx.recv().unwrap().wake()); - assert_eq!(block_on(ready), 7); - waker.join().unwrap(); - } - - const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0]; - const BLUE: [f32; 4] = [0.0, 0.0, 1.0, 1.0]; - const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0]; - - /// One app launch with crash recovery in `dir` (dropping it is the crash: background writes - /// already queued finish, nothing else runs). - fn launch(dir: &Path) -> PhotocraftApp { - let mut app = PhotocraftApp::new(Session::new(), recovery_services(Some(dir.to_path_buf()))); - let ctx = egui::Context::default(); - prefs_ui::tick(&mut app, &ctx); - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); - while app.session.has_jobs() && std::time::Instant::now() < deadline { - photocraft_ui_egui::jobs_ui::tick(&mut app, &ctx); - std::thread::sleep(std::time::Duration::from_millis(1)); - } - assert!(!app.session.has_jobs(), "recovery finished"); - app - } - - /// The first pixel of each open document, and whether it's unsaved. - fn open_docs(app: &PhotocraftApp) -> Vec<([f32; 4], bool)> { - app.session.documents().iter().map(|d| (photocraft_compose::flatten(&d.doc).px.first().copied().unwrap_or_default(), d.is_dirty())).collect() - } - - fn index_of(app: &PhotocraftApp, color: [f32; 4]) -> usize { - open_docs(app).iter().position(|(c, _)| *c == color).unwrap() - } - - fn new_doc(app: &mut PhotocraftApp, color: &str) { - app.run("file.new", json!({"width": 4, "height": 4})).unwrap(); - app.run("edit.fill", json!({"color": color})).unwrap(); - } - - fn autosave(app: &mut PhotocraftApp, ctx: &egui::Context) { - prefs_ui::autosave_now(app); - prefs_ui::tick(app, ctx); - } - - #[test] - fn recovered_documents_survive_a_second_crash_until_saved_or_closed() { - let dir = std::env::temp_dir().join(format!("photocraft-recovery-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - let ctx = egui::Context::default(); - // Launch 1: two unsaved documents are autosaved, then the app crashes. - { - let mut app = launch(&dir); - new_doc(&mut app, "#ff0000"); - new_doc(&mut app, "#0000ff"); - autosave(&mut app, &ctx); - } - assert_eq!(list_recovery(&dir).len(), 2); - // Launch 2 recovers both and crashes again before its first autosave (#444). - { - let mut app = launch(&dir); - let mut docs = open_docs(&app); - docs.sort_by(|a, b| a.0[0].total_cmp(&b.0[0])); - assert_eq!(docs, [(BLUE, true), (RED, true)], "recovered and still unsaved"); - prefs_ui::tick(&mut app, &ctx); - } - assert_eq!(list_recovery(&dir).len(), 2, "recovering keeps the entries on disk"); - // Launch 3 has both again; autosaving unchanged documents adds nothing, a new document - // (whose id may repeat one from an earlier launch) gets an entry of its own. - { - let mut app = launch(&dir); - assert_eq!(app.session.documents().len(), 2); - autosave(&mut app, &ctx); - new_doc(&mut app, "#00ff00"); - autosave(&mut app, &ctx); - } - assert_eq!(list_recovery(&dir).len(), 3); - // Launch 4: closing and saving recovered documents removes their entries, no duplicates. - let mut app = launch(&dir); - assert_eq!(app.session.documents().len(), 3); - let red = index_of(&app, RED); - app.run("file.close", json!({"document": red})).unwrap(); - // Saving marks the revision saved (the file write itself is the save service's job). - assert!(app.session.set_active(index_of(&app, BLUE))); - let st = app.session.active_mut().unwrap(); - st.saved_revision = st.revision; - prefs_ui::tick(&mut app, &ctx); - let left = list_recovery(&dir); - assert_eq!(left.len(), 1); - assert_eq!(photocraft_compose::flatten(&photocraft_format::recover(&left[0]).unwrap()).px.first().copied(), Some(GREEN)); - let green = index_of(&app, GREEN); - app.run("file.close", json!({"document": green})).unwrap(); - prefs_ui::tick(&mut app, &ctx); - assert!(list_recovery(&dir).is_empty()); - drop(app); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn failed_background_autosave_is_reported_and_retried_without_another_edit() { - let dir = temp("autosave-retry"); - let recovery = dir.join("Recovery"); - // A regular file prevents creation of the recovery bundle directory. - std::fs::write(&recovery, b"blocked").unwrap(); - let ctx = egui::Context::default(); - let mut app = launch(&recovery); - new_doc(&mut app, "#ff0000"); - let revision = app.session.active().unwrap().revision; - assert_ne!(revision, 0, "a sidecar-less bundle lists as revision 0"); - autosave(&mut app, &ctx); - - let mut failed = false; - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); - while std::time::Instant::now() < deadline { - prefs_ui::tick(&mut app, &ctx); - if app.ui.status.starts_with("Autosave failed:") { - failed = true; - break; - } - std::thread::sleep(std::time::Duration::from_millis(10)); - } - assert!(failed, "background write failures must reach the UI"); - assert!(app.ui.status_error); - assert!(list_recovery(&recovery).is_empty()); - - // No edit occurs: retrying this very same revision must still work. - std::fs::remove_file(&recovery).unwrap(); - std::fs::create_dir(&recovery).unwrap(); - autosave(&mut app, &ctx); - // The worker commits the bundle's manifest before it publishes the sidecar, and - // `list_recovery` lists a committed sidecar-less bundle (revision 0) on its own, so - // the first non-empty listing can come from the middle of the write. Wait for the write - // to finish: the entry then carries the sidecar's revision. - let mut recovered = Vec::new(); - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); - while std::time::Instant::now() < deadline { - prefs_ui::tick(&mut app, &ctx); - recovered = list_recovery(&recovery); - if recovered.iter().any(|e| e.info.revision == revision) { - break; - } - std::thread::sleep(std::time::Duration::from_millis(10)); - } - assert_eq!(recovered.len(), 1, "unchanged revision should retry after failure"); - assert_eq!(recovered[0].info.revision, revision); - let restored = photocraft_format::recover(&recovered[0]).unwrap(); - assert_eq!(photocraft_compose::flatten(&restored).px.first().copied(), Some(RED)); - drop(app); - std::fs::remove_dir_all(dir).unwrap(); - } - - use std::sync::atomic::{AtomicUsize, Ordering}; - - fn temp(tag: &str) -> PathBuf { - static N: AtomicUsize = AtomicUsize::new(0); - let d = std::env::temp_dir().join(format!("photocraft-services-{tag}-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed))); - let _ = std::fs::remove_dir_all(&d); - std::fs::create_dir_all(&d).unwrap(); - d - } - - fn red_png(w: u32, h: u32) -> Vec { - let img = Image::from_u8(w, h, ChannelLayout::Rgba, [255u8, 0, 0, 255].repeat((w * h) as usize)).unwrap(); - photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &EncodeOptions::default()).unwrap() - } - - /// A 1×1 uncompressed 32-bit TGA (TGA has no magic number). - fn tga_1x1() -> Vec { - let mut b = vec![0u8, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 32, 8]; - b.extend_from_slice(&[0, 0, 255, 255]); // BGRA red - b - } - - #[test] - fn copied_image_file_pastes_its_pixels() { - let dir = temp("png"); - let png = dir.join("red.png"); - std::fs::write(&png, red_png(3, 2)).unwrap(); - let (w, h, px) = image_from_files(&[png]).unwrap(); - assert_eq!((w, h), (3, 2)); - assert_eq!(px, [255u8, 0, 0, 255].repeat(6)); - } - - #[test] - fn crlf_from_a_uri_list_is_ignored() { - // arboard splits text/uri-list on LF, so GNOME Files' CRLF list leaves a '\r' behind. - let dir = temp("crlf"); - let png = dir.join("red image.png"); - std::fs::write(&png, red_png(2, 2)).unwrap(); - let with_cr = PathBuf::from(format!("{}\r", png.display())); - assert_eq!(image_from_files(&[with_cr]).map(|(w, h, _)| (w, h)), Some((2, 2))); - } - - #[test] - fn non_images_are_skipped_for_the_first_image() { - let dir = temp("mixed"); - let (txt, png) = (dir.join("notes.txt"), dir.join("red.png")); - std::fs::write(&txt, b"not an image").unwrap(); - std::fs::write(&png, red_png(4, 1)).unwrap(); - let missing = dir.join("gone.png"); - assert_eq!(image_from_files(&[missing.clone(), txt.clone(), dir.clone(), png]).map(|(w, h, _)| (w, h)), Some((4, 1))); - assert!(image_from_files(&[missing, txt, dir]).is_none()); - assert!(image_from_files(&[]).is_none()); - } - - #[test] - fn a_damaged_image_is_skipped_not_a_panic() { - let dir = temp("damaged"); - let bad = dir.join("cut.png"); - std::fs::write(&bad, &red_png(8, 8)[..20]).unwrap(); - assert!(image_from_files(&[bad]).is_none()); - } - - fn encoded(format: photocraft_codecs::Format, w: u32, h: u32) -> Vec { - let img = Image::from_u8(w, h, ChannelLayout::Rgba, [255u8, 0, 0, 255].repeat((w * h) as usize)).unwrap(); - photocraft_codecs::encode(&img, format, &EncodeOptions::default()).unwrap() - } - - #[test] - fn non_png_clipboard_images_paste() { - // #2546: a screenshot tool that offers only image/bmp or image/jpeg pasted nothing. - let bmp = encoded(photocraft_codecs::Format::Bmp, 3, 2); - let offers = vec!["text/plain".to_string(), "image/bmp".to_string()]; - let mut asked = Vec::new(); - let got = image_from_offers(&offers, |mime| { - asked.push(mime.to_string()); - Some(bmp.clone()) - }); - assert_eq!(got, Some((3, 2, [255u8, 0, 0, 255].repeat(6)))); - assert_eq!(asked, ["image/bmp"], "text offers are never fetched"); - - let jpeg = encoded(photocraft_codecs::Format::Jpeg, 16, 8); - let offers = vec!["image/jpeg".to_string()]; - assert_eq!(image_from_offers(&offers, |_| Some(jpeg.clone())).map(|(w, h, _)| (w, h)), Some((16, 8))); - } - - #[test] - fn undecodable_clipboard_offers_fall_through_to_the_next() { - let bmp = encoded(photocraft_codecs::Format::Bmp, 2, 2); - let cut = encoded(photocraft_codecs::Format::Png, 8, 8)[..20].to_vec(); - let offers: Vec = ["image/webp", "image/png", "image/x-tga", "image/bmp"].map(String::from).to_vec(); - let got = image_from_offers(&offers, |mime| match mime { - "image/webp" => None, - "image/png" => Some(cut.clone()), - "image/x-tga" => Some(b"not an image".to_vec()), - _ => Some(bmp.clone()), - }); - assert_eq!(got.map(|(w, h, _)| (w, h)), Some((2, 2))); - assert!(image_from_offers(&offers[..3], |_| Some(cut.clone())).is_none()); - assert!(image_from_offers(&[], |_| Some(bmp.clone())).is_none()); - } - - #[test] - fn clipboard_tga_is_trusted_only_by_its_type() { - assert_eq!(image_from_offers(&["image/x-tga".to_string()], |_| Some(tga_1x1())), Some((1, 1, vec![255, 0, 0, 255]))); - assert!(image_from_offers(&["image/x-unknown".to_string()], |_| Some(tga_1x1())).is_none()); - } - - #[test] - fn tga_is_trusted_only_with_its_extension() { - let dir = temp("tga"); - let (tga, bin) = (dir.join("red.tga"), dir.join("red.bin")); - std::fs::write(&tga, tga_1x1()).unwrap(); - std::fs::write(&bin, tga_1x1()).unwrap(); - assert_eq!(image_from_files(&[tga]), Some((1, 1, vec![255, 0, 0, 255]))); - assert!(image_from_files(&[bin]).is_none()); - } - - /// #7582: a panic while reading the OS clipboard (in arboard, or decoding a copied file) is - /// the paste's error in the status bar, not a crash: the document stays and the next paste - /// works. The same for a panic while writing it. - #[test] - fn a_panicking_clipboard_read_is_reported_not_a_crash() { - let panics = Rc::new(Cell::new(true)); - let p = panics.clone(); - let get = guarded_clipboard_get(move || if p.get() { panic!("clipboard decoder bug") } else { Ok(Some((2, 2, [0u8, 0, 255, 255].repeat(4)))) }); - let mut app = PhotocraftApp::new(Session::new(), Services { clipboard_get_image: Some(get), ..Default::default() }); - app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); - let layers = app.session.active().unwrap().doc.layers.len(); - - let error = app.run("edit.paste", json!({})).unwrap_err(); - assert!(error.contains("Paste failed"), "{error}"); - assert!(app.ui.status_error && app.ui.status.contains("Paste failed"), "{}", app.ui.status); - assert_eq!(app.session.active().unwrap().doc.layers.len(), layers, "the document is unchanged"); - - panics.set(false); - app.run("edit.paste", json!({})).unwrap(); - assert_eq!(app.session.active().unwrap().doc.layers.len(), layers + 1, "the next paste works"); - - let mut set = guarded_clipboard_set(|_: u32, _: u32, _: &[u8]| panic!("clipboard writer bug")); - assert!(set(1, 1, &[0; 4]).unwrap_err().contains("Copy failed")); - } -} +mod tests; diff --git a/apps/photocraft/src/services/tests.rs b/apps/photocraft/src/services/tests.rs new file mode 100644 index 0000000000..f9bce2a367 --- /dev/null +++ b/apps/photocraft/src/services/tests.rs @@ -0,0 +1,686 @@ +use super::*; +use photocraft_engine::Session; +use photocraft_format::list_recovery; +use photocraft_ui_egui::{PhotocraftApp, prefs_ui}; +use serde_json::{Value, json}; + +/// #6601: a chosen path whose name isn't valid Unicode is reported, never handed on lossily +/// (Open would fail with "No such file", Save would write a second, renamed file). +#[test] +fn a_chosen_path_that_is_not_valid_unicode_is_an_error_not_another_name() { + #[cfg(unix)] + let bad = { + use std::os::unix::ffi::OsStrExt; + std::env::temp_dir().join(std::ffi::OsStr::from_bytes(b"img\xFF.png")) + }; + #[cfg(windows)] + let bad = { + use std::os::windows::ffi::OsStringExt; + let mut wide: Vec = "img".encode_utf16().collect(); + wide.push(0xD800); + wide.extend(".png".encode_utf16()); + std::env::temp_dir().join(std::ffi::OsString::from_wide(&wide)) + }; + let good = std::env::temp_dir().join("ok.png"); + let save = |path: &Path| answer_one(path, true, FileDialogAnswer::SaveTo); + assert!(matches!(save(&bad), FileDialogAnswer::Unavailable(e) if e.contains("not valid Unicode") && e.contains("another name"))); + assert!(matches!(save(&good), FileDialogAnswer::SaveTo(p) if p == good.to_str().unwrap())); + let open = answer([good.as_path(), bad.as_path()], false, FileDialogAnswer::Paths); + assert!(matches!(open, FileDialogAnswer::Unavailable(e) if e.contains("open it again"))); +} + +/// #6121: the file type picked in the save dialog gives the name its extension where the +/// dialog left the one it opened with, and only there. +#[test] +fn the_picked_file_type_gives_the_name_its_extension() { + let exts = |e: &[&str]| e.iter().map(|s| s.to_string()).collect::>(); + let (png, psd) = (exts(&["png"]), exts(&["psd", "psb"])); + let opened = Some("Untitled-1.psd"); + let cases = [ + // PNG picked, the name as the dialog opened (or renamed, its extension kept). + ("/pics/Untitled-1.psd", opened, &png, "/pics/Untitled-1.png"), + ("/pics/art.psd", opened, &png, "/pics/art.png"), + ("/pics/ART.PSD", opened, &png, "/pics/ART.png"), + // No extension: the type's. One PhotoCraft doesn't save is part of the name. + ("/pics/art", opened, &png, "/pics/art.png"), + ("/pics/scan.2024", opened, &png, "/pics/scan.2024.png"), + // Typed, an extension PhotoCraft saves is the user's: kept, whatever the type says + // (the PSD type untouched, or PNG picked and .jpg typed). + ("/pics/art.png", opened, &psd, "/pics/art.png"), + ("/pics/art.jpg", opened, &png, "/pics/art.jpg"), + ("/pics/art.pcraft", opened, &png, "/pics/art.pcraft"), + // Already the type's: kept, including its other extensions. + ("/pics/art.png", opened, &png, "/pics/art.png"), + ("/pics/art.PNG", opened, &png, "/pics/art.PNG"), + ("/pics/big.psb", opened, &psd, "/pics/big.psb"), + // The dialog opened on a .pcraft: that is the extension the type replaces. + ("/pics/art.pcraft", Some("art.pcraft"), &png, "/pics/art.png"), + ("/pics/art.psd", Some("art.pcraft"), &png, "/pics/art.psd"), + ]; + for (typed, opened, chosen, want) in cases { + assert_eq!(with_chosen_type(Path::new(typed), opened, chosen), PathBuf::from(want), "{typed} (opened {opened:?})"); + } + // No type picked: the name as typed. + assert_eq!(with_chosen_type(Path::new("/pics/art.psd"), opened, &[]), PathBuf::from("/pics/art.psd")); +} + +/// Regression using the real clipboard on an isolated Windows CI runner. +#[cfg(target_os = "windows")] +#[test] +#[ignore = "requires exclusive use of the Windows clipboard"] +fn busy_native_clipboard_preserves_copied_shape() { + for id in ["edit.paste", "edit.pasteSpecial.pasteInPlace"] { + let mut native = native(None); + let services = + Services { clipboard_set_image: native.clipboard_set_image.take(), clipboard_get_image: native.clipboard_get_image.take(), ..Default::default() }; + let mut app = PhotocraftApp::new(Session::new(), services); + app.run("file.new", json!({"width": 80, "height": 60})).unwrap(); + app.run("shape.create", json!({"kind": "rect", "rect": [10, 10, 40, 20], "fill": "#ff0000"})).unwrap(); + app.run("edit.copy", json!({})).unwrap(); + assert!(app.session.clipboard.as_ref().unwrap().layers.is_some()); + assert!(app.services.clipboard_get_image.as_mut().unwrap()().unwrap().is_some(), "native export succeeded"); + app.run("file.new", json!({"width": 80, "height": 60})).unwrap(); + + // Another thread holds the OS clipboard open beyond arboard's bounded retry window. + let (ready_tx, ready_rx) = std::sync::mpsc::channel(); + let (release_tx, release_rx) = std::sync::mpsc::channel(); + let holder = std::thread::spawn(move || { + // A non-null window distinguishes this owner from arboard's null-window opens. + let guard = winsafe::HWND::GetDesktopWindow().OpenClipboard().unwrap(); + ready_tx.send(()).unwrap(); + release_rx.recv_timeout(std::time::Duration::from_secs(10)).unwrap(); + drop(guard); + }); + ready_rx.recv_timeout(std::time::Duration::from_secs(10)).unwrap(); + let contention = arboard::Clipboard::new().unwrap().get_image().err(); + let first = app.run(id, json!({})); + release_tx.send(()).unwrap(); + holder.join().unwrap(); + assert!(matches!(contention, Some(arboard::Error::ClipboardOccupied)), "diagnostic must actually occupy the clipboard: {contention:?}"); + eprintln!("paste while clipboard occupied: {first:?}"); + assert!(first.is_err(), "report contention rather than a successful no-op"); + assert!( + app.session.clipboard.as_ref().is_some_and(|clip| clip.layers.is_some()), + "a temporary OS read failure must not discard the copied editable shape" + ); + app.run(id, json!({})).unwrap(); + let state = app.session.active().unwrap(); + assert!( + matches!(state.doc.layer(state.active_layer.unwrap()).unwrap().content, photocraft_doc::LayerContent::Shape(_)), + "retry keeps the shape editable" + ); + } +} + +#[cfg(all(unix, not(target_os = "macos")))] +#[test] +fn open_filters_cover_uppercase_and_mixed_case_extensions() { + // Matches `text` against a glob of literals and `[..]` classes, as the portal would after `*.`. + fn matches(glob: &str, text: &str) -> bool { + let mut text = text.chars(); + let mut glob = glob.chars(); + while let Some(g) = glob.next() { + let class: String = if g == '[' { glob.by_ref().take_while(|&c| c != ']').collect() } else { g.to_string() }; + if !text.next().is_some_and(|t| class.contains(t)) { + return false; + } + } + text.next().is_none() + } + assert_eq!(open_filter_extensions(&["cr2", "pcraft"]), ["[cC][rR]2", "[pP][cC][rR][aA][fF][tT]"]); + let globs = open_filter_extensions(OPEN_EXTS); + assert_eq!(globs.len(), OPEN_EXTS.len()); + for (ext, glob) in OPEN_EXTS.iter().zip(&globs) { + // Every casing: lower, UPPER, and alternating both ways (JpG, jPg). + let alternating = |upper_first: bool| -> String { + ext.chars().enumerate().map(|(i, c)| if (i % 2 == 0) == upper_first { c.to_ascii_uppercase() } else { c }).collect() + }; + for name in [ext.to_string(), ext.to_ascii_uppercase(), alternating(true), alternating(false)] { + assert!(matches(glob, &name), "{glob} should match .{name}"); + } + assert!(!matches(glob, &format!("{ext}x")) && !matches(glob, &ext[..ext.len() - 1]), "{glob} matches only .{ext}"); + } + assert!(!globs.iter().any(|glob| matches(glob, "txt"))); + let svg_filter = open_filters().into_iter().find(|(name, _)| *name == "SVG").map(|(_, exts)| exts).unwrap_or_default(); + assert_eq!(svg_filter, open_filter_extensions(SVG_EXTS)); + let psd_filter = open_filters().into_iter().find(|(name, _)| *name == "Photoshop").map(|(_, exts)| exts).unwrap_or_default(); + assert_eq!(psd_filter, open_filter_extensions(&["psd", "psb", "psdt"])); + assert!(psd_filter.iter().any(|glob| matches(glob, "psd")) && psd_filter.iter().any(|glob| matches(glob, "PSD"))); + assert!(svg_filter.iter().any(|glob| matches(glob, "svg")) && svg_filter.iter().any(|glob| matches(glob, "svgz"))); +} + +/// #6337: after All Formats, every format File › Open reads has its own filter, and no filter +/// offers an extension All Formats doesn't. +#[test] +fn every_open_format_has_its_own_filter() { + let filters = open_filters(); + assert_eq!(filters[0], ("All Formats", open_filter_extensions(OPEN_EXTS)), "All Formats comes first"); + let mut named: Vec<&str> = OPEN_FILTERS.iter().flat_map(|(_, exts)| exts.iter().copied()).collect(); + let total = named.len(); + named.sort_unstable(); + named.dedup(); + assert_eq!(named.len(), total, "an extension is listed under two filters"); + let mut all = OPEN_EXTS.to_vec(); + all.sort_unstable(); + assert_eq!(named, all, "the named filters cover All Formats exactly"); + let names: Vec<&str> = filters.iter().map(|(name, _)| *name).collect(); + for name in ["Photoshop", "Affinity", "HEIF", "PNG", "JPEG", "TIFF", "Portable Bitmap", "OpenEXR", "Radiance HDR", "Paint.NET"] { + assert!(names.contains(&name), "{name}"); + } +} + +#[cfg(not(all(unix, not(target_os = "macos"))))] +#[test] +fn open_filters_keep_literal_extensions_on_windows_and_macos() { + assert_eq!(open_filter_extensions(OPEN_EXTS), OPEN_EXTS); + assert_eq!(open_filter_extensions(&["pcraft"]), ["pcraft"]); + assert_eq!(open_filters().into_iter().find(|(name, _)| *name == "SVG").map(|(_, exts)| exts), Some(vec!["svg".to_string(), "svgz".to_string()])); + assert_eq!( + open_filters().into_iter().find(|(name, _)| *name == "Photoshop").map(|(_, exts)| exts), + Some(vec!["psd".to_string(), "psb".to_string(), "psdt".to_string()]) + ); +} + +#[test] +fn flatpak_builds_have_no_update_transport() { + assert!(update_transport(Some(std::ffi::OsStr::new("ai.storyteller.photocraft"))).is_none()); + assert!(update_transport(None).is_some()); +} + +#[test] +fn xwayland_command_matches_how_photocraft_was_installed() { + // Flatpak: WAYLAND_DISPLAY doesn't reach the sandbox's socket choice; flatpak's flags do. + let flatpak = xwayland_command(Some("ai.storyteller.photocraft"), None, false); + assert_eq!(flatpak.as_deref(), Some("flatpak run --nosocket=wayland --socket=x11 ai.storyteller.photocraft")); + // AppImage: its own path, quoted for the shell (spaces, quotes). + let appimage = xwayland_command(None, Some("/home/me/My Apps/it's.AppImage"), true); + assert_eq!(appimage.as_deref(), Some(r"WAYLAND_DISPLAY= '/home/me/My Apps/it'\''s.AppImage'")); + let bare = xwayland_command(None, Some("/opt/photocraft-0.3.0-linux-x86_64.AppImage"), true); + assert_eq!(bare.as_deref(), Some("WAYLAND_DISPLAY= /opt/photocraft-0.3.0-linux-x86_64.AppImage")); + // deb, rpm, AUR, tarball: the binary on the PATH. + assert_eq!(xwayland_command(None, None, true).as_deref(), Some("WAYLAND_DISPLAY= photocraft")); + assert_eq!(xwayland_command(Some(""), Some(""), true).as_deref(), Some("WAYLAND_DISPLAY= photocraft")); + // No X server (XWayland disabled): nothing to suggest. + assert_eq!(xwayland_command(None, Some("/opt/p.AppImage"), false), None); +} + +/// Tests every native save dialog and records the suggested file name. Each name's file type must come first +/// in the save panel, or the panel appends the first type's extension (`photo.webp.psd`, `photo.gif.psd`). +#[test] +fn every_save_dialog_leads_with_its_own_extension() { + let asked: Rc>> = Rc::default(); + let log = asked.clone(); + // Record each save dialog's suggested name and cancel it, as the user would. + let services = Services { + file_dialog: Some(Box::new(move |request, _parent, reply| { + if let FileDialogRequest::Save { suggested } = request { + log.borrow_mut().push(suggested); + } + reply.send(None); + })), + ..Default::default() + }; + let mut app = PhotocraftApp::new(Session::new(), services); + let ctx = egui::Context::default(); + // Dialogs are shown on the next frame: poll once so each is answered before the next asks. + let invoke = |app: &mut PhotocraftApp, id: &str| { + let r = photocraft_ui_egui::menus::invoke(app, &ctx, id, json!({})); + app.poll_file_dialog(&ctx, None); + r + }; + let dialog = |app: &mut PhotocraftApp, id: &str, fields: Value| { + let d = invoke(app, id).unwrap()["dialog"].as_u64().unwrap(); + for (k, v) in fields.as_object().unwrap() { + app.ui.dialog_mut(d).unwrap().fields.insert(k.clone(), v.clone()); + } + let _ = photocraft_ui_egui::dialogs::confirm(app, d); + app.poll_file_dialog(&ctx, None); + }; + new_doc(&mut app, "#ff0000"); + // Save As, Save a Copy. + // Files in a format Save As can't write, like .dng, should suggest .psd instead. + let _ = invoke(&mut app, "file.saveAs"); + for name in ["cat.pcraft", "cat.jpeg", "cat.gif", "cat.bmp", "cat.dng"] { + app.session.active_mut().unwrap().path = Some(name.into()); + let _ = invoke(&mut app, "file.saveAs"); + } + let _ = invoke(&mut app, "file.saveACopy"); + // Export As, Quick Export, Save for Web (with and without slices). + for format in ["png", "jpg", "webp", "tif", "tga"] { + dialog(&mut app, "file.export.exportAs", json!({"format": format})); + } + for format in ["png", "jpg", "gif", "webp"] { + app.run("prefs.set", json!({"path": "export.quickExportFormat", "value": format})).unwrap(); + let _ = invoke(&mut app, "file.export.quickExportAsPng"); + } + for format in ["gif", "png8", "png24", "jpeg", "wbmp"] { + dialog(&mut app, "file.export.saveForWebLegacy", json!({"format": format})); + } + app.run("slice.new", json!({"x": 0, "y": 0, "width": 2, "height": 2})).unwrap(); + dialog(&mut app, "file.export.saveForWebLegacy", json!({"html": true})); + // Measurement Log, Export/Import Presets. + app.run("image.analysis.recordMeasurements", json!({})).unwrap(); + let _ = invoke(&mut app, "measurementLog.export"); + dialog(&mut app, "edit.presets.exportImportPresets", json!({"action": "export"})); + let asked = asked.borrow(); + let exts: Vec<&str> = asked.iter().filter_map(|s| s.rsplit_once('.').map(|(_, e)| e)).collect(); + // The extension each save above should suggest, in order. + let want = [ + "psd", // Save As untitled + "pcraft jpeg gif bmp psd", // Save As opened .pcraft .jpeg .gif .bmp .dng + "psd", // Save a Copy + "png jpg webp tif tga", // Export As + "png jpg gif webp", // Quick Export + "gif png png jpg wbmp html", // Save for Web: gif png8 png24 jpeg wbmp, then with slices + "csv pcpresets", // Measurement Log, Export Presets + ] + .join(" "); + assert_eq!(exts, want.split(' ').collect::>()); + for (name, ext) in asked.iter().zip(exts) { + // The first type's first extension is the one Windows adds to the bare name. + assert_eq!(save_filters(name)[0].1.first().map(String::as_str), Some(ext), "{name}: {:?}", save_filters(name)[0]); + } + assert_eq!(save_filters("Untitled")[0].0, "PSD Document", "no extension keeps the default"); +} + +/// Every flat format Save As offers is one PhotoCraft writes, and ICO is among them (#4357). +#[test] +fn save_as_offers_only_writable_formats_including_ico() { + // Layered formats, and PDF, are written by `photocraft-io`, not a codec. + let layered = ["psd", "psb", "pcraft", "ora", "pdf"]; + for (name, exts) in SAVE_FILTERS { + for ext in exts.iter().filter(|e| !layered.contains(e)) { + let format = photocraft_codecs::from_extension(ext).unwrap_or_else(|| panic!("{name}: .{ext} is no known format")); + assert!(format.caps().write, "{name}: .{ext} can't be written"); + } + } + for ext in ["ico", "gif", "bmp", "dds"] { + assert!(save_filters("Untitled-1.psd").iter().any(|(_, exts)| exts.iter().any(|e| e == ext)), ".{ext} is offered"); + } + assert_eq!(save_filters("icon.ico")[0].0, "ICO", "an .ico name leads with its own type"); + // What Save As writes there: an icon up to 256×256, and a clear error past that. + let doc = |side: u32| { + let mut s = Session::new(); + s.execute("file.new", json!({"width": side, "height": side})).unwrap(); + s.active().unwrap().doc.clone() + }; + let opts = export_options(&photocraft_ui_egui::ExportSettings::default()); + let icon = photocraft_io::export(&doc(256), "icon.ico", &opts).unwrap(); + assert_eq!(icon.bytes[..4], [0, 0, 1, 0], "an ICO header"); + let err = photocraft_io::export(&doc(300), "icon.ico", &opts).map(|_| ()).unwrap_err().to_string(); + assert!(err.contains("256"), "{err}"); +} + +/// #4394: with File name extensions shown, Windows kept `image.psd` when the type was changed to +/// PhotoCraft. Given the bare `image`, it adds the extension of whichever type is picked +/// (checked by hand with rfd 0.17.2 on Windows 11), defaulting to the first type's. +#[test] +fn the_windows_save_dialog_gets_a_bare_name_so_the_type_picks_the_extension() { + for (suggested, name, first) in [ + ("/pics/image.psd", "image", "psd"), + ("/pics/image.psb", "image", "psb"), + ("/pics/image.pcraft", "image", "pcraft"), + ("/pics/sky.fit", "sky", "fit"), + ("cat.jpeg", "cat", "jpeg"), + ("swatches.aco", "swatches", "aco"), + ] { + assert_eq!(dialog_file_name(suggested, true).as_deref(), Some(name), "{suggested}"); + assert_eq!(save_filters(suggested)[0].1[0], first, "{suggested}"); + // Elsewhere the dialogs keep the whole name (see `dialog_file_name`). + let whole = Path::new(suggested).file_name().unwrap().to_string_lossy().into_owned(); + assert_eq!(dialog_file_name(suggested, false), Some(whole), "{suggested}"); + } + // Kept whole: a second dot (Windows could keep `scan.jpg`), the user's upper case, no + // extension, and a dotfile. + for name in ["scan.jpg.psd", "my.photo.psd", "transparent.PNG", "Untitled", ".psd"] { + assert_eq!(dialog_file_name(name, true).as_deref(), Some(name)); + } + assert_eq!(dialog_file_name("", true), None); +} + +/// A name in another letter case reaches the same file where the file system ignores case +/// (Windows, and macOS by default), and only there. Two files with the same contents are two. +#[test] +fn same_file_follows_the_file_system() { + let dir = std::env::temp_dir().join(format!("photocraft-same-file-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let (cat, dog, upper) = (dir.join("CAT.psd"), dir.join("dog.psd"), dir.join("CAT.PSD")); + std::fs::write(&cat, b"same").unwrap(); + std::fs::write(&dog, b"same").unwrap(); + assert!(same_file(&cat, &cat)); + assert!(!same_file(&cat, &dog)); + assert_eq!(same_file(&upper, &cat), upper.exists(), "the same file only where letter case is ignored"); + assert!(!same_file(&dir.join("missing.psd"), &cat)); + std::fs::remove_dir_all(&dir).unwrap(); +} + +/// A hard link is another entry in the folder, though it reaches the same file: a save to it +/// replaces that entry and leaves the other name on the old file. Another spelling of a name, +/// where letter case is ignored, is the same entry. +#[test] +fn a_hard_link_is_another_entry() { + let dir = std::env::temp_dir().join(format!("photocraft-same-entry-{}", std::process::id())); + std::fs::create_dir_all(dir.join("other")).unwrap(); + let (cat, bare, upper, other) = (dir.join("CAT.psd"), dir.join("CAT"), dir.join("CAT.PSD"), dir.join("other").join("CAT.psd")); + std::fs::write(&cat, b"cat").unwrap(); + std::fs::hard_link(&cat, &bare).unwrap(); + std::fs::hard_link(&cat, &other).unwrap(); + // Where both names reach one file (one inode on Unix), the folder still lists both. + let one_file = |_: &Path, _: &Path| true; + assert!(!same_entry(&bare, &cat, one_file)); + assert!(!same_entry(&bare, &cat, same_file)); + assert!(!same_entry(&other, &cat, same_file), "another folder"); + assert!(same_entry(&cat, &cat, one_file)); + assert!(same_entry(&cat, &cat, same_file)); + if upper.exists() { + assert!(same_entry(&upper, &cat, same_file), "one entry where letter case is ignored"); + } else { + std::fs::hard_link(&cat, &upper).unwrap(); + assert!(!same_entry(&upper, &cat, same_file), "two entries where letter case tells names apart"); + } + assert!(!same_entry(&dir.join("missing.psd"), &cat, same_file)); + std::fs::remove_dir_all(&dir).unwrap(); +} + +#[test] +fn block_on_waits_for_a_wake_from_another_thread() { + let (tx, rx) = std::sync::mpsc::channel::(); + let mut woken = false; + let ready = std::future::poll_fn(move |cx| { + if woken { + return std::task::Poll::Ready(7); + } + woken = true; + let _ = tx.send(cx.waker().clone()); + std::task::Poll::Pending + }); + let waker = std::thread::spawn(move || rx.recv().unwrap().wake()); + assert_eq!(block_on(ready), 7); + waker.join().unwrap(); +} + +const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0]; +const BLUE: [f32; 4] = [0.0, 0.0, 1.0, 1.0]; +const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0]; + +/// One app launch with crash recovery in `dir` (dropping it is the crash: background writes +/// already queued finish, nothing else runs). +fn launch(dir: &Path) -> PhotocraftApp { + let mut app = PhotocraftApp::new(Session::new(), recovery_services(Some(dir.to_path_buf()))); + let ctx = egui::Context::default(); + prefs_ui::tick(&mut app, &ctx); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + while app.session.has_jobs() && std::time::Instant::now() < deadline { + photocraft_ui_egui::jobs_ui::tick(&mut app, &ctx); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + assert!(!app.session.has_jobs(), "recovery finished"); + app +} + +/// The first pixel of each open document, and whether it's unsaved. +fn open_docs(app: &PhotocraftApp) -> Vec<([f32; 4], bool)> { + app.session.documents().iter().map(|d| (photocraft_compose::flatten(&d.doc).px.first().copied().unwrap_or_default(), d.is_dirty())).collect() +} + +fn index_of(app: &PhotocraftApp, color: [f32; 4]) -> usize { + open_docs(app).iter().position(|(c, _)| *c == color).unwrap() +} + +fn new_doc(app: &mut PhotocraftApp, color: &str) { + app.run("file.new", json!({"width": 4, "height": 4})).unwrap(); + app.run("edit.fill", json!({"color": color})).unwrap(); +} + +fn autosave(app: &mut PhotocraftApp, ctx: &egui::Context) { + prefs_ui::autosave_now(app); + prefs_ui::tick(app, ctx); +} + +#[test] +fn recovered_documents_survive_a_second_crash_until_saved_or_closed() { + let dir = std::env::temp_dir().join(format!("photocraft-recovery-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let ctx = egui::Context::default(); + // Launch 1: two unsaved documents are autosaved, then the app crashes. + { + let mut app = launch(&dir); + new_doc(&mut app, "#ff0000"); + new_doc(&mut app, "#0000ff"); + autosave(&mut app, &ctx); + } + assert_eq!(list_recovery(&dir).len(), 2); + // Launch 2 recovers both and crashes again before its first autosave (#444). + { + let mut app = launch(&dir); + let mut docs = open_docs(&app); + docs.sort_by(|a, b| a.0[0].total_cmp(&b.0[0])); + assert_eq!(docs, [(BLUE, true), (RED, true)], "recovered and still unsaved"); + prefs_ui::tick(&mut app, &ctx); + } + assert_eq!(list_recovery(&dir).len(), 2, "recovering keeps the entries on disk"); + // Launch 3 has both again; autosaving unchanged documents adds nothing, a new document + // (whose id may repeat one from an earlier launch) gets an entry of its own. + { + let mut app = launch(&dir); + assert_eq!(app.session.documents().len(), 2); + autosave(&mut app, &ctx); + new_doc(&mut app, "#00ff00"); + autosave(&mut app, &ctx); + } + assert_eq!(list_recovery(&dir).len(), 3); + // Launch 4: closing and saving recovered documents removes their entries, no duplicates. + let mut app = launch(&dir); + assert_eq!(app.session.documents().len(), 3); + let red = index_of(&app, RED); + app.run("file.close", json!({"document": red})).unwrap(); + // Saving marks the revision saved (the file write itself is the save service's job). + assert!(app.session.set_active(index_of(&app, BLUE))); + let st = app.session.active_mut().unwrap(); + st.saved_revision = st.revision; + prefs_ui::tick(&mut app, &ctx); + let left = list_recovery(&dir); + assert_eq!(left.len(), 1); + assert_eq!(photocraft_compose::flatten(&photocraft_format::recover(&left[0]).unwrap()).px.first().copied(), Some(GREEN)); + let green = index_of(&app, GREEN); + app.run("file.close", json!({"document": green})).unwrap(); + prefs_ui::tick(&mut app, &ctx); + assert!(list_recovery(&dir).is_empty()); + drop(app); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn failed_background_autosave_is_reported_and_retried_without_another_edit() { + let dir = temp("autosave-retry"); + let recovery = dir.join("Recovery"); + // A regular file prevents creation of the recovery bundle directory. + std::fs::write(&recovery, b"blocked").unwrap(); + let ctx = egui::Context::default(); + let mut app = launch(&recovery); + new_doc(&mut app, "#ff0000"); + let revision = app.session.active().unwrap().revision; + assert_ne!(revision, 0, "a sidecar-less bundle lists as revision 0"); + autosave(&mut app, &ctx); + + let mut failed = false; + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); + while std::time::Instant::now() < deadline { + prefs_ui::tick(&mut app, &ctx); + if app.ui.status.starts_with("Autosave failed:") { + failed = true; + break; + } + std::thread::sleep(std::time::Duration::from_millis(10)); + } + assert!(failed, "background write failures must reach the UI"); + assert!(app.ui.status_error); + assert!(list_recovery(&recovery).is_empty()); + + // No edit occurs: retrying this very same revision must still work. + std::fs::remove_file(&recovery).unwrap(); + std::fs::create_dir(&recovery).unwrap(); + autosave(&mut app, &ctx); + // The worker commits the bundle's manifest before it publishes the sidecar, and + // `list_recovery` lists a committed sidecar-less bundle (revision 0) on its own, so + // the first non-empty listing can come from the middle of the write. Wait for the write + // to finish: the entry then carries the sidecar's revision. + let mut recovered = Vec::new(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); + while std::time::Instant::now() < deadline { + prefs_ui::tick(&mut app, &ctx); + recovered = list_recovery(&recovery); + if recovered.iter().any(|e| e.info.revision == revision) { + break; + } + std::thread::sleep(std::time::Duration::from_millis(10)); + } + assert_eq!(recovered.len(), 1, "unchanged revision should retry after failure"); + assert_eq!(recovered[0].info.revision, revision); + let restored = photocraft_format::recover(&recovered[0]).unwrap(); + assert_eq!(photocraft_compose::flatten(&restored).px.first().copied(), Some(RED)); + drop(app); + std::fs::remove_dir_all(dir).unwrap(); +} + +use std::sync::atomic::{AtomicUsize, Ordering}; + +fn temp(tag: &str) -> PathBuf { + static N: AtomicUsize = AtomicUsize::new(0); + let d = std::env::temp_dir().join(format!("photocraft-services-{tag}-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed))); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d +} + +fn red_png(w: u32, h: u32) -> Vec { + let img = Image::from_u8(w, h, ChannelLayout::Rgba, [255u8, 0, 0, 255].repeat((w * h) as usize)).unwrap(); + photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &EncodeOptions::default()).unwrap() +} + +/// A 1×1 uncompressed 32-bit TGA (TGA has no magic number). +fn tga_1x1() -> Vec { + let mut b = vec![0u8, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 32, 8]; + b.extend_from_slice(&[0, 0, 255, 255]); // BGRA red + b +} + +#[test] +fn copied_image_file_pastes_its_pixels() { + let dir = temp("png"); + let png = dir.join("red.png"); + std::fs::write(&png, red_png(3, 2)).unwrap(); + let (w, h, px) = image_from_files(&[png]).unwrap(); + assert_eq!((w, h), (3, 2)); + assert_eq!(px, [255u8, 0, 0, 255].repeat(6)); +} + +#[test] +fn crlf_from_a_uri_list_is_ignored() { + // arboard splits text/uri-list on LF, so GNOME Files' CRLF list leaves a '\r' behind. + let dir = temp("crlf"); + let png = dir.join("red image.png"); + std::fs::write(&png, red_png(2, 2)).unwrap(); + let with_cr = PathBuf::from(format!("{}\r", png.display())); + assert_eq!(image_from_files(&[with_cr]).map(|(w, h, _)| (w, h)), Some((2, 2))); +} + +#[test] +fn non_images_are_skipped_for_the_first_image() { + let dir = temp("mixed"); + let (txt, png) = (dir.join("notes.txt"), dir.join("red.png")); + std::fs::write(&txt, b"not an image").unwrap(); + std::fs::write(&png, red_png(4, 1)).unwrap(); + let missing = dir.join("gone.png"); + assert_eq!(image_from_files(&[missing.clone(), txt.clone(), dir.clone(), png]).map(|(w, h, _)| (w, h)), Some((4, 1))); + assert!(image_from_files(&[missing, txt, dir]).is_none()); + assert!(image_from_files(&[]).is_none()); +} + +#[test] +fn a_damaged_image_is_skipped_not_a_panic() { + let dir = temp("damaged"); + let bad = dir.join("cut.png"); + std::fs::write(&bad, &red_png(8, 8)[..20]).unwrap(); + assert!(image_from_files(&[bad]).is_none()); +} + +fn encoded(format: photocraft_codecs::Format, w: u32, h: u32) -> Vec { + let img = Image::from_u8(w, h, ChannelLayout::Rgba, [255u8, 0, 0, 255].repeat((w * h) as usize)).unwrap(); + photocraft_codecs::encode(&img, format, &EncodeOptions::default()).unwrap() +} + +#[test] +fn non_png_clipboard_images_paste() { + // #2546: a screenshot tool that offers only image/bmp or image/jpeg pasted nothing. + let bmp = encoded(photocraft_codecs::Format::Bmp, 3, 2); + let offers = vec!["text/plain".to_string(), "image/bmp".to_string()]; + let mut asked = Vec::new(); + let got = image_from_offers(&offers, |mime| { + asked.push(mime.to_string()); + Some(bmp.clone()) + }); + assert_eq!(got, Some((3, 2, [255u8, 0, 0, 255].repeat(6)))); + assert_eq!(asked, ["image/bmp"], "text offers are never fetched"); + + let jpeg = encoded(photocraft_codecs::Format::Jpeg, 16, 8); + let offers = vec!["image/jpeg".to_string()]; + assert_eq!(image_from_offers(&offers, |_| Some(jpeg.clone())).map(|(w, h, _)| (w, h)), Some((16, 8))); +} + +#[test] +fn undecodable_clipboard_offers_fall_through_to_the_next() { + let bmp = encoded(photocraft_codecs::Format::Bmp, 2, 2); + let cut = encoded(photocraft_codecs::Format::Png, 8, 8)[..20].to_vec(); + let offers: Vec = ["image/webp", "image/png", "image/x-tga", "image/bmp"].map(String::from).to_vec(); + let got = image_from_offers(&offers, |mime| match mime { + "image/webp" => None, + "image/png" => Some(cut.clone()), + "image/x-tga" => Some(b"not an image".to_vec()), + _ => Some(bmp.clone()), + }); + assert_eq!(got.map(|(w, h, _)| (w, h)), Some((2, 2))); + assert!(image_from_offers(&offers[..3], |_| Some(cut.clone())).is_none()); + assert!(image_from_offers(&[], |_| Some(bmp.clone())).is_none()); +} + +#[test] +fn clipboard_tga_is_trusted_only_by_its_type() { + assert_eq!(image_from_offers(&["image/x-tga".to_string()], |_| Some(tga_1x1())), Some((1, 1, vec![255, 0, 0, 255]))); + assert!(image_from_offers(&["image/x-unknown".to_string()], |_| Some(tga_1x1())).is_none()); +} + +#[test] +fn tga_is_trusted_only_with_its_extension() { + let dir = temp("tga"); + let (tga, bin) = (dir.join("red.tga"), dir.join("red.bin")); + std::fs::write(&tga, tga_1x1()).unwrap(); + std::fs::write(&bin, tga_1x1()).unwrap(); + assert_eq!(image_from_files(&[tga]), Some((1, 1, vec![255, 0, 0, 255]))); + assert!(image_from_files(&[bin]).is_none()); +} + +/// #7582: a panic while reading the OS clipboard (in arboard, or decoding a copied file) is +/// the paste's error in the status bar, not a crash: the document stays and the next paste +/// works. The same for a panic while writing it. +#[test] +fn a_panicking_clipboard_read_is_reported_not_a_crash() { + let panics = Rc::new(Cell::new(true)); + let p = panics.clone(); + let get = guarded_clipboard_get(move || if p.get() { panic!("clipboard decoder bug") } else { Ok(Some((2, 2, [0u8, 0, 255, 255].repeat(4)))) }); + let mut app = PhotocraftApp::new(Session::new(), Services { clipboard_get_image: Some(get), ..Default::default() }); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + let layers = app.session.active().unwrap().doc.layers.len(); + + let error = app.run("edit.paste", json!({})).unwrap_err(); + assert!(error.contains("Paste failed"), "{error}"); + assert!(app.ui.status_error && app.ui.status.contains("Paste failed"), "{}", app.ui.status); + assert_eq!(app.session.active().unwrap().doc.layers.len(), layers, "the document is unchanged"); + + panics.set(false); + app.run("edit.paste", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().doc.layers.len(), layers + 1, "the next paste works"); + + let mut set = guarded_clipboard_set(|_: u32, _: u32, _: &[u8]| panic!("clipboard writer bug")); + assert!(set(1, 1, &[0; 4]).unwrap_err().contains("Copy failed")); +} diff --git a/apps/photocraft/src/single_instance.rs b/apps/photocraft/src/single_instance.rs index b193cade68..4d836adc90 100644 --- a/apps/photocraft/src/single_instance.rs +++ b/apps/photocraft/src/single_instance.rs @@ -627,378 +627,4 @@ pub fn absolute(path: &str) -> String { } #[cfg(test)] -mod tests { - use super::*; - use std::path::PathBuf; - use std::sync::mpsc::channel; - - const FAST: Timing = Timing { handoff: Duration::from_millis(1500), ack: Duration::from_millis(500), request: Duration::from_millis(800) }; - - fn temp_dir(name: &str) -> PathBuf { - let dir = std::env::temp_dir().join(format!("photocraft-single-instance-{name}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - dir - } - - /// Launch with `paths` on another thread (it blocks until the primary's UI takes them). - fn launch(dir: &Path, paths: &[&str], timing: Timing) -> std::thread::JoinHandle { - let (dir, paths): (PathBuf, Vec) = (dir.to_path_buf(), paths.iter().map(|p| p.to_string()).collect()); - std::thread::spawn(move || claim_with(&dir, &paths, timing)) - } - - /// Play the UI: drain until `n` events arrived (or 5 s passed). - fn drain(ui: &mut OsEventsFn, n: usize) -> Vec { - let mut got = Vec::new(); - let deadline = Instant::now() + Duration::from_secs(5); - while got.len() < n && Instant::now() < deadline { - got.extend(ui()); - std::thread::sleep(Duration::from_millis(10)); - } - got - } - - fn primary(dir: &Path) -> Primary { - match claim_with(dir, &[], FAST) { - Launch::Primary(p) => p, - _ => panic!("first launch should be primary"), - } - } - - /// A socket path short enough for every Unix (`sun_path` is about 100 bytes; macOS: 104). - #[cfg(unix)] - fn short_socket_path(tag: &str) -> PathBuf { - std::env::temp_dir().join(format!("pc-si-{}-{tag}", std::process::id())).join(SOCKET_FILE) - } - - /// The loopback port the primary under `dir` listens on. - fn port_of(dir: &Path) -> u16 { - match read_info(dir).unwrap().0 { - Endpoint::Port(port) => port, - #[cfg(unix)] - Endpoint::Socket(path) => panic!("expected a loopback port, found {}", path.display()), - } - } - - #[test] - fn second_launch_hands_its_paths_to_the_first() { - let dir = temp_dir("handoff"); - let primary = primary(&dir); - let mut ui = primary.connect(&egui::Context::default()); - let paths = ["C:\\art\\one.psd", "/home/a/two é.png"]; - let second = launch(&dir, &paths, TIMING); - assert_eq!(drain(&mut ui, 1), vec![OsEvent::Open(paths.iter().map(|p| p.to_string()).collect())]); - assert!(matches!(second.join().unwrap(), Launch::Forwarded)); - // A plain second start (no files) just brings the window forward. - let third = launch(&dir, &[], TIMING); - assert_eq!(drain(&mut ui, 1), vec![OsEvent::Open(Vec::new())]); - assert!(matches!(third.join().unwrap(), Launch::Forwarded)); - drop(primary); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn simultaneous_launches_all_land_in_one_instance() { - let dir = temp_dir("race"); - let (tx, rx) = channel(); - for i in 0..6 { - let (dir, tx) = (dir.clone(), tx.clone()); - std::thread::spawn(move || { - let _ = tx.send(claim(&dir, &[format!("file{i}.psd")])); - }); - } - drop(tx); - let (mut primaries, mut forwarded, mut events) = (Vec::new(), 0, Vec::new()); - let mut ui: Option = None; - let deadline = Instant::now() + Duration::from_secs(10); - while primaries.len() + forwarded < 6 && Instant::now() < deadline { - while let Ok(launch) = rx.try_recv() { - match launch { - Launch::Primary(p) => primaries.push(p), - Launch::Forwarded => forwarded += 1, - Launch::Standalone(reason) => panic!("standalone: {reason}"), - } - } - if ui.is_none() - && let Some(p) = primaries.first() - { - ui = Some(p.connect(&egui::Context::default())); - } - if let Some(ui) = ui.as_mut() { - events.extend(ui()); - } - std::thread::sleep(Duration::from_millis(10)); - } - assert_eq!((primaries.len(), forwarded, events.len()), (1, 5, 5)); - drop(primaries); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn a_crashed_instance_leaves_nothing_in_the_way() { - let dir = temp_dir("stale"); - std::fs::create_dir_all(&dir).unwrap(); - // instance.json from a process that is gone; the lock is free. - std::fs::write(dir.join(INFO_FILE), r#"{"port":1,"token":"x","pid":1}"#).unwrap(); - let primary = primary(&dir); - assert!(read_info(&dir).is_some_and(|(endpoint, _)| endpoint != Endpoint::Port(1))); - drop(primary); - // Released with the handle, as on process exit. - assert!(matches!(claim_with(&dir, &[], FAST), Launch::Primary(_))); - let _ = std::fs::remove_dir_all(&dir); - } - - /// Review of #3755, point 1 (and the quitting half of point 3): a launch waiting on a primary - /// that shuts down (closing, or about to relaunch itself in CPU mode) isn't told `ok`; it takes - /// the lock over and opens the file itself. - #[test] - fn a_launch_waiting_on_a_closing_instance_takes_over() { - let dir = temp_dir("closing"); - let primary = primary(&dir); - // The UI never drains (it is shutting down, or never came up). - let waiting = launch(&dir, &["a.psd"], FAST); - std::thread::sleep(Duration::from_millis(200)); - primary.shutdown(); - assert!(matches!(waiting.join().unwrap(), Launch::Primary(_)), "the waiting launch becomes the primary"); - // After shutdown new connections are refused too. - let (endpoint, token) = read_info(&dir).unwrap(); - drop(primary); - let short = Instant::now() + Duration::from_millis(300); - assert!(send(&endpoint, &token, &["b.psd".into()], short).is_err()); - let _ = std::fs::remove_dir_all(&dir); - } - - /// Review of #3755, point 3: a primary whose UI never takes the paths (hung) doesn't - /// acknowledge them, and doesn't keep them queued to open later as well. - #[test] - fn a_hung_instance_never_swallows_a_file() { - let dir = temp_dir("hung-ui"); - let primary = primary(&dir); - let mut ui = primary.connect(&egui::Context::default()); - let started = Instant::now(); - assert!(matches!(claim_with(&dir, &["a.psd".into()], FAST), Launch::Standalone(_))); - assert!(started.elapsed() < FAST.handoff + Duration::from_secs(1), "{:?}", started.elapsed()); - assert!(ui().is_empty(), "withdrawn, not opened later"); - drop(primary); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn requests_without_the_token_or_malformed_are_rejected() { - let token = generate_token().unwrap(); - let ok = parse_request(&json!({"token": token, "open": ["a"], "wait_ms": 250}).to_string(), &token); - assert_eq!(ok, Some((vec!["a".to_string()], Duration::from_millis(250)))); - let wrong = generate_token().unwrap(); - assert_eq!(parse_request(&json!({"token": wrong, "open": ["a"]}).to_string(), &token), None); - for bad in ["", "not json", "{}", r#"{"token":5}"#, &json!({"token": token}).to_string(), &json!({"token": token, "open": [1]}).to_string()] { - assert_eq!(parse_request(bad, &token), None, "{bad:?}"); - } - let many: Vec = (0..=MAX_PATHS).map(|i| i.to_string()).collect(); - assert_eq!(parse_request(&json!({"token": token, "open": many}).to_string(), &token), None); - } - - #[test] - fn a_stalled_client_does_not_hold_up_the_next_launch() { - let dir = temp_dir("stalled"); - let primary = primary(&dir); - let mut ui = primary.connect(&egui::Context::default()); - let port = port_of(&dir); - // Connects and never sends a line (each would otherwise hold the listener). - let stalled: Vec = (0..3).map(|_| TcpStream::connect((Ipv4Addr::LOCALHOST, port)).unwrap()).collect(); - let started = Instant::now(); - let next = launch(&dir, &["b.psd"], FAST); - assert_eq!(drain(&mut ui, 1), vec![OsEvent::Open(vec!["b.psd".into()])]); - assert!(matches!(next.join().unwrap(), Launch::Forwarded)); - assert!(started.elapsed() < FAST.request, "took {:?}", started.elapsed()); - drop(stalled); - drop(primary); - let _ = std::fs::remove_dir_all(&dir); - } - - /// A client that trickles a byte at a time can't keep its slot past the request deadline. - #[test] - fn a_trickling_client_is_cut_off_at_the_request_deadline() { - let dir = temp_dir("trickle"); - let primary = primary(&dir); - let port = port_of(&dir); - let mut slow = TcpStream::connect((Ipv4Addr::LOCALHOST, port)).unwrap(); - let started = Instant::now(); - let mut cut_off = false; - while started.elapsed() < FAST.request * 4 { - if slow.write_all(b"{").is_err() { - cut_off = true; - break; - } - std::thread::sleep(Duration::from_millis(100)); - } - assert!(cut_off, "still connected after {:?}", started.elapsed()); - assert!(started.elapsed() < FAST.request * 3, "{:?}", started.elapsed()); - drop(primary); - let _ = std::fs::remove_dir_all(&dir); - } - - #[cfg(unix)] - #[test] - fn the_token_file_is_private_to_the_user() { - use std::os::unix::fs::PermissionsExt; - let dir = temp_dir("mode"); - std::fs::create_dir_all(&dir).unwrap(); - // A wide leftover temporary file from a crashed start doesn't widen the new one. - let tmp = dir.join(format!("{INFO_FILE}.{}.tmp", std::process::id())); - std::fs::write(&tmp, "{}").unwrap(); - std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o644)).unwrap(); - write_info(&dir, &Endpoint::Port(1), &generate_token().unwrap()).unwrap(); - let mode = std::fs::metadata(dir.join(INFO_FILE)).unwrap().permissions().mode() & 0o777; - assert_eq!(mode, 0o600); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn an_unreachable_instance_falls_back_to_a_standalone_launch() { - let dir = temp_dir("unreachable"); - std::fs::create_dir_all(&dir).unwrap(); - // Someone holds the lock but nothing listens on the advertised port. - let held = File::create(dir.join(LOCK_FILE)).unwrap(); - held.lock().unwrap(); - let closed = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap().local_addr().unwrap().port(); - write_info(&dir, &Endpoint::Port(closed), &generate_token().unwrap()).unwrap(); - assert!(matches!(claim_with(&dir, &["a.psd".into()], FAST), Launch::Standalone(_))); - drop(held); - let _ = std::fs::remove_dir_all(&dir); - } - - /// Review of #3755, point 2 and the smaller points: who takes part in single-instance. - #[test] - fn only_per_user_launches_without_process_options_take_part() { - let base = LaunchContext { - per_user_settings: true, - new_instance_flag: false, - new_instance_env: None, - control: false, - unreadable_paths: false, - launch_options: &[], - }; - assert_eq!(skip_reason(&base), None); - // A portable copy's folder or a PHOTOCRAFT_CONFIG_DIR may be shared between users. - assert!(skip_reason(&LaunchContext { per_user_settings: false, ..base }).is_some()); - assert!(skip_reason(&LaunchContext { new_instance_flag: true, ..base }).is_some()); - assert!(skip_reason(&LaunchContext { new_instance_env: Some("1"), ..base }).is_some()); - assert_eq!(skip_reason(&LaunchContext { new_instance_env: Some("0"), ..base }), None); - assert_eq!(skip_reason(&LaunchContext { new_instance_env: Some(""), ..base }), None); - assert!(skip_reason(&LaunchContext { control: true, ..base }).is_some()); - assert!(skip_reason(&LaunchContext { unreadable_paths: true, ..base }).is_some()); - let reason = skip_reason(&LaunchContext { launch_options: &[PerProcess::SafeGpu, PerProcess::GpuAdapterEnv], ..base }); - assert_eq!(reason.as_deref(), Some("--safe-gpu, PHOTOCRAFT_GPU_ADAPTER only applies to a new process")); - } - - /// #1540: inside a Flatpak sandbox the hand-off runs over a Unix socket in the app's runtime - /// directory, which every sandbox of the app shares, with the same lock, token and reply. - #[cfg(unix)] - #[test] - fn a_sandboxed_second_launch_hands_its_paths_over_a_unix_socket() { - use std::os::unix::fs::PermissionsExt; - let dir = temp_dir("socket"); - // Short: a Unix socket path is limited to about 100 bytes (macOS: 104). - let socket = short_socket_path("a"); - let transport = Transport::Socket(socket.clone()); - let primary = match claim_in(&dir, &[], FAST, &transport) { - Launch::Primary(p) => p, - _ => panic!("first launch should be primary"), - }; - assert_eq!(std::fs::metadata(&socket).unwrap().permissions().mode() & 0o777, 0o600); - let info: Value = serde_json::from_slice(&std::fs::read(dir.join(INFO_FILE)).unwrap()).unwrap(); - assert_eq!(info.get("socket").and_then(Value::as_str), Some(socket.to_str().unwrap())); - assert!(info.get("port").is_none()); - let mut ui = primary.connect(&egui::Context::default()); - let paths = ["/home/a/one.psd".to_string()]; - let (d, p, t) = (dir.clone(), paths.clone(), transport.clone()); - let second = std::thread::spawn(move || claim_in(&d, &p, TIMING, &t)); - assert_eq!(drain(&mut ui, 1), vec![OsEvent::Open(paths.to_vec())]); - assert!(matches!(second.join().unwrap(), Launch::Forwarded)); - // The token still gates the socket. - let (endpoint, _) = read_info(&dir).unwrap(); - assert!(send(&endpoint, "not the token", &["x.psd".into()], Instant::now() + FAST.handoff).is_err()); - primary.shutdown(); - assert!(!socket.exists(), "shutdown removes the socket file"); - // The next primary binds the same path; the old one's drop (a second shutdown) must leave it. - let next = match claim_in(&dir, &[], FAST, &transport) { - Launch::Primary(p) => p, - _ => panic!("the lock is free again"), - }; - drop(primary); - assert!(socket.exists(), "a second shutdown doesn't remove the next primary's socket"); - drop(next); - let _ = std::fs::remove_dir_all(&dir); - } - - /// A socket file left by a crashed primary (and a stale `instance.json` naming it) is replaced. - #[cfg(unix)] - #[test] - fn a_crashed_primary_s_socket_file_does_not_block_the_next_one() { - use std::os::unix::fs::FileTypeExt; - let dir = temp_dir("stale-socket"); - let socket = short_socket_path("b"); - std::fs::create_dir_all(&dir).unwrap(); - std::fs::create_dir_all(socket.parent().unwrap()).unwrap(); - std::fs::write(&socket, b"not a socket").unwrap(); - write_info(&dir, &Endpoint::Socket(socket.clone()), &generate_token().unwrap()).unwrap(); - let primary = match claim_in(&dir, &["a.psd".into()], FAST, &Transport::Socket(socket.clone())) { - Launch::Primary(p) => p, - Launch::Forwarded => panic!("nothing was listening"), - Launch::Standalone(e) => panic!("{e}"), - }; - assert!(std::fs::metadata(&socket).unwrap().file_type().is_socket()); - drop(primary); - let _ = std::fs::remove_dir_all(&dir); - let _ = std::fs::remove_dir_all(socket.parent().unwrap()); - } - - /// The socket transport is chosen only inside a Flatpak with a runtime directory. - #[cfg(unix)] - #[test] - fn the_socket_transport_needs_a_flatpak_id_and_a_runtime_directory() { - use std::ffi::OsStr; - let (id, run) = (OsStr::new("ai.storyteller.photocraft"), OsStr::new("/run/user/1000")); - assert_eq!(sandbox_socket(Some(id), Some(run)), Some(PathBuf::from("/run/user/1000/app/ai.storyteller.photocraft/instance.sock"))); - assert_eq!(sandbox_socket(None, Some(run)), None); - assert_eq!(sandbox_socket(Some(id), None), None); - assert_eq!(sandbox_socket(Some(OsStr::new("")), Some(run)), None); - assert_eq!(sandbox_socket(Some(id), Some(OsStr::new(""))), None); - } - - /// A variable documented as the equivalent of a per-launch flag counts as that flag: a launch - /// that sets only variables has per-process options, so it keeps its own process rather than - /// handing its files to the running instance, which never sees the override. - #[test] - fn an_environment_override_counts_as_a_process_option() { - let with = |values: &[(&str, &str)]| env_launch_options_from(|n| values.iter().find(|(k, _)| *k == n).map(|(_, v)| (*v).into())); - assert_eq!(with(&[("PHOTOCRAFT_PRESENT_MODE", "novsync")]), vec![PerProcess::PresentMode]); - assert_eq!( - with(&[("PHOTOCRAFT_STROKE_TRACE", "strokes.csv"), ("PHOTOCRAFT_FRAME_LATENCY", "2")]), - vec![PerProcess::FrameLatency, PerProcess::StrokeTrace] - ); - // Nothing set, or a value that means off, is an ordinary launch. Each variable is off the way - // it is read where it takes effect, not by one rule shared across all three. - assert!(with(&[]).is_empty()); - assert!(with(&[("PHOTOCRAFT_FRAME_LATENCY", "")]).is_empty()); - // The trace is off at `off` and `false` as well, and a value the presentation parser rejects - // is ignored there, so neither keeps a process of its own here. - assert!(with(&[("PHOTOCRAFT_STROKE_TRACE", "off"), ("PHOTOCRAFT_PRESENT_MODE", "maybe"), ("PHOTOCRAFT_FRAME_LATENCY", "4")]).is_empty()); - // The trace and the two presentation values are trimmed where they take effect. - assert_eq!( - with(&[("PHOTOCRAFT_PRESENT_MODE", " novsync "), ("PHOTOCRAFT_STROKE_TRACE", " 1 ")]), - vec![PerProcess::PresentMode, PerProcess::StrokeTrace] - ); - // The menus and the automation roots are flags' fallbacks: `launch_args::parse` counts them. - assert!(with(&[("PHOTOCRAFT_IN_WINDOW_MENUS", "1"), ("PHOTOCRAFT_AUTOMATION_WRITE_ROOT", "/tmp/out")]).is_empty()); - let base = LaunchContext { - per_user_settings: true, - new_instance_flag: false, - new_instance_env: None, - control: false, - unreadable_paths: false, - launch_options: &[], - }; - let reason = skip_reason(&LaunchContext { launch_options: &with(&[("PHOTOCRAFT_PRESENT_MODE", "novsync")]), ..base }); - assert!(reason.as_deref().is_some_and(|r| r.contains("--present-mode")), "{reason:?}"); - } -} +mod tests; diff --git a/apps/photocraft/src/single_instance/tests.rs b/apps/photocraft/src/single_instance/tests.rs new file mode 100644 index 0000000000..dc5755719f --- /dev/null +++ b/apps/photocraft/src/single_instance/tests.rs @@ -0,0 +1,367 @@ +use super::*; +use std::path::PathBuf; +use std::sync::mpsc::channel; + +const FAST: Timing = Timing { handoff: Duration::from_millis(1500), ack: Duration::from_millis(500), request: Duration::from_millis(800) }; + +fn temp_dir(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("photocraft-single-instance-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + dir +} + +/// Launch with `paths` on another thread (it blocks until the primary's UI takes them). +fn launch(dir: &Path, paths: &[&str], timing: Timing) -> std::thread::JoinHandle { + let (dir, paths): (PathBuf, Vec) = (dir.to_path_buf(), paths.iter().map(|p| p.to_string()).collect()); + std::thread::spawn(move || claim_with(&dir, &paths, timing)) +} + +/// Play the UI: drain until `n` events arrived (or 5 s passed). +fn drain(ui: &mut OsEventsFn, n: usize) -> Vec { + let mut got = Vec::new(); + let deadline = Instant::now() + Duration::from_secs(5); + while got.len() < n && Instant::now() < deadline { + got.extend(ui()); + std::thread::sleep(Duration::from_millis(10)); + } + got +} + +fn primary(dir: &Path) -> Primary { + match claim_with(dir, &[], FAST) { + Launch::Primary(p) => p, + _ => panic!("first launch should be primary"), + } +} + +/// A socket path short enough for every Unix (`sun_path` is about 100 bytes; macOS: 104). +#[cfg(unix)] +fn short_socket_path(tag: &str) -> PathBuf { + std::env::temp_dir().join(format!("pc-si-{}-{tag}", std::process::id())).join(SOCKET_FILE) +} + +/// The loopback port the primary under `dir` listens on. +fn port_of(dir: &Path) -> u16 { + match read_info(dir).unwrap().0 { + Endpoint::Port(port) => port, + #[cfg(unix)] + Endpoint::Socket(path) => panic!("expected a loopback port, found {}", path.display()), + } +} + +#[test] +fn second_launch_hands_its_paths_to_the_first() { + let dir = temp_dir("handoff"); + let primary = primary(&dir); + let mut ui = primary.connect(&egui::Context::default()); + let paths = ["C:\\art\\one.psd", "/home/a/two é.png"]; + let second = launch(&dir, &paths, TIMING); + assert_eq!(drain(&mut ui, 1), vec![OsEvent::Open(paths.iter().map(|p| p.to_string()).collect())]); + assert!(matches!(second.join().unwrap(), Launch::Forwarded)); + // A plain second start (no files) just brings the window forward. + let third = launch(&dir, &[], TIMING); + assert_eq!(drain(&mut ui, 1), vec![OsEvent::Open(Vec::new())]); + assert!(matches!(third.join().unwrap(), Launch::Forwarded)); + drop(primary); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn simultaneous_launches_all_land_in_one_instance() { + let dir = temp_dir("race"); + let (tx, rx) = channel(); + for i in 0..6 { + let (dir, tx) = (dir.clone(), tx.clone()); + std::thread::spawn(move || { + let _ = tx.send(claim(&dir, &[format!("file{i}.psd")])); + }); + } + drop(tx); + let (mut primaries, mut forwarded, mut events) = (Vec::new(), 0, Vec::new()); + let mut ui: Option = None; + let deadline = Instant::now() + Duration::from_secs(10); + while primaries.len() + forwarded < 6 && Instant::now() < deadline { + while let Ok(launch) = rx.try_recv() { + match launch { + Launch::Primary(p) => primaries.push(p), + Launch::Forwarded => forwarded += 1, + Launch::Standalone(reason) => panic!("standalone: {reason}"), + } + } + if ui.is_none() + && let Some(p) = primaries.first() + { + ui = Some(p.connect(&egui::Context::default())); + } + if let Some(ui) = ui.as_mut() { + events.extend(ui()); + } + std::thread::sleep(Duration::from_millis(10)); + } + assert_eq!((primaries.len(), forwarded, events.len()), (1, 5, 5)); + drop(primaries); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_crashed_instance_leaves_nothing_in_the_way() { + let dir = temp_dir("stale"); + std::fs::create_dir_all(&dir).unwrap(); + // instance.json from a process that is gone; the lock is free. + std::fs::write(dir.join(INFO_FILE), r#"{"port":1,"token":"x","pid":1}"#).unwrap(); + let primary = primary(&dir); + assert!(read_info(&dir).is_some_and(|(endpoint, _)| endpoint != Endpoint::Port(1))); + drop(primary); + // Released with the handle, as on process exit. + assert!(matches!(claim_with(&dir, &[], FAST), Launch::Primary(_))); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Review of #3755, point 1 (and the quitting half of point 3): a launch waiting on a primary +/// that shuts down (closing, or about to relaunch itself in CPU mode) isn't told `ok`; it takes +/// the lock over and opens the file itself. +#[test] +fn a_launch_waiting_on_a_closing_instance_takes_over() { + let dir = temp_dir("closing"); + let primary = primary(&dir); + // The UI never drains (it is shutting down, or never came up). + let waiting = launch(&dir, &["a.psd"], FAST); + std::thread::sleep(Duration::from_millis(200)); + primary.shutdown(); + assert!(matches!(waiting.join().unwrap(), Launch::Primary(_)), "the waiting launch becomes the primary"); + // After shutdown new connections are refused too. + let (endpoint, token) = read_info(&dir).unwrap(); + drop(primary); + let short = Instant::now() + Duration::from_millis(300); + assert!(send(&endpoint, &token, &["b.psd".into()], short).is_err()); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Review of #3755, point 3: a primary whose UI never takes the paths (hung) doesn't +/// acknowledge them, and doesn't keep them queued to open later as well. +#[test] +fn a_hung_instance_never_swallows_a_file() { + let dir = temp_dir("hung-ui"); + let primary = primary(&dir); + let mut ui = primary.connect(&egui::Context::default()); + let started = Instant::now(); + assert!(matches!(claim_with(&dir, &["a.psd".into()], FAST), Launch::Standalone(_))); + assert!(started.elapsed() < FAST.handoff + Duration::from_secs(1), "{:?}", started.elapsed()); + assert!(ui().is_empty(), "withdrawn, not opened later"); + drop(primary); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn requests_without_the_token_or_malformed_are_rejected() { + let token = generate_token().unwrap(); + let ok = parse_request(&json!({"token": token, "open": ["a"], "wait_ms": 250}).to_string(), &token); + assert_eq!(ok, Some((vec!["a".to_string()], Duration::from_millis(250)))); + let wrong = generate_token().unwrap(); + assert_eq!(parse_request(&json!({"token": wrong, "open": ["a"]}).to_string(), &token), None); + for bad in ["", "not json", "{}", r#"{"token":5}"#, &json!({"token": token}).to_string(), &json!({"token": token, "open": [1]}).to_string()] { + assert_eq!(parse_request(bad, &token), None, "{bad:?}"); + } + let many: Vec = (0..=MAX_PATHS).map(|i| i.to_string()).collect(); + assert_eq!(parse_request(&json!({"token": token, "open": many}).to_string(), &token), None); +} + +#[test] +fn a_stalled_client_does_not_hold_up_the_next_launch() { + let dir = temp_dir("stalled"); + let primary = primary(&dir); + let mut ui = primary.connect(&egui::Context::default()); + let port = port_of(&dir); + // Connects and never sends a line (each would otherwise hold the listener). + let stalled: Vec = (0..3).map(|_| TcpStream::connect((Ipv4Addr::LOCALHOST, port)).unwrap()).collect(); + let started = Instant::now(); + let next = launch(&dir, &["b.psd"], FAST); + assert_eq!(drain(&mut ui, 1), vec![OsEvent::Open(vec!["b.psd".into()])]); + assert!(matches!(next.join().unwrap(), Launch::Forwarded)); + assert!(started.elapsed() < FAST.request, "took {:?}", started.elapsed()); + drop(stalled); + drop(primary); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A client that trickles a byte at a time can't keep its slot past the request deadline. +#[test] +fn a_trickling_client_is_cut_off_at_the_request_deadline() { + let dir = temp_dir("trickle"); + let primary = primary(&dir); + let port = port_of(&dir); + let mut slow = TcpStream::connect((Ipv4Addr::LOCALHOST, port)).unwrap(); + let started = Instant::now(); + let mut cut_off = false; + while started.elapsed() < FAST.request * 4 { + if slow.write_all(b"{").is_err() { + cut_off = true; + break; + } + std::thread::sleep(Duration::from_millis(100)); + } + assert!(cut_off, "still connected after {:?}", started.elapsed()); + assert!(started.elapsed() < FAST.request * 3, "{:?}", started.elapsed()); + drop(primary); + let _ = std::fs::remove_dir_all(&dir); +} + +#[cfg(unix)] +#[test] +fn the_token_file_is_private_to_the_user() { + use std::os::unix::fs::PermissionsExt; + let dir = temp_dir("mode"); + std::fs::create_dir_all(&dir).unwrap(); + // A wide leftover temporary file from a crashed start doesn't widen the new one. + let tmp = dir.join(format!("{INFO_FILE}.{}.tmp", std::process::id())); + std::fs::write(&tmp, "{}").unwrap(); + std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o644)).unwrap(); + write_info(&dir, &Endpoint::Port(1), &generate_token().unwrap()).unwrap(); + let mode = std::fs::metadata(dir.join(INFO_FILE)).unwrap().permissions().mode() & 0o777; + assert_eq!(mode, 0o600); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn an_unreachable_instance_falls_back_to_a_standalone_launch() { + let dir = temp_dir("unreachable"); + std::fs::create_dir_all(&dir).unwrap(); + // Someone holds the lock but nothing listens on the advertised port. + let held = File::create(dir.join(LOCK_FILE)).unwrap(); + held.lock().unwrap(); + let closed = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap().local_addr().unwrap().port(); + write_info(&dir, &Endpoint::Port(closed), &generate_token().unwrap()).unwrap(); + assert!(matches!(claim_with(&dir, &["a.psd".into()], FAST), Launch::Standalone(_))); + drop(held); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Review of #3755, point 2 and the smaller points: who takes part in single-instance. +#[test] +fn only_per_user_launches_without_process_options_take_part() { + let base = LaunchContext { + per_user_settings: true, + new_instance_flag: false, + new_instance_env: None, + control: false, + unreadable_paths: false, + launch_options: &[], + }; + assert_eq!(skip_reason(&base), None); + // A portable copy's folder or a PHOTOCRAFT_CONFIG_DIR may be shared between users. + assert!(skip_reason(&LaunchContext { per_user_settings: false, ..base }).is_some()); + assert!(skip_reason(&LaunchContext { new_instance_flag: true, ..base }).is_some()); + assert!(skip_reason(&LaunchContext { new_instance_env: Some("1"), ..base }).is_some()); + assert_eq!(skip_reason(&LaunchContext { new_instance_env: Some("0"), ..base }), None); + assert_eq!(skip_reason(&LaunchContext { new_instance_env: Some(""), ..base }), None); + assert!(skip_reason(&LaunchContext { control: true, ..base }).is_some()); + assert!(skip_reason(&LaunchContext { unreadable_paths: true, ..base }).is_some()); + let reason = skip_reason(&LaunchContext { launch_options: &[PerProcess::SafeGpu, PerProcess::GpuAdapterEnv], ..base }); + assert_eq!(reason.as_deref(), Some("--safe-gpu, PHOTOCRAFT_GPU_ADAPTER only applies to a new process")); +} + +/// #1540: inside a Flatpak sandbox the hand-off runs over a Unix socket in the app's runtime +/// directory, which every sandbox of the app shares, with the same lock, token and reply. +#[cfg(unix)] +#[test] +fn a_sandboxed_second_launch_hands_its_paths_over_a_unix_socket() { + use std::os::unix::fs::PermissionsExt; + let dir = temp_dir("socket"); + // Short: a Unix socket path is limited to about 100 bytes (macOS: 104). + let socket = short_socket_path("a"); + let transport = Transport::Socket(socket.clone()); + let primary = match claim_in(&dir, &[], FAST, &transport) { + Launch::Primary(p) => p, + _ => panic!("first launch should be primary"), + }; + assert_eq!(std::fs::metadata(&socket).unwrap().permissions().mode() & 0o777, 0o600); + let info: Value = serde_json::from_slice(&std::fs::read(dir.join(INFO_FILE)).unwrap()).unwrap(); + assert_eq!(info.get("socket").and_then(Value::as_str), Some(socket.to_str().unwrap())); + assert!(info.get("port").is_none()); + let mut ui = primary.connect(&egui::Context::default()); + let paths = ["/home/a/one.psd".to_string()]; + let (d, p, t) = (dir.clone(), paths.clone(), transport.clone()); + let second = std::thread::spawn(move || claim_in(&d, &p, TIMING, &t)); + assert_eq!(drain(&mut ui, 1), vec![OsEvent::Open(paths.to_vec())]); + assert!(matches!(second.join().unwrap(), Launch::Forwarded)); + // The token still gates the socket. + let (endpoint, _) = read_info(&dir).unwrap(); + assert!(send(&endpoint, "not the token", &["x.psd".into()], Instant::now() + FAST.handoff).is_err()); + primary.shutdown(); + assert!(!socket.exists(), "shutdown removes the socket file"); + // The next primary binds the same path; the old one's drop (a second shutdown) must leave it. + let next = match claim_in(&dir, &[], FAST, &transport) { + Launch::Primary(p) => p, + _ => panic!("the lock is free again"), + }; + drop(primary); + assert!(socket.exists(), "a second shutdown doesn't remove the next primary's socket"); + drop(next); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A socket file left by a crashed primary (and a stale `instance.json` naming it) is replaced. +#[cfg(unix)] +#[test] +fn a_crashed_primary_s_socket_file_does_not_block_the_next_one() { + use std::os::unix::fs::FileTypeExt; + let dir = temp_dir("stale-socket"); + let socket = short_socket_path("b"); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::create_dir_all(socket.parent().unwrap()).unwrap(); + std::fs::write(&socket, b"not a socket").unwrap(); + write_info(&dir, &Endpoint::Socket(socket.clone()), &generate_token().unwrap()).unwrap(); + let primary = match claim_in(&dir, &["a.psd".into()], FAST, &Transport::Socket(socket.clone())) { + Launch::Primary(p) => p, + Launch::Forwarded => panic!("nothing was listening"), + Launch::Standalone(e) => panic!("{e}"), + }; + assert!(std::fs::metadata(&socket).unwrap().file_type().is_socket()); + drop(primary); + let _ = std::fs::remove_dir_all(&dir); + let _ = std::fs::remove_dir_all(socket.parent().unwrap()); +} + +/// The socket transport is chosen only inside a Flatpak with a runtime directory. +#[cfg(unix)] +#[test] +fn the_socket_transport_needs_a_flatpak_id_and_a_runtime_directory() { + use std::ffi::OsStr; + let (id, run) = (OsStr::new("ai.storyteller.photocraft"), OsStr::new("/run/user/1000")); + assert_eq!(sandbox_socket(Some(id), Some(run)), Some(PathBuf::from("/run/user/1000/app/ai.storyteller.photocraft/instance.sock"))); + assert_eq!(sandbox_socket(None, Some(run)), None); + assert_eq!(sandbox_socket(Some(id), None), None); + assert_eq!(sandbox_socket(Some(OsStr::new("")), Some(run)), None); + assert_eq!(sandbox_socket(Some(id), Some(OsStr::new(""))), None); +} + +/// A variable documented as the equivalent of a per-launch flag counts as that flag: a launch +/// that sets only variables has per-process options, so it keeps its own process rather than +/// handing its files to the running instance, which never sees the override. +#[test] +fn an_environment_override_counts_as_a_process_option() { + let with = |values: &[(&str, &str)]| env_launch_options_from(|n| values.iter().find(|(k, _)| *k == n).map(|(_, v)| (*v).into())); + assert_eq!(with(&[("PHOTOCRAFT_PRESENT_MODE", "novsync")]), vec![PerProcess::PresentMode]); + assert_eq!(with(&[("PHOTOCRAFT_STROKE_TRACE", "strokes.csv"), ("PHOTOCRAFT_FRAME_LATENCY", "2")]), vec![PerProcess::FrameLatency, PerProcess::StrokeTrace]); + // Nothing set, or a value that means off, is an ordinary launch. Each variable is off the way + // it is read where it takes effect, not by one rule shared across all three. + assert!(with(&[]).is_empty()); + assert!(with(&[("PHOTOCRAFT_FRAME_LATENCY", "")]).is_empty()); + // The trace is off at `off` and `false` as well, and a value the presentation parser rejects + // is ignored there, so neither keeps a process of its own here. + assert!(with(&[("PHOTOCRAFT_STROKE_TRACE", "off"), ("PHOTOCRAFT_PRESENT_MODE", "maybe"), ("PHOTOCRAFT_FRAME_LATENCY", "4")]).is_empty()); + // The trace and the two presentation values are trimmed where they take effect. + assert_eq!(with(&[("PHOTOCRAFT_PRESENT_MODE", " novsync "), ("PHOTOCRAFT_STROKE_TRACE", " 1 ")]), vec![PerProcess::PresentMode, PerProcess::StrokeTrace]); + // The menus and the automation roots are flags' fallbacks: `launch_args::parse` counts them. + assert!(with(&[("PHOTOCRAFT_IN_WINDOW_MENUS", "1"), ("PHOTOCRAFT_AUTOMATION_WRITE_ROOT", "/tmp/out")]).is_empty()); + let base = LaunchContext { + per_user_settings: true, + new_instance_flag: false, + new_instance_env: None, + control: false, + unreadable_paths: false, + launch_options: &[], + }; + let reason = skip_reason(&LaunchContext { launch_options: &with(&[("PHOTOCRAFT_PRESENT_MODE", "novsync")]), ..base }); + assert!(reason.as_deref().is_some_and(|r| r.contains("--present-mode")), "{reason:?}"); +} diff --git a/crates/algo/src/art_history.rs b/crates/algo/src/art_history.rs index 7fcb286c22..d5895a466f 100644 --- a/crates/algo/src/art_history.rs +++ b/crates/algo/src/art_history.rs @@ -655,399 +655,4 @@ pub fn stamp(p: &mut StampParams<'_>) -> Result { } #[cfg(test)] -mod tests { - use super::*; - - fn fill(w: usize, h: usize, ch: usize, f: impl Fn(i32, i32, usize) -> f32) -> Vec { - let mut v = vec![0.0; w * h * ch]; - for y in 0..h { - for x in 0..w { - for c in 0..ch { - v[(y * w + x) * ch + c] = f(x as i32, y as i32, c); - } - } - } - v - } - - fn horizontal(len: f32) -> Vec<[f32; 2]> { - vec![[10.0, 32.0], [10.0 + len, 32.0]] - } - - #[test] - fn tight_short_emits_more_dabs_than_tight_long() { - let pts = horizontal(100.0); - let short = place_dabs(&pts, 10.0, 50.0, Style::TightShort, RNG_SEED).unwrap(); - let long = place_dabs(&pts, 10.0, 50.0, Style::TightLong, RNG_SEED).unwrap(); - assert!(short.len() > long.len(), "short {} long {}", short.len(), long.len()); - let s = spacing_px(10.0, 50.0, Style::TightShort).unwrap(); - let l = spacing_px(10.0, 50.0, Style::TightLong).unwrap(); - assert!(s < l, "{s} {l}"); - } - - #[test] - fn tight_curl_angles_increase_and_loose_curl_scatters() { - let pts = horizontal(80.0); - let tight = place_dabs(&pts, 12.0, 50.0, Style::TightCurl, RNG_SEED).unwrap(); - let loose = place_dabs(&pts, 12.0, 50.0, Style::LooseCurl, RNG_SEED).unwrap(); - assert!(tight.len() >= 3 && loose.len() >= 3); - let dt: Vec = tight.windows(2).map(|w| w[1].theta - w[0].theta).collect(); - assert!(dt.iter().all(|d| *d > 0.05), "tight curl steps {dt:?}"); - let dl: Vec = loose.windows(2).map(|w| w[1].theta - w[0].theta).collect(); - let mean = |v: &[f32]| v.iter().sum::() / v.len() as f32; - assert!(mean(&dl) > mean(&dt), "loose curl {dl:?} vs tight {dt:?}"); - let scatter_t: f32 = tight.iter().map(|d| (d.y - 32.0).abs()).sum(); - let scatter_l: f32 = loose.iter().map(|d| (d.y - 32.0).abs()).sum(); - assert!(scatter_l > scatter_t, "loose scatter {scatter_l} tight {scatter_t}"); - } - - #[test] - fn seeded_scatter_is_replayable() { - let pts = horizontal(60.0); - let a = place_dabs(&pts, 16.0, 40.0, Style::LooseMedium, RNG_SEED ^ 3).unwrap(); - let b = place_dabs(&pts, 16.0, 40.0, Style::LooseMedium, RNG_SEED ^ 3).unwrap(); - assert_eq!(a, b); - let c = place_dabs(&pts, 16.0, 40.0, Style::LooseMedium, RNG_SEED ^ 4).unwrap(); - assert_ne!(a, c); - } - - fn fixture(ch: usize) -> (usize, usize, Vec, Vec, Dab) { - let (w, h) = (128usize, 96usize); - let src = fill(w, h, ch, |x, y, c| if c + 1 == ch && ch > 1 { 1.0 } else { ((x * 13 + y * 7 + c as i32 * 3).rem_euclid(251) as f32) / 255.0 }); - let dest0 = fill(w, h, ch, |_, _, c| if c + 1 == ch && ch > 1 { 1.0 } else { 0.1 }); - // Centre 1 px inside a 64-tile so the rotated read crosses the seam. - let dab = Dab { x: 63.0, y: 40.0, theta: 0.4, radius: 18.0, pressure: 1.0 }; - (w, h, src, dest0, dab) - } - - #[allow(clippy::too_many_arguments)] - fn stamp_run(w: usize, h: usize, ch: usize, src: &[f32], dest: &mut [f32], dab: &Dab, tile: i32) -> u32 { - stamp_dabs(w, h, ch, src, dest, std::slice::from_ref(dab), tile) - } - - #[allow(clippy::too_many_arguments)] - fn stamp_dabs(w: usize, h: usize, ch: usize, src: &[f32], dest: &mut [f32], dabs: &[Dab], tile: i32) -> u32 { - let mut p = StampParams { - dest, - dest_w: w, - dest_h: h, - dest_origin: (0, 0), - src, - src_w: w, - src_h: h, - src_origin: (0, 0), - ch, - dabs, - hardness: 1.0, - opacity: 1.0, - flow: 1.0, - tolerance: 0.0, - tile, - selection: None, - lock_transparent: false, - alpha: (ch > 1).then_some(ch - 1), - }; - stamp(&mut p).unwrap() - } - - fn max_abs(a: &[f32], b: &[f32]) -> f32 { - a.iter().zip(b).fold(0.0f32, |m, (x, y)| m.max((x - y).abs())) - } - - fn max_u8(a: &[f32], b: &[f32]) -> i32 { - a.iter() - .zip(b) - .map(|(x, y)| { - let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as i32; - (q(*x) - q(*y)).abs() - }) - .max() - .unwrap_or(0) - } - - #[test] - fn tiled_stamp_matches_untiled_at_a_tile_seam() { - let (w, h, src, dest0, dab) = fixture(4); - let mut tiled = dest0.clone(); - let mut flat = dest0.clone(); - let n_t = stamp_run(w, h, 4, &src, &mut tiled, &dab, 64); - let n_f = stamp_run(w, h, 4, &src, &mut flat, &dab, 0); - assert!(n_t > 0 && n_f > 0, "wrote {n_t} tiled / {n_f} flat"); - assert_eq!(max_u8(&tiled, &flat), 0, "8-bit seam"); - assert!(max_abs(&tiled, &flat) <= 1.0 / 32_767.0, "16-bit seam {}", max_abs(&tiled, &flat)); - assert!(max_abs(&tiled, &flat) <= 1.0e-5, "32f seam {}", max_abs(&tiled, &flat)); - - let (w, h, src, dest0, dab) = fixture(1); - let mut tiled = dest0.clone(); - let mut flat = dest0; - stamp_run(w, h, 1, &src, &mut tiled, &dab, 64); - stamp_run(w, h, 1, &src, &mut flat, &dab, 0); - assert_eq!(max_u8(&tiled, &flat), 0, "gray 8-bit seam"); - } - - #[test] - fn leftward_and_curl_strokes_match_untiled_across_a_tile_edge() { - let (w, h, ch) = (128usize, 96usize, 4); - let src = fill(w, h, ch, |x, y, c| if c == 3 { 1.0 } else { ((x * 13 + y * 7 + c as i32 * 3).rem_euclid(251) as f32) / 255.0 }); - let dest0 = fill(w, h, ch, |_, _, c| if c == 3 { 1.0 } else { 0.1 }); - for style in [Style::TightMedium, Style::TightCurl, Style::LooseCurl] { - let dabs = place_dabs(&[[110.0, 40.0], [20.0, 40.0]], 40.0, 50.0, style, RNG_SEED).unwrap(); - let mut tiled = dest0.clone(); - let mut flat = dest0.clone(); - stamp_dabs(w, h, ch, &src, &mut tiled, &dabs, 64); - stamp_dabs(w, h, ch, &src, &mut flat, &dabs, 0); - assert_eq!(max_abs(&tiled, &flat), 0.0, "{} seam at x = 64", style.as_str()); - } - } - - /// A dab at angle 0 copies the history pixel under each covered pixel, not a blend of it - /// and its lower-right neighbours. - #[test] - fn unrotated_dab_restores_the_source_pixel() { - let (w, h, ch) = (48usize, 48usize, 4); - let src = fill(w, h, ch, |x, y, c| if c == 3 { 1.0 } else { ((x * 37 + y * 11 + c as i32 * 5).rem_euclid(97) as f32) / 96.0 }); - let mut dest = fill(w, h, ch, |_, _, c| if c == 3 { 1.0 } else { 0.5 }); - let dab = Dab { x: 24.0, y: 24.0, theta: 0.0, radius: 8.0, pressure: 1.0 }; - stamp_run(w, h, ch, &src, &mut dest, &dab, 0); - for (x, y) in [(24usize, 24usize), (20, 22), (27, 26)] { - let i = (y * w + x) * ch; - assert_eq!(&dest[i..i + ch], &src[i..i + ch], "pixel {x},{y}"); - } - } - - #[test] - fn halo_covers_rotated_read_reach() { - let size = 40.0; - for style in - [Style::TightShort, Style::TightMedium, Style::TightLong, Style::LooseMedium, Style::LooseLong, Style::Dab, Style::TightCurl, Style::LooseCurl] - { - let halo = halo_radius(size, style).unwrap(); - let side = sample_side(size, style).unwrap(); - let reach = (side + 1) / 2; - assert!(halo >= reach, "{:?}: halo {halo} < reach {reach} (side {side})", style.as_str()); - } - } - - #[test] - fn tolerance_skips_an_unchanged_layer() { - let (w, h, ch) = (48usize, 48usize, 4); - let src = fill(w, h, ch, |x, y, c| if c == 3 { 1.0 } else { (x + y) as f32 / 100.0 }); - let mut dest = src.clone(); - let dab = Dab { x: 24.0, y: 24.0, theta: 0.0, radius: 8.0, pressure: 1.0 }; - let mut p = StampParams { - dest: &mut dest, - dest_w: w, - dest_h: h, - dest_origin: (0, 0), - src: &src, - src_w: w, - src_h: h, - src_origin: (0, 0), - ch, - dabs: std::slice::from_ref(&dab), - hardness: 1.0, - opacity: 1.0, - flow: 1.0, - tolerance: 1.0, - tile: 0, - selection: None, - lock_transparent: false, - alpha: Some(3), - }; - let n = stamp(&mut p).unwrap(); - assert_eq!(n, 0); - assert_eq!(dest, src); - } - - #[test] - fn tolerance_zero_writes_where_history_differs() { - let (w, h, ch) = (48usize, 48usize, 4); - let src = fill(w, h, ch, |_, _, c| if c == 3 { 1.0 } else { 0.9 }); - let mut dest = fill(w, h, ch, |_, _, c| if c == 3 { 1.0 } else { 0.1 }); - let dab = Dab { x: 24.0, y: 24.0, theta: 0.0, radius: 8.0, pressure: 1.0 }; - let mut p = StampParams { - dest: &mut dest, - dest_w: w, - dest_h: h, - dest_origin: (0, 0), - src: &src, - src_w: w, - src_h: h, - src_origin: (0, 0), - ch, - dabs: std::slice::from_ref(&dab), - hardness: 1.0, - opacity: 1.0, - flow: 1.0, - tolerance: 0.0, - tile: 0, - selection: None, - lock_transparent: false, - alpha: Some(3), - }; - let n = stamp(&mut p).unwrap(); - assert!(n > 0); - let i = (24 * w + 24) * ch; - assert!((dest[i] - 0.9).abs() < 1.0e-5, "{}", dest[i]); - } - - #[test] - fn tolerance_ignores_unchanged_alpha() { - // Colour moved by 0.3 and alpha did not: the 0.25 threshold must not see a 0.225 average. - let (w, h, ch) = (48usize, 48usize, 4); - let src = fill(w, h, ch, |_, _, c| if c == 3 { 1.0 } else { 0.6 }); - let dest0 = fill(w, h, ch, |_, _, c| if c == 3 { 1.0 } else { 0.3 }); - let dab = Dab { x: 24.0, y: 24.0, theta: 0.0, radius: 8.0, pressure: 1.0 }; - for (tolerance, paints) in [(0.25, true), (0.35, false)] { - let mut dest = dest0.clone(); - let mut p = StampParams { - dest: &mut dest, - dest_w: w, - dest_h: h, - dest_origin: (0, 0), - src: &src, - src_w: w, - src_h: h, - src_origin: (0, 0), - ch, - dabs: std::slice::from_ref(&dab), - hardness: 1.0, - opacity: 1.0, - flow: 1.0, - tolerance, - tile: 0, - selection: None, - lock_transparent: false, - alpha: Some(3), - }; - let n = stamp(&mut p).unwrap(); - assert_eq!(n > 0, paints, "tolerance {tolerance}"); - } - } - - /// The Eraser keeps the colour and lowers only the alpha: an erased patch differs from the - /// history state and is painted back with a tolerance above 0. - #[test] - fn tolerance_sees_an_erased_patch() { - let (w, h, ch) = (48usize, 48usize, 4); - let src = fill(w, h, ch, |_, _, c| if c == 0 || c == 3 { 1.0 } else { 0.0 }); - let mut dest = fill(w, h, ch, |_, _, c| match c { - 0 => 1.0, - 3 => 0.6, - _ => 0.0, - }); - let dab = Dab { x: 24.0, y: 24.0, theta: 0.0, radius: 8.0, pressure: 1.0 }; - let mut p = StampParams { - dest: &mut dest, - dest_w: w, - dest_h: h, - dest_origin: (0, 0), - src: &src, - src_w: w, - src_h: h, - src_origin: (0, 0), - ch, - dabs: std::slice::from_ref(&dab), - hardness: 1.0, - opacity: 1.0, - flow: 1.0, - tolerance: 0.25, - tile: 0, - selection: None, - lock_transparent: false, - alpha: Some(3), - }; - assert!(stamp(&mut p).unwrap() > 0, "alpha 1 -> 0.6 is over tolerance 0.25"); - let i = (24 * w + 24) * ch; - assert!((dest[i + 3] - 1.0).abs() < 1.0e-5, "alpha restored, got {}", dest[i + 3]); - } - #[test] - fn empty_or_mismatched_buffers_error() { - let mut dest = vec![0.0f32; 16]; - let src = vec![0.0f32; 16]; - let dab = Dab { x: 1.0, y: 1.0, theta: 0.0, radius: 1.0, pressure: 1.0 }; - let mut p = StampParams { - dest: &mut dest, - dest_w: 0, - dest_h: 4, - dest_origin: (0, 0), - src: &src, - src_w: 4, - src_h: 4, - src_origin: (0, 0), - ch: 1, - dabs: std::slice::from_ref(&dab), - hardness: 1.0, - opacity: 1.0, - flow: 1.0, - tolerance: 0.0, - tile: 0, - selection: None, - lock_transparent: false, - alpha: None, - }; - assert_eq!(stamp(&mut p), Err(StampError::Empty)); - let mut dest = vec![0.0f32; 16]; - let src = vec![0.0f32; 8]; - let mut p = StampParams { - dest: &mut dest, - dest_w: 4, - dest_h: 4, - dest_origin: (0, 0), - src: &src, - src_w: 2, - src_h: 2, - src_origin: (0, 0), - ch: 4, - dabs: std::slice::from_ref(&dab), - hardness: 1.0, - opacity: 1.0, - flow: 1.0, - tolerance: 0.0, - tile: 0, - selection: None, - lock_transparent: false, - alpha: None, - }; - assert!(stamp(&mut p).is_err()); - assert!(place_dabs(&[], 10.0, 50.0, Style::TightMedium, 0).is_err()); - assert!(Style::parse("nope").is_none()); - assert_eq!(Style::parse("tightMedium"), Some(Style::TightMedium)); - } - - #[test] - fn two_stamps_with_the_same_seed_match() { - let pts = horizontal(50.0); - let dabs = place_dabs(&pts, 12.0, 50.0, Style::LooseCurl, RNG_SEED).unwrap(); - let (w, h, ch) = (80usize, 64usize, 4); - let src = fill(w, h, ch, |x, y, c| if c == 3 { 1.0 } else { (x + 3 * y) as f32 / 200.0 }); - let dest0 = fill(w, h, ch, |_, _, c| if c == 3 { 1.0 } else { 0.2 }); - let run = |dest: &mut [f32]| { - let mut p = StampParams { - dest, - dest_w: w, - dest_h: h, - dest_origin: (0, 0), - src: &src, - src_w: w, - src_h: h, - src_origin: (0, 0), - ch, - dabs: &dabs, - hardness: 0.8, - opacity: 1.0, - flow: 1.0, - tolerance: 0.0, - tile: 64, - selection: None, - lock_transparent: false, - alpha: Some(3), - }; - stamp(&mut p).unwrap() - }; - let mut a = dest0.clone(); - let mut b = dest0; - assert_eq!(run(&mut a), run(&mut b)); - assert_eq!(a, b); - } -} +mod tests; diff --git a/crates/algo/src/art_history/tests.rs b/crates/algo/src/art_history/tests.rs new file mode 100644 index 0000000000..373cfc304b --- /dev/null +++ b/crates/algo/src/art_history/tests.rs @@ -0,0 +1,393 @@ +use super::*; + +fn fill(w: usize, h: usize, ch: usize, f: impl Fn(i32, i32, usize) -> f32) -> Vec { + let mut v = vec![0.0; w * h * ch]; + for y in 0..h { + for x in 0..w { + for c in 0..ch { + v[(y * w + x) * ch + c] = f(x as i32, y as i32, c); + } + } + } + v +} + +fn horizontal(len: f32) -> Vec<[f32; 2]> { + vec![[10.0, 32.0], [10.0 + len, 32.0]] +} + +#[test] +fn tight_short_emits_more_dabs_than_tight_long() { + let pts = horizontal(100.0); + let short = place_dabs(&pts, 10.0, 50.0, Style::TightShort, RNG_SEED).unwrap(); + let long = place_dabs(&pts, 10.0, 50.0, Style::TightLong, RNG_SEED).unwrap(); + assert!(short.len() > long.len(), "short {} long {}", short.len(), long.len()); + let s = spacing_px(10.0, 50.0, Style::TightShort).unwrap(); + let l = spacing_px(10.0, 50.0, Style::TightLong).unwrap(); + assert!(s < l, "{s} {l}"); +} + +#[test] +fn tight_curl_angles_increase_and_loose_curl_scatters() { + let pts = horizontal(80.0); + let tight = place_dabs(&pts, 12.0, 50.0, Style::TightCurl, RNG_SEED).unwrap(); + let loose = place_dabs(&pts, 12.0, 50.0, Style::LooseCurl, RNG_SEED).unwrap(); + assert!(tight.len() >= 3 && loose.len() >= 3); + let dt: Vec = tight.windows(2).map(|w| w[1].theta - w[0].theta).collect(); + assert!(dt.iter().all(|d| *d > 0.05), "tight curl steps {dt:?}"); + let dl: Vec = loose.windows(2).map(|w| w[1].theta - w[0].theta).collect(); + let mean = |v: &[f32]| v.iter().sum::() / v.len() as f32; + assert!(mean(&dl) > mean(&dt), "loose curl {dl:?} vs tight {dt:?}"); + let scatter_t: f32 = tight.iter().map(|d| (d.y - 32.0).abs()).sum(); + let scatter_l: f32 = loose.iter().map(|d| (d.y - 32.0).abs()).sum(); + assert!(scatter_l > scatter_t, "loose scatter {scatter_l} tight {scatter_t}"); +} + +#[test] +fn seeded_scatter_is_replayable() { + let pts = horizontal(60.0); + let a = place_dabs(&pts, 16.0, 40.0, Style::LooseMedium, RNG_SEED ^ 3).unwrap(); + let b = place_dabs(&pts, 16.0, 40.0, Style::LooseMedium, RNG_SEED ^ 3).unwrap(); + assert_eq!(a, b); + let c = place_dabs(&pts, 16.0, 40.0, Style::LooseMedium, RNG_SEED ^ 4).unwrap(); + assert_ne!(a, c); +} + +fn fixture(ch: usize) -> (usize, usize, Vec, Vec, Dab) { + let (w, h) = (128usize, 96usize); + let src = fill(w, h, ch, |x, y, c| if c + 1 == ch && ch > 1 { 1.0 } else { ((x * 13 + y * 7 + c as i32 * 3).rem_euclid(251) as f32) / 255.0 }); + let dest0 = fill(w, h, ch, |_, _, c| if c + 1 == ch && ch > 1 { 1.0 } else { 0.1 }); + // Centre 1 px inside a 64-tile so the rotated read crosses the seam. + let dab = Dab { x: 63.0, y: 40.0, theta: 0.4, radius: 18.0, pressure: 1.0 }; + (w, h, src, dest0, dab) +} + +#[allow(clippy::too_many_arguments)] +fn stamp_run(w: usize, h: usize, ch: usize, src: &[f32], dest: &mut [f32], dab: &Dab, tile: i32) -> u32 { + stamp_dabs(w, h, ch, src, dest, std::slice::from_ref(dab), tile) +} + +#[allow(clippy::too_many_arguments)] +fn stamp_dabs(w: usize, h: usize, ch: usize, src: &[f32], dest: &mut [f32], dabs: &[Dab], tile: i32) -> u32 { + let mut p = StampParams { + dest, + dest_w: w, + dest_h: h, + dest_origin: (0, 0), + src, + src_w: w, + src_h: h, + src_origin: (0, 0), + ch, + dabs, + hardness: 1.0, + opacity: 1.0, + flow: 1.0, + tolerance: 0.0, + tile, + selection: None, + lock_transparent: false, + alpha: (ch > 1).then_some(ch - 1), + }; + stamp(&mut p).unwrap() +} + +fn max_abs(a: &[f32], b: &[f32]) -> f32 { + a.iter().zip(b).fold(0.0f32, |m, (x, y)| m.max((x - y).abs())) +} + +fn max_u8(a: &[f32], b: &[f32]) -> i32 { + a.iter() + .zip(b) + .map(|(x, y)| { + let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as i32; + (q(*x) - q(*y)).abs() + }) + .max() + .unwrap_or(0) +} + +#[test] +fn tiled_stamp_matches_untiled_at_a_tile_seam() { + let (w, h, src, dest0, dab) = fixture(4); + let mut tiled = dest0.clone(); + let mut flat = dest0.clone(); + let n_t = stamp_run(w, h, 4, &src, &mut tiled, &dab, 64); + let n_f = stamp_run(w, h, 4, &src, &mut flat, &dab, 0); + assert!(n_t > 0 && n_f > 0, "wrote {n_t} tiled / {n_f} flat"); + assert_eq!(max_u8(&tiled, &flat), 0, "8-bit seam"); + assert!(max_abs(&tiled, &flat) <= 1.0 / 32_767.0, "16-bit seam {}", max_abs(&tiled, &flat)); + assert!(max_abs(&tiled, &flat) <= 1.0e-5, "32f seam {}", max_abs(&tiled, &flat)); + + let (w, h, src, dest0, dab) = fixture(1); + let mut tiled = dest0.clone(); + let mut flat = dest0; + stamp_run(w, h, 1, &src, &mut tiled, &dab, 64); + stamp_run(w, h, 1, &src, &mut flat, &dab, 0); + assert_eq!(max_u8(&tiled, &flat), 0, "gray 8-bit seam"); +} + +#[test] +fn leftward_and_curl_strokes_match_untiled_across_a_tile_edge() { + let (w, h, ch) = (128usize, 96usize, 4); + let src = fill(w, h, ch, |x, y, c| if c == 3 { 1.0 } else { ((x * 13 + y * 7 + c as i32 * 3).rem_euclid(251) as f32) / 255.0 }); + let dest0 = fill(w, h, ch, |_, _, c| if c == 3 { 1.0 } else { 0.1 }); + for style in [Style::TightMedium, Style::TightCurl, Style::LooseCurl] { + let dabs = place_dabs(&[[110.0, 40.0], [20.0, 40.0]], 40.0, 50.0, style, RNG_SEED).unwrap(); + let mut tiled = dest0.clone(); + let mut flat = dest0.clone(); + stamp_dabs(w, h, ch, &src, &mut tiled, &dabs, 64); + stamp_dabs(w, h, ch, &src, &mut flat, &dabs, 0); + assert_eq!(max_abs(&tiled, &flat), 0.0, "{} seam at x = 64", style.as_str()); + } +} + +/// A dab at angle 0 copies the history pixel under each covered pixel, not a blend of it +/// and its lower-right neighbours. +#[test] +fn unrotated_dab_restores_the_source_pixel() { + let (w, h, ch) = (48usize, 48usize, 4); + let src = fill(w, h, ch, |x, y, c| if c == 3 { 1.0 } else { ((x * 37 + y * 11 + c as i32 * 5).rem_euclid(97) as f32) / 96.0 }); + let mut dest = fill(w, h, ch, |_, _, c| if c == 3 { 1.0 } else { 0.5 }); + let dab = Dab { x: 24.0, y: 24.0, theta: 0.0, radius: 8.0, pressure: 1.0 }; + stamp_run(w, h, ch, &src, &mut dest, &dab, 0); + for (x, y) in [(24usize, 24usize), (20, 22), (27, 26)] { + let i = (y * w + x) * ch; + assert_eq!(&dest[i..i + ch], &src[i..i + ch], "pixel {x},{y}"); + } +} + +#[test] +fn halo_covers_rotated_read_reach() { + let size = 40.0; + for style in [Style::TightShort, Style::TightMedium, Style::TightLong, Style::LooseMedium, Style::LooseLong, Style::Dab, Style::TightCurl, Style::LooseCurl] + { + let halo = halo_radius(size, style).unwrap(); + let side = sample_side(size, style).unwrap(); + let reach = (side + 1) / 2; + assert!(halo >= reach, "{:?}: halo {halo} < reach {reach} (side {side})", style.as_str()); + } +} + +#[test] +fn tolerance_skips_an_unchanged_layer() { + let (w, h, ch) = (48usize, 48usize, 4); + let src = fill(w, h, ch, |x, y, c| if c == 3 { 1.0 } else { (x + y) as f32 / 100.0 }); + let mut dest = src.clone(); + let dab = Dab { x: 24.0, y: 24.0, theta: 0.0, radius: 8.0, pressure: 1.0 }; + let mut p = StampParams { + dest: &mut dest, + dest_w: w, + dest_h: h, + dest_origin: (0, 0), + src: &src, + src_w: w, + src_h: h, + src_origin: (0, 0), + ch, + dabs: std::slice::from_ref(&dab), + hardness: 1.0, + opacity: 1.0, + flow: 1.0, + tolerance: 1.0, + tile: 0, + selection: None, + lock_transparent: false, + alpha: Some(3), + }; + let n = stamp(&mut p).unwrap(); + assert_eq!(n, 0); + assert_eq!(dest, src); +} + +#[test] +fn tolerance_zero_writes_where_history_differs() { + let (w, h, ch) = (48usize, 48usize, 4); + let src = fill(w, h, ch, |_, _, c| if c == 3 { 1.0 } else { 0.9 }); + let mut dest = fill(w, h, ch, |_, _, c| if c == 3 { 1.0 } else { 0.1 }); + let dab = Dab { x: 24.0, y: 24.0, theta: 0.0, radius: 8.0, pressure: 1.0 }; + let mut p = StampParams { + dest: &mut dest, + dest_w: w, + dest_h: h, + dest_origin: (0, 0), + src: &src, + src_w: w, + src_h: h, + src_origin: (0, 0), + ch, + dabs: std::slice::from_ref(&dab), + hardness: 1.0, + opacity: 1.0, + flow: 1.0, + tolerance: 0.0, + tile: 0, + selection: None, + lock_transparent: false, + alpha: Some(3), + }; + let n = stamp(&mut p).unwrap(); + assert!(n > 0); + let i = (24 * w + 24) * ch; + assert!((dest[i] - 0.9).abs() < 1.0e-5, "{}", dest[i]); +} + +#[test] +fn tolerance_ignores_unchanged_alpha() { + // Colour moved by 0.3 and alpha did not: the 0.25 threshold must not see a 0.225 average. + let (w, h, ch) = (48usize, 48usize, 4); + let src = fill(w, h, ch, |_, _, c| if c == 3 { 1.0 } else { 0.6 }); + let dest0 = fill(w, h, ch, |_, _, c| if c == 3 { 1.0 } else { 0.3 }); + let dab = Dab { x: 24.0, y: 24.0, theta: 0.0, radius: 8.0, pressure: 1.0 }; + for (tolerance, paints) in [(0.25, true), (0.35, false)] { + let mut dest = dest0.clone(); + let mut p = StampParams { + dest: &mut dest, + dest_w: w, + dest_h: h, + dest_origin: (0, 0), + src: &src, + src_w: w, + src_h: h, + src_origin: (0, 0), + ch, + dabs: std::slice::from_ref(&dab), + hardness: 1.0, + opacity: 1.0, + flow: 1.0, + tolerance, + tile: 0, + selection: None, + lock_transparent: false, + alpha: Some(3), + }; + let n = stamp(&mut p).unwrap(); + assert_eq!(n > 0, paints, "tolerance {tolerance}"); + } +} + +/// The Eraser keeps the colour and lowers only the alpha: an erased patch differs from the +/// history state and is painted back with a tolerance above 0. +#[test] +fn tolerance_sees_an_erased_patch() { + let (w, h, ch) = (48usize, 48usize, 4); + let src = fill(w, h, ch, |_, _, c| if c == 0 || c == 3 { 1.0 } else { 0.0 }); + let mut dest = fill(w, h, ch, |_, _, c| match c { + 0 => 1.0, + 3 => 0.6, + _ => 0.0, + }); + let dab = Dab { x: 24.0, y: 24.0, theta: 0.0, radius: 8.0, pressure: 1.0 }; + let mut p = StampParams { + dest: &mut dest, + dest_w: w, + dest_h: h, + dest_origin: (0, 0), + src: &src, + src_w: w, + src_h: h, + src_origin: (0, 0), + ch, + dabs: std::slice::from_ref(&dab), + hardness: 1.0, + opacity: 1.0, + flow: 1.0, + tolerance: 0.25, + tile: 0, + selection: None, + lock_transparent: false, + alpha: Some(3), + }; + assert!(stamp(&mut p).unwrap() > 0, "alpha 1 -> 0.6 is over tolerance 0.25"); + let i = (24 * w + 24) * ch; + assert!((dest[i + 3] - 1.0).abs() < 1.0e-5, "alpha restored, got {}", dest[i + 3]); +} +#[test] +fn empty_or_mismatched_buffers_error() { + let mut dest = vec![0.0f32; 16]; + let src = vec![0.0f32; 16]; + let dab = Dab { x: 1.0, y: 1.0, theta: 0.0, radius: 1.0, pressure: 1.0 }; + let mut p = StampParams { + dest: &mut dest, + dest_w: 0, + dest_h: 4, + dest_origin: (0, 0), + src: &src, + src_w: 4, + src_h: 4, + src_origin: (0, 0), + ch: 1, + dabs: std::slice::from_ref(&dab), + hardness: 1.0, + opacity: 1.0, + flow: 1.0, + tolerance: 0.0, + tile: 0, + selection: None, + lock_transparent: false, + alpha: None, + }; + assert_eq!(stamp(&mut p), Err(StampError::Empty)); + let mut dest = vec![0.0f32; 16]; + let src = vec![0.0f32; 8]; + let mut p = StampParams { + dest: &mut dest, + dest_w: 4, + dest_h: 4, + dest_origin: (0, 0), + src: &src, + src_w: 2, + src_h: 2, + src_origin: (0, 0), + ch: 4, + dabs: std::slice::from_ref(&dab), + hardness: 1.0, + opacity: 1.0, + flow: 1.0, + tolerance: 0.0, + tile: 0, + selection: None, + lock_transparent: false, + alpha: None, + }; + assert!(stamp(&mut p).is_err()); + assert!(place_dabs(&[], 10.0, 50.0, Style::TightMedium, 0).is_err()); + assert!(Style::parse("nope").is_none()); + assert_eq!(Style::parse("tightMedium"), Some(Style::TightMedium)); +} + +#[test] +fn two_stamps_with_the_same_seed_match() { + let pts = horizontal(50.0); + let dabs = place_dabs(&pts, 12.0, 50.0, Style::LooseCurl, RNG_SEED).unwrap(); + let (w, h, ch) = (80usize, 64usize, 4); + let src = fill(w, h, ch, |x, y, c| if c == 3 { 1.0 } else { (x + 3 * y) as f32 / 200.0 }); + let dest0 = fill(w, h, ch, |_, _, c| if c == 3 { 1.0 } else { 0.2 }); + let run = |dest: &mut [f32]| { + let mut p = StampParams { + dest, + dest_w: w, + dest_h: h, + dest_origin: (0, 0), + src: &src, + src_w: w, + src_h: h, + src_origin: (0, 0), + ch, + dabs: &dabs, + hardness: 0.8, + opacity: 1.0, + flow: 1.0, + tolerance: 0.0, + tile: 64, + selection: None, + lock_transparent: false, + alpha: Some(3), + }; + stamp(&mut p).unwrap() + }; + let mut a = dest0.clone(); + let mut b = dest0; + assert_eq!(run(&mut a), run(&mut b)); + assert_eq!(a, b); +} diff --git a/crates/algo/src/blur.rs b/crates/algo/src/blur.rs index fb62681222..bd762d073f 100644 --- a/crates/algo/src/blur.rs +++ b/crates/algo/src/blur.rs @@ -784,465 +784,4 @@ fn surface_direct(src: &Image, out: Rect, ctx: &Ctx, r: i32, t: f32) -> Vec } #[cfg(test)] -mod tests { - use super::*; - use photocraft_color::{ColorMode, PixelFormat, SampleType}; - use photocraft_raster::Surface; - - #[test] - fn radial_blur_samples_large_arcs_beyond_64_intervals() { - let bounds = Rect::new(0, 0, 1000, 1000); - let out = Rect::new(999, 500, 1000, 501); - let ctx = Ctx { bounds, mode: photocraft_color::ColorMode::Grayscale, alpha: false }; - let mut img = Image::new(bounds, 1); - let (cx, cy) = (500.0f32, 500.0f32); - let (x, y) = (999.5f32, 500.5f32); - let (dx, dy) = (x - cx, y - cy); - let arc = 100.0f32.to_radians(); - let count = radial_intervals(arc * dx.hypot(dy), RadialQuality::Good); - assert_eq!(count, 256); - assert_eq!(radial_intervals(f32::INFINITY, RadialQuality::Draft), 64); - assert_eq!(radial_intervals(f32::INFINITY, RadialQuality::Good), 256); - assert_eq!(radial_intervals(f32::INFINITY, RadialQuality::Best), 4096); - assert_eq!(radial_intervals(f32::NAN, RadialQuality::Best), 1); - - // Put a small bright patch halfway between two samples from the former 64-interval - // limit. Dense sampling should pick it up; the coarse path misses it entirely. - let sparse_midpoint = (31.5 / 64.0 - 0.5) * arc; - let (s, c) = sparse_midpoint.sin_cos(); - let px = (cx + dx * c - dy * s - 0.5).round() as i32; - let py = (cy + dx * s + dy * c - 0.5).round() as i32; - for yy in py - 1..=py + 1 { - for xx in px - 1..=px + 1 { - let index = (yy - bounds.y0) as usize * bounds.width() as usize + (xx - bounds.x0) as usize; - img.data[index] = 1.0; - } - } - - let sample_path = |x: f32, y: f32, pts: &mut Vec<(f32, f32)>, intervals: usize| { - let (dx, dy) = (x - cx, y - cy); - for i in 0..=intervals { - let t = (i as f32 / intervals as f32 - 0.5) * arc; - let (s, c) = t.sin_cos(); - pts.push((cx + dx * c - dy * s, cy + dx * s + dy * c)); - } - }; - let actual = radial(&img, out, &ctx, 100.0, RadialMethod::Spin, RadialQuality::Good, (0.5, 0.5))[0]; - let expected = average_samples(&img, out, &ctx, |x, y, pts| sample_path(x, y, pts, 8192))[0]; - let coarse = average_samples(&img, out, &ctx, |x, y, pts| sample_path(x, y, pts, 64))[0]; - - assert!(actual > 0.001, "dense radial samples should resolve the bright patch, got {actual}"); - assert!((actual - expected).abs() < 0.0015, "radial result {actual} differs from dense reference {expected}"); - assert!(coarse < expected * 0.1, "former 64-interval sampling unexpectedly resolved the patch: {coarse} vs {expected}"); - } - - #[test] - fn fixed_channel_convolution_matches_scalar_tap_order() { - fn check() { - for width in [1, 7, 256] { - for radius in [0.0, 0.5, 3.0, 4.0] { - let k = gaussian_kernel(radius); - let src: Vec = (0..(width + k.len() - 1) * N).map(|i| ((i * 73) % 251) as f32 / 250.0).collect(); - let mut expected = vec![0.0f32; width * N]; - for x in 0..width { - for (i, w) in k.iter().enumerate() { - for c in 0..N { - expected[x * N + c] += src[(x + i) * N + c] * w; - } - } - } - let mut actual = vec![0.0f32; width * N]; - conv_row::(&src, &mut actual, &k); - assert_eq!(actual, expected, "channels={N} width={width} radius={radius}"); - } - } - } - check::<1>(); - check::<2>(); - check::<3>(); - check::<4>(); - check::<5>(); - } - - #[test] - fn box_gaussian_matches_exact_kernel() { - // A hard vertical edge (premultiplied RGBA-ish, 2 channels) blurred with σ = 12. - let src_rect = Rect::new(-60, -60, 180, 68); - let mut img = Image::new(src_rect, 2); - for y in src_rect.y0..src_rect.y1 { - for x in src_rect.x0..src_rect.x1 { - let i = ((y - src_rect.y0) as usize * src_rect.width() as usize + (x - src_rect.x0) as usize) * 2; - img.data[i] = if x < 60 { 1.0 } else { 0.0 }; - img.data[i + 1] = 1.0; - } - } - let out = Rect::new(0, 0, 120, 8); - let k = gaussian_kernel(12.0); - let exact = conv_sep(&img, out, &k, &k, true); - let fast = box_passes(&img, out, true, &boxes_for_gauss(12.0, 3)); - let err = exact.iter().zip(&fast).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); - assert!(err < 0.02, "max error {err}"); - assert_eq!(boxes_for_gauss(10.0, 3).len(), 3); - } - - #[test] - fn box_passes_match_the_direct_box_kernel() { - // Noisy RGBA with varying alpha, so premultiplication and every channel are exercised. - for r in [5usize, 17, 60] { - let (w, h, m) = (40, 24, r as i32 + 2); - let src_rect = Rect::new(-m, -m, w + m, h + m); - let mut img = Image::new(src_rect, 4); - let mut s = 0x9e37_79b9u32; - for v in img.data.iter_mut() { - s ^= s << 13; - s ^= s >> 17; - s ^= s << 5; - *v = (s % 256) as f32 / 255.0; - } - let out = Rect::new(0, 0, w, h); - let k = vec![1.0 / (2 * r + 1) as f32; 2 * r + 1]; - let direct = conv_sep(&img, out, &k, &k, true); - let ctx = Ctx { bounds: src_rect, mode: crate::ColorMode::Rgb, alpha: true }; - let fast = boxed(&img, out, &ctx, r as f32); - let err = direct.iter().zip(&fast).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); - assert!(err < 1e-5, "radius {r}: max error {err}"); - } - } - - /// The definition the running sums must match: each box applied in turn as a direct - /// convolution (cost per pixel proportional to the radius) to `img`, which covers `out` grown - /// by every box's reach (its own edge handling included). - fn direct_boxes(img: &Image, out: Rect, boxes: &[usize], alpha: bool) -> Vec { - let mut cur = img.clone(); - let mut left: i32 = boxes.iter().map(|w| (w / 2) as i32).sum(); - for &w in boxes { - left -= (w / 2) as i32; - let k = vec![1.0 / w as f32; w]; - let rect = out.inflate(left); - cur = Image { rect, ch: img.ch, data: conv_sep(&cur, rect, &k, &k, alpha) }; - } - cur.data - } - - /// Noisy pixels over `r` (alpha varying, some fully transparent). - fn noisy(fmt: PixelFormat, r: Rect, seed: u32) -> Surface { - let mut s = Surface::new(fmt); - let mut st = seed; - let mut v = Vec::new(); - for _ in 0..r.width() * r.height() { - for c in 0..fmt.channels() { - st ^= st << 13; - st ^= st >> 17; - st ^= st << 5; - let x = (st % 256) as f32 / 255.0; - v.push(if fmt.alpha && c + 1 == fmt.channels() && st.is_multiple_of(5) { 0.0 } else { x }); - } - } - s.write_region(r, &v); - s - } - - #[test] - fn layer_box_blurs_match_direct_convolution_at_any_radius() { - // Gaussian and Box Blur at radii up to several times the layer (37 × 23), filtered as a - // document layer (canvas edge repeated, as Photoshop does) and on their own (transparent - // beyond), at every depth, with and without alpha, 1 to 5 channels. - let canvas = Rect::new(0, 0, 37, 23); - let formats = [ - PixelFormat::RGBA8, - PixelFormat::RGBA16, - PixelFormat::RGBA32F, - PixelFormat::GRAY8, - PixelFormat::CMYKA8, - PixelFormat::new(ColorMode::Lab, SampleType::F32, false), - ]; - let params = [ - FilterParams::GaussianBlur { radius: 4.5 }, - FilterParams::GaussianBlur { radius: 9.3 }, - FilterParams::GaussianBlur { radius: 40.0 }, - FilterParams::BoxBlur { radius: 5.0 }, - FilterParams::BoxBlur { radius: 70.0 }, - ]; - for (i, fmt) in formats.into_iter().enumerate() { - let s = noisy(fmt, canvas, 0x9e37_79b9 + i as u32); - // A level of the depth (colour and alpha are each rounded on write) plus float noise. - let tol = match fmt.sample { - SampleType::U8 => 1.0 / 255.0, - SampleType::U16 => 1.0 / 65535.0, - _ => 0.0, - } + 2e-5; - for p in ¶ms { - let boxes = box_widths(p).expect("a box-pass blur"); - let reach: i32 = boxes.iter().map(|w| (w / 2) as i32).sum(); - let area = crate::output_area(p, s.content_bounds(), canvas, None); - for (got, img, out) in [ - (crate::apply_in(&s, p, area, canvas, None, canvas), Image::read_clamped(&s, canvas.inflate(reach), canvas), canvas), - (crate::apply(&s, p, area, canvas, None), Image::read(&s, area.inflate(reach)), area), - ] { - // Compared alpha-weighted: colour is meaningless where (nearly) transparent. - let (mut got, mut want) = (got.read_region(out), direct_boxes(&img, out, &boxes, fmt.alpha)); - premultiply(&mut got, img.ch, fmt.alpha); - premultiply(&mut want, img.ch, fmt.alpha); - let err = got.iter().zip(&want).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); - assert!(err <= tol, "{} on {fmt:?} over {out:?}: max error {err}", p.label()); - } - } - } - } - - #[test] - fn layer_box_blurs_mix_by_the_selection_and_stop_when_cancelled() { - let canvas = Rect::new(0, 0, 37, 23); - let s = noisy(PixelFormat::RGBA32F, canvas, 7); - let p = FilterParams::GaussianBlur { radius: 12.0 }; - let full = crate::apply_in(&s, &p, canvas, canvas, None, canvas); - let half = Surface::with_default(PixelFormat::new(ColorMode::Grayscale, SampleType::F32, false), &[0.5]); - let mixed = crate::apply_in(&s, &p, canvas, canvas, Some(&half), canvas); - for (x, y) in [(0, 0), (18, 11), (36, 22)] { - let (o, f, m) = (s.pixel(x, y), full.pixel(x, y), mixed.pixel(x, y)); - assert!((m[3] - (o[3] + f[3]) / 2.0).abs() < 1e-5, "({x},{y}) alpha"); - for c in 0..3 { - assert!((m[c] * m[3] - (o[c] * o[3] + f[c] * f[3]) / 2.0).abs() < 1e-5, "({x},{y}) premultiplied channel {c}"); - } - } - let cancel = || true; - let ctl = Interrupt::cancel_only(&cancel); - assert!(crate::apply_in_with(&s, &p, canvas, canvas, None, canvas, &ctl).is_none()); - } - - #[test] - fn surface_blur_8bit_histogram_matches_the_direct_sum() { - // 8-bit levels with some fully transparent pixels, which the sum skips. - let src_rect = Rect::new(-14, -14, 40, 34); - let mut img = Image::new(src_rect, 4); - let mut s = 0x6c07_8965u32; - for px in img.data.as_chunks_mut::<4>().0 { - for v in px.iter_mut() { - s ^= s << 13; - s ^= s >> 17; - s ^= s << 5; - *v = (s % 256) as f32 / 255.0; - } - if s.is_multiple_of(7) { - px[3] = 0.0; - } - } - let ctx = Ctx { bounds: src_rect, mode: crate::ColorMode::Rgb, alpha: true }; - // The output reaches the source edge, where samples read as transparent. - let out = Rect::new(-2, 0, 26, 20); - for (r, threshold) in [(1, 2.0), (4, 15.0), (12, 60.0), (12, 255.0)] { - let t = (threshold / 255.0) * 2.5; - let reach = ((t * 255.0f32).ceil() as usize).min(255); - let fast = surface_8bit(&img, out, &ctx, r, t, reach).expect("8-bit input"); - let direct = surface_direct(&img, out, &ctx, r, t); - let err = direct.iter().zip(&fast).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); - assert!(err < 1e-5, "r {r} threshold {threshold}: max error {err}"); - } - // Not 8-bit: the histogram declines and the direct sum is used. - // (0, 0) is inside every window above. - let i = (14 * src_rect.width() as usize + 14) * 4; - img.data[i] = 0.5 / 255.0; - assert!(surface_8bit(&img, out, &ctx, 4, 0.1, 26).is_none()); - } - - #[test] - fn motion_kernel_matches_the_per_pixel_samples() { - // Noisy RGBA with some transparent pixels; the output reaches the source edge. - let src_rect = Rect::new(-30, -30, 50, 40); - let mut img = Image::new(src_rect, 4); - let mut s = 0x1b87_3593u32; - for px in img.data.as_chunks_mut::<4>().0 { - for v in px.iter_mut() { - s ^= s << 13; - s ^= s >> 17; - s ^= s << 5; - *v = (s % 1000) as f32 / 999.0; - } - if s.is_multiple_of(5) { - px[3] = 0.0; - } - } - let out = Rect::new(-12, -6, 30, 22); - for alpha in [true, false] { - let ctx = Ctx { bounds: src_rect, mode: crate::ColorMode::Rgb, alpha }; - for (angle, distance) in [(0.0, 1.0), (0.0, 9.0), (30.0, 7.0), (90.0, 12.0), (-45.0, 20.0), (137.0, 33.5), (200.0, 40.0)] { - let fast = motion(&img, out, &ctx, angle, distance); - let offs = motion_offsets(angle, distance); - let slow = average_samples(&img, out, &ctx, |x, y, pts| pts.extend(offs.iter().map(|&(dx, dy)| (x + dx, y + dy)))); - let err = slow.iter().zip(&fast).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); - assert!(err < 1e-5, "alpha {alpha} angle {angle} distance {distance}: max error {err}"); - } - } - } - - /// The direct sum with f64 accumulators: the reference both fast paths are held to. - fn surface_reference(src: &Image, out: Rect, ctx: &Ctx, r: i32, t: f32) -> Vec { - let n = src.ch; - let cc = if ctx.alpha { n - 1 } else { n }; - let mut res = Vec::new(); - for y in out.y0..out.y1 { - for x in out.x0..out.x1 { - let p = src.px(x, y); - for &v0 in p.iter().take(cc) { - let c = res.len() % n; - let (mut acc, mut wsum) = (0.0f64, 0.0f64); - for yy in y - r..=y + r { - for xx in x - r..=x + r { - if ctx.alpha && src.get(xx, yy, n - 1) <= 0.0 { - continue; - } - let v = src.get(xx, yy, c); - let w = (1.0 - (v - v0).abs() / t).max(0.0); - acc += f64::from(v) * f64::from(w); - wsum += f64::from(w); - } - } - res.push(if wsum > 0.0 { (acc / wsum) as f32 } else { v0 }); - } - if ctx.alpha { - res.push(p[n - 1]); - } - } - } - res - } - - #[test] - fn surface_blur_ranked_sums_match_the_weighted_window_at_any_depth() { - // 16-bit levels and arbitrary floats (including negatives and values above 1), with some - // fully transparent pixels, which the sum skips. - for (quant, channels, alpha) in [(Some(65535.0f32), 4, true), (None, 4, true), (None, 1, false)] { - let src_rect = Rect::new(-20, -20, 48, 40); - let mut img = Image::new(src_rect, channels); - let mut s = 0x1b87_3593u32; - for px in img.data.chunks_mut(channels) { - for v in px.iter_mut() { - s ^= s << 13; - s ^= s >> 17; - s ^= s << 5; - let raw = (s % 10_000) as f32 / 10_000.0; - *v = quant.map_or(raw * 1.5 - 0.25, |q| (raw * q).round() / q); - } - if alpha && s.is_multiple_of(7) { - px[channels - 1] = 0.0; - } - } - let ctx = Ctx { bounds: src_rect, mode: crate::ColorMode::Rgb, alpha }; - // The output reaches the source edge, where samples read as 0. - let out = Rect::new(-6, 0, 30, 22); - for (r, threshold) in [(1, 2.0), (4, 15.0), (12, 60.0), (16, 255.0)] { - let t = (threshold / 255.0) * 2.5; - let ranked = surface_ranked(&img, out, &ctx, r, t).expect("finite input"); - let reference = surface_reference(&img, out, &ctx, r, t); - assert_eq!(ranked.len(), reference.len()); - let err = reference.iter().zip(&ranked).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); - assert!(err < 1e-6, "{quant:?} r {r} threshold {threshold}: max error {err}"); - } - } - } - - #[test] - fn surface_blur_ranked_declines_non_finite_samples_and_handles_empty_output() { - let src_rect = Rect::new(0, 0, 8, 8); - let mut img = Image::new(src_rect, 1); - img.data.fill(0.5); - let ctx = Ctx { bounds: src_rect, mode: crate::ColorMode::Grayscale, alpha: false }; - assert_eq!(surface_ranked(&img, Rect::new(2, 2, 2, 6), &ctx, 2, 0.1), Some(Vec::new())); - img.data[9] = f32::NAN; - assert!(surface_ranked(&img, Rect::new(0, 0, 8, 8), &ctx, 2, 0.1).is_none()); - // The public entry still answers, through the direct sum. - assert_eq!(surface(&img, Rect::new(0, 0, 8, 8), &ctx, 12.0, 15.0).len(), 64); - } - - /// Release-mode timings of the direct sum and the ranked path on one 256 px tile of - /// 16-bit-like and float noise (`cargo test -p photocraft-algo --release -- --ignored --nocapture surface_timing`). - #[test] - #[ignore] - fn surface_timing() { - for (label, quant) in [("16-bit", Some(65535.0f32)), ("float", None)] { - for r in [2, 4, 8, 16, 32, 64, 100] { - let out = Rect::new(0, 0, 256, 256); - let src_rect = out.inflate(r); - let mut img = Image::new(src_rect, 4); - let mut s = 0x2545_f491u32; - let len = img.data.len(); - for (i, v) in img.data.iter_mut().enumerate() { - s ^= s << 13; - s ^= s >> 17; - s ^= s << 5; - // Smooth gradient plus noise, so the threshold keeps a realistic share. - let x = (i / 4) as f32 / len as f32 * 4.0; - let raw = (0.5 + 0.4 * (x * 6.0).sin() + (s % 1000) as f32 / 20000.0).clamp(0.0, 1.0); - *v = quant.map_or(raw, |q| (raw * q).round() / q); - } - let ctx = Ctx { bounds: src_rect, mode: crate::ColorMode::Rgb, alpha: true }; - let t = (15.0 / 255.0) * 2.5; - let a = std::time::Instant::now(); - let direct = surface_direct(&img, out, &ctx, r, t); - let td = a.elapsed(); - let a = std::time::Instant::now(); - let ranked = surface_ranked(&img, out, &ctx, r, t).expect("finite"); - let tr = a.elapsed(); - let err = direct.iter().zip(&ranked).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); - println!("{label} r {r:3}: direct {td:>10.2?} ranked {tr:>10.2?} max err {err:.2e}"); - } - } - } - - /// A column strip's passes stop between passes once cancelled, not only before the strip - /// (#6205); uncancelled, every pass runs. - #[test] - fn line_passes_stop_between_passes_when_cancelled() { - use std::sync::atomic::{AtomicUsize, Ordering}; - let (radii, w, len) = ([2usize, 3, 2], 4usize, 50usize); - let reach: usize = radii.iter().sum(); - let line: Vec = (0..(len + 2 * reach) * w).map(|i| (i % 7) as f32 + 1.0).collect(); - let run = |ctl: &Interrupt| { - let mut s = Scratch { line: line.clone(), ..Scratch::default() }; - let mut dst = vec![0.0f32; len * w]; - line_passes(&mut dst, w, &radii, &mut s, ctl); - dst - }; - assert!(run(&Interrupt::NONE).iter().all(|v| *v > 0.0)); - let calls = AtomicUsize::new(0); - let cancel = || calls.fetch_add(1, Ordering::SeqCst) >= 1; - // Cancelled after the first pass: the last pass (the one writing `dst`) never runs. - assert!(run(&Interrupt::cancel_only(&cancel)).iter().all(|v| *v == 0.0)); - assert_eq!(calls.load(Ordering::SeqCst), 2); - } - - /// A box blur cancelled at any of its checks returns `None` (never a half-blurred result); - /// one that is asked but never cancelled is bit-identical to the uninterruptible run. - #[test] - fn box_blur_honours_a_cancel_at_every_check() { - use std::sync::atomic::{AtomicUsize, Ordering}; - let (n, src) = (4usize, Rect::new(0, 0, 150, 90)); - let px: Vec = (0..src.width() as usize * src.height() as usize * n).map(|i| (i as f32 * 0.13).sin() * 0.5 + 0.5).collect(); - let read = |r: Rect, buf: &mut Vec| { - buf.clear(); - let (x0, x1) = ((r.x0 * n as i32) as usize, (r.x1 * n as i32) as usize); - let row = r.y0 as usize * src.width() as usize * n; - buf.extend_from_slice(&px[row + x0..row + x1]); - }; - let Some(boxes) = box_widths(&FilterParams::GaussianBlur { radius: 12.0 }) else { panic!("box passes") }; - let out = Rect::new(-5, 3, 155, 80); - let want = box_blur(src, &read, out, n, true, &boxes, &Interrupt::NONE).unwrap(); - let checks = AtomicUsize::new(0); - let count = || { - checks.fetch_add(1, Ordering::SeqCst); - false - }; - let got = box_blur(src, &read, out, n, true, &boxes, &Interrupt::cancel_only(&count)).unwrap(); - assert_eq!(got.len(), want.len()); - for ((ta, a), (tb, b)) in got.iter().zip(&want) { - assert_eq!(ta, tb); - assert!(a.iter().zip(b).all(|(x, y)| x.to_bits() == y.to_bits()), "strip {ta:?} differs"); - } - let total = checks.load(Ordering::SeqCst); - for k in (0..total).step_by((total / 40).max(1)) { - let seen = AtomicUsize::new(0); - let cancel = || seen.fetch_add(1, Ordering::SeqCst) >= k; - assert!(box_blur(src, &read, out, n, true, &boxes, &Interrupt::cancel_only(&cancel)).is_none(), "cancelled at check {k}"); - } - } -} +mod tests; diff --git a/crates/algo/src/blur/tests.rs b/crates/algo/src/blur/tests.rs new file mode 100644 index 0000000000..32256bc954 --- /dev/null +++ b/crates/algo/src/blur/tests.rs @@ -0,0 +1,460 @@ +use super::*; +use photocraft_color::{ColorMode, PixelFormat, SampleType}; +use photocraft_raster::Surface; + +#[test] +fn radial_blur_samples_large_arcs_beyond_64_intervals() { + let bounds = Rect::new(0, 0, 1000, 1000); + let out = Rect::new(999, 500, 1000, 501); + let ctx = Ctx { bounds, mode: photocraft_color::ColorMode::Grayscale, alpha: false }; + let mut img = Image::new(bounds, 1); + let (cx, cy) = (500.0f32, 500.0f32); + let (x, y) = (999.5f32, 500.5f32); + let (dx, dy) = (x - cx, y - cy); + let arc = 100.0f32.to_radians(); + let count = radial_intervals(arc * dx.hypot(dy), RadialQuality::Good); + assert_eq!(count, 256); + assert_eq!(radial_intervals(f32::INFINITY, RadialQuality::Draft), 64); + assert_eq!(radial_intervals(f32::INFINITY, RadialQuality::Good), 256); + assert_eq!(radial_intervals(f32::INFINITY, RadialQuality::Best), 4096); + assert_eq!(radial_intervals(f32::NAN, RadialQuality::Best), 1); + + // Put a small bright patch halfway between two samples from the former 64-interval + // limit. Dense sampling should pick it up; the coarse path misses it entirely. + let sparse_midpoint = (31.5 / 64.0 - 0.5) * arc; + let (s, c) = sparse_midpoint.sin_cos(); + let px = (cx + dx * c - dy * s - 0.5).round() as i32; + let py = (cy + dx * s + dy * c - 0.5).round() as i32; + for yy in py - 1..=py + 1 { + for xx in px - 1..=px + 1 { + let index = (yy - bounds.y0) as usize * bounds.width() as usize + (xx - bounds.x0) as usize; + img.data[index] = 1.0; + } + } + + let sample_path = |x: f32, y: f32, pts: &mut Vec<(f32, f32)>, intervals: usize| { + let (dx, dy) = (x - cx, y - cy); + for i in 0..=intervals { + let t = (i as f32 / intervals as f32 - 0.5) * arc; + let (s, c) = t.sin_cos(); + pts.push((cx + dx * c - dy * s, cy + dx * s + dy * c)); + } + }; + let actual = radial(&img, out, &ctx, 100.0, RadialMethod::Spin, RadialQuality::Good, (0.5, 0.5))[0]; + let expected = average_samples(&img, out, &ctx, |x, y, pts| sample_path(x, y, pts, 8192))[0]; + let coarse = average_samples(&img, out, &ctx, |x, y, pts| sample_path(x, y, pts, 64))[0]; + + assert!(actual > 0.001, "dense radial samples should resolve the bright patch, got {actual}"); + assert!((actual - expected).abs() < 0.0015, "radial result {actual} differs from dense reference {expected}"); + assert!(coarse < expected * 0.1, "former 64-interval sampling unexpectedly resolved the patch: {coarse} vs {expected}"); +} + +#[test] +fn fixed_channel_convolution_matches_scalar_tap_order() { + fn check() { + for width in [1, 7, 256] { + for radius in [0.0, 0.5, 3.0, 4.0] { + let k = gaussian_kernel(radius); + let src: Vec = (0..(width + k.len() - 1) * N).map(|i| ((i * 73) % 251) as f32 / 250.0).collect(); + let mut expected = vec![0.0f32; width * N]; + for x in 0..width { + for (i, w) in k.iter().enumerate() { + for c in 0..N { + expected[x * N + c] += src[(x + i) * N + c] * w; + } + } + } + let mut actual = vec![0.0f32; width * N]; + conv_row::(&src, &mut actual, &k); + assert_eq!(actual, expected, "channels={N} width={width} radius={radius}"); + } + } + } + check::<1>(); + check::<2>(); + check::<3>(); + check::<4>(); + check::<5>(); +} + +#[test] +fn box_gaussian_matches_exact_kernel() { + // A hard vertical edge (premultiplied RGBA-ish, 2 channels) blurred with σ = 12. + let src_rect = Rect::new(-60, -60, 180, 68); + let mut img = Image::new(src_rect, 2); + for y in src_rect.y0..src_rect.y1 { + for x in src_rect.x0..src_rect.x1 { + let i = ((y - src_rect.y0) as usize * src_rect.width() as usize + (x - src_rect.x0) as usize) * 2; + img.data[i] = if x < 60 { 1.0 } else { 0.0 }; + img.data[i + 1] = 1.0; + } + } + let out = Rect::new(0, 0, 120, 8); + let k = gaussian_kernel(12.0); + let exact = conv_sep(&img, out, &k, &k, true); + let fast = box_passes(&img, out, true, &boxes_for_gauss(12.0, 3)); + let err = exact.iter().zip(&fast).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); + assert!(err < 0.02, "max error {err}"); + assert_eq!(boxes_for_gauss(10.0, 3).len(), 3); +} + +#[test] +fn box_passes_match_the_direct_box_kernel() { + // Noisy RGBA with varying alpha, so premultiplication and every channel are exercised. + for r in [5usize, 17, 60] { + let (w, h, m) = (40, 24, r as i32 + 2); + let src_rect = Rect::new(-m, -m, w + m, h + m); + let mut img = Image::new(src_rect, 4); + let mut s = 0x9e37_79b9u32; + for v in img.data.iter_mut() { + s ^= s << 13; + s ^= s >> 17; + s ^= s << 5; + *v = (s % 256) as f32 / 255.0; + } + let out = Rect::new(0, 0, w, h); + let k = vec![1.0 / (2 * r + 1) as f32; 2 * r + 1]; + let direct = conv_sep(&img, out, &k, &k, true); + let ctx = Ctx { bounds: src_rect, mode: crate::ColorMode::Rgb, alpha: true }; + let fast = boxed(&img, out, &ctx, r as f32); + let err = direct.iter().zip(&fast).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); + assert!(err < 1e-5, "radius {r}: max error {err}"); + } +} + +/// The definition the running sums must match: each box applied in turn as a direct +/// convolution (cost per pixel proportional to the radius) to `img`, which covers `out` grown +/// by every box's reach (its own edge handling included). +fn direct_boxes(img: &Image, out: Rect, boxes: &[usize], alpha: bool) -> Vec { + let mut cur = img.clone(); + let mut left: i32 = boxes.iter().map(|w| (w / 2) as i32).sum(); + for &w in boxes { + left -= (w / 2) as i32; + let k = vec![1.0 / w as f32; w]; + let rect = out.inflate(left); + cur = Image { rect, ch: img.ch, data: conv_sep(&cur, rect, &k, &k, alpha) }; + } + cur.data +} + +/// Noisy pixels over `r` (alpha varying, some fully transparent). +fn noisy(fmt: PixelFormat, r: Rect, seed: u32) -> Surface { + let mut s = Surface::new(fmt); + let mut st = seed; + let mut v = Vec::new(); + for _ in 0..r.width() * r.height() { + for c in 0..fmt.channels() { + st ^= st << 13; + st ^= st >> 17; + st ^= st << 5; + let x = (st % 256) as f32 / 255.0; + v.push(if fmt.alpha && c + 1 == fmt.channels() && st.is_multiple_of(5) { 0.0 } else { x }); + } + } + s.write_region(r, &v); + s +} + +#[test] +fn layer_box_blurs_match_direct_convolution_at_any_radius() { + // Gaussian and Box Blur at radii up to several times the layer (37 × 23), filtered as a + // document layer (canvas edge repeated, as Photoshop does) and on their own (transparent + // beyond), at every depth, with and without alpha, 1 to 5 channels. + let canvas = Rect::new(0, 0, 37, 23); + let formats = [ + PixelFormat::RGBA8, + PixelFormat::RGBA16, + PixelFormat::RGBA32F, + PixelFormat::GRAY8, + PixelFormat::CMYKA8, + PixelFormat::new(ColorMode::Lab, SampleType::F32, false), + ]; + let params = [ + FilterParams::GaussianBlur { radius: 4.5 }, + FilterParams::GaussianBlur { radius: 9.3 }, + FilterParams::GaussianBlur { radius: 40.0 }, + FilterParams::BoxBlur { radius: 5.0 }, + FilterParams::BoxBlur { radius: 70.0 }, + ]; + for (i, fmt) in formats.into_iter().enumerate() { + let s = noisy(fmt, canvas, 0x9e37_79b9 + i as u32); + // A level of the depth (colour and alpha are each rounded on write) plus float noise. + let tol = match fmt.sample { + SampleType::U8 => 1.0 / 255.0, + SampleType::U16 => 1.0 / 65535.0, + _ => 0.0, + } + 2e-5; + for p in ¶ms { + let boxes = box_widths(p).expect("a box-pass blur"); + let reach: i32 = boxes.iter().map(|w| (w / 2) as i32).sum(); + let area = crate::output_area(p, s.content_bounds(), canvas, None); + for (got, img, out) in [ + (crate::apply_in(&s, p, area, canvas, None, canvas), Image::read_clamped(&s, canvas.inflate(reach), canvas), canvas), + (crate::apply(&s, p, area, canvas, None), Image::read(&s, area.inflate(reach)), area), + ] { + // Compared alpha-weighted: colour is meaningless where (nearly) transparent. + let (mut got, mut want) = (got.read_region(out), direct_boxes(&img, out, &boxes, fmt.alpha)); + premultiply(&mut got, img.ch, fmt.alpha); + premultiply(&mut want, img.ch, fmt.alpha); + let err = got.iter().zip(&want).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); + assert!(err <= tol, "{} on {fmt:?} over {out:?}: max error {err}", p.label()); + } + } + } +} + +#[test] +fn layer_box_blurs_mix_by_the_selection_and_stop_when_cancelled() { + let canvas = Rect::new(0, 0, 37, 23); + let s = noisy(PixelFormat::RGBA32F, canvas, 7); + let p = FilterParams::GaussianBlur { radius: 12.0 }; + let full = crate::apply_in(&s, &p, canvas, canvas, None, canvas); + let half = Surface::with_default(PixelFormat::new(ColorMode::Grayscale, SampleType::F32, false), &[0.5]); + let mixed = crate::apply_in(&s, &p, canvas, canvas, Some(&half), canvas); + for (x, y) in [(0, 0), (18, 11), (36, 22)] { + let (o, f, m) = (s.pixel(x, y), full.pixel(x, y), mixed.pixel(x, y)); + assert!((m[3] - (o[3] + f[3]) / 2.0).abs() < 1e-5, "({x},{y}) alpha"); + for c in 0..3 { + assert!((m[c] * m[3] - (o[c] * o[3] + f[c] * f[3]) / 2.0).abs() < 1e-5, "({x},{y}) premultiplied channel {c}"); + } + } + let cancel = || true; + let ctl = Interrupt::cancel_only(&cancel); + assert!(crate::apply_in_with(&s, &p, canvas, canvas, None, canvas, &ctl).is_none()); +} + +#[test] +fn surface_blur_8bit_histogram_matches_the_direct_sum() { + // 8-bit levels with some fully transparent pixels, which the sum skips. + let src_rect = Rect::new(-14, -14, 40, 34); + let mut img = Image::new(src_rect, 4); + let mut s = 0x6c07_8965u32; + for px in img.data.as_chunks_mut::<4>().0 { + for v in px.iter_mut() { + s ^= s << 13; + s ^= s >> 17; + s ^= s << 5; + *v = (s % 256) as f32 / 255.0; + } + if s.is_multiple_of(7) { + px[3] = 0.0; + } + } + let ctx = Ctx { bounds: src_rect, mode: crate::ColorMode::Rgb, alpha: true }; + // The output reaches the source edge, where samples read as transparent. + let out = Rect::new(-2, 0, 26, 20); + for (r, threshold) in [(1, 2.0), (4, 15.0), (12, 60.0), (12, 255.0)] { + let t = (threshold / 255.0) * 2.5; + let reach = ((t * 255.0f32).ceil() as usize).min(255); + let fast = surface_8bit(&img, out, &ctx, r, t, reach).expect("8-bit input"); + let direct = surface_direct(&img, out, &ctx, r, t); + let err = direct.iter().zip(&fast).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); + assert!(err < 1e-5, "r {r} threshold {threshold}: max error {err}"); + } + // Not 8-bit: the histogram declines and the direct sum is used. + // (0, 0) is inside every window above. + let i = (14 * src_rect.width() as usize + 14) * 4; + img.data[i] = 0.5 / 255.0; + assert!(surface_8bit(&img, out, &ctx, 4, 0.1, 26).is_none()); +} + +#[test] +fn motion_kernel_matches_the_per_pixel_samples() { + // Noisy RGBA with some transparent pixels; the output reaches the source edge. + let src_rect = Rect::new(-30, -30, 50, 40); + let mut img = Image::new(src_rect, 4); + let mut s = 0x1b87_3593u32; + for px in img.data.as_chunks_mut::<4>().0 { + for v in px.iter_mut() { + s ^= s << 13; + s ^= s >> 17; + s ^= s << 5; + *v = (s % 1000) as f32 / 999.0; + } + if s.is_multiple_of(5) { + px[3] = 0.0; + } + } + let out = Rect::new(-12, -6, 30, 22); + for alpha in [true, false] { + let ctx = Ctx { bounds: src_rect, mode: crate::ColorMode::Rgb, alpha }; + for (angle, distance) in [(0.0, 1.0), (0.0, 9.0), (30.0, 7.0), (90.0, 12.0), (-45.0, 20.0), (137.0, 33.5), (200.0, 40.0)] { + let fast = motion(&img, out, &ctx, angle, distance); + let offs = motion_offsets(angle, distance); + let slow = average_samples(&img, out, &ctx, |x, y, pts| pts.extend(offs.iter().map(|&(dx, dy)| (x + dx, y + dy)))); + let err = slow.iter().zip(&fast).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); + assert!(err < 1e-5, "alpha {alpha} angle {angle} distance {distance}: max error {err}"); + } + } +} + +/// The direct sum with f64 accumulators: the reference both fast paths are held to. +fn surface_reference(src: &Image, out: Rect, ctx: &Ctx, r: i32, t: f32) -> Vec { + let n = src.ch; + let cc = if ctx.alpha { n - 1 } else { n }; + let mut res = Vec::new(); + for y in out.y0..out.y1 { + for x in out.x0..out.x1 { + let p = src.px(x, y); + for &v0 in p.iter().take(cc) { + let c = res.len() % n; + let (mut acc, mut wsum) = (0.0f64, 0.0f64); + for yy in y - r..=y + r { + for xx in x - r..=x + r { + if ctx.alpha && src.get(xx, yy, n - 1) <= 0.0 { + continue; + } + let v = src.get(xx, yy, c); + let w = (1.0 - (v - v0).abs() / t).max(0.0); + acc += f64::from(v) * f64::from(w); + wsum += f64::from(w); + } + } + res.push(if wsum > 0.0 { (acc / wsum) as f32 } else { v0 }); + } + if ctx.alpha { + res.push(p[n - 1]); + } + } + } + res +} + +#[test] +fn surface_blur_ranked_sums_match_the_weighted_window_at_any_depth() { + // 16-bit levels and arbitrary floats (including negatives and values above 1), with some + // fully transparent pixels, which the sum skips. + for (quant, channels, alpha) in [(Some(65535.0f32), 4, true), (None, 4, true), (None, 1, false)] { + let src_rect = Rect::new(-20, -20, 48, 40); + let mut img = Image::new(src_rect, channels); + let mut s = 0x1b87_3593u32; + for px in img.data.chunks_mut(channels) { + for v in px.iter_mut() { + s ^= s << 13; + s ^= s >> 17; + s ^= s << 5; + let raw = (s % 10_000) as f32 / 10_000.0; + *v = quant.map_or(raw * 1.5 - 0.25, |q| (raw * q).round() / q); + } + if alpha && s.is_multiple_of(7) { + px[channels - 1] = 0.0; + } + } + let ctx = Ctx { bounds: src_rect, mode: crate::ColorMode::Rgb, alpha }; + // The output reaches the source edge, where samples read as 0. + let out = Rect::new(-6, 0, 30, 22); + for (r, threshold) in [(1, 2.0), (4, 15.0), (12, 60.0), (16, 255.0)] { + let t = (threshold / 255.0) * 2.5; + let ranked = surface_ranked(&img, out, &ctx, r, t).expect("finite input"); + let reference = surface_reference(&img, out, &ctx, r, t); + assert_eq!(ranked.len(), reference.len()); + let err = reference.iter().zip(&ranked).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); + assert!(err < 1e-6, "{quant:?} r {r} threshold {threshold}: max error {err}"); + } + } +} + +#[test] +fn surface_blur_ranked_declines_non_finite_samples_and_handles_empty_output() { + let src_rect = Rect::new(0, 0, 8, 8); + let mut img = Image::new(src_rect, 1); + img.data.fill(0.5); + let ctx = Ctx { bounds: src_rect, mode: crate::ColorMode::Grayscale, alpha: false }; + assert_eq!(surface_ranked(&img, Rect::new(2, 2, 2, 6), &ctx, 2, 0.1), Some(Vec::new())); + img.data[9] = f32::NAN; + assert!(surface_ranked(&img, Rect::new(0, 0, 8, 8), &ctx, 2, 0.1).is_none()); + // The public entry still answers, through the direct sum. + assert_eq!(surface(&img, Rect::new(0, 0, 8, 8), &ctx, 12.0, 15.0).len(), 64); +} + +/// Release-mode timings of the direct sum and the ranked path on one 256 px tile of +/// 16-bit-like and float noise (`cargo test -p photocraft-algo --release -- --ignored --nocapture surface_timing`). +#[test] +#[ignore] +fn surface_timing() { + for (label, quant) in [("16-bit", Some(65535.0f32)), ("float", None)] { + for r in [2, 4, 8, 16, 32, 64, 100] { + let out = Rect::new(0, 0, 256, 256); + let src_rect = out.inflate(r); + let mut img = Image::new(src_rect, 4); + let mut s = 0x2545_f491u32; + let len = img.data.len(); + for (i, v) in img.data.iter_mut().enumerate() { + s ^= s << 13; + s ^= s >> 17; + s ^= s << 5; + // Smooth gradient plus noise, so the threshold keeps a realistic share. + let x = (i / 4) as f32 / len as f32 * 4.0; + let raw = (0.5 + 0.4 * (x * 6.0).sin() + (s % 1000) as f32 / 20000.0).clamp(0.0, 1.0); + *v = quant.map_or(raw, |q| (raw * q).round() / q); + } + let ctx = Ctx { bounds: src_rect, mode: crate::ColorMode::Rgb, alpha: true }; + let t = (15.0 / 255.0) * 2.5; + let a = std::time::Instant::now(); + let direct = surface_direct(&img, out, &ctx, r, t); + let td = a.elapsed(); + let a = std::time::Instant::now(); + let ranked = surface_ranked(&img, out, &ctx, r, t).expect("finite"); + let tr = a.elapsed(); + let err = direct.iter().zip(&ranked).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); + println!("{label} r {r:3}: direct {td:>10.2?} ranked {tr:>10.2?} max err {err:.2e}"); + } + } +} + +/// A column strip's passes stop between passes once cancelled, not only before the strip +/// (#6205); uncancelled, every pass runs. +#[test] +fn line_passes_stop_between_passes_when_cancelled() { + use std::sync::atomic::{AtomicUsize, Ordering}; + let (radii, w, len) = ([2usize, 3, 2], 4usize, 50usize); + let reach: usize = radii.iter().sum(); + let line: Vec = (0..(len + 2 * reach) * w).map(|i| (i % 7) as f32 + 1.0).collect(); + let run = |ctl: &Interrupt| { + let mut s = Scratch { line: line.clone(), ..Scratch::default() }; + let mut dst = vec![0.0f32; len * w]; + line_passes(&mut dst, w, &radii, &mut s, ctl); + dst + }; + assert!(run(&Interrupt::NONE).iter().all(|v| *v > 0.0)); + let calls = AtomicUsize::new(0); + let cancel = || calls.fetch_add(1, Ordering::SeqCst) >= 1; + // Cancelled after the first pass: the last pass (the one writing `dst`) never runs. + assert!(run(&Interrupt::cancel_only(&cancel)).iter().all(|v| *v == 0.0)); + assert_eq!(calls.load(Ordering::SeqCst), 2); +} + +/// A box blur cancelled at any of its checks returns `None` (never a half-blurred result); +/// one that is asked but never cancelled is bit-identical to the uninterruptible run. +#[test] +fn box_blur_honours_a_cancel_at_every_check() { + use std::sync::atomic::{AtomicUsize, Ordering}; + let (n, src) = (4usize, Rect::new(0, 0, 150, 90)); + let px: Vec = (0..src.width() as usize * src.height() as usize * n).map(|i| (i as f32 * 0.13).sin() * 0.5 + 0.5).collect(); + let read = |r: Rect, buf: &mut Vec| { + buf.clear(); + let (x0, x1) = ((r.x0 * n as i32) as usize, (r.x1 * n as i32) as usize); + let row = r.y0 as usize * src.width() as usize * n; + buf.extend_from_slice(&px[row + x0..row + x1]); + }; + let Some(boxes) = box_widths(&FilterParams::GaussianBlur { radius: 12.0 }) else { panic!("box passes") }; + let out = Rect::new(-5, 3, 155, 80); + let want = box_blur(src, &read, out, n, true, &boxes, &Interrupt::NONE).unwrap(); + let checks = AtomicUsize::new(0); + let count = || { + checks.fetch_add(1, Ordering::SeqCst); + false + }; + let got = box_blur(src, &read, out, n, true, &boxes, &Interrupt::cancel_only(&count)).unwrap(); + assert_eq!(got.len(), want.len()); + for ((ta, a), (tb, b)) in got.iter().zip(&want) { + assert_eq!(ta, tb); + assert!(a.iter().zip(b).all(|(x, y)| x.to_bits() == y.to_bits()), "strip {ta:?} differs"); + } + let total = checks.load(Ordering::SeqCst); + for k in (0..total).step_by((total / 40).max(1)) { + let seen = AtomicUsize::new(0); + let cancel = || seen.fetch_add(1, Ordering::SeqCst) >= k; + assert!(box_blur(src, &read, out, n, true, &boxes, &Interrupt::cancel_only(&cancel)).is_none(), "cancelled at check {k}"); + } +} diff --git a/crates/algo/src/blur2.rs b/crates/algo/src/blur2.rs index dc57f39adb..5096a9fb9a 100644 --- a/crates/algo/src/blur2.rs +++ b/crates/algo/src/blur2.rs @@ -181,7 +181,6 @@ fn conv_spans(src: &Image, out: Rect, ctx: &Ctx, spans: &Spans) -> Vec { } #[cfg(test)] -#[path = "shape_blur_tests.rs"] mod shape_tests; // ---------- smart blur ---------- @@ -362,7 +361,6 @@ fn smart_rows(src: &Image, out: Rect, inner: Rect } #[cfg(test)] -#[path = "smart_blur_tests.rs"] mod smart_tests; // ---------- lens blur ---------- diff --git a/crates/algo/src/shape_blur_tests.rs b/crates/algo/src/blur2/shape_tests.rs similarity index 100% rename from crates/algo/src/shape_blur_tests.rs rename to crates/algo/src/blur2/shape_tests.rs diff --git a/crates/algo/src/smart_blur_tests.rs b/crates/algo/src/blur2/smart_tests.rs similarity index 100% rename from crates/algo/src/smart_blur_tests.rs rename to crates/algo/src/blur2/smart_tests.rs diff --git a/crates/algo/src/content_aware.rs b/crates/algo/src/content_aware.rs index 84b15a215b..955a911119 100644 --- a/crates/algo/src/content_aware.rs +++ b/crates/algo/src/content_aware.rs @@ -723,450 +723,4 @@ pub fn default_brush_size(hole: Rect) -> f64 { } #[cfg(test)] -mod tests { - use super::mosaic_size; - - fn blank(w: usize, h: usize) -> (usize, usize) { - (w, h) - } - - #[test] - fn a_thin_image_with_turned_variants_does_not_get_a_quadratic_mosaic() { - // 40000×1 plus its 90° copy (1×40000): about 1.6 billion mosaic cells for 80000 pixels. - assert_eq!(mosaic_size(40_000, 1, 8, &[blank(1, 40_000)]), None); - assert_eq!(mosaic_size(usize::MAX, 1, 8, &[blank(1, 1)]), None); - assert_eq!(mosaic_size(100, 100, 8, &[blank(100, 100)]), Some((208, 108))); - } - - use super::*; - - /// Vertical stripes (period 6) in grey, with a hole in the middle. - fn stripes(w: usize, h: usize) -> (Vec, Vec) { - let img: Vec = (0..w * h).map(|i| if (i % w) % 6 < 3 { 0.2 } else { 0.8 }).collect(); - let hole: Vec = (0..w * h).map(|i| (i % w).abs_diff(w / 2) < 4 && (i / w).abs_diff(h / 2) < 4).collect(); - (img, hole) - } - - #[test] - fn strokes_paint_their_path_and_leave_a_mismatched_mask_alone() { - let area = Rect::new(10, 20, 50, 40); - let (w, h) = (40, 20); - let strokes = [ - SamplingStroke { add: true, size: 6.0, points: vec![[12.0, 25.0], [40.0, 25.0], [45.0, 35.0]] }, - SamplingStroke { add: false, size: 3.0, points: vec![[30.0, 25.0]] }, - SamplingStroke { add: true, size: 2.0, points: Vec::new() }, - ]; - let mut mask = vec![false; w * h]; - paint_strokes(&mut mask, area, &strokes); - // The same pixels as testing every pixel against every segment of each stroke in turn. - let mut want = vec![false; w * h]; - for s in &strokes { - let r2 = (s.size / 2.0).max(0.5).powi(2); - let segs: Vec<_> = if s.points.len() == 1 { vec![(s.points[0], s.points[0])] } else { s.points.windows(2).map(|p| (p[0], p[1])).collect() }; - for (i, m) in want.iter_mut().enumerate() { - let c = [f64::from(area.x0) + (i % w) as f64 + 0.5, f64::from(area.y0) + (i / w) as f64 + 0.5]; - if segs.iter().any(|(a, b)| seg_dist2(c, *a, *b) <= r2) { - *m = s.add; - } - } - } - assert_eq!(mask, want); - assert!(mask[5 * w + 10] && !mask[5 * w + 20], "added along the path, cleared under the subtracting dab"); - // A mask shorter or longer than the area is not touched (and nothing panics). - for len in [0, 7, w * h - 1, w * h + 3] { - let mut short = vec![false; len]; - paint_strokes(&mut short, area, &strokes); - assert!(short.iter().all(|v| !v), "len {len}"); - } - // Hostile coordinates stay inside the area. - let mut m = vec![false; w * h]; - let wild = [SamplingStroke { add: true, size: 5000.0, points: vec![[f64::MAX, -1e300], [f64::NAN, 1e7]] }]; - paint_strokes(&mut m, area, &wild); - } - - #[test] - fn cancelled_fill_stops_and_progress_reaches_one() { - use std::sync::atomic::{AtomicU32, Ordering}; - let (w, h) = (60, 40); - let (img, hole) = stripes(w, h); - let source = vec![true; w * h]; - let yes = || true; - let cancelled = photocraft_raster::Interrupt::cancel_only(&yes); - assert!(fill_with(w, h, 1, &img, &hole, &source, &FillOptions::default(), &cancelled).is_err()); - let last = AtomicU32::new(0); - let no = || false; - let progress = |f: f32| { - assert!(f >= f32::from_bits(last.load(Ordering::Relaxed)), "progress went backwards"); - last.store(f.to_bits(), Ordering::Relaxed); - }; - let out = fill_with(w, h, 1, &img, &hole, &source, &FillOptions::default(), &photocraft_raster::Interrupt::new(&no, &progress)).unwrap(); - assert_eq!(f32::from_bits(last.load(Ordering::Relaxed)), 1.0); - assert_eq!(out, fill(w, h, 1, &img, &hole, &source, &FillOptions::default()), "same result as the plain fill"); - } - - #[test] - fn filling_in_place_is_filling_a_copy() { - let (w, h) = (90, 70); - let rgb: Vec = noise(w, h, 4).iter().enumerate().map(|(i, v)| v * 0.5 + 0.3 * ((i / 3 % w) % 11 < 5) as u8 as f32).collect(); - let hole: Vec = (0..w * h).map(|i| (30..52).contains(&(i % w)) && (25..44).contains(&(i / w))).collect(); - let source: Vec = (0..w * h).map(|i| i % w < 75).collect(); - let none = Interrupt::NONE; - for opts in [FillOptions::default(), FillOptions { color_adaptation: Adapt::NONE, mirror: true, ..Default::default() }] { - let copy = fill_with(w, h, 3, &rgb, &hole, &source, &opts, &none).unwrap(); - let owned = fill_owned(w, h, 3, rgb.clone(), &hole, &source, &opts, &none).unwrap(); - assert_eq!(copy.iter().map(|v| v.to_bits()).collect::>(), owned.iter().map(|v| v.to_bits()).collect::>()); - // Only the hole changes. - assert!((0..w * h).all(|i| hole[i] || (0..3).all(|c| owned[i * 3 + c].to_bits() == rgb[i * 3 + c].to_bits()))); - } - // Nothing to copy from: the membrane, either way. - let nowhere = vec![false; w * h]; - let copy = fill_with(w, h, 3, &rgb, &hole, &nowhere, &FillOptions::default(), &none).unwrap(); - assert_eq!(copy, fill_owned(w, h, 3, rgb.clone(), &hole, &nowhere, &FillOptions::default(), &none).unwrap()); - } - - #[test] - fn auto_sampling_can_be_cancelled() { - let (w, h) = (200, 160); - let img: Vec = noise(w, h, 5).iter().enumerate().map(|(i, v)| v * 0.1 + if (i / 3) % w < 120 { 0.3 } else { 0.6 }).collect(); - let hole: Vec = (0..w * h).map(|i| (80..110).contains(&(i % w)) && (60..90).contains(&(i / w))).collect(); - let yes = || true; - assert!(auto_sampling_with(w, h, 3, &img, &hole, &Interrupt::cancel_only(&yes)).is_err()); - assert_eq!(auto_sampling_with(w, h, 3, &img, &hole, &Interrupt::NONE).unwrap(), auto_sampling(w, h, 3, &img, &hole)); - } - - #[test] - fn fills_only_the_hole_with_known_texture() { - let (w, h) = (48, 32); - let (img, hole) = stripes(w, h); - let src = vec![true; w * h]; - let out = fill(w, h, 1, &img, &hole, &src, &FillOptions { color_adaptation: Adapt::NONE, ..Default::default() }); - for i in 0..w * h { - if !hole[i] { - assert_eq!(out[i], img[i]); - } - } - // The hole is filled with stripe values, not a flat average. - let vals: Vec = (0..w * h).filter(|i| hole[*i]).map(|i| out[i]).collect(); - assert!(vals.iter().any(|v| *v < 0.35) && vals.iter().any(|v| *v > 0.65), "{vals:?}"); - } - - #[test] - fn sampling_area_restricts_sources() { - // Left half dark, right half bright; sampling only the right half fills bright. - let (w, h) = (40, 20); - let img: Vec = (0..w * h).map(|i| if i % w < 20 { 0.1 } else { 0.9 }).collect(); - let hole: Vec = (0..w * h).map(|i| (16..24).contains(&(i % w)) && (6..14).contains(&(i / w))).collect(); - let right: Vec = (0..w * h).map(|i| i % w >= 24).collect(); - let out = fill(w, h, 1, &img, &hole, &right, &FillOptions { color_adaptation: Adapt::NONE, ..Default::default() }); - let mean: f32 = (0..w * h).filter(|i| hole[*i]).map(|i| out[i]).sum::() / 64.0; - assert!(mean > 0.8, "mean {mean}"); - } - - #[test] - fn adaptations_run_and_stay_deterministic() { - let (w, h) = (32, 24); - let (img, hole) = stripes(w, h); - let rgb: Vec = img.iter().flat_map(|v| [*v, *v * 0.5, 1.0 - *v]).collect(); - let src = vec![true; w * h]; - let opts = FillOptions { color_adaptation: color_level("high"), rotations: rotation_level("low"), scale: true, mirror: true, seed: 7 }; - let a = fill(w, h, 3, &rgb, &hole, &src, &opts); - let b = fill(w, h, 3, &rgb, &hole, &src, &opts); - assert_eq!(a, b); - assert!(a.iter().all(|v| v.is_finite() && (0.0..=1.0).contains(v))); - } - - #[test] - fn color_adaptation_follows_a_gradient() { - // A horizontal brightness ramp with a hole: adaptation keeps the fill near the ramp. - let (w, h) = (40, 20); - let img: Vec = (0..w * h).map(|i| (i % w) as f32 / w as f32).collect(); - let hole: Vec = (0..w * h).map(|i| (14..26).contains(&(i % w)) && (5..15).contains(&(i / w))).collect(); - let src = vec![true; w * h]; - let out = fill(w, h, 1, &img, &hole, &src, &FillOptions { color_adaptation: color_level("veryHigh"), ..Default::default() }); - let err: f32 = (0..w * h).filter(|i| hole[*i]).map(|i| (out[i] - img[i]).abs()).sum::() / 120.0; - assert!(err < 0.12, "mean error {err}"); - } - - /// A vertical sky gradient (each row one colour) filled at every adaptation level stays the - /// gradient: no tinted blotch where the copied rows' colours were shifted per channel. - #[test] - fn color_adaptation_leaves_a_smooth_gradient_untinted() { - let (w, h) = (120, 60); - let row = |y: usize| { - let t = y as f32 / (h - 1) as f32; - [0.27 + 0.45 * t, 0.53 + 0.32 * t, 0.86 + 0.1 * t] - }; - let img: Vec = (0..w * h).flat_map(|i| row(i / w)).collect(); - let hole: Vec = (0..w * h).map(|i| (50..70).contains(&(i % w)) && (20..40).contains(&(i / w))).collect(); - let src = vec![true; w * h]; - for level in ["none", "default", "high", "veryHigh"] { - let out = fill(w, h, 3, &img, &hole, &src, &FillOptions { color_adaptation: color_level(level), ..Default::default() }); - let (out, img) = (&out, &img); - let worst = (0..w * h).filter(|i| hole[*i]).flat_map(|i| (0..3).map(move |c| (out[i * 3 + c] - img[i * 3 + c]).abs())).fold(0.0f32, f32::max); - assert!(worst < 3.0 / 255.0, "{level}: off by {}", worst * 255.0); - } - } - - /// I.i.d. noise: every value occurs once, so a filled pixel equal to an image pixel was copied. - fn noise(w: usize, h: usize, seed: u64) -> Vec { - let mut z = seed; - (0..w * h * 3) - .map(|_| { - z = z.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); - 0.2 + 0.6 * ((z >> 40) as f32 / (1u64 << 24) as f32) - }) - .collect() - } - - #[test] - fn sampling_window_is_photoshops() { - let canvas = Rect::new(0, 0, 800, 800); - let sq = |x0: i32, y0: i32, w: i32, h: i32| Rect::new(x0, y0, x0 + w, y0 + h); - // Photoshop 25.4's sampling overlay: a square of side 4·√(max(w,50)·max(h,50)) centred on - // the selection's bounds. - assert_eq!(sampling_window(sq(375, 375, 50, 50), canvas), sq(300, 300, 200, 200)); - assert_eq!(sampling_window(sq(350, 350, 100, 100), canvas), sq(200, 200, 400, 400)); - assert_eq!(sampling_window(sq(395, 395, 10, 10), canvas), sq(300, 300, 200, 200)); - assert_eq!(sampling_window(sq(370, 370, 60, 60), canvas), sq(280, 280, 240, 240)); - // Long selections (Photoshop's overlay, read off the screen to a pixel: 281, 399, 691). - assert_eq!(sampling_window(sq(350, 385, 100, 30), canvas), sq(258, 258, 283, 283)); - assert_eq!(sampling_window(sq(300, 375, 200, 50), canvas), sq(200, 200, 400, 400)); - assert_eq!(sampling_window(sq(250, 350, 300, 100), canvas), sq(53, 53, 693, 693)); - // At the canvas edge the square slides inwards rather than being cut. - assert_eq!(sampling_window(sq(10, 375, 50, 50), canvas), sq(0, 300, 200, 200)); - assert_eq!(sampling_window(sq(5, 5, 60, 60), canvas), sq(0, 0, 240, 240)); - // A canvas smaller than the square clips it; a very long selection keeps its length. - assert_eq!(sampling_window(sq(40, 40, 50, 50), Rect::new(0, 0, 150, 120)), Rect::new(0, 0, 150, 120)); - assert_eq!(sampling_window(sq(100, 995, 1800, 10), Rect::new(0, 0, 2000, 2000)), sq(100, 400, 1800, 1200)); - assert_eq!(sampling_window(Rect::EMPTY, canvas), Rect::EMPTY); - } - - #[test] - fn auto_sampling_keeps_what_looks_like_the_surroundings() { - // Grey texture, dark on the left, 50 levels brighter on the right; the hole is in the dark - // part near the boundary (Photoshop's Auto leaves the bright part out). - let (w, h) = (200, 200); - let tex = noise(w, h, 3); - let shade = |x: usize, band: bool| { - if band { - if (130..150).contains(&x) { 0.55 } else { 0.35 } - } else if x < 135 { - 0.35 - } else { - 0.55 - } - }; - for band in [false, true] { - let img: Vec = (0..w * h * 3).map(|i| shade((i / 3) % w, band) + (tex[i] - 0.5) * 0.1).collect(); - let hole: Vec = (0..w * h).map(|i| (75..125).contains(&(i % w)) && (75..125).contains(&(i / w))).collect(); - let area = auto_sampling(w, h, 3, &img, &hole); - let frac = |x0: usize, x1: usize| { - let n = (0..w * h).filter(|i| (x0..x1).contains(&(i % w)) && !hole[*i]).count(); - (0..w * h).filter(|i| (x0..x1).contains(&(i % w)) && area[*i]).count() as f32 / n as f32 - }; - assert!(hole.iter().zip(&area).all(|(hl, a)| !(*hl && *a)), "never the hole"); - assert!(frac(0, 125) > 0.95, "the dark side is sampled ({})", frac(0, 125)); - if band { - // A bright band through the window is left out; the dark area beyond it is not. - assert!(frac(133, 147) < 0.05, "the band is excluded ({})", frac(133, 147)); - assert!(frac(155, 200) > 0.9, "beyond the band is sampled ({})", frac(155, 200)); - } else { - assert!(frac(140, 200) < 0.05, "the bright side is excluded ({})", frac(140, 200)); - } - } - } - - #[test] - fn auto_sampling_keeps_the_surroundings_of_every_part_of_a_thin_selection() { - // A long thin selection across a grey ramp, and a small knob selected with it in a red - // corner. Each part keeps its own surroundings; a compact selection is unchanged. - let (w, h) = (900, 600); - let tex = noise(w, h, 4); - let img: Vec = (0..w * h * 3) - .map(|i| { - let (x, y, c) = ((i / 3) % w, (i / 3) / w, i % 3); - let base = if x > 690 && y > 420 { [0.7, 0.25, 0.2][c] } else { 0.2 + 0.5 * x as f32 / w as f32 }; - base + (tex[i] - 0.5) * 0.04 - }) - .collect(); - let line = |i: usize| (30..870).contains(&(i % w)) && (180..192).contains(&(i / w)); - let knob = |i: usize| ((i % w) as f32 - 795.0).hypot((i / w) as f32 - 510.0) < 10.0; - let hole: Vec = (0..w * h).map(|i| line(i) || knob(i)).collect(); - let area = auto_sampling(w, h, 3, &img, &hole); - let around_knob = (0..w * h).filter(|&i| !hole[i] && ((i % w) as f32 - 795.0).hypot((i / w) as f32 - 510.0) < 24.0); - let (n, kept) = around_knob.fold((0, 0), |(n, k), i| (n + 1, k + usize::from(area[i]))); - assert!(kept as f32 > 0.9 * n as f32, "{kept} of {n} pixels around the knob"); - assert!(thin_band(w, h, &hole) >= 20.0, "{}", thin_band(w, h, &hole)); - let disc: Vec = (0..w * h).map(|i| ((i % w) as f32 - 450.0).hypot((i / w) as f32 - 300.0) < 90.0).collect(); - assert_eq!(thin_band(w, h, &disc), 1.5); - } - - #[test] - fn without_colour_adaptation_the_fill_copies_pixels_exactly() { - // A smooth texture with fine noise, so that every value is unique: a filled pixel equal to - // an image pixel was copied from it. Photoshop's fill (colour adaptation None) is such - // copies, joined by narrow seams. - let (w, h) = (120, 120); - let fine = noise(w, h, 9); - let img: Vec = (0..w * h * 3) - .map(|i| { - let (x, y, c) = (((i / 3) % w) as f32, ((i / 3) / w) as f32, i % 3); - 0.5 + 0.2 * (x * 0.21 + c as f32).sin() * (y * 0.17).cos() + 0.1 * (x * 0.05 - y * 0.08).sin() + (fine[i] - 0.5) * 0.08 - }) - .collect(); - let hole: Vec = (0..w * h).map(|i| (40..80).contains(&(i % w)) && (40..80).contains(&(i / w))).collect(); - // Votes of identical copies average to the copy up to float rounding. - let key = |v: &[f32], i: usize| [0, 1, 2].map(|c| (v[i * 3 + c] * 1e5).round() as i64); - let known: std::collections::HashSet<[i64; 3]> = (0..w * h).filter(|i| !hole[*i]).map(|i| key(&img, i)).collect(); - let out = fill(w, h, 3, &img, &hole, &vec![true; w * h], &FillOptions { color_adaptation: Adapt::NONE, ..Default::default() }); - let exact = (0..w * h).filter(|i| hole[*i] && known.contains(&key(&out, *i))).count(); - assert!(exact as f32 > 0.2 * 1600.0, "{exact} of 1600 filled pixels are exact copies"); - // And the fill is as busy as the noise around it, not a blur of it. - let lap = |v: &[f32], x: usize, y: usize| { - let p = |x: usize, y: usize| v[(y * w + x) * 3]; - (4.0 * p(x, y) - p(x - 1, y) - p(x + 1, y) - p(x, y - 1) - p(x, y + 1)).abs() - }; - let mean = |inside: bool| { - let pts: Vec<(usize, usize)> = (1..h - 1).flat_map(|y| (1..w - 1).map(move |x| (x, y))).filter(|&(x, y)| hole[y * w + x] == inside).collect(); - pts.iter().map(|&(x, y)| lap(&out, x, y)).sum::() / pts.len() as f32 - }; - assert!(mean(true) > 0.6 * mean(false), "fill detail {} against {}", mean(true), mean(false)); - } - - #[test] - fn patch_color_shifts_up_to_about_four_hundredths_per_step() { - // Content 0.4 brighter than where it lands (Photoshop's Patch, Color 3 and 10). - let from: Vec = (0..300).map(|i| 0.7 + 0.05 * ((i % 7) as f32 / 7.0)).collect(); - let to: Vec = from.iter().map(|v| v - 0.4).collect(); - let level = from.iter().sum::() / 300.0; - let shift = |c: u8| { - let gb = level_transform(1, &from, &to, color_amount(c)); - level - from.iter().map(|v| gb[0].0 * v + gb[0].1).sum::() / 300.0 - }; - assert_eq!(shift(0), 0.0); - assert!((shift(3) - 0.12).abs() < 0.01, "{}", shift(3)); - assert!((shift(10) - 0.4).abs() < 0.01, "{}", shift(10)); - } - - /// A soft background (gradients, broad out-of-focus blobs of colour, fine noise) with thin, long bright - /// objects over it: three coiled strings 3 to 7 px wide and two straighter ones, each with an - /// anti-aliased edge and a faint halo. Returns the image; what removing the coils should give - /// (the background and the straighter strings, which stay); and the selection a user would draw - /// around the coils, `margin` px wide. - fn strings_scene(w: usize, h: usize, margin: f32) -> (Vec, Vec, Vec) { - let fine = noise(w, h, 11); - // Out-of-focus colour: broad blobs over two gradients. - let blob = noise(3, 3, 5); - let bg: Vec = (0..w * h * 3) - .map(|i| { - let (x, y, c) = (((i / 3) % w) as f32 / w as f32, ((i / 3) / w) as f32 / h as f32, i % 3); - let mut v = [0.18 + 0.25 * x, 0.22 + 0.1 * y, 0.3 - 0.1 * x][c]; - for b in blob.as_chunks::<3>().0 { - let (bx, by, s) = (b[0] * 1.6 - 0.3, b[1] * 1.6 - 0.3, 0.1 + 0.25 * b[2]); - v += (b[(c + 1) % 3] - 0.2) * 0.5 * (-((x - bx).powi(2) + (y - by).powi(2) * 0.56) / (2.0 * s * s)).exp(); - } - v + (fine[i] - 0.5) * 0.03 - }) - .collect(); - // Signed distance to each object's surface, stamped from points along it. - let stamp = |sd: &mut [f32], pts: &mut dyn Iterator, half: f32| { - for (px, py) in pts { - let reach = (half + 4.0) as i32 + 1; - for dy in -reach..=reach { - for dx in -reach..=reach { - let (x, y) = (px as i32 + dx, py as i32 + dy); - if x >= 0 && y >= 0 && (x as usize) < w && (y as usize) < h { - let i = y as usize * w + x as usize; - sd[i] = sd[i].min((x as f32 - px).hypot(y as f32 - py) - half); - } - } - } - } - }; - let mut coils = vec![f32::INFINITY; w * h]; - for (k, half) in [1.5f32, 2.5, 3.5].into_iter().enumerate() { - let (y0, r) = ((0.22 + 0.28 * k as f32) * h as f32, 10.0 + 2.0 * k as f32); - let mut pts = (0..4000).map(|j| { - let t = j as f32 / 4000.0; - let a = 8.0 * std::f32::consts::TAU * t; - (18.0 + t * (w as f32 - 60.0) + r * a.cos(), y0 + 6.0 * (6.0 * t).sin() + 0.7 * r * a.sin()) - }); - stamp(&mut coils, &mut pts, half); - } - let mut straight = vec![f32::INFINITY; w * h]; - for y in [0.07, 0.93] { - stamp(&mut straight, &mut (0..2000).map(|j| (j as f32 / 2000.0 * w as f32, y * h as f32 + 3.0 * (j as f32 / 300.0).sin())), 2.0); - } - let draw = |base: &[f32], sd: &[f32]| -> Vec { - let mut img = base.to_vec(); - for i in 0..w * h { - let cover = (0.5 - sd[i]).clamp(0.0, 1.0); - let halo = if sd[i] > 0.0 { 0.08 * (-sd[i] * sd[i] / 2.9).exp() } else { 0.0 }; - for (c, metal) in [0.9f32, 0.85, 0.7].into_iter().enumerate() { - let v = &mut img[i * 3 + c]; - *v = *v * (1.0 - cover) + metal * cover + halo * (1.0 - cover); - } - } - img - }; - let clean = draw(&bg, &straight); - let both: Vec = coils.iter().zip(&straight).map(|(a, b)| a.min(*b)).collect(); - let img = draw(&bg, &both); - let hole = coils.iter().map(|d| *d <= margin).collect(); - (img, clean, hole) - } - - /// RMS over the hole of the error averaged over 7 × 7 pixels (in levels of 255): the noise - /// cancels out, a ghost of the removed outline or a blotch of another shade does not. - fn blotch_error(w: usize, h: usize, out: &[f32], clean: &[f32], hole: &[bool]) -> f32 { - let (mut sum, mut n) = (0.0f64, 0usize); - for y in 3..h - 3 { - for x in 3..w - 3 { - if !hole[y * w + x] { - continue; - } - let mut e = [0.0f32; 3]; - for j in (y - 3..=y + 3).flat_map(|yy| (x - 3..=x + 3).map(move |xx| yy * w + xx)) { - for (c, ec) in e.iter_mut().enumerate() { - *ec += out[j * 3 + c] - clean[j * 3 + c]; - } - } - sum += f64::from(e.iter().map(|v| (v / 49.0).powi(2)).sum::() / 3.0); - n += 1; - } - } - ((sum / n.max(1) as f64).sqrt() * 255.0) as f32 - } - - /// Removing thin, long objects (guitar strings, wires) from a soft background (#1366): the - /// fill is the background, with no ghost of their outline and nothing of their colour copied - /// back in. Their selection is long but only a few pixels thick, so the fill is worked out at - /// a scale where it is still a few pixels thick rather than one where the strings' surroundings - /// have merged into a blur. - #[test] - fn thin_objects_leave_no_ghost_and_none_of_their_colour() { - let (w, h) = (360, 270); - let (img, clean, hole) = strings_scene(w, h, 2.0); - let source = auto_sampling(w, h, 3, &img, &hole); - let out = fill(w, h, 3, &img, &hole, &source, &FillOptions::default()); - let blotch = blotch_error(w, h, &out, &clean, &hole); - let luma = |v: &[f32], i: usize| (v[i * 3] + v[i * 3 + 1] + v[i * 3 + 2]) / 3.0; - let bright = (0..w * h).filter(|&i| hole[i] && luma(&out, i) > luma(&clean, i) + 0.06).count(); - // Before #1366 the outlines stayed as darker and lighter blotches (13 levels of 255) and - // 1121 pixels took the strings' colour. - assert!(blotch < 2.5, "ghosts and blotches: {blotch:.2} levels of 255"); - assert_eq!(bright, 0, "filled pixels with the strings' colour"); - } - - #[test] - fn variant_geometry() { - let img = vec![0.5f32; 10 * 6]; - let ok = vec![true; 60]; - let src = Src { w: 10, h: 6, ch: 1, img: &img, ok: &ok }; - let v = variant(src, 90.0, 1.0, false, &Interrupt::NONE).unwrap(); - assert_eq!((v.w, v.h), (6, 10)); - let v = variant(src, 0.0, 0.8, true, &Interrupt::NONE).unwrap(); - assert_eq!((v.w, v.h), (8, 5)); - assert!(v.ok.iter().filter(|o| **o).count() > 20); - } -} +mod tests; diff --git a/crates/algo/src/content_aware/tests.rs b/crates/algo/src/content_aware/tests.rs new file mode 100644 index 0000000000..183e6e5b88 --- /dev/null +++ b/crates/algo/src/content_aware/tests.rs @@ -0,0 +1,445 @@ +use super::mosaic_size; + +fn blank(w: usize, h: usize) -> (usize, usize) { + (w, h) +} + +#[test] +fn a_thin_image_with_turned_variants_does_not_get_a_quadratic_mosaic() { + // 40000×1 plus its 90° copy (1×40000): about 1.6 billion mosaic cells for 80000 pixels. + assert_eq!(mosaic_size(40_000, 1, 8, &[blank(1, 40_000)]), None); + assert_eq!(mosaic_size(usize::MAX, 1, 8, &[blank(1, 1)]), None); + assert_eq!(mosaic_size(100, 100, 8, &[blank(100, 100)]), Some((208, 108))); +} + +use super::*; + +/// Vertical stripes (period 6) in grey, with a hole in the middle. +fn stripes(w: usize, h: usize) -> (Vec, Vec) { + let img: Vec = (0..w * h).map(|i| if (i % w) % 6 < 3 { 0.2 } else { 0.8 }).collect(); + let hole: Vec = (0..w * h).map(|i| (i % w).abs_diff(w / 2) < 4 && (i / w).abs_diff(h / 2) < 4).collect(); + (img, hole) +} + +#[test] +fn strokes_paint_their_path_and_leave_a_mismatched_mask_alone() { + let area = Rect::new(10, 20, 50, 40); + let (w, h) = (40, 20); + let strokes = [ + SamplingStroke { add: true, size: 6.0, points: vec![[12.0, 25.0], [40.0, 25.0], [45.0, 35.0]] }, + SamplingStroke { add: false, size: 3.0, points: vec![[30.0, 25.0]] }, + SamplingStroke { add: true, size: 2.0, points: Vec::new() }, + ]; + let mut mask = vec![false; w * h]; + paint_strokes(&mut mask, area, &strokes); + // The same pixels as testing every pixel against every segment of each stroke in turn. + let mut want = vec![false; w * h]; + for s in &strokes { + let r2 = (s.size / 2.0).max(0.5).powi(2); + let segs: Vec<_> = if s.points.len() == 1 { vec![(s.points[0], s.points[0])] } else { s.points.windows(2).map(|p| (p[0], p[1])).collect() }; + for (i, m) in want.iter_mut().enumerate() { + let c = [f64::from(area.x0) + (i % w) as f64 + 0.5, f64::from(area.y0) + (i / w) as f64 + 0.5]; + if segs.iter().any(|(a, b)| seg_dist2(c, *a, *b) <= r2) { + *m = s.add; + } + } + } + assert_eq!(mask, want); + assert!(mask[5 * w + 10] && !mask[5 * w + 20], "added along the path, cleared under the subtracting dab"); + // A mask shorter or longer than the area is not touched (and nothing panics). + for len in [0, 7, w * h - 1, w * h + 3] { + let mut short = vec![false; len]; + paint_strokes(&mut short, area, &strokes); + assert!(short.iter().all(|v| !v), "len {len}"); + } + // Hostile coordinates stay inside the area. + let mut m = vec![false; w * h]; + let wild = [SamplingStroke { add: true, size: 5000.0, points: vec![[f64::MAX, -1e300], [f64::NAN, 1e7]] }]; + paint_strokes(&mut m, area, &wild); +} + +#[test] +fn cancelled_fill_stops_and_progress_reaches_one() { + use std::sync::atomic::{AtomicU32, Ordering}; + let (w, h) = (60, 40); + let (img, hole) = stripes(w, h); + let source = vec![true; w * h]; + let yes = || true; + let cancelled = photocraft_raster::Interrupt::cancel_only(&yes); + assert!(fill_with(w, h, 1, &img, &hole, &source, &FillOptions::default(), &cancelled).is_err()); + let last = AtomicU32::new(0); + let no = || false; + let progress = |f: f32| { + assert!(f >= f32::from_bits(last.load(Ordering::Relaxed)), "progress went backwards"); + last.store(f.to_bits(), Ordering::Relaxed); + }; + let out = fill_with(w, h, 1, &img, &hole, &source, &FillOptions::default(), &photocraft_raster::Interrupt::new(&no, &progress)).unwrap(); + assert_eq!(f32::from_bits(last.load(Ordering::Relaxed)), 1.0); + assert_eq!(out, fill(w, h, 1, &img, &hole, &source, &FillOptions::default()), "same result as the plain fill"); +} + +#[test] +fn filling_in_place_is_filling_a_copy() { + let (w, h) = (90, 70); + let rgb: Vec = noise(w, h, 4).iter().enumerate().map(|(i, v)| v * 0.5 + 0.3 * ((i / 3 % w) % 11 < 5) as u8 as f32).collect(); + let hole: Vec = (0..w * h).map(|i| (30..52).contains(&(i % w)) && (25..44).contains(&(i / w))).collect(); + let source: Vec = (0..w * h).map(|i| i % w < 75).collect(); + let none = Interrupt::NONE; + for opts in [FillOptions::default(), FillOptions { color_adaptation: Adapt::NONE, mirror: true, ..Default::default() }] { + let copy = fill_with(w, h, 3, &rgb, &hole, &source, &opts, &none).unwrap(); + let owned = fill_owned(w, h, 3, rgb.clone(), &hole, &source, &opts, &none).unwrap(); + assert_eq!(copy.iter().map(|v| v.to_bits()).collect::>(), owned.iter().map(|v| v.to_bits()).collect::>()); + // Only the hole changes. + assert!((0..w * h).all(|i| hole[i] || (0..3).all(|c| owned[i * 3 + c].to_bits() == rgb[i * 3 + c].to_bits()))); + } + // Nothing to copy from: the membrane, either way. + let nowhere = vec![false; w * h]; + let copy = fill_with(w, h, 3, &rgb, &hole, &nowhere, &FillOptions::default(), &none).unwrap(); + assert_eq!(copy, fill_owned(w, h, 3, rgb.clone(), &hole, &nowhere, &FillOptions::default(), &none).unwrap()); +} + +#[test] +fn auto_sampling_can_be_cancelled() { + let (w, h) = (200, 160); + let img: Vec = noise(w, h, 5).iter().enumerate().map(|(i, v)| v * 0.1 + if (i / 3) % w < 120 { 0.3 } else { 0.6 }).collect(); + let hole: Vec = (0..w * h).map(|i| (80..110).contains(&(i % w)) && (60..90).contains(&(i / w))).collect(); + let yes = || true; + assert!(auto_sampling_with(w, h, 3, &img, &hole, &Interrupt::cancel_only(&yes)).is_err()); + assert_eq!(auto_sampling_with(w, h, 3, &img, &hole, &Interrupt::NONE).unwrap(), auto_sampling(w, h, 3, &img, &hole)); +} + +#[test] +fn fills_only_the_hole_with_known_texture() { + let (w, h) = (48, 32); + let (img, hole) = stripes(w, h); + let src = vec![true; w * h]; + let out = fill(w, h, 1, &img, &hole, &src, &FillOptions { color_adaptation: Adapt::NONE, ..Default::default() }); + for i in 0..w * h { + if !hole[i] { + assert_eq!(out[i], img[i]); + } + } + // The hole is filled with stripe values, not a flat average. + let vals: Vec = (0..w * h).filter(|i| hole[*i]).map(|i| out[i]).collect(); + assert!(vals.iter().any(|v| *v < 0.35) && vals.iter().any(|v| *v > 0.65), "{vals:?}"); +} + +#[test] +fn sampling_area_restricts_sources() { + // Left half dark, right half bright; sampling only the right half fills bright. + let (w, h) = (40, 20); + let img: Vec = (0..w * h).map(|i| if i % w < 20 { 0.1 } else { 0.9 }).collect(); + let hole: Vec = (0..w * h).map(|i| (16..24).contains(&(i % w)) && (6..14).contains(&(i / w))).collect(); + let right: Vec = (0..w * h).map(|i| i % w >= 24).collect(); + let out = fill(w, h, 1, &img, &hole, &right, &FillOptions { color_adaptation: Adapt::NONE, ..Default::default() }); + let mean: f32 = (0..w * h).filter(|i| hole[*i]).map(|i| out[i]).sum::() / 64.0; + assert!(mean > 0.8, "mean {mean}"); +} + +#[test] +fn adaptations_run_and_stay_deterministic() { + let (w, h) = (32, 24); + let (img, hole) = stripes(w, h); + let rgb: Vec = img.iter().flat_map(|v| [*v, *v * 0.5, 1.0 - *v]).collect(); + let src = vec![true; w * h]; + let opts = FillOptions { color_adaptation: color_level("high"), rotations: rotation_level("low"), scale: true, mirror: true, seed: 7 }; + let a = fill(w, h, 3, &rgb, &hole, &src, &opts); + let b = fill(w, h, 3, &rgb, &hole, &src, &opts); + assert_eq!(a, b); + assert!(a.iter().all(|v| v.is_finite() && (0.0..=1.0).contains(v))); +} + +#[test] +fn color_adaptation_follows_a_gradient() { + // A horizontal brightness ramp with a hole: adaptation keeps the fill near the ramp. + let (w, h) = (40, 20); + let img: Vec = (0..w * h).map(|i| (i % w) as f32 / w as f32).collect(); + let hole: Vec = (0..w * h).map(|i| (14..26).contains(&(i % w)) && (5..15).contains(&(i / w))).collect(); + let src = vec![true; w * h]; + let out = fill(w, h, 1, &img, &hole, &src, &FillOptions { color_adaptation: color_level("veryHigh"), ..Default::default() }); + let err: f32 = (0..w * h).filter(|i| hole[*i]).map(|i| (out[i] - img[i]).abs()).sum::() / 120.0; + assert!(err < 0.12, "mean error {err}"); +} + +/// A vertical sky gradient (each row one colour) filled at every adaptation level stays the +/// gradient: no tinted blotch where the copied rows' colours were shifted per channel. +#[test] +fn color_adaptation_leaves_a_smooth_gradient_untinted() { + let (w, h) = (120, 60); + let row = |y: usize| { + let t = y as f32 / (h - 1) as f32; + [0.27 + 0.45 * t, 0.53 + 0.32 * t, 0.86 + 0.1 * t] + }; + let img: Vec = (0..w * h).flat_map(|i| row(i / w)).collect(); + let hole: Vec = (0..w * h).map(|i| (50..70).contains(&(i % w)) && (20..40).contains(&(i / w))).collect(); + let src = vec![true; w * h]; + for level in ["none", "default", "high", "veryHigh"] { + let out = fill(w, h, 3, &img, &hole, &src, &FillOptions { color_adaptation: color_level(level), ..Default::default() }); + let (out, img) = (&out, &img); + let worst = (0..w * h).filter(|i| hole[*i]).flat_map(|i| (0..3).map(move |c| (out[i * 3 + c] - img[i * 3 + c]).abs())).fold(0.0f32, f32::max); + assert!(worst < 3.0 / 255.0, "{level}: off by {}", worst * 255.0); + } +} + +/// I.i.d. noise: every value occurs once, so a filled pixel equal to an image pixel was copied. +fn noise(w: usize, h: usize, seed: u64) -> Vec { + let mut z = seed; + (0..w * h * 3) + .map(|_| { + z = z.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + 0.2 + 0.6 * ((z >> 40) as f32 / (1u64 << 24) as f32) + }) + .collect() +} + +#[test] +fn sampling_window_is_photoshops() { + let canvas = Rect::new(0, 0, 800, 800); + let sq = |x0: i32, y0: i32, w: i32, h: i32| Rect::new(x0, y0, x0 + w, y0 + h); + // Photoshop 25.4's sampling overlay: a square of side 4·√(max(w,50)·max(h,50)) centred on + // the selection's bounds. + assert_eq!(sampling_window(sq(375, 375, 50, 50), canvas), sq(300, 300, 200, 200)); + assert_eq!(sampling_window(sq(350, 350, 100, 100), canvas), sq(200, 200, 400, 400)); + assert_eq!(sampling_window(sq(395, 395, 10, 10), canvas), sq(300, 300, 200, 200)); + assert_eq!(sampling_window(sq(370, 370, 60, 60), canvas), sq(280, 280, 240, 240)); + // Long selections (Photoshop's overlay, read off the screen to a pixel: 281, 399, 691). + assert_eq!(sampling_window(sq(350, 385, 100, 30), canvas), sq(258, 258, 283, 283)); + assert_eq!(sampling_window(sq(300, 375, 200, 50), canvas), sq(200, 200, 400, 400)); + assert_eq!(sampling_window(sq(250, 350, 300, 100), canvas), sq(53, 53, 693, 693)); + // At the canvas edge the square slides inwards rather than being cut. + assert_eq!(sampling_window(sq(10, 375, 50, 50), canvas), sq(0, 300, 200, 200)); + assert_eq!(sampling_window(sq(5, 5, 60, 60), canvas), sq(0, 0, 240, 240)); + // A canvas smaller than the square clips it; a very long selection keeps its length. + assert_eq!(sampling_window(sq(40, 40, 50, 50), Rect::new(0, 0, 150, 120)), Rect::new(0, 0, 150, 120)); + assert_eq!(sampling_window(sq(100, 995, 1800, 10), Rect::new(0, 0, 2000, 2000)), sq(100, 400, 1800, 1200)); + assert_eq!(sampling_window(Rect::EMPTY, canvas), Rect::EMPTY); +} + +#[test] +fn auto_sampling_keeps_what_looks_like_the_surroundings() { + // Grey texture, dark on the left, 50 levels brighter on the right; the hole is in the dark + // part near the boundary (Photoshop's Auto leaves the bright part out). + let (w, h) = (200, 200); + let tex = noise(w, h, 3); + let shade = |x: usize, band: bool| { + if band { + if (130..150).contains(&x) { 0.55 } else { 0.35 } + } else if x < 135 { + 0.35 + } else { + 0.55 + } + }; + for band in [false, true] { + let img: Vec = (0..w * h * 3).map(|i| shade((i / 3) % w, band) + (tex[i] - 0.5) * 0.1).collect(); + let hole: Vec = (0..w * h).map(|i| (75..125).contains(&(i % w)) && (75..125).contains(&(i / w))).collect(); + let area = auto_sampling(w, h, 3, &img, &hole); + let frac = |x0: usize, x1: usize| { + let n = (0..w * h).filter(|i| (x0..x1).contains(&(i % w)) && !hole[*i]).count(); + (0..w * h).filter(|i| (x0..x1).contains(&(i % w)) && area[*i]).count() as f32 / n as f32 + }; + assert!(hole.iter().zip(&area).all(|(hl, a)| !(*hl && *a)), "never the hole"); + assert!(frac(0, 125) > 0.95, "the dark side is sampled ({})", frac(0, 125)); + if band { + // A bright band through the window is left out; the dark area beyond it is not. + assert!(frac(133, 147) < 0.05, "the band is excluded ({})", frac(133, 147)); + assert!(frac(155, 200) > 0.9, "beyond the band is sampled ({})", frac(155, 200)); + } else { + assert!(frac(140, 200) < 0.05, "the bright side is excluded ({})", frac(140, 200)); + } + } +} + +#[test] +fn auto_sampling_keeps_the_surroundings_of_every_part_of_a_thin_selection() { + // A long thin selection across a grey ramp, and a small knob selected with it in a red + // corner. Each part keeps its own surroundings; a compact selection is unchanged. + let (w, h) = (900, 600); + let tex = noise(w, h, 4); + let img: Vec = (0..w * h * 3) + .map(|i| { + let (x, y, c) = ((i / 3) % w, (i / 3) / w, i % 3); + let base = if x > 690 && y > 420 { [0.7, 0.25, 0.2][c] } else { 0.2 + 0.5 * x as f32 / w as f32 }; + base + (tex[i] - 0.5) * 0.04 + }) + .collect(); + let line = |i: usize| (30..870).contains(&(i % w)) && (180..192).contains(&(i / w)); + let knob = |i: usize| ((i % w) as f32 - 795.0).hypot((i / w) as f32 - 510.0) < 10.0; + let hole: Vec = (0..w * h).map(|i| line(i) || knob(i)).collect(); + let area = auto_sampling(w, h, 3, &img, &hole); + let around_knob = (0..w * h).filter(|&i| !hole[i] && ((i % w) as f32 - 795.0).hypot((i / w) as f32 - 510.0) < 24.0); + let (n, kept) = around_knob.fold((0, 0), |(n, k), i| (n + 1, k + usize::from(area[i]))); + assert!(kept as f32 > 0.9 * n as f32, "{kept} of {n} pixels around the knob"); + assert!(thin_band(w, h, &hole) >= 20.0, "{}", thin_band(w, h, &hole)); + let disc: Vec = (0..w * h).map(|i| ((i % w) as f32 - 450.0).hypot((i / w) as f32 - 300.0) < 90.0).collect(); + assert_eq!(thin_band(w, h, &disc), 1.5); +} + +#[test] +fn without_colour_adaptation_the_fill_copies_pixels_exactly() { + // A smooth texture with fine noise, so that every value is unique: a filled pixel equal to + // an image pixel was copied from it. Photoshop's fill (colour adaptation None) is such + // copies, joined by narrow seams. + let (w, h) = (120, 120); + let fine = noise(w, h, 9); + let img: Vec = (0..w * h * 3) + .map(|i| { + let (x, y, c) = (((i / 3) % w) as f32, ((i / 3) / w) as f32, i % 3); + 0.5 + 0.2 * (x * 0.21 + c as f32).sin() * (y * 0.17).cos() + 0.1 * (x * 0.05 - y * 0.08).sin() + (fine[i] - 0.5) * 0.08 + }) + .collect(); + let hole: Vec = (0..w * h).map(|i| (40..80).contains(&(i % w)) && (40..80).contains(&(i / w))).collect(); + // Votes of identical copies average to the copy up to float rounding. + let key = |v: &[f32], i: usize| [0, 1, 2].map(|c| (v[i * 3 + c] * 1e5).round() as i64); + let known: std::collections::HashSet<[i64; 3]> = (0..w * h).filter(|i| !hole[*i]).map(|i| key(&img, i)).collect(); + let out = fill(w, h, 3, &img, &hole, &vec![true; w * h], &FillOptions { color_adaptation: Adapt::NONE, ..Default::default() }); + let exact = (0..w * h).filter(|i| hole[*i] && known.contains(&key(&out, *i))).count(); + assert!(exact as f32 > 0.2 * 1600.0, "{exact} of 1600 filled pixels are exact copies"); + // And the fill is as busy as the noise around it, not a blur of it. + let lap = |v: &[f32], x: usize, y: usize| { + let p = |x: usize, y: usize| v[(y * w + x) * 3]; + (4.0 * p(x, y) - p(x - 1, y) - p(x + 1, y) - p(x, y - 1) - p(x, y + 1)).abs() + }; + let mean = |inside: bool| { + let pts: Vec<(usize, usize)> = (1..h - 1).flat_map(|y| (1..w - 1).map(move |x| (x, y))).filter(|&(x, y)| hole[y * w + x] == inside).collect(); + pts.iter().map(|&(x, y)| lap(&out, x, y)).sum::() / pts.len() as f32 + }; + assert!(mean(true) > 0.6 * mean(false), "fill detail {} against {}", mean(true), mean(false)); +} + +#[test] +fn patch_color_shifts_up_to_about_four_hundredths_per_step() { + // Content 0.4 brighter than where it lands (Photoshop's Patch, Color 3 and 10). + let from: Vec = (0..300).map(|i| 0.7 + 0.05 * ((i % 7) as f32 / 7.0)).collect(); + let to: Vec = from.iter().map(|v| v - 0.4).collect(); + let level = from.iter().sum::() / 300.0; + let shift = |c: u8| { + let gb = level_transform(1, &from, &to, color_amount(c)); + level - from.iter().map(|v| gb[0].0 * v + gb[0].1).sum::() / 300.0 + }; + assert_eq!(shift(0), 0.0); + assert!((shift(3) - 0.12).abs() < 0.01, "{}", shift(3)); + assert!((shift(10) - 0.4).abs() < 0.01, "{}", shift(10)); +} + +/// A soft background (gradients, broad out-of-focus blobs of colour, fine noise) with thin, long bright +/// objects over it: three coiled strings 3 to 7 px wide and two straighter ones, each with an +/// anti-aliased edge and a faint halo. Returns the image; what removing the coils should give +/// (the background and the straighter strings, which stay); and the selection a user would draw +/// around the coils, `margin` px wide. +fn strings_scene(w: usize, h: usize, margin: f32) -> (Vec, Vec, Vec) { + let fine = noise(w, h, 11); + // Out-of-focus colour: broad blobs over two gradients. + let blob = noise(3, 3, 5); + let bg: Vec = (0..w * h * 3) + .map(|i| { + let (x, y, c) = (((i / 3) % w) as f32 / w as f32, ((i / 3) / w) as f32 / h as f32, i % 3); + let mut v = [0.18 + 0.25 * x, 0.22 + 0.1 * y, 0.3 - 0.1 * x][c]; + for b in blob.as_chunks::<3>().0 { + let (bx, by, s) = (b[0] * 1.6 - 0.3, b[1] * 1.6 - 0.3, 0.1 + 0.25 * b[2]); + v += (b[(c + 1) % 3] - 0.2) * 0.5 * (-((x - bx).powi(2) + (y - by).powi(2) * 0.56) / (2.0 * s * s)).exp(); + } + v + (fine[i] - 0.5) * 0.03 + }) + .collect(); + // Signed distance to each object's surface, stamped from points along it. + let stamp = |sd: &mut [f32], pts: &mut dyn Iterator, half: f32| { + for (px, py) in pts { + let reach = (half + 4.0) as i32 + 1; + for dy in -reach..=reach { + for dx in -reach..=reach { + let (x, y) = (px as i32 + dx, py as i32 + dy); + if x >= 0 && y >= 0 && (x as usize) < w && (y as usize) < h { + let i = y as usize * w + x as usize; + sd[i] = sd[i].min((x as f32 - px).hypot(y as f32 - py) - half); + } + } + } + } + }; + let mut coils = vec![f32::INFINITY; w * h]; + for (k, half) in [1.5f32, 2.5, 3.5].into_iter().enumerate() { + let (y0, r) = ((0.22 + 0.28 * k as f32) * h as f32, 10.0 + 2.0 * k as f32); + let mut pts = (0..4000).map(|j| { + let t = j as f32 / 4000.0; + let a = 8.0 * std::f32::consts::TAU * t; + (18.0 + t * (w as f32 - 60.0) + r * a.cos(), y0 + 6.0 * (6.0 * t).sin() + 0.7 * r * a.sin()) + }); + stamp(&mut coils, &mut pts, half); + } + let mut straight = vec![f32::INFINITY; w * h]; + for y in [0.07, 0.93] { + stamp(&mut straight, &mut (0..2000).map(|j| (j as f32 / 2000.0 * w as f32, y * h as f32 + 3.0 * (j as f32 / 300.0).sin())), 2.0); + } + let draw = |base: &[f32], sd: &[f32]| -> Vec { + let mut img = base.to_vec(); + for i in 0..w * h { + let cover = (0.5 - sd[i]).clamp(0.0, 1.0); + let halo = if sd[i] > 0.0 { 0.08 * (-sd[i] * sd[i] / 2.9).exp() } else { 0.0 }; + for (c, metal) in [0.9f32, 0.85, 0.7].into_iter().enumerate() { + let v = &mut img[i * 3 + c]; + *v = *v * (1.0 - cover) + metal * cover + halo * (1.0 - cover); + } + } + img + }; + let clean = draw(&bg, &straight); + let both: Vec = coils.iter().zip(&straight).map(|(a, b)| a.min(*b)).collect(); + let img = draw(&bg, &both); + let hole = coils.iter().map(|d| *d <= margin).collect(); + (img, clean, hole) +} + +/// RMS over the hole of the error averaged over 7 × 7 pixels (in levels of 255): the noise +/// cancels out, a ghost of the removed outline or a blotch of another shade does not. +fn blotch_error(w: usize, h: usize, out: &[f32], clean: &[f32], hole: &[bool]) -> f32 { + let (mut sum, mut n) = (0.0f64, 0usize); + for y in 3..h - 3 { + for x in 3..w - 3 { + if !hole[y * w + x] { + continue; + } + let mut e = [0.0f32; 3]; + for j in (y - 3..=y + 3).flat_map(|yy| (x - 3..=x + 3).map(move |xx| yy * w + xx)) { + for (c, ec) in e.iter_mut().enumerate() { + *ec += out[j * 3 + c] - clean[j * 3 + c]; + } + } + sum += f64::from(e.iter().map(|v| (v / 49.0).powi(2)).sum::() / 3.0); + n += 1; + } + } + ((sum / n.max(1) as f64).sqrt() * 255.0) as f32 +} + +/// Removing thin, long objects (guitar strings, wires) from a soft background (#1366): the +/// fill is the background, with no ghost of their outline and nothing of their colour copied +/// back in. Their selection is long but only a few pixels thick, so the fill is worked out at +/// a scale where it is still a few pixels thick rather than one where the strings' surroundings +/// have merged into a blur. +#[test] +fn thin_objects_leave_no_ghost_and_none_of_their_colour() { + let (w, h) = (360, 270); + let (img, clean, hole) = strings_scene(w, h, 2.0); + let source = auto_sampling(w, h, 3, &img, &hole); + let out = fill(w, h, 3, &img, &hole, &source, &FillOptions::default()); + let blotch = blotch_error(w, h, &out, &clean, &hole); + let luma = |v: &[f32], i: usize| (v[i * 3] + v[i * 3 + 1] + v[i * 3 + 2]) / 3.0; + let bright = (0..w * h).filter(|&i| hole[i] && luma(&out, i) > luma(&clean, i) + 0.06).count(); + // Before #1366 the outlines stayed as darker and lighter blotches (13 levels of 255) and + // 1121 pixels took the strings' colour. + assert!(blotch < 2.5, "ghosts and blotches: {blotch:.2} levels of 255"); + assert_eq!(bright, 0, "filled pixels with the strings' colour"); +} + +#[test] +fn variant_geometry() { + let img = vec![0.5f32; 10 * 6]; + let ok = vec![true; 60]; + let src = Src { w: 10, h: 6, ch: 1, img: &img, ok: &ok }; + let v = variant(src, 90.0, 1.0, false, &Interrupt::NONE).unwrap(); + assert_eq!((v.w, v.h), (6, 10)); + let v = variant(src, 0.0, 0.8, true, &Interrupt::NONE).unwrap(); + assert_eq!((v.w, v.h), (8, 5)); + assert!(v.ok.iter().filter(|o| **o).count() > 20); +} diff --git a/crates/algo/src/gallery.rs b/crates/algo/src/gallery.rs index 53ed13d3b8..e0d2c44a9e 100644 --- a/crates/algo/src/gallery.rs +++ b/crates/algo/src/gallery.rs @@ -15,11 +15,9 @@ use crate::image::{Image, premultiply}; use crate::{BlurPath, Ctx, FieldPin, IrisPin, SpinPin}; #[cfg(test)] -#[path = "tests_iris.rs"] mod tests; #[cfg(test)] -#[path = "tests_tilt_shift.rs"] mod tilt_shift_tests; /// Gaussian σ for a gallery blur amount in px. diff --git a/crates/algo/src/tests_iris.rs b/crates/algo/src/gallery/tests.rs similarity index 99% rename from crates/algo/src/tests_iris.rs rename to crates/algo/src/gallery/tests.rs index 2d54c8f134..e822d7a938 100644 --- a/crates/algo/src/tests_iris.rs +++ b/crates/algo/src/gallery/tests.rs @@ -2,7 +2,6 @@ use super::*; use photocraft_color::{ColorMode, PixelFormat, SampleType}; use photocraft_raster::{Interrupt, Surface}; -#[path = "tests_iris_reference.rs"] mod reference; fn image(rect: Rect, ch: usize) -> Image { diff --git a/crates/algo/src/tests_iris_reference.rs b/crates/algo/src/gallery/tests/reference.rs similarity index 100% rename from crates/algo/src/tests_iris_reference.rs rename to crates/algo/src/gallery/tests/reference.rs diff --git a/crates/algo/src/tests_tilt_shift.rs b/crates/algo/src/gallery/tilt_shift_tests.rs similarity index 99% rename from crates/algo/src/tests_tilt_shift.rs rename to crates/algo/src/gallery/tilt_shift_tests.rs index b82dd1c2c4..5d3ea66678 100644 --- a/crates/algo/src/tests_tilt_shift.rs +++ b/crates/algo/src/gallery/tilt_shift_tests.rs @@ -2,7 +2,6 @@ use super::*; use photocraft_color::{ColorMode, PixelFormat, SampleType}; use photocraft_raster::{Interrupt, Surface}; -#[path = "tests_tilt_shift_reference.rs"] mod reference; fn image(rect: Rect, ch: usize) -> Image { diff --git a/crates/algo/src/tests_tilt_shift_reference.rs b/crates/algo/src/gallery/tilt_shift_tests/reference.rs similarity index 100% rename from crates/algo/src/tests_tilt_shift_reference.rs rename to crates/algo/src/gallery/tilt_shift_tests/reference.rs diff --git a/crates/algo/src/inpaint.rs b/crates/algo/src/inpaint.rs index 87ed2a3576..87b8407a95 100644 --- a/crates/algo/src/inpaint.rs +++ b/crates/algo/src/inpaint.rs @@ -51,64 +51,25 @@ use crate::poisson::membrane_fill; mod proximity_integral; use proximity_integral::HoleIntegral; -/// Below this many cells a pass runs on the calling thread (thread hand-off costs more than it -/// saves). Every pass gives the same result either way. -const PAR_MIN: usize = 64 * 64; +mod common; +mod solver; +mod sources; +mod synthesis; -/// [`PAR_MIN`] for the passes that match or vote a patch per cell. -const PAR_MIN_PATCHES: usize = 16 * 16; - -/// Largest level (in cells) whose source patches' moments [`Solver::prepare`] keeps. -const SOURCE_MOMENTS_MAX: usize = 1 << 20; - -/// SplitMix64: tiny deterministic RNG. -#[derive(Clone)] -pub(crate) struct Rng(u64); -impl Rng { - /// A generator whose sequence is fixed by `seed`. - pub(crate) fn new(seed: u64) -> Self { - Rng(seed ^ 0x9E37_79B9_7F4A_7C15) - } - /// The next value of the SplitMix64 sequence. - pub(crate) fn next(&mut self) -> u64 { - crate::photo_util::splitmix64(&mut self.0) - } - /// Skip `n` numbers (the same state as after `n` calls of [`Rng::next`]). - pub(crate) fn skip(&mut self, n: u64) { - self.0 = self.0.wrapping_add(n.wrapping_mul(0x9E37_79B9_7F4A_7C15)); - } - /// Uniform integer in `lo..=hi`. - pub(crate) fn range(&mut self, lo: i32, hi: i32) -> i32 { - if hi <= lo { - return lo; - } - lo + (self.next() % (hi - lo + 1) as u64) as i32 - } -} - -/// How far a copied patch may be adjusted to its target, per channel: `gain · source + bias`, the -/// gain within `gain` and the bias within `±bias` (Image Melding's photometric transform). The -/// gain is the ratio of the patches' standard deviations, the bias what then matches their means. -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct Adapt { - pub gain: (f32, f32), - pub bias: f32, -} - -impl Adapt { - /// Copies are taken as they are. - pub const NONE: Adapt = Adapt { gain: (1.0, 1.0), bias: 0.0 }; - - pub fn is_none(&self) -> bool { - self.gain == (1.0, 1.0) && self.bias == 0.0 - } -} - -impl Default for Adapt { - fn default() -> Self { - Self::NONE - } -} +#[cfg(test)] +use common::Bounds; +pub(crate) use common::Rng; +pub use common::{Adapt, Px}; +use common::{Level, SOURCE_MOMENTS_MAX}; +use solver::Solver; +pub(crate) use solver::fit; +#[cfg(test)] +use solver::least_sum; +use sources::{Coarser, Sources, THIN_RATIO, downsample, hole_bounds, hole_thickness, peel_affordable, targets_around, valid_sources, window_count}; +#[cfg(test)] +use sources::{hole_bbox, integral}; +use synthesis::onion_peel; +pub use synthesis::{best_offset, synthesize}; /// Parameters for [`complete`]. #[derive(Clone, Debug, PartialEq)] @@ -135,1417 +96,6 @@ impl Default for CompleteParams { } } -/// What a pixel is to [`complete_masked`]. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Px { - /// Not part of the image (a gap, or outside a transformed copy): ignored. - Void, - /// Known, part of the context the fill must agree with, but not copied from. - Known, - /// Known and may be copied from. - Source, - /// To be filled. - Hole, -} - -/// One pyramid level. Level 0 borrows the caller's buffers until it is solved. -struct Level<'a> { - w: usize, - h: usize, - img: Cow<'a, [f32]>, - px: Cow<'a, [Px]>, -} - -impl Level<'_> { - const EMPTY: Level<'static> = Level { w: 0, h: 0, img: Cow::Borrowed(&[]), px: Cow::Borrowed(&[]) }; -} - -/// The half-open box `[x0, x1) × [y0, y1)` of a level's grid. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -struct Bounds { - x0: usize, - y0: usize, - x1: usize, - y1: usize, -} - -impl Bounds { - /// Grown by `r` on every side, within a `w × h` grid. - fn grow(self, r: usize, w: usize, h: usize) -> Bounds { - Bounds { x0: self.x0.saturating_sub(r), y0: self.y0.saturating_sub(r), x1: self.x1.saturating_add(r).min(w), y1: self.y1.saturating_add(r).min(h) } - } - - /// The same box on the next coarser level (whose cells are 2 × 2 of these). - fn half(self) -> Bounds { - Bounds { x0: self.x0 / 2, y0: self.y0 / 2, x1: self.x1.div_ceil(2), y1: self.y1.div_ceil(2) } - } - - fn width(&self) -> usize { - self.x1.saturating_sub(self.x0) - } - - fn height(&self) -> usize { - self.y1.saturating_sub(self.y0) - } - - fn area(&self) -> usize { - self.width() * self.height() - } -} - -/// Half-size level: a cell is a hole if any of its pixels is; else it averages its non-void -/// pixels, and may be copied from only if all of them may. -fn downsample(l: &Level, ch: usize) -> Level<'static> { - let (w, h) = (l.w.div_ceil(2), l.h.div_ceil(2)); - let mut img = vec![0.0f32; w * h * ch]; - let mut px = vec![Px::Void; w * h]; - let (lw, lh, limg, lpx) = (l.w, l.h, &*l.img, &*l.px); - let row = |y: usize, irow: &mut [f32], prow: &mut [Px]| { - for (x, p) in prow.iter_mut().enumerate() { - let mut n = 0.0f32; - let o = x * ch; - let (mut hole, mut all_source, mut any) = (false, true, false); - for (dx, dy) in [(0, 0), (1, 0), (0, 1), (1, 1)] { - let (sx, sy) = (x * 2 + dx, y * 2 + dy); - if sx >= lw || sy >= lh { - continue; - } - let si = sy * lw + sx; - match lpx[si] { - Px::Hole => hole = true, - Px::Void => all_source = false, - k => { - any = true; - all_source &= k == Px::Source; - for c in 0..ch { - irow[o + c] += limg[si * ch + c]; - } - n += 1.0; - } - } - } - if n > 0.0 { - for c in 0..ch { - irow[o + c] /= n; - } - } - *p = if hole { - Px::Hole - } else if !any { - Px::Void - } else if all_source { - Px::Source - } else { - Px::Known - }; - } - }; - par::chunks2_mut(&mut img, w * ch, &mut px, w, w * h >= PAR_MIN, row); - Level { w, h, img: Cow::Owned(img), px: Cow::Owned(px) } -} - -/// Summed-area table of a boolean grid (`(w+1) × (h+1)`). Not inlined: in [`synthesize`] it made -/// Create Texture's candidate loop slower (measured). -#[inline(never)] -fn integral(w: usize, h: usize, m: &[bool]) -> Vec { - let mut s = vec![0u32; (w + 1) * (h + 1)]; - for y in 0..h { - let mut row = 0u32; - for x in 0..w { - row += u32::from(m[y * w + x]); - s[(y + 1) * (w + 1) + x + 1] = s[y * (w + 1) + x + 1] + row; - } - } - s -} - -/// Count of set cells in the clipped window `[x0, x1) × [y0, y1)`. -fn window_count(s: &[u32], gw: usize, gh: usize, x0: i32, y0: i32, x1: i32, y1: i32) -> u32 { - let (x0, y0) = (x0.max(0) as usize, y0.max(0) as usize); - let (x1, y1) = ((x1.max(0) as usize).min(gw), (y1.max(0) as usize).min(gh)); - if x1 <= x0 || y1 <= y0 { - return 0; - } - let w1 = gw + 1; - s[y1 * w1 + x1] + s[y0 * w1 + x0] - s[y0 * w1 + x1] - s[y1 * w1 + x0] -} - -fn hole_bbox(w: usize, h: usize, hole: &[bool]) -> Option<(usize, usize, usize, usize)> { - let mut b: Option<(usize, usize, usize, usize)> = None; - for y in 0..h { - for x in 0..w { - if hole[y * w + x] { - b = Some(match b { - None => (x, y, x + 1, y + 1), - Some((x0, y0, x1, y1)) => (x0.min(x), y0.min(y), x1.max(x + 1), y1.max(y + 1)), - }); - } - } - } - b -} - -/// A hole at most `1 / THIN_RATIO` as thick as its bounds are long counts as thin (a wire, a -/// string, a hair, a long brush stroke): see the module docs. -const THIN_RATIO: usize = 4; - -/// How thick the hole within bounds `hb` of a `w`-wide role grid is: twice the largest distance -/// from a hole pixel to the nearest pixel that is not one (a long, thin hole is thin however long -/// its bounds). -fn hole_thickness(w: usize, hb: Bounds, px: &[Px]) -> usize { - // The bounds and a ring of non-hole cells around them (also past the grid's edge). - let (gw, gh) = (hb.width() + 2, hb.height() + 2); - let outside: Vec = par::map(gw * gh, gw * gh >= PAR_MIN, |i| { - let (gx, gy) = (i % gw, i / gw); - if gx == 0 || gy == 0 || gx > hb.width() || gy > hb.height() { - return true; - } - px.get((hb.y0 + gy - 1) * w + hb.x0 + gx - 1) != Some(&Px::Hole) - }); - let deepest = crate::selection::edt(&outside, gw, gh).into_iter().fold(0.0f32, f32::max); - (2.0 * deepest).ceil() as usize -} - -/// Most target pixels × sources the onion peel of a thin hole may compare (its search is -/// exhaustive, though most comparisons stop early: about a second at this many). -const PEEL_BUDGET: usize = 1 << 28; - -/// Whether the onion peel of the hole cells within `hb` of a `w`-wide role grid from `sources` -/// source centres stays within [`PEEL_BUDGET`]. -fn peel_affordable(w: usize, px: &[Px], hb: Bounds, sources: usize) -> bool { - let holes: usize = (hb.y0..hb.y1).map(|y| px.get(y * w + hb.x0..y * w + hb.x1).map_or(0, |row| row.iter().filter(|k| **k == Px::Hole).count())).sum(); - holes.saturating_mul(sources) <= PEEL_BUDGET -} - -/// Bounds of the hole pixels of a role grid. -fn hole_bounds(w: usize, h: usize, px: &[Px]) -> Option { - // A zero-width grid holds no pixels whatever its height; don't size a row table by it. - if w == 0 || h == 0 { - return None; - } - // Per row the first and last hole column; the union of the rows' spans. - let rows: Vec> = par::map(h, w * h >= PAR_MIN, |y| { - let row = px.get(y * w..(y + 1) * w)?; - let x0 = row.iter().position(|k| *k == Px::Hole)?; - let x1 = row.iter().rposition(|k| *k == Px::Hole).unwrap_or(x0) + 1; - Some((x0, x1)) - }); - let mut b: Option = None; - for (y, span) in rows.into_iter().enumerate() { - if let Some((x0, x1)) = span { - b = Some(match b { - None => Bounds { x0, y0: y, x1, y1: y + 1 }, - Some(b) => Bounds { x0: b.x0.min(x0), y0: b.y0, x1: b.x1.max(x1), y1: y + 1 }, - }); - } - } - b -} - -/// Valid source centres: the whole `2r+1` patch inside the grid and copyable. Found per row -/// (each pixel's horizontal run), then per column of runs. `None` when cancelled. -fn valid_sources(w: usize, h: usize, r: usize, px: &[Px], ctl: &photocraft_raster::Interrupt) -> Option> { - const BAND: usize = 64; - let side = 2 * r + 1; - let par = w * h >= PAR_MIN; - let mut run = vec![false; w * h]; - if w < side || h < side { - return Some(run); - } - // Per row: is the run of `side` pixels centred on each one all copyable (a sliding count)? - par::chunks_mut(&mut run, w, par, |y, out| { - if y % BAND == 0 && ctl.cancelled() { - return; - } - let row = &px[y * w..(y + 1) * w]; - let copyable = |x: usize| usize::from(row[x] == Px::Source); - let mut count: usize = (0..side).map(copyable).sum(); - out[r] = count == side; - for (x, o) in out.iter_mut().enumerate().take(w - r).skip(r + 1) { - count = count + copyable(x + r) - copyable(x - r - 1); - *o = count == side; - } - }); - if ctl.cancelled() { - return None; - } - // Per column, in bands of rows: how many such runs end each row in a row; a centre is valid - // where `side` of them stack up to `r` rows below it. - let mut valid = vec![false; w * h]; - par::chunks_mut(&mut valid, BAND * w, par, |band, out| { - if ctl.cancelled() { - return; - } - let (y0, rows) = (band * BAND, out.len() / w); - let mut stack = vec![0usize; w]; - for yy in y0.saturating_sub(r)..(y0 + rows + r).min(h) { - for (x, n) in stack.iter_mut().enumerate() { - *n = if run[yy * w + x] { *n + 1 } else { 0 }; - } - // `yy` is the bottom row of centre `y`'s patch. - if yy < y0 + r || yy < 2 * r { - continue; - } - let y = yy - r; - for (v, n) in out[(y - y0) * w..(y - y0 + 1) * w].iter_mut().zip(&stack).take(w - r).skip(r) { - *v = *n >= side; - } - } - }); - if ctl.cancelled() { - return None; - } - Some(valid) -} - -/// Columns per block of [`Sources`]' index. -const SOURCE_BLOCK: usize = 64; - -/// The valid source centres in row-major order, indexed by counts per row and per block of -/// [`SOURCE_BLOCK`] columns (so the `k`-th is found without listing them all). -struct Sources { - /// Valid centres before each row (`h + 1` entries). - row_start: Vec, - /// Per row, the valid centres in it before each block. - block_start: Vec, - blocks: usize, -} - -impl Sources { - fn new(valid: &[bool], w: usize) -> Sources { - let h = valid.len().checked_div(w).unwrap_or(0); - let blocks = w.div_ceil(SOURCE_BLOCK); - let mut block_start = vec![0u32; h * blocks]; - // Per row: the block prefix, and the row's count. - let counts: Vec = par::map(h, valid.len() >= PAR_MIN, |y| valid[y * w..(y + 1) * w].iter().filter(|v| **v).count()); - par::chunks_mut(&mut block_start, blocks, valid.len() >= PAR_MIN, |y, out| { - let mut n = 0u32; - for (b, o) in out.iter_mut().enumerate() { - *o = n; - n += valid[y * w + b * SOURCE_BLOCK..y * w + ((b + 1) * SOURCE_BLOCK).min(w)].iter().filter(|v| **v).count() as u32; - } - }); - let mut row_start = Vec::with_capacity(counts.len() + 1); - let mut total = 0usize; - row_start.push(0); - for c in counts { - total += c; - row_start.push(total); - } - Sources { row_start, block_start, blocks } - } - - fn len(&self) -> usize { - self.row_start.last().copied().unwrap_or(0) - } - - /// The `k`-th valid centre in row-major order (`k < len`). - fn nth(&self, k: usize, valid: &[bool], w: usize) -> (i32, i32) { - let y = self.row_start.partition_point(|&s| s <= k).saturating_sub(1); - let left = k.saturating_sub(self.row_start.get(y).copied().unwrap_or(0)); - let row_blocks = self.block_start.get(y * self.blocks..(y + 1) * self.blocks).unwrap_or(&[]); - let b = row_blocks.partition_point(|&s| s as usize <= left).saturating_sub(1); - let mut left = left.saturating_sub(row_blocks.get(b).copied().unwrap_or(0) as usize); - let x0 = b * SOURCE_BLOCK; - for (x, v) in valid.iter().skip(y * w + x0).take(w.saturating_sub(x0)).enumerate() { - if *v { - if left == 0 { - return ((x0 + x) as i32, y as i32); - } - left -= 1; - } - } - (0, 0) - } - - /// All of them, in row-major order. - fn all(&self, valid: &[bool], w: usize) -> Vec<(i32, i32)> { - let mut out = Vec::with_capacity(self.len()); - for (i, v) in valid.iter().enumerate() { - if *v { - out.push(((i % w) as i32, (i / w) as i32)); - } - } - out - } -} - -/// Per cell of `tb` (the hole's bounds `hb` grown by the patch radius, where all of them lie): is -/// it a target centre (its patch overlaps the hole)? -fn targets_around(w: usize, r: usize, px: &[Px], hb: Bounds, tb: Bounds) -> Vec { - // Hole counts summed over the hole's bounds: every hole pixel lies inside them. - let (bw, bh) = (hb.width(), hb.height()); - let mut s = vec![0u32; (bw + 1) * (bh + 1)]; - for y in 0..bh { - let mut row = 0u32; - for x in 0..bw { - row += u32::from(px[(hb.y0 + y) * w + hb.x0 + x] == Px::Hole); - s[(y + 1) * (bw + 1) + x + 1] = s[y * (bw + 1) + x + 1] + row; - } - } - let mut targets = vec![false; tb.area()]; - let ri = r as i32; - let (ox, oy) = (hb.x0 as i32, hb.y0 as i32); - for y in tb.y0..tb.y1 { - for x in tb.x0..tb.x1 { - let k = (y - tb.y0) * tb.width() + (x - tb.x0); - let (x, y) = (x as i32, y as i32); - targets[k] = window_count(&s, bw, bh, x - ri - ox, y - ri - oy, x + ri + 1 - ox, y + ri + 1 - oy) > 0; - } - } - targets -} - -/// A finished coarser level: its size, pixels and match field (the source centre per cell of -/// its target box, `i32::MIN` where there is none; empty when it had nothing to copy). -struct Coarser { - w: usize, - h: usize, - img: Vec, - field: Vec<(i32, i32)>, - tbox: Bounds, -} - -impl Coarser { - /// The match of cell `(x, y)` (`i32::MIN` outside the target box). - fn field_at(&self, x: usize, y: usize) -> (i32, i32) { - let t = self.tbox; - if x < t.x0 || x >= t.x1 || y < t.y0 || y >= t.y1 { - return (i32::MIN, i32::MIN); - } - self.field.get((y - t.y0) * t.width() + (x - t.x0)).copied().unwrap_or((i32::MIN, i32::MIN)) - } -} - -/// Most channels whose moments the colour adaptation fits (the rest are copied as they are). -const MOM_CH: usize = 8; - -/// Per-level PatchMatch/EM state. -struct Solver<'a> { - w: usize, - h: usize, - ch: usize, - r: i32, - img: &'a mut Vec, - px: &'a [Px], - /// Valid source centres: the whole patch is inside the grid and may be copied from. - valid: Vec, - /// The hole's bounds and the targets' (the hole's grown by the patch radius): nothing outside - /// them changes or is matched. The match field, its costs and these per-target tables are - /// kept over `tbox`, row-major. - hole_box: Bounds, - tbox: Bounds, - /// Target centres (the patch overlaps the hole). - targets: Vec, - /// Per cell of `tbox`: the whole patch is inside the grid and not void (so its distances - /// need no bounds checks and its own moments can be kept). - full: Vec, - /// With colour adaptation, per cell of `tbox` and channel (at most [`MOM_CH`]): `Σt, Σt²` of - /// the patch, for full patches, as of the last [`Solver::costs`]. - tmom: Vec<[f32; 2]>, - /// With colour adaptation where it pays: per source centre and channel, `Σs, Σs²` of its - /// patch (source pixels never change within a level). Empty otherwise. - smom: Vec<[f32; 2]>, - adapt: Adapt, - /// Cancellation: checked per row band; a cancelled solve's output is discarded. - ctl: photocraft_raster::Interrupt<'a>, -} - -/// A channel deviation under which a patch counts as flat for [`fit`] (about 5 levels of 255). -const FLAT: f32 = 0.02; - -/// Gain and bias of one channel for target moments `(Σt, Σt²)` and source moments `(Σs, Σs²)` -/// over `n` samples, within the limits. -#[inline] -pub(crate) fn fit(a: Adapt, n: f32, st: f32, stt: f32, ss: f32, sss: f32) -> (f32, f32) { - let (mt, ms) = (st / n, ss / n); - let vt = (stt / n - mt * mt).max(0.0); - let vs = (sss / n - ms * ms).max(0.0); - let g = if vs > 1e-10 { (vt / vs).sqrt() } else { 1.0 }; - let (mut lo, mut hi) = a.gain; - // Nearly flat patches of about the same colour (their means within the bias of each other): - // the ratio of their deviations is noise, so match the mean first, keeping the gain where the - // bias can still bring the source's mean to the target's. Gained about zero, a gain at its - // limit moved bright means further than the bias could bring back, and each channel by a - // different amount: a tinted blotch in a smooth gradient. Textured patches, and flat ones - // whose colours differ more (Content-Aware Move's Color), are fitted as before. - if vt.max(vs) < FLAT * FLAT && (mt - ms).abs() <= a.bias && ms > 1e-6 { - let (glo, ghi) = ((mt - a.bias) / ms, (mt + a.bias) / ms); - if glo.max(lo) <= ghi.min(hi) { - (lo, hi) = (glo.max(lo), ghi.min(hi)); - } - } - let g = g.clamp(lo, hi); - let b = (mt - g * ms).clamp(-a.bias, a.bias); - (g, b) -} - -impl Solver<'_> { - #[inline] - fn is_valid(&self, x: i32, y: i32) -> bool { - x >= 0 && y >= 0 && (x as usize) < self.w && (y as usize) < self.h && self.valid[y as usize * self.w + x as usize] - } - - /// Mark the full target patches (`full`), and keep the source moments where they pay off. - fn prepare(&mut self, keep_source_moments: bool) { - let (w, h, r, tb) = (self.w, self.h, self.r as usize, self.tbox); - let side = 2 * r + 1; - let mut full = vec![false; tb.area()]; - let px = self.px; - par::chunks_mut(&mut full, tb.width(), tb.area() >= PAR_MIN_PATCHES, |ty, out| { - let y = tb.y0 + ty; - if y < r || y + r >= h { - return; - } - for (tx, f) in out.iter_mut().enumerate() { - let x = tb.x0 + tx; - if x < r || x + r >= w { - continue; - } - *f = (y - r..=y + r).all(|yy| px[yy * w + x - r..yy * w + x - r + side].iter().all(|k| *k != Px::Void)); - } - }); - self.full = full; - if self.adapt.is_none() { - return; - } - let c8 = self.ch.min(MOM_CH); - self.tmom = vec![[0.0; 2]; tb.area() * c8]; - if !keep_source_moments { - return; - } - let (ch, img, valid, ctl) = (self.ch, &*self.img, &self.valid, &self.ctl); - let mut smom = vec![[0.0f32; 2]; w * h * c8]; - par::chunks_mut(&mut smom, w * c8, w * h >= PAR_MIN_PATCHES, |y, out| { - if ctl.cancelled() { - return; - } - for x in 0..w { - if valid[y * w + x] { - patch_moments(img, w, ch, c8, side, x - r, y - r, &mut out[x * c8..(x + 1) * c8]); - } - } - }); - self.smom = smom; - } - - /// Distance between the target patch at `t` (its pixels inside the grid and not void; `k` its - /// index in the `tbox` tables) and the source patch at `s`, per sample; with colour adaptation - /// the source is fitted first. - #[inline] - fn dist(&self, t: (i32, i32), k: usize, s: (i32, i32), cutoff: f32) -> f32 { - let full = self.full[k]; - if !self.adapt.is_none() { - return if full { self.dist_adapted_full(k, t, s) } else { self.dist_adapted(t, s) }; - } - if full { self.dist_full(t, s, cutoff) } else { self.dist_clipped(t, s, cutoff) } - } - - /// [`Solver::dist`] without adaptation, of a patch that may be clipped. - fn dist_clipped(&self, t: (i32, i32), s: (i32, i32), cutoff: f32) -> f32 { - let (w, h, ch, r) = (self.w as i32, self.h as i32, self.ch, self.r); - let full = ((2 * r + 1) * (2 * r + 1)) as f32 * ch as f32; - let mut sum = 0.0f32; - let mut n = 0usize; - for dy in -r..=r { - let ty = t.1 + dy; - if ty < 0 || ty >= h { - continue; - } - let sy = s.1 + dy; - for dx in -r..=r { - let tx = t.0 + dx; - if tx < 0 || tx >= w || self.px[ty as usize * self.w + tx as usize] == Px::Void { - continue; - } - let ti = (ty as usize * self.w + tx as usize) * ch; - let si = (sy as usize * self.w + (s.0 + dx) as usize) * ch; - for c in 0..ch { - let d = self.img[ti + c] - self.img[si + c]; - sum += d * d; - } - n += ch; - } - // Early out: the mean can only be ≥ sum / (full patch size). - if sum > cutoff * full { - return f32::INFINITY; - } - } - if n == 0 { f32::INFINITY } else { sum / n as f32 } - } - - /// [`Solver::dist_clipped`] of a full patch: the same sums, in the same order. It gives up - /// (infinity) as soon as the sum shows the patch is worse than `cutoff`, which the sum, only - /// growing, can show after any pixel: the caller only asks whether it is better. - fn dist_full(&self, t: (i32, i32), s: (i32, i32), cutoff: f32) -> f32 { - let (w, ch, r) = (self.w, self.ch, self.r); - let side = (2 * r + 1) as usize; - let full = ((2 * r + 1) * (2 * r + 1)) as f32 * ch as f32; - let (span, limit) = (side * ch, cutoff * full); - let mut sum = 0.0f32; - for dy in -r..=r { - let ti = ((t.1 + dy) as usize * w + (t.0 - r) as usize) * ch; - let si = ((s.1 + dy) as usize * w + (s.0 - r) as usize) * ch; - for (tp, sp) in self.img[ti..ti + span].chunks_exact(ch).zip(self.img[si..si + span].chunks_exact(ch)) { - for (a, b) in tp.iter().zip(sp) { - let d = a - b; - sum += d * d; - } - if sum > limit { - return f32::INFINITY; - } - } - } - sum / (side * side * ch) as f32 - } - - /// Moments of the target patch at `t` and the source patch at `s` per channel: - /// `[Σt, Σt², Σs, Σs², Σts]`, and the sample count. - fn moments(&self, t: (i32, i32), s: (i32, i32), m: &mut [[f32; 5]]) -> usize { - let (w, h, ch, r) = (self.w as i32, self.h as i32, self.ch, self.r); - m.iter_mut().for_each(|v| *v = [0.0; 5]); - let mut n = 0usize; - for dy in -r..=r { - let ty = t.1 + dy; - if ty < 0 || ty >= h { - continue; - } - let sy = s.1 + dy; - for dx in -r..=r { - let tx = t.0 + dx; - if tx < 0 || tx >= w || self.px[ty as usize * self.w + tx as usize] == Px::Void { - continue; - } - let ti = (ty as usize * self.w + tx as usize) * ch; - let si = (sy as usize * self.w + (s.0 + dx) as usize) * ch; - for (c, mc) in m.iter_mut().enumerate().take(ch) { - let (a, b) = (self.img[ti + c], self.img[si + c]); - mc[0] += a; - mc[1] += a * a; - mc[2] += b; - mc[3] += b * b; - mc[4] += a * b; - } - n += 1; - } - } - n - } - - /// [`Solver::moments`] of a full target patch (`k` in the `tbox` tables): the target's own - /// sums kept from [`Solver::costs`], the source's from [`Solver::prepare`] when kept, each - /// summed in the same order as there. - fn moments_full(&self, k: usize, t: (i32, i32), s: (i32, i32), m: &mut [[f32; 5]]) { - let (w, ch, r) = (self.w, self.ch, self.r); - let c8 = m.len(); - let side = (2 * r + 1) as usize; - let tm = &self.tmom[k * c8..(k + 1) * c8]; - let sm = self.smom.get((s.1 as usize * w + s.0 as usize) * c8..(s.1 as usize * w + s.0 as usize + 1) * c8); - let mut acc = [[0.0f32; 3]; MOM_CH]; - for dy in -r..=r { - let ti = ((t.1 + dy) as usize * w + (t.0 - r) as usize) * ch; - let si = ((s.1 + dy) as usize * w + (s.0 - r) as usize) * ch; - let (trow, srow) = (&self.img[ti..ti + side * ch], &self.img[si..si + side * ch]); - if sm.is_some() { - for (tp, sp) in trow.chunks_exact(ch).zip(srow.chunks_exact(ch)) { - for c in 0..c8 { - acc[c][2] += tp[c] * sp[c]; - } - } - } else { - for (tp, sp) in trow.chunks_exact(ch).zip(srow.chunks_exact(ch)) { - for c in 0..c8 { - let (a, b) = (tp[c], sp[c]); - acc[c][0] += b; - acc[c][1] += b * b; - acc[c][2] += a * b; - } - } - } - } - for (c, mc) in m.iter_mut().enumerate() { - let [ss, sss] = match sm { - Some(sm) => sm[c], - None => [acc[c][0], acc[c][1]], - }; - *mc = [tm[c][0], tm[c][1], ss, sss, acc[c][2]]; - } - } - - fn dist_adapted(&self, t: (i32, i32), s: (i32, i32)) -> f32 { - let mut m = [[0.0f32; 5]; MOM_CH]; - let ch = self.ch.min(MOM_CH); - let n = self.moments(t, s, &mut m[..ch]); - if n == 0 { - return f32::INFINITY; - } - adapted_cost(self.adapt, n as f32, &m[..ch]) - } - - fn dist_adapted_full(&self, k: usize, t: (i32, i32), s: (i32, i32)) -> f32 { - let mut m = [[0.0f32; 5]; MOM_CH]; - let ch = self.ch.min(MOM_CH); - self.moments_full(k, t, s, &mut m[..ch]); - let side = (2 * self.r + 1) as usize; - adapted_cost(self.adapt, (side * side) as f32, &m[..ch]) - } - - /// Gain and bias per channel for the match `t → s` (identity without adaptation). - fn transform(&self, t: (i32, i32), k: usize, s: (i32, i32), out: &mut [(f32, f32)]) { - if self.adapt.is_none() { - out.iter_mut().for_each(|v| *v = (1.0, 0.0)); - return; - } - let mut m = [[0.0f32; 5]; MOM_CH]; - let ch = self.ch.min(MOM_CH); - let n = if self.full[k] { - self.moments_full(k, t, s, &mut m[..ch]); - let side = (2 * self.r + 1) as usize; - side * side - } else { - self.moments(t, s, &mut m[..ch]) - }; - for (c, o) in out.iter_mut().enumerate() { - *o = if n == 0 || c >= ch { (1.0, 0.0) } else { fit(self.adapt, n as f32, m[c][0], m[c][1], m[c][2], m[c][3]) }; - } - } - - /// One PatchMatch step at target `t` (`k` in the target box) whose match is `cur`: propagation - /// from the matches of the neighbours visited just before it (`left` in its row, `up` in its - /// column, in this pass's direction `step`), then random search in exponentially shrinking - /// windows around the best (two numbers from `rng` per window). - #[allow(clippy::too_many_arguments)] - #[inline] - fn pm_step( - &self, - t: (i32, i32), - k: usize, - cur: ((i32, i32), f32), - left: Option<(i32, i32)>, - up: Option<(i32, i32)>, - step: i32, - rng: &mut Rng, - search_radius: i32, - ) -> ((i32, i32), f32) { - let (mut best, mut bc) = cur; - if let Some(c) = left { - let cand = (c.0 + step, c.1); - if self.is_valid(cand.0, cand.1) && cand != best { - let d = self.dist(t, k, cand, bc); - if d < bc { - (best, bc) = (cand, d); - } - } - } - if let Some(c) = up { - let cand = (c.0, c.1 + step); - if self.is_valid(cand.0, cand.1) && cand != best { - let d = self.dist(t, k, cand, bc); - if d < bc { - (best, bc) = (cand, d); - } - } - } - let mut rad = search_radius; - while rad >= 1 { - let cand = (best.0 + rng.range(-rad, rad), best.1 + rng.range(-rad, rad)); - if self.is_valid(cand.0, cand.1) && cand != best { - let d = self.dist(t, k, cand, bc); - if d < bc { - (best, bc) = (cand, d); - } - } - rad /= 2; - } - (best, bc) - } - - /// One PatchMatch pass over all target rows, in bands of the grid's rows: each band is - /// visited in raster order (backwards on odd passes), propagating within itself, its random - /// numbers seeded by its index. `nnf` and `cost` are over the target box. The bands run in - /// parallel; when there are fewer of them than threads, each is also swept in wavefronts of - /// blocks (a cell depends only on its neighbours before it in its row and its column), which - /// visits every cell with the same neighbours and random numbers as the raster order. - fn patchmatch(&self, nnf: &mut [(i32, i32)], cost: &mut [f32], pass: usize, seed: u64, search_radius: i32) { - const BAND: usize = 16; - let tb = self.tbox; - let tw = tb.width(); - if tw == 0 || tb.height() == 0 || nnf.len() < tb.area() || cost.len() < tb.area() { - return; - } - let reverse = pass % 2 == 1; - let step: i32 = if reverse { -1 } else { 1 }; - let band_seed = |bi: usize| seed ^ (bi as u64).wrapping_mul(0x2545_F491_4F6C_DD1D) ^ ((pass as u64) << 40); - // The bands crossing the target box: index, first row, rows in the box. - let mut bands = Vec::new(); - let mut y = tb.y0; - while y < tb.y1 { - let bi = y / BAND; - let end = ((bi + 1) * BAND).min(tb.y1); - bands.push((bi, y, end - y)); - y = end; - } - let threads = par::threads(); - if tb.area() >= PAR_MIN_PATCHES * 8 && !bands.is_empty() && bands.len() < threads { - self.patchmatch_wavefront(nnf, cost, &bands, reverse, &band_seed, search_radius); - return; - } - let band_fn = |bi: usize, ys: usize, nn: &mut [(i32, i32)], co: &mut [f32]| { - if self.ctl.cancelled() { - return; - } - let rows = nn.len() / tw; - let mut rng = Rng::new(band_seed(bi)); - for ry in 0..rows { - if self.ctl.cancelled() { - return; - } - let ly = if reverse { rows - 1 - ry } else { ry }; - let y = ys + ly; - for rx in 0..tw { - let lx = if reverse { tw - 1 - rx } else { rx }; - let li = ly * tw + lx; - let k = (y - tb.y0) * tw + lx; - if !self.targets[k] { - continue; - } - // Neighbours outside the target box hold no match: nothing to try. - let nx = lx as i32 - step; - let left = (nx >= 0 && (nx as usize) < tw).then(|| nn[ly * tw + nx as usize]); - let nly = ly as i32 - step; - let up = (nly >= 0 && (nly as usize) < rows).then(|| nn[nly as usize * tw + lx]); - let t = ((tb.x0 + lx) as i32, y as i32); - (nn[li], co[li]) = self.pm_step(t, k, (nn[li], co[li]), left, up, step, &mut rng, search_radius); - } - } - }; - // The target box's rows, band by band. - let mut parts = Vec::with_capacity(bands.len()); - let (mut nn_rest, mut co_rest) = (&mut nnf[..tb.area()], &mut cost[..tb.area()]); - for &(bi, ys, rows) in &bands { - let (nn, nr) = std::mem::take(&mut nn_rest).split_at_mut(rows * tw); - let (co, cr) = std::mem::take(&mut co_rest).split_at_mut(rows * tw); - parts.push((bi, ys, nn, co)); - (nn_rest, co_rest) = (nr, cr); - } - let par = tb.area() >= PAR_MIN_PATCHES && parts.len() > 1; - par::each(parts, par, |(bi, ys, nn, co)| band_fn(bi, ys, nn, co)); - } - - /// [`Solver::patchmatch`] swept in wavefronts: the cells of each band in blocks of a row, a - /// block once the block before it in its row and the one above it (in the pass's direction) - /// are done. A target's random numbers are those it would draw in raster order (each target - /// draws the same count). - fn patchmatch_wavefront( - &self, - nnf: &mut [(i32, i32)], - cost: &mut [f32], - bands: &[(usize, usize, usize)], - reverse: bool, - band_seed: &(dyn Fn(usize) -> u64 + Sync), - search_radius: i32, - ) { - use std::sync::atomic::{AtomicU32, AtomicU64, Ordering::Relaxed}; - - let tb = self.tbox; - let tw = tb.width(); - let step: i32 = if reverse { -1 } else { 1 }; - let pack = |(x, y): (i32, i32)| (u64::from(x as u32) << 32) | u64::from(y as u32); - let unpack = |v: u64| ((v >> 32) as u32 as i32, v as u32 as i32); - // Random numbers each target draws. - let mut draws = 0u64; - let mut rad = search_radius; - while rad >= 1 { - draws += 2; - rad /= 2; - } - // Targets before each column of each row of the box. - let mut before = vec![0u32; tb.height() * (tw + 1)]; - for (ry, row) in before.chunks_mut(tw + 1).enumerate() { - for lx in 0..tw { - row[lx + 1] = row[lx] + u32::from(self.targets[ry * tw + lx]); - } - } - // Targets visited before each of a band's rows (in the pass's order). - let row_base: Vec> = bands - .iter() - .map(|&(_, ys, rows)| { - let mut base = Vec::with_capacity(rows); - let mut n = 0u64; - for pr in 0..rows { - base.push(n); - let ly = if reverse { rows - 1 - pr } else { pr }; - n += u64::from(before[(ys + ly - tb.y0) * (tw + 1) + tw]); - } - base - }) - .collect(); - let block = (tw / 8).clamp(4, 32); - let blocks = tw.div_ceil(block); - let nn: Vec = nnf[..tb.area()].iter().map(|m| AtomicU64::new(pack(*m))).collect(); - let co: Vec = cost[..tb.area()].iter().map(|c| AtomicU32::new(c.to_bits())).collect(); - let sweep = |(j, pr, b): (usize, usize, usize)| { - let (bi, ys, rows) = bands[j]; - let ly = if reverse { rows - 1 - pr } else { pr }; - let y = ys + ly; - let ry = y - tb.y0; - let (pc0, pc1) = (b * block, ((b + 1) * block).min(tw)); - // The targets visited before this block, in raster order. - let first = if reverse { tw - 1 - pc0 } else { pc0 }; - let row = &before[ry * (tw + 1)..(ry + 1) * (tw + 1)]; - let in_row = if reverse { row[tw] - row[first + 1] } else { row[first] }; - let mut rng = Rng::new(band_seed(bi)); - rng.skip((row_base[j][pr] + u64::from(in_row)) * draws); - for pc in pc0..pc1 { - let lx = if reverse { tw - 1 - pc } else { pc }; - let k = ry * tw + lx; - if !self.targets[k] { - continue; - } - let nx = lx as i32 - step; - let left = (nx >= 0 && (nx as usize) < tw).then(|| unpack(nn[ry * tw + nx as usize].load(Relaxed))); - let nly = ly as i32 - step; - let up = (nly >= 0 && (nly as usize) < rows).then(|| unpack(nn[(ys + nly as usize - tb.y0) * tw + lx].load(Relaxed))); - let cur = (unpack(nn[k].load(Relaxed)), f32::from_bits(co[k].load(Relaxed))); - let t = ((tb.x0 + lx) as i32, y as i32); - let (m, c) = self.pm_step(t, k, cur, left, up, step, &mut rng, search_radius); - nn[k].store(pack(m), Relaxed); - co[k].store(c.to_bits(), Relaxed); - } - }; - // Wavefront `d`: block `b` of (visited) row `pr` with `pr + b = d`, in every band. Each - // wave ends before the next starts. - let longest = bands.iter().map(|b| b.2).max().unwrap_or(0); - for d in 0..longest + blocks - 1 { - if self.ctl.cancelled() { - return; - } - let wave: Vec<(usize, usize, usize)> = bands - .iter() - .enumerate() - .flat_map(|(j, &(_, _, rows))| (0..rows).filter(move |&pr| pr <= d && d - pr < blocks).map(move |pr| (j, pr, d - pr))) - .collect(); - par::each(wave, true, sweep); - } - for (m, a) in nnf.iter_mut().zip(&nn) { - *m = unpack(a.load(Relaxed)); - } - for (c, a) in cost.iter_mut().zip(&co) { - *c = f32::from_bits(a.load(Relaxed)); - } - } - - /// Recompute every target's match cost (hole pixels change between iterations), and with - /// colour adaptation the full target patches' own moments. - fn costs(&mut self, nnf: &[(i32, i32)], cost: &mut [f32]) -> Result<(), photocraft_raster::Cancelled> { - let (w, ch, r, tb) = (self.w, self.ch, self.r as usize, self.tbox); - let par = tb.area() >= PAR_MIN_PATCHES; - self.ctl.check()?; - if !self.adapt.is_none() { - let c8 = ch.min(MOM_CH); - let side = 2 * r + 1; - let mut tmom = std::mem::take(&mut self.tmom); - let (img, full, ctl) = (&*self.img, &self.full, &self.ctl); - par::chunks_mut(&mut tmom, tb.width() * c8, par, |ty, out| { - if ctl.cancelled() { - return; - } - for tx in 0..tb.width() { - if full[ty * tb.width() + tx] { - patch_moments(img, w, ch, c8, side, tb.x0 + tx - r, tb.y0 + ty - r, &mut out[tx * c8..(tx + 1) * c8]); - } - } - }); - self.tmom = tmom; - } - let this = &*self; - par::chunks_mut(cost, tb.width(), par, |ty, co| { - if this.ctl.cancelled() { - return; - } - let y = tb.y0 + ty; - for (tx, c) in co.iter_mut().enumerate() { - let k = ty * tb.width() + tx; - if this.targets[k] { - *c = this.dist(((tb.x0 + tx) as i32, y as i32), k, nnf[k], f32::INFINITY); - } - } - }); - self.ctl.check() - } - - /// Re-estimate hole pixels by a similarity-weighted vote of all overlapping patch matches - /// (each copy adjusted by its gain and bias). - fn vote(&mut self, nnf: &[(i32, i32)], cost: &[f32]) { - let (w, h, ch, r) = (self.w, self.h, self.ch, self.r); - let (tb, hb) = (self.tbox, self.hole_box); - // A cancelled solve is thrown away. - if self.ctl.cancelled() { - return; - } - let used = |k: usize| self.targets[k] && cost[k].is_finite(); - // σ² from the 75th percentile of match costs (Wexler et al. use a robust scale like this). - let cs: Vec = (0..tb.area()).filter(|&k| used(k)).map(|k| cost[k]).collect(); - let mut cs = cs; - let sigma2 = if cs.is_empty() { - 1.0 - } else { - let k = (cs.len() * 3 / 4).min(cs.len() - 1); - let (_, v, _) = cs.select_nth_unstable_by(k, |a, b| a.total_cmp(b)); - v.max(1e-6) - }; - drop(cs); - // Each target's weight and photometric transform (computed once, used by every pixel it - // covers). - let adapted = !self.adapt.is_none(); - let par = tb.area() >= PAR_MIN_PATCHES; - // A weight (zero for a target that doesn't vote) and its match's centre (as a pixel - // index) per target. - let mut wt = vec![0.0f32; tb.area()]; - let mut src = vec![0isize; tb.area()]; - par::chunks2_mut(&mut wt, tb.width(), &mut src, tb.width(), par, |ty, wrow, srow| { - for (tx, (o, sc)) in wrow.iter_mut().zip(srow.iter_mut()).enumerate() { - let k = ty * tb.width() + tx; - if used(k) { - *o = (-cost[k] / (2.0 * sigma2)).exp().max(1e-8); - *sc = nnf[k].1 as isize * w as isize + nnf[k].0 as isize; - } - } - }); - let mut gb: Vec<(f32, f32)> = Vec::new(); - if adapted { - gb = vec![(1.0f32, 0.0f32); tb.area() * ch]; - let this = &*self; - par::chunks_mut(&mut gb, tb.width() * ch, par, |ty, out| { - if this.ctl.cancelled() { - return; - } - let y = tb.y0 + ty; - for tx in 0..tb.width() { - let k = ty * tb.width() + tx; - if used(k) { - this.transform(((tb.x0 + tx) as i32, y as i32), k, nnf[k], &mut out[tx * ch..(tx + 1) * ch]); - } - } - }); - } - // The vote, into a buffer over the hole's bounds (every pixel reads the old pixels). - let votes = Votes { w, h, ch, r: r as usize, tbox: tb, img: &*self.img, wt: &wt, src: &src, gb: &gb }; - let (px, ctl) = (self.px, &self.ctl); - let mut out = vec![0.0f32; hb.area() * ch]; - let mut got = vec![false; hb.area()]; - let row = |yy: usize, orow: &mut [f32], grow: &mut [bool]| { - if ctl.cancelled() { - return; - } - let y = hb.y0 + yy; - for x in hb.x0..hb.x1 { - if px[y * w + x] != Px::Hole { - continue; - } - let o = (x - hb.x0) * ch; - let dst = &mut orow[o..o + ch]; - grow[x - hb.x0] = match (ch, adapted) { - (1, false) => votes.pixel::<1, false>(x, y, dst), - (3, false) => votes.pixel::<3, false>(x, y, dst), - (4, false) => votes.pixel::<4, false>(x, y, dst), - (1, true) => votes.pixel::<1, true>(x, y, dst), - (3, true) => votes.pixel::<3, true>(x, y, dst), - (4, true) => votes.pixel::<4, true>(x, y, dst), - _ => votes.pixel_any(x, y, adapted, dst), - }; - } - }; - par::chunks2_mut(&mut out, hb.width() * ch, &mut got, hb.width(), hb.area() >= PAR_MIN_PATCHES, row); - for yy in 0..hb.height() { - for xx in 0..hb.width() { - if got[yy * hb.width() + xx] { - let (d, s) = (((hb.y0 + yy) * w + hb.x0 + xx) * ch, (yy * hb.width() + xx) * ch); - self.img[d..d + ch].copy_from_slice(&out[s..s + ch]); - } - } - } - } -} - -/// What [`Solver::vote`] votes with: per target (over the target box) its weight (zero when it -/// doesn't vote), its match's centre as a pixel index, and with colour adaptation its gain and -/// bias per channel. -struct Votes<'a> { - w: usize, - h: usize, - ch: usize, - r: usize, - tbox: Bounds, - img: &'a [f32], - wt: &'a [f32], - src: &'a [isize], - gb: &'a [(f32, f32)], -} - -impl Votes<'_> { - /// Hole pixel `(x, y)`'s vote into `out` (`CH` channels): the weighted mean of what the - /// matches of the patches covering it put there, summed patch by patch in raster order of - /// their centres. False when no patch votes. - #[inline(always)] - fn pixel(&self, x: usize, y: usize, out: &mut [f32]) -> bool { - let (w, r, tb) = (self.w, self.r, self.tbox); - let mut acc = [0.0f32; CH]; - let mut wsum = 0.0f32; - for ty in y.saturating_sub(r)..=(y + r).min(self.h - 1) { - let dy = ty as isize - y as isize; - let krow = (ty - tb.y0) * tb.width(); - for tx in x.saturating_sub(r)..=(x + r).min(w - 1) { - let k = krow + tx - tb.x0; - let wt = self.wt[k]; - if wt == 0.0 { - continue; - } - // The pixel of the match's patch that lands here. - let si = (self.src[k] - dy * w as isize - (tx as isize - x as isize)) as usize * CH; - let s = &self.img[si..si + CH]; - for c in 0..CH { - let v = if ADAPT { - let (g, b) = self.gb[k * CH + c]; - g * s[c] + b - } else { - s[c] - }; - acc[c] += v * wt; - } - wsum += wt; - } - } - if wsum > 0.0 { - for (d, a) in out.iter_mut().zip(&acc) { - *d = a / wsum; - } - return true; - } - false - } - - /// [`Votes::pixel`] for any number of channels. - fn pixel_any(&self, x: usize, y: usize, adapted: bool, out: &mut [f32]) -> bool { - let (w, r, tb, ch) = (self.w, self.r, self.tbox, self.ch); - let mut acc = vec![0.0f32; ch]; - let mut wsum = 0.0f32; - for ty in y.saturating_sub(r)..=(y + r).min(self.h - 1) { - let dy = ty as isize - y as isize; - let krow = (ty - tb.y0) * tb.width(); - for tx in x.saturating_sub(r)..=(x + r).min(w - 1) { - let k = krow + tx - tb.x0; - let wt = self.wt[k]; - if wt == 0.0 { - continue; - } - let si = (self.src[k] - dy * w as isize - (tx as isize - x as isize)) as usize * ch; - for (c, a) in acc.iter_mut().enumerate() { - let v = if adapted { - let (g, b) = self.gb[k * ch + c]; - g * self.img[si + c] + b - } else { - self.img[si + c] - }; - *a += v * wt; - } - wsum += wt; - } - } - if wsum > 0.0 { - for (d, a) in out.iter_mut().zip(&acc) { - *d = a / wsum; - } - return true; - } - false - } -} - -/// `Σv, Σv²` per channel (the first `out.len()`) of the `side × side` patch with top-left -/// `(x0, y0)`, summed row by row, pixel by pixel, as [`Solver::moments`] does. -#[allow(clippy::too_many_arguments)] -fn patch_moments(img: &[f32], w: usize, ch: usize, c8: usize, side: usize, x0: usize, y0: usize, out: &mut [[f32; 2]]) { - out.iter_mut().for_each(|v| *v = [0.0; 2]); - for y in y0..y0 + side { - let row = &img[(y * w + x0) * ch..(y * w + x0 + side) * ch]; - for p in row.chunks_exact(ch) { - for (c, o) in out.iter_mut().enumerate().take(c8) { - let a = p[c]; - o[0] += a; - o[1] += a * a; - } - } - } -} - -/// The adapted distance from the moments `[Σt, Σt², Σs, Σs², Σts]` of each channel over `n` -/// samples: what is left of the target after the source is fitted to it, per sample. -#[inline] -fn adapted_cost(a: Adapt, nf: f32, m: &[[f32; 5]]) -> f32 { - let mut sum = 0.0f32; - for mc in m { - let (g, b) = fit(a, nf, mc[0], mc[1], mc[2], mc[3]); - // Σ (t − g s − b)², expanded. - sum += mc[1] + g * g * mc[3] + nf * b * b - 2.0 * g * mc[4] - 2.0 * b * mc[0] + 2.0 * g * b * mc[2]; - } - sum.max(0.0) / (nf * m.len() as f32) -} - -/// `Σ (t − s)²` over a target patch's known pixels (offsets `offs` from its centre, samples -/// `tv`, `CH` per pixel) against the source patch centred at pixel `base`, summed in that order; -/// `None` once the sum reaches `limit` (it only grows). -#[inline(always)] -fn known_sse(image: &[f32], offs: &[isize], tv: &[f32], base: isize, limit: f32) -> Option { - let mut e = 0.0f32; - for (o, t) in offs.iter().zip(tv.as_chunks::().0) { - let si = (base + o) as usize * CH; - let s = &image[si..si + CH]; - for c in 0..CH { - let d = t[c] - s[c]; - e += d * d; - } - if e >= limit { - return None; - } - } - Some(e) -} - -/// [`known_sse`] of [`LANES`] sources at once, each against its own limit (summed in step: the -/// sums are independent, so the processor overlaps them). -#[inline(always)] -fn known_sse_lanes(image: &[f32], offs: &[isize], tv: &[f32], bases: [isize; LANES], limits: [f32; LANES]) -> [Option; LANES] { - let mut e = [0.0f32; LANES]; - for (o, t) in offs.iter().zip(tv.as_chunks::().0) { - for l in 0..LANES { - let si = (bases[l] + o) as usize * CH; - let s = &image[si..si + CH]; - for c in 0..CH { - let d = t[c] - s[c]; - e[l] += d * d; - } - } - // Sums only grow: once all of them reached their limits, none can win. - if (0..LANES).all(|l| e[l] >= limits[l]) { - break; - } - } - std::array::from_fn(|l| (e[l] < limits[l]).then_some(e[l])) -} - -/// Sources [`known_sse_lanes`] sums at once. -const LANES: usize = 4; - -/// [`known_sse`] for any number of channels. -fn known_sse_any(image: &[f32], ch: usize, offs: &[isize], tv: &[f32], base: isize, limit: f32) -> Option { - let mut e = 0.0f32; - for (o, t) in offs.iter().zip(tv.chunks_exact(ch.max(1))) { - let si = (base + o) as usize * ch; - for (tc, sc) in t.iter().zip(&image[si..si + ch]) { - let d = tc - sc; - e += d * d; - } - if e >= limit { - return None; - } - } - Some(e) -} - -/// The best source so far of [`onion_peel`]'s search. -#[derive(Clone, Copy)] -struct Best { - /// Error per sample, and the place in the sources. - v: f32, - j: usize, - /// Sums of squared errors from which `sum / n` is above `v`, and at least `v`. - worse: f32, - equal: f32, -} - -/// The least sum `e ≥ 0` with `e / n > v` (`strict`) or `e / n ≥ v` in float arithmetic (the -/// quotient only grows with `e`); infinity for an infinite `v`. -fn least_sum(v: f32, n: f32, strict: bool) -> f32 { - let holds = |e: f32| if strict { e / n > v } else { e / n >= v }; - if !v.is_finite() || !n.is_finite() || n <= 0.0 { - return f32::INFINITY; - } - let mut e = (v * n).max(0.0); - while e > 0.0 && holds(e.next_down()) { - e = e.next_down(); - } - while !holds(e) && e < f32::INFINITY { - e = e.next_up(); - } - e -} - -/// Fill the hole from its edge inwards, one ring at a time: each pixel takes the centre of the -/// source patch that best matches what is already known around it (the first in `sources` of -/// those that match best). `hb` bounds the hole. -/// -/// The search is exhaustive, but most sources are given up early (#2771, #2805): the target's -/// known pixels are gathered once, the search starts from where the pixel's filled neighbours -/// took their sources (or every 16th source at the hole's edge), and a source's error stops being -/// added up once it can only lose (it only grows). So it finds the same source as a plain scan in -/// order, sooner. -#[allow(clippy::too_many_arguments)] -fn onion_peel( - w: usize, - h: usize, - ch: usize, - r: i32, - img: &mut [f32], - px: &[Px], - hb: Bounds, - sources: &[(i32, i32)], - ctl: &photocraft_raster::Interrupt, -) -> Result<(), photocraft_raster::Cancelled> { - const NONE: u32 = u32::MAX; - let mut known: Vec = px.iter().map(|k| matches!(k, Px::Known | Px::Source)).collect(); - // Each source centre's place in `sources`, and the source each filled pixel took. - let mut index = vec![NONE; w * h]; - for (j, &(x, y)) in sources.iter().enumerate() { - index[y as usize * w + x as usize] = j as u32; - } - let mut took = vec![NONE; w * h]; - let neighbours = [(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)]; - loop { - ctl.check()?; - let mut front: Vec = Vec::new(); - for y in hb.y0..hb.y1 { - for x in hb.x0..hb.x1 { - let i = y * w + x; - if known[i] || px[i] != Px::Hole { - continue; - } - let (x, y) = (x as i32, y as i32); - let edge = (-1..=1).any(|dy: i32| { - (-1..=1).any(|dx: i32| { - let (nx, ny) = (x + dx, y + dy); - nx >= 0 && ny >= 0 && (nx as usize) < w && (ny as usize) < h && known[ny as usize * w + nx as usize] - }) - }); - if edge { - front.push(i); - } - } - } - if front.is_empty() { - break; - } - let (known_now, took_now) = (&known, &took); - let image = &*img; - let best = |&i: &usize| -> (Vec, u32) { - let (x, y) = ((i % w) as i32, (i / w) as i32); - // The known pixels of the target patch, in the plain scan's order: each one's offset - // from the patch centre (in pixels) and its samples (gathered once, #2805). - let side = (2 * r + 1) as usize; - let mut offs: Vec = Vec::with_capacity(side * side); - let mut tv: Vec = Vec::with_capacity(side * side * ch); - for dy in -r..=r { - for dx in -r..=r { - let (tx, ty) = (x + dx, y + dy); - if tx >= 0 && ty >= 0 && (tx as usize) < w && (ty as usize) < h && known_now[ty as usize * w + tx as usize] { - let ti = (ty as usize * w + tx as usize) * ch; - offs.push(dy as isize * w as isize + dx as isize); - tv.extend_from_slice(&image[ti..ti + ch]); - } - } - } - // The best so far: its error per sample, its place in `sources` (the first of equals - // wins, as in a scan in order), and the sums of squares at which a source surely loses - // to it (`e / n` above the best) or ties it (at least the best). - let mut best = Best { v: f32::INFINITY, j: usize::MAX, worse: f32::INFINITY, equal: f32::INFINITY }; - if !offs.is_empty() { - let nf = offs.len() as f32; - let base_of = |j: usize| sources.get(j).map_or(0, |&(sx, sy)| sy as isize * w as isize + sx as isize); - // The sum at which source `j` can't win: a tie loses to an earlier source. - let limit_of = |j: usize, best: &Best| if j > best.j { best.equal } else { best.worse }; - // Source `j`'s whole sum `e` (it did not reach its limit): does it win? - let adopt = |j: usize, e: f32, best: &mut Best| { - let v = e / nf; - if v < f32::INFINITY && (v < best.v || (v == best.v && j < best.j)) { - *best = Best { v, j, worse: least_sum(v, nf, true), equal: least_sum(v, nf, false) }; - } - }; - let consider = |j: usize, best: &mut Best| { - if j >= sources.len() { - return; - } - let (base, limit) = (base_of(j), limit_of(j, best)); - let e = match ch { - 1 => known_sse::<1>(image, &offs, &tv, base, limit), - 3 => known_sse::<3>(image, &offs, &tv, base, limit), - 4 => known_sse::<4>(image, &offs, &tv, base, limit), - _ => known_sse_any(image, ch, &offs, &tv, base, limit), - }; - if let Some(e) = e { - adopt(j, e, best); - } - }; - // A close bound early: where the filled neighbours' sources point (shifted as in - // PatchMatch's propagation), or at the hole's edge, where none is filled yet, - // every 16th source. - for (dx, dy) in neighbours { - let (qx, qy) = (x + dx, y + dy); - if qx < 0 || qy < 0 || qx as usize >= w || qy as usize >= h { - continue; - } - let Some(&(sx, sy)) = sources.get(took_now[qy as usize * w + qx as usize] as usize) else { continue }; - let (cx, cy) = (sx - dx, sy - dy); - if cx >= 0 && cy >= 0 && (cx as usize) < w && (cy as usize) < h && index[cy as usize * w + cx as usize] != NONE { - consider(index[cy as usize * w + cx as usize] as usize, &mut best); - } - } - if best.j == usize::MAX { - for j in (0..sources.len()).step_by(16) { - consider(j, &mut best); - } - } - // The scan in order, `LANES` sources at a time (their sums are independent, so they - // overlap), each against its limit from the best before them: the best only gets - // better, so a source given up would have lost to it anyway. - let mut j = 0; - while j + LANES <= sources.len() { - if j.is_multiple_of(4096) && j > 0 && ctl.cancelled() { - break; - } - let bases: [isize; LANES] = std::array::from_fn(|l| base_of(j + l)); - let limits: [f32; LANES] = std::array::from_fn(|l| limit_of(j + l, &best)); - let sums = match ch { - 1 => known_sse_lanes::<1>(image, &offs, &tv, bases, limits), - 3 => known_sse_lanes::<3>(image, &offs, &tv, bases, limits), - 4 => known_sse_lanes::<4>(image, &offs, &tv, bases, limits), - _ => std::array::from_fn(|l| known_sse_any(image, ch, &offs, &tv, bases[l], limits[l])), - }; - for (l, e) in sums.into_iter().enumerate() { - if let Some(e) = e { - adopt(j + l, e, &mut best); - } - } - j += LANES; - } - for j in j..sources.len() { - consider(j, &mut best); - } - } - let (sx, sy) = sources.get(best.j).copied().unwrap_or((0, 0)); - let si = (sy as usize * w + sx as usize) * ch; - (image[si..si + ch].to_vec(), if best.j == usize::MAX { NONE } else { best.j as u32 }) - }; - let vals: Vec<(Vec, u32)> = par::map(front.len(), front.len() * sources.len() >= 4096, |k| best(&front[k])); - ctl.check()?; - for (&i, (v, j)) in front.iter().zip(vals) { - img[i * ch..(i + 1) * ch].copy_from_slice(&v); - known[i] = true; - took[i] = j; - } - } - Ok(()) -} - /// Content-aware completion of `hole` (see module docs), copying from any pixel outside it. Returns /// `None` when there is no fully-known patch to copy from (the caller can fall back to /// [`membrane_fill`]). @@ -1820,685 +370,5 @@ fn complete_cow<'a>( Ok(prev.map(|c| c.img).ok_or(Cow::Owned(Vec::new()))) } -/// Proximity match: the displacement `(dx, dy)` (within `max_radius`) whose surroundings best match the -/// ring of `ring` pixels around the hole, with the displaced hole fully inside the grid and outside the -/// hole. `None` if no displacement fits. -pub fn best_offset(w: usize, h: usize, ch: usize, img: &[f32], hole: &[bool], ring: usize, max_radius: i32) -> Option<(i32, i32)> { - let (bx0, by0, bx1, by1) = hole_bbox(w, h, hole)?; - // No valid translation can move farther than the source image's extent. - // Bound arbitrary public API inputs before constructing i32 search ranges: - // usize -> i32 truncation and signed increments otherwise overflow or hang. - let extent = w.max(h).min((i32::MAX / 4) as usize) as i32; - let max_radius = max_radius.max(0).min(extent); - if max_radius == 0 { - return None; - } - let ring = ring.max(1).min(extent as usize) as i32; - // Every set cell lies in the hole bounds. Counts outside that rectangle are zero, - // so source rejection needs a table for the hole, not for the whole photo. - let hs = HoleIntegral::new(w, hole, (bx0, by0, bx1, by1))?; - // Sample points: the hole's ring (dilated minus hole), subsampled for speed. - let mut pts = Vec::new(); - let (x0, y0) = (bx0 as i32 - ring, by0 as i32 - ring); - let (x1, y1) = (bx1 as i32 + ring, by1 as i32 + ring); - for y in y0.max(0)..y1.min(h as i32) { - for x in x0.max(0)..x1.min(w as i32) { - if hole[y as usize * w + x as usize] { - continue; - } - if hs.count(x - ring, y - ring, x + ring + 1, y + ring + 1) > 0 { - pts.push((x, y)); - } - } - } - let stride = (pts.len() / 2000).max(1); - let pts: Vec<(i32, i32)> = pts.into_iter().step_by(stride).collect(); - let eval = |dx: i32, dy: i32, cutoff: f32| -> Option { - let (hx0, hy0, hx1, hy1) = (x0 + dx, y0 + dy, x1 + dx, y1 + dy); - let inside = hx0 >= 0 && hy0 >= 0 && hx1 <= w as i32 && hy1 <= h as i32; - if (dx, dy) == (0, 0) || !inside || hs.count(hx0, hy0, hx1, hy1) != 0 { - return None; - } - let mut e = 0.0f32; - let n = pts.len().max(1) as f32; - let penalty = 1.0 + 1e-3 * ((dx as f32).hypot(dy as f32) / max_radius as f32); - for (i, &(x, y)) in pts.iter().enumerate() { - let (a, b) = ((y as usize * w + x as usize) * ch, ((y + dy) as usize * w + (x + dx) as usize) * ch); - for c in 0..ch { - let d = img[a + c] - img[b + c]; - e += d * d; - } - // SSD terms are nonnegative. The partial score is a lower bound on the - // final score; use the same division and penalty to keep float rounding - // and strict tie ordering unchanged. Check in batches to keep this cheap. - if i % 32 == 31 && cutoff.is_finite() && e / n * penalty >= cutoff { - return None; - } - } - // Mild preference for nearer sources on ties. - Some(e / n * penalty) - }; - // Coarse grid over the search window, then a full-resolution refinement around the winner. - let step = (max_radius / 24).max(1); - let mut best: Option<((i32, i32), f32)> = None; - let consider = |dx: i32, dy: i32, best: &mut Option<((i32, i32), f32)>| { - if let Some(e) = eval(dx, dy, best.map_or(f32::INFINITY, |(_, error)| error)) - && best.is_none_or(|(_, be)| e < be) - { - *best = Some(((dx, dy), e)); - } - }; - let mut dy = -max_radius; - while dy <= max_radius { - let mut dx = -max_radius; - while dx <= max_radius { - consider(dx, dy, &mut best); - dx += step; - } - dy += step; - } - if step > 1 - && let Some(((bx, by), _)) = best - { - for dy in (by - step)..=(by + step) { - for dx in (bx - step)..=(bx + step) { - consider(dx, dy, &mut best); - } - } - } - best.map(|b| b.0) -} - -/// Create texture: fill the hole with blocks of surrounding texture (see module docs). -pub fn synthesize(w: usize, h: usize, ch: usize, img: &[f32], hole: &[bool], block: usize, seed: u64) -> Vec { - let mut out = img.to_vec(); - let Some((bx0, by0, bx1, by1)) = hole_bbox(w, h, hole) else { return out }; - let b = block.max(4) as i32; - let ov = (b / 3).max(1); - let hs = integral(w, h, hole); - // Candidate block origins: whole block (with overlap) inside the grid and outside the hole. - let mut cands = Vec::new(); - for y in ov..(h as i32 - b - ov) { - for x in ov..(w as i32 - b - ov) { - if window_count(&hs, w, h, x - ov, y - ov, x + b + ov, y + b + ov) == 0 { - cands.push((x, y)); - } - } - } - if cands.is_empty() { - return membrane_fill(w, h, ch, img, hole); - } - let mut filled: Vec = hole.iter().map(|x| !x).collect(); - let mut rng = Rng::new(seed); - let mut by = by0 as i32; - while by < by1 as i32 { - let mut bx = bx0 as i32; - while bx < bx1 as i32 { - if window_count(&hs, w, h, bx, by, bx + b, by + b) > 0 { - // Pick the candidate whose block best agrees with already-known pixels around/inside. - let mut best = (cands[0], f32::INFINITY); - for _ in 0..48 { - let c = cands[(rng.next() % cands.len() as u64) as usize]; - let (mut e, mut n) = (0.0f32, 0u32); - for y in (by - ov)..(by + b + ov) { - for x in (bx - ov)..(bx + b + ov) { - if x < 0 || y < 0 || x >= w as i32 || y >= h as i32 || !filled[y as usize * w + x as usize] { - continue; - } - let (a, s) = ((y as usize * w + x as usize) * ch, ((y - by + c.1) as usize * w + (x - bx + c.0) as usize) * ch); - for k in 0..ch { - let d = out[a + k] - img[s + k]; - e += d * d; - } - n += 1; - } - } - let e = if n == 0 { 0.0 } else { e / n as f32 }; - if e < best.1 { - best = (c, e); - } - } - let c = best.0; - let (x0, y0) = ((bx - ov).max(0), (by - ov).max(0)); - let (x1, y1) = ((bx + b + ov).min(w as i32), (by + b + ov).min(h as i32)); - let src = |x: i32, y: i32| ((y - by + c.1) as usize * w + (x - bx + c.0) as usize) * ch; - // Squared difference between what is there and the block, where both exist. - let err = |x: i32, y: i32| { - let i = y as usize * w + x as usize; - if !(hole[i] && filled[i]) { - return 0.0; - } - let (a, s) = (i * ch, src(x, y)); - (0..ch).map(|q| (out[a + q] - img[s + q]).powi(2)).sum::() - }; - // Minimum-error boundary cuts through the overlaps with the blocks to the left and - // above: the block is copied right of and below them, untouched pixels are kept - // on the other side. Copying (rather than averaging) keeps the texture's grain. - let left = min_cut((x0..(bx + ov).min(x1)).len(), (y0..y1).len(), |u, v| err(x0 + u as i32, y0 + v as i32)); - let top = min_cut((y0..(by + ov).min(y1)).len(), (x0..x1).len(), |u, v| err(x0 + v as i32, y0 + u as i32)); - for y in y0..y1 { - for x in x0..x1 { - let i = y as usize * w + x as usize; - if !hole[i] { - continue; - } - let (u, v) = ((x - x0) as usize, (y - y0) as usize); - let keep = filled[i] && (left.get(v).is_some_and(|s| u < *s) || top.get(u).is_some_and(|s| v < *s)); - if !keep { - let (a, s) = (i * ch, src(x, y)); - out[a..a + ch].copy_from_slice(&img[s..s + ch]); - } - filled[i] = true; - } - } - } - bx += b; - } - by += b; - } - out -} - -/// The minimum-error cut through a band `across` wide and `along` long (Efros & Freeman's -/// boundary cut, by dynamic programming): for each step along the band, the offset across it -/// where the cut runs (`err(across, along)` is the cost of a pixel). Pixels before the cut keep -/// what is there. Empty when there is no cost anywhere (nothing to cut through). -fn min_cut(across: usize, along: usize, err: impl Fn(usize, usize) -> f32) -> Vec { - if across == 0 || along == 0 { - return Vec::new(); - } - // Cumulative cost, step by step along the band; the cut may move by one pixel per step. - let mut acc: Vec = (0..along).flat_map(|v| (0..across).map(move |u| (u, v))).map(|(u, v)| err(u, v)).collect(); - if acc.iter().all(|x| *x == 0.0) { - return Vec::new(); - } - for v in 1..along { - for u in 0..across { - let lo = u.saturating_sub(1); - let hi = (u + 1).min(across - 1); - let m = (lo..=hi).map(|k| acc[(v - 1) * across + k]).fold(f32::INFINITY, f32::min); - acc[v * across + u] += m; - } - } - let argmin = |v: usize, lo: usize, hi: usize| (lo..=hi).min_by(|a, b| acc[v * across + a].total_cmp(&acc[v * across + b])).unwrap_or(lo); - let mut cut = vec![0; along]; - let mut u = argmin(along - 1, 0, across - 1); - for v in (0..along).rev() { - if v + 1 < along { - u = argmin(v, u.saturating_sub(1), (u + 1).min(across - 1)); - } - cut[v] = u; - } - cut -} - #[cfg(test)] -mod tests { - use super::*; - - /// The mean is matched first: on a nearly flat bright patch with a noisy deviation ratio the - /// gain stays where the bias can still reach the target's mean. - #[test] - fn fit_matches_the_mean_before_the_contrast() { - let a = Adapt { gain: (0.9, 1.1), bias: 0.04 }; - // Target mean 0.70, source mean 0.70; deviations 0.01 vs 0.004 (ratio 2.5). - let n = 25.0; - let (mt, ms, sdt, sds) = (0.70f32, 0.70f32, 0.01f32, 0.004f32); - let (g, b) = fit(a, n, mt * n, (sdt * sdt + mt * mt) * n, ms * n, (sds * sds + ms * ms) * n); - assert!((g * ms + b - mt).abs() < 1e-5, "mean {} vs {mt} (g {g}, b {b})", g * ms + b); - // Where the mean can't be reached anyway, the limits hold as before. - let (g, b) = fit(a, n, 0.2 * n, 0.04 * n, 0.9 * n, 0.81 * n); - assert!((a.gain.0..=a.gain.1).contains(&g) && b.abs() <= a.bias + 1e-6); - } - - /// A zero-width image has no pixels however tall it is claimed to be: no per-row table. - #[test] - fn zero_width_images_complete_without_sizing_by_height() { - let p = CompleteParams::default(); - assert_eq!(complete(0, 1 << 40, 3, &[], &[], &p), Some(Vec::new())); - assert_eq!(complete(1 << 40, 0, 3, &[], &[], &p), Some(Vec::new())); - } - - /// Smooth gradient plus deterministic fine noise. - fn texture(w: usize, h: usize) -> Vec { - let mut rng = Rng::new(7); - (0..w * h) - .flat_map(|i| { - let (x, y) = ((i % w) as f32, (i / w) as f32); - let n = (rng.next() % 1000) as f32 / 1000.0 * 0.04 - 0.02; - [0.3 + 0.004 * x + n, 0.5 + 0.002 * y + n, 0.4 + n] - }) - .collect() - } - - fn disc(w: usize, h: usize, cx: f32, cy: f32, r: f32) -> Vec { - (0..w * h).map(|i| ((i % w) as f32 - cx).hypot((i / w) as f32 - cy) < r).collect() - } - - fn hole_rmse(a: &[f32], b: &[f32], hole: &[bool], ch: usize) -> f32 { - let (mut e, mut n) = (0.0f32, 0); - for (i, hh) in hole.iter().enumerate() { - if *hh { - for c in 0..ch { - e += (a[i * ch + c] - b[i * ch + c]).powi(2); - n += 1; - } - } - } - (e / n as f32).sqrt() - } - - #[test] - fn completion_fills_blemish_from_texture() { - let (w, h, ch) = (96, 96, 3); - let clean = texture(w, h); - let hole = disc(w, h, 48.0, 48.0, 9.0); - let mut dirty = clean.clone(); - for (i, hh) in hole.iter().enumerate() { - if *hh { - dirty[i * ch..i * ch + ch].copy_from_slice(&[0.02, 0.02, 0.02]); - } - } - let out = complete(w, h, ch, &dirty, &hole, &CompleteParams::default()).unwrap(); - let before = hole_rmse(&dirty, &clean, &hole, ch); - let after = hole_rmse(&out, &clean, &hole, ch); - assert!(after < 0.06 && after < before * 0.15, "rmse before {before} after {after}"); - // Outside the hole untouched. - assert!(out.iter().zip(&dirty).zip(hole.iter().flat_map(|h| [*h; 3])).all(|((a, b), h)| h || a == b)); - // Deterministic. - assert_eq!(out, complete(w, h, ch, &dirty, &hole, &CompleteParams::default()).unwrap()); - } - - #[test] - fn completion_continues_structure() { - // Vertical stripes: the filled hole should keep the stripes (not a blur). - let (w, h, ch) = (80, 80, 1); - let clean: Vec = (0..w * h).map(|i| if (i % w / 4) % 2 == 0 { 0.2 } else { 0.8 }).collect(); - let hole = disc(w, h, 40.0, 40.0, 7.0); - let dirty: Vec = clean.iter().zip(&hole).map(|(c, h)| if *h { 0.5 } else { *c }).collect(); - let out = complete(w, h, ch, &dirty, &hole, &CompleteParams::default()).unwrap(); - let err = hole_rmse(&out, &clean, &hole, ch); - assert!(err < 0.15, "{err}"); - } - - #[test] - fn proximity_finds_matching_offset() { - let (w, h, ch) = (80, 60, 1); - // Periodic pattern with period 10 in x: a match is any multiple-of-10 displacement. - let img: Vec = (0..w * h).map(|i| ((i % w) as f32 * std::f32::consts::TAU / 10.0).sin() * 0.4 + 0.5).collect(); - let hole = disc(w, h, 40.0, 30.0, 5.0); - let (dx, dy) = best_offset(w, h, ch, &img, &hole, 3, 20).unwrap(); - assert_eq!(dx.rem_euclid(10), 0, "dx {dx} dy {dy}"); - assert!((dx, dy) != (0, 0)); - } - - #[test] - fn proximity_search_clamps_hostile_radii_without_overflow_or_hanging() { - let (w, h, ch) = (24, 20, 1); - let img: Vec = (0..w * h).map(|i| (i % w) as f32 / w as f32).collect(); - let hole = disc(w, h, 12.0, 10.0, 2.0); - // User-supplied values used to overflow i32 loops, cast a huge usize - // ring into a negative number, or take billions of search iterations. - let result = best_offset(w, h, ch, &img, &hole, usize::MAX, i32::MAX); - if let Some((dx, dy)) = result { - assert!(dx.abs() <= w as i32 && dy.abs() <= h as i32); - } - assert_eq!(best_offset(w, h, ch, &img, &hole, 2, -1), None); - assert_eq!(best_offset(w, h, ch, &img, &hole, 2, 0), None); - } - - /// Structure, fine noise and flat patches (so that some matches tie exactly), `ch` channels. - fn busy(w: usize, h: usize, ch: usize, seed: u64) -> Vec { - let mut rng = Rng::new(seed); - (0..w * h) - .flat_map(|i| { - let (x, y) = (i % w, i / w); - let flat = (x / 9 + y / 7) % 5 == 0; - let n = (rng.next() % 1000) as f32 / 1000.0; - (0..ch) - .map(move |c| if flat { 0.25 + 0.1 * c as f32 } else { (0.2 + 0.004 * x as f32 + 0.1 * ((x + 2 * y + c) % 6) as f32 + 0.05 * n).min(1.0) }) - }) - .collect() - } - - fn bits(v: &[f32]) -> Vec { - v.iter().map(|x| x.to_bits()).collect() - } - - /// Roles: a hole, a band that is context only, a corner that is no image. - fn roles(w: usize, h: usize, hole: &[bool]) -> Vec { - (0..w * h) - .map(|i| { - let (x, y) = (i % w, i / w); - if hole[i] { - Px::Hole - } else if x < 4 && y < 6 { - Px::Void - } else if (w * 3 / 4..w * 3 / 4 + 3).contains(&x) { - Px::Known - } else { - Px::Source - } - }) - .collect() - } - - #[test] - fn a_hole_is_as_thick_as_it_is_through_not_along() { - let (w, h) = (240, 120); - let all = Bounds { x0: 0, y0: 0, x1: w, y1: h }; - let thickness = |hole: &[bool]| { - let px: Vec = hole.iter().map(|&o| if o { Px::Hole } else { Px::Source }).collect(); - hole_thickness(w, hole_bounds(w, h, &px).unwrap_or(all), &px) - }; - // A band 200 px long and 9 px thick; a disc of radius 20; the band touching the edge - // counts the outside of the image as not hole. - let band: Vec = (0..w * h).map(|i| (20..220).contains(&(i % w)) && (50..59).contains(&(i / w))).collect(); - assert!((9..=11).contains(&thickness(&band)), "{}", thickness(&band)); - assert!((39..=42).contains(&thickness(&disc(w, h, 120.0, 60.0, 20.0)))); - let edge: Vec = (0..w * h).map(|i| i / w < 9).collect(); - assert!((9..=11).contains(&thickness(&edge)), "{}", thickness(&edge)); - } - - /// A long thin hole goes the thin way (a shallow pyramid that starts from a membrane): it is - /// filled, only it changes, and the result does not depend on the thread count either. - #[test] - #[cfg(not(target_arch = "wasm32"))] - fn thin_holes_are_filled_the_same_on_any_number_of_threads() { - let (w, h) = (300, 200); - let img = busy(w, h, 3, 5); - // A wavy line 6 px thick across the image. - let hole: Vec = (0..w * h).map(|i| (((i % w) as f32 * 0.05).sin() * 30.0 + 100.0 - (i / w) as f32).abs() < 3.0).collect(); - let px = roles(w, h, &hole); - let run = |threads: usize| { - let pool = rayon::ThreadPoolBuilder::new().num_threads(threads).build().unwrap(); - pool.install(|| complete_masked(w, h, 3, &img, &px, &CompleteParams::default(), &photocraft_raster::Interrupt::NONE)).unwrap().unwrap() - }; - let one = run(1); - assert_eq!(bits(&one), bits(&run(7))); - assert!((0..w * h).all(|i| hole[i] || (0..3).all(|c| one[i * 3 + c].to_bits() == img[i * 3 + c].to_bits()))); - assert!((0..w * h).filter(|&i| hole[i]).all(|i| (0..3).all(|c| one[i * 3 + c].is_finite()))); - } - - #[test] - #[cfg(not(target_arch = "wasm32"))] - fn results_do_not_depend_on_the_thread_count() { - // Big enough for the parallel passes, and for PatchMatch to sweep in wavefronts where - // there are fewer bands than threads (never with one thread). - let (w, h) = (300, 260); - for (ch, adapt) in [(3, Adapt::NONE), (4, Adapt { gain: (0.9, 1.1), bias: 0.04 })] { - let img = busy(w, h, ch, 3); - let hole = disc(w, h, 140.0, 130.0, 40.0); - let px = roles(w, h, &hole); - let p = CompleteParams { adapt, ..Default::default() }; - let run = |threads: usize| { - let pool = rayon::ThreadPoolBuilder::new().num_threads(threads).build().unwrap(); - bits(&pool.install(|| complete_masked(w, h, ch, &img, &px, &p, &photocraft_raster::Interrupt::NONE)).unwrap().unwrap()) - }; - let one = run(1); - assert_eq!(one, run(3), "{ch} channels, 3 threads"); - assert_eq!(one, run(16), "{ch} channels, 16 threads"); - } - } - - /// The onion peel as first written: every source in order, every known pixel summed. - fn onion_peel_plain(w: usize, h: usize, ch: usize, r: i32, img: &mut [f32], px: &[Px], sources: &[(i32, i32)]) { - let mut known: Vec = px.iter().map(|k| matches!(k, Px::Known | Px::Source)).collect(); - loop { - let front: Vec = (0..w * h) - .filter(|&i| { - let (x, y) = ((i % w) as i32, (i / w) as i32); - !known[i] - && px[i] == Px::Hole - && (-1..=1).any(|dy: i32| { - (-1..=1).any(|dx: i32| { - let (nx, ny) = (x + dx, y + dy); - nx >= 0 && ny >= 0 && (nx as usize) < w && (ny as usize) < h && known[ny as usize * w + nx as usize] - }) - }) - }) - .collect(); - if front.is_empty() { - break; - } - let vals: Vec> = front - .iter() - .map(|&i| { - let (x, y) = ((i % w) as i32, (i / w) as i32); - let mut best = (f32::INFINITY, (0i32, 0i32)); - for &(sx, sy) in sources { - let (mut e, mut n) = (0.0f32, 0usize); - for dy in -r..=r { - for dx in -r..=r { - let (tx, ty) = (x + dx, y + dy); - if tx < 0 || ty < 0 || tx as usize >= w || ty as usize >= h || !known[ty as usize * w + tx as usize] { - continue; - } - let (ti, si) = ((ty as usize * w + tx as usize) * ch, ((sy + dy) as usize * w + (sx + dx) as usize) * ch); - for c in 0..ch { - let d = img[ti + c] - img[si + c]; - e += d * d; - } - n += 1; - } - } - if n > 0 && e / (n as f32) < best.0 { - best = (e / n as f32, (sx, sy)); - } - } - let si = (best.1.1 as usize * w + best.1.0 as usize) * ch; - img[si..si + ch].to_vec() - }) - .collect(); - for (&i, v) in front.iter().zip(vals) { - img[i * ch..(i + 1) * ch].copy_from_slice(&v); - known[i] = true; - } - } - } - - /// #2805's case (upstream's own speed-up of the onion peel, superseded here): repeating - /// texture with many exact ties, two holes; the result must be the plain scan's to the bit. - #[test] - fn onion_peel_picks_exactly_what_the_plain_scan_picks() { - let (w, h, ch, r) = (48, 40, 3, 3); - let mut img = texture(w, h); - for y in 0..h { - for x in 6..w / 2 { - for c in 0..ch { - img[(y * w + x) * ch + c] = img[(y * w + x % 6) * ch + c]; - } - } - } - let none = photocraft_raster::Interrupt::NONE; - for hole in [disc(w, h, 20.0, 18.0, 7.5), disc(w, h, 34.0, 22.0, 5.0)] { - let px: Vec = hole.iter().map(|h| if *h { Px::Hole } else { Px::Source }).collect(); - let near = integral(w, h, &hole); - let sources: Vec<(i32, i32)> = (r..h as i32 - r) - .flat_map(|y| (r..w as i32 - r).map(move |x| (x, y))) - .filter(|&(x, y)| window_count(&near, w, h, x - r, y - r, x + r + 1, y + r + 1) == 0) - .collect(); - let (mut fast, mut plain) = (img.clone(), img.clone()); - onion_peel(w, h, ch, r, &mut fast, &px, hole_bounds(w, h, &px).unwrap(), &sources, &none).unwrap(); - onion_peel_plain(w, h, ch, r, &mut plain, &px, &sources); - assert!(fast.iter().zip(&plain).all(|(a, b)| a.to_bits() == b.to_bits())); - assert_ne!(fast, img); - } - } - - #[test] - fn onion_peel_takes_the_plain_scans_sources() { - let none = photocraft_raster::Interrupt::NONE; - for (w, h, ch, seed) in [(44, 36, 1, 1), (50, 40, 3, 2), (40, 40, 4, 3)] { - let mut img = busy(w, h, ch, seed); - // Also an image of a few exact values, where many sources tie. - if seed == 3 { - img.iter_mut().for_each(|v| *v = (*v * 3.0).round() / 3.0); - } - let hole = disc(w, h, w as f32 * 0.45, h as f32 * 0.5, 7.5); - let px = roles(w, h, &hole); - let valid = valid_sources(w, h, 3, &px, &none).unwrap(); - let sources = Sources::new(&valid, w).all(&valid, w); - let (mut a, mut b) = (img.clone(), img.clone()); - onion_peel(w, h, ch, 3, &mut a, &px, hole_bounds(w, h, &px).unwrap(), &sources, &none).unwrap(); - onion_peel_plain(w, h, ch, 3, &mut b, &px, &sources); - assert_eq!(bits(&a), bits(&b), "{w}×{h}×{ch}"); - } - } - - #[test] - fn least_sum_is_where_the_quotient_crosses() { - let mut rng = Rng::new(5); - for i in 0..4000 { - let n = (1 + rng.next() % 49) as f32; - let v = match i % 4 { - 0 => 0.0, - 1 => (rng.next() % 1000) as f32 * 1e-9, - _ => (rng.next() % 1_000_000) as f32 / 1_000_000.0, - }; - for strict in [true, false] { - let holds = |e: f32| if strict { e / n > v } else { e / n >= v }; - let e = least_sum(v, n, strict); - assert!(holds(e), "{v} {n} {strict}: {e}"); - assert!(e == 0.0 || !holds(e.next_down()), "{v} {n} {strict}: {e} is not the least"); - } - } - assert_eq!(least_sum(f32::INFINITY, 4.0, true), f32::INFINITY); - } - - #[test] - fn valid_sources_are_the_wholly_copyable_patches() { - let (w, h, r) = (37, 29, 2); - let mut rng = Rng::new(9); - let px: Vec = (0..w * h) - .map(|_| match rng.next() % 23 { - 0 => Px::Hole, - 1 => Px::Void, - 2 => Px::Known, - _ => Px::Source, - }) - .collect(); - let valid = valid_sources(w, h, r, &px, &photocraft_raster::Interrupt::NONE).unwrap(); - let source: Vec = px.iter().map(|k| *k == Px::Source).collect(); - let ss = integral(w, h, &source); - let (ri, full) = (r as i32, ((2 * r + 1) * (2 * r + 1)) as u32); - for y in 0..h as i32 { - for x in 0..w as i32 { - let inside = x >= ri && y >= ri && x + ri < w as i32 && y + ri < h as i32; - let want = inside && window_count(&ss, w, h, x - ri, y - ri, x + ri + 1, y + ri + 1) == full; - assert_eq!(valid[y as usize * w + x as usize], want, "({x}, {y})"); - } - } - // Counting per row and block finds the centres in order. - let sources = Sources::new(&valid, w); - let list = sources.all(&valid, w); - assert!(list.len() > 10 && list.len() == sources.len()); - for (k, p) in list.iter().enumerate() { - assert_eq!(sources.nth(k, &valid, w), *p); - } - // And on a grid wider than a block, with empty blocks and rows. - let (w, h) = (300, 9); - let wide: Vec = (0..w * h).map(|i| (i % w) % 7 == 3 && (i % w) / 64 != 2 && i / w != 4).collect(); - let sources = Sources::new(&wide, w); - let list = sources.all(&wide, w); - for (k, p) in list.iter().enumerate() { - assert_eq!(sources.nth(k, &wide, w), *p); - } - } - - #[test] - fn full_patches_measure_as_clipped_ones() { - let (w, h, ch, r) = (46, 38, 4, 3); - let mut img = busy(w, h, ch, 4); - let hole = disc(w, h, 20.0, 18.0, 6.0); - let px = roles(w, h, &hole); - let none = photocraft_raster::Interrupt::NONE; - let hb = hole_bounds(w, h, &px).unwrap(); - let tb = hb.grow(r, w, h); - let valid = valid_sources(w, h, r, &px, &none).unwrap(); - let picks: Vec<(i32, i32)> = Sources::new(&valid, w).all(&valid, w).iter().step_by(37).copied().collect(); - assert!(picks.len() > 5); - for adapt in [Adapt::NONE, Adapt { gain: (0.8, 1.25), bias: 0.08 }] { - for keep in [false, true] { - let targets = targets_around(w, r, &px, hb, tb); - let mut s = Solver { - w, - h, - ch, - r: r as i32, - img: &mut img, - px: &px, - valid: valid.clone(), - targets, - hole_box: hb, - tbox: tb, - full: Vec::new(), - tmom: Vec::new(), - smom: Vec::new(), - adapt, - ctl: none, - }; - s.prepare(keep); - let nnf = vec![picks[0]; tb.area()]; - let mut cost = vec![f32::INFINITY; tb.area()]; - s.costs(&nnf, &mut cost).unwrap(); - let mut checked = 0; - for k in 0..tb.area() { - if !s.targets[k] || !s.full[k] { - continue; - } - let t = ((tb.x0 + k % tb.width()) as i32, (tb.y0 + k / tb.width()) as i32); - for &src in &picks { - if adapt.is_none() { - let exact = s.dist_clipped(t, src, f32::INFINITY); - assert_eq!(s.dist_full(t, src, f32::INFINITY).to_bits(), exact.to_bits()); - for cutoff in [exact * 0.5, exact, exact * 2.0] { - let (a, b) = (s.dist_full(t, src, cutoff), s.dist_clipped(t, src, cutoff)); - assert_eq!(a < cutoff, b < cutoff); - } - } else { - let (mut m1, mut m2) = ([[0.0f32; 5]; 4], [[0.0f32; 5]; 4]); - s.moments_full(k, t, src, &mut m1); - assert_eq!(s.moments(t, src, &mut m2), (2 * r + 1) * (2 * r + 1)); - assert_eq!(m1.map(|c| c.map(f32::to_bits)), m2.map(|c| c.map(f32::to_bits))); - assert_eq!(s.dist_adapted_full(k, t, src).to_bits(), s.dist_adapted(t, src).to_bits()); - } - checked += 1; - } - } - assert!(checked > 100, "{checked}"); - } - } - } - - #[test] - fn owned_completion_fills_in_place_or_gives_the_pixels_back() { - let (w, h, ch) = (64, 52, 3); - let img = busy(w, h, ch, 6); - let hole = disc(w, h, 30.0, 26.0, 8.0); - let px = roles(w, h, &hole); - let (p, none) = (CompleteParams::default(), photocraft_raster::Interrupt::NONE); - let borrowed = complete_masked(w, h, ch, &img, &px, &p, &none).unwrap().unwrap(); - let owned = complete_masked_owned(w, h, ch, img.clone(), &px, &p, &none).unwrap().unwrap(); - assert_eq!(bits(&owned), bits(&borrowed)); - // Nothing may be copied: no completion, and the pixels come back as they were. - let known: Vec = px.iter().map(|k| if *k == Px::Source { Px::Known } else { *k }).collect(); - assert!(complete_masked(w, h, ch, &img, &known, &p, &none).unwrap().is_none()); - let back = complete_masked_owned(w, h, ch, img.clone(), &known, &p, &none).unwrap().unwrap_err(); - assert_eq!(bits(&back), bits(&img)); - // Cancelled, it stops. - let yes = || true; - assert!(complete_masked_owned(w, h, ch, img, &px, &p, &photocraft_raster::Interrupt::cancel_only(&yes)).is_err()); - } - - #[test] - fn synthesis_fills_hole_with_plausible_values() { - let (w, h, ch) = (64, 64, 3); - let clean = texture(w, h); - let hole = disc(w, h, 32.0, 32.0, 6.0); - let out = synthesize(w, h, ch, &clean, &hole, 8, 3); - let err = hole_rmse(&out, &clean, &hole, ch); - assert!(err < 0.15, "{err}"); - assert!(out.iter().all(|v| v.is_finite())); - } -} +mod tests; diff --git a/crates/algo/src/inpaint/common.rs b/crates/algo/src/inpaint/common.rs new file mode 100644 index 0000000000..bbbcc8df26 --- /dev/null +++ b/crates/algo/src/inpaint/common.rs @@ -0,0 +1,119 @@ +use super::*; + +/// Below this many cells a pass runs on the calling thread (thread hand-off costs more than it +/// saves). Every pass gives the same result either way. +pub(super) const PAR_MIN: usize = 64 * 64; + +/// [`PAR_MIN`] for the passes that match or vote a patch per cell. +pub(super) const PAR_MIN_PATCHES: usize = 16 * 16; + +/// Largest level (in cells) whose source patches' moments [`Solver::prepare`] keeps. +pub(super) const SOURCE_MOMENTS_MAX: usize = 1 << 20; + +/// SplitMix64: tiny deterministic RNG. +#[derive(Clone)] +pub(crate) struct Rng(pub(crate) u64); + +impl Rng { + /// A generator whose sequence is fixed by `seed`. + pub(crate) fn new(seed: u64) -> Self { + Rng(seed ^ 0x9E37_79B9_7F4A_7C15) + } + /// The next value of the SplitMix64 sequence. + pub(crate) fn next(&mut self) -> u64 { + crate::photo_util::splitmix64(&mut self.0) + } + /// Skip `n` numbers (the same state as after `n` calls of [`Rng::next`]). + pub(crate) fn skip(&mut self, n: u64) { + self.0 = self.0.wrapping_add(n.wrapping_mul(0x9E37_79B9_7F4A_7C15)); + } + /// Uniform integer in `lo..=hi`. + pub(crate) fn range(&mut self, lo: i32, hi: i32) -> i32 { + if hi <= lo { + return lo; + } + lo + (self.next() % (hi - lo + 1) as u64) as i32 + } +} + +/// How far a copied patch may be adjusted to its target, per channel: `gain · source + bias`, the +/// gain within `gain` and the bias within `±bias` (Image Melding's photometric transform). The +/// gain is the ratio of the patches' standard deviations, the bias what then matches their means. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Adapt { + pub gain: (f32, f32), + pub bias: f32, +} + +impl Adapt { + /// Copies are taken as they are. + pub const NONE: Adapt = Adapt { gain: (1.0, 1.0), bias: 0.0 }; + + pub fn is_none(&self) -> bool { + self.gain == (1.0, 1.0) && self.bias == 0.0 + } +} + +impl Default for Adapt { + fn default() -> Self { + Self::NONE + } +} + +/// What a pixel is to [`complete_masked`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Px { + /// Not part of the image (a gap, or outside a transformed copy): ignored. + Void, + /// Known, part of the context the fill must agree with, but not copied from. + Known, + /// Known and may be copied from. + Source, + /// To be filled. + Hole, +} + +/// One pyramid level. Level 0 borrows the caller's buffers until it is solved. +pub(super) struct Level<'a> { + pub(super) w: usize, + pub(super) h: usize, + pub(super) img: Cow<'a, [f32]>, + pub(super) px: Cow<'a, [Px]>, +} + +impl Level<'_> { + pub(super) const EMPTY: Level<'static> = Level { w: 0, h: 0, img: Cow::Borrowed(&[]), px: Cow::Borrowed(&[]) }; +} + +/// The half-open box `[x0, x1) × [y0, y1)` of a level's grid. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct Bounds { + pub(super) x0: usize, + pub(super) y0: usize, + pub(super) x1: usize, + pub(super) y1: usize, +} + +impl Bounds { + /// Grown by `r` on every side, within a `w × h` grid. + pub(super) fn grow(self, r: usize, w: usize, h: usize) -> Bounds { + Bounds { x0: self.x0.saturating_sub(r), y0: self.y0.saturating_sub(r), x1: self.x1.saturating_add(r).min(w), y1: self.y1.saturating_add(r).min(h) } + } + + /// The same box on the next coarser level (whose cells are 2 × 2 of these). + pub(super) fn half(self) -> Bounds { + Bounds { x0: self.x0 / 2, y0: self.y0 / 2, x1: self.x1.div_ceil(2), y1: self.y1.div_ceil(2) } + } + + pub(super) fn width(&self) -> usize { + self.x1.saturating_sub(self.x0) + } + + pub(super) fn height(&self) -> usize { + self.y1.saturating_sub(self.y0) + } + + pub(super) fn area(&self) -> usize { + self.width() * self.height() + } +} diff --git a/crates/algo/src/inpaint/solver.rs b/crates/algo/src/inpaint/solver.rs new file mode 100644 index 0000000000..b5cc82915d --- /dev/null +++ b/crates/algo/src/inpaint/solver.rs @@ -0,0 +1,866 @@ +use super::common::{Adapt, Bounds, PAR_MIN_PATCHES, Px, Rng}; +use super::*; + +/// Most channels whose moments the colour adaptation fits (the rest are copied as they are). +const MOM_CH: usize = 8; + +/// Per-level PatchMatch/EM state. +pub(super) struct Solver<'a> { + pub(super) w: usize, + pub(super) h: usize, + pub(super) ch: usize, + pub(super) r: i32, + pub(super) img: &'a mut Vec, + pub(super) px: &'a [Px], + /// Valid source centres: the whole patch is inside the grid and may be copied from. + pub(super) valid: Vec, + /// The hole's bounds and the targets' (the hole's grown by the patch radius): nothing outside + /// them changes or is matched. The match field, its costs and these per-target tables are + /// kept over `tbox`, row-major. + pub(super) hole_box: Bounds, + pub(super) tbox: Bounds, + /// Target centres (the patch overlaps the hole). + pub(super) targets: Vec, + /// Per cell of `tbox`: the whole patch is inside the grid and not void (so its distances + /// need no bounds checks and its own moments can be kept). + pub(super) full: Vec, + /// With colour adaptation, per cell of `tbox` and channel (at most [`MOM_CH`]): `Σt, Σt²` of + /// the patch, for full patches, as of the last [`Solver::costs`]. + pub(super) tmom: Vec<[f32; 2]>, + /// With colour adaptation where it pays: per source centre and channel, `Σs, Σs²` of its + /// patch (source pixels never change within a level). Empty otherwise. + pub(super) smom: Vec<[f32; 2]>, + pub(super) adapt: Adapt, + /// Cancellation: checked per row band; a cancelled solve's output is discarded. + pub(super) ctl: photocraft_raster::Interrupt<'a>, +} + +/// A channel deviation under which a patch counts as flat for [`fit`] (about 5 levels of 255). +const FLAT: f32 = 0.02; + +/// Gain and bias of one channel for target moments `(Σt, Σt²)` and source moments `(Σs, Σs²)` +/// over `n` samples, within the limits. +#[inline] +pub(crate) fn fit(a: Adapt, n: f32, st: f32, stt: f32, ss: f32, sss: f32) -> (f32, f32) { + let (mt, ms) = (st / n, ss / n); + let vt = (stt / n - mt * mt).max(0.0); + let vs = (sss / n - ms * ms).max(0.0); + let g = if vs > 1e-10 { (vt / vs).sqrt() } else { 1.0 }; + let (mut lo, mut hi) = a.gain; + // Nearly flat patches of about the same colour (their means within the bias of each other): + // the ratio of their deviations is noise, so match the mean first, keeping the gain where the + // bias can still bring the source's mean to the target's. Gained about zero, a gain at its + // limit moved bright means further than the bias could bring back, and each channel by a + // different amount: a tinted blotch in a smooth gradient. Textured patches, and flat ones + // whose colours differ more (Content-Aware Move's Color), are fitted as before. + if vt.max(vs) < FLAT * FLAT && (mt - ms).abs() <= a.bias && ms > 1e-6 { + let (glo, ghi) = ((mt - a.bias) / ms, (mt + a.bias) / ms); + if glo.max(lo) <= ghi.min(hi) { + (lo, hi) = (glo.max(lo), ghi.min(hi)); + } + } + let g = g.clamp(lo, hi); + let b = (mt - g * ms).clamp(-a.bias, a.bias); + (g, b) +} + +impl Solver<'_> { + #[inline] + pub(super) fn is_valid(&self, x: i32, y: i32) -> bool { + x >= 0 && y >= 0 && (x as usize) < self.w && (y as usize) < self.h && self.valid[y as usize * self.w + x as usize] + } + + /// Mark the full target patches (`full`), and keep the source moments where they pay off. + pub(super) fn prepare(&mut self, keep_source_moments: bool) { + let (w, h, r, tb) = (self.w, self.h, self.r as usize, self.tbox); + let side = 2 * r + 1; + let mut full = vec![false; tb.area()]; + let px = self.px; + par::chunks_mut(&mut full, tb.width(), tb.area() >= PAR_MIN_PATCHES, |ty, out| { + let y = tb.y0 + ty; + if y < r || y + r >= h { + return; + } + for (tx, f) in out.iter_mut().enumerate() { + let x = tb.x0 + tx; + if x < r || x + r >= w { + continue; + } + *f = (y - r..=y + r).all(|yy| px[yy * w + x - r..yy * w + x - r + side].iter().all(|k| *k != Px::Void)); + } + }); + self.full = full; + if self.adapt.is_none() { + return; + } + let c8 = self.ch.min(MOM_CH); + self.tmom = vec![[0.0; 2]; tb.area() * c8]; + if !keep_source_moments { + return; + } + let (ch, img, valid, ctl) = (self.ch, &*self.img, &self.valid, &self.ctl); + let mut smom = vec![[0.0f32; 2]; w * h * c8]; + par::chunks_mut(&mut smom, w * c8, w * h >= PAR_MIN_PATCHES, |y, out| { + if ctl.cancelled() { + return; + } + for x in 0..w { + if valid[y * w + x] { + patch_moments(img, w, ch, c8, side, x - r, y - r, &mut out[x * c8..(x + 1) * c8]); + } + } + }); + self.smom = smom; + } + + /// Distance between the target patch at `t` (its pixels inside the grid and not void; `k` its + /// index in the `tbox` tables) and the source patch at `s`, per sample; with colour adaptation + /// the source is fitted first. + #[inline] + fn dist(&self, t: (i32, i32), k: usize, s: (i32, i32), cutoff: f32) -> f32 { + let full = self.full[k]; + if !self.adapt.is_none() { + return if full { self.dist_adapted_full(k, t, s) } else { self.dist_adapted(t, s) }; + } + if full { self.dist_full(t, s, cutoff) } else { self.dist_clipped(t, s, cutoff) } + } + + /// [`Solver::dist`] without adaptation, of a patch that may be clipped. + pub(super) fn dist_clipped(&self, t: (i32, i32), s: (i32, i32), cutoff: f32) -> f32 { + let (w, h, ch, r) = (self.w as i32, self.h as i32, self.ch, self.r); + let full = ((2 * r + 1) * (2 * r + 1)) as f32 * ch as f32; + let mut sum = 0.0f32; + let mut n = 0usize; + for dy in -r..=r { + let ty = t.1 + dy; + if ty < 0 || ty >= h { + continue; + } + let sy = s.1 + dy; + for dx in -r..=r { + let tx = t.0 + dx; + if tx < 0 || tx >= w || self.px[ty as usize * self.w + tx as usize] == Px::Void { + continue; + } + let ti = (ty as usize * self.w + tx as usize) * ch; + let si = (sy as usize * self.w + (s.0 + dx) as usize) * ch; + for c in 0..ch { + let d = self.img[ti + c] - self.img[si + c]; + sum += d * d; + } + n += ch; + } + // Early out: the mean can only be ≥ sum / (full patch size). + if sum > cutoff * full { + return f32::INFINITY; + } + } + if n == 0 { f32::INFINITY } else { sum / n as f32 } + } + + /// [`Solver::dist_clipped`] of a full patch: the same sums, in the same order. It gives up + /// (infinity) as soon as the sum shows the patch is worse than `cutoff`, which the sum, only + /// growing, can show after any pixel: the caller only asks whether it is better. + pub(super) fn dist_full(&self, t: (i32, i32), s: (i32, i32), cutoff: f32) -> f32 { + let (w, ch, r) = (self.w, self.ch, self.r); + let side = (2 * r + 1) as usize; + let full = ((2 * r + 1) * (2 * r + 1)) as f32 * ch as f32; + let (span, limit) = (side * ch, cutoff * full); + let mut sum = 0.0f32; + for dy in -r..=r { + let ti = ((t.1 + dy) as usize * w + (t.0 - r) as usize) * ch; + let si = ((s.1 + dy) as usize * w + (s.0 - r) as usize) * ch; + for (tp, sp) in self.img[ti..ti + span].chunks_exact(ch).zip(self.img[si..si + span].chunks_exact(ch)) { + for (a, b) in tp.iter().zip(sp) { + let d = a - b; + sum += d * d; + } + if sum > limit { + return f32::INFINITY; + } + } + } + sum / (side * side * ch) as f32 + } + + /// Moments of the target patch at `t` and the source patch at `s` per channel: + /// `[Σt, Σt², Σs, Σs², Σts]`, and the sample count. + pub(super) fn moments(&self, t: (i32, i32), s: (i32, i32), m: &mut [[f32; 5]]) -> usize { + let (w, h, ch, r) = (self.w as i32, self.h as i32, self.ch, self.r); + m.iter_mut().for_each(|v| *v = [0.0; 5]); + let mut n = 0usize; + for dy in -r..=r { + let ty = t.1 + dy; + if ty < 0 || ty >= h { + continue; + } + let sy = s.1 + dy; + for dx in -r..=r { + let tx = t.0 + dx; + if tx < 0 || tx >= w || self.px[ty as usize * self.w + tx as usize] == Px::Void { + continue; + } + let ti = (ty as usize * self.w + tx as usize) * ch; + let si = (sy as usize * self.w + (s.0 + dx) as usize) * ch; + for (c, mc) in m.iter_mut().enumerate().take(ch) { + let (a, b) = (self.img[ti + c], self.img[si + c]); + mc[0] += a; + mc[1] += a * a; + mc[2] += b; + mc[3] += b * b; + mc[4] += a * b; + } + n += 1; + } + } + n + } + + /// [`Solver::moments`] of a full target patch (`k` in the `tbox` tables): the target's own + /// sums kept from [`Solver::costs`], the source's from [`Solver::prepare`] when kept, each + /// summed in the same order as there. + pub(super) fn moments_full(&self, k: usize, t: (i32, i32), s: (i32, i32), m: &mut [[f32; 5]]) { + let (w, ch, r) = (self.w, self.ch, self.r); + let c8 = m.len(); + let side = (2 * r + 1) as usize; + let tm = &self.tmom[k * c8..(k + 1) * c8]; + let sm = self.smom.get((s.1 as usize * w + s.0 as usize) * c8..(s.1 as usize * w + s.0 as usize + 1) * c8); + let mut acc = [[0.0f32; 3]; MOM_CH]; + for dy in -r..=r { + let ti = ((t.1 + dy) as usize * w + (t.0 - r) as usize) * ch; + let si = ((s.1 + dy) as usize * w + (s.0 - r) as usize) * ch; + let (trow, srow) = (&self.img[ti..ti + side * ch], &self.img[si..si + side * ch]); + if sm.is_some() { + for (tp, sp) in trow.chunks_exact(ch).zip(srow.chunks_exact(ch)) { + for c in 0..c8 { + acc[c][2] += tp[c] * sp[c]; + } + } + } else { + for (tp, sp) in trow.chunks_exact(ch).zip(srow.chunks_exact(ch)) { + for c in 0..c8 { + let (a, b) = (tp[c], sp[c]); + acc[c][0] += b; + acc[c][1] += b * b; + acc[c][2] += a * b; + } + } + } + } + for (c, mc) in m.iter_mut().enumerate() { + let [ss, sss] = match sm { + Some(sm) => sm[c], + None => [acc[c][0], acc[c][1]], + }; + *mc = [tm[c][0], tm[c][1], ss, sss, acc[c][2]]; + } + } + + pub(super) fn dist_adapted(&self, t: (i32, i32), s: (i32, i32)) -> f32 { + let mut m = [[0.0f32; 5]; MOM_CH]; + let ch = self.ch.min(MOM_CH); + let n = self.moments(t, s, &mut m[..ch]); + if n == 0 { + return f32::INFINITY; + } + adapted_cost(self.adapt, n as f32, &m[..ch]) + } + + pub(super) fn dist_adapted_full(&self, k: usize, t: (i32, i32), s: (i32, i32)) -> f32 { + let mut m = [[0.0f32; 5]; MOM_CH]; + let ch = self.ch.min(MOM_CH); + self.moments_full(k, t, s, &mut m[..ch]); + let side = (2 * self.r + 1) as usize; + adapted_cost(self.adapt, (side * side) as f32, &m[..ch]) + } + + /// Gain and bias per channel for the match `t → s` (identity without adaptation). + fn transform(&self, t: (i32, i32), k: usize, s: (i32, i32), out: &mut [(f32, f32)]) { + if self.adapt.is_none() { + out.iter_mut().for_each(|v| *v = (1.0, 0.0)); + return; + } + let mut m = [[0.0f32; 5]; MOM_CH]; + let ch = self.ch.min(MOM_CH); + let n = if self.full[k] { + self.moments_full(k, t, s, &mut m[..ch]); + let side = (2 * self.r + 1) as usize; + side * side + } else { + self.moments(t, s, &mut m[..ch]) + }; + for (c, o) in out.iter_mut().enumerate() { + *o = if n == 0 || c >= ch { (1.0, 0.0) } else { fit(self.adapt, n as f32, m[c][0], m[c][1], m[c][2], m[c][3]) }; + } + } + + /// One PatchMatch step at target `t` (`k` in the target box) whose match is `cur`: propagation + /// from the matches of the neighbours visited just before it (`left` in its row, `up` in its + /// column, in this pass's direction `step`), then random search in exponentially shrinking + /// windows around the best (two numbers from `rng` per window). + #[allow(clippy::too_many_arguments)] + #[inline] + fn pm_step( + &self, + t: (i32, i32), + k: usize, + cur: ((i32, i32), f32), + left: Option<(i32, i32)>, + up: Option<(i32, i32)>, + step: i32, + rng: &mut Rng, + search_radius: i32, + ) -> ((i32, i32), f32) { + let (mut best, mut bc) = cur; + if let Some(c) = left { + let cand = (c.0 + step, c.1); + if self.is_valid(cand.0, cand.1) && cand != best { + let d = self.dist(t, k, cand, bc); + if d < bc { + (best, bc) = (cand, d); + } + } + } + if let Some(c) = up { + let cand = (c.0, c.1 + step); + if self.is_valid(cand.0, cand.1) && cand != best { + let d = self.dist(t, k, cand, bc); + if d < bc { + (best, bc) = (cand, d); + } + } + } + let mut rad = search_radius; + while rad >= 1 { + let cand = (best.0 + rng.range(-rad, rad), best.1 + rng.range(-rad, rad)); + if self.is_valid(cand.0, cand.1) && cand != best { + let d = self.dist(t, k, cand, bc); + if d < bc { + (best, bc) = (cand, d); + } + } + rad /= 2; + } + (best, bc) + } + + /// One PatchMatch pass over all target rows, in bands of the grid's rows: each band is + /// visited in raster order (backwards on odd passes), propagating within itself, its random + /// numbers seeded by its index. `nnf` and `cost` are over the target box. The bands run in + /// parallel; when there are fewer of them than threads, each is also swept in wavefronts of + /// blocks (a cell depends only on its neighbours before it in its row and its column), which + /// visits every cell with the same neighbours and random numbers as the raster order. + pub(super) fn patchmatch(&self, nnf: &mut [(i32, i32)], cost: &mut [f32], pass: usize, seed: u64, search_radius: i32) { + const BAND: usize = 16; + let tb = self.tbox; + let tw = tb.width(); + if tw == 0 || tb.height() == 0 || nnf.len() < tb.area() || cost.len() < tb.area() { + return; + } + let reverse = pass % 2 == 1; + let step: i32 = if reverse { -1 } else { 1 }; + let band_seed = |bi: usize| seed ^ (bi as u64).wrapping_mul(0x2545_F491_4F6C_DD1D) ^ ((pass as u64) << 40); + // The bands crossing the target box: index, first row, rows in the box. + let mut bands = Vec::new(); + let mut y = tb.y0; + while y < tb.y1 { + let bi = y / BAND; + let end = ((bi + 1) * BAND).min(tb.y1); + bands.push((bi, y, end - y)); + y = end; + } + let threads = par::threads(); + if tb.area() >= PAR_MIN_PATCHES * 8 && !bands.is_empty() && bands.len() < threads { + self.patchmatch_wavefront(nnf, cost, &bands, reverse, &band_seed, search_radius); + return; + } + let band_fn = |bi: usize, ys: usize, nn: &mut [(i32, i32)], co: &mut [f32]| { + if self.ctl.cancelled() { + return; + } + let rows = nn.len() / tw; + let mut rng = Rng::new(band_seed(bi)); + for ry in 0..rows { + if self.ctl.cancelled() { + return; + } + let ly = if reverse { rows - 1 - ry } else { ry }; + let y = ys + ly; + for rx in 0..tw { + let lx = if reverse { tw - 1 - rx } else { rx }; + let li = ly * tw + lx; + let k = (y - tb.y0) * tw + lx; + if !self.targets[k] { + continue; + } + // Neighbours outside the target box hold no match: nothing to try. + let nx = lx as i32 - step; + let left = (nx >= 0 && (nx as usize) < tw).then(|| nn[ly * tw + nx as usize]); + let nly = ly as i32 - step; + let up = (nly >= 0 && (nly as usize) < rows).then(|| nn[nly as usize * tw + lx]); + let t = ((tb.x0 + lx) as i32, y as i32); + (nn[li], co[li]) = self.pm_step(t, k, (nn[li], co[li]), left, up, step, &mut rng, search_radius); + } + } + }; + // The target box's rows, band by band. + let mut parts = Vec::with_capacity(bands.len()); + let (mut nn_rest, mut co_rest) = (&mut nnf[..tb.area()], &mut cost[..tb.area()]); + for &(bi, ys, rows) in &bands { + let (nn, nr) = std::mem::take(&mut nn_rest).split_at_mut(rows * tw); + let (co, cr) = std::mem::take(&mut co_rest).split_at_mut(rows * tw); + parts.push((bi, ys, nn, co)); + (nn_rest, co_rest) = (nr, cr); + } + let par = tb.area() >= PAR_MIN_PATCHES && parts.len() > 1; + par::each(parts, par, |(bi, ys, nn, co)| band_fn(bi, ys, nn, co)); + } + + /// [`Solver::patchmatch`] swept in wavefronts: the cells of each band in blocks of a row, a + /// block once the block before it in its row and the one above it (in the pass's direction) + /// are done. A target's random numbers are those it would draw in raster order (each target + /// draws the same count). + fn patchmatch_wavefront( + &self, + nnf: &mut [(i32, i32)], + cost: &mut [f32], + bands: &[(usize, usize, usize)], + reverse: bool, + band_seed: &(dyn Fn(usize) -> u64 + Sync), + search_radius: i32, + ) { + use std::sync::atomic::{AtomicU32, AtomicU64, Ordering::Relaxed}; + + let tb = self.tbox; + let tw = tb.width(); + let step: i32 = if reverse { -1 } else { 1 }; + let pack = |(x, y): (i32, i32)| (u64::from(x as u32) << 32) | u64::from(y as u32); + let unpack = |v: u64| ((v >> 32) as u32 as i32, v as u32 as i32); + // Random numbers each target draws. + let mut draws = 0u64; + let mut rad = search_radius; + while rad >= 1 { + draws += 2; + rad /= 2; + } + // Targets before each column of each row of the box. + let mut before = vec![0u32; tb.height() * (tw + 1)]; + for (ry, row) in before.chunks_mut(tw + 1).enumerate() { + for lx in 0..tw { + row[lx + 1] = row[lx] + u32::from(self.targets[ry * tw + lx]); + } + } + // Targets visited before each of a band's rows (in the pass's order). + let row_base: Vec> = bands + .iter() + .map(|&(_, ys, rows)| { + let mut base = Vec::with_capacity(rows); + let mut n = 0u64; + for pr in 0..rows { + base.push(n); + let ly = if reverse { rows - 1 - pr } else { pr }; + n += u64::from(before[(ys + ly - tb.y0) * (tw + 1) + tw]); + } + base + }) + .collect(); + let block = (tw / 8).clamp(4, 32); + let blocks = tw.div_ceil(block); + let nn: Vec = nnf[..tb.area()].iter().map(|m| AtomicU64::new(pack(*m))).collect(); + let co: Vec = cost[..tb.area()].iter().map(|c| AtomicU32::new(c.to_bits())).collect(); + let sweep = |(j, pr, b): (usize, usize, usize)| { + let (bi, ys, rows) = bands[j]; + let ly = if reverse { rows - 1 - pr } else { pr }; + let y = ys + ly; + let ry = y - tb.y0; + let (pc0, pc1) = (b * block, ((b + 1) * block).min(tw)); + // The targets visited before this block, in raster order. + let first = if reverse { tw - 1 - pc0 } else { pc0 }; + let row = &before[ry * (tw + 1)..(ry + 1) * (tw + 1)]; + let in_row = if reverse { row[tw] - row[first + 1] } else { row[first] }; + let mut rng = Rng::new(band_seed(bi)); + rng.skip((row_base[j][pr] + u64::from(in_row)) * draws); + for pc in pc0..pc1 { + let lx = if reverse { tw - 1 - pc } else { pc }; + let k = ry * tw + lx; + if !self.targets[k] { + continue; + } + let nx = lx as i32 - step; + let left = (nx >= 0 && (nx as usize) < tw).then(|| unpack(nn[ry * tw + nx as usize].load(Relaxed))); + let nly = ly as i32 - step; + let up = (nly >= 0 && (nly as usize) < rows).then(|| unpack(nn[(ys + nly as usize - tb.y0) * tw + lx].load(Relaxed))); + let cur = (unpack(nn[k].load(Relaxed)), f32::from_bits(co[k].load(Relaxed))); + let t = ((tb.x0 + lx) as i32, y as i32); + let (m, c) = self.pm_step(t, k, cur, left, up, step, &mut rng, search_radius); + nn[k].store(pack(m), Relaxed); + co[k].store(c.to_bits(), Relaxed); + } + }; + // Wavefront `d`: block `b` of (visited) row `pr` with `pr + b = d`, in every band. Each + // wave ends before the next starts. + let longest = bands.iter().map(|b| b.2).max().unwrap_or(0); + for d in 0..longest + blocks - 1 { + if self.ctl.cancelled() { + return; + } + let wave: Vec<(usize, usize, usize)> = bands + .iter() + .enumerate() + .flat_map(|(j, &(_, _, rows))| (0..rows).filter(move |&pr| pr <= d && d - pr < blocks).map(move |pr| (j, pr, d - pr))) + .collect(); + par::each(wave, true, sweep); + } + for (m, a) in nnf.iter_mut().zip(&nn) { + *m = unpack(a.load(Relaxed)); + } + for (c, a) in cost.iter_mut().zip(&co) { + *c = f32::from_bits(a.load(Relaxed)); + } + } + + /// Recompute every target's match cost (hole pixels change between iterations), and with + /// colour adaptation the full target patches' own moments. + pub(super) fn costs(&mut self, nnf: &[(i32, i32)], cost: &mut [f32]) -> Result<(), photocraft_raster::Cancelled> { + let (w, ch, r, tb) = (self.w, self.ch, self.r as usize, self.tbox); + let par = tb.area() >= PAR_MIN_PATCHES; + self.ctl.check()?; + if !self.adapt.is_none() { + let c8 = ch.min(MOM_CH); + let side = 2 * r + 1; + let mut tmom = std::mem::take(&mut self.tmom); + let (img, full, ctl) = (&*self.img, &self.full, &self.ctl); + par::chunks_mut(&mut tmom, tb.width() * c8, par, |ty, out| { + if ctl.cancelled() { + return; + } + for tx in 0..tb.width() { + if full[ty * tb.width() + tx] { + patch_moments(img, w, ch, c8, side, tb.x0 + tx - r, tb.y0 + ty - r, &mut out[tx * c8..(tx + 1) * c8]); + } + } + }); + self.tmom = tmom; + } + let this = &*self; + par::chunks_mut(cost, tb.width(), par, |ty, co| { + if this.ctl.cancelled() { + return; + } + let y = tb.y0 + ty; + for (tx, c) in co.iter_mut().enumerate() { + let k = ty * tb.width() + tx; + if this.targets[k] { + *c = this.dist(((tb.x0 + tx) as i32, y as i32), k, nnf[k], f32::INFINITY); + } + } + }); + self.ctl.check() + } + + /// Re-estimate hole pixels by a similarity-weighted vote of all overlapping patch matches + /// (each copy adjusted by its gain and bias). + pub(super) fn vote(&mut self, nnf: &[(i32, i32)], cost: &[f32]) { + let (w, h, ch, r) = (self.w, self.h, self.ch, self.r); + let (tb, hb) = (self.tbox, self.hole_box); + // A cancelled solve is thrown away. + if self.ctl.cancelled() { + return; + } + let used = |k: usize| self.targets[k] && cost[k].is_finite(); + // σ² from the 75th percentile of match costs (Wexler et al. use a robust scale like this). + let cs: Vec = (0..tb.area()).filter(|&k| used(k)).map(|k| cost[k]).collect(); + let mut cs = cs; + let sigma2 = if cs.is_empty() { + 1.0 + } else { + let k = (cs.len() * 3 / 4).min(cs.len() - 1); + let (_, v, _) = cs.select_nth_unstable_by(k, |a, b| a.total_cmp(b)); + v.max(1e-6) + }; + drop(cs); + // Each target's weight and photometric transform (computed once, used by every pixel it + // covers). + let adapted = !self.adapt.is_none(); + let par = tb.area() >= PAR_MIN_PATCHES; + // A weight (zero for a target that doesn't vote) and its match's centre (as a pixel + // index) per target. + let mut wt = vec![0.0f32; tb.area()]; + let mut src = vec![0isize; tb.area()]; + par::chunks2_mut(&mut wt, tb.width(), &mut src, tb.width(), par, |ty, wrow, srow| { + for (tx, (o, sc)) in wrow.iter_mut().zip(srow.iter_mut()).enumerate() { + let k = ty * tb.width() + tx; + if used(k) { + *o = (-cost[k] / (2.0 * sigma2)).exp().max(1e-8); + *sc = nnf[k].1 as isize * w as isize + nnf[k].0 as isize; + } + } + }); + let mut gb: Vec<(f32, f32)> = Vec::new(); + if adapted { + gb = vec![(1.0f32, 0.0f32); tb.area() * ch]; + let this = &*self; + par::chunks_mut(&mut gb, tb.width() * ch, par, |ty, out| { + if this.ctl.cancelled() { + return; + } + let y = tb.y0 + ty; + for tx in 0..tb.width() { + let k = ty * tb.width() + tx; + if used(k) { + this.transform(((tb.x0 + tx) as i32, y as i32), k, nnf[k], &mut out[tx * ch..(tx + 1) * ch]); + } + } + }); + } + // The vote, into a buffer over the hole's bounds (every pixel reads the old pixels). + let votes = Votes { w, h, ch, r: r as usize, tbox: tb, img: &*self.img, wt: &wt, src: &src, gb: &gb }; + let (px, ctl) = (self.px, &self.ctl); + let mut out = vec![0.0f32; hb.area() * ch]; + let mut got = vec![false; hb.area()]; + let row = |yy: usize, orow: &mut [f32], grow: &mut [bool]| { + if ctl.cancelled() { + return; + } + let y = hb.y0 + yy; + for x in hb.x0..hb.x1 { + if px[y * w + x] != Px::Hole { + continue; + } + let o = (x - hb.x0) * ch; + let dst = &mut orow[o..o + ch]; + grow[x - hb.x0] = match (ch, adapted) { + (1, false) => votes.pixel::<1, false>(x, y, dst), + (3, false) => votes.pixel::<3, false>(x, y, dst), + (4, false) => votes.pixel::<4, false>(x, y, dst), + (1, true) => votes.pixel::<1, true>(x, y, dst), + (3, true) => votes.pixel::<3, true>(x, y, dst), + (4, true) => votes.pixel::<4, true>(x, y, dst), + _ => votes.pixel_any(x, y, adapted, dst), + }; + } + }; + par::chunks2_mut(&mut out, hb.width() * ch, &mut got, hb.width(), hb.area() >= PAR_MIN_PATCHES, row); + for yy in 0..hb.height() { + for xx in 0..hb.width() { + if got[yy * hb.width() + xx] { + let (d, s) = (((hb.y0 + yy) * w + hb.x0 + xx) * ch, (yy * hb.width() + xx) * ch); + self.img[d..d + ch].copy_from_slice(&out[s..s + ch]); + } + } + } + } +} + +/// What [`Solver::vote`] votes with: per target (over the target box) its weight (zero when it +/// doesn't vote), its match's centre as a pixel index, and with colour adaptation its gain and +/// bias per channel. +struct Votes<'a> { + w: usize, + h: usize, + ch: usize, + r: usize, + tbox: Bounds, + img: &'a [f32], + wt: &'a [f32], + src: &'a [isize], + gb: &'a [(f32, f32)], +} + +impl Votes<'_> { + /// Hole pixel `(x, y)`'s vote into `out` (`CH` channels): the weighted mean of what the + /// matches of the patches covering it put there, summed patch by patch in raster order of + /// their centres. False when no patch votes. + #[inline(always)] + fn pixel(&self, x: usize, y: usize, out: &mut [f32]) -> bool { + let (w, r, tb) = (self.w, self.r, self.tbox); + let mut acc = [0.0f32; CH]; + let mut wsum = 0.0f32; + for ty in y.saturating_sub(r)..=(y + r).min(self.h - 1) { + let dy = ty as isize - y as isize; + let krow = (ty - tb.y0) * tb.width(); + for tx in x.saturating_sub(r)..=(x + r).min(w - 1) { + let k = krow + tx - tb.x0; + let wt = self.wt[k]; + if wt == 0.0 { + continue; + } + // The pixel of the match's patch that lands here. + let si = (self.src[k] - dy * w as isize - (tx as isize - x as isize)) as usize * CH; + let s = &self.img[si..si + CH]; + for c in 0..CH { + let v = if ADAPT { + let (g, b) = self.gb[k * CH + c]; + g * s[c] + b + } else { + s[c] + }; + acc[c] += v * wt; + } + wsum += wt; + } + } + if wsum > 0.0 { + for (d, a) in out.iter_mut().zip(&acc) { + *d = a / wsum; + } + return true; + } + false + } + + /// [`Votes::pixel`] for any number of channels. + fn pixel_any(&self, x: usize, y: usize, adapted: bool, out: &mut [f32]) -> bool { + let (w, r, tb, ch) = (self.w, self.r, self.tbox, self.ch); + let mut acc = vec![0.0f32; ch]; + let mut wsum = 0.0f32; + for ty in y.saturating_sub(r)..=(y + r).min(self.h - 1) { + let dy = ty as isize - y as isize; + let krow = (ty - tb.y0) * tb.width(); + for tx in x.saturating_sub(r)..=(x + r).min(w - 1) { + let k = krow + tx - tb.x0; + let wt = self.wt[k]; + if wt == 0.0 { + continue; + } + let si = (self.src[k] - dy * w as isize - (tx as isize - x as isize)) as usize * ch; + for (c, a) in acc.iter_mut().enumerate() { + let v = if adapted { + let (g, b) = self.gb[k * ch + c]; + g * self.img[si + c] + b + } else { + self.img[si + c] + }; + *a += v * wt; + } + wsum += wt; + } + } + if wsum > 0.0 { + for (d, a) in out.iter_mut().zip(&acc) { + *d = a / wsum; + } + return true; + } + false + } +} + +/// `Σv, Σv²` per channel (the first `out.len()`) of the `side × side` patch with top-left +/// `(x0, y0)`, summed row by row, pixel by pixel, as [`Solver::moments`] does. +#[allow(clippy::too_many_arguments)] +fn patch_moments(img: &[f32], w: usize, ch: usize, c8: usize, side: usize, x0: usize, y0: usize, out: &mut [[f32; 2]]) { + out.iter_mut().for_each(|v| *v = [0.0; 2]); + for y in y0..y0 + side { + let row = &img[(y * w + x0) * ch..(y * w + x0 + side) * ch]; + for p in row.chunks_exact(ch) { + for (c, o) in out.iter_mut().enumerate().take(c8) { + let a = p[c]; + o[0] += a; + o[1] += a * a; + } + } + } +} + +/// The adapted distance from the moments `[Σt, Σt², Σs, Σs², Σts]` of each channel over `n` +/// samples: what is left of the target after the source is fitted to it, per sample. +#[inline] +fn adapted_cost(a: Adapt, nf: f32, m: &[[f32; 5]]) -> f32 { + let mut sum = 0.0f32; + for mc in m { + let (g, b) = fit(a, nf, mc[0], mc[1], mc[2], mc[3]); + // Σ (t − g s − b)², expanded. + sum += mc[1] + g * g * mc[3] + nf * b * b - 2.0 * g * mc[4] - 2.0 * b * mc[0] + 2.0 * g * b * mc[2]; + } + sum.max(0.0) / (nf * m.len() as f32) +} + +/// `Σ (t − s)²` over a target patch's known pixels (offsets `offs` from its centre, samples +/// `tv`, `CH` per pixel) against the source patch centred at pixel `base`, summed in that order; +/// `None` once the sum reaches `limit` (it only grows). +#[inline(always)] +pub(super) fn known_sse(image: &[f32], offs: &[isize], tv: &[f32], base: isize, limit: f32) -> Option { + let mut e = 0.0f32; + for (o, t) in offs.iter().zip(tv.as_chunks::().0) { + let si = (base + o) as usize * CH; + let s = &image[si..si + CH]; + for c in 0..CH { + let d = t[c] - s[c]; + e += d * d; + } + if e >= limit { + return None; + } + } + Some(e) +} + +/// [`known_sse`] of [`LANES`] sources at once, each against its own limit (summed in step: the +/// sums are independent, so the processor overlaps them). +#[inline(always)] +pub(super) fn known_sse_lanes(image: &[f32], offs: &[isize], tv: &[f32], bases: [isize; LANES], limits: [f32; LANES]) -> [Option; LANES] { + let mut e = [0.0f32; LANES]; + for (o, t) in offs.iter().zip(tv.as_chunks::().0) { + for l in 0..LANES { + let si = (bases[l] + o) as usize * CH; + let s = &image[si..si + CH]; + for c in 0..CH { + let d = t[c] - s[c]; + e[l] += d * d; + } + } + // Sums only grow: once all of them reached their limits, none can win. + if (0..LANES).all(|l| e[l] >= limits[l]) { + break; + } + } + std::array::from_fn(|l| (e[l] < limits[l]).then_some(e[l])) +} + +/// Sources [`known_sse_lanes`] sums at once. +pub(super) const LANES: usize = 4; + +/// [`known_sse`] for any number of channels. +pub(super) fn known_sse_any(image: &[f32], ch: usize, offs: &[isize], tv: &[f32], base: isize, limit: f32) -> Option { + let mut e = 0.0f32; + for (o, t) in offs.iter().zip(tv.chunks_exact(ch.max(1))) { + let si = (base + o) as usize * ch; + for (tc, sc) in t.iter().zip(&image[si..si + ch]) { + let d = tc - sc; + e += d * d; + } + if e >= limit { + return None; + } + } + Some(e) +} + +/// The best source so far of [`onion_peel`]'s search. +#[derive(Clone, Copy)] +pub(super) struct Best { + /// Error per sample, and the place in the sources. + pub(super) v: f32, + pub(super) j: usize, + /// Sums of squared errors from which `sum / n` is above `v`, and at least `v`. + pub(super) worse: f32, + pub(super) equal: f32, +} + +/// The least sum `e ≥ 0` with `e / n > v` (`strict`) or `e / n ≥ v` in float arithmetic (the +/// quotient only grows with `e`); infinity for an infinite `v`. +pub(super) fn least_sum(v: f32, n: f32, strict: bool) -> f32 { + let holds = |e: f32| if strict { e / n > v } else { e / n >= v }; + if !v.is_finite() || !n.is_finite() || n <= 0.0 { + return f32::INFINITY; + } + let mut e = (v * n).max(0.0); + while e > 0.0 && holds(e.next_down()) { + e = e.next_down(); + } + while !holds(e) && e < f32::INFINITY { + e = e.next_up(); + } + e +} diff --git a/crates/algo/src/inpaint/sources.rs b/crates/algo/src/inpaint/sources.rs new file mode 100644 index 0000000000..a3f390cfc3 --- /dev/null +++ b/crates/algo/src/inpaint/sources.rs @@ -0,0 +1,326 @@ +use super::common::{Bounds, Level, PAR_MIN, Px}; +use super::*; + +/// Half-size level: a cell is a hole if any of its pixels is; else it averages its non-void +/// pixels, and may be copied from only if all of them may. +pub(super) fn downsample(l: &Level, ch: usize) -> Level<'static> { + let (w, h) = (l.w.div_ceil(2), l.h.div_ceil(2)); + let mut img = vec![0.0f32; w * h * ch]; + let mut px = vec![Px::Void; w * h]; + let (lw, lh, limg, lpx) = (l.w, l.h, &*l.img, &*l.px); + let row = |y: usize, irow: &mut [f32], prow: &mut [Px]| { + for (x, p) in prow.iter_mut().enumerate() { + let mut n = 0.0f32; + let o = x * ch; + let (mut hole, mut all_source, mut any) = (false, true, false); + for (dx, dy) in [(0, 0), (1, 0), (0, 1), (1, 1)] { + let (sx, sy) = (x * 2 + dx, y * 2 + dy); + if sx >= lw || sy >= lh { + continue; + } + let si = sy * lw + sx; + match lpx[si] { + Px::Hole => hole = true, + Px::Void => all_source = false, + k => { + any = true; + all_source &= k == Px::Source; + for c in 0..ch { + irow[o + c] += limg[si * ch + c]; + } + n += 1.0; + } + } + } + if n > 0.0 { + for c in 0..ch { + irow[o + c] /= n; + } + } + *p = if hole { + Px::Hole + } else if !any { + Px::Void + } else if all_source { + Px::Source + } else { + Px::Known + }; + } + }; + par::chunks2_mut(&mut img, w * ch, &mut px, w, w * h >= PAR_MIN, row); + Level { w, h, img: Cow::Owned(img), px: Cow::Owned(px) } +} + +/// Summed-area table of a boolean grid (`(w+1) × (h+1)`). Not inlined: in [`synthesize`] it made +/// Create Texture's candidate loop slower (measured). +#[inline(never)] +pub(super) fn integral(w: usize, h: usize, m: &[bool]) -> Vec { + let mut s = vec![0u32; (w + 1) * (h + 1)]; + for y in 0..h { + let mut row = 0u32; + for x in 0..w { + row += u32::from(m[y * w + x]); + s[(y + 1) * (w + 1) + x + 1] = s[y * (w + 1) + x + 1] + row; + } + } + s +} + +/// Count of set cells in the clipped window `[x0, x1) × [y0, y1)`. +pub(super) fn window_count(s: &[u32], gw: usize, gh: usize, x0: i32, y0: i32, x1: i32, y1: i32) -> u32 { + let (x0, y0) = (x0.max(0) as usize, y0.max(0) as usize); + let (x1, y1) = ((x1.max(0) as usize).min(gw), (y1.max(0) as usize).min(gh)); + if x1 <= x0 || y1 <= y0 { + return 0; + } + let w1 = gw + 1; + s[y1 * w1 + x1] + s[y0 * w1 + x0] - s[y0 * w1 + x1] - s[y1 * w1 + x0] +} + +pub(super) fn hole_bbox(w: usize, h: usize, hole: &[bool]) -> Option<(usize, usize, usize, usize)> { + let mut b: Option<(usize, usize, usize, usize)> = None; + for y in 0..h { + for x in 0..w { + if hole[y * w + x] { + b = Some(match b { + None => (x, y, x + 1, y + 1), + Some((x0, y0, x1, y1)) => (x0.min(x), y0.min(y), x1.max(x + 1), y1.max(y + 1)), + }); + } + } + } + b +} + +/// A hole at most `1 / THIN_RATIO` as thick as its bounds are long counts as thin (a wire, a +/// string, a hair, a long brush stroke): see the module docs. +pub(super) const THIN_RATIO: usize = 4; + +/// How thick the hole within bounds `hb` of a `w`-wide role grid is: twice the largest distance +/// from a hole pixel to the nearest pixel that is not one (a long, thin hole is thin however long +/// its bounds). +pub(super) fn hole_thickness(w: usize, hb: Bounds, px: &[Px]) -> usize { + // The bounds and a ring of non-hole cells around them (also past the grid's edge). + let (gw, gh) = (hb.width() + 2, hb.height() + 2); + let outside: Vec = par::map(gw * gh, gw * gh >= PAR_MIN, |i| { + let (gx, gy) = (i % gw, i / gw); + if gx == 0 || gy == 0 || gx > hb.width() || gy > hb.height() { + return true; + } + px.get((hb.y0 + gy - 1) * w + hb.x0 + gx - 1) != Some(&Px::Hole) + }); + let deepest = crate::selection::edt(&outside, gw, gh).into_iter().fold(0.0f32, f32::max); + (2.0 * deepest).ceil() as usize +} + +/// Most target pixels × sources the onion peel of a thin hole may compare (its search is +/// exhaustive, though most comparisons stop early: about a second at this many). +const PEEL_BUDGET: usize = 1 << 28; + +/// Whether the onion peel of the hole cells within `hb` of a `w`-wide role grid from `sources` +/// source centres stays within [`PEEL_BUDGET`]. +pub(super) fn peel_affordable(w: usize, px: &[Px], hb: Bounds, sources: usize) -> bool { + let holes: usize = (hb.y0..hb.y1).map(|y| px.get(y * w + hb.x0..y * w + hb.x1).map_or(0, |row| row.iter().filter(|k| **k == Px::Hole).count())).sum(); + holes.saturating_mul(sources) <= PEEL_BUDGET +} + +/// Bounds of the hole pixels of a role grid. +pub(super) fn hole_bounds(w: usize, h: usize, px: &[Px]) -> Option { + // A zero-width grid holds no pixels whatever its height; don't size a row table by it. + if w == 0 || h == 0 { + return None; + } + // Per row the first and last hole column; the union of the rows' spans. + let rows: Vec> = par::map(h, w * h >= PAR_MIN, |y| { + let row = px.get(y * w..(y + 1) * w)?; + let x0 = row.iter().position(|k| *k == Px::Hole)?; + let x1 = row.iter().rposition(|k| *k == Px::Hole).unwrap_or(x0) + 1; + Some((x0, x1)) + }); + let mut b: Option = None; + for (y, span) in rows.into_iter().enumerate() { + if let Some((x0, x1)) = span { + b = Some(match b { + None => Bounds { x0, y0: y, x1, y1: y + 1 }, + Some(b) => Bounds { x0: b.x0.min(x0), y0: b.y0, x1: b.x1.max(x1), y1: y + 1 }, + }); + } + } + b +} + +/// Valid source centres: the whole `2r+1` patch inside the grid and copyable. Found per row +/// (each pixel's horizontal run), then per column of runs. `None` when cancelled. +pub(super) fn valid_sources(w: usize, h: usize, r: usize, px: &[Px], ctl: &photocraft_raster::Interrupt) -> Option> { + const BAND: usize = 64; + let side = 2 * r + 1; + let par = w * h >= PAR_MIN; + let mut run = vec![false; w * h]; + if w < side || h < side { + return Some(run); + } + // Per row: is the run of `side` pixels centred on each one all copyable (a sliding count)? + par::chunks_mut(&mut run, w, par, |y, out| { + if y % BAND == 0 && ctl.cancelled() { + return; + } + let row = &px[y * w..(y + 1) * w]; + let copyable = |x: usize| usize::from(row[x] == Px::Source); + let mut count: usize = (0..side).map(copyable).sum(); + out[r] = count == side; + for (x, o) in out.iter_mut().enumerate().take(w - r).skip(r + 1) { + count = count + copyable(x + r) - copyable(x - r - 1); + *o = count == side; + } + }); + if ctl.cancelled() { + return None; + } + // Per column, in bands of rows: how many such runs end each row in a row; a centre is valid + // where `side` of them stack up to `r` rows below it. + let mut valid = vec![false; w * h]; + par::chunks_mut(&mut valid, BAND * w, par, |band, out| { + if ctl.cancelled() { + return; + } + let (y0, rows) = (band * BAND, out.len() / w); + let mut stack = vec![0usize; w]; + for yy in y0.saturating_sub(r)..(y0 + rows + r).min(h) { + for (x, n) in stack.iter_mut().enumerate() { + *n = if run[yy * w + x] { *n + 1 } else { 0 }; + } + // `yy` is the bottom row of centre `y`'s patch. + if yy < y0 + r || yy < 2 * r { + continue; + } + let y = yy - r; + for (v, n) in out[(y - y0) * w..(y - y0 + 1) * w].iter_mut().zip(&stack).take(w - r).skip(r) { + *v = *n >= side; + } + } + }); + if ctl.cancelled() { + return None; + } + Some(valid) +} + +/// Columns per block of [`Sources`]' index. +const SOURCE_BLOCK: usize = 64; + +/// The valid source centres in row-major order, indexed by counts per row and per block of +/// [`SOURCE_BLOCK`] columns (so the `k`-th is found without listing them all). +pub(super) struct Sources { + /// Valid centres before each row (`h + 1` entries). + row_start: Vec, + /// Per row, the valid centres in it before each block. + block_start: Vec, + blocks: usize, +} + +impl Sources { + pub(super) fn new(valid: &[bool], w: usize) -> Sources { + let h = valid.len().checked_div(w).unwrap_or(0); + let blocks = w.div_ceil(SOURCE_BLOCK); + let mut block_start = vec![0u32; h * blocks]; + // Per row: the block prefix, and the row's count. + let counts: Vec = par::map(h, valid.len() >= PAR_MIN, |y| valid[y * w..(y + 1) * w].iter().filter(|v| **v).count()); + par::chunks_mut(&mut block_start, blocks, valid.len() >= PAR_MIN, |y, out| { + let mut n = 0u32; + for (b, o) in out.iter_mut().enumerate() { + *o = n; + n += valid[y * w + b * SOURCE_BLOCK..y * w + ((b + 1) * SOURCE_BLOCK).min(w)].iter().filter(|v| **v).count() as u32; + } + }); + let mut row_start = Vec::with_capacity(counts.len() + 1); + let mut total = 0usize; + row_start.push(0); + for c in counts { + total += c; + row_start.push(total); + } + Sources { row_start, block_start, blocks } + } + + pub(super) fn len(&self) -> usize { + self.row_start.last().copied().unwrap_or(0) + } + + /// The `k`-th valid centre in row-major order (`k < len`). + pub(super) fn nth(&self, k: usize, valid: &[bool], w: usize) -> (i32, i32) { + let y = self.row_start.partition_point(|&s| s <= k).saturating_sub(1); + let left = k.saturating_sub(self.row_start.get(y).copied().unwrap_or(0)); + let row_blocks = self.block_start.get(y * self.blocks..(y + 1) * self.blocks).unwrap_or(&[]); + let b = row_blocks.partition_point(|&s| s as usize <= left).saturating_sub(1); + let mut left = left.saturating_sub(row_blocks.get(b).copied().unwrap_or(0) as usize); + let x0 = b * SOURCE_BLOCK; + for (x, v) in valid.iter().skip(y * w + x0).take(w.saturating_sub(x0)).enumerate() { + if *v { + if left == 0 { + return ((x0 + x) as i32, y as i32); + } + left -= 1; + } + } + (0, 0) + } + + /// All of them, in row-major order. + pub(super) fn all(&self, valid: &[bool], w: usize) -> Vec<(i32, i32)> { + let mut out = Vec::with_capacity(self.len()); + for (i, v) in valid.iter().enumerate() { + if *v { + out.push(((i % w) as i32, (i / w) as i32)); + } + } + out + } +} + +/// Per cell of `tb` (the hole's bounds `hb` grown by the patch radius, where all of them lie): is +/// it a target centre (its patch overlaps the hole)? +pub(super) fn targets_around(w: usize, r: usize, px: &[Px], hb: Bounds, tb: Bounds) -> Vec { + // Hole counts summed over the hole's bounds: every hole pixel lies inside them. + let (bw, bh) = (hb.width(), hb.height()); + let mut s = vec![0u32; (bw + 1) * (bh + 1)]; + for y in 0..bh { + let mut row = 0u32; + for x in 0..bw { + row += u32::from(px[(hb.y0 + y) * w + hb.x0 + x] == Px::Hole); + s[(y + 1) * (bw + 1) + x + 1] = s[y * (bw + 1) + x + 1] + row; + } + } + let mut targets = vec![false; tb.area()]; + let ri = r as i32; + let (ox, oy) = (hb.x0 as i32, hb.y0 as i32); + for y in tb.y0..tb.y1 { + for x in tb.x0..tb.x1 { + let k = (y - tb.y0) * tb.width() + (x - tb.x0); + let (x, y) = (x as i32, y as i32); + targets[k] = window_count(&s, bw, bh, x - ri - ox, y - ri - oy, x + ri + 1 - ox, y + ri + 1 - oy) > 0; + } + } + targets +} + +/// A finished coarser level: its size, pixels and match field (the source centre per cell of +/// its target box, `i32::MIN` where there is none; empty when it had nothing to copy). +pub(super) struct Coarser { + pub(super) w: usize, + pub(super) h: usize, + pub(super) img: Vec, + pub(super) field: Vec<(i32, i32)>, + pub(super) tbox: Bounds, +} + +impl Coarser { + /// The match of cell `(x, y)` (`i32::MIN` outside the target box). + pub(super) fn field_at(&self, x: usize, y: usize) -> (i32, i32) { + let t = self.tbox; + if x < t.x0 || x >= t.x1 || y < t.y0 || y >= t.y1 { + return (i32::MIN, i32::MIN); + } + self.field.get((y - t.y0) * t.width() + (x - t.x0)).copied().unwrap_or((i32::MIN, i32::MIN)) + } +} diff --git a/crates/algo/src/inpaint/synthesis.rs b/crates/algo/src/inpaint/synthesis.rs new file mode 100644 index 0000000000..0c3bf9c375 --- /dev/null +++ b/crates/algo/src/inpaint/synthesis.rs @@ -0,0 +1,381 @@ +use super::common::{Bounds, Px, Rng}; +use super::solver::{Best, LANES, known_sse, known_sse_any, known_sse_lanes, least_sum}; +use super::sources::{hole_bbox, integral, window_count}; +use super::*; + +/// Fill the hole from its edge inwards, one ring at a time: each pixel takes the centre of the +/// source patch that best matches what is already known around it (the first in `sources` of +/// those that match best). `hb` bounds the hole. +/// +/// The search is exhaustive, but most sources are given up early (#2771, #2805): the target's +/// known pixels are gathered once, the search starts from where the pixel's filled neighbours +/// took their sources (or every 16th source at the hole's edge), and a source's error stops being +/// added up once it can only lose (it only grows). So it finds the same source as a plain scan in +/// order, sooner. +#[allow(clippy::too_many_arguments)] +pub(super) fn onion_peel( + w: usize, + h: usize, + ch: usize, + r: i32, + img: &mut [f32], + px: &[Px], + hb: Bounds, + sources: &[(i32, i32)], + ctl: &photocraft_raster::Interrupt, +) -> Result<(), photocraft_raster::Cancelled> { + const NONE: u32 = u32::MAX; + let mut known: Vec = px.iter().map(|k| matches!(k, Px::Known | Px::Source)).collect(); + // Each source centre's place in `sources`, and the source each filled pixel took. + let mut index = vec![NONE; w * h]; + for (j, &(x, y)) in sources.iter().enumerate() { + index[y as usize * w + x as usize] = j as u32; + } + let mut took = vec![NONE; w * h]; + let neighbours = [(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)]; + loop { + ctl.check()?; + let mut front: Vec = Vec::new(); + for y in hb.y0..hb.y1 { + for x in hb.x0..hb.x1 { + let i = y * w + x; + if known[i] || px[i] != Px::Hole { + continue; + } + let (x, y) = (x as i32, y as i32); + let edge = (-1..=1).any(|dy: i32| { + (-1..=1).any(|dx: i32| { + let (nx, ny) = (x + dx, y + dy); + nx >= 0 && ny >= 0 && (nx as usize) < w && (ny as usize) < h && known[ny as usize * w + nx as usize] + }) + }); + if edge { + front.push(i); + } + } + } + if front.is_empty() { + break; + } + let (known_now, took_now) = (&known, &took); + let image = &*img; + let best = |&i: &usize| -> (Vec, u32) { + let (x, y) = ((i % w) as i32, (i / w) as i32); + // The known pixels of the target patch, in the plain scan's order: each one's offset + // from the patch centre (in pixels) and its samples (gathered once, #2805). + let side = (2 * r + 1) as usize; + let mut offs: Vec = Vec::with_capacity(side * side); + let mut tv: Vec = Vec::with_capacity(side * side * ch); + for dy in -r..=r { + for dx in -r..=r { + let (tx, ty) = (x + dx, y + dy); + if tx >= 0 && ty >= 0 && (tx as usize) < w && (ty as usize) < h && known_now[ty as usize * w + tx as usize] { + let ti = (ty as usize * w + tx as usize) * ch; + offs.push(dy as isize * w as isize + dx as isize); + tv.extend_from_slice(&image[ti..ti + ch]); + } + } + } + // The best so far: its error per sample, its place in `sources` (the first of equals + // wins, as in a scan in order), and the sums of squares at which a source surely loses + // to it (`e / n` above the best) or ties it (at least the best). + let mut best = Best { v: f32::INFINITY, j: usize::MAX, worse: f32::INFINITY, equal: f32::INFINITY }; + if !offs.is_empty() { + let nf = offs.len() as f32; + let base_of = |j: usize| sources.get(j).map_or(0, |&(sx, sy)| sy as isize * w as isize + sx as isize); + // The sum at which source `j` can't win: a tie loses to an earlier source. + let limit_of = |j: usize, best: &Best| if j > best.j { best.equal } else { best.worse }; + // Source `j`'s whole sum `e` (it did not reach its limit): does it win? + let adopt = |j: usize, e: f32, best: &mut Best| { + let v = e / nf; + if v < f32::INFINITY && (v < best.v || (v == best.v && j < best.j)) { + *best = Best { v, j, worse: least_sum(v, nf, true), equal: least_sum(v, nf, false) }; + } + }; + let consider = |j: usize, best: &mut Best| { + if j >= sources.len() { + return; + } + let (base, limit) = (base_of(j), limit_of(j, best)); + let e = match ch { + 1 => known_sse::<1>(image, &offs, &tv, base, limit), + 3 => known_sse::<3>(image, &offs, &tv, base, limit), + 4 => known_sse::<4>(image, &offs, &tv, base, limit), + _ => known_sse_any(image, ch, &offs, &tv, base, limit), + }; + if let Some(e) = e { + adopt(j, e, best); + } + }; + // A close bound early: where the filled neighbours' sources point (shifted as in + // PatchMatch's propagation), or at the hole's edge, where none is filled yet, + // every 16th source. + for (dx, dy) in neighbours { + let (qx, qy) = (x + dx, y + dy); + if qx < 0 || qy < 0 || qx as usize >= w || qy as usize >= h { + continue; + } + let Some(&(sx, sy)) = sources.get(took_now[qy as usize * w + qx as usize] as usize) else { continue }; + let (cx, cy) = (sx - dx, sy - dy); + if cx >= 0 && cy >= 0 && (cx as usize) < w && (cy as usize) < h && index[cy as usize * w + cx as usize] != NONE { + consider(index[cy as usize * w + cx as usize] as usize, &mut best); + } + } + if best.j == usize::MAX { + for j in (0..sources.len()).step_by(16) { + consider(j, &mut best); + } + } + // The scan in order, `LANES` sources at a time (their sums are independent, so they + // overlap), each against its limit from the best before them: the best only gets + // better, so a source given up would have lost to it anyway. + let mut j = 0; + while j + LANES <= sources.len() { + if j.is_multiple_of(4096) && j > 0 && ctl.cancelled() { + break; + } + let bases: [isize; LANES] = std::array::from_fn(|l| base_of(j + l)); + let limits: [f32; LANES] = std::array::from_fn(|l| limit_of(j + l, &best)); + let sums = match ch { + 1 => known_sse_lanes::<1>(image, &offs, &tv, bases, limits), + 3 => known_sse_lanes::<3>(image, &offs, &tv, bases, limits), + 4 => known_sse_lanes::<4>(image, &offs, &tv, bases, limits), + _ => std::array::from_fn(|l| known_sse_any(image, ch, &offs, &tv, bases[l], limits[l])), + }; + for (l, e) in sums.into_iter().enumerate() { + if let Some(e) = e { + adopt(j + l, e, &mut best); + } + } + j += LANES; + } + for j in j..sources.len() { + consider(j, &mut best); + } + } + let (sx, sy) = sources.get(best.j).copied().unwrap_or((0, 0)); + let si = (sy as usize * w + sx as usize) * ch; + (image[si..si + ch].to_vec(), if best.j == usize::MAX { NONE } else { best.j as u32 }) + }; + let vals: Vec<(Vec, u32)> = par::map(front.len(), front.len() * sources.len() >= 4096, |k| best(&front[k])); + ctl.check()?; + for (&i, (v, j)) in front.iter().zip(vals) { + img[i * ch..(i + 1) * ch].copy_from_slice(&v); + known[i] = true; + took[i] = j; + } + } + Ok(()) +} + +/// Proximity match: the displacement `(dx, dy)` (within `max_radius`) whose surroundings best match the +/// ring of `ring` pixels around the hole, with the displaced hole fully inside the grid and outside the +/// hole. `None` if no displacement fits. +pub fn best_offset(w: usize, h: usize, ch: usize, img: &[f32], hole: &[bool], ring: usize, max_radius: i32) -> Option<(i32, i32)> { + let (bx0, by0, bx1, by1) = hole_bbox(w, h, hole)?; + // No valid translation can move farther than the source image's extent. + // Bound arbitrary public API inputs before constructing i32 search ranges: + // usize -> i32 truncation and signed increments otherwise overflow or hang. + let extent = w.max(h).min((i32::MAX / 4) as usize) as i32; + let max_radius = max_radius.max(0).min(extent); + if max_radius == 0 { + return None; + } + let ring = ring.max(1).min(extent as usize) as i32; + // Every set cell lies in the hole bounds. Counts outside that rectangle are zero, + // so source rejection needs a table for the hole, not for the whole photo. + let hs = HoleIntegral::new(w, hole, (bx0, by0, bx1, by1))?; + // Sample points: the hole's ring (dilated minus hole), subsampled for speed. + let mut pts = Vec::new(); + let (x0, y0) = (bx0 as i32 - ring, by0 as i32 - ring); + let (x1, y1) = (bx1 as i32 + ring, by1 as i32 + ring); + for y in y0.max(0)..y1.min(h as i32) { + for x in x0.max(0)..x1.min(w as i32) { + if hole[y as usize * w + x as usize] { + continue; + } + if hs.count(x - ring, y - ring, x + ring + 1, y + ring + 1) > 0 { + pts.push((x, y)); + } + } + } + let stride = (pts.len() / 2000).max(1); + let pts: Vec<(i32, i32)> = pts.into_iter().step_by(stride).collect(); + let eval = |dx: i32, dy: i32, cutoff: f32| -> Option { + let (hx0, hy0, hx1, hy1) = (x0 + dx, y0 + dy, x1 + dx, y1 + dy); + let inside = hx0 >= 0 && hy0 >= 0 && hx1 <= w as i32 && hy1 <= h as i32; + if (dx, dy) == (0, 0) || !inside || hs.count(hx0, hy0, hx1, hy1) != 0 { + return None; + } + let mut e = 0.0f32; + let n = pts.len().max(1) as f32; + let penalty = 1.0 + 1e-3 * ((dx as f32).hypot(dy as f32) / max_radius as f32); + for (i, &(x, y)) in pts.iter().enumerate() { + let (a, b) = ((y as usize * w + x as usize) * ch, ((y + dy) as usize * w + (x + dx) as usize) * ch); + for c in 0..ch { + let d = img[a + c] - img[b + c]; + e += d * d; + } + // SSD terms are nonnegative. The partial score is a lower bound on the + // final score; use the same division and penalty to keep float rounding + // and strict tie ordering unchanged. Check in batches to keep this cheap. + if i % 32 == 31 && cutoff.is_finite() && e / n * penalty >= cutoff { + return None; + } + } + // Mild preference for nearer sources on ties. + Some(e / n * penalty) + }; + // Coarse grid over the search window, then a full-resolution refinement around the winner. + let step = (max_radius / 24).max(1); + let mut best: Option<((i32, i32), f32)> = None; + let consider = |dx: i32, dy: i32, best: &mut Option<((i32, i32), f32)>| { + if let Some(e) = eval(dx, dy, best.map_or(f32::INFINITY, |(_, error)| error)) + && best.is_none_or(|(_, be)| e < be) + { + *best = Some(((dx, dy), e)); + } + }; + let mut dy = -max_radius; + while dy <= max_radius { + let mut dx = -max_radius; + while dx <= max_radius { + consider(dx, dy, &mut best); + dx += step; + } + dy += step; + } + if step > 1 + && let Some(((bx, by), _)) = best + { + for dy in (by - step)..=(by + step) { + for dx in (bx - step)..=(bx + step) { + consider(dx, dy, &mut best); + } + } + } + best.map(|b| b.0) +} + +/// Create texture: fill the hole with blocks of surrounding texture (see module docs). +pub fn synthesize(w: usize, h: usize, ch: usize, img: &[f32], hole: &[bool], block: usize, seed: u64) -> Vec { + let mut out = img.to_vec(); + let Some((bx0, by0, bx1, by1)) = hole_bbox(w, h, hole) else { return out }; + let b = block.max(4) as i32; + let ov = (b / 3).max(1); + let hs = integral(w, h, hole); + // Candidate block origins: whole block (with overlap) inside the grid and outside the hole. + let mut cands = Vec::new(); + for y in ov..(h as i32 - b - ov) { + for x in ov..(w as i32 - b - ov) { + if window_count(&hs, w, h, x - ov, y - ov, x + b + ov, y + b + ov) == 0 { + cands.push((x, y)); + } + } + } + if cands.is_empty() { + return membrane_fill(w, h, ch, img, hole); + } + let mut filled: Vec = hole.iter().map(|x| !x).collect(); + let mut rng = Rng::new(seed); + let mut by = by0 as i32; + while by < by1 as i32 { + let mut bx = bx0 as i32; + while bx < bx1 as i32 { + if window_count(&hs, w, h, bx, by, bx + b, by + b) > 0 { + // Pick the candidate whose block best agrees with already-known pixels around/inside. + let mut best = (cands[0], f32::INFINITY); + for _ in 0..48 { + let c = cands[(rng.next() % cands.len() as u64) as usize]; + let (mut e, mut n) = (0.0f32, 0u32); + for y in (by - ov)..(by + b + ov) { + for x in (bx - ov)..(bx + b + ov) { + if x < 0 || y < 0 || x >= w as i32 || y >= h as i32 || !filled[y as usize * w + x as usize] { + continue; + } + let (a, s) = ((y as usize * w + x as usize) * ch, ((y - by + c.1) as usize * w + (x - bx + c.0) as usize) * ch); + for k in 0..ch { + let d = out[a + k] - img[s + k]; + e += d * d; + } + n += 1; + } + } + let e = if n == 0 { 0.0 } else { e / n as f32 }; + if e < best.1 { + best = (c, e); + } + } + let c = best.0; + let (x0, y0) = ((bx - ov).max(0), (by - ov).max(0)); + let (x1, y1) = ((bx + b + ov).min(w as i32), (by + b + ov).min(h as i32)); + let src = |x: i32, y: i32| ((y - by + c.1) as usize * w + (x - bx + c.0) as usize) * ch; + // Squared difference between what is there and the block, where both exist. + let err = |x: i32, y: i32| { + let i = y as usize * w + x as usize; + if !(hole[i] && filled[i]) { + return 0.0; + } + let (a, s) = (i * ch, src(x, y)); + (0..ch).map(|q| (out[a + q] - img[s + q]).powi(2)).sum::() + }; + // Minimum-error boundary cuts through the overlaps with the blocks to the left and + // above: the block is copied right of and below them, untouched pixels are kept + // on the other side. Copying (rather than averaging) keeps the texture's grain. + let left = min_cut((x0..(bx + ov).min(x1)).len(), (y0..y1).len(), |u, v| err(x0 + u as i32, y0 + v as i32)); + let top = min_cut((y0..(by + ov).min(y1)).len(), (x0..x1).len(), |u, v| err(x0 + v as i32, y0 + u as i32)); + for y in y0..y1 { + for x in x0..x1 { + let i = y as usize * w + x as usize; + if !hole[i] { + continue; + } + let (u, v) = ((x - x0) as usize, (y - y0) as usize); + let keep = filled[i] && (left.get(v).is_some_and(|s| u < *s) || top.get(u).is_some_and(|s| v < *s)); + if !keep { + let (a, s) = (i * ch, src(x, y)); + out[a..a + ch].copy_from_slice(&img[s..s + ch]); + } + filled[i] = true; + } + } + } + bx += b; + } + by += b; + } + out +} + +/// The minimum-error cut through a band `across` wide and `along` long (Efros & Freeman's +/// boundary cut, by dynamic programming): for each step along the band, the offset across it +/// where the cut runs (`err(across, along)` is the cost of a pixel). Pixels before the cut keep +/// what is there. Empty when there is no cost anywhere (nothing to cut through). +fn min_cut(across: usize, along: usize, err: impl Fn(usize, usize) -> f32) -> Vec { + if across == 0 || along == 0 { + return Vec::new(); + } + // Cumulative cost, step by step along the band; the cut may move by one pixel per step. + let mut acc: Vec = (0..along).flat_map(|v| (0..across).map(move |u| (u, v))).map(|(u, v)| err(u, v)).collect(); + if acc.iter().all(|x| *x == 0.0) { + return Vec::new(); + } + for v in 1..along { + for u in 0..across { + let lo = u.saturating_sub(1); + let hi = (u + 1).min(across - 1); + let m = (lo..=hi).map(|k| acc[(v - 1) * across + k]).fold(f32::INFINITY, f32::min); + acc[v * across + u] += m; + } + } + let argmin = |v: usize, lo: usize, hi: usize| (lo..=hi).min_by(|a, b| acc[v * across + a].total_cmp(&acc[v * across + b])).unwrap_or(lo); + let mut cut = vec![0; along]; + let mut u = argmin(along - 1, 0, across - 1); + for v in (0..along).rev() { + if v + 1 < along { + u = argmin(v, u.saturating_sub(1), (u + 1).min(across - 1)); + } + cut[v] = u; + } + cut +} diff --git a/crates/algo/src/inpaint/tests.rs b/crates/algo/src/inpaint/tests.rs new file mode 100644 index 0000000000..45690fac01 --- /dev/null +++ b/crates/algo/src/inpaint/tests.rs @@ -0,0 +1,466 @@ +use super::*; + +/// The mean is matched first: on a nearly flat bright patch with a noisy deviation ratio the +/// gain stays where the bias can still reach the target's mean. +#[test] +fn fit_matches_the_mean_before_the_contrast() { + let a = Adapt { gain: (0.9, 1.1), bias: 0.04 }; + // Target mean 0.70, source mean 0.70; deviations 0.01 vs 0.004 (ratio 2.5). + let n = 25.0; + let (mt, ms, sdt, sds) = (0.70f32, 0.70f32, 0.01f32, 0.004f32); + let (g, b) = fit(a, n, mt * n, (sdt * sdt + mt * mt) * n, ms * n, (sds * sds + ms * ms) * n); + assert!((g * ms + b - mt).abs() < 1e-5, "mean {} vs {mt} (g {g}, b {b})", g * ms + b); + // Where the mean can't be reached anyway, the limits hold as before. + let (g, b) = fit(a, n, 0.2 * n, 0.04 * n, 0.9 * n, 0.81 * n); + assert!((a.gain.0..=a.gain.1).contains(&g) && b.abs() <= a.bias + 1e-6); +} + +/// A zero-width image has no pixels however tall it is claimed to be: no per-row table. +#[test] +fn zero_width_images_complete_without_sizing_by_height() { + let p = CompleteParams::default(); + assert_eq!(complete(0, 1 << 40, 3, &[], &[], &p), Some(Vec::new())); + assert_eq!(complete(1 << 40, 0, 3, &[], &[], &p), Some(Vec::new())); +} + +/// Smooth gradient plus deterministic fine noise. +fn texture(w: usize, h: usize) -> Vec { + let mut rng = Rng::new(7); + (0..w * h) + .flat_map(|i| { + let (x, y) = ((i % w) as f32, (i / w) as f32); + let n = (rng.next() % 1000) as f32 / 1000.0 * 0.04 - 0.02; + [0.3 + 0.004 * x + n, 0.5 + 0.002 * y + n, 0.4 + n] + }) + .collect() +} + +fn disc(w: usize, h: usize, cx: f32, cy: f32, r: f32) -> Vec { + (0..w * h).map(|i| ((i % w) as f32 - cx).hypot((i / w) as f32 - cy) < r).collect() +} + +fn hole_rmse(a: &[f32], b: &[f32], hole: &[bool], ch: usize) -> f32 { + let (mut e, mut n) = (0.0f32, 0); + for (i, hh) in hole.iter().enumerate() { + if *hh { + for c in 0..ch { + e += (a[i * ch + c] - b[i * ch + c]).powi(2); + n += 1; + } + } + } + (e / n as f32).sqrt() +} + +#[test] +fn completion_fills_blemish_from_texture() { + let (w, h, ch) = (96, 96, 3); + let clean = texture(w, h); + let hole = disc(w, h, 48.0, 48.0, 9.0); + let mut dirty = clean.clone(); + for (i, hh) in hole.iter().enumerate() { + if *hh { + dirty[i * ch..i * ch + ch].copy_from_slice(&[0.02, 0.02, 0.02]); + } + } + let out = complete(w, h, ch, &dirty, &hole, &CompleteParams::default()).unwrap(); + let before = hole_rmse(&dirty, &clean, &hole, ch); + let after = hole_rmse(&out, &clean, &hole, ch); + assert!(after < 0.06 && after < before * 0.15, "rmse before {before} after {after}"); + // Outside the hole untouched. + assert!(out.iter().zip(&dirty).zip(hole.iter().flat_map(|h| [*h; 3])).all(|((a, b), h)| h || a == b)); + // Deterministic. + assert_eq!(out, complete(w, h, ch, &dirty, &hole, &CompleteParams::default()).unwrap()); +} + +#[test] +fn completion_continues_structure() { + // Vertical stripes: the filled hole should keep the stripes (not a blur). + let (w, h, ch) = (80, 80, 1); + let clean: Vec = (0..w * h).map(|i| if (i % w / 4) % 2 == 0 { 0.2 } else { 0.8 }).collect(); + let hole = disc(w, h, 40.0, 40.0, 7.0); + let dirty: Vec = clean.iter().zip(&hole).map(|(c, h)| if *h { 0.5 } else { *c }).collect(); + let out = complete(w, h, ch, &dirty, &hole, &CompleteParams::default()).unwrap(); + let err = hole_rmse(&out, &clean, &hole, ch); + assert!(err < 0.15, "{err}"); +} + +#[test] +fn proximity_finds_matching_offset() { + let (w, h, ch) = (80, 60, 1); + // Periodic pattern with period 10 in x: a match is any multiple-of-10 displacement. + let img: Vec = (0..w * h).map(|i| ((i % w) as f32 * std::f32::consts::TAU / 10.0).sin() * 0.4 + 0.5).collect(); + let hole = disc(w, h, 40.0, 30.0, 5.0); + let (dx, dy) = best_offset(w, h, ch, &img, &hole, 3, 20).unwrap(); + assert_eq!(dx.rem_euclid(10), 0, "dx {dx} dy {dy}"); + assert!((dx, dy) != (0, 0)); +} + +#[test] +fn proximity_search_clamps_hostile_radii_without_overflow_or_hanging() { + let (w, h, ch) = (24, 20, 1); + let img: Vec = (0..w * h).map(|i| (i % w) as f32 / w as f32).collect(); + let hole = disc(w, h, 12.0, 10.0, 2.0); + // User-supplied values used to overflow i32 loops, cast a huge usize + // ring into a negative number, or take billions of search iterations. + let result = best_offset(w, h, ch, &img, &hole, usize::MAX, i32::MAX); + if let Some((dx, dy)) = result { + assert!(dx.abs() <= w as i32 && dy.abs() <= h as i32); + } + assert_eq!(best_offset(w, h, ch, &img, &hole, 2, -1), None); + assert_eq!(best_offset(w, h, ch, &img, &hole, 2, 0), None); +} + +/// Structure, fine noise and flat patches (so that some matches tie exactly), `ch` channels. +fn busy(w: usize, h: usize, ch: usize, seed: u64) -> Vec { + let mut rng = Rng::new(seed); + (0..w * h) + .flat_map(|i| { + let (x, y) = (i % w, i / w); + let flat = (x / 9 + y / 7) % 5 == 0; + let n = (rng.next() % 1000) as f32 / 1000.0; + (0..ch).map(move |c| if flat { 0.25 + 0.1 * c as f32 } else { (0.2 + 0.004 * x as f32 + 0.1 * ((x + 2 * y + c) % 6) as f32 + 0.05 * n).min(1.0) }) + }) + .collect() +} + +fn bits(v: &[f32]) -> Vec { + v.iter().map(|x| x.to_bits()).collect() +} + +/// Roles: a hole, a band that is context only, a corner that is no image. +fn roles(w: usize, h: usize, hole: &[bool]) -> Vec { + (0..w * h) + .map(|i| { + let (x, y) = (i % w, i / w); + if hole[i] { + Px::Hole + } else if x < 4 && y < 6 { + Px::Void + } else if (w * 3 / 4..w * 3 / 4 + 3).contains(&x) { + Px::Known + } else { + Px::Source + } + }) + .collect() +} + +#[test] +fn a_hole_is_as_thick_as_it_is_through_not_along() { + let (w, h) = (240, 120); + let all = Bounds { x0: 0, y0: 0, x1: w, y1: h }; + let thickness = |hole: &[bool]| { + let px: Vec = hole.iter().map(|&o| if o { Px::Hole } else { Px::Source }).collect(); + hole_thickness(w, hole_bounds(w, h, &px).unwrap_or(all), &px) + }; + // A band 200 px long and 9 px thick; a disc of radius 20; the band touching the edge + // counts the outside of the image as not hole. + let band: Vec = (0..w * h).map(|i| (20..220).contains(&(i % w)) && (50..59).contains(&(i / w))).collect(); + assert!((9..=11).contains(&thickness(&band)), "{}", thickness(&band)); + assert!((39..=42).contains(&thickness(&disc(w, h, 120.0, 60.0, 20.0)))); + let edge: Vec = (0..w * h).map(|i| i / w < 9).collect(); + assert!((9..=11).contains(&thickness(&edge)), "{}", thickness(&edge)); +} + +/// A long thin hole goes the thin way (a shallow pyramid that starts from a membrane): it is +/// filled, only it changes, and the result does not depend on the thread count either. +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn thin_holes_are_filled_the_same_on_any_number_of_threads() { + let (w, h) = (300, 200); + let img = busy(w, h, 3, 5); + // A wavy line 6 px thick across the image. + let hole: Vec = (0..w * h).map(|i| (((i % w) as f32 * 0.05).sin() * 30.0 + 100.0 - (i / w) as f32).abs() < 3.0).collect(); + let px = roles(w, h, &hole); + let run = |threads: usize| { + let pool = rayon::ThreadPoolBuilder::new().num_threads(threads).build().unwrap(); + pool.install(|| complete_masked(w, h, 3, &img, &px, &CompleteParams::default(), &photocraft_raster::Interrupt::NONE)).unwrap().unwrap() + }; + let one = run(1); + assert_eq!(bits(&one), bits(&run(7))); + assert!((0..w * h).all(|i| hole[i] || (0..3).all(|c| one[i * 3 + c].to_bits() == img[i * 3 + c].to_bits()))); + assert!((0..w * h).filter(|&i| hole[i]).all(|i| (0..3).all(|c| one[i * 3 + c].is_finite()))); +} + +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn results_do_not_depend_on_the_thread_count() { + // Big enough for the parallel passes, and for PatchMatch to sweep in wavefronts where + // there are fewer bands than threads (never with one thread). + let (w, h) = (300, 260); + for (ch, adapt) in [(3, Adapt::NONE), (4, Adapt { gain: (0.9, 1.1), bias: 0.04 })] { + let img = busy(w, h, ch, 3); + let hole = disc(w, h, 140.0, 130.0, 40.0); + let px = roles(w, h, &hole); + let p = CompleteParams { adapt, ..Default::default() }; + let run = |threads: usize| { + let pool = rayon::ThreadPoolBuilder::new().num_threads(threads).build().unwrap(); + bits(&pool.install(|| complete_masked(w, h, ch, &img, &px, &p, &photocraft_raster::Interrupt::NONE)).unwrap().unwrap()) + }; + let one = run(1); + assert_eq!(one, run(3), "{ch} channels, 3 threads"); + assert_eq!(one, run(16), "{ch} channels, 16 threads"); + } +} + +/// The onion peel as first written: every source in order, every known pixel summed. +fn onion_peel_plain(w: usize, h: usize, ch: usize, r: i32, img: &mut [f32], px: &[Px], sources: &[(i32, i32)]) { + let mut known: Vec = px.iter().map(|k| matches!(k, Px::Known | Px::Source)).collect(); + loop { + let front: Vec = (0..w * h) + .filter(|&i| { + let (x, y) = ((i % w) as i32, (i / w) as i32); + !known[i] + && px[i] == Px::Hole + && (-1..=1).any(|dy: i32| { + (-1..=1).any(|dx: i32| { + let (nx, ny) = (x + dx, y + dy); + nx >= 0 && ny >= 0 && (nx as usize) < w && (ny as usize) < h && known[ny as usize * w + nx as usize] + }) + }) + }) + .collect(); + if front.is_empty() { + break; + } + let vals: Vec> = front + .iter() + .map(|&i| { + let (x, y) = ((i % w) as i32, (i / w) as i32); + let mut best = (f32::INFINITY, (0i32, 0i32)); + for &(sx, sy) in sources { + let (mut e, mut n) = (0.0f32, 0usize); + for dy in -r..=r { + for dx in -r..=r { + let (tx, ty) = (x + dx, y + dy); + if tx < 0 || ty < 0 || tx as usize >= w || ty as usize >= h || !known[ty as usize * w + tx as usize] { + continue; + } + let (ti, si) = ((ty as usize * w + tx as usize) * ch, ((sy + dy) as usize * w + (sx + dx) as usize) * ch); + for c in 0..ch { + let d = img[ti + c] - img[si + c]; + e += d * d; + } + n += 1; + } + } + if n > 0 && e / (n as f32) < best.0 { + best = (e / n as f32, (sx, sy)); + } + } + let si = (best.1.1 as usize * w + best.1.0 as usize) * ch; + img[si..si + ch].to_vec() + }) + .collect(); + for (&i, v) in front.iter().zip(vals) { + img[i * ch..(i + 1) * ch].copy_from_slice(&v); + known[i] = true; + } + } +} + +/// #2805's case (upstream's own speed-up of the onion peel, superseded here): repeating +/// texture with many exact ties, two holes; the result must be the plain scan's to the bit. +#[test] +fn onion_peel_picks_exactly_what_the_plain_scan_picks() { + let (w, h, ch, r) = (48, 40, 3, 3); + let mut img = texture(w, h); + for y in 0..h { + for x in 6..w / 2 { + for c in 0..ch { + img[(y * w + x) * ch + c] = img[(y * w + x % 6) * ch + c]; + } + } + } + let none = photocraft_raster::Interrupt::NONE; + for hole in [disc(w, h, 20.0, 18.0, 7.5), disc(w, h, 34.0, 22.0, 5.0)] { + let px: Vec = hole.iter().map(|h| if *h { Px::Hole } else { Px::Source }).collect(); + let near = integral(w, h, &hole); + let sources: Vec<(i32, i32)> = (r..h as i32 - r) + .flat_map(|y| (r..w as i32 - r).map(move |x| (x, y))) + .filter(|&(x, y)| window_count(&near, w, h, x - r, y - r, x + r + 1, y + r + 1) == 0) + .collect(); + let (mut fast, mut plain) = (img.clone(), img.clone()); + onion_peel(w, h, ch, r, &mut fast, &px, hole_bounds(w, h, &px).unwrap(), &sources, &none).unwrap(); + onion_peel_plain(w, h, ch, r, &mut plain, &px, &sources); + assert!(fast.iter().zip(&plain).all(|(a, b)| a.to_bits() == b.to_bits())); + assert_ne!(fast, img); + } +} + +#[test] +fn onion_peel_takes_the_plain_scans_sources() { + let none = photocraft_raster::Interrupt::NONE; + for (w, h, ch, seed) in [(44, 36, 1, 1), (50, 40, 3, 2), (40, 40, 4, 3)] { + let mut img = busy(w, h, ch, seed); + // Also an image of a few exact values, where many sources tie. + if seed == 3 { + img.iter_mut().for_each(|v| *v = (*v * 3.0).round() / 3.0); + } + let hole = disc(w, h, w as f32 * 0.45, h as f32 * 0.5, 7.5); + let px = roles(w, h, &hole); + let valid = valid_sources(w, h, 3, &px, &none).unwrap(); + let sources = Sources::new(&valid, w).all(&valid, w); + let (mut a, mut b) = (img.clone(), img.clone()); + onion_peel(w, h, ch, 3, &mut a, &px, hole_bounds(w, h, &px).unwrap(), &sources, &none).unwrap(); + onion_peel_plain(w, h, ch, 3, &mut b, &px, &sources); + assert_eq!(bits(&a), bits(&b), "{w}×{h}×{ch}"); + } +} + +#[test] +fn least_sum_is_where_the_quotient_crosses() { + let mut rng = Rng::new(5); + for i in 0..4000 { + let n = (1 + rng.next() % 49) as f32; + let v = match i % 4 { + 0 => 0.0, + 1 => (rng.next() % 1000) as f32 * 1e-9, + _ => (rng.next() % 1_000_000) as f32 / 1_000_000.0, + }; + for strict in [true, false] { + let holds = |e: f32| if strict { e / n > v } else { e / n >= v }; + let e = least_sum(v, n, strict); + assert!(holds(e), "{v} {n} {strict}: {e}"); + assert!(e == 0.0 || !holds(e.next_down()), "{v} {n} {strict}: {e} is not the least"); + } + } + assert_eq!(least_sum(f32::INFINITY, 4.0, true), f32::INFINITY); +} + +#[test] +fn valid_sources_are_the_wholly_copyable_patches() { + let (w, h, r) = (37, 29, 2); + let mut rng = Rng::new(9); + let px: Vec = (0..w * h) + .map(|_| match rng.next() % 23 { + 0 => Px::Hole, + 1 => Px::Void, + 2 => Px::Known, + _ => Px::Source, + }) + .collect(); + let valid = valid_sources(w, h, r, &px, &photocraft_raster::Interrupt::NONE).unwrap(); + let source: Vec = px.iter().map(|k| *k == Px::Source).collect(); + let ss = integral(w, h, &source); + let (ri, full) = (r as i32, ((2 * r + 1) * (2 * r + 1)) as u32); + for y in 0..h as i32 { + for x in 0..w as i32 { + let inside = x >= ri && y >= ri && x + ri < w as i32 && y + ri < h as i32; + let want = inside && window_count(&ss, w, h, x - ri, y - ri, x + ri + 1, y + ri + 1) == full; + assert_eq!(valid[y as usize * w + x as usize], want, "({x}, {y})"); + } + } + // Counting per row and block finds the centres in order. + let sources = Sources::new(&valid, w); + let list = sources.all(&valid, w); + assert!(list.len() > 10 && list.len() == sources.len()); + for (k, p) in list.iter().enumerate() { + assert_eq!(sources.nth(k, &valid, w), *p); + } + // And on a grid wider than a block, with empty blocks and rows. + let (w, h) = (300, 9); + let wide: Vec = (0..w * h).map(|i| (i % w) % 7 == 3 && (i % w) / 64 != 2 && i / w != 4).collect(); + let sources = Sources::new(&wide, w); + let list = sources.all(&wide, w); + for (k, p) in list.iter().enumerate() { + assert_eq!(sources.nth(k, &wide, w), *p); + } +} + +#[test] +fn full_patches_measure_as_clipped_ones() { + let (w, h, ch, r) = (46, 38, 4, 3); + let mut img = busy(w, h, ch, 4); + let hole = disc(w, h, 20.0, 18.0, 6.0); + let px = roles(w, h, &hole); + let none = photocraft_raster::Interrupt::NONE; + let hb = hole_bounds(w, h, &px).unwrap(); + let tb = hb.grow(r, w, h); + let valid = valid_sources(w, h, r, &px, &none).unwrap(); + let picks: Vec<(i32, i32)> = Sources::new(&valid, w).all(&valid, w).iter().step_by(37).copied().collect(); + assert!(picks.len() > 5); + for adapt in [Adapt::NONE, Adapt { gain: (0.8, 1.25), bias: 0.08 }] { + for keep in [false, true] { + let targets = targets_around(w, r, &px, hb, tb); + let mut s = Solver { + w, + h, + ch, + r: r as i32, + img: &mut img, + px: &px, + valid: valid.clone(), + targets, + hole_box: hb, + tbox: tb, + full: Vec::new(), + tmom: Vec::new(), + smom: Vec::new(), + adapt, + ctl: none, + }; + s.prepare(keep); + let nnf = vec![picks[0]; tb.area()]; + let mut cost = vec![f32::INFINITY; tb.area()]; + s.costs(&nnf, &mut cost).unwrap(); + let mut checked = 0; + for k in 0..tb.area() { + if !s.targets[k] || !s.full[k] { + continue; + } + let t = ((tb.x0 + k % tb.width()) as i32, (tb.y0 + k / tb.width()) as i32); + for &src in &picks { + if adapt.is_none() { + let exact = s.dist_clipped(t, src, f32::INFINITY); + assert_eq!(s.dist_full(t, src, f32::INFINITY).to_bits(), exact.to_bits()); + for cutoff in [exact * 0.5, exact, exact * 2.0] { + let (a, b) = (s.dist_full(t, src, cutoff), s.dist_clipped(t, src, cutoff)); + assert_eq!(a < cutoff, b < cutoff); + } + } else { + let (mut m1, mut m2) = ([[0.0f32; 5]; 4], [[0.0f32; 5]; 4]); + s.moments_full(k, t, src, &mut m1); + assert_eq!(s.moments(t, src, &mut m2), (2 * r + 1) * (2 * r + 1)); + assert_eq!(m1.map(|c| c.map(f32::to_bits)), m2.map(|c| c.map(f32::to_bits))); + assert_eq!(s.dist_adapted_full(k, t, src).to_bits(), s.dist_adapted(t, src).to_bits()); + } + checked += 1; + } + } + assert!(checked > 100, "{checked}"); + } + } +} + +#[test] +fn owned_completion_fills_in_place_or_gives_the_pixels_back() { + let (w, h, ch) = (64, 52, 3); + let img = busy(w, h, ch, 6); + let hole = disc(w, h, 30.0, 26.0, 8.0); + let px = roles(w, h, &hole); + let (p, none) = (CompleteParams::default(), photocraft_raster::Interrupt::NONE); + let borrowed = complete_masked(w, h, ch, &img, &px, &p, &none).unwrap().unwrap(); + let owned = complete_masked_owned(w, h, ch, img.clone(), &px, &p, &none).unwrap().unwrap(); + assert_eq!(bits(&owned), bits(&borrowed)); + // Nothing may be copied: no completion, and the pixels come back as they were. + let known: Vec = px.iter().map(|k| if *k == Px::Source { Px::Known } else { *k }).collect(); + assert!(complete_masked(w, h, ch, &img, &known, &p, &none).unwrap().is_none()); + let back = complete_masked_owned(w, h, ch, img.clone(), &known, &p, &none).unwrap().unwrap_err(); + assert_eq!(bits(&back), bits(&img)); + // Cancelled, it stops. + let yes = || true; + assert!(complete_masked_owned(w, h, ch, img, &px, &p, &photocraft_raster::Interrupt::cancel_only(&yes)).is_err()); +} + +#[test] +fn synthesis_fills_hole_with_plausible_values() { + let (w, h, ch) = (64, 64, 3); + let clean = texture(w, h); + let hole = disc(w, h, 32.0, 32.0, 6.0); + let out = synthesize(w, h, ch, &clean, &hole, 8, 3); + let err = hole_rmse(&out, &clean, &hole, ch); + assert!(err < 0.15, "{err}"); + assert!(out.iter().all(|v| v.is_finite())); +} diff --git a/crates/algo/src/lib.rs b/crates/algo/src/lib.rs index 9e8fa5301d..04acf276da 100644 --- a/crates/algo/src/lib.rs +++ b/crates/algo/src/lib.rs @@ -1375,15 +1375,6 @@ const RESULT_BUDGET: usize = 256 << 20; #[cfg(test)] mod tests; -#[cfg(test)] -mod tests_ext; - -#[cfg(test)] -mod tests_mosaic; - -#[cfg(test)] -mod tests_selection_mix; - /// The current upstream sampler through the identical source/selection/tile pipeline. #[cfg(test)] #[allow(clippy::too_many_arguments)] diff --git a/crates/algo/src/liquify.rs b/crates/algo/src/liquify.rs index 5d35f5791b..379500b25c 100644 --- a/crates/algo/src/liquify.rs +++ b/crates/algo/src/liquify.rs @@ -1035,537 +1035,4 @@ impl ProxyImage { } #[cfg(test)] -mod tests { - use super::*; - use photocraft_color::{ColorMode, PixelFormat, SampleType}; - - /// The segment walk before #937: every dab, whether or not it can reach the field. - fn full_walk(f: &mut LiquifyField, s: &LiquifyStroke, a: [f64; 3], b: [f64; 3]) -> Rect { - f.walk_segment(s, a, b, false) - } - - #[test] - fn a_segment_walks_only_the_dabs_that_can_reach_the_field() { - // #937: a segment to a far-off point walked one dab per spacing step along its whole - // length (~3e14 for 1e15 px). Skipping the dabs that can't reach a field node must leave - // every result bit-identical to the full walk. - use LiquifyTool::*; - let bounds = Rect::new(-7, 3, 89, 67); - let segments: [([f64; 3], [f64; 3]); 10] = [ - ([10.0, 20.0, 1.0], [70.0, 50.0, 0.5]), // inside - ([-900.0, 30.0, 1.0], [40.0, 31.0, 1.0]), // in from far left - ([40.0, 30.0, 1.0], [40.0, 4000.0, 0.2]), // out downwards - ([-500.0, -500.0, 1.0], [600.0, 600.0, 1.0]), // diagonal through - ([-300.0, -9.0, 1.0], [300.0, -9.0, 1.0]), // parallel, just above (the brush reaches) - ([-300.0, -400.0, 1.0], [300.0, -400.0, 1.0]), // parallel, far above (reaches nothing) - ([88.5, -50.0, 1.0], [88.5, 120.0, 1.0]), // vertical, along the right edge - ([200.0, 200.0, 1.0], [201.0, 900.0, 1.0]), // entirely outside - ([0.0, 0.0, 1.0], [0.25, 0.1, 1.0]), // shorter than one step - ([60.0, 40.0, 1.0], [-2000.0, 45.0, 1.0]), // continues the stroke before it, out left - ]; - for tool in [ForwardWarp, PushLeft, Reconstruct, Smooth, TwirlCw, TwirlCcw, Pucker, Bloat, Freeze, Thaw] { - for size in [6.0, 40.0] { - for (a, b) in segments { - let s = LiquifyStroke::new(tool, size); - let (mut fast, mut full) = (LiquifyField::new(bounds, 2.0), LiquifyField::new(bounds, 2.0)); - // Some displacement first, so Reconstruct and Smooth have something to undo. - for f in [&mut fast, &mut full] { - f.stroke_segment(&LiquifyStroke::new(ForwardWarp, 30.0), [20.0, 20.0, 1.0], [60.0, 40.0, 1.0]); - } - let dirty = fast.stroke_segment(&s, a, b); - assert_eq!(dirty, full_walk(&mut full, &s, a, b), "{tool:?} {size} {a:?} {b:?}"); - assert!(fast.d == full.d && fast.freeze == full.freeze, "{tool:?} {size} {a:?} {b:?}"); - } - } - } - } - - /// The same path sampled by `parts` pointer events per corner-to-corner leg, unevenly. - fn sampled(path: &[[f64; 3]], parts: usize) -> Vec> { - let mut out = vec![path[0].to_vec()]; - for w in path.windows(2) { - let (a, b) = (w[0], w[1]); - // Uneven steps, as a real pointer gives: t grows quadratically. - for k in 1..=parts { - let t = (k * k) as f64 / (parts * parts) as f64; - out.push((0..3).map(|i| a[i] + (b[i] - a[i]) * t).collect()); - } - } - out - } - - /// #2606: dabs restarted at every pointer event, so a fast mouse (few far-apart events) and a - /// slow one (many close ones) warped the same path differently. Spacing now runs on along the - /// whole stroke: any sampling of a path gives the same field. - #[test] - fn the_result_does_not_depend_on_how_finely_the_path_was_sampled() { - use LiquifyTool::*; - let path = [[20.0, 20.0, 1.0], [62.0, 26.0, 0.6], [70.0, 50.0, 0.9], [28.0, 55.0, 1.0], [30.0, 30.0, 1.0]]; - for tool in [ForwardWarp, PushLeft, TwirlCw, Bloat, Reconstruct, Smooth, Freeze] { - for size in [12.0, 40.0] { - let field = |parts: usize| { - let mut warp = LiquifyStroke::new(ForwardWarp, 30.0); - warp.points = vec![vec![30.0, 30.0], vec![50.0, 40.0]]; - let mut s = LiquifyStroke::new(tool, size); - s.points = sampled(&path, parts); - // Some displacement first, so Reconstruct and Smooth have something to change. - LiquifyField::from_strokes(bounds(), 2.0, &[warp, s]) - }; - let coarse = field(1); - for parts in [3, 17, 60] { - let fine = field(parts); - let dd = coarse.d.iter().zip(&fine.d).map(|(p, q)| (p[0] - q[0]).abs().max((p[1] - q[1]).abs())).fold(0.0f32, f32::max); - let df = coarse.freeze.iter().zip(&fine.freeze).map(|(p, q)| (p - q).abs()).fold(0.0f32, f32::max); - assert!(dd < 1e-3 && df < 1e-4, "{tool:?} {size}px, {parts} events per leg: field differs by {dd} px, mask by {df}"); - } - } - } - } - - /// A long drag whose events land exactly on dab positions, along a diagonal: rounding must not - /// add or drop the dab at a segment's end, or the deep displacement a long Forward Warp builds - /// up differs by a whole dab between a slow and a fast pointer. - #[test] - fn a_long_diagonal_drag_gives_one_field_at_any_event_spacing() { - let field = |step: f64| { - let mut s = LiquifyStroke::new(LiquifyTool::ForwardWarp, 40.0); - s.points = (0..=(300.0 / step) as usize).map(|k| vec![40.0 + k as f64 * step * 0.6, 20.0 + k as f64 * step * 0.8]).collect(); - LiquifyField::from_strokes(Rect::new(0, 0, 320, 300), 2.0, &[s]) - }; - let (slow, fast) = (field(2.0), field(60.0)); - let dd = slow.d.iter().zip(&fast.d).map(|(p, q)| (p[0] - q[0]).abs().max((p[1] - q[1]).abs())).fold(0.0f32, f32::max); - assert!(slow.max_displacement() > 50.0, "the drag builds up a deep displacement"); - assert!(dd < 1e-3, "slow and fast pointer fields differ by {dd} px"); - } - - #[test] - fn a_huge_canvas_gets_a_coarser_field_not_a_huge_one() { - // 400000² px at 2 px per node is 4·10¹⁰ nodes. - let f = LiquifyField::new(Rect::new(0, 0, 400_000, 400_000), 2.0); - assert!(f.w * f.h <= MAX_FIELD_NODES && f.d.len() == f.w * f.h && f.freeze.len() == f.d.len()); - assert!(f.cell > 64.0); - assert_eq!(LiquifyField::new(Rect::new(0, 0, 100, 100), 2.0).cell, 2.0); - } - - #[test] - fn a_stroke_interrupted_by_a_jump_restarts_its_spacing() { - // A segment that does not start where the last one ended begins a new run of dabs there. - let s = LiquifyStroke::new(LiquifyTool::ForwardWarp, 20.0); - let mut f = LiquifyField::new(bounds(), 2.0); - f.stroke_begin(&s, [10.0, 10.0, 1.0]); - f.stroke_segment(&s, [10.0, 10.0, 1.0], [10.3, 10.0, 1.0]); - let mut g = LiquifyField::new(bounds(), 2.0); - f.stroke_segment(&s, [40.0, 30.0, 1.0], [50.0, 30.0, 1.0]); - g.stroke_begin(&s, [40.0, 30.0, 1.0]); - g.stroke_segment(&s, [40.0, 30.0, 1.0], [50.0, 30.0, 1.0]); - assert_eq!(f, g); - // Hostile points: nothing panics and the next segment starts afresh. - f.stroke_segment(&s, [f64::NAN, 3.0, 1.0], [4.0, f64::INFINITY, 1.0]); - f.stroke_segment(&s, [4.0, 3.0, f64::NAN], [9.0, 3.0, 1.0]); - } - - #[test] - fn a_segment_to_a_far_off_point_returns() { - // The issue's request: about 3.3e14 steps before the fix. Also a segment whose length - // overflows f64. - let mut f = LiquifyField::new(Rect::new(0, 0, 24, 16), 2.0); - let s = LiquifyStroke::new(LiquifyTool::ForwardWarp, 30.0); - let dirty = f.stroke_segment(&s, [0.0, 0.0, 1.0], [1e15, 0.0, 1.0]); - assert!(!dirty.is_empty() && dirty.x1 <= 64, "{dirty:?}"); - f.stroke_segment(&s, [-1e308, 5.0, 1.0], [1e308, 5.0, 1.0]); - f.stroke_segment(&LiquifyStroke::new(LiquifyTool::Bloat, 30.0), [5.0, -1e15, 1.0], [5.0, 1e15, 1.0]); - } - - fn sample(st: SampleType) -> Surface { - let mut s = Surface::new(PixelFormat::new(ColorMode::Rgb, st, true)); - for y in 0..64 { - for x in 0..96 { - let v = ((x / 4 + y / 4) % 2) as f32; - s.write_pixel(x, y, &[v, (x as f32) / 96.0, (y as f32) / 64.0, 1.0]); - } - } - s - } - - fn bounds() -> Rect { - Rect::new(0, 0, 96, 64) - } - - fn worst(a: &Surface, b: &Surface, r: Rect) -> f32 { - a.read_region(r).iter().zip(b.read_region(r)).map(|(x, y)| (x - y).abs()).fold(0.0, f32::max) - } - - fn lasso(points: &[[f64; 2]], amount: Option) -> LiquifyStroke { - let mut s = LiquifyStroke::new(LiquifyTool::LassoMask, 1.0); - s.points = points.iter().map(|p| p.to_vec()).collect(); - s.amount = amount; - s - } - - /// Reference even-odd test (ray casting), to check the scanline fill against. - fn inside(p: [f64; 2], poly: &[[f64; 2]]) -> bool { - let mut inside = false; - let mut j = poly.len() - 1; - for (i, a) in poly.iter().enumerate() { - let b = poly[j]; - if (a[1] > p[1]) != (b[1] > p[1]) && p[0] < (b[0] - a[0]) * (p[1] - a[1]) / (b[1] - a[1]) + a[0] { - inside = !inside; - } - j = i; - } - inside - } - - #[test] - fn lasso_freezes_exactly_the_nodes_inside_a_concave_polygon() { - // A concave "C" with a notch, at a non-integer cell size. - let poly = [[10.0, 8.0], [70.0, 8.0], [70.0, 20.0], [30.0, 22.5], [33.0, 40.0], [80.0, 41.0], [60.0, 58.0], [9.0, 55.0]]; - for cell in [1.0, 2.0, 3.5] { - let mut f = LiquifyField::new(bounds(), cell); - let dirty = f.apply_stroke(&lasso(&poly, None)); - assert_eq!(dirty, Rect::new(9, 8, 80, 58)); - for j in 0..f.h { - for i in 0..f.w { - let want = if inside(f.node_pos(i, j), &poly) { 1.0 } else { 0.0 }; - assert_eq!(f.freeze[j * f.w + i], want, "cell {cell}: node ({i}, {j}) at {:?}", f.node_pos(i, j)); - } - } - assert!(f.freeze.contains(&1.0)); - // Strokes replay to the same field (undo rebuilds from the list). - assert_eq!(LiquifyField::from_strokes(bounds(), cell, &[lasso(&poly, None)]), f); - } - } - - #[test] - fn lasso_thaws_with_amount_zero() { - let mut f = LiquifyField::new(bounds(), 2.0); - f.apply_stroke(&LiquifyStroke::new(LiquifyTool::FreezeAll, 1.0)); - assert!(f.freeze.iter().all(|&v| v == 1.0)); - let square = [[20.0, 20.0], [40.0, 20.0], [40.0, 40.0], [20.0, 40.0]]; - f.apply_stroke(&lasso(&square, Some(0.0))); - assert_eq!(f.freeze_at(30.0, 30.0), 0.0, "thawed inside"); - assert_eq!(f.freeze_at(5.0, 5.0), 1.0, "still frozen outside"); - } - - #[test] - fn lasso_ignores_degenerate_and_hostile_polygons() { - let empty = LiquifyField::new(bounds(), 2.0); - let cases: [&[[f64; 2]]; 6] = [ - &[], - &[[10.0, 10.0], [50.0, 50.0]], - &[[f64::NAN, 10.0], [50.0, f64::INFINITY], [20.0, 30.0]], - // Entirely outside the canvas, on every side. - &[[-50.0, -50.0], [-10.0, -50.0], [-10.0, -10.0]], - &[[200.0, 10.0], [300.0, 10.0], [250.0, 50.0]], - &[[10.0, 1e12], [50.0, 1e12], [30.0, 2e12]], - ]; - for poly in cases { - let mut f = empty.clone(); - assert_eq!(f.apply_stroke(&lasso(poly, None)), Rect::EMPTY, "{poly:?}"); - assert_eq!(f, empty, "{poly:?}"); - } - // Huge coordinates around the canvas clamp to it instead of overflowing. - let mut f = empty.clone(); - f.apply_stroke(&lasso(&[[-1e15, -1e15], [1e15, -1e15], [1e15, 1e15], [-1e15, 1e15]], None)); - assert!(f.freeze.iter().all(|&v| v == 1.0)); - // A NaN point among good ones is skipped. - let mut f = empty.clone(); - f.apply_stroke(&lasso(&[[10.0, 10.0], [f64::NAN, 0.0], [50.0, 10.0], [50.0, 50.0], [10.0, 50.0]], None)); - assert_eq!(f.freeze_at(30.0, 30.0), 1.0); - } - - #[test] - fn the_brush_fades_to_nothing_at_its_rim_at_every_density() { - for density in [0.0, 0.25, 0.5, 0.75, 1.0, f64::NAN, -3.0, 7.0] { - assert_eq!(falloff(0.0, density), 1.0, "full strength at the centre ({density})"); - assert_eq!(falloff(1.0, density), 0.0, "nothing at the rim ({density})"); - // Flat at the rim: the last 2 % of the radius moves at most a couple of percent. - assert!(falloff(0.98f64.powi(2), density) < 0.02, "{density}: {}", falloff(0.98f64.powi(2), density)); - let mut prev = 1.0; - for k in 1..=100 { - let v = falloff(k as f64 / 100.0, density); - assert!(v <= prev && v >= 0.0, "{density}: not falling at t² = {k}%"); - prev = v; - } - } - // Density widens the strong core: more strength at every radius, as in Photoshop. - for k in 1..100 { - let t2 = k as f64 / 100.0; - assert!(falloff(t2, 1.0) >= falloff(t2, 0.5) && falloff(t2, 0.5) >= falloff(t2, 0.0), "t² = {t2}"); - } - assert!(falloff(0.5, 1.0) > 0.5 && falloff(0.5, 0.0) < 0.2); - } - - /// #2606: the dab's strength used to stop at 1 - Density at its rim, so a Forward Warp moved - /// everything just inside the brush and nothing just outside, tearing the image along every - /// dab's circle (a hard-edged block at Density 0, half strength at the default 50). - #[test] - fn forward_warp_leaves_the_brush_rim_in_place() { - // A drag of one dab spacing (a twentieth of the radius): one dab, centred where it started. - let (r, drag) = (20.0, 1.0); - for density in [0.0, 50.0, 100.0] { - let mut s = LiquifyStroke::new(LiquifyTool::ForwardWarp, 2.0 * r); - s.density = density; - s.points = vec![vec![48.0, 32.0], vec![48.0 + drag, 32.0]]; - let f = LiquifyField::from_strokes(bounds(), 1.0, &[s]); - let mut rim = 0; - for j in 0..f.h { - for i in 0..f.w { - let p = f.node_pos(i, j); - let t = (p[0] - 48.0).hypot(p[1] - 32.0) / r; - if (0.97..1.0).contains(&t) { - let d = f.d[j * f.w + i]; - assert!(f64::from(d[0].hypot(d[1])) < 0.03 * drag, "density {density}: a node at {t:.3} r moved {d:?}"); - rim += 1; - } - } - } - assert!(rim > 20, "{rim} rim nodes"); - assert!(f.sample(48.0, 32.0)[0] < -0.9 * drag, "density {density}: the centre follows the brush"); - } - } - - #[test] - fn a_wide_integer_translation_keeps_channels_and_tile_edges_at_every_format() { - let b = Rect::new(13, -1, 13 + 70 * 256, 1); - let w = b.width() as usize; - for mode in [ColorMode::Grayscale, ColorMode::Rgb, ColorMode::Cmyk] { - for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { - let format = PixelFormat::new(mode, depth, true); - let n = format.channels(); - let mut data = Vec::new(); - for i in 0..w * 2 { - let alpha = if i % 13 == 0 { 0.0 } else { 0.5 }; - for c in 0..mode.color_channels() { - data.push(if alpha == 0.0 { 0.0 } else { ((i * 19 + c * 43) % 251 + 2) as f32 / 255.0 }); - } - data.push(alpha); - } - let mut source = Surface::new(format); - source.write_region(b, &data); - source.write_pixel(b.x0 - 1, b.y0 - 1, &vec![0.75; n]); - let before = source.read_region(b); - let mut field = LiquifyField::new(b, 2.5); - field.d.fill([-1.0, 0.0]); - let output = apply_liquify(&source, &field); - let after = output.read_region(b); - let tolerance = if depth == SampleType::F32 { 4.0 * f32::EPSILON } else { 0.0 }; - for (original, moved) in before.chunks_exact(w * n).zip(after.chunks_exact(w * n)) { - for (x, pixel) in moved.chunks_exact(n).enumerate() { - let offset = x.saturating_sub(1) * n; - for (actual, expected) in pixel.iter().zip(&original[offset..offset + n]) { - assert!((actual - expected).abs() <= tolerance, "{mode:?}/{depth:?} at column {x}"); - } - } - } - assert_eq!(output.pixel(b.x0 - 1, b.y0 - 1), source.pixel(b.x0 - 1, b.y0 - 1)); - } - } - } - - #[test] - fn no_strokes_is_identity_at_every_depth() { - for st in [SampleType::U8, SampleType::U16, SampleType::F32] { - let s = sample(st); - let f = LiquifyField::new(bounds(), 2.0); - assert_eq!(apply_liquify(&s, &f), s); - // A field with exactly-zero strokes (zero pressure) is still identity. - let mut st0 = LiquifyStroke::new(LiquifyTool::ForwardWarp, 30.0); - st0.pressure = 0.0; - st0.points = vec![vec![40.0, 30.0], vec![60.0, 30.0]]; - let f = LiquifyField::from_strokes(bounds(), 2.0, &[st0]); - assert!(f.is_identity()); - } - } - - #[test] - fn full_resolution_preview_matches_the_unit_scale_proxy_and_partial_updates() { - let canvas = Rect::new(0, 0, 96, 64); - for sample_type in [SampleType::U8, SampleType::U16, SampleType::F32] { - let source = sample(sample_type); - let mut stroke = LiquifyStroke::new(LiquifyTool::ForwardWarp, 32.0); - stroke.points = vec![vec![38.0, 30.0, 1.0], vec![52.0, 34.0, 0.8]]; - let mut field = LiquifyField::from_strokes(canvas, 2.0, &[stroke]); - - let proxy = ProxyImage::new(&source, canvas, 96); - assert_eq!(proxy.scale, 1.0); - let mut want = vec![[0; 4]; proxy.w * proxy.h]; - proxy.render(&field, [0, 0, proxy.w, proxy.h], &mut want); - - let mut got = vec![[0; 4]; proxy.w * proxy.h]; - let mut scratch = Vec::new(); - assert!(ProxyImage::render_full_resolution(&source, &field, canvas, canvas, &mut got, &mut scratch)); - assert_eq!(got, want, "full-resolution render at {sample_type:?}"); - - let mut more = LiquifyStroke::new(LiquifyTool::Bloat, 16.0); - more.points = vec![vec![43.0, 32.0, 1.0]]; - let dirty = field.apply_stroke(&more); - proxy.render(&field, proxy.proxy_rect(dirty), &mut want); - assert!(ProxyImage::render_full_resolution(&source, &field, canvas, dirty, &mut got, &mut scratch)); - assert_eq!(got, want, "partial update at {sample_type:?}"); - } - } - - #[test] - fn forward_warp_displaces_along_the_stroke_and_reconstruct_restores() { - let mut s = LiquifyStroke::new(LiquifyTool::ForwardWarp, 40.0); - s.points = vec![vec![40.0, 32.0], vec![52.0, 32.0]]; - let mut f = LiquifyField::from_strokes(bounds(), 2.0, &[s]); - // Content moved right: the output at the end point samples from the left. - let d = f.sample(52.0, 32.0); - assert!(d[0] < -4.0 && d[1].abs() < 0.5, "{d:?}"); - // A pixel-level check: a marker column follows the stroke. - let mut img = Surface::new(PixelFormat::new(ColorMode::Grayscale, SampleType::F32, true)); - img.fill_rect(bounds(), &[0.0, 1.0]); - img.fill_rect(Rect::new(40, 28, 42, 36), &[1.0, 1.0]); - let out = apply_liquify(&img, &f); - let brightest = (30..70).max_by(|a, b| out.pixel(*a, 32)[0].total_cmp(&out.pixel(*b, 32)[0])).unwrap(); - assert!(brightest > 44, "marker moved right: {brightest}"); - // Reconstruct All restores the original exactly. - let mut rec = LiquifyStroke::new(LiquifyTool::ReconstructAll, 10.0); - rec.amount = Some(100.0); - f.apply_stroke(&rec); - assert!(f.is_identity()); - assert_eq!(apply_liquify(&img, &f), img); - } - - #[test] - fn reconstruct_brush_reduces_the_field_and_freeze_protects() { - let mut s = LiquifyStroke::new(LiquifyTool::ForwardWarp, 40.0); - s.points = vec![vec![30.0, 32.0], vec![45.0, 32.0]]; - let mut f = LiquifyField::from_strokes(bounds(), 2.0, std::slice::from_ref(&s)); - let before = f.max_displacement(); - let mut r = LiquifyStroke::new(LiquifyTool::Reconstruct, 80.0); - r.points = vec![vec![40.0, 32.0]; 30]; - f.apply_stroke(&r); - assert!(f.max_displacement() < before * 0.2, "{} vs {before}", f.max_displacement()); - // Frozen area doesn't move. - let mut fr = LiquifyStroke::new(LiquifyTool::Freeze, 60.0); - fr.density = 100.0; - fr.points = vec![vec![40.0, 32.0]]; - let mut g = LiquifyField::new(bounds(), 2.0); - g.apply_stroke(&fr); - assert!(g.freeze_at(40.0, 32.0) > 0.99); - g.apply_stroke(&s); - assert!(g.sample(40.0, 32.0)[0].abs() < 1e-3); - // Thaw unfreezes. - let mut th = fr.clone(); - th.tool = LiquifyTool::Thaw; - g.apply_stroke(&th); - assert!(g.freeze_at(40.0, 32.0) < 0.01); - // Mask All / Invert / None. - g.apply_stroke(&LiquifyStroke::new(LiquifyTool::FreezeAll, 1.0)); - assert!(g.freeze.iter().all(|f| *f == 1.0)); - g.apply_stroke(&LiquifyStroke::new(LiquifyTool::InvertFreeze, 1.0)); - assert!(g.freeze.iter().all(|f| *f == 0.0)); - g.apply_stroke(&fr); - g.apply_stroke(&LiquifyStroke::new(LiquifyTool::InvertFreeze, 1.0)); - assert!(g.freeze_at(40.0, 32.0) < 0.01 && g.freeze_at(5.0, 5.0) > 0.99); - g.apply_stroke(&LiquifyStroke::new(LiquifyTool::ThawAll, 1.0)); - assert!(g.freeze.iter().all(|f| *f == 0.0)); - } - - #[test] - fn fully_frozen_pixels_keep_their_mapping_when_an_adjacent_area_is_warped() { - let bounds = bounds(); - let mut src = Surface::new(PixelFormat::new(ColorMode::Rgb, SampleType::F32, true)); - for y in 0..bounds.height() { - for x in 0..bounds.width() { - src.write_pixel(x as i32, y as i32, &[x as f32 / bounds.width() as f32, y as f32 / bounds.height() as f32, 0.0, 1.0]); - } - } - - let mut mask_only = LiquifyField::new(bounds, 2.0); - mask_only.apply_stroke(&lasso(&[[0.0, 0.0], [40.0, 0.0], [40.0, 64.0], [0.0, 64.0]], None)); - assert_eq!(apply_liquify(&src, &mask_only), src); - - let mut field = LiquifyField::new(bounds, 2.0); - let mut first_warp = LiquifyStroke::new(LiquifyTool::ForwardWarp, 40.0); - first_warp.points = vec![vec![22.0, 32.0], vec![34.0, 32.0]]; - field.apply_stroke(&first_warp); - - field.apply_stroke(&lasso(&[[0.0, 0.0], [40.0, 0.0], [40.0, 64.0], [0.0, 64.0]], None)); - let frozen_pixel = (37, 32); - assert!(field.freeze_at(f64::from(frozen_pixel.0) + 0.5, f64::from(frozen_pixel.1) + 0.5) > 0.999); - let before = apply_liquify(&src, &field).pixel(frozen_pixel.0, frozen_pixel.1); - assert_ne!(before, src.pixel(frozen_pixel.0, frozen_pixel.1), "freezing must retain the earlier warp"); - let neighbor_before = apply_liquify(&src, &field).pixel(43, 32); - - let mut adjacent_warp = LiquifyStroke::new(LiquifyTool::ForwardWarp, 24.0); - adjacent_warp.points = vec![vec![44.0, 32.0], vec![52.0, 32.0]]; - field.apply_stroke(&adjacent_warp); - - let after = apply_liquify(&src, &field).pixel(frozen_pixel.0, frozen_pixel.1); - let neighbor_after = apply_liquify(&src, &field).pixel(43, 32); - assert_eq!(before, after, "a fully frozen pixel must keep its pre-neighbor-warp mapping"); - assert_ne!(neighbor_before, neighbor_after, "an adjacent unfrozen pixel must still move"); - } - - #[test] - fn twirl_pucker_bloat_and_push_left_have_the_right_sense() { - let at = |tool: LiquifyTool, pts: Vec>| { - let mut s = LiquifyStroke::new(tool, 40.0); - s.points = pts; - LiquifyField::from_strokes(bounds(), 2.0, &[s]) - }; - let c = vec![vec![48.0, 32.0]; 10]; - // Pucker pulls content in: the output samples outward (d points away from the centre). - let f = at(LiquifyTool::Pucker, c.clone()); - assert!(f.sample(58.0, 32.0)[0] > 0.1); - let f = at(LiquifyTool::Bloat, c.clone()); - assert!(f.sample(58.0, 32.0)[0] < -0.1); - // Twirl clockwise (y down): content right of centre moves down, so it samples from above. - let f = at(LiquifyTool::TwirlCw, c.clone()); - assert!(f.sample(58.0, 32.0)[1] < -0.1, "{:?}", f.sample(58.0, 32.0)); - let f = at(LiquifyTool::TwirlCcw, c); - assert!(f.sample(58.0, 32.0)[1] > 0.1); - // Push Left while dragging up moves content left (samples from the right). - let f = at(LiquifyTool::PushLeft, vec![vec![48.0, 44.0], vec![48.0, 20.0]]); - assert!(f.sample(48.0, 32.0)[0] > 0.5, "{:?}", f.sample(48.0, 32.0)); - // Smooth reduces sharp field differences. - let mut s = LiquifyStroke::new(LiquifyTool::ForwardWarp, 12.0); - s.points = vec![vec![40.0, 32.0], vec![50.0, 32.0]]; - let mut g = LiquifyField::from_strokes(bounds(), 2.0, &[s]); - let m0 = g.max_displacement(); - let mut sm = LiquifyStroke::new(LiquifyTool::Smooth, 60.0); - sm.points = vec![vec![45.0, 32.0]; 20]; - g.apply_stroke(&sm); - assert!(g.max_displacement() < m0); - } - - #[test] - fn replay_is_deterministic_and_depths_agree() { - let mut s = LiquifyStroke::new(LiquifyTool::TwirlCw, 50.0); - s.points = vec![vec![48.0, 32.0, 0.5], vec![50.0, 33.0, 1.0], vec![52.0, 34.0]]; - let a = LiquifyField::from_strokes(bounds(), 2.0, std::slice::from_ref(&s)); - let b = LiquifyField::from_strokes(bounds(), 2.0, std::slice::from_ref(&s)); - assert_eq!(a, b); - let r8 = apply_liquify(&sample(SampleType::U8), &a); - let r32 = apply_liquify(&sample(SampleType::F32), &a); - assert!(worst(&r8, &r32, bounds()) < 2.0 / 255.0 + 1e-4); - } - - #[test] - fn proxy_matches_the_full_render_roughly() { - let src = sample(SampleType::U8); - let mut s = LiquifyStroke::new(LiquifyTool::Bloat, 40.0); - s.points = vec![vec![48.0, 32.0]; 8]; - let f = LiquifyField::from_strokes(bounds(), 2.0, &[s]); - let p = ProxyImage::new(&src, bounds(), 96); - assert_eq!((p.w, p.h, p.scale), (96, 64, 1.0)); - let mut out = vec![[0u8; 4]; p.w * p.h]; - p.render(&f, [0, 0, p.w, p.h], &mut out); - let full = apply_liquify(&src, &f); - let mut bad = 0; - for y in 0..64 { - for x in 0..96 { - let q = full.pixel(x, y); - let o = out[y as usize * 96 + x as usize]; - if (f32::from(o[1]) / 255.0 - q[1]).abs() > 0.1 { - bad += 1; - } - } - } - assert!(bad < 96 * 64 / 50, "{bad}"); - } -} +mod tests; diff --git a/crates/algo/src/liquify/tests.rs b/crates/algo/src/liquify/tests.rs new file mode 100644 index 0000000000..1cc360b2c3 --- /dev/null +++ b/crates/algo/src/liquify/tests.rs @@ -0,0 +1,532 @@ +use super::*; +use photocraft_color::{ColorMode, PixelFormat, SampleType}; + +/// The segment walk before #937: every dab, whether or not it can reach the field. +fn full_walk(f: &mut LiquifyField, s: &LiquifyStroke, a: [f64; 3], b: [f64; 3]) -> Rect { + f.walk_segment(s, a, b, false) +} + +#[test] +fn a_segment_walks_only_the_dabs_that_can_reach_the_field() { + // #937: a segment to a far-off point walked one dab per spacing step along its whole + // length (~3e14 for 1e15 px). Skipping the dabs that can't reach a field node must leave + // every result bit-identical to the full walk. + use LiquifyTool::*; + let bounds = Rect::new(-7, 3, 89, 67); + let segments: [([f64; 3], [f64; 3]); 10] = [ + ([10.0, 20.0, 1.0], [70.0, 50.0, 0.5]), // inside + ([-900.0, 30.0, 1.0], [40.0, 31.0, 1.0]), // in from far left + ([40.0, 30.0, 1.0], [40.0, 4000.0, 0.2]), // out downwards + ([-500.0, -500.0, 1.0], [600.0, 600.0, 1.0]), // diagonal through + ([-300.0, -9.0, 1.0], [300.0, -9.0, 1.0]), // parallel, just above (the brush reaches) + ([-300.0, -400.0, 1.0], [300.0, -400.0, 1.0]), // parallel, far above (reaches nothing) + ([88.5, -50.0, 1.0], [88.5, 120.0, 1.0]), // vertical, along the right edge + ([200.0, 200.0, 1.0], [201.0, 900.0, 1.0]), // entirely outside + ([0.0, 0.0, 1.0], [0.25, 0.1, 1.0]), // shorter than one step + ([60.0, 40.0, 1.0], [-2000.0, 45.0, 1.0]), // continues the stroke before it, out left + ]; + for tool in [ForwardWarp, PushLeft, Reconstruct, Smooth, TwirlCw, TwirlCcw, Pucker, Bloat, Freeze, Thaw] { + for size in [6.0, 40.0] { + for (a, b) in segments { + let s = LiquifyStroke::new(tool, size); + let (mut fast, mut full) = (LiquifyField::new(bounds, 2.0), LiquifyField::new(bounds, 2.0)); + // Some displacement first, so Reconstruct and Smooth have something to undo. + for f in [&mut fast, &mut full] { + f.stroke_segment(&LiquifyStroke::new(ForwardWarp, 30.0), [20.0, 20.0, 1.0], [60.0, 40.0, 1.0]); + } + let dirty = fast.stroke_segment(&s, a, b); + assert_eq!(dirty, full_walk(&mut full, &s, a, b), "{tool:?} {size} {a:?} {b:?}"); + assert!(fast.d == full.d && fast.freeze == full.freeze, "{tool:?} {size} {a:?} {b:?}"); + } + } + } +} + +/// The same path sampled by `parts` pointer events per corner-to-corner leg, unevenly. +fn sampled(path: &[[f64; 3]], parts: usize) -> Vec> { + let mut out = vec![path[0].to_vec()]; + for w in path.windows(2) { + let (a, b) = (w[0], w[1]); + // Uneven steps, as a real pointer gives: t grows quadratically. + for k in 1..=parts { + let t = (k * k) as f64 / (parts * parts) as f64; + out.push((0..3).map(|i| a[i] + (b[i] - a[i]) * t).collect()); + } + } + out +} + +/// #2606: dabs restarted at every pointer event, so a fast mouse (few far-apart events) and a +/// slow one (many close ones) warped the same path differently. Spacing now runs on along the +/// whole stroke: any sampling of a path gives the same field. +#[test] +fn the_result_does_not_depend_on_how_finely_the_path_was_sampled() { + use LiquifyTool::*; + let path = [[20.0, 20.0, 1.0], [62.0, 26.0, 0.6], [70.0, 50.0, 0.9], [28.0, 55.0, 1.0], [30.0, 30.0, 1.0]]; + for tool in [ForwardWarp, PushLeft, TwirlCw, Bloat, Reconstruct, Smooth, Freeze] { + for size in [12.0, 40.0] { + let field = |parts: usize| { + let mut warp = LiquifyStroke::new(ForwardWarp, 30.0); + warp.points = vec![vec![30.0, 30.0], vec![50.0, 40.0]]; + let mut s = LiquifyStroke::new(tool, size); + s.points = sampled(&path, parts); + // Some displacement first, so Reconstruct and Smooth have something to change. + LiquifyField::from_strokes(bounds(), 2.0, &[warp, s]) + }; + let coarse = field(1); + for parts in [3, 17, 60] { + let fine = field(parts); + let dd = coarse.d.iter().zip(&fine.d).map(|(p, q)| (p[0] - q[0]).abs().max((p[1] - q[1]).abs())).fold(0.0f32, f32::max); + let df = coarse.freeze.iter().zip(&fine.freeze).map(|(p, q)| (p - q).abs()).fold(0.0f32, f32::max); + assert!(dd < 1e-3 && df < 1e-4, "{tool:?} {size}px, {parts} events per leg: field differs by {dd} px, mask by {df}"); + } + } + } +} + +/// A long drag whose events land exactly on dab positions, along a diagonal: rounding must not +/// add or drop the dab at a segment's end, or the deep displacement a long Forward Warp builds +/// up differs by a whole dab between a slow and a fast pointer. +#[test] +fn a_long_diagonal_drag_gives_one_field_at_any_event_spacing() { + let field = |step: f64| { + let mut s = LiquifyStroke::new(LiquifyTool::ForwardWarp, 40.0); + s.points = (0..=(300.0 / step) as usize).map(|k| vec![40.0 + k as f64 * step * 0.6, 20.0 + k as f64 * step * 0.8]).collect(); + LiquifyField::from_strokes(Rect::new(0, 0, 320, 300), 2.0, &[s]) + }; + let (slow, fast) = (field(2.0), field(60.0)); + let dd = slow.d.iter().zip(&fast.d).map(|(p, q)| (p[0] - q[0]).abs().max((p[1] - q[1]).abs())).fold(0.0f32, f32::max); + assert!(slow.max_displacement() > 50.0, "the drag builds up a deep displacement"); + assert!(dd < 1e-3, "slow and fast pointer fields differ by {dd} px"); +} + +#[test] +fn a_huge_canvas_gets_a_coarser_field_not_a_huge_one() { + // 400000² px at 2 px per node is 4·10¹⁰ nodes. + let f = LiquifyField::new(Rect::new(0, 0, 400_000, 400_000), 2.0); + assert!(f.w * f.h <= MAX_FIELD_NODES && f.d.len() == f.w * f.h && f.freeze.len() == f.d.len()); + assert!(f.cell > 64.0); + assert_eq!(LiquifyField::new(Rect::new(0, 0, 100, 100), 2.0).cell, 2.0); +} + +#[test] +fn a_stroke_interrupted_by_a_jump_restarts_its_spacing() { + // A segment that does not start where the last one ended begins a new run of dabs there. + let s = LiquifyStroke::new(LiquifyTool::ForwardWarp, 20.0); + let mut f = LiquifyField::new(bounds(), 2.0); + f.stroke_begin(&s, [10.0, 10.0, 1.0]); + f.stroke_segment(&s, [10.0, 10.0, 1.0], [10.3, 10.0, 1.0]); + let mut g = LiquifyField::new(bounds(), 2.0); + f.stroke_segment(&s, [40.0, 30.0, 1.0], [50.0, 30.0, 1.0]); + g.stroke_begin(&s, [40.0, 30.0, 1.0]); + g.stroke_segment(&s, [40.0, 30.0, 1.0], [50.0, 30.0, 1.0]); + assert_eq!(f, g); + // Hostile points: nothing panics and the next segment starts afresh. + f.stroke_segment(&s, [f64::NAN, 3.0, 1.0], [4.0, f64::INFINITY, 1.0]); + f.stroke_segment(&s, [4.0, 3.0, f64::NAN], [9.0, 3.0, 1.0]); +} + +#[test] +fn a_segment_to_a_far_off_point_returns() { + // The issue's request: about 3.3e14 steps before the fix. Also a segment whose length + // overflows f64. + let mut f = LiquifyField::new(Rect::new(0, 0, 24, 16), 2.0); + let s = LiquifyStroke::new(LiquifyTool::ForwardWarp, 30.0); + let dirty = f.stroke_segment(&s, [0.0, 0.0, 1.0], [1e15, 0.0, 1.0]); + assert!(!dirty.is_empty() && dirty.x1 <= 64, "{dirty:?}"); + f.stroke_segment(&s, [-1e308, 5.0, 1.0], [1e308, 5.0, 1.0]); + f.stroke_segment(&LiquifyStroke::new(LiquifyTool::Bloat, 30.0), [5.0, -1e15, 1.0], [5.0, 1e15, 1.0]); +} + +fn sample(st: SampleType) -> Surface { + let mut s = Surface::new(PixelFormat::new(ColorMode::Rgb, st, true)); + for y in 0..64 { + for x in 0..96 { + let v = ((x / 4 + y / 4) % 2) as f32; + s.write_pixel(x, y, &[v, (x as f32) / 96.0, (y as f32) / 64.0, 1.0]); + } + } + s +} + +fn bounds() -> Rect { + Rect::new(0, 0, 96, 64) +} + +fn worst(a: &Surface, b: &Surface, r: Rect) -> f32 { + a.read_region(r).iter().zip(b.read_region(r)).map(|(x, y)| (x - y).abs()).fold(0.0, f32::max) +} + +fn lasso(points: &[[f64; 2]], amount: Option) -> LiquifyStroke { + let mut s = LiquifyStroke::new(LiquifyTool::LassoMask, 1.0); + s.points = points.iter().map(|p| p.to_vec()).collect(); + s.amount = amount; + s +} + +/// Reference even-odd test (ray casting), to check the scanline fill against. +fn inside(p: [f64; 2], poly: &[[f64; 2]]) -> bool { + let mut inside = false; + let mut j = poly.len() - 1; + for (i, a) in poly.iter().enumerate() { + let b = poly[j]; + if (a[1] > p[1]) != (b[1] > p[1]) && p[0] < (b[0] - a[0]) * (p[1] - a[1]) / (b[1] - a[1]) + a[0] { + inside = !inside; + } + j = i; + } + inside +} + +#[test] +fn lasso_freezes_exactly_the_nodes_inside_a_concave_polygon() { + // A concave "C" with a notch, at a non-integer cell size. + let poly = [[10.0, 8.0], [70.0, 8.0], [70.0, 20.0], [30.0, 22.5], [33.0, 40.0], [80.0, 41.0], [60.0, 58.0], [9.0, 55.0]]; + for cell in [1.0, 2.0, 3.5] { + let mut f = LiquifyField::new(bounds(), cell); + let dirty = f.apply_stroke(&lasso(&poly, None)); + assert_eq!(dirty, Rect::new(9, 8, 80, 58)); + for j in 0..f.h { + for i in 0..f.w { + let want = if inside(f.node_pos(i, j), &poly) { 1.0 } else { 0.0 }; + assert_eq!(f.freeze[j * f.w + i], want, "cell {cell}: node ({i}, {j}) at {:?}", f.node_pos(i, j)); + } + } + assert!(f.freeze.contains(&1.0)); + // Strokes replay to the same field (undo rebuilds from the list). + assert_eq!(LiquifyField::from_strokes(bounds(), cell, &[lasso(&poly, None)]), f); + } +} + +#[test] +fn lasso_thaws_with_amount_zero() { + let mut f = LiquifyField::new(bounds(), 2.0); + f.apply_stroke(&LiquifyStroke::new(LiquifyTool::FreezeAll, 1.0)); + assert!(f.freeze.iter().all(|&v| v == 1.0)); + let square = [[20.0, 20.0], [40.0, 20.0], [40.0, 40.0], [20.0, 40.0]]; + f.apply_stroke(&lasso(&square, Some(0.0))); + assert_eq!(f.freeze_at(30.0, 30.0), 0.0, "thawed inside"); + assert_eq!(f.freeze_at(5.0, 5.0), 1.0, "still frozen outside"); +} + +#[test] +fn lasso_ignores_degenerate_and_hostile_polygons() { + let empty = LiquifyField::new(bounds(), 2.0); + let cases: [&[[f64; 2]]; 6] = [ + &[], + &[[10.0, 10.0], [50.0, 50.0]], + &[[f64::NAN, 10.0], [50.0, f64::INFINITY], [20.0, 30.0]], + // Entirely outside the canvas, on every side. + &[[-50.0, -50.0], [-10.0, -50.0], [-10.0, -10.0]], + &[[200.0, 10.0], [300.0, 10.0], [250.0, 50.0]], + &[[10.0, 1e12], [50.0, 1e12], [30.0, 2e12]], + ]; + for poly in cases { + let mut f = empty.clone(); + assert_eq!(f.apply_stroke(&lasso(poly, None)), Rect::EMPTY, "{poly:?}"); + assert_eq!(f, empty, "{poly:?}"); + } + // Huge coordinates around the canvas clamp to it instead of overflowing. + let mut f = empty.clone(); + f.apply_stroke(&lasso(&[[-1e15, -1e15], [1e15, -1e15], [1e15, 1e15], [-1e15, 1e15]], None)); + assert!(f.freeze.iter().all(|&v| v == 1.0)); + // A NaN point among good ones is skipped. + let mut f = empty.clone(); + f.apply_stroke(&lasso(&[[10.0, 10.0], [f64::NAN, 0.0], [50.0, 10.0], [50.0, 50.0], [10.0, 50.0]], None)); + assert_eq!(f.freeze_at(30.0, 30.0), 1.0); +} + +#[test] +fn the_brush_fades_to_nothing_at_its_rim_at_every_density() { + for density in [0.0, 0.25, 0.5, 0.75, 1.0, f64::NAN, -3.0, 7.0] { + assert_eq!(falloff(0.0, density), 1.0, "full strength at the centre ({density})"); + assert_eq!(falloff(1.0, density), 0.0, "nothing at the rim ({density})"); + // Flat at the rim: the last 2 % of the radius moves at most a couple of percent. + assert!(falloff(0.98f64.powi(2), density) < 0.02, "{density}: {}", falloff(0.98f64.powi(2), density)); + let mut prev = 1.0; + for k in 1..=100 { + let v = falloff(k as f64 / 100.0, density); + assert!(v <= prev && v >= 0.0, "{density}: not falling at t² = {k}%"); + prev = v; + } + } + // Density widens the strong core: more strength at every radius, as in Photoshop. + for k in 1..100 { + let t2 = k as f64 / 100.0; + assert!(falloff(t2, 1.0) >= falloff(t2, 0.5) && falloff(t2, 0.5) >= falloff(t2, 0.0), "t² = {t2}"); + } + assert!(falloff(0.5, 1.0) > 0.5 && falloff(0.5, 0.0) < 0.2); +} + +/// #2606: the dab's strength used to stop at 1 - Density at its rim, so a Forward Warp moved +/// everything just inside the brush and nothing just outside, tearing the image along every +/// dab's circle (a hard-edged block at Density 0, half strength at the default 50). +#[test] +fn forward_warp_leaves_the_brush_rim_in_place() { + // A drag of one dab spacing (a twentieth of the radius): one dab, centred where it started. + let (r, drag) = (20.0, 1.0); + for density in [0.0, 50.0, 100.0] { + let mut s = LiquifyStroke::new(LiquifyTool::ForwardWarp, 2.0 * r); + s.density = density; + s.points = vec![vec![48.0, 32.0], vec![48.0 + drag, 32.0]]; + let f = LiquifyField::from_strokes(bounds(), 1.0, &[s]); + let mut rim = 0; + for j in 0..f.h { + for i in 0..f.w { + let p = f.node_pos(i, j); + let t = (p[0] - 48.0).hypot(p[1] - 32.0) / r; + if (0.97..1.0).contains(&t) { + let d = f.d[j * f.w + i]; + assert!(f64::from(d[0].hypot(d[1])) < 0.03 * drag, "density {density}: a node at {t:.3} r moved {d:?}"); + rim += 1; + } + } + } + assert!(rim > 20, "{rim} rim nodes"); + assert!(f.sample(48.0, 32.0)[0] < -0.9 * drag, "density {density}: the centre follows the brush"); + } +} + +#[test] +fn a_wide_integer_translation_keeps_channels_and_tile_edges_at_every_format() { + let b = Rect::new(13, -1, 13 + 70 * 256, 1); + let w = b.width() as usize; + for mode in [ColorMode::Grayscale, ColorMode::Rgb, ColorMode::Cmyk] { + for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + let format = PixelFormat::new(mode, depth, true); + let n = format.channels(); + let mut data = Vec::new(); + for i in 0..w * 2 { + let alpha = if i % 13 == 0 { 0.0 } else { 0.5 }; + for c in 0..mode.color_channels() { + data.push(if alpha == 0.0 { 0.0 } else { ((i * 19 + c * 43) % 251 + 2) as f32 / 255.0 }); + } + data.push(alpha); + } + let mut source = Surface::new(format); + source.write_region(b, &data); + source.write_pixel(b.x0 - 1, b.y0 - 1, &vec![0.75; n]); + let before = source.read_region(b); + let mut field = LiquifyField::new(b, 2.5); + field.d.fill([-1.0, 0.0]); + let output = apply_liquify(&source, &field); + let after = output.read_region(b); + let tolerance = if depth == SampleType::F32 { 4.0 * f32::EPSILON } else { 0.0 }; + for (original, moved) in before.chunks_exact(w * n).zip(after.chunks_exact(w * n)) { + for (x, pixel) in moved.chunks_exact(n).enumerate() { + let offset = x.saturating_sub(1) * n; + for (actual, expected) in pixel.iter().zip(&original[offset..offset + n]) { + assert!((actual - expected).abs() <= tolerance, "{mode:?}/{depth:?} at column {x}"); + } + } + } + assert_eq!(output.pixel(b.x0 - 1, b.y0 - 1), source.pixel(b.x0 - 1, b.y0 - 1)); + } + } +} + +#[test] +fn no_strokes_is_identity_at_every_depth() { + for st in [SampleType::U8, SampleType::U16, SampleType::F32] { + let s = sample(st); + let f = LiquifyField::new(bounds(), 2.0); + assert_eq!(apply_liquify(&s, &f), s); + // A field with exactly-zero strokes (zero pressure) is still identity. + let mut st0 = LiquifyStroke::new(LiquifyTool::ForwardWarp, 30.0); + st0.pressure = 0.0; + st0.points = vec![vec![40.0, 30.0], vec![60.0, 30.0]]; + let f = LiquifyField::from_strokes(bounds(), 2.0, &[st0]); + assert!(f.is_identity()); + } +} + +#[test] +fn full_resolution_preview_matches_the_unit_scale_proxy_and_partial_updates() { + let canvas = Rect::new(0, 0, 96, 64); + for sample_type in [SampleType::U8, SampleType::U16, SampleType::F32] { + let source = sample(sample_type); + let mut stroke = LiquifyStroke::new(LiquifyTool::ForwardWarp, 32.0); + stroke.points = vec![vec![38.0, 30.0, 1.0], vec![52.0, 34.0, 0.8]]; + let mut field = LiquifyField::from_strokes(canvas, 2.0, &[stroke]); + + let proxy = ProxyImage::new(&source, canvas, 96); + assert_eq!(proxy.scale, 1.0); + let mut want = vec![[0; 4]; proxy.w * proxy.h]; + proxy.render(&field, [0, 0, proxy.w, proxy.h], &mut want); + + let mut got = vec![[0; 4]; proxy.w * proxy.h]; + let mut scratch = Vec::new(); + assert!(ProxyImage::render_full_resolution(&source, &field, canvas, canvas, &mut got, &mut scratch)); + assert_eq!(got, want, "full-resolution render at {sample_type:?}"); + + let mut more = LiquifyStroke::new(LiquifyTool::Bloat, 16.0); + more.points = vec![vec![43.0, 32.0, 1.0]]; + let dirty = field.apply_stroke(&more); + proxy.render(&field, proxy.proxy_rect(dirty), &mut want); + assert!(ProxyImage::render_full_resolution(&source, &field, canvas, dirty, &mut got, &mut scratch)); + assert_eq!(got, want, "partial update at {sample_type:?}"); + } +} + +#[test] +fn forward_warp_displaces_along_the_stroke_and_reconstruct_restores() { + let mut s = LiquifyStroke::new(LiquifyTool::ForwardWarp, 40.0); + s.points = vec![vec![40.0, 32.0], vec![52.0, 32.0]]; + let mut f = LiquifyField::from_strokes(bounds(), 2.0, &[s]); + // Content moved right: the output at the end point samples from the left. + let d = f.sample(52.0, 32.0); + assert!(d[0] < -4.0 && d[1].abs() < 0.5, "{d:?}"); + // A pixel-level check: a marker column follows the stroke. + let mut img = Surface::new(PixelFormat::new(ColorMode::Grayscale, SampleType::F32, true)); + img.fill_rect(bounds(), &[0.0, 1.0]); + img.fill_rect(Rect::new(40, 28, 42, 36), &[1.0, 1.0]); + let out = apply_liquify(&img, &f); + let brightest = (30..70).max_by(|a, b| out.pixel(*a, 32)[0].total_cmp(&out.pixel(*b, 32)[0])).unwrap(); + assert!(brightest > 44, "marker moved right: {brightest}"); + // Reconstruct All restores the original exactly. + let mut rec = LiquifyStroke::new(LiquifyTool::ReconstructAll, 10.0); + rec.amount = Some(100.0); + f.apply_stroke(&rec); + assert!(f.is_identity()); + assert_eq!(apply_liquify(&img, &f), img); +} + +#[test] +fn reconstruct_brush_reduces_the_field_and_freeze_protects() { + let mut s = LiquifyStroke::new(LiquifyTool::ForwardWarp, 40.0); + s.points = vec![vec![30.0, 32.0], vec![45.0, 32.0]]; + let mut f = LiquifyField::from_strokes(bounds(), 2.0, std::slice::from_ref(&s)); + let before = f.max_displacement(); + let mut r = LiquifyStroke::new(LiquifyTool::Reconstruct, 80.0); + r.points = vec![vec![40.0, 32.0]; 30]; + f.apply_stroke(&r); + assert!(f.max_displacement() < before * 0.2, "{} vs {before}", f.max_displacement()); + // Frozen area doesn't move. + let mut fr = LiquifyStroke::new(LiquifyTool::Freeze, 60.0); + fr.density = 100.0; + fr.points = vec![vec![40.0, 32.0]]; + let mut g = LiquifyField::new(bounds(), 2.0); + g.apply_stroke(&fr); + assert!(g.freeze_at(40.0, 32.0) > 0.99); + g.apply_stroke(&s); + assert!(g.sample(40.0, 32.0)[0].abs() < 1e-3); + // Thaw unfreezes. + let mut th = fr.clone(); + th.tool = LiquifyTool::Thaw; + g.apply_stroke(&th); + assert!(g.freeze_at(40.0, 32.0) < 0.01); + // Mask All / Invert / None. + g.apply_stroke(&LiquifyStroke::new(LiquifyTool::FreezeAll, 1.0)); + assert!(g.freeze.iter().all(|f| *f == 1.0)); + g.apply_stroke(&LiquifyStroke::new(LiquifyTool::InvertFreeze, 1.0)); + assert!(g.freeze.iter().all(|f| *f == 0.0)); + g.apply_stroke(&fr); + g.apply_stroke(&LiquifyStroke::new(LiquifyTool::InvertFreeze, 1.0)); + assert!(g.freeze_at(40.0, 32.0) < 0.01 && g.freeze_at(5.0, 5.0) > 0.99); + g.apply_stroke(&LiquifyStroke::new(LiquifyTool::ThawAll, 1.0)); + assert!(g.freeze.iter().all(|f| *f == 0.0)); +} + +#[test] +fn fully_frozen_pixels_keep_their_mapping_when_an_adjacent_area_is_warped() { + let bounds = bounds(); + let mut src = Surface::new(PixelFormat::new(ColorMode::Rgb, SampleType::F32, true)); + for y in 0..bounds.height() { + for x in 0..bounds.width() { + src.write_pixel(x as i32, y as i32, &[x as f32 / bounds.width() as f32, y as f32 / bounds.height() as f32, 0.0, 1.0]); + } + } + + let mut mask_only = LiquifyField::new(bounds, 2.0); + mask_only.apply_stroke(&lasso(&[[0.0, 0.0], [40.0, 0.0], [40.0, 64.0], [0.0, 64.0]], None)); + assert_eq!(apply_liquify(&src, &mask_only), src); + + let mut field = LiquifyField::new(bounds, 2.0); + let mut first_warp = LiquifyStroke::new(LiquifyTool::ForwardWarp, 40.0); + first_warp.points = vec![vec![22.0, 32.0], vec![34.0, 32.0]]; + field.apply_stroke(&first_warp); + + field.apply_stroke(&lasso(&[[0.0, 0.0], [40.0, 0.0], [40.0, 64.0], [0.0, 64.0]], None)); + let frozen_pixel = (37, 32); + assert!(field.freeze_at(f64::from(frozen_pixel.0) + 0.5, f64::from(frozen_pixel.1) + 0.5) > 0.999); + let before = apply_liquify(&src, &field).pixel(frozen_pixel.0, frozen_pixel.1); + assert_ne!(before, src.pixel(frozen_pixel.0, frozen_pixel.1), "freezing must retain the earlier warp"); + let neighbor_before = apply_liquify(&src, &field).pixel(43, 32); + + let mut adjacent_warp = LiquifyStroke::new(LiquifyTool::ForwardWarp, 24.0); + adjacent_warp.points = vec![vec![44.0, 32.0], vec![52.0, 32.0]]; + field.apply_stroke(&adjacent_warp); + + let after = apply_liquify(&src, &field).pixel(frozen_pixel.0, frozen_pixel.1); + let neighbor_after = apply_liquify(&src, &field).pixel(43, 32); + assert_eq!(before, after, "a fully frozen pixel must keep its pre-neighbor-warp mapping"); + assert_ne!(neighbor_before, neighbor_after, "an adjacent unfrozen pixel must still move"); +} + +#[test] +fn twirl_pucker_bloat_and_push_left_have_the_right_sense() { + let at = |tool: LiquifyTool, pts: Vec>| { + let mut s = LiquifyStroke::new(tool, 40.0); + s.points = pts; + LiquifyField::from_strokes(bounds(), 2.0, &[s]) + }; + let c = vec![vec![48.0, 32.0]; 10]; + // Pucker pulls content in: the output samples outward (d points away from the centre). + let f = at(LiquifyTool::Pucker, c.clone()); + assert!(f.sample(58.0, 32.0)[0] > 0.1); + let f = at(LiquifyTool::Bloat, c.clone()); + assert!(f.sample(58.0, 32.0)[0] < -0.1); + // Twirl clockwise (y down): content right of centre moves down, so it samples from above. + let f = at(LiquifyTool::TwirlCw, c.clone()); + assert!(f.sample(58.0, 32.0)[1] < -0.1, "{:?}", f.sample(58.0, 32.0)); + let f = at(LiquifyTool::TwirlCcw, c); + assert!(f.sample(58.0, 32.0)[1] > 0.1); + // Push Left while dragging up moves content left (samples from the right). + let f = at(LiquifyTool::PushLeft, vec![vec![48.0, 44.0], vec![48.0, 20.0]]); + assert!(f.sample(48.0, 32.0)[0] > 0.5, "{:?}", f.sample(48.0, 32.0)); + // Smooth reduces sharp field differences. + let mut s = LiquifyStroke::new(LiquifyTool::ForwardWarp, 12.0); + s.points = vec![vec![40.0, 32.0], vec![50.0, 32.0]]; + let mut g = LiquifyField::from_strokes(bounds(), 2.0, &[s]); + let m0 = g.max_displacement(); + let mut sm = LiquifyStroke::new(LiquifyTool::Smooth, 60.0); + sm.points = vec![vec![45.0, 32.0]; 20]; + g.apply_stroke(&sm); + assert!(g.max_displacement() < m0); +} + +#[test] +fn replay_is_deterministic_and_depths_agree() { + let mut s = LiquifyStroke::new(LiquifyTool::TwirlCw, 50.0); + s.points = vec![vec![48.0, 32.0, 0.5], vec![50.0, 33.0, 1.0], vec![52.0, 34.0]]; + let a = LiquifyField::from_strokes(bounds(), 2.0, std::slice::from_ref(&s)); + let b = LiquifyField::from_strokes(bounds(), 2.0, std::slice::from_ref(&s)); + assert_eq!(a, b); + let r8 = apply_liquify(&sample(SampleType::U8), &a); + let r32 = apply_liquify(&sample(SampleType::F32), &a); + assert!(worst(&r8, &r32, bounds()) < 2.0 / 255.0 + 1e-4); +} + +#[test] +fn proxy_matches_the_full_render_roughly() { + let src = sample(SampleType::U8); + let mut s = LiquifyStroke::new(LiquifyTool::Bloat, 40.0); + s.points = vec![vec![48.0, 32.0]; 8]; + let f = LiquifyField::from_strokes(bounds(), 2.0, &[s]); + let p = ProxyImage::new(&src, bounds(), 96); + assert_eq!((p.w, p.h, p.scale), (96, 64, 1.0)); + let mut out = vec![[0u8; 4]; p.w * p.h]; + p.render(&f, [0, 0, p.w, p.h], &mut out); + let full = apply_liquify(&src, &f); + let mut bad = 0; + for y in 0..64 { + for x in 0..96 { + let q = full.pixel(x, y); + let o = out[y as usize * 96 + x as usize]; + if (f32::from(o[1]) / 255.0 - q[1]).abs() > 0.1 { + bad += 1; + } + } + } + assert!(bad < 96 * 64 / 50, "{bad}"); +} diff --git a/crates/algo/src/panorama.rs b/crates/algo/src/panorama.rs index 87f8415b99..dc44f06c1f 100644 --- a/crates/algo/src/panorama.rs +++ b/crates/algo/src/panorama.rs @@ -38,6 +38,12 @@ use crate::features::{self, Descriptor, Model}; use crate::photo_util::{Normal, Rng, par_map, par_rows, solve_dense}; use crate::transform::Homography; +mod blend; + +pub use blend::{Geometry, Photometric, RoiImage, blend_levels, multiband, photometric, seam_labels}; +#[cfg(test)] +use blend::{expand, multiband_batched, push_pull, reduce}; + /// Photomerge layouts. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Layout { @@ -720,696 +726,6 @@ fn align_layout(feats: &[ImageFeatures], matches: &[PairMatch], opts: &AlignOpti Some(Alignment { layout, reference, placements, focal, k1, pairs: edges.iter().map(|e| (e.0, e.1, e.2)).collect(), rms }) } -// ---------- photometric ---------- - -/// One image warped into the panorama: an axis-aligned region with colour channels and coverage. -#[derive(Clone, Debug)] -pub struct RoiImage { - pub x0: i32, - pub y0: i32, - pub w: usize, - pub h: usize, - /// Colour channels per pixel (no alpha). - pub ch: usize, - pub px: Vec, - /// Coverage `0..=1`. - pub alpha: Vec, -} - -impl RoiImage { - fn at(&self, x: i32, y: i32) -> Option { - let (lx, ly) = (x - self.x0, y - self.y0); - (lx >= 0 && ly >= 0 && (lx as usize) < self.w && (ly as usize) < self.h).then(|| ly as usize * self.w + lx as usize) - } -} - -/// Placements and source sizes (for the vignetting radius). -pub type Geometry<'a> = (&'a [Placement], &'a [(usize, usize)]); - -/// Gains (per image, per channel) and the vignetting model found by [`photometric`]. -#[derive(Clone, Debug, PartialEq)] -pub struct Photometric { - pub gains: Vec>, - /// `log V(r) = a·r² + b·r⁴`, `r` = distance from the image centre over the half diagonal. - pub vignette: [f64; 2], -} - -impl Photometric { - /// Multiplier that corrects a pixel of image `i` at normalised squared radius `r2`. - pub fn factor(&self, i: usize, c: usize, r2: f64) -> f32 { - let v = (self.vignette[0] * r2 + self.vignette[1] * r2 * r2).exp(); - (1.0 / (self.gains[i][c] as f64 * v)) as f32 - } -} - -/// Estimates exposure gains (`gain`) and a shared vignetting falloff (`vignette`) from the -/// overlaps of `imgs` (`placements`/`sizes` give each panorama pixel's source radius). -/// Without `geometry` (placements and source sizes) the vignetting model is not estimated. -pub fn photometric(imgs: &[RoiImage], geometry: Option, gain: bool, vignette: bool) -> Photometric { - let vignette = vignette && geometry.is_some(); - let n = imgs.len(); - let ch = imgs.first().map_or(1, |i| i.ch); - let identity = Photometric { gains: vec![vec![1.0; ch]; n], vignette: [0.0, 0.0] }; - if n == 0 || (!gain && !vignette) { - return identity; - } - // Overlap samples on a grid: (a, b, colours, radii²). - let (mut x0, mut y0, mut x1, mut y1) = (i32::MAX, i32::MAX, i32::MIN, i32::MIN); - for im in imgs { - x0 = x0.min(im.x0); - y0 = y0.min(im.y0); - x1 = x1.max(im.x0 + im.w as i32); - y1 = y1.max(im.y0 + im.h as i32); - } - let step = (((x1 - x0) as i64 * (y1 - y0) as i64 / 40_000).max(1) as f64).sqrt().ceil() as i32; - let r2_of = |i: usize, u: i32, v: i32| -> Option { - let Some((placements, sizes)) = geometry else { return Some(0.0) }; - let (sx, sy) = placements[i].inverse(u as f64 + 0.5, v as f64 + 0.5)?; - let (w, h) = (sizes[i].0 as f64, sizes[i].1 as f64); - let (dx, dy) = (sx - w / 2.0, sy - h / 2.0); - Some((dx * dx + dy * dy) / (w * w / 4.0 + h * h / 4.0)) - }; - type Sample = (usize, usize, Vec, Vec, f64, f64); - let mut samples: Vec = Vec::new(); - let mut y = y0; - while y < y1 { - let mut x = x0; - while x < x1 { - let cover: Vec<(usize, usize)> = (0..n).filter_map(|i| imgs[i].at(x, y).filter(|&k| imgs[i].alpha[k] > 0.999).map(|k| (i, k))).collect(); - for p in 0..cover.len() { - for q in p + 1..cover.len() { - let ((a, ka), (b, kb)) = (cover[p], cover[q]); - let ca = imgs[a].px[ka * ch..(ka + 1) * ch].to_vec(); - let cb = imgs[b].px[kb * ch..(kb + 1) * ch].to_vec(); - if ca.iter().chain(&cb).any(|v| !(0.02..=0.98).contains(v)) { - continue; - } - // Disagreeing content (parallax, moving objects) says nothing about exposure. - if ca.iter().zip(&cb).any(|(x, y)| (x / y).ln().abs() > 1.0) { - continue; - } - let (Some(ra), Some(rb)) = (r2_of(a, x, y), r2_of(b, x, y)) else { continue }; - samples.push((a, b, ca, cb, ra, rb)); - } - } - x += step; - } - y += step; - } - if samples.len() < 20 { - return identity; - } - // Unknowns: log gain per image (per channel), then a, b (shared, from mean log intensity). - let sigma_n = 0.05; - let sigma_g = if gain { 0.15 } else { 1e-4 }; - let mut out = identity.clone(); - let nv = if vignette { 2 } else { 0 }; - // Vignetting is solved on the channel mean, then gains per channel with it fixed. - let mut ne = Normal::new(n + nv); - for (a, b, ca, cb, ra, rb) in &samples { - let la = ca.iter().map(|v| (*v as f64).ln()).sum::() / ch as f64; - let lb = cb.iter().map(|v| (*v as f64).ln()).sum::() / ch as f64; - let mut row = vec![(*a, 1.0), (*b, -1.0)]; - if vignette { - row.push((n, ra - rb)); - row.push((n + 1, ra * ra - rb * rb)); - } - ne.add(&row, la - lb, 1.0 / sigma_n); - } - for i in 0..n { - ne.add(&[(i, 1.0)], 0.0, 1.0 / sigma_g); - } - if vignette { - ne.add(&[(n, 1.0)], 0.0, 0.5); - ne.add(&[(n + 1, 1.0)], 0.0, 0.5); - } - let Some(sol) = ne.solve() else { return out }; - if vignette { - // Vignetting only darkens; clamp a runaway brightening fit. - out.vignette = [sol[n].clamp(-2.0, 0.5), sol[n + 1].clamp(-2.0, 2.0)]; - } - if gain { - for c in 0..ch { - let mut ne = Normal::new(n); - for (a, b, ca, cb, ra, rb) in &samples { - let va = out.vignette[0] * ra + out.vignette[1] * ra * ra; - let vb = out.vignette[0] * rb + out.vignette[1] * rb * rb; - ne.add(&[(*a, 1.0), (*b, -1.0)], ((ca[c] as f64).ln() - va) - ((cb[c] as f64).ln() - vb), 1.0 / sigma_n); - } - for i in 0..n { - ne.add(&[(i, 1.0)], 0.0, 1.0 / sigma_g); - } - if let Some(g) = ne.solve() { - for i in 0..n { - out.gains[i][c] = g[i].exp().clamp(0.2, 5.0) as f32; - } - } - } - } - out -} - -// ---------- seams ---------- - -/// Seam labels on a `w × h` grid (`-1` = no image): images are added in `order`; each new image -/// takes the part of its overlap with the composite that lies on its side of the cheapest path -/// through the overlap (cost = colour difference). -pub fn seam_labels(w: usize, h: usize, luma: &[Vec], cover: &[Vec], order: &[usize]) -> Vec { - let mut label = vec![-1i32; w * h]; - for &img in order { - let cov = &cover[img]; - let mut overlap = vec![false; w * h]; - let (mut sx, mut sy, mut no) = (0.0f64, 0.0f64, 0usize); - let (mut nx, mut ny, mut nn) = (0.0f64, 0.0f64, 0usize); - for i in 0..w * h { - if !cov[i] { - continue; - } - nx += (i % w) as f64; - ny += (i / w) as f64; - nn += 1; - if label[i] >= 0 { - overlap[i] = true; - sx += (i % w) as f64; - sy += (i / w) as f64; - no += 1; - } else { - label[i] = img as i32; - } - } - if no == 0 { - continue; - } - let (cx, cy) = (nx / nn as f64, ny / nn as f64); - let contained = nn == no; - let (ox, oy) = if contained { - // Wholly inside the composite (#5745: two photos in one document, the second moved - // by Auto-Align so the canvas crops it to the part over the first). Its side of the - // seam is the one it lies towards from the composite's centre; an image centred on - // the composite has no side, and the earlier images keep it. - let (mut px, mut py, mut pn) = (0.0f64, 0.0f64, 0usize); - for (i, l) in label.iter().enumerate() { - if *l >= 0 { - px += (i % w) as f64; - py += (i / w) as f64; - pn += 1; - } - } - let (px, py) = (px / pn.max(1) as f64, py / pn.max(1) as f64); - if (cx - px).abs() < 0.5 && (cy - py).abs() < 0.5 { - continue; - } - (px, py) - } else { - (sx / no as f64, sy / no as f64) - }; - let vertical = (cx - ox).abs() >= (cy - oy).abs(); - // Image on the increasing side along the seam's cross axis? - let positive = if vertical { cx > ox } else { cy > oy }; - // A contained image has no pixels of its own, so a seam on its outer edge would leave it - // nothing: break cost ties away from its side (towards larger k when it lies on the - // decreasing side) so it keeps its side of the overlap. - let prefer_high = contained && !positive; - let cost = |i: usize| -> f32 { 0.002 + (luma[img][i] - luma[label[i] as usize][i]).abs() }; - let (lines, len) = if vertical { (h, w) } else { (w, h) }; - let idx = |line: usize, k: usize| if vertical { line * w + k } else { k * w + line }; - // DP over lines (rows for a vertical seam), within the overlap. - let mut acc = vec![f32::INFINITY; w * h]; - let mut from = vec![usize::MAX; w * h]; - let mut prev_line: Option = None; - for line in 0..lines { - let any = (0..len).any(|k| overlap[idx(line, k)]); - if !any { - continue; - } - for k in 0..len { - let i = idx(line, k); - if !overlap[i] { - continue; - } - let mut best = (0.0f32, usize::MAX); - if let Some(pl) = prev_line.filter(|pl| *pl + 1 == line) { - best = (f32::INFINITY, usize::MAX); - let dks = if prefer_high { [1i64, 0, -1] } else { [-1i64, 0, 1] }; - for dk in dks { - let kk = k as i64 + dk; - if kk < 0 || kk >= len as i64 { - continue; - } - let j = idx(pl, kk as usize); - if acc[j] < best.0 { - best = (acc[j], kk as usize); - } - } - if best.1 == usize::MAX { - best = (0.0, usize::MAX); - } - } - acc[i] = best.0 + cost(i); - from[i] = best.1; - } - prev_line = Some(line); - } - // Backtrack from the cheapest end; lines not reached keep their own best cell. - let mut seam = vec![usize::MAX; lines]; - let mut line = lines; - while line > 0 { - line -= 1; - if seam[line] != usize::MAX { - continue; - } - let Some(k) = (0..len) - .filter(|&k| overlap[idx(line, k)]) - .min_by(|&a, &b| acc[idx(line, a)].total_cmp(&acc[idx(line, b)]).then(if prefer_high { b.cmp(&a) } else { a.cmp(&b) })) - else { - continue; - }; - let (mut l, mut k) = (line, k); - loop { - seam[l] = k; - let f = from[idx(l, k)]; - if f == usize::MAX || l == 0 { - break; - } - l -= 1; - if seam[l] != usize::MAX { - break; - } - k = f; - } - } - for line in 0..lines { - let s = seam[line]; - if s == usize::MAX { - continue; - } - let on_side = |k: usize| if positive { k > s } else { k < s }; - // A contained image has no other cells, so where the overlap has nothing on its side - // of the seam (a line one cell wide) it takes the seam cell rather than nothing. - let take_seam = contained && !(0..len).any(|k| overlap[idx(line, k)] && on_side(k)); - for k in 0..len { - let i = idx(line, k); - if overlap[i] && (on_side(k) || (take_seam && k == s)) { - label[i] = img as i32; - } - } - } - } - label -} - -// ---------- multi-band blending ---------- - -/// Number of pyramid levels used by [`multiband`] for a seam mask of this size. -pub fn blend_levels(w: usize, h: usize) -> usize { - let mut s = w.min(h); - let mut n = 1; - while s > 16 && n < 7 { - s /= 2; - n += 1; - } - n -} - -/// `a[i] ⊕ b[i]` for every `i` (the shorter length wins, like `zip`), in parallel on native -/// targets. Purely elementwise, so the result is the serial result bit for bit. -fn par_zip(a: &[f32], b: &[f32], f: impl Fn(f32, f32) -> f32 + Sync + Send) -> Vec { - const CHUNK: usize = 1 << 14; - let mut out = vec![0.0f32; a.len().min(b.len())]; - let fill = |o: &mut [f32], a: &[f32], b: &[f32]| { - for ((o, &a), &b) in o.iter_mut().zip(a).zip(b) { - *o = f(a, b); - } - }; - #[cfg(not(target_arch = "wasm32"))] - { - use rayon::prelude::*; - out.par_chunks_mut(CHUNK).zip(a.par_chunks(CHUNK)).zip(b.par_chunks(CHUNK)).for_each(|((o, a), b)| fill(o, a, b)); - } - #[cfg(target_arch = "wasm32")] - out.chunks_mut(CHUNK).zip(a.chunks(CHUNK)).zip(b.chunks(CHUNK)).for_each(|((o, a), b)| fill(o, a, b)); - out -} - -/// `f(a[i])` for every `i`, in parallel on native targets (elementwise, so bit for bit serial). -fn par_map1(a: &[f32], f: impl Fn(f32) -> f32 + Sync + Send) -> Vec { - par_zip(a, a, |x, _| f(x)) -} - -// `reduce`, `expand` and `push_pull` run one pyramid level for one image at a time, and the -// images themselves only fill part of a many-core machine, so each of them also runs its rows -// in parallel. Every output element is computed by the same expression, in the same order, as -// the one-thread loops they replace (rows never read each other's output), so the result is -// bit for bit unchanged. - -fn reduce(w: usize, h: usize, ch: usize, src: &[f32]) -> (usize, usize, Vec) { - let (nw, nh) = (w.div_ceil(2), h.div_ceil(2)); - let k = [1.0f32, 4.0, 6.0, 4.0, 1.0]; - // Separable 5-tap binomial, then decimate. - let mut tmp = vec![0.0f32; nw * h * ch]; - par_rows(&mut tmp, nw, ch, |y, row| { - let line = &src[y * w * ch..(y + 1) * w * ch]; - for x in 0..nw { - // The clamped source column of each tap is the same for every channel. - let xs: [usize; 5] = std::array::from_fn(|t| (2 * x as i64 + t as i64 - 2).clamp(0, w as i64 - 1) as usize * ch); - for c in 0..ch { - let mut s = 0.0; - for (kv, xx) in k.iter().zip(xs) { - s += kv * line[xx + c]; - } - row[x * ch + c] = s / 16.0; - } - } - }); - let mut out = vec![0.0f32; nw * nh * ch]; - par_rows(&mut out, nw, ch, |y, row| { - // Each output row is five source rows added in tap order: the same sum per element as - // before (`0 + k0·a + k1·b + …`), but over whole rows so it vectorises. - for (t, kv) in k.iter().enumerate() { - let yy = (2 * y as i64 + t as i64 - 2).clamp(0, h as i64 - 1) as usize; - for (o, &v) in row.iter_mut().zip(&tmp[yy * nw * ch..(yy + 1) * nw * ch]) { - *o += kv * v; - } - } - for o in row.iter_mut() { - *o /= 16.0; - } - }); - (nw, nh, out) -} - -fn expand(sw: usize, sh: usize, ch: usize, src: &[f32], w: usize, h: usize) -> Vec { - // Bilinear upsampling at half-pixel-aligned positions. - let mut out = vec![0.0f32; w * h * ch]; - // Source columns and weights depend on x only: worked out once instead of for every row. - // The clamped position is never negative, so truncating is `floor` (and spares the libm call). - let cols: Vec<(usize, usize, f32)> = (0..w) - .map(|x| { - let fx = ((x as f32 + 0.5) / 2.0 - 0.5).clamp(0.0, (sw - 1) as f32); - let x0 = fx as usize; - (x0 * ch, (x0 + 1).min(sw - 1) * ch, fx - x0 as f32) - }) - .collect(); - par_rows(&mut out, w, ch, |y, row| { - let fy = ((y as f32 + 0.5) / 2.0 - 0.5).clamp(0.0, (sh - 1) as f32); - let y0 = fy as usize; - let ty = fy - y0 as f32; - let y1 = (y0 + 1).min(sh - 1); - let (r0, r1) = (&src[y0 * sw * ch..(y0 + 1) * sw * ch], &src[y1 * sw * ch..(y1 + 1) * sw * ch]); - for (px, &(x0, x1, tx)) in row.chunks_exact_mut(ch.max(1)).zip(&cols) { - for (c, o) in px.iter_mut().enumerate() { - let top = r0[x0 + c] + (r0[x1 + c] - r0[x0 + c]) * tx; - let bot = r1[x0 + c] + (r1[x1 + c] - r1[x0 + c]) * tx; - *o = top + (bot - top) * ty; - } - } - }); - out -} - -/// Fills pixels with zero `wt` from their surroundings (push-pull), so pyramid levels don't -/// pull in black from outside an image. -fn push_pull(w: usize, h: usize, ch: usize, px: &mut [f32], wt: &[f32]) { - if w <= 1 && h <= 1 { - return; - } - let (nw, nh) = (w.div_ceil(2), h.div_ceil(2)); - // Coarse sums. A coarse row is fed by two fine rows; walking them in raster order adds each - // coarse cell's (up to) four fine pixels in the order the serial scatter-add did, from zero. - let mut cpx = vec![0.0f32; nw * nh * ch]; - let mut cw = vec![0.0f32; nw * nh]; - par_rows(&mut cw, nw, 1, |cy, row| { - for y in 2 * cy..(2 * cy + 2).min(h) { - for (x, &a) in wt[y * w..(y + 1) * w].iter().enumerate() { - row[x / 2] += a; - } - } - }); - let px_in: &[f32] = px; - par_rows(&mut cpx, nw, ch, |cy, row| { - for y in 2 * cy..(2 * cy + 2).min(h) { - for x in 0..w { - let (i, j) = (y * w + x, x / 2); - let a = wt[i]; - for c in 0..ch { - row[j * ch + c] += a * px_in[i * ch + c]; - } - } - } - }); - // Normalise by the weight (this reads `cw` before it is reset to 0 / 1 below). - par_rows(&mut cpx, nw, ch, |cy, row| { - for cx in 0..nw { - let wj = cw[cy * nw + cx]; - if wj > 0.0 { - for c in 0..ch { - row[cx * ch + c] /= wj; - } - } - } - }); - for v in cw.iter_mut() { - if *v > 0.0 { - *v = 1.0; - } - } - if cw.contains(&0.0) && cw.iter().any(|v| *v > 0.0) { - push_pull(nw, nh, ch, &mut cpx, &cw); - } - par_rows(px, w, ch, |y, row| { - for x in 0..w { - let i = y * w + x; - if wt[i] < 1.0 { - let j = (y / 2) * nw + x / 2; - let a = wt[i]; - for c in 0..ch { - row[x * ch + c] = a * row[x * ch + c] + (1.0 - a) * cpx[j * ch + c]; - } - } - } - }); -} - -/// One image's pyramid in [`multiband`]: the grid origin `(gx0, gy0)` at level 0, the Laplacian -/// levels `(w, h, colours)` and the Gaussian weight levels. -type PyramidBand = (i32, i32, Vec<(usize, usize, Vec)>, Vec>); - -/// The part of `band` on panorama row `py` of level `l`: the panorama column its first pixel -/// lands on, its width, its weight row and its colour row. `None` when it misses the row. -fn band_row(band: &PyramidBand, l: usize, ch: usize, py: usize) -> Option<(usize, usize, &[f32], &[f32])> { - let (ox, oy) = ((band.0 >> l) as usize, (band.1 >> l) as usize); - let (lw, lh, colours) = &band.2[l]; - (py >= oy && py - oy < *lh).then(|| { - let y = py - oy; - (ox, *lw, &band.3[l][y * lw..(y + 1) * lw], &colours[y * lw * ch..(y + 1) * lw * ch]) - }) -} - -/// Estimated bytes of band construction [`multiband`] keeps in flight at once. Images are built -/// and accumulated in batches under it, so its peak memory doesn't grow with the image count -/// (#7758). Four 24 MP RGB sources (~1.2 GB each) fit in one batch: building bands side by side -/// uses a many-core machine better than one band's row-parallel work, and one at a time made the -/// usual 2–4 image Photomerge 12–36% slower on a 32-thread desktop. -#[cfg(not(target_arch = "wasm32"))] -const BAND_BUDGET: usize = 5 << 30; -/// Without threads the bands of a batch are built one after another anyway, so each is added as -/// soon as it is built (the browser's address space is 4 GB). -#[cfg(target_arch = "wasm32")] -const BAND_BUDGET: usize = 0; - -/// Multi-band blend of `imgs` into a `w × h` panorama (origin 0,0) with one weight map per image -/// over the same grid as its ROI (`weights[i]` has `w_i × h_i` entries). Returns the colour -/// channels (`ch` per pixel) and the total coverage. -pub fn multiband(w: usize, h: usize, imgs: &[RoiImage], weights: &[Vec], levels: usize) -> (Vec, Vec) { - multiband_batched(w, h, imgs, weights, levels, BAND_BUDGET) -} - -/// [`multiband`], building at most `budget` estimated bytes of bands at a time (at least one -/// image). Each pixel still adds the bands in image order, so the result doesn't depend on it. -fn multiband_batched(w: usize, h: usize, imgs: &[RoiImage], weights: &[Vec], levels: usize, budget: usize) -> (Vec, Vec) { - let ch = imgs.first().map_or(1, |i| i.ch); - let levels = levels.max(1); - let align = 1i32 << (levels - 1); - // Level sizes of the panorama. - let mut sizes = vec![(w, h)]; - for _ in 1..levels { - let Some(&(pw, ph)) = sizes.last() else { break }; - sizes.push((pw.div_ceil(2), ph.div_ceil(2))); - } - let mut acc: Vec> = sizes.iter().map(|&(lw, lh)| vec![0.0; lw * lh * ch]).collect(); - let mut wsum: Vec> = sizes.iter().map(|&(lw, lh)| vec![0.0; lw * lh]).collect(); - let margin = align * 4; - // Each image on its ROI grown by a margin and aligned to the coarsest level's grid. - let grid = |im: &RoiImage| { - let gx0 = ((im.x0 - margin).max(0) / align) * align; - let gy0 = ((im.y0 - margin).max(0) / align) * align; - let gx1 = (im.x0 + im.w as i32 + margin).min(w as i32); - let gy1 = (im.y0 + im.h as i32 + margin).min(h as i32); - (gx0, gy0, (gx1 - gx0).max(1) as usize, (gy1 - gy0).max(1) as usize) - }; - // Building one band holds its grid's colour and weight planes about three times over: the - // pyramids are 4/3 of a plane, and the grid copy, coverage and `expand` scratch come on top. - let cost = |im: &RoiImage| { - let (_, _, gw, gh) = grid(im); - gw.saturating_mul(gh).saturating_mul(ch + 1).saturating_mul(4 * 3) - }; - let band = |k: usize| -> PyramidBand { - let im = &imgs[k]; - let (gx0, gy0, gw, gh) = grid(im); - // Each grid pixel takes the image pixel that lands on it (every image pixel lands on at - // most one), so rows of the grid are independent and fill in parallel. - let src_of = |gx: usize, gy: usize| -> Option { - let (x, y) = (gx as i64 + gx0 as i64 - im.x0 as i64, gy as i64 + gy0 as i64 - im.y0 as i64); - (x >= 0 && y >= 0 && (x as usize) < im.w && (y as usize) < im.h).then(|| y as usize * im.w + x as usize) - }; - let mut px = vec![0.0f32; gw * gh * ch]; - par_rows(&mut px, gw, ch, |gy, row| { - for gx in 0..gw { - if let Some(i) = src_of(gx, gy) { - row[gx * ch..(gx + 1) * ch].copy_from_slice(&im.px[i * ch..(i + 1) * ch]); - } - } - }); - let mut cov = vec![0.0f32; gw * gh]; - par_rows(&mut cov, gw, 1, |gy, row| { - for (gx, o) in row.iter_mut().enumerate() { - if let Some(i) = src_of(gx, gy) { - *o = im.alpha[i]; - } - } - }); - let mut wt = vec![0.0f32; gw * gh]; - par_rows(&mut wt, gw, 1, |gy, row| { - for (gx, o) in row.iter_mut().enumerate() { - if let Some(i) = src_of(gx, gy) { - *o = weights[k][i] * im.alpha[i].min(1.0); - } - } - }); - let bin: Vec = par_map1(&cov, |a| if a > 0.5 { 1.0 } else { 0.0 }); - drop(cov); - push_pull(gw, gh, ch, &mut px, &bin); - drop(bin); - // Laplacian of the colours, Gaussian of the weights. Planes move into the pyramids rather - // than being copied: with one image built at a time, a copy is a serial pass over it. - let mut lap: Vec<(usize, usize, Vec)> = Vec::new(); - let mut gau: Vec> = Vec::new(); - let (mut cw, mut chh, mut cur, mut cwt) = (gw, gh, px, wt); - for l in 0..levels { - if l + 1 == levels { - lap.push((cw, chh, cur)); - gau.push(cwt); - break; - } - let (nw, nh, down) = reduce(cw, chh, ch, &cur); - let up = expand(nw, nh, ch, &down, cw, chh); - lap.push((cw, chh, par_zip(&cur, &up, |a, b| a - b))); - let (_, _, wdown) = reduce(cw, chh, 1, &cwt); - gau.push(cwt); - cw = nw; - chh = nh; - cur = down; - cwt = wdown; - } - (gx0, gy0, lap, gau) - }; - // Build the bands a batch at a time and add each batch before building the next. Each pixel - // adds the bands in the same order as the serial loop (per level, bands one after another; - // batches follow each other in image order), but rows of a level are independent, so they - // run in parallel: every row walks the batch's bands itself. - let mut start = 0; - while start < imgs.len() { - let mut end = start + 1; - let mut bytes = cost(&imgs[start]); - while let Some(im) = imgs.get(end) - && bytes.saturating_add(cost(im)) <= budget - { - bytes = bytes.saturating_add(cost(im)); - end += 1; - } - let bands = par_map(end - start, |j| band(start + j)); - for l in 0..levels { - let pw = sizes[l].0; - par_rows(&mut wsum[l], pw, 1, |py, row| { - for b in &bands { - let Some((ox, lw, g, _)) = band_row(b, l, ch, py) else { continue }; - for x in 0..lw { - let px = ox + x; - if px >= pw { - break; - } - let k = g[x]; - if k <= 0.0 { - continue; - } - row[px] += k; - } - } - }); - par_rows(&mut acc[l], pw, ch, |py, row| { - for b in &bands { - let Some((ox, lw, g, band)) = band_row(b, l, ch, py) else { continue }; - for x in 0..lw { - let px = ox + x; - if px >= pw { - break; - } - let k = g[x]; - if k <= 0.0 { - continue; - } - for c in 0..ch { - row[px * ch + c] += k * band[x * ch + c]; - } - } - } - }); - } - start = end; - } - for l in 0..levels { - let pw = sizes[l].0; - let ws = &wsum[l]; - par_rows(&mut acc[l], pw, ch, |py, row| { - for x in 0..pw { - let k = ws[py * pw + x]; - for c in 0..ch { - row[x * ch + c] = if k > 1e-8 { row[x * ch + c] / k } else { 0.0 }; - } - } - }); - } - // Collapse. - // `levels ≥ 1`, so there is always a coarsest level. - let Some(mut cur) = acc.pop() else { return (vec![0.0; w * h * ch], vec![0.0; w * h]) }; - for l in (0..levels - 1).rev() { - let (pw, ph) = sizes[l]; - let (sw, sh) = sizes[l + 1]; - let up = expand(sw, sh, ch, &cur, pw, ph); - cur = par_zip(&acc[l], &up, |a, b| a + b); - } - // Coverage: union of the images. Rows are independent; each walks the images in order, so a - // pixel sees the same sequence of `max` calls as in the serial loop. - let mut cov = vec![0.0f32; w * h]; - par_rows(&mut cov, w, 1, |py, row| { - for im in imgs { - let y = py as i64 - im.y0 as i64; - if y < 0 || y as usize >= im.h { - continue; - } - for x in 0..im.w { - let px = im.x0 + x as i32; - if px < 0 || px as usize >= w { - continue; - } - let p = px as usize; - row[p] = row[p].max(im.alpha[y as usize * im.w + x]); - } - } - }); - (cur, cov) -} - #[cfg(test)] mod tests { use super::*; @@ -1677,407 +993,4 @@ mod tests { /// The row-parallel `reduce` / `expand` / `push_pull` / `multiband` against the serial code they /// replaced, kept below verbatim as the reference. Every output must stay bit for bit the same. #[cfg(test)] -mod parallel_tests { - use super::*; - - fn mix(mut z: u64) -> u64 { - z = z.wrapping_add(0x9E37_79B9_7F4A_7C15); - z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); - z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); - z ^ (z >> 31) - } - - /// Deterministic data from integer arithmetic only (no libm): mostly `0..1`, with negatives, - /// signed zeros and large values so a different order of operations cannot hide. - fn noise(len: usize, seed: u64) -> Vec { - (0..len as u64) - .map(|i| { - let z = mix(seed.wrapping_mul(0x1234_5678_9ABC).wrapping_add(i)); - let v = (z >> 40) as f32 / 16_777_216.0; - match z & 31 { - 0 => -v, - 1 => -0.0, - 2 => v * 1000.0, - 3 => 0.0, - _ => v, - } - }) - .collect() - } - - /// Weights with exact zeros, exact ones and partial values, in blobs and noise. - fn weights(w: usize, h: usize, seed: u64) -> Vec { - (0..w * h) - .map(|i| { - let (x, y) = (i % w, i / w); - let z = mix(seed + i as u64); - if (x / 5 + y / 3) % 3 == 0 { - 0.0 - } else if z.is_multiple_of(7) { - ((z >> 20) % 100) as f32 / 100.0 - } else { - 1.0 - } - }) - .collect() - } - - fn bits(v: &[f32]) -> Vec { - v.iter().map(|x| x.to_bits()).collect() - } - - fn fnv(parts: &[&[f32]]) -> u64 { - let mut h = 0xcbf2_9ce4_8422_2325u64; - for p in parts { - for x in *p { - h ^= x.to_bits() as u64; - h = h.wrapping_mul(0x0000_0100_0000_01b3); - } - } - h - } - - /// Sizes that cross the odd / even and tiny cases (1 wide, 1 high, 1×1, odd, power of two + 1). - const SIZES: [(usize, usize); 12] = [(1, 1), (1, 9), (9, 1), (2, 2), (3, 5), (4, 4), (17, 13), (64, 40), (65, 41), (97, 61), (130, 7), (7, 130)]; - - fn ref_reduce(w: usize, h: usize, ch: usize, src: &[f32]) -> (usize, usize, Vec) { - let (nw, nh) = (w.div_ceil(2), h.div_ceil(2)); - let k = [1.0f32, 4.0, 6.0, 4.0, 1.0]; - // Separable 5-tap binomial, then decimate. - let mut tmp = vec![0.0f32; nw * h * ch]; - for y in 0..h { - for x in 0..nw { - for c in 0..ch { - let mut s = 0.0; - for (t, kv) in k.iter().enumerate() { - let xx = (2 * x as i64 + t as i64 - 2).clamp(0, w as i64 - 1) as usize; - s += kv * src[(y * w + xx) * ch + c]; - } - tmp[(y * nw + x) * ch + c] = s / 16.0; - } - } - } - let mut out = vec![0.0f32; nw * nh * ch]; - for y in 0..nh { - for x in 0..nw { - for c in 0..ch { - let mut s = 0.0; - for (t, kv) in k.iter().enumerate() { - let yy = (2 * y as i64 + t as i64 - 2).clamp(0, h as i64 - 1) as usize; - s += kv * tmp[(yy * nw + x) * ch + c]; - } - out[(y * nw + x) * ch + c] = s / 16.0; - } - } - } - (nw, nh, out) - } - - fn ref_expand(sw: usize, sh: usize, ch: usize, src: &[f32], w: usize, h: usize) -> Vec { - // Bilinear upsampling at half-pixel-aligned positions. - let mut out = vec![0.0f32; w * h * ch]; - for y in 0..h { - let fy = ((y as f32 + 0.5) / 2.0 - 0.5).clamp(0.0, (sh - 1) as f32); - let (y0, ty) = (fy.floor() as usize, fy - fy.floor()); - let y1 = (y0 + 1).min(sh - 1); - for x in 0..w { - let fx = ((x as f32 + 0.5) / 2.0 - 0.5).clamp(0.0, (sw - 1) as f32); - let (x0, tx) = (fx.floor() as usize, fx - fx.floor()); - let x1 = (x0 + 1).min(sw - 1); - for c in 0..ch { - let p = |xx: usize, yy: usize| src[(yy * sw + xx) * ch + c]; - let top = p(x0, y0) + (p(x1, y0) - p(x0, y0)) * tx; - let bot = p(x0, y1) + (p(x1, y1) - p(x0, y1)) * tx; - out[(y * w + x) * ch + c] = top + (bot - top) * ty; - } - } - } - out - } - - fn ref_push_pull(w: usize, h: usize, ch: usize, px: &mut [f32], wt: &[f32]) { - if w <= 1 && h <= 1 { - return; - } - let (nw, nh) = (w.div_ceil(2), h.div_ceil(2)); - let mut cpx = vec![0.0f32; nw * nh * ch]; - let mut cw = vec![0.0f32; nw * nh]; - for y in 0..h { - for x in 0..w { - let (i, j) = (y * w + x, (y / 2) * nw + x / 2); - let a = wt[i]; - cw[j] += a; - for c in 0..ch { - cpx[j * ch + c] += a * px[i * ch + c]; - } - } - } - for j in 0..nw * nh { - if cw[j] > 0.0 { - for c in 0..ch { - cpx[j * ch + c] /= cw[j]; - } - cw[j] = 1.0; - } - } - if cw.contains(&0.0) && cw.iter().any(|v| *v > 0.0) { - ref_push_pull(nw, nh, ch, &mut cpx, &cw); - } - for y in 0..h { - for x in 0..w { - let i = y * w + x; - if wt[i] < 1.0 { - let j = (y / 2) * nw + x / 2; - let a = wt[i]; - for c in 0..ch { - px[i * ch + c] = a * px[i * ch + c] + (1.0 - a) * cpx[j * ch + c]; - } - } - } - } - } - - fn ref_multiband(w: usize, h: usize, imgs: &[RoiImage], weights: &[Vec], levels: usize) -> (Vec, Vec) { - let ch = imgs.first().map_or(1, |i| i.ch); - let levels = levels.max(1); - let align = 1i32 << (levels - 1); - // Level sizes of the panorama. - let mut sizes = vec![(w, h)]; - for _ in 1..levels { - let Some(&(pw, ph)) = sizes.last() else { break }; - sizes.push((pw.div_ceil(2), ph.div_ceil(2))); - } - let mut acc: Vec> = sizes.iter().map(|&(lw, lh)| vec![0.0; lw * lh * ch]).collect(); - let mut wsum: Vec> = sizes.iter().map(|&(lw, lh)| vec![0.0; lw * lh]).collect(); - let margin = align * 4; - // Each image on its ROI grown by a margin and aligned to the coarsest level's grid. - let bands = par_map(imgs.len(), |k| { - let im = &imgs[k]; - let gx0 = ((im.x0 - margin).max(0) / align) * align; - let gy0 = ((im.y0 - margin).max(0) / align) * align; - let gx1 = (im.x0 + im.w as i32 + margin).min(w as i32); - let gy1 = (im.y0 + im.h as i32 + margin).min(h as i32); - let (gw, gh) = ((gx1 - gx0).max(1) as usize, (gy1 - gy0).max(1) as usize); - let mut px = vec![0.0f32; gw * gh * ch]; - let mut cov = vec![0.0f32; gw * gh]; - let mut wt = vec![0.0f32; gw * gh]; - for y in 0..im.h { - for x in 0..im.w { - let (gx, gy) = (im.x0 + x as i32 - gx0, im.y0 + y as i32 - gy0); - if gx < 0 || gy < 0 || gx as usize >= gw || gy as usize >= gh { - continue; - } - let (i, g) = (y * im.w + x, gy as usize * gw + gx as usize); - cov[g] = im.alpha[i]; - wt[g] = weights[k][i] * im.alpha[i].min(1.0); - px[g * ch..(g + 1) * ch].copy_from_slice(&im.px[i * ch..(i + 1) * ch]); - } - } - let bin: Vec = cov.iter().map(|a| if *a > 0.5 { 1.0 } else { 0.0 }).collect(); - ref_push_pull(gw, gh, ch, &mut px, &bin); - // Laplacian of the colours, Gaussian of the weights. - let mut lap: Vec<(usize, usize, Vec)> = Vec::new(); - let mut gau: Vec> = Vec::new(); - let (mut cw, mut chh, mut cur, mut cwt) = (gw, gh, px, wt); - for l in 0..levels { - if l + 1 == levels { - lap.push((cw, chh, cur.clone())); - gau.push(cwt.clone()); - break; - } - let (nw, nh, down) = ref_reduce(cw, chh, ch, &cur); - let up = ref_expand(nw, nh, ch, &down, cw, chh); - lap.push((cw, chh, cur.iter().zip(&up).map(|(a, b)| a - b).collect())); - gau.push(cwt.clone()); - let (_, _, wdown) = ref_reduce(cw, chh, 1, &cwt); - cw = nw; - chh = nh; - cur = down; - cwt = wdown; - } - (gx0, gy0, lap, gau) - }); - for (gx0, gy0, lap, gau) in &bands { - for (l, ((lw, lh, band), g)) in lap.iter().zip(gau).enumerate() { - let (ox, oy) = ((gx0 >> l) as usize, (gy0 >> l) as usize); - let (pw, ph) = sizes[l]; - for y in 0..*lh { - let py = oy + y; - if py >= ph { - break; - } - for x in 0..*lw { - let px = ox + x; - if px >= pw { - break; - } - let (i, p) = (y * lw + x, py * pw + px); - let k = g[i]; - if k <= 0.0 { - continue; - } - wsum[l][p] += k; - for c in 0..ch { - acc[l][p * ch + c] += k * band[i * ch + c]; - } - } - } - } - } - for l in 0..levels { - let (pw, ph) = sizes[l]; - for p in 0..pw * ph { - let k = wsum[l][p]; - for c in 0..ch { - acc[l][p * ch + c] = if k > 1e-8 { acc[l][p * ch + c] / k } else { 0.0 }; - } - } - } - // Collapse. - // `levels ≥ 1`, so there is always a coarsest level. - let Some(mut cur) = acc.pop() else { return (vec![0.0; w * h * ch], vec![0.0; w * h]) }; - for l in (0..levels - 1).rev() { - let (pw, ph) = sizes[l]; - let (sw, sh) = sizes[l + 1]; - let up = ref_expand(sw, sh, ch, &cur, pw, ph); - cur = acc[l].iter().zip(&up).map(|(a, b)| a + b).collect(); - } - // Coverage: union of the images. - let mut cov = vec![0.0f32; w * h]; - for im in imgs { - for y in 0..im.h { - for x in 0..im.w { - let (px, py) = (im.x0 + x as i32, im.y0 + y as i32); - if px < 0 || py < 0 || px as usize >= w || py as usize >= h { - continue; - } - let p = py as usize * w + px as usize; - cov[p] = cov[p].max(im.alpha[y * im.w + x]); - } - } - } - (cur, cov) - } - - #[test] - fn reduce_and_expand_match_the_serial_code() { - for (n, &(w, h)) in SIZES.iter().enumerate() { - for ch in [1usize, 3, 4] { - let src = noise(w * h * ch, n as u64 * 7 + ch as u64); - let (nw, nh, got) = reduce(w, h, ch, &src); - let (rw, rh, want) = ref_reduce(w, h, ch, &src); - assert_eq!((nw, nh), (rw, rh)); - assert_eq!(bits(&got), bits(&want), "reduce {w}x{h}x{ch}"); - // Expand back to the original size and to sizes that are not twice the source's. - for (ew, eh) in [(w, h), (2 * nw, 2 * nh), (2 * nw - 1, 2 * nh + 1), (w + 3, h + 5)] { - let got = expand(nw, nh, ch, &want, ew, eh); - let want_up = ref_expand(nw, nh, ch, &want, ew, eh); - assert_eq!(bits(&got), bits(&want_up), "expand {nw}x{nh}x{ch} to {ew}x{eh}"); - } - } - } - } - - #[test] - fn push_pull_matches_the_serial_code() { - for (n, &(w, h)) in SIZES.iter().enumerate() { - for ch in [1usize, 3] { - for variant in 0..3u64 { - let wt = match variant { - 0 => weights(w, h, n as u64), - 1 => vec![1.0; w * h], - // A single covered pixel: every level of the recursion has to fill from it. - _ => (0..w * h).map(|i| if i == (w * h) / 3 { 1.0 } else { 0.0 }).collect(), - }; - let px = noise(w * h * ch, 100 + n as u64); - let (mut got, mut want) = (px.clone(), px); - push_pull(w, h, ch, &mut got, &wt); - ref_push_pull(w, h, ch, &mut want, &wt); - assert_eq!(bits(&got), bits(&want), "push_pull {w}x{h}x{ch} variant {variant}"); - } - } - } - } - - /// ROIs of assorted sizes and offsets (some sticking out of the canvas), with holes in the alpha. - fn rois(w: usize, h: usize, ch: usize, seed: u64) -> (Vec, Vec>) { - let specs = - [(0i32, 0i32, w * 2 / 3, h), (w as i32 / 3, -(h as i32) / 5, w * 2 / 3 + 1, h * 3 / 4 + 1), (-(w as i32) / 4, h as i32 / 2, w / 2 + 1, h / 2 + 3)]; - let imgs: Vec = specs - .iter() - .enumerate() - .map(|(k, &(x0, y0, iw, ih))| { - let (iw, ih) = (iw.max(1), ih.max(1)); - let mut alpha = vec![1.0f32; iw * ih]; - for (i, a) in alpha.iter_mut().enumerate() { - let z = mix(seed + k as u64 * 1000 + i as u64); - if (i % iw) / 4 % 5 == 2 && (i / iw) % 6 < 3 { - *a = 0.0; - } else if z.is_multiple_of(11) { - *a = 0.3; - } - } - RoiImage { x0, y0, w: iw, h: ih, ch, px: noise(iw * ih * ch, seed + k as u64), alpha } - }) - .collect(); - let wts = imgs.iter().enumerate().map(|(k, r)| weights(r.w, r.h, seed + 50 + k as u64)).collect(); - (imgs, wts) - } - - #[test] - fn multiband_matches_the_serial_code() { - for (n, &(w, h)) in [(1usize, 1usize), (5, 3), (40, 30), (97, 61), (130, 70), (64, 64), (201, 129)].iter().enumerate() { - for ch in [1usize, 3] { - let (imgs, wts) = rois(w, h, ch, n as u64 * 31 + ch as u64); - for levels in [1usize, 2, 3, 5, 7] { - let got = multiband(w, h, &imgs, &wts, levels); - let want = ref_multiband(w, h, &imgs, &wts, levels); - assert_eq!(bits(&got.0), bits(&want.0), "colours {w}x{h}x{ch} levels {levels}"); - assert_eq!(bits(&got.1), bits(&want.1), "coverage {w}x{h}x{ch} levels {levels}"); - } - } - } - // No images at all, and zero levels. - assert_eq!(multiband(9, 7, &[], &[], 3).0.len(), ref_multiband(9, 7, &[], &[], 3).0.len()); - } - - /// Batching the bands (#7758) changes when they are built, not the result. Budgets from none - /// (one image per batch) up to everything in steps of a fifth pass through every split of the - /// three images. - #[test] - fn multiband_batches_match_the_serial_code() { - let budgets: Vec = - std::iter::successors(Some(1024.0f64), |b| Some(b * 1.2)).take_while(|b| *b < 4e6).map(|b| b as usize).chain([0, usize::MAX]).collect(); - for (n, &(w, h)) in [(40usize, 30usize), (97, 61), (201, 129)].iter().enumerate() { - for ch in [1usize, 3] { - let (imgs, wts) = rois(w, h, ch, n as u64 * 17 + ch as u64); - for levels in [1usize, 3, 5] { - let want = ref_multiband(w, h, &imgs, &wts, levels); - for &budget in &budgets { - let got = multiband_batched(w, h, &imgs, &wts, levels, budget); - assert_eq!(bits(&got.0), bits(&want.0), "colours {w}x{h}x{ch} levels {levels} budget {budget}"); - assert_eq!(bits(&got.1), bits(&want.1), "coverage {w}x{h}x{ch} levels {levels} budget {budget}"); - } - } - } - } - } - - /// Hashes recorded from the code before it was made parallel (plain f32 arithmetic only, so - /// they hold on every platform). - #[test] - fn multiband_hashes_recorded_from_the_serial_code() { - let (imgs, wts) = rois(97, 61, 3, 5); - let (px, cov) = multiband(97, 61, &imgs, &wts, 5); - assert_eq!(fnv(&[&px, &cov]), 0xf89a5726082ebb6c, "97x61 rgb, 5 levels"); - let (imgs, wts) = rois(130, 70, 1, 9); - let (px, cov) = multiband(130, 70, &imgs, &wts, 7); - assert_eq!(fnv(&[&px, &cov]), 0xb7d7ddc59d201730, "130x70 grey, 7 levels"); - let wt = weights(65, 41, 3); - let mut px = noise(65 * 41 * 3, 4); - push_pull(65, 41, 3, &mut px, &wt); - assert_eq!(fnv(&[&px]), 0x50ea36a84ca9a68f, "push_pull 65x41 rgb"); - let (nw, nh, r) = reduce(65, 41, 3, &px); - assert_eq!(fnv(&[&r, &expand(nw, nh, 3, &r, 65, 41)]), 0x51823acfb4206dd8, "reduce + expand 65x41 rgb"); - } -} +mod parallel_tests; diff --git a/crates/algo/src/panorama/blend.rs b/crates/algo/src/panorama/blend.rs new file mode 100644 index 0000000000..1aaa821c14 --- /dev/null +++ b/crates/algo/src/panorama/blend.rs @@ -0,0 +1,692 @@ +use super::*; + +// ---------- photometric ---------- + +/// One image warped into the panorama: an axis-aligned region with colour channels and coverage. +#[derive(Clone, Debug)] +pub struct RoiImage { + pub x0: i32, + pub y0: i32, + pub w: usize, + pub h: usize, + /// Colour channels per pixel (no alpha). + pub ch: usize, + pub px: Vec, + /// Coverage `0..=1`. + pub alpha: Vec, +} + +impl RoiImage { + fn at(&self, x: i32, y: i32) -> Option { + let (lx, ly) = (x - self.x0, y - self.y0); + (lx >= 0 && ly >= 0 && (lx as usize) < self.w && (ly as usize) < self.h).then(|| ly as usize * self.w + lx as usize) + } +} + +/// Placements and source sizes (for the vignetting radius). +pub type Geometry<'a> = (&'a [Placement], &'a [(usize, usize)]); + +/// Gains (per image, per channel) and the vignetting model found by [`photometric`]. +#[derive(Clone, Debug, PartialEq)] +pub struct Photometric { + pub gains: Vec>, + /// `log V(r) = a·r² + b·r⁴`, `r` = distance from the image centre over the half diagonal. + pub vignette: [f64; 2], +} + +impl Photometric { + /// Multiplier that corrects a pixel of image `i` at normalised squared radius `r2`. + pub fn factor(&self, i: usize, c: usize, r2: f64) -> f32 { + let v = (self.vignette[0] * r2 + self.vignette[1] * r2 * r2).exp(); + (1.0 / (self.gains[i][c] as f64 * v)) as f32 + } +} + +/// Estimates exposure gains (`gain`) and a shared vignetting falloff (`vignette`) from the +/// overlaps of `imgs` (`placements`/`sizes` give each panorama pixel's source radius). +/// Without `geometry` (placements and source sizes) the vignetting model is not estimated. +pub fn photometric(imgs: &[RoiImage], geometry: Option, gain: bool, vignette: bool) -> Photometric { + let vignette = vignette && geometry.is_some(); + let n = imgs.len(); + let ch = imgs.first().map_or(1, |i| i.ch); + let identity = Photometric { gains: vec![vec![1.0; ch]; n], vignette: [0.0, 0.0] }; + if n == 0 || (!gain && !vignette) { + return identity; + } + // Overlap samples on a grid: (a, b, colours, radii²). + let (mut x0, mut y0, mut x1, mut y1) = (i32::MAX, i32::MAX, i32::MIN, i32::MIN); + for im in imgs { + x0 = x0.min(im.x0); + y0 = y0.min(im.y0); + x1 = x1.max(im.x0 + im.w as i32); + y1 = y1.max(im.y0 + im.h as i32); + } + let step = (((x1 - x0) as i64 * (y1 - y0) as i64 / 40_000).max(1) as f64).sqrt().ceil() as i32; + let r2_of = |i: usize, u: i32, v: i32| -> Option { + let Some((placements, sizes)) = geometry else { return Some(0.0) }; + let (sx, sy) = placements[i].inverse(u as f64 + 0.5, v as f64 + 0.5)?; + let (w, h) = (sizes[i].0 as f64, sizes[i].1 as f64); + let (dx, dy) = (sx - w / 2.0, sy - h / 2.0); + Some((dx * dx + dy * dy) / (w * w / 4.0 + h * h / 4.0)) + }; + type Sample = (usize, usize, Vec, Vec, f64, f64); + let mut samples: Vec = Vec::new(); + let mut y = y0; + while y < y1 { + let mut x = x0; + while x < x1 { + let cover: Vec<(usize, usize)> = (0..n).filter_map(|i| imgs[i].at(x, y).filter(|&k| imgs[i].alpha[k] > 0.999).map(|k| (i, k))).collect(); + for p in 0..cover.len() { + for q in p + 1..cover.len() { + let ((a, ka), (b, kb)) = (cover[p], cover[q]); + let ca = imgs[a].px[ka * ch..(ka + 1) * ch].to_vec(); + let cb = imgs[b].px[kb * ch..(kb + 1) * ch].to_vec(); + if ca.iter().chain(&cb).any(|v| !(0.02..=0.98).contains(v)) { + continue; + } + // Disagreeing content (parallax, moving objects) says nothing about exposure. + if ca.iter().zip(&cb).any(|(x, y)| (x / y).ln().abs() > 1.0) { + continue; + } + let (Some(ra), Some(rb)) = (r2_of(a, x, y), r2_of(b, x, y)) else { continue }; + samples.push((a, b, ca, cb, ra, rb)); + } + } + x += step; + } + y += step; + } + if samples.len() < 20 { + return identity; + } + // Unknowns: log gain per image (per channel), then a, b (shared, from mean log intensity). + let sigma_n = 0.05; + let sigma_g = if gain { 0.15 } else { 1e-4 }; + let mut out = identity.clone(); + let nv = if vignette { 2 } else { 0 }; + // Vignetting is solved on the channel mean, then gains per channel with it fixed. + let mut ne = Normal::new(n + nv); + for (a, b, ca, cb, ra, rb) in &samples { + let la = ca.iter().map(|v| (*v as f64).ln()).sum::() / ch as f64; + let lb = cb.iter().map(|v| (*v as f64).ln()).sum::() / ch as f64; + let mut row = vec![(*a, 1.0), (*b, -1.0)]; + if vignette { + row.push((n, ra - rb)); + row.push((n + 1, ra * ra - rb * rb)); + } + ne.add(&row, la - lb, 1.0 / sigma_n); + } + for i in 0..n { + ne.add(&[(i, 1.0)], 0.0, 1.0 / sigma_g); + } + if vignette { + ne.add(&[(n, 1.0)], 0.0, 0.5); + ne.add(&[(n + 1, 1.0)], 0.0, 0.5); + } + let Some(sol) = ne.solve() else { return out }; + if vignette { + // Vignetting only darkens; clamp a runaway brightening fit. + out.vignette = [sol[n].clamp(-2.0, 0.5), sol[n + 1].clamp(-2.0, 2.0)]; + } + if gain { + for c in 0..ch { + let mut ne = Normal::new(n); + for (a, b, ca, cb, ra, rb) in &samples { + let va = out.vignette[0] * ra + out.vignette[1] * ra * ra; + let vb = out.vignette[0] * rb + out.vignette[1] * rb * rb; + ne.add(&[(*a, 1.0), (*b, -1.0)], ((ca[c] as f64).ln() - va) - ((cb[c] as f64).ln() - vb), 1.0 / sigma_n); + } + for i in 0..n { + ne.add(&[(i, 1.0)], 0.0, 1.0 / sigma_g); + } + if let Some(g) = ne.solve() { + for i in 0..n { + out.gains[i][c] = g[i].exp().clamp(0.2, 5.0) as f32; + } + } + } + } + out +} + +// ---------- seams ---------- + +/// Seam labels on a `w × h` grid (`-1` = no image): images are added in `order`; each new image +/// takes the part of its overlap with the composite that lies on its side of the cheapest path +/// through the overlap (cost = colour difference). +pub fn seam_labels(w: usize, h: usize, luma: &[Vec], cover: &[Vec], order: &[usize]) -> Vec { + let mut label = vec![-1i32; w * h]; + for &img in order { + let cov = &cover[img]; + let mut overlap = vec![false; w * h]; + let (mut sx, mut sy, mut no) = (0.0f64, 0.0f64, 0usize); + let (mut nx, mut ny, mut nn) = (0.0f64, 0.0f64, 0usize); + for i in 0..w * h { + if !cov[i] { + continue; + } + nx += (i % w) as f64; + ny += (i / w) as f64; + nn += 1; + if label[i] >= 0 { + overlap[i] = true; + sx += (i % w) as f64; + sy += (i / w) as f64; + no += 1; + } else { + label[i] = img as i32; + } + } + if no == 0 { + continue; + } + let (cx, cy) = (nx / nn as f64, ny / nn as f64); + let contained = nn == no; + let (ox, oy) = if contained { + // Wholly inside the composite (#5745: two photos in one document, the second moved + // by Auto-Align so the canvas crops it to the part over the first). Its side of the + // seam is the one it lies towards from the composite's centre; an image centred on + // the composite has no side, and the earlier images keep it. + let (mut px, mut py, mut pn) = (0.0f64, 0.0f64, 0usize); + for (i, l) in label.iter().enumerate() { + if *l >= 0 { + px += (i % w) as f64; + py += (i / w) as f64; + pn += 1; + } + } + let (px, py) = (px / pn.max(1) as f64, py / pn.max(1) as f64); + if (cx - px).abs() < 0.5 && (cy - py).abs() < 0.5 { + continue; + } + (px, py) + } else { + (sx / no as f64, sy / no as f64) + }; + let vertical = (cx - ox).abs() >= (cy - oy).abs(); + // Image on the increasing side along the seam's cross axis? + let positive = if vertical { cx > ox } else { cy > oy }; + // A contained image has no pixels of its own, so a seam on its outer edge would leave it + // nothing: break cost ties away from its side (towards larger k when it lies on the + // decreasing side) so it keeps its side of the overlap. + let prefer_high = contained && !positive; + let cost = |i: usize| -> f32 { 0.002 + (luma[img][i] - luma[label[i] as usize][i]).abs() }; + let (lines, len) = if vertical { (h, w) } else { (w, h) }; + let idx = |line: usize, k: usize| if vertical { line * w + k } else { k * w + line }; + // DP over lines (rows for a vertical seam), within the overlap. + let mut acc = vec![f32::INFINITY; w * h]; + let mut from = vec![usize::MAX; w * h]; + let mut prev_line: Option = None; + for line in 0..lines { + let any = (0..len).any(|k| overlap[idx(line, k)]); + if !any { + continue; + } + for k in 0..len { + let i = idx(line, k); + if !overlap[i] { + continue; + } + let mut best = (0.0f32, usize::MAX); + if let Some(pl) = prev_line.filter(|pl| *pl + 1 == line) { + best = (f32::INFINITY, usize::MAX); + let dks = if prefer_high { [1i64, 0, -1] } else { [-1i64, 0, 1] }; + for dk in dks { + let kk = k as i64 + dk; + if kk < 0 || kk >= len as i64 { + continue; + } + let j = idx(pl, kk as usize); + if acc[j] < best.0 { + best = (acc[j], kk as usize); + } + } + if best.1 == usize::MAX { + best = (0.0, usize::MAX); + } + } + acc[i] = best.0 + cost(i); + from[i] = best.1; + } + prev_line = Some(line); + } + // Backtrack from the cheapest end; lines not reached keep their own best cell. + let mut seam = vec![usize::MAX; lines]; + let mut line = lines; + while line > 0 { + line -= 1; + if seam[line] != usize::MAX { + continue; + } + let Some(k) = (0..len) + .filter(|&k| overlap[idx(line, k)]) + .min_by(|&a, &b| acc[idx(line, a)].total_cmp(&acc[idx(line, b)]).then(if prefer_high { b.cmp(&a) } else { a.cmp(&b) })) + else { + continue; + }; + let (mut l, mut k) = (line, k); + loop { + seam[l] = k; + let f = from[idx(l, k)]; + if f == usize::MAX || l == 0 { + break; + } + l -= 1; + if seam[l] != usize::MAX { + break; + } + k = f; + } + } + for line in 0..lines { + let s = seam[line]; + if s == usize::MAX { + continue; + } + let on_side = |k: usize| if positive { k > s } else { k < s }; + // A contained image has no other cells, so where the overlap has nothing on its side + // of the seam (a line one cell wide) it takes the seam cell rather than nothing. + let take_seam = contained && !(0..len).any(|k| overlap[idx(line, k)] && on_side(k)); + for k in 0..len { + let i = idx(line, k); + if overlap[i] && (on_side(k) || (take_seam && k == s)) { + label[i] = img as i32; + } + } + } + } + label +} + +// ---------- multi-band blending ---------- + +/// Number of pyramid levels used by [`multiband`] for a seam mask of this size. +pub fn blend_levels(w: usize, h: usize) -> usize { + let mut s = w.min(h); + let mut n = 1; + while s > 16 && n < 7 { + s /= 2; + n += 1; + } + n +} + +/// `a[i] ⊕ b[i]` for every `i` (the shorter length wins, like `zip`), in parallel on native +/// targets. Purely elementwise, so the result is the serial result bit for bit. +fn par_zip(a: &[f32], b: &[f32], f: impl Fn(f32, f32) -> f32 + Sync + Send) -> Vec { + const CHUNK: usize = 1 << 14; + let mut out = vec![0.0f32; a.len().min(b.len())]; + let fill = |o: &mut [f32], a: &[f32], b: &[f32]| { + for ((o, &a), &b) in o.iter_mut().zip(a).zip(b) { + *o = f(a, b); + } + }; + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + out.par_chunks_mut(CHUNK).zip(a.par_chunks(CHUNK)).zip(b.par_chunks(CHUNK)).for_each(|((o, a), b)| fill(o, a, b)); + } + #[cfg(target_arch = "wasm32")] + out.chunks_mut(CHUNK).zip(a.chunks(CHUNK)).zip(b.chunks(CHUNK)).for_each(|((o, a), b)| fill(o, a, b)); + out +} + +/// `f(a[i])` for every `i`, in parallel on native targets (elementwise, so bit for bit serial). +fn par_map1(a: &[f32], f: impl Fn(f32) -> f32 + Sync + Send) -> Vec { + par_zip(a, a, |x, _| f(x)) +} + +// `reduce`, `expand` and `push_pull` run one pyramid level for one image at a time, and the +// images themselves only fill part of a many-core machine, so each of them also runs its rows +// in parallel. Every output element is computed by the same expression, in the same order, as +// the one-thread loops they replace (rows never read each other's output), so the result is +// bit for bit unchanged. + +pub(super) fn reduce(w: usize, h: usize, ch: usize, src: &[f32]) -> (usize, usize, Vec) { + let (nw, nh) = (w.div_ceil(2), h.div_ceil(2)); + let k = [1.0f32, 4.0, 6.0, 4.0, 1.0]; + // Separable 5-tap binomial, then decimate. + let mut tmp = vec![0.0f32; nw * h * ch]; + par_rows(&mut tmp, nw, ch, |y, row| { + let line = &src[y * w * ch..(y + 1) * w * ch]; + for x in 0..nw { + // The clamped source column of each tap is the same for every channel. + let xs: [usize; 5] = std::array::from_fn(|t| (2 * x as i64 + t as i64 - 2).clamp(0, w as i64 - 1) as usize * ch); + for c in 0..ch { + let mut s = 0.0; + for (kv, xx) in k.iter().zip(xs) { + s += kv * line[xx + c]; + } + row[x * ch + c] = s / 16.0; + } + } + }); + let mut out = vec![0.0f32; nw * nh * ch]; + par_rows(&mut out, nw, ch, |y, row| { + // Each output row is five source rows added in tap order: the same sum per element as + // before (`0 + k0·a + k1·b + …`), but over whole rows so it vectorises. + for (t, kv) in k.iter().enumerate() { + let yy = (2 * y as i64 + t as i64 - 2).clamp(0, h as i64 - 1) as usize; + for (o, &v) in row.iter_mut().zip(&tmp[yy * nw * ch..(yy + 1) * nw * ch]) { + *o += kv * v; + } + } + for o in row.iter_mut() { + *o /= 16.0; + } + }); + (nw, nh, out) +} + +pub(super) fn expand(sw: usize, sh: usize, ch: usize, src: &[f32], w: usize, h: usize) -> Vec { + // Bilinear upsampling at half-pixel-aligned positions. + let mut out = vec![0.0f32; w * h * ch]; + // Source columns and weights depend on x only: worked out once instead of for every row. + // The clamped position is never negative, so truncating is `floor` (and spares the libm call). + let cols: Vec<(usize, usize, f32)> = (0..w) + .map(|x| { + let fx = ((x as f32 + 0.5) / 2.0 - 0.5).clamp(0.0, (sw - 1) as f32); + let x0 = fx as usize; + (x0 * ch, (x0 + 1).min(sw - 1) * ch, fx - x0 as f32) + }) + .collect(); + par_rows(&mut out, w, ch, |y, row| { + let fy = ((y as f32 + 0.5) / 2.0 - 0.5).clamp(0.0, (sh - 1) as f32); + let y0 = fy as usize; + let ty = fy - y0 as f32; + let y1 = (y0 + 1).min(sh - 1); + let (r0, r1) = (&src[y0 * sw * ch..(y0 + 1) * sw * ch], &src[y1 * sw * ch..(y1 + 1) * sw * ch]); + for (px, &(x0, x1, tx)) in row.chunks_exact_mut(ch.max(1)).zip(&cols) { + for (c, o) in px.iter_mut().enumerate() { + let top = r0[x0 + c] + (r0[x1 + c] - r0[x0 + c]) * tx; + let bot = r1[x0 + c] + (r1[x1 + c] - r1[x0 + c]) * tx; + *o = top + (bot - top) * ty; + } + } + }); + out +} + +/// Fills pixels with zero `wt` from their surroundings (push-pull), so pyramid levels don't +/// pull in black from outside an image. +pub(super) fn push_pull(w: usize, h: usize, ch: usize, px: &mut [f32], wt: &[f32]) { + if w <= 1 && h <= 1 { + return; + } + let (nw, nh) = (w.div_ceil(2), h.div_ceil(2)); + // Coarse sums. A coarse row is fed by two fine rows; walking them in raster order adds each + // coarse cell's (up to) four fine pixels in the order the serial scatter-add did, from zero. + let mut cpx = vec![0.0f32; nw * nh * ch]; + let mut cw = vec![0.0f32; nw * nh]; + par_rows(&mut cw, nw, 1, |cy, row| { + for y in 2 * cy..(2 * cy + 2).min(h) { + for (x, &a) in wt[y * w..(y + 1) * w].iter().enumerate() { + row[x / 2] += a; + } + } + }); + let px_in: &[f32] = px; + par_rows(&mut cpx, nw, ch, |cy, row| { + for y in 2 * cy..(2 * cy + 2).min(h) { + for x in 0..w { + let (i, j) = (y * w + x, x / 2); + let a = wt[i]; + for c in 0..ch { + row[j * ch + c] += a * px_in[i * ch + c]; + } + } + } + }); + // Normalise by the weight (this reads `cw` before it is reset to 0 / 1 below). + par_rows(&mut cpx, nw, ch, |cy, row| { + for cx in 0..nw { + let wj = cw[cy * nw + cx]; + if wj > 0.0 { + for c in 0..ch { + row[cx * ch + c] /= wj; + } + } + } + }); + for v in cw.iter_mut() { + if *v > 0.0 { + *v = 1.0; + } + } + if cw.contains(&0.0) && cw.iter().any(|v| *v > 0.0) { + push_pull(nw, nh, ch, &mut cpx, &cw); + } + par_rows(px, w, ch, |y, row| { + for x in 0..w { + let i = y * w + x; + if wt[i] < 1.0 { + let j = (y / 2) * nw + x / 2; + let a = wt[i]; + for c in 0..ch { + row[x * ch + c] = a * row[x * ch + c] + (1.0 - a) * cpx[j * ch + c]; + } + } + } + }); +} + +/// One image's pyramid in [`multiband`]: the grid origin `(gx0, gy0)` at level 0, the Laplacian +/// levels `(w, h, colours)` and the Gaussian weight levels. +type PyramidBand = (i32, i32, Vec<(usize, usize, Vec)>, Vec>); + +/// The part of `band` on panorama row `py` of level `l`: the panorama column its first pixel +/// lands on, its width, its weight row and its colour row. `None` when it misses the row. +fn band_row(band: &PyramidBand, l: usize, ch: usize, py: usize) -> Option<(usize, usize, &[f32], &[f32])> { + let (ox, oy) = ((band.0 >> l) as usize, (band.1 >> l) as usize); + let (lw, lh, colours) = &band.2[l]; + (py >= oy && py - oy < *lh).then(|| { + let y = py - oy; + (ox, *lw, &band.3[l][y * lw..(y + 1) * lw], &colours[y * lw * ch..(y + 1) * lw * ch]) + }) +} + +/// Estimated bytes of band construction [`multiband`] keeps in flight at once. Images are built +/// and accumulated in batches under it, so its peak memory doesn't grow with the image count +/// (#7758). Four 24 MP RGB sources (~1.2 GB each) fit in one batch: building bands side by side +/// uses a many-core machine better than one band's row-parallel work, and one at a time made the +/// usual 2–4 image Photomerge 12–36% slower on a 32-thread desktop. +#[cfg(not(target_arch = "wasm32"))] +const BAND_BUDGET: usize = 5 << 30; + +/// Without threads the bands of a batch are built one after another anyway, so each is added as +/// soon as it is built (the browser's address space is 4 GB). +#[cfg(target_arch = "wasm32")] +const BAND_BUDGET: usize = 0; + +/// Multi-band blend of `imgs` into a `w × h` panorama (origin 0,0) with one weight map per image +/// over the same grid as its ROI (`weights[i]` has `w_i × h_i` entries). Returns the colour +/// channels (`ch` per pixel) and the total coverage. +pub fn multiband(w: usize, h: usize, imgs: &[RoiImage], weights: &[Vec], levels: usize) -> (Vec, Vec) { + multiband_batched(w, h, imgs, weights, levels, BAND_BUDGET) +} + +/// [`multiband`], building at most `budget` estimated bytes of bands at a time (at least one +/// image). Each pixel still adds the bands in image order, so the result doesn't depend on it. +pub(super) fn multiband_batched(w: usize, h: usize, imgs: &[RoiImage], weights: &[Vec], levels: usize, budget: usize) -> (Vec, Vec) { + let ch = imgs.first().map_or(1, |i| i.ch); + let levels = levels.max(1); + let align = 1i32 << (levels - 1); + // Level sizes of the panorama. + let mut sizes = vec![(w, h)]; + for _ in 1..levels { + let Some(&(pw, ph)) = sizes.last() else { break }; + sizes.push((pw.div_ceil(2), ph.div_ceil(2))); + } + let mut acc: Vec> = sizes.iter().map(|&(lw, lh)| vec![0.0; lw * lh * ch]).collect(); + let mut wsum: Vec> = sizes.iter().map(|&(lw, lh)| vec![0.0; lw * lh]).collect(); + let margin = align * 4; + // Each image on its ROI grown by a margin and aligned to the coarsest level's grid. + let grid = |im: &RoiImage| { + let gx0 = ((im.x0 - margin).max(0) / align) * align; + let gy0 = ((im.y0 - margin).max(0) / align) * align; + let gx1 = (im.x0 + im.w as i32 + margin).min(w as i32); + let gy1 = (im.y0 + im.h as i32 + margin).min(h as i32); + (gx0, gy0, (gx1 - gx0).max(1) as usize, (gy1 - gy0).max(1) as usize) + }; + // Building one band holds its grid's colour and weight planes about three times over: the + // pyramids are 4/3 of a plane, and the grid copy, coverage and `expand` scratch come on top. + let cost = |im: &RoiImage| { + let (_, _, gw, gh) = grid(im); + gw.saturating_mul(gh).saturating_mul(ch + 1).saturating_mul(4 * 3) + }; + let band = |k: usize| -> PyramidBand { + let im = &imgs[k]; + let (gx0, gy0, gw, gh) = grid(im); + // Each grid pixel takes the image pixel that lands on it (every image pixel lands on at + // most one), so rows of the grid are independent and fill in parallel. + let src_of = |gx: usize, gy: usize| -> Option { + let (x, y) = (gx as i64 + gx0 as i64 - im.x0 as i64, gy as i64 + gy0 as i64 - im.y0 as i64); + (x >= 0 && y >= 0 && (x as usize) < im.w && (y as usize) < im.h).then(|| y as usize * im.w + x as usize) + }; + let mut px = vec![0.0f32; gw * gh * ch]; + par_rows(&mut px, gw, ch, |gy, row| { + for gx in 0..gw { + if let Some(i) = src_of(gx, gy) { + row[gx * ch..(gx + 1) * ch].copy_from_slice(&im.px[i * ch..(i + 1) * ch]); + } + } + }); + let mut cov = vec![0.0f32; gw * gh]; + par_rows(&mut cov, gw, 1, |gy, row| { + for (gx, o) in row.iter_mut().enumerate() { + if let Some(i) = src_of(gx, gy) { + *o = im.alpha[i]; + } + } + }); + let mut wt = vec![0.0f32; gw * gh]; + par_rows(&mut wt, gw, 1, |gy, row| { + for (gx, o) in row.iter_mut().enumerate() { + if let Some(i) = src_of(gx, gy) { + *o = weights[k][i] * im.alpha[i].min(1.0); + } + } + }); + let bin: Vec = par_map1(&cov, |a| if a > 0.5 { 1.0 } else { 0.0 }); + drop(cov); + push_pull(gw, gh, ch, &mut px, &bin); + drop(bin); + // Laplacian of the colours, Gaussian of the weights. Planes move into the pyramids rather + // than being copied: with one image built at a time, a copy is a serial pass over it. + let mut lap: Vec<(usize, usize, Vec)> = Vec::new(); + let mut gau: Vec> = Vec::new(); + let (mut cw, mut chh, mut cur, mut cwt) = (gw, gh, px, wt); + for l in 0..levels { + if l + 1 == levels { + lap.push((cw, chh, cur)); + gau.push(cwt); + break; + } + let (nw, nh, down) = reduce(cw, chh, ch, &cur); + let up = expand(nw, nh, ch, &down, cw, chh); + lap.push((cw, chh, par_zip(&cur, &up, |a, b| a - b))); + let (_, _, wdown) = reduce(cw, chh, 1, &cwt); + gau.push(cwt); + cw = nw; + chh = nh; + cur = down; + cwt = wdown; + } + (gx0, gy0, lap, gau) + }; + // Build the bands a batch at a time and add each batch before building the next. Each pixel + // adds the bands in the same order as the serial loop (per level, bands one after another; + // batches follow each other in image order), but rows of a level are independent, so they + // run in parallel: every row walks the batch's bands itself. + let mut start = 0; + while start < imgs.len() { + let mut end = start + 1; + let mut bytes = cost(&imgs[start]); + while let Some(im) = imgs.get(end) + && bytes.saturating_add(cost(im)) <= budget + { + bytes = bytes.saturating_add(cost(im)); + end += 1; + } + let bands = par_map(end - start, |j| band(start + j)); + for l in 0..levels { + let pw = sizes[l].0; + par_rows(&mut wsum[l], pw, 1, |py, row| { + for b in &bands { + let Some((ox, lw, g, _)) = band_row(b, l, ch, py) else { continue }; + for x in 0..lw { + let px = ox + x; + if px >= pw { + break; + } + let k = g[x]; + if k <= 0.0 { + continue; + } + row[px] += k; + } + } + }); + par_rows(&mut acc[l], pw, ch, |py, row| { + for b in &bands { + let Some((ox, lw, g, band)) = band_row(b, l, ch, py) else { continue }; + for x in 0..lw { + let px = ox + x; + if px >= pw { + break; + } + let k = g[x]; + if k <= 0.0 { + continue; + } + for c in 0..ch { + row[px * ch + c] += k * band[x * ch + c]; + } + } + } + }); + } + start = end; + } + for l in 0..levels { + let pw = sizes[l].0; + let ws = &wsum[l]; + par_rows(&mut acc[l], pw, ch, |py, row| { + for x in 0..pw { + let k = ws[py * pw + x]; + for c in 0..ch { + row[x * ch + c] = if k > 1e-8 { row[x * ch + c] / k } else { 0.0 }; + } + } + }); + } + // Collapse. + // `levels ≥ 1`, so there is always a coarsest level. + let Some(mut cur) = acc.pop() else { return (vec![0.0; w * h * ch], vec![0.0; w * h]) }; + for l in (0..levels - 1).rev() { + let (pw, ph) = sizes[l]; + let (sw, sh) = sizes[l + 1]; + let up = expand(sw, sh, ch, &cur, pw, ph); + cur = par_zip(&acc[l], &up, |a, b| a + b); + } + // Coverage: union of the images. Rows are independent; each walks the images in order, so a + // pixel sees the same sequence of `max` calls as in the serial loop. + let mut cov = vec![0.0f32; w * h]; + par_rows(&mut cov, w, 1, |py, row| { + for im in imgs { + let y = py as i64 - im.y0 as i64; + if y < 0 || y as usize >= im.h { + continue; + } + for x in 0..im.w { + let px = im.x0 + x as i32; + if px < 0 || px as usize >= w { + continue; + } + let p = px as usize; + row[p] = row[p].max(im.alpha[y as usize * im.w + x]); + } + } + }); + (cur, cov) +} diff --git a/crates/algo/src/panorama/parallel_tests.rs b/crates/algo/src/panorama/parallel_tests.rs new file mode 100644 index 0000000000..77c25b0f98 --- /dev/null +++ b/crates/algo/src/panorama/parallel_tests.rs @@ -0,0 +1,402 @@ +use super::*; + +fn mix(mut z: u64) -> u64 { + z = z.wrapping_add(0x9E37_79B9_7F4A_7C15); + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) +} + +/// Deterministic data from integer arithmetic only (no libm): mostly `0..1`, with negatives, +/// signed zeros and large values so a different order of operations cannot hide. +fn noise(len: usize, seed: u64) -> Vec { + (0..len as u64) + .map(|i| { + let z = mix(seed.wrapping_mul(0x1234_5678_9ABC).wrapping_add(i)); + let v = (z >> 40) as f32 / 16_777_216.0; + match z & 31 { + 0 => -v, + 1 => -0.0, + 2 => v * 1000.0, + 3 => 0.0, + _ => v, + } + }) + .collect() +} + +/// Weights with exact zeros, exact ones and partial values, in blobs and noise. +fn weights(w: usize, h: usize, seed: u64) -> Vec { + (0..w * h) + .map(|i| { + let (x, y) = (i % w, i / w); + let z = mix(seed + i as u64); + if (x / 5 + y / 3) % 3 == 0 { + 0.0 + } else if z.is_multiple_of(7) { + ((z >> 20) % 100) as f32 / 100.0 + } else { + 1.0 + } + }) + .collect() +} + +fn bits(v: &[f32]) -> Vec { + v.iter().map(|x| x.to_bits()).collect() +} + +fn fnv(parts: &[&[f32]]) -> u64 { + let mut h = 0xcbf2_9ce4_8422_2325u64; + for p in parts { + for x in *p { + h ^= x.to_bits() as u64; + h = h.wrapping_mul(0x0000_0100_0000_01b3); + } + } + h +} + +/// Sizes that cross the odd / even and tiny cases (1 wide, 1 high, 1×1, odd, power of two + 1). +const SIZES: [(usize, usize); 12] = [(1, 1), (1, 9), (9, 1), (2, 2), (3, 5), (4, 4), (17, 13), (64, 40), (65, 41), (97, 61), (130, 7), (7, 130)]; + +fn ref_reduce(w: usize, h: usize, ch: usize, src: &[f32]) -> (usize, usize, Vec) { + let (nw, nh) = (w.div_ceil(2), h.div_ceil(2)); + let k = [1.0f32, 4.0, 6.0, 4.0, 1.0]; + // Separable 5-tap binomial, then decimate. + let mut tmp = vec![0.0f32; nw * h * ch]; + for y in 0..h { + for x in 0..nw { + for c in 0..ch { + let mut s = 0.0; + for (t, kv) in k.iter().enumerate() { + let xx = (2 * x as i64 + t as i64 - 2).clamp(0, w as i64 - 1) as usize; + s += kv * src[(y * w + xx) * ch + c]; + } + tmp[(y * nw + x) * ch + c] = s / 16.0; + } + } + } + let mut out = vec![0.0f32; nw * nh * ch]; + for y in 0..nh { + for x in 0..nw { + for c in 0..ch { + let mut s = 0.0; + for (t, kv) in k.iter().enumerate() { + let yy = (2 * y as i64 + t as i64 - 2).clamp(0, h as i64 - 1) as usize; + s += kv * tmp[(yy * nw + x) * ch + c]; + } + out[(y * nw + x) * ch + c] = s / 16.0; + } + } + } + (nw, nh, out) +} + +fn ref_expand(sw: usize, sh: usize, ch: usize, src: &[f32], w: usize, h: usize) -> Vec { + // Bilinear upsampling at half-pixel-aligned positions. + let mut out = vec![0.0f32; w * h * ch]; + for y in 0..h { + let fy = ((y as f32 + 0.5) / 2.0 - 0.5).clamp(0.0, (sh - 1) as f32); + let (y0, ty) = (fy.floor() as usize, fy - fy.floor()); + let y1 = (y0 + 1).min(sh - 1); + for x in 0..w { + let fx = ((x as f32 + 0.5) / 2.0 - 0.5).clamp(0.0, (sw - 1) as f32); + let (x0, tx) = (fx.floor() as usize, fx - fx.floor()); + let x1 = (x0 + 1).min(sw - 1); + for c in 0..ch { + let p = |xx: usize, yy: usize| src[(yy * sw + xx) * ch + c]; + let top = p(x0, y0) + (p(x1, y0) - p(x0, y0)) * tx; + let bot = p(x0, y1) + (p(x1, y1) - p(x0, y1)) * tx; + out[(y * w + x) * ch + c] = top + (bot - top) * ty; + } + } + } + out +} + +fn ref_push_pull(w: usize, h: usize, ch: usize, px: &mut [f32], wt: &[f32]) { + if w <= 1 && h <= 1 { + return; + } + let (nw, nh) = (w.div_ceil(2), h.div_ceil(2)); + let mut cpx = vec![0.0f32; nw * nh * ch]; + let mut cw = vec![0.0f32; nw * nh]; + for y in 0..h { + for x in 0..w { + let (i, j) = (y * w + x, (y / 2) * nw + x / 2); + let a = wt[i]; + cw[j] += a; + for c in 0..ch { + cpx[j * ch + c] += a * px[i * ch + c]; + } + } + } + for j in 0..nw * nh { + if cw[j] > 0.0 { + for c in 0..ch { + cpx[j * ch + c] /= cw[j]; + } + cw[j] = 1.0; + } + } + if cw.contains(&0.0) && cw.iter().any(|v| *v > 0.0) { + ref_push_pull(nw, nh, ch, &mut cpx, &cw); + } + for y in 0..h { + for x in 0..w { + let i = y * w + x; + if wt[i] < 1.0 { + let j = (y / 2) * nw + x / 2; + let a = wt[i]; + for c in 0..ch { + px[i * ch + c] = a * px[i * ch + c] + (1.0 - a) * cpx[j * ch + c]; + } + } + } + } +} + +fn ref_multiband(w: usize, h: usize, imgs: &[RoiImage], weights: &[Vec], levels: usize) -> (Vec, Vec) { + let ch = imgs.first().map_or(1, |i| i.ch); + let levels = levels.max(1); + let align = 1i32 << (levels - 1); + // Level sizes of the panorama. + let mut sizes = vec![(w, h)]; + for _ in 1..levels { + let Some(&(pw, ph)) = sizes.last() else { break }; + sizes.push((pw.div_ceil(2), ph.div_ceil(2))); + } + let mut acc: Vec> = sizes.iter().map(|&(lw, lh)| vec![0.0; lw * lh * ch]).collect(); + let mut wsum: Vec> = sizes.iter().map(|&(lw, lh)| vec![0.0; lw * lh]).collect(); + let margin = align * 4; + // Each image on its ROI grown by a margin and aligned to the coarsest level's grid. + let bands = par_map(imgs.len(), |k| { + let im = &imgs[k]; + let gx0 = ((im.x0 - margin).max(0) / align) * align; + let gy0 = ((im.y0 - margin).max(0) / align) * align; + let gx1 = (im.x0 + im.w as i32 + margin).min(w as i32); + let gy1 = (im.y0 + im.h as i32 + margin).min(h as i32); + let (gw, gh) = ((gx1 - gx0).max(1) as usize, (gy1 - gy0).max(1) as usize); + let mut px = vec![0.0f32; gw * gh * ch]; + let mut cov = vec![0.0f32; gw * gh]; + let mut wt = vec![0.0f32; gw * gh]; + for y in 0..im.h { + for x in 0..im.w { + let (gx, gy) = (im.x0 + x as i32 - gx0, im.y0 + y as i32 - gy0); + if gx < 0 || gy < 0 || gx as usize >= gw || gy as usize >= gh { + continue; + } + let (i, g) = (y * im.w + x, gy as usize * gw + gx as usize); + cov[g] = im.alpha[i]; + wt[g] = weights[k][i] * im.alpha[i].min(1.0); + px[g * ch..(g + 1) * ch].copy_from_slice(&im.px[i * ch..(i + 1) * ch]); + } + } + let bin: Vec = cov.iter().map(|a| if *a > 0.5 { 1.0 } else { 0.0 }).collect(); + ref_push_pull(gw, gh, ch, &mut px, &bin); + // Laplacian of the colours, Gaussian of the weights. + let mut lap: Vec<(usize, usize, Vec)> = Vec::new(); + let mut gau: Vec> = Vec::new(); + let (mut cw, mut chh, mut cur, mut cwt) = (gw, gh, px, wt); + for l in 0..levels { + if l + 1 == levels { + lap.push((cw, chh, cur.clone())); + gau.push(cwt.clone()); + break; + } + let (nw, nh, down) = ref_reduce(cw, chh, ch, &cur); + let up = ref_expand(nw, nh, ch, &down, cw, chh); + lap.push((cw, chh, cur.iter().zip(&up).map(|(a, b)| a - b).collect())); + gau.push(cwt.clone()); + let (_, _, wdown) = ref_reduce(cw, chh, 1, &cwt); + cw = nw; + chh = nh; + cur = down; + cwt = wdown; + } + (gx0, gy0, lap, gau) + }); + for (gx0, gy0, lap, gau) in &bands { + for (l, ((lw, lh, band), g)) in lap.iter().zip(gau).enumerate() { + let (ox, oy) = ((gx0 >> l) as usize, (gy0 >> l) as usize); + let (pw, ph) = sizes[l]; + for y in 0..*lh { + let py = oy + y; + if py >= ph { + break; + } + for x in 0..*lw { + let px = ox + x; + if px >= pw { + break; + } + let (i, p) = (y * lw + x, py * pw + px); + let k = g[i]; + if k <= 0.0 { + continue; + } + wsum[l][p] += k; + for c in 0..ch { + acc[l][p * ch + c] += k * band[i * ch + c]; + } + } + } + } + } + for l in 0..levels { + let (pw, ph) = sizes[l]; + for p in 0..pw * ph { + let k = wsum[l][p]; + for c in 0..ch { + acc[l][p * ch + c] = if k > 1e-8 { acc[l][p * ch + c] / k } else { 0.0 }; + } + } + } + // Collapse. + // `levels ≥ 1`, so there is always a coarsest level. + let Some(mut cur) = acc.pop() else { return (vec![0.0; w * h * ch], vec![0.0; w * h]) }; + for l in (0..levels - 1).rev() { + let (pw, ph) = sizes[l]; + let (sw, sh) = sizes[l + 1]; + let up = ref_expand(sw, sh, ch, &cur, pw, ph); + cur = acc[l].iter().zip(&up).map(|(a, b)| a + b).collect(); + } + // Coverage: union of the images. + let mut cov = vec![0.0f32; w * h]; + for im in imgs { + for y in 0..im.h { + for x in 0..im.w { + let (px, py) = (im.x0 + x as i32, im.y0 + y as i32); + if px < 0 || py < 0 || px as usize >= w || py as usize >= h { + continue; + } + let p = py as usize * w + px as usize; + cov[p] = cov[p].max(im.alpha[y * im.w + x]); + } + } + } + (cur, cov) +} + +#[test] +fn reduce_and_expand_match_the_serial_code() { + for (n, &(w, h)) in SIZES.iter().enumerate() { + for ch in [1usize, 3, 4] { + let src = noise(w * h * ch, n as u64 * 7 + ch as u64); + let (nw, nh, got) = reduce(w, h, ch, &src); + let (rw, rh, want) = ref_reduce(w, h, ch, &src); + assert_eq!((nw, nh), (rw, rh)); + assert_eq!(bits(&got), bits(&want), "reduce {w}x{h}x{ch}"); + // Expand back to the original size and to sizes that are not twice the source's. + for (ew, eh) in [(w, h), (2 * nw, 2 * nh), (2 * nw - 1, 2 * nh + 1), (w + 3, h + 5)] { + let got = expand(nw, nh, ch, &want, ew, eh); + let want_up = ref_expand(nw, nh, ch, &want, ew, eh); + assert_eq!(bits(&got), bits(&want_up), "expand {nw}x{nh}x{ch} to {ew}x{eh}"); + } + } + } +} + +#[test] +fn push_pull_matches_the_serial_code() { + for (n, &(w, h)) in SIZES.iter().enumerate() { + for ch in [1usize, 3] { + for variant in 0..3u64 { + let wt = match variant { + 0 => weights(w, h, n as u64), + 1 => vec![1.0; w * h], + // A single covered pixel: every level of the recursion has to fill from it. + _ => (0..w * h).map(|i| if i == (w * h) / 3 { 1.0 } else { 0.0 }).collect(), + }; + let px = noise(w * h * ch, 100 + n as u64); + let (mut got, mut want) = (px.clone(), px); + push_pull(w, h, ch, &mut got, &wt); + ref_push_pull(w, h, ch, &mut want, &wt); + assert_eq!(bits(&got), bits(&want), "push_pull {w}x{h}x{ch} variant {variant}"); + } + } + } +} + +/// ROIs of assorted sizes and offsets (some sticking out of the canvas), with holes in the alpha. +fn rois(w: usize, h: usize, ch: usize, seed: u64) -> (Vec, Vec>) { + let specs = + [(0i32, 0i32, w * 2 / 3, h), (w as i32 / 3, -(h as i32) / 5, w * 2 / 3 + 1, h * 3 / 4 + 1), (-(w as i32) / 4, h as i32 / 2, w / 2 + 1, h / 2 + 3)]; + let imgs: Vec = specs + .iter() + .enumerate() + .map(|(k, &(x0, y0, iw, ih))| { + let (iw, ih) = (iw.max(1), ih.max(1)); + let mut alpha = vec![1.0f32; iw * ih]; + for (i, a) in alpha.iter_mut().enumerate() { + let z = mix(seed + k as u64 * 1000 + i as u64); + if (i % iw) / 4 % 5 == 2 && (i / iw) % 6 < 3 { + *a = 0.0; + } else if z.is_multiple_of(11) { + *a = 0.3; + } + } + RoiImage { x0, y0, w: iw, h: ih, ch, px: noise(iw * ih * ch, seed + k as u64), alpha } + }) + .collect(); + let wts = imgs.iter().enumerate().map(|(k, r)| weights(r.w, r.h, seed + 50 + k as u64)).collect(); + (imgs, wts) +} + +#[test] +fn multiband_matches_the_serial_code() { + for (n, &(w, h)) in [(1usize, 1usize), (5, 3), (40, 30), (97, 61), (130, 70), (64, 64), (201, 129)].iter().enumerate() { + for ch in [1usize, 3] { + let (imgs, wts) = rois(w, h, ch, n as u64 * 31 + ch as u64); + for levels in [1usize, 2, 3, 5, 7] { + let got = multiband(w, h, &imgs, &wts, levels); + let want = ref_multiband(w, h, &imgs, &wts, levels); + assert_eq!(bits(&got.0), bits(&want.0), "colours {w}x{h}x{ch} levels {levels}"); + assert_eq!(bits(&got.1), bits(&want.1), "coverage {w}x{h}x{ch} levels {levels}"); + } + } + } + // No images at all, and zero levels. + assert_eq!(multiband(9, 7, &[], &[], 3).0.len(), ref_multiband(9, 7, &[], &[], 3).0.len()); +} + +/// Batching the bands (#7758) changes when they are built, not the result. Budgets from none +/// (one image per batch) up to everything in steps of a fifth pass through every split of the +/// three images. +#[test] +fn multiband_batches_match_the_serial_code() { + let budgets: Vec = + std::iter::successors(Some(1024.0f64), |b| Some(b * 1.2)).take_while(|b| *b < 4e6).map(|b| b as usize).chain([0, usize::MAX]).collect(); + for (n, &(w, h)) in [(40usize, 30usize), (97, 61), (201, 129)].iter().enumerate() { + for ch in [1usize, 3] { + let (imgs, wts) = rois(w, h, ch, n as u64 * 17 + ch as u64); + for levels in [1usize, 3, 5] { + let want = ref_multiband(w, h, &imgs, &wts, levels); + for &budget in &budgets { + let got = multiband_batched(w, h, &imgs, &wts, levels, budget); + assert_eq!(bits(&got.0), bits(&want.0), "colours {w}x{h}x{ch} levels {levels} budget {budget}"); + assert_eq!(bits(&got.1), bits(&want.1), "coverage {w}x{h}x{ch} levels {levels} budget {budget}"); + } + } + } + } +} + +/// Hashes recorded from the code before it was made parallel (plain f32 arithmetic only, so +/// they hold on every platform). +#[test] +fn multiband_hashes_recorded_from_the_serial_code() { + let (imgs, wts) = rois(97, 61, 3, 5); + let (px, cov) = multiband(97, 61, &imgs, &wts, 5); + assert_eq!(fnv(&[&px, &cov]), 0xf89a5726082ebb6c, "97x61 rgb, 5 levels"); + let (imgs, wts) = rois(130, 70, 1, 9); + let (px, cov) = multiband(130, 70, &imgs, &wts, 7); + assert_eq!(fnv(&[&px, &cov]), 0xb7d7ddc59d201730, "130x70 grey, 7 levels"); + let wt = weights(65, 41, 3); + let mut px = noise(65 * 41 * 3, 4); + push_pull(65, 41, 3, &mut px, &wt); + assert_eq!(fnv(&[&px]), 0x50ea36a84ca9a68f, "push_pull 65x41 rgb"); + let (nw, nh, r) = reduce(65, 41, 3, &px); + assert_eq!(fnv(&[&r, &expand(nw, nh, 3, &r, 65, 41)]), 0x51823acfb4206dd8, "reduce + expand 65x41 rgb"); +} diff --git a/crates/algo/src/quantize.rs b/crates/algo/src/quantize.rs index 70d5b5c90c..ceb9c332ad 100644 --- a/crates/algo/src/quantize.rs +++ b/crates/algo/src/quantize.rs @@ -731,447 +731,4 @@ pub fn to_bitmap_custom(gray: &mut [f32], w: usize, map: &[f32], mw: usize, mh: } #[cfg(test)] -mod tests { - use super::*; - - fn gradient(w: usize, h: usize) -> Vec<[f32; 4]> { - (0..w * h).map(|i| [(i % w) as f32 / (w - 1) as f32, (i / w) as f32 / (h - 1) as f32, 0.3, 1.0]).collect() - } - - fn to8_reference(v: f32) -> u8 { - (v.clamp(0.0, 1.0) * 255.0).round() as u8 - } - - #[test] - fn to8_matches_round_on_samples_and_edges() { - // Every half-way point and its neighbours, plus a dense sweep of the unit range. - for k in 0..=256u32 { - let mid = (k as f32 + 0.5) / 255.0; - for d in -3i32..=3 { - let v = f32::from_bits((mid.to_bits() as i32 + d) as u32); - assert_eq!(to8(v), to8_reference(v), "{v:e}"); - } - } - for i in 0..200_000u32 { - let v = f32::from_bits(i * 20_000); - assert_eq!(to8(v), to8_reference(v), "{v:e}"); - } - for v in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -0.0, 0.0, 1.0, -1.0, 2.0, 1e30, -1e30, f32::MIN_POSITIVE, 1e-45] { - assert_eq!(to8(v), to8_reference(v), "{v:e}"); - } - } - - #[test] - #[cfg(not(target_arch = "wasm32"))] - #[ignore = "checks all 2^32 floats, a few seconds in release; run with --release --ignored"] - fn to8_matches_round_for_every_float() { - use rayon::prelude::*; - let bad = (0..=u32::MAX).into_par_iter().filter(|&b| to8(f32::from_bits(b)) != to8_reference(f32::from_bits(b))).count(); - assert_eq!(bad, 0); - } - - /// A repeatable 96x64 image: a gradient with up to 31 levels of integer-hash noise and a - /// few see-through pixels. - fn golden_image() -> Vec<[f32; 4]> { - let (w, h) = (96usize, 64usize); - (0..w * h) - .map(|i| { - let (x, y) = ((i % w) as f32, (i / w) as f32); - let noise = |salt: u32| ((((i as u32).wrapping_mul(2_654_435_761).wrapping_add(salt.wrapping_mul(40_503))) >> 13) & 31) as f32 / 255.0; - let alpha = if i % 17 == 0 { 0.25 } else { 1.0 }; - [x / (w - 1) as f32 * 0.8 + noise(1), y / (h - 1) as f32 * 0.7 + noise(2), ((x + y) / (w + h) as f32) * 0.6 + noise(3), alpha] - }) - .collect() - } - - /// Palettes written down from the version before the speed-up (hash-map histogram, every box - /// rescanned each split, comparison sort, serial k-means). Any change to how the palettes - /// are built has to give these exact colours. - #[test] - fn palettes_match_the_recorded_originals() { - let px = golden_image(); - #[rustfmt::skip] - let cases: Vec<(PaletteKind, usize, Forced, &[Rgb8])> = vec![ - ( - PaletteKind::Adaptive, - 16, - Forced::None, - &[ - [40, 173, 80], [196, 175, 150], [92, 173, 103], [92, 81, 71], [195, 83, 118], [39, 82, 49], - [142, 82, 95], [195, 37, 101], [143, 36, 79], [40, 128, 64], [196, 129, 133], [92, 127, 87], - [91, 36, 56], [38, 35, 33], [144, 128, 111], [144, 174, 127], - ], - ), - ( - PaletteKind::Perceptual, - 16, - Forced::None, - &[ - [104, 111, 87], [51, 129, 68], [48, 178, 79], [110, 74, 77], [165, 46, 93], [205, 50, 107], - [200, 154, 143], [44, 54, 42], [190, 101, 121], [61, 32, 44], [155, 115, 111], [48, 93, 56], - [119, 42, 71], [84, 172, 98], [126, 165, 115], [172, 168, 135], - ], - ), - ( - PaletteKind::Selective, - 24, - Forced::BlackWhite, - &[ - [0, 0, 0], [255, 255, 255], [102, 107, 85], [65, 69, 55], [87, 133, 89], [109, 73, 76], - [164, 42, 92], [204, 51, 102], [199, 153, 142], [54, 170, 84], [199, 107, 126], [65, 33, 45], - [153, 102, 102], [187, 180, 145], [40, 106, 54], [100, 176, 107], [138, 174, 123], [50, 188, 80], - [32, 37, 33], [47, 139, 69], [144, 143, 116], [41, 80, 49], [108, 33, 64], [151, 70, 94], - ], - ), - ( - PaletteKind::Adaptive, - 8, - Forced::Primaries, - &[ - [0, 0, 0], [255, 255, 255], [255, 0, 0], [0, 255, 0], [0, 0, 255], [0, 255, 255], - [255, 0, 255], [255, 255, 0], - ], - ), - ( - PaletteKind::Perceptual, - 12, - Forced::BlackWhite, - &[ - [0, 0, 0], [255, 255, 255], [104, 106, 85], [137, 43, 79], [148, 170, 126], [181, 144, 132], - [66, 172, 87], [88, 49, 60], [57, 118, 67], [42, 54, 41], [183, 101, 118], [196, 50, 105], - ], - ), - ]; - for (kind, colors, forced, expected) in cases { - assert_eq!(build_palette(&px, kind, colors, forced).unwrap(), expected, "{kind:?} {colors} {forced:?}"); - } - } - - /// The pre-speed-up median cut and k-means, kept as the oracle for the faster ones. - fn median_cut_reference(pts: &[([f32; 3], u32)], n: usize) -> Vec<[f32; 3]> { - if pts.is_empty() || n == 0 { - return Vec::new(); - } - let mut boxes: Vec> = vec![pts.to_vec()]; - while boxes.len() < n { - let (bi, axis, score) = boxes - .iter() - .enumerate() - .filter(|(_, b)| b.len() > 1) - .map(|(i, b)| { - let mut best = (0usize, -1.0f32); - for a in 0..3 { - let (lo, hi) = b.iter().fold((f32::MAX, f32::MIN), |(lo, hi), p| (lo.min(p.0[a]), hi.max(p.0[a]))); - if hi - lo > best.1 { - best = (a, hi - lo); - } - } - let w: f32 = b.iter().map(|p| p.1 as f32).sum(); - (i, best.0, best.1 * w.sqrt()) - }) - .fold((usize::MAX, 0, -1.0f32), |acc, x| if x.2 > acc.2 { x } else { acc }); - if bi == usize::MAX || score <= 0.0 { - break; - } - let mut b = boxes.swap_remove(bi); - b.sort_by(|p, q| p.0[axis].total_cmp(&q.0[axis])); - let total: u64 = b.iter().map(|p| u64::from(p.1)).sum(); - let mut acc = 0u64; - let mut cut = 1; - for (i, p) in b.iter().enumerate() { - acc += u64::from(p.1); - if acc * 2 >= total { - cut = (i + 1).clamp(1, b.len() - 1); - break; - } - } - let rest = b.split_off(cut); - boxes.push(b); - boxes.push(rest); - } - boxes - .iter() - .map(|b| { - let w: f64 = b.iter().map(|p| f64::from(p.1)).sum(); - std::array::from_fn(|a| (b.iter().map(|p| f64::from(p.0[a]) * f64::from(p.1)).sum::() / w) as f32) - }) - .collect() - } - - fn kmeans_reference(pts: &[([f32; 3], u32)], centers: &mut [[f32; 3]], iters: usize) { - for _ in 0..iters { - let lookup = Nearest::new(centers.iter().copied()); - let mut sum = vec![[0.0f64; 3]; centers.len()]; - let mut cnt = vec![0.0f64; centers.len()]; - for (p, w) in pts { - let i = lookup.find(*p); - for a in 0..3 { - sum[i][a] += f64::from(p[a]) * f64::from(*w); - } - cnt[i] += f64::from(*w); - } - for (i, c) in centers.iter_mut().enumerate() { - if cnt[i] > 0.0 { - *c = std::array::from_fn(|a| (sum[i][a] / cnt[i]) as f32); - } - } - } - } - - /// Points with many repeated coordinates (ties), negative values, -0.0 and weights up to - /// a few thousand, so the stable-sort and float-order rules are all exercised. - fn tie_heavy_points(n: usize, seed: u64) -> Vec<([f32; 3], u32)> { - let mut s = seed; - let mut next = move || { - s = s.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407); - (s >> 33) as u32 - }; - (0..n) - .map(|_| { - let mut c = |range: u32| match next() % 40 { - 0 => -0.0, - 1 => 0.0, - _ => (next() % range) as f32 * 0.5 - (range / 4) as f32, - }; - ([c(24), c(300), c(150)], 1 + next() % 3000) - }) - .collect() - } - - #[test] - fn faster_median_cut_and_kmeans_equal_the_originals_bit_for_bit() { - // 40 000 points cross the 256-point radix threshold on the first splits. - for (n, boxes, seed) in [(40_000, 256, 1), (40_000, 37, 2), (3_000, 256, 3), (200, 64, 4), (2, 8, 5)] { - let pts = tie_heavy_points(n, seed); - let new = median_cut(&pts, boxes); - let old = median_cut_reference(&pts, boxes); - assert_eq!(new.len(), old.len()); - for (a, b) in new.iter().zip(&old) { - assert_eq!(a.map(f32::to_bits), b.map(f32::to_bits), "median cut, n={n} boxes={boxes}"); - } - let (mut a, mut b) = (new, old); - kmeans(&pts, &mut a, 3); - kmeans_reference(&pts, &mut b, 3); - for (x, y) in a.iter().zip(&b) { - assert_eq!(x.map(f32::to_bits), y.map(f32::to_bits), "kmeans, n={n} boxes={boxes}"); - } - } - } - - #[test] - fn radix_sort_is_the_stable_total_cmp_sort() { - for axis in 0..3 { - let mut pts = tie_heavy_points(5_000, 9 + axis as u64); - // The weight field doubles as an id: equal keys must keep their input order. - for (i, p) in pts.iter_mut().enumerate() { - p.1 = i as u32; - } - pts[10].0[axis] = f32::NAN; - pts[11].0[axis] = -f32::NAN; - pts[12].0[axis] = f32::INFINITY; - pts[13].0[axis] = f32::NEG_INFINITY; - let mut expected = pts.clone(); - expected.sort_by(|p, q| p.0[axis].total_cmp(&q.0[axis])); - radix_sort_along(&mut pts, axis); - let bits = |v: &[([f32; 3], u32)]| v.iter().map(|p| (p.0.map(f32::to_bits), p.1)).collect::>(); - assert_eq!(bits(&pts), bits(&expected), "axis {axis}"); - } - } - - #[test] - fn histogram_counts_opaque_pixels_sorted() { - let px = [[1.0, 0.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0], [1.0, 0.0, 0.0, 0.5], [1.0, 0.0, 0.0, 0.49], [0.0, 0.0, 1.0, 1.0], [0.0, 0.0, 0.0, 1.0]]; - assert_eq!(histogram(&px), vec![([0, 0, 0], 1), ([0, 0, 255], 2), ([255, 0, 0], 2)]); - assert!(histogram(&[]).is_empty()); - } - - #[test] - fn fixed_palettes_have_expected_sizes() { - assert_eq!(web_palette().len(), 216); - assert_eq!(mac_palette().len(), 256); - assert_eq!(windows_palette().len(), 256); - assert_eq!(uniform_palette(27).len(), 27); - let mut m = mac_palette(); - m.sort_unstable(); - m.dedup(); - assert_eq!(m.len(), 256, "mac palette entries are unique"); - } - - #[test] - fn exact_palette_and_failure() { - let px = vec![[1.0, 0.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0], [1.0, 0.0, 0.0, 1.0]]; - assert_eq!(build_palette(&px, PaletteKind::Exact, 256, Forced::None).unwrap().len(), 2); - assert!(build_palette(&gradient(64, 64), PaletteKind::Exact, 256, Forced::None).is_err()); - } - - #[test] - fn adaptive_and_perceptual_respect_count_and_forced() { - let px = gradient(40, 40); - for kind in [PaletteKind::Adaptive, PaletteKind::Perceptual, PaletteKind::Selective] { - let pal = build_palette(&px, kind, 16, Forced::BlackWhite).unwrap(); - assert!(pal.len() <= 16 && pal.len() >= 8, "{kind:?} {}", pal.len()); - assert_eq!(&pal[..2], &[[0, 0, 0], [255, 255, 255]]); - } - } - - #[test] - fn forced_colours_filling_the_count_do_not_panic() { - // 2 colours + Black and White (or 8 + Primaries) leaves no room for - // computed entries; the median cut used to return no centres and - // k-means indexed into the empty list. - let px = vec![[1.0, 1.0, 1.0, 1.0]; 16]; - for kind in [PaletteKind::Adaptive, PaletteKind::Perceptual, PaletteKind::Selective] { - let pal = build_palette(&px, kind, 2, Forced::BlackWhite).unwrap(); - assert_eq!(pal, vec![[0, 0, 0], [255, 255, 255]], "{kind:?}"); - let pal = build_palette(&gradient(8, 8), kind, 8, Forced::Primaries).unwrap(); - assert_eq!(pal.len(), 8, "{kind:?}"); - } - } - - #[test] - #[ignore = "24 MP release timing comparison; run with --release --ignored --nocapture"] - fn indexed_diffusion_24mp_release_comparison() { - let source = gradient(6000, 4000); - let pal = web_palette(); - for run in 0..4 { - let mut linear = source.clone(); - let mut accelerated = source.clone(); - let mut before = None; - let mut after = None; - // Reverse the order on alternating rounds; exclude the first round as warmup. - for old in if run % 2 == 0 { [true, false] } else { [false, true] } { - let start = std::time::Instant::now(); - if old { - let indices = quantize_with(&mut linear, 6000, &pal, Dither::Diffusion, 0.75, None, |c| linear_rgb_nearest(&pal, c)); - before = Some((start.elapsed().as_secs_f64() * 1000.0, indices)); - } else { - let indices = quantize(&mut accelerated, 6000, &pal, Dither::Diffusion, 0.75, None); - after = Some((start.elapsed().as_secs_f64() * 1000.0, indices)); - } - } - let (before_ms, before_indices) = before.unwrap(); - let (after_ms, after_indices) = after.unwrap(); - assert_eq!(before_indices.iter().zip(&after_indices).position(|(a, b)| a != b), None, "first differing index"); - assert_eq!(linear.iter().zip(&accelerated).position(|(a, b)| a != b), None, "first differing pixel"); - println!( - "{}", - serde_json::json!({"run":run,"warmup":run==0,"pixels":24_000_000,"palette_entries":216,"linear_ms":before_ms,"accelerated_ms":after_ms}) - ); - } - } - - fn linear_rgb_nearest(pal: &[Rgb8], c: [f32; 3]) -> usize { - let mut best = (f32::MAX, 0); - for (i, e) in pal.iter().enumerate() { - let d: f32 = (0..3).map(|k| (c[k] * 255.0 - f32::from(e[k])).powi(2)).sum(); - if d < best.0 { - best = (d, i); - } - } - best.1 - } - - #[test] - fn all_dithers_match_the_original_linear_palette_search_exactly() { - let mut source = gradient(93, 61); - for (i, p) in source.iter_mut().enumerate() { - p[2] = (i % 71) as f32 / 70.0; - p[3] = [0.0, 0.2, 0.7, 1.0][i % 4]; - } - for count in [8, 16, 32, 64, 128, 256] { - let pal = build_palette(&source, PaletteKind::Selective, count, Forced::BlackWhite).unwrap(); - for dither in [Dither::None, Dither::Diffusion, Dither::Pattern, Dither::Noise] { - for transparent in [None, Some(1)] { - let mut actual = source.clone(); - let mut expected = source.clone(); - let indices = quantize(&mut actual, 93, &pal, dither, 0.75, transparent); - let old_indices = quantize_with(&mut expected, 93, &pal, dither, 0.75, transparent, |c| linear_rgb_nearest(&pal, c)); - assert_eq!(indices, old_indices, "{count} {dither:?} {transparent:?}"); - assert_eq!(actual, expected, "{count} {dither:?} {transparent:?}"); - } - } - } - } - - #[test] - fn quantize_maps_to_palette_with_each_dither() { - let pal = vec![[0, 0, 0], [255, 255, 255]]; - for d in [Dither::None, Dither::Diffusion, Dither::Pattern, Dither::Noise] { - let mut px: Vec<[f32; 4]> = (0..64) - .map(|i| [i as f32 / 63.0; 4]) - .map(|mut p| { - p[3] = 1.0; - p - }) - .collect(); - let idx = quantize(&mut px, 8, &pal, d, 1.0, None); - assert!(px.iter().all(|p| p[0] == 0.0 || p[0] == 1.0), "{d:?}"); - assert_eq!(idx.len(), 64); - // Mean brightness is preserved by dithering (not by plain thresholding). - if d == Dither::Diffusion { - let mean = px.iter().map(|p| p[0]).sum::() / 64.0; - assert!((mean - 0.5).abs() < 0.08, "{mean}"); - } - } - let mut px = vec![[1.0, 1.0, 1.0, 0.2]]; - let idx = quantize(&mut px, 1, &pal, Dither::None, 1.0, Some(1)); - assert_eq!((idx[0], px[0][3]), (1, 0.0)); - } - - #[test] - fn bitmap_methods_are_binary_and_track_tone() { - for m in [ - BitmapMethod::Threshold, - BitmapMethod::Pattern, - BitmapMethod::Diffusion, - BitmapMethod::Halftone { cell: 6.0, angle: 45.0, shape: HalftoneShape::Round }, - ] { - let mut g = vec![0.25f32; 32 * 32]; - to_bitmap(&mut g, 32, m); - assert!(g.iter().all(|v| *v == 0.0 || *v == 1.0)); - let mean = g.iter().sum::() / g.len() as f32; - if m != BitmapMethod::Threshold { - assert!((mean - 0.25).abs() < 0.15, "{m:?} {mean}"); - } else { - assert_eq!(mean, 0.0); - } - } - } - - /// The first 8-bit gray level (of a 0..=255 ramp) that `t` turns white. - fn first_white(t: f32) -> u32 { - (0..=255).find(|v| *v as f32 / 255.0 >= t).unwrap_or(256) - } - - #[test] - fn custom_pattern_thresholds_match_photoshop() { - // Photoshop (Image › Mode › Bitmap, Custom Pattern) on a 0..255 ramp: the first white - // level per pattern pixel, measured against defined patterns. - let l = |v: &[u8]| v.iter().map(|v| f32::from(*v) / 255.0).collect::>(); - let ramp7 = custom_pattern_thresholds(&l(&[0, 40, 80, 120, 160, 200, 240])); - assert_eq!(ramp7.iter().map(|t| first_white(*t)).collect::>(), [237, 201, 164, 128, 92, 55, 19]); - let five = custom_pattern_thresholds(&l(&[10, 200, 90, 250, 150])); - assert_eq!(five.iter().map(|t| first_white(*t)).collect::>(), [230, 77, 179, 26, 128]); - // Equal pixels share their rank: 100, 100 both sit at 50%. - let ties = custom_pattern_thresholds(&l(&[100, 100, 200, 50])); - assert_eq!(ties.iter().map(|t| first_white(*t)).collect::>(), [128, 128, 32, 224]); - assert!(custom_pattern_thresholds(&[]).is_empty()); - assert_eq!(custom_pattern_thresholds(&[f32::NAN, 0.3]).len(), 2); - } - - #[test] - fn custom_pattern_tiles_from_the_top_left() { - // A 2x1 map: even columns need 75%, odd ones 25%. - let map = [0.75, 0.25]; - let mut g = vec![0.5; 6]; - to_bitmap_custom(&mut g, 3, &map, 2, 1); - assert_eq!(g, [0.0, 1.0, 0.0, 0.0, 1.0, 0.0]); - // A map that doesn't match its size, or an empty image width, is a 50% threshold. - let mut g = vec![0.4, 0.6]; - to_bitmap_custom(&mut g, 2, &map, 3, 1); - assert_eq!(g, [0.0, 1.0]); - let mut g = vec![0.6]; - to_bitmap_custom(&mut g, 0, &map, 2, 1); - assert_eq!(g, [1.0]); - } -} +mod tests; diff --git a/crates/algo/src/quantize/tests.rs b/crates/algo/src/quantize/tests.rs new file mode 100644 index 0000000000..14afa17f56 --- /dev/null +++ b/crates/algo/src/quantize/tests.rs @@ -0,0 +1,442 @@ +use super::*; + +fn gradient(w: usize, h: usize) -> Vec<[f32; 4]> { + (0..w * h).map(|i| [(i % w) as f32 / (w - 1) as f32, (i / w) as f32 / (h - 1) as f32, 0.3, 1.0]).collect() +} + +fn to8_reference(v: f32) -> u8 { + (v.clamp(0.0, 1.0) * 255.0).round() as u8 +} + +#[test] +fn to8_matches_round_on_samples_and_edges() { + // Every half-way point and its neighbours, plus a dense sweep of the unit range. + for k in 0..=256u32 { + let mid = (k as f32 + 0.5) / 255.0; + for d in -3i32..=3 { + let v = f32::from_bits((mid.to_bits() as i32 + d) as u32); + assert_eq!(to8(v), to8_reference(v), "{v:e}"); + } + } + for i in 0..200_000u32 { + let v = f32::from_bits(i * 20_000); + assert_eq!(to8(v), to8_reference(v), "{v:e}"); + } + for v in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -0.0, 0.0, 1.0, -1.0, 2.0, 1e30, -1e30, f32::MIN_POSITIVE, 1e-45] { + assert_eq!(to8(v), to8_reference(v), "{v:e}"); + } +} + +#[test] +#[cfg(not(target_arch = "wasm32"))] +#[ignore = "checks all 2^32 floats, a few seconds in release; run with --release --ignored"] +fn to8_matches_round_for_every_float() { + use rayon::prelude::*; + let bad = (0..=u32::MAX).into_par_iter().filter(|&b| to8(f32::from_bits(b)) != to8_reference(f32::from_bits(b))).count(); + assert_eq!(bad, 0); +} + +/// A repeatable 96x64 image: a gradient with up to 31 levels of integer-hash noise and a +/// few see-through pixels. +fn golden_image() -> Vec<[f32; 4]> { + let (w, h) = (96usize, 64usize); + (0..w * h) + .map(|i| { + let (x, y) = ((i % w) as f32, (i / w) as f32); + let noise = |salt: u32| ((((i as u32).wrapping_mul(2_654_435_761).wrapping_add(salt.wrapping_mul(40_503))) >> 13) & 31) as f32 / 255.0; + let alpha = if i % 17 == 0 { 0.25 } else { 1.0 }; + [x / (w - 1) as f32 * 0.8 + noise(1), y / (h - 1) as f32 * 0.7 + noise(2), ((x + y) / (w + h) as f32) * 0.6 + noise(3), alpha] + }) + .collect() +} + +/// Palettes written down from the version before the speed-up (hash-map histogram, every box +/// rescanned each split, comparison sort, serial k-means). Any change to how the palettes +/// are built has to give these exact colours. +#[test] +fn palettes_match_the_recorded_originals() { + let px = golden_image(); + #[rustfmt::skip] + let cases: Vec<(PaletteKind, usize, Forced, &[Rgb8])> = vec![ + ( + PaletteKind::Adaptive, + 16, + Forced::None, + &[ + [40, 173, 80], [196, 175, 150], [92, 173, 103], [92, 81, 71], [195, 83, 118], [39, 82, 49], + [142, 82, 95], [195, 37, 101], [143, 36, 79], [40, 128, 64], [196, 129, 133], [92, 127, 87], + [91, 36, 56], [38, 35, 33], [144, 128, 111], [144, 174, 127], + ], + ), + ( + PaletteKind::Perceptual, + 16, + Forced::None, + &[ + [104, 111, 87], [51, 129, 68], [48, 178, 79], [110, 74, 77], [165, 46, 93], [205, 50, 107], + [200, 154, 143], [44, 54, 42], [190, 101, 121], [61, 32, 44], [155, 115, 111], [48, 93, 56], + [119, 42, 71], [84, 172, 98], [126, 165, 115], [172, 168, 135], + ], + ), + ( + PaletteKind::Selective, + 24, + Forced::BlackWhite, + &[ + [0, 0, 0], [255, 255, 255], [102, 107, 85], [65, 69, 55], [87, 133, 89], [109, 73, 76], + [164, 42, 92], [204, 51, 102], [199, 153, 142], [54, 170, 84], [199, 107, 126], [65, 33, 45], + [153, 102, 102], [187, 180, 145], [40, 106, 54], [100, 176, 107], [138, 174, 123], [50, 188, 80], + [32, 37, 33], [47, 139, 69], [144, 143, 116], [41, 80, 49], [108, 33, 64], [151, 70, 94], + ], + ), + ( + PaletteKind::Adaptive, + 8, + Forced::Primaries, + &[ + [0, 0, 0], [255, 255, 255], [255, 0, 0], [0, 255, 0], [0, 0, 255], [0, 255, 255], + [255, 0, 255], [255, 255, 0], + ], + ), + ( + PaletteKind::Perceptual, + 12, + Forced::BlackWhite, + &[ + [0, 0, 0], [255, 255, 255], [104, 106, 85], [137, 43, 79], [148, 170, 126], [181, 144, 132], + [66, 172, 87], [88, 49, 60], [57, 118, 67], [42, 54, 41], [183, 101, 118], [196, 50, 105], + ], + ), + ]; + for (kind, colors, forced, expected) in cases { + assert_eq!(build_palette(&px, kind, colors, forced).unwrap(), expected, "{kind:?} {colors} {forced:?}"); + } +} + +/// The pre-speed-up median cut and k-means, kept as the oracle for the faster ones. +fn median_cut_reference(pts: &[([f32; 3], u32)], n: usize) -> Vec<[f32; 3]> { + if pts.is_empty() || n == 0 { + return Vec::new(); + } + let mut boxes: Vec> = vec![pts.to_vec()]; + while boxes.len() < n { + let (bi, axis, score) = boxes + .iter() + .enumerate() + .filter(|(_, b)| b.len() > 1) + .map(|(i, b)| { + let mut best = (0usize, -1.0f32); + for a in 0..3 { + let (lo, hi) = b.iter().fold((f32::MAX, f32::MIN), |(lo, hi), p| (lo.min(p.0[a]), hi.max(p.0[a]))); + if hi - lo > best.1 { + best = (a, hi - lo); + } + } + let w: f32 = b.iter().map(|p| p.1 as f32).sum(); + (i, best.0, best.1 * w.sqrt()) + }) + .fold((usize::MAX, 0, -1.0f32), |acc, x| if x.2 > acc.2 { x } else { acc }); + if bi == usize::MAX || score <= 0.0 { + break; + } + let mut b = boxes.swap_remove(bi); + b.sort_by(|p, q| p.0[axis].total_cmp(&q.0[axis])); + let total: u64 = b.iter().map(|p| u64::from(p.1)).sum(); + let mut acc = 0u64; + let mut cut = 1; + for (i, p) in b.iter().enumerate() { + acc += u64::from(p.1); + if acc * 2 >= total { + cut = (i + 1).clamp(1, b.len() - 1); + break; + } + } + let rest = b.split_off(cut); + boxes.push(b); + boxes.push(rest); + } + boxes + .iter() + .map(|b| { + let w: f64 = b.iter().map(|p| f64::from(p.1)).sum(); + std::array::from_fn(|a| (b.iter().map(|p| f64::from(p.0[a]) * f64::from(p.1)).sum::() / w) as f32) + }) + .collect() +} + +fn kmeans_reference(pts: &[([f32; 3], u32)], centers: &mut [[f32; 3]], iters: usize) { + for _ in 0..iters { + let lookup = Nearest::new(centers.iter().copied()); + let mut sum = vec![[0.0f64; 3]; centers.len()]; + let mut cnt = vec![0.0f64; centers.len()]; + for (p, w) in pts { + let i = lookup.find(*p); + for a in 0..3 { + sum[i][a] += f64::from(p[a]) * f64::from(*w); + } + cnt[i] += f64::from(*w); + } + for (i, c) in centers.iter_mut().enumerate() { + if cnt[i] > 0.0 { + *c = std::array::from_fn(|a| (sum[i][a] / cnt[i]) as f32); + } + } + } +} + +/// Points with many repeated coordinates (ties), negative values, -0.0 and weights up to +/// a few thousand, so the stable-sort and float-order rules are all exercised. +fn tie_heavy_points(n: usize, seed: u64) -> Vec<([f32; 3], u32)> { + let mut s = seed; + let mut next = move || { + s = s.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407); + (s >> 33) as u32 + }; + (0..n) + .map(|_| { + let mut c = |range: u32| match next() % 40 { + 0 => -0.0, + 1 => 0.0, + _ => (next() % range) as f32 * 0.5 - (range / 4) as f32, + }; + ([c(24), c(300), c(150)], 1 + next() % 3000) + }) + .collect() +} + +#[test] +fn faster_median_cut_and_kmeans_equal_the_originals_bit_for_bit() { + // 40 000 points cross the 256-point radix threshold on the first splits. + for (n, boxes, seed) in [(40_000, 256, 1), (40_000, 37, 2), (3_000, 256, 3), (200, 64, 4), (2, 8, 5)] { + let pts = tie_heavy_points(n, seed); + let new = median_cut(&pts, boxes); + let old = median_cut_reference(&pts, boxes); + assert_eq!(new.len(), old.len()); + for (a, b) in new.iter().zip(&old) { + assert_eq!(a.map(f32::to_bits), b.map(f32::to_bits), "median cut, n={n} boxes={boxes}"); + } + let (mut a, mut b) = (new, old); + kmeans(&pts, &mut a, 3); + kmeans_reference(&pts, &mut b, 3); + for (x, y) in a.iter().zip(&b) { + assert_eq!(x.map(f32::to_bits), y.map(f32::to_bits), "kmeans, n={n} boxes={boxes}"); + } + } +} + +#[test] +fn radix_sort_is_the_stable_total_cmp_sort() { + for axis in 0..3 { + let mut pts = tie_heavy_points(5_000, 9 + axis as u64); + // The weight field doubles as an id: equal keys must keep their input order. + for (i, p) in pts.iter_mut().enumerate() { + p.1 = i as u32; + } + pts[10].0[axis] = f32::NAN; + pts[11].0[axis] = -f32::NAN; + pts[12].0[axis] = f32::INFINITY; + pts[13].0[axis] = f32::NEG_INFINITY; + let mut expected = pts.clone(); + expected.sort_by(|p, q| p.0[axis].total_cmp(&q.0[axis])); + radix_sort_along(&mut pts, axis); + let bits = |v: &[([f32; 3], u32)]| v.iter().map(|p| (p.0.map(f32::to_bits), p.1)).collect::>(); + assert_eq!(bits(&pts), bits(&expected), "axis {axis}"); + } +} + +#[test] +fn histogram_counts_opaque_pixels_sorted() { + let px = [[1.0, 0.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0], [1.0, 0.0, 0.0, 0.5], [1.0, 0.0, 0.0, 0.49], [0.0, 0.0, 1.0, 1.0], [0.0, 0.0, 0.0, 1.0]]; + assert_eq!(histogram(&px), vec![([0, 0, 0], 1), ([0, 0, 255], 2), ([255, 0, 0], 2)]); + assert!(histogram(&[]).is_empty()); +} + +#[test] +fn fixed_palettes_have_expected_sizes() { + assert_eq!(web_palette().len(), 216); + assert_eq!(mac_palette().len(), 256); + assert_eq!(windows_palette().len(), 256); + assert_eq!(uniform_palette(27).len(), 27); + let mut m = mac_palette(); + m.sort_unstable(); + m.dedup(); + assert_eq!(m.len(), 256, "mac palette entries are unique"); +} + +#[test] +fn exact_palette_and_failure() { + let px = vec![[1.0, 0.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0], [1.0, 0.0, 0.0, 1.0]]; + assert_eq!(build_palette(&px, PaletteKind::Exact, 256, Forced::None).unwrap().len(), 2); + assert!(build_palette(&gradient(64, 64), PaletteKind::Exact, 256, Forced::None).is_err()); +} + +#[test] +fn adaptive_and_perceptual_respect_count_and_forced() { + let px = gradient(40, 40); + for kind in [PaletteKind::Adaptive, PaletteKind::Perceptual, PaletteKind::Selective] { + let pal = build_palette(&px, kind, 16, Forced::BlackWhite).unwrap(); + assert!(pal.len() <= 16 && pal.len() >= 8, "{kind:?} {}", pal.len()); + assert_eq!(&pal[..2], &[[0, 0, 0], [255, 255, 255]]); + } +} + +#[test] +fn forced_colours_filling_the_count_do_not_panic() { + // 2 colours + Black and White (or 8 + Primaries) leaves no room for + // computed entries; the median cut used to return no centres and + // k-means indexed into the empty list. + let px = vec![[1.0, 1.0, 1.0, 1.0]; 16]; + for kind in [PaletteKind::Adaptive, PaletteKind::Perceptual, PaletteKind::Selective] { + let pal = build_palette(&px, kind, 2, Forced::BlackWhite).unwrap(); + assert_eq!(pal, vec![[0, 0, 0], [255, 255, 255]], "{kind:?}"); + let pal = build_palette(&gradient(8, 8), kind, 8, Forced::Primaries).unwrap(); + assert_eq!(pal.len(), 8, "{kind:?}"); + } +} + +#[test] +#[ignore = "24 MP release timing comparison; run with --release --ignored --nocapture"] +fn indexed_diffusion_24mp_release_comparison() { + let source = gradient(6000, 4000); + let pal = web_palette(); + for run in 0..4 { + let mut linear = source.clone(); + let mut accelerated = source.clone(); + let mut before = None; + let mut after = None; + // Reverse the order on alternating rounds; exclude the first round as warmup. + for old in if run % 2 == 0 { [true, false] } else { [false, true] } { + let start = std::time::Instant::now(); + if old { + let indices = quantize_with(&mut linear, 6000, &pal, Dither::Diffusion, 0.75, None, |c| linear_rgb_nearest(&pal, c)); + before = Some((start.elapsed().as_secs_f64() * 1000.0, indices)); + } else { + let indices = quantize(&mut accelerated, 6000, &pal, Dither::Diffusion, 0.75, None); + after = Some((start.elapsed().as_secs_f64() * 1000.0, indices)); + } + } + let (before_ms, before_indices) = before.unwrap(); + let (after_ms, after_indices) = after.unwrap(); + assert_eq!(before_indices.iter().zip(&after_indices).position(|(a, b)| a != b), None, "first differing index"); + assert_eq!(linear.iter().zip(&accelerated).position(|(a, b)| a != b), None, "first differing pixel"); + println!( + "{}", + serde_json::json!({"run":run,"warmup":run==0,"pixels":24_000_000,"palette_entries":216,"linear_ms":before_ms,"accelerated_ms":after_ms}) + ); + } +} + +fn linear_rgb_nearest(pal: &[Rgb8], c: [f32; 3]) -> usize { + let mut best = (f32::MAX, 0); + for (i, e) in pal.iter().enumerate() { + let d: f32 = (0..3).map(|k| (c[k] * 255.0 - f32::from(e[k])).powi(2)).sum(); + if d < best.0 { + best = (d, i); + } + } + best.1 +} + +#[test] +fn all_dithers_match_the_original_linear_palette_search_exactly() { + let mut source = gradient(93, 61); + for (i, p) in source.iter_mut().enumerate() { + p[2] = (i % 71) as f32 / 70.0; + p[3] = [0.0, 0.2, 0.7, 1.0][i % 4]; + } + for count in [8, 16, 32, 64, 128, 256] { + let pal = build_palette(&source, PaletteKind::Selective, count, Forced::BlackWhite).unwrap(); + for dither in [Dither::None, Dither::Diffusion, Dither::Pattern, Dither::Noise] { + for transparent in [None, Some(1)] { + let mut actual = source.clone(); + let mut expected = source.clone(); + let indices = quantize(&mut actual, 93, &pal, dither, 0.75, transparent); + let old_indices = quantize_with(&mut expected, 93, &pal, dither, 0.75, transparent, |c| linear_rgb_nearest(&pal, c)); + assert_eq!(indices, old_indices, "{count} {dither:?} {transparent:?}"); + assert_eq!(actual, expected, "{count} {dither:?} {transparent:?}"); + } + } + } +} + +#[test] +fn quantize_maps_to_palette_with_each_dither() { + let pal = vec![[0, 0, 0], [255, 255, 255]]; + for d in [Dither::None, Dither::Diffusion, Dither::Pattern, Dither::Noise] { + let mut px: Vec<[f32; 4]> = (0..64) + .map(|i| [i as f32 / 63.0; 4]) + .map(|mut p| { + p[3] = 1.0; + p + }) + .collect(); + let idx = quantize(&mut px, 8, &pal, d, 1.0, None); + assert!(px.iter().all(|p| p[0] == 0.0 || p[0] == 1.0), "{d:?}"); + assert_eq!(idx.len(), 64); + // Mean brightness is preserved by dithering (not by plain thresholding). + if d == Dither::Diffusion { + let mean = px.iter().map(|p| p[0]).sum::() / 64.0; + assert!((mean - 0.5).abs() < 0.08, "{mean}"); + } + } + let mut px = vec![[1.0, 1.0, 1.0, 0.2]]; + let idx = quantize(&mut px, 1, &pal, Dither::None, 1.0, Some(1)); + assert_eq!((idx[0], px[0][3]), (1, 0.0)); +} + +#[test] +fn bitmap_methods_are_binary_and_track_tone() { + for m in [ + BitmapMethod::Threshold, + BitmapMethod::Pattern, + BitmapMethod::Diffusion, + BitmapMethod::Halftone { cell: 6.0, angle: 45.0, shape: HalftoneShape::Round }, + ] { + let mut g = vec![0.25f32; 32 * 32]; + to_bitmap(&mut g, 32, m); + assert!(g.iter().all(|v| *v == 0.0 || *v == 1.0)); + let mean = g.iter().sum::() / g.len() as f32; + if m != BitmapMethod::Threshold { + assert!((mean - 0.25).abs() < 0.15, "{m:?} {mean}"); + } else { + assert_eq!(mean, 0.0); + } + } +} + +/// The first 8-bit gray level (of a 0..=255 ramp) that `t` turns white. +fn first_white(t: f32) -> u32 { + (0..=255).find(|v| *v as f32 / 255.0 >= t).unwrap_or(256) +} + +#[test] +fn custom_pattern_thresholds_match_photoshop() { + // Photoshop (Image › Mode › Bitmap, Custom Pattern) on a 0..255 ramp: the first white + // level per pattern pixel, measured against defined patterns. + let l = |v: &[u8]| v.iter().map(|v| f32::from(*v) / 255.0).collect::>(); + let ramp7 = custom_pattern_thresholds(&l(&[0, 40, 80, 120, 160, 200, 240])); + assert_eq!(ramp7.iter().map(|t| first_white(*t)).collect::>(), [237, 201, 164, 128, 92, 55, 19]); + let five = custom_pattern_thresholds(&l(&[10, 200, 90, 250, 150])); + assert_eq!(five.iter().map(|t| first_white(*t)).collect::>(), [230, 77, 179, 26, 128]); + // Equal pixels share their rank: 100, 100 both sit at 50%. + let ties = custom_pattern_thresholds(&l(&[100, 100, 200, 50])); + assert_eq!(ties.iter().map(|t| first_white(*t)).collect::>(), [128, 128, 32, 224]); + assert!(custom_pattern_thresholds(&[]).is_empty()); + assert_eq!(custom_pattern_thresholds(&[f32::NAN, 0.3]).len(), 2); +} + +#[test] +fn custom_pattern_tiles_from_the_top_left() { + // A 2x1 map: even columns need 75%, odd ones 25%. + let map = [0.75, 0.25]; + let mut g = vec![0.5; 6]; + to_bitmap_custom(&mut g, 3, &map, 2, 1); + assert_eq!(g, [0.0, 1.0, 0.0, 0.0, 1.0, 0.0]); + // A map that doesn't match its size, or an empty image width, is a 50% threshold. + let mut g = vec![0.4, 0.6]; + to_bitmap_custom(&mut g, 2, &map, 3, 1); + assert_eq!(g, [0.0, 1.0]); + let mut g = vec![0.6]; + to_bitmap_custom(&mut g, 0, &map, 2, 1); + assert_eq!(g, [1.0]); +} diff --git a/crates/algo/src/resample.rs b/crates/algo/src/resample.rs index 4ad84a10c0..4dcf0b6944 100644 --- a/crates/algo/src/resample.rs +++ b/crates/algo/src/resample.rs @@ -514,407 +514,4 @@ pub fn crop_surface(s: &Surface, keep: Rect) -> Surface { } #[cfg(test)] -mod tests { - use super::*; - use photocraft_color::{ColorMode, PixelFormat, SampleType}; - - fn ramp(sample: SampleType) -> Surface { - let mut s = Surface::new(PixelFormat::new(ColorMode::Rgb, sample, true)); - let r = Rect::new(0, 0, 64, 32); - let v: Vec = (0..32).flat_map(|_| (0..64).flat_map(|x| [x as f32 / 63.0, 0.5, 1.0 - x as f32 / 63.0, 1.0])).collect(); - s.write_region(r, &v); - s - } - - #[test] - fn fixed_channel_rows_match_dynamic_resampling() { - fn check() { - for scale in [0.12, 0.5, 1.0, 2.3] { - for filter in [Kernel::Nearest, Kernel::Bilinear, keys(Resample::Bicubic, scale), keys(Resample::BicubicSharper, scale), Kernel::Lanczos] { - for clamp in [None, Some((-3, 31))] { - let ts = taps(-5, 41, scale, filter, clamp, (-3, 31)); - let row: Vec = (0..35 * N).map(|i| ((i * 73) % 251) as f32 / 250.0).collect(); - let def: Vec = (0..N).map(|i| i as f32 / 7.0).collect(); - let mut expected = vec![0.0; ts.len() * N]; - let mut actual = expected.clone(); - horizontal_dynamic(&row, &mut expected, &ts, -3, &def, N); - horizontal_fixed::(&row, &mut actual, &ts, -3, &def); - assert_eq!(actual, expected, "N={N} scale={scale} filter={filter:?} clamp={clamp:?}"); - } - } - } - } - check::<1>(); - check::<2>(); - check::<3>(); - check::<4>(); - check::<5>(); - } - - /// Photoshop 25.4's Image Size of a 16-bit greyscale pattern, in levels of 32768. Covers the - /// filters and their 2-D rules: Sharper reducing the width while the height grows is designed - /// for the height (not widened) and runs the width first; Bicubic Automatic splits a mixed - /// resize into Sharper and Smoother; Bicubic widens for the height's 0.6 while the width - /// grows; Smoother below ¼ averages down first; Bilinear below ½ averages whole pixels. On black - /// and white the overshoot is clipped between the passes, so their order shows. - #[test] - fn matches_photoshop_image_size() { - // (black and white pattern, filter, size, new size, Photoshop's levels) - type Probe = (bool, Resample, (i32, i32), (i32, i32), &'static [u16]); - let cases: [Probe; 9] = [ - ( - false, - Resample::BicubicSharper, - (12, 10), - (7, 16), - &[ - 3777, 13165, 22219, 16176, 10460, 19488, 29643, 11249, 12634, 21696, 13330, 10319, 18965, 29120, 21280, 11204, 20279, 16184, 8200, 17548, - 27703, 21824, 10182, 19259, 26967, 5238, 16528, 26683, 17366, 8895, 17922, 32768, 2402, 15190, 25345, 17493, 7834, 16903, 31316, 1748, - 14172, 24326, 24718, 6368, 15746, 30390, 0, 13107, 23169, 31215, 4790, 14456, 27639, 5080, 11597, 21880, 29649, 3864, 13507, 24136, 20600, - 10264, 20931, 28009, 0, 12446, 21385, 28735, 8754, 19642, 26154, 4049, 10895, 20832, 23523, 7620, 18485, 23204, 20126, 8787, 19818, 21447, - 6173, 17467, 20390, 31862, 6616, 18480, 24094, 6500, 16129, 19749, 27472, 5810, 17460, 28281, 7655, 15108, 18394, 25515, 4427, 16043, - 28749, 7026, 13691, 17871, 24992, 3904, 15520, 27200, 6075, 13168, - ], - ), - ( - false, - Resample::BicubicAutomatic, - (12, 10), - (7, 16), - &[ - 4201, 12337, 27677, 15894, 4816, 20021, 29631, 10348, 9882, 27304, 14492, 3766, 19574, 29046, 18743, 5944, 25299, 16116, 4147, 17829, - 27787, 19399, 4206, 21790, 23748, 7966, 15117, 26569, 15941, 2695, 19445, 28341, 10104, 13050, 25465, 16251, 2613, 18023, 26770, 8432, - 11951, 24281, 22800, 7141, 15351, 24790, 5953, 11004, 23130, 28322, 10921, 12440, 24940, 9659, 9368, 22012, 27611, 10006, 10488, 26419, - 18657, 7071, 20807, 25492, 6937, 9239, 26574, 22363, 5435, 19688, 24808, 9136, 8184, 25295, 19708, 3939, 18677, 25053, 18234, 7120, 24061, - 17941, 2545, 17568, 24869, 23748, 6081, 21401, 21862, 6018, 15056, 23602, 22177, 4859, 17816, 28450, 11911, 11653, 22253, 20263, 3595, - 15790, 29734, 12969, 9683, 21668, 19678, 3010, 15424, 28429, 11728, 9300, - ], - ), - ( - false, - Resample::Bicubic, - (12, 10), - (20, 6), - &[ - 11517, 10000, 8617, 9364, 12272, 16362, 21396, 25508, 25506, 19474, 10887, 5289, 5842, 10286, 14986, 18566, 21910, 25511, 28611, 29922, - 24788, 17949, 8497, 4593, 7309, 12594, 17150, 20945, 24892, 26196, 22979, 16123, 9691, 7483, 10061, 14653, 18841, 22420, 25514, 26824, - 25702, 23396, 17586, 11378, 8127, 8882, 12310, 17039, 22345, 25871, 24700, 18125, 9951, 5493, 6802, 11215, 15576, 19259, 22384, 23694, - 26692, 26985, 22732, 14270, 6889, 4950, 8348, 13583, 17529, 21570, 25966, 27275, 22817, 14643, 8068, 6911, 10694, 15930, 19443, 20705, - 21499, 23413, 25601, 24336, 18665, 11686, 7800, 8947, 12974, 18067, 22707, 25285, 23077, 16645, 9789, 6586, 8147, 12329, 15935, 17465, - 17962, 20462, 24615, 25377, 20036, 11458, 5421, 5415, 9528, 14134, 17782, 22482, 26926, 27479, 21881, 13308, 7533, 7734, 11549, 13992, - ], - ), - ( - false, - Resample::BicubicSmoother, - (40, 3), - (9, 3), - &[ - 11315, 18740, 17475, 15974, 16503, 16042, 18215, 14712, 16238, 18482, 14351, 14664, 18012, 20260, 13338, 15511, 18468, 18275, 16790, 19168, - 14745, 14998, 20341, 18150, 13819, 16493, 16432, - ], - ), - ( - false, - Resample::Bilinear, - (12, 10), - (5, 4), - &[11316, 14541, 17920, 10855, 24679, 19763, 9933, 23757, 6247, 20070, 25601, 5325, 19149, 17306, 15463, 20992, 16384, 14541, 23143, 10854], - ), - ( - false, - Resample::Nearest, - (12, 10), - (7, 16), - &[ - 1638, 12698, 23757, 3482, 9011, 20070, 31130, 1638, 12698, 23757, 3482, 9011, 20070, 31130, 31130, 10854, 21914, 1638, 7168, 18227, 29286, - 29286, 9011, 20070, 31130, 5325, 16384, 27443, 29286, 9011, 20070, 31130, 5325, 16384, 27443, 27443, 7168, 18227, 29286, 3482, 14541, - 25600, 25600, 5325, 16384, 27443, 1638, 12698, 23757, 25600, 5325, 16384, 27443, 1638, 12698, 23757, 23757, 3482, 14541, 25600, 31130, - 10854, 21914, 23757, 3482, 14541, 25600, 31130, 10854, 21914, 21914, 1638, 12698, 23757, 29286, 9011, 20070, 20070, 31130, 10854, 21914, - 27443, 7168, 18227, 20070, 31130, 10854, 21914, 27443, 7168, 18227, 18227, 29286, 9011, 20070, 25600, 5325, 16384, 16384, 27443, 7168, - 18227, 23757, 3482, 14541, 16384, 27443, 7168, 18227, 23757, 3482, 14541, - ], - ), - ( - true, - Resample::Bicubic, - (12, 10), - (20, 6), - &[ - 9960, 6313, 993, 0, 4525, 14807, 26472, 32768, 32768, 23510, 10514, 0, 0, 0, 10110, 22576, 31764, 32768, 32768, 32768, 26136, 18594, 6164, - 0, 0, 2565, 14499, 26983, 32768, 32768, 26358, 14709, 3969, 0, 0, 6602, 17734, 27952, 32768, 32768, 31590, 27808, 18307, 7429, 0, 0, 3712, - 14435, 26473, 32768, 31131, 20665, 7535, 0, 0, 2177, 13238, 25049, 32768, 32768, 32768, 32768, 26136, 14174, 2548, 0, 0, 6190, 18705, - 30273, 32768, 32768, 25517, 13238, 2177, 0, 0, 7250, 19418, 26624, 32768, 32768, 32768, 28203, 18522, 7200, 0, 0, 3285, 14794, 26862, - 32768, 29913, 19013, 6667, 0, 0, 4443, 14506, 20751, 17344, 23066, 31075, 32361, 23949, 10738, 0, 0, 0, 10110, 22657, 32768, 32768, 32768, - 22658, 10192, 1004, 0, 0, 0, - ], - ), - ( - true, - Resample::BicubicSharper, - (12, 10), - (7, 16), - &[ - 801, 3050, 32489, 16260, 0, 29819, 32767, 9161, 1781, 29578, 14350, 0, 32768, 32767, 21132, 0, 25409, 17862, 0, 26925, 32767, 22769, 0, - 24839, 27566, 0, 9397, 32768, 19813, 0, 27795, 32768, 0, 0, 32768, 20744, 0, 25797, 32768, 0, 0, 32768, 27555, 0, 11184, 32768, 0, 0, - 32768, 32768, 0, 0, 32768, 5110, 0, 30386, 32768, 0, 0, 32768, 20385, 0, 23267, 32768, 0, 0, 32768, 29130, 0, 19191, 32768, 2670, 0, 31290, - 25387, 0, 21263, 32767, 20198, 0, 21586, 24510, 0, 23714, 32768, 32768, 0, 14165, 27804, 1007, 14254, 32768, 30149, 0, 16077, 32112, 2886, - 1884, 21043, 29607, 0, 16384, 32768, 3566, 0, 12683, 29616, 0, 16384, 32768, 3196, 0, - ], - ), - ( - true, - Resample::BicubicSharper, - (12, 10), - (20, 6), - &[ - 9273, 5043, 0, 0, 2698, 14484, 28464, 32768, 32768, 24841, 10877, 0, 0, 0, 9684, 22346, 31492, 32768, 32768, 32768, 25960, 18430, 4978, 0, - 0, 977, 15047, 28475, 32768, 32768, 27939, 14157, 1813, 0, 0, 5296, 17828, 28439, 32768, 32768, 32768, 27849, 17576, 6209, 0, 0, 2169, - 15076, 28935, 32768, 32768, 22167, 7399, 0, 0, 211, 12977, 24638, 32768, 32768, 32768, 32768, 25960, 14244, 824, 0, 0, 5093, 18802, 31993, - 32768, 32768, 26467, 12977, 211, 0, 0, 6300, 19418, 26712, 32768, 32768, 32768, 27907, 17874, 5820, 0, 0, 1853, 16055, 29518, 32768, 32768, - 20889, 5880, 0, 0, 2879, 13798, 20185, 19010, 25565, 32768, 32302, 25431, 11478, 0, 0, 0, 9684, 23083, 32768, 32768, 32768, 23084, 10422, - 1276, 0, 0, 0, - ], - ), - ]; - for (binary, filter, (w, h), (wo, ho), want) in cases { - let mut s = Surface::new(PixelFormat::new(ColorMode::Grayscale, SampleType::U16, false)); - let canvas = Rect::new(0, 0, w, h); - let level = |x: i32, y: i32| match ((x * 37 + y * 101) % 17) as f32 { - k if binary => { - if k > 8.0 { - 32767.0 / 32768.0 - } else { - 0.0 - } - } - k => ((k / 16.0 * 0.9 + 0.05) * 32768.0).round() / 32768.0, - }; - let px: Vec = (0..h).flat_map(|y| (0..w).map(move |x| level(x, y))).collect(); - s.write_region(canvas, &px); - let o = resize_surface_in_canvas(&s, wo as f64 / w as f64, ho as f64 / h as f64, filter, canvas); - let got = o.read_region(Rect::new(0, 0, wo, ho)); - assert_eq!(got.len(), want.len(), "{filter:?}"); - let worst = got.iter().zip(want).map(|(g, &p)| (g * 32768.0 - p as f32).abs()).fold(0.0f32, f32::max); - assert!(worst <= 8.0, "{filter:?} {w}x{h} to {wo}x{ho}: {worst} levels of 32768 from Photoshop"); - } - } - - /// Photoshop's Bicubic doubles with the Keys cubic at a = −0.75 (Catmull-Rom is −0.5): an - /// impulse spreads as −9, −27, 67, 225 /256 and back, as Photoshop 25.4 gives it. - #[test] - fn bicubic_is_photoshops_keys_cubic() { - let mut s = Surface::new(PixelFormat::new(ColorMode::Grayscale, SampleType::F32, false)); - let mut row = [0.25; 30]; - row[10] = 0.75; - s.write_region(Rect::new(0, 0, 30, 1), &row); - let o = resize_surface(&s, 2.0, 1.0, Resample::Bicubic); - let got: Vec = o.read_region(Rect::new(17, 0, 25, 1)).iter().map(|v| (v - 0.25) * 512.0).collect(); - for (g, want) in got.iter().zip([-9.0, -27.0, 67.0, 225.0, 225.0, 67.0, -27.0, -9.0]) { - assert!((g - want).abs() < 1e-3, "{got:?}"); - } - } - - #[test] - fn identity_scale_is_lossless() { - for f in [Resample::Nearest, Resample::Bilinear, Resample::Bicubic, Resample::Lanczos] { - let s = ramp(SampleType::U16); - let o = resize_surface(&s, 1.0, 1.0, f); - let r = Rect::new(0, 0, 64, 32); - let (a, b) = (s.read_region(r), o.read_region(r)); - let d = a.iter().zip(&b).map(|(x, y)| (x - y).abs()).fold(0.0f32, f32::max); - assert!(d < 1e-4, "{f:?} {d}"); - } - } - - #[test] - fn half_and_double_sizes() { - for f in [Resample::Nearest, Resample::Bilinear, Resample::Bicubic, Resample::Lanczos, Resample::PreserveDetails] { - let s = ramp(SampleType::F32); - let half = resize_surface(&s, 0.5, 0.5, f); - assert_eq!(half.content_bounds(), Rect::new(0, 0, 32, 16), "{f:?}"); - let p = half.pixel(16, 8); - assert!((p[1] - 0.5).abs() < 0.02 && (p[3] - 1.0).abs() < 1e-3, "{f:?} {p:?}"); - let dbl = resize_surface(&s, 2.0, 2.0, f); - assert_eq!(dbl.content_bounds(), Rect::new(0, 0, 128, 64), "{f:?}"); - // Mid-gray channel and the ramp's monotonicity are preserved. - let row: Vec = (8..120).map(|x| dbl.pixel(x, 30)[0]).collect(); - assert!(row.windows(2).all(|w| w[1] >= w[0] - 0.02), "{f:?}"); - } - } - - #[test] - fn downscale_averages_checkerboard() { - let mut s = Surface::new(PixelFormat::RGBA8); - for y in 0..64 { - for x in 0..64 { - let v = ((x + y) % 2) as f32; - s.write_pixel(x, y, &[v, v, v, 1.0]); - } - } - let o = resize_surface(&s, 0.25, 0.25, Resample::Bicubic); - let p = o.pixel(8, 8); - assert!((p[0] - 0.5).abs() < 0.05, "{p:?}"); - } - - /// A reduction by a tiny scale covers millions of source samples per output sample; only the - /// ones in the content get a weight, the rest fold onto its ends or into `outside`. - #[test] - fn tiny_scales_do_not_get_a_weight_per_covered_sample() { - for kernel in [Kernel::Bilinear, Kernel::Keys { a: -0.5, stretch: 1.0 }] { - for edge in [None, Some((0, 99))] { - let t = taps(0, 3, 1e-6, kernel, edge, (0, 99)); - for t in &t { - assert!(t.weights.len() <= 100, "{}", t.weights.len()); - let total = t.weights.iter().sum::() + t.outside; - assert!((total - 1.0).abs() < 1e-3, "{total}"); - } - } - } - } - - #[test] - fn transparent_edges_do_not_darken() { - let mut s = Surface::new(PixelFormat::RGBA32F); - s.fill_rect(Rect::new(10, 10, 20, 20), &[1.0, 0.0, 0.0, 1.0]); - let o = resize_surface(&s, 1.7, 1.7, Resample::Lanczos); - let edge = o.pixel(17, 25); - assert!(edge[3] > 0.0 && (edge[0] - 1.0).abs() < 0.05 && edge[1].abs() < 0.05, "{edge:?}"); - } - - /// Image Size of a layer that fills the canvas: its edges stay opaque and keep their colour, - /// up or down, at every depth; a layer away from the edges keeps its soft border. - #[test] - fn canvas_edges_repeat_instead_of_fading() { - let canvas = Rect::new(0, 0, 30, 20); - let colour = [0.2, 0.6, 1.0, 1.0]; - let filters = [Resample::Nearest, Resample::Bilinear, Resample::Bicubic, Resample::Lanczos, Resample::PreserveDetails]; - for sample in [SampleType::U8, SampleType::U16, SampleType::F32] { - let fmt = PixelFormat::new(ColorMode::Rgb, sample, true); - let mut s = Surface::new(fmt); - s.fill_rect(canvas, &colour); - for f in filters { - for k in [2.0, 1.37, 0.5] { - let o = resize_surface_in_canvas(&s, k, k, f, canvas); - let dst = scaled_rect(canvas, k, k); - assert_eq!(o.content_bounds(), dst, "{sample:?} {f:?} {k}"); - for (x, y) in [(0, 0), (dst.x1 - 1, 0), (0, dst.y1 - 1), (dst.x1 - 1, dst.y1 - 1), (dst.x1 / 2, 0), (0, dst.y1 / 2)] { - let p = o.pixel(x, y); - let off = p.iter().zip(colour).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); - assert!(off < 0.01, "{sample:?} {f:?} {k} ({x},{y}): {p:?}"); - } - } - } - // Inside the canvas the default pixel is still what lies around a layer. - let mut inner = Surface::new(fmt); - inner.fill_rect(Rect::new(10, 5, 20, 15), &[1.0, 0.0, 0.0, 1.0]); - let r = Rect::new(0, 0, 60, 40); - let a = resize_surface_in_canvas(&inner, 1.7, 1.7, Resample::Lanczos, canvas); - assert_eq!(a.read_region(r), resize_surface(&inner, 1.7, 1.7, Resample::Lanczos).read_region(r), "{sample:?}"); - } - } - - /// Two tiles in opposite corners of a 100000 px square: the content bounds are huge but - /// almost nothing is stored. Shrinking it to one pixel must neither allocate a window - /// proportional to the scale (#713) nor read the empty middle. - #[test] - fn tiny_target_of_a_huge_sparse_source() { - let mut s = Surface::new(PixelFormat::RGBA32F); - s.fill_rect(Rect::new(0, 0, 256, 256), &[1.0, 1.0, 1.0, 1.0]); - s.fill_rect(Rect::new(99_840, 99_840, 100_096, 100_096), &[1.0, 1.0, 1.0, 1.0]); - let k = 1.0 / 100_096.0; - let o = resize_surface(&s, k, k, Resample::Bicubic); - assert_eq!(o.content_bounds(), Rect::new(0, 0, 1, 1)); - let p = o.pixel(0, 0); - // Two 256² tiles out of 100096²: nearly transparent, and white where it isn't. - assert!(p[3] >= 0.0 && p[3] < 1e-3 && p.iter().all(|v| v.is_finite()), "{p:?}"); - // Squashed to one row but kept wide: the whole height feeds one band of output rows, - // which must not hold a full-height intermediate. - let o = resize_surface(&s, 1000.0 / 100_096.0, k, Resample::Bicubic); - let b = o.content_bounds(); - assert!(b.height() == 1 && (1000..=1001).contains(&b.width()), "{b:?}"); - assert!(o.pixel(0, 0)[3] > 0.0 && o.pixel(500, 0)[3] == 0.0, "{:?} {:?}", o.pixel(0, 0), o.pixel(500, 0)); - } - - /// Tile rows with nothing stored are not read; they count as rows of the default pixel, - /// exactly as reading them would (and within rounding for a non-zero default). - #[test] - fn skipped_empty_rows_match_reading_them() { - for (fmt, def, tol) in [(PixelFormat::RGBA32F, vec![0.0, 0.0, 0.0, 0.0], 0.0), (PixelFormat::GRAY8, vec![1.0], 1e-6)] { - let mut sparse = Surface::with_default(fmt, &def); - sparse.fill_rect(Rect::new(0, 0, 300, 40), &vec![0.5; def.len()]); - sparse.fill_rect(Rect::new(100, 1500, 400, 1540), &vec![0.25; def.len()]); - // The same pixels with the empty rows stored as tiles of the default pixel. - let mut dense = sparse.clone(); - dense.fill_rect(Rect::new(0, 40, 400, 1500), &def); - assert!(dense.tile_count() > sparse.tile_count()); - for f in [Resample::Bilinear, Resample::Bicubic, Resample::Lanczos] { - for (kx, ky) in [(0.013, 0.013), (0.37, 0.37), (1.0, 0.01)] { - let (a, b) = (resize_surface(&sparse, kx, ky, f), resize_surface(&dense, kx, ky, f)); - let r = a.content_bounds().union(&b.content_bounds()); - let d = a.read_region(r).iter().zip(b.read_region(r)).map(|(x, y)| (x - y).abs()).fold(0.0f32, f32::max); - assert!(d <= tol, "{fmt:?} {f:?} {kx} {ky}: {d}"); - } - } - } - } - - /// Reading the source in row chunks gives exactly what one read of the whole window gives. - #[test] - fn chunked_reads_match_a_single_read() { - let mut s = ramp(SampleType::F32); - s.fill_rect(Rect::new(600, 700, 640, 720), &[0.3, 0.9, 0.1, 0.5]); - let mut mask = Surface::with_default(PixelFormat::GRAY8, &[1.0]); - mask.fill_rect(Rect::new(0, 0, 40, 30), &[0.0]); - mask.fill_rect(Rect::new(500, 900, 530, 940), &[0.25]); - for src in [&s, &mask] { - for f in [Resample::Nearest, Resample::Bilinear, Resample::Bicubic, Resample::Lanczos] { - for k in [0.013, 0.37, 1.6] { - let whole = resize_with_budget(src, k, k, f, None, usize::MAX); - let chunked = resize_with_budget(src, k, k, f, None, 1); - let r = whole.content_bounds().union(&chunked.content_bounds()); - assert_eq!(whole.read_region(r), chunked.read_region(r), "{f:?} {k}"); - } - } - } - } - - #[test] - fn masks_keep_default_pixel() { - let fmt = PixelFormat::GRAY8; - let mut m = Surface::with_default(fmt, &[1.0]); - m.fill_rect(Rect::new(0, 0, 10, 10), &[0.0]); - let o = resize_surface(&m, 2.0, 2.0, Resample::Bilinear); - assert_eq!(o.default_pixel(), vec![1.0]); - assert!(o.pixel(5, 5)[0] < 0.01); - } - - #[test] - fn translate_and_crop() { - let s = ramp(SampleType::U8); - let t = translate_surface(&s, 5, -3); - assert_eq!(t.pixel(15, 7), s.pixel(10, 10)); - let c = crop_surface(&s, Rect::new(0, 0, 10, 10)); - assert_eq!(c.content_bounds(), Rect::new(0, 0, 10, 10)); - } - - /// #1114: nearest neighbor reduction must sample single source pixels, never average. - #[test] - fn nearest_neighbor_reduction_does_not_average() { - let mut s = Surface::new(PixelFormat::GRAY8); - for y in 0..8 { - for x in 0..8 { - if (x + y) % 2 == 0 { - s.fill_rect(Rect::new(x, y, x + 1, y + 1), &[1.0]); - } - } - } - let reduced = resize_surface(&s, 0.5, 0.5, Resample::Nearest); - for y in 0..4 { - for x in 0..4 { - let p = reduced.pixel(x, y)[0]; - assert!(p == 0.0 || p == 1.0, "nearest produced an averaged value {p} at ({x}, {y})"); - } - } - } -} +mod tests; diff --git a/crates/algo/src/resample/tests.rs b/crates/algo/src/resample/tests.rs new file mode 100644 index 0000000000..0ee08847e1 --- /dev/null +++ b/crates/algo/src/resample/tests.rs @@ -0,0 +1,402 @@ +use super::*; +use photocraft_color::{ColorMode, PixelFormat, SampleType}; + +fn ramp(sample: SampleType) -> Surface { + let mut s = Surface::new(PixelFormat::new(ColorMode::Rgb, sample, true)); + let r = Rect::new(0, 0, 64, 32); + let v: Vec = (0..32).flat_map(|_| (0..64).flat_map(|x| [x as f32 / 63.0, 0.5, 1.0 - x as f32 / 63.0, 1.0])).collect(); + s.write_region(r, &v); + s +} + +#[test] +fn fixed_channel_rows_match_dynamic_resampling() { + fn check() { + for scale in [0.12, 0.5, 1.0, 2.3] { + for filter in [Kernel::Nearest, Kernel::Bilinear, keys(Resample::Bicubic, scale), keys(Resample::BicubicSharper, scale), Kernel::Lanczos] { + for clamp in [None, Some((-3, 31))] { + let ts = taps(-5, 41, scale, filter, clamp, (-3, 31)); + let row: Vec = (0..35 * N).map(|i| ((i * 73) % 251) as f32 / 250.0).collect(); + let def: Vec = (0..N).map(|i| i as f32 / 7.0).collect(); + let mut expected = vec![0.0; ts.len() * N]; + let mut actual = expected.clone(); + horizontal_dynamic(&row, &mut expected, &ts, -3, &def, N); + horizontal_fixed::(&row, &mut actual, &ts, -3, &def); + assert_eq!(actual, expected, "N={N} scale={scale} filter={filter:?} clamp={clamp:?}"); + } + } + } + } + check::<1>(); + check::<2>(); + check::<3>(); + check::<4>(); + check::<5>(); +} + +/// Photoshop 25.4's Image Size of a 16-bit greyscale pattern, in levels of 32768. Covers the +/// filters and their 2-D rules: Sharper reducing the width while the height grows is designed +/// for the height (not widened) and runs the width first; Bicubic Automatic splits a mixed +/// resize into Sharper and Smoother; Bicubic widens for the height's 0.6 while the width +/// grows; Smoother below ¼ averages down first; Bilinear below ½ averages whole pixels. On black +/// and white the overshoot is clipped between the passes, so their order shows. +#[test] +fn matches_photoshop_image_size() { + // (black and white pattern, filter, size, new size, Photoshop's levels) + type Probe = (bool, Resample, (i32, i32), (i32, i32), &'static [u16]); + let cases: [Probe; 9] = [ + ( + false, + Resample::BicubicSharper, + (12, 10), + (7, 16), + &[ + 3777, 13165, 22219, 16176, 10460, 19488, 29643, 11249, 12634, 21696, 13330, 10319, 18965, 29120, 21280, 11204, 20279, 16184, 8200, 17548, + 27703, 21824, 10182, 19259, 26967, 5238, 16528, 26683, 17366, 8895, 17922, 32768, 2402, 15190, 25345, 17493, 7834, 16903, 31316, 1748, 14172, + 24326, 24718, 6368, 15746, 30390, 0, 13107, 23169, 31215, 4790, 14456, 27639, 5080, 11597, 21880, 29649, 3864, 13507, 24136, 20600, 10264, + 20931, 28009, 0, 12446, 21385, 28735, 8754, 19642, 26154, 4049, 10895, 20832, 23523, 7620, 18485, 23204, 20126, 8787, 19818, 21447, 6173, + 17467, 20390, 31862, 6616, 18480, 24094, 6500, 16129, 19749, 27472, 5810, 17460, 28281, 7655, 15108, 18394, 25515, 4427, 16043, 28749, 7026, + 13691, 17871, 24992, 3904, 15520, 27200, 6075, 13168, + ], + ), + ( + false, + Resample::BicubicAutomatic, + (12, 10), + (7, 16), + &[ + 4201, 12337, 27677, 15894, 4816, 20021, 29631, 10348, 9882, 27304, 14492, 3766, 19574, 29046, 18743, 5944, 25299, 16116, 4147, 17829, 27787, + 19399, 4206, 21790, 23748, 7966, 15117, 26569, 15941, 2695, 19445, 28341, 10104, 13050, 25465, 16251, 2613, 18023, 26770, 8432, 11951, 24281, + 22800, 7141, 15351, 24790, 5953, 11004, 23130, 28322, 10921, 12440, 24940, 9659, 9368, 22012, 27611, 10006, 10488, 26419, 18657, 7071, 20807, + 25492, 6937, 9239, 26574, 22363, 5435, 19688, 24808, 9136, 8184, 25295, 19708, 3939, 18677, 25053, 18234, 7120, 24061, 17941, 2545, 17568, + 24869, 23748, 6081, 21401, 21862, 6018, 15056, 23602, 22177, 4859, 17816, 28450, 11911, 11653, 22253, 20263, 3595, 15790, 29734, 12969, 9683, + 21668, 19678, 3010, 15424, 28429, 11728, 9300, + ], + ), + ( + false, + Resample::Bicubic, + (12, 10), + (20, 6), + &[ + 11517, 10000, 8617, 9364, 12272, 16362, 21396, 25508, 25506, 19474, 10887, 5289, 5842, 10286, 14986, 18566, 21910, 25511, 28611, 29922, 24788, + 17949, 8497, 4593, 7309, 12594, 17150, 20945, 24892, 26196, 22979, 16123, 9691, 7483, 10061, 14653, 18841, 22420, 25514, 26824, 25702, 23396, + 17586, 11378, 8127, 8882, 12310, 17039, 22345, 25871, 24700, 18125, 9951, 5493, 6802, 11215, 15576, 19259, 22384, 23694, 26692, 26985, 22732, + 14270, 6889, 4950, 8348, 13583, 17529, 21570, 25966, 27275, 22817, 14643, 8068, 6911, 10694, 15930, 19443, 20705, 21499, 23413, 25601, 24336, + 18665, 11686, 7800, 8947, 12974, 18067, 22707, 25285, 23077, 16645, 9789, 6586, 8147, 12329, 15935, 17465, 17962, 20462, 24615, 25377, 20036, + 11458, 5421, 5415, 9528, 14134, 17782, 22482, 26926, 27479, 21881, 13308, 7533, 7734, 11549, 13992, + ], + ), + ( + false, + Resample::BicubicSmoother, + (40, 3), + (9, 3), + &[ + 11315, 18740, 17475, 15974, 16503, 16042, 18215, 14712, 16238, 18482, 14351, 14664, 18012, 20260, 13338, 15511, 18468, 18275, 16790, 19168, + 14745, 14998, 20341, 18150, 13819, 16493, 16432, + ], + ), + ( + false, + Resample::Bilinear, + (12, 10), + (5, 4), + &[11316, 14541, 17920, 10855, 24679, 19763, 9933, 23757, 6247, 20070, 25601, 5325, 19149, 17306, 15463, 20992, 16384, 14541, 23143, 10854], + ), + ( + false, + Resample::Nearest, + (12, 10), + (7, 16), + &[ + 1638, 12698, 23757, 3482, 9011, 20070, 31130, 1638, 12698, 23757, 3482, 9011, 20070, 31130, 31130, 10854, 21914, 1638, 7168, 18227, 29286, + 29286, 9011, 20070, 31130, 5325, 16384, 27443, 29286, 9011, 20070, 31130, 5325, 16384, 27443, 27443, 7168, 18227, 29286, 3482, 14541, 25600, + 25600, 5325, 16384, 27443, 1638, 12698, 23757, 25600, 5325, 16384, 27443, 1638, 12698, 23757, 23757, 3482, 14541, 25600, 31130, 10854, 21914, + 23757, 3482, 14541, 25600, 31130, 10854, 21914, 21914, 1638, 12698, 23757, 29286, 9011, 20070, 20070, 31130, 10854, 21914, 27443, 7168, 18227, + 20070, 31130, 10854, 21914, 27443, 7168, 18227, 18227, 29286, 9011, 20070, 25600, 5325, 16384, 16384, 27443, 7168, 18227, 23757, 3482, 14541, + 16384, 27443, 7168, 18227, 23757, 3482, 14541, + ], + ), + ( + true, + Resample::Bicubic, + (12, 10), + (20, 6), + &[ + 9960, 6313, 993, 0, 4525, 14807, 26472, 32768, 32768, 23510, 10514, 0, 0, 0, 10110, 22576, 31764, 32768, 32768, 32768, 26136, 18594, 6164, 0, + 0, 2565, 14499, 26983, 32768, 32768, 26358, 14709, 3969, 0, 0, 6602, 17734, 27952, 32768, 32768, 31590, 27808, 18307, 7429, 0, 0, 3712, 14435, + 26473, 32768, 31131, 20665, 7535, 0, 0, 2177, 13238, 25049, 32768, 32768, 32768, 32768, 26136, 14174, 2548, 0, 0, 6190, 18705, 30273, 32768, + 32768, 25517, 13238, 2177, 0, 0, 7250, 19418, 26624, 32768, 32768, 32768, 28203, 18522, 7200, 0, 0, 3285, 14794, 26862, 32768, 29913, 19013, + 6667, 0, 0, 4443, 14506, 20751, 17344, 23066, 31075, 32361, 23949, 10738, 0, 0, 0, 10110, 22657, 32768, 32768, 32768, 22658, 10192, 1004, 0, 0, + 0, + ], + ), + ( + true, + Resample::BicubicSharper, + (12, 10), + (7, 16), + &[ + 801, 3050, 32489, 16260, 0, 29819, 32767, 9161, 1781, 29578, 14350, 0, 32768, 32767, 21132, 0, 25409, 17862, 0, 26925, 32767, 22769, 0, 24839, + 27566, 0, 9397, 32768, 19813, 0, 27795, 32768, 0, 0, 32768, 20744, 0, 25797, 32768, 0, 0, 32768, 27555, 0, 11184, 32768, 0, 0, 32768, 32768, 0, + 0, 32768, 5110, 0, 30386, 32768, 0, 0, 32768, 20385, 0, 23267, 32768, 0, 0, 32768, 29130, 0, 19191, 32768, 2670, 0, 31290, 25387, 0, 21263, + 32767, 20198, 0, 21586, 24510, 0, 23714, 32768, 32768, 0, 14165, 27804, 1007, 14254, 32768, 30149, 0, 16077, 32112, 2886, 1884, 21043, 29607, + 0, 16384, 32768, 3566, 0, 12683, 29616, 0, 16384, 32768, 3196, 0, + ], + ), + ( + true, + Resample::BicubicSharper, + (12, 10), + (20, 6), + &[ + 9273, 5043, 0, 0, 2698, 14484, 28464, 32768, 32768, 24841, 10877, 0, 0, 0, 9684, 22346, 31492, 32768, 32768, 32768, 25960, 18430, 4978, 0, 0, + 977, 15047, 28475, 32768, 32768, 27939, 14157, 1813, 0, 0, 5296, 17828, 28439, 32768, 32768, 32768, 27849, 17576, 6209, 0, 0, 2169, 15076, + 28935, 32768, 32768, 22167, 7399, 0, 0, 211, 12977, 24638, 32768, 32768, 32768, 32768, 25960, 14244, 824, 0, 0, 5093, 18802, 31993, 32768, + 32768, 26467, 12977, 211, 0, 0, 6300, 19418, 26712, 32768, 32768, 32768, 27907, 17874, 5820, 0, 0, 1853, 16055, 29518, 32768, 32768, 20889, + 5880, 0, 0, 2879, 13798, 20185, 19010, 25565, 32768, 32302, 25431, 11478, 0, 0, 0, 9684, 23083, 32768, 32768, 32768, 23084, 10422, 1276, 0, 0, + 0, + ], + ), + ]; + for (binary, filter, (w, h), (wo, ho), want) in cases { + let mut s = Surface::new(PixelFormat::new(ColorMode::Grayscale, SampleType::U16, false)); + let canvas = Rect::new(0, 0, w, h); + let level = |x: i32, y: i32| match ((x * 37 + y * 101) % 17) as f32 { + k if binary => { + if k > 8.0 { + 32767.0 / 32768.0 + } else { + 0.0 + } + } + k => ((k / 16.0 * 0.9 + 0.05) * 32768.0).round() / 32768.0, + }; + let px: Vec = (0..h).flat_map(|y| (0..w).map(move |x| level(x, y))).collect(); + s.write_region(canvas, &px); + let o = resize_surface_in_canvas(&s, wo as f64 / w as f64, ho as f64 / h as f64, filter, canvas); + let got = o.read_region(Rect::new(0, 0, wo, ho)); + assert_eq!(got.len(), want.len(), "{filter:?}"); + let worst = got.iter().zip(want).map(|(g, &p)| (g * 32768.0 - p as f32).abs()).fold(0.0f32, f32::max); + assert!(worst <= 8.0, "{filter:?} {w}x{h} to {wo}x{ho}: {worst} levels of 32768 from Photoshop"); + } +} + +/// Photoshop's Bicubic doubles with the Keys cubic at a = −0.75 (Catmull-Rom is −0.5): an +/// impulse spreads as −9, −27, 67, 225 /256 and back, as Photoshop 25.4 gives it. +#[test] +fn bicubic_is_photoshops_keys_cubic() { + let mut s = Surface::new(PixelFormat::new(ColorMode::Grayscale, SampleType::F32, false)); + let mut row = [0.25; 30]; + row[10] = 0.75; + s.write_region(Rect::new(0, 0, 30, 1), &row); + let o = resize_surface(&s, 2.0, 1.0, Resample::Bicubic); + let got: Vec = o.read_region(Rect::new(17, 0, 25, 1)).iter().map(|v| (v - 0.25) * 512.0).collect(); + for (g, want) in got.iter().zip([-9.0, -27.0, 67.0, 225.0, 225.0, 67.0, -27.0, -9.0]) { + assert!((g - want).abs() < 1e-3, "{got:?}"); + } +} + +#[test] +fn identity_scale_is_lossless() { + for f in [Resample::Nearest, Resample::Bilinear, Resample::Bicubic, Resample::Lanczos] { + let s = ramp(SampleType::U16); + let o = resize_surface(&s, 1.0, 1.0, f); + let r = Rect::new(0, 0, 64, 32); + let (a, b) = (s.read_region(r), o.read_region(r)); + let d = a.iter().zip(&b).map(|(x, y)| (x - y).abs()).fold(0.0f32, f32::max); + assert!(d < 1e-4, "{f:?} {d}"); + } +} + +#[test] +fn half_and_double_sizes() { + for f in [Resample::Nearest, Resample::Bilinear, Resample::Bicubic, Resample::Lanczos, Resample::PreserveDetails] { + let s = ramp(SampleType::F32); + let half = resize_surface(&s, 0.5, 0.5, f); + assert_eq!(half.content_bounds(), Rect::new(0, 0, 32, 16), "{f:?}"); + let p = half.pixel(16, 8); + assert!((p[1] - 0.5).abs() < 0.02 && (p[3] - 1.0).abs() < 1e-3, "{f:?} {p:?}"); + let dbl = resize_surface(&s, 2.0, 2.0, f); + assert_eq!(dbl.content_bounds(), Rect::new(0, 0, 128, 64), "{f:?}"); + // Mid-gray channel and the ramp's monotonicity are preserved. + let row: Vec = (8..120).map(|x| dbl.pixel(x, 30)[0]).collect(); + assert!(row.windows(2).all(|w| w[1] >= w[0] - 0.02), "{f:?}"); + } +} + +#[test] +fn downscale_averages_checkerboard() { + let mut s = Surface::new(PixelFormat::RGBA8); + for y in 0..64 { + for x in 0..64 { + let v = ((x + y) % 2) as f32; + s.write_pixel(x, y, &[v, v, v, 1.0]); + } + } + let o = resize_surface(&s, 0.25, 0.25, Resample::Bicubic); + let p = o.pixel(8, 8); + assert!((p[0] - 0.5).abs() < 0.05, "{p:?}"); +} + +/// A reduction by a tiny scale covers millions of source samples per output sample; only the +/// ones in the content get a weight, the rest fold onto its ends or into `outside`. +#[test] +fn tiny_scales_do_not_get_a_weight_per_covered_sample() { + for kernel in [Kernel::Bilinear, Kernel::Keys { a: -0.5, stretch: 1.0 }] { + for edge in [None, Some((0, 99))] { + let t = taps(0, 3, 1e-6, kernel, edge, (0, 99)); + for t in &t { + assert!(t.weights.len() <= 100, "{}", t.weights.len()); + let total = t.weights.iter().sum::() + t.outside; + assert!((total - 1.0).abs() < 1e-3, "{total}"); + } + } + } +} + +#[test] +fn transparent_edges_do_not_darken() { + let mut s = Surface::new(PixelFormat::RGBA32F); + s.fill_rect(Rect::new(10, 10, 20, 20), &[1.0, 0.0, 0.0, 1.0]); + let o = resize_surface(&s, 1.7, 1.7, Resample::Lanczos); + let edge = o.pixel(17, 25); + assert!(edge[3] > 0.0 && (edge[0] - 1.0).abs() < 0.05 && edge[1].abs() < 0.05, "{edge:?}"); +} + +/// Image Size of a layer that fills the canvas: its edges stay opaque and keep their colour, +/// up or down, at every depth; a layer away from the edges keeps its soft border. +#[test] +fn canvas_edges_repeat_instead_of_fading() { + let canvas = Rect::new(0, 0, 30, 20); + let colour = [0.2, 0.6, 1.0, 1.0]; + let filters = [Resample::Nearest, Resample::Bilinear, Resample::Bicubic, Resample::Lanczos, Resample::PreserveDetails]; + for sample in [SampleType::U8, SampleType::U16, SampleType::F32] { + let fmt = PixelFormat::new(ColorMode::Rgb, sample, true); + let mut s = Surface::new(fmt); + s.fill_rect(canvas, &colour); + for f in filters { + for k in [2.0, 1.37, 0.5] { + let o = resize_surface_in_canvas(&s, k, k, f, canvas); + let dst = scaled_rect(canvas, k, k); + assert_eq!(o.content_bounds(), dst, "{sample:?} {f:?} {k}"); + for (x, y) in [(0, 0), (dst.x1 - 1, 0), (0, dst.y1 - 1), (dst.x1 - 1, dst.y1 - 1), (dst.x1 / 2, 0), (0, dst.y1 / 2)] { + let p = o.pixel(x, y); + let off = p.iter().zip(colour).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); + assert!(off < 0.01, "{sample:?} {f:?} {k} ({x},{y}): {p:?}"); + } + } + } + // Inside the canvas the default pixel is still what lies around a layer. + let mut inner = Surface::new(fmt); + inner.fill_rect(Rect::new(10, 5, 20, 15), &[1.0, 0.0, 0.0, 1.0]); + let r = Rect::new(0, 0, 60, 40); + let a = resize_surface_in_canvas(&inner, 1.7, 1.7, Resample::Lanczos, canvas); + assert_eq!(a.read_region(r), resize_surface(&inner, 1.7, 1.7, Resample::Lanczos).read_region(r), "{sample:?}"); + } +} + +/// Two tiles in opposite corners of a 100000 px square: the content bounds are huge but +/// almost nothing is stored. Shrinking it to one pixel must neither allocate a window +/// proportional to the scale (#713) nor read the empty middle. +#[test] +fn tiny_target_of_a_huge_sparse_source() { + let mut s = Surface::new(PixelFormat::RGBA32F); + s.fill_rect(Rect::new(0, 0, 256, 256), &[1.0, 1.0, 1.0, 1.0]); + s.fill_rect(Rect::new(99_840, 99_840, 100_096, 100_096), &[1.0, 1.0, 1.0, 1.0]); + let k = 1.0 / 100_096.0; + let o = resize_surface(&s, k, k, Resample::Bicubic); + assert_eq!(o.content_bounds(), Rect::new(0, 0, 1, 1)); + let p = o.pixel(0, 0); + // Two 256² tiles out of 100096²: nearly transparent, and white where it isn't. + assert!(p[3] >= 0.0 && p[3] < 1e-3 && p.iter().all(|v| v.is_finite()), "{p:?}"); + // Squashed to one row but kept wide: the whole height feeds one band of output rows, + // which must not hold a full-height intermediate. + let o = resize_surface(&s, 1000.0 / 100_096.0, k, Resample::Bicubic); + let b = o.content_bounds(); + assert!(b.height() == 1 && (1000..=1001).contains(&b.width()), "{b:?}"); + assert!(o.pixel(0, 0)[3] > 0.0 && o.pixel(500, 0)[3] == 0.0, "{:?} {:?}", o.pixel(0, 0), o.pixel(500, 0)); +} + +/// Tile rows with nothing stored are not read; they count as rows of the default pixel, +/// exactly as reading them would (and within rounding for a non-zero default). +#[test] +fn skipped_empty_rows_match_reading_them() { + for (fmt, def, tol) in [(PixelFormat::RGBA32F, vec![0.0, 0.0, 0.0, 0.0], 0.0), (PixelFormat::GRAY8, vec![1.0], 1e-6)] { + let mut sparse = Surface::with_default(fmt, &def); + sparse.fill_rect(Rect::new(0, 0, 300, 40), &vec![0.5; def.len()]); + sparse.fill_rect(Rect::new(100, 1500, 400, 1540), &vec![0.25; def.len()]); + // The same pixels with the empty rows stored as tiles of the default pixel. + let mut dense = sparse.clone(); + dense.fill_rect(Rect::new(0, 40, 400, 1500), &def); + assert!(dense.tile_count() > sparse.tile_count()); + for f in [Resample::Bilinear, Resample::Bicubic, Resample::Lanczos] { + for (kx, ky) in [(0.013, 0.013), (0.37, 0.37), (1.0, 0.01)] { + let (a, b) = (resize_surface(&sparse, kx, ky, f), resize_surface(&dense, kx, ky, f)); + let r = a.content_bounds().union(&b.content_bounds()); + let d = a.read_region(r).iter().zip(b.read_region(r)).map(|(x, y)| (x - y).abs()).fold(0.0f32, f32::max); + assert!(d <= tol, "{fmt:?} {f:?} {kx} {ky}: {d}"); + } + } + } +} + +/// Reading the source in row chunks gives exactly what one read of the whole window gives. +#[test] +fn chunked_reads_match_a_single_read() { + let mut s = ramp(SampleType::F32); + s.fill_rect(Rect::new(600, 700, 640, 720), &[0.3, 0.9, 0.1, 0.5]); + let mut mask = Surface::with_default(PixelFormat::GRAY8, &[1.0]); + mask.fill_rect(Rect::new(0, 0, 40, 30), &[0.0]); + mask.fill_rect(Rect::new(500, 900, 530, 940), &[0.25]); + for src in [&s, &mask] { + for f in [Resample::Nearest, Resample::Bilinear, Resample::Bicubic, Resample::Lanczos] { + for k in [0.013, 0.37, 1.6] { + let whole = resize_with_budget(src, k, k, f, None, usize::MAX); + let chunked = resize_with_budget(src, k, k, f, None, 1); + let r = whole.content_bounds().union(&chunked.content_bounds()); + assert_eq!(whole.read_region(r), chunked.read_region(r), "{f:?} {k}"); + } + } + } +} + +#[test] +fn masks_keep_default_pixel() { + let fmt = PixelFormat::GRAY8; + let mut m = Surface::with_default(fmt, &[1.0]); + m.fill_rect(Rect::new(0, 0, 10, 10), &[0.0]); + let o = resize_surface(&m, 2.0, 2.0, Resample::Bilinear); + assert_eq!(o.default_pixel(), vec![1.0]); + assert!(o.pixel(5, 5)[0] < 0.01); +} + +#[test] +fn translate_and_crop() { + let s = ramp(SampleType::U8); + let t = translate_surface(&s, 5, -3); + assert_eq!(t.pixel(15, 7), s.pixel(10, 10)); + let c = crop_surface(&s, Rect::new(0, 0, 10, 10)); + assert_eq!(c.content_bounds(), Rect::new(0, 0, 10, 10)); +} + +/// #1114: nearest neighbor reduction must sample single source pixels, never average. +#[test] +fn nearest_neighbor_reduction_does_not_average() { + let mut s = Surface::new(PixelFormat::GRAY8); + for y in 0..8 { + for x in 0..8 { + if (x + y) % 2 == 0 { + s.fill_rect(Rect::new(x, y, x + 1, y + 1), &[1.0]); + } + } + } + let reduced = resize_surface(&s, 0.5, 0.5, Resample::Nearest); + for y in 0..4 { + for x in 0..4 { + let p = reduced.pixel(x, y)[0]; + assert!(p == 0.0 || p == 1.0, "nearest produced an averaged value {p} at ({x}, {y})"); + } + } +} diff --git a/crates/algo/src/seam.rs b/crates/algo/src/seam.rs index b85fba5bab..ebf7d5a705 100644 --- a/crates/algo/src/seam.rs +++ b/crates/algo/src/seam.rs @@ -748,576 +748,4 @@ pub fn skin_mask(w: usize, h: usize, ch: usize, img: &[f32]) -> Vec { } #[cfg(test)] -mod tests { - use super::*; - - /// The straightforward implementation the per-seam carver replaced (full energy map, fresh - /// seam search and a new buffer per seam), kept as the oracle for `carver_matches_reference`. - mod reference { - use super::super::{protection, resample_protection, transpose}; - - pub(super) fn energy(w: usize, h: usize, ch: usize, img: &[f32]) -> Vec { - let mut e = vec![0.0f32; w * h]; - for y in 0..h { - for x in 0..w { - let (xl, xr) = (x.saturating_sub(1), (x + 1).min(w - 1)); - let (yu, yd) = (y.saturating_sub(1), (y + 1).min(h - 1)); - let at = |xx: usize, yy: usize, c: usize| img[(yy * w + xx) * ch + c]; - let mut s = 0.0; - for c in 0..ch { - let v = at(x, y, c); - s += (at(xr, y, c) - v).abs() + (v - at(xl, y, c)).abs(); - s += (at(x, yd, c) - v).abs() + (v - at(x, yu, c)).abs(); - } - let v = s * 0.5; - e[y * w + x] = if v.is_nan() { f32::INFINITY } else { v }; - } - } - e - } - pub(super) fn find_seam(w: usize, h: usize, energy: &[f32]) -> Vec { - let mut cost = energy[..w].to_vec(); - let mut from = vec![0u8; w * h]; // 0 = up-left, 1 = up, 2 = up-right - let mut next = vec![0.0f32; w]; - for y in 1..h { - for x in 0..w { - let mut best = (cost[x], 1u8); - if x > 0 && cost[x - 1] < best.0 { - best = (cost[x - 1], 0); - } - if x + 1 < w && cost[x + 1] < best.0 { - best = (cost[x + 1], 2); - } - next[x] = best.0 + energy[y * w + x]; - from[y * w + x] = best.1; - } - std::mem::swap(&mut cost, &mut next); - } - let mut x = (0..w).min_by(|a, b| cost[*a].total_cmp(&cost[*b])).unwrap_or(0); - let mut seam = vec![0usize; h]; - for y in (0..h).rev() { - seam[y] = x; - if y > 0 { - x = match from[y * w + x] { - 0 => x - 1, - 2 => x + 1, - _ => x, - }; - } - } - seam - } - fn remove_seam(w: usize, h: usize, ch: usize, img: &[f32], seam: &[usize]) -> Vec { - let mut out = Vec::with_capacity((w - 1) * h * ch); - for (y, &sx) in seam.iter().enumerate().take(h) { - let row = &img[y * w * ch..(y + 1) * w * ch]; - out.extend_from_slice(&row[..sx * ch]); - out.extend_from_slice(&row[(sx + 1) * ch..]); - } - out - } - pub(super) fn carve_width(w: usize, h: usize, ch: usize, img: &[f32], protect: Option<&[f32]>, new_w: usize) -> Vec { - let new_w = new_w.max(1); - if new_w == w || w == 0 || h == 0 { - return img.to_vec(); - } - let protect_e = |e: &mut [f32], p: Option<&Vec>| { - if let Some(p) = p { - for (e, &p) in e.iter_mut().zip(p) { - *e += protection(p); - } - } - }; - if new_w < w { - let (mut cur, mut cw) = (img.to_vec(), w); - let mut prot = protect.map(<[f32]>::to_vec); - while cw > new_w { - let mut e = energy(cw, h, ch, &cur); - protect_e(&mut e, prot.as_ref()); - let seam = find_seam(cw, h, &e); - cur = remove_seam(cw, h, ch, &cur, &seam); - prot = prot.map(|p| remove_seam(cw, h, 1, &p, &seam)); - cw -= 1; - } - return cur; - } - // Enlarge in rounds of at most half the current width, each duplicating the k lowest seams. - let (mut cur, mut cw) = (img.to_vec(), w); - let mut prot = protect.map(<[f32]>::to_vec); - while cw < new_w { - let k = (new_w - cw).min((cw / 2).max(1)); - // Find k seams on a shrinking copy, mapping each back to original columns. - let mut idx: Vec> = (0..h).map(|_| (0..cw).collect()).collect(); - let (mut tmp, mut tw) = (cur.clone(), cw); - let mut tprot = prot.clone(); - let mut dup: Vec> = vec![Vec::with_capacity(k); h]; - for _ in 0..k { - // A 1 px wide image's only seam is its one column: take it, so it is duplicated. - if tw == 0 { - break; - } - let mut e = energy(tw, h, ch, &tmp); - protect_e(&mut e, tprot.as_ref()); - let seam = find_seam(tw, h, &e); - for (y, &sx) in seam.iter().enumerate() { - dup[y].push(idx[y].remove(sx)); - } - tmp = remove_seam(tw, h, ch, &tmp, &seam); - tprot = tprot.map(|p| remove_seam(tw, h, 1, &p, &seam)); - tw -= 1; - } - let added = dup[0].len(); - if added == 0 { - break; - } - let nw = cw + added; - let mut out = Vec::with_capacity(nw * h * ch); - let mut nprot = prot.as_ref().map(|_| Vec::with_capacity(nw * h)); - for (y, d) in dup.iter_mut().enumerate() { - d.sort_unstable(); - let row = &cur[y * cw * ch..(y + 1) * cw * ch]; - let mut di = 0; - for x in 0..cw { - out.extend_from_slice(&row[x * ch..(x + 1) * ch]); - if let (Some(np), Some(p)) = (nprot.as_mut(), prot.as_ref()) { - np.push(p[y * cw + x]); - } - while di < d.len() && d[di] == x { - let xr = (x + 1).min(cw - 1); - for c in 0..ch { - out.push((row[x * ch + c] + row[xr * ch + c]) * 0.5); - } - if let (Some(np), Some(p)) = (nprot.as_mut(), prot.as_ref()) { - np.push(p[y * cw + x]); - } - di += 1; - } - } - } - cur = out; - prot = nprot; - cw = nw; - } - cur - } - - pub(super) fn carve(w: usize, h: usize, ch: usize, img: &[f32], protect: Option<&[f32]>, new_w: usize, new_h: usize) -> Vec { - let (new_w, new_h) = (new_w.max(1), new_h.max(1)); - let wide = carve_width(w, h, ch, img, protect, new_w); - if new_h == h { - return wide; - } - let prot_t = protect.map(|p| transpose(new_w, h, 1, &resample_protection(w, h, p, new_w))); - let t = transpose(new_w, h, ch, &wide); - let tall = carve_width(h, new_w, ch, &t, prot_t.as_deref(), new_h); - transpose(new_h, new_w, ch, &tall) - } - } - - /// The carver gives bit-identical output to the reference implementation it replaced, over - /// random shapes (including 1 px wide and tall), channel counts, tie-heavy quantised noise, - /// protection, shrinking, enlarging past half the width and both axes at once. - #[test] - fn carver_matches_reference() { - let mut seed = 1u32; - let mut next = |n: usize| { - seed ^= seed << 13; - seed ^= seed >> 17; - seed ^= seed << 5; - seed as usize % n - }; - for case in 0..400u32 { - let (w, h, ch) = (1 + next(24), 1 + next(18), [1, 3, 4][next(3)]); - let levels = [2, 5, 255, 65_536][next(4)]; - let img = noise(w * h * ch, levels, 11 + case); - let protect = (next(3) == 0).then(|| noise(w * h, 3, 101 + case)); - let (nw, nh) = (1 + next(2 * w + 2), 1 + next(2 * h + 2)); - let got = carve(w, h, ch, &img, protect.as_deref(), nw, nh); - let want = reference::carve(w, h, ch, &img, protect.as_deref(), nw, nh); - let bits = |v: &[f32]| v.iter().map(|f| f.to_bits()).collect::>(); - assert_eq!(bits(&got), bits(&want), "case {case}: {w}x{h}x{ch} -> {nw}x{nh}, levels {levels}, protect {}", protect.is_some()); - } - // The seam search alone, on raw energy maps full of ties. - for case in 0..200u32 { - let (w, h) = (1 + next(40), 1 + next(30)); - let e = noise(w * h, [2, 3, 1000][next(3)], 7 + case); - assert_eq!(find_seam(w, h, &e), reference::find_seam(w, h, &e), "seam case {case}: {w}x{h}"); - let img = noise(w * h * 3, 7, 3 + case); - let bits = |v: Vec| v.into_iter().map(f32::to_bits).collect::>(); - assert_eq!(bits(energy(w, h, 3, &img)), bits(reference::energy(w, h, 3, &img)), "energy case {case}"); - } - } - - /// After every removal, the carver's incrementally updated seam search matches a full pass - /// over its current energy bit for bit (path costs and the seam traced from them), on images - /// where seams run through the edges, through flat areas full of ties and through protection. - /// Its energy matches a fresh map of the pixels left, and so do the pixels. - #[test] - fn incremental_dp_matches_full_dp() { - let mut ramp = vec![0.0f32; 120 * 90]; - for (i, v) in ramp.iter_mut().enumerate() { - let (x, y) = ((i % 120) as f32, (i / 120) as f32); - *v = ((x * 0.07).sin() * (y * 0.05).cos() * 0.5 + 0.5).clamp(0.0, 1.0); - } - // NaN and infinite samples and NaN protection: infinite energies, never NaN costs. - let mut odd = noise(40 * 30 * 3, 255, 11); - odd.iter_mut().step_by(13).for_each(|v| *v = f32::NAN); - odd.iter_mut().skip(5).step_by(17).for_each(|v| *v = f32::INFINITY); - let mut odd_prot = noise(40 * 30, 3, 12); - odd_prot.iter_mut().step_by(7).for_each(|v| *v = -f32::NAN); - // (w, h, channels, image, protection, seams to remove) - type Case = (usize, usize, usize, Vec, Option>, usize); - let cases: Vec = vec![ - (120, 90, 1, ramp, None, 40), - (97, 64, 3, noise(97 * 64 * 3, 2, 5), None, 90), - (80, 70, 4, noise(80 * 70 * 4, 1000, 6), Some(noise(80 * 70, 3, 7)), 60), - (64, 50, 3, bar(64, 50), None, 63), - (33, 1, 1, noise(33, 5, 8), None, 32), - (2, 40, 3, noise(2 * 40 * 3, 9, 9), None, 2), - (50, 40, 1, vec![0.5; 50 * 40], Some(noise(50 * 40, 2, 10)), 49), - (40, 30, 3, odd, Some(odd_prot), 25), - ]; - let bits = |v: &[f32]| v.iter().map(|f| f.to_bits()).collect::>(); - for (case, (w, h, ch, img, prot, seams)) in cases.into_iter().enumerate() { - let mut c = Carver::new(w, h, ch, &img, prot.as_deref()); - for step in 0..=seams { - let rows = Rows { stride: c.w, cw: c.cw, off: &c.off }; - let mut fresh = Dp::default(); - fresh.full(rows, &c.e); - for y in 0..h { - assert_eq!(bits(&c.dp.cost[rows.of(y)]), bits(&fresh.cost[rows.of(y)]), "case {case} step {step} row {y}: costs"); - } - assert_eq!(c.dp.seam(rows), fresh.seam(rows), "case {case} step {step}: seam"); - // The pixels left, packed, and their energy (plus protection) from scratch. - let left: Vec = (0..h) - .flat_map(|y| c.idx[rows.of(y)].iter().flat_map(move |&x| (0..ch).map(move |k| (y * w + x as usize) * ch + k))) - .map(|i| img[i]) - .collect(); - let mut want = energy(c.cw, h, ch, &left); - if let Some(p) = &prot { - let kept = (0..h).flat_map(|y| c.idx[rows.of(y)].iter().map(move |&x| y * w + x as usize)); - for (e, i) in want.iter_mut().zip(kept) { - *e += protection(p[i]); - } - } - let have: Vec = (0..h).flat_map(|y| c.e[rows.of(y)].to_vec()).collect(); - assert_eq!(bits(&have), bits(&want), "case {case} step {step}: energy"); - if step == seams { - assert_eq!(bits(&c.into_pixels()), bits(&left), "case {case}: pixels"); - break; - } - c.remove_seam(); - } - } - } - - /// Hostile but well-formed shapes return early instead of panicking: no channels, empty - /// sizes (also through the height pass), and images or protection maps shorter than their - /// size says (a short map protects nothing). - #[test] - fn degenerate_inputs_do_not_panic() { - assert!(carve(3, 3, 0, &[], None, 2, 2).is_empty()); - assert!(carve(3, 3, 0, &[], None, 5, 5).is_empty()); - assert!(transpose(3, 3, 0, &[]).is_empty()); - assert!(resize_bilinear(3, 3, 0, &[], 2, 2).is_empty()); - assert!(resize_bilinear(3, 3, 1, &[0.5; 9], 0, 2).is_empty()); - assert!(resize_bilinear(3, 3, 1, &[0.5; 9], 2, 0).is_empty()); - assert_eq!(resize_bilinear(3, 3, 1, &[0.5; 4], 2, 2), vec![0.0; 4]); - assert!(carve(0, 5, 3, &[], None, 3, 7).is_empty()); - assert!(carve(0, 5, 3, &[], None, 3, 2).is_empty()); - let img = noise(10 * 5, 7, 3); - assert_eq!(carve(10, 5, 1, &img, Some(&[0.0; 3]), 4, 5), carve(10, 5, 1, &img, None, 4, 5)); - assert_eq!(carve(10, 5, 1, &img, Some(&[0.0; 3]), 4, 3), carve(10, 5, 1, &img, None, 4, 3)); - assert_eq!(carve(10, 5, 3, &[0.5; 20], None, 4, 5), vec![0.5; 20]); - assert_eq!(carve_width(usize::MAX, 2, 4, &[0.5; 8], None, 1), vec![0.5; 8]); - // Values past the size are ignored, through both passes. - let long = noise(20, 7, 4); - assert_eq!(carve(5, 3, 1, &long, None, 3, 3), carve(5, 3, 1, &long[..15], None, 3, 3)); - assert_eq!(carve(5, 3, 1, &long, None, 5, 2), carve(5, 3, 1, &long[..15], None, 5, 2)); - } - - /// Infinite samples, and finite ones whose differences overflow, give energies that aren't - /// numbers; those are the highest energy (pinned deliberately: the code before NaN-free costs - /// fed NaN to the seam search and chose differently). - #[test] - fn infinite_samples_carve_deterministically() { - let inf = f32::INFINITY; - assert_eq!(carve(2, 1, 1, &[inf, 0.5], None, 1, 1), [0.5]); - assert_eq!(carve(2, 1, 1, &[f32::MAX, f32::MAX], None, 6, 1), [f32::MAX, inf, inf, inf, inf, f32::MAX]); - let mut img = noise(30 * 20 * 3, 255, 41); - img.iter_mut().step_by(11).for_each(|v| *v = inf); - img.iter_mut().skip(4).step_by(23).for_each(|v| *v = -inf); - let out = carve(30, 20, 3, &img, None, 21, 14); - assert_eq!(out.len(), 21 * 14 * 3); - assert_eq!(out, carve(30, 20, 3, &img, None, 21, 14)); - } - - /// Infinite protection protects like full protection in the height pass too, where the map - /// is resampled (and an infinity alone would resample to NaN). - #[test] - fn infinite_protection_protects_in_both_passes() { - let (w, h) = (6, 6); - let img: Vec = (0..w * h).map(|i| (i * 7 % 5) as f32 / 4.0).collect(); - let row = |v: f32| (0..w * h).map(|i| if i / w == 2 { v } else { 0.0 }).collect::>(); - let (full, inf) = (row(1.0), row(f32::INFINITY)); - for (nw, nh) in [(6, 3), (4, 3), (3, 6)] { - assert_eq!(carve(w, h, 1, &img, Some(&inf), nw, nh), carve(w, h, 1, &img, Some(&full), nw, nh), "{nw}x{nh}"); - } - let kept = carve(w, h, 1, &img, Some(&inf), 6, 3); - assert!(kept.chunks(6).any(|r| r == &img[12..18]), "the protected row survives"); - } - - /// A cancel that arrives after the seam search, during the tall-image rebuild, still stops - /// the carve. - #[test] - fn proxy_rebuild_observes_cancellation() { - use std::sync::atomic::{AtomicUsize, Ordering}; - let (w, h, ch, new_w) = (128, PROXY_SHRINK_MIN_HEIGHT, 3, 64); - let img = noise(w * h * ch, 7, 5); - let calls = AtomicUsize::new(0); - // One check per seam passes; the first one after the search cancels. - let cancel = || calls.fetch_add(1, Ordering::Relaxed) >= w - new_w; - assert_eq!(carve_width_with(w, h, ch, &img, None, new_w, &Interrupt::cancel_only(&cancel)), Err(Cancelled)); - assert!(calls.load(Ordering::Relaxed) > w - new_w, "the rebuild checked for cancellation"); - } - - /// NaN samples and NaN protection steer seams the same whatever their sign and payload - /// (which arithmetic does not preserve consistently across builds): the same pixels are kept. - #[test] - fn nan_payloads_do_not_steer_seams() { - let (w, h, ch) = (24, 18, 3); - let (base, prot_base) = (noise(w * h * ch, 255, 21), noise(w * h, 3, 22)); - let carve_with_nans = |pixel: f32, prot: f32| { - let (mut img, mut p) = (base.clone(), prot_base.clone()); - img.iter_mut().step_by(37).for_each(|v| *v = pixel); - p.iter_mut().step_by(29).for_each(|v| *v = prot); - carve(w, h, ch, &img, Some(&p), 15, 11) - }; - let canonical = |v: Vec| v.into_iter().map(|f| if f.is_nan() { u32::MAX } else { f.to_bits() }).collect::>(); - let nans = [f32::NAN, -f32::NAN, f32::from_bits(0x7fc0_1234), f32::from_bits(0xffc0_0001)]; - let want = canonical(carve_with_nans(nans[0], nans[0])); - for &a in &nans { - for &b in &nans { - assert_eq!(canonical(carve_with_nans(a, b)), want, "pixel NaN {:#x}, protection NaN {:#x}", a.to_bits(), b.to_bits()); - } - } - } - - #[test] - fn cancelled_carve_stops() { - let (w, h) = (40, 20); - let img = vec![0.5f32; w * h * 3]; - let yes = || true; - assert_eq!(carve_with(w, h, 3, &img, None, 30, 15, &Interrupt::cancel_only(&yes)), Err(Cancelled)); - assert_eq!(carve_with(w, h, 3, &img, None, 30, 15, &Interrupt::NONE).unwrap(), carve(w, h, 3, &img, None, 30, 15)); - } - - /// A flat grey image with a salient vertical bar at x = 10..14 (red/blue columns). - fn bar(w: usize, h: usize) -> Vec { - let mut v = vec![0.5f32; w * h * 3]; - for y in 0..h { - for x in 10..14 { - let c = if x % 2 == 0 { [1.0, 0.0, 0.0] } else { [0.0, 0.0, 1.0] }; - v[(y * w + x) * 3..(y * w + x) * 3 + 3].copy_from_slice(&c); - } - } - v - } - - /// Columns that are pure red or pure blue top to bottom. - fn red_columns(w: usize, h: usize, img: &[f32]) -> usize { - let pure = |p: &[f32]| p[1] < 0.05 && ((p[0] > 0.95 && p[2] < 0.05) || (p[2] > 0.95 && p[0] < 0.05)); - (0..w).filter(|x| (0..h).all(|y| pure(&img[(y * w + x) * 3..(y * w + x) * 3 + 3]))).count() - } - - #[test] - fn seam_follows_low_energy() { - let (w, h) = (5, 4); - let mut e = vec![9.0f32; w * h]; - for y in 0..h { - e[y * w + 2] = 0.0; - } - assert_eq!(find_seam(w, h, &e), vec![2; 4]); - } - - #[test] - fn shrinking_keeps_the_salient_bar() { - let (w, h) = (40, 12); - let img = bar(w, h); - let out = carve(w, h, 3, &img, None, 24, h); - assert_eq!(out.len(), 24 * h * 3); - assert_eq!(red_columns(24, h, &out), 4, "the bar survives intact"); - // Plain resampling squashes it instead. - let plain = resize_bilinear(w, h, 3, &img, 24, h); - assert!(red_columns(24, h, &plain) < 4); - } - - #[test] - fn tall_proxy_shrink_preserves_full_resolution_salient_and_protected_pixels() { - let (w, h, ch, new_w) = (512, PROXY_SHRINK_MIN_HEIGHT, 3, 384); - let mut img = bar(w, h); - let mut protect = vec![0.0; w * h]; - for y in 0..h { - let i = (y * w + 256) * ch; - img[i..i + ch].copy_from_slice(&[0.03, 0.87, 0.42]); - protect[y * w + 256] = 1.0; - } - - let out = carve_width_with(w, h, ch, &img, Some(&protect), new_w, &Interrupt::NONE).unwrap(); - - assert_eq!(out.len(), new_w * h * ch); - assert_eq!(red_columns(new_w, h, &out), 4, "the full-resolution bar survives"); - for y in 0..h { - let row = &out[y * new_w * ch..(y + 1) * new_w * ch]; - assert!(row.chunks_exact(ch).any(|px| px == [0.03, 0.87, 0.42]), "protected mark survives row {y}"); - } - } - - #[test] - fn tall_proxy_shrink_observes_cancellation_before_modifying_source() { - let (w, h, ch) = (128, PROXY_SHRINK_MIN_HEIGHT, 3); - let img = vec![0.5; w * h * ch]; - let cancelled = || true; - assert_eq!(carve_width_with(w, h, ch, &img, None, 64, &Interrupt::cancel_only(&cancelled)), Err(Cancelled)); - } - - #[test] - fn enlarging_duplicates_flat_areas() { - let (w, h) = (30, 8); - let img = bar(w, h); - let out = carve(w, h, 3, &img, None, 50, h); - assert_eq!(out.len(), 50 * h * 3); - assert_eq!(red_columns(50, h, &out), 4); - } - - #[test] - fn height_and_protection() { - let (w, h) = (20, 30); - // Horizontal bar: carve height. - let mut img = vec![0.2f32; w * h]; - for x in 0..w { - img[12 * w + x] = 1.0; - } - let out = carve(w, h, 1, &img, None, w, 18); - assert_eq!(out.len(), w * 18); - assert_eq!((0..18).filter(|y| (0..w).all(|x| out[y * w + x] > 0.9)).count(), 1); - // Protecting a flat region keeps it: the seams go elsewhere. - let flat = vec![0.5f32; 16 * 4]; - let mut protect = vec![0.0f32; 16 * 4]; - for y in 0..4 { - protect[y * 16 + 3] = 1.0; - } - let mut marked = flat.clone(); - for y in 0..4 { - marked[y * 16 + 3] = 0.51; - } - let out = carve(16, 4, 1, &marked, Some(&protect), 8, 4); - assert!((0..4).all(|y| out[y * 8..y * 8 + 8].iter().any(|v| (*v - 0.51).abs() < 1e-6))); - } - - /// Noise quantised to `levels` values, so the energy map is full of exact ties. - fn noise(len: usize, levels: u32, seed: u32) -> Vec { - let mut s = seed | 1; - (0..len) - .map(|_| { - s ^= s << 13; - s ^= s >> 17; - s ^= s << 5; - (s % levels) as f32 / (levels - 1) as f32 - }) - .collect() - } - - fn fnv(v: &[f32]) -> u64 { - v.iter().flat_map(|f| f.to_bits().to_le_bytes()).fold(0xcbf2_9ce4_8422_2325, |h, b| (h ^ u64::from(b)).wrapping_mul(0x100_0000_01b3)) - } - - /// The exact output bits of a spread of carves (shrink, enlarge past half the width, both - /// axes, protection, 1/3/4 channels, tie-heavy and smooth images), pinned so that speed work - /// can't change which seams are chosen or how pixels are blended. - #[test] - fn output_bits_are_pinned() { - let cases: [(usize, usize, usize, u32, bool, usize, usize); 8] = [ - (61, 47, 3, 2, false, 40, 47), - (61, 47, 3, 255, false, 61, 30), - (61, 47, 4, 4, true, 35, 29), - (33, 20, 1, 3, false, 80, 20), - (33, 20, 3, 1000, true, 50, 45), - (48, 36, 4, 7, false, 70, 18), - (5, 3, 1, 2, false, 1, 1), - (40, 40, 3, 2, true, 39, 41), - ]; - let got: Vec = cases - .iter() - .enumerate() - .map(|(i, &(w, h, ch, levels, prot, nw, nh))| { - let img = noise(w * h * ch, levels, 7 + i as u32); - let protect = prot.then(|| noise(w * h, 3, 99 + i as u32)); - let out = carve(w, h, ch, &img, protect.as_deref(), nw, nh); - assert_eq!(out.len(), nw * nh * ch); - fnv(&out) - }) - .collect(); - assert_eq!(got, PINNED); - } - - const PINNED: [u64; 8] = [ - 0x24ea_9353_02c2_7c58, - 0x5a6e_8554_a0cb_ebb1, - 0x8b18_d63f_396e_21c9, - 0x1db2_23ad_3e6a_a7c5, - 0x721d_6cc5_34e0_3fdf, - 0x961a_ea6d_e512_ec7d, - 0x4d25_767f_9dce_13f5, - 0x2157_9f86_27d6_b835, - ]; - - /// [`output_bits_are_pinned`] for the reduced-height seam search of tall images (rows at - /// least [`PROXY_SHRINK_MIN_HEIGHT`], at least [`PROXY_SHRINK_MIN_SEAMS`] seams): widths and, - /// through the transposed pass, heights, with and without protection, on tie-heavy and - /// fine-grained noise. - #[test] - fn tall_proxy_output_bits_are_pinned() { - let cases: [(usize, usize, usize, u32, bool, usize, usize); 5] = [ - (96, PROXY_SHRINK_MIN_HEIGHT, 3, 2, false, 30, PROXY_SHRINK_MIN_HEIGHT), - (130, 2_100, 4, 255, true, 64, 2_100), - (80, 2_600, 1, 65_536, false, 16, 2_600), - (PROXY_SHRINK_MIN_HEIGHT, 90, 3, 5, false, PROXY_SHRINK_MIN_HEIGHT, 20), - (2_050, 100, 4, 1000, true, 2_050, 36), - ]; - let got: Vec = cases - .iter() - .enumerate() - .map(|(i, &(w, h, ch, levels, prot, nw, nh))| { - let img = noise(w * h * ch, levels, 31 + i as u32); - let protect = prot.then(|| noise(w * h, 3, 131 + i as u32)); - let out = carve(w, h, ch, &img, protect.as_deref(), nw, nh); - assert_eq!(out.len(), nw * nh * ch); - fnv(&out) - }) - .collect(); - assert_eq!(got, TALL_PINNED); - } - - const TALL_PINNED: [u64; 5] = [0x5657_83ac_cb26_56a5, 0x81a6_b5f7_e299_fdfb, 0xcdf2_9df9_9b83_def5, 0xa713_544a_4dcc_d8d8, 0x3557_de9f_ffb0_881e]; - - #[test] - fn one_pixel_lines_enlarge_by_repeating() { - // Width 1 has no seam to spare: its one column is repeated. Height 1 likewise (through - // the transposed pass), alone or with the other axis. - let col = [0.1f32, 0.2, 0.3, 0.4, 0.5]; - assert_eq!(carve(1, 5, 1, &col, None, 4, 5), col.iter().flat_map(|v| [*v; 4]).collect::>()); - assert_eq!(carve(5, 1, 1, &col, None, 5, 3), col.repeat(3)); - assert_eq!(carve(1, 1, 3, &[0.7, 0.8, 0.9], None, 3, 2), [0.7, 0.8, 0.9].repeat(6)); - for (w, h, nw, nh) in [(1, 5, 6, 10), (1, 17, 6, 34), (16, 1, 21, 2), (7, 1, 3, 8), (2, 1, 1, 8)] { - let img = vec![0.5f32; w * h * 4]; - assert_eq!(carve(w, h, 4, &img, Some(&vec![1.0; w * h]), nw, nh).len(), nw * nh * 4, "{w}x{h} -> {nw}x{nh}"); - } - } - - #[test] - fn skin_rule() { - let px = [0.86f32, 0.62, 0.5, 0.2, 0.4, 0.8]; - assert_eq!(skin_mask(2, 1, 3, &px), vec![1.0, 0.0]); - } -} +mod tests; diff --git a/crates/algo/src/seam/tests.rs b/crates/algo/src/seam/tests.rs new file mode 100644 index 0000000000..5788b03ce2 --- /dev/null +++ b/crates/algo/src/seam/tests.rs @@ -0,0 +1,569 @@ +use super::*; + +/// The straightforward implementation the per-seam carver replaced (full energy map, fresh +/// seam search and a new buffer per seam), kept as the oracle for `carver_matches_reference`. +mod reference { + use super::super::{protection, resample_protection, transpose}; + + pub(super) fn energy(w: usize, h: usize, ch: usize, img: &[f32]) -> Vec { + let mut e = vec![0.0f32; w * h]; + for y in 0..h { + for x in 0..w { + let (xl, xr) = (x.saturating_sub(1), (x + 1).min(w - 1)); + let (yu, yd) = (y.saturating_sub(1), (y + 1).min(h - 1)); + let at = |xx: usize, yy: usize, c: usize| img[(yy * w + xx) * ch + c]; + let mut s = 0.0; + for c in 0..ch { + let v = at(x, y, c); + s += (at(xr, y, c) - v).abs() + (v - at(xl, y, c)).abs(); + s += (at(x, yd, c) - v).abs() + (v - at(x, yu, c)).abs(); + } + let v = s * 0.5; + e[y * w + x] = if v.is_nan() { f32::INFINITY } else { v }; + } + } + e + } + pub(super) fn find_seam(w: usize, h: usize, energy: &[f32]) -> Vec { + let mut cost = energy[..w].to_vec(); + let mut from = vec![0u8; w * h]; // 0 = up-left, 1 = up, 2 = up-right + let mut next = vec![0.0f32; w]; + for y in 1..h { + for x in 0..w { + let mut best = (cost[x], 1u8); + if x > 0 && cost[x - 1] < best.0 { + best = (cost[x - 1], 0); + } + if x + 1 < w && cost[x + 1] < best.0 { + best = (cost[x + 1], 2); + } + next[x] = best.0 + energy[y * w + x]; + from[y * w + x] = best.1; + } + std::mem::swap(&mut cost, &mut next); + } + let mut x = (0..w).min_by(|a, b| cost[*a].total_cmp(&cost[*b])).unwrap_or(0); + let mut seam = vec![0usize; h]; + for y in (0..h).rev() { + seam[y] = x; + if y > 0 { + x = match from[y * w + x] { + 0 => x - 1, + 2 => x + 1, + _ => x, + }; + } + } + seam + } + fn remove_seam(w: usize, h: usize, ch: usize, img: &[f32], seam: &[usize]) -> Vec { + let mut out = Vec::with_capacity((w - 1) * h * ch); + for (y, &sx) in seam.iter().enumerate().take(h) { + let row = &img[y * w * ch..(y + 1) * w * ch]; + out.extend_from_slice(&row[..sx * ch]); + out.extend_from_slice(&row[(sx + 1) * ch..]); + } + out + } + pub(super) fn carve_width(w: usize, h: usize, ch: usize, img: &[f32], protect: Option<&[f32]>, new_w: usize) -> Vec { + let new_w = new_w.max(1); + if new_w == w || w == 0 || h == 0 { + return img.to_vec(); + } + let protect_e = |e: &mut [f32], p: Option<&Vec>| { + if let Some(p) = p { + for (e, &p) in e.iter_mut().zip(p) { + *e += protection(p); + } + } + }; + if new_w < w { + let (mut cur, mut cw) = (img.to_vec(), w); + let mut prot = protect.map(<[f32]>::to_vec); + while cw > new_w { + let mut e = energy(cw, h, ch, &cur); + protect_e(&mut e, prot.as_ref()); + let seam = find_seam(cw, h, &e); + cur = remove_seam(cw, h, ch, &cur, &seam); + prot = prot.map(|p| remove_seam(cw, h, 1, &p, &seam)); + cw -= 1; + } + return cur; + } + // Enlarge in rounds of at most half the current width, each duplicating the k lowest seams. + let (mut cur, mut cw) = (img.to_vec(), w); + let mut prot = protect.map(<[f32]>::to_vec); + while cw < new_w { + let k = (new_w - cw).min((cw / 2).max(1)); + // Find k seams on a shrinking copy, mapping each back to original columns. + let mut idx: Vec> = (0..h).map(|_| (0..cw).collect()).collect(); + let (mut tmp, mut tw) = (cur.clone(), cw); + let mut tprot = prot.clone(); + let mut dup: Vec> = vec![Vec::with_capacity(k); h]; + for _ in 0..k { + // A 1 px wide image's only seam is its one column: take it, so it is duplicated. + if tw == 0 { + break; + } + let mut e = energy(tw, h, ch, &tmp); + protect_e(&mut e, tprot.as_ref()); + let seam = find_seam(tw, h, &e); + for (y, &sx) in seam.iter().enumerate() { + dup[y].push(idx[y].remove(sx)); + } + tmp = remove_seam(tw, h, ch, &tmp, &seam); + tprot = tprot.map(|p| remove_seam(tw, h, 1, &p, &seam)); + tw -= 1; + } + let added = dup[0].len(); + if added == 0 { + break; + } + let nw = cw + added; + let mut out = Vec::with_capacity(nw * h * ch); + let mut nprot = prot.as_ref().map(|_| Vec::with_capacity(nw * h)); + for (y, d) in dup.iter_mut().enumerate() { + d.sort_unstable(); + let row = &cur[y * cw * ch..(y + 1) * cw * ch]; + let mut di = 0; + for x in 0..cw { + out.extend_from_slice(&row[x * ch..(x + 1) * ch]); + if let (Some(np), Some(p)) = (nprot.as_mut(), prot.as_ref()) { + np.push(p[y * cw + x]); + } + while di < d.len() && d[di] == x { + let xr = (x + 1).min(cw - 1); + for c in 0..ch { + out.push((row[x * ch + c] + row[xr * ch + c]) * 0.5); + } + if let (Some(np), Some(p)) = (nprot.as_mut(), prot.as_ref()) { + np.push(p[y * cw + x]); + } + di += 1; + } + } + } + cur = out; + prot = nprot; + cw = nw; + } + cur + } + + pub(super) fn carve(w: usize, h: usize, ch: usize, img: &[f32], protect: Option<&[f32]>, new_w: usize, new_h: usize) -> Vec { + let (new_w, new_h) = (new_w.max(1), new_h.max(1)); + let wide = carve_width(w, h, ch, img, protect, new_w); + if new_h == h { + return wide; + } + let prot_t = protect.map(|p| transpose(new_w, h, 1, &resample_protection(w, h, p, new_w))); + let t = transpose(new_w, h, ch, &wide); + let tall = carve_width(h, new_w, ch, &t, prot_t.as_deref(), new_h); + transpose(new_h, new_w, ch, &tall) + } +} + +/// The carver gives bit-identical output to the reference implementation it replaced, over +/// random shapes (including 1 px wide and tall), channel counts, tie-heavy quantised noise, +/// protection, shrinking, enlarging past half the width and both axes at once. +#[test] +fn carver_matches_reference() { + let mut seed = 1u32; + let mut next = |n: usize| { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + seed as usize % n + }; + for case in 0..400u32 { + let (w, h, ch) = (1 + next(24), 1 + next(18), [1, 3, 4][next(3)]); + let levels = [2, 5, 255, 65_536][next(4)]; + let img = noise(w * h * ch, levels, 11 + case); + let protect = (next(3) == 0).then(|| noise(w * h, 3, 101 + case)); + let (nw, nh) = (1 + next(2 * w + 2), 1 + next(2 * h + 2)); + let got = carve(w, h, ch, &img, protect.as_deref(), nw, nh); + let want = reference::carve(w, h, ch, &img, protect.as_deref(), nw, nh); + let bits = |v: &[f32]| v.iter().map(|f| f.to_bits()).collect::>(); + assert_eq!(bits(&got), bits(&want), "case {case}: {w}x{h}x{ch} -> {nw}x{nh}, levels {levels}, protect {}", protect.is_some()); + } + // The seam search alone, on raw energy maps full of ties. + for case in 0..200u32 { + let (w, h) = (1 + next(40), 1 + next(30)); + let e = noise(w * h, [2, 3, 1000][next(3)], 7 + case); + assert_eq!(find_seam(w, h, &e), reference::find_seam(w, h, &e), "seam case {case}: {w}x{h}"); + let img = noise(w * h * 3, 7, 3 + case); + let bits = |v: Vec| v.into_iter().map(f32::to_bits).collect::>(); + assert_eq!(bits(energy(w, h, 3, &img)), bits(reference::energy(w, h, 3, &img)), "energy case {case}"); + } +} + +/// After every removal, the carver's incrementally updated seam search matches a full pass +/// over its current energy bit for bit (path costs and the seam traced from them), on images +/// where seams run through the edges, through flat areas full of ties and through protection. +/// Its energy matches a fresh map of the pixels left, and so do the pixels. +#[test] +fn incremental_dp_matches_full_dp() { + let mut ramp = vec![0.0f32; 120 * 90]; + for (i, v) in ramp.iter_mut().enumerate() { + let (x, y) = ((i % 120) as f32, (i / 120) as f32); + *v = ((x * 0.07).sin() * (y * 0.05).cos() * 0.5 + 0.5).clamp(0.0, 1.0); + } + // NaN and infinite samples and NaN protection: infinite energies, never NaN costs. + let mut odd = noise(40 * 30 * 3, 255, 11); + odd.iter_mut().step_by(13).for_each(|v| *v = f32::NAN); + odd.iter_mut().skip(5).step_by(17).for_each(|v| *v = f32::INFINITY); + let mut odd_prot = noise(40 * 30, 3, 12); + odd_prot.iter_mut().step_by(7).for_each(|v| *v = -f32::NAN); + // (w, h, channels, image, protection, seams to remove) + type Case = (usize, usize, usize, Vec, Option>, usize); + let cases: Vec = vec![ + (120, 90, 1, ramp, None, 40), + (97, 64, 3, noise(97 * 64 * 3, 2, 5), None, 90), + (80, 70, 4, noise(80 * 70 * 4, 1000, 6), Some(noise(80 * 70, 3, 7)), 60), + (64, 50, 3, bar(64, 50), None, 63), + (33, 1, 1, noise(33, 5, 8), None, 32), + (2, 40, 3, noise(2 * 40 * 3, 9, 9), None, 2), + (50, 40, 1, vec![0.5; 50 * 40], Some(noise(50 * 40, 2, 10)), 49), + (40, 30, 3, odd, Some(odd_prot), 25), + ]; + let bits = |v: &[f32]| v.iter().map(|f| f.to_bits()).collect::>(); + for (case, (w, h, ch, img, prot, seams)) in cases.into_iter().enumerate() { + let mut c = Carver::new(w, h, ch, &img, prot.as_deref()); + for step in 0..=seams { + let rows = Rows { stride: c.w, cw: c.cw, off: &c.off }; + let mut fresh = Dp::default(); + fresh.full(rows, &c.e); + for y in 0..h { + assert_eq!(bits(&c.dp.cost[rows.of(y)]), bits(&fresh.cost[rows.of(y)]), "case {case} step {step} row {y}: costs"); + } + assert_eq!(c.dp.seam(rows), fresh.seam(rows), "case {case} step {step}: seam"); + // The pixels left, packed, and their energy (plus protection) from scratch. + let left: Vec = + (0..h).flat_map(|y| c.idx[rows.of(y)].iter().flat_map(move |&x| (0..ch).map(move |k| (y * w + x as usize) * ch + k))).map(|i| img[i]).collect(); + let mut want = energy(c.cw, h, ch, &left); + if let Some(p) = &prot { + let kept = (0..h).flat_map(|y| c.idx[rows.of(y)].iter().map(move |&x| y * w + x as usize)); + for (e, i) in want.iter_mut().zip(kept) { + *e += protection(p[i]); + } + } + let have: Vec = (0..h).flat_map(|y| c.e[rows.of(y)].to_vec()).collect(); + assert_eq!(bits(&have), bits(&want), "case {case} step {step}: energy"); + if step == seams { + assert_eq!(bits(&c.into_pixels()), bits(&left), "case {case}: pixels"); + break; + } + c.remove_seam(); + } + } +} + +/// Hostile but well-formed shapes return early instead of panicking: no channels, empty +/// sizes (also through the height pass), and images or protection maps shorter than their +/// size says (a short map protects nothing). +#[test] +fn degenerate_inputs_do_not_panic() { + assert!(carve(3, 3, 0, &[], None, 2, 2).is_empty()); + assert!(carve(3, 3, 0, &[], None, 5, 5).is_empty()); + assert!(transpose(3, 3, 0, &[]).is_empty()); + assert!(resize_bilinear(3, 3, 0, &[], 2, 2).is_empty()); + assert!(resize_bilinear(3, 3, 1, &[0.5; 9], 0, 2).is_empty()); + assert!(resize_bilinear(3, 3, 1, &[0.5; 9], 2, 0).is_empty()); + assert_eq!(resize_bilinear(3, 3, 1, &[0.5; 4], 2, 2), vec![0.0; 4]); + assert!(carve(0, 5, 3, &[], None, 3, 7).is_empty()); + assert!(carve(0, 5, 3, &[], None, 3, 2).is_empty()); + let img = noise(10 * 5, 7, 3); + assert_eq!(carve(10, 5, 1, &img, Some(&[0.0; 3]), 4, 5), carve(10, 5, 1, &img, None, 4, 5)); + assert_eq!(carve(10, 5, 1, &img, Some(&[0.0; 3]), 4, 3), carve(10, 5, 1, &img, None, 4, 3)); + assert_eq!(carve(10, 5, 3, &[0.5; 20], None, 4, 5), vec![0.5; 20]); + assert_eq!(carve_width(usize::MAX, 2, 4, &[0.5; 8], None, 1), vec![0.5; 8]); + // Values past the size are ignored, through both passes. + let long = noise(20, 7, 4); + assert_eq!(carve(5, 3, 1, &long, None, 3, 3), carve(5, 3, 1, &long[..15], None, 3, 3)); + assert_eq!(carve(5, 3, 1, &long, None, 5, 2), carve(5, 3, 1, &long[..15], None, 5, 2)); +} + +/// Infinite samples, and finite ones whose differences overflow, give energies that aren't +/// numbers; those are the highest energy (pinned deliberately: the code before NaN-free costs +/// fed NaN to the seam search and chose differently). +#[test] +fn infinite_samples_carve_deterministically() { + let inf = f32::INFINITY; + assert_eq!(carve(2, 1, 1, &[inf, 0.5], None, 1, 1), [0.5]); + assert_eq!(carve(2, 1, 1, &[f32::MAX, f32::MAX], None, 6, 1), [f32::MAX, inf, inf, inf, inf, f32::MAX]); + let mut img = noise(30 * 20 * 3, 255, 41); + img.iter_mut().step_by(11).for_each(|v| *v = inf); + img.iter_mut().skip(4).step_by(23).for_each(|v| *v = -inf); + let out = carve(30, 20, 3, &img, None, 21, 14); + assert_eq!(out.len(), 21 * 14 * 3); + assert_eq!(out, carve(30, 20, 3, &img, None, 21, 14)); +} + +/// Infinite protection protects like full protection in the height pass too, where the map +/// is resampled (and an infinity alone would resample to NaN). +#[test] +fn infinite_protection_protects_in_both_passes() { + let (w, h) = (6, 6); + let img: Vec = (0..w * h).map(|i| (i * 7 % 5) as f32 / 4.0).collect(); + let row = |v: f32| (0..w * h).map(|i| if i / w == 2 { v } else { 0.0 }).collect::>(); + let (full, inf) = (row(1.0), row(f32::INFINITY)); + for (nw, nh) in [(6, 3), (4, 3), (3, 6)] { + assert_eq!(carve(w, h, 1, &img, Some(&inf), nw, nh), carve(w, h, 1, &img, Some(&full), nw, nh), "{nw}x{nh}"); + } + let kept = carve(w, h, 1, &img, Some(&inf), 6, 3); + assert!(kept.chunks(6).any(|r| r == &img[12..18]), "the protected row survives"); +} + +/// A cancel that arrives after the seam search, during the tall-image rebuild, still stops +/// the carve. +#[test] +fn proxy_rebuild_observes_cancellation() { + use std::sync::atomic::{AtomicUsize, Ordering}; + let (w, h, ch, new_w) = (128, PROXY_SHRINK_MIN_HEIGHT, 3, 64); + let img = noise(w * h * ch, 7, 5); + let calls = AtomicUsize::new(0); + // One check per seam passes; the first one after the search cancels. + let cancel = || calls.fetch_add(1, Ordering::Relaxed) >= w - new_w; + assert_eq!(carve_width_with(w, h, ch, &img, None, new_w, &Interrupt::cancel_only(&cancel)), Err(Cancelled)); + assert!(calls.load(Ordering::Relaxed) > w - new_w, "the rebuild checked for cancellation"); +} + +/// NaN samples and NaN protection steer seams the same whatever their sign and payload +/// (which arithmetic does not preserve consistently across builds): the same pixels are kept. +#[test] +fn nan_payloads_do_not_steer_seams() { + let (w, h, ch) = (24, 18, 3); + let (base, prot_base) = (noise(w * h * ch, 255, 21), noise(w * h, 3, 22)); + let carve_with_nans = |pixel: f32, prot: f32| { + let (mut img, mut p) = (base.clone(), prot_base.clone()); + img.iter_mut().step_by(37).for_each(|v| *v = pixel); + p.iter_mut().step_by(29).for_each(|v| *v = prot); + carve(w, h, ch, &img, Some(&p), 15, 11) + }; + let canonical = |v: Vec| v.into_iter().map(|f| if f.is_nan() { u32::MAX } else { f.to_bits() }).collect::>(); + let nans = [f32::NAN, -f32::NAN, f32::from_bits(0x7fc0_1234), f32::from_bits(0xffc0_0001)]; + let want = canonical(carve_with_nans(nans[0], nans[0])); + for &a in &nans { + for &b in &nans { + assert_eq!(canonical(carve_with_nans(a, b)), want, "pixel NaN {:#x}, protection NaN {:#x}", a.to_bits(), b.to_bits()); + } + } +} + +#[test] +fn cancelled_carve_stops() { + let (w, h) = (40, 20); + let img = vec![0.5f32; w * h * 3]; + let yes = || true; + assert_eq!(carve_with(w, h, 3, &img, None, 30, 15, &Interrupt::cancel_only(&yes)), Err(Cancelled)); + assert_eq!(carve_with(w, h, 3, &img, None, 30, 15, &Interrupt::NONE).unwrap(), carve(w, h, 3, &img, None, 30, 15)); +} + +/// A flat grey image with a salient vertical bar at x = 10..14 (red/blue columns). +fn bar(w: usize, h: usize) -> Vec { + let mut v = vec![0.5f32; w * h * 3]; + for y in 0..h { + for x in 10..14 { + let c = if x % 2 == 0 { [1.0, 0.0, 0.0] } else { [0.0, 0.0, 1.0] }; + v[(y * w + x) * 3..(y * w + x) * 3 + 3].copy_from_slice(&c); + } + } + v +} + +/// Columns that are pure red or pure blue top to bottom. +fn red_columns(w: usize, h: usize, img: &[f32]) -> usize { + let pure = |p: &[f32]| p[1] < 0.05 && ((p[0] > 0.95 && p[2] < 0.05) || (p[2] > 0.95 && p[0] < 0.05)); + (0..w).filter(|x| (0..h).all(|y| pure(&img[(y * w + x) * 3..(y * w + x) * 3 + 3]))).count() +} + +#[test] +fn seam_follows_low_energy() { + let (w, h) = (5, 4); + let mut e = vec![9.0f32; w * h]; + for y in 0..h { + e[y * w + 2] = 0.0; + } + assert_eq!(find_seam(w, h, &e), vec![2; 4]); +} + +#[test] +fn shrinking_keeps_the_salient_bar() { + let (w, h) = (40, 12); + let img = bar(w, h); + let out = carve(w, h, 3, &img, None, 24, h); + assert_eq!(out.len(), 24 * h * 3); + assert_eq!(red_columns(24, h, &out), 4, "the bar survives intact"); + // Plain resampling squashes it instead. + let plain = resize_bilinear(w, h, 3, &img, 24, h); + assert!(red_columns(24, h, &plain) < 4); +} + +#[test] +fn tall_proxy_shrink_preserves_full_resolution_salient_and_protected_pixels() { + let (w, h, ch, new_w) = (512, PROXY_SHRINK_MIN_HEIGHT, 3, 384); + let mut img = bar(w, h); + let mut protect = vec![0.0; w * h]; + for y in 0..h { + let i = (y * w + 256) * ch; + img[i..i + ch].copy_from_slice(&[0.03, 0.87, 0.42]); + protect[y * w + 256] = 1.0; + } + + let out = carve_width_with(w, h, ch, &img, Some(&protect), new_w, &Interrupt::NONE).unwrap(); + + assert_eq!(out.len(), new_w * h * ch); + assert_eq!(red_columns(new_w, h, &out), 4, "the full-resolution bar survives"); + for y in 0..h { + let row = &out[y * new_w * ch..(y + 1) * new_w * ch]; + assert!(row.chunks_exact(ch).any(|px| px == [0.03, 0.87, 0.42]), "protected mark survives row {y}"); + } +} + +#[test] +fn tall_proxy_shrink_observes_cancellation_before_modifying_source() { + let (w, h, ch) = (128, PROXY_SHRINK_MIN_HEIGHT, 3); + let img = vec![0.5; w * h * ch]; + let cancelled = || true; + assert_eq!(carve_width_with(w, h, ch, &img, None, 64, &Interrupt::cancel_only(&cancelled)), Err(Cancelled)); +} + +#[test] +fn enlarging_duplicates_flat_areas() { + let (w, h) = (30, 8); + let img = bar(w, h); + let out = carve(w, h, 3, &img, None, 50, h); + assert_eq!(out.len(), 50 * h * 3); + assert_eq!(red_columns(50, h, &out), 4); +} + +#[test] +fn height_and_protection() { + let (w, h) = (20, 30); + // Horizontal bar: carve height. + let mut img = vec![0.2f32; w * h]; + for x in 0..w { + img[12 * w + x] = 1.0; + } + let out = carve(w, h, 1, &img, None, w, 18); + assert_eq!(out.len(), w * 18); + assert_eq!((0..18).filter(|y| (0..w).all(|x| out[y * w + x] > 0.9)).count(), 1); + // Protecting a flat region keeps it: the seams go elsewhere. + let flat = vec![0.5f32; 16 * 4]; + let mut protect = vec![0.0f32; 16 * 4]; + for y in 0..4 { + protect[y * 16 + 3] = 1.0; + } + let mut marked = flat.clone(); + for y in 0..4 { + marked[y * 16 + 3] = 0.51; + } + let out = carve(16, 4, 1, &marked, Some(&protect), 8, 4); + assert!((0..4).all(|y| out[y * 8..y * 8 + 8].iter().any(|v| (*v - 0.51).abs() < 1e-6))); +} + +/// Noise quantised to `levels` values, so the energy map is full of exact ties. +fn noise(len: usize, levels: u32, seed: u32) -> Vec { + let mut s = seed | 1; + (0..len) + .map(|_| { + s ^= s << 13; + s ^= s >> 17; + s ^= s << 5; + (s % levels) as f32 / (levels - 1) as f32 + }) + .collect() +} + +fn fnv(v: &[f32]) -> u64 { + v.iter().flat_map(|f| f.to_bits().to_le_bytes()).fold(0xcbf2_9ce4_8422_2325, |h, b| (h ^ u64::from(b)).wrapping_mul(0x100_0000_01b3)) +} + +/// The exact output bits of a spread of carves (shrink, enlarge past half the width, both +/// axes, protection, 1/3/4 channels, tie-heavy and smooth images), pinned so that speed work +/// can't change which seams are chosen or how pixels are blended. +#[test] +fn output_bits_are_pinned() { + let cases: [(usize, usize, usize, u32, bool, usize, usize); 8] = [ + (61, 47, 3, 2, false, 40, 47), + (61, 47, 3, 255, false, 61, 30), + (61, 47, 4, 4, true, 35, 29), + (33, 20, 1, 3, false, 80, 20), + (33, 20, 3, 1000, true, 50, 45), + (48, 36, 4, 7, false, 70, 18), + (5, 3, 1, 2, false, 1, 1), + (40, 40, 3, 2, true, 39, 41), + ]; + let got: Vec = cases + .iter() + .enumerate() + .map(|(i, &(w, h, ch, levels, prot, nw, nh))| { + let img = noise(w * h * ch, levels, 7 + i as u32); + let protect = prot.then(|| noise(w * h, 3, 99 + i as u32)); + let out = carve(w, h, ch, &img, protect.as_deref(), nw, nh); + assert_eq!(out.len(), nw * nh * ch); + fnv(&out) + }) + .collect(); + assert_eq!(got, PINNED); +} + +const PINNED: [u64; 8] = [ + 0x24ea_9353_02c2_7c58, + 0x5a6e_8554_a0cb_ebb1, + 0x8b18_d63f_396e_21c9, + 0x1db2_23ad_3e6a_a7c5, + 0x721d_6cc5_34e0_3fdf, + 0x961a_ea6d_e512_ec7d, + 0x4d25_767f_9dce_13f5, + 0x2157_9f86_27d6_b835, +]; + +/// [`output_bits_are_pinned`] for the reduced-height seam search of tall images (rows at +/// least [`PROXY_SHRINK_MIN_HEIGHT`], at least [`PROXY_SHRINK_MIN_SEAMS`] seams): widths and, +/// through the transposed pass, heights, with and without protection, on tie-heavy and +/// fine-grained noise. +#[test] +fn tall_proxy_output_bits_are_pinned() { + let cases: [(usize, usize, usize, u32, bool, usize, usize); 5] = [ + (96, PROXY_SHRINK_MIN_HEIGHT, 3, 2, false, 30, PROXY_SHRINK_MIN_HEIGHT), + (130, 2_100, 4, 255, true, 64, 2_100), + (80, 2_600, 1, 65_536, false, 16, 2_600), + (PROXY_SHRINK_MIN_HEIGHT, 90, 3, 5, false, PROXY_SHRINK_MIN_HEIGHT, 20), + (2_050, 100, 4, 1000, true, 2_050, 36), + ]; + let got: Vec = cases + .iter() + .enumerate() + .map(|(i, &(w, h, ch, levels, prot, nw, nh))| { + let img = noise(w * h * ch, levels, 31 + i as u32); + let protect = prot.then(|| noise(w * h, 3, 131 + i as u32)); + let out = carve(w, h, ch, &img, protect.as_deref(), nw, nh); + assert_eq!(out.len(), nw * nh * ch); + fnv(&out) + }) + .collect(); + assert_eq!(got, TALL_PINNED); +} + +const TALL_PINNED: [u64; 5] = [0x5657_83ac_cb26_56a5, 0x81a6_b5f7_e299_fdfb, 0xcdf2_9df9_9b83_def5, 0xa713_544a_4dcc_d8d8, 0x3557_de9f_ffb0_881e]; + +#[test] +fn one_pixel_lines_enlarge_by_repeating() { + // Width 1 has no seam to spare: its one column is repeated. Height 1 likewise (through + // the transposed pass), alone or with the other axis. + let col = [0.1f32, 0.2, 0.3, 0.4, 0.5]; + assert_eq!(carve(1, 5, 1, &col, None, 4, 5), col.iter().flat_map(|v| [*v; 4]).collect::>()); + assert_eq!(carve(5, 1, 1, &col, None, 5, 3), col.repeat(3)); + assert_eq!(carve(1, 1, 3, &[0.7, 0.8, 0.9], None, 3, 2), [0.7, 0.8, 0.9].repeat(6)); + for (w, h, nw, nh) in [(1, 5, 6, 10), (1, 17, 6, 34), (16, 1, 21, 2), (7, 1, 3, 8), (2, 1, 1, 8)] { + let img = vec![0.5f32; w * h * 4]; + assert_eq!(carve(w, h, 4, &img, Some(&vec![1.0; w * h]), nw, nh).len(), nw * nh * 4, "{w}x{h} -> {nw}x{nh}"); + } +} + +#[test] +fn skin_rule() { + let px = [0.86f32, 0.62, 0.5, 0.2, 0.4, 0.8]; + assert_eq!(skin_mask(2, 1, 3, &px), vec![1.0, 0.0]); +} diff --git a/crates/algo/src/segment/mod.rs b/crates/algo/src/segment.rs similarity index 100% rename from crates/algo/src/segment/mod.rs rename to crates/algo/src/segment.rs diff --git a/crates/algo/src/selection.rs b/crates/algo/src/selection.rs index 1e71a502c7..70e815b2b2 100644 --- a/crates/algo/src/selection.rs +++ b/crates/algo/src/selection.rs @@ -896,668 +896,4 @@ pub fn polygon(points: &[(f32, f32)], area: Rect, anti_alias: bool) -> Vec } #[cfg(test)] -mod tests { - use super::*; - - fn img(w: usize, h: usize, f: impl Fn(usize, usize) -> [f32; 4]) -> Vec<[f32; 4]> { - (0..h).flat_map(|y| (0..w).map(move |x| (x, y))).map(|(x, y)| f(x, y)).collect() - } - - #[test] - fn wand_contiguous_vs_global() { - // Two separate red squares on white. - let px = img(20, 10, |x, _| if (2..6).contains(&x) || (12..16).contains(&x) { [1.0, 0.0, 0.0, 1.0] } else { [1.0; 4] }); - let a = Rect::new(0, 0, 20, 10); - let c = magic_wand(&px, a, (3, 3), 10.0, true, false); - assert_eq!(c.iter().filter(|v| **v > 0.0).count(), 40); - let g = magic_wand(&px, a, (3, 3), 10.0, false, false); - assert_eq!(g.iter().filter(|v| **v > 0.0).count(), 80); - let aa = magic_wand(&px, a, (3, 3), 10.0, true, true); - assert!(aa[3 * 20 + 6] > 0.0 && aa[3 * 20 + 6] < 1.0); - assert!(magic_wand(&px, a, (50, 3), 10.0, true, false).iter().all(|v| *v == 0.0)); - } - - #[test] - fn wand_tolerance() { - let px = img(10, 1, |x, _| [x as f32 * 10.0 / 255.0, 0.0, 0.0, 1.0]); - let m = magic_wand(&px, Rect::new(0, 0, 10, 1), (0, 0), 25.0, true, false); - assert_eq!(m.iter().filter(|v| **v > 0.0).count(), 3); - } - - #[test] - fn wand_ignores_hidden_rgb_only_when_both_pixels_are_fully_transparent() { - let area = Rect::new(0, 0, 6, 1); - let pixels = [[255, 0, 0, 0], [0, 255, 0, 0], [255, 0, 0, 128], [253, 0, 0, 128], [0, 0, 255, 0], [255, 0, 0, 255]]; - let floats: Vec<_> = pixels.iter().map(|p| p.map(|v| f32::from(v) / 255.0)).collect(); - for (seed, tolerance, contiguous, expected) in [ - ((0, 0), 0.0, true, [1.0, 1.0, 0.0, 0.0, 0.0, 0.0]), - ((0, 0), 0.0, false, [1.0, 1.0, 0.0, 0.0, 1.0, 0.0]), - ((4, 0), 32.0, false, [1.0, 1.0, 0.0, 0.0, 1.0, 0.0]), - ((2, 0), 0.0, false, [0.0, 0.0, 1.0, 0.0, 0.0, 0.0]), - ((2, 0), 2.0, true, [0.0, 0.0, 1.0, 1.0, 0.0, 0.0]), - ((5, 0), 32.0, false, [0.0, 0.0, 0.0, 0.0, 0.0, 1.0]), - ] { - assert_eq!(magic_wand(&floats, area, seed, tolerance, contiguous, false), expected); - let region = wand_region(&pixels, area, seed, tolerance, contiguous, false).unwrap(); - for (x, value) in expected.into_iter().enumerate() { - assert_eq!(region.at(x as i32, 0), value, "seed={seed:?}, tolerance={tolerance}, x={x}"); - } - } - // Hidden RGB cannot introduce extra edges into the anti-aliased selection either. - let plain: Vec<_> = pixels.iter().map(|p| if p[3] == 0 { [0; 4] } else { *p }).collect(); - for contiguous in [false, true] { - assert_eq!(wand_region(&pixels, area, (0, 0), 0.0, contiguous, true), wand_region(&plain, area, (0, 0), 0.0, contiguous, true)); - } - } - - #[test] - fn skin_tones_selects_skin_and_not_cream_or_white() { - let px = |rgb: [u8; 3]| [rgb[0], rgb[1], rgb[2]].map(|v| f32::from(v) / 255.0); - let rgba = |rgb: [u8; 3]| { - let [r, g, b] = px(rgb); - [r, g, b, 1.0] - }; - // Skin in light and shadow, then a cream shirt, a near-white wall, blue denim and black. - let skin = - [[183, 119, 81], [177, 132, 93], [180, 121, 84], [120, 76, 52], [173, 107, 75], [255, 219, 172], [194, 140, 104], [141, 85, 36], [92, 51, 23]] - .map(rgba); - let m = skin_tones(&skin, 40.0); - assert!(m.iter().all(|&v| v > 0.95), "skin {m:?}"); - let other = [[231, 225, 202], [252, 253, 247], [40, 60, 110], [5, 5, 5], [128, 128, 128], [220, 40, 40], [200, 160, 40]].map(rgba); - let m = skin_tones(&other, 40.0); - assert!(m.iter().all(|&v| v < 0.05), "not skin {m:?}"); - // Fuzziness widens the region; transparent pixels are never selected. - let pale = [rgba([230, 215, 200])]; - assert!(skin_tones(&pale, 200.0)[0] > skin_tones(&pale, 0.0)[0]); - assert_eq!(skin_tones(&[[0.7, 0.45, 0.3, 0.0]], 40.0), vec![0.0]); - } - - #[test] - fn color_range_falloff() { - let px = vec![[1.0, 0.0, 0.0, 1.0], [0.9, 0.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0], [1.0, 0.0, 0.0, 0.0]]; - let m = color_range(&px, [1.0, 0.0, 0.0], 40.0); - assert_eq!(m[0], 1.0); - assert!(m[1] > 0.3 && m[1] < 1.0); - assert_eq!(m[2], 0.0); - assert_eq!(m[3], 0.0); - } - - #[test] - fn color_range_several_samples_and_localized() { - let red = [1.0, 0.0, 0.0, 1.0]; - let blue = [0.0, 0.0, 1.0, 1.0]; - let green = [0.0, 1.0, 0.0, 1.0]; - // 4 × 1: red, blue, green, red. - let px = vec![red, blue, green, red]; - let s = |c: [f32; 4], at: Option<(f32, f32)>| RangeSample { color: [c[0], c[1], c[2]], at }; - let m = color_range_samples(&px, 4, &[s(red, None), s(blue, None)], 10.0, None); - assert_eq!(m, vec![1.0, 1.0, 0.0, 1.0]); - // One sample is exactly the single-colour Color Range. - assert_eq!(color_range_samples(&px, 4, &[s(red, None)], 40.0, None), color_range(&px, [1.0, 0.0, 0.0], 40.0)); - // Localized at x = 0 with a 2 px range: the far red pixel (x = 3) drops out, x = 1 would be half. - let m = color_range_samples(&px, 4, &[s(red, Some((0.0, 0.0)))], 10.0, Some(2.0)); - assert_eq!(m, vec![1.0, 0.0, 0.0, 0.0]); - let reds = vec![red; 4]; - let m = color_range_samples(&reds, 4, &[s(red, Some((0.0, 0.0)))], 10.0, Some(2.0)); - assert_eq!(m, vec![1.0, 0.5, 0.0, 0.0]); - // No samples: nothing selected. - assert!(color_range_samples(&px, 4, &[], 10.0, None).iter().all(|v| *v == 0.0)); - } - - /// Photoshop 2024's own Color Range coverage around the sample Lab (60, 25, 19.9961), read - /// from its selections on a 16-bit Lab document: (Lab in Photoshop's internal scale, where - /// a/b = (v16 − 32768)/256, fuzziness, coverage). - const PHOTOSHOP_COVERAGE: &[([f32; 3], f32, f32)] = &[ - ([61.9989, 25.5977, 20.5742], 40.0, 0.9686), - ([64.9989, 25.5977, 20.5742], 40.0, 0.7961), - ([67.9988, 25.5977, 20.5742], 40.0, 0.4824), - ([71.9997, 25.5977, 20.5742], 40.0, 0.1098), - ([79.9985, 25.5977, 20.5742], 40.0, 0.0), - ([71.9997, 25.5977, 20.5742], 100.0, 0.8118), - ([79.9985, 25.5977, 20.5742], 100.0, 0.4824), - ([60.0, 13.5508, 20.5742], 40.0, 0.0432), - ([60.0, 19.5742, 20.5742], 40.0, 0.6706), - ([60.0, 22.582, 20.5742], 40.0, 0.9333), - ([60.0, 28.6055, 20.5742], 40.0, 0.8549), - ([60.0, 31.6211, 20.5742], 40.0, 0.5098), - ([60.0, 37.6445, 20.5742], 40.0, 0.0078), - ([60.0, 13.5508, 20.5742], 100.0, 0.7647), - ([60.0, 37.6445, 20.5742], 100.0, 0.7137), - ([60.0, 25.5977, 10.5352], 40.0, 0.1725), - ([60.0, 25.5977, 16.5586], 40.0, 0.8667), - ([60.0, 25.5977, 24.5898], 40.0, 0.7647), - ([60.0, 25.5977, 30.6133], 40.0, 0.0863), - ([60.0, 25.5977, 10.5352], 100.0, 0.8392), - ([60.0, 25.5977, 30.6133], 100.0, 0.8), - ]; - - #[test] - fn lab_range_matches_photoshop() { - let r = LabRange::point([60.0, 25.0, 19.9961]); - for &(lab, fz, ps) in PHOTOSHOP_COVERAGE { - let got = lab_range_coverage(lab, &r, fz); - assert!((got - ps).abs() <= 2.0 / 255.0, "{lab:?} at fuzziness {fz}: {got} vs Photoshop {ps}"); - } - // Lightness is three times as forgiving as hue: the same 6-unit step along L and along a. - assert!(lab_range_coverage([66.0, 25.0, 20.0], &r, 40.0) > lab_range_coverage([60.0, 31.0, 20.0], &r, 40.0)); - // The sampled colour itself is always fully selected. - for fz in [1.0, 10.0, 40.0] { - assert_eq!(lab_range_coverage([60.0, 25.0, 19.9961], &r, fz), 1.0); - } - assert_eq!(quantize_lab8([60.1, 25.4, -19.6]), [(153.0f32 / 2.55), 25.0, -20.0]); - } - - #[test] - fn lab_range_box_and_edges() { - let r = LabRange::spanning(&[[50.0, 10.0, 0.0], [60.0, 20.0, 5.0]]).unwrap(); - assert_eq!(r, LabRange { lo: [50.0, 10.0, 0.0], hi: [60.0, 20.0, 5.0] }); - assert!(LabRange::spanning(&[]).is_none()); - // Everything inside the box is fully selected, whatever the fuzziness. - for fz in [1.0, 40.0, 200.0] { - assert_eq!(lab_range_coverage([55.0, 15.0, 2.0], &r, fz), 1.0); - } - // Coverage falls off outside it and is gone a fuzziness away. - let near = lab_range_coverage([55.0, 22.0, 2.0], &r, 40.0); - assert!(near > 0.0 && near < 1.0, "{near}"); - assert_eq!(lab_range_coverage([55.0, 40.0, 2.0], &r, 40.0), 0.0); - // Fuzziness 0: exact colours only. - let p = LabRange::point([50.0, 10.0, -5.0]); - assert_eq!(lab_range_coverage([50.0, 10.0, -5.0], &p, 0.0), 1.0); - assert_eq!(lab_range_coverage([50.0, 11.0, -5.0], &p, 0.0), 0.0); - // Hostile numbers never panic and never select. - for v in [f32::NAN, f32::INFINITY, -f32::INFINITY] { - for fz in [v, 40.0] { - let k = lab_range_coverage([v, 0.0, 0.0], &p, fz); - assert!((0.0..=1.0).contains(&k), "{k}"); - } - } - } - - /// Boxes Photoshop 2024's Color Range dialog returned after Subtract from Sample, at - /// fuzziness 40 unless noted: (lo, hi, subtracted value, fuzziness, new lo, new hi) on one axis. - const PHOTOSHOP_SUBTRACT_A: &[(f32, f32, f32, f32, f32, f32)] = &[ - (0.0, 20.0, 5.0, 40.0, 5.0, 20.0), - (0.0, 20.0, 10.0, 40.0, 0.0, 10.0), - (0.0, 20.0, 15.0, 40.0, 0.0, 15.0), - (0.0, 20.0, 0.0, 40.0, 2.68, 20.0), - (0.0, 20.0, -2.0, 40.0, 0.68, 20.0), - (0.0, 20.0, -3.0, 40.0, 2.36, 20.0), - (0.0, 20.0, -8.0, 40.0, 0.04, 20.0), - (0.0, 20.0, -11.0, 40.0, 2.4, 20.0), - (0.0, 20.0, -13.0, 40.0, 0.4, 20.0), - (0.0, 20.0, -14.0, 40.0, 0.0, 20.0), - (0.0, 20.0, 20.0, 40.0, 0.0, 17.32), - (0.0, 20.0, 23.0, 40.0, 0.0, 17.64), - (0.0, 20.0, 33.0, 40.0, 0.0, 19.6), - (0.0, 20.0, 0.0, 80.0, 5.35, 20.0), - (0.0, 20.0, -12.0, 80.0, 4.05, 20.0), - (0.0, 20.0, -22.0, 80.0, 4.76, 20.0), - (0.0, 20.0, -30.0, 80.0, 0.0, 20.0), - (0.0, 6.0, 4.0, 40.0, 0.0, 4.0), - (0.0, 2.0, 0.0, 40.0, 2.0, 2.0), - (0.0, 2.0, 3.0, 40.0, 0.0, 0.32), - ]; - - #[test] - fn subtract_reshapes_the_box_like_photoshop() { - for &(lo, hi, m, fz, want_lo, want_hi) in PHOTOSHOP_SUBTRACT_A { - let r = LabRange { lo: [50.0, lo, 0.0], hi: [50.0, hi, 0.0] }.subtract(&[50.0, m, 0.0], fz); - assert!( - (r.lo[1] - want_lo).abs() < 0.03 && (r.hi[1] - want_hi).abs() < 0.03, - "a [{lo}, {hi}] − {m} at {fz}: [{}, {}] vs Photoshop [{want_lo}, {want_hi}]", - r.lo[1], - r.hi[1] - ); - } - // Lightness (box 40–60, fuzziness 40): Photoshop gave 43.14, 41.17, 40.79 and 45.1. - for (m, want) in [(40.0, 43.14), (34.902, 41.17), (25.098, 40.79), (45.098, 45.1)] { - let r = LabRange { lo: [40.0, 0.0, 0.0], hi: [60.0, 0.0, 0.0] }.subtract(&[m, 0.0, 0.0], 40.0); - assert!((r.lo[0] - want).abs() < 0.05, "L − {m}: {} vs Photoshop {want}", r.lo[0]); - } - // All three axes at once (Photoshop: two samples, then one colour outside the box). - let r = LabRange { lo: [53.58, 0.0, 0.0], hi: [59.05, 30.56, 25.03] }.subtract(&[53.33, -28.71, 36.45], 40.0); - let want = LabRange { lo: [56.47, 0.0, 0.0], hi: [59.05, 30.56, 23.05] }; - for k in 0..3 { - assert!((r.lo[k] - want.lo[k]).abs() < 0.05 && (r.hi[k] - want.hi[k]).abs() < 0.05, "{r:?} vs {want:?}"); - } - // A single sample can't be subtracted from itself; hostile numbers change nothing. - let p = LabRange::point([50.0, 10.0, 10.0]); - assert_eq!(p.subtract(&[50.0, 10.0, 10.0], 40.0), p); - assert_eq!(p.subtract(&[f32::NAN, f32::INFINITY, -f32::INFINITY], f32::NAN), p); - assert_eq!(LabRange::spanning(&[[50.0, 0.0, 0.0]]).unwrap().grow(&[60.0, -5.0, 3.0]), LabRange { lo: [50.0, -5.0, 0.0], hi: [60.0, 0.0, 3.0] }); - } - - #[test] - fn eight_bit_grid_steps_are_uneven_like_photoshop() { - let r = LabRange::point([50.0, 10.0, -20.0]); - // The sampled colour itself is fully selected at any fuzziness. - for fz in [1.0, 5.0, 10.0, 40.0] { - assert_eq!(lab_range_coverage_8bit([50.0, 10.0, -20.0], &r, fz), 1.0); - } - // One step above on a counts as 1.5 units, one below as 0.5 (×3 weight): at fuzziness 40 - // (width 40.16) that is t = 4.5/40.16 and 1.5/40.16. - let up = lab_range_coverage_8bit([50.0, 11.0, -20.0], &r, 40.0); - let down = lab_range_coverage_8bit([50.0, 9.0, -20.0], &r, 40.0); - let p = |d: f32| (((1.0 - 2.0 * (d / (40.0 * 256.0 / 255.0)).powi(2)) * 256.0).floor().min(255.0)) / 255.0; - assert_eq!((up, down), (p(4.5), p(1.5))); - assert!(down > up); - // Lightness has no such offset; the exact (non-8-bit) coverage is symmetric. - assert_eq!(lab_range_coverage_8bit([51.0, 10.0, -20.0], &r, 40.0), lab_range_coverage_8bit([49.0, 10.0, -20.0], &r, 40.0)); - assert_eq!(lab_range_coverage([50.0, 11.0, -20.0], &r, 40.0), lab_range_coverage([50.0, 9.0, -20.0], &r, 40.0)); - let px = [[50.0, 11.0, -20.0, 1.0], [50.0, 9.0, -20.0, 1.0]]; - assert_eq!(color_range_lab(&px, 2, &r, 40.0, true, None), vec![up, down]); - } - - #[test] - fn color_range_lab_alpha_and_localized() { - let r = LabRange::point([50.0, 0.0, 0.0]); - let px = img(10, 1, |x, _| [50.0, 0.0, 0.0, if x == 0 { 0.0 } else { 1.0 }]); - let m = color_range_lab(&px, 10, &r, 40.0, false, None); - assert_eq!(m[0], 0.0, "transparent pixels are never selected"); - assert!(m[1..].iter().all(|v| *v > 0.9)); - let at = [(1.0, 0.0)]; - let l = color_range_lab(&px, 10, &r, 40.0, false, Some((4.0, &at))); - assert!(l[1] > l[3] && l[3] > 0.0 && l[6] == 0.0, "{l:?}"); - // No positions: localized clusters have nothing to centre on and change nothing. - assert_eq!(color_range_lab(&px, 10, &r, 40.0, false, Some((4.0, &[]))), m); - assert!(color_range_lab(&[], 0, &r, 40.0, false, None).is_empty()); - } - - #[test] - fn hue_families() { - let px = vec![ - [1.0, 0.0, 0.0, 1.0], // red - [1.0, 0.5, 0.0, 1.0], // orange: between red and yellow - [0.5, 0.5, 0.5, 1.0], // grey - [1.0, 0.5, 0.5, 1.0], // pink: a muted red - [0.0, 0.0, 1.0, 1.0], // blue - [1.0, 0.0, 0.0, 0.0], // transparent - ]; - let reds = hue_range(&px, 0.0); - assert_eq!(reds[0], 1.0); - assert!((reds[1] - 0.5).abs() < 1e-5); - assert_eq!(reds[2], 0.0); - assert!((reds[3] - 0.5).abs() < 1e-5); - assert_eq!(reds[4], 0.0); - assert_eq!(reds[5], 0.0); - let yellows = hue_range(&px, 60.0); - assert!((yellows[1] - 0.5).abs() < 1e-5); - assert_eq!(hue_range(&px, 240.0)[4], 1.0); - // Magentas wrap around 360°. - assert_eq!(hue_range(&[[1.0, 0.0, 1.0, 1.0]], 300.0)[0], 1.0); - assert!((hue_range(&[[1.0, 0.0, 0.5, 1.0]], 300.0)[0] - 0.5).abs() < 1e-5); - } - - #[test] - fn hue_families_weigh_dark_colours_like_photoshop() { - // Photoshop 2025's Blues on an 8-bit sRGB document (selection levels 0..255, #5243): the - // muted navy #3d3f54, a dark blue (0, 0, 84) and a mid blue (61, 61, 153). - let c = |r: u8, g: u8, b: u8| [f32::from(r) / 255.0, f32::from(g) / 255.0, f32::from(b) / 255.0, 1.0]; - let blues = hue_range(&[c(0x3d, 0x3f, 0x54), c(0, 0, 84), c(61, 61, 153)], 240.0); - for (got, want) in blues.iter().zip([35.0, 140.0, 129.0]) { - assert!((got * 255.0 - want).abs() <= 1.0, "{} vs Photoshop {want}", got * 255.0); - } - } - - #[test] - fn tonal_ranges() { - let g = |v: f32| [v / 255.0, v / 255.0, v / 255.0, 1.0]; - let px = vec![g(0.0), g(60.0), g(75.0), g(128.0), g(200.0), g(255.0)]; - let near = |a: &[f32], b: &[f32]| a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-4); - // Shadows up to 65, fading over 20 levels. - let sh = tone_range(&px, 0.0, 65.0, 20.0); - assert!(near(&sh, &[1.0, 1.0, 0.5, 0.0, 0.0, 0.0]), "{sh:?}"); - // Highlights from 190. - let h = tone_range(&px, 190.0, 255.0, 20.0); - assert!(near(&h, &[0.0, 0.0, 0.0, 0.0, 1.0, 1.0]), "{h:?}"); - // Midtones 105..150. - let m = tone_range(&px, 105.0, 150.0, 20.0); - assert!(near(&m, &[0.0, 0.0, 0.0, 1.0, 0.0, 0.0]), "{m:?}"); - } - - fn square(w: usize, h: usize) -> Vec { - (0..w * h).map(|i| if (5..15).contains(&(i % w)) && (5..15).contains(&(i / w)) { 1.0 } else { 0.0 }).collect() - } - - #[test] - fn expand_contract_border() { - let m = square(20, 20); - let e = expand(&m, 20, 20, 2.0); - assert_eq!(e[10 * 20 + 3], 1.0); - assert_eq!(e[10 * 20 + 2], 0.0); - let c = contract(&m, 20, 20, 2.0); - assert_eq!(c[10 * 20 + 6], 0.0); - assert_eq!(c[10 * 20 + 7], 1.0); - let b = border(&m, 20, 20, 4.0); - assert_eq!(b[10 * 20 + 10], 0.0); - assert!(b[10 * 20 + 5] > 0.5 && b[10 * 20 + 4] > 0.5); - } - - /// Photoshop 27.11, measured: a 32×32 rectangle at (16,16) in 64×64, Select › Modify › - /// Border 4 px, filled white. Row y = 32 for x = 8..=24, and the diagonal (16,16)..(24,24). - #[test] - fn border_matches_photoshop() { - let (w, h) = (64, 64); - let m: Vec = (0..w * h).map(|i| if (16..48).contains(&(i % w)) && (16..48).contains(&(i / w)) { 1.0 } else { 0.0 }).collect(); - let b = border(&m, w, h, 4.0); - let v = |x: usize, y: usize| (b[y * w + x] * 255.0).round() as i32; - let row: Vec = (8..=24).map(|x| v(x, 32)).collect(); - let diag: Vec = (16..=24).map(|d| v(d, d)).collect(); - let near = |got: &[i32], want: &[i32]| got.iter().zip(want).all(|(g, w)| (g - w).abs() <= 1); - let want_row = [0, 0, 0, 0, 63, 127, 191, 255, 255, 191, 127, 63, 0, 0, 0, 0, 0]; - assert!(near(&row, &want_row), "{row:?}"); - assert!(near(&diag, &[255, 191, 127, 63, 0, 0, 0, 0, 0]), "{diag:?}"); - } - - #[test] - fn smooth_removes_specks_and_feather_softens() { - let mut m = square(20, 20); - m[2 * 20 + 2] = 1.0; - let s = smooth(&m, 20, 20, 1.0); - assert_eq!(s[2 * 20 + 2], 0.0); - assert_eq!(s[10 * 20 + 10], 1.0); - // Radius 2 (σ 2) keeps the blur inside the 20×20 canvas, so no coverage is lost. - let f = feather(&square(20, 20), 20, 20, 2.0); - let edge = f[10 * 20 + 5]; - assert!(edge > 0.3 && edge < 0.8, "{edge}"); - let sum: f32 = f.iter().sum(); - assert!((sum - 100.0).abs() < 1.0); - } - - #[test] - fn polygon_area_and_aa() { - let a = Rect::new(0, 0, 20, 20); - let sq = polygon(&[(2.0, 2.0), (12.0, 2.0), (12.0, 12.0), (2.0, 12.0)], a, true); - let area: f32 = sq.iter().sum(); - assert!((area - 100.0).abs() < 1e-3, "{area}"); - let tri = polygon(&[(0.0, 0.0), (10.0, 0.0), (0.0, 10.0)], a, true); - let area: f32 = tri.iter().sum(); - assert!((area - 50.0).abs() < 1.0, "{area}"); - assert!(tri.iter().any(|v| *v > 0.0 && *v < 1.0)); - let hard = polygon(&[(0.0, 0.0), (10.0, 0.0), (0.0, 10.0)], a, false); - assert!(hard.iter().all(|v| *v == 0.0 || *v == 1.0)); - assert!(polygon(&[(0.0, 0.0), (1.0, 1.0)], a, true).iter().all(|v| *v == 0.0)); - } - - /// The previous polygon fill (every edge tested on every sub-row), kept as the oracle. - fn old_polygon(points: &[(f32, f32)], area: Rect, anti_alias: bool) -> Vec { - let (w, h) = (area.width() as usize, area.height() as usize); - let mut m = vec![0.0f32; w * h]; - if points.len() < 3 { - return m; - } - let sub = if anti_alias { 4 } else { 1 }; - let mut xs: Vec = Vec::new(); - for py in 0..h { - for s in 0..sub { - let y = area.y0 as f32 + py as f32 + (s as f32 + 0.5) / sub as f32; - xs.clear(); - for i in 0..points.len() { - let (a, b) = (points[i], points[(i + 1) % points.len()]); - if (a.1 <= y && b.1 > y) || (b.1 <= y && a.1 > y) { - xs.push(a.0 + (y - a.1) / (b.1 - a.1) * (b.0 - a.0)); - } - } - xs.sort_by(|a, b| a.total_cmp(b)); - for span in xs.as_chunks::<2>().0 { - let (x0, x1) = ((span[0] - area.x0 as f32).max(0.0), (span[1] - area.x0 as f32).min(w as f32)); - if x1 <= x0 { - continue; - } - let (c0, c1) = (x0.floor() as usize, (x1.ceil() as usize).min(w)); - for cx in c0..c1 { - let cov = if anti_alias { - ((cx + 1) as f32).min(x1) - (cx as f32).max(x0) - } else { - let c = cx as f32 + 0.5; - if c >= x0 && c < x1 { 1.0 } else { 0.0 } - }; - m[py * w + cx] += cov.max(0.0) / sub as f32; - } - } - } - } - for v in &mut m { - *v = v.min(1.0); - } - m - } - - #[test] - fn polygon_matches_the_every_edge_fill_bit_for_bit() { - let mut seed = 0x2545_f491_u32; - let mut rnd = move || { - seed ^= seed << 13; - seed ^= seed >> 17; - seed ^= seed << 5; - seed as f32 / u32::MAX as f32 - }; - // Taller than one 64-row band, offset, and a 1-pixel-wide area. - let areas = [Rect::new(0, 0, 90, 150), Rect::new(-13, 7, 60, 211), Rect::new(5, -40, 6, 30)]; - let mut cases: Vec> = vec![ - // Self-intersecting star, horizontal edges, repeated points, collinear runs. - (0..11) - .map(|i| { - let t = i as f32 * 4.0 * std::f32::consts::PI / 11.0; - (40.0 + 35.0 * t.cos(), 80.0 + 70.0 * t.sin()) - }) - .collect(), - vec![(10.0, 10.0), (50.0, 10.0), (50.0, 10.0), (50.0, 60.0), (30.0, 60.0), (30.0, 30.0), (10.0, 30.0)], - vec![(0.0, 0.0), (20.0, 0.0), (40.0, 0.0), (40.0, 0.0), (0.0, 0.0)], - // Vertices on the sub-row centres and the pixel edges. - vec![(3.125, 2.375), (70.5, 2.375), (70.875, 140.625), (3.0, 140.0), (35.0, 64.0), (35.0, 64.125)], - // Entirely outside, and straddling every side. - vec![(-500.0, -500.0), (-400.0, -500.0), (-450.0, -300.0)], - vec![(-80.0, -60.0), (300.0, 20.0), (60.0, 400.0)], - // Non-finite coordinates and a negative zero. - vec![(10.0, 10.0), (f32::NAN, 40.0), (60.0, 70.0), (20.0, f32::INFINITY), (-0.0, -0.0), (0.0, 0.0)], - ]; - for n in [3, 7, 40, 400] { - for spread in [1.0, 2.0] { - cases.push((0..n).map(|_| (rnd() * 100.0 * spread - 50.0 * (spread - 1.0), rnd() * 220.0 * spread - 60.0 * spread)).collect()); - // Lasso-like: a random walk snapped to quarter pixels. - let (mut x, mut y) = (45.0f32, 75.0f32); - cases.push( - (0..n) - .map(|_| { - x = ((x + (rnd() - 0.5) * 12.0 * spread) * 4.0).round() / 4.0; - y = ((y + (rnd() - 0.5) * 12.0 * spread) * 4.0).round() / 4.0; - (x, y) - }) - .collect(), - ); - } - } - for pts in &cases { - for &area in &areas { - for aa in [true, false] { - let (new, old) = (polygon(pts, area, aa), old_polygon(pts, area, aa)); - assert_eq!(new.len(), old.len()); - let diff = new.iter().zip(&old).position(|(a, b)| a.to_bits() != b.to_bits()); - assert!(diff.is_none(), "{pts:?} {area:?} aa={aa}: first difference at {diff:?}"); - } - } - } - } - - #[test] - fn combine_modes() { - let a = Rect::new(0, 0, 4, 1); - let old = mask_to_surface(&[1.0, 1.0, 0.0, 0.0], a); - let new = [0.0, 1.0, 1.0, 0.0]; - let v = |s: Option| mask_from_surface(s.as_ref(), a); - assert_eq!(v(combine(Some(&old), &new, a, SelectionMode::Replace)), vec![0.0, 1.0, 1.0, 0.0]); - assert_eq!(v(combine(Some(&old), &new, a, SelectionMode::Add)), vec![1.0, 1.0, 1.0, 0.0]); - assert_eq!(v(combine(Some(&old), &new, a, SelectionMode::Subtract)), vec![1.0, 0.0, 0.0, 0.0]); - assert_eq!(v(combine(Some(&old), &new, a, SelectionMode::Intersect)), vec![0.0, 1.0, 0.0, 0.0]); - assert!(combine(Some(&old), &[1.0; 4], a, SelectionMode::Subtract).is_none()); - assert_eq!(SelectionMode::parse("add"), SelectionMode::Add); - } - - /// The previous (per-sample) conversions, kept as the oracle for the tiled fast paths. - fn old_mask_to_surface(m: &[f32], area: Rect) -> Surface { - let mut s = Surface::new(PixelFormat::GRAY8); - if !area.is_empty() { - s.write_region(area, m); - } - s.prune(); - s - } - - fn old_combine(old: Option<&Surface>, new: &[f32], area: Rect, mode: SelectionMode) -> Option { - let mut prev = Vec::new(); - match old { - Some(s) => s.read_region_into(area, &mut prev), - None => prev = vec![0.0; new.len()], - } - let q: Vec = new.iter().map(|v| (v.clamp(0.0, 1.0) * 255.0).round() / 255.0).collect(); - let out: Vec = match mode { - SelectionMode::Replace => q, - SelectionMode::Add => prev.iter().zip(&q).map(|(a, b)| a.max(*b)).collect(), - SelectionMode::Subtract => prev.iter().zip(&q).map(|(a, b)| (a - b).max(0.0)).collect(), - SelectionMode::Intersect => prev.iter().zip(&q).map(|(a, b)| a.min(*b)).collect(), - }; - let out: Vec = out.into_iter().map(|v| if v < 0.5 / 255.0 { 0.0 } else { v }).collect(); - if out.iter().all(|v| *v <= 0.0) { - return None; - } - Some(old_mask_to_surface(&out, area)) - } - - #[test] - fn tiled_conversions_match_per_sample_ones() { - let mut rng = crate::photo_util::Rng(7); - let mut u = move || (rng.next() >> 11) as f32 / (1u64 << 53) as f32; - // Off-grid areas spanning several tiles, including negative origins. - // The last one holds whole tiles, which fully selected masks fill (shared tiles). - for area in - [Rect::new(0, 0, 300, 20), Rect::new(-37, 250, 530, 263), Rect::new(255, -3, 258, 600), Rect::new(5, 5, 6, 6), Rect::new(-37, -300, 530, 263)] - { - let n = area.width() as usize * area.height() as usize; - let old_m: Vec = (0..n).map(|i| if i % 97 < 40 { u() } else { 0.0 }).collect(); - let old = old_mask_to_surface(&old_m, area); - let fast = mask_to_surface(&old_m, area); - assert_eq!(fast, old, "{area:?}"); - let mut slow_read = Vec::new(); - old.read_region_into(area, &mut slow_read); - assert_eq!(mask_from_surface(Some(&old), area), slow_read); - for kind in 0..4 { - let new: Vec = (0..n) - .map(|i| match kind { - 0 => u() * 1.2 - 0.1, - 1 => { - if i % 131 < 50 { - 1.0 - } else { - 0.0 - } - } - 2 => 0.001, - _ => f32::from(u8::from(i >= 1000)), - }) - .collect(); - for mode in [SelectionMode::Replace, SelectionMode::Add, SelectionMode::Subtract, SelectionMode::Intersect] { - for prev in [None, Some(&old)] { - assert_eq!(combine(prev, &new, area, mode), old_combine(prev, &new, area, mode), "{area:?} {kind} {mode:?}"); - } - } - } - } - // A short mask buffer reads as zeros instead of panicking. - let a = Rect::new(0, 0, 10, 10); - assert!(combine(None, &[1.0; 5], a, SelectionMode::Replace).is_some()); - assert_eq!(mask_to_surface(&[], a).tile_count(), 0); - assert!(combine(None, &[], Rect::EMPTY, SelectionMode::Replace).is_none()); - } - - fn blobs(w: i32, h: i32) -> Vec<[u8; 4]> { - // Deterministic blotchy image with gradients and hard edges. - (0..w * h) - .map(|i| { - let (x, y) = (i % w, i / w); - let v = ((x * 7 + y * 3) % 23 + if (x / 5 + y / 4) % 3 == 0 { 120 } else { 0 }) as u8; - [v, v / 2, 255 - v, if x % 11 == 0 { 128 } else { 255 }] - }) - .collect() - } - - #[test] - fn magic_wand_rejects_incomplete_and_overflowing_pixel_inputs() { - let area = Rect::new(0, 0, 4, 4); - let short = vec![[255u8, 0, 0, 255]; 4]; - let floats: Vec<[f32; 4]> = short.iter().map(|p| p.map(|v| f32::from(v) / 255.0)).collect(); - assert_eq!(magic_wand(&floats, area, (1, 1), 0.0, true, false), Vec::::new()); - assert_eq!(wand_region(&short, area, (1, 1), 0.0, true, false), None); - - let huge = Rect::new(i32::MIN, i32::MIN, i32::MAX, i32::MAX); - assert!(magic_wand(&floats, huge, (0, 0), 0.0, false, false).is_empty()); - assert_eq!(wand_region(&short, huge, (0, 0), 0.0, false, false), None); - - let valid = Rect::new(0, 0, 2, 2); - assert_eq!(magic_wand(&floats, valid, (0, 0), 0.0, false, false), vec![1.0; 4]); - assert!(wand_region(&short, valid, (0, 0), 0.0, false, false).is_some()); - } - - #[test] - fn region_coverage_outside_a_short_mask_is_zero() { - let region = Region { bbox: Rect::new(-2, -3, 1, -1), mask: vec![255, 128] }; - assert_eq!(region.at(-2, -3), 1.0); - assert!((region.at(-1, -3) - 128.0 / 255.0).abs() < 1e-6); - assert_eq!(region.at(0, -3), 0.0); - assert_eq!(region.at(-2, -2), 0.0); - assert_eq!(region.at(-3, -3), 0.0); - - let extreme = Region { bbox: Rect::new(i32::MIN, i32::MIN, i32::MAX, i32::MAX), mask: vec![] }; - assert_eq!(extreme.at(i32::MAX - 1, i32::MAX - 1), 0.0); - assert_eq!(extreme.at(i32::MIN, i32::MIN), 0.0); - } - - #[test] - fn wand_region_matches_reference_magic_wand() { - let (w, h) = (37, 29); - let area = Rect::new(3, -2, 3 + w, -2 + h); - let img = blobs(w, h); - let f: Vec<[f32; 4]> = img.iter().map(|p| p.map(|v| v as f32 / 255.0)).collect(); - for (seed, tol, contiguous, aa) in [ - ((10, 5), 10.0, true, true), - ((10, 5), 10.0, true, false), - ((20, 20), 40.0, false, true), - ((4, -2), 0.0, true, true), - ((30, 10), 255.0, true, true), - ] { - let reference = magic_wand(&f, area, seed, tol, contiguous, aa); - let r = wand_region(&img, area, seed, tol, contiguous, aa).unwrap(); - for y in area.y0..area.y1 { - for x in area.x0..area.x1 { - let want = (reference[((y - area.y0) * w + x - area.x0) as usize] * 255.0).round(); - assert!((r.at(x, y) * 255.0 - want).abs() <= 1.0, "{seed:?} {tol} {contiguous} {aa} at {x},{y}: {} vs {want}", r.at(x, y) * 255.0); - } - } - } - assert!(wand_region(&img, area, (0, 0), 10.0, true, true).is_none()); - } - - #[test] - fn combine_region_matches_combine() { - let area = Rect::new(0, 0, 40, 30); - let mut old = Surface::new(PixelFormat::GRAY8); - old.fill_rect(Rect::new(5, 5, 25, 20), &[1.0]); - old.fill_rect(Rect::new(8, 8, 10, 10), &[0.4]); - let img = blobs(40, 30); - let region = wand_region(&img, area, (12, 12), 30.0, true, true).unwrap(); - let full: Vec = (0..area.height()).flat_map(|y| (0..area.width()).map(move |x| (x, y))).map(|(x, y)| region.at(x as i32, y as i32)).collect(); - for mode in [SelectionMode::Replace, SelectionMode::Add, SelectionMode::Subtract, SelectionMode::Intersect] { - let a = combine(Some(&old), &full, area, mode); - let b = combine_region(Some(&old), Some(®ion), mode); - assert_eq!(a.is_some(), b.is_some(), "{mode:?}"); - if let (Some(a), Some(b)) = (a, b) { - for y in 0..30 { - for x in 0..40 { - assert!((a.pixel(x, y)[0] - b.pixel(x, y)[0]).abs() < 1.5 / 255.0, "{mode:?} {x},{y}"); - } - } - } - } - assert!(combine_region(None, None, SelectionMode::Subtract).is_none()); - } -} +mod tests; diff --git a/crates/algo/src/selection/tests.rs b/crates/algo/src/selection/tests.rs new file mode 100644 index 0000000000..368633f03a --- /dev/null +++ b/crates/algo/src/selection/tests.rs @@ -0,0 +1,656 @@ +use super::*; + +fn img(w: usize, h: usize, f: impl Fn(usize, usize) -> [f32; 4]) -> Vec<[f32; 4]> { + (0..h).flat_map(|y| (0..w).map(move |x| (x, y))).map(|(x, y)| f(x, y)).collect() +} + +#[test] +fn wand_contiguous_vs_global() { + // Two separate red squares on white. + let px = img(20, 10, |x, _| if (2..6).contains(&x) || (12..16).contains(&x) { [1.0, 0.0, 0.0, 1.0] } else { [1.0; 4] }); + let a = Rect::new(0, 0, 20, 10); + let c = magic_wand(&px, a, (3, 3), 10.0, true, false); + assert_eq!(c.iter().filter(|v| **v > 0.0).count(), 40); + let g = magic_wand(&px, a, (3, 3), 10.0, false, false); + assert_eq!(g.iter().filter(|v| **v > 0.0).count(), 80); + let aa = magic_wand(&px, a, (3, 3), 10.0, true, true); + assert!(aa[3 * 20 + 6] > 0.0 && aa[3 * 20 + 6] < 1.0); + assert!(magic_wand(&px, a, (50, 3), 10.0, true, false).iter().all(|v| *v == 0.0)); +} + +#[test] +fn wand_tolerance() { + let px = img(10, 1, |x, _| [x as f32 * 10.0 / 255.0, 0.0, 0.0, 1.0]); + let m = magic_wand(&px, Rect::new(0, 0, 10, 1), (0, 0), 25.0, true, false); + assert_eq!(m.iter().filter(|v| **v > 0.0).count(), 3); +} + +#[test] +fn wand_ignores_hidden_rgb_only_when_both_pixels_are_fully_transparent() { + let area = Rect::new(0, 0, 6, 1); + let pixels = [[255, 0, 0, 0], [0, 255, 0, 0], [255, 0, 0, 128], [253, 0, 0, 128], [0, 0, 255, 0], [255, 0, 0, 255]]; + let floats: Vec<_> = pixels.iter().map(|p| p.map(|v| f32::from(v) / 255.0)).collect(); + for (seed, tolerance, contiguous, expected) in [ + ((0, 0), 0.0, true, [1.0, 1.0, 0.0, 0.0, 0.0, 0.0]), + ((0, 0), 0.0, false, [1.0, 1.0, 0.0, 0.0, 1.0, 0.0]), + ((4, 0), 32.0, false, [1.0, 1.0, 0.0, 0.0, 1.0, 0.0]), + ((2, 0), 0.0, false, [0.0, 0.0, 1.0, 0.0, 0.0, 0.0]), + ((2, 0), 2.0, true, [0.0, 0.0, 1.0, 1.0, 0.0, 0.0]), + ((5, 0), 32.0, false, [0.0, 0.0, 0.0, 0.0, 0.0, 1.0]), + ] { + assert_eq!(magic_wand(&floats, area, seed, tolerance, contiguous, false), expected); + let region = wand_region(&pixels, area, seed, tolerance, contiguous, false).unwrap(); + for (x, value) in expected.into_iter().enumerate() { + assert_eq!(region.at(x as i32, 0), value, "seed={seed:?}, tolerance={tolerance}, x={x}"); + } + } + // Hidden RGB cannot introduce extra edges into the anti-aliased selection either. + let plain: Vec<_> = pixels.iter().map(|p| if p[3] == 0 { [0; 4] } else { *p }).collect(); + for contiguous in [false, true] { + assert_eq!(wand_region(&pixels, area, (0, 0), 0.0, contiguous, true), wand_region(&plain, area, (0, 0), 0.0, contiguous, true)); + } +} + +#[test] +fn skin_tones_selects_skin_and_not_cream_or_white() { + let px = |rgb: [u8; 3]| [rgb[0], rgb[1], rgb[2]].map(|v| f32::from(v) / 255.0); + let rgba = |rgb: [u8; 3]| { + let [r, g, b] = px(rgb); + [r, g, b, 1.0] + }; + // Skin in light and shadow, then a cream shirt, a near-white wall, blue denim and black. + let skin = [[183, 119, 81], [177, 132, 93], [180, 121, 84], [120, 76, 52], [173, 107, 75], [255, 219, 172], [194, 140, 104], [141, 85, 36], [92, 51, 23]] + .map(rgba); + let m = skin_tones(&skin, 40.0); + assert!(m.iter().all(|&v| v > 0.95), "skin {m:?}"); + let other = [[231, 225, 202], [252, 253, 247], [40, 60, 110], [5, 5, 5], [128, 128, 128], [220, 40, 40], [200, 160, 40]].map(rgba); + let m = skin_tones(&other, 40.0); + assert!(m.iter().all(|&v| v < 0.05), "not skin {m:?}"); + // Fuzziness widens the region; transparent pixels are never selected. + let pale = [rgba([230, 215, 200])]; + assert!(skin_tones(&pale, 200.0)[0] > skin_tones(&pale, 0.0)[0]); + assert_eq!(skin_tones(&[[0.7, 0.45, 0.3, 0.0]], 40.0), vec![0.0]); +} + +#[test] +fn color_range_falloff() { + let px = vec![[1.0, 0.0, 0.0, 1.0], [0.9, 0.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0], [1.0, 0.0, 0.0, 0.0]]; + let m = color_range(&px, [1.0, 0.0, 0.0], 40.0); + assert_eq!(m[0], 1.0); + assert!(m[1] > 0.3 && m[1] < 1.0); + assert_eq!(m[2], 0.0); + assert_eq!(m[3], 0.0); +} + +#[test] +fn color_range_several_samples_and_localized() { + let red = [1.0, 0.0, 0.0, 1.0]; + let blue = [0.0, 0.0, 1.0, 1.0]; + let green = [0.0, 1.0, 0.0, 1.0]; + // 4 × 1: red, blue, green, red. + let px = vec![red, blue, green, red]; + let s = |c: [f32; 4], at: Option<(f32, f32)>| RangeSample { color: [c[0], c[1], c[2]], at }; + let m = color_range_samples(&px, 4, &[s(red, None), s(blue, None)], 10.0, None); + assert_eq!(m, vec![1.0, 1.0, 0.0, 1.0]); + // One sample is exactly the single-colour Color Range. + assert_eq!(color_range_samples(&px, 4, &[s(red, None)], 40.0, None), color_range(&px, [1.0, 0.0, 0.0], 40.0)); + // Localized at x = 0 with a 2 px range: the far red pixel (x = 3) drops out, x = 1 would be half. + let m = color_range_samples(&px, 4, &[s(red, Some((0.0, 0.0)))], 10.0, Some(2.0)); + assert_eq!(m, vec![1.0, 0.0, 0.0, 0.0]); + let reds = vec![red; 4]; + let m = color_range_samples(&reds, 4, &[s(red, Some((0.0, 0.0)))], 10.0, Some(2.0)); + assert_eq!(m, vec![1.0, 0.5, 0.0, 0.0]); + // No samples: nothing selected. + assert!(color_range_samples(&px, 4, &[], 10.0, None).iter().all(|v| *v == 0.0)); +} + +/// Photoshop 2024's own Color Range coverage around the sample Lab (60, 25, 19.9961), read +/// from its selections on a 16-bit Lab document: (Lab in Photoshop's internal scale, where +/// a/b = (v16 − 32768)/256, fuzziness, coverage). +const PHOTOSHOP_COVERAGE: &[([f32; 3], f32, f32)] = &[ + ([61.9989, 25.5977, 20.5742], 40.0, 0.9686), + ([64.9989, 25.5977, 20.5742], 40.0, 0.7961), + ([67.9988, 25.5977, 20.5742], 40.0, 0.4824), + ([71.9997, 25.5977, 20.5742], 40.0, 0.1098), + ([79.9985, 25.5977, 20.5742], 40.0, 0.0), + ([71.9997, 25.5977, 20.5742], 100.0, 0.8118), + ([79.9985, 25.5977, 20.5742], 100.0, 0.4824), + ([60.0, 13.5508, 20.5742], 40.0, 0.0432), + ([60.0, 19.5742, 20.5742], 40.0, 0.6706), + ([60.0, 22.582, 20.5742], 40.0, 0.9333), + ([60.0, 28.6055, 20.5742], 40.0, 0.8549), + ([60.0, 31.6211, 20.5742], 40.0, 0.5098), + ([60.0, 37.6445, 20.5742], 40.0, 0.0078), + ([60.0, 13.5508, 20.5742], 100.0, 0.7647), + ([60.0, 37.6445, 20.5742], 100.0, 0.7137), + ([60.0, 25.5977, 10.5352], 40.0, 0.1725), + ([60.0, 25.5977, 16.5586], 40.0, 0.8667), + ([60.0, 25.5977, 24.5898], 40.0, 0.7647), + ([60.0, 25.5977, 30.6133], 40.0, 0.0863), + ([60.0, 25.5977, 10.5352], 100.0, 0.8392), + ([60.0, 25.5977, 30.6133], 100.0, 0.8), +]; + +#[test] +fn lab_range_matches_photoshop() { + let r = LabRange::point([60.0, 25.0, 19.9961]); + for &(lab, fz, ps) in PHOTOSHOP_COVERAGE { + let got = lab_range_coverage(lab, &r, fz); + assert!((got - ps).abs() <= 2.0 / 255.0, "{lab:?} at fuzziness {fz}: {got} vs Photoshop {ps}"); + } + // Lightness is three times as forgiving as hue: the same 6-unit step along L and along a. + assert!(lab_range_coverage([66.0, 25.0, 20.0], &r, 40.0) > lab_range_coverage([60.0, 31.0, 20.0], &r, 40.0)); + // The sampled colour itself is always fully selected. + for fz in [1.0, 10.0, 40.0] { + assert_eq!(lab_range_coverage([60.0, 25.0, 19.9961], &r, fz), 1.0); + } + assert_eq!(quantize_lab8([60.1, 25.4, -19.6]), [(153.0f32 / 2.55), 25.0, -20.0]); +} + +#[test] +fn lab_range_box_and_edges() { + let r = LabRange::spanning(&[[50.0, 10.0, 0.0], [60.0, 20.0, 5.0]]).unwrap(); + assert_eq!(r, LabRange { lo: [50.0, 10.0, 0.0], hi: [60.0, 20.0, 5.0] }); + assert!(LabRange::spanning(&[]).is_none()); + // Everything inside the box is fully selected, whatever the fuzziness. + for fz in [1.0, 40.0, 200.0] { + assert_eq!(lab_range_coverage([55.0, 15.0, 2.0], &r, fz), 1.0); + } + // Coverage falls off outside it and is gone a fuzziness away. + let near = lab_range_coverage([55.0, 22.0, 2.0], &r, 40.0); + assert!(near > 0.0 && near < 1.0, "{near}"); + assert_eq!(lab_range_coverage([55.0, 40.0, 2.0], &r, 40.0), 0.0); + // Fuzziness 0: exact colours only. + let p = LabRange::point([50.0, 10.0, -5.0]); + assert_eq!(lab_range_coverage([50.0, 10.0, -5.0], &p, 0.0), 1.0); + assert_eq!(lab_range_coverage([50.0, 11.0, -5.0], &p, 0.0), 0.0); + // Hostile numbers never panic and never select. + for v in [f32::NAN, f32::INFINITY, -f32::INFINITY] { + for fz in [v, 40.0] { + let k = lab_range_coverage([v, 0.0, 0.0], &p, fz); + assert!((0.0..=1.0).contains(&k), "{k}"); + } + } +} + +/// Boxes Photoshop 2024's Color Range dialog returned after Subtract from Sample, at +/// fuzziness 40 unless noted: (lo, hi, subtracted value, fuzziness, new lo, new hi) on one axis. +const PHOTOSHOP_SUBTRACT_A: &[(f32, f32, f32, f32, f32, f32)] = &[ + (0.0, 20.0, 5.0, 40.0, 5.0, 20.0), + (0.0, 20.0, 10.0, 40.0, 0.0, 10.0), + (0.0, 20.0, 15.0, 40.0, 0.0, 15.0), + (0.0, 20.0, 0.0, 40.0, 2.68, 20.0), + (0.0, 20.0, -2.0, 40.0, 0.68, 20.0), + (0.0, 20.0, -3.0, 40.0, 2.36, 20.0), + (0.0, 20.0, -8.0, 40.0, 0.04, 20.0), + (0.0, 20.0, -11.0, 40.0, 2.4, 20.0), + (0.0, 20.0, -13.0, 40.0, 0.4, 20.0), + (0.0, 20.0, -14.0, 40.0, 0.0, 20.0), + (0.0, 20.0, 20.0, 40.0, 0.0, 17.32), + (0.0, 20.0, 23.0, 40.0, 0.0, 17.64), + (0.0, 20.0, 33.0, 40.0, 0.0, 19.6), + (0.0, 20.0, 0.0, 80.0, 5.35, 20.0), + (0.0, 20.0, -12.0, 80.0, 4.05, 20.0), + (0.0, 20.0, -22.0, 80.0, 4.76, 20.0), + (0.0, 20.0, -30.0, 80.0, 0.0, 20.0), + (0.0, 6.0, 4.0, 40.0, 0.0, 4.0), + (0.0, 2.0, 0.0, 40.0, 2.0, 2.0), + (0.0, 2.0, 3.0, 40.0, 0.0, 0.32), +]; + +#[test] +fn subtract_reshapes_the_box_like_photoshop() { + for &(lo, hi, m, fz, want_lo, want_hi) in PHOTOSHOP_SUBTRACT_A { + let r = LabRange { lo: [50.0, lo, 0.0], hi: [50.0, hi, 0.0] }.subtract(&[50.0, m, 0.0], fz); + assert!( + (r.lo[1] - want_lo).abs() < 0.03 && (r.hi[1] - want_hi).abs() < 0.03, + "a [{lo}, {hi}] − {m} at {fz}: [{}, {}] vs Photoshop [{want_lo}, {want_hi}]", + r.lo[1], + r.hi[1] + ); + } + // Lightness (box 40–60, fuzziness 40): Photoshop gave 43.14, 41.17, 40.79 and 45.1. + for (m, want) in [(40.0, 43.14), (34.902, 41.17), (25.098, 40.79), (45.098, 45.1)] { + let r = LabRange { lo: [40.0, 0.0, 0.0], hi: [60.0, 0.0, 0.0] }.subtract(&[m, 0.0, 0.0], 40.0); + assert!((r.lo[0] - want).abs() < 0.05, "L − {m}: {} vs Photoshop {want}", r.lo[0]); + } + // All three axes at once (Photoshop: two samples, then one colour outside the box). + let r = LabRange { lo: [53.58, 0.0, 0.0], hi: [59.05, 30.56, 25.03] }.subtract(&[53.33, -28.71, 36.45], 40.0); + let want = LabRange { lo: [56.47, 0.0, 0.0], hi: [59.05, 30.56, 23.05] }; + for k in 0..3 { + assert!((r.lo[k] - want.lo[k]).abs() < 0.05 && (r.hi[k] - want.hi[k]).abs() < 0.05, "{r:?} vs {want:?}"); + } + // A single sample can't be subtracted from itself; hostile numbers change nothing. + let p = LabRange::point([50.0, 10.0, 10.0]); + assert_eq!(p.subtract(&[50.0, 10.0, 10.0], 40.0), p); + assert_eq!(p.subtract(&[f32::NAN, f32::INFINITY, -f32::INFINITY], f32::NAN), p); + assert_eq!(LabRange::spanning(&[[50.0, 0.0, 0.0]]).unwrap().grow(&[60.0, -5.0, 3.0]), LabRange { lo: [50.0, -5.0, 0.0], hi: [60.0, 0.0, 3.0] }); +} + +#[test] +fn eight_bit_grid_steps_are_uneven_like_photoshop() { + let r = LabRange::point([50.0, 10.0, -20.0]); + // The sampled colour itself is fully selected at any fuzziness. + for fz in [1.0, 5.0, 10.0, 40.0] { + assert_eq!(lab_range_coverage_8bit([50.0, 10.0, -20.0], &r, fz), 1.0); + } + // One step above on a counts as 1.5 units, one below as 0.5 (×3 weight): at fuzziness 40 + // (width 40.16) that is t = 4.5/40.16 and 1.5/40.16. + let up = lab_range_coverage_8bit([50.0, 11.0, -20.0], &r, 40.0); + let down = lab_range_coverage_8bit([50.0, 9.0, -20.0], &r, 40.0); + let p = |d: f32| (((1.0 - 2.0 * (d / (40.0 * 256.0 / 255.0)).powi(2)) * 256.0).floor().min(255.0)) / 255.0; + assert_eq!((up, down), (p(4.5), p(1.5))); + assert!(down > up); + // Lightness has no such offset; the exact (non-8-bit) coverage is symmetric. + assert_eq!(lab_range_coverage_8bit([51.0, 10.0, -20.0], &r, 40.0), lab_range_coverage_8bit([49.0, 10.0, -20.0], &r, 40.0)); + assert_eq!(lab_range_coverage([50.0, 11.0, -20.0], &r, 40.0), lab_range_coverage([50.0, 9.0, -20.0], &r, 40.0)); + let px = [[50.0, 11.0, -20.0, 1.0], [50.0, 9.0, -20.0, 1.0]]; + assert_eq!(color_range_lab(&px, 2, &r, 40.0, true, None), vec![up, down]); +} + +#[test] +fn color_range_lab_alpha_and_localized() { + let r = LabRange::point([50.0, 0.0, 0.0]); + let px = img(10, 1, |x, _| [50.0, 0.0, 0.0, if x == 0 { 0.0 } else { 1.0 }]); + let m = color_range_lab(&px, 10, &r, 40.0, false, None); + assert_eq!(m[0], 0.0, "transparent pixels are never selected"); + assert!(m[1..].iter().all(|v| *v > 0.9)); + let at = [(1.0, 0.0)]; + let l = color_range_lab(&px, 10, &r, 40.0, false, Some((4.0, &at))); + assert!(l[1] > l[3] && l[3] > 0.0 && l[6] == 0.0, "{l:?}"); + // No positions: localized clusters have nothing to centre on and change nothing. + assert_eq!(color_range_lab(&px, 10, &r, 40.0, false, Some((4.0, &[]))), m); + assert!(color_range_lab(&[], 0, &r, 40.0, false, None).is_empty()); +} + +#[test] +fn hue_families() { + let px = vec![ + [1.0, 0.0, 0.0, 1.0], // red + [1.0, 0.5, 0.0, 1.0], // orange: between red and yellow + [0.5, 0.5, 0.5, 1.0], // grey + [1.0, 0.5, 0.5, 1.0], // pink: a muted red + [0.0, 0.0, 1.0, 1.0], // blue + [1.0, 0.0, 0.0, 0.0], // transparent + ]; + let reds = hue_range(&px, 0.0); + assert_eq!(reds[0], 1.0); + assert!((reds[1] - 0.5).abs() < 1e-5); + assert_eq!(reds[2], 0.0); + assert!((reds[3] - 0.5).abs() < 1e-5); + assert_eq!(reds[4], 0.0); + assert_eq!(reds[5], 0.0); + let yellows = hue_range(&px, 60.0); + assert!((yellows[1] - 0.5).abs() < 1e-5); + assert_eq!(hue_range(&px, 240.0)[4], 1.0); + // Magentas wrap around 360°. + assert_eq!(hue_range(&[[1.0, 0.0, 1.0, 1.0]], 300.0)[0], 1.0); + assert!((hue_range(&[[1.0, 0.0, 0.5, 1.0]], 300.0)[0] - 0.5).abs() < 1e-5); +} + +#[test] +fn hue_families_weigh_dark_colours_like_photoshop() { + // Photoshop 2025's Blues on an 8-bit sRGB document (selection levels 0..255, #5243): the + // muted navy #3d3f54, a dark blue (0, 0, 84) and a mid blue (61, 61, 153). + let c = |r: u8, g: u8, b: u8| [f32::from(r) / 255.0, f32::from(g) / 255.0, f32::from(b) / 255.0, 1.0]; + let blues = hue_range(&[c(0x3d, 0x3f, 0x54), c(0, 0, 84), c(61, 61, 153)], 240.0); + for (got, want) in blues.iter().zip([35.0, 140.0, 129.0]) { + assert!((got * 255.0 - want).abs() <= 1.0, "{} vs Photoshop {want}", got * 255.0); + } +} + +#[test] +fn tonal_ranges() { + let g = |v: f32| [v / 255.0, v / 255.0, v / 255.0, 1.0]; + let px = vec![g(0.0), g(60.0), g(75.0), g(128.0), g(200.0), g(255.0)]; + let near = |a: &[f32], b: &[f32]| a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-4); + // Shadows up to 65, fading over 20 levels. + let sh = tone_range(&px, 0.0, 65.0, 20.0); + assert!(near(&sh, &[1.0, 1.0, 0.5, 0.0, 0.0, 0.0]), "{sh:?}"); + // Highlights from 190. + let h = tone_range(&px, 190.0, 255.0, 20.0); + assert!(near(&h, &[0.0, 0.0, 0.0, 0.0, 1.0, 1.0]), "{h:?}"); + // Midtones 105..150. + let m = tone_range(&px, 105.0, 150.0, 20.0); + assert!(near(&m, &[0.0, 0.0, 0.0, 1.0, 0.0, 0.0]), "{m:?}"); +} + +fn square(w: usize, h: usize) -> Vec { + (0..w * h).map(|i| if (5..15).contains(&(i % w)) && (5..15).contains(&(i / w)) { 1.0 } else { 0.0 }).collect() +} + +#[test] +fn expand_contract_border() { + let m = square(20, 20); + let e = expand(&m, 20, 20, 2.0); + assert_eq!(e[10 * 20 + 3], 1.0); + assert_eq!(e[10 * 20 + 2], 0.0); + let c = contract(&m, 20, 20, 2.0); + assert_eq!(c[10 * 20 + 6], 0.0); + assert_eq!(c[10 * 20 + 7], 1.0); + let b = border(&m, 20, 20, 4.0); + assert_eq!(b[10 * 20 + 10], 0.0); + assert!(b[10 * 20 + 5] > 0.5 && b[10 * 20 + 4] > 0.5); +} + +/// Photoshop 27.11, measured: a 32×32 rectangle at (16,16) in 64×64, Select › Modify › +/// Border 4 px, filled white. Row y = 32 for x = 8..=24, and the diagonal (16,16)..(24,24). +#[test] +fn border_matches_photoshop() { + let (w, h) = (64, 64); + let m: Vec = (0..w * h).map(|i| if (16..48).contains(&(i % w)) && (16..48).contains(&(i / w)) { 1.0 } else { 0.0 }).collect(); + let b = border(&m, w, h, 4.0); + let v = |x: usize, y: usize| (b[y * w + x] * 255.0).round() as i32; + let row: Vec = (8..=24).map(|x| v(x, 32)).collect(); + let diag: Vec = (16..=24).map(|d| v(d, d)).collect(); + let near = |got: &[i32], want: &[i32]| got.iter().zip(want).all(|(g, w)| (g - w).abs() <= 1); + let want_row = [0, 0, 0, 0, 63, 127, 191, 255, 255, 191, 127, 63, 0, 0, 0, 0, 0]; + assert!(near(&row, &want_row), "{row:?}"); + assert!(near(&diag, &[255, 191, 127, 63, 0, 0, 0, 0, 0]), "{diag:?}"); +} + +#[test] +fn smooth_removes_specks_and_feather_softens() { + let mut m = square(20, 20); + m[2 * 20 + 2] = 1.0; + let s = smooth(&m, 20, 20, 1.0); + assert_eq!(s[2 * 20 + 2], 0.0); + assert_eq!(s[10 * 20 + 10], 1.0); + // Radius 2 (σ 2) keeps the blur inside the 20×20 canvas, so no coverage is lost. + let f = feather(&square(20, 20), 20, 20, 2.0); + let edge = f[10 * 20 + 5]; + assert!(edge > 0.3 && edge < 0.8, "{edge}"); + let sum: f32 = f.iter().sum(); + assert!((sum - 100.0).abs() < 1.0); +} + +#[test] +fn polygon_area_and_aa() { + let a = Rect::new(0, 0, 20, 20); + let sq = polygon(&[(2.0, 2.0), (12.0, 2.0), (12.0, 12.0), (2.0, 12.0)], a, true); + let area: f32 = sq.iter().sum(); + assert!((area - 100.0).abs() < 1e-3, "{area}"); + let tri = polygon(&[(0.0, 0.0), (10.0, 0.0), (0.0, 10.0)], a, true); + let area: f32 = tri.iter().sum(); + assert!((area - 50.0).abs() < 1.0, "{area}"); + assert!(tri.iter().any(|v| *v > 0.0 && *v < 1.0)); + let hard = polygon(&[(0.0, 0.0), (10.0, 0.0), (0.0, 10.0)], a, false); + assert!(hard.iter().all(|v| *v == 0.0 || *v == 1.0)); + assert!(polygon(&[(0.0, 0.0), (1.0, 1.0)], a, true).iter().all(|v| *v == 0.0)); +} + +/// The previous polygon fill (every edge tested on every sub-row), kept as the oracle. +fn old_polygon(points: &[(f32, f32)], area: Rect, anti_alias: bool) -> Vec { + let (w, h) = (area.width() as usize, area.height() as usize); + let mut m = vec![0.0f32; w * h]; + if points.len() < 3 { + return m; + } + let sub = if anti_alias { 4 } else { 1 }; + let mut xs: Vec = Vec::new(); + for py in 0..h { + for s in 0..sub { + let y = area.y0 as f32 + py as f32 + (s as f32 + 0.5) / sub as f32; + xs.clear(); + for i in 0..points.len() { + let (a, b) = (points[i], points[(i + 1) % points.len()]); + if (a.1 <= y && b.1 > y) || (b.1 <= y && a.1 > y) { + xs.push(a.0 + (y - a.1) / (b.1 - a.1) * (b.0 - a.0)); + } + } + xs.sort_by(|a, b| a.total_cmp(b)); + for span in xs.as_chunks::<2>().0 { + let (x0, x1) = ((span[0] - area.x0 as f32).max(0.0), (span[1] - area.x0 as f32).min(w as f32)); + if x1 <= x0 { + continue; + } + let (c0, c1) = (x0.floor() as usize, (x1.ceil() as usize).min(w)); + for cx in c0..c1 { + let cov = if anti_alias { + ((cx + 1) as f32).min(x1) - (cx as f32).max(x0) + } else { + let c = cx as f32 + 0.5; + if c >= x0 && c < x1 { 1.0 } else { 0.0 } + }; + m[py * w + cx] += cov.max(0.0) / sub as f32; + } + } + } + } + for v in &mut m { + *v = v.min(1.0); + } + m +} + +#[test] +fn polygon_matches_the_every_edge_fill_bit_for_bit() { + let mut seed = 0x2545_f491_u32; + let mut rnd = move || { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + seed as f32 / u32::MAX as f32 + }; + // Taller than one 64-row band, offset, and a 1-pixel-wide area. + let areas = [Rect::new(0, 0, 90, 150), Rect::new(-13, 7, 60, 211), Rect::new(5, -40, 6, 30)]; + let mut cases: Vec> = vec![ + // Self-intersecting star, horizontal edges, repeated points, collinear runs. + (0..11) + .map(|i| { + let t = i as f32 * 4.0 * std::f32::consts::PI / 11.0; + (40.0 + 35.0 * t.cos(), 80.0 + 70.0 * t.sin()) + }) + .collect(), + vec![(10.0, 10.0), (50.0, 10.0), (50.0, 10.0), (50.0, 60.0), (30.0, 60.0), (30.0, 30.0), (10.0, 30.0)], + vec![(0.0, 0.0), (20.0, 0.0), (40.0, 0.0), (40.0, 0.0), (0.0, 0.0)], + // Vertices on the sub-row centres and the pixel edges. + vec![(3.125, 2.375), (70.5, 2.375), (70.875, 140.625), (3.0, 140.0), (35.0, 64.0), (35.0, 64.125)], + // Entirely outside, and straddling every side. + vec![(-500.0, -500.0), (-400.0, -500.0), (-450.0, -300.0)], + vec![(-80.0, -60.0), (300.0, 20.0), (60.0, 400.0)], + // Non-finite coordinates and a negative zero. + vec![(10.0, 10.0), (f32::NAN, 40.0), (60.0, 70.0), (20.0, f32::INFINITY), (-0.0, -0.0), (0.0, 0.0)], + ]; + for n in [3, 7, 40, 400] { + for spread in [1.0, 2.0] { + cases.push((0..n).map(|_| (rnd() * 100.0 * spread - 50.0 * (spread - 1.0), rnd() * 220.0 * spread - 60.0 * spread)).collect()); + // Lasso-like: a random walk snapped to quarter pixels. + let (mut x, mut y) = (45.0f32, 75.0f32); + cases.push( + (0..n) + .map(|_| { + x = ((x + (rnd() - 0.5) * 12.0 * spread) * 4.0).round() / 4.0; + y = ((y + (rnd() - 0.5) * 12.0 * spread) * 4.0).round() / 4.0; + (x, y) + }) + .collect(), + ); + } + } + for pts in &cases { + for &area in &areas { + for aa in [true, false] { + let (new, old) = (polygon(pts, area, aa), old_polygon(pts, area, aa)); + assert_eq!(new.len(), old.len()); + let diff = new.iter().zip(&old).position(|(a, b)| a.to_bits() != b.to_bits()); + assert!(diff.is_none(), "{pts:?} {area:?} aa={aa}: first difference at {diff:?}"); + } + } + } +} + +#[test] +fn combine_modes() { + let a = Rect::new(0, 0, 4, 1); + let old = mask_to_surface(&[1.0, 1.0, 0.0, 0.0], a); + let new = [0.0, 1.0, 1.0, 0.0]; + let v = |s: Option| mask_from_surface(s.as_ref(), a); + assert_eq!(v(combine(Some(&old), &new, a, SelectionMode::Replace)), vec![0.0, 1.0, 1.0, 0.0]); + assert_eq!(v(combine(Some(&old), &new, a, SelectionMode::Add)), vec![1.0, 1.0, 1.0, 0.0]); + assert_eq!(v(combine(Some(&old), &new, a, SelectionMode::Subtract)), vec![1.0, 0.0, 0.0, 0.0]); + assert_eq!(v(combine(Some(&old), &new, a, SelectionMode::Intersect)), vec![0.0, 1.0, 0.0, 0.0]); + assert!(combine(Some(&old), &[1.0; 4], a, SelectionMode::Subtract).is_none()); + assert_eq!(SelectionMode::parse("add"), SelectionMode::Add); +} + +/// The previous (per-sample) conversions, kept as the oracle for the tiled fast paths. +fn old_mask_to_surface(m: &[f32], area: Rect) -> Surface { + let mut s = Surface::new(PixelFormat::GRAY8); + if !area.is_empty() { + s.write_region(area, m); + } + s.prune(); + s +} + +fn old_combine(old: Option<&Surface>, new: &[f32], area: Rect, mode: SelectionMode) -> Option { + let mut prev = Vec::new(); + match old { + Some(s) => s.read_region_into(area, &mut prev), + None => prev = vec![0.0; new.len()], + } + let q: Vec = new.iter().map(|v| (v.clamp(0.0, 1.0) * 255.0).round() / 255.0).collect(); + let out: Vec = match mode { + SelectionMode::Replace => q, + SelectionMode::Add => prev.iter().zip(&q).map(|(a, b)| a.max(*b)).collect(), + SelectionMode::Subtract => prev.iter().zip(&q).map(|(a, b)| (a - b).max(0.0)).collect(), + SelectionMode::Intersect => prev.iter().zip(&q).map(|(a, b)| a.min(*b)).collect(), + }; + let out: Vec = out.into_iter().map(|v| if v < 0.5 / 255.0 { 0.0 } else { v }).collect(); + if out.iter().all(|v| *v <= 0.0) { + return None; + } + Some(old_mask_to_surface(&out, area)) +} + +#[test] +fn tiled_conversions_match_per_sample_ones() { + let mut rng = crate::photo_util::Rng(7); + let mut u = move || (rng.next() >> 11) as f32 / (1u64 << 53) as f32; + // Off-grid areas spanning several tiles, including negative origins. + // The last one holds whole tiles, which fully selected masks fill (shared tiles). + for area in [Rect::new(0, 0, 300, 20), Rect::new(-37, 250, 530, 263), Rect::new(255, -3, 258, 600), Rect::new(5, 5, 6, 6), Rect::new(-37, -300, 530, 263)] { + let n = area.width() as usize * area.height() as usize; + let old_m: Vec = (0..n).map(|i| if i % 97 < 40 { u() } else { 0.0 }).collect(); + let old = old_mask_to_surface(&old_m, area); + let fast = mask_to_surface(&old_m, area); + assert_eq!(fast, old, "{area:?}"); + let mut slow_read = Vec::new(); + old.read_region_into(area, &mut slow_read); + assert_eq!(mask_from_surface(Some(&old), area), slow_read); + for kind in 0..4 { + let new: Vec = (0..n) + .map(|i| match kind { + 0 => u() * 1.2 - 0.1, + 1 => { + if i % 131 < 50 { + 1.0 + } else { + 0.0 + } + } + 2 => 0.001, + _ => f32::from(u8::from(i >= 1000)), + }) + .collect(); + for mode in [SelectionMode::Replace, SelectionMode::Add, SelectionMode::Subtract, SelectionMode::Intersect] { + for prev in [None, Some(&old)] { + assert_eq!(combine(prev, &new, area, mode), old_combine(prev, &new, area, mode), "{area:?} {kind} {mode:?}"); + } + } + } + } + // A short mask buffer reads as zeros instead of panicking. + let a = Rect::new(0, 0, 10, 10); + assert!(combine(None, &[1.0; 5], a, SelectionMode::Replace).is_some()); + assert_eq!(mask_to_surface(&[], a).tile_count(), 0); + assert!(combine(None, &[], Rect::EMPTY, SelectionMode::Replace).is_none()); +} + +fn blobs(w: i32, h: i32) -> Vec<[u8; 4]> { + // Deterministic blotchy image with gradients and hard edges. + (0..w * h) + .map(|i| { + let (x, y) = (i % w, i / w); + let v = ((x * 7 + y * 3) % 23 + if (x / 5 + y / 4) % 3 == 0 { 120 } else { 0 }) as u8; + [v, v / 2, 255 - v, if x % 11 == 0 { 128 } else { 255 }] + }) + .collect() +} + +#[test] +fn magic_wand_rejects_incomplete_and_overflowing_pixel_inputs() { + let area = Rect::new(0, 0, 4, 4); + let short = vec![[255u8, 0, 0, 255]; 4]; + let floats: Vec<[f32; 4]> = short.iter().map(|p| p.map(|v| f32::from(v) / 255.0)).collect(); + assert_eq!(magic_wand(&floats, area, (1, 1), 0.0, true, false), Vec::::new()); + assert_eq!(wand_region(&short, area, (1, 1), 0.0, true, false), None); + + let huge = Rect::new(i32::MIN, i32::MIN, i32::MAX, i32::MAX); + assert!(magic_wand(&floats, huge, (0, 0), 0.0, false, false).is_empty()); + assert_eq!(wand_region(&short, huge, (0, 0), 0.0, false, false), None); + + let valid = Rect::new(0, 0, 2, 2); + assert_eq!(magic_wand(&floats, valid, (0, 0), 0.0, false, false), vec![1.0; 4]); + assert!(wand_region(&short, valid, (0, 0), 0.0, false, false).is_some()); +} + +#[test] +fn region_coverage_outside_a_short_mask_is_zero() { + let region = Region { bbox: Rect::new(-2, -3, 1, -1), mask: vec![255, 128] }; + assert_eq!(region.at(-2, -3), 1.0); + assert!((region.at(-1, -3) - 128.0 / 255.0).abs() < 1e-6); + assert_eq!(region.at(0, -3), 0.0); + assert_eq!(region.at(-2, -2), 0.0); + assert_eq!(region.at(-3, -3), 0.0); + + let extreme = Region { bbox: Rect::new(i32::MIN, i32::MIN, i32::MAX, i32::MAX), mask: vec![] }; + assert_eq!(extreme.at(i32::MAX - 1, i32::MAX - 1), 0.0); + assert_eq!(extreme.at(i32::MIN, i32::MIN), 0.0); +} + +#[test] +fn wand_region_matches_reference_magic_wand() { + let (w, h) = (37, 29); + let area = Rect::new(3, -2, 3 + w, -2 + h); + let img = blobs(w, h); + let f: Vec<[f32; 4]> = img.iter().map(|p| p.map(|v| v as f32 / 255.0)).collect(); + for (seed, tol, contiguous, aa) in + [((10, 5), 10.0, true, true), ((10, 5), 10.0, true, false), ((20, 20), 40.0, false, true), ((4, -2), 0.0, true, true), ((30, 10), 255.0, true, true)] + { + let reference = magic_wand(&f, area, seed, tol, contiguous, aa); + let r = wand_region(&img, area, seed, tol, contiguous, aa).unwrap(); + for y in area.y0..area.y1 { + for x in area.x0..area.x1 { + let want = (reference[((y - area.y0) * w + x - area.x0) as usize] * 255.0).round(); + assert!((r.at(x, y) * 255.0 - want).abs() <= 1.0, "{seed:?} {tol} {contiguous} {aa} at {x},{y}: {} vs {want}", r.at(x, y) * 255.0); + } + } + } + assert!(wand_region(&img, area, (0, 0), 10.0, true, true).is_none()); +} + +#[test] +fn combine_region_matches_combine() { + let area = Rect::new(0, 0, 40, 30); + let mut old = Surface::new(PixelFormat::GRAY8); + old.fill_rect(Rect::new(5, 5, 25, 20), &[1.0]); + old.fill_rect(Rect::new(8, 8, 10, 10), &[0.4]); + let img = blobs(40, 30); + let region = wand_region(&img, area, (12, 12), 30.0, true, true).unwrap(); + let full: Vec = (0..area.height()).flat_map(|y| (0..area.width()).map(move |x| (x, y))).map(|(x, y)| region.at(x as i32, y as i32)).collect(); + for mode in [SelectionMode::Replace, SelectionMode::Add, SelectionMode::Subtract, SelectionMode::Intersect] { + let a = combine(Some(&old), &full, area, mode); + let b = combine_region(Some(&old), Some(®ion), mode); + assert_eq!(a.is_some(), b.is_some(), "{mode:?}"); + if let (Some(a), Some(b)) = (a, b) { + for y in 0..30 { + for x in 0..40 { + assert!((a.pixel(x, y)[0] - b.pixel(x, y)[0]).abs() < 1.5 / 255.0, "{mode:?} {x},{y}"); + } + } + } + } + assert!(combine_region(None, None, SelectionMode::Subtract).is_none()); +} diff --git a/crates/algo/src/stack.rs b/crates/algo/src/stack.rs index dbb5b22e65..3d0c9a87b3 100644 --- a/crates/algo/src/stack.rs +++ b/crates/algo/src/stack.rs @@ -205,308 +205,4 @@ fn combine_with(layers: &[Vec<[f32; 4]>], f: impl Fn(&mut [f32], &mut EntropyScr } #[cfg(test)] -mod tests { - use super::*; - - fn px(v: f32) -> Vec<[f32; 4]> { - vec![[v, v, v, 1.0]] - } - - #[test] - fn basic_statistics() { - let layers = vec![px(0.1), px(0.9), px(0.2), px(0.3), px(0.1)]; - let at = |s| combine(&layers, s)[0][0]; - assert!((at(Stat::Mean) - 0.32).abs() < 1e-6); - assert!((at(Stat::Median) - 0.2).abs() < 1e-6); - assert_eq!(at(Stat::Minimum), 0.1); - assert_eq!(at(Stat::Maximum), 0.9); - assert!((at(Stat::Range) - 0.8).abs() < 1e-6); - assert!((at(Stat::Summation) - 1.6).abs() < 1e-6); - let var = at(Stat::Variance); - assert!((at(Stat::StandardDeviation) - var.sqrt()).abs() < 1e-6); - assert!(at(Stat::Skewness) > 0.5, "right-skewed"); - assert!(at(Stat::Entropy) > 0.0 && at(Stat::Entropy) <= 1.0); - assert!(at(Stat::Kurtosis) > 0.0); - } - - #[test] - fn statistics_preserve_hdr_and_signed_samples() { - let layers = vec![px(-2.0), px(4.0)]; - for (mode, expected) in [ - (Stat::Mean, 1.0), - (Stat::Median, 1.0), - (Stat::Minimum, -2.0), - (Stat::Maximum, 4.0), - (Stat::Range, 6.0), - (Stat::Summation, 2.0), - (Stat::Variance, 9.0), - (Stat::StandardDeviation, 3.0), - ] { - assert_eq!(combine(&layers, mode)[0], [expected, expected, expected, 1.0], "{mode:?}"); - } - for mode in [Stat::Mean, Stat::Median] { - assert_eq!(combine(&[px(2.0), px(4.0)], mode)[0], [3.0, 3.0, 3.0, 1.0]); - assert_eq!(combine(&[px(-2.0), px(-4.0)], mode)[0], [-3.0, -3.0, -3.0, 1.0]); - } - // These display-oriented statistics still apply their own normalisation. - for mode in [Stat::Entropy, Stat::Skewness, Stat::Kurtosis] { - assert!((0.0..=1.0).contains(&combine(&layers, mode)[0][0]), "{mode:?}"); - } - } - - #[test] - fn transparent_samples_are_ignored() { - let layers = vec![vec![[0.5, 0.5, 0.5, 1.0]], vec![[1.0, 1.0, 1.0, 0.0]]]; - assert_eq!(combine(&layers, Stat::Mean)[0], [0.5, 0.5, 0.5, 1.0]); - let empty = vec![vec![[1.0, 1.0, 1.0, 0.0]]]; - assert_eq!(combine(&empty, Stat::Mean)[0][3], 0.0); - } - - #[test] - fn median_removes_outlier() { - let layers = vec![px(0.5), px(0.5), px(1.0)]; - assert_eq!(combine(&layers, Stat::Median)[0][0], 0.5); - } - - /// Five layers over six pixels (the last layer is short). Covers opaque, partly transparent, - /// fully transparent, HDR / negative, single-sample and tied-value pixels. - fn fixture() -> Vec> { - vec![ - vec![[0.10, 0.20, 0.30, 1.0], [0.5, 0.5, 0.5, 1.0], [0.9, 0.9, 0.9, 0.0], [-2.0, 4.0, 0.0, 1.0], [0.7, 0.2, 0.1, 0.5], [0.25, 0.25, 0.25, 1.0]], - vec![[0.90, 0.60, 0.30, 1.0], [0.0, 0.0, 0.0, 0.0], [0.8, 0.8, 0.8, 0.0], [3.0, -1.0, 0.5, 0.75], [0.0, 0.0, 0.0, 0.0], [0.25, 0.75, 0.25, 1.0]], - vec![[0.20, 0.90, 0.30, 0.5], [0.1, 0.2, 0.3, 1.0], [0.7, 0.7, 0.7, 0.0], [0.5, 0.5, 0.5, 1.0], [0.0, 0.0, 0.0, 0.0], [0.5, 0.75, 0.25, 0.25]], - vec![[0.30, 0.05, 0.30, 0.25], [0.3, 0.4, 0.5, 0.5], [0.6, 0.6, 0.6, 0.0], [1.5, 1.5, 1.5, 1.0], [0.0, 0.0, 0.0, 0.0], [0.25, 0.75, 0.5, 1.0]], - vec![[0.10, 0.70, 0.99, 1.0], [0.9, 0.1, 0.2, 1.0], [0.5, 0.5, 0.5, 0.0], [0.0, 0.0, 0.0, 1.0]], - ] - } - - fn bits(px: &[[f32; 4]]) -> Vec<[u32; 4]> { - px.iter().map(|p| p.map(f32::to_bits)).collect() - } - - /// Every mode except Entropy is bit-for-bit what the old serial loop produced. The expected - /// bit patterns were recorded by running the unmodified `combine` on [`fixture`]. - #[test] - fn statistics_are_bit_identical_to_the_serial_implementation() { - let layers = fixture(); - let expected: Vec<(Stat, Vec<[u32; 4]>)> = vec![ - ( - Stat::Kurtosis, - [ - [0x3e96956b, 0x3e182e3f, 0x3ea66664, 0x3f800000], - [0x3e3d004c, 0x3e0b4396, 0x3e030e1f, 0x3f800000], - [0x00000000, 0x00000000, 0x00000000, 0x00000000], - [0x3e594eb2, 0x3e6ef420, 0x3e7ffffe, 0x3f800000], - [0x00000000, 0x00000000, 0x00000000, 0x3f000000], - [0x3e6eeeee, 0x3e6eeeee, 0x3e6eeeee, 0x3f800000], - ] - .to_vec(), - ), - ( - Stat::Maximum, - [ - [0x3f666666, 0x3f666666, 0x3f7d70a4, 0x3f800000], - [0x3f666666, 0x3f000000, 0x3f000000, 0x3f800000], - [0x00000000, 0x00000000, 0x00000000, 0x00000000], - [0x40400000, 0x40800000, 0x3fc00000, 0x3f800000], - [0x3f333333, 0x3e4ccccd, 0x3dcccccd, 0x3f000000], - [0x3f000000, 0x3f400000, 0x3f000000, 0x3f800000], - ] - .to_vec(), - ), - ( - Stat::Mean, - [ - [0x3ea3d70a, 0x3efae148, 0x3ee0418a, 0x3f800000], - [0x3ee66666, 0x3e99999a, 0x3ec00000, 0x3f800000], - [0x00000000, 0x00000000, 0x00000000, 0x00000000], - [0x3f19999a, 0x3f800000, 0x3f000000, 0x3f800000], - [0x3f333333, 0x3e4ccccd, 0x3dcccccd, 0x3f000000], - [0x3ea00000, 0x3f200000, 0x3ea00000, 0x3f800000], - ] - .to_vec(), - ), - ( - Stat::Median, - [ - [0x3e4ccccd, 0x3f19999a, 0x3e99999a, 0x3f800000], - [0x3ecccccd, 0x3e99999a, 0x3ecccccd, 0x3f800000], - [0x00000000, 0x00000000, 0x00000000, 0x00000000], - [0x3f000000, 0x3f000000, 0x3f000000, 0x3f800000], - [0x3f333333, 0x3e4ccccd, 0x3dcccccd, 0x3f000000], - [0x3e800000, 0x3f400000, 0x3e800000, 0x3f800000], - ] - .to_vec(), - ), - ( - Stat::Minimum, - [ - [0x3dcccccd, 0x3d4ccccd, 0x3e99999a, 0x3f800000], - [0x3dcccccd, 0x3dcccccd, 0x3e4ccccd, 0x3f800000], - [0x00000000, 0x00000000, 0x00000000, 0x00000000], - [0xc0000000, 0xbf800000, 0x00000000, 0x3f800000], - [0x3f333333, 0x3e4ccccd, 0x3dcccccd, 0x3f000000], - [0x3e800000, 0x3e800000, 0x3e800000, 0x3f800000], - ] - .to_vec(), - ), - ( - Stat::Range, - [ - [0x3f4ccccc, 0x3f599999, 0x3f30a3d7, 0x3f800000], - [0x3f4ccccc, 0x3ecccccd, 0x3e99999a, 0x3f800000], - [0x00000000, 0x00000000, 0x00000000, 0x00000000], - [0x40a00000, 0x40a00000, 0x3fc00000, 0x3f800000], - [0x00000000, 0x00000000, 0x00000000, 0x3f000000], - [0x3e800000, 0x3f000000, 0x3e800000, 0x3f800000], - ] - .to_vec(), - ), - ( - Stat::Skewness, - [ - [0x3f522026, 0x3ee7cf76, 0x3f600000, 0x3f800000], - [0x3f1bd152, 0x3efffffe, 0x3ee4a11b, 0x3f800000], - [0x00000000, 0x00000000, 0x00000000, 0x00000000], - [0x3eedb65a, 0x3f2ea754, 0x3f3a6c7a, 0x3f800000], - [0x3f000000, 0x3f000000, 0x3f000000, 0x3f000000], - [0x3f49e69e, 0x3e58658a, 0x3f49e69e, 0x3f800000], - ] - .to_vec(), - ), - ( - Stat::StandardDeviation, - [ - [0x3e99421e, 0x3ea23b6b, 0x3e8d4fdf, 0x3f800000], - [0x3e97739e, 0x3e21e89b, 0x3e050581, 0x3f800000], - [0x00000000, 0x00000000, 0x00000000, 0x00000000], - [0x3fd3e0b1, 0x3fd9f9e5, 0x3f0c378c, 0x3f800000], - [0x00000000, 0x00000000, 0x00000000, 0x3f000000], - [0x3dddb3d7, 0x3e5db3d7, 0x3dddb3d7, 0x3f800000], - ] - .to_vec(), - ), - ( - Stat::Summation, - [ - [0x3fcccccd, 0x401ccccd, 0x400c28f6, 0x3f800000], - [0x3fe66666, 0x3f99999a, 0x3fc00000, 0x3f800000], - [0x00000000, 0x00000000, 0x00000000, 0x00000000], - [0x40400000, 0x40a00000, 0x40200000, 0x3f800000], - [0x3f333333, 0x3e4ccccd, 0x3dcccccd, 0x3f000000], - [0x3fa00000, 0x40200000, 0x3fa00000, 0x3f800000], - ] - .to_vec(), - ), - ( - Stat::Variance, - [ - [0x3db78033, 0x3dcd9e83, 0x3d9c022a, 0x3f800000], - [0x3db33332, 0x3ccccccd, 0x3c8a3d70, 0x3f800000], - [0x00000000, 0x00000000, 0x00000000, 0x00000000], - [0x402f5c29, 0x4039999a, 0x3e99999a, 0x3f800000], - [0x00000000, 0x00000000, 0x00000000, 0x3f000000], - [0x3c400000, 0x3d400000, 0x3c400000, 0x3f800000], - ] - .to_vec(), - ), - ]; - for (mode, want) in expected { - assert_eq!(bits(&combine(&layers, mode)), want, "{mode:?}"); - } - } - - /// Entropy against values worked out by hand (bits of the 8-bit histogram, over log2(N)). - #[test] - fn entropy_matches_hand_computed_values() { - let out = combine(&fixture(), Stat::Entropy); - let h = |ps: &[f64]| -> f64 { - let n: f64 = ps.iter().sum(); - ps.iter().map(|c| -(c / n) * (c / n).log2()).sum::() / n.log2() - }; - // Pixel 1: four distinct values -> 2 bits / log2(4) = exactly 1. - assert_eq!(out[1][0], 1.0); - // Pixel 2: every sample transparent -> untouched. - assert_eq!(out[2], [0.0; 4]); - // Pixel 3, red: -2 and 0 land in bin 0, 3 and 1.5 clamp into bin 255, 0.5 is alone. - assert!((f64::from(out[3][0]) - h(&[2.0, 2.0, 1.0])).abs() < 1e-6, "{}", out[3][0]); - // Pixel 4: a single contributing sample has no entropy. - assert_eq!(out[4], [0.0, 0.0, 0.0, 0.5]); - // Pixel 5: three samples share a bin, one is alone, in every channel. - for (c, v) in out[5].iter().take(3).enumerate() { - assert!((f64::from(*v) - h(&[3.0, 1.0])).abs() < 1e-6, "channel {c}: {v}"); - } - } - - /// The old HashMap summed in a random order, so Entropy could differ by an ulp between runs. - /// Now the bins are summed in ascending order: repeated runs (and any thread count) agree. - #[test] - fn entropy_is_deterministic() { - let layers: Vec> = (0..7) - .map(|k| { - (0..3 * CHUNK + 17).map(|i| [((i * 7 + k * 13) % 11) as f32 / 10.0, ((i + k) % 5) as f32 / 4.0, ((i * k) % 9) as f32 / 8.0, 1.0]).collect() - }) - .collect(); - let first = bits(&combine(&layers, Stat::Entropy)); - for _ in 0..8 { - assert_eq!(bits(&combine(&layers, Stat::Entropy)), first); - } - } - - /// Chunking is invisible: a multi-chunk image (with a ragged last chunk and layers of unequal - /// length) gives, pixel by pixel, what combining that pixel on its own gives. - #[test] - fn chunked_result_equals_per_pixel_result() { - let len = 2 * CHUNK + 5; - let layer = |k: usize, n: usize| -> Vec<[f32; 4]> { - (0..n) - .map(|i| { - [ - ((i * 31 + k * 7) % 101) as f32 / 100.0, - ((i * 17 + k) % 53) as f32 / 52.0 - 0.2, - ((i + 3 * k) % 29) as f32 / 28.0, - if (i + k).is_multiple_of(4) { 0.0 } else { 0.5 + ((i + k) % 3) as f32 / 4.0 }, - ] - }) - .collect() - }; - let layers = vec![layer(1, len), layer(2, CHUNK + 3), layer(3, len - 1), layer(4, 0), layer(5, len)]; - for mode in [ - Stat::Entropy, - Stat::Kurtosis, - Stat::Maximum, - Stat::Mean, - Stat::Median, - Stat::Minimum, - Stat::Range, - Stat::Skewness, - Stat::StandardDeviation, - Stat::Summation, - Stat::Variance, - ] { - let whole = combine(&layers, mode); - assert_eq!(whole.len(), len); - for i in (0..len).step_by(97).chain([CHUNK - 1, CHUNK, CHUNK + 1, 2 * CHUNK - 1, 2 * CHUNK, len - 1]) { - let one: Vec> = layers.iter().map(|l| l.get(i).map(|p| vec![*p]).unwrap_or_default()).collect(); - assert_eq!(whole[i].map(f32::to_bits), combine(&one, mode)[0].map(f32::to_bits), "{mode:?} pixel {i}"); - } - } - } - - #[test] - fn no_layers_gives_an_empty_result() { - assert!(combine(&[], Stat::Median).is_empty()); - } - - /// [`ipow`] multiplies in the order `x·x²` for the cube and `x²·x²` for the fourth power. - #[test] - fn ipow_squares_and_multiplies() { - for x in [0.58f32, -0.12, -2.6, 2.4, -0.6, 1.0e-3, 0.0] { - assert_eq!(ipow(x, 0).to_bits(), 1.0f32.to_bits()); - assert_eq!(ipow(x, 1).to_bits(), x.to_bits()); - assert_eq!(ipow(x, 2).to_bits(), (x * x).to_bits()); - assert_eq!(ipow(x, 3).to_bits(), (x * (x * x)).to_bits()); - assert_eq!(ipow(x, 4).to_bits(), ((x * x) * (x * x)).to_bits()); - } - } -} +mod tests; diff --git a/crates/algo/src/stack/tests.rs b/crates/algo/src/stack/tests.rs new file mode 100644 index 0000000000..9e14a6be44 --- /dev/null +++ b/crates/algo/src/stack/tests.rs @@ -0,0 +1,301 @@ +use super::*; + +fn px(v: f32) -> Vec<[f32; 4]> { + vec![[v, v, v, 1.0]] +} + +#[test] +fn basic_statistics() { + let layers = vec![px(0.1), px(0.9), px(0.2), px(0.3), px(0.1)]; + let at = |s| combine(&layers, s)[0][0]; + assert!((at(Stat::Mean) - 0.32).abs() < 1e-6); + assert!((at(Stat::Median) - 0.2).abs() < 1e-6); + assert_eq!(at(Stat::Minimum), 0.1); + assert_eq!(at(Stat::Maximum), 0.9); + assert!((at(Stat::Range) - 0.8).abs() < 1e-6); + assert!((at(Stat::Summation) - 1.6).abs() < 1e-6); + let var = at(Stat::Variance); + assert!((at(Stat::StandardDeviation) - var.sqrt()).abs() < 1e-6); + assert!(at(Stat::Skewness) > 0.5, "right-skewed"); + assert!(at(Stat::Entropy) > 0.0 && at(Stat::Entropy) <= 1.0); + assert!(at(Stat::Kurtosis) > 0.0); +} + +#[test] +fn statistics_preserve_hdr_and_signed_samples() { + let layers = vec![px(-2.0), px(4.0)]; + for (mode, expected) in [ + (Stat::Mean, 1.0), + (Stat::Median, 1.0), + (Stat::Minimum, -2.0), + (Stat::Maximum, 4.0), + (Stat::Range, 6.0), + (Stat::Summation, 2.0), + (Stat::Variance, 9.0), + (Stat::StandardDeviation, 3.0), + ] { + assert_eq!(combine(&layers, mode)[0], [expected, expected, expected, 1.0], "{mode:?}"); + } + for mode in [Stat::Mean, Stat::Median] { + assert_eq!(combine(&[px(2.0), px(4.0)], mode)[0], [3.0, 3.0, 3.0, 1.0]); + assert_eq!(combine(&[px(-2.0), px(-4.0)], mode)[0], [-3.0, -3.0, -3.0, 1.0]); + } + // These display-oriented statistics still apply their own normalisation. + for mode in [Stat::Entropy, Stat::Skewness, Stat::Kurtosis] { + assert!((0.0..=1.0).contains(&combine(&layers, mode)[0][0]), "{mode:?}"); + } +} + +#[test] +fn transparent_samples_are_ignored() { + let layers = vec![vec![[0.5, 0.5, 0.5, 1.0]], vec![[1.0, 1.0, 1.0, 0.0]]]; + assert_eq!(combine(&layers, Stat::Mean)[0], [0.5, 0.5, 0.5, 1.0]); + let empty = vec![vec![[1.0, 1.0, 1.0, 0.0]]]; + assert_eq!(combine(&empty, Stat::Mean)[0][3], 0.0); +} + +#[test] +fn median_removes_outlier() { + let layers = vec![px(0.5), px(0.5), px(1.0)]; + assert_eq!(combine(&layers, Stat::Median)[0][0], 0.5); +} + +/// Five layers over six pixels (the last layer is short). Covers opaque, partly transparent, +/// fully transparent, HDR / negative, single-sample and tied-value pixels. +fn fixture() -> Vec> { + vec![ + vec![[0.10, 0.20, 0.30, 1.0], [0.5, 0.5, 0.5, 1.0], [0.9, 0.9, 0.9, 0.0], [-2.0, 4.0, 0.0, 1.0], [0.7, 0.2, 0.1, 0.5], [0.25, 0.25, 0.25, 1.0]], + vec![[0.90, 0.60, 0.30, 1.0], [0.0, 0.0, 0.0, 0.0], [0.8, 0.8, 0.8, 0.0], [3.0, -1.0, 0.5, 0.75], [0.0, 0.0, 0.0, 0.0], [0.25, 0.75, 0.25, 1.0]], + vec![[0.20, 0.90, 0.30, 0.5], [0.1, 0.2, 0.3, 1.0], [0.7, 0.7, 0.7, 0.0], [0.5, 0.5, 0.5, 1.0], [0.0, 0.0, 0.0, 0.0], [0.5, 0.75, 0.25, 0.25]], + vec![[0.30, 0.05, 0.30, 0.25], [0.3, 0.4, 0.5, 0.5], [0.6, 0.6, 0.6, 0.0], [1.5, 1.5, 1.5, 1.0], [0.0, 0.0, 0.0, 0.0], [0.25, 0.75, 0.5, 1.0]], + vec![[0.10, 0.70, 0.99, 1.0], [0.9, 0.1, 0.2, 1.0], [0.5, 0.5, 0.5, 0.0], [0.0, 0.0, 0.0, 1.0]], + ] +} + +fn bits(px: &[[f32; 4]]) -> Vec<[u32; 4]> { + px.iter().map(|p| p.map(f32::to_bits)).collect() +} + +/// Every mode except Entropy is bit-for-bit what the old serial loop produced. The expected +/// bit patterns were recorded by running the unmodified `combine` on [`fixture`]. +#[test] +fn statistics_are_bit_identical_to_the_serial_implementation() { + let layers = fixture(); + let expected: Vec<(Stat, Vec<[u32; 4]>)> = vec![ + ( + Stat::Kurtosis, + [ + [0x3e96956b, 0x3e182e3f, 0x3ea66664, 0x3f800000], + [0x3e3d004c, 0x3e0b4396, 0x3e030e1f, 0x3f800000], + [0x00000000, 0x00000000, 0x00000000, 0x00000000], + [0x3e594eb2, 0x3e6ef420, 0x3e7ffffe, 0x3f800000], + [0x00000000, 0x00000000, 0x00000000, 0x3f000000], + [0x3e6eeeee, 0x3e6eeeee, 0x3e6eeeee, 0x3f800000], + ] + .to_vec(), + ), + ( + Stat::Maximum, + [ + [0x3f666666, 0x3f666666, 0x3f7d70a4, 0x3f800000], + [0x3f666666, 0x3f000000, 0x3f000000, 0x3f800000], + [0x00000000, 0x00000000, 0x00000000, 0x00000000], + [0x40400000, 0x40800000, 0x3fc00000, 0x3f800000], + [0x3f333333, 0x3e4ccccd, 0x3dcccccd, 0x3f000000], + [0x3f000000, 0x3f400000, 0x3f000000, 0x3f800000], + ] + .to_vec(), + ), + ( + Stat::Mean, + [ + [0x3ea3d70a, 0x3efae148, 0x3ee0418a, 0x3f800000], + [0x3ee66666, 0x3e99999a, 0x3ec00000, 0x3f800000], + [0x00000000, 0x00000000, 0x00000000, 0x00000000], + [0x3f19999a, 0x3f800000, 0x3f000000, 0x3f800000], + [0x3f333333, 0x3e4ccccd, 0x3dcccccd, 0x3f000000], + [0x3ea00000, 0x3f200000, 0x3ea00000, 0x3f800000], + ] + .to_vec(), + ), + ( + Stat::Median, + [ + [0x3e4ccccd, 0x3f19999a, 0x3e99999a, 0x3f800000], + [0x3ecccccd, 0x3e99999a, 0x3ecccccd, 0x3f800000], + [0x00000000, 0x00000000, 0x00000000, 0x00000000], + [0x3f000000, 0x3f000000, 0x3f000000, 0x3f800000], + [0x3f333333, 0x3e4ccccd, 0x3dcccccd, 0x3f000000], + [0x3e800000, 0x3f400000, 0x3e800000, 0x3f800000], + ] + .to_vec(), + ), + ( + Stat::Minimum, + [ + [0x3dcccccd, 0x3d4ccccd, 0x3e99999a, 0x3f800000], + [0x3dcccccd, 0x3dcccccd, 0x3e4ccccd, 0x3f800000], + [0x00000000, 0x00000000, 0x00000000, 0x00000000], + [0xc0000000, 0xbf800000, 0x00000000, 0x3f800000], + [0x3f333333, 0x3e4ccccd, 0x3dcccccd, 0x3f000000], + [0x3e800000, 0x3e800000, 0x3e800000, 0x3f800000], + ] + .to_vec(), + ), + ( + Stat::Range, + [ + [0x3f4ccccc, 0x3f599999, 0x3f30a3d7, 0x3f800000], + [0x3f4ccccc, 0x3ecccccd, 0x3e99999a, 0x3f800000], + [0x00000000, 0x00000000, 0x00000000, 0x00000000], + [0x40a00000, 0x40a00000, 0x3fc00000, 0x3f800000], + [0x00000000, 0x00000000, 0x00000000, 0x3f000000], + [0x3e800000, 0x3f000000, 0x3e800000, 0x3f800000], + ] + .to_vec(), + ), + ( + Stat::Skewness, + [ + [0x3f522026, 0x3ee7cf76, 0x3f600000, 0x3f800000], + [0x3f1bd152, 0x3efffffe, 0x3ee4a11b, 0x3f800000], + [0x00000000, 0x00000000, 0x00000000, 0x00000000], + [0x3eedb65a, 0x3f2ea754, 0x3f3a6c7a, 0x3f800000], + [0x3f000000, 0x3f000000, 0x3f000000, 0x3f000000], + [0x3f49e69e, 0x3e58658a, 0x3f49e69e, 0x3f800000], + ] + .to_vec(), + ), + ( + Stat::StandardDeviation, + [ + [0x3e99421e, 0x3ea23b6b, 0x3e8d4fdf, 0x3f800000], + [0x3e97739e, 0x3e21e89b, 0x3e050581, 0x3f800000], + [0x00000000, 0x00000000, 0x00000000, 0x00000000], + [0x3fd3e0b1, 0x3fd9f9e5, 0x3f0c378c, 0x3f800000], + [0x00000000, 0x00000000, 0x00000000, 0x3f000000], + [0x3dddb3d7, 0x3e5db3d7, 0x3dddb3d7, 0x3f800000], + ] + .to_vec(), + ), + ( + Stat::Summation, + [ + [0x3fcccccd, 0x401ccccd, 0x400c28f6, 0x3f800000], + [0x3fe66666, 0x3f99999a, 0x3fc00000, 0x3f800000], + [0x00000000, 0x00000000, 0x00000000, 0x00000000], + [0x40400000, 0x40a00000, 0x40200000, 0x3f800000], + [0x3f333333, 0x3e4ccccd, 0x3dcccccd, 0x3f000000], + [0x3fa00000, 0x40200000, 0x3fa00000, 0x3f800000], + ] + .to_vec(), + ), + ( + Stat::Variance, + [ + [0x3db78033, 0x3dcd9e83, 0x3d9c022a, 0x3f800000], + [0x3db33332, 0x3ccccccd, 0x3c8a3d70, 0x3f800000], + [0x00000000, 0x00000000, 0x00000000, 0x00000000], + [0x402f5c29, 0x4039999a, 0x3e99999a, 0x3f800000], + [0x00000000, 0x00000000, 0x00000000, 0x3f000000], + [0x3c400000, 0x3d400000, 0x3c400000, 0x3f800000], + ] + .to_vec(), + ), + ]; + for (mode, want) in expected { + assert_eq!(bits(&combine(&layers, mode)), want, "{mode:?}"); + } +} + +/// Entropy against values worked out by hand (bits of the 8-bit histogram, over log2(N)). +#[test] +fn entropy_matches_hand_computed_values() { + let out = combine(&fixture(), Stat::Entropy); + let h = |ps: &[f64]| -> f64 { + let n: f64 = ps.iter().sum(); + ps.iter().map(|c| -(c / n) * (c / n).log2()).sum::() / n.log2() + }; + // Pixel 1: four distinct values -> 2 bits / log2(4) = exactly 1. + assert_eq!(out[1][0], 1.0); + // Pixel 2: every sample transparent -> untouched. + assert_eq!(out[2], [0.0; 4]); + // Pixel 3, red: -2 and 0 land in bin 0, 3 and 1.5 clamp into bin 255, 0.5 is alone. + assert!((f64::from(out[3][0]) - h(&[2.0, 2.0, 1.0])).abs() < 1e-6, "{}", out[3][0]); + // Pixel 4: a single contributing sample has no entropy. + assert_eq!(out[4], [0.0, 0.0, 0.0, 0.5]); + // Pixel 5: three samples share a bin, one is alone, in every channel. + for (c, v) in out[5].iter().take(3).enumerate() { + assert!((f64::from(*v) - h(&[3.0, 1.0])).abs() < 1e-6, "channel {c}: {v}"); + } +} + +/// The old HashMap summed in a random order, so Entropy could differ by an ulp between runs. +/// Now the bins are summed in ascending order: repeated runs (and any thread count) agree. +#[test] +fn entropy_is_deterministic() { + let layers: Vec> = (0..7) + .map(|k| (0..3 * CHUNK + 17).map(|i| [((i * 7 + k * 13) % 11) as f32 / 10.0, ((i + k) % 5) as f32 / 4.0, ((i * k) % 9) as f32 / 8.0, 1.0]).collect()) + .collect(); + let first = bits(&combine(&layers, Stat::Entropy)); + for _ in 0..8 { + assert_eq!(bits(&combine(&layers, Stat::Entropy)), first); + } +} + +/// Chunking is invisible: a multi-chunk image (with a ragged last chunk and layers of unequal +/// length) gives, pixel by pixel, what combining that pixel on its own gives. +#[test] +fn chunked_result_equals_per_pixel_result() { + let len = 2 * CHUNK + 5; + let layer = |k: usize, n: usize| -> Vec<[f32; 4]> { + (0..n) + .map(|i| { + [ + ((i * 31 + k * 7) % 101) as f32 / 100.0, + ((i * 17 + k) % 53) as f32 / 52.0 - 0.2, + ((i + 3 * k) % 29) as f32 / 28.0, + if (i + k).is_multiple_of(4) { 0.0 } else { 0.5 + ((i + k) % 3) as f32 / 4.0 }, + ] + }) + .collect() + }; + let layers = vec![layer(1, len), layer(2, CHUNK + 3), layer(3, len - 1), layer(4, 0), layer(5, len)]; + for mode in [ + Stat::Entropy, + Stat::Kurtosis, + Stat::Maximum, + Stat::Mean, + Stat::Median, + Stat::Minimum, + Stat::Range, + Stat::Skewness, + Stat::StandardDeviation, + Stat::Summation, + Stat::Variance, + ] { + let whole = combine(&layers, mode); + assert_eq!(whole.len(), len); + for i in (0..len).step_by(97).chain([CHUNK - 1, CHUNK, CHUNK + 1, 2 * CHUNK - 1, 2 * CHUNK, len - 1]) { + let one: Vec> = layers.iter().map(|l| l.get(i).map(|p| vec![*p]).unwrap_or_default()).collect(); + assert_eq!(whole[i].map(f32::to_bits), combine(&one, mode)[0].map(f32::to_bits), "{mode:?} pixel {i}"); + } + } +} + +#[test] +fn no_layers_gives_an_empty_result() { + assert!(combine(&[], Stat::Median).is_empty()); +} + +/// [`ipow`] multiplies in the order `x·x²` for the cube and `x²·x²` for the fourth power. +#[test] +fn ipow_squares_and_multiplies() { + for x in [0.58f32, -0.12, -2.6, 2.4, -0.6, 1.0e-3, 0.0] { + assert_eq!(ipow(x, 0).to_bits(), 1.0f32.to_bits()); + assert_eq!(ipow(x, 1).to_bits(), x.to_bits()); + assert_eq!(ipow(x, 2).to_bits(), (x * x).to_bits()); + assert_eq!(ipow(x, 3).to_bits(), (x * (x * x)).to_bits()); + assert_eq!(ipow(x, 4).to_bits(), ((x * x) * (x * x)).to_bits()); + } +} diff --git a/crates/algo/src/tests.rs b/crates/algo/src/tests.rs index 6d7e879346..57b7428330 100644 --- a/crates/algo/src/tests.rs +++ b/crates/algo/src/tests.rs @@ -1,5 +1,8 @@ use super::*; use photocraft_color::{PixelFormat, SampleType}; +mod ext; +mod mosaic; +mod selection_mix; fn fmt(s: SampleType) -> PixelFormat { PixelFormat::new(ColorMode::Rgb, s, true) diff --git a/crates/algo/src/tests_ext.rs b/crates/algo/src/tests/ext.rs similarity index 100% rename from crates/algo/src/tests_ext.rs rename to crates/algo/src/tests/ext.rs diff --git a/crates/algo/src/tests_mosaic.rs b/crates/algo/src/tests/mosaic.rs similarity index 100% rename from crates/algo/src/tests_mosaic.rs rename to crates/algo/src/tests/mosaic.rs diff --git a/crates/algo/src/tests_selection_mix.rs b/crates/algo/src/tests/selection_mix.rs similarity index 100% rename from crates/algo/src/tests_selection_mix.rs rename to crates/algo/src/tests/selection_mix.rs diff --git a/crates/algo/src/transform.rs b/crates/algo/src/transform.rs index 3edd0a1879..1ed0ec7c04 100644 --- a/crates/algo/src/transform.rs +++ b/crates/algo/src/transform.rs @@ -551,353 +551,4 @@ fn warp( } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn output_size_prices_the_unclipped_extent_independently_of_position() { - let src = Rect::new(0, 0, 24, 16); - for dx in [0.0, 900_000.0, 10_000_000.0] { - let h = Homography([1.0, 0.0, dx, 0.0, 1.0, -dx, 0.0, 0.0, 1.0]); - assert_eq!(warp_output_size(src, &h), Some((26, 18))); - } - for sx in [1e7, -1e7] { - let h = Homography([sx, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]); - assert_eq!(warp_output_size(src, &h), Some((240_000_002, 18))); - } - } - - /// The unclipped size matches the clipped bounds where nothing is clipped, saturates when it - /// can't be represented, and is `None` for empty or singular inputs. - #[test] - fn output_size_saturates_overflows_and_preserves_filter_support() { - let src = Rect::new(0, 0, 24, 16); - let fractional = Homography([0.5, 0.0, 0.25, 0.0, 1.0, 0.75, 0.0, 0.0, 1.0]); - let bounds = warp_output_bounds(src, &fractional).unwrap(); - assert_eq!(warp_output_size(src, &fractional), Some((u64::from(bounds.width()), u64::from(bounds.height())))); - let huge = Homography([1e308, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]); - assert_eq!(warp_output_size(src, &huge), Some((u64::MAX, u64::MAX))); - assert_eq!(warp_output_size(Rect::EMPTY, &Homography::IDENTITY), None); - assert_eq!(warp_output_size(src, &Homography([0.0; 9])), None); - } - - /// [`warp_output_clipped`] says yes exactly when [`warp_output_bounds`] clamps a side (#7807). - #[test] - fn output_clipped_matches_the_clamped_bounds() { - let src = Rect::new(0, 0, 24, 16); - let at = |dx: f64| Homography([1.0, 0.0, dx, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]); - let edge = f64::from(WARP_REACH) - 24.0; - assert!(!warp_output_clipped(src, &at(edge)), "the right edge lands on the reach"); - assert_eq!(warp_output_bounds(src, &at(edge)).map(|b| b.x1), Some(WARP_REACH + 1)); - assert!(warp_output_clipped(src, &at(edge + 1.0)), "one pixel past it"); - assert_eq!(warp_output_bounds(src, &at(edge + 1.0)).map(|b| b.x1), Some(WARP_REACH + 1), "clamped"); - assert!(warp_output_clipped(src, &at(-f64::from(WARP_REACH) - 1.0))); - assert!(!warp_output_clipped(Rect::EMPTY, &at(1e12)), "nothing to clip"); - } - - #[test] - fn the_interruptible_warp_reports_progress_and_stops_when_cancelled() { - let mut s = Surface::new(PixelFormat::RGBA8); - s.fill_rect(Rect::new(0, 0, 600, 400), &[0.2, 0.4, 0.6, 1.0]); - let r = s.content_bounds(); - let h = Homography::rect_to_quad([0.0, 0.0, 600.0, 400.0], [[10.0, 0.0], [590.0, 20.0], [600.0, 400.0], [0.0, 380.0]]).unwrap(); - let reported = std::sync::Mutex::new(0.0f32); - let progress = |p: f32| { - let mut m = reported.lock().unwrap(); - *m = m.max(p); - }; - let never = || false; - let out = warp_surface_with(&s, r, &h, Interp::Bicubic, &Interrupt::new(&never, &progress)).unwrap().expect("not cancelled"); - assert_eq!(out.read_region(r), warp_surface(&s, r, &h, Interp::Bicubic).unwrap().read_region(r)); - assert!(*reported.lock().unwrap() > 0.9); - let always = || true; - assert!(warp_surface_with(&s, r, &h, Interp::Bicubic, &Interrupt::cancel_only(&always)).unwrap().is_none()); - } - - /// Perspective Crop's map lands each quad corner exactly on its rectangle corner; degenerate, - /// self-crossing, counter-clockwise and non-finite quads have none. - #[test] - fn quad_to_rect_maps_corners_and_refuses_bad_quads() { - let q = [[30.0, 12.0], [140.0, 25.0], [128.0, 110.0], [14.0, 95.0]]; - let h = quad_to_rect(&q, 100.0, 80.0).unwrap(); - for (c, want) in q.iter().zip([[0.0, 0.0], [100.0, 0.0], [100.0, 80.0], [0.0, 80.0]]) { - let (x, y) = h.apply(c[0], c[1]); - assert!((x - want[0]).abs() < 1e-9 && (y - want[1]).abs() < 1e-9, "{c:?} -> ({x}, {y})"); - } - let (w, ht) = quad_size(&q); - assert!((w - 112.874).abs() < 1e-3 && (ht - 85.185).abs() < 1e-3, "{w} x {ht}"); - for bad in [ - [[0.0, 0.0], [50.0, 0.0], [100.0, 0.0], [0.0, 50.0]], - [[0.0, 0.0], [50.0, 50.0], [50.0, 0.0], [0.0, 50.0]], - [[0.0, 0.0], [0.0, 50.0], [50.0, 50.0], [50.0, 0.0]], - [[0.0, 0.0], [f64::NAN, 0.0], [50.0, 50.0], [0.0, 50.0]], - [[0.0, 0.0]; 4], - ] { - assert!(quad_to_rect(&bad, 10.0, 10.0).is_none(), "{bad:?}"); - } - assert!(quad_to_rect(&q, 0.0, 10.0).is_none()); - } - - fn rgba() -> Surface { - Surface::new(PixelFormat::RGBA8) - } - - /// The "pixel stretch" (#3773): a 1 px column scaled 100x stays solid across the stretch, as in - /// Photoshop. Samples past the source edge repeat the edge, and only the outline is antialiased. - #[test] - fn stretched_single_column_stays_opaque() { - let mut s = rgba(); - s.fill_rect(Rect::new(0, 0, 1, 4), &[0.0, 1.0, 0.0, 1.0]); - for interp in [Interp::Bicubic, Interp::Bilinear] { - let h = Homography::rect_to_quad([0.0, 0.0, 1.0, 4.0], [[0.0, 0.0], [100.0, 0.0], [100.0, 4.0], [0.0, 4.0]]).unwrap(); - let w = warp_surface(&s, Rect::new(0, 0, 1, 4), &h, interp).unwrap(); - assert_eq!(w.content_bounds(), Rect::new(0, 0, 100, 4), "{interp:?}"); - for x in [0, 1, 25, 50, 75, 99] { - for y in 0..4 { - assert!((w.sample_channel(x, y, 3) - 1.0).abs() < 1e-6, "{interp:?} alpha at ({x}, {y}) = {}", w.sample_channel(x, y, 3)); - } - } - } - } - - /// Photoshop 27.11's Free Transform, Bicubic, 200 % about the centre of a 64 px image whose left - /// half is grey 64 and right half grey 192: the row across the edge, columns 26..36. - #[test] - fn bicubic_upscale_matches_photoshop() { - let mut src = rgba(); - let g = |v: f32| v / 255.0; - src.fill_rect(Rect::new(0, 0, 32, 64), &[g(64.0), g(64.0), g(64.0), 1.0]); - src.fill_rect(Rect::new(32, 0, 64, 64), &[g(192.0), g(192.0), g(192.0), 1.0]); - let q = [[-32.0, -32.0], [96.0, -32.0], [96.0, 96.0], [-32.0, 96.0]]; - let h = Homography::rect_to_quad([0.0, 0.0, 64.0, 64.0], q).unwrap(); - let out = warp_surface(&src, Rect::new(0, 0, 64, 64), &h, Interp::Bicubic).unwrap(); - let photoshop = [64.0, 64.0, 64.0, 60.0, 51.0, 93.0, 163.0, 206.0, 197.0, 192.0]; - for (i, want) in photoshop.iter().enumerate() { - let got = out.pixel(26 + i as i32, 50)[0] * 255.0; - assert!((got - want).abs() <= 1.5, "column {}: {got} vs {want}", 26 + i); - } - } - - #[test] - fn homography_maps_rect_corners_and_inverts() { - let r = [10.0, 20.0, 110.0, 70.0]; - let q = [[0.0, 0.0], [200.0, 10.0], [180.0, 150.0], [-20.0, 120.0]]; - let h = Homography::rect_to_quad(r, q).unwrap(); - for (p, e) in [(10.0, 20.0), (110.0, 20.0), (110.0, 70.0), (10.0, 70.0)].iter().zip(q) { - let (x, y) = h.apply(p.0, p.1); - assert!((x - e[0]).abs() < 1e-9 && (y - e[1]).abs() < 1e-9, "{p:?} → {x},{y} vs {e:?}"); - } - let inv = h.inverse().unwrap(); - let (x, y) = inv.apply(90.0, 60.0); - let (bx, by) = h.apply(x, y); - assert!((bx - 90.0).abs() < 1e-9 && (by - 60.0).abs() < 1e-9); - assert!(Homography::rect_to_quad(r, [[0.0, 0.0]; 4]).is_none() || Homography::rect_to_quad(r, [[0.0, 0.0]; 4]).unwrap().inverse().is_none()); - } - - #[test] - fn steep_distort_keeps_every_pixel_inside_the_quad() { - // Corner C is almost flat, so the horizon of the inverse map crosses the 256-px tiles that - // also hold quad pixels; those tiles must still read every source pixel that lands in them. - let mut s = rgba(); - s.fill_rect(Rect::new(0, 0, 100, 100), &[1.0, 0.0, 0.0, 1.0]); - let r = s.content_bounds(); - let h = Homography::rect_to_quad([0.0, 0.0, 100.0, 100.0], [[0.0, 0.0], [300.0, 0.0], [155.0, 155.0], [0.0, 300.0]]).unwrap(); - let w = warp_surface(&s, r, &h, Interp::Nearest).unwrap(); - for (x, y) in [(20, 20), (252, 14), (252, 42), (14, 252), (42, 252)] { - let a = w.read_region(Rect::new(x, y, x + 1, y + 1))[3]; - assert!(a > 0.99, "({x},{y}) inside the quad is transparent: {a}"); - } - for (x, y) in [(200, 200), (280, 100), (100, 280)] { - assert_eq!(w.read_region(Rect::new(x, y, x + 1, y + 1))[3], 0.0, "({x},{y}) outside the quad is painted"); - } - } - - /// #4863: a Distort with the bottom corners pulled in and one dragged past the horizon (a - /// concave quad) leaves part of the source behind the horizon. That part maps to the far side, - /// where it showed as a mirrored copy wrapped round infinity; only the front side is drawn. - #[test] - fn a_distort_past_the_horizon_draws_only_its_front_side() { - let mut s = rgba(); - s.fill_rect(Rect::new(0, 0, 100, 100), &[0.0, 0.5, 1.0, 1.0]); - let r = s.content_bounds(); - let h = Homography::rect_to_quad([0.0, 0.0, 100.0, 100.0], [[0.0, 0.0], [300.0, 0.0], [60.0, 60.0], [0.0, 300.0]]).unwrap(); - let corners = [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)].map(|(x, y)| h.w(x, y)); - assert!(corners.iter().any(|w| *w > 0.0) && corners.iter().any(|w| *w < 0.0), "the source straddles the horizon: {corners:?}"); - let front = h.front_side([0.0, 0.0, 100.0, 100.0]); - let inv = h.inverse().unwrap(); - let clip = Rect::new(-400, -400, 700, 700); - for interp in [Interp::Nearest, Interp::Bilinear] { - let w = warp_surface_clipped(&s, r, &h, interp, clip).unwrap(); - let px = w.read_region(clip); - let (mut drawn, mut behind) = (0, 0); - for y in clip.y0..clip.y1 { - for x in clip.x0..clip.x1 { - let i = ((y - clip.y0) * clip.width() as i32 + (x - clip.x0)) as usize * 4; - if px[i + 3] > 0.0 { - drawn += 1; - // The source point this pixel samples is on the far side of the horizon. - if front * inv.w(x as f64 + 0.5, y as f64 + 0.5) <= 0.0 { - behind += 1; - } - } - } - } - assert!(drawn > 1000, "{interp:?}: the front side is drawn ({drawn} px)"); - assert_eq!(behind, 0, "{interp:?}: {behind} pixels come from behind the horizon"); - } - // A quad wholly in front of the horizon is drawn exactly as before. - let ok = Homography::rect_to_quad([0.0, 0.0, 100.0, 100.0], [[0.0, 0.0], [300.0, 0.0], [155.0, 155.0], [0.0, 300.0]]).unwrap(); - assert_eq!(ok.front_side([0.0, 0.0, 100.0, 100.0]), ok.w(50.0, 50.0).signum()); - } - - /// #7557: a Perspective Crop quad low on a strongly converging photo puts the horizon across - /// the layer with most of it (and its centre) on the far side. The clip maps wholly into the - /// quad, so its side is the one drawn, not the source's majority. - #[test] - fn a_clip_wholly_on_one_side_draws_that_side() { - let mut s = rgba(); - s.fill_rect(Rect::new(0, 0, 100, 100), &[1.0, 0.0, 0.0, 1.0]); - let q = [[40.0, 70.0], [60.0, 70.0], [90.0, 95.0], [10.0, 95.0]]; - let h = quad_to_rect(&q, 50.0, 39.0).unwrap(); - assert!(h.front_side([0.0, 0.0, 100.0, 100.0]) * h.w(50.0, 80.0) < 0.0, "the source's majority is behind the quad's side"); - for interp in [Interp::Nearest, Interp::Bilinear, Interp::Bicubic] { - let w = warp_surface_clipped(&s, s.content_bounds(), &h, interp, Rect::new(0, 0, 50, 39)).unwrap(); - assert_eq!(w.rgba(25, 20), [1.0, 0.0, 0.0, 1.0], "{interp:?}"); - } - } - - #[test] - fn identity_and_translation_are_exact() { - let mut s = rgba(); - s.fill_rect(Rect::new(4, 4, 20, 12), &[1.0, 0.5, 0.0, 1.0]); - let r = s.content_bounds(); - for interp in [Interp::Nearest, Interp::Bilinear, Interp::Bicubic] { - let h = Homography([1.0, 0.0, 7.0, 0.0, 1.0, -3.0, 0.0, 0.0, 1.0]); - let o = warp_surface(&s, r, &h, interp).unwrap(); - assert_eq!(o.content_bounds(), Rect::new(11, 1, 27, 9), "{interp:?}"); - assert_eq!(o.pixel(15, 5), vec![1.0, 128.0 / 255.0, 0.0, 1.0], "{interp:?}"); - } - } - - #[test] - fn translation_preserves_colour_range_at_every_depth() { - use photocraft_color::{ColorMode, SampleType}; - - let h = Homography([1.0, 0.0, 7.0, 0.0, 1.0, -3.0, 0.0, 0.0, 1.0]); - for sample in SampleType::ALL { - for mode in [ColorMode::Rgb, ColorMode::Grayscale] { - for alpha in [false, true] { - let mut s = Surface::new(PixelFormat::new(mode, sample, alpha)); - let mut pixel = if mode == ColorMode::Rgb { vec![2.0, -0.25, 0.5] } else { vec![2.0] }; - if alpha { - pixel.push(0.5); - } - s.fill_rect(Rect::new(4, 4, 8, 8), &pixel); - let mut expected = s.pixel(5, 5); - if !alpha { - expected.push(1.0); - } - for interp in [Interp::Nearest, Interp::Bilinear, Interp::Bicubic] { - let out = warp_surface(&s, s.content_bounds(), &h, interp).unwrap(); - assert_eq!(out.pixel(12, 2), expected, "{sample:?}/{mode:?}/alpha={alpha}/{interp:?}"); - assert_eq!(out.pixel(0, 0).last(), Some(&0.0)); - } - } - } - } - } - - #[test] - fn bilinear_translation_interpolates_signed_hdr_colours() { - let mut s = Surface::new(PixelFormat::RGBA32F); - s.write_pixel(0, 0, &[2.0, -0.5, 0.25, 0.5]); - s.write_pixel(1, 0, &[4.0, -0.25, 0.75, 0.5]); - let h = Homography([1.0, 0.0, 0.5, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]); - let out = warp_surface(&s, s.content_bounds(), &h, Interp::Bilinear).unwrap(); - assert_eq!(out.pixel(1, 0), vec![3.0, -0.375, 0.5, 0.5]); - } - - #[test] - fn scale_doubles_size_and_rotation_keeps_area() { - let mut s = rgba(); - s.fill_rect(Rect::new(0, 0, 40, 20), &[0.2, 0.4, 0.6, 1.0]); - let r = s.content_bounds(); - let up = warp_surface( - &s, - r, - &Homography::rect_to_quad([0.0, 0.0, 40.0, 20.0], [[0.0, 0.0], [80.0, 0.0], [80.0, 40.0], [0.0, 40.0]]).unwrap(), - Interp::Bicubic, - ) - .unwrap(); - let b = up.content_bounds(); - assert!(b.width() >= 80 && b.width() <= 82 && b.height() >= 40 && b.height() <= 42, "{b:?}"); - // 90° rotation about (20, 10): a 40×20 box becomes 20×40. - let q = [[30.0, -10.0], [30.0, 30.0], [10.0, 30.0], [10.0, -10.0]]; - let rot = warp_surface(&s, r, &Homography::rect_to_quad([0.0, 0.0, 40.0, 20.0], q).unwrap(), Interp::Bilinear).unwrap(); - let b = rot.content_bounds(); - assert!(b.width().abs_diff(20) <= 2 && b.height().abs_diff(40) <= 2, "{b:?}"); - let p = rot.pixel(20, 10); - assert!((p[0] - 0.2).abs() < 0.01 && p[3] > 0.99, "{p:?}"); - } - - /// #6203: a bicubic rotation of a sprite whose edge pixels are partly transparent overshoots - /// its alpha past 1. The colour must stay the sprite's, not grow with the overshoot into a - /// light border. - #[test] - fn rotation_keeps_the_colour_of_a_soft_edged_sprite() { - let mut s = rgba(); - s.fill_rect(Rect::new(10, 10, 30, 30), &[0.8, 0.6, 0.4, 0.5]); - s.fill_rect(Rect::new(11, 11, 29, 29), &[0.8, 0.6, 0.4, 1.0]); - let (c, k) = (20.0, std::f64::consts::FRAC_1_SQRT_2 * 10.0); - let q = [[c, c - 2.0 * k], [c + 2.0 * k, c], [c, c + 2.0 * k], [c - 2.0 * k, c]]; - let h = Homography::rect_to_quad([10.0, 10.0, 30.0, 30.0], q).unwrap(); - for interp in [Interp::Bicubic, Interp::Bilinear] { - let out = warp_surface(&s, s.content_bounds(), &h, interp).unwrap(); - let b = out.content_bounds(); - for y in b.y0..b.y1 { - for x in b.x0..b.x1 { - let p = out.pixel(x, y); - if p[3] > 0.0 { - let off = (0..3).map(|i| (p[i] - [0.8, 0.6, 0.4][i]).abs()).fold(0.0f32, f32::max); - assert!(off <= 1.0 / 255.0, "{interp:?} ({x}, {y}): {p:?}"); - } - } - } - } - } - - #[test] - fn large_downscale_is_prefiltered() { - // A 1px checkerboard shrunk 8× must come out ~50% grey, not aliased black/white. - let mut s = rgba(); - for y in 0..64 { - for x in 0..64 { - let v = ((x + y) % 2) as f32; - s.fill_rect(Rect::new(x, y, x + 1, y + 1), &[v, v, v, 1.0]); - } - } - let h = Homography::rect_to_quad([0.0, 0.0, 64.0, 64.0], [[0.0, 0.0], [8.0, 0.0], [8.0, 8.0], [0.0, 8.0]]).unwrap(); - let o = warp_surface(&s, s.content_bounds(), &h, Interp::Bicubic).unwrap(); - let p = o.pixel(4, 4); - assert!((p[0] - 0.5).abs() < 0.1, "{p:?}"); - } - - #[test] - fn surfaces_without_alpha_gain_it() { - let mut s = Surface::new(PixelFormat::new(photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::U8, false)); - s.fill_rect(Rect::new(0, 0, 10, 10), &[1.0, 0.0, 0.0]); - let h = Homography([1.0, 0.0, 5.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]); - let o = warp_surface(&s, Rect::new(0, 0, 10, 10), &h, Interp::Nearest).unwrap(); - assert!(o.format().alpha); - assert_eq!(o.pixel(2, 2)[3], 0.0); - assert_eq!(o.pixel(7, 2), vec![1.0, 0.0, 0.0, 1.0]); - } - - #[test] - fn homography_is_identity() { - assert!(Homography::IDENTITY.is_identity()); - assert!(Homography([2.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 2.0]).is_identity()); - assert!(!Homography([1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]).is_identity()); - assert!(!Homography([1.0, 0.1, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]).is_identity()); - } -} +mod tests; diff --git a/crates/algo/src/transform/tests.rs b/crates/algo/src/transform/tests.rs new file mode 100644 index 0000000000..b70bc74c3d --- /dev/null +++ b/crates/algo/src/transform/tests.rs @@ -0,0 +1,344 @@ +use super::*; + +#[test] +fn output_size_prices_the_unclipped_extent_independently_of_position() { + let src = Rect::new(0, 0, 24, 16); + for dx in [0.0, 900_000.0, 10_000_000.0] { + let h = Homography([1.0, 0.0, dx, 0.0, 1.0, -dx, 0.0, 0.0, 1.0]); + assert_eq!(warp_output_size(src, &h), Some((26, 18))); + } + for sx in [1e7, -1e7] { + let h = Homography([sx, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]); + assert_eq!(warp_output_size(src, &h), Some((240_000_002, 18))); + } +} + +/// The unclipped size matches the clipped bounds where nothing is clipped, saturates when it +/// can't be represented, and is `None` for empty or singular inputs. +#[test] +fn output_size_saturates_overflows_and_preserves_filter_support() { + let src = Rect::new(0, 0, 24, 16); + let fractional = Homography([0.5, 0.0, 0.25, 0.0, 1.0, 0.75, 0.0, 0.0, 1.0]); + let bounds = warp_output_bounds(src, &fractional).unwrap(); + assert_eq!(warp_output_size(src, &fractional), Some((u64::from(bounds.width()), u64::from(bounds.height())))); + let huge = Homography([1e308, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]); + assert_eq!(warp_output_size(src, &huge), Some((u64::MAX, u64::MAX))); + assert_eq!(warp_output_size(Rect::EMPTY, &Homography::IDENTITY), None); + assert_eq!(warp_output_size(src, &Homography([0.0; 9])), None); +} + +/// [`warp_output_clipped`] says yes exactly when [`warp_output_bounds`] clamps a side (#7807). +#[test] +fn output_clipped_matches_the_clamped_bounds() { + let src = Rect::new(0, 0, 24, 16); + let at = |dx: f64| Homography([1.0, 0.0, dx, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]); + let edge = f64::from(WARP_REACH) - 24.0; + assert!(!warp_output_clipped(src, &at(edge)), "the right edge lands on the reach"); + assert_eq!(warp_output_bounds(src, &at(edge)).map(|b| b.x1), Some(WARP_REACH + 1)); + assert!(warp_output_clipped(src, &at(edge + 1.0)), "one pixel past it"); + assert_eq!(warp_output_bounds(src, &at(edge + 1.0)).map(|b| b.x1), Some(WARP_REACH + 1), "clamped"); + assert!(warp_output_clipped(src, &at(-f64::from(WARP_REACH) - 1.0))); + assert!(!warp_output_clipped(Rect::EMPTY, &at(1e12)), "nothing to clip"); +} + +#[test] +fn the_interruptible_warp_reports_progress_and_stops_when_cancelled() { + let mut s = Surface::new(PixelFormat::RGBA8); + s.fill_rect(Rect::new(0, 0, 600, 400), &[0.2, 0.4, 0.6, 1.0]); + let r = s.content_bounds(); + let h = Homography::rect_to_quad([0.0, 0.0, 600.0, 400.0], [[10.0, 0.0], [590.0, 20.0], [600.0, 400.0], [0.0, 380.0]]).unwrap(); + let reported = std::sync::Mutex::new(0.0f32); + let progress = |p: f32| { + let mut m = reported.lock().unwrap(); + *m = m.max(p); + }; + let never = || false; + let out = warp_surface_with(&s, r, &h, Interp::Bicubic, &Interrupt::new(&never, &progress)).unwrap().expect("not cancelled"); + assert_eq!(out.read_region(r), warp_surface(&s, r, &h, Interp::Bicubic).unwrap().read_region(r)); + assert!(*reported.lock().unwrap() > 0.9); + let always = || true; + assert!(warp_surface_with(&s, r, &h, Interp::Bicubic, &Interrupt::cancel_only(&always)).unwrap().is_none()); +} + +/// Perspective Crop's map lands each quad corner exactly on its rectangle corner; degenerate, +/// self-crossing, counter-clockwise and non-finite quads have none. +#[test] +fn quad_to_rect_maps_corners_and_refuses_bad_quads() { + let q = [[30.0, 12.0], [140.0, 25.0], [128.0, 110.0], [14.0, 95.0]]; + let h = quad_to_rect(&q, 100.0, 80.0).unwrap(); + for (c, want) in q.iter().zip([[0.0, 0.0], [100.0, 0.0], [100.0, 80.0], [0.0, 80.0]]) { + let (x, y) = h.apply(c[0], c[1]); + assert!((x - want[0]).abs() < 1e-9 && (y - want[1]).abs() < 1e-9, "{c:?} -> ({x}, {y})"); + } + let (w, ht) = quad_size(&q); + assert!((w - 112.874).abs() < 1e-3 && (ht - 85.185).abs() < 1e-3, "{w} x {ht}"); + for bad in [ + [[0.0, 0.0], [50.0, 0.0], [100.0, 0.0], [0.0, 50.0]], + [[0.0, 0.0], [50.0, 50.0], [50.0, 0.0], [0.0, 50.0]], + [[0.0, 0.0], [0.0, 50.0], [50.0, 50.0], [50.0, 0.0]], + [[0.0, 0.0], [f64::NAN, 0.0], [50.0, 50.0], [0.0, 50.0]], + [[0.0, 0.0]; 4], + ] { + assert!(quad_to_rect(&bad, 10.0, 10.0).is_none(), "{bad:?}"); + } + assert!(quad_to_rect(&q, 0.0, 10.0).is_none()); +} + +fn rgba() -> Surface { + Surface::new(PixelFormat::RGBA8) +} + +/// The "pixel stretch" (#3773): a 1 px column scaled 100x stays solid across the stretch, as in +/// Photoshop. Samples past the source edge repeat the edge, and only the outline is antialiased. +#[test] +fn stretched_single_column_stays_opaque() { + let mut s = rgba(); + s.fill_rect(Rect::new(0, 0, 1, 4), &[0.0, 1.0, 0.0, 1.0]); + for interp in [Interp::Bicubic, Interp::Bilinear] { + let h = Homography::rect_to_quad([0.0, 0.0, 1.0, 4.0], [[0.0, 0.0], [100.0, 0.0], [100.0, 4.0], [0.0, 4.0]]).unwrap(); + let w = warp_surface(&s, Rect::new(0, 0, 1, 4), &h, interp).unwrap(); + assert_eq!(w.content_bounds(), Rect::new(0, 0, 100, 4), "{interp:?}"); + for x in [0, 1, 25, 50, 75, 99] { + for y in 0..4 { + assert!((w.sample_channel(x, y, 3) - 1.0).abs() < 1e-6, "{interp:?} alpha at ({x}, {y}) = {}", w.sample_channel(x, y, 3)); + } + } + } +} + +/// Photoshop 27.11's Free Transform, Bicubic, 200 % about the centre of a 64 px image whose left +/// half is grey 64 and right half grey 192: the row across the edge, columns 26..36. +#[test] +fn bicubic_upscale_matches_photoshop() { + let mut src = rgba(); + let g = |v: f32| v / 255.0; + src.fill_rect(Rect::new(0, 0, 32, 64), &[g(64.0), g(64.0), g(64.0), 1.0]); + src.fill_rect(Rect::new(32, 0, 64, 64), &[g(192.0), g(192.0), g(192.0), 1.0]); + let q = [[-32.0, -32.0], [96.0, -32.0], [96.0, 96.0], [-32.0, 96.0]]; + let h = Homography::rect_to_quad([0.0, 0.0, 64.0, 64.0], q).unwrap(); + let out = warp_surface(&src, Rect::new(0, 0, 64, 64), &h, Interp::Bicubic).unwrap(); + let photoshop = [64.0, 64.0, 64.0, 60.0, 51.0, 93.0, 163.0, 206.0, 197.0, 192.0]; + for (i, want) in photoshop.iter().enumerate() { + let got = out.pixel(26 + i as i32, 50)[0] * 255.0; + assert!((got - want).abs() <= 1.5, "column {}: {got} vs {want}", 26 + i); + } +} + +#[test] +fn homography_maps_rect_corners_and_inverts() { + let r = [10.0, 20.0, 110.0, 70.0]; + let q = [[0.0, 0.0], [200.0, 10.0], [180.0, 150.0], [-20.0, 120.0]]; + let h = Homography::rect_to_quad(r, q).unwrap(); + for (p, e) in [(10.0, 20.0), (110.0, 20.0), (110.0, 70.0), (10.0, 70.0)].iter().zip(q) { + let (x, y) = h.apply(p.0, p.1); + assert!((x - e[0]).abs() < 1e-9 && (y - e[1]).abs() < 1e-9, "{p:?} → {x},{y} vs {e:?}"); + } + let inv = h.inverse().unwrap(); + let (x, y) = inv.apply(90.0, 60.0); + let (bx, by) = h.apply(x, y); + assert!((bx - 90.0).abs() < 1e-9 && (by - 60.0).abs() < 1e-9); + assert!(Homography::rect_to_quad(r, [[0.0, 0.0]; 4]).is_none() || Homography::rect_to_quad(r, [[0.0, 0.0]; 4]).unwrap().inverse().is_none()); +} + +#[test] +fn steep_distort_keeps_every_pixel_inside_the_quad() { + // Corner C is almost flat, so the horizon of the inverse map crosses the 256-px tiles that + // also hold quad pixels; those tiles must still read every source pixel that lands in them. + let mut s = rgba(); + s.fill_rect(Rect::new(0, 0, 100, 100), &[1.0, 0.0, 0.0, 1.0]); + let r = s.content_bounds(); + let h = Homography::rect_to_quad([0.0, 0.0, 100.0, 100.0], [[0.0, 0.0], [300.0, 0.0], [155.0, 155.0], [0.0, 300.0]]).unwrap(); + let w = warp_surface(&s, r, &h, Interp::Nearest).unwrap(); + for (x, y) in [(20, 20), (252, 14), (252, 42), (14, 252), (42, 252)] { + let a = w.read_region(Rect::new(x, y, x + 1, y + 1))[3]; + assert!(a > 0.99, "({x},{y}) inside the quad is transparent: {a}"); + } + for (x, y) in [(200, 200), (280, 100), (100, 280)] { + assert_eq!(w.read_region(Rect::new(x, y, x + 1, y + 1))[3], 0.0, "({x},{y}) outside the quad is painted"); + } +} + +/// #4863: a Distort with the bottom corners pulled in and one dragged past the horizon (a +/// concave quad) leaves part of the source behind the horizon. That part maps to the far side, +/// where it showed as a mirrored copy wrapped round infinity; only the front side is drawn. +#[test] +fn a_distort_past_the_horizon_draws_only_its_front_side() { + let mut s = rgba(); + s.fill_rect(Rect::new(0, 0, 100, 100), &[0.0, 0.5, 1.0, 1.0]); + let r = s.content_bounds(); + let h = Homography::rect_to_quad([0.0, 0.0, 100.0, 100.0], [[0.0, 0.0], [300.0, 0.0], [60.0, 60.0], [0.0, 300.0]]).unwrap(); + let corners = [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)].map(|(x, y)| h.w(x, y)); + assert!(corners.iter().any(|w| *w > 0.0) && corners.iter().any(|w| *w < 0.0), "the source straddles the horizon: {corners:?}"); + let front = h.front_side([0.0, 0.0, 100.0, 100.0]); + let inv = h.inverse().unwrap(); + let clip = Rect::new(-400, -400, 700, 700); + for interp in [Interp::Nearest, Interp::Bilinear] { + let w = warp_surface_clipped(&s, r, &h, interp, clip).unwrap(); + let px = w.read_region(clip); + let (mut drawn, mut behind) = (0, 0); + for y in clip.y0..clip.y1 { + for x in clip.x0..clip.x1 { + let i = ((y - clip.y0) * clip.width() as i32 + (x - clip.x0)) as usize * 4; + if px[i + 3] > 0.0 { + drawn += 1; + // The source point this pixel samples is on the far side of the horizon. + if front * inv.w(x as f64 + 0.5, y as f64 + 0.5) <= 0.0 { + behind += 1; + } + } + } + } + assert!(drawn > 1000, "{interp:?}: the front side is drawn ({drawn} px)"); + assert_eq!(behind, 0, "{interp:?}: {behind} pixels come from behind the horizon"); + } + // A quad wholly in front of the horizon is drawn exactly as before. + let ok = Homography::rect_to_quad([0.0, 0.0, 100.0, 100.0], [[0.0, 0.0], [300.0, 0.0], [155.0, 155.0], [0.0, 300.0]]).unwrap(); + assert_eq!(ok.front_side([0.0, 0.0, 100.0, 100.0]), ok.w(50.0, 50.0).signum()); +} + +/// #7557: a Perspective Crop quad low on a strongly converging photo puts the horizon across +/// the layer with most of it (and its centre) on the far side. The clip maps wholly into the +/// quad, so its side is the one drawn, not the source's majority. +#[test] +fn a_clip_wholly_on_one_side_draws_that_side() { + let mut s = rgba(); + s.fill_rect(Rect::new(0, 0, 100, 100), &[1.0, 0.0, 0.0, 1.0]); + let q = [[40.0, 70.0], [60.0, 70.0], [90.0, 95.0], [10.0, 95.0]]; + let h = quad_to_rect(&q, 50.0, 39.0).unwrap(); + assert!(h.front_side([0.0, 0.0, 100.0, 100.0]) * h.w(50.0, 80.0) < 0.0, "the source's majority is behind the quad's side"); + for interp in [Interp::Nearest, Interp::Bilinear, Interp::Bicubic] { + let w = warp_surface_clipped(&s, s.content_bounds(), &h, interp, Rect::new(0, 0, 50, 39)).unwrap(); + assert_eq!(w.rgba(25, 20), [1.0, 0.0, 0.0, 1.0], "{interp:?}"); + } +} + +#[test] +fn identity_and_translation_are_exact() { + let mut s = rgba(); + s.fill_rect(Rect::new(4, 4, 20, 12), &[1.0, 0.5, 0.0, 1.0]); + let r = s.content_bounds(); + for interp in [Interp::Nearest, Interp::Bilinear, Interp::Bicubic] { + let h = Homography([1.0, 0.0, 7.0, 0.0, 1.0, -3.0, 0.0, 0.0, 1.0]); + let o = warp_surface(&s, r, &h, interp).unwrap(); + assert_eq!(o.content_bounds(), Rect::new(11, 1, 27, 9), "{interp:?}"); + assert_eq!(o.pixel(15, 5), vec![1.0, 128.0 / 255.0, 0.0, 1.0], "{interp:?}"); + } +} + +#[test] +fn translation_preserves_colour_range_at_every_depth() { + use photocraft_color::{ColorMode, SampleType}; + + let h = Homography([1.0, 0.0, 7.0, 0.0, 1.0, -3.0, 0.0, 0.0, 1.0]); + for sample in SampleType::ALL { + for mode in [ColorMode::Rgb, ColorMode::Grayscale] { + for alpha in [false, true] { + let mut s = Surface::new(PixelFormat::new(mode, sample, alpha)); + let mut pixel = if mode == ColorMode::Rgb { vec![2.0, -0.25, 0.5] } else { vec![2.0] }; + if alpha { + pixel.push(0.5); + } + s.fill_rect(Rect::new(4, 4, 8, 8), &pixel); + let mut expected = s.pixel(5, 5); + if !alpha { + expected.push(1.0); + } + for interp in [Interp::Nearest, Interp::Bilinear, Interp::Bicubic] { + let out = warp_surface(&s, s.content_bounds(), &h, interp).unwrap(); + assert_eq!(out.pixel(12, 2), expected, "{sample:?}/{mode:?}/alpha={alpha}/{interp:?}"); + assert_eq!(out.pixel(0, 0).last(), Some(&0.0)); + } + } + } + } +} + +#[test] +fn bilinear_translation_interpolates_signed_hdr_colours() { + let mut s = Surface::new(PixelFormat::RGBA32F); + s.write_pixel(0, 0, &[2.0, -0.5, 0.25, 0.5]); + s.write_pixel(1, 0, &[4.0, -0.25, 0.75, 0.5]); + let h = Homography([1.0, 0.0, 0.5, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]); + let out = warp_surface(&s, s.content_bounds(), &h, Interp::Bilinear).unwrap(); + assert_eq!(out.pixel(1, 0), vec![3.0, -0.375, 0.5, 0.5]); +} + +#[test] +fn scale_doubles_size_and_rotation_keeps_area() { + let mut s = rgba(); + s.fill_rect(Rect::new(0, 0, 40, 20), &[0.2, 0.4, 0.6, 1.0]); + let r = s.content_bounds(); + let up = + warp_surface(&s, r, &Homography::rect_to_quad([0.0, 0.0, 40.0, 20.0], [[0.0, 0.0], [80.0, 0.0], [80.0, 40.0], [0.0, 40.0]]).unwrap(), Interp::Bicubic) + .unwrap(); + let b = up.content_bounds(); + assert!(b.width() >= 80 && b.width() <= 82 && b.height() >= 40 && b.height() <= 42, "{b:?}"); + // 90° rotation about (20, 10): a 40×20 box becomes 20×40. + let q = [[30.0, -10.0], [30.0, 30.0], [10.0, 30.0], [10.0, -10.0]]; + let rot = warp_surface(&s, r, &Homography::rect_to_quad([0.0, 0.0, 40.0, 20.0], q).unwrap(), Interp::Bilinear).unwrap(); + let b = rot.content_bounds(); + assert!(b.width().abs_diff(20) <= 2 && b.height().abs_diff(40) <= 2, "{b:?}"); + let p = rot.pixel(20, 10); + assert!((p[0] - 0.2).abs() < 0.01 && p[3] > 0.99, "{p:?}"); +} + +/// #6203: a bicubic rotation of a sprite whose edge pixels are partly transparent overshoots +/// its alpha past 1. The colour must stay the sprite's, not grow with the overshoot into a +/// light border. +#[test] +fn rotation_keeps_the_colour_of_a_soft_edged_sprite() { + let mut s = rgba(); + s.fill_rect(Rect::new(10, 10, 30, 30), &[0.8, 0.6, 0.4, 0.5]); + s.fill_rect(Rect::new(11, 11, 29, 29), &[0.8, 0.6, 0.4, 1.0]); + let (c, k) = (20.0, std::f64::consts::FRAC_1_SQRT_2 * 10.0); + let q = [[c, c - 2.0 * k], [c + 2.0 * k, c], [c, c + 2.0 * k], [c - 2.0 * k, c]]; + let h = Homography::rect_to_quad([10.0, 10.0, 30.0, 30.0], q).unwrap(); + for interp in [Interp::Bicubic, Interp::Bilinear] { + let out = warp_surface(&s, s.content_bounds(), &h, interp).unwrap(); + let b = out.content_bounds(); + for y in b.y0..b.y1 { + for x in b.x0..b.x1 { + let p = out.pixel(x, y); + if p[3] > 0.0 { + let off = (0..3).map(|i| (p[i] - [0.8, 0.6, 0.4][i]).abs()).fold(0.0f32, f32::max); + assert!(off <= 1.0 / 255.0, "{interp:?} ({x}, {y}): {p:?}"); + } + } + } + } +} + +#[test] +fn large_downscale_is_prefiltered() { + // A 1px checkerboard shrunk 8× must come out ~50% grey, not aliased black/white. + let mut s = rgba(); + for y in 0..64 { + for x in 0..64 { + let v = ((x + y) % 2) as f32; + s.fill_rect(Rect::new(x, y, x + 1, y + 1), &[v, v, v, 1.0]); + } + } + let h = Homography::rect_to_quad([0.0, 0.0, 64.0, 64.0], [[0.0, 0.0], [8.0, 0.0], [8.0, 8.0], [0.0, 8.0]]).unwrap(); + let o = warp_surface(&s, s.content_bounds(), &h, Interp::Bicubic).unwrap(); + let p = o.pixel(4, 4); + assert!((p[0] - 0.5).abs() < 0.1, "{p:?}"); +} + +#[test] +fn surfaces_without_alpha_gain_it() { + let mut s = Surface::new(PixelFormat::new(photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::U8, false)); + s.fill_rect(Rect::new(0, 0, 10, 10), &[1.0, 0.0, 0.0]); + let h = Homography([1.0, 0.0, 5.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]); + let o = warp_surface(&s, Rect::new(0, 0, 10, 10), &h, Interp::Nearest).unwrap(); + assert!(o.format().alpha); + assert_eq!(o.pixel(2, 2)[3], 0.0); + assert_eq!(o.pixel(7, 2), vec![1.0, 0.0, 0.0, 1.0]); +} + +#[test] +fn homography_is_identity() { + assert!(Homography::IDENTITY.is_identity()); + assert!(Homography([2.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 2.0]).is_identity()); + assert!(!Homography([1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]).is_identity()); + assert!(!Homography([1.0, 0.1, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]).is_identity()); +} diff --git a/crates/automation/src/rpc.rs b/crates/automation/src/rpc.rs index b98094eb5d..98ccc9a24a 100644 --- a/crates/automation/src/rpc.rs +++ b/crates/automation/src/rpc.rs @@ -391,982 +391,4 @@ fn serve_tcp_until_idle( } #[cfg(test)] -mod tests { - use super::*; - - fn session() -> Mutex { - Mutex::new(Headless::trusted_local()) - } - - #[test] - fn document_activation_reply_survives_engine_rpc() { - let h = session(); - let mut g = h.lock().unwrap(); - for _ in 0..2 { - g.handle("engine.execute", json!({"command": "file.new", "params": {"width": 4, "height": 4}})).unwrap(); - } - let reply = g.handle("engine.execute", json!({"command": "document.activate", "params": {"offset": -1}})).unwrap(); - assert_eq!(reply, json!({"document": 0})); - let reply = g.handle("engine.execute", json!({"command": "document.activate", "params": {"document": 1}})).unwrap(); - assert_eq!(reply, json!({"document": 1})); - } - - #[test] - fn execute_reports_invalid_filter_parameters_without_changing_history() { - let h = session(); - assert_eq!(respond(&h, r#"{"method":"doc.new","params":{"width":8,"height":8}}"#)["ok"], true); - let before = h.lock().unwrap().inspect(None).unwrap(); - for (params, key) in - [(json!({"radius":"big"}), "radius"), (json!({"radus":3}), "radus"), (json!({"radius":5000}), "radius"), (json!({"radius":-4}), "radius")] - { - for wait in [true, false] { - let request = json!({"method":"engine.execute","params":{"command":"filter.blur.gaussianBlur","params":params,"wait":wait}}); - let reply = respond(&h, &request.to_string()); - assert_eq!(reply["ok"], false); - let error = reply["error"].as_str().unwrap(); - assert!(error.contains("filter.blur.gaussianBlur") && error.contains(key), "{error}"); - assert_eq!(h.lock().unwrap().inspect(None).unwrap(), before); - } - } - } - - /// Pins the reply shape documented in docs/control-protocol.md › Command list replies - /// (#3684): a bare JSON array (not `{"commands": [...]}`), one object per command with - /// exactly these keys (plus an optional `keywords` string), from `engine.commands` (filtered or not) and `command.list`. - #[test] - fn command_list_replies_are_documented_array_of_objects() { - let h = session(); - let mut g = h.lock().unwrap(); - let all = g.handle("engine.commands", json!({})).unwrap(); - let filtered = g.handle("engine.commands", json!({"filter": "BLUR"})).unwrap(); - let engine = g.handle("engine.execute", json!({"command": "command.list"})).unwrap(); - for (name, reply) in [("engine.commands", &all), ("engine.commands {filter}", &filtered), ("command.list", &engine)] { - let items = reply.as_array().unwrap_or_else(|| panic!("{name} must reply with a bare array, got {reply}")); - assert!(!items.is_empty(), "{name}"); - for c in items { - // `keywords` is optional: only commands with other search names carry it (#5060). - let mut keys: Vec<&str> = c.as_object().unwrap().keys().map(String::as_str).filter(|k| *k != "keywords").collect(); - keys.sort_unstable(); - assert!(c.get("keywords").is_none_or(Value::is_string), "{name}: {c}"); - assert_eq!(keys, ["disabledReason", "enabled", "id", "label", "menu", "needsDocument", "params", "shortcut"], "{name}: {c}"); - assert!(c["id"].is_string() && c["label"].is_string() && c["params"].is_string() && c["enabled"].is_boolean(), "{c}"); - assert!(c["needsDocument"].is_boolean(), "{c}"); - assert_eq!(c["disabledReason"].is_null(), c["enabled"] == true, "disabledReason is null exactly when enabled: {c}"); - assert!(c["menu"].as_array().unwrap().iter().all(Value::is_string), "{c}"); - assert!(c["shortcut"].is_string() || c["shortcut"].is_null(), "{c}"); - } - } - let n_all = all.as_array().unwrap().len(); - assert_eq!(engine.as_array().unwrap().len(), n_all); - let filtered = filtered.as_array().unwrap(); - assert!(filtered.len() < n_all); - assert!(filtered.iter().all(|c| format!("{} {}", c["id"], c["label"]).to_lowercase().contains("blur"))); - let new = all.as_array().unwrap().iter().find(|c| c["id"] == "file.new").unwrap(); - assert_eq!((&new["menu"], &new["shortcut"], &new["enabled"]), (&json!(["File"]), &json!("Cmd+N"), &json!(true)), "{new}"); - assert_eq!((&new["disabledReason"], &new["needsDocument"]), (&Value::Null, &json!(false)), "{new}"); - } - - #[test] - fn lines_round_trip_and_errors() { - let h = session(); - let input = concat!( - r#"{"id":1,"method":"doc.new","params":{"width":64,"height":32,"background":"white"}}"#, - "\n", - "\n", - r#"{"id":2,"method":"engine.execute","params":{"command":"layer.new.layer","params":{"name":"Ink"}}}"#, - "\n", - r#"{"id":3,"method":"doc.inspect"}"#, - "\n", - r#"{"id":4,"method":"nope"}"#, - "\n", - "not json\n", - ); - let mut out = Vec::new(); - serve_lines(&h, input.as_bytes(), &mut out).unwrap(); - let replies: Vec = String::from_utf8(out).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect(); - assert_eq!(replies.len(), 5); - assert!(replies[0]["ok"].as_bool().unwrap()); - assert_eq!(replies[1]["id"], 2); - assert!(replies[2]["result"].to_string().contains("Ink")); - assert!(!replies[3]["ok"].as_bool().unwrap()); - assert!(replies[3]["error"].as_str().unwrap().contains("unknown method")); - assert_eq!(replies[4]["id"], Value::Null); - } - - /// Regression: after a panic while the session lock was held, every later request - /// failed with "session lock poisoned"; the server now keeps serving. - #[test] - fn poisoned_session_keeps_serving() { - let h = session(); - let _ = std::thread::scope(|sc| { - sc.spawn(|| { - let _g = h.lock().unwrap(); - panic!("poison the session lock"); - }) - .join() - }); - assert!(h.is_poisoned()); - let r = respond(&h, r#"{"id":1,"method":"doc.new","params":{"width":8,"height":8}}"#); - assert_eq!(r["ok"], true, "{r}"); - } - - #[test] - fn batch_stops_on_error_unless_told_not_to() { - let h = session(); - let mut g = h.lock().unwrap(); - g.handle("doc.new", json!({"width": 16, "height": 16})).unwrap(); - let steps = json!([ - {"command": "layer.new.layer", "params": {"name": "A"}}, - {"command": "no.such.command"}, - {"command": "layer.new.layer", "params": {"name": "B"}}, - {"method": "doc.inspect"} - ]); - let r = g.handle("batch", json!({"steps": steps})).unwrap(); - assert_eq!(r["completed"], 1); - assert_eq!(r["failed"], 1); - assert_eq!(r["results"].as_array().unwrap().len(), 2); - let r = g.handle("batch", json!({"steps": steps, "stopOnError": false})).unwrap(); - assert_eq!(r["completed"], 3); - let insp = &r["results"][3]["result"]; - assert!(insp.to_string().contains("\"B\"")); - } - - #[test] - fn batch_rejects_too_many_steps() { - let h = session(); - let mut g = h.lock().unwrap(); - let steps = vec![json!({"command": "command.list"}); MAX_BATCH_STEPS + 1]; - let error = g.handle("batch", json!({"steps": steps})).unwrap_err(); - assert!(error.to_string().contains("maximum is 256")); - } - - #[test] - fn render_to_file_and_base64() { - let h = session(); - let mut g = h.lock().unwrap(); - g.handle("doc.new", json!({"width": 40, "height": 20, "background": "black"})).unwrap(); - let b = g.handle("doc.render", json!({"maxSide": 10})).unwrap(); - let png = base64::engine::general_purpose::STANDARD.decode(b["base64"].as_str().unwrap()).unwrap(); - let img = photocraft_codecs::decode(&png).unwrap(); - assert_eq!(img.dimensions(), (10, 5)); - let path = std::env::temp_dir().join(format!("pc-rpc-{}.png", std::process::id())); - let r = g.handle("doc.render", json!({"path": path.to_string_lossy(), "maxSide": 0})).unwrap(); - assert!(r["bytes"].as_u64().unwrap() > 0); - assert_eq!(photocraft_codecs::decode(&std::fs::read(&path).unwrap()).unwrap().dimensions(), (40, 20)); - let _ = std::fs::remove_file(path); - } - - #[test] - fn background_jobs_list_wait_and_cancel() { - let mut h = Headless::new(); - h.handle("doc.new", json!({"width": 600, "height": 400})).unwrap(); - h.handle("engine.execute", json!({"command": "layer.new.layer"})).unwrap(); - h.handle("engine.execute", json!({"command": "edit.fill", "params": {"color": "#808080"}})).unwrap(); - // Default: waits, the result is the command's. - let r = h.handle("engine.execute", json!({"command": "filter.noise.addNoise", "params": {"amount": 20}})).unwrap(); - assert!(r["filter"].is_object(), "{r}"); - // wait: false returns a job id at once. - let r = h.handle("engine.execute", json!({"command": "filter.blur.gaussianBlur", "params": {"radius": 40}, "wait": false})).unwrap(); - let job = r["job"].as_u64().unwrap(); - let listed = h.handle("jobs.list", json!({})).unwrap(); - assert!(listed["jobs"].as_array().unwrap().iter().any(|j| j["id"] == job), "{listed}"); - // Wait for it via jobs.list (which applies finished jobs). - let t = std::time::Instant::now(); - loop { - let l = h.handle("jobs.list", json!({})).unwrap(); - let state = l["jobs"].as_array().unwrap().iter().find(|j| j["id"] == job).map(|j| j["state"].clone()); - if state == Some(json!("done")) { - break; - } - assert!(t.elapsed().as_secs() < 60, "{l}"); - std::thread::sleep(std::time::Duration::from_millis(5)); - } - // Cancel: a second job, cancelled at once, leaves the document unchanged. - let before = h.session.active().unwrap().doc.clone(); - let r = h.handle("engine.execute", json!({"command": "filter.blur.gaussianBlur", "params": {"radius": 40}, "wait": false})).unwrap(); - let job = r["job"].as_u64().unwrap(); - h.handle("jobs.cancel", json!({"job": job})).unwrap(); - assert!(h.handle("jobs.cancel", json!({"job": "nope"})).is_err()); - let l = h.handle("jobs.list", json!({})).unwrap(); - assert_eq!(l["jobs"].as_array().unwrap().iter().find(|j| j["id"] == job).unwrap()["state"], "cancelled"); - assert!(std::sync::Arc::ptr_eq(&h.session.active().unwrap().doc, &before)); - } - - #[test] - fn batch_steps_can_start_background_jobs() { - let mut h = Headless::new(); - h.handle("doc.new", json!({"width": 600, "height": 400})).unwrap(); - let steps = json!([ - {"command": "layer.new.layer"}, - {"command": "edit.fill", "params": {"color": "#808080"}}, - {"command": "filter.blur.gaussianBlur", "params": {"radius": 40}, "wait": false} - ]); - let r = h.handle("batch", json!({"steps": steps})).unwrap(); - assert_eq!(r["completed"], 3, "{r}"); - let job = r["results"][2]["result"]["job"].as_u64().unwrap_or_else(|| panic!("no job id: {r}")); - assert_eq!(r["results"][2]["result"]["pending"], true); - let listed = h.handle("jobs.list", json!({})).unwrap(); - assert!(listed["jobs"].as_array().unwrap().iter().any(|j| j["id"] == job), "{listed}"); - let t = std::time::Instant::now(); - while h.session.jobs().iter().any(|j| j.id.0 == job) { - assert!(t.elapsed().as_secs() < 60); - std::thread::sleep(std::time::Duration::from_millis(5)); - h.handle("jobs.list", json!({})).unwrap(); - } - } - - /// Regression (#503): a finished `wait: false` job was only applied by a later command or - /// `jobs.list`, so save, inspect, render and `session.list` still saw the document without it. - #[test] - fn every_request_sees_a_finished_background_job() { - let dir = std::env::temp_dir().join(format!("pc-rpc-job-sync-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let (before, after) = (dir.join("before.png"), dir.join("after.png")); - let mut h = Headless::trusted_local(); - h.handle("doc.new", json!({"width": 64, "height": 48})).unwrap(); - h.handle("engine.execute", json!({"command": "filter.noise.addNoise", "params": {"amount": 50}})).unwrap(); - h.handle("doc.save", json!({"path": before.to_string_lossy()})).unwrap(); - let render = |h: &mut Headless| h.handle("doc.render", json!({"maxSide": 0})).unwrap()["base64"].clone(); - let unblurred = render(&mut h); - let revision = |h: &mut Headless| h.handle("session.list", json!({})).unwrap()["documents"][0]["revision"].clone(); - let start = revision(&mut h); - h.handle("engine.execute", json!({"command": "filter.blur.gaussianBlur", "params": {"radius": 4}, "wait": false})).unwrap(); - // Only reading requests from here on: no command and no `jobs.list`. - let t = std::time::Instant::now(); - while revision(&mut h) == start { - assert!(t.elapsed().as_secs() < 60, "session.list never saw the finished job"); - std::thread::sleep(std::time::Duration::from_millis(5)); - } - let history = h.handle("doc.inspect", json!({})).unwrap()["history"].clone(); - assert_eq!(history.as_array().unwrap().last().unwrap(), "Gaussian Blur", "{history}"); - h.handle("doc.save", json!({"path": after.to_string_lossy()})).unwrap(); - let decode = |p: &std::path::Path| photocraft_codecs::decode(&std::fs::read(p).unwrap()).unwrap().to_rgba8(); - assert_ne!(decode(&before), decode(&after), "the export holds the blur"); - assert_ne!(render(&mut h), unblurred, "the preview holds the blur"); - std::fs::remove_dir_all(dir).unwrap(); - } - - /// Regression: `quality` 85.0 or "85" was ignored (a lossless WebP, reply ok) and 0 or 500 was - /// clamped, where the CLI refuses anything but a whole number from 1 to 100. - #[test] - fn doc_save_rejects_a_bad_quality_instead_of_ignoring_or_clamping_it() { - let dir = std::env::temp_dir().join(format!("pc-rpc-save-quality-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let path = dir.join("x.webp"); - let mut h = Headless::trusted_local(); - h.handle("doc.new", json!({"width": 16, "height": 16})).unwrap(); - for q in [json!(85.0), json!("85"), json!(0), json!(500), json!(-5), json!(true)] { - let err = h.handle("doc.save", json!({"path": path.to_string_lossy(), "quality": q})).unwrap_err().to_string(); - assert!(err.contains("quality"), "{q}: {err}"); - assert!(!path.exists(), "{q} wrote a file"); - } - h.handle("doc.save", json!({"path": path.to_string_lossy(), "quality": 85})).unwrap(); - let bytes = std::fs::read(&path).unwrap(); - assert_eq!(bytes.get(12..16), Some(&b"VP8 "[..]), "a WebP saved with a quality is lossy"); - std::fs::remove_dir_all(dir).unwrap(); - } - - #[test] - fn automation_preview_rejects_oversized_full_size_and_numeric_wraparound() { - let mut h = Headless::new(); - h.handle("doc.new", json!({"width": 2049, "height": 1})).unwrap(); - for max in [json!(0), json!(2049), json!(u64::from(u32::MAX) + 1), json!(-1), json!(1.5)] { - assert!(h.handle("doc.render", json!({"maxSide": max})).is_err()); - } - // A smaller preview still works, and rejection leaves the source document intact. - let rendered = h.handle("doc.render", json!({"maxSide": 32})).unwrap(); - let png = base64::engine::general_purpose::STANDARD.decode(rendered["base64"].as_str().unwrap()).unwrap(); - assert_eq!(photocraft_codecs::decode(&png).unwrap().dimensions(), (32, 1)); - assert_eq!(h.session.active().unwrap().doc.size.width, 2049); - } - - #[test] - fn stdio_rejects_oversized_frames_before_dispatch() { - let h = Mutex::new(Headless::new()); - let input = " ".repeat(MAX_REQUEST_BYTES + 1); - let mut out = Vec::new(); - serve_lines(&h, input.as_bytes(), &mut out).unwrap(); - let reply: Value = serde_json::from_slice(&out).unwrap(); - assert_eq!(reply["ok"], false); - assert!(reply["error"].as_str().unwrap().contains("request exceeds")); - assert!(h.lock().unwrap().session.documents().is_empty()); - } - - /// Regression (#505): an over-long or non-UTF-8 line ended the stdio session, losing every - /// open document. Now it gets one error reply, the rest of the line is skipped (never - /// dispatched), and the next request is served. - #[test] - fn stdio_skips_a_rejected_line_and_keeps_the_session() { - let h = Mutex::new(Headless::new()); - let mut input = b"{\"id\":1,\"method\":\"doc.new\",\"params\":{\"width\":8,\"height\":8}}\n".to_vec(); - input.extend(" ".repeat(MAX_REQUEST_BYTES + 1).into_bytes()); - input.extend(b"{\"id\":9,\"method\":\"doc.close\"}\n"); - input.extend(b"\xff\xfe{\"id\":8,\"method\":\"doc.close\"}\n"); - input.extend(b"{\"id\":2,\"method\":\"session.list\"}\n"); - let mut out = Vec::new(); - serve_lines(&h, input.as_slice(), &mut out).unwrap(); - let replies: Vec = String::from_utf8(out).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect(); - assert_eq!(replies.len(), 4, "{replies:?}"); - assert_eq!(replies[0]["ok"], true); - assert!(replies[1]["error"].as_str().unwrap().contains("request exceeds"), "{}", replies[1]); - assert!(replies[2]["error"].as_str().unwrap().contains("not valid UTF-8"), "{}", replies[2]); - assert_eq!(replies[3]["id"], 2); - assert_eq!(replies[3]["result"]["documents"].as_array().unwrap().len(), 1, "the document stays open"); - } - - #[test] - fn preview_rejection_precedes_output_file_creation() { - let root = std::env::temp_dir().join(format!("pc-preview-budget-{}", std::process::id())); - std::fs::create_dir_all(&root).unwrap(); - let workspace = crate::AuthorizedWorkspace::new(None, Some(&root)).unwrap(); - let mut h = Headless::with_workspace(workspace); - h.handle("doc.new", json!({"width": 16, "height": 8})).unwrap(); - let result = h.handle("doc.render", json!({"maxSide": 2049, "path": "rejected.png"})); - assert!(result.unwrap_err().to_string().contains("preview side exceeds")); - assert!(!root.join("rejected.png").exists()); - assert!(h.handle("doc.render", json!({"maxSide": 16, "path": "accepted.png"})).is_ok()); - assert!(root.join("accepted.png").exists()); - // Release directory capabilities before cleanup on Windows. - drop(h); - std::fs::remove_file(root.join("accepted.png")).unwrap(); - std::fs::remove_dir(root).unwrap(); - } - - #[test] - fn doc_place_reads_through_the_read_root_and_never_outside_it() { - let base = std::env::temp_dir().join(format!("pc-doc-place-{}", std::process::id())); - let root = base.join("workspace"); - let outside = base.join("outside"); - for dir in [&root, &outside] { - std::fs::create_dir_all(dir).unwrap(); - } - let img = photocraft_codecs::Image::from_u8(8, 6, photocraft_codecs::ChannelLayout::Rgb, vec![42; 8 * 6 * 3]).unwrap(); - let png = photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap(); - std::fs::write(root.join("logo.png"), &png).unwrap(); - std::fs::write(outside.join("logo.png"), &png).unwrap(); - let absolute = outside.join("logo.png").to_string_lossy().into_owned(); - - let mut h = Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&root), Some(&root)).unwrap()); - h.handle("doc.new", json!({"width": 40, "height": 30})).unwrap(); - let placed = h.handle("doc.place", json!({"path": "logo.png", "scale": 50})).unwrap(); - assert!(placed["layer"].as_u64().is_some(), "{placed}"); - assert_eq!(placed["scale"].as_f64(), Some(50.0), "the options reach the command: {placed}"); - let inspected = h.handle("doc.inspect", json!({})).unwrap(); - assert_eq!(inspected["layers"].as_array().map(Vec::len), Some(2), "the placed layer is in the document: {inspected}"); - // A path outside the read root is refused the way the ambient command is (#2810). - for (path, reason) in [("../outside/logo.png", "parent traversal"), (absolute.as_str(), "must be inside the automation root")] { - let refused = h.handle("doc.place", json!({"path": path})).unwrap_err().to_string(); - assert!(refused.contains(reason), "{refused}"); - let inspected = h.handle("doc.inspect", json!({})).unwrap(); - assert_eq!(inspected["layers"].as_array().map(Vec::len), Some(2), "nothing was placed: {refused}"); - } - // Trusted local keeps the ambient command: that caller may read the path itself. - let mut t = Headless::trusted_local(); - t.handle("doc.new", json!({"width": 40, "height": 30})).unwrap(); - let trusted = t.handle("doc.place", json!({"path": root.join("logo.png").to_string_lossy()})).unwrap(); - assert!(trusted["layer"].as_u64().is_some(), "{trusted}"); - // Release directory capabilities before cleanup on Windows. - drop(t); - drop(h); - std::fs::remove_dir_all(base).unwrap(); - } - - #[test] - fn doc_replace_smart_object_reads_through_the_read_root_and_never_outside_it() { - let base = std::env::temp_dir().join(format!("pc-doc-replace-so-{}", std::process::id())); - let root = base.join("workspace"); - let outside = base.join("outside"); - for dir in [&root, &outside] { - std::fs::create_dir_all(dir).unwrap(); - } - let png = |w: u32, h: u32, v: u8| { - let img = photocraft_codecs::Image::from_u8(w, h, photocraft_codecs::ChannelLayout::Rgb, vec![v; (w * h * 3) as usize]).unwrap(); - photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap() - }; - std::fs::write(root.join("logo.png"), png(8, 6, 42)).unwrap(); - std::fs::write(root.join("red.png"), png(8, 6, 200)).unwrap(); - std::fs::write(outside.join("red.png"), png(8, 6, 200)).unwrap(); - let absolute = outside.join("red.png").to_string_lossy().into_owned(); - - let mut h = Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&root), Some(&root)).unwrap()); - h.handle("doc.new", json!({"width": 40, "height": 30})).unwrap(); - let layer = h.handle("doc.place", json!({"path": "logo.png"})).unwrap()["layer"].clone(); - // The smart object's file name and the composite at its centre: what Replace Contents changes. - let contents = |h: &mut Headless| { - let inspected = h.handle("doc.inspect", json!({})).unwrap(); - let layers = inspected["layers"].as_array().unwrap(); - let so = layers.iter().find(|l| l["id"] == layer).unwrap_or_else(|| panic!("{inspected}")); - let name = so["smartSource"]["fileName"].as_str().unwrap_or_default().to_owned(); - let rendered = h.handle("doc.render", json!({"maxSide": 0})).unwrap(); - let png = base64::engine::general_purpose::STANDARD.decode(rendered["base64"].as_str().unwrap()).unwrap(); - let img = photocraft_codecs::decode(&png).unwrap(); - let (w, ht) = img.dimensions(); - let data = img.as_u8().unwrap(); - let channels = data.len() / (w * ht) as usize; - (name, data[((ht / 2 * w + w / 2) as usize) * channels]) - }; - assert_eq!(contents(&mut h), ("logo.png".to_owned(), 42), "the placed contents"); - let replaced = h.handle("doc.replaceSmartObject", json!({"path": "red.png", "layer": layer})).unwrap(); - assert_eq!(replaced["layer"], layer, "{replaced}"); - assert_eq!(contents(&mut h), ("red.png".to_owned(), 200), "the contents were replaced"); - h.handle("engine.execute", json!({"command": "edit.undo"})).unwrap(); - assert_eq!(contents(&mut h), ("logo.png".to_owned(), 42), "one undo step restores the old contents"); - h.handle("engine.execute", json!({"command": "edit.redo"})).unwrap(); - assert_eq!(contents(&mut h), ("red.png".to_owned(), 200), "redo replaces them again"); - // Outside the read root, a bad layer, a missing path or a file that is no image: refused, nothing changed. - for (params, reason) in [ - (json!({"path": "../outside/red.png"}), "parent traversal"), - (json!({"path": absolute}), "must be inside the automation root"), - (json!({"path": "logo.png", "layer": 999_999}), "no such layer"), - (json!({}), "needs `path`"), - ] { - let refused = h.handle("doc.replaceSmartObject", params).unwrap_err().to_string(); - assert!(refused.contains(reason), "{refused}"); - assert_eq!(contents(&mut h), ("red.png".to_owned(), 200), "nothing changed: {refused}"); - } - std::fs::write(root.join("junk.png"), b"not an image").unwrap(); - assert!(h.handle("doc.replaceSmartObject", json!({"path": "junk.png", "layer": layer})).is_err()); - assert_eq!(contents(&mut h), ("red.png".to_owned(), 200), "a file that is no image changes nothing"); - // The ambient command keeps its refusal. - let ambient = h.handle("engine.execute", json!({"command": "layer.smartObjects.replaceContents", "params": {"path": "red.png"}})); - assert!(ambient.unwrap_err().to_string().contains("ambient filesystem paths")); - // Trusted local keeps the ambient command. - let mut t = Headless::trusted_local(); - t.handle("doc.new", json!({"width": 40, "height": 30})).unwrap(); - let tl = t.handle("doc.place", json!({"path": root.join("logo.png").to_string_lossy()})).unwrap()["layer"].clone(); - let trusted = t.handle("doc.replaceSmartObject", json!({"path": root.join("red.png").to_string_lossy(), "layer": tl})).unwrap(); - assert_eq!(trusted["layer"], tl, "{trusted}"); - drop(t); - drop(h); - std::fs::remove_dir_all(base).unwrap(); - } - - #[test] - fn doc_export_layers_reports_skips_in_workspace_and_trusted_sessions() { - for trusted in [false, true] { - let base = std::env::temp_dir().join(format!("pc-export-skips-{}-{trusted}", std::process::id())); - let _ = std::fs::remove_dir_all(&base); - std::fs::create_dir_all(&base).unwrap(); - let mut h = - if trusted { Headless::trusted_local() } else { Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&base), Some(&base)).unwrap()) }; - h.handle("doc.new", json!({"width": 4, "height": 4, "background": "white", "name": "card"})).unwrap(); - let adjustment = h.handle("engine.execute", json!({"command": "layer.newAdjustmentLayer.levels"})).unwrap()["layer"].clone(); - h.handle("engine.execute", json!({"command": "layer.setProps", "params": {"name": "Levels"}})).unwrap(); - let hidden = h.handle("engine.execute", json!({"command": "layer.new.layer", "params": {"name": "Hidden"}})).unwrap()["layer"].clone(); - h.handle("engine.execute", json!({"command": "layer.setProps", "params": {"visible": false}})).unwrap(); - // Exercise the actual JSON-lines serve envelope, not only direct dispatch. - let h = Mutex::new(h); - let out_dir = base.join("out").to_string_lossy().into_owned(); - let request = json!({"id": 8491, "method": "doc.exportLayers", "params": {"dir": out_dir}}).to_string() + "\n"; - let mut output = Vec::new(); - serve_lines(&h, request.as_bytes(), &mut output).unwrap(); - let reply: Value = serde_json::from_slice(&output).unwrap(); - assert_eq!(reply["id"], 8491); - assert_eq!(reply["ok"], true, "{reply}"); - assert_eq!(reply["result"]["files"], json!([format!("{out_dir}/card_0001_Background.png")])); - if !trusted { - assert_eq!(reply["result"]["count"], 1); - } - assert_eq!( - reply["result"]["skipped"], - json!([ - {"layer": hidden, "name": "Hidden", "reason": "hidden by visibleOnly"}, - {"layer": adjustment, "name": "Levels", "reason": "adjustment layer has no pixels of its own"} - ]) - ); - assert_eq!(std::fs::read_dir(base.join("out")).unwrap().count(), 1); - let mut h = h.into_inner().unwrap(); - let all_dir = base.join("all").to_string_lossy().into_owned(); - let all = h.export_layers(None, &all_dir, &json!({"visibleOnly": false})).unwrap(); - assert_eq!(all["files"].as_array().unwrap().len(), 2); - assert_eq!(all["skipped"].as_array().unwrap().len(), 1); - // Workspace no-overwrite errors still fail and remove only newly created files. - if !trusted { - let collision = base.join("collision"); - std::fs::create_dir_all(&collision).unwrap(); - std::fs::write(collision.join("card_0002_Background.png"), b"keep").unwrap(); - assert!(h.export_layers(None, &collision.to_string_lossy(), &json!({"visibleOnly": false})).is_err()); - assert_eq!(std::fs::read_dir(&collision).unwrap().count(), 1); - assert_eq!(std::fs::read(collision.join("card_0002_Background.png")).unwrap(), b"keep"); - } - drop(h); - std::fs::remove_dir_all(base).unwrap(); - } - } - - #[test] - fn doc_export_layers_writes_only_beneath_the_write_root() { - let base = std::env::temp_dir().join(format!("pc-doc-export-layers-{}", std::process::id())); - let root = base.join("workspace"); - std::fs::create_dir_all(&root).unwrap(); - let mut h = Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&root), Some(&root)).unwrap()); - h.handle("doc.new", json!({"width": 12, "height": 8, "background": "white", "name": "card"})).unwrap(); - h.handle("engine.execute", json!({"command": "layer.new.layer", "params": {"name": "Badge"}})).unwrap(); - - let out = root.join("out"); - let exported = h.handle("doc.exportLayers", json!({"dir": out.to_string_lossy(), "format": "png", "prefix": "card"})).unwrap(); - assert_eq!(exported["count"].as_u64(), Some(2), "{exported}"); - let mut names: Vec = std::fs::read_dir(&out).unwrap().map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()).collect(); - names.sort(); - assert_eq!(names.len(), 2, "{exported}"); - for name in names { - assert!(name.starts_with("card_") && name.ends_with(".png"), "{name}"); - let bytes = std::fs::read(out.join(&name)).unwrap(); - assert_eq!(photocraft_codecs::decode(&bytes).unwrap().dimensions(), (12, 8), "{name}"); - } - // Outside the write root nothing is created, not even the directory. - let escaped = base.join("escaped"); - let refused = h.handle("doc.exportLayers", json!({"dir": escaped.to_string_lossy()})).unwrap_err().to_string(); - assert!(refused.contains("must be inside the automation root"), "{refused}"); - assert!(!escaped.exists()); - // The ambient command keeps its refusal for the very same directory. - let ambient = - h.handle("engine.execute", json!({"command": "file.export.layersToFiles", "params": {"dir": out.to_string_lossy()}})).unwrap_err().to_string(); - assert!(ambient.contains("ambient filesystem paths"), "{ambient}"); - // Release directory capabilities before cleanup on Windows. - drop(h); - std::fs::remove_dir_all(base).unwrap(); - } - - #[test] - fn doc_export_data_sets_refuse_collisions_and_import_reads_the_root() { - let base = std::env::temp_dir().join(format!("pc-doc-data-sets-{}", std::process::id())); - let root = base.join("workspace"); - std::fs::create_dir_all(&root).unwrap(); - let mut h = Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&root), Some(&root)).unwrap()); - h.handle("doc.new", json!({"width": 8, "height": 8, "background": "white", "name": "card"})).unwrap(); - let inspected = h.handle("doc.inspect", json!({})).unwrap(); - let layer = inspected["layers"][0]["id"].as_u64().expect("the layer id"); - h.handle("engine.execute", json!({"command": "image.variables.define", "params": {"defs": [{"name": "show", "layer": layer, "type": "visibility"}]}})) - .unwrap(); - h.handle( - "engine.execute", - json!({"command": "image.variables.dataSets", "params": {"dataSets": [ - {"name": "one", "values": [{"variable": "show", "kind": "visibility", "value": true}]}, - {"name": "two", "values": [{"variable": "show", "kind": "visibility", "value": false}]}, - ]}}), - ) - .unwrap(); - - let sets = root.join("sets"); - let exported = h.handle("doc.exportDataSets", json!({"dir": sets.to_string_lossy(), "format": "png"})).unwrap(); - assert_eq!(exported["count"].as_u64(), Some(2), "{exported}"); - assert_eq!(std::fs::read_dir(&sets).unwrap().count(), 2, "{exported}"); - // Colliding names are refused as in the command, before any file is written. - let clash = root.join("clash"); - let refused = h.handle("doc.exportDataSets", json!({"dir": clash.to_string_lossy(), "naming": "{document}"})).unwrap_err().to_string(); - assert!(refused.contains("{index}"), "{refused}"); - assert_eq!(std::fs::read_dir(&clash).unwrap().count(), 0, "no file of the refused batch"); - // A CSV from the read root, and one outside it. - std::fs::write(root.join("sets.csv"), "Data Set,show\none,true\ntwo,false\n").unwrap(); - let imported = h.handle("doc.importDataSets", json!({"path": "sets.csv"})).unwrap(); - assert_eq!(imported["imported"].as_u64(), Some(2), "{imported}"); - std::fs::write(base.join("outside.csv"), "Data Set,show\none,true\n").unwrap(); - let outside = h.handle("doc.importDataSets", json!({"path": base.join("outside.csv").to_string_lossy()})).unwrap_err().to_string(); - assert!(outside.contains("must be inside the automation root"), "{outside}"); - // Release directory capabilities before cleanup on Windows. - drop(h); - std::fs::remove_dir_all(base).unwrap(); - } - - #[test] - fn indexed_place_replace_and_data_set_methods_keep_the_active_document() { - let base = std::env::temp_dir().join(format!("pc-doc-index-active-{}", std::process::id())); - let root = base.join("workspace"); - std::fs::create_dir_all(&root).unwrap(); - let img = photocraft_codecs::Image::from_u8(4, 4, photocraft_codecs::ChannelLayout::Rgb, vec![42; 4 * 4 * 3]).unwrap(); - std::fs::write(root.join("logo.png"), photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap()).unwrap(); - std::fs::write(root.join("sets.csv"), "Data Set,show\none,true\ntwo,false\n").unwrap(); - let mut h = Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&root), Some(&root)).unwrap()); - h.handle("doc.new", json!({"width": 8, "height": 8, "background": "white", "name": "first"})).unwrap(); - h.handle("doc.new", json!({"width": 8, "height": 8, "background": "white", "name": "second"})).unwrap(); - let layer = h.handle("doc.inspect", json!({})).unwrap()["layers"][0]["id"].as_u64().expect("the layer id"); - h.handle("engine.execute", json!({"command": "image.variables.define", "params": {"defs": [{"name": "show", "layer": layer, "type": "visibility"}]}})) - .unwrap(); - h.handle("doc.select", json!({"index": 0})).unwrap(); - - let steps = [ - ("doc.place", json!({"path": "logo.png", "index": 1}), true), - // Document 1's active layer is now the placed Smart Object. - ("doc.replaceSmartObject", json!({"path": "logo.png", "index": 1}), true), - ("doc.replaceSmartObject", json!({"path": "missing.png", "index": 1}), false), - ("doc.importDataSets", json!({"path": "sets.csv", "index": 1}), true), - ("doc.exportLayers", json!({"dir": "layers", "index": 1}), true), - ("doc.exportDataSets", json!({"dir": "sets", "index": 1}), true), - // A failing call restores the active document too. - ("doc.importDataSets", json!({"path": "missing.csv", "index": 1}), false), - ]; - for (method, params, succeeds) in steps { - let result = h.handle(method, params.clone()); - assert_eq!(result.is_ok(), succeeds, "{method} {params}: {result:?}"); - assert_eq!(h.session.active_index(), Some(0), "{method} {params} must not select document 1"); - } - assert_eq!(h.session.documents()[0].doc.layer_count(), 1, "nothing was placed into the active document"); - assert_eq!(h.session.documents()[1].doc.layer_count(), 2, "the placed layer is in document 1"); - assert_eq!(std::fs::read_dir(root.join("sets")).unwrap().count(), 2, "document 1's data sets were exported"); - // Release directory capabilities before cleanup on Windows. - drop(h); - std::fs::remove_dir_all(base).unwrap(); - } - - #[test] - fn doc_export_data_sets_judges_pixel_replacement_paths_like_apply() { - let base = std::env::temp_dir().join(format!("pc-doc-data-set-pixels-{}", std::process::id())); - let root = base.join("workspace"); - std::fs::create_dir_all(&root).unwrap(); - let red = photocraft_codecs::Image::from_u8(4, 4, photocraft_codecs::ChannelLayout::Rgb, [255, 0, 0].repeat(16)).unwrap(); - let photo = base.join("photo.png"); - std::fs::write(&photo, photocraft_codecs::encode(&red, photocraft_codecs::Format::Png, &Default::default()).unwrap()).unwrap(); - let mut h = Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&root), Some(&root)).unwrap()); - h.handle("doc.new", json!({"width": 8, "height": 8, "background": "white", "name": "card"})).unwrap(); - let layer = h.handle("engine.execute", json!({"command": "layer.new.layer", "params": {}})).unwrap()["layer"].clone(); - h.handle( - "engine.execute", - json!({"command": "image.variables.define", "params": {"defs": [{"name": "photo", "layer": layer, "type": "pixelReplacement"}]}}), - ) - .unwrap(); - // Storing the path is allowed; reading it is what the gate judges. - h.handle( - "engine.execute", - json!({"command": "image.variables.dataSets", "params": {"dataSets": [ - {"name": "swap", "values": [{"variable": "photo", "kind": "pixels", "value": photo.to_string_lossy()}]}, - ]}}), - ) - .unwrap(); - let applied = h.handle("engine.execute", json!({"command": "image.applyDataSet", "params": {"name": "swap"}})).unwrap_err().to_string(); - assert!(applied.contains("ambient filesystem paths"), "{applied}"); - let sets = root.join("sets"); - let exported = h.handle("doc.exportDataSets", json!({"dir": sets.to_string_lossy(), "format": "png"})).unwrap_err().to_string(); - assert!(exported.contains("ambient filesystem paths"), "{exported}"); - assert_eq!(std::fs::read_dir(&sets).map_or(0, Iterator::count), 0, "nothing of the refused batch is written"); - // Release directory capabilities before cleanup on Windows. - drop(h); - std::fs::remove_dir_all(base).unwrap(); - } - - #[test] - fn workspace_psd_saves_embed_no_file_a_linked_smart_object_names() { - use photocraft_engine::doc::{LayerContent, SmartSource}; - - // An image PhotoCraft can open (other linked files are never embedded): an embedded copy - // carries these exact bytes, while pixels written for the layer don't. - let image = photocraft_codecs::Image::from_u8(8, 8, photocraft_codecs::ChannelLayout::Rgb, (0..192u8).collect()).unwrap(); - let marker = photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap(); - let has_marker = |bytes: &[u8]| bytes.windows(marker.len()).any(|w| w == marker.as_slice()); - let base = std::env::temp_dir().join(format!("pc-psd-linked-embed-{}", std::process::id())); - let root = base.join("workspace"); - std::fs::create_dir_all(&root).unwrap(); - let outside = base.join("outside.png"); - std::fs::write(&outside, &marker).unwrap(); - // A document whose smart object names a file outside the roots as its source. - let mut session = photocraft_engine::Session::new(); - session.execute("file.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap(); - session.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - let state = session.active_mut().unwrap(); - let LayerContent::Smart(smart) = &mut std::sync::Arc::make_mut(&mut state.doc).layers[0].content else { panic!("smart object") }; - smart.source = SmartSource::Linked { path: outside.to_string_lossy().into_owned() }; - std::fs::write(root.join("in.pcraft"), photocraft_engine::smart_cmds::encode_source(&state.doc).unwrap()).unwrap(); - // A trusted export embeds the linked file, as before. - assert!(has_marker(&photocraft_io::export(&state.doc, "psd", &Default::default()).unwrap().bytes)); - - let mut h = Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&root), Some(&root)).unwrap()); - h.handle("doc.open", json!({"path": "in.pcraft"})).unwrap(); - let saved = h.handle("doc.save", json!({"path": "out.psd"})).unwrap(); - let warnings = saved["warnings"].to_string(); - assert!(warnings.contains("written as pixels"), "{warnings}"); - assert!(!has_marker(&std::fs::read(root.join("out.psd")).unwrap()), "the linked file outside the roots is not embedded"); - // Release directory capabilities before cleanup on Windows. - drop(h); - std::fs::remove_dir_all(base).unwrap(); - } - - #[test] - fn allowed_filters_do_not_rerender_a_smart_object_from_its_linked_file() { - use photocraft_engine::doc::{LayerContent, SmartSource}; - - let base = std::env::temp_dir().join(format!("pc-linked-rerender-{}", std::process::id())); - let root = base.join("workspace"); - std::fs::create_dir_all(&root).unwrap(); - let red = photocraft_codecs::Image::from_u8(8, 8, photocraft_codecs::ChannelLayout::Rgb, [255, 0, 0].repeat(64)).unwrap(); - let outside = base.join("red.png"); - std::fs::write(&outside, photocraft_codecs::encode(&red, photocraft_codecs::Format::Png, &Default::default()).unwrap()).unwrap(); - // A document whose white smart object names a file outside the roots as its source. - let mut session = photocraft_engine::Session::new(); - session.execute("file.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap(); - session.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - let state = session.active_mut().unwrap(); - let LayerContent::Smart(smart) = &mut std::sync::Arc::make_mut(&mut state.doc).layers[0].content else { panic!("smart object") }; - smart.source = SmartSource::Linked { path: outside.to_string_lossy().into_owned() }; - std::fs::write(root.join("p.pcraft"), photocraft_engine::smart_cmds::encode_source(&state.doc).unwrap()).unwrap(); - - let mut h = Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&root), Some(&root)).unwrap()); - h.handle("doc.open", json!({"path": "p.pcraft"})).unwrap(); - h.handle("engine.execute", json!({"command": "filter.blur.gaussianBlur", "params": {"radius": 0.5}})).unwrap(); - let doc = &h.session.active().unwrap().doc; - let LayerContent::Smart(smart) = &doc.layers[0].content else { panic!("smart object") }; - assert_eq!(smart.smart_filters.len(), 1, "the filter is still recorded"); - assert_eq!(smart.cache.as_ref().unwrap().rgba(4, 4), [1.0, 1.0, 1.0, 1.0], "the linked file outside the roots is not read"); - // Release directory capabilities before cleanup on Windows. - drop(h); - std::fs::remove_dir_all(base).unwrap(); - } - - #[test] - fn workspace_layer_exports_keep_linked_smart_objects_as_pixels() { - use photocraft_engine::doc::{LayerContent, SmartSource}; - - const MARKER: &[u8] = b"PHOTOCRAFT-LINKED-0002"; - let has_marker = |bytes: &[u8]| bytes.windows(MARKER.len()).any(|w| w == MARKER); - let base = std::env::temp_dir().join(format!("pc-export-layers-linked-{}", std::process::id())); - let root = base.join("workspace"); - std::fs::create_dir_all(&root).unwrap(); - let outside = base.join("outside.txt"); - std::fs::write(&outside, MARKER).unwrap(); - // A document whose smart object names a file outside the roots as its source. - let mut session = photocraft_engine::Session::new(); - session.execute("file.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap(); - session.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - let state = session.active_mut().unwrap(); - let LayerContent::Smart(smart) = &mut std::sync::Arc::make_mut(&mut state.doc).layers[0].content else { panic!("smart object") }; - smart.source = SmartSource::Linked { path: outside.to_string_lossy().into_owned() }; - std::fs::write(root.join("in.pcraft"), photocraft_engine::smart_cmds::encode_source(&state.doc).unwrap()).unwrap(); - - let mut h = Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&root), Some(&root)).unwrap()); - h.handle("doc.open", json!({"path": "in.pcraft"})).unwrap(); - let out = root.join("layers"); - for format in ["psd", "psb"] { - let exported = h.handle("doc.exportLayers", json!({"dir": out.to_string_lossy(), "format": format})).unwrap(); - assert_eq!(exported["count"], 1, "{exported}"); - } - let files: Vec<_> = std::fs::read_dir(&out).unwrap().map(|e| e.unwrap().path()).collect(); - assert_eq!(files.len(), 2, "{files:?}"); - for file in files { - assert!(!has_marker(&std::fs::read(&file).unwrap()), "{} embeds no file outside the roots", file.display()); - } - // Release directory capabilities before cleanup on Windows. - drop(h); - std::fs::remove_dir_all(base).unwrap(); - } - - #[test] - fn trusted_local_render_keeps_full_size_behavior() { - let mut h = Headless::trusted_local(); - h.handle("doc.new", json!({"width": 2049, "height": 1})).unwrap(); - let rendered = h.handle("doc.render", json!({"maxSide": 0})).unwrap(); - let png = base64::engine::general_purpose::STANDARD.decode(rendered["base64"].as_str().unwrap()).unwrap(); - assert_eq!(photocraft_codecs::decode(&png).unwrap().dimensions(), (2049, 1)); - } - - #[test] - fn methods_lists_the_job_methods_and_every_listed_name_is_served() { - let mut h = Headless::new(); - let listed = h.handle("methods", Value::Null).unwrap(); - let listed: Vec<&str> = listed.as_array().unwrap().iter().map(|m| m.as_str().unwrap()).collect(); - assert_eq!(listed, METHODS); - // The job methods `engine.execute {"wait": false}` depends on are discoverable (#414). - assert!(listed.contains(&"jobs.list") && listed.contains(&"jobs.cancel")); - for m in METHODS { - if let Err(e) = h.handle(m, Value::Null) { - assert!(!e.to_string().contains("unknown method"), "{m} is listed but not served: {e}"); - } - } - assert!(h.handle("jobs.nope", Value::Null).unwrap_err().to_string().contains("unknown method")); - } - - #[test] - fn batch_response_budget_stops_later_steps_even_when_stop_on_error_is_false() { - let mut h = Headless::new(); - let mut steps = vec![json!({"command": "command.list"}); MAX_BATCH_STEPS - 1]; - steps.push(json!({"command": "file.new", "params": {"width": 8, "height": 8}})); - let result = h.batch(&json!({"steps": steps, "stopOnError": false})).unwrap(); - assert_eq!(result["failed"], 1); - assert!(result["results"].as_array().unwrap().last().unwrap()["error"].as_str().unwrap().contains("batch response budget exceeded")); - assert!(h.session.documents().is_empty(), "later edit must not execute after the quota is exhausted"); - assert!(crate::budgets::json_bytes(&result).is_ok()); - assert!(h.handle("methods", Value::Null).is_ok()); - } - - #[test] - fn idle_tcp_daemon_releases_its_port_but_keeps_active_clients() { - use std::io::BufReader; - const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; - let h = Arc::new(Mutex::new(Headless::new())); - let (ready_tx, ready_rx) = std::sync::mpsc::channel(); - let (done_tx, done_rx) = std::sync::mpsc::channel(); - let server = std::thread::spawn(move || { - let result = serve_tcp_until_idle("127.0.0.1:0", h, TOKEN.to_owned(), move |addr| ready_tx.send(addr).unwrap(), Duration::from_millis(200)); - done_tx.send(result).unwrap(); - }); - let addr = ready_rx.recv_timeout(Duration::from_secs(2)).unwrap(); - let mut client = std::net::TcpStream::connect(addr).unwrap(); - client.set_read_timeout(Some(Duration::from_secs(2))).unwrap(); - let mut reader = BufReader::new(client.try_clone().unwrap()); - writeln!(client, r#"{{"id":"auth","method":"auth","params":{{"token":"{TOKEN}"}}}}"#).unwrap(); - let mut line = String::new(); - reader.read_line(&mut line).unwrap(); - let auth: Value = serde_json::from_str(&line).unwrap(); - assert_eq!(auth["result"]["authenticated"], true); - // The port stays owned well past the idle limit while a client is connected. - assert!( - matches!(done_rx.recv_timeout(Duration::from_millis(450)), Err(std::sync::mpsc::RecvTimeoutError::Timeout)), - "daemon exited with a live client" - ); - drop(reader); - drop(client); - assert!(done_rx.recv_timeout(Duration::from_secs(3)).unwrap().is_ok(), "idle daemon did not exit cleanly"); - server.join().unwrap(); - assert!(TcpListener::bind(addr).is_ok(), "idle listener still owns its port"); - } - - #[test] - fn tcp_serves_loopback() { - use std::io::{BufReader, Write as _}; - const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; - let h = Arc::new(Mutex::new(Headless::new())); - let (tx, rx) = std::sync::mpsc::channel(); - std::thread::spawn(move || { - let _ = serve_tcp("127.0.0.1:0", h, TOKEN.into(), move |a| tx.send(a).unwrap()); - }); - let addr = rx.recv().unwrap(); - let mut s = std::net::TcpStream::connect(addr).unwrap(); - writeln!(s, r#"{{"id":"auth","method":"auth","params":{{"token":"{TOKEN}"}}}}"#).unwrap(); - let mut reader = BufReader::new(s.try_clone().unwrap()); - let mut line = String::new(); - reader.read_line(&mut line).unwrap(); - let auth: Value = serde_json::from_str(&line).unwrap(); - assert_eq!(auth["result"]["authenticated"], true); - writeln!(s, r#"{{"id":"a","method":"methods"}}"#).unwrap(); - line.clear(); - reader.read_line(&mut line).unwrap(); - let v: Value = serde_json::from_str(&line).unwrap(); - assert_eq!(v["id"], "a"); - assert!(v["result"].as_array().unwrap().iter().any(|m| m == "batch")); - } - - /// #4965: a connection that keeps sending without authenticating is closed at the deadline, - /// and one that authenticated in time keeps being served after it. - #[test] - fn tcp_connections_must_authenticate_before_the_deadline_whatever_they_send() { - use std::io::{BufReader, Write as _}; - use std::time::{Duration, Instant}; - const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; - let listener = TcpListener::bind("127.0.0.1:0").unwrap(); - let addr = listener.local_addr().unwrap(); - let server = std::thread::spawn(move || { - let h = Mutex::new(Headless::new()); - let mut results = Vec::new(); - for _ in 0..2 { - let (stream, _) = listener.accept().unwrap(); - let started = Instant::now(); - let r = serve_tcp_connection(&h, stream, TOKEN, Duration::from_millis(300)); - results.push((r.map_err(|e| e.kind()), started.elapsed())); - } - results - }); - - // Never a newline, a byte every 20 ms: each read succeeds long before the idle timeout. - let mut slow = std::net::TcpStream::connect(addr).unwrap(); - for _ in 0..150 { - if slow.write_all(b" ").is_err() { - break; - } - std::thread::sleep(Duration::from_millis(20)); - } - drop(slow); - - // Authenticates at once, then asks again 300 ms after the deadline. - let mut s = std::net::TcpStream::connect(addr).unwrap(); - s.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); - writeln!(s, r#"{{"id":"auth","method":"auth","params":{{"token":"{TOKEN}"}}}}"#).unwrap(); - let mut reader = BufReader::new(s.try_clone().unwrap()); - let mut line = String::new(); - reader.read_line(&mut line).unwrap(); - assert_eq!(serde_json::from_str::(&line).unwrap()["result"]["authenticated"], true); - std::thread::sleep(Duration::from_millis(600)); - writeln!(s, r#"{{"id":"a","method":"methods"}}"#).unwrap(); - line.clear(); - reader.read_line(&mut line).unwrap(); - assert_eq!(serde_json::from_str::(&line).unwrap()["id"], "a"); - drop(reader); - drop(s); - - let results = server.join().unwrap(); - let (slow_result, slow_time) = &results[0]; - assert!(matches!(slow_result, Err(std::io::ErrorKind::TimedOut | std::io::ErrorKind::WouldBlock)), "{slow_result:?}"); - assert!(*slow_time < Duration::from_secs(3), "the trickle did not extend the deadline: {slow_time:?}"); - assert_eq!(results[1].0, Ok(()), "the authenticated connection ended with its client"); - } - - #[test] - fn tcp_repeat_auth_reports_already_authenticated_and_keeps_serving() { - use std::io::{BufReader, Write as _}; - const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; - let h = Arc::new(Mutex::new(Headless::new())); - let (tx, rx) = std::sync::mpsc::channel(); - std::thread::spawn(move || { - let _ = serve_tcp("127.0.0.1:0", h, TOKEN.into(), move |a| tx.send(a).unwrap()); - }); - let addr = rx.recv().unwrap(); - let mut s = std::net::TcpStream::connect(addr).unwrap(); - let mut reader = BufReader::new(s.try_clone().unwrap()); - let mut line = String::new(); - for id in ["auth", "again"] { - writeln!(s, r#"{{"id":"{id}","method":"auth","params":{{"token":"{TOKEN}"}}}}"#).unwrap(); - line.clear(); - reader.read_line(&mut line).unwrap(); - } - let again: Value = serde_json::from_str(&line).unwrap(); - assert_eq!(again["id"], "again"); - assert_eq!(again["ok"], false); - assert_eq!(again["error"], "already authenticated"); - writeln!(s, r#"{{"id":"m","method":"methods"}}"#).unwrap(); - line.clear(); - reader.read_line(&mut line).unwrap(); - let v: Value = serde_json::from_str(&line).unwrap(); - assert_eq!(v["id"], "m"); - assert_eq!(v["ok"], true); - } - - #[test] - fn tcp_rejects_requests_before_authentication() { - use std::io::{BufReader, Write as _}; - const TOKEN: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; - let h = Arc::new(Mutex::new(Headless::new())); - let (tx, rx) = std::sync::mpsc::channel(); - std::thread::spawn(move || { - let _ = serve_tcp("127.0.0.1:0", h, TOKEN.into(), move |a| tx.send(a).unwrap()); - }); - let addr = rx.recv().unwrap(); - let mut s = std::net::TcpStream::connect(addr).unwrap(); - writeln!(s, r#"{{"id":1,"method":"methods"}}"#).unwrap(); - let mut line = String::new(); - BufReader::new(s).read_line(&mut line).unwrap(); - let v: Value = serde_json::from_str(&line).unwrap(); - assert_eq!(v["ok"], false); - assert_eq!(v["error"], "authentication required"); - assert!(v.get("result").is_none()); - } - - #[test] - fn invalid_document_index_is_rejected_not_the_active_document() { - let h = session(); - for _ in 0..2 { - assert_eq!(respond(&h, r#"{"method":"doc.new","params":{"width":8,"height":8}}"#)["ok"], true); - } - let count = |h: &Mutex| h.lock().unwrap().session_list()["documents"].as_array().unwrap().len(); - for index in [json!("0"), json!(-1), json!(0.5), json!(true)] { - for method in ["doc.close", "doc.inspect", "doc.select"] { - let reply = respond(&h, &json!({"method": method, "params": {"index": index}}).to_string()); - assert_eq!(reply["ok"], false, "{method} {index}: {reply}"); - assert!(reply["error"].as_str().unwrap().contains("`index` must be a non-negative integer"), "{reply}"); - } - assert_eq!(count(&h), 2, "index {index} closed a document"); - } - // Null means "the active document", like a missing `index`. - assert_eq!(respond(&h, r#"{"method":"doc.inspect","params":{"index":null}}"#)["ok"], true); - // A valid index still closes that document. - let reply = respond(&h, r#"{"method":"doc.close","params":{"index":0}}"#); - assert_eq!(reply["ok"], true, "{reply}"); - assert_eq!(count(&h), 1); - } -} +mod tests; diff --git a/crates/automation/src/rpc/tests.rs b/crates/automation/src/rpc/tests.rs new file mode 100644 index 0000000000..b7e22b3ffa --- /dev/null +++ b/crates/automation/src/rpc/tests.rs @@ -0,0 +1,974 @@ +use super::*; + +fn session() -> Mutex { + Mutex::new(Headless::trusted_local()) +} + +#[test] +fn document_activation_reply_survives_engine_rpc() { + let h = session(); + let mut g = h.lock().unwrap(); + for _ in 0..2 { + g.handle("engine.execute", json!({"command": "file.new", "params": {"width": 4, "height": 4}})).unwrap(); + } + let reply = g.handle("engine.execute", json!({"command": "document.activate", "params": {"offset": -1}})).unwrap(); + assert_eq!(reply, json!({"document": 0})); + let reply = g.handle("engine.execute", json!({"command": "document.activate", "params": {"document": 1}})).unwrap(); + assert_eq!(reply, json!({"document": 1})); +} + +#[test] +fn execute_reports_invalid_filter_parameters_without_changing_history() { + let h = session(); + assert_eq!(respond(&h, r#"{"method":"doc.new","params":{"width":8,"height":8}}"#)["ok"], true); + let before = h.lock().unwrap().inspect(None).unwrap(); + for (params, key) in + [(json!({"radius":"big"}), "radius"), (json!({"radus":3}), "radus"), (json!({"radius":5000}), "radius"), (json!({"radius":-4}), "radius")] + { + for wait in [true, false] { + let request = json!({"method":"engine.execute","params":{"command":"filter.blur.gaussianBlur","params":params,"wait":wait}}); + let reply = respond(&h, &request.to_string()); + assert_eq!(reply["ok"], false); + let error = reply["error"].as_str().unwrap(); + assert!(error.contains("filter.blur.gaussianBlur") && error.contains(key), "{error}"); + assert_eq!(h.lock().unwrap().inspect(None).unwrap(), before); + } + } +} + +/// Pins the reply shape documented in docs/control-protocol.md › Command list replies +/// (#3684): a bare JSON array (not `{"commands": [...]}`), one object per command with +/// exactly these keys (plus an optional `keywords` string), from `engine.commands` (filtered or not) and `command.list`. +#[test] +fn command_list_replies_are_documented_array_of_objects() { + let h = session(); + let mut g = h.lock().unwrap(); + let all = g.handle("engine.commands", json!({})).unwrap(); + let filtered = g.handle("engine.commands", json!({"filter": "BLUR"})).unwrap(); + let engine = g.handle("engine.execute", json!({"command": "command.list"})).unwrap(); + for (name, reply) in [("engine.commands", &all), ("engine.commands {filter}", &filtered), ("command.list", &engine)] { + let items = reply.as_array().unwrap_or_else(|| panic!("{name} must reply with a bare array, got {reply}")); + assert!(!items.is_empty(), "{name}"); + for c in items { + // `keywords` is optional: only commands with other search names carry it (#5060). + let mut keys: Vec<&str> = c.as_object().unwrap().keys().map(String::as_str).filter(|k| *k != "keywords").collect(); + keys.sort_unstable(); + assert!(c.get("keywords").is_none_or(Value::is_string), "{name}: {c}"); + assert_eq!(keys, ["disabledReason", "enabled", "id", "label", "menu", "needsDocument", "params", "shortcut"], "{name}: {c}"); + assert!(c["id"].is_string() && c["label"].is_string() && c["params"].is_string() && c["enabled"].is_boolean(), "{c}"); + assert!(c["needsDocument"].is_boolean(), "{c}"); + assert_eq!(c["disabledReason"].is_null(), c["enabled"] == true, "disabledReason is null exactly when enabled: {c}"); + assert!(c["menu"].as_array().unwrap().iter().all(Value::is_string), "{c}"); + assert!(c["shortcut"].is_string() || c["shortcut"].is_null(), "{c}"); + } + } + let n_all = all.as_array().unwrap().len(); + assert_eq!(engine.as_array().unwrap().len(), n_all); + let filtered = filtered.as_array().unwrap(); + assert!(filtered.len() < n_all); + assert!(filtered.iter().all(|c| format!("{} {}", c["id"], c["label"]).to_lowercase().contains("blur"))); + let new = all.as_array().unwrap().iter().find(|c| c["id"] == "file.new").unwrap(); + assert_eq!((&new["menu"], &new["shortcut"], &new["enabled"]), (&json!(["File"]), &json!("Cmd+N"), &json!(true)), "{new}"); + assert_eq!((&new["disabledReason"], &new["needsDocument"]), (&Value::Null, &json!(false)), "{new}"); +} + +#[test] +fn lines_round_trip_and_errors() { + let h = session(); + let input = concat!( + r#"{"id":1,"method":"doc.new","params":{"width":64,"height":32,"background":"white"}}"#, + "\n", + "\n", + r#"{"id":2,"method":"engine.execute","params":{"command":"layer.new.layer","params":{"name":"Ink"}}}"#, + "\n", + r#"{"id":3,"method":"doc.inspect"}"#, + "\n", + r#"{"id":4,"method":"nope"}"#, + "\n", + "not json\n", + ); + let mut out = Vec::new(); + serve_lines(&h, input.as_bytes(), &mut out).unwrap(); + let replies: Vec = String::from_utf8(out).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect(); + assert_eq!(replies.len(), 5); + assert!(replies[0]["ok"].as_bool().unwrap()); + assert_eq!(replies[1]["id"], 2); + assert!(replies[2]["result"].to_string().contains("Ink")); + assert!(!replies[3]["ok"].as_bool().unwrap()); + assert!(replies[3]["error"].as_str().unwrap().contains("unknown method")); + assert_eq!(replies[4]["id"], Value::Null); +} + +/// Regression: after a panic while the session lock was held, every later request +/// failed with "session lock poisoned"; the server now keeps serving. +#[test] +fn poisoned_session_keeps_serving() { + let h = session(); + let _ = std::thread::scope(|sc| { + sc.spawn(|| { + let _g = h.lock().unwrap(); + panic!("poison the session lock"); + }) + .join() + }); + assert!(h.is_poisoned()); + let r = respond(&h, r#"{"id":1,"method":"doc.new","params":{"width":8,"height":8}}"#); + assert_eq!(r["ok"], true, "{r}"); +} + +#[test] +fn batch_stops_on_error_unless_told_not_to() { + let h = session(); + let mut g = h.lock().unwrap(); + g.handle("doc.new", json!({"width": 16, "height": 16})).unwrap(); + let steps = json!([ + {"command": "layer.new.layer", "params": {"name": "A"}}, + {"command": "no.such.command"}, + {"command": "layer.new.layer", "params": {"name": "B"}}, + {"method": "doc.inspect"} + ]); + let r = g.handle("batch", json!({"steps": steps})).unwrap(); + assert_eq!(r["completed"], 1); + assert_eq!(r["failed"], 1); + assert_eq!(r["results"].as_array().unwrap().len(), 2); + let r = g.handle("batch", json!({"steps": steps, "stopOnError": false})).unwrap(); + assert_eq!(r["completed"], 3); + let insp = &r["results"][3]["result"]; + assert!(insp.to_string().contains("\"B\"")); +} + +#[test] +fn batch_rejects_too_many_steps() { + let h = session(); + let mut g = h.lock().unwrap(); + let steps = vec![json!({"command": "command.list"}); MAX_BATCH_STEPS + 1]; + let error = g.handle("batch", json!({"steps": steps})).unwrap_err(); + assert!(error.to_string().contains("maximum is 256")); +} + +#[test] +fn render_to_file_and_base64() { + let h = session(); + let mut g = h.lock().unwrap(); + g.handle("doc.new", json!({"width": 40, "height": 20, "background": "black"})).unwrap(); + let b = g.handle("doc.render", json!({"maxSide": 10})).unwrap(); + let png = base64::engine::general_purpose::STANDARD.decode(b["base64"].as_str().unwrap()).unwrap(); + let img = photocraft_codecs::decode(&png).unwrap(); + assert_eq!(img.dimensions(), (10, 5)); + let path = std::env::temp_dir().join(format!("pc-rpc-{}.png", std::process::id())); + let r = g.handle("doc.render", json!({"path": path.to_string_lossy(), "maxSide": 0})).unwrap(); + assert!(r["bytes"].as_u64().unwrap() > 0); + assert_eq!(photocraft_codecs::decode(&std::fs::read(&path).unwrap()).unwrap().dimensions(), (40, 20)); + let _ = std::fs::remove_file(path); +} + +#[test] +fn background_jobs_list_wait_and_cancel() { + let mut h = Headless::new(); + h.handle("doc.new", json!({"width": 600, "height": 400})).unwrap(); + h.handle("engine.execute", json!({"command": "layer.new.layer"})).unwrap(); + h.handle("engine.execute", json!({"command": "edit.fill", "params": {"color": "#808080"}})).unwrap(); + // Default: waits, the result is the command's. + let r = h.handle("engine.execute", json!({"command": "filter.noise.addNoise", "params": {"amount": 20}})).unwrap(); + assert!(r["filter"].is_object(), "{r}"); + // wait: false returns a job id at once. + let r = h.handle("engine.execute", json!({"command": "filter.blur.gaussianBlur", "params": {"radius": 40}, "wait": false})).unwrap(); + let job = r["job"].as_u64().unwrap(); + let listed = h.handle("jobs.list", json!({})).unwrap(); + assert!(listed["jobs"].as_array().unwrap().iter().any(|j| j["id"] == job), "{listed}"); + // Wait for it via jobs.list (which applies finished jobs). + let t = std::time::Instant::now(); + loop { + let l = h.handle("jobs.list", json!({})).unwrap(); + let state = l["jobs"].as_array().unwrap().iter().find(|j| j["id"] == job).map(|j| j["state"].clone()); + if state == Some(json!("done")) { + break; + } + assert!(t.elapsed().as_secs() < 60, "{l}"); + std::thread::sleep(std::time::Duration::from_millis(5)); + } + // Cancel: a second job, cancelled at once, leaves the document unchanged. + let before = h.session.active().unwrap().doc.clone(); + let r = h.handle("engine.execute", json!({"command": "filter.blur.gaussianBlur", "params": {"radius": 40}, "wait": false})).unwrap(); + let job = r["job"].as_u64().unwrap(); + h.handle("jobs.cancel", json!({"job": job})).unwrap(); + assert!(h.handle("jobs.cancel", json!({"job": "nope"})).is_err()); + let l = h.handle("jobs.list", json!({})).unwrap(); + assert_eq!(l["jobs"].as_array().unwrap().iter().find(|j| j["id"] == job).unwrap()["state"], "cancelled"); + assert!(std::sync::Arc::ptr_eq(&h.session.active().unwrap().doc, &before)); +} + +#[test] +fn batch_steps_can_start_background_jobs() { + let mut h = Headless::new(); + h.handle("doc.new", json!({"width": 600, "height": 400})).unwrap(); + let steps = json!([ + {"command": "layer.new.layer"}, + {"command": "edit.fill", "params": {"color": "#808080"}}, + {"command": "filter.blur.gaussianBlur", "params": {"radius": 40}, "wait": false} + ]); + let r = h.handle("batch", json!({"steps": steps})).unwrap(); + assert_eq!(r["completed"], 3, "{r}"); + let job = r["results"][2]["result"]["job"].as_u64().unwrap_or_else(|| panic!("no job id: {r}")); + assert_eq!(r["results"][2]["result"]["pending"], true); + let listed = h.handle("jobs.list", json!({})).unwrap(); + assert!(listed["jobs"].as_array().unwrap().iter().any(|j| j["id"] == job), "{listed}"); + let t = std::time::Instant::now(); + while h.session.jobs().iter().any(|j| j.id.0 == job) { + assert!(t.elapsed().as_secs() < 60); + std::thread::sleep(std::time::Duration::from_millis(5)); + h.handle("jobs.list", json!({})).unwrap(); + } +} + +/// Regression (#503): a finished `wait: false` job was only applied by a later command or +/// `jobs.list`, so save, inspect, render and `session.list` still saw the document without it. +#[test] +fn every_request_sees_a_finished_background_job() { + let dir = std::env::temp_dir().join(format!("pc-rpc-job-sync-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let (before, after) = (dir.join("before.png"), dir.join("after.png")); + let mut h = Headless::trusted_local(); + h.handle("doc.new", json!({"width": 64, "height": 48})).unwrap(); + h.handle("engine.execute", json!({"command": "filter.noise.addNoise", "params": {"amount": 50}})).unwrap(); + h.handle("doc.save", json!({"path": before.to_string_lossy()})).unwrap(); + let render = |h: &mut Headless| h.handle("doc.render", json!({"maxSide": 0})).unwrap()["base64"].clone(); + let unblurred = render(&mut h); + let revision = |h: &mut Headless| h.handle("session.list", json!({})).unwrap()["documents"][0]["revision"].clone(); + let start = revision(&mut h); + h.handle("engine.execute", json!({"command": "filter.blur.gaussianBlur", "params": {"radius": 4}, "wait": false})).unwrap(); + // Only reading requests from here on: no command and no `jobs.list`. + let t = std::time::Instant::now(); + while revision(&mut h) == start { + assert!(t.elapsed().as_secs() < 60, "session.list never saw the finished job"); + std::thread::sleep(std::time::Duration::from_millis(5)); + } + let history = h.handle("doc.inspect", json!({})).unwrap()["history"].clone(); + assert_eq!(history.as_array().unwrap().last().unwrap(), "Gaussian Blur", "{history}"); + h.handle("doc.save", json!({"path": after.to_string_lossy()})).unwrap(); + let decode = |p: &std::path::Path| photocraft_codecs::decode(&std::fs::read(p).unwrap()).unwrap().to_rgba8(); + assert_ne!(decode(&before), decode(&after), "the export holds the blur"); + assert_ne!(render(&mut h), unblurred, "the preview holds the blur"); + std::fs::remove_dir_all(dir).unwrap(); +} + +/// Regression: `quality` 85.0 or "85" was ignored (a lossless WebP, reply ok) and 0 or 500 was +/// clamped, where the CLI refuses anything but a whole number from 1 to 100. +#[test] +fn doc_save_rejects_a_bad_quality_instead_of_ignoring_or_clamping_it() { + let dir = std::env::temp_dir().join(format!("pc-rpc-save-quality-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("x.webp"); + let mut h = Headless::trusted_local(); + h.handle("doc.new", json!({"width": 16, "height": 16})).unwrap(); + for q in [json!(85.0), json!("85"), json!(0), json!(500), json!(-5), json!(true)] { + let err = h.handle("doc.save", json!({"path": path.to_string_lossy(), "quality": q})).unwrap_err().to_string(); + assert!(err.contains("quality"), "{q}: {err}"); + assert!(!path.exists(), "{q} wrote a file"); + } + h.handle("doc.save", json!({"path": path.to_string_lossy(), "quality": 85})).unwrap(); + let bytes = std::fs::read(&path).unwrap(); + assert_eq!(bytes.get(12..16), Some(&b"VP8 "[..]), "a WebP saved with a quality is lossy"); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn automation_preview_rejects_oversized_full_size_and_numeric_wraparound() { + let mut h = Headless::new(); + h.handle("doc.new", json!({"width": 2049, "height": 1})).unwrap(); + for max in [json!(0), json!(2049), json!(u64::from(u32::MAX) + 1), json!(-1), json!(1.5)] { + assert!(h.handle("doc.render", json!({"maxSide": max})).is_err()); + } + // A smaller preview still works, and rejection leaves the source document intact. + let rendered = h.handle("doc.render", json!({"maxSide": 32})).unwrap(); + let png = base64::engine::general_purpose::STANDARD.decode(rendered["base64"].as_str().unwrap()).unwrap(); + assert_eq!(photocraft_codecs::decode(&png).unwrap().dimensions(), (32, 1)); + assert_eq!(h.session.active().unwrap().doc.size.width, 2049); +} + +#[test] +fn stdio_rejects_oversized_frames_before_dispatch() { + let h = Mutex::new(Headless::new()); + let input = " ".repeat(MAX_REQUEST_BYTES + 1); + let mut out = Vec::new(); + serve_lines(&h, input.as_bytes(), &mut out).unwrap(); + let reply: Value = serde_json::from_slice(&out).unwrap(); + assert_eq!(reply["ok"], false); + assert!(reply["error"].as_str().unwrap().contains("request exceeds")); + assert!(h.lock().unwrap().session.documents().is_empty()); +} + +/// Regression (#505): an over-long or non-UTF-8 line ended the stdio session, losing every +/// open document. Now it gets one error reply, the rest of the line is skipped (never +/// dispatched), and the next request is served. +#[test] +fn stdio_skips_a_rejected_line_and_keeps_the_session() { + let h = Mutex::new(Headless::new()); + let mut input = b"{\"id\":1,\"method\":\"doc.new\",\"params\":{\"width\":8,\"height\":8}}\n".to_vec(); + input.extend(" ".repeat(MAX_REQUEST_BYTES + 1).into_bytes()); + input.extend(b"{\"id\":9,\"method\":\"doc.close\"}\n"); + input.extend(b"\xff\xfe{\"id\":8,\"method\":\"doc.close\"}\n"); + input.extend(b"{\"id\":2,\"method\":\"session.list\"}\n"); + let mut out = Vec::new(); + serve_lines(&h, input.as_slice(), &mut out).unwrap(); + let replies: Vec = String::from_utf8(out).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect(); + assert_eq!(replies.len(), 4, "{replies:?}"); + assert_eq!(replies[0]["ok"], true); + assert!(replies[1]["error"].as_str().unwrap().contains("request exceeds"), "{}", replies[1]); + assert!(replies[2]["error"].as_str().unwrap().contains("not valid UTF-8"), "{}", replies[2]); + assert_eq!(replies[3]["id"], 2); + assert_eq!(replies[3]["result"]["documents"].as_array().unwrap().len(), 1, "the document stays open"); +} + +#[test] +fn preview_rejection_precedes_output_file_creation() { + let root = std::env::temp_dir().join(format!("pc-preview-budget-{}", std::process::id())); + std::fs::create_dir_all(&root).unwrap(); + let workspace = crate::AuthorizedWorkspace::new(None, Some(&root)).unwrap(); + let mut h = Headless::with_workspace(workspace); + h.handle("doc.new", json!({"width": 16, "height": 8})).unwrap(); + let result = h.handle("doc.render", json!({"maxSide": 2049, "path": "rejected.png"})); + assert!(result.unwrap_err().to_string().contains("preview side exceeds")); + assert!(!root.join("rejected.png").exists()); + assert!(h.handle("doc.render", json!({"maxSide": 16, "path": "accepted.png"})).is_ok()); + assert!(root.join("accepted.png").exists()); + // Release directory capabilities before cleanup on Windows. + drop(h); + std::fs::remove_file(root.join("accepted.png")).unwrap(); + std::fs::remove_dir(root).unwrap(); +} + +#[test] +fn doc_place_reads_through_the_read_root_and_never_outside_it() { + let base = std::env::temp_dir().join(format!("pc-doc-place-{}", std::process::id())); + let root = base.join("workspace"); + let outside = base.join("outside"); + for dir in [&root, &outside] { + std::fs::create_dir_all(dir).unwrap(); + } + let img = photocraft_codecs::Image::from_u8(8, 6, photocraft_codecs::ChannelLayout::Rgb, vec![42; 8 * 6 * 3]).unwrap(); + let png = photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap(); + std::fs::write(root.join("logo.png"), &png).unwrap(); + std::fs::write(outside.join("logo.png"), &png).unwrap(); + let absolute = outside.join("logo.png").to_string_lossy().into_owned(); + + let mut h = Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&root), Some(&root)).unwrap()); + h.handle("doc.new", json!({"width": 40, "height": 30})).unwrap(); + let placed = h.handle("doc.place", json!({"path": "logo.png", "scale": 50})).unwrap(); + assert!(placed["layer"].as_u64().is_some(), "{placed}"); + assert_eq!(placed["scale"].as_f64(), Some(50.0), "the options reach the command: {placed}"); + let inspected = h.handle("doc.inspect", json!({})).unwrap(); + assert_eq!(inspected["layers"].as_array().map(Vec::len), Some(2), "the placed layer is in the document: {inspected}"); + // A path outside the read root is refused the way the ambient command is (#2810). + for (path, reason) in [("../outside/logo.png", "parent traversal"), (absolute.as_str(), "must be inside the automation root")] { + let refused = h.handle("doc.place", json!({"path": path})).unwrap_err().to_string(); + assert!(refused.contains(reason), "{refused}"); + let inspected = h.handle("doc.inspect", json!({})).unwrap(); + assert_eq!(inspected["layers"].as_array().map(Vec::len), Some(2), "nothing was placed: {refused}"); + } + // Trusted local keeps the ambient command: that caller may read the path itself. + let mut t = Headless::trusted_local(); + t.handle("doc.new", json!({"width": 40, "height": 30})).unwrap(); + let trusted = t.handle("doc.place", json!({"path": root.join("logo.png").to_string_lossy()})).unwrap(); + assert!(trusted["layer"].as_u64().is_some(), "{trusted}"); + // Release directory capabilities before cleanup on Windows. + drop(t); + drop(h); + std::fs::remove_dir_all(base).unwrap(); +} + +#[test] +fn doc_replace_smart_object_reads_through_the_read_root_and_never_outside_it() { + let base = std::env::temp_dir().join(format!("pc-doc-replace-so-{}", std::process::id())); + let root = base.join("workspace"); + let outside = base.join("outside"); + for dir in [&root, &outside] { + std::fs::create_dir_all(dir).unwrap(); + } + let png = |w: u32, h: u32, v: u8| { + let img = photocraft_codecs::Image::from_u8(w, h, photocraft_codecs::ChannelLayout::Rgb, vec![v; (w * h * 3) as usize]).unwrap(); + photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap() + }; + std::fs::write(root.join("logo.png"), png(8, 6, 42)).unwrap(); + std::fs::write(root.join("red.png"), png(8, 6, 200)).unwrap(); + std::fs::write(outside.join("red.png"), png(8, 6, 200)).unwrap(); + let absolute = outside.join("red.png").to_string_lossy().into_owned(); + + let mut h = Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&root), Some(&root)).unwrap()); + h.handle("doc.new", json!({"width": 40, "height": 30})).unwrap(); + let layer = h.handle("doc.place", json!({"path": "logo.png"})).unwrap()["layer"].clone(); + // The smart object's file name and the composite at its centre: what Replace Contents changes. + let contents = |h: &mut Headless| { + let inspected = h.handle("doc.inspect", json!({})).unwrap(); + let layers = inspected["layers"].as_array().unwrap(); + let so = layers.iter().find(|l| l["id"] == layer).unwrap_or_else(|| panic!("{inspected}")); + let name = so["smartSource"]["fileName"].as_str().unwrap_or_default().to_owned(); + let rendered = h.handle("doc.render", json!({"maxSide": 0})).unwrap(); + let png = base64::engine::general_purpose::STANDARD.decode(rendered["base64"].as_str().unwrap()).unwrap(); + let img = photocraft_codecs::decode(&png).unwrap(); + let (w, ht) = img.dimensions(); + let data = img.as_u8().unwrap(); + let channels = data.len() / (w * ht) as usize; + (name, data[((ht / 2 * w + w / 2) as usize) * channels]) + }; + assert_eq!(contents(&mut h), ("logo.png".to_owned(), 42), "the placed contents"); + let replaced = h.handle("doc.replaceSmartObject", json!({"path": "red.png", "layer": layer})).unwrap(); + assert_eq!(replaced["layer"], layer, "{replaced}"); + assert_eq!(contents(&mut h), ("red.png".to_owned(), 200), "the contents were replaced"); + h.handle("engine.execute", json!({"command": "edit.undo"})).unwrap(); + assert_eq!(contents(&mut h), ("logo.png".to_owned(), 42), "one undo step restores the old contents"); + h.handle("engine.execute", json!({"command": "edit.redo"})).unwrap(); + assert_eq!(contents(&mut h), ("red.png".to_owned(), 200), "redo replaces them again"); + // Outside the read root, a bad layer, a missing path or a file that is no image: refused, nothing changed. + for (params, reason) in [ + (json!({"path": "../outside/red.png"}), "parent traversal"), + (json!({"path": absolute}), "must be inside the automation root"), + (json!({"path": "logo.png", "layer": 999_999}), "no such layer"), + (json!({}), "needs `path`"), + ] { + let refused = h.handle("doc.replaceSmartObject", params).unwrap_err().to_string(); + assert!(refused.contains(reason), "{refused}"); + assert_eq!(contents(&mut h), ("red.png".to_owned(), 200), "nothing changed: {refused}"); + } + std::fs::write(root.join("junk.png"), b"not an image").unwrap(); + assert!(h.handle("doc.replaceSmartObject", json!({"path": "junk.png", "layer": layer})).is_err()); + assert_eq!(contents(&mut h), ("red.png".to_owned(), 200), "a file that is no image changes nothing"); + // The ambient command keeps its refusal. + let ambient = h.handle("engine.execute", json!({"command": "layer.smartObjects.replaceContents", "params": {"path": "red.png"}})); + assert!(ambient.unwrap_err().to_string().contains("ambient filesystem paths")); + // Trusted local keeps the ambient command. + let mut t = Headless::trusted_local(); + t.handle("doc.new", json!({"width": 40, "height": 30})).unwrap(); + let tl = t.handle("doc.place", json!({"path": root.join("logo.png").to_string_lossy()})).unwrap()["layer"].clone(); + let trusted = t.handle("doc.replaceSmartObject", json!({"path": root.join("red.png").to_string_lossy(), "layer": tl})).unwrap(); + assert_eq!(trusted["layer"], tl, "{trusted}"); + drop(t); + drop(h); + std::fs::remove_dir_all(base).unwrap(); +} + +#[test] +fn doc_export_layers_reports_skips_in_workspace_and_trusted_sessions() { + for trusted in [false, true] { + let base = std::env::temp_dir().join(format!("pc-export-skips-{}-{trusted}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(&base).unwrap(); + let mut h = + if trusted { Headless::trusted_local() } else { Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&base), Some(&base)).unwrap()) }; + h.handle("doc.new", json!({"width": 4, "height": 4, "background": "white", "name": "card"})).unwrap(); + let adjustment = h.handle("engine.execute", json!({"command": "layer.newAdjustmentLayer.levels"})).unwrap()["layer"].clone(); + h.handle("engine.execute", json!({"command": "layer.setProps", "params": {"name": "Levels"}})).unwrap(); + let hidden = h.handle("engine.execute", json!({"command": "layer.new.layer", "params": {"name": "Hidden"}})).unwrap()["layer"].clone(); + h.handle("engine.execute", json!({"command": "layer.setProps", "params": {"visible": false}})).unwrap(); + // Exercise the actual JSON-lines serve envelope, not only direct dispatch. + let h = Mutex::new(h); + let out_dir = base.join("out").to_string_lossy().into_owned(); + let request = json!({"id": 8491, "method": "doc.exportLayers", "params": {"dir": out_dir}}).to_string() + "\n"; + let mut output = Vec::new(); + serve_lines(&h, request.as_bytes(), &mut output).unwrap(); + let reply: Value = serde_json::from_slice(&output).unwrap(); + assert_eq!(reply["id"], 8491); + assert_eq!(reply["ok"], true, "{reply}"); + assert_eq!(reply["result"]["files"], json!([format!("{out_dir}/card_0001_Background.png")])); + if !trusted { + assert_eq!(reply["result"]["count"], 1); + } + assert_eq!( + reply["result"]["skipped"], + json!([ + {"layer": hidden, "name": "Hidden", "reason": "hidden by visibleOnly"}, + {"layer": adjustment, "name": "Levels", "reason": "adjustment layer has no pixels of its own"} + ]) + ); + assert_eq!(std::fs::read_dir(base.join("out")).unwrap().count(), 1); + let mut h = h.into_inner().unwrap(); + let all_dir = base.join("all").to_string_lossy().into_owned(); + let all = h.export_layers(None, &all_dir, &json!({"visibleOnly": false})).unwrap(); + assert_eq!(all["files"].as_array().unwrap().len(), 2); + assert_eq!(all["skipped"].as_array().unwrap().len(), 1); + // Workspace no-overwrite errors still fail and remove only newly created files. + if !trusted { + let collision = base.join("collision"); + std::fs::create_dir_all(&collision).unwrap(); + std::fs::write(collision.join("card_0002_Background.png"), b"keep").unwrap(); + assert!(h.export_layers(None, &collision.to_string_lossy(), &json!({"visibleOnly": false})).is_err()); + assert_eq!(std::fs::read_dir(&collision).unwrap().count(), 1); + assert_eq!(std::fs::read(collision.join("card_0002_Background.png")).unwrap(), b"keep"); + } + drop(h); + std::fs::remove_dir_all(base).unwrap(); + } +} + +#[test] +fn doc_export_layers_writes_only_beneath_the_write_root() { + let base = std::env::temp_dir().join(format!("pc-doc-export-layers-{}", std::process::id())); + let root = base.join("workspace"); + std::fs::create_dir_all(&root).unwrap(); + let mut h = Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&root), Some(&root)).unwrap()); + h.handle("doc.new", json!({"width": 12, "height": 8, "background": "white", "name": "card"})).unwrap(); + h.handle("engine.execute", json!({"command": "layer.new.layer", "params": {"name": "Badge"}})).unwrap(); + + let out = root.join("out"); + let exported = h.handle("doc.exportLayers", json!({"dir": out.to_string_lossy(), "format": "png", "prefix": "card"})).unwrap(); + assert_eq!(exported["count"].as_u64(), Some(2), "{exported}"); + let mut names: Vec = std::fs::read_dir(&out).unwrap().map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()).collect(); + names.sort(); + assert_eq!(names.len(), 2, "{exported}"); + for name in names { + assert!(name.starts_with("card_") && name.ends_with(".png"), "{name}"); + let bytes = std::fs::read(out.join(&name)).unwrap(); + assert_eq!(photocraft_codecs::decode(&bytes).unwrap().dimensions(), (12, 8), "{name}"); + } + // Outside the write root nothing is created, not even the directory. + let escaped = base.join("escaped"); + let refused = h.handle("doc.exportLayers", json!({"dir": escaped.to_string_lossy()})).unwrap_err().to_string(); + assert!(refused.contains("must be inside the automation root"), "{refused}"); + assert!(!escaped.exists()); + // The ambient command keeps its refusal for the very same directory. + let ambient = + h.handle("engine.execute", json!({"command": "file.export.layersToFiles", "params": {"dir": out.to_string_lossy()}})).unwrap_err().to_string(); + assert!(ambient.contains("ambient filesystem paths"), "{ambient}"); + // Release directory capabilities before cleanup on Windows. + drop(h); + std::fs::remove_dir_all(base).unwrap(); +} + +#[test] +fn doc_export_data_sets_refuse_collisions_and_import_reads_the_root() { + let base = std::env::temp_dir().join(format!("pc-doc-data-sets-{}", std::process::id())); + let root = base.join("workspace"); + std::fs::create_dir_all(&root).unwrap(); + let mut h = Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&root), Some(&root)).unwrap()); + h.handle("doc.new", json!({"width": 8, "height": 8, "background": "white", "name": "card"})).unwrap(); + let inspected = h.handle("doc.inspect", json!({})).unwrap(); + let layer = inspected["layers"][0]["id"].as_u64().expect("the layer id"); + h.handle("engine.execute", json!({"command": "image.variables.define", "params": {"defs": [{"name": "show", "layer": layer, "type": "visibility"}]}})) + .unwrap(); + h.handle( + "engine.execute", + json!({"command": "image.variables.dataSets", "params": {"dataSets": [ + {"name": "one", "values": [{"variable": "show", "kind": "visibility", "value": true}]}, + {"name": "two", "values": [{"variable": "show", "kind": "visibility", "value": false}]}, + ]}}), + ) + .unwrap(); + + let sets = root.join("sets"); + let exported = h.handle("doc.exportDataSets", json!({"dir": sets.to_string_lossy(), "format": "png"})).unwrap(); + assert_eq!(exported["count"].as_u64(), Some(2), "{exported}"); + assert_eq!(std::fs::read_dir(&sets).unwrap().count(), 2, "{exported}"); + // Colliding names are refused as in the command, before any file is written. + let clash = root.join("clash"); + let refused = h.handle("doc.exportDataSets", json!({"dir": clash.to_string_lossy(), "naming": "{document}"})).unwrap_err().to_string(); + assert!(refused.contains("{index}"), "{refused}"); + assert_eq!(std::fs::read_dir(&clash).unwrap().count(), 0, "no file of the refused batch"); + // A CSV from the read root, and one outside it. + std::fs::write(root.join("sets.csv"), "Data Set,show\none,true\ntwo,false\n").unwrap(); + let imported = h.handle("doc.importDataSets", json!({"path": "sets.csv"})).unwrap(); + assert_eq!(imported["imported"].as_u64(), Some(2), "{imported}"); + std::fs::write(base.join("outside.csv"), "Data Set,show\none,true\n").unwrap(); + let outside = h.handle("doc.importDataSets", json!({"path": base.join("outside.csv").to_string_lossy()})).unwrap_err().to_string(); + assert!(outside.contains("must be inside the automation root"), "{outside}"); + // Release directory capabilities before cleanup on Windows. + drop(h); + std::fs::remove_dir_all(base).unwrap(); +} + +#[test] +fn indexed_place_replace_and_data_set_methods_keep_the_active_document() { + let base = std::env::temp_dir().join(format!("pc-doc-index-active-{}", std::process::id())); + let root = base.join("workspace"); + std::fs::create_dir_all(&root).unwrap(); + let img = photocraft_codecs::Image::from_u8(4, 4, photocraft_codecs::ChannelLayout::Rgb, vec![42; 4 * 4 * 3]).unwrap(); + std::fs::write(root.join("logo.png"), photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap()).unwrap(); + std::fs::write(root.join("sets.csv"), "Data Set,show\none,true\ntwo,false\n").unwrap(); + let mut h = Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&root), Some(&root)).unwrap()); + h.handle("doc.new", json!({"width": 8, "height": 8, "background": "white", "name": "first"})).unwrap(); + h.handle("doc.new", json!({"width": 8, "height": 8, "background": "white", "name": "second"})).unwrap(); + let layer = h.handle("doc.inspect", json!({})).unwrap()["layers"][0]["id"].as_u64().expect("the layer id"); + h.handle("engine.execute", json!({"command": "image.variables.define", "params": {"defs": [{"name": "show", "layer": layer, "type": "visibility"}]}})) + .unwrap(); + h.handle("doc.select", json!({"index": 0})).unwrap(); + + let steps = [ + ("doc.place", json!({"path": "logo.png", "index": 1}), true), + // Document 1's active layer is now the placed Smart Object. + ("doc.replaceSmartObject", json!({"path": "logo.png", "index": 1}), true), + ("doc.replaceSmartObject", json!({"path": "missing.png", "index": 1}), false), + ("doc.importDataSets", json!({"path": "sets.csv", "index": 1}), true), + ("doc.exportLayers", json!({"dir": "layers", "index": 1}), true), + ("doc.exportDataSets", json!({"dir": "sets", "index": 1}), true), + // A failing call restores the active document too. + ("doc.importDataSets", json!({"path": "missing.csv", "index": 1}), false), + ]; + for (method, params, succeeds) in steps { + let result = h.handle(method, params.clone()); + assert_eq!(result.is_ok(), succeeds, "{method} {params}: {result:?}"); + assert_eq!(h.session.active_index(), Some(0), "{method} {params} must not select document 1"); + } + assert_eq!(h.session.documents()[0].doc.layer_count(), 1, "nothing was placed into the active document"); + assert_eq!(h.session.documents()[1].doc.layer_count(), 2, "the placed layer is in document 1"); + assert_eq!(std::fs::read_dir(root.join("sets")).unwrap().count(), 2, "document 1's data sets were exported"); + // Release directory capabilities before cleanup on Windows. + drop(h); + std::fs::remove_dir_all(base).unwrap(); +} + +#[test] +fn doc_export_data_sets_judges_pixel_replacement_paths_like_apply() { + let base = std::env::temp_dir().join(format!("pc-doc-data-set-pixels-{}", std::process::id())); + let root = base.join("workspace"); + std::fs::create_dir_all(&root).unwrap(); + let red = photocraft_codecs::Image::from_u8(4, 4, photocraft_codecs::ChannelLayout::Rgb, [255, 0, 0].repeat(16)).unwrap(); + let photo = base.join("photo.png"); + std::fs::write(&photo, photocraft_codecs::encode(&red, photocraft_codecs::Format::Png, &Default::default()).unwrap()).unwrap(); + let mut h = Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&root), Some(&root)).unwrap()); + h.handle("doc.new", json!({"width": 8, "height": 8, "background": "white", "name": "card"})).unwrap(); + let layer = h.handle("engine.execute", json!({"command": "layer.new.layer", "params": {}})).unwrap()["layer"].clone(); + h.handle( + "engine.execute", + json!({"command": "image.variables.define", "params": {"defs": [{"name": "photo", "layer": layer, "type": "pixelReplacement"}]}}), + ) + .unwrap(); + // Storing the path is allowed; reading it is what the gate judges. + h.handle( + "engine.execute", + json!({"command": "image.variables.dataSets", "params": {"dataSets": [ + {"name": "swap", "values": [{"variable": "photo", "kind": "pixels", "value": photo.to_string_lossy()}]}, + ]}}), + ) + .unwrap(); + let applied = h.handle("engine.execute", json!({"command": "image.applyDataSet", "params": {"name": "swap"}})).unwrap_err().to_string(); + assert!(applied.contains("ambient filesystem paths"), "{applied}"); + let sets = root.join("sets"); + let exported = h.handle("doc.exportDataSets", json!({"dir": sets.to_string_lossy(), "format": "png"})).unwrap_err().to_string(); + assert!(exported.contains("ambient filesystem paths"), "{exported}"); + assert_eq!(std::fs::read_dir(&sets).map_or(0, Iterator::count), 0, "nothing of the refused batch is written"); + // Release directory capabilities before cleanup on Windows. + drop(h); + std::fs::remove_dir_all(base).unwrap(); +} + +#[test] +fn workspace_psd_saves_embed_no_file_a_linked_smart_object_names() { + use photocraft_engine::doc::{LayerContent, SmartSource}; + + // An image PhotoCraft can open (other linked files are never embedded): an embedded copy + // carries these exact bytes, while pixels written for the layer don't. + let image = photocraft_codecs::Image::from_u8(8, 8, photocraft_codecs::ChannelLayout::Rgb, (0..192u8).collect()).unwrap(); + let marker = photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap(); + let has_marker = |bytes: &[u8]| bytes.windows(marker.len()).any(|w| w == marker.as_slice()); + let base = std::env::temp_dir().join(format!("pc-psd-linked-embed-{}", std::process::id())); + let root = base.join("workspace"); + std::fs::create_dir_all(&root).unwrap(); + let outside = base.join("outside.png"); + std::fs::write(&outside, &marker).unwrap(); + // A document whose smart object names a file outside the roots as its source. + let mut session = photocraft_engine::Session::new(); + session.execute("file.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap(); + session.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + let state = session.active_mut().unwrap(); + let LayerContent::Smart(smart) = &mut std::sync::Arc::make_mut(&mut state.doc).layers[0].content else { panic!("smart object") }; + smart.source = SmartSource::Linked { path: outside.to_string_lossy().into_owned() }; + std::fs::write(root.join("in.pcraft"), photocraft_engine::smart_cmds::encode_source(&state.doc).unwrap()).unwrap(); + // A trusted export embeds the linked file, as before. + assert!(has_marker(&photocraft_io::export(&state.doc, "psd", &Default::default()).unwrap().bytes)); + + let mut h = Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&root), Some(&root)).unwrap()); + h.handle("doc.open", json!({"path": "in.pcraft"})).unwrap(); + let saved = h.handle("doc.save", json!({"path": "out.psd"})).unwrap(); + let warnings = saved["warnings"].to_string(); + assert!(warnings.contains("written as pixels"), "{warnings}"); + assert!(!has_marker(&std::fs::read(root.join("out.psd")).unwrap()), "the linked file outside the roots is not embedded"); + // Release directory capabilities before cleanup on Windows. + drop(h); + std::fs::remove_dir_all(base).unwrap(); +} + +#[test] +fn allowed_filters_do_not_rerender_a_smart_object_from_its_linked_file() { + use photocraft_engine::doc::{LayerContent, SmartSource}; + + let base = std::env::temp_dir().join(format!("pc-linked-rerender-{}", std::process::id())); + let root = base.join("workspace"); + std::fs::create_dir_all(&root).unwrap(); + let red = photocraft_codecs::Image::from_u8(8, 8, photocraft_codecs::ChannelLayout::Rgb, [255, 0, 0].repeat(64)).unwrap(); + let outside = base.join("red.png"); + std::fs::write(&outside, photocraft_codecs::encode(&red, photocraft_codecs::Format::Png, &Default::default()).unwrap()).unwrap(); + // A document whose white smart object names a file outside the roots as its source. + let mut session = photocraft_engine::Session::new(); + session.execute("file.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap(); + session.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + let state = session.active_mut().unwrap(); + let LayerContent::Smart(smart) = &mut std::sync::Arc::make_mut(&mut state.doc).layers[0].content else { panic!("smart object") }; + smart.source = SmartSource::Linked { path: outside.to_string_lossy().into_owned() }; + std::fs::write(root.join("p.pcraft"), photocraft_engine::smart_cmds::encode_source(&state.doc).unwrap()).unwrap(); + + let mut h = Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&root), Some(&root)).unwrap()); + h.handle("doc.open", json!({"path": "p.pcraft"})).unwrap(); + h.handle("engine.execute", json!({"command": "filter.blur.gaussianBlur", "params": {"radius": 0.5}})).unwrap(); + let doc = &h.session.active().unwrap().doc; + let LayerContent::Smart(smart) = &doc.layers[0].content else { panic!("smart object") }; + assert_eq!(smart.smart_filters.len(), 1, "the filter is still recorded"); + assert_eq!(smart.cache.as_ref().unwrap().rgba(4, 4), [1.0, 1.0, 1.0, 1.0], "the linked file outside the roots is not read"); + // Release directory capabilities before cleanup on Windows. + drop(h); + std::fs::remove_dir_all(base).unwrap(); +} + +#[test] +fn workspace_layer_exports_keep_linked_smart_objects_as_pixels() { + use photocraft_engine::doc::{LayerContent, SmartSource}; + + const MARKER: &[u8] = b"PHOTOCRAFT-LINKED-0002"; + let has_marker = |bytes: &[u8]| bytes.windows(MARKER.len()).any(|w| w == MARKER); + let base = std::env::temp_dir().join(format!("pc-export-layers-linked-{}", std::process::id())); + let root = base.join("workspace"); + std::fs::create_dir_all(&root).unwrap(); + let outside = base.join("outside.txt"); + std::fs::write(&outside, MARKER).unwrap(); + // A document whose smart object names a file outside the roots as its source. + let mut session = photocraft_engine::Session::new(); + session.execute("file.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap(); + session.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + let state = session.active_mut().unwrap(); + let LayerContent::Smart(smart) = &mut std::sync::Arc::make_mut(&mut state.doc).layers[0].content else { panic!("smart object") }; + smart.source = SmartSource::Linked { path: outside.to_string_lossy().into_owned() }; + std::fs::write(root.join("in.pcraft"), photocraft_engine::smart_cmds::encode_source(&state.doc).unwrap()).unwrap(); + + let mut h = Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&root), Some(&root)).unwrap()); + h.handle("doc.open", json!({"path": "in.pcraft"})).unwrap(); + let out = root.join("layers"); + for format in ["psd", "psb"] { + let exported = h.handle("doc.exportLayers", json!({"dir": out.to_string_lossy(), "format": format})).unwrap(); + assert_eq!(exported["count"], 1, "{exported}"); + } + let files: Vec<_> = std::fs::read_dir(&out).unwrap().map(|e| e.unwrap().path()).collect(); + assert_eq!(files.len(), 2, "{files:?}"); + for file in files { + assert!(!has_marker(&std::fs::read(&file).unwrap()), "{} embeds no file outside the roots", file.display()); + } + // Release directory capabilities before cleanup on Windows. + drop(h); + std::fs::remove_dir_all(base).unwrap(); +} + +#[test] +fn trusted_local_render_keeps_full_size_behavior() { + let mut h = Headless::trusted_local(); + h.handle("doc.new", json!({"width": 2049, "height": 1})).unwrap(); + let rendered = h.handle("doc.render", json!({"maxSide": 0})).unwrap(); + let png = base64::engine::general_purpose::STANDARD.decode(rendered["base64"].as_str().unwrap()).unwrap(); + assert_eq!(photocraft_codecs::decode(&png).unwrap().dimensions(), (2049, 1)); +} + +#[test] +fn methods_lists_the_job_methods_and_every_listed_name_is_served() { + let mut h = Headless::new(); + let listed = h.handle("methods", Value::Null).unwrap(); + let listed: Vec<&str> = listed.as_array().unwrap().iter().map(|m| m.as_str().unwrap()).collect(); + assert_eq!(listed, METHODS); + // The job methods `engine.execute {"wait": false}` depends on are discoverable (#414). + assert!(listed.contains(&"jobs.list") && listed.contains(&"jobs.cancel")); + for m in METHODS { + if let Err(e) = h.handle(m, Value::Null) { + assert!(!e.to_string().contains("unknown method"), "{m} is listed but not served: {e}"); + } + } + assert!(h.handle("jobs.nope", Value::Null).unwrap_err().to_string().contains("unknown method")); +} + +#[test] +fn batch_response_budget_stops_later_steps_even_when_stop_on_error_is_false() { + let mut h = Headless::new(); + let mut steps = vec![json!({"command": "command.list"}); MAX_BATCH_STEPS - 1]; + steps.push(json!({"command": "file.new", "params": {"width": 8, "height": 8}})); + let result = h.batch(&json!({"steps": steps, "stopOnError": false})).unwrap(); + assert_eq!(result["failed"], 1); + assert!(result["results"].as_array().unwrap().last().unwrap()["error"].as_str().unwrap().contains("batch response budget exceeded")); + assert!(h.session.documents().is_empty(), "later edit must not execute after the quota is exhausted"); + assert!(crate::budgets::json_bytes(&result).is_ok()); + assert!(h.handle("methods", Value::Null).is_ok()); +} + +#[test] +fn idle_tcp_daemon_releases_its_port_but_keeps_active_clients() { + use std::io::BufReader; + const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; + let h = Arc::new(Mutex::new(Headless::new())); + let (ready_tx, ready_rx) = std::sync::mpsc::channel(); + let (done_tx, done_rx) = std::sync::mpsc::channel(); + let server = std::thread::spawn(move || { + let result = serve_tcp_until_idle("127.0.0.1:0", h, TOKEN.to_owned(), move |addr| ready_tx.send(addr).unwrap(), Duration::from_millis(200)); + done_tx.send(result).unwrap(); + }); + let addr = ready_rx.recv_timeout(Duration::from_secs(2)).unwrap(); + let mut client = std::net::TcpStream::connect(addr).unwrap(); + client.set_read_timeout(Some(Duration::from_secs(2))).unwrap(); + let mut reader = BufReader::new(client.try_clone().unwrap()); + writeln!(client, r#"{{"id":"auth","method":"auth","params":{{"token":"{TOKEN}"}}}}"#).unwrap(); + let mut line = String::new(); + reader.read_line(&mut line).unwrap(); + let auth: Value = serde_json::from_str(&line).unwrap(); + assert_eq!(auth["result"]["authenticated"], true); + // The port stays owned well past the idle limit while a client is connected. + assert!(matches!(done_rx.recv_timeout(Duration::from_millis(450)), Err(std::sync::mpsc::RecvTimeoutError::Timeout)), "daemon exited with a live client"); + drop(reader); + drop(client); + assert!(done_rx.recv_timeout(Duration::from_secs(3)).unwrap().is_ok(), "idle daemon did not exit cleanly"); + server.join().unwrap(); + assert!(TcpListener::bind(addr).is_ok(), "idle listener still owns its port"); +} + +#[test] +fn tcp_serves_loopback() { + use std::io::{BufReader, Write as _}; + const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; + let h = Arc::new(Mutex::new(Headless::new())); + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let _ = serve_tcp("127.0.0.1:0", h, TOKEN.into(), move |a| tx.send(a).unwrap()); + }); + let addr = rx.recv().unwrap(); + let mut s = std::net::TcpStream::connect(addr).unwrap(); + writeln!(s, r#"{{"id":"auth","method":"auth","params":{{"token":"{TOKEN}"}}}}"#).unwrap(); + let mut reader = BufReader::new(s.try_clone().unwrap()); + let mut line = String::new(); + reader.read_line(&mut line).unwrap(); + let auth: Value = serde_json::from_str(&line).unwrap(); + assert_eq!(auth["result"]["authenticated"], true); + writeln!(s, r#"{{"id":"a","method":"methods"}}"#).unwrap(); + line.clear(); + reader.read_line(&mut line).unwrap(); + let v: Value = serde_json::from_str(&line).unwrap(); + assert_eq!(v["id"], "a"); + assert!(v["result"].as_array().unwrap().iter().any(|m| m == "batch")); +} + +/// #4965: a connection that keeps sending without authenticating is closed at the deadline, +/// and one that authenticated in time keeps being served after it. +#[test] +fn tcp_connections_must_authenticate_before_the_deadline_whatever_they_send() { + use std::io::{BufReader, Write as _}; + use std::time::{Duration, Instant}; + const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let server = std::thread::spawn(move || { + let h = Mutex::new(Headless::new()); + let mut results = Vec::new(); + for _ in 0..2 { + let (stream, _) = listener.accept().unwrap(); + let started = Instant::now(); + let r = serve_tcp_connection(&h, stream, TOKEN, Duration::from_millis(300)); + results.push((r.map_err(|e| e.kind()), started.elapsed())); + } + results + }); + + // Never a newline, a byte every 20 ms: each read succeeds long before the idle timeout. + let mut slow = std::net::TcpStream::connect(addr).unwrap(); + for _ in 0..150 { + if slow.write_all(b" ").is_err() { + break; + } + std::thread::sleep(Duration::from_millis(20)); + } + drop(slow); + + // Authenticates at once, then asks again 300 ms after the deadline. + let mut s = std::net::TcpStream::connect(addr).unwrap(); + s.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + writeln!(s, r#"{{"id":"auth","method":"auth","params":{{"token":"{TOKEN}"}}}}"#).unwrap(); + let mut reader = BufReader::new(s.try_clone().unwrap()); + let mut line = String::new(); + reader.read_line(&mut line).unwrap(); + assert_eq!(serde_json::from_str::(&line).unwrap()["result"]["authenticated"], true); + std::thread::sleep(Duration::from_millis(600)); + writeln!(s, r#"{{"id":"a","method":"methods"}}"#).unwrap(); + line.clear(); + reader.read_line(&mut line).unwrap(); + assert_eq!(serde_json::from_str::(&line).unwrap()["id"], "a"); + drop(reader); + drop(s); + + let results = server.join().unwrap(); + let (slow_result, slow_time) = &results[0]; + assert!(matches!(slow_result, Err(std::io::ErrorKind::TimedOut | std::io::ErrorKind::WouldBlock)), "{slow_result:?}"); + assert!(*slow_time < Duration::from_secs(3), "the trickle did not extend the deadline: {slow_time:?}"); + assert_eq!(results[1].0, Ok(()), "the authenticated connection ended with its client"); +} + +#[test] +fn tcp_repeat_auth_reports_already_authenticated_and_keeps_serving() { + use std::io::{BufReader, Write as _}; + const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; + let h = Arc::new(Mutex::new(Headless::new())); + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let _ = serve_tcp("127.0.0.1:0", h, TOKEN.into(), move |a| tx.send(a).unwrap()); + }); + let addr = rx.recv().unwrap(); + let mut s = std::net::TcpStream::connect(addr).unwrap(); + let mut reader = BufReader::new(s.try_clone().unwrap()); + let mut line = String::new(); + for id in ["auth", "again"] { + writeln!(s, r#"{{"id":"{id}","method":"auth","params":{{"token":"{TOKEN}"}}}}"#).unwrap(); + line.clear(); + reader.read_line(&mut line).unwrap(); + } + let again: Value = serde_json::from_str(&line).unwrap(); + assert_eq!(again["id"], "again"); + assert_eq!(again["ok"], false); + assert_eq!(again["error"], "already authenticated"); + writeln!(s, r#"{{"id":"m","method":"methods"}}"#).unwrap(); + line.clear(); + reader.read_line(&mut line).unwrap(); + let v: Value = serde_json::from_str(&line).unwrap(); + assert_eq!(v["id"], "m"); + assert_eq!(v["ok"], true); +} + +#[test] +fn tcp_rejects_requests_before_authentication() { + use std::io::{BufReader, Write as _}; + const TOKEN: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + let h = Arc::new(Mutex::new(Headless::new())); + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let _ = serve_tcp("127.0.0.1:0", h, TOKEN.into(), move |a| tx.send(a).unwrap()); + }); + let addr = rx.recv().unwrap(); + let mut s = std::net::TcpStream::connect(addr).unwrap(); + writeln!(s, r#"{{"id":1,"method":"methods"}}"#).unwrap(); + let mut line = String::new(); + BufReader::new(s).read_line(&mut line).unwrap(); + let v: Value = serde_json::from_str(&line).unwrap(); + assert_eq!(v["ok"], false); + assert_eq!(v["error"], "authentication required"); + assert!(v.get("result").is_none()); +} + +#[test] +fn invalid_document_index_is_rejected_not_the_active_document() { + let h = session(); + for _ in 0..2 { + assert_eq!(respond(&h, r#"{"method":"doc.new","params":{"width":8,"height":8}}"#)["ok"], true); + } + let count = |h: &Mutex| h.lock().unwrap().session_list()["documents"].as_array().unwrap().len(); + for index in [json!("0"), json!(-1), json!(0.5), json!(true)] { + for method in ["doc.close", "doc.inspect", "doc.select"] { + let reply = respond(&h, &json!({"method": method, "params": {"index": index}}).to_string()); + assert_eq!(reply["ok"], false, "{method} {index}: {reply}"); + assert!(reply["error"].as_str().unwrap().contains("`index` must be a non-negative integer"), "{reply}"); + } + assert_eq!(count(&h), 2, "index {index} closed a document"); + } + // Null means "the active document", like a missing `index`. + assert_eq!(respond(&h, r#"{"method":"doc.inspect","params":{"index":null}}"#)["ok"], true); + // A valid index still closes that document. + let reply = respond(&h, r#"{"method":"doc.close","params":{"index":0}}"#); + assert_eq!(reply["ok"], true, "{reply}"); + assert_eq!(count(&h), 1); +} diff --git a/crates/automation/src/workspace.rs b/crates/automation/src/workspace.rs index 12e7329180..13cbbb2169 100644 --- a/crates/automation/src/workspace.rs +++ b/crates/automation/src/workspace.rs @@ -483,598 +483,4 @@ impl Drop for ExportSequence { } #[cfg(test)] -mod tests { - use super::*; - - fn roots(name: &str) -> (PathBuf, PathBuf, AuthorizedWorkspace) { - let base = std::env::temp_dir().join(format!("photocraft-workspace-{}-{name}", std::process::id())); - let inside = base.join("inside"); - let outside = base.join("outside"); - let _ = std::fs::remove_dir_all(&base); - std::fs::create_dir_all(&inside).unwrap(); - std::fs::create_dir_all(&outside).unwrap(); - let workspace = AuthorizedWorkspace::new(Some(&inside), Some(&inside)).unwrap(); - (inside, outside, workspace) - } - - #[test] - fn export_cleanup_owns_only_created_files_even_during_unwind() { - let (inside, _, workspace) = roots("export-cleanup"); - std::fs::create_dir(inside.join("frames")).unwrap(); - std::fs::write(inside.join("frames/clip_0009.png"), b"old").unwrap(); - let panic = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - let mut export = workspace.export_sequence("frames").unwrap(); - export.write("clip_0000.png", b"new").unwrap(); - assert!(export.write("clip_0009.png", b"overwrite").is_err()); - assert!(export.write("../escape.png", b"escape").is_err()); - panic!("rendering panic"); - })); - assert!(panic.is_err()); - assert_eq!(std::fs::read_dir(inside.join("frames")).unwrap().count(), 1); - assert_eq!(std::fs::read(inside.join("frames/clip_0009.png")).unwrap(), b"old"); - assert!(AuthorizedWorkspace::default().export_sequence("frames").is_err()); - } - - #[cfg(unix)] - #[test] - fn export_directory_symlinks_cannot_escape_the_granted_root() { - let (inside, outside, workspace) = roots("export-symlink"); - std::os::unix::fs::symlink(&outside, inside.join("escape")).unwrap(); - assert!(workspace.export_sequence("escape").is_err()); - assert_eq!(std::fs::read_dir(outside).unwrap().count(), 0); - } - - #[test] - fn valid_read_and_nonexistent_output_write_stay_in_root() { - let (inside, _, workspace) = roots("valid"); - std::fs::write(inside.join("read.txt"), b"canary").unwrap(); - assert_eq!(workspace.read("read.txt").unwrap(), b"canary"); - workspace.write("new-output.txt", b"created").unwrap(); - assert_eq!(std::fs::read(inside.join("new-output.txt")).unwrap(), b"created"); - } - - #[test] - fn large_observed_length_does_not_trigger_a_fixed_limit_or_upfront_reservation() { - let mut shortened = std::io::Cursor::new(b"psb"); - assert_eq!(read_to_observed_length(&mut shortened, (1 << 30) + 1).unwrap(), b"psb"); - } - - #[test] - fn read_growth_is_rejected_at_the_observed_length() { - let mut growing = std::io::repeat(b'x').take(65); - let error = read_to_observed_length(&mut growing, 64).unwrap_err().to_string(); - assert!(error.contains("grew beyond its observed length of 64 bytes"), "{error}"); - let mut allowed = std::io::repeat(b'x').take(64); - assert_eq!(read_to_observed_length(&mut allowed, 64).unwrap().len(), 64); - let mut empty = std::io::Cursor::new(b"x"); - assert!(read_to_observed_length(&mut empty, 0).is_err()); - } - - #[test] - fn open_pcraft_loads_a_directory_below_the_read_root() { - let (inside, _, workspace) = roots("pcraft-dir"); - let doc = photocraft_doc::Document::new("Native", photocraft_doc::Size::new(16, 12), photocraft_doc::ColorMode::Rgb, photocraft_doc::SampleType::U8); - photocraft_format::PcraftWriter::new().save_dir(&doc, &inside.join("native.pcraft"), &photocraft_format::SaveOptions::default()).unwrap(); - let loaded = workspace.open_pcraft("native.pcraft").unwrap().expect("the directory form loads"); - assert_eq!(loaded.name, doc.name); - assert_eq!((loaded.size.width, loaded.size.height), (16, 12)); - } - - #[test] - fn open_pcraft_reports_zip_files_and_missing_paths_clearly() { - let (inside, _, workspace) = roots("pcraft-errors"); - let doc = photocraft_doc::Document::new("Zipped", photocraft_doc::Size::new(4, 4), photocraft_doc::ColorMode::Rgb, photocraft_doc::SampleType::U8); - let zip = inside.join("zipped.pcraft"); - photocraft_format::PcraftWriter::new().save_path(&doc, &zip, &photocraft_format::SaveOptions::default()).unwrap(); - assert!(zip.is_file()); - assert!(workspace.open_pcraft("zipped.pcraft").unwrap().is_none(), "the zip form falls back to the bytes path"); - let error = workspace.open_pcraft("missing.pcraft").unwrap_err().to_string(); - assert!(error.contains("failed"), "a missing path propagates its io error: {error}"); - assert!(AuthorizedWorkspace::default().open_pcraft("x.pcraft").is_err(), "no read authority fails closed"); - } - - #[cfg(unix)] - #[test] - fn open_pcraft_rejects_non_regular_entries_and_escaping_symlinks() { - let (inside, _, workspace) = roots("pcraft-nonregular"); - let bundle = inside.join("native.pcraft"); - std::fs::create_dir_all(bundle.join("manifest.json")).unwrap(); - let error = workspace.open_pcraft("native.pcraft").unwrap_err().to_string(); - assert!(error.contains("not a regular file"), "a directory entry is refused, not streamed: {error}"); - - let (inside2, _, workspace2) = roots("pcraft-symlink"); - let bundle2 = inside2.join("native.pcraft"); - std::fs::create_dir(&bundle2).unwrap(); - std::os::unix::fs::symlink("/dev/zero", bundle2.join("manifest.json")).unwrap(); - assert!(workspace2.open_pcraft("native.pcraft").is_err(), "an escaping symlink entry is refused"); - } - - fn temp_files(dir: &Path) -> Vec { - std::fs::read_dir(dir).unwrap().flatten().map(|e| e.file_name().to_string_lossy().into_owned()).filter(|n| n.ends_with(".tmp")).collect() - } - - #[test] - fn write_replaces_atomically_and_leaves_no_temp_file() { - let (inside, _, workspace) = roots("atomic"); - std::fs::create_dir_all(inside.join("sub")).unwrap(); - workspace.write("sub/out.psd", b"original").unwrap(); - workspace.write("sub/out.psd", b"replacement").unwrap(); - assert_eq!(std::fs::read(inside.join("sub/out.psd")).unwrap(), b"replacement"); - assert!(temp_files(&inside.join("sub")).is_empty()); - // Renaming over a directory fails: nothing is left behind and the directory survives. - std::fs::create_dir_all(inside.join("adir")).unwrap(); - assert!(workspace.write("adir", b"x").is_err()); - assert!(inside.join("adir").is_dir()); - assert!(temp_files(&inside).is_empty()); - } - - /// #7095: replacing a file through the automation path keeps the old file's extended - /// attributes, the same as a save through `atomic_write` does. - #[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))] - #[test] - fn write_keeps_the_replaced_files_extended_attributes() { - #[cfg(target_os = "macos")] - const TAG: &str = "com.apple.metadata:_kMDItemUserTags"; - #[cfg(not(target_os = "macos"))] - const TAG: &str = "user.photocraft.test"; - - let (inside, _, workspace) = roots("xattr"); - let path = inside.join("doc.psd"); - workspace.write("doc.psd", b"original").unwrap(); - if rustix::fs::setxattr(&path, TAG, b"tagged", rustix::fs::XattrFlags::empty()).is_err() { - return; // a file system without extended attributes: nothing to assert - } - - workspace.write("doc.psd", b"replacement, longer").unwrap(); - - assert_eq!(std::fs::read(&path).unwrap(), b"replacement, longer"); - let mut buf = [0u8; 64]; - let len = rustix::fs::getxattr(&path, TAG, buf.as_mut_slice()).expect("the attribute was dropped"); - assert_eq!(&buf[..len], b"tagged"); - assert!(temp_files(&inside).is_empty()); - } - - #[cfg(unix)] - #[test] - fn write_into_read_only_folder_keeps_the_original() { - use std::os::unix::fs::PermissionsExt; - let (inside, _, workspace) = roots("readonly"); - let ro = inside.join("ro"); - std::fs::create_dir_all(&ro).unwrap(); - std::fs::write(ro.join("doc.psd"), b"original").unwrap(); - std::fs::set_permissions(&ro, std::fs::Permissions::from_mode(0o555)).unwrap(); - let root_user = std::fs::File::create(ro.join("probe")).is_ok(); - if !root_user { - assert!(workspace.write("ro/doc.psd", b"new").is_err()); - assert_eq!(std::fs::read(ro.join("doc.psd")).unwrap(), b"original"); - assert!(temp_files(&ro).is_empty()); - } - std::fs::set_permissions(&ro, std::fs::Permissions::from_mode(0o755)).unwrap(); - } - - #[test] - fn rejects_absolute_traversal_mixed_prefix_and_malformed_paths_without_panicking() { - let (_, _, workspace) = roots("reject"); - for path in [ - "", - "/absolute", - "../escape", - "a/../escape", - "a\\..\\escape", - "a\\b", - "C:/escape", - "a//b", - "./a", - "name:stream", - "NUL", - "con.txt", - "folder/COM1.log", - ] { - assert!(workspace.read(path).is_err(), "read accepted {path:?}"); - assert!(workspace.write(path, b"x").is_err(), "write accepted {path:?}"); - } - } - - #[test] - fn read_and_write_authority_are_separate() { - let (inside, _, _) = roots("separate"); - std::fs::write(inside.join("read.txt"), b"canary").unwrap(); - let read_only = AuthorizedWorkspace::new(Some(&inside), None).unwrap(); - assert_eq!(read_only.read("read.txt").unwrap(), b"canary"); - assert!(read_only.write("blocked.txt", b"x").is_err()); - let write_only = AuthorizedWorkspace::new(None, Some(&inside)).unwrap(); - assert!(write_only.read("read.txt").is_err()); - write_only.write("written.txt", b"ok").unwrap(); - } - - #[test] - fn missing_parent_is_a_stable_error_before_any_file_is_created() { - let (inside, _, workspace) = roots("missing-parent"); - let error = workspace.write("missing/output.txt", b"x").unwrap_err().to_string(); - assert!(error.contains("automation write"), "{error}"); - assert!(!inside.join("missing").exists()); - } - - #[cfg(unix)] - #[test] - fn symlink_escape_is_rejected() { - use std::os::unix::fs::symlink; - - let (inside, outside, workspace) = roots("symlink"); - std::fs::write(outside.join("secret.txt"), b"outside").unwrap(); - symlink(&outside, inside.join("link")).unwrap(); - assert!(workspace.read("link/secret.txt").is_err()); - assert!(workspace.write("link/new.txt", b"blocked").is_err()); - assert!(!outside.join("new.txt").exists()); - } - - #[cfg(windows)] - #[test] - fn windows_symlink_escape_is_rejected_when_supported() { - use std::os::windows::fs::symlink_dir; - - let (inside, outside, workspace) = roots("windows-link"); - std::fs::write(outside.join("secret.txt"), b"outside").unwrap(); - if symlink_dir(&outside, inside.join("link")).is_err() { - return; - } - assert!(workspace.read("link/secret.txt").is_err()); - assert!(workspace.write("link/new.txt", b"blocked").is_err()); - assert!(!outside.join("new.txt").exists()); - } - - #[cfg(windows)] - #[test] - fn windows_junction_escape_is_rejected_when_supported() { - use std::process::Command; - - let (inside, outside, workspace) = roots("windows-junction"); - std::fs::write(outside.join("secret.txt"), b"outside").unwrap(); - let link = inside.join("junction"); - let status = Command::new("cmd.exe").args(["/D", "/C", "mklink", "/J"]).arg(&link).arg(&outside).status(); - if !status.is_ok_and(|status| status.success()) { - return; - } - assert!(workspace.read("junction/secret.txt").is_err()); - assert!(workspace.write("junction/new.txt", b"blocked").is_err()); - assert!(!outside.join("new.txt").exists()); - let _ = std::fs::remove_dir(link); - } - - #[test] - fn filesystem_commands_fail_closed() { - for id in [ - "file.open", - "file.openAs", - "file.save", - "file.saveAs", - "file.saveACopy", - "file.export.saveForWebLegacy", - "pattern.import", - "layer.smartObjects.exportContents", - "layer.smartObjects.replaceContents", - "layer.smartObjects.relinkToFile", - "layer.smartObjects.convertToLinked", - "measurementLog.export", - "layer.videoLayers.reloadFrame", - "edit.colorSettings", - ] { - assert!(authorize_engine_command(id, &serde_json::json!({})).is_err()); - } - assert!(authorize_engine_command("file.new", &serde_json::json!({})).is_ok()); - assert!(authorize_engine_command("file.automate.cropAndStraightenPhotos", &serde_json::json!({})).is_ok()); - assert!(authorize_desktop_engine_command("file.automate.cropAndStraightenPhotos", &serde_json::json!({})).is_ok()); - for id in ["layer.smartObjects.editContents", "layer.smartObjects.convertToLayers", "layer.smartObjects.saveContents"] { - assert!(authorize_desktop_engine_command(id, &serde_json::json!({"layer": 19})).is_ok(), "{id}"); - } - for id in ["layer.smartObjects.editContents", "layer.smartObjects.convertToLayers"] { - assert!(authorize_engine_command(id, &serde_json::json!({"path": "/outside/source.psb"})).is_err(), "{id}"); - } - // The UI-level examples in docs/control-protocol.md. - for id in ["view.zoomIn", "window.theme.pro", "edit.search"] { - assert!(authorize_desktop_engine_command(id, &serde_json::json!({})).is_ok(), "{id}"); - } - assert!(authorize_engine_command("image.mode.cmyk", &serde_json::json!({})).is_ok()); - assert!(authorize_desktop_engine_command("image.mode.cmyk", &serde_json::json!({})).is_err()); - assert!(authorize_engine_command("image.mode.rgb", &serde_json::json!({"profile": "/outside/profile.icc"})).is_err()); - assert!(authorize_engine_command("image.mode.rgb", &serde_json::json!({"profile": "srgb"})).is_ok()); - assert!(authorize_engine_command("file.new", &serde_json::json!({"profile": "/outside/profile.icc"})).is_err()); - assert!(authorize_engine_command("file.new", &serde_json::json!({"profile": "adobe-rgb-compat"})).is_ok()); - assert!(authorize_engine_command("file.new", &serde_json::json!({"profile": "working"})).is_ok()); - assert!(authorize_engine_command("file.new", &serde_json::json!({"profile": "none"})).is_ok()); - assert!(authorize_engine_command("file.new", &serde_json::json!({"profile": "default"})).is_err()); - assert!(authorize_engine_command("file.new", &serde_json::json!({"profile": "working-cmyk"})).is_err()); - // Shortcut sets: text in and out is fine; a path reads or writes the filesystem. - let ks = |p: serde_json::Value| authorize_engine_command("edit.keyboardShortcuts", &p); - assert!(ks(serde_json::json!({"exportKys": true, "summarize": true, "importKys": ""})).is_ok()); - for key in ["importKys", "exportKys", "summarize"] { - assert!(ks(serde_json::json!({ key: {"path": "/outside/set.kys"} })).is_err(), "{key}"); - } - assert!(authorize_engine_command("filter.distort.displace", &serde_json::json!({"mapPath": "outside.png"})).is_err()); - assert!(authorize_engine_command("layer.setAdjustment", &serde_json::json!({"file": "outside.cube"})).is_err()); - assert!(authorize_engine_command("prefs.set", &serde_json::json!({"path": "colorSettings.workingRgb", "value": "outside.icc"})).is_err()); - assert!(authorize_engine_step("file.open", &serde_json::json!({})).is_err()); - assert!(authorize_engine_step("actions.play", &serde_json::json!({})).is_ok()); - // An allowed command can't reach a denied one by running it on its own behalf. - let mut session = photocraft_engine::Session::new(); - session.execute("file.new", serde_json::json!({"width": 4, "height": 4})).unwrap(); - session.authorize = Some(authorize_desktop_engine_step); - let params = serde_json::json!({"to": "grayscale"}); - assert!(authorize_desktop_engine_command("file.automate.conditionalModeChange", ¶ms).is_ok()); - assert!(session.execute("file.automate.conditionalModeChange", params).is_err()); - assert_eq!(session.active().unwrap().doc.mode, photocraft_engine::doc::ColorMode::Rgb); - assert!(authorize_desktop_engine_step("file.saveACopy", &serde_json::json!({})).is_err()); - } - - // Regression test for #3763: `edit.installedProfiles` scans the OS and user ICC folders but - // takes no path parameter, so automation let it through until it was listed as ambient. - #[test] - fn installed_profiles_listing_is_refused_for_automation() { - for params in [serde_json::json!({}), serde_json::json!({"class": "output", "colorSpace": "cmyk"})] { - assert!(authorize_engine_command("edit.installedProfiles", ¶ms).is_err(), "authorize_engine_command allowed it with {params}"); - assert!(authorize_desktop_engine_command("edit.installedProfiles", ¶ms).is_err(), "authorize_desktop_engine_command allowed it with {params}"); - assert!(authorize_engine_step("edit.installedProfiles", ¶ms).is_err(), "authorize_engine_step allowed it with {params}"); - } - // The sandboxed session refuses it before the engine scans any folder. - let mut headless = crate::Headless::new(); - let refused = headless.command_run("edit.installedProfiles", serde_json::json!({})).unwrap_err(); - assert!(refused.to_string().contains("ambient filesystem paths"), "{refused}"); - } - - #[test] - fn apply_data_set_is_judged_by_the_values_it_applies() { - let mut headless = crate::Headless::new(); - headless.command_run("file.new", serde_json::json!({"width": 8, "height": 8})).unwrap(); - let layer = headless.command_run("layer.new.layer", serde_json::json!({})).unwrap()["layer"].clone(); - let defs = [ - serde_json::json!({"name": "shown", "layer": layer, "type": "visibility"}), - serde_json::json!({"name": "photo", "layer": layer, "type": "pixelReplacement"}), - ]; - headless.command_run("image.variables.define", serde_json::json!({"defs": defs})).unwrap(); - let sets = serde_json::json!({"dataSets": [ - {"name": "hidden", "values": [{"variable": "shown", "kind": "visibility", "value": false}]}, - {"name": "swap", "values": [ - {"variable": "shown", "kind": "visibility", "value": false}, - {"variable": "photo", "kind": "pixels", "value": "/outside/photo.png"}, - ]}, - ]}); - headless.command_run("image.variables.dataSets", sets).unwrap(); - let visible = |headless: &crate::Headless| headless.session.active().unwrap().doc.layers.iter().all(|l| l.visible); - let refused = headless.command_run("image.applyDataSet", serde_json::json!({"name": "swap"})).unwrap_err(); - assert!(refused.to_string().contains("ambient filesystem paths"), "{refused}"); - assert!(visible(&headless), "a refused data set applies none of its values"); - assert!(headless.command_run("image.applyDataSet", serde_json::json!({"name": "hidden"})).is_ok()); - assert!(!visible(&headless)); - } - - #[test] - fn automation_rejects_ambient_path_commands_and_preferences() { - for (id, params) in [ - ("brush.presets.importAbr", serde_json::json!({"path": "/outside/set.abr"})), - ("brush.presets.importImage", serde_json::json!({"path": "/outside/tip.png"})), - ("gradient.presets.importGrd", serde_json::json!({"path": "/outside/set.grd"})), - ("plugin.install", serde_json::json!({"path": "/outside/plugin.wasm"})), - ("plugin.reload", serde_json::json!({"path": "/outside/plugins"})), - ("plugin.reload", serde_json::json!({})), - ("plugin.install", serde_json::json!({"path": " "})), - ("swatches.import", serde_json::json!({"path": "/outside/set.aco"})), - ("swatches.export", serde_json::json!({"path": "/outside/set.ase"})), - ("actions.load", serde_json::json!({"path": "/outside/set.atn"})), - ("actions.save", serde_json::json!({"path": "/outside/set.atn"})), - ("style.presets.importAsl", serde_json::json!({"path": "/outside/set.asl"})), - ("style.presets.exportAsl", serde_json::json!({"path": "/outside/set.asl"})), - ("style.presets.exportAsl", serde_json::json!({"path": 5})), - ("layer.layerStyle.contours.load", serde_json::json!({"path": "/outside/set.shc"})), - ("layer.layerStyle.contours.save", serde_json::json!({"path": "/outside/set.shc"})), - ] { - assert!(authorize_engine_command(id, ¶ms).is_err(), "{id}: {params}"); - } - for (id, params) in [ - ("brush.presets.importAbr", serde_json::json!({"data": "QUJD"})), - ("brush.presets.importImage", serde_json::json!({"data": "QUJD"})), - ("gradient.presets.importGrd", serde_json::json!({"data": "QUJD"})), - ("plugin.install", serde_json::json!({"data": "QUJD"})), - ("swatches.import", serde_json::json!({"data": "QUJD"})), - ("swatches.export", serde_json::json!({"format": "ase"})), - ("actions.load", serde_json::json!({"data": "QUJD"})), - ("actions.save", serde_json::json!({"set": "S"})), - ("style.presets.importAsl", serde_json::json!({"data": "QUJD"})), - ("style.presets.exportAsl", serde_json::json!({"group": "Basics"})), - ("layer.layerStyle.contours.load", serde_json::json!({"data": "QUJD"})), - ("layer.layerStyle.contours.save", serde_json::json!({"names": ["a"]})), - ] { - assert!(authorize_engine_command(id, ¶ms).is_ok(), "{id}: {params}"); - } - for path in [ - "", - "colorSettings", - "colorSettings.workingRgb", - "scriptEvents", - "scriptEvents.enabled", - ".scriptEvents", - ".scriptEvents.enabled", - "historyLog.filePath", - ".historyLog.filePath", - "plugIns.additionalPluginsFolder", - "fileHandling.lutFolder", - "fileHandling", - "scratchDisks.disks", - ".", - "..historyLog.filePath", - ] { - assert!(authorize_engine_command("prefs.set", &serde_json::json!({"path": path, "value": {}})).is_err(), "{path}"); - } - assert!( - authorize_engine_command("prefs.set", &serde_json::json!({"values": {"interface.language": "fr", "historyLog.filePath": "/outside/log"}})).is_err() - ); - assert!(authorize_engine_command("prefs.set", &serde_json::json!({"path": "interface.language", "value": "fr"})).is_ok()); - assert!(authorize_engine_command("prefs.set", &serde_json::json!({"path": "fileHandling.autosave", "value": false})).is_ok()); - } - - #[test] - fn registry_filesystem_path_params_are_classified() { - let probe = serde_json::json!({ - "path": "/outside/photocraft-probe", - "file": "/outside/photocraft-probe.icc", - "mapPath": "/outside/photocraft-probe.png", - "profile": "/outside/photocraft-probe.icc", - "workingRgb": "/outside/photocraft-probe.icc", - "workingCmyk": "/outside/photocraft-probe.icc", - "workingGray": "/outside/photocraft-probe.icc", - "input": "/outside/photocraft-input", - "output": "/outside/photocraft-output", - "paths": ["/outside/photocraft-probe.psd"], - }); - let preference_probe = serde_json::json!({"path": ".scriptEvents", "value": {}}); - let unclassified: Vec<_> = photocraft_engine::command_specs() - .iter() - .filter(|spec| documents_filesystem_path_params(spec.id, spec.params)) - .filter(|spec| { - let params = if spec.id == "prefs.set" { &preference_probe } else { &probe }; - authorize_engine_command(spec.id, params).is_ok() - }) - .map(|spec| spec.id) - .collect(); - assert!(unclassified.is_empty(), "filesystem path parameters in the command registry need an automation policy: {unclassified:?}"); - } - - fn documents_filesystem_path_params(id: &str, params: &str) -> bool { - // These commands return settings or installed-profile paths; they do not accept a host - // filesystem path as an automation input. - if matches!(id, "prefs.get" | "prefs.reset" | "edit.installedProfiles") { - return false; - } - // These registry descriptions refer to document vector paths, not host files. - if matches!( - id, - "filter.blurGallery.pathBlur" - | "filter.render.flame" - | "shape.create" - | "shape.edit" - | "shape.info" - | "shape.presets.list" - | "shape.presets.new" - | "path.list" - | "path.info" - | "path.set" - | "path.transform" - | "path.moveAnchors" - | "path.moveHandle" - | "path.bendSegment" - | "path.convertPoint" - | "path.addAnchor" - | "path.deleteAnchor" - | "path.clippingPath.set" - | "path.rename" - | "path.stroke" - | "type.attachToPath" - | "type.fillPath" - | "type.detachFromPath" - | "select.toWorkPath" - | "layer.vectorMask.add" - | "layer.vectorMask.edit" - | "layer.vectorMask.info" - | "paint.symmetryFromPath" - | "edit.defineCustomShape" - | "layer.combineShapes.unite" - | "layer.combineShapes.subtractFrontShape" - | "layer.combineShapes.intersectShapeAreas" - | "layer.combineShapes.excludeOverlappingShapes" - | "layer.combineShapes.mergeShapeComponents" - ) || id.starts_with("layer.newFillLayer.") - || id.starts_with("layer.newAdjustmentLayer.") - { - // New fill and adjustment layers take a vector path as their vector mask (#1419). - return false; - } - params.to_ascii_lowercase().contains("path") - } - - #[test] - fn whole_preferences_update_cannot_enable_automation_script_events() { - let mut headless = crate::headless::Headless::new(); - let result = headless.command_run( - "prefs.set", - serde_json::json!({ - "path": "", - "value": { - "scriptEvents": { - "enabled": true, - "bindings": [{ - "event": "newDocument", - "steps": [["file.saveACopy", {"path": "/outside/canary.psd"}]] - }] - } - } - }), - ); - assert!(result.is_err()); - - for (id, params) in [ - ("brush.presets.importAbr", serde_json::json!({"path": "/outside/set.abr"})), - ("gradient.presets.importGrd", serde_json::json!({"path": "/outside/set.grd"})), - ("plugin.install", serde_json::json!({"path": "/outside/plugin.wasm"})), - ("plugin.reload", serde_json::json!({"path": "/outside/plugins"})), - ("style.presets.importAsl", serde_json::json!({"path": "/outside/set.asl"})), - ("style.presets.exportAsl", serde_json::json!({"path": "/outside/set.asl"})), - ("prefs.set", serde_json::json!({"path": "historyLog.filePath", "value": "/outside/log"})), - ("prefs.set", serde_json::json!({"values": {"interface.language": "fr", "historyLog.filePath": "/outside/log"}})), - ] { - assert!(headless.command_run(id, params).is_err(), "{id}"); - } - headless.command_run("file.new", serde_json::json!({"width": 5, "height": 5})).unwrap(); - assert!(headless.session.file_menu.event_log.is_empty()); - } - - /// #2176: an absolute path beneath the root names the same file as its relative path; every - /// other absolute path is refused before any file effect. - #[test] - fn absolute_paths_beneath_the_root_are_translated_and_others_refused() { - let (inside, outside, workspace) = roots("absolute-paths"); - let abs = |p: &Path| p.to_string_lossy().into_owned(); - - workspace.write(&abs(&inside.join("a.bin")), b"one").unwrap(); - assert_eq!(std::fs::read(inside.join("a.bin")).unwrap(), b"one"); - assert_eq!(workspace.read(&abs(&inside.join("a.bin"))).unwrap(), b"one"); - // Forward slashes too (on Windows the native spelling uses `\`). - assert_eq!(workspace.read(&abs(&inside.join("a.bin")).replace('\\', "/")).unwrap(), b"one"); - std::fs::create_dir(inside.join("sub")).unwrap(); - workspace.write(&abs(&inside.join("sub").join("b.bin")), b"two").unwrap(); - assert_eq!(std::fs::read(inside.join("sub/b.bin")).unwrap(), b"two"); - assert_eq!(workspace.read("sub/b.bin").unwrap(), b"two", "relative paths still work"); - - let refused = |path: String| { - let error = workspace.write(&path, b"x").unwrap_err().to_string(); - assert!(error.contains("automation path rejected"), "{path}: {error}"); - }; - refused(abs(&outside.join("escape.bin"))); - refused(abs(&inside.join("..").join("outside").join("traversal.bin"))); - refused(abs(&inside)); - refused(abs(&inside.join("CON"))); - refused(format!("{}:hidden", abs(&inside.join("a.bin")))); - // A sibling whose name merely starts with the root's name is not beneath it. - let sibling = inside.with_file_name("inside-sibling"); - std::fs::create_dir_all(&sibling).unwrap(); - refused(abs(&sibling.join("lookalike.bin"))); - refused(format!("{}-sibling/lookalike.bin", abs(&inside))); - // Climbing back out through a subdirectory is refused too. - refused(abs(&inside.join("sub").join("..").join("..").join("outside").join("climb.bin"))); - assert!(!sibling.join("lookalike.bin").exists()); - assert!(!outside.join("climb.bin").exists()); - assert!(!outside.join("escape.bin").exists()); - assert!(!outside.join("traversal.bin").exists()); - assert_eq!(std::fs::read(inside.join("a.bin")).unwrap(), b"one"); - } - - /// Each authority is checked against its own root, and none granted refuses absolute paths. - #[test] - fn absolute_paths_are_checked_against_the_authority_s_own_root() { - let (inside, outside, _) = roots("absolute-authority"); - let workspace = AuthorizedWorkspace::new(Some(&outside), Some(&inside)).unwrap(); - let target = inside.join("written.bin"); - workspace.write(&target.to_string_lossy(), b"w").unwrap(); - assert!(workspace.read(&target.to_string_lossy()).is_err(), "not under the read root"); - let none = AuthorizedWorkspace::default(); - assert!(none.read(&target.to_string_lossy()).is_err()); - } -} +mod tests; diff --git a/crates/automation/src/workspace/tests.rs b/crates/automation/src/workspace/tests.rs new file mode 100644 index 0000000000..2a94de15f2 --- /dev/null +++ b/crates/automation/src/workspace/tests.rs @@ -0,0 +1,581 @@ +use super::*; + +fn roots(name: &str) -> (PathBuf, PathBuf, AuthorizedWorkspace) { + let base = std::env::temp_dir().join(format!("photocraft-workspace-{}-{name}", std::process::id())); + let inside = base.join("inside"); + let outside = base.join("outside"); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(&inside).unwrap(); + std::fs::create_dir_all(&outside).unwrap(); + let workspace = AuthorizedWorkspace::new(Some(&inside), Some(&inside)).unwrap(); + (inside, outside, workspace) +} + +#[test] +fn export_cleanup_owns_only_created_files_even_during_unwind() { + let (inside, _, workspace) = roots("export-cleanup"); + std::fs::create_dir(inside.join("frames")).unwrap(); + std::fs::write(inside.join("frames/clip_0009.png"), b"old").unwrap(); + let panic = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let mut export = workspace.export_sequence("frames").unwrap(); + export.write("clip_0000.png", b"new").unwrap(); + assert!(export.write("clip_0009.png", b"overwrite").is_err()); + assert!(export.write("../escape.png", b"escape").is_err()); + panic!("rendering panic"); + })); + assert!(panic.is_err()); + assert_eq!(std::fs::read_dir(inside.join("frames")).unwrap().count(), 1); + assert_eq!(std::fs::read(inside.join("frames/clip_0009.png")).unwrap(), b"old"); + assert!(AuthorizedWorkspace::default().export_sequence("frames").is_err()); +} + +#[cfg(unix)] +#[test] +fn export_directory_symlinks_cannot_escape_the_granted_root() { + let (inside, outside, workspace) = roots("export-symlink"); + std::os::unix::fs::symlink(&outside, inside.join("escape")).unwrap(); + assert!(workspace.export_sequence("escape").is_err()); + assert_eq!(std::fs::read_dir(outside).unwrap().count(), 0); +} + +#[test] +fn valid_read_and_nonexistent_output_write_stay_in_root() { + let (inside, _, workspace) = roots("valid"); + std::fs::write(inside.join("read.txt"), b"canary").unwrap(); + assert_eq!(workspace.read("read.txt").unwrap(), b"canary"); + workspace.write("new-output.txt", b"created").unwrap(); + assert_eq!(std::fs::read(inside.join("new-output.txt")).unwrap(), b"created"); +} + +#[test] +fn large_observed_length_does_not_trigger_a_fixed_limit_or_upfront_reservation() { + let mut shortened = std::io::Cursor::new(b"psb"); + assert_eq!(read_to_observed_length(&mut shortened, (1 << 30) + 1).unwrap(), b"psb"); +} + +#[test] +fn read_growth_is_rejected_at_the_observed_length() { + let mut growing = std::io::repeat(b'x').take(65); + let error = read_to_observed_length(&mut growing, 64).unwrap_err().to_string(); + assert!(error.contains("grew beyond its observed length of 64 bytes"), "{error}"); + let mut allowed = std::io::repeat(b'x').take(64); + assert_eq!(read_to_observed_length(&mut allowed, 64).unwrap().len(), 64); + let mut empty = std::io::Cursor::new(b"x"); + assert!(read_to_observed_length(&mut empty, 0).is_err()); +} + +#[test] +fn open_pcraft_loads_a_directory_below_the_read_root() { + let (inside, _, workspace) = roots("pcraft-dir"); + let doc = photocraft_doc::Document::new("Native", photocraft_doc::Size::new(16, 12), photocraft_doc::ColorMode::Rgb, photocraft_doc::SampleType::U8); + photocraft_format::PcraftWriter::new().save_dir(&doc, &inside.join("native.pcraft"), &photocraft_format::SaveOptions::default()).unwrap(); + let loaded = workspace.open_pcraft("native.pcraft").unwrap().expect("the directory form loads"); + assert_eq!(loaded.name, doc.name); + assert_eq!((loaded.size.width, loaded.size.height), (16, 12)); +} + +#[test] +fn open_pcraft_reports_zip_files_and_missing_paths_clearly() { + let (inside, _, workspace) = roots("pcraft-errors"); + let doc = photocraft_doc::Document::new("Zipped", photocraft_doc::Size::new(4, 4), photocraft_doc::ColorMode::Rgb, photocraft_doc::SampleType::U8); + let zip = inside.join("zipped.pcraft"); + photocraft_format::PcraftWriter::new().save_path(&doc, &zip, &photocraft_format::SaveOptions::default()).unwrap(); + assert!(zip.is_file()); + assert!(workspace.open_pcraft("zipped.pcraft").unwrap().is_none(), "the zip form falls back to the bytes path"); + let error = workspace.open_pcraft("missing.pcraft").unwrap_err().to_string(); + assert!(error.contains("failed"), "a missing path propagates its io error: {error}"); + assert!(AuthorizedWorkspace::default().open_pcraft("x.pcraft").is_err(), "no read authority fails closed"); +} + +#[cfg(unix)] +#[test] +fn open_pcraft_rejects_non_regular_entries_and_escaping_symlinks() { + let (inside, _, workspace) = roots("pcraft-nonregular"); + let bundle = inside.join("native.pcraft"); + std::fs::create_dir_all(bundle.join("manifest.json")).unwrap(); + let error = workspace.open_pcraft("native.pcraft").unwrap_err().to_string(); + assert!(error.contains("not a regular file"), "a directory entry is refused, not streamed: {error}"); + + let (inside2, _, workspace2) = roots("pcraft-symlink"); + let bundle2 = inside2.join("native.pcraft"); + std::fs::create_dir(&bundle2).unwrap(); + std::os::unix::fs::symlink("/dev/zero", bundle2.join("manifest.json")).unwrap(); + assert!(workspace2.open_pcraft("native.pcraft").is_err(), "an escaping symlink entry is refused"); +} + +fn temp_files(dir: &Path) -> Vec { + std::fs::read_dir(dir).unwrap().flatten().map(|e| e.file_name().to_string_lossy().into_owned()).filter(|n| n.ends_with(".tmp")).collect() +} + +#[test] +fn write_replaces_atomically_and_leaves_no_temp_file() { + let (inside, _, workspace) = roots("atomic"); + std::fs::create_dir_all(inside.join("sub")).unwrap(); + workspace.write("sub/out.psd", b"original").unwrap(); + workspace.write("sub/out.psd", b"replacement").unwrap(); + assert_eq!(std::fs::read(inside.join("sub/out.psd")).unwrap(), b"replacement"); + assert!(temp_files(&inside.join("sub")).is_empty()); + // Renaming over a directory fails: nothing is left behind and the directory survives. + std::fs::create_dir_all(inside.join("adir")).unwrap(); + assert!(workspace.write("adir", b"x").is_err()); + assert!(inside.join("adir").is_dir()); + assert!(temp_files(&inside).is_empty()); +} + +/// #7095: replacing a file through the automation path keeps the old file's extended +/// attributes, the same as a save through `atomic_write` does. +#[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))] +#[test] +fn write_keeps_the_replaced_files_extended_attributes() { + #[cfg(target_os = "macos")] + const TAG: &str = "com.apple.metadata:_kMDItemUserTags"; + #[cfg(not(target_os = "macos"))] + const TAG: &str = "user.photocraft.test"; + + let (inside, _, workspace) = roots("xattr"); + let path = inside.join("doc.psd"); + workspace.write("doc.psd", b"original").unwrap(); + if rustix::fs::setxattr(&path, TAG, b"tagged", rustix::fs::XattrFlags::empty()).is_err() { + return; // a file system without extended attributes: nothing to assert + } + + workspace.write("doc.psd", b"replacement, longer").unwrap(); + + assert_eq!(std::fs::read(&path).unwrap(), b"replacement, longer"); + let mut buf = [0u8; 64]; + let len = rustix::fs::getxattr(&path, TAG, buf.as_mut_slice()).expect("the attribute was dropped"); + assert_eq!(&buf[..len], b"tagged"); + assert!(temp_files(&inside).is_empty()); +} + +#[cfg(unix)] +#[test] +fn write_into_read_only_folder_keeps_the_original() { + use std::os::unix::fs::PermissionsExt; + let (inside, _, workspace) = roots("readonly"); + let ro = inside.join("ro"); + std::fs::create_dir_all(&ro).unwrap(); + std::fs::write(ro.join("doc.psd"), b"original").unwrap(); + std::fs::set_permissions(&ro, std::fs::Permissions::from_mode(0o555)).unwrap(); + let root_user = std::fs::File::create(ro.join("probe")).is_ok(); + if !root_user { + assert!(workspace.write("ro/doc.psd", b"new").is_err()); + assert_eq!(std::fs::read(ro.join("doc.psd")).unwrap(), b"original"); + assert!(temp_files(&ro).is_empty()); + } + std::fs::set_permissions(&ro, std::fs::Permissions::from_mode(0o755)).unwrap(); +} + +#[test] +fn rejects_absolute_traversal_mixed_prefix_and_malformed_paths_without_panicking() { + let (_, _, workspace) = roots("reject"); + for path in + ["", "/absolute", "../escape", "a/../escape", "a\\..\\escape", "a\\b", "C:/escape", "a//b", "./a", "name:stream", "NUL", "con.txt", "folder/COM1.log"] + { + assert!(workspace.read(path).is_err(), "read accepted {path:?}"); + assert!(workspace.write(path, b"x").is_err(), "write accepted {path:?}"); + } +} + +#[test] +fn read_and_write_authority_are_separate() { + let (inside, _, _) = roots("separate"); + std::fs::write(inside.join("read.txt"), b"canary").unwrap(); + let read_only = AuthorizedWorkspace::new(Some(&inside), None).unwrap(); + assert_eq!(read_only.read("read.txt").unwrap(), b"canary"); + assert!(read_only.write("blocked.txt", b"x").is_err()); + let write_only = AuthorizedWorkspace::new(None, Some(&inside)).unwrap(); + assert!(write_only.read("read.txt").is_err()); + write_only.write("written.txt", b"ok").unwrap(); +} + +#[test] +fn missing_parent_is_a_stable_error_before_any_file_is_created() { + let (inside, _, workspace) = roots("missing-parent"); + let error = workspace.write("missing/output.txt", b"x").unwrap_err().to_string(); + assert!(error.contains("automation write"), "{error}"); + assert!(!inside.join("missing").exists()); +} + +#[cfg(unix)] +#[test] +fn symlink_escape_is_rejected() { + use std::os::unix::fs::symlink; + + let (inside, outside, workspace) = roots("symlink"); + std::fs::write(outside.join("secret.txt"), b"outside").unwrap(); + symlink(&outside, inside.join("link")).unwrap(); + assert!(workspace.read("link/secret.txt").is_err()); + assert!(workspace.write("link/new.txt", b"blocked").is_err()); + assert!(!outside.join("new.txt").exists()); +} + +#[cfg(windows)] +#[test] +fn windows_symlink_escape_is_rejected_when_supported() { + use std::os::windows::fs::symlink_dir; + + let (inside, outside, workspace) = roots("windows-link"); + std::fs::write(outside.join("secret.txt"), b"outside").unwrap(); + if symlink_dir(&outside, inside.join("link")).is_err() { + return; + } + assert!(workspace.read("link/secret.txt").is_err()); + assert!(workspace.write("link/new.txt", b"blocked").is_err()); + assert!(!outside.join("new.txt").exists()); +} + +#[cfg(windows)] +#[test] +fn windows_junction_escape_is_rejected_when_supported() { + use std::process::Command; + + let (inside, outside, workspace) = roots("windows-junction"); + std::fs::write(outside.join("secret.txt"), b"outside").unwrap(); + let link = inside.join("junction"); + let status = Command::new("cmd.exe").args(["/D", "/C", "mklink", "/J"]).arg(&link).arg(&outside).status(); + if !status.is_ok_and(|status| status.success()) { + return; + } + assert!(workspace.read("junction/secret.txt").is_err()); + assert!(workspace.write("junction/new.txt", b"blocked").is_err()); + assert!(!outside.join("new.txt").exists()); + let _ = std::fs::remove_dir(link); +} + +#[test] +fn filesystem_commands_fail_closed() { + for id in [ + "file.open", + "file.openAs", + "file.save", + "file.saveAs", + "file.saveACopy", + "file.export.saveForWebLegacy", + "pattern.import", + "layer.smartObjects.exportContents", + "layer.smartObjects.replaceContents", + "layer.smartObjects.relinkToFile", + "layer.smartObjects.convertToLinked", + "measurementLog.export", + "layer.videoLayers.reloadFrame", + "edit.colorSettings", + ] { + assert!(authorize_engine_command(id, &serde_json::json!({})).is_err()); + } + assert!(authorize_engine_command("file.new", &serde_json::json!({})).is_ok()); + assert!(authorize_engine_command("file.automate.cropAndStraightenPhotos", &serde_json::json!({})).is_ok()); + assert!(authorize_desktop_engine_command("file.automate.cropAndStraightenPhotos", &serde_json::json!({})).is_ok()); + for id in ["layer.smartObjects.editContents", "layer.smartObjects.convertToLayers", "layer.smartObjects.saveContents"] { + assert!(authorize_desktop_engine_command(id, &serde_json::json!({"layer": 19})).is_ok(), "{id}"); + } + for id in ["layer.smartObjects.editContents", "layer.smartObjects.convertToLayers"] { + assert!(authorize_engine_command(id, &serde_json::json!({"path": "/outside/source.psb"})).is_err(), "{id}"); + } + // The UI-level examples in docs/control-protocol.md. + for id in ["view.zoomIn", "window.theme.pro", "edit.search"] { + assert!(authorize_desktop_engine_command(id, &serde_json::json!({})).is_ok(), "{id}"); + } + assert!(authorize_engine_command("image.mode.cmyk", &serde_json::json!({})).is_ok()); + assert!(authorize_desktop_engine_command("image.mode.cmyk", &serde_json::json!({})).is_err()); + assert!(authorize_engine_command("image.mode.rgb", &serde_json::json!({"profile": "/outside/profile.icc"})).is_err()); + assert!(authorize_engine_command("image.mode.rgb", &serde_json::json!({"profile": "srgb"})).is_ok()); + assert!(authorize_engine_command("file.new", &serde_json::json!({"profile": "/outside/profile.icc"})).is_err()); + assert!(authorize_engine_command("file.new", &serde_json::json!({"profile": "adobe-rgb-compat"})).is_ok()); + assert!(authorize_engine_command("file.new", &serde_json::json!({"profile": "working"})).is_ok()); + assert!(authorize_engine_command("file.new", &serde_json::json!({"profile": "none"})).is_ok()); + assert!(authorize_engine_command("file.new", &serde_json::json!({"profile": "default"})).is_err()); + assert!(authorize_engine_command("file.new", &serde_json::json!({"profile": "working-cmyk"})).is_err()); + // Shortcut sets: text in and out is fine; a path reads or writes the filesystem. + let ks = |p: serde_json::Value| authorize_engine_command("edit.keyboardShortcuts", &p); + assert!(ks(serde_json::json!({"exportKys": true, "summarize": true, "importKys": ""})).is_ok()); + for key in ["importKys", "exportKys", "summarize"] { + assert!(ks(serde_json::json!({ key: {"path": "/outside/set.kys"} })).is_err(), "{key}"); + } + assert!(authorize_engine_command("filter.distort.displace", &serde_json::json!({"mapPath": "outside.png"})).is_err()); + assert!(authorize_engine_command("layer.setAdjustment", &serde_json::json!({"file": "outside.cube"})).is_err()); + assert!(authorize_engine_command("prefs.set", &serde_json::json!({"path": "colorSettings.workingRgb", "value": "outside.icc"})).is_err()); + assert!(authorize_engine_step("file.open", &serde_json::json!({})).is_err()); + assert!(authorize_engine_step("actions.play", &serde_json::json!({})).is_ok()); + // An allowed command can't reach a denied one by running it on its own behalf. + let mut session = photocraft_engine::Session::new(); + session.execute("file.new", serde_json::json!({"width": 4, "height": 4})).unwrap(); + session.authorize = Some(authorize_desktop_engine_step); + let params = serde_json::json!({"to": "grayscale"}); + assert!(authorize_desktop_engine_command("file.automate.conditionalModeChange", ¶ms).is_ok()); + assert!(session.execute("file.automate.conditionalModeChange", params).is_err()); + assert_eq!(session.active().unwrap().doc.mode, photocraft_engine::doc::ColorMode::Rgb); + assert!(authorize_desktop_engine_step("file.saveACopy", &serde_json::json!({})).is_err()); +} + +// Regression test for #3763: `edit.installedProfiles` scans the OS and user ICC folders but +// takes no path parameter, so automation let it through until it was listed as ambient. +#[test] +fn installed_profiles_listing_is_refused_for_automation() { + for params in [serde_json::json!({}), serde_json::json!({"class": "output", "colorSpace": "cmyk"})] { + assert!(authorize_engine_command("edit.installedProfiles", ¶ms).is_err(), "authorize_engine_command allowed it with {params}"); + assert!(authorize_desktop_engine_command("edit.installedProfiles", ¶ms).is_err(), "authorize_desktop_engine_command allowed it with {params}"); + assert!(authorize_engine_step("edit.installedProfiles", ¶ms).is_err(), "authorize_engine_step allowed it with {params}"); + } + // The sandboxed session refuses it before the engine scans any folder. + let mut headless = crate::Headless::new(); + let refused = headless.command_run("edit.installedProfiles", serde_json::json!({})).unwrap_err(); + assert!(refused.to_string().contains("ambient filesystem paths"), "{refused}"); +} + +#[test] +fn apply_data_set_is_judged_by_the_values_it_applies() { + let mut headless = crate::Headless::new(); + headless.command_run("file.new", serde_json::json!({"width": 8, "height": 8})).unwrap(); + let layer = headless.command_run("layer.new.layer", serde_json::json!({})).unwrap()["layer"].clone(); + let defs = [ + serde_json::json!({"name": "shown", "layer": layer, "type": "visibility"}), + serde_json::json!({"name": "photo", "layer": layer, "type": "pixelReplacement"}), + ]; + headless.command_run("image.variables.define", serde_json::json!({"defs": defs})).unwrap(); + let sets = serde_json::json!({"dataSets": [ + {"name": "hidden", "values": [{"variable": "shown", "kind": "visibility", "value": false}]}, + {"name": "swap", "values": [ + {"variable": "shown", "kind": "visibility", "value": false}, + {"variable": "photo", "kind": "pixels", "value": "/outside/photo.png"}, + ]}, + ]}); + headless.command_run("image.variables.dataSets", sets).unwrap(); + let visible = |headless: &crate::Headless| headless.session.active().unwrap().doc.layers.iter().all(|l| l.visible); + let refused = headless.command_run("image.applyDataSet", serde_json::json!({"name": "swap"})).unwrap_err(); + assert!(refused.to_string().contains("ambient filesystem paths"), "{refused}"); + assert!(visible(&headless), "a refused data set applies none of its values"); + assert!(headless.command_run("image.applyDataSet", serde_json::json!({"name": "hidden"})).is_ok()); + assert!(!visible(&headless)); +} + +#[test] +fn automation_rejects_ambient_path_commands_and_preferences() { + for (id, params) in [ + ("brush.presets.importAbr", serde_json::json!({"path": "/outside/set.abr"})), + ("brush.presets.importImage", serde_json::json!({"path": "/outside/tip.png"})), + ("gradient.presets.importGrd", serde_json::json!({"path": "/outside/set.grd"})), + ("plugin.install", serde_json::json!({"path": "/outside/plugin.wasm"})), + ("plugin.reload", serde_json::json!({"path": "/outside/plugins"})), + ("plugin.reload", serde_json::json!({})), + ("plugin.install", serde_json::json!({"path": " "})), + ("swatches.import", serde_json::json!({"path": "/outside/set.aco"})), + ("swatches.export", serde_json::json!({"path": "/outside/set.ase"})), + ("actions.load", serde_json::json!({"path": "/outside/set.atn"})), + ("actions.save", serde_json::json!({"path": "/outside/set.atn"})), + ("style.presets.importAsl", serde_json::json!({"path": "/outside/set.asl"})), + ("style.presets.exportAsl", serde_json::json!({"path": "/outside/set.asl"})), + ("style.presets.exportAsl", serde_json::json!({"path": 5})), + ("layer.layerStyle.contours.load", serde_json::json!({"path": "/outside/set.shc"})), + ("layer.layerStyle.contours.save", serde_json::json!({"path": "/outside/set.shc"})), + ] { + assert!(authorize_engine_command(id, ¶ms).is_err(), "{id}: {params}"); + } + for (id, params) in [ + ("brush.presets.importAbr", serde_json::json!({"data": "QUJD"})), + ("brush.presets.importImage", serde_json::json!({"data": "QUJD"})), + ("gradient.presets.importGrd", serde_json::json!({"data": "QUJD"})), + ("plugin.install", serde_json::json!({"data": "QUJD"})), + ("swatches.import", serde_json::json!({"data": "QUJD"})), + ("swatches.export", serde_json::json!({"format": "ase"})), + ("actions.load", serde_json::json!({"data": "QUJD"})), + ("actions.save", serde_json::json!({"set": "S"})), + ("style.presets.importAsl", serde_json::json!({"data": "QUJD"})), + ("style.presets.exportAsl", serde_json::json!({"group": "Basics"})), + ("layer.layerStyle.contours.load", serde_json::json!({"data": "QUJD"})), + ("layer.layerStyle.contours.save", serde_json::json!({"names": ["a"]})), + ] { + assert!(authorize_engine_command(id, ¶ms).is_ok(), "{id}: {params}"); + } + for path in [ + "", + "colorSettings", + "colorSettings.workingRgb", + "scriptEvents", + "scriptEvents.enabled", + ".scriptEvents", + ".scriptEvents.enabled", + "historyLog.filePath", + ".historyLog.filePath", + "plugIns.additionalPluginsFolder", + "fileHandling.lutFolder", + "fileHandling", + "scratchDisks.disks", + ".", + "..historyLog.filePath", + ] { + assert!(authorize_engine_command("prefs.set", &serde_json::json!({"path": path, "value": {}})).is_err(), "{path}"); + } + assert!( + authorize_engine_command("prefs.set", &serde_json::json!({"values": {"interface.language": "fr", "historyLog.filePath": "/outside/log"}})).is_err() + ); + assert!(authorize_engine_command("prefs.set", &serde_json::json!({"path": "interface.language", "value": "fr"})).is_ok()); + assert!(authorize_engine_command("prefs.set", &serde_json::json!({"path": "fileHandling.autosave", "value": false})).is_ok()); +} + +#[test] +fn registry_filesystem_path_params_are_classified() { + let probe = serde_json::json!({ + "path": "/outside/photocraft-probe", + "file": "/outside/photocraft-probe.icc", + "mapPath": "/outside/photocraft-probe.png", + "profile": "/outside/photocraft-probe.icc", + "workingRgb": "/outside/photocraft-probe.icc", + "workingCmyk": "/outside/photocraft-probe.icc", + "workingGray": "/outside/photocraft-probe.icc", + "input": "/outside/photocraft-input", + "output": "/outside/photocraft-output", + "paths": ["/outside/photocraft-probe.psd"], + }); + let preference_probe = serde_json::json!({"path": ".scriptEvents", "value": {}}); + let unclassified: Vec<_> = photocraft_engine::command_specs() + .iter() + .filter(|spec| documents_filesystem_path_params(spec.id, spec.params)) + .filter(|spec| { + let params = if spec.id == "prefs.set" { &preference_probe } else { &probe }; + authorize_engine_command(spec.id, params).is_ok() + }) + .map(|spec| spec.id) + .collect(); + assert!(unclassified.is_empty(), "filesystem path parameters in the command registry need an automation policy: {unclassified:?}"); +} + +fn documents_filesystem_path_params(id: &str, params: &str) -> bool { + // These commands return settings or installed-profile paths; they do not accept a host + // filesystem path as an automation input. + if matches!(id, "prefs.get" | "prefs.reset" | "edit.installedProfiles") { + return false; + } + // These registry descriptions refer to document vector paths, not host files. + if matches!( + id, + "filter.blurGallery.pathBlur" + | "filter.render.flame" + | "shape.create" + | "shape.edit" + | "shape.info" + | "shape.presets.list" + | "shape.presets.new" + | "path.list" + | "path.info" + | "path.set" + | "path.transform" + | "path.moveAnchors" + | "path.moveHandle" + | "path.bendSegment" + | "path.convertPoint" + | "path.addAnchor" + | "path.deleteAnchor" + | "path.clippingPath.set" + | "path.rename" + | "path.stroke" + | "type.attachToPath" + | "type.fillPath" + | "type.detachFromPath" + | "select.toWorkPath" + | "layer.vectorMask.add" + | "layer.vectorMask.edit" + | "layer.vectorMask.info" + | "paint.symmetryFromPath" + | "edit.defineCustomShape" + | "layer.combineShapes.unite" + | "layer.combineShapes.subtractFrontShape" + | "layer.combineShapes.intersectShapeAreas" + | "layer.combineShapes.excludeOverlappingShapes" + | "layer.combineShapes.mergeShapeComponents" + ) || id.starts_with("layer.newFillLayer.") + || id.starts_with("layer.newAdjustmentLayer.") + { + // New fill and adjustment layers take a vector path as their vector mask (#1419). + return false; + } + params.to_ascii_lowercase().contains("path") +} + +#[test] +fn whole_preferences_update_cannot_enable_automation_script_events() { + let mut headless = crate::headless::Headless::new(); + let result = headless.command_run( + "prefs.set", + serde_json::json!({ + "path": "", + "value": { + "scriptEvents": { + "enabled": true, + "bindings": [{ + "event": "newDocument", + "steps": [["file.saveACopy", {"path": "/outside/canary.psd"}]] + }] + } + } + }), + ); + assert!(result.is_err()); + + for (id, params) in [ + ("brush.presets.importAbr", serde_json::json!({"path": "/outside/set.abr"})), + ("gradient.presets.importGrd", serde_json::json!({"path": "/outside/set.grd"})), + ("plugin.install", serde_json::json!({"path": "/outside/plugin.wasm"})), + ("plugin.reload", serde_json::json!({"path": "/outside/plugins"})), + ("style.presets.importAsl", serde_json::json!({"path": "/outside/set.asl"})), + ("style.presets.exportAsl", serde_json::json!({"path": "/outside/set.asl"})), + ("prefs.set", serde_json::json!({"path": "historyLog.filePath", "value": "/outside/log"})), + ("prefs.set", serde_json::json!({"values": {"interface.language": "fr", "historyLog.filePath": "/outside/log"}})), + ] { + assert!(headless.command_run(id, params).is_err(), "{id}"); + } + headless.command_run("file.new", serde_json::json!({"width": 5, "height": 5})).unwrap(); + assert!(headless.session.file_menu.event_log.is_empty()); +} + +/// #2176: an absolute path beneath the root names the same file as its relative path; every +/// other absolute path is refused before any file effect. +#[test] +fn absolute_paths_beneath_the_root_are_translated_and_others_refused() { + let (inside, outside, workspace) = roots("absolute-paths"); + let abs = |p: &Path| p.to_string_lossy().into_owned(); + + workspace.write(&abs(&inside.join("a.bin")), b"one").unwrap(); + assert_eq!(std::fs::read(inside.join("a.bin")).unwrap(), b"one"); + assert_eq!(workspace.read(&abs(&inside.join("a.bin"))).unwrap(), b"one"); + // Forward slashes too (on Windows the native spelling uses `\`). + assert_eq!(workspace.read(&abs(&inside.join("a.bin")).replace('\\', "/")).unwrap(), b"one"); + std::fs::create_dir(inside.join("sub")).unwrap(); + workspace.write(&abs(&inside.join("sub").join("b.bin")), b"two").unwrap(); + assert_eq!(std::fs::read(inside.join("sub/b.bin")).unwrap(), b"two"); + assert_eq!(workspace.read("sub/b.bin").unwrap(), b"two", "relative paths still work"); + + let refused = |path: String| { + let error = workspace.write(&path, b"x").unwrap_err().to_string(); + assert!(error.contains("automation path rejected"), "{path}: {error}"); + }; + refused(abs(&outside.join("escape.bin"))); + refused(abs(&inside.join("..").join("outside").join("traversal.bin"))); + refused(abs(&inside)); + refused(abs(&inside.join("CON"))); + refused(format!("{}:hidden", abs(&inside.join("a.bin")))); + // A sibling whose name merely starts with the root's name is not beneath it. + let sibling = inside.with_file_name("inside-sibling"); + std::fs::create_dir_all(&sibling).unwrap(); + refused(abs(&sibling.join("lookalike.bin"))); + refused(format!("{}-sibling/lookalike.bin", abs(&inside))); + // Climbing back out through a subdirectory is refused too. + refused(abs(&inside.join("sub").join("..").join("..").join("outside").join("climb.bin"))); + assert!(!sibling.join("lookalike.bin").exists()); + assert!(!outside.join("climb.bin").exists()); + assert!(!outside.join("escape.bin").exists()); + assert!(!outside.join("traversal.bin").exists()); + assert_eq!(std::fs::read(inside.join("a.bin")).unwrap(), b"one"); +} + +/// Each authority is checked against its own root, and none granted refuses absolute paths. +#[test] +fn absolute_paths_are_checked_against_the_authority_s_own_root() { + let (inside, outside, _) = roots("absolute-authority"); + let workspace = AuthorizedWorkspace::new(Some(&outside), Some(&inside)).unwrap(); + let target = inside.join("written.bin"); + workspace.write(&target.to_string_lossy(), b"w").unwrap(); + assert!(workspace.read(&target.to_string_lossy()).is_err(), "not under the read root"); + let none = AuthorizedWorkspace::default(); + assert!(none.read(&target.to_string_lossy()).is_err()); +} diff --git a/crates/automation/tests/it/mcp.rs b/crates/automation/tests/it/mcp.rs index fe44d0be6b..0ac5c17a5f 100644 --- a/crates/automation/tests/it/mcp.rs +++ b/crates/automation/tests/it/mcp.rs @@ -273,12 +273,13 @@ async fn command_ids_in_tool_schemas_exist() { client.cancel().await.unwrap(); } -/// `UI_SET_FIELDS` in `crates/ui-egui/src/control.rs`, read from source. The desktop shell owns the +/// `UI_SET_FIELDS` in `crates/ui-egui/src/control/params.rs`, read from source. The desktop shell owns the /// list; this crate describes it over MCP without depending on the UI crate (both are L6). /// Anchored on the declaration, not on the doc comment that mentions it first, and checked against /// the declared array length so a mis-parse fails loudly instead of testing the wrong names. fn ui_set_fields() -> Vec { - let src = std::fs::read_to_string(std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../ui-egui/src/control.rs")).expect("ui-egui control.rs"); + let src = + std::fs::read_to_string(std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../ui-egui/src/control/params.rs")).expect("ui-egui control/params.rs"); let (_, rest) = src.split_once("UI_SET_FIELDS: [&str; ").expect("UI_SET_FIELDS is declared"); let declared: usize = rest.split_once(']').expect("declared length").0.parse().expect("declared length"); let body = rest.split_once('[').expect("field array").1.split_once("];").expect("terminated array").0; diff --git a/crates/codecs/src/codecs/mod.rs b/crates/codecs/src/codecs.rs similarity index 100% rename from crates/codecs/src/codecs/mod.rs rename to crates/codecs/src/codecs.rs diff --git a/crates/codecs/src/codecs/tiff.rs b/crates/codecs/src/codecs/tiff.rs index dbe44f2427..1db3b0c44c 100644 --- a/crates/codecs/src/codecs/tiff.rs +++ b/crates/codecs/src/codecs/tiff.rs @@ -43,101 +43,6 @@ use crate::fidelity::Plan; use crate::image::{ChannelLayout, DecodeWarning, Image, Metadata, SampleType}; use crate::options::{EncodeOptions, Limits, TiffCompression}; -const F: Format = Format::Tiff; -const TAG_XMP: u16 = 700; -/// Photoshop image resources (`8BIM` blocks). -const TAG_PHOTOSHOP: u16 = 34377; -/// Photoshop `ImageSourceData`: the layers of a layered TIFF. -const TAG_IMAGE_SOURCE_DATA: u16 = 37724; - -/// `true` when [`encode`] writes little-endian (`II`) files: the `tiff` encoder writes the -/// running target's byte order, and every target PhotoCraft builds for is little-endian. -/// Byte-order-sensitive payloads (Photoshop layer data) must be produced to match. -pub fn writes_little_endian() -> bool { - cfg!(target_endian = "little") -} - -/// `(34377 image resources, 37724 image source data)` payloads, each absent when the tag is. -pub type PhotoshopTags<'a> = (Option<&'a [u8]>, Option<&'a [u8]>); - -/// The raw payloads of the Photoshop private tags in the first directory: `(34377 image -/// resources, 37724 image source data)`. Classic and BigTIFF, either byte order; only -/// header bytes and the two payloads are touched, and nothing is allocated. Anything malformed -/// reads as "absent". -pub fn photoshop_tags(b: &[u8]) -> PhotoshopTags<'_> { - fn walk(b: &[u8]) -> Option> { - let le = match b.get(0..2)? { - b"II" => true, - b"MM" => false, - _ => return None, - }; - let u16_at = |o: u64| -> Option { - let o = usize::try_from(o).ok()?; - let s = b.get(o..o.checked_add(2)?)?; - Some(if le { u16::from_le_bytes([s[0], s[1]]) } else { u16::from_be_bytes([s[0], s[1]]) }) - }; - let u32_at = |o: u64| -> Option { - let o = usize::try_from(o).ok()?; - let s: [u8; 4] = b.get(o..o.checked_add(4)?)?.try_into().ok()?; - Some(if le { u32::from_le_bytes(s) } else { u32::from_be_bytes(s) }) - }; - let u64_at = |o: u64| -> Option { - let o = usize::try_from(o).ok()?; - let s: [u8; 8] = b.get(o..o.checked_add(8)?)?.try_into().ok()?; - Some(if le { u64::from_le_bytes(s) } else { u64::from_be_bytes(s) }) - }; - let (big, ifd) = match u16_at(2)? { - 42 => (false, u64::from(u32_at(4)?)), - 43 => (true, u64_at(8)?), - _ => return None, - }; - let n = if big { u64_at(ifd)? } else { u64::from(u16_at(ifd)?) }.min(4096); - let (entry, first, inline) = if big { (20u64, ifd.checked_add(8)?, 8u64) } else { (12, ifd.checked_add(2)?, 4) }; - let mut resources = None; - let mut layers = None; - for i in 0..n { - let e = first.checked_add(i.checked_mul(entry)?)?; - let tag = u16_at(e)?; - if tag != TAG_PHOTOSHOP && tag != TAG_IMAGE_SOURCE_DATA { - continue; - } - // BYTE, ASCII, SBYTE or UNDEFINED: one byte per element. - if !matches!(u16_at(e + 2)?, 1 | 2 | 6 | 7) { - continue; - } - let count = if big { u64_at(e + 4)? } else { u64::from(u32_at(e + 4)?) }; - let value_at = e + if big { 12 } else { 8 }; - let start = if count <= inline { - value_at - } else if big { - u64_at(value_at)? - } else { - u64::from(u32_at(value_at)?) - }; - let start = usize::try_from(start).ok()?; - let data = b.get(start..start.checked_add(usize::try_from(count).ok()?)?)?; - if tag == TAG_PHOTOSHOP { - resources = Some(data); - } else { - layers = Some(data); - } - } - Some((resources, layers)) - } - walk(b).unwrap_or((None, None)) -} - -/// ASCII tags mapped to `Metadata::text` keys. -const TEXT_TAGS: &[(Tag, &str)] = &[ - (Tag::ImageDescription, "Description"), - (Tag::Make, "Make"), - (Tag::Model, "Model"), - (Tag::Software, "Software"), - (Tag::DateTime, "DateTime"), - (Tag::Artist, "Artist"), - (Tag::Copyright, "Copyright"), -]; - fn err(e: impl std::fmt::Display) -> CodecError { CodecError::malformed(F, e) } @@ -225,1050 +130,6 @@ fn camera_raw(b: &[u8]) -> bool { false } -/// Decodes the page Photoshop would open: the first full-resolution directory. -pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result { - decode_page(bytes, None, limits) -} - -/// Decodes page `page` of [`ifd::tiff_info`]'s list (`None`: the default page). The image -/// carries the page's metadata, a [`DecodeWarning::MorePages`] when the file holds more -/// full-resolution pages, and a [`DecodeWarning::Truncated`] when image data is cut off. -pub(crate) fn decode_page(bytes: &[u8], page: Option, limits: &Limits) -> Result { - if camera_raw(bytes) { - return Err(CodecError::unsupported(F, "camera raw files (such as CR2, NEF, ARW or DNG) are not flat images; decode them with photocraft-raw")); - } - let file = File::parse(bytes).ok_or_else(|| err("not a TIFF or BigTIFF header"))?; - let info = ifd::info_of(&file)?; - let index = match page { - Some(i) => i, - None => info.default_page().ok_or_else(|| err("no image directory"))?, - }; - let p = info - .pages - .get(index) - .ok_or_else(|| CodecError::InvalidImage(format!("TIFF page {index} does not exist (the file has {} directories)", info.pages.len())))?; - let dir = file.ifd(p.ifd_offset).ok_or_else(|| err("image directory cut off"))?; - let mut img = decode_ifd(&file, &dir, limits)?; - let extra_samples = std::mem::take(&mut img.meta.extra_samples); - img.meta = metadata(&file, &dir, &mut img.icc); - img.meta.extra_samples = extra_samples; - let pages = info.page_count(); - if pages > 1 { - img.warnings.push(DecodeWarning::MorePages { total: info.complete.then_some(u32::try_from(pages).unwrap_or(u32::MAX)) }); - } - Ok(img) -} - -/// The Orientation (1–8) of page `page` (`None`: the default page); 1 when absent, malformed -/// or out of range. Classic TIFF and BigTIFF. -pub(crate) fn orientation(bytes: &[u8], page: Option) -> u16 { - let Some(file) = File::parse(bytes) else { return 1 }; - let Ok(info) = ifd::info_of(&file) else { return 1 }; - page.or_else(|| info.default_page()).and_then(|i| info.pages.get(i)).and_then(|p| file.ifd(p.ifd_offset)).map_or(1, |d| ifd::orientation_of(&file, &d)) -} - -/// The page's metadata; the ICC profile goes to `icc`. -fn metadata(f: &File<'_>, dir: &Ifd, icc: &mut Option>) -> Metadata { - *icc = f.tag_bytes(dir, Tag::IccProfile.to_u16()).filter(|b| !b.is_empty()).map(<[u8]>::to_vec); - let text = |tag: u16| { - let b = f.tag_bytes(dir, tag)?; - let s = std::str::from_utf8(b).ok()?.trim_end_matches('\0'); - (!s.is_empty()).then(|| s.to_owned()) - }; - let mut meta = Metadata { xmp: text(TAG_XMP), ..Default::default() }; - let unit = f.tag_uint(dir, Tag::ResolutionUnit.to_u16()).unwrap_or(2); - if let (Some(x), Some(y)) = (f.tag_f64(dir, Tag::XResolution.to_u16()), f.tag_f64(dir, Tag::YResolution.to_u16())) - && x > 0.0 - && y > 0.0 - && x.is_finite() - && y.is_finite() - { - meta.dpi = match unit { - 2 => Some((x as f32, y as f32)), - 3 => Some(((x * 2.54) as f32, (y * 2.54) as f32)), - _ => None, - }; - } - for (tag, key) in TEXT_TAGS { - if let Some(s) = text(tag.to_u16()) { - meta.text.push(((*key).to_owned(), s)); - } - } - // Photoshop keeps a layered TIFF's layers and resources in IFD0, where `photoshop_tags` - // reads them; any other page reads its own directory's copies. - let (resources, layers) = - if dir.at == f.first_ifd { photoshop_tags(f.b) } else { (f.tag_bytes(dir, TAG_PHOTOSHOP), f.tag_bytes(dir, TAG_IMAGE_SOURCE_DATA)) }; - meta.photoshop_resources = resources.map(<[u8]>::to_vec); - meta.photoshop_layers = layers.map(<[u8]>::to_vec); - // EXIF: the Exif and GPS directories IFD0 points to, with IFD0's descriptive tags, as an - // EXIF block (the other pages are reduced copies or layers of the same image). - if dir.at == f.first_ifd - && let Some(e) = tiff_exif::read(f.b).filter(ExifDirs::has_directories) - { - meta.exif = Some(tiff_exif::block(&e)); - } - meta -} - -// --------------------------------------------------------------------------- -// Banded pixel decoding -// --------------------------------------------------------------------------- - -/// The file seen with a few byte ranges replaced: the header's first-IFD offset (so the `tiff` -/// decoder opens the chosen directory as its IFD0) and, for WhiteIsZero and palette images, -/// the PhotometricInterpretation value (so the decoder hands over the stored samples and this -/// module applies the interpretation itself). Reads past the end return no bytes. -#[derive(Clone, Copy)] -struct Patched<'a> { - b: &'a [u8], - patches: &'a [(u64, Vec)], - pos: u64, -} - -impl Read for Patched<'_> { - fn read(&mut self, out: &mut [u8]) -> io::Result { - let Some(src) = usize::try_from(self.pos).ok().and_then(|p| self.b.get(p..)) else { return Ok(0) }; - let n = out.len().min(src.len()); - let (Some(o), Some(s)) = (out.get_mut(..n), src.get(..n)) else { return Ok(0) }; - o.copy_from_slice(s); - let end = self.pos.saturating_add(n as u64); - for (at, bytes) in self.patches { - let lo = (*at).max(self.pos); - let hi = at.saturating_add(bytes.len() as u64).min(end); - for i in lo..hi { - let (Ok(oi), Ok(pi)) = (usize::try_from(i - self.pos), usize::try_from(i - at)) else { continue }; - if let (Some(d), Some(&v)) = (o.get_mut(oi), bytes.get(pi)) { - *d = v; - } - } - } - self.pos = end; - Ok(n) - } -} - -impl Seek for Patched<'_> { - fn seek(&mut self, to: SeekFrom) -> io::Result { - let new = match to { - SeekFrom::Start(n) => Some(n), - SeekFrom::End(d) => (self.b.len() as u64).checked_add_signed(d), - SeekFrom::Current(d) => self.pos.checked_add_signed(d), - }; - let new = new.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "seek out of range"))?; - self.pos = new; - Ok(new) - } -} - -/// How a stored sample is laid out in the `tiff` crate's chunk buffer (native endian). -#[derive(Clone, Copy, PartialEq, Eq, Debug)] -enum Src { - /// 1, 2 or 4-bit unsigned, packed MSB first, rows padded to a byte. - Bits(u8), - U8, - U16, - U32, - U64, - F16, - F32, - F64, -} - -impl Src { - fn bytes(self) -> usize { - match self { - Src::Bits(_) | Src::U8 => 1, - Src::U16 | Src::F16 => 2, - Src::U32 | Src::F32 => 4, - Src::U64 | Src::F64 => 8, - } - } - - /// The output sample type: integers above 16 bits keep their top 16, doubles become f32. - fn out(self) -> SampleType { - match self { - Src::Bits(_) | Src::U8 => SampleType::U8, - Src::U16 | Src::U32 | Src::U64 => SampleType::U16, - Src::F16 => SampleType::F16, - Src::F32 | Src::F64 => SampleType::F32, - } - } - - /// Stored bytes and output bytes are the same: a plain copy. - fn is_identity(self) -> bool { - matches!(self, Src::U8 | Src::U16 | Src::F16 | Src::F32) - } -} - -/// Everything needed to decode and place the chunks of one directory. -struct Layout { - w: usize, - src: Src, - out: SampleType, - out_layout: ChannelLayout, - /// Samples per pixel in a decoded chunk (1 for planar data). - chunk_spp: usize, - planar: bool, - /// Planes decoded for planar data: one per output channel (extra planes are skipped). - planes: usize, - /// Tile width (a strip is `w` wide). - cw: usize, - across: usize, - chunks_per_plane: usize, - /// WhiteIsZero: invert the gray channel. - invert: bool, - /// The decoded sample (chunky) or file plane (planar) of the alpha channel (when there is one). - alpha_sample: usize, - /// Associated (premultiplied) alpha to turn straight. - premultiplied: bool, - /// Palette images: the colour map (16-bit RGB per index). - palette: Option>, - /// Upper bound for one chunk's scratch buffer. - scratch_cap: usize, - /// File sample indices that are neither colour nor the chosen alpha (spot / extra alpha). - extra_at: Vec, -} - -impl Layout { - fn out_channels(&self) -> usize { - self.out_layout.channels() - } - /// The decoded sample (chunky) or file plane (planar) of output channel `k`. - fn source_sample(&self, k: usize) -> usize { - if self.out_layout.has_alpha() && k + 1 == self.out_channels() { self.alpha_sample } else { k } - } - fn out_row(&self) -> usize { - self.w * self.out_channels() * self.out.bytes() - } - fn extra_row(&self) -> usize { - self.w.saturating_mul(self.extra_at.len()).saturating_mul(self.out.bytes()) - } - /// A chunky strip already in the output's layout: decoded in place. - fn direct(&self) -> bool { - self.copyable() && self.across == 1 - } - /// Chunk rows are output rows: copied without conversion. - fn copyable(&self) -> bool { - !self.planar && self.palette.is_none() && self.src.is_identity() && self.chunk_spp == self.out_channels() - } -} - -/// A chunk read that hit the end of the file (the data is missing, not malformed). -fn is_eof(e: &tiff::TiffError) -> bool { - matches!(e, tiff::TiffError::IoError(io) if io.kind() == io::ErrorKind::UnexpectedEof) -} - -/// Decodes the pixels of one directory. -fn decode_ifd(f: &File<'_>, dir: &Ifd, limits: &Limits) -> Result { - // The values the `tiff` crate reads must exist: a count past the end of the file is - // neither allocated nor read. - if let Some(e) = dir.entries.iter().find(|e| ifd::STRUCTURAL_TAGS.contains(&e.tag) && f.data(e).is_none()) { - return Err(err(format!("tag {} points past the end of the file", e.tag))); - } - let need = |tag: u16, name: &str| f.tag_uint(dir, tag).ok_or_else(|| err(format!("missing or unreadable {name}"))); - let w = u32::try_from(need(ifd::TAG_WIDTH, "ImageWidth")?).map_err(|_| err("ImageWidth out of range"))?; - let h = u32::try_from(need(ifd::TAG_HEIGHT, "ImageLength")?).map_err(|_| err("ImageLength out of range"))?; - if w == 0 || h == 0 { - return Err(CodecError::InvalidImage(format!("zero-sized image {w}x{h}"))); - } - let spp = f.tag_uint(dir, ifd::TAG_SAMPLES).unwrap_or(1); - if spp == 0 || spp > 64 { - return Err(CodecError::unsupported(F, format!("{spp} samples per pixel"))); - } - let bits_all = f.tag_uints(dir, ifd::TAG_BITS, spp).unwrap_or_else(|| vec![1]); - let bits = bits_all.first().copied().unwrap_or(1); - if bits_all.iter().any(|&b| b != bits) { - return Err(CodecError::unsupported(F, format!("mixed bits per sample {bits_all:?}"))); - } - let format = f.tag_uint(dir, ifd::TAG_SAMPLE_FORMAT).unwrap_or(1); - let photometric_entry = dir.get(ifd::TAG_PHOTOMETRIC).copied(); - let photometric = f.tag_uint(dir, ifd::TAG_PHOTOMETRIC).ok_or_else(|| CodecError::unsupported(F, "missing PhotometricInterpretation"))?; - let planar = f.tag_uint(dir, ifd::TAG_PLANAR) == Some(2); - let extra = f.tag_uints(dir, ifd::TAG_EXTRA_SAMPLES, 64).unwrap_or_default(); - let tiled = dir.get(ifd::TAG_TILE_OFFSETS).is_some(); - let (cw, ch) = if tiled { - let tw = need(ifd::TAG_TILE_WIDTH, "TileWidth")?; - let tl = need(ifd::TAG_TILE_LENGTH, "TileLength")?; - (tw, tl) - } else { - (u64::from(w), f.tag_uint(dir, ifd::TAG_ROWS_PER_STRIP).unwrap_or(u64::from(h)).min(u64::from(h))) - }; - if cw == 0 || ch == 0 { - return Err(err("zero tile or strip size")); - } - // The chunk tables must match the geometry. Checked here, in 64 bits, before the `tiff` - // crate does the same arithmetic in narrower types. - let planes_in_file = if planar { spp } else { 1 }; - let expected = u64::from(w) - .div_ceil(cw) - .checked_mul(u64::from(h).div_ceil(ch)) - .and_then(|n| n.checked_mul(planes_in_file)) - .filter(|&n| n <= u64::from(u32::MAX)) - .ok_or_else(|| err("too many strips or tiles"))?; - let (offsets_tag, counts_tag) = if tiled { (324, 325) } else { (273, 279) }; - let counts = (dir.get(offsets_tag).map(|e| e.count), dir.get(counts_tag).map(|e| e.count)); - if counts != (Some(expected), Some(expected)) { - return Err(err(format!("{expected} strips or tiles expected, the tables list {counts:?}"))); - } - let src = match (format, bits) { - (1, 1 | 2 | 4) => Src::Bits(bits as u8), - (1, 8) => Src::U8, - (1, 16) => Src::U16, - (1, 32) => Src::U32, - (1, 64) => Src::U64, - (3, 16) => Src::F16, - (3, 32) => Src::F32, - (3, 64) => Src::F64, - (2, _) => return Err(CodecError::unsupported(F, "signed integer samples")), - _ => return Err(CodecError::unsupported(F, format!("{bits}-bit samples (sample format {format})"))), - }; - - // WhiteIsZero and palette images are handed to the `tiff` crate as BlackIsZero: it then - // returns the stored samples, and the interpretation is applied here (for every depth and - // with alpha, which the crate's own inversion does not cover). - let invert = photometric == 0; - let palette = if photometric == 3 { - if spp != 1 || !matches!(src, Src::Bits(_) | Src::U8 | Src::U16) { - return Err(CodecError::unsupported(F, format!("palette image with {spp} samples of {bits} bits"))); - } - let n = 1u64 << bits; - let map = dir.get(ifd::TAG_COLOR_MAP).filter(|e| e.ty == 3 && e.count == 3 * n).ok_or_else(|| err("palette image without a valid ColorMap"))?; - let at = |i: u64| f.uint(map, i).and_then(|v| u16::try_from(v).ok()); - let table: Option> = (0..n).map(|i| Some([at(i)?, at(n + i)?, at(2 * n + i)?])).collect(); - Some(table.ok_or_else(|| err("palette ColorMap cut off"))?) - } else { - None - }; - // CIE L*a*b*: CIELab (8; a* and b* signed) and ICCLab (9; a* and b* offset) are handed to the - // `tiff` crate as RGB, then labelled Lab with a* and b* in PhotoCraft's encoding - // (`convert_ab`). - let lab = matches!(photometric, 8 | 9); - if lab && (spp < 3 || !matches!(src, Src::U8 | Src::U16)) { - return Err(CodecError::unsupported(F, format!("Lab image with {spp} samples of {bits} bits"))); - } - // TIFF 6.0 lets any extra sample be the alpha (#1349). For RGB and CMYK the `tiff` crate - // returns the alpha only when it is the first extra sample: otherwise it is asked for every - // sample (as multiband gray) and the colour and alpha samples are picked here. An alpha - // position past the samples the file has is ignored. - let color: usize = match photometric { - 2 | 8 | 9 => 3, - 5 => 4, - _ => 1, - }; - let alpha_at = extra.iter().position(|&e| e == 1 || e == 2).filter(|&a| (color as u64).saturating_add(a as u64) < spp); - // Samples the colour model does not keep. RGB, CMYK and Lab only hand back every sample when - // asked (photometric patched to black-is-zero below); gray already comes back as multiband. - let unused = !extra.is_empty() && (spp as usize) > color.saturating_add(usize::from(alpha_at.is_some())); - let all_samples = palette.is_none() && matches!(photometric, 2 | 5 | 8 | 9) && (alpha_at.is_some_and(|a| a > 0) || (!planar && unused)); - let mut patches: Vec<(u64, Vec)> = Vec::new(); - let encode_u = |v: u64, len: usize| -> Vec { - let b = if f.le { v.to_le_bytes() } else { v.to_be_bytes() }; - if f.le { b.get(..len).map(<[u8]>::to_vec).unwrap_or_default() } else { b.get(8 - len..).map(<[u8]>::to_vec).unwrap_or_default() } - }; - if f.big { - patches.push((8, encode_u(dir.at, 8))); - } else { - let at = u32::try_from(dir.at).map_err(|_| err("directory offset out of range"))?; - patches.push((4, encode_u(u64::from(at), 4))); - } - // The directory is seen as the last of its chain: the chain was walked already, and a - // cycle through it must not fail this page. - patches.push((dir.next_at, vec![0; if f.big { 8 } else { 4 }])); - if invert || palette.is_some() || all_samples || lab { - let e = photometric_entry.ok_or_else(|| err("missing PhotometricInterpretation"))?; - let len = match e.ty { - 3 if e.count == 1 => 2, - 4 if e.count == 1 => 4, - _ => return Err(err("malformed PhotometricInterpretation")), - }; - patches.push((e.value_at, encode_u(if lab && !all_samples { 2 } else { 1 }, len))); - } - - let tl = { - let mut l = tiff::decoder::Limits::default(); - l.decoding_buffer_size = limits.alloc_usize(); - // No compressed chunk can be larger than the file. - l.intermediate_buffer_size = f.b.len().max(1); - l - }; - let open = || Decoder::new(Patched { b: f.b, patches: &patches, pos: 0 }).map(|d| d.with_limits(tl.clone())).map_err(map_err); - let mut dec = open()?; - if dec.dimensions().map_err(map_err)? != (w, h) || (dec.get_chunk_type() == ChunkType::Tile) != tiled { - return Err(err("inconsistent image directory")); - } - let ct = dec.colortype().map_err(map_err)?; - let gray_alpha = alpha_at.is_some() || (extra.is_empty() && spp == 2); - let (out_layout, chunk_spp) = match ct { - _ if palette.is_some() => (ChannelLayout::Rgb, 1), - tiff::ColorType::Gray(_) => (ChannelLayout::Gray, 1), - tiff::ColorType::Multiband { num_samples, .. } if all_samples => { - // Lab reads as RGB here and is relabelled below. - let layout = match photometric { - 2 | 8 | 9 => { - if alpha_at.is_some() { - ChannelLayout::Rgba - } else { - ChannelLayout::Rgb - } - } - 5 => { - if alpha_at.is_some() { - ChannelLayout::CmykA - } else { - ChannelLayout::Cmyk - } - } - _ => { - if gray_alpha { - ChannelLayout::GrayA - } else { - ChannelLayout::Gray - } - } - }; - (layout, usize::from(num_samples)) - } - tiff::ColorType::Multiband { num_samples, .. } if photometric <= 1 => { - (if gray_alpha { ChannelLayout::GrayA } else { ChannelLayout::Gray }, usize::from(num_samples)) - } - tiff::ColorType::RGB(_) => (ChannelLayout::Rgb, 3), - tiff::ColorType::RGBA(_) => (ChannelLayout::Rgba, 4), - tiff::ColorType::CMYK(_) => (ChannelLayout::Cmyk, 4), - tiff::ColorType::CMYKA(_) => (ChannelLayout::CmykA, 5), - other => return Err(CodecError::unsupported(F, format!("colour type {other:?}"))), - }; - let out_layout = match out_layout { - ChannelLayout::Rgb if lab => ChannelLayout::Lab, - ChannelLayout::Rgba if lab => ChannelLayout::LabA, - _ if lab => return Err(err("Lab image that does not read as three colour samples")), - l => l, - }; - let chunk_spp = if planar { 1 } else { chunk_spp }; - // The sample (chunky) or plane (planar) that holds the alpha: the colour samples come first. - let alpha_sample = out_layout.color_channels() + alpha_at.unwrap_or(0); - if out_layout.has_alpha() && (alpha_sample as u64 >= spp || (!planar && alpha_sample >= chunk_spp)) { - return Err(err("the alpha sample is past the samples of a pixel")); - } - if matches!(src, Src::Bits(_)) && (out_layout.channels() > 1 || spp != 1) && palette.is_none() { - return Err(CodecError::unsupported(F, format!("{bits}-bit samples with {spp} samples per pixel"))); - } - if (!planar && palette.is_none() && chunk_spp < out_layout.channels()) || (planar && out_layout.channels() as u64 > spp) { - return Err(err("fewer samples than the colour type needs")); - } - let out = match (&palette, src) { - (Some(_), Src::U16) => SampleType::U16, - (Some(_), _) => SampleType::U8, - _ => src.out(), - }; - limits.check(w, h, out_layout, out)?; - // Decompression-bomb guard: no compression method expands data by more than a few thousand - // times (Deflate at most ~1032:1, LZW ~2730:1, PackBits 128:1), so a file far too small for - // its declared size is refused before the image is allocated. Uncompressed data may be up - // to three quarters missing (that decodes with a `Truncated` warning). - let stored = u64::from(w).saturating_mul(u64::from(h)).saturating_mul(spp).saturating_mul(bits).div_ceil(8); - let ratio: u64 = match f.tag_uint(dir, ifd::TAG_COMPRESSION).unwrap_or(1) { - 1 => 4, - 32773 => 130, - _ => 4096, - }; - if stored > (f.b.len() as u64).saturating_mul(ratio).saturating_add(1 << 20) { - return Err(err(format!("a {} byte file cannot hold a {w}x{h} image", f.b.len()))); - } - - let (wu, hu) = (w as usize, h as usize); - let (cw, ch) = (usize::try_from(cw).map_err(|_| err("tile too wide"))?, usize::try_from(ch).map_err(|_| err("tile too tall"))?); - let across = wu.div_ceil(cw); - let down = hu.div_ceil(ch); - let chunks_per_plane = across.checked_mul(down).ok_or_else(|| err("too many tiles"))?; - let planes_in_file = if planar { spp as usize } else { 1 }; - let total = if tiled { dec.tile_count() } else { dec.strip_count() }.map_err(map_err)?; - if Some(total as usize) != chunks_per_plane.checked_mul(planes_in_file) { - return Err(err("strip or tile count does not match the image size")); - } - // One chunk's decoded bytes, clipped to the image: the scratch buffer may hold a little - // more (the `tiff` crate reads whole tiles in some planar cases) but never an amount that - // only a hostile tile size could ask for. - let chunk_bytes = cw - .min(wu) - .checked_mul(ch.min(hu)) - .and_then(|px| px.checked_mul(chunk_spp)) - .and_then(|s| s.checked_mul(src.bytes())) - .ok_or_else(|| CodecError::LimitExceeded("tile size".into()))?; - let scratch_cap = chunk_bytes.saturating_mul(2).max(64 << 20).min(limits.alloc_usize()); - let (extra_at, extras_over_limit) = extra_sample_indices(spp as usize, color, alpha_at, out_layout.has_alpha()); - let mut lay = Layout { - w: wu, - src, - out, - out_layout, - chunk_spp, - planar, - planes: if planar { out_layout.channels() } else { 1 }, - cw, - across, - chunks_per_plane, - invert: invert && palette.is_none(), - alpha_sample, - premultiplied: out_layout.has_alpha() && alpha_at.and_then(|a| extra.get(a)) == Some(&1), - palette, - scratch_cap, - extra_at, - }; - // Extra samples share the allocation budget with the image: their interleaved buffer and the - // planes split from it are held next to the image, so both count against `max_alloc`. When - // they don't fit, the image still opens (it passed its own check above) without them. - let mut extras_dropped = 0; - if !lay.extra_at.is_empty() { - let per_pixel = out_layout.channels().saturating_add(lay.extra_at.len().saturating_mul(2)).saturating_mul(out.bytes()); - if limits.check_bytes(w, h, per_pixel as u64).is_err() { - extras_dropped = u32::try_from(lay.extra_at.len()).unwrap_or(u32::MAX); - lay.extra_at.clear(); - } - } - - // The output, allocated once and fallibly. - let out_row = lay.out_row(); - let len = out_row.checked_mul(hu).ok_or_else(|| CodecError::LimitExceeded("image size".into()))?; - let mut data = zeroed(len)?; - let band_bytes = out_row.checked_mul(ch.min(hu)).ok_or_else(|| CodecError::LimitExceeded("band size".into()))?; - - let extra_row = lay.extra_row(); - let extra_len = extra_row.checked_mul(hu).ok_or_else(|| CodecError::LimitExceeded("extra samples".into()))?; - let mut extra_data = if lay.extra_at.is_empty() { Vec::new() } else { zeroed(extra_len)? }; - let extra_band = extra_row.saturating_mul(ch.min(hu)); - let tally = decode_bands(&lay, &mut data, band_bytes, extra_data.as_mut_slice(), extra_band, &mut dec, &open)?; - if tally.decoded == 0 && tally.missing > 0 { - return Err(err("the image data is missing (cut off or past the end of the file)")); - } - if lab { - convert_ab(&mut data, out_layout.channels(), out, photometric == 8, false); - } - let mut img = Image::from_raw(w, h, out_layout, out, data)?; - if !lay.extra_at.is_empty() { - // TIFF 6.0 defines ExtraSamples 0, 1 and 2 only; a reserved value reads as unspecified, - // so a save never writes it back. - let kind_of = |si: usize| match si.checked_sub(color).and_then(|k| extra.get(k)).copied() { - Some(v @ 0..=2) => v as u16, - _ => 0, - }; - img.meta.extra_samples = split_extra_samples(&extra_data, wu, hu, &lay.extra_at, out, kind_of)?; - } - if extras_over_limit > 0 { - let count = u32::try_from(extras_over_limit).unwrap_or(u32::MAX); - img.warnings.push(DecodeWarning::ExtraSamplesOverLimit { format: F, count }); - } - if extras_dropped > 0 { - img.warnings.push(DecodeWarning::ExtraSamplesDropped { format: F, count: extras_dropped }); - } - if tally.missing > 0 { - img.warnings.push(DecodeWarning::Truncated { format: F }); - } - Ok(img) -} - -/// The a* and b* samples (1 and 2 of every pixel) of a Lab image between the file's encoding and -/// PhotoCraft's (8 bits: `a + 128`; 16 bits: `(a + 128) · 257`). In the file, CIELab holds them -/// signed (8 bits: `a`; 16 bits: `a · 256`) and ICCLab offset (8 bits: `a + 128`; 16 bits: -/// `(a + 128) · 256`). `to_file` picks the direction; samples are native-endian. -fn convert_ab(data: &mut [u8], channels: usize, sample: SampleType, signed: bool, to_file: bool) { - match sample { - SampleType::U8 if signed => data.chunks_exact_mut(channels).for_each(|px| { - px[1] ^= 0x80; - px[2] ^= 0x80; - }), - SampleType::U16 => data.chunks_exact_mut(channels * 2).for_each(|px| { - for c in [1, 2] { - let v = u16::from_ne_bytes([px[2 * c], px[2 * c + 1]]); - // The file's value as `a · 256` (signed) and back. - let file_a256 = |v: u16| if signed { f64::from(v as i16) } else { f64::from(v) - 32768.0 }; - let out = if to_file { - let a256 = (f64::from(v) - 32896.0) * 256.0 / 257.0; - let a256 = a256.round().clamp(-32768.0, 32767.0); - if signed { (a256 as i16) as u16 } else { (a256 + 32768.0) as u16 } - } else { - (file_a256(v) * 257.0 / 256.0 + 32896.0).round().clamp(0.0, 65535.0) as u16 - }; - px[2 * c..2 * c + 2].copy_from_slice(&out.to_ne_bytes()); - } - }), - _ => {} - } -} - -/// File sample indices that are not a colour channel and not the one alpha sample, capped at -/// [`crate::MAX_EXTRA_SAMPLES`], and how many past the cap were left out. -fn extra_sample_indices(spp: usize, color: usize, alpha_at: Option, has_alpha: bool) -> (Vec, usize) { - let mut used = vec![false; spp]; - for i in 0..color.min(spp) { - if let Some(slot) = used.get_mut(i) { - *slot = true; - } - } - if has_alpha { - let a = alpha_at.map(|k| color.saturating_add(k)).unwrap_or(color); - if let Some(slot) = used.get_mut(a) { - *slot = true; - } - } - let mut all: Vec = used.into_iter().enumerate().filter(|(_, on)| !*on).map(|(i, _)| i).collect(); - let over = all.len().saturating_sub(crate::MAX_EXTRA_SAMPLES); - all.truncate(crate::MAX_EXTRA_SAMPLES); - (all, over) -} - -/// Interleaved extra samples (`extra_at.len()` per pixel) → one plane per sample. Each plane is -/// allocated fallibly (the caller has checked their total against the limits). -fn split_extra_samples( - buf: &[u8], - w: usize, - h: usize, - at: &[usize], - sample: SampleType, - mut kind_of: impl FnMut(usize) -> u16, -) -> Result, CodecError> { - let b = sample.bytes(); - let n = w.saturating_mul(h); - let spp = at.len(); - let mut out = Vec::with_capacity(spp); - for (ei, &si) in at.iter().enumerate() { - let mut data = zeroed(n.saturating_mul(b))?; - for i in 0..n { - let src = (i.saturating_mul(spp).saturating_add(ei)).saturating_mul(b); - let dst = i.saturating_mul(b); - if let (Some(s), Some(d)) = (buf.get(src..src.saturating_add(b)), data.get_mut(dst..dst.saturating_add(b))) { - d.copy_from_slice(s); - } - } - out.push(crate::ExtraSample { kind: kind_of(si), data }); - } - Ok(out) -} - -/// A zero-filled buffer, allocated fallibly. On native targets the zeroing (and the first -/// touch of every page, which dominates on a fresh multi-hundred-megabyte buffer) is spread over -/// all cores. -fn zeroed(len: usize) -> Result, CodecError> { - let mut v = Vec::new(); - v.try_reserve_exact(len).map_err(|_| CodecError::LimitExceeded(format!("cannot allocate {len} bytes for the image")))?; - #[cfg(not(target_arch = "wasm32"))] - { - use rayon::prelude::*; - // The capacity is already there: this only writes the zeros. - v.par_extend(rayon::iter::repeat_n(0u8, len)); - } - #[cfg(target_arch = "wasm32")] - v.resize(len, 0); - Ok(v) -} - -/// Chunks decoded and chunks whose data ended early. -#[derive(Default, Clone, Copy)] -struct Tally { - decoded: usize, - missing: usize, -} - -impl std::ops::Add for Tally { - type Output = Tally; - fn add(self, o: Tally) -> Tally { - Tally { decoded: self.decoded + o.decoded, missing: self.missing + o.missing } - } -} - -/// Decodes every band into `data`, in parallel on native targets (one decoder and scratch -/// buffer per worker). `extra` receives samples that are not part of the colour image, one -/// band of rows at a time, when it is non-empty. -#[cfg(not(target_arch = "wasm32"))] -fn decode_bands<'a, O>( - lay: &Layout, - data: &mut [u8], - band_bytes: usize, - extra: &mut [u8], - extra_band: usize, - _first: &mut Decoder>, - open: &O, -) -> Result -where - O: Fn() -> Result>, CodecError> + Sync, -{ - use rayon::prelude::*; - if extra.is_empty() { - return data - .par_chunks_mut(band_bytes.max(1)) - .enumerate() - .map_init( - || open().map(|d| (d, Vec::new())).map_err(|e| e.to_string()), - |worker, (b, band)| { - let (dec, scratch) = worker.as_mut().map_err(|e| err(e.clone()))?; - decode_band(lay, dec, scratch, b, band, None) - }, - ) - .try_reduce(Tally::default, |a, b| Ok(a + b)); - } - data.par_chunks_mut(band_bytes.max(1)) - .zip(extra.par_chunks_mut(extra_band.max(1))) - .enumerate() - .map_init( - || open().map(|d| (d, Vec::new())).map_err(|e| e.to_string()), - |worker, (b, (band, extra_band))| { - let (dec, scratch) = worker.as_mut().map_err(|e| err(e.clone()))?; - decode_band(lay, dec, scratch, b, band, Some(extra_band)) - }, - ) - .try_reduce(Tally::default, |a, b| Ok(a + b)) -} - -/// Decodes every band into `data`, one after the other. -#[cfg(target_arch = "wasm32")] -fn decode_bands<'a, O>( - lay: &Layout, - data: &mut [u8], - band_bytes: usize, - extra: &mut [u8], - extra_band: usize, - first: &mut Decoder>, - _open: &O, -) -> Result -where - O: Fn() -> Result>, CodecError> + Sync, -{ - let mut scratch = Vec::new(); - let mut tally = Tally::default(); - if extra.is_empty() { - for (b, band) in data.chunks_mut(band_bytes.max(1)).enumerate() { - tally = tally + decode_band(lay, first, &mut scratch, b, band, None)?; - } - return Ok(tally); - } - for (b, (band, extra_band)) in data.chunks_mut(band_bytes.max(1)).zip(extra.chunks_mut(extra_band.max(1))).enumerate() { - tally = tally + decode_band(lay, first, &mut scratch, b, band, Some(extra_band))?; - } - Ok(tally) -} - -/// Decodes band `b` (one strip, or one row of tiles, in every plane) into its output rows. -fn decode_band( - lay: &Layout, - dec: &mut Decoder>, - scratch: &mut Vec, - b: usize, - band: &mut [u8], - mut extra: Option<&mut [u8]>, -) -> Result { - let out_row = lay.out_row(); - let rows = band.len() / out_row.max(1); - let px = lay.out_channels() * lay.out.bytes(); - let mut tally = Tally::default(); - for plane in 0..lay.planes { - let file_plane = lay.source_sample(plane); - for col in 0..lay.across { - let chunk = file_plane - .checked_mul(lay.chunks_per_plane) - .and_then(|c| c.checked_add(b.checked_mul(lay.across)?)) - .and_then(|c| c.checked_add(col)) - .and_then(|c| u32::try_from(c).ok()) - .ok_or_else(|| err("chunk index out of range"))?; - let pref = dec.image_chunk_buffer_layout(chunk).map_err(map_err)?; - let stride = pref.row_stride.map(|s| s.get()).ok_or_else(|| err("empty chunk row"))?; - // In place: the strip's decoded bytes are exactly its output rows. - if lay.direct() && pref.len == band.len() && stride == out_row { - match dec.read_chunk_bytes(chunk, band) { - Ok(()) => tally.decoded += 1, - Err(e) if is_eof(&e) => tally.missing += 1, - Err(e) => return Err(map_err(e)), - } - continue; - } - if pref.len > lay.scratch_cap { - return Err(CodecError::LimitExceeded(format!("a {} byte strip or tile", pref.len))); - } - if scratch.len() < pref.len { - scratch.resize(pref.len, 0); - } - let buf = scratch.get_mut(..pref.len).ok_or_else(|| err("scratch buffer"))?; - match dec.read_chunk_bytes(chunk, buf) { - Ok(()) => tally.decoded += 1, - Err(e) if is_eof(&e) => { - tally.missing += 1; - continue; - } - Err(e) => return Err(map_err(e)), - } - let x0 = col * lay.cw; - let n = lay.cw.min(lay.w.saturating_sub(x0)); - for (ri, (src_row, dst_row)) in buf.chunks_exact(stride).zip(band.chunks_exact_mut(out_row)).take(rows).enumerate() { - let Some(dst) = dst_row.get_mut(x0 * px..(x0 + n) * px) else { continue }; - convert_row(lay, src_row, dst, n, plane); - if !lay.planar && plane == 0 && !lay.extra_at.is_empty() { - let erow = lay.extra_row(); - if let Some(extra) = extra.as_deref_mut() - && let Some(er) = extra.get_mut(ri.saturating_mul(erow)..ri.saturating_mul(erow).saturating_add(erow)) - { - deposit_extras(lay, src_row, er, n, x0); - } - } - } - } - } - if lay.planar && !lay.extra_at.is_empty() { - read_planar_extras(lay, dec, scratch, b, rows, extra, &mut tally)?; - } - finish_band(lay, band); - Ok(tally) -} - -/// Copies the non-colour samples of a chunky row into the extra-sample band. -fn deposit_extras(lay: &Layout, src: &[u8], dst: &mut [u8], n: usize, x0: usize) { - let ech = lay.extra_at.len(); - if ech == 0 { - return; - } - let px = ech * lay.out.bytes(); - let Some(dst) = dst.get_mut(x0.saturating_mul(px)..(x0.saturating_add(n)).saturating_mul(px)) else { return }; - for (ei, &si) in lay.extra_at.iter().enumerate() { - transfer(lay.src, src, lay.chunk_spp, si, dst, lay.out, ech, ei, n); - } -} - -/// Planar files store each extra sample as its own plane. Read those planes into `extra`. -fn read_planar_extras( - lay: &Layout, - dec: &mut Decoder>, - scratch: &mut Vec, - b: usize, - rows: usize, - extra: Option<&mut [u8]>, - tally: &mut Tally, -) -> Result<(), CodecError> { - let Some(extra) = extra else { return Ok(()) }; - let ech = lay.extra_at.len(); - let erow = lay.extra_row(); - if ech == 0 || erow == 0 { - return Ok(()); - } - for (ei, &file_plane) in lay.extra_at.iter().enumerate() { - for col in 0..lay.across { - let chunk = file_plane - .checked_mul(lay.chunks_per_plane) - .and_then(|c| c.checked_add(b.checked_mul(lay.across)?)) - .and_then(|c| c.checked_add(col)) - .and_then(|c| u32::try_from(c).ok()) - .ok_or_else(|| err("chunk index out of range"))?; - let pref = dec.image_chunk_buffer_layout(chunk).map_err(map_err)?; - let stride = pref.row_stride.map(|s| s.get()).ok_or_else(|| err("empty chunk row"))?; - if pref.len > lay.scratch_cap { - return Err(CodecError::LimitExceeded(format!("a {} byte strip or tile", pref.len))); - } - if scratch.len() < pref.len { - scratch.resize(pref.len, 0); - } - let buf = scratch.get_mut(..pref.len).ok_or_else(|| err("scratch buffer"))?; - match dec.read_chunk_bytes(chunk, buf) { - Ok(()) => tally.decoded += 1, - Err(e) if is_eof(&e) => { - tally.missing += 1; - continue; - } - Err(e) => return Err(map_err(e)), - } - let x0 = col * lay.cw; - let n = lay.cw.min(lay.w.saturating_sub(x0)); - for (ri, src_row) in buf.chunks_exact(stride).take(rows).enumerate() { - let start = ri.saturating_mul(erow); - let Some(er) = extra.get_mut(start..start.saturating_add(erow)) else { continue }; - let px = ech * lay.out.bytes(); - let Some(dst) = er.get_mut(x0.saturating_mul(px)..(x0.saturating_add(n)).saturating_mul(px)) else { continue }; - transfer(lay.src, src_row, 1, 0, dst, lay.out, ech, ei, n); - } - } - } - Ok(()) -} - -/// Converts `n` pixels of one decoded chunk row into output pixels (`plane` for planar data). -fn convert_row(lay: &Layout, src: &[u8], dst: &mut [u8], n: usize, plane: usize) { - let och = lay.out_channels(); - if let Some(map) = &lay.palette { - let ob = lay.out.bytes(); - for (i, d) in dst.chunks_exact_mut(och * ob).take(n).enumerate() { - let index = sample_index(lay.src, src, i); - let Some(rgb) = map.get(index) else { continue }; - for (c, v) in d.chunks_exact_mut(ob).zip(rgb) { - if ob == 1 { - c.copy_from_slice(&[(v >> 8) as u8]); - } else { - c.copy_from_slice(&v.to_ne_bytes()); - } - } - } - return; - } - if lay.copyable() { - if let Some(s) = src.get(..dst.len()) { - dst.copy_from_slice(s); - } - return; - } - if lay.planar { - transfer(lay.src, src, 1, 0, dst, lay.out, och, plane, n); - } else { - for k in 0..och { - transfer(lay.src, src, lay.chunk_spp, lay.source_sample(k), dst, lay.out, och, k, n); - } - } -} - -/// The value of pixel `i` in a row of one-sample indices (palette and sub-byte gray). -fn sample_index(src: Src, row: &[u8], i: usize) -> usize { - match src { - Src::Bits(bits) => { - let bits = usize::from(bits); - let bit = i * bits; - let byte = row.get(bit / 8).copied().unwrap_or(0); - usize::from((byte >> (8 - bits - bit % 8)) & ((1u8 << bits) - 1)) - } - Src::U8 => row.get(i).copied().map_or(0, usize::from), - Src::U16 => row.get(i * 2..i * 2 + 2).and_then(|s| s.try_into().ok()).map_or(0, |s| usize::from(u16::from_ne_bytes(s))), - _ => 0, - } -} - -/// Copies sample `si` of each of `n` decoded pixels (`sspp` samples each) to output channel -/// `di` (`dch` channels), converting the sample type. -#[allow(clippy::too_many_arguments)] -fn transfer(src: Src, row: &[u8], sspp: usize, si: usize, dst: &mut [u8], out: SampleType, dch: usize, di: usize, n: usize) { - let ob = out.bytes(); - if let Src::Bits(bits) = src { - let max = (1u32 << bits) - 1; - for (i, d) in dst.chunks_exact_mut(dch * ob).take(n).enumerate() { - if let Some(d) = d.get_mut(di) { - *d = (sample_index(src, row, i) as u32 * 255 / max) as u8; - } - } - return; - } - let sb = src.bytes(); - if src.is_identity() { - // Same sample type: a strided copy. - if sb == 1 { - for (d, s) in dst.iter_mut().skip(di).step_by(dch).zip(row.iter().skip(si).step_by(sspp)).take(n) { - *d = *s; - } - } else { - for (d, s) in dst.chunks_exact_mut(ob).skip(di).step_by(dch).zip(row.chunks_exact(sb).skip(si).step_by(sspp)).take(n) { - d.copy_from_slice(s); - } - } - return; - } - for (s, d) in row.chunks_exact(sspp * sb).zip(dst.chunks_exact_mut(dch * ob)).take(n) { - let (Some(s), Some(d)) = (s.get(si * sb..(si + 1) * sb), d.get_mut(di * ob..(di + 1) * ob)) else { continue }; - match src { - Src::U32 => { - let v = s.try_into().map_or(0, u32::from_ne_bytes); - d.copy_from_slice(&((v >> 16) as u16).to_ne_bytes()); - } - Src::U64 => { - let v = s.try_into().map_or(0, u64::from_ne_bytes); - d.copy_from_slice(&((v >> 48) as u16).to_ne_bytes()); - } - Src::F64 => { - let v = s.try_into().map_or(0.0, f64::from_ne_bytes); - d.copy_from_slice(&(v as f32).to_ne_bytes()); - } - _ => d.copy_from_slice(s), - } - } -} - -/// Applies what the stored samples leave to the reader: WhiteIsZero inversion of the gray -/// channel, and turning associated (premultiplied) alpha into straight alpha. -fn finish_band(lay: &Layout, band: &mut [u8]) { - if !lay.invert && !lay.premultiplied { - return; - } - let ch = lay.out_channels(); - let ob = lay.out.bytes(); - let color = lay.out_layout.color_channels(); - for p in band.chunks_exact_mut(ch * ob) { - match lay.out { - SampleType::U8 => { - if lay.invert - && let Some(g) = p.first_mut() - { - *g = 255 - *g; - } - if lay.premultiplied { - let a = u32::from(p.get(ch - 1).copied().unwrap_or(255)); - for c in p.iter_mut().take(color) { - *c = (u32::from(*c) * 255 + a / 2).checked_div(a).unwrap_or(0).min(255) as u8; - } - } - } - SampleType::U16 => { - let get = |p: &[u8], i: usize| p.get(i * 2..i * 2 + 2).and_then(|s| s.try_into().ok()).map_or(0, u16::from_ne_bytes); - let a = u32::from(get(p, ch - 1)); - for i in 0..color { - let mut v = u32::from(get(p, i)); - if lay.invert && i == 0 { - v = 65535 - v; - } - if lay.premultiplied { - v = (v * 65535 + a / 2).checked_div(a).unwrap_or(0).min(65535); - } - if let Some(s) = p.get_mut(i * 2..i * 2 + 2) { - s.copy_from_slice(&(v as u16).to_ne_bytes()); - } - } - } - SampleType::F16 | SampleType::F32 => { - let get = |p: &[u8], i: usize| -> f32 { - if ob == 2 { - p.get(i * 2..i * 2 + 2).and_then(|s| s.try_into().ok()).map_or(0.0, |s| f16::from_bits(u16::from_ne_bytes(s)).to_f32()) - } else { - p.get(i * 4..i * 4 + 4).and_then(|s| s.try_into().ok()).map_or(0.0, f32::from_ne_bytes) - } - }; - let a = get(p, ch - 1); - for i in 0..color { - let mut v = get(p, i); - if lay.invert && i == 0 { - v = 1.0 - v; - } - if lay.premultiplied && a > 0.0 { - v /= a; - } - if ob == 2 { - if let Some(s) = p.get_mut(i * 2..i * 2 + 2) { - s.copy_from_slice(&f16::from_f32(v).to_bits().to_ne_bytes()); - } - } else if let Some(s) = p.get_mut(i * 4..i * 4 + 4) { - s.copy_from_slice(&v.to_ne_bytes()); - } - } - } - } - } -} - -// --------------------------------------------------------------------------- -// Encoding -// --------------------------------------------------------------------------- - -/// Bytes written with TIFF type UNDEFINED (7), as required for ICC. -struct Undefined<'a>(&'a [u8]); - -impl TiffValue for Undefined<'_> { - const BYTE_LEN: u8 = 1; - const FIELD_TYPE: Type = Type::UNDEFINED; - fn count(&self) -> usize { - self.0.len() - } - fn data(&self) -> Cow<'_, [u8]> { - Cow::Borrowed(self.0) - } -} - macro_rules! custom_colortype { ($name:ident, $inner:ty, $photo:expr, $bits:expr, $fmt:expr, int) => { struct $name; @@ -1300,6 +161,18 @@ macro_rules! custom_colortype { } use PhotometricInterpretation as PI; + +mod bands; +mod decode; +mod encode; +mod tags; + +pub(crate) use decode::{decode, decode_page, orientation}; +pub(crate) use encode::encode; +#[cfg(test)] +use encode::{Extras, try_with_capacity}; +use tags::F; +pub use tags::{PhotoshopTags, photoshop_tags, writes_little_endian}; custom_colortype!(GrayA8, u8, PI::BlackIsZero, &[8, 8], &[SampleFormat::Uint; 2], int); custom_colortype!(GrayA16, u16, PI::BlackIsZero, &[16, 16], &[SampleFormat::Uint; 2], int); custom_colortype!(GrayA32F, f32, PI::BlackIsZero, &[32, 32], &[SampleFormat::IEEEFP; 2], float); @@ -1311,481 +184,6 @@ custom_colortype!(Lab16, u16, PI::CIELab, &[16; 3], &[SampleFormat::Uint; 3], in custom_colortype!(LabA8, u8, PI::CIELab, &[8; 4], &[SampleFormat::Uint; 4], int); custom_colortype!(LabA16, u16, PI::CIELab, &[16; 4], &[SampleFormat::Uint; 4], int); -// Colour types with 1..=MAX_EXTRA_SAMPLES trailing extra samples (spot channels, extra alpha). -// One generic type per (sample, photometric, bit depth, total sample count) instead of a -// hand-written type for every layout. `N` is the total sample count, not the extra count. -const fn extra_photo(v: u16) -> PhotometricInterpretation { - match v { - 1 => PhotometricInterpretation::BlackIsZero, - 2 => PhotometricInterpretation::RGB, - 5 => PhotometricInterpretation::CMYK, - 8 => PhotometricInterpretation::CIELab, - _ => PhotometricInterpretation::RGB, - } -} - -trait ExtraKind: Copy + TiffValue + 'static { - const FORMAT: SampleFormat; - fn predict(row: &[Self], out: &mut Vec, samples: usize); -} - -impl ExtraKind for u8 { - const FORMAT: SampleFormat = SampleFormat::Uint; - fn predict(row: &[Self], out: &mut Vec, samples: usize) { - let n = samples.min(row.len()); - out.extend_from_slice(&row[..n]); - out.extend(row.iter().zip(&row[n..]).map(|(prev, current)| current.wrapping_sub(*prev))); - } -} - -impl ExtraKind for u16 { - const FORMAT: SampleFormat = SampleFormat::Uint; - fn predict(row: &[Self], out: &mut Vec, samples: usize) { - let n = samples.min(row.len()); - out.extend_from_slice(&row[..n]); - out.extend(row.iter().zip(&row[n..]).map(|(prev, current)| current.wrapping_sub(*prev))); - } -} - -impl ExtraKind for f32 { - const FORMAT: SampleFormat = SampleFormat::IEEEFP; - fn predict(row: &[Self], out: &mut Vec, _samples: usize) { - out.extend_from_slice(row); - } -} - -struct Extras(std::marker::PhantomData); - -impl TiffColorType for Extras -where - T: ExtraKind, -{ - type Inner = T; - const TIFF_VALUE: PhotometricInterpretation = extra_photo(PHOTO); - const BITS_PER_SAMPLE: &'static [u16] = &[BITS; N]; - const SAMPLE_FORMAT: &'static [SampleFormat] = &[T::FORMAT; N]; - fn horizontal_predict(row: &[Self::Inner], result: &mut Vec) { - T::predict(row, result, N); - } -} - -macro_rules! write_extras { - ($n:expr, $enc:expr, $w:expr, $h:expr, $data:expr, $tags:expr, $sample:ty, $photo:literal, $bits:literal, $base:literal) => { - match $n { - 1 => write_one::, K>($enc, $w, $h, $data, $tags), - 2 => write_one::, K>($enc, $w, $h, $data, $tags), - 3 => write_one::, K>($enc, $w, $h, $data, $tags), - 4 => write_one::, K>($enc, $w, $h, $data, $tags), - 5 => write_one::, K>($enc, $w, $h, $data, $tags), - 6 => write_one::, K>($enc, $w, $h, $data, $tags), - 7 => write_one::, K>($enc, $w, $h, $data, $tags), - 8 => write_one::, K>($enc, $w, $h, $data, $tags), - 9 => write_one::, K>($enc, $w, $h, $data, $tags), - 10 => write_one::, K>($enc, $w, $h, $data, $tags), - 11 => write_one::, K>($enc, $w, $h, $data, $tags), - 12 => write_one::, K>($enc, $w, $h, $data, $tags), - 13 => write_one::, K>($enc, $w, $h, $data, $tags), - 14 => write_one::, K>($enc, $w, $h, $data, $tags), - 15 => write_one::, K>($enc, $w, $h, $data, $tags), - 16 => write_one::, K>($enc, $w, $h, $data, $tags), - other => Err(io::Error::new(io::ErrorKind::InvalidInput, format!("unsupported extra samples ({other})")).into()), - } - }; -} - -/// An empty buffer with room for `len` elements, allocated fallibly: a save too large for memory -/// is an error, not an abort. -fn try_with_capacity(len: usize) -> io::Result> { - let mut v = Vec::new(); - v.try_reserve_exact(len).map_err(|_| io::Error::new(io::ErrorKind::OutOfMemory, format!("cannot allocate {len} samples for the extra samples")))?; - Ok(v) -} - -fn bytes_as_u16(b: &[u8]) -> io::Result> { - let chunks = b.as_chunks::<2>().0; - let mut v = try_with_capacity(chunks.len())?; - v.extend(chunks.iter().map(|c| u16::from_ne_bytes(*c))); - Ok(v) -} - -fn bytes_as_f32(b: &[u8]) -> io::Result> { - let chunks = b.as_chunks::<4>().0; - let mut v = try_with_capacity(chunks.len())?; - v.extend(chunks.iter().map(|c| f32::from_ne_bytes(*c))); - Ok(v) -} - -/// Interleaves colour (and alpha) samples with [`Metadata::extra_samples`]. -fn interleave_extras(img: &Image) -> Result, String> { - let (w, h) = img.dimensions(); - let n = (w as usize).checked_mul(h as usize).ok_or_else(|| "image size overflows".to_string())?; - let sb = img.sample_type().bytes(); - let ch = img.layout().channels(); - let extras = &img.meta.extra_samples; - let total = ch.checked_add(extras.len()).ok_or_else(|| "too many samples".to_string())?; - let px = total.checked_mul(sb).ok_or_else(|| "sample size overflows".to_string())?; - let len = n.checked_mul(px).ok_or_else(|| "image size overflows".to_string())?; - let mut out = try_with_capacity::(len).map_err(|e| e.to_string())?; - out.resize(len, 0); - let base = img.data(); - let base_px = ch.saturating_mul(sb); - for i in 0..n { - let src = i.saturating_mul(base_px); - let dst = i.saturating_mul(px); - let Some(s) = base.get(src..src.saturating_add(base_px)) else { - return Err("image buffer is shorter than its dimensions".into()); - }; - let Some(d) = out.get_mut(dst..dst.saturating_add(base_px)) else { - return Err("extra-sample buffer is short".into()); - }; - d.copy_from_slice(s); - for (k, e) in extras.iter().enumerate() { - let es = i.saturating_mul(sb); - let ed = dst.saturating_add(base_px).saturating_add(k.saturating_mul(sb)); - let Some(s) = e.data.get(es..es.saturating_add(sb)) else { - return Err(format!("extra sample {k} is shorter than the image")); - }; - let Some(d) = out.get_mut(ed..ed.saturating_add(sb)) else { - return Err("extra-sample buffer is short".into()); - }; - d.copy_from_slice(s); - } - } - Ok(out) -} - -fn write_with_extras(enc: &mut TiffEncoder<&mut Cursor>, K>, img: &Image, tags: &TagSet<'_>) -> tiff::TiffResult<()> { - use ChannelLayout as L; - use SampleType as S; - let (w, h) = img.dimensions(); - let n = img.meta.extra_samples.len(); - if img.layout().is_lab() { - let file = lab_file(img); - let bytes = interleave_extras(&file).map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?; - return match (file.layout(), file.sample_type()) { - (L::Lab, S::U8) => write_extras!(n, enc, w, h, &bytes, tags, u8, 8, 8, 3), - (L::Lab, _) => { - let v = bytes_as_u16(&bytes)?; - write_extras!(n, enc, w, h, &v, tags, u16, 8, 16, 3) - } - (_, S::U8) => write_extras!(n, enc, w, h, &bytes, tags, u8, 8, 8, 4), - _ => { - let v = bytes_as_u16(&bytes)?; - write_extras!(n, enc, w, h, &v, tags, u16, 8, 16, 4) - } - }; - } - let bytes = interleave_extras(img).map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?; - match (img.layout(), img.sample_type()) { - (L::Gray, S::U8) => write_extras!(n, enc, w, h, &bytes, tags, u8, 1, 8, 1), - (L::Gray, S::U16) => { - let v = bytes_as_u16(&bytes)?; - write_extras!(n, enc, w, h, &v, tags, u16, 1, 16, 1) - } - (L::Gray, S::F32) => { - let v = bytes_as_f32(&bytes)?; - write_extras!(n, enc, w, h, &v, tags, f32, 1, 32, 1) - } - (L::GrayA, S::U8) => write_extras!(n, enc, w, h, &bytes, tags, u8, 1, 8, 2), - (L::GrayA, S::U16) => { - let v = bytes_as_u16(&bytes)?; - write_extras!(n, enc, w, h, &v, tags, u16, 1, 16, 2) - } - (L::GrayA, S::F32) => { - let v = bytes_as_f32(&bytes)?; - write_extras!(n, enc, w, h, &v, tags, f32, 1, 32, 2) - } - (L::Rgb, S::U8) => write_extras!(n, enc, w, h, &bytes, tags, u8, 2, 8, 3), - (L::Rgb, S::U16) => { - let v = bytes_as_u16(&bytes)?; - write_extras!(n, enc, w, h, &v, tags, u16, 2, 16, 3) - } - (L::Rgb, S::F32) => { - let v = bytes_as_f32(&bytes)?; - write_extras!(n, enc, w, h, &v, tags, f32, 2, 32, 3) - } - (L::Rgba, S::U8) => write_extras!(n, enc, w, h, &bytes, tags, u8, 2, 8, 4), - (L::Rgba, S::U16) => { - let v = bytes_as_u16(&bytes)?; - write_extras!(n, enc, w, h, &v, tags, u16, 2, 16, 4) - } - (L::Rgba, S::F32) => { - let v = bytes_as_f32(&bytes)?; - write_extras!(n, enc, w, h, &v, tags, f32, 2, 32, 4) - } - (L::Cmyk, S::U8) => write_extras!(n, enc, w, h, &bytes, tags, u8, 5, 8, 4), - (L::Cmyk, S::U16) => { - let v = bytes_as_u16(&bytes)?; - write_extras!(n, enc, w, h, &v, tags, u16, 5, 16, 4) - } - (L::Cmyk, S::F32) => { - let v = bytes_as_f32(&bytes)?; - write_extras!(n, enc, w, h, &v, tags, f32, 5, 32, 4) - } - (L::CmykA, S::U8) => write_extras!(n, enc, w, h, &bytes, tags, u8, 5, 8, 5), - (L::CmykA, S::U16) => { - let v = bytes_as_u16(&bytes)?; - write_extras!(n, enc, w, h, &v, tags, u16, 5, 16, 5) - } - (L::CmykA, S::F32) => { - let v = bytes_as_f32(&bytes)?; - write_extras!(n, enc, w, h, &v, tags, f32, 5, 32, 5) - } - _ => Err(io::Error::new(io::ErrorKind::InvalidInput, format!("unsupported extra samples ({n})")).into()), - } -} - -struct TagSet<'a> { - icc: Option<&'a [u8]>, - /// The EXIF block's directories and IFD0 tags, written as the TIFF's own. - exif: Option, - xmp: Option<&'a [u8]>, - dpi: Option<(f32, f32)>, - text: Vec<(Tag, &'a str)>, - /// ExtraSamples tag, including the unassociated-alpha marker when the image has alpha. - extra_samples: &'a [u16], - photoshop_resources: Option<&'a [u8]>, - photoshop_layers: Option<&'a [u8]>, -} - -/// Writes one image directory. (The `tiff` encoder only compresses through `write_data`, which -/// takes every sample at once.) -fn write_one(enc: &mut TiffEncoder<&mut Cursor>, K>, w: u32, h: u32, data: &[C::Inner], tags: &TagSet<'_>) -> tiff::TiffResult<()> -where - C: TiffColorType, - [C::Inner]: TiffValue, - K: TiffKind, -{ - // The Exif and GPS directories go before the image, outside its chain; IFD0 points to them. - let mut sub = |e: &ExifDirs, fields: &[tiff_exif::Field]| (!fields.is_empty()).then(|| tiff_exif::write_directory(enc, fields, e.le)).transpose(); - let exif_at = match &tags.exif { - Some(e) => sub(e, &e.exif)?, - None => None, - }; - let gps_at = match &tags.exif { - Some(e) => sub(e, &e.gps)?, - None => None, - }; - let mut im = enc.new_image::(w, h)?; - if let Some((x, y)) = tags.dpi { - im.resolution_unit(ResolutionUnit::Inch); - im.x_resolution(Rational { n: (x * 1000.0).round() as u32, d: 1000 }); - im.y_resolution(Rational { n: (y * 1000.0).round() as u32, d: 1000 }); - } - let d = im.encoder(); - if !tags.extra_samples.is_empty() { - d.write_tag(Tag::ExtraSamples, tags.extra_samples)?; - } - if let Some(icc) = tags.icc { - d.write_tag(Tag::IccProfile, Undefined(icc))?; - } - if let Some(xmp) = tags.xmp { - d.write_tag(Tag::Unknown(TAG_XMP), xmp)?; - } - for (tag, s) in &tags.text { - d.write_tag(*tag, *s)?; - } - if let Some(e) = &tags.exif { - // The EXIF block's descriptive IFD0 tags, unless the text metadata already wrote them. - let ifd0: Vec = e.ifd0.iter().filter(|f| !tags.text.iter().any(|(t, _)| t.to_u16() == f.tag)).cloned().collect(); - tiff_exif::write_fields(d, &ifd0, e.le)?; - } - if let Some(at) = exif_at { - d.write_tag(Tag::Unknown(tiff_exif::TAG_EXIF_IFD), at)?; - } - if let Some(at) = gps_at { - d.write_tag(Tag::Unknown(tiff_exif::TAG_GPS_IFD), at)?; - } - if let Some(r) = tags.photoshop_resources { - d.write_tag(Tag::Unknown(TAG_PHOTOSHOP), r)?; - } - if let Some(l) = tags.photoshop_layers { - d.write_tag(Tag::Unknown(TAG_IMAGE_SOURCE_DATA), Undefined(l))?; - } - im.write_data(data) -} - -/// A Lab image as CIELab stores it: a* and b* signed, 8 or 16 bits (CIELab has no float form: -/// 32-bit Lab is written with 16 bits). Extra samples follow the new sample type. -fn lab_file(img: &Image) -> Image { - let sample = if img.sample_type() == SampleType::U8 { SampleType::U8 } else { SampleType::U16 }; - // `convert` brings the extra samples to the new sample type with the image. - let mut file = img.convert(img.layout(), sample); - let channels = file.layout().channels(); - convert_ab(file.data_mut(), channels, sample, true, true); - file -} - -/// Writes the image with the colour type matching its layout and sample type. -fn write_image(enc: &mut TiffEncoder<&mut Cursor>, K>, img: &Image, tags: &TagSet<'_>) -> tiff::TiffResult<()> { - use ChannelLayout as L; - use SampleType as S; - if !img.meta.extra_samples.is_empty() { - return write_with_extras::(enc, img, tags); - } - let (w, h) = img.dimensions(); - let u16s = || img.to_u16_samples().unwrap_or_default(); - let f32s = || img.to_f32_samples().unwrap_or_default(); - let d8 = img.data(); - match (img.layout(), img.sample_type()) { - (L::Gray, S::U8) => write_one::(enc, w, h, d8, tags), - (L::Gray, S::U16) => write_one::(enc, w, h, &u16s(), tags), - (L::Gray, S::F32) => write_one::(enc, w, h, &f32s(), tags), - (L::GrayA, S::U8) => write_one::(enc, w, h, d8, tags), - (L::GrayA, S::U16) => write_one::(enc, w, h, &u16s(), tags), - (L::GrayA, S::F32) => write_one::(enc, w, h, &f32s(), tags), - (L::Rgb, S::U8) => write_one::(enc, w, h, d8, tags), - (L::Rgb, S::U16) => write_one::(enc, w, h, &u16s(), tags), - (L::Rgb, S::F32) => write_one::(enc, w, h, &f32s(), tags), - (L::Rgba, S::U8) => write_one::(enc, w, h, d8, tags), - (L::Rgba, S::U16) => write_one::(enc, w, h, &u16s(), tags), - (L::Rgba, S::F32) => write_one::(enc, w, h, &f32s(), tags), - (L::Cmyk, S::U8) => write_one::(enc, w, h, d8, tags), - (L::Cmyk, S::U16) => write_one::(enc, w, h, &u16s(), tags), - (L::Cmyk, S::F32) => write_one::(enc, w, h, &f32s(), tags), - (L::CmykA, S::U8) => write_one::(enc, w, h, d8, tags), - (L::CmykA, S::U16) => write_one::(enc, w, h, &u16s(), tags), - (L::CmykA, S::F32) => write_one::(enc, w, h, &f32s(), tags), - (L::Lab | L::LabA, _) => { - let file = lab_file(img); - let u16s = || file.to_u16_samples().unwrap_or_default(); - match (file.layout(), file.sample_type()) { - (L::Lab, S::U8) => write_one::(enc, w, h, file.data(), tags), - (L::Lab, _) => write_one::(enc, w, h, &u16s(), tags), - (_, S::U8) => write_one::(enc, w, h, file.data(), tags), - _ => write_one::(enc, w, h, &u16s(), tags), - } - } - (l, s) => Err(io::Error::new(io::ErrorKind::InvalidInput, format!("unsupported {l:?} {s:?}")).into()), - } -} - -/// Classic TIFF offsets are 32-bit: a file that may grow past this is written as BigTIFF. -const CLASSIC_LIMIT: u64 = u32::MAX as u64; - -/// An upper estimate of the file size: the uncompressed samples plus every tag payload plus -/// room for the directory and strip tables. -fn estimated_size(img: &Image, tags: &TagSet<'_>) -> u64 { - let payloads = [tags.icc, tags.xmp, tags.photoshop_resources, tags.photoshop_layers].iter().flatten().map(|p| p.len() as u64).sum::(); - let text = tags.text.iter().map(|(_, s)| s.len() as u64).sum::() - + tags.exif.iter().flat_map(|e| e.ifd0.iter().chain(&e.exif).chain(&e.gps)).map(|f| f.value.len() as u64 + 12).sum::(); - // Strip tables: one offset and one count per strip of about 1 MB. - let tables = (img.data().len() as u64 / (1 << 20) + 1) * 16; - let extras: u64 = img.meta.extra_samples.iter().map(|e| e.data.len() as u64).sum(); - (img.data().len() as u64).saturating_add(extras).saturating_add(payloads).saturating_add(text).saturating_add(tables).saturating_add(1 << 20) -} - -/// The byte length of one extra-sample plane: one sample per pixel of `img`, in its sample type. -/// `None` when the pixel count overflows a `usize` (no such image buffer can exist). -fn extra_plane_len(img: &Image) -> Option { - let (w, h) = img.dimensions(); - (w as usize).checked_mul(h as usize)?.checked_mul(img.sample_type().bytes()) -} - -/// Every extra plane must hold exactly one sample per pixel of `img`, in its sample type. -/// -/// The writer copies one sample per pixel out of each plane, so a plane of any other length -/// would be silently truncated (long) or read past its end (short). A sample-type conversion -/// reinterprets the bytes in the new width instead, so an unchecked plane would also change -/// meaning rather than fail. Refuse the image instead of writing either. -fn check_extra_planes(img: &Image) -> Result<(), CodecError> { - let (w, h) = img.dimensions(); - let sample = img.sample_type(); - let plane_len = extra_plane_len(img).ok_or_else(|| CodecError::encode(F, format!("the extra-sample size of a {w}x{h} image overflows")))?; - for (k, e) in img.meta.extra_samples.iter().enumerate() { - if e.data.len() != plane_len { - return Err(CodecError::encode( - F, - format!("extra sample {k} is {} bytes; a {w}x{h} {sample:?} image needs exactly {plane_len} (one sample per pixel)", e.data.len()), - )); - } - } - Ok(()) -} - -pub(crate) fn encode(src: &Image, plan: Plan, opts: &EncodeOptions) -> Result, CodecError> { - // Check the source planes before `converted`, which brings them to the plan's sample type - // with the image but deliberately leaves a wrong-sized plane alone: past that point a bad - // plane would be reinterpreted in the new width rather than rejected. - check_extra_planes(src)?; - // `converted` brings the extra samples to the plan's sample type with the image. - encode_ready(&src.converted(plan.layout, plan.sample), opts) -} - -fn encode_ready(img: &Image, opts: &EncodeOptions) -> Result, CodecError> { - let compression = match opts.tiff_compression { - TiffCompression::None => tiff::encoder::Compression::Uncompressed, - TiffCompression::Lzw => tiff::encoder::Compression::Lzw, - TiffCompression::Deflate => tiff::encoder::Compression::Deflate(tiff::encoder::DeflateLevel::Balanced), - TiffCompression::PackBits => tiff::encoder::Compression::Packbits, - }; - let predictor = if !img.sample_type().is_float() && matches!(opts.tiff_compression, TiffCompression::Lzw | TiffCompression::Deflate) { - tiff::encoder::Predictor::Horizontal - } else { - tiff::encoder::Predictor::None - }; - let text: Vec<(Tag, &str)> = if opts.embed_metadata { - img.meta - .text - .iter() - .filter_map(|(k, v)| TEXT_TAGS.iter().find(|(_, key)| key.eq_ignore_ascii_case(k)).map(|(t, _)| (*t, v.as_str()))) - .filter(|(_, v)| v.is_ascii() && !v.contains('\0')) - .collect() - } else { - Vec::new() - }; - // TIFF writes no Orientation tag (= 1): keep the XMP from contradicting it. - let xmp = if opts.embed_metadata { img.meta.xmp.as_deref().map(|x| crate::resolution::export_xmp(x, img.meta.dpi)) } else { None }; - if img.meta.extra_samples.len() > crate::MAX_EXTRA_SAMPLES { - return Err(CodecError::encode(F, format!("TIFF stores at most {} extra samples", crate::MAX_EXTRA_SAMPLES))); - } - // Validate again in the sample type the planes now hold: `Image::convert` takes a plane's - // bytes before it rebuilds them, so one it could not rebuild would arrive here empty. The Lab - // path's later re-type through `lab_file` converts a plane only when its length already - // matches the image, which this guarantees. - check_extra_planes(img)?; - let mut kinds = Vec::with_capacity(img.meta.extra_samples.len().saturating_add(1)); - if img.layout().has_alpha() { - kinds.push(2); - } - // TIFF 6.0 reserves ExtraSamples values above 2: those are written as 0 (unspecified). - for e in &img.meta.extra_samples { - kinds.push(if e.kind <= 2 { e.kind } else { 0 }); - } - let tags = TagSet { - icc: if opts.embed_icc { img.icc.as_deref() } else { None }, - exif: if opts.embed_metadata { img.meta.exif.as_deref().and_then(|e| tiff_exif::read(crate::orientation::tiff_body(e))) } else { None }, - xmp: xmp.as_deref().map(str::as_bytes), - dpi: if opts.embed_metadata { img.meta.dpi.filter(|d| d.0 > 0.0 && d.1 > 0.0) } else { None }, - text, - extra_samples: &kinds, - // Document content, not metadata: written whenever present. - photoshop_resources: img.meta.photoshop_resources.as_deref().filter(|r| !r.is_empty()), - photoshop_layers: img.meta.photoshop_layers.as_deref().filter(|l| !l.is_empty()), - }; - - // BigTIFF when asked, or when the file could pass the 4 GiB a classic TIFF can address. A - // classic write that still runs out of 32-bit offsets (compression grew the data) is redone - // as BigTIFF. - let write = |big: bool| -> tiff::TiffResult> { - let mut cursor = Cursor::new(Vec::new()); - if big { - let mut enc = TiffEncoder::new_big(&mut cursor)?.with_compression(compression).with_predictor(predictor); - write_image::(&mut enc, img, &tags)?; - } else { - let mut enc = TiffEncoder::new(&mut cursor)?.with_compression(compression).with_predictor(predictor); - write_image::(&mut enc, img, &tags)?; - } - Ok(cursor.into_inner()) - }; - let big = opts.tiff_bigtiff || estimated_size(img, &tags) > CLASSIC_LIMIT; - match write(big) { - Ok(v) => Ok(v), - Err(tiff::TiffError::IntSizeError) if !big => write(true).map_err(|e| CodecError::encode(F, e)), - Err(e) => Err(CodecError::encode(F, e)), - } -} - #[cfg(test)] mod bits_len { use super::Extras; diff --git a/crates/codecs/src/codecs/tiff/bands.rs b/crates/codecs/src/codecs/tiff/bands.rs new file mode 100644 index 0000000000..fe35cc98d2 --- /dev/null +++ b/crates/codecs/src/codecs/tiff/bands.rs @@ -0,0 +1,487 @@ +use super::decode::{Layout, Patched, Src, is_eof}; +use super::*; + +/// The a* and b* samples (1 and 2 of every pixel) of a Lab image between the file's encoding and +/// PhotoCraft's (8 bits: `a + 128`; 16 bits: `(a + 128) · 257`). In the file, CIELab holds them +/// signed (8 bits: `a`; 16 bits: `a · 256`) and ICCLab offset (8 bits: `a + 128`; 16 bits: +/// `(a + 128) · 256`). `to_file` picks the direction; samples are native-endian. +pub(super) fn convert_ab(data: &mut [u8], channels: usize, sample: SampleType, signed: bool, to_file: bool) { + match sample { + SampleType::U8 if signed => data.chunks_exact_mut(channels).for_each(|px| { + px[1] ^= 0x80; + px[2] ^= 0x80; + }), + SampleType::U16 => data.chunks_exact_mut(channels * 2).for_each(|px| { + for c in [1, 2] { + let v = u16::from_ne_bytes([px[2 * c], px[2 * c + 1]]); + // The file's value as `a · 256` (signed) and back. + let file_a256 = |v: u16| if signed { f64::from(v as i16) } else { f64::from(v) - 32768.0 }; + let out = if to_file { + let a256 = (f64::from(v) - 32896.0) * 256.0 / 257.0; + let a256 = a256.round().clamp(-32768.0, 32767.0); + if signed { (a256 as i16) as u16 } else { (a256 + 32768.0) as u16 } + } else { + (file_a256(v) * 257.0 / 256.0 + 32896.0).round().clamp(0.0, 65535.0) as u16 + }; + px[2 * c..2 * c + 2].copy_from_slice(&out.to_ne_bytes()); + } + }), + _ => {} + } +} + +/// File sample indices that are not a colour channel and not the one alpha sample, capped at +/// [`crate::MAX_EXTRA_SAMPLES`], and how many past the cap were left out. +pub(super) fn extra_sample_indices(spp: usize, color: usize, alpha_at: Option, has_alpha: bool) -> (Vec, usize) { + let mut used = vec![false; spp]; + for i in 0..color.min(spp) { + if let Some(slot) = used.get_mut(i) { + *slot = true; + } + } + if has_alpha { + let a = alpha_at.map(|k| color.saturating_add(k)).unwrap_or(color); + if let Some(slot) = used.get_mut(a) { + *slot = true; + } + } + let mut all: Vec = used.into_iter().enumerate().filter(|(_, on)| !*on).map(|(i, _)| i).collect(); + let over = all.len().saturating_sub(crate::MAX_EXTRA_SAMPLES); + all.truncate(crate::MAX_EXTRA_SAMPLES); + (all, over) +} + +/// Interleaved extra samples (`extra_at.len()` per pixel) → one plane per sample. Each plane is +/// allocated fallibly (the caller has checked their total against the limits). +pub(super) fn split_extra_samples( + buf: &[u8], + w: usize, + h: usize, + at: &[usize], + sample: SampleType, + mut kind_of: impl FnMut(usize) -> u16, +) -> Result, CodecError> { + let b = sample.bytes(); + let n = w.saturating_mul(h); + let spp = at.len(); + let mut out = Vec::with_capacity(spp); + for (ei, &si) in at.iter().enumerate() { + let mut data = zeroed(n.saturating_mul(b))?; + for i in 0..n { + let src = (i.saturating_mul(spp).saturating_add(ei)).saturating_mul(b); + let dst = i.saturating_mul(b); + if let (Some(s), Some(d)) = (buf.get(src..src.saturating_add(b)), data.get_mut(dst..dst.saturating_add(b))) { + d.copy_from_slice(s); + } + } + out.push(crate::ExtraSample { kind: kind_of(si), data }); + } + Ok(out) +} + +/// A zero-filled buffer, allocated fallibly. On native targets the zeroing (and the first +/// touch of every page, which dominates on a fresh multi-hundred-megabyte buffer) is spread over +/// all cores. +pub(super) fn zeroed(len: usize) -> Result, CodecError> { + let mut v = Vec::new(); + v.try_reserve_exact(len).map_err(|_| CodecError::LimitExceeded(format!("cannot allocate {len} bytes for the image")))?; + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + // The capacity is already there: this only writes the zeros. + v.par_extend(rayon::iter::repeat_n(0u8, len)); + } + #[cfg(target_arch = "wasm32")] + v.resize(len, 0); + Ok(v) +} + +/// Chunks decoded and chunks whose data ended early. +#[derive(Default, Clone, Copy)] +pub(super) struct Tally { + pub(super) decoded: usize, + pub(super) missing: usize, +} + +impl std::ops::Add for Tally { + type Output = Tally; + fn add(self, o: Tally) -> Tally { + Tally { decoded: self.decoded + o.decoded, missing: self.missing + o.missing } + } +} + +/// Decodes every band into `data`, in parallel on native targets (one decoder and scratch +/// buffer per worker). `extra` receives samples that are not part of the colour image, one +/// band of rows at a time, when it is non-empty. +#[cfg(not(target_arch = "wasm32"))] +pub(super) fn decode_bands<'a, O>( + lay: &Layout, + data: &mut [u8], + band_bytes: usize, + extra: &mut [u8], + extra_band: usize, + _first: &mut Decoder>, + open: &O, +) -> Result +where + O: Fn() -> Result>, CodecError> + Sync, +{ + use rayon::prelude::*; + if extra.is_empty() { + return data + .par_chunks_mut(band_bytes.max(1)) + .enumerate() + .map_init( + || open().map(|d| (d, Vec::new())).map_err(|e| e.to_string()), + |worker, (b, band)| { + let (dec, scratch) = worker.as_mut().map_err(|e| err(e.clone()))?; + decode_band(lay, dec, scratch, b, band, None) + }, + ) + .try_reduce(Tally::default, |a, b| Ok(a + b)); + } + data.par_chunks_mut(band_bytes.max(1)) + .zip(extra.par_chunks_mut(extra_band.max(1))) + .enumerate() + .map_init( + || open().map(|d| (d, Vec::new())).map_err(|e| e.to_string()), + |worker, (b, (band, extra_band))| { + let (dec, scratch) = worker.as_mut().map_err(|e| err(e.clone()))?; + decode_band(lay, dec, scratch, b, band, Some(extra_band)) + }, + ) + .try_reduce(Tally::default, |a, b| Ok(a + b)) +} + +/// Decodes every band into `data`, one after the other. +#[cfg(target_arch = "wasm32")] +pub(super) fn decode_bands<'a, O>( + lay: &Layout, + data: &mut [u8], + band_bytes: usize, + extra: &mut [u8], + extra_band: usize, + first: &mut Decoder>, + _open: &O, +) -> Result +where + O: Fn() -> Result>, CodecError> + Sync, +{ + let mut scratch = Vec::new(); + let mut tally = Tally::default(); + if extra.is_empty() { + for (b, band) in data.chunks_mut(band_bytes.max(1)).enumerate() { + tally = tally + decode_band(lay, first, &mut scratch, b, band, None)?; + } + return Ok(tally); + } + for (b, (band, extra_band)) in data.chunks_mut(band_bytes.max(1)).zip(extra.chunks_mut(extra_band.max(1))).enumerate() { + tally = tally + decode_band(lay, first, &mut scratch, b, band, Some(extra_band))?; + } + Ok(tally) +} + +/// Decodes band `b` (one strip, or one row of tiles, in every plane) into its output rows. +fn decode_band( + lay: &Layout, + dec: &mut Decoder>, + scratch: &mut Vec, + b: usize, + band: &mut [u8], + mut extra: Option<&mut [u8]>, +) -> Result { + let out_row = lay.out_row(); + let rows = band.len() / out_row.max(1); + let px = lay.out_channels() * lay.out.bytes(); + let mut tally = Tally::default(); + for plane in 0..lay.planes { + let file_plane = lay.source_sample(plane); + for col in 0..lay.across { + let chunk = file_plane + .checked_mul(lay.chunks_per_plane) + .and_then(|c| c.checked_add(b.checked_mul(lay.across)?)) + .and_then(|c| c.checked_add(col)) + .and_then(|c| u32::try_from(c).ok()) + .ok_or_else(|| err("chunk index out of range"))?; + let pref = dec.image_chunk_buffer_layout(chunk).map_err(map_err)?; + let stride = pref.row_stride.map(|s| s.get()).ok_or_else(|| err("empty chunk row"))?; + // In place: the strip's decoded bytes are exactly its output rows. + if lay.direct() && pref.len == band.len() && stride == out_row { + match dec.read_chunk_bytes(chunk, band) { + Ok(()) => tally.decoded += 1, + Err(e) if is_eof(&e) => tally.missing += 1, + Err(e) => return Err(map_err(e)), + } + continue; + } + if pref.len > lay.scratch_cap { + return Err(CodecError::LimitExceeded(format!("a {} byte strip or tile", pref.len))); + } + if scratch.len() < pref.len { + scratch.resize(pref.len, 0); + } + let buf = scratch.get_mut(..pref.len).ok_or_else(|| err("scratch buffer"))?; + match dec.read_chunk_bytes(chunk, buf) { + Ok(()) => tally.decoded += 1, + Err(e) if is_eof(&e) => { + tally.missing += 1; + continue; + } + Err(e) => return Err(map_err(e)), + } + let x0 = col * lay.cw; + let n = lay.cw.min(lay.w.saturating_sub(x0)); + for (ri, (src_row, dst_row)) in buf.chunks_exact(stride).zip(band.chunks_exact_mut(out_row)).take(rows).enumerate() { + let Some(dst) = dst_row.get_mut(x0 * px..(x0 + n) * px) else { continue }; + convert_row(lay, src_row, dst, n, plane); + if !lay.planar && plane == 0 && !lay.extra_at.is_empty() { + let erow = lay.extra_row(); + if let Some(extra) = extra.as_deref_mut() + && let Some(er) = extra.get_mut(ri.saturating_mul(erow)..ri.saturating_mul(erow).saturating_add(erow)) + { + deposit_extras(lay, src_row, er, n, x0); + } + } + } + } + } + if lay.planar && !lay.extra_at.is_empty() { + read_planar_extras(lay, dec, scratch, b, rows, extra, &mut tally)?; + } + finish_band(lay, band); + Ok(tally) +} + +/// Copies the non-colour samples of a chunky row into the extra-sample band. +fn deposit_extras(lay: &Layout, src: &[u8], dst: &mut [u8], n: usize, x0: usize) { + let ech = lay.extra_at.len(); + if ech == 0 { + return; + } + let px = ech * lay.out.bytes(); + let Some(dst) = dst.get_mut(x0.saturating_mul(px)..(x0.saturating_add(n)).saturating_mul(px)) else { return }; + for (ei, &si) in lay.extra_at.iter().enumerate() { + transfer(lay.src, src, lay.chunk_spp, si, dst, lay.out, ech, ei, n); + } +} + +/// Planar files store each extra sample as its own plane. Read those planes into `extra`. +fn read_planar_extras( + lay: &Layout, + dec: &mut Decoder>, + scratch: &mut Vec, + b: usize, + rows: usize, + extra: Option<&mut [u8]>, + tally: &mut Tally, +) -> Result<(), CodecError> { + let Some(extra) = extra else { return Ok(()) }; + let ech = lay.extra_at.len(); + let erow = lay.extra_row(); + if ech == 0 || erow == 0 { + return Ok(()); + } + for (ei, &file_plane) in lay.extra_at.iter().enumerate() { + for col in 0..lay.across { + let chunk = file_plane + .checked_mul(lay.chunks_per_plane) + .and_then(|c| c.checked_add(b.checked_mul(lay.across)?)) + .and_then(|c| c.checked_add(col)) + .and_then(|c| u32::try_from(c).ok()) + .ok_or_else(|| err("chunk index out of range"))?; + let pref = dec.image_chunk_buffer_layout(chunk).map_err(map_err)?; + let stride = pref.row_stride.map(|s| s.get()).ok_or_else(|| err("empty chunk row"))?; + if pref.len > lay.scratch_cap { + return Err(CodecError::LimitExceeded(format!("a {} byte strip or tile", pref.len))); + } + if scratch.len() < pref.len { + scratch.resize(pref.len, 0); + } + let buf = scratch.get_mut(..pref.len).ok_or_else(|| err("scratch buffer"))?; + match dec.read_chunk_bytes(chunk, buf) { + Ok(()) => tally.decoded += 1, + Err(e) if is_eof(&e) => { + tally.missing += 1; + continue; + } + Err(e) => return Err(map_err(e)), + } + let x0 = col * lay.cw; + let n = lay.cw.min(lay.w.saturating_sub(x0)); + for (ri, src_row) in buf.chunks_exact(stride).take(rows).enumerate() { + let start = ri.saturating_mul(erow); + let Some(er) = extra.get_mut(start..start.saturating_add(erow)) else { continue }; + let px = ech * lay.out.bytes(); + let Some(dst) = er.get_mut(x0.saturating_mul(px)..(x0.saturating_add(n)).saturating_mul(px)) else { continue }; + transfer(lay.src, src_row, 1, 0, dst, lay.out, ech, ei, n); + } + } + } + Ok(()) +} + +/// Converts `n` pixels of one decoded chunk row into output pixels (`plane` for planar data). +fn convert_row(lay: &Layout, src: &[u8], dst: &mut [u8], n: usize, plane: usize) { + let och = lay.out_channels(); + if let Some(map) = &lay.palette { + let ob = lay.out.bytes(); + for (i, d) in dst.chunks_exact_mut(och * ob).take(n).enumerate() { + let index = sample_index(lay.src, src, i); + let Some(rgb) = map.get(index) else { continue }; + for (c, v) in d.chunks_exact_mut(ob).zip(rgb) { + if ob == 1 { + c.copy_from_slice(&[(v >> 8) as u8]); + } else { + c.copy_from_slice(&v.to_ne_bytes()); + } + } + } + return; + } + if lay.copyable() { + if let Some(s) = src.get(..dst.len()) { + dst.copy_from_slice(s); + } + return; + } + if lay.planar { + transfer(lay.src, src, 1, 0, dst, lay.out, och, plane, n); + } else { + for k in 0..och { + transfer(lay.src, src, lay.chunk_spp, lay.source_sample(k), dst, lay.out, och, k, n); + } + } +} + +/// The value of pixel `i` in a row of one-sample indices (palette and sub-byte gray). +fn sample_index(src: Src, row: &[u8], i: usize) -> usize { + match src { + Src::Bits(bits) => { + let bits = usize::from(bits); + let bit = i * bits; + let byte = row.get(bit / 8).copied().unwrap_or(0); + usize::from((byte >> (8 - bits - bit % 8)) & ((1u8 << bits) - 1)) + } + Src::U8 => row.get(i).copied().map_or(0, usize::from), + Src::U16 => row.get(i * 2..i * 2 + 2).and_then(|s| s.try_into().ok()).map_or(0, |s| usize::from(u16::from_ne_bytes(s))), + _ => 0, + } +} + +/// Copies sample `si` of each of `n` decoded pixels (`sspp` samples each) to output channel +/// `di` (`dch` channels), converting the sample type. +#[allow(clippy::too_many_arguments)] +fn transfer(src: Src, row: &[u8], sspp: usize, si: usize, dst: &mut [u8], out: SampleType, dch: usize, di: usize, n: usize) { + let ob = out.bytes(); + if let Src::Bits(bits) = src { + let max = (1u32 << bits) - 1; + for (i, d) in dst.chunks_exact_mut(dch * ob).take(n).enumerate() { + if let Some(d) = d.get_mut(di) { + *d = (sample_index(src, row, i) as u32 * 255 / max) as u8; + } + } + return; + } + let sb = src.bytes(); + if src.is_identity() { + // Same sample type: a strided copy. + if sb == 1 { + for (d, s) in dst.iter_mut().skip(di).step_by(dch).zip(row.iter().skip(si).step_by(sspp)).take(n) { + *d = *s; + } + } else { + for (d, s) in dst.chunks_exact_mut(ob).skip(di).step_by(dch).zip(row.chunks_exact(sb).skip(si).step_by(sspp)).take(n) { + d.copy_from_slice(s); + } + } + return; + } + for (s, d) in row.chunks_exact(sspp * sb).zip(dst.chunks_exact_mut(dch * ob)).take(n) { + let (Some(s), Some(d)) = (s.get(si * sb..(si + 1) * sb), d.get_mut(di * ob..(di + 1) * ob)) else { continue }; + match src { + Src::U32 => { + let v = s.try_into().map_or(0, u32::from_ne_bytes); + d.copy_from_slice(&((v >> 16) as u16).to_ne_bytes()); + } + Src::U64 => { + let v = s.try_into().map_or(0, u64::from_ne_bytes); + d.copy_from_slice(&((v >> 48) as u16).to_ne_bytes()); + } + Src::F64 => { + let v = s.try_into().map_or(0.0, f64::from_ne_bytes); + d.copy_from_slice(&(v as f32).to_ne_bytes()); + } + _ => d.copy_from_slice(s), + } + } +} + +/// Applies what the stored samples leave to the reader: WhiteIsZero inversion of the gray +/// channel, and turning associated (premultiplied) alpha into straight alpha. +fn finish_band(lay: &Layout, band: &mut [u8]) { + if !lay.invert && !lay.premultiplied { + return; + } + let ch = lay.out_channels(); + let ob = lay.out.bytes(); + let color = lay.out_layout.color_channels(); + for p in band.chunks_exact_mut(ch * ob) { + match lay.out { + SampleType::U8 => { + if lay.invert + && let Some(g) = p.first_mut() + { + *g = 255 - *g; + } + if lay.premultiplied { + let a = u32::from(p.get(ch - 1).copied().unwrap_or(255)); + for c in p.iter_mut().take(color) { + *c = (u32::from(*c) * 255 + a / 2).checked_div(a).unwrap_or(0).min(255) as u8; + } + } + } + SampleType::U16 => { + let get = |p: &[u8], i: usize| p.get(i * 2..i * 2 + 2).and_then(|s| s.try_into().ok()).map_or(0, u16::from_ne_bytes); + let a = u32::from(get(p, ch - 1)); + for i in 0..color { + let mut v = u32::from(get(p, i)); + if lay.invert && i == 0 { + v = 65535 - v; + } + if lay.premultiplied { + v = (v * 65535 + a / 2).checked_div(a).unwrap_or(0).min(65535); + } + if let Some(s) = p.get_mut(i * 2..i * 2 + 2) { + s.copy_from_slice(&(v as u16).to_ne_bytes()); + } + } + } + SampleType::F16 | SampleType::F32 => { + let get = |p: &[u8], i: usize| -> f32 { + if ob == 2 { + p.get(i * 2..i * 2 + 2).and_then(|s| s.try_into().ok()).map_or(0.0, |s| f16::from_bits(u16::from_ne_bytes(s)).to_f32()) + } else { + p.get(i * 4..i * 4 + 4).and_then(|s| s.try_into().ok()).map_or(0.0, f32::from_ne_bytes) + } + }; + let a = get(p, ch - 1); + for i in 0..color { + let mut v = get(p, i); + if lay.invert && i == 0 { + v = 1.0 - v; + } + if lay.premultiplied && a > 0.0 { + v /= a; + } + if ob == 2 { + if let Some(s) = p.get_mut(i * 2..i * 2 + 2) { + s.copy_from_slice(&f16::from_f32(v).to_bits().to_ne_bytes()); + } + } else if let Some(s) = p.get_mut(i * 4..i * 4 + 4) { + s.copy_from_slice(&v.to_ne_bytes()); + } + } + } + } + } +} diff --git a/crates/codecs/src/codecs/tiff/decode.rs b/crates/codecs/src/codecs/tiff/decode.rs new file mode 100644 index 0000000000..4b5d38cb59 --- /dev/null +++ b/crates/codecs/src/codecs/tiff/decode.rs @@ -0,0 +1,544 @@ +use super::bands::{convert_ab, decode_bands, extra_sample_indices, split_extra_samples, zeroed}; +use super::tags::{F, TAG_IMAGE_SOURCE_DATA, TAG_PHOTOSHOP, TAG_XMP, TEXT_TAGS, photoshop_tags}; +use super::*; + +/// Decodes the page Photoshop would open: the first full-resolution directory. +pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result { + decode_page(bytes, None, limits) +} + +/// Decodes page `page` of [`ifd::tiff_info`]'s list (`None`: the default page). The image +/// carries the page's metadata, a [`DecodeWarning::MorePages`] when the file holds more +/// full-resolution pages, and a [`DecodeWarning::Truncated`] when image data is cut off. +pub(crate) fn decode_page(bytes: &[u8], page: Option, limits: &Limits) -> Result { + if camera_raw(bytes) { + return Err(CodecError::unsupported(F, "camera raw files (such as CR2, NEF, ARW or DNG) are not flat images; decode them with photocraft-raw")); + } + let file = File::parse(bytes).ok_or_else(|| err("not a TIFF or BigTIFF header"))?; + let info = ifd::info_of(&file)?; + let index = match page { + Some(i) => i, + None => info.default_page().ok_or_else(|| err("no image directory"))?, + }; + let p = info + .pages + .get(index) + .ok_or_else(|| CodecError::InvalidImage(format!("TIFF page {index} does not exist (the file has {} directories)", info.pages.len())))?; + let dir = file.ifd(p.ifd_offset).ok_or_else(|| err("image directory cut off"))?; + let mut img = decode_ifd(&file, &dir, limits)?; + let extra_samples = std::mem::take(&mut img.meta.extra_samples); + img.meta = metadata(&file, &dir, &mut img.icc); + img.meta.extra_samples = extra_samples; + let pages = info.page_count(); + if pages > 1 { + img.warnings.push(DecodeWarning::MorePages { total: info.complete.then_some(u32::try_from(pages).unwrap_or(u32::MAX)) }); + } + Ok(img) +} + +/// The Orientation (1–8) of page `page` (`None`: the default page); 1 when absent, malformed +/// or out of range. Classic TIFF and BigTIFF. +pub(crate) fn orientation(bytes: &[u8], page: Option) -> u16 { + let Some(file) = File::parse(bytes) else { return 1 }; + let Ok(info) = ifd::info_of(&file) else { return 1 }; + page.or_else(|| info.default_page()).and_then(|i| info.pages.get(i)).and_then(|p| file.ifd(p.ifd_offset)).map_or(1, |d| ifd::orientation_of(&file, &d)) +} + +/// The page's metadata; the ICC profile goes to `icc`. +fn metadata(f: &File<'_>, dir: &Ifd, icc: &mut Option>) -> Metadata { + *icc = f.tag_bytes(dir, Tag::IccProfile.to_u16()).filter(|b| !b.is_empty()).map(<[u8]>::to_vec); + let text = |tag: u16| { + let b = f.tag_bytes(dir, tag)?; + let s = std::str::from_utf8(b).ok()?.trim_end_matches('\0'); + (!s.is_empty()).then(|| s.to_owned()) + }; + let mut meta = Metadata { xmp: text(TAG_XMP), ..Default::default() }; + let unit = f.tag_uint(dir, Tag::ResolutionUnit.to_u16()).unwrap_or(2); + if let (Some(x), Some(y)) = (f.tag_f64(dir, Tag::XResolution.to_u16()), f.tag_f64(dir, Tag::YResolution.to_u16())) + && x > 0.0 + && y > 0.0 + && x.is_finite() + && y.is_finite() + { + meta.dpi = match unit { + 2 => Some((x as f32, y as f32)), + 3 => Some(((x * 2.54) as f32, (y * 2.54) as f32)), + _ => None, + }; + } + for (tag, key) in TEXT_TAGS { + if let Some(s) = text(tag.to_u16()) { + meta.text.push(((*key).to_owned(), s)); + } + } + // Photoshop keeps a layered TIFF's layers and resources in IFD0, where `photoshop_tags` + // reads them; any other page reads its own directory's copies. + let (resources, layers) = + if dir.at == f.first_ifd { photoshop_tags(f.b) } else { (f.tag_bytes(dir, TAG_PHOTOSHOP), f.tag_bytes(dir, TAG_IMAGE_SOURCE_DATA)) }; + meta.photoshop_resources = resources.map(<[u8]>::to_vec); + meta.photoshop_layers = layers.map(<[u8]>::to_vec); + // EXIF: the Exif and GPS directories IFD0 points to, with IFD0's descriptive tags, as an + // EXIF block (the other pages are reduced copies or layers of the same image). + if dir.at == f.first_ifd + && let Some(e) = tiff_exif::read(f.b).filter(ExifDirs::has_directories) + { + meta.exif = Some(tiff_exif::block(&e)); + } + meta +} + +// --------------------------------------------------------------------------- +// Banded pixel decoding +// --------------------------------------------------------------------------- + +/// The file seen with a few byte ranges replaced: the header's first-IFD offset (so the `tiff` +/// decoder opens the chosen directory as its IFD0) and, for WhiteIsZero and palette images, +/// the PhotometricInterpretation value (so the decoder hands over the stored samples and this +/// module applies the interpretation itself). Reads past the end return no bytes. +#[derive(Clone, Copy)] +pub(super) struct Patched<'a> { + b: &'a [u8], + patches: &'a [(u64, Vec)], + pos: u64, +} + +impl Read for Patched<'_> { + fn read(&mut self, out: &mut [u8]) -> io::Result { + let Some(src) = usize::try_from(self.pos).ok().and_then(|p| self.b.get(p..)) else { return Ok(0) }; + let n = out.len().min(src.len()); + let (Some(o), Some(s)) = (out.get_mut(..n), src.get(..n)) else { return Ok(0) }; + o.copy_from_slice(s); + let end = self.pos.saturating_add(n as u64); + for (at, bytes) in self.patches { + let lo = (*at).max(self.pos); + let hi = at.saturating_add(bytes.len() as u64).min(end); + for i in lo..hi { + let (Ok(oi), Ok(pi)) = (usize::try_from(i - self.pos), usize::try_from(i - at)) else { continue }; + if let (Some(d), Some(&v)) = (o.get_mut(oi), bytes.get(pi)) { + *d = v; + } + } + } + self.pos = end; + Ok(n) + } +} + +impl Seek for Patched<'_> { + fn seek(&mut self, to: SeekFrom) -> io::Result { + let new = match to { + SeekFrom::Start(n) => Some(n), + SeekFrom::End(d) => (self.b.len() as u64).checked_add_signed(d), + SeekFrom::Current(d) => self.pos.checked_add_signed(d), + }; + let new = new.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "seek out of range"))?; + self.pos = new; + Ok(new) + } +} + +/// How a stored sample is laid out in the `tiff` crate's chunk buffer (native endian). +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(super) enum Src { + /// 1, 2 or 4-bit unsigned, packed MSB first, rows padded to a byte. + Bits(u8), + U8, + U16, + U32, + U64, + F16, + F32, + F64, +} + +impl Src { + pub(super) fn bytes(self) -> usize { + match self { + Src::Bits(_) | Src::U8 => 1, + Src::U16 | Src::F16 => 2, + Src::U32 | Src::F32 => 4, + Src::U64 | Src::F64 => 8, + } + } + + /// The output sample type: integers above 16 bits keep their top 16, doubles become f32. + fn out(self) -> SampleType { + match self { + Src::Bits(_) | Src::U8 => SampleType::U8, + Src::U16 | Src::U32 | Src::U64 => SampleType::U16, + Src::F16 => SampleType::F16, + Src::F32 | Src::F64 => SampleType::F32, + } + } + + /// Stored bytes and output bytes are the same: a plain copy. + pub(super) fn is_identity(self) -> bool { + matches!(self, Src::U8 | Src::U16 | Src::F16 | Src::F32) + } +} + +/// Everything needed to decode and place the chunks of one directory. +pub(super) struct Layout { + pub(super) w: usize, + pub(super) src: Src, + pub(super) out: SampleType, + pub(super) out_layout: ChannelLayout, + /// Samples per pixel in a decoded chunk (1 for planar data). + pub(super) chunk_spp: usize, + pub(super) planar: bool, + /// Planes decoded for planar data: one per output channel (extra planes are skipped). + pub(super) planes: usize, + /// Tile width (a strip is `w` wide). + pub(super) cw: usize, + pub(super) across: usize, + pub(super) chunks_per_plane: usize, + /// WhiteIsZero: invert the gray channel. + pub(super) invert: bool, + /// The decoded sample (chunky) or file plane (planar) of the alpha channel (when there is one). + alpha_sample: usize, + /// Associated (premultiplied) alpha to turn straight. + pub(super) premultiplied: bool, + /// Palette images: the colour map (16-bit RGB per index). + pub(super) palette: Option>, + /// Upper bound for one chunk's scratch buffer. + pub(super) scratch_cap: usize, + /// File sample indices that are neither colour nor the chosen alpha (spot / extra alpha). + pub(super) extra_at: Vec, +} + +impl Layout { + pub(super) fn out_channels(&self) -> usize { + self.out_layout.channels() + } + /// The decoded sample (chunky) or file plane (planar) of output channel `k`. + pub(super) fn source_sample(&self, k: usize) -> usize { + if self.out_layout.has_alpha() && k + 1 == self.out_channels() { self.alpha_sample } else { k } + } + pub(super) fn out_row(&self) -> usize { + self.w * self.out_channels() * self.out.bytes() + } + pub(super) fn extra_row(&self) -> usize { + self.w.saturating_mul(self.extra_at.len()).saturating_mul(self.out.bytes()) + } + /// A chunky strip already in the output's layout: decoded in place. + pub(super) fn direct(&self) -> bool { + self.copyable() && self.across == 1 + } + /// Chunk rows are output rows: copied without conversion. + pub(super) fn copyable(&self) -> bool { + !self.planar && self.palette.is_none() && self.src.is_identity() && self.chunk_spp == self.out_channels() + } +} + +/// A chunk read that hit the end of the file (the data is missing, not malformed). +pub(super) fn is_eof(e: &tiff::TiffError) -> bool { + matches!(e, tiff::TiffError::IoError(io) if io.kind() == io::ErrorKind::UnexpectedEof) +} + +/// Decodes the pixels of one directory. +fn decode_ifd(f: &File<'_>, dir: &Ifd, limits: &Limits) -> Result { + // The values the `tiff` crate reads must exist: a count past the end of the file is + // neither allocated nor read. + if let Some(e) = dir.entries.iter().find(|e| ifd::STRUCTURAL_TAGS.contains(&e.tag) && f.data(e).is_none()) { + return Err(err(format!("tag {} points past the end of the file", e.tag))); + } + let need = |tag: u16, name: &str| f.tag_uint(dir, tag).ok_or_else(|| err(format!("missing or unreadable {name}"))); + let w = u32::try_from(need(ifd::TAG_WIDTH, "ImageWidth")?).map_err(|_| err("ImageWidth out of range"))?; + let h = u32::try_from(need(ifd::TAG_HEIGHT, "ImageLength")?).map_err(|_| err("ImageLength out of range"))?; + if w == 0 || h == 0 { + return Err(CodecError::InvalidImage(format!("zero-sized image {w}x{h}"))); + } + let spp = f.tag_uint(dir, ifd::TAG_SAMPLES).unwrap_or(1); + if spp == 0 || spp > 64 { + return Err(CodecError::unsupported(F, format!("{spp} samples per pixel"))); + } + let bits_all = f.tag_uints(dir, ifd::TAG_BITS, spp).unwrap_or_else(|| vec![1]); + let bits = bits_all.first().copied().unwrap_or(1); + if bits_all.iter().any(|&b| b != bits) { + return Err(CodecError::unsupported(F, format!("mixed bits per sample {bits_all:?}"))); + } + let format = f.tag_uint(dir, ifd::TAG_SAMPLE_FORMAT).unwrap_or(1); + let photometric_entry = dir.get(ifd::TAG_PHOTOMETRIC).copied(); + let photometric = f.tag_uint(dir, ifd::TAG_PHOTOMETRIC).ok_or_else(|| CodecError::unsupported(F, "missing PhotometricInterpretation"))?; + let planar = f.tag_uint(dir, ifd::TAG_PLANAR) == Some(2); + let extra = f.tag_uints(dir, ifd::TAG_EXTRA_SAMPLES, 64).unwrap_or_default(); + let tiled = dir.get(ifd::TAG_TILE_OFFSETS).is_some(); + let (cw, ch) = if tiled { + let tw = need(ifd::TAG_TILE_WIDTH, "TileWidth")?; + let tl = need(ifd::TAG_TILE_LENGTH, "TileLength")?; + (tw, tl) + } else { + (u64::from(w), f.tag_uint(dir, ifd::TAG_ROWS_PER_STRIP).unwrap_or(u64::from(h)).min(u64::from(h))) + }; + if cw == 0 || ch == 0 { + return Err(err("zero tile or strip size")); + } + // The chunk tables must match the geometry. Checked here, in 64 bits, before the `tiff` + // crate does the same arithmetic in narrower types. + let planes_in_file = if planar { spp } else { 1 }; + let expected = u64::from(w) + .div_ceil(cw) + .checked_mul(u64::from(h).div_ceil(ch)) + .and_then(|n| n.checked_mul(planes_in_file)) + .filter(|&n| n <= u64::from(u32::MAX)) + .ok_or_else(|| err("too many strips or tiles"))?; + let (offsets_tag, counts_tag) = if tiled { (324, 325) } else { (273, 279) }; + let counts = (dir.get(offsets_tag).map(|e| e.count), dir.get(counts_tag).map(|e| e.count)); + if counts != (Some(expected), Some(expected)) { + return Err(err(format!("{expected} strips or tiles expected, the tables list {counts:?}"))); + } + let src = match (format, bits) { + (1, 1 | 2 | 4) => Src::Bits(bits as u8), + (1, 8) => Src::U8, + (1, 16) => Src::U16, + (1, 32) => Src::U32, + (1, 64) => Src::U64, + (3, 16) => Src::F16, + (3, 32) => Src::F32, + (3, 64) => Src::F64, + (2, _) => return Err(CodecError::unsupported(F, "signed integer samples")), + _ => return Err(CodecError::unsupported(F, format!("{bits}-bit samples (sample format {format})"))), + }; + + // WhiteIsZero and palette images are handed to the `tiff` crate as BlackIsZero: it then + // returns the stored samples, and the interpretation is applied here (for every depth and + // with alpha, which the crate's own inversion does not cover). + let invert = photometric == 0; + let palette = if photometric == 3 { + if spp != 1 || !matches!(src, Src::Bits(_) | Src::U8 | Src::U16) { + return Err(CodecError::unsupported(F, format!("palette image with {spp} samples of {bits} bits"))); + } + let n = 1u64 << bits; + let map = dir.get(ifd::TAG_COLOR_MAP).filter(|e| e.ty == 3 && e.count == 3 * n).ok_or_else(|| err("palette image without a valid ColorMap"))?; + let at = |i: u64| f.uint(map, i).and_then(|v| u16::try_from(v).ok()); + let table: Option> = (0..n).map(|i| Some([at(i)?, at(n + i)?, at(2 * n + i)?])).collect(); + Some(table.ok_or_else(|| err("palette ColorMap cut off"))?) + } else { + None + }; + // CIE L*a*b*: CIELab (8; a* and b* signed) and ICCLab (9; a* and b* offset) are handed to the + // `tiff` crate as RGB, then labelled Lab with a* and b* in PhotoCraft's encoding + // (`convert_ab`). + let lab = matches!(photometric, 8 | 9); + if lab && (spp < 3 || !matches!(src, Src::U8 | Src::U16)) { + return Err(CodecError::unsupported(F, format!("Lab image with {spp} samples of {bits} bits"))); + } + // TIFF 6.0 lets any extra sample be the alpha (#1349). For RGB and CMYK the `tiff` crate + // returns the alpha only when it is the first extra sample: otherwise it is asked for every + // sample (as multiband gray) and the colour and alpha samples are picked here. An alpha + // position past the samples the file has is ignored. + let color: usize = match photometric { + 2 | 8 | 9 => 3, + 5 => 4, + _ => 1, + }; + let alpha_at = extra.iter().position(|&e| e == 1 || e == 2).filter(|&a| (color as u64).saturating_add(a as u64) < spp); + // Samples the colour model does not keep. RGB, CMYK and Lab only hand back every sample when + // asked (photometric patched to black-is-zero below); gray already comes back as multiband. + let unused = !extra.is_empty() && (spp as usize) > color.saturating_add(usize::from(alpha_at.is_some())); + let all_samples = palette.is_none() && matches!(photometric, 2 | 5 | 8 | 9) && (alpha_at.is_some_and(|a| a > 0) || (!planar && unused)); + let mut patches: Vec<(u64, Vec)> = Vec::new(); + let encode_u = |v: u64, len: usize| -> Vec { + let b = if f.le { v.to_le_bytes() } else { v.to_be_bytes() }; + if f.le { b.get(..len).map(<[u8]>::to_vec).unwrap_or_default() } else { b.get(8 - len..).map(<[u8]>::to_vec).unwrap_or_default() } + }; + if f.big { + patches.push((8, encode_u(dir.at, 8))); + } else { + let at = u32::try_from(dir.at).map_err(|_| err("directory offset out of range"))?; + patches.push((4, encode_u(u64::from(at), 4))); + } + // The directory is seen as the last of its chain: the chain was walked already, and a + // cycle through it must not fail this page. + patches.push((dir.next_at, vec![0; if f.big { 8 } else { 4 }])); + if invert || palette.is_some() || all_samples || lab { + let e = photometric_entry.ok_or_else(|| err("missing PhotometricInterpretation"))?; + let len = match e.ty { + 3 if e.count == 1 => 2, + 4 if e.count == 1 => 4, + _ => return Err(err("malformed PhotometricInterpretation")), + }; + patches.push((e.value_at, encode_u(if lab && !all_samples { 2 } else { 1 }, len))); + } + + let tl = { + let mut l = tiff::decoder::Limits::default(); + l.decoding_buffer_size = limits.alloc_usize(); + // No compressed chunk can be larger than the file. + l.intermediate_buffer_size = f.b.len().max(1); + l + }; + let open = || Decoder::new(Patched { b: f.b, patches: &patches, pos: 0 }).map(|d| d.with_limits(tl.clone())).map_err(map_err); + let mut dec = open()?; + if dec.dimensions().map_err(map_err)? != (w, h) || (dec.get_chunk_type() == ChunkType::Tile) != tiled { + return Err(err("inconsistent image directory")); + } + let ct = dec.colortype().map_err(map_err)?; + let gray_alpha = alpha_at.is_some() || (extra.is_empty() && spp == 2); + let (out_layout, chunk_spp) = match ct { + _ if palette.is_some() => (ChannelLayout::Rgb, 1), + tiff::ColorType::Gray(_) => (ChannelLayout::Gray, 1), + tiff::ColorType::Multiband { num_samples, .. } if all_samples => { + // Lab reads as RGB here and is relabelled below. + let layout = match photometric { + 2 | 8 | 9 => { + if alpha_at.is_some() { + ChannelLayout::Rgba + } else { + ChannelLayout::Rgb + } + } + 5 => { + if alpha_at.is_some() { + ChannelLayout::CmykA + } else { + ChannelLayout::Cmyk + } + } + _ => { + if gray_alpha { + ChannelLayout::GrayA + } else { + ChannelLayout::Gray + } + } + }; + (layout, usize::from(num_samples)) + } + tiff::ColorType::Multiband { num_samples, .. } if photometric <= 1 => { + (if gray_alpha { ChannelLayout::GrayA } else { ChannelLayout::Gray }, usize::from(num_samples)) + } + tiff::ColorType::RGB(_) => (ChannelLayout::Rgb, 3), + tiff::ColorType::RGBA(_) => (ChannelLayout::Rgba, 4), + tiff::ColorType::CMYK(_) => (ChannelLayout::Cmyk, 4), + tiff::ColorType::CMYKA(_) => (ChannelLayout::CmykA, 5), + other => return Err(CodecError::unsupported(F, format!("colour type {other:?}"))), + }; + let out_layout = match out_layout { + ChannelLayout::Rgb if lab => ChannelLayout::Lab, + ChannelLayout::Rgba if lab => ChannelLayout::LabA, + _ if lab => return Err(err("Lab image that does not read as three colour samples")), + l => l, + }; + let chunk_spp = if planar { 1 } else { chunk_spp }; + // The sample (chunky) or plane (planar) that holds the alpha: the colour samples come first. + let alpha_sample = out_layout.color_channels() + alpha_at.unwrap_or(0); + if out_layout.has_alpha() && (alpha_sample as u64 >= spp || (!planar && alpha_sample >= chunk_spp)) { + return Err(err("the alpha sample is past the samples of a pixel")); + } + if matches!(src, Src::Bits(_)) && (out_layout.channels() > 1 || spp != 1) && palette.is_none() { + return Err(CodecError::unsupported(F, format!("{bits}-bit samples with {spp} samples per pixel"))); + } + if (!planar && palette.is_none() && chunk_spp < out_layout.channels()) || (planar && out_layout.channels() as u64 > spp) { + return Err(err("fewer samples than the colour type needs")); + } + let out = match (&palette, src) { + (Some(_), Src::U16) => SampleType::U16, + (Some(_), _) => SampleType::U8, + _ => src.out(), + }; + limits.check(w, h, out_layout, out)?; + // Decompression-bomb guard: no compression method expands data by more than a few thousand + // times (Deflate at most ~1032:1, LZW ~2730:1, PackBits 128:1), so a file far too small for + // its declared size is refused before the image is allocated. Uncompressed data may be up + // to three quarters missing (that decodes with a `Truncated` warning). + let stored = u64::from(w).saturating_mul(u64::from(h)).saturating_mul(spp).saturating_mul(bits).div_ceil(8); + let ratio: u64 = match f.tag_uint(dir, ifd::TAG_COMPRESSION).unwrap_or(1) { + 1 => 4, + 32773 => 130, + _ => 4096, + }; + if stored > (f.b.len() as u64).saturating_mul(ratio).saturating_add(1 << 20) { + return Err(err(format!("a {} byte file cannot hold a {w}x{h} image", f.b.len()))); + } + + let (wu, hu) = (w as usize, h as usize); + let (cw, ch) = (usize::try_from(cw).map_err(|_| err("tile too wide"))?, usize::try_from(ch).map_err(|_| err("tile too tall"))?); + let across = wu.div_ceil(cw); + let down = hu.div_ceil(ch); + let chunks_per_plane = across.checked_mul(down).ok_or_else(|| err("too many tiles"))?; + let planes_in_file = if planar { spp as usize } else { 1 }; + let total = if tiled { dec.tile_count() } else { dec.strip_count() }.map_err(map_err)?; + if Some(total as usize) != chunks_per_plane.checked_mul(planes_in_file) { + return Err(err("strip or tile count does not match the image size")); + } + // One chunk's decoded bytes, clipped to the image: the scratch buffer may hold a little + // more (the `tiff` crate reads whole tiles in some planar cases) but never an amount that + // only a hostile tile size could ask for. + let chunk_bytes = cw + .min(wu) + .checked_mul(ch.min(hu)) + .and_then(|px| px.checked_mul(chunk_spp)) + .and_then(|s| s.checked_mul(src.bytes())) + .ok_or_else(|| CodecError::LimitExceeded("tile size".into()))?; + let scratch_cap = chunk_bytes.saturating_mul(2).max(64 << 20).min(limits.alloc_usize()); + let (extra_at, extras_over_limit) = extra_sample_indices(spp as usize, color, alpha_at, out_layout.has_alpha()); + let mut lay = Layout { + w: wu, + src, + out, + out_layout, + chunk_spp, + planar, + planes: if planar { out_layout.channels() } else { 1 }, + cw, + across, + chunks_per_plane, + invert: invert && palette.is_none(), + alpha_sample, + premultiplied: out_layout.has_alpha() && alpha_at.and_then(|a| extra.get(a)) == Some(&1), + palette, + scratch_cap, + extra_at, + }; + // Extra samples share the allocation budget with the image: their interleaved buffer and the + // planes split from it are held next to the image, so both count against `max_alloc`. When + // they don't fit, the image still opens (it passed its own check above) without them. + let mut extras_dropped = 0; + if !lay.extra_at.is_empty() { + let per_pixel = out_layout.channels().saturating_add(lay.extra_at.len().saturating_mul(2)).saturating_mul(out.bytes()); + if limits.check_bytes(w, h, per_pixel as u64).is_err() { + extras_dropped = u32::try_from(lay.extra_at.len()).unwrap_or(u32::MAX); + lay.extra_at.clear(); + } + } + + // The output, allocated once and fallibly. + let out_row = lay.out_row(); + let len = out_row.checked_mul(hu).ok_or_else(|| CodecError::LimitExceeded("image size".into()))?; + let mut data = zeroed(len)?; + let band_bytes = out_row.checked_mul(ch.min(hu)).ok_or_else(|| CodecError::LimitExceeded("band size".into()))?; + + let extra_row = lay.extra_row(); + let extra_len = extra_row.checked_mul(hu).ok_or_else(|| CodecError::LimitExceeded("extra samples".into()))?; + let mut extra_data = if lay.extra_at.is_empty() { Vec::new() } else { zeroed(extra_len)? }; + let extra_band = extra_row.saturating_mul(ch.min(hu)); + let tally = decode_bands(&lay, &mut data, band_bytes, extra_data.as_mut_slice(), extra_band, &mut dec, &open)?; + if tally.decoded == 0 && tally.missing > 0 { + return Err(err("the image data is missing (cut off or past the end of the file)")); + } + if lab { + convert_ab(&mut data, out_layout.channels(), out, photometric == 8, false); + } + let mut img = Image::from_raw(w, h, out_layout, out, data)?; + if !lay.extra_at.is_empty() { + // TIFF 6.0 defines ExtraSamples 0, 1 and 2 only; a reserved value reads as unspecified, + // so a save never writes it back. + let kind_of = |si: usize| match si.checked_sub(color).and_then(|k| extra.get(k)).copied() { + Some(v @ 0..=2) => v as u16, + _ => 0, + }; + img.meta.extra_samples = split_extra_samples(&extra_data, wu, hu, &lay.extra_at, out, kind_of)?; + } + if extras_over_limit > 0 { + let count = u32::try_from(extras_over_limit).unwrap_or(u32::MAX); + img.warnings.push(DecodeWarning::ExtraSamplesOverLimit { format: F, count }); + } + if extras_dropped > 0 { + img.warnings.push(DecodeWarning::ExtraSamplesDropped { format: F, count: extras_dropped }); + } + if tally.missing > 0 { + img.warnings.push(DecodeWarning::Truncated { format: F }); + } + Ok(img) +} diff --git a/crates/codecs/src/codecs/tiff/encode.rs b/crates/codecs/src/codecs/tiff/encode.rs new file mode 100644 index 0000000000..d71c32efde --- /dev/null +++ b/crates/codecs/src/codecs/tiff/encode.rs @@ -0,0 +1,496 @@ +use super::bands::convert_ab; +use super::tags::{F, TAG_IMAGE_SOURCE_DATA, TAG_PHOTOSHOP, TAG_XMP, TEXT_TAGS}; +use super::*; + +// --------------------------------------------------------------------------- +// Encoding +// --------------------------------------------------------------------------- + +/// Bytes written with TIFF type UNDEFINED (7), as required for ICC. +struct Undefined<'a>(&'a [u8]); + +impl TiffValue for Undefined<'_> { + const BYTE_LEN: u8 = 1; + const FIELD_TYPE: Type = Type::UNDEFINED; + fn count(&self) -> usize { + self.0.len() + } + fn data(&self) -> Cow<'_, [u8]> { + Cow::Borrowed(self.0) + } +} + +// Colour types with 1..=MAX_EXTRA_SAMPLES trailing extra samples (spot channels, extra alpha). +// One generic type per (sample, photometric, bit depth, total sample count) instead of a +// hand-written type for every layout. `N` is the total sample count, not the extra count. +const fn extra_photo(v: u16) -> PhotometricInterpretation { + match v { + 1 => PhotometricInterpretation::BlackIsZero, + 2 => PhotometricInterpretation::RGB, + 5 => PhotometricInterpretation::CMYK, + 8 => PhotometricInterpretation::CIELab, + _ => PhotometricInterpretation::RGB, + } +} + +trait ExtraKind: Copy + TiffValue + 'static { + const FORMAT: SampleFormat; + fn predict(row: &[Self], out: &mut Vec, samples: usize); +} + +impl ExtraKind for u8 { + const FORMAT: SampleFormat = SampleFormat::Uint; + fn predict(row: &[Self], out: &mut Vec, samples: usize) { + let n = samples.min(row.len()); + out.extend_from_slice(&row[..n]); + out.extend(row.iter().zip(&row[n..]).map(|(prev, current)| current.wrapping_sub(*prev))); + } +} + +impl ExtraKind for u16 { + const FORMAT: SampleFormat = SampleFormat::Uint; + fn predict(row: &[Self], out: &mut Vec, samples: usize) { + let n = samples.min(row.len()); + out.extend_from_slice(&row[..n]); + out.extend(row.iter().zip(&row[n..]).map(|(prev, current)| current.wrapping_sub(*prev))); + } +} + +impl ExtraKind for f32 { + const FORMAT: SampleFormat = SampleFormat::IEEEFP; + fn predict(row: &[Self], out: &mut Vec, _samples: usize) { + out.extend_from_slice(row); + } +} + +pub(super) struct Extras(pub(super) std::marker::PhantomData); + +impl TiffColorType for Extras +where + T: ExtraKind, +{ + type Inner = T; + const TIFF_VALUE: PhotometricInterpretation = extra_photo(PHOTO); + const BITS_PER_SAMPLE: &'static [u16] = &[BITS; N]; + const SAMPLE_FORMAT: &'static [SampleFormat] = &[T::FORMAT; N]; + fn horizontal_predict(row: &[Self::Inner], result: &mut Vec) { + T::predict(row, result, N); + } +} + +macro_rules! write_extras { + ($n:expr, $enc:expr, $w:expr, $h:expr, $data:expr, $tags:expr, $sample:ty, $photo:literal, $bits:literal, $base:literal) => { + match $n { + 1 => write_one::, K>($enc, $w, $h, $data, $tags), + 2 => write_one::, K>($enc, $w, $h, $data, $tags), + 3 => write_one::, K>($enc, $w, $h, $data, $tags), + 4 => write_one::, K>($enc, $w, $h, $data, $tags), + 5 => write_one::, K>($enc, $w, $h, $data, $tags), + 6 => write_one::, K>($enc, $w, $h, $data, $tags), + 7 => write_one::, K>($enc, $w, $h, $data, $tags), + 8 => write_one::, K>($enc, $w, $h, $data, $tags), + 9 => write_one::, K>($enc, $w, $h, $data, $tags), + 10 => write_one::, K>($enc, $w, $h, $data, $tags), + 11 => write_one::, K>($enc, $w, $h, $data, $tags), + 12 => write_one::, K>($enc, $w, $h, $data, $tags), + 13 => write_one::, K>($enc, $w, $h, $data, $tags), + 14 => write_one::, K>($enc, $w, $h, $data, $tags), + 15 => write_one::, K>($enc, $w, $h, $data, $tags), + 16 => write_one::, K>($enc, $w, $h, $data, $tags), + other => Err(io::Error::new(io::ErrorKind::InvalidInput, format!("unsupported extra samples ({other})")).into()), + } + }; +} + +/// An empty buffer with room for `len` elements, allocated fallibly: a save too large for memory +/// is an error, not an abort. +pub(super) fn try_with_capacity(len: usize) -> io::Result> { + let mut v = Vec::new(); + v.try_reserve_exact(len).map_err(|_| io::Error::new(io::ErrorKind::OutOfMemory, format!("cannot allocate {len} samples for the extra samples")))?; + Ok(v) +} + +fn bytes_as_u16(b: &[u8]) -> io::Result> { + let chunks = b.as_chunks::<2>().0; + let mut v = try_with_capacity(chunks.len())?; + v.extend(chunks.iter().map(|c| u16::from_ne_bytes(*c))); + Ok(v) +} + +fn bytes_as_f32(b: &[u8]) -> io::Result> { + let chunks = b.as_chunks::<4>().0; + let mut v = try_with_capacity(chunks.len())?; + v.extend(chunks.iter().map(|c| f32::from_ne_bytes(*c))); + Ok(v) +} + +/// Interleaves colour (and alpha) samples with [`Metadata::extra_samples`]. +fn interleave_extras(img: &Image) -> Result, String> { + let (w, h) = img.dimensions(); + let n = (w as usize).checked_mul(h as usize).ok_or_else(|| "image size overflows".to_string())?; + let sb = img.sample_type().bytes(); + let ch = img.layout().channels(); + let extras = &img.meta.extra_samples; + let total = ch.checked_add(extras.len()).ok_or_else(|| "too many samples".to_string())?; + let px = total.checked_mul(sb).ok_or_else(|| "sample size overflows".to_string())?; + let len = n.checked_mul(px).ok_or_else(|| "image size overflows".to_string())?; + let mut out = try_with_capacity::(len).map_err(|e| e.to_string())?; + out.resize(len, 0); + let base = img.data(); + let base_px = ch.saturating_mul(sb); + for i in 0..n { + let src = i.saturating_mul(base_px); + let dst = i.saturating_mul(px); + let Some(s) = base.get(src..src.saturating_add(base_px)) else { + return Err("image buffer is shorter than its dimensions".into()); + }; + let Some(d) = out.get_mut(dst..dst.saturating_add(base_px)) else { + return Err("extra-sample buffer is short".into()); + }; + d.copy_from_slice(s); + for (k, e) in extras.iter().enumerate() { + let es = i.saturating_mul(sb); + let ed = dst.saturating_add(base_px).saturating_add(k.saturating_mul(sb)); + let Some(s) = e.data.get(es..es.saturating_add(sb)) else { + return Err(format!("extra sample {k} is shorter than the image")); + }; + let Some(d) = out.get_mut(ed..ed.saturating_add(sb)) else { + return Err("extra-sample buffer is short".into()); + }; + d.copy_from_slice(s); + } + } + Ok(out) +} + +fn write_with_extras(enc: &mut TiffEncoder<&mut Cursor>, K>, img: &Image, tags: &TagSet<'_>) -> tiff::TiffResult<()> { + use ChannelLayout as L; + use SampleType as S; + let (w, h) = img.dimensions(); + let n = img.meta.extra_samples.len(); + if img.layout().is_lab() { + let file = lab_file(img); + let bytes = interleave_extras(&file).map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?; + return match (file.layout(), file.sample_type()) { + (L::Lab, S::U8) => write_extras!(n, enc, w, h, &bytes, tags, u8, 8, 8, 3), + (L::Lab, _) => { + let v = bytes_as_u16(&bytes)?; + write_extras!(n, enc, w, h, &v, tags, u16, 8, 16, 3) + } + (_, S::U8) => write_extras!(n, enc, w, h, &bytes, tags, u8, 8, 8, 4), + _ => { + let v = bytes_as_u16(&bytes)?; + write_extras!(n, enc, w, h, &v, tags, u16, 8, 16, 4) + } + }; + } + let bytes = interleave_extras(img).map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?; + match (img.layout(), img.sample_type()) { + (L::Gray, S::U8) => write_extras!(n, enc, w, h, &bytes, tags, u8, 1, 8, 1), + (L::Gray, S::U16) => { + let v = bytes_as_u16(&bytes)?; + write_extras!(n, enc, w, h, &v, tags, u16, 1, 16, 1) + } + (L::Gray, S::F32) => { + let v = bytes_as_f32(&bytes)?; + write_extras!(n, enc, w, h, &v, tags, f32, 1, 32, 1) + } + (L::GrayA, S::U8) => write_extras!(n, enc, w, h, &bytes, tags, u8, 1, 8, 2), + (L::GrayA, S::U16) => { + let v = bytes_as_u16(&bytes)?; + write_extras!(n, enc, w, h, &v, tags, u16, 1, 16, 2) + } + (L::GrayA, S::F32) => { + let v = bytes_as_f32(&bytes)?; + write_extras!(n, enc, w, h, &v, tags, f32, 1, 32, 2) + } + (L::Rgb, S::U8) => write_extras!(n, enc, w, h, &bytes, tags, u8, 2, 8, 3), + (L::Rgb, S::U16) => { + let v = bytes_as_u16(&bytes)?; + write_extras!(n, enc, w, h, &v, tags, u16, 2, 16, 3) + } + (L::Rgb, S::F32) => { + let v = bytes_as_f32(&bytes)?; + write_extras!(n, enc, w, h, &v, tags, f32, 2, 32, 3) + } + (L::Rgba, S::U8) => write_extras!(n, enc, w, h, &bytes, tags, u8, 2, 8, 4), + (L::Rgba, S::U16) => { + let v = bytes_as_u16(&bytes)?; + write_extras!(n, enc, w, h, &v, tags, u16, 2, 16, 4) + } + (L::Rgba, S::F32) => { + let v = bytes_as_f32(&bytes)?; + write_extras!(n, enc, w, h, &v, tags, f32, 2, 32, 4) + } + (L::Cmyk, S::U8) => write_extras!(n, enc, w, h, &bytes, tags, u8, 5, 8, 4), + (L::Cmyk, S::U16) => { + let v = bytes_as_u16(&bytes)?; + write_extras!(n, enc, w, h, &v, tags, u16, 5, 16, 4) + } + (L::Cmyk, S::F32) => { + let v = bytes_as_f32(&bytes)?; + write_extras!(n, enc, w, h, &v, tags, f32, 5, 32, 4) + } + (L::CmykA, S::U8) => write_extras!(n, enc, w, h, &bytes, tags, u8, 5, 8, 5), + (L::CmykA, S::U16) => { + let v = bytes_as_u16(&bytes)?; + write_extras!(n, enc, w, h, &v, tags, u16, 5, 16, 5) + } + (L::CmykA, S::F32) => { + let v = bytes_as_f32(&bytes)?; + write_extras!(n, enc, w, h, &v, tags, f32, 5, 32, 5) + } + _ => Err(io::Error::new(io::ErrorKind::InvalidInput, format!("unsupported extra samples ({n})")).into()), + } +} + +struct TagSet<'a> { + icc: Option<&'a [u8]>, + /// The EXIF block's directories and IFD0 tags, written as the TIFF's own. + exif: Option, + xmp: Option<&'a [u8]>, + dpi: Option<(f32, f32)>, + text: Vec<(Tag, &'a str)>, + /// ExtraSamples tag, including the unassociated-alpha marker when the image has alpha. + extra_samples: &'a [u16], + photoshop_resources: Option<&'a [u8]>, + photoshop_layers: Option<&'a [u8]>, +} + +/// Writes one image directory. (The `tiff` encoder only compresses through `write_data`, which +/// takes every sample at once.) +fn write_one(enc: &mut TiffEncoder<&mut Cursor>, K>, w: u32, h: u32, data: &[C::Inner], tags: &TagSet<'_>) -> tiff::TiffResult<()> +where + C: TiffColorType, + [C::Inner]: TiffValue, + K: TiffKind, +{ + // The Exif and GPS directories go before the image, outside its chain; IFD0 points to them. + let mut sub = |e: &ExifDirs, fields: &[tiff_exif::Field]| (!fields.is_empty()).then(|| tiff_exif::write_directory(enc, fields, e.le)).transpose(); + let exif_at = match &tags.exif { + Some(e) => sub(e, &e.exif)?, + None => None, + }; + let gps_at = match &tags.exif { + Some(e) => sub(e, &e.gps)?, + None => None, + }; + let mut im = enc.new_image::(w, h)?; + if let Some((x, y)) = tags.dpi { + im.resolution_unit(ResolutionUnit::Inch); + im.x_resolution(Rational { n: (x * 1000.0).round() as u32, d: 1000 }); + im.y_resolution(Rational { n: (y * 1000.0).round() as u32, d: 1000 }); + } + let d = im.encoder(); + if !tags.extra_samples.is_empty() { + d.write_tag(Tag::ExtraSamples, tags.extra_samples)?; + } + if let Some(icc) = tags.icc { + d.write_tag(Tag::IccProfile, Undefined(icc))?; + } + if let Some(xmp) = tags.xmp { + d.write_tag(Tag::Unknown(TAG_XMP), xmp)?; + } + for (tag, s) in &tags.text { + d.write_tag(*tag, *s)?; + } + if let Some(e) = &tags.exif { + // The EXIF block's descriptive IFD0 tags, unless the text metadata already wrote them. + let ifd0: Vec = e.ifd0.iter().filter(|f| !tags.text.iter().any(|(t, _)| t.to_u16() == f.tag)).cloned().collect(); + tiff_exif::write_fields(d, &ifd0, e.le)?; + } + if let Some(at) = exif_at { + d.write_tag(Tag::Unknown(tiff_exif::TAG_EXIF_IFD), at)?; + } + if let Some(at) = gps_at { + d.write_tag(Tag::Unknown(tiff_exif::TAG_GPS_IFD), at)?; + } + if let Some(r) = tags.photoshop_resources { + d.write_tag(Tag::Unknown(TAG_PHOTOSHOP), r)?; + } + if let Some(l) = tags.photoshop_layers { + d.write_tag(Tag::Unknown(TAG_IMAGE_SOURCE_DATA), Undefined(l))?; + } + im.write_data(data) +} + +/// A Lab image as CIELab stores it: a* and b* signed, 8 or 16 bits (CIELab has no float form: +/// 32-bit Lab is written with 16 bits). Extra samples follow the new sample type. +fn lab_file(img: &Image) -> Image { + let sample = if img.sample_type() == SampleType::U8 { SampleType::U8 } else { SampleType::U16 }; + // `convert` brings the extra samples to the new sample type with the image. + let mut file = img.convert(img.layout(), sample); + let channels = file.layout().channels(); + convert_ab(file.data_mut(), channels, sample, true, true); + file +} + +/// Writes the image with the colour type matching its layout and sample type. +fn write_image(enc: &mut TiffEncoder<&mut Cursor>, K>, img: &Image, tags: &TagSet<'_>) -> tiff::TiffResult<()> { + use ChannelLayout as L; + use SampleType as S; + if !img.meta.extra_samples.is_empty() { + return write_with_extras::(enc, img, tags); + } + let (w, h) = img.dimensions(); + let u16s = || img.to_u16_samples().unwrap_or_default(); + let f32s = || img.to_f32_samples().unwrap_or_default(); + let d8 = img.data(); + match (img.layout(), img.sample_type()) { + (L::Gray, S::U8) => write_one::(enc, w, h, d8, tags), + (L::Gray, S::U16) => write_one::(enc, w, h, &u16s(), tags), + (L::Gray, S::F32) => write_one::(enc, w, h, &f32s(), tags), + (L::GrayA, S::U8) => write_one::(enc, w, h, d8, tags), + (L::GrayA, S::U16) => write_one::(enc, w, h, &u16s(), tags), + (L::GrayA, S::F32) => write_one::(enc, w, h, &f32s(), tags), + (L::Rgb, S::U8) => write_one::(enc, w, h, d8, tags), + (L::Rgb, S::U16) => write_one::(enc, w, h, &u16s(), tags), + (L::Rgb, S::F32) => write_one::(enc, w, h, &f32s(), tags), + (L::Rgba, S::U8) => write_one::(enc, w, h, d8, tags), + (L::Rgba, S::U16) => write_one::(enc, w, h, &u16s(), tags), + (L::Rgba, S::F32) => write_one::(enc, w, h, &f32s(), tags), + (L::Cmyk, S::U8) => write_one::(enc, w, h, d8, tags), + (L::Cmyk, S::U16) => write_one::(enc, w, h, &u16s(), tags), + (L::Cmyk, S::F32) => write_one::(enc, w, h, &f32s(), tags), + (L::CmykA, S::U8) => write_one::(enc, w, h, d8, tags), + (L::CmykA, S::U16) => write_one::(enc, w, h, &u16s(), tags), + (L::CmykA, S::F32) => write_one::(enc, w, h, &f32s(), tags), + (L::Lab | L::LabA, _) => { + let file = lab_file(img); + let u16s = || file.to_u16_samples().unwrap_or_default(); + match (file.layout(), file.sample_type()) { + (L::Lab, S::U8) => write_one::(enc, w, h, file.data(), tags), + (L::Lab, _) => write_one::(enc, w, h, &u16s(), tags), + (_, S::U8) => write_one::(enc, w, h, file.data(), tags), + _ => write_one::(enc, w, h, &u16s(), tags), + } + } + (l, s) => Err(io::Error::new(io::ErrorKind::InvalidInput, format!("unsupported {l:?} {s:?}")).into()), + } +} + +/// Classic TIFF offsets are 32-bit: a file that may grow past this is written as BigTIFF. +const CLASSIC_LIMIT: u64 = u32::MAX as u64; + +/// An upper estimate of the file size: the uncompressed samples plus every tag payload plus +/// room for the directory and strip tables. +fn estimated_size(img: &Image, tags: &TagSet<'_>) -> u64 { + let payloads = [tags.icc, tags.xmp, tags.photoshop_resources, tags.photoshop_layers].iter().flatten().map(|p| p.len() as u64).sum::(); + let text = tags.text.iter().map(|(_, s)| s.len() as u64).sum::() + + tags.exif.iter().flat_map(|e| e.ifd0.iter().chain(&e.exif).chain(&e.gps)).map(|f| f.value.len() as u64 + 12).sum::(); + // Strip tables: one offset and one count per strip of about 1 MB. + let tables = (img.data().len() as u64 / (1 << 20) + 1) * 16; + let extras: u64 = img.meta.extra_samples.iter().map(|e| e.data.len() as u64).sum(); + (img.data().len() as u64).saturating_add(extras).saturating_add(payloads).saturating_add(text).saturating_add(tables).saturating_add(1 << 20) +} + +/// The byte length of one extra-sample plane: one sample per pixel of `img`, in its sample type. +/// `None` when the pixel count overflows a `usize` (no such image buffer can exist). +fn extra_plane_len(img: &Image) -> Option { + let (w, h) = img.dimensions(); + (w as usize).checked_mul(h as usize)?.checked_mul(img.sample_type().bytes()) +} + +/// Every extra plane must hold exactly one sample per pixel of `img`, in its sample type. +/// +/// The writer copies one sample per pixel out of each plane, so a plane of any other length +/// would be silently truncated (long) or read past its end (short). A sample-type conversion +/// reinterprets the bytes in the new width instead, so an unchecked plane would also change +/// meaning rather than fail. Refuse the image instead of writing either. +fn check_extra_planes(img: &Image) -> Result<(), CodecError> { + let (w, h) = img.dimensions(); + let sample = img.sample_type(); + let plane_len = extra_plane_len(img).ok_or_else(|| CodecError::encode(F, format!("the extra-sample size of a {w}x{h} image overflows")))?; + for (k, e) in img.meta.extra_samples.iter().enumerate() { + if e.data.len() != plane_len { + return Err(CodecError::encode( + F, + format!("extra sample {k} is {} bytes; a {w}x{h} {sample:?} image needs exactly {plane_len} (one sample per pixel)", e.data.len()), + )); + } + } + Ok(()) +} + +pub(crate) fn encode(src: &Image, plan: Plan, opts: &EncodeOptions) -> Result, CodecError> { + // Check the source planes before `converted`, which brings them to the plan's sample type + // with the image but deliberately leaves a wrong-sized plane alone: past that point a bad + // plane would be reinterpreted in the new width rather than rejected. + check_extra_planes(src)?; + // `converted` brings the extra samples to the plan's sample type with the image. + encode_ready(&src.converted(plan.layout, plan.sample), opts) +} + +fn encode_ready(img: &Image, opts: &EncodeOptions) -> Result, CodecError> { + let compression = match opts.tiff_compression { + TiffCompression::None => tiff::encoder::Compression::Uncompressed, + TiffCompression::Lzw => tiff::encoder::Compression::Lzw, + TiffCompression::Deflate => tiff::encoder::Compression::Deflate(tiff::encoder::DeflateLevel::Balanced), + TiffCompression::PackBits => tiff::encoder::Compression::Packbits, + }; + let predictor = if !img.sample_type().is_float() && matches!(opts.tiff_compression, TiffCompression::Lzw | TiffCompression::Deflate) { + tiff::encoder::Predictor::Horizontal + } else { + tiff::encoder::Predictor::None + }; + let text: Vec<(Tag, &str)> = if opts.embed_metadata { + img.meta + .text + .iter() + .filter_map(|(k, v)| TEXT_TAGS.iter().find(|(_, key)| key.eq_ignore_ascii_case(k)).map(|(t, _)| (*t, v.as_str()))) + .filter(|(_, v)| v.is_ascii() && !v.contains('\0')) + .collect() + } else { + Vec::new() + }; + // TIFF writes no Orientation tag (= 1): keep the XMP from contradicting it. + let xmp = if opts.embed_metadata { img.meta.xmp.as_deref().map(|x| crate::resolution::export_xmp(x, img.meta.dpi)) } else { None }; + if img.meta.extra_samples.len() > crate::MAX_EXTRA_SAMPLES { + return Err(CodecError::encode(F, format!("TIFF stores at most {} extra samples", crate::MAX_EXTRA_SAMPLES))); + } + // Validate again in the sample type the planes now hold: `Image::convert` takes a plane's + // bytes before it rebuilds them, so one it could not rebuild would arrive here empty. The Lab + // path's later re-type through `lab_file` converts a plane only when its length already + // matches the image, which this guarantees. + check_extra_planes(img)?; + let mut kinds = Vec::with_capacity(img.meta.extra_samples.len().saturating_add(1)); + if img.layout().has_alpha() { + kinds.push(2); + } + // TIFF 6.0 reserves ExtraSamples values above 2: those are written as 0 (unspecified). + for e in &img.meta.extra_samples { + kinds.push(if e.kind <= 2 { e.kind } else { 0 }); + } + let tags = TagSet { + icc: if opts.embed_icc { img.icc.as_deref() } else { None }, + exif: if opts.embed_metadata { img.meta.exif.as_deref().and_then(|e| tiff_exif::read(crate::orientation::tiff_body(e))) } else { None }, + xmp: xmp.as_deref().map(str::as_bytes), + dpi: if opts.embed_metadata { img.meta.dpi.filter(|d| d.0 > 0.0 && d.1 > 0.0) } else { None }, + text, + extra_samples: &kinds, + // Document content, not metadata: written whenever present. + photoshop_resources: img.meta.photoshop_resources.as_deref().filter(|r| !r.is_empty()), + photoshop_layers: img.meta.photoshop_layers.as_deref().filter(|l| !l.is_empty()), + }; + + // BigTIFF when asked, or when the file could pass the 4 GiB a classic TIFF can address. A + // classic write that still runs out of 32-bit offsets (compression grew the data) is redone + // as BigTIFF. + let write = |big: bool| -> tiff::TiffResult> { + let mut cursor = Cursor::new(Vec::new()); + if big { + let mut enc = TiffEncoder::new_big(&mut cursor)?.with_compression(compression).with_predictor(predictor); + write_image::(&mut enc, img, &tags)?; + } else { + let mut enc = TiffEncoder::new(&mut cursor)?.with_compression(compression).with_predictor(predictor); + write_image::(&mut enc, img, &tags)?; + } + Ok(cursor.into_inner()) + }; + let big = opts.tiff_bigtiff || estimated_size(img, &tags) > CLASSIC_LIMIT; + match write(big) { + Ok(v) => Ok(v), + Err(tiff::TiffError::IntSizeError) if !big => write(true).map_err(|e| CodecError::encode(F, e)), + Err(e) => Err(CodecError::encode(F, e)), + } +} diff --git a/crates/codecs/src/codecs/tiff/tags.rs b/crates/codecs/src/codecs/tiff/tags.rs new file mode 100644 index 0000000000..df110f777a --- /dev/null +++ b/crates/codecs/src/codecs/tiff/tags.rs @@ -0,0 +1,99 @@ +use super::*; + +pub(super) const F: Format = Format::Tiff; + +pub(super) const TAG_XMP: u16 = 700; + +/// Photoshop image resources (`8BIM` blocks). +pub(super) const TAG_PHOTOSHOP: u16 = 34377; + +/// Photoshop `ImageSourceData`: the layers of a layered TIFF. +pub(super) const TAG_IMAGE_SOURCE_DATA: u16 = 37724; + +/// `true` when [`encode`] writes little-endian (`II`) files: the `tiff` encoder writes the +/// running target's byte order, and every target PhotoCraft builds for is little-endian. +/// Byte-order-sensitive payloads (Photoshop layer data) must be produced to match. +pub fn writes_little_endian() -> bool { + cfg!(target_endian = "little") +} + +/// `(34377 image resources, 37724 image source data)` payloads, each absent when the tag is. +pub type PhotoshopTags<'a> = (Option<&'a [u8]>, Option<&'a [u8]>); + +/// The raw payloads of the Photoshop private tags in the first directory: `(34377 image +/// resources, 37724 image source data)`. Classic and BigTIFF, either byte order; only +/// header bytes and the two payloads are touched, and nothing is allocated. Anything malformed +/// reads as "absent". +pub fn photoshop_tags(b: &[u8]) -> PhotoshopTags<'_> { + fn walk(b: &[u8]) -> Option> { + let le = match b.get(0..2)? { + b"II" => true, + b"MM" => false, + _ => return None, + }; + let u16_at = |o: u64| -> Option { + let o = usize::try_from(o).ok()?; + let s = b.get(o..o.checked_add(2)?)?; + Some(if le { u16::from_le_bytes([s[0], s[1]]) } else { u16::from_be_bytes([s[0], s[1]]) }) + }; + let u32_at = |o: u64| -> Option { + let o = usize::try_from(o).ok()?; + let s: [u8; 4] = b.get(o..o.checked_add(4)?)?.try_into().ok()?; + Some(if le { u32::from_le_bytes(s) } else { u32::from_be_bytes(s) }) + }; + let u64_at = |o: u64| -> Option { + let o = usize::try_from(o).ok()?; + let s: [u8; 8] = b.get(o..o.checked_add(8)?)?.try_into().ok()?; + Some(if le { u64::from_le_bytes(s) } else { u64::from_be_bytes(s) }) + }; + let (big, ifd) = match u16_at(2)? { + 42 => (false, u64::from(u32_at(4)?)), + 43 => (true, u64_at(8)?), + _ => return None, + }; + let n = if big { u64_at(ifd)? } else { u64::from(u16_at(ifd)?) }.min(4096); + let (entry, first, inline) = if big { (20u64, ifd.checked_add(8)?, 8u64) } else { (12, ifd.checked_add(2)?, 4) }; + let mut resources = None; + let mut layers = None; + for i in 0..n { + let e = first.checked_add(i.checked_mul(entry)?)?; + let tag = u16_at(e)?; + if tag != TAG_PHOTOSHOP && tag != TAG_IMAGE_SOURCE_DATA { + continue; + } + // BYTE, ASCII, SBYTE or UNDEFINED: one byte per element. + if !matches!(u16_at(e + 2)?, 1 | 2 | 6 | 7) { + continue; + } + let count = if big { u64_at(e + 4)? } else { u64::from(u32_at(e + 4)?) }; + let value_at = e + if big { 12 } else { 8 }; + let start = if count <= inline { + value_at + } else if big { + u64_at(value_at)? + } else { + u64::from(u32_at(value_at)?) + }; + let start = usize::try_from(start).ok()?; + let data = b.get(start..start.checked_add(usize::try_from(count).ok()?)?)?; + if tag == TAG_PHOTOSHOP { + resources = Some(data); + } else { + layers = Some(data); + } + } + Some((resources, layers)) + } + walk(b).unwrap_or((None, None)) +} + +/// ASCII tags mapped to `Metadata::text` keys. +pub(super) const TEXT_TAGS: &[(Tag, &str)] = &[ + (Tag::ImageDescription, "Description"), + (Tag::Make, "Make"), + (Tag::Model, "Model"), + (Tag::Software, "Software"), + (Tag::DateTime, "DateTime"), + (Tag::Artist, "Artist"), + (Tag::Copyright, "Copyright"), +]; diff --git a/crates/codecs/src/codecs/vp8/mod.rs b/crates/codecs/src/codecs/vp8.rs similarity index 100% rename from crates/codecs/src/codecs/vp8/mod.rs rename to crates/codecs/src/codecs/vp8.rs diff --git a/crates/color/src/blend.rs b/crates/color/src/blend.rs index 508c26977e..101a84fb91 100644 --- a/crates/color/src/blend.rs +++ b/crates/color/src/blend.rs @@ -486,406 +486,4 @@ pub fn composite_atop(mode: BlendMode, backdrop: [f32; 4], source: [f32; 4], opa } #[cfg(test)] -mod tests { - use super::*; - - const E: f32 = 1e-5; - - fn close(a: f32, b: f32) -> bool { - (a - b).abs() < E - } - - #[test] - fn psd_keys_roundtrip_and_unique() { - let mut seen = std::collections::HashSet::new(); - for m in std::iter::once(BlendMode::PassThrough).chain(BlendMode::LAYER_MODES) { - assert!(seen.insert(m.psd_key()), "duplicate key {m:?}"); - assert_eq!(BlendMode::from_psd_key(m.psd_key()), Some(m)); - } - assert_eq!(BlendMode::from_psd_key(*b"zzzz"), None); - assert_eq!(seen.len(), 28); - } - - #[test] - fn paint_net_modes_keep_their_math_and_distinct_psd_status() { - assert!(close(blend_channel(BlendMode::Reflect, 0.5, 0.5), 0.5)); - assert!(close(blend_channel(BlendMode::Reflect, 0.2, 0.0), 0.04)); - assert!(close(blend_channel(BlendMode::Glow, 0.5, 0.2), 0.08)); - assert!(close(blend_channel(BlendMode::Negation, 0.2, 0.7), 0.9)); - assert_eq!(blend_channel(BlendMode::Reflect, 0.0, 1.0), 1.0); - assert_eq!(blend_channel(BlendMode::Glow, 1.0, 0.0), 1.0); - assert_eq!(blend_channel(BlendMode::PaintNetColorBurn, 1.0, 0.0), 0.0); - assert_eq!(blend_channel(BlendMode::PaintNetColorDodge, 0.0, 1.0), 1.0); - for b in 0..=255u8 { - for s in 0..=255u8 { - assert!(close(blend_channel(BlendMode::Xor, f32::from(b) / 255.0, f32::from(s) / 255.0), f32::from(b ^ s) / 255.0)); - } - } - for mode in BlendMode::PAINT_NET_MODES { - assert!(!mode.has_psd_equivalent()); - assert_eq!(mode.psd_key(), *b"norm"); - for b in [0.0, 0.1, 0.5, 1.0] { - for s in [0.0, 0.1, 0.5, 1.0] { - let v = blend_channel(mode, b, s); - assert!(v.is_finite() && (0.0..=1.0).contains(&v), "{mode:?}"); - } - } - } - assert_eq!(BlendMode::layer_modes().count(), 33); - } - - #[test] - fn normal_is_source() { - for &(cb, cs) in &[(0.2, 0.7), (1.0, 0.0), (0.0, 1.0)] { - assert!(close(blend_channel(BlendMode::Normal, cb, cs), cs)); - } - } - - #[test] - fn identities_with_white_and_black() { - // Multiply by white / screen with black / add black / darken with white leave backdrop unchanged. - for cb in [0.0f32, 0.1, 0.5, 0.9, 1.0] { - assert!(close(blend_channel(BlendMode::Multiply, cb, 1.0), cb)); - assert!(close(blend_channel(BlendMode::Screen, cb, 0.0), cb)); - assert!(close(blend_channel(BlendMode::LinearDodge, cb, 0.0), cb)); - assert!(close(blend_channel(BlendMode::Darken, cb, 1.0), cb)); - assert!(close(blend_channel(BlendMode::Lighten, cb, 0.0), cb)); - assert!(close(blend_channel(BlendMode::Difference, cb, 0.0), cb)); - assert!(close(blend_channel(BlendMode::Subtract, cb, 0.0), cb)); - assert!(close(blend_channel(BlendMode::LinearBurn, cb, 1.0), cb)); - assert!(close(blend_channel(BlendMode::Exclusion, cb, 0.0), cb)); - // 50% gray is neutral for the "light" family - assert!(close(blend_channel(BlendMode::HardLight, cb, 0.5), cb)); - assert!(close(blend_channel(BlendMode::SoftLight, cb, 0.5), cb)); - assert!(close(blend_channel(BlendMode::LinearLight, cb, 0.5), cb)); - } - } - - #[test] - fn known_values() { - assert!(close(blend_channel(BlendMode::Multiply, 0.5, 0.5), 0.25)); - assert!(close(blend_channel(BlendMode::Screen, 0.5, 0.5), 0.75)); - assert!(close(blend_channel(BlendMode::Overlay, 0.25, 0.5), 0.25)); - assert!(close(blend_channel(BlendMode::Overlay, 0.75, 1.0), 1.0)); - assert!(close(blend_channel(BlendMode::ColorDodge, 0.5, 0.5), 1.0)); - assert!(close(blend_channel(BlendMode::ColorBurn, 0.5, 0.5), 0.0)); - assert!(close(blend_channel(BlendMode::ColorBurn, 1.0, 0.0), 1.0)); - assert!(close(blend_channel(BlendMode::ColorDodge, 0.0, 1.0), 0.0)); - assert!(close(blend_channel(BlendMode::Divide, 0.25, 0.5), 0.5)); - assert!(close(blend_channel(BlendMode::Divide, 0.0, 0.0), 0.0)); - assert!(close(blend_channel(BlendMode::Divide, 0.3, 0.0), 1.0)); - assert!(close(blend_channel(BlendMode::Exclusion, 0.5, 0.5), 0.5)); - assert!(close(blend_channel(BlendMode::PinLight, 0.8, 0.2), 0.4)); - assert!(close(blend_channel(BlendMode::PinLight, 0.1, 0.9), 0.8)); - assert!(close(blend_channel(BlendMode::HardMix, 0.6, 0.4), 1.0)); - assert!(close(blend_channel(BlendMode::HardMix, 0.6, 0.3), 0.0)); - } - - /// #8804: Photoshop's Soft Light over a dark backdrop (cb ≤ 0.25, cs > 0.5) follows the W3C - /// curve `D(cb) = ((16·cb − 12)·cb + 4)·cb`, not `sqrt(cb)`. Measured on psd-tools - /// `blend-modes/rgb-blend-modes.psd` (Photoshop's merged image), in 8-bit levels: - /// (backdrop, source, Photoshop). - #[test] - fn soft_light_follows_photoshop_over_dark_backdrops() { - for (cb, cs, ps) in [(4u8, 247u8, 11.0f32), (6, 254, 19.0), (9, 252, 25.0), (10, 237, 32.0), (14, 253, 46.0)] { - let got = blend_channel(BlendMode::SoftLight, f32::from(cb) / 255.0, f32::from(cs) / 255.0) * 255.0; - assert!((got - ps).abs() <= 7.0, "cb {cb} cs {cs}: {got} vs Photoshop {ps}"); - } - } - - #[test] - fn soft_light_is_the_w3c_formula() { - let d = |cb: f32| if cb <= 0.25 { ((16.0 * cb - 12.0) * cb + 4.0) * cb } else { cb.sqrt() }; - let w3c = |cb: f32, cs: f32| if cs <= 0.5 { cb - (1.0 - 2.0 * cs) * cb * (1.0 - cb) } else { cb + (2.0 * cs - 1.0) * (d(cb) - cb) }; - for b in (0..=255u8).step_by(3) { - for s in (0..=255u8).step_by(5) { - let (cb, cs) = (f32::from(b) / 255.0, f32::from(s) / 255.0); - let got = blend_channel(BlendMode::SoftLight, cb, cs); - assert!((got - w3c(cb, cs)).abs() < 1e-5, "cb {b} cs {s}: {got} vs {}", w3c(cb, cs)); - } - } - // Continuous where the two halves of D meet (both give 0.5 at cb = 0.25). - let below = blend_channel(BlendMode::SoftLight, 0.25, 1.0); - let above = blend_channel(BlendMode::SoftLight, 0.25 + 1e-6, 1.0); - assert!(close(below, 0.5) && (above - below).abs() < 1e-4, "{below} {above}"); - // A negative backdrop (32-bit documents) counts as black under a light source, as before. - assert!(close(blend_channel(BlendMode::SoftLight, -0.1, 1.0), 0.0)); - } - - #[test] - fn vivid_light_source_extremes_and_interior_values() { - for cb in [0.0, 0.25, 0.5, 0.75, 1.0] { - assert_eq!(blend_channel(BlendMode::VividLight, cb, 0.0), 0.0); - assert_eq!(blend_channel(BlendMode::VividLight, cb, 1.0), 1.0); - } - assert!(close(blend_channel(BlendMode::VividLight, 0.75, 0.25), 0.5)); - assert!(close(blend_channel(BlendMode::VividLight, 0.25, 0.75), 0.5)); - } - - #[test] - fn hard_mix_matches_photoshop_extremes_and_interior_values() { - assert_eq!(blend_channel(BlendMode::HardMix, 1.0, 0.0), 1.0); - assert_eq!(blend_channel(BlendMode::HardMix, 0.0, 1.0), 0.0); - assert_eq!(blend_channel(BlendMode::HardMix, 1.0 - 1e-5, 0.0), 1.0); - assert_eq!(blend_channel(BlendMode::HardMix, 1e-5, 1.0), 0.0); - assert_eq!(blend_channel(BlendMode::HardMix, 0.6, 0.4), 1.0); - assert_eq!(blend_channel(BlendMode::HardMix, 0.6, 0.3), 0.0); - } - - #[test] - fn vivid_light_and_hard_mix_composite_extremes() { - assert_eq!(composite(BlendMode::VividLight, [1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 1.0], 1.0), [0.0, 0.0, 0.0, 1.0]); - assert_eq!(composite(BlendMode::VividLight, [0.0, 0.0, 0.0, 1.0], [1.0, 1.0, 1.0, 1.0], 1.0), [1.0, 1.0, 1.0, 1.0]); - assert_eq!(composite(BlendMode::HardMix, [0.0, 0.0, 0.0, 1.0], [1.0, 1.0, 1.0, 1.0], 1.0), [0.0, 0.0, 0.0, 1.0]); - assert_eq!(composite(BlendMode::HardMix, [1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 1.0], 1.0), [1.0, 1.0, 1.0, 1.0]); - } - - #[test] - fn separable_outputs_stay_in_unit_range() { - let steps: Vec = (0..=20).map(|i| i as f32 / 20.0).collect(); - for m in BlendMode::LAYER_MODES { - for &cb in &steps { - for &cs in &steps { - let v = blend_rgb(m, [cb, cs, 0.5], [cs, cb, 0.25]); - for c in v { - assert!((-E..=1.0 + E).contains(&c), "{m:?} cb={cb} cs={cs} -> {c}"); - } - } - } - } - } - - #[test] - fn add_and_divide_clip_at_integer_depths_but_not_in_float() { - // Integer depths: Photoshop clips Linear Dodge (Add) and Divide at 1. - assert_eq!(blend_channel(BlendMode::LinearDodge, 2.0, 0.5), 1.0); - assert_eq!(blend_channel(BlendMode::LinearDodge, 0.75, 0.5), 1.0); - assert_eq!(blend_channel(BlendMode::Divide, 2.0, 0.5), 1.0); - assert_eq!(blend_channel(BlendMode::Divide, 0.5, 0.25), 1.0); - // 32-bit float: light adds up past 1 (adding light never darkens). - assert!(close(blend_channel_hdr(BlendMode::LinearDodge, 2.0, 0.5), 2.5)); - assert!(close(blend_channel_hdr(BlendMode::LinearDodge, 0.75, 0.5), 1.25)); - assert!(close(blend_channel_hdr(BlendMode::Divide, 2.0, 0.5), 4.0)); - assert!(close(blend_channel_hdr(BlendMode::Divide, 0.5, 0.25), 2.0)); - assert_eq!(blend_rgb_hdr(BlendMode::LinearDodge, [2.0, 0.5, 4.0], [0.5, 0.25, 0.5]), [2.5, 0.75, 4.5]); - assert_eq!(blend_rgb_hdr(BlendMode::Divide, [2.0, 0.5, 4.0], [0.5, 0.25, 0.5]), [4.0, 2.0, 8.0]); - // Divide by zero keeps its guard; overflow stays finite. - assert_eq!(blend_channel_hdr(BlendMode::Divide, 0.0, 0.0), 0.0); - assert_eq!(blend_channel_hdr(BlendMode::Divide, 3.0, 0.0), 1.0); - assert_eq!(blend_channel_hdr(BlendMode::Divide, 3.0, -1.0), 1.0); - assert_eq!(blend_channel_hdr(BlendMode::Divide, f32::MAX, 1e-30), f32::MAX); - assert_eq!(blend_channel_hdr(BlendMode::LinearDodge, f32::MAX, f32::MAX), f32::MAX); - assert!(blend_channel_hdr(BlendMode::LinearDodge, f32::INFINITY, 1.0).is_finite()); - // Every other separable mode is unchanged (the non-separable ones keep values above 1: - // blend_rgb_within), and the in-range results agree. - for m in BlendMode::LAYER_MODES.into_iter().filter(|m| m.is_separable() && !matches!(m, BlendMode::LinearDodge | BlendMode::Divide)) { - for (cb, cs) in [(0.2, 0.3), (0.9, 0.05), (2.0, 0.5), (0.4, 1.5)] { - assert_eq!(blend_rgb(m, [cb, cs, 0.5], [cs, cb, 0.25]), blend_rgb_hdr(m, [cb, cs, 0.5], [cs, cb, 0.25]), "{m:?} cb={cb} cs={cs}"); - } - } - let (cb, cs) = ([0.2, 0.3, 0.1], [0.3, 0.4, 0.4]); - assert_eq!(blend_rgb_hdr(BlendMode::LinearDodge, cb, cs), blend_rgb(BlendMode::LinearDodge, cb, cs)); - assert_eq!(blend_rgb_hdr(BlendMode::Divide, cb, cs), blend_rgb(BlendMode::Divide, cb, cs)); - } - - #[test] - fn luminosity_and_color_swap_components() { - let cb = [0.8, 0.2, 0.2]; - let cs = [0.1, 0.1, 0.9]; - let l = blend_rgb(BlendMode::Luminosity, cb, cs); - assert!(close(lum(l), lum(cs))); - let c = blend_rgb(BlendMode::Color, cb, cs); - assert!(close(lum(c), lum(cb))); - let h = blend_rgb(BlendMode::Hue, cb, cs); - assert!(close(lum(h), lum(cb))); - let s = blend_rgb(BlendMode::Saturation, cb, [0.5, 0.5, 0.5]); - // zero-saturation source desaturates the backdrop - assert!(close(s[0], s[1]) && close(s[1], s[2])); - } - - /// ClipColor exactly as ISO 32000 / W3C write it (what `clip_color` was before it guarded - /// out-of-range luminosities). - fn spec_clip_color(c: [f32; 3]) -> [f32; 3] { - let l = lum(c); - let n = c[0].min(c[1]).min(c[2]); - let x = c[0].max(c[1]).max(c[2]); - let mut out = c; - if n < 0.0 { - let d = l - n; - for v in &mut out { - *v = if d.abs() < 1e-12 { l } else { l + (*v - l) * l / d }; - } - } - if x > 1.0 { - let d = x - l; - for v in &mut out { - *v = if d.abs() < 1e-12 { l } else { l + (*v - l) * (1.0 - l) / d }; - } - } - out - } - - fn spec_blend_rgb(mode: BlendMode, cb: [f32; 3], cs: [f32; 3]) -> [f32; 3] { - let set_lum = |c: [f32; 3], l: f32| { - let d = l - lum(c); - spec_clip_color([c[0] + d, c[1] + d, c[2] + d]) - }; - match mode { - BlendMode::Hue => set_lum(set_sat(cs, sat(cb)), lum(cb)), - BlendMode::Saturation => set_lum(set_sat(cb, sat(cs)), lum(cb)), - BlendMode::Color => set_lum(cs, lum(cb)), - BlendMode::Luminosity => set_lum(cb, lum(cs)), - m => blend_rgb(m, cb, cs), - } - } - - const NON_SEPARABLE: [BlendMode; 4] = [BlendMode::Hue, BlendMode::Saturation, BlendMode::Color, BlendMode::Luminosity]; - - #[test] - fn non_separable_modes_unchanged_on_integer_inputs() { - // 8/16-bit documents only hold 0..1, where the luminosity stays in range (up to a - // rounding step at white) and ClipColor is the plain ISO 32000 formula. - let mut edges: Vec = vec![0.0, 1.0 / 255.0, 0.5, 254.0 / 255.0, 65534.0 / 65535.0, 1.0]; - edges.extend((0..=8).map(|i| i as f32 / 8.0)); - let mut colors = Vec::new(); - for &r in &edges { - for &g in &edges { - for &b in &edges { - colors.push([r, g, b]); - } - } - } - let mut seed = 0x1234_5678u32; - let mut next = |levels: u32| { - seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); - ((seed >> 8) % (levels + 1)) as f32 / levels as f32 - }; - for _ in 0..2000 { - let levels = if next(1) > 0.5 { 255 } else { 65535 }; - colors.push([next(levels), next(levels), next(levels)]); - } - let mut worst = 0.0f32; - for (i, &cb) in colors.iter().enumerate() { - for &cs in colors.iter().skip(i % 7).step_by(7) { - for m in NON_SEPARABLE { - let (got, want) = (blend_rgb(m, cb, cs), spec_blend_rgb(m, cb, cs)); - for k in 0..3 { - worst = worst.max((got[k] - want[k]).abs()); - } - } - } - } - // Only white-ish colours whose luminosity rounds a step above 1 can differ, by a rounding step. - assert!(worst <= 1e-6, "{worst}"); - } - - #[test] - fn non_separable_modes_stable_when_luminosity_is_out_of_range() { - // The spec formula divided by `max − lum`, which is rounding noise for a grey above 1 and - // turns colours inside out when the luminosity is above 1: Luminosity of a grey of 2 over - // (0.5, 0.25, 0.125) gave (1.0, 2.32, 2.99). - let spec = spec_blend_rgb(BlendMode::Luminosity, [0.5, 0.25, 0.125], [2.0; 3]); - assert!(spec[0] < spec[2], "{spec:?}"); - let colors: [[f32; 3]; 10] = [ - [1.0, 1.0, 1.0], - [1.5, 1.5, 1.5], - [2.0, 2.0, 2.0], - [4.0, 4.0, 4.0], - [1000.0, 1000.0, 1000.0], - [2.0, 2.0, 1.999_999], - [4.0, 3.999_9, 4.0], - [3.0, 0.25, 0.125], - [1.25, 0.875, 3.75], - [-0.25, 0.5, 1.375], - ]; - for top in [1.0, f32::MAX] { - for m in NON_SEPARABLE { - for cb in colors { - for cs in colors { - let r = blend_rgb_within(m, cb, cs, top); - assert!(r.iter().all(|v| v.is_finite()), "{m:?} {cb:?} {cs:?} {top}: {r:?}"); - // The target luminosity is kept, at any depth. - let want = if m == BlendMode::Luminosity { lum(cs) } else { lum(cb) }; - if want >= 0.0 { - assert!((lum(r) - want).abs() <= 1e-4 * want.max(1.0), "{m:?} {cb:?} {cs:?} {top}: {r:?}"); - } - let (lo, hi) = (r[0].min(r[1]).min(r[2]), r[0].max(r[1]).max(r[2])); - if top == 1.0 { - // In gamut, or (a luminosity above 1 has no in-gamut colour) its grey. - assert!((lo >= 0.0 && hi <= 1.0 + E) || hi - lo <= 1e-6 * hi, "{m:?} {cb:?} {cs:?}: {r:?}"); - } else { - assert!(lo >= -1e-6 * hi.max(1.0), "{m:?} {cb:?} {cs:?}: {r:?}"); - } - } - } - } - } - // 32-bit: a grey backdrop gives a grey of its own luminosity in Hue and Saturation, a - // grey source a grey in Color, and bright colours keep their values above 1. - for g in [1.5f32, 2.0, 4.0, 1000.0] { - let grey = [g; 3]; - for cs in colors { - for m in [BlendMode::Hue, BlendMode::Saturation] { - let r = blend_rgb_within(m, grey, cs, f32::MAX); - assert!(r.iter().all(|&v| (v - lum(grey)).abs() <= 1e-5 * g), "{m:?} {g} {cs:?}: {r:?}"); - } - } - let r = blend_rgb_within(BlendMode::Luminosity, [0.5, 0.25, 0.125], grey, f32::MAX); - assert!(r[0] > 1.0 && r[0] > r[1] && r[1] > r[2], "{g}: {r:?}"); - let r = blend_rgb_within(BlendMode::Color, grey, [3.0, 0.25, 0.125], f32::MAX); - assert!(r[0] > 1.0 && r[0] > r[1] && r[1] > r[2], "{g}: {r:?}"); - // Integer documents: no colour of that luminosity fits in 0..1, so it is its grey. - let r = blend_rgb_within(BlendMode::Luminosity, [0.5, 0.25, 0.125], grey, 1.0); - assert!(r.iter().all(|&v| (v - lum(grey)).abs() <= 1e-5 * g), "{g}: {r:?}"); - } - // Continuous across near-greys: the result barely moves from the grey's. - for m in NON_SEPARABLE { - let a = blend_rgb_within(m, [2.0, 2.0, 2.0], [4.0, 4.0, 4.0], f32::MAX); - let b = blend_rgb_within(m, [2.0, 2.0, 1.999_999], [4.0, 3.999_999, 4.0], f32::MAX); - assert!(a.iter().zip(b).all(|(x, y)| (x - y).abs() <= 1e-4), "{m:?}: {a:?} {b:?}"); - } - } - - #[test] - fn darker_lighter_color_pick_whole_pixel() { - let a = [0.9, 0.1, 0.1]; - let b = [0.2, 0.6, 0.2]; - assert_eq!(blend_rgb(BlendMode::DarkerColor, a, b), if lum(b) < lum(a) { b } else { a }); - assert_eq!(blend_rgb(BlendMode::LighterColor, a, b), if lum(b) > lum(a) { b } else { a }); - } - - #[test] - fn composite_alpha_rules() { - let bg = [0.2, 0.4, 0.6, 1.0]; - // Transparent source leaves backdrop. - assert_eq!(composite(BlendMode::Multiply, bg, [1.0, 0.0, 0.0, 0.0], 1.0), bg); - // Opaque normal source replaces. - let r = composite(BlendMode::Normal, bg, [1.0, 0.0, 0.0, 1.0], 1.0); - assert!(close(r[0], 1.0) && close(r[3], 1.0)); - // Half opacity normal = lerp. - let r = composite(BlendMode::Normal, bg, [1.0, 1.0, 1.0, 1.0], 0.5); - assert!(close(r[0], 0.6) && close(r[1], 0.7) && close(r[2], 0.8)); - // Blend over transparent backdrop yields source regardless of mode. - let r = composite(BlendMode::Multiply, [0.0; 4], [0.3, 0.5, 0.7, 1.0], 1.0); - assert!(close(r[0], 0.3) && close(r[1], 0.5) && close(r[2], 0.7) && close(r[3], 1.0)); - // Alpha accumulates. - let r = composite(BlendMode::Screen, [0.0, 0.0, 0.0, 0.5], [0.0, 0.0, 0.0, 0.5], 1.0); - assert!(close(r[3], 0.75)); - } - - #[test] - fn composite_atop_keeps_alpha_and_moves_colour_by_source_alpha() { - let bg = [1.0, 1.0, 1.0, 0.5]; - // Half-transparent white, black at 50%: halfway, alpha kept (#5783). - let r = composite_atop(BlendMode::Normal, bg, [0.0, 0.0, 0.0, 1.0], 0.5); - assert!(close(r[0], 0.5) && close(r[2], 0.5) && r[3] == 0.5, "{r:?}"); - // Non-Normal modes blend against the backdrop as it is: Multiply by black at 50% halves it. - let r = composite_atop(BlendMode::Multiply, bg, [0.0, 0.0, 0.0, 1.0], 0.5); - assert!(close(r[0], 0.5) && r[3] == 0.5, "{r:?}"); - // Opaque backdrops agree with source-over. - let opaque = [0.2, 0.4, 0.6, 1.0]; - assert_eq!(composite_atop(BlendMode::Screen, opaque, [0.5, 0.5, 0.5, 0.7], 0.8), composite(BlendMode::Screen, opaque, [0.5, 0.5, 0.5, 0.7], 0.8)); - // A transparent source leaves the backdrop. - assert_eq!(composite_atop(BlendMode::Normal, bg, [0.0, 0.0, 0.0, 0.0], 1.0), bg); - } -} +mod tests; diff --git a/crates/color/src/blend/tests.rs b/crates/color/src/blend/tests.rs new file mode 100644 index 0000000000..156580e206 --- /dev/null +++ b/crates/color/src/blend/tests.rs @@ -0,0 +1,401 @@ +use super::*; + +const E: f32 = 1e-5; + +fn close(a: f32, b: f32) -> bool { + (a - b).abs() < E +} + +#[test] +fn psd_keys_roundtrip_and_unique() { + let mut seen = std::collections::HashSet::new(); + for m in std::iter::once(BlendMode::PassThrough).chain(BlendMode::LAYER_MODES) { + assert!(seen.insert(m.psd_key()), "duplicate key {m:?}"); + assert_eq!(BlendMode::from_psd_key(m.psd_key()), Some(m)); + } + assert_eq!(BlendMode::from_psd_key(*b"zzzz"), None); + assert_eq!(seen.len(), 28); +} + +#[test] +fn paint_net_modes_keep_their_math_and_distinct_psd_status() { + assert!(close(blend_channel(BlendMode::Reflect, 0.5, 0.5), 0.5)); + assert!(close(blend_channel(BlendMode::Reflect, 0.2, 0.0), 0.04)); + assert!(close(blend_channel(BlendMode::Glow, 0.5, 0.2), 0.08)); + assert!(close(blend_channel(BlendMode::Negation, 0.2, 0.7), 0.9)); + assert_eq!(blend_channel(BlendMode::Reflect, 0.0, 1.0), 1.0); + assert_eq!(blend_channel(BlendMode::Glow, 1.0, 0.0), 1.0); + assert_eq!(blend_channel(BlendMode::PaintNetColorBurn, 1.0, 0.0), 0.0); + assert_eq!(blend_channel(BlendMode::PaintNetColorDodge, 0.0, 1.0), 1.0); + for b in 0..=255u8 { + for s in 0..=255u8 { + assert!(close(blend_channel(BlendMode::Xor, f32::from(b) / 255.0, f32::from(s) / 255.0), f32::from(b ^ s) / 255.0)); + } + } + for mode in BlendMode::PAINT_NET_MODES { + assert!(!mode.has_psd_equivalent()); + assert_eq!(mode.psd_key(), *b"norm"); + for b in [0.0, 0.1, 0.5, 1.0] { + for s in [0.0, 0.1, 0.5, 1.0] { + let v = blend_channel(mode, b, s); + assert!(v.is_finite() && (0.0..=1.0).contains(&v), "{mode:?}"); + } + } + } + assert_eq!(BlendMode::layer_modes().count(), 33); +} + +#[test] +fn normal_is_source() { + for &(cb, cs) in &[(0.2, 0.7), (1.0, 0.0), (0.0, 1.0)] { + assert!(close(blend_channel(BlendMode::Normal, cb, cs), cs)); + } +} + +#[test] +fn identities_with_white_and_black() { + // Multiply by white / screen with black / add black / darken with white leave backdrop unchanged. + for cb in [0.0f32, 0.1, 0.5, 0.9, 1.0] { + assert!(close(blend_channel(BlendMode::Multiply, cb, 1.0), cb)); + assert!(close(blend_channel(BlendMode::Screen, cb, 0.0), cb)); + assert!(close(blend_channel(BlendMode::LinearDodge, cb, 0.0), cb)); + assert!(close(blend_channel(BlendMode::Darken, cb, 1.0), cb)); + assert!(close(blend_channel(BlendMode::Lighten, cb, 0.0), cb)); + assert!(close(blend_channel(BlendMode::Difference, cb, 0.0), cb)); + assert!(close(blend_channel(BlendMode::Subtract, cb, 0.0), cb)); + assert!(close(blend_channel(BlendMode::LinearBurn, cb, 1.0), cb)); + assert!(close(blend_channel(BlendMode::Exclusion, cb, 0.0), cb)); + // 50% gray is neutral for the "light" family + assert!(close(blend_channel(BlendMode::HardLight, cb, 0.5), cb)); + assert!(close(blend_channel(BlendMode::SoftLight, cb, 0.5), cb)); + assert!(close(blend_channel(BlendMode::LinearLight, cb, 0.5), cb)); + } +} + +#[test] +fn known_values() { + assert!(close(blend_channel(BlendMode::Multiply, 0.5, 0.5), 0.25)); + assert!(close(blend_channel(BlendMode::Screen, 0.5, 0.5), 0.75)); + assert!(close(blend_channel(BlendMode::Overlay, 0.25, 0.5), 0.25)); + assert!(close(blend_channel(BlendMode::Overlay, 0.75, 1.0), 1.0)); + assert!(close(blend_channel(BlendMode::ColorDodge, 0.5, 0.5), 1.0)); + assert!(close(blend_channel(BlendMode::ColorBurn, 0.5, 0.5), 0.0)); + assert!(close(blend_channel(BlendMode::ColorBurn, 1.0, 0.0), 1.0)); + assert!(close(blend_channel(BlendMode::ColorDodge, 0.0, 1.0), 0.0)); + assert!(close(blend_channel(BlendMode::Divide, 0.25, 0.5), 0.5)); + assert!(close(blend_channel(BlendMode::Divide, 0.0, 0.0), 0.0)); + assert!(close(blend_channel(BlendMode::Divide, 0.3, 0.0), 1.0)); + assert!(close(blend_channel(BlendMode::Exclusion, 0.5, 0.5), 0.5)); + assert!(close(blend_channel(BlendMode::PinLight, 0.8, 0.2), 0.4)); + assert!(close(blend_channel(BlendMode::PinLight, 0.1, 0.9), 0.8)); + assert!(close(blend_channel(BlendMode::HardMix, 0.6, 0.4), 1.0)); + assert!(close(blend_channel(BlendMode::HardMix, 0.6, 0.3), 0.0)); +} + +/// #8804: Photoshop's Soft Light over a dark backdrop (cb ≤ 0.25, cs > 0.5) follows the W3C +/// curve `D(cb) = ((16·cb − 12)·cb + 4)·cb`, not `sqrt(cb)`. Measured on psd-tools +/// `blend-modes/rgb-blend-modes.psd` (Photoshop's merged image), in 8-bit levels: +/// (backdrop, source, Photoshop). +#[test] +fn soft_light_follows_photoshop_over_dark_backdrops() { + for (cb, cs, ps) in [(4u8, 247u8, 11.0f32), (6, 254, 19.0), (9, 252, 25.0), (10, 237, 32.0), (14, 253, 46.0)] { + let got = blend_channel(BlendMode::SoftLight, f32::from(cb) / 255.0, f32::from(cs) / 255.0) * 255.0; + assert!((got - ps).abs() <= 7.0, "cb {cb} cs {cs}: {got} vs Photoshop {ps}"); + } +} + +#[test] +fn soft_light_is_the_w3c_formula() { + let d = |cb: f32| if cb <= 0.25 { ((16.0 * cb - 12.0) * cb + 4.0) * cb } else { cb.sqrt() }; + let w3c = |cb: f32, cs: f32| if cs <= 0.5 { cb - (1.0 - 2.0 * cs) * cb * (1.0 - cb) } else { cb + (2.0 * cs - 1.0) * (d(cb) - cb) }; + for b in (0..=255u8).step_by(3) { + for s in (0..=255u8).step_by(5) { + let (cb, cs) = (f32::from(b) / 255.0, f32::from(s) / 255.0); + let got = blend_channel(BlendMode::SoftLight, cb, cs); + assert!((got - w3c(cb, cs)).abs() < 1e-5, "cb {b} cs {s}: {got} vs {}", w3c(cb, cs)); + } + } + // Continuous where the two halves of D meet (both give 0.5 at cb = 0.25). + let below = blend_channel(BlendMode::SoftLight, 0.25, 1.0); + let above = blend_channel(BlendMode::SoftLight, 0.25 + 1e-6, 1.0); + assert!(close(below, 0.5) && (above - below).abs() < 1e-4, "{below} {above}"); + // A negative backdrop (32-bit documents) counts as black under a light source, as before. + assert!(close(blend_channel(BlendMode::SoftLight, -0.1, 1.0), 0.0)); +} + +#[test] +fn vivid_light_source_extremes_and_interior_values() { + for cb in [0.0, 0.25, 0.5, 0.75, 1.0] { + assert_eq!(blend_channel(BlendMode::VividLight, cb, 0.0), 0.0); + assert_eq!(blend_channel(BlendMode::VividLight, cb, 1.0), 1.0); + } + assert!(close(blend_channel(BlendMode::VividLight, 0.75, 0.25), 0.5)); + assert!(close(blend_channel(BlendMode::VividLight, 0.25, 0.75), 0.5)); +} + +#[test] +fn hard_mix_matches_photoshop_extremes_and_interior_values() { + assert_eq!(blend_channel(BlendMode::HardMix, 1.0, 0.0), 1.0); + assert_eq!(blend_channel(BlendMode::HardMix, 0.0, 1.0), 0.0); + assert_eq!(blend_channel(BlendMode::HardMix, 1.0 - 1e-5, 0.0), 1.0); + assert_eq!(blend_channel(BlendMode::HardMix, 1e-5, 1.0), 0.0); + assert_eq!(blend_channel(BlendMode::HardMix, 0.6, 0.4), 1.0); + assert_eq!(blend_channel(BlendMode::HardMix, 0.6, 0.3), 0.0); +} + +#[test] +fn vivid_light_and_hard_mix_composite_extremes() { + assert_eq!(composite(BlendMode::VividLight, [1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 1.0], 1.0), [0.0, 0.0, 0.0, 1.0]); + assert_eq!(composite(BlendMode::VividLight, [0.0, 0.0, 0.0, 1.0], [1.0, 1.0, 1.0, 1.0], 1.0), [1.0, 1.0, 1.0, 1.0]); + assert_eq!(composite(BlendMode::HardMix, [0.0, 0.0, 0.0, 1.0], [1.0, 1.0, 1.0, 1.0], 1.0), [0.0, 0.0, 0.0, 1.0]); + assert_eq!(composite(BlendMode::HardMix, [1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 1.0], 1.0), [1.0, 1.0, 1.0, 1.0]); +} + +#[test] +fn separable_outputs_stay_in_unit_range() { + let steps: Vec = (0..=20).map(|i| i as f32 / 20.0).collect(); + for m in BlendMode::LAYER_MODES { + for &cb in &steps { + for &cs in &steps { + let v = blend_rgb(m, [cb, cs, 0.5], [cs, cb, 0.25]); + for c in v { + assert!((-E..=1.0 + E).contains(&c), "{m:?} cb={cb} cs={cs} -> {c}"); + } + } + } + } +} + +#[test] +fn add_and_divide_clip_at_integer_depths_but_not_in_float() { + // Integer depths: Photoshop clips Linear Dodge (Add) and Divide at 1. + assert_eq!(blend_channel(BlendMode::LinearDodge, 2.0, 0.5), 1.0); + assert_eq!(blend_channel(BlendMode::LinearDodge, 0.75, 0.5), 1.0); + assert_eq!(blend_channel(BlendMode::Divide, 2.0, 0.5), 1.0); + assert_eq!(blend_channel(BlendMode::Divide, 0.5, 0.25), 1.0); + // 32-bit float: light adds up past 1 (adding light never darkens). + assert!(close(blend_channel_hdr(BlendMode::LinearDodge, 2.0, 0.5), 2.5)); + assert!(close(blend_channel_hdr(BlendMode::LinearDodge, 0.75, 0.5), 1.25)); + assert!(close(blend_channel_hdr(BlendMode::Divide, 2.0, 0.5), 4.0)); + assert!(close(blend_channel_hdr(BlendMode::Divide, 0.5, 0.25), 2.0)); + assert_eq!(blend_rgb_hdr(BlendMode::LinearDodge, [2.0, 0.5, 4.0], [0.5, 0.25, 0.5]), [2.5, 0.75, 4.5]); + assert_eq!(blend_rgb_hdr(BlendMode::Divide, [2.0, 0.5, 4.0], [0.5, 0.25, 0.5]), [4.0, 2.0, 8.0]); + // Divide by zero keeps its guard; overflow stays finite. + assert_eq!(blend_channel_hdr(BlendMode::Divide, 0.0, 0.0), 0.0); + assert_eq!(blend_channel_hdr(BlendMode::Divide, 3.0, 0.0), 1.0); + assert_eq!(blend_channel_hdr(BlendMode::Divide, 3.0, -1.0), 1.0); + assert_eq!(blend_channel_hdr(BlendMode::Divide, f32::MAX, 1e-30), f32::MAX); + assert_eq!(blend_channel_hdr(BlendMode::LinearDodge, f32::MAX, f32::MAX), f32::MAX); + assert!(blend_channel_hdr(BlendMode::LinearDodge, f32::INFINITY, 1.0).is_finite()); + // Every other separable mode is unchanged (the non-separable ones keep values above 1: + // blend_rgb_within), and the in-range results agree. + for m in BlendMode::LAYER_MODES.into_iter().filter(|m| m.is_separable() && !matches!(m, BlendMode::LinearDodge | BlendMode::Divide)) { + for (cb, cs) in [(0.2, 0.3), (0.9, 0.05), (2.0, 0.5), (0.4, 1.5)] { + assert_eq!(blend_rgb(m, [cb, cs, 0.5], [cs, cb, 0.25]), blend_rgb_hdr(m, [cb, cs, 0.5], [cs, cb, 0.25]), "{m:?} cb={cb} cs={cs}"); + } + } + let (cb, cs) = ([0.2, 0.3, 0.1], [0.3, 0.4, 0.4]); + assert_eq!(blend_rgb_hdr(BlendMode::LinearDodge, cb, cs), blend_rgb(BlendMode::LinearDodge, cb, cs)); + assert_eq!(blend_rgb_hdr(BlendMode::Divide, cb, cs), blend_rgb(BlendMode::Divide, cb, cs)); +} + +#[test] +fn luminosity_and_color_swap_components() { + let cb = [0.8, 0.2, 0.2]; + let cs = [0.1, 0.1, 0.9]; + let l = blend_rgb(BlendMode::Luminosity, cb, cs); + assert!(close(lum(l), lum(cs))); + let c = blend_rgb(BlendMode::Color, cb, cs); + assert!(close(lum(c), lum(cb))); + let h = blend_rgb(BlendMode::Hue, cb, cs); + assert!(close(lum(h), lum(cb))); + let s = blend_rgb(BlendMode::Saturation, cb, [0.5, 0.5, 0.5]); + // zero-saturation source desaturates the backdrop + assert!(close(s[0], s[1]) && close(s[1], s[2])); +} + +/// ClipColor exactly as ISO 32000 / W3C write it (what `clip_color` was before it guarded +/// out-of-range luminosities). +fn spec_clip_color(c: [f32; 3]) -> [f32; 3] { + let l = lum(c); + let n = c[0].min(c[1]).min(c[2]); + let x = c[0].max(c[1]).max(c[2]); + let mut out = c; + if n < 0.0 { + let d = l - n; + for v in &mut out { + *v = if d.abs() < 1e-12 { l } else { l + (*v - l) * l / d }; + } + } + if x > 1.0 { + let d = x - l; + for v in &mut out { + *v = if d.abs() < 1e-12 { l } else { l + (*v - l) * (1.0 - l) / d }; + } + } + out +} + +fn spec_blend_rgb(mode: BlendMode, cb: [f32; 3], cs: [f32; 3]) -> [f32; 3] { + let set_lum = |c: [f32; 3], l: f32| { + let d = l - lum(c); + spec_clip_color([c[0] + d, c[1] + d, c[2] + d]) + }; + match mode { + BlendMode::Hue => set_lum(set_sat(cs, sat(cb)), lum(cb)), + BlendMode::Saturation => set_lum(set_sat(cb, sat(cs)), lum(cb)), + BlendMode::Color => set_lum(cs, lum(cb)), + BlendMode::Luminosity => set_lum(cb, lum(cs)), + m => blend_rgb(m, cb, cs), + } +} + +const NON_SEPARABLE: [BlendMode; 4] = [BlendMode::Hue, BlendMode::Saturation, BlendMode::Color, BlendMode::Luminosity]; + +#[test] +fn non_separable_modes_unchanged_on_integer_inputs() { + // 8/16-bit documents only hold 0..1, where the luminosity stays in range (up to a + // rounding step at white) and ClipColor is the plain ISO 32000 formula. + let mut edges: Vec = vec![0.0, 1.0 / 255.0, 0.5, 254.0 / 255.0, 65534.0 / 65535.0, 1.0]; + edges.extend((0..=8).map(|i| i as f32 / 8.0)); + let mut colors = Vec::new(); + for &r in &edges { + for &g in &edges { + for &b in &edges { + colors.push([r, g, b]); + } + } + } + let mut seed = 0x1234_5678u32; + let mut next = |levels: u32| { + seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + ((seed >> 8) % (levels + 1)) as f32 / levels as f32 + }; + for _ in 0..2000 { + let levels = if next(1) > 0.5 { 255 } else { 65535 }; + colors.push([next(levels), next(levels), next(levels)]); + } + let mut worst = 0.0f32; + for (i, &cb) in colors.iter().enumerate() { + for &cs in colors.iter().skip(i % 7).step_by(7) { + for m in NON_SEPARABLE { + let (got, want) = (blend_rgb(m, cb, cs), spec_blend_rgb(m, cb, cs)); + for k in 0..3 { + worst = worst.max((got[k] - want[k]).abs()); + } + } + } + } + // Only white-ish colours whose luminosity rounds a step above 1 can differ, by a rounding step. + assert!(worst <= 1e-6, "{worst}"); +} + +#[test] +fn non_separable_modes_stable_when_luminosity_is_out_of_range() { + // The spec formula divided by `max − lum`, which is rounding noise for a grey above 1 and + // turns colours inside out when the luminosity is above 1: Luminosity of a grey of 2 over + // (0.5, 0.25, 0.125) gave (1.0, 2.32, 2.99). + let spec = spec_blend_rgb(BlendMode::Luminosity, [0.5, 0.25, 0.125], [2.0; 3]); + assert!(spec[0] < spec[2], "{spec:?}"); + let colors: [[f32; 3]; 10] = [ + [1.0, 1.0, 1.0], + [1.5, 1.5, 1.5], + [2.0, 2.0, 2.0], + [4.0, 4.0, 4.0], + [1000.0, 1000.0, 1000.0], + [2.0, 2.0, 1.999_999], + [4.0, 3.999_9, 4.0], + [3.0, 0.25, 0.125], + [1.25, 0.875, 3.75], + [-0.25, 0.5, 1.375], + ]; + for top in [1.0, f32::MAX] { + for m in NON_SEPARABLE { + for cb in colors { + for cs in colors { + let r = blend_rgb_within(m, cb, cs, top); + assert!(r.iter().all(|v| v.is_finite()), "{m:?} {cb:?} {cs:?} {top}: {r:?}"); + // The target luminosity is kept, at any depth. + let want = if m == BlendMode::Luminosity { lum(cs) } else { lum(cb) }; + if want >= 0.0 { + assert!((lum(r) - want).abs() <= 1e-4 * want.max(1.0), "{m:?} {cb:?} {cs:?} {top}: {r:?}"); + } + let (lo, hi) = (r[0].min(r[1]).min(r[2]), r[0].max(r[1]).max(r[2])); + if top == 1.0 { + // In gamut, or (a luminosity above 1 has no in-gamut colour) its grey. + assert!((lo >= 0.0 && hi <= 1.0 + E) || hi - lo <= 1e-6 * hi, "{m:?} {cb:?} {cs:?}: {r:?}"); + } else { + assert!(lo >= -1e-6 * hi.max(1.0), "{m:?} {cb:?} {cs:?}: {r:?}"); + } + } + } + } + } + // 32-bit: a grey backdrop gives a grey of its own luminosity in Hue and Saturation, a + // grey source a grey in Color, and bright colours keep their values above 1. + for g in [1.5f32, 2.0, 4.0, 1000.0] { + let grey = [g; 3]; + for cs in colors { + for m in [BlendMode::Hue, BlendMode::Saturation] { + let r = blend_rgb_within(m, grey, cs, f32::MAX); + assert!(r.iter().all(|&v| (v - lum(grey)).abs() <= 1e-5 * g), "{m:?} {g} {cs:?}: {r:?}"); + } + } + let r = blend_rgb_within(BlendMode::Luminosity, [0.5, 0.25, 0.125], grey, f32::MAX); + assert!(r[0] > 1.0 && r[0] > r[1] && r[1] > r[2], "{g}: {r:?}"); + let r = blend_rgb_within(BlendMode::Color, grey, [3.0, 0.25, 0.125], f32::MAX); + assert!(r[0] > 1.0 && r[0] > r[1] && r[1] > r[2], "{g}: {r:?}"); + // Integer documents: no colour of that luminosity fits in 0..1, so it is its grey. + let r = blend_rgb_within(BlendMode::Luminosity, [0.5, 0.25, 0.125], grey, 1.0); + assert!(r.iter().all(|&v| (v - lum(grey)).abs() <= 1e-5 * g), "{g}: {r:?}"); + } + // Continuous across near-greys: the result barely moves from the grey's. + for m in NON_SEPARABLE { + let a = blend_rgb_within(m, [2.0, 2.0, 2.0], [4.0, 4.0, 4.0], f32::MAX); + let b = blend_rgb_within(m, [2.0, 2.0, 1.999_999], [4.0, 3.999_999, 4.0], f32::MAX); + assert!(a.iter().zip(b).all(|(x, y)| (x - y).abs() <= 1e-4), "{m:?}: {a:?} {b:?}"); + } +} + +#[test] +fn darker_lighter_color_pick_whole_pixel() { + let a = [0.9, 0.1, 0.1]; + let b = [0.2, 0.6, 0.2]; + assert_eq!(blend_rgb(BlendMode::DarkerColor, a, b), if lum(b) < lum(a) { b } else { a }); + assert_eq!(blend_rgb(BlendMode::LighterColor, a, b), if lum(b) > lum(a) { b } else { a }); +} + +#[test] +fn composite_alpha_rules() { + let bg = [0.2, 0.4, 0.6, 1.0]; + // Transparent source leaves backdrop. + assert_eq!(composite(BlendMode::Multiply, bg, [1.0, 0.0, 0.0, 0.0], 1.0), bg); + // Opaque normal source replaces. + let r = composite(BlendMode::Normal, bg, [1.0, 0.0, 0.0, 1.0], 1.0); + assert!(close(r[0], 1.0) && close(r[3], 1.0)); + // Half opacity normal = lerp. + let r = composite(BlendMode::Normal, bg, [1.0, 1.0, 1.0, 1.0], 0.5); + assert!(close(r[0], 0.6) && close(r[1], 0.7) && close(r[2], 0.8)); + // Blend over transparent backdrop yields source regardless of mode. + let r = composite(BlendMode::Multiply, [0.0; 4], [0.3, 0.5, 0.7, 1.0], 1.0); + assert!(close(r[0], 0.3) && close(r[1], 0.5) && close(r[2], 0.7) && close(r[3], 1.0)); + // Alpha accumulates. + let r = composite(BlendMode::Screen, [0.0, 0.0, 0.0, 0.5], [0.0, 0.0, 0.0, 0.5], 1.0); + assert!(close(r[3], 0.75)); +} + +#[test] +fn composite_atop_keeps_alpha_and_moves_colour_by_source_alpha() { + let bg = [1.0, 1.0, 1.0, 0.5]; + // Half-transparent white, black at 50%: halfway, alpha kept (#5783). + let r = composite_atop(BlendMode::Normal, bg, [0.0, 0.0, 0.0, 1.0], 0.5); + assert!(close(r[0], 0.5) && close(r[2], 0.5) && r[3] == 0.5, "{r:?}"); + // Non-Normal modes blend against the backdrop as it is: Multiply by black at 50% halves it. + let r = composite_atop(BlendMode::Multiply, bg, [0.0, 0.0, 0.0, 1.0], 0.5); + assert!(close(r[0], 0.5) && r[3] == 0.5, "{r:?}"); + // Opaque backdrops agree with source-over. + let opaque = [0.2, 0.4, 0.6, 1.0]; + assert_eq!(composite_atop(BlendMode::Screen, opaque, [0.5, 0.5, 0.5, 0.7], 0.8), composite(BlendMode::Screen, opaque, [0.5, 0.5, 0.5, 0.7], 0.8)); + // A transparent source leaves the backdrop. + assert_eq!(composite_atop(BlendMode::Normal, bg, [0.0, 0.0, 0.0, 0.0], 1.0), bg); +} diff --git a/crates/compose/src/adjust.rs b/crates/compose/src/adjust.rs index cd907e9cfa..c25867c938 100644 --- a/crates/compose/src/adjust.rs +++ b/crates/compose/src/adjust.rs @@ -10,6 +10,32 @@ use photocraft_doc::adjust::{CurvePoint, HueRange, LevelsChannel, ToneSpace, lut use crate::Buffer; +mod channels; +mod color; +mod tone; + +#[cfg(test)] +use channels::lab_denorm; +pub use channels::{ + LAB_NEUTRAL, LabOp, apply_cmy, cmy_adjustment, cmyk_channel_adjustment, ink_brightness_contrast_lut, ink_luma, ink_through, lab_channel_adjustment, + lab_stored_op, stored_channel_adjustment, stored_channels, threshold_white, +}; +use channels::{apply_lab, legacy_brightness_contrast, legacy_brightness_contrast_hdr}; +use color::gradient; +pub use color::{ + BalanceCurve, VIBRANCE_BOOST, VIBRANCE_GREY, bayer4, black_white_gray, color_balance_channel, colorize_saturation, hdr_saturation_factor, hsl_to_rgb, + hue_range_tables, hue_saturation, hue_saturation_in, lut3d_sample, photo_filter_matrix, range_lightness, rgb_to_hsl, selective_color, + selective_color_weights, vibrance_lin, vibrance_px, +}; +#[cfg(test)] +use tone::LUT_SIZE; +pub(crate) use tone::apply_tone; +pub use tone::{ + TONE_SLOPE_SPAN, contour_curve_lut, curve_lut, curve_lut_mode, curve_map_lut, float_tone_extrapolates, float_tone_identity, levels, levels_float, + levels_gamma, levels_q, modern_brightness, modern_contrast, modern_lut, posterize, posterize_in, tone_luts, tone_luts_depth, tone_luts_q, +}; +use tone::{lut, map_rgb}; + /// The document tone curve used to linearize values for adjustments that /// work in linear light (Exposure). Until ICC profiles are wired in (M8) this /// approximates the Photoshop defaults: sRGB for colour documents and the @@ -265,57 +291,6 @@ fn apply_depth_mode(adj: &Adjustment, buf: &mut Buffer, transfer: Transfer, dept } } -/// Legacy Brightness/Contrast on a 32-bit document's samples: unclipped, with contrast pivoting at -/// 127 of 255 (photoshop corpus rgb32 and gray32 brightness-contrast-legacy.psd: every pixel -/// exact, negative and over-white values included; the 8/16-bit pivot, 128, is 0.43 of a level -/// off there). -fn legacy_brightness_contrast_hdr(brightness: f32, contrast: f32) -> impl Fn(f32) -> f32 { - const PIVOT: f32 = 127.0 / 255.0; - let b = brightness / 255.0; - let c = contrast.clamp(-100.0, 99.0); - let k = if c >= 0.0 { 1.0 / (1.0 - c / 100.0) } else { 1.0 + c / 100.0 }; - let (pre, post) = if c >= 0.0 { (b, 0.0) } else { (0.0, b) }; - move |v: f32| (v + pre - PIVOT) * k + PIVOT + post -} - -/// Legacy Brightness/Contrast as one channel's tone curve (see [`apply_depth`]). -fn legacy_brightness_contrast(brightness: f32, contrast: f32) -> impl Fn(f32) -> f32 { - legacy_brightness_contrast_at(brightness, contrast, LEGACY_PIVOT) -} - -/// [`legacy_brightness_contrast`] with contrast pivoting at `pivot`. -fn legacy_brightness_contrast_at(brightness: f32, contrast: f32, pivot: f32) -> impl Fn(f32) -> f32 { - let b = brightness / 255.0; - let c = contrast.clamp(-100.0, 99.0); - let k = if c >= 0.0 { 1.0 / (1.0 - c / 100.0) } else { 1.0 + c / 100.0 }; - let (pre, post) = if c >= 0.0 { (b, 0.0) } else { (0.0, b) }; - move |v: f32| ((v + pre - pivot) * k + pivot + post).clamp(0.0, 1.0) -} - -/// Whether Threshold at `level` turns colour `c` white in a document of `depth` (`None`: unknown, -/// treated as 8-bit). Photoshop splits on the luminosity 0.30 R + 0.59 G + 0.11 B (the blend -/// modes' `lum`), not the Rec. 601 grey, of the document's whole sample values: -/// - 8 bits: white when that luminosity, rounded to a level with halves down, reaches the level; -/// - 16 bits: white when it reaches the level converted to 16 bits (128 → 16448); -/// - 32 bits: white when it reaches the level. -/// -/// Exact on every pixel of psd-tools threshold_rgb.psd, threshold_16bits_rgb.psd and -/// threshold_16bits_grayscale.psd and of the photoshop corpus's rgb16 threshold-128.psd, where the -/// Rec. 601 grey split 28 and 100 pixels of the first two the other way. The sums of -/// `30 R + 59 G + 11 B` over whole samples are exact in f32 (at most 3 276 800). -pub fn threshold_white(c: [f32; 3], level: f32, depth: Option) -> bool { - let t = (level * 255.0).round(); - let sum = |q: f32| { - let [r, g, b] = c.map(|v| (v.clamp(0.0, 1.0) * q).round()); - 30.0 * r + 59.0 * g + 11.0 * b - }; - match depth { - None | Some(SampleType::U8) => sum(255.0) > 100.0 * t - 50.0, - Some(SampleType::U16) => sum(32768.0) >= 100.0 * (t * 32768.0 / 255.0).round(), - Some(SampleType::F32) => (0.3 * c[0] + 0.59 * c[1] + 0.11 * c[2]) * 255.0 >= t, - } -} - /// Applies an adjustment in a document of colour `mode`: [`apply_depth`], except that in Lab /// and CMYK documents the adjustments Photoshop evaluates on the document's own channels do so /// (see [`lab_channel_adjustment`] and [`cmyk_channel_adjustment`]). @@ -348,1197 +323,6 @@ pub fn apply_in(adj: &Adjustment, buf: &mut Buffer, transfer: Transfer, depth: O } } -/// Whether a Lab document evaluates `adj` on its L, a and b channels rather than on the screen -/// colour: Invert and Posterize (L, a and b alike), Brightness/Contrast (L only), Threshold -/// (split on L, neutral result) and Gradient Map (driven by L). Levels and Curves carry their own -/// Lab records ([`ToneSpace::Lab`]); everything else stays on the screen colour. -pub fn lab_channel_adjustment(adj: &Adjustment) -> bool { - matches!( - adj, - Adjustment::Invert - | Adjustment::Posterize { .. } - | Adjustment::Threshold { .. } - | Adjustment::BrightnessContrast { .. } - | Adjustment::GradientMap { .. } - ) -} - -/// Whether a CMYK document evaluates `adj` on its inks rather than on the screen colour: Invert -/// and Posterize (each ink, black included, so paper inverts to 400% ink), Threshold (paper or -/// 100% black ink alone) and Brightness/Contrast (each ink's stored value, 1 - ink, through the -/// tone curve; see [`ink_through`]). Photoshop corpus cmyk8 and cmyk16 invert, posterize-4, -/// threshold-128 and brightness-contrast(-legacy) follow these rules on the files' own inks on -/// every pixel; here the inks are the screen colour separated through the document's CMYK -/// profile, so neutrals carry the black that profile generates rather than the file's. -pub fn cmyk_channel_adjustment(adj: &Adjustment) -> bool { - stored_channel_adjustment(adj) || cmy_adjustment(adj) || matches!(adj, Adjustment::BrightnessContrast { .. }) -} - -/// Whether a CMYK document evaluates `adj` on C, M and Y as the complement of an RGB colour, -/// black kept ([`apply_cmy`]): Hue/Saturation (not Colorize, which Photoshop separates again, -/// black and all) and Color Balance (photoshop corpus cmyk16 hue-saturation.psd follows this on -/// every pixel within half a level, cmyk8 within two; color-balance within our RGB Color -/// Balance's own error). -pub fn cmy_adjustment(adj: &Adjustment) -> bool { - matches!(adj, Adjustment::HueSaturation { colorize: false, .. } | Adjustment::ColorBalance { .. }) -} - -/// A [`cmy_adjustment`] on straight inks (C, M, Y, K; 0 none): the RGB adjustment on -/// `(1 - c, 1 - m, 1 - y)`, black left alone. -pub fn apply_cmy(adj: &Adjustment, inks: &mut [[f32; 4]]) { - let width = i32::try_from(inks.len()).unwrap_or(i32::MAX); - let mut buf = Buffer { rect: crate::Rect::new(0, 0, width, 1), px: inks.iter().map(|i| [1.0 - i[0], 1.0 - i[1], 1.0 - i[2], 1.0]).collect() }; - apply_depth(adj, &mut buf, Transfer::Srgb, None); - for (ink, p) in inks.iter_mut().zip(&buf.px) { - for c in 0..3 { - ink[c] = (1.0 - p[c]).clamp(0.0, 1.0); - } - } -} - -/// Brightness/Contrast as the lookup table (4096 samples over 0..1) a CMYK ink's stored value, -/// `1 - ink`, goes through ([`ink_through`]): [`modern_lut`], or the legacy linear curve with its -/// contrast pivoting at 128 in ink, which is 127 of 255 stored (photoshop corpus cmyk16 -/// brightness-contrast-legacy.psd sits 0.43 of a level off around 128 stored, as a one-level -/// pivot shift times contrast +30's slope predicts). -pub fn ink_brightness_contrast_lut(brightness: f32, contrast: f32, legacy: bool) -> Vec { - if !legacy { - return modern_lut(brightness, contrast); - } - let curve = legacy_brightness_contrast_at(brightness, contrast, 1.0 - LEGACY_PIVOT); - (0..LUT_SIZE).map(|k| curve(k as f32 / (LUT_SIZE - 1) as f32)).collect() -} - -/// One CMYK ink (0: none) through a channel tone curve the way Photoshop applies one in CMYK: to -/// the stored value, `1 - ink`, so raising brightness takes ink away. -pub fn ink_through(table: &[f32], ink: f32) -> f32 { - 1.0 - lut(table, 1.0 - ink) -} - -/// Whether [`stored_channels`] evaluates `adj`: Invert, Posterize and Threshold. -pub fn stored_channel_adjustment(adj: &Adjustment) -> bool { - matches!(adj, Adjustment::Invert | Adjustment::Posterize { .. } | Adjustment::Threshold { .. }) -} - -/// Invert, Posterize or Threshold on one pixel's own channels in a Lab or CMYK document of -/// `depth` (`None`: unknown, treated as 8-bit): `ch` holds L, a, b normalised as [`lab_norm`] -/// gives them, or the C, M, Y, K inks (0: none). Lab Invert turns 8-bit bytes `v` into `255 - v` -/// (a becomes -1 - a) and mirrors a and b around neutral at 16 bits (photoshop corpus lab16 -/// invert.psd: neutral stays neutral). CMYK Threshold compares [`ink_luma`]. -pub fn stored_channels(adj: &Adjustment, mode: ColorMode, depth: Option, ch: &mut [f32]) { - let lab = mode == ColorMode::Lab; - match adj { - Adjustment::Invert => { - let mirror = if lab && depth.is_some_and(|d| d != SampleType::U8) { 256.0 / 255.0 } else { 1.0 }; - for (i, v) in ch.iter_mut().enumerate() { - *v = if i > 0 { mirror } else { 1.0 } - v.clamp(0.0, 1.0); - } - } - // CMYK posterizes the stored values (1 - ink), which its uneven levels make differ from - // posterizing the ink: psd-tools posterize_cmyk.psd (3 to 21 levels) is exact so. - Adjustment::Posterize { levels } if mode == ColorMode::Cmyk => ch.iter_mut().for_each(|v| *v = 1.0 - posterize_in(1.0 - *v, *levels, depth)), - Adjustment::Posterize { levels } => ch.iter_mut().for_each(|v| *v = posterize_in(*v, *levels, depth)), - Adjustment::Threshold { level } => { - // On the 8-bit grid, like the RGB threshold. - let t = (level * 255.0).round(); - let out = if lab { - let white = ch.first().is_some_and(|l| (l.clamp(0.0, 1.0) * 255.0).round() >= t); - [if white { 1.0 } else { 0.0 }, 128.0 / 255.0, 128.0 / 255.0, 0.0] - } else { - let ink = |i: usize| ch.get(i).copied().unwrap_or(0.0); - let black = (ink_luma([ink(0), ink(1), ink(2), ink(3)]) * 255.0).round() < t; - [0.0, 0.0, 0.0, if black { 1.0 } else { 0.0 }] - }; - ch.iter_mut().zip(out).for_each(|(v, o)| *v = o); - } - _ => {} - } -} - -/// The luma Photoshop's CMYK Threshold compares: Rec. 601 weights on the inks' plain complement, -/// `(1 - c)(1 - k)` and so on, whatever the document's profile (photoshop corpus cmyk8 and cmyk16 -/// threshold-128.psd: every pixel on the right side of level 128). -pub fn ink_luma(ink: [f32; 4]) -> f32 { - let paper = 1.0 - ink[3].clamp(0.0, 1.0); - rgb_to_gray([0, 1, 2].map(|i| (1.0 - ink[i].clamp(0.0, 1.0)) * paper)) -} - -/// Encoded sRGB → Lab normalised the way Photoshop's channels hold it: L/100, (a+128)/255, -/// (b+128)/255. -fn lab_norm(c: [f32; 3]) -> [f32; 3] { - let l = srgb_to_lab(c); - [l[0] / 100.0, (l[1] + 128.0) / 255.0, (l[2] + 128.0) / 255.0] -} - -/// The inverse of [`lab_norm`]. -fn lab_denorm(n: [f32; 3]) -> [f32; 3] { - lab_to_srgb([n[0] * 100.0, n[1] * 255.0 - 128.0, n[2] * 255.0 - 128.0]) -} - -/// Neutral a or b as Lab surfaces store it ((0 + 128) / 255). -pub const LAB_NEUTRAL: f32 = 128.0 / 255.0; - -/// An adjustment Photoshop evaluates on a Lab document's own channels, as an operation on one -/// pixel's stored L, a, b (normalised as Lab surfaces store them: L / 100, (a + 128) / 255, -/// (b + 128) / 255) in a document of `depth`: Invert and Posterize (each channel), Threshold -/// (split on L, neutral result), Brightness/Contrast (L) and Levels or Curves with Lab records. -/// `None` for any other adjustment. On the stored values colours outside the display gamut keep -/// theirs, where [`apply_in`] can only round-trip them through clipped display RGB. -pub fn lab_stored_op(adj: &Adjustment, depth: Option) -> Option> { - let op: LabOp<'_> = match adj { - Adjustment::Invert | Adjustment::Posterize { .. } => Box::new(move |ch: &mut [f32; 3]| stored_channels(adj, ColorMode::Lab, depth, ch)), - Adjustment::Threshold { level } => { - // Split on L on the 8-bit grid, like the display path (`apply_lab`). - let t = (level * 255.0).round(); - Box::new(move |ch: &mut [f32; 3]| { - let white = (ch[0].clamp(0.0, 1.0) * 255.0).round() >= t; - *ch = [if white { 1.0 } else { 0.0 }, LAB_NEUTRAL, LAB_NEUTRAL]; - }) - } - Adjustment::BrightnessContrast { brightness, contrast, legacy } => { - let (b, c, legacy) = (*brightness, *contrast, *legacy); - let legacy_curve = legacy_brightness_contrast(b, c); - Box::new(move |ch: &mut [f32; 3]| { - ch[0] = if legacy { legacy_curve(ch[0]) } else { modern_contrast(modern_brightness(ch[0], b), c).clamp(0.0, 1.0) }; - }) - } - Adjustment::Levels { space: ToneSpace::Lab, .. } | Adjustment::Curves { space: ToneSpace::Lab, .. } => { - let luts = tone_luts_depth(adj, depth); - Box::new(move |ch: &mut [f32; 3]| { - for (v, t) in ch.iter_mut().zip(&luts) { - *v = lut(t, *v); - } - }) - } - _ => return None, - }; - Some(op) -} - -/// One pixel's stored L, a, b through an adjustment ([`lab_stored_op`]). -pub type LabOp<'a> = Box; - -/// The Lab evaluation of a [`lab_channel_adjustment`] in a document of `depth` (no-op for any -/// other adjustment). -fn apply_lab(adj: &Adjustment, buf: &mut Buffer, depth: Option) { - match adj { - // L → 100 - L and a, b mirrored about neutral; each channel posterized (see `stored_channels`). - Adjustment::Invert | Adjustment::Posterize { .. } => map_rgb(buf, |c| { - let mut n = lab_norm(c); - stored_channels(adj, ColorMode::Lab, depth, &mut n); - lab_denorm(n) - }), - Adjustment::Threshold { level } => { - // Split on L alone (on the 8-bit grid); the result is neutral black or white. - let t = (level * 255.0).round(); - map_rgb(buf, |c| [if (lab_norm(c)[0].clamp(0.0, 1.0) * 255.0).round() >= t { 1.0 } else { 0.0 }; 3]) - } - Adjustment::BrightnessContrast { brightness, contrast, legacy } => { - let legacy_curve = legacy_brightness_contrast(*brightness, *contrast); - let modern = (!*legacy).then(|| modern_lut(*brightness, *contrast)); - let curve = |v: f32| match &modern { - Some(table) => lut(table, v), - None => legacy_curve(v), - }; - // The tone curve on L only. Added as the difference of two round trips (like - // `tone_in_space`) so a and b, and colours a round trip moves, stay put. - map_rgb(buf, |c| { - let n = lab_norm(c); - let l = curve(n[0]); - if l == n[0] { - return c; - } - let (before, after) = (lab_denorm(n), lab_denorm([l, n[1], n[2]])); - std::array::from_fn(|i| (c[i] + after[i] - before[i]).clamp(0.0, 1.0)) - }) - } - Adjustment::GradientMap { stops, reverse, dither } => { - let (w, x0, y0) = (buf.rect.width().max(1) as usize, buf.rect.x0, buf.rect.y0); - for (i, p) in buf.px.iter_mut().enumerate() { - if p[3] <= 0.0 { - continue; - } - // Driven by L: equal lightness maps to the same stop colour whatever the chroma. - let l = lab_norm([p[0], p[1], p[2]])[0].clamp(0.0, 1.0); - let mut o = gradient(stops, if *reverse { 1.0 - l } else { l }); - if *dither { - let d = bayer4(x0 + (i % w) as i32, y0 + (i / w) as i32) / 255.0; - o = o.map(|v| (v + d).clamp(0.0, 1.0)); - } - p[..3].copy_from_slice(&o); - } - } - _ => {} - } -} - -/// Float RGB curve channels with no edit must preserve samples outside the LUT domain; edited -/// ones extend past it (see [`float_tone_extrapolates`]). -pub fn float_tone_identity(adj: &Adjustment, depth: Option) -> [bool; 3] { - match adj { - Adjustment::Curves { master, per_channel, space: ToneSpace::Rgb, .. } if depth == Some(SampleType::F32) => { - std::array::from_fn(|i| photocraft_doc::adjust::is_identity_curve(master) && photocraft_doc::adjust::is_identity_curve(&per_channel[i])) - } - _ => [false; 3], - } -} - -/// Whether an edited Curves adjustment continues past 0..1 instead of clipping: in a 32-bit RGB -/// document Photoshop extends each curve beyond its end points along the slope of its end -/// segments (#7157: `[[0,0],[255,128]]` maps -0.5 to -0.250980407 and 2 to 1.003921628). Only -/// in RGB documents: the curve's space is not the document's, and other modes keep the table. -pub fn float_tone_extrapolates(adj: &Adjustment, depth: Option, mode: ColorMode) -> bool { - matches!(adj, Adjustment::Curves { space: ToneSpace::Rgb, .. }) && depth == Some(SampleType::F32) && mode == ColorMode::Rgb -} - -pub(crate) fn apply_tone(buf: &mut Buffer, space: ToneSpace, luts: &[Vec; 4], identity: [bool; 3], extrapolate: bool) { - let sample = if extrapolate { lut_extended } else { lut }; - match space { - ToneSpace::Rgb => map_rgb(buf, |c| std::array::from_fn(|i| if identity[i] { c[i] } else { sample(&luts[i], c[i]) })), - ToneSpace::Cmyk | ToneSpace::Lab => map_rgb(buf, |c| tone_in_space(space, luts, c)), - } -} - -/// Per-channel LUTs of a Levels or Curves adjustment: each channel's record first, then the -/// master (composite) record, as Photoshop does (psd-tools levels_rgb.psd and curves_rgb.psd, -/// #975). Four rows: the three `per_channel` channels then black -/// (identity unless the space is CMYK). In Lab there is no composite record, so the master is ignored. -pub fn tone_luts(adj: &Adjustment) -> [Vec; 4] { - tone_luts_q(adj, None) -} - -/// [`tone_luts`] for samples with `quantum` steps per unit (Levels works on whole levels; see -/// [`levels_q`]). -pub fn tone_luts_q(adj: &Adjustment, quantum: Option) -> [Vec; 4] { - let x = |k: usize| k as f32 / (LUT_SIZE - 1) as f32; - match adj { - Adjustment::Levels { master, per_channel, space, black } => { - let ident = LevelsChannel::default(); - let m = if *space == ToneSpace::Lab { &ident } else { master }; - let row = |c: &LevelsChannel| (0..LUT_SIZE).map(|k| levels_q(m, levels_q(c, x(k), quantum), quantum)).collect(); - [row(&per_channel[0]), row(&per_channel[1]), row(&per_channel[2]), row(if *space == ToneSpace::Cmyk { black } else { &ident })] - } - Adjustment::Curves { master, per_channel, space, black, pencil } => { - let m = if *space == ToneSpace::Lab { curve_lut(&[]) } else { curve_lut_mode(master, *pencil) }; - let row = |c: &[CurvePoint]| curve_lut_mode(c, *pencil).iter().map(|&v| lut(&m, v)).collect(); - [row(&per_channel[0]), row(&per_channel[1]), row(&per_channel[2]), row(if *space == ToneSpace::Cmyk { black } else { &[] })] - } - _ => std::array::from_fn(|_| (0..LUT_SIZE).map(x).collect()), - } -} - -/// [`tone_luts_q`] in a document of `depth` (`None`: unrounded). 32-bit Levels use -/// [`levels_float`], sampled on 0..1 and kept in 0..1 for LUT consumers. Float RGB rendering -/// evaluates the formula directly instead, so samples and results outside that domain survive. -pub fn tone_luts_depth(adj: &Adjustment, depth: Option) -> [Vec; 4] { - match (adj, depth) { - (Adjustment::Levels { master, per_channel, space: ToneSpace::Rgb, .. }, Some(SampleType::F32)) => { - let x = |k: usize| k as f32 / (LUT_SIZE - 1) as f32; - let row = |c: &LevelsChannel| (0..LUT_SIZE).map(|k| levels_float(master, levels_float(c, x(k))).clamp(0.0, 1.0)).collect(); - [row(&per_channel[0]), row(&per_channel[1]), row(&per_channel[2]), (0..LUT_SIZE).map(x).collect()] - } - _ => tone_luts_q(adj, depth.and_then(crate::adjustment_quantum)), - } -} - -/// Applies channel LUTs to a display-RGB colour in CMYK (ink brightness, 1 - ink) or Lab space, -/// through the conversions the document's surfaces use. The change is added as a difference of -/// two round trips, so channels a curve leaves alone (and out-of-gamut colours) stay exact. -fn tone_in_space(space: ToneSpace, luts: &[Vec; 4], c: [f32; 3]) -> [f32; 3] { - use photocraft_color::convert::{cmyk_to_rgb, rgb_to_cmyk}; - let (before, after) = match space { - ToneSpace::Cmyk => { - let ink = rgb_to_cmyk(c); - let out: [f32; 4] = std::array::from_fn(|i| 1.0 - lut(&luts[i], 1.0 - ink[i])); - if out == ink { - return c; - } - (cmyk_to_rgb(ink), cmyk_to_rgb(out)) - } - ToneSpace::Lab => { - let l = srgb_to_lab(c); - let n = [l[0] / 100.0, (l[1] + 128.0) / 255.0, (l[2] + 128.0) / 255.0]; - let o: [f32; 3] = std::array::from_fn(|i| lut(&luts[i], n[i])); - if o == n { - return c; - } - let back = |v: [f32; 3]| lab_to_srgb([v[0] * 100.0, v[1] * 255.0 - 128.0, v[2] * 255.0 - 128.0]); - (back(n), back(o)) - } - ToneSpace::Rgb => return std::array::from_fn(|i| lut(&luts[i], c[i])), - }; - std::array::from_fn(|i| (c[i] + after[i] - before[i]).clamp(0.0, 1.0)) -} - -/// Hue/Saturation's range edits as three hue-indexed tables (hue shift in degrees, saturation and -/// lightness as fractions), sampled at hue `k / (len - 1)` turns. Ranges add up where they overlap. -pub fn hue_range_tables(ranges: &[HueRange; 6]) -> [Vec; 3] { - let at = |k: usize| { - let deg = k as f32 / (LUT_SIZE - 1) as f32 * 360.0; - ranges.iter().filter(|r| !r.is_neutral()).fold([0.0f32; 3], |acc, r| { - let w = r.weight(deg); - [acc[0] + w * r.hue, acc[1] + w * r.saturation / 100.0, acc[2] + w * r.lightness / 100.0] - }) - }; - let rows: Vec<[f32; 3]> = (0..LUT_SIZE).map(at).collect(); - std::array::from_fn(|i| rows.iter().map(|r| r[i]).collect()) -} - -/// Hue/Saturation's saturation `s` (-1..1) as [`hue_saturation`] takes it in a document of -/// `depth`. A 32-bit Colorize builds its colour with the saturation times `1 - |lightness|`: -/// the photoshop corpus's rgb32 hue-saturation-colorize.psd (Saturation 40, Lightness +5) has 0.95 -/// of the chroma at every lightness, and is exact so, where 8 and 16 bits keep the full saturation -/// (their oracles are exact without it). Only a raised Lightness is measured; a lowered one is -/// taken to scale the same way. -pub fn colorize_saturation(s: f32, lightness: f32, colorize: bool, depth: Option) -> f32 { - // Clamped here too: a PSD can store a saturation beyond ±100, and the GPU scales it unclamped. - if colorize && depth == Some(SampleType::F32) { s.clamp(-1.0, 1.0) * (1.0 - lightness.abs().min(1.0)) } else { s } -} - -/// One Hue/Saturation evaluation: hue shift in degrees, saturation and lightness in -1..=1. -/// Colorize sets the hue and saturation instead of shifting them; at 0% it leaves only the -/// lightness, as in Photoshop (#2326). Ticking Colorize in the dialog starts saturation at 25%. -pub fn hue_saturation(c: [f32; 3], hue: f32, s: f32, l: f32, colorize: bool) -> [f32; 3] { - hue_saturation_in(c, hue, s, l, colorize, None) -} - -/// [`hue_saturation`] in a document of `depth`. At 32 bits Photoshop doesn't clip the raised -/// saturation, so saturated colours leave 0..1 (red with Hue +40, Saturation +25, Lightness -10 -/// becomes (1.0477, 0.649, -0.1477)), and it scales each colour's chroma around its lightness by -/// [`hdr_saturation_factor`], so colours at or above lightness 1 keep their hue too: the photoshop -/// corpus's rgb32 hue-saturation.psd is exact so. -pub fn hue_saturation_in(c: [f32; 3], hue: f32, s: f32, l: f32, colorize: bool, depth: Option) -> [f32; 3] { - let hdr = depth == Some(SampleType::F32); - let lighten = |v: f32| if l > 0.0 { v + (1.0 - v) * l } else { v * (1.0 + l) }; - if colorize { - // Colorize builds the colour at the lightened (or darkened) lightness, so black with - // Lightness +30 becomes a 30 % lightness colour, not grey (measured in Photoshop 27.11). - let (_, _, ll) = rgb_to_hsl(c); - return hsl_to_rgb(hue.rem_euclid(360.0) / 360.0, s.abs().min(1.0), lighten(ll)); - } - // Photoshop applies Lightness first, then rotates the hue and scales the saturation of the - // result: Hue +40, Saturation +25, Lightness -10 turns (240, 160, 30) into (173, 243, 0), not - // (168, 230, 14) (Photoshop 27.11 corpus file adjustments/rgb8/hue-saturation). - let lc = c.map(lighten); - let (hh, ss, ll) = rgb_to_hsl(lc); - let hh = (hh + hue / 360.0).rem_euclid(1.0); - if hdr { - // The chroma, not the HSL saturation, whose `2 - max - min` divisor is 0 at lightness 1 - // and negative above it: (2, 0, 0) with Hue +40 becomes (2, 1.333, 0) in Photoshop. - let d = (lc[0].max(lc[1]).max(lc[2]) - lc[0].min(lc[1]).min(lc[2])) * hdr_saturation_factor(s); - return hue_rgb(hh, ll - d / 2.0, ll + d / 2.0); - } - // Raising saturation divides by 1 - s, lowering it multiplies by 1 + s: +50 % doubles it - // (measured in Photoshop 27.11); +100 % saturates any colour that has some. - let ss = if s > 0.0 { ss / (1.0 - s).max(1.0 / 512.0) } else { ss * (1.0 + s) }.clamp(0.0, 1.0); - hsl_to_rgb(hh, ss, ll) -} - -/// The factor 32-bit Hue/Saturation scales chroma by for saturation `s` (-1..1), as Photoshop -/// computes it (measured at every whole percent from -100 to +100 on a 32-bit document): lowering -/// cuts `s` to 1/256 steps, raising cuts it to 254 steps out of 255, takes 255 / (255 - steps) to -/// 1/256 and stops at 32767/256, so +25 % gives 340/256, +99 % 63.75 and +100 % 127.996. -/// compose.wgsl's Hue/Saturation does the same in whole numbers. -pub fn hdr_saturation_factor(s: f32) -> f32 { - // The 1e-4 keeps a master plus range sum on its step: -0.46 + 0.96 is 0.49999997 in f32. - let s = s.clamp(-1.0, 1.0); - if s <= 0.0 { - return 1.0 - (-s * 256.0 + 1e-4).floor() / 256.0; - } - let steps = (s * 254.0 + 1e-4).floor() as u32; - (65280 / 255u32.saturating_sub(steps).max(1)).min(32767) as f32 / 256.0 -} - -/// A colour range's Lightness, applied after the master edits. It moves each channel towards the -/// pixel's brightest channel when raised and towards its darkest when lowered, not towards white -/// or black: Blues +50 turns (0, 29, 115) into (57, 71, 115), Blues -50 turns (102, 128, 204) into -/// (102, 115, 153) (measured in Photoshop 27.11). -pub fn range_lightness(c: [f32; 3], l: f32) -> [f32; 3] { - let l = l.clamp(-1.0, 1.0); - let target = if l > 0.0 { c[0].max(c[1]).max(c[2]) } else { c[0].min(c[1]).min(c[2]) }; - c.map(|v| v + (target - v) * l.abs()) -} - -/// Black & White grey value. Each colour is the sum of a grey part (its smallest channel), a -/// secondary-colour part (yellow, cyan or magenta: middle − smallest) and a primary part (red, -/// green or blue: largest − middle); the sliders (percent, Photoshop defaults 40 60 40 60 20 80 for -/// reds, yellows, greens, cyans, blues, magentas) weight the two colour parts. Unclipped: the -/// document's depth decides the range. -pub fn black_white_gray(c: [f32; 3], weights: &[f32; 6]) -> f32 { - let (r, g, b) = (c[0], c[1], c[2]); - let (max, min) = (r.max(g).max(b), r.min(g).min(b)); - let mid = r + g + b - max - min; - // Primary: the largest channel; secondary: the two largest channels together. - let primary = if r >= g && r >= b { - 0 - } else if g >= b { - 2 - } else { - 4 - }; - let secondary = if b <= r && b <= g { - 1 // red + green = yellow - } else if r <= g { - 3 // green + blue = cyan - } else { - 5 // red + blue = magenta - }; - min + (mid - min) * weights[secondary] / 100.0 + (max - mid) * weights[primary] / 100.0 -} - -/// Ordered-dither offset in -0.5..0.5 (4×4 Bayer matrix) for document pixel (x, y). -pub fn bayer4(x: i32, y: i32) -> f32 { - const M: [f32; 16] = [0.0, 8.0, 2.0, 10.0, 12.0, 4.0, 14.0, 6.0, 3.0, 11.0, 1.0, 9.0, 15.0, 7.0, 13.0, 5.0]; - (M[((y & 3) * 4 + (x & 3)) as usize] + 0.5) / 16.0 - 0.5 -} - -/// Samples a 3D LUT (`n`³ RGB triplets, red fastest) at `c`, trilinear or tetrahedral. -pub fn lut3d_sample(lut: &[f32], n: usize, c: [f32; 3], tetrahedral: bool) -> [f32; 3] { - // A degenerate or short table can't be sampled: leave the colour alone. - if n < 2 || n.checked_pow(3).and_then(|c| c.checked_mul(3)).is_none_or(|len| lut.len() < len) { - return c; - } - let m = (n - 1) as f32; - let pos = c.map(|v| v.clamp(0.0, 1.0) * m); - let i0 = pos.map(|p| (p.floor() as usize).min(n - 2)); - let f: [f32; 3] = std::array::from_fn(|k| pos[k] - i0[k] as f32); - let at = |dr: usize, dg: usize, db: usize| -> [f32; 3] { - let idx = (((i0[2] + db) * n + i0[1] + dg) * n + i0[0] + dr) * 3; - [lut[idx], lut[idx + 1], lut[idx + 2]] - }; - let mix = |w: &[(f32, [f32; 3])]| -> [f32; 3] { std::array::from_fn(|k| w.iter().map(|(a, v)| a * v[k]).sum()) }; - let (fr, fg, fb) = (f[0], f[1], f[2]); - if tetrahedral { - let (c000, c111) = (at(0, 0, 0), at(1, 1, 1)); - if fr > fg { - if fg > fb { - mix(&[(1.0 - fr, c000), (fr - fg, at(1, 0, 0)), (fg - fb, at(1, 1, 0)), (fb, c111)]) - } else if fr > fb { - mix(&[(1.0 - fr, c000), (fr - fb, at(1, 0, 0)), (fb - fg, at(1, 0, 1)), (fg, c111)]) - } else { - mix(&[(1.0 - fb, c000), (fb - fr, at(0, 0, 1)), (fr - fg, at(1, 0, 1)), (fg, c111)]) - } - } else if fb > fg { - mix(&[(1.0 - fb, c000), (fb - fg, at(0, 0, 1)), (fg - fr, at(0, 1, 1)), (fr, c111)]) - } else if fb > fr { - mix(&[(1.0 - fg, c000), (fg - fb, at(0, 1, 0)), (fb - fr, at(0, 1, 1)), (fr, c111)]) - } else { - mix(&[(1.0 - fg, c000), (fg - fr, at(0, 1, 0)), (fr - fb, at(1, 1, 0)), (fb, c111)]) - } - } else { - let lerp = |a: [f32; 3], b: [f32; 3], t: f32| -> [f32; 3] { std::array::from_fn(|k| a[k] + (b[k] - a[k]) * t) }; - let c00 = lerp(at(0, 0, 0), at(1, 0, 0), fr); - let c10 = lerp(at(0, 1, 0), at(1, 1, 0), fr); - let c01 = lerp(at(0, 0, 1), at(1, 0, 1), fr); - let c11 = lerp(at(0, 1, 1), at(1, 1, 1), fr); - lerp(lerp(c00, c10, fg), lerp(c01, c11, fg), fb) - } -} - -/// Color Balance on channel `ch` (0 red, 1 green, 2 blue) of `v` (0..1); `tones` are the -/// shadows, midtones and highlights slider triples (cyan–red, magenta–green, yellow–blue, -/// −100..100). -/// -/// Reverse-engineered from Photoshop (a 16-bit gray ramp through every tone at ±10..±100, pairs of -/// tones, and random settings of all nine sliders, Preserve Luminosity on and off): the three -/// tones fold into one Levels per channel (input black point, input white point, midtone gamma), -/// within 0.8 of 255 everywhere. Folding matters: a lowered shadows and a raised highlights -/// slider cancel each other's gamma, which applying the tones one after another doesn't (#3423). -/// - Preserve Luminosity off: a slider only moves its own channel. Lowered shadows set the black -/// point to |shadows| levels, raised highlights set the white point to 255 − highlights levels, -/// and the gamma is 2^(m / 100) with m = midtones + (shadows + highlights) / 2. -/// - Preserve Luminosity on: each channel's black point is (max − own) shadows levels, its white -/// point 255 − (own − min) highlights levels, and m = own − (max + min) / 2 midtones. -/// -/// A gamma > 1 starts with slope 2^gamma at black (up to 18 of 255 brighter -/// near black without it). When the black point reaches the white point, input -/// at or above the white point is white and the rest black. -pub fn color_balance_channel(tones: [[f32; 3]; 3], preserve_luminosity: bool, ch: usize, v: f32) -> f32 { - BalanceCurve::new(tones, preserve_luminosity, ch).eval(v) -} - -/// One channel's Color Balance curve (see [`color_balance_channel`]), with the terms that don't -/// depend on the sample worked out once rather than per pixel. -pub struct BalanceCurve { - /// Input black and white points. - b: f32, - w: f32, - /// The power curve's exponent, 1 / gamma. - e: f32, - /// The Hermite join of a gamma > 1. - knee: Option, -} - -/// Where a gamma > 1 curve's Hermite join ends (`u0`), its starting slope 2^gamma (`s0`), and the -/// power curve's value (`p`) and slope (`d`) at `u0`. -#[derive(Clone, Copy)] -struct Knee { - u0: f32, - s0: f32, - p: f32, - d: f32, -} - -impl BalanceCurve { - /// The red, green and blue curves. - pub fn rgb(tones: [[f32; 3]; 3], preserve_luminosity: bool) -> [Self; 3] { - std::array::from_fn(|ch| Self::new(tones, preserve_luminosity, ch)) - } - - /// The curve of channel `ch` (0 red, 1 green, 2 blue) for the shadows, midtones and - /// highlights slider triples `tones`. - pub fn new(tones: [[f32; 3]; 3], preserve_luminosity: bool, ch: usize) -> Self { - let [shadows, midtones, highlights] = tones.map(|t| t.map(|s| if s.is_finite() { s.clamp(-100.0, 100.0) } else { 0.0 })); - let own = |t: [f32; 3]| t.get(ch).copied().unwrap_or(0.0); - let max = |t: [f32; 3]| t[0].max(t[1]).max(t[2]); - let min = |t: [f32; 3]| t[0].min(t[1]).min(t[2]); - let (black, white, m) = if preserve_luminosity { - (max(shadows) - own(shadows), own(highlights) - min(highlights), own(midtones) - (max(midtones) + min(midtones)) / 2.0) - } else { - ((-own(shadows)).max(0.0), own(highlights).max(0.0), own(midtones) + (own(shadows) + own(highlights)) / 2.0) - }; - // The midtone gamma of the channel's Levels: `u^(1/gamma)`, except that a gamma > 1 - // (which would start with infinite slope) starts at slope 2^gamma and joins the power - // curve in a cubic Hermite at twice the input where that line meets it (Photoshop, - // measured on a 16-bit ramp at gamma 1.07..2: within 0.02 of 255). - let gamma = 2f32.powf(m / 100.0); - let e = 1.0 / gamma.max(0.01); - let knee = if gamma > 1.0 { - let s0 = 2f32.powf(gamma); - let u0 = (2.0 * s0.powf(1.0 / (e - 1.0))).min(1.0); - (!u0.is_nan() && u0 > 0.0).then(|| Knee { u0, s0, p: u0.powf(e), d: e * u0.powf(e - 1.0) }) - } else { - None - }; - Self { b: black / 255.0, w: 1.0 - white / 255.0, e, knee } - } - - /// The curve at `v` (0..1). - pub fn eval(&self, v: f32) -> f32 { - let (b, w) = (self.b, self.w); - let v = if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }; - if v >= w { - return 1.0; - } - if v <= b { - return 0.0; - } - let u = (v - b) / (w - b); - match self.knee { - Some(Knee { u0, s0, p, d }) if u < u0 => { - let t = u / u0; - let (t2, t3) = (t * t, t * t * t); - ((t3 - 2.0 * t2 + t) * u0 * s0 + (3.0 * t2 - 2.0 * t3) * p + (t3 - t2) * u0 * d).clamp(0.0, 1.0) - } - _ => u.powf(self.e), - } - } -} - -/// How much a colour belongs to each Selective Color range: reds, yellows, greens, cyans, -/// blues, magentas (by chroma within the hue sector), whites, neutrals and blacks (by lightness). -pub fn selective_color_weights(c: [f32; 3]) -> [f32; 9] { - let max = c[0].max(c[1]).max(c[2]); - let min = c[0].min(c[1]).min(c[2]); - let mid = c[0] + c[1] + c[2] - max - min; - let top = |i: usize| if c[i] >= max { max - mid } else { 0.0 }; - let bottom = |i: usize| if c[i] <= min { mid - min } else { 0.0 }; - [ - top(0), - bottom(2), - top(1), - bottom(0), - top(2), - bottom(1), - ((min - 0.5) * 2.0).max(0.0), - (1.0 - (max - 0.5).abs() - (min - 0.5).abs()).clamp(0.0, 1.0), - ((0.5 - max) * 2.0).max(0.0), - ] -} - -/// Photoshop Selective Color: each range shifts the cyan, magenta and yellow ink (1 − R, G, B) by -/// its percentage, plus its black percentage on every ink, weighted by how much the colour belongs -/// to the range. Relative mode scales the shift by the ink already present (so it can't tint pure -/// white). Absolute mode scales it by the room the ink has: adding ink by min(1, 2 × (1 − ink)), -/// removing it by min(1, 2 × ink), so Neutrals Cyan +50 darkens red 64 by 32, not 64 (all 72 -/// absolute range × ink cases within 1 level of Photoshop 27.11). -pub fn selective_color(c: [f32; 3], relative: bool, adj: &[[f32; 4]; 9]) -> [f32; 3] { - let w = selective_color_weights(c); - let mut delta = [0.0f32; 3]; - for (r, wr) in w.iter().enumerate() { - if *wr <= 0.0 { - continue; - } - let a = adj[r].map(|v| v / 100.0); - for i in 0..3 { - let ink = 1.0 - c[i]; - let d = a[i] + a[3]; - let d = if relative { - d * ink - } else if d > 0.0 { - d * (2.0 * (1.0 - ink)).min(1.0) - } else { - d * (2.0 * ink).min(1.0) - }; - delta[i] += d * wr; - } - } - std::array::from_fn(|i| (c[i] - delta[i]).clamp(0.0, 1.0)) -} - -const LUT_SIZE: usize = 4096; - -fn map_rgb(buf: &mut Buffer, f: impl Fn([f32; 3]) -> [f32; 3]) { - for p in &mut buf.px { - if p[3] <= 0.0 { - continue; - } - let r = f([p[0], p[1], p[2]]); - p[0] = r[0]; - p[1] = r[1]; - p[2] = r[2]; - } -} - -#[inline] -fn lut(table: &[f32], v: f32) -> f32 { - let x = v.clamp(0.0, 1.0) * (table.len() - 1) as f32; - // Never negative (NaN casts to 0, as its floor did), so truncating is `floor`, without the - // libm call baseline x86-64 (no SSE4.1) makes for it. - let i = x as usize; - let j = (i + 1).min(table.len() - 1); - let f = x - i as f32; - table[i] * (1.0 - f) + table[j] * f -} - -/// Table steps the end slopes of [`lut_extended`] are measured over: one step's difference near -/// 0.5 carries f32 rounding (2e-4 of the slope), while 16 steps are still only 0.4 % of the domain. -pub const TONE_SLOPE_SPAN: usize = 16; - -/// [`lut`] continued past 0..1 along the slope of the table's end segments, as Photoshop applies -/// a curve to float samples ([`float_tone_extrapolates`]). Inside the domain it is [`lut`]; -/// non-finite samples stay with it too, so an infinite one can't become NaN on a flat end. -#[inline] -fn lut_extended(table: &[f32], v: f32) -> f32 { - let n = table.len(); - if !v.is_finite() || (0.0..=1.0).contains(&v) || n < 2 { - return lut(table, v); - } - let k = TONE_SLOPE_SPAN.min(n - 1); - let per_unit = (n - 1) as f32 / k as f32; - if v < 0.0 { table[0] + v * (table[k] - table[0]) * per_unit } else { table[n - 1] + (v - 1.0) * (table[n - 1] - table[n - 1 - k]) * per_unit } -} - -/// Photo Filter's linear-light RGB matrix. Photoshop multiplies the pixel's D50 XYZ, relative to -/// white, by the filter colour's (mixed in by `density`): a fixed linear map, so it is folded into -/// one matrix. With `normalize_y` the map keeps luminance Y (32-bit Preserve Luminosity; 8/16-bit -/// documents instead restore the encoded luminosity like the Luminosity blend mode). Fitted on the -/// photoshop corpus `photo-filter.psd`: rgb16 within 0.6/255 everywhere. -pub fn photo_filter_matrix(color: [f32; 3], density: f32, normalize_y: bool) -> [[f32; 3]; 3] { - let d = if density.is_finite() { density.clamp(0.0, 1.0) } else { 0.0 }; - let xyz = mat3_mul(&SRGB_TO_XYZ_D50, color.map(|v| srgb_to_linear(v.clamp(0.0, 1.0)))); - let mut s: [f32; 3] = std::array::from_fn(|i| 1.0 - d + d * xyz[i] / D50[i]); - if normalize_y && s[1] > 1e-6 { - let y = s[1]; - s = s.map(|v| v / y); - } - // XYZ_D50_TO_SRGB · diag(s) · SRGB_TO_XYZ_D50 - std::array::from_fn(|r| std::array::from_fn(|c| (0..3).map(|k| XYZ_D50_TO_SRGB[r][k] * s[k] * SRGB_TO_XYZ_D50[k][c]).sum())) -} - -/// Photoshop's Vibrance on one pixel (`v`, `s`: the sliders / 100; `hi`: the sample ceiling). -/// -/// Measured black-box against Photoshop 25.4 on 7,400-colour charts (8- and 16-bit; sRGB, Adobe RGB -/// and ProPhoto documents). Both sliders work in linear light through the document's tone curve, -/// Vibrance first, then Saturation: -/// - Saturation moves each colour away from (or towards) the grey `0.288 R + 0.712 G` (blue has no -/// weight, in every profile) by `1 + s`, clipping each channel: within 0.07/255 at every `s`. -/// - Vibrance is an HSV change in linear light that keeps the hue: see [`vibrance_lin`]. -pub fn vibrance_px(c: [f32; 3], v: f32, s: f32, transfer: Transfer, hi: f32) -> [f32; 3] { - let mut l = c.map(|x| transfer.decode(x)); - if v != 0.0 { - l = vibrance_lin(l, v); - } - if s != 0.0 { - let g = VIBRANCE_GREY[0] * l[0] + VIBRANCE_GREY[1] * l[1]; - l = l.map(|x| (g + (1.0 + s) * (x - g)).clamp(0.0, hi)); - } - l.map(|x| transfer.encode(x.clamp(0.0, hi))) -} - -/// Weights of the grey Photoshop's Vibrance › Saturation desaturates to (R, G; blue has none). -pub const VIBRANCE_GREY: [f32; 2] = [0.288, 0.712]; - -/// Positive Vibrance's saturation boost, fitted to the measurements (see [`vibrance_lin`]). -pub const VIBRANCE_BOOST: [f32; 7] = [0.5001, 0.0887, 0.4374, 0.7573, -0.8113, 0.5154, 2.8026]; - -/// The Vibrance slider (`v` in [-1, 1]) on a linear-light pixel. With `t = 1 - min/max` (HSV -/// saturation) and `V = max`: -/// - below 0 (`a = -v`): `t' = t (1 - a/4) (1 - a + a t (1 + t) / 2)` and -/// `V' = V - a t (1 - t) (2 - t + t²) V (1 - V)`; exact (0.2/255 mean) except in the deepest -/// shadows (`V` under 0.05), which Photoshop desaturates less. -/// - above 0: `V' = V + v/4 t (1 - t) (2 - t + t²) V (1 - V)` (exact) and a saturation boost that -/// grows as `t` and `V` fall, damped on reds and skin (HSV hue 0–30°, fading out by 45° and in -/// from 300°): a fit, 0.4 (+10) to 5 (+100) /255 off on average. -pub fn vibrance_lin(c: [f32; 3], v: f32) -> [f32; 3] { - let mx = c[0].max(c[1]).max(c[2]); - let mn = c[0].min(c[1]).min(c[2]); - if mx <= 0.0 || mx - mn <= 1e-9 { - return c; - } - let t = 1.0 - mn / mx; - let shape = t * (1.0 - t) * (2.0 - t + t * t) * mx * (1.0 - mx).max(0.0); - let (t2, v2) = if v < 0.0 { - let a = -v; - (t * (1.0 - a / 4.0) * (1.0 - a + a * t * (1.0 + t) / 2.0), mx - a * shape) - } else { - let [c0, c1, p, q, r0, ra, rt] = VIBRANCE_BOOST; - let w = vibrance_skin(hsv_hue(c, mx, mn)); - let a = v * (1.0 - w) + 0.64 * v.powf(1.6) * w; - let boost = (c0 * a + c1 * a * a) * t.powf(p) * (1.0 - t).powf(q) * ((r0 + ra * a + rt * (1.0 - t)) * (1.0 - mx).max(0.0)).exp(); - ((t * (1.0 + boost)).min(1.0), mx + v / 4.0 * shape) - }; - let m2 = v2 * (1.0 - t2); - let k = (v2 - m2) / (mx - mn); - c.map(|x| m2 + (x - mn) * k) -} - -/// How much positive Vibrance treats a hue (degrees) as skin: 1 on 0–30°, fading to 0 by 45° and -/// in again from 300°. -fn vibrance_skin(h: f32) -> f32 { - if h <= 30.0 { - 1.0 - } else if h < 45.0 { - (45.0 - h) / 15.0 - } else if h < 300.0 { - 0.0 - } else { - (h - 300.0) / 60.0 - } -} - -/// HSV hue in degrees of `c` (its max `mx` and min `mn` given, `mx > mn`). -fn hsv_hue(c: [f32; 3], mx: f32, mn: f32) -> f32 { - let d = mx - mn; - let h = if mx == c[0] { - ((c[1] - c[2]) / d).rem_euclid(6.0) - } else if mx == c[1] { - (c[2] - c[0]) / d + 2.0 - } else { - (c[0] - c[1]) / d + 4.0 - }; - h * 60.0 -} - -/// Modern Brightness curve (one channel, `brightness` in [-150, 150]); pins pure black and white, -/// and `b = 0` is the identity. Raised, it is a line of slope `s = 1.375^(b/50)` from the origin -/// up to a knee at output 126/255, then a cubic Hermite to (1, 1) whose end slope is -/// `1 / (1 + 0.084 b)`; past about +110, where no such cubic stays below white, the roll-off is -/// `1 - (1 - y0)(1 - u)^α` instead (continuous slope `α` at the knee, flat at white). Lowered, it -/// is the inverse of the curve raised by as much. -/// -/// Fit to every Photoshop measurement we have, all within about a level and a half: its ±50 -/// samples (`modern_brightness_matches_photoshop`), the photoshop corpus's brightness-contrast.psd -/// (+25 with contrast +30) and psd-tools' brightnesscontrast_rgb.psd, whose masked layers give -/// +23, -31 and -95 (+150 within 6 levels there, where every curve family tried bottoms out). -pub fn modern_brightness(v: f32, brightness: f32) -> f32 { - if brightness == 0.0 || !brightness.is_finite() { - return v; - } - Brightness::new(brightness).eval(v) -} - -/// [`modern_brightness`] for one slider value, its curve's constants worked out once. -struct Brightness { - raise: bool, - s: f32, - e: f32, - x0: f32, - /// The knee's slope over the roll-off's secant (`α` of Fritsch–Carlson); a power roll-off - /// replaces the Hermite when α² + β² > 9. - alpha: f32, - hermite: bool, -} - -/// Output level of the Brightness curve's knee. -const BRIGHTNESS_KNEE: f32 = 126.0 / 255.0; - -impl Brightness { - fn new(brightness: f32) -> Self { - let b = brightness.abs(); - let s = 1.375f32.powf(b / 50.0); - let e = 1.0 / (1.0 + 0.084 * b); - let x0 = (BRIGHTNESS_KNEE / s).min(1.0); - let secant = (1.0 - BRIGHTNESS_KNEE) / (1.0 - x0).max(1e-6); - let (alpha, beta) = (s / secant, e / secant); - Brightness { raise: brightness > 0.0, s, e, x0, alpha, hermite: alpha * alpha + beta * beta <= 9.0 } - } - - fn eval(&self, v: f32) -> f32 { - let v = v.clamp(0.0, 1.0); - if self.raise { - return self.raised(v); - } - if v <= 0.0 || v >= 1.0 { - return v; - } - // The inverse of the raised curve (monotone on [0, 1]), by bisection. - let (mut lo, mut hi) = (0.0f32, 1.0f32); - for _ in 0..32 { - let mid = 0.5 * (lo + hi); - if self.raised(mid) < v { - lo = mid; - } else { - hi = mid; - } - } - 0.5 * (lo + hi) - } - - /// The curve raised: the line, then a monotone roll-off to (1, 1). - fn raised(&self, x: f32) -> f32 { - let Brightness { s, e, x0, alpha, hermite, .. } = *self; - let y0 = BRIGHTNESS_KNEE; - if x <= x0 { - return y0.min(s * x); - } - let h = (1.0 - x0).max(1e-6); - let t = ((x - x0) / h).clamp(0.0, 1.0); - let y = if hermite { - let (t2, t3) = (t * t, t * t * t); - (2.0 * t3 - 3.0 * t2 + 1.0) * y0 + (t3 - 2.0 * t2 + t) * h * s + (-2.0 * t3 + 3.0 * t2) + (t3 - t2) * h * e - } else { - 1.0 - (1.0 - y0) * (1.0 - t).powf(alpha) - }; - y.clamp(0.0, 1.0) - } -} - -/// Modern Brightness/Contrast as one channel's lookup table (4096 samples over 0..1): -/// [`modern_brightness`] then [`modern_contrast`], as Photoshop applies them. -pub fn modern_lut(brightness: f32, contrast: f32) -> Vec { - let step = |k: usize, n: usize| k as f32 / (n - 1) as f32; - let bright: Vec = if brightness == 0.0 || !brightness.is_finite() { - (0..LUT_SIZE).map(|k| step(k, LUT_SIZE)).collect() - } else if brightness > 0.0 { - let curve = Brightness::new(brightness); - (0..LUT_SIZE).map(|k| curve.raised(step(k, LUT_SIZE))).collect() - } else { - // Lowered: invert the raised curve, sampled four times finer, in one monotone pass. - let curve = Brightness::new(-brightness); - let fine = 4 * LUT_SIZE; - let ys: Vec = (0..fine).map(|j| curve.raised(step(j, fine))).collect(); - let mut j = 0; - (0..LUT_SIZE) - .map(|k| { - let y = step(k, LUT_SIZE); - while j + 2 < fine && ys.get(j + 1).is_some_and(|&n| n < y) { - j += 1; - } - let (y0, y1) = (ys.get(j).copied().unwrap_or(0.0), ys.get(j + 1).copied().unwrap_or(1.0)); - let f = if y1 > y0 { ((y - y0) / (y1 - y0)).clamp(0.0, 1.0) } else { 0.0 }; - (step(j, fine) + f / (fine - 1) as f32).clamp(0.0, 1.0) - }) - .collect() - }; - bright.into_iter().map(|b| modern_contrast(b, contrast).clamp(0.0, 1.0)).collect() -} - -/// Modern Contrast curve (one channel, `contrast` in [-50, 100]). A symmetric cubic-Hermite S-curve -/// pivoting at 0.5: endpoint slope `1 - c/128`, centre slope `1 + c/128`. Near-exact vs Photoshop -/// (≤0.5/255). `c = 0` is the identity; pins 0, 0.5 and 1. -pub fn modern_contrast(v: f32, contrast: f32) -> f32 { - if contrast == 0.0 { - return v; - } - let k = contrast / 128.0; - let (end, mid) = (1.0 - k, 1.0 + k); - // Cubic Hermite on [0, 0.5]: pinned (0,0) slope `end`, (0.5,0.5) slope `mid`. `t` in [0,1]. - let half = |t: f32| end * 0.5 * (t * t * t - 2.0 * t * t + t) + (-2.0 * t * t * t + 3.0 * t * t) * 0.5 + mid * 0.5 * (t * t * t - t * t); - let v = v.clamp(0.0, 1.0); - if v <= 0.5 { half(v / 0.5) } else { 1.0 - half((1.0 - v) / 0.5) } -} - -/// Photoshop posterize: `n` equal input bins over 0..=255, output levels -/// `floor(k * 255 / (n - 1))` (exact on the corpus for 3, 7, 13 and 21 levels). -pub fn posterize(v: f32, levels: u32) -> f32 { - let n = levels.clamp(2, 255) as f32; - let x = (v.clamp(0.0, 1.0) * 255.0).round(); - let bin = (x * n / 256.0).floor().min(n - 1.0); - (bin * 255.0 / (n - 1.0)).floor() / 255.0 -} - -/// [`posterize`] in a document of `depth` (`None`: unknown, treated as 8-bit). At 16 bits -/// Photoshop bins the 16-bit sample (`⌊v · n / 32768⌋`) and lands on 8-bit levels through a -/// 16-bit step: `⌊b · 32768 / (n - 1)⌋`, converted with `⌊(o · 255 + 16384) / 32768⌋`, so -/// 127.5 comes out as 128 but 42.5 as 42 (8 bits floor them all). Exact on every sample of -/// psd-tools posterize_16bits_rgb.psd and posterize_16bits_grayscale.psd (levels 2 to 21), -/// which the 8-bit rule missed by up to half the range. -pub fn posterize_in(v: f32, levels: u32, depth: Option) -> f32 { - if depth != Some(SampleType::U16) { - return posterize(v, levels); - } - let n = f64::from(levels.clamp(2, 255)); - let x = (f64::from(v.clamp(0.0, 1.0)) * 32768.0).round(); - let bin = (x * n / 32768.0).floor().min(n - 1.0); - let step = (bin * 32768.0 / (n - 1.0)).floor(); - (((step * 255.0 + 16384.0) / 32768.0).floor() / 255.0) as f32 -} - -pub fn levels(ch: &LevelsChannel, v: f32) -> f32 { - levels_q(ch, v, None) -} - -/// [`levels`] on samples with `quantum` steps per unit (8-bit: 255). Photoshop works on whole -/// levels in three steps, each rounded half up to a whole level: the input-range stretch, the -/// midtone gamma ([`levels_gamma`]) and the output range. So a 44..214 range maps 45, 46, 47, 48 -/// → 1.5, 3, 4.5, 6 → 2, 3, 5, 6 (psd-tools levels_grayscale, where the gamma toe magnifies the -/// steps), and an output range narrower than 0..255 maps neighbouring gamma levels to one level -/// (psd-tools levels_rgb: 43..48 → 58 through a 0.47 channel gamma and the master's 48..255). -/// In a LUT the result is a staircase that is exact at every level. -pub fn levels_q(ch: &LevelsChannel, v: f32, quantum: Option) -> f32 { - let range = (ch.in_white - ch.in_black).max(1e-6); - let quantum = quantum.filter(|q| q.is_finite() && *q >= 1.0); - let whole = |x: f32| match quantum { - Some(q) => (x * q + 0.5).floor() / q, - None => x, - }; - let u = match quantum { - Some(q) => { - let v = (v * q).round() / q; - (((v - ch.in_black) / range).clamp(0.0, 1.0) * q + 0.5 + 1e-3).floor() / q - } - None => ((v - ch.in_black) / range).clamp(0.0, 1.0), - }; - let t = whole(levels_gamma(u, ch.gamma.max(0.01))); - whole(ch.out_black + t * (ch.out_white - ch.out_black)) -} - -/// Exponent of the shadow toe in [`levels_gamma`] (fitted; see there). -const LEVELS_TOE_POWER: f32 = 2.2; - -/// Levels' midtone gamma `g` on `u` in 0..1: `u^(1/g)`, except that above 1, where that power -/// curve is infinitely steep at black, Photoshop starts along a toe `a·u − b·u^q` of slope -/// `a = 2^g` that joins the curve with the same value and slope. `q` = [`LEVELS_TOE_POWER`] is -/// fitted on whole-level oracles at gamma 1.16, 1.22, 1.3, 1.78 and 2.0 (psd-tools levels_rgb -/// and levels_grayscale, the photoshop corpus's rgb8 and gray8 levels.psd, a measured 0..255 -/// ramp): all but 2 of their 1118 levels exact, the others within one. Below 1 the power curve is -/// exact (gamma 0.67 and 0.7: every level). -pub fn levels_gamma(u: f32, g: f32) -> f32 { - let c = 1.0 / g; - if g <= 1.0 { - return u.powf(c); - } - let (a, q) = (2f32.powf(g), LEVELS_TOE_POWER); - // Where the toe meets the curve: a·u1 − b·u1^q = u1^c and a − q·b·u1^(q−1) = c·u1^(c−1). - let u1 = ((1.0 - c / q) / (a * (1.0 - 1.0 / q))).powf(1.0 / (1.0 - c)); - if u >= u1 || u1 <= 0.0 { - return u.powf(c); - } - let b = (a * u1 - u1.powf(c)) / u1.powf(q); - // Just above gamma 1 the toe shrinks to nothing: u1^q underflows to 0 while u1 doesn't, and - // the power curve is the toe's limit there (otherwise b = inf and black turns NaN). - if !b.is_finite() { - return u.powf(c); - } - a * u - b * u.powf(q) -} - -/// [`levels`] in a 32-bit document. Neither the input is clipped to the input range nor the result -/// to the output range there, and the midtone gamma is a plain power curve, mirrored below the -/// black point (the oracle corpus' rgb32 and gray32 levels.psd: within 0.5/255, 10/255 off with -/// the clipped curve). -pub fn levels_float(ch: &LevelsChannel, v: f32) -> f32 { - let t = (v - ch.in_black) / (ch.in_white - ch.in_black).max(1e-6); - let t = if ch.gamma == 1.0 { t } else { t.signum() * t.abs().powf(1.0 / ch.gamma.max(0.01)) }; - ch.out_black + t * (ch.out_white - ch.out_black) -} - -/// The LUT of one Curves curve: [`curve_map_lut`] for a pencil-drawn map, else [`curve_lut`]. -pub fn curve_lut_mode(points: &[CurvePoint], pencil: bool) -> Vec { - if pencil { curve_map_lut(points) } else { curve_lut(points) } -} - -/// A pencil-drawn Curves map (see [`photocraft_doc::adjust::curve_map`]): straight segments -/// between its entries, constant outside the first/last, clamped to 0..=1, sampled into a LUT. -pub fn curve_map_lut(points: &[CurvePoint]) -> Vec { - let mut pts: Vec<(f32, f32)> = points.iter().filter(|p| p.input.is_finite() && p.output.is_finite()).map(|p| (p.input, p.output)).collect(); - pts.sort_by(|a, b| a.0.total_cmp(&b.0)); - pts.dedup_by(|a, b| (a.0 - b.0).abs() < 1e-6); - let ident = |k: usize| k as f32 / (LUT_SIZE - 1) as f32; - let (Some(&first), Some(&last)) = (pts.first(), pts.last()) else { return (0..LUT_SIZE).map(ident).collect() }; - let mut seg = 0; - (0..LUT_SIZE) - .map(|k| { - let xv = ident(k); - if xv <= first.0 { - return first.1.clamp(0.0, 1.0); - } - if xv >= last.0 { - return last.1.clamp(0.0, 1.0); - } - while pts.get(seg + 1).is_some_and(|p| p.0 < xv) { - seg += 1; - } - let (Some(&(x0, y0)), Some(&(x1, y1))) = (pts.get(seg), pts.get(seg + 1)) else { return last.1.clamp(0.0, 1.0) }; - let t = if x1 > x0 { (xv - x0) / (x1 - x0) } else { 0.0 }; - (y0 + (y1 - y0) * t).clamp(0.0, 1.0) - }) - .collect() -} - -/// Photoshop curve: a natural cubic spline through the points (it may -/// overshoot between points, as Photoshop's does), constant outside the -/// first/last point, clamped to 0..=1, sampled into a LUT. -pub fn curve_lut(points: &[CurvePoint]) -> Vec { - let mut pts: Vec<(f32, f32)> = points.iter().map(|p| (p.input, p.output)).collect(); - pts.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal)); - pts.dedup_by(|a, b| (a.0 - b.0).abs() < 1e-6); - if pts.len() < 2 { - return (0..LUT_SIZE).map(|i| i as f32 / (LUT_SIZE - 1) as f32).collect(); - } - let n = pts.len(); - // Second derivatives of the natural spline (tridiagonal solve). - let mut m2 = vec![0.0f64; n]; - if n > 2 { - let x: Vec = pts.iter().map(|p| f64::from(p.0)).collect(); - let y: Vec = pts.iter().map(|p| f64::from(p.1)).collect(); - let mut c = vec![0.0f64; n]; - let mut d = vec![0.0f64; n]; - for i in 1..n - 1 { - let (h0, h1) = (x[i] - x[i - 1], x[i + 1] - x[i]); - let a = h0 / 6.0; - let b = (h0 + h1) / 3.0; - let cc = h1 / 6.0; - let r = (y[i + 1] - y[i]) / h1 - (y[i] - y[i - 1]) / h0; - let denom = b - a * c[i - 1]; - c[i] = cc / denom; - d[i] = (r - a * d[i - 1]) / denom; - } - for i in (1..n - 1).rev() { - m2[i] = d[i] - c[i] * m2[i + 1]; - } - } - (0..LUT_SIZE) - .map(|k| { - let xv = k as f32 / (LUT_SIZE - 1) as f32; - if xv <= pts[0].0 { - return pts[0].1.clamp(0.0, 1.0); - } - if xv >= pts[n - 1].0 { - return pts[n - 1].1.clamp(0.0, 1.0); - } - let i = pts.windows(2).position(|w| xv <= w[1].0).unwrap_or(n - 2); - let (x0, y0) = (f64::from(pts[i].0), f64::from(pts[i].1)); - let (x1, y1) = (f64::from(pts[i + 1].0), f64::from(pts[i + 1].1)); - let h = x1 - x0; - let t = f64::from(xv); - let a = (x1 - t) / h; - let b = (t - x0) / h; - let y = a * y0 + b * y1 + ((a * a * a - a) * m2[i] + (b * b * b - b) * m2[i + 1]) * h * h / 6.0; - (y as f32).clamp(0.0, 1.0) - }) - .collect() -} - -/// A layer-style contour curve: [`curve_lut`], except that the curve bends sharply at corner -/// points (`corners[i]` true; Photoshop's Contour Editor "Corner"): each run between corners is -/// its own natural spline, so all-corner points make a polyline. Missing flags are smooth. -pub fn contour_curve_lut(points: &[CurvePoint], corners: &[bool]) -> Vec { - let mut pts: Vec<(CurvePoint, bool)> = points.iter().enumerate().map(|(i, p)| (p.clone(), corners.get(i).copied().unwrap_or(false))).collect(); - if !pts.iter().any(|p| p.1) { - return curve_lut(points); - } - pts.sort_by(|a, b| a.0.input.partial_cmp(&b.0.input).unwrap_or(std::cmp::Ordering::Equal)); - pts.dedup_by(|a, b| (a.0.input - b.0.input).abs() < 1e-6); - let mut out: Vec = Vec::new(); - let mut start = 0usize; - let last = pts.len().saturating_sub(1); - for i in 1..=last { - let corner = pts.get(i).is_some_and(|p| p.1); - if !(corner || i == last) { - continue; - } - let Some(seg) = pts.get(start..=i) else { break }; - let from = seg.first().map_or(0.0, |p| p.0.input); - let lut = curve_lut(&seg.iter().map(|p| p.0.clone()).collect::>()); - if out.is_empty() { - out = lut; - } else { - for (k, (o, v)) in out.iter_mut().zip(lut).enumerate() { - if k as f32 / (LUT_SIZE - 1) as f32 >= from { - *o = v; - } - } - } - start = i; - } - if out.is_empty() { curve_lut(points) } else { out } -} - -fn gradient(stops: &[(f32, [f32; 3])], t: f32) -> [f32; 3] { - match stops { - [] => [t; 3], - [s] => s.1, - _ => { - if t <= stops[0].0 { - return stops[0].1; - } - for w in stops.windows(2) { - if t <= w[1].0 { - let k = if w[1].0 > w[0].0 { (t - w[0].0) / (w[1].0 - w[0].0) } else { 0.0 }; - return std::array::from_fn(|i| w[0].1[i] + (w[1].1[i] - w[0].1[i]) * k); - } - } - stops[stops.len() - 1].1 - } - } -} - -pub fn rgb_to_hsl(c: [f32; 3]) -> (f32, f32, f32) { - let max = c[0].max(c[1]).max(c[2]); - let min = c[0].min(c[1]).min(c[2]); - let l = (max + min) / 2.0; - if (max - min).abs() < 1e-7 { - return (0.0, 0.0, l); - } - let d = max - min; - let s = if l > 0.5 { d / (2.0 - max - min) } else { d / (max + min) }; - let h = if max == c[0] { - ((c[1] - c[2]) / d).rem_euclid(6.0) - } else if max == c[1] { - (c[2] - c[0]) / d + 2.0 - } else { - (c[0] - c[1]) / d + 4.0 - }; - (h / 6.0, s, l) -} - -pub fn hsl_to_rgb(h: f32, s: f32, l: f32) -> [f32; 3] { - if s <= 0.0 { - return [l; 3]; - } - let q = if l < 0.5 { l * (1.0 + s) } else { l + s - l * s }; - hue_rgb(h, 2.0 * l - q, q) -} - -/// The colour of hue `h` (0..1) with its smallest channel at `p` and its largest at `q`. -fn hue_rgb(h: f32, p: f32, q: f32) -> [f32; 3] { - let f = |mut t: f32| { - t = t.rem_euclid(1.0); - if t < 1.0 / 6.0 { - p + (q - p) * 6.0 * t - } else if t < 0.5 { - q - } else if t < 2.0 / 3.0 { - p + (q - p) * (2.0 / 3.0 - t) * 6.0 - } else { - p - } - }; - [f(h + 1.0 / 3.0), f(h), f(h - 1.0 / 3.0)] -} - #[cfg(test)] mod lookup_tests { use super::*; @@ -1613,892 +397,7 @@ mod lookup_tests { } #[cfg(test)] -mod tone_tests { - use super::*; - use photocraft_geom::Rect; - - fn ramp() -> Buffer { - let rect = Rect::new(0, 0, 8, 8); - let px = (0..64).map(|i| [((i % 8) as f32) / 7.0, ((i / 8) as f32) / 7.0, 0.3, 1.0]).collect(); - Buffer { rect, px } - } - - /// Photoshop 27.11, measured: Brightness/Contrast with Use Legacy on, over a gray ramp - /// (x = 0, 16, …, 240, 255), one row per (brightness, contrast). - /// One pixel through `adj` in a 32-bit document. - fn hdr(adj: &Adjustment, c: [f32; 3]) -> [f32; 3] { - let mut b = Buffer::filled(crate::Rect::new(0, 0, 1, 1), [c[0], c[1], c[2], 1.0]); - apply_depth(adj, &mut b, Transfer::Gamma(1.0), Some(SampleType::F32)); - [b.px[0][0], b.px[0][1], b.px[0][2]] - } - - /// Photoshop's 32-bit Hue/Saturation (photoshop corpus rgb32 hue-saturation.psd: hue +40, - /// saturation +25, lightness -10): saturated colours leave 0..1, and the saturation factor is - /// 1 / (1 - 63/255), so red becomes (1.0477, 0.649, -0.1477), where 8 bits clip to (0.9, 0.6, 0). - #[test] - fn thirty_two_bit_hue_saturation_is_unclipped() { - let adj = Adjustment::HueSaturation { hue: 40.0, saturation: 25.0, lightness: -10.0, colorize: false, ranges: HueRange::defaults() }; - let near = |got: [f32; 3], want: [f32; 3]| got.iter().zip(want).all(|(g, w)| (g - w).abs() < 1e-3); - for (c, want) in - [([1.0, 0.0, 0.0], [1.0477, 0.649, -0.1477]), ([0.9301, 0.6105, 0.2541], [0.7804, 0.9369, 0.1289]), ([0.0, 0.3864, 1.0], [0.1871, -0.1477, 1.0477])] - { - assert!(near(hdr(&adj, c), want), "{c:?}: {:?}", hdr(&adj, c)); - } - let mut b = Buffer::filled(crate::Rect::new(0, 0, 1, 1), [1.0, 0.0, 0.0, 1.0]); - apply_depth(&adj, &mut b, Transfer::Srgb, Some(SampleType::U16)); - assert!(b.px[0].iter().all(|v| (0.0..=1.0).contains(v)), "16 bits clip: {:?}", b.px[0]); - } - - /// Photoshop's 32-bit Colorize (photoshop corpus rgb32 hue-saturation-colorize.psd: hue -160, - /// saturation 40, lightness +5): red becomes (0.3445, 0.5852, 0.7055), 0.95 of the chroma an - /// 8-bit Colorize gives at the same lightness, (0.335, 0.5883, 0.715). - #[test] - fn thirty_two_bit_colorize_scales_the_saturation() { - let adj = Adjustment::HueSaturation { hue: -160.0, saturation: 40.0, lightness: 5.0, colorize: true, ranges: HueRange::defaults() }; - let near = |got: [f32; 3], want: [f32; 3]| got.iter().zip(want).all(|(g, w)| (g - w).abs() < 2e-3); - let red = hdr(&adj, [1.0, 0.0, 0.0]); - assert!(near(red, [0.3445, 0.5852, 0.7055]), "{red:?}"); - let mut b = Buffer::filled(crate::Rect::new(0, 0, 1, 1), [1.0, 0.0, 0.0, 1.0]); - apply_depth(&adj, &mut b, Transfer::Srgb, Some(SampleType::U16)); - assert!(near([b.px[0][0], b.px[0][1], b.px[0][2]], [0.335, 0.5883, 0.715]), "16-bit keeps the full saturation: {:?}", b.px[0]); - } - - /// Photoshop's 32-bit saturation factor (Hue/Saturation on red (1, 0, 0) in a 32-bit document, - /// read back from the saved float TIFF, exact in 1/512): red's R is 0.5 + 0.5 x the factor. - #[test] - fn thirty_two_bit_saturation_steps_match_photoshop() { - for (sat, want) in [ - (10.0, 539.0 / 512.0), - (75.0, 2.4609375), - (90.0, 2673.0 / 512.0), - (99.0, 32.375), - (100.0, 33023.0 / 512.0), - (-10.0, 487.0 / 512.0), - (-25.0, 0.875), - (-50.0, 0.75), - (-100.0, 0.5), - ] { - let adj = Adjustment::HueSaturation { hue: 0.0, saturation: sat, lightness: 0.0, colorize: false, ranges: HueRange::defaults() }; - let got = hdr(&adj, [1.0, 0.0, 0.0])[0]; - assert!((got - want).abs() < 1e-4, "saturation {sat}: {got}, Photoshop {want}"); - } - } - - /// 32-bit colours at or above HSL lightness 1 (red at +1 stop, (2, 0, 0)) keep their hue and - /// get their chroma scaled like any other, as in Photoshop; they used to turn NaN or grey. - #[test] - fn thirty_two_bit_hue_saturation_keeps_bright_colours() { - let pale = [280.0 / 255.0, 230.0 / 255.0, 256.0 / 255.0]; - let near = |got: [f32; 3], want: [f32; 3]| got.iter().zip(want).all(|(g, w)| (g - w).abs() <= 1e-3 * w.abs().max(1.0)); - for (hue, sat, c, want) in [ - (40.0, 0.0, [2.0, 0.0, 0.0], [2.0, 1.33301, 0.0]), - (40.0, 0.0, pale, [1.09804, 0.930687, 0.901961]), - (0.0, 25.0, [2.0, 0.0, 0.0], [2.32812, -0.328125, -0.328125]), - (0.0, 25.0, pale, [1.13021, 0.869792, 1.00521]), - (0.0, -25.0, [2.0, 0.0, 0.0], [1.75, 0.25, 0.25]), - (0.0, 100.0, [140.0 / 255.0, 115.0 / 255.0, 128.0 / 255.0], [6.77432, -5.77432, 0.750976]), - (0.0, 100.0, [2.0, 0.0, 0.0], [128.996, -126.996, -126.996]), - ] { - let adj = Adjustment::HueSaturation { hue, saturation: sat, lightness: 0.0, colorize: false, ranges: HueRange::defaults() }; - let got = hdr(&adj, c); - assert!(near(got, want), "hue {hue}, saturation {sat}, {c:?}: {got:?}, Photoshop {want:?}"); - } - // A master plus a range edit that add up to a whole step stay on it: Reds +96 over a master - // -46 scales red as much as a master +50 alone (in f32 the sum is 0.49999997). - let mut ranges = HueRange::defaults(); - ranges[0].saturation = 96.0; - let summed = Adjustment::HueSaturation { hue: 0.0, saturation: -46.0, lightness: 0.0, colorize: false, ranges }; - let single = Adjustment::HueSaturation { hue: 0.0, saturation: 50.0, lightness: 0.0, colorize: false, ranges: HueRange::defaults() }; - assert_eq!(hdr(&summed, [1.0, 0.0, 0.0]), hdr(&single, [1.0, 0.0, 0.0])); - // Lightness 0 with a negative channel divides by zero the same way. - let adj = Adjustment::HueSaturation { hue: 40.0, saturation: 25.0, lightness: 0.0, colorize: false, ranges: HueRange::defaults() }; - assert!(hdr(&adj, [0.25, -0.25, 0.0]).iter().all(|v| v.is_finite())); - } - - /// Photoshop's own 32-bit results (photoshop corpus rgb32): nothing clips, legacy contrast - /// pivots at 127, the mixer cuts its percentages to 1/1024 and counts 255/512 of the - /// constant, and the Black & White tint keeps values above 1. - #[test] - fn thirty_two_bit_adjustments_match_photoshop_unclipped() { - let near = |got: [f32; 3], want: [f32; 3], tol: f32| got.iter().zip(want).all(|(g, w)| (g - w).abs() <= tol); - let bc = Adjustment::BrightnessContrast { brightness: 25.0, contrast: 30.0, legacy: true }; - // brightness-contrast-legacy.psd - assert!(near(hdr(&bc, [0.4910, 0.0009, 0.9301]), [0.6280, -0.0721, 1.2553], 2e-4), "{:?}", hdr(&bc, [0.4910, 0.0009, 0.9301])); - // channel-mixer.psd: pure red, green, blue and black, exactly. - let mixer = Adjustment::ChannelMixer { matrix: [[0.8, 0.3, -0.1, 0.0], [0.1, 0.9, 0.0, 0.05], [0.0, 0.2, 0.7, 0.0]], monochrome: false }; - for (c, want) in [ - ([1.0, 0.0, 0.0], [0.7998047, 0.1245117, 0.0]), - ([0.0, 1.0, 0.0], [0.2998047, 0.9243164, 0.1992188]), - ([0.0, 0.0, 1.0], [-0.0996094, 0.0249023, 0.6992188]), - ([0.0, 0.0, 0.0], [0.0, 0.0249023, 0.0]), - ] { - assert!(near(hdr(&mixer, c), want, 1e-6), "{c:?}: {:?}", hdr(&mixer, c)); - } - // black-white-tint.psd: white tints past 1. - let bw = Adjustment::BlackWhite { weights: [40.0, 60.0, 40.0, 60.0, 20.0, 80.0], tint: Some([0.88235295, 0.827451, 0.7019608]) }; - assert!(near(hdr(&bw, [1.0; 3]), [1.0522, 0.9973, 0.8718], 2e-4), "{:?}", hdr(&bw, [1.0; 3])); - // 8/16-bit documents still clip. - let mut b = Buffer::filled(crate::Rect::new(0, 0, 1, 1), [1.0, 1.0, 1.0, 1.0]); - apply_depth(&bw, &mut b, Transfer::Srgb, None); - assert!(b.px[0].iter().all(|v| *v <= 1.0)); - } - - #[test] - fn legacy_brightness_contrast_matches_photoshop() { - const X: [u8; 17] = [0, 16, 32, 48, 64, 80, 96, 112, 128, 144, 160, 176, 192, 208, 224, 240, 255]; - let measured: [(f32, f32, [u8; 17]); 7] = [ - (40.0, 0.0, [40, 56, 72, 88, 104, 120, 136, 152, 168, 184, 200, 216, 232, 248, 255, 255, 255]), - (-40.0, 0.0, [0, 0, 0, 8, 24, 40, 56, 72, 88, 104, 120, 136, 152, 168, 184, 200, 215]), - (0.0, 30.0, [0, 0, 0, 14, 37, 60, 82, 105, 128, 151, 174, 196, 219, 242, 255, 255, 255]), - (0.0, -30.0, [38, 49, 61, 72, 83, 94, 106, 117, 128, 139, 150, 162, 173, 184, 195, 207, 217]), - (40.0, 30.0, [3, 25, 48, 71, 94, 117, 139, 162, 185, 208, 231, 253, 255, 255, 255, 255, 255]), - (100.0, 0.0, [100, 116, 132, 148, 164, 180, 196, 212, 228, 244, 255, 255, 255, 255, 255, 255, 255]), - (0.0, 80.0, [0, 0, 0, 0, 0, 0, 0, 48, 128, 208, 255, 255, 255, 255, 255, 255, 255]), - ]; - for (brightness, contrast, want) in measured { - let rect = Rect::new(0, 0, 17, 1); - let px = X.iter().map(|x| [f32::from(*x) / 255.0; 4]).map(|p| [p[0], p[1], p[2], 1.0]).collect(); - let mut b = Buffer { rect, px }; - apply(&Adjustment::BrightnessContrast { brightness, contrast, legacy: true }, &mut b); - for (i, (p, w)) in b.px.iter().zip(want).enumerate() { - let got = (p[0] * 255.0).round() as i32; - assert!((got - i32::from(w)).abs() <= 1, "b {brightness} c {contrast} at {}: {got} vs Photoshop {w}", X[i]); - } - } - } - - /// Pixel → Photoshop's split. 8-bit from psd-tools threshold_rgb.psd: the first three are - /// white though their Rec. 601 grey rounds below 60, and (131, 109, 99) sits exactly on 114.5 - /// at level 115 (halves round down). 16-bit from threshold_16bits_rgb.psd and the photoshop - /// corpus's rgb16 threshold-128.psd, whose mid grey 16448 is level 128 in 16 bits. - #[test] - fn threshold_splits_on_the_luminosity_like_photoshop() { - let c8 = |r: u8, g: u8, b: u8| [r, g, b].map(|v| f32::from(v) / 255.0); - for (c, level, white) in - [(c8(87, 51, 31), 60u8, true), (c8(90, 49, 33), 60, true), (c8(68, 57, 50), 60, true), (c8(48, 63, 72), 60, false), (c8(131, 109, 99), 115, false)] - { - assert_eq!(threshold_white(c, f32::from(level) / 255.0, Some(SampleType::U8)), white, "8-bit {c:?} at {level}"); - } - let c16 = |r: u16, g: u16, b: u16| [r, g, b].map(|v| f32::from(v) / 32768.0); - for (c, level, white) in [ - (c16(8995, 7196, 6425), 60u8, false), - (c16(11180, 6554, 3984), 60, false), - (c16(16448, 16448, 16448), 128, true), - (c16(16447, 16447, 16447), 128, false), - ] { - assert_eq!(threshold_white(c, f32::from(level) / 255.0, Some(SampleType::U16)), white, "16-bit {c:?} at {level}"); - } - // Through the adjustment: neutral black or white. - let mut b = Buffer::filled(Rect::new(0, 0, 1, 1), [87.0 / 255.0, 51.0 / 255.0, 31.0 / 255.0, 1.0]); - apply_depth(&Adjustment::Threshold { level: 60.0 / 255.0 }, &mut b, Transfer::Srgb, Some(SampleType::U8)); - assert_eq!(b.px[0], [1.0, 1.0, 1.0, 1.0]); - } - - /// 16-bit sample → Photoshop's 8-bit level, from psd-tools posterize_16bits_rgb.psd: bins - /// split on the 16-bit sample (10794 and 10923 straddle a third of 32768), and the middle of 3 - /// levels is 128 where 8 bits give 127, while 21 levels keep 25 for 25.5. - #[test] - fn sixteen_bit_posterize_matches_photoshop() { - let points: [(u32, u16, u8); 9] = - [(3, 10794, 0), (3, 10923, 128), (3, 21845, 128), (3, 21974, 255), (13, 2504, 0), (13, 2542, 21), (13, 7453, 42), (13, 7582, 64), (21, 3341, 25)]; - for (levels, x, want) in points { - let got = posterize_in(f32::from(x) / 32768.0, levels, Some(SampleType::U16)); - assert!((got * 255.0 - f32::from(want)).abs() < 1e-3, "{levels} levels at {x}: {} vs Photoshop {want}", got * 255.0); - } - // 8 bits keep their rule. - assert_eq!(posterize_in(128.0 / 255.0, 3, Some(SampleType::U8)), posterize(128.0 / 255.0, 3)); - } - - #[test] - fn color_lookup_with_an_overflowing_stored_size_is_the_identity() { - // A stored document's size is untrusted: (2²²)³ × 3 overflows, which once wrapped past - // the table-length guard and indexed out of bounds. - for size in [1 << 22, u32::MAX] { - let a = Adjustment::ColorLookup { name: "x".into(), lut: Some(std::sync::Arc::new(vec![0.5; 24])), size, tetrahedral: false, dither: false }; - let mut b = ramp(); - apply(&a, &mut b); - assert_eq!(b.px, ramp().px, "size {size}"); - } - } - - /// Photoshop 27.11, measured: Color Balance with one cyan–red slider moved, over a gray ramp - /// (x = 0, 16, …, 240, 255); red and green out (blue follows green on gray). - #[test] - fn color_balance_matches_photoshop() { - const X: [u8; 17] = [0, 16, 32, 48, 64, 80, 96, 112, 128, 144, 160, 176, 192, 208, 224, 240, 255]; - type Row = (&'static str, f32, bool, [u8; 17], [u8; 17]); - let measured: [Row; 6] = [ - ("midtones", 50.0, false, [0, 36, 59, 78, 96, 112, 128, 142, 156, 170, 183, 196, 209, 221, 233, 244, 255], X), - ("shadows", -100.0, false, [0, 0, 0, 0, 0, 0, 0, 7, 23, 43, 67, 93, 122, 154, 186, 221, 255], X), - ("highlights", 100.0, false, [0, 51, 84, 111, 136, 160, 182, 202, 223, 242, 255, 255, 255, 255, 255, 255, 255], X), - ("shadows", 50.0, true, X, [0, 0, 0, 0, 17, 37, 57, 77, 97, 117, 137, 157, 177, 197, 216, 236, 255]), - ( - "midtones", - 100.0, - true, - [0, 36, 59, 78, 96, 112, 128, 142, 156, 170, 183, 196, 209, 221, 233, 244, 255], - [0, 5, 14, 24, 36, 50, 64, 80, 97, 114, 132, 151, 171, 191, 212, 234, 255], - ), - ("highlights", -100.0, true, X, [0, 26, 53, 79, 105, 132, 158, 184, 211, 237, 255, 255, 255, 255, 255, 255, 255]), - ]; - // Two sliders in one tone, Preserve Luminosity on (measured): shadows red and blue +50 darken - // only green; highlights red −50 with green +50 lift green by 100 and blue by 50. - let two = - |tones: [[f32; 3]; 3], x: f32| -> [i32; 3] { std::array::from_fn(|ch| (color_balance_channel(tones, true, ch, x / 255.0) * 255.0).round() as i32) }; - assert_eq!(two([[50.0, 0.0, 50.0], [0.0; 3], [0.0; 3]], 128.0), [128, 97, 128]); - let hi = two([[0.0; 3], [0.0; 3], [-50.0, 50.0, 0.0]], 128.0); - assert!((hi[0] - 128).abs() <= 1 && (hi[1] - 211).abs() <= 1 && (hi[2] - 159).abs() <= 1, "{hi:?}"); - for (tone, amount, preserve, red, green) in measured { - let mut tones = [[0.0f32; 3]; 3]; - tones[["shadows", "midtones", "highlights"].iter().position(|t| *t == tone).unwrap()][0] = amount; - for (i, x) in X.iter().enumerate() { - let v = f32::from(*x) / 255.0; - let got = |ch| (color_balance_channel(tones, preserve, ch, v) * 255.0).round() as i32; - let (r, g) = (got(0), got(1)); - assert!((r - i32::from(red[i])).abs() <= 1, "{tone} {amount} pl {preserve} at {x}: red {r} vs Photoshop {}", red[i]); - assert!((g - i32::from(green[i])).abs() <= 1, "{tone} {amount} pl {preserve} at {x}: green {g} vs Photoshop {}", green[i]); - } - } - } - - /// Photoshop, measured (8-bit gray ramp, every channel): whole settings, where the tones fold - /// into one Levels per channel (#3423). The issue's midtones red +100 / magenta −100 (the - /// shadow toe), its sequoia14 layer with Preserve Luminosity off and on, all nine sliders with - /// Preserve Luminosity on, a black point past the white point, and lowered shadows with raised - /// highlights (their gammas cancel: a straight line between the two points). - #[test] - fn color_balance_whole_settings_match_photoshop() { - const X: [u8; 12] = [0, 4, 8, 16, 32, 64, 96, 128, 160, 192, 224, 255]; - type Case = ([[f32; 3]; 3], bool, [[u8; 12]; 3]); - let cases: [Case; 6] = [ - ( - [[0.0; 3], [100.0, -100.0, 0.0], [0.0; 3]], - false, - [[0, 16, 30, 55, 90, 128, 156, 181, 202, 221, 239, 255], [0, 0, 0, 1, 4, 16, 36, 64, 100, 145, 197, 255], X], - ), - ( - [[-6.0, 22.0, 5.0], [-1.0, -3.0, -8.0], [-1.0, -4.0, -6.0]], - false, - [ - [0, 0, 2, 9, 25, 56, 89, 122, 156, 188, 222, 255], - [0, 5, 9, 18, 35, 67, 100, 131, 163, 194, 225, 255], - [0, 3, 7, 14, 29, 60, 91, 123, 156, 189, 222, 255], - ], - ), - ( - [[-6.0, 22.0, 5.0], [-1.0, -3.0, -8.0], [-1.0, -4.0, -6.0]], - true, - [ - [0, 0, 0, 0, 5, 42, 80, 117, 154, 189, 226, 255], - [0, 4, 8, 16, 33, 66, 98, 130, 162, 195, 226, 255], - [0, 0, 0, 0, 15, 48, 82, 116, 151, 186, 221, 255], - ], - ), - ( - [[40.0, -30.0, 20.0], [-50.0, 25.0, 60.0], [30.0, -70.0, 10.0]], - true, - [ - [0, 1, 3, 9, 25, 69, 126, 193, 255, 255, 255, 255], - [0, 0, 0, 0, 0, 0, 46, 93, 136, 177, 217, 255], - [0, 0, 0, 0, 44, 107, 156, 199, 238, 255, 255, 255], - ], - ), - ( - [[100.0, -100.0, 0.0], [0.0; 3], [-100.0, 100.0, 0.0]], - true, - [X, [0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255], [0, 0, 0, 0, 0, 0, 0, 130, 255, 255, 255, 255]], - ), - ( - [[-76.0, -2.0, 60.0], [0.0; 3], [99.0, 0.0, -30.0]], - false, - [ - [0, 0, 0, 0, 0, 0, 71, 171, 255, 255, 255, 255], - [0, 2, 6, 14, 29, 61, 94, 126, 158, 191, 224, 255], - [0, 6, 11, 21, 39, 73, 106, 137, 168, 197, 227, 255], - ], - ), - ]; - for (tones, preserve, want) in cases { - for (ch, row) in want.iter().enumerate() { - for (x, w) in X.iter().zip(row) { - let got = (color_balance_channel(tones, preserve, ch, f32::from(*x) / 255.0) * 255.0).round() as i32; - assert!((got - i32::from(*w)).abs() <= 1, "{tones:?} pl {preserve} ch {ch} at {x}: {got} vs Photoshop {w}"); - } - } - } - // Hostile input stays in range. - for v in [f32::NAN, -1.0, 2.0, f32::INFINITY] { - let out = color_balance_channel([[f32::NAN, 1e9, -1e9]; 3], true, 7, v); - assert!((0.0..=1.0).contains(&out), "{v}: {out}"); - } - } - - #[test] - fn color_balance_midtones_with_multiple_sliders_preserve_luminosity() { - // A shared offset depends on the two extremes, not the sum of moved sliders. - // The old per-slider product leaves red/blue unchanged for [30, 0, 30]. - let tones = [[0.0; 3], [30.0, 0.0, 30.0], [0.0; 3]]; - for input in [0.25_f32, 0.5, 0.75] { - for (ch, offset) in [-0.15_f32, 0.15, -0.15].into_iter().enumerate() { - let expected = input.powf(2f32.powf(offset)); - let actual = color_balance_channel(tones, true, ch, input); - assert!((actual - expected).abs() < 1e-6, "channel {ch}, input {input}: {actual} vs {expected}"); - } - // Preserve Luminosity off must still affect only the moved channels. - assert_eq!(color_balance_channel(tones, false, 1, input), input); - // One moved slider retains its previous half-strength compensation. - let single = [[0.0; 3], [30.0, 0.0, 0.0], [0.0; 3]]; - assert!((color_balance_channel(single, true, 0, input) - input.powf(2f32.powf(-0.15))).abs() < 1e-6); - assert!((color_balance_channel(single, true, 1, input) - input.powf(2f32.powf(0.15))).abs() < 1e-6); - } - } - - #[test] - fn color_balance_curve_matches_the_per_sample_formula_bitwise() { - // The curve works out its sample-independent terms once; this is the formula it replaced, - // evaluated whole for every sample. - fn per_sample(tones: [[f32; 3]; 3], preserve_luminosity: bool, ch: usize, v: f32) -> f32 { - let [shadows, midtones, highlights] = tones.map(|t| t.map(|s| if s.is_finite() { s.clamp(-100.0, 100.0) } else { 0.0 })); - let own = |t: [f32; 3]| t.get(ch).copied().unwrap_or(0.0); - let max = |t: [f32; 3]| t[0].max(t[1]).max(t[2]); - let min = |t: [f32; 3]| t[0].min(t[1]).min(t[2]); - let (black, white, m) = if preserve_luminosity { - (max(shadows) - own(shadows), own(highlights) - min(highlights), own(midtones) - (max(midtones) + min(midtones)) / 2.0) - } else { - ((-own(shadows)).max(0.0), own(highlights).max(0.0), own(midtones) + (own(shadows) + own(highlights)) / 2.0) - }; - let (b, w) = (black / 255.0, 1.0 - white / 255.0); - let v = if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }; - if v >= w { - return 1.0; - } - if v <= b { - return 0.0; - } - let (u, gamma) = ((v - b) / (w - b), 2f32.powf(m / 100.0)); - let e = 1.0 / gamma.max(0.01); - let power = u.powf(e); - if gamma <= 1.0 { - return power; - } - let s0 = 2f32.powf(gamma); - let u0 = (2.0 * s0.powf(1.0 / (e - 1.0))).min(1.0); - if u0.is_nan() || u0 <= 0.0 || u >= u0 { - return power; - } - let (p, d, t) = (u0.powf(e), e * u0.powf(e - 1.0), u / u0); - let (t2, t3) = (t * t, t * t * t); - ((t3 - 2.0 * t2 + t) * u0 * s0 + (3.0 * t2 - 2.0 * t3) * p + (t3 - t2) * u0 * d).clamp(0.0, 1.0) - } - let mut seed = 0x9e37_79b9_u32; - let mut slider = || { - seed ^= seed << 13; - seed ^= seed >> 17; - seed ^= seed << 5; - (seed % 241) as f32 - 120.0 - }; - let mut settings = vec![[[0.0; 3]; 3], [[f32::NAN, 1e9, -1e9]; 3], [[-100.0; 3], [100.0; 3], [100.0; 3]]]; - settings.extend((0..120).map(|_| std::array::from_fn(|_| std::array::from_fn(|_| slider())))); - let samples: Vec = (0..=1024).map(|i| i as f32 / 1024.0).chain([-0.5, 1.5, f32::NAN, f32::INFINITY]).collect(); - for tones in settings { - for preserve in [false, true] { - for ch in [0, 1, 2, 7] { - let curve = BalanceCurve::new(tones, preserve, ch); - for &v in &samples { - let (got, want) = (curve.eval(v), per_sample(tones, preserve, ch, v)); - assert_eq!(got.to_bits(), want.to_bits(), "{tones:?} {preserve} ch {ch} v {v}: {got} vs {want}"); - } - } - } - } - } - - #[test] - fn levels_and_curves_apply_each_channel_before_the_master() { - // These two affine tone adjustments describe the same mapping: - // channel(x) = 1 / 2 + x / 2, then master(x) = x / 2, so 0 maps to 0.25. - // Levels used to apply the master first (0 mapped to 0.5). - let line = |a: f32, b: f32| vec![CurvePoint { input: 0.0, output: a }, CurvePoint { input: 1.0, output: b }]; - let levels = Adjustment::Levels { - master: LevelsChannel { out_white: 0.5, ..Default::default() }, - per_channel: std::array::from_fn(|_| LevelsChannel { out_black: 0.5, ..Default::default() }), - space: ToneSpace::Rgb, - black: Default::default(), - }; - let curves = Adjustment::Curves { - master: line(0.0, 0.5), - per_channel: std::array::from_fn(|_| line(0.5, 1.0)), - space: ToneSpace::Rgb, - black: Vec::new(), - pencil: false, - }; - for depth in [None, Some(SampleType::U8), Some(SampleType::U16), Some(SampleType::F32)] { - let ll = tone_luts_depth(&levels, depth); - let cl = tone_luts_depth(&curves, depth); - for channel in 0..3 { - for index in [0, LUT_SIZE / 4, LUT_SIZE / 2, 3 * LUT_SIZE / 4, LUT_SIZE - 1] { - assert!( - (ll[channel][index] - cl[channel][index]).abs() < 0.01, - "{depth:?} channel {channel} sample {index}: Levels {} vs Curves {}", - ll[channel][index], - cl[channel][index] - ); - } - } - assert!((cl[0][0] - 0.25).abs() < 0.01, "{depth:?}: {}", cl[0][0]); - - // Exercise the compositor's real adjustment path, not only its LUT builder. - for adj in [&levels, &curves] { - let mut pixel = Buffer { rect: Rect::new(0, 0, 1, 1), px: vec![[0.0, 0.0, 0.0, 1.0]] }; - apply_depth(adj, &mut pixel, Transfer::Srgb, depth); - for channel in 0..3 { - assert!((pixel.px[0][channel] - 0.25).abs() < 0.01, "{depth:?}: {adj:?} rendered {:?}", pixel.px[0]); - } - } - } - - // Lab has no composite/master tone record. - let mut lab = curves.clone(); - let mut lab_without_master = curves; - if let Adjustment::Curves { space, .. } = &mut lab { - *space = ToneSpace::Lab; - } - if let Adjustment::Curves { master, space, .. } = &mut lab_without_master { - *space = ToneSpace::Lab; - *master = line(0.0, 1.0); - } - assert_eq!(tone_luts(&lab), tone_luts(&lab_without_master)); - } - - #[test] - fn identity_tone_in_every_space_is_identity() { - for space in [ToneSpace::Rgb, ToneSpace::Cmyk, ToneSpace::Lab] { - let mut a = Adjustment::identity_curves(); - if let Adjustment::Curves { space: s, .. } = &mut a { - *s = space; - } - let mut b = ramp(); - apply(&a, &mut b); - for (x, y) in b.px.iter().zip(ramp().px.iter()) { - for k in 0..3 { - assert!((x[k] - y[k]).abs() < 0.02, "{space:?} {x:?} {y:?}"); - } - } - } - } - - #[test] - fn cmyk_black_curve_darkens_and_lab_lightness_lifts() { - let line = |a: f32, b: f32| vec![CurvePoint { input: 0.0, output: a }, CurvePoint { input: 1.0, output: b }]; - // Black brightness 1 -> 0.5: more black ink everywhere. - let a = Adjustment::Curves { - master: line(0.0, 1.0), - per_channel: [line(0.0, 1.0), line(0.0, 1.0), line(0.0, 1.0)], - space: ToneSpace::Cmyk, - black: line(0.0, 0.5), - pencil: false, - }; - let mut b = Buffer { rect: Rect::new(0, 0, 1, 1), px: vec![[0.8, 0.8, 0.8, 1.0]] }; - apply(&a, &mut b); - assert!(b.px[0][0] < 0.7, "{:?}", b.px[0]); - // Lab lightness 0..1 -> 0.2..1 lifts a dark grey; a/b untouched keeps it grey. - let a = Adjustment::Curves { - master: line(1.0, 0.0), // ignored in Lab - per_channel: [line(0.2, 1.0), line(0.0, 1.0), line(0.0, 1.0)], - space: ToneSpace::Lab, - black: Vec::new(), - pencil: false, - }; - let mut b = Buffer { rect: Rect::new(0, 0, 1, 1), px: vec![[0.2, 0.2, 0.2, 1.0]] }; - apply(&a, &mut b); - let p = b.px[0]; - assert!(p[0] > 0.3 && (p[0] - p[2]).abs() < 0.02, "{p:?}"); - } - - #[test] - fn hue_ranges_only_touch_their_colours() { - let mut ranges = HueRange::defaults(); - ranges[0].saturation = -100.0; // desaturate reds - let a = Adjustment::HueSaturation { hue: 0.0, saturation: 0.0, lightness: 0.0, colorize: false, ranges }; - let mut b = Buffer { rect: Rect::new(0, 0, 3, 1), px: vec![[0.9, 0.1, 0.1, 1.0], [0.1, 0.1, 0.9, 1.0], [0.5, 0.5, 0.5, 1.0]] }; - apply(&a, &mut b); - let red = b.px[0]; - assert!((red[0] - red[1]).abs() < 0.05, "red desaturated {red:?}"); - assert!((b.px[1][2] - 0.9).abs() < 1e-4 && (b.px[1][0] - 0.1).abs() < 1e-4, "blue untouched {:?}", b.px[1]); - assert_eq!(b.px[2], [0.5, 0.5, 0.5, 1.0]); - } - - #[test] - fn colorize_at_zero_saturation_is_grey() { - // Photoshop: Colorize at 0% saturation leaves no colour, only the pixel's lightness (#2326). - let px = vec![[0.9, 0.2, 0.1, 1.0], [0.1, 0.6, 0.8, 1.0], [0.5, 0.5, 0.5, 1.0]]; - for depth in [None, Some(SampleType::U8), Some(SampleType::U16), Some(SampleType::F32)] { - for lightness in [0.0, 30.0, -30.0] { - let a = Adjustment::HueSaturation { hue: 200.0, saturation: 0.0, lightness, colorize: true, ranges: HueRange::defaults() }; - let mut b = Buffer { rect: Rect::new(0, 0, 3, 1), px: px.clone() }; - apply_depth(&a, &mut b, Transfer::Srgb, depth); - for p in &b.px { - assert!((p[0] - p[1]).abs() < 1e-4 && (p[1] - p[2]).abs() < 1e-4, "{depth:?} lightness {lightness}: {p:?}"); - } - } - // Low saturations still tint: the old 25% floor no longer hides them. - let tint = |saturation: f32| { - let a = Adjustment::HueSaturation { hue: 0.0, saturation, lightness: 0.0, colorize: true, ranges: HueRange::defaults() }; - let mut b = Buffer { rect: Rect::new(0, 0, 1, 1), px: vec![[0.5, 0.5, 0.5, 1.0]] }; - apply_depth(&a, &mut b, Transfer::Srgb, depth); - b.px[0][0] - b.px[0][2] - }; - assert!(tint(10.0) > 0.05 && tint(10.0) < tint(25.0), "{depth:?}: 10% {} vs 25% {}", tint(10.0), tint(25.0)); - } - } - - /// Photoshop 27.11, measured: Hue/Saturation raising saturation, and Colorize with Lightness. - #[test] - fn hue_saturation_matches_photoshop() { - // (input, hue, saturation, lightness, colorize, Photoshop's output) - type Case = ([u8; 3], f32, f32, f32, bool, [u8; 3]); - let measured: [Case; 8] = [ - ([204, 102, 102], 0.0, 50.0, 0.0, false, [254, 51, 51]), - ([204, 159, 102], 0.0, 50.0, 0.0, false, [254, 164, 51]), - ([204, 102, 102], 0.0, -50.0, 0.0, false, [178, 127, 127]), - ([0, 0, 0], 120.0, 100.0, 30.0, true, [0, 152, 0]), - ([28, 28, 28], 120.0, 100.0, 30.0, true, [0, 192, 0]), - ([160, 160, 160], 30.0, 25.0, -40.0, true, [120, 96, 73]), - ([252, 252, 252], 30.0, 25.0, -40.0, true, [177, 151, 126]), - ([255, 143, 0], 30.0, 25.0, -40.0, true, [95, 76, 58]), - ]; - for (input, hue, saturation, lightness, colorize, want) in measured { - let a = Adjustment::HueSaturation { hue, saturation, lightness, colorize, ranges: HueRange::defaults() }; - let c = input.map(|v| v as f32 / 255.0); - let mut b = Buffer { rect: Rect::new(0, 0, 1, 1), px: vec![[c[0], c[1], c[2], 1.0]] }; - apply(&a, &mut b); - for (i, w) in want.iter().enumerate() { - let got = b.px[0][i] * 255.0; - assert!((got - *w as f32).abs() <= 2.0, "{input:?} h{hue} s{saturation} l{lightness} colorize {colorize}, channel {i}: {got} vs {w}"); - } - } - } - - /// Photoshop 27.11, measured: a range's Lightness (Blues ±50) moves towards the brightest or darkest channel. - #[test] - fn range_lightness_matches_photoshop() { - let measured = [ - ([0u8, 29, 115], 0.5, [57u8, 71, 115]), - ([0, 64, 255], 0.5, [125, 157, 255]), - ([102, 128, 204], 0.5, [152, 165, 204]), - ([102, 128, 204], -0.5, [102, 115, 154]), - ([0, 18, 115], -0.5, [0, 9, 58]), - ]; - for (input, l, want) in measured { - let got = range_lightness(input.map(|v| v as f32 / 255.0), l); - for i in 0..3 { - assert!((got[i] * 255.0 - want[i] as f32).abs() <= 2.5, "{input:?} channel {i}: {} vs {}", got[i] * 255.0, want[i]); - } - } - } - - /// Photoshop's own render (merged image of psd-tools `adjustments/huesaturation_lightness_rgb.psd`, - /// layer "Hue/Saturation 1"): a dull magenta gets the whole range edit, as a vivid one does (#4089). - #[test] - fn hue_ranges_apply_in_full_to_dull_colours() { - let range = |lightness: f32, bounds: [f32; 4]| HueRange { hue: 0.0, saturation: 0.0, lightness, bounds }; - let ranges = [ - range(-11.0, [-57.0, 4.0, 82.0, 175.0]), - range(100.0, [12.0, 45.0, 75.0, 105.0]), - HueRange::neutral(2), - HueRange::neutral(3), - HueRange::neutral(4), - range(100.0, [-117.0, -50.0, 39.0, 104.0]), - ]; - let a = Adjustment::HueSaturation { hue: 0.0, saturation: 0.0, lightness: 17.0, colorize: false, ranges }; - let measured = [([126u8, 97, 120], [148u8, 148, 148]), ([131, 103, 125], [152, 152, 152]), ([95, 69, 90], [122, 122, 122])]; - for (input, want) in measured { - let c = input.map(|v| v as f32 / 255.0); - let mut b = Buffer { rect: Rect::new(0, 0, 1, 1), px: vec![[c[0], c[1], c[2], 1.0]] }; - apply(&a, &mut b); - for (i, w) in want.iter().enumerate() { - let got = b.px[0][i] * 255.0; - assert!((got - *w as f32).abs() <= 2.0, "{input:?} channel {i}: {got} vs {w}"); - } - } - // Greys have no hue, so the ranges leave them alone: only the master Lightness moves them. - let mut b = Buffer { rect: Rect::new(0, 0, 1, 1), px: vec![[0.4, 0.4, 0.4, 1.0]] }; - apply(&a, &mut b); - let p = b.px[0]; - assert!((p[0] - p[1]).abs() < 1e-6 && (p[1] - p[2]).abs() < 1e-6 && (p[0] - (0.4 + 0.6 * 0.17)).abs() < 1e-4, "{p:?}"); - } - - #[test] - fn black_white_weights() { - let d = [40.0, 60.0, 40.0, 60.0, 20.0, 80.0]; - assert!((black_white_gray([0.5; 3], &d) - 0.5).abs() < 1e-6, "greys keep their value"); - assert!((black_white_gray([1.0, 0.0, 0.0], &d) - 0.4).abs() < 1e-6); - assert!((black_white_gray([1.0, 1.0, 0.0], &d) - 0.6).abs() < 1e-6); - let mut w = d; - w[0] = 100.0; - assert!(black_white_gray([1.0, 0.0, 0.0], &w) > black_white_gray([1.0, 0.0, 0.0], &d)); - } - - /// #8537: 32-bit superwhites stay above 1 (Photoshop 27.11: 2.0 stays 2.0, neutrals cap at - /// 16, negatives go to 0); 8-bit still clips at 1. - #[test] - fn black_white_keeps_32_bit_superwhites() { - let adj = Adjustment::BlackWhite { weights: [40.0, 60.0, 40.0, 60.0, 20.0, 80.0], tint: None }; - let run = |depth, c: f32| { - let mut b = Buffer { rect: Rect::new(0, 0, 1, 1), px: vec![[c, c, c, 1.0]] }; - apply_depth(&adj, &mut b, Transfer::Srgb, Some(depth)); - b.px[0][0] - }; - assert_eq!(run(SampleType::F32, 2.0), 2.0); - assert_eq!(run(SampleType::F32, 20.0), 16.0); - assert_eq!(run(SampleType::F32, -0.5), 0.0); - assert_eq!(run(SampleType::U8, 2.0), 1.0); - } - - /// Photoshop 27.11, measured: Black & White (default weights) with Tint over greys. The tint - /// is blended like the Color blend mode: its hue and saturation at the grey's luminosity. - #[test] - fn black_white_tint_matches_photoshop() { - let weights = [40.0, 60.0, 40.0, 60.0, 20.0, 80.0]; - let measured: [([u8; 3], u8, [u8; 3]); 6] = [ - ([255, 0, 0], 24, [81, 1, 1]), - ([255, 0, 0], 120, [255, 64, 64]), - ([255, 0, 0], 240, [255, 235, 235]), - ([0xe1, 0xd3, 0xb3], 120, [133, 119, 87]), - ([0xe1, 0xd3, 0xb3], 24, [33, 24, 1]), - ([0x40, 0x20, 0x10], 120, [144, 112, 96]), - ]; - for (tint, grey, want) in measured { - let tint = Some(tint.map(|v| v as f32 / 255.0)); - let mut b = Buffer { rect: Rect::new(0, 0, 1, 1), px: vec![[grey as f32 / 255.0; 4]] }; - b.px[0][3] = 1.0; - apply(&Adjustment::BlackWhite { weights, tint }, &mut b); - for (i, w) in want.iter().enumerate() { - let got = b.px[0][i] * 255.0; - assert!((got - *w as f32).abs() <= 2.5, "tint {tint:?} grey {grey} channel {i}: {got} vs {w}"); - } - } - } - - #[test] - fn gradient_map_follows_the_w3c_luminosity() { - // Photoshop's Gradient Map is driven by 0.3 R + 0.59 G + 0.11 B (photoshop corpus rgb8 and - // rgb16 gradient-map.psd), not the Rec. 601 grey. - let stops = vec![(0.0, [0.0; 3]), (1.0, [1.0; 3])]; - for (c, t) in [([0.0, 1.0, 0.0], 0.59), ([1.0, 0.0, 0.0], 0.3), ([0.0, 0.0, 1.0], 0.11), ([0.2, 0.6, 0.9], 0.513)] { - let mut b = Buffer::filled(crate::Rect::new(0, 0, 1, 1), [c[0], c[1], c[2], 1.0]); - apply(&Adjustment::GradientMap { stops: stops.clone(), reverse: false, dither: false }, &mut b); - assert!((b.px[0][0] - t).abs() < 1e-5, "{c:?}: {}", b.px[0][0]); - } - } - - #[test] - fn gradient_map_dither_stays_close() { - let stops = vec![(0.0, [0.0; 3]), (1.0, [1.0; 3])]; - let mut a = ramp(); - let mut b = ramp(); - apply(&Adjustment::GradientMap { stops: stops.clone(), reverse: false, dither: false }, &mut a); - apply(&Adjustment::GradientMap { stops, reverse: false, dither: true }, &mut b); - assert!(a.px.iter().zip(&b.px).all(|(x, y)| (x[0] - y[0]).abs() <= 0.5 / 255.0 + 1e-6)); - assert!(a.px.iter().zip(&b.px).any(|(x, y)| x[0] != y[0])); - } - - /// `adj` applied in a Lab document to one encoded sRGB colour, returned as (L, a, b). - fn in_lab(adj: &Adjustment, c: [f32; 3]) -> [f32; 3] { - let mut b = Buffer::filled(crate::Rect::new(0, 0, 1, 1), [c[0], c[1], c[2], 1.0]); - apply_in(adj, &mut b, Transfer::Srgb, Some(SampleType::U8), ColorMode::Lab); - srgb_to_lab([b.px[0][0], b.px[0][1], b.px[0][2]]) - } - - /// A muted, in-gamut colour from (L, a, b). - fn lab(l: f32, a: f32, b: f32) -> [f32; 3] { - lab_to_srgb([l, a, b]) - } - - fn near(got: [f32; 3], want: [f32; 3], tol: f32) -> bool { - got.iter().zip(want).all(|(g, w)| (g - w).abs() <= tol) - } - - #[test] - fn lab_invert_flips_l_a_and_b() { - let got = in_lab(&Adjustment::Invert, lab(30.0, 12.0, -18.0)); - // n -> 1 - n: L -> 100 - L, a -> -a - 1, b -> -b - 1 (mirrored on the 0..255 grid). - assert!(near(got, [70.0, -13.0, 17.0], 0.6), "{got:?}"); - // On the screen colour it would not be a mirror in Lab. - let mut rgb = Buffer::filled(crate::Rect::new(0, 0, 1, 1), [0.0, 0.0, 0.0, 1.0]); - let c = lab(30.0, 12.0, -18.0); - rgb.px[0] = [c[0], c[1], c[2], 1.0]; - apply(&Adjustment::Invert, &mut rgb); - assert!(!near(srgb_to_lab([rgb.px[0][0], rgb.px[0][1], rgb.px[0][2]]), got, 1.0)); - } - - #[test] - fn sixteen_bit_lab_invert_keeps_greys_neutral() { - // 16-bit Lab Invert mirrors a and b around neutral (photoshop corpus lab16 invert.psd); - // 8-bit bytes land one step off it. - let mut b = Buffer::filled(crate::Rect::new(0, 0, 1, 1), [0.0, 0.0, 0.0, 1.0]); - let c = lab(40.0, 0.0, 0.0); - b.px[0] = [c[0], c[1], c[2], 1.0]; - apply_in(&Adjustment::Invert, &mut b, Transfer::Srgb, Some(SampleType::U16), ColorMode::Lab); - let got = srgb_to_lab([b.px[0][0], b.px[0][1], b.px[0][2]]); - assert!(near(got, [60.0, 0.0, 0.0], 0.05), "{got:?}"); - assert!(near(in_lab(&Adjustment::Invert, c), [60.0, -1.0, -1.0], 0.1)); - } - - /// `adj` applied in a CMYK document to one encoded sRGB colour. - fn in_cmyk(adj: &Adjustment, c: [f32; 3]) -> [f32; 3] { - let mut b = Buffer::filled(crate::Rect::new(0, 0, 1, 1), [c[0], c[1], c[2], 1.0]); - apply_in(adj, &mut b, Transfer::Srgb, Some(SampleType::U8), ColorMode::Cmyk); - [b.px[0][0], b.px[0][1], b.px[0][2]] - } - - #[test] - fn cmyk_invert_posterize_and_threshold_work_on_the_inks() { - use photocraft_color::convert::{cmyk_to_rgb, rgb_to_cmyk}; - // Paper inverts to all four inks at 100%, not to RGB black (photoshop corpus cmyk8 invert.psd). - assert!(near(in_cmyk(&Adjustment::Invert, [1.0; 3]), cmyk_to_rgb([1.0; 4]), 2e-3)); - let red = [0.9, 0.2, 0.1]; - assert!(near(in_cmyk(&Adjustment::Invert, red), cmyk_to_rgb(rgb_to_cmyk(red).map(|v| 1.0 - v)), 2e-3)); - let two = cmyk_to_rgb(rgb_to_cmyk(red).map(|v| if v >= 0.5 { 1.0 } else { 0.0 })); - assert!(near(in_cmyk(&Adjustment::Posterize { levels: 2 }, red), two, 2e-3)); - // Threshold's black is the black ink alone (threshold-128.psd), its white the paper. - let t = Adjustment::Threshold { level: 0.5 }; - assert!(near(in_cmyk(&t, [0.2; 3]), cmyk_to_rgb([0.0, 0.0, 0.0, 1.0]), 2e-3)); - assert!(near(in_cmyk(&t, [0.8; 3]), cmyk_to_rgb([0.0; 4]), 2e-3)); - } - - /// CMYK posterizes the stored value 1 - ink: with 3 levels an ink of 85 (stored 170) lands on - /// the middle step, 128 (stored 127), where posterizing the ink would drop it to none (psd-tools - /// posterize_cmyk.psd, levels 3 to 21, exact so). - #[test] - fn cmyk_posterize_works_on_the_stored_values() { - let mut ink = [85.0 / 255.0; 4]; - stored_channels(&Adjustment::Posterize { levels: 3 }, ColorMode::Cmyk, Some(SampleType::U8), &mut ink); - assert!(ink.iter().all(|v| (v * 255.0 - 128.0).abs() < 1e-3), "{ink:?}"); - assert_eq!(posterize(85.0 / 255.0, 3), 0.0, "posterizing the ink itself"); - } - - #[test] - fn cmyk_threshold_compares_the_inks_plain_luma() { - assert_eq!(ink_luma([0.0; 4]), 1.0); - assert_eq!(ink_luma([0.0, 0.0, 0.0, 1.0]), 0.0); - // Two greys either side of level 128 in photoshop corpus cmyk8 threshold-128.psd: black, - // then white (8-bit inks). - let at = |i: [f32; 4]| { - let mut ch = i.map(|v| v / 255.0); - stored_channels(&Adjustment::Threshold { level: 128.0 / 255.0 }, ColorMode::Cmyk, Some(SampleType::U8), &mut ch); - ch - }; - assert_eq!(at([144.0, 122.0, 121.0, 35.0]), [0.0, 0.0, 0.0, 1.0]); - assert_eq!(at([131.0, 110.0, 110.0, 19.0]), [0.0; 4]); - } - - #[test] - fn cmyk_brightness_contrast_curves_each_ink_from_paper() { - use photocraft_color::convert::{cmyk_to_rgb, rgb_to_cmyk}; - // The tone curve runs on each ink's stored value, 1 - ink (photoshop corpus cmyk8 - // brightness-contrast.psd and -legacy.psd): raising brightness takes ink away, and paper - // and solid ink stay put. - let red = [0.9, 0.2, 0.1]; - for legacy in [false, true] { - let adj = Adjustment::BrightnessContrast { brightness: 25.0, contrast: 30.0, legacy }; - let table = ink_brightness_contrast_lut(25.0, 30.0, legacy); - let want = cmyk_to_rgb(rgb_to_cmyk(red).map(|v| 1.0 - lut(&table, 1.0 - v))); - assert!(near(in_cmyk(&adj, red), want, 2e-3), "legacy {legacy}"); - assert!(near(in_cmyk(&adj, [1.0; 3]), [1.0; 3], 2e-3), "legacy {legacy}: paper"); - let solid = cmyk_to_rgb([1.0; 4]); - assert!(near(in_cmyk(&adj, solid), cmyk_to_rgb(rgb_to_cmyk(solid).map(|v| ink_through(&table, v))), 2e-3)); - } - // Legacy +25 / +30 on Photoshop's own 16-bit inks (photoshop corpus cmyk16 - // brightness-contrast-legacy.psd): contrast pivots at 128 in ink, 127 stored. - let legacy = ink_brightness_contrast_lut(25.0, 30.0, true); - for (ink, ps) in [(139.0, 108.0), (160.0, 137.99), (172.0, 155.13), (183.0, 170.85), (196.0, 189.42), (98.0, 49.42), (128.0, 92.28), (168.0, 149.42)] { - let got = ink_through(&legacy, ink / 255.0) * 255.0; - assert!((got - ps).abs() < 0.1, "ink {ink}: {got} vs Photoshop {ps}"); - } - let brighter = Adjustment::BrightnessContrast { brightness: 60.0, contrast: 0.0, legacy: false }; - let ink = ink_brightness_contrast_lut(60.0, 0.0, false); - assert!(ink_through(&ink, 0.5) < 0.5 && ink_through(&ink, 0.0) == 0.0 && (ink_through(&ink, 1.0) - 1.0).abs() < 1e-6); - // On the screen colour it would land elsewhere. - let mut rgb = Buffer::filled(crate::Rect::new(0, 0, 1, 1), [red[0], red[1], red[2], 1.0]); - apply(&brighter, &mut rgb); - assert!(!near(in_cmyk(&brighter, red), [rgb.px[0][0], rgb.px[0][1], rgb.px[0][2]], 0.01)); - } - - #[test] - fn lab_posterize_steps_l_a_and_b() { - let got = in_lab(&Adjustment::Posterize { levels: 2 }, lab(70.0, 20.0, -30.0)); - // Two levels: each normalised channel snaps to 0 or 1 (L 100, a and b at +127 / -128). - assert!(near(got, srgb_to_lab(lab_denorm([1.0, 1.0, 0.0])), 1e-3), "{got:?}"); - let grey = in_lab(&Adjustment::Posterize { levels: 255 }, lab(50.0, 0.0, 0.0)); - assert!(near(grey, [50.0, 0.0, 0.0], 1.1), "255 levels is within a step of the identity: {grey:?}"); - } - - #[test] - fn lab_threshold_splits_on_l_with_a_neutral_result() { - let t = Adjustment::Threshold { level: 0.5 }; - // A saturated blue (L ≈ 32) and yellow (L ≈ 97): black and white, nothing in between. - for (c, white) in [([0.0, 0.0, 1.0], false), ([1.0, 1.0, 0.0], true), (lab(52.0, 40.0, 30.0), true), (lab(48.0, -40.0, 30.0), false)] { - let mut b = Buffer::filled(crate::Rect::new(0, 0, 1, 1), [c[0], c[1], c[2], 1.0]); - apply_in(&t, &mut b, Transfer::Srgb, None, ColorMode::Lab); - let v = if white { 1.0 } else { 0.0 }; - assert_eq!(b.px[0], [v, v, v, 1.0], "{c:?}"); - } - } - - #[test] - fn lab_brightness_contrast_moves_l_only() { - for legacy in [false, true] { - let adj = Adjustment::BrightnessContrast { brightness: 40.0, contrast: 30.0, legacy }; - let before = [45.0, 15.0, -20.0]; - let got = in_lab(&adj, lab(before[0], before[1], before[2])); - assert!(got[0] > before[0] + 5.0, "{legacy}: L rises: {got:?}"); - assert!((got[1] - before[1]).abs() < 0.5 && (got[2] - before[2]).abs() < 0.5, "{legacy}: a, b kept: {got:?}"); - } - } - - #[test] - fn lab_gradient_map_follows_l() { - let stops = vec![(0.0, [1.0, 0.0, 0.0]), (1.0, [0.0, 0.0, 1.0])]; - for reverse in [false, true] { - let map = Adjustment::GradientMap { stops: stops.clone(), reverse, dither: false }; - // A grey and a saturated colour with the same L map to the same colour. - let grey = in_lab(&map, lab(60.0, 0.0, 0.0)); - let green = in_lab(&map, lab(60.0, -50.0, 40.0)); - assert!(near(grey, green, 1e-3), "{reverse}: {grey:?} vs {green:?}"); - let t = if reverse { 0.4 } else { 0.6 }; - let want = srgb_to_lab([1.0 - t, 0.0, t]); - assert!(near(grey, want, 0.05), "{reverse}: {grey:?} vs {want:?}"); - } - } - - #[test] - fn other_modes_and_adjustments_keep_the_screen_colour_path() { - let c = [0.2, 0.5, 0.7, 1.0]; - let lab_only = [Adjustment::Invert, Adjustment::Threshold { level: 0.47 }, Adjustment::Posterize { levels: 4 }]; - for adj in - lab_only.iter().chain([&Adjustment::HueSaturation { hue: 30.0, saturation: 0.0, lightness: 0.0, colorize: false, ranges: HueRange::defaults() }]) - { - for mode in [ColorMode::Rgb, ColorMode::Cmyk, ColorMode::Grayscale, ColorMode::Lab] { - let (mut a, mut b) = (Buffer::filled(crate::Rect::new(0, 0, 1, 1), c), Buffer::filled(crate::Rect::new(0, 0, 1, 1), c)); - apply_in(adj, &mut a, Transfer::Srgb, None, mode); - apply_depth(adj, &mut b, Transfer::Srgb, None); - let own = (mode == ColorMode::Lab && lab_channel_adjustment(adj)) || (mode == ColorMode::Cmyk && cmyk_channel_adjustment(adj)); - assert_eq!(a.px == b.px, !own, "{adj:?} in {mode:?}"); - } - } - // Transparent pixels are left alone and odd values never panic. - let mut t = Buffer::filled(crate::Rect::new(0, 0, 2, 1), [f32::NAN, 2.0, -1.0, 0.0]); - for adj in lab_only.iter().chain([&Adjustment::GradientMap { stops: vec![], reverse: true, dither: true }]) { - for mode in [ColorMode::Lab, ColorMode::Cmyk] { - apply_in(adj, &mut t, Transfer::Srgb, None, mode); - let mut odd = Buffer::filled(crate::Rect::new(0, 0, 1, 1), [f32::NAN, f32::INFINITY, -3.0, 1.0]); - apply_in(adj, &mut odd, Transfer::Srgb, Some(SampleType::U16), mode); - } - } - assert!(t.px[0][1] == 2.0); - } -} +mod tone_tests; /// Legacy Brightness/Contrast scales contrast around 128 of 255 (contrast 80 keeps 128 at 128, /// measured on Photoshop 27.11; a 0.5 pivot moved it to 130). diff --git a/crates/compose/src/adjust/channels.rs b/crates/compose/src/adjust/channels.rs new file mode 100644 index 0000000000..4b7d42b92a --- /dev/null +++ b/crates/compose/src/adjust/channels.rs @@ -0,0 +1,278 @@ +use super::color::{bayer4, gradient}; +use super::tone::{LUT_SIZE, lut, map_rgb, modern_brightness, modern_contrast, modern_lut, posterize_in, tone_luts_depth}; +use super::*; + +/// Legacy Brightness/Contrast on a 32-bit document's samples: unclipped, with contrast pivoting at +/// 127 of 255 (photoshop corpus rgb32 and gray32 brightness-contrast-legacy.psd: every pixel +/// exact, negative and over-white values included; the 8/16-bit pivot, 128, is 0.43 of a level +/// off there). +pub(super) fn legacy_brightness_contrast_hdr(brightness: f32, contrast: f32) -> impl Fn(f32) -> f32 { + const PIVOT: f32 = 127.0 / 255.0; + let b = brightness / 255.0; + let c = contrast.clamp(-100.0, 99.0); + let k = if c >= 0.0 { 1.0 / (1.0 - c / 100.0) } else { 1.0 + c / 100.0 }; + let (pre, post) = if c >= 0.0 { (b, 0.0) } else { (0.0, b) }; + move |v: f32| (v + pre - PIVOT) * k + PIVOT + post +} + +/// Legacy Brightness/Contrast as one channel's tone curve (see [`apply_depth`]). +pub(super) fn legacy_brightness_contrast(brightness: f32, contrast: f32) -> impl Fn(f32) -> f32 { + legacy_brightness_contrast_at(brightness, contrast, LEGACY_PIVOT) +} + +/// [`legacy_brightness_contrast`] with contrast pivoting at `pivot`. +fn legacy_brightness_contrast_at(brightness: f32, contrast: f32, pivot: f32) -> impl Fn(f32) -> f32 { + let b = brightness / 255.0; + let c = contrast.clamp(-100.0, 99.0); + let k = if c >= 0.0 { 1.0 / (1.0 - c / 100.0) } else { 1.0 + c / 100.0 }; + let (pre, post) = if c >= 0.0 { (b, 0.0) } else { (0.0, b) }; + move |v: f32| ((v + pre - pivot) * k + pivot + post).clamp(0.0, 1.0) +} + +/// Whether Threshold at `level` turns colour `c` white in a document of `depth` (`None`: unknown, +/// treated as 8-bit). Photoshop splits on the luminosity 0.30 R + 0.59 G + 0.11 B (the blend +/// modes' `lum`), not the Rec. 601 grey, of the document's whole sample values: +/// - 8 bits: white when that luminosity, rounded to a level with halves down, reaches the level; +/// - 16 bits: white when it reaches the level converted to 16 bits (128 → 16448); +/// - 32 bits: white when it reaches the level. +/// +/// Exact on every pixel of psd-tools threshold_rgb.psd, threshold_16bits_rgb.psd and +/// threshold_16bits_grayscale.psd and of the photoshop corpus's rgb16 threshold-128.psd, where the +/// Rec. 601 grey split 28 and 100 pixels of the first two the other way. The sums of +/// `30 R + 59 G + 11 B` over whole samples are exact in f32 (at most 3 276 800). +pub fn threshold_white(c: [f32; 3], level: f32, depth: Option) -> bool { + let t = (level * 255.0).round(); + let sum = |q: f32| { + let [r, g, b] = c.map(|v| (v.clamp(0.0, 1.0) * q).round()); + 30.0 * r + 59.0 * g + 11.0 * b + }; + match depth { + None | Some(SampleType::U8) => sum(255.0) > 100.0 * t - 50.0, + Some(SampleType::U16) => sum(32768.0) >= 100.0 * (t * 32768.0 / 255.0).round(), + Some(SampleType::F32) => (0.3 * c[0] + 0.59 * c[1] + 0.11 * c[2]) * 255.0 >= t, + } +} + +/// Whether a Lab document evaluates `adj` on its L, a and b channels rather than on the screen +/// colour: Invert and Posterize (L, a and b alike), Brightness/Contrast (L only), Threshold +/// (split on L, neutral result) and Gradient Map (driven by L). Levels and Curves carry their own +/// Lab records ([`ToneSpace::Lab`]); everything else stays on the screen colour. +pub fn lab_channel_adjustment(adj: &Adjustment) -> bool { + matches!( + adj, + Adjustment::Invert + | Adjustment::Posterize { .. } + | Adjustment::Threshold { .. } + | Adjustment::BrightnessContrast { .. } + | Adjustment::GradientMap { .. } + ) +} + +/// Whether a CMYK document evaluates `adj` on its inks rather than on the screen colour: Invert +/// and Posterize (each ink, black included, so paper inverts to 400% ink), Threshold (paper or +/// 100% black ink alone) and Brightness/Contrast (each ink's stored value, 1 - ink, through the +/// tone curve; see [`ink_through`]). Photoshop corpus cmyk8 and cmyk16 invert, posterize-4, +/// threshold-128 and brightness-contrast(-legacy) follow these rules on the files' own inks on +/// every pixel; here the inks are the screen colour separated through the document's CMYK +/// profile, so neutrals carry the black that profile generates rather than the file's. +pub fn cmyk_channel_adjustment(adj: &Adjustment) -> bool { + stored_channel_adjustment(adj) || cmy_adjustment(adj) || matches!(adj, Adjustment::BrightnessContrast { .. }) +} + +/// Whether a CMYK document evaluates `adj` on C, M and Y as the complement of an RGB colour, +/// black kept ([`apply_cmy`]): Hue/Saturation (not Colorize, which Photoshop separates again, +/// black and all) and Color Balance (photoshop corpus cmyk16 hue-saturation.psd follows this on +/// every pixel within half a level, cmyk8 within two; color-balance within our RGB Color +/// Balance's own error). +pub fn cmy_adjustment(adj: &Adjustment) -> bool { + matches!(adj, Adjustment::HueSaturation { colorize: false, .. } | Adjustment::ColorBalance { .. }) +} + +/// A [`cmy_adjustment`] on straight inks (C, M, Y, K; 0 none): the RGB adjustment on +/// `(1 - c, 1 - m, 1 - y)`, black left alone. +pub fn apply_cmy(adj: &Adjustment, inks: &mut [[f32; 4]]) { + let width = i32::try_from(inks.len()).unwrap_or(i32::MAX); + let mut buf = Buffer { rect: crate::Rect::new(0, 0, width, 1), px: inks.iter().map(|i| [1.0 - i[0], 1.0 - i[1], 1.0 - i[2], 1.0]).collect() }; + apply_depth(adj, &mut buf, Transfer::Srgb, None); + for (ink, p) in inks.iter_mut().zip(&buf.px) { + for c in 0..3 { + ink[c] = (1.0 - p[c]).clamp(0.0, 1.0); + } + } +} + +/// Brightness/Contrast as the lookup table (4096 samples over 0..1) a CMYK ink's stored value, +/// `1 - ink`, goes through ([`ink_through`]): [`modern_lut`], or the legacy linear curve with its +/// contrast pivoting at 128 in ink, which is 127 of 255 stored (photoshop corpus cmyk16 +/// brightness-contrast-legacy.psd sits 0.43 of a level off around 128 stored, as a one-level +/// pivot shift times contrast +30's slope predicts). +pub fn ink_brightness_contrast_lut(brightness: f32, contrast: f32, legacy: bool) -> Vec { + if !legacy { + return modern_lut(brightness, contrast); + } + let curve = legacy_brightness_contrast_at(brightness, contrast, 1.0 - LEGACY_PIVOT); + (0..LUT_SIZE).map(|k| curve(k as f32 / (LUT_SIZE - 1) as f32)).collect() +} + +/// One CMYK ink (0: none) through a channel tone curve the way Photoshop applies one in CMYK: to +/// the stored value, `1 - ink`, so raising brightness takes ink away. +pub fn ink_through(table: &[f32], ink: f32) -> f32 { + 1.0 - lut(table, 1.0 - ink) +} + +/// Whether [`stored_channels`] evaluates `adj`: Invert, Posterize and Threshold. +pub fn stored_channel_adjustment(adj: &Adjustment) -> bool { + matches!(adj, Adjustment::Invert | Adjustment::Posterize { .. } | Adjustment::Threshold { .. }) +} + +/// Invert, Posterize or Threshold on one pixel's own channels in a Lab or CMYK document of +/// `depth` (`None`: unknown, treated as 8-bit): `ch` holds L, a, b normalised as [`lab_norm`] +/// gives them, or the C, M, Y, K inks (0: none). Lab Invert turns 8-bit bytes `v` into `255 - v` +/// (a becomes -1 - a) and mirrors a and b around neutral at 16 bits (photoshop corpus lab16 +/// invert.psd: neutral stays neutral). CMYK Threshold compares [`ink_luma`]. +pub fn stored_channels(adj: &Adjustment, mode: ColorMode, depth: Option, ch: &mut [f32]) { + let lab = mode == ColorMode::Lab; + match adj { + Adjustment::Invert => { + let mirror = if lab && depth.is_some_and(|d| d != SampleType::U8) { 256.0 / 255.0 } else { 1.0 }; + for (i, v) in ch.iter_mut().enumerate() { + *v = if i > 0 { mirror } else { 1.0 } - v.clamp(0.0, 1.0); + } + } + // CMYK posterizes the stored values (1 - ink), which its uneven levels make differ from + // posterizing the ink: psd-tools posterize_cmyk.psd (3 to 21 levels) is exact so. + Adjustment::Posterize { levels } if mode == ColorMode::Cmyk => ch.iter_mut().for_each(|v| *v = 1.0 - posterize_in(1.0 - *v, *levels, depth)), + Adjustment::Posterize { levels } => ch.iter_mut().for_each(|v| *v = posterize_in(*v, *levels, depth)), + Adjustment::Threshold { level } => { + // On the 8-bit grid, like the RGB threshold. + let t = (level * 255.0).round(); + let out = if lab { + let white = ch.first().is_some_and(|l| (l.clamp(0.0, 1.0) * 255.0).round() >= t); + [if white { 1.0 } else { 0.0 }, 128.0 / 255.0, 128.0 / 255.0, 0.0] + } else { + let ink = |i: usize| ch.get(i).copied().unwrap_or(0.0); + let black = (ink_luma([ink(0), ink(1), ink(2), ink(3)]) * 255.0).round() < t; + [0.0, 0.0, 0.0, if black { 1.0 } else { 0.0 }] + }; + ch.iter_mut().zip(out).for_each(|(v, o)| *v = o); + } + _ => {} + } +} + +/// The luma Photoshop's CMYK Threshold compares: Rec. 601 weights on the inks' plain complement, +/// `(1 - c)(1 - k)` and so on, whatever the document's profile (photoshop corpus cmyk8 and cmyk16 +/// threshold-128.psd: every pixel on the right side of level 128). +pub fn ink_luma(ink: [f32; 4]) -> f32 { + let paper = 1.0 - ink[3].clamp(0.0, 1.0); + rgb_to_gray([0, 1, 2].map(|i| (1.0 - ink[i].clamp(0.0, 1.0)) * paper)) +} + +/// Encoded sRGB → Lab normalised the way Photoshop's channels hold it: L/100, (a+128)/255, +/// (b+128)/255. +fn lab_norm(c: [f32; 3]) -> [f32; 3] { + let l = srgb_to_lab(c); + [l[0] / 100.0, (l[1] + 128.0) / 255.0, (l[2] + 128.0) / 255.0] +} + +/// The inverse of [`lab_norm`]. +pub(super) fn lab_denorm(n: [f32; 3]) -> [f32; 3] { + lab_to_srgb([n[0] * 100.0, n[1] * 255.0 - 128.0, n[2] * 255.0 - 128.0]) +} + +/// Neutral a or b as Lab surfaces store it ((0 + 128) / 255). +pub const LAB_NEUTRAL: f32 = 128.0 / 255.0; + +/// An adjustment Photoshop evaluates on a Lab document's own channels, as an operation on one +/// pixel's stored L, a, b (normalised as Lab surfaces store them: L / 100, (a + 128) / 255, +/// (b + 128) / 255) in a document of `depth`: Invert and Posterize (each channel), Threshold +/// (split on L, neutral result), Brightness/Contrast (L) and Levels or Curves with Lab records. +/// `None` for any other adjustment. On the stored values colours outside the display gamut keep +/// theirs, where [`apply_in`] can only round-trip them through clipped display RGB. +pub fn lab_stored_op(adj: &Adjustment, depth: Option) -> Option> { + let op: LabOp<'_> = match adj { + Adjustment::Invert | Adjustment::Posterize { .. } => Box::new(move |ch: &mut [f32; 3]| stored_channels(adj, ColorMode::Lab, depth, ch)), + Adjustment::Threshold { level } => { + // Split on L on the 8-bit grid, like the display path (`apply_lab`). + let t = (level * 255.0).round(); + Box::new(move |ch: &mut [f32; 3]| { + let white = (ch[0].clamp(0.0, 1.0) * 255.0).round() >= t; + *ch = [if white { 1.0 } else { 0.0 }, LAB_NEUTRAL, LAB_NEUTRAL]; + }) + } + Adjustment::BrightnessContrast { brightness, contrast, legacy } => { + let (b, c, legacy) = (*brightness, *contrast, *legacy); + let legacy_curve = legacy_brightness_contrast(b, c); + Box::new(move |ch: &mut [f32; 3]| { + ch[0] = if legacy { legacy_curve(ch[0]) } else { modern_contrast(modern_brightness(ch[0], b), c).clamp(0.0, 1.0) }; + }) + } + Adjustment::Levels { space: ToneSpace::Lab, .. } | Adjustment::Curves { space: ToneSpace::Lab, .. } => { + let luts = tone_luts_depth(adj, depth); + Box::new(move |ch: &mut [f32; 3]| { + for (v, t) in ch.iter_mut().zip(&luts) { + *v = lut(t, *v); + } + }) + } + _ => return None, + }; + Some(op) +} + +/// One pixel's stored L, a, b through an adjustment ([`lab_stored_op`]). +pub type LabOp<'a> = Box; + +/// The Lab evaluation of a [`lab_channel_adjustment`] in a document of `depth` (no-op for any +/// other adjustment). +pub(super) fn apply_lab(adj: &Adjustment, buf: &mut Buffer, depth: Option) { + match adj { + // L → 100 - L and a, b mirrored about neutral; each channel posterized (see `stored_channels`). + Adjustment::Invert | Adjustment::Posterize { .. } => map_rgb(buf, |c| { + let mut n = lab_norm(c); + stored_channels(adj, ColorMode::Lab, depth, &mut n); + lab_denorm(n) + }), + Adjustment::Threshold { level } => { + // Split on L alone (on the 8-bit grid); the result is neutral black or white. + let t = (level * 255.0).round(); + map_rgb(buf, |c| [if (lab_norm(c)[0].clamp(0.0, 1.0) * 255.0).round() >= t { 1.0 } else { 0.0 }; 3]) + } + Adjustment::BrightnessContrast { brightness, contrast, legacy } => { + let legacy_curve = legacy_brightness_contrast(*brightness, *contrast); + let modern = (!*legacy).then(|| modern_lut(*brightness, *contrast)); + let curve = |v: f32| match &modern { + Some(table) => lut(table, v), + None => legacy_curve(v), + }; + // The tone curve on L only. Added as the difference of two round trips (like + // `tone_in_space`) so a and b, and colours a round trip moves, stay put. + map_rgb(buf, |c| { + let n = lab_norm(c); + let l = curve(n[0]); + if l == n[0] { + return c; + } + let (before, after) = (lab_denorm(n), lab_denorm([l, n[1], n[2]])); + std::array::from_fn(|i| (c[i] + after[i] - before[i]).clamp(0.0, 1.0)) + }) + } + Adjustment::GradientMap { stops, reverse, dither } => { + let (w, x0, y0) = (buf.rect.width().max(1) as usize, buf.rect.x0, buf.rect.y0); + for (i, p) in buf.px.iter_mut().enumerate() { + if p[3] <= 0.0 { + continue; + } + // Driven by L: equal lightness maps to the same stop colour whatever the chroma. + let l = lab_norm([p[0], p[1], p[2]])[0].clamp(0.0, 1.0); + let mut o = gradient(stops, if *reverse { 1.0 - l } else { l }); + if *dither { + let d = bayer4(x0 + (i % w) as i32, y0 + (i / w) as i32) / 255.0; + o = o.map(|v| (v + d).clamp(0.0, 1.0)); + } + p[..3].copy_from_slice(&o); + } + } + _ => {} + } +} diff --git a/crates/compose/src/adjust/color.rs b/crates/compose/src/adjust/color.rs new file mode 100644 index 0000000000..f47d1154f0 --- /dev/null +++ b/crates/compose/src/adjust/color.rs @@ -0,0 +1,482 @@ +use super::tone::LUT_SIZE; +use super::*; + +/// Hue/Saturation's range edits as three hue-indexed tables (hue shift in degrees, saturation and +/// lightness as fractions), sampled at hue `k / (len - 1)` turns. Ranges add up where they overlap. +pub fn hue_range_tables(ranges: &[HueRange; 6]) -> [Vec; 3] { + let at = |k: usize| { + let deg = k as f32 / (LUT_SIZE - 1) as f32 * 360.0; + ranges.iter().filter(|r| !r.is_neutral()).fold([0.0f32; 3], |acc, r| { + let w = r.weight(deg); + [acc[0] + w * r.hue, acc[1] + w * r.saturation / 100.0, acc[2] + w * r.lightness / 100.0] + }) + }; + let rows: Vec<[f32; 3]> = (0..LUT_SIZE).map(at).collect(); + std::array::from_fn(|i| rows.iter().map(|r| r[i]).collect()) +} + +/// Hue/Saturation's saturation `s` (-1..1) as [`hue_saturation`] takes it in a document of +/// `depth`. A 32-bit Colorize builds its colour with the saturation times `1 - |lightness|`: +/// the photoshop corpus's rgb32 hue-saturation-colorize.psd (Saturation 40, Lightness +5) has 0.95 +/// of the chroma at every lightness, and is exact so, where 8 and 16 bits keep the full saturation +/// (their oracles are exact without it). Only a raised Lightness is measured; a lowered one is +/// taken to scale the same way. +pub fn colorize_saturation(s: f32, lightness: f32, colorize: bool, depth: Option) -> f32 { + // Clamped here too: a PSD can store a saturation beyond ±100, and the GPU scales it unclamped. + if colorize && depth == Some(SampleType::F32) { s.clamp(-1.0, 1.0) * (1.0 - lightness.abs().min(1.0)) } else { s } +} + +/// One Hue/Saturation evaluation: hue shift in degrees, saturation and lightness in -1..=1. +/// Colorize sets the hue and saturation instead of shifting them; at 0% it leaves only the +/// lightness, as in Photoshop (#2326). Ticking Colorize in the dialog starts saturation at 25%. +pub fn hue_saturation(c: [f32; 3], hue: f32, s: f32, l: f32, colorize: bool) -> [f32; 3] { + hue_saturation_in(c, hue, s, l, colorize, None) +} + +/// [`hue_saturation`] in a document of `depth`. At 32 bits Photoshop doesn't clip the raised +/// saturation, so saturated colours leave 0..1 (red with Hue +40, Saturation +25, Lightness -10 +/// becomes (1.0477, 0.649, -0.1477)), and it scales each colour's chroma around its lightness by +/// [`hdr_saturation_factor`], so colours at or above lightness 1 keep their hue too: the photoshop +/// corpus's rgb32 hue-saturation.psd is exact so. +pub fn hue_saturation_in(c: [f32; 3], hue: f32, s: f32, l: f32, colorize: bool, depth: Option) -> [f32; 3] { + let hdr = depth == Some(SampleType::F32); + let lighten = |v: f32| if l > 0.0 { v + (1.0 - v) * l } else { v * (1.0 + l) }; + if colorize { + // Colorize builds the colour at the lightened (or darkened) lightness, so black with + // Lightness +30 becomes a 30 % lightness colour, not grey (measured in Photoshop 27.11). + let (_, _, ll) = rgb_to_hsl(c); + return hsl_to_rgb(hue.rem_euclid(360.0) / 360.0, s.abs().min(1.0), lighten(ll)); + } + // Photoshop applies Lightness first, then rotates the hue and scales the saturation of the + // result: Hue +40, Saturation +25, Lightness -10 turns (240, 160, 30) into (173, 243, 0), not + // (168, 230, 14) (Photoshop 27.11 corpus file adjustments/rgb8/hue-saturation). + let lc = c.map(lighten); + let (hh, ss, ll) = rgb_to_hsl(lc); + let hh = (hh + hue / 360.0).rem_euclid(1.0); + if hdr { + // The chroma, not the HSL saturation, whose `2 - max - min` divisor is 0 at lightness 1 + // and negative above it: (2, 0, 0) with Hue +40 becomes (2, 1.333, 0) in Photoshop. + let d = (lc[0].max(lc[1]).max(lc[2]) - lc[0].min(lc[1]).min(lc[2])) * hdr_saturation_factor(s); + return hue_rgb(hh, ll - d / 2.0, ll + d / 2.0); + } + // Raising saturation divides by 1 - s, lowering it multiplies by 1 + s: +50 % doubles it + // (measured in Photoshop 27.11); +100 % saturates any colour that has some. + let ss = if s > 0.0 { ss / (1.0 - s).max(1.0 / 512.0) } else { ss * (1.0 + s) }.clamp(0.0, 1.0); + hsl_to_rgb(hh, ss, ll) +} + +/// The factor 32-bit Hue/Saturation scales chroma by for saturation `s` (-1..1), as Photoshop +/// computes it (measured at every whole percent from -100 to +100 on a 32-bit document): lowering +/// cuts `s` to 1/256 steps, raising cuts it to 254 steps out of 255, takes 255 / (255 - steps) to +/// 1/256 and stops at 32767/256, so +25 % gives 340/256, +99 % 63.75 and +100 % 127.996. +/// compose.wgsl's Hue/Saturation does the same in whole numbers. +pub fn hdr_saturation_factor(s: f32) -> f32 { + // The 1e-4 keeps a master plus range sum on its step: -0.46 + 0.96 is 0.49999997 in f32. + let s = s.clamp(-1.0, 1.0); + if s <= 0.0 { + return 1.0 - (-s * 256.0 + 1e-4).floor() / 256.0; + } + let steps = (s * 254.0 + 1e-4).floor() as u32; + (65280 / 255u32.saturating_sub(steps).max(1)).min(32767) as f32 / 256.0 +} + +/// A colour range's Lightness, applied after the master edits. It moves each channel towards the +/// pixel's brightest channel when raised and towards its darkest when lowered, not towards white +/// or black: Blues +50 turns (0, 29, 115) into (57, 71, 115), Blues -50 turns (102, 128, 204) into +/// (102, 115, 153) (measured in Photoshop 27.11). +pub fn range_lightness(c: [f32; 3], l: f32) -> [f32; 3] { + let l = l.clamp(-1.0, 1.0); + let target = if l > 0.0 { c[0].max(c[1]).max(c[2]) } else { c[0].min(c[1]).min(c[2]) }; + c.map(|v| v + (target - v) * l.abs()) +} + +/// Black & White grey value. Each colour is the sum of a grey part (its smallest channel), a +/// secondary-colour part (yellow, cyan or magenta: middle − smallest) and a primary part (red, +/// green or blue: largest − middle); the sliders (percent, Photoshop defaults 40 60 40 60 20 80 for +/// reds, yellows, greens, cyans, blues, magentas) weight the two colour parts. Unclipped: the +/// document's depth decides the range. +pub fn black_white_gray(c: [f32; 3], weights: &[f32; 6]) -> f32 { + let (r, g, b) = (c[0], c[1], c[2]); + let (max, min) = (r.max(g).max(b), r.min(g).min(b)); + let mid = r + g + b - max - min; + // Primary: the largest channel; secondary: the two largest channels together. + let primary = if r >= g && r >= b { + 0 + } else if g >= b { + 2 + } else { + 4 + }; + let secondary = if b <= r && b <= g { + 1 // red + green = yellow + } else if r <= g { + 3 // green + blue = cyan + } else { + 5 // red + blue = magenta + }; + min + (mid - min) * weights[secondary] / 100.0 + (max - mid) * weights[primary] / 100.0 +} + +/// Ordered-dither offset in -0.5..0.5 (4×4 Bayer matrix) for document pixel (x, y). +pub fn bayer4(x: i32, y: i32) -> f32 { + const M: [f32; 16] = [0.0, 8.0, 2.0, 10.0, 12.0, 4.0, 14.0, 6.0, 3.0, 11.0, 1.0, 9.0, 15.0, 7.0, 13.0, 5.0]; + (M[((y & 3) * 4 + (x & 3)) as usize] + 0.5) / 16.0 - 0.5 +} + +/// Samples a 3D LUT (`n`³ RGB triplets, red fastest) at `c`, trilinear or tetrahedral. +pub fn lut3d_sample(lut: &[f32], n: usize, c: [f32; 3], tetrahedral: bool) -> [f32; 3] { + // A degenerate or short table can't be sampled: leave the colour alone. + if n < 2 || n.checked_pow(3).and_then(|c| c.checked_mul(3)).is_none_or(|len| lut.len() < len) { + return c; + } + let m = (n - 1) as f32; + let pos = c.map(|v| v.clamp(0.0, 1.0) * m); + let i0 = pos.map(|p| (p.floor() as usize).min(n - 2)); + let f: [f32; 3] = std::array::from_fn(|k| pos[k] - i0[k] as f32); + let at = |dr: usize, dg: usize, db: usize| -> [f32; 3] { + let idx = (((i0[2] + db) * n + i0[1] + dg) * n + i0[0] + dr) * 3; + [lut[idx], lut[idx + 1], lut[idx + 2]] + }; + let mix = |w: &[(f32, [f32; 3])]| -> [f32; 3] { std::array::from_fn(|k| w.iter().map(|(a, v)| a * v[k]).sum()) }; + let (fr, fg, fb) = (f[0], f[1], f[2]); + if tetrahedral { + let (c000, c111) = (at(0, 0, 0), at(1, 1, 1)); + if fr > fg { + if fg > fb { + mix(&[(1.0 - fr, c000), (fr - fg, at(1, 0, 0)), (fg - fb, at(1, 1, 0)), (fb, c111)]) + } else if fr > fb { + mix(&[(1.0 - fr, c000), (fr - fb, at(1, 0, 0)), (fb - fg, at(1, 0, 1)), (fg, c111)]) + } else { + mix(&[(1.0 - fb, c000), (fb - fr, at(0, 0, 1)), (fr - fg, at(1, 0, 1)), (fg, c111)]) + } + } else if fb > fg { + mix(&[(1.0 - fb, c000), (fb - fg, at(0, 0, 1)), (fg - fr, at(0, 1, 1)), (fr, c111)]) + } else if fb > fr { + mix(&[(1.0 - fg, c000), (fg - fb, at(0, 1, 0)), (fb - fr, at(0, 1, 1)), (fr, c111)]) + } else { + mix(&[(1.0 - fg, c000), (fg - fr, at(0, 1, 0)), (fr - fb, at(1, 1, 0)), (fb, c111)]) + } + } else { + let lerp = |a: [f32; 3], b: [f32; 3], t: f32| -> [f32; 3] { std::array::from_fn(|k| a[k] + (b[k] - a[k]) * t) }; + let c00 = lerp(at(0, 0, 0), at(1, 0, 0), fr); + let c10 = lerp(at(0, 1, 0), at(1, 1, 0), fr); + let c01 = lerp(at(0, 0, 1), at(1, 0, 1), fr); + let c11 = lerp(at(0, 1, 1), at(1, 1, 1), fr); + lerp(lerp(c00, c10, fg), lerp(c01, c11, fg), fb) + } +} + +/// Color Balance on channel `ch` (0 red, 1 green, 2 blue) of `v` (0..1); `tones` are the +/// shadows, midtones and highlights slider triples (cyan–red, magenta–green, yellow–blue, +/// −100..100). +/// +/// Reverse-engineered from Photoshop (a 16-bit gray ramp through every tone at ±10..±100, pairs of +/// tones, and random settings of all nine sliders, Preserve Luminosity on and off): the three +/// tones fold into one Levels per channel (input black point, input white point, midtone gamma), +/// within 0.8 of 255 everywhere. Folding matters: a lowered shadows and a raised highlights +/// slider cancel each other's gamma, which applying the tones one after another doesn't (#3423). +/// - Preserve Luminosity off: a slider only moves its own channel. Lowered shadows set the black +/// point to |shadows| levels, raised highlights set the white point to 255 − highlights levels, +/// and the gamma is 2^(m / 100) with m = midtones + (shadows + highlights) / 2. +/// - Preserve Luminosity on: each channel's black point is (max − own) shadows levels, its white +/// point 255 − (own − min) highlights levels, and m = own − (max + min) / 2 midtones. +/// +/// A gamma > 1 starts with slope 2^gamma at black (up to 18 of 255 brighter +/// near black without it). When the black point reaches the white point, input +/// at or above the white point is white and the rest black. +pub fn color_balance_channel(tones: [[f32; 3]; 3], preserve_luminosity: bool, ch: usize, v: f32) -> f32 { + BalanceCurve::new(tones, preserve_luminosity, ch).eval(v) +} + +/// One channel's Color Balance curve (see [`color_balance_channel`]), with the terms that don't +/// depend on the sample worked out once rather than per pixel. +pub struct BalanceCurve { + /// Input black and white points. + b: f32, + w: f32, + /// The power curve's exponent, 1 / gamma. + e: f32, + /// The Hermite join of a gamma > 1. + knee: Option, +} + +/// Where a gamma > 1 curve's Hermite join ends (`u0`), its starting slope 2^gamma (`s0`), and the +/// power curve's value (`p`) and slope (`d`) at `u0`. +#[derive(Clone, Copy)] +struct Knee { + u0: f32, + s0: f32, + p: f32, + d: f32, +} + +impl BalanceCurve { + /// The red, green and blue curves. + pub fn rgb(tones: [[f32; 3]; 3], preserve_luminosity: bool) -> [Self; 3] { + std::array::from_fn(|ch| Self::new(tones, preserve_luminosity, ch)) + } + + /// The curve of channel `ch` (0 red, 1 green, 2 blue) for the shadows, midtones and + /// highlights slider triples `tones`. + pub fn new(tones: [[f32; 3]; 3], preserve_luminosity: bool, ch: usize) -> Self { + let [shadows, midtones, highlights] = tones.map(|t| t.map(|s| if s.is_finite() { s.clamp(-100.0, 100.0) } else { 0.0 })); + let own = |t: [f32; 3]| t.get(ch).copied().unwrap_or(0.0); + let max = |t: [f32; 3]| t[0].max(t[1]).max(t[2]); + let min = |t: [f32; 3]| t[0].min(t[1]).min(t[2]); + let (black, white, m) = if preserve_luminosity { + (max(shadows) - own(shadows), own(highlights) - min(highlights), own(midtones) - (max(midtones) + min(midtones)) / 2.0) + } else { + ((-own(shadows)).max(0.0), own(highlights).max(0.0), own(midtones) + (own(shadows) + own(highlights)) / 2.0) + }; + // The midtone gamma of the channel's Levels: `u^(1/gamma)`, except that a gamma > 1 + // (which would start with infinite slope) starts at slope 2^gamma and joins the power + // curve in a cubic Hermite at twice the input where that line meets it (Photoshop, + // measured on a 16-bit ramp at gamma 1.07..2: within 0.02 of 255). + let gamma = 2f32.powf(m / 100.0); + let e = 1.0 / gamma.max(0.01); + let knee = if gamma > 1.0 { + let s0 = 2f32.powf(gamma); + let u0 = (2.0 * s0.powf(1.0 / (e - 1.0))).min(1.0); + (!u0.is_nan() && u0 > 0.0).then(|| Knee { u0, s0, p: u0.powf(e), d: e * u0.powf(e - 1.0) }) + } else { + None + }; + Self { b: black / 255.0, w: 1.0 - white / 255.0, e, knee } + } + + /// The curve at `v` (0..1). + pub fn eval(&self, v: f32) -> f32 { + let (b, w) = (self.b, self.w); + let v = if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }; + if v >= w { + return 1.0; + } + if v <= b { + return 0.0; + } + let u = (v - b) / (w - b); + match self.knee { + Some(Knee { u0, s0, p, d }) if u < u0 => { + let t = u / u0; + let (t2, t3) = (t * t, t * t * t); + ((t3 - 2.0 * t2 + t) * u0 * s0 + (3.0 * t2 - 2.0 * t3) * p + (t3 - t2) * u0 * d).clamp(0.0, 1.0) + } + _ => u.powf(self.e), + } + } +} + +/// How much a colour belongs to each Selective Color range: reds, yellows, greens, cyans, +/// blues, magentas (by chroma within the hue sector), whites, neutrals and blacks (by lightness). +pub fn selective_color_weights(c: [f32; 3]) -> [f32; 9] { + let max = c[0].max(c[1]).max(c[2]); + let min = c[0].min(c[1]).min(c[2]); + let mid = c[0] + c[1] + c[2] - max - min; + let top = |i: usize| if c[i] >= max { max - mid } else { 0.0 }; + let bottom = |i: usize| if c[i] <= min { mid - min } else { 0.0 }; + [ + top(0), + bottom(2), + top(1), + bottom(0), + top(2), + bottom(1), + ((min - 0.5) * 2.0).max(0.0), + (1.0 - (max - 0.5).abs() - (min - 0.5).abs()).clamp(0.0, 1.0), + ((0.5 - max) * 2.0).max(0.0), + ] +} + +/// Photoshop Selective Color: each range shifts the cyan, magenta and yellow ink (1 − R, G, B) by +/// its percentage, plus its black percentage on every ink, weighted by how much the colour belongs +/// to the range. Relative mode scales the shift by the ink already present (so it can't tint pure +/// white). Absolute mode scales it by the room the ink has: adding ink by min(1, 2 × (1 − ink)), +/// removing it by min(1, 2 × ink), so Neutrals Cyan +50 darkens red 64 by 32, not 64 (all 72 +/// absolute range × ink cases within 1 level of Photoshop 27.11). +pub fn selective_color(c: [f32; 3], relative: bool, adj: &[[f32; 4]; 9]) -> [f32; 3] { + let w = selective_color_weights(c); + let mut delta = [0.0f32; 3]; + for (r, wr) in w.iter().enumerate() { + if *wr <= 0.0 { + continue; + } + let a = adj[r].map(|v| v / 100.0); + for i in 0..3 { + let ink = 1.0 - c[i]; + let d = a[i] + a[3]; + let d = if relative { + d * ink + } else if d > 0.0 { + d * (2.0 * (1.0 - ink)).min(1.0) + } else { + d * (2.0 * ink).min(1.0) + }; + delta[i] += d * wr; + } + } + std::array::from_fn(|i| (c[i] - delta[i]).clamp(0.0, 1.0)) +} + +/// Photo Filter's linear-light RGB matrix. Photoshop multiplies the pixel's D50 XYZ, relative to +/// white, by the filter colour's (mixed in by `density`): a fixed linear map, so it is folded into +/// one matrix. With `normalize_y` the map keeps luminance Y (32-bit Preserve Luminosity; 8/16-bit +/// documents instead restore the encoded luminosity like the Luminosity blend mode). Fitted on the +/// photoshop corpus `photo-filter.psd`: rgb16 within 0.6/255 everywhere. +pub fn photo_filter_matrix(color: [f32; 3], density: f32, normalize_y: bool) -> [[f32; 3]; 3] { + let d = if density.is_finite() { density.clamp(0.0, 1.0) } else { 0.0 }; + let xyz = mat3_mul(&SRGB_TO_XYZ_D50, color.map(|v| srgb_to_linear(v.clamp(0.0, 1.0)))); + let mut s: [f32; 3] = std::array::from_fn(|i| 1.0 - d + d * xyz[i] / D50[i]); + if normalize_y && s[1] > 1e-6 { + let y = s[1]; + s = s.map(|v| v / y); + } + // XYZ_D50_TO_SRGB · diag(s) · SRGB_TO_XYZ_D50 + std::array::from_fn(|r| std::array::from_fn(|c| (0..3).map(|k| XYZ_D50_TO_SRGB[r][k] * s[k] * SRGB_TO_XYZ_D50[k][c]).sum())) +} + +/// Photoshop's Vibrance on one pixel (`v`, `s`: the sliders / 100; `hi`: the sample ceiling). +/// +/// Measured black-box against Photoshop 25.4 on 7,400-colour charts (8- and 16-bit; sRGB, Adobe RGB +/// and ProPhoto documents). Both sliders work in linear light through the document's tone curve, +/// Vibrance first, then Saturation: +/// - Saturation moves each colour away from (or towards) the grey `0.288 R + 0.712 G` (blue has no +/// weight, in every profile) by `1 + s`, clipping each channel: within 0.07/255 at every `s`. +/// - Vibrance is an HSV change in linear light that keeps the hue: see [`vibrance_lin`]. +pub fn vibrance_px(c: [f32; 3], v: f32, s: f32, transfer: Transfer, hi: f32) -> [f32; 3] { + let mut l = c.map(|x| transfer.decode(x)); + if v != 0.0 { + l = vibrance_lin(l, v); + } + if s != 0.0 { + let g = VIBRANCE_GREY[0] * l[0] + VIBRANCE_GREY[1] * l[1]; + l = l.map(|x| (g + (1.0 + s) * (x - g)).clamp(0.0, hi)); + } + l.map(|x| transfer.encode(x.clamp(0.0, hi))) +} + +/// Weights of the grey Photoshop's Vibrance › Saturation desaturates to (R, G; blue has none). +pub const VIBRANCE_GREY: [f32; 2] = [0.288, 0.712]; + +/// Positive Vibrance's saturation boost, fitted to the measurements (see [`vibrance_lin`]). +pub const VIBRANCE_BOOST: [f32; 7] = [0.5001, 0.0887, 0.4374, 0.7573, -0.8113, 0.5154, 2.8026]; + +/// The Vibrance slider (`v` in [-1, 1]) on a linear-light pixel. With `t = 1 - min/max` (HSV +/// saturation) and `V = max`: +/// - below 0 (`a = -v`): `t' = t (1 - a/4) (1 - a + a t (1 + t) / 2)` and +/// `V' = V - a t (1 - t) (2 - t + t²) V (1 - V)`; exact (0.2/255 mean) except in the deepest +/// shadows (`V` under 0.05), which Photoshop desaturates less. +/// - above 0: `V' = V + v/4 t (1 - t) (2 - t + t²) V (1 - V)` (exact) and a saturation boost that +/// grows as `t` and `V` fall, damped on reds and skin (HSV hue 0–30°, fading out by 45° and in +/// from 300°): a fit, 0.4 (+10) to 5 (+100) /255 off on average. +pub fn vibrance_lin(c: [f32; 3], v: f32) -> [f32; 3] { + let mx = c[0].max(c[1]).max(c[2]); + let mn = c[0].min(c[1]).min(c[2]); + if mx <= 0.0 || mx - mn <= 1e-9 { + return c; + } + let t = 1.0 - mn / mx; + let shape = t * (1.0 - t) * (2.0 - t + t * t) * mx * (1.0 - mx).max(0.0); + let (t2, v2) = if v < 0.0 { + let a = -v; + (t * (1.0 - a / 4.0) * (1.0 - a + a * t * (1.0 + t) / 2.0), mx - a * shape) + } else { + let [c0, c1, p, q, r0, ra, rt] = VIBRANCE_BOOST; + let w = vibrance_skin(hsv_hue(c, mx, mn)); + let a = v * (1.0 - w) + 0.64 * v.powf(1.6) * w; + let boost = (c0 * a + c1 * a * a) * t.powf(p) * (1.0 - t).powf(q) * ((r0 + ra * a + rt * (1.0 - t)) * (1.0 - mx).max(0.0)).exp(); + ((t * (1.0 + boost)).min(1.0), mx + v / 4.0 * shape) + }; + let m2 = v2 * (1.0 - t2); + let k = (v2 - m2) / (mx - mn); + c.map(|x| m2 + (x - mn) * k) +} + +/// How much positive Vibrance treats a hue (degrees) as skin: 1 on 0–30°, fading to 0 by 45° and +/// in again from 300°. +fn vibrance_skin(h: f32) -> f32 { + if h <= 30.0 { + 1.0 + } else if h < 45.0 { + (45.0 - h) / 15.0 + } else if h < 300.0 { + 0.0 + } else { + (h - 300.0) / 60.0 + } +} + +/// HSV hue in degrees of `c` (its max `mx` and min `mn` given, `mx > mn`). +fn hsv_hue(c: [f32; 3], mx: f32, mn: f32) -> f32 { + let d = mx - mn; + let h = if mx == c[0] { + ((c[1] - c[2]) / d).rem_euclid(6.0) + } else if mx == c[1] { + (c[2] - c[0]) / d + 2.0 + } else { + (c[0] - c[1]) / d + 4.0 + }; + h * 60.0 +} + +pub(super) fn gradient(stops: &[(f32, [f32; 3])], t: f32) -> [f32; 3] { + match stops { + [] => [t; 3], + [s] => s.1, + _ => { + if t <= stops[0].0 { + return stops[0].1; + } + for w in stops.windows(2) { + if t <= w[1].0 { + let k = if w[1].0 > w[0].0 { (t - w[0].0) / (w[1].0 - w[0].0) } else { 0.0 }; + return std::array::from_fn(|i| w[0].1[i] + (w[1].1[i] - w[0].1[i]) * k); + } + } + stops[stops.len() - 1].1 + } + } +} + +pub fn rgb_to_hsl(c: [f32; 3]) -> (f32, f32, f32) { + let max = c[0].max(c[1]).max(c[2]); + let min = c[0].min(c[1]).min(c[2]); + let l = (max + min) / 2.0; + if (max - min).abs() < 1e-7 { + return (0.0, 0.0, l); + } + let d = max - min; + let s = if l > 0.5 { d / (2.0 - max - min) } else { d / (max + min) }; + let h = if max == c[0] { + ((c[1] - c[2]) / d).rem_euclid(6.0) + } else if max == c[1] { + (c[2] - c[0]) / d + 2.0 + } else { + (c[0] - c[1]) / d + 4.0 + }; + (h / 6.0, s, l) +} + +pub fn hsl_to_rgb(h: f32, s: f32, l: f32) -> [f32; 3] { + if s <= 0.0 { + return [l; 3]; + } + let q = if l < 0.5 { l * (1.0 + s) } else { l + s - l * s }; + hue_rgb(h, 2.0 * l - q, q) +} + +/// The colour of hue `h` (0..1) with its smallest channel at `p` and its largest at `q`. +fn hue_rgb(h: f32, p: f32, q: f32) -> [f32; 3] { + let f = |mut t: f32| { + t = t.rem_euclid(1.0); + if t < 1.0 / 6.0 { + p + (q - p) * 6.0 * t + } else if t < 0.5 { + q + } else if t < 2.0 / 3.0 { + p + (q - p) * (2.0 / 3.0 - t) * 6.0 + } else { + p + } + }; + [f(h + 1.0 / 3.0), f(h), f(h - 1.0 / 3.0)] +} diff --git a/crates/compose/src/adjust/tone.rs b/crates/compose/src/adjust/tone.rs new file mode 100644 index 0000000000..3659748392 --- /dev/null +++ b/crates/compose/src/adjust/tone.rs @@ -0,0 +1,488 @@ +use super::*; + +/// Float RGB curve channels with no edit must preserve samples outside the LUT domain; edited +/// ones extend past it (see [`float_tone_extrapolates`]). +pub fn float_tone_identity(adj: &Adjustment, depth: Option) -> [bool; 3] { + match adj { + Adjustment::Curves { master, per_channel, space: ToneSpace::Rgb, .. } if depth == Some(SampleType::F32) => { + std::array::from_fn(|i| photocraft_doc::adjust::is_identity_curve(master) && photocraft_doc::adjust::is_identity_curve(&per_channel[i])) + } + _ => [false; 3], + } +} + +/// Whether an edited Curves adjustment continues past 0..1 instead of clipping: in a 32-bit RGB +/// document Photoshop extends each curve beyond its end points along the slope of its end +/// segments (#7157: `[[0,0],[255,128]]` maps -0.5 to -0.250980407 and 2 to 1.003921628). Only +/// in RGB documents: the curve's space is not the document's, and other modes keep the table. +pub fn float_tone_extrapolates(adj: &Adjustment, depth: Option, mode: ColorMode) -> bool { + matches!(adj, Adjustment::Curves { space: ToneSpace::Rgb, .. }) && depth == Some(SampleType::F32) && mode == ColorMode::Rgb +} + +pub(crate) fn apply_tone(buf: &mut Buffer, space: ToneSpace, luts: &[Vec; 4], identity: [bool; 3], extrapolate: bool) { + let sample = if extrapolate { lut_extended } else { lut }; + match space { + ToneSpace::Rgb => map_rgb(buf, |c| std::array::from_fn(|i| if identity[i] { c[i] } else { sample(&luts[i], c[i]) })), + ToneSpace::Cmyk | ToneSpace::Lab => map_rgb(buf, |c| tone_in_space(space, luts, c)), + } +} + +/// Per-channel LUTs of a Levels or Curves adjustment: each channel's record first, then the +/// master (composite) record, as Photoshop does (psd-tools levels_rgb.psd and curves_rgb.psd, +/// #975). Four rows: the three `per_channel` channels then black +/// (identity unless the space is CMYK). In Lab there is no composite record, so the master is ignored. +pub fn tone_luts(adj: &Adjustment) -> [Vec; 4] { + tone_luts_q(adj, None) +} + +/// [`tone_luts`] for samples with `quantum` steps per unit (Levels works on whole levels; see +/// [`levels_q`]). +pub fn tone_luts_q(adj: &Adjustment, quantum: Option) -> [Vec; 4] { + let x = |k: usize| k as f32 / (LUT_SIZE - 1) as f32; + match adj { + Adjustment::Levels { master, per_channel, space, black } => { + let ident = LevelsChannel::default(); + let m = if *space == ToneSpace::Lab { &ident } else { master }; + let row = |c: &LevelsChannel| (0..LUT_SIZE).map(|k| levels_q(m, levels_q(c, x(k), quantum), quantum)).collect(); + [row(&per_channel[0]), row(&per_channel[1]), row(&per_channel[2]), row(if *space == ToneSpace::Cmyk { black } else { &ident })] + } + Adjustment::Curves { master, per_channel, space, black, pencil } => { + let m = if *space == ToneSpace::Lab { curve_lut(&[]) } else { curve_lut_mode(master, *pencil) }; + let row = |c: &[CurvePoint]| curve_lut_mode(c, *pencil).iter().map(|&v| lut(&m, v)).collect(); + [row(&per_channel[0]), row(&per_channel[1]), row(&per_channel[2]), row(if *space == ToneSpace::Cmyk { black } else { &[] })] + } + _ => std::array::from_fn(|_| (0..LUT_SIZE).map(x).collect()), + } +} + +/// [`tone_luts_q`] in a document of `depth` (`None`: unrounded). 32-bit Levels use +/// [`levels_float`], sampled on 0..1 and kept in 0..1 for LUT consumers. Float RGB rendering +/// evaluates the formula directly instead, so samples and results outside that domain survive. +pub fn tone_luts_depth(adj: &Adjustment, depth: Option) -> [Vec; 4] { + match (adj, depth) { + (Adjustment::Levels { master, per_channel, space: ToneSpace::Rgb, .. }, Some(SampleType::F32)) => { + let x = |k: usize| k as f32 / (LUT_SIZE - 1) as f32; + let row = |c: &LevelsChannel| (0..LUT_SIZE).map(|k| levels_float(master, levels_float(c, x(k))).clamp(0.0, 1.0)).collect(); + [row(&per_channel[0]), row(&per_channel[1]), row(&per_channel[2]), (0..LUT_SIZE).map(x).collect()] + } + _ => tone_luts_q(adj, depth.and_then(crate::adjustment_quantum)), + } +} + +/// Applies channel LUTs to a display-RGB colour in CMYK (ink brightness, 1 - ink) or Lab space, +/// through the conversions the document's surfaces use. The change is added as a difference of +/// two round trips, so channels a curve leaves alone (and out-of-gamut colours) stay exact. +fn tone_in_space(space: ToneSpace, luts: &[Vec; 4], c: [f32; 3]) -> [f32; 3] { + use photocraft_color::convert::{cmyk_to_rgb, rgb_to_cmyk}; + let (before, after) = match space { + ToneSpace::Cmyk => { + let ink = rgb_to_cmyk(c); + let out: [f32; 4] = std::array::from_fn(|i| 1.0 - lut(&luts[i], 1.0 - ink[i])); + if out == ink { + return c; + } + (cmyk_to_rgb(ink), cmyk_to_rgb(out)) + } + ToneSpace::Lab => { + let l = srgb_to_lab(c); + let n = [l[0] / 100.0, (l[1] + 128.0) / 255.0, (l[2] + 128.0) / 255.0]; + let o: [f32; 3] = std::array::from_fn(|i| lut(&luts[i], n[i])); + if o == n { + return c; + } + let back = |v: [f32; 3]| lab_to_srgb([v[0] * 100.0, v[1] * 255.0 - 128.0, v[2] * 255.0 - 128.0]); + (back(n), back(o)) + } + ToneSpace::Rgb => return std::array::from_fn(|i| lut(&luts[i], c[i])), + }; + std::array::from_fn(|i| (c[i] + after[i] - before[i]).clamp(0.0, 1.0)) +} + +pub(super) const LUT_SIZE: usize = 4096; + +pub(super) fn map_rgb(buf: &mut Buffer, f: impl Fn([f32; 3]) -> [f32; 3]) { + for p in &mut buf.px { + if p[3] <= 0.0 { + continue; + } + let r = f([p[0], p[1], p[2]]); + p[0] = r[0]; + p[1] = r[1]; + p[2] = r[2]; + } +} + +#[inline] +pub(super) fn lut(table: &[f32], v: f32) -> f32 { + let x = v.clamp(0.0, 1.0) * (table.len() - 1) as f32; + // Never negative (NaN casts to 0, as its floor did), so truncating is `floor`, without the + // libm call baseline x86-64 (no SSE4.1) makes for it. + let i = x as usize; + let j = (i + 1).min(table.len() - 1); + let f = x - i as f32; + table[i] * (1.0 - f) + table[j] * f +} + +/// Table steps the end slopes of [`lut_extended`] are measured over: one step's difference near +/// 0.5 carries f32 rounding (2e-4 of the slope), while 16 steps are still only 0.4 % of the domain. +pub const TONE_SLOPE_SPAN: usize = 16; + +/// [`lut`] continued past 0..1 along the slope of the table's end segments, as Photoshop applies +/// a curve to float samples ([`float_tone_extrapolates`]). Inside the domain it is [`lut`]; +/// non-finite samples stay with it too, so an infinite one can't become NaN on a flat end. +#[inline] +fn lut_extended(table: &[f32], v: f32) -> f32 { + let n = table.len(); + if !v.is_finite() || (0.0..=1.0).contains(&v) || n < 2 { + return lut(table, v); + } + let k = TONE_SLOPE_SPAN.min(n - 1); + let per_unit = (n - 1) as f32 / k as f32; + if v < 0.0 { table[0] + v * (table[k] - table[0]) * per_unit } else { table[n - 1] + (v - 1.0) * (table[n - 1] - table[n - 1 - k]) * per_unit } +} + +/// Modern Brightness curve (one channel, `brightness` in [-150, 150]); pins pure black and white, +/// and `b = 0` is the identity. Raised, it is a line of slope `s = 1.375^(b/50)` from the origin +/// up to a knee at output 126/255, then a cubic Hermite to (1, 1) whose end slope is +/// `1 / (1 + 0.084 b)`; past about +110, where no such cubic stays below white, the roll-off is +/// `1 - (1 - y0)(1 - u)^α` instead (continuous slope `α` at the knee, flat at white). Lowered, it +/// is the inverse of the curve raised by as much. +/// +/// Fit to every Photoshop measurement we have, all within about a level and a half: its ±50 +/// samples (`modern_brightness_matches_photoshop`), the photoshop corpus's brightness-contrast.psd +/// (+25 with contrast +30) and psd-tools' brightnesscontrast_rgb.psd, whose masked layers give +/// +23, -31 and -95 (+150 within 6 levels there, where every curve family tried bottoms out). +pub fn modern_brightness(v: f32, brightness: f32) -> f32 { + if brightness == 0.0 || !brightness.is_finite() { + return v; + } + Brightness::new(brightness).eval(v) +} + +/// [`modern_brightness`] for one slider value, its curve's constants worked out once. +struct Brightness { + raise: bool, + s: f32, + e: f32, + x0: f32, + /// The knee's slope over the roll-off's secant (`α` of Fritsch–Carlson); a power roll-off + /// replaces the Hermite when α² + β² > 9. + alpha: f32, + hermite: bool, +} + +/// Output level of the Brightness curve's knee. +const BRIGHTNESS_KNEE: f32 = 126.0 / 255.0; + +impl Brightness { + fn new(brightness: f32) -> Self { + let b = brightness.abs(); + let s = 1.375f32.powf(b / 50.0); + let e = 1.0 / (1.0 + 0.084 * b); + let x0 = (BRIGHTNESS_KNEE / s).min(1.0); + let secant = (1.0 - BRIGHTNESS_KNEE) / (1.0 - x0).max(1e-6); + let (alpha, beta) = (s / secant, e / secant); + Brightness { raise: brightness > 0.0, s, e, x0, alpha, hermite: alpha * alpha + beta * beta <= 9.0 } + } + + fn eval(&self, v: f32) -> f32 { + let v = v.clamp(0.0, 1.0); + if self.raise { + return self.raised(v); + } + if v <= 0.0 || v >= 1.0 { + return v; + } + // The inverse of the raised curve (monotone on [0, 1]), by bisection. + let (mut lo, mut hi) = (0.0f32, 1.0f32); + for _ in 0..32 { + let mid = 0.5 * (lo + hi); + if self.raised(mid) < v { + lo = mid; + } else { + hi = mid; + } + } + 0.5 * (lo + hi) + } + + /// The curve raised: the line, then a monotone roll-off to (1, 1). + fn raised(&self, x: f32) -> f32 { + let Brightness { s, e, x0, alpha, hermite, .. } = *self; + let y0 = BRIGHTNESS_KNEE; + if x <= x0 { + return y0.min(s * x); + } + let h = (1.0 - x0).max(1e-6); + let t = ((x - x0) / h).clamp(0.0, 1.0); + let y = if hermite { + let (t2, t3) = (t * t, t * t * t); + (2.0 * t3 - 3.0 * t2 + 1.0) * y0 + (t3 - 2.0 * t2 + t) * h * s + (-2.0 * t3 + 3.0 * t2) + (t3 - t2) * h * e + } else { + 1.0 - (1.0 - y0) * (1.0 - t).powf(alpha) + }; + y.clamp(0.0, 1.0) + } +} + +/// Modern Brightness/Contrast as one channel's lookup table (4096 samples over 0..1): +/// [`modern_brightness`] then [`modern_contrast`], as Photoshop applies them. +pub fn modern_lut(brightness: f32, contrast: f32) -> Vec { + let step = |k: usize, n: usize| k as f32 / (n - 1) as f32; + let bright: Vec = if brightness == 0.0 || !brightness.is_finite() { + (0..LUT_SIZE).map(|k| step(k, LUT_SIZE)).collect() + } else if brightness > 0.0 { + let curve = Brightness::new(brightness); + (0..LUT_SIZE).map(|k| curve.raised(step(k, LUT_SIZE))).collect() + } else { + // Lowered: invert the raised curve, sampled four times finer, in one monotone pass. + let curve = Brightness::new(-brightness); + let fine = 4 * LUT_SIZE; + let ys: Vec = (0..fine).map(|j| curve.raised(step(j, fine))).collect(); + let mut j = 0; + (0..LUT_SIZE) + .map(|k| { + let y = step(k, LUT_SIZE); + while j + 2 < fine && ys.get(j + 1).is_some_and(|&n| n < y) { + j += 1; + } + let (y0, y1) = (ys.get(j).copied().unwrap_or(0.0), ys.get(j + 1).copied().unwrap_or(1.0)); + let f = if y1 > y0 { ((y - y0) / (y1 - y0)).clamp(0.0, 1.0) } else { 0.0 }; + (step(j, fine) + f / (fine - 1) as f32).clamp(0.0, 1.0) + }) + .collect() + }; + bright.into_iter().map(|b| modern_contrast(b, contrast).clamp(0.0, 1.0)).collect() +} + +/// Modern Contrast curve (one channel, `contrast` in [-50, 100]). A symmetric cubic-Hermite S-curve +/// pivoting at 0.5: endpoint slope `1 - c/128`, centre slope `1 + c/128`. Near-exact vs Photoshop +/// (≤0.5/255). `c = 0` is the identity; pins 0, 0.5 and 1. +pub fn modern_contrast(v: f32, contrast: f32) -> f32 { + if contrast == 0.0 { + return v; + } + let k = contrast / 128.0; + let (end, mid) = (1.0 - k, 1.0 + k); + // Cubic Hermite on [0, 0.5]: pinned (0,0) slope `end`, (0.5,0.5) slope `mid`. `t` in [0,1]. + let half = |t: f32| end * 0.5 * (t * t * t - 2.0 * t * t + t) + (-2.0 * t * t * t + 3.0 * t * t) * 0.5 + mid * 0.5 * (t * t * t - t * t); + let v = v.clamp(0.0, 1.0); + if v <= 0.5 { half(v / 0.5) } else { 1.0 - half((1.0 - v) / 0.5) } +} + +/// Photoshop posterize: `n` equal input bins over 0..=255, output levels +/// `floor(k * 255 / (n - 1))` (exact on the corpus for 3, 7, 13 and 21 levels). +pub fn posterize(v: f32, levels: u32) -> f32 { + let n = levels.clamp(2, 255) as f32; + let x = (v.clamp(0.0, 1.0) * 255.0).round(); + let bin = (x * n / 256.0).floor().min(n - 1.0); + (bin * 255.0 / (n - 1.0)).floor() / 255.0 +} + +/// [`posterize`] in a document of `depth` (`None`: unknown, treated as 8-bit). At 16 bits +/// Photoshop bins the 16-bit sample (`⌊v · n / 32768⌋`) and lands on 8-bit levels through a +/// 16-bit step: `⌊b · 32768 / (n - 1)⌋`, converted with `⌊(o · 255 + 16384) / 32768⌋`, so +/// 127.5 comes out as 128 but 42.5 as 42 (8 bits floor them all). Exact on every sample of +/// psd-tools posterize_16bits_rgb.psd and posterize_16bits_grayscale.psd (levels 2 to 21), +/// which the 8-bit rule missed by up to half the range. +pub fn posterize_in(v: f32, levels: u32, depth: Option) -> f32 { + if depth != Some(SampleType::U16) { + return posterize(v, levels); + } + let n = f64::from(levels.clamp(2, 255)); + let x = (f64::from(v.clamp(0.0, 1.0)) * 32768.0).round(); + let bin = (x * n / 32768.0).floor().min(n - 1.0); + let step = (bin * 32768.0 / (n - 1.0)).floor(); + (((step * 255.0 + 16384.0) / 32768.0).floor() / 255.0) as f32 +} + +pub fn levels(ch: &LevelsChannel, v: f32) -> f32 { + levels_q(ch, v, None) +} + +/// [`levels`] on samples with `quantum` steps per unit (8-bit: 255). Photoshop works on whole +/// levels in three steps, each rounded half up to a whole level: the input-range stretch, the +/// midtone gamma ([`levels_gamma`]) and the output range. So a 44..214 range maps 45, 46, 47, 48 +/// → 1.5, 3, 4.5, 6 → 2, 3, 5, 6 (psd-tools levels_grayscale, where the gamma toe magnifies the +/// steps), and an output range narrower than 0..255 maps neighbouring gamma levels to one level +/// (psd-tools levels_rgb: 43..48 → 58 through a 0.47 channel gamma and the master's 48..255). +/// In a LUT the result is a staircase that is exact at every level. +pub fn levels_q(ch: &LevelsChannel, v: f32, quantum: Option) -> f32 { + let range = (ch.in_white - ch.in_black).max(1e-6); + let quantum = quantum.filter(|q| q.is_finite() && *q >= 1.0); + let whole = |x: f32| match quantum { + Some(q) => (x * q + 0.5).floor() / q, + None => x, + }; + let u = match quantum { + Some(q) => { + let v = (v * q).round() / q; + (((v - ch.in_black) / range).clamp(0.0, 1.0) * q + 0.5 + 1e-3).floor() / q + } + None => ((v - ch.in_black) / range).clamp(0.0, 1.0), + }; + let t = whole(levels_gamma(u, ch.gamma.max(0.01))); + whole(ch.out_black + t * (ch.out_white - ch.out_black)) +} + +/// Exponent of the shadow toe in [`levels_gamma`] (fitted; see there). +const LEVELS_TOE_POWER: f32 = 2.2; + +/// Levels' midtone gamma `g` on `u` in 0..1: `u^(1/g)`, except that above 1, where that power +/// curve is infinitely steep at black, Photoshop starts along a toe `a·u − b·u^q` of slope +/// `a = 2^g` that joins the curve with the same value and slope. `q` = [`LEVELS_TOE_POWER`] is +/// fitted on whole-level oracles at gamma 1.16, 1.22, 1.3, 1.78 and 2.0 (psd-tools levels_rgb +/// and levels_grayscale, the photoshop corpus's rgb8 and gray8 levels.psd, a measured 0..255 +/// ramp): all but 2 of their 1118 levels exact, the others within one. Below 1 the power curve is +/// exact (gamma 0.67 and 0.7: every level). +pub fn levels_gamma(u: f32, g: f32) -> f32 { + let c = 1.0 / g; + if g <= 1.0 { + return u.powf(c); + } + let (a, q) = (2f32.powf(g), LEVELS_TOE_POWER); + // Where the toe meets the curve: a·u1 − b·u1^q = u1^c and a − q·b·u1^(q−1) = c·u1^(c−1). + let u1 = ((1.0 - c / q) / (a * (1.0 - 1.0 / q))).powf(1.0 / (1.0 - c)); + if u >= u1 || u1 <= 0.0 { + return u.powf(c); + } + let b = (a * u1 - u1.powf(c)) / u1.powf(q); + // Just above gamma 1 the toe shrinks to nothing: u1^q underflows to 0 while u1 doesn't, and + // the power curve is the toe's limit there (otherwise b = inf and black turns NaN). + if !b.is_finite() { + return u.powf(c); + } + a * u - b * u.powf(q) +} + +/// [`levels`] in a 32-bit document. Neither the input is clipped to the input range nor the result +/// to the output range there, and the midtone gamma is a plain power curve, mirrored below the +/// black point (the oracle corpus' rgb32 and gray32 levels.psd: within 0.5/255, 10/255 off with +/// the clipped curve). +pub fn levels_float(ch: &LevelsChannel, v: f32) -> f32 { + let t = (v - ch.in_black) / (ch.in_white - ch.in_black).max(1e-6); + let t = if ch.gamma == 1.0 { t } else { t.signum() * t.abs().powf(1.0 / ch.gamma.max(0.01)) }; + ch.out_black + t * (ch.out_white - ch.out_black) +} + +/// The LUT of one Curves curve: [`curve_map_lut`] for a pencil-drawn map, else [`curve_lut`]. +pub fn curve_lut_mode(points: &[CurvePoint], pencil: bool) -> Vec { + if pencil { curve_map_lut(points) } else { curve_lut(points) } +} + +/// A pencil-drawn Curves map (see [`photocraft_doc::adjust::curve_map`]): straight segments +/// between its entries, constant outside the first/last, clamped to 0..=1, sampled into a LUT. +pub fn curve_map_lut(points: &[CurvePoint]) -> Vec { + let mut pts: Vec<(f32, f32)> = points.iter().filter(|p| p.input.is_finite() && p.output.is_finite()).map(|p| (p.input, p.output)).collect(); + pts.sort_by(|a, b| a.0.total_cmp(&b.0)); + pts.dedup_by(|a, b| (a.0 - b.0).abs() < 1e-6); + let ident = |k: usize| k as f32 / (LUT_SIZE - 1) as f32; + let (Some(&first), Some(&last)) = (pts.first(), pts.last()) else { return (0..LUT_SIZE).map(ident).collect() }; + let mut seg = 0; + (0..LUT_SIZE) + .map(|k| { + let xv = ident(k); + if xv <= first.0 { + return first.1.clamp(0.0, 1.0); + } + if xv >= last.0 { + return last.1.clamp(0.0, 1.0); + } + while pts.get(seg + 1).is_some_and(|p| p.0 < xv) { + seg += 1; + } + let (Some(&(x0, y0)), Some(&(x1, y1))) = (pts.get(seg), pts.get(seg + 1)) else { return last.1.clamp(0.0, 1.0) }; + let t = if x1 > x0 { (xv - x0) / (x1 - x0) } else { 0.0 }; + (y0 + (y1 - y0) * t).clamp(0.0, 1.0) + }) + .collect() +} + +/// Photoshop curve: a natural cubic spline through the points (it may +/// overshoot between points, as Photoshop's does), constant outside the +/// first/last point, clamped to 0..=1, sampled into a LUT. +pub fn curve_lut(points: &[CurvePoint]) -> Vec { + let mut pts: Vec<(f32, f32)> = points.iter().map(|p| (p.input, p.output)).collect(); + pts.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal)); + pts.dedup_by(|a, b| (a.0 - b.0).abs() < 1e-6); + if pts.len() < 2 { + return (0..LUT_SIZE).map(|i| i as f32 / (LUT_SIZE - 1) as f32).collect(); + } + let n = pts.len(); + // Second derivatives of the natural spline (tridiagonal solve). + let mut m2 = vec![0.0f64; n]; + if n > 2 { + let x: Vec = pts.iter().map(|p| f64::from(p.0)).collect(); + let y: Vec = pts.iter().map(|p| f64::from(p.1)).collect(); + let mut c = vec![0.0f64; n]; + let mut d = vec![0.0f64; n]; + for i in 1..n - 1 { + let (h0, h1) = (x[i] - x[i - 1], x[i + 1] - x[i]); + let a = h0 / 6.0; + let b = (h0 + h1) / 3.0; + let cc = h1 / 6.0; + let r = (y[i + 1] - y[i]) / h1 - (y[i] - y[i - 1]) / h0; + let denom = b - a * c[i - 1]; + c[i] = cc / denom; + d[i] = (r - a * d[i - 1]) / denom; + } + for i in (1..n - 1).rev() { + m2[i] = d[i] - c[i] * m2[i + 1]; + } + } + (0..LUT_SIZE) + .map(|k| { + let xv = k as f32 / (LUT_SIZE - 1) as f32; + if xv <= pts[0].0 { + return pts[0].1.clamp(0.0, 1.0); + } + if xv >= pts[n - 1].0 { + return pts[n - 1].1.clamp(0.0, 1.0); + } + let i = pts.windows(2).position(|w| xv <= w[1].0).unwrap_or(n - 2); + let (x0, y0) = (f64::from(pts[i].0), f64::from(pts[i].1)); + let (x1, y1) = (f64::from(pts[i + 1].0), f64::from(pts[i + 1].1)); + let h = x1 - x0; + let t = f64::from(xv); + let a = (x1 - t) / h; + let b = (t - x0) / h; + let y = a * y0 + b * y1 + ((a * a * a - a) * m2[i] + (b * b * b - b) * m2[i + 1]) * h * h / 6.0; + (y as f32).clamp(0.0, 1.0) + }) + .collect() +} + +/// A layer-style contour curve: [`curve_lut`], except that the curve bends sharply at corner +/// points (`corners[i]` true; Photoshop's Contour Editor "Corner"): each run between corners is +/// its own natural spline, so all-corner points make a polyline. Missing flags are smooth. +pub fn contour_curve_lut(points: &[CurvePoint], corners: &[bool]) -> Vec { + let mut pts: Vec<(CurvePoint, bool)> = points.iter().enumerate().map(|(i, p)| (p.clone(), corners.get(i).copied().unwrap_or(false))).collect(); + if !pts.iter().any(|p| p.1) { + return curve_lut(points); + } + pts.sort_by(|a, b| a.0.input.partial_cmp(&b.0.input).unwrap_or(std::cmp::Ordering::Equal)); + pts.dedup_by(|a, b| (a.0.input - b.0.input).abs() < 1e-6); + let mut out: Vec = Vec::new(); + let mut start = 0usize; + let last = pts.len().saturating_sub(1); + for i in 1..=last { + let corner = pts.get(i).is_some_and(|p| p.1); + if !(corner || i == last) { + continue; + } + let Some(seg) = pts.get(start..=i) else { break }; + let from = seg.first().map_or(0.0, |p| p.0.input); + let lut = curve_lut(&seg.iter().map(|p| p.0.clone()).collect::>()); + if out.is_empty() { + out = lut; + } else { + for (k, (o, v)) in out.iter_mut().zip(lut).enumerate() { + if k as f32 / (LUT_SIZE - 1) as f32 >= from { + *o = v; + } + } + } + start = i; + } + if out.is_empty() { curve_lut(points) } else { out } +} diff --git a/crates/compose/src/adjust/tone_tests.rs b/crates/compose/src/adjust/tone_tests.rs new file mode 100644 index 0000000000..fbd91bf14b --- /dev/null +++ b/crates/compose/src/adjust/tone_tests.rs @@ -0,0 +1,883 @@ +use super::*; +use photocraft_geom::Rect; + +fn ramp() -> Buffer { + let rect = Rect::new(0, 0, 8, 8); + let px = (0..64).map(|i| [((i % 8) as f32) / 7.0, ((i / 8) as f32) / 7.0, 0.3, 1.0]).collect(); + Buffer { rect, px } +} + +/// Photoshop 27.11, measured: Brightness/Contrast with Use Legacy on, over a gray ramp +/// (x = 0, 16, …, 240, 255), one row per (brightness, contrast). +/// One pixel through `adj` in a 32-bit document. +fn hdr(adj: &Adjustment, c: [f32; 3]) -> [f32; 3] { + let mut b = Buffer::filled(crate::Rect::new(0, 0, 1, 1), [c[0], c[1], c[2], 1.0]); + apply_depth(adj, &mut b, Transfer::Gamma(1.0), Some(SampleType::F32)); + [b.px[0][0], b.px[0][1], b.px[0][2]] +} + +/// Photoshop's 32-bit Hue/Saturation (photoshop corpus rgb32 hue-saturation.psd: hue +40, +/// saturation +25, lightness -10): saturated colours leave 0..1, and the saturation factor is +/// 1 / (1 - 63/255), so red becomes (1.0477, 0.649, -0.1477), where 8 bits clip to (0.9, 0.6, 0). +#[test] +fn thirty_two_bit_hue_saturation_is_unclipped() { + let adj = Adjustment::HueSaturation { hue: 40.0, saturation: 25.0, lightness: -10.0, colorize: false, ranges: HueRange::defaults() }; + let near = |got: [f32; 3], want: [f32; 3]| got.iter().zip(want).all(|(g, w)| (g - w).abs() < 1e-3); + for (c, want) in + [([1.0, 0.0, 0.0], [1.0477, 0.649, -0.1477]), ([0.9301, 0.6105, 0.2541], [0.7804, 0.9369, 0.1289]), ([0.0, 0.3864, 1.0], [0.1871, -0.1477, 1.0477])] + { + assert!(near(hdr(&adj, c), want), "{c:?}: {:?}", hdr(&adj, c)); + } + let mut b = Buffer::filled(crate::Rect::new(0, 0, 1, 1), [1.0, 0.0, 0.0, 1.0]); + apply_depth(&adj, &mut b, Transfer::Srgb, Some(SampleType::U16)); + assert!(b.px[0].iter().all(|v| (0.0..=1.0).contains(v)), "16 bits clip: {:?}", b.px[0]); +} + +/// Photoshop's 32-bit Colorize (photoshop corpus rgb32 hue-saturation-colorize.psd: hue -160, +/// saturation 40, lightness +5): red becomes (0.3445, 0.5852, 0.7055), 0.95 of the chroma an +/// 8-bit Colorize gives at the same lightness, (0.335, 0.5883, 0.715). +#[test] +fn thirty_two_bit_colorize_scales_the_saturation() { + let adj = Adjustment::HueSaturation { hue: -160.0, saturation: 40.0, lightness: 5.0, colorize: true, ranges: HueRange::defaults() }; + let near = |got: [f32; 3], want: [f32; 3]| got.iter().zip(want).all(|(g, w)| (g - w).abs() < 2e-3); + let red = hdr(&adj, [1.0, 0.0, 0.0]); + assert!(near(red, [0.3445, 0.5852, 0.7055]), "{red:?}"); + let mut b = Buffer::filled(crate::Rect::new(0, 0, 1, 1), [1.0, 0.0, 0.0, 1.0]); + apply_depth(&adj, &mut b, Transfer::Srgb, Some(SampleType::U16)); + assert!(near([b.px[0][0], b.px[0][1], b.px[0][2]], [0.335, 0.5883, 0.715]), "16-bit keeps the full saturation: {:?}", b.px[0]); +} + +/// Photoshop's 32-bit saturation factor (Hue/Saturation on red (1, 0, 0) in a 32-bit document, +/// read back from the saved float TIFF, exact in 1/512): red's R is 0.5 + 0.5 x the factor. +#[test] +fn thirty_two_bit_saturation_steps_match_photoshop() { + for (sat, want) in [ + (10.0, 539.0 / 512.0), + (75.0, 2.4609375), + (90.0, 2673.0 / 512.0), + (99.0, 32.375), + (100.0, 33023.0 / 512.0), + (-10.0, 487.0 / 512.0), + (-25.0, 0.875), + (-50.0, 0.75), + (-100.0, 0.5), + ] { + let adj = Adjustment::HueSaturation { hue: 0.0, saturation: sat, lightness: 0.0, colorize: false, ranges: HueRange::defaults() }; + let got = hdr(&adj, [1.0, 0.0, 0.0])[0]; + assert!((got - want).abs() < 1e-4, "saturation {sat}: {got}, Photoshop {want}"); + } +} + +/// 32-bit colours at or above HSL lightness 1 (red at +1 stop, (2, 0, 0)) keep their hue and +/// get their chroma scaled like any other, as in Photoshop; they used to turn NaN or grey. +#[test] +fn thirty_two_bit_hue_saturation_keeps_bright_colours() { + let pale = [280.0 / 255.0, 230.0 / 255.0, 256.0 / 255.0]; + let near = |got: [f32; 3], want: [f32; 3]| got.iter().zip(want).all(|(g, w)| (g - w).abs() <= 1e-3 * w.abs().max(1.0)); + for (hue, sat, c, want) in [ + (40.0, 0.0, [2.0, 0.0, 0.0], [2.0, 1.33301, 0.0]), + (40.0, 0.0, pale, [1.09804, 0.930687, 0.901961]), + (0.0, 25.0, [2.0, 0.0, 0.0], [2.32812, -0.328125, -0.328125]), + (0.0, 25.0, pale, [1.13021, 0.869792, 1.00521]), + (0.0, -25.0, [2.0, 0.0, 0.0], [1.75, 0.25, 0.25]), + (0.0, 100.0, [140.0 / 255.0, 115.0 / 255.0, 128.0 / 255.0], [6.77432, -5.77432, 0.750976]), + (0.0, 100.0, [2.0, 0.0, 0.0], [128.996, -126.996, -126.996]), + ] { + let adj = Adjustment::HueSaturation { hue, saturation: sat, lightness: 0.0, colorize: false, ranges: HueRange::defaults() }; + let got = hdr(&adj, c); + assert!(near(got, want), "hue {hue}, saturation {sat}, {c:?}: {got:?}, Photoshop {want:?}"); + } + // A master plus a range edit that add up to a whole step stay on it: Reds +96 over a master + // -46 scales red as much as a master +50 alone (in f32 the sum is 0.49999997). + let mut ranges = HueRange::defaults(); + ranges[0].saturation = 96.0; + let summed = Adjustment::HueSaturation { hue: 0.0, saturation: -46.0, lightness: 0.0, colorize: false, ranges }; + let single = Adjustment::HueSaturation { hue: 0.0, saturation: 50.0, lightness: 0.0, colorize: false, ranges: HueRange::defaults() }; + assert_eq!(hdr(&summed, [1.0, 0.0, 0.0]), hdr(&single, [1.0, 0.0, 0.0])); + // Lightness 0 with a negative channel divides by zero the same way. + let adj = Adjustment::HueSaturation { hue: 40.0, saturation: 25.0, lightness: 0.0, colorize: false, ranges: HueRange::defaults() }; + assert!(hdr(&adj, [0.25, -0.25, 0.0]).iter().all(|v| v.is_finite())); +} + +/// Photoshop's own 32-bit results (photoshop corpus rgb32): nothing clips, legacy contrast +/// pivots at 127, the mixer cuts its percentages to 1/1024 and counts 255/512 of the +/// constant, and the Black & White tint keeps values above 1. +#[test] +fn thirty_two_bit_adjustments_match_photoshop_unclipped() { + let near = |got: [f32; 3], want: [f32; 3], tol: f32| got.iter().zip(want).all(|(g, w)| (g - w).abs() <= tol); + let bc = Adjustment::BrightnessContrast { brightness: 25.0, contrast: 30.0, legacy: true }; + // brightness-contrast-legacy.psd + assert!(near(hdr(&bc, [0.4910, 0.0009, 0.9301]), [0.6280, -0.0721, 1.2553], 2e-4), "{:?}", hdr(&bc, [0.4910, 0.0009, 0.9301])); + // channel-mixer.psd: pure red, green, blue and black, exactly. + let mixer = Adjustment::ChannelMixer { matrix: [[0.8, 0.3, -0.1, 0.0], [0.1, 0.9, 0.0, 0.05], [0.0, 0.2, 0.7, 0.0]], monochrome: false }; + for (c, want) in [ + ([1.0, 0.0, 0.0], [0.7998047, 0.1245117, 0.0]), + ([0.0, 1.0, 0.0], [0.2998047, 0.9243164, 0.1992188]), + ([0.0, 0.0, 1.0], [-0.0996094, 0.0249023, 0.6992188]), + ([0.0, 0.0, 0.0], [0.0, 0.0249023, 0.0]), + ] { + assert!(near(hdr(&mixer, c), want, 1e-6), "{c:?}: {:?}", hdr(&mixer, c)); + } + // black-white-tint.psd: white tints past 1. + let bw = Adjustment::BlackWhite { weights: [40.0, 60.0, 40.0, 60.0, 20.0, 80.0], tint: Some([0.88235295, 0.827451, 0.7019608]) }; + assert!(near(hdr(&bw, [1.0; 3]), [1.0522, 0.9973, 0.8718], 2e-4), "{:?}", hdr(&bw, [1.0; 3])); + // 8/16-bit documents still clip. + let mut b = Buffer::filled(crate::Rect::new(0, 0, 1, 1), [1.0, 1.0, 1.0, 1.0]); + apply_depth(&bw, &mut b, Transfer::Srgb, None); + assert!(b.px[0].iter().all(|v| *v <= 1.0)); +} + +#[test] +fn legacy_brightness_contrast_matches_photoshop() { + const X: [u8; 17] = [0, 16, 32, 48, 64, 80, 96, 112, 128, 144, 160, 176, 192, 208, 224, 240, 255]; + let measured: [(f32, f32, [u8; 17]); 7] = [ + (40.0, 0.0, [40, 56, 72, 88, 104, 120, 136, 152, 168, 184, 200, 216, 232, 248, 255, 255, 255]), + (-40.0, 0.0, [0, 0, 0, 8, 24, 40, 56, 72, 88, 104, 120, 136, 152, 168, 184, 200, 215]), + (0.0, 30.0, [0, 0, 0, 14, 37, 60, 82, 105, 128, 151, 174, 196, 219, 242, 255, 255, 255]), + (0.0, -30.0, [38, 49, 61, 72, 83, 94, 106, 117, 128, 139, 150, 162, 173, 184, 195, 207, 217]), + (40.0, 30.0, [3, 25, 48, 71, 94, 117, 139, 162, 185, 208, 231, 253, 255, 255, 255, 255, 255]), + (100.0, 0.0, [100, 116, 132, 148, 164, 180, 196, 212, 228, 244, 255, 255, 255, 255, 255, 255, 255]), + (0.0, 80.0, [0, 0, 0, 0, 0, 0, 0, 48, 128, 208, 255, 255, 255, 255, 255, 255, 255]), + ]; + for (brightness, contrast, want) in measured { + let rect = Rect::new(0, 0, 17, 1); + let px = X.iter().map(|x| [f32::from(*x) / 255.0; 4]).map(|p| [p[0], p[1], p[2], 1.0]).collect(); + let mut b = Buffer { rect, px }; + apply(&Adjustment::BrightnessContrast { brightness, contrast, legacy: true }, &mut b); + for (i, (p, w)) in b.px.iter().zip(want).enumerate() { + let got = (p[0] * 255.0).round() as i32; + assert!((got - i32::from(w)).abs() <= 1, "b {brightness} c {contrast} at {}: {got} vs Photoshop {w}", X[i]); + } + } +} + +/// Pixel → Photoshop's split. 8-bit from psd-tools threshold_rgb.psd: the first three are +/// white though their Rec. 601 grey rounds below 60, and (131, 109, 99) sits exactly on 114.5 +/// at level 115 (halves round down). 16-bit from threshold_16bits_rgb.psd and the photoshop +/// corpus's rgb16 threshold-128.psd, whose mid grey 16448 is level 128 in 16 bits. +#[test] +fn threshold_splits_on_the_luminosity_like_photoshop() { + let c8 = |r: u8, g: u8, b: u8| [r, g, b].map(|v| f32::from(v) / 255.0); + for (c, level, white) in + [(c8(87, 51, 31), 60u8, true), (c8(90, 49, 33), 60, true), (c8(68, 57, 50), 60, true), (c8(48, 63, 72), 60, false), (c8(131, 109, 99), 115, false)] + { + assert_eq!(threshold_white(c, f32::from(level) / 255.0, Some(SampleType::U8)), white, "8-bit {c:?} at {level}"); + } + let c16 = |r: u16, g: u16, b: u16| [r, g, b].map(|v| f32::from(v) / 32768.0); + for (c, level, white) in [ + (c16(8995, 7196, 6425), 60u8, false), + (c16(11180, 6554, 3984), 60, false), + (c16(16448, 16448, 16448), 128, true), + (c16(16447, 16447, 16447), 128, false), + ] { + assert_eq!(threshold_white(c, f32::from(level) / 255.0, Some(SampleType::U16)), white, "16-bit {c:?} at {level}"); + } + // Through the adjustment: neutral black or white. + let mut b = Buffer::filled(Rect::new(0, 0, 1, 1), [87.0 / 255.0, 51.0 / 255.0, 31.0 / 255.0, 1.0]); + apply_depth(&Adjustment::Threshold { level: 60.0 / 255.0 }, &mut b, Transfer::Srgb, Some(SampleType::U8)); + assert_eq!(b.px[0], [1.0, 1.0, 1.0, 1.0]); +} + +/// 16-bit sample → Photoshop's 8-bit level, from psd-tools posterize_16bits_rgb.psd: bins +/// split on the 16-bit sample (10794 and 10923 straddle a third of 32768), and the middle of 3 +/// levels is 128 where 8 bits give 127, while 21 levels keep 25 for 25.5. +#[test] +fn sixteen_bit_posterize_matches_photoshop() { + let points: [(u32, u16, u8); 9] = + [(3, 10794, 0), (3, 10923, 128), (3, 21845, 128), (3, 21974, 255), (13, 2504, 0), (13, 2542, 21), (13, 7453, 42), (13, 7582, 64), (21, 3341, 25)]; + for (levels, x, want) in points { + let got = posterize_in(f32::from(x) / 32768.0, levels, Some(SampleType::U16)); + assert!((got * 255.0 - f32::from(want)).abs() < 1e-3, "{levels} levels at {x}: {} vs Photoshop {want}", got * 255.0); + } + // 8 bits keep their rule. + assert_eq!(posterize_in(128.0 / 255.0, 3, Some(SampleType::U8)), posterize(128.0 / 255.0, 3)); +} + +#[test] +fn color_lookup_with_an_overflowing_stored_size_is_the_identity() { + // A stored document's size is untrusted: (2²²)³ × 3 overflows, which once wrapped past + // the table-length guard and indexed out of bounds. + for size in [1 << 22, u32::MAX] { + let a = Adjustment::ColorLookup { name: "x".into(), lut: Some(std::sync::Arc::new(vec![0.5; 24])), size, tetrahedral: false, dither: false }; + let mut b = ramp(); + apply(&a, &mut b); + assert_eq!(b.px, ramp().px, "size {size}"); + } +} + +/// Photoshop 27.11, measured: Color Balance with one cyan–red slider moved, over a gray ramp +/// (x = 0, 16, …, 240, 255); red and green out (blue follows green on gray). +#[test] +fn color_balance_matches_photoshop() { + const X: [u8; 17] = [0, 16, 32, 48, 64, 80, 96, 112, 128, 144, 160, 176, 192, 208, 224, 240, 255]; + type Row = (&'static str, f32, bool, [u8; 17], [u8; 17]); + let measured: [Row; 6] = [ + ("midtones", 50.0, false, [0, 36, 59, 78, 96, 112, 128, 142, 156, 170, 183, 196, 209, 221, 233, 244, 255], X), + ("shadows", -100.0, false, [0, 0, 0, 0, 0, 0, 0, 7, 23, 43, 67, 93, 122, 154, 186, 221, 255], X), + ("highlights", 100.0, false, [0, 51, 84, 111, 136, 160, 182, 202, 223, 242, 255, 255, 255, 255, 255, 255, 255], X), + ("shadows", 50.0, true, X, [0, 0, 0, 0, 17, 37, 57, 77, 97, 117, 137, 157, 177, 197, 216, 236, 255]), + ( + "midtones", + 100.0, + true, + [0, 36, 59, 78, 96, 112, 128, 142, 156, 170, 183, 196, 209, 221, 233, 244, 255], + [0, 5, 14, 24, 36, 50, 64, 80, 97, 114, 132, 151, 171, 191, 212, 234, 255], + ), + ("highlights", -100.0, true, X, [0, 26, 53, 79, 105, 132, 158, 184, 211, 237, 255, 255, 255, 255, 255, 255, 255]), + ]; + // Two sliders in one tone, Preserve Luminosity on (measured): shadows red and blue +50 darken + // only green; highlights red −50 with green +50 lift green by 100 and blue by 50. + let two = + |tones: [[f32; 3]; 3], x: f32| -> [i32; 3] { std::array::from_fn(|ch| (color_balance_channel(tones, true, ch, x / 255.0) * 255.0).round() as i32) }; + assert_eq!(two([[50.0, 0.0, 50.0], [0.0; 3], [0.0; 3]], 128.0), [128, 97, 128]); + let hi = two([[0.0; 3], [0.0; 3], [-50.0, 50.0, 0.0]], 128.0); + assert!((hi[0] - 128).abs() <= 1 && (hi[1] - 211).abs() <= 1 && (hi[2] - 159).abs() <= 1, "{hi:?}"); + for (tone, amount, preserve, red, green) in measured { + let mut tones = [[0.0f32; 3]; 3]; + tones[["shadows", "midtones", "highlights"].iter().position(|t| *t == tone).unwrap()][0] = amount; + for (i, x) in X.iter().enumerate() { + let v = f32::from(*x) / 255.0; + let got = |ch| (color_balance_channel(tones, preserve, ch, v) * 255.0).round() as i32; + let (r, g) = (got(0), got(1)); + assert!((r - i32::from(red[i])).abs() <= 1, "{tone} {amount} pl {preserve} at {x}: red {r} vs Photoshop {}", red[i]); + assert!((g - i32::from(green[i])).abs() <= 1, "{tone} {amount} pl {preserve} at {x}: green {g} vs Photoshop {}", green[i]); + } + } +} + +/// Photoshop, measured (8-bit gray ramp, every channel): whole settings, where the tones fold +/// into one Levels per channel (#3423). The issue's midtones red +100 / magenta −100 (the +/// shadow toe), its sequoia14 layer with Preserve Luminosity off and on, all nine sliders with +/// Preserve Luminosity on, a black point past the white point, and lowered shadows with raised +/// highlights (their gammas cancel: a straight line between the two points). +#[test] +fn color_balance_whole_settings_match_photoshop() { + const X: [u8; 12] = [0, 4, 8, 16, 32, 64, 96, 128, 160, 192, 224, 255]; + type Case = ([[f32; 3]; 3], bool, [[u8; 12]; 3]); + let cases: [Case; 6] = [ + ( + [[0.0; 3], [100.0, -100.0, 0.0], [0.0; 3]], + false, + [[0, 16, 30, 55, 90, 128, 156, 181, 202, 221, 239, 255], [0, 0, 0, 1, 4, 16, 36, 64, 100, 145, 197, 255], X], + ), + ( + [[-6.0, 22.0, 5.0], [-1.0, -3.0, -8.0], [-1.0, -4.0, -6.0]], + false, + [ + [0, 0, 2, 9, 25, 56, 89, 122, 156, 188, 222, 255], + [0, 5, 9, 18, 35, 67, 100, 131, 163, 194, 225, 255], + [0, 3, 7, 14, 29, 60, 91, 123, 156, 189, 222, 255], + ], + ), + ( + [[-6.0, 22.0, 5.0], [-1.0, -3.0, -8.0], [-1.0, -4.0, -6.0]], + true, + [ + [0, 0, 0, 0, 5, 42, 80, 117, 154, 189, 226, 255], + [0, 4, 8, 16, 33, 66, 98, 130, 162, 195, 226, 255], + [0, 0, 0, 0, 15, 48, 82, 116, 151, 186, 221, 255], + ], + ), + ( + [[40.0, -30.0, 20.0], [-50.0, 25.0, 60.0], [30.0, -70.0, 10.0]], + true, + [ + [0, 1, 3, 9, 25, 69, 126, 193, 255, 255, 255, 255], + [0, 0, 0, 0, 0, 0, 46, 93, 136, 177, 217, 255], + [0, 0, 0, 0, 44, 107, 156, 199, 238, 255, 255, 255], + ], + ), + ( + [[100.0, -100.0, 0.0], [0.0; 3], [-100.0, 100.0, 0.0]], + true, + [X, [0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255], [0, 0, 0, 0, 0, 0, 0, 130, 255, 255, 255, 255]], + ), + ( + [[-76.0, -2.0, 60.0], [0.0; 3], [99.0, 0.0, -30.0]], + false, + [ + [0, 0, 0, 0, 0, 0, 71, 171, 255, 255, 255, 255], + [0, 2, 6, 14, 29, 61, 94, 126, 158, 191, 224, 255], + [0, 6, 11, 21, 39, 73, 106, 137, 168, 197, 227, 255], + ], + ), + ]; + for (tones, preserve, want) in cases { + for (ch, row) in want.iter().enumerate() { + for (x, w) in X.iter().zip(row) { + let got = (color_balance_channel(tones, preserve, ch, f32::from(*x) / 255.0) * 255.0).round() as i32; + assert!((got - i32::from(*w)).abs() <= 1, "{tones:?} pl {preserve} ch {ch} at {x}: {got} vs Photoshop {w}"); + } + } + } + // Hostile input stays in range. + for v in [f32::NAN, -1.0, 2.0, f32::INFINITY] { + let out = color_balance_channel([[f32::NAN, 1e9, -1e9]; 3], true, 7, v); + assert!((0.0..=1.0).contains(&out), "{v}: {out}"); + } +} + +#[test] +fn color_balance_midtones_with_multiple_sliders_preserve_luminosity() { + // A shared offset depends on the two extremes, not the sum of moved sliders. + // The old per-slider product leaves red/blue unchanged for [30, 0, 30]. + let tones = [[0.0; 3], [30.0, 0.0, 30.0], [0.0; 3]]; + for input in [0.25_f32, 0.5, 0.75] { + for (ch, offset) in [-0.15_f32, 0.15, -0.15].into_iter().enumerate() { + let expected = input.powf(2f32.powf(offset)); + let actual = color_balance_channel(tones, true, ch, input); + assert!((actual - expected).abs() < 1e-6, "channel {ch}, input {input}: {actual} vs {expected}"); + } + // Preserve Luminosity off must still affect only the moved channels. + assert_eq!(color_balance_channel(tones, false, 1, input), input); + // One moved slider retains its previous half-strength compensation. + let single = [[0.0; 3], [30.0, 0.0, 0.0], [0.0; 3]]; + assert!((color_balance_channel(single, true, 0, input) - input.powf(2f32.powf(-0.15))).abs() < 1e-6); + assert!((color_balance_channel(single, true, 1, input) - input.powf(2f32.powf(0.15))).abs() < 1e-6); + } +} + +#[test] +fn color_balance_curve_matches_the_per_sample_formula_bitwise() { + // The curve works out its sample-independent terms once; this is the formula it replaced, + // evaluated whole for every sample. + fn per_sample(tones: [[f32; 3]; 3], preserve_luminosity: bool, ch: usize, v: f32) -> f32 { + let [shadows, midtones, highlights] = tones.map(|t| t.map(|s| if s.is_finite() { s.clamp(-100.0, 100.0) } else { 0.0 })); + let own = |t: [f32; 3]| t.get(ch).copied().unwrap_or(0.0); + let max = |t: [f32; 3]| t[0].max(t[1]).max(t[2]); + let min = |t: [f32; 3]| t[0].min(t[1]).min(t[2]); + let (black, white, m) = if preserve_luminosity { + (max(shadows) - own(shadows), own(highlights) - min(highlights), own(midtones) - (max(midtones) + min(midtones)) / 2.0) + } else { + ((-own(shadows)).max(0.0), own(highlights).max(0.0), own(midtones) + (own(shadows) + own(highlights)) / 2.0) + }; + let (b, w) = (black / 255.0, 1.0 - white / 255.0); + let v = if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }; + if v >= w { + return 1.0; + } + if v <= b { + return 0.0; + } + let (u, gamma) = ((v - b) / (w - b), 2f32.powf(m / 100.0)); + let e = 1.0 / gamma.max(0.01); + let power = u.powf(e); + if gamma <= 1.0 { + return power; + } + let s0 = 2f32.powf(gamma); + let u0 = (2.0 * s0.powf(1.0 / (e - 1.0))).min(1.0); + if u0.is_nan() || u0 <= 0.0 || u >= u0 { + return power; + } + let (p, d, t) = (u0.powf(e), e * u0.powf(e - 1.0), u / u0); + let (t2, t3) = (t * t, t * t * t); + ((t3 - 2.0 * t2 + t) * u0 * s0 + (3.0 * t2 - 2.0 * t3) * p + (t3 - t2) * u0 * d).clamp(0.0, 1.0) + } + let mut seed = 0x9e37_79b9_u32; + let mut slider = || { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + (seed % 241) as f32 - 120.0 + }; + let mut settings = vec![[[0.0; 3]; 3], [[f32::NAN, 1e9, -1e9]; 3], [[-100.0; 3], [100.0; 3], [100.0; 3]]]; + settings.extend((0..120).map(|_| std::array::from_fn(|_| std::array::from_fn(|_| slider())))); + let samples: Vec = (0..=1024).map(|i| i as f32 / 1024.0).chain([-0.5, 1.5, f32::NAN, f32::INFINITY]).collect(); + for tones in settings { + for preserve in [false, true] { + for ch in [0, 1, 2, 7] { + let curve = BalanceCurve::new(tones, preserve, ch); + for &v in &samples { + let (got, want) = (curve.eval(v), per_sample(tones, preserve, ch, v)); + assert_eq!(got.to_bits(), want.to_bits(), "{tones:?} {preserve} ch {ch} v {v}: {got} vs {want}"); + } + } + } + } +} + +#[test] +fn levels_and_curves_apply_each_channel_before_the_master() { + // These two affine tone adjustments describe the same mapping: + // channel(x) = 1 / 2 + x / 2, then master(x) = x / 2, so 0 maps to 0.25. + // Levels used to apply the master first (0 mapped to 0.5). + let line = |a: f32, b: f32| vec![CurvePoint { input: 0.0, output: a }, CurvePoint { input: 1.0, output: b }]; + let levels = Adjustment::Levels { + master: LevelsChannel { out_white: 0.5, ..Default::default() }, + per_channel: std::array::from_fn(|_| LevelsChannel { out_black: 0.5, ..Default::default() }), + space: ToneSpace::Rgb, + black: Default::default(), + }; + let curves = Adjustment::Curves { + master: line(0.0, 0.5), + per_channel: std::array::from_fn(|_| line(0.5, 1.0)), + space: ToneSpace::Rgb, + black: Vec::new(), + pencil: false, + }; + for depth in [None, Some(SampleType::U8), Some(SampleType::U16), Some(SampleType::F32)] { + let ll = tone_luts_depth(&levels, depth); + let cl = tone_luts_depth(&curves, depth); + for channel in 0..3 { + for index in [0, LUT_SIZE / 4, LUT_SIZE / 2, 3 * LUT_SIZE / 4, LUT_SIZE - 1] { + assert!( + (ll[channel][index] - cl[channel][index]).abs() < 0.01, + "{depth:?} channel {channel} sample {index}: Levels {} vs Curves {}", + ll[channel][index], + cl[channel][index] + ); + } + } + assert!((cl[0][0] - 0.25).abs() < 0.01, "{depth:?}: {}", cl[0][0]); + + // Exercise the compositor's real adjustment path, not only its LUT builder. + for adj in [&levels, &curves] { + let mut pixel = Buffer { rect: Rect::new(0, 0, 1, 1), px: vec![[0.0, 0.0, 0.0, 1.0]] }; + apply_depth(adj, &mut pixel, Transfer::Srgb, depth); + for channel in 0..3 { + assert!((pixel.px[0][channel] - 0.25).abs() < 0.01, "{depth:?}: {adj:?} rendered {:?}", pixel.px[0]); + } + } + } + + // Lab has no composite/master tone record. + let mut lab = curves.clone(); + let mut lab_without_master = curves; + if let Adjustment::Curves { space, .. } = &mut lab { + *space = ToneSpace::Lab; + } + if let Adjustment::Curves { master, space, .. } = &mut lab_without_master { + *space = ToneSpace::Lab; + *master = line(0.0, 1.0); + } + assert_eq!(tone_luts(&lab), tone_luts(&lab_without_master)); +} + +#[test] +fn identity_tone_in_every_space_is_identity() { + for space in [ToneSpace::Rgb, ToneSpace::Cmyk, ToneSpace::Lab] { + let mut a = Adjustment::identity_curves(); + if let Adjustment::Curves { space: s, .. } = &mut a { + *s = space; + } + let mut b = ramp(); + apply(&a, &mut b); + for (x, y) in b.px.iter().zip(ramp().px.iter()) { + for k in 0..3 { + assert!((x[k] - y[k]).abs() < 0.02, "{space:?} {x:?} {y:?}"); + } + } + } +} + +#[test] +fn cmyk_black_curve_darkens_and_lab_lightness_lifts() { + let line = |a: f32, b: f32| vec![CurvePoint { input: 0.0, output: a }, CurvePoint { input: 1.0, output: b }]; + // Black brightness 1 -> 0.5: more black ink everywhere. + let a = Adjustment::Curves { + master: line(0.0, 1.0), + per_channel: [line(0.0, 1.0), line(0.0, 1.0), line(0.0, 1.0)], + space: ToneSpace::Cmyk, + black: line(0.0, 0.5), + pencil: false, + }; + let mut b = Buffer { rect: Rect::new(0, 0, 1, 1), px: vec![[0.8, 0.8, 0.8, 1.0]] }; + apply(&a, &mut b); + assert!(b.px[0][0] < 0.7, "{:?}", b.px[0]); + // Lab lightness 0..1 -> 0.2..1 lifts a dark grey; a/b untouched keeps it grey. + let a = Adjustment::Curves { + master: line(1.0, 0.0), // ignored in Lab + per_channel: [line(0.2, 1.0), line(0.0, 1.0), line(0.0, 1.0)], + space: ToneSpace::Lab, + black: Vec::new(), + pencil: false, + }; + let mut b = Buffer { rect: Rect::new(0, 0, 1, 1), px: vec![[0.2, 0.2, 0.2, 1.0]] }; + apply(&a, &mut b); + let p = b.px[0]; + assert!(p[0] > 0.3 && (p[0] - p[2]).abs() < 0.02, "{p:?}"); +} + +#[test] +fn hue_ranges_only_touch_their_colours() { + let mut ranges = HueRange::defaults(); + ranges[0].saturation = -100.0; // desaturate reds + let a = Adjustment::HueSaturation { hue: 0.0, saturation: 0.0, lightness: 0.0, colorize: false, ranges }; + let mut b = Buffer { rect: Rect::new(0, 0, 3, 1), px: vec![[0.9, 0.1, 0.1, 1.0], [0.1, 0.1, 0.9, 1.0], [0.5, 0.5, 0.5, 1.0]] }; + apply(&a, &mut b); + let red = b.px[0]; + assert!((red[0] - red[1]).abs() < 0.05, "red desaturated {red:?}"); + assert!((b.px[1][2] - 0.9).abs() < 1e-4 && (b.px[1][0] - 0.1).abs() < 1e-4, "blue untouched {:?}", b.px[1]); + assert_eq!(b.px[2], [0.5, 0.5, 0.5, 1.0]); +} + +#[test] +fn colorize_at_zero_saturation_is_grey() { + // Photoshop: Colorize at 0% saturation leaves no colour, only the pixel's lightness (#2326). + let px = vec![[0.9, 0.2, 0.1, 1.0], [0.1, 0.6, 0.8, 1.0], [0.5, 0.5, 0.5, 1.0]]; + for depth in [None, Some(SampleType::U8), Some(SampleType::U16), Some(SampleType::F32)] { + for lightness in [0.0, 30.0, -30.0] { + let a = Adjustment::HueSaturation { hue: 200.0, saturation: 0.0, lightness, colorize: true, ranges: HueRange::defaults() }; + let mut b = Buffer { rect: Rect::new(0, 0, 3, 1), px: px.clone() }; + apply_depth(&a, &mut b, Transfer::Srgb, depth); + for p in &b.px { + assert!((p[0] - p[1]).abs() < 1e-4 && (p[1] - p[2]).abs() < 1e-4, "{depth:?} lightness {lightness}: {p:?}"); + } + } + // Low saturations still tint: the old 25% floor no longer hides them. + let tint = |saturation: f32| { + let a = Adjustment::HueSaturation { hue: 0.0, saturation, lightness: 0.0, colorize: true, ranges: HueRange::defaults() }; + let mut b = Buffer { rect: Rect::new(0, 0, 1, 1), px: vec![[0.5, 0.5, 0.5, 1.0]] }; + apply_depth(&a, &mut b, Transfer::Srgb, depth); + b.px[0][0] - b.px[0][2] + }; + assert!(tint(10.0) > 0.05 && tint(10.0) < tint(25.0), "{depth:?}: 10% {} vs 25% {}", tint(10.0), tint(25.0)); + } +} + +/// Photoshop 27.11, measured: Hue/Saturation raising saturation, and Colorize with Lightness. +#[test] +fn hue_saturation_matches_photoshop() { + // (input, hue, saturation, lightness, colorize, Photoshop's output) + type Case = ([u8; 3], f32, f32, f32, bool, [u8; 3]); + let measured: [Case; 8] = [ + ([204, 102, 102], 0.0, 50.0, 0.0, false, [254, 51, 51]), + ([204, 159, 102], 0.0, 50.0, 0.0, false, [254, 164, 51]), + ([204, 102, 102], 0.0, -50.0, 0.0, false, [178, 127, 127]), + ([0, 0, 0], 120.0, 100.0, 30.0, true, [0, 152, 0]), + ([28, 28, 28], 120.0, 100.0, 30.0, true, [0, 192, 0]), + ([160, 160, 160], 30.0, 25.0, -40.0, true, [120, 96, 73]), + ([252, 252, 252], 30.0, 25.0, -40.0, true, [177, 151, 126]), + ([255, 143, 0], 30.0, 25.0, -40.0, true, [95, 76, 58]), + ]; + for (input, hue, saturation, lightness, colorize, want) in measured { + let a = Adjustment::HueSaturation { hue, saturation, lightness, colorize, ranges: HueRange::defaults() }; + let c = input.map(|v| v as f32 / 255.0); + let mut b = Buffer { rect: Rect::new(0, 0, 1, 1), px: vec![[c[0], c[1], c[2], 1.0]] }; + apply(&a, &mut b); + for (i, w) in want.iter().enumerate() { + let got = b.px[0][i] * 255.0; + assert!((got - *w as f32).abs() <= 2.0, "{input:?} h{hue} s{saturation} l{lightness} colorize {colorize}, channel {i}: {got} vs {w}"); + } + } +} + +/// Photoshop 27.11, measured: a range's Lightness (Blues ±50) moves towards the brightest or darkest channel. +#[test] +fn range_lightness_matches_photoshop() { + let measured = [ + ([0u8, 29, 115], 0.5, [57u8, 71, 115]), + ([0, 64, 255], 0.5, [125, 157, 255]), + ([102, 128, 204], 0.5, [152, 165, 204]), + ([102, 128, 204], -0.5, [102, 115, 154]), + ([0, 18, 115], -0.5, [0, 9, 58]), + ]; + for (input, l, want) in measured { + let got = range_lightness(input.map(|v| v as f32 / 255.0), l); + for i in 0..3 { + assert!((got[i] * 255.0 - want[i] as f32).abs() <= 2.5, "{input:?} channel {i}: {} vs {}", got[i] * 255.0, want[i]); + } + } +} + +/// Photoshop's own render (merged image of psd-tools `adjustments/huesaturation_lightness_rgb.psd`, +/// layer "Hue/Saturation 1"): a dull magenta gets the whole range edit, as a vivid one does (#4089). +#[test] +fn hue_ranges_apply_in_full_to_dull_colours() { + let range = |lightness: f32, bounds: [f32; 4]| HueRange { hue: 0.0, saturation: 0.0, lightness, bounds }; + let ranges = [ + range(-11.0, [-57.0, 4.0, 82.0, 175.0]), + range(100.0, [12.0, 45.0, 75.0, 105.0]), + HueRange::neutral(2), + HueRange::neutral(3), + HueRange::neutral(4), + range(100.0, [-117.0, -50.0, 39.0, 104.0]), + ]; + let a = Adjustment::HueSaturation { hue: 0.0, saturation: 0.0, lightness: 17.0, colorize: false, ranges }; + let measured = [([126u8, 97, 120], [148u8, 148, 148]), ([131, 103, 125], [152, 152, 152]), ([95, 69, 90], [122, 122, 122])]; + for (input, want) in measured { + let c = input.map(|v| v as f32 / 255.0); + let mut b = Buffer { rect: Rect::new(0, 0, 1, 1), px: vec![[c[0], c[1], c[2], 1.0]] }; + apply(&a, &mut b); + for (i, w) in want.iter().enumerate() { + let got = b.px[0][i] * 255.0; + assert!((got - *w as f32).abs() <= 2.0, "{input:?} channel {i}: {got} vs {w}"); + } + } + // Greys have no hue, so the ranges leave them alone: only the master Lightness moves them. + let mut b = Buffer { rect: Rect::new(0, 0, 1, 1), px: vec![[0.4, 0.4, 0.4, 1.0]] }; + apply(&a, &mut b); + let p = b.px[0]; + assert!((p[0] - p[1]).abs() < 1e-6 && (p[1] - p[2]).abs() < 1e-6 && (p[0] - (0.4 + 0.6 * 0.17)).abs() < 1e-4, "{p:?}"); +} + +#[test] +fn black_white_weights() { + let d = [40.0, 60.0, 40.0, 60.0, 20.0, 80.0]; + assert!((black_white_gray([0.5; 3], &d) - 0.5).abs() < 1e-6, "greys keep their value"); + assert!((black_white_gray([1.0, 0.0, 0.0], &d) - 0.4).abs() < 1e-6); + assert!((black_white_gray([1.0, 1.0, 0.0], &d) - 0.6).abs() < 1e-6); + let mut w = d; + w[0] = 100.0; + assert!(black_white_gray([1.0, 0.0, 0.0], &w) > black_white_gray([1.0, 0.0, 0.0], &d)); +} + +/// #8537: 32-bit superwhites stay above 1 (Photoshop 27.11: 2.0 stays 2.0, neutrals cap at +/// 16, negatives go to 0); 8-bit still clips at 1. +#[test] +fn black_white_keeps_32_bit_superwhites() { + let adj = Adjustment::BlackWhite { weights: [40.0, 60.0, 40.0, 60.0, 20.0, 80.0], tint: None }; + let run = |depth, c: f32| { + let mut b = Buffer { rect: Rect::new(0, 0, 1, 1), px: vec![[c, c, c, 1.0]] }; + apply_depth(&adj, &mut b, Transfer::Srgb, Some(depth)); + b.px[0][0] + }; + assert_eq!(run(SampleType::F32, 2.0), 2.0); + assert_eq!(run(SampleType::F32, 20.0), 16.0); + assert_eq!(run(SampleType::F32, -0.5), 0.0); + assert_eq!(run(SampleType::U8, 2.0), 1.0); +} + +/// Photoshop 27.11, measured: Black & White (default weights) with Tint over greys. The tint +/// is blended like the Color blend mode: its hue and saturation at the grey's luminosity. +#[test] +fn black_white_tint_matches_photoshop() { + let weights = [40.0, 60.0, 40.0, 60.0, 20.0, 80.0]; + let measured: [([u8; 3], u8, [u8; 3]); 6] = [ + ([255, 0, 0], 24, [81, 1, 1]), + ([255, 0, 0], 120, [255, 64, 64]), + ([255, 0, 0], 240, [255, 235, 235]), + ([0xe1, 0xd3, 0xb3], 120, [133, 119, 87]), + ([0xe1, 0xd3, 0xb3], 24, [33, 24, 1]), + ([0x40, 0x20, 0x10], 120, [144, 112, 96]), + ]; + for (tint, grey, want) in measured { + let tint = Some(tint.map(|v| v as f32 / 255.0)); + let mut b = Buffer { rect: Rect::new(0, 0, 1, 1), px: vec![[grey as f32 / 255.0; 4]] }; + b.px[0][3] = 1.0; + apply(&Adjustment::BlackWhite { weights, tint }, &mut b); + for (i, w) in want.iter().enumerate() { + let got = b.px[0][i] * 255.0; + assert!((got - *w as f32).abs() <= 2.5, "tint {tint:?} grey {grey} channel {i}: {got} vs {w}"); + } + } +} + +#[test] +fn gradient_map_follows_the_w3c_luminosity() { + // Photoshop's Gradient Map is driven by 0.3 R + 0.59 G + 0.11 B (photoshop corpus rgb8 and + // rgb16 gradient-map.psd), not the Rec. 601 grey. + let stops = vec![(0.0, [0.0; 3]), (1.0, [1.0; 3])]; + for (c, t) in [([0.0, 1.0, 0.0], 0.59), ([1.0, 0.0, 0.0], 0.3), ([0.0, 0.0, 1.0], 0.11), ([0.2, 0.6, 0.9], 0.513)] { + let mut b = Buffer::filled(crate::Rect::new(0, 0, 1, 1), [c[0], c[1], c[2], 1.0]); + apply(&Adjustment::GradientMap { stops: stops.clone(), reverse: false, dither: false }, &mut b); + assert!((b.px[0][0] - t).abs() < 1e-5, "{c:?}: {}", b.px[0][0]); + } +} + +#[test] +fn gradient_map_dither_stays_close() { + let stops = vec![(0.0, [0.0; 3]), (1.0, [1.0; 3])]; + let mut a = ramp(); + let mut b = ramp(); + apply(&Adjustment::GradientMap { stops: stops.clone(), reverse: false, dither: false }, &mut a); + apply(&Adjustment::GradientMap { stops, reverse: false, dither: true }, &mut b); + assert!(a.px.iter().zip(&b.px).all(|(x, y)| (x[0] - y[0]).abs() <= 0.5 / 255.0 + 1e-6)); + assert!(a.px.iter().zip(&b.px).any(|(x, y)| x[0] != y[0])); +} + +/// `adj` applied in a Lab document to one encoded sRGB colour, returned as (L, a, b). +fn in_lab(adj: &Adjustment, c: [f32; 3]) -> [f32; 3] { + let mut b = Buffer::filled(crate::Rect::new(0, 0, 1, 1), [c[0], c[1], c[2], 1.0]); + apply_in(adj, &mut b, Transfer::Srgb, Some(SampleType::U8), ColorMode::Lab); + srgb_to_lab([b.px[0][0], b.px[0][1], b.px[0][2]]) +} + +/// A muted, in-gamut colour from (L, a, b). +fn lab(l: f32, a: f32, b: f32) -> [f32; 3] { + lab_to_srgb([l, a, b]) +} + +fn near(got: [f32; 3], want: [f32; 3], tol: f32) -> bool { + got.iter().zip(want).all(|(g, w)| (g - w).abs() <= tol) +} + +#[test] +fn lab_invert_flips_l_a_and_b() { + let got = in_lab(&Adjustment::Invert, lab(30.0, 12.0, -18.0)); + // n -> 1 - n: L -> 100 - L, a -> -a - 1, b -> -b - 1 (mirrored on the 0..255 grid). + assert!(near(got, [70.0, -13.0, 17.0], 0.6), "{got:?}"); + // On the screen colour it would not be a mirror in Lab. + let mut rgb = Buffer::filled(crate::Rect::new(0, 0, 1, 1), [0.0, 0.0, 0.0, 1.0]); + let c = lab(30.0, 12.0, -18.0); + rgb.px[0] = [c[0], c[1], c[2], 1.0]; + apply(&Adjustment::Invert, &mut rgb); + assert!(!near(srgb_to_lab([rgb.px[0][0], rgb.px[0][1], rgb.px[0][2]]), got, 1.0)); +} + +#[test] +fn sixteen_bit_lab_invert_keeps_greys_neutral() { + // 16-bit Lab Invert mirrors a and b around neutral (photoshop corpus lab16 invert.psd); + // 8-bit bytes land one step off it. + let mut b = Buffer::filled(crate::Rect::new(0, 0, 1, 1), [0.0, 0.0, 0.0, 1.0]); + let c = lab(40.0, 0.0, 0.0); + b.px[0] = [c[0], c[1], c[2], 1.0]; + apply_in(&Adjustment::Invert, &mut b, Transfer::Srgb, Some(SampleType::U16), ColorMode::Lab); + let got = srgb_to_lab([b.px[0][0], b.px[0][1], b.px[0][2]]); + assert!(near(got, [60.0, 0.0, 0.0], 0.05), "{got:?}"); + assert!(near(in_lab(&Adjustment::Invert, c), [60.0, -1.0, -1.0], 0.1)); +} + +/// `adj` applied in a CMYK document to one encoded sRGB colour. +fn in_cmyk(adj: &Adjustment, c: [f32; 3]) -> [f32; 3] { + let mut b = Buffer::filled(crate::Rect::new(0, 0, 1, 1), [c[0], c[1], c[2], 1.0]); + apply_in(adj, &mut b, Transfer::Srgb, Some(SampleType::U8), ColorMode::Cmyk); + [b.px[0][0], b.px[0][1], b.px[0][2]] +} + +#[test] +fn cmyk_invert_posterize_and_threshold_work_on_the_inks() { + use photocraft_color::convert::{cmyk_to_rgb, rgb_to_cmyk}; + // Paper inverts to all four inks at 100%, not to RGB black (photoshop corpus cmyk8 invert.psd). + assert!(near(in_cmyk(&Adjustment::Invert, [1.0; 3]), cmyk_to_rgb([1.0; 4]), 2e-3)); + let red = [0.9, 0.2, 0.1]; + assert!(near(in_cmyk(&Adjustment::Invert, red), cmyk_to_rgb(rgb_to_cmyk(red).map(|v| 1.0 - v)), 2e-3)); + let two = cmyk_to_rgb(rgb_to_cmyk(red).map(|v| if v >= 0.5 { 1.0 } else { 0.0 })); + assert!(near(in_cmyk(&Adjustment::Posterize { levels: 2 }, red), two, 2e-3)); + // Threshold's black is the black ink alone (threshold-128.psd), its white the paper. + let t = Adjustment::Threshold { level: 0.5 }; + assert!(near(in_cmyk(&t, [0.2; 3]), cmyk_to_rgb([0.0, 0.0, 0.0, 1.0]), 2e-3)); + assert!(near(in_cmyk(&t, [0.8; 3]), cmyk_to_rgb([0.0; 4]), 2e-3)); +} + +/// CMYK posterizes the stored value 1 - ink: with 3 levels an ink of 85 (stored 170) lands on +/// the middle step, 128 (stored 127), where posterizing the ink would drop it to none (psd-tools +/// posterize_cmyk.psd, levels 3 to 21, exact so). +#[test] +fn cmyk_posterize_works_on_the_stored_values() { + let mut ink = [85.0 / 255.0; 4]; + stored_channels(&Adjustment::Posterize { levels: 3 }, ColorMode::Cmyk, Some(SampleType::U8), &mut ink); + assert!(ink.iter().all(|v| (v * 255.0 - 128.0).abs() < 1e-3), "{ink:?}"); + assert_eq!(posterize(85.0 / 255.0, 3), 0.0, "posterizing the ink itself"); +} + +#[test] +fn cmyk_threshold_compares_the_inks_plain_luma() { + assert_eq!(ink_luma([0.0; 4]), 1.0); + assert_eq!(ink_luma([0.0, 0.0, 0.0, 1.0]), 0.0); + // Two greys either side of level 128 in photoshop corpus cmyk8 threshold-128.psd: black, + // then white (8-bit inks). + let at = |i: [f32; 4]| { + let mut ch = i.map(|v| v / 255.0); + stored_channels(&Adjustment::Threshold { level: 128.0 / 255.0 }, ColorMode::Cmyk, Some(SampleType::U8), &mut ch); + ch + }; + assert_eq!(at([144.0, 122.0, 121.0, 35.0]), [0.0, 0.0, 0.0, 1.0]); + assert_eq!(at([131.0, 110.0, 110.0, 19.0]), [0.0; 4]); +} + +#[test] +fn cmyk_brightness_contrast_curves_each_ink_from_paper() { + use photocraft_color::convert::{cmyk_to_rgb, rgb_to_cmyk}; + // The tone curve runs on each ink's stored value, 1 - ink (photoshop corpus cmyk8 + // brightness-contrast.psd and -legacy.psd): raising brightness takes ink away, and paper + // and solid ink stay put. + let red = [0.9, 0.2, 0.1]; + for legacy in [false, true] { + let adj = Adjustment::BrightnessContrast { brightness: 25.0, contrast: 30.0, legacy }; + let table = ink_brightness_contrast_lut(25.0, 30.0, legacy); + let want = cmyk_to_rgb(rgb_to_cmyk(red).map(|v| 1.0 - lut(&table, 1.0 - v))); + assert!(near(in_cmyk(&adj, red), want, 2e-3), "legacy {legacy}"); + assert!(near(in_cmyk(&adj, [1.0; 3]), [1.0; 3], 2e-3), "legacy {legacy}: paper"); + let solid = cmyk_to_rgb([1.0; 4]); + assert!(near(in_cmyk(&adj, solid), cmyk_to_rgb(rgb_to_cmyk(solid).map(|v| ink_through(&table, v))), 2e-3)); + } + // Legacy +25 / +30 on Photoshop's own 16-bit inks (photoshop corpus cmyk16 + // brightness-contrast-legacy.psd): contrast pivots at 128 in ink, 127 stored. + let legacy = ink_brightness_contrast_lut(25.0, 30.0, true); + for (ink, ps) in [(139.0, 108.0), (160.0, 137.99), (172.0, 155.13), (183.0, 170.85), (196.0, 189.42), (98.0, 49.42), (128.0, 92.28), (168.0, 149.42)] { + let got = ink_through(&legacy, ink / 255.0) * 255.0; + assert!((got - ps).abs() < 0.1, "ink {ink}: {got} vs Photoshop {ps}"); + } + let brighter = Adjustment::BrightnessContrast { brightness: 60.0, contrast: 0.0, legacy: false }; + let ink = ink_brightness_contrast_lut(60.0, 0.0, false); + assert!(ink_through(&ink, 0.5) < 0.5 && ink_through(&ink, 0.0) == 0.0 && (ink_through(&ink, 1.0) - 1.0).abs() < 1e-6); + // On the screen colour it would land elsewhere. + let mut rgb = Buffer::filled(crate::Rect::new(0, 0, 1, 1), [red[0], red[1], red[2], 1.0]); + apply(&brighter, &mut rgb); + assert!(!near(in_cmyk(&brighter, red), [rgb.px[0][0], rgb.px[0][1], rgb.px[0][2]], 0.01)); +} + +#[test] +fn lab_posterize_steps_l_a_and_b() { + let got = in_lab(&Adjustment::Posterize { levels: 2 }, lab(70.0, 20.0, -30.0)); + // Two levels: each normalised channel snaps to 0 or 1 (L 100, a and b at +127 / -128). + assert!(near(got, srgb_to_lab(lab_denorm([1.0, 1.0, 0.0])), 1e-3), "{got:?}"); + let grey = in_lab(&Adjustment::Posterize { levels: 255 }, lab(50.0, 0.0, 0.0)); + assert!(near(grey, [50.0, 0.0, 0.0], 1.1), "255 levels is within a step of the identity: {grey:?}"); +} + +#[test] +fn lab_threshold_splits_on_l_with_a_neutral_result() { + let t = Adjustment::Threshold { level: 0.5 }; + // A saturated blue (L ≈ 32) and yellow (L ≈ 97): black and white, nothing in between. + for (c, white) in [([0.0, 0.0, 1.0], false), ([1.0, 1.0, 0.0], true), (lab(52.0, 40.0, 30.0), true), (lab(48.0, -40.0, 30.0), false)] { + let mut b = Buffer::filled(crate::Rect::new(0, 0, 1, 1), [c[0], c[1], c[2], 1.0]); + apply_in(&t, &mut b, Transfer::Srgb, None, ColorMode::Lab); + let v = if white { 1.0 } else { 0.0 }; + assert_eq!(b.px[0], [v, v, v, 1.0], "{c:?}"); + } +} + +#[test] +fn lab_brightness_contrast_moves_l_only() { + for legacy in [false, true] { + let adj = Adjustment::BrightnessContrast { brightness: 40.0, contrast: 30.0, legacy }; + let before = [45.0, 15.0, -20.0]; + let got = in_lab(&adj, lab(before[0], before[1], before[2])); + assert!(got[0] > before[0] + 5.0, "{legacy}: L rises: {got:?}"); + assert!((got[1] - before[1]).abs() < 0.5 && (got[2] - before[2]).abs() < 0.5, "{legacy}: a, b kept: {got:?}"); + } +} + +#[test] +fn lab_gradient_map_follows_l() { + let stops = vec![(0.0, [1.0, 0.0, 0.0]), (1.0, [0.0, 0.0, 1.0])]; + for reverse in [false, true] { + let map = Adjustment::GradientMap { stops: stops.clone(), reverse, dither: false }; + // A grey and a saturated colour with the same L map to the same colour. + let grey = in_lab(&map, lab(60.0, 0.0, 0.0)); + let green = in_lab(&map, lab(60.0, -50.0, 40.0)); + assert!(near(grey, green, 1e-3), "{reverse}: {grey:?} vs {green:?}"); + let t = if reverse { 0.4 } else { 0.6 }; + let want = srgb_to_lab([1.0 - t, 0.0, t]); + assert!(near(grey, want, 0.05), "{reverse}: {grey:?} vs {want:?}"); + } +} + +#[test] +fn other_modes_and_adjustments_keep_the_screen_colour_path() { + let c = [0.2, 0.5, 0.7, 1.0]; + let lab_only = [Adjustment::Invert, Adjustment::Threshold { level: 0.47 }, Adjustment::Posterize { levels: 4 }]; + for adj in lab_only.iter().chain([&Adjustment::HueSaturation { hue: 30.0, saturation: 0.0, lightness: 0.0, colorize: false, ranges: HueRange::defaults() }]) + { + for mode in [ColorMode::Rgb, ColorMode::Cmyk, ColorMode::Grayscale, ColorMode::Lab] { + let (mut a, mut b) = (Buffer::filled(crate::Rect::new(0, 0, 1, 1), c), Buffer::filled(crate::Rect::new(0, 0, 1, 1), c)); + apply_in(adj, &mut a, Transfer::Srgb, None, mode); + apply_depth(adj, &mut b, Transfer::Srgb, None); + let own = (mode == ColorMode::Lab && lab_channel_adjustment(adj)) || (mode == ColorMode::Cmyk && cmyk_channel_adjustment(adj)); + assert_eq!(a.px == b.px, !own, "{adj:?} in {mode:?}"); + } + } + // Transparent pixels are left alone and odd values never panic. + let mut t = Buffer::filled(crate::Rect::new(0, 0, 2, 1), [f32::NAN, 2.0, -1.0, 0.0]); + for adj in lab_only.iter().chain([&Adjustment::GradientMap { stops: vec![], reverse: true, dither: true }]) { + for mode in [ColorMode::Lab, ColorMode::Cmyk] { + apply_in(adj, &mut t, Transfer::Srgb, None, mode); + let mut odd = Buffer::filled(crate::Rect::new(0, 0, 1, 1), [f32::NAN, f32::INFINITY, -3.0, 1.0]); + apply_in(adj, &mut odd, Transfer::Srgb, Some(SampleType::U16), mode); + } + } + assert!(t.px[0][1] == 2.0); +} diff --git a/crates/compose/src/cmyk.rs b/crates/compose/src/cmyk.rs index 52db6582d9..96a6df0ceb 100644 --- a/crates/compose/src/cmyk.rs +++ b/crates/compose/src/cmyk.rs @@ -712,5 +712,4 @@ pub fn render_cmyk_bands(doc: &Document, rect: Rect, band_rows: i32, mut sink } #[cfg(test)] -#[path = "cmyk_tests.rs"] mod tests; diff --git a/crates/compose/src/cmyk_tests.rs b/crates/compose/src/cmyk/tests.rs similarity index 100% rename from crates/compose/src/cmyk_tests.rs rename to crates/compose/src/cmyk/tests.rs diff --git a/crates/compose/src/composite.rs b/crates/compose/src/composite.rs new file mode 100644 index 0000000000..dccaed8c4b --- /dev/null +++ b/crates/compose/src/composite.rs @@ -0,0 +1,685 @@ +use super::content::{channel_weights, empty_in, recycle_buffer, render_content, restore_channels, scratch_buffer, surface_to_buffer}; +use super::ctx::Ctx; +use super::extents::{effects_frame, mask_k, mask_vals, shapeless_stroke_bounds}; +use super::fx_cache::effect_maps; +use super::*; + +/// Composite an isolated group's sibling list (bottom→top) onto `backdrop` (its own buffer). +pub(crate) fn composite_stack(layers: &[Layer], backdrop: &mut Buffer, cx: &Ctx) { + composite_stack_at(layers, backdrop, cx, advanced::Scope::ISOLATED); +} + +/// Composite a sibling list (bottom→top) onto `backdrop`; `scope` says where the stack sits (see +/// [`advanced::Scope`]: it decides what knockouts reveal). +pub(crate) fn composite_stack_at(layers: &[Layer], backdrop: &mut Buffer, cx: &Ctx, scope: advanced::Scope) { + // Shallow knockouts stop at the bottom of this stack: the backdrop it starts from. + let floor = (!scope.root && advanced::needs_floor(layers)).then(|| backdrop.clone()); + let mut i = 0; + while i < layers.len() { + let base = &layers[i]; + // Collect the clipping group: following layers with `clipped = true`. + let mut j = i + 1; + while j < layers.len() && layers[j].clipped && !base.clipped { + j += 1; + } + let clipped = &layers[i + 1..j]; + if base.visible { + let ko = advanced::knockout_target(base, floor.as_ref(), backdrop.rect, cx, scope); + composite_layer(base, clipped, backdrop, cx, ko.as_deref(), scope); + if let (LayerContent::Adjustment(_), Some(q)) = (&base.content, adjustment_quantum(cx.depth)) { + quantize(backdrop, q); + } + } + i = j.max(i + 1); + } +} + +/// Steps per unit of an integer document's samples: Photoshop applies adjustment layers to +/// buffers of the document's depth (8-bit: 255 levels, 16-bit: 32768), so their result is +/// rounded there; a steep curve then amplifies the rounding of its input exactly as in +/// Photoshop (psd-tools adjustment_nested_composition_4: 9.6 → 5.1 % of pixels off; +/// exposure_grayscale passes). Blends stay in float (quantising them too made other files +/// worse). +pub fn adjustment_quantum(depth: photocraft_color::SampleType) -> Option { + match depth { + photocraft_color::SampleType::U8 => Some(255.0), + photocraft_color::SampleType::U16 => Some(32768.0), + photocraft_color::SampleType::F32 => None, + } +} + +pub(crate) fn quantize(b: &mut Buffer, q: f32) { + for p in &mut b.px { + for v in p.iter_mut() { + *v = branchless_floor(*v * q + 0.5) / q; + } + } +} + +/// `x.floor()`, bit for bit (signed zeros, infinities and NaNs included), without a call: baseline +/// x86-64 has no SSE4.1 `roundss`, so `floor` is a software routine there, called once per sample +/// of the backdrop under every adjustment layer ([`quantize`]). This form has no branch, so the +/// loop vectorizes. +#[inline] +pub(crate) fn branchless_floor(x: f32) -> f32 { + // From 2^23 on every f32 is whole. Below it, adding and taking away 2^23 rounds to the + // nearest whole number; where that went up, step down. + const WHOLE: f32 = 8_388_608.0; + let a = x.abs(); + let r = ((a + WHOLE) - WHOLE).copysign(x); + let r = if r > x { r - 1.0 } else { r }; + if a < WHOLE { r } else { x } +} + +/// Blend an adjustment layer's result (`adjusted`) back into the backdrop it was made from, each +/// pixel by its coverage `ks` (opacity × mask) in blend mode `mode`. +fn blend_back(backdrop: &mut [[f32; 4]], adjusted: &[[f32; 4]], ks: impl Iterator, mode: BlendMode) { + for ((b, a), k) in backdrop.iter_mut().zip(adjusted).zip(ks) { + if k <= 0.0 { + continue; + } + let s = [a[0], a[1], a[2]]; + // Normal is the source as it is (`blend_rgb` gives exactly that), and most adjustment + // layers are Normal: no per-pixel mode dispatch for them. + let blended = if mode == BlendMode::Normal { s } else { blend::blend_rgb(mode, [b[0], b[1], b[2]], s) }; + *b = [b[0] + (blended[0] - b[0]) * k, b[1] + (blended[1] - b[1]) * k, b[2] + (blended[2] - b[2]) * k, b[3]]; + } +} + +/// Deterministic hash for Dissolve (document-coordinate based, so it is stable under tiling). +#[inline] +pub(crate) fn dissolve_noise(x: i32, y: i32) -> f32 { + let mut h = (x as u32).wrapping_mul(0x8da6_b343) ^ (y as u32).wrapping_mul(0xd816_3841) ^ 0x9e37_79b9; + h ^= h >> 15; + h = h.wrapping_mul(0x2c1b_3c6d); + h ^= h >> 12; + (h & 0xffff) as f32 / 65536.0 +} + +/// Whether `layer` replaces everything beneath it in its stack: a visible, unclipped fill layer +/// in Normal mode at full opacity and fill, without masks, effects, channel restrictions or Blend +/// If, whose fill is opaque everywhere (a solid colour, or a gradient whose colour and opacity +/// stops are all opaque). Normal blending at alpha 1 returns the layer's colour exactly, so the +/// layers below can be skipped (the live Gradient tool's preview recomposites the whole canvas on +/// every pointer move). +pub fn occludes_below(layer: &Layer, mode: photocraft_color::ColorMode) -> bool { + let LayerContent::Fill(f) = &layer.content else { return false }; + let opaque = match f { + Fill::Solid(c) => c.alpha >= 1.0, + Fill::Gradient { stops, opacity_stops, .. } => { + !stops.is_empty() && stops.iter().all(|(_, c)| c.alpha >= 1.0) && opacity_stops.iter().all(|(_, o)| *o >= 1.0) + } + Fill::Pattern { .. } => false, + }; + // A cached render in use (a PSD's stored fill pixels) may not be opaque. + let cached = layer.fill_cache.as_ref().is_some_and(|c| c.fill == *f); + opaque + && !cached + && layer.visible + && !layer.clipped + && layer.blend == photocraft_color::BlendMode::Normal + && layer.opacity >= 1.0 + && layer.fill_opacity >= 1.0 + && !layer.mask.as_ref().is_some_and(|m| m.enabled) + && !layer.vector_mask.as_ref().is_some_and(|m| m.enabled) + && !effects::has_effects(layer) + && layer.excluded_channels == 0 + && !blend_if_active(layer, mode) +} + +/// Whether Blending Options › Blend If changes how `layer` composites in a `mode` document. +/// RGB documents test Gray and R, G, B; grayscale (and duotone) documents their one channel. +/// Other modes composite in display RGB, where ranges over their own channels have no exact +/// equivalent, so (like channel restrictions) the setting round-trips but isn't applied there. +pub fn blend_if_active(layer: &Layer, mode: photocraft_color::ColorMode) -> bool { + use photocraft_color::ColorMode as M; + matches!(mode, M::Rgb | M::Grayscale | M::Duotone) && !layer.blend_if.is_default() +} + +/// How much of a pixel shows through `layer`'s Blend If ranges, given the layer's own colour +/// (`this`, `None` where the layer has no content of its own there) and the colour beneath it +/// (`under`, `None` where nothing is beneath). Every range multiplies in. +fn blend_if_weight(layer: &Layer, mode: photocraft_color::ColorMode, this: Option<[f32; 4]>, under: Option<[f32; 4]>) -> f32 { + use photocraft_color::ColorMode as M; + let bi = &layer.blend_if; + let mut k = 1.0; + for (side, px) in [this, under].into_iter().enumerate() { + let Some(p) = px else { continue }; + let v = |c: usize| blend_if_level(p[c]); + match mode { + // Gray is the colour channels' luma (Rec. 601 weights), then R, G, B. + M::Rgb => { + let gray = 0.299 * v(0) + 0.587 * v(1) + 0.114 * v(2); + k *= bi.get(0)[side].weight(gray); + for c in 0..3 { + k *= bi.get(c + 1)[side].weight(v(c)); + } + } + // One channel: the PSD spec marks the composite-gray entry irrelevant here, so the + // channel's own entry carries the setting; both are honoured. + _ => k *= bi.get(0)[side].weight(v(0)) * bi.get(1)[side].weight(v(0)), + } + if k <= 0.0 { + return 0.0; + } + } + k +} + +/// A channel value on Blend If's 0..=255 scale. Compositing can leave an 8- or 16-bit level a few +/// millionths off (a level-20 backdrop composited at partial alpha reads 19.999998), which would +/// put it on the wrong side of a hard point at that level: a value that close to a level is that +/// level. Values of those depths that aren't on a level are at least 1/257 away from one. The GPU +/// compositor (`compose.wgsl` `blend_if_weight`) snaps alike. +fn blend_if_level(x: f32) -> f32 { + let v = x.clamp(0.0, 1.0) * 255.0; + let r = v.round(); + if (v - r).abs() < 1e-4 { r } else { v } +} + +/// Blend If groups inside one another whose own colour is still rendered separately. Each extra +/// level multiplies the work by the tree's depth, so the cost is polynomial, not exponential. +const MAX_BLEND_IF_GROUP_DEPTH: u32 = 2; + +thread_local! { + /// Blend If groups being rendered for their own colour on this thread. + static BLEND_IF_GROUPS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Apply `layer`'s Blend If to a finished composite: `out` (the backdrop with the layer drawn) +/// is mixed back towards `before` (the backdrop without it) where the ranges hide the layer. +/// Mixing premultiplied colour by `k` equals compositing the layer at `k` × its alpha, since +/// every blend mode's source-over result is linear in the source alpha. +fn apply_blend_if(layer: &Layer, before: &Buffer, out: &mut Buffer, cx: &Ctx) { + // "This Layer" is the layer's own colour; adjustment layers (no content of their own) are + // judged by their result. So are groups nested deeper than `MAX_BLEND_IF_GROUP_DEPTH` Blend + // Ifs: a group's own colour re-composites its children, which doubles the work at every + // level of Blend If groups inside one another. + let is_group = matches!(layer.content, LayerContent::Group(_)); + let nested = BLEND_IF_GROUPS.with(std::cell::Cell::get); + let own = if matches!(layer.content, LayerContent::Adjustment(_)) || (is_group && nested >= MAX_BLEND_IF_GROUP_DEPTH) { + None + } else { + BLEND_IF_GROUPS.with(|d| d.set(nested + u32::from(is_group))); + let own = render_content(layer, out.rect, cx); + BLEND_IF_GROUPS.with(|d| d.set(nested)); + own + }; + for (i, (p, b)) in out.px.iter_mut().zip(&before.px).enumerate() { + let this = match &own { + Some(o) => Some(o.px[i]).filter(|q| q[3] > 0.0), + None => Some(*p), + }; + let under = Some(*b).filter(|q| q[3] > 0.0); + let k = blend_if_weight(layer, cx.mode, this, under); + if k >= 1.0 { + continue; + } + let a = b[3] + (p[3] - b[3]) * k; + *p = if a > 0.0 { + let c = |c: usize| ((b[c] * b[3] + (p[c] * p[3] - b[c] * b[3]) * k) / a).clamp(0.0, 1.0); + [c(0), c(1), c(2), a] + } else { + [0.0; 4] + }; + } +} + +/// Composite `layer` (plus its clipping group) onto `backdrop`, honouring its channel restrictions +/// and Blend If, and knocking out to `ko` when it has a knockout (see [`advanced`]). +pub(crate) fn composite_layer(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffer, cx: &Ctx, ko: Option<&Buffer>, scope: advanced::Scope) { + // Blend Clipped Layers as Group off: the base alone, then each clipped layer in its own mode. + if advanced::clips_individually(layer, clipped) { + advanced::composite_clipped_individually(layer, clipped, backdrop, cx, ko, scope); + return; + } + let w = channel_weights(layer, cx.mode); + let blend_if = blend_if_active(layer, cx.mode); + let before = (w.is_some() || blend_if).then(|| backdrop.clone()); + match ko { + Some(target) => advanced::knockout(layer, backdrop, target, false, cx, |b| composite_layer_any(layer, clipped, b, cx, scope)), + None => composite_layer_any(layer, clipped, backdrop, cx, scope), + } + if let Some(before) = &before { + if let Some(w) = w { + restore_channels(backdrop, before, w); + } + if blend_if { + apply_blend_if(layer, before, backdrop, cx); + } + } +} + +fn composite_layer_any(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffer, cx: &Ctx, scope: advanced::Scope) { + if let LayerContent::Group(g) = &layer.content + && let Some(ab) = &g.artboard + { + composite_artboard(layer, ab, clipped, backdrop, cx, scope); + return; + } + composite_layer_plain(layer, clipped, backdrop, cx, scope); +} + +/// An artboard: its background and the group, composited only inside the board (contents and +/// effects outside it are clipped away; the backdrop there is untouched). +fn composite_artboard(layer: &Layer, ab: &photocraft_doc::Artboard, clipped: &[Layer], backdrop: &mut Buffer, cx: &Ctx, scope: advanced::Scope) { + let board = ab.rect.intersect(&backdrop.rect); + if board.is_empty() { + return; + } + let (bw, w) = (board.width() as usize, backdrop.rect.width() as usize); + let row0 = |y: i32| (y - backdrop.rect.y0) as usize * w + (board.x0 - backdrop.rect.x0) as usize; + let mut sub = Buffer::transparent(board); + for y in board.y0..board.y1 { + let o = row0(y); + let so = (y - board.y0) as usize * bw; + sub.px[so..so + bw].copy_from_slice(&backdrop.px[o..o + bw]); + } + if let Some(bg) = ab.background.rgba() { + blend_into(&mut sub, &Buffer::filled(board, bg), BlendMode::Normal, 1.0); + } + composite_layer_plain(layer, clipped, &mut sub, cx, scope); + for y in board.y0..board.y1 { + let o = row0(y); + let so = (y - board.y0) as usize * bw; + backdrop.px[o..o + bw].copy_from_slice(&sub.px[so..so + bw]); + } +} + +/// The surface `render_content` reads `layer`'s pixels from, when that is all it draws. +pub(crate) fn pixel_surface(layer: &Layer) -> Option<&Surface> { + if matches!(layer.content, LayerContent::Group(_) | LayerContent::Fill(_) | LayerContent::Adjustment(_)) { + return None; + } + layer.surface() +} + +/// A pixel layer (nothing clipped to it) onto `backdrop`, read from its tiles a row at a time: +/// the same arithmetic as `render_content` + `blend_into_fill`, without a tile-sized copy of the +/// layer (a megabyte per 256² render tile). +pub(crate) fn composite_pixel_layer(layer: &Layer, surf: &Surface, backdrop: &mut Buffer, cx: &Ctx) { + let rect = backdrop.rect; + let w = rect.width() as usize; + if w == 0 { + return; + } + let mv = mask_vals(layer, rect, cx); + let gamma = text_gamma(layer); + let mut row = vec![[0.0f32; 4]; w]; + for (ry, dst) in backdrop.px.chunks_exact_mut(w).enumerate() { + let y = rect.y0 + ry as i32; + surf.read_rgba_into(Rect::new(rect.x0, y, rect.x1, y + 1), &mut row); + if let Some(m) = mv.as_ref().and_then(|m| m.get(ry * w..(ry + 1) * w)) { + for (p, k) in row.iter_mut().zip(m) { + p[3] *= k; + } + } + blend_span_fill(dst, &row, rect.x0, y, layer.blend, layer.opacity, layer.fill_opacity, gamma); + } +} + +pub(crate) fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffer, cx: &Ctx, scope: advanced::Scope) { + let rect = backdrop.rect; + // A TSL-off stroke base that is transparent here can still have visible clipped siblings; + // keep the full clipping path for it instead of the stroke-bounds shortcut. Other bases keep + // the usual skip (their clipped layers vanish with them). + if (clipped.is_empty() || shapeless_stroke_bounds(layer).is_none()) && empty_in(layer, rect) { + return; + } + let opacity = layer.opacity * layer.fill_opacity; + + // Pass-through groups composite their children straight into the backdrop. Below 100% fill + // Photoshop renders the group isolated, like Normal (psd-tools passthrough_fill_*: an + // adjustment inside no longer reaches the layers beneath), and so it does for a group that + // is the base of a clipping group and holds an adjustment layer (psd-tools + // passthrough_clipping_mask_adjustment: an Exposure inside leaves the layers beneath alone), + // while such a group's blend modes still reach the backdrop (passthrough_clipping_mask_blendmode). + let clip_base_adjusts = clipped.iter().any(|c| c.visible) + && matches!(&layer.content, LayerContent::Group(g) if g.children.iter().any(|c| c.visible && matches!(c.content, LayerContent::Adjustment(_)))); + if let LayerContent::Group(g) = &layer.content + && layer.blend == BlendMode::PassThrough + && layer.fill_opacity >= 1.0 + && !effects::has_effects(layer) + && !clip_base_adjusts + { + let needs_mix = opacity < 1.0 || layer.mask.is_some() || layer.vector_mask.is_some(); + let has_clipped = clipped.iter().any(|c| c.visible); + // Children can draw directly unless mixing or clipping needs the original backdrop. + let before = (needs_mix || has_clipped).then(|| backdrop.clone()); + composite_stack_at(&g.children, backdrop, cx, scope.pass_through()); + if needs_mix && let Some(before) = &before { + let mv = mask_vals(layer, rect, cx); + for (i, (p, a)) in backdrop.px.iter_mut().zip(&before.px).enumerate() { + let k = opacity * mask_k(&mv, i); + let b = *p; + // Coverage mixes premultiplied colour; the stored buffer remains straight alpha. + let wa = a[3] * (1.0 - k); + let wb = b[3] * k; + let alpha = wa + wb; + *p = if alpha > 0.0 { + let c = |c: usize| (a[c] * wa + b[c] * wb) / alpha; + [c(0), c(1), c(2), alpha] + } else { + [0.0; 4] + }; + } + } + // Layers clipped to a pass-through group sit atop the group's + // isolated rendering; their effect (isolated result with vs. without + // them, each placed over the original backdrop) is added to the + // pass-through result. Exact when the children blend Normal, close + // otherwise (matches psd-tools clipping-mask3/4/5). + if has_clipped && let (Some(before), Some(iso)) = (before, render_content(layer, rect, cx)) { + let mut clipped_iso = iso.clone(); + advanced::composite_clipped(clipped, &mut clipped_iso, cx); + let mut without = before.clone(); + blend_into(&mut without, &iso, BlendMode::Normal, opacity); + let mut with = before; + blend_into(&mut with, &clipped_iso, BlendMode::Normal, opacity); + for ((p, w), wo) in backdrop.px.iter_mut().zip(&with.px).zip(&without.px) { + // Work premultiplied so transparent areas stay consistent. + let pa = p[3]; + let mut pm = [p[0] * pa, p[1] * pa, p[2] * pa, pa]; + for c in 0..3 { + pm[c] += w[c] * w[3] - wo[c] * wo[3]; + } + pm[3] += w[3] - wo[3]; + let a = pm[3].clamp(0.0, 1.0); + *p = if a > 0.0 { [(pm[0] / a).clamp(0.0, 1.0), (pm[1] / a).clamp(0.0, 1.0), (pm[2] / a).clamp(0.0, 1.0), a] } else { [0.0; 4] }; + } + } + return; + } + + // Adjustment layers transform the backdrop, then blend the result back in. + if let LayerContent::Adjustment(adj) = &layer.content { + let mv = mask_vals(layer, rect, cx); + if mv.as_ref().is_some_and(|values| values.iter().all(|&value| opacity * value <= 0.0)) { + return; + } + let mut adjusted = scratch_buffer(rect); + adjusted.px.copy_from_slice(&backdrop.px); + cx.apply_adjustment(adj, &mut adjusted); + // Clipped layers onto an adjustment are uncommon; they composite atop the adjusted result. + advanced::composite_clipped(clipped, &mut adjusted, cx); + if layer.blend == BlendMode::Dissolve { + // An adjustment has no standalone source alpha. Its effective coverage comes from its + // own opacity and mask, not a continuous RGB mix (#3050). + for y in rect.y0..rect.y1 { + for x in rect.x0..rect.x1 { + let i = ((y - rect.y0) as usize) * rect.width() as usize + (x - rect.x0) as usize; + let k = opacity * mask_k(&mv, i); + if k > 0.0 && dissolve_noise(x, y) < k { + let a = adjusted.px[i]; + backdrop.px[i] = [a[0], a[1], a[2], backdrop.px[i][3]]; + } + } + } + } else { + match &mv { + Some(m) => blend_back(&mut backdrop.px, &adjusted.px, m.iter().map(|v| opacity * v), layer.blend), + None => blend_back(&mut backdrop.px, &adjusted.px, std::iter::repeat(opacity), layer.blend), + } + } + recycle_buffer(adjusted); + return; + } + + if effects::has_effects(layer) { + // Layer / Vector Mask Hides Effects: the effects are built without that mask, which then + // hides the finished layer and effects. + let src = advanced::effects_source(layer); + let hide = advanced::hiding_mask(layer, rect, cx); + let before = hide.as_ref().map(|_| backdrop.clone()); + composite_layer_effects(&src, clipped, backdrop, cx); + if let (Some(m), Some(b)) = (&hide, &before) { + advanced::apply_hiding_mask(backdrop, b, m); + } + return; + } + if let Some((mut content, stroke, mask)) = shape_parts(layer, clipped, rect, cx) { + advanced::composite_clipped(clipped, &mut content, cx); + for (i, (p, s)) in content.px.iter_mut().zip(&stroke.px).enumerate() { + *p = psblend::composite(BlendMode::Normal, *p, *s, 1.0); + p[3] *= mask_k(&mask, i); + } + blend_into_fill(backdrop, &content, layer.blend, layer.opacity, layer.fill_opacity, 1.0); + return; + } + if !matches!(layer.content, LayerContent::Group(_) | LayerContent::Fill(_) | LayerContent::Adjustment(_)) + && let Some(s) = layer.surface() + && layer.blend == BlendMode::Normal + && opacity >= 1.0 + && !clipped.iter().any(|c| c.visible) + && layer.mask.is_none() + && layer.vector_mask.is_none() + && text_gamma(layer) == 1.0 + && !psblend::LAB_MIX.with(|l| l.get()) + && backdrop.px.iter().all(|p| p[3] <= 0.0) + { + s.read_rgba_into(rect, &mut backdrop.px); + for p in &mut backdrop.px { + if p[3] <= 0.0 { + *p = [0.0; 4]; + } else if p[3] < 1.0 { + *p = psblend::composite_normal_rgb([0.0; 4], *p, 1.0); + } + } + return; + } + if clipped.is_empty() + && let Some(surf) = pixel_surface(layer) + { + return composite_pixel_layer(layer, surf, backdrop, cx); + } + let Some(mut content) = render_content(layer, rect, cx) else { return }; + advanced::composite_clipped(clipped, &mut content, cx); + blend_into_fill(backdrop, &content, layer.blend, layer.opacity, layer.fill_opacity, text_gamma(layer)); + recycle_buffer(content); +} + +/// A layer with effects (and its clipping group) onto `backdrop`. +fn composite_layer_effects(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffer, cx: &Ctx) { + let rect = backdrop.rect; + // Neighbourhoods are already captured by the full-region effect maps; + // content and effect application only need the output rectangle. + // A stroked shape's vector stroke stays above its clipped layers and interior effects. + let (mut content, vstroke) = match split_parts(layer, rect, cx) { + Some((fill, stroke, mask)) => (fill, Some((stroke, mask))), + None => { + let Some(content) = render_content(layer, rect, cx) else { return }; + (content, None) + } + }; + advanced::composite_clipped(clipped, &mut content, cx); + let vstroke = vstroke.as_ref().map(|(s, m)| effects::VectorStroke { stroke: s, mask: m.as_deref() }); + let maps = effect_maps(layer, rect, cx); + effects::composite_with_effects_prepared(layer, &content, backdrop, &maps, effects_frame(layer, cx.canvas), cx.patterns, vstroke); +} + +/// The coverage-mixing gamma of a layer: the text blending gamma +/// ([`psblend::set_text_gamma`], Photoshop's default 1.45) for type layers, else 1. +pub fn text_gamma(layer: &Layer) -> f32 { + if matches!(layer.content, LayerContent::Text(_)) { psblend::text_gamma() } else { 1.0 } +} + +/// A stroked shape layer with visible clipped layers: Photoshop draws the shape's vector stroke +/// above the clipped layers, so the base content is the fill alone and the stroke is laid on top +/// after clipping. See [`split_parts`]. +fn shape_parts(layer: &Layer, clipped: &[Layer], rect: Rect, cx: &Ctx) -> Option<(Buffer, Buffer, Option>)> { + if !clipped.iter().any(|c| c.visible) { + return None; + } + split_parts(layer, rect, cx) +} + +/// A stroked shape layer's (fill, vector stroke, mask values) over `rect`; `None` for other +/// layers. Fill and stroke are unmasked: the mask applies to them together. Layer effects paint +/// the fill's interior effects beneath the vector stroke (psd-tools stroke-composite: a colour +/// overlay leaves the stroke, the stroke effect covers it). +fn split_parts(layer: &Layer, rect: Rect, cx: &Ctx) -> Option<(Buffer, Buffer, Option>)> { + let LayerContent::Shape(sh) = &layer.content else { return None }; + sh.stroke.as_ref()?; + let (fs, ss) = shape_split::split(sh, cx.canvas, cx.depth)?; + Some((surface_to_buffer(&fs, rect), surface_to_buffer(&ss, rect), mask_vals(layer, rect, cx))) +} + +pub(crate) fn texture_ctx<'a>(layer: &Layer, region: Rect, cx: &Ctx<'a>) -> effects::TextureCtx<'a> { + let sb = effects_frame(layer, cx.canvas); + effects::TextureCtx { rect: region, patterns: cx.patterns.source(), anchor: layer.effects.reference.unwrap_or((f64::from(sb.x0), f64::from(sb.y0))) } +} + +/// Composite `layer` onto `base` restricted to the base's alpha (clipping mask semantics), +/// honouring its channel restrictions and Blend If. +pub(crate) fn composite_atop(layer: &Layer, base: &mut Buffer, cx: &Ctx) { + let w = channel_weights(layer, cx.mode); + let blend_if = blend_if_active(layer, cx.mode); + let before = (w.is_some() || blend_if).then(|| base.clone()); + composite_atop_any(layer, base, cx); + if let Some(before) = &before { + if let Some(w) = w { + restore_channels(base, before, w); + } + if blend_if { + apply_blend_if(layer, before, base, cx); + } + } +} + +fn composite_atop_any(layer: &Layer, base: &mut Buffer, cx: &Ctx) { + let rect = base.rect; + if let LayerContent::Adjustment(adj) = &layer.content { + let mut adjusted = base.clone(); + cx.apply_adjustment(adj, &mut adjusted); + let mv = mask_vals(layer, rect, cx); + for (i, p) in base.px.iter_mut().enumerate() { + let k = layer.opacity * layer.fill_opacity * mask_k(&mv, i); + let a = adjusted.px[i]; + if layer.blend == BlendMode::Dissolve { + let x = rect.x0 + (i % rect.width() as usize) as i32; + let y = rect.y0 + (i / rect.width() as usize) as i32; + if dissolve_noise(x, y) < k { + *p = [a[0], a[1], a[2], p[3]]; + } + continue; + } + let bl = blend::blend_rgb(layer.blend, [p[0], p[1], p[2]], [a[0], a[1], a[2]]); + for c in 0..3 { + p[c] += (bl[c] - p[c]) * k; + } + } + return; + } + if effects::has_effects(layer) { + // Effects of a clipped layer are clipped to the base too: render + // them over the base (treated as opaque) and keep the base's alpha. + // The full-region effect maps already capture their neighbourhoods. + // A mask that hides the effects applies to the finished result instead. + let hide = advanced::hiding_mask(layer, rect, cx); + let src = advanced::effects_source(layer); + let layer = src.as_ref(); + let (content, vstroke) = match split_parts(layer, rect, cx) { + Some((fill, stroke, mask)) => (fill, Some((stroke, mask))), + None => { + let Some(content) = render_content(layer, rect, cx) else { return }; + (content, None) + } + }; + let vstroke = vstroke.as_ref().map(|(s, m)| effects::VectorStroke { stroke: s, mask: m.as_deref() }); + let mut opaque = Buffer { rect, px: base.px.iter().map(|p| [p[0], p[1], p[2], 1.0]).collect() }; + let maps = effect_maps(layer, rect, cx); + effects::composite_with_effects_prepared(layer, &content, &mut opaque, &maps, effects_frame(layer, cx.canvas), cx.patterns, vstroke); + if let Some(m) = &hide { + let plain = Buffer { rect, px: base.px.iter().map(|p| [p[0], p[1], p[2], 1.0]).collect() }; + advanced::apply_hiding_mask(&mut opaque, &plain, m); + } + for (p, o) in base.px.iter_mut().zip(&opaque.px) { + if p[3] > 0.0 { + *p = [o[0], o[1], o[2], p[3]]; + } + } + return; + } + let Some(content) = render_content(layer, rect, cx) else { return }; + let opacity = layer.opacity * layer.fill_opacity; + let gamma = text_gamma(layer); + for (i, p) in base.px.iter_mut().enumerate() { + let alpha = p[3]; + if alpha <= 0.0 { + continue; + } + let s = content.px[i]; + if layer.blend == BlendMode::Dissolve { + // Clipping preserves the opaque base's alpha. Dissolve still selects source + // pixels by spatial coverage instead of continuously mixing the colours (#3052). + let x = rect.x0 + (i as i32 % rect.width() as i32); + let y = rect.y0 + (i as i32 / rect.width() as i32); + if dissolve_noise(x, y) < s[3] * opacity { + *p = [s[0], s[1], s[2], alpha]; + } + continue; + } + // Blend as if the base were opaque, then keep the base's alpha. + let r = blend::composite_gamma(layer.blend, [p[0], p[1], p[2], 1.0], s, opacity, gamma); + *p = [r[0], r[1], r[2], alpha]; + } +} + +/// Blend an isolated layer buffer into the backdrop. +fn blend_into(backdrop: &mut Buffer, src: &Buffer, mode: BlendMode, opacity: f32) { + blend_into_g(backdrop, src, mode, opacity, 1.0); +} + +/// [`blend_into_g`] for a layer's own `opacity` and `fill`: Fill is part of the blend for +/// Photoshop's special eight ([`psblend::composite_fill`]), plain coverage otherwise. +pub(crate) fn blend_into_fill(backdrop: &mut Buffer, src: &Buffer, mode: BlendMode, opacity: f32, fill: f32, gamma: f32) { + for_rows(backdrop, src, |dst, s, x0, y| blend_span_fill(dst, s, x0, y, mode, opacity, fill, gamma)); +} + +/// [`blend_into`] mixing coverage in a `gamma` space (type layers). +pub(crate) fn blend_into_g(backdrop: &mut Buffer, src: &Buffer, mode: BlendMode, opacity: f32, gamma: f32) { + for_rows(backdrop, src, |dst, s, x0, y| blend_span_g(dst, s, x0, y, mode, opacity, gamma)); +} + +/// Runs `f(backdrop row, src row, x0, y)` over the rows of two buffers covering the same rect. +fn for_rows(backdrop: &mut Buffer, src: &Buffer, mut f: impl FnMut(&mut [[f32; 4]], &[[f32; 4]], i32, i32)) { + let rect = backdrop.rect; + let w = (rect.width() as usize).max(1); + for (ry, (dst, s)) in backdrop.px.chunks_mut(w).zip(src.px.chunks(w)).enumerate() { + f(dst, s, rect.x0, rect.y0 + ry as i32); + } +} + +/// [`blend_into_fill`] of one row: `dst` and `src` start at pixel (`x0`, `y`). +#[allow(clippy::too_many_arguments)] +fn blend_span_fill(dst: &mut [[f32; 4]], src: &[[f32; 4]], x0: i32, y: i32, mode: BlendMode, opacity: f32, fill: f32, gamma: f32) { + if fill >= 1.0 || !psblend::fill_is_special(mode) { + return blend_span_g(dst, src, x0, y, mode, opacity * fill, gamma); + } + for (b, s) in dst.iter_mut().zip(src) { + if s[3] > 0.0 { + *b = psblend::composite_fill(mode, *b, *s, opacity, fill, gamma); + } + } +} + +/// [`blend_into_g`] of one row: `dst` and `src` start at pixel (`x0`, `y`). +fn blend_span_g(dst: &mut [[f32; 4]], src: &[[f32; 4]], x0: i32, y: i32, mode: BlendMode, opacity: f32, gamma: f32) { + // The blend space is constant in this loop. Some TLS implementations synchronise even a + // boolean read, so select the common Normal kernel once instead of once per pixel. + if mode == BlendMode::Normal && gamma == 1.0 && !psblend::LAB_MIX.with(|l| l.get()) { + return psblend::composite_normal_rgb_span(dst, src, opacity); + } + for (x, (b, s)) in (x0..).zip(dst.iter_mut().zip(src)) { + let mut s = *s; + if s[3] <= 0.0 { + continue; + } + if mode == BlendMode::Dissolve { + s[3] = if dissolve_noise(x, y) < s[3] * opacity { 1.0 } else { 0.0 }; + *b = blend::composite(BlendMode::Normal, *b, s, 1.0); + continue; + } + *b = blend::composite_gamma(mode, *b, s, opacity, gamma); + } +} diff --git a/crates/compose/src/content.rs b/crates/compose/src/content.rs new file mode 100644 index 0000000000..88ec2751a9 --- /dev/null +++ b/crates/compose/src/content.rs @@ -0,0 +1,241 @@ +use super::composite::{adjustment_quantum, composite_stack}; +use super::ctx::Ctx; +use super::extents::{effect_shape, effect_source_bounds, mask_vals, shapeless_stroke_bounds, transparent_outside}; +use super::fx_cache::effect_maps; +use super::*; + +/// Tile size for parallel rendering (tile results are independent). +pub const RENDER_TILE: i32 = 256; + +// One tile of scratch per worker; nested rendering takes its own buffer. +thread_local! { + static SCRATCH: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; +} + +pub(crate) fn scratch_buffer(rect: Rect) -> Buffer { + if rect.width() as usize * rect.height() as usize > (RENDER_TILE * RENDER_TILE) as usize { + return Buffer::transparent(rect); + } + let mut px = SCRATCH.with(|slot| std::mem::take(&mut *slot.borrow_mut())); + px.resize(rect.width() as usize * rect.height() as usize, [0.0; 4]); + Buffer { rect, px } +} + +pub(crate) fn recycle_buffer(buf: Buffer) { + if buf.px.capacity() <= (RENDER_TILE * RENDER_TILE) as usize { + SCRATCH.with(|slot| { + let mut slot = slot.borrow_mut(); + if slot.capacity() < buf.px.capacity() { + *slot = buf.px; + } + }); + } +} + +#[cfg(test)] +#[test] +fn scratch_reuse_preserves_pixels_and_bounds_retention() { + SCRATCH.with(|slot| slot.borrow_mut().clear()); + let rect = Rect::new(-2, -3, 18, 11); + for fmt in [photocraft_color::PixelFormat::RGBA8, photocraft_color::PixelFormat::RGBA16, photocraft_color::PixelFormat::RGBA32F] { + let s = Surface::with_default(fmt, &[0.2, 0.4, 0.6, 0.8]); + let buf = surface_to_scratch(&s, rect); + assert_eq!(buf, surface_to_buffer(&s, rect)); + let ptr = buf.px.as_ptr(); + recycle_buffer(buf); + let reused = surface_to_scratch(&Surface::new(fmt), rect); + assert_eq!(reused.px.as_ptr(), ptr); + assert!(reused.px.iter().all(|p| p == &[0.0; 4])); + let nested = scratch_buffer(rect); + assert_ne!(nested.px.as_ptr(), reused.px.as_ptr()); + recycle_buffer(nested); + recycle_buffer(reused); + } + let cached = SCRATCH.with(|slot| slot.borrow().as_ptr()); + let huge = scratch_buffer(Rect::new(0, 0, RENDER_TILE + 1, RENDER_TILE)); + recycle_buffer(huge); + SCRATCH.with(|slot| { + assert_eq!(slot.borrow().as_ptr(), cached); + assert!(slot.borrow().capacity() <= (RENDER_TILE * RENDER_TILE) as usize); + }); +} + +/// Render a layer's own content (no blending into the backdrop yet) into an isolated buffer. +/// Returns None for layers that operate on the backdrop (adjustments, pass-through groups). +pub(crate) fn render_content(layer: &Layer, rect: Rect, cx: &Ctx) -> Option { + let mut buf = match &layer.content { + LayerContent::Group(g) => { + let mut b = Buffer::transparent(rect); + composite_stack(&g.children, &mut b, cx); + b + } + LayerContent::Fill(f) => match &layer.fill_cache { + // Photoshop's own rendering, valid while the fill is unchanged. + Some(c) if c.fill == *f => surface_to_scratch(&c.surface, rect), + _ if cx.mode == photocraft_color::ColorMode::Cmyk => { + let frame = fill_frame(layer, cx.canvas); + let native_rect = if matches!(f, Fill::Solid(_)) { Rect::new(0, 0, 1, 1) } else { rect }; + match gradient_fill::render_cmyk_fill(f, native_rect, frame, cx.depth) { + Some(s) if matches!(f, Fill::Solid(_)) => Buffer::filled(rect, s.rgba(0, 0)), + Some(s) => surface_to_buffer(&s, rect), + None => render_fill(f, rect, frame, cx.patterns, adjustment_quantum(cx.depth)), + } + } + _ => render_fill(f, rect, fill_frame(layer, cx.canvas), cx.patterns, adjustment_quantum(cx.depth)), + }, + LayerContent::Adjustment(_) => return None, + _ => match layer.surface() { + Some(s) => surface_to_scratch(s, rect), + None => Buffer::transparent(rect), + }, + }; + if let Some(m) = mask_vals(layer, rect, cx) { + for (p, k) in buf.px.iter_mut().zip(&m) { + p[3] *= k; + } + } + Some(buf) +} + +/// The shape `layer`'s effect maps are built from over `rect` (row-major; for the GPU +/// compositor): its content's alpha (masks applied), joined with the [`effect_outline`] of a +/// filled shape. Zero for adjustment layers. +/// +/// See also [`stroke_frame`]. +pub fn layer_shape(doc: &Document, layer: &Layer, rect: Rect) -> Vec { + let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(doc.pixel_format().mode); + let cx = Ctx::for_doc(doc, &patterns); + effect_shape(layer, rect, &cx) +} + +/// The frame a gradient stroke `st` of `layer` is laid out in (`effects::FxMaps::stroke_frame`), +/// from the layer's cached effect maps; `None` when `st` isn't a gradient stroke of the layer. +/// For the GPU compositor. +pub fn stroke_frame(doc: &Document, layer: &Layer, st: &photocraft_doc::StrokeFx) -> Option { + if !matches!(st.paint, photocraft_doc::FxPaint::Gradient(_)) || !effects::has_effects(layer) { + return None; + } + let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(doc.pixel_format().mode); + let cx = Ctx::for_doc(doc, &patterns); + effect_maps(layer, doc.bounds(), &cx).stroke_frame(st) +} + +pub fn surface_to_buffer(s: &Surface, rect: Rect) -> Buffer { + let mut px = vec![[0.0f32; 4]; rect.width() as usize * rect.height() as usize]; + s.read_rgba_into(rect, &mut px); + Buffer { rect, px } +} + +fn surface_to_scratch(s: &Surface, rect: Rect) -> Buffer { + let mut buf = scratch_buffer(rect); + s.read_rgba_into(rect, &mut buf.px); + buf +} + +/// The frame a fill layer's gradient is laid out in ("Align with layer", Photoshop's default): +/// the layer's bounds, i.e. the area its masks reveal: a hide-all pixel mask's painted area, or +/// the vector mask's path; otherwise the canvas. +pub fn fill_frame(layer: &Layer, canvas: Rect) -> Rect { + let mut frame = canvas; + // "Align with layer" off: the canvas (the Gradient tool's live gradients). + if let LayerContent::Fill(Fill::Gradient { align: false, .. }) = &layer.content { + return frame; + } + if let Some(m) = &layer.mask + && m.enabled + && m.surface.default_pixel().first().is_some_and(|v| *v <= 0.0) + { + let b = bounds::content_bounds(&m.surface).intersect(&canvas); + if !b.is_empty() { + frame = b; + } + } + if let Some(vm) = &layer.vector_mask + && vm.enabled + && !vm.path.inverted + && let Some((x0, y0, x1, y1)) = vm.path.control_bounds() + { + let b = Rect::new(x0.floor() as i32, y0.floor() as i32, x1.ceil() as i32, y1.ceil() as i32).intersect(&frame); + if !b.is_empty() { + frame = b; + } + } + frame +} + +/// A fill layer's content over `canvas`, laid out in the frame its masks give it (as the +/// compositor does) but without applying the masks: the pixels a PSD fill layer stores. +pub fn render_fill_content(layer: &Layer, f: &Fill, canvas: Rect, patterns: &[Pattern]) -> Buffer { + let prepared = pattern::PreparedPatterns::new(patterns, pattern::PREPARED_PATTERN_BYTES); + render_fill(f, canvas, fill_frame(layer, canvas), &prepared, None) +} + +/// `quantum`: the document depth's levels, which a dithered gradient is rounded to +/// ([`gradient_fill::render_quantized`]); `None` keeps it in float. +pub(crate) fn render_fill(f: &Fill, rect: Rect, canvas: Rect, patterns: &pattern::PreparedPatterns<'_>, quantum: Option) -> Buffer { + match f { + Fill::Solid(c) => { + let rgb = c.to_rgb(); + Buffer::filled(rect, [rgb[0], rgb[1], rgb[2], c.alpha]) + } + // Gradient geometry relative to the layer's frame, independent of the render rect. + Fill::Gradient { .. } => Buffer { rect, px: gradient_fill::render_quantized(f, rect, canvas, quantum) }, + // Laid out from the layer's frame when linked; transparent if the pattern is missing. + Fill::Pattern { name, scale, id, angle, link, phase } => match patterns.get(id, name) { + Some(tile) => Buffer { rect, px: pattern::render(&tile, &pattern::Placement::new(canvas, *link, *phase, *scale, *angle), rect) }, + None => Buffer::transparent(rect), + }, + } +} + +/// `true` when a pixel-backed layer has nothing to contribute in `rect`: +/// no allocated tiles there, a transparent default, and no effects (which +/// could reach in from outside). Clipped layers depend on the base, so they +/// vanish with it. +pub(crate) fn empty_in(layer: &Layer, rect: Rect) -> bool { + if effects::has_effects(layer) { + // Effects reach at most `margin` beyond the layer's pixels (when it is transparent + // outside them; a group's from its children with their effects): render tiles away from a + // small text layer skip it entirely. + let canvas = Rect::new(i32::MIN / 4, i32::MIN / 4, i32::MAX / 4, i32::MAX / 4); + let bounds = shapeless_stroke_bounds(layer).unwrap_or_else(|| effect_source_bounds(layer, canvas)); + return transparent_outside(layer) && bounds.inflate(effects::margin(layer)).intersect(&rect).is_empty(); + } + match &layer.content { + LayerContent::Raster(_) | LayerContent::Text(_) | LayerContent::Shape(_) | LayerContent::Smart(_) => match layer.surface() { + Some(s) => !s.has_tiles_in(rect) && s.default_pixel().last().is_some_and(|a| *a <= 0.0) && s.format().alpha, + None => true, + }, + _ => false, + } +} + +/// Blending Options › Channels as per-channel weights over display RGB (1 = the layer's result, +/// 0 = the backdrop's value kept), or `None` when every channel blends. RGB documents map R, G, B +/// directly and a grayscale document's single channel covers all three; other modes composite in +/// display RGB, where a restriction to their own channels has no exact equivalent, so it is +/// ignored there. +pub fn channel_weights(layer: &Layer, mode: photocraft_color::ColorMode) -> Option<[f32; 3]> { + use photocraft_color::ColorMode as M; + let x = layer.excluded_channels; + if x == 0 { + return None; + } + let keep = |bit: u32| if x & (1 << bit) != 0 { 0.0 } else { 1.0 }; + match mode { + M::Rgb => Some([keep(0), keep(1), keep(2)]), + M::Grayscale | M::Duotone => Some([keep(0); 3]), + _ => None, + } + .filter(|w| w != &[1.0; 3]) +} + +/// Put back the backdrop's values in the channels a layer leaves out (`w` from +/// [`channel_weights`]); alpha stays the layer's result. +pub(crate) fn restore_channels(out: &mut Buffer, before: &Buffer, w: [f32; 3]) { + for (p, b) in out.px.iter_mut().zip(&before.px) { + for c in 0..3 { + p[c] = b[c] + (p[c] - b[c]) * w[c]; + } + } +} diff --git a/crates/compose/src/ctx.rs b/crates/compose/src/ctx.rs new file mode 100644 index 0000000000..38c150db55 --- /dev/null +++ b/crates/compose/src/ctx.rs @@ -0,0 +1,225 @@ +use super::content::empty_in; +use super::fx_cache::{effect_maps, fx_over_budget, layer_identity}; +use super::*; + +type VectorMaskSlot = std::sync::Arc>; + +#[derive(Default)] +pub(crate) struct RenderVectorMasks { + /// Compiled masks by content. Callers pass temporary clones (see `advanced.rs`), so an + /// address cannot identify a mask: a dropped clone's address is reused by the next one. + masks: std::sync::Mutex>, +} + +impl RenderVectorMasks { + pub(crate) fn values(&self, mask: &photocraft_doc::VectorMask, rect: Rect) -> Vec { + let slot = { + let mut masks = self.masks.lock().unwrap_or_else(|e| e.into_inner()); + match masks.iter().find(|(m, _)| m == mask) { + Some((_, slot)) => slot.clone(), + None => { + let slot = VectorMaskSlot::default(); + masks.push((mask.clone(), slot.clone())); + slot + } + } + }; + // Compilation is sequential. Rendering can enter Rayon and must happen after + // initialization, so waiting tiles cannot re-enter a slot still being built. + let compiled = slot.get_or_init(|| photocraft_vector::CompiledVectorMask::new(mask)); + compiled.render(rect) + } +} + +/// Rendering context shared down the tree. +pub(crate) struct Ctx<'a> { + /// Document canvas: fill layers and gradients are laid out relative to it, never to the render rect. + pub(crate) canvas: Rect, + /// Tone transfer used by adjustments that work in linear light. + pub(crate) transfer: adjust::Transfer, + /// Global light for layer effects. + pub(crate) light: photocraft_doc::GlobalLight, + /// Prepared document patterns, shared across all tiles and bands of this render call. + pub(crate) patterns: &'a pattern::PreparedPatterns<'a>, + /// The document's colour mode (channel restrictions name its channels). + pub(crate) mode: photocraft_color::ColorMode, + pub(crate) depth: photocraft_color::SampleType, + /// At most 1 MiB of tone tables, initialized once and shared by this render's tiles and bands. + pub(crate) tone_luts: Vec<(&'a photocraft_doc::Adjustment, std::sync::OnceLock<[Vec; 4]>)>, + pub(crate) vector_masks: RenderVectorMasks, + /// Effect maps used by this render, by cache key: built before the parallel tiles (see + /// [`prepare_effects`]) and held for the whole render (or band, for maps clipped to it: the + /// `bool`), so eviction can't force a rebuild. + pub(crate) fx_maps: std::sync::Mutex, bool)>>, + /// The rectangle being rendered (a band of [`render_bands`]); see [`effect_region`]. + pub(crate) fx_clip: std::sync::Mutex>, + /// The whole-region effect maps of this render's layers wouldn't fit in the effect cache + /// together ([`fx_over_budget`]), so local ones are clipped to the render rect (#8330). + pub(crate) fx_over_budget: bool, + /// The document being rendered (deep knockouts reveal its Background); `None` for a lone layer. + pub(crate) doc: Option<&'a Document>, + /// Effect-map identities of this render's document layers (see [`LayerKeys`]). + pub(crate) layer_keys: LayerKeys, +} + +/// Memo of [`layer_identity`] for the layers of the document being rendered. The identity depends +/// on the layer alone, not on the tile, so it is computed once per layer per render instead of +/// once per tile. Only layers that sit in the document tree are memoised by address: the document +/// is borrowed for the whole render, so no other object can live at such an address. Temporary +/// copies (`advanced::effects_source`) are never in the tree and always take the full path. +#[derive(Default)] +pub(crate) struct LayerKeys { + /// Addresses of every layer in the document tree, collected on first use. + in_doc: std::sync::OnceLock>, + ids: std::sync::Mutex>, + /// Identities computed (tests count them). + #[cfg(test)] + pub(crate) built: std::sync::atomic::AtomicUsize, +} + +impl LayerKeys { + pub(crate) fn identity(&self, layer: &Layer, doc: Option<&Document>) -> u64 { + let addr = std::ptr::from_ref(layer) as usize; + let in_doc = doc.is_some_and(|d| self.in_doc.get_or_init(|| doc_layer_addresses(d)).contains(&addr)); + if in_doc { + let mut ids = self.ids.lock().unwrap_or_else(|e| e.into_inner()); + // Computing an identity only hashes immutable layer data; it does not run Rayon + // work or re-enter this memo. Keep the miss and insertion atomic across callers. + *ids.entry(addr).or_insert_with(|| self.compute(layer)) + } else { + self.compute(layer) + } + } + + fn compute(&self, layer: &Layer) -> u64 { + use std::hash::Hasher; + #[cfg(test)] + self.built.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let mut h = std::collections::hash_map::DefaultHasher::new(); + layer_identity(layer, &mut h, &mut |_| {}); + h.finish() + } +} + +/// Addresses of all layers of `doc` (groups' children included). +fn doc_layer_addresses(doc: &Document) -> std::collections::HashSet { + let mut out = std::collections::HashSet::new(); + let mut todo: Vec<&Layer> = doc.layers.iter().collect(); + while let Some(l) = todo.pop() { + out.insert(std::ptr::from_ref(l) as usize); + if let LayerContent::Group(g) = &l.content { + todo.extend(g.children.iter()); + } + } + out +} + +impl<'a> Ctx<'a> { + pub(crate) fn for_doc(doc: &'a Document, patterns: &'a pattern::PreparedPatterns<'a>) -> Self { + Self { + doc: Some(doc), + canvas: doc.bounds(), + transfer: adjust::Transfer::for_document(doc.mode, doc.depth), + light: doc.global_light, + patterns, + mode: doc.mode, + depth: doc.depth, + vector_masks: RenderVectorMasks::default(), + fx_maps: Default::default(), + fx_clip: Default::default(), + fx_over_budget: fx_over_budget(&doc.layers, doc.bounds()), + layer_keys: Default::default(), + tone_luts: prepare_tones(&doc.layers, 0), + } + } + + /// Start rendering `rect`: effect maps clipped to the previous rectangle are let go. + pub(crate) fn set_fx_clip(&self, rect: Rect) { + let mut clip = self.fx_clip.lock().unwrap_or_else(|e| e.into_inner()); + if *clip != Some(rect) { + *clip = Some(rect); + self.fx_maps.lock().unwrap_or_else(|e| e.into_inner()).retain(|_, (_, clipped)| !*clipped); + } + } + + pub(crate) fn apply_adjustment(&self, adj: &photocraft_doc::Adjustment, buf: &mut Buffer) { + if let photocraft_doc::Adjustment::Levels { space, .. } | photocraft_doc::Adjustment::Curves { space, .. } = adj + && !matches!(adj, photocraft_doc::Adjustment::Levels { space: photocraft_doc::adjust::ToneSpace::Rgb, .. } if self.depth == photocraft_color::SampleType::F32) + && let Some((_, luts)) = self.tone_luts.iter().find(|(a, _)| std::ptr::eq(*a, adj)) + { + let identity = adjust::float_tone_identity(adj, Some(self.depth)); + if identity == [true; 3] { + return; + } + let extrapolate = adjust::float_tone_extrapolates(adj, Some(self.depth), self.mode); + adjust::apply_tone(buf, *space, luts.get_or_init(|| adjust::tone_luts_depth(adj, Some(self.depth))), identity, extrapolate); + } else { + adjust::apply_in(adj, buf, self.transfer, Some(self.depth), self.mode); + } + } +} + +pub(crate) fn prepare_tones(layers: &[Layer], depth: u32) -> Vec<(&photocraft_doc::Adjustment, std::sync::OnceLock<[Vec; 4]>)> { + let mut out = Vec::new(); + for layer in layers.iter().filter(|l| l.visible) { + if out.len() == 16 { + break; + } + match &layer.content { + LayerContent::Adjustment(a @ (photocraft_doc::Adjustment::Levels { .. } | photocraft_doc::Adjustment::Curves { .. })) => { + out.push((a, Default::default())) + } + LayerContent::Group(g) if depth < PREPARE_DEPTH => out.extend(prepare_tones(&g.children, depth + 1).into_iter().take(16 - out.len())), + _ => {} + } + } + out +} + +/// Deepest group nesting preparation walks (deeper layers prepare on demand). +pub(crate) const PREPARE_DEPTH: u32 = 64; + +/// Build the effect maps of every visible layer in `layers` (groups included) that can reach +/// `rect` before tiles render in parallel, layers concurrently on native targets, each build +/// inside `setting` (the tiles' thread-local colour setting). Tiles then only read finished maps: +/// none builds one while others need it (#276), and none duplicates another's build. Builds never +/// wait on each other (`cached_effect_maps`), so building them in parallel can't deadlock. +pub(crate) fn prepare_effects(layers: &[Layer], rect: Rect, cx: &Ctx, setting: impl Fn(&mut dyn FnMut()) + Sync) { + let mut todo = Vec::new(); + effect_layers(layers, rect, 0, &mut todo); + let build = |l: &std::borrow::Cow| { + setting(&mut || { + let _ = effect_maps(l, rect, cx); + }); + }; + #[cfg(not(target_arch = "wasm32"))] + if todo.len() > 1 { + use rayon::prelude::*; + todo.par_iter().for_each(build); + return; + } + todo.iter().for_each(build); +} + +/// The visible layers of `layers` (groups included) with effects that can reach `rect`. +pub(crate) fn effect_layers<'l>(layers: &'l [Layer], rect: Rect, depth: u32, out: &mut Vec>) { + let mut base_visible = true; + for l in layers { + if !l.clipped { + base_visible = l.visible; + } + // A clipping group is drawn only when its base is. + if !l.visible || !base_visible { + continue; + } + if effects::has_effects(l) && !empty_in(l, rect) { + // A mask that hides the effects is left out of the shape they are built from. + out.push(advanced::effects_source(l)); + } + if let LayerContent::Group(g) = &l.content + && depth < PREPARE_DEPTH + { + effect_layers(&g.children, rect, depth + 1, out); + } + } +} diff --git a/crates/compose/src/effects.rs b/crates/compose/src/effects.rs index cc24e479c3..adf0b7a7b0 100644 --- a/crates/compose/src/effects.rs +++ b/crates/compose/src/effects.rs @@ -32,6 +32,33 @@ use photocraft_geom::Rect; use crate::pattern::{PREPARED_PATTERN_BYTES, Placement, PreparedPatterns}; use crate::{Buffer, psblend}; +mod bevel; +mod blur; +mod composite; +mod distance; +mod paint; + +pub use bevel::{BEVEL_H_EPS, BevelGeom, BevelPaint, TextureCtx, bevel_chisel_h, bevel_geom, satin_distance}; +#[cfg(test)] +use bevel::{bevel_maps, satin_map}; +pub use blur::tent_kernel; +#[cfg(test)] +use blur::{blur, box_line, dilate, tent, tent_direct}; +pub(crate) use composite::{VectorStroke, build_maps_prepared, composite_with_effects_prepared, map_count}; +pub use composite::{build_maps, composite_with_effects, outline_share, premerges_layer, shadow_see_through, stroke_widths}; +pub use distance::{FieldKind, STROKE_CHAMFER_MAX, bevel_distance_fields, distance_field, stroke_outside_exact}; +#[cfg(test)] +use distance::{ + SharpEdges, THREADS, bevel_dist_inside, bevel_dist_outside, chamfer_nearest, dist_inside, dist_outside, edge_offset, edt, edt_nearest, par_units, + sharp_edges, +}; +use paint::dissolves; +pub use paint::{ + bevel_contour_lut, glow_gradient_gain, glow_lut, gradient_t, gradient_units, hash_noise, ranged_lut, sample_gradient, satin_lut, spread_split, +}; +#[cfg(test)] +use paint::{glow_map, lut_at, noise, offset, shadow_map}; + /// `true` if the layer has at least one enabled effect and the master switch is on. pub fn has_effects(layer: &Layer) -> bool { layer.effects.enabled && layer.effects.items.iter().any(Effect::enabled) @@ -149,1617 +176,6 @@ impl Map { } } -/// 1D squared distance transform (Felzenszwalb & Huttenlocher). -fn dt1(f: &[f32], out: &mut [f32], v: &mut [usize], z: &mut [f32], near: &mut [usize]) { - let n = f.len(); - let mut k = 0usize; - v[0] = 0; - z[0] = f32::NEG_INFINITY; - z[1] = f32::INFINITY; - for q in 1..n { - loop { - let p = v[k]; - let s = ((f[q] + (q * q) as f32) - (f[p] + (p * p) as f32)) / (2.0 * q as f32 - 2.0 * p as f32); - if s <= z[k] && k > 0 { - k -= 1; - continue; - } - if s <= z[k] { - // k == 0 and parabola dominates: replace. - v[0] = q; - z[0] = f32::NEG_INFINITY; - z[1] = f32::INFINITY; - break; - } - k += 1; - v[k] = q; - z[k] = s; - z[k + 1] = f32::INFINITY; - break; - } - } - k = 0; - for (q, o) in out.iter_mut().enumerate() { - while z[k + 1] < q as f32 { - k += 1; - } - let p = v[k]; - let d = q as f32 - p as f32; - *o = d * d + f[p]; - near[q] = p; - } -} - -/// Exact Euclidean distance from every pixel to the nearest pixel where -/// `inside` is true (0 on those pixels). -#[cfg(test)] -fn edt(inside: &[bool], w: usize, h: usize) -> Vec { - edt_nearest(inside, w, h).0 -} - -/// Maps with fewer pixels (or other units of work) than this are not worth spawning threads for. -const PAR_MIN: usize = 1 << 16; - -/// Most threads one pass uses (as for the blurs, [`rows_par`]). -const PAR_THREADS: usize = 16; - -#[cfg(test)] -thread_local! { - /// Test hook: the thread count [`par_threads`] gives on this thread, whatever the work. - static THREADS: std::cell::Cell> = const { std::cell::Cell::new(None) }; -} - -/// How many threads a pass over `work` pixels (or similar units) uses. -fn par_threads(work: usize) -> usize { - #[cfg(test)] - if let Some(n) = THREADS.with(std::cell::Cell::get) { - return n; - } - if cfg!(target_arch = "wasm32") || work < PAR_MIN { 1 } else { std::thread::available_parallelism().map_or(1, |n| n.get()).clamp(1, PAR_THREADS) } -} - -/// Runs `f(scratch, u, a_u, b_u)` for every unit `u` of two slices: unit `u` of `a` is -/// `a[u * unit_a..][..unit_a]` (the last may be shorter), the same of `b` with `unit_b`, which is 0 -/// when there is no second slice. `work` says how big the whole pass is ([`par_threads`]). Groups of -/// units go to scoped OS threads, each with a scratch value from `init`; not to rayon, as for -/// [`rows_par`]: maps are built from inside rayon tiles, where a waiting worker steals other tiles. -/// A unit is computed from its own arguments alone, so the result does not depend on the threads. -fn par_units( - work: usize, - a: &mut [A], - unit_a: usize, - b: &mut [B], - unit_b: usize, - init: impl Fn() -> S + Sync, - f: impl Fn(&mut S, usize, &mut [A], &mut [B]) + Sync, -) { - if unit_a == 0 { - return; - } - let units = a.len().div_ceil(unit_a); - let threads = par_threads(work).min(units); - if threads <= 1 { - run_units(&mut init(), 0, a, unit_a, b, unit_b, &f); - return; - } - // Many more groups than threads, so that a heavy one (an edge-rich stretch) does not hold the rest up. - let group = units.div_ceil(threads * 8).max(1); - let mut groups = Vec::new(); - let (mut rest_a, mut rest_b, mut first) = (a, b, 0usize); - while !rest_a.is_empty() { - let (ga, na) = rest_a.split_at_mut((group * unit_a).min(rest_a.len())); - let (gb, nb) = rest_b.split_at_mut((group * unit_b).min(rest_b.len())); - groups.push((first, ga, gb)); - (rest_a, rest_b, first) = (na, nb, first + group); - } - let queue = std::sync::Mutex::new(groups.into_iter()); - let worker = || { - let mut scratch = init(); - loop { - let next = queue.lock().unwrap_or_else(std::sync::PoisonError::into_inner).next(); - let Some((first, ga, gb)) = next else { break }; - run_units(&mut scratch, first, ga, unit_a, gb, unit_b, &f); - } - }; - std::thread::scope(|sc| { - // A thread that cannot be spawned leaves its share to the others. - for _ in 1..threads { - let _ = std::thread::Builder::new().spawn_scoped(sc, worker); - } - worker(); - }); -} - -fn run_units(scratch: &mut S, first: usize, a: &mut [A], unit_a: usize, b: &mut [B], unit_b: usize, f: &impl Fn(&mut S, usize, &mut [A], &mut [B])) { - for (k, ua) in a.chunks_mut(unit_a).enumerate() { - let ub = b.get_mut(k * unit_b..((k + 1) * unit_b).min(b.len())).unwrap_or(&mut []); - f(scratch, first + k, ua, ub); - } -} - -/// A `w × h` buffer of `fill`, then filled row by row through `f(y, row)`. -fn par_fill(w: usize, h: usize, fill: T, f: impl Fn(usize, &mut [T]) + Sync) -> Vec { - let mut out = vec![fill; w.saturating_mul(h)]; - par_units(out.len(), &mut out, w.max(1), &mut [] as &mut [()], 0, || (), |_, y, row, _| f(y, row)); - out -} - -/// Working buffers of the 1D distance transform, for lines of up to `n` pixels. -struct Dt1Scratch { - f: Vec, - o: Vec, - v: Vec, - z: Vec, - near: Vec, -} - -impl Dt1Scratch { - fn new(n: usize) -> Self { - Dt1Scratch { f: vec![0.0; n], o: vec![0.0; n], v: vec![0; n], z: vec![0.0; n + 1], near: vec![0; n] } - } -} - -/// [`edt`] plus the index of the nearest `inside` pixel (as `u32`: a map past 2³² pixels has no -/// nearest pixel to give, and every distance is then "far"). -/// -/// Both passes run line by line in parallel: the columns, then the rows. The columns' results are -/// kept column by column (`gc[x * h + y]`) so that each thread writes its own stretch of them. -fn edt_nearest(inside: &[bool], w: usize, h: usize) -> (Vec, Vec) { - const INF: f32 = 1e20; - let total = w.saturating_mul(h); - if total != inside.len() || total > u32::MAX as usize { - return (vec![INF; inside.len()], vec![0; inside.len()]); - } - let n = w.max(h); - let mut gc = vec![0.0f32; total]; - let mut nc = vec![0u32; total]; - par_units( - total, - &mut gc, - h.max(1), - &mut nc, - h.max(1), - || Dt1Scratch::new(n), - |t, x, g, near| { - for (y, f) in t.f[..h].iter_mut().enumerate() { - *f = if inside[y * w + x] { 0.0 } else { INF }; - } - dt1(&t.f[..h], &mut t.o[..h], &mut t.v, &mut t.z, &mut t.near[..h]); - g.copy_from_slice(&t.o[..h]); - for (d, &p) in near.iter_mut().zip(&t.near[..h]) { - *d = p as u32; - } - }, - ); - let mut g = vec![0.0f32; total]; - let mut nearest = vec![0u32; total]; - par_units( - total, - &mut g, - w.max(1), - &mut nearest, - w.max(1), - || Dt1Scratch::new(n), - |t, y, out, near| { - for (x, f) in t.f[..w].iter_mut().enumerate() { - *f = gc[x * h + y]; - } - dt1(&t.f[..w], &mut t.o[..w], &mut t.v, &mut t.z, &mut t.near[..w]); - for (x, (d, ne)) in out.iter_mut().zip(near.iter_mut()).enumerate() { - *d = t.o[x].sqrt(); - let px = t.near[x]; - *ne = (nc[px * h + y] as usize * w + px) as u32; - } - }, - ); - (g, nearest) -} - -/// Chamfer distance transform with a 5 × 5 mask of exact Euclidean step lengths (1, √2, √5), -/// plus the index of the nearest `inside` pixel (0 on inside pixels). Photoshop's effect -/// distances follow this metric: its stroke corners measure 3.236 = √5 + 1 at offset (1, 3) -/// and 3.650 = √5 + √2 at (2, 3), where the exact distances are 3.162 and 3.606. -#[cfg(test)] -fn chamfer_nearest(inside: &[bool], w: usize, h: usize) -> (Vec, Vec) { - chamfer_from(inside.iter().map(|&b| if b { 0.0 } else { CHAMFER_INF }).collect(), w, h) -} - -const CHAMFER_INF: f32 = 1e20; - -/// [`chamfer_nearest`] from per-pixel start values (`CHAMFER_INF` = not a seed): the result is -/// the minimum over seeds of start value + path length, so partly covered seeds can start at -/// their sub-pixel edge offset. -fn chamfer_from(mut d: Vec, w: usize, h: usize) -> (Vec, Vec) { - const S2: f32 = std::f32::consts::SQRT_2; - const S5: f32 = 2.236_068; - // Forward-pass neighbours (already visited in raster order); the backward pass mirrors them. - const FWD: [(i64, i64, f32); 8] = [(-1, 0, 1.0), (-1, -1, S2), (0, -1, 1.0), (1, -1, S2), (-1, -2, S5), (1, -2, S5), (-2, -1, S5), (2, -1, S5)]; - let mut near: Vec = (0..w * h).collect(); - let (wi, hi) = (w as i64, h as i64); - let relax = |x: i64, y: i64, sign: i64, d: &mut Vec, near: &mut Vec| { - let i = (y * wi + x) as usize; - let mut best = d[i]; - let mut bn = near[i]; - for &(ox, oy, wt) in &FWD { - let (nx, ny) = (x + ox * sign, y + oy * sign); - if nx < 0 || ny < 0 || nx >= wi || ny >= hi { - continue; - } - let j = (ny * wi + nx) as usize; - let c = d[j] + wt; - if c < best { - best = c; - bn = near[j]; - } - } - d[i] = best; - near[i] = bn; - }; - for y in 0..hi { - for x in 0..wi { - relax(x, y, 1, &mut d, &mut near); - } - } - for y in (0..hi).rev() { - for x in (0..wi).rev() { - relax(x, y, -1, &mut d, &mut near); - } - } - (d, near) -} - -/// Distance from each pixel centre outside the shape to the shape's edge. -/// Pixels with non-zero alpha are inside; the edge inside the nearest such -/// pixel is placed by its alpha (coverage), as Photoshop does. Inside pixels -/// get ≤ 0. -fn dist_outside(s: &Map) -> Vec { - dist_outside_by(s, Metric::Euclidean) -} - -/// Distance metric for effect distance fields. -#[derive(Clone, Copy, PartialEq)] -enum Metric { - /// Exact Euclidean (effect edges). - Euclidean, - /// 5 × 5 chamfer (inside strokes, spread / choke; see [`chamfer_nearest`]). - Chamfer, -} - -/// Outside width from which a stroke's outer edge uses the exact Euclidean transform instead of -/// the fitted 5 × 5 chamfer. -/// -/// The chamfer's level sets are octagons: measured against a point source, its distance exceeds -/// the Euclidean radius by up to `0.027 · r` px — 0.48 px at r = 18 (the widest outside stroke any -/// Photoshop oracle matches with the chamfer) and 1.6 px at r = 60, where a wide stroke's boundary -/// visibly facets (#3646). Half a pixel of deviation is reached at r ≈ 19, so strokes narrower -/// than 20 px keep the chamfer, whose sub-pixel edge seeding Photoshop matches at small offsets, -/// and wider ones stay round. -pub const STROKE_CHAMFER_MAX: f32 = 20.0; - -/// Whether a stroke whose outside edge is `out_w` px wide uses the exact Euclidean transform (round) -/// rather than the 5 × 5 chamfer's octagon ([`STROKE_CHAMFER_MAX`]). The CPU compositor and the GPU -/// compositor's `program_with` both call this, so a stroke picks the same field in each. -pub fn stroke_outside_exact(out_w: f32) -> bool { - out_w >= STROKE_CHAMFER_MAX -} - -fn dist_outside_by(s: &Map, m: Metric) -> Vec { - if m == Metric::Chamfer { - // Seeds start at their sub-pixel edge offset (1 − coverage). - let start = s.v.iter().map(|&a| if a > INSIDE_EPS { 1.0 - a.min(1.0) } else { CHAMFER_INF }).collect(); - let (d, _) = chamfer_from(start, s.w, s.h); - return d.iter().zip(&s.v).map(|(d, &a)| if a > INSIDE_EPS { -0.5 } else { d - 0.5 }).collect(); - } - let inside = covered(s, |a| a > INSIDE_EPS); - let (d, near) = edt_nearest(&inside, s.w, s.h); - par_fill(s.w, s.h, 0.0f32, |y, row| { - for (x, out) in row.iter_mut().enumerate() { - let i = y * s.w + x; - *out = if inside[i] { -0.5 } else { d[i] - 0.5 + (1.0 - s.v[near[i] as usize].min(1.0)) }; - } - }) -} - -/// Which pixels of `s` satisfy `test`, row by row in parallel. -fn covered(s: &Map, test: impl Fn(f32) -> bool + Sync) -> Vec { - par_fill(s.w, s.h, false, |y, row| { - for (e, &a) in row.iter_mut().zip(s.v.get(y * s.w..).unwrap_or_default()) { - *e = test(a); - } - }) -} - -/// Distance from each pixel centre inside the shape to the shape's edge -/// (≤ 0 outside). -fn dist_inside(s: &Map) -> Vec { - dist_inside_by(s, Metric::Euclidean) -} - -fn dist_inside_by(s: &Map, m: Metric) -> Vec { - if m == Metric::Chamfer { - // Partly covered edge pixels (alpha below their neighbourhood's) are seeds starting at - // their coverage, mirroring `dist_outside`: a 25 % edge column puts the edge 0.25 px in. - let cov = local_coverage(s); - let start = - s.v.iter() - .zip(&cov.v) - .map(|(&a, &c)| { - if a <= INSIDE_EPS { - 0.0 - } else if c < 1.0 - INSIDE_EPS { - c - } else { - CHAMFER_INF - } - }) - .collect(); - let (d, _) = chamfer_from(start, s.w, s.h); - return d.iter().zip(&s.v).map(|(d, &a)| if a <= INSIDE_EPS { -0.5 } else { d - 0.5 }).collect(); - } - let outside = covered(s, |a| a <= INSIDE_EPS); - let (d, _) = edt_nearest(&outside, s.w, s.h); - par_fill(s.w, s.h, 0.0f32, |y, row| { - for (x, out) in row.iter_mut().enumerate() { - let i = y * s.w + x; - *out = if outside[i] { -0.5 } else { d[i] - 0.5 }; - } - }) -} - -/// Alpha relative to the 3×3 neighbourhood maximum: separates edge coverage -/// from the fill's own opacity on shape layers. -fn local_coverage(s: &Map) -> Map { - let mut out = s.clone(); - for y in 0..s.h as i64 { - for x in 0..s.w as i64 { - let a = s.get(x, y); - if a <= INSIDE_EPS { - continue; - } - let mut mx = a; - for dy in -1..=1 { - for dx in -1..=1 { - mx = mx.max(s.get(x + dx, y + dy)); - } - } - out.v[y as usize * s.w + x as usize] = (a / mx).min(1.0); - } - } - out -} - -/// Signed distance from the centre of a pixel of coverage `a` to the straight edge crossing it, -/// positive when the centre is inside the shape. `n` is the edge's unit normal (its signs don't -/// matter). -/// -/// A unit pixel cut by a straight edge at distance `r` from its centre (on the side that holds at -/// most half of the pixel) is covered `1/2 - r/u` while the edge crosses two opposite sides, and -/// `((u + v)/2 - r)² / (2uv)` once it only cuts off a corner, with `u ≥ v` the larger and smaller -/// component of the normal. Inverting that places the edge by its coverage at any angle. For an -/// axis-aligned edge (`v = 0`) it is the `a - 1/2` that [`dist_outside`] assumes. -fn edge_offset(n: [f32; 2], a: f32) -> f32 { - if !a.is_finite() { - return 0.0; - } - let (u, v) = (n[0].abs().max(n[1].abs()), n[0].abs().min(n[1].abs())); - let (c, inside) = if a > 0.5 { (1.0 - a, true) } else { (a, false) }; - let c = c.clamp(0.0, 0.5); - // The coverage below which the edge only cuts off a corner. - let corner = if u > 0.0 { v / (2.0 * u) } else { 0.0 }; - let r = if c >= corner { (0.5 - c) * u } else { 0.5 * (u + v) - (2.0 * u * v * c).sqrt() }; - if inside { r } else { -r } -} - -/// A sharp, anti-aliased edge pixel: where it puts the straight edge crossing it. -#[derive(Clone, Copy)] -struct SharpEdge { - /// Signed distance from the pixel's centre to the edge, positive inside ([`edge_offset`]). - offset: f32, - /// The edge's unit normal pointing into the shape (`[0, 0]` when the coverage gives no direction). - normal: [f32; 2], -} - -/// Half the spacing of the edge pixels along an edge (at most √2 / 2, along a diagonal): a pixel -/// within it of the foot of the perpendicular sees the edge as a line, one further out as its end. -const EDGE_REACH: f32 = 0.75; - -impl SharpEdge { - /// Distance to the edge from the pixel `(dx, dy)` away from this one, positive on the shape's - /// side (`inside`) or on the empty side. It is the distance to the edge's line where the - /// perpendicular lands within [`EDGE_REACH`] of this pixel, and to the end of that stretch - /// beyond, so the distance to a straight edge is exact and does not follow the pixel staircase. - /// `None` when the edge has no direction or `(dx, dy)` is on the wrong side of it. - fn distance(&self, dx: f32, dy: f32, inside: bool) -> Option { - let [nx, ny] = self.normal; - if nx == 0.0 && ny == 0.0 { - return None; - } - let signed = self.offset + dx * nx + dy * ny; - let across = if inside { signed } else { -signed }; - let along = (dx * -ny + dy * nx).abs(); - (across > 0.0).then(|| across.hypot((along - EDGE_REACH).max(0.0))) - } -} - -/// A sharp edge pixel and where it sits. -#[derive(Clone, Copy)] -struct EdgePixel { - /// Index of the pixel in the map. - at: u32, - /// The pixel's coverage ([`local_coverage`] of it). - cov: f32, - edge: SharpEdge, -} - -/// The sharp edge pixels of a map: a short list, and for every pixel a 4 byte slot (0 = no edge, k = -/// the k-th of the list). Maps are big and edge pixels few, so a per-pixel `Option` (16 -/// bytes) made every pass over it, and the copies the refinement needs, memory-bound. -struct SharpEdges { - w: usize, - h: usize, - slot: Vec, - pixels: Vec, -} - -impl SharpEdges { - fn empty(w: usize, h: usize) -> Self { - SharpEdges { w, h, slot: Vec::new(), pixels: Vec::new() } - } - - /// The edge of pixel `i`, if it is a sharp edge pixel. - fn get(&self, i: usize) -> Option { - let k = (*self.slot.get(i)? as usize).checked_sub(1)?; - self.pixels.get(k).map(|p| p.edge) - } - - /// The edge of pixel `(x, y)`, if it is a sharp edge pixel (`None` off the map). - fn at(&self, x: usize, y: usize) -> Option { - if x >= self.w || y >= self.h { None } else { self.get(y * self.w + x) } - } - - fn has(&self, x: usize, y: usize) -> bool { - self.at(x, y).is_some() - } - - fn is_empty(&self) -> bool { - self.pixels.is_empty() - } - - /// Every sharp edge pixel, as (index in the map, its edge), in pixel order. - #[cfg(test)] - fn iter(&self) -> impl Iterator + '_ { - self.pixels.iter().map(|p| (p.at as usize, p.edge)) - } -} - -/// Where the sharp, anti-aliased edge pixels of `s` put the edge ([`edge_offset`], along the normal -/// the coverage gradient gives). Sharp pixels are partly covered and touch both an empty and a full -/// pixel; hard edges and soft ramps have none and keep the `alpha - 1/2` of [`dist_outside`]. -/// -/// An edge pixel is covered and has an empty neighbour, so a pass over which pixels are covered finds -/// the few candidates without computing [`local_coverage`] of the whole map; the coverage is then -/// worked out where it is needed, by the same formula. Rows are independent and go in parallel. -fn sharp_edges(s: &Map) -> SharpEdges { - let (w, h) = (s.w, s.h); - if w == 0 || h == 0 || s.v.len() != w * h || s.v.len() >= u32::MAX as usize { - return SharpEdges::empty(w, h); - } - let (wi, hi) = (w as i64, h as i64); - // `local_coverage` of the pixel at (x, y), on the map. - let cov_at = |x: i64, y: i64| -> f32 { - let a = s.v[y as usize * w + x as usize]; - if a <= INSIDE_EPS { - return a; - } - let mut mx = a; - for dy in -1..=1 { - for dx in -1..=1 { - mx = mx.max(s.get(x + dx, y + dy)); - } - } - (a / mx).min(1.0) - }; - // The coverage with the map's border repeated, for the gradient. - let cov_clamped = |x: i64, y: i64| cov_at(x.max(0).min(wi - 1), y.max(0).min(hi - 1)); - // Whether a pixel is not empty. Off the map counts as covered: only a neighbour on the map can be empty. - let solid = |x: i64, y: i64| -> bool { - if x < 0 || y < 0 || x >= wi || y >= hi { - return true; - } - let a = s.v[y as usize * w + x as usize]; - a.is_nan() || a > INSIDE_EPS - }; - let mut rows: Vec> = vec![Vec::new(); h]; - par_units( - w * h, - &mut rows, - 1, - &mut [] as &mut [()], - 0, - || (), - |_, y, row, _| { - let Some(row) = row.first_mut() else { return }; - let y = y as i64; - for x in 0..wi { - if !solid(x, y) || (-1..=1).all(|dy| (-1..=1).all(|dx| solid(x + dx, y + dy))) { - continue; - } - let i = (y * wi + x) as usize; - let c = cov_at(x, y); - if s.v[i] <= INSIDE_EPS || c >= 1.0 - INSIDE_EPS { - continue; - } - let (mut empty, mut full) = (false, false); - for (dx, dy) in (-1..=1).flat_map(|dy| (-1..=1).map(move |dx| (dx, dy))) { - let (nx, ny) = (x + dx, y + dy); - if (dx, dy) == (0, 0) || nx < 0 || ny < 0 || nx >= wi || ny >= hi { - continue; - } - empty |= s.get(nx, ny) <= INSIDE_EPS; - full |= cov_at(nx, ny) >= 1.0 - INSIDE_EPS; - } - if !(empty && full) { - continue; - } - let at = &cov_clamped; - let gx = (at(x + 1, y - 1) + 2.0 * at(x + 1, y) + at(x + 1, y + 1)) - (at(x - 1, y - 1) + 2.0 * at(x - 1, y) + at(x - 1, y + 1)); - let gy = (at(x - 1, y + 1) + 2.0 * at(x, y + 1) + at(x + 1, y + 1)) - (at(x - 1, y - 1) + 2.0 * at(x, y - 1) + at(x + 1, y - 1)); - let len = gx.hypot(gy); - let (normal, n) = if len.is_finite() && len > 1e-6 { ([gx / len, gy / len], [gx / len, gy / len]) } else { ([0.0, 0.0], [1.0, 0.0]) }; - row.push(EdgePixel { at: i as u32, cov: c, edge: SharpEdge { offset: edge_offset(n, c), normal } }); - } - }, - ); - let mut pixels: Vec = Vec::with_capacity(rows.iter().map(Vec::len).sum()); - for row in rows { - pixels.extend(row); - } - let mut slot = vec![0u32; w * h]; - for (k, p) in pixels.iter().enumerate() { - if let Some(s) = slot.get_mut(p.at as usize) { - *s = k as u32 + 1; - } - } - refine_edge_normals(&mut pixels, &slot, w, h); - SharpEdges { w, h, slot, pixels } -} - -/// How far (in pixels) around an edge pixel [`refine_edge_normals`] looks for its neighbours. -const NORMAL_RADIUS: i64 = 3; - -/// The 3×3 gradient of the coverage gives an edge's direction to 1-2 degrees, and its error is -/// systematic, so it tilts the distance of every pixel the same way and shows as a faint ripple. -/// The edge points of a straight edge's pixels (each pixel's centre moved to its edge) lie on one -/// line, and the line through the points of the pixels around one gives the direction to a fraction -/// of a degree. Where those points are not on a line (corners, tight curves) the gradient's normal -/// stays. -fn refine_edge_normals(pixels: &mut [EdgePixel], slot: &[u32], w: usize, h: usize) { - let (wi, hi) = (w as i64, h as i64); - let points: Vec<[f32; 2]> = pixels - .iter() - .map(|p| [(p.at as i64 % wi) as f32 - p.edge.offset * p.edge.normal[0], (p.at as i64 / wi) as f32 - p.edge.offset * p.edge.normal[1]]) - .collect(); - let before: Vec = pixels.iter().map(|p| p.edge).collect(); - // Every pixel reads the unrefined edges around it and writes its own, so they go in parallel. - let work = pixels.len().saturating_mul(32); - par_units(work, pixels, 1, &mut [] as &mut [()], 0, Vec::<[f32; 2]>::new, |near, k, pixel, _| { - let (Some(pixel), Some(&e)) = (pixel.first_mut(), before.get(k)) else { return }; - let (x, y) = (pixel.at as i64 % wi, pixel.at as i64 / wi); - let (mut n, mut sum) = (0.0f32, [0.0f32; 2]); - near.clear(); - for (dx, dy) in (-NORMAL_RADIUS..=NORMAL_RADIUS).flat_map(|dy| (-NORMAL_RADIUS..=NORMAL_RADIUS).map(move |dx| (dx, dy))) { - let (nx, ny) = (x + dx, y + dy); - if dx * dx + dy * dy > NORMAL_RADIUS * NORMAL_RADIUS || nx < 0 || ny < 0 || nx >= wi || ny >= hi { - continue; - } - let Some(j) = slot.get((ny * wi + nx) as usize).and_then(|&s| (s as usize).checked_sub(1)) else { continue }; - let (Some(o), Some(&p)) = (before.get(j), points.get(j)) else { continue }; - if o.normal[0] * e.normal[0] + o.normal[1] * e.normal[1] > 0.9 { - near.push(p); - sum = [sum[0] + p[0], sum[1] + p[1]]; - n += 1.0; - } - } - if near.len() < 3 { - return; - } - let mean = [sum[0] / n, sum[1] / n]; - let (mut sxx, mut sxy, mut syy) = (0.0f32, 0.0f32, 0.0f32); - for p in near.iter() { - let (dx, dy) = (p[0] - mean[0], p[1] - mean[1]); - sxx += dx * dx; - sxy += dx * dy; - syy += dy * dy; - } - // Spread along and across the best line through the points. - let half = 0.5 * (sxx + syy); - let root = (0.25 * (sxx - syy) * (sxx - syy) + sxy * sxy).sqrt(); - let (along, across) = (((half + root) / n).max(0.0).sqrt(), ((half - root) / n).max(0.0).sqrt()); - if !(along > EDGE_LINE_MIN_SPREAD && across < EDGE_LINE_MAX_OFF) { - return; - } - let angle = 0.5 * (2.0 * sxy).atan2(sxx - syy); - let mut normal = [-angle.sin(), angle.cos()]; - if normal[0] * e.normal[0] + normal[1] * e.normal[1] < 0.0 { - normal = [-normal[0], -normal[1]]; - } - pixel.edge.normal = normal; - pixel.edge.offset = edge_offset(normal, pixel.cov); - }); -} - -/// The edge points around a pixel must spread at least this far (px, standard deviation) along -/// their line to give it a direction, and stay within [`EDGE_LINE_MAX_OFF`] of it. -const EDGE_LINE_MIN_SPREAD: f32 = 0.7; -const EDGE_LINE_MAX_OFF: f32 = 0.1; - -/// How far from the foot of the perpendicular (in pixels) [`edge_distance`] looks for edge pixels. -const FOOT_RADIUS: i64 = 2; - -/// The distance from pixel `p` to the sharp edge whose pixel `q` is nearest to it, or `None` when -/// `q` gives no usable distance. The nearest pixel by its centre is not the best one: it can sit a -/// few pixels along the edge from the foot of the perpendicular and deeper than the edge, and the -/// further `p` is from the edge the further, so its distance ripples along the edge. So this takes -/// the smallest distance of the edge pixels around that foot, which is exact for a straight edge. -fn edge_distance(sharp: &SharpEdges, p: [usize; 2], q: [usize; 2], inside: bool) -> Option { - let (px, py) = (p[0] as f32, p[1] as f32); - let e = sharp.at(q[0], q[1])?; - let mut best = e.distance(px - q[0] as f32, py - q[1] as f32, inside)?; - // Where p's perpendicular meets q's line. - let signed = e.offset + (px - q[0] as f32) * e.normal[0] + (py - q[1] as f32) * e.normal[1]; - let (fx, fy) = ((px - signed * e.normal[0]).round() as i64, (py - signed * e.normal[1]).round() as i64); - for sy in (fy - FOOT_RADIUS).max(0)..=(fy + FOOT_RADIUS).min(sharp.h as i64 - 1) { - for sx in (fx - FOOT_RADIUS).max(0)..=(fx + FOOT_RADIUS).min(sharp.w as i64 - 1) { - if let Some(near) = sharp.at(sx as usize, sy as usize) - && let Some(d) = near.distance(px - sx as f32, py - sy as f32, inside) - { - best = best.min(d); - } - } - } - Some(best) -} - -/// [`dist_inside`] for chiselled bevels. A sharp edge pixel puts the edge where its coverage says, -/// at any angle, and the pixels near it measure to that edge ([`edge_distance`]), so the distance -/// ramps stay planar along an oblique edge instead of following the pixel staircase. The plain -/// distance (to the nearest empty pixel, less half a pixel) never falls short of the true one, so -/// it caps the result where an edge lies exactly on a pixel boundary and has no sharp pixel; a mask -/// without sharp pixels gives exactly [`dist_inside`]. Values past `reach` pixels are not refined. -fn bevel_dist_inside(s: &Map, sharp: &SharpEdges, reach: f32) -> Vec { - let empty = covered(s, |a| a <= INSIDE_EPS); - let (d, near) = edt_nearest(&empty, s.w, s.h); - let at = |x: usize, y: usize| -> f32 { - let i = y * s.w + x; - if empty[i] { - return -0.5; - } - if let Some(e) = sharp.get(i) { - return e.offset; - } - let plain = d[i] - 0.5; - if d[i] > reach + EDGE_MARGIN || sharp.is_empty() { - return plain; - } - // The sharp pixel next to the nearest empty one that is nearest to this pixel. - let (px, py) = (x as i64, y as i64); - let (ox, oy) = ((near[i] as usize % s.w) as i64, (near[i] as usize / s.w) as i64); - let q = (-1..=1) - .flat_map(|dy| (-1..=1).map(move |dx| (ox + dx, oy + dy))) - .filter(|&(x, y)| x >= 0 && y >= 0 && sharp.has(x as usize, y as usize)) - .min_by_key(|&(x, y)| (x - px) * (x - px) + (y - py) * (y - py)); - match q.and_then(|(x, y)| edge_distance(sharp, [px as usize, py as usize], [x as usize, y as usize], true)) { - Some(refined) => refined.min(plain), - None => plain, - } - }; - par_fill(s.w, s.h, 0.0f32, |y, row| { - for (x, out) in row.iter_mut().enumerate() { - *out = at(x, y); - } - }) -} - -/// [`dist_outside`] for chiselled bevels, with sharp edge pixels placed as in [`bevel_dist_inside`]. -fn bevel_dist_outside(s: &Map, sharp: &SharpEdges, reach: f32) -> Vec { - let inside = covered(s, |a| a > INSIDE_EPS); - let (d, near) = edt_nearest(&inside, s.w, s.h); - let at = |x: usize, y: usize| -> f32 { - let i = y * s.w + x; - if let Some(e) = sharp.get(i) { - return -e.offset; - } - if inside[i] { - return -0.5; - } - let q = near[i] as usize; - let Some(e) = sharp.get(q) else { return d[i] - (s.v[q].min(1.0) - 0.5) }; - let (p, qp) = ([x, y], [q % s.w, q / s.w]); - let measured = if d[i] <= reach + EDGE_MARGIN { - edge_distance(sharp, p, qp, false) - } else { - e.distance(p[0] as f32 - qp[0] as f32, p[1] as f32 - qp[1] as f32, false) - }; - measured.unwrap_or(d[i] - e.offset) - }; - par_fill(s.w, s.h, 0.0f32, |y, row| { - for (x, out) in row.iter_mut().enumerate() { - *out = at(x, y); - } - }) -} - -/// Pixels past the reach that are still refined, so the value is right where the ramp ends. -const EDGE_MARGIN: f32 = 2.0; - -/// Alpha above which a pixel belongs to the layer's shape (half an 8-bit step). -const INSIDE_EPS: f32 = 0.5 / 255.0; - -/// The soft falloff of an effect of `size` pixels: two box passes of width `size` (a tent), -/// as Photoshop does. Fitted on psd-tools layer_effects.psd against the earlier Gaussian -/// (sigma = 0.4 × size): drop shadow coverage error 0.0064 → 0.0038, satin 0.014 → 0.002. -fn blur(m: &mut Map, size: f32) { - if size.is_finite() { - tent(m, size); - } -} - -/// Grows the shape by `r` pixels (anti-aliased), keeping the original soft edge. Distances use -/// the 5 × 5 chamfer metric, as for strokes: Photoshop's spread of a group drop shadow around an -/// ellipse (ag-psd group-drop-shadows) is round at 0° and 45° and falls short in between, peaking -/// near 15° where the chamfer metric overestimates most (5/255 lighter with an exact Euclidean -/// dilation, within 2/255 with the chamfer). -fn dilate(s: &Map, r: f32) -> Map { - if r <= 0.0 { - return s.clone(); - } - let d = dist_outside_by(s, Metric::Chamfer); - let mut out = s.clone(); - for (o, d) in out.v.iter_mut().zip(d) { - // Partly covered pixels (distance sentinel < 0) grow by `r` from their own coverage, so a - // 2 % spread doesn't make every anti-aliased edge pixel opaque (ag-psd drop shadow). - *o = if d < 0.0 { (*o + r).min(1.0) } else { o.max((r + 0.5 - d).clamp(0.0, 1.0)) }; - } - out -} - -fn contour_lut(c: &Contour) -> Option> { - match c { - Contour::Linear => None, - Contour::Custom { points, corners, .. } => Some(crate::adjust::contour_curve_lut(points, corners)), - } -} - -/// Satin's coverage transfer: the contour read from its far end, `|c(1 − v) − c(1)|`. Measured in -/// Photoshop 27.11: Cone and Cone − Inverted Satins are identical, and a Gaussian Satin runs under -/// the diagonal (0.36 at 0.5) while the same Gaussian on a glow or gloss runs over it (0.65). -/// `None` = identity. -pub fn satin_lut(c: &Contour) -> Option> { - let lut = contour_lut(c)?; - let end = lut.last().copied().unwrap_or(1.0); - Some(lut.iter().rev().map(|v| (v - end).abs()).collect()) -} - -/// Interpolated lookup in a 0..=1 table (as the GPU's `lut()`). -fn lut_at(l: &[f32], v: f32) -> f32 { - let x = v.clamp(0.0, 1.0) * (l.len() - 1) as f32; - let i = x.floor() as usize; - let j = (i + 1).min(l.len() - 1); - l[i] + (l[j] - l[i]) * (x - i as f32) -} - -/// A glow's coverage transfer: its contour applied over the Range (Photoshop maps the glow's -/// coverage `v` through `contour(min(v / range, 1))`, so the default 50 % doubles a blurred -/// edge's 0.5 to full strength). `None` = identity. -pub fn glow_lut(g: &Glow) -> Option> { - ranged_lut(&g.contour, g.range) -} - -/// A contour applied over a Range (`contour(min(v / range, 1))`); `None` = identity. -pub fn ranged_lut(contour: &Contour, range: f32) -> Option> { - let base = contour_lut(contour); - let range = if range.is_finite() { range.clamp(0.01, 1.0) } else { 1.0 }; - if range >= 0.999 { - return base; - } - let n = 4096; - Some( - (0..n) - .map(|k| { - let v = (k as f32 / (n - 1) as f32 / range).min(1.0); - base.as_ref().map_or(v, |l| lut_at(l, v)) - }) - .collect(), - ) -} - -/// The bevel Contour element's height transfer: the contour alone. Unlike a glow's, its Range is -/// not a `v / range` stretch: that flattened a Linear contour at the default 50 % to a bevel half -/// as wide as Photoshop's (a real 18 px smooth inner bevel at 136 % depth: top-edge highlight gone -/// 15 px in, Photoshop's still 0.19 at 16 px), and dropping it lowers the bad pixels of every -/// contour oracle (bevel-inner-contour-ramp-peak 25.9 → 21.8 %, -double-ring-aa-r70 25.2 → 21.0 %, -/// bevel-pillow-chisel-hard-gloss-and-contour 11.4 → 7.2 %). What Range does instead is still open. -pub fn bevel_contour_lut(c: &photocraft_doc::BevelContour) -> Vec { - contour_lut(&c.contour).unwrap_or_else(|| (0..4096).map(|k| k as f32 / 4095.0).collect()) -} - -fn apply_lut(m: Map, l: Option>) -> Map { - match l { - None => m, - Some(l) => m.map(|v| lut_at(&l, v)), - } -} - -/// Deterministic per-pixel value in 0..=1, hashed from document coordinates -/// (the same hash as the GPU's `dissolve_noise`), so the speckle is stable -/// across renders, frames and tiles. -pub fn hash_noise(x: i64, y: i64) -> f32 { - let mut h = (x as i32 as u32).wrapping_mul(0x8da6_b343) ^ (y as i32 as u32).wrapping_mul(0xd816_3841) ^ 0x9e37_79b9; - h ^= h >> 15; - h = h.wrapping_mul(0x2c1b_3c6d); - h ^= h >> 12; - (h & 0xffff) as f32 / 65536.0 -} - -/// Effect noise (Photoshop's Noise slider): monochrome speckle in the coverage, -/// applied after the contour. `amount` is 0..=1; 0 leaves the map untouched. The speckle is -/// scaled by the coverage, so it fades out with the effect instead of lighting up the blur's -/// near-zero tail out to the edge of its rectangular reach (#7833). -fn noise(m: &mut Map, amount: f32, x0: i32, y0: i32) { - if !amount.is_finite() || amount <= 0.0 { - return; - } - for y in 0..m.h { - for x in 0..m.w { - let v = &mut m.v[y * m.w + x]; - if *v <= 0.0 { - continue; - } - let n = hash_noise(i64::from(x0 + x as i32), i64::from(y0 + y as i32)); - *v = (*v * (1.0 + (n - 0.5) * 2.0 * amount)).clamp(0.0, 1.0); - } - } -} - -fn apply_contour(m: Map, c: &Contour) -> Map { - match contour_lut(c) { - None => m, - Some(l) => m.map(|v| lut_at(&l, v)), - } -} - -fn rgb(c: &photocraft_color::Color) -> [f32; 3] { - c.to_rgb() -} - -/// Offset of an effect lit from `angle` at `distance` (shadow falls away from -/// the light), rounded to whole pixels as Photoshop does. -fn offset(angle: f32, distance: f32) -> (f32, f32) { - let a = angle.to_radians(); - ((-a.cos() * distance).round(), (a.sin() * distance).round()) -} - -/// The lengths a 100 % gradient at `angle` spans in a `w` × `h` frame: the chord (Linear and -/// Reflected) and the ellipse-norm length (Radial, Angle, Diamond; its half is the radius). -pub fn gradient_units(angle: f32, w: f32, h: f32) -> (f32, f32) { - let (s, c) = angle.to_radians().sin_cos(); - // Gradient length: the bounds' extent along the angle as an ellipse - // norm (a unit gradient scaled to the bounds); fitted on psd-tools - // gradient-styles.psd (cached Photoshop renderings of every style). - let len = ((c * w).powi(2) + (s * h).powi(2)).sqrt().max(1.0); - // Linear / Reflected span the chord of the bounds through their centre along the angle: - // min(w / |cos|, h / |sin|). A 45° gradient on a 29 px square runs 41 px (psd-tools - // shape-fx2), an 87° one on a 600 × 60 text line 60 px (layer_effects); axis-aligned angles - // span the width / height. - let chord = (w / c.abs().max(1e-6)).min(h / s.abs().max(1e-6)).max(1.0); - (chord, len) -} - -/// Gradient parameter `t` in `0..=1` for pixel centre `(x, y)` inside `bounds`. -#[allow(clippy::too_many_arguments)] -pub fn gradient_t(style: GradientStyle, angle: f32, scale: f32, reverse: bool, offset: (f32, f32), bounds: Rect, x: f32, y: f32) -> f32 { - let w = bounds.width().max(1) as f32; - let h = bounds.height().max(1) as f32; - let cx = bounds.x0 as f32 + w / 2.0 + offset.0 * w; - let cy = bounds.y0 as f32 + h / 2.0 + offset.1 * h; - let (s, c) = angle.to_radians().sin_cos(); - let (dx, dy) = (x - cx, y - cy); - // Distance along the gradient direction (y axis points down). - let along = dx * c - dy * s; - let across = dx * s + dy * c; - let (chord, len) = gradient_units(angle, w, h); - let (chord, len) = (chord * scale.max(1e-3), len * scale.max(1e-3)); - // Linear / Reflected sample the pixel's top-left corner, half a pixel before its centre - // (with the whole-pixel end points of `fill_layout`: layer_effects' overlay 5.8 → 1.8/255, - // shape-fx2 2.8 → 1.1/255, gradient-fill.psd 1.9 → 0.5/255). - let corner = 0.5 * (c - s); - let mut t = match style { - GradientStyle::Linear => (along - corner) / chord + 0.5, - GradientStyle::Reflected => ((along - corner) / (chord / 2.0)).abs(), - GradientStyle::Radial => (dx * dx + dy * dy).sqrt() / (len / 2.0), - GradientStyle::Diamond => (along.abs() + across.abs()) / (len / 2.0), - // Clockwise sweep starting at the gradient angle. - GradientStyle::Angle => ((angle.to_radians() - (-dy).atan2(dx)) / std::f32::consts::TAU).rem_euclid(1.0), - }; - t = t.clamp(0.0, 1.0); - if reverse { 1.0 - t } else { t } -} - -/// Samples colour and opacity stops at `t`. -pub fn sample_gradient(g: &Gradient, t: f32) -> [f32; 4] { - PreparedGradient::new(g).sample(t) -} - -// Prepared only for one paint call: CMYK conversions must use that call's active profile. -struct PreparedGradient { - color: Vec<(f32, [f32; 3])>, - opacity: Vec<(f32, [f32; 3])>, -} - -impl PreparedGradient { - fn new(g: &Gradient) -> Self { - Self { color: g.stops.iter().map(|(p, c)| (*p, rgb(c))).collect(), opacity: g.opacity_stops.iter().map(|(p, a)| (*p, [*a; 3])).collect() } - } - - fn sample(&self, t: f32) -> [f32; 4] { - let color = sample_stops(&self.color, t); - let alpha = if self.opacity.is_empty() { 1.0 } else { sample_stops(&self.opacity, t)[0] }; - [color[0], color[1], color[2], alpha] - } -} - -fn sample_stops(stops: &[(f32, [f32; 3])], t: f32) -> [f32; 3] { - match stops { - [] => [t; 3], - [s] => s.1, - _ => { - if t <= stops[0].0 { - return stops[0].1; - } - for w in stops.windows(2) { - if t <= w[1].0 { - let k = if w[1].0 > w[0].0 { (t - w[0].0) / (w[1].0 - w[0].0) } else { 0.0 }; - return std::array::from_fn(|i| w[0].1[i] + (w[1].1[i] - w[0].1[i]) * k); - } - } - stops[stops.len() - 1].1 - } - } -} - -/// Composite `color × coverage` into `dst` (both over the same rectangle). -fn paint(dst: &mut Buffer, m: &Map, color: impl Fn(usize) -> [f32; 4], blend: BlendMode, opacity: f32) { - let (x0, y0, w) = (i64::from(dst.rect.x0), i64::from(dst.rect.y0), (dst.rect.width().max(1)) as usize); - for (i, p) in dst.px.iter_mut().enumerate() { - let a = m.v[i] * opacity; - if a <= 0.0 { - continue; - } - let c = color(i); - if blend == BlendMode::Dissolve { - if dissolves_in(x0 + (i % w) as i64, y0 + (i / w) as i64, c[3] * a) { - *p = psblend::composite(BlendMode::Normal, *p, [c[0], c[1], c[2], 1.0], 1.0); - } - continue; - } - *p = psblend::composite(blend, *p, [c[0], c[1], c[2], c[3] * a], 1.0); - } -} - -/// Whether `e` paints anything in Dissolve mode. -fn dissolves(e: &Effect) -> bool { - let d = |m: BlendMode| m == BlendMode::Dissolve; - match e { - Effect::DropShadow(s) | Effect::InnerShadow(s) => d(s.common.blend), - Effect::OuterGlow(g) | Effect::InnerGlow(g) => d(g.common.blend), - Effect::Stroke(s) => d(s.common.blend), - Effect::ColorOverlay { common, .. } | Effect::GradientOverlay { common, .. } | Effect::PatternOverlay { common, .. } => d(common.blend), - Effect::Satin(s) => d(s.common.blend), - Effect::BevelEmboss(b) => d(b.highlight.blend) || d(b.shadow.blend), - } -} - -/// Dissolve on an effect (#6995): a pixel takes the effect fully or not at all, with probability -/// `coverage`, picked by the same document-coordinate noise as a Dissolve layer. A soft glow or -/// shadow turns into scattered speckle instead of a smooth falloff. -fn dissolves_in(x: i64, y: i64, coverage: f32) -> bool { - hash_noise(x, y) < coverage -} - -fn paint_color(dst: &mut Buffer, m: &Map, c: [f32; 3], blend: BlendMode, opacity: f32) { - paint(dst, m, |_| [c[0], c[1], c[2], 1.0], blend, opacity); -} - -/// Spread / choke of a soft effect: (dilation radius, blur width). The dilation is whole pixels -/// (`size × spread` rounded: a 2 % spread of a 5 px shadow doesn't grow it at all), the blur -/// keeps `size × (1 − spread)` (ag-psd effects 10.6 → 3.8 % of pixels off). -pub fn spread_split(size: f32, spread: f32) -> (f32, f32) { - ((size * spread).round(), size * (1.0 - spread)) -} - -fn shadow_map(shape: &Map, s: &Shadow, light: &GlobalLight, inner: bool, origin: (i32, i32)) -> Map { - let angle = if s.use_global_light { light.angle } else { s.angle }; - let (dx, dy) = offset(angle, s.distance); - let src = if inner { shape.clone().map(|a| 1.0 - a) } else { shape.clone() }; - let mut m = src.shifted(dx, dy, if inner { 1.0 } else { 0.0 }); - let (r, bw) = spread_split(s.size, s.spread); - m = dilate(&m, r); - blur(&mut m, bw); - let mut m = apply_contour(m, &s.contour); - noise(&mut m, s.noise, origin.0, origin.1); - if inner { - for (v, a) in m.v.iter_mut().zip(&shape.v) { - *v *= a; - } - } - m -} - -fn glow_map(shape: &Map, g: &Glow, inner: bool, origin: (i32, i32)) -> Map { - // An inner glow is built from the edge inwards; a centre-source glow is its inverse, taken - // after the contour and Range (Photoshop 27.11, measured: the centre glow is exactly - // 1 − the edge glow, for both techniques). - let src = if inner { shape.clone().map(|a| 1.0 - a) } else { shape.clone() }; - let mut m = match g.technique { - GlowTechnique::Precise => { - // Coverage falls linearly from 0.5 at the edge to 0 at `size + 1` px (centre to - // centre), solid within the spread / choke: after the default 50 % Range that is - // Photoshop's 1 − D / (size + 1) beyond the solid part (measured: outer and inner, - // sizes 10 and 20, spread 0 and 40 %, choke 0 and 30 %: within 1 level; other Range - // values are unmeasured). The distances here are 0.5 px short of centre to centre. - let d = if inner { dist_inside(shape) } else { dist_outside(&src) }; - let solid = g.size * g.spread; - let soft = (g.size + 1.0 - solid).max(1e-3); - let mut m = Map::new(shape.w, shape.h, 0.0); - for (o, d) in m.v.iter_mut().zip(d) { - let d = d + 0.5; - *o = if d <= solid { 1.0 } else { 0.5 * (1.0 - (d - solid) / soft).clamp(0.0, 1.0) }; - } - m - } - GlowTechnique::Softer => { - let (r, bw) = spread_split(g.size, g.spread); - let mut m = dilate(&src, r); - blur(&mut m, bw); - m - } - }; - m = apply_lut(m, glow_lut(g)); - if inner && g.source == GlowSource::Center { - m = m.map(|v| 1.0 - v); - } - noise(&mut m, g.noise, origin.0, origin.1); - if inner { - for (v, a) in m.v.iter_mut().zip(&shape.v) { - *v *= a; - } - } - m -} - -/// Paints a pattern (looked up in `patterns`) through coverage `m`; missing patterns paint nothing. -#[allow(clippy::too_many_arguments)] -fn paint_pattern( - dst: &mut Buffer, - m: &Map, - patterns: &PreparedPatterns<'_>, - name: &str, - id: &str, - place: Placement, - big: Rect, - blend: BlendMode, - opacity: f32, -) { - let Some(tile) = patterns.get(id, name) else { return }; - let w = big.width() as usize; - paint( - dst, - m, - |i| { - let (x, y) = (f64::from(big.x0 + (i % w) as i32) + 0.5, f64::from(big.y0 + (i / w) as i32) + 0.5); - let (u, v) = place.map(x, y); - tile.sample(u, v) - }, - blend, - opacity, - ); -} - -#[allow(clippy::too_many_arguments)] -fn paint_fx( - dst: &mut Buffer, - m: &Map, - p: &FxPaint, - shape_bounds: Rect, - anchor: (f64, f64), - big: Rect, - blend: BlendMode, - opacity: f32, - patterns: &PreparedPatterns<'_>, -) { - match p { - FxPaint::Color(c) => paint_color(dst, m, rgb(c), blend, opacity), - FxPaint::Gradient(g) => { - let prepared = PreparedGradient::new(g); - let (angle, scale, offset) = crate::fill_layout::gradient_layout(g.style, g.angle, g.scale, g.offset, shape_bounds); - let w = big.width() as usize; - paint( - dst, - m, - |i| { - let (x, y) = ((big.x0 + (i % w) as i32) as f32 + 0.5, (big.y0 + (i / w) as i32) as f32 + 0.5); - prepared.sample(gradient_t(g.style, angle, scale, g.reverse, offset, shape_bounds, x, y)) - }, - blend, - opacity, - ) - } - FxPaint::Pattern { name, id, scale } => { - paint_pattern(dst, m, patterns, name, id, Placement::anchored(anchor, true, (0.0, 0.0), *scale, 0.0), big, blend, opacity) - } - } -} - -/// The opacity gain of a gradient glow: it is opaque from strength `range²` on (see [`paint_glow`]). -pub fn glow_gradient_gain(range: f32) -> f32 { - let r = if range.is_finite() { range.clamp(0.01, 1.0) } else { 1.0 }; - 1.0 / (r * r) -} - -/// A glow's paint over its map `m`. A gradient runs along the glow rather than across the -/// canvas: Photoshop colours the glow where its (ranged, contoured) strength is `v` with the -/// gradient at `1 - v`, so the first stop hugs the edge, and the glow is opaque from `v = range²` -/// on (photoshop corpus outer-glow-gradient.psd: 1.4/255 mean, against bands across the canvas; -/// psd-tools layer_params.psd). Glows have no gradient angle, style or Reverse. -#[allow(clippy::too_many_arguments)] -fn paint_glow(dst: &mut Buffer, m: &Map, g: &Glow, shape_bounds: Rect, anchor: (f64, f64), big: Rect, patterns: &PreparedPatterns<'_>) { - let FxPaint::Gradient(gradient) = &g.paint else { - return paint_fx(dst, m, &g.paint, shape_bounds, anchor, big, g.common.blend, g.common.opacity, patterns); - }; - let prepared = PreparedGradient::new(gradient); - let gain = glow_gradient_gain(g.range); - let strength = Map { w: m.w, h: m.h, v: m.v.iter().map(|v| (v * gain).min(1.0)).collect() }; - paint(dst, &strength, |i| prepared.sample(1.0 - m.v.get(i).copied().unwrap_or(0.0).clamp(0.0, 1.0)), g.common.blend, g.common.opacity); -} - -/// A box width as the blurs use it: at least 1, at most [`MAX_REACH`] (an effect never reaches -/// further, see [`margin`]), and 1 for NaN. A size or softness from a command or a file can be -/// anything, and an unbounded width sizes the kernel and its buffers (#1543). -fn box_width(w: f32) -> f32 { - if w.is_nan() { 1.0 } else { w.clamp(1.0, MAX_REACH) } -} - -/// Normalised weights of a centred box of (fractional) width `w`: tap `i` gets the overlap of -/// `[i - 0.5, i + 0.5]` with `[-w/2, w/2]`. -fn box_weights(w: f32) -> Vec { - let w = box_width(w); - let half = w / 2.0; - let r = (half - 0.5).ceil().max(0.0) as i64; - let v: Vec = (-r..=r).map(|i| ((i as f32 + 0.5).min(half) - (i as f32 - 0.5).max(-half)).max(0.0)).collect(); - let sum: f32 = v.iter().sum(); - v.iter().map(|x| x / sum).collect() -} - -/// The 1D kernel of two box passes of width `w` (a tent of half-width ≈ `w`): `(radius, weights)`. -/// Photoshop's bevel height maps are this blur of the shape (fitted on the corpus: a smooth -/// inner bevel of size 5 matches within 0.7 % mean, size 41 within 2.6 %). -pub fn tent_kernel(w: f32) -> (i32, Vec) { - let b = box_weights(w); - let n = b.len() * 2 - 1; - let mut t = vec![0.0f32; n]; - for (i, x) in b.iter().enumerate() { - for (j, y) in b.iter().enumerate() { - t[i + j] += x * y; - } - } - ((n as i32 - 1) / 2, t) -} - -/// Box geometry for a (fractional) width: (`r`, end-tap weight `f`, 1 / width) — the -/// [`box_weights`] taps are `r - 1` full ones each side of the centre plus the two end taps at `f`. -fn box_geom(bw: f32) -> (i64, f64, f64) { - let bw = box_width(bw); - let half = bw / 2.0; - let r = (half - 0.5).ceil().max(0.0) as i64; - let f = f64::from((half - (r as f32 - 0.5)).clamp(0.0, 1.0)); - (r, f, 1.0 / f64::from(bw)) -} - -/// One box pass over `src` (zero outside it) evaluated at `x0 .. x0 + dst.len()`, as a running -/// sum (O(1) per sample whatever the width). -fn box_line(src: &[f64], x0: i64, dst: &mut [f64], bw: f32) { - let n = src.len() as i64; - let (r, f, norm) = box_geom(bw); - let at = |i: i64| if i >= 0 && i < n { src[i as usize] } else { 0.0 }; - if r == 0 { - for (k, d) in dst.iter_mut().enumerate() { - *d = at(x0 + k as i64); - } - return; - } - let window = x0 - (r - 1)..=x0 + (r - 1); - let mut inner: f64 = window.clone().map(at).sum(); - let mut last_covered = window.rev().find(|&x| at(x) != 0.0).unwrap_or(i64::MIN); - for (k, d) in dst.iter_mut().enumerate() { - let x = x0 + k as i64; - *d = (inner + f * (at(x - r) + at(x + r))) * norm; - let entering = at(x + r); - inner += entering - at(x - r + 1); - if entering != 0.0 { - last_covered = x + r; - } - // Cancellation can leave positive residue after the last covered pixel leaves. - // Noise amplifies even that residue into visible speckles (#5638). Reset only - // truly empty windows, preserving arbitrarily faint real coverage. - if last_covered < x - r + 2 { - inner = 0.0; - } - } -} - -/// Two box passes along a line, exactly the convolution with [`tent_kernel`] (zero outside): the -/// first pass is evaluated `r` samples beyond each end so the second sees what lies there. -fn tent_line(src: &[f32], dst: &mut [f32], bw: f32) { - let (r, _, _) = box_geom(bw); - let s: Vec = src.iter().map(|v| f64::from(*v)).collect(); - let mut mid = vec![0.0f64; src.len() + 2 * r as usize]; - box_line(&s, -r, &mut mid, bw); - let mut out = vec![0.0f64; src.len()]; - // `mid[k]` holds position k - r: output position p reads index p + r. - box_line(&mid, r, &mut out, bw); - for (d, v) in dst.iter_mut().zip(out) { - *d = v as f32; - } -} - -/// Rows of a `w`-wide row-major buffer, each through `f(src_row, dst_row)`, in parallel on -/// scoped OS threads. Not rayon: maps can be built from inside a rayon tile, where a waiting -/// worker steals other tiles. Map builds no longer block on each other (#276), but the blur -/// keeps out of the tile pool. -fn rows_par(src: &[f32], dst: &mut [f32], w: usize, f: impl Fn(&[f32], &mut [f32]) + Sync) { - if w == 0 { - return; - } - let threads = - if cfg!(target_arch = "wasm32") || src.len() < 1 << 16 { 1 } else { std::thread::available_parallelism().map_or(1, |n| n.get()).clamp(1, 16) }; - if threads == 1 { - dst.chunks_mut(w).zip(src.chunks(w)).for_each(|(d, s)| f(s, d)); - return; - } - let rows = (src.len() / w).div_ceil(threads); - std::thread::scope(|sc| { - for (d, s) in dst.chunks_mut(rows * w).zip(src.chunks(rows * w)) { - let f = &f; - sc.spawn(move || d.chunks_mut(w).zip(s.chunks(w)).for_each(|(d, s)| f(s, d))); - } - }); -} - -fn transpose_map(v: &[f32], w: usize, h: usize) -> Vec { - let mut out = vec![0.0f32; v.len()]; - const B: usize = 32; - for by in (0..h).step_by(B) { - for bx in (0..w).step_by(B) { - for y in by..(by + B).min(h) { - for x in bx..(bx + B).min(w) { - out[x * h + y] = v[y * w + x]; - } - } - } - } - out -} - -/// Two box passes of width `w` along each axis (the tent [`tent_kernel`] describes, which the GPU -/// convolves directly). -fn tent(m: &mut Map, w: f32) { - if tent_kernel(w).0 == 0 || m.v.is_empty() { - return; - } - tent_fast(m, w); -} - -/// [`tent`] as a direct convolution with [`tent_kernel`] (the GPU's way; tests compare). -#[cfg(test)] -fn tent_direct(m: &mut Map, w: f32) { - { - let (r, k) = tent_kernel(w); - let (mw, mh) = (m.w as i64, m.h as i64); - let mut tmp = vec![0.0f32; m.v.len()]; - for y in 0..mh { - for x in 0..mw { - let mut acc = 0.0; - for (i, kv) in k.iter().enumerate() { - let xx = x + i as i64 - r as i64; - if xx >= 0 && xx < mw { - acc += m.v[(y * mw + xx) as usize] * kv; - } - } - tmp[(y * mw + x) as usize] = acc; - } - } - for y in 0..mh { - for x in 0..mw { - let mut acc = 0.0; - for (i, kv) in k.iter().enumerate() { - let yy = y + i as i64 - r as i64; - if yy >= 0 && yy < mh { - acc += tmp[(yy * mw + x) as usize] * kv; - } - } - m.v[(y * mw + x) as usize] = acc; - } - } - } -} - -fn tent_fast(m: &mut Map, w: f32) { - let (mw, mh) = (m.w, m.h); - let twice = |s: &[f32], d: &mut [f32]| tent_line(s, d, w); - let mut a = vec![0.0f32; m.v.len()]; - rows_par(&m.v, &mut a, mw, twice); - let t = transpose_map(&a, mw, mh); - let mut b = vec![0.0f32; t.len()]; - rows_par(&t, &mut b, mh, twice); - m.v = transpose_map(&b, mh, mw); -} - -/// Where a bevel's maps paint: inside the shape (with the layer), outside it (onto the -/// backdrop), or both (emboss styles: maps 0–1 inside, 2–3 outside). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum BevelPaint { - Inner, - Outer, - Both, -} - -/// Height below which an outer bevel pixel counts as off the bevel (beyond the blur's reach): -/// above float noise of the running-sum blur (~3e-7), far below anything that shades. -pub const BEVEL_H_EPS: f32 = 1e-5; - -/// Bevel geometry shared by the CPU maps and the GPU programs. -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct BevelGeom { - pub paint: BevelPaint, - /// Box width of the smooth height blur (size; half the size, rounded up, for emboss styles). - pub width: f32, - /// Height-map gradient scale: depth × width (smooth) or depth × size (chisel), signed by - /// direction. - pub depth: f32, - /// Pillow emboss: the outside slopes face the other way. - pub pillow: bool, - /// Chisel Soft: extra tent width over the chiselled height map. - pub chisel_soft: f32, -} - -pub fn bevel_geom(b: &Bevel) -> BevelGeom { - let size = b.size.max(1.0); - let emboss = matches!(b.style, BevelStyle::Emboss | BevelStyle::PillowEmboss); - let paint = match b.style { - BevelStyle::OuterBevel => BevelPaint::Outer, - BevelStyle::Emboss | BevelStyle::PillowEmboss => BevelPaint::Both, - BevelStyle::InnerBevel | BevelStyle::StrokeEmboss => BevelPaint::Inner, - }; - // Emboss styles straddle the edge with half the size, rounded up to whole pixels: a 41 px - // emboss blurs over 21 (psd-tools layer_effects: 20.5 left narrow letter parts up to - // 5.7/255 dark, 21 is within 2.2). - let width = if emboss { (size / 2.0).ceil() } else { size }; - let smooth = b.technique == BevelTechnique::Smooth; - let sign = if b.up { 1.0 } else { -1.0 }; - BevelGeom { - paint, - width, - // A bevel rises `depth × width / 2` px: Smooth with a slope falling from `depth` at the - // edge (the tent), a chisel with the constant slope of its ramp (see `bevel_chisel_h`). - depth: b.depth * if smooth { width } else { size / 2.0 } * sign, - pillow: b.style == BevelStyle::PillowEmboss, - chisel_soft: if b.technique == BevelTechnique::ChiselSoft { (size / 4.0).max(1.0) } else { 0.0 }, - } -} - -/// Bevel height map in `0..=1`. Smooth: the shape blurred by two box passes of the bevel -/// width. Chisel: linear ramps of the distance to the edge (size wide; emboss styles straddle the -/// edge), slightly blurred for Chisel Soft. The distance puts the edge by the anti-aliased -/// coverage of its pixels ([`bevel_dist_inside`]), so a facet is planar at any angle. Soften blurs -/// the result. -fn bevel_height(shape: &Map, b: &Bevel, g: &BevelGeom, tex: &TextureCtx, patterns: &PreparedPatterns<'_>) -> Map { - let size = b.size.max(1.0); - let mut h = if b.technique == BevelTechnique::Smooth { - let mut h = shape.clone(); - tent(&mut h, g.width); - h - } else { - let [din, dout] = bevel_dists(shape, size); - let soft = g.chisel_soft > 0.0; - let w = shape.w; - let v = par_fill(w, shape.h, 0.0, |y, row| { - for (x, o) in row.iter_mut().enumerate() { - let i = y * w + x; - *o = bevel_chisel_h(g.paint, size, din[i], dout[i], soft); - } - }); - let mut h = Map { w, h: shape.h, v }; - // Inner and outer Chisel Soft are not blurred in Photoshop (their facets equal Chisel - // Hard's across a straight edge); emboss styles keep the blur until measured. - if soft && g.paint == BevelPaint::Both { - tent(&mut h, g.chisel_soft); - } - h - }; - // Contour element: the height profile through the contour. - if let Some(c) = &b.contour { - h = apply_lut(h, Some(bevel_contour_lut(c))); - } - // Texture element: the pattern's luminance as extra height, scaled so a full-contrast step - // at 100 % depth slopes like the bevel at its depth. - if let Some(t) = &b.texture - && let Some(tile) = patterns.get(&t.id, &t.name) - { - let unit = if b.depth.abs() > 1e-6 { (g.depth / b.depth).abs().max(1e-3) } else { g.width.max(1.0) }; - let place = Placement::anchored(tex.anchor, t.link, t.phase, t.scale, 0.0); - let k = t.depth / unit; - let (x0, y0) = (tex.rect.x0, tex.rect.y0); - let w = h.w; - par_units( - h.v.len(), - &mut h.v, - w, - &mut [] as &mut [()], - 0, - || (), - |_, y, row, _| { - for (x, o) in row.iter_mut().enumerate() { - let (u, v) = place.map(f64::from(x0 + x as i32) + 0.5, f64::from(y0 + y as i32) + 0.5); - let p = tile.sample(u, v); - let l = (0.299 * p[0] + 0.587 * p[1] + 0.114 * p[2]) * p[3]; - *o += k * if t.invert { 1.0 - l } else { l }; - } - }, - ); - } - if b.soften >= 1.0 { - tent(&mut h, b.soften); - } - h -} - -/// Where a bevel texture tiles: the maps' rectangle, the document's patterns and the linked -/// origin (the effects reference point, else the layer's top-left). -pub struct TextureCtx<'a> { - pub rect: Rect, - pub patterns: &'a [Pattern], - pub anchor: (f64, f64), -} - -/// Chiselled height from the inside / outside distances (keep in sync with `fs_mbevelh`). -/// -/// Photoshop 27.11, measured across straight edges (sizes 10 and 20, depth 100 and 300): a chisel -/// facet has the constant slope `depth × size / (2 (size + 1))`, i.e. one height step of -/// `1 / (size + 1)` per pixel at the `depth × size / 2` scale of [`bevel_geom`]. Inner Hard's ramp -/// runs from half a pixel beyond the edge to `size + ½` (the facet is flat right up to the edge -/// pixel); Inner Soft starts a pixel further out, so its edge pixel is steeper; Outer Hard ends a -/// pixel further out. All within 1 level of Photoshop on those profiles. -pub fn bevel_chisel_h(paint: BevelPaint, size: f32, din: f32, dout: f32, soft: bool) -> f32 { - let ramp = size + 1.0; - match paint { - BevelPaint::Outer if !soft => { - let top = (size + 2.0) / ramp; - if dout > 0.0 { ((size + 1.5 - dout) / ramp).clamp(0.0, top) } else { top } - } - // Outer Soft: Outer Hard's ramp a pixel shorter, with a steeper edge pixel. - BevelPaint::Outer => { - if dout > 0.0 { - 1.0 - ((dout + 0.5) / ramp).clamp(0.0, 1.0) - } else { - (size + 2.0) / ramp - } - } - BevelPaint::Both => { - let half = size / 2.0 + 0.5; - if din > 0.0 { 0.5 + 0.5 * (din / half).clamp(0.0, 1.0) } else { 0.5 - 0.5 * (dout / half).clamp(0.0, 1.0) } - } - BevelPaint::Inner if soft => { - if din > 0.0 { - ((din + 1.5) / ramp).clamp(0.0, (size + 2.0) / ramp) - } else { - 0.0 - } - } - BevelPaint::Inner => { - if din > 0.0 { - ((din + 0.5) / ramp).clamp(0.0, 1.0) - } else { - 0.0 - } - } - } -} - -/// Bevel highlight and shadow maps: `[hi, sh]` (inner or outer) or `[hi, sh, hi_out, sh_out]` -/// (emboss styles). -fn bevel_maps(shape: &Map, b: &Bevel, light: &GlobalLight, tex: &TextureCtx, patterns: &PreparedPatterns<'_>) -> (Vec, BevelPaint) { - let g = bevel_geom(b); - let hmap = bevel_height(shape, b, &g, tex, patterns); - let (angle, altitude) = if b.use_global_light { (light.angle, light.altitude) } else { (b.angle, b.altitude) }; - let (sa, ca) = angle.to_radians().sin_cos(); - let (se, ce) = altitude.to_radians().sin_cos(); - let light_v = [ca * ce, -sa * ce, se]; - // Region: 0 = inside (× the shape's alpha), 1 = under the layer's edge and outside. - // A pixel is on the bevel where its height is raised. Emboss styles also shade the last pixel - // past the blur's reach (a raised 4-neighbour: it still slopes; psd-tools layer_effects' - // emboss shadow runs one row past it), outer bevels don't (Photoshop oracle - // bevel-outer-smooth). - // Outer chisel bevels too: the pixel where their ramp reaches zero still slopes (Photoshop - // 27.11 shades it, half strength, at `size + 1½` px out). - let reach_past = g.paint == BevelPaint::Both || (g.paint == BevelPaint::Outer && b.technique != BevelTechnique::Smooth); - let on_bevel = |x: i64, y: i64| { - hmap.get(x, y) > BEVEL_H_EPS || (reach_past && [(1, 0), (-1, 0), (0, 1), (0, -1)].iter().any(|(dx, dy)| hmap.get(x + dx, y + dy) > BEVEL_H_EPS)) - }; - // The gloss contour remaps the shading `n · light` before it splits into highlight (above - // what it maps a flat face's `sin(altitude)` to) and shadow. Applied to the highlight and shadow amounts - // instead, a contour that starts high (Rolling Slope - Descending) lit every pixel the light - // missed, so a bevelled glyph's flat face took the full highlight (#7360) where Photoshop - // leaves it at the layer's colour. The Linear contour changes nothing either way. - let gloss = contour_lut(&b.gloss_contour); - let shade_into = |depth: f32, region_kind: u8| -> (Map, Map) { - let (mut hi, mut sh) = (Map::new(shape.w, shape.h, 0.0), Map::new(shape.w, shape.h, 0.0)); - // Rows on threads: every pixel reads only `hmap` and `shape`. - par_units( - hi.v.len(), - &mut hi.v, - shape.w, - &mut sh.v, - shape.w, - || (), - |_, y, hi_row, sh_row| { - let y = y as i64; - for x in 0..shape.w as i64 { - let i = y as usize * shape.w + x as usize; - let gx = (hmap.get(x + 1, y) - hmap.get(x - 1, y)) * 0.5 * depth; - let gy = (hmap.get(x, y + 1) - hmap.get(x, y - 1)) * 0.5 * depth; - let n = [-gx, -gy, 1.0]; - let len = (n[0] * n[0] + n[1] * n[1] + 1.0).sqrt(); - let shade = (n[0] * light_v[0] + n[1] * light_v[1] + n[2] * light_v[2]) / len; - let region = if region_kind == 0 { shape.v[i] } else { f32::from(shape.v[i] < 1.0 - INSIDE_EPS && on_bevel(x, y)) }; - let k = gloss.as_ref().map_or(shade - se, |l| lut_at(l, shade) - lut_at(l, se)); - if k > 0.0 { - hi_row[x as usize] = (k / (1.0 - se).max(1e-3)).clamp(0.0, 1.0) * region; - } else { - sh_row[x as usize] = (-k / se.max(1e-3)).clamp(0.0, 1.0) * region; - } - } - }, - ); - (hi, sh) - }; - let maps = match g.paint { - BevelPaint::Inner | BevelPaint::Outer => { - let (hi, sh) = shade_into(g.depth, u8::from(g.paint == BevelPaint::Outer)); - vec![hi, sh] - } - BevelPaint::Both => { - // One map per colour over the whole bevel: the inside half where the shape is (× its - // alpha), the outside half (pillow: facing the other way) for the rest of each pixel. - // A 1 % edge pixel of a pillow emboss takes the outside shading (Photoshop oracle - // bevel-pillow-smooth), a 75 % one of an emboss mostly the inside (layer_effects). - let (hi, sh) = shade_into(g.depth, 0); - let (ho, so) = shade_into(if g.pillow { -g.depth } else { g.depth }, 1); - let mix = |a: Map, b: Map| -> Map { - let v = par_fill(a.w, a.h, 0.0, |y, row| { - for (x, o) in row.iter_mut().enumerate() { - let i = y * a.w + x; - let (x, y, s) = (a.v[i], b.v[i], shape.v[i]); - *o = if s > INSIDE_EPS { x } else { 0.0 } + y * (1.0 - s.min(1.0)); - } - }); - Map { w: a.w, h: a.h, v } - }; - vec![mix(hi, ho), mix(sh, so)] - } - }; - (maps, g.paint) -} - /// Effect maps derived from a layer's shape (its alpha), computed once over the layer's whole /// region and cropped per render tile. They depend only on the shape, the effect settings and the /// global light, never on the backdrop, so they can be cached across tiles and edits. @@ -1829,1682 +245,5 @@ impl FxMaps { } } -/// The distance the two satin copies are offset by. Photoshop draws Distance 0 as 1 px (an -/// edge band of 2/size, measured in Photoshop 27.11), not as two copies cancelling out. -pub fn satin_distance(s: &photocraft_doc::effects::Satin) -> f32 { - s.distance.max(1.0) -} - -fn satin_map(shape: &Map, s: &photocraft_doc::effects::Satin) -> Map { - let (dx, dy) = offset(s.angle, satin_distance(s)); - let mut a = shape.shifted(dx, dy, 0.0); - let mut b = shape.shifted(-dx, -dy, 0.0); - // Two box passes of the satin size (fitted: 0.2 % mean error on psd-tools layer_effects). - tent(&mut a, s.size); - tent(&mut b, s.size); - let mut m = Map { w: shape.w, h: shape.h, v: a.v.iter().zip(&b.v).map(|(x, y)| (x - y).abs()).collect() }; - if s.invert { - m = m.map(|v| 1.0 - v); - } - let mut m = apply_lut(m, satin_lut(&s.contour)); - for (v, a) in m.v.iter_mut().zip(&shape.v) { - *v *= a; - } - m -} - -/// Build every effect map for `layer` from its alpha `shape` over `rect`. -pub fn build_maps(layer: &Layer, shape: Vec, rect: Rect, light: &GlobalLight, tex: &TextureCtx) -> FxMaps { - let prepared = PreparedPatterns::new(tex.patterns, PREPARED_PATTERN_BYTES); - build_maps_prepared(layer, shape, rect, light, tex, &prepared) -} - -/// How many region-sized arrays [`build_maps_prepared`] builds for `layer` (what -/// [`FxMaps::bytes`] counts): the shape, each effect's maps, and a stroke's distance fields. Kept -/// next to the builder so the effect cache's estimate (#8330) follows it. -pub(crate) fn map_count(layer: &Layer) -> usize { - let items: Vec<&Effect> = layer.effects.items.iter().filter(|e| e.enabled()).collect(); - let per: usize = items - .iter() - .map(|e| match e { - Effect::DropShadow(_) | Effect::InnerShadow(_) | Effect::OuterGlow(_) | Effect::InnerGlow(_) | Effect::Satin(_) => 1, - Effect::BevelEmboss(_) => 2, - _ => 0, - }) - .sum(); - let out_widths: Vec = - items.iter().filter_map(|e| if let Effect::Stroke(st) = e { Some(stroke_widths(st).1) } else { None }).filter(|w| *w > 0.0).collect(); - let has_stroke = items.iter().any(|e| matches!(e, Effect::Stroke(_))); - let outside = usize::from(out_widths.iter().any(|&w| !stroke_outside_exact(w))) + usize::from(out_widths.iter().any(|&w| stroke_outside_exact(w))); - let stroke = if has_stroke { 1 + outside } else { 0 }; - let vector_outline = - if has_stroke && matches!(layer.content, photocraft_doc::LayerContent::Shape(_)) && crate::effect_outline(layer).is_none() { outside } else { 0 }; - 1 + per + stroke + vector_outline -} - -pub(crate) fn build_maps_prepared( - layer: &Layer, - shape: Vec, - rect: Rect, - light: &GlobalLight, - tex: &TextureCtx, - patterns: &PreparedPatterns<'_>, -) -> FxMaps { - let (w, h) = (rect.width() as usize, rect.height() as usize); - let shape = Map { w, h, v: shape }; - let items: Vec<&Effect> = layer.effects.items.iter().filter(|e| e.enabled()).collect(); - let mut bevel_paint = vec![BevelPaint::Inner; items.len()]; - let per: Vec> = items - .iter() - .enumerate() - .map(|(i, e)| match e { - Effect::DropShadow(s) => vec![shadow_map(&shape, s, light, false, (rect.x0, rect.y0))], - Effect::InnerShadow(s) => vec![shadow_map(&shape, s, light, true, (rect.x0, rect.y0))], - Effect::OuterGlow(g) => vec![glow_map(&shape, g, false, (rect.x0, rect.y0))], - Effect::InnerGlow(g) => vec![glow_map(&shape, g, true, (rect.x0, rect.y0))], - Effect::Satin(s) => vec![satin_map(&shape, s)], - Effect::BevelEmboss(b) => { - let (maps, paint) = bevel_maps(&shape, b, light, tex, patterns); - bevel_paint[i] = paint; - maps - } - _ => Vec::new(), - }) - .collect(); - let has_stroke = items.iter().any(|e| matches!(e, Effect::Stroke(_))); - let vector_shape = matches!(layer.content, photocraft_doc::LayerContent::Shape(_)); - // A stroke's outer edge keeps the 5 × 5 chamfer while its outside width is under - // `STROKE_CHAMFER_MAX` — Photoshop matches the chamfer's sub-pixel edge seeding at small - // offsets — and uses the exact Euclidean transform at or above it, where the chamfer's octagon - // facets a wide stroke (#3646). Inside stroke distances always keep the chamfer. Each outer - // field is built only when a stroke of that width is present; the compositor picks per stroke, - // so one layer may hold both a narrow and a wide stroke. - let out_widths: Vec = - items.iter().filter_map(|e| if let Effect::Stroke(st) = e { Some(stroke_widths(st).1) } else { None }).filter(|w| *w > 0.0).collect(); - let chamfer_out = out_widths.iter().any(|&w| !stroke_outside_exact(w)); - let exact_out = out_widths.iter().any(|&w| stroke_outside_exact(w)); - let (din, dout, dout_exact) = if has_stroke { - ( - Some(dist_inside_by(&shape, Metric::Chamfer)), - chamfer_out.then(|| dist_outside_by(&shape, Metric::Chamfer)), - exact_out.then(|| dist_outside_by(&shape, Metric::Euclidean)), - ) - } else { - (None, None, None) - }; - // Without an outline (unfilled shapes), estimate the vector outline from local coverage; it - // picks the chamfer or the exact transform the same way. - let outline = crate::effect_outline(layer).is_some(); - let (vdout, vdout_exact) = if has_stroke && vector_shape && !outline { - let lc = local_coverage(&shape); - (chamfer_out.then(|| dist_outside_by(&lc, Metric::Chamfer)), exact_out.then(|| dist_outside_by(&lc, Metric::Euclidean))) - } else { - (None, None) - }; - let mut frames: Vec<(u32, Rect)> = Vec::new(); - for e in &items { - if let Effect::Stroke(st) = e - && matches!(st.paint, FxPaint::Gradient(_)) - { - let out_w = stroke_widths(st).1; - if !frames.iter().any(|f| f.0 == out_w.to_bits()) { - frames.push((out_w.to_bits(), stroke_frame(&shape, out_w, rect))); - } - } - } - FxMaps { rect, shape, per, bevel_paint, din, dout, dout_exact, vdout, vdout_exact, outline, frames } -} - -/// Far outside any shape (distance fill for cropped distance fields). -const FAR: f32 = 1.0e9; - -/// Keep an exterior effect behind the layer's shape when Fill is partly or wholly -/// transparent. The visible part beneath a fully opaque fill is already covered by the -/// layer, so avoid attenuating anti-aliased edges twice in that case. -fn knock_out_exterior(map: &mut Map, shape: &Map, fill_opacity: f32) { - let see_through = 1.0 - fill_opacity.clamp(0.0, 1.0); - for (coverage, alpha) in map.v.iter_mut().zip(&shape.v) { - *coverage *= 1.0 - alpha * see_through; - } -} - -/// How far the layer lets a knocked-out drop shadow show beneath its own shape (Layer Knocks Out -/// Drop Shadow), 0 = covered, 1 = knocked out wholly. In a normal mode an opaque layer covers the -/// shadow anyway, so only see-through fill knocks it out (and anti-aliased edges are not -/// attenuated twice). In any other mode the layer blends with what's beneath it, shadow and all: -/// an Exclusion or Difference layer would invert it, Multiply darken by it, Screen show it as -/// grey. Photoshop keeps it out from under the shape, so here it's knocked out wholly. -pub fn shadow_see_through(layer: &Layer) -> f32 { - if matches!(layer.blend, BlendMode::Normal | BlendMode::Dissolve | BlendMode::PassThrough) { 1.0 - layer.fill_opacity.clamp(0.0, 1.0) } else { 1.0 } -} - -/// Blend Interior Effects as Group off (Photoshop's default): the layer's mode applies to its -/// own pixels only, and the interior effects paint over the blended result. The layer is merged -/// into the backdrop before they paint, so an Overlay colour overlay on a black Color-mode layer -/// tints the grey beneath it (#3996). A Normal layer merges only when an interior effect blends -/// in another mode: below 100 % fill that effect sees the backdrop through the layer, so a Soft -/// Light overlay on a Fill 0 % layer soft-lights the backdrop instead of showing its own colour -/// (#6232). Normal effects give the same result either way, and the merge would count a -/// half-transparent backdrop twice, so those layers keep the plain composite. -pub fn premerges_layer(layer: &Layer) -> bool { - !layer.advanced.blend_interior - && match layer.blend { - BlendMode::PassThrough | BlendMode::Dissolve => false, - BlendMode::Normal => blends_inside(layer), - _ => true, - } -} - -/// `true` if an enabled effect painted inside the layer (with its content) blends in a mode -/// other than Normal. -fn blends_inside(layer: &Layer) -> bool { - let blends = |m: BlendMode| m != BlendMode::Normal; - layer.effects.items.iter().filter(|e| e.enabled()).any(|e| match e { - Effect::ColorOverlay { common, .. } | Effect::GradientOverlay { common, .. } | Effect::PatternOverlay { common, .. } => blends(common.blend), - Effect::Satin(s) => blends(s.common.blend), - Effect::InnerGlow(g) => blends(g.common.blend), - Effect::InnerShadow(s) => blends(s.common.blend), - Effect::Stroke(s) => stroke_widths(s).0 > 0.0 && blends(s.common.blend), - Effect::BevelEmboss(b) => bevel_geom(b).paint == BevelPaint::Inner && (blends(b.highlight.blend) || blends(b.shadow.blend)), - Effect::DropShadow(_) | Effect::OuterGlow(_) => false, - }) -} - -/// Composites `content` (the layer's own pixels over `big`, alpha already -/// masked, clipped layers applied) plus its effects into `backdrop`. -pub fn composite_with_effects(layer: &Layer, content: &Buffer, backdrop: &mut Buffer, maps: &FxMaps, layer_bounds: Rect, patterns: &[Pattern]) { - let prepared = PreparedPatterns::new(patterns, PREPARED_PATTERN_BYTES); - composite_with_effects_prepared(layer, content, backdrop, maps, layer_bounds, &prepared, None); -} - -pub(crate) fn composite_with_effects_prepared( - layer: &Layer, - content: &Buffer, - backdrop: &mut Buffer, - maps: &FxMaps, - layer_bounds: Rect, - patterns: &PreparedPatterns<'_>, - vstroke: Option>, -) { - let big = content.rect; - let (w, h) = (big.width() as usize, big.height() as usize); - // The effect shape: the content's alpha (with a split-off vector stroke, `content` is the - // unmasked fill and the mask applies to fill ∪ stroke), joined with a filled shape's outline. - let kmask = |i: usize| vstroke.as_ref().and_then(|v| v.mask).and_then(|m| m.get(i)).copied().unwrap_or(1.0); - let union = |i: usize, a: f32| vstroke.as_ref().and_then(|v| v.stroke.px.get(i)).map_or(a, |s| kmask(i) * (a + s[3] * (1.0 - a))); - // Transparency Shapes Layer off: the shape is the whole layer (its masks, as the maps were - // built), and the content's own transparency acts like fill opacity within it. - let shapeless = !layer.advanced.transparency_shapes; - let shape = if shapeless { - maps.crop(&maps.shape, big, 0.0) - } else if maps.outline { - let o = maps.crop(&maps.shape, big, 0.0); - Map { w, h, v: o.v.iter().zip(&content.px).enumerate().map(|(i, (o, p))| o.max(union(i, p[3]))).collect() } - } else { - Map { w, h, v: content.px.iter().enumerate().map(|(i, p)| union(i, p[3])).collect() } - }; - let relative = shapeless || maps.outline || vstroke.is_some(); - let fx = |i: usize, k: usize| maps.crop(&maps.per[i][k], big, 0.0); - // Layer bounds (gradients aligned with the layer use the whole layer, - // independent of the render rect). - let sb = layer_bounds; - // Linked patterns tile from the effects reference point (else the layer's top-left). - let anchor = layer.effects.reference.unwrap_or((f64::from(sb.x0), f64::from(sb.y0))); - let rect = backdrop.rect; - let before = backdrop.clone(); - // Exterior effects are painted on a backdrop copy extended to `big`. - let mut work = Buffer::transparent(big); - for y in rect.y0.max(big.y0)..rect.y1.min(big.y1) { - for x in rect.x0.max(big.x0)..rect.x1.min(big.x1) { - work.px[((y - big.y0) as usize) * w + (x - big.x0) as usize] = before.get(x, y); - } - } - let items: Vec<&Effect> = layer.effects.items.iter().filter(|e| e.enabled()).collect(); - let vector_shape = matches!(layer.content, photocraft_doc::LayerContent::Shape(_)); - // Multiple instances: the first listed is on top, so paint in reverse. - let rev = || items.iter().copied().enumerate().rev(); - - for (i, e) in rev() { - if let Effect::DropShadow(s) = e { - let mut m = fx(i, 0); - if s.knocks_out { - // The layer hides the shadow beneath it where its fill is see-through (at 100 % - // fill in a normal mode it covers it anyway; at 0 % the shape shows the bare - // backdrop), and wholly in a mode that blends with it ([`shadow_see_through`]). - knock_out_exterior(&mut m, &shape, 1.0 - shadow_see_through(layer)); - } - paint_color(&mut work, &m, rgb(&s.color), s.common.blend, s.common.opacity); - } - } - for (i, e) in rev() { - if let Effect::OuterGlow(g) = e { - let mut m = fx(i, 0); - // The glow is behind the shape, not painted across its interior when Fill is 0 %. - // Preserve the existing anti-aliased edge when the fill is fully opaque. - knock_out_exterior(&mut m, &shape, layer.fill_opacity); - paint_glow(&mut work, &m, g, sb, anchor, big, patterns); - } - } - - // The layer: content at fill opacity, then interior effects. Interior effects are painted - // relative to the layer's shape (alpha = coverage within the shape), then the shape's alpha - // applies: a colour overlay at 100 % replaces the colour of a half-transparent edge pixel and - // keeps its alpha, as in Photoshop. - let fill = layer.fill_opacity; - // Blend Interior Effects as Group: the interior effects (overlays, satin, inner glow) are - // combined with the content first, and fill opacity applies to the combination. - let interior_group = layer.advanced.blend_interior && fill < 1.0; - let content_fill = if interior_group { 1.0 } else { fill }; - let inside = |a: f32| a > INSIDE_EPS; - // Within an outline (or a split-off vector stroke) the content's own transparency (a fading - // gradient fill) acts like fill opacity: the effects still cover the whole shape. - let lay_alpha = |i: usize, p: &[f32; 4], a: f32| { - if !inside(a) { - 0.0 - } else if relative { - content_fill * (kmask(i) * p[3] / a).min(1.0) - } else { - content_fill - } - }; - let mut lay = Buffer { rect: big, px: content.px.iter().zip(&shape.v).enumerate().map(|(i, (p, a))| [p[0], p[1], p[2], lay_alpha(i, p, *a)]).collect() }; - let gamma = crate::text_gamma(layer); - let premerge = premerges_layer(layer); - if premerge { - for (lp, wp) in lay.px.iter_mut().zip(&work.px) { - *lp = psblend::composite_gamma(layer.blend, *wp, *lp, 1.0, gamma); - } - } - let rel = |m: Map| -> Map { - let v = m.v.iter().zip(&shape.v).map(|(m, a)| if inside(*a) { (m / a).min(1.0) } else { 0.0 }).collect(); - Map { w: m.w, h: m.h, v } - }; - let full = Map { w, h, v: shape.v.iter().map(|a| if inside(*a) { 1.0 } else { 0.0 }).collect() }; - for (_, e) in rev() { - if let Effect::PatternOverlay { common, name, id, scale, angle, link, phase } = e { - paint_pattern(&mut lay, &full, patterns, name, id, Placement::anchored(anchor, *link, *phase, *scale, *angle), big, common.blend, common.opacity); - } - } - for (_, e) in rev() { - if let Effect::GradientOverlay { common, gradient, .. } = e { - paint_fx(&mut lay, &full, &FxPaint::Gradient(gradient.clone()), sb, anchor, big, common.blend, common.opacity, patterns) - } - } - for (_, e) in rev() { - if let Effect::ColorOverlay { common, color } = e { - paint_color(&mut lay, &full, rgb(color), common.blend, common.opacity); - } - } - for (i, e) in rev() { - if let Effect::Satin(s) = e { - let m = rel(fx(i, 0)); - paint_color(&mut lay, &m, rgb(&s.color), s.common.blend, s.common.opacity); - } - } - for (i, e) in rev() { - if let Effect::InnerGlow(g) = e { - paint_glow(&mut lay, &rel(fx(i, 0)), g, sb, anchor, big, patterns); - } - } - if interior_group { - for p in &mut lay.px { - p[3] *= fill.max(0.0); - } - } - for (i, e) in rev() { - if let Effect::InnerShadow(s) = e { - let m = rel(fx(i, 0)); - paint_color(&mut lay, &m, rgb(&s.color), s.common.blend, s.common.opacity); - } - } - // A stroked shape's vector stroke: Photoshop draws it above the fill's clipped layers and - // interior effects, below the stroke effect (psd-tools stroke-composite). - if let Some(vs) = &vstroke { - for (i, ((p, s), a)) in lay.px.iter_mut().zip(&vs.stroke.px).zip(&shape.v).enumerate() { - if s[3] > 0.0 && inside(*a) { - *p = psblend::composite(BlendMode::Normal, *p, [s[0], s[1], s[2], fill * (kmask(i) * s[3] / a).min(1.0)], 1.0); - } - } - } - // Strokes. Inside parts are painted over the layer (bottom instance first); outside parts - // are slid beneath it, so the first listed (top) instance is processed first. - let strokes: Vec<&photocraft_doc::StrokeFx> = items.iter().filter_map(|e| if let Effect::Stroke(s) = e { Some(s) } else { None }).collect(); - let ready = !strokes.is_empty(); - let din = if ready { maps.din.as_ref().map(|a| maps.crop_vec(a, big, 0.0)).unwrap_or_default() } else { Vec::new() }; - // A stroke's outer edge picks the chamfer or the exact field by its width - // ([`stroke_outside_exact`]); both are cropped here, and only the ones a stroke needs exist. - let crop_out = |v: &Option>| v.as_ref().map(|b| maps.crop_vec(b, big, FAR)); - let (dout, dout_exact, vdout, vdout_exact) = - if ready { (crop_out(&maps.dout), crop_out(&maps.dout_exact), crop_out(&maps.vdout), crop_out(&maps.vdout_exact)) } else { (None, None, None, None) }; - let widths = stroke_widths; - // A gradient stroke aligned with the layer spans the stroke's own extent. - let frame = |st: &photocraft_doc::StrokeFx| maps.stroke_frame(st).unwrap_or(sb); - for st in strokes.iter().rev().copied() { - let (in_w, _) = widths(st); - if in_w <= 0.0 { - continue; - } - let mut m = Map::new(w, h, 0.0); - for ((mv, a), dv) in m.v.iter_mut().zip(&shape.v).zip(&din) { - *mv = if inside(*a) { (in_w + 0.5 - dv).clamp(0.0, 1.0) } else { 0.0 }; - } - paint_fx(&mut lay, &m, &st.paint, frame(st), anchor, big, st.common.blend, st.common.opacity, patterns); - } - for (i, e) in rev() { - if let Effect::BevelEmboss(b) = e - && maps.bevel_paint[i] == BevelPaint::Inner - { - let (hi, sh) = (rel(fx(i, 0)), rel(fx(i, 1))); - paint_color(&mut lay, &hi, rgb(&b.highlight_color), b.highlight.blend, b.highlight.opacity); - paint_color(&mut lay, &sh, rgb(&b.shadow_color), b.shadow.blend, b.shadow.opacity); - } - } - // The shape's own alpha. - for (p, a) in lay.px.iter_mut().zip(&shape.v) { - p[3] *= a.min(1.0); - } - // Shape layers without a filled outline stroke their vector outline, estimated from local - // coverage; every other layer strokes its shape. The width then picks the field. - let vector_outline = vector_shape && !maps.outline; - // Outside parts lie beneath the layer and blend onto the backdrop with their own mode. A - // higher stroke covers the ones below it (Photoshop: a Multiply stroke listed above a wider - // Normal stroke multiplies the backdrop, not the lower stroke). Each stroke's share is its - // coverage × opacity not yet taken by strokes above; for Normal strokes this equals stacking - // them top over bottom. - if strokes.iter().any(|st| widths(st).1 > 0.0) { - let base = work.clone(); - let mut acc = vec![[0.0f32; 4]; w * h]; // premultiplied Σ share·blended - let mut cover = vec![0.0f32; w * h]; - for st in strokes.iter().copied() { - let (_, out_w) = widths(st); - if out_w <= 0.0 { - continue; - } - // Shape layers: Photoshop strokes the vector outline (estimated from local coverage - // for unfilled shapes); the stroke never shows through the shape's pixels. Along a - // filled shape's outline it covers the part of each edge pixel outside the path. - let exact = stroke_outside_exact(out_w); - let d: &[f32] = if vector_outline { - (if exact { vdout_exact.as_deref() } else { vdout.as_deref() }).unwrap_or_default() - } else if exact { - dout_exact.as_deref().unwrap_or_default() - } else { - dout.as_deref().unwrap_or_default() - }; - let mut share = vec![0.0f32; w * h]; - for (i, sh) in share.iter_mut().enumerate() { - let band = (out_w + 0.5 - d[i]).clamp(0.0, 1.0); - let k = - if inside(shape.v[i]) { if vector_shape && !maps.outline { 0.0 } else { band * outline_share(shape.v[i], lay.px[i][3]) } } else { band }; - let mut k = k * st.common.opacity; - if st.common.blend == BlendMode::Dissolve { - let (x, y) = (i64::from(big.x0) + (i % w) as i64, i64::from(big.y0) + (i / w) as i64); - k = if k > 0.0 && dissolves_in(x, y, k) { 1.0 } else { 0.0 }; - } - *sh = k * (1.0 - cover[i]); - cover[i] += *sh; - } - // The stroke blended over the backdrop at full coverage. - let mut blended = base.clone(); - let ones = Map { w, h, v: share.iter().map(|&s| if s > 0.0 { 1.0 } else { 0.0 }).collect() }; - // The share already carries the Dissolve choice, so the paint itself composites as Normal. - let paint_blend = if st.common.blend == BlendMode::Dissolve { BlendMode::Normal } else { st.common.blend }; - paint_fx(&mut blended, &ones, &st.paint, frame(st), anchor, big, paint_blend, 1.0, patterns); - for ((a, b), s) in acc.iter_mut().zip(&blended.px).zip(&share) { - if *s > 0.0 { - for c in 0..3 { - a[c] += s * b[c] * b[3]; - } - a[3] += s * b[3]; - } - } - } - for ((p, a), c) in work.px.iter_mut().zip(&acc).zip(&cover) { - if *c <= 0.0 { - continue; - } - let k = 1.0 - c.min(1.0); - let alpha = p[3] * k + a[3]; - if alpha > 0.0 { - *p = [(p[0] * p[3] * k + a[0]) / alpha, (p[1] * p[3] * k + a[1]) / alpha, (p[2] * p[3] * k + a[2]) / alpha, alpha.min(1.0)]; - } - } - } - for (i, e) in rev() { - if let Effect::BevelEmboss(b) = e - && maps.bevel_paint[i] == BevelPaint::Outer - { - let (hi, sh) = (fx(i, 0), fx(i, 1)); - paint_color(&mut work, &hi, rgb(&b.highlight_color), b.highlight.blend, b.highlight.opacity); - paint_color(&mut work, &sh, rgb(&b.shadow_color), b.shadow.blend, b.shadow.opacity); - } - } - - // Layer (with interior effects) onto the exterior result, in the layer's mode. - let mode = if premerge || layer.blend == BlendMode::PassThrough { BlendMode::Normal } else { layer.blend }; - for (wp, lp) in work.px.iter_mut().zip(&lay.px) { - if lp[3] > 0.0 { - *wp = psblend::composite_gamma(mode, *wp, *lp, 1.0, gamma); - } - } - // Emboss styles shade the composited layer (their maps cover inside and outside). Painting - // them into the layer before its (text-gamma) composite left a type layer's lit top edges up - // to 6/255 dark (psd-tools layer_effects Emboss: 7.8 → 5.7/255). - for (i, e) in rev() { - if let Effect::BevelEmboss(b) = e - && maps.bevel_paint[i] == BevelPaint::Both - { - paint_color(&mut work, &fx(i, 0), rgb(&b.highlight_color), b.highlight.blend, b.highlight.opacity); - paint_color(&mut work, &fx(i, 1), rgb(&b.shadow_color), b.shadow.blend, b.shadow.opacity); - } - } - // Layer opacity applies to the whole stack. - let op = layer.opacity; - for y in rect.y0..rect.y1 { - for x in rect.x0..rect.x1 { - let i = ((y - rect.y0) as usize) * rect.width() as usize + (x - rect.x0) as usize; - let a = before.px[i]; - let b = if x >= big.x0 && x < big.x1 && y >= big.y0 && y < big.y1 { work.px[((y - big.y0) as usize) * w + (x - big.x0) as usize] } else { a }; - backdrop.px[i] = if layer.blend == BlendMode::Dissolve { - // Dissolve applies layer opacity to the completed interior/exterior effect - // stack as pixel coverage, not continuous gray interpolation (#3051). - if crate::dissolve_noise(x, y) < op { b } else { a } - } else { - mix_premul(a, b, op) - }; - } - } -} - -/// Coverage of an outside stroke beneath a filled shape's edge pixel, for a pixel the outline -/// covers `cov` of and the layer (with its interior effects) ends at alpha `l`. Photoshop treats -/// the stroke and the shape as disjoint areas: the stroke fills the part outside the path and -/// the layer adds its own alpha (psd-tools stroke-effects: a 58 % covered edge pixel of an -/// opaque fill ends opaque, one of a faded fill at 42 % + its alpha). Composited beneath the -/// layer, `share + l (1 - share) = (1 - cov) + l`. -pub fn outline_share(cov: f32, l: f32) -> f32 { - let outside = (1.0 - cov.clamp(0.0, 1.0)).max(0.0); - if outside <= 1e-6 { - return 0.0; - } - let rest = 1.0 - l.clamp(0.0, 1.0); - if rest <= 1e-6 { 1.0 } else { (outside / rest).min(1.0) } -} - -/// (inside width, outside width) of a stroke. -pub fn stroke_widths(st: &photocraft_doc::StrokeFx) -> (f32, f32) { - match st.position { - StrokePosition::Outside => (0.0, st.size), - StrokePosition::Inside => (st.size, 0.0), - StrokePosition::Center => (st.size / 2.0, st.size / 2.0), - } -} - -/// The frame a gradient stroke aligned with the layer is laid out in: the pixel bounds of the -/// effect shape (over `rect`) grown by the stroke's outside width less one pixel. Photoshop -/// spans the gradient over the stroke's extent, not the layer's: a 4 px outside stroke around a -/// 22 px square runs its 90° gradient over 28 px (psd-tools stroke-effects), a 3 px one around -/// 36 px of type over 40 px (psd-tools effect-stroke-gradient). -fn stroke_frame(shape: &Map, out_w: f32, rect: Rect) -> Rect { - let (mut x0, mut y0, mut x1, mut y1) = (usize::MAX, usize::MAX, 0usize, 0usize); - for y in 0..shape.h { - for x in 0..shape.w { - if shape.v[y * shape.w + x] > INSIDE_EPS { - (x0, y0, x1, y1) = (x0.min(x), y0.min(y), x1.max(x + 1), y1.max(y + 1)); - } - } - } - if x0 == usize::MAX { - return rect; - } - let grow = if out_w.is_finite() { (out_w.min(MAX_REACH).ceil() as i32 - 1).max(0) } else { 0 }; - Rect::new(rect.x0 + x0 as i32, rect.y0 + y0 as i32, rect.x0 + x1 as i32, rect.y0 + y1 as i32).inflate(grow) -} - -/// A stroked shape's vector stroke, composited apart from its fill (which the compositor then -/// passes unmasked): the stroke's pixels over the render rect and the layer's mask values. -pub(crate) struct VectorStroke<'a> { - pub stroke: &'a Buffer, - pub mask: Option<&'a [f32]>, -} - -/// Premultiplied linear interpolation between two straight-alpha pixels. -fn mix_premul(a: [f32; 4], b: [f32; 4], k: f32) -> [f32; 4] { - let alpha = a[3] + (b[3] - a[3]) * k; - if alpha <= 0.0 { - return [0.0; 4]; - } - let mut out = [0.0; 4]; - for c in 0..3 { - out[c] = (a[c] * a[3] + (b[c] * b[3] - a[c] * a[3]) * k) / alpha; - } - out[3] = alpha; - out -} - -/// A distance field of an effect shape, as the map builders above compute it (for the GPU -/// compositor, which builds the rest of the maps itself; keep in sync with `shadow_map`, -/// `glow_map`, `bevel_maps` and `build_maps`). -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub enum FieldKind { - /// `dist_outside` of the shape: precise outer glows. - Outside, - /// `dist_inside` of the shape: precise inner glows. - Inside, - /// `bevel_dist_outside` of the shape: the outside distance of chiselled bevels. - BevelOutside, - /// `bevel_dist_inside` of the shape: the inside distance of chiselled bevels. - BevelInside, - /// Chamfer distance outside the shape: a narrow raster stroke's outer edge (see - /// [`stroke_outside_exact`]), and the spread of drop shadows and softer outer glows - /// ([`dilate`]); their metric is fitted to Photoshop (#224) and keeps the sub-pixel seeding. - StrokeOutside, - /// Chamfer distance outside `1 - alpha`: the choke of inner shadows and softer inner glows. - ChokeInside, - /// Stroke distance inside the shape. - StrokeInside, - /// Exact Euclidean distance outside the shape: a wide raster stroke's outer edge (see - /// [`stroke_outside_exact`]). The chamfer's level sets are polygons (an ~8-fold octagon), so a - /// wide stroke's outer boundary facets; the shadow / glow spread above keeps the chamfer (#3646). - StrokeOutsideExact, - /// Stroke distance outside a shape layer's outline (from its local coverage), exact Euclidean. - StrokeOutsideVector, - /// Chamfer distance outside a shape layer's outline (from its local coverage): a narrow vector - /// stroke's outer edge, where the chamfer matches Photoshop (see [`STROKE_CHAMFER_MAX`]). - StrokeOutsideVectorChamfer, -} - -/// The `kind` distance field of the shape `alpha` (row-major `w × h`). Values past `reach` pixels -/// from the shape's edge are only meant to be large (the bevel fields skip refining them). -pub fn distance_field(kind: FieldKind, alpha: Vec, w: usize, h: usize, reach: f32) -> Vec { - let s = Map { w, h, v: alpha }; - match kind { - FieldKind::Outside => dist_outside(&s), - FieldKind::Inside => dist_inside(&s), - FieldKind::BevelOutside => bevel_dist_outside(&s, &sharp_edges(&s), reach), - FieldKind::BevelInside => bevel_dist_inside(&s, &sharp_edges(&s), reach), - FieldKind::StrokeOutside => dist_outside_by(&s, Metric::Chamfer), - FieldKind::ChokeInside => dist_outside_by(&s.map(|a| 1.0 - a), Metric::Chamfer), - FieldKind::StrokeInside => dist_inside_by(&s, Metric::Chamfer), - FieldKind::StrokeOutsideExact => dist_outside_by(&s, Metric::Euclidean), - FieldKind::StrokeOutsideVector => dist_outside_by(&local_coverage(&s), Metric::Euclidean), - FieldKind::StrokeOutsideVectorChamfer => dist_outside_by(&local_coverage(&s), Metric::Chamfer), - } -} - -/// Both chiselled bevel fields of `alpha`, `[BevelInside, BevelOutside]`: each is its -/// [`distance_field`], with the sharp edges they both start from found once. -pub fn bevel_distance_fields(alpha: Vec, w: usize, h: usize, reach: f32) -> [Vec; 2] { - bevel_dists(&Map { w, h, v: alpha }, reach) -} - -/// The inside and outside bevel distances of `s`, from one set of sharp edges. -fn bevel_dists(s: &Map, reach: f32) -> [Vec; 2] { - let sharp = sharp_edges(s); - [bevel_dist_inside(s, &sharp, reach), bevel_dist_outside(s, &sharp, reach)] -} - #[cfg(test)] -mod tests { - use super::*; - - /// Runs `f` with every parallel pass on this thread using `n` threads (1 = in order), whatever its size. - fn with_threads(n: usize, f: impl FnOnce() -> R) -> R { - struct Restore(Option); - impl Drop for Restore { - fn drop(&mut self) { - THREADS.with(|t| t.set(self.0)); - } - } - let _restore = Restore(THREADS.with(|t| t.replace(Some(n)))); - f() - } - - fn bits(v: &[f32]) -> Vec { - v.iter().map(|x| x.to_bits()).collect() - } - - #[test] - fn edt_is_exact() { - let (w, h) = (7, 5); - let mut inside = vec![false; w * h]; - inside[2 * w + 3] = true; - let d = edt(&inside, w, h); - assert_eq!(d[2 * w + 3], 0.0); - assert!((d[2 * w + 6] - 3.0).abs() < 1e-6); - assert!((d[0] - (9.0f32 + 4.0).sqrt()).abs() < 1e-5); - assert!((d[4 * w + 5] - (4.0f32 + 4.0).sqrt()).abs() < 1e-5); - } - - #[test] - fn edt_two_seeds() { - let (w, h) = (10, 1); - let mut inside = vec![false; w]; - inside[0] = true; - inside[9] = true; - let d = edt(&inside, w, h); - assert_eq!(d, vec![0.0, 1.0, 2.0, 3.0, 4.0, 4.0, 3.0, 2.0, 1.0, 0.0]); - } - - #[test] - fn blur_preserves_mass() { - let mut m = Map::new(21, 21, 0.0); - m.v[10 * 21 + 10] = 1.0; - blur(&mut m, 6.0); - let sum: f32 = m.v.iter().sum(); - assert!((sum - 1.0).abs() < 1e-4, "{sum}"); - assert!(m.v[10 * 21 + 10] < 1.0); - } - - #[test] - fn gradient_geometry() { - let b = Rect::new(0, 0, 100, 100); - let t = |s, x, y| gradient_t(s, 0.0, 1.0, false, (0.0, 0.0), b, x, y); - assert!(t(GradientStyle::Linear, 0.0, 50.0) < 0.01); - // Linear / reflected sample pixel corners: the centre is reached half a pixel later. - assert!((t(GradientStyle::Linear, 50.5, 50.0) - 0.5).abs() < 1e-6); - assert!(t(GradientStyle::Linear, 100.0, 50.0) > 0.99); - assert!(t(GradientStyle::Reflected, 50.5, 50.0) < 1e-6); - assert!((t(GradientStyle::Reflected, 0.0, 50.0) - 1.0).abs() < 1e-6); - assert!(t(GradientStyle::Radial, 50.0, 50.0) < 1e-6); - assert!((t(GradientStyle::Radial, 50.0, 0.0) - 1.0).abs() < 1e-6); - assert!((t(GradientStyle::Diamond, 75.0, 75.0) - 1.0).abs() < 1e-6); - let ang = t(GradientStyle::Angle, 50.0, 0.0); - assert!((ang - 0.75).abs() < 1e-3, "{ang}"); - let rev = gradient_t(GradientStyle::Linear, 0.0, 1.0, true, (0.0, 0.0), b, 0.0, 50.0); - assert!(rev > 0.99); - } - - #[test] - fn effect_gradients_snap_end_points_and_sample_corners() { - // 87° over 600 × 60 at (99, 422): end points (397, 482) and (400, 422), so the overlay runs - // along (3, -60) from its midpoint (398.5, 452), sampled at pixel corners. - let frame = Rect::new(99, 422, 699, 482); - let (a, sc, o) = crate::fill_layout::gradient_layout(GradientStyle::Linear, 87.0, 1.0, (0.0, 0.0), frame); - assert!((a - (60f32).atan2(3.0).to_degrees()).abs() < 1e-3, "{a}"); - let t = |x: f32, y: f32| gradient_t(GradientStyle::Linear, a, sc, false, o, frame, x, y); - assert!((t(399.0, 452.5) - 0.5).abs() < 1e-4, "{}", t(399.0, 452.5)); - assert!(t(400.5, 422.5) > 0.99 && t(397.5, 482.5) < 0.01); - } - - #[test] - fn chamfer_uses_euclidean_step_lengths() { - let (w, h) = (9, 9); - let mut inside = vec![false; w * h]; - inside[0] = true; - let (d, near) = chamfer_nearest(&inside, w, h); - let at = |x: usize, y: usize| d[y * w + x]; - assert!((at(3, 0) - 3.0).abs() < 1e-5); - assert!((at(2, 2) - 2.0 * std::f32::consts::SQRT_2).abs() < 1e-5); - assert!((at(1, 2) - 5f32.sqrt()).abs() < 1e-5); - assert!((at(1, 3) - (5f32.sqrt() + 1.0)).abs() < 1e-5, "knight + straight, not √10"); - assert!((at(2, 3) - (5f32.sqrt() + std::f32::consts::SQRT_2)).abs() < 1e-5); - assert!(near.iter().all(|&n| n == 0)); - } - - #[test] - fn spread_dilates_with_the_chamfer_metric() { - // One opaque pixel grown by 3 px: at offset (1, 3) the chamfer distance is √5 + 1 = 3.236 - // (Euclidean 3.162), so the anti-aliased rim keeps 3 + 0.5 − (3.236 − 0.5) = 0.764. - let mut m = Map::new(9, 9, 0.0); - m.v[4 * 9 + 4] = 1.0; - let d = dilate(&m, 3.0); - assert!((d.v[7 * 9 + 5] - 0.764).abs() < 1e-3, "{}", d.v[7 * 9 + 5]); - // (2, 3): √5 + √2 = 3.650 (Euclidean 3.606) leaves 0.350; axis steps are exact. - assert!((d.v[7 * 9 + 6] - (4.0 - 5f32.sqrt() - std::f32::consts::SQRT_2)).abs() < 1e-4, "{}", d.v[7 * 9 + 6]); - assert_eq!(d.v[4 * 9 + 7], 1.0); - } - - #[test] - fn running_sum_tent_matches_the_kernel() { - let (w, h) = (37usize, 23usize); - let src: Vec = (0..w * h).map(|i| ((i * 7919) % 101) as f32 / 100.0).collect(); - for width in [1.0f32, 2.0, 3.5, 5.0, 8.25, 41.0] { - let mut m = Map { w, h, v: src.clone() }; - tent(&mut m, width); - let mut want = Map { w, h, v: src.clone() }; - tent_direct(&mut want, width); - for (a, b) in m.v.iter().zip(&want.v) { - assert!((a - b).abs() < 1e-5, "width {width}: {a} vs {b}"); - } - } - } - - #[test] - fn tent_kernel_is_two_boxes() { - let (r, k) = tent_kernel(5.0); - assert_eq!(r, 4); - let sum: f32 = k.iter().sum(); - assert!((sum - 1.0).abs() < 1e-6); - assert!((k[4] - 5.0 / 25.0).abs() < 1e-6 && (k[0] - 1.0 / 25.0).abs() < 1e-6); - // Fractional widths taper the end taps; width 1 is the identity. - let (r, k) = tent_kernel(4.0); - assert_eq!(r, 4); - assert!(k[0] > 0.0 && k[0] < 1.0 / 25.0); - assert_eq!(tent_kernel(1.0), (0, vec![1.0])); - // #1543: a huge, infinite or NaN width is capped, not turned into a kernel of 2^62 taps. - for w in [1e30, f32::INFINITY, f32::MAX] { - assert_eq!(tent_kernel(w), tent_kernel(MAX_REACH), "{w}"); - } - assert_eq!(tent_kernel(f32::NAN), (0, vec![1.0])); - } - - fn no_tex() -> TextureCtx<'static> { - TextureCtx { rect: Rect::new(0, 0, 1, 1), patterns: &[], anchor: (0.0, 0.0) } - } - - fn square(n: usize, x0: usize, x1: usize) -> Map { - let mut m = Map::new(n, n, 0.0); - for y in x0..x1 { - for x in x0..x1 { - m.v[y * n + x] = 1.0; - } - } - m - } - - fn bevel_of(style: BevelStyle, technique: BevelTechnique) -> Bevel { - Bevel { - enabled: true, - style, - technique, - depth: 1.0, - up: true, - size: 5.0, - soften: 0.0, - angle: 90.0, - altitude: 30.0, - use_global_light: false, - gloss_contour: Contour::Linear, - gloss_anti_alias: false, - highlight: photocraft_doc::FxCommon::new(BlendMode::Screen, 0.75), - highlight_color: photocraft_color::Color::WHITE, - shadow: photocraft_doc::FxCommon::new(BlendMode::Multiply, 0.75), - shadow_color: photocraft_color::Color::BLACK, - contour: None, - texture: None, - } - } - - #[test] - fn smooth_inner_bevel_lights_the_top_edge_inside_only() { - let shape = square(40, 10, 30); - let (maps, paint) = bevel_maps( - &shape, - &bevel_of(BevelStyle::InnerBevel, BevelTechnique::Smooth), - &GlobalLight::default(), - &no_tex(), - &PreparedPatterns::new(&[], PREPARED_PATTERN_BYTES), - ); - assert_eq!(paint, BevelPaint::Inner); - let at = |m: &Map, x: usize, y: usize| m.v[y * 40 + x]; - // Light from the top: highlight along the top edge, shadow along the bottom, flat middle. - assert!(at(&maps[0], 20, 10) > 0.5 && at(&maps[1], 20, 10) == 0.0); - assert!(at(&maps[1], 20, 29) > 0.5); - assert!(at(&maps[0], 20, 20) < 1e-3 && at(&maps[1], 20, 20) < 1e-3); - // Nothing outside the shape; the ramp reaches about `size` inside. - assert_eq!(at(&maps[0], 20, 8), 0.0); - assert!(at(&maps[0], 20, 15) < 0.05); - } - - /// Photoshop 27.11, measured across a straight edge (size 10, depth 100 %, light from the top - /// at 30°): a chisel facet has the slope `depth × size / (2 (size + 1))`, flat right up to the - /// edge pixel for Inner Hard; Inner Soft's edge pixel is half as steep again; Outer Hard - /// still shades, partly, the pixel where its ramp reaches zero `size + 1½` px out. - #[test] - fn chisel_facets_match_photoshop() { - let amount = |g: f32| { - let (se, ce) = 30f32.to_radians().sin_cos(); - ((g * ce + se) / (1.0 + g * g).sqrt() - se) / (1.0 - se) - }; - let n = 80; - let shape = square(n, 20, 60); - let maps = |style, technique| { - let mut b = bevel_of(style, technique); - b.size = 10.0; - bevel_maps(&shape, &b, &GlobalLight::default(), &no_tex(), &PreparedPatterns::new(&[], PREPARED_PATTERN_BYTES)).0 - }; - let at = |m: &Map, y: usize| m.v[y * n + 40]; - let facet = amount(10.0 / 22.0); - let hard = maps(BevelStyle::InnerBevel, BevelTechnique::ChiselHard); - for y in 20..30 { - assert!((at(&hard[0], y) - facet).abs() < 0.01, "inner hard facet at row {y}: {} vs {facet}", at(&hard[0], y)); - } - assert!(at(&hard[0], 30) > 0.05 && at(&hard[0], 30) < facet, "one partial pixel at the end"); - let soft = maps(BevelStyle::InnerBevel, BevelTechnique::ChiselSoft); - assert!((at(&soft[0], 20) - amount(1.5 * 10.0 / 22.0)).abs() < 0.01, "steeper edge pixel: {}", at(&soft[0], 20)); - assert!((at(&soft[0], 24) - facet).abs() < 0.01, "then Chisel Hard's facet"); - let outer = maps(BevelStyle::OuterBevel, BevelTechnique::ChiselHard); - // Below the shape (rows 60..): shadow facet through 10½ px, partial at 11½. - assert!((at(&outer[1], 70) - at(&outer[1], 61)).abs() < 1e-4); - assert!(at(&outer[1], 71) > 0.05 && at(&outer[1], 71) < at(&outer[1], 70)); - assert_eq!(at(&outer[1], 72), 0.0); - } - - #[test] - fn emboss_paints_both_sides_and_pillow_flips_the_outside() { - let shape = square(40, 10, 30); - let l = GlobalLight::default(); - let (e, paint) = - bevel_maps(&shape, &bevel_of(BevelStyle::Emboss, BevelTechnique::Smooth), &l, &no_tex(), &PreparedPatterns::new(&[], PREPARED_PATTERN_BYTES)); - assert_eq!((paint, e.len()), (BevelPaint::Both, 2)); - let at = |m: &Map, x: usize, y: usize| m.v[y * 40 + x]; - // Emboss: the slope across the top edge faces the light on both sides. - assert!(at(&e[0], 20, 10) > 0.3 && at(&e[0], 20, 9) > 0.3); - let (p, _) = - bevel_maps(&shape, &bevel_of(BevelStyle::PillowEmboss, BevelTechnique::Smooth), &l, &no_tex(), &PreparedPatterns::new(&[], PREPARED_PATTERN_BYTES)); - assert!(at(&p[0], 20, 10) > 0.3 && at(&p[1], 20, 9) > 0.3, "pillow: outside top edge in shadow"); - } - - #[test] - fn emboss_width_rounds_up_and_shades_past_the_blur() { - let mut b = bevel_of(BevelStyle::Emboss, BevelTechnique::Smooth); - b.size = 41.0; - let g = bevel_geom(&b); - assert_eq!((g.width, g.depth), (21.0, 21.0)); - b.size = 5.0; - assert_eq!(bevel_geom(&b).width, 3.0); - // The first row past the height blur's reach still slopes (its upper neighbour is raised), - // so it shades; the row after it does not. - let shape = square(60, 20, 40); - b.size = 9.0; - b.angle = 90.0; - let (m, _) = bevel_maps(&shape, &b, &GlobalLight::default(), &no_tex(), &PreparedPatterns::new(&[], PREPARED_PATTERN_BYTES)); - let reach = tent_kernel(bevel_geom(&b).width).0 as usize; - let row = 39 + reach + 1; // last shape row + reach + 1: height 0, neighbour above raised - assert!(m[1].v[row * 60 + 30] > 0.0, "{}", m[1].v[row * 60 + 30]); - assert_eq!(m[1].v[(row + 1) * 60 + 30], 0.0); - } - - /// A `len` x `wid` bar through the middle of a `w` x `h` map at `deg` degrees, anti-aliased by - /// 16 x 16 supersampling (the coverage a scanline rasteriser gives). - fn aa_bar(w: usize, h: usize, deg: f32, len: f32, wid: f32) -> Map { - let (sn, cs) = deg.to_radians().sin_cos(); - let (cx, cy) = (w as f32 / 2.0, h as f32 / 2.0); - let mut m = Map::new(w, h, 0.0); - const N: usize = 16; - for y in 0..h { - for x in 0..w { - let mut hit = 0; - for sy in 0..N { - for sx in 0..N { - let (px, py) = (x as f32 + (sx as f32 + 0.5) / N as f32 - cx, y as f32 + (sy as f32 + 0.5) / N as f32 - cy); - let (u, v) = (px * cs + py * sn, -px * sn + py * cs); - hit += usize::from(u.abs() <= len / 2.0 && v.abs() <= wid / 2.0); - } - } - m.v[y * w + x] = hit as f32 / (N * N) as f32; - } - } - m - } - - /// Ripple and bias of a distance field on an `aa_bar` (`inside` or outside it): the worst - /// standard deviation of the error among pixels at the same true distance from a long edge - /// (0.5 px bins, 0.6..8 px, away from the ends), and the worst mean error of a bin. A constant - /// offset is no ripple: only a field that varies along the edge shades in stripes. - fn bar_ripple(f: &[f32], w: usize, h: usize, deg: f32, wid: f32, inside: bool) -> (f32, f32) { - let (sn, cs) = deg.to_radians().sin_cos(); - let mut bins: Vec> = vec![Vec::new(); 16]; - for y in 0..h { - for x in 0..w { - let (px, py) = (x as f32 + 0.5 - w as f32 / 2.0, y as f32 + 0.5 - h as f32 / 2.0); - let (u, v) = (px * cs + py * sn, -px * sn + py * cs); - let truth = if inside { wid / 2.0 - v.abs() } else { v.abs() - wid / 2.0 }; - if u.abs() < 40.0 && (0.6..8.0).contains(&truth) { - bins[(truth * 2.0) as usize].push(f[y * w + x] - truth); - } - } - } - let (mut ripple, mut bias) = (0.0f32, 0.0f32); - for b in bins.iter().filter(|b| b.len() > 8) { - let mean = b.iter().sum::() / b.len() as f32; - let sd = (b.iter().map(|e| (e - mean) * (e - mean)).sum::() / b.len() as f32).sqrt(); - ripple = ripple.max(sd); - bias = bias.max(mean.abs()); - } - (ripple, bias) - } - - /// The worst standard deviation of the chisel shading (highlight minus shadow) along lines - /// parallel to an `aa_bar` 2..6 px in from its edges, the way Issue #1926 measured stripes. - fn bar_shade_ripple(deg: f32, light: f32) -> f32 { - let (w, h) = (220usize, 220usize); - let bar = aa_bar(w, h, deg, 150.0, 16.0); - let mut b = bevel_of(BevelStyle::InnerBevel, BevelTechnique::ChiselHard); - (b.size, b.depth, b.angle, b.altitude) = (8.0, 2.2, light, 32.0); - let (m, _) = bevel_maps(&bar, &b, &GlobalLight::default(), &no_tex(), &PreparedPatterns::new(&[], PREPARED_PATTERN_BYTES)); - let (sn, cs) = deg.to_radians().sin_cos(); - let mut worst = 0.0f32; - for o in [-6.0f32, -5.0, -4.0, -3.0, -2.0, 2.0, 3.0, 4.0, 5.0, 6.0] { - let line: Vec = (-60..=60) - .map(|k| { - let t = k as f32 * 0.5; - let (x, y) = (w as f32 / 2.0 + t * cs - o * sn, h as f32 / 2.0 + t * sn + o * cs); - let i = y.floor() as usize * w + x.floor() as usize; - m[0].v[i] - m[1].v[i] - }) - .collect(); - let mean = line.iter().sum::() / line.len() as f32; - worst = worst.max((line.iter().map(|v| (v - mean) * (v - mean)).sum::() / line.len() as f32).sqrt()); - } - worst - } - - /// Coverage of a unit pixel by the half plane `n . p + s >= 0` (`p` from the pixel's centre), - /// by 64 x 64 supersampling. - fn half_plane_coverage(n: [f32; 2], s: f32) -> f32 { - const N: usize = 64; - let mut hit = 0; - for y in 0..N { - for x in 0..N { - let (px, py) = ((x as f32 + 0.5) / N as f32 - 0.5, (y as f32 + 0.5) / N as f32 - 0.5); - hit += usize::from(n[0] * px + n[1] * py + s >= 0.0); - } - } - hit as f32 / (N * N) as f32 - } - - #[test] - fn edge_offset_places_a_straight_edge_by_its_coverage() { - for step in 0..=12 { - let (sn, cs) = (step as f32 * 7.5).to_radians().sin_cos(); - for k in -12..=12 { - let s = k as f32 * 0.05; - let a = half_plane_coverage([cs, sn], s); - // Where the edge only just touches the pixel the coverage hardly moves with it. - if !(0.03..=0.97).contains(&a) { - continue; - } - let got = edge_offset([cs, sn], a); - assert!((got - s).abs() < 0.03, "{}deg s {s}: coverage {a} gave {got}", step as f32 * 7.5); - } - } - // Axis-aligned edges keep `alpha - 1/2`; a pixel no coverage says anything about is 0. - assert!((edge_offset([1.0, 0.0], 0.25) + 0.25).abs() < 1e-6); - assert!((edge_offset([0.0, 1.0], 0.9) - 0.4).abs() < 1e-6); - assert_eq!(edge_offset([0.6, 0.8], f32::NAN), 0.0); - } - - #[test] - fn bevel_distances_equal_the_plain_ones_without_anti_aliasing() { - // Hard edges (no partly covered pixel) and soft ramps (no sharp one) keep the plain fields. - let (w, h) = (96usize, 80usize); - let mut maps = Vec::new(); - for kind in 0..4 { - let mut m = Map::new(w, h, 0.0); - let mut seed = 12345u32; - for y in 0..h { - for x in 0..w { - let (dx, dy) = (x as f32 - 48.0, y as f32 - 40.0); - m.v[y * w + x] = match kind { - 0 => f32::from((50.0..90.0).contains(&(x as f32 * 0.6 + y as f32))), - 1 => f32::from(dx * dx + dy * dy < 30.0 * 30.0), - 2 => { - seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); - f32::from(seed >> 28 < 5 && x > 10 && x < 80) - } - _ => ((20.0 - (dx * dx + dy * dy).sqrt()) / 8.0).clamp(0.0, 1.0), - }; - } - } - maps.push(m); - } - for (i, m) in maps.iter().enumerate() { - let sharp = sharp_edges(m); - assert!(sharp.is_empty(), "map {i} has no anti-aliased edge"); - assert_eq!(bevel_dist_inside(m, &sharp, 1e9), dist_inside(m), "inside, map {i}"); - assert_eq!(bevel_dist_outside(m, &sharp, 1e9), dist_outside(m), "outside, map {i}"); - } - } - - #[test] - fn chisel_distance_has_no_ripple_along_oblique_edges() { - // The plain distance to a pixel's centre ripples with the staircase of an oblique edge (the - // stripes of Issue #1926); at 0 and 45 degrees the staircase is regular and it does not. - let (w, h) = (160, 160); - for deg in [0.0f32, 30.0, 45.0, 60.0, 75.0, 120.0, 150.0] { - let bar = aa_bar(w, h, deg, 120.0, 40.0); - let sharp = sharp_edges(&bar); - let inside = bar_ripple(&bevel_dist_inside(&bar, &sharp, 40.0), w, h, deg, 40.0, true); - let outside = bar_ripple(&bevel_dist_outside(&bar, &sharp, 40.0), w, h, deg, 40.0, false); - for (what, (ripple, bias)) in [("inside", inside), ("outside", outside)] { - assert!(ripple < 0.008 && bias < 0.01, "{deg} deg {what}: ripple {ripple}, bias {bias}"); - } - } - let plain = aa_bar(w, h, 60.0, 120.0, 40.0); - let (ripple, _) = bar_ripple(&dist_inside(&plain), w, h, 60.0, 40.0, true); - assert!(ripple > 0.1, "the plain field still ripples ({ripple}), so the test above means something"); - } - - #[test] - fn edge_normals_follow_straight_edges_to_a_fraction_of_a_degree() { - // The 3x3 gradient is 1-3 degrees off and the error is systematic; the line through the edge - // points of the pixels around one is not. - let (w, h, wid) = (160usize, 160usize, 40.0f32); - for deg in [30.0f32, 60.0, 75.0, 120.0, 150.0] { - let sharp = sharp_edges(&aa_bar(w, h, deg, 120.0, wid)); - let (sn, cs) = deg.to_radians().sin_cos(); - let (mut worst, mut seen) = (0.0f32, 0); - for (i, e) in sharp.iter() { - let (px, py) = ((i % w) as f32 + 0.5 - w as f32 / 2.0, (i / w) as f32 + 0.5 - h as f32 / 2.0); - let (u, v) = (px * cs + py * sn, -px * sn + py * cs); - if u.abs() > 40.0 || (wid / 2.0 - v.abs()).abs() > 1.5 { - continue; - } - let into = if v > 0.0 { [sn, -cs] } else { [-sn, cs] }; - worst = worst.max((e.normal[0] * into[0] + e.normal[1] * into[1]).clamp(-1.0, 1.0).acos().to_degrees()); - seen += 1; - } - assert!(seen > 100 && worst < 0.6, "{deg} deg: {seen} edge pixels, normal off by up to {worst} deg"); - } - } - - #[test] - fn chisel_distance_is_close_on_round_shapes() { - // Circles (a hard stretch of edge at each pole, where the edge lies on a pixel boundary) and - // rounded rectangles on whole pixels (straight hard edges joined to anti-aliased arcs): the - // distance to the sharp pixels alone is up to 0.3 px too long there, so the plain distance - // caps it. Errors are against the exact distance to the shape, 0.6..8 px from its edge. - let worst = |f: &[f32], w: usize, h: usize, sdf: &dyn Fn(f32, f32) -> f32, inside: bool| { - let mut mx = 0.0f32; - for y in 0..h { - for x in 0..w { - let t = sdf(x as f32 + 0.5, y as f32 + 0.5); - let truth = if inside { -t } else { t }; - if (0.6..8.0).contains(&truth) { - mx = mx.max((f[y * w + x] - truth).abs()); - } - } - } - mx - }; - for r in [20.0f32, 40.0, 70.0] { - let (w, h) = (200usize, 200usize); - let m = aa_disc(w, h, r); - let sharp = sharp_edges(&m); - let sdf = |x: f32, y: f32| (x - 100.0).hypot(y - 100.0) - r; - let (i, o) = (worst(&bevel_dist_inside(&m, &sharp, 12.0), w, h, &sdf, true), worst(&bevel_dist_outside(&m, &sharp, 12.0), w, h, &sdf, false)); - assert!(i < 0.05 && o < 0.07, "disc {r}: inside off by {i}, outside by {o}"); - } - for rad in [6.0f32, 12.0, 24.0] { - let (w, h) = (200usize, 160usize); - let m = aa_round_rect(w, h, 20.0, 20.0, 180.0, 140.0, rad); - let sharp = sharp_edges(&m); - let sdf = |x: f32, y: f32| { - let (qx, qy) = ((x - 100.0).abs() - (80.0 - rad), (y - 80.0).abs() - (60.0 - rad)); - qx.max(0.0).hypot(qy.max(0.0)) + qx.max(qy).min(0.0) - rad - }; - let (i, o) = (worst(&bevel_dist_inside(&m, &sharp, 12.0), w, h, &sdf, true), worst(&bevel_dist_outside(&m, &sharp, 12.0), w, h, &sdf, false)); - assert!(i < 0.08 && o < 0.2, "rounded rect, radius {rad}: inside off by {i}, outside by {o}"); - } - } - - #[test] - fn chisel_facets_are_flat_along_oblique_edges() { - // Issue #1926: the facets of a chiselled bar at 30, 60, 120, 150 degrees were striped. - for deg in [0.0f32, 30.0, 45.0, 60.0, 75.0, 120.0, 150.0] { - for light in [-90.0f32, 0.0, 45.0, 120.0] { - let ripple = bar_shade_ripple(deg, light); - assert!(ripple < 0.03, "{deg} deg bar, light {light}: shading ripple {ripple}"); - } - } - } - - #[test] - fn bevel_distances_survive_degenerate_maps() { - let cases: [(usize, usize, f32); 7] = [(0, 0, 0.0), (1, 1, 0.5), (1, 1, 1.0), (2, 2, 0.5), (3, 1, 0.3), (5, 5, f32::NAN), (4, 4, 1.0)]; - for (w, h, a) in cases { - let m = Map::new(w, h, a); - let sharp = sharp_edges(&m); - for reach in [0.0, 8.0, f32::NAN, f32::INFINITY, -3.0] { - assert_eq!(bevel_dist_inside(&m, &sharp, reach).len(), w * h); - assert_eq!(bevel_dist_outside(&m, &sharp, reach).len(), w * h); - } - } - // A single partly covered pixel in an empty map, and an edge on the map's border. - let mut m = Map::new(5, 5, 0.0); - m.v[12] = 0.4; - let _ = (bevel_dist_inside(&m, &sharp_edges(&m), 4.0), bevel_dist_outside(&m, &sharp_edges(&m), 4.0)); - let mut m = Map::new(8, 8, 0.0); - for y in 0..8 { - m.v[y * 8 + 7] = 1.0; - m.v[y * 8 + 6] = 0.5; - } - let _ = (bevel_dist_inside(&m, &sharp_edges(&m), 4.0), bevel_dist_outside(&m, &sharp_edges(&m), 4.0)); - } - - #[test] - fn par_units_visits_every_unit_once_with_its_own_slices() { - // Lengths that leave a short last unit, no second slice, units of different sizes, and nothing at all. - let cases: [(usize, usize, usize, usize); 8] = - [(0, 3, 0, 0), (1, 1, 1, 1), (10, 3, 0, 0), (64, 8, 64, 8), (65, 8, 13, 1), (200, 1, 200, 1), (7, 7, 14, 2), (9, 4, 0, 5)]; - for (la, ua, lb, ub) in cases { - for threads in [1, 2, 3, 8, 64] { - let (mut a, mut b) = (vec![0u32; la], vec![0u32; lb]); - let calls = std::sync::atomic::AtomicUsize::new(0); - with_threads(threads, || { - par_units( - la, - &mut a, - ua, - &mut b, - ub, - || (), - |_, u, sa, sb| { - calls.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - assert!(sa.len() <= ua && sb.len() <= ub); - for (k, v) in sa.iter_mut().enumerate() { - *v = (u * ua + k) as u32 + 1; - } - for (k, v) in sb.iter_mut().enumerate() { - *v = (u * ub + k) as u32 + 1; - } - }, - ); - }); - assert_eq!(calls.into_inner(), la.div_ceil(ua), "{la} {ua} {lb} {ub} on {threads}"); - assert!(a.iter().enumerate().all(|(i, &v)| v == i as u32 + 1), "a: {la} {ua} {lb} {ub} on {threads}"); - // `b` is written for the units that exist in `a` and no further. - let written = (la.div_ceil(ua) * ub).min(lb); - assert!(b.iter().enumerate().all(|(i, &v)| v == if i < written { i as u32 + 1 } else { 0 }), "b: {la} {ua} {lb} {ub} on {threads}"); - } - } - // A unit size of 0 does nothing. - let mut a = vec![1u8; 4]; - par_units(4, &mut a, 0, &mut [] as &mut [()], 0, || (), |_, _, _, _| panic!("no units")); - } - - #[test] - fn nearest_distances_do_not_depend_on_the_threads() { - // Sizes that do not divide into the thread groups, lines of 1 pixel, and a noisy map where - // many pixels are equally far from two seeds (the nearest one must resolve the same way). - for (w, h) in [(37usize, 23usize), (1, 40), (40, 1), (2, 2), (101, 3), (64, 64)] { - let mut seed = 7u32; - let inside: Vec = (0..w * h) - .map(|_| { - seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); - (seed >> 24).is_multiple_of(11) - }) - .collect(); - let (d1, n1) = with_threads(1, || edt_nearest(&inside, w, h)); - for threads in [2, 3, 8] { - let (d, n) = with_threads(threads, || edt_nearest(&inside, w, h)); - assert_eq!((bits(&d), n), (bits(&d1), n1.clone()), "{w}x{h} on {threads} threads"); - } - // And the nearest pixel is a seed at exactly that distance. - for (i, (&d, &q)) in d1.iter().zip(&n1).enumerate() { - if inside.iter().any(|&b| b) { - let (dx, dy) = ((i % w) as f32 - (q as usize % w) as f32, (i / w) as f32 - (q as usize / w) as f32); - assert!(inside[q as usize] && (dx.hypot(dy) - d).abs() < 1e-3, "{w}x{h} at {i}: {d} vs seed {q}"); - } - } - } - } - - #[test] - fn nearest_distances_survive_degenerate_sizes() { - // The slice does not match the size, or there is nothing: no panic, and a result per input pixel. - for (len, w, h) in [(0usize, 0usize, 0usize), (0, 5, 0), (0, 0, 5), (6, 2, 2), (6, 4, 2), (1, 0, 1)] { - let (d, n) = edt_nearest(&vec![true; len], w, h); - assert_eq!((d.len(), n.len()), (len, len), "{len} px as {w}x{h}"); - } - } - - #[test] - fn chisel_fields_do_not_depend_on_the_threads() { - // Edge pixels at every angle, curves, patchy opacity and an edge along the border, on sizes that - // leave short last groups; one thread (in order) is the reference. - let mut maps = vec![ - aa_disc(97, 83, 30.0), - aa_round_rect(131, 77, 9.0, 11.0, 120.0, 66.0, 14.0), - aa_bar(120, 120, 33.0, 100.0, 30.0), - aa_bar(90, 130, 60.0, 150.0, 25.0), - ]; - let mut patchy = aa_disc(101, 101, 40.0); - for (i, v) in patchy.v.iter_mut().enumerate() { - if (i % 101 / 13 + i / 101 / 17) % 5 == 0 { - *v *= 0.6; - } - } - maps.push(patchy); - maps.push(aa_bar(64, 64, 40.0, 220.0, 30.0)); - for (k, m) in maps.iter().enumerate() { - for reach in [3.0f32, 12.0] { - let one = with_threads(1, || (sharp_edges(m), distance_field_of(m, reach))); - for threads in [2, 5, 16] { - let many = with_threads(threads, || (sharp_edges(m), distance_field_of(m, reach))); - assert_eq!(one.0.slot, many.0.slot, "map {k} sharp slots on {threads} threads"); - let edges = |s: &SharpEdges| { - s.pixels.iter().map(|p| (p.at, p.cov.to_bits(), p.edge.offset.to_bits(), p.edge.normal.map(f32::to_bits))).collect::>() - }; - assert_eq!(edges(&one.0), edges(&many.0), "map {k} sharp edges on {threads} threads"); - for (a, b) in one.1.iter().zip(&many.1) { - assert_eq!(bits(a), bits(b), "map {k}, reach {reach} on {threads} threads"); - } - } - } - } - } - - #[test] - fn bevel_maps_do_not_depend_on_the_threads() { - // Every style and technique, softened or not, and a texture; one thread (in order) is the reference. - let mut patchy = aa_disc(101, 101, 40.0); - for (i, v) in patchy.v.iter_mut().enumerate() { - if (i % 101 / 13 + i / 101 / 17) % 5 == 0 { - *v *= 0.6; - } - } - let shapes = [aa_disc(97, 83, 30.0), aa_round_rect(131, 77, 9.0, 11.0, 120.0, 66.0, 14.0), aa_bar(90, 130, 60.0, 150.0, 25.0), patchy]; - let mut sf = photocraft_raster::Surface::new(photocraft_color::PixelFormat::RGBA8); - sf.fill_rect(Rect::new(0, 0, 4, 2), &[0.0, 0.0, 0.0, 1.0]); - sf.fill_rect(Rect::new(0, 2, 4, 4), &[1.0, 1.0, 1.0, 1.0]); - let pats = [Pattern::new("stripes", sf, 4, 4)]; - let light = GlobalLight::default(); - let styles = [BevelStyle::InnerBevel, BevelStyle::OuterBevel, BevelStyle::Emboss, BevelStyle::PillowEmboss, BevelStyle::StrokeEmboss]; - for (k, shape) in shapes.iter().enumerate() { - let tex = TextureCtx { rect: Rect::new(3, 5, 3 + shape.w as i32, 5 + shape.h as i32), patterns: &pats, anchor: (0.0, 0.0) }; - for style in styles { - for technique in [BevelTechnique::Smooth, BevelTechnique::ChiselHard, BevelTechnique::ChiselSoft] { - for (size, soften, textured) in [(5.0, 0.0, false), (12.0, 2.0, false), (8.0, 0.0, true)] { - let mut b = bevel_of(style, technique); - (b.size, b.soften) = (size, soften); - if textured { - b.texture = Some(photocraft_doc::BevelTexture { - name: "stripes".into(), - id: String::new(), - scale: 1.0, - depth: 1.0, - invert: false, - link: true, - phase: (0.0, 0.0), - }); - } - let run = || bevel_maps(shape, &b, &light, &tex, &PreparedPatterns::new(&pats, PREPARED_PATTERN_BYTES)).0; - let one = with_threads(1, run); - for threads in [2, 5, 16] { - let many = with_threads(threads, run); - assert_eq!(one.len(), many.len()); - for (j, (a, m)) in one.iter().zip(&many).enumerate() { - assert_eq!(bits(&a.v), bits(&m.v), "shape {k}, {style:?} {technique:?} size {size} map {j} on {threads} threads"); - } - } - } - } - } - } - } - - /// The four fields that use the distance transform, of `m`. - fn distance_field_of(m: &Map, reach: f32) -> Vec> { - [FieldKind::Inside, FieldKind::Outside, FieldKind::BevelInside, FieldKind::BevelOutside] - .map(|k| distance_field(k, m.v.clone(), m.w, m.h, reach)) - .to_vec() - } - - fn aa_disc(w: usize, h: usize, r: f32) -> Map { - let mut m = Map::new(w, h, 0.0); - const N: usize = 16; - for y in 0..h { - for x in 0..w { - let mut hit = 0; - for sy in 0..N { - for sx in 0..N { - let (px, py) = (x as f32 + (sx as f32 + 0.5) / N as f32 - w as f32 / 2.0, y as f32 + (sy as f32 + 0.5) / N as f32 - h as f32 / 2.0); - hit += usize::from(px * px + py * py <= r * r); - } - } - m.v[y * w + x] = hit as f32 / (N * N) as f32; - } - } - m - } - - /// Integer-aligned rounded rectangle (x0..x1 x y0..y1, corner radius `rad`), anti-aliased by supersampling. - fn aa_round_rect(w: usize, h: usize, x0: f32, y0: f32, x1: f32, y1: f32, rad: f32) -> Map { - let sdf = |px: f32, py: f32| { - let (cx, cy) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0); - let (qx, qy) = ((px - cx).abs() - ((x1 - x0) / 2.0 - rad), (py - cy).abs() - ((y1 - y0) / 2.0 - rad)); - qx.max(0.0).hypot(qy.max(0.0)) + qx.max(qy).min(0.0) - rad - }; - let mut m = Map::new(w, h, 0.0); - const N: usize = 16; - for y in 0..h { - for x in 0..w { - let mut hit = 0; - for sy in 0..N { - for sx in 0..N { - hit += usize::from(sdf(x as f32 + (sx as f32 + 0.5) / N as f32, y as f32 + (sy as f32 + 0.5) / N as f32) <= 0.0); - } - } - m.v[y * w + x] = hit as f32 / (N * N) as f32; - } - } - m - } - - #[test] - fn chisel_hard_has_flat_facets() { - let shape = square(48, 10, 38); - let (m, _) = bevel_maps( - &shape, - &bevel_of(BevelStyle::InnerBevel, BevelTechnique::ChiselHard), - &GlobalLight::default(), - &no_tex(), - &PreparedPatterns::new(&[], PREPARED_PATTERN_BYTES), - ); - let at = |x: usize, y: usize| m[0].v[y * 48 + x]; - // A constant slope: equal highlight along the top facet. - assert!(at(24, 12) > 0.1 && (at(24, 12) - at(24, 13)).abs() < 1e-3); - } - - #[test] - fn linear_bevel_contour_leaves_the_height_alone_at_any_range() { - for range in [0.5, 0.7, 1.0] { - let lut = bevel_contour_lut(&photocraft_doc::BevelContour { contour: Contour::Linear, range, anti_alias: false }); - for v in [0.0f32, 0.25, 0.5, 0.75, 1.0] { - assert!((lut_at(&lut, v) - v).abs() < 1e-3, "range {range}: {v} -> {}", lut_at(&lut, v)); - } - } - } - - #[test] - fn bevel_contour_and_texture_shape_the_height() { - let shape = square(40, 6, 34); - let l = GlobalLight::default(); - let plain = bevel_of(BevelStyle::InnerBevel, BevelTechnique::Smooth); - let (a, _) = bevel_maps(&shape, &plain, &l, &no_tex(), &PreparedPatterns::new(&[], PREPARED_PATTERN_BYTES)); - // A contour reshapes the profile (here a ramp folded at its middle). - let mut c = plain.clone(); - let fold = vec![ - photocraft_doc::adjust::CurvePoint { input: 0.0, output: 0.0 }, - photocraft_doc::adjust::CurvePoint { input: 0.5, output: 1.0 }, - photocraft_doc::adjust::CurvePoint { input: 1.0, output: 0.0 }, - ]; - c.contour = Some(photocraft_doc::BevelContour { - contour: Contour::Custom { name: "fold".into(), points: fold, corners: vec![] }, - range: 1.0, - anti_alias: false, - }); - let (b, _) = bevel_maps(&shape, &c, &l, &no_tex(), &PreparedPatterns::new(&[], PREPARED_PATTERN_BYTES)); - let diff: f32 = a[1].v.iter().zip(&b[1].v).map(|(x, y)| (x - y).abs()).sum(); - assert!(diff > 5.0, "{diff}"); - // A striped texture lights the flat middle. - let mut sf = photocraft_raster::Surface::new(photocraft_color::PixelFormat::RGBA8); - sf.fill_rect(Rect::new(0, 0, 4, 2), &[0.0, 0.0, 0.0, 1.0]); - sf.fill_rect(Rect::new(0, 2, 4, 4), &[1.0, 1.0, 1.0, 1.0]); - let pats = [Pattern::new("stripes", sf, 4, 4)]; - let mut t = plain.clone(); - t.texture = Some(photocraft_doc::BevelTexture { - name: "stripes".into(), - id: String::new(), - scale: 1.0, - depth: 1.0, - invert: false, - link: true, - phase: (0.0, 0.0), - }); - let tex = TextureCtx { rect: Rect::new(0, 0, 40, 40), patterns: &pats, anchor: (0.0, 0.0) }; - let (m, _) = bevel_maps(&shape, &t, &l, &tex, &PreparedPatterns::new(&pats, PREPARED_PATTERN_BYTES)); - let mid: f32 = (16..24).map(|y| m[0].v[y * 40 + 20] + m[1].v[y * 40 + 20]).sum(); - let flat: f32 = (16..24).map(|y| a[0].v[y * 40 + 20] + a[1].v[y * 40 + 20]).sum(); - assert!(mid > flat + 0.5, "{mid} vs {flat}"); - } - - #[test] - fn glow_range_stretches_the_contour() { - let mut g = Glow { - common: photocraft_doc::FxCommon::new(BlendMode::Screen, 1.0), - paint: FxPaint::Color(photocraft_color::Color::WHITE), - technique: GlowTechnique::Softer, - spread: 0.0, - size: 10.0, - contour: Contour::Linear, - anti_alias: false, - range: 0.5, - jitter: 0.0, - noise: 0.0, - source: GlowSource::Edge, - }; - let l = glow_lut(&g).unwrap(); - assert!((lut_at(&l, 0.25) - 0.5).abs() < 1e-3 && (lut_at(&l, 0.75) - 1.0).abs() < 1e-6); - g.range = 1.0; - assert!(glow_lut(&g).is_none()); - } - - /// Photoshop 27.11, measured on a 128 px square (Normal, black, 100 %, Range 50 %): a precise - /// glow's coverage across the edge, and a centre-source inner glow as 1 − the edge glow. - #[test] - fn glows_match_photoshop() { - let glow = |technique, size: f32, spread: f32, source| Glow { - common: photocraft_doc::FxCommon::new(BlendMode::Normal, 1.0), - paint: FxPaint::Color(photocraft_color::Color::BLACK), - technique, - spread, - size, - contour: Contour::Linear, - anti_alias: false, - range: 0.5, - jitter: 0.0, - noise: 0.0, - source, - }; - let n = 60; - let mut shape = Map::new(n, n, 0.0); - for y in 20..40 { - for x in 20..40 { - shape.v[y * n + x] = 1.0; - } - } - let at = |m: &Map, x: usize| m.v[30 * n + x]; - // Outer, precise, size 10: Photoshop's black glow over white reads 47, 93, 140, 186, 232 - // at 2, 4, 6, 8 and 10 px out from the edge pixel (alpha 1 − D / 11). - let m = glow_map(&shape, &glow(GlowTechnique::Precise, 10.0, 0.0, GlowSource::Edge), false, (0, 0)); - for (d, ps) in [(2, 47.0f32), (4, 93.0), (6, 140.0), (8, 186.0), (10, 232.0)] { - let got = 255.0 * (1.0 - at(&m, 20 - d)); - assert!((got - ps).abs() <= 1.5, "outer precise at {d} px: {got} vs Photoshop {ps}"); - } - // Spread 40 %: solid for the first 4 px. - let m = glow_map(&shape, &glow(GlowTechnique::Precise, 10.0, 0.4, GlowSource::Edge), false, (0, 0)); - assert!((at(&m, 16) - 1.0).abs() < 1e-6 && at(&m, 14) < 1.0); - // Centre source = 1 − edge, for both techniques. - for t in [GlowTechnique::Precise, GlowTechnique::Softer] { - let e = glow_map(&shape, &glow(t, 6.0, 0.0, GlowSource::Edge), true, (0, 0)); - let c = glow_map(&shape, &glow(t, 6.0, 0.0, GlowSource::Center), true, (0, 0)); - for x in 20..40 { - assert!((at(&c, x) - (1.0 - at(&e, x))).abs() < 1e-5, "{t:?} at {x}"); - } - } - } - - #[test] - fn offsets_follow_light() { - let (dx, dy) = offset(120.0, 10.0); - assert_eq!((dx, dy), (5.0, 9.0)); - } - - fn square_shape(n: usize) -> Map { - let mut m = Map::new(n, n, 0.0); - for y in 5..n - 5 { - for x in 5..n - 5 { - m.v[y * n + x] = 1.0; - } - } - m - } - - #[test] - fn satin_at_distance_zero_matches_photoshop() { - // Photoshop 27.11, Satin black 100 %, angle 90°, Linear contour, distance 0, size 5 over a - // #808080 square: the rows from the top edge read 82, 102, 123, 128. - let s = photocraft_doc::effects::Satin { - common: photocraft_doc::FxCommon::new(BlendMode::Normal, 1.0), - color: photocraft_color::Color::BLACK, - angle: 90.0, - distance: 0.0, - size: 5.0, - contour: Contour::Linear, - anti_alias: false, - invert: false, - }; - let m = satin_map(&square_shape(60), &s); - for (row, gray) in [(5, 82.0), (7, 102.0), (9, 123.0), (11, 128.0), (30, 128.0)] { - let want = 1.0 - gray / 128.0; - let got = m.v[row * 60 + 30]; - assert!((got - want).abs() < 0.02, "row {row}: {got} vs {want}"); - } - } - - fn shadow(noise: f32, origin: (i32, i32)) -> Map { - let s = Shadow { - common: photocraft_doc::FxCommon::new(BlendMode::Multiply, 1.0), - color: photocraft_color::Color::BLACK, - angle: 0.0, - use_global_light: false, - distance: 0.0, - spread: 0.0, - size: 6.0, - contour: Contour::Linear, - anti_alias: false, - noise, - knocks_out: true, - }; - shadow_map(&square_shape(40), &s, &GlobalLight::default(), false, origin) - } - - #[test] - fn shadow_noise_speckles_soft_coverage_deterministically() { - let plain = shadow(0.0, (0, 0)); - let noisy = shadow(0.5, (0, 0)); - let again = shadow(0.5, (0, 0)); - let (mut diff, mut identical) = (0.0f32, true); - for i in 0..plain.v.len() { - diff += (plain.v[i] - noisy.v[i]).abs(); - if noisy.v[i] != again.v[i] { - identical = false; - } - } - assert!(diff > 5.0, "noise changes the soft band: {diff}"); - assert!(identical, "same coords, same speckle"); - // Every value stays a coverage. - assert!(noisy.v.iter().all(|v| (0.0..=1.0).contains(v))); - // The speckle moves with the document origin, not the tile. - let moved = shadow(0.5, (100, 100)); - assert_ne!(noisy.v, moved.v, "hashed from document coordinates"); - // Full noise can punch holes even in the solid part. - let heavy = shadow(1.0, (0, 0)); - assert!(heavy.v.iter().any(|v| *v < 0.5) && heavy.v.iter().any(|v| *v > 0.5), "heavy noise spans the range",); - } - - #[test] - fn box_blur_preserves_faint_coverage_and_empty_gaps() { - let src = [0.0, 0.3, 0.7, 0.0, 0.0, 0.0, 0.0, 1e-20, 0.0, 0.0, 0.0]; - let mut actual = [0.0; 11]; - box_line(&src, 0, &mut actual, 3.0); - assert_eq!(actual[5], 0.0, "an empty window must be exactly empty"); - assert_eq!(actual[10], 0.0, "the second tail must also be empty"); - assert!((actual[7] - 1e-20 / 3.0).abs() < 1e-30, "real faint coverage is not rounded away"); - } - - #[test] - fn effect_noise_does_not_light_up_empty_blur_tails() { - // A sloping antialiased shape leaves rounding residue in a running-sum blur. - // The direct finite-support convolution is the oracle for untouched pixels. - for size in [5.0, 5.5, 13.0] { - let mut shape = Map::new(96, 64, 0.0); - for y in 8..48 { - for x in 8..48 { - shape.v[y * shape.w + x] = ((x as f32 - y as f32 * 0.7) * 0.3).clamp(0.0, 1.0); - } - } - let mut direct = shape.clone(); - tent_direct(&mut direct, size); - let mut actual = shape; - blur(&mut actual, size); - noise(&mut actual, 0.26, 0, 0); - let stray = direct.v.iter().zip(&actual.v).filter(|(reference, noisy)| **reference == 0.0 && **noisy > 1e-5).count(); - assert_eq!(stray, 0, "noise created {stray} visible pixels outside a size-{size} blur"); - } - } - - #[test] - fn glow_noise_follows_the_contour_and_range() { - let g = |noise: f32| Glow { - common: photocraft_doc::FxCommon::new(BlendMode::Screen, 1.0), - paint: FxPaint::Color(photocraft_color::Color::WHITE), - technique: GlowTechnique::Softer, - spread: 0.0, - size: 6.0, - contour: Contour::Linear, - anti_alias: false, - range: 0.5, - jitter: 0.0, - noise, - source: GlowSource::Edge, - }; - let plain = glow_map(&square_shape(40), &g(0.0), false, (0, 0)); - let noisy = glow_map(&square_shape(40), &g(0.6), false, (0, 0)); - let diff: f32 = plain.v.iter().zip(&noisy.v).map(|(a, b)| (a - b).abs()).sum(); - assert!(diff > 5.0, "glow noise changes the coverage: {diff}"); - } - - /// Issue #7833: the speckle stays inside the glow's visible falloff instead of filling the - /// blur's whole rectangular reach out to the map edge. - #[test] - fn effect_noise_stays_inside_the_visible_falloff() { - let mut shape = Map::new(80, 80, 0.0); - for y in 35..45 { - for x in 35..45 { - shape.v[y * 80 + x] = 1.0; - } - } - let g = |noise: f32| Glow { - common: photocraft_doc::FxCommon::new(BlendMode::Screen, 1.0), - paint: FxPaint::Color(photocraft_color::Color::WHITE), - technique: GlowTechnique::Softer, - spread: 0.0, - size: 10.0, - contour: Contour::Linear, - anti_alias: false, - range: 0.5, - jitter: 0.0, - noise, - source: GlowSource::Edge, - }; - let s = |noise: f32| Shadow { - common: photocraft_doc::FxCommon::new(BlendMode::Multiply, 1.0), - color: photocraft_color::Color::BLACK, - angle: 0.0, - use_global_light: false, - distance: 0.0, - spread: 0.0, - size: 10.0, - contour: Contour::Linear, - anti_alias: false, - noise, - knocks_out: true, - }; - let light = GlobalLight::default(); - let pairs = [ - ("glow", glow_map(&shape, &g(0.0), false, (0, 0)), glow_map(&shape, &g(0.5), false, (0, 0))), - ("shadow", shadow_map(&shape, &s(0.0), &light, false, (0, 0)), shadow_map(&shape, &s(0.5), &light, false, (0, 0))), - ]; - for (name, plain, noisy) in pairs { - for (i, (p, n)) in plain.v.iter().zip(&noisy.v).enumerate() { - if *p < 1.0 / 255.0 { - assert!(*n <= 2.0 / 255.0, "{name}: pixel ({}, {}) invisible without noise: {p} -> {n}", i % 80, i / 80); - } - } - } - } - - #[test] - fn shifting_by_hostile_distances_does_not_overflow() { - let m = square_shape(12); - for d in [1.0e30, -1.0e30, f32::INFINITY, f32::NAN] { - let s = m.shifted(d, d, 0.0); - assert_eq!(s.v.len(), 144); - } - } -} +mod tests; diff --git a/crates/compose/src/effects/bevel.rs b/crates/compose/src/effects/bevel.rs new file mode 100644 index 0000000000..ec038d842f --- /dev/null +++ b/crates/compose/src/effects/bevel.rs @@ -0,0 +1,284 @@ +use super::blur::tent; +use super::distance::{INSIDE_EPS, bevel_dists, par_fill, par_units}; +use super::paint::{apply_lut, bevel_contour_lut, contour_lut, lut_at, offset, satin_lut}; +use super::*; + +/// Where a bevel's maps paint: inside the shape (with the layer), outside it (onto the +/// backdrop), or both (emboss styles: maps 0–1 inside, 2–3 outside). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BevelPaint { + Inner, + Outer, + Both, +} + +/// Height below which an outer bevel pixel counts as off the bevel (beyond the blur's reach): +/// above float noise of the running-sum blur (~3e-7), far below anything that shades. +pub const BEVEL_H_EPS: f32 = 1e-5; + +/// Bevel geometry shared by the CPU maps and the GPU programs. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct BevelGeom { + pub paint: BevelPaint, + /// Box width of the smooth height blur (size; half the size, rounded up, for emboss styles). + pub width: f32, + /// Height-map gradient scale: depth × width (smooth) or depth × size (chisel), signed by + /// direction. + pub depth: f32, + /// Pillow emboss: the outside slopes face the other way. + pub pillow: bool, + /// Chisel Soft: extra tent width over the chiselled height map. + pub chisel_soft: f32, +} + +pub fn bevel_geom(b: &Bevel) -> BevelGeom { + let size = b.size.max(1.0); + let emboss = matches!(b.style, BevelStyle::Emboss | BevelStyle::PillowEmboss); + let paint = match b.style { + BevelStyle::OuterBevel => BevelPaint::Outer, + BevelStyle::Emboss | BevelStyle::PillowEmboss => BevelPaint::Both, + BevelStyle::InnerBevel | BevelStyle::StrokeEmboss => BevelPaint::Inner, + }; + // Emboss styles straddle the edge with half the size, rounded up to whole pixels: a 41 px + // emboss blurs over 21 (psd-tools layer_effects: 20.5 left narrow letter parts up to + // 5.7/255 dark, 21 is within 2.2). + let width = if emboss { (size / 2.0).ceil() } else { size }; + let smooth = b.technique == BevelTechnique::Smooth; + let sign = if b.up { 1.0 } else { -1.0 }; + BevelGeom { + paint, + width, + // A bevel rises `depth × width / 2` px: Smooth with a slope falling from `depth` at the + // edge (the tent), a chisel with the constant slope of its ramp (see `bevel_chisel_h`). + depth: b.depth * if smooth { width } else { size / 2.0 } * sign, + pillow: b.style == BevelStyle::PillowEmboss, + chisel_soft: if b.technique == BevelTechnique::ChiselSoft { (size / 4.0).max(1.0) } else { 0.0 }, + } +} + +/// Bevel height map in `0..=1`. Smooth: the shape blurred by two box passes of the bevel +/// width. Chisel: linear ramps of the distance to the edge (size wide; emboss styles straddle the +/// edge), slightly blurred for Chisel Soft. The distance puts the edge by the anti-aliased +/// coverage of its pixels ([`bevel_dist_inside`]), so a facet is planar at any angle. Soften blurs +/// the result. +fn bevel_height(shape: &Map, b: &Bevel, g: &BevelGeom, tex: &TextureCtx, patterns: &PreparedPatterns<'_>) -> Map { + let size = b.size.max(1.0); + let mut h = if b.technique == BevelTechnique::Smooth { + let mut h = shape.clone(); + tent(&mut h, g.width); + h + } else { + let [din, dout] = bevel_dists(shape, size); + let soft = g.chisel_soft > 0.0; + let w = shape.w; + let v = par_fill(w, shape.h, 0.0, |y, row| { + for (x, o) in row.iter_mut().enumerate() { + let i = y * w + x; + *o = bevel_chisel_h(g.paint, size, din[i], dout[i], soft); + } + }); + let mut h = Map { w, h: shape.h, v }; + // Inner and outer Chisel Soft are not blurred in Photoshop (their facets equal Chisel + // Hard's across a straight edge); emboss styles keep the blur until measured. + if soft && g.paint == BevelPaint::Both { + tent(&mut h, g.chisel_soft); + } + h + }; + // Contour element: the height profile through the contour. + if let Some(c) = &b.contour { + h = apply_lut(h, Some(bevel_contour_lut(c))); + } + // Texture element: the pattern's luminance as extra height, scaled so a full-contrast step + // at 100 % depth slopes like the bevel at its depth. + if let Some(t) = &b.texture + && let Some(tile) = patterns.get(&t.id, &t.name) + { + let unit = if b.depth.abs() > 1e-6 { (g.depth / b.depth).abs().max(1e-3) } else { g.width.max(1.0) }; + let place = Placement::anchored(tex.anchor, t.link, t.phase, t.scale, 0.0); + let k = t.depth / unit; + let (x0, y0) = (tex.rect.x0, tex.rect.y0); + let w = h.w; + par_units( + h.v.len(), + &mut h.v, + w, + &mut [] as &mut [()], + 0, + || (), + |_, y, row, _| { + for (x, o) in row.iter_mut().enumerate() { + let (u, v) = place.map(f64::from(x0 + x as i32) + 0.5, f64::from(y0 + y as i32) + 0.5); + let p = tile.sample(u, v); + let l = (0.299 * p[0] + 0.587 * p[1] + 0.114 * p[2]) * p[3]; + *o += k * if t.invert { 1.0 - l } else { l }; + } + }, + ); + } + if b.soften >= 1.0 { + tent(&mut h, b.soften); + } + h +} + +/// Where a bevel texture tiles: the maps' rectangle, the document's patterns and the linked +/// origin (the effects reference point, else the layer's top-left). +pub struct TextureCtx<'a> { + pub rect: Rect, + pub patterns: &'a [Pattern], + pub anchor: (f64, f64), +} + +/// Chiselled height from the inside / outside distances (keep in sync with `fs_mbevelh`). +/// +/// Photoshop 27.11, measured across straight edges (sizes 10 and 20, depth 100 and 300): a chisel +/// facet has the constant slope `depth × size / (2 (size + 1))`, i.e. one height step of +/// `1 / (size + 1)` per pixel at the `depth × size / 2` scale of [`bevel_geom`]. Inner Hard's ramp +/// runs from half a pixel beyond the edge to `size + ½` (the facet is flat right up to the edge +/// pixel); Inner Soft starts a pixel further out, so its edge pixel is steeper; Outer Hard ends a +/// pixel further out. All within 1 level of Photoshop on those profiles. +pub fn bevel_chisel_h(paint: BevelPaint, size: f32, din: f32, dout: f32, soft: bool) -> f32 { + let ramp = size + 1.0; + match paint { + BevelPaint::Outer if !soft => { + let top = (size + 2.0) / ramp; + if dout > 0.0 { ((size + 1.5 - dout) / ramp).clamp(0.0, top) } else { top } + } + // Outer Soft: Outer Hard's ramp a pixel shorter, with a steeper edge pixel. + BevelPaint::Outer => { + if dout > 0.0 { + 1.0 - ((dout + 0.5) / ramp).clamp(0.0, 1.0) + } else { + (size + 2.0) / ramp + } + } + BevelPaint::Both => { + let half = size / 2.0 + 0.5; + if din > 0.0 { 0.5 + 0.5 * (din / half).clamp(0.0, 1.0) } else { 0.5 - 0.5 * (dout / half).clamp(0.0, 1.0) } + } + BevelPaint::Inner if soft => { + if din > 0.0 { + ((din + 1.5) / ramp).clamp(0.0, (size + 2.0) / ramp) + } else { + 0.0 + } + } + BevelPaint::Inner => { + if din > 0.0 { + ((din + 0.5) / ramp).clamp(0.0, 1.0) + } else { + 0.0 + } + } + } +} + +/// Bevel highlight and shadow maps: `[hi, sh]` (inner or outer) or `[hi, sh, hi_out, sh_out]` +/// (emboss styles). +pub(super) fn bevel_maps(shape: &Map, b: &Bevel, light: &GlobalLight, tex: &TextureCtx, patterns: &PreparedPatterns<'_>) -> (Vec, BevelPaint) { + let g = bevel_geom(b); + let hmap = bevel_height(shape, b, &g, tex, patterns); + let (angle, altitude) = if b.use_global_light { (light.angle, light.altitude) } else { (b.angle, b.altitude) }; + let (sa, ca) = angle.to_radians().sin_cos(); + let (se, ce) = altitude.to_radians().sin_cos(); + let light_v = [ca * ce, -sa * ce, se]; + // Region: 0 = inside (× the shape's alpha), 1 = under the layer's edge and outside. + // A pixel is on the bevel where its height is raised. Emboss styles also shade the last pixel + // past the blur's reach (a raised 4-neighbour: it still slopes; psd-tools layer_effects' + // emboss shadow runs one row past it), outer bevels don't (Photoshop oracle + // bevel-outer-smooth). + // Outer chisel bevels too: the pixel where their ramp reaches zero still slopes (Photoshop + // 27.11 shades it, half strength, at `size + 1½` px out). + let reach_past = g.paint == BevelPaint::Both || (g.paint == BevelPaint::Outer && b.technique != BevelTechnique::Smooth); + let on_bevel = |x: i64, y: i64| { + hmap.get(x, y) > BEVEL_H_EPS || (reach_past && [(1, 0), (-1, 0), (0, 1), (0, -1)].iter().any(|(dx, dy)| hmap.get(x + dx, y + dy) > BEVEL_H_EPS)) + }; + // The gloss contour remaps the shading `n · light` before it splits into highlight (above + // what it maps a flat face's `sin(altitude)` to) and shadow. Applied to the highlight and shadow amounts + // instead, a contour that starts high (Rolling Slope - Descending) lit every pixel the light + // missed, so a bevelled glyph's flat face took the full highlight (#7360) where Photoshop + // leaves it at the layer's colour. The Linear contour changes nothing either way. + let gloss = contour_lut(&b.gloss_contour); + let shade_into = |depth: f32, region_kind: u8| -> (Map, Map) { + let (mut hi, mut sh) = (Map::new(shape.w, shape.h, 0.0), Map::new(shape.w, shape.h, 0.0)); + // Rows on threads: every pixel reads only `hmap` and `shape`. + par_units( + hi.v.len(), + &mut hi.v, + shape.w, + &mut sh.v, + shape.w, + || (), + |_, y, hi_row, sh_row| { + let y = y as i64; + for x in 0..shape.w as i64 { + let i = y as usize * shape.w + x as usize; + let gx = (hmap.get(x + 1, y) - hmap.get(x - 1, y)) * 0.5 * depth; + let gy = (hmap.get(x, y + 1) - hmap.get(x, y - 1)) * 0.5 * depth; + let n = [-gx, -gy, 1.0]; + let len = (n[0] * n[0] + n[1] * n[1] + 1.0).sqrt(); + let shade = (n[0] * light_v[0] + n[1] * light_v[1] + n[2] * light_v[2]) / len; + let region = if region_kind == 0 { shape.v[i] } else { f32::from(shape.v[i] < 1.0 - INSIDE_EPS && on_bevel(x, y)) }; + let k = gloss.as_ref().map_or(shade - se, |l| lut_at(l, shade) - lut_at(l, se)); + if k > 0.0 { + hi_row[x as usize] = (k / (1.0 - se).max(1e-3)).clamp(0.0, 1.0) * region; + } else { + sh_row[x as usize] = (-k / se.max(1e-3)).clamp(0.0, 1.0) * region; + } + } + }, + ); + (hi, sh) + }; + let maps = match g.paint { + BevelPaint::Inner | BevelPaint::Outer => { + let (hi, sh) = shade_into(g.depth, u8::from(g.paint == BevelPaint::Outer)); + vec![hi, sh] + } + BevelPaint::Both => { + // One map per colour over the whole bevel: the inside half where the shape is (× its + // alpha), the outside half (pillow: facing the other way) for the rest of each pixel. + // A 1 % edge pixel of a pillow emboss takes the outside shading (Photoshop oracle + // bevel-pillow-smooth), a 75 % one of an emboss mostly the inside (layer_effects). + let (hi, sh) = shade_into(g.depth, 0); + let (ho, so) = shade_into(if g.pillow { -g.depth } else { g.depth }, 1); + let mix = |a: Map, b: Map| -> Map { + let v = par_fill(a.w, a.h, 0.0, |y, row| { + for (x, o) in row.iter_mut().enumerate() { + let i = y * a.w + x; + let (x, y, s) = (a.v[i], b.v[i], shape.v[i]); + *o = if s > INSIDE_EPS { x } else { 0.0 } + y * (1.0 - s.min(1.0)); + } + }); + Map { w: a.w, h: a.h, v } + }; + vec![mix(hi, ho), mix(sh, so)] + } + }; + (maps, g.paint) +} + +/// The distance the two satin copies are offset by. Photoshop draws Distance 0 as 1 px (an +/// edge band of 2/size, measured in Photoshop 27.11), not as two copies cancelling out. +pub fn satin_distance(s: &photocraft_doc::effects::Satin) -> f32 { + s.distance.max(1.0) +} + +pub(super) fn satin_map(shape: &Map, s: &photocraft_doc::effects::Satin) -> Map { + let (dx, dy) = offset(s.angle, satin_distance(s)); + let mut a = shape.shifted(dx, dy, 0.0); + let mut b = shape.shifted(-dx, -dy, 0.0); + // Two box passes of the satin size (fitted: 0.2 % mean error on psd-tools layer_effects). + tent(&mut a, s.size); + tent(&mut b, s.size); + let mut m = Map { w: shape.w, h: shape.h, v: a.v.iter().zip(&b.v).map(|(x, y)| (x - y).abs()).collect() }; + if s.invert { + m = m.map(|v| 1.0 - v); + } + let mut m = apply_lut(m, satin_lut(&s.contour)); + for (v, a) in m.v.iter_mut().zip(&shape.v) { + *v *= a; + } + m +} diff --git a/crates/compose/src/effects/blur.rs b/crates/compose/src/effects/blur.rs new file mode 100644 index 0000000000..686870523d --- /dev/null +++ b/crates/compose/src/effects/blur.rs @@ -0,0 +1,212 @@ +use super::distance::{Metric, dist_outside_by}; +use super::*; + +/// The soft falloff of an effect of `size` pixels: two box passes of width `size` (a tent), +/// as Photoshop does. Fitted on psd-tools layer_effects.psd against the earlier Gaussian +/// (sigma = 0.4 × size): drop shadow coverage error 0.0064 → 0.0038, satin 0.014 → 0.002. +pub(super) fn blur(m: &mut Map, size: f32) { + if size.is_finite() { + tent(m, size); + } +} + +/// Grows the shape by `r` pixels (anti-aliased), keeping the original soft edge. Distances use +/// the 5 × 5 chamfer metric, as for strokes: Photoshop's spread of a group drop shadow around an +/// ellipse (ag-psd group-drop-shadows) is round at 0° and 45° and falls short in between, peaking +/// near 15° where the chamfer metric overestimates most (5/255 lighter with an exact Euclidean +/// dilation, within 2/255 with the chamfer). +pub(super) fn dilate(s: &Map, r: f32) -> Map { + if r <= 0.0 { + return s.clone(); + } + let d = dist_outside_by(s, Metric::Chamfer); + let mut out = s.clone(); + for (o, d) in out.v.iter_mut().zip(d) { + // Partly covered pixels (distance sentinel < 0) grow by `r` from their own coverage, so a + // 2 % spread doesn't make every anti-aliased edge pixel opaque (ag-psd drop shadow). + *o = if d < 0.0 { (*o + r).min(1.0) } else { o.max((r + 0.5 - d).clamp(0.0, 1.0)) }; + } + out +} + +/// A box width as the blurs use it: at least 1, at most [`MAX_REACH`] (an effect never reaches +/// further, see [`margin`]), and 1 for NaN. A size or softness from a command or a file can be +/// anything, and an unbounded width sizes the kernel and its buffers (#1543). +fn box_width(w: f32) -> f32 { + if w.is_nan() { 1.0 } else { w.clamp(1.0, MAX_REACH) } +} + +/// Normalised weights of a centred box of (fractional) width `w`: tap `i` gets the overlap of +/// `[i - 0.5, i + 0.5]` with `[-w/2, w/2]`. +fn box_weights(w: f32) -> Vec { + let w = box_width(w); + let half = w / 2.0; + let r = (half - 0.5).ceil().max(0.0) as i64; + let v: Vec = (-r..=r).map(|i| ((i as f32 + 0.5).min(half) - (i as f32 - 0.5).max(-half)).max(0.0)).collect(); + let sum: f32 = v.iter().sum(); + v.iter().map(|x| x / sum).collect() +} + +/// The 1D kernel of two box passes of width `w` (a tent of half-width ≈ `w`): `(radius, weights)`. +/// Photoshop's bevel height maps are this blur of the shape (fitted on the corpus: a smooth +/// inner bevel of size 5 matches within 0.7 % mean, size 41 within 2.6 %). +pub fn tent_kernel(w: f32) -> (i32, Vec) { + let b = box_weights(w); + let n = b.len() * 2 - 1; + let mut t = vec![0.0f32; n]; + for (i, x) in b.iter().enumerate() { + for (j, y) in b.iter().enumerate() { + t[i + j] += x * y; + } + } + ((n as i32 - 1) / 2, t) +} + +/// Box geometry for a (fractional) width: (`r`, end-tap weight `f`, 1 / width) — the +/// [`box_weights`] taps are `r - 1` full ones each side of the centre plus the two end taps at `f`. +fn box_geom(bw: f32) -> (i64, f64, f64) { + let bw = box_width(bw); + let half = bw / 2.0; + let r = (half - 0.5).ceil().max(0.0) as i64; + let f = f64::from((half - (r as f32 - 0.5)).clamp(0.0, 1.0)); + (r, f, 1.0 / f64::from(bw)) +} + +/// One box pass over `src` (zero outside it) evaluated at `x0 .. x0 + dst.len()`, as a running +/// sum (O(1) per sample whatever the width). +pub(super) fn box_line(src: &[f64], x0: i64, dst: &mut [f64], bw: f32) { + let n = src.len() as i64; + let (r, f, norm) = box_geom(bw); + let at = |i: i64| if i >= 0 && i < n { src[i as usize] } else { 0.0 }; + if r == 0 { + for (k, d) in dst.iter_mut().enumerate() { + *d = at(x0 + k as i64); + } + return; + } + let window = x0 - (r - 1)..=x0 + (r - 1); + let mut inner: f64 = window.clone().map(at).sum(); + let mut last_covered = window.rev().find(|&x| at(x) != 0.0).unwrap_or(i64::MIN); + for (k, d) in dst.iter_mut().enumerate() { + let x = x0 + k as i64; + *d = (inner + f * (at(x - r) + at(x + r))) * norm; + let entering = at(x + r); + inner += entering - at(x - r + 1); + if entering != 0.0 { + last_covered = x + r; + } + // Cancellation can leave positive residue after the last covered pixel leaves. + // Noise amplifies even that residue into visible speckles (#5638). Reset only + // truly empty windows, preserving arbitrarily faint real coverage. + if last_covered < x - r + 2 { + inner = 0.0; + } + } +} + +/// Two box passes along a line, exactly the convolution with [`tent_kernel`] (zero outside): the +/// first pass is evaluated `r` samples beyond each end so the second sees what lies there. +fn tent_line(src: &[f32], dst: &mut [f32], bw: f32) { + let (r, _, _) = box_geom(bw); + let s: Vec = src.iter().map(|v| f64::from(*v)).collect(); + let mut mid = vec![0.0f64; src.len() + 2 * r as usize]; + box_line(&s, -r, &mut mid, bw); + let mut out = vec![0.0f64; src.len()]; + // `mid[k]` holds position k - r: output position p reads index p + r. + box_line(&mid, r, &mut out, bw); + for (d, v) in dst.iter_mut().zip(out) { + *d = v as f32; + } +} + +/// Rows of a `w`-wide row-major buffer, each through `f(src_row, dst_row)`, in parallel on +/// scoped OS threads. Not rayon: maps can be built from inside a rayon tile, where a waiting +/// worker steals other tiles. Map builds no longer block on each other (#276), but the blur +/// keeps out of the tile pool. +fn rows_par(src: &[f32], dst: &mut [f32], w: usize, f: impl Fn(&[f32], &mut [f32]) + Sync) { + if w == 0 { + return; + } + let threads = + if cfg!(target_arch = "wasm32") || src.len() < 1 << 16 { 1 } else { std::thread::available_parallelism().map_or(1, |n| n.get()).clamp(1, 16) }; + if threads == 1 { + dst.chunks_mut(w).zip(src.chunks(w)).for_each(|(d, s)| f(s, d)); + return; + } + let rows = (src.len() / w).div_ceil(threads); + std::thread::scope(|sc| { + for (d, s) in dst.chunks_mut(rows * w).zip(src.chunks(rows * w)) { + let f = &f; + sc.spawn(move || d.chunks_mut(w).zip(s.chunks(w)).for_each(|(d, s)| f(s, d))); + } + }); +} + +fn transpose_map(v: &[f32], w: usize, h: usize) -> Vec { + let mut out = vec![0.0f32; v.len()]; + const B: usize = 32; + for by in (0..h).step_by(B) { + for bx in (0..w).step_by(B) { + for y in by..(by + B).min(h) { + for x in bx..(bx + B).min(w) { + out[x * h + y] = v[y * w + x]; + } + } + } + } + out +} + +/// Two box passes of width `w` along each axis (the tent [`tent_kernel`] describes, which the GPU +/// convolves directly). +pub(super) fn tent(m: &mut Map, w: f32) { + if tent_kernel(w).0 == 0 || m.v.is_empty() { + return; + } + tent_fast(m, w); +} + +/// [`tent`] as a direct convolution with [`tent_kernel`] (the GPU's way; tests compare). +#[cfg(test)] +pub(super) fn tent_direct(m: &mut Map, w: f32) { + { + let (r, k) = tent_kernel(w); + let (mw, mh) = (m.w as i64, m.h as i64); + let mut tmp = vec![0.0f32; m.v.len()]; + for y in 0..mh { + for x in 0..mw { + let mut acc = 0.0; + for (i, kv) in k.iter().enumerate() { + let xx = x + i as i64 - r as i64; + if xx >= 0 && xx < mw { + acc += m.v[(y * mw + xx) as usize] * kv; + } + } + tmp[(y * mw + x) as usize] = acc; + } + } + for y in 0..mh { + for x in 0..mw { + let mut acc = 0.0; + for (i, kv) in k.iter().enumerate() { + let yy = y + i as i64 - r as i64; + if yy >= 0 && yy < mh { + acc += tmp[(yy * mw + x) as usize] * kv; + } + } + m.v[(y * mw + x) as usize] = acc; + } + } + } +} + +fn tent_fast(m: &mut Map, w: f32) { + let (mw, mh) = (m.w, m.h); + let twice = |s: &[f32], d: &mut [f32]| tent_line(s, d, w); + let mut a = vec![0.0f32; m.v.len()]; + rows_par(&m.v, &mut a, mw, twice); + let t = transpose_map(&a, mw, mh); + let mut b = vec![0.0f32; t.len()]; + rows_par(&t, &mut b, mh, twice); + m.v = transpose_map(&b, mh, mw); +} diff --git a/crates/compose/src/effects/composite.rs b/crates/compose/src/effects/composite.rs new file mode 100644 index 0000000000..cf6402f1ca --- /dev/null +++ b/crates/compose/src/effects/composite.rs @@ -0,0 +1,533 @@ +use super::bevel::{BevelPaint, TextureCtx, bevel_geom, bevel_maps, satin_map}; +use super::distance::{INSIDE_EPS, Metric, dist_inside_by, dist_outside_by, local_coverage, stroke_outside_exact}; +use super::paint::{dissolves_in, glow_map, paint_color, paint_fx, paint_glow, paint_pattern, rgb, shadow_map}; +use super::*; + +/// Build every effect map for `layer` from its alpha `shape` over `rect`. +pub fn build_maps(layer: &Layer, shape: Vec, rect: Rect, light: &GlobalLight, tex: &TextureCtx) -> FxMaps { + let prepared = PreparedPatterns::new(tex.patterns, PREPARED_PATTERN_BYTES); + build_maps_prepared(layer, shape, rect, light, tex, &prepared) +} + +/// How many region-sized arrays [`build_maps_prepared`] builds for `layer` (what +/// [`FxMaps::bytes`] counts): the shape, each effect's maps, and a stroke's distance fields. Kept +/// next to the builder so the effect cache's estimate (#8330) follows it. +pub(crate) fn map_count(layer: &Layer) -> usize { + let items: Vec<&Effect> = layer.effects.items.iter().filter(|e| e.enabled()).collect(); + let per: usize = items + .iter() + .map(|e| match e { + Effect::DropShadow(_) | Effect::InnerShadow(_) | Effect::OuterGlow(_) | Effect::InnerGlow(_) | Effect::Satin(_) => 1, + Effect::BevelEmboss(_) => 2, + _ => 0, + }) + .sum(); + let out_widths: Vec = + items.iter().filter_map(|e| if let Effect::Stroke(st) = e { Some(stroke_widths(st).1) } else { None }).filter(|w| *w > 0.0).collect(); + let has_stroke = items.iter().any(|e| matches!(e, Effect::Stroke(_))); + let outside = usize::from(out_widths.iter().any(|&w| !stroke_outside_exact(w))) + usize::from(out_widths.iter().any(|&w| stroke_outside_exact(w))); + let stroke = if has_stroke { 1 + outside } else { 0 }; + let vector_outline = + if has_stroke && matches!(layer.content, photocraft_doc::LayerContent::Shape(_)) && crate::effect_outline(layer).is_none() { outside } else { 0 }; + 1 + per + stroke + vector_outline +} + +pub(crate) fn build_maps_prepared( + layer: &Layer, + shape: Vec, + rect: Rect, + light: &GlobalLight, + tex: &TextureCtx, + patterns: &PreparedPatterns<'_>, +) -> FxMaps { + let (w, h) = (rect.width() as usize, rect.height() as usize); + let shape = Map { w, h, v: shape }; + let items: Vec<&Effect> = layer.effects.items.iter().filter(|e| e.enabled()).collect(); + let mut bevel_paint = vec![BevelPaint::Inner; items.len()]; + let per: Vec> = items + .iter() + .enumerate() + .map(|(i, e)| match e { + Effect::DropShadow(s) => vec![shadow_map(&shape, s, light, false, (rect.x0, rect.y0))], + Effect::InnerShadow(s) => vec![shadow_map(&shape, s, light, true, (rect.x0, rect.y0))], + Effect::OuterGlow(g) => vec![glow_map(&shape, g, false, (rect.x0, rect.y0))], + Effect::InnerGlow(g) => vec![glow_map(&shape, g, true, (rect.x0, rect.y0))], + Effect::Satin(s) => vec![satin_map(&shape, s)], + Effect::BevelEmboss(b) => { + let (maps, paint) = bevel_maps(&shape, b, light, tex, patterns); + bevel_paint[i] = paint; + maps + } + _ => Vec::new(), + }) + .collect(); + let has_stroke = items.iter().any(|e| matches!(e, Effect::Stroke(_))); + let vector_shape = matches!(layer.content, photocraft_doc::LayerContent::Shape(_)); + // A stroke's outer edge keeps the 5 × 5 chamfer while its outside width is under + // `STROKE_CHAMFER_MAX` — Photoshop matches the chamfer's sub-pixel edge seeding at small + // offsets — and uses the exact Euclidean transform at or above it, where the chamfer's octagon + // facets a wide stroke (#3646). Inside stroke distances always keep the chamfer. Each outer + // field is built only when a stroke of that width is present; the compositor picks per stroke, + // so one layer may hold both a narrow and a wide stroke. + let out_widths: Vec = + items.iter().filter_map(|e| if let Effect::Stroke(st) = e { Some(stroke_widths(st).1) } else { None }).filter(|w| *w > 0.0).collect(); + let chamfer_out = out_widths.iter().any(|&w| !stroke_outside_exact(w)); + let exact_out = out_widths.iter().any(|&w| stroke_outside_exact(w)); + let (din, dout, dout_exact) = if has_stroke { + ( + Some(dist_inside_by(&shape, Metric::Chamfer)), + chamfer_out.then(|| dist_outside_by(&shape, Metric::Chamfer)), + exact_out.then(|| dist_outside_by(&shape, Metric::Euclidean)), + ) + } else { + (None, None, None) + }; + // Without an outline (unfilled shapes), estimate the vector outline from local coverage; it + // picks the chamfer or the exact transform the same way. + let outline = crate::effect_outline(layer).is_some(); + let (vdout, vdout_exact) = if has_stroke && vector_shape && !outline { + let lc = local_coverage(&shape); + (chamfer_out.then(|| dist_outside_by(&lc, Metric::Chamfer)), exact_out.then(|| dist_outside_by(&lc, Metric::Euclidean))) + } else { + (None, None) + }; + let mut frames: Vec<(u32, Rect)> = Vec::new(); + for e in &items { + if let Effect::Stroke(st) = e + && matches!(st.paint, FxPaint::Gradient(_)) + { + let out_w = stroke_widths(st).1; + if !frames.iter().any(|f| f.0 == out_w.to_bits()) { + frames.push((out_w.to_bits(), stroke_frame(&shape, out_w, rect))); + } + } + } + FxMaps { rect, shape, per, bevel_paint, din, dout, dout_exact, vdout, vdout_exact, outline, frames } +} + +/// Far outside any shape (distance fill for cropped distance fields). +const FAR: f32 = 1.0e9; + +/// Keep an exterior effect behind the layer's shape when Fill is partly or wholly +/// transparent. The visible part beneath a fully opaque fill is already covered by the +/// layer, so avoid attenuating anti-aliased edges twice in that case. +fn knock_out_exterior(map: &mut Map, shape: &Map, fill_opacity: f32) { + let see_through = 1.0 - fill_opacity.clamp(0.0, 1.0); + for (coverage, alpha) in map.v.iter_mut().zip(&shape.v) { + *coverage *= 1.0 - alpha * see_through; + } +} + +/// How far the layer lets a knocked-out drop shadow show beneath its own shape (Layer Knocks Out +/// Drop Shadow), 0 = covered, 1 = knocked out wholly. In a normal mode an opaque layer covers the +/// shadow anyway, so only see-through fill knocks it out (and anti-aliased edges are not +/// attenuated twice). In any other mode the layer blends with what's beneath it, shadow and all: +/// an Exclusion or Difference layer would invert it, Multiply darken by it, Screen show it as +/// grey. Photoshop keeps it out from under the shape, so here it's knocked out wholly. +pub fn shadow_see_through(layer: &Layer) -> f32 { + if matches!(layer.blend, BlendMode::Normal | BlendMode::Dissolve | BlendMode::PassThrough) { 1.0 - layer.fill_opacity.clamp(0.0, 1.0) } else { 1.0 } +} + +/// Blend Interior Effects as Group off (Photoshop's default): the layer's mode applies to its +/// own pixels only, and the interior effects paint over the blended result. The layer is merged +/// into the backdrop before they paint, so an Overlay colour overlay on a black Color-mode layer +/// tints the grey beneath it (#3996). A Normal layer merges only when an interior effect blends +/// in another mode: below 100 % fill that effect sees the backdrop through the layer, so a Soft +/// Light overlay on a Fill 0 % layer soft-lights the backdrop instead of showing its own colour +/// (#6232). Normal effects give the same result either way, and the merge would count a +/// half-transparent backdrop twice, so those layers keep the plain composite. +pub fn premerges_layer(layer: &Layer) -> bool { + !layer.advanced.blend_interior + && match layer.blend { + BlendMode::PassThrough | BlendMode::Dissolve => false, + BlendMode::Normal => blends_inside(layer), + _ => true, + } +} + +/// `true` if an enabled effect painted inside the layer (with its content) blends in a mode +/// other than Normal. +fn blends_inside(layer: &Layer) -> bool { + let blends = |m: BlendMode| m != BlendMode::Normal; + layer.effects.items.iter().filter(|e| e.enabled()).any(|e| match e { + Effect::ColorOverlay { common, .. } | Effect::GradientOverlay { common, .. } | Effect::PatternOverlay { common, .. } => blends(common.blend), + Effect::Satin(s) => blends(s.common.blend), + Effect::InnerGlow(g) => blends(g.common.blend), + Effect::InnerShadow(s) => blends(s.common.blend), + Effect::Stroke(s) => stroke_widths(s).0 > 0.0 && blends(s.common.blend), + Effect::BevelEmboss(b) => bevel_geom(b).paint == BevelPaint::Inner && (blends(b.highlight.blend) || blends(b.shadow.blend)), + Effect::DropShadow(_) | Effect::OuterGlow(_) => false, + }) +} + +/// Composites `content` (the layer's own pixels over `big`, alpha already +/// masked, clipped layers applied) plus its effects into `backdrop`. +pub fn composite_with_effects(layer: &Layer, content: &Buffer, backdrop: &mut Buffer, maps: &FxMaps, layer_bounds: Rect, patterns: &[Pattern]) { + let prepared = PreparedPatterns::new(patterns, PREPARED_PATTERN_BYTES); + composite_with_effects_prepared(layer, content, backdrop, maps, layer_bounds, &prepared, None); +} + +pub(crate) fn composite_with_effects_prepared( + layer: &Layer, + content: &Buffer, + backdrop: &mut Buffer, + maps: &FxMaps, + layer_bounds: Rect, + patterns: &PreparedPatterns<'_>, + vstroke: Option>, +) { + let big = content.rect; + let (w, h) = (big.width() as usize, big.height() as usize); + // The effect shape: the content's alpha (with a split-off vector stroke, `content` is the + // unmasked fill and the mask applies to fill ∪ stroke), joined with a filled shape's outline. + let kmask = |i: usize| vstroke.as_ref().and_then(|v| v.mask).and_then(|m| m.get(i)).copied().unwrap_or(1.0); + let union = |i: usize, a: f32| vstroke.as_ref().and_then(|v| v.stroke.px.get(i)).map_or(a, |s| kmask(i) * (a + s[3] * (1.0 - a))); + // Transparency Shapes Layer off: the shape is the whole layer (its masks, as the maps were + // built), and the content's own transparency acts like fill opacity within it. + let shapeless = !layer.advanced.transparency_shapes; + let shape = if shapeless { + maps.crop(&maps.shape, big, 0.0) + } else if maps.outline { + let o = maps.crop(&maps.shape, big, 0.0); + Map { w, h, v: o.v.iter().zip(&content.px).enumerate().map(|(i, (o, p))| o.max(union(i, p[3]))).collect() } + } else { + Map { w, h, v: content.px.iter().enumerate().map(|(i, p)| union(i, p[3])).collect() } + }; + let relative = shapeless || maps.outline || vstroke.is_some(); + let fx = |i: usize, k: usize| maps.crop(&maps.per[i][k], big, 0.0); + // Layer bounds (gradients aligned with the layer use the whole layer, + // independent of the render rect). + let sb = layer_bounds; + // Linked patterns tile from the effects reference point (else the layer's top-left). + let anchor = layer.effects.reference.unwrap_or((f64::from(sb.x0), f64::from(sb.y0))); + let rect = backdrop.rect; + let before = backdrop.clone(); + // Exterior effects are painted on a backdrop copy extended to `big`. + let mut work = Buffer::transparent(big); + for y in rect.y0.max(big.y0)..rect.y1.min(big.y1) { + for x in rect.x0.max(big.x0)..rect.x1.min(big.x1) { + work.px[((y - big.y0) as usize) * w + (x - big.x0) as usize] = before.get(x, y); + } + } + let items: Vec<&Effect> = layer.effects.items.iter().filter(|e| e.enabled()).collect(); + let vector_shape = matches!(layer.content, photocraft_doc::LayerContent::Shape(_)); + // Multiple instances: the first listed is on top, so paint in reverse. + let rev = || items.iter().copied().enumerate().rev(); + + for (i, e) in rev() { + if let Effect::DropShadow(s) = e { + let mut m = fx(i, 0); + if s.knocks_out { + // The layer hides the shadow beneath it where its fill is see-through (at 100 % + // fill in a normal mode it covers it anyway; at 0 % the shape shows the bare + // backdrop), and wholly in a mode that blends with it ([`shadow_see_through`]). + knock_out_exterior(&mut m, &shape, 1.0 - shadow_see_through(layer)); + } + paint_color(&mut work, &m, rgb(&s.color), s.common.blend, s.common.opacity); + } + } + for (i, e) in rev() { + if let Effect::OuterGlow(g) = e { + let mut m = fx(i, 0); + // The glow is behind the shape, not painted across its interior when Fill is 0 %. + // Preserve the existing anti-aliased edge when the fill is fully opaque. + knock_out_exterior(&mut m, &shape, layer.fill_opacity); + paint_glow(&mut work, &m, g, sb, anchor, big, patterns); + } + } + + // The layer: content at fill opacity, then interior effects. Interior effects are painted + // relative to the layer's shape (alpha = coverage within the shape), then the shape's alpha + // applies: a colour overlay at 100 % replaces the colour of a half-transparent edge pixel and + // keeps its alpha, as in Photoshop. + let fill = layer.fill_opacity; + // Blend Interior Effects as Group: the interior effects (overlays, satin, inner glow) are + // combined with the content first, and fill opacity applies to the combination. + let interior_group = layer.advanced.blend_interior && fill < 1.0; + let content_fill = if interior_group { 1.0 } else { fill }; + let inside = |a: f32| a > INSIDE_EPS; + // Within an outline (or a split-off vector stroke) the content's own transparency (a fading + // gradient fill) acts like fill opacity: the effects still cover the whole shape. + let lay_alpha = |i: usize, p: &[f32; 4], a: f32| { + if !inside(a) { + 0.0 + } else if relative { + content_fill * (kmask(i) * p[3] / a).min(1.0) + } else { + content_fill + } + }; + let mut lay = Buffer { rect: big, px: content.px.iter().zip(&shape.v).enumerate().map(|(i, (p, a))| [p[0], p[1], p[2], lay_alpha(i, p, *a)]).collect() }; + let gamma = crate::text_gamma(layer); + let premerge = premerges_layer(layer); + if premerge { + for (lp, wp) in lay.px.iter_mut().zip(&work.px) { + *lp = psblend::composite_gamma(layer.blend, *wp, *lp, 1.0, gamma); + } + } + let rel = |m: Map| -> Map { + let v = m.v.iter().zip(&shape.v).map(|(m, a)| if inside(*a) { (m / a).min(1.0) } else { 0.0 }).collect(); + Map { w: m.w, h: m.h, v } + }; + let full = Map { w, h, v: shape.v.iter().map(|a| if inside(*a) { 1.0 } else { 0.0 }).collect() }; + for (_, e) in rev() { + if let Effect::PatternOverlay { common, name, id, scale, angle, link, phase } = e { + paint_pattern(&mut lay, &full, patterns, name, id, Placement::anchored(anchor, *link, *phase, *scale, *angle), big, common.blend, common.opacity); + } + } + for (_, e) in rev() { + if let Effect::GradientOverlay { common, gradient, .. } = e { + paint_fx(&mut lay, &full, &FxPaint::Gradient(gradient.clone()), sb, anchor, big, common.blend, common.opacity, patterns) + } + } + for (_, e) in rev() { + if let Effect::ColorOverlay { common, color } = e { + paint_color(&mut lay, &full, rgb(color), common.blend, common.opacity); + } + } + for (i, e) in rev() { + if let Effect::Satin(s) = e { + let m = rel(fx(i, 0)); + paint_color(&mut lay, &m, rgb(&s.color), s.common.blend, s.common.opacity); + } + } + for (i, e) in rev() { + if let Effect::InnerGlow(g) = e { + paint_glow(&mut lay, &rel(fx(i, 0)), g, sb, anchor, big, patterns); + } + } + if interior_group { + for p in &mut lay.px { + p[3] *= fill.max(0.0); + } + } + for (i, e) in rev() { + if let Effect::InnerShadow(s) = e { + let m = rel(fx(i, 0)); + paint_color(&mut lay, &m, rgb(&s.color), s.common.blend, s.common.opacity); + } + } + // A stroked shape's vector stroke: Photoshop draws it above the fill's clipped layers and + // interior effects, below the stroke effect (psd-tools stroke-composite). + if let Some(vs) = &vstroke { + for (i, ((p, s), a)) in lay.px.iter_mut().zip(&vs.stroke.px).zip(&shape.v).enumerate() { + if s[3] > 0.0 && inside(*a) { + *p = psblend::composite(BlendMode::Normal, *p, [s[0], s[1], s[2], fill * (kmask(i) * s[3] / a).min(1.0)], 1.0); + } + } + } + // Strokes. Inside parts are painted over the layer (bottom instance first); outside parts + // are slid beneath it, so the first listed (top) instance is processed first. + let strokes: Vec<&photocraft_doc::StrokeFx> = items.iter().filter_map(|e| if let Effect::Stroke(s) = e { Some(s) } else { None }).collect(); + let ready = !strokes.is_empty(); + let din = if ready { maps.din.as_ref().map(|a| maps.crop_vec(a, big, 0.0)).unwrap_or_default() } else { Vec::new() }; + // A stroke's outer edge picks the chamfer or the exact field by its width + // ([`stroke_outside_exact`]); both are cropped here, and only the ones a stroke needs exist. + let crop_out = |v: &Option>| v.as_ref().map(|b| maps.crop_vec(b, big, FAR)); + let (dout, dout_exact, vdout, vdout_exact) = + if ready { (crop_out(&maps.dout), crop_out(&maps.dout_exact), crop_out(&maps.vdout), crop_out(&maps.vdout_exact)) } else { (None, None, None, None) }; + let widths = stroke_widths; + // A gradient stroke aligned with the layer spans the stroke's own extent. + let frame = |st: &photocraft_doc::StrokeFx| maps.stroke_frame(st).unwrap_or(sb); + for st in strokes.iter().rev().copied() { + let (in_w, _) = widths(st); + if in_w <= 0.0 { + continue; + } + let mut m = Map::new(w, h, 0.0); + for ((mv, a), dv) in m.v.iter_mut().zip(&shape.v).zip(&din) { + *mv = if inside(*a) { (in_w + 0.5 - dv).clamp(0.0, 1.0) } else { 0.0 }; + } + paint_fx(&mut lay, &m, &st.paint, frame(st), anchor, big, st.common.blend, st.common.opacity, patterns); + } + for (i, e) in rev() { + if let Effect::BevelEmboss(b) = e + && maps.bevel_paint[i] == BevelPaint::Inner + { + let (hi, sh) = (rel(fx(i, 0)), rel(fx(i, 1))); + paint_color(&mut lay, &hi, rgb(&b.highlight_color), b.highlight.blend, b.highlight.opacity); + paint_color(&mut lay, &sh, rgb(&b.shadow_color), b.shadow.blend, b.shadow.opacity); + } + } + // The shape's own alpha. + for (p, a) in lay.px.iter_mut().zip(&shape.v) { + p[3] *= a.min(1.0); + } + // Shape layers without a filled outline stroke their vector outline, estimated from local + // coverage; every other layer strokes its shape. The width then picks the field. + let vector_outline = vector_shape && !maps.outline; + // Outside parts lie beneath the layer and blend onto the backdrop with their own mode. A + // higher stroke covers the ones below it (Photoshop: a Multiply stroke listed above a wider + // Normal stroke multiplies the backdrop, not the lower stroke). Each stroke's share is its + // coverage × opacity not yet taken by strokes above; for Normal strokes this equals stacking + // them top over bottom. + if strokes.iter().any(|st| widths(st).1 > 0.0) { + let base = work.clone(); + let mut acc = vec![[0.0f32; 4]; w * h]; // premultiplied Σ share·blended + let mut cover = vec![0.0f32; w * h]; + for st in strokes.iter().copied() { + let (_, out_w) = widths(st); + if out_w <= 0.0 { + continue; + } + // Shape layers: Photoshop strokes the vector outline (estimated from local coverage + // for unfilled shapes); the stroke never shows through the shape's pixels. Along a + // filled shape's outline it covers the part of each edge pixel outside the path. + let exact = stroke_outside_exact(out_w); + let d: &[f32] = if vector_outline { + (if exact { vdout_exact.as_deref() } else { vdout.as_deref() }).unwrap_or_default() + } else if exact { + dout_exact.as_deref().unwrap_or_default() + } else { + dout.as_deref().unwrap_or_default() + }; + let mut share = vec![0.0f32; w * h]; + for (i, sh) in share.iter_mut().enumerate() { + let band = (out_w + 0.5 - d[i]).clamp(0.0, 1.0); + let k = + if inside(shape.v[i]) { if vector_shape && !maps.outline { 0.0 } else { band * outline_share(shape.v[i], lay.px[i][3]) } } else { band }; + let mut k = k * st.common.opacity; + if st.common.blend == BlendMode::Dissolve { + let (x, y) = (i64::from(big.x0) + (i % w) as i64, i64::from(big.y0) + (i / w) as i64); + k = if k > 0.0 && dissolves_in(x, y, k) { 1.0 } else { 0.0 }; + } + *sh = k * (1.0 - cover[i]); + cover[i] += *sh; + } + // The stroke blended over the backdrop at full coverage. + let mut blended = base.clone(); + let ones = Map { w, h, v: share.iter().map(|&s| if s > 0.0 { 1.0 } else { 0.0 }).collect() }; + // The share already carries the Dissolve choice, so the paint itself composites as Normal. + let paint_blend = if st.common.blend == BlendMode::Dissolve { BlendMode::Normal } else { st.common.blend }; + paint_fx(&mut blended, &ones, &st.paint, frame(st), anchor, big, paint_blend, 1.0, patterns); + for ((a, b), s) in acc.iter_mut().zip(&blended.px).zip(&share) { + if *s > 0.0 { + for c in 0..3 { + a[c] += s * b[c] * b[3]; + } + a[3] += s * b[3]; + } + } + } + for ((p, a), c) in work.px.iter_mut().zip(&acc).zip(&cover) { + if *c <= 0.0 { + continue; + } + let k = 1.0 - c.min(1.0); + let alpha = p[3] * k + a[3]; + if alpha > 0.0 { + *p = [(p[0] * p[3] * k + a[0]) / alpha, (p[1] * p[3] * k + a[1]) / alpha, (p[2] * p[3] * k + a[2]) / alpha, alpha.min(1.0)]; + } + } + } + for (i, e) in rev() { + if let Effect::BevelEmboss(b) = e + && maps.bevel_paint[i] == BevelPaint::Outer + { + let (hi, sh) = (fx(i, 0), fx(i, 1)); + paint_color(&mut work, &hi, rgb(&b.highlight_color), b.highlight.blend, b.highlight.opacity); + paint_color(&mut work, &sh, rgb(&b.shadow_color), b.shadow.blend, b.shadow.opacity); + } + } + + // Layer (with interior effects) onto the exterior result, in the layer's mode. + let mode = if premerge || layer.blend == BlendMode::PassThrough { BlendMode::Normal } else { layer.blend }; + for (wp, lp) in work.px.iter_mut().zip(&lay.px) { + if lp[3] > 0.0 { + *wp = psblend::composite_gamma(mode, *wp, *lp, 1.0, gamma); + } + } + // Emboss styles shade the composited layer (their maps cover inside and outside). Painting + // them into the layer before its (text-gamma) composite left a type layer's lit top edges up + // to 6/255 dark (psd-tools layer_effects Emboss: 7.8 → 5.7/255). + for (i, e) in rev() { + if let Effect::BevelEmboss(b) = e + && maps.bevel_paint[i] == BevelPaint::Both + { + paint_color(&mut work, &fx(i, 0), rgb(&b.highlight_color), b.highlight.blend, b.highlight.opacity); + paint_color(&mut work, &fx(i, 1), rgb(&b.shadow_color), b.shadow.blend, b.shadow.opacity); + } + } + // Layer opacity applies to the whole stack. + let op = layer.opacity; + for y in rect.y0..rect.y1 { + for x in rect.x0..rect.x1 { + let i = ((y - rect.y0) as usize) * rect.width() as usize + (x - rect.x0) as usize; + let a = before.px[i]; + let b = if x >= big.x0 && x < big.x1 && y >= big.y0 && y < big.y1 { work.px[((y - big.y0) as usize) * w + (x - big.x0) as usize] } else { a }; + backdrop.px[i] = if layer.blend == BlendMode::Dissolve { + // Dissolve applies layer opacity to the completed interior/exterior effect + // stack as pixel coverage, not continuous gray interpolation (#3051). + if crate::dissolve_noise(x, y) < op { b } else { a } + } else { + mix_premul(a, b, op) + }; + } + } +} + +/// Coverage of an outside stroke beneath a filled shape's edge pixel, for a pixel the outline +/// covers `cov` of and the layer (with its interior effects) ends at alpha `l`. Photoshop treats +/// the stroke and the shape as disjoint areas: the stroke fills the part outside the path and +/// the layer adds its own alpha (psd-tools stroke-effects: a 58 % covered edge pixel of an +/// opaque fill ends opaque, one of a faded fill at 42 % + its alpha). Composited beneath the +/// layer, `share + l (1 - share) = (1 - cov) + l`. +pub fn outline_share(cov: f32, l: f32) -> f32 { + let outside = (1.0 - cov.clamp(0.0, 1.0)).max(0.0); + if outside <= 1e-6 { + return 0.0; + } + let rest = 1.0 - l.clamp(0.0, 1.0); + if rest <= 1e-6 { 1.0 } else { (outside / rest).min(1.0) } +} + +/// (inside width, outside width) of a stroke. +pub fn stroke_widths(st: &photocraft_doc::StrokeFx) -> (f32, f32) { + match st.position { + StrokePosition::Outside => (0.0, st.size), + StrokePosition::Inside => (st.size, 0.0), + StrokePosition::Center => (st.size / 2.0, st.size / 2.0), + } +} + +/// The frame a gradient stroke aligned with the layer is laid out in: the pixel bounds of the +/// effect shape (over `rect`) grown by the stroke's outside width less one pixel. Photoshop +/// spans the gradient over the stroke's extent, not the layer's: a 4 px outside stroke around a +/// 22 px square runs its 90° gradient over 28 px (psd-tools stroke-effects), a 3 px one around +/// 36 px of type over 40 px (psd-tools effect-stroke-gradient). +fn stroke_frame(shape: &Map, out_w: f32, rect: Rect) -> Rect { + let (mut x0, mut y0, mut x1, mut y1) = (usize::MAX, usize::MAX, 0usize, 0usize); + for y in 0..shape.h { + for x in 0..shape.w { + if shape.v[y * shape.w + x] > INSIDE_EPS { + (x0, y0, x1, y1) = (x0.min(x), y0.min(y), x1.max(x + 1), y1.max(y + 1)); + } + } + } + if x0 == usize::MAX { + return rect; + } + let grow = if out_w.is_finite() { (out_w.min(MAX_REACH).ceil() as i32 - 1).max(0) } else { 0 }; + Rect::new(rect.x0 + x0 as i32, rect.y0 + y0 as i32, rect.x0 + x1 as i32, rect.y0 + y1 as i32).inflate(grow) +} + +/// A stroked shape's vector stroke, composited apart from its fill (which the compositor then +/// passes unmasked): the stroke's pixels over the render rect and the layer's mask values. +pub(crate) struct VectorStroke<'a> { + pub stroke: &'a Buffer, + pub mask: Option<&'a [f32]>, +} + +/// Premultiplied linear interpolation between two straight-alpha pixels. +fn mix_premul(a: [f32; 4], b: [f32; 4], k: f32) -> [f32; 4] { + let alpha = a[3] + (b[3] - a[3]) * k; + if alpha <= 0.0 { + return [0.0; 4]; + } + let mut out = [0.0; 4]; + for c in 0..3 { + out[c] = (a[c] * a[3] + (b[c] * b[3] - a[c] * a[3]) * k) / alpha; + } + out[3] = alpha; + out +} diff --git a/crates/compose/src/effects/distance.rs b/crates/compose/src/effects/distance.rs new file mode 100644 index 0000000000..8581e1c821 --- /dev/null +++ b/crates/compose/src/effects/distance.rs @@ -0,0 +1,810 @@ +use super::*; + +/// 1D squared distance transform (Felzenszwalb & Huttenlocher). +fn dt1(f: &[f32], out: &mut [f32], v: &mut [usize], z: &mut [f32], near: &mut [usize]) { + let n = f.len(); + let mut k = 0usize; + v[0] = 0; + z[0] = f32::NEG_INFINITY; + z[1] = f32::INFINITY; + for q in 1..n { + loop { + let p = v[k]; + let s = ((f[q] + (q * q) as f32) - (f[p] + (p * p) as f32)) / (2.0 * q as f32 - 2.0 * p as f32); + if s <= z[k] && k > 0 { + k -= 1; + continue; + } + if s <= z[k] { + // k == 0 and parabola dominates: replace. + v[0] = q; + z[0] = f32::NEG_INFINITY; + z[1] = f32::INFINITY; + break; + } + k += 1; + v[k] = q; + z[k] = s; + z[k + 1] = f32::INFINITY; + break; + } + } + k = 0; + for (q, o) in out.iter_mut().enumerate() { + while z[k + 1] < q as f32 { + k += 1; + } + let p = v[k]; + let d = q as f32 - p as f32; + *o = d * d + f[p]; + near[q] = p; + } +} + +/// Exact Euclidean distance from every pixel to the nearest pixel where +/// `inside` is true (0 on those pixels). +#[cfg(test)] +pub(super) fn edt(inside: &[bool], w: usize, h: usize) -> Vec { + edt_nearest(inside, w, h).0 +} + +/// Maps with fewer pixels (or other units of work) than this are not worth spawning threads for. +const PAR_MIN: usize = 1 << 16; + +/// Most threads one pass uses (as for the blurs, [`rows_par`]). +const PAR_THREADS: usize = 16; + +#[cfg(test)] +thread_local! { + /// Test hook: the thread count [`par_threads`] gives on this thread, whatever the work. + pub(super) static THREADS: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// How many threads a pass over `work` pixels (or similar units) uses. +fn par_threads(work: usize) -> usize { + #[cfg(test)] + if let Some(n) = THREADS.with(std::cell::Cell::get) { + return n; + } + if cfg!(target_arch = "wasm32") || work < PAR_MIN { 1 } else { std::thread::available_parallelism().map_or(1, |n| n.get()).clamp(1, PAR_THREADS) } +} + +/// Runs `f(scratch, u, a_u, b_u)` for every unit `u` of two slices: unit `u` of `a` is +/// `a[u * unit_a..][..unit_a]` (the last may be shorter), the same of `b` with `unit_b`, which is 0 +/// when there is no second slice. `work` says how big the whole pass is ([`par_threads`]). Groups of +/// units go to scoped OS threads, each with a scratch value from `init`; not to rayon, as for +/// [`rows_par`]: maps are built from inside rayon tiles, where a waiting worker steals other tiles. +/// A unit is computed from its own arguments alone, so the result does not depend on the threads. +pub(super) fn par_units( + work: usize, + a: &mut [A], + unit_a: usize, + b: &mut [B], + unit_b: usize, + init: impl Fn() -> S + Sync, + f: impl Fn(&mut S, usize, &mut [A], &mut [B]) + Sync, +) { + if unit_a == 0 { + return; + } + let units = a.len().div_ceil(unit_a); + let threads = par_threads(work).min(units); + if threads <= 1 { + run_units(&mut init(), 0, a, unit_a, b, unit_b, &f); + return; + } + // Many more groups than threads, so that a heavy one (an edge-rich stretch) does not hold the rest up. + let group = units.div_ceil(threads * 8).max(1); + let mut groups = Vec::new(); + let (mut rest_a, mut rest_b, mut first) = (a, b, 0usize); + while !rest_a.is_empty() { + let (ga, na) = rest_a.split_at_mut((group * unit_a).min(rest_a.len())); + let (gb, nb) = rest_b.split_at_mut((group * unit_b).min(rest_b.len())); + groups.push((first, ga, gb)); + (rest_a, rest_b, first) = (na, nb, first + group); + } + let queue = std::sync::Mutex::new(groups.into_iter()); + let worker = || { + let mut scratch = init(); + loop { + let next = queue.lock().unwrap_or_else(std::sync::PoisonError::into_inner).next(); + let Some((first, ga, gb)) = next else { break }; + run_units(&mut scratch, first, ga, unit_a, gb, unit_b, &f); + } + }; + std::thread::scope(|sc| { + // A thread that cannot be spawned leaves its share to the others. + for _ in 1..threads { + let _ = std::thread::Builder::new().spawn_scoped(sc, worker); + } + worker(); + }); +} + +fn run_units(scratch: &mut S, first: usize, a: &mut [A], unit_a: usize, b: &mut [B], unit_b: usize, f: &impl Fn(&mut S, usize, &mut [A], &mut [B])) { + for (k, ua) in a.chunks_mut(unit_a).enumerate() { + let ub = b.get_mut(k * unit_b..((k + 1) * unit_b).min(b.len())).unwrap_or(&mut []); + f(scratch, first + k, ua, ub); + } +} + +/// A `w × h` buffer of `fill`, then filled row by row through `f(y, row)`. +pub(super) fn par_fill(w: usize, h: usize, fill: T, f: impl Fn(usize, &mut [T]) + Sync) -> Vec { + let mut out = vec![fill; w.saturating_mul(h)]; + par_units(out.len(), &mut out, w.max(1), &mut [] as &mut [()], 0, || (), |_, y, row, _| f(y, row)); + out +} + +/// Working buffers of the 1D distance transform, for lines of up to `n` pixels. +struct Dt1Scratch { + f: Vec, + o: Vec, + v: Vec, + z: Vec, + near: Vec, +} + +impl Dt1Scratch { + fn new(n: usize) -> Self { + Dt1Scratch { f: vec![0.0; n], o: vec![0.0; n], v: vec![0; n], z: vec![0.0; n + 1], near: vec![0; n] } + } +} + +/// [`edt`] plus the index of the nearest `inside` pixel (as `u32`: a map past 2³² pixels has no +/// nearest pixel to give, and every distance is then "far"). +/// +/// Both passes run line by line in parallel: the columns, then the rows. The columns' results are +/// kept column by column (`gc[x * h + y]`) so that each thread writes its own stretch of them. +pub(super) fn edt_nearest(inside: &[bool], w: usize, h: usize) -> (Vec, Vec) { + const INF: f32 = 1e20; + let total = w.saturating_mul(h); + if total != inside.len() || total > u32::MAX as usize { + return (vec![INF; inside.len()], vec![0; inside.len()]); + } + let n = w.max(h); + let mut gc = vec![0.0f32; total]; + let mut nc = vec![0u32; total]; + par_units( + total, + &mut gc, + h.max(1), + &mut nc, + h.max(1), + || Dt1Scratch::new(n), + |t, x, g, near| { + for (y, f) in t.f[..h].iter_mut().enumerate() { + *f = if inside[y * w + x] { 0.0 } else { INF }; + } + dt1(&t.f[..h], &mut t.o[..h], &mut t.v, &mut t.z, &mut t.near[..h]); + g.copy_from_slice(&t.o[..h]); + for (d, &p) in near.iter_mut().zip(&t.near[..h]) { + *d = p as u32; + } + }, + ); + let mut g = vec![0.0f32; total]; + let mut nearest = vec![0u32; total]; + par_units( + total, + &mut g, + w.max(1), + &mut nearest, + w.max(1), + || Dt1Scratch::new(n), + |t, y, out, near| { + for (x, f) in t.f[..w].iter_mut().enumerate() { + *f = gc[x * h + y]; + } + dt1(&t.f[..w], &mut t.o[..w], &mut t.v, &mut t.z, &mut t.near[..w]); + for (x, (d, ne)) in out.iter_mut().zip(near.iter_mut()).enumerate() { + *d = t.o[x].sqrt(); + let px = t.near[x]; + *ne = (nc[px * h + y] as usize * w + px) as u32; + } + }, + ); + (g, nearest) +} + +/// Chamfer distance transform with a 5 × 5 mask of exact Euclidean step lengths (1, √2, √5), +/// plus the index of the nearest `inside` pixel (0 on inside pixels). Photoshop's effect +/// distances follow this metric: its stroke corners measure 3.236 = √5 + 1 at offset (1, 3) +/// and 3.650 = √5 + √2 at (2, 3), where the exact distances are 3.162 and 3.606. +#[cfg(test)] +pub(super) fn chamfer_nearest(inside: &[bool], w: usize, h: usize) -> (Vec, Vec) { + chamfer_from(inside.iter().map(|&b| if b { 0.0 } else { CHAMFER_INF }).collect(), w, h) +} + +const CHAMFER_INF: f32 = 1e20; + +/// [`chamfer_nearest`] from per-pixel start values (`CHAMFER_INF` = not a seed): the result is +/// the minimum over seeds of start value + path length, so partly covered seeds can start at +/// their sub-pixel edge offset. +fn chamfer_from(mut d: Vec, w: usize, h: usize) -> (Vec, Vec) { + const S2: f32 = std::f32::consts::SQRT_2; + const S5: f32 = 2.236_068; + // Forward-pass neighbours (already visited in raster order); the backward pass mirrors them. + const FWD: [(i64, i64, f32); 8] = [(-1, 0, 1.0), (-1, -1, S2), (0, -1, 1.0), (1, -1, S2), (-1, -2, S5), (1, -2, S5), (-2, -1, S5), (2, -1, S5)]; + let mut near: Vec = (0..w * h).collect(); + let (wi, hi) = (w as i64, h as i64); + let relax = |x: i64, y: i64, sign: i64, d: &mut Vec, near: &mut Vec| { + let i = (y * wi + x) as usize; + let mut best = d[i]; + let mut bn = near[i]; + for &(ox, oy, wt) in &FWD { + let (nx, ny) = (x + ox * sign, y + oy * sign); + if nx < 0 || ny < 0 || nx >= wi || ny >= hi { + continue; + } + let j = (ny * wi + nx) as usize; + let c = d[j] + wt; + if c < best { + best = c; + bn = near[j]; + } + } + d[i] = best; + near[i] = bn; + }; + for y in 0..hi { + for x in 0..wi { + relax(x, y, 1, &mut d, &mut near); + } + } + for y in (0..hi).rev() { + for x in (0..wi).rev() { + relax(x, y, -1, &mut d, &mut near); + } + } + (d, near) +} + +/// Distance from each pixel centre outside the shape to the shape's edge. +/// Pixels with non-zero alpha are inside; the edge inside the nearest such +/// pixel is placed by its alpha (coverage), as Photoshop does. Inside pixels +/// get ≤ 0. +pub(super) fn dist_outside(s: &Map) -> Vec { + dist_outside_by(s, Metric::Euclidean) +} + +/// Distance metric for effect distance fields. +#[derive(Clone, Copy, PartialEq)] +pub(super) enum Metric { + /// Exact Euclidean (effect edges). + Euclidean, + /// 5 × 5 chamfer (inside strokes, spread / choke; see [`chamfer_nearest`]). + Chamfer, +} + +/// Outside width from which a stroke's outer edge uses the exact Euclidean transform instead of +/// the fitted 5 × 5 chamfer. +/// +/// The chamfer's level sets are octagons: measured against a point source, its distance exceeds +/// the Euclidean radius by up to `0.027 · r` px — 0.48 px at r = 18 (the widest outside stroke any +/// Photoshop oracle matches with the chamfer) and 1.6 px at r = 60, where a wide stroke's boundary +/// visibly facets (#3646). Half a pixel of deviation is reached at r ≈ 19, so strokes narrower +/// than 20 px keep the chamfer, whose sub-pixel edge seeding Photoshop matches at small offsets, +/// and wider ones stay round. +pub const STROKE_CHAMFER_MAX: f32 = 20.0; + +/// Whether a stroke whose outside edge is `out_w` px wide uses the exact Euclidean transform (round) +/// rather than the 5 × 5 chamfer's octagon ([`STROKE_CHAMFER_MAX`]). The CPU compositor and the GPU +/// compositor's `program_with` both call this, so a stroke picks the same field in each. +pub fn stroke_outside_exact(out_w: f32) -> bool { + out_w >= STROKE_CHAMFER_MAX +} + +pub(super) fn dist_outside_by(s: &Map, m: Metric) -> Vec { + if m == Metric::Chamfer { + // Seeds start at their sub-pixel edge offset (1 − coverage). + let start = s.v.iter().map(|&a| if a > INSIDE_EPS { 1.0 - a.min(1.0) } else { CHAMFER_INF }).collect(); + let (d, _) = chamfer_from(start, s.w, s.h); + return d.iter().zip(&s.v).map(|(d, &a)| if a > INSIDE_EPS { -0.5 } else { d - 0.5 }).collect(); + } + let inside = covered(s, |a| a > INSIDE_EPS); + let (d, near) = edt_nearest(&inside, s.w, s.h); + par_fill(s.w, s.h, 0.0f32, |y, row| { + for (x, out) in row.iter_mut().enumerate() { + let i = y * s.w + x; + *out = if inside[i] { -0.5 } else { d[i] - 0.5 + (1.0 - s.v[near[i] as usize].min(1.0)) }; + } + }) +} + +/// Which pixels of `s` satisfy `test`, row by row in parallel. +fn covered(s: &Map, test: impl Fn(f32) -> bool + Sync) -> Vec { + par_fill(s.w, s.h, false, |y, row| { + for (e, &a) in row.iter_mut().zip(s.v.get(y * s.w..).unwrap_or_default()) { + *e = test(a); + } + }) +} + +/// Distance from each pixel centre inside the shape to the shape's edge +/// (≤ 0 outside). +pub(super) fn dist_inside(s: &Map) -> Vec { + dist_inside_by(s, Metric::Euclidean) +} + +pub(super) fn dist_inside_by(s: &Map, m: Metric) -> Vec { + if m == Metric::Chamfer { + // Partly covered edge pixels (alpha below their neighbourhood's) are seeds starting at + // their coverage, mirroring `dist_outside`: a 25 % edge column puts the edge 0.25 px in. + let cov = local_coverage(s); + let start = + s.v.iter() + .zip(&cov.v) + .map(|(&a, &c)| { + if a <= INSIDE_EPS { + 0.0 + } else if c < 1.0 - INSIDE_EPS { + c + } else { + CHAMFER_INF + } + }) + .collect(); + let (d, _) = chamfer_from(start, s.w, s.h); + return d.iter().zip(&s.v).map(|(d, &a)| if a <= INSIDE_EPS { -0.5 } else { d - 0.5 }).collect(); + } + let outside = covered(s, |a| a <= INSIDE_EPS); + let (d, _) = edt_nearest(&outside, s.w, s.h); + par_fill(s.w, s.h, 0.0f32, |y, row| { + for (x, out) in row.iter_mut().enumerate() { + let i = y * s.w + x; + *out = if outside[i] { -0.5 } else { d[i] - 0.5 }; + } + }) +} + +/// Alpha relative to the 3×3 neighbourhood maximum: separates edge coverage +/// from the fill's own opacity on shape layers. +pub(super) fn local_coverage(s: &Map) -> Map { + let mut out = s.clone(); + for y in 0..s.h as i64 { + for x in 0..s.w as i64 { + let a = s.get(x, y); + if a <= INSIDE_EPS { + continue; + } + let mut mx = a; + for dy in -1..=1 { + for dx in -1..=1 { + mx = mx.max(s.get(x + dx, y + dy)); + } + } + out.v[y as usize * s.w + x as usize] = (a / mx).min(1.0); + } + } + out +} + +/// Signed distance from the centre of a pixel of coverage `a` to the straight edge crossing it, +/// positive when the centre is inside the shape. `n` is the edge's unit normal (its signs don't +/// matter). +/// +/// A unit pixel cut by a straight edge at distance `r` from its centre (on the side that holds at +/// most half of the pixel) is covered `1/2 - r/u` while the edge crosses two opposite sides, and +/// `((u + v)/2 - r)² / (2uv)` once it only cuts off a corner, with `u ≥ v` the larger and smaller +/// component of the normal. Inverting that places the edge by its coverage at any angle. For an +/// axis-aligned edge (`v = 0`) it is the `a - 1/2` that [`dist_outside`] assumes. +pub(super) fn edge_offset(n: [f32; 2], a: f32) -> f32 { + if !a.is_finite() { + return 0.0; + } + let (u, v) = (n[0].abs().max(n[1].abs()), n[0].abs().min(n[1].abs())); + let (c, inside) = if a > 0.5 { (1.0 - a, true) } else { (a, false) }; + let c = c.clamp(0.0, 0.5); + // The coverage below which the edge only cuts off a corner. + let corner = if u > 0.0 { v / (2.0 * u) } else { 0.0 }; + let r = if c >= corner { (0.5 - c) * u } else { 0.5 * (u + v) - (2.0 * u * v * c).sqrt() }; + if inside { r } else { -r } +} + +/// A sharp, anti-aliased edge pixel: where it puts the straight edge crossing it. +#[derive(Clone, Copy)] +pub(super) struct SharpEdge { + /// Signed distance from the pixel's centre to the edge, positive inside ([`edge_offset`]). + pub(super) offset: f32, + /// The edge's unit normal pointing into the shape (`[0, 0]` when the coverage gives no direction). + pub(super) normal: [f32; 2], +} + +/// Half the spacing of the edge pixels along an edge (at most √2 / 2, along a diagonal): a pixel +/// within it of the foot of the perpendicular sees the edge as a line, one further out as its end. +const EDGE_REACH: f32 = 0.75; + +impl SharpEdge { + /// Distance to the edge from the pixel `(dx, dy)` away from this one, positive on the shape's + /// side (`inside`) or on the empty side. It is the distance to the edge's line where the + /// perpendicular lands within [`EDGE_REACH`] of this pixel, and to the end of that stretch + /// beyond, so the distance to a straight edge is exact and does not follow the pixel staircase. + /// `None` when the edge has no direction or `(dx, dy)` is on the wrong side of it. + fn distance(&self, dx: f32, dy: f32, inside: bool) -> Option { + let [nx, ny] = self.normal; + if nx == 0.0 && ny == 0.0 { + return None; + } + let signed = self.offset + dx * nx + dy * ny; + let across = if inside { signed } else { -signed }; + let along = (dx * -ny + dy * nx).abs(); + (across > 0.0).then(|| across.hypot((along - EDGE_REACH).max(0.0))) + } +} + +/// A sharp edge pixel and where it sits. +#[derive(Clone, Copy)] +pub(super) struct EdgePixel { + /// Index of the pixel in the map. + pub(super) at: u32, + /// The pixel's coverage ([`local_coverage`] of it). + pub(super) cov: f32, + pub(super) edge: SharpEdge, +} + +/// The sharp edge pixels of a map: a short list, and for every pixel a 4 byte slot (0 = no edge, k = +/// the k-th of the list). Maps are big and edge pixels few, so a per-pixel `Option` (16 +/// bytes) made every pass over it, and the copies the refinement needs, memory-bound. +pub(super) struct SharpEdges { + w: usize, + h: usize, + pub(super) slot: Vec, + pub(super) pixels: Vec, +} + +impl SharpEdges { + fn empty(w: usize, h: usize) -> Self { + SharpEdges { w, h, slot: Vec::new(), pixels: Vec::new() } + } + + /// The edge of pixel `i`, if it is a sharp edge pixel. + fn get(&self, i: usize) -> Option { + let k = (*self.slot.get(i)? as usize).checked_sub(1)?; + self.pixels.get(k).map(|p| p.edge) + } + + /// The edge of pixel `(x, y)`, if it is a sharp edge pixel (`None` off the map). + fn at(&self, x: usize, y: usize) -> Option { + if x >= self.w || y >= self.h { None } else { self.get(y * self.w + x) } + } + + fn has(&self, x: usize, y: usize) -> bool { + self.at(x, y).is_some() + } + + pub(super) fn is_empty(&self) -> bool { + self.pixels.is_empty() + } + + /// Every sharp edge pixel, as (index in the map, its edge), in pixel order. + #[cfg(test)] + pub(super) fn iter(&self) -> impl Iterator + '_ { + self.pixels.iter().map(|p| (p.at as usize, p.edge)) + } +} + +/// Where the sharp, anti-aliased edge pixels of `s` put the edge ([`edge_offset`], along the normal +/// the coverage gradient gives). Sharp pixels are partly covered and touch both an empty and a full +/// pixel; hard edges and soft ramps have none and keep the `alpha - 1/2` of [`dist_outside`]. +/// +/// An edge pixel is covered and has an empty neighbour, so a pass over which pixels are covered finds +/// the few candidates without computing [`local_coverage`] of the whole map; the coverage is then +/// worked out where it is needed, by the same formula. Rows are independent and go in parallel. +pub(super) fn sharp_edges(s: &Map) -> SharpEdges { + let (w, h) = (s.w, s.h); + if w == 0 || h == 0 || s.v.len() != w * h || s.v.len() >= u32::MAX as usize { + return SharpEdges::empty(w, h); + } + let (wi, hi) = (w as i64, h as i64); + // `local_coverage` of the pixel at (x, y), on the map. + let cov_at = |x: i64, y: i64| -> f32 { + let a = s.v[y as usize * w + x as usize]; + if a <= INSIDE_EPS { + return a; + } + let mut mx = a; + for dy in -1..=1 { + for dx in -1..=1 { + mx = mx.max(s.get(x + dx, y + dy)); + } + } + (a / mx).min(1.0) + }; + // The coverage with the map's border repeated, for the gradient. + let cov_clamped = |x: i64, y: i64| cov_at(x.max(0).min(wi - 1), y.max(0).min(hi - 1)); + // Whether a pixel is not empty. Off the map counts as covered: only a neighbour on the map can be empty. + let solid = |x: i64, y: i64| -> bool { + if x < 0 || y < 0 || x >= wi || y >= hi { + return true; + } + let a = s.v[y as usize * w + x as usize]; + a.is_nan() || a > INSIDE_EPS + }; + let mut rows: Vec> = vec![Vec::new(); h]; + par_units( + w * h, + &mut rows, + 1, + &mut [] as &mut [()], + 0, + || (), + |_, y, row, _| { + let Some(row) = row.first_mut() else { return }; + let y = y as i64; + for x in 0..wi { + if !solid(x, y) || (-1..=1).all(|dy| (-1..=1).all(|dx| solid(x + dx, y + dy))) { + continue; + } + let i = (y * wi + x) as usize; + let c = cov_at(x, y); + if s.v[i] <= INSIDE_EPS || c >= 1.0 - INSIDE_EPS { + continue; + } + let (mut empty, mut full) = (false, false); + for (dx, dy) in (-1..=1).flat_map(|dy| (-1..=1).map(move |dx| (dx, dy))) { + let (nx, ny) = (x + dx, y + dy); + if (dx, dy) == (0, 0) || nx < 0 || ny < 0 || nx >= wi || ny >= hi { + continue; + } + empty |= s.get(nx, ny) <= INSIDE_EPS; + full |= cov_at(nx, ny) >= 1.0 - INSIDE_EPS; + } + if !(empty && full) { + continue; + } + let at = &cov_clamped; + let gx = (at(x + 1, y - 1) + 2.0 * at(x + 1, y) + at(x + 1, y + 1)) - (at(x - 1, y - 1) + 2.0 * at(x - 1, y) + at(x - 1, y + 1)); + let gy = (at(x - 1, y + 1) + 2.0 * at(x, y + 1) + at(x + 1, y + 1)) - (at(x - 1, y - 1) + 2.0 * at(x, y - 1) + at(x + 1, y - 1)); + let len = gx.hypot(gy); + let (normal, n) = if len.is_finite() && len > 1e-6 { ([gx / len, gy / len], [gx / len, gy / len]) } else { ([0.0, 0.0], [1.0, 0.0]) }; + row.push(EdgePixel { at: i as u32, cov: c, edge: SharpEdge { offset: edge_offset(n, c), normal } }); + } + }, + ); + let mut pixels: Vec = Vec::with_capacity(rows.iter().map(Vec::len).sum()); + for row in rows { + pixels.extend(row); + } + let mut slot = vec![0u32; w * h]; + for (k, p) in pixels.iter().enumerate() { + if let Some(s) = slot.get_mut(p.at as usize) { + *s = k as u32 + 1; + } + } + refine_edge_normals(&mut pixels, &slot, w, h); + SharpEdges { w, h, slot, pixels } +} + +/// How far (in pixels) around an edge pixel [`refine_edge_normals`] looks for its neighbours. +const NORMAL_RADIUS: i64 = 3; + +/// The 3×3 gradient of the coverage gives an edge's direction to 1-2 degrees, and its error is +/// systematic, so it tilts the distance of every pixel the same way and shows as a faint ripple. +/// The edge points of a straight edge's pixels (each pixel's centre moved to its edge) lie on one +/// line, and the line through the points of the pixels around one gives the direction to a fraction +/// of a degree. Where those points are not on a line (corners, tight curves) the gradient's normal +/// stays. +fn refine_edge_normals(pixels: &mut [EdgePixel], slot: &[u32], w: usize, h: usize) { + let (wi, hi) = (w as i64, h as i64); + let points: Vec<[f32; 2]> = pixels + .iter() + .map(|p| [(p.at as i64 % wi) as f32 - p.edge.offset * p.edge.normal[0], (p.at as i64 / wi) as f32 - p.edge.offset * p.edge.normal[1]]) + .collect(); + let before: Vec = pixels.iter().map(|p| p.edge).collect(); + // Every pixel reads the unrefined edges around it and writes its own, so they go in parallel. + let work = pixels.len().saturating_mul(32); + par_units(work, pixels, 1, &mut [] as &mut [()], 0, Vec::<[f32; 2]>::new, |near, k, pixel, _| { + let (Some(pixel), Some(&e)) = (pixel.first_mut(), before.get(k)) else { return }; + let (x, y) = (pixel.at as i64 % wi, pixel.at as i64 / wi); + let (mut n, mut sum) = (0.0f32, [0.0f32; 2]); + near.clear(); + for (dx, dy) in (-NORMAL_RADIUS..=NORMAL_RADIUS).flat_map(|dy| (-NORMAL_RADIUS..=NORMAL_RADIUS).map(move |dx| (dx, dy))) { + let (nx, ny) = (x + dx, y + dy); + if dx * dx + dy * dy > NORMAL_RADIUS * NORMAL_RADIUS || nx < 0 || ny < 0 || nx >= wi || ny >= hi { + continue; + } + let Some(j) = slot.get((ny * wi + nx) as usize).and_then(|&s| (s as usize).checked_sub(1)) else { continue }; + let (Some(o), Some(&p)) = (before.get(j), points.get(j)) else { continue }; + if o.normal[0] * e.normal[0] + o.normal[1] * e.normal[1] > 0.9 { + near.push(p); + sum = [sum[0] + p[0], sum[1] + p[1]]; + n += 1.0; + } + } + if near.len() < 3 { + return; + } + let mean = [sum[0] / n, sum[1] / n]; + let (mut sxx, mut sxy, mut syy) = (0.0f32, 0.0f32, 0.0f32); + for p in near.iter() { + let (dx, dy) = (p[0] - mean[0], p[1] - mean[1]); + sxx += dx * dx; + sxy += dx * dy; + syy += dy * dy; + } + // Spread along and across the best line through the points. + let half = 0.5 * (sxx + syy); + let root = (0.25 * (sxx - syy) * (sxx - syy) + sxy * sxy).sqrt(); + let (along, across) = (((half + root) / n).max(0.0).sqrt(), ((half - root) / n).max(0.0).sqrt()); + if !(along > EDGE_LINE_MIN_SPREAD && across < EDGE_LINE_MAX_OFF) { + return; + } + let angle = 0.5 * (2.0 * sxy).atan2(sxx - syy); + let mut normal = [-angle.sin(), angle.cos()]; + if normal[0] * e.normal[0] + normal[1] * e.normal[1] < 0.0 { + normal = [-normal[0], -normal[1]]; + } + pixel.edge.normal = normal; + pixel.edge.offset = edge_offset(normal, pixel.cov); + }); +} + +/// The edge points around a pixel must spread at least this far (px, standard deviation) along +/// their line to give it a direction, and stay within [`EDGE_LINE_MAX_OFF`] of it. +const EDGE_LINE_MIN_SPREAD: f32 = 0.7; + +const EDGE_LINE_MAX_OFF: f32 = 0.1; + +/// How far from the foot of the perpendicular (in pixels) [`edge_distance`] looks for edge pixels. +const FOOT_RADIUS: i64 = 2; + +/// The distance from pixel `p` to the sharp edge whose pixel `q` is nearest to it, or `None` when +/// `q` gives no usable distance. The nearest pixel by its centre is not the best one: it can sit a +/// few pixels along the edge from the foot of the perpendicular and deeper than the edge, and the +/// further `p` is from the edge the further, so its distance ripples along the edge. So this takes +/// the smallest distance of the edge pixels around that foot, which is exact for a straight edge. +fn edge_distance(sharp: &SharpEdges, p: [usize; 2], q: [usize; 2], inside: bool) -> Option { + let (px, py) = (p[0] as f32, p[1] as f32); + let e = sharp.at(q[0], q[1])?; + let mut best = e.distance(px - q[0] as f32, py - q[1] as f32, inside)?; + // Where p's perpendicular meets q's line. + let signed = e.offset + (px - q[0] as f32) * e.normal[0] + (py - q[1] as f32) * e.normal[1]; + let (fx, fy) = ((px - signed * e.normal[0]).round() as i64, (py - signed * e.normal[1]).round() as i64); + for sy in (fy - FOOT_RADIUS).max(0)..=(fy + FOOT_RADIUS).min(sharp.h as i64 - 1) { + for sx in (fx - FOOT_RADIUS).max(0)..=(fx + FOOT_RADIUS).min(sharp.w as i64 - 1) { + if let Some(near) = sharp.at(sx as usize, sy as usize) + && let Some(d) = near.distance(px - sx as f32, py - sy as f32, inside) + { + best = best.min(d); + } + } + } + Some(best) +} + +/// [`dist_inside`] for chiselled bevels. A sharp edge pixel puts the edge where its coverage says, +/// at any angle, and the pixels near it measure to that edge ([`edge_distance`]), so the distance +/// ramps stay planar along an oblique edge instead of following the pixel staircase. The plain +/// distance (to the nearest empty pixel, less half a pixel) never falls short of the true one, so +/// it caps the result where an edge lies exactly on a pixel boundary and has no sharp pixel; a mask +/// without sharp pixels gives exactly [`dist_inside`]. Values past `reach` pixels are not refined. +pub(super) fn bevel_dist_inside(s: &Map, sharp: &SharpEdges, reach: f32) -> Vec { + let empty = covered(s, |a| a <= INSIDE_EPS); + let (d, near) = edt_nearest(&empty, s.w, s.h); + let at = |x: usize, y: usize| -> f32 { + let i = y * s.w + x; + if empty[i] { + return -0.5; + } + if let Some(e) = sharp.get(i) { + return e.offset; + } + let plain = d[i] - 0.5; + if d[i] > reach + EDGE_MARGIN || sharp.is_empty() { + return plain; + } + // The sharp pixel next to the nearest empty one that is nearest to this pixel. + let (px, py) = (x as i64, y as i64); + let (ox, oy) = ((near[i] as usize % s.w) as i64, (near[i] as usize / s.w) as i64); + let q = (-1..=1) + .flat_map(|dy| (-1..=1).map(move |dx| (ox + dx, oy + dy))) + .filter(|&(x, y)| x >= 0 && y >= 0 && sharp.has(x as usize, y as usize)) + .min_by_key(|&(x, y)| (x - px) * (x - px) + (y - py) * (y - py)); + match q.and_then(|(x, y)| edge_distance(sharp, [px as usize, py as usize], [x as usize, y as usize], true)) { + Some(refined) => refined.min(plain), + None => plain, + } + }; + par_fill(s.w, s.h, 0.0f32, |y, row| { + for (x, out) in row.iter_mut().enumerate() { + *out = at(x, y); + } + }) +} + +/// [`dist_outside`] for chiselled bevels, with sharp edge pixels placed as in [`bevel_dist_inside`]. +pub(super) fn bevel_dist_outside(s: &Map, sharp: &SharpEdges, reach: f32) -> Vec { + let inside = covered(s, |a| a > INSIDE_EPS); + let (d, near) = edt_nearest(&inside, s.w, s.h); + let at = |x: usize, y: usize| -> f32 { + let i = y * s.w + x; + if let Some(e) = sharp.get(i) { + return -e.offset; + } + if inside[i] { + return -0.5; + } + let q = near[i] as usize; + let Some(e) = sharp.get(q) else { return d[i] - (s.v[q].min(1.0) - 0.5) }; + let (p, qp) = ([x, y], [q % s.w, q / s.w]); + let measured = if d[i] <= reach + EDGE_MARGIN { + edge_distance(sharp, p, qp, false) + } else { + e.distance(p[0] as f32 - qp[0] as f32, p[1] as f32 - qp[1] as f32, false) + }; + measured.unwrap_or(d[i] - e.offset) + }; + par_fill(s.w, s.h, 0.0f32, |y, row| { + for (x, out) in row.iter_mut().enumerate() { + *out = at(x, y); + } + }) +} + +/// Pixels past the reach that are still refined, so the value is right where the ramp ends. +const EDGE_MARGIN: f32 = 2.0; + +/// Alpha above which a pixel belongs to the layer's shape (half an 8-bit step). +pub(super) const INSIDE_EPS: f32 = 0.5 / 255.0; + +/// A distance field of an effect shape, as the map builders above compute it (for the GPU +/// compositor, which builds the rest of the maps itself; keep in sync with `shadow_map`, +/// `glow_map`, `bevel_maps` and `build_maps`). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum FieldKind { + /// `dist_outside` of the shape: precise outer glows. + Outside, + /// `dist_inside` of the shape: precise inner glows. + Inside, + /// `bevel_dist_outside` of the shape: the outside distance of chiselled bevels. + BevelOutside, + /// `bevel_dist_inside` of the shape: the inside distance of chiselled bevels. + BevelInside, + /// Chamfer distance outside the shape: a narrow raster stroke's outer edge (see + /// [`stroke_outside_exact`]), and the spread of drop shadows and softer outer glows + /// ([`dilate`]); their metric is fitted to Photoshop (#224) and keeps the sub-pixel seeding. + StrokeOutside, + /// Chamfer distance outside `1 - alpha`: the choke of inner shadows and softer inner glows. + ChokeInside, + /// Stroke distance inside the shape. + StrokeInside, + /// Exact Euclidean distance outside the shape: a wide raster stroke's outer edge (see + /// [`stroke_outside_exact`]). The chamfer's level sets are polygons (an ~8-fold octagon), so a + /// wide stroke's outer boundary facets; the shadow / glow spread above keeps the chamfer (#3646). + StrokeOutsideExact, + /// Stroke distance outside a shape layer's outline (from its local coverage), exact Euclidean. + StrokeOutsideVector, + /// Chamfer distance outside a shape layer's outline (from its local coverage): a narrow vector + /// stroke's outer edge, where the chamfer matches Photoshop (see [`STROKE_CHAMFER_MAX`]). + StrokeOutsideVectorChamfer, +} + +/// The `kind` distance field of the shape `alpha` (row-major `w × h`). Values past `reach` pixels +/// from the shape's edge are only meant to be large (the bevel fields skip refining them). +pub fn distance_field(kind: FieldKind, alpha: Vec, w: usize, h: usize, reach: f32) -> Vec { + let s = Map { w, h, v: alpha }; + match kind { + FieldKind::Outside => dist_outside(&s), + FieldKind::Inside => dist_inside(&s), + FieldKind::BevelOutside => bevel_dist_outside(&s, &sharp_edges(&s), reach), + FieldKind::BevelInside => bevel_dist_inside(&s, &sharp_edges(&s), reach), + FieldKind::StrokeOutside => dist_outside_by(&s, Metric::Chamfer), + FieldKind::ChokeInside => dist_outside_by(&s.map(|a| 1.0 - a), Metric::Chamfer), + FieldKind::StrokeInside => dist_inside_by(&s, Metric::Chamfer), + FieldKind::StrokeOutsideExact => dist_outside_by(&s, Metric::Euclidean), + FieldKind::StrokeOutsideVector => dist_outside_by(&local_coverage(&s), Metric::Euclidean), + FieldKind::StrokeOutsideVectorChamfer => dist_outside_by(&local_coverage(&s), Metric::Chamfer), + } +} + +/// Both chiselled bevel fields of `alpha`, `[BevelInside, BevelOutside]`: each is its +/// [`distance_field`], with the sharp edges they both start from found once. +pub fn bevel_distance_fields(alpha: Vec, w: usize, h: usize, reach: f32) -> [Vec; 2] { + bevel_dists(&Map { w, h, v: alpha }, reach) +} + +/// The inside and outside bevel distances of `s`, from one set of sharp edges. +pub(super) fn bevel_dists(s: &Map, reach: f32) -> [Vec; 2] { + let sharp = sharp_edges(s); + [bevel_dist_inside(s, &sharp, reach), bevel_dist_outside(s, &sharp, reach)] +} diff --git a/crates/compose/src/effects/paint.rs b/crates/compose/src/effects/paint.rs new file mode 100644 index 0000000000..9b17749049 --- /dev/null +++ b/crates/compose/src/effects/paint.rs @@ -0,0 +1,402 @@ +use super::blur::{blur, dilate}; +use super::distance::{dist_inside, dist_outside}; +use super::*; + +pub(super) fn contour_lut(c: &Contour) -> Option> { + match c { + Contour::Linear => None, + Contour::Custom { points, corners, .. } => Some(crate::adjust::contour_curve_lut(points, corners)), + } +} + +/// Satin's coverage transfer: the contour read from its far end, `|c(1 − v) − c(1)|`. Measured in +/// Photoshop 27.11: Cone and Cone − Inverted Satins are identical, and a Gaussian Satin runs under +/// the diagonal (0.36 at 0.5) while the same Gaussian on a glow or gloss runs over it (0.65). +/// `None` = identity. +pub fn satin_lut(c: &Contour) -> Option> { + let lut = contour_lut(c)?; + let end = lut.last().copied().unwrap_or(1.0); + Some(lut.iter().rev().map(|v| (v - end).abs()).collect()) +} + +/// Interpolated lookup in a 0..=1 table (as the GPU's `lut()`). +pub(super) fn lut_at(l: &[f32], v: f32) -> f32 { + let x = v.clamp(0.0, 1.0) * (l.len() - 1) as f32; + let i = x.floor() as usize; + let j = (i + 1).min(l.len() - 1); + l[i] + (l[j] - l[i]) * (x - i as f32) +} + +/// A glow's coverage transfer: its contour applied over the Range (Photoshop maps the glow's +/// coverage `v` through `contour(min(v / range, 1))`, so the default 50 % doubles a blurred +/// edge's 0.5 to full strength). `None` = identity. +pub fn glow_lut(g: &Glow) -> Option> { + ranged_lut(&g.contour, g.range) +} + +/// A contour applied over a Range (`contour(min(v / range, 1))`); `None` = identity. +pub fn ranged_lut(contour: &Contour, range: f32) -> Option> { + let base = contour_lut(contour); + let range = if range.is_finite() { range.clamp(0.01, 1.0) } else { 1.0 }; + if range >= 0.999 { + return base; + } + let n = 4096; + Some( + (0..n) + .map(|k| { + let v = (k as f32 / (n - 1) as f32 / range).min(1.0); + base.as_ref().map_or(v, |l| lut_at(l, v)) + }) + .collect(), + ) +} + +/// The bevel Contour element's height transfer: the contour alone. Unlike a glow's, its Range is +/// not a `v / range` stretch: that flattened a Linear contour at the default 50 % to a bevel half +/// as wide as Photoshop's (a real 18 px smooth inner bevel at 136 % depth: top-edge highlight gone +/// 15 px in, Photoshop's still 0.19 at 16 px), and dropping it lowers the bad pixels of every +/// contour oracle (bevel-inner-contour-ramp-peak 25.9 → 21.8 %, -double-ring-aa-r70 25.2 → 21.0 %, +/// bevel-pillow-chisel-hard-gloss-and-contour 11.4 → 7.2 %). What Range does instead is still open. +pub fn bevel_contour_lut(c: &photocraft_doc::BevelContour) -> Vec { + contour_lut(&c.contour).unwrap_or_else(|| (0..4096).map(|k| k as f32 / 4095.0).collect()) +} + +pub(super) fn apply_lut(m: Map, l: Option>) -> Map { + match l { + None => m, + Some(l) => m.map(|v| lut_at(&l, v)), + } +} + +/// Deterministic per-pixel value in 0..=1, hashed from document coordinates +/// (the same hash as the GPU's `dissolve_noise`), so the speckle is stable +/// across renders, frames and tiles. +pub fn hash_noise(x: i64, y: i64) -> f32 { + let mut h = (x as i32 as u32).wrapping_mul(0x8da6_b343) ^ (y as i32 as u32).wrapping_mul(0xd816_3841) ^ 0x9e37_79b9; + h ^= h >> 15; + h = h.wrapping_mul(0x2c1b_3c6d); + h ^= h >> 12; + (h & 0xffff) as f32 / 65536.0 +} + +/// Effect noise (Photoshop's Noise slider): monochrome speckle in the coverage, +/// applied after the contour. `amount` is 0..=1; 0 leaves the map untouched. The speckle is +/// scaled by the coverage, so it fades out with the effect instead of lighting up the blur's +/// near-zero tail out to the edge of its rectangular reach (#7833). +pub(super) fn noise(m: &mut Map, amount: f32, x0: i32, y0: i32) { + if !amount.is_finite() || amount <= 0.0 { + return; + } + for y in 0..m.h { + for x in 0..m.w { + let v = &mut m.v[y * m.w + x]; + if *v <= 0.0 { + continue; + } + let n = hash_noise(i64::from(x0 + x as i32), i64::from(y0 + y as i32)); + *v = (*v * (1.0 + (n - 0.5) * 2.0 * amount)).clamp(0.0, 1.0); + } + } +} + +fn apply_contour(m: Map, c: &Contour) -> Map { + match contour_lut(c) { + None => m, + Some(l) => m.map(|v| lut_at(&l, v)), + } +} + +pub(super) fn rgb(c: &photocraft_color::Color) -> [f32; 3] { + c.to_rgb() +} + +/// Offset of an effect lit from `angle` at `distance` (shadow falls away from +/// the light), rounded to whole pixels as Photoshop does. +pub(super) fn offset(angle: f32, distance: f32) -> (f32, f32) { + let a = angle.to_radians(); + ((-a.cos() * distance).round(), (a.sin() * distance).round()) +} + +/// The lengths a 100 % gradient at `angle` spans in a `w` × `h` frame: the chord (Linear and +/// Reflected) and the ellipse-norm length (Radial, Angle, Diamond; its half is the radius). +pub fn gradient_units(angle: f32, w: f32, h: f32) -> (f32, f32) { + let (s, c) = angle.to_radians().sin_cos(); + // Gradient length: the bounds' extent along the angle as an ellipse + // norm (a unit gradient scaled to the bounds); fitted on psd-tools + // gradient-styles.psd (cached Photoshop renderings of every style). + let len = ((c * w).powi(2) + (s * h).powi(2)).sqrt().max(1.0); + // Linear / Reflected span the chord of the bounds through their centre along the angle: + // min(w / |cos|, h / |sin|). A 45° gradient on a 29 px square runs 41 px (psd-tools + // shape-fx2), an 87° one on a 600 × 60 text line 60 px (layer_effects); axis-aligned angles + // span the width / height. + let chord = (w / c.abs().max(1e-6)).min(h / s.abs().max(1e-6)).max(1.0); + (chord, len) +} + +/// Gradient parameter `t` in `0..=1` for pixel centre `(x, y)` inside `bounds`. +#[allow(clippy::too_many_arguments)] +pub fn gradient_t(style: GradientStyle, angle: f32, scale: f32, reverse: bool, offset: (f32, f32), bounds: Rect, x: f32, y: f32) -> f32 { + let w = bounds.width().max(1) as f32; + let h = bounds.height().max(1) as f32; + let cx = bounds.x0 as f32 + w / 2.0 + offset.0 * w; + let cy = bounds.y0 as f32 + h / 2.0 + offset.1 * h; + let (s, c) = angle.to_radians().sin_cos(); + let (dx, dy) = (x - cx, y - cy); + // Distance along the gradient direction (y axis points down). + let along = dx * c - dy * s; + let across = dx * s + dy * c; + let (chord, len) = gradient_units(angle, w, h); + let (chord, len) = (chord * scale.max(1e-3), len * scale.max(1e-3)); + // Linear / Reflected sample the pixel's top-left corner, half a pixel before its centre + // (with the whole-pixel end points of `fill_layout`: layer_effects' overlay 5.8 → 1.8/255, + // shape-fx2 2.8 → 1.1/255, gradient-fill.psd 1.9 → 0.5/255). + let corner = 0.5 * (c - s); + let mut t = match style { + GradientStyle::Linear => (along - corner) / chord + 0.5, + GradientStyle::Reflected => ((along - corner) / (chord / 2.0)).abs(), + GradientStyle::Radial => (dx * dx + dy * dy).sqrt() / (len / 2.0), + GradientStyle::Diamond => (along.abs() + across.abs()) / (len / 2.0), + // Clockwise sweep starting at the gradient angle. + GradientStyle::Angle => ((angle.to_radians() - (-dy).atan2(dx)) / std::f32::consts::TAU).rem_euclid(1.0), + }; + t = t.clamp(0.0, 1.0); + if reverse { 1.0 - t } else { t } +} + +/// Samples colour and opacity stops at `t`. +pub fn sample_gradient(g: &Gradient, t: f32) -> [f32; 4] { + PreparedGradient::new(g).sample(t) +} + +// Prepared only for one paint call: CMYK conversions must use that call's active profile. +struct PreparedGradient { + color: Vec<(f32, [f32; 3])>, + opacity: Vec<(f32, [f32; 3])>, +} + +impl PreparedGradient { + fn new(g: &Gradient) -> Self { + Self { color: g.stops.iter().map(|(p, c)| (*p, rgb(c))).collect(), opacity: g.opacity_stops.iter().map(|(p, a)| (*p, [*a; 3])).collect() } + } + + fn sample(&self, t: f32) -> [f32; 4] { + let color = sample_stops(&self.color, t); + let alpha = if self.opacity.is_empty() { 1.0 } else { sample_stops(&self.opacity, t)[0] }; + [color[0], color[1], color[2], alpha] + } +} + +fn sample_stops(stops: &[(f32, [f32; 3])], t: f32) -> [f32; 3] { + match stops { + [] => [t; 3], + [s] => s.1, + _ => { + if t <= stops[0].0 { + return stops[0].1; + } + for w in stops.windows(2) { + if t <= w[1].0 { + let k = if w[1].0 > w[0].0 { (t - w[0].0) / (w[1].0 - w[0].0) } else { 0.0 }; + return std::array::from_fn(|i| w[0].1[i] + (w[1].1[i] - w[0].1[i]) * k); + } + } + stops[stops.len() - 1].1 + } + } +} + +/// Composite `color × coverage` into `dst` (both over the same rectangle). +fn paint(dst: &mut Buffer, m: &Map, color: impl Fn(usize) -> [f32; 4], blend: BlendMode, opacity: f32) { + let (x0, y0, w) = (i64::from(dst.rect.x0), i64::from(dst.rect.y0), (dst.rect.width().max(1)) as usize); + for (i, p) in dst.px.iter_mut().enumerate() { + let a = m.v[i] * opacity; + if a <= 0.0 { + continue; + } + let c = color(i); + if blend == BlendMode::Dissolve { + if dissolves_in(x0 + (i % w) as i64, y0 + (i / w) as i64, c[3] * a) { + *p = psblend::composite(BlendMode::Normal, *p, [c[0], c[1], c[2], 1.0], 1.0); + } + continue; + } + *p = psblend::composite(blend, *p, [c[0], c[1], c[2], c[3] * a], 1.0); + } +} + +/// Whether `e` paints anything in Dissolve mode. +pub(super) fn dissolves(e: &Effect) -> bool { + let d = |m: BlendMode| m == BlendMode::Dissolve; + match e { + Effect::DropShadow(s) | Effect::InnerShadow(s) => d(s.common.blend), + Effect::OuterGlow(g) | Effect::InnerGlow(g) => d(g.common.blend), + Effect::Stroke(s) => d(s.common.blend), + Effect::ColorOverlay { common, .. } | Effect::GradientOverlay { common, .. } | Effect::PatternOverlay { common, .. } => d(common.blend), + Effect::Satin(s) => d(s.common.blend), + Effect::BevelEmboss(b) => d(b.highlight.blend) || d(b.shadow.blend), + } +} + +/// Dissolve on an effect (#6995): a pixel takes the effect fully or not at all, with probability +/// `coverage`, picked by the same document-coordinate noise as a Dissolve layer. A soft glow or +/// shadow turns into scattered speckle instead of a smooth falloff. +pub(super) fn dissolves_in(x: i64, y: i64, coverage: f32) -> bool { + hash_noise(x, y) < coverage +} + +pub(super) fn paint_color(dst: &mut Buffer, m: &Map, c: [f32; 3], blend: BlendMode, opacity: f32) { + paint(dst, m, |_| [c[0], c[1], c[2], 1.0], blend, opacity); +} + +/// Spread / choke of a soft effect: (dilation radius, blur width). The dilation is whole pixels +/// (`size × spread` rounded: a 2 % spread of a 5 px shadow doesn't grow it at all), the blur +/// keeps `size × (1 − spread)` (ag-psd effects 10.6 → 3.8 % of pixels off). +pub fn spread_split(size: f32, spread: f32) -> (f32, f32) { + ((size * spread).round(), size * (1.0 - spread)) +} + +pub(super) fn shadow_map(shape: &Map, s: &Shadow, light: &GlobalLight, inner: bool, origin: (i32, i32)) -> Map { + let angle = if s.use_global_light { light.angle } else { s.angle }; + let (dx, dy) = offset(angle, s.distance); + let src = if inner { shape.clone().map(|a| 1.0 - a) } else { shape.clone() }; + let mut m = src.shifted(dx, dy, if inner { 1.0 } else { 0.0 }); + let (r, bw) = spread_split(s.size, s.spread); + m = dilate(&m, r); + blur(&mut m, bw); + let mut m = apply_contour(m, &s.contour); + noise(&mut m, s.noise, origin.0, origin.1); + if inner { + for (v, a) in m.v.iter_mut().zip(&shape.v) { + *v *= a; + } + } + m +} + +pub(super) fn glow_map(shape: &Map, g: &Glow, inner: bool, origin: (i32, i32)) -> Map { + // An inner glow is built from the edge inwards; a centre-source glow is its inverse, taken + // after the contour and Range (Photoshop 27.11, measured: the centre glow is exactly + // 1 − the edge glow, for both techniques). + let src = if inner { shape.clone().map(|a| 1.0 - a) } else { shape.clone() }; + let mut m = match g.technique { + GlowTechnique::Precise => { + // Coverage falls linearly from 0.5 at the edge to 0 at `size + 1` px (centre to + // centre), solid within the spread / choke: after the default 50 % Range that is + // Photoshop's 1 − D / (size + 1) beyond the solid part (measured: outer and inner, + // sizes 10 and 20, spread 0 and 40 %, choke 0 and 30 %: within 1 level; other Range + // values are unmeasured). The distances here are 0.5 px short of centre to centre. + let d = if inner { dist_inside(shape) } else { dist_outside(&src) }; + let solid = g.size * g.spread; + let soft = (g.size + 1.0 - solid).max(1e-3); + let mut m = Map::new(shape.w, shape.h, 0.0); + for (o, d) in m.v.iter_mut().zip(d) { + let d = d + 0.5; + *o = if d <= solid { 1.0 } else { 0.5 * (1.0 - (d - solid) / soft).clamp(0.0, 1.0) }; + } + m + } + GlowTechnique::Softer => { + let (r, bw) = spread_split(g.size, g.spread); + let mut m = dilate(&src, r); + blur(&mut m, bw); + m + } + }; + m = apply_lut(m, glow_lut(g)); + if inner && g.source == GlowSource::Center { + m = m.map(|v| 1.0 - v); + } + noise(&mut m, g.noise, origin.0, origin.1); + if inner { + for (v, a) in m.v.iter_mut().zip(&shape.v) { + *v *= a; + } + } + m +} + +/// Paints a pattern (looked up in `patterns`) through coverage `m`; missing patterns paint nothing. +#[allow(clippy::too_many_arguments)] +pub(super) fn paint_pattern( + dst: &mut Buffer, + m: &Map, + patterns: &PreparedPatterns<'_>, + name: &str, + id: &str, + place: Placement, + big: Rect, + blend: BlendMode, + opacity: f32, +) { + let Some(tile) = patterns.get(id, name) else { return }; + let w = big.width() as usize; + paint( + dst, + m, + |i| { + let (x, y) = (f64::from(big.x0 + (i % w) as i32) + 0.5, f64::from(big.y0 + (i / w) as i32) + 0.5); + let (u, v) = place.map(x, y); + tile.sample(u, v) + }, + blend, + opacity, + ); +} + +#[allow(clippy::too_many_arguments)] +pub(super) fn paint_fx( + dst: &mut Buffer, + m: &Map, + p: &FxPaint, + shape_bounds: Rect, + anchor: (f64, f64), + big: Rect, + blend: BlendMode, + opacity: f32, + patterns: &PreparedPatterns<'_>, +) { + match p { + FxPaint::Color(c) => paint_color(dst, m, rgb(c), blend, opacity), + FxPaint::Gradient(g) => { + let prepared = PreparedGradient::new(g); + let (angle, scale, offset) = crate::fill_layout::gradient_layout(g.style, g.angle, g.scale, g.offset, shape_bounds); + let w = big.width() as usize; + paint( + dst, + m, + |i| { + let (x, y) = ((big.x0 + (i % w) as i32) as f32 + 0.5, (big.y0 + (i / w) as i32) as f32 + 0.5); + prepared.sample(gradient_t(g.style, angle, scale, g.reverse, offset, shape_bounds, x, y)) + }, + blend, + opacity, + ) + } + FxPaint::Pattern { name, id, scale } => { + paint_pattern(dst, m, patterns, name, id, Placement::anchored(anchor, true, (0.0, 0.0), *scale, 0.0), big, blend, opacity) + } + } +} + +/// The opacity gain of a gradient glow: it is opaque from strength `range²` on (see [`paint_glow`]). +pub fn glow_gradient_gain(range: f32) -> f32 { + let r = if range.is_finite() { range.clamp(0.01, 1.0) } else { 1.0 }; + 1.0 / (r * r) +} + +/// A glow's paint over its map `m`. A gradient runs along the glow rather than across the +/// canvas: Photoshop colours the glow where its (ranged, contoured) strength is `v` with the +/// gradient at `1 - v`, so the first stop hugs the edge, and the glow is opaque from `v = range²` +/// on (photoshop corpus outer-glow-gradient.psd: 1.4/255 mean, against bands across the canvas; +/// psd-tools layer_params.psd). Glows have no gradient angle, style or Reverse. +#[allow(clippy::too_many_arguments)] +pub(super) fn paint_glow(dst: &mut Buffer, m: &Map, g: &Glow, shape_bounds: Rect, anchor: (f64, f64), big: Rect, patterns: &PreparedPatterns<'_>) { + let FxPaint::Gradient(gradient) = &g.paint else { + return paint_fx(dst, m, &g.paint, shape_bounds, anchor, big, g.common.blend, g.common.opacity, patterns); + }; + let prepared = PreparedGradient::new(gradient); + let gain = glow_gradient_gain(g.range); + let strength = Map { w: m.w, h: m.h, v: m.v.iter().map(|v| (v * gain).min(1.0)).collect() }; + paint(dst, &strength, |i| prepared.sample(1.0 - m.v.get(i).copied().unwrap_or(0.0).clamp(0.0, 1.0)), g.common.blend, g.common.opacity); +} diff --git a/crates/compose/src/effects/tests.rs b/crates/compose/src/effects/tests.rs new file mode 100644 index 0000000000..4aea00004f --- /dev/null +++ b/crates/compose/src/effects/tests.rs @@ -0,0 +1,1049 @@ +use super::*; + +/// Runs `f` with every parallel pass on this thread using `n` threads (1 = in order), whatever its size. +fn with_threads(n: usize, f: impl FnOnce() -> R) -> R { + struct Restore(Option); + impl Drop for Restore { + fn drop(&mut self) { + THREADS.with(|t| t.set(self.0)); + } + } + let _restore = Restore(THREADS.with(|t| t.replace(Some(n)))); + f() +} + +fn bits(v: &[f32]) -> Vec { + v.iter().map(|x| x.to_bits()).collect() +} + +#[test] +fn edt_is_exact() { + let (w, h) = (7, 5); + let mut inside = vec![false; w * h]; + inside[2 * w + 3] = true; + let d = edt(&inside, w, h); + assert_eq!(d[2 * w + 3], 0.0); + assert!((d[2 * w + 6] - 3.0).abs() < 1e-6); + assert!((d[0] - (9.0f32 + 4.0).sqrt()).abs() < 1e-5); + assert!((d[4 * w + 5] - (4.0f32 + 4.0).sqrt()).abs() < 1e-5); +} + +#[test] +fn edt_two_seeds() { + let (w, h) = (10, 1); + let mut inside = vec![false; w]; + inside[0] = true; + inside[9] = true; + let d = edt(&inside, w, h); + assert_eq!(d, vec![0.0, 1.0, 2.0, 3.0, 4.0, 4.0, 3.0, 2.0, 1.0, 0.0]); +} + +#[test] +fn blur_preserves_mass() { + let mut m = Map::new(21, 21, 0.0); + m.v[10 * 21 + 10] = 1.0; + blur(&mut m, 6.0); + let sum: f32 = m.v.iter().sum(); + assert!((sum - 1.0).abs() < 1e-4, "{sum}"); + assert!(m.v[10 * 21 + 10] < 1.0); +} + +#[test] +fn gradient_geometry() { + let b = Rect::new(0, 0, 100, 100); + let t = |s, x, y| gradient_t(s, 0.0, 1.0, false, (0.0, 0.0), b, x, y); + assert!(t(GradientStyle::Linear, 0.0, 50.0) < 0.01); + // Linear / reflected sample pixel corners: the centre is reached half a pixel later. + assert!((t(GradientStyle::Linear, 50.5, 50.0) - 0.5).abs() < 1e-6); + assert!(t(GradientStyle::Linear, 100.0, 50.0) > 0.99); + assert!(t(GradientStyle::Reflected, 50.5, 50.0) < 1e-6); + assert!((t(GradientStyle::Reflected, 0.0, 50.0) - 1.0).abs() < 1e-6); + assert!(t(GradientStyle::Radial, 50.0, 50.0) < 1e-6); + assert!((t(GradientStyle::Radial, 50.0, 0.0) - 1.0).abs() < 1e-6); + assert!((t(GradientStyle::Diamond, 75.0, 75.0) - 1.0).abs() < 1e-6); + let ang = t(GradientStyle::Angle, 50.0, 0.0); + assert!((ang - 0.75).abs() < 1e-3, "{ang}"); + let rev = gradient_t(GradientStyle::Linear, 0.0, 1.0, true, (0.0, 0.0), b, 0.0, 50.0); + assert!(rev > 0.99); +} + +#[test] +fn effect_gradients_snap_end_points_and_sample_corners() { + // 87° over 600 × 60 at (99, 422): end points (397, 482) and (400, 422), so the overlay runs + // along (3, -60) from its midpoint (398.5, 452), sampled at pixel corners. + let frame = Rect::new(99, 422, 699, 482); + let (a, sc, o) = crate::fill_layout::gradient_layout(GradientStyle::Linear, 87.0, 1.0, (0.0, 0.0), frame); + assert!((a - (60f32).atan2(3.0).to_degrees()).abs() < 1e-3, "{a}"); + let t = |x: f32, y: f32| gradient_t(GradientStyle::Linear, a, sc, false, o, frame, x, y); + assert!((t(399.0, 452.5) - 0.5).abs() < 1e-4, "{}", t(399.0, 452.5)); + assert!(t(400.5, 422.5) > 0.99 && t(397.5, 482.5) < 0.01); +} + +#[test] +fn chamfer_uses_euclidean_step_lengths() { + let (w, h) = (9, 9); + let mut inside = vec![false; w * h]; + inside[0] = true; + let (d, near) = chamfer_nearest(&inside, w, h); + let at = |x: usize, y: usize| d[y * w + x]; + assert!((at(3, 0) - 3.0).abs() < 1e-5); + assert!((at(2, 2) - 2.0 * std::f32::consts::SQRT_2).abs() < 1e-5); + assert!((at(1, 2) - 5f32.sqrt()).abs() < 1e-5); + assert!((at(1, 3) - (5f32.sqrt() + 1.0)).abs() < 1e-5, "knight + straight, not √10"); + assert!((at(2, 3) - (5f32.sqrt() + std::f32::consts::SQRT_2)).abs() < 1e-5); + assert!(near.iter().all(|&n| n == 0)); +} + +#[test] +fn spread_dilates_with_the_chamfer_metric() { + // One opaque pixel grown by 3 px: at offset (1, 3) the chamfer distance is √5 + 1 = 3.236 + // (Euclidean 3.162), so the anti-aliased rim keeps 3 + 0.5 − (3.236 − 0.5) = 0.764. + let mut m = Map::new(9, 9, 0.0); + m.v[4 * 9 + 4] = 1.0; + let d = dilate(&m, 3.0); + assert!((d.v[7 * 9 + 5] - 0.764).abs() < 1e-3, "{}", d.v[7 * 9 + 5]); + // (2, 3): √5 + √2 = 3.650 (Euclidean 3.606) leaves 0.350; axis steps are exact. + assert!((d.v[7 * 9 + 6] - (4.0 - 5f32.sqrt() - std::f32::consts::SQRT_2)).abs() < 1e-4, "{}", d.v[7 * 9 + 6]); + assert_eq!(d.v[4 * 9 + 7], 1.0); +} + +#[test] +fn running_sum_tent_matches_the_kernel() { + let (w, h) = (37usize, 23usize); + let src: Vec = (0..w * h).map(|i| ((i * 7919) % 101) as f32 / 100.0).collect(); + for width in [1.0f32, 2.0, 3.5, 5.0, 8.25, 41.0] { + let mut m = Map { w, h, v: src.clone() }; + tent(&mut m, width); + let mut want = Map { w, h, v: src.clone() }; + tent_direct(&mut want, width); + for (a, b) in m.v.iter().zip(&want.v) { + assert!((a - b).abs() < 1e-5, "width {width}: {a} vs {b}"); + } + } +} + +#[test] +fn tent_kernel_is_two_boxes() { + let (r, k) = tent_kernel(5.0); + assert_eq!(r, 4); + let sum: f32 = k.iter().sum(); + assert!((sum - 1.0).abs() < 1e-6); + assert!((k[4] - 5.0 / 25.0).abs() < 1e-6 && (k[0] - 1.0 / 25.0).abs() < 1e-6); + // Fractional widths taper the end taps; width 1 is the identity. + let (r, k) = tent_kernel(4.0); + assert_eq!(r, 4); + assert!(k[0] > 0.0 && k[0] < 1.0 / 25.0); + assert_eq!(tent_kernel(1.0), (0, vec![1.0])); + // #1543: a huge, infinite or NaN width is capped, not turned into a kernel of 2^62 taps. + for w in [1e30, f32::INFINITY, f32::MAX] { + assert_eq!(tent_kernel(w), tent_kernel(MAX_REACH), "{w}"); + } + assert_eq!(tent_kernel(f32::NAN), (0, vec![1.0])); +} + +fn no_tex() -> TextureCtx<'static> { + TextureCtx { rect: Rect::new(0, 0, 1, 1), patterns: &[], anchor: (0.0, 0.0) } +} + +fn square(n: usize, x0: usize, x1: usize) -> Map { + let mut m = Map::new(n, n, 0.0); + for y in x0..x1 { + for x in x0..x1 { + m.v[y * n + x] = 1.0; + } + } + m +} + +fn bevel_of(style: BevelStyle, technique: BevelTechnique) -> Bevel { + Bevel { + enabled: true, + style, + technique, + depth: 1.0, + up: true, + size: 5.0, + soften: 0.0, + angle: 90.0, + altitude: 30.0, + use_global_light: false, + gloss_contour: Contour::Linear, + gloss_anti_alias: false, + highlight: photocraft_doc::FxCommon::new(BlendMode::Screen, 0.75), + highlight_color: photocraft_color::Color::WHITE, + shadow: photocraft_doc::FxCommon::new(BlendMode::Multiply, 0.75), + shadow_color: photocraft_color::Color::BLACK, + contour: None, + texture: None, + } +} + +#[test] +fn smooth_inner_bevel_lights_the_top_edge_inside_only() { + let shape = square(40, 10, 30); + let (maps, paint) = bevel_maps( + &shape, + &bevel_of(BevelStyle::InnerBevel, BevelTechnique::Smooth), + &GlobalLight::default(), + &no_tex(), + &PreparedPatterns::new(&[], PREPARED_PATTERN_BYTES), + ); + assert_eq!(paint, BevelPaint::Inner); + let at = |m: &Map, x: usize, y: usize| m.v[y * 40 + x]; + // Light from the top: highlight along the top edge, shadow along the bottom, flat middle. + assert!(at(&maps[0], 20, 10) > 0.5 && at(&maps[1], 20, 10) == 0.0); + assert!(at(&maps[1], 20, 29) > 0.5); + assert!(at(&maps[0], 20, 20) < 1e-3 && at(&maps[1], 20, 20) < 1e-3); + // Nothing outside the shape; the ramp reaches about `size` inside. + assert_eq!(at(&maps[0], 20, 8), 0.0); + assert!(at(&maps[0], 20, 15) < 0.05); +} + +/// Photoshop 27.11, measured across a straight edge (size 10, depth 100 %, light from the top +/// at 30°): a chisel facet has the slope `depth × size / (2 (size + 1))`, flat right up to the +/// edge pixel for Inner Hard; Inner Soft's edge pixel is half as steep again; Outer Hard +/// still shades, partly, the pixel where its ramp reaches zero `size + 1½` px out. +#[test] +fn chisel_facets_match_photoshop() { + let amount = |g: f32| { + let (se, ce) = 30f32.to_radians().sin_cos(); + ((g * ce + se) / (1.0 + g * g).sqrt() - se) / (1.0 - se) + }; + let n = 80; + let shape = square(n, 20, 60); + let maps = |style, technique| { + let mut b = bevel_of(style, technique); + b.size = 10.0; + bevel_maps(&shape, &b, &GlobalLight::default(), &no_tex(), &PreparedPatterns::new(&[], PREPARED_PATTERN_BYTES)).0 + }; + let at = |m: &Map, y: usize| m.v[y * n + 40]; + let facet = amount(10.0 / 22.0); + let hard = maps(BevelStyle::InnerBevel, BevelTechnique::ChiselHard); + for y in 20..30 { + assert!((at(&hard[0], y) - facet).abs() < 0.01, "inner hard facet at row {y}: {} vs {facet}", at(&hard[0], y)); + } + assert!(at(&hard[0], 30) > 0.05 && at(&hard[0], 30) < facet, "one partial pixel at the end"); + let soft = maps(BevelStyle::InnerBevel, BevelTechnique::ChiselSoft); + assert!((at(&soft[0], 20) - amount(1.5 * 10.0 / 22.0)).abs() < 0.01, "steeper edge pixel: {}", at(&soft[0], 20)); + assert!((at(&soft[0], 24) - facet).abs() < 0.01, "then Chisel Hard's facet"); + let outer = maps(BevelStyle::OuterBevel, BevelTechnique::ChiselHard); + // Below the shape (rows 60..): shadow facet through 10½ px, partial at 11½. + assert!((at(&outer[1], 70) - at(&outer[1], 61)).abs() < 1e-4); + assert!(at(&outer[1], 71) > 0.05 && at(&outer[1], 71) < at(&outer[1], 70)); + assert_eq!(at(&outer[1], 72), 0.0); +} + +#[test] +fn emboss_paints_both_sides_and_pillow_flips_the_outside() { + let shape = square(40, 10, 30); + let l = GlobalLight::default(); + let (e, paint) = + bevel_maps(&shape, &bevel_of(BevelStyle::Emboss, BevelTechnique::Smooth), &l, &no_tex(), &PreparedPatterns::new(&[], PREPARED_PATTERN_BYTES)); + assert_eq!((paint, e.len()), (BevelPaint::Both, 2)); + let at = |m: &Map, x: usize, y: usize| m.v[y * 40 + x]; + // Emboss: the slope across the top edge faces the light on both sides. + assert!(at(&e[0], 20, 10) > 0.3 && at(&e[0], 20, 9) > 0.3); + let (p, _) = + bevel_maps(&shape, &bevel_of(BevelStyle::PillowEmboss, BevelTechnique::Smooth), &l, &no_tex(), &PreparedPatterns::new(&[], PREPARED_PATTERN_BYTES)); + assert!(at(&p[0], 20, 10) > 0.3 && at(&p[1], 20, 9) > 0.3, "pillow: outside top edge in shadow"); +} + +#[test] +fn emboss_width_rounds_up_and_shades_past_the_blur() { + let mut b = bevel_of(BevelStyle::Emboss, BevelTechnique::Smooth); + b.size = 41.0; + let g = bevel_geom(&b); + assert_eq!((g.width, g.depth), (21.0, 21.0)); + b.size = 5.0; + assert_eq!(bevel_geom(&b).width, 3.0); + // The first row past the height blur's reach still slopes (its upper neighbour is raised), + // so it shades; the row after it does not. + let shape = square(60, 20, 40); + b.size = 9.0; + b.angle = 90.0; + let (m, _) = bevel_maps(&shape, &b, &GlobalLight::default(), &no_tex(), &PreparedPatterns::new(&[], PREPARED_PATTERN_BYTES)); + let reach = tent_kernel(bevel_geom(&b).width).0 as usize; + let row = 39 + reach + 1; // last shape row + reach + 1: height 0, neighbour above raised + assert!(m[1].v[row * 60 + 30] > 0.0, "{}", m[1].v[row * 60 + 30]); + assert_eq!(m[1].v[(row + 1) * 60 + 30], 0.0); +} + +/// A `len` x `wid` bar through the middle of a `w` x `h` map at `deg` degrees, anti-aliased by +/// 16 x 16 supersampling (the coverage a scanline rasteriser gives). +fn aa_bar(w: usize, h: usize, deg: f32, len: f32, wid: f32) -> Map { + let (sn, cs) = deg.to_radians().sin_cos(); + let (cx, cy) = (w as f32 / 2.0, h as f32 / 2.0); + let mut m = Map::new(w, h, 0.0); + const N: usize = 16; + for y in 0..h { + for x in 0..w { + let mut hit = 0; + for sy in 0..N { + for sx in 0..N { + let (px, py) = (x as f32 + (sx as f32 + 0.5) / N as f32 - cx, y as f32 + (sy as f32 + 0.5) / N as f32 - cy); + let (u, v) = (px * cs + py * sn, -px * sn + py * cs); + hit += usize::from(u.abs() <= len / 2.0 && v.abs() <= wid / 2.0); + } + } + m.v[y * w + x] = hit as f32 / (N * N) as f32; + } + } + m +} + +/// Ripple and bias of a distance field on an `aa_bar` (`inside` or outside it): the worst +/// standard deviation of the error among pixels at the same true distance from a long edge +/// (0.5 px bins, 0.6..8 px, away from the ends), and the worst mean error of a bin. A constant +/// offset is no ripple: only a field that varies along the edge shades in stripes. +fn bar_ripple(f: &[f32], w: usize, h: usize, deg: f32, wid: f32, inside: bool) -> (f32, f32) { + let (sn, cs) = deg.to_radians().sin_cos(); + let mut bins: Vec> = vec![Vec::new(); 16]; + for y in 0..h { + for x in 0..w { + let (px, py) = (x as f32 + 0.5 - w as f32 / 2.0, y as f32 + 0.5 - h as f32 / 2.0); + let (u, v) = (px * cs + py * sn, -px * sn + py * cs); + let truth = if inside { wid / 2.0 - v.abs() } else { v.abs() - wid / 2.0 }; + if u.abs() < 40.0 && (0.6..8.0).contains(&truth) { + bins[(truth * 2.0) as usize].push(f[y * w + x] - truth); + } + } + } + let (mut ripple, mut bias) = (0.0f32, 0.0f32); + for b in bins.iter().filter(|b| b.len() > 8) { + let mean = b.iter().sum::() / b.len() as f32; + let sd = (b.iter().map(|e| (e - mean) * (e - mean)).sum::() / b.len() as f32).sqrt(); + ripple = ripple.max(sd); + bias = bias.max(mean.abs()); + } + (ripple, bias) +} + +/// The worst standard deviation of the chisel shading (highlight minus shadow) along lines +/// parallel to an `aa_bar` 2..6 px in from its edges, the way Issue #1926 measured stripes. +fn bar_shade_ripple(deg: f32, light: f32) -> f32 { + let (w, h) = (220usize, 220usize); + let bar = aa_bar(w, h, deg, 150.0, 16.0); + let mut b = bevel_of(BevelStyle::InnerBevel, BevelTechnique::ChiselHard); + (b.size, b.depth, b.angle, b.altitude) = (8.0, 2.2, light, 32.0); + let (m, _) = bevel_maps(&bar, &b, &GlobalLight::default(), &no_tex(), &PreparedPatterns::new(&[], PREPARED_PATTERN_BYTES)); + let (sn, cs) = deg.to_radians().sin_cos(); + let mut worst = 0.0f32; + for o in [-6.0f32, -5.0, -4.0, -3.0, -2.0, 2.0, 3.0, 4.0, 5.0, 6.0] { + let line: Vec = (-60..=60) + .map(|k| { + let t = k as f32 * 0.5; + let (x, y) = (w as f32 / 2.0 + t * cs - o * sn, h as f32 / 2.0 + t * sn + o * cs); + let i = y.floor() as usize * w + x.floor() as usize; + m[0].v[i] - m[1].v[i] + }) + .collect(); + let mean = line.iter().sum::() / line.len() as f32; + worst = worst.max((line.iter().map(|v| (v - mean) * (v - mean)).sum::() / line.len() as f32).sqrt()); + } + worst +} + +/// Coverage of a unit pixel by the half plane `n . p + s >= 0` (`p` from the pixel's centre), +/// by 64 x 64 supersampling. +fn half_plane_coverage(n: [f32; 2], s: f32) -> f32 { + const N: usize = 64; + let mut hit = 0; + for y in 0..N { + for x in 0..N { + let (px, py) = ((x as f32 + 0.5) / N as f32 - 0.5, (y as f32 + 0.5) / N as f32 - 0.5); + hit += usize::from(n[0] * px + n[1] * py + s >= 0.0); + } + } + hit as f32 / (N * N) as f32 +} + +#[test] +fn edge_offset_places_a_straight_edge_by_its_coverage() { + for step in 0..=12 { + let (sn, cs) = (step as f32 * 7.5).to_radians().sin_cos(); + for k in -12..=12 { + let s = k as f32 * 0.05; + let a = half_plane_coverage([cs, sn], s); + // Where the edge only just touches the pixel the coverage hardly moves with it. + if !(0.03..=0.97).contains(&a) { + continue; + } + let got = edge_offset([cs, sn], a); + assert!((got - s).abs() < 0.03, "{}deg s {s}: coverage {a} gave {got}", step as f32 * 7.5); + } + } + // Axis-aligned edges keep `alpha - 1/2`; a pixel no coverage says anything about is 0. + assert!((edge_offset([1.0, 0.0], 0.25) + 0.25).abs() < 1e-6); + assert!((edge_offset([0.0, 1.0], 0.9) - 0.4).abs() < 1e-6); + assert_eq!(edge_offset([0.6, 0.8], f32::NAN), 0.0); +} + +#[test] +fn bevel_distances_equal_the_plain_ones_without_anti_aliasing() { + // Hard edges (no partly covered pixel) and soft ramps (no sharp one) keep the plain fields. + let (w, h) = (96usize, 80usize); + let mut maps = Vec::new(); + for kind in 0..4 { + let mut m = Map::new(w, h, 0.0); + let mut seed = 12345u32; + for y in 0..h { + for x in 0..w { + let (dx, dy) = (x as f32 - 48.0, y as f32 - 40.0); + m.v[y * w + x] = match kind { + 0 => f32::from((50.0..90.0).contains(&(x as f32 * 0.6 + y as f32))), + 1 => f32::from(dx * dx + dy * dy < 30.0 * 30.0), + 2 => { + seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + f32::from(seed >> 28 < 5 && x > 10 && x < 80) + } + _ => ((20.0 - (dx * dx + dy * dy).sqrt()) / 8.0).clamp(0.0, 1.0), + }; + } + } + maps.push(m); + } + for (i, m) in maps.iter().enumerate() { + let sharp = sharp_edges(m); + assert!(sharp.is_empty(), "map {i} has no anti-aliased edge"); + assert_eq!(bevel_dist_inside(m, &sharp, 1e9), dist_inside(m), "inside, map {i}"); + assert_eq!(bevel_dist_outside(m, &sharp, 1e9), dist_outside(m), "outside, map {i}"); + } +} + +#[test] +fn chisel_distance_has_no_ripple_along_oblique_edges() { + // The plain distance to a pixel's centre ripples with the staircase of an oblique edge (the + // stripes of Issue #1926); at 0 and 45 degrees the staircase is regular and it does not. + let (w, h) = (160, 160); + for deg in [0.0f32, 30.0, 45.0, 60.0, 75.0, 120.0, 150.0] { + let bar = aa_bar(w, h, deg, 120.0, 40.0); + let sharp = sharp_edges(&bar); + let inside = bar_ripple(&bevel_dist_inside(&bar, &sharp, 40.0), w, h, deg, 40.0, true); + let outside = bar_ripple(&bevel_dist_outside(&bar, &sharp, 40.0), w, h, deg, 40.0, false); + for (what, (ripple, bias)) in [("inside", inside), ("outside", outside)] { + assert!(ripple < 0.008 && bias < 0.01, "{deg} deg {what}: ripple {ripple}, bias {bias}"); + } + } + let plain = aa_bar(w, h, 60.0, 120.0, 40.0); + let (ripple, _) = bar_ripple(&dist_inside(&plain), w, h, 60.0, 40.0, true); + assert!(ripple > 0.1, "the plain field still ripples ({ripple}), so the test above means something"); +} + +#[test] +fn edge_normals_follow_straight_edges_to_a_fraction_of_a_degree() { + // The 3x3 gradient is 1-3 degrees off and the error is systematic; the line through the edge + // points of the pixels around one is not. + let (w, h, wid) = (160usize, 160usize, 40.0f32); + for deg in [30.0f32, 60.0, 75.0, 120.0, 150.0] { + let sharp = sharp_edges(&aa_bar(w, h, deg, 120.0, wid)); + let (sn, cs) = deg.to_radians().sin_cos(); + let (mut worst, mut seen) = (0.0f32, 0); + for (i, e) in sharp.iter() { + let (px, py) = ((i % w) as f32 + 0.5 - w as f32 / 2.0, (i / w) as f32 + 0.5 - h as f32 / 2.0); + let (u, v) = (px * cs + py * sn, -px * sn + py * cs); + if u.abs() > 40.0 || (wid / 2.0 - v.abs()).abs() > 1.5 { + continue; + } + let into = if v > 0.0 { [sn, -cs] } else { [-sn, cs] }; + worst = worst.max((e.normal[0] * into[0] + e.normal[1] * into[1]).clamp(-1.0, 1.0).acos().to_degrees()); + seen += 1; + } + assert!(seen > 100 && worst < 0.6, "{deg} deg: {seen} edge pixels, normal off by up to {worst} deg"); + } +} + +#[test] +fn chisel_distance_is_close_on_round_shapes() { + // Circles (a hard stretch of edge at each pole, where the edge lies on a pixel boundary) and + // rounded rectangles on whole pixels (straight hard edges joined to anti-aliased arcs): the + // distance to the sharp pixels alone is up to 0.3 px too long there, so the plain distance + // caps it. Errors are against the exact distance to the shape, 0.6..8 px from its edge. + let worst = |f: &[f32], w: usize, h: usize, sdf: &dyn Fn(f32, f32) -> f32, inside: bool| { + let mut mx = 0.0f32; + for y in 0..h { + for x in 0..w { + let t = sdf(x as f32 + 0.5, y as f32 + 0.5); + let truth = if inside { -t } else { t }; + if (0.6..8.0).contains(&truth) { + mx = mx.max((f[y * w + x] - truth).abs()); + } + } + } + mx + }; + for r in [20.0f32, 40.0, 70.0] { + let (w, h) = (200usize, 200usize); + let m = aa_disc(w, h, r); + let sharp = sharp_edges(&m); + let sdf = |x: f32, y: f32| (x - 100.0).hypot(y - 100.0) - r; + let (i, o) = (worst(&bevel_dist_inside(&m, &sharp, 12.0), w, h, &sdf, true), worst(&bevel_dist_outside(&m, &sharp, 12.0), w, h, &sdf, false)); + assert!(i < 0.05 && o < 0.07, "disc {r}: inside off by {i}, outside by {o}"); + } + for rad in [6.0f32, 12.0, 24.0] { + let (w, h) = (200usize, 160usize); + let m = aa_round_rect(w, h, 20.0, 20.0, 180.0, 140.0, rad); + let sharp = sharp_edges(&m); + let sdf = |x: f32, y: f32| { + let (qx, qy) = ((x - 100.0).abs() - (80.0 - rad), (y - 80.0).abs() - (60.0 - rad)); + qx.max(0.0).hypot(qy.max(0.0)) + qx.max(qy).min(0.0) - rad + }; + let (i, o) = (worst(&bevel_dist_inside(&m, &sharp, 12.0), w, h, &sdf, true), worst(&bevel_dist_outside(&m, &sharp, 12.0), w, h, &sdf, false)); + assert!(i < 0.08 && o < 0.2, "rounded rect, radius {rad}: inside off by {i}, outside by {o}"); + } +} + +#[test] +fn chisel_facets_are_flat_along_oblique_edges() { + // Issue #1926: the facets of a chiselled bar at 30, 60, 120, 150 degrees were striped. + for deg in [0.0f32, 30.0, 45.0, 60.0, 75.0, 120.0, 150.0] { + for light in [-90.0f32, 0.0, 45.0, 120.0] { + let ripple = bar_shade_ripple(deg, light); + assert!(ripple < 0.03, "{deg} deg bar, light {light}: shading ripple {ripple}"); + } + } +} + +#[test] +fn bevel_distances_survive_degenerate_maps() { + let cases: [(usize, usize, f32); 7] = [(0, 0, 0.0), (1, 1, 0.5), (1, 1, 1.0), (2, 2, 0.5), (3, 1, 0.3), (5, 5, f32::NAN), (4, 4, 1.0)]; + for (w, h, a) in cases { + let m = Map::new(w, h, a); + let sharp = sharp_edges(&m); + for reach in [0.0, 8.0, f32::NAN, f32::INFINITY, -3.0] { + assert_eq!(bevel_dist_inside(&m, &sharp, reach).len(), w * h); + assert_eq!(bevel_dist_outside(&m, &sharp, reach).len(), w * h); + } + } + // A single partly covered pixel in an empty map, and an edge on the map's border. + let mut m = Map::new(5, 5, 0.0); + m.v[12] = 0.4; + let _ = (bevel_dist_inside(&m, &sharp_edges(&m), 4.0), bevel_dist_outside(&m, &sharp_edges(&m), 4.0)); + let mut m = Map::new(8, 8, 0.0); + for y in 0..8 { + m.v[y * 8 + 7] = 1.0; + m.v[y * 8 + 6] = 0.5; + } + let _ = (bevel_dist_inside(&m, &sharp_edges(&m), 4.0), bevel_dist_outside(&m, &sharp_edges(&m), 4.0)); +} + +#[test] +fn par_units_visits_every_unit_once_with_its_own_slices() { + // Lengths that leave a short last unit, no second slice, units of different sizes, and nothing at all. + let cases: [(usize, usize, usize, usize); 8] = + [(0, 3, 0, 0), (1, 1, 1, 1), (10, 3, 0, 0), (64, 8, 64, 8), (65, 8, 13, 1), (200, 1, 200, 1), (7, 7, 14, 2), (9, 4, 0, 5)]; + for (la, ua, lb, ub) in cases { + for threads in [1, 2, 3, 8, 64] { + let (mut a, mut b) = (vec![0u32; la], vec![0u32; lb]); + let calls = std::sync::atomic::AtomicUsize::new(0); + with_threads(threads, || { + par_units( + la, + &mut a, + ua, + &mut b, + ub, + || (), + |_, u, sa, sb| { + calls.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + assert!(sa.len() <= ua && sb.len() <= ub); + for (k, v) in sa.iter_mut().enumerate() { + *v = (u * ua + k) as u32 + 1; + } + for (k, v) in sb.iter_mut().enumerate() { + *v = (u * ub + k) as u32 + 1; + } + }, + ); + }); + assert_eq!(calls.into_inner(), la.div_ceil(ua), "{la} {ua} {lb} {ub} on {threads}"); + assert!(a.iter().enumerate().all(|(i, &v)| v == i as u32 + 1), "a: {la} {ua} {lb} {ub} on {threads}"); + // `b` is written for the units that exist in `a` and no further. + let written = (la.div_ceil(ua) * ub).min(lb); + assert!(b.iter().enumerate().all(|(i, &v)| v == if i < written { i as u32 + 1 } else { 0 }), "b: {la} {ua} {lb} {ub} on {threads}"); + } + } + // A unit size of 0 does nothing. + let mut a = vec![1u8; 4]; + par_units(4, &mut a, 0, &mut [] as &mut [()], 0, || (), |_, _, _, _| panic!("no units")); +} + +#[test] +fn nearest_distances_do_not_depend_on_the_threads() { + // Sizes that do not divide into the thread groups, lines of 1 pixel, and a noisy map where + // many pixels are equally far from two seeds (the nearest one must resolve the same way). + for (w, h) in [(37usize, 23usize), (1, 40), (40, 1), (2, 2), (101, 3), (64, 64)] { + let mut seed = 7u32; + let inside: Vec = (0..w * h) + .map(|_| { + seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + (seed >> 24).is_multiple_of(11) + }) + .collect(); + let (d1, n1) = with_threads(1, || edt_nearest(&inside, w, h)); + for threads in [2, 3, 8] { + let (d, n) = with_threads(threads, || edt_nearest(&inside, w, h)); + assert_eq!((bits(&d), n), (bits(&d1), n1.clone()), "{w}x{h} on {threads} threads"); + } + // And the nearest pixel is a seed at exactly that distance. + for (i, (&d, &q)) in d1.iter().zip(&n1).enumerate() { + if inside.iter().any(|&b| b) { + let (dx, dy) = ((i % w) as f32 - (q as usize % w) as f32, (i / w) as f32 - (q as usize / w) as f32); + assert!(inside[q as usize] && (dx.hypot(dy) - d).abs() < 1e-3, "{w}x{h} at {i}: {d} vs seed {q}"); + } + } + } +} + +#[test] +fn nearest_distances_survive_degenerate_sizes() { + // The slice does not match the size, or there is nothing: no panic, and a result per input pixel. + for (len, w, h) in [(0usize, 0usize, 0usize), (0, 5, 0), (0, 0, 5), (6, 2, 2), (6, 4, 2), (1, 0, 1)] { + let (d, n) = edt_nearest(&vec![true; len], w, h); + assert_eq!((d.len(), n.len()), (len, len), "{len} px as {w}x{h}"); + } +} + +#[test] +fn chisel_fields_do_not_depend_on_the_threads() { + // Edge pixels at every angle, curves, patchy opacity and an edge along the border, on sizes that + // leave short last groups; one thread (in order) is the reference. + let mut maps = vec![ + aa_disc(97, 83, 30.0), + aa_round_rect(131, 77, 9.0, 11.0, 120.0, 66.0, 14.0), + aa_bar(120, 120, 33.0, 100.0, 30.0), + aa_bar(90, 130, 60.0, 150.0, 25.0), + ]; + let mut patchy = aa_disc(101, 101, 40.0); + for (i, v) in patchy.v.iter_mut().enumerate() { + if (i % 101 / 13 + i / 101 / 17) % 5 == 0 { + *v *= 0.6; + } + } + maps.push(patchy); + maps.push(aa_bar(64, 64, 40.0, 220.0, 30.0)); + for (k, m) in maps.iter().enumerate() { + for reach in [3.0f32, 12.0] { + let one = with_threads(1, || (sharp_edges(m), distance_field_of(m, reach))); + for threads in [2, 5, 16] { + let many = with_threads(threads, || (sharp_edges(m), distance_field_of(m, reach))); + assert_eq!(one.0.slot, many.0.slot, "map {k} sharp slots on {threads} threads"); + let edges = |s: &SharpEdges| { + s.pixels.iter().map(|p| (p.at, p.cov.to_bits(), p.edge.offset.to_bits(), p.edge.normal.map(f32::to_bits))).collect::>() + }; + assert_eq!(edges(&one.0), edges(&many.0), "map {k} sharp edges on {threads} threads"); + for (a, b) in one.1.iter().zip(&many.1) { + assert_eq!(bits(a), bits(b), "map {k}, reach {reach} on {threads} threads"); + } + } + } + } +} + +#[test] +fn bevel_maps_do_not_depend_on_the_threads() { + // Every style and technique, softened or not, and a texture; one thread (in order) is the reference. + let mut patchy = aa_disc(101, 101, 40.0); + for (i, v) in patchy.v.iter_mut().enumerate() { + if (i % 101 / 13 + i / 101 / 17) % 5 == 0 { + *v *= 0.6; + } + } + let shapes = [aa_disc(97, 83, 30.0), aa_round_rect(131, 77, 9.0, 11.0, 120.0, 66.0, 14.0), aa_bar(90, 130, 60.0, 150.0, 25.0), patchy]; + let mut sf = photocraft_raster::Surface::new(photocraft_color::PixelFormat::RGBA8); + sf.fill_rect(Rect::new(0, 0, 4, 2), &[0.0, 0.0, 0.0, 1.0]); + sf.fill_rect(Rect::new(0, 2, 4, 4), &[1.0, 1.0, 1.0, 1.0]); + let pats = [Pattern::new("stripes", sf, 4, 4)]; + let light = GlobalLight::default(); + let styles = [BevelStyle::InnerBevel, BevelStyle::OuterBevel, BevelStyle::Emboss, BevelStyle::PillowEmboss, BevelStyle::StrokeEmboss]; + for (k, shape) in shapes.iter().enumerate() { + let tex = TextureCtx { rect: Rect::new(3, 5, 3 + shape.w as i32, 5 + shape.h as i32), patterns: &pats, anchor: (0.0, 0.0) }; + for style in styles { + for technique in [BevelTechnique::Smooth, BevelTechnique::ChiselHard, BevelTechnique::ChiselSoft] { + for (size, soften, textured) in [(5.0, 0.0, false), (12.0, 2.0, false), (8.0, 0.0, true)] { + let mut b = bevel_of(style, technique); + (b.size, b.soften) = (size, soften); + if textured { + b.texture = Some(photocraft_doc::BevelTexture { + name: "stripes".into(), + id: String::new(), + scale: 1.0, + depth: 1.0, + invert: false, + link: true, + phase: (0.0, 0.0), + }); + } + let run = || bevel_maps(shape, &b, &light, &tex, &PreparedPatterns::new(&pats, PREPARED_PATTERN_BYTES)).0; + let one = with_threads(1, run); + for threads in [2, 5, 16] { + let many = with_threads(threads, run); + assert_eq!(one.len(), many.len()); + for (j, (a, m)) in one.iter().zip(&many).enumerate() { + assert_eq!(bits(&a.v), bits(&m.v), "shape {k}, {style:?} {technique:?} size {size} map {j} on {threads} threads"); + } + } + } + } + } + } +} + +/// The four fields that use the distance transform, of `m`. +fn distance_field_of(m: &Map, reach: f32) -> Vec> { + [FieldKind::Inside, FieldKind::Outside, FieldKind::BevelInside, FieldKind::BevelOutside].map(|k| distance_field(k, m.v.clone(), m.w, m.h, reach)).to_vec() +} + +fn aa_disc(w: usize, h: usize, r: f32) -> Map { + let mut m = Map::new(w, h, 0.0); + const N: usize = 16; + for y in 0..h { + for x in 0..w { + let mut hit = 0; + for sy in 0..N { + for sx in 0..N { + let (px, py) = (x as f32 + (sx as f32 + 0.5) / N as f32 - w as f32 / 2.0, y as f32 + (sy as f32 + 0.5) / N as f32 - h as f32 / 2.0); + hit += usize::from(px * px + py * py <= r * r); + } + } + m.v[y * w + x] = hit as f32 / (N * N) as f32; + } + } + m +} + +/// Integer-aligned rounded rectangle (x0..x1 x y0..y1, corner radius `rad`), anti-aliased by supersampling. +fn aa_round_rect(w: usize, h: usize, x0: f32, y0: f32, x1: f32, y1: f32, rad: f32) -> Map { + let sdf = |px: f32, py: f32| { + let (cx, cy) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0); + let (qx, qy) = ((px - cx).abs() - ((x1 - x0) / 2.0 - rad), (py - cy).abs() - ((y1 - y0) / 2.0 - rad)); + qx.max(0.0).hypot(qy.max(0.0)) + qx.max(qy).min(0.0) - rad + }; + let mut m = Map::new(w, h, 0.0); + const N: usize = 16; + for y in 0..h { + for x in 0..w { + let mut hit = 0; + for sy in 0..N { + for sx in 0..N { + hit += usize::from(sdf(x as f32 + (sx as f32 + 0.5) / N as f32, y as f32 + (sy as f32 + 0.5) / N as f32) <= 0.0); + } + } + m.v[y * w + x] = hit as f32 / (N * N) as f32; + } + } + m +} + +#[test] +fn chisel_hard_has_flat_facets() { + let shape = square(48, 10, 38); + let (m, _) = bevel_maps( + &shape, + &bevel_of(BevelStyle::InnerBevel, BevelTechnique::ChiselHard), + &GlobalLight::default(), + &no_tex(), + &PreparedPatterns::new(&[], PREPARED_PATTERN_BYTES), + ); + let at = |x: usize, y: usize| m[0].v[y * 48 + x]; + // A constant slope: equal highlight along the top facet. + assert!(at(24, 12) > 0.1 && (at(24, 12) - at(24, 13)).abs() < 1e-3); +} + +#[test] +fn linear_bevel_contour_leaves_the_height_alone_at_any_range() { + for range in [0.5, 0.7, 1.0] { + let lut = bevel_contour_lut(&photocraft_doc::BevelContour { contour: Contour::Linear, range, anti_alias: false }); + for v in [0.0f32, 0.25, 0.5, 0.75, 1.0] { + assert!((lut_at(&lut, v) - v).abs() < 1e-3, "range {range}: {v} -> {}", lut_at(&lut, v)); + } + } +} + +#[test] +fn bevel_contour_and_texture_shape_the_height() { + let shape = square(40, 6, 34); + let l = GlobalLight::default(); + let plain = bevel_of(BevelStyle::InnerBevel, BevelTechnique::Smooth); + let (a, _) = bevel_maps(&shape, &plain, &l, &no_tex(), &PreparedPatterns::new(&[], PREPARED_PATTERN_BYTES)); + // A contour reshapes the profile (here a ramp folded at its middle). + let mut c = plain.clone(); + let fold = vec![ + photocraft_doc::adjust::CurvePoint { input: 0.0, output: 0.0 }, + photocraft_doc::adjust::CurvePoint { input: 0.5, output: 1.0 }, + photocraft_doc::adjust::CurvePoint { input: 1.0, output: 0.0 }, + ]; + c.contour = + Some(photocraft_doc::BevelContour { contour: Contour::Custom { name: "fold".into(), points: fold, corners: vec![] }, range: 1.0, anti_alias: false }); + let (b, _) = bevel_maps(&shape, &c, &l, &no_tex(), &PreparedPatterns::new(&[], PREPARED_PATTERN_BYTES)); + let diff: f32 = a[1].v.iter().zip(&b[1].v).map(|(x, y)| (x - y).abs()).sum(); + assert!(diff > 5.0, "{diff}"); + // A striped texture lights the flat middle. + let mut sf = photocraft_raster::Surface::new(photocraft_color::PixelFormat::RGBA8); + sf.fill_rect(Rect::new(0, 0, 4, 2), &[0.0, 0.0, 0.0, 1.0]); + sf.fill_rect(Rect::new(0, 2, 4, 4), &[1.0, 1.0, 1.0, 1.0]); + let pats = [Pattern::new("stripes", sf, 4, 4)]; + let mut t = plain.clone(); + t.texture = + Some(photocraft_doc::BevelTexture { name: "stripes".into(), id: String::new(), scale: 1.0, depth: 1.0, invert: false, link: true, phase: (0.0, 0.0) }); + let tex = TextureCtx { rect: Rect::new(0, 0, 40, 40), patterns: &pats, anchor: (0.0, 0.0) }; + let (m, _) = bevel_maps(&shape, &t, &l, &tex, &PreparedPatterns::new(&pats, PREPARED_PATTERN_BYTES)); + let mid: f32 = (16..24).map(|y| m[0].v[y * 40 + 20] + m[1].v[y * 40 + 20]).sum(); + let flat: f32 = (16..24).map(|y| a[0].v[y * 40 + 20] + a[1].v[y * 40 + 20]).sum(); + assert!(mid > flat + 0.5, "{mid} vs {flat}"); +} + +#[test] +fn glow_range_stretches_the_contour() { + let mut g = Glow { + common: photocraft_doc::FxCommon::new(BlendMode::Screen, 1.0), + paint: FxPaint::Color(photocraft_color::Color::WHITE), + technique: GlowTechnique::Softer, + spread: 0.0, + size: 10.0, + contour: Contour::Linear, + anti_alias: false, + range: 0.5, + jitter: 0.0, + noise: 0.0, + source: GlowSource::Edge, + }; + let l = glow_lut(&g).unwrap(); + assert!((lut_at(&l, 0.25) - 0.5).abs() < 1e-3 && (lut_at(&l, 0.75) - 1.0).abs() < 1e-6); + g.range = 1.0; + assert!(glow_lut(&g).is_none()); +} + +/// Photoshop 27.11, measured on a 128 px square (Normal, black, 100 %, Range 50 %): a precise +/// glow's coverage across the edge, and a centre-source inner glow as 1 − the edge glow. +#[test] +fn glows_match_photoshop() { + let glow = |technique, size: f32, spread: f32, source| Glow { + common: photocraft_doc::FxCommon::new(BlendMode::Normal, 1.0), + paint: FxPaint::Color(photocraft_color::Color::BLACK), + technique, + spread, + size, + contour: Contour::Linear, + anti_alias: false, + range: 0.5, + jitter: 0.0, + noise: 0.0, + source, + }; + let n = 60; + let mut shape = Map::new(n, n, 0.0); + for y in 20..40 { + for x in 20..40 { + shape.v[y * n + x] = 1.0; + } + } + let at = |m: &Map, x: usize| m.v[30 * n + x]; + // Outer, precise, size 10: Photoshop's black glow over white reads 47, 93, 140, 186, 232 + // at 2, 4, 6, 8 and 10 px out from the edge pixel (alpha 1 − D / 11). + let m = glow_map(&shape, &glow(GlowTechnique::Precise, 10.0, 0.0, GlowSource::Edge), false, (0, 0)); + for (d, ps) in [(2, 47.0f32), (4, 93.0), (6, 140.0), (8, 186.0), (10, 232.0)] { + let got = 255.0 * (1.0 - at(&m, 20 - d)); + assert!((got - ps).abs() <= 1.5, "outer precise at {d} px: {got} vs Photoshop {ps}"); + } + // Spread 40 %: solid for the first 4 px. + let m = glow_map(&shape, &glow(GlowTechnique::Precise, 10.0, 0.4, GlowSource::Edge), false, (0, 0)); + assert!((at(&m, 16) - 1.0).abs() < 1e-6 && at(&m, 14) < 1.0); + // Centre source = 1 − edge, for both techniques. + for t in [GlowTechnique::Precise, GlowTechnique::Softer] { + let e = glow_map(&shape, &glow(t, 6.0, 0.0, GlowSource::Edge), true, (0, 0)); + let c = glow_map(&shape, &glow(t, 6.0, 0.0, GlowSource::Center), true, (0, 0)); + for x in 20..40 { + assert!((at(&c, x) - (1.0 - at(&e, x))).abs() < 1e-5, "{t:?} at {x}"); + } + } +} + +#[test] +fn offsets_follow_light() { + let (dx, dy) = offset(120.0, 10.0); + assert_eq!((dx, dy), (5.0, 9.0)); +} + +fn square_shape(n: usize) -> Map { + let mut m = Map::new(n, n, 0.0); + for y in 5..n - 5 { + for x in 5..n - 5 { + m.v[y * n + x] = 1.0; + } + } + m +} + +#[test] +fn satin_at_distance_zero_matches_photoshop() { + // Photoshop 27.11, Satin black 100 %, angle 90°, Linear contour, distance 0, size 5 over a + // #808080 square: the rows from the top edge read 82, 102, 123, 128. + let s = photocraft_doc::effects::Satin { + common: photocraft_doc::FxCommon::new(BlendMode::Normal, 1.0), + color: photocraft_color::Color::BLACK, + angle: 90.0, + distance: 0.0, + size: 5.0, + contour: Contour::Linear, + anti_alias: false, + invert: false, + }; + let m = satin_map(&square_shape(60), &s); + for (row, gray) in [(5, 82.0), (7, 102.0), (9, 123.0), (11, 128.0), (30, 128.0)] { + let want = 1.0 - gray / 128.0; + let got = m.v[row * 60 + 30]; + assert!((got - want).abs() < 0.02, "row {row}: {got} vs {want}"); + } +} + +fn shadow(noise: f32, origin: (i32, i32)) -> Map { + let s = Shadow { + common: photocraft_doc::FxCommon::new(BlendMode::Multiply, 1.0), + color: photocraft_color::Color::BLACK, + angle: 0.0, + use_global_light: false, + distance: 0.0, + spread: 0.0, + size: 6.0, + contour: Contour::Linear, + anti_alias: false, + noise, + knocks_out: true, + }; + shadow_map(&square_shape(40), &s, &GlobalLight::default(), false, origin) +} + +#[test] +fn shadow_noise_speckles_soft_coverage_deterministically() { + let plain = shadow(0.0, (0, 0)); + let noisy = shadow(0.5, (0, 0)); + let again = shadow(0.5, (0, 0)); + let (mut diff, mut identical) = (0.0f32, true); + for i in 0..plain.v.len() { + diff += (plain.v[i] - noisy.v[i]).abs(); + if noisy.v[i] != again.v[i] { + identical = false; + } + } + assert!(diff > 5.0, "noise changes the soft band: {diff}"); + assert!(identical, "same coords, same speckle"); + // Every value stays a coverage. + assert!(noisy.v.iter().all(|v| (0.0..=1.0).contains(v))); + // The speckle moves with the document origin, not the tile. + let moved = shadow(0.5, (100, 100)); + assert_ne!(noisy.v, moved.v, "hashed from document coordinates"); + // Full noise can punch holes even in the solid part. + let heavy = shadow(1.0, (0, 0)); + assert!(heavy.v.iter().any(|v| *v < 0.5) && heavy.v.iter().any(|v| *v > 0.5), "heavy noise spans the range",); +} + +#[test] +fn box_blur_preserves_faint_coverage_and_empty_gaps() { + let src = [0.0, 0.3, 0.7, 0.0, 0.0, 0.0, 0.0, 1e-20, 0.0, 0.0, 0.0]; + let mut actual = [0.0; 11]; + box_line(&src, 0, &mut actual, 3.0); + assert_eq!(actual[5], 0.0, "an empty window must be exactly empty"); + assert_eq!(actual[10], 0.0, "the second tail must also be empty"); + assert!((actual[7] - 1e-20 / 3.0).abs() < 1e-30, "real faint coverage is not rounded away"); +} + +#[test] +fn effect_noise_does_not_light_up_empty_blur_tails() { + // A sloping antialiased shape leaves rounding residue in a running-sum blur. + // The direct finite-support convolution is the oracle for untouched pixels. + for size in [5.0, 5.5, 13.0] { + let mut shape = Map::new(96, 64, 0.0); + for y in 8..48 { + for x in 8..48 { + shape.v[y * shape.w + x] = ((x as f32 - y as f32 * 0.7) * 0.3).clamp(0.0, 1.0); + } + } + let mut direct = shape.clone(); + tent_direct(&mut direct, size); + let mut actual = shape; + blur(&mut actual, size); + noise(&mut actual, 0.26, 0, 0); + let stray = direct.v.iter().zip(&actual.v).filter(|(reference, noisy)| **reference == 0.0 && **noisy > 1e-5).count(); + assert_eq!(stray, 0, "noise created {stray} visible pixels outside a size-{size} blur"); + } +} + +#[test] +fn glow_noise_follows_the_contour_and_range() { + let g = |noise: f32| Glow { + common: photocraft_doc::FxCommon::new(BlendMode::Screen, 1.0), + paint: FxPaint::Color(photocraft_color::Color::WHITE), + technique: GlowTechnique::Softer, + spread: 0.0, + size: 6.0, + contour: Contour::Linear, + anti_alias: false, + range: 0.5, + jitter: 0.0, + noise, + source: GlowSource::Edge, + }; + let plain = glow_map(&square_shape(40), &g(0.0), false, (0, 0)); + let noisy = glow_map(&square_shape(40), &g(0.6), false, (0, 0)); + let diff: f32 = plain.v.iter().zip(&noisy.v).map(|(a, b)| (a - b).abs()).sum(); + assert!(diff > 5.0, "glow noise changes the coverage: {diff}"); +} + +/// Issue #7833: the speckle stays inside the glow's visible falloff instead of filling the +/// blur's whole rectangular reach out to the map edge. +#[test] +fn effect_noise_stays_inside_the_visible_falloff() { + let mut shape = Map::new(80, 80, 0.0); + for y in 35..45 { + for x in 35..45 { + shape.v[y * 80 + x] = 1.0; + } + } + let g = |noise: f32| Glow { + common: photocraft_doc::FxCommon::new(BlendMode::Screen, 1.0), + paint: FxPaint::Color(photocraft_color::Color::WHITE), + technique: GlowTechnique::Softer, + spread: 0.0, + size: 10.0, + contour: Contour::Linear, + anti_alias: false, + range: 0.5, + jitter: 0.0, + noise, + source: GlowSource::Edge, + }; + let s = |noise: f32| Shadow { + common: photocraft_doc::FxCommon::new(BlendMode::Multiply, 1.0), + color: photocraft_color::Color::BLACK, + angle: 0.0, + use_global_light: false, + distance: 0.0, + spread: 0.0, + size: 10.0, + contour: Contour::Linear, + anti_alias: false, + noise, + knocks_out: true, + }; + let light = GlobalLight::default(); + let pairs = [ + ("glow", glow_map(&shape, &g(0.0), false, (0, 0)), glow_map(&shape, &g(0.5), false, (0, 0))), + ("shadow", shadow_map(&shape, &s(0.0), &light, false, (0, 0)), shadow_map(&shape, &s(0.5), &light, false, (0, 0))), + ]; + for (name, plain, noisy) in pairs { + for (i, (p, n)) in plain.v.iter().zip(&noisy.v).enumerate() { + if *p < 1.0 / 255.0 { + assert!(*n <= 2.0 / 255.0, "{name}: pixel ({}, {}) invisible without noise: {p} -> {n}", i % 80, i / 80); + } + } + } +} + +#[test] +fn shifting_by_hostile_distances_does_not_overflow() { + let m = square_shape(12); + for d in [1.0e30, -1.0e30, f32::INFINITY, f32::NAN] { + let s = m.shifted(d, d, 0.0); + assert_eq!(s.v.len(), 144); + } +} diff --git a/crates/compose/src/extents.rs b/crates/compose/src/extents.rs new file mode 100644 index 0000000000..77b99bed85 --- /dev/null +++ b/crates/compose/src/extents.rs @@ -0,0 +1,428 @@ +use super::content::{render_content, surface_to_buffer}; +use super::ctx::Ctx; +use super::*; + +/// Bounds of a layer's own pixels (union over group children; the canvas +/// for fill layers; an artboard's board). +pub fn layer_bounds(layer: &Layer, canvas: Rect) -> Rect { + // Transparency Shapes Layer off: effects and knockout cover the whole layer (the canvas). + if advanced::shapeless(layer) { + return canvas; + } + match &layer.content { + LayerContent::Group(g) if g.artboard.is_some() => g.artboard.as_ref().map_or(Rect::EMPTY, |a| a.rect), + LayerContent::Group(g) => g.children.iter().filter(|c| c.visible).fold(Rect::EMPTY, |acc, c| { + let b = layer_bounds(c, canvas); + if b.is_empty() { + acc + } else if acc.is_empty() { + b + } else { + acc.union(&b) + } + }), + LayerContent::Fill(_) => canvas, + _ => { + let b = layer.surface().map_or(Rect::EMPTY, bounds::content_bounds); + let b = match &layer.content { + LayerContent::Shape(sh) => { + let p = shape_bounds(sh).map(|r| r.intersect(&canvas)).unwrap_or(Rect::EMPTY); + if !b.is_empty() && !p.is_empty() { + b.union(&p) + } else if !p.is_empty() { + p + } else { + b + } + } + _ => b, + }; + // Effects follow a filled shape's outline, also where its fill is transparent. + match effect_outline(layer).and_then(|_| paint_bounds(layer)).filter(|_| effects::has_effects(layer)) { + Some(p) if !b.is_empty() => b.union(&p), + Some(p) => p, + None => b, + } + } + } +} + +/// Where a layer's effects take their shape from: [`layer_bounds`], except that a group's +/// children count with their own effects (a child's outside stroke shapes the group's drop +/// shadow and must not be cut off at the child's pixels, #3274). +pub fn effect_source_bounds(layer: &Layer, canvas: Rect) -> Rect { + match &layer.content { + LayerContent::Group(g) if g.artboard.is_none() && !advanced::shapeless(layer) => g.children.iter().filter(|c| c.visible).fold(Rect::EMPTY, |acc, c| { + let m = if effects::has_effects(c) { effects::margin(c) } else { 0 }; + let b = effect_source_bounds(c, canvas); + let b = if b.is_empty() { b } else { b.inflate(m) }; + if b.is_empty() { + acc + } else if acc.is_empty() { + b + } else { + acc.union(&b) + } + }), + _ => layer_bounds(layer, canvas), + } +} + +/// The path a shape layer's effects are shaped by: its fill path. Photoshop builds a filled +/// shape's layer effects from its vector outline, not from its pixels: a stroke runs along the +/// whole path even where a gradient fill fades out (psd-tools stroke-effects). `None` for other +/// layers, shapes without fill, empty and inverted paths, and shapes whose vector stroke reaches +/// past the path (their pixels give the outline: psd-tools double-stroke-effects), and shapes +/// with a density or feather. +pub fn effect_outline(layer: &Layer) -> Option<&photocraft_doc::vector::Path> { + let LayerContent::Shape(sh) = &layer.content else { return None }; + let stroke_inside = sh.stroke.as_ref().is_none_or(|s| s.width <= 0.0 || s.align == photocraft_doc::vector::StrokeAlign::Inside); + // A soft (feathered or less dense) fill's own alpha is its outline. + (sh.fill.is_some() && stroke_inside && !sh.path.is_empty() && !sh.path.inverted && !sh.has_soft_mask()).then_some(&sh.path) +} + +/// The shape a layer's effects are built from over `rect` (row-major): its content's alpha +/// (masks applied), completed for shapes with an [`effect_outline`] by the outline's coverage +/// where the fill is see-through. With `l` the alpha and `f` the fill's own opacity (the largest +/// alpha around), the shape is `l + (1 - f) × coverage`: Photoshop's own rasterization where the +/// fill is opaque (it can differ from ours by a fraction of a pixel: psd-tools shape-fx2), the +/// path where the fill fades out (psd-tools stroke-effects). +pub(crate) fn effect_shape(layer: &Layer, rect: Rect, cx: &Ctx) -> Vec { + let n = rect.width() as usize * rect.height() as usize; + // Transparency Shapes Layer off: the effects take the whole layer as their shape (its masks + // still apply). + if !layer.advanced.transparency_shapes { + return mask_vals(layer, rect, cx).unwrap_or_else(|| vec![1.0; n]); + } + let Some(path) = effect_outline(layer).filter(|_| n > 0) else { + return render_content(layer, rect, cx).map(|b| b.px.iter().map(|p| p[3]).collect()).unwrap_or_else(|| vec![0.0; n]); + }; + // Unmasked: the masks scale the shape, they aren't the fill's transparency. + let a: Vec = layer.surface().map(|s| surface_to_buffer(s, rect).px.iter().map(|p| p[3]).collect()).unwrap_or_else(|| vec![0.0; n]); + let cov = photocraft_vector::path_coverage(path, rect); + let mv = mask_vals(layer, rect, cx); + let (w, h) = (rect.width() as usize, rect.height() as usize); + let mut out = vec![0.0; n]; + for y in 0..h { + for x in 0..w { + let i = y * w + x; + // A pixel the outline covers is inside, whatever the fill's opacity. + let v = if cov[i] >= 1.0 - 1e-3 { + 1.0 + } else { + let mut f = 0.0f32; + for yy in y.saturating_sub(1)..(y + 2).min(h) { + for xx in x.saturating_sub(1)..(x + 2).min(w) { + f = f.max(a[yy * w + xx]); + } + } + (a[i] + (1.0 - f.min(1.0)) * cov[i]).clamp(0.0, 1.0) + }; + out[i] = v * mask_k(&mv, i); + } + } + out +} + +/// The frame layer-effect gradients and linked patterns are laid out in, when it isn't the +/// layer's pixel bounds: a shape layer's path bounds, truncated to whole pixels. Its rendered +/// pixels can extend past the path (transparent anti-aliasing margin), which Photoshop ignores: +/// psd-tools shape-fx2's 45° overlay spans the 0.92–29.61 path as 0–29 (29 px, centred at 14.5), +/// not the 32 px of pixels. +pub fn paint_bounds(layer: &Layer) -> Option { + let LayerContent::Shape(sh) = &layer.content else { return None }; + let (x0, y0, x1, y1) = sh.path.control_bounds()?; + let r = Rect::new(x0.floor() as i32, y0.floor() as i32, x1.floor() as i32, y1.floor() as i32); + (!r.is_empty()).then_some(r) +} + +/// The frame a layer's effects are laid out in: [`paint_bounds`] for a shape, else the layer's +/// bounds ([`layer_bounds`]). A Gradient Overlay spans it, linked patterns tile from its corner. +pub fn effects_frame(layer: &Layer, canvas: Rect) -> Rect { + paint_bounds(layer).unwrap_or_else(|| layer_bounds(layer, canvas)) +} + +/// The pixels a change from `a` to `b` repaints beyond those it changed: where a layer whose +/// effects span its frame ([`effects::spans_frame`]) moved that frame, the layer's whole composite +/// before and after. Painting on a layer with a Gradient Overlay lays the one gradient out again +/// over the grown layer, as Photoshop does after each stroke; damage that covers only the stroke +/// leaves the old gradient around earlier strokes (#4053). Empty when no such frame moved. +pub fn relayout_damage(a: &Document, b: &Document) -> Rect { + let mut out = Rect::EMPTY; + let mut add = |r: Rect| { + if !r.is_empty() { + out = if out.is_empty() { r } else { out.union(&r) }; + } + }; + for (_, _, y) in b.walk() { + if !y.visible || !effects::spans_frame(y) { + continue; + } + let Some(x) = a.layer(y.id) else { continue }; + if effects_frame(x, a.bounds()) == effects_frame(y, b.bounds()) { + continue; + } + add(change_bounds(x, a.bounds()).unwrap_or_else(|| a.bounds())); + add(change_bounds(y, b.bounds()).unwrap_or_else(|| b.bounds())); + } + out +} + +/// The bounding box of a shape layer's path and stroke, ignoring its Density and Feather: its +/// path control bounds plus stroke width (a conservative reach for any alignment, cap and join). +pub fn hard_shape_bounds(sh: &photocraft_doc::ShapeLayer) -> Option { + if sh.fill.is_none() && sh.stroke.as_ref().is_none_or(|s| s.width <= 0.0 || s.opacity <= 0.0) { + return None; + } + let (x0, y0, x1, y1) = sh.path.control_bounds()?; + let stroke_margin = sh.stroke.as_ref().filter(|s| s.opacity > 0.0).map_or(0.0, |s| s.width.ceil()) as i32; + let r = Rect::new(x0.floor() as i32, y0.floor() as i32, x1.ceil() as i32, y1.ceil() as i32).inflate(stroke_margin); + (!r.is_empty()).then_some(r) +} + +/// The frame Free Transform, the Move tool's transform controls, snapping and Properties show for +/// a soft shape (Density below 100 % or a Feather), whose rendering reaches past its path: the +/// pixels the same shape renders in `format` over `canvas` at full Density without Feather, so +/// the frame is exactly the hard shape's whatever the stroke's alignment, cap and join (in +/// Photoshop a shape's transform frame follows its path and stroke whatever its mask Density and +/// Feather, #5846). An inverted path's frame is its own outline, not the whole canvas. Renders +/// only the strips along the edges of the rasterizers' (1 px conservative) bounds. +pub fn soft_shape_frame(sh: &photocraft_doc::ShapeLayer, format: photocraft_color::PixelFormat, canvas: Rect) -> Option { + let mut path = sh.path.clone(); + path.inverted = false; + let hard = photocraft_doc::ShapeLayer { density: 1.0, feather: 0.0, path, fill: sh.fill.clone(), stroke: sh.stroke.clone(), ..Default::default() }; + let shape = photocraft_vector::CompiledShape::new(&hard, photocraft_vector::DEFAULT_TOLERANCE, canvas); + let r = shape.bounds()?.intersect(&canvas); + trim_to_painted(r, |strip| shape.render(format, strip).content_bounds()) +} + +/// `r` shrunk to the pixels `painted` reports (the painted bounds within a strip of `r`, empty if +/// none), looking in from each edge through strips that double in thickness: a few renders per +/// edge however wide the empty margin (a subtracted or intersected subpath can leave most of the +/// rasterizers' bounds empty), and none of `r`'s inside rendered at once. +pub(crate) fn trim_to_painted(mut r: Rect, mut painted: impl FnMut(Rect) -> Rect) -> Option { + // Top: the first strip holding paint gives the first painted row. + let mut t = 1; + while !r.is_empty() { + let strip = Rect::new(r.x0, r.y0, r.x1, r.y0.saturating_add(t).min(r.y1)); + let p = painted(strip).intersect(&strip); + if !p.is_empty() { + r.y0 = p.y0; + break; + } + r.y0 = strip.y1; + t = t.saturating_mul(2); + } + let mut t = 1; + while !r.is_empty() { + let strip = Rect::new(r.x0, r.y1.saturating_sub(t).max(r.y0), r.x1, r.y1); + let p = painted(strip).intersect(&strip); + if !p.is_empty() { + r.y1 = p.y1; + break; + } + r.y1 = strip.y0; + t = t.saturating_mul(2); + } + let mut t = 1; + while !r.is_empty() { + let strip = Rect::new(r.x0, r.y0, r.x0.saturating_add(t).min(r.x1), r.y1); + let p = painted(strip).intersect(&strip); + if !p.is_empty() { + r.x0 = p.x0; + break; + } + r.x0 = strip.x1; + t = t.saturating_mul(2); + } + let mut t = 1; + while !r.is_empty() { + let strip = Rect::new(r.x1.saturating_sub(t).max(r.x0), r.y0, r.x1, r.y1); + let p = painted(strip).intersect(&strip); + if !p.is_empty() { + r.x1 = p.x1; + break; + } + r.x1 = strip.x0; + t = t.saturating_mul(2); + } + (!r.is_empty()).then_some(r) +} + +/// The bounding box of a shape layer's vector content: its path control bounds plus stroke width +/// (and the reach of a soft fill). +pub fn shape_bounds(sh: &photocraft_doc::ShapeLayer) -> Option { + let r = hard_shape_bounds(sh)?; + // A soft fill reaches past the path: by its feather, or everywhere below 100 % density. + if sh.fill.is_some() && sh.has_soft_mask() { + if sh.density.is_finite() && sh.density < 1.0 { + return Some(Rect::new(i32::MIN / 4, i32::MIN / 4, i32::MAX / 4, i32::MAX / 4)); + } + return Some(r.union(&photocraft_vector::feather::path_area(&sh.path, masks::feather_sigma(sh.feather)))); + } + Some(r) +} + +/// The layer's effective mask over `rect` (row-major), read once per tile: the pixel mask +/// times the rasterized vector mask. +pub(crate) fn mask_vals(layer: &Layer, rect: Rect, cx: &Ctx) -> Option> { + // Feathers blur across tiles: read the cached, canvas-wide combined mask. + if masks::has_feather(layer) + && let Some(s) = masks::combined_mask(layer, cx.canvas) + { + let mut v = Vec::new(); + s.read_region_into(rect, &mut v); + return Some(v); + } + let vector = layer.vector_mask.as_ref().map(|vm| cx.vector_masks.values(vm, rect)); + let Some(m) = layer.mask.as_ref() else { return vector }; + let mut v = Vec::new(); + m.values_into(rect, &mut v); + if let Some(vm) = vector { + for (a, b) in v.iter_mut().zip(vm) { + *a *= b; + } + } + Some(v) +} + +#[inline] +pub(crate) fn mask_k(m: &Option>, i: usize) -> f32 { + m.as_ref().map_or(1.0, |v| v[i]) +} + +/// For the narrow `tsly=0` case where only local stroke effects are enabled, the effects cannot +/// contribute outside the stroke reach from the layer's pixels. Other `tsly=0` effects can cover +/// the full layer, and advanced blending can change the backdrop independently of those pixels. +pub(crate) fn shapeless_stroke_bounds(layer: &Layer) -> Option { + use photocraft_doc::Knockout; + + if layer.advanced.transparency_shapes + || layer.advanced.knockout != Knockout::None + || layer.advanced.blend_interior + || layer.clipped + || !layer.blend_if.is_default() + || layer.mask.as_ref().is_some_and(|m| m.enabled) + || layer.vector_mask.as_ref().is_some_and(|m| m.enabled) + || !transparent_outside(layer) + || !effects::maps_are_local(layer) + { + return None; + } + + if !layer.effects.enabled + || !layer.effects.items.iter().any(|e| e.enabled()) + || layer.effects.items.iter().any(|e| e.enabled() && !matches!(e, photocraft_doc::Effect::Stroke(_))) + { + return None; + } + + match &layer.content { + LayerContent::Raster(_) | LayerContent::Text(_) | LayerContent::Shape(_) | LayerContent::Smart(_) => { + let b = layer.surface().map_or(Rect::EMPTY, bounds::content_bounds); + // A filled shape's effects follow its outline, also where its fill is transparent (as + // in `layer_bounds`). + Some(match effect_outline(layer).and_then(|_| paint_bounds(layer)) { + Some(p) if !b.is_empty() => b.union(&p), + Some(p) => p, + None => b, + }) + } + _ => None, + } +} + +/// Where `layer`'s composite (its pixels and effects; a group's visible children with theirs) can +/// be non-transparent, or `None` when it may draw anywhere (a surface with an opaque default +/// pixel). Outside it, compositing the layer leaves the backdrop unchanged in every blend mode. +/// Adjustment layers count as empty: they only change pixels already there (which is what an +/// isolated group needs; see [`change_bounds`] for the document-level question). +pub fn composite_bounds(layer: &Layer, canvas: Rect) -> Option { + if !transparent_outside(layer) { + return None; + } + let own = match &layer.content { + LayerContent::Group(g) if g.artboard.is_none() => { + let mut acc = Rect::EMPTY; + for c in g.children.iter().filter(|c| c.visible) { + let b = composite_bounds(c, canvas)?; + if !b.is_empty() { + acc = if acc.is_empty() { b } else { acc.union(&b) }; + } + } + acc + } + LayerContent::Adjustment(_) => Rect::EMPTY, + _ => layer_bounds(layer, canvas), + }; + if own.is_empty() { + return Some(Rect::EMPTY); + } + let m = if effects::has_effects(layer) { effects::margin(layer) } else { 0 }; + Some(own.inflate(m).intersect(&canvas)) +} + +/// The document pixels that showing, hiding, moving or restyling `layer` can change, or `None` +/// for anywhere: an adjustment layer (and a pass-through group holding one) reaches everything +/// beneath it. Clipped layers above stay within their base's bounds, so they are covered too; +/// effects of groups around the layer can reach further (callers grow the rect by that reach). +pub fn change_bounds(layer: &Layer, canvas: Rect) -> Option { + fn reaches_below(l: &Layer) -> bool { + match &l.content { + LayerContent::Adjustment(_) => !l.clipped, + // Clipped to a base, an adjustment changes only the base's pixels; one with no base + // beneath it in its list composites as an ordinary adjustment (#6535). + LayerContent::Group(g) if l.blend == BlendMode::PassThrough => g.children.iter().enumerate().any(|(k, c)| { + let orphan = + c.clipped && matches!(c.content, LayerContent::Adjustment(_)) && g.children.get(..k).is_none_or(|below| below.iter().all(|b| b.clipped)); + orphan || reaches_below(c) + }), + _ => false, + } + } + if matches!(layer.content, LayerContent::Adjustment(_)) || reaches_below(layer) { + return None; + } + composite_bounds(layer, canvas) +} + +/// [`change_bounds`] of `layers[k]` in its sibling list (bottom→top), which also bounds a clipped +/// adjustment layer: it changes only its clip base's pixels, so it reaches as far as showing, +/// hiding or restyling that base does (#6535). Still `None` when there is no base below it (the +/// compositor then draws it as an ordinary adjustment) or the base is an adjustment itself +/// (layers clipped to one composite atop the adjusted backdrop, everywhere). `outer` is the list +/// holding the group whose children `layers` are, and that group's index there (`None` at the +/// top level): a pass-through group that is a clip base renders isolated while it holds a visible +/// adjustment, so showing or hiding one inside can change the whole group. +pub fn change_bounds_in(layers: &[Layer], k: usize, outer: Option<(&[Layer], usize)>, canvas: Rect) -> Option { + let layer = layers.get(k)?; + if layer.clipped && matches!(layer.content, LayerContent::Adjustment(_)) { + let base = layers.get(..k)?.iter().rev().find(|l| !l.clipped)?; + if matches!(base.content, LayerContent::Adjustment(_)) { + return None; + } + if let Some((outer, g)) = outer + && let Some(group) = outer.get(g) + && group.blend == BlendMode::PassThrough + && !group.clipped + && outer.get(g + 1).is_some_and(|above| above.clipped) + { + // The group bounds its base too. + return change_bounds(group, canvas); + } + return change_bounds(base, canvas); + } + change_bounds(layer, canvas) +} + +/// Whether the layer's content is transparent outside its bounds (every surface it draws from +/// has a transparent default pixel), so its effects can't change pixels beyond its bounds grown +/// by their reach. +pub fn transparent_outside(layer: &Layer) -> bool { + match &layer.content { + LayerContent::Group(g) => g.children.iter().filter(|c| c.visible).all(transparent_outside), + // Fill layers cover the canvas (their bounds); adjustments draw nothing of their own. + LayerContent::Fill(_) | LayerContent::Adjustment(_) => true, + _ => layer.surface().is_none_or(|s| s.format().alpha && s.default_pixel().last().is_some_and(|a| *a <= 0.0)), + } +} diff --git a/crates/compose/src/fx_cache.rs b/crates/compose/src/fx_cache.rs new file mode 100644 index 0000000000..cd08eaff7c --- /dev/null +++ b/crates/compose/src/fx_cache.rs @@ -0,0 +1,281 @@ +use super::composite::texture_ctx; +use super::ctx::{Ctx, PREPARE_DEPTH}; +use super::extents::{effect_shape, effect_source_bounds}; +use super::*; + +// --------------------------------------------------------------------------------------------- +// Layer-effect map cache + +/// Order-independent identity of a layer's pixels, masks, effects, Advanced Blending and Blend If +/// and (for groups) children. +/// Pixels are identified by their copy-on-write tile pointers. `pin` sees every tile hashed: a +/// cache entry keeps a [`std::sync::Weak`] to each, which reserves the tile's address (so no +/// other tile can reuse it and match the key) without keeping its pixels alive (#4530). +pub(crate) fn layer_identity(layer: &Layer, h: &mut std::collections::hash_map::DefaultHasher, pin: &mut dyn FnMut(&std::sync::Arc)) { + use std::hash::{Hash, Hasher}; + fn surface_fp(s: &Surface, pin: &mut dyn FnMut(&std::sync::Arc)) -> u64 { + let mut h = std::collections::hash_map::DefaultHasher::new(); + s.format().hash(&mut h); + // Missing tiles read the default pixel, so tile identity alone is not pixel identity. + for sample in s.default_pixel() { + sample.to_bits().hash(&mut h); + } + let tiles = s.tiles().fold(s.tile_count() as u64, |acc, (c, t)| { + pin(t); + let mut x = (std::sync::Arc::as_ptr(t) as usize as u64) ^ ((c.tx as u64) << 40) ^ ((c.ty as u32 as u64) << 8); + x = x.wrapping_mul(0x9e37_79b9_7f4a_7c15); + acc.wrapping_add(x ^ (x >> 29)) + }); + tiles.hash(&mut h); + h.finish() + } + layer.id.0.hash(h); + // What the maps depend on: `fill_opacity` shades them; layer `opacity` is applied when the + // maps are composited and `visible` only skips the lookup entirely, so neither belongs in + // the key (an opacity drag must not rebuild shadows over the whole layer; the GPU's + // `fx::shape_key` keeps them out for the same reason). + layer.fill_opacity.to_bits().hash(h); + match &layer.content { + LayerContent::Group(g) => { + for c in &g.children { + // A styled group's maps come from its children's composite, so how each child + // composites (unlike the group's own visibility and opacity) shapes them. + (c.visible, c.opacity.to_bits(), c.clipped).hash(h); + format!("{:?}", c.blend).hash(h); + layer_identity(c, h, pin); + } + format!("{:?}", g.artboard).hash(h); + } + LayerContent::Fill(f) => { + format!("{f:?}").hash(h); + // The cached pixels are what shapes the maps while they match the fill: a + // pixel-only rewrite of the cache (Image › Transform, crop) leaves `f` alone, and + // the stale maps would keep shadowing the pre-rewrite shape. + if let Some(c) = &layer.fill_cache + && c.fill == *f + { + surface_fp(&c.surface, pin).hash(h); + } + } + LayerContent::Adjustment(a) => format!("{a:?}").hash(h), + _ => layer.surface().map_or(0, |s| surface_fp(s, pin)).hash(h), + } + if let Some(m) = &layer.mask { + (surface_fp(&m.surface, pin), m.enabled, m.density.to_bits(), m.feather.to_bits()).hash(h); + } + if let Some(vm) = &layer.vector_mask { + format!("{vm:?}").hash(h); + } + format!("{:?}", layer.effects).hash(h); + // Transparency Shapes Layer picks the shape (content or the whole layer); a group child's + // Blend If and knockout change the composite a styled group's shape comes from. + layer.advanced.hash(h); + layer.blend_if.hash(h); + h.write_u8(0xfe); +} + +struct FxEntry { + maps: std::sync::Arc, + /// The tiles the key identifies (see [`layer_identity`]): their addresses, not their pixels. + _pin: Vec>, + bytes: usize, +} + +/// Global cache of effect maps (bounded by bytes), one slot per layer state. Slots are filled +/// with `set`, never `get_or_init`: nothing may block on a build (see `cached_effect_maps`). +type FxSlot = std::sync::Arc>; + +struct FxCache { + map: std::collections::HashMap, + order: std::collections::VecDeque, + bytes: usize, +} + +/// Default effect-cache budget (Preferences › Performance can change it). +pub const DEFAULT_FX_CACHE_BUDGET: usize = 768 << 20; + +static FX_CACHE_BUDGET: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(DEFAULT_FX_CACHE_BUDGET); + +/// Set the memory budget (bytes) of the layer-effect map cache; entries over it are evicted +/// oldest-first on the next build. +pub fn set_effect_cache_budget(bytes: usize) { + FX_CACHE_BUDGET.store(bytes.max(1 << 20), std::sync::atomic::Ordering::Relaxed); +} + +/// The current effect-cache budget in bytes. +pub fn effect_cache_budget() -> usize { + FX_CACHE_BUDGET.load(std::sync::atomic::Ordering::Relaxed) +} + +/// Bytes currently held by the effect-map cache. +pub fn effect_cache_bytes() -> usize { + fx_cache().lock().unwrap_or_else(|e| e.into_inner()).bytes +} + +/// Drop every cached effect map (Edit › Purge › All). Returns the bytes released. +pub fn purge_effect_cache() -> usize { + let mut c = fx_cache().lock().unwrap_or_else(|e| e.into_inner()); + let freed = c.bytes; + c.map.clear(); + c.order.clear(); + c.bytes = 0; + freed +} + +fn fx_cache() -> &'static std::sync::Mutex { + static C: std::sync::OnceLock> = std::sync::OnceLock::new(); + C.get_or_init(|| std::sync::Mutex::new(FxCache { map: Default::default(), order: Default::default(), bytes: 0 })) +} + +/// Where `layer`'s effect maps are built (see [`effect_maps`]) and whether that is clipped to the +/// rectangle being rendered rather than the whole region. +/// +/// Transparency Shapes Layer off makes the region the whole canvas whatever the layer holds: on a +/// 1920 × 103675 webtoon page each such layer's maps took about 2.4 GB, and a render held them for +/// every layer at once (60 GB with 25 stroked type layers, #1909). When its effects are local +/// ([`effects::maps_are_local`]), such a layer's maps are built over the render rectangle padded +/// by twice the effect reach instead, which gives the same pixels there. So are any layer's local +/// maps when the render's whole-region maps wouldn't fit in the effect cache ([`fx_over_budget`]). +/// Only when `rect`, what +/// the caller composites the layer over, lies within the render rectangle: a group's effect shape +/// (or anything else rendering children over a wider area) gets the whole region. +pub(crate) fn effect_region(layer: &Layer, rect: Rect, cx: &Ctx) -> (Rect, bool) { + let m = effects::margin(layer); + let region = effect_source_bounds(layer, cx.canvas).inflate(m).intersect(&cx.canvas.inflate(m)); + let clip = *cx.fx_clip.lock().unwrap_or_else(|e| e.into_inner()); + match clip { + Some(c) if c.contains_rect(&rect) && (advanced::shapeless(layer) || cx.fx_over_budget) && effects::maps_are_local(layer) => { + let part = region.intersect(&c.inflate(m.saturating_mul(2))); + (part, part != region) + } + _ => (region, false), + } +} + +/// Whether the effect maps of the visible layers of `layers` (groups included), each over its +/// whole region, would take more than the effect cache budget together. A render needs all of +/// them, so when they don't fit, building one evicts the next one needed and every render builds +/// them all again, seconds even for a small rect (#8330). Counted as [`effects::FxMaps::bytes`] +/// counts the built maps ([`effects::map_count`] arrays over each region). +pub(crate) fn fx_over_budget(layers: &[Layer], canvas: Rect) -> bool { + fx_region_bytes(layers, canvas) > effect_cache_budget() as u64 +} + +/// The bytes [`fx_over_budget`] compares with the budget. +pub(crate) fn fx_region_bytes(layers: &[Layer], canvas: Rect) -> u64 { + fn bytes(layers: &[Layer], canvas: Rect, depth: u32) -> u64 { + let mut total = 0u64; + for l in layers.iter().filter(|l| l.visible) { + if effects::has_effects(l) { + let m = effects::margin(l); + let region = effect_source_bounds(l, canvas).inflate(m).intersect(&canvas.inflate(m)); + let maps = effects::map_count(l) as u64; + let px = u64::from(region.width()) * u64::from(region.height()); + total = total.saturating_add(maps.saturating_mul(px).saturating_mul(4)); + } + if let LayerContent::Group(g) = &l.content + && depth < PREPARE_DEPTH + { + total = total.saturating_add(bytes(&g.children, canvas, depth + 1)); + } + } + total + } + bytes(layers, canvas, 0) +} + +/// Most bytes one layer's effect maps and source may take to build, whatever the cache budget. +const MAX_FX_BUILD_BYTES: u64 = if cfg!(target_pointer_width = "64") { 4 << 30 } else { 512 << 20 }; + +/// The layer's effect maps over its region (layer bounds grown by the effect reach, within the +/// canvas grown likewise; see [`effect_region`]), built once per layer state and shared by every +/// tile. `rect` is what the caller composites the layer over (see [`effect_region`]). +pub(crate) fn effect_maps(layer: &Layer, rect: Rect, cx: &Ctx) -> std::sync::Arc { + use std::hash::{Hash, Hasher}; + let (mut region, clipped) = effect_region(layer, rect, cx); + // Non-local effects keep their whole source region, which a few distant pixels stretch over + // the canvas: past the cap the effects are left out instead of allocating it. + let region_px = u64::from(region.width()) * u64::from(region.height()); + if (effects::map_count(layer) as u64 + 1).saturating_mul(region_px).saturating_mul(4) > MAX_FX_BUILD_BYTES { + region = Rect::EMPTY; + } + static NO_CACHE: std::sync::OnceLock = std::sync::OnceLock::new(); + if *NO_CACHE.get_or_init(|| std::env::var_os("PHOTOCRAFT_FX_NOCACHE").is_some()) { + let shape = if region.is_empty() { Vec::new() } else { effect_shape(layer, region, cx) }; + return std::sync::Arc::new(effects::build_maps_prepared(layer, shape, region, &cx.light, &texture_ctx(layer, region, cx), cx.patterns)); + } + let mut h = std::collections::hash_map::DefaultHasher::new(); + cx.layer_keys.identity(layer, cx.doc).hash(&mut h); + (region.x0, region.y0, region.x1, region.y1).hash(&mut h); + (cx.light.angle.to_bits(), cx.light.altitude.to_bits()).hash(&mut h); + let key = h.finish(); + // Prepared for this render (see `prepare_effects`): no global lookup, no build. + if let Some((m, _)) = cx.fx_maps.lock().unwrap_or_else(|e| e.into_inner()).get(&key) { + return m.clone(); + } + let maps = cached_effect_maps(layer, region, key, cx); + cx.fx_maps.lock().unwrap_or_else(|e| e.into_inner()).entry(key).or_insert((maps, clipped)).0.clone() +} + +fn build_fx_slot_maps(layer: &Layer, region: Rect, key: u64, cx: &Ctx, slot: &FxSlot) -> std::sync::Arc { + let shape: Vec = if region.is_empty() { Vec::new() } else { effect_shape(layer, region, cx) }; + let maps = effects::build_maps_prepared(layer, shape, region, &cx.light, &texture_ctx(layer, region, cx), cx.patterns); + let mut pin = Vec::new(); + layer_identity(layer, &mut std::collections::hash_map::DefaultHasher::new(), &mut |t| pin.push(std::sync::Arc::downgrade(t))); + // The maps, plus what each reserved tile address keeps allocated. + let bytes = maps.bytes().saturating_add(pin.len().saturating_mul(std::mem::size_of::() + 2 * std::mem::size_of::())); + let maps = std::sync::Arc::new(maps); + if slot.set(FxEntry { maps: maps.clone(), _pin: pin, bytes }).is_ok() { + // Counted exactly once, by the build that filled the slot, and only while the + // slot is still cached (eviction may have dropped it meanwhile). + let mut c = fx_cache().lock().unwrap_or_else(|e| e.into_inner()); + if c.map.get(&key).is_some_and(|s| std::sync::Arc::ptr_eq(s, slot)) { + c.bytes += bytes; + } + } + // A concurrent build that finished first wins, so every tile shares one map. + slot.get().map_or(maps, |e| e.maps.clone()) +} + +fn evict_fx_cache_over_budget(key: u64) { + let mut c = fx_cache().lock().unwrap_or_else(|e| e.into_inner()); + let budget = effect_cache_budget(); + while c.bytes > budget && c.order.len() > 1 { + let Some(old) = c.order.pop_front() else { break }; + if old == key { + c.order.push_back(old); + continue; + } + if let Some(s) = c.map.remove(&old) { + c.bytes = c.bytes.saturating_sub(s.get().map_or(0, |e| e.bytes)); + } + } +} + +/// The layer's effect maps from the global cache, built on a miss. +/// +/// Never waits for another thread's build (#276): this can run on a Rayon worker inside a tile, +/// and the build itself runs Rayon work. A worker waiting on that work may steal another tile of +/// the same layer; had it blocked on a once-init held further up its own stack, it would deadlock. +/// Instead a miss builds the maps here and the first finished build is kept. Renders build every +/// layer's maps before their parallel tiles (`prepare_effects`), so tiles rarely miss. +fn cached_effect_maps(layer: &Layer, region: Rect, key: u64, cx: &Ctx) -> std::sync::Arc { + let slot = { + let mut c = fx_cache().lock().unwrap_or_else(|e| e.into_inner()); + if let Some(s) = c.map.get(&key) { + s.clone() + } else { + let s: FxSlot = Default::default(); + c.map.insert(key, s.clone()); + c.order.push_back(key); + s + } + }; + let maps = match slot.get() { + Some(e) => e.maps.clone(), + None => build_fx_slot_maps(layer, region, key, cx, &slot), + }; + // Evict the oldest entries over budget (never the one just used). + evict_fx_cache_over_budget(key); + maps +} diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 0a3f5c4802..e593290571 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -42,6 +42,47 @@ use psblend as blend; pub use advanced::advanced_active; +mod composite; +mod content; +mod ctx; +mod extents; +mod fx_cache; +mod reduced; +mod render; + +pub use composite::{adjustment_quantum, blend_if_active, occludes_below, text_gamma}; +#[cfg(test)] +use composite::{blend_into_fill, blend_into_g, branchless_floor, composite_layer_plain, composite_pixel_layer, pixel_surface, quantize}; +use composite::{composite_atop, composite_layer, composite_stack_at, dissolve_noise}; +#[cfg(test)] +use content::render_fill; +pub use content::{RENDER_TILE, channel_weights, fill_frame, layer_shape, render_fill_content, stroke_frame, surface_to_buffer}; +use content::{empty_in, render_content}; +use ctx::{Ctx, prepare_effects}; +#[cfg(test)] +use ctx::{LayerKeys, PREPARE_DEPTH, effect_layers, prepare_tones}; +use extents::mask_vals; +pub use extents::{ + change_bounds, change_bounds_in, composite_bounds, effect_outline, effect_source_bounds, effects_frame, hard_shape_bounds, layer_bounds, paint_bounds, + relayout_damage, shape_bounds, soft_shape_frame, transparent_outside, +}; +#[cfg(test)] +use extents::{mask_k, shapeless_stroke_bounds, trim_to_painted}; +pub use fx_cache::{DEFAULT_FX_CACHE_BUDGET, effect_cache_budget, effect_cache_bytes, purge_effect_cache, set_effect_cache_budget}; +#[cfg(test)] +use fx_cache::{effect_maps, effect_region, fx_region_bytes}; +pub use reduced::{PROXY_THUMBNAIL_PIXELS, render_reduced, render_reduced_damage, render_reduced_rect, thumbnail, thumbnail_buffer, thumbnail_size}; +#[cfg(test)] +use reduced::{ReducedStats, render_reduced_in_bands, render_reduced_with}; +use render::in_blend_space; +#[cfg(test)] +use render::render_tiled_with; +pub(crate) use render::visible_layers; +pub use render::{ + BAND_PIXELS, MAX_RENDER_PIXELS, band_rows_for, cmyk_space, composite_to_surface, flatten, flatten_to_surface, render, render_bands, render_layer, + render_layer_in, render_tiled, +}; + /// Straight-alpha RGBA float buffer covering a rectangle. #[derive(Clone, Debug, PartialEq)] pub struct Buffer { @@ -95,2487 +136,6 @@ impl Buffer { } } -/// Tile size for parallel rendering (tile results are independent). -pub const RENDER_TILE: i32 = 256; - -// One tile of scratch per worker; nested rendering takes its own buffer. -thread_local! { - static SCRATCH: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; -} - -fn scratch_buffer(rect: Rect) -> Buffer { - if rect.width() as usize * rect.height() as usize > (RENDER_TILE * RENDER_TILE) as usize { - return Buffer::transparent(rect); - } - let mut px = SCRATCH.with(|slot| std::mem::take(&mut *slot.borrow_mut())); - px.resize(rect.width() as usize * rect.height() as usize, [0.0; 4]); - Buffer { rect, px } -} - -fn recycle_buffer(buf: Buffer) { - if buf.px.capacity() <= (RENDER_TILE * RENDER_TILE) as usize { - SCRATCH.with(|slot| { - let mut slot = slot.borrow_mut(); - if slot.capacity() < buf.px.capacity() { - *slot = buf.px; - } - }); - } -} - -#[cfg(test)] -#[test] -fn scratch_reuse_preserves_pixels_and_bounds_retention() { - SCRATCH.with(|slot| slot.borrow_mut().clear()); - let rect = Rect::new(-2, -3, 18, 11); - for fmt in [photocraft_color::PixelFormat::RGBA8, photocraft_color::PixelFormat::RGBA16, photocraft_color::PixelFormat::RGBA32F] { - let s = Surface::with_default(fmt, &[0.2, 0.4, 0.6, 0.8]); - let buf = surface_to_scratch(&s, rect); - assert_eq!(buf, surface_to_buffer(&s, rect)); - let ptr = buf.px.as_ptr(); - recycle_buffer(buf); - let reused = surface_to_scratch(&Surface::new(fmt), rect); - assert_eq!(reused.px.as_ptr(), ptr); - assert!(reused.px.iter().all(|p| p == &[0.0; 4])); - let nested = scratch_buffer(rect); - assert_ne!(nested.px.as_ptr(), reused.px.as_ptr()); - recycle_buffer(nested); - recycle_buffer(reused); - } - let cached = SCRATCH.with(|slot| slot.borrow().as_ptr()); - let huge = scratch_buffer(Rect::new(0, 0, RENDER_TILE + 1, RENDER_TILE)); - recycle_buffer(huge); - SCRATCH.with(|slot| { - assert_eq!(slot.borrow().as_ptr(), cached); - assert!(slot.borrow().capacity() <= (RENDER_TILE * RENDER_TILE) as usize); - }); -} - -/// Every layer the compositor draws, groups before their children: hidden layers and everything -/// inside hidden groups are left out. -pub(crate) fn visible_layers(layers: &[Layer]) -> Vec<&Layer> { - fn rec<'a>(layers: &'a [Layer], out: &mut Vec<&'a Layer>) { - for l in layers.iter().filter(|l| l.visible) { - out.push(l); - if let Some(children) = l.children() { - rec(children, out); - } - } - } - let mut out = Vec::new(); - rec(layers, &mut out); - out -} - -/// Composite the whole document over `rect`, in parallel 256² tiles on -/// native targets (single-threaded on wasm). -pub fn render(doc: &Document, rect: Rect) -> Buffer { - render_tiled(doc, rect, RENDER_TILE) -} - -/// Most pixels one [`render`] call will produce (2^30, a 16 GiB buffer; 32768² px). Larger rects -/// (a hostile canvas size is up to 300000 px a side) return an empty buffer instead of aborting -/// on allocation; callers wanting more render in pieces. -pub const MAX_RENDER_PIXELS: u64 = 1 << 30; - -/// [`render`] with an explicit tile size (tests check tile independence). -pub fn render_tiled(doc: &Document, rect: Rect, tile: i32) -> Buffer { - let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(doc.pixel_format().mode); - let cx = Ctx::for_doc(doc, &patterns); - render_tiled_with(doc, rect, tile, &cx) -} - -fn render_tiled_with(doc: &Document, rect: Rect, tile: i32, cx: &Ctx) -> Buffer { - let tile = tile.max(1); - // Lab documents mix Normal blending in CIELAB, as Photoshop does (psblend::LAB_MIX); 32-bit - // documents don't clip Add / Divide or Hue / Saturation / Color / Luminosity at 1 (psblend::HDR). - let lab = doc.mode == photocraft_color::ColorMode::Lab; - let hdr = doc.depth == photocraft_color::SampleType::F32; - // CMYK layers are read through the document's own CMYK profile (thread-local scope). - let cmyk = cmyk_space(doc); - let cmyk = cmyk.as_ref(); - if rect.is_empty() { - return Buffer::transparent(rect); - } - // Refuse rects too large to hold: an empty buffer, not an allocation failure. - if u64::from(rect.width()) * u64::from(rect.height()) > MAX_RENDER_PIXELS { - return Buffer::transparent(Rect::EMPTY); - } - // A CMYK stack with adjustment layers the inks carry exactly composites on its inks. - if let Some(buf) = native::render_cmyk(doc, rect, tile) { - return buf; - } - // A Lab stack with adjustment layers that work on L, a and b composites on its stored values. - if let Some(buf) = native_lab::render_lab(doc, rect, tile) { - return buf; - } - cx.set_fx_clip(rect); - if i64::from(rect.width()) <= i64::from(tile) && i64::from(rect.height()) <= i64::from(tile) { - return photocraft_color::convert::with_cmyk_space(cmyk, || { - let mut buf = multichannel::backdrop(doc, rect); - in_blend_space(lab, hdr, || composite_stack_at(&doc.layers, &mut buf, cx, advanced::Scope::ROOT)); - buf - }); - } - // Effect maps are built once, here, before any tile needs them (#276). - prepare_effects(&doc.layers, rect, cx, |f| { - photocraft_color::convert::with_cmyk_space(cmyk, || in_blend_space(lab, hdr, f)); - }); - let run = |t: Rect| { - photocraft_color::convert::with_cmyk_space(cmyk, || { - let mut b = multichannel::backdrop(doc, t); - in_blend_space(lab, hdr, || composite_stack_at(&doc.layers, &mut b, cx, advanced::Scope::ROOT)); - b - }) - }; - // Tiles are written straight into the output, one row of tiles (a band) at a time, so the - // peak is the output plus the tiles in flight, not a second full-size copy. - let w = rect.width() as usize; - let mut out = Buffer::transparent(rect); - let band_tiles = |y0: i32| { - let y1 = y0.saturating_add(tile).min(rect.y1); - let mut v = Vec::new(); - let mut x = rect.x0; - while x < rect.x1 { - let x1 = x.saturating_add(tile).min(rect.x1); - v.push(Rect::new(x, y0, x1, y1)); - x = x1; - } - v - }; - let put = |band: &mut [[f32; 4]], y0: i32, part: &Buffer| { - let pw = part.rect.width() as usize; - for (row, src) in part.px.chunks_exact(pw).enumerate() { - let o = ((part.rect.y0 - y0) as usize + row) * w + (part.rect.x0 - rect.x0) as usize; - band[o..o + pw].copy_from_slice(src); - } - }; - let band_len = w * tile as usize; - #[cfg(not(target_arch = "wasm32"))] - { - use rayon::prelude::*; - let bands = rect.height().div_ceil(tile as u32) as usize; - if bands >= 2 * rayon::current_num_threads() { - // Enough bands to keep every core busy: one band per task, its tiles in turn. - out.px.par_chunks_mut(band_len).enumerate().for_each(|(i, band)| { - let y0 = rect.y0 + i as i32 * tile; - for t in band_tiles(y0) { - put(band, y0, &run(t)); - } - }); - } else { - // Few, wide bands: the tiles of each band in parallel, and the bands too, so a band's - // slowest tile doesn't leave the other cores idle until the next band starts. Each - // tile is written as soon as it is done, so only the tiles in flight are held. - out.px.par_chunks_mut(band_len).enumerate().for_each(|(i, band)| { - let y0 = rect.y0 + i as i32 * tile; - let band = std::sync::Mutex::new(band); - band_tiles(y0).into_par_iter().for_each(|t| { - let part = run(t); - let mut band = band.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - put(&mut band, y0, &part); - }); - }); - } - } - #[cfg(target_arch = "wasm32")] - for (i, band) in out.px.chunks_mut(band_len).enumerate() { - let y0 = rect.y0 + i as i32 * tile; - for t in band_tiles(y0) { - put(band, y0, &run(t)); - } - } - out -} - -/// Runs `f` with this thread's document blend flags set ([`psblend::LAB_MIX`], [`psblend::HDR`]), -/// then restores the values they had (also on unwind): a nested rayon job can run another tile -/// on this thread mid-composite, and clearing the flags there broke the outer tile (#1112). -fn in_blend_space(lab: bool, hdr: bool, f: impl FnOnce() -> R) -> R { - psblend::with_lab_mix(lab, || psblend::with_hdr(hdr, f)) -} - -/// The document's own CMYK profile for reading its CMYK pixels (`None`: not a CMYK document, -/// untagged, or the built-in coated CMYK). Enter it with `photocraft_color::convert::with_cmyk_space` -/// around code that converts the document's CMYK pixels or colours to RGB. -pub fn cmyk_space(doc: &Document) -> Option> { - if doc.mode != photocraft_color::ColorMode::Cmyk { - return None; - } - photocraft_color::convert::CmykSpace::for_profile(doc.icc_profile.as_ref()) -} - -/// Pixels per band of [`render_bands`] (a 14000 px wide band is ~600 rows, ~130 MB of f32). -pub const BAND_PIXELS: u64 = 8 << 20; - -/// Composite `rect` in horizontal bands, top to bottom, handing each band to `sink` (tiles inside -/// a band render in parallel). Peak memory is one band instead of the whole composite, so huge -/// documents can be exported or displayed without a full-size float copy. `band_rows` of 0 picks -/// about [`BAND_PIXELS`] per band; bands are whole multiples of [`RENDER_TILE`] rows. -pub fn render_bands(doc: &Document, rect: Rect, band_rows: i32, mut sink: impl FnMut(Buffer) -> Result<(), E>) -> Result<(), E> { - if rect.is_empty() { - return Ok(()); - } - // Keep prepared pixels and compiled vector masks across bands without retaining any rendered band. - let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(doc.pixel_format().mode); - let cx = Ctx::for_doc(doc, &patterns); - let rows = band_rows_for(rect.width(), band_rows); - let mut y = rect.y0; - while y < rect.y1 { - let y1 = y.saturating_add(rows).min(rect.y1); - sink(render_tiled_with(doc, Rect::new(rect.x0, y, rect.x1, y1), RENDER_TILE, &cx))?; - y = y1; - } - Ok(()) -} - -/// Band height for [`render_bands`]: `requested` rounded up to whole tiles, or ~[`BAND_PIXELS`]. -pub fn band_rows_for(width: u32, requested: i32) -> i32 { - let want = if requested > 0 { i64::from(requested) } else { (BAND_PIXELS / u64::from(width.max(1))) as i64 }; - let tiles = (want + i64::from(RENDER_TILE) - 1) / i64::from(RENDER_TILE); - (tiles.clamp(1, 1 << 16) * i64::from(RENDER_TILE)) as i32 -} - -/// The document's composite as a pixel surface in `fmt` (straight RGBA converted to its model -/// and depth), optionally flattened over an opaque `background`; rendered and written in bands, -/// so no full-size float composite is held. Tiles equal to the default pixel are pruned. -/// -/// Fully transparent pixels are written as the default pixel. Converting transparent black -/// leaves colour behind in CMYK (K = 100%) and Lab (neutral a/b = 0.5), and those pixels would -/// otherwise count as content: the result would span the whole canvas. -/// -/// A CMYK document flattened to CMYK is composited in its ink values instead, so flattening -/// doesn't round-trip its pixels through RGB: plain Normal layers by [`native::flatten_cmyk`] -/// (#3778), and masks, groups, clipping, other blend modes and the other layer kinds by [`cmyk`] -/// where its layers mix on their inks (#2220). Otherwise the composite goes back to CMYK through -/// the document's own profile, the one its layers were read through. A Lab document of plain -/// layers is composited in its L, a and b ([`native_lab::flatten_lab`]). -pub fn flatten_to_surface(doc: &Document, fmt: photocraft_color::PixelFormat, background: Option<[f32; 3]>) -> Surface { - composite_to_surface(doc, doc.bounds(), fmt, background) -} - -/// [`flatten_to_surface`] over `rect` only (the rest of the surface stays empty). -pub fn composite_to_surface(doc: &Document, rect: Rect, fmt: photocraft_color::PixelFormat, background: Option<[f32; 3]>) -> Surface { - let paper = background.is_some_and(|bg| bg == [1.0; 3]); - if (background.is_none() || paper) - && let Some(s) = native::flatten_cmyk(doc, rect, fmt, paper) - { - return s; - } - if (background.is_none() || paper) - && let Some(s) = native_lab::flatten_lab(doc, rect, fmt, paper) - { - return s; - } - let space = cmyk_space(doc); - let to_cmyk = fmt.mode == photocraft_color::ColorMode::Cmyk && doc.mode == photocraft_color::ColorMode::Cmyk; - if to_cmyk && cmyk::renders_inks(doc) { - return composite_inks_to_surface(doc, rect, fmt, background, space.as_ref()); - } - // The composite separates back to CMYK through the document's own profile, the one its - // pixels were read through. - let mut s = Surface::new(fmt); - let n = fmt.channels(); - let empty = s.default_pixel(); - let mut data = Vec::new(); - let _ = render_bands(doc, rect, 0, |band| -> Result<(), ()> { - let band = match background { - Some(bg) => band.over_background(bg), - None => band, - }; - data.clear(); - data.resize(band.px.len() * n, 0.0); - photocraft_color::convert::with_cmyk_space(space.as_ref(), || { - for (p, out) in band.px.iter().zip(data.chunks_exact_mut(n)) { - if fmt.alpha && (p[3] <= 0.0 || p[3].is_nan()) && empty.len() == n { - out.copy_from_slice(&empty); - } else { - photocraft_raster::from_rgba_into(&fmt, *p, out); - } - } - }); - s.write_region(band.rect, &data); - Ok(()) - }); - s.prune(); - s -} - -/// One CMYK pixel's output channels into `data`: its inks (over `paper` when given) and alpha. -fn push_ink_pixel(data: &mut Vec, p: &[f32; 5], paper: Option<[f32; 4]>, fmt: photocraft_color::PixelFormat, empty: &[f32]) { - if paper.is_none() && fmt.alpha && (p[4] <= 0.0 || p[4].is_nan()) && empty.len() == fmt.channels() { - data.extend_from_slice(empty); - return; - } - // Over the paper (fully covered pixels keep their inks exactly), or straight. - let ink = |c: usize| match paper { - Some(bg) if p[4] < 1.0 => p[c] * p[4] + bg[c] * (1.0 - p[4]), - _ => p[c], - }; - data.extend((0..4).map(ink)); - if fmt.alpha { - data.push(if paper.is_some() { 1.0 } else { p[4] }); - } -} - -/// [`composite_to_surface`] for a CMYK document flattened to CMYK, composited in its inks. -fn composite_inks_to_surface( - doc: &Document, - rect: Rect, - fmt: photocraft_color::PixelFormat, - background: Option<[f32; 3]>, - space: Option<&std::sync::Arc>, -) -> Surface { - let mut s = Surface::new(fmt); - let n = fmt.channels(); - let empty = s.default_pixel(); - let mut data = Vec::new(); - // White paper is no ink; another background colour goes through the profile. - let paper = background - .map(|bg| if bg == [1.0; 3] { [0.0; 4] } else { photocraft_color::convert::with_cmyk_space(space, || photocraft_color::convert::rgb_to_cmyk(bg)) }); - let _ = cmyk::render_cmyk_bands(doc, rect, 0, |band| -> Result<(), ()> { - data.clear(); - data.reserve(band.px.len() * n); - for p in &band.px { - push_ink_pixel(&mut data, p, paper, fmt, &empty); - } - s.write_region(band.rect, &data); - Ok(()) - }); - s.prune(); - s -} - -/// Composite the full canvas. -pub fn flatten(doc: &Document) -> Buffer { - render(doc, doc.bounds()) -} - -/// Render an arbitrary subset: a single layer (e.g. for thumbnails), isolated. -/// Rects past [`MAX_RENDER_PIXELS`] give an empty buffer. -pub fn render_layer(layer: &Layer, rect: Rect) -> Buffer { - if u64::from(rect.width()) * u64::from(rect.height()) > MAX_RENDER_PIXELS { - return Buffer::transparent(Rect::EMPTY); - } - let mut buf = Buffer::transparent(rect); - let patterns = pattern::PreparedPatterns::new(&[], pattern::PREPARED_PATTERN_BYTES); - composite_stack_at( - std::slice::from_ref(layer), - &mut buf, - &Ctx { - canvas: rect, - transfer: adjust::Transfer::Srgb, - light: photocraft_doc::GlobalLight::default(), - patterns: &patterns, - mode: photocraft_color::ColorMode::Rgb, - depth: photocraft_color::SampleType::F32, - vector_masks: RenderVectorMasks::default(), - fx_maps: Default::default(), - fx_clip: Default::default(), - fx_over_budget: false, - tone_luts: prepare_tones(std::slice::from_ref(layer), 0), - doc: None, - layer_keys: Default::default(), - }, - advanced::Scope::ROOT, - ); - buf -} - -/// [`render_layer`] in `doc`'s context: the layer alone over `rect`, with the document's patterns, -/// Global Light, colour mode, depth and canvas (fill layers and gradients are laid out on it), as -/// the canvas composites it. Bakes (Scripts › Flatten All Layer Effects) render through this so -/// the pixels match what was on screen (#5719). Rects past [`MAX_RENDER_PIXELS`] give an empty -/// buffer. -pub fn render_layer_in(doc: &Document, layer: &Layer, rect: Rect) -> Buffer { - if rect.is_empty() { - return Buffer::transparent(rect); - } - if u64::from(rect.width()) * u64::from(rect.height()) > MAX_RENDER_PIXELS { - return Buffer::transparent(Rect::EMPTY); - } - let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(doc.pixel_format().mode); - // A lone layer: a deep knockout reveals transparency, not the document's Background. - let cx = Ctx { doc: None, ..Ctx::for_doc(doc, &patterns) }; - let lab = doc.mode == photocraft_color::ColorMode::Lab; - let hdr = doc.depth == photocraft_color::SampleType::F32; - let cmyk = cmyk_space(doc); - photocraft_color::convert::with_cmyk_space(cmyk.as_ref(), || { - let mut buf = Buffer::transparent(rect); - in_blend_space(lab, hdr, || composite_stack_at(std::slice::from_ref(layer), &mut buf, &cx, advanced::Scope::ROOT)); - buf - }) -} - -/// Documents above this many pixels get thumbnails from a proxy (see [`proxy`]) when that is -/// faithful; smaller ones are reduced from the exact composite. -pub const PROXY_THUMBNAIL_PIXELS: u64 = 16 << 20; - -/// Downscaled RGBA8 render of the document (area-averaged) for thumbnails, navigators and -/// histograms, at most `max_side` pixels on its longer side. Large documents are reduced from a -/// downsampled proxy (about twice the thumbnail's size), so a thumbnail of a 200 MP document -/// costs milliseconds and no full-size composite; the rest stream the exact composite in bands. -pub fn thumbnail(doc: &Document, max_side: u32) -> Rgba8Image { - thumbnail_buffer(doc, max_side).to_rgba8() -} - -/// Width and height of [`thumbnail`]`(doc, max_side)`. -pub fn thumbnail_size(doc: &Document, max_side: u32) -> (u32, u32) { - let b = doc.bounds(); - let longest = b.width().max(b.height()).max(1); - let scale = (max_side as f32 / longest as f32).min(1.0); - (((b.width() as f32 * scale).round() as u32).max(1), ((b.height() as f32 * scale).round() as u32).max(1)) -} - -/// [`thumbnail`] as straight-alpha floats (for callers that colour-convert it first). -pub fn thumbnail_buffer(doc: &Document, max_side: u32) -> Buffer { - let b = doc.bounds(); - let longest = b.width().max(b.height()).max(1); - let (w, h) = thumbnail_size(doc, max_side); - let k = longest / max_side.max(1).saturating_mul(2); - if k >= 2 && doc.size.area() > PROXY_THUMBNAIL_PIXELS && proxy::proxy_faithful(doc) { - render_reduced(&proxy::proxy_document(doc, k), w, h) - } else { - render_reduced(doc, w, h) - } -} - -/// The document's composite area-averaged (premultiplied) down to `w`×`h` (clamped to the -/// document size), rendered in bands so no full-size composite is held. -pub fn render_reduced(doc: &Document, w: u32, h: u32) -> Buffer { - render_reduced_in_bands(doc, doc.bounds(), w, h, None, 0) -} - -/// [`render_reduced`] of any area of the document plane, `rect`, which may lie past the canvas -/// (layer pixels there are kept until a crop deletes them). The buffer's rect is in output pixels -/// from (0, 0). -pub fn render_reduced_rect(doc: &Document, rect: Rect, w: u32, h: u32) -> Buffer { - render_reduced_in_bands(doc, rect, w, h, None, 0) -} - -/// The part of [`render_reduced`]`(doc, w, h)` that a change to `damage` (document pixels) can -/// affect: the output pixels whose source areas meet it, rendered from just those areas, with the -/// same values the whole reduction gives them. The buffer's rect is in output pixels (empty when -/// `damage` misses the document), so a reduced canvas texture can update only what a stroke touched. -pub fn render_reduced_damage(doc: &Document, w: u32, h: u32, damage: Rect) -> Buffer { - render_reduced_in_bands(doc, doc.bounds(), w, h, Some(damage), 0) -} - -/// [`render_reduced_rect`] (or, with `damage`, [`render_reduced_damage`]) of area `b` with an -/// explicit band height (see [`render_bands`]). -fn render_reduced_in_bands(doc: &Document, b: Rect, w: u32, h: u32, damage: Option, band_rows: i32) -> Buffer { - render_reduced_with(doc, b, w, h, damage, band_rows, true, &mut ReducedStats::default()) -} - -/// What a reduced render composited (tests check that one-colour areas are not composited). -#[derive(Debug, Default)] -struct ReducedStats { - /// Whether one-colour areas were looked for ([`uniform::UniformAreas`]). - uniform: bool, - /// Document pixels composited one by one. - composited: u64, -} - -/// A tile of a reduced render: one colour (premultiplied), or its composited pixels. -enum Part { - Solid([f32; 4]), - Px(Buffer), -} - -/// A column of document tiles in a reduced render (`b`-relative source columns). -struct TileColumn { - /// The columns rendered: the tile's, within the source area. - x0: usize, - x1: usize, - /// The whole tile's columns within `b`, whose values decide whether it is one colour. - whole: (i64, i64), - /// Runs of (output column, how many of the rendered columns it averages). - runs: Vec<(usize, f32)>, -} - -/// [`render_reduced_in_bands`]; `uniform` off composites every pixel (the reference in tests). -#[allow(clippy::too_many_arguments)] -fn render_reduced_with(doc: &Document, b: Rect, w: u32, h: u32, damage: Option, band_rows: i32, uniform: bool, stats: &mut ReducedStats) -> Buffer { - let (fw, fh) = (b.width() as usize, b.height() as usize); - let (w, h) = (w.clamp(1, b.width().max(1)) as usize, h.clamp(1, b.height().max(1)) as usize); - let full = Rect::from_xywh(0, 0, w as u32, h as u32); - if fw == 0 || fh == 0 { - return Buffer::transparent(if damage.is_some() { Rect::EMPTY } else { full }); - } - // Output column / row of each document column / row: output pixel t covers [t·f/n, (t+1)·f/n). - let span = |t: usize, f: usize, n: usize| (t * f / n, ((t + 1) * f / n).max(t * f / n + 1).min(f)); - // The output pixel whose span holds document column / row `x` (spans are contiguous: n <= f). - let cell = |x: usize, f: usize, n: usize| ((x + 1) * n).saturating_sub(1) / f; - // Output pixels to produce and the document area they cover. - let out = match damage { - None => full, - Some(d) => { - let d = d.intersect(&b); - if d.is_empty() { - return Buffer::transparent(Rect::EMPTY); - } - let (x0, x1) = ((d.x0 - b.x0) as usize, (d.x1 - b.x0) as usize); - let (y0, y1) = ((d.y0 - b.y0) as usize, (d.y1 - b.y0) as usize); - Rect::new(cell(x0, fw, w) as i32, cell(y0, fh, h) as i32, cell(x1 - 1, fw, w) as i32 + 1, cell(y1 - 1, fh, h) as i32 + 1) - } - }; - let (ox0, oy0, ow, oh) = (out.x0 as usize, out.y0 as usize, out.width() as usize, out.height() as usize); - let (sx0, sx1) = (span(ox0, fw, w).0, span(ox0 + ow - 1, fw, w).1); - let (sy0, sy1) = (span(oy0, fh, h).0, span(oy0 + oh - 1, fh, h).1); - let src = Rect::new(b.x0 + sx0 as i32, b.y0 + sy0 as i32, b.x0 + sx1 as i32, b.y0 + sy1 as i32); - if (w, h) == (fw, fh) { - let mut px = render(doc, src); - px.rect = out; - return px; - } - let map = |f: usize, n: usize| { - let mut m = vec![0u32; f]; - for t in 0..n { - let (a, z) = span(t, f, n); - m[a..z].fill(t as u32); - } - m - }; - let (cols, rows) = (map(fw, w), map(fh, h)); - let cols = &cols[sx0..sx1]; - let mut acc = vec![[0.0f32; 4]; ow * oh]; - // Each output row sums its source rows in a band (in order, top to bottom), each row's pixels - // left to right: `row(y, out)` adds source row `y` (band-relative) to output row `out`. - let sum_band = |acc: &mut [[f32; 4]], by0: usize, by1: usize, row: &(dyn Fn(usize, &mut [[f32; 4]]) + Sync)| { - let (t0, t1) = (rows[by0] as usize, rows[by1 - 1] as usize + 1); - let sum_row = |t: usize, out: &mut [[f32; 4]]| { - let (a, z) = span(t, fh, h); - for y in a.max(by0)..z.min(by1) { - row(y - by0, out); - } - }; - let part = &mut acc[(t0 - oy0) * ow..(t1 - oy0) * ow]; - #[cfg(not(target_arch = "wasm32"))] - { - use rayon::prelude::*; - part.par_chunks_mut(ow).enumerate().for_each(|(i, out)| sum_row(t0 + i, out)); - } - #[cfg(target_arch = "wasm32")] - for (i, out) in part.chunks_mut(ow).enumerate() { - sum_row(t0 + i, out); - } - }; - let add = |o: &mut [f32; 4], p: &[f32; 4]| { - for i in 0..3 { - o[i] += p[i] * p[3]; - } - o[3] += p[3]; - }; - if let Some(uniform) = uniform.then(|| uniform::UniformAreas::new(doc)).flatten() { - stats.uniform = true; - // One-colour tiles (a new document's background, the empty parts of a sparse one) are - // composited once per colour and summed per run of source columns, not per pixel - // (#4017). Tiles lie on the document's tile grid whatever `damage` is, so a damage - // render sums exactly what the whole reduction does. - let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(doc.pixel_format().mode); - let cx = Ctx::for_doc(doc, &patterns); - let t = RENDER_TILE as usize; - // The document tile grid (the surfaces' own), in `b`-relative coordinates: the start of - // the tile holding `v` (negative when `b` starts inside a tile). - let grid = |v: usize, o: i32| (i64::from(o) + v as i64).div_euclid(t as i64) * t as i64 - i64::from(o); - let tile_cols: Vec = (grid(sx0, b.x0)..sx1 as i64) - .step_by(t) - .map(|gx| { - let (x0, x1) = ((gx.max(0) as usize).max(sx0), ((gx + t as i64) as usize).min(sx1)); - let mut runs: Vec<(usize, f32)> = Vec::new(); - for &c in &cols[x0 - sx0..x1 - sx0] { - match runs.last_mut() { - Some((last, n)) if *last == c as usize - ox0 => *n += 1.0, - _ => runs.push((c as usize - ox0, 1.0)), - } - } - TileColumn { x0, x1, whole: (gx.max(0), (gx + t as i64).min(fw as i64)), runs } - }) - .collect(); - let band_h = band_rows_for(src.width(), band_rows).max(RENDER_TILE) as usize; - let mut y = grid(sy0, b.y0); - while y < sy1 as i64 { - let y1 = (y + band_h as i64).min(sy1 as i64); - let tiles: Vec<(Rect, Rect)> = (y..y1) - .step_by(t) - .flat_map(|gy| { - tile_cols.iter().map(move |&TileColumn { x0, x1, whole: (gx0, gx1), .. }| { - let at = |x0: i64, y0: i64, x1: i64, y1: i64| Rect::new(b.x0 + x0 as i32, b.y0 + y0 as i32, b.x0 + x1 as i32, b.y0 + y1 as i32); - let (gy0, gy1) = (gy.max(0), (gy + t as i64).min(fh as i64)); - (at(gx0, gy0, gx1, gy1), at(x0 as i64, gy0.max(sy0 as i64), x1 as i64, gy1.min(sy1 as i64))) - }) - }) - .collect(); - let one = |(whole, part): &(Rect, Rect)| -> Part { - let render = |r: Rect| render_tiled_with(doc, r, RENDER_TILE, &cx); - match uniform.color(*whole, |r| render(r).px.first().copied()) { - Some(p) => Part::Solid([p[0] * p[3], p[1] * p[3], p[2] * p[3], p[3]]), - None => Part::Px(render(*part)), - } - }; - #[cfg(not(target_arch = "wasm32"))] - let parts: Vec = { - use rayon::prelude::*; - tiles.par_iter().map(one).collect() - }; - #[cfg(target_arch = "wasm32")] - let parts: Vec = tiles.iter().map(one).collect(); - stats.composited += parts.iter().map(|p| if let Part::Px(b) = p { b.px.len() as u64 } else { 0 }).sum::(); - let (by0, by1) = (y.max(sy0 as i64) as usize, y1 as usize); - let n = tile_cols.len(); - let band_y = y; - sum_band(&mut acc, by0, by1, &|row: usize, out: &mut [[f32; 4]]| { - let y = (by0 + row) as i64; - let j = (y - band_y) as usize / t; - let ty = (y - (band_y + (j * t) as i64).max(sy0 as i64)) as usize; - for (TileColumn { x0, x1, runs, .. }, part) in tile_cols.iter().zip(parts.iter().skip(j * n).take(n)) { - match part { - Part::Solid(pa) => { - for &(c, k) in runs { - let o = &mut out[c]; - for i in 0..4 { - o[i] += pa[i] * k; - } - } - } - Part::Px(buf) => { - let tw = x1 - x0; - for (p, &c) in buf.px.iter().skip(ty * tw).take(tw).zip(&cols[x0 - sx0..x1 - sx0]) { - add(&mut out[c as usize - ox0], p); - } - } - } - } - }); - y = y1; - } - } else { - let ok: Result<(), ()> = render_bands(doc, src, band_rows, |band| { - stats.composited += band.px.len() as u64; - let (by0, by1) = ((band.rect.y0 - b.y0) as usize, (band.rect.y1 - b.y0) as usize); - let sw = sx1 - sx0; - sum_band(&mut acc, by0, by1, &|y: usize, out: &mut [[f32; 4]]| { - for (p, &c) in band.px[y * sw..(y + 1) * sw].iter().zip(cols) { - add(&mut out[c as usize - ox0], p); - } - }); - Ok(()) - }); - debug_assert!(ok.is_ok()); - } - let col_w: Vec = (0..ow) - .map(|x| { - let (x0, x1) = span(ox0 + x, fw, w); - (x1 - x0).max(1) - }) - .collect(); - let norm_row = |row: usize, out: &mut [[f32; 4]]| { - let (y0, y1) = span(oy0 + row, fh, h); - let rh = (y1 - y0).max(1); - for (p, &cw) in out.iter_mut().zip(&col_w) { - let a = p[3]; - if a > 0.0 { - let n = (rh * cw) as f32; - *p = [p[0] / a, p[1] / a, p[2] / a, a / n]; - } else { - *p = [0.0; 4]; - } - } - }; - #[cfg(not(target_arch = "wasm32"))] - { - use rayon::prelude::*; - acc.par_chunks_mut(ow).enumerate().for_each(|(row, out)| norm_row(row, out)); - } - #[cfg(target_arch = "wasm32")] - for (row, out) in acc.chunks_mut(ow).enumerate() { - norm_row(row, out); - } - Buffer { rect: out, px: acc } -} - -type VectorMaskSlot = std::sync::Arc>; - -#[derive(Default)] -struct RenderVectorMasks { - /// Compiled masks by content. Callers pass temporary clones (see `advanced.rs`), so an - /// address cannot identify a mask: a dropped clone's address is reused by the next one. - masks: std::sync::Mutex>, -} - -impl RenderVectorMasks { - fn values(&self, mask: &photocraft_doc::VectorMask, rect: Rect) -> Vec { - let slot = { - let mut masks = self.masks.lock().unwrap_or_else(|e| e.into_inner()); - match masks.iter().find(|(m, _)| m == mask) { - Some((_, slot)) => slot.clone(), - None => { - let slot = VectorMaskSlot::default(); - masks.push((mask.clone(), slot.clone())); - slot - } - } - }; - // Compilation is sequential. Rendering can enter Rayon and must happen after - // initialization, so waiting tiles cannot re-enter a slot still being built. - let compiled = slot.get_or_init(|| photocraft_vector::CompiledVectorMask::new(mask)); - compiled.render(rect) - } -} - -/// Rendering context shared down the tree. -struct Ctx<'a> { - /// Document canvas: fill layers and gradients are laid out relative to it, never to the render rect. - canvas: Rect, - /// Tone transfer used by adjustments that work in linear light. - transfer: adjust::Transfer, - /// Global light for layer effects. - light: photocraft_doc::GlobalLight, - /// Prepared document patterns, shared across all tiles and bands of this render call. - patterns: &'a pattern::PreparedPatterns<'a>, - /// The document's colour mode (channel restrictions name its channels). - mode: photocraft_color::ColorMode, - depth: photocraft_color::SampleType, - /// At most 1 MiB of tone tables, initialized once and shared by this render's tiles and bands. - tone_luts: Vec<(&'a photocraft_doc::Adjustment, std::sync::OnceLock<[Vec; 4]>)>, - vector_masks: RenderVectorMasks, - /// Effect maps used by this render, by cache key: built before the parallel tiles (see - /// [`prepare_effects`]) and held for the whole render (or band, for maps clipped to it: the - /// `bool`), so eviction can't force a rebuild. - fx_maps: std::sync::Mutex, bool)>>, - /// The rectangle being rendered (a band of [`render_bands`]); see [`effect_region`]. - fx_clip: std::sync::Mutex>, - /// The whole-region effect maps of this render's layers wouldn't fit in the effect cache - /// together ([`fx_over_budget`]), so local ones are clipped to the render rect (#8330). - fx_over_budget: bool, - /// The document being rendered (deep knockouts reveal its Background); `None` for a lone layer. - doc: Option<&'a Document>, - /// Effect-map identities of this render's document layers (see [`LayerKeys`]). - layer_keys: LayerKeys, -} - -/// Memo of [`layer_identity`] for the layers of the document being rendered. The identity depends -/// on the layer alone, not on the tile, so it is computed once per layer per render instead of -/// once per tile. Only layers that sit in the document tree are memoised by address: the document -/// is borrowed for the whole render, so no other object can live at such an address. Temporary -/// copies (`advanced::effects_source`) are never in the tree and always take the full path. -#[derive(Default)] -struct LayerKeys { - /// Addresses of every layer in the document tree, collected on first use. - in_doc: std::sync::OnceLock>, - ids: std::sync::Mutex>, - /// Identities computed (tests count them). - #[cfg(test)] - built: std::sync::atomic::AtomicUsize, -} - -impl LayerKeys { - fn identity(&self, layer: &Layer, doc: Option<&Document>) -> u64 { - let addr = std::ptr::from_ref(layer) as usize; - let in_doc = doc.is_some_and(|d| self.in_doc.get_or_init(|| doc_layer_addresses(d)).contains(&addr)); - if in_doc { - let mut ids = self.ids.lock().unwrap_or_else(|e| e.into_inner()); - // Computing an identity only hashes immutable layer data; it does not run Rayon - // work or re-enter this memo. Keep the miss and insertion atomic across callers. - *ids.entry(addr).or_insert_with(|| self.compute(layer)) - } else { - self.compute(layer) - } - } - - fn compute(&self, layer: &Layer) -> u64 { - use std::hash::Hasher; - #[cfg(test)] - self.built.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - let mut h = std::collections::hash_map::DefaultHasher::new(); - layer_identity(layer, &mut h, &mut |_| {}); - h.finish() - } -} - -/// Addresses of all layers of `doc` (groups' children included). -fn doc_layer_addresses(doc: &Document) -> std::collections::HashSet { - let mut out = std::collections::HashSet::new(); - let mut todo: Vec<&Layer> = doc.layers.iter().collect(); - while let Some(l) = todo.pop() { - out.insert(std::ptr::from_ref(l) as usize); - if let LayerContent::Group(g) = &l.content { - todo.extend(g.children.iter()); - } - } - out -} - -impl<'a> Ctx<'a> { - fn for_doc(doc: &'a Document, patterns: &'a pattern::PreparedPatterns<'a>) -> Self { - Self { - doc: Some(doc), - canvas: doc.bounds(), - transfer: adjust::Transfer::for_document(doc.mode, doc.depth), - light: doc.global_light, - patterns, - mode: doc.mode, - depth: doc.depth, - vector_masks: RenderVectorMasks::default(), - fx_maps: Default::default(), - fx_clip: Default::default(), - fx_over_budget: fx_over_budget(&doc.layers, doc.bounds()), - layer_keys: Default::default(), - tone_luts: prepare_tones(&doc.layers, 0), - } - } - - /// Start rendering `rect`: effect maps clipped to the previous rectangle are let go. - fn set_fx_clip(&self, rect: Rect) { - let mut clip = self.fx_clip.lock().unwrap_or_else(|e| e.into_inner()); - if *clip != Some(rect) { - *clip = Some(rect); - self.fx_maps.lock().unwrap_or_else(|e| e.into_inner()).retain(|_, (_, clipped)| !*clipped); - } - } - - fn apply_adjustment(&self, adj: &photocraft_doc::Adjustment, buf: &mut Buffer) { - if let photocraft_doc::Adjustment::Levels { space, .. } | photocraft_doc::Adjustment::Curves { space, .. } = adj - && !matches!(adj, photocraft_doc::Adjustment::Levels { space: photocraft_doc::adjust::ToneSpace::Rgb, .. } if self.depth == photocraft_color::SampleType::F32) - && let Some((_, luts)) = self.tone_luts.iter().find(|(a, _)| std::ptr::eq(*a, adj)) - { - let identity = adjust::float_tone_identity(adj, Some(self.depth)); - if identity == [true; 3] { - return; - } - let extrapolate = adjust::float_tone_extrapolates(adj, Some(self.depth), self.mode); - adjust::apply_tone(buf, *space, luts.get_or_init(|| adjust::tone_luts_depth(adj, Some(self.depth))), identity, extrapolate); - } else { - adjust::apply_in(adj, buf, self.transfer, Some(self.depth), self.mode); - } - } -} - -fn prepare_tones(layers: &[Layer], depth: u32) -> Vec<(&photocraft_doc::Adjustment, std::sync::OnceLock<[Vec; 4]>)> { - let mut out = Vec::new(); - for layer in layers.iter().filter(|l| l.visible) { - if out.len() == 16 { - break; - } - match &layer.content { - LayerContent::Adjustment(a @ (photocraft_doc::Adjustment::Levels { .. } | photocraft_doc::Adjustment::Curves { .. })) => { - out.push((a, Default::default())) - } - LayerContent::Group(g) if depth < PREPARE_DEPTH => out.extend(prepare_tones(&g.children, depth + 1).into_iter().take(16 - out.len())), - _ => {} - } - } - out -} - -/// Deepest group nesting preparation walks (deeper layers prepare on demand). -const PREPARE_DEPTH: u32 = 64; - -/// Build the effect maps of every visible layer in `layers` (groups included) that can reach -/// `rect` before tiles render in parallel, layers concurrently on native targets, each build -/// inside `setting` (the tiles' thread-local colour setting). Tiles then only read finished maps: -/// none builds one while others need it (#276), and none duplicates another's build. Builds never -/// wait on each other (`cached_effect_maps`), so building them in parallel can't deadlock. -fn prepare_effects(layers: &[Layer], rect: Rect, cx: &Ctx, setting: impl Fn(&mut dyn FnMut()) + Sync) { - let mut todo = Vec::new(); - effect_layers(layers, rect, 0, &mut todo); - let build = |l: &std::borrow::Cow| { - setting(&mut || { - let _ = effect_maps(l, rect, cx); - }); - }; - #[cfg(not(target_arch = "wasm32"))] - if todo.len() > 1 { - use rayon::prelude::*; - todo.par_iter().for_each(build); - return; - } - todo.iter().for_each(build); -} - -/// The visible layers of `layers` (groups included) with effects that can reach `rect`. -fn effect_layers<'l>(layers: &'l [Layer], rect: Rect, depth: u32, out: &mut Vec>) { - let mut base_visible = true; - for l in layers { - if !l.clipped { - base_visible = l.visible; - } - // A clipping group is drawn only when its base is. - if !l.visible || !base_visible { - continue; - } - if effects::has_effects(l) && !empty_in(l, rect) { - // A mask that hides the effects is left out of the shape they are built from. - out.push(advanced::effects_source(l)); - } - if let LayerContent::Group(g) = &l.content - && depth < PREPARE_DEPTH - { - effect_layers(&g.children, rect, depth + 1, out); - } - } -} - -/// Composite an isolated group's sibling list (bottom→top) onto `backdrop` (its own buffer). -fn composite_stack(layers: &[Layer], backdrop: &mut Buffer, cx: &Ctx) { - composite_stack_at(layers, backdrop, cx, advanced::Scope::ISOLATED); -} - -/// Composite a sibling list (bottom→top) onto `backdrop`; `scope` says where the stack sits (see -/// [`advanced::Scope`]: it decides what knockouts reveal). -fn composite_stack_at(layers: &[Layer], backdrop: &mut Buffer, cx: &Ctx, scope: advanced::Scope) { - // Shallow knockouts stop at the bottom of this stack: the backdrop it starts from. - let floor = (!scope.root && advanced::needs_floor(layers)).then(|| backdrop.clone()); - let mut i = 0; - while i < layers.len() { - let base = &layers[i]; - // Collect the clipping group: following layers with `clipped = true`. - let mut j = i + 1; - while j < layers.len() && layers[j].clipped && !base.clipped { - j += 1; - } - let clipped = &layers[i + 1..j]; - if base.visible { - let ko = advanced::knockout_target(base, floor.as_ref(), backdrop.rect, cx, scope); - composite_layer(base, clipped, backdrop, cx, ko.as_deref(), scope); - if let (LayerContent::Adjustment(_), Some(q)) = (&base.content, adjustment_quantum(cx.depth)) { - quantize(backdrop, q); - } - } - i = j.max(i + 1); - } -} - -/// Steps per unit of an integer document's samples: Photoshop applies adjustment layers to -/// buffers of the document's depth (8-bit: 255 levels, 16-bit: 32768), so their result is -/// rounded there; a steep curve then amplifies the rounding of its input exactly as in -/// Photoshop (psd-tools adjustment_nested_composition_4: 9.6 → 5.1 % of pixels off; -/// exposure_grayscale passes). Blends stay in float (quantising them too made other files -/// worse). -pub fn adjustment_quantum(depth: photocraft_color::SampleType) -> Option { - match depth { - photocraft_color::SampleType::U8 => Some(255.0), - photocraft_color::SampleType::U16 => Some(32768.0), - photocraft_color::SampleType::F32 => None, - } -} - -fn quantize(b: &mut Buffer, q: f32) { - for p in &mut b.px { - for v in p.iter_mut() { - *v = branchless_floor(*v * q + 0.5) / q; - } - } -} - -/// `x.floor()`, bit for bit (signed zeros, infinities and NaNs included), without a call: baseline -/// x86-64 has no SSE4.1 `roundss`, so `floor` is a software routine there, called once per sample -/// of the backdrop under every adjustment layer ([`quantize`]). This form has no branch, so the -/// loop vectorizes. -#[inline] -fn branchless_floor(x: f32) -> f32 { - // From 2^23 on every f32 is whole. Below it, adding and taking away 2^23 rounds to the - // nearest whole number; where that went up, step down. - const WHOLE: f32 = 8_388_608.0; - let a = x.abs(); - let r = ((a + WHOLE) - WHOLE).copysign(x); - let r = if r > x { r - 1.0 } else { r }; - if a < WHOLE { r } else { x } -} - -/// Blend an adjustment layer's result (`adjusted`) back into the backdrop it was made from, each -/// pixel by its coverage `ks` (opacity × mask) in blend mode `mode`. -fn blend_back(backdrop: &mut [[f32; 4]], adjusted: &[[f32; 4]], ks: impl Iterator, mode: BlendMode) { - for ((b, a), k) in backdrop.iter_mut().zip(adjusted).zip(ks) { - if k <= 0.0 { - continue; - } - let s = [a[0], a[1], a[2]]; - // Normal is the source as it is (`blend_rgb` gives exactly that), and most adjustment - // layers are Normal: no per-pixel mode dispatch for them. - let blended = if mode == BlendMode::Normal { s } else { blend::blend_rgb(mode, [b[0], b[1], b[2]], s) }; - *b = [b[0] + (blended[0] - b[0]) * k, b[1] + (blended[1] - b[1]) * k, b[2] + (blended[2] - b[2]) * k, b[3]]; - } -} - -/// Deterministic hash for Dissolve (document-coordinate based, so it is stable under tiling). -#[inline] -fn dissolve_noise(x: i32, y: i32) -> f32 { - let mut h = (x as u32).wrapping_mul(0x8da6_b343) ^ (y as u32).wrapping_mul(0xd816_3841) ^ 0x9e37_79b9; - h ^= h >> 15; - h = h.wrapping_mul(0x2c1b_3c6d); - h ^= h >> 12; - (h & 0xffff) as f32 / 65536.0 -} - -/// Bounds of a layer's own pixels (union over group children; the canvas -/// for fill layers; an artboard's board). -pub fn layer_bounds(layer: &Layer, canvas: Rect) -> Rect { - // Transparency Shapes Layer off: effects and knockout cover the whole layer (the canvas). - if advanced::shapeless(layer) { - return canvas; - } - match &layer.content { - LayerContent::Group(g) if g.artboard.is_some() => g.artboard.as_ref().map_or(Rect::EMPTY, |a| a.rect), - LayerContent::Group(g) => g.children.iter().filter(|c| c.visible).fold(Rect::EMPTY, |acc, c| { - let b = layer_bounds(c, canvas); - if b.is_empty() { - acc - } else if acc.is_empty() { - b - } else { - acc.union(&b) - } - }), - LayerContent::Fill(_) => canvas, - _ => { - let b = layer.surface().map_or(Rect::EMPTY, bounds::content_bounds); - let b = match &layer.content { - LayerContent::Shape(sh) => { - let p = shape_bounds(sh).map(|r| r.intersect(&canvas)).unwrap_or(Rect::EMPTY); - if !b.is_empty() && !p.is_empty() { - b.union(&p) - } else if !p.is_empty() { - p - } else { - b - } - } - _ => b, - }; - // Effects follow a filled shape's outline, also where its fill is transparent. - match effect_outline(layer).and_then(|_| paint_bounds(layer)).filter(|_| effects::has_effects(layer)) { - Some(p) if !b.is_empty() => b.union(&p), - Some(p) => p, - None => b, - } - } - } -} - -/// Where a layer's effects take their shape from: [`layer_bounds`], except that a group's -/// children count with their own effects (a child's outside stroke shapes the group's drop -/// shadow and must not be cut off at the child's pixels, #3274). -pub fn effect_source_bounds(layer: &Layer, canvas: Rect) -> Rect { - match &layer.content { - LayerContent::Group(g) if g.artboard.is_none() && !advanced::shapeless(layer) => g.children.iter().filter(|c| c.visible).fold(Rect::EMPTY, |acc, c| { - let m = if effects::has_effects(c) { effects::margin(c) } else { 0 }; - let b = effect_source_bounds(c, canvas); - let b = if b.is_empty() { b } else { b.inflate(m) }; - if b.is_empty() { - acc - } else if acc.is_empty() { - b - } else { - acc.union(&b) - } - }), - _ => layer_bounds(layer, canvas), - } -} - -/// The path a shape layer's effects are shaped by: its fill path. Photoshop builds a filled -/// shape's layer effects from its vector outline, not from its pixels: a stroke runs along the -/// whole path even where a gradient fill fades out (psd-tools stroke-effects). `None` for other -/// layers, shapes without fill, empty and inverted paths, and shapes whose vector stroke reaches -/// past the path (their pixels give the outline: psd-tools double-stroke-effects), and shapes -/// with a density or feather. -pub fn effect_outline(layer: &Layer) -> Option<&photocraft_doc::vector::Path> { - let LayerContent::Shape(sh) = &layer.content else { return None }; - let stroke_inside = sh.stroke.as_ref().is_none_or(|s| s.width <= 0.0 || s.align == photocraft_doc::vector::StrokeAlign::Inside); - // A soft (feathered or less dense) fill's own alpha is its outline. - (sh.fill.is_some() && stroke_inside && !sh.path.is_empty() && !sh.path.inverted && !sh.has_soft_mask()).then_some(&sh.path) -} - -/// The shape a layer's effects are built from over `rect` (row-major): its content's alpha -/// (masks applied), completed for shapes with an [`effect_outline`] by the outline's coverage -/// where the fill is see-through. With `l` the alpha and `f` the fill's own opacity (the largest -/// alpha around), the shape is `l + (1 - f) × coverage`: Photoshop's own rasterization where the -/// fill is opaque (it can differ from ours by a fraction of a pixel: psd-tools shape-fx2), the -/// path where the fill fades out (psd-tools stroke-effects). -fn effect_shape(layer: &Layer, rect: Rect, cx: &Ctx) -> Vec { - let n = rect.width() as usize * rect.height() as usize; - // Transparency Shapes Layer off: the effects take the whole layer as their shape (its masks - // still apply). - if !layer.advanced.transparency_shapes { - return mask_vals(layer, rect, cx).unwrap_or_else(|| vec![1.0; n]); - } - let Some(path) = effect_outline(layer).filter(|_| n > 0) else { - return render_content(layer, rect, cx).map(|b| b.px.iter().map(|p| p[3]).collect()).unwrap_or_else(|| vec![0.0; n]); - }; - // Unmasked: the masks scale the shape, they aren't the fill's transparency. - let a: Vec = layer.surface().map(|s| surface_to_buffer(s, rect).px.iter().map(|p| p[3]).collect()).unwrap_or_else(|| vec![0.0; n]); - let cov = photocraft_vector::path_coverage(path, rect); - let mv = mask_vals(layer, rect, cx); - let (w, h) = (rect.width() as usize, rect.height() as usize); - let mut out = vec![0.0; n]; - for y in 0..h { - for x in 0..w { - let i = y * w + x; - // A pixel the outline covers is inside, whatever the fill's opacity. - let v = if cov[i] >= 1.0 - 1e-3 { - 1.0 - } else { - let mut f = 0.0f32; - for yy in y.saturating_sub(1)..(y + 2).min(h) { - for xx in x.saturating_sub(1)..(x + 2).min(w) { - f = f.max(a[yy * w + xx]); - } - } - (a[i] + (1.0 - f.min(1.0)) * cov[i]).clamp(0.0, 1.0) - }; - out[i] = v * mask_k(&mv, i); - } - } - out -} - -/// The frame layer-effect gradients and linked patterns are laid out in, when it isn't the -/// layer's pixel bounds: a shape layer's path bounds, truncated to whole pixels. Its rendered -/// pixels can extend past the path (transparent anti-aliasing margin), which Photoshop ignores: -/// psd-tools shape-fx2's 45° overlay spans the 0.92–29.61 path as 0–29 (29 px, centred at 14.5), -/// not the 32 px of pixels. -pub fn paint_bounds(layer: &Layer) -> Option { - let LayerContent::Shape(sh) = &layer.content else { return None }; - let (x0, y0, x1, y1) = sh.path.control_bounds()?; - let r = Rect::new(x0.floor() as i32, y0.floor() as i32, x1.floor() as i32, y1.floor() as i32); - (!r.is_empty()).then_some(r) -} - -/// The frame a layer's effects are laid out in: [`paint_bounds`] for a shape, else the layer's -/// bounds ([`layer_bounds`]). A Gradient Overlay spans it, linked patterns tile from its corner. -pub fn effects_frame(layer: &Layer, canvas: Rect) -> Rect { - paint_bounds(layer).unwrap_or_else(|| layer_bounds(layer, canvas)) -} - -/// The pixels a change from `a` to `b` repaints beyond those it changed: where a layer whose -/// effects span its frame ([`effects::spans_frame`]) moved that frame, the layer's whole composite -/// before and after. Painting on a layer with a Gradient Overlay lays the one gradient out again -/// over the grown layer, as Photoshop does after each stroke; damage that covers only the stroke -/// leaves the old gradient around earlier strokes (#4053). Empty when no such frame moved. -pub fn relayout_damage(a: &Document, b: &Document) -> Rect { - let mut out = Rect::EMPTY; - let mut add = |r: Rect| { - if !r.is_empty() { - out = if out.is_empty() { r } else { out.union(&r) }; - } - }; - for (_, _, y) in b.walk() { - if !y.visible || !effects::spans_frame(y) { - continue; - } - let Some(x) = a.layer(y.id) else { continue }; - if effects_frame(x, a.bounds()) == effects_frame(y, b.bounds()) { - continue; - } - add(change_bounds(x, a.bounds()).unwrap_or_else(|| a.bounds())); - add(change_bounds(y, b.bounds()).unwrap_or_else(|| b.bounds())); - } - out -} - -/// The bounding box of a shape layer's path and stroke, ignoring its Density and Feather: its -/// path control bounds plus stroke width (a conservative reach for any alignment, cap and join). -pub fn hard_shape_bounds(sh: &photocraft_doc::ShapeLayer) -> Option { - if sh.fill.is_none() && sh.stroke.as_ref().is_none_or(|s| s.width <= 0.0 || s.opacity <= 0.0) { - return None; - } - let (x0, y0, x1, y1) = sh.path.control_bounds()?; - let stroke_margin = sh.stroke.as_ref().filter(|s| s.opacity > 0.0).map_or(0.0, |s| s.width.ceil()) as i32; - let r = Rect::new(x0.floor() as i32, y0.floor() as i32, x1.ceil() as i32, y1.ceil() as i32).inflate(stroke_margin); - (!r.is_empty()).then_some(r) -} - -/// The frame Free Transform, the Move tool's transform controls, snapping and Properties show for -/// a soft shape (Density below 100 % or a Feather), whose rendering reaches past its path: the -/// pixels the same shape renders in `format` over `canvas` at full Density without Feather, so -/// the frame is exactly the hard shape's whatever the stroke's alignment, cap and join (in -/// Photoshop a shape's transform frame follows its path and stroke whatever its mask Density and -/// Feather, #5846). An inverted path's frame is its own outline, not the whole canvas. Renders -/// only the strips along the edges of the rasterizers' (1 px conservative) bounds. -pub fn soft_shape_frame(sh: &photocraft_doc::ShapeLayer, format: photocraft_color::PixelFormat, canvas: Rect) -> Option { - let mut path = sh.path.clone(); - path.inverted = false; - let hard = photocraft_doc::ShapeLayer { density: 1.0, feather: 0.0, path, fill: sh.fill.clone(), stroke: sh.stroke.clone(), ..Default::default() }; - let shape = photocraft_vector::CompiledShape::new(&hard, photocraft_vector::DEFAULT_TOLERANCE, canvas); - let r = shape.bounds()?.intersect(&canvas); - trim_to_painted(r, |strip| shape.render(format, strip).content_bounds()) -} - -/// `r` shrunk to the pixels `painted` reports (the painted bounds within a strip of `r`, empty if -/// none), looking in from each edge through strips that double in thickness: a few renders per -/// edge however wide the empty margin (a subtracted or intersected subpath can leave most of the -/// rasterizers' bounds empty), and none of `r`'s inside rendered at once. -fn trim_to_painted(mut r: Rect, mut painted: impl FnMut(Rect) -> Rect) -> Option { - // Top: the first strip holding paint gives the first painted row. - let mut t = 1; - while !r.is_empty() { - let strip = Rect::new(r.x0, r.y0, r.x1, r.y0.saturating_add(t).min(r.y1)); - let p = painted(strip).intersect(&strip); - if !p.is_empty() { - r.y0 = p.y0; - break; - } - r.y0 = strip.y1; - t = t.saturating_mul(2); - } - let mut t = 1; - while !r.is_empty() { - let strip = Rect::new(r.x0, r.y1.saturating_sub(t).max(r.y0), r.x1, r.y1); - let p = painted(strip).intersect(&strip); - if !p.is_empty() { - r.y1 = p.y1; - break; - } - r.y1 = strip.y0; - t = t.saturating_mul(2); - } - let mut t = 1; - while !r.is_empty() { - let strip = Rect::new(r.x0, r.y0, r.x0.saturating_add(t).min(r.x1), r.y1); - let p = painted(strip).intersect(&strip); - if !p.is_empty() { - r.x0 = p.x0; - break; - } - r.x0 = strip.x1; - t = t.saturating_mul(2); - } - let mut t = 1; - while !r.is_empty() { - let strip = Rect::new(r.x1.saturating_sub(t).max(r.x0), r.y0, r.x1, r.y1); - let p = painted(strip).intersect(&strip); - if !p.is_empty() { - r.x1 = p.x1; - break; - } - r.x1 = strip.x0; - t = t.saturating_mul(2); - } - (!r.is_empty()).then_some(r) -} - -/// The bounding box of a shape layer's vector content: its path control bounds plus stroke width -/// (and the reach of a soft fill). -pub fn shape_bounds(sh: &photocraft_doc::ShapeLayer) -> Option { - let r = hard_shape_bounds(sh)?; - // A soft fill reaches past the path: by its feather, or everywhere below 100 % density. - if sh.fill.is_some() && sh.has_soft_mask() { - if sh.density.is_finite() && sh.density < 1.0 { - return Some(Rect::new(i32::MIN / 4, i32::MIN / 4, i32::MAX / 4, i32::MAX / 4)); - } - return Some(r.union(&photocraft_vector::feather::path_area(&sh.path, masks::feather_sigma(sh.feather)))); - } - Some(r) -} - -/// The layer's effective mask over `rect` (row-major), read once per tile: the pixel mask -/// times the rasterized vector mask. -fn mask_vals(layer: &Layer, rect: Rect, cx: &Ctx) -> Option> { - // Feathers blur across tiles: read the cached, canvas-wide combined mask. - if masks::has_feather(layer) - && let Some(s) = masks::combined_mask(layer, cx.canvas) - { - let mut v = Vec::new(); - s.read_region_into(rect, &mut v); - return Some(v); - } - let vector = layer.vector_mask.as_ref().map(|vm| cx.vector_masks.values(vm, rect)); - let Some(m) = layer.mask.as_ref() else { return vector }; - let mut v = Vec::new(); - m.values_into(rect, &mut v); - if let Some(vm) = vector { - for (a, b) in v.iter_mut().zip(vm) { - *a *= b; - } - } - Some(v) -} - -#[inline] -fn mask_k(m: &Option>, i: usize) -> f32 { - m.as_ref().map_or(1.0, |v| v[i]) -} - -/// Render a layer's own content (no blending into the backdrop yet) into an isolated buffer. -/// Returns None for layers that operate on the backdrop (adjustments, pass-through groups). -fn render_content(layer: &Layer, rect: Rect, cx: &Ctx) -> Option { - let mut buf = match &layer.content { - LayerContent::Group(g) => { - let mut b = Buffer::transparent(rect); - composite_stack(&g.children, &mut b, cx); - b - } - LayerContent::Fill(f) => match &layer.fill_cache { - // Photoshop's own rendering, valid while the fill is unchanged. - Some(c) if c.fill == *f => surface_to_scratch(&c.surface, rect), - _ if cx.mode == photocraft_color::ColorMode::Cmyk => { - let frame = fill_frame(layer, cx.canvas); - let native_rect = if matches!(f, Fill::Solid(_)) { Rect::new(0, 0, 1, 1) } else { rect }; - match gradient_fill::render_cmyk_fill(f, native_rect, frame, cx.depth) { - Some(s) if matches!(f, Fill::Solid(_)) => Buffer::filled(rect, s.rgba(0, 0)), - Some(s) => surface_to_buffer(&s, rect), - None => render_fill(f, rect, frame, cx.patterns, adjustment_quantum(cx.depth)), - } - } - _ => render_fill(f, rect, fill_frame(layer, cx.canvas), cx.patterns, adjustment_quantum(cx.depth)), - }, - LayerContent::Adjustment(_) => return None, - _ => match layer.surface() { - Some(s) => surface_to_scratch(s, rect), - None => Buffer::transparent(rect), - }, - }; - if let Some(m) = mask_vals(layer, rect, cx) { - for (p, k) in buf.px.iter_mut().zip(&m) { - p[3] *= k; - } - } - Some(buf) -} - -/// The shape `layer`'s effect maps are built from over `rect` (row-major; for the GPU -/// compositor): its content's alpha (masks applied), joined with the [`effect_outline`] of a -/// filled shape. Zero for adjustment layers. -/// -/// See also [`stroke_frame`]. -pub fn layer_shape(doc: &Document, layer: &Layer, rect: Rect) -> Vec { - let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(doc.pixel_format().mode); - let cx = Ctx::for_doc(doc, &patterns); - effect_shape(layer, rect, &cx) -} - -/// The frame a gradient stroke `st` of `layer` is laid out in (`effects::FxMaps::stroke_frame`), -/// from the layer's cached effect maps; `None` when `st` isn't a gradient stroke of the layer. -/// For the GPU compositor. -pub fn stroke_frame(doc: &Document, layer: &Layer, st: &photocraft_doc::StrokeFx) -> Option { - if !matches!(st.paint, photocraft_doc::FxPaint::Gradient(_)) || !effects::has_effects(layer) { - return None; - } - let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(doc.pixel_format().mode); - let cx = Ctx::for_doc(doc, &patterns); - effect_maps(layer, doc.bounds(), &cx).stroke_frame(st) -} - -pub fn surface_to_buffer(s: &Surface, rect: Rect) -> Buffer { - let mut px = vec![[0.0f32; 4]; rect.width() as usize * rect.height() as usize]; - s.read_rgba_into(rect, &mut px); - Buffer { rect, px } -} - -fn surface_to_scratch(s: &Surface, rect: Rect) -> Buffer { - let mut buf = scratch_buffer(rect); - s.read_rgba_into(rect, &mut buf.px); - buf -} - -/// The frame a fill layer's gradient is laid out in ("Align with layer", Photoshop's default): -/// the layer's bounds, i.e. the area its masks reveal: a hide-all pixel mask's painted area, or -/// the vector mask's path; otherwise the canvas. -pub fn fill_frame(layer: &Layer, canvas: Rect) -> Rect { - let mut frame = canvas; - // "Align with layer" off: the canvas (the Gradient tool's live gradients). - if let LayerContent::Fill(Fill::Gradient { align: false, .. }) = &layer.content { - return frame; - } - if let Some(m) = &layer.mask - && m.enabled - && m.surface.default_pixel().first().is_some_and(|v| *v <= 0.0) - { - let b = bounds::content_bounds(&m.surface).intersect(&canvas); - if !b.is_empty() { - frame = b; - } - } - if let Some(vm) = &layer.vector_mask - && vm.enabled - && !vm.path.inverted - && let Some((x0, y0, x1, y1)) = vm.path.control_bounds() - { - let b = Rect::new(x0.floor() as i32, y0.floor() as i32, x1.ceil() as i32, y1.ceil() as i32).intersect(&frame); - if !b.is_empty() { - frame = b; - } - } - frame -} - -/// A fill layer's content over `canvas`, laid out in the frame its masks give it (as the -/// compositor does) but without applying the masks: the pixels a PSD fill layer stores. -pub fn render_fill_content(layer: &Layer, f: &Fill, canvas: Rect, patterns: &[Pattern]) -> Buffer { - let prepared = pattern::PreparedPatterns::new(patterns, pattern::PREPARED_PATTERN_BYTES); - render_fill(f, canvas, fill_frame(layer, canvas), &prepared, None) -} - -/// `quantum`: the document depth's levels, which a dithered gradient is rounded to -/// ([`gradient_fill::render_quantized`]); `None` keeps it in float. -fn render_fill(f: &Fill, rect: Rect, canvas: Rect, patterns: &pattern::PreparedPatterns<'_>, quantum: Option) -> Buffer { - match f { - Fill::Solid(c) => { - let rgb = c.to_rgb(); - Buffer::filled(rect, [rgb[0], rgb[1], rgb[2], c.alpha]) - } - // Gradient geometry relative to the layer's frame, independent of the render rect. - Fill::Gradient { .. } => Buffer { rect, px: gradient_fill::render_quantized(f, rect, canvas, quantum) }, - // Laid out from the layer's frame when linked; transparent if the pattern is missing. - Fill::Pattern { name, scale, id, angle, link, phase } => match patterns.get(id, name) { - Some(tile) => Buffer { rect, px: pattern::render(&tile, &pattern::Placement::new(canvas, *link, *phase, *scale, *angle), rect) }, - None => Buffer::transparent(rect), - }, - } -} - -/// `true` when a pixel-backed layer has nothing to contribute in `rect`: -/// no allocated tiles there, a transparent default, and no effects (which -/// could reach in from outside). Clipped layers depend on the base, so they -/// vanish with it. -fn empty_in(layer: &Layer, rect: Rect) -> bool { - if effects::has_effects(layer) { - // Effects reach at most `margin` beyond the layer's pixels (when it is transparent - // outside them; a group's from its children with their effects): render tiles away from a - // small text layer skip it entirely. - let canvas = Rect::new(i32::MIN / 4, i32::MIN / 4, i32::MAX / 4, i32::MAX / 4); - let bounds = shapeless_stroke_bounds(layer).unwrap_or_else(|| effect_source_bounds(layer, canvas)); - return transparent_outside(layer) && bounds.inflate(effects::margin(layer)).intersect(&rect).is_empty(); - } - match &layer.content { - LayerContent::Raster(_) | LayerContent::Text(_) | LayerContent::Shape(_) | LayerContent::Smart(_) => match layer.surface() { - Some(s) => !s.has_tiles_in(rect) && s.default_pixel().last().is_some_and(|a| *a <= 0.0) && s.format().alpha, - None => true, - }, - _ => false, - } -} - -/// For the narrow `tsly=0` case where only local stroke effects are enabled, the effects cannot -/// contribute outside the stroke reach from the layer's pixels. Other `tsly=0` effects can cover -/// the full layer, and advanced blending can change the backdrop independently of those pixels. -fn shapeless_stroke_bounds(layer: &Layer) -> Option { - use photocraft_doc::Knockout; - - if layer.advanced.transparency_shapes - || layer.advanced.knockout != Knockout::None - || layer.advanced.blend_interior - || layer.clipped - || !layer.blend_if.is_default() - || layer.mask.as_ref().is_some_and(|m| m.enabled) - || layer.vector_mask.as_ref().is_some_and(|m| m.enabled) - || !transparent_outside(layer) - || !effects::maps_are_local(layer) - { - return None; - } - - if !layer.effects.enabled - || !layer.effects.items.iter().any(|e| e.enabled()) - || layer.effects.items.iter().any(|e| e.enabled() && !matches!(e, photocraft_doc::Effect::Stroke(_))) - { - return None; - } - - match &layer.content { - LayerContent::Raster(_) | LayerContent::Text(_) | LayerContent::Shape(_) | LayerContent::Smart(_) => { - let b = layer.surface().map_or(Rect::EMPTY, bounds::content_bounds); - // A filled shape's effects follow its outline, also where its fill is transparent (as - // in `layer_bounds`). - Some(match effect_outline(layer).and_then(|_| paint_bounds(layer)) { - Some(p) if !b.is_empty() => b.union(&p), - Some(p) => p, - None => b, - }) - } - _ => None, - } -} - -/// Blending Options › Channels as per-channel weights over display RGB (1 = the layer's result, -/// 0 = the backdrop's value kept), or `None` when every channel blends. RGB documents map R, G, B -/// directly and a grayscale document's single channel covers all three; other modes composite in -/// display RGB, where a restriction to their own channels has no exact equivalent, so it is -/// ignored there. -pub fn channel_weights(layer: &Layer, mode: photocraft_color::ColorMode) -> Option<[f32; 3]> { - use photocraft_color::ColorMode as M; - let x = layer.excluded_channels; - if x == 0 { - return None; - } - let keep = |bit: u32| if x & (1 << bit) != 0 { 0.0 } else { 1.0 }; - match mode { - M::Rgb => Some([keep(0), keep(1), keep(2)]), - M::Grayscale | M::Duotone => Some([keep(0); 3]), - _ => None, - } - .filter(|w| w != &[1.0; 3]) -} - -/// Put back the backdrop's values in the channels a layer leaves out (`w` from -/// [`channel_weights`]); alpha stays the layer's result. -fn restore_channels(out: &mut Buffer, before: &Buffer, w: [f32; 3]) { - for (p, b) in out.px.iter_mut().zip(&before.px) { - for c in 0..3 { - p[c] = b[c] + (p[c] - b[c]) * w[c]; - } - } -} - -/// Where `layer`'s composite (its pixels and effects; a group's visible children with theirs) can -/// be non-transparent, or `None` when it may draw anywhere (a surface with an opaque default -/// pixel). Outside it, compositing the layer leaves the backdrop unchanged in every blend mode. -/// Adjustment layers count as empty: they only change pixels already there (which is what an -/// isolated group needs; see [`change_bounds`] for the document-level question). -pub fn composite_bounds(layer: &Layer, canvas: Rect) -> Option { - if !transparent_outside(layer) { - return None; - } - let own = match &layer.content { - LayerContent::Group(g) if g.artboard.is_none() => { - let mut acc = Rect::EMPTY; - for c in g.children.iter().filter(|c| c.visible) { - let b = composite_bounds(c, canvas)?; - if !b.is_empty() { - acc = if acc.is_empty() { b } else { acc.union(&b) }; - } - } - acc - } - LayerContent::Adjustment(_) => Rect::EMPTY, - _ => layer_bounds(layer, canvas), - }; - if own.is_empty() { - return Some(Rect::EMPTY); - } - let m = if effects::has_effects(layer) { effects::margin(layer) } else { 0 }; - Some(own.inflate(m).intersect(&canvas)) -} - -/// The document pixels that showing, hiding, moving or restyling `layer` can change, or `None` -/// for anywhere: an adjustment layer (and a pass-through group holding one) reaches everything -/// beneath it. Clipped layers above stay within their base's bounds, so they are covered too; -/// effects of groups around the layer can reach further (callers grow the rect by that reach). -pub fn change_bounds(layer: &Layer, canvas: Rect) -> Option { - fn reaches_below(l: &Layer) -> bool { - match &l.content { - LayerContent::Adjustment(_) => !l.clipped, - // Clipped to a base, an adjustment changes only the base's pixels; one with no base - // beneath it in its list composites as an ordinary adjustment (#6535). - LayerContent::Group(g) if l.blend == BlendMode::PassThrough => g.children.iter().enumerate().any(|(k, c)| { - let orphan = - c.clipped && matches!(c.content, LayerContent::Adjustment(_)) && g.children.get(..k).is_none_or(|below| below.iter().all(|b| b.clipped)); - orphan || reaches_below(c) - }), - _ => false, - } - } - if matches!(layer.content, LayerContent::Adjustment(_)) || reaches_below(layer) { - return None; - } - composite_bounds(layer, canvas) -} - -/// [`change_bounds`] of `layers[k]` in its sibling list (bottom→top), which also bounds a clipped -/// adjustment layer: it changes only its clip base's pixels, so it reaches as far as showing, -/// hiding or restyling that base does (#6535). Still `None` when there is no base below it (the -/// compositor then draws it as an ordinary adjustment) or the base is an adjustment itself -/// (layers clipped to one composite atop the adjusted backdrop, everywhere). `outer` is the list -/// holding the group whose children `layers` are, and that group's index there (`None` at the -/// top level): a pass-through group that is a clip base renders isolated while it holds a visible -/// adjustment, so showing or hiding one inside can change the whole group. -pub fn change_bounds_in(layers: &[Layer], k: usize, outer: Option<(&[Layer], usize)>, canvas: Rect) -> Option { - let layer = layers.get(k)?; - if layer.clipped && matches!(layer.content, LayerContent::Adjustment(_)) { - let base = layers.get(..k)?.iter().rev().find(|l| !l.clipped)?; - if matches!(base.content, LayerContent::Adjustment(_)) { - return None; - } - if let Some((outer, g)) = outer - && let Some(group) = outer.get(g) - && group.blend == BlendMode::PassThrough - && !group.clipped - && outer.get(g + 1).is_some_and(|above| above.clipped) - { - // The group bounds its base too. - return change_bounds(group, canvas); - } - return change_bounds(base, canvas); - } - change_bounds(layer, canvas) -} - -/// Whether the layer's content is transparent outside its bounds (every surface it draws from -/// has a transparent default pixel), so its effects can't change pixels beyond its bounds grown -/// by their reach. -pub fn transparent_outside(layer: &Layer) -> bool { - match &layer.content { - LayerContent::Group(g) => g.children.iter().filter(|c| c.visible).all(transparent_outside), - // Fill layers cover the canvas (their bounds); adjustments draw nothing of their own. - LayerContent::Fill(_) | LayerContent::Adjustment(_) => true, - _ => layer.surface().is_none_or(|s| s.format().alpha && s.default_pixel().last().is_some_and(|a| *a <= 0.0)), - } -} - -/// Whether `layer` replaces everything beneath it in its stack: a visible, unclipped fill layer -/// in Normal mode at full opacity and fill, without masks, effects, channel restrictions or Blend -/// If, whose fill is opaque everywhere (a solid colour, or a gradient whose colour and opacity -/// stops are all opaque). Normal blending at alpha 1 returns the layer's colour exactly, so the -/// layers below can be skipped (the live Gradient tool's preview recomposites the whole canvas on -/// every pointer move). -pub fn occludes_below(layer: &Layer, mode: photocraft_color::ColorMode) -> bool { - let LayerContent::Fill(f) = &layer.content else { return false }; - let opaque = match f { - Fill::Solid(c) => c.alpha >= 1.0, - Fill::Gradient { stops, opacity_stops, .. } => { - !stops.is_empty() && stops.iter().all(|(_, c)| c.alpha >= 1.0) && opacity_stops.iter().all(|(_, o)| *o >= 1.0) - } - Fill::Pattern { .. } => false, - }; - // A cached render in use (a PSD's stored fill pixels) may not be opaque. - let cached = layer.fill_cache.as_ref().is_some_and(|c| c.fill == *f); - opaque - && !cached - && layer.visible - && !layer.clipped - && layer.blend == photocraft_color::BlendMode::Normal - && layer.opacity >= 1.0 - && layer.fill_opacity >= 1.0 - && !layer.mask.as_ref().is_some_and(|m| m.enabled) - && !layer.vector_mask.as_ref().is_some_and(|m| m.enabled) - && !effects::has_effects(layer) - && layer.excluded_channels == 0 - && !blend_if_active(layer, mode) -} - -/// Whether Blending Options › Blend If changes how `layer` composites in a `mode` document. -/// RGB documents test Gray and R, G, B; grayscale (and duotone) documents their one channel. -/// Other modes composite in display RGB, where ranges over their own channels have no exact -/// equivalent, so (like channel restrictions) the setting round-trips but isn't applied there. -pub fn blend_if_active(layer: &Layer, mode: photocraft_color::ColorMode) -> bool { - use photocraft_color::ColorMode as M; - matches!(mode, M::Rgb | M::Grayscale | M::Duotone) && !layer.blend_if.is_default() -} - -/// How much of a pixel shows through `layer`'s Blend If ranges, given the layer's own colour -/// (`this`, `None` where the layer has no content of its own there) and the colour beneath it -/// (`under`, `None` where nothing is beneath). Every range multiplies in. -fn blend_if_weight(layer: &Layer, mode: photocraft_color::ColorMode, this: Option<[f32; 4]>, under: Option<[f32; 4]>) -> f32 { - use photocraft_color::ColorMode as M; - let bi = &layer.blend_if; - let mut k = 1.0; - for (side, px) in [this, under].into_iter().enumerate() { - let Some(p) = px else { continue }; - let v = |c: usize| blend_if_level(p[c]); - match mode { - // Gray is the colour channels' luma (Rec. 601 weights), then R, G, B. - M::Rgb => { - let gray = 0.299 * v(0) + 0.587 * v(1) + 0.114 * v(2); - k *= bi.get(0)[side].weight(gray); - for c in 0..3 { - k *= bi.get(c + 1)[side].weight(v(c)); - } - } - // One channel: the PSD spec marks the composite-gray entry irrelevant here, so the - // channel's own entry carries the setting; both are honoured. - _ => k *= bi.get(0)[side].weight(v(0)) * bi.get(1)[side].weight(v(0)), - } - if k <= 0.0 { - return 0.0; - } - } - k -} - -/// A channel value on Blend If's 0..=255 scale. Compositing can leave an 8- or 16-bit level a few -/// millionths off (a level-20 backdrop composited at partial alpha reads 19.999998), which would -/// put it on the wrong side of a hard point at that level: a value that close to a level is that -/// level. Values of those depths that aren't on a level are at least 1/257 away from one. The GPU -/// compositor (`compose.wgsl` `blend_if_weight`) snaps alike. -fn blend_if_level(x: f32) -> f32 { - let v = x.clamp(0.0, 1.0) * 255.0; - let r = v.round(); - if (v - r).abs() < 1e-4 { r } else { v } -} - -/// Blend If groups inside one another whose own colour is still rendered separately. Each extra -/// level multiplies the work by the tree's depth, so the cost is polynomial, not exponential. -const MAX_BLEND_IF_GROUP_DEPTH: u32 = 2; - -thread_local! { - /// Blend If groups being rendered for their own colour on this thread. - static BLEND_IF_GROUPS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// Apply `layer`'s Blend If to a finished composite: `out` (the backdrop with the layer drawn) -/// is mixed back towards `before` (the backdrop without it) where the ranges hide the layer. -/// Mixing premultiplied colour by `k` equals compositing the layer at `k` × its alpha, since -/// every blend mode's source-over result is linear in the source alpha. -fn apply_blend_if(layer: &Layer, before: &Buffer, out: &mut Buffer, cx: &Ctx) { - // "This Layer" is the layer's own colour; adjustment layers (no content of their own) are - // judged by their result. So are groups nested deeper than `MAX_BLEND_IF_GROUP_DEPTH` Blend - // Ifs: a group's own colour re-composites its children, which doubles the work at every - // level of Blend If groups inside one another. - let is_group = matches!(layer.content, LayerContent::Group(_)); - let nested = BLEND_IF_GROUPS.with(std::cell::Cell::get); - let own = if matches!(layer.content, LayerContent::Adjustment(_)) || (is_group && nested >= MAX_BLEND_IF_GROUP_DEPTH) { - None - } else { - BLEND_IF_GROUPS.with(|d| d.set(nested + u32::from(is_group))); - let own = render_content(layer, out.rect, cx); - BLEND_IF_GROUPS.with(|d| d.set(nested)); - own - }; - for (i, (p, b)) in out.px.iter_mut().zip(&before.px).enumerate() { - let this = match &own { - Some(o) => Some(o.px[i]).filter(|q| q[3] > 0.0), - None => Some(*p), - }; - let under = Some(*b).filter(|q| q[3] > 0.0); - let k = blend_if_weight(layer, cx.mode, this, under); - if k >= 1.0 { - continue; - } - let a = b[3] + (p[3] - b[3]) * k; - *p = if a > 0.0 { - let c = |c: usize| ((b[c] * b[3] + (p[c] * p[3] - b[c] * b[3]) * k) / a).clamp(0.0, 1.0); - [c(0), c(1), c(2), a] - } else { - [0.0; 4] - }; - } -} - -/// Composite `layer` (plus its clipping group) onto `backdrop`, honouring its channel restrictions -/// and Blend If, and knocking out to `ko` when it has a knockout (see [`advanced`]). -fn composite_layer(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffer, cx: &Ctx, ko: Option<&Buffer>, scope: advanced::Scope) { - // Blend Clipped Layers as Group off: the base alone, then each clipped layer in its own mode. - if advanced::clips_individually(layer, clipped) { - advanced::composite_clipped_individually(layer, clipped, backdrop, cx, ko, scope); - return; - } - let w = channel_weights(layer, cx.mode); - let blend_if = blend_if_active(layer, cx.mode); - let before = (w.is_some() || blend_if).then(|| backdrop.clone()); - match ko { - Some(target) => advanced::knockout(layer, backdrop, target, false, cx, |b| composite_layer_any(layer, clipped, b, cx, scope)), - None => composite_layer_any(layer, clipped, backdrop, cx, scope), - } - if let Some(before) = &before { - if let Some(w) = w { - restore_channels(backdrop, before, w); - } - if blend_if { - apply_blend_if(layer, before, backdrop, cx); - } - } -} - -fn composite_layer_any(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffer, cx: &Ctx, scope: advanced::Scope) { - if let LayerContent::Group(g) = &layer.content - && let Some(ab) = &g.artboard - { - composite_artboard(layer, ab, clipped, backdrop, cx, scope); - return; - } - composite_layer_plain(layer, clipped, backdrop, cx, scope); -} - -/// An artboard: its background and the group, composited only inside the board (contents and -/// effects outside it are clipped away; the backdrop there is untouched). -fn composite_artboard(layer: &Layer, ab: &photocraft_doc::Artboard, clipped: &[Layer], backdrop: &mut Buffer, cx: &Ctx, scope: advanced::Scope) { - let board = ab.rect.intersect(&backdrop.rect); - if board.is_empty() { - return; - } - let (bw, w) = (board.width() as usize, backdrop.rect.width() as usize); - let row0 = |y: i32| (y - backdrop.rect.y0) as usize * w + (board.x0 - backdrop.rect.x0) as usize; - let mut sub = Buffer::transparent(board); - for y in board.y0..board.y1 { - let o = row0(y); - let so = (y - board.y0) as usize * bw; - sub.px[so..so + bw].copy_from_slice(&backdrop.px[o..o + bw]); - } - if let Some(bg) = ab.background.rgba() { - blend_into(&mut sub, &Buffer::filled(board, bg), BlendMode::Normal, 1.0); - } - composite_layer_plain(layer, clipped, &mut sub, cx, scope); - for y in board.y0..board.y1 { - let o = row0(y); - let so = (y - board.y0) as usize * bw; - backdrop.px[o..o + bw].copy_from_slice(&sub.px[so..so + bw]); - } -} - -/// The surface `render_content` reads `layer`'s pixels from, when that is all it draws. -fn pixel_surface(layer: &Layer) -> Option<&Surface> { - if matches!(layer.content, LayerContent::Group(_) | LayerContent::Fill(_) | LayerContent::Adjustment(_)) { - return None; - } - layer.surface() -} - -/// A pixel layer (nothing clipped to it) onto `backdrop`, read from its tiles a row at a time: -/// the same arithmetic as `render_content` + `blend_into_fill`, without a tile-sized copy of the -/// layer (a megabyte per 256² render tile). -fn composite_pixel_layer(layer: &Layer, surf: &Surface, backdrop: &mut Buffer, cx: &Ctx) { - let rect = backdrop.rect; - let w = rect.width() as usize; - if w == 0 { - return; - } - let mv = mask_vals(layer, rect, cx); - let gamma = text_gamma(layer); - let mut row = vec![[0.0f32; 4]; w]; - for (ry, dst) in backdrop.px.chunks_exact_mut(w).enumerate() { - let y = rect.y0 + ry as i32; - surf.read_rgba_into(Rect::new(rect.x0, y, rect.x1, y + 1), &mut row); - if let Some(m) = mv.as_ref().and_then(|m| m.get(ry * w..(ry + 1) * w)) { - for (p, k) in row.iter_mut().zip(m) { - p[3] *= k; - } - } - blend_span_fill(dst, &row, rect.x0, y, layer.blend, layer.opacity, layer.fill_opacity, gamma); - } -} - -fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffer, cx: &Ctx, scope: advanced::Scope) { - let rect = backdrop.rect; - // A TSL-off stroke base that is transparent here can still have visible clipped siblings; - // keep the full clipping path for it instead of the stroke-bounds shortcut. Other bases keep - // the usual skip (their clipped layers vanish with them). - if (clipped.is_empty() || shapeless_stroke_bounds(layer).is_none()) && empty_in(layer, rect) { - return; - } - let opacity = layer.opacity * layer.fill_opacity; - - // Pass-through groups composite their children straight into the backdrop. Below 100% fill - // Photoshop renders the group isolated, like Normal (psd-tools passthrough_fill_*: an - // adjustment inside no longer reaches the layers beneath), and so it does for a group that - // is the base of a clipping group and holds an adjustment layer (psd-tools - // passthrough_clipping_mask_adjustment: an Exposure inside leaves the layers beneath alone), - // while such a group's blend modes still reach the backdrop (passthrough_clipping_mask_blendmode). - let clip_base_adjusts = clipped.iter().any(|c| c.visible) - && matches!(&layer.content, LayerContent::Group(g) if g.children.iter().any(|c| c.visible && matches!(c.content, LayerContent::Adjustment(_)))); - if let LayerContent::Group(g) = &layer.content - && layer.blend == BlendMode::PassThrough - && layer.fill_opacity >= 1.0 - && !effects::has_effects(layer) - && !clip_base_adjusts - { - let needs_mix = opacity < 1.0 || layer.mask.is_some() || layer.vector_mask.is_some(); - let has_clipped = clipped.iter().any(|c| c.visible); - // Children can draw directly unless mixing or clipping needs the original backdrop. - let before = (needs_mix || has_clipped).then(|| backdrop.clone()); - composite_stack_at(&g.children, backdrop, cx, scope.pass_through()); - if needs_mix && let Some(before) = &before { - let mv = mask_vals(layer, rect, cx); - for (i, (p, a)) in backdrop.px.iter_mut().zip(&before.px).enumerate() { - let k = opacity * mask_k(&mv, i); - let b = *p; - // Coverage mixes premultiplied colour; the stored buffer remains straight alpha. - let wa = a[3] * (1.0 - k); - let wb = b[3] * k; - let alpha = wa + wb; - *p = if alpha > 0.0 { - let c = |c: usize| (a[c] * wa + b[c] * wb) / alpha; - [c(0), c(1), c(2), alpha] - } else { - [0.0; 4] - }; - } - } - // Layers clipped to a pass-through group sit atop the group's - // isolated rendering; their effect (isolated result with vs. without - // them, each placed over the original backdrop) is added to the - // pass-through result. Exact when the children blend Normal, close - // otherwise (matches psd-tools clipping-mask3/4/5). - if has_clipped && let (Some(before), Some(iso)) = (before, render_content(layer, rect, cx)) { - let mut clipped_iso = iso.clone(); - advanced::composite_clipped(clipped, &mut clipped_iso, cx); - let mut without = before.clone(); - blend_into(&mut without, &iso, BlendMode::Normal, opacity); - let mut with = before; - blend_into(&mut with, &clipped_iso, BlendMode::Normal, opacity); - for ((p, w), wo) in backdrop.px.iter_mut().zip(&with.px).zip(&without.px) { - // Work premultiplied so transparent areas stay consistent. - let pa = p[3]; - let mut pm = [p[0] * pa, p[1] * pa, p[2] * pa, pa]; - for c in 0..3 { - pm[c] += w[c] * w[3] - wo[c] * wo[3]; - } - pm[3] += w[3] - wo[3]; - let a = pm[3].clamp(0.0, 1.0); - *p = if a > 0.0 { [(pm[0] / a).clamp(0.0, 1.0), (pm[1] / a).clamp(0.0, 1.0), (pm[2] / a).clamp(0.0, 1.0), a] } else { [0.0; 4] }; - } - } - return; - } - - // Adjustment layers transform the backdrop, then blend the result back in. - if let LayerContent::Adjustment(adj) = &layer.content { - let mv = mask_vals(layer, rect, cx); - if mv.as_ref().is_some_and(|values| values.iter().all(|&value| opacity * value <= 0.0)) { - return; - } - let mut adjusted = scratch_buffer(rect); - adjusted.px.copy_from_slice(&backdrop.px); - cx.apply_adjustment(adj, &mut adjusted); - // Clipped layers onto an adjustment are uncommon; they composite atop the adjusted result. - advanced::composite_clipped(clipped, &mut adjusted, cx); - if layer.blend == BlendMode::Dissolve { - // An adjustment has no standalone source alpha. Its effective coverage comes from its - // own opacity and mask, not a continuous RGB mix (#3050). - for y in rect.y0..rect.y1 { - for x in rect.x0..rect.x1 { - let i = ((y - rect.y0) as usize) * rect.width() as usize + (x - rect.x0) as usize; - let k = opacity * mask_k(&mv, i); - if k > 0.0 && dissolve_noise(x, y) < k { - let a = adjusted.px[i]; - backdrop.px[i] = [a[0], a[1], a[2], backdrop.px[i][3]]; - } - } - } - } else { - match &mv { - Some(m) => blend_back(&mut backdrop.px, &adjusted.px, m.iter().map(|v| opacity * v), layer.blend), - None => blend_back(&mut backdrop.px, &adjusted.px, std::iter::repeat(opacity), layer.blend), - } - } - recycle_buffer(adjusted); - return; - } - - if effects::has_effects(layer) { - // Layer / Vector Mask Hides Effects: the effects are built without that mask, which then - // hides the finished layer and effects. - let src = advanced::effects_source(layer); - let hide = advanced::hiding_mask(layer, rect, cx); - let before = hide.as_ref().map(|_| backdrop.clone()); - composite_layer_effects(&src, clipped, backdrop, cx); - if let (Some(m), Some(b)) = (&hide, &before) { - advanced::apply_hiding_mask(backdrop, b, m); - } - return; - } - if let Some((mut content, stroke, mask)) = shape_parts(layer, clipped, rect, cx) { - advanced::composite_clipped(clipped, &mut content, cx); - for (i, (p, s)) in content.px.iter_mut().zip(&stroke.px).enumerate() { - *p = psblend::composite(BlendMode::Normal, *p, *s, 1.0); - p[3] *= mask_k(&mask, i); - } - blend_into_fill(backdrop, &content, layer.blend, layer.opacity, layer.fill_opacity, 1.0); - return; - } - if !matches!(layer.content, LayerContent::Group(_) | LayerContent::Fill(_) | LayerContent::Adjustment(_)) - && let Some(s) = layer.surface() - && layer.blend == BlendMode::Normal - && opacity >= 1.0 - && !clipped.iter().any(|c| c.visible) - && layer.mask.is_none() - && layer.vector_mask.is_none() - && text_gamma(layer) == 1.0 - && !psblend::LAB_MIX.with(|l| l.get()) - && backdrop.px.iter().all(|p| p[3] <= 0.0) - { - s.read_rgba_into(rect, &mut backdrop.px); - for p in &mut backdrop.px { - if p[3] <= 0.0 { - *p = [0.0; 4]; - } else if p[3] < 1.0 { - *p = psblend::composite_normal_rgb([0.0; 4], *p, 1.0); - } - } - return; - } - if clipped.is_empty() - && let Some(surf) = pixel_surface(layer) - { - return composite_pixel_layer(layer, surf, backdrop, cx); - } - let Some(mut content) = render_content(layer, rect, cx) else { return }; - advanced::composite_clipped(clipped, &mut content, cx); - blend_into_fill(backdrop, &content, layer.blend, layer.opacity, layer.fill_opacity, text_gamma(layer)); - recycle_buffer(content); -} - -/// A layer with effects (and its clipping group) onto `backdrop`. -fn composite_layer_effects(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffer, cx: &Ctx) { - let rect = backdrop.rect; - // Neighbourhoods are already captured by the full-region effect maps; - // content and effect application only need the output rectangle. - // A stroked shape's vector stroke stays above its clipped layers and interior effects. - let (mut content, vstroke) = match split_parts(layer, rect, cx) { - Some((fill, stroke, mask)) => (fill, Some((stroke, mask))), - None => { - let Some(content) = render_content(layer, rect, cx) else { return }; - (content, None) - } - }; - advanced::composite_clipped(clipped, &mut content, cx); - let vstroke = vstroke.as_ref().map(|(s, m)| effects::VectorStroke { stroke: s, mask: m.as_deref() }); - let maps = effect_maps(layer, rect, cx); - effects::composite_with_effects_prepared(layer, &content, backdrop, &maps, effects_frame(layer, cx.canvas), cx.patterns, vstroke); -} - -/// The coverage-mixing gamma of a layer: the text blending gamma -/// ([`psblend::set_text_gamma`], Photoshop's default 1.45) for type layers, else 1. -pub fn text_gamma(layer: &Layer) -> f32 { - if matches!(layer.content, LayerContent::Text(_)) { psblend::text_gamma() } else { 1.0 } -} - -/// A stroked shape layer with visible clipped layers: Photoshop draws the shape's vector stroke -/// above the clipped layers, so the base content is the fill alone and the stroke is laid on top -/// after clipping. See [`split_parts`]. -fn shape_parts(layer: &Layer, clipped: &[Layer], rect: Rect, cx: &Ctx) -> Option<(Buffer, Buffer, Option>)> { - if !clipped.iter().any(|c| c.visible) { - return None; - } - split_parts(layer, rect, cx) -} - -/// A stroked shape layer's (fill, vector stroke, mask values) over `rect`; `None` for other -/// layers. Fill and stroke are unmasked: the mask applies to them together. Layer effects paint -/// the fill's interior effects beneath the vector stroke (psd-tools stroke-composite: a colour -/// overlay leaves the stroke, the stroke effect covers it). -fn split_parts(layer: &Layer, rect: Rect, cx: &Ctx) -> Option<(Buffer, Buffer, Option>)> { - let LayerContent::Shape(sh) = &layer.content else { return None }; - sh.stroke.as_ref()?; - let (fs, ss) = shape_split::split(sh, cx.canvas, cx.depth)?; - Some((surface_to_buffer(&fs, rect), surface_to_buffer(&ss, rect), mask_vals(layer, rect, cx))) -} - -// --------------------------------------------------------------------------------------------- -// Layer-effect map cache - -/// Order-independent identity of a layer's pixels, masks, effects, Advanced Blending and Blend If -/// and (for groups) children. -/// Pixels are identified by their copy-on-write tile pointers. `pin` sees every tile hashed: a -/// cache entry keeps a [`std::sync::Weak`] to each, which reserves the tile's address (so no -/// other tile can reuse it and match the key) without keeping its pixels alive (#4530). -fn layer_identity(layer: &Layer, h: &mut std::collections::hash_map::DefaultHasher, pin: &mut dyn FnMut(&std::sync::Arc)) { - use std::hash::{Hash, Hasher}; - fn surface_fp(s: &Surface, pin: &mut dyn FnMut(&std::sync::Arc)) -> u64 { - let mut h = std::collections::hash_map::DefaultHasher::new(); - s.format().hash(&mut h); - // Missing tiles read the default pixel, so tile identity alone is not pixel identity. - for sample in s.default_pixel() { - sample.to_bits().hash(&mut h); - } - let tiles = s.tiles().fold(s.tile_count() as u64, |acc, (c, t)| { - pin(t); - let mut x = (std::sync::Arc::as_ptr(t) as usize as u64) ^ ((c.tx as u64) << 40) ^ ((c.ty as u32 as u64) << 8); - x = x.wrapping_mul(0x9e37_79b9_7f4a_7c15); - acc.wrapping_add(x ^ (x >> 29)) - }); - tiles.hash(&mut h); - h.finish() - } - layer.id.0.hash(h); - // What the maps depend on: `fill_opacity` shades them; layer `opacity` is applied when the - // maps are composited and `visible` only skips the lookup entirely, so neither belongs in - // the key (an opacity drag must not rebuild shadows over the whole layer; the GPU's - // `fx::shape_key` keeps them out for the same reason). - layer.fill_opacity.to_bits().hash(h); - match &layer.content { - LayerContent::Group(g) => { - for c in &g.children { - // A styled group's maps come from its children's composite, so how each child - // composites (unlike the group's own visibility and opacity) shapes them. - (c.visible, c.opacity.to_bits(), c.clipped).hash(h); - format!("{:?}", c.blend).hash(h); - layer_identity(c, h, pin); - } - format!("{:?}", g.artboard).hash(h); - } - LayerContent::Fill(f) => { - format!("{f:?}").hash(h); - // The cached pixels are what shapes the maps while they match the fill: a - // pixel-only rewrite of the cache (Image › Transform, crop) leaves `f` alone, and - // the stale maps would keep shadowing the pre-rewrite shape. - if let Some(c) = &layer.fill_cache - && c.fill == *f - { - surface_fp(&c.surface, pin).hash(h); - } - } - LayerContent::Adjustment(a) => format!("{a:?}").hash(h), - _ => layer.surface().map_or(0, |s| surface_fp(s, pin)).hash(h), - } - if let Some(m) = &layer.mask { - (surface_fp(&m.surface, pin), m.enabled, m.density.to_bits(), m.feather.to_bits()).hash(h); - } - if let Some(vm) = &layer.vector_mask { - format!("{vm:?}").hash(h); - } - format!("{:?}", layer.effects).hash(h); - // Transparency Shapes Layer picks the shape (content or the whole layer); a group child's - // Blend If and knockout change the composite a styled group's shape comes from. - layer.advanced.hash(h); - layer.blend_if.hash(h); - h.write_u8(0xfe); -} - -struct FxEntry { - maps: std::sync::Arc, - /// The tiles the key identifies (see [`layer_identity`]): their addresses, not their pixels. - _pin: Vec>, - bytes: usize, -} - -/// Global cache of effect maps (bounded by bytes), one slot per layer state. Slots are filled -/// with `set`, never `get_or_init`: nothing may block on a build (see `cached_effect_maps`). -type FxSlot = std::sync::Arc>; -struct FxCache { - map: std::collections::HashMap, - order: std::collections::VecDeque, - bytes: usize, -} - -/// Default effect-cache budget (Preferences › Performance can change it). -pub const DEFAULT_FX_CACHE_BUDGET: usize = 768 << 20; -static FX_CACHE_BUDGET: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(DEFAULT_FX_CACHE_BUDGET); - -/// Set the memory budget (bytes) of the layer-effect map cache; entries over it are evicted -/// oldest-first on the next build. -pub fn set_effect_cache_budget(bytes: usize) { - FX_CACHE_BUDGET.store(bytes.max(1 << 20), std::sync::atomic::Ordering::Relaxed); -} - -/// The current effect-cache budget in bytes. -pub fn effect_cache_budget() -> usize { - FX_CACHE_BUDGET.load(std::sync::atomic::Ordering::Relaxed) -} - -/// Bytes currently held by the effect-map cache. -pub fn effect_cache_bytes() -> usize { - fx_cache().lock().unwrap_or_else(|e| e.into_inner()).bytes -} - -/// Drop every cached effect map (Edit › Purge › All). Returns the bytes released. -pub fn purge_effect_cache() -> usize { - let mut c = fx_cache().lock().unwrap_or_else(|e| e.into_inner()); - let freed = c.bytes; - c.map.clear(); - c.order.clear(); - c.bytes = 0; - freed -} - -fn fx_cache() -> &'static std::sync::Mutex { - static C: std::sync::OnceLock> = std::sync::OnceLock::new(); - C.get_or_init(|| std::sync::Mutex::new(FxCache { map: Default::default(), order: Default::default(), bytes: 0 })) -} - -/// Where `layer`'s effect maps are built (see [`effect_maps`]) and whether that is clipped to the -/// rectangle being rendered rather than the whole region. -/// -/// Transparency Shapes Layer off makes the region the whole canvas whatever the layer holds: on a -/// 1920 × 103675 webtoon page each such layer's maps took about 2.4 GB, and a render held them for -/// every layer at once (60 GB with 25 stroked type layers, #1909). When its effects are local -/// ([`effects::maps_are_local`]), such a layer's maps are built over the render rectangle padded -/// by twice the effect reach instead, which gives the same pixels there. So are any layer's local -/// maps when the render's whole-region maps wouldn't fit in the effect cache ([`fx_over_budget`]). -/// Only when `rect`, what -/// the caller composites the layer over, lies within the render rectangle: a group's effect shape -/// (or anything else rendering children over a wider area) gets the whole region. -fn effect_region(layer: &Layer, rect: Rect, cx: &Ctx) -> (Rect, bool) { - let m = effects::margin(layer); - let region = effect_source_bounds(layer, cx.canvas).inflate(m).intersect(&cx.canvas.inflate(m)); - let clip = *cx.fx_clip.lock().unwrap_or_else(|e| e.into_inner()); - match clip { - Some(c) if c.contains_rect(&rect) && (advanced::shapeless(layer) || cx.fx_over_budget) && effects::maps_are_local(layer) => { - let part = region.intersect(&c.inflate(m.saturating_mul(2))); - (part, part != region) - } - _ => (region, false), - } -} - -/// Whether the effect maps of the visible layers of `layers` (groups included), each over its -/// whole region, would take more than the effect cache budget together. A render needs all of -/// them, so when they don't fit, building one evicts the next one needed and every render builds -/// them all again, seconds even for a small rect (#8330). Counted as [`effects::FxMaps::bytes`] -/// counts the built maps ([`effects::map_count`] arrays over each region). -fn fx_over_budget(layers: &[Layer], canvas: Rect) -> bool { - fx_region_bytes(layers, canvas) > effect_cache_budget() as u64 -} - -/// The bytes [`fx_over_budget`] compares with the budget. -fn fx_region_bytes(layers: &[Layer], canvas: Rect) -> u64 { - fn bytes(layers: &[Layer], canvas: Rect, depth: u32) -> u64 { - let mut total = 0u64; - for l in layers.iter().filter(|l| l.visible) { - if effects::has_effects(l) { - let m = effects::margin(l); - let region = effect_source_bounds(l, canvas).inflate(m).intersect(&canvas.inflate(m)); - let maps = effects::map_count(l) as u64; - let px = u64::from(region.width()) * u64::from(region.height()); - total = total.saturating_add(maps.saturating_mul(px).saturating_mul(4)); - } - if let LayerContent::Group(g) = &l.content - && depth < PREPARE_DEPTH - { - total = total.saturating_add(bytes(&g.children, canvas, depth + 1)); - } - } - total - } - bytes(layers, canvas, 0) -} - -/// Most bytes one layer's effect maps and source may take to build, whatever the cache budget. -const MAX_FX_BUILD_BYTES: u64 = if cfg!(target_pointer_width = "64") { 4 << 30 } else { 512 << 20 }; - -/// The layer's effect maps over its region (layer bounds grown by the effect reach, within the -/// canvas grown likewise; see [`effect_region`]), built once per layer state and shared by every -/// tile. `rect` is what the caller composites the layer over (see [`effect_region`]). -fn effect_maps(layer: &Layer, rect: Rect, cx: &Ctx) -> std::sync::Arc { - use std::hash::{Hash, Hasher}; - let (mut region, clipped) = effect_region(layer, rect, cx); - // Non-local effects keep their whole source region, which a few distant pixels stretch over - // the canvas: past the cap the effects are left out instead of allocating it. - let region_px = u64::from(region.width()) * u64::from(region.height()); - if (effects::map_count(layer) as u64 + 1).saturating_mul(region_px).saturating_mul(4) > MAX_FX_BUILD_BYTES { - region = Rect::EMPTY; - } - static NO_CACHE: std::sync::OnceLock = std::sync::OnceLock::new(); - if *NO_CACHE.get_or_init(|| std::env::var_os("PHOTOCRAFT_FX_NOCACHE").is_some()) { - let shape = if region.is_empty() { Vec::new() } else { effect_shape(layer, region, cx) }; - return std::sync::Arc::new(effects::build_maps_prepared(layer, shape, region, &cx.light, &texture_ctx(layer, region, cx), cx.patterns)); - } - let mut h = std::collections::hash_map::DefaultHasher::new(); - cx.layer_keys.identity(layer, cx.doc).hash(&mut h); - (region.x0, region.y0, region.x1, region.y1).hash(&mut h); - (cx.light.angle.to_bits(), cx.light.altitude.to_bits()).hash(&mut h); - let key = h.finish(); - // Prepared for this render (see `prepare_effects`): no global lookup, no build. - if let Some((m, _)) = cx.fx_maps.lock().unwrap_or_else(|e| e.into_inner()).get(&key) { - return m.clone(); - } - let maps = cached_effect_maps(layer, region, key, cx); - cx.fx_maps.lock().unwrap_or_else(|e| e.into_inner()).entry(key).or_insert((maps, clipped)).0.clone() -} - -fn build_fx_slot_maps(layer: &Layer, region: Rect, key: u64, cx: &Ctx, slot: &FxSlot) -> std::sync::Arc { - let shape: Vec = if region.is_empty() { Vec::new() } else { effect_shape(layer, region, cx) }; - let maps = effects::build_maps_prepared(layer, shape, region, &cx.light, &texture_ctx(layer, region, cx), cx.patterns); - let mut pin = Vec::new(); - layer_identity(layer, &mut std::collections::hash_map::DefaultHasher::new(), &mut |t| pin.push(std::sync::Arc::downgrade(t))); - // The maps, plus what each reserved tile address keeps allocated. - let bytes = maps.bytes().saturating_add(pin.len().saturating_mul(std::mem::size_of::() + 2 * std::mem::size_of::())); - let maps = std::sync::Arc::new(maps); - if slot.set(FxEntry { maps: maps.clone(), _pin: pin, bytes }).is_ok() { - // Counted exactly once, by the build that filled the slot, and only while the - // slot is still cached (eviction may have dropped it meanwhile). - let mut c = fx_cache().lock().unwrap_or_else(|e| e.into_inner()); - if c.map.get(&key).is_some_and(|s| std::sync::Arc::ptr_eq(s, slot)) { - c.bytes += bytes; - } - } - // A concurrent build that finished first wins, so every tile shares one map. - slot.get().map_or(maps, |e| e.maps.clone()) -} - -fn evict_fx_cache_over_budget(key: u64) { - let mut c = fx_cache().lock().unwrap_or_else(|e| e.into_inner()); - let budget = effect_cache_budget(); - while c.bytes > budget && c.order.len() > 1 { - let Some(old) = c.order.pop_front() else { break }; - if old == key { - c.order.push_back(old); - continue; - } - if let Some(s) = c.map.remove(&old) { - c.bytes = c.bytes.saturating_sub(s.get().map_or(0, |e| e.bytes)); - } - } -} - -/// The layer's effect maps from the global cache, built on a miss. -/// -/// Never waits for another thread's build (#276): this can run on a Rayon worker inside a tile, -/// and the build itself runs Rayon work. A worker waiting on that work may steal another tile of -/// the same layer; had it blocked on a once-init held further up its own stack, it would deadlock. -/// Instead a miss builds the maps here and the first finished build is kept. Renders build every -/// layer's maps before their parallel tiles (`prepare_effects`), so tiles rarely miss. -fn cached_effect_maps(layer: &Layer, region: Rect, key: u64, cx: &Ctx) -> std::sync::Arc { - let slot = { - let mut c = fx_cache().lock().unwrap_or_else(|e| e.into_inner()); - if let Some(s) = c.map.get(&key) { - s.clone() - } else { - let s: FxSlot = Default::default(); - c.map.insert(key, s.clone()); - c.order.push_back(key); - s - } - }; - let maps = match slot.get() { - Some(e) => e.maps.clone(), - None => build_fx_slot_maps(layer, region, key, cx, &slot), - }; - // Evict the oldest entries over budget (never the one just used). - evict_fx_cache_over_budget(key); - maps -} - -fn texture_ctx<'a>(layer: &Layer, region: Rect, cx: &Ctx<'a>) -> effects::TextureCtx<'a> { - let sb = effects_frame(layer, cx.canvas); - effects::TextureCtx { rect: region, patterns: cx.patterns.source(), anchor: layer.effects.reference.unwrap_or((f64::from(sb.x0), f64::from(sb.y0))) } -} - -/// Composite `layer` onto `base` restricted to the base's alpha (clipping mask semantics), -/// honouring its channel restrictions and Blend If. -fn composite_atop(layer: &Layer, base: &mut Buffer, cx: &Ctx) { - let w = channel_weights(layer, cx.mode); - let blend_if = blend_if_active(layer, cx.mode); - let before = (w.is_some() || blend_if).then(|| base.clone()); - composite_atop_any(layer, base, cx); - if let Some(before) = &before { - if let Some(w) = w { - restore_channels(base, before, w); - } - if blend_if { - apply_blend_if(layer, before, base, cx); - } - } -} - -fn composite_atop_any(layer: &Layer, base: &mut Buffer, cx: &Ctx) { - let rect = base.rect; - if let LayerContent::Adjustment(adj) = &layer.content { - let mut adjusted = base.clone(); - cx.apply_adjustment(adj, &mut adjusted); - let mv = mask_vals(layer, rect, cx); - for (i, p) in base.px.iter_mut().enumerate() { - let k = layer.opacity * layer.fill_opacity * mask_k(&mv, i); - let a = adjusted.px[i]; - if layer.blend == BlendMode::Dissolve { - let x = rect.x0 + (i % rect.width() as usize) as i32; - let y = rect.y0 + (i / rect.width() as usize) as i32; - if dissolve_noise(x, y) < k { - *p = [a[0], a[1], a[2], p[3]]; - } - continue; - } - let bl = blend::blend_rgb(layer.blend, [p[0], p[1], p[2]], [a[0], a[1], a[2]]); - for c in 0..3 { - p[c] += (bl[c] - p[c]) * k; - } - } - return; - } - if effects::has_effects(layer) { - // Effects of a clipped layer are clipped to the base too: render - // them over the base (treated as opaque) and keep the base's alpha. - // The full-region effect maps already capture their neighbourhoods. - // A mask that hides the effects applies to the finished result instead. - let hide = advanced::hiding_mask(layer, rect, cx); - let src = advanced::effects_source(layer); - let layer = src.as_ref(); - let (content, vstroke) = match split_parts(layer, rect, cx) { - Some((fill, stroke, mask)) => (fill, Some((stroke, mask))), - None => { - let Some(content) = render_content(layer, rect, cx) else { return }; - (content, None) - } - }; - let vstroke = vstroke.as_ref().map(|(s, m)| effects::VectorStroke { stroke: s, mask: m.as_deref() }); - let mut opaque = Buffer { rect, px: base.px.iter().map(|p| [p[0], p[1], p[2], 1.0]).collect() }; - let maps = effect_maps(layer, rect, cx); - effects::composite_with_effects_prepared(layer, &content, &mut opaque, &maps, effects_frame(layer, cx.canvas), cx.patterns, vstroke); - if let Some(m) = &hide { - let plain = Buffer { rect, px: base.px.iter().map(|p| [p[0], p[1], p[2], 1.0]).collect() }; - advanced::apply_hiding_mask(&mut opaque, &plain, m); - } - for (p, o) in base.px.iter_mut().zip(&opaque.px) { - if p[3] > 0.0 { - *p = [o[0], o[1], o[2], p[3]]; - } - } - return; - } - let Some(content) = render_content(layer, rect, cx) else { return }; - let opacity = layer.opacity * layer.fill_opacity; - let gamma = text_gamma(layer); - for (i, p) in base.px.iter_mut().enumerate() { - let alpha = p[3]; - if alpha <= 0.0 { - continue; - } - let s = content.px[i]; - if layer.blend == BlendMode::Dissolve { - // Clipping preserves the opaque base's alpha. Dissolve still selects source - // pixels by spatial coverage instead of continuously mixing the colours (#3052). - let x = rect.x0 + (i as i32 % rect.width() as i32); - let y = rect.y0 + (i as i32 / rect.width() as i32); - if dissolve_noise(x, y) < s[3] * opacity { - *p = [s[0], s[1], s[2], alpha]; - } - continue; - } - // Blend as if the base were opaque, then keep the base's alpha. - let r = blend::composite_gamma(layer.blend, [p[0], p[1], p[2], 1.0], s, opacity, gamma); - *p = [r[0], r[1], r[2], alpha]; - } -} - -/// Blend an isolated layer buffer into the backdrop. -fn blend_into(backdrop: &mut Buffer, src: &Buffer, mode: BlendMode, opacity: f32) { - blend_into_g(backdrop, src, mode, opacity, 1.0); -} - -/// [`blend_into_g`] for a layer's own `opacity` and `fill`: Fill is part of the blend for -/// Photoshop's special eight ([`psblend::composite_fill`]), plain coverage otherwise. -fn blend_into_fill(backdrop: &mut Buffer, src: &Buffer, mode: BlendMode, opacity: f32, fill: f32, gamma: f32) { - for_rows(backdrop, src, |dst, s, x0, y| blend_span_fill(dst, s, x0, y, mode, opacity, fill, gamma)); -} - -/// [`blend_into`] mixing coverage in a `gamma` space (type layers). -fn blend_into_g(backdrop: &mut Buffer, src: &Buffer, mode: BlendMode, opacity: f32, gamma: f32) { - for_rows(backdrop, src, |dst, s, x0, y| blend_span_g(dst, s, x0, y, mode, opacity, gamma)); -} - -/// Runs `f(backdrop row, src row, x0, y)` over the rows of two buffers covering the same rect. -fn for_rows(backdrop: &mut Buffer, src: &Buffer, mut f: impl FnMut(&mut [[f32; 4]], &[[f32; 4]], i32, i32)) { - let rect = backdrop.rect; - let w = (rect.width() as usize).max(1); - for (ry, (dst, s)) in backdrop.px.chunks_mut(w).zip(src.px.chunks(w)).enumerate() { - f(dst, s, rect.x0, rect.y0 + ry as i32); - } -} - -/// [`blend_into_fill`] of one row: `dst` and `src` start at pixel (`x0`, `y`). -#[allow(clippy::too_many_arguments)] -fn blend_span_fill(dst: &mut [[f32; 4]], src: &[[f32; 4]], x0: i32, y: i32, mode: BlendMode, opacity: f32, fill: f32, gamma: f32) { - if fill >= 1.0 || !psblend::fill_is_special(mode) { - return blend_span_g(dst, src, x0, y, mode, opacity * fill, gamma); - } - for (b, s) in dst.iter_mut().zip(src) { - if s[3] > 0.0 { - *b = psblend::composite_fill(mode, *b, *s, opacity, fill, gamma); - } - } -} - -/// [`blend_into_g`] of one row: `dst` and `src` start at pixel (`x0`, `y`). -fn blend_span_g(dst: &mut [[f32; 4]], src: &[[f32; 4]], x0: i32, y: i32, mode: BlendMode, opacity: f32, gamma: f32) { - // The blend space is constant in this loop. Some TLS implementations synchronise even a - // boolean read, so select the common Normal kernel once instead of once per pixel. - if mode == BlendMode::Normal && gamma == 1.0 && !psblend::LAB_MIX.with(|l| l.get()) { - return psblend::composite_normal_rgb_span(dst, src, opacity); - } - for (x, (b, s)) in (x0..).zip(dst.iter_mut().zip(src)) { - let mut s = *s; - if s[3] <= 0.0 { - continue; - } - if mode == BlendMode::Dissolve { - s[3] = if dissolve_noise(x, y) < s[3] * opacity { 1.0 } else { 0.0 }; - *b = blend::composite(BlendMode::Normal, *b, s, 1.0); - continue; - } - *b = blend::composite_gamma(mode, *b, s, opacity, gamma); - } -} - #[cfg(test)] mod soft_shape_tests; #[cfg(test)] diff --git a/crates/compose/src/masks.rs b/crates/compose/src/masks.rs index 7335be90d0..851c9bc509 100644 --- a/crates/compose/src/masks.rs +++ b/crates/compose/src/masks.rs @@ -251,358 +251,4 @@ fn build_mask(layer: &Layer, canvas: Rect) -> Surface { } #[cfg(test)] -mod tests { - use super::*; - use photocraft_doc::LayerMask; - use photocraft_doc::vector::{Knot, Path, Subpath, VectorMask}; - - fn pending(c: &Mutex, k: u64) -> Arc> { - match lookup(c, k) { - CachedMask::Pending(slot, _) => slot, - CachedMask::Hit(_) => panic!("expected a cold mask"), - } - } - - /// A built mask (and no pixel-mask input), as `finish_mask`'s build returns it. - fn test_surface() -> (Surface, Option) { - let mut surface = Surface::new(FORMAT); - surface.fill_rect(Rect::new(0, 0, 2, 2), &[0.5]); - (surface, None) - } - - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn cold_callers_share_one_build_without_retaining_a_second_cache() { - use std::sync::Barrier; - use std::sync::atomic::{AtomicUsize, Ordering}; - - let c = Mutex::new(Cache::default()); - // Acquire all callers' slots before allowing any builder to finish. - let slots: Vec<_> = (0..8).map(|_| pending(&c, 7)).collect(); - assert!(slots.iter().all(|slot| Arc::ptr_eq(slot, &slots[0]))); - let barrier = Barrier::new(slots.len()); - let builds = AtomicUsize::new(0); - let outputs = std::thread::scope(|scope| { - let handles: Vec<_> = slots - .iter() - .map(|slot| { - let (c, barrier, builds) = (&c, &barrier, &builds); - scope.spawn(move || { - barrier.wait(); - finish_mask(c, 7, slot, 0, || { - builds.fetch_add(1, Ordering::SeqCst); - test_surface() - }) - }) - }) - .collect(); - handles.into_iter().map(|handle| handle.join().unwrap()).collect::>() - }); - assert_eq!(builds.load(Ordering::SeqCst), 1); - assert!(outputs.iter().all(|surface| Arc::ptr_eq(surface.tiles().next().unwrap().1, outputs[0].tiles().next().unwrap().1))); - - // Evicting the retained result cannot make existing callers build again. - c.lock().unwrap().map.clear(); - let again = finish_mask(&c, 7, &slots[0], 0, || panic!("rebuilt an active slot")); - assert!(Arc::ptr_eq(again.tiles().next().unwrap().1, outputs[0].tiles().next().unwrap().1)); - drop(slots); - let next = pending(&c, 8); - assert_eq!(c.lock().unwrap().in_flight.len(), 1); - drop(next); - } - - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn distinct_keys_build_while_another_key_is_paused() { - use std::sync::mpsc; - use std::time::Duration; - - let c = Mutex::new(Cache::default()); - let (started_tx, started_rx) = mpsc::channel(); - let (release_tx, release_rx) = mpsc::channel(); - let (second_tx, second_rx) = mpsc::channel(); - std::thread::scope(|scope| { - let c = &c; - let first = scope.spawn(move || { - cached_mask(c, 1, || { - started_tx.send(()).unwrap(); - release_rx.recv_timeout(Duration::from_secs(10)).unwrap(); - test_surface() - }) - }); - started_rx.recv_timeout(Duration::from_secs(5)).unwrap(); - let second = scope.spawn(move || { - let surface = cached_mask(c, 2, test_surface); - second_tx.send(surface.sample_channel(0, 0, 0)).unwrap(); - }); - assert!((second_rx.recv_timeout(Duration::from_secs(5)).unwrap() - 0.5).abs() <= 1.0 / f32::from(u16::MAX)); - release_tx.send(()).unwrap(); - first.join().unwrap(); - second.join().unwrap(); - }); - } - - #[test] - fn obsolete_in_flight_build_does_not_repopulate_the_cache() { - let c = Mutex::new(Cache::default()); - let old = pending(&c, 1); - c.lock().unwrap().in_flight.clear(); - let current = pending(&c, 1); - assert!(!Arc::ptr_eq(&old, ¤t)); - let old_surface = finish_mask(&c, 1, &old, 0, test_surface); - assert!(c.lock().unwrap().map.is_empty()); - let current_surface = finish_mask(&c, 1, ¤t, 0, test_surface); - assert!(!Arc::ptr_eq(old_surface.tiles().next().unwrap().1, current_surface.tiles().next().unwrap().1)); - assert_eq!(c.lock().unwrap().map.len(), 1); - } - - #[test] - fn a_purge_during_a_shared_build_keeps_the_cache_empty() { - let c = Mutex::new(Cache::default()); - let CachedMask::Pending(slot, generation) = lookup(&c, 1) else { panic!("expected a cold mask") }; - c.lock().unwrap().clear(); - finish_mask(&c, 1, &slot, generation, test_surface); - assert!(c.lock().unwrap().map.is_empty()); - assert_eq!(c.lock().unwrap().bytes, 0); - } - - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn parallel_feathered_pixel_mask_returns_the_same_tiles() { - let canvas = Rect::new(0, 0, 600, 400); - let mut layer = Layer::raster("cold shared mask", PixelFormat::RGBA8); - let mut mask = photocraft_doc::LayerMask::reveal_all(); - mask.surface.fill_rect(canvas, &[0.5]); - mask.feather = 8.0; - layer.mask = Some(mask); - let barrier = std::sync::Barrier::new(8); - let outputs = std::thread::scope(|scope| { - let handles: Vec<_> = (0..8) - .map(|_| { - let (layer, barrier) = (&layer, &barrier); - scope.spawn(move || { - barrier.wait(); - combined_mask(layer, canvas).unwrap() - }) - }) - .collect(); - handles.into_iter().map(|handle| handle.join().unwrap()).collect::>() - }); - assert!(outputs.iter().all(|surface| Arc::ptr_eq(surface.tiles().next().unwrap().1, outputs[0].tiles().next().unwrap().1))); - } - - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn vector_mask_build_inside_a_small_rayon_pool_completes() { - use rayon::prelude::*; - use std::sync::mpsc; - use std::time::Duration; - - let (tx, rx) = mpsc::channel(); - let handle = std::thread::spawn(move || { - let canvas = Rect::new(0, 0, 512, 512); - let mut layer = Layer::raster("rayon vector mask", PixelFormat::RGBA8); - let mut mask = VectorMask::new(photocraft_vector::shapes::ellipse(8.0, 8.0, 496.0, 496.0)); - mask.feather = 8.0; - layer.vector_mask = Some(mask); - let pool = rayon::ThreadPoolBuilder::new().num_threads(2).build().unwrap(); - let outputs: Vec<_> = pool.install(|| (0..8).into_par_iter().map(|_| combined_mask(&layer, canvas).unwrap()).collect()); - assert!(outputs.iter().all(|surface| Arc::ptr_eq(surface.tiles().next().unwrap().1, outputs[0].tiles().next().unwrap().1))); - tx.send(()).unwrap(); - }); - rx.recv_timeout(Duration::from_secs(10)).expect("mask initializer deadlocked inside Rayon"); - handle.join().unwrap(); - } - - fn one_tile(sample: SampleType) -> Surface { - let mut surface = Surface::with_default(PixelFormat { mode: ColorMode::Grayscale, sample, alpha: false }, &[1.0]); - surface.fill_rect(Rect::new(0, 0, 1, 1), &[0.0]); - surface - } - - #[test] - fn charges_input_and_output_at_every_depth_including_off_canvas_tiles() { - let result = one_tile(SampleType::F32); - for sample in SampleType::ALL { - let mut input = one_tile(sample); - input.fill_rect(Rect::new(1024, 1024, 1025, 1025), &[0.0]); - let tile_pixels = (photocraft_geom::TILE_SIZE * photocraft_geom::TILE_SIZE) as usize; - let expected = tile_pixels * (SampleType::F32.bytes() + 2 * sample.bytes()) + SampleType::F32.bytes() + sample.bytes(); - let bytes = entry_bytes(&result, Some(&input)); - assert_eq!(bytes, expected, "{sample:?}"); - let mut cache = Cache::default(); - cache.insert(1, result.clone(), None, bytes, bytes * 2, cache.generation); - cache.insert(2, result.clone(), None, bytes, bytes * 2, cache.generation); - assert_eq!(cache.bytes, bytes * 2, "shared tiles are conservatively charged per entry"); - } - } - - #[test] - fn byte_budget_evicts_the_least_recently_used_entry() { - let surface = one_tile(SampleType::F32); - let bytes = entry_bytes(&surface, None); - let mut cache = Cache::default(); - cache.insert(1, surface.clone(), None, bytes, bytes * 2, cache.generation); - cache.insert(2, surface.clone(), None, bytes, bytes * 2, cache.generation); - assert!(cache.get(1).is_some()); - cache.insert(3, surface, None, bytes, bytes * 2, cache.generation); - assert!(cache.get(2).is_none()); - assert!(cache.get(1).is_some()); - assert!(cache.get(3).is_some()); - assert_eq!(cache.bytes, bytes * 2); - } - - #[test] - fn entry_limit_also_bounds_masks_with_no_tiles() { - let surface = Surface::new(FORMAT); - let bytes = entry_bytes(&surface, None); - let mut cache = Cache::default(); - for key in 0..CAPACITY as u64 { - cache.insert(key, surface.clone(), None, bytes, CACHE_BUDGET, cache.generation); - } - assert!(cache.get(0).is_some()); - cache.insert(CAPACITY as u64, surface, None, bytes, CACHE_BUDGET, cache.generation); - assert_eq!(cache.map.len(), CAPACITY); - assert!(cache.get(1).is_none()); - assert!(cache.get(0).is_some()); - assert_eq!(cache.bytes, bytes * CAPACITY); - } - - #[test] - fn oversized_results_are_usable_without_retention_or_other_eviction() { - let surface = one_tile(SampleType::F32); - let bytes = entry_bytes(&surface, None); - let mut cache = Cache::default(); - let small = Surface::new(FORMAT); - let small_bytes = entry_bytes(&small, None); - cache.insert(1, small, None, small_bytes, bytes - 1, cache.generation); - let tile = surface.tiles().next().unwrap().1.clone(); - let owners = Arc::strong_count(&tile); - cache.insert(2, surface.clone(), None, bytes, bytes - 1, cache.generation); - assert!(cache.get(2).is_none()); - assert!(cache.get(1).is_some()); - assert_eq!(cache.bytes, small_bytes); - assert_eq!(Arc::strong_count(&tile), owners); - assert_eq!(surface.pixel(0, 0), vec![0.0]); - } - - #[test] - fn replacement_and_purge_release_accounted_bytes_and_tile_references() { - let first = one_tile(SampleType::U8); - let second = one_tile(SampleType::F32); - let first_bytes = entry_bytes(&first, None); - let second_bytes = entry_bytes(&second, None); - let first_tile = first.tiles().next().unwrap().1.clone(); - let second_tile = second.tiles().next().unwrap().1.clone(); - let mut cache = Cache::default(); - cache.insert(1, first.clone(), None, first_bytes, CACHE_BUDGET, cache.generation); - assert_eq!(Arc::strong_count(&first_tile), 3); - cache.insert(1, second.clone(), None, second_bytes, CACHE_BUDGET, cache.generation); - assert_eq!(cache.bytes, second_bytes); - assert_eq!(cache.map.len(), 1); - assert_eq!(Arc::strong_count(&first_tile), 2); - assert_eq!(Arc::strong_count(&second_tile), 3); - assert_eq!(cache.clear(), second_bytes); - assert_eq!(cache.bytes, 0); - assert!(cache.map.is_empty()); - assert_eq!(Arc::strong_count(&second_tile), 2); - assert_eq!(cache.clear(), 0); - } - - #[test] - fn a_build_started_before_purge_cannot_refill_the_cache() { - let surface = one_tile(SampleType::F32); - let bytes = entry_bytes(&surface, None); - let mut cache = Cache::default(); - assert!(cache.get(1).is_none()); - let generation_before_purge = cache.generation; - cache.clear(); - cache.insert(1, surface.clone(), None, bytes, CACHE_BUDGET, generation_before_purge); - assert!(cache.map.is_empty()); - assert_eq!(cache.bytes, 0); - cache.insert(1, surface, None, bytes, CACHE_BUDGET, cache.generation); - assert!(cache.get(1).is_some()); - } - - #[test] - fn pixel_edits_refresh_cached_masks_at_every_depth() { - let canvas = Rect::new(0, 0, 64, 64); - for sample in [SampleType::U8, SampleType::U16, SampleType::F32] { - let mut layer = Layer::raster("edited mask", PixelFormat::RGBA8); - let mut mask = LayerMask::hide_all(); - mask.surface = Surface::new(PixelFormat { sample, ..FORMAT }); - mask.surface.fill_rect(canvas, &[1.0]); - mask.feather = 4.0; - layer.mask = Some(mask); - - let first = combined_mask(&layer, canvas).unwrap(); - assert!((first.sample_channel(32, 32, 0) - 1.0).abs() < 1e-6); - drop(first); - // No document/undo snapshot shares the input. Previously this write could - // reuse the original tile address and return the old cached white mask. - layer.mask.as_mut().unwrap().surface.fill_rect(canvas, &[0.0]); - let edited = combined_mask(&layer, canvas).unwrap(); - assert_eq!(edited.sample_channel(32, 32, 0), 0.0, "{sample:?}"); - - layer.mask.as_mut().unwrap().surface.fill_rect(canvas, &[0.5]); - let repainted = combined_mask(&layer, canvas).unwrap(); - assert!((repainted.sample_channel(32, 32, 0) - 0.5).abs() < 0.005, "{sample:?}"); - let warm = combined_mask(&layer, canvas).unwrap(); - assert!(repainted.tiles().zip(warm.tiles()).all(|((_, a), (_, b))| Arc::ptr_eq(a, b))); - } - } - - #[test] - fn cache_budget_holds_five_50mp_u8_input_u16_result_masks() { - // Account for whole 256×256 tiles, as entry_bytes does, rather than just logical pixels. - let (w, h) = (6336usize, 7920usize); - let tile = photocraft_geom::TILE_SIZE as usize; - let tile_count = w.div_ceil(tile) * h.div_ceil(tile); - let tile_pixels = tile * tile; - let one_entry = tile_count * tile_pixels * (SampleType::U8.bytes() + FORMAT.sample.bytes()); - assert!(one_entry.saturating_mul(5) <= CACHE_BUDGET, "five reported-size masks must fit"); - - let mut cache = Cache::default(); - let surface = Surface::new(FORMAT); - for key in 0..5 { - cache.insert(key, surface.clone(), None, one_entry, CACHE_BUDGET, cache.generation); - } - for key in 0..5 { - assert!(cache.get(key).is_some(), "mask {key} was evicted before the next plan"); - } - } - - #[test] - fn matches_the_cpu_mask_and_is_cached() { - let mut l = Layer::raster("l", PixelFormat::RGBA8); - let pts = [(5.0, 5.0), (30.0, 6.0), (20.0, 28.0)]; - let knots = pts.iter().map(|&(x, y)| Knot::corner(x, y)).collect(); - let mut path = Path::default(); - path.subpaths.push(Subpath { knots, closed: true, ..Default::default() }); - let mut vm = VectorMask::new(path); - vm.density = 0.9; - l.vector_mask = Some(vm); - let canvas = Rect::new(0, 0, 40, 32); - let s = combined_mask(&l, canvas).unwrap(); - let want = photocraft_vector::vector_mask_values(l.vector_mask.as_ref().unwrap(), canvas); - let mut got = Vec::new(); - s.read_region_into(canvas, &mut got); - for (a, b) in got.iter().zip(&want) { - assert!((a - b).abs() <= 1.0 / f32::from(u16::MAX)); - } - let again = combined_mask(&l, canvas).unwrap(); - assert!(s.tiles().zip(again.tiles()).all(|(a, b)| Arc::ptr_eq(a.1, b.1))); - l.vector_mask = None; - assert!(combined_mask(&l, canvas).is_none()); - } - - #[test] - fn hostile_path_coordinates_do_not_overflow() { - let mut l = Layer::raster("l", PixelFormat::RGBA8); - let knots = [(-1.0e30, -1.0e30), (1.0e30, 0.0), (0.0, 1.0e30)].iter().map(|&(x, y)| Knot::corner(x, y)).collect(); - let mut path = Path::default(); - path.subpaths.push(Subpath { knots, closed: true, ..Default::default() }); - l.vector_mask = Some(VectorMask::new(path)); - let _ = combined_mask(&l, Rect::new(0, 0, 8, 8)); - } -} +mod tests; diff --git a/crates/compose/src/masks/tests.rs b/crates/compose/src/masks/tests.rs new file mode 100644 index 0000000000..b6aa42fe1f --- /dev/null +++ b/crates/compose/src/masks/tests.rs @@ -0,0 +1,353 @@ +use super::*; +use photocraft_doc::LayerMask; +use photocraft_doc::vector::{Knot, Path, Subpath, VectorMask}; + +fn pending(c: &Mutex, k: u64) -> Arc> { + match lookup(c, k) { + CachedMask::Pending(slot, _) => slot, + CachedMask::Hit(_) => panic!("expected a cold mask"), + } +} + +/// A built mask (and no pixel-mask input), as `finish_mask`'s build returns it. +fn test_surface() -> (Surface, Option) { + let mut surface = Surface::new(FORMAT); + surface.fill_rect(Rect::new(0, 0, 2, 2), &[0.5]); + (surface, None) +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn cold_callers_share_one_build_without_retaining_a_second_cache() { + use std::sync::Barrier; + use std::sync::atomic::{AtomicUsize, Ordering}; + + let c = Mutex::new(Cache::default()); + // Acquire all callers' slots before allowing any builder to finish. + let slots: Vec<_> = (0..8).map(|_| pending(&c, 7)).collect(); + assert!(slots.iter().all(|slot| Arc::ptr_eq(slot, &slots[0]))); + let barrier = Barrier::new(slots.len()); + let builds = AtomicUsize::new(0); + let outputs = std::thread::scope(|scope| { + let handles: Vec<_> = slots + .iter() + .map(|slot| { + let (c, barrier, builds) = (&c, &barrier, &builds); + scope.spawn(move || { + barrier.wait(); + finish_mask(c, 7, slot, 0, || { + builds.fetch_add(1, Ordering::SeqCst); + test_surface() + }) + }) + }) + .collect(); + handles.into_iter().map(|handle| handle.join().unwrap()).collect::>() + }); + assert_eq!(builds.load(Ordering::SeqCst), 1); + assert!(outputs.iter().all(|surface| Arc::ptr_eq(surface.tiles().next().unwrap().1, outputs[0].tiles().next().unwrap().1))); + + // Evicting the retained result cannot make existing callers build again. + c.lock().unwrap().map.clear(); + let again = finish_mask(&c, 7, &slots[0], 0, || panic!("rebuilt an active slot")); + assert!(Arc::ptr_eq(again.tiles().next().unwrap().1, outputs[0].tiles().next().unwrap().1)); + drop(slots); + let next = pending(&c, 8); + assert_eq!(c.lock().unwrap().in_flight.len(), 1); + drop(next); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn distinct_keys_build_while_another_key_is_paused() { + use std::sync::mpsc; + use std::time::Duration; + + let c = Mutex::new(Cache::default()); + let (started_tx, started_rx) = mpsc::channel(); + let (release_tx, release_rx) = mpsc::channel(); + let (second_tx, second_rx) = mpsc::channel(); + std::thread::scope(|scope| { + let c = &c; + let first = scope.spawn(move || { + cached_mask(c, 1, || { + started_tx.send(()).unwrap(); + release_rx.recv_timeout(Duration::from_secs(10)).unwrap(); + test_surface() + }) + }); + started_rx.recv_timeout(Duration::from_secs(5)).unwrap(); + let second = scope.spawn(move || { + let surface = cached_mask(c, 2, test_surface); + second_tx.send(surface.sample_channel(0, 0, 0)).unwrap(); + }); + assert!((second_rx.recv_timeout(Duration::from_secs(5)).unwrap() - 0.5).abs() <= 1.0 / f32::from(u16::MAX)); + release_tx.send(()).unwrap(); + first.join().unwrap(); + second.join().unwrap(); + }); +} + +#[test] +fn obsolete_in_flight_build_does_not_repopulate_the_cache() { + let c = Mutex::new(Cache::default()); + let old = pending(&c, 1); + c.lock().unwrap().in_flight.clear(); + let current = pending(&c, 1); + assert!(!Arc::ptr_eq(&old, ¤t)); + let old_surface = finish_mask(&c, 1, &old, 0, test_surface); + assert!(c.lock().unwrap().map.is_empty()); + let current_surface = finish_mask(&c, 1, ¤t, 0, test_surface); + assert!(!Arc::ptr_eq(old_surface.tiles().next().unwrap().1, current_surface.tiles().next().unwrap().1)); + assert_eq!(c.lock().unwrap().map.len(), 1); +} + +#[test] +fn a_purge_during_a_shared_build_keeps_the_cache_empty() { + let c = Mutex::new(Cache::default()); + let CachedMask::Pending(slot, generation) = lookup(&c, 1) else { panic!("expected a cold mask") }; + c.lock().unwrap().clear(); + finish_mask(&c, 1, &slot, generation, test_surface); + assert!(c.lock().unwrap().map.is_empty()); + assert_eq!(c.lock().unwrap().bytes, 0); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn parallel_feathered_pixel_mask_returns_the_same_tiles() { + let canvas = Rect::new(0, 0, 600, 400); + let mut layer = Layer::raster("cold shared mask", PixelFormat::RGBA8); + let mut mask = photocraft_doc::LayerMask::reveal_all(); + mask.surface.fill_rect(canvas, &[0.5]); + mask.feather = 8.0; + layer.mask = Some(mask); + let barrier = std::sync::Barrier::new(8); + let outputs = std::thread::scope(|scope| { + let handles: Vec<_> = (0..8) + .map(|_| { + let (layer, barrier) = (&layer, &barrier); + scope.spawn(move || { + barrier.wait(); + combined_mask(layer, canvas).unwrap() + }) + }) + .collect(); + handles.into_iter().map(|handle| handle.join().unwrap()).collect::>() + }); + assert!(outputs.iter().all(|surface| Arc::ptr_eq(surface.tiles().next().unwrap().1, outputs[0].tiles().next().unwrap().1))); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn vector_mask_build_inside_a_small_rayon_pool_completes() { + use rayon::prelude::*; + use std::sync::mpsc; + use std::time::Duration; + + let (tx, rx) = mpsc::channel(); + let handle = std::thread::spawn(move || { + let canvas = Rect::new(0, 0, 512, 512); + let mut layer = Layer::raster("rayon vector mask", PixelFormat::RGBA8); + let mut mask = VectorMask::new(photocraft_vector::shapes::ellipse(8.0, 8.0, 496.0, 496.0)); + mask.feather = 8.0; + layer.vector_mask = Some(mask); + let pool = rayon::ThreadPoolBuilder::new().num_threads(2).build().unwrap(); + let outputs: Vec<_> = pool.install(|| (0..8).into_par_iter().map(|_| combined_mask(&layer, canvas).unwrap()).collect()); + assert!(outputs.iter().all(|surface| Arc::ptr_eq(surface.tiles().next().unwrap().1, outputs[0].tiles().next().unwrap().1))); + tx.send(()).unwrap(); + }); + rx.recv_timeout(Duration::from_secs(10)).expect("mask initializer deadlocked inside Rayon"); + handle.join().unwrap(); +} + +fn one_tile(sample: SampleType) -> Surface { + let mut surface = Surface::with_default(PixelFormat { mode: ColorMode::Grayscale, sample, alpha: false }, &[1.0]); + surface.fill_rect(Rect::new(0, 0, 1, 1), &[0.0]); + surface +} + +#[test] +fn charges_input_and_output_at_every_depth_including_off_canvas_tiles() { + let result = one_tile(SampleType::F32); + for sample in SampleType::ALL { + let mut input = one_tile(sample); + input.fill_rect(Rect::new(1024, 1024, 1025, 1025), &[0.0]); + let tile_pixels = (photocraft_geom::TILE_SIZE * photocraft_geom::TILE_SIZE) as usize; + let expected = tile_pixels * (SampleType::F32.bytes() + 2 * sample.bytes()) + SampleType::F32.bytes() + sample.bytes(); + let bytes = entry_bytes(&result, Some(&input)); + assert_eq!(bytes, expected, "{sample:?}"); + let mut cache = Cache::default(); + cache.insert(1, result.clone(), None, bytes, bytes * 2, cache.generation); + cache.insert(2, result.clone(), None, bytes, bytes * 2, cache.generation); + assert_eq!(cache.bytes, bytes * 2, "shared tiles are conservatively charged per entry"); + } +} + +#[test] +fn byte_budget_evicts_the_least_recently_used_entry() { + let surface = one_tile(SampleType::F32); + let bytes = entry_bytes(&surface, None); + let mut cache = Cache::default(); + cache.insert(1, surface.clone(), None, bytes, bytes * 2, cache.generation); + cache.insert(2, surface.clone(), None, bytes, bytes * 2, cache.generation); + assert!(cache.get(1).is_some()); + cache.insert(3, surface, None, bytes, bytes * 2, cache.generation); + assert!(cache.get(2).is_none()); + assert!(cache.get(1).is_some()); + assert!(cache.get(3).is_some()); + assert_eq!(cache.bytes, bytes * 2); +} + +#[test] +fn entry_limit_also_bounds_masks_with_no_tiles() { + let surface = Surface::new(FORMAT); + let bytes = entry_bytes(&surface, None); + let mut cache = Cache::default(); + for key in 0..CAPACITY as u64 { + cache.insert(key, surface.clone(), None, bytes, CACHE_BUDGET, cache.generation); + } + assert!(cache.get(0).is_some()); + cache.insert(CAPACITY as u64, surface, None, bytes, CACHE_BUDGET, cache.generation); + assert_eq!(cache.map.len(), CAPACITY); + assert!(cache.get(1).is_none()); + assert!(cache.get(0).is_some()); + assert_eq!(cache.bytes, bytes * CAPACITY); +} + +#[test] +fn oversized_results_are_usable_without_retention_or_other_eviction() { + let surface = one_tile(SampleType::F32); + let bytes = entry_bytes(&surface, None); + let mut cache = Cache::default(); + let small = Surface::new(FORMAT); + let small_bytes = entry_bytes(&small, None); + cache.insert(1, small, None, small_bytes, bytes - 1, cache.generation); + let tile = surface.tiles().next().unwrap().1.clone(); + let owners = Arc::strong_count(&tile); + cache.insert(2, surface.clone(), None, bytes, bytes - 1, cache.generation); + assert!(cache.get(2).is_none()); + assert!(cache.get(1).is_some()); + assert_eq!(cache.bytes, small_bytes); + assert_eq!(Arc::strong_count(&tile), owners); + assert_eq!(surface.pixel(0, 0), vec![0.0]); +} + +#[test] +fn replacement_and_purge_release_accounted_bytes_and_tile_references() { + let first = one_tile(SampleType::U8); + let second = one_tile(SampleType::F32); + let first_bytes = entry_bytes(&first, None); + let second_bytes = entry_bytes(&second, None); + let first_tile = first.tiles().next().unwrap().1.clone(); + let second_tile = second.tiles().next().unwrap().1.clone(); + let mut cache = Cache::default(); + cache.insert(1, first.clone(), None, first_bytes, CACHE_BUDGET, cache.generation); + assert_eq!(Arc::strong_count(&first_tile), 3); + cache.insert(1, second.clone(), None, second_bytes, CACHE_BUDGET, cache.generation); + assert_eq!(cache.bytes, second_bytes); + assert_eq!(cache.map.len(), 1); + assert_eq!(Arc::strong_count(&first_tile), 2); + assert_eq!(Arc::strong_count(&second_tile), 3); + assert_eq!(cache.clear(), second_bytes); + assert_eq!(cache.bytes, 0); + assert!(cache.map.is_empty()); + assert_eq!(Arc::strong_count(&second_tile), 2); + assert_eq!(cache.clear(), 0); +} + +#[test] +fn a_build_started_before_purge_cannot_refill_the_cache() { + let surface = one_tile(SampleType::F32); + let bytes = entry_bytes(&surface, None); + let mut cache = Cache::default(); + assert!(cache.get(1).is_none()); + let generation_before_purge = cache.generation; + cache.clear(); + cache.insert(1, surface.clone(), None, bytes, CACHE_BUDGET, generation_before_purge); + assert!(cache.map.is_empty()); + assert_eq!(cache.bytes, 0); + cache.insert(1, surface, None, bytes, CACHE_BUDGET, cache.generation); + assert!(cache.get(1).is_some()); +} + +#[test] +fn pixel_edits_refresh_cached_masks_at_every_depth() { + let canvas = Rect::new(0, 0, 64, 64); + for sample in [SampleType::U8, SampleType::U16, SampleType::F32] { + let mut layer = Layer::raster("edited mask", PixelFormat::RGBA8); + let mut mask = LayerMask::hide_all(); + mask.surface = Surface::new(PixelFormat { sample, ..FORMAT }); + mask.surface.fill_rect(canvas, &[1.0]); + mask.feather = 4.0; + layer.mask = Some(mask); + + let first = combined_mask(&layer, canvas).unwrap(); + assert!((first.sample_channel(32, 32, 0) - 1.0).abs() < 1e-6); + drop(first); + // No document/undo snapshot shares the input. Previously this write could + // reuse the original tile address and return the old cached white mask. + layer.mask.as_mut().unwrap().surface.fill_rect(canvas, &[0.0]); + let edited = combined_mask(&layer, canvas).unwrap(); + assert_eq!(edited.sample_channel(32, 32, 0), 0.0, "{sample:?}"); + + layer.mask.as_mut().unwrap().surface.fill_rect(canvas, &[0.5]); + let repainted = combined_mask(&layer, canvas).unwrap(); + assert!((repainted.sample_channel(32, 32, 0) - 0.5).abs() < 0.005, "{sample:?}"); + let warm = combined_mask(&layer, canvas).unwrap(); + assert!(repainted.tiles().zip(warm.tiles()).all(|((_, a), (_, b))| Arc::ptr_eq(a, b))); + } +} + +#[test] +fn cache_budget_holds_five_50mp_u8_input_u16_result_masks() { + // Account for whole 256×256 tiles, as entry_bytes does, rather than just logical pixels. + let (w, h) = (6336usize, 7920usize); + let tile = photocraft_geom::TILE_SIZE as usize; + let tile_count = w.div_ceil(tile) * h.div_ceil(tile); + let tile_pixels = tile * tile; + let one_entry = tile_count * tile_pixels * (SampleType::U8.bytes() + FORMAT.sample.bytes()); + assert!(one_entry.saturating_mul(5) <= CACHE_BUDGET, "five reported-size masks must fit"); + + let mut cache = Cache::default(); + let surface = Surface::new(FORMAT); + for key in 0..5 { + cache.insert(key, surface.clone(), None, one_entry, CACHE_BUDGET, cache.generation); + } + for key in 0..5 { + assert!(cache.get(key).is_some(), "mask {key} was evicted before the next plan"); + } +} + +#[test] +fn matches_the_cpu_mask_and_is_cached() { + let mut l = Layer::raster("l", PixelFormat::RGBA8); + let pts = [(5.0, 5.0), (30.0, 6.0), (20.0, 28.0)]; + let knots = pts.iter().map(|&(x, y)| Knot::corner(x, y)).collect(); + let mut path = Path::default(); + path.subpaths.push(Subpath { knots, closed: true, ..Default::default() }); + let mut vm = VectorMask::new(path); + vm.density = 0.9; + l.vector_mask = Some(vm); + let canvas = Rect::new(0, 0, 40, 32); + let s = combined_mask(&l, canvas).unwrap(); + let want = photocraft_vector::vector_mask_values(l.vector_mask.as_ref().unwrap(), canvas); + let mut got = Vec::new(); + s.read_region_into(canvas, &mut got); + for (a, b) in got.iter().zip(&want) { + assert!((a - b).abs() <= 1.0 / f32::from(u16::MAX)); + } + let again = combined_mask(&l, canvas).unwrap(); + assert!(s.tiles().zip(again.tiles()).all(|(a, b)| Arc::ptr_eq(a.1, b.1))); + l.vector_mask = None; + assert!(combined_mask(&l, canvas).is_none()); +} + +#[test] +fn hostile_path_coordinates_do_not_overflow() { + let mut l = Layer::raster("l", PixelFormat::RGBA8); + let knots = [(-1.0e30, -1.0e30), (1.0e30, 0.0), (0.0, 1.0e30)].iter().map(|&(x, y)| Knot::corner(x, y)).collect(); + let mut path = Path::default(); + path.subpaths.push(Subpath { knots, closed: true, ..Default::default() }); + l.vector_mask = Some(VectorMask::new(path)); + let _ = combined_mask(&l, Rect::new(0, 0, 8, 8)); +} diff --git a/crates/compose/src/reduced.rs b/crates/compose/src/reduced.rs new file mode 100644 index 0000000000..479bf1655f --- /dev/null +++ b/crates/compose/src/reduced.rs @@ -0,0 +1,300 @@ +use super::content::RENDER_TILE; +use super::ctx::Ctx; +use super::render::{band_rows_for, render, render_bands, render_tiled_with}; +use super::*; + +/// Documents above this many pixels get thumbnails from a proxy (see [`proxy`]) when that is +/// faithful; smaller ones are reduced from the exact composite. +pub const PROXY_THUMBNAIL_PIXELS: u64 = 16 << 20; + +/// Downscaled RGBA8 render of the document (area-averaged) for thumbnails, navigators and +/// histograms, at most `max_side` pixels on its longer side. Large documents are reduced from a +/// downsampled proxy (about twice the thumbnail's size), so a thumbnail of a 200 MP document +/// costs milliseconds and no full-size composite; the rest stream the exact composite in bands. +pub fn thumbnail(doc: &Document, max_side: u32) -> Rgba8Image { + thumbnail_buffer(doc, max_side).to_rgba8() +} + +/// Width and height of [`thumbnail`]`(doc, max_side)`. +pub fn thumbnail_size(doc: &Document, max_side: u32) -> (u32, u32) { + let b = doc.bounds(); + let longest = b.width().max(b.height()).max(1); + let scale = (max_side as f32 / longest as f32).min(1.0); + (((b.width() as f32 * scale).round() as u32).max(1), ((b.height() as f32 * scale).round() as u32).max(1)) +} + +/// [`thumbnail`] as straight-alpha floats (for callers that colour-convert it first). +pub fn thumbnail_buffer(doc: &Document, max_side: u32) -> Buffer { + let b = doc.bounds(); + let longest = b.width().max(b.height()).max(1); + let (w, h) = thumbnail_size(doc, max_side); + let k = longest / max_side.max(1).saturating_mul(2); + if k >= 2 && doc.size.area() > PROXY_THUMBNAIL_PIXELS && proxy::proxy_faithful(doc) { + render_reduced(&proxy::proxy_document(doc, k), w, h) + } else { + render_reduced(doc, w, h) + } +} + +/// The document's composite area-averaged (premultiplied) down to `w`×`h` (clamped to the +/// document size), rendered in bands so no full-size composite is held. +pub fn render_reduced(doc: &Document, w: u32, h: u32) -> Buffer { + render_reduced_in_bands(doc, doc.bounds(), w, h, None, 0) +} + +/// [`render_reduced`] of any area of the document plane, `rect`, which may lie past the canvas +/// (layer pixels there are kept until a crop deletes them). The buffer's rect is in output pixels +/// from (0, 0). +pub fn render_reduced_rect(doc: &Document, rect: Rect, w: u32, h: u32) -> Buffer { + render_reduced_in_bands(doc, rect, w, h, None, 0) +} + +/// The part of [`render_reduced`]`(doc, w, h)` that a change to `damage` (document pixels) can +/// affect: the output pixels whose source areas meet it, rendered from just those areas, with the +/// same values the whole reduction gives them. The buffer's rect is in output pixels (empty when +/// `damage` misses the document), so a reduced canvas texture can update only what a stroke touched. +pub fn render_reduced_damage(doc: &Document, w: u32, h: u32, damage: Rect) -> Buffer { + render_reduced_in_bands(doc, doc.bounds(), w, h, Some(damage), 0) +} + +/// [`render_reduced_rect`] (or, with `damage`, [`render_reduced_damage`]) of area `b` with an +/// explicit band height (see [`render_bands`]). +pub(crate) fn render_reduced_in_bands(doc: &Document, b: Rect, w: u32, h: u32, damage: Option, band_rows: i32) -> Buffer { + render_reduced_with(doc, b, w, h, damage, band_rows, true, &mut ReducedStats::default()) +} + +/// What a reduced render composited (tests check that one-colour areas are not composited). +#[derive(Debug, Default)] +pub(crate) struct ReducedStats { + /// Whether one-colour areas were looked for ([`uniform::UniformAreas`]). + pub(crate) uniform: bool, + /// Document pixels composited one by one. + pub(crate) composited: u64, +} + +/// A tile of a reduced render: one colour (premultiplied), or its composited pixels. +enum Part { + Solid([f32; 4]), + Px(Buffer), +} + +/// A column of document tiles in a reduced render (`b`-relative source columns). +struct TileColumn { + /// The columns rendered: the tile's, within the source area. + x0: usize, + x1: usize, + /// The whole tile's columns within `b`, whose values decide whether it is one colour. + whole: (i64, i64), + /// Runs of (output column, how many of the rendered columns it averages). + runs: Vec<(usize, f32)>, +} + +/// [`render_reduced_in_bands`]; `uniform` off composites every pixel (the reference in tests). +#[allow(clippy::too_many_arguments)] +pub(crate) fn render_reduced_with( + doc: &Document, + b: Rect, + w: u32, + h: u32, + damage: Option, + band_rows: i32, + uniform: bool, + stats: &mut ReducedStats, +) -> Buffer { + let (fw, fh) = (b.width() as usize, b.height() as usize); + let (w, h) = (w.clamp(1, b.width().max(1)) as usize, h.clamp(1, b.height().max(1)) as usize); + let full = Rect::from_xywh(0, 0, w as u32, h as u32); + if fw == 0 || fh == 0 { + return Buffer::transparent(if damage.is_some() { Rect::EMPTY } else { full }); + } + // Output column / row of each document column / row: output pixel t covers [t·f/n, (t+1)·f/n). + let span = |t: usize, f: usize, n: usize| (t * f / n, ((t + 1) * f / n).max(t * f / n + 1).min(f)); + // The output pixel whose span holds document column / row `x` (spans are contiguous: n <= f). + let cell = |x: usize, f: usize, n: usize| ((x + 1) * n).saturating_sub(1) / f; + // Output pixels to produce and the document area they cover. + let out = match damage { + None => full, + Some(d) => { + let d = d.intersect(&b); + if d.is_empty() { + return Buffer::transparent(Rect::EMPTY); + } + let (x0, x1) = ((d.x0 - b.x0) as usize, (d.x1 - b.x0) as usize); + let (y0, y1) = ((d.y0 - b.y0) as usize, (d.y1 - b.y0) as usize); + Rect::new(cell(x0, fw, w) as i32, cell(y0, fh, h) as i32, cell(x1 - 1, fw, w) as i32 + 1, cell(y1 - 1, fh, h) as i32 + 1) + } + }; + let (ox0, oy0, ow, oh) = (out.x0 as usize, out.y0 as usize, out.width() as usize, out.height() as usize); + let (sx0, sx1) = (span(ox0, fw, w).0, span(ox0 + ow - 1, fw, w).1); + let (sy0, sy1) = (span(oy0, fh, h).0, span(oy0 + oh - 1, fh, h).1); + let src = Rect::new(b.x0 + sx0 as i32, b.y0 + sy0 as i32, b.x0 + sx1 as i32, b.y0 + sy1 as i32); + if (w, h) == (fw, fh) { + let mut px = render(doc, src); + px.rect = out; + return px; + } + let map = |f: usize, n: usize| { + let mut m = vec![0u32; f]; + for t in 0..n { + let (a, z) = span(t, f, n); + m[a..z].fill(t as u32); + } + m + }; + let (cols, rows) = (map(fw, w), map(fh, h)); + let cols = &cols[sx0..sx1]; + let mut acc = vec![[0.0f32; 4]; ow * oh]; + // Each output row sums its source rows in a band (in order, top to bottom), each row's pixels + // left to right: `row(y, out)` adds source row `y` (band-relative) to output row `out`. + let sum_band = |acc: &mut [[f32; 4]], by0: usize, by1: usize, row: &(dyn Fn(usize, &mut [[f32; 4]]) + Sync)| { + let (t0, t1) = (rows[by0] as usize, rows[by1 - 1] as usize + 1); + let sum_row = |t: usize, out: &mut [[f32; 4]]| { + let (a, z) = span(t, fh, h); + for y in a.max(by0)..z.min(by1) { + row(y - by0, out); + } + }; + let part = &mut acc[(t0 - oy0) * ow..(t1 - oy0) * ow]; + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + part.par_chunks_mut(ow).enumerate().for_each(|(i, out)| sum_row(t0 + i, out)); + } + #[cfg(target_arch = "wasm32")] + for (i, out) in part.chunks_mut(ow).enumerate() { + sum_row(t0 + i, out); + } + }; + let add = |o: &mut [f32; 4], p: &[f32; 4]| { + for i in 0..3 { + o[i] += p[i] * p[3]; + } + o[3] += p[3]; + }; + if let Some(uniform) = uniform.then(|| uniform::UniformAreas::new(doc)).flatten() { + stats.uniform = true; + // One-colour tiles (a new document's background, the empty parts of a sparse one) are + // composited once per colour and summed per run of source columns, not per pixel + // (#4017). Tiles lie on the document's tile grid whatever `damage` is, so a damage + // render sums exactly what the whole reduction does. + let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(doc.pixel_format().mode); + let cx = Ctx::for_doc(doc, &patterns); + let t = RENDER_TILE as usize; + // The document tile grid (the surfaces' own), in `b`-relative coordinates: the start of + // the tile holding `v` (negative when `b` starts inside a tile). + let grid = |v: usize, o: i32| (i64::from(o) + v as i64).div_euclid(t as i64) * t as i64 - i64::from(o); + let tile_cols: Vec = (grid(sx0, b.x0)..sx1 as i64) + .step_by(t) + .map(|gx| { + let (x0, x1) = ((gx.max(0) as usize).max(sx0), ((gx + t as i64) as usize).min(sx1)); + let mut runs: Vec<(usize, f32)> = Vec::new(); + for &c in &cols[x0 - sx0..x1 - sx0] { + match runs.last_mut() { + Some((last, n)) if *last == c as usize - ox0 => *n += 1.0, + _ => runs.push((c as usize - ox0, 1.0)), + } + } + TileColumn { x0, x1, whole: (gx.max(0), (gx + t as i64).min(fw as i64)), runs } + }) + .collect(); + let band_h = band_rows_for(src.width(), band_rows).max(RENDER_TILE) as usize; + let mut y = grid(sy0, b.y0); + while y < sy1 as i64 { + let y1 = (y + band_h as i64).min(sy1 as i64); + let tiles: Vec<(Rect, Rect)> = (y..y1) + .step_by(t) + .flat_map(|gy| { + tile_cols.iter().map(move |&TileColumn { x0, x1, whole: (gx0, gx1), .. }| { + let at = |x0: i64, y0: i64, x1: i64, y1: i64| Rect::new(b.x0 + x0 as i32, b.y0 + y0 as i32, b.x0 + x1 as i32, b.y0 + y1 as i32); + let (gy0, gy1) = (gy.max(0), (gy + t as i64).min(fh as i64)); + (at(gx0, gy0, gx1, gy1), at(x0 as i64, gy0.max(sy0 as i64), x1 as i64, gy1.min(sy1 as i64))) + }) + }) + .collect(); + let one = |(whole, part): &(Rect, Rect)| -> Part { + let render = |r: Rect| render_tiled_with(doc, r, RENDER_TILE, &cx); + match uniform.color(*whole, |r| render(r).px.first().copied()) { + Some(p) => Part::Solid([p[0] * p[3], p[1] * p[3], p[2] * p[3], p[3]]), + None => Part::Px(render(*part)), + } + }; + #[cfg(not(target_arch = "wasm32"))] + let parts: Vec = { + use rayon::prelude::*; + tiles.par_iter().map(one).collect() + }; + #[cfg(target_arch = "wasm32")] + let parts: Vec = tiles.iter().map(one).collect(); + stats.composited += parts.iter().map(|p| if let Part::Px(b) = p { b.px.len() as u64 } else { 0 }).sum::(); + let (by0, by1) = (y.max(sy0 as i64) as usize, y1 as usize); + let n = tile_cols.len(); + let band_y = y; + sum_band(&mut acc, by0, by1, &|row: usize, out: &mut [[f32; 4]]| { + let y = (by0 + row) as i64; + let j = (y - band_y) as usize / t; + let ty = (y - (band_y + (j * t) as i64).max(sy0 as i64)) as usize; + for (TileColumn { x0, x1, runs, .. }, part) in tile_cols.iter().zip(parts.iter().skip(j * n).take(n)) { + match part { + Part::Solid(pa) => { + for &(c, k) in runs { + let o = &mut out[c]; + for i in 0..4 { + o[i] += pa[i] * k; + } + } + } + Part::Px(buf) => { + let tw = x1 - x0; + for (p, &c) in buf.px.iter().skip(ty * tw).take(tw).zip(&cols[x0 - sx0..x1 - sx0]) { + add(&mut out[c as usize - ox0], p); + } + } + } + } + }); + y = y1; + } + } else { + let ok: Result<(), ()> = render_bands(doc, src, band_rows, |band| { + stats.composited += band.px.len() as u64; + let (by0, by1) = ((band.rect.y0 - b.y0) as usize, (band.rect.y1 - b.y0) as usize); + let sw = sx1 - sx0; + sum_band(&mut acc, by0, by1, &|y: usize, out: &mut [[f32; 4]]| { + for (p, &c) in band.px[y * sw..(y + 1) * sw].iter().zip(cols) { + add(&mut out[c as usize - ox0], p); + } + }); + Ok(()) + }); + debug_assert!(ok.is_ok()); + } + let col_w: Vec = (0..ow) + .map(|x| { + let (x0, x1) = span(ox0 + x, fw, w); + (x1 - x0).max(1) + }) + .collect(); + let norm_row = |row: usize, out: &mut [[f32; 4]]| { + let (y0, y1) = span(oy0 + row, fh, h); + let rh = (y1 - y0).max(1); + for (p, &cw) in out.iter_mut().zip(&col_w) { + let a = p[3]; + if a > 0.0 { + let n = (rh * cw) as f32; + *p = [p[0] / a, p[1] / a, p[2] / a, a / n]; + } else { + *p = [0.0; 4]; + } + } + }; + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + acc.par_chunks_mut(ow).enumerate().for_each(|(row, out)| norm_row(row, out)); + } + #[cfg(target_arch = "wasm32")] + for (row, out) in acc.chunks_mut(ow).enumerate() { + norm_row(row, out); + } + Buffer { rect: out, px: acc } +} diff --git a/crates/compose/src/render.rs b/crates/compose/src/render.rs new file mode 100644 index 0000000000..33b17d25b8 --- /dev/null +++ b/crates/compose/src/render.rs @@ -0,0 +1,360 @@ +use super::composite::composite_stack_at; +use super::content::RENDER_TILE; +use super::ctx::{Ctx, RenderVectorMasks, prepare_effects, prepare_tones}; +use super::*; + +/// Every layer the compositor draws, groups before their children: hidden layers and everything +/// inside hidden groups are left out. +pub(crate) fn visible_layers(layers: &[Layer]) -> Vec<&Layer> { + fn rec<'a>(layers: &'a [Layer], out: &mut Vec<&'a Layer>) { + for l in layers.iter().filter(|l| l.visible) { + out.push(l); + if let Some(children) = l.children() { + rec(children, out); + } + } + } + let mut out = Vec::new(); + rec(layers, &mut out); + out +} + +/// Composite the whole document over `rect`, in parallel 256² tiles on +/// native targets (single-threaded on wasm). +pub fn render(doc: &Document, rect: Rect) -> Buffer { + render_tiled(doc, rect, RENDER_TILE) +} + +/// Most pixels one [`render`] call will produce (2^30, a 16 GiB buffer; 32768² px). Larger rects +/// (a hostile canvas size is up to 300000 px a side) return an empty buffer instead of aborting +/// on allocation; callers wanting more render in pieces. +pub const MAX_RENDER_PIXELS: u64 = 1 << 30; + +/// [`render`] with an explicit tile size (tests check tile independence). +pub fn render_tiled(doc: &Document, rect: Rect, tile: i32) -> Buffer { + let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(doc.pixel_format().mode); + let cx = Ctx::for_doc(doc, &patterns); + render_tiled_with(doc, rect, tile, &cx) +} + +pub(crate) fn render_tiled_with(doc: &Document, rect: Rect, tile: i32, cx: &Ctx) -> Buffer { + let tile = tile.max(1); + // Lab documents mix Normal blending in CIELAB, as Photoshop does (psblend::LAB_MIX); 32-bit + // documents don't clip Add / Divide or Hue / Saturation / Color / Luminosity at 1 (psblend::HDR). + let lab = doc.mode == photocraft_color::ColorMode::Lab; + let hdr = doc.depth == photocraft_color::SampleType::F32; + // CMYK layers are read through the document's own CMYK profile (thread-local scope). + let cmyk = cmyk_space(doc); + let cmyk = cmyk.as_ref(); + if rect.is_empty() { + return Buffer::transparent(rect); + } + // Refuse rects too large to hold: an empty buffer, not an allocation failure. + if u64::from(rect.width()) * u64::from(rect.height()) > MAX_RENDER_PIXELS { + return Buffer::transparent(Rect::EMPTY); + } + // A CMYK stack with adjustment layers the inks carry exactly composites on its inks. + if let Some(buf) = native::render_cmyk(doc, rect, tile) { + return buf; + } + // A Lab stack with adjustment layers that work on L, a and b composites on its stored values. + if let Some(buf) = native_lab::render_lab(doc, rect, tile) { + return buf; + } + cx.set_fx_clip(rect); + if i64::from(rect.width()) <= i64::from(tile) && i64::from(rect.height()) <= i64::from(tile) { + return photocraft_color::convert::with_cmyk_space(cmyk, || { + let mut buf = multichannel::backdrop(doc, rect); + in_blend_space(lab, hdr, || composite_stack_at(&doc.layers, &mut buf, cx, advanced::Scope::ROOT)); + buf + }); + } + // Effect maps are built once, here, before any tile needs them (#276). + prepare_effects(&doc.layers, rect, cx, |f| { + photocraft_color::convert::with_cmyk_space(cmyk, || in_blend_space(lab, hdr, f)); + }); + let run = |t: Rect| { + photocraft_color::convert::with_cmyk_space(cmyk, || { + let mut b = multichannel::backdrop(doc, t); + in_blend_space(lab, hdr, || composite_stack_at(&doc.layers, &mut b, cx, advanced::Scope::ROOT)); + b + }) + }; + // Tiles are written straight into the output, one row of tiles (a band) at a time, so the + // peak is the output plus the tiles in flight, not a second full-size copy. + let w = rect.width() as usize; + let mut out = Buffer::transparent(rect); + let band_tiles = |y0: i32| { + let y1 = y0.saturating_add(tile).min(rect.y1); + let mut v = Vec::new(); + let mut x = rect.x0; + while x < rect.x1 { + let x1 = x.saturating_add(tile).min(rect.x1); + v.push(Rect::new(x, y0, x1, y1)); + x = x1; + } + v + }; + let put = |band: &mut [[f32; 4]], y0: i32, part: &Buffer| { + let pw = part.rect.width() as usize; + for (row, src) in part.px.chunks_exact(pw).enumerate() { + let o = ((part.rect.y0 - y0) as usize + row) * w + (part.rect.x0 - rect.x0) as usize; + band[o..o + pw].copy_from_slice(src); + } + }; + let band_len = w * tile as usize; + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + let bands = rect.height().div_ceil(tile as u32) as usize; + if bands >= 2 * rayon::current_num_threads() { + // Enough bands to keep every core busy: one band per task, its tiles in turn. + out.px.par_chunks_mut(band_len).enumerate().for_each(|(i, band)| { + let y0 = rect.y0 + i as i32 * tile; + for t in band_tiles(y0) { + put(band, y0, &run(t)); + } + }); + } else { + // Few, wide bands: the tiles of each band in parallel, and the bands too, so a band's + // slowest tile doesn't leave the other cores idle until the next band starts. Each + // tile is written as soon as it is done, so only the tiles in flight are held. + out.px.par_chunks_mut(band_len).enumerate().for_each(|(i, band)| { + let y0 = rect.y0 + i as i32 * tile; + let band = std::sync::Mutex::new(band); + band_tiles(y0).into_par_iter().for_each(|t| { + let part = run(t); + let mut band = band.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + put(&mut band, y0, &part); + }); + }); + } + } + #[cfg(target_arch = "wasm32")] + for (i, band) in out.px.chunks_mut(band_len).enumerate() { + let y0 = rect.y0 + i as i32 * tile; + for t in band_tiles(y0) { + put(band, y0, &run(t)); + } + } + out +} + +/// Runs `f` with this thread's document blend flags set ([`psblend::LAB_MIX`], [`psblend::HDR`]), +/// then restores the values they had (also on unwind): a nested rayon job can run another tile +/// on this thread mid-composite, and clearing the flags there broke the outer tile (#1112). +pub(crate) fn in_blend_space(lab: bool, hdr: bool, f: impl FnOnce() -> R) -> R { + psblend::with_lab_mix(lab, || psblend::with_hdr(hdr, f)) +} + +/// The document's own CMYK profile for reading its CMYK pixels (`None`: not a CMYK document, +/// untagged, or the built-in coated CMYK). Enter it with `photocraft_color::convert::with_cmyk_space` +/// around code that converts the document's CMYK pixels or colours to RGB. +pub fn cmyk_space(doc: &Document) -> Option> { + if doc.mode != photocraft_color::ColorMode::Cmyk { + return None; + } + photocraft_color::convert::CmykSpace::for_profile(doc.icc_profile.as_ref()) +} + +/// Pixels per band of [`render_bands`] (a 14000 px wide band is ~600 rows, ~130 MB of f32). +pub const BAND_PIXELS: u64 = 8 << 20; + +/// Composite `rect` in horizontal bands, top to bottom, handing each band to `sink` (tiles inside +/// a band render in parallel). Peak memory is one band instead of the whole composite, so huge +/// documents can be exported or displayed without a full-size float copy. `band_rows` of 0 picks +/// about [`BAND_PIXELS`] per band; bands are whole multiples of [`RENDER_TILE`] rows. +pub fn render_bands(doc: &Document, rect: Rect, band_rows: i32, mut sink: impl FnMut(Buffer) -> Result<(), E>) -> Result<(), E> { + if rect.is_empty() { + return Ok(()); + } + // Keep prepared pixels and compiled vector masks across bands without retaining any rendered band. + let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(doc.pixel_format().mode); + let cx = Ctx::for_doc(doc, &patterns); + let rows = band_rows_for(rect.width(), band_rows); + let mut y = rect.y0; + while y < rect.y1 { + let y1 = y.saturating_add(rows).min(rect.y1); + sink(render_tiled_with(doc, Rect::new(rect.x0, y, rect.x1, y1), RENDER_TILE, &cx))?; + y = y1; + } + Ok(()) +} + +/// Band height for [`render_bands`]: `requested` rounded up to whole tiles, or ~[`BAND_PIXELS`]. +pub fn band_rows_for(width: u32, requested: i32) -> i32 { + let want = if requested > 0 { i64::from(requested) } else { (BAND_PIXELS / u64::from(width.max(1))) as i64 }; + let tiles = (want + i64::from(RENDER_TILE) - 1) / i64::from(RENDER_TILE); + (tiles.clamp(1, 1 << 16) * i64::from(RENDER_TILE)) as i32 +} + +/// The document's composite as a pixel surface in `fmt` (straight RGBA converted to its model +/// and depth), optionally flattened over an opaque `background`; rendered and written in bands, +/// so no full-size float composite is held. Tiles equal to the default pixel are pruned. +/// +/// Fully transparent pixels are written as the default pixel. Converting transparent black +/// leaves colour behind in CMYK (K = 100%) and Lab (neutral a/b = 0.5), and those pixels would +/// otherwise count as content: the result would span the whole canvas. +/// +/// A CMYK document flattened to CMYK is composited in its ink values instead, so flattening +/// doesn't round-trip its pixels through RGB: plain Normal layers by [`native::flatten_cmyk`] +/// (#3778), and masks, groups, clipping, other blend modes and the other layer kinds by [`cmyk`] +/// where its layers mix on their inks (#2220). Otherwise the composite goes back to CMYK through +/// the document's own profile, the one its layers were read through. A Lab document of plain +/// layers is composited in its L, a and b ([`native_lab::flatten_lab`]). +pub fn flatten_to_surface(doc: &Document, fmt: photocraft_color::PixelFormat, background: Option<[f32; 3]>) -> Surface { + composite_to_surface(doc, doc.bounds(), fmt, background) +} + +/// [`flatten_to_surface`] over `rect` only (the rest of the surface stays empty). +pub fn composite_to_surface(doc: &Document, rect: Rect, fmt: photocraft_color::PixelFormat, background: Option<[f32; 3]>) -> Surface { + let paper = background.is_some_and(|bg| bg == [1.0; 3]); + if (background.is_none() || paper) + && let Some(s) = native::flatten_cmyk(doc, rect, fmt, paper) + { + return s; + } + if (background.is_none() || paper) + && let Some(s) = native_lab::flatten_lab(doc, rect, fmt, paper) + { + return s; + } + let space = cmyk_space(doc); + let to_cmyk = fmt.mode == photocraft_color::ColorMode::Cmyk && doc.mode == photocraft_color::ColorMode::Cmyk; + if to_cmyk && cmyk::renders_inks(doc) { + return composite_inks_to_surface(doc, rect, fmt, background, space.as_ref()); + } + // The composite separates back to CMYK through the document's own profile, the one its + // pixels were read through. + let mut s = Surface::new(fmt); + let n = fmt.channels(); + let empty = s.default_pixel(); + let mut data = Vec::new(); + let _ = render_bands(doc, rect, 0, |band| -> Result<(), ()> { + let band = match background { + Some(bg) => band.over_background(bg), + None => band, + }; + data.clear(); + data.resize(band.px.len() * n, 0.0); + photocraft_color::convert::with_cmyk_space(space.as_ref(), || { + for (p, out) in band.px.iter().zip(data.chunks_exact_mut(n)) { + if fmt.alpha && (p[3] <= 0.0 || p[3].is_nan()) && empty.len() == n { + out.copy_from_slice(&empty); + } else { + photocraft_raster::from_rgba_into(&fmt, *p, out); + } + } + }); + s.write_region(band.rect, &data); + Ok(()) + }); + s.prune(); + s +} + +/// One CMYK pixel's output channels into `data`: its inks (over `paper` when given) and alpha. +fn push_ink_pixel(data: &mut Vec, p: &[f32; 5], paper: Option<[f32; 4]>, fmt: photocraft_color::PixelFormat, empty: &[f32]) { + if paper.is_none() && fmt.alpha && (p[4] <= 0.0 || p[4].is_nan()) && empty.len() == fmt.channels() { + data.extend_from_slice(empty); + return; + } + // Over the paper (fully covered pixels keep their inks exactly), or straight. + let ink = |c: usize| match paper { + Some(bg) if p[4] < 1.0 => p[c] * p[4] + bg[c] * (1.0 - p[4]), + _ => p[c], + }; + data.extend((0..4).map(ink)); + if fmt.alpha { + data.push(if paper.is_some() { 1.0 } else { p[4] }); + } +} + +/// [`composite_to_surface`] for a CMYK document flattened to CMYK, composited in its inks. +fn composite_inks_to_surface( + doc: &Document, + rect: Rect, + fmt: photocraft_color::PixelFormat, + background: Option<[f32; 3]>, + space: Option<&std::sync::Arc>, +) -> Surface { + let mut s = Surface::new(fmt); + let n = fmt.channels(); + let empty = s.default_pixel(); + let mut data = Vec::new(); + // White paper is no ink; another background colour goes through the profile. + let paper = background + .map(|bg| if bg == [1.0; 3] { [0.0; 4] } else { photocraft_color::convert::with_cmyk_space(space, || photocraft_color::convert::rgb_to_cmyk(bg)) }); + let _ = cmyk::render_cmyk_bands(doc, rect, 0, |band| -> Result<(), ()> { + data.clear(); + data.reserve(band.px.len() * n); + for p in &band.px { + push_ink_pixel(&mut data, p, paper, fmt, &empty); + } + s.write_region(band.rect, &data); + Ok(()) + }); + s.prune(); + s +} + +/// Composite the full canvas. +pub fn flatten(doc: &Document) -> Buffer { + render(doc, doc.bounds()) +} + +/// Render an arbitrary subset: a single layer (e.g. for thumbnails), isolated. +/// Rects past [`MAX_RENDER_PIXELS`] give an empty buffer. +pub fn render_layer(layer: &Layer, rect: Rect) -> Buffer { + if u64::from(rect.width()) * u64::from(rect.height()) > MAX_RENDER_PIXELS { + return Buffer::transparent(Rect::EMPTY); + } + let mut buf = Buffer::transparent(rect); + let patterns = pattern::PreparedPatterns::new(&[], pattern::PREPARED_PATTERN_BYTES); + composite_stack_at( + std::slice::from_ref(layer), + &mut buf, + &Ctx { + canvas: rect, + transfer: adjust::Transfer::Srgb, + light: photocraft_doc::GlobalLight::default(), + patterns: &patterns, + mode: photocraft_color::ColorMode::Rgb, + depth: photocraft_color::SampleType::F32, + vector_masks: RenderVectorMasks::default(), + fx_maps: Default::default(), + fx_clip: Default::default(), + fx_over_budget: false, + tone_luts: prepare_tones(std::slice::from_ref(layer), 0), + doc: None, + layer_keys: Default::default(), + }, + advanced::Scope::ROOT, + ); + buf +} + +/// [`render_layer`] in `doc`'s context: the layer alone over `rect`, with the document's patterns, +/// Global Light, colour mode, depth and canvas (fill layers and gradients are laid out on it), as +/// the canvas composites it. Bakes (Scripts › Flatten All Layer Effects) render through this so +/// the pixels match what was on screen (#5719). Rects past [`MAX_RENDER_PIXELS`] give an empty +/// buffer. +pub fn render_layer_in(doc: &Document, layer: &Layer, rect: Rect) -> Buffer { + if rect.is_empty() { + return Buffer::transparent(rect); + } + if u64::from(rect.width()) * u64::from(rect.height()) > MAX_RENDER_PIXELS { + return Buffer::transparent(Rect::EMPTY); + } + let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(doc.pixel_format().mode); + // A lone layer: a deep knockout reveals transparency, not the document's Background. + let cx = Ctx { doc: None, ..Ctx::for_doc(doc, &patterns) }; + let lab = doc.mode == photocraft_color::ColorMode::Lab; + let hdr = doc.depth == photocraft_color::SampleType::F32; + let cmyk = cmyk_space(doc); + photocraft_color::convert::with_cmyk_space(cmyk.as_ref(), || { + let mut buf = Buffer::transparent(rect); + in_blend_space(lab, hdr, || composite_stack_at(std::slice::from_ref(layer), &mut buf, &cx, advanced::Scope::ROOT)); + buf + }) +} diff --git a/crates/engine/src/actions_cmds.rs b/crates/engine/src/actions_cmds.rs deleted file mode 100644 index 7f9b52ff85..0000000000 --- a/crates/engine/src/actions_cmds.rs +++ /dev/null @@ -1,1842 +0,0 @@ -//! Window › Actions, as engine commands (`actions.record` / `stop` / `play` / `list` / `get` / -//! `delete` / `move` / `rename` / `toggle`). -//! -//! The list lives on [`Session`] so the panel, the CLI, the control channel and MCP share one -//! copy. Recording copies replayable journal entries (commands whose [`CommandSpec::journal`] is -//! set, except action-editing commands and the already-expanded `edit.transform.again` and -//! `edit.transform.againCopy`) into an action. A replayable command's journal entry replaces the -//! entries of the commands it ran on its own behalf, so they are recorded once (#3067). Playback -//! runs those steps with [`Session::execute`] and stops at the first error, leaving one history -//! step per step that ran. Steps switched off with `actions.toggle` (the Actions panel check -//! marks) are skipped by playback, Batch and droplets. -//! -//! An untrusted session installs [`Session::authorize`]. `actions.play` calls it for every nested -//! step, because the outer `actions.play` id would otherwise hide a recorded `file.*` command from -//! the top-level check. - -use std::collections::BTreeSet; - -use serde::{Deserialize, Serialize}; -use serde_json::{Value, json}; - -use crate::commands::CommandSpec; -use crate::{EngineError, Result, Session}; - -fn bad(cmd: &str, msg: impl Into) -> EngineError { - EngineError::BadParams { cmd: cmd.into(), msg: msg.into() } -} - -/// One recorded action. `steps` is the `[[id, params], …]` shape `file.automate.batch` and -/// droplets already accept. -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -pub struct Action { - pub name: String, - #[serde(default)] - pub steps: Vec<(String, Value)>, - /// Indices of steps excluded from playback (unchecked in the Actions panel). - #[serde(default, skip_serializing_if = "BTreeSet::is_empty")] - pub disabled: BTreeSet, - /// Indices of steps whose dialog Photoshop shows during playback (the panel's dialog - /// toggle column). Headless playback runs them with their recorded params; the flag is - /// kept so Save Actions writes it back. - #[serde(default, skip_serializing_if = "BTreeSet::is_empty")] - pub dialogs: BTreeSet, - /// The action set the action belongs to: the folder Photoshop shows in the Actions panel, - /// filled by Load Actions (`actions.load`) and written by Save Actions (`actions.save`). - #[serde(default, skip_serializing_if = "Option::is_none")] - pub set: Option, - /// Button Mode colour. Empty is none; otherwise one of [`BUTTON_COLORS`]. - #[serde(default, skip_serializing_if = "String::is_empty")] - pub color: String, -} - -/// Button Mode colours, in Photoshop's order. Empty is no colour. -pub const BUTTON_COLORS: [&str; 8] = ["", "red", "orange", "yellow", "green", "blue", "violet", "gray"]; - -impl Action { - pub fn new(name: impl Into, steps: Vec<(String, Value)>) -> Self { - Self { name: name.into(), steps, disabled: BTreeSet::new(), dialogs: BTreeSet::new(), set: None, color: String::new() } - } - - /// Apply `f` to every per-step index set (`disabled`, `dialogs`) after steps moved. - pub(crate) fn remap_steps(&mut self, f: impl Fn(usize) -> Option) { - self.disabled = self.disabled.iter().filter_map(|&i| f(i)).collect(); - self.dialogs = self.dialogs.iter().filter_map(|&i| f(i)).collect(); - } - - pub fn step_enabled(&self, step: usize) -> bool { - !self.disabled.contains(&step) - } - - /// The steps playback runs, with their indices in `steps`. - pub fn enabled_steps(&self) -> impl Iterator { - self.steps.iter().enumerate().filter(|(i, _)| self.step_enabled(*i)) - } -} - -/// On-disk form of [`ActionState::list`] (`actions.json` in the preset store). -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct ActionsFile { - pub version: u32, - pub actions: Vec, -} - -pub const MAX_PLAYBACK_STEPS: u64 = 100_000; - -/// Actions list and the recording / playback flags. Only `list` is persisted. -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -#[serde(default)] -pub struct ActionState { - pub list: Vec, - /// Journal length when recording started, and the action index being recorded into. - #[serde(skip)] - pub recording: Option<(usize, usize)>, - /// Nesting depth of `actions.play`, bounded by the playback stack limit. - #[serde(skip)] - pub playing: u8, - /// Active action names, for cycle detection in engine and desktop playback. - #[serde(skip)] - pub playback_stack: Vec, - /// Number of steps executed by the current top-level playback tree. - #[serde(skip)] - pub playback_steps: u64, - /// How many scripts (`file.scripts.browse`) are running inside one another. - #[serde(skip)] - pub script_depth: u8, - /// Steps run by the current top-level script and everything it calls. - #[serde(skip)] - pub script_steps: u64, - /// Bumped whenever `list` changes, so the preset store can skip unchanged writes. - #[serde(skip)] - pub rev: u64, - /// Bumped by each `actions.record`, so a background job knows whether the recording it was - /// started in is still the one running when its result lands. - #[serde(skip)] - pub take: u64, -} - -impl ActionState { - pub(crate) fn touch(&mut self) { - self.rev = self.rev.saturating_add(1); - } -} - -/// Replay commands and named action calls, excluding edits to the action definitions and the -/// already-expanded Again wrapper. -pub fn replayable(id: &str) -> bool { - // Again and Again on a Copy journal their concrete steps (`edit.transform`, after - // `layer.duplicate` for the copy) and record those: the wrappers look up the last transform in - // the journal, so they fail where no transform ran yet, e.g. an action played in a new session. - id == "actions.play" - || (!id.starts_with("actions.") - // Browse executes its steps through Session::execute, so those concrete - // commands are already journaled. Recording the wrapper as well replays - // every script edit twice (#3057). - && !matches!(id, "edit.transform.again" | "edit.transform.againCopy" | "file.scripts.browse") - && (shell_view_command(id) || shell_save_command(id) || crate::commands::find(id).is_some_and(|c| c.journal))) -} - -/// File › Save, Save As and Save a Copy, and File › Export › Export As, recorded by the desktop -/// shell once the file has a path (#2032, #4373, #7207). The shell replays them; batch and -/// droplets write to their destination folder instead. -pub fn shell_save_command(id: &str) -> bool { - matches!(id, "file.save" | "file.saveAs" | "file.saveACopy" | "file.export.exportAs") -} - -/// The failure for a played Save step whose document `target` (the one active when the step -/// started) is no longer open: a Save Document script event closed it. Playback stops there, so -/// the next step without a document, such as the Close half of an imported Close with Save: Yes, -/// doesn't act on whichever document is active now (#7367). -pub fn save_target_closed(s: &Session, id: &str, target: Option) -> Option { - let target = target.filter(|_| shell_save_command(id))?; - (!s.documents().iter().any(|d| d.doc.id == target)).then(|| { - "the document was closed during the save (by a Save Document script event); playback stopped so later steps don't act on another document".into() - }) -} - -/// Charge one step against the complete nested playback tree. -pub fn consume_playback_step(s: &mut Session) -> bool { - // Inside a script the step also counts against the script's total: each top-level playback - // resets its own counter, so a script playing actions in a row would never reach the limit. - if s.actions.script_depth > 0 { - if s.actions.script_steps >= crate::automate_cmds::MAX_SCRIPT_STEPS { - return false; - } - s.actions.script_steps += 1; - } - if s.actions.playback_steps >= MAX_PLAYBACK_STEPS { - false - } else { - s.actions.playback_steps += 1; - true - } -} -/// View-only menu commands recorded by the desktop shell. Headless playback reports -/// them as unsupported instead of silently dropping them; Batch and droplets skip them. -pub fn shell_view_command(id: &str) -> bool { - matches!(id, "view.fitOnScreen" | "view.actualPixels" | "view.zoomIn" | "view.zoomOut") -} - -/// Shared validation for headless and shell playback. Does not start playback. -pub fn playback_plan(s: &Session, p: &Value) -> Result<(Action, usize)> { - if s.actions.playing > 0 && s.actions.playback_stack.is_empty() { - return Err(bad("actions.play", "an action is already playing")); - } - let idx = resolve(&s.actions.list, p, "actions.play")?; - let action = s.actions.list.get(idx).cloned().ok_or_else(|| bad("actions.play", "no such action"))?; - if s.actions.playback_stack.iter().any(|name| name == &action.name) || s.actions.recording.is_some_and(|(_, i)| i == idx) { - return Err(bad("actions.play", format!("recursive action call to `{}`", action.name))); - } - if s.actions.playback_stack.len() >= 16 { - return Err(bad("actions.play", "action nesting exceeds 16 levels")); - } - let from = from_step(p, action.steps.len())?; - Ok((action, from)) -} - -/// The actions that `steps` call through Play Action steps and the branches of Conditional steps, -/// followed transitively, in list order, so a droplet can run without the Actions panel that made -/// it (#2794, #6804). Index references in `steps` and in the copies become names, which resolve -/// without the rest of the list. A target that doesn't resolve is left alone: it fails at -/// playback, as it would have before. -pub fn called_actions(list: &[Action], steps: &mut [(String, Value)]) -> Vec { - fn targets(list: &[Action], steps: &mut [(String, Value)], depth: usize, queue: &mut Vec<(usize, usize)>) { - for (id, params) in steps.iter_mut() { - match id.as_str() { - "actions.play" => { - let Ok(i) = resolve(list, params, "actions.play") else { continue }; - if let (Some(action), Some(obj)) = (list.get(i), params.as_object_mut()) { - obj.insert("action".into(), json!(action.name)); - } - queue.push((i, depth)); - } - // Conditional branches only take names, so there is nothing to rewrite. - "actions.conditional" => { - for key in ["then", "else"] { - let Some(name) = params.get(key).and_then(Value::as_str) else { continue }; - if let Some(i) = list.iter().position(|a| a.name == name) { - queue.push((i, depth)); - } - } - } - _ => {} - } - } - } - let mut queue = Vec::new(); - targets(list, steps, 1, &mut queue); - let mut found = std::collections::BTreeMap::new(); - while let Some((i, depth)) = queue.pop() { - // Playback stops at 16 levels, so deeper calls never run. - if depth > 16 || found.contains_key(&i) { - continue; - } - let Some(mut action) = list.get(i).cloned() else { continue }; - targets(list, &mut action.steps, depth + 1, &mut queue); - found.insert(i, action); - } - found.into_values().collect() -} - -fn always(_: &Session) -> std::result::Result<(), String> { - Ok(()) -} - -fn num(v: &Value) -> Option { - v.as_i64().or_else(|| v.as_f64().filter(|f| f.is_finite()).map(|f| f.round() as i64)) -} - -pub(crate) fn resolve(list: &[Action], p: &Value, cmd: &str) -> Result { - let Some(v) = p.get("action") else { - return Err(bad(cmd, "needs \"action\" (a name or an index)")); - }; - if let Some(i) = num(v) { - if i < 0 { - return Err(bad(cmd, "action index is negative")); - } - let Some(i) = usize::try_from(i).ok() else { - return Err(bad(cmd, "action index is out of range")); - }; - if i >= list.len() { - return Err(bad(cmd, format!("no action at index {i}"))); - } - return Ok(i); - } - match v.as_str() { - Some(name) if !name.is_empty() => list.iter().position(|a| a.name == name).ok_or_else(|| bad(cmd, format!("no action named `{name}`"))), - Some(_) => Err(bad(cmd, "action name is empty")), - None => Err(bad(cmd, "\"action\" must be a name or an index")), - } -} - -fn from_step(p: &Value, len: usize) -> Result { - let Some(v) = p.get("from") else { return Ok(0) }; - if v.is_null() { - return Ok(0); - } - let Some(i) = num(v) else { - return Err(bad("actions.play", "\"from\" must be a step index")); - }; - if i < 0 { - return Err(bad("actions.play", "\"from\" is negative")); - } - let Some(i) = usize::try_from(i).ok() else { - return Err(bad("actions.play", "\"from\" is out of range")); - }; - if i > len { - return Err(bad("actions.play", format!("\"from\" {i} is past the last step ({len})"))); - } - Ok(i) -} - -fn list(s: &mut Session, _p: &Value) -> Result { - let actions: Vec = s.actions.list.iter().map(|a| json!({"name": a.name, "steps": a.steps.len(), "set": a.set})).collect(); - let recording = s.actions.recording.and_then(|(_, i)| s.actions.list.get(i).map(|a| a.name.clone())); - Ok(json!({"actions": actions, "recording": recording})) -} - -fn get(s: &mut Session, p: &Value) -> Result { - let idx = resolve(&s.actions.list, p, "actions.get")?; - let action = &s.actions.list[idx]; - let steps: Vec = action.steps.iter().map(|(id, params)| json!([id, params])).collect(); - Ok(json!({"name": action.name, "steps": steps, "disabled": action.disabled, "dialogs": action.dialogs, "set": action.set, "color": action.color})) -} - -fn record(s: &mut Session, p: &Value) -> Result { - not_playing(s, "actions.record")?; - if s.actions.recording.is_some() { - return Err(bad("actions.record", "already recording; stop first")); - } - let idx = if p.get("action").is_some() { - resolve(&s.actions.list, p, "actions.record")? - } else { - let name = match p.get("name") { - None | Some(Value::Null) => { - let mut n = s.actions.list.len().saturating_add(1); - while s.actions.list.iter().any(|a| a.name == format!("Action {n}")) { - n = n.checked_add(1).ok_or_else(|| bad("actions.record", "cannot allocate a unique action name"))?; - } - format!("Action {n}") - } - Some(Value::String(n)) if !n.is_empty() => n.clone(), - Some(Value::String(_)) => return Err(bad("actions.record", "\"name\" is empty")), - Some(_) => return Err(bad("actions.record", "\"name\" must be a string")), - }; - if s.actions.list.iter().any(|action| action.name == name) { - return Err(bad("actions.record", "an action with this name already exists")); - } - s.actions.list.push(Action::new(name, Vec::new())); - s.actions.touch(); - s.actions.list.len() - 1 - }; - s.actions.recording = Some((s.journal.len(), idx)); - s.actions.take = s.actions.take.wrapping_add(1); - let name = s.actions.list.get(idx).map(|a| a.name.clone()).unwrap_or_default(); - Ok(json!({"action": name, "index": idx})) -} - -/// Replayable journal entries not yet committed to this action while recording. -pub fn pending_steps(s: &Session, action: usize) -> impl Iterator { - let from = s.actions.recording.filter(|(_, i)| *i == action).map_or(s.journal.len(), |(from, _)| from); - s.journal.iter().skip(from).filter(|(id, _)| replayable(id)) -} - -pub(crate) fn flush_recording(s: &mut Session) -> Result<()> { - let Some((_, idx)) = s.actions.recording else { return Ok(()) }; - if idx >= s.actions.list.len() { - return Err(bad("actions.stop", "the action being recorded no longer exists")); - } - let steps: Vec<_> = pending_steps(s, idx).cloned().collect(); - s.actions.recording = Some((s.journal.len(), idx)); - if !steps.is_empty() { - s.actions.list[idx].steps.extend(steps); - s.actions.touch(); - } - Ok(()) -} - -fn stop(s: &mut Session, _p: &Value) -> Result { - not_playing(s, "actions.stop")?; - let Some((_, idx)) = s.actions.recording else { - return Err(bad("actions.stop", "not recording")); - }; - flush_recording(s)?; - s.actions.recording = None; - let action = &s.actions.list[idx]; - Ok(json!({"action": action.name, "steps": action.steps.len()})) -} - -/// A step Photoshop plays as a silent no-op although its menu item is greyed: Deselect with an -/// open document and nothing selected (actions often start with it to clear any selection, #6744). -fn noop_step(s: &Session, id: &str) -> bool { - id == "select.deselect" && s.active().is_some_and(|d| d.doc.selection.is_none()) -} - -fn run_recorded(s: &mut Session, action: &Action, from: usize) -> (u64, Option) { - let mut ran = 0u64; - let mut failed = None; - for (i, (id, params)) in action.enabled_steps().skip_while(|(i, _)| *i < from) { - if !consume_playback_step(s) { - failed = Some(json!({"step": i, "id": id, "error": format!("action playback exceeded the {}-step limit", MAX_PLAYBACK_STEPS)})); - break; - } - if let Some(auth) = s.authorize - && let Err(e) = auth(id, params) - { - failed = Some(json!({"step": i, "id": id, "error": e.to_string()})); - break; - } - if noop_step(s, id) { - ran += 1; - continue; - } - match s.execute(id, params.clone()) { - Ok(value) => { - if let Some(error) = nested_failure(id, &value) { - failed = Some(json!({"step": i, "id": id, "error": error})); - break; - } - ran += 1; - } - Err(e) => { - failed = Some(json!({"step": i, "id": id, "error": e.to_string()})); - break; - } - } - } - (ran, failed) -} - -/// Suspend recording while a called action executes. Keep its commands in the journal -/// for diagnostics, but record just the named call in the parent action. -pub fn begin_playback(s: &mut Session, action: &Action) -> Result> { - flush_recording(s)?; - if s.actions.playing == 0 { - s.actions.playback_steps = 0; - } - let recording = s.actions.recording.take(); - s.actions.playing = s.actions.playing.saturating_add(1); - s.actions.playback_stack.push(action.name.clone()); - Ok(recording) -} - -pub fn finish_playback(s: &mut Session, recording: Option<(usize, usize)>, action: &Action, from: usize) { - s.actions.playback_stack.pop(); - s.actions.playing = s.actions.playing.saturating_sub(1); - if let Some((_, idx)) = recording { - restore_recording(s, idx, &action.name, from); - } -} - -/// Resume recording into action `idx` and journal the named call that suspended it. -pub fn restore_recording(s: &mut Session, idx: usize, action: &str, from: usize) { - s.actions.recording = Some((s.journal.len(), idx)); - let mut params = json!({"action": action}); - if from > 0 { - params["from"] = json!(from); - } - s.journal.push(("actions.play".into(), params)); -} - -/// Nested playback returns a structured failure even though the command itself succeeded. -/// Promote it to the caller's failed step so no later parent steps run after a child fails. -pub fn nested_failure(id: &str, value: &Value) -> Option { - (id == "actions.play" || id == "actions.conditional").then(|| value.get("failed")).flatten().map(|failure| { - format!( - "action `{}` step {} failed: {}", - value.get("action").and_then(Value::as_str).unwrap_or(""), - failure.get("step").and_then(Value::as_u64).unwrap_or(0).saturating_add(1), - failure.get("error").and_then(Value::as_str).unwrap_or("unknown error") - ) - }) -} - -fn play(s: &mut Session, p: &Value) -> Result { - let (action, from) = playback_plan(s, p)?; - let recording = begin_playback(s, &action)?; - let (ran, failed) = run_recorded(s, &action, from); - finish_playback(s, recording, &action, from); - Ok(match failed { - Some(f) => json!({"action": action.name, "ran": ran, "failed": f}), - None => json!({"action": action.name, "ran": ran}), - }) -} - -pub(crate) fn not_playing(s: &Session, cmd: &str) -> Result<()> { - if s.actions.playing > 0 { Err(bad(cmd, "cannot edit actions during playback")) } else { Ok(()) } -} - -/// Move to a final zero-based index, either in an action's steps or in the action list. -fn move_item(s: &mut Session, p: &Value) -> Result { - not_playing(s, "actions.move")?; - let idx = resolve(&s.actions.list, p, "actions.move")?; - let index = |key: &str| -> Result { - p.get(key) - .and_then(Value::as_u64) - .and_then(|n| usize::try_from(n).ok()) - .ok_or_else(|| bad("actions.move", format!("{key} must be a non-negative integer"))) - }; - let to = index("to")?; - if p.get("step").is_some() { - let step = index("step")?; - let len = s.actions.list[idx].steps.len().saturating_add(pending_steps(s, idx).count()); - if step >= len || to >= len { - return Err(bad("actions.move", "step or destination is out of range")); - } - if s.actions.recording.is_some_and(|(_, i)| i == idx) { - flush_recording(s)?; - } - let action = &mut s.actions.list[idx]; - let moved = action.steps.remove(step); - action.steps.insert(to, moved); - action.remap_steps(|i| Some(moved_index(i, step, to))); - let result = json!({"action": action.name, "step": to}); - s.actions.touch(); - Ok(result) - } else { - if to >= s.actions.list.len() { - return Err(bad("actions.move", "destination is out of range")); - } - let moved = s.actions.list.remove(idx); - let result = json!({"action": moved.name, "index": to}); - s.actions.list.insert(to, moved); - if let Some((_, recording)) = s.actions.recording.as_mut() { - *recording = moved_index(*recording, idx, to); - } - s.actions.touch(); - Ok(result) - } -} - -/// Follow a selected/recording row when a list item is moved. -pub fn moved_index(index: usize, from: usize, to: usize) -> usize { - if index == from { - to - } else if from < index && index <= to { - index - 1 - } else if to <= index && index < from { - index + 1 - } else { - index - } -} - -fn delete(s: &mut Session, p: &Value) -> Result { - not_playing(s, "actions.delete")?; - let idx = resolve(&s.actions.list, p, "actions.delete")?; - if let Some(step) = p.get("step") { - let step = step.as_u64().and_then(|i| usize::try_from(i).ok()).ok_or_else(|| bad("actions.delete", "step must be a non-negative integer"))?; - let len = s.actions.list[idx].steps.len().saturating_add(pending_steps(s, idx).count()); - if step >= len { - return Err(bad("actions.delete", "step is out of range")); - } - // Commit pending entries before editing the action; never erase the command - // journal or undo the edit that produced the deleted recording step. - if s.actions.recording.is_some_and(|(_, i)| i == idx) { - flush_recording(s)?; - } - let action = &mut s.actions.list[idx]; - action.steps.remove(step); - action.remap_steps(|i| { - if i == step { - None - } else if i > step { - Some(i - 1) - } else { - Some(i) - } - }); - let result = json!({"action": action.name, "deletedStep": step, "steps": action.steps.len()}); - s.actions.touch(); - return Ok(result); - } - if s.actions.recording.is_some() { - return Err(bad("actions.delete", "stop recording before deleting an action")); - } - let name = s.actions.list.remove(idx).name; - s.actions.touch(); - // Its function key goes with it, or the next action given the same name would inherit it. - let key = format!("{PLAY_SHORTCUT_PREFIX}{name}"); - if s.prefs().shortcuts.contains_key(&key) { - s.edit_prefs(|prefs| { - prefs.shortcuts.remove(&key); - }); - } - Ok(json!({"deleted": name})) -} - -/// The Actions panel check marks. With `step`, switch one step on or off; without it, switch -/// every step (all on unless all already are, like clicking the action's check mark). -fn toggle(s: &mut Session, p: &Value) -> Result { - let cmd = "actions.toggle"; - not_playing(s, cmd)?; - let idx = resolve(&s.actions.list, p, cmd)?; - let enabled = match p.get("enabled") { - None | Some(Value::Null) => None, - Some(Value::Bool(b)) => Some(*b), - Some(_) => return Err(bad(cmd, "\"enabled\" must be true or false")), - }; - let step = match p.get("step") { - None | Some(Value::Null) => None, - Some(v) => Some(v.as_u64().and_then(|i| usize::try_from(i).ok()).ok_or_else(|| bad(cmd, "step must be a non-negative integer"))?), - }; - let len = s.actions.list[idx].steps.len().saturating_add(pending_steps(s, idx).count()); - if step.is_some_and(|step| step >= len) { - return Err(bad(cmd, "step is out of range")); - } - if s.actions.recording.is_some_and(|(_, i)| i == idx) { - flush_recording(s)?; - } - let action = &mut s.actions.list[idx]; - match step { - Some(step) => { - if enabled.unwrap_or(!action.step_enabled(step)) { - action.disabled.remove(&step); - } else { - action.disabled.insert(step); - } - } - None if enabled.unwrap_or(!action.disabled.is_empty()) => action.disabled.clear(), - None => action.disabled = (0..action.steps.len()).collect(), - } - let result = json!({"action": action.name, "disabled": action.disabled}); - s.actions.touch(); - Ok(result) -} - -/// Prefix of the persisted shortcut override that plays a named action (`actions.play:`). -pub const PLAY_SHORTCUT_PREFIX: &str = "actions.play:"; - -/// Rename an action in place. Nested `actions.play` steps and `actions.conditional` branches -/// that call it by name, and its function-key binding, follow the new name so nothing silently -/// stops working. -fn rename(s: &mut Session, p: &Value) -> Result { - not_playing(s, "actions.rename")?; - let idx = resolve(&s.actions.list, p, "actions.rename")?; - let name = match p.get("name") { - Some(Value::String(n)) if !n.trim().is_empty() => n.clone(), - Some(Value::String(_)) => return Err(bad("actions.rename", "\"name\" is empty")), - Some(_) => return Err(bad("actions.rename", "\"name\" must be a string")), - None => return Err(bad("actions.rename", "needs \"name\"")), - }; - let old = s.actions.list.get(idx).map(|a| a.name.clone()).ok_or_else(|| bad("actions.rename", "no such action"))?; - if old == name { - return Ok(json!({"action": name, "index": idx})); - } - if s.actions.list.iter().any(|a| a.name == name) { - return Err(bad("actions.rename", "an action with this name already exists")); - } - let pending = s.actions.recording.map_or(s.journal.len(), |(start, _)| start); - let calls = s.actions.list.iter_mut().flat_map(|a| a.steps.iter_mut()).chain(s.journal.iter_mut().skip(pending)); - for (id, params) in calls { - let keys: &[&str] = match id.as_str() { - "actions.play" => &["action"], - "actions.conditional" => &["then", "else"], - _ => &[], - }; - for key in keys { - if params.get(*key).and_then(Value::as_str) == Some(old.as_str()) { - params[*key] = json!(name); - } - } - } - if let Some(action) = s.actions.list.get_mut(idx) { - action.name = name.clone(); - } - s.actions.touch(); - let (from, to) = (format!("{PLAY_SHORTCUT_PREFIX}{old}"), format!("{PLAY_SHORTCUT_PREFIX}{name}")); - if s.prefs().shortcuts.contains_key(&from) { - s.edit_prefs(|prefs| { - if let Some(key) = prefs.shortcuts.remove(&from) { - prefs.shortcuts.insert(to, key); - } - }); - } - Ok(json!({"action": name, "index": idx})) -} - -fn set_color(s: &mut Session, p: &Value) -> Result { - let cmd = "actions.setColor"; - not_playing(s, cmd)?; - let idx = resolve(&s.actions.list, p, cmd)?; - let Some(color) = p.get("color").and_then(Value::as_str) else { - return Err(bad(cmd, "needs \"color\"")); - }; - if !BUTTON_COLORS.contains(&color) { - return Err(bad(cmd, "color must be empty, red, orange, yellow, green, blue, violet, or gray")); - } - let Some(action) = s.actions.list.get_mut(idx) else { - return Err(bad(cmd, "no such action")); - }; - action.color = color.to_string(); - let name = action.name.clone(); - s.actions.touch(); - Ok(json!({"action": name, "color": color})) -} - -pub fn specs() -> Vec { - vec![ - CommandSpec { - id: "actions.move", - label: "Move Action or Step", - menu: &[], - shortcut: None, - params: r##"{"action":name|index, "step":index?, "to":index}. Move a step within its action, or the action itself. to is the final zero-based index. Pending recorded steps can be moved."##, - enabled: always, - run: move_item, - journal: false, - }, - CommandSpec { - id: "actions.list", - label: "List Actions", - menu: &[], - shortcut: None, - params: "{} → {actions:[{name, steps:count, set:name|null}], recording:name|null}", - enabled: always, - run: list, - journal: false, - }, - CommandSpec { - id: "actions.get", - label: "Get Action", - menu: &[], - shortcut: None, - params: r##"{"action":name|index} → {name, steps:[[id, params]…], disabled:[step…], dialogs:[step…], set:name|null, color:str} (steps is the shape file.automate.batch and droplets take; disabled lists the 0-based steps playback skips; dialogs the steps whose dialog Photoshop would show; set the action set from Load Actions; color is the Button Mode swatch, or empty)"##, - enabled: always, - run: get, - journal: false, - }, - CommandSpec { - id: "actions.record", - label: "Record Action", - menu: &[], - shortcut: None, - params: r##"{"name":str? (new action, default "Action N")} or {"action":name|index} (append) → {action, index}"##, - enabled: always, - run: record, - journal: false, - }, - CommandSpec { - id: "actions.stop", - label: "Stop Recording", - menu: &[], - shortcut: None, - params: "{} → {action, steps:count} (steps recorded since actions.record, queries and action-editing commands omitted)", - enabled: always, - run: stop, - journal: false, - }, - CommandSpec { - id: "actions.play", - label: "Play Action", - menu: &[], - shortcut: None, - params: r##"{"action":name|index, "from":step?} → {action, ran, failed?:{step, id, error}}. step and from are 0-based; steps switched off with actions.toggle are skipped. Stops at the first error (the command still returns ok, with failed set) and leaves one history step per step that ran. Nested calls are supported up to 16 levels; cycles are rejected. Recording stores a named call rather than its expanded commands. Each step is checked with Session::authorize when one is installed."##, - enabled: always, - run: play, - journal: false, - }, - CommandSpec { - id: "actions.delete", - label: "Delete Action", - menu: &[], - shortcut: None, - params: r##"{"action":name|index, "step":index?} → {deleted:name} or {action, deletedStep, steps:count}. step is 0-based, including pending recorded steps. Whole-action deletion is refused while recording."##, - enabled: always, - run: delete, - journal: false, - }, - CommandSpec { - id: "actions.toggle", - label: "Toggle Action Steps", - menu: &[], - shortcut: None, - params: r##"{"action":name|index, "step":index?, "enabled":bool?} → {action, disabled:[step…]}. Switch one 0-based step (including pending recorded steps) on or off for playback, Batch and droplets; omitted enabled flips it. Without step, switch every step: on unless all already are, or as enabled says."##, - enabled: always, - run: toggle, - journal: false, - }, - CommandSpec { - id: "actions.rename", - label: "Rename Action", - menu: &[], - shortcut: None, - params: r##"{"action":name|index, "name":str} → {action, index}. The name must not be empty or whitespace-only and must be unique. Nested Play Action steps and the action's function key follow the rename."##, - enabled: always, - run: rename, - journal: false, - }, - CommandSpec { - id: "actions.setColor", - label: "Set Action Color", - menu: &[], - shortcut: None, - params: r##"{"action":name|index, "color":""|"red"|"orange"|"yellow"|"green"|"blue"|"violet"|"gray"} → {action, color}. The Button Mode colour. Empty clears it."##, - enabled: always, - run: set_color, - journal: false, - }, - ] -} - -#[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - - fn pixel(s: &Session, layer: usize, x: i32, y: i32) -> Vec { - s.active().unwrap().doc.layers[layer].surface().unwrap().pixel(x, y) - } - - #[test] - fn deselect_with_nothing_selected_is_a_noop_in_playback() { - // #6744: imported actions often start with Deselect; with no selection Photoshop plays on. - let mut s = Session::new(); - s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); - let before = s.active().unwrap().history.past_len(); - // Outside playback the command stays disabled, like Photoshop's greyed menu item. - assert!(s.execute("select.deselect", json!({})).is_err()); - assert!(s.active().unwrap().doc.selection.is_none()); - assert_eq!(s.active().unwrap().history.past_len(), before, "rejection adds no history step"); - let deselect = crate::commands::find("select.deselect").unwrap(); - assert_eq!((deselect.run)(&mut s, &json!({})).unwrap(), Value::Null); - assert_eq!(s.active().unwrap().history.past_len(), before, "no history step"); - - let steps = vec![("select.deselect".to_string(), json!({})), ("layer.new.layer".to_string(), json!({"name": "A"}))]; - s.actions.list.push(Action::new("Clear", steps)); - let played = s.execute("actions.play", json!({"action": 0})).unwrap(); - assert_eq!(played["ran"], 2, "{played}"); - assert_eq!(s.active().unwrap().doc.layers.last().unwrap().name, "A"); - } - - #[test] - fn unchecked_steps_are_skipped_and_follow_move_and_delete() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); - let step = |name: &str| ("layer.new.layer".to_string(), json!({"name": name})); - s.actions.list.push(Action::new("Three", vec![step("A"), step("B"), step("C")])); - let names = |s: &Session| s.active().unwrap().doc.layers.iter().skip(1).map(|l| l.name.clone()).collect::>(); - - assert_eq!(s.execute("actions.toggle", json!({"action": "Three", "step": 1})).unwrap()["disabled"], json!([1])); - let played = s.execute("actions.play", json!({"action": 0})).unwrap(); - assert_eq!(played["ran"], 2); - assert_eq!(names(&s), ["A", "C"], "the unchecked step is skipped"); - assert_eq!(s.execute("actions.get", json!({"action": 0})).unwrap()["disabled"], json!([1])); - - // Moving step 3 to the top keeps B (now step 2) unchecked; deleting the moved step shifts it to 1. - s.execute("actions.move", json!({"action": 0, "step": 2, "to": 0})).unwrap(); - let ids: Vec<_> = s.actions.list[0].steps.iter().map(|(_, p)| p["name"].as_str().unwrap()).collect(); - assert_eq!((ids, s.actions.list[0].disabled.iter().copied().collect::>()), (vec!["C", "A", "B"], vec![2])); - s.execute("actions.delete", json!({"action": 0, "step": 0})).unwrap(); - assert_eq!(s.actions.list[0].steps, [step("A"), step("B")], "deleting removes only that step"); - assert_eq!(s.actions.list[0].disabled.iter().copied().collect::>(), [1]); - - // The action's own check: all on unless all already are. - s.execute("actions.toggle", json!({"action": 0})).unwrap(); - assert!(s.actions.list[0].disabled.is_empty()); - s.execute("actions.toggle", json!({"action": 0})).unwrap(); - assert_eq!(s.actions.list[0].disabled.len(), 2); - s.execute("actions.toggle", json!({"action": 0, "step": 0, "enabled": true})).unwrap(); - assert_eq!(s.actions.list[0].disabled.iter().copied().collect::>(), [1]); - - for bad in [ - json!({"action": 0, "step": 2}), - json!({"action": 0, "step": -1}), - json!({"action": 0, "step": "x"}), - json!({"action": 0, "step": 0, "enabled": "yes"}), - json!({"action": 7, "step": 0}), - json!({}), - ] { - assert!(s.execute("actions.toggle", bad.clone()).is_err(), "{bad}"); - } - assert_eq!(s.actions.list[0].disabled.iter().copied().collect::>(), [1], "rejected toggles change nothing"); - } - - #[test] - fn rename_keeps_calls_and_function_key_and_rejects_bad_names() { - let mut s = Session::new(); - s.actions.list.push(Action { - name: "Action 1".into(), - steps: vec![("layer.new.layer".into(), json!({}))], - disabled: Default::default(), - ..Default::default() - }); - s.actions.list.push(Action { - name: "Caller".into(), - steps: vec![("actions.play".into(), json!({"action": "Action 1"}))], - disabled: Default::default(), - ..Default::default() - }); - s.edit_prefs(|p| p.shortcuts.insert(format!("{PLAY_SHORTCUT_PREFIX}Action 1"), "F2".into())); - assert_eq!(s.execute("actions.rename", json!({"action": 0, "name": "Sepia"})).unwrap()["action"], "Sepia"); - assert_eq!(s.execute("actions.list", json!({})).unwrap()["actions"][0]["name"], "Sepia"); - assert_eq!(s.actions.list[1].steps[0].1["action"], "Sepia"); - assert_eq!(s.prefs().shortcuts.get("actions.play:Sepia").map(String::as_str), Some("F2")); - assert!(!s.prefs().shortcuts.contains_key("actions.play:Action 1")); - for bad in [ - json!({"action": 0, "name": ""}), - json!({"action": 0, "name": " "}), - json!({"action": 0, "name": "Caller"}), - json!({"action": 0, "name": 7}), - json!({"action": 9, "name": "X"}), - json!({"action": 0}), - ] { - assert!(s.execute("actions.rename", bad.clone()).is_err(), "{bad}"); - } - assert_eq!(s.actions.list[0].name, "Sepia"); - } - - #[test] - fn rename_follows_conditional_branches() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); - for name in ["B", "Other"] { - s.actions.list.push(Action { name: name.into(), steps: vec![("layer.new.layer".into(), json!({}))], ..Default::default() }); - } - s.actions.list.push(Action { - name: "Main".into(), - steps: vec![ - ("actions.conditional".into(), json!({"if": "always", "then": "B", "else": "Other"})), - ("actions.conditional".into(), json!({"if": "never", "then": "Other", "else": "B"})), - ], - ..Default::default() - }); - s.execute("actions.rename", json!({"action": "B", "name": "C"})).unwrap(); - let steps = &s.actions.list[2].steps; - assert_eq!(steps[0].1, json!({"if": "always", "then": "C", "else": "Other"})); - assert_eq!(steps[1].1, json!({"if": "never", "then": "Other", "else": "C"})); - let r = s.execute("actions.play", json!({"action": "Main"})).unwrap(); - assert!(r.get("failed").is_none(), "{r}"); - } - - #[test] - fn delete_action_drops_its_function_key_but_deleting_a_step_keeps_it() { - let mut s = Session::new(); - let key = format!("{PLAY_SHORTCUT_PREFIX}Action 1"); - s.actions.list.push(Action::new("Action 1", vec![("layer.new.layer".into(), json!({})), ("layer.new.layer".into(), json!({}))])); - s.edit_prefs(|p| p.shortcuts.insert(key.clone(), "F2".into())); - s.execute("actions.delete", json!({"action": 0, "step": 0})).unwrap(); - assert_eq!(s.prefs().shortcuts.get(&key).map(String::as_str), Some("F2"), "deleting a step keeps the key"); - assert_eq!(s.execute("actions.delete", json!({"action": 0})).unwrap()["deleted"], "Action 1"); - assert!(!s.prefs().shortcuts.contains_key(&key), "the deleted action's function key is gone"); - s.execute("actions.record", json!({})).unwrap(); - s.execute("actions.stop", json!({})).unwrap(); - assert_eq!(s.actions.list[0].name, "Action 1"); - assert!(!s.prefs().shortcuts.contains_key(&key), "a new action with the same name starts unbound"); - } - - fn record_red(s: &mut Session, depth: u32) { - s.execute("file.new", json!({"width": 40, "height": 40, "depth": depth})).unwrap(); - s.execute("actions.record", json!({"name": "Red"})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.execute("select.rect", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); - s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); - let _ = s.execute("document.pixel", json!({"x": 1, "y": 1})); - let _ = s.execute("actions.list", json!({})); - s.execute("actions.stop", json!({})).unwrap(); - } - - fn translated_square(s: &mut Session, depth: u32) { - s.execute("file.new", json!({"width": 20, "height": 8, "depth": depth, "background": "transparent"})).unwrap(); - s.edit("red square", |doc, _| { - doc.layers[0].surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(0, 2, 2, 4), &[1.0, 0.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 4, 0], "interpolation": "nearest"})).unwrap(); - assert_eq!(pixel(s, 0, 4, 2), vec![1.0, 0.0, 0.0, 1.0]); - } - - #[test] - fn record_transform_again_replays_one_concrete_transform_at_each_depth() { - for depth in [8, 16, 32] { - let mut s = Session::new(); - translated_square(&mut s, depth); - let from = s.journal.len(); - s.execute("actions.record", json!({"name": "Again"})).unwrap(); - s.execute("edit.transform.again", json!({})).unwrap(); - let ids: Vec<&str> = s.journal.iter().skip(from).map(|(id, _)| id.as_str()).collect(); - assert_eq!(ids, ["edit.transform", "edit.transform.again"], "both commands stay in the journal during recording"); - let live_count = s.journal.iter().skip(from).filter(|(id, _)| replayable(id)).count(); - s.execute("actions.stop", json!({})).unwrap(); - let recorded = s.execute("actions.get", json!({"action": "Again"})).unwrap(); - let steps = recorded["steps"].as_array().unwrap(); - assert_eq!(steps.len(), 1, "depth {depth}: record the concrete transform once"); - assert_eq!(live_count, 1, "depth {depth}: the live Actions count agrees"); - assert_eq!(steps[0][0], "edit.transform"); - assert_eq!(steps[0][1]["matrix"], json!([1, 0, 0, 1, 4, 0])); - assert_eq!(steps[0][1]["interpolation"], "nearest"); - - translated_square(&mut s, depth); - let before = s.active().unwrap().history.past_len(); - let played = s.execute("actions.play", json!({"action": "Again"})).unwrap(); - assert!(played.get("failed").is_none(), "depth {depth}: {played}"); - assert_eq!(played["ran"], 1, "depth {depth}: apply the recorded transform once"); - assert_eq!(s.active().unwrap().history.past_len(), before + 1, "depth {depth}: one undo step"); - assert_eq!(pixel(&s, 0, 8, 2), vec![1.0, 0.0, 0.0, 1.0], "depth {depth}: moved four pixels"); - assert_eq!(pixel(&s, 0, 12, 2), vec![0.0; 4], "depth {depth}: no second transform"); - assert!(s.undo()); - assert_eq!(pixel(&s, 0, 4, 2), vec![1.0, 0.0, 0.0, 1.0]); - assert_eq!(pixel(&s, 0, 8, 2), vec![0.0; 4]); - assert!(s.redo()); - assert_eq!(pixel(&s, 0, 8, 2), vec![1.0, 0.0, 0.0, 1.0]); - assert_eq!(pixel(&s, 0, 4, 2), vec![0.0; 4]); - } - } - - #[test] - fn record_transform_again_on_a_copy_replays_in_a_session_without_a_transform() { - for depth in [8, 16] { - let mut s = Session::new(); - translated_square(&mut s, depth); - s.execute("actions.record", json!({"name": "Step"})).unwrap(); - s.execute("edit.transform.againCopy", json!({})).unwrap(); - s.execute("actions.stop", json!({})).unwrap(); - let got = s.execute("actions.get", json!({"action": "Step"})).unwrap(); - let ids: Vec<&str> = got["steps"].as_array().unwrap().iter().map(|st| st[0].as_str().unwrap()).collect(); - assert_eq!(ids, ["layer.duplicate", "edit.transform"], "depth {depth}: the concrete steps, not the wrapper"); - let action = s.actions.list[0].clone(); - - // A new session has no transform to repeat: the concrete steps still play. - let mut fresh = Session::new(); - fresh.execute("file.new", json!({"width": 20, "height": 8, "depth": depth, "background": "transparent"})).unwrap(); - fresh - .edit("red square", |doc, _| { - doc.layers[0].surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(4, 2, 6, 4), &[1.0, 0.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - fresh.actions.list.push(action); - let played = fresh.execute("actions.play", json!({"action": "Step"})).unwrap(); - assert!(played.get("failed").is_none(), "depth {depth}: {played}"); - assert_eq!(played["ran"], 2, "depth {depth}"); - assert_eq!(fresh.active().unwrap().doc.layers.len(), 2, "depth {depth}: one copy"); - assert_eq!(pixel(&fresh, 0, 4, 2), vec![1.0, 0.0, 0.0, 1.0], "depth {depth}: the original stays"); - assert_eq!(pixel(&fresh, 1, 8, 2), vec![1.0, 0.0, 0.0, 1.0], "depth {depth}: the copy moved four pixels"); - assert_eq!(pixel(&fresh, 1, 4, 2), vec![0.0; 4], "depth {depth}: moved once"); - } - } - - #[test] - fn record_drops_the_steps_of_a_command_that_failed_and_was_taken_back() { - // Transform Again on a Copy of a position-locked layer duplicates it, fails to move the - // copy and takes the copy back: nothing is left to record. - let mut s = Session::new(); - translated_square(&mut s, 8); - let id = s.active().unwrap().active_layer.unwrap(); - s.execute("layer.setProps", json!({"layer": id.0, "locks": {"position": true}})).unwrap(); - s.execute("actions.record", json!({"name": "Locked"})).unwrap(); - assert!(s.execute("edit.transform.againCopy", json!({})).is_err()); - assert_eq!(s.execute("actions.stop", json!({})).unwrap()["steps"], 0, "no Duplicate step for a copy that was taken back"); - - // Straighten rolls back when its crop is refused after the rotation ran. - ruled_background(&mut s, 8); - s.execute("image.analysis.rulerTool", json!({"start": [10, 30], "end": [70, 25]})).unwrap(); - s.authorize = Some(|id, _| if id == "image.crop" { Err(EngineError::Other("refused".into())) } else { Ok(()) }); - s.execute("actions.record", json!({"name": "Refused"})).unwrap(); - assert!(s.execute("image.analysis.straightenLayer", json!({})).is_err()); - assert_eq!(s.active().unwrap().doc.size.width, 80, "the rotation was taken back"); - assert_eq!(s.execute("actions.stop", json!({})).unwrap()["steps"], 0, "no rotation step for a rotation that was taken back"); - } - - #[test] - fn record_script_that_plays_an_action_keeps_each_step_once() { - let mut s = Session::new(); - translated_square(&mut s, 8); - s.execute("actions.record", json!({"name": "Inner"})).unwrap(); - s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 1, 0], "interpolation": "nearest"})).unwrap(); - s.execute("actions.stop", json!({})).unwrap(); - - // Browse records the concrete steps it ran, not itself (#3057): the script's transform and - // the action call, each once, in order. - let script = json!({"steps": [["edit.transform", {"matrix": [1, 0, 0, 1, 2, 0], "interpolation": "nearest"}], ["actions.play", {"action": "Inner"}]]}); - s.execute("actions.record", json!({"name": "Outer"})).unwrap(); - s.execute("file.scripts.browse", script.clone()).unwrap(); - s.execute("actions.stop", json!({})).unwrap(); - let got = s.execute("actions.get", json!({"action": "Outer"})).unwrap(); - assert_eq!(got["steps"], script["steps"]); - } - - #[test] - fn record_explicit_transform_keeps_one_replayable_step() { - let mut s = Session::new(); - translated_square(&mut s, 8); - s.execute("actions.record", json!({"name": "Move"})).unwrap(); - s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 4, 0], "interpolation": "nearest"})).unwrap(); - assert_eq!(s.execute("actions.stop", json!({})).unwrap()["steps"], 1); - let recorded = s.execute("actions.get", json!({"action": "Move"})).unwrap(); - assert_eq!(recorded["steps"][0][0], "edit.transform"); - - translated_square(&mut s, 8); - let before = s.active().unwrap().history.past_len(); - let played = s.execute("actions.play", json!({"action": "Move"})).unwrap(); - assert!(played.get("failed").is_none(), "{played}"); - assert_eq!(played["ran"], 1); - assert_eq!(s.active().unwrap().history.past_len(), before + 1); - assert_eq!(pixel(&s, 0, 8, 2), vec![1.0, 0.0, 0.0, 1.0]); - assert_eq!(pixel(&s, 0, 12, 2), vec![0.0; 4]); - } - - /// A Background with a red bar and a slanted ruler line, ready for Straighten. - fn ruled_background(s: &mut Session, depth: u32) { - s.execute("file.new", json!({"width": 80, "height": 60, "depth": depth})).unwrap(); - s.edit("red bar", |doc, _| { - doc.layers[0].surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(10, 20, 60, 8), &[1.0, 0.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - } - - #[test] - fn record_command_that_runs_commands_replays_it_once() { - // Straighten Layer runs Image Rotation and Crop itself: only its own call is recorded, - // so playback rotates once, not three times (rotate, crop, then straighten again). - for depth in [8, 16] { - let mut s = Session::new(); - ruled_background(&mut s, depth); - s.execute("actions.record", json!({"name": "Level"})).unwrap(); - s.execute("image.analysis.rulerTool", json!({"start": [10, 30], "end": [70, 25]})).unwrap(); - s.execute("image.analysis.straightenLayer", json!({})).unwrap(); - s.execute("actions.stop", json!({})).unwrap(); - let got = s.execute("actions.get", json!({"action": "Level"})).unwrap(); - let ids: Vec<&str> = got["steps"].as_array().unwrap().iter().map(|st| st[0].as_str().unwrap()).collect(); - assert_eq!(ids, ["image.analysis.rulerTool", "image.analysis.straightenLayer"], "depth {depth}"); - let direct = s.active().unwrap().doc.clone(); - - ruled_background(&mut s, depth); - let before = s.active().unwrap().history.past_len(); - let played = s.execute("actions.play", json!({"action": "Level"})).unwrap(); - assert!(played.get("failed").is_none(), "depth {depth}: {played}"); - assert_eq!(played["ran"], 2, "depth {depth}"); - assert_eq!(s.active().unwrap().history.past_len(), before + 1, "depth {depth}: one Straighten step (the ruler is no step)"); - let replayed = s.active().unwrap().doc.clone(); - assert_eq!(replayed.size, direct.size, "depth {depth}: rotated and cropped once"); - let r = photocraft_geom::Rect::new(0, 0, direct.size.width as i32, direct.size.height as i32); - let px = |d: &photocraft_doc::Document| d.layers[0].surface().unwrap().read_region(r); - assert_eq!(px(&replayed), px(&direct), "depth {depth}: same pixels as the direct run"); - } - } - - #[test] - fn record_keeps_only_replayable_steps() { - let mut s = Session::new(); - record_red(&mut s, 8); - let got = s.execute("actions.get", json!({"action": "Red"})).unwrap(); - let ids: Vec<&str> = got["steps"].as_array().unwrap().iter().map(|st| st[0].as_str().unwrap()).collect(); - assert_eq!(ids, ["layer.new.layer", "select.rect", "edit.fill"]); - assert!(s.journal.iter().all(|(id, _)| !id.starts_with("actions."))); - let listed = s.execute("actions.list", json!({})).unwrap(); - assert_eq!(listed["actions"][0]["steps"], 3); - assert!(listed["recording"].is_null()); - } - - #[test] - fn play_on_another_document_matches_pixels_at_each_depth() { - for depth in [8, 16, 32] { - let mut s = Session::new(); - record_red(&mut s, depth); - s.execute("file.new", json!({"width": 40, "height": 40, "depth": depth})).unwrap(); - let before = s.active().unwrap().history.past_len(); - let r = s.execute("actions.play", json!({"action": 0})).unwrap(); - assert!(r.get("failed").is_none(), "depth {depth}: {r}"); - assert_eq!(r["ran"], 3, "depth {depth}"); - assert_eq!(s.active().unwrap().doc.layers.len(), 2, "depth {depth}"); - assert_eq!(s.active().unwrap().history.past_len(), before + 3, "depth {depth}: one history step per played step"); - let px = pixel(&s, 1, 5, 5); - assert!(px.iter().zip([1.0, 0.0, 0.0, 1.0]).all(|(a, b)| (a - b).abs() < 1.0e-5), "depth {depth}: {px:?}"); - assert_eq!(s.actions.playing, 0); - } - } - - #[test] - fn recorded_layer_selection_replays_by_name_on_another_document() { - for depth in [8, 16, 32] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 8, "height": 8, "depth": depth})).unwrap(); - let original = s.active().unwrap().active_layer.unwrap(); - s.execute("layer.setProps", json!({"name": "Photo"})).unwrap(); - s.execute("layer.new.layer", json!({"name": "LogoBase"})).unwrap(); - s.execute("actions.record", json!({"name": "Duplicate photo"})).unwrap(); - s.execute("layer.select", json!({"layer": original.0, "mode": "replace"})).unwrap(); - // The target name must be captured now, not when recording stops. - s.execute("layer.setProps", json!({"name": "Retouched"})).unwrap(); - s.execute("layer.duplicate", json!({})).unwrap(); - s.execute("actions.stop", json!({})).unwrap(); - assert_eq!(s.actions.list[0].steps[0].1, json!({"name":"Photo", "mode":"replace"})); - // Persisted actions must work in an entirely different session too. - let saved = serde_json::to_string(&s.actions.list).unwrap(); - let mut replay = Session::new(); - replay.actions.list = serde_json::from_str(&saved).unwrap(); - replay.execute("file.new", json!({"width": 8, "height": 8, "depth": depth})).unwrap(); - replay.execute("layer.setProps", json!({"name": "Photo"})).unwrap(); - let target = replay.active().unwrap().active_layer.unwrap(); - assert_ne!(original, target); - replay.execute("layer.new.layer", json!({"name": "LogoBase"})).unwrap(); - let result = replay.execute("actions.play", json!({"action": 0})).unwrap(); - assert!(result.get("failed").is_none(), "{result}"); - assert_eq!(result["ran"], 3); - assert_eq!(replay.active().unwrap().doc.layer(target).unwrap().name, "Retouched"); - let active = replay.active().unwrap().active_layer.unwrap(); - assert_eq!(replay.active().unwrap().doc.layer(active).unwrap().name, "Retouched copy"); - } - } - - /// #7845: dragging a layer in the Layers panel while recording keeps the drop target by name, - /// so the action plays on another document (whose layer ids differ) instead of failing with - /// "no such layer". The reporter's steps, replayed on a new document. - #[test] - fn recorded_layer_drag_replays_on_another_document() { - for depth in [8, 16, 32] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 16, "height": 16, "depth": depth})).unwrap(); - s.execute("actions.record", json!({"name": "Retouch"})).unwrap(); - s.execute("layer.stampVisible", json!({})).unwrap(); - let layer1 = s.active().unwrap().active_layer.unwrap(); - s.execute("layer.new.layerViaCopy", json!({})).unwrap(); - let layer2 = s.active().unwrap().active_layer.unwrap(); - s.execute("layer.select", json!({"layer": layer1.0, "mode": "replace"})).unwrap(); - s.execute("filter.noise.median", json!({"radius": 6})).unwrap(); - s.execute("layer.new.layerViaCopy", json!({})).unwrap(); - let copy = s.active().unwrap().active_layer.unwrap(); - s.execute("layer.moveTo", json!({"layer": copy.0, "target": layer2.0, "position": "above"})).unwrap(); - s.execute("actions.stop", json!({})).unwrap(); - let (id, step) = s.actions.list[0].steps.last().unwrap(); - assert_eq!((id.as_str(), step), ("layer.moveTo", &json!({"target": "Layer 1 copy", "position": "above"}))); - let names = |s: &Session| s.active().unwrap().doc.layers.iter().rev().map(|l| l.name.clone()).collect::>(); - let recorded = names(&s); - let saved = serde_json::to_string(&s.actions.list).unwrap(); - let mut replay = Session::new(); - replay.actions.list = serde_json::from_str(&saved).unwrap(); - replay.execute("file.new", json!({"width": 16, "height": 16, "depth": depth})).unwrap(); - let result = replay.execute("actions.play", json!({"action": 0})).unwrap(); - assert!(result.get("failed").is_none(), "{depth}: {result}"); - assert_eq!(names(&replay), recorded, "{depth}: the same stack"); - } - // Several layers of the drop target's name: the recorded occurrence picks the right one. - let mut s = Session::new(); - s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); - s.execute("layer.new.layer", json!({"name": "Twin"})).unwrap(); - s.execute("layer.new.layer", json!({"name": "Twin"})).unwrap(); - let upper = s.active().unwrap().active_layer.unwrap(); - s.execute("layer.new.layer", json!({"name": "Mover"})).unwrap(); - let mover = s.active().unwrap().active_layer.unwrap(); - s.execute("actions.record", json!({"name": "Drop"})).unwrap(); - s.execute("layer.moveTo", json!({"layer": mover.0, "target": upper.0, "position": "below"})).unwrap(); - s.execute("actions.stop", json!({})).unwrap(); - assert_eq!(s.actions.list[0].steps[0].1, json!({"target": "Twin", "targetOccurrence": 1, "position": "below"})); - // The moved layer shares the target's name: the occurrence counts the other "Twin"s only, - // so it means the same layer before the move (on replay) as after it (when recorded). - let build = |s: &mut Session| { - s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); - for _ in 0..3 { - s.execute("layer.new.layer", json!({"name": "Twin"})).unwrap(); - } - s.active().unwrap().doc.layers.iter().map(|l| l.id).collect::>() - }; - let mut s = Session::new(); - let ids = build(&mut s); - let (lowest, top) = (ids[1], ids[3]); - s.execute("actions.record", json!({"name": "Twins"})).unwrap(); - s.execute("layer.moveTo", json!({"layer": top.0, "target": lowest.0, "position": "below"})).unwrap(); - s.execute("actions.stop", json!({})).unwrap(); - assert_eq!(s.actions.list[0].steps[0].1, json!({"target": "Twin", "targetOccurrence": 0, "position": "below"})); - let order = |s: &Session| s.active().unwrap().doc.layers.iter().map(|l| l.id).collect::>(); - let want: Vec<_> = order(&s).iter().map(|id| ids.iter().position(|x| x == id).unwrap()).collect(); - let saved = serde_json::to_string(&s.actions.list).unwrap(); - let mut replay = Session::new(); - replay.actions.list = serde_json::from_str(&saved).unwrap(); - let ids2 = build(&mut replay); - let result = replay.execute("actions.play", json!({"action": 0})).unwrap(); - assert!(result.get("failed").is_none(), "{result}"); - let got: Vec<_> = order(&replay).iter().map(|id| ids2.iter().position(|x| x == id).unwrap()).collect(); - assert_eq!(got, want, "the same layer became the lowest"); - // A moved group holding a same-named layer: its contents don't count either, or moving the - // group past another "Twin" would shift the occurrence between recording and replay. - let build_group = |s: &mut Session| { - s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); - s.execute("layer.new.layer", json!({"name": "Twin"})).unwrap(); - s.execute("layer.new.layer", json!({"name": "Twin"})).unwrap(); - s.execute("layer.groupLayers", json!({})).unwrap(); - let group = s.active().unwrap().active_layer.unwrap(); - s.execute("layer.new.layer", json!({"name": "Twin"})).unwrap(); - let top = s.active().unwrap().active_layer.unwrap(); - s.execute("layer.select", json!({"layer": group.0, "mode": "replace"})).unwrap(); - (group, top) - }; - let mut g = Session::new(); - let (group, top) = build_group(&mut g); - g.execute("actions.record", json!({"name": "Group"})).unwrap(); - g.execute("layer.moveTo", json!({"layer": group.0, "target": top.0, "position": "above"})).unwrap(); - g.execute("actions.stop", json!({})).unwrap(); - let recorded = g.actions.list[0].steps[0].1.clone(); - let saved = serde_json::to_string(&g.actions.list).unwrap(); - let mut replay = Session::new(); - replay.actions.list = serde_json::from_str(&saved).unwrap(); - let (group2, _) = build_group(&mut replay); - let result = replay.execute("actions.play", json!({"action": 0})).unwrap(); - assert!(result.get("failed").is_none(), "{recorded}: {result}"); - let top_layer = |s: &Session| s.active().unwrap().doc.layers.last().map(|l| l.id); - assert_eq!(top_layer(&replay), Some(group2), "{recorded}: the group went to the top"); - // Several moved layers named like the target are left out too, so the name is unambiguous. - let mut m = Session::new(); - m.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); - let a = photocraft_doc::LayerId(m.execute("layer.new.layer", json!({"name": "Twin"})).unwrap()["layer"].as_u64().unwrap()); - let b = photocraft_doc::LayerId(m.execute("layer.new.layer", json!({"name": "Twin"})).unwrap()["layer"].as_u64().unwrap()); - let target = photocraft_doc::LayerId(m.execute("layer.new.layer", json!({"name": "Twin"})).unwrap()["layer"].as_u64().unwrap()); - m.execute("layer.moveTo", json!({"layers": [a.0, b.0], "target": "Twin", "position": "above"})).unwrap(); - assert_eq!(m.active().unwrap().doc.layers.last().map(|l| l.id), Some(b), "both moved above the third Twin"); - assert_eq!(m.active().unwrap().doc.layers.iter().rev().nth(2).map(|l| l.id), Some(target)); - // An ⌥-drag copy of the selected layer beside itself replays by name too. - let mut c = Session::new(); - c.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); - let src = photocraft_doc::LayerId(c.execute("layer.new.layer", json!({"name": "Solo"})).unwrap()["layer"].as_u64().unwrap()); - c.execute("actions.record", json!({"name": "Copy"})).unwrap(); - c.execute("layer.moveTo", json!({"layer": src.0, "target": src.0, "position": "above", "copy": true})).unwrap(); - c.execute("actions.stop", json!({})).unwrap(); - assert_eq!(c.actions.list[0].steps[0].1, json!({"target": "Solo", "position": "above", "copy": true})); - let saved = serde_json::to_string(&c.actions.list).unwrap(); - let mut replay = Session::new(); - replay.actions.list = serde_json::from_str(&saved).unwrap(); - replay.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); - replay.execute("layer.new.layer", json!({"name": "Solo"})).unwrap(); - let before = replay.active().unwrap().doc.layers.len(); - let result = replay.execute("actions.play", json!({"action": 0})).unwrap(); - assert!(result.get("failed").is_none(), "{result}"); - assert_eq!(replay.active().unwrap().doc.layers.len(), before + 1, "one copy"); - // Copying a group holding a layer named like the target: the new copy's contents (made - // before the step is recorded) don't count, so the occurrence matches the replay. - let build_copy = |s: &mut Session| { - s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); - s.execute("layer.new.layer", json!({"name": "Twin"})).unwrap(); - s.execute("layer.groupLayers", json!({})).unwrap(); - let group = s.active().unwrap().active_layer.unwrap(); - let a = photocraft_doc::LayerId(s.execute("layer.new.layer", json!({"name": "Twin"})).unwrap()["layer"].as_u64().unwrap()); - let b = photocraft_doc::LayerId(s.execute("layer.new.layer", json!({"name": "Twin"})).unwrap()["layer"].as_u64().unwrap()); - s.execute("layer.select", json!({"layer": group.0, "mode": "replace"})).unwrap(); - (group, a, b) - }; - let mut gc = Session::new(); - let (group, a, _) = build_copy(&mut gc); - gc.execute("actions.record", json!({"name": "Copy group"})).unwrap(); - // Below `a`: the copy's "Twin" then comes before `a` in document order. - gc.execute("layer.moveTo", json!({"layer": group.0, "target": a.0, "position": "below", "copy": true})).unwrap(); - gc.execute("actions.stop", json!({})).unwrap(); - let saved = serde_json::to_string(&gc.actions.list).unwrap(); - let mut replay = Session::new(); - replay.actions.list = serde_json::from_str(&saved).unwrap(); - let (_, a2, _) = build_copy(&mut replay); - let result = replay.execute("actions.play", json!({"action": 0})).unwrap(); - assert!(result.get("failed").is_none(), "{result}"); - let layers = &replay.active().unwrap().doc.layers; - let at = layers.iter().position(|l| l.id == a2).unwrap(); - let below = at.checked_sub(1).and_then(|i| layers.get(i)).map(|l| l.name.as_str()); - assert_eq!(below, Some("Group 1 copy"), "the copy landed below the same Twin"); - // A drag of several layers keeps its ids (not covered by name). - s.execute("actions.record", json!({"name": "Several"})).unwrap(); - s.execute("layer.moveTo", json!({"layers": [ids[2].0, ids[3].0], "target": ids[1].0, "position": "above"})).unwrap(); - s.execute("actions.stop", json!({})).unwrap(); - assert_eq!(s.actions.list[1].steps[0].1["target"], json!(ids[1].0)); - // Bad targets are errors, not panics. - for bad in [ - json!({"target": "Nobody"}), - json!({"target": "Twin"}), - json!({"target": "Twin", "targetOccurrence": 9}), - json!({"target": "Twin", "targetOccurrence": -1}), - json!({"target": true}), - ] { - assert!(s.execute("layer.moveTo", bad.clone()).is_err(), "{bad}"); - } - } - - /// An Alt-drag copy records `inPlace` (#7200), which only matters for an artboard: a plain - /// layer's recorded copy must still export to .atn, while an artboard's must be refused rather - /// than exported as a copy beside the original. - #[test] - fn recorded_in_place_duplicate_keeps_in_place_only_for_artboards() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); - s.execute("actions.record", json!({"name": "Layer copy"})).unwrap(); - s.execute("layer.duplicate", json!({"inPlace": true})).unwrap(); - s.execute("actions.stop", json!({})).unwrap(); - s.execute("layer.new.artboard", json!({"name": "Board", "rect": [0, 0, 8, 8]})).unwrap(); - s.execute("actions.record", json!({"name": "Board copy"})).unwrap(); - s.execute("layer.duplicate", json!({"inPlace": true})).unwrap(); - s.execute("actions.stop", json!({})).unwrap(); - assert_eq!(s.actions.list[0].steps, vec![("layer.duplicate".to_string(), json!({}))]); - assert_eq!(s.actions.list[1].steps, vec![("layer.duplicate".to_string(), json!({"inPlace": true}))]); - assert!(crate::atn_cmds::export("Audit", &[&s.actions.list[0]], &[], false).is_ok()); - assert!(crate::atn_cmds::export("Audit", &[&s.actions.list[1]], &[], false).is_err()); - // Several selected layers are copied together: one artboard among them keeps `inPlace`. - let mut s = Session::new(); - s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); - let photo = s.active().unwrap().active_layer.unwrap(); - s.execute("layer.new.layer", json!({"name": "Logo"})).unwrap(); - s.execute("layer.select", json!({"layer": photo.0, "mode": "add"})).unwrap(); - s.execute("actions.record", json!({"name": "Layers copy"})).unwrap(); - s.execute("layer.duplicate", json!({"inPlace": true})).unwrap(); - s.execute("actions.stop", json!({})).unwrap(); - assert_eq!(s.active().unwrap().selected_layers().len(), 2, "both layers were copied"); - s.execute("layer.new.artboard", json!({"name": "Board", "rect": [0, 0, 8, 8]})).unwrap(); - s.execute("layer.select", json!({"layer": photo.0, "mode": "add"})).unwrap(); - s.execute("actions.record", json!({"name": "Mixed copy"})).unwrap(); - s.execute("layer.duplicate", json!({"inPlace": true})).unwrap(); - s.execute("actions.stop", json!({})).unwrap(); - assert_eq!(s.actions.list[0].steps, vec![("layer.duplicate".to_string(), json!({}))]); - assert_eq!(s.actions.list[1].steps, vec![("layer.duplicate".to_string(), json!({"inPlace": true}))]); - } - - #[test] - fn named_selection_preserves_modes_and_duplicate_occurrences() { - let mut s = Session::new(); - s.execute("file.new", json!({"width":4,"height":4})).unwrap(); - s.execute("layer.setProps", json!({"name":"Photo"})).unwrap(); - let first = s.active().unwrap().active_layer.unwrap(); - s.execute("layer.new.group", json!({"name":"Group"})).unwrap(); - // A duplicate nested in a group must be found even when that group is collapsed. - let second = s - .edit("child", |doc, active| { - let child = photocraft_doc::Layer::raster("Photo", doc.pixel_format()); - let id = child.id; - if let photocraft_doc::LayerContent::Group(group) = &mut doc.layer_mut(active.unwrap()).unwrap().content { - group.children.push(child); - group.expanded = false; - } - Ok(id) - }) - .unwrap(); - s.execute("actions.record", json!({"name":"Select duplicates"})).unwrap(); - s.execute("layer.select", json!({"layer":first.0})).unwrap(); - s.execute("layer.select", json!({"layer":second.0,"mode":"add"})).unwrap(); - s.execute("actions.stop", json!({})).unwrap(); - assert_eq!(s.actions.list[0].steps[0].1, json!({"name":"Photo","occurrence":0})); - assert_eq!(s.actions.list[0].steps[1].1, json!({"name":"Photo","occurrence":1,"mode":"add"})); - s.execute("layer.select", json!({"layer":first.0})).unwrap(); - let r = s.execute("actions.play", json!({"action":0})).unwrap(); - assert!(r.get("failed").is_none(), "{r}"); - assert_eq!(s.active().unwrap().selected_layers(), vec![first, second]); - s.execute("layer.select", json!({"name":"Photo","occurrence":1,"mode":"toggle"})).unwrap(); - assert_eq!(s.active().unwrap().selected_layers(), vec![first]); - s.execute("layer.select", json!({"name":"Photo","occurrence":1,"mode":"range"})).unwrap(); - assert!(s.active().unwrap().selected_layers().contains(&second)); - // Main's imported .atn steps use a string-valued `layer` and choose the topmost match. - s.execute("layer.select", json!({"layer":"Photo"})).unwrap(); - assert_eq!(s.active().unwrap().selected_layers(), vec![second]); - s.execute("layer.select", json!({"name":"Photo","occurrence":0,"mode":"add"})).unwrap(); - s.execute("layer.select", json!({"name":"Photo","occurrence":1,"mode":"remove"})).unwrap(); - assert_eq!(s.active().unwrap().selected_layers(), vec![first]); - // Removing an unselected layer does not add it; removing the last target keeps it. - s.execute("layer.select", json!({"layer":"Photo","mode":"remove"})).unwrap(); - s.execute("layer.select", json!({"name":"Photo","occurrence":0,"mode":"remove"})).unwrap(); - assert_eq!(s.active().unwrap().selected_layers(), vec![first]); - for p in [ - json!({"name":"absent"}), - json!({"name":"Photo"}), - json!({"name":1}), - json!({"name":"Photo","occurrence":-1}), - json!({"name":"Photo","occurrence":1.5}), - json!({"name":"Photo","occurrence":99}), - json!({"name":"Photo","layer":first.0}), - json!({"layer":first.0,"occurrence":0}), - ] { - let before = s.active().unwrap().selected_layers(); - assert!(s.execute("layer.select", p.clone()).is_err(), "{p}"); - assert_eq!(s.active().unwrap().selected_layers(), before); - } - s.actions.list.push(Action { - name: "Missing".into(), - steps: vec![("layer.select".into(), json!({"name":"absent"})), ("layer.duplicate".into(), json!({}))], - disabled: Default::default(), - ..Default::default() - }); - let before = s.active().unwrap().doc.walk().len(); - let result = s.execute("actions.play", json!({"action":"Missing"})).unwrap(); - assert_eq!(result["ran"], 0); - assert!(result["failed"]["error"].as_str().unwrap().contains("absent")); - assert_eq!(s.active().unwrap().doc.walk().len(), before); - } - - #[test] - fn play_stops_at_the_failing_step_and_reports_it() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 16, "height": 16})).unwrap(); - s.execute("actions.record", json!({})).unwrap(); - s.execute("layer.new.layer", json!({"name": "One"})).unwrap(); - s.execute("actions.stop", json!({})).unwrap(); - s.actions.list[0].steps.push(("not.a.command".into(), json!({}))); - s.execute("file.new", json!({"width": 16, "height": 16})).unwrap(); - let r = s.execute("actions.play", json!({"action": "Action 1"})).unwrap(); - assert_eq!(r["ran"], 1); - assert_eq!(r["failed"]["step"], 1); - assert_eq!(r["failed"]["id"], "not.a.command"); - assert!(r["failed"]["error"].as_str().unwrap().contains("unknown command")); - assert_eq!(s.active().unwrap().doc.layers.len(), 2, "the step before the failure is kept"); - assert_eq!(s.actions.playing, 0); - // A later play still runs. - assert_eq!(s.execute("actions.play", json!({"action": 0, "from": 1})).unwrap()["ran"], 0); - } - - #[test] - fn play_refuses_recursion() { - let mut s = Session::new(); - s.actions.list.push(Action { - name: "Loop".into(), - steps: vec![("actions.play".into(), json!({"action": "Loop"}))], - disabled: Default::default(), - ..Default::default() - }); - let r = s.execute("actions.play", json!({"action": "Loop"})).unwrap(); - assert_eq!(r["ran"], 0); - assert_eq!(r["failed"]["id"], "actions.play"); - assert!(r["failed"]["error"].as_str().unwrap().contains("recursive action"), "{r}"); - assert_eq!(s.actions.playing, 0); - } - - #[test] - fn play_checks_each_step_with_the_authorize_hook() { - fn deny_file(id: &str, _: &Value) -> Result<()> { - if id.starts_with("file.") { Err(EngineError::Other(format!("automation command `{id}` is disabled"))) } else { Ok(()) } - } - let mut s = Session::new(); - s.authorize = Some(deny_file); - s.actions.list.push(Action { - name: "Open".into(), - steps: vec![("file.open".into(), json!({"path": "/etc/passwd"})), ("layer.new.layer".into(), json!({}))], - disabled: Default::default(), - ..Default::default() - }); - let r = s.execute("actions.play", json!({"action": "Open"})).unwrap(); - assert_eq!(r["ran"], 0); - assert_eq!(r["failed"]["step"], 0); - assert_eq!(r["failed"]["id"], "file.open"); - assert!(r["failed"]["error"].as_str().unwrap().contains("disabled"), "{r}"); - assert!(s.documents().is_empty(), "the refused step does not open a document"); - } - - #[test] - fn append_delete_and_from_step() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap(); - let started = s.execute("actions.record", json!({"name": "Grow"})).unwrap(); - assert_eq!(started["index"], 0); - s.execute("layer.new.layer", json!({"name": "One"})).unwrap(); - assert!(s.execute("actions.record", json!({})).is_err(), "already recording"); - assert!(s.execute("actions.delete", json!({"action": 0})).is_err(), "delete while recording"); - let stopped = s.execute("actions.stop", json!({})).unwrap(); - assert_eq!(stopped["steps"], 1); - s.execute("actions.record", json!({"action": "Grow"})).unwrap(); - s.execute("layer.new.layer", json!({"name": "Two"})).unwrap(); - assert_eq!(s.execute("actions.stop", json!({})).unwrap()["steps"], 2); - assert!(s.execute("actions.stop", json!({})).is_err(), "not recording"); - let before = s.active().unwrap().doc.layers.len(); - let r = s.execute("actions.play", json!({"action": "Grow", "from": 1})).unwrap(); - assert_eq!(r["ran"], 1); - assert_eq!(s.active().unwrap().doc.layers.len(), before + 1); - assert_eq!(s.execute("actions.delete", json!({"action": "Grow"})).unwrap()["deleted"], "Grow"); - assert!(s.actions.list.is_empty()); - assert!(s.execute("actions.get", json!({"action": "Grow"})).is_err()); - } - - #[test] - fn delete_one_step_while_recording_keeps_journal_and_remaining_steps() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); - s.execute("actions.record", json!({"name": "Edit"})).unwrap(); - s.execute("layer.new.layer", json!({"name": "Kept"})).unwrap(); - s.execute("layer.new.layer", json!({"name": "Removed"})).unwrap(); - let journal = s.journal.clone(); - let rev = s.actions.rev; - let before = s.actions.clone(); - for step in [json!(-1), json!(2), json!(0.5), json!(null), json!("0"), json!(u64::MAX)] { - assert!(s.execute("actions.delete", json!({"action": 0, "step": step})).is_err()); - assert_eq!(s.actions, before, "invalid deletion is atomic"); - } - assert_eq!(pending_steps(&s, 0).count(), 2); - let result = s.execute("actions.delete", json!({"action": 0, "step": 1})).unwrap(); - assert_eq!(result["steps"], 1); - assert_eq!(s.journal, journal, "deleting a recording does not erase executed commands"); - assert_eq!(s.active().unwrap().doc.layers.len(), 3, "it does not undo document edits"); - assert!(s.actions.recording.is_some()); - assert!(s.actions.rev > rev); - s.execute("layer.new.layer", json!({"name": "After"})).unwrap(); - s.execute("actions.stop", json!({})).unwrap(); - assert_eq!(s.actions.list[0].steps.iter().map(|(_, p)| p["name"].as_str().unwrap()).collect::>(), ["Kept", "After"]); - s.execute("actions.delete", json!({"action": "Edit", "step": 0})).unwrap(); - assert_eq!(s.actions.list[0].steps[0].1["name"], "After"); - let saved = serde_json::to_string(&s.actions.list).unwrap(); - s.actions.list = serde_json::from_str(&saved).unwrap(); - s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); - assert_eq!(s.execute("actions.play", json!({"action": 0})).unwrap()["ran"], 1); - assert_eq!(s.active().unwrap().doc.layers[1].name, "After"); - s.execute("actions.delete", json!({"action": 0, "step": 0})).unwrap(); - assert_eq!(s.actions.list.len(), 1, "an empty action still exists"); - assert!(s.actions.list[0].steps.is_empty()); - } - - #[test] - fn nested_call_records_one_named_step_and_tracks_child_edits() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 4, "height": 4})).unwrap(); - s.actions.list.push(Action { - name: "Child".into(), - steps: vec![("layer.new.layer".into(), json!({"name": "Child layer"}))], - disabled: Default::default(), - ..Default::default() - }); - s.execute("actions.record", json!({"name": "Parent"})).unwrap(); - s.execute("layer.new.layer", json!({"name": "Before"})).unwrap(); - s.execute("actions.play", json!({"action": 0})).unwrap(); - assert_eq!(pending_steps(&s, 1).cloned().collect::>(), [("actions.play".into(), json!({"action": "Child"}))]); - s.execute("layer.new.layer", json!({"name": "After"})).unwrap(); - s.execute("actions.stop", json!({})).unwrap(); - assert_eq!(s.actions.list[1].steps.iter().map(|st| st.0.as_str()).collect::>(), ["layer.new.layer", "actions.play", "layer.new.layer"]); - s.actions.list[0].steps.push(("layer.new.layer".into(), json!({"name": "Added later"}))); - s.execute("actions.move", json!({"action": "Child", "to": 1})).unwrap(); - let saved = serde_json::to_string(&s.actions.list).unwrap(); - s.actions.list = serde_json::from_str(&saved).unwrap(); - s.execute("file.new", json!({"width": 4, "height": 4})).unwrap(); - let result = s.execute("actions.play", json!({"action": "Parent"})).unwrap(); - assert!(result.get("failed").is_none(), "{result}"); - assert_eq!( - s.active().unwrap().doc.layers.iter().skip(1).map(|l| l.name.as_str()).collect::>(), - ["Before", "Child layer", "Added later", "After"] - ); - assert!(s.actions.playback_stack.is_empty()); - } - - #[test] - fn nested_failure_cycles_depth_and_authorization_stop_parent() { - let mut s = Session::new(); - s.actions.list.push(Action { - name: "A".into(), - steps: vec![("actions.play".into(), json!({"action": "B"})), ("file.new".into(), json!({"width": 2,"height": 2}))], - disabled: Default::default(), - ..Default::default() - }); - s.actions.list.push(Action { - name: "B".into(), - steps: vec![("actions.play".into(), json!({"action": "A"}))], - disabled: Default::default(), - ..Default::default() - }); - let r = s.execute("actions.play", json!({"action": "A"})).unwrap(); - assert!(r["failed"]["error"].as_str().unwrap().contains("recursive")); - assert!(s.documents().is_empty()); - s.actions.list[1].steps = vec![("file.new".into(), json!({"width": 2,"height": 2}))]; - s.authorize = Some(|id, _| if id == "file.new" { Err(EngineError::Other("denied nested file".into())) } else { Ok(()) }); - let r = s.execute("actions.play", json!({"action": "A"})).unwrap(); - assert!(r["failed"]["error"].as_str().unwrap().contains("denied nested file")); - assert!(s.documents().is_empty()); - s.authorize = None; - s.actions.list.clear(); - for i in 0..17 { - s.actions.list.push(Action { - name: format!("N{i}"), - steps: if i < 16 { vec![("actions.play".into(), json!({"action":format!("N{}", i + 1)}))] } else { vec![] }, - disabled: Default::default(), - ..Default::default() - }); - } - let r = s.execute("actions.play", json!({"action": "N0"})).unwrap(); - assert!(r["failed"]["error"].as_str().unwrap().contains("16 levels")); - assert_eq!(s.actions.playing, 0); - assert!(s.actions.playback_stack.is_empty()); - s.actions.list[15].steps.clear(); - assert!(s.execute("actions.play", json!({"action": "N0"})).unwrap().get("failed").is_none()); - } - - #[test] - fn move_pending_steps_is_atomic_persists_and_changes_playback_order() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 4, "height": 4})).unwrap(); - s.execute("actions.record", json!({"name": "Order"})).unwrap(); - for name in ["One", "Two", "Three"] { - s.execute("layer.new.layer", json!({"name": name})).unwrap(); - } - let before = s.actions.clone(); - for params in [ - json!({"action":0,"step":0,"to":3}), - json!({"action":0,"step":99,"to":0}), - json!({"action":0,"step":0.5,"to":0}), - json!({"action":0,"to":-1}), - json!({"action":0,"to":null}), - ] { - assert!(s.execute("actions.move", params).is_err()); - assert_eq!(s.actions, before); - } - let journal = s.journal.clone(); - s.execute("actions.move", json!({"action":0,"step":0,"to":2})).unwrap(); - s.execute("actions.move", json!({"action":0,"step":1,"to":0})).unwrap(); - assert_eq!(s.journal, journal); - s.execute("layer.new.layer", json!({"name":"Four"})).unwrap(); - s.execute("actions.stop", json!({})).unwrap(); - assert_eq!(s.actions.list[0].steps.iter().map(|st| st.1["name"].as_str().unwrap()).collect::>(), ["Three", "Two", "One", "Four"]); - s.execute("file.new", json!({"width":4,"height":4})).unwrap(); - s.execute("actions.play", json!({"action":0})).unwrap(); - assert_eq!(s.active().unwrap().doc.layers.iter().skip(1).map(|l| l.name.as_str()).collect::>(), ["Three", "Two", "One", "Four"]); - } - - #[test] - fn new_names_do_not_collide_with_named_calls() { - let mut s = Session::new(); - s.actions.list.push(Action { name: "Action 2".into(), steps: vec![], disabled: Default::default(), ..Default::default() }); - assert_eq!(s.execute("actions.record", json!({})).unwrap()["action"], "Action 3"); - s.execute("actions.stop", json!({})).unwrap(); - assert!(s.execute("actions.record", json!({"name":"Action 2"})).is_err()); - assert!(s.actions.recording.is_none()); - } - - #[test] - fn moving_action_keeps_recording_attached_to_it() { - let mut s = Session::new(); - s.execute("file.new", json!({"width":4,"height":4})).unwrap(); - for name in ["A", "B", "C"] { - s.actions.list.push(Action { name: name.into(), steps: vec![], disabled: Default::default(), ..Default::default() }); - } - s.execute("actions.record", json!({"action":"B"})).unwrap(); - s.execute("layer.new.layer", json!({"name":"before"})).unwrap(); - s.execute("actions.move", json!({"action":"B","to":2})).unwrap(); - s.execute("actions.move", json!({"action":"A","to":2})).unwrap(); - s.execute("layer.new.layer", json!({"name":"after"})).unwrap(); - s.execute("actions.stop", json!({})).unwrap(); - assert_eq!(s.actions.list[1].name, "B"); - assert_eq!(s.actions.list[1].steps.len(), 2); - } - - #[test] - fn bad_params_do_not_panic() { - let mut s = Session::new(); - let junk = [ - Value::Null, - json!([]), - json!("x"), - json!(1), - json!({"action": true}), - json!({"action": -1}), - json!({"action": 99}), - json!({"action": ""}), - json!({"name": 1}), - json!({"name": ""}), - json!({"from": "start"}), - json!({"from": -3}), - json!({"action": "missing", "from": 4}), - ]; - for id in ["actions.list", "actions.get", "actions.record", "actions.stop", "actions.play", "actions.delete", "actions.move"] { - for p in &junk { - let _ = s.execute(id, p.clone()); - } - } - assert_eq!(s.actions.playing, 0); - assert!(crate::commands::command_specs().iter().any(|c| c.id == "actions.play" && !c.journal && c.menu.is_empty())); - } - - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn actions_persist_with_the_preset_store() { - let dir = std::env::temp_dir().join(format!("pc-actions-{}-persist", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - let mut s = Session::new(); - let warnings = s.attach_preset_store(crate::preset_store::open_dir(&dir)); - assert!(warnings.iter().all(|w| !w.contains("actions")), "{warnings:?}"); - s.execute("file.new", json!({"width": 4, "height": 4})).unwrap(); - s.execute("actions.record", json!({"name": "Kept"})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.execute("actions.stop", json!({})).unwrap(); - drop(s); - - let mut t = Session::new(); - t.attach_preset_store(crate::preset_store::open_dir(&dir)); - let listed = t.execute("actions.list", json!({})).unwrap(); - assert_eq!(listed["actions"][0]["name"], "Kept"); - assert_eq!(listed["actions"][0]["steps"], 1); - assert_eq!(t.execute("actions.get", json!({"action": "Kept"})).unwrap()["steps"][0][0], "layer.new.layer"); - - // An action created before the store finishes loading is kept, and a different one on - // disk is merged in. - let mut early = Session::new(); - early.execute("actions.record", json!({"name": "Early"})).unwrap(); - early.execute("actions.stop", json!({})).unwrap(); - early.attach_preset_store(crate::preset_store::open_dir(&dir)); - let names: Vec = early.actions.list.iter().map(|a| a.name.clone()).collect(); - assert!(names.contains(&"Early".into()) && names.contains(&"Kept".into()), "{names:?}"); - - std::fs::write(dir.join("actions.json"), b"{").unwrap(); - let mut bad = Session::new(); - let warnings = bad.attach_preset_store(crate::preset_store::open_dir(&dir)); - assert!(warnings.iter().any(|w| w.contains("actions")), "{warnings:?}"); - assert!(bad.actions.list.is_empty()); - let _ = std::fs::remove_dir_all(&dir); - } - - /// AUTO-219-4: a recording made on one document replays on a second one — a crop, a filter, - /// a selection fill and styled text all act on the document the replay runs in. - #[test] - fn a_recorded_edit_run_replays_on_a_second_document() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 64, "height": 64, "background": "white"})).unwrap(); - s.execute("actions.record", json!({"name": "Studio"})).unwrap(); - s.execute("image.crop", json!({"x": 8, "y": 8, "width": 48, "height": 48})).unwrap(); - s.execute("filter.blur.gaussianBlur", json!({"radius": 2})).unwrap(); - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 12, "height": 12})).unwrap(); - s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); - s.execute("select.deselect", json!({})).unwrap(); - s.execute("type.create", json!({"x": 10, "y": 36, "text": "Hi", "size": 12, "color": "#000000"})).unwrap(); - s.execute("type.setStyle", json!({"fauxBold": true})).unwrap(); - let stopped = s.execute("actions.stop", json!({})).unwrap(); - let steps = stopped["steps"].as_u64().unwrap(); - assert!(steps >= 7, "the recording keeps every family: {stopped}"); - - // The second document: a different size, background and name. The replay must act here. - s.execute("file.new", json!({"width": 100, "height": 80, "background": "black", "name": "Second"})).unwrap(); - let played = s.execute("actions.play", json!({"action": "Studio"})).unwrap(); - assert!(played.get("failed").is_none(), "replay: {played}"); - assert_eq!(played["ran"].as_u64(), Some(steps), "every step ran: {played}"); - let d = &s.active().unwrap().doc; - assert_eq!((d.size.width, d.size.height), (48, 48), "the crop replayed onto the second document"); - assert_eq!(pixel(&s, 0, 16, 16), vec![1.0, 0.0, 0.0, 1.0], "the selection fill replayed"); - assert_eq!(pixel(&s, 0, 2, 2), vec![0.0, 0.0, 0.0, 1.0], "outside the selection stays black"); - let last = d.layers.last().unwrap(); - match &last.content { - photocraft_doc::LayerContent::Text(t) => { - assert_eq!(t.text, "Hi", "the styled text replayed"); - assert!(t.char_runs().iter().any(|r| r.style.faux_bold), "the bold run replayed"); - } - other => panic!("expected the recorded type layer, got {other:?}"), - } - // The first document is untouched. - let first = &s.documents()[0].doc; - assert_eq!((first.size.width, first.size.height), (48, 48), "the recording document keeps its own crop"); - } - - #[test] - fn button_color_is_one_of_the_photoshop_swatches() { - let mut s = Session::new(); - s.execute("actions.record", json!({"name": "Print"})).unwrap(); - s.execute("actions.stop", json!({})).unwrap(); - let set = s.execute("actions.setColor", json!({"action": "Print", "color": "blue"})).unwrap(); - assert_eq!(set["color"], "blue"); - assert_eq!(s.actions.list[0].color, "blue"); - assert_eq!(s.execute("actions.get", json!({"action": 0})).unwrap()["color"], "blue"); - let saved = serde_json::to_string(&s.actions.list).unwrap(); - assert!(saved.contains("blue")); - s.execute("actions.setColor", json!({"action": 0, "color": ""})).unwrap(); - assert!(s.actions.list[0].color.is_empty()); - assert!(!serde_json::to_string(&s.actions.list).unwrap().contains("color"), "an empty colour is omitted"); - for bad in [json!({"action": 0, "color": "pink"}), json!({"action": 0}), json!({"action": 4, "color": "red"}), json!({"color": "red"})] { - assert!(s.execute("actions.setColor", bad).is_err()); - } - assert!(s.actions.list[0].color.is_empty(), "rejected colours change nothing"); - } -} - -#[cfg(test)] -mod security_tests { - use super::*; - - #[test] - fn playback_budget_is_shared_by_nested_calls() { - let mut session = Session::new(); - session.actions.playback_steps = MAX_PLAYBACK_STEPS - 1; - assert!(consume_playback_step(&mut session)); - assert!(!consume_playback_step(&mut session)); - } -} diff --git a/crates/engine/src/adjust_params.rs b/crates/engine/src/adjust_params.rs index 69fc2d76f3..1361dbef5e 100644 --- a/crates/engine/src/adjust_params.rs +++ b/crates/engine/src/adjust_params.rs @@ -1081,665 +1081,4 @@ pub fn user_keys(p: &Value) -> Map { } #[cfg(test)] -mod tests { - use super::*; - - const KINDS: [&str; 15] = [ - "invert", - "brightnessContrast", - "threshold", - "posterize", - "exposure", - "vibrance", - "hueSaturation", - "levels", - "curves", - "colorBalance", - "blackWhite", - "photoFilter", - "channelMixer", - "gradientMap", - "selectiveColor", - ]; - - /// A non-default parameter set per kind (RGB channel keys for Levels/Curves). - pub(crate) fn sample(kind: &str) -> Value { - match kind { - "brightnessContrast" => json!({"brightness": 20, "contrast": -10, "legacy": true}), - "threshold" => json!({"level": 100}), - "posterize" => json!({"levels": 7}), - "exposure" => json!({"exposure": 1.5, "offset": 0.1, "gamma": 1.4}), - "vibrance" => json!({"vibrance": 30, "saturation": -20}), - "hueSaturation" => { - json!({"hue": 25, "saturation": -20, "lightness": 10, "reds": {"hue": 10, "saturation": -30, "lightness": 5, "range": [300, 340, 20, 50]}}) - } - "levels" => json!({"inBlack": 10, "inWhite": 240, "outBlack": 5, "outWhite": 250, "gamma": 1.2, "red": {"inBlack": 3, "gamma": 0.8}}), - "curves" => json!({"points": [[0, 0], [128, 150], [255, 255]], "blue": [[0, 20], [255, 235]]}), - "colorBalance" => json!({"shadows": [10, -5, 0], "midtones": [0, 20, -30], "highlights": [5, 5, 5], "preserveLuminosity": false}), - "blackWhite" => json!({"reds": 120, "blues": -40, "tint": true, "tintColor": "#d0a070"}), - "photoFilter" => json!({"color": "#3366cc", "density": 40, "preserveLuminosity": false}), - "channelMixer" => json!({"red": [80, 30, -10, 5], "blue": [0, 10, 90, 0]}), - "gradientMap" => json!({"stops": [[0, "#000000"], [0.5, "#ff0000"], [1, [1, 1, 1]]], "reverse": true, "dither": true}), - "selectiveColor" => json!({"method": "absolute", "reds": [10, 0, -20, 5]}), - _ => json!({}), - } - } - - #[test] - fn every_kind_round_trips_through_params() { - for mode in [ColorMode::Rgb, ColorMode::Cmyk, ColorMode::Lab, ColorMode::Grayscale] { - for kind in KINDS { - let mut p = sample(kind); - if matches!(kind, "levels" | "curves") && default_space(mode) != ToneSpace::Rgb { - // Off RGB the channel keys are the document's. - p.as_object_mut().unwrap().retain(|k, _| !matches!(k.as_str(), "red" | "blue")); - } - let a = from_params(kind, &p, None, mode).unwrap_or_else(|e| panic!("{kind} {mode:?}: {e}")); - assert_ne!(Some(&a), default_for(kind, mode).ok().as_ref().filter(|_| kind != "invert"), "{kind} params ignored"); - let back = from_params(kind, &to_params(&a), None, mode).unwrap(); - assert_eq!(to_params(&back), to_params(&a), "{kind} {mode:?}"); - // A partial update keeps everything it doesn't name. - let again = from_params(kind, &json!({}), Some(&a), mode).unwrap(); - assert_eq!(again, a, "{kind} {mode:?}"); - } - } - } - - #[test] - fn params_reach_the_model() { - let a = from_params("colorBalance", &json!({"midtones": [50, 0, -200]}), None, ColorMode::Rgb).unwrap(); - assert_eq!(a, Adjustment::ColorBalance { shadows: [0.0; 3], midtones: [50.0, 0.0, -100.0], highlights: [0.0; 3], preserve_luminosity: true }); - let a = from_params("channelMixer", &json!({"monochrome": true}), None, ColorMode::Rgb).unwrap(); - assert!(matches!(a, Adjustment::ChannelMixer { matrix, monochrome: true } if matrix[0] == [0.4, 0.4, 0.2, 0.0])); - let a = from_params("photoFilter", &json!({"filter": "cooling80", "density": 60}), None, ColorMode::Rgb).unwrap(); - assert!(matches!(a, Adjustment::PhotoFilter { color, density, .. } if color[2] == 1.0 && (density - 0.6).abs() < 1e-6)); - let a = from_params("blackWhite", &json!({"reds": 120, "tint": true}), None, ColorMode::Rgb).unwrap(); - assert!(matches!(a, Adjustment::BlackWhite { weights, tint: Some(_) } if weights[0] == 120.0 && weights[1] == 60.0)); - let a = from_params("hueSaturation", &json!({"blues": {"hue": 40}}), None, ColorMode::Rgb).unwrap(); - assert!(matches!(&a, Adjustment::HueSaturation { ranges, .. } if ranges[4].hue == 40.0 && ranges[0].is_neutral())); - // Colorize without a saturation starts at 25%; an explicit 0 and an already colorized base are kept. - let a = from_params("hueSaturation", &json!({"colorize": true, "hue": 30}), None, ColorMode::Rgb).unwrap(); - assert!(matches!(a, Adjustment::HueSaturation { colorize: true, saturation: 25.0, .. }), "{a:?}"); - let a = from_params("hueSaturation", &json!({"colorize": true, "saturation": 0}), None, ColorMode::Rgb).unwrap(); - assert!(matches!(a, Adjustment::HueSaturation { colorize: true, saturation: 0.0, .. }), "{a:?}"); - let a = from_params("hueSaturation", &json!({"hue": 120}), Some(&a), ColorMode::Rgb).unwrap(); - assert!(matches!(a, Adjustment::HueSaturation { colorize: true, saturation: 0.0, hue: 120.0, .. }), "{a:?}"); - let a = from_params("gradientMap", &json!({"stops": [[1, "#ffffff"], [0, "#000000"]], "dither": true}), None, ColorMode::Rgb).unwrap(); - assert!(matches!(&a, Adjustment::GradientMap { stops, dither: true, .. } if stops[0].0 == 0.0)); - // CMYK curves: ink channels; Lab: lightness without a composite. - let a = from_params("curves", &json!({"black": [[0, 0], [255, 200]]}), None, ColorMode::Rgb).unwrap(); - assert!(matches!(&a, Adjustment::Curves { space: ToneSpace::Cmyk, black, .. } if black.len() == 2)); - let a = from_params("curves", &json!({"points": [[0, 40], [255, 255]]}), None, ColorMode::Lab).unwrap(); - assert!(matches!(&a, Adjustment::Curves { space: ToneSpace::Lab, per_channel, .. } if per_channel[0][0].output > 0.1)); - let a = from_params("levels", &json!({"inBlack": 20}), None, ColorMode::Cmyk).unwrap(); - assert!(matches!(&a, Adjustment::Levels { space: ToneSpace::Cmyk, master, .. } if (master.in_black - 20.0 / 255.0).abs() < 1e-6)); - } - - #[test] - fn bad_params_are_errors_not_panics() { - for (kind, p) in [ - ("curves", json!({"points": "abc"})), - ("curves", json!({"points": [[0, 0]]})), - ("curves", json!({"red": [[0, 0], [1]]})), - ("curves", json!({"points": [[5, 5], [5, 9]]})), - ("curves", json!({"pencil": true, "points": [1, 2, 3]})), - ("curves", json!({"pencil": "yes"})), - ("curves", json!({"points": (0..256).map(|k| if k == 9 { json!("x") } else { json!(k) }).collect::>()})), - ("levels", json!({"red": 3})), - ("levels", json!({"inBlack": "x"})), - ("hueSaturation", json!({"reds": {"range": [1, 2]}})), - ("hueSaturation", json!({"colorize": 1})), - ("colorBalance", json!({"shadows": [1, 2]})), - ("blackWhite", json!({"tintColor": "#zz0000"})), - ("photoFilter", json!({"filter": "nope"})), - ("photoFilter", json!({"color": [1]})), - ("channelMixer", json!({"red": [1, 2, 3]})), - ("gradientMap", json!({"stops": [[0, "#000"]]})), - ("gradientMap", json!({"stops": 7})), - ("selectiveColor", json!({"method": 5})), - ("selectiveColor", json!({"reds": "not-an-array"})), - ("selectiveColor", json!({"colors": "reds", "cyan": "50"})), - ("colorLookup", json!({"lut": 42})), - ("colorLookup", json!({"interpolation": 5})), - ("colorLookup", json!({"dither": "yes"})), - ("nope", json!({})), - ("levels", json!([1, 2])), - ] { - assert!(from_params(kind, &p, None, ColorMode::Rgb).is_err(), "{kind} {p}"); - } - // Out-of-range numbers clamp. - let a = from_params("hueSaturation", &json!({"hue": 1e9, "saturation": -1e9}), None, ColorMode::Rgb).unwrap(); - assert!(matches!(a, Adjustment::HueSaturation { hue: 180.0, saturation: -100.0, .. })); - let a = from_params("levels", &json!({"inBlack": 250, "inWhite": 10}), None, ColorMode::Rgb).unwrap(); - assert!(matches!(a, Adjustment::Levels { master, .. } if master.in_white > master.in_black)); - } - - #[test] - fn curve_points_outside_0_255_are_refused_as_the_message_says() { - // Photoshop refuses them too ("the settings in the file are invalid"); they used to be - // moved onto the edge silently. - for pts in [json!([[0, 0], [300, 255]]), json!([[0, -1], [255, 255]]), json!([[0, 0]])] { - let e = from_params("curves", &json!({ "points": pts }), None, ColorMode::Rgb).unwrap_err().to_string(); - assert!(e.contains("[input, output] pairs in 0..255") && e.contains("`curves adjustment`"), "{e}"); - } - assert!(from_params("curves", &json!({"points": [[0, 0], [128.5, 140], [255, 255]]}), None, ColorMode::Rgb).is_ok()); - } - - fn curves_parts(a: &Adjustment) -> (&[CurvePoint], &[Vec; 3]) { - match a { - Adjustment::Curves { master, per_channel, .. } => (master, per_channel), - _ => panic!("expected curves"), - } - } - - fn tone_output(adjustment: &Adjustment, sample: [f32; 3]) -> [f32; 3] { - let luts = photocraft_compose::adjust::tone_luts(adjustment); - std::array::from_fn(|channel| { - let row = &luts[channel]; - let position = sample[channel].clamp(0.0, 1.0) * (row.len().saturating_sub(1)) as f32; - let lower = position.floor() as usize; - let upper = lower.saturating_add(1).min(row.len().saturating_sub(1)); - let fraction = position - lower as f32; - row.get(lower).copied().unwrap_or(0.0) * (1.0 - fraction) + row.get(upper).copied().unwrap_or(0.0) * fraction - }) - } - - #[test] - fn curves_black_and_white_eyedroppers_move_the_input_references() { - let base = json!({ - "points": [[0, 8], [120, 150], [255, 245]], - "red": [[0, 0], [100, 130], [255, 255]], - "green": [[0, 0], [110, 125], [255, 255]], - "blue": [[0, 0], [90, 120], [255, 255]] - }); - let black = curves_eyedropper(&base, CurvesEyedropper::Black, [0.2, 0.3, 0.4], ColorMode::Rgb).unwrap(); - let (master, channels) = curves_parts(&black); - for (curve, sample) in channels.iter().zip([0.2, 0.3, 0.4]) { - assert!((curve[0].input - sample).abs() < 1e-6 && curve[0].output == 0.0, "{curve:?}"); - assert_eq!(curve.len(), 3, "existing edit points are preserved"); - } - assert_eq!(master[0].output, 0.0, "the composite cannot lift the sampled black"); - assert!(tone_output(&black, [0.2, 0.3, 0.4]).iter().all(|value| *value < 1e-3)); - - let white = curves_eyedropper(&base, CurvesEyedropper::White, [0.6, 0.7, 0.8], ColorMode::Rgb).unwrap(); - let (master, channels) = curves_parts(&white); - for (curve, sample) in channels.iter().zip([0.6, 0.7, 0.8]) { - let end = curve.last().unwrap(); - assert!((end.input - sample).abs() < 1e-6 && end.output == 1.0, "{curve:?}"); - assert_eq!(curve.len(), 3, "existing edit points are preserved"); - } - assert_eq!(master.last().map(|p| p.output), Some(1.0), "the composite cannot lower the sampled white"); - assert!(tone_output(&white, [0.6, 0.7, 0.8]).iter().all(|value| *value > 1.0 - 1e-3)); - - let edge_black = curves_eyedropper(&base, CurvesEyedropper::Black, [1.0, 0.3, 0.4], ColorMode::Rgb).unwrap(); - let (_, edge_channels) = curves_parts(&edge_black); - assert_eq!(edge_channels[0].len(), 3, "edge samples preserve other curve points"); - assert_eq!(edge_channels[0].last().map(|p| p.output), Some(0.0)); - let edge_white = curves_eyedropper(&base, CurvesEyedropper::White, [0.0, 0.7, 0.8], ColorMode::Rgb).unwrap(); - let (_, edge_channels) = curves_parts(&edge_white); - assert_eq!(edge_channels[0].len(), 3, "edge samples preserve other curve points"); - assert_eq!(edge_channels[0].first().map(|p| p.output), Some(1.0)); - } - - #[test] - fn black_and_white_eyedroppers_round_trip_near_serialization_boundaries() { - let cases = [ - (CurvesEyedropper::White, 0.0, 1.0), - (CurvesEyedropper::White, 0.001, 1.0), - (CurvesEyedropper::White, 0.494 / 255.0, 1.0), - // 0.496 level rounds to 0.50; the sample is just below that representable point. - (CurvesEyedropper::White, 0.496 / 255.0, 0.992), - (CurvesEyedropper::White, 0.2, 1.0), - (CurvesEyedropper::Black, 1.0, 0.0), - (CurvesEyedropper::Black, 0.999, 0.0), - (CurvesEyedropper::Black, 1.0 - 0.494 / 255.0, 0.0), - // 254.504 levels rounds to 254.50, leaving a representable 0.50-level gap. - (CurvesEyedropper::Black, 1.0 - 0.496 / 255.0, 0.008), - (CurvesEyedropper::Black, 0.8, 0.0), - ]; - for (picker, sample, expected_output) in cases { - let resolved = curves_eyedropper(&json!({}), picker, [sample; 3], ColorMode::Rgb).unwrap(); - let params = to_params(&resolved); - let parsed = from_params("curves", ¶ms, None, ColorMode::Rgb).unwrap(); - let (master, channels) = curves_parts(&parsed); - for curve in std::iter::once(master).chain(channels.iter().map(Vec::as_slice)) { - assert!(curve.len() >= 2, "{picker:?} sample={sample}: {curve:?}"); - assert!(curve.len() <= MAX_CURVE_POINTS, "{picker:?} sample={sample}: {curve:?}"); - assert!(curve.windows(2).all(|pair| pair[0].input < pair[1].input), "{picker:?} sample={sample}: {curve:?}"); - assert!(curve.windows(2).all(|pair| pair[1].input - pair[0].input >= CURVE_POINT_DUPLICATE_DISTANCE), "{picker:?} sample={sample}: {curve:?}"); - } - let output = tone_output(&parsed, [sample; 3]); - assert!( - output.iter().all(|value| (*value - expected_output).abs() < 1e-3), - "{picker:?} sample={sample} output={output:?} expected={expected_output}" - ); - } - } - - #[test] - fn endpoint_eyedroppers_fall_back_when_serialization_collapses_curve_points() { - let base = json!({ - "points": [[0, 0], [64, 50], [128, 100], [192, 200], [255, 255]], - "red": [[0, 0], [64, 50], [128, 100], [192, 200], [255, 255]], - "green": [[0, 0], [64, 50], [128, 100], [192, 200], [255, 255]], - "blue": [[0, 0], [64, 50], [128, 100], [192, 200], [255, 255]] - }); - let cases = [(CurvesEyedropper::Black, 0.995, 0.0, true), (CurvesEyedropper::White, 0.005, 1.0, false)]; - for (picker, sample, target, black) in cases { - let resolved = curves_eyedropper(&base, picker, [sample; 3], ColorMode::Rgb).unwrap(); - let parsed = from_params("curves", &to_params(&resolved), None, ColorMode::Rgb).unwrap(); - let (master, channels) = curves_parts(&parsed); - for curve in std::iter::once(master).chain(channels.iter().map(Vec::as_slice)) { - assert_eq!(curve.len(), 5, "collapsed points use the deterministic fallback: {curve:?}"); - for (point, input) in curve.iter().zip([0.0, 64.0, 128.0, 192.0, 255.0]) { - assert!((point.input * 255.0 - input).abs() < 1e-3, "existing point position was retained: {curve:?}"); - } - } - for curve in channels { - let plateau: Vec<_> = if black { curve.iter().rev().take(2).collect() } else { curve.iter().take(2).collect() }; - assert!(plateau.into_iter().all(|point| (point.output - target).abs() < 1e-6), "{curve:?}"); - } - let output = tone_output(&parsed, [sample; 3]); - assert!(output.iter().all(|value| (*value - target).abs() < 0.01), "{picker:?}: {output:?}"); - } - } - - #[test] - fn black_and_white_round_trips_preserve_representable_curve_edits() { - let base = json!({ - "points": [[0, 8], [120, 150], [255, 245]], - "red": [[0, 0], [100, 130], [255, 255]], - "green": [[0, 0], [110, 125], [255, 255]], - "blue": [[0, 0], [90, 120], [255, 255]] - }); - let black = curves_eyedropper(&base, CurvesEyedropper::Black, [0.2, 0.3, 0.4], ColorMode::Rgb).unwrap(); - let black = from_params("curves", &to_params(&black), None, ColorMode::Rgb).unwrap(); - let (_, channels) = curves_parts(&black); - assert_eq!(channels[0].len(), 3); - assert!((channels[0][1].input * 255.0 - 131.0).abs() < 1e-3); - assert!((channels[0][1].output * 255.0 - 130.0).abs() < 1e-3); - - let white = curves_eyedropper(&base, CurvesEyedropper::White, [0.6, 0.7, 0.8], ColorMode::Rgb).unwrap(); - let white = from_params("curves", &to_params(&white), None, ColorMode::Rgb).unwrap(); - let (_, channels) = curves_parts(&white); - assert_eq!(channels[0].len(), 3); - assert!((channels[0][1].input * 255.0 - 60.0).abs() < 1e-3); - assert!((channels[0][1].output * 255.0 - 130.0).abs() < 1e-3); - } - - fn assert_gray_point_preserves_luma_and_existing_curve_edits(sample: [f32; 3]) { - let base = json!({ - "points": [[0, 0], [128, 96], [255, 255]], - "red": [[0, 0], [80, 90], [255, 255]], - "green": [[0, 0], [90, 100], [255, 255]], - "blue": [[0, 0], [70, 80], [255, 255]] - }); - let original = from_params("curves", &base, None, ColorMode::Rgb).unwrap(); - let expected_luma = rgb_luma(sample); - let resolved = curves_eyedropper(&base, CurvesEyedropper::NeutralGray, sample, ColorMode::Rgb).unwrap(); - let parsed = from_params("curves", &to_params(&resolved), None, ColorMode::Rgb).unwrap(); - let (master, channels) = curves_parts(&parsed); - let (original_master, original_channels) = curves_parts(&original); - assert_eq!(master, original_master, "the existing master curve is retained"); - for (curve, old_curve) in channels.iter().zip(original_channels) { - let old_edit = old_curve.get(1).expect("the test curve has an interior edit"); - assert!( - curve.iter().any(|point| { (point.input - old_edit.input).abs() < 1e-6 && (point.output - old_edit.output).abs() < 1e-6 }), - "the existing channel edit is retained: {curve:?}" - ); - } - let output = tone_output(&parsed, sample); - assert!((output[0] - output[1]).abs() < 0.002 && (output[1] - output[2]).abs() < 0.002, "sample must become neutral: {output:?}"); - assert!((rgb_luma(output) - expected_luma).abs() < 0.003, "luma changed from {expected_luma} to {} ({output:?})", rgb_luma(output)); - } - - #[test] - fn curves_neutral_gray_preserves_luma_for_a_light_cast_sample() { - assert_gray_point_preserves_luma_and_existing_curve_edits([0.88, 0.76, 0.63]); - } - - #[test] - fn curves_neutral_gray_preserves_luma_for_a_dark_cast_sample() { - assert_gray_point_preserves_luma_and_existing_curve_edits([0.17, 0.105, 0.075]); - } - - #[test] - fn curves_neutral_gray_handles_near_black_and_near_white_samples() { - for sample in [[0.004, 0.006, 0.008], [0.992, 0.996, 0.999], [0.0, 0.0, 0.0], [1.0, 1.0, 1.0]] { - let resolved = curves_eyedropper(&json!({}), CurvesEyedropper::NeutralGray, sample, ColorMode::Rgb).unwrap(); - let parsed = from_params("curves", &to_params(&resolved), None, ColorMode::Rgb).unwrap(); - let (master, channels) = curves_parts(&parsed); - for curve in std::iter::once(master).chain(channels.iter().map(Vec::as_slice)) { - assert!(curve.len() >= 2, "{sample:?}: {curve:?}"); - assert!(curve.windows(2).all(|pair| pair[0].input < pair[1].input), "{sample:?}: {curve:?}"); - assert!(curve.windows(2).all(|pair| pair[1].input - pair[0].input >= CURVE_POINT_DUPLICATE_DISTANCE), "{sample:?}: {curve:?}"); - } - let output = tone_output(&parsed, sample); - assert!((output[0] - output[1]).abs() < 0.002 && (output[1] - output[2]).abs() < 0.002, "{sample:?}: {output:?}"); - assert!((rgb_luma(output) - rgb_luma(sample)).abs() < 0.003, "{sample:?}: {output:?}"); - } - } - - #[test] - fn gray_point_fallback_keeps_tightly_spaced_points_round_trip_safe() { - let base = json!({ - "red": [[0, 0], [100, 100], [100.51, 100], [255, 255]], - "green": [[0, 0], [100, 100], [100.51, 100], [255, 255]], - "blue": [[0, 0], [100, 100], [100.51, 100], [255, 255]] - }); - let sample = [100.25 / 255.0, 100.1 / 255.0, 100.4 / 255.0]; - let target = rgb_luma(sample); - let resolved = curves_eyedropper(&base, CurvesEyedropper::NeutralGray, sample, ColorMode::Rgb).unwrap(); - let parsed = from_params("curves", &to_params(&resolved), None, ColorMode::Rgb).unwrap(); - let (_, channels) = curves_parts(&parsed); - for (curve, input) in channels.iter().zip(sample) { - assert_eq!(curve.len(), 4, "the fallback keeps every serialized point: {curve:?}"); - assert!(curve.windows(2).all(|pair| pair[1].input - pair[0].input >= CURVE_POINT_DUPLICATE_DISTANCE), "{curve:?}"); - let sample_pair = curve.windows(2).find(|pair| pair[0].input <= input && input <= pair[1].input).unwrap(); - assert!((sample_pair[0].output - sample_pair[1].output).abs() < 1e-6, "fallback forms a plateau around the sample: {curve:?}"); - assert!((sample_pair[0].output - target).abs() < 0.001, "fallback uses the luma target: {curve:?}"); - } - } - - #[test] - fn curves_eyedropper_param_drives_the_command() { - let mut s = crate::Session::new(); - s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); - s.execute("edit.fill", json!({"color": [0.6, 0.5, 0.4]})).unwrap(); - s.execute("image.adjustments.curves", json!({"eyedropper": {"point": "white", "at": [2, 2]}})).unwrap(); - let px: Vec = serde_json::from_value(s.execute("document.pixel", json!({"x": 2, "y": 2})).unwrap()).unwrap(); - assert!(px.iter().take(3).all(|v| *v > 0.99), "the sample becomes white: {px:?}"); - s.execute("image.adjustments.curves", json!({"eyedropper": {"point": "black", "color": [1.0, 1.0, 1.0]}})).unwrap(); - let px: Vec = serde_json::from_value(s.execute("document.pixel", json!({"x": 2, "y": 2})).unwrap()).unwrap(); - assert!(px.iter().take(3).all(|v| *v < 0.01), "the given colour becomes black: {px:?}"); - for bad in [ - json!("black"), - json!({"point": "nope", "at": [1, 1]}), - json!({"point": "black"}), - json!({"point": "black", "at": [99, 1]}), - json!({"point": "black", "at": [-1, 1]}), - json!({"point": "black", "at": [1]}), - json!({"point": "gray", "at": [f64::MAX, 1]}), - json!({"point": "black", "color": "red"}), - ] { - assert!(s.execute("image.adjustments.curves", json!({"eyedropper": bad})).is_err(), "{bad}"); - } - } - - /// The Properties panel's pickers on a Curves adjustment layer (UI-217-15): one undoable step - /// that samples the image below the layer, so a repeated click keeps the same curve. - #[test] - fn layer_eyedropper_samples_below_the_curves_layer() { - let mut s = crate::Session::new(); - s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); - s.execute("edit.fill", json!({"color": [0.6, 0.5, 0.4]})).unwrap(); - s.execute("layer.newAdjustmentLayer.curves", json!({})).unwrap(); - let steps = s.active().unwrap().history.past_len(); - let pick = json!({"eyedropper": {"point": "white", "at": [2, 2], "size": 3}}); - s.execute("layer.setAdjustment", pick.clone()).unwrap(); - assert_eq!(s.active().unwrap().history.past_len(), steps + 1); - let px: Vec = serde_json::from_value(s.execute("document.pixel", json!({"x": 2, "y": 2})).unwrap()).unwrap(); - assert!(px.iter().take(3).all(|v| *v > 0.99), "the sample becomes white: {px:?}"); - let curve = s.active().unwrap().doc.clone(); - s.execute("layer.setAdjustment", pick).unwrap(); - let same = |a: &photocraft_doc::Document, b: &photocraft_doc::Document| a.layers.last().map(|l| &l.content) == b.layers.last().map(|l| &l.content); - assert!(same(&curve, &s.active().unwrap().doc), "sampled below the layer, not through it"); - s.execute("edit.undo", json!({})).unwrap(); - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(s.active().unwrap().history.past_len(), steps); - for bad in [json!({"point": "black", "at": [99, 1]}), json!({"point": "black", "at": [1, 1], "size": 2}), json!({"point": "x", "at": [1, 1]})] { - assert!(s.execute("layer.setAdjustment", json!({"eyedropper": bad})).is_err(), "{bad}"); - } - s.execute("layer.newAdjustmentLayer.hueSaturation", json!({})).unwrap(); - assert!(s.execute("layer.setAdjustment", json!({"eyedropper": {"point": "white", "at": [1, 1]}})).is_err(), "Levels and Curves only"); - } - - /// #3127: on a smart object the eyedropper param records the adjustment it resolved to as - /// the smart filter, not the raw sample (which re-rendered as an identity). - #[test] - fn eyedropper_on_a_smart_object_records_the_resolved_adjustment() { - for kind in ["curves", "levels"] { - let mut s = crate::Session::new(); - s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); - s.execute("edit.fill", json!({"color": [0.6, 0.5, 0.4]})).unwrap(); - s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - s.execute(&format!("image.adjustments.{kind}"), json!({"eyedropper": {"point": "white", "at": [2, 2]}})).unwrap(); - let px: Vec = serde_json::from_value(s.execute("document.pixel", json!({"x": 2, "y": 2})).unwrap()).unwrap(); - assert!(px.iter().take(3).all(|v| *v > 0.99), "{kind}: {px:?}"); - } - } - - /// Levels' Set White/Neutral Gray Point (#3116): the white point maps the sampled colour to - /// white at 8 and 16 bit, the gray point neutralises a tinted grey at its luma on a Levels - /// layer as one undoable step, and bad picks fail. - #[test] - fn levels_eyedroppers_set_white_and_neutral_gray() { - let pixel = |s: &mut crate::Session| -> Vec { serde_json::from_value(s.execute("document.pixel", json!({"x": 2, "y": 2})).unwrap()).unwrap() }; - for depth in [8, 16] { - let mut s = crate::Session::new(); - s.execute("file.new", json!({"width": 8, "height": 8, "depth": depth})).unwrap(); - s.execute("edit.fill", json!({"color": [0.6, 0.5, 0.4]})).unwrap(); - s.execute("image.adjustments.levels", json!({"eyedropper": {"point": "white", "at": [2, 2]}})).unwrap(); - let px = pixel(&mut s); - assert!(px.iter().take(3).all(|v| *v > 0.995), "{depth}-bit: the sample becomes white: {px:?}"); - } - let mut s = crate::Session::new(); - s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); - s.execute("edit.fill", json!({"color": [0.6, 0.5, 0.4]})).unwrap(); - let before = pixel(&mut s); - s.execute("layer.newAdjustmentLayer.levels", json!({})).unwrap(); - let steps = s.active().unwrap().history.past_len(); - s.execute("layer.setAdjustment", json!({"eyedropper": {"point": "gray", "at": [2, 2]}})).unwrap(); - assert_eq!(s.active().unwrap().history.past_len(), steps + 1); - let px = pixel(&mut s); - let (lo, hi) = px.iter().take(3).fold((1.0f32, 0.0f32), |(lo, hi), v| (lo.min(*v), hi.max(*v))); - assert!(hi - lo < 2.5 / 255.0, "neutral: {px:?}"); - let luma = |c: &[f32]| c[0] * 0.2126 + c[1] * 0.7152 + c[2] * 0.0722; - assert!((luma(&px) - luma(&before)).abs() < 2.0 / 255.0, "keeps the luma: {px:?} vs {before:?}"); - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(pixel(&mut s), before); - for bad in [json!({"point": "gray", "at": [99, 1]}), json!({"point": "x", "at": [1, 1]}), json!({"point": "white", "color": [f64::NAN, 0, 0]})] { - assert!(s.execute("layer.setAdjustment", json!({"eyedropper": bad})).is_err(), "{bad}"); - assert!(s.execute("image.adjustments.levels", json!({"eyedropper": bad})).is_err(), "{bad}"); - } - s.execute("file.new", json!({"width": 8, "height": 8, "mode": "grayscale"})).unwrap(); - assert!(s.execute("image.adjustments.levels", json!({"eyedropper": {"point": "gray", "at": [1, 1]}})).is_err(), "no gray picker in Grayscale"); - s.execute("image.adjustments.levels", json!({"eyedropper": {"point": "black", "color": [1.0, 1.0, 1.0]}})).unwrap(); - } - - #[test] - fn curves_eyedropper_support_is_explicit_and_bad_samples_fail() { - assert!(curves_eyedropper(&json!({}), CurvesEyedropper::Black, [0.4; 3], ColorMode::Grayscale).is_ok()); - assert!(curves_eyedropper(&json!({}), CurvesEyedropper::White, [0.4; 3], ColorMode::Grayscale).is_ok()); - assert!(curves_eyedropper(&json!({}), CurvesEyedropper::NeutralGray, [0.4; 3], ColorMode::Grayscale).is_err()); - for mode in [ColorMode::Cmyk, ColorMode::Lab] { - assert!(curves_eyedropper(&json!({}), CurvesEyedropper::Black, [0.4; 3], mode).is_err()); - } - assert!(curves_eyedropper(&json!({}), CurvesEyedropper::Black, [f32::NAN, 0.0, 0.0], ColorMode::Rgb).is_err()); - } - - #[test] - fn hue_range_sliders_stay_ordered() { - let a = from_params("hueSaturation", &json!({"greens": {"range": [100, 90, 200, 150]}}), None, ColorMode::Rgb).unwrap(); - let Adjustment::HueSaturation { ranges, .. } = a else { panic!() }; - let b = ranges[2].bounds; - assert!(b[0] <= b[1] && b[1] <= b[2] && b[2] <= b[3] && b[3] - b[0] < 360.0, "{b:?}"); - } - - /// A colourful 16×16 document (`mode`, `depth`) for command tests. - fn colourful(mode: &str, depth: u32) -> crate::Session { - let mut s = crate::Session::new(); - s.execute("file.new", json!({"width": 16, "height": 16, "mode": mode, "depth": depth})).unwrap(); - for (i, c) in ["#c83c28", "#3c8c50", "#2850b4", "#d2b464"].iter().enumerate() { - s.execute("select.rect", json!({"x": (i % 2) * 8, "y": (i / 2) * 8, "width": 8, "height": 8})).unwrap(); - s.execute("edit.fill", json!({"color": c})).unwrap(); - } - s.execute("select.deselect", json!({})).unwrap(); - s - } - - fn pixels(s: &crate::Session) -> Vec> { - let d = s.active().unwrap(); - let bg = d.doc.layers[0].surface().unwrap(); - [(2, 2), (10, 2), (2, 10), (10, 10)].iter().map(|&(x, y)| bg.pixel(x, y)).collect() - } - - #[test] - fn destructive_commands_apply_their_params_at_every_depth() { - for depth in [8, 16, 32] { - for kind in KINDS.iter().filter(|k| **k != "invert") { - let mut s = colourful("rgb", depth); - let before = pixels(&s); - let steps = s.active().unwrap().history.past_len(); - s.execute(&format!("image.adjustments.{kind}"), sample(kind)).unwrap_or_else(|e| panic!("{kind} @{depth}: {e}")); - assert_ne!(pixels(&s), before, "{kind} @{depth} changed nothing"); - assert_eq!(s.active().unwrap().history.past_len(), steps + 1, "{kind}: one history step"); - // Identity params leave the pixels alone (within one 8-bit step). - let mut s = colourful("rgb", depth); - s.execute(&format!("image.adjustments.{kind}"), to_params(&default_for(kind, ColorMode::Rgb).unwrap())).unwrap(); - if !matches!(*kind, "threshold" | "posterize" | "blackWhite" | "gradientMap" | "photoFilter") { - for (a, b) in pixels(&s).iter().zip(&before) { - assert!(a.iter().zip(b).all(|(x, y)| (x - y).abs() <= 1.0 / 255.0 + 1e-4), "{kind} @{depth}: {a:?} vs {b:?}"); - } - } - } - } - } - - #[test] - fn curves_pencil_maps_draw_smooth_and_convert_back() { - // A drawn inversion: 256 output levels. - let inverted: Vec = (0..256).rev().map(|k| k as f32).collect(); - let a = from_params("curves", &json!({"pencil": true, "points": inverted}), None, ColorMode::Rgb).unwrap(); - assert!(matches!(&a, Adjustment::Curves { pencil: true, master, .. } if master.len() == CURVE_MAP_LEN)); - assert!((tone_output(&a, [0.25; 3])[0] - 0.75).abs() < 1e-3); - assert_eq!(from_params("curves", &to_params(&a), None, ColorMode::Rgb).unwrap(), a); - // Smooth evens out a hard step but keeps the endpoints. - let step: Vec = (0..256).map(|k| if k < 128 { 0.0 } else { 255.0 }).collect(); - let s = from_params("curves", &json!({"red": step, "smooth": 2}), Some(&a), ColorMode::Rgb).unwrap(); - let (_, chans) = curves_parts(&s); - assert!(chans[0][127].output > 0.2 && chans[0][128].output < 0.8, "{:?}", &chans[0][120..136]); - assert_eq!((chans[0][0].output, chans[0][255].output), (0.0, 1.0)); - // Edit points: the map is fitted with a point curve that still inverts. - let pts = from_params("curves", &json!({"pencil": false}), Some(&a), ColorMode::Rgb).unwrap(); - let (master, _) = curves_parts(&pts); - assert!(matches!(&pts, Adjustment::Curves { pencil: false, .. }) && master.len() <= MAX_FITTED_POINTS, "{master:?}"); - assert!((tone_output(&pts, [0.25; 3])[0] - 0.75).abs() < 2.0 / 255.0); - // The command draws it at every depth. - for depth in [8, 16, 32] { - let mut s = colourful("rgb", depth); - let before = pixels(&s); - s.execute("image.adjustments.curves", to_params(&a)).unwrap(); - let after = pixels(&s); - assert!((after[0][0] - (1.0 - before[0][0])).abs() < 2.0 / 255.0, "@{depth}: {after:?} vs {before:?}"); - } - } - - #[test] - fn destructive_levels_dont_clip_in_32_bit() { - // Input 15..230, gamma 1.3, output 10..245: integer documents stop at the output range, - // while float documents preserve the curve's signed and HDR values beyond it (the - // compose-side `levels_dont_clip_in_32_bit` pins the same curve, #2592). - let params = json!({"inBlack": 15, "inWhite": 230, "gamma": 1.3, "outBlack": 10, "outWhite": 245}); - for depth in [8, 16, 32] { - let mut s = crate::Session::new(); - s.execute("file.new", json!({"width": 16, "height": 16, "depth": depth, "background": "white"})).unwrap(); - s.execute("select.rect", json!({"x": 0, "y": 0, "width": 8, "height": 16})).unwrap(); - s.execute("edit.fill", json!({"color": "#000000"})).unwrap(); - s.execute("select.deselect", json!({})).unwrap(); - s.execute("image.adjustments.levels", params.clone()).unwrap(); - let px = pixels(&s); - if depth == 32 { - assert!(px[0][0].is_finite() && px[0][0] < 0.0, "float black keeps its signed result: {:?}", px[0]); - assert!(px[1][0].is_finite() && px[1][0] > 1.0, "float white keeps its HDR result: {:?}", px[1]); - } else { - assert!((px[0][0] * 255.0 - 10.0).abs() < 0.6, "black @{depth}: {:?}", px[0]); - assert!((px[1][0] * 255.0 - 245.0).abs() < 0.6, "white @{depth}: {:?}", px[1]); - } - } - } - - #[test] - fn cmyk_and_lab_documents_use_their_channels() { - let mut s = colourful("cmyk", 8); - let before = pixels(&s); - // More black ink darkens every patch. - s.execute("image.adjustments.curves", json!({"black": [[0, 0], [255, 180]]})).unwrap(); - let after = pixels(&s); - assert!(after.iter().zip(&before).all(|(a, b)| a[3] > b[3] + 0.05), "{after:?} vs {before:?}"); - let mut s = colourful("lab", 16); - let before = pixels(&s); - s.execute("image.adjustments.levels", json!({"lightness": {"outBlack": 60}})).unwrap(); - let after = pixels(&s); - assert!(after.iter().zip(&before).all(|(a, b)| a[0] >= b[0]), "lightness lifted {after:?} vs {before:?}"); - // The adjustment layer of a CMYK document defaults to ink channels. - let mut s = colourful("cmyk", 8); - s.execute("layer.newAdjustmentLayer.curves", json!({})).unwrap(); - let id = s.active().unwrap().active_layer.unwrap(); - let l = s.active().unwrap().doc.layer(id).unwrap().clone(); - assert!(matches!(l.content, photocraft_doc::LayerContent::Adjustment(Adjustment::Curves { space: ToneSpace::Cmyk, .. }))); - } - - #[test] - fn set_adjustment_merges_and_resets() { - let mut s = colourful("rgb", 8); - s.execute("layer.newAdjustmentLayer.colorBalance", json!({"midtones": [30, 0, 0]})).unwrap(); - s.execute("layer.setAdjustment", json!({"highlights": [0, 0, -20]})).unwrap(); - let id = s.active().unwrap().active_layer.unwrap(); - let adj = |s: &crate::Session| match &s.active().unwrap().doc.layer(id).unwrap().content { - photocraft_doc::LayerContent::Adjustment(a) => a.clone(), - _ => panic!(), - }; - assert!(matches!(adj(&s), Adjustment::ColorBalance { midtones: [30.0, 0.0, 0.0], highlights: [0.0, 0.0, -20.0], .. })); - s.execute("layer.setAdjustment", json!({"layer": id.0})).unwrap(); - assert_eq!(adj(&s), default_for("colorBalance", ColorMode::Rgb).unwrap()); - // Bad params are errors and leave the layer alone. - s.execute("layer.setAdjustment", json!({"midtones": [10, 10, 10]})).unwrap(); - let kept = adj(&s); - for bad in [json!({"midtones": "x"}), json!({"preserveLuminosity": 3}), json!({"shadows": [1]})] { - assert!(s.execute("layer.setAdjustment", bad.clone()).is_err(), "{bad}"); - assert_eq!(adj(&s), kept); - } - } - - #[test] - fn commands_reject_bad_params_gracefully() { - let mut s = colourful("rgb", 8); - for (kind, p) in [ - ("curves", json!({"points": [[0, 0]]})), - ("levels", json!({"red": "dark"})), - ("gradientMap", json!({"stops": [[0, 1, 2]]})), - ("photoFilter", json!({"filter": 3})), - ("channelMixer", json!({"gray": [1, 2]})), - ("hueSaturation", json!({"reds": 4})), - ("blackWhite", json!({"tint": "yes"})), - ] { - for prefix in ["image.adjustments.", "layer.newAdjustmentLayer."] { - let r = s.execute(&format!("{prefix}{kind}"), p.clone()); - assert!(matches!(r, Err(EngineError::BadParams { .. })), "{prefix}{kind} {p}: {r:?}"); - } - } - } - #[test] - fn destructive_levels_match_independent_signed_hdr_endpoints() { - // Input 15..230, gamma 1.3, output 10..245: black and white land on the output range in - // integer documents. Float32 keeps HDR values outside 0..1, as the compositor's real-file - // Levels oracle does. These independently calculated endpoints use the signed-power - // curve at black and white, not display-clipped values. - let params = json!({"inBlack": 15, "inWhite": 230, "gamma": 1.3, "outBlack": 10, "outWhite": 245}); - for (depth, low, high, tolerance) in [(8, 10.0, 245.0, 0.6), (16, 10.0, 245.0, 0.6), (32, -20.308_89, 265.750_3, 0.01)] { - let mut s = crate::Session::new(); - s.execute("file.new", json!({"width": 16, "height": 16, "depth": depth, "background": "white"})).unwrap(); - s.execute("select.rect", json!({"x": 0, "y": 0, "width": 8, "height": 16})).unwrap(); - s.execute("edit.fill", json!({"color": "#000000"})).unwrap(); - s.execute("select.deselect", json!({})).unwrap(); - s.execute("image.adjustments.levels", params.clone()).unwrap(); - let px = pixels(&s); - assert!((px[0][0] * 255.0 - low).abs() < tolerance, "black @{depth}: {:?}", px[0]); - assert!((px[1][0] * 255.0 - high).abs() < tolerance, "white @{depth}: {:?}", px[1]); - if depth == 32 { - assert!(px[0][0] < 0.0 && px[1][0] > 1.0, "HDR endpoints must remain unclipped"); - } - } - } -} +mod tests; diff --git a/crates/engine/src/adjust_params/tests.rs b/crates/engine/src/adjust_params/tests.rs new file mode 100644 index 0000000000..a7b6cc53de --- /dev/null +++ b/crates/engine/src/adjust_params/tests.rs @@ -0,0 +1,657 @@ +use super::*; + +const KINDS: [&str; 15] = [ + "invert", + "brightnessContrast", + "threshold", + "posterize", + "exposure", + "vibrance", + "hueSaturation", + "levels", + "curves", + "colorBalance", + "blackWhite", + "photoFilter", + "channelMixer", + "gradientMap", + "selectiveColor", +]; + +/// A non-default parameter set per kind (RGB channel keys for Levels/Curves). +pub(crate) fn sample(kind: &str) -> Value { + match kind { + "brightnessContrast" => json!({"brightness": 20, "contrast": -10, "legacy": true}), + "threshold" => json!({"level": 100}), + "posterize" => json!({"levels": 7}), + "exposure" => json!({"exposure": 1.5, "offset": 0.1, "gamma": 1.4}), + "vibrance" => json!({"vibrance": 30, "saturation": -20}), + "hueSaturation" => { + json!({"hue": 25, "saturation": -20, "lightness": 10, "reds": {"hue": 10, "saturation": -30, "lightness": 5, "range": [300, 340, 20, 50]}}) + } + "levels" => json!({"inBlack": 10, "inWhite": 240, "outBlack": 5, "outWhite": 250, "gamma": 1.2, "red": {"inBlack": 3, "gamma": 0.8}}), + "curves" => json!({"points": [[0, 0], [128, 150], [255, 255]], "blue": [[0, 20], [255, 235]]}), + "colorBalance" => json!({"shadows": [10, -5, 0], "midtones": [0, 20, -30], "highlights": [5, 5, 5], "preserveLuminosity": false}), + "blackWhite" => json!({"reds": 120, "blues": -40, "tint": true, "tintColor": "#d0a070"}), + "photoFilter" => json!({"color": "#3366cc", "density": 40, "preserveLuminosity": false}), + "channelMixer" => json!({"red": [80, 30, -10, 5], "blue": [0, 10, 90, 0]}), + "gradientMap" => json!({"stops": [[0, "#000000"], [0.5, "#ff0000"], [1, [1, 1, 1]]], "reverse": true, "dither": true}), + "selectiveColor" => json!({"method": "absolute", "reds": [10, 0, -20, 5]}), + _ => json!({}), + } +} + +#[test] +fn every_kind_round_trips_through_params() { + for mode in [ColorMode::Rgb, ColorMode::Cmyk, ColorMode::Lab, ColorMode::Grayscale] { + for kind in KINDS { + let mut p = sample(kind); + if matches!(kind, "levels" | "curves") && default_space(mode) != ToneSpace::Rgb { + // Off RGB the channel keys are the document's. + p.as_object_mut().unwrap().retain(|k, _| !matches!(k.as_str(), "red" | "blue")); + } + let a = from_params(kind, &p, None, mode).unwrap_or_else(|e| panic!("{kind} {mode:?}: {e}")); + assert_ne!(Some(&a), default_for(kind, mode).ok().as_ref().filter(|_| kind != "invert"), "{kind} params ignored"); + let back = from_params(kind, &to_params(&a), None, mode).unwrap(); + assert_eq!(to_params(&back), to_params(&a), "{kind} {mode:?}"); + // A partial update keeps everything it doesn't name. + let again = from_params(kind, &json!({}), Some(&a), mode).unwrap(); + assert_eq!(again, a, "{kind} {mode:?}"); + } + } +} + +#[test] +fn params_reach_the_model() { + let a = from_params("colorBalance", &json!({"midtones": [50, 0, -200]}), None, ColorMode::Rgb).unwrap(); + assert_eq!(a, Adjustment::ColorBalance { shadows: [0.0; 3], midtones: [50.0, 0.0, -100.0], highlights: [0.0; 3], preserve_luminosity: true }); + let a = from_params("channelMixer", &json!({"monochrome": true}), None, ColorMode::Rgb).unwrap(); + assert!(matches!(a, Adjustment::ChannelMixer { matrix, monochrome: true } if matrix[0] == [0.4, 0.4, 0.2, 0.0])); + let a = from_params("photoFilter", &json!({"filter": "cooling80", "density": 60}), None, ColorMode::Rgb).unwrap(); + assert!(matches!(a, Adjustment::PhotoFilter { color, density, .. } if color[2] == 1.0 && (density - 0.6).abs() < 1e-6)); + let a = from_params("blackWhite", &json!({"reds": 120, "tint": true}), None, ColorMode::Rgb).unwrap(); + assert!(matches!(a, Adjustment::BlackWhite { weights, tint: Some(_) } if weights[0] == 120.0 && weights[1] == 60.0)); + let a = from_params("hueSaturation", &json!({"blues": {"hue": 40}}), None, ColorMode::Rgb).unwrap(); + assert!(matches!(&a, Adjustment::HueSaturation { ranges, .. } if ranges[4].hue == 40.0 && ranges[0].is_neutral())); + // Colorize without a saturation starts at 25%; an explicit 0 and an already colorized base are kept. + let a = from_params("hueSaturation", &json!({"colorize": true, "hue": 30}), None, ColorMode::Rgb).unwrap(); + assert!(matches!(a, Adjustment::HueSaturation { colorize: true, saturation: 25.0, .. }), "{a:?}"); + let a = from_params("hueSaturation", &json!({"colorize": true, "saturation": 0}), None, ColorMode::Rgb).unwrap(); + assert!(matches!(a, Adjustment::HueSaturation { colorize: true, saturation: 0.0, .. }), "{a:?}"); + let a = from_params("hueSaturation", &json!({"hue": 120}), Some(&a), ColorMode::Rgb).unwrap(); + assert!(matches!(a, Adjustment::HueSaturation { colorize: true, saturation: 0.0, hue: 120.0, .. }), "{a:?}"); + let a = from_params("gradientMap", &json!({"stops": [[1, "#ffffff"], [0, "#000000"]], "dither": true}), None, ColorMode::Rgb).unwrap(); + assert!(matches!(&a, Adjustment::GradientMap { stops, dither: true, .. } if stops[0].0 == 0.0)); + // CMYK curves: ink channels; Lab: lightness without a composite. + let a = from_params("curves", &json!({"black": [[0, 0], [255, 200]]}), None, ColorMode::Rgb).unwrap(); + assert!(matches!(&a, Adjustment::Curves { space: ToneSpace::Cmyk, black, .. } if black.len() == 2)); + let a = from_params("curves", &json!({"points": [[0, 40], [255, 255]]}), None, ColorMode::Lab).unwrap(); + assert!(matches!(&a, Adjustment::Curves { space: ToneSpace::Lab, per_channel, .. } if per_channel[0][0].output > 0.1)); + let a = from_params("levels", &json!({"inBlack": 20}), None, ColorMode::Cmyk).unwrap(); + assert!(matches!(&a, Adjustment::Levels { space: ToneSpace::Cmyk, master, .. } if (master.in_black - 20.0 / 255.0).abs() < 1e-6)); +} + +#[test] +fn bad_params_are_errors_not_panics() { + for (kind, p) in [ + ("curves", json!({"points": "abc"})), + ("curves", json!({"points": [[0, 0]]})), + ("curves", json!({"red": [[0, 0], [1]]})), + ("curves", json!({"points": [[5, 5], [5, 9]]})), + ("curves", json!({"pencil": true, "points": [1, 2, 3]})), + ("curves", json!({"pencil": "yes"})), + ("curves", json!({"points": (0..256).map(|k| if k == 9 { json!("x") } else { json!(k) }).collect::>()})), + ("levels", json!({"red": 3})), + ("levels", json!({"inBlack": "x"})), + ("hueSaturation", json!({"reds": {"range": [1, 2]}})), + ("hueSaturation", json!({"colorize": 1})), + ("colorBalance", json!({"shadows": [1, 2]})), + ("blackWhite", json!({"tintColor": "#zz0000"})), + ("photoFilter", json!({"filter": "nope"})), + ("photoFilter", json!({"color": [1]})), + ("channelMixer", json!({"red": [1, 2, 3]})), + ("gradientMap", json!({"stops": [[0, "#000"]]})), + ("gradientMap", json!({"stops": 7})), + ("selectiveColor", json!({"method": 5})), + ("selectiveColor", json!({"reds": "not-an-array"})), + ("selectiveColor", json!({"colors": "reds", "cyan": "50"})), + ("colorLookup", json!({"lut": 42})), + ("colorLookup", json!({"interpolation": 5})), + ("colorLookup", json!({"dither": "yes"})), + ("nope", json!({})), + ("levels", json!([1, 2])), + ] { + assert!(from_params(kind, &p, None, ColorMode::Rgb).is_err(), "{kind} {p}"); + } + // Out-of-range numbers clamp. + let a = from_params("hueSaturation", &json!({"hue": 1e9, "saturation": -1e9}), None, ColorMode::Rgb).unwrap(); + assert!(matches!(a, Adjustment::HueSaturation { hue: 180.0, saturation: -100.0, .. })); + let a = from_params("levels", &json!({"inBlack": 250, "inWhite": 10}), None, ColorMode::Rgb).unwrap(); + assert!(matches!(a, Adjustment::Levels { master, .. } if master.in_white > master.in_black)); +} + +#[test] +fn curve_points_outside_0_255_are_refused_as_the_message_says() { + // Photoshop refuses them too ("the settings in the file are invalid"); they used to be + // moved onto the edge silently. + for pts in [json!([[0, 0], [300, 255]]), json!([[0, -1], [255, 255]]), json!([[0, 0]])] { + let e = from_params("curves", &json!({ "points": pts }), None, ColorMode::Rgb).unwrap_err().to_string(); + assert!(e.contains("[input, output] pairs in 0..255") && e.contains("`curves adjustment`"), "{e}"); + } + assert!(from_params("curves", &json!({"points": [[0, 0], [128.5, 140], [255, 255]]}), None, ColorMode::Rgb).is_ok()); +} + +fn curves_parts(a: &Adjustment) -> (&[CurvePoint], &[Vec; 3]) { + match a { + Adjustment::Curves { master, per_channel, .. } => (master, per_channel), + _ => panic!("expected curves"), + } +} + +fn tone_output(adjustment: &Adjustment, sample: [f32; 3]) -> [f32; 3] { + let luts = photocraft_compose::adjust::tone_luts(adjustment); + std::array::from_fn(|channel| { + let row = &luts[channel]; + let position = sample[channel].clamp(0.0, 1.0) * (row.len().saturating_sub(1)) as f32; + let lower = position.floor() as usize; + let upper = lower.saturating_add(1).min(row.len().saturating_sub(1)); + let fraction = position - lower as f32; + row.get(lower).copied().unwrap_or(0.0) * (1.0 - fraction) + row.get(upper).copied().unwrap_or(0.0) * fraction + }) +} + +#[test] +fn curves_black_and_white_eyedroppers_move_the_input_references() { + let base = json!({ + "points": [[0, 8], [120, 150], [255, 245]], + "red": [[0, 0], [100, 130], [255, 255]], + "green": [[0, 0], [110, 125], [255, 255]], + "blue": [[0, 0], [90, 120], [255, 255]] + }); + let black = curves_eyedropper(&base, CurvesEyedropper::Black, [0.2, 0.3, 0.4], ColorMode::Rgb).unwrap(); + let (master, channels) = curves_parts(&black); + for (curve, sample) in channels.iter().zip([0.2, 0.3, 0.4]) { + assert!((curve[0].input - sample).abs() < 1e-6 && curve[0].output == 0.0, "{curve:?}"); + assert_eq!(curve.len(), 3, "existing edit points are preserved"); + } + assert_eq!(master[0].output, 0.0, "the composite cannot lift the sampled black"); + assert!(tone_output(&black, [0.2, 0.3, 0.4]).iter().all(|value| *value < 1e-3)); + + let white = curves_eyedropper(&base, CurvesEyedropper::White, [0.6, 0.7, 0.8], ColorMode::Rgb).unwrap(); + let (master, channels) = curves_parts(&white); + for (curve, sample) in channels.iter().zip([0.6, 0.7, 0.8]) { + let end = curve.last().unwrap(); + assert!((end.input - sample).abs() < 1e-6 && end.output == 1.0, "{curve:?}"); + assert_eq!(curve.len(), 3, "existing edit points are preserved"); + } + assert_eq!(master.last().map(|p| p.output), Some(1.0), "the composite cannot lower the sampled white"); + assert!(tone_output(&white, [0.6, 0.7, 0.8]).iter().all(|value| *value > 1.0 - 1e-3)); + + let edge_black = curves_eyedropper(&base, CurvesEyedropper::Black, [1.0, 0.3, 0.4], ColorMode::Rgb).unwrap(); + let (_, edge_channels) = curves_parts(&edge_black); + assert_eq!(edge_channels[0].len(), 3, "edge samples preserve other curve points"); + assert_eq!(edge_channels[0].last().map(|p| p.output), Some(0.0)); + let edge_white = curves_eyedropper(&base, CurvesEyedropper::White, [0.0, 0.7, 0.8], ColorMode::Rgb).unwrap(); + let (_, edge_channels) = curves_parts(&edge_white); + assert_eq!(edge_channels[0].len(), 3, "edge samples preserve other curve points"); + assert_eq!(edge_channels[0].first().map(|p| p.output), Some(1.0)); +} + +#[test] +fn black_and_white_eyedroppers_round_trip_near_serialization_boundaries() { + let cases = [ + (CurvesEyedropper::White, 0.0, 1.0), + (CurvesEyedropper::White, 0.001, 1.0), + (CurvesEyedropper::White, 0.494 / 255.0, 1.0), + // 0.496 level rounds to 0.50; the sample is just below that representable point. + (CurvesEyedropper::White, 0.496 / 255.0, 0.992), + (CurvesEyedropper::White, 0.2, 1.0), + (CurvesEyedropper::Black, 1.0, 0.0), + (CurvesEyedropper::Black, 0.999, 0.0), + (CurvesEyedropper::Black, 1.0 - 0.494 / 255.0, 0.0), + // 254.504 levels rounds to 254.50, leaving a representable 0.50-level gap. + (CurvesEyedropper::Black, 1.0 - 0.496 / 255.0, 0.008), + (CurvesEyedropper::Black, 0.8, 0.0), + ]; + for (picker, sample, expected_output) in cases { + let resolved = curves_eyedropper(&json!({}), picker, [sample; 3], ColorMode::Rgb).unwrap(); + let params = to_params(&resolved); + let parsed = from_params("curves", ¶ms, None, ColorMode::Rgb).unwrap(); + let (master, channels) = curves_parts(&parsed); + for curve in std::iter::once(master).chain(channels.iter().map(Vec::as_slice)) { + assert!(curve.len() >= 2, "{picker:?} sample={sample}: {curve:?}"); + assert!(curve.len() <= MAX_CURVE_POINTS, "{picker:?} sample={sample}: {curve:?}"); + assert!(curve.windows(2).all(|pair| pair[0].input < pair[1].input), "{picker:?} sample={sample}: {curve:?}"); + assert!(curve.windows(2).all(|pair| pair[1].input - pair[0].input >= CURVE_POINT_DUPLICATE_DISTANCE), "{picker:?} sample={sample}: {curve:?}"); + } + let output = tone_output(&parsed, [sample; 3]); + assert!(output.iter().all(|value| (*value - expected_output).abs() < 1e-3), "{picker:?} sample={sample} output={output:?} expected={expected_output}"); + } +} + +#[test] +fn endpoint_eyedroppers_fall_back_when_serialization_collapses_curve_points() { + let base = json!({ + "points": [[0, 0], [64, 50], [128, 100], [192, 200], [255, 255]], + "red": [[0, 0], [64, 50], [128, 100], [192, 200], [255, 255]], + "green": [[0, 0], [64, 50], [128, 100], [192, 200], [255, 255]], + "blue": [[0, 0], [64, 50], [128, 100], [192, 200], [255, 255]] + }); + let cases = [(CurvesEyedropper::Black, 0.995, 0.0, true), (CurvesEyedropper::White, 0.005, 1.0, false)]; + for (picker, sample, target, black) in cases { + let resolved = curves_eyedropper(&base, picker, [sample; 3], ColorMode::Rgb).unwrap(); + let parsed = from_params("curves", &to_params(&resolved), None, ColorMode::Rgb).unwrap(); + let (master, channels) = curves_parts(&parsed); + for curve in std::iter::once(master).chain(channels.iter().map(Vec::as_slice)) { + assert_eq!(curve.len(), 5, "collapsed points use the deterministic fallback: {curve:?}"); + for (point, input) in curve.iter().zip([0.0, 64.0, 128.0, 192.0, 255.0]) { + assert!((point.input * 255.0 - input).abs() < 1e-3, "existing point position was retained: {curve:?}"); + } + } + for curve in channels { + let plateau: Vec<_> = if black { curve.iter().rev().take(2).collect() } else { curve.iter().take(2).collect() }; + assert!(plateau.into_iter().all(|point| (point.output - target).abs() < 1e-6), "{curve:?}"); + } + let output = tone_output(&parsed, [sample; 3]); + assert!(output.iter().all(|value| (*value - target).abs() < 0.01), "{picker:?}: {output:?}"); + } +} + +#[test] +fn black_and_white_round_trips_preserve_representable_curve_edits() { + let base = json!({ + "points": [[0, 8], [120, 150], [255, 245]], + "red": [[0, 0], [100, 130], [255, 255]], + "green": [[0, 0], [110, 125], [255, 255]], + "blue": [[0, 0], [90, 120], [255, 255]] + }); + let black = curves_eyedropper(&base, CurvesEyedropper::Black, [0.2, 0.3, 0.4], ColorMode::Rgb).unwrap(); + let black = from_params("curves", &to_params(&black), None, ColorMode::Rgb).unwrap(); + let (_, channels) = curves_parts(&black); + assert_eq!(channels[0].len(), 3); + assert!((channels[0][1].input * 255.0 - 131.0).abs() < 1e-3); + assert!((channels[0][1].output * 255.0 - 130.0).abs() < 1e-3); + + let white = curves_eyedropper(&base, CurvesEyedropper::White, [0.6, 0.7, 0.8], ColorMode::Rgb).unwrap(); + let white = from_params("curves", &to_params(&white), None, ColorMode::Rgb).unwrap(); + let (_, channels) = curves_parts(&white); + assert_eq!(channels[0].len(), 3); + assert!((channels[0][1].input * 255.0 - 60.0).abs() < 1e-3); + assert!((channels[0][1].output * 255.0 - 130.0).abs() < 1e-3); +} + +fn assert_gray_point_preserves_luma_and_existing_curve_edits(sample: [f32; 3]) { + let base = json!({ + "points": [[0, 0], [128, 96], [255, 255]], + "red": [[0, 0], [80, 90], [255, 255]], + "green": [[0, 0], [90, 100], [255, 255]], + "blue": [[0, 0], [70, 80], [255, 255]] + }); + let original = from_params("curves", &base, None, ColorMode::Rgb).unwrap(); + let expected_luma = rgb_luma(sample); + let resolved = curves_eyedropper(&base, CurvesEyedropper::NeutralGray, sample, ColorMode::Rgb).unwrap(); + let parsed = from_params("curves", &to_params(&resolved), None, ColorMode::Rgb).unwrap(); + let (master, channels) = curves_parts(&parsed); + let (original_master, original_channels) = curves_parts(&original); + assert_eq!(master, original_master, "the existing master curve is retained"); + for (curve, old_curve) in channels.iter().zip(original_channels) { + let old_edit = old_curve.get(1).expect("the test curve has an interior edit"); + assert!( + curve.iter().any(|point| { (point.input - old_edit.input).abs() < 1e-6 && (point.output - old_edit.output).abs() < 1e-6 }), + "the existing channel edit is retained: {curve:?}" + ); + } + let output = tone_output(&parsed, sample); + assert!((output[0] - output[1]).abs() < 0.002 && (output[1] - output[2]).abs() < 0.002, "sample must become neutral: {output:?}"); + assert!((rgb_luma(output) - expected_luma).abs() < 0.003, "luma changed from {expected_luma} to {} ({output:?})", rgb_luma(output)); +} + +#[test] +fn curves_neutral_gray_preserves_luma_for_a_light_cast_sample() { + assert_gray_point_preserves_luma_and_existing_curve_edits([0.88, 0.76, 0.63]); +} + +#[test] +fn curves_neutral_gray_preserves_luma_for_a_dark_cast_sample() { + assert_gray_point_preserves_luma_and_existing_curve_edits([0.17, 0.105, 0.075]); +} + +#[test] +fn curves_neutral_gray_handles_near_black_and_near_white_samples() { + for sample in [[0.004, 0.006, 0.008], [0.992, 0.996, 0.999], [0.0, 0.0, 0.0], [1.0, 1.0, 1.0]] { + let resolved = curves_eyedropper(&json!({}), CurvesEyedropper::NeutralGray, sample, ColorMode::Rgb).unwrap(); + let parsed = from_params("curves", &to_params(&resolved), None, ColorMode::Rgb).unwrap(); + let (master, channels) = curves_parts(&parsed); + for curve in std::iter::once(master).chain(channels.iter().map(Vec::as_slice)) { + assert!(curve.len() >= 2, "{sample:?}: {curve:?}"); + assert!(curve.windows(2).all(|pair| pair[0].input < pair[1].input), "{sample:?}: {curve:?}"); + assert!(curve.windows(2).all(|pair| pair[1].input - pair[0].input >= CURVE_POINT_DUPLICATE_DISTANCE), "{sample:?}: {curve:?}"); + } + let output = tone_output(&parsed, sample); + assert!((output[0] - output[1]).abs() < 0.002 && (output[1] - output[2]).abs() < 0.002, "{sample:?}: {output:?}"); + assert!((rgb_luma(output) - rgb_luma(sample)).abs() < 0.003, "{sample:?}: {output:?}"); + } +} + +#[test] +fn gray_point_fallback_keeps_tightly_spaced_points_round_trip_safe() { + let base = json!({ + "red": [[0, 0], [100, 100], [100.51, 100], [255, 255]], + "green": [[0, 0], [100, 100], [100.51, 100], [255, 255]], + "blue": [[0, 0], [100, 100], [100.51, 100], [255, 255]] + }); + let sample = [100.25 / 255.0, 100.1 / 255.0, 100.4 / 255.0]; + let target = rgb_luma(sample); + let resolved = curves_eyedropper(&base, CurvesEyedropper::NeutralGray, sample, ColorMode::Rgb).unwrap(); + let parsed = from_params("curves", &to_params(&resolved), None, ColorMode::Rgb).unwrap(); + let (_, channels) = curves_parts(&parsed); + for (curve, input) in channels.iter().zip(sample) { + assert_eq!(curve.len(), 4, "the fallback keeps every serialized point: {curve:?}"); + assert!(curve.windows(2).all(|pair| pair[1].input - pair[0].input >= CURVE_POINT_DUPLICATE_DISTANCE), "{curve:?}"); + let sample_pair = curve.windows(2).find(|pair| pair[0].input <= input && input <= pair[1].input).unwrap(); + assert!((sample_pair[0].output - sample_pair[1].output).abs() < 1e-6, "fallback forms a plateau around the sample: {curve:?}"); + assert!((sample_pair[0].output - target).abs() < 0.001, "fallback uses the luma target: {curve:?}"); + } +} + +#[test] +fn curves_eyedropper_param_drives_the_command() { + let mut s = crate::Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + s.execute("edit.fill", json!({"color": [0.6, 0.5, 0.4]})).unwrap(); + s.execute("image.adjustments.curves", json!({"eyedropper": {"point": "white", "at": [2, 2]}})).unwrap(); + let px: Vec = serde_json::from_value(s.execute("document.pixel", json!({"x": 2, "y": 2})).unwrap()).unwrap(); + assert!(px.iter().take(3).all(|v| *v > 0.99), "the sample becomes white: {px:?}"); + s.execute("image.adjustments.curves", json!({"eyedropper": {"point": "black", "color": [1.0, 1.0, 1.0]}})).unwrap(); + let px: Vec = serde_json::from_value(s.execute("document.pixel", json!({"x": 2, "y": 2})).unwrap()).unwrap(); + assert!(px.iter().take(3).all(|v| *v < 0.01), "the given colour becomes black: {px:?}"); + for bad in [ + json!("black"), + json!({"point": "nope", "at": [1, 1]}), + json!({"point": "black"}), + json!({"point": "black", "at": [99, 1]}), + json!({"point": "black", "at": [-1, 1]}), + json!({"point": "black", "at": [1]}), + json!({"point": "gray", "at": [f64::MAX, 1]}), + json!({"point": "black", "color": "red"}), + ] { + assert!(s.execute("image.adjustments.curves", json!({"eyedropper": bad})).is_err(), "{bad}"); + } +} + +/// The Properties panel's pickers on a Curves adjustment layer (UI-217-15): one undoable step +/// that samples the image below the layer, so a repeated click keeps the same curve. +#[test] +fn layer_eyedropper_samples_below_the_curves_layer() { + let mut s = crate::Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + s.execute("edit.fill", json!({"color": [0.6, 0.5, 0.4]})).unwrap(); + s.execute("layer.newAdjustmentLayer.curves", json!({})).unwrap(); + let steps = s.active().unwrap().history.past_len(); + let pick = json!({"eyedropper": {"point": "white", "at": [2, 2], "size": 3}}); + s.execute("layer.setAdjustment", pick.clone()).unwrap(); + assert_eq!(s.active().unwrap().history.past_len(), steps + 1); + let px: Vec = serde_json::from_value(s.execute("document.pixel", json!({"x": 2, "y": 2})).unwrap()).unwrap(); + assert!(px.iter().take(3).all(|v| *v > 0.99), "the sample becomes white: {px:?}"); + let curve = s.active().unwrap().doc.clone(); + s.execute("layer.setAdjustment", pick).unwrap(); + let same = |a: &photocraft_doc::Document, b: &photocraft_doc::Document| a.layers.last().map(|l| &l.content) == b.layers.last().map(|l| &l.content); + assert!(same(&curve, &s.active().unwrap().doc), "sampled below the layer, not through it"); + s.execute("edit.undo", json!({})).unwrap(); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(s.active().unwrap().history.past_len(), steps); + for bad in [json!({"point": "black", "at": [99, 1]}), json!({"point": "black", "at": [1, 1], "size": 2}), json!({"point": "x", "at": [1, 1]})] { + assert!(s.execute("layer.setAdjustment", json!({"eyedropper": bad})).is_err(), "{bad}"); + } + s.execute("layer.newAdjustmentLayer.hueSaturation", json!({})).unwrap(); + assert!(s.execute("layer.setAdjustment", json!({"eyedropper": {"point": "white", "at": [1, 1]}})).is_err(), "Levels and Curves only"); +} + +/// #3127: on a smart object the eyedropper param records the adjustment it resolved to as +/// the smart filter, not the raw sample (which re-rendered as an identity). +#[test] +fn eyedropper_on_a_smart_object_records_the_resolved_adjustment() { + for kind in ["curves", "levels"] { + let mut s = crate::Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + s.execute("edit.fill", json!({"color": [0.6, 0.5, 0.4]})).unwrap(); + s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + s.execute(&format!("image.adjustments.{kind}"), json!({"eyedropper": {"point": "white", "at": [2, 2]}})).unwrap(); + let px: Vec = serde_json::from_value(s.execute("document.pixel", json!({"x": 2, "y": 2})).unwrap()).unwrap(); + assert!(px.iter().take(3).all(|v| *v > 0.99), "{kind}: {px:?}"); + } +} + +/// Levels' Set White/Neutral Gray Point (#3116): the white point maps the sampled colour to +/// white at 8 and 16 bit, the gray point neutralises a tinted grey at its luma on a Levels +/// layer as one undoable step, and bad picks fail. +#[test] +fn levels_eyedroppers_set_white_and_neutral_gray() { + let pixel = |s: &mut crate::Session| -> Vec { serde_json::from_value(s.execute("document.pixel", json!({"x": 2, "y": 2})).unwrap()).unwrap() }; + for depth in [8, 16] { + let mut s = crate::Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8, "depth": depth})).unwrap(); + s.execute("edit.fill", json!({"color": [0.6, 0.5, 0.4]})).unwrap(); + s.execute("image.adjustments.levels", json!({"eyedropper": {"point": "white", "at": [2, 2]}})).unwrap(); + let px = pixel(&mut s); + assert!(px.iter().take(3).all(|v| *v > 0.995), "{depth}-bit: the sample becomes white: {px:?}"); + } + let mut s = crate::Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + s.execute("edit.fill", json!({"color": [0.6, 0.5, 0.4]})).unwrap(); + let before = pixel(&mut s); + s.execute("layer.newAdjustmentLayer.levels", json!({})).unwrap(); + let steps = s.active().unwrap().history.past_len(); + s.execute("layer.setAdjustment", json!({"eyedropper": {"point": "gray", "at": [2, 2]}})).unwrap(); + assert_eq!(s.active().unwrap().history.past_len(), steps + 1); + let px = pixel(&mut s); + let (lo, hi) = px.iter().take(3).fold((1.0f32, 0.0f32), |(lo, hi), v| (lo.min(*v), hi.max(*v))); + assert!(hi - lo < 2.5 / 255.0, "neutral: {px:?}"); + let luma = |c: &[f32]| c[0] * 0.2126 + c[1] * 0.7152 + c[2] * 0.0722; + assert!((luma(&px) - luma(&before)).abs() < 2.0 / 255.0, "keeps the luma: {px:?} vs {before:?}"); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(pixel(&mut s), before); + for bad in [json!({"point": "gray", "at": [99, 1]}), json!({"point": "x", "at": [1, 1]}), json!({"point": "white", "color": [f64::NAN, 0, 0]})] { + assert!(s.execute("layer.setAdjustment", json!({"eyedropper": bad})).is_err(), "{bad}"); + assert!(s.execute("image.adjustments.levels", json!({"eyedropper": bad})).is_err(), "{bad}"); + } + s.execute("file.new", json!({"width": 8, "height": 8, "mode": "grayscale"})).unwrap(); + assert!(s.execute("image.adjustments.levels", json!({"eyedropper": {"point": "gray", "at": [1, 1]}})).is_err(), "no gray picker in Grayscale"); + s.execute("image.adjustments.levels", json!({"eyedropper": {"point": "black", "color": [1.0, 1.0, 1.0]}})).unwrap(); +} + +#[test] +fn curves_eyedropper_support_is_explicit_and_bad_samples_fail() { + assert!(curves_eyedropper(&json!({}), CurvesEyedropper::Black, [0.4; 3], ColorMode::Grayscale).is_ok()); + assert!(curves_eyedropper(&json!({}), CurvesEyedropper::White, [0.4; 3], ColorMode::Grayscale).is_ok()); + assert!(curves_eyedropper(&json!({}), CurvesEyedropper::NeutralGray, [0.4; 3], ColorMode::Grayscale).is_err()); + for mode in [ColorMode::Cmyk, ColorMode::Lab] { + assert!(curves_eyedropper(&json!({}), CurvesEyedropper::Black, [0.4; 3], mode).is_err()); + } + assert!(curves_eyedropper(&json!({}), CurvesEyedropper::Black, [f32::NAN, 0.0, 0.0], ColorMode::Rgb).is_err()); +} + +#[test] +fn hue_range_sliders_stay_ordered() { + let a = from_params("hueSaturation", &json!({"greens": {"range": [100, 90, 200, 150]}}), None, ColorMode::Rgb).unwrap(); + let Adjustment::HueSaturation { ranges, .. } = a else { panic!() }; + let b = ranges[2].bounds; + assert!(b[0] <= b[1] && b[1] <= b[2] && b[2] <= b[3] && b[3] - b[0] < 360.0, "{b:?}"); +} + +/// A colourful 16×16 document (`mode`, `depth`) for command tests. +fn colourful(mode: &str, depth: u32) -> crate::Session { + let mut s = crate::Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16, "mode": mode, "depth": depth})).unwrap(); + for (i, c) in ["#c83c28", "#3c8c50", "#2850b4", "#d2b464"].iter().enumerate() { + s.execute("select.rect", json!({"x": (i % 2) * 8, "y": (i / 2) * 8, "width": 8, "height": 8})).unwrap(); + s.execute("edit.fill", json!({"color": c})).unwrap(); + } + s.execute("select.deselect", json!({})).unwrap(); + s +} + +fn pixels(s: &crate::Session) -> Vec> { + let d = s.active().unwrap(); + let bg = d.doc.layers[0].surface().unwrap(); + [(2, 2), (10, 2), (2, 10), (10, 10)].iter().map(|&(x, y)| bg.pixel(x, y)).collect() +} + +#[test] +fn destructive_commands_apply_their_params_at_every_depth() { + for depth in [8, 16, 32] { + for kind in KINDS.iter().filter(|k| **k != "invert") { + let mut s = colourful("rgb", depth); + let before = pixels(&s); + let steps = s.active().unwrap().history.past_len(); + s.execute(&format!("image.adjustments.{kind}"), sample(kind)).unwrap_or_else(|e| panic!("{kind} @{depth}: {e}")); + assert_ne!(pixels(&s), before, "{kind} @{depth} changed nothing"); + assert_eq!(s.active().unwrap().history.past_len(), steps + 1, "{kind}: one history step"); + // Identity params leave the pixels alone (within one 8-bit step). + let mut s = colourful("rgb", depth); + s.execute(&format!("image.adjustments.{kind}"), to_params(&default_for(kind, ColorMode::Rgb).unwrap())).unwrap(); + if !matches!(*kind, "threshold" | "posterize" | "blackWhite" | "gradientMap" | "photoFilter") { + for (a, b) in pixels(&s).iter().zip(&before) { + assert!(a.iter().zip(b).all(|(x, y)| (x - y).abs() <= 1.0 / 255.0 + 1e-4), "{kind} @{depth}: {a:?} vs {b:?}"); + } + } + } + } +} + +#[test] +fn curves_pencil_maps_draw_smooth_and_convert_back() { + // A drawn inversion: 256 output levels. + let inverted: Vec = (0..256).rev().map(|k| k as f32).collect(); + let a = from_params("curves", &json!({"pencil": true, "points": inverted}), None, ColorMode::Rgb).unwrap(); + assert!(matches!(&a, Adjustment::Curves { pencil: true, master, .. } if master.len() == CURVE_MAP_LEN)); + assert!((tone_output(&a, [0.25; 3])[0] - 0.75).abs() < 1e-3); + assert_eq!(from_params("curves", &to_params(&a), None, ColorMode::Rgb).unwrap(), a); + // Smooth evens out a hard step but keeps the endpoints. + let step: Vec = (0..256).map(|k| if k < 128 { 0.0 } else { 255.0 }).collect(); + let s = from_params("curves", &json!({"red": step, "smooth": 2}), Some(&a), ColorMode::Rgb).unwrap(); + let (_, chans) = curves_parts(&s); + assert!(chans[0][127].output > 0.2 && chans[0][128].output < 0.8, "{:?}", &chans[0][120..136]); + assert_eq!((chans[0][0].output, chans[0][255].output), (0.0, 1.0)); + // Edit points: the map is fitted with a point curve that still inverts. + let pts = from_params("curves", &json!({"pencil": false}), Some(&a), ColorMode::Rgb).unwrap(); + let (master, _) = curves_parts(&pts); + assert!(matches!(&pts, Adjustment::Curves { pencil: false, .. }) && master.len() <= MAX_FITTED_POINTS, "{master:?}"); + assert!((tone_output(&pts, [0.25; 3])[0] - 0.75).abs() < 2.0 / 255.0); + // The command draws it at every depth. + for depth in [8, 16, 32] { + let mut s = colourful("rgb", depth); + let before = pixels(&s); + s.execute("image.adjustments.curves", to_params(&a)).unwrap(); + let after = pixels(&s); + assert!((after[0][0] - (1.0 - before[0][0])).abs() < 2.0 / 255.0, "@{depth}: {after:?} vs {before:?}"); + } +} + +#[test] +fn destructive_levels_dont_clip_in_32_bit() { + // Input 15..230, gamma 1.3, output 10..245: integer documents stop at the output range, + // while float documents preserve the curve's signed and HDR values beyond it (the + // compose-side `levels_dont_clip_in_32_bit` pins the same curve, #2592). + let params = json!({"inBlack": 15, "inWhite": 230, "gamma": 1.3, "outBlack": 10, "outWhite": 245}); + for depth in [8, 16, 32] { + let mut s = crate::Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16, "depth": depth, "background": "white"})).unwrap(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 8, "height": 16})).unwrap(); + s.execute("edit.fill", json!({"color": "#000000"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s.execute("image.adjustments.levels", params.clone()).unwrap(); + let px = pixels(&s); + if depth == 32 { + assert!(px[0][0].is_finite() && px[0][0] < 0.0, "float black keeps its signed result: {:?}", px[0]); + assert!(px[1][0].is_finite() && px[1][0] > 1.0, "float white keeps its HDR result: {:?}", px[1]); + } else { + assert!((px[0][0] * 255.0 - 10.0).abs() < 0.6, "black @{depth}: {:?}", px[0]); + assert!((px[1][0] * 255.0 - 245.0).abs() < 0.6, "white @{depth}: {:?}", px[1]); + } + } +} + +#[test] +fn cmyk_and_lab_documents_use_their_channels() { + let mut s = colourful("cmyk", 8); + let before = pixels(&s); + // More black ink darkens every patch. + s.execute("image.adjustments.curves", json!({"black": [[0, 0], [255, 180]]})).unwrap(); + let after = pixels(&s); + assert!(after.iter().zip(&before).all(|(a, b)| a[3] > b[3] + 0.05), "{after:?} vs {before:?}"); + let mut s = colourful("lab", 16); + let before = pixels(&s); + s.execute("image.adjustments.levels", json!({"lightness": {"outBlack": 60}})).unwrap(); + let after = pixels(&s); + assert!(after.iter().zip(&before).all(|(a, b)| a[0] >= b[0]), "lightness lifted {after:?} vs {before:?}"); + // The adjustment layer of a CMYK document defaults to ink channels. + let mut s = colourful("cmyk", 8); + s.execute("layer.newAdjustmentLayer.curves", json!({})).unwrap(); + let id = s.active().unwrap().active_layer.unwrap(); + let l = s.active().unwrap().doc.layer(id).unwrap().clone(); + assert!(matches!(l.content, photocraft_doc::LayerContent::Adjustment(Adjustment::Curves { space: ToneSpace::Cmyk, .. }))); +} + +#[test] +fn set_adjustment_merges_and_resets() { + let mut s = colourful("rgb", 8); + s.execute("layer.newAdjustmentLayer.colorBalance", json!({"midtones": [30, 0, 0]})).unwrap(); + s.execute("layer.setAdjustment", json!({"highlights": [0, 0, -20]})).unwrap(); + let id = s.active().unwrap().active_layer.unwrap(); + let adj = |s: &crate::Session| match &s.active().unwrap().doc.layer(id).unwrap().content { + photocraft_doc::LayerContent::Adjustment(a) => a.clone(), + _ => panic!(), + }; + assert!(matches!(adj(&s), Adjustment::ColorBalance { midtones: [30.0, 0.0, 0.0], highlights: [0.0, 0.0, -20.0], .. })); + s.execute("layer.setAdjustment", json!({"layer": id.0})).unwrap(); + assert_eq!(adj(&s), default_for("colorBalance", ColorMode::Rgb).unwrap()); + // Bad params are errors and leave the layer alone. + s.execute("layer.setAdjustment", json!({"midtones": [10, 10, 10]})).unwrap(); + let kept = adj(&s); + for bad in [json!({"midtones": "x"}), json!({"preserveLuminosity": 3}), json!({"shadows": [1]})] { + assert!(s.execute("layer.setAdjustment", bad.clone()).is_err(), "{bad}"); + assert_eq!(adj(&s), kept); + } +} + +#[test] +fn commands_reject_bad_params_gracefully() { + let mut s = colourful("rgb", 8); + for (kind, p) in [ + ("curves", json!({"points": [[0, 0]]})), + ("levels", json!({"red": "dark"})), + ("gradientMap", json!({"stops": [[0, 1, 2]]})), + ("photoFilter", json!({"filter": 3})), + ("channelMixer", json!({"gray": [1, 2]})), + ("hueSaturation", json!({"reds": 4})), + ("blackWhite", json!({"tint": "yes"})), + ] { + for prefix in ["image.adjustments.", "layer.newAdjustmentLayer."] { + let r = s.execute(&format!("{prefix}{kind}"), p.clone()); + assert!(matches!(r, Err(EngineError::BadParams { .. })), "{prefix}{kind} {p}: {r:?}"); + } + } +} +#[test] +fn destructive_levels_match_independent_signed_hdr_endpoints() { + // Input 15..230, gamma 1.3, output 10..245: black and white land on the output range in + // integer documents. Float32 keeps HDR values outside 0..1, as the compositor's real-file + // Levels oracle does. These independently calculated endpoints use the signed-power + // curve at black and white, not display-clipped values. + let params = json!({"inBlack": 15, "inWhite": 230, "gamma": 1.3, "outBlack": 10, "outWhite": 245}); + for (depth, low, high, tolerance) in [(8, 10.0, 245.0, 0.6), (16, 10.0, 245.0, 0.6), (32, -20.308_89, 265.750_3, 0.01)] { + let mut s = crate::Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16, "depth": depth, "background": "white"})).unwrap(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 8, "height": 16})).unwrap(); + s.execute("edit.fill", json!({"color": "#000000"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s.execute("image.adjustments.levels", params.clone()).unwrap(); + let px = pixels(&s); + assert!((px[0][0] * 255.0 - low).abs() < tolerance, "black @{depth}: {:?}", px[0]); + assert!((px[1][0] * 255.0 - high).abs() < tolerance, "white @{depth}: {:?}", px[1]); + if depth == 32 { + assert!(px[0][0] < 0.0 && px[1][0] > 1.0, "HDR endpoints must remain unclipped"); + } + } +} diff --git a/crates/engine/src/align_cmds.rs b/crates/engine/src/align_cmds.rs deleted file mode 100644 index 99e3c8a590..0000000000 --- a/crates/engine/src/align_cmds.rs +++ /dev/null @@ -1,947 +0,0 @@ -//! Edit › Auto-Align Layers and Auto-Blend Layers, on the selected pixel layers. -//! -//! Both share Photomerge's registration and blending ([`photocraft_algo::panorama`] via -//! `photo_cmds`). Auto-Align matches Harris / steered-BRIEF features between every pair of -//! layers, chains the verified pairs from the reference layer (maximum spanning tree) and -//! bundle-adjusts all of them, then warps each layer. Layers that nearly coincide (a focus or -//! exposure bracket) have nothing to match and register by intensity instead -//! ([`photocraft_algo::direct`], `registration`: auto falls back to it, or ask for it). Projections: Auto, Perspective -//! (homography), Cylindrical and Spherical (rigid motion on the cylinder / sphere, focal length -//! from the homographies or EXIF), Collage (similarity) and Reposition (translation). The -//! reference stays put in the planar projections. -//! -//! Auto-Blend gives each selected layer a mask so the composite shows, per pixel, the sharpest -//! layer (Stack Images, for focus stacking) or one layer per region with seams routed where the -//! layers agree (Panorama). With Seamless Tones and Colors it also adds a merged layer: the -//! panorama blended with Laplacian pyramids so transitions are invisible, the stack fused on the -//! Laplacian pyramid, each coefficient from the layer sharpest at that scale -//! ([`pyramid::fuse_stack`]; `haloControl` keeps a bright object's defocused glow out of the -//! coarse levels). -//! Stack Images can also add a hidden Depth layer, the layer each pixel is sharpest in by depth -//! from focus ([`photocraft_algo::dff`]): black = the bottom layer, white = the top, so that once -//! on a layer mask it drives Lens Blur's depth map. - -use photocraft_algo::panorama::Layout; -use photocraft_algo::pyramid; -use photocraft_algo::transform::Interp; -use photocraft_algo::warp::warp_mesh_gray; -use photocraft_doc::{Document, Layer, LayerContent, LayerId, LayerMask}; -use photocraft_geom::Rect; -use photocraft_raster::{Surface, to_rgba}; -use serde_json::{Value, json}; - -use crate::commands::CommandSpec; -use crate::photo_cmds::{NO_DETAIL, plane_matrix, register, register_direct, seam_blend, seam_order, warp_placed}; -use crate::{EngineError, Result, Session}; - -fn bad(cmd: &str, msg: impl Into) -> EngineError { - EngineError::BadParams { cmd: cmd.into(), msg: msg.into() } -} - -/// The selected raster layers, bottom to top. -fn selected_pixel_layers(s: &Session) -> Vec { - let Some(st) = s.active() else { return Vec::new() }; - st.selected_layers().into_iter().filter(|id| st.doc.layer(*id).is_some_and(|l| matches!(l.content, LayerContent::Raster(_)))).collect() -} - -/// Whether a lock keeps the layer `id` from being moved or warped: lock all, position or pixels. -/// The Background's own position lock doesn't count: like Free Transform, Auto-Align turns the -/// Background into a normal layer when it has to move it (Photoshop). -fn pinned(doc: &Document, id: LayerId) -> bool { - let l = doc.effective_locks(id); - l.all || l.pixels || (l.position && !doc.is_background(id)) -} - -fn two_layers(s: &Session) -> std::result::Result<(), String> { - s.active().ok_or("no document open")?; - if selected_pixel_layers(s).len() < 2 { Err("select two or more pixel layers in the Layers panel".into()) } else { Ok(()) } -} - -fn auto_align(s: &mut Session, p: &Value) -> Result { - let cmd = "edit.autoAlignLayers"; - let ids = selected_pixel_layers(s); - if ids.len() < 2 { - return Err(bad(cmd, "select two or more pixel layers")); - } - let projection = p.get("projection").and_then(Value::as_str).unwrap_or("auto"); - let layout = Layout::parse(projection) - .ok_or_else(|| bad(cmd, format!("unknown projection `{projection}` (auto|perspective|cylindrical|spherical|collage|reposition)")))?; - let st = s.active().ok_or(EngineError::NoDocument)?; - let doc = st.doc.clone(); - let reference = match p.get("reference").and_then(Value::as_u64) { - Some(r) if ids.contains(&LayerId(r)) => LayerId(r), - Some(r) => return Err(bad(cmd, format!("reference {r} is not a selected pixel layer"))), - // As in Photoshop, a locked layer stays put: it becomes the reference (#7080). - None => ids.iter().copied().find(|id| pinned(&doc, *id)).unwrap_or(ids[0]), - }; - let ref_idx = ids.iter().position(|i| *i == reference).unwrap_or(0); - let area = doc.bounds(); - let surfs: Vec<&Surface> = ids.iter().map(|id| doc.layer(*id).and_then(|l| l.surface()).ok_or(EngineError::NoLayer(*id))).collect::>()?; - let images: Vec<(&Surface, Rect)> = surfs.iter().map(|s| (*s, area)).collect(); - let focal35 = doc.metadata.exif.as_ref().and_then(|e| photocraft_algo::exif::read(e).focal_length_35mm); - let geometric = p.get("geometricCorrection").and_then(Value::as_bool).unwrap_or(false); - let registration = p.get("registration").and_then(Value::as_str).unwrap_or("auto"); - if !matches!(registration, "auto" | "features" | "intensity") { - return Err(bad(cmd, "`registration` must be auto|features|intensity")); - } - let no_detail = || EngineError::Other(NO_DETAIL.into()); - // Features first (a panorama); layers that nearly coincide (a focus or exposure bracket) have - // nothing to match, and register by intensity instead. - let by_features = (registration != "intensity").then(|| register(&images, layout, Some(ref_idx), geometric, focal35)).flatten(); - let (al, used) = match (by_features, registration) { - (Some(al), _) => (al, "features"), - (None, "features") => return Err(no_detail()), - (None, _) => ( - register_direct(&images, layout, ref_idx).map_err(|m| if registration == "intensity" && m != NO_DETAIL { bad(cmd, m) } else { no_detail() })?, - "intensity", - ), - }; - let interp = Interp::parse(p.get("interpolation").and_then(Value::as_str).unwrap_or("bicubic")); - let planar = matches!(al.layout, Layout::Perspective | Layout::Collage | Layout::Reposition); - let mut inliers = vec![0usize; ids.len()]; - for &(a, b, n) in &al.pairs { - inliers[a] += n; - inliers[b] += n; - } - // Everything but the reference moves in planar layouts; every layer is reprojected otherwise. - let moves: Vec = (0..ids.len()).filter(|&i| al.placements[i].is_some() && (i != ref_idx || !planar)).collect(); - let failed: Vec = (0..ids.len()).filter(|&i| al.placements[i].is_none()).map(|i| ids[i].0).collect(); - if moves.is_empty() { - return Err(EngineError::Other("Auto-Align couldn't find enough matching detail between the layers".into())); - } - if let Some(l) = moves.iter().find(|&&i| pinned(&doc, ids[i])).and_then(|&i| doc.layer(ids[i])) { - return Err(EngineError::Other(format!("Auto-Align can't move the locked layer \"{}\"", l.name))); - } - let warped: Vec<(LayerId, Surface, Option)> = moves - .iter() - .map(|&i| { - let pl = al.placements[i].as_ref().ok_or_else(|| EngineError::Other("Auto-Align lost a layer's placement".into()))?; - let l = doc.layer(ids[i]).ok_or(EngineError::NoLayer(ids[i]))?; - let surf = l.surface().ok_or(EngineError::NoLayer(ids[i]))?; - let b = surf.content_bounds(); - let px = if b.is_empty() { surf.clone() } else { warp_placed(surf, b, (0.0, 0.0), pl, (0.0, 0.0), interp)? }; - // Masks warp as masks: one grey channel whose outside keeps its default (reveal-all - // stays revealed), not as colour, which would come back grey + alpha reading 0 outside. - let mask = match l.mask.as_ref() { - Some(m) => Some(match plane_matrix(pl, (0.0, 0.0)) { - Some(h) => crate::transform_cmds::warp_gray(&m.surface, &h, Interp::Bilinear)?, - None => warp_mesh_gray(&m.surface, &|x, y| pl.forward(x, y), Interp::Bilinear), - }), - None => None, - }; - Ok((ids[i], px, mask)) - }) - .collect::>()?; - s.edit("Auto-Align Layers", |doc, _| { - for (id, px, mask) in &warped { - // Photoshop turns the Background into a normal layer before moving it. - crate::extra_cmds::background_to_layer(doc, *id); - let l = doc.layer_mut(*id).ok_or(EngineError::NoLayer(*id))?; - if let Some(surf) = l.surface_mut() { - *surf = px.clone(); - } - if let (Some(m), Some(ms)) = (&mut l.mask, mask) { - m.surface = ms.clone(); - } - } - Ok(()) - })?; - let model = match al.layout { - Layout::Reposition => "reposition", - Layout::Collage => "collage", - Layout::Perspective | Layout::Auto => "perspective", - Layout::Cylindrical => "cylindrical", - Layout::Spherical => "spherical", - }; - let aligned: Vec = moves - .iter() - .filter_map(|&i| { - let pl = al.placements[i].as_ref()?; - Some(json!({"layer": ids[i].0, "model": model, "matches": inliers[i], "matrix": plane_matrix(pl, (0.0, 0.0)).map(|h| h.0.to_vec())})) - }) - .collect(); - Ok( - json!({"reference": reference.0, "layout": al.layout.name(), "registration": used, "focal": al.focal, "rms": al.rms, "aligned": aligned, "failed": failed}), - ) -} - -/// The most memory Auto-Blend's working buffers may take past the canvas: a bound independent -/// of the layers' own bounding boxes, which a sparse layer (a dot at each far corner) can make -/// arbitrarily large, and of how many layers are blended. -const MAX_BLEND_BYTES: u64 = 4 << 30; - -/// What Auto-Blend's buffers hold per work-area pixel, as f32: each layer's pixels, luminance, -/// alpha and mask weight, plus the merged picture and the depth map. -fn blend_bytes_per_pixel(layers: u64, channels: u64) -> u64 { - layers.saturating_mul(channels.saturating_add(3)).saturating_add(channels.saturating_mul(2)).saturating_mul(4) -} - -/// Auto-Blend's buffers, for allocation errors. -const BLEND_BUFFERS: &str = "Auto-Blend Layers"; - -fn auto_blend(s: &mut Session, p: &Value) -> Result { - let cmd = "edit.autoBlendLayers"; - let ids = selected_pixel_layers(s); - if ids.len() < 2 { - return Err(bad(cmd, "select two or more pixel layers")); - } - let method = p.get("method").and_then(Value::as_str).unwrap_or("panorama"); - if !matches!(method, "panorama" | "stack") { - return Err(bad(cmd, "`method` must be panorama|stack")); - } - let seamless = p.get("seamlessTones").and_then(Value::as_bool).unwrap_or(true); - let halo = match p.get("haloControl") { - None | Some(Value::Null) => pyramid::StackFusion::default().halo, - Some(v) => match v.as_f64() { - Some(h) if (0.0..=f64::from(pyramid::HALO_MAX)).contains(&h) => h as f32, - _ => return Err(bad(cmd, format!("`haloControl` must be a number from 0 to {}", pyramid::HALO_MAX))), - }, - }; - let want_depth = p.get("depthMap").and_then(Value::as_bool).unwrap_or(false); - if want_depth && method != "stack" { - return Err(bad(cmd, "`depthMap` needs `method`: stack")); - } - let st = s.active().ok_or(EngineError::NoDocument)?; - let doc: std::sync::Arc = st.doc.clone(); - let mut union = Rect::EMPTY; - let mut content_px = 0u64; - let px_of = |r: &Rect| u64::from(r.width()) * u64::from(r.height()); - for id in &ids { - if let Some(b) = doc.layer(*id).and_then(|l| l.surface()).map(|s| s.content_bounds()) { - union = union.union(&b); - content_px = content_px.saturating_add(px_of(&b)); - } - } - // The whole layers, past the canvas too (#5745): Auto-Align leaves a panorama's layers - // partly off the canvas, and Photoshop masks and blends all of each layer, so Reveal All - // shows the whole panorama. Layers so far apart that their bounds are mostly empty, or - // whose buffers would exceed `MAX_BLEND_BYTES`, keep to the canvas. - let canvas = doc.bounds(); - let channels = ids.iter().filter_map(|id| doc.layer(*id).and_then(|l| l.surface()).map(|s| s.channels() as u64)).max().unwrap_or(4); - let per_px = blend_bytes_per_pixel(ids.len() as u64, channels); - let fits = px_of(&union).saturating_mul(per_px) <= MAX_BLEND_BYTES && px_of(&union) <= content_px.max(px_of(&canvas)).saturating_mul(2); - let area = if fits { union } else { union.intersect(&canvas) }; - if area.is_empty() { - return Err(EngineError::Other("the selected layers are empty".into())); - } - let (w, h) = (area.width() as usize, area.height() as usize); - let mut imgs: Vec> = Vec::new(); - let mut luma: Vec> = Vec::new(); - let mut alpha: Vec> = Vec::new(); - let mut fmt = None; - for id in &ids { - let l = doc.layer(*id).ok_or(EngineError::NoLayer(*id))?; - let surf = l.surface().ok_or(EngineError::NoLayer(*id))?; - let (px, f) = (crate::allocation::read_region(surf, area, BLEND_BUFFERS)?, surf.format()); - let n = f.channels(); - let (mut lv, mut av) = (crate::allocation::filled(w * h, 0.0f32, BLEND_BUFFERS)?, crate::allocation::filled(w * h, 0.0f32, BLEND_BUFFERS)?); - for i in 0..w * h { - let c = to_rgba(&f, &px[i * n..(i + 1) * n]); - lv[i] = 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]; - av[i] = c[3]; - } - if fmt.is_some_and(|g: photocraft_color::PixelFormat| g != f) { - return Err(EngineError::Other("the layers have different pixel formats".into())); - } - fmt = Some(f); - imgs.push(px); - luma.push(lv); - alpha.push(av); - } - let fmt = fmt.ok_or(EngineError::NoDocument)?; - let (weights, blended) = if method == "stack" { - let weights = pyramid::stack_weights(w, h, &luma, &alpha); - let blended = seamless.then(|| { - let refs: Vec<&[f32]> = imgs.iter().map(Vec::as_slice).collect(); - let p = pyramid::StackFusion { halo, ..Default::default() }; - pyramid::fuse_stack(w, h, fmt.channels(), &refs, &luma, &alpha, p) - }); - (weights, blended) - } else { - // Panorama: seams routed through agreement, multi-band blended (photo_cmds). - let surfs: Vec = - ids.iter().map(|id| doc.layer(*id).and_then(|l| l.surface()).cloned().ok_or(EngineError::NoLayer(*id))).collect::>()?; - let order = seam_order(&surfs, 0); - // Seamless Tones and Colors also evens out exposure and colour between the layers (gain - // compensation over their overlaps), as in Photomerge. - let b = seam_blend(&surfs, area, &order, seamless, seamless, None); - let weights: Vec> = b.layers.iter().map(|(_, m)| m.read_region(area)).collect(); - let blended = seamless.then(|| b.composite.read_region(area)); - (weights, blended) - }; - // The depth map: the layer each pixel is sharpest in, from the focus volume guided by the - // merged picture (or, without one, by the per-pixel pick), as a hidden gray layer, black = - // the bottom layer, white = the top, ready for Lens Blur's depth map once on a mask. - let depth_px = want_depth.then(|| { - let n = fmt.channels(); - let guide: Vec = match &blended { - Some(px) => (0..w * h) - .map(|i| { - let c = to_rgba(&fmt, &px[i * n..(i + 1) * n]); - 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2] - }) - .collect(), - None => (0..w * h).map(|i| luma.iter().zip(&weights).map(|(l, wt)| l[i] * wt[i]).sum()).collect(), - }; - let refs: Vec<&[f32]> = luma.iter().map(Vec::as_slice).collect(); - let dm = photocraft_algo::dff::depth_from_focus(&refs, &guide, w, h, &photocraft_algo::dff::DepthParams::default()); - let scale = 1.0 / (ids.len() - 1).max(1) as f32; - let mut out = vec![0.0f32; w * h * n]; - for (i, d) in dm.depth.iter().enumerate() { - let g = (d * scale).clamp(0.0, 1.0); - photocraft_raster::from_rgba_into(&fmt, [g, g, g, 1.0], &mut out[i * n..(i + 1) * n]); - } - out - }); - let top = *ids.last().ok_or_else(|| EngineError::Other("Auto-Blend needs two or more layers".into()))?; - let label = "Auto-Blend Layers"; - let (new_layer, depth_layer) = s.edit(label, |doc, active| { - for (id, wt) in ids.iter().zip(&weights) { - // The Background can't have a mask: it becomes a normal layer first, as in Photoshop. - crate::extra_cmds::background_to_layer_for_mask(doc, *id); - let l = doc.layer_mut(*id).ok_or(EngineError::NoLayer(*id))?; - let mut mask = LayerMask::hide_all(); - mask.surface.write_region(area, wt); - mask.surface.prune(); - l.mask = Some(mask); - } - let mut below = top; - let depth_id = depth_px.as_ref().map(|px| { - let mut l = Layer::raster(doc.next_layer_name("Depth"), fmt); - l.visible = false; - if let Some(surf) = l.surface_mut() { - surf.write_region(area, px); - surf.prune(); - } - below = doc.insert_above(Some(below), l); - below - }); - let Some(px) = &blended else { - if depth_id.is_some() { - *active = depth_id; - } - return Ok((None, depth_id)); - }; - let mut l = Layer::raster(doc.next_layer_name("Blended"), fmt); - if let Some(surf) = l.surface_mut() { - surf.write_region(area, px); - surf.prune(); - } - let nid = doc.insert_above(Some(below), l); - *active = Some(nid); - Ok((Some(nid), depth_id)) - })?; - Ok(json!({"method": method, "layers": ids.iter().map(|i| i.0).collect::>(), "blended": new_layer.map(|l| l.0), "depth": depth_layer.map(|l| l.0)})) -} - -macro_rules! spec { - ($id:literal, $label:literal, $params:literal, $run:expr) => { - CommandSpec { id: $id, label: $label, menu: &["Edit"], shortcut: None, params: $params, enabled: two_layers, run: $run, journal: true } - }; -} - -pub fn specs() -> Vec { - vec![ - spec!( - "edit.autoAlignLayers", - "Auto-Align Layers…", - r##"{"projection":"auto|perspective|cylindrical|spherical|collage|reposition","reference":layer id?=the locked selected layer, else the bottom selected layer,"geometricCorrection":bool=false,"interpolation":"bicubic|bilinear|nearest","registration":"auto|features|intensity"}"##, - auto_align - ), - spec!( - "edit.autoBlendLayers", - "Auto-Blend Layers…", - r##"{"method":"panorama|stack","seamlessTones":bool=true,"haloControl":0..8=2,"depthMap":bool=false}"##, - auto_blend - ), - ] -} - -#[cfg(test)] -mod tests { - use super::*; - - /// Deterministic texture written into a layer at offset (dx, dy). - fn texture_layer(s: &mut Session, name: &str, dx: i32, dy: i32) -> LayerId { - s.execute("layer.new.layer", json!({"name": name})).unwrap(); - let id = s.active().unwrap().active_layer.unwrap(); - paint_texture(s, id, dx, dy); - id - } - - /// Writes the deterministic texture into layer `id` at offset (dx, dy). - fn paint_texture(s: &mut Session, id: LayerId, dx: i32, dy: i32) { - s.edit("tex", |doc, _| { - let surf = doc.layer_mut(id).unwrap().surface_mut().unwrap(); - let mut seed = 99u64; - let mut rnd = || { - seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); - (seed >> 33) as f64 / (1u64 << 31) as f64 - }; - surf.fill_rect(Rect::new(dx, dy, dx + 240, dy + 180), &[0.4, 0.4, 0.4, 1.0]); - for _ in 0..120 { - let (x, y) = ((rnd() * 220.0) as i32, (rnd() * 160.0) as i32); - let (sw, sh) = (4 + (rnd() * 14.0) as i32, 4 + (rnd() * 10.0) as i32); - let v = rnd() as f32; - surf.fill_rect(Rect::new(dx + x, dy + y, dx + x + sw, dy + y + sh), &[v, 1.0 - v, v * 0.5, 1.0]); - } - Ok(()) - }) - .unwrap(); - } - - fn select(s: &mut Session, ids: &[LayerId]) { - s.execute("layer.select", json!({"layer": ids[0].0})).unwrap(); - for id in &ids[1..] { - s.execute("layer.select", json!({"layer": id.0, "mode": "add"})).unwrap(); - } - } - - #[test] - fn auto_align_repositions_at_all_depths() { - for depth in [8, 16, 32] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 300, "height": 240, "depth": depth, "background": "transparent"})).unwrap(); - let a = texture_layer(&mut s, "A", 20, 20); - let b = texture_layer(&mut s, "B", 31, 13); - assert!(!s.is_enabled("edit.autoAlignLayers"), "one layer selected"); - select(&mut s, &[a, b]); - assert!(s.is_enabled("edit.autoAlignLayers")); - let r = s.execute("edit.autoAlignLayers", json!({"projection": "reposition"})).unwrap(); - assert_eq!(r["reference"], a.0); - let bb = s.active().unwrap().doc.layer(b).unwrap().surface().unwrap().content_bounds(); - assert!((bb.x0 - 20).abs() <= 1 && (bb.y0 - 20).abs() <= 1, "depth {depth}: {bb:?} {r}"); - s.undo(); - let bb = s.active().unwrap().doc.layer(b).unwrap().surface().unwrap().content_bounds(); - assert_eq!((bb.x0, bb.y0), (31, 13)); - } - } - - #[test] - fn auto_align_auto_projection_and_errors() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 300, "height": 240, "background": "transparent"})).unwrap(); - let a = texture_layer(&mut s, "A", 20, 20); - let b = texture_layer(&mut s, "B", 26, 25); - select(&mut s, &[a, b]); - let r = s.execute("edit.autoAlignLayers", json!({})).unwrap(); - let m = r["aligned"][0]["matrix"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect::>(); - assert!((m[2] + 6.0).abs() < 1.0 && (m[5] + 5.0).abs() < 1.0, "{r}"); - assert!(s.execute("edit.autoAlignLayers", json!({"projection": "sideways"})).is_err()); - assert!(s.execute("edit.autoAlignLayers", json!({"reference": u64::MAX})).is_err()); - } - - /// As in Photoshop, a locked layer stays where it is: it becomes the reference and the - /// others move onto it (#7080). - #[test] - fn auto_align_keeps_a_locked_layer_as_the_reference() { - for lock in ["all", "position", "pixels"] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 300, "height": 240, "background": "transparent"})).unwrap(); - let a = texture_layer(&mut s, "A", 20, 20); - let b = texture_layer(&mut s, "B", 31, 13); - s.edit("lock", |doc, _| { - doc.layer_mut(b).unwrap().locks.set(lock, true); - Ok(()) - }) - .unwrap(); - select(&mut s, &[a, b]); - let r = s.execute("edit.autoAlignLayers", json!({"projection": "reposition"})).unwrap(); - assert_eq!(r["reference"], b.0, "{lock}: {r}"); - let doc = &s.active().unwrap().doc; - let bb = doc.layer(b).unwrap().surface().unwrap().content_bounds(); - assert_eq!((bb.x0, bb.y0), (31, 13), "{lock}: the locked layer stays put"); - let ab = doc.layer(a).unwrap().surface().unwrap().content_bounds(); - assert!((ab.x0 - 31).abs() <= 1 && (ab.y0 - 13).abs() <= 1, "{lock}: {ab:?} {r}"); - // An explicit reference that would move the locked layer is refused. - s.undo(); - assert!(s.execute("edit.autoAlignLayers", json!({"projection": "reposition", "reference": a.0})).is_err()); - // Two locked layers: nothing may move. - s.edit("lock", |doc, _| { - doc.layer_mut(a).unwrap().locks.set(lock, true); - Ok(()) - }) - .unwrap(); - assert!(s.execute("edit.autoAlignLayers", json!({"projection": "reposition"})).is_err()); - let bb = s.active().unwrap().doc.layer(a).unwrap().surface().unwrap().content_bounds(); - assert_eq!((bb.x0, bb.y0), (20, 20)); - } - } - - /// The Background doesn't block Auto-Align: when a projection reprojects every layer - /// (Cylindrical, Spherical, or Auto choosing one), or another layer is the reference, it - /// becomes a normal layer ("Layer 0") and moves, as in Photoshop and as Free Transform does. - #[test] - fn auto_align_moves_the_background_as_a_normal_layer() { - let setup = || { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 300, "height": 240, "background": "white"})).unwrap(); - let bg = s.active().unwrap().doc.background().unwrap().id; - paint_texture(&mut s, bg, 20, 20); - let b = texture_layer(&mut s, "B", 31, 13); - select(&mut s, &[bg, b]); - (s, bg, b) - }; - for projection in ["cylindrical", "spherical", "auto"] { - let (mut s, bg, b) = setup(); - let r = s.execute("edit.autoAlignLayers", json!({"projection": projection})).unwrap_or_else(|e| panic!("{projection}: {e}")); - let doc = &s.active().unwrap().doc; - let moved = r["aligned"].as_array().unwrap().iter().any(|a| a["layer"] == bg.0); - assert_eq!(moved, projection != "auto" || r["layout"] != "perspective", "{projection}: {r}"); - assert_eq!(doc.is_background(bg), !moved, "{projection}: a moved Background is a normal layer: {r}"); - if moved { - assert_eq!(doc.layer(bg).unwrap().name, "Layer 0", "{projection}"); - } - assert!(doc.layer(b).is_some(), "{projection}"); - s.undo(); - assert!(s.active().unwrap().doc.is_background(bg), "{projection}: undo restores the Background"); - } - // Planar, with the other layer as the reference: the Background moves onto it. - let (mut s, bg, b) = setup(); - s.execute("edit.autoAlignLayers", json!({"projection": "reposition", "reference": b.0})).unwrap(); - let doc = &s.active().unwrap().doc; - assert!(!doc.is_background(bg)); - // Default reference: the Background (bottom) stays put and stays the Background. - let (mut s, bg, b) = setup(); - let r = s.execute("edit.autoAlignLayers", json!({"projection": "reposition"})).unwrap(); - assert_eq!(r["reference"], bg.0, "{r}"); - let doc = &s.active().unwrap().doc; - assert!(doc.is_background(bg)); - let bb = doc.layer(b).unwrap().surface().unwrap().content_bounds(); - assert!((bb.x0 - 20).abs() <= 1 && (bb.y0 - 20).abs() <= 1, "{bb:?} {r}"); - } - - /// The moving layer's mask is warped as a mask: one grey channel whose outside keeps its - /// default (reveal-all stays revealed, hide-all stays hidden), for planar and mesh warps. - #[test] - fn auto_align_warps_layer_masks_keeping_their_default() { - for (projection, reveal) in [("reposition", true), ("reposition", false), ("cylindrical", true)] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 300, "height": 240, "background": "transparent"})).unwrap(); - let a = texture_layer(&mut s, "A", 20, 20); - let b = texture_layer(&mut s, "B", 31, 13); - let (inside, outside) = if reveal { (0.0, 1.0) } else { (1.0, 0.0) }; - s.edit("mask", |doc, _| { - let mut m = if reveal { LayerMask::reveal_all() } else { LayerMask::hide_all() }; - m.surface.fill_rect(Rect::new(100, 100, 110, 110), &[inside]); - doc.layer_mut(b).unwrap().mask = Some(m); - Ok(()) - }) - .unwrap(); - select(&mut s, &[a, b]); - let r = s.execute("edit.autoAlignLayers", json!({"projection": projection})).unwrap(); - let doc = &s.active().unwrap().doc; - let m = doc.layer(b).unwrap().mask.as_ref().unwrap(); - assert_eq!(m.surface.format().channels(), 1, "{projection}: {r}"); - assert_eq!(m.value(250, 200), outside, "{projection} reveal={reveal}: {r}"); - assert_eq!(m.value(5, 5), outside, "{projection} reveal={reveal}: {r}"); - if projection == "reposition" { - // The square moved with the layer (by about (-11, +7)). - assert!((m.value(94, 112) - inside).abs() < 0.01, "{r}"); - } - } - } - - #[test] - fn auto_blend_panorama_masks_and_seamless_layer() { - for depth in [8, 16, 32] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 200, "height": 60, "depth": depth, "background": "transparent"})).unwrap(); - s.execute("layer.new.layer", json!({"name": "left"})).unwrap(); - s.edit("l", |doc, active| { - doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(0, 0, 130, 60), &[0.2, 0.3, 0.8, 1.0]); - Ok(()) - }) - .unwrap(); - let left = s.active().unwrap().active_layer.unwrap(); - s.execute("layer.new.layer", json!({"name": "right"})).unwrap(); - s.edit("r", |doc, active| { - doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(70, 0, 200, 60), &[0.9, 0.6, 0.2, 1.0]); - Ok(()) - }) - .unwrap(); - let right = s.active().unwrap().active_layer.unwrap(); - select(&mut s, &[left, right]); - let r = s.execute("edit.autoBlendLayers", json!({"method": "panorama"})).unwrap(); - let doc = &s.active().unwrap().doc; - let ml = doc.layer(left).unwrap().mask.as_ref().unwrap(); - let mr = doc.layer(right).unwrap().mask.as_ref().unwrap(); - assert_eq!((ml.value(10, 30), mr.value(10, 30)), (1.0, 0.0), "depth {depth}"); - assert_eq!((ml.value(190, 30), mr.value(190, 30)), (0.0, 1.0)); - let blended = LayerId(r["blended"].as_u64().unwrap()); - let px = doc.layer(blended).unwrap().surface().unwrap().pixel(5, 30); - assert!((px[2] - 0.8).abs() < 0.02, "{px:?}"); - s.undo(); - assert!(s.active().unwrap().doc.layer(left).unwrap().mask.is_none()); - } - } - - /// #5745: the Background can't take a mask, so Auto-Blend turns it into a normal layer first. - #[test] - fn auto_blend_turns_the_background_into_a_layer() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 200, "height": 60, "background": "white"})).unwrap(); - let bg = s.active().unwrap().doc.background().unwrap().id; - s.execute("layer.new.layer", json!({"name": "right"})).unwrap(); - s.edit("r", |doc, active| { - doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(70, 0, 200, 60), &[0.9, 0.6, 0.2, 1.0]); - Ok(()) - }) - .unwrap(); - let right = s.active().unwrap().active_layer.unwrap(); - select(&mut s, &[bg, right]); - s.execute("edit.autoBlendLayers", json!({"method": "panorama"})).unwrap(); - let doc = &s.active().unwrap().doc; - assert!(!doc.is_background(bg), "the Background became a layer to take its mask"); - assert!(doc.layer(bg).unwrap().mask.is_some()); - s.undo(); - assert!(s.active().unwrap().doc.is_background(bg), "undo restores the Background"); - } - - /// Seamless Tones and Colors evens out a 10% exposure step between two panorama layers. - #[test] - fn auto_blend_panorama_seamless_matches_exposure() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 200, "height": 60, "background": "transparent"})).unwrap(); - let mut ids = Vec::new(); - for (name, x0, x1, gain) in [("left", 0, 130, 1.0f32), ("right", 70, 200, 1.1)] { - s.execute("layer.new.layer", json!({ "name": name })).unwrap(); - s.edit(name, |doc, active| { - doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(x0, 0, x1, 60), &[0.2 * gain, 0.4 * gain, 0.5 * gain, 1.0]); - Ok(()) - }) - .unwrap(); - ids.push(s.active().unwrap().active_layer.unwrap()); - } - select(&mut s, &ids); - let r = s.execute("edit.autoBlendLayers", json!({"method": "panorama"})).unwrap(); - let doc = &s.active().unwrap().doc; - let blended = doc.layer(LayerId(r["blended"].as_u64().unwrap())).unwrap().surface().unwrap(); - let (a, b) = (blended.pixel(10, 30), blended.pixel(190, 30)); - // 0.5 vs 0.55 without gain compensation. - assert!((a[2] - b[2]).abs() < 0.015, "{a:?} {b:?}"); - } - - /// #5745: the top layer hangs off the canvas's right edge, so cropped to the canvas it lies - /// wholly over the bottom one. It used to get an all-black mask; now it shows on its side. - #[test] - fn auto_blend_panorama_of_a_layer_the_canvas_crops_to_all_overlap() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 200, "height": 60, "background": "transparent"})).unwrap(); - s.execute("layer.new.layer", json!({"name": "left"})).unwrap(); - s.edit("l", |doc, active| { - doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(0, 0, 200, 60), &[0.2, 0.4, 0.5, 1.0]); - Ok(()) - }) - .unwrap(); - let left = s.active().unwrap().active_layer.unwrap(); - s.execute("layer.new.layer", json!({"name": "right"})).unwrap(); - s.edit("r", |doc, active| { - doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(120, 0, 320, 60), &[0.2, 0.4, 0.5, 1.0]); - Ok(()) - }) - .unwrap(); - let right = s.active().unwrap().active_layer.unwrap(); - select(&mut s, &[left, right]); - s.execute("edit.autoBlendLayers", json!({"method": "panorama", "seamlessTones": false})).unwrap(); - let doc = &s.active().unwrap().doc; - let ml = doc.layer(left).unwrap().mask.as_ref().unwrap(); - let mr = doc.layer(right).unwrap().mask.as_ref().unwrap(); - assert_eq!((ml.value(10, 30), mr.value(10, 30)), (1.0, 0.0)); - assert_eq!((ml.value(195, 30), mr.value(195, 30)), (0.0, 1.0)); - for x in 0..200 { - assert_eq!(ml.value(x, 30) + mr.value(x, 30), 1.0, "x {x} shows one layer"); - } - } - - /// #5745: a layer Auto-Align left partly off the canvas is masked and blended over all of - /// its bounds, not cut off at the canvas edge. - #[test] - fn auto_blend_panorama_masks_past_the_canvas() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 200, "height": 60, "background": "transparent"})).unwrap(); - s.execute("layer.new.layer", json!({"name": "left"})).unwrap(); - s.edit("l", |doc, active| { - doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(0, 0, 150, 60), &[0.2, 0.4, 0.5, 1.0]); - Ok(()) - }) - .unwrap(); - let left = s.active().unwrap().active_layer.unwrap(); - s.execute("layer.new.layer", json!({"name": "right"})).unwrap(); - s.edit("r", |doc, active| { - doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(120, 0, 320, 60), &[0.2, 0.4, 0.5, 1.0]); - Ok(()) - }) - .unwrap(); - let right = s.active().unwrap().active_layer.unwrap(); - select(&mut s, &[left, right]); - let r = s.execute("edit.autoBlendLayers", json!({"method": "panorama"})).unwrap(); - let doc = &s.active().unwrap().doc; - let ml = doc.layer(left).unwrap().mask.as_ref().unwrap(); - let mr = doc.layer(right).unwrap().mask.as_ref().unwrap(); - assert_eq!((ml.value(10, 30), mr.value(10, 30)), (1.0, 0.0)); - assert_eq!((ml.value(300, 30), mr.value(300, 30)), (0.0, 1.0), "off the canvas"); - let blended = doc.layer(LayerId(r["blended"].as_u64().unwrap())).unwrap().surface().unwrap(); - assert_eq!(blended.pixel(300, 30)[3], 1.0, "the merged layer covers the off-canvas part"); - } - - /// A sparse layer whose bounds are huge (a dot at each far corner) raises its own content - /// estimate, so the extent past the canvas is capped independently: it keeps to the canvas. - #[test] - fn auto_blend_sparse_huge_bounds_keep_to_the_canvas() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 200, "height": 200, "background": "transparent"})).unwrap(); - s.execute("layer.new.layer", json!({"name": "a"})).unwrap(); - s.edit("a", |doc, active| { - let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); - surf.fill_rect(Rect::new(0, 0, 150, 200), &[0.2, 0.4, 0.5, 1.0]); - surf.fill_rect(Rect::new(100_000, 100_000, 100_001, 100_001), &[0.2, 0.4, 0.5, 1.0]); - Ok(()) - }) - .unwrap(); - let a = s.active().unwrap().active_layer.unwrap(); - s.execute("layer.new.layer", json!({"name": "b"})).unwrap(); - s.edit("b", |doc, active| { - doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(50, 0, 200, 200), &[0.2, 0.4, 0.5, 1.0]); - Ok(()) - }) - .unwrap(); - let b = s.active().unwrap().active_layer.unwrap(); - select(&mut s, &[a, b]); - let r = s.execute("edit.autoBlendLayers", json!({"method": "panorama"})).unwrap(); - let doc = &s.active().unwrap().doc; - let bb = doc.layer(LayerId(r["blended"].as_u64().unwrap())).unwrap().surface().unwrap().content_bounds(); - assert!(bb.x1 <= 200 && bb.y1 <= 200, "{bb:?}"); - } - - /// The budget past the canvas counts every layer's buffers, not just the work-area pixels. - #[test] - fn auto_blend_budget_counts_layers_and_channels() { - // Two RGBA layers: 4 bytes × (2 layers × (4 channels + luma, alpha, weight) + merged + depth). - assert_eq!(blend_bytes_per_pixel(2, 4), 88); - assert!(blend_bytes_per_pixel(5, 4) > blend_bytes_per_pixel(2, 4)); - // A 2^27-pixel area would need about 11 GiB for just two RGBA layers: it keeps to the canvas. - assert!((1u64 << 27).saturating_mul(blend_bytes_per_pixel(2, 4)) > MAX_BLEND_BYTES); - assert_eq!(blend_bytes_per_pixel(u64::MAX, 4), u64::MAX, "saturates instead of overflowing"); - } - - #[test] - fn auto_blend_stack_without_seamless() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 64, "height": 64, "background": "transparent"})).unwrap(); - s.execute("layer.new.layer", json!({"name": "sharp"})).unwrap(); - s.edit("checker", |doc, active| { - let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); - for y in (0..64).step_by(2) { - for x in (0..64).step_by(2) { - let v = if (x / 2 + y / 2) % 2 == 0 { 0.1 } else { 0.9 }; - surf.fill_rect(Rect::new(x, y, x + 2, y + 2), &[v, v, v, 1.0]); - } - } - Ok(()) - }) - .unwrap(); - let a = s.active().unwrap().active_layer.unwrap(); - s.execute("layer.new.layer", json!({"name": "flat"})).unwrap(); - s.edit("flat", |doc, active| { - doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(0, 0, 64, 64), &[0.5, 0.5, 0.5, 1.0]); - Ok(()) - }) - .unwrap(); - let flat = s.active().unwrap().active_layer.unwrap(); - select(&mut s, &[a, flat]); - let r = s.execute("edit.autoBlendLayers", json!({"method": "stack", "seamlessTones": false})).unwrap(); - assert!(r["blended"].is_null()); - let doc = &s.active().unwrap().doc; - // The detailed layer is sharper everywhere. - let shown = (0..64).filter(|x| doc.layer(a).unwrap().mask.as_ref().unwrap().value(*x, 32) > 0.5).count(); - assert_eq!(shown, 64); - assert_eq!(doc.layer(flat).unwrap().mask.as_ref().unwrap().value(10, 10), 0.0); - assert!(s.execute("edit.autoBlendLayers", json!({"method": "sideways"})).is_err()); - } - - /// A smooth layer (soft blobs on a gradient) and the same picture a few pixels away: the - /// intensity registration finds the shift to a fraction of a pixel at every motion model. - fn smooth_layer(s: &mut Session, name: &str, dx: i32, dy: i32) -> LayerId { - s.execute("layer.new.layer", json!({"name": name})).unwrap(); - s.edit("smooth", |doc, active| { - let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); - for y in 0..150 { - for x in 0..200 { - let (u, v) = ((x - dx) as f32, (y - dy) as f32); - let blob = (-((u - 90.0).powi(2) + (v - 70.0).powi(2)) / (2.0 * 25.0f32.powi(2))).exp(); - let blob2 = (-((u - 150.0).powi(2) + (v - 40.0).powi(2)) / (2.0 * 15.0f32.powi(2))).exp(); - let g = 0.2 + 0.5 * blob + 0.25 * blob2 + 0.001 * u; - surf.fill_rect(Rect::new(x, y, x + 1, y + 1), &[g, g * 0.8, g * 0.6, 1.0]); - } - } - Ok(()) - }) - .unwrap(); - s.active().unwrap().active_layer.unwrap() - } - - #[test] - fn auto_align_registers_a_smooth_bracket_by_intensity() { - for depth in [8, 16, 32] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 200, "height": 150, "depth": depth, "background": "transparent"})).unwrap(); - let a = smooth_layer(&mut s, "A", 0, 0); - let b = smooth_layer(&mut s, "B", 4, 3); - select(&mut s, &[a, b]); - assert!(s.execute("edit.autoAlignLayers", json!({"registration": "sideways"})).is_err()); - assert!(s.execute("edit.autoAlignLayers", json!({"projection": "cylindrical", "registration": "intensity"})).is_err()); - for (params, model) in [ - (json!({"projection": "reposition", "registration": "intensity"}), "reposition"), - (json!({"registration": "intensity"}), "collage"), - (json!({"projection": "perspective", "registration": "intensity"}), "perspective"), - ] { - let r = s.execute("edit.autoAlignLayers", params).unwrap(); - assert_eq!(r["registration"], "intensity", "depth {depth}: {r}"); - assert_eq!(r["aligned"][0]["model"], model); - let m = r["aligned"][0]["matrix"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect::>(); - assert!((m[2] + 4.0).abs() < 0.25 && (m[5] + 3.0).abs() < 0.25, "depth {depth} {model}: {r}"); - // B now shows A's picture. - let doc = &s.active().unwrap().doc; - let (pa, pb) = (doc.layer(a).unwrap().surface().unwrap().pixel(90, 70), doc.layer(b).unwrap().surface().unwrap().pixel(90, 70)); - assert!((pa[0] - pb[0]).abs() < 0.02, "depth {depth} {model}: {pa:?} vs {pb:?}"); - s.undo(); - } - } - } - - /// Layers with nothing in common are no fit: the intensity registration says so instead of - /// moving them by whatever pose its search box ends at. - #[test] - fn auto_align_rejects_unrelated_layers_instead_of_guessing_a_pose() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 200, "height": 150, "depth": 8, "background": "transparent"})).unwrap(); - let a = smooth_layer(&mut s, "A", 0, 0); - s.execute("layer.new.layer", json!({"name": "stripes"})).unwrap(); - s.edit("stripes", |doc, active| { - let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); - for y in 0..150 { - for x in 0..200 { - let g = if (x / 7 + y / 11) % 2 == 0 { 0.9 } else { 0.1 }; - surf.fill_rect(Rect::new(x, y, x + 1, y + 1), &[g, g, g, 1.0]); - } - } - Ok(()) - }) - .unwrap(); - let b = s.active().unwrap().active_layer.unwrap(); - select(&mut s, &[a, b]); - for registration in ["intensity", "auto"] { - let err = s.execute("edit.autoAlignLayers", json!({"registration": registration})).unwrap_err().to_string(); - assert_eq!(err, NO_DETAIL, "{registration}"); - } - // A layer that is mostly empty overlaps too little to be placed. - let c = smooth_layer(&mut s, "C", 2, 1); - s.edit("hole", |doc, _| { - let surf = doc.layer_mut(c).unwrap().surface_mut().unwrap(); - surf.fill_rect(Rect::new(0, 0, 200, 120), &[0.0, 0.0, 0.0, 0.0]); - Ok(()) - }) - .unwrap(); - select(&mut s, &[a, c]); - assert_eq!(s.execute("edit.autoAlignLayers", json!({"registration": "intensity"})).unwrap_err().to_string(), NO_DETAIL); - } - - /// Two layers, each sharp on one half: the merged layer takes each half from the sharp layer. - #[test] - fn auto_blend_stack_fuses_the_sharp_halves() { - let checker = |x: i32, y: i32| if (x / 3 + y / 3) % 2 == 0 { 0.2 } else { 0.8 }; - for depth in [8, 16, 32] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 96, "height": 64, "depth": depth, "background": "transparent"})).unwrap(); - let mut ids = Vec::new(); - for (name, sharp_left) in [("left", true), ("right", false)] { - s.execute("layer.new.layer", json!({"name": name})).unwrap(); - s.edit(name, |doc, active| { - let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); - for y in 0..64 { - for x in 0..96 { - // The sharp half is the checker, the other half its local mean (flat gray). - let v = if (x < 48) == sharp_left { checker(x, y) } else { 0.5 }; - surf.fill_rect(Rect::new(x, y, x + 1, y + 1), &[v, v, v, 1.0]); - } - } - Ok(()) - }) - .unwrap(); - ids.push(s.active().unwrap().active_layer.unwrap()); - } - select(&mut s, &ids); - for halo in [0.0, 2.0] { - let r = s.execute("edit.autoBlendLayers", json!({"method": "stack", "haloControl": halo})).unwrap(); - let doc = &s.active().unwrap().doc; - let blended = doc.layer(LayerId(r["blended"].as_u64().unwrap())).unwrap().surface().unwrap(); - for (x, y) in [(10, 20), (20, 40), (76, 20), (85, 40)] { - let px = blended.pixel(x, y); - assert!((px[0] - checker(x, y)).abs() < 0.08, "depth {depth} halo {halo} ({x},{y}): {px:?}"); - assert!((px[3] - 1.0).abs() < 1e-3, "{px:?}"); - } - // The masks still pick per pixel. - assert_eq!(doc.layer(ids[0]).unwrap().mask.as_ref().unwrap().value(10, 20), 1.0); - assert_eq!(doc.layer(ids[1]).unwrap().mask.as_ref().unwrap().value(85, 40), 1.0); - s.undo(); - assert!(s.active().unwrap().doc.layer(ids[0]).unwrap().mask.is_none()); - } - for bad in [json!(-1), json!(9), json!("hard")] { - assert!(s.execute("edit.autoBlendLayers", json!({"method": "stack", "haloControl": bad})).is_err(), "{bad}"); - } - } - } - - /// Three layers, each sharp in one third: the Depth layer says which, black to white from - /// the bottom layer to the top, hidden, and undone with the rest. - #[test] - fn auto_blend_stack_depth_map() { - for depth in [8, 16, 32] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 96, "height": 48, "depth": depth, "background": "transparent"})).unwrap(); - let mut ids = Vec::new(); - for k in 0..3 { - s.execute("layer.new.layer", json!({"name": format!("L{k}")})).unwrap(); - s.edit("third", |doc, active| { - let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); - for y in 0..48 { - for x in 0..96 { - let v = if x / 32 == k && ((x / 2) + (y / 2)) % 2 == 0 { - 0.2 - } else if x / 32 == k { - 0.8 - } else { - 0.5 - }; - surf.fill_rect(Rect::new(x, y, x + 1, y + 1), &[v, v, v, 1.0]); - } - } - Ok(()) - }) - .unwrap(); - ids.push(s.active().unwrap().active_layer.unwrap()); - } - select(&mut s, &ids); - assert!(s.execute("edit.autoBlendLayers", json!({"method": "panorama", "depthMap": true})).is_err()); - for seamless in [false, true] { - let r = s.execute("edit.autoBlendLayers", json!({"method": "stack", "seamlessTones": seamless, "depthMap": true})).unwrap(); - let doc = &s.active().unwrap().doc; - let d = doc.layer(LayerId(r["depth"].as_u64().unwrap())).unwrap(); - assert!(!d.visible && d.name.starts_with("Depth"), "depth {depth}: {} visible {} {r}", d.name, d.visible); - let surf = d.surface().unwrap(); - for (x, want) in [(8, 0.0), (48, 0.5), (88, 1.0)] { - let px = surf.pixel(x, 24); - assert!((px[0] - want).abs() < 0.2 && (px[3] - 1.0).abs() < 1e-3, "depth {depth} seamless {seamless} x {x}: {px:?}"); - } - assert_eq!(r["blended"].is_null(), !seamless); - if seamless { - // The merged layer sits above the depth layer and is the active one. - assert_eq!(s.active().unwrap().active_layer, Some(LayerId(r["blended"].as_u64().unwrap()))); - } - s.undo(); - assert!(s.active().unwrap().doc.layer(LayerId(r["depth"].as_u64().unwrap())).is_none()); - } - } - } -} diff --git a/crates/engine/src/atn_cmds.rs b/crates/engine/src/atn_cmds.rs deleted file mode 100644 index 244c21479a..0000000000 --- a/crates/engine/src/atn_cmds.rs +++ /dev/null @@ -1,4302 +0,0 @@ -//! Photoshop Actions files (`.atn`): Load Actions (`actions.load`) and Save Actions -//! (`actions.save`), plus the two step commands a Photoshop set needs: `actions.stopMessage` -//! (Photoshop's Insert Stop) and `actions.photoshopStep` (a step PhotoCraft has no command for -//! yet, kept verbatim so Save Actions writes it back unchanged). -//! -//! Parsing and writing live in `photocraft-psd` (`atn`); this module maps Photoshop *events* -//! (`gaussianBlur` with `Rds`, `make` of an adjustment layer, `set` of the selection…) onto -//! PhotoCraft commands and back. An event is keyed by both its four-character code (`GsnB`, -//! older files) and its string name (`gaussianBlur`, Photoshop 2024 and later), as the two are -//! interchangeable in Photoshop. The table ([`EVENTS`]) is bidirectional: a step that was -//! imported exports to the same event. Events outside it become `actions.photoshopStep` steps, -//! which fail at playback with the step's Photoshop name, so an action never silently skips -//! work; tool selections and other steps with no document effect are imported switched off. -//! -//! Layer references by name (`select` of layer "Shadow") become `{"layer": "Shadow"}`, which -//! `commands::layer_param` resolves in whatever document the action plays on (#219). A switch -//! to another open document (`select` of `Dcmn` by offset) becomes `document.activate -//! {"offset"}`, the tab that many places from the active one (#7103). - -use photocraft_psd::atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}; -use photocraft_psd::descriptor::{Class, Descriptor, Id, ReferenceItem, UnicodeString, Value as D}; -use serde_json::{Map, Value, json}; - -use crate::actions_cmds::Action; -use crate::commands::CommandSpec; -use crate::{EngineError, Result, Session}; - -/// A step PhotoCraft cannot play yet, kept verbatim (`{"event", "name", "descriptor": base64}`). -pub const PHOTOSHOP_STEP: &str = "actions.photoshopStep"; -/// Photoshop's Insert Stop: `{"message", "allowContinue"}`. -pub const STOP_MESSAGE: &str = "actions.stopMessage"; -/// The set name Save Actions uses for actions that came from no set. -pub const DEFAULT_SET: &str = "PhotoCraft Actions"; - -fn bad(cmd: &str, msg: impl Into) -> EngineError { - EngineError::BadParams { cmd: cmd.into(), msg: msg.into() } -} - -fn always(_: &Session) -> std::result::Result<(), String> { - Ok(()) -} - -// ------------------------------------------------------------------ descriptor access - -fn num(v: &D) -> Option { - match v { - D::Integer(i) => Some(f64::from(*i)), - D::LargeInteger(i) => Some(*i as f64), - D::Double(d) | D::UnitFloat { value: d, .. } => Some(*d), - _ => None, - } - .filter(|f| f.is_finite()) -} - -fn trimmed(id: &Id) -> String { - String::from_utf8_lossy(id.as_bytes()).trim_end().to_string() -} - -fn get_num(d: &Descriptor, k: &str) -> Option { - d.get(k).and_then(num) -} - -fn get_bool(d: &Descriptor, k: &str) -> Option { - match d.get(k) { - Some(D::Boolean(b)) => Some(*b), - _ => None, - } -} - -fn get_text(d: &Descriptor, k: &str) -> Option { - match d.get(k) { - Some(D::Text(t)) => Some(t.to_string_lossy()), - _ => None, - } -} - -/// An enumerated value's id, trailing spaces removed (`Ordn.Trgt` → `"Trgt"`). -fn get_enum(d: &Descriptor, k: &str) -> Option { - match d.get(k) { - Some(D::Enumerated { value, .. }) => Some(trimmed(value)), - _ => None, - } -} - -fn get_obj<'a>(d: &'a Descriptor, k: &str) -> Option<&'a Descriptor> { - match d.get(k) { - Some(D::Descriptor(o) | D::GlobalObject(o)) => Some(o), - _ => None, - } -} - -fn get_list<'a>(d: &'a Descriptor, k: &str) -> Option<&'a [D]> { - match d.get(k) { - Some(D::List(l)) => Some(l), - _ => None, - } -} - -fn get_ref<'a>(d: &'a Descriptor, k: &str) -> Option<&'a [ReferenceItem]> { - match d.get(k) { - Some(D::Reference(r)) => Some(r), - _ => None, - } -} - -/// The class of a reference's first item, trimmed (`Lyr`, `Chnl`, `AdjL`…). -fn ref_class(r: &[ReferenceItem]) -> Option { - Some(trimmed(match r.first()? { - ReferenceItem::Property { class, .. } - | ReferenceItem::Class(class) - | ReferenceItem::Enumerated { class, .. } - | ReferenceItem::Offset { class, .. } - | ReferenceItem::Identifier { class, .. } - | ReferenceItem::Index { class, .. } - | ReferenceItem::Name { class, .. } => &class.class_id, - })) -} - -/// How a reference names its target: the ordinal (`Trgt`, `Frnt`…), a name, a property… -enum Target { - Ordinal(String), - Name(String), - Property(String), - Class, - Offset(i32), - Index(u32), - Other, -} - -fn target(r: &[ReferenceItem]) -> Target { - match r.first() { - Some(ReferenceItem::Enumerated { value, .. }) => Target::Ordinal(trimmed(value)), - Some(ReferenceItem::Name { name, .. }) => Target::Name(name.to_string_lossy()), - Some(ReferenceItem::Property { key, .. }) => Target::Property(trimmed(key)), - Some(ReferenceItem::Class(_)) => Target::Class, - Some(ReferenceItem::Offset { offset, .. }) => Target::Offset(*offset), - Some(ReferenceItem::Index { index, .. }) => Target::Index(*index), - _ => Target::Other, - } -} - -/// `{"layer": name}` for a reference that names a layer, `{}` for the target layer, `None` -/// for anything else (an index or id: meaningless in another document). -fn layer_target(r: &[ReferenceItem]) -> Option> { - let mut m = Map::new(); - match target(r) { - Target::Ordinal(o) if o == "Trgt" => {} - Target::Name(n) => { - m.insert("layer".into(), json!(n)); - } - Target::Property(p) if p == "Bckg" => { - m.insert("layer".into(), json!("Background")); - } - _ => return None, - } - Some(m) -} - -// ------------------------------------------------------------------ descriptor building - -/// A Photoshop id: codes shorter than four characters are space-padded (`H `, `Rd `), -/// longer names stay strings. -fn code(s: &str) -> Id { - if s.len() < 4 { Id::new(&format!("{s:<4}")) } else { Id::new(s) } -} - -fn class(c: &str) -> Class { - Class { name: UnicodeString::new_nul(""), class_id: code(c) } -} - -/// The pixel and percent units of a `UntF` value. -const PX: [u8; 4] = *b"#Pxl"; -const PCT: [u8; 4] = *b"#Prc"; -/// Points (1/72 in): what Photoshop calls "relative" units. -const PT: [u8; 4] = *b"#Rlt"; - -fn px(v: f64) -> D { - D::UnitFloat { unit: PX, value: v } -} - -fn pct(v: f64) -> D { - D::UnitFloat { unit: *b"#Prc", value: v } -} - -fn ang(v: f64) -> D { - D::UnitFloat { unit: *b"#Ang", value: v } -} - -fn long(v: f64) -> D { - D::Integer(v.round().clamp(f64::from(i32::MIN), f64::from(i32::MAX)) as i32) -} - -fn text(s: &str) -> D { - D::Text(UnicodeString::new_nul(s)) -} - -fn enm(ty: &str, v: &str) -> D { - D::Enumerated { type_id: code(ty), value: code(v) } -} - -fn target_ref(cls: &str) -> D { - D::Reference(vec![ReferenceItem::Enumerated { class: class(cls), type_id: Id::new("Ordn"), value: Id::new("Trgt") }]) -} - -fn name_ref(cls: &str, name: &str) -> D { - D::Reference(vec![ReferenceItem::Name { class: class(cls), name: UnicodeString::new_nul(name) }]) -} - -fn class_ref(cls: &str) -> D { - D::Reference(vec![ReferenceItem::Class(class(cls))]) -} - -/// The `null` reference for a command's `layer` param: by name, else the target layer. -fn layer_ref(p: &Value) -> Option { - match p.get("layer") { - None | Some(Value::Null) => Some(target_ref("Lyr ")), - Some(Value::String(n)) => Some(name_ref("Lyr ", n)), - _ => None, - } -} - -fn desc(cls: &str) -> Descriptor { - Descriptor::new(cls) -} - -// ------------------------------------------------------------------ JSON access - -fn jnum(p: &Value, k: &str) -> Option { - p.get(k).and_then(Value::as_f64).filter(|f| f.is_finite()) -} - -fn jbool(p: &Value, k: &str) -> Option { - p.get(k).and_then(Value::as_bool) -} - -fn jstr<'a>(p: &'a Value, k: &str) -> Option<&'a str> { - p.get(k).and_then(Value::as_str) -} - -// ------------------------------------------------------------------ colours and enums - -/// A Photoshop colour object as `#rrggbb`: `RGBC` (0..255), `HSBC`, `Grsc`. -fn color_hex(c: &Descriptor) -> Option { - let hex = |r: f64, g: f64, b: f64| { - format!("#{:02x}{:02x}{:02x}", r.round().clamp(0.0, 255.0) as u8, g.round().clamp(0.0, 255.0) as u8, b.round().clamp(0.0, 255.0) as u8) - }; - if let (Some(r), Some(g), Some(b)) = (get_num(c, "Rd "), get_num(c, "Grn "), get_num(c, "Bl ")) { - return Some(hex(r, g, b)); - } - if let (Some(h), Some(s), Some(v)) = (get_num(c, "H "), get_num(c, "Strt"), get_num(c, "Brgh")) { - let (s, v) = ((s / 100.0).clamp(0.0, 1.0), (v / 100.0).clamp(0.0, 1.0)); - let h = h.rem_euclid(360.0) / 60.0; - let i = h.floor(); - let f = h - i; - let (p, q, t) = (v * (1.0 - s), v * (1.0 - s * f), v * (1.0 - s * (1.0 - f))); - let (r, g, b) = match i as i32 { - 0 => (v, t, p), - 1 => (q, v, p), - 2 => (p, v, t), - 3 => (p, q, v), - 4 => (t, p, v), - _ => (v, p, q), - }; - return Some(hex(r * 255.0, g * 255.0, b * 255.0)); - } - get_num(c, "Gry ").map(|g| { - let v = 255.0 - g * 2.55; - hex(v, v, v) - }) -} - -fn color_desc(hex: &str) -> Option { - let h = hex.strip_prefix('#')?; - if h.len() != 6 || !h.is_ascii() { - return None; - } - let ch = |i: usize| u8::from_str_radix(h.get(i..i + 2)?, 16).ok().map(f64::from); - Some(desc("RGBC").with("Rd ", D::Double(ch(0)?)).with("Grn ", D::Double(ch(2)?)).with("Bl ", D::Double(ch(4)?))) -} - -/// A `Pth ` value's text: Photoshop stores `"txtu"`, a little-endian total length, a -/// little-endian UTF-16 unit count and the units (NUL-terminated). -fn path_text(v: &D) -> Option { - let D::Path(b) = v else { return None }; - if b.get(0..4)? != b"txtu" { - return None; - } - let n = u32::from_le_bytes(b.get(8..12)?.try_into().ok()?) as usize; - let units: Vec = b.get(12..12usize.checked_add(n.checked_mul(2)?)?)?.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).collect(); - let text = String::from_utf16_lossy(&units); - let text = text.trim_end_matches('\0'); - (!text.is_empty()).then(|| text.to_string()) -} - -fn path_value(text: &str) -> D { - let units: Vec = text.encode_utf16().chain(std::iter::once(0)).collect(); - let mut b = b"txtu".to_vec(); - b.extend_from_slice(&((12 + units.len() * 2) as u32).to_le_bytes()); - b.extend_from_slice(&(units.len() as u32).to_le_bytes()); - for u in units { - b.extend_from_slice(&u.to_le_bytes()); - } - D::Path(b) -} - -/// Photoshop's `BlnM` enumeration ↔ PhotoCraft's blend mode labels. -const BLEND_MODES: &[(&str, &str)] = &[ - ("Nrml", "Normal"), - ("normal", "Normal"), - ("Dslv", "Dissolve"), - ("dissolve", "Dissolve"), - ("Drkn", "Darken"), - ("darken", "Darken"), - ("Mltp", "Multiply"), - ("multiply", "Multiply"), - ("CBrn", "Color Burn"), - ("colorBurn", "Color Burn"), - ("linearBurn", "Linear Burn"), - ("darkerColor", "Darker Color"), - ("Lghn", "Lighten"), - ("lighten", "Lighten"), - ("Scrn", "Screen"), - ("screen", "Screen"), - ("CDdg", "Color Dodge"), - ("colorDodge", "Color Dodge"), - ("linearDodge", "Linear Dodge (Add)"), - ("lighterColor", "Lighter Color"), - ("Ovrl", "Overlay"), - ("overlay", "Overlay"), - ("SftL", "Soft Light"), - ("softLight", "Soft Light"), - ("HrdL", "Hard Light"), - ("hardLight", "Hard Light"), - ("vividLight", "Vivid Light"), - ("linearLight", "Linear Light"), - ("pinLight", "Pin Light"), - ("hardMix", "Hard Mix"), - ("Dfrn", "Difference"), - ("difference", "Difference"), - ("Xclu", "Exclusion"), - ("exclusion", "Exclusion"), - ("blendSubtraction", "Subtract"), - ("blendDivide", "Divide"), - ("H", "Hue"), - ("hue", "Hue"), - ("Strt", "Saturation"), - ("saturation", "Saturation"), - ("Clr", "Color"), - ("color", "Color"), - ("Lmns", "Luminosity"), - ("luminosity", "Luminosity"), - ("PsTh", "Pass Through"), - ("passThrough", "Pass Through"), -]; - -fn blend_label(ps: &str) -> Option<&'static str> { - BLEND_MODES.iter().find(|(k, _)| *k == ps).map(|(_, v)| *v) -} - -fn blend_ps(label: &str) -> Option<&'static str> { - crate::commands::blend_from_str(label).and_then(|m| BLEND_MODES.iter().find(|(_, v)| crate::commands::blend_from_str(v) == Some(m))).map(|(k, _)| *k) -} - -/// Photoshop ↔ PhotoCraft value tables; Photoshop codes compare without their space padding. -fn lookup<'a>(table: &'a [(&'a str, &'a str)], key: &str) -> Option<&'a str> { - table.iter().find(|(k, _)| k.trim_end() == key.trim_end()).map(|(_, v)| *v) -} - -fn lookup_back<'a>(table: &'a [(&'a str, &'a str)], value: &str) -> Option<&'a str> { - table.iter().find(|(_, v)| *v == value).map(|(k, _)| *k) -} - -/// `Chnl` enumeration ↔ the per-channel keys of the adjustment commands. -const CHANNELS: &[(&str, &str)] = &[ - ("Rd", "red"), - ("Grn", "green"), - ("Bl", "blue"), - ("Gry", "gray"), - ("Cyn", "cyan"), - ("Mgnt", "magenta"), - ("Yllw", "yellow"), - ("Blck", "black"), - ("Lmnc", "lightness"), - ("A", "a"), - ("B", "b"), -]; - -/// The channel an adjustment entry's `Chnl` reference names: `None` = the composite. -fn channel_key(d: &Descriptor) -> Option> { - let r = get_ref(d, "Chnl")?; - Some(match target(r) { - Target::Ordinal(o) if o == "Trgt" || o == "Cmps" => None, - Target::Ordinal(o) => Some(lookup(CHANNELS, &o)?), - _ => return None, - }) -} - -/// A Levels or Curves entry's channel: `Chnl.Cmps` for the composite, as Photoshop records it. -/// Photoshop silently skips a Set whose composite is `Ordn.Trgt` (#8543). -fn channel_ref(key: Option<&str>) -> D { - let value = key.and_then(|k| lookup_back(CHANNELS, k)); - D::Reference(vec![ReferenceItem::Enumerated { class: class("Chnl"), type_id: code("Chnl"), value: code(value.unwrap_or("Cmps")) }]) -} - -// ------------------------------------------------------------------ field tables - -#[derive(Clone, Copy)] -enum Kind { - Px, - Pct, - Ang, - Long, - /// An integer field whose value must survive conversion without rounding or saturation. - ExactLong, - Dbl, - Bool, - /// An enumeration: its type id and the Photoshop ↔ PhotoCraft value pairs. - Enum(&'static str, &'static [(&'static str, &'static str)]), - /// A blend mode (`BlnM`). - Blend, - /// A colour object ↔ `#rrggbb`. - Color, -} - -/// One descriptor key ↔ one command param. -struct F(&'static str, &'static str, Kind); - -/// Import mapped descriptor fields, leaving absent values to command defaults. -/// Return `None` when a present enum, blend mode or colour cannot be represented. -fn fields_from(d: &Descriptor, fields: &[F]) -> Option> { - let mut m = Map::new(); - for F(key, param, kind) in fields { - let v = match kind { - Kind::Px | Kind::Pct | Kind::Ang | Kind::Long | Kind::ExactLong | Kind::Dbl => get_num(d, key).map(Value::from), - Kind::Bool => get_bool(d, key).map(Value::from), - Kind::Enum(_, table) => match get_enum(d, key) { - Some(e) => Some(Value::from(lookup(table, &e)?)), - None => None, - }, - Kind::Blend => match get_enum(d, key) { - Some(e) => Some(Value::from(blend_label(&e)?)), - None => None, - }, - Kind::Color => match get_obj(d, key) { - Some(c) => Some(Value::from(color_hex(c)?)), - None => None, - }, - }; - if let Some(v) = v { - m.insert((*param).into(), v); - } - } - Some(m) -} - -/// Export supplied mapped params, omitting absent values to preserve event defaults. -/// Return `None` for unsupported values; `ExactLong` also rejects rounding or saturation. -fn fields_to(p: &Value, fields: &[F], mut d: Descriptor) -> Option { - for F(key, param, kind) in fields { - let Some(v) = p.get(param) else { continue }; - let out = match kind { - Kind::Px => px(v.as_f64()?), - Kind::Pct => pct(v.as_f64()?), - Kind::Ang => ang(v.as_f64()?), - // A value outside the descriptor's 32-bit integer refuses the step rather than being - // clamped to another value (an Add Noise seed above i32::MAX replayed as i32::MAX, #7287). - Kind::Long => { - let n = v.as_f64()?.round(); - if !(f64::from(i32::MIN)..=f64::from(i32::MAX)).contains(&n) { - return None; - } - long(n) - } - Kind::ExactLong => { - let number = v.as_f64()?; - let integer = number as i32; - if f64::from(integer) != number { - return None; - } - D::Integer(integer) - } - Kind::Dbl => D::Double(v.as_f64()?), - Kind::Bool => D::Boolean(v.as_bool()?), - Kind::Enum(ty, table) => enm(ty, lookup_back(table, v.as_str()?)?), - Kind::Blend => enm("BlnM", blend_ps(v.as_str()?)?), - Kind::Color => D::Descriptor(color_desc(v.as_str()?)?), - }; - d = d.with(key, out); - } - Some(d) -} - -// ------------------------------------------------------------------ adjustments - -/// The `Adjs` entries of a per-channel adjustment (Levels, Curves): `(channel key, entry)`. -fn per_channel(d: &Descriptor) -> Option, &Descriptor)>> { - get_list(d, "Adjs")? - .iter() - .map(|v| match v { - D::Descriptor(e) => Some((channel_key(e)?, e)), - _ => None, - }) - .collect() -} - -fn levels_from(d: &Descriptor) -> Option { - if get_bool(d, "Auto") == Some(true) { - return None; - } - let mut out = Map::new(); - for (chan, e) in per_channel(d)? { - let mut m = Map::new(); - if let Some(i) = get_list(e, "Inpt") { - if let Some(v) = i.first().and_then(num) { - m.insert("inBlack".into(), v.into()); - } - if let Some(v) = i.get(1).and_then(num) { - m.insert("inWhite".into(), v.into()); - } - } - if let Some(o) = get_list(e, "Otpt") { - if let Some(v) = o.first().and_then(num) { - m.insert("outBlack".into(), v.into()); - } - if let Some(v) = o.get(1).and_then(num) { - m.insert("outWhite".into(), v.into()); - } - } - if let Some(g) = get_num(e, "Gmm ") { - m.insert("gamma".into(), g.into()); - } - match chan { - None => out.extend(m), - Some(k) => { - out.insert(k.into(), Value::Object(m)); - } - } - } - Some(Value::Object(out)) -} - -fn levels_entry(chan: Option<&str>, p: &Value) -> Descriptor { - let mut e = desc("LvlA").with("Chnl", channel_ref(chan)); - if jnum(p, "inBlack").is_some() || jnum(p, "inWhite").is_some() { - e = e.with("Inpt", D::List(vec![long(jnum(p, "inBlack").unwrap_or(0.0)), long(jnum(p, "inWhite").unwrap_or(255.0))])); - } - if let Some(g) = jnum(p, "gamma") { - e = e.with("Gmm ", D::Double(g)); - } - if jnum(p, "outBlack").is_some() || jnum(p, "outWhite").is_some() { - e = e.with("Otpt", D::List(vec![long(jnum(p, "outBlack").unwrap_or(0.0)), long(jnum(p, "outWhite").unwrap_or(255.0))])); - } - e -} - -fn levels_to(p: &Value) -> Option { - let mut entries = vec![D::Descriptor(levels_entry(None, p))]; - for (_, k) in CHANNELS { - if let Some(c) = p.get(*k).filter(|v| v.is_object()) { - entries.push(D::Descriptor(levels_entry(Some(k), c))); - } - } - Some(desc("Lvls").with("presetKind", enm("presetKindType", "presetKindCustom")).with("Adjs", D::List(entries))) -} - -fn curve_points(e: &Descriptor) -> Option { - let pts: Option> = get_list(e, "Crv ")? - .iter() - .map(|v| match v { - D::Descriptor(pt) => Some(json!([get_num(pt, "Hrzn")?, get_num(pt, "Vrtc")?])), - _ => None, - }) - .collect(); - pts.map(Value::Array) -} - -fn curves_from(d: &Descriptor) -> Option { - let mut out = Map::new(); - for (chan, e) in per_channel(d)? { - let pts = curve_points(e)?; - out.insert(chan.unwrap_or("points").into(), pts); - } - Some(Value::Object(out)) -} - -fn curve_entry(chan: Option<&str>, pts: &Value) -> Option { - let list: Option> = pts - .as_array()? - .iter() - .map(|pt| { - let a = pt.as_array()?; - Some(D::Descriptor(desc("Pnt ").with("Hrzn", D::Double(a.first()?.as_f64()?)).with("Vrtc", D::Double(a.get(1)?.as_f64()?)))) - }) - .collect(); - Some(desc("CrvA").with("Chnl", channel_ref(chan)).with("Crv ", D::List(list?))) -} - -fn curves_to(p: &Value) -> Option { - let mut entries = Vec::new(); - if let Some(pts) = p.get("points") { - entries.push(D::Descriptor(curve_entry(None, pts)?)); - } - for (_, k) in CHANNELS { - if let Some(pts) = p.get(*k) { - entries.push(D::Descriptor(curve_entry(Some(k), pts)?)); - } - } - Some(desc("Crvs").with("presetKind", enm("presetKindType", "presetKindCustom")).with("Adjs", D::List(entries))) -} - -/// The hue key of a Hue/Saturation adjustment (`Hst2`): Photoshop's `H ` (#8302). -const HUE_KEY: &str = "H "; - -const HUE_RANGES: [&str; 6] = ["reds", "yellows", "greens", "cyans", "blues", "magentas"]; - -fn hue_sat_from(d: &Descriptor) -> Option { - let mut out = Map::new(); - if let Some(c) = get_bool(d, "Clrz") { - out.insert("colorize".into(), c.into()); - } - for e in get_list(d, "Adjs").unwrap_or(&[]) { - let D::Descriptor(e) = e else { return None }; - let mut m = Map::new(); - // Photoshop's hue key is `H ` (stringID "hue", #8302); PhotoCraft wrote `Hue ` before, - // so its own older files still read. - let hue = get_num(e, HUE_KEY).or_else(|| get_num(e, "Hue ")); - for (param, v) in [("hue", hue), ("saturation", get_num(e, "Strt")), ("lightness", get_num(e, "Lght"))] { - if let Some(v) = v { - m.insert(param.into(), v.into()); - } - } - match get_num(e, "LclR") { - None => out.extend(m), - Some(r) => { - let name = *HUE_RANGES.get((r as usize).checked_sub(1)?)?; - if let (Some(a), Some(b), Some(c), Some(dd)) = (get_num(e, "BgnR"), get_num(e, "BgnS"), get_num(e, "EndS"), get_num(e, "EndR")) { - m.insert("range".into(), json!([a, b, c, dd])); - } - out.insert(name.into(), Value::Object(m)); - } - } - } - Some(Value::Object(out)) -} - -fn hue_entry(p: &Value, range: Option<(usize, &Value)>) -> Option { - let mut e = desc("Hst2"); - if let Some((i, r)) = range { - e = e.with("LclR", long(i as f64 + 1.0)); - if let Some(a) = r.get("range").and_then(Value::as_array) - && a.len() == 4 - { - for (k, v) in ["BgnR", "BgnS", "EndS", "EndR"].iter().zip(a) { - e = e.with(k, long(v.as_f64()?)); - } - } - } - for (key, param) in [(HUE_KEY, "hue"), ("Strt", "saturation"), ("Lght", "lightness")] { - e = e.with(key, long(jnum(p, param).unwrap_or(0.0))); - } - Some(e) -} - -// Exporters leave out a param the step doesn't set only where Photoshop plays the missing key -// as PhotoCraft's default (checked against Photoshop: Fill opacity and mode, Crop delete, -// Selective Color method, Channel Mixer monochrome, Paint Bucket contiguous; Gradient Map -// reverse and dither, which Photoshop itself leaves out when off). Elsewhere they -// write PhotoCraft's default, as Photoshop plays a missing key differently (Color Balance -// preserve luminosity off, Canvas Size anchored top left, Apply Image Normal) or refuses the -// step (Paint Bucket without a tolerance). -fn hue_sat_to(p: &Value) -> Option { - let d = desc("HStr").with("presetKind", enm("presetKindType", "presetKindCustom")).with("Clrz", D::Boolean(jbool(p, "colorize").unwrap_or(false))); - let mut entries = vec![D::Descriptor(hue_entry(p, None)?)]; - for (i, name) in HUE_RANGES.iter().enumerate() { - if let Some(r) = p.get(*name).filter(|v| v.is_object()) { - entries.push(D::Descriptor(hue_entry(r, Some((i, r)))?)); - } - } - Some(d.with("Adjs", D::List(entries))) -} - -fn triple(d: &Descriptor, k: &str) -> Option { - let l = get_list(d, k)?; - let v: Option> = l.iter().map(num).collect(); - Some(json!(v?)) -} - -fn triple_to(p: &Value, k: &str) -> Option { - Some(D::List(p.get(k)?.as_array()?.iter().map(|v| v.as_f64().map(long)).collect::>>()?)) -} - -fn color_balance_from(d: &Descriptor) -> Option { - let mut out = Map::new(); - for (key, param) in [("ShdL", "shadows"), ("MdtL", "midtones"), ("HghL", "highlights")] { - if let Some(v) = triple(d, key) { - out.insert(param.into(), v); - } - } - if let Some(b) = get_bool(d, "PrsL") { - out.insert("preserveLuminosity".into(), b.into()); - } - Some(Value::Object(out)) -} - -fn color_balance_to(p: &Value) -> Option { - let mut d = desc("ClrB"); - for (key, param) in [("ShdL", "shadows"), ("MdtL", "midtones"), ("HghL", "highlights")] { - d = d.with(key, triple_to(p, param).unwrap_or_else(|| D::List(vec![long(0.0), long(0.0), long(0.0)]))); - } - Some(d.with("PrsL", D::Boolean(jbool(p, "preserveLuminosity").unwrap_or(true)))) -} - -const BW: &[F] = &[ - F("Rd ", "reds", Kind::Long), - F("Yllw", "yellows", Kind::Long), - F("Grn ", "greens", Kind::Long), - F("Cyn ", "cyans", Kind::Long), - F("Bl ", "blues", Kind::Long), - F("Mgnt", "magentas", Kind::Long), - F("useTint", "tint", Kind::Bool), - F("tintColor", "tintColor", Kind::Color), -]; - -fn mixer_channel(e: &Descriptor) -> Option { - Some(json!([get_num(e, "Rd ").unwrap_or(0.0), get_num(e, "Grn ").unwrap_or(0.0), get_num(e, "Bl ").unwrap_or(0.0), get_num(e, "Cnst").unwrap_or(0.0)])) -} - -fn channel_mixer_from(d: &Descriptor) -> Option { - let mut out = Map::new(); - for (key, param) in [("Rd ", "red"), ("Grn ", "green"), ("Bl ", "blue"), ("Gry ", "gray")] { - if let Some(e) = get_obj(d, key) { - out.insert(param.into(), mixer_channel(e)?); - } - } - if let Some(m) = get_bool(d, "Mnch") { - out.insert("monochrome".into(), m.into()); - } - Some(Value::Object(out)) -} - -fn channel_mixer_to(p: &Value) -> Option { - let mut d = desc("ChnM").with("presetKind", enm("presetKindType", "presetKindCustom")); - for (key, param) in [("Rd ", "red"), ("Grn ", "green"), ("Bl ", "blue"), ("Gry ", "gray")] { - if let Some(a) = p.get(param).and_then(Value::as_array) { - let v = |i: usize| a.get(i).and_then(Value::as_f64).unwrap_or(0.0); - d = d.with(key, D::Descriptor(desc("ChMx").with("Rd ", pct(v(0))).with("Grn ", pct(v(1))).with("Bl ", pct(v(2))).with("Cnst", pct(v(3))))); - } - } - if let Some(m) = jbool(p, "monochrome") { - d = d.with("Mnch", D::Boolean(m)); - } - Some(d) -} - -/// Photoshop's `Clrs` colour-range enumeration. Yellows is `Ylws` (`Yllw` is the yellow ink -/// key); earlier PhotoCraft builds wrote `Yllw`, which import still reads (#6745). -const SELECTIVE_RANGES: &[(&str, &str)] = &[ - ("Rds", "reds"), - ("Ylws", "yellows"), - ("Grns", "greens"), - ("Cyns", "cyans"), - ("Bls", "blues"), - ("Mgnt", "magentas"), - ("Whts", "whites"), - ("Ntrl", "neutrals"), - ("Blks", "blacks"), -]; - -fn selective_from(d: &Descriptor) -> Option { - let mut out = Map::new(); - if let Some(m) = get_enum(d, "Mthd") { - out.insert("method".into(), (if m == "Absl" { "absolute" } else { "relative" }).into()); - } - for e in get_list(d, "ClrC").unwrap_or(&[]) { - let D::Descriptor(e) = e else { return None }; - let range = get_enum(e, "Clrs")?; - let name = lookup(SELECTIVE_RANGES, if range == "Yllw" { "Ylws" } else { &range })?; - let v = |k: &str| get_num(e, k).unwrap_or(0.0); - out.insert(name.into(), json!([v("Cyn "), v("Mgnt"), v("Yllw"), v("Blck")])); - } - Some(Value::Object(out)) -} - -fn selective_to(p: &Value) -> Option { - // Match command execution: scalar components override only the selected range, `relative` - // takes precedence over `method`, and invalid values must not become a different edit. - let photocraft_doc::Adjustment::SelectiveColor { relative, adjustments } = crate::adjust_cmds::selective_from_params(p, None).ok()? else { - return None; - }; - let mut list = Vec::new(); - for (name, row) in crate::adjust_cmds::RANGES.into_iter().zip(adjustments) { - if p.get(name).is_some_and(|v| !v.is_null()) || jstr(p, "colors") == Some(name) { - let ps = lookup_back(SELECTIVE_RANGES, name)?; - let [cyan, magenta, yellow, black] = row.map(f64::from); - list.push(D::Descriptor( - desc("ClrC") - .with("Clrs", enm("Clrs", ps)) - .with("Cyn ", pct(cyan)) - .with("Mgnt", pct(magenta)) - .with("Yllw", pct(yellow)) - .with("Blck", pct(black)), - )); - } - } - Some( - desc("SlcC") - .with("presetKind", enm("presetKindType", "presetKindCustom")) - .with("Mthd", enm("CrcM", if relative { "Rltv" } else { "Absl" })) - .with("ClrC", D::List(list)), - ) -} - -/// Gradient Map: the gradient's colour stops at 0..4096 → `stops: [[0..1, "#rrggbb"], …]`. -fn gradient_map_from(d: &Descriptor) -> Option { - let grad = get_obj(d, "Grad")?; - let stops: Option> = get_list(grad, "Clrs")? - .iter() - .map(|v| match v { - D::Descriptor(stop) => Some(json!([(get_num(stop, "Lctn")? / 4096.0).clamp(0.0, 1.0), color_hex(get_obj(stop, "Clr ")?)?])), - _ => None, - }) - .collect(); - let mut out = json!({"stops": stops?}); - if let Some(r) = get_bool(d, "Rvrs") { - out["reverse"] = json!(r); - } - if let Some(dd) = get_bool(d, "Dthr") { - out["dither"] = json!(dd); - } - Some(out) -} - -fn gradient_map_to(p: &Value) -> Option { - let stops: Option> = p - .get("stops")? - .as_array()? - .iter() - .map(|st| { - let a = st.as_array()?; - Some(D::Descriptor( - desc("Clrt") - .with("Clr ", D::Descriptor(color_desc(a.get(1)?.as_str()?)?)) - .with("Type", enm("Clry", "UsrS")) - .with("Lctn", long((a.first()?.as_f64()? * 4096.0).round())) - .with("Mdpn", long(50.0)), - )) - }) - .collect(); - let transparency = D::List(vec![ - D::Descriptor(desc("TrnS").with("Opct", pct(100.0)).with("Lctn", long(0.0)).with("Mdpn", long(50.0))), - D::Descriptor(desc("TrnS").with("Opct", pct(100.0)).with("Lctn", long(4096.0)).with("Mdpn", long(50.0))), - ]); - let grad = desc("Grdn") - .with("Nm ", text("Custom")) - .with("GrdF", enm("GrdF", "CstS")) - .with("Intr", D::Double(4096.0)) - .with("Clrs", D::List(stops?)) - .with("Trns", transparency); - let mut d = desc("GdMp").with("Grad", D::Descriptor(grad)); - if let Some(r) = jbool(p, "reverse") { - d = d.with("Rvrs", D::Boolean(r)); - } - if let Some(dd) = jbool(p, "dither") { - d = d.with("Dthr", D::Boolean(dd)); - } - Some(d) -} - -/// An adjustment: its Photoshop class (usually also the direct event's code; Black & White and -/// Photo Filter run by name), the command suffix (`image.adjustments.`, `layer.newAdjustmentLayer.`), and -/// the converters between the adjustment descriptor and the command params. -struct Adjustment { - class: &'static str, - suffix: &'static str, - from: fn(&Descriptor) -> Option, - to: fn(&Value) -> Option, -} - -macro_rules! adj_fields { - ($class:literal, $suffix:literal, $fields:expr) => { - Adjustment { class: $class, suffix: $suffix, from: |d| fields_from(d, $fields).map(Value::Object), to: |p| fields_to(p, $fields, desc($class)) } - }; -} - -const ADJUSTMENTS: &[Adjustment] = &[ - Adjustment { class: "Lvls", suffix: "levels", from: levels_from, to: levels_to }, - Adjustment { class: "Crvs", suffix: "curves", from: curves_from, to: curves_to }, - Adjustment { class: "HStr", suffix: "hueSaturation", from: hue_sat_from, to: hue_sat_to }, - adj_fields!("BrgC", "brightnessContrast", &[F("Brgh", "brightness", Kind::Long), F("Cntr", "contrast", Kind::Long), F("useLegacy", "legacy", Kind::Bool)]), - adj_fields!("Thrs", "threshold", &[F("Lvl ", "level", Kind::Long)]), - adj_fields!("Pstr", "posterize", &[F("Lvls", "levels", Kind::Long)]), - adj_fields!("Invr", "invert", &[]), - Adjustment { class: "ClrB", suffix: "colorBalance", from: color_balance_from, to: color_balance_to }, - adj_fields!("Vbrn", "vibrance", &[F("vibrance", "vibrance", Kind::Long), F("Strt", "saturation", Kind::Long)]), - adj_fields!("Exps", "exposure", &[F("Exps", "exposure", Kind::Dbl), F("Ofst", "offset", Kind::Dbl), F("gammaCorrection", "gamma", Kind::Dbl)]), - Adjustment { class: "PhtF", suffix: "photoFilter", from: |d| fields_from(d, PHOTO_FILTER_FIELDS).map(Value::Object), to: photo_filter_to }, - adj_fields!("BanW", "blackWhite", BW), - Adjustment { class: "ChnM", suffix: "channelMixer", from: channel_mixer_from, to: channel_mixer_to }, - Adjustment { class: "SlcC", suffix: "selectiveColor", from: selective_from, to: selective_to }, - Adjustment { class: "GdMp", suffix: "gradientMap", from: gradient_map_from, to: gradient_map_to }, -]; - -/// Adjustment classes PhotoCraft once exported, with the class Photoshop uses. Measured in -/// Photoshop (#8481): a Make whose Black & White type is `BlnW` fails ("the command Make is not -/// currently available"), `BanW` runs. Import keeps accepting them so actions saved before still -/// load; export never writes them. -const LEGACY_CLASSES: &[(&str, &str)] = &[("BlnW", "BanW")]; - -/// The adjustment with Photoshop class `c`, or the one an old PhotoCraft class stands for. -fn adjustment_by_class(c: &str) -> Option<&'static Adjustment> { - let c = c.trim_end(); - let c = LEGACY_CLASSES.iter().find(|(old, _)| *old == c).map_or(c, |(_, class)| class); - ADJUSTMENTS.iter().find(|a| a.class.trim_end() == c) -} - -const PHOTO_FILTER_FIELDS: &[F] = &[F("Clr ", "color", Kind::Color), F("Dnst", "density", Kind::Long), F("PrsL", "preserveLuminosity", Kind::Bool)]; - -/// A `PhtF` step whose params carry a `filter` preset without an explicit `color`: the descriptor -/// form is colour-only (Photoshop stores no preset key — the `phfl` notes in `crates/io` conclude -/// the same from its CS2 oracles), so the resolved colour must be written, or re-imported playback -/// falls back to the default warming filter. With both present, the explicit colour wins, as when -/// running the command. An unknown preset id keeps the old export (no colour) instead of failing. -fn photo_filter_to(p: &Value) -> Option { - let mut p = p.clone(); - if p.get("color").is_none() { - let hex = p.get("filter").and_then(Value::as_str).and_then(preset_color); - if let (Some(hex), Some(o)) = (hex, p.as_object_mut()) { - o.insert("color".into(), hex.into()); - } - } - fields_to(&p, PHOTO_FILTER_FIELDS, desc("PhtF")) -} - -/// The preset id's resolved `#rrggbb`, or none (no id given, or an unknown one). -fn preset_color(id: &str) -> Option { - crate::adjust_params::PHOTO_FILTERS.iter().find(|f| f.0 == id).map(|(_, _, rgb)| format!("#{:02x}{:02x}{:02x}", rgb[0], rgb[1], rgb[2])) -} - -fn adjustment_by_suffix(suffix: &str) -> Option<&'static Adjustment> { - ADJUSTMENTS.iter().find(|a| a.suffix == suffix) -} - -// ------------------------------------------------------------------ the event table - -/// What one Photoshop step maps to. -enum Mapped { - /// One or more PhotoCraft steps (a `make` with a name becomes new layer + rename). - Steps(Vec<(String, Value)>), - /// No PhotoCraft equivalent; `harmless` steps (tool selections…) are imported switched off. - Unsupported { harmless: bool }, -} - -fn step(id: &str, params: Value) -> Mapped { - Mapped::Steps(vec![(id.to_string(), params)]) -} - -fn steps(v: Vec<(&str, Value)>) -> Mapped { - Mapped::Steps(v.into_iter().map(|(id, p)| (id.to_string(), p)).collect()) -} - -fn none(id: &str) -> Mapped { - step(id, json!({})) -} - -/// An event: code (empty when Photoshop only has a string name), string name, the panel -/// label, the command ids it exports (the first is the one simple events import to), and the -/// two converters. -struct Event { - code: &'static str, - name: &'static str, - label: &'static str, - ids: &'static [&'static str], - from: fn(&Descriptor) -> Mapped, - to: fn(&str, &Value) -> Option, -} - -macro_rules! ev { - ($code:literal, $name:literal, $label:literal, $id:literal, $fields:expr) => { - ev!($code, $name, $label, $id, $fields, unless | _ | false) - }; - // `unless`: params the descriptor can't carry, so such a step isn't exported (it would replay - // differently) rather than losing them. - ($code:literal, $name:literal, $label:literal, $id:literal, $fields:expr, unless $skip:expr) => { - Event { - code: $code, - name: $name, - label: $label, - ids: &[$id], - from: |d| match fields_from(d, $fields) { - Some(m) => step($id, Value::Object(m)), - None => Mapped::Unsupported { harmless: false }, - }, - to: |_, p| if pixel_target(p) && !($skip)(p) && holds_its_settings($id, p) { fields_to(p, $fields, desc("null")) } else { None }, - } - }; -} - -/// Minimum / Maximum with Preserve: Roundness. The descriptor here maps the radius only, and -/// Photoshop's encoding of the shape isn't verified, so such a step is not exported: it would -/// replay as the default Squareness (#7233). -fn preserves_roundness(p: &Value) -> bool { - p.get("preserve").and_then(Value::as_str) == Some("roundness") -} - -/// Whether any of the boolean `flags` is on in `p` (present, not null and not `false`). -fn flag_set(p: &Value, flags: &[&str]) -> bool { - flags.iter().any(|f| p.get(*f).is_some_and(|v| !v.is_null() && *v != Value::Bool(false))) -} - -/// Select > Modify with "Apply effect at canvas bounds": the descriptor has no field for it, so such a -/// step is not exported (it would replay without the option). -fn applies_at_canvas_bounds(p: &Value) -> bool { - flag_set(p, &["applyAtCanvasBounds"]) -} - -/// Settings a mapped event has no field for, by command: `(param, the value the event plays as)`. -/// Photoshop's event has nowhere to put these, so a step that sets one cannot be written: it -/// would import as a different edit, silently. Such a step is refused, the way [`pixel_target`] -/// refuses a filter aimed at a mask -- and no key Photoshop does not define is invented for it, -/// which the clean-room rule forbids and which would make the file wrong in another reader. -/// -/// A step that leaves the setting at the value the event plays as exports as before. -/// How a setting the event cannot carry behaves once the step is replayed without it. Which of -/// the two a setting takes follows the command's own reading of it, not the parameter spec. -enum Lost { - /// Replay uses this value, so only a step already at it survives. Numbers and strings are - /// both compared as written, since the commands below read these settings as written. - ReplaysAs(&'static str), - /// The command reads only this one spelling as anything other than what replay does, so every - /// other value survives -- a differently cased one included, because it too plays as replay's. - DiffersAt(&'static str), -} - -const UNHOLDABLE: &[(&str, &[(&str, Lost)])] = &[ - // Crst carries ClSz only; replay seeds the pattern from 0 (#7668). - ("filter.pixelate.crystallize", &[("seed", Lost::ReplaysAs("0"))]), - // RdlB carries Amnt, BlrM and BlrQ; replay spins or zooms about the middle of the layer. - ("filter.blur.radialBlur", &[("centerX", Lost::ReplaysAs("0.5")), ("centerY", Lost::ReplaysAs("0.5"))]), - // Mnm /Mxm carry Rds only; replay keeps squareness, and so does the command for anything but - // the exact string "roundness" -- see `preserve` in filters.rs. - ("filter.other.minimum", &[("preserve", Lost::DiffersAt("roundness"))]), - ("filter.other.maximum", &[("preserve", Lost::DiffersAt("roundness"))]), -]; - -/// Whether every setting of `p` that its event cannot hold would play the same without it -/// (see [`UNHOLDABLE`]). -fn holds_its_settings(id: &str, p: &Value) -> bool { - let Some((_, settings)) = UNHOLDABLE.iter().find(|(cmd, _)| *cmd == id) else { return true }; - settings.iter().all(|(param, lost)| match (p.get(param), lost) { - (None | Some(Value::Null), _) => true, - (Some(v), Lost::ReplaysAs(played)) => v.as_str() == Some(played) || v.as_f64().is_some_and(|n| played.parse::().is_ok_and(|d| n == d)), - (Some(v), Lost::DiffersAt(spelling)) => v.as_str() != Some(spelling), - }) -} - -/// Whether `p` edits the layer's pixels: no `"target"` or `"target":"pixels"`. Photoshop's -/// descriptor for a plain event has no field for a mask, Quick Mask or channel target, so such -/// a step can't be exported faithfully. -fn pixel_target(p: &Value) -> bool { - p.get("target").is_none_or(|t| t.as_str() == Some("pixels")) -} - -const INTERPOLATION: &[(&str, &str)] = &[ - ("Bcbc", "bicubic"), - ("Blnr", "bilinear"), - ("Nrst", "nearest"), - ("bicubicSharper", "bicubicSharper"), - ("bicubicSmoother", "bicubicSmoother"), - ("bicubicAutomatic", "bicubicAutomatic"), - ("automaticInterpolation", "automatic"), - ("preserveDetailsUpscale", "preserveDetails"), - ("deepUpscale", "preserveDetails"), -]; -const NOISE: &[(&str, &str)] = &[("Unfr", "uniform"), ("Gsn ", "gaussian")]; -const OFFSET_FILL: &[(&str, &str)] = &[("Wrp ", "wrap"), ("Rpt ", "repeat"), ("Bckg", "transparent")]; -const TRIM: &[(&str, &str)] = &[("Trns", "transparent"), ("topLeftPixelColor", "topLeft"), ("bottomRightPixelColor", "bottomRight")]; -const EXTENSION: &[(&str, &str)] = &[("Bckg", "background"), ("Frgd", "foreground"), ("Wht ", "white"), ("Blck", "black"), ("Trns", "transparent")]; -const FILL_CONTENTS: &[(&str, &str)] = &[ - ("FrgC", "foreground"), - ("BckC", "background"), - ("Wht ", "white"), - ("Blck", "black"), - ("Gry ", "gray"), - ("Clr ", "color"), - ("HstS", "history"), - ("contentAware", "contentAware"), -]; -const STROKE_LOCATION: &[(&str, &str)] = &[("Insd", "inside"), ("Cntr", "center"), ("OtsF", "outside")]; -const INTENT: &[(&str, &str)] = &[("Img ", "perceptual"), ("Clrm", "relative"), ("Grp ", "saturation"), ("AbsC", "absolute")]; -const PROFILES: &[(&str, &str)] = - &[("sRGB IEC61966-2.1", "srgb"), ("Display P3", "display-p3"), ("Adobe RGB (1998)", "adobe-rgb-compat"), ("ProPhoto RGB", "prophoto-compat")]; -/// Smart Blur quality. Photoshop's codes come first, so they are what an export writes (measured in -/// Photoshop: `Hgh `/`Mdm `/`Low ` play back as its fallback, low quality). The old codes after -/// them still read, for actions PhotoCraft wrote before. -const SMART_BLUR_QUALITY: &[(&str, &str)] = &[("SBQL", "low"), ("SBQM", "medium"), ("SBQH", "high"), ("Hgh ", "high"), ("Mdm ", "medium"), ("Low ", "low")]; -const SMART_BLUR_MODE: &[(&str, &str)] = &[("SBMN", "normal"), ("SBME", "edgeOnly"), ("SBMO", "overlayEdge")]; -const RADIAL_METHOD: &[(&str, &str)] = &[("Spn ", "spin"), ("Zm ", "zoom")]; -const RADIAL_QUALITY: &[(&str, &str)] = &[("Drft", "draft"), ("Gd ", "good"), ("Bst ", "best")]; -const LABEL_COLORS: &[(&str, &str)] = - &[("None", "none"), ("Rd", "red"), ("Orng", "orange"), ("Ylw", "yellow"), ("Grn", "green"), ("Bl", "blue"), ("Vlt", "violet"), ("Gry", "gray")]; -const ALIGN: &[(&str, &str)] = - &[("AdLf", "leftEdges"), ("AdCH", "horizontalCenters"), ("AdRg", "rightEdges"), ("AdTp", "topEdges"), ("AdCV", "verticalCenters"), ("AdBt", "bottomEdges")]; -const PURGE: &[(&str, &str)] = &[("Al", "all"), ("Clpb", "clipboard"), ("Hsty", "histories"), ("Undo", "undo")]; -const MODES: &[(&str, &str)] = &[("RGBM", "rgb"), ("Grys", "grayscale"), ("CMYM", "cmyk"), ("LbCM", "lab"), ("Mltc", "multichannel")]; - -// Events whose target depends on the descriptor (`make`, `set`, `select`…): custom converters. - -fn adjustment_steps(a: &Adjustment, prefix: &str, type_desc: Option<&Descriptor>) -> Mapped { - let params = match type_desc { - Some(t) if get_enum(t, "presetKind").as_deref() != Some("presetKindDefault") => match (a.from)(t) { - Some(p) => p, - None => return Mapped::Unsupported { harmless: false }, - }, - _ => json!({}), - }; - step(&format!("{prefix}{}", a.suffix), params) -} - -/// A `patternLayer` descriptor's pattern, scale, angle and link as the params of -/// `layer.newFillLayer.pattern` / `layer.fill.pattern.set`. The pattern goes by name: ids differ -/// between Photoshop's library and one rebuilt from the same `.pat` file. None for a pattern -/// recorded without a name or id. -fn pattern_params(t: &Descriptor) -> Option> { - let mut p = Map::new(); - if let Some(ptrn) = get_obj(t, "Ptrn") { - let key = get_text(ptrn, "Nm ").filter(|n| !n.is_empty()).or_else(|| get_text(ptrn, "Idnt").filter(|i| !i.is_empty()))?; - p.insert("pattern".into(), key.into()); - } - if let Some(s) = get_num(t, "Scl ") { - p.insert("scale".into(), s.into()); - } - if let Some(a) = get_num(t, "Angl") { - p.insert("angle".into(), a.into()); - } - if let Some(l) = get_bool(t, "Algn") { - p.insert("link".into(), l.into()); - } - Some(p) -} - -/// The `patternLayer` descriptor for [`pattern_params`]' params. -fn pattern_desc(p: &Value) -> Option { - let mut t = desc("patternLayer"); - if let Some(n) = jstr(p, "pattern") { - t = t.with("Ptrn", D::Descriptor(desc("Ptrn").with("Nm ", text(n)))); - } - if let Some(s) = jnum(p, "scale") { - t = t.with("Scl ", pct(s)); - } - if let Some(a) = jnum(p, "angle") { - t = t.with("Angl", ang(a)); - } - if let Some(l) = jbool(p, "link") { - t = t.with("Algn", D::Boolean(l)); - } - if p.get("phase").is_some() { - return None; - } - Some(t) -} - -/// Layer › Layer Mask: the `UsrM` value of an Add Layer Mask `Mk` ↔ its command. -const MASK_USING: &[(&str, &str)] = &[ - ("RvlA", "layer.layerMask.revealAll"), - ("HdAl", "layer.layerMask.hideAll"), - ("RvlS", "layer.layerMask.revealSelection"), - ("HdSl", "layer.layerMask.hideSelection"), -]; - -fn make_from(d: &Descriptor) -> Mapped { - // Duplicate layer/group into a new document: `Mk` with a document class, a layer - // `Usng`, an optional `Nm` (the new document's name) and an optional `LyrN` - // (the copy's name). A `Dplc` with a `T` document reference (duplicate into another - // open document) stays a kept Photoshop step: document indices mean nothing at replay. - if let Some(r) = get_ref(d, "null") - && ref_class(r).as_deref() == Some("Dcmn") - && matches!(target(r), Target::Class) - && let Some(u) = get_ref(d, "Usng") - && matches!(ref_class(u).as_deref(), Some("Lyr") | Some("layerSection")) - && let Some(mut p) = layer_target(u) - { - p.insert("document".into(), "new".into()); - if let Some(n) = get_text(d, "Nm ") { - p.insert("documentName".into(), n.into()); - } - if let Some(n) = get_text(d, "LyrN") { - p.insert("name".into(), n.into()); - } - return step("layer.duplicate", Value::Object(p)); - } - // Add Layer Mask: a `Chnl` class made at the mask channel, `Usng` what it reveals. - if let Some(D::Class(c)) = d.get("Nw ") - && trimmed(&c.class_id) == "Chnl" - { - // The target layer's mask only: a further item (a `Lyr` by name…) puts it on another layer. - let at_mask = get_ref(d, "At ") - .is_some_and(|r| r.len() == 1 && ref_class(r).as_deref() == Some("Chnl") && matches!(target(r), Target::Ordinal(o) if o == "Msk")); - return match get_enum(d, "Usng").and_then(|u| lookup(MASK_USING, &u)) { - Some(id) if at_mask => none(id), - _ => Mapped::Unsupported { harmless: false }, - }; - } - if let Some(nw) = get_obj(d, "Nw ") { - // Layer via Copy / Cut (`Usng` = the selection), or a new document. - if get_enum(d, "Usng").as_deref() == Some("Slct") { - let id = if get_bool(d, "Cpy ") == Some(true) { "layer.new.layerViaCopy" } else { "layer.new.layerViaCut" }; - let mut v = vec![(id, json!({}))]; - if let Some(n) = get_text(nw, "Nm ") { - v.push(("layer.setProps", json!({"name": n}))); - } - return steps(v); - } - if get_text(nw, "preset").is_some() { - return none("file.newFromClipboard"); - } - if let (Some(w), Some(h)) = (get_num(nw, "Wdth"), get_num(nw, "Hght")) { - let res = get_num(nw, "Rslt").unwrap_or(72.0); - // Dimensions are in points (`#Rlt`) unless given in pixels. - let to_px = |k: &str, v: f64| match nw.get(k) { - Some(D::UnitFloat { unit: PX, .. }) => v, - _ => v * res / 72.0, - }; - let mut p = json!({"width": to_px("Wdth", w).round(), "height": to_px("Hght", h).round(), "resolution": res}); - if let Some(n) = get_text(nw, "Nm ") { - p["name"] = json!(n); - } - if let Some(D::Class(c)) = nw.get("Md ") - && let Some(m) = lookup(MODES, &trimmed(&c.class_id)) - { - p["mode"] = json!(m); - } - if let Some(depth) = get_num(nw, "Dpth") { - p["depth"] = json!(depth); - } - if let Some(f) = get_enum(nw, "Fl ") { - p["background"] = json!(match f.as_str() { - "Wht" => "white", - "BckC" => "backgroundColor", - "Trns" => "transparent", - _ => "white", - }); - } - return step("file.new", p); - } - return Mapped::Unsupported { harmless: false }; - } - let Some(r) = get_ref(d, "null") else { return Mapped::Unsupported { harmless: false } }; - let using = get_obj(d, "Usng"); - let type_desc = using.and_then(|u| get_obj(u, "Type")); - match ref_class(r).as_deref() { - Some("Lyr") => { - let mut p = Map::new(); - if let Some(u) = using { - if let Some(n) = get_text(u, "Nm ") { - p.insert("name".into(), n.into()); - } - if let Some(o) = get_num(u, "Opct") { - p.insert("opacity".into(), (o / 100.0).into()); - } - if let Some(m) = get_enum(u, "Md ").and_then(|m| blend_label(&m)) { - p.insert("mode".into(), m.into()); - } - } - step("layer.new.layer", Value::Object(p)) - } - Some("AdjL") => match type_desc.and_then(|t| adjustment_by_class(&trimmed(&t.class_id))) { - Some(a) => adjustment_steps(a, "layer.newAdjustmentLayer.", type_desc), - None => Mapped::Unsupported { harmless: false }, - }, - Some("contentLayer") => match type_desc { - Some(t) if t.class_id.is("solidColorLayer") => match get_obj(t, "Clr ").and_then(color_hex) { - Some(c) => step("layer.newFillLayer.solidColor", json!({"color": c})), - None => none("layer.newFillLayer.solidColor"), - }, - Some(t) if t.class_id.is("patternLayer") => match pattern_params(t) { - Some(p) => step("layer.newFillLayer.pattern", Value::Object(p)), - None => Mapped::Unsupported { harmless: false }, - }, - _ => Mapped::Unsupported { harmless: false }, - }, - Some("layerSection") => { - let mut p = Map::new(); - if let Some(n) = using.and_then(|u| get_text(u, "Nm ")) { - p.insert("name".into(), n.into()); - } - match get_ref(d, "From") { - // A named source layer stays the source (#7236); a target reference and an - // index/id source (our exporter never writes those) keep the old implicit - // import: the group lands on the current selection at playback. - Some(r) => { - if let Some(t) = layer_target(r) { - p.extend(t); - } - step("layer.groupLayers", Value::Object(p)) - } - None => step("layer.new.group", Value::Object(p)), - } - } - _ => Mapped::Unsupported { harmless: false }, - } -} - -fn make_to(id: &str, p: &Value) -> Option { - let with_name = |cls: &str| { - let mut u = desc(cls); - if let Some(n) = jstr(p, "name") { - u = u.with("Nm ", text(n)); - } - u - }; - Some(match id { - "layer.new.layer" => { - // The descriptor carries the name, opacity and mode only. A step that also clips to - // the layer below, labels the layer, fills it with the neutral colour or places it - // below the active layer would replay as a different layer, so it isn't exported - // (strict export fails, a partial one skips it: #7502, #7512, #7513, #7514). - let set = |key: &str, default: Value| p.get(key).is_some_and(|v| !v.is_null() && *v != default); - if set("clipToPrevious", Value::Bool(false)) - || set("color", json!("none")) - || set("fillNeutral", Value::Bool(false)) - || set("position", json!("above")) - { - return None; - } - let mut u = with_name("Lyr "); - if let Some(o) = jnum(p, "opacity") { - u = u.with("Opct", pct(o * 100.0)); - } - if let Some(m) = jstr(p, "mode").and_then(blend_ps) { - u = u.with("Md ", enm("BlnM", m)); - } - desc("null").with("null", class_ref("Lyr ")).with("Usng", D::Descriptor(u)) - } - "layer.new.group" => desc("null").with("null", class_ref("layerSection")).with("Usng", D::Descriptor(with_name("layerSection"))), - "layer.groupLayers" => { - // An explicit source layer goes in by name like every other layer reference; a - // step without one keeps the target-layer form (#7236). - desc("null").with("null", class_ref("layerSection")).with("From", layer_ref(p)?).with("Usng", D::Descriptor(with_name("layerSection"))) - } - "layer.new.layerViaCopy" | "layer.new.layerViaCut" => { - let mut d = desc("null").with("Nw ", D::Descriptor(desc("Lyr "))).with("Usng", enm("ArSl", "Slct")); - if id == "layer.new.layerViaCopy" { - d = d.with("Cpy ", D::Boolean(true)); - } - d - } - "layer.newFillLayer.solidColor" => { - let mut t = desc("solidColorLayer"); - // The descriptor's colour is opaque RGB: a colour with alpha, or one it can't parse, - // would replay as the default black (#7507). - if let Some(c) = p.get("color").filter(|v| !v.is_null()) { - t = t.with("Clr ", D::Descriptor(c.as_str().and_then(color_desc)?)); - } - desc("null").with("null", class_ref("contentLayer")).with("Usng", D::Descriptor(desc("contentLayer").with("Type", D::Descriptor(t)))) - } - "layer.newFillLayer.pattern" => { - if p.get("path").is_some() { - return None; - } - let t = pattern_desc(p)?; - desc("null").with("null", class_ref("contentLayer")).with("Usng", D::Descriptor(desc("contentLayer").with("Type", D::Descriptor(t)))) - } - "layer.duplicate" => { - // Duplicate into a new document is a `Mk`, not a `Dplc` (see `make_from`). - // Anything else falls through to the `Dplc` event below. - if jstr(p, "document") != Some("new") { - return None; - } - let mut d = desc("null").with("null", class_ref("Dcmn")).with("Usng", layer_ref(p)?); - if let Some(n) = jstr(p, "documentName") { - d = d.with("Nm ", text(n)); - } - if let Some(n) = jstr(p, "name") { - d = d.with("LyrN", text(n)); - } - d - } - "layer.layerMask.revealAll" | "layer.layerMask.hideAll" | "layer.layerMask.revealSelection" | "layer.layerMask.hideSelection" => { - // Photoshop adds the mask to the target layer only. - if p.get("layer").is_some() { - return None; - } - let at = D::Reference(vec![ReferenceItem::Enumerated { class: class("Chnl"), type_id: code("Chnl"), value: code("Msk ") }]); - desc("null").with("Nw ", D::Class(class("Chnl"))).with("At ", at).with("Usng", enm("UsrM", lookup_back(MASK_USING, id)?)) - } - "file.newFromClipboard" => desc("null").with("Nw ", D::Descriptor(desc("Dcmn").with("preset", text("Clipboard")))), - "file.new" => { - let mut n = desc("Dcmn"); - if let Some(name) = jstr(p, "name") { - n = n.with("Nm ", text(name)); - } - if let Some(m) = jstr(p, "mode").and_then(|m| lookup_back(MODES, if m == "gray" { "grayscale" } else { m })) { - n = n.with("Md ", D::Class(class(m))); - } - n = n.with("Wdth", px(jnum(p, "width").unwrap_or(1920.0))).with("Hght", px(jnum(p, "height").unwrap_or(1080.0))); - n = n.with("Rslt", D::UnitFloat { unit: *b"#Rsl", value: jnum(p, "resolution").unwrap_or(72.0) }); - // `Fl ` is white, transparent or Photoshop's own background colour: black, a hex - // colour or a given `backgroundColor` would replay as something else (#7503). - if p.get("backgroundColor").is_some_and(|v| !v.is_null()) { - return None; - } - let fill = match p.get("background").filter(|v| !v.is_null()) { - None => "Wht ", - Some(b) => match b.as_str()? { - "white" => "Wht ", - "transparent" => "Trns", - "backgroundColor" => "BckC", - _ => return None, - }, - }; - n = n.with("Fl ", enm("Fl ", fill)).with("Dpth", long(jnum(p, "depth").unwrap_or(8.0))); - desc("null").with("Nw ", D::Descriptor(n)) - } - _ => { - let suffix = id.strip_prefix("layer.newAdjustmentLayer.")?; - let a = adjustment_by_suffix(suffix)?; - let t = if p.as_object().is_some_and(|o| o.is_empty()) { - desc(a.class).with("presetKind", enm("presetKindType", "presetKindDefault")) - } else { - (a.to)(p)? - }; - desc("null").with("null", class_ref("AdjL")).with("Usng", D::Descriptor(desc("AdjL").with("Type", D::Descriptor(t)))) - } - }) -} - -fn set_from(d: &Descriptor) -> Mapped { - let Some(r) = get_ref(d, "null") else { return Mapped::Unsupported { harmless: false } }; - let unsupported = Mapped::Unsupported { harmless: false }; - match (ref_class(r).as_deref(), target(r)) { - (Some("Chnl"), Target::Property(p)) if p == "fsel" => match d.get("T ") { - Some(D::Enumerated { value, .. }) => match trimmed(value).as_str() { - "Al" => none("select.all"), - "None" => none("select.deselect"), - "Prvs" => none("select.reselect"), - _ => unsupported, - }, - Some(D::Reference(t)) => match (ref_class(t).as_deref(), target(t)) { - (Some("Chnl"), Target::Ordinal(o)) if o == "Trsp" => step("select.loadSelection", json!({"channel": "transparency"})), - // ⌘-click on the targeted channel (a layer mask after `select` of `Msk`). - (Some("Chnl"), Target::Ordinal(o)) if o == "Trgt" => step("select.loadSelection", json!({"channel": "targeted"})), - (Some("Chnl"), Target::Name(n)) => step("select.loadSelection", json!({"channel": n})), - _ => unsupported, - }, - Some(D::Descriptor(t)) if t.class_id.is("Plgn") => { - let pts: Option> = get_list(t, "Pts ") - .unwrap_or(&[]) - .iter() - .map(|v| match v { - D::Descriptor(pt) => Some(json!([get_num(pt, "Hrzn")?, get_num(pt, "Vrtc")?])), - _ => None, - }) - .collect(); - match pts { - Some(pts) if pts.len() >= 3 => step("select.lasso", json!({"points": pts})), - _ => unsupported, - } - } - Some(D::Descriptor(t)) if t.class_id.is("Rctn") || t.class_id.is("Elps") => { - let (Some(top), Some(left), Some(bottom), Some(right)) = (get_num(t, "Top "), get_num(t, "Left"), get_num(t, "Btom"), get_num(t, "Rght")) - else { - return unsupported; - }; - let mut p = json!({"x": left.round(), "y": top.round(), "width": (right - left).round().max(0.0), "height": (bottom - top).round().max(0.0)}); - if t.class_id.is("Elps") { - p["ellipse"] = json!(true); - } - step("select.rect", p) - } - _ => unsupported, - }, - // Quick Mask mode on (`set` of the document's quick-mask property); `clearEvent` turns it off. - (Some("Prpr"), Target::Property(p)) if p == "QucM" => step("select.editInQuickMaskMode", json!({"on": true})), - // Layer › New › Layer From Background (Photoshop records the New Layer dialog's values - // as a `set` of the Background); values other than the defaults then apply to the layer. - (Some("Lyr"), Target::Property(p)) if p == "Bckg" => { - // On an image that opened as a normal layer there is no Background to convert; - // Photoshop stops there, but the step's purpose (an editable layer) is met. - // Photoshop's `set` of another layer doesn't target it: the selected layer stays. - let mut v = vec![("layer.new.layerFromBackground", json!({"ifPresent": true, "select": false}))]; - let mut props = Map::new(); - props.insert("layer".into(), "Layer 0".into()); - if let Some(t) = get_obj(d, "T ") { - if let Some(n) = get_text(t, "Nm ") { - props.insert("name".into(), n.into()); - } - if let Some(o) = get_num(t, "Opct").filter(|o| (o - 100.0).abs() > 1e-9) { - props.insert("opacity".into(), (o / 100.0).into()); - } - match get_enum(t, "Md ").as_deref() { - None | Some("Nrml") => {} - Some(m) => match blend_label(m) { - Some(label) => { - props.insert("blend".into(), label.into()); - } - None => return unsupported, - }, - } - } - if props.len() > 1 { - v.push(("layer.setProps", Value::Object(props))); - } - steps(v) - } - // The toolbox colours. - (Some("Clr"), Target::Property(p)) if p == "FrgC" || p == "BckC" => match get_obj(d, "T ").and_then(color_hex) { - Some(hex) => step("tools.setColors", json!({(if p == "FrgC" { "foreground" } else { "background" }): hex})), - None => unsupported, - }, - (Some("Lyr"), _) => { - let Some(mut p) = layer_target(r) else { return unsupported }; - let Some(t) = get_obj(d, "T ") else { return unsupported }; - let mut v = Vec::new(); - if let Some(c) = get_enum(t, "Clr ").and_then(|c| lookup(LABEL_COLORS, &c)) { - let mut lp = p.clone(); - lp.insert("color".into(), c.into()); - v.push(("layer.setLabelColor", Value::Object(lp))); - } - if let Some(n) = get_text(t, "Nm ") { - p.insert("name".into(), n.into()); - } - if let Some(o) = get_num(t, "Opct") { - p.insert("opacity".into(), (o / 100.0).into()); - } - if let Some(f) = get_num(t, "fillOpacity") { - p.insert("fill".into(), (f / 100.0).into()); - } - if let Some(m) = get_enum(t, "Md ") { - let Some(label) = blend_label(&m) else { return unsupported }; - p.insert("blend".into(), label.into()); - } - if let Some(vis) = get_bool(t, "Vsbl") { - p.insert("visible".into(), vis.into()); - } - if p.keys().any(|k| k != "layer") { - v.push(("layer.setProps", Value::Object(p))); - } - if v.is_empty() { unsupported } else { steps(v) } - } - // A Pattern Fill layer's pattern (double-click its thumbnail). - (Some("contentLayer"), Target::Ordinal(o)) if o == "Trgt" => match get_obj(d, "T ") { - Some(t) if t.class_id.is("patternLayer") => match pattern_params(t) { - Some(p) if !p.is_empty() => step("layer.fill.pattern.set", Value::Object(p)), - _ => unsupported, - }, - _ => unsupported, - }, - (Some("AdjL"), Target::Ordinal(o)) if o == "Trgt" => { - match get_obj(d, "T ").and_then(|t| adjustment_by_class(&trimmed(&t.class_id)).map(|a| (a, t))) { - Some((a, t)) => match (a.from)(t) { - // `kind` names the adjustment so Save Actions can write the class back. - // Not on an empty set (Photoshop's "reset to default"): params with any key - // merge, none reset. - Some(mut p) => { - if let Some(o) = p.as_object_mut().filter(|o| !o.is_empty()) { - o.insert("kind".into(), json!(a.suffix)); - } - step("layer.setAdjustment", p) - } - None => unsupported, - }, - None => unsupported, - } - } - _ => unsupported, - } -} - -fn set_to(id: &str, p: &Value) -> Option { - let fsel = D::Reference(vec![ReferenceItem::Property { class: class("Chnl"), key: Id::new("fsel") }]); - let sel = |t: D| desc("null").with("null", fsel.clone()).with("T ", t); - Some(match id { - "select.all" => sel(enm("Ordn", "Al ")), - "select.deselect" => sel(enm("Ordn", "None")), - "select.reselect" => sel(enm("Ordn", "Prvs")), - // The descriptor loads a plain new selection: inverting it or combining it with the current - // one (add, subtract, intersect) would be lost (#7506). - "select.loadSelection" - if p.get("invert").is_some_and(|v| *v != Value::Bool(false) && !v.is_null()) - || p.get("operation").is_some_and(|v| *v != json!("new") && !v.is_null()) => - { - return None; - } - "select.loadSelection" => match jstr(p, "channel")? { - "transparency" => sel(D::Reference(vec![ReferenceItem::Enumerated { class: class("Chnl"), type_id: Id::new("Chnl"), value: Id::new("Trsp") }])), - "targeted" => sel(D::Reference(vec![ReferenceItem::Enumerated { class: class("Chnl"), type_id: Id::new("Ordn"), value: Id::new("Trgt") }])), - name => sel(name_ref("Chnl", name)), - }, - "select.lasso" => { - let pts: Option> = p - .get("points")? - .as_array()? - .iter() - .map(|pt| { - let a = pt.as_array()?; - Some(D::Descriptor(desc("Pnt ").with("Hrzn", px(a.first()?.as_f64()?)).with("Vrtc", px(a.get(1)?.as_f64()?)))) - }) - .collect(); - sel(D::Descriptor(desc("Plgn").with("Pts ", D::List(pts?)))) - } - "select.editInQuickMaskMode" => { - if jbool(p, "on") != Some(true) { - return None; - } - desc("null").with("null", quick_mask_ref()) - } - "tools.setColors" => { - // One colour per Photoshop step: a step that sets both (or any other key) doesn't - // export rather than lose one. - if p.as_object().is_some_and(|o| o.keys().any(|k| k != "foreground" && k != "background")) { - return None; - } - let (key, hex) = match (jstr(p, "foreground"), jstr(p, "background")) { - (Some(f), None) => ("FrgC", f), - (None, Some(b)) => ("BckC", b), - _ => return None, - }; - desc("null") - .with("null", D::Reference(vec![ReferenceItem::Property { class: class("Clr "), key: code(key) }])) - .with("T ", D::Descriptor(color_desc(hex)?)) - } - "select.rect" => { - match jstr(p, "mode") { - None | Some("replace") => {} - Some(_) => return None, - } - let (x, y, w, h) = (jnum(p, "x")?, jnum(p, "y")?, jnum(p, "width")?, jnum(p, "height")?); - let cls = if jbool(p, "ellipse") == Some(true) { "Elps" } else { "Rctn" }; - sel(D::Descriptor(desc(cls).with("Top ", px(y)).with("Left", px(x)).with("Btom", px(y + h)).with("Rght", px(x + w)))) - } - "layer.setProps" | "layer.renameLayer" | "layer.setLabelColor" => { - // Only these keys map onto the `Lyr ` descriptor; locks, clipping, Advanced Blending - // channels or an explicit `layers` list would be dropped (#7196, #7246). - const MAPPED: [&str; 7] = ["layer", "name", "opacity", "fill", "blend", "visible", "color"]; - if p.as_object().is_some_and(|m| m.iter().any(|(k, v)| !v.is_null() && !MAPPED.contains(&k.as_str()))) { - return None; - } - let mut t = desc("Lyr "); - if let Some(n) = jstr(p, "name") { - t = t.with("Nm ", text(n)); - } - if let Some(o) = jnum(p, "opacity") { - t = t.with("Opct", pct(o * 100.0)); - } - if let Some(f) = jnum(p, "fill") { - t = t.with("fillOpacity", pct(f * 100.0)); - } - if let Some(m) = jstr(p, "blend") { - t = t.with("Md ", enm("BlnM", blend_ps(m)?)); - } - if let Some(v) = jbool(p, "visible") { - t = t.with("Vsbl", D::Boolean(v)); - } - if let Some(c) = jstr(p, "color") { - t = t.with("Clr ", enm("Clr ", lookup_back(LABEL_COLORS, c)?)); - } - if t.items.is_empty() { - return None; - } - desc("null").with("null", layer_ref(p)?).with("T ", D::Descriptor(t)) - } - "layer.new.layerFromBackground" => { - let bckg = D::Reference(vec![ReferenceItem::Property { class: class("Lyr "), key: Id::new("Bckg") }]); - desc("null").with("null", bckg).with("T ", D::Descriptor(desc("Lyr ").with("Opct", pct(100.0)).with("Md ", enm("BlnM", "Nrml")))) - } - "layer.fill.pattern.set" => { - if p.get("layer").is_some() || p.get("document").is_some() { - return None; - } - desc("null").with("null", target_ref("contentLayer")).with("T ", D::Descriptor(pattern_desc(p)?)) - } - "layer.setAdjustment" => { - // The adjustment kind isn't in the params: Photoshop needs it, so only steps that - // name one (`kind`) export. - let kind = jstr(p, "kind")?; - // `layer.setAdjustment` changes only the settings it names. Color Balance and - // Hue/Saturation descriptors carry every setting, filling absent ones with defaults, - // so a partial edit would replay as one that also resets the rest (#8531). - // Present and of the shape the writer reads: anything else it would write as 0. - let number = |p: &Value, k: &str| p.get(k).and_then(Value::as_f64).is_some_and(f64::is_finite); - let numbers = |p: &Value, keys: &[&str]| keys.iter().all(|k| number(p, k)); - let flag = |k: &str| p.get(k).is_some_and(Value::is_boolean); - let triplet = - |k: &str| p.get(k).and_then(Value::as_array).is_some_and(|a| a.len() == 3 && a.iter().all(|v| v.as_f64().is_some_and(f64::is_finite))); - let complete = match kind { - "colorBalance" => ["shadows", "midtones", "highlights"].iter().all(|k| triplet(k)) && flag("preserveLuminosity"), - // Every colour range written carries its own hue, saturation and lightness too. - "hueSaturation" => { - flag("colorize") - && numbers(p, &["hue", "saturation", "lightness"]) - && HUE_RANGES.iter().filter_map(|r| p.get(*r).filter(|v| !v.is_null())).all(|r| { - // Bounds, when given, are the four whole numbers `hue_entry` writes (as integers); - // otherwise it drops or rounds them. - let bounds = r.get("range").filter(|v| !v.is_null()).is_none_or(|v| { - v.as_array().is_some_and(|a| a.len() == 4 && a.iter().all(|b| b.as_f64().is_some_and(|b| b.is_finite() && b.fract() == 0.0))) - }); - r.is_object() && numbers(r, &["hue", "saturation", "lightness"]) && bounds - }) - } - _ => true, - }; - if !complete { - return None; - } - let a = adjustment_by_suffix(kind)?; - desc("null").with("null", target_ref("AdjL")).with("T ", D::Descriptor((a.to)(p)?)) - } - _ => return None, - }) -} - -/// Tool classes Photoshop records when an action switches tools: no document effect. -fn is_tool_class(c: &str) -> bool { - c.ends_with("Tl") || c.ends_with("Tool") -} - -fn select_from(d: &Descriptor) -> Mapped { - let Some(r) = get_ref(d, "null") else { return Mapped::Unsupported { harmless: false } }; - match (ref_class(r).as_deref(), target(r)) { - (Some("Lyr"), Target::Name(n)) => { - let mut p = json!({"layer": n}); - match get_enum(d, "selectionModifier").as_deref() { - Some("addToSelection") => p["mode"] = json!("add"), - Some("removeFromSelection") => p["mode"] = json!("remove"), - // Shift-click: select everything between the active layer and this one. - Some("addToSelectionContinuous") => p["mode"] = json!("range"), - _ => {} - } - step("layer.select", p) - } - // The Channels panel: the active layer's mask, or back to the composite (`RGB`, `CMYK`…). - (Some("Chnl"), Target::Ordinal(o)) => match o.as_str() { - "Msk" => step("channel.target", json!({"channel": "mask"})), - "RGB" | "CMYK" | "Lab" | "Gry" => step("channel.target", json!({"channel": "composite"})), - // Re-selecting the channel that is already targeted changes nothing. - "Trgt" => Mapped::Unsupported { harmless: true }, - _ => Mapped::Unsupported { harmless: false }, - }, - // History › Step Backward / Step Forward. - (Some("HstS"), Target::Ordinal(o)) if o == "Prvs" => none("edit.undo"), - (Some("HstS"), Target::Ordinal(o)) if o == "Nxt" => none("edit.redo"), - (Some("Lyr"), Target::Ordinal(o)) => { - // Shift+Alt+[ / ] add the next layer to the selection instead of replacing it. - let add = get_enum(d, "selectionModifier").as_deref() == Some("addToSelection"); - match (o.as_str(), add) { - ("Frwr", false) => none("layer.selectAbove"), - ("Frwr", true) => none("layer.addAboveToSelection"), - ("Bckw", false) => none("layer.selectBelow"), - ("Bckw", true) => none("layer.addBelowToSelection"), - ("Frnt", _) => none("layer.selectTop"), - ("Back", _) => none("layer.selectBottom"), - _ => Mapped::Unsupported { harmless: false }, - } - } - (Some(c), Target::Class) if is_tool_class(c) => Mapped::Unsupported { harmless: true }, - // A menu item chosen while recording (`Mn`): the View menu's zoom items replay. - (Some("Mn"), Target::Ordinal(item)) => match lookup(MENU_ITEMS, &item) { - Some(id) => none(id), - None => Mapped::Unsupported { harmless: false }, - }, - // Switching to another open document: its offset from the active one, -1 for the previous - // tab and 1 for the next (a template action copies from one and pastes into the other, #7103). - (Some("Dcmn"), Target::Offset(o)) => step("document.activate", json!({"offset": o})), - _ => Mapped::Unsupported { harmless: false }, - } -} - -/// `MnIt` menu-item codes ↔ the shell's view commands. -const MENU_ITEMS: &[(&str, &str)] = &[("FtOn", "view.fitOnScreen"), ("ActP", "view.actualPixels"), ("ZmIn", "view.zoomIn"), ("ZmOt", "view.zoomOut")]; - -fn select_to(id: &str, p: &Value) -> Option { - let ord = |o: &str| D::Reference(vec![ReferenceItem::Enumerated { class: class("Lyr "), type_id: code("Ordn"), value: code(o) }]); - let enumerated = |cls: &str, ty: &str, v: &str| D::Reference(vec![ReferenceItem::Enumerated { class: class(cls), type_id: code(ty), value: code(v) }]); - Some(match id { - "layer.select" => { - if p.get("occurrence").is_some() { - return None; - } - let name = jstr(p, "name").or_else(|| jstr(p, "layer"))?; - let mut d = desc("null").with("null", name_ref("Lyr ", name)); - match jstr(p, "mode") { - None | Some("replace") => {} - Some("add") => d = d.with("selectionModifier", enm("selectionModifierType", "addToSelection")), - Some("remove") => d = d.with("selectionModifier", enm("selectionModifierType", "removeFromSelection")), - Some("range") => d = d.with("selectionModifier", enm("selectionModifierType", "addToSelectionContinuous")), - Some(_) => return None, - } - d.with("MkVs", D::Boolean(false)) - } - "channel.target" => { - let v = match jstr(p, "channel") { - Some("mask") => "Msk ", - None | Some("composite") => "RGB ", - Some(_) => return None, - }; - desc("null").with("null", enumerated("Chnl", "Chnl", v)).with("MkVs", D::Boolean(false)) - } - "edit.undo" => desc("null").with("null", enumerated("HstS", "Ordn", "Prvs")), - "edit.redo" => desc("null").with("null", enumerated("HstS", "Ordn", "Nxt ")), - "layer.selectAbove" => desc("null").with("null", ord("Frwr")), - "layer.selectBelow" => desc("null").with("null", ord("Bckw")), - "layer.addAboveToSelection" => desc("null").with("null", ord("Frwr")).with("selectionModifier", enm("selectionModifierType", "addToSelection")), - "layer.addBelowToSelection" => desc("null").with("null", ord("Bckw")).with("selectionModifier", enm("selectionModifierType", "addToSelection")), - "layer.selectTop" => desc("null").with("null", ord("Frnt")), - "layer.selectBottom" => desc("null").with("null", ord("Back")), - // An absolute tab index has no Photoshop equivalent; an offset is what Photoshop records. - "document.activate" if p.get("document").is_none_or(Value::is_null) => { - let offset = i32::try_from(p.get("offset")?.as_i64()?).ok()?; - desc("null").with("null", D::Reference(vec![ReferenceItem::Offset { class: class("Dcmn"), offset }])) - } - _ => { - let item = lookup_back(MENU_ITEMS, id)?; - desc("null").with("null", D::Reference(vec![ReferenceItem::Enumerated { class: class("Mn "), type_id: code("MnIt"), value: code(item) }])) - } - }) -} - -fn delete_from(d: &Descriptor) -> Mapped { - match get_ref(d, "null") { - None => none("edit.clear"), - Some(r) if ref_class(r).as_deref() == Some("Lyr") => match layer_target(r) { - Some(p) => step("layer.delete", Value::Object(p)), - None => Mapped::Unsupported { harmless: false }, - }, - // The targeted channel of a layer is its mask (what Photoshop records after making an - // adjustment layer over a selection and discarding the mask). - Some(r) if ref_class(r).as_deref() == Some("Chnl") && matches!(target(r), Target::Ordinal(o) if o == "Trgt") => none("layer.layerMask.delete"), - Some(_) => Mapped::Unsupported { harmless: false }, - } -} - -fn quick_mask_ref() -> D { - D::Reference(vec![ - ReferenceItem::Property { class: class("Prpr"), key: code("QucM") }, - ReferenceItem::Enumerated { class: class("Dcmn"), type_id: code("Ordn"), value: code("Trgt") }, - ]) -} - -fn clear_from(d: &Descriptor) -> Mapped { - match get_ref(d, "null").map(target) { - Some(Target::Property(p)) if p == "QucM" => step("select.editInQuickMaskMode", json!({"on": false})), - None => none("edit.clear"), - _ => Mapped::Unsupported { harmless: false }, - } -} - -fn clear_to(id: &str, p: &Value) -> Option { - match id { - "select.editInQuickMaskMode" if jbool(p, "on") == Some(false) => Some(desc("null").with("null", quick_mask_ref())), - _ => None, - } -} - -/// `placeEvent`: File › Place Embedded / Linked, with the file and the recorded scale. -fn place_from(d: &Descriptor) -> Mapped { - let Some(path) = d.get("null").and_then(path_text) else { return Mapped::Unsupported { harmless: false } }; - let mut p = json!({"path": path}); - if let Some(w) = get_num(d, "Wdth") { - p["scale"] = json!(w); - } - step(if get_bool(d, "Lnkd") == Some(true) { "file.placeLinked" } else { "file.placeEmbedded" }, p) -} - -fn place_to(id: &str, p: &Value) -> Option { - let mut d = desc("null").with("null", path_value(jstr(p, "path")?)).with("FTcs", enm("QCSt", "Qcsa")); - if let Some(s) = jnum(p, "scale") { - d = d.with("Wdth", pct(s)).with("Hght", pct(s)); - } - Some(d.with("Lnkd", D::Boolean(id == "file.placeLinked")).with("Antl", D::Boolean(true))) -} - -/// `open`: File › Open of a recorded path. -fn open_from(d: &Descriptor) -> Mapped { - match d.get("null").and_then(path_text) { - Some(path) => step("file.openAs", json!({"path": path})), - None => Mapped::Unsupported { harmless: false }, - } -} - -fn open_to(_: &str, p: &Value) -> Option { - Some(desc("null").with("null", path_value(jstr(p, "path")?))) -} - -/// Save As format classes (`As`) and the extensions PhotoCraft saves them under. The first -/// extension of a class is the one exported, and the first class of an extension is the one -/// written back. `WebPFormat` is Photoshop's built-in WebP (checked against Photoshop 2026); the -/// Google classes come from the older WebPShop plug-in and are only read. -const SAVE_FORMATS: &[(&str, &[&str])] = &[ - ("Pht3", &["psd"]), - ("PNGF", &["png"]), - ("JPEG", &["jpg", "jpeg"]), - ("TIFF", &["tif", "tiff"]), - ("BMPF", &["bmp"]), - ("WebPFormat", &["webp"]), - ("Google WebPShop", &["webp"]), - ("Google WebP", &["webp"]), -]; - -fn path_extension(path: &str) -> Option { - let name = path.rsplit(['/', '\\']).next()?; - let (stem, ext) = name.rsplit_once('.')?; - (!stem.is_empty() && !ext.is_empty()).then(|| ext.to_ascii_lowercase()) -} - -/// `save`: a plain Save, or a Save As (`As` format, `In` destination, `Cpy` As a Copy). -/// Only a destination that is a file of the recorded format imports: a folder (#5430), a missing -/// or unknown format or a mismatched extension stays a kept Photoshop step, so playback stops -/// before writing rather than saving over the played file (#7102). -fn save_from(d: &Descriptor) -> Mapped { - let unsupported = Mapped::Unsupported { harmless: false }; - if d.get("As ").is_none() && d.get("In ").is_none() { - return step("file.save", json!({})); - } - // A Save As needs a format descriptor to check the destination against: without one (or - // with a format that isn't a descriptor) the step is kept. - let Some(format) = get_obj(d, "As ") else { return unsupported }; - let Some(path) = d.get("In ").and_then(path_text) else { return unsupported }; - if get_bool(d, "DIDr") == Some(true) { - return unsupported; - } - let Some(ext) = path_extension(&path) else { return unsupported }; - let class = trimmed(&format.class_id); - let Some((_, exts)) = SAVE_FORMATS.iter().find(|(c, _)| *c == class) else { return unsupported }; - if !exts.contains(&ext.as_str()) { - return unsupported; - } - step(if get_bool(d, "Cpy ") == Some(true) { "file.saveACopy" } else { "file.saveAs" }, json!({"path": path})) -} - -fn save_to(id: &str, p: &Value) -> Option { - if id == "file.save" { - return Some(desc("null")); - } - let path = jstr(p, "path")?; - let ext = path_extension(path)?; - let (class, _) = SAVE_FORMATS.iter().find(|(_, exts)| exts.contains(&ext.as_str()))?; - let d = desc("null").with("As ", D::Descriptor(desc(class))).with("In ", path_value(path)); - Some(if id == "file.saveACopy" { d.with("Cpy ", D::Boolean(true)) } else { d }) -} - -/// Photoshop's four-character condition codes that differ from the string ids. -const CONDITION_CODES: &[(&str, &str)] = &[("Lyrs", "hasLayers")]; - -/// `conditional`: Insert Conditional, with its Then and Else actions by name. -fn conditional_from(d: &Descriptor) -> Mapped { - let Some(c) = get_enum(d, "null") else { return Mapped::Unsupported { harmless: false } }; - let condition = lookup(CONDITION_CODES, &c).unwrap_or(c.as_str()); - if !crate::actions_edit_cmds::CONDITIONS.contains(&condition) { - return Mapped::Unsupported { harmless: false }; - } - let branch = |key: &str| match get_ref(d, key).map(target) { - // Clipped like the stored action names, so the load-time rename map finds it. - Some(Target::Name(n)) => Some(clip_name(&n)), - _ => None, - }; - step("actions.conditional", json!({"if": condition, "then": branch("then"), "else": branch("else")})) -} - -fn conditional_to(_: &str, p: &Value) -> Option { - let condition = jstr(p, "if")?; - let code = lookup_back(CONDITION_CODES, condition).unwrap_or(condition); - let mut d = desc("null").with("null", enm("Cndt", code)); - for key in ["then", "else"] { - if let Some(name) = jstr(p, key) { - let mut items = vec![ReferenceItem::Name { class: class("Actn"), name: UnicodeString::new_nul(name) }]; - if let Some(set) = jstr(p, "set") { - items.push(ReferenceItem::Name { class: class("ASet"), name: UnicodeString::new_nul(set) }); - } - d = d.with(key, D::Reference(items)); - } - } - Some(d) -} - -/// `close`: Photoshop's Save prompt answer becomes a Save step before the Close. -fn close_from(d: &Descriptor) -> Mapped { - if get_enum(d, "Svng").as_deref() == Some("Ys") { steps(vec![("file.save", json!({})), ("file.close", json!({}))]) } else { none("file.close") } -} - -/// A Close of an explicit document has no mapping here: written as a plain Close it would -/// close the active document on playback, so it is left to `skipUnsupported`. -fn close_to(_: &str, p: &Value) -> Option { - if p.get("document").is_some_and(|d| !d.is_null()) { - return None; - } - Some(desc("null").with("Svng", enm("YsN ", "N "))) -} - -/// `transform`: Photoshop records a Free Transform relative to the frame (offset of its centre, -/// width/height in percent, angle). A layer moved only becomes `layer.translate`; anything -/// else is `edit.transform`'s relative form; the selection's frame is `select.transformSelection`. -fn transform_from(d: &Descriptor) -> Mapped { - // No reference (a smart object replaced in place, `replaceLayer`) means the target layer. - let target_layer = [ReferenceItem::Enumerated { class: class("Lyr "), type_id: code("Ordn"), value: code("Trgt") }]; - let r: &[ReferenceItem] = get_ref(d, "null").unwrap_or(&target_layer); - let unsupported = Mapped::Unsupported { harmless: false }; - let mut p = Map::new(); - if let Some(o) = get_obj(d, "Ofst") { - let in_px = |k: &str| matches!(o.get(k), Some(D::UnitFloat { unit: PX, .. })); - if !in_px("Hrzn") || !in_px("Vrtc") { - return unsupported; - } - if let Some(x) = get_num(o, "Hrzn") { - p.insert("dx".into(), x.into()); - } - if let Some(y) = get_num(o, "Vrtc") { - p.insert("dy".into(), y.into()); - } - } - for (key, param) in [("Wdth", "scaleX"), ("Hght", "scaleY"), ("Angl", "rotate")] { - if let Some(v) = get_num(d, key) { - p.insert(param.into(), v.into()); - } - } - if d.get("Skew").is_some() || d.get("Usng").is_some() { - return unsupported; - } - // A whole-pixel move is a plain `layer.translate`; a fractional one needs `edit.transform` - // to keep its sub-pixel placement and interpolation. - let whole_pixels = ["dx", "dy"].iter().all(|k| p.get(*k).and_then(Value::as_f64).is_none_or(|v| v.fract() == 0.0)); - let geometry_only = p.keys().all(|k| k == "dx" || k == "dy") && whole_pixels; - // The resampling applies to a selection as much as to a layer (#7515). - // Photoshop's bicubic variants are kept (the transforms render them as Bicubic, and they export - // back unchanged); Automatic and Preserve Details become the nearest bicubic choice. Dropping - // them fell back to the command's default, bilinear for a selection (#8697). - let interpolation = get_enum(d, "Intr").and_then(|i| lookup(INTERPOLATION, &i)).and_then(|i| match i { - "bicubic" | "bilinear" | "nearest" | "bicubicSharper" | "bicubicSmoother" | "bicubicAutomatic" => Some(i), - "automatic" => Some("bicubicAutomatic"), - "preserveDetails" => Some("bicubic"), - _ => None, - }); - match (ref_class(r).as_deref(), target(r)) { - (Some("Chnl"), Target::Property(prop)) if prop == "fsel" => { - if let Some(i) = interpolation { - p.insert("interpolation".into(), i.into()); - } - step("select.transformSelection", Value::Object(p)) - } - (Some("Lyr"), _) => { - let Some(mut lp) = layer_target(r) else { return unsupported }; - if geometry_only { - lp.insert("dx".into(), p.get("dx").and_then(Value::as_f64).unwrap_or(0.0).into()); - lp.insert("dy".into(), p.get("dy").and_then(Value::as_f64).unwrap_or(0.0).into()); - return step("layer.translate", Value::Object(lp)); - } - lp.extend(p); - if let Some(i) = interpolation { - lp.insert("interpolation".into(), i.into()); - } - step("edit.transform", Value::Object(lp)) - } - _ => unsupported, - } -} - -fn transform_to(id: &str, p: &Value) -> Option { - let given = |k: &str| p.get(k).is_some_and(|v| !v.is_null()); - if ["quad", "corners", "matrix", "rect"].iter().any(|k| given(k)) { - return None; - } - // The descriptor scales and rotates about the centre (`FTcs` average) without skew or warp: - // another reference point, a skew or a warp would replay as a different transform (#7516, - // #7517, #7518, #7519). - let nonzero = |k: &str| p.get(k).is_some_and(|v| !v.is_null() && v.as_f64() != Some(0.0)); - let off_centre = p.get("reference").is_some_and(|v| !v.is_null() && *v != json!("center")); - if nonzero("skewX") || nonzero("skewY") || off_centre || ["warp", "style", "mesh", "grid"].iter().any(|k| given(k)) { - return None; - } - let target = match id { - // The `Trnf` descriptor has no field for a mask, Quick Mask or alpha channel target; a - // layer reference would transform the layer's pixels instead. - "edit.transform" if !pixel_target(p) => return None, - "edit.transform" => layer_ref(p)?, - "select.transformSelection" => D::Reference(vec![ReferenceItem::Property { class: class("Chnl"), key: code("fsel") }]), - _ => return None, - }; - let mut d = desc("null").with("null", target).with("FTcs", enm("QCSt", "Qcsa")); - d = d.with("Ofst", D::Descriptor(desc("Ofst").with("Hrzn", px(jnum(p, "dx").unwrap_or(0.0))).with("Vrtc", px(jnum(p, "dy").unwrap_or(0.0))))); - for (key, param) in [("Wdth", "scaleX"), ("Hght", "scaleY")] { - if let Some(v) = jnum(p, param) { - d = d.with(key, pct(v)); - } - } - if let Some(a) = jnum(p, "rotate") { - d = d.with("Angl", ang(a)); - } - if let Some(i) = jstr(p, "interpolation").and_then(|i| lookup_back(INTERPOLATION, i)) { - d = d.with("Intr", enm("Intp", i)); - } - Some(d) -} - -/// `Clcn` (Apply Image / Calculations blending) ↔ `image.applyImage`'s `blending`. -const CALC_BLEND: &[(&str, &str)] = &[ - ("Nrml", "normal"), - ("Mltp", "multiply"), - ("Scrn", "screen"), - ("Ovrl", "overlay"), - ("SftL", "softLight"), - ("HrdL", "hardLight"), - ("CDdg", "colorDodge"), - ("CBrn", "colorBurn"), - ("Drkn", "darken"), - ("Lghn", "lighten"), - ("Dfrn", "difference"), - ("Xclu", "exclusion"), - ("linearBurn", "linearBurn"), - ("linearDodge", "linearDodge"), - ("Add ", "add"), - ("Sbtr", "subtract"), -]; -const SOURCE_CHANNELS: &[(&str, &str)] = - &[("RGB", "composite"), ("CMYK", "composite"), ("Lab", "composite"), ("Trsp", "transparency"), ("Msk", "mask"), ("fsel", "selection")]; - -fn apply_image_from(d: &Descriptor) -> Mapped { - let unsupported = Mapped::Unsupported { harmless: false }; - let Some(with) = get_obj(d, "With") else { return unsupported }; - let Some(r) = get_ref(with, "T ") else { return unsupported }; - let mut source = Map::new(); - for item in r { - match item { - ReferenceItem::Enumerated { class, value, .. } if class.class_id.is("Chnl") => { - let v = trimmed(value); - let Some(channel) = lookup(SOURCE_CHANNELS, &v).or_else(|| lookup(CHANNELS, &v)) else { return unsupported }; - source.insert("channel".into(), channel.into()); - } - // A named (alpha) channel. - ReferenceItem::Name { class, name } if class.class_id.is("Chnl") => { - source.insert("channel".into(), name.to_string_lossy().into()); - } - ReferenceItem::Name { class, name } if class.class_id.is("Lyr ") => { - source.insert("layer".into(), name.to_string_lossy().into()); - } - ReferenceItem::Enumerated { class, value, .. } if class.class_id.is("Lyr ") && trimmed(value) == "Mrgd" => { - source.insert("layer".into(), "merged".into()); - } - _ => return unsupported, - } - } - if let Some(i) = get_bool(with, "Invr") { - source.insert("invert".into(), i.into()); - } - let mut p = json!({"source": source}); - if let Some(c) = get_enum(with, "Clcl") { - match lookup(CALC_BLEND, &c) { - Some(b) => p["blending"] = json!(b), - None => return unsupported, - } - } - for (key, param) in [("Scl ", "scale"), ("Ofst", "offset"), ("Opct", "opacity")] { - if let Some(v) = get_num(with, key) { - p[param] = json!(v); - } - } - if let Some(t) = get_bool(with, "PrsT") { - p["preserveTransparency"] = json!(t); - } - step("image.applyImage", p) -} - -/// Apply Image's source channel as a `Chnl` reference item. The dialog sends Channels-panel names -/// ("RGB", "Red", "Alpha 1"), which the command reads case-insensitively: the composite names map to -/// the composite, colour names to their enumeration, and any other name to a named (alpha) channel, -/// as Photoshop records it. -fn apply_image_channel(channel: &str) -> Option { - let l = channel.to_ascii_lowercase(); - let key = match l.as_str() { - "rgb" | "cmyk" | "lab" | "merged" => "composite", - "layermask" => "mask", - // Sources the command knows by keyword but Photoshop has no channel for. - "quickmask" | "quick mask" | "vectormask" | "vector mask" => return None, - other => other, - }; - Some(match lookup_back(SOURCE_CHANNELS, key).or_else(|| lookup_back(CHANNELS, key)) { - Some(chan) => ReferenceItem::Enumerated { class: class("Chnl"), type_id: code("Chnl"), value: code(chan) }, - None if !channel.trim().is_empty() => ReferenceItem::Name { class: class("Chnl"), name: UnicodeString::new_nul(channel) }, - None => return None, - }) -} - -fn apply_image_to(_: &str, p: &Value) -> Option { - // The optional blending mask has no descriptor mapping: refuse it rather than drop it, - // which would widen the edit to the whole layer. - let mask_channel = match p.get("mask") { - Some(m) => m.get("channel"), - None => p.get("maskChannel"), - }; - if mask_channel.is_some_and(|c| !(c.is_null() || c == "none" || c == "")) { - return None; - } - // The Apply Image dialog sends flat `sourceLayer`/`sourceChannel`/`sourceInvert` fields; read - // them as the command does, or the export would quietly reset them to the merged composite. - let source = crate::channel_cmds::source_spec(p, "source", "source").unwrap_or(json!({})); - // A source from another open document has no event form here: skip the step, don't rewrite it. - if source.get("document").is_some_and(|d| !d.is_null()) { - return None; - } - // A layer id or channel index has no name to record: refuse it rather than write the composite. - let not_name = |k: &str| source.get(k).is_some_and(|v| !(v.is_null() || v.is_string())); - if !source.is_object() || not_name("layer") || not_name("channel") { - return None; - } - let mut items = vec![apply_image_channel(jstr(&source, "channel").unwrap_or("composite"))?]; - match jstr(&source, "layer") { - Some("merged") | None => items.push(ReferenceItem::Enumerated { class: class("Lyr "), type_id: code("Ordn"), value: code("Mrgd") }), - Some(name) => items.push(ReferenceItem::Name { class: class("Lyr "), name: UnicodeString::new_nul(name) }), - } - let mut with = desc("null").with("T ", D::Reference(items)); - if let Some(i) = jbool(&source, "invert") { - with = with.with("Invr", D::Boolean(i)); - } - with = with.with("Clcl", enm("Clcn", lookup_back(CALC_BLEND, jstr(p, "blending").unwrap_or("multiply"))?)); - if let Some(v) = jnum(p, "opacity") { - with = with.with("Opct", pct(v)); - } - if let Some(v) = jnum(p, "scale") { - with = with.with("Scl ", D::Double(v)); - } - if let Some(v) = jnum(p, "offset") { - with = with.with("Ofst", D::Double(v)); - } - if let Some(t) = jbool(p, "preserveTransparency") { - with = with.with("PrsT", D::Boolean(t)); - } - Some(desc("null").with("With", D::Descriptor(with))) -} - -const WEB_FORMATS: &[(&str, &str)] = &[("PN24", "png24"), ("PN8", "png8"), ("JPEG", "jpeg"), ("GIFf", "gif"), ("WBMP", "wbmp")]; - -/// `export` (Save for Web): needs the destination path (`In`), as the command writes a file. -fn export_from(d: &Descriptor) -> Mapped { - let unsupported = Mapped::Unsupported { harmless: false }; - let Some(u) = get_obj(d, "Usng") else { return unsupported }; - let Some(path) = d.get("In ").and_then(path_text) else { return unsupported }; - let mut p = json!({"path": path}); - if let Some(f) = get_enum(u, "Fmt ") { - match lookup(WEB_FORMATS, &f) { - Some(f) => p["format"] = json!(f), - None => return unsupported, - } - } - for (key, param) in [("Intr", "interlaced"), ("Trns", "transparency"), ("EICC", "embedIcc"), ("Prgr", "progressive"), ("Optm", "optimized")] { - if let Some(b) = get_bool(u, key) { - p[param] = json!(b); - } - } - for (key, param) in [("Qlty", "quality"), ("NCol", "colors")] { - if let Some(v) = get_num(u, key) { - p[param] = json!(v); - } - } - if get_bool(u, "Mtt ") == Some(false) { - p["matte"] = json!("none"); - } else if let (Some(r), Some(g), Some(b)) = (get_num(u, "MttR"), get_num(u, "MttG"), get_num(u, "MttB")) { - p["matte"] = - json!(format!("#{:02x}{:02x}{:02x}", r.round().clamp(0.0, 255.0) as u8, g.round().clamp(0.0, 255.0) as u8, b.round().clamp(0.0, 255.0) as u8)); - } - step("file.export.saveForWebLegacy", p) -} - -fn export_to(_: &str, p: &Value) -> Option { - let path = jstr(p, "path")?; - let mut u = desc("SaveForWeb").with("Op ", enm("SWOp", "OpSa")).with("Fmt ", enm("IRFm", lookup_back(WEB_FORMATS, jstr(p, "format").unwrap_or("png24"))?)); - for (key, param, default) in [ - ("Intr", "interlaced", false), - ("Trns", "transparency", true), - ("EICC", "embedIcc", false), - ("Prgr", "progressive", false), - ("Optm", "optimized", true), - ] { - u = u.with(key, D::Boolean(jbool(p, param).unwrap_or(default))); - } - if let Some(q) = jnum(p, "quality") { - u = u.with("Qlty", long(q)); - } - if let Some(c) = jnum(p, "colors") { - u = u.with("NCol", long(c)); - } - match jstr(p, "matte") { - Some("none") => u = u.with("Mtt ", D::Boolean(false)), - matte => { - let c = color_desc(matte.unwrap_or("#ffffff"))?; - u = u - .with("Mtt ", D::Boolean(true)) - .with("MttR", get_num(&c, "Rd ").map(long)?) - .with("MttG", get_num(&c, "Grn ").map(long)?) - .with("MttB", get_num(&c, "Bl ").map(long)?); - } - } - Some(desc("null").with("Usng", D::Descriptor(u)).with("In ", path_value(path))) -} - -fn delete_to(id: &str, p: &Value) -> Option { - Some(match id { - "edit.clear" => desc("null"), - "layer.delete" => desc("null").with("null", layer_ref(p)?), - "layer.layerMask.delete" => desc("null").with("null", target_ref("Chnl")), - _ => return None, - }) -} - -/// `hide` / `show` take a list of references (or one). -fn visibility_from(d: &Descriptor, id: &str) -> Mapped { - let refs: Vec<&[ReferenceItem]> = match d.get("null") { - Some(D::List(l)) => l.iter().filter_map(|v| if let D::Reference(r) = v { Some(r.as_slice()) } else { None }).collect(), - Some(D::Reference(r)) => vec![r.as_slice()], - _ => return Mapped::Unsupported { harmless: false }, - }; - let mut v = Vec::new(); - for r in refs { - match layer_target(r) { - Some(p) => v.push((id, Value::Object(p))), - None => return Mapped::Unsupported { harmless: false }, - } - } - if v.is_empty() { Mapped::Unsupported { harmless: false } } else { steps(v) } -} - -fn visibility_to(_: &str, p: &Value) -> Option { - Some(desc("null").with("null", D::List(vec![layer_ref(p)?]))) -} - -fn move_from(d: &Descriptor) -> Mapped { - let Some(r) = get_ref(d, "null") else { return Mapped::Unsupported { harmless: false } }; - // The selection outline nudged. - if ref_class(r).as_deref() == Some("Chnl") && matches!(target(r), Target::Property(p) if p == "fsel") { - return match get_obj(d, "T ") { - Some(t) if matches!(t.get("Hrzn"), Some(D::UnitFloat { unit: PX, .. })) => match (get_num(t, "Hrzn"), get_num(t, "Vrtc")) { - (Some(dx), Some(dy)) => step("select.transformSelection", json!({"dx": dx.round(), "dy": dy.round()})), - _ => Mapped::Unsupported { harmless: false }, - }, - _ => Mapped::Unsupported { harmless: false }, - }; - } - if ref_class(r).as_deref() != Some("Lyr") { - return Mapped::Unsupported { harmless: false }; - } - let Some(mut p) = layer_target(r) else { return Mapped::Unsupported { harmless: false } }; - match d.get("T ") { - Some(D::Descriptor(t)) => { - let unit = |k: &str| match t.get(k) { - Some(D::UnitFloat { unit, .. }) => Some(*unit), - _ => None, - }; - let (Some(dx), Some(dy)) = (get_num(t, "Hrzn"), get_num(t, "Vrtc")) else { return Mapped::Unsupported { harmless: false } }; - match (unit("Hrzn"), unit("Vrtc")) { - (Some(PX), Some(PX)) => { - p.insert("dx".into(), dx.round().into()); - p.insert("dy".into(), dy.round().into()); - } - // A nudge recorded with the rulers in other units: points, converted to pixels - // at the resolution of the document the action plays on. - (Some(PT), Some(PT)) => { - p.insert("dx".into(), dx.into()); - p.insert("dy".into(), dy.into()); - p.insert("units".into(), "pt".into()); - } - _ => return Mapped::Unsupported { harmless: false }, - } - step("layer.translate", Value::Object(p)) - } - Some(D::Reference(t)) => { - let id = match target(t) { - Target::Ordinal(o) if o == "Frnt" => "layer.arrange.bringToFront", - Target::Ordinal(o) if o == "Back" => "layer.arrange.sendToBack", - Target::Ordinal(o) if o == "Nxt" => "layer.arrange.bringForward", - Target::Ordinal(o) if o == "Prvs" => "layer.arrange.sendBackward", - Target::Offset(1) => "layer.arrange.bringForward", - Target::Offset(-1) => "layer.arrange.sendBackward", - // Index 0 is the bottom of the stack. - Target::Index(0) => "layer.arrange.sendToBack", - _ => return Mapped::Unsupported { harmless: false }, - }; - step(id, Value::Object(p)) - } - _ => Mapped::Unsupported { harmless: false }, - } -} - -fn move_to(id: &str, p: &Value) -> Option { - let ord = |o: &str| D::Reference(vec![ReferenceItem::Enumerated { class: class("Lyr "), type_id: code("Ordn"), value: code(o) }]); - let t = match id { - "layer.translate" => { - let unit = match jstr(p, "units") { - None | Some("px") => PX, - Some("pt") => PT, - Some(_) => return None, - }; - let v = |k: &str| D::UnitFloat { unit, value: jnum(p, k).unwrap_or(0.0) }; - D::Descriptor(desc("Ofst").with("Hrzn", v("dx")).with("Vrtc", v("dy"))) - } - "layer.arrange.bringToFront" => ord("Frnt"), - "layer.arrange.sendToBack" => ord("Back"), - "layer.arrange.bringForward" => ord("Nxt "), - "layer.arrange.sendBackward" => ord("Prvs"), - _ => return None, - }; - Some(desc("null").with("null", layer_ref(p)?).with("T ", t)) -} - -fn duplicate_from(d: &Descriptor) -> Mapped { - let Some(r) = get_ref(d, "null") else { return Mapped::Unsupported { harmless: false } }; - match ref_class(r).as_deref() { - Some("Lyr") => { - // A `T` document reference (duplicate into another open document) has no - // replayable meaning here: keep the step verbatim rather than misplay it. - if get_ref(d, "T ").is_some() { - return Mapped::Unsupported { harmless: false }; - } - let Some(mut p) = layer_target(r) else { return Mapped::Unsupported { harmless: false } }; - if let Some(n) = get_text(d, "Nm ") { - p.insert("name".into(), n.into()); - } - step("layer.duplicate", Value::Object(p)) - } - Some("Dcmn") => { - let mut p = Map::new(); - if let Some(n) = get_text(d, "Nm ") { - p.insert("name".into(), n.into()); - } - if let Some(m) = get_bool(d, "Mrgd") { - p.insert("mergedOnly".into(), m.into()); - } - step("image.duplicate", Value::Object(p)) - } - _ => Mapped::Unsupported { harmless: false }, - } -} - -fn duplicate_to(id: &str, p: &Value) -> Option { - // Duplicate into a new document is a `Mk` (handled above); let it fall through. - if id == "layer.duplicate" && jstr(p, "document") == Some("new") { - return None; - } - // Photoshop's Duplicate has no in-place flag: a plain one would place the artboard copy beside - // the original on playback. - if id == "layer.duplicate" && jbool(p, "inPlace") == Some(true) { - return None; - } - let mut d = match id { - "layer.duplicate" => desc("null").with("null", layer_ref(p)?), - "image.duplicate" => { - desc("null").with("null", D::Reference(vec![ReferenceItem::Enumerated { class: class("Dcmn"), type_id: Id::new("Ordn"), value: Id::new("Frst") }])) - } - _ => return None, - }; - if let Some(n) = jstr(p, "name") { - d = d.with("Nm ", text(n)); - } - if let Some(m) = jbool(p, "mergedOnly") { - d = d.with("Mrgd", D::Boolean(m)); - } - Some(d) -} - -/// Only a comp name in the active document is portable across action playback. -fn apply_comp_from(d: &Descriptor) -> Mapped { - match get_ref(d, "null") { - Some([ReferenceItem::Name { class, name }]) if trimmed(&class.class_id) == "compsClass" => { - step("layerComp.apply", json!({"comp": name.to_string_lossy()})) - } - _ => Mapped::Unsupported { harmless: false }, - } -} - -fn apply_comp_to(_: &str, p: &Value) -> Option { - Some(desc("null").with("null", name_ref("compsClass", jstr(p, "comp")?))) -} - -fn play_from(d: &Descriptor) -> Mapped { - match get_ref(d, "null").map(target) { - Some(Target::Name(n)) => step("actions.play", json!({"action": clip_name(&n)})), - _ => Mapped::Unsupported { harmless: false }, - } -} - -fn play_to(_: &str, p: &Value) -> Option { - let name = jstr(p, "action")?; - // The Play Action descriptor written here carries no starting step, so a call from a later step is not a whole call. - if p.get("from").is_some_and(|v| !v.is_null() && v.as_f64() != Some(0.0)) { - return None; - } - let mut items = vec![ReferenceItem::Name { class: class("Actn"), name: UnicodeString::new_nul(name) }]; - if let Some(set) = jstr(p, "set") { - items.push(ReferenceItem::Name { class: class("ASet"), name: UnicodeString::new_nul(set) }); - } - Some(desc("null").with("null", D::Reference(items))) -} - -fn fill_from(d: &Descriptor) -> Mapped { - if let Some(from) = get_obj(d, "From") { - // The Paint Bucket tool's click: its point is in pixels, or in percent of the canvas - // (not replayable without the document size). - let in_px = |k: &str| matches!(from.get(k), Some(D::UnitFloat { unit: PX, .. })); - let (Some(x), Some(y)) = (get_num(from, "Hrzn"), get_num(from, "Vrtc")) else { return Mapped::Unsupported { harmless: false } }; - if !in_px("Hrzn") || !in_px("Vrtc") { - return Mapped::Unsupported { harmless: false }; - } - let mut p = json!({"x": x.round(), "y": y.round()}); - match get_enum(d, "Usng").as_deref() { - Some("FrgC") | None => {} - Some("Pttn") => p["contents"] = json!("pattern"), - Some("Clr") => match get_obj(d, "Clr ").and_then(color_hex) { - Some(c) => p["color"] = json!(c), - None => return Mapped::Unsupported { harmless: false }, - }, - Some(_) => return Mapped::Unsupported { harmless: false }, - } - if let Some(t) = get_num(d, "Tlrn") { - p["tolerance"] = json!(t); - } - if let Some(c) = get_bool(d, "Cntg") { - p["contiguous"] = json!(c); - } - if let Some(a) = get_bool(d, "AntA") { - p["antiAlias"] = json!(a); - } - if let Some(m) = get_bool(d, "Mrgd") { - p["sampleAllLayers"] = json!(m); - } - if let Some(o) = get_num(d, "Opct") { - p["opacity"] = json!(o); - } - return step("paint.bucket", p); - } - let Some(contents) = get_enum(d, "Usng").and_then(|u| lookup(FILL_CONTENTS, &u)) else { return Mapped::Unsupported { harmless: false } }; - let mut p = json!({"contents": contents}); - if contents == "color" { - match get_obj(d, "Clr ").and_then(color_hex) { - Some(c) => p["color"] = json!(c), - None => return Mapped::Unsupported { harmless: false }, - } - } - if let Some(o) = get_num(d, "Opct") { - p["opacity"] = json!(o); - } - if let Some(m) = get_enum(d, "Md ") { - match blend_label(&m) { - Some(l) => p["mode"] = json!(l), - None => return Mapped::Unsupported { harmless: false }, - } - } - if let Some(t) = get_bool(d, "PrsT") { - p["preserveTransparency"] = json!(t); - } - step("edit.fill", p) -} - -fn fill_to(id: &str, p: &Value) -> Option { - if id == "paint.bucket" { - let mut d = desc("null").with("From", D::Descriptor(desc("Pnt ").with("Hrzn", px(jnum(p, "x")?)).with("Vrtc", px(jnum(p, "y")?)))); - d = d.with("Tlrn", long(jnum(p, "tolerance").unwrap_or(32.0))).with("AntA", D::Boolean(jbool(p, "antiAlias").unwrap_or(true))); - // `source` is the command's older name for `contents`. - d = if p.get("contents").or_else(|| p.get("source")).and_then(Value::as_str) == Some("pattern") { - // `Pttn` names no pattern and holds no placement: a chosen pattern, a scale, an angle - // or a phase would replay with the current pattern at its defaults (#7543, #7544, - // #7545, #7546). - let num = |k: &str, default: f64| p.get(k).is_some_and(|v| !v.is_null() && v.as_f64() != Some(default)); - let phase = p.get("phase").is_some_and(|v| !v.is_null() && v.as_array().is_none_or(|a| a.iter().any(|c| c.as_f64() != Some(0.0)))); - if p.get("pattern").is_some_and(|v| !v.is_null()) || num("scale", 100.0) || num("angle", 0.0) || phase { - return None; - } - d.with("Usng", enm("FlCn", "Pttn")) - } else { - // An explicit colour overrides the foreground (#7199): it travels as Fill's `Clr `. - match bucket_color(p.get("color"))? { - Some(c) => d.with("Usng", enm("FlCn", "Clr ")).with("Clr ", D::Descriptor(c)), - None => d.with("Usng", enm("FlCn", "FrgC")), - } - }; - if let Some(o) = jnum(p, "opacity") { - d = d.with("Opct", pct(o)); - } - if let Some(c) = jbool(p, "contiguous") { - d = d.with("Cntg", D::Boolean(c)); - } - if let Some(m) = jbool(p, "sampleAllLayers") { - d = d.with("Mrgd", D::Boolean(m)); - } - return Some(d); - } - let contents = jstr(p, "contents").unwrap_or("color"); - let mut d = desc("null").with("Usng", enm("FlCn", lookup_back(FILL_CONTENTS, contents)?)); - if contents == "color" { - d = d.with("Clr ", D::Descriptor(color_desc(jstr(p, "color")?)?)); - } - if let Some(o) = jnum(p, "opacity") { - d = d.with("Opct", pct(o)); - } - if let Some(m) = jstr(p, "mode") { - d = d.with("Md ", enm("BlnM", blend_ps(m)?)); - } - if let Some(t) = jbool(p, "preserveTransparency") { - d = d.with("PrsT", D::Boolean(t)); - } - Some(d) -} - -/// The Paint Bucket's `color` as `paint.bucket` reads it (`[r, g, b(, a)]` in 0..=1 or -/// `#rrggbb(aa)`): `Some(None)` when it fills with the foreground (no colour, or a string the -/// command doesn't read), `None` when the colour can't be written (not opaque, or outside 0..=1). -fn bucket_color(v: Option<&Value>) -> Option> { - let rgba = match v { - Some(Value::Array(a)) if a.len() >= 3 => { - let c: Vec = a.iter().map(|x| x.as_f64().unwrap_or(0.0)).collect(); - [*c.first()?, *c.get(1)?, *c.get(2)?, c.get(3).copied().unwrap_or(1.0)] - } - Some(Value::String(h)) => { - let h = h.trim_start_matches('#'); - let c = |i: usize| h.get(i..i + 2).and_then(|x| u8::from_str_radix(x, 16).ok()).map(|v| f64::from(v) / 255.0); - let (Some(r), Some(g), Some(b)) = (c(0), c(2), c(4)) else { return Some(None) }; - [r, g, b, c(6).unwrap_or(1.0)] - } - _ => return Some(None), - }; - if rgba[3] != 1.0 || !rgba.iter().all(|v| (0.0..=1.0).contains(v)) { - return None; - } - Some(Some(desc("RGBC").with("Rd ", D::Double(rgba[0] * 255.0)).with("Grn ", D::Double(rgba[1] * 255.0)).with("Bl ", D::Double(rgba[2] * 255.0)))) -} - -/// Preserve the command's effective integer width instead of rounding its input again. -fn stroke_to(_: &str, p: &Value) -> Option { - if !pixel_target(p) { - return None; - } - let mut params = if p.is_null() { Map::new() } else { p.as_object()?.clone() }; - params.insert("width".into(), Value::from(crate::extra_cmds::stroke_width(p))); - fields_to(&Value::Object(params), STROKE, desc("null")) -} - -const STROKE: &[F] = &[ - F("Wdth", "width", Kind::Long), - F("Lctn", "location", Kind::Enum("StrL", STROKE_LOCATION)), - F("Opct", "opacity", Kind::Pct), - F("Md ", "mode", Kind::Blend), - F("Clr ", "color", Kind::Color), - F("PrsT", "preserveTransparency", Kind::Bool), -]; - -/// Whether an event's `null` reference targets a layer (Edit › Transform) rather than the -/// document (Image › Image Rotation). -fn targets_layer(d: &Descriptor) -> bool { - get_ref(d, "null").and_then(ref_class).as_deref() == Some("Lyr") -} - -fn rotate_from(d: &Descriptor) -> Mapped { - let Some(angle) = get_num(d, "Angl") else { return Mapped::Unsupported { harmless: false } }; - let a = angle.rem_euclid(360.0); - let (layer, doc) = if (a - 90.0).abs() < 1e-6 { - ("edit.transform.rotate90Cw", "image.imageRotation.90cw") - } else if (a - 270.0).abs() < 1e-6 { - ("edit.transform.rotate90Ccw", "image.imageRotation.90ccw") - } else if (a - 180.0).abs() < 1e-6 { - ("edit.transform.rotate180", "image.imageRotation.180") - } else if targets_layer(d) { - return Mapped::Unsupported { harmless: false }; - } else { - let mut p = json!({"angle": angle.abs(), "direction": if angle < 0.0 { "ccw" } else { "cw" }}); - if let Some(i) = get_enum(d, "Intr").and_then(|i| lookup(INTERPOLATION, &i)).filter(|i| matches!(*i, "bicubic" | "bilinear" | "nearest")) { - p["interpolation"] = i.into(); - } - return step("image.rotation.arbitrary", p); - }; - none(if targets_layer(d) { layer } else { doc }) -} - -fn rotate_to(id: &str, p: &Value) -> Option { - let (angle, layer) = match id { - "edit.transform.rotate90Cw" => (90.0, true), - "edit.transform.rotate90Ccw" => (-90.0, true), - "edit.transform.rotate180" => (180.0, true), - "image.imageRotation.90cw" => (90.0, false), - "image.imageRotation.90ccw" => (-90.0, false), - "image.imageRotation.180" => (180.0, false), - "image.rotation.arbitrary" => (jnum(p, "angle")? * if jstr(p, "direction") == Some("ccw") { -1.0 } else { 1.0 }, false), - _ => return None, - }; - let mut d = desc("null"); - if layer { - d = d.with("null", target_ref("Lyr ")); - } - d = d.with("Angl", ang(angle)); - if id == "image.rotation.arbitrary" - && let Some(i) = p.get("interpolation") - { - // The command resamples with nearest, bilinear or bicubic; any other value can't be - // carried faithfully, so refuse rather than replay with a different interpolation. - let i = match i.as_str()? { - "nearestNeighbor" => "nearest", - i @ ("bicubic" | "bilinear" | "nearest") => i, - _ => return None, - }; - d = d.with("Intr", enm("Intp", lookup_back(INTERPOLATION, i)?)); - } - Some(d) -} - -fn flip_from(d: &Descriptor) -> Mapped { - let Some(axis) = get_enum(d, "Axis") else { return Mapped::Unsupported { harmless: false } }; - let horizontal = axis == "Hrzn"; - none(match (targets_layer(d), horizontal) { - (true, true) => "edit.transform.flipHorizontal", - (true, false) => "edit.transform.flipVertical", - (false, true) => "image.imageRotation.flipCanvasHorizontal", - (false, false) => "image.imageRotation.flipCanvasVertical", - }) -} - -fn flip_to(id: &str, _: &Value) -> Option { - let (layer, axis) = match id { - "edit.transform.flipHorizontal" => (true, "Hrzn"), - "edit.transform.flipVertical" => (true, "Vrtc"), - "image.imageRotation.flipCanvasHorizontal" => (false, "Hrzn"), - "image.imageRotation.flipCanvasVertical" => (false, "Vrtc"), - _ => return None, - }; - let mut d = desc("null"); - if layer { - d = d.with("null", target_ref("Lyr ")); - } - Some(d.with("Axis", enm("Ornt", axis))) -} - -fn convert_mode_from(d: &Descriptor) -> Mapped { - if let Some(depth) = get_num(d, "Dpth") { - return match depth as i64 { - 8 => none("image.mode.bits8"), - 16 => none("image.mode.bits16"), - 32 => none("image.mode.bits32"), - _ => Mapped::Unsupported { harmless: false }, - }; - } - // The mode as an enumeration (`ClrS.Grys`), a class (`Grys`), or an object of the mode's - // class holding its options (`BtmM {Rslt, Mthd}`, `Grys {Rt}` from Bitmap). - let (mode, options) = match d.get("T ") { - Some(D::Enumerated { value, .. }) => (trimmed(value), None), - Some(D::Class(c)) => (trimmed(&c.class_id), None), - Some(D::Descriptor(o)) => (trimmed(&o.class_id), Some(o)), - _ => return Mapped::Unsupported { harmless: false }, - }; - if mode == "BtmM" { - return bitmap_from(options); - } - // Bitmap to Grayscale records a size ratio; only 1 keeps the pixels as they are. - if options.and_then(|o| get_num(o, "Rt ")).is_some_and(|r| (r - 1.0).abs() > 1e-9) { - return Mapped::Unsupported { harmless: false }; - } - match lookup(MODES, &mode) { - Some(m) => none(&format!("image.mode.{m}")), - None => Mapped::Unsupported { harmless: false }, - } -} - -const BITMAP_METHOD: &[(&str, &str)] = &[("Thrh", "threshold"), ("PtnD", "pattern"), ("DfnD", "diffusion")]; - -/// Image › Mode › Bitmap. Its Output resolution resamples the image, keeping the print size, -/// before the conversion; at the document's own resolution that is a no-op. Halftone screens -/// and custom patterns stay unsupported. -fn bitmap_from(options: Option<&Descriptor>) -> Mapped { - let Some(o) = options else { return none("image.mode.bitmap") }; - let method = match get_enum(o, "Mthd") { - None => "diffusion", - Some(m) => match lookup(BITMAP_METHOD, &m) { - Some(m) => m, - None => return Mapped::Unsupported { harmless: false }, - }, - }; - let convert = ("image.mode.bitmap", json!({"method": method})); - match get_num(o, "Rslt") { - Some(r) => steps(vec![("image.imageSize", json!({"resolution": r, "resample": "bicubic", "keepPrintSize": true})), convert]), - None => steps(vec![convert]), - } -} - -fn bitmap_to(p: &Value) -> Option { - let method = lookup_back(BITMAP_METHOD, jstr(p, "method").unwrap_or("diffusion"))?; - Some(desc("null").with("T ", D::Descriptor(desc("BtmM").with("Mthd", enm("Mthd", method))))) -} - -fn convert_mode_to(id: &str, p: &Value) -> Option { - Some(match id { - "image.mode.bits8" => desc("null").with("Dpth", long(8.0)), - "image.mode.bits16" => desc("null").with("Dpth", long(16.0)), - "image.mode.bits32" => desc("null").with("Dpth", long(32.0)), - "image.mode.bitmap" => bitmap_to(p)?, - _ => desc("null").with("T ", enm("ClrS", lookup_back(MODES, id.strip_prefix("image.mode.")?)?)), - }) -} - -fn canvas_size_from(d: &Descriptor) -> Mapped { - let mut p = Map::new(); - for (k, param) in [("Wdth", "width"), ("Hght", "height")] { - match d.get(k) { - Some(D::UnitFloat { unit: PX, value }) => { - p.insert(param.into(), value.round().into()); - } - Some(_) => return Mapped::Unsupported { harmless: false }, - None => {} - } - } - if let Some(r) = get_bool(d, "Rltv") { - p.insert("relative".into(), r.into()); - } - let v = get_enum(d, "Vrtc").unwrap_or_else(|| "Cntr".into()); - let h = get_enum(d, "Hrzn").unwrap_or_else(|| "Cntr".into()); - let anchor = match (v.as_str(), h.as_str()) { - ("Top", "Left") => "topLeft", - ("Top", "Cntr") => "top", - ("Top", "Rght") => "topRight", - ("Cntr", "Left") => "left", - ("Cntr", "Cntr") => "center", - ("Cntr", "Rght") => "right", - ("Bttm", "Left") => "bottomLeft", - ("Bttm", "Cntr") => "bottom", - ("Bttm", "Rght") => "bottomRight", - _ => return Mapped::Unsupported { harmless: false }, - }; - p.insert("anchor".into(), anchor.into()); - if let Some(c) = get_enum(d, "canvasExtensionColorType") { - match lookup(EXTENSION, &c) { - Some(c) => { - p.insert("extensionColor".into(), c.into()); - } - None => match get_obj(d, "canvasExtensionColor").and_then(color_hex) { - Some(hex) => { - p.insert("extensionColor".into(), hex.into()); - } - None => return Mapped::Unsupported { harmless: false }, - }, - } - } - step("image.canvasSize", Value::Object(p)) -} - -fn canvas_size_to(_: &str, p: &Value) -> Option { - let anchor = jstr(p, "anchor").unwrap_or("center"); - let v = if anchor.starts_with("top") { - "Top " - } else if anchor.starts_with("bottom") { - "Bttm" - } else { - "Cntr" - }; - let h = if anchor.to_ascii_lowercase().ends_with("left") { - "Left" - } else if anchor.to_ascii_lowercase().ends_with("right") { - "Rght" - } else { - "Cntr" - }; - let mut d = desc("null"); - if let Some(r) = jbool(p, "relative") { - d = d.with("Rltv", D::Boolean(r)); - } - if let Some(w) = jnum(p, "width") { - d = d.with("Wdth", px(w)); - } - if let Some(hh) = jnum(p, "height") { - d = d.with("Hght", px(hh)); - } - d = d.with("Hrzn", enm("HrzL", h)).with("Vrtc", enm("VrtL", v)); - if let Some(c) = jstr(p, "extensionColor") { - d = match lookup_back(EXTENSION, c) { - Some(e) => d.with("canvasExtensionColorType", enm("canvasExtensionColorType", e)), - None => d.with("canvasExtensionColorType", enm("canvasExtensionColorType", "Othr")).with("canvasExtensionColor", D::Descriptor(color_desc(c)?)), - }; - } - Some(d) -} - -fn image_size_from(d: &Descriptor) -> Mapped { - let mut p = Map::new(); - let mut percent: Option = None; - for (k, param) in [("Wdth", "width"), ("Hght", "height")] { - match d.get(k) { - Some(D::UnitFloat { unit: PX, value }) => { - p.insert(param.into(), value.round().into()); - } - // Percent scales both sides at playback; two different percentages, or physical - // units, need the document's size and resolution and stay unsupported. - Some(D::UnitFloat { unit: PCT, value }) => match percent { - Some(other) if (other - value).abs() > 1e-9 => return Mapped::Unsupported { harmless: false }, - _ => percent = Some(*value), - }, - Some(_) => return Mapped::Unsupported { harmless: false }, - None => {} - } - } - if let Some(pc) = percent { - p.insert("percent".into(), pc.into()); - } - if let Some(r) = get_num(d, "Rslt") { - p.insert("resolution".into(), r.into()); - } - if let Some(i) = get_enum(d, "Intr") { - match lookup(INTERPOLATION, &i) { - Some(i) => { - p.insert("resample".into(), i.into()); - // Resample on with only the resolution changed: Photoshop keeps the print size. - if p.contains_key("resolution") && !p.contains_key("width") && !p.contains_key("height") && !p.contains_key("percent") { - p.insert("keepPrintSize".into(), true.into()); - } - } - None => return Mapped::Unsupported { harmless: false }, - } - } else if p.contains_key("resolution") && !p.contains_key("width") && !p.contains_key("height") && !p.contains_key("percent") { - p.insert("resample".into(), "none".into()); - } - if p.is_empty() { - return Mapped::Unsupported { harmless: false }; - } - step("image.imageSize", Value::Object(p)) -} - -/// Shadows/Highlights (`adaptCorrect`, #5830): the shadow and highlight tones are `shadowMode` -/// and `highlightMode` objects (amount and width in %, radius in px), then the black and white -/// clips (%), midtone contrast (`center`) and colour correction. Each key is read as its char ID -/// or its string ID, whichever the file used; absent keys keep the command's defaults. -const SHADOWS_HIGHLIGHTS_TONES: [(&str, &str, &str); 2] = [("sdwM", "shadowMode", "shadow"), ("hglM", "highlightMode", "highlight")]; -const SHADOWS_HIGHLIGHTS_TONE: [(&str, &str, &str); 3] = [("Amnt", "amount", "Amount"), ("Wdth", "width", "Tone"), ("Rds ", "radius", "Radius")]; -const SHADOWS_HIGHLIGHTS: [(&str, &str, &str); 4] = - [("BlcC", "blackClip", "blackClip"), ("WhtC", "whiteClip", "whiteClip"), ("Cntr", "center", "midtone"), ("ClrC", "colorCorrection", "color")]; - -fn shadows_highlights_from(d: &Descriptor) -> Mapped { - let mut m = Map::new(); - for (code, name, prefix) in SHADOWS_HIGHLIGHTS_TONES { - let Some(t) = get_obj(d, code).or_else(|| get_obj(d, name)) else { continue }; - for (code, name, suffix) in SHADOWS_HIGHLIGHTS_TONE { - if let Some(v) = get_num(t, code).or_else(|| get_num(t, name)) { - m.insert(format!("{prefix}{suffix}"), Value::from(v)); - } - } - } - for (code, name, param) in SHADOWS_HIGHLIGHTS { - if let Some(v) = get_num(d, code).or_else(|| get_num(d, name)) { - m.insert(param.into(), Value::from(v)); - } - } - step("image.adjustments.shadowsHighlights", Value::Object(m)) -} - -fn shadows_highlights_to(_: &str, p: &Value) -> Option { - let mut d = desc("null"); - for (_, name, prefix) in SHADOWS_HIGHLIGHTS_TONES { - let mut t = desc("adaptCorrectTones"); - for (_, key, suffix) in SHADOWS_HIGHLIGHTS_TONE { - if let Some(v) = jnum(p, &format!("{prefix}{suffix}")) { - t = t.with(key, if suffix == "Radius" { long(v) } else { pct(v) }); - } - } - d = d.with(name, D::Descriptor(t)); - } - for (_, key, param) in SHADOWS_HIGHLIGHTS { - if let Some(v) = jnum(p, param) { - d = d.with(key, if matches!(param, "midtone" | "color") { long(v) } else { D::Double(v) }); - } - } - Some(d) -} - -fn image_size_to(_: &str, p: &Value) -> Option { - // Resolution only with Resample on imports as keep-print-size; a command without it cannot be told apart. - if jnum(p, "resolution").is_some() - && jnum(p, "width").is_none() - && jnum(p, "height").is_none() - && jnum(p, "percent").is_none() - && jstr(p, "resample").is_some_and(|r| r != "none") - && jbool(p, "keepPrintSize") != Some(true) - { - return None; - } - let mut d = desc("null"); - // `resample: "none"` changes the resolution only and the command ignores any size then. The - // descriptor has no "none" (it is the absence of `Intr`), so writing the ignored size would - // turn the step into a pixel resize on playback (#7189). - let resolution_only = jstr(p, "resample") == Some("none"); - if resolution_only && jnum(p, "resolution").is_none() { - // Nothing left to record: the step changes nothing. - return None; - } - if let Some(pc) = jnum(p, "percent").filter(|_| !resolution_only) { - d = d.with("Wdth", pct(pc)).with("Hght", pct(pc)).with("CnsP", D::Boolean(true)); - } - if let Some(w) = jnum(p, "width").filter(|_| !resolution_only) { - d = d.with("Wdth", px(w)); - } - if let Some(h) = jnum(p, "height").filter(|_| !resolution_only) { - d = d.with("Hght", px(h)); - } - if let Some(r) = jnum(p, "resolution") { - d = d.with("Rslt", D::UnitFloat { unit: *b"#Rsl", value: r }); - } - if let Some(i) = jstr(p, "resample").filter(|r| *r != "none") { - d = d.with("Intr", enm("Intp", lookup_back(INTERPOLATION, i)?)); - } - Some(d) -} - -fn crop_from(d: &Descriptor) -> Mapped { - let mut p = Map::new(); - if let Some(t) = get_obj(d, "To ") { - // Pixels only, like Canvas Size: a side in percent or points needs the document's size - // or resolution and must not be played as pixels. - let side = |k: &str| match t.get(k) { - Some(D::UnitFloat { unit: PX, value }) if value.is_finite() => Some(*value), - _ => None, - }; - let (Some(top), Some(left), Some(bottom), Some(right)) = (side("Top "), side("Left"), side("Btom"), side("Rght")) else { - return Mapped::Unsupported { harmless: false }; - }; - p.insert("x".into(), left.round().into()); - p.insert("y".into(), top.round().into()); - p.insert("width".into(), (right - left).round().into()); - p.insert("height".into(), (bottom - top).round().into()); - } - if let Some(a) = get_num(d, "Angl") { - p.insert("angle".into(), a.into()); - } - if let Some(del) = get_bool(d, "Dlt ") { - p.insert("deleteCroppedPixels".into(), del.into()); - } - step("image.crop", Value::Object(p)) -} - -fn crop_to(_: &str, p: &Value) -> Option { - // The W x H x Resolution output options have no field here: refuse rather than export a plain - // rectangle crop that keeps the old size and resolution on replay. - if ["targetWidth", "targetHeight", "resolution"].iter().any(|k| p.get(k).is_some_and(|v| !v.is_null())) { - return None; - } - let mut d = desc("null"); - if let (Some(x), Some(y), Some(w), Some(h)) = (jnum(p, "x"), jnum(p, "y"), jnum(p, "width"), jnum(p, "height")) { - d = d.with("To ", D::Descriptor(desc("Rctn").with("Top ", px(y)).with("Left", px(x)).with("Btom", px(y + h)).with("Rght", px(x + w)))); - } - if let Some(a) = jnum(p, "angle") { - d = d.with("Angl", ang(a)); - } - if let Some(del) = jbool(p, "deleteCroppedPixels") { - d = d.with("Dlt ", D::Boolean(del)); - } - Some(d) -} - -fn stop_from(d: &Descriptor) -> Mapped { - step(STOP_MESSAGE, json!({"message": get_text(d, "Msge").unwrap_or_default(), "allowContinue": get_bool(d, "Cntn").unwrap_or(false)})) -} - -fn stop_to(_: &str, p: &Value) -> Option { - Some(desc("null").with("Msge", text(jstr(p, "message").unwrap_or(""))).with("Cntn", D::Boolean(jbool(p, "allowContinue").unwrap_or(false)))) -} - -fn paste_from(d: &Descriptor) -> Mapped { - none(if get_bool(d, "inPlace") == Some(true) { "edit.pasteSpecial.pasteInPlace" } else { "edit.paste" }) -} - -fn paste_to(id: &str, _: &Value) -> Option { - let mut d = desc("null"); - if id == "edit.pasteSpecial.pasteInPlace" { - d = d.with("inPlace", D::Boolean(true)); - } - Some(d.with("AntA", enm("Annt", "Anno"))) -} - -fn merge_visible_from(d: &Descriptor) -> Mapped { - none(if get_bool(d, "Dplc") == Some(true) { "layer.stampVisible" } else { "layer.mergeVisible" }) -} - -fn merge_visible_to(id: &str, _: &Value) -> Option { - Some(if id == "layer.stampVisible" { desc("null").with("Dplc", D::Boolean(true)) } else { desc("null") }) -} - -fn align_from(d: &Descriptor) -> Mapped { - match get_enum(d, "Usng").and_then(|u| lookup(ALIGN, &u)) { - Some(a) => step(&format!("layer.align.{a}"), if get_bool(d, "alignToCanvas") == Some(true) { json!({"to": "canvas"}) } else { json!({}) }), - None => Mapped::Unsupported { harmless: false }, - } -} - -fn align_to(id: &str, p: &Value) -> Option { - let a = lookup_back(ALIGN, id.strip_prefix("layer.align.")?)?; - Some(desc("null").with("null", target_ref("Lyr ")).with("Usng", enm("ADSt", a)).with("alignToCanvas", D::Boolean(jstr(p, "to") == Some("canvas")))) -} - -fn purge_from(d: &Descriptor) -> Mapped { - match get_enum(d, "null").and_then(|u| lookup(PURGE, &u)) { - Some(p) => none(&format!("edit.purge.{p}")), - None => Mapped::Unsupported { harmless: true }, - } -} - -fn purge_to(id: &str, _: &Value) -> Option { - Some(desc("null").with("null", enm("PrgI", lookup_back(PURGE, id.strip_prefix("edit.purge.")?)?))) -} - -fn reset_from(d: &Descriptor) -> Mapped { - match get_ref(d, "null").map(target) { - Some(Target::Property(p)) if p == "Clrs" => none("tools.defaultColors"), - _ => Mapped::Unsupported { harmless: true }, - } -} - -fn reset_to(_: &str, _: &Value) -> Option { - Some(desc("null").with("null", D::Reference(vec![ReferenceItem::Property { class: class("Clr "), key: Id::new("Clrs") }]))) -} - -fn profile_from(d: &Descriptor, id: &str) -> Mapped { - let name = get_text(d, "T ").or_else(|| get_text(d, "profile")); - let Some(profile) = name.as_deref().and_then(|n| lookup(PROFILES, n)) else { return Mapped::Unsupported { harmless: false } }; - let mut p = json!({"profile": profile}); - if id == "edit.convertToProfile" { - if let Some(i) = get_enum(d, "Inte").and_then(|i| lookup(INTENT, &i)) { - p["intent"] = json!(i); - } - if let Some(b) = get_bool(d, "MpBl") { - p["bpc"] = json!(b); - } - } - step(id, p) -} - -fn profile_to(id: &str, p: &Value) -> Option { - let name = lookup_back(PROFILES, jstr(p, "profile")?)?; - let mut d = desc("null").with("null", target_ref("Dcmn")); - if id == "edit.convertToProfile" { - d = d - .with("T ", text(name)) - .with("Inte", enm("Inte", lookup_back(INTENT, jstr(p, "intent").unwrap_or("relative"))?)) - .with("MpBl", D::Boolean(jbool(p, "bpc").unwrap_or(true))); - } else { - d = d.with("profile", text(name)); - } - Some(d) -} - -fn levels_event_from(d: &Descriptor) -> Mapped { - if get_bool(d, "Auto") == Some(true) { - return none("image.autoTone"); - } - if get_bool(d, "AuCo") == Some(true) { - return none("image.autoContrast"); - } - match levels_from(d) { - Some(p) => step("image.adjustments.levels", p), - None => Mapped::Unsupported { harmless: false }, - } -} - -fn levels_event_to(id: &str, p: &Value) -> Option { - Some(match id { - "image.autoTone" => desc("null").with("Auto", D::Boolean(true)), - "image.autoContrast" => desc("null").with("AuCo", D::Boolean(true)), - _ => levels_to(p)?, - }) -} - -/// A direct adjustment event (Image › Adjustments › …). The command id is `image.adjustments.` -/// unless it is given. -macro_rules! adjustment_event { - ($code:literal, $class:literal, $name:literal, $label:literal) => { - adjustment_event!($code, $class, $name, $label, concat!("image.adjustments.", $name)) - }; - ($code:literal, $class:literal, $name:literal, $label:literal, $id:expr) => { - Event { - code: $code, - name: $name, - label: $label, - ids: &[$id], - from: |d| match adjustment_by_class($class) { - Some(a) => adjustment_steps(a, "image.adjustments.", Some(d)), - None => Mapped::Unsupported { harmless: false }, - }, - to: |_, p| adjustment_by_class($class).and_then(|a| (a.to)(p)), - } - }; -} - -const RIPPLE_SIZE: &[(&str, &str)] = &[("Sml", "small"), ("Mdm", "medium"), ("Lrg", "large")]; - -/// Whether a Select and Mask step carries Refine Edge Brush strokes or the workspace's tool -/// edits (Quick Selection, Brush, Lasso…), which no descriptor holds. -fn has_refine_strokes(p: &Value) -> bool { - p.get("refineStrokes").is_some_and(|v| !v.is_null() && v.as_array().is_none_or(|a| !a.is_empty())) || crate::select_mask_edits::has_edits(p) -} - -/// Select and Mask to Photoshop. The descriptor has no field for the Refine Edge Brush or the -/// workspace's tools, so a step with `refineStrokes` or `edits` can't be exported faithfully. One with `sampleAllLayers` is not -/// exported here either: it exports as `smartBrushWorkspace`. -fn refine_edge_to(_: &str, p: &Value) -> Option { - if !pixel_target(p) || p.get("sampleAllLayers").is_some() || has_refine_strokes(p) { - return None; - } - fields_to(p, REFINE_EDGE, desc("null")) -} - -/// Select and Mask (`refineSelectionEdge`). Smart Radius, decontamination and the output follow -/// Photoshop's; the edge itself is PhotoCraft's own matting, so results differ in detail. -const REFINE_EDGE: &[F] = &[ - F("refineEdgeBorderRadius", "radius", Kind::Px), - F("refineEdgeAutoRadius", "smartRadius", Kind::Bool), - F("refineEdgeSmooth", "smooth", Kind::Long), - F("refineEdgeFeatherRadius", "feather", Kind::Px), - F("refineEdgeBorderContrast", "contrast", Kind::Pct), - F("refineEdgeChoke", "shiftEdge", Kind::Pct), - F("refineEdgeDecontaminate", "decontaminate", Kind::Bool), - F("refineEdgeDeconAmount", "amount", Kind::Pct), - F("refineEdgeOutput", "output", Kind::Enum("refineEdgeOutput", REFINE_OUTPUT)), -]; -const REFINE_OUTPUT: &[(&str, &str)] = &[ - ("refineEdgeOutputSelection", "selection"), - ("refineEdgeOutputUserMask", "layerMask"), - ("refineEdgeOutputNewLayer", "newLayer"), - ("refineEdgeOutputNewLayerWithMask", "newLayerWithMask"), - ("refineEdgeOutputNewDocument", "newDocument"), - ("refineEdgeOutputNewDocumentWithMask", "newDocumentWithMask"), -]; - -/// Filter Gallery effects (`GEfc` with the effect in `GEfk`): Photoshop's effect code, the -/// command, and its fields. A stack of several effects stays unsupported. -const GALLERY: &[(&str, &str, &[F])] = &[("Spt", "filter.gallery.spatter", &[F("SprR", "sprayRadius", Kind::Long), F("Smth", "smoothness", Kind::Long)])]; -const GALLERY_IDS: &[&str] = &["filter.gallery.spatter"]; - -fn gallery_from(d: &Descriptor) -> Mapped { - let Some(effect) = get_enum(d, "GEfk") else { return Mapped::Unsupported { harmless: false } }; - match GALLERY.iter().find(|(code, _, _)| *code == effect).and_then(|(_, id, fields)| Some((*id, fields_from(d, fields)?))) { - Some((id, p)) => step(id, Value::Object(p)), - None => Mapped::Unsupported { harmless: false }, - } -} - -fn gallery_to(id: &str, p: &Value) -> Option { - let (code, _, fields) = GALLERY.iter().find(|(_, cmd, _)| *cmd == id)?; - fields_to(p, fields, desc("null").with("GEfk", enm("GEft", code))) -} - -/// Select and Mask as Photoshop CC 2015.5 and later record it (`smartBrushWorkspace`); the -/// older Refine Edge event is [`REFINE_EDGE`], which is also what Select and Mask exports as. -const SMART_BRUSH: &[F] = &[ - F("smartBrushRadius", "radius", Kind::Px), - F("smartBrushUseSmartRadius", "smartRadius", Kind::Bool), - F("smartBrushSmooth", "smooth", Kind::Long), - F("smartBrushFeather", "feather", Kind::Px), - F("smartBrushContrast", "contrast", Kind::Pct), - F("smartBrushShiftEdge", "shiftEdge", Kind::Pct), - F("smartBrushDecontaminate", "decontaminate", Kind::Bool), - F("smartBrushDeconAmount", "amount", Kind::Pct), - F("refineEdgeOutput", "output", Kind::Enum("refineEdgeOutput", REFINE_OUTPUT)), - F("sampleAllLayers", "sampleAllLayers", Kind::Bool), -]; - -/// Select › Color Range's `Clrs` presets ↔ `select.colorRange`'s `select`. -const COLOR_RANGE: &[(&str, &str)] = &[ - ("Rds", "reds"), - ("Ylws", "yellows"), - ("Grns", "greens"), - ("Cyns", "cyans"), - ("Bls", "blues"), - ("Mgnt", "magentas"), - ("Hghl", "highlights"), - ("Mdtn", "midtones"), - ("Shdw", "shadows"), - ("OtOf", "outOfGamut"), - ("skinTone", "skinTones"), -]; - -/// The Color Range keys the converter reads (or that don't change a preset's result: -/// `colorModel` is the model of sampled colours). -const COLOR_RANGE_KEYS: &[&str] = &[ - "Clrs", - "Fzns", - "Invr", - "colorModel", - "shadowsFuzziness", - "shadowsUpperLimit", - "midtonesFuzziness", - "midtonesLowerLimit", - "midtonesUpperLimit", - "highlightsFuzziness", - "highlightsLowerLimit", -]; - -/// Color Range (`ClrR`) with a preset. Sampled Colors records Lab minimum and maximum colours, -/// which `select.colorRange` (eyedropper points on the image) can't reproduce, and an unknown -/// key (Detect Faces, Localized Color Clusters…) could change the result: both stay -/// unsupported. -fn color_range_from(d: &Descriptor) -> Mapped { - let unsupported = Mapped::Unsupported { harmless: false }; - if d.items.iter().any(|(k, _)| !COLOR_RANGE_KEYS.contains(&trimmed(k).as_str())) { - return unsupported; - } - let Some(preset) = get_enum(d, "Clrs").and_then(|c| lookup(COLOR_RANGE, &c)) else { return unsupported }; - let mut p = Map::new(); - p.insert("select".into(), preset.into()); - let key = |suffix: &str| get_num(d, &format!("{preset}{suffix}")); - match preset { - "skinTones" => { - if let Some(f) = get_num(d, "Fzns") { - p.insert("fuzziness".into(), f.into()); - } - } - "shadows" | "midtones" | "highlights" => { - if let Some(f) = key("Fuzziness") { - p.insert("fuzziness".into(), f.into()); - } - let range = match (preset, key("LowerLimit"), key("UpperLimit")) { - ("shadows", _, hi) => hi.map(Value::from), - ("highlights", lo, _) => lo.map(Value::from), - (_, Some(lo), Some(hi)) => Some(json!([lo, hi])), - (_, None, None) => None, - _ => return unsupported, - }; - if let Some(r) = range { - p.insert("tonalRange".into(), r); - } - } - _ => {} - } - if get_bool(d, "Invr") == Some(true) { - p.insert("invert".into(), true.into()); - } - step("select.colorRange", Value::Object(p)) -} - -fn color_range_to(_: &str, p: &Value) -> Option { - let preset = jstr(p, "select")?; - if p.as_object()?.keys().any(|k| !matches!(k.as_str(), "select" | "fuzziness" | "tonalRange" | "invert")) { - return None; - } - let mut d = desc("null").with("Clrs", enm("Clrs", lookup_back(COLOR_RANGE, preset)?)); - let tonal = matches!(preset, "shadows" | "midtones" | "highlights"); - if let Some(f) = jnum(p, "fuzziness") { - match preset { - "skinTones" => d = d.with("Fzns", long(f)), - _ if tonal => d = d.with(&format!("{preset}Fuzziness"), long(f)), - _ => {} - } - } - if let Some(r) = p.get("tonalRange") { - match preset { - "shadows" => d = d.with("shadowsUpperLimit", long(r.as_f64()?)), - "highlights" => d = d.with("highlightsLowerLimit", long(r.as_f64()?)), - "midtones" => { - let a = r.as_array()?; - d = d.with("midtonesLowerLimit", long(a.first()?.as_f64()?)).with("midtonesUpperLimit", long(a.get(1)?.as_f64()?)); - } - _ => return None, - } - } - if jbool(p, "invert") == Some(true) { - d = d.with("Invr", D::Boolean(true)); - } - Some(d) -} - -/// Create / Release Clipping Mask (`groupEvent` / `ungroup`) on the target or a named layer. -fn clipping_from(d: &Descriptor, id: &str) -> Mapped { - match get_ref(d, "null") { - None => none(id), - Some(r) if ref_class(r).as_deref() == Some("Lyr") => match layer_target(r) { - Some(p) => step(id, Value::Object(p)), - None => Mapped::Unsupported { harmless: false }, - }, - Some(_) => Mapped::Unsupported { harmless: false }, - } -} - -fn clipping_to(_: &str, p: &Value) -> Option { - Some(desc("null").with("null", layer_ref(p)?)) -} - -/// A clipping mask event: `clipping_from` / `clipping_to` with one command id. -macro_rules! clipping_event { - ($code:literal, $name:literal, $label:literal, $id:literal) => { - Event { code: $code, name: $name, label: $label, ids: &[$id], from: |d| clipping_from(d, $id), to: clipping_to } - }; -} - -const RADIAL_BLUR_FIELDS: &[F] = - &[F("Amnt", "amount", Kind::Long), F("BlrM", "method", Kind::Enum("BlrM", RADIAL_METHOD)), F("BlrQ", "quality", Kind::Enum("BlrQ", RADIAL_QUALITY))]; - -fn radial_blur_from(d: &Descriptor) -> Mapped { - match fields_from(d, RADIAL_BLUR_FIELDS) { - Some(m) => step("filter.blur.radialBlur", Value::Object(m)), - None => Mapped::Unsupported { harmless: false }, - } -} - -fn radial_blur_to(_: &str, p: &Value) -> Option { - if !pixel_target(p) { - return None; - } - // Photoshop's Radial Blur has no center parameter and always blurs from the center (0.5, 0.5). - // An explicit center must match 0.5 exactly; any non-default center cannot be faithfully exported. - let is_default_center = |k: &str| match p.get(k) { - None | Some(Value::Null) => true, - Some(v) => v.as_f64() == Some(0.5), - }; - if !is_default_center("centerX") || !is_default_center("centerY") { - return None; - } - fields_to(p, RADIAL_BLUR_FIELDS, desc("null")) -} - -/// Every Photoshop event PhotoCraft maps. The order matters only for the panel label. -const EVENTS: &[Event] = &[ - // Filters. - ev!("GsnB", "gaussianBlur", "Gaussian Blur", "filter.blur.gaussianBlur", &[F("Rds ", "radius", Kind::Px)]), - ev!( - "UnsM", - "unsharpMask", - "Unsharp Mask", - "filter.sharpen.unsharpMask", - &[F("Amnt", "amount", Kind::Pct), F("Rds ", "radius", Kind::Px), F("Thsh", "threshold", Kind::Long)] - ), - ev!( - "AdNs", - "addNoise", - "Add Noise", - "filter.noise.addNoise", - &[ - F("Dstr", "distribution", Kind::Enum("Dstr", NOISE)), - F("Nose", "amount", Kind::Pct), - F("Mnch", "monochromatic", Kind::Bool), - F("FlRs", "seed", Kind::Long) - ] - ), - ev!("Mdn ", "median", "Median", "filter.noise.median", &[F("Rds ", "radius", Kind::Px)]), - ev!("DstS", "dustAndScratches", "Dust & Scratches", "filter.noise.dustAndScratches", &[F("Rds ", "radius", Kind::Px), F("Thsh", "threshold", Kind::Long)]), - ev!("Dspc", "despeckle", "Despeckle", "filter.noise.despeckle", &[]), - // Photoshop records Emboss's angle, height and amount as plain integers (#7946). - ev!( - "Embs", - "emboss", - "Emboss", - "filter.stylize.emboss", - &[F("Angl", "angle", Kind::Long), F("Hght", "height", Kind::Long), F("Amnt", "amount", Kind::Long)] - ), - ev!("MtnB", "motionBlur", "Motion Blur", "filter.blur.motionBlur", &[F("Angl", "angle", Kind::Ang), F("Dstn", "distance", Kind::Px)]), - ev!("", "boxblur", "Box Blur", "filter.blur.boxBlur", &[F("Rds ", "radius", Kind::Px)]), - ev!("", "surfaceBlur", "Surface Blur", "filter.blur.surfaceBlur", &[F("Rds ", "radius", Kind::Px), F("Thsh", "threshold", Kind::Long)]), - ev!( - "SmrB", - "smartBlur", - "Smart Blur", - "filter.blur.smartBlur", - &[ - F("Rds ", "radius", Kind::Dbl), - F("Thsh", "threshold", Kind::Dbl), - F("SmBQ", "quality", Kind::Enum("SmBQ", SMART_BLUR_QUALITY)), - F("SmBM", "mode", Kind::Enum("SmBM", SMART_BLUR_MODE)) - ] - ), - Event { code: "RdlB", name: "radialBlur", label: "Radial Blur", ids: &["filter.blur.radialBlur"], from: radial_blur_from, to: radial_blur_to }, - ev!("Blr ", "blur", "Blur", "filter.blur.blur", &[]), - ev!("BlrM", "blurMore", "Blur More", "filter.blur.blurMore", &[]), - ev!("Shrp", "sharpen", "Sharpen", "filter.sharpen.sharpen", &[]), - ev!("ShrM", "sharpenMore", "Sharpen More", "filter.sharpen.sharpenMore", &[]), - ev!("ShrE", "sharpenEdges", "Sharpen Edges", "filter.sharpen.sharpenEdges", &[]), - ev!("HghP", "highPass", "High Pass", "filter.other.highPass", &[F("Rds ", "radius", Kind::Px)]), - ev!("Mnm ", "minimum", "Minimum", "filter.other.minimum", &[F("Rds ", "radius", Kind::Px)], unless preserves_roundness), - ev!("Mxm ", "maximum", "Maximum", "filter.other.maximum", &[F("Rds ", "radius", Kind::Px)], unless preserves_roundness), - ev!( - "Ofst", - "offset", - "Offset", - "filter.other.offset", - &[F("Hrzn", "horizontal", Kind::Long), F("Vrtc", "vertical", Kind::Long), F("Fl ", "undefinedAreas", Kind::Enum("FlMd", OFFSET_FILL))] - ), - ev!("Rple", "ripple", "Ripple", "filter.distort.ripple", &[F("Amnt", "amount", Kind::ExactLong), F("RplS", "size", Kind::Enum("RplS", RIPPLE_SIZE))]), - ev!("Crst", "crystallize", "Crystallize", "filter.pixelate.crystallize", &[F("ClSz", "cellSize", Kind::ExactLong)]), - Event { code: "GEfc", name: "filterGallery", label: "Filter Gallery", ids: GALLERY_IDS, from: gallery_from, to: gallery_to }, - // Adjustments (Image › Adjustments). - Event { - code: "", - name: "adaptCorrect", - label: "Shadows/Highlights", - ids: &["image.adjustments.shadowsHighlights"], - from: shadows_highlights_from, - to: shadows_highlights_to, - }, - Event { - code: "Lvls", - name: "levels", - label: "Levels", - ids: &["image.adjustments.levels", "image.autoTone", "image.autoContrast"], - from: levels_event_from, - to: levels_event_to, - }, - adjustment_event!("Crvs", "Crvs", "curves", "Curves"), - adjustment_event!("HStr", "HStr", "hueSaturation", "Hue/Saturation"), - adjustment_event!("BrgC", "BrgC", "brightnessEvent", "Brightness/Contrast", "image.adjustments.brightnessContrast"), - adjustment_event!("Thrs", "Thrs", "threshold", "Threshold"), - adjustment_event!("Pstr", "Pstr", "posterize", "Posterize"), - adjustment_event!("Invr", "Invr", "invert", "Invert"), - adjustment_event!("ClrB", "ClrB", "colorBalance", "Color Balance"), - adjustment_event!("Vbrn", "Vbrn", "vibrance", "Vibrance"), - adjustment_event!("Exps", "Exps", "exposure", "Exposure"), - // Photoshop runs Photo Filter by name only: `PhtF` is the class, not an event (#8301). - adjustment_event!("", "PhtF", "photoFilter", "Photo Filter"), - adjustment_event!("", "BanW", "blackAndWhite", "Black & White", "image.adjustments.blackWhite"), - adjustment_event!("ChnM", "ChnM", "channelMixer", "Channel Mixer"), - adjustment_event!("GdMp", "GdMp", "gradientMapEvent", "Gradient Map", "image.adjustments.gradientMap"), - adjustment_event!("SlcC", "SlcC", "selectiveColor", "Selective Color"), - ev!("Dstt", "desaturate", "Desaturate", "image.adjustments.desaturate", &[]), - ev!("Eqlz", "equalize", "Equalize", "image.adjustments.equalize", &[]), - ev!("", "autoColor", "Auto Color", "image.autoColor", &[]), - // Image. - Event { code: "ImgS", name: "imageSize", label: "Image Size", ids: &["image.imageSize"], from: image_size_from, to: image_size_to }, - Event { code: "CnvS", name: "canvasSize", label: "Canvas Size", ids: &["image.canvasSize"], from: canvas_size_from, to: canvas_size_to }, - Event { - code: "Rtte", - name: "rotateEventEnum", - label: "Rotate", - ids: &[ - "image.imageRotation.90cw", - "image.imageRotation.90ccw", - "image.imageRotation.180", - "image.rotation.arbitrary", - "edit.transform.rotate90Cw", - "edit.transform.rotate90Ccw", - "edit.transform.rotate180", - ], - from: rotate_from, - to: rotate_to, - }, - Event { - code: "Flip", - name: "flip", - label: "Flip", - ids: &[ - "image.imageRotation.flipCanvasHorizontal", - "image.imageRotation.flipCanvasVertical", - "edit.transform.flipHorizontal", - "edit.transform.flipVertical", - ], - from: flip_from, - to: flip_to, - }, - Event { code: "Crop", name: "crop", label: "Crop", ids: &["image.crop"], from: crop_from, to: crop_to }, - ev!( - "", - "trim", - "Trim", - "image.trim", - &[ - F("trimBasedOn", "basedOn", Kind::Enum("trimBasedOn", TRIM)), - F("Top ", "top", Kind::Bool), - F("Btom", "bottom", Kind::Bool), - F("Left", "left", Kind::Bool), - F("Rght", "right", Kind::Bool) - ] - ), - ev!("RvlA", "revealAll", "Reveal All", "image.revealAll", &[]), - Event { - code: "CnvM", - name: "convertMode", - label: "Convert Mode", - ids: &[ - "image.mode.rgb", - "image.mode.grayscale", - "image.mode.cmyk", - "image.mode.lab", - "image.mode.multichannel", - "image.mode.bits8", - "image.mode.bits16", - "image.mode.bits32", - "image.mode.bitmap", - ], - from: convert_mode_from, - to: convert_mode_to, - }, - Event { code: "Dplc", name: "duplicate", label: "Duplicate", ids: &["layer.duplicate", "image.duplicate"], from: duplicate_from, to: duplicate_to }, - // Layers. - Event { - code: "Mk ", - name: "make", - label: "Make", - ids: &[ - "layer.new.layer", - "layer.new.group", - "layer.groupLayers", - "layer.duplicate", - "layer.new.layerViaCopy", - "layer.new.layerViaCut", - "layer.newFillLayer.solidColor", - "layer.newFillLayer.pattern", - "layer.newAdjustmentLayer.levels", - "layer.newAdjustmentLayer.curves", - "layer.newAdjustmentLayer.hueSaturation", - "layer.newAdjustmentLayer.brightnessContrast", - "layer.newAdjustmentLayer.threshold", - "layer.newAdjustmentLayer.posterize", - "layer.newAdjustmentLayer.invert", - "layer.newAdjustmentLayer.colorBalance", - "layer.newAdjustmentLayer.vibrance", - "layer.newAdjustmentLayer.exposure", - "layer.newAdjustmentLayer.photoFilter", - "layer.newAdjustmentLayer.blackWhite", - "layer.newAdjustmentLayer.channelMixer", - "layer.newAdjustmentLayer.selectiveColor", - "layer.newAdjustmentLayer.gradientMap", - "layer.layerMask.revealAll", - "layer.layerMask.hideAll", - "layer.layerMask.revealSelection", - "layer.layerMask.hideSelection", - "file.new", - "file.newFromClipboard", - ], - from: make_from, - to: make_to, - }, - Event { - code: "setd", - name: "set", - label: "Set", - ids: &[ - "select.all", - "select.deselect", - "select.reselect", - "select.loadSelection", - "select.rect", - "select.lasso", - "select.editInQuickMaskMode", - "tools.setColors", - "layer.setProps", - "layer.renameLayer", - "layer.setLabelColor", - "layer.setAdjustment", - "layer.fill.pattern.set", - "layer.new.layerFromBackground", - ], - from: set_from, - to: set_to, - }, - Event { - code: "slct", - name: "select", - label: "Select", - ids: &[ - "layer.select", - "layer.selectAbove", - "layer.selectBelow", - "layer.addAboveToSelection", - "layer.addBelowToSelection", - "layer.selectTop", - "layer.selectBottom", - "channel.target", - "edit.undo", - "edit.redo", - "view.fitOnScreen", - "view.actualPixels", - "view.zoomIn", - "view.zoomOut", - "document.activate", - ], - from: select_from, - to: select_to, - }, - Event { code: "Dlt ", name: "delete", label: "Delete", ids: &["layer.delete", "edit.clear", "layer.layerMask.delete"], from: delete_from, to: delete_to }, - Event { code: "", name: "clearEvent", label: "Clear", ids: &["select.editInQuickMaskMode"], from: clear_from, to: clear_to }, - Event { - code: "Trnf", - name: "transform", - label: "Transform", - ids: &["edit.transform", "select.transformSelection"], - from: transform_from, - to: transform_to, - }, - Event { code: "AppI", name: "applyImageEvent", label: "Apply Image", ids: &["image.applyImage"], from: apply_image_from, to: apply_image_to }, - ev!("", "newPlacedLayer", "Convert to Smart Object", "layer.smartObjects.convertToSmartObject", &[]), - ev!("", "placedLayerEditContents", "Edit Contents", "layer.smartObjects.editContents", &[]), - ev!("", "updatePlacedLayer", "Update Smart Objects", "layer.smartObjects.updateModifiedContent", &[]), - Event { code: "Hd ", name: "hide", label: "Hide", ids: &["layer.hideLayers"], from: |d| visibility_from(d, "layer.hideLayers"), to: visibility_to }, - Event { code: "Shw ", name: "show", label: "Show", ids: &["layer.showLayers"], from: |d| visibility_from(d, "layer.showLayers"), to: visibility_to }, - Event { - code: "move", - name: "move", - label: "Move", - ids: &["layer.translate", "layer.arrange.bringToFront", "layer.arrange.sendToBack", "layer.arrange.bringForward", "layer.arrange.sendBackward"], - from: move_from, - to: move_to, - }, - ev!("FltI", "flattenImage", "Flatten Image", "layer.flattenImage", &[]), - Event { - code: "MrgV", - name: "mergeVisible", - label: "Merge Visible", - ids: &["layer.mergeVisible", "layer.stampVisible"], - from: merge_visible_from, - to: merge_visible_to, - }, - ev!("Mrg2", "mergeLayersNew", "Merge Layers", "layer.mergeLayers", &[]), - clipping_event!("Ungr", "ungroup", "Release Clipping Mask", "layer.releaseClippingMask"), - ev!("CpTL", "copyToLayer", "Layer Via Copy", "layer.new.layerViaCopy", &[]), - ev!("CtTL", "cutToLayer", "Layer Via Cut", "layer.new.layerViaCut", &[]), - ev!("", "rasterizeLayer", "Rasterize", "layer.rasterize.layer", &[]), - ev!("", "selectAllLayers", "Select All Layers", "select.allLayers", &[]), - ev!("", "selectNoLayers", "Deselect Layers", "select.deselectLayers", &[]), - clipping_event!("GrpL", "groupEvent", "Create Clipping Mask", "layer.createClippingMask"), - ev!("", "ungroupLayersEvent", "Ungroup Layers", "layer.ungroupLayers", &[]), - ev!("", "copyEffects", "Copy Layer Style", "layer.layerStyle.copyLayerStyle", &[]), - ev!("", "pasteEffects", "Paste Layer Style", "layer.layerStyle.pasteLayerStyle", &[]), - Event { - code: "", - name: "collapseAllGroupsEvent", - label: "Collapse All Groups", - ids: &["layer.setExpanded"], - from: |_| step("layer.setExpanded", json!({"all": true, "expanded": false})), - to: |_, p| (jbool(p, "all") == Some(true) && jbool(p, "expanded") == Some(false)).then(|| desc("null")), - }, - ev!("Dfrg", "defringe", "Defringe", "layer.matting.defringe", &[F("Wdth", "width", Kind::Px)]), - Event { - code: "Algn", - name: "align", - label: "Align", - ids: &[ - "layer.align.leftEdges", - "layer.align.horizontalCenters", - "layer.align.rightEdges", - "layer.align.topEdges", - "layer.align.verticalCenters", - "layer.align.bottomEdges", - ], - from: align_from, - to: align_to, - }, - // Selection. - ev!("Invs", "inverse", "Inverse", "select.inverse", &[]), - ev!("Fthr", "feather", "Feather", "select.modify.feather", &[F("Rds ", "radius", Kind::Px)], unless applies_at_canvas_bounds), - ev!("Expn", "expand", "Expand", "select.modify.expand", &[F("By ", "radius", Kind::Px)], unless applies_at_canvas_bounds), - ev!("Cntc", "contract", "Contract", "select.modify.contract", &[F("By ", "radius", Kind::Px)], unless applies_at_canvas_bounds), - ev!("Smth", "smoothness", "Smooth", "select.modify.smooth", &[F("Rds ", "radius", Kind::Px)], unless applies_at_canvas_bounds), - ev!("Brdr", "border", "Border", "select.modify.border", &[F("Wdth", "radius", Kind::Px)]), - ev!("Grow", "grow", "Grow", "select.grow", &[F("Tlrn", "tolerance", Kind::Long)]), - ev!("Smlr", "similar", "Similar", "select.similar", &[F("Tlrn", "tolerance", Kind::Long)]), - // `refineSelectionEdge` has no Sample All Layers, so a step with it exports as - // `smartBrushWorkspace` instead of dropping it. - Event { - code: "", - name: "refineSelectionEdge", - label: "Select and Mask", - ids: &["select.refineEdge"], - from: |d| match fields_from(d, REFINE_EDGE) { - Some(m) => step("select.refineEdge", Value::Object(m)), - None => Mapped::Unsupported { harmless: false }, - }, - to: refine_edge_to, - }, - ev!("", "smartBrushWorkspace", "Select and Mask", "select.refineEdge", SMART_BRUSH, unless has_refine_strokes), - ev!("", "autoCutout", "Select Subject", "select.subject", &[F("sampleAllLayers", "sampleAllLayers", Kind::Bool)]), - Event { code: "ClrR", name: "colorRange", label: "Color Range", ids: &["select.colorRange"], from: color_range_from, to: color_range_to }, - // Edit. - Event { code: "Fl ", name: "fill", label: "Fill", ids: &["edit.fill", "paint.bucket"], from: fill_from, to: fill_to }, - Event { - code: "Strk", - name: "stroke", - label: "Stroke", - ids: &["edit.stroke"], - from: |d| match fields_from(d, STROKE) { - Some(m) => step("edit.stroke", Value::Object(m)), - None => Mapped::Unsupported { harmless: false }, - }, - to: stroke_to, - }, - ev!("copy", "copyEvent", "Copy", "edit.copy", &[]), - ev!("CpyM", "copyMerged", "Copy Merged", "edit.copyMerged", &[]), - ev!("cut ", "cut", "Cut", "edit.cut", &[]), - Event { code: "past", name: "paste", label: "Paste", ids: &["edit.paste", "edit.pasteSpecial.pasteInPlace"], from: paste_from, to: paste_to }, - Event { - code: "Prge", - name: "purge", - label: "Purge", - ids: &["edit.purge.all", "edit.purge.clipboard", "edit.purge.histories", "edit.purge.undo"], - from: purge_from, - to: purge_to, - }, - Event { code: "Rset", name: "reset", label: "Reset", ids: &["tools.defaultColors"], from: reset_from, to: reset_to }, - ev!("Exch", "exchange", "Exchange", "tools.swapColors", &[]), - Event { - code: "", - name: "assignProfile", - label: "Assign Profile", - ids: &["edit.assignProfile"], - from: |d| profile_from(d, "edit.assignProfile"), - to: profile_to, - }, - Event { - code: "", - name: "convertToProfile", - label: "Convert to Profile", - ids: &["edit.convertToProfile"], - from: |d| profile_from(d, "edit.convertToProfile"), - to: profile_to, - }, - // File and actions. - Event { code: "Cls ", name: "close", label: "Close", ids: &["file.close"], from: close_from, to: close_to }, - Event { code: "Expr", name: "export", label: "Export", ids: &["file.export.saveForWebLegacy"], from: export_from, to: export_to }, - Event { code: "Plc ", name: "placeEvent", label: "Place", ids: &["file.placeEmbedded", "file.placeLinked"], from: place_from, to: place_to }, - Event { code: "Opn ", name: "open", label: "Open", ids: &["file.openAs"], from: open_from, to: open_to }, - Event { code: "", name: "conditional", label: "If", ids: &["actions.conditional"], from: conditional_from, to: conditional_to }, - Event { code: "save", name: "save", label: "Save", ids: &["file.save", "file.saveAs", "file.saveACopy"], from: save_from, to: save_to }, - ev!("Rvrt", "revert", "Revert", "file.revert", &[]), - Event { code: "Ply ", name: "play", label: "Play", ids: &["actions.play"], from: play_from, to: play_to }, - Event { code: "", name: "applyComp", label: "Apply Layer Comp", ids: &["layerComp.apply"], from: apply_comp_from, to: apply_comp_to }, - Event { code: "Stop", name: "stop", label: "Stop", ids: &[STOP_MESSAGE], from: stop_from, to: stop_to }, -]; - -/// Four-char codes PhotoCraft once exported for events Photoshop only runs by name (or by -/// another code), with the name they stand for. Measured in Photoshop: `executeAction` with -/// these codes fails ("the command is not currently available"), and `Fltn` is the -/// `flatness` property, not the flatten event. Import keeps accepting them so actions saved -/// before still load; export never writes them. -const LEGACY_CODES: &[(&str, &str)] = - &[("BoxB", "boxblur"), ("SrfB", "surfaceBlur"), ("Fltn", "flattenImage"), ("BlnW", "blackAndWhite"), ("PhtF", "photoFilter")]; - -fn event_for(item: &AtnEvent) -> Option<&'static Event> { - let id = item.id(); - let find = |id: &str| EVENTS.iter().find(|e| (!e.code.is_empty() && e.code.trim_end() == id.trim_end()) || e.name == id); - find(&id).or_else(|| match item { - AtnEvent::Code(_) => LEGACY_CODES.iter().find(|(code, _)| *code == id).and_then(|(_, name)| find(name)), - AtnEvent::Name(_) => None, - }) -} - -/// The event `id` exports as: the first event listing it whose converter accepts the params -/// (Quick Mask on is a `set`, off a `clearEvent`). -fn event_and_descriptor(id: &str, params: &Value) -> Option<(&'static Event, Descriptor)> { - EVENTS.iter().filter(|e| e.ids.contains(&id)).find_map(|e| (e.to)(id, params).map(|d| (e, d))) -} - -// ------------------------------------------------------------------ import - -/// A step with no PhotoCraft equivalent. -#[derive(Clone, Debug, PartialEq, serde::Serialize)] -pub struct Unsupported { - pub action: String, - pub step: usize, - pub event: String, - pub name: String, -} - -/// What a `.atn` file imports to. -#[derive(Clone, Debug, Default)] -pub struct Imported { - pub set: String, - pub actions: Vec, - /// Function keys the file assigns, as `(action name, key)`. - pub function_keys: Vec<(String, String)>, - pub unsupported: Vec, - pub warnings: Vec, -} - -fn photoshop_step(item: &AtnItem) -> (String, Value) { - let descriptor = item.descriptor.as_ref().map(|d| photocraft_paint::tile::b64_encode(&d.to_bytes())); - let event_kind = match &item.event { - AtnEvent::Code(_) => "code", - AtnEvent::Name(_) => "name", - }; - (PHOTOSHOP_STEP.into(), json!({"event": item.event.id(), "eventKind": event_kind, "name": item.label(), "descriptor": descriptor})) -} - -/// Integral floats become integers (`2.0` → `2`), as the commands' own docs and recordings -/// use, so an imported step reads and compares like a recorded one. -fn normalise(v: &mut Value) { - match v { - Value::Number(n) => { - if let Some(f) = n.as_f64() - && f.fract() == 0.0 - && f.abs() < 9.0e15 - && n.as_i64().is_none() - { - *v = Value::from(f as i64); - } - } - Value::Array(a) => a.iter_mut().for_each(normalise), - Value::Object(o) => o.values_mut().for_each(normalise), - _ => {} - } -} - -/// Longest action or set name kept (Photoshop's own limit is 255). A file's names are lengths it -/// chooses, and each is copied into every action and every unsupported-step diagnostic. -const MAX_NAME_CHARS: usize = 1024; - -fn clip_name(s: &str) -> String { - s.chars().take(MAX_NAME_CHARS).collect() -} - -fn convert_action(a: &AtnAction, set: &str, unsupported: &mut Vec) -> Action { - let name = clip_name(&a.name.to_string_lossy()); - let mut action = Action::new(name.clone(), Vec::new()); - action.set = Some(clip_name(set)); - for (i, item) in a.items.iter().enumerate() { - let mapped = match (event_for(&item.event), &item.descriptor) { - (Some(e), Some(d)) => (e.from)(d), - (Some(e), None) => (e.from)(&Descriptor::default()), - (None, _) => Mapped::Unsupported { harmless: false }, - }; - let (new_steps, enabled) = match mapped { - Mapped::Steps(s) => (s, item.enabled), - Mapped::Unsupported { harmless } => { - unsupported.push(Unsupported { action: name.clone(), step: i, event: item.event.id(), name: item.label() }); - (vec![photoshop_step(item)], item.enabled && !harmless) - } - }; - for mut s in new_steps { - normalise(&mut s.1); - let idx = action.steps.len(); - action.steps.push(s); - if !enabled { - action.disabled.insert(idx); - } - if item.with_dialog { - action.dialogs.insert(idx); - } - } - } - action -} - -/// Convert a `.atn` file. Fails only when the file is unreadable: every step imports, as a -/// command or as a kept Photoshop step. -pub fn import(bytes: &[u8]) -> std::result::Result { - let file = atn::parse(bytes).map_err(|e| e.to_string())?; - let set = file.name.to_string_lossy(); - let set = if set.trim().is_empty() { DEFAULT_SET.to_string() } else { clip_name(&set) }; - let mut out = Imported { set: set.clone(), warnings: file.warnings.clone(), ..Default::default() }; - for a in &file.actions { - let action = convert_action(a, &set, &mut out.unsupported); - if a.function_key > 0 { - out.function_keys.push((action.name.clone(), function_key_name(a.function_key, a.shift, a.command))); - } - out.actions.push(action); - } - Ok(out) -} - -// ------------------------------------------------------------------ export - -/// A step Save Actions could not express as a Photoshop event. -#[derive(Clone, Debug, PartialEq, serde::Serialize)] -pub struct Skipped { - pub action: String, - pub step: usize, - pub id: String, -} - -fn export_item(id: &str, params: &Value, set: &str) -> Option { - if id == PHOTOSHOP_STEP { - let event = jstr(params, "event")?; - let event = match params.get("eventKind") { - Some(Value::String(kind)) if kind == "code" => AtnEvent::Code(event.as_bytes().try_into().ok()?), - Some(Value::String(kind)) if kind == "name" => AtnEvent::name(event), - Some(_) => return None, - // Older PhotoCraft action data did not retain the event kind. Keep its previous - // best-effort export behavior for compatibility. - None => match event.as_bytes() { - [a, b, c, d] => AtnEvent::Code([*a, *b, *c, *d]), - _ => AtnEvent::name(event), - }, - }; - let descriptor = match jstr(params, "descriptor") { - Some(b64) => Some(Descriptor::from_bytes(&photocraft_paint::tile::b64_decode(b64)?).ok()?), - None => None, - }; - return Some(AtnItem { event, dictionary: jstr(params, "name").unwrap_or("").as_bytes().to_vec(), descriptor, ..Default::default() }); - } - let mut params = params.clone(); - if (id == "actions.play" || id == "actions.conditional") && params.get("set").is_none() { - params["set"] = json!(set); - } - let (e, descriptor) = event_and_descriptor(id, ¶ms)?; - let event = if e.code.is_empty() { AtnEvent::name(e.name) } else { AtnEvent::Code(e.code.as_bytes().try_into().ok()?) }; - Some(AtnItem { event, dictionary: e.label.as_bytes().to_vec(), descriptor: Some(descriptor), ..Default::default() }) -} - -/// Photoshop applies only the rename when a Set mixes it with opacity or blend mode (#8304). -/// Write each layer property separately, renaming last so named references still resolve. -fn export_items(id: &str, params: &Value, set: &str) -> Option> { - let item = export_item(id, params, set)?; - if id != "layer.setProps" { - return Some(vec![item]); - } - let descriptor = item.descriptor.as_ref()?; - let properties = get_obj(descriptor, "T ")?; - if properties.items.len() <= 1 { - return Some(vec![item]); - } - let target = descriptor.get("null")?; - let mut items = Vec::with_capacity(properties.items.len()); - for (key, value) in properties.items.iter().filter(|(k, _)| !k.is("Nm ")).chain(properties.items.iter().filter(|(k, _)| k.is("Nm "))) { - let mut property = properties.clone(); - property.items = vec![(key.clone(), value.clone())]; - let descriptor = desc("null").with("null", target.clone()).with("T ", D::Descriptor(property)); - items.push(AtnItem { descriptor: Some(descriptor), ..item.clone() }); - } - Some(items) -} - -/// An action's key as a shortcut string: `F5`, with Photoshop's Shift and Command options -/// `Shift+F5`, `Cmd+F5` or `Cmd+Shift+F5` (#7646). -pub fn function_key_name(key: u16, shift: bool, command: bool) -> String { - format!("{}{}F{key}", if command { "Cmd+" } else { "" }, if shift { "Shift+" } else { "" }) -} - -/// The `.atn` function key (1…15), Shift and Command of a shortcut string, or `None` for -/// anything else. -pub fn parse_function_key(key: &str) -> Option<(u16, bool, bool)> { - let (mut shift, mut command) = (false, false); - let mut rest = key; - loop { - if let Some(r) = rest.strip_prefix("Cmd+").filter(|_| !command) { - (command, rest) = (true, r); - } else if let Some(r) = rest.strip_prefix("Shift+").filter(|_| !shift) { - (shift, rest) = (true, r); - } else { - break; - } - } - let n = rest.strip_prefix('F')?.parse::().ok().filter(|n| (1..=15).contains(n))?; - Some((n, shift, command)) -} - -/// The `.atn` bytes of `actions` as the set `set`. `function_keys` gives each action's key -/// (`F1`…`F15`, with `Shift+` and `Cmd+` as [`function_key_name`] writes them). Steps with no Photoshop equivalent are an error unless `skip_unsupported`. -pub fn export( - set: &str, - actions: &[&Action], - function_keys: &[(String, String)], - skip_unsupported: bool, -) -> std::result::Result<(Vec, Vec), String> { - let mut skipped = Vec::new(); - let mut file = AtnFile { name: UnicodeString::new_nul(set), expanded: true, actions: Vec::new(), warnings: Vec::new() }; - for a in actions { - let mut out = AtnAction { name: UnicodeString::new_nul(&a.name), expanded: false, ..Default::default() }; - if let Some((n, shift, command)) = function_keys.iter().find(|(n, _)| n == &a.name).and_then(|(_, key)| parse_function_key(key)) { - (out.function_key, out.shift, out.command) = (n, shift, command); - } - for (i, (id, params)) in a.steps.iter().enumerate() { - let Some(items) = export_items(id, params, set) else { - if skip_unsupported { - skipped.push(Skipped { action: a.name.clone(), step: i, id: id.clone() }); - continue; - } - let step_name = match params.get("layer") { - Some(Value::Number(n)) => format!("`{id}` with numeric layer {n}"), - _ => format!("`{id}`"), - }; - return Err(format!( - "step {} of `{}` ({step_name}) has no Photoshop equivalent; pass \"skipUnsupported\": true to leave it out", - i + 1, - a.name - )); - }; - for mut item in items { - item.enabled = a.step_enabled(i); - item.with_dialog = a.dialogs.contains(&i); - item.dialog_options = if item.with_dialog { 2 } else { 0 }; - out.items.push(item); - } - } - file.actions.push(out); - } - let bytes = atn::write(&file).map_err(|e| e.to_string())?; - Ok((bytes, skipped)) -} - -// ------------------------------------------------------------------ commands - -/// Assigns names not already used, as `name`, `name 2`, `name 3`… A plain linear scan of the -/// taken list per candidate is cubic when an action file repeats one base name many times, so -/// membership uses a set and the next suffix to try is cached per base name. -struct UniqueNames { - taken: std::collections::HashSet, - next_suffix: std::collections::HashMap, -} - -impl UniqueNames { - fn new>(existing: I) -> Self { - UniqueNames { taken: existing.into_iter().collect(), next_suffix: std::collections::HashMap::new() } - } - - /// Reserves and returns a unique name derived from `name`, recording it as taken. - fn claim(&mut self, name: &str) -> String { - if self.taken.insert(name.to_string()) { - return name.to_string(); - } - let mut i = self.next_suffix.get(name).copied().unwrap_or(2); - loop { - let candidate = format!("{name} {i}"); - i += 1; - if self.taken.insert(candidate.clone()) { - self.next_suffix.insert(name.to_string(), i); - return candidate; - } - } - } -} - -fn load(s: &mut Session, p: &Value) -> Result { - let cmd = "actions.load"; - if s.actions.recording.is_some() || s.actions.playing > 0 { - return Err(bad(cmd, "stop recording or playing before loading actions")); - } - let (bytes, _) = crate::preset_import_cmds::file_bytes(p, cmd, ".atn file")?; - let mut imp = import(&bytes).map_err(|e| bad(cmd, e))?; - match p.get("set") { - None | Some(Value::Null) => {} - Some(Value::String(n)) if !n.trim().is_empty() => { - imp.set = n.trim().to_string(); - for a in &mut imp.actions { - a.set = Some(imp.set.clone()); - } - } - Some(_) => return Err(bad(cmd, "`set` must be a non-empty string")), - } - let replace = match p.get("replace") { - None | Some(Value::Null) => true, - Some(Value::Bool(b)) => *b, - Some(_) => return Err(bad(cmd, "`replace` must be true or false")), - }; - if replace { - s.actions.list.retain(|a| a.set.as_deref() != Some(imp.set.as_str())); - } - let mut taken = UniqueNames::new(s.actions.list.iter().map(|a| a.name.clone())); - let mut names = Vec::with_capacity(imp.actions.len()); - // The file's name of each action that had to be renamed, and its new name. - let mut renamed: std::collections::HashMap = std::collections::HashMap::new(); - let mut steps = 0usize; - let mut added = Vec::with_capacity(imp.actions.len()); - for mut a in imp.actions { - let name = taken.claim(&a.name); - if name != a.name { - renamed.entry(a.name.clone()).or_insert_with(|| name.clone()); - } - a.name = name.clone(); - steps = steps.saturating_add(a.steps.len()); - names.push(name); - added.push(a); - } - // Play and Conditional steps call actions by name: follow the renames in the actions just - // loaded, each target looked up once by the name the file gave it. - for a in &mut added { - for (id, params) in &mut a.steps { - let keys: &[&str] = match id.as_str() { - "actions.play" => &["action"], - "actions.conditional" => &["then", "else"], - _ => &[], - }; - for key in keys { - if let Some(to) = params.get(*key).and_then(Value::as_str).and_then(|n| renamed.get(n)) { - params[*key] = json!(to); - } - } - } - } - s.actions.list.extend(added); - let keys: Vec<(String, String)> = imp.function_keys.into_iter().map(|(n, k)| (renamed.get(&n).cloned().unwrap_or(n), k)).collect(); - if !keys.is_empty() { - s.edit_prefs(|prefs| { - for (name, key) in &keys { - // A function key belongs to one action. - prefs.shortcuts.retain(|k, v| !(k.starts_with(crate::actions_cmds::PLAY_SHORTCUT_PREFIX) && v == key)); - prefs.shortcuts.insert(format!("{}{name}", crate::actions_cmds::PLAY_SHORTCUT_PREFIX), key.clone()); - } - }); - } - s.actions.touch(); - Ok(json!({ - "set": imp.set, - "actions": names, - "steps": steps, - "unsupported": imp.unsupported, - "functionKeys": keys.iter().map(|(n, k)| json!({"action": n, "key": k})).collect::>(), - "warnings": imp.warnings, - })) -} - -fn save(s: &mut Session, p: &Value) -> Result { - let cmd = "actions.save"; - crate::actions_cmds::flush_recording(s)?; - let skip = match p.get("skipUnsupported") { - None | Some(Value::Null) => false, - Some(Value::Bool(b)) => *b, - Some(_) => return Err(bad(cmd, "`skipUnsupported` must be true or false")), - }; - let set_param = match p.get("set") { - None | Some(Value::Null) => None, - Some(Value::String(n)) if !n.trim().is_empty() => Some(n.trim().to_string()), - Some(_) => return Err(bad(cmd, "`set` must be a non-empty string")), - }; - let (set, actions): (String, Vec<&Action>) = if p.get("action").is_some() { - let idx = crate::actions_cmds::resolve(&s.actions.list, p, cmd)?; - let a = &s.actions.list[idx]; - (set_param.or_else(|| a.set.clone()).unwrap_or_else(|| a.name.clone()), vec![a]) - } else if let Some(set) = set_param { - let list: Vec<&Action> = s.actions.list.iter().filter(|a| a.set.as_deref() == Some(set.as_str())).collect(); - if list.is_empty() { - return Err(bad(cmd, format!("no actions in a set named `{set}`"))); - } - (set, list) - } else { - (DEFAULT_SET.to_string(), s.actions.list.iter().collect()) - }; - if actions.is_empty() { - return Err(bad(cmd, "there are no actions to save")); - } - let names: Vec = actions.iter().map(|a| a.name.clone()).collect(); - let keys: Vec<(String, String)> = - s.prefs().shortcuts.iter().filter_map(|(k, v)| k.strip_prefix(crate::actions_cmds::PLAY_SHORTCUT_PREFIX).map(|n| (n.to_string(), v.clone()))).collect(); - let (bytes, skipped) = export(&set, &actions, &keys, skip).map_err(|e| bad(cmd, e))?; - let steps: usize = actions.iter().map(|a| a.steps.len()).sum::().saturating_sub(skipped.len()); - let mut out = json!({"set": set, "actions": names, "steps": steps, "bytes": bytes.len(), "skipped": skipped}); - match p.get("path") { - None | Some(Value::Null) => { - out["data"] = json!(photocraft_paint::tile::b64_encode(&bytes)); - } - Some(Value::String(path)) if !path.trim().is_empty() => { - write_file(path, &bytes).map_err(|e| EngineError::Other(format!("{path}: {e}")))?; - out["path"] = json!(path); - } - Some(_) => return Err(bad(cmd, "`path` must be a non-empty string")), - } - Ok(out) -} - -#[cfg(not(target_arch = "wasm32"))] -fn write_file(path: &str, bytes: &[u8]) -> std::io::Result<()> { - // Atomic replacement (temporary file + rename): a failed write keeps the previous ATN (#7290). - photocraft_format::atomic_write(std::path::Path::new(path), bytes) -} - -#[cfg(target_arch = "wasm32")] -fn write_file(path: &str, _bytes: &[u8]) -> std::io::Result<()> { - Err(std::io::Error::other(format!("cannot write paths on the web ({path}); omit `path` to get the bytes back as `data`"))) -} - -fn stop_message(_: &mut Session, p: &Value) -> Result { - let message = jstr(p, "message").unwrap_or("Stop").to_string(); - if jbool(p, "allowContinue").unwrap_or(false) { - Ok(json!({"message": message, "continued": true})) - } else { - Err(EngineError::Other(format!("stopped by the action: {message}"))) - } -} - -fn photoshop_step_run(_: &mut Session, p: &Value) -> Result { - let name = jstr(p, "name").filter(|n| !n.is_empty()).unwrap_or("this step"); - let event = jstr(p, "event").unwrap_or("?"); - Err(EngineError::Other(format!("Photoshop step \"{name}\" ({event}) has no PhotoCraft equivalent yet; switch it off in the Actions panel to skip it"))) -} - -pub fn specs() -> Vec { - vec![ - CommandSpec { - id: "actions.load", - label: "Load Actions…", - menu: &[], - shortcut: None, - params: r##"{"path":".atn file"?,"data":base64 bytes?,"set":name? (override the file's set name),"replace":bool=true (replace the actions of a set of the same name)} → {set, actions:[names], steps, unsupported:[{action, step, event, name}], functionKeys:[{action, key}], warnings}. Photoshop steps PhotoCraft cannot play become actions.photoshopStep steps (kept for Save Actions; they fail at playback with the step's name); tool selections and other steps with no document effect are imported switched off. Layer references by name replay in any document."##, - enabled: always, - run: load, - journal: false, - }, - CommandSpec { - id: "actions.save", - label: "Save Actions…", - menu: &[], - shortcut: None, - params: r##"{"path":".atn file"? (else the bytes come back as base64 `data`),"set":name? (that set's actions; default: every action, as the set "PhotoCraft Actions"),"action":name|index? (one action),"skipUnsupported":bool=false (leave out steps with no Photoshop equivalent instead of failing)} → {set, actions:[names], steps, bytes, skipped:[{action, step, id}], path|data}"##, - enabled: always, - run: save, - journal: false, - }, - CommandSpec { - id: STOP_MESSAGE, - label: "Stop", - menu: &[], - shortcut: None, - params: r##"{"message":str,"allowContinue":bool=false} (Photoshop's Insert Stop: a step that shows the message; headless playback continues when allowContinue is set and otherwise stops the action with the message)"##, - enabled: always, - run: stop_message, - journal: true, - }, - CommandSpec { - id: PHOTOSHOP_STEP, - label: "Photoshop Step", - menu: &[], - shortcut: None, - params: r##"{"event":id,"name":str,"descriptor":base64?} (a step from a .atn file PhotoCraft has no command for: fails at playback, written back by actions.save)"##, - enabled: always, - run: photoshop_step_run, - journal: true, - }, - ] -} - -#[cfg(test)] -mod tests; - -#[cfg(test)] -mod layer_props_tests; diff --git a/crates/engine/src/channel_cmds.rs b/crates/engine/src/channel_cmds.rs deleted file mode 100644 index 5c6eeaedcd..0000000000 --- a/crates/engine/src/channel_cmds.rs +++ /dev/null @@ -1,2085 +0,0 @@ -//! Channels: alpha and spot channels, Select › Save / Load Selection, Quick Mask, channel -//! targeting and visibility (the Channels panel), Image › Apply Image / Calculations, and the -//! Channels panel menu (Split / Merge Channels, Merge Spot Channel). -//! -//! Alpha channels live in [`Document::channels`] (white = selected). Quick Mask is a temporary -//! channel in [`Document::quick_mask`], so entering and leaving it are history steps like in -//! Photoshop. Which channel is targeted and which are visible is view state on -//! [`DocState::channel_view`] (not history), like the active layer. -//! -//! Pixel commands (`paint.*`, `filter.*`, `image.adjustments.*`, `edit.fill`) take -//! `"target": {"channel": i}` or `"target": "quickMask"`; [`Session::execute`] fills that in from the -//! targeted channel when the caller didn't pass a target. Targeting a single colour channel keeps -//! those commands from touching the other colour channels of the layer ([`restrict_to_color`]). - -use photocraft_algo::selection::{self as sel, SelectionMode}; -use photocraft_color::{BlendMode, Color, ColorMode, PixelFormat, blend::blend_channel}; -use photocraft_doc::{AlphaChannel, ColorIndicates, Document, Layer, LayerContent, LayerId}; -use photocraft_geom::{Rect, TileCoord}; -use photocraft_raster::{Surface, from_rgba, to_rgba}; -use serde::Serialize; -use serde_json::{Value, json}; - -use crate::commands::CommandSpec; -use crate::{DocState, EngineError, Result, Session}; - -#[cfg(test)] -mod tests; - -// --------------------------------------------------------------------------------------------- -// View state - -/// What pixel commands edit (Channels panel click / ⌘2…⌘9). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)] -#[serde(rename_all = "camelCase", tag = "kind", content = "index")] -pub enum ChannelTarget { - /// The layers (all colour channels). In Quick Mask mode this edits the Quick Mask. - #[default] - Composite, - /// One colour channel of the active layer (index into the pixel format's colour channels). - Color(usize), - /// An alpha or spot channel (index into [`Document::channels`]). - Alpha(usize), - /// The active layer's layer mask. - LayerMask, - /// The active layer's vector mask. - VectorMask, -} - -/// Per-document Channels panel state: the target and the eye toggles. Not part of history. -#[derive(Clone, Debug, Default, PartialEq, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct ChannelView { - pub target: ChannelTarget, - /// Hidden colour channels (missing entries are visible). - pub color_hidden: Vec, - /// Visible alpha channels (missing entries are hidden). - pub alpha_visible: Vec, - pub quick_mask_hidden: bool, - /// ⌥-click view of the active layer's mask (#196); see [`crate::mask_view_cmds`]. - pub layer_mask: Option, -} - -impl ChannelView { - pub fn color_visible(&self, k: usize) -> bool { - !self.color_hidden.get(k).copied().unwrap_or(false) - } - pub fn alpha_shown(&self, i: usize) -> bool { - self.alpha_visible.get(i).copied().unwrap_or(false) - } - pub fn set_color_visible(&mut self, k: usize, v: bool) { - if self.color_hidden.len() <= k { - self.color_hidden.resize(k + 1, false); - } - self.color_hidden[k] = !v; - } - pub fn set_alpha_visible(&mut self, i: usize, v: bool) { - if self.alpha_visible.len() <= i { - self.alpha_visible.resize(i + 1, false); - } - self.alpha_visible[i] = v; - } - /// Number of visible colour channels out of `colors`. - pub fn visible_colors(&self, colors: usize) -> usize { - (0..colors).filter(|k| self.color_visible(*k)).count() - } - /// True when the canvas shows just the normal composite (nothing extra to draw). - pub fn is_plain(&self, doc: &Document) -> bool { - let colors = color_count(doc); - self.visible_colors(colors) == colors - && !(0..doc.channels.len()).any(|i| self.alpha_shown(i)) - && (doc.quick_mask.is_none() || self.quick_mask_hidden) - && self.shown_layer_mask(doc).is_none() - } - /// The layer mask shown on the canvas (#196) and how, if its layer still has a mask. - pub fn shown_layer_mask<'a>(&self, doc: &'a Document) -> Option<(&'a photocraft_doc::LayerMask, crate::mask_view_cmds::MaskViewMode)> { - let v = self.layer_mask?; - Some((crate::mask_view_cmds::viewed_mask(doc.layer(v.layer)?, v.filter)?, v.mode)) - } -} - -/// Session-wide Quick Mask Options (double-click the Quick Mask button in Photoshop). -#[derive(Clone, Copy, Debug, PartialEq, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct QuickMaskOptions { - pub color: Color, - pub opacity: f32, - pub indicates: ColorIndicates, -} - -impl Default for QuickMaskOptions { - fn default() -> Self { - Self { color: AlphaChannel::DEFAULT_COLOR, opacity: 0.5, indicates: ColorIndicates::MaskedAreas } - } -} - -/// Keep the view valid after the document changed (undo, deleted channels, mode changes). -pub(crate) fn fix_view(st: &mut DocState) { - let n = st.doc.channels.len(); - let colors = color_count(&st.doc); - let quick = st.doc.quick_mask.is_some(); - { - let v = &mut st.channel_view; - v.alpha_visible.truncate(n); - v.color_hidden.truncate(colors); - match v.target { - ChannelTarget::Alpha(i) if i >= n => v.target = ChannelTarget::Composite, - ChannelTarget::Color(k) if k >= colors || colors < 2 => v.target = ChannelTarget::Composite, - ChannelTarget::LayerMask if st.active_layer.and_then(|id| st.doc.layer(id)).is_none_or(|l| l.mask.is_none()) => { - v.target = ChannelTarget::Composite; - } - ChannelTarget::VectorMask if st.active_layer.and_then(|id| st.doc.layer(id)).is_none_or(|l| l.vector_mask.is_none()) => { - v.target = ChannelTarget::Composite; - } - _ => {} - } - } - crate::mask_view_cmds::fix(st); - // An alpha/spot eye, Quick Mask, or the active layer's mask can be the only thing on the - // canvas (so R, G and B can all be off). Otherwise the colour channels come back. - let active = st.active_layer; - let shown = { - let doc = &st.doc; - let v = &st.channel_view; - (0..n).any(|i| v.alpha_shown(i)) || (quick && !v.quick_mask_hidden) || active.is_some_and(|id| doc.layer(id).is_some_and(|l| l.mask.is_some())) - }; - if st.channel_view.visible_colors(colors) == 0 && !shown { - st.channel_view.color_hidden.clear(); - } -} - -/// Bump the revision for a view-only change without dirtying a clean document. -fn touch(st: &mut DocState) { - let clean = st.saved_revision == st.revision; - st.revision += 1; - st.view_revision += 1; - if clean { - st.saved_revision = st.revision; - } - st.last_damage = None; -} - -// --------------------------------------------------------------------------------------------- -// Channel names and formats - -/// Colour channel names of a document mode (the rows under the composite). -pub fn color_names(mode: ColorMode) -> &'static [&'static str] { - match mode { - ColorMode::Cmyk => &["Cyan", "Magenta", "Yellow", "Black"], - ColorMode::Lab => &["Lightness", "a", "b"], - ColorMode::Grayscale => &["Gray"], - _ => &["Red", "Green", "Blue"], - } -} - -/// Name of the composite row. -pub fn composite_name(mode: ColorMode) -> &'static str { - match mode { - ColorMode::Cmyk => "CMYK", - ColorMode::Lab => "Lab", - ColorMode::Grayscale => "Gray", - _ => "RGB", - } -} - -/// The Curves dialog's Channel popup lists only this channel when the Channels panel has a -/// single non-composite target (a colour component, layer mask, saved channel or Quick Mask). -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct IsolatedCurveChannel { - /// Channels-panel name, including a custom alpha name or "{layer} Mask". - pub name: String, - /// Curves param key: empty = composite `points`; otherwise `red`/`green`/… - pub key: &'static str, - /// Index into the tone-space histograms (composite = 0 for RGB/CMYK). - pub hist: usize, - /// Colour components keep their curve tint; masks and alphas do not. - pub tint: bool, - /// Built-in labels (colour channels, Quick Mask) follow the interface language; a custom - /// alpha name or a "{layer} Mask" keeps the layer name, so it stays exactly as entered (#5335). - pub translate: bool, - /// The gray plane this target edits, whatever the document's colour mode; its surface is - /// what the dialog's histogram must describe (#5335). None for colour components. - pub gray: Option, -} - -/// A grayscale plane Curves can target: the dialog parses and previews its curves in gray levels -/// even in Lab and CMYK documents (#5335). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum GraySurface { - /// The active layer's layer mask. - LayerMask, - /// A saved channel, as an index into [`Document::channels`]. - Alpha(usize), - /// The Quick Mask. - QuickMask, - /// The active smart object's filter mask (FILE-215-3). - FilterMask, -} - -/// Isolated Curves channel for the active document, matching [`inject_target`]. -pub fn isolated_curve_channel(st: &DocState) -> Option { - isolated_curve_channel_for(st, false) -} - -/// [`isolated_curve_channel`] with the Layers panel's mask target added: clicking a mask -/// thumbnail targets it without touching the Channels panel, and both ways of selecting the mask -/// must give the same Curves dropdown (#5335). -pub fn isolated_curve_channel_for(st: &DocState, layers_panel_mask: bool) -> Option { - let doc = &st.doc; - let mode = edit_mode(doc); - match st.channel_view.target { - ChannelTarget::Color(k) => { - let names = color_names(mode); - let keys = crate::adjust_params::channel_keys(crate::adjust_params::default_space(mode)); - let name = names.get(k)?.to_string(); - let key = *keys.get(k)?; - let hist = if matches!(mode, ColorMode::Lab) { k } else { k.saturating_add(1) }; - Some(IsolatedCurveChannel { name, key, hist, tint: true, translate: true, gray: None }) - } - ChannelTarget::Alpha(i) => doc.channels.get(i).map(|c| IsolatedCurveChannel { - name: c.name.clone(), - key: "", - hist: 0, - tint: false, - translate: false, - gray: Some(GraySurface::Alpha(i)), - }), - ChannelTarget::Composite if doc.quick_mask.is_some() => { - Some(IsolatedCurveChannel { name: "Quick Mask".into(), key: "", hist: 0, tint: false, translate: true, gray: Some(GraySurface::QuickMask) }) - } - ChannelTarget::LayerMask => layer_mask_curve_channel(st), - ChannelTarget::Composite if crate::mask_view_cmds::current(st).is_some_and(|v| v.filter) => filter_mask_curve_channel(st), - ChannelTarget::Composite if crate::mask_view_cmds::current(st).is_some() || layers_panel_mask => layer_mask_curve_channel(st), - _ => None, - } -} - -fn layer_mask_curve_channel(st: &DocState) -> Option { - let layer = st.active_layer.and_then(|id| st.doc.layer(id))?; - layer.mask.as_ref()?; - let name = format!("{} Mask", layer.name); - Some(IsolatedCurveChannel { name, key: "", hist: 0, tint: false, translate: false, gray: Some(GraySurface::LayerMask) }) -} - -/// The Curves target when the active smart object's filter mask is targeted (its thumbnail on the -/// Smart Filters row, FILE-215-3): a gray plane, though the mask may not exist until the first edit. -pub fn filter_mask_curve_channel(st: &DocState) -> Option { - let layer = st.active_layer.and_then(|id| st.doc.layer(id))?; - crate::smart_cmds::filter_mask_paintable(layer).ok()?; - let name = format!("{} Filter Mask", layer.name); - Some(IsolatedCurveChannel { name, key: "", hist: 0, tint: false, translate: false, gray: Some(GraySurface::FilterMask) }) -} - -fn edit_mode(doc: &Document) -> ColorMode { - doc.pixel_format().mode -} - -pub fn color_count(doc: &Document) -> usize { - edit_mode(doc).color_channels() -} - -/// Pixel format of alpha channels: grayscale at the document depth, no transparency. -pub fn channel_format(doc: &Document) -> PixelFormat { - PixelFormat::new(ColorMode::Grayscale, doc.depth, false) -} - -/// Next free "`base` N" name (Alpha 1, Spot Color 2, …). -pub fn next_alpha_name(doc: &Document, base: &str) -> String { - // `channels.len() + 1` candidates always include a free one. - (1..=doc.channels.len() + 1).map(|n| format!("{base} {n}")).find(|n| !doc.channels.iter().any(|c| &c.name == n)).unwrap_or_else(|| base.to_string()) -} - -// --------------------------------------------------------------------------------------------- -// Planes: one grayscale value per canvas pixel - -fn read_plane(s: &Surface, r: Rect) -> Vec { - let mut v = Vec::new(); - s.read_region_into(r, &mut v); - let ch = s.channels(); - if ch > 1 { v.chunks_exact(ch).map(|p| p[0]).collect() } else { v } -} - -fn plane_surface(vals: &[f32], r: Rect, fmt: PixelFormat) -> Surface { - let mut s = Surface::new(fmt); - let clamped: Vec = vals.iter().map(|v| v.clamp(0.0, 1.0)).collect(); - s.write_region(r, &clamped); - s.prune(); - s -} - -/// Make every canvas pixel of `s` explicit so filters and adjustments that work on the content -/// bounds also see the untouched (default-valued) parts of a channel. -fn materialize(s: &mut Surface, r: Rect) { - let v = s.read_region(r); - s.write_region(r, &v); -} - -fn luminosity(rgba: [f32; 4]) -> f32 { - 0.299 * rgba[0] + 0.587 * rgba[1] + 0.114 * rgba[2] -} - -// --------------------------------------------------------------------------------------------- -// Channel references - -/// A channel named in params: `"composite"`, a colour name (`"red"`, `"cyan"`, `"lightness"`…), -/// an alpha index (number) or name, `"quickMask"`, `"selection"`, `"transparency"`, `"mask"`. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum ChanRef { - Composite, - Color(usize), - Alpha(usize), - QuickMask, - Selection, - Transparency, - LayerMask, - /// The layer's vector mask, rasterized (⌘-click its thumbnail, #196). - VectorMask, -} - -pub fn parse_ref(v: &Value, doc: &Document) -> Option { - let mode = edit_mode(doc); - match v { - Value::Number(n) => n.as_u64().map(|i| ChanRef::Alpha(i as usize)), - Value::Object(o) => { - if let Some(k) = o.get("color").and_then(Value::as_u64) { - Some(ChanRef::Color(k as usize)) - } else { - o.get("alpha").and_then(Value::as_u64).map(|i| ChanRef::Alpha(i as usize)) - } - } - Value::String(s) => { - let l = s.to_ascii_lowercase(); - match l.as_str() { - "composite" | "merged" => return Some(ChanRef::Composite), - "quickmask" | "quick mask" => return Some(ChanRef::QuickMask), - "selection" => return Some(ChanRef::Selection), - "transparency" => return Some(ChanRef::Transparency), - "mask" | "layermask" => return Some(ChanRef::LayerMask), - "vectormask" | "vector mask" => return Some(ChanRef::VectorMask), - _ => {} - } - if l == composite_name(mode).to_ascii_lowercase() { - return Some(ChanRef::Composite); - } - if let Some(k) = color_names(mode).iter().position(|n| n.eq_ignore_ascii_case(&l)) { - return Some(if color_names(mode).len() == 1 { ChanRef::Composite } else { ChanRef::Color(k) }); - } - doc.channels.iter().position(|c| c.name == *s).map(ChanRef::Alpha) - } - _ => None, - } -} - -fn bad(cmd: &str, msg: impl Into) -> EngineError { - EngineError::BadParams { cmd: cmd.into(), msg: msg.into() } -} - -fn doc_index(s: &Session, p: &Value, key: &str) -> Result { - match crate::commands::int(p, key).and_then(|v| u64::try_from(v).ok()) { - Some(i) if (i as usize) < s.documents().len() => Ok(i as usize), - Some(i) => Err(EngineError::Other(format!("no open document {i}"))), - None => s.active_index().ok_or(EngineError::NoDocument), - } -} - -/// Alpha channel index from `p[key]` (number or name), checked against the document. -fn alpha_index(doc: &Document, p: &Value, key: &str, cmd: &str) -> Result { - match p.get(key).and_then(|v| parse_ref(v, doc)) { - Some(ChanRef::Alpha(i)) if i < doc.channels.len() => Ok(i), - Some(ChanRef::Alpha(i)) => Err(bad(cmd, format!("no alpha channel {i} (document has {})", doc.channels.len()))), - _ => Err(bad(cmd, format!("`{key}` must name an alpha channel (index or name)"))), - } -} - -// --------------------------------------------------------------------------------------------- -// Sources (Load Selection, Apply Image, Calculations) - -/// Native pixel values of a layer or of the merged image over the canvas. -fn native_pixels(doc: &Document, layer: Option) -> Result<(Vec, usize)> { - let r = doc.bounds(); - let fmt = doc.pixel_format(); - let n = fmt.channels(); - match layer { - Some(id) => { - let l = doc.layer(id).ok_or(EngineError::NoLayer(id))?; - let s = l.surface().ok_or_else(|| EngineError::Other(format!("layer \"{}\" has no pixels", l.name)))?; - if s.format() == fmt { - return Ok((s.read_region(r), n)); - } - let raw = s.read_region(r); - let sf = s.format(); - Ok((raw.chunks_exact(sf.channels()).flat_map(|p| from_rgba(&fmt, to_rgba(&sf, p))).collect(), n)) - } - None => { - let buf = photocraft_compose::render(doc, r); - Ok((buf.px.iter().flat_map(|p| from_rgba(&fmt, *p)).collect(), n)) - } - } -} - -/// `"layer"` param of a source: a layer id, a layer name (the topmost of that name, as a loaded -/// Photoshop action refers to it), or `"merged"` (default). An unknown name is an error. -fn source_layer(doc: &Document, p: &Value, cmd: &str) -> Result> { - match p.get("layer") { - Some(Value::Number(n)) => Ok(n.as_u64().map(LayerId)), - Some(Value::String(name)) if !name.is_empty() && name != "merged" => doc - .walk() - .into_iter() - .rev() - .find(|(_, _, l)| l.name == *name) - .map(|(_, _, l)| Some(l.id)) - .ok_or_else(|| bad(cmd, format!("no source layer named \"{name}\""))), - _ => Ok(None), - } -} - -/// Planes of channel `r` from document `doc` (`layer` = None: merged). A composite gives one -/// plane per colour channel; everything else gives one plane. -fn ref_planes(doc: &Document, layer: Option, active: Option, r: ChanRef) -> Result>> { - let area = doc.bounds(); - let colors = color_count(doc); - Ok(match r { - ChanRef::Composite | ChanRef::Color(_) => { - let (px, n) = native_pixels(doc, layer)?; - let planes: Vec> = (0..colors).map(|c| px.chunks_exact(n).map(|p| p[c]).collect()).collect(); - match r { - ChanRef::Color(k) => vec![planes.get(k).cloned().ok_or_else(|| EngineError::Other(format!("no colour channel {k}")))?], - _ => planes, - } - } - ChanRef::Alpha(i) => vec![read_plane(&doc.channels.get(i).ok_or_else(|| EngineError::Other(format!("no alpha channel {i}")))?.surface, area)], - ChanRef::QuickMask => vec![read_plane(&doc.quick_mask.as_ref().ok_or_else(|| EngineError::Other("not in Quick Mask mode".into()))?.surface, area)], - ChanRef::Selection => vec![sel::mask_from_surface(doc.selection.as_ref(), area)], - ChanRef::Transparency => { - let id = layer.or(active).ok_or_else(|| EngineError::Other("transparency needs a layer".into()))?; - let l = doc.layer(id).ok_or(EngineError::NoLayer(id))?; - match l.surface() { - Some(s) => { - let mut px = vec![[0.0f32; 4]; area.width() as usize * area.height() as usize]; - s.read_rgba_into(area, &mut px); - vec![px.iter().map(|p| p[3]).collect()] - } - // A shape can have no pixel cache yet (for example after loading a document). - // Use its existing renderer rather than treating it as a canvas-wide fill. - None => match &l.content { - LayerContent::Shape(shape) => vec![ - photocraft_vector::CompiledShape::new(shape, photocraft_vector::DEFAULT_TOLERANCE, area) - .render_rgba(area) - .into_iter() - .map(|p| p[3]) - .collect(), - ], - // Adjustment and fill layers cover the whole canvas. - _ => vec![vec![1.0; area.width() as usize * area.height() as usize]], - }, - } - } - ChanRef::LayerMask => { - let id = layer.or(active).ok_or_else(|| EngineError::Other("layer mask needs a layer".into()))?; - let l = doc.layer(id).ok_or(EngineError::NoLayer(id))?; - let m = l.mask.as_ref().ok_or_else(|| EngineError::Other(format!("layer \"{}\" has no mask", l.name)))?; - vec![read_plane(&m.surface, area)] - } - ChanRef::VectorMask => { - let id = layer.or(active).ok_or_else(|| EngineError::Other("vector mask needs a layer".into()))?; - let l = doc.layer(id).ok_or(EngineError::NoLayer(id))?; - let m = l.vector_mask.as_ref().ok_or_else(|| EngineError::Other(format!("layer \"{}\" has no vector mask", l.name)))?; - // The path's shape, whether or not the mask is enabled (as Photoshop loads it). - let shape = photocraft_doc::VectorMask { enabled: true, density: 1.0, feather: 0.0, ..m.clone() }; - vec![photocraft_vector::vector_mask_values(&shape, area)] - } - }) -} - -/// One grayscale plane (composites reduce to luminosity, as in Calculations). -fn gray_plane(doc: &Document, layer: Option, active: Option, r: ChanRef) -> Result> { - let mut planes = ref_planes(doc, layer, active, r)?; - if planes.len() == 1 - && let Some(only) = planes.pop() - { - return Ok(only); - } - let fmt = doc.pixel_format(); - let n = planes.first().map_or(0, Vec::len); - let mut px = vec![0.0f32; fmt.channels()]; - Ok((0..n) - .map(|i| { - for (c, p) in planes.iter().enumerate() { - px[c] = p[i]; - } - if fmt.alpha { - px[planes.len()] = 1.0; - } - luminosity(to_rgba(&fmt, &px)) - }) - .collect()) -} - -/// A source spec `{document?, layer?, channel, invert?}`, reduced to planes over the canvas of -/// the active document (sizes must match, as in Photoshop). -fn source(s: &Session, p: &Value, cmd: &str, gray: bool) -> Result>> { - let di = doc_index(s, p, "document")?; - let st = &s.documents()[di]; - let target = s.active().ok_or(EngineError::NoDocument)?; - if st.doc.size != target.doc.size { - return Err(bad(cmd, format!("source document \"{}\" is {}×{}; it must match the target size", st.doc.name, st.doc.size.width, st.doc.size.height))); - } - let r = p.get("channel").map_or(Some(ChanRef::Composite), |v| parse_ref(v, &st.doc)).ok_or_else(|| bad(cmd, "unknown `channel`"))?; - let layer = source_layer(&st.doc, p, cmd)?; - let mut planes = if gray { vec![gray_plane(&st.doc, layer, st.active_layer, r)?] } else { ref_planes(&st.doc, layer, st.active_layer, r)? }; - // Guard every caller (`.remove(0)` / `src[0]`) against an empty source. - if planes.is_empty() { - return Err(bad(cmd, "the source has no channels")); - } - if p.get("invert").and_then(Value::as_bool).unwrap_or(false) { - for pl in &mut planes { - for v in pl.iter_mut() { - *v = 1.0 - *v; - } - } - } - Ok(planes) -} - -// --------------------------------------------------------------------------------------------- -// Blending (Apply Image / Calculations) - -/// Apply Image / Calculations blending: the separable layer modes plus Add and Subtract with -/// scale and offset. -#[derive(Clone, Copy, Debug, PartialEq)] -pub enum Blending { - Mode(BlendMode), - Add { scale: f32, offset: f32 }, - Subtract { scale: f32, offset: f32 }, -} - -impl Blending { - pub fn parse(p: &Value) -> std::result::Result { - let name = p.get("blending").and_then(Value::as_str).unwrap_or("multiply"); - let scale = p.get("scale").and_then(Value::as_f64).unwrap_or(1.0).clamp(1.0, 2.0) as f32; - let offset = p.get("offset").and_then(Value::as_f64).unwrap_or(0.0).clamp(-255.0, 255.0) as f32 / 255.0; - match name.to_ascii_lowercase().as_str() { - "add" => Ok(Blending::Add { scale, offset }), - "subtract" => Ok(Blending::Subtract { scale, offset }), - other => match crate::commands::blend_from_str(other) { - Some(m) if m.is_separable() && !matches!(m, BlendMode::Dissolve | BlendMode::PassThrough) => Ok(Blending::Mode(m)), - _ => Err(format!("unsupported blending `{other}`")), - }, - } - } - - /// Blend `top` (the source) onto `base` (the target). - pub fn apply(self, base: f32, top: f32) -> f32 { - match self { - Blending::Mode(m) => blend_channel(m, base, top), - Blending::Add { scale, offset } => (base + top) / scale + offset, - Blending::Subtract { scale, offset } => (base - top) / scale + offset, - } - .clamp(0.0, 1.0) - } -} - -/// A source spec from `p[key]`, or from flat `Document` / `Layer` / -/// `Channel` / `Invert` keys (what the generic dialog form sends). -pub(crate) fn source_spec(p: &Value, key: &str, prefix: &str) -> Option { - if let Some(v) = p.get(key) { - return Some(v.clone()); - } - let mut m = serde_json::Map::new(); - for (k, field) in [("document", "Document"), ("layer", "Layer"), ("channel", "Channel"), ("invert", "Invert")] { - match p.get(format!("{prefix}{field}")) { - None | Some(Value::Null) => {} - Some(Value::String(s)) if s.is_empty() || (k == "layer" && s == "merged") => {} - Some(v) => { - m.insert(k.into(), v.clone()); - } - } - } - (!m.is_empty()).then_some(Value::Object(m)) -} - -fn mask_plane(s: &Session, p: &Value, cmd: &str) -> Result>> { - match source_spec(p, "mask", "mask") { - None | Some(Value::Null) | Some(Value::Bool(false)) => Ok(None), - Some(m) if m.get("channel").is_none_or(|c| c == "none") => Ok(None), - Some(m) => Ok(Some(source(s, &m, cmd, true)?.remove(0))), - } -} - -// --------------------------------------------------------------------------------------------- -// Targets for pixel commands - -/// Where a pixel command writes, from its `"target"` param. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum Target { - Pixels, - Mask, - /// A smart object's filter mask (`"target":"filterMask"`): where it is black the smart - /// filters don't show (FILE-215-3). - FilterMask, - Alpha(usize), - QuickMask, -} - -pub(crate) fn target_of(p: &Value) -> Target { - match p.get("target") { - Some(Value::String(s)) => match s.as_str() { - "mask" => Target::Mask, - "filterMask" => Target::FilterMask, - "quickMask" => Target::QuickMask, - _ => Target::Pixels, - }, - Some(Value::Object(o)) => o.get("channel").and_then(Value::as_u64).map_or(Target::Pixels, |i| Target::Alpha(i as usize)), - _ => Target::Pixels, - } -} - -/// The target is an alpha channel or the Quick Mask (no layer involved). -pub(crate) fn is_channel_target(p: &Value) -> bool { - matches!(target_of(p), Target::Alpha(_) | Target::QuickMask) -} - -/// The surface a pixel command writes to and whether the layer's transparency is locked. -pub(crate) fn target_surface<'a>(doc: &'a mut Document, layer: Option, p: &Value) -> Result<(&'a mut Surface, bool)> { - match target_of(p) { - Target::Alpha(i) => { - let n = doc.channels.len(); - doc.channels.get_mut(i).map(|c| (&mut c.surface, false)).ok_or_else(|| EngineError::Other(format!("no alpha channel {i} (document has {n})"))) - } - Target::QuickMask => doc.quick_mask.as_mut().map(|c| (&mut c.surface, false)).ok_or_else(|| EngineError::Other("not in Quick Mask mode".into())), - t => { - let id = layer.ok_or_else(|| EngineError::Other("no active layer".into()))?; - let lock = doc.effective_locks(id).transparency && t == Target::Pixels; - Ok((crate::commands::paint_surface(doc, id, p)?, lock)) - } - } -} - -pub(crate) fn read_target_surface<'a>(doc: &'a Document, layer: Option, p: &Value) -> Result<&'a Surface> { - match target_of(p) { - Target::Alpha(i) => { - let n = doc.channels.len(); - doc.channels.get(i).map(|c| &c.surface).ok_or_else(|| EngineError::Other(format!("no alpha channel {i} (document has {n})"))) - } - Target::QuickMask => doc.quick_mask.as_ref().map(|c| &c.surface).ok_or_else(|| EngineError::Other("not in Quick Mask mode".into())), - Target::Pixels => { - let id = layer.ok_or_else(|| EngineError::Other("no active layer".into()))?; - doc.layer(id).and_then(Layer::surface).ok_or(EngineError::NoLayer(id)) - } - Target::Mask => { - let id = layer.ok_or_else(|| EngineError::Other("no active layer".into()))?; - doc.layer(id).and_then(|l| l.mask.as_ref()).map(|m| &m.surface).ok_or(EngineError::NoLayer(id)) - } - Target::FilterMask => { - let id = layer.ok_or_else(|| EngineError::Other("no active layer".into()))?; - doc.layer(id) - .and_then(|l| crate::mask_view_cmds::viewed_mask(l, true)) - .map(|m| &m.surface) - .ok_or_else(|| EngineError::Other("the layer has no filter mask".into())) - } - } -} - -/// The grayscale surface filters and adjustments edit instead of the layer's pixels (made explicit -/// over the canvas), if the params target one: an alpha channel, the Quick Mask, or the mask of -/// `layer`. -pub(crate) fn channel_surface_for_filter<'a>(doc: &'a mut Document, layer: Option, p: &Value) -> Result> { - if target_of(p) == Target::Pixels { - return Ok(None); - } - let b = doc.bounds(); - let (surf, _) = target_surface(doc, layer, p)?; - materialize(surf, b); - Ok(Some(surf)) -} - -/// Commands that edit a targeted layer mask in place of the layer: the Image › Adjustments table, -/// the filters and the fills (Edit › Fill and its keys). A mask target enables them on any layer -/// with a mask, so ⌘I inverts an adjustment layer's mask (#780) and Fill fills it (#2456) as in -/// Photoshop. -fn edits_mask(id: &str) -> bool { - id.strip_prefix("image.adjustments.").is_some_and(|kind| crate::adjust_params::default_for(kind, ColorMode::Rgb).is_ok()) - || crate::filters::params_for(id, &Value::Null).is_some() - || id == "edit.fill" - // Copying a targeted mask (#2928). - || id == "edit.copy" - || crate::fill_key_cmds::IDS.contains(&id) -} - -/// The precondition of `id` when `p` targets the active layer's mask (`"target":"mask"`): the -/// layer needs a mask. None when another precondition applies. -pub(crate) fn mask_target_enabled(s: &Session, id: &str, p: &Value) -> Option> { - match target_of(p) { - // The commands that paint, fill, filter or adjust the filter mask need a smart object with - // smart filters, not a pixel layer. Paste keeps its own check (something to paste). - Target::FilterMask if follows_filter_mask(id) && !PASTE_IDS.contains(&id) => { - Some(crate::active_layer_of(s).and_then(crate::smart_cmds::filter_mask_paintable)) - } - Target::Mask if edits_mask(id) => { - Some(crate::active_layer_of(s).and_then(|l| if l.mask.is_some() { Ok(()) } else { Err("the active layer has no layer mask".into()) })) - } - _ => None, - } -} - -/// Whether command `id` edits the targeted channel or mask when its params name no `"target"` -/// (filters, adjustments, paint and fill commands); the shell adds its mask target to these. -pub fn follows_target(id: &str) -> bool { - // Moving the selected pixels (⌘-drag, Move tool) moves the targeted mask's, not the layer's. - // Moving a layer with its unlinked mask targeted moves the mask alone (`layer.translate`). - routed(id) || id == "select.float" || id == "layer.translate" -} - -/// Whether command `id` edits a smart object's targeted filter mask (`"target":"filterMask"`): -/// every routed command but those that act on the smart object itself while its filter mask is -/// targeted (Edit › Transform, Apply Image, Convert for Smart Filters, Last Filter, Liquify, the -/// lens filters and Vanishing Point, which add a smart filter, the render filters that make a new -/// layer, and Desaturate), so neither the shell nor the engine sends those the filter mask. -pub fn follows_filter_mask(id: &str) -> bool { - routed(id) - && !id.starts_with("edit.transform.") - && !matches!( - id, - "image.applyImage" - | "image.adjustments.desaturate" - | "filter.vanishingPoint" - | "filter.render.flame" - | "filter.render.tree" - | "filter.render.pictureFrame" - | "filter.convertForSmartFilters" - | "filter.lastFilter" - | crate::distort_cmds::LIQUIFY - | crate::lens_cmds::LENS - | crate::lens_cmds::WIDE - | crate::lens_cmds::RAW - ) -} - -/// The paint and retouch tools that follow the targeted channel or mask. -const PAINT_IDS: &[&str] = &[ - "paint.stroke", - "paint.pencil", - "paint.bucket", - "paint.gradient", - "paint.mixerBrush", - "paint.cloneStamp", - "paint.patternStamp", - "paint.healingBrush", - "paint.spotHealing", - "paint.dodge", - "paint.burn", - "paint.sponge", - "paint.blur", - "paint.sharpen", - "paint.smudge", - "paint.historyBrush", - "paint.artHistoryBrush", - "paint.redEye", - "paint.remove", -]; - -/// Pasting into a targeted mask or channel (#1035). -const PASTE_IDS: &[&str] = &["edit.paste", "edit.pasteSpecial.pasteInPlace", "edit.pasteSpecial.pasteInto", "edit.pasteSpecial.pasteOutside"]; - -/// Commands whose target follows the Channels panel. -pub(crate) fn routed(id: &str) -> bool { - id.starts_with("filter.") - || id == "plugin.run" - || id.starts_with("image.adjustments.") - || matches!(id, "edit.fill" | "image.applyImage") - || crate::fill_key_cmds::IDS.contains(&id) - || PAINT_IDS.contains(&id) - // Pasting into a targeted mask or channel (#1035); Copy takes a targeted mask (#2928). - || id == "edit.copy" - || PASTE_IDS.contains(&id) - // Edit › Transform › Rotate/Flip turn a targeted mask or channel (#2835). - || matches!( - id, - "edit.transform.rotate180" - | "edit.transform.rotate90Cw" - | "edit.transform.rotate90Ccw" - | "edit.transform.flipHorizontal" - | "edit.transform.flipVertical" - ) -} - -/// Fill in `"target"` from the targeted channel (or Quick Mask mode) when the caller gave none. -pub(crate) fn inject_target(s: &Session, id: &str, params: Value) -> Value { - if !routed(id) || params.get("target").is_some() { - return params; - } - let Some(st) = s.active() else { return params }; - let t = match st.channel_view.target { - ChannelTarget::Alpha(i) if i < st.doc.channels.len() => json!({ "channel": i }), - ChannelTarget::Composite if st.doc.quick_mask.is_some() => json!("quickMask"), - ChannelTarget::LayerMask => json!("mask"), - // Viewing the active layer's mask (⌥-click): pixel commands edit the mask. - // A shown filter mask takes only the commands that edit it; the rest act on the smart object. - ChannelTarget::Composite if crate::mask_view_cmds::current(st).is_some_and(|v| v.filter) => { - if !follows_filter_mask(id) { - return params; - } - json!("filterMask") - } - ChannelTarget::Composite if crate::mask_view_cmds::current(st).is_some() => json!("mask"), - _ => return params, - }; - match params { - Value::Object(mut m) => { - m.insert("target".into(), t); - Value::Object(m) - } - _ => json!({ "target": t }), - } -} - -/// The smart object whose filter mask command `id` with `params` edits (`"target":"filterMask"`): -/// its `"layer"` param, else the active layer. None for a command that doesn't edit the filter -/// mask, so moving the smart object doesn't re-render its filters. -pub(crate) fn filter_mask_layer(s: &Session, id: &str, params: &Value) -> Option { - if target_of(params) != Target::FilterMask || !follows_filter_mask(id) { - return None; - } - params.get("layer").and_then(Value::as_u64).map(LayerId).or_else(|| s.active()?.active_layer) -} - -/// The colour channel pixel commands are limited to, if a single colour channel is targeted. -pub(crate) fn color_restriction(s: &Session, id: &str, params: &Value) -> Option { - if !routed(id) || is_channel_target(params) || crate::commands::is_mask_target(params) { - return None; - } - match s.active()?.channel_view.target { - ChannelTarget::Color(k) => Some(k), - _ => None, - } -} - -/// After a pixel edit with colour channel `k` targeted, put the other channels (and the layer's -/// transparency) of layer `id` back as they were. Only changed tiles are touched. -pub(crate) fn restrict_to_color(before: &Document, after: &mut Document, id: LayerId, k: usize) { - let Some(old) = before.layer(id).and_then(Layer::surface) else { return }; - let Some(new) = after.layer_mut(id).and_then(Layer::surface_mut) else { return }; - if old.format() != new.format() { - return; - } - let mut coords: Vec = new.tiles().filter(|(c, t)| old.tile(**c).is_none_or(|o| !std::sync::Arc::ptr_eq(o, t))).map(|(c, _)| *c).collect(); - coords.extend(old.tiles().filter(|(c, _)| new.tile(**c).is_none()).map(|(c, _)| *c)); - let n = new.channels(); - for c in coords { - let r = c.rect(); - let o = old.read_region(r); - let mut v = new.read_region(r); - for (pn, po) in v.chunks_exact_mut(n).zip(o.chunks_exact(n)) { - for ch in 0..n { - if ch != k { - pn[ch] = po[ch]; - } - } - } - new.write_region(r, &v); - } - new.prune(); -} - -/// The colour channel Clear is limited to: the Channels panel targets a single one. -pub(crate) fn targeted_color(s: &Session) -> Option { - match s.active()?.channel_view.target { - ChannelTarget::Color(k) => Some(k), - _ => None, - } -} - -/// Clear (Delete) with colour channel `k` of layer `id` targeted (#2720): fill the selected area -/// (or the canvas) of that channel only with the background colour's value for it, as Photoshop -/// does. A channel has no transparency of its own, so the other channels and the layer's alpha -/// stay; partly selected pixels blend. -pub(crate) fn clear_color_channel(doc: &mut Document, id: LayerId, k: usize, background: [f32; 4]) -> Result<()> { - let canvas = doc.bounds(); - let sel = doc.selection.clone(); - let area = sel.as_ref().map_or(canvas, |m| m.content_bounds().intersect(&canvas)); - let surf = crate::commands::paint_surface(doc, id, &Value::Null)?; - let fmt = surf.format(); - let n = fmt.channels(); - // The background colour in the layer's colour model, so `k` picks the right component. - let Some(v) = from_rgba(&fmt, [background[0], background[1], background[2], 1.0]).get(k).copied().filter(|_| k < n) else { - return Err(EngineError::Other(format!("no colour channel {k} in this layer"))); - }; - if area.is_empty() { - return Ok(()); - } - let cover = - sel.as_ref().map(|m| crate::allocation::read_region(m, area, "clearing a channel selection").map(|v| (v, m.format().channels().max(1)))).transpose()?; - let mut px = crate::allocation::read_region(surf, area, "clearing a channel")?; - for (i, p) in px.chunks_exact_mut(n).enumerate() { - let w = cover.as_ref().map_or(1.0, |(m, mk)| m.get(i * mk).copied().unwrap_or(0.0)); - if let Some(c) = p.get_mut(k) { - *c += (v - *c) * w.clamp(0.0, 1.0); - } - } - surf.try_write_region(area, &px)?; - surf.prune(); - Ok(()) -} - -/// The alpha channel or Quick Mask the Channels panel targets, as `"target"` params: Clear -/// (Delete) fills it instead of the layer (#2734). -pub(crate) fn targeted_channel(s: &Session) -> Option { - let st = s.active()?; - let t = match st.channel_view.target { - ChannelTarget::Alpha(i) if i < st.doc.channels.len() => json!({ "channel": i }), - ChannelTarget::Composite if st.doc.quick_mask.is_some() => json!("quickMask"), - _ => return None, - }; - Some(json!({ "target": t })) -} - -/// Clear (Delete) with an alpha channel or the Quick Mask targeted (`target` from -/// [`targeted_channel`]): fill the selected area (or the canvas) of it with the background colour, -/// as gray, as Photoshop does. Partly selected pixels blend. -pub(crate) fn clear_channel(doc: &mut Document, target: &Value, background: [f32; 4]) -> Result<()> { - let canvas = doc.bounds(); - let sel = doc.selection.clone(); - let area = sel.as_ref().map_or(canvas, |m| m.content_bounds().intersect(&canvas)); - if area.is_empty() { - return Ok(()); - } - let (surf, _) = target_surface(doc, None, target)?; - crate::fill_cmds::fill_color(surf, area, [background[0], background[1], background[2], 1.0], sel.as_ref()) -} - -/// The active document targets an alpha channel or is in Quick Mask mode, so pixel commands -/// work without a pixel layer. -pub(crate) fn edits_channel(s: &Session) -> bool { - s.active().is_some_and(|st| { - st.doc.quick_mask.is_some() && st.channel_view.target == ChannelTarget::Composite - || matches!(st.channel_view.target, ChannelTarget::Alpha(i) if i < st.doc.channels.len()) - }) -} - -// --------------------------------------------------------------------------------------------- -// Enabled predicates - -fn has_doc(s: &Session) -> std::result::Result<(), String> { - s.active().map(|_| ()).ok_or_else(|| "no document open".into()) -} -fn has_channels(s: &Session) -> std::result::Result<(), String> { - has_doc(s)?; - if s.active().is_some_and(|d| !d.doc.channels.is_empty()) { Ok(()) } else { Err("the document has no alpha channels".into()) } -} -fn has_selection(s: &Session) -> std::result::Result<(), String> { - has_doc(s)?; - if s.active().is_some_and(|d| d.doc.selection.is_some()) { Ok(()) } else { Err("no selection".into()) } -} -fn has_spot(s: &Session) -> std::result::Result<(), String> { - has_doc(s)?; - if s.active().is_some_and(|d| d.doc.channels.iter().any(|c| c.spot.is_some())) { Ok(()) } else { Err("the document has no spot channels".into()) } -} -fn can_split(s: &Session) -> std::result::Result<(), String> { - let d = s.active().ok_or("no document open")?; - if color_count(&d.doc) + d.doc.channels.len() < 2 { Err("only one channel to split".into()) } else { Ok(()) } -} -fn can_merge(s: &Session) -> std::result::Result<(), String> { - has_doc(s)?; - if mergeable(s).len() >= 2 { Ok(()) } else { Err("Merge Channels needs at least two open grayscale documents of the same size".into()) } -} - -// --------------------------------------------------------------------------------------------- -// Save / Load Selection - -fn operation<'a>(p: &'a Value, key: &str) -> &'a str { - p.get(key).and_then(Value::as_str).unwrap_or("new") -} - -fn save_selection(s: &mut Session, p: &Value) -> Result { - let cmd = "select.saveSelection"; - let op = p.get("operation").and_then(Value::as_str).unwrap_or("new").to_string(); - if !matches!(op.as_str(), "new" | "replace" | "add" | "subtract" | "intersect") { - return Err(bad(cmd, format!("unknown operation `{op}`"))); - } - let di = doc_index(s, p, "document")?; - let src = s.active().ok_or(EngineError::NoDocument)?; - let area = src.doc.bounds(); - let selection = sel::mask_from_surface(src.doc.selection.as_ref(), area); - if s.documents()[di].doc.size != src.doc.size { - return Err(bad(cmd, "the destination document must have the same size")); - } - let channel = p.get("channel").cloned().unwrap_or(Value::Null); - let name = p.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()).map(str::to_string); - let prev = s.active_index(); - s.set_active(di); - let r = s.edit("Save Selection", |doc, _| { - let fmt = channel_format(doc); - let existing = match &channel { - Value::Null => None, - Value::String(x) if x == "new" => None, - v => match parse_ref(v, doc) { - Some(ChanRef::Alpha(i)) if i < doc.channels.len() => Some(i), - _ => return Err(bad(cmd, "`channel` must be \"new\" or an existing alpha channel")), - }, - }; - match (existing, op.as_str()) { - (None, _) | (_, "new") => { - let name = name.clone().unwrap_or_else(|| next_alpha_name(doc, "Alpha")); - doc.channels.push(AlphaChannel::new(name, plane_surface(&selection, area, fmt))); - Ok(doc.channels.len() - 1) - } - (Some(i), op) => { - let old = read_plane(&doc.channels[i].surface, area); - let vals: Vec = match op { - "add" => old.iter().zip(&selection).map(|(a, b)| a.max(*b)).collect(), - "subtract" => old.iter().zip(&selection).map(|(a, b)| (a - b).max(0.0)).collect(), - "intersect" => old.iter().zip(&selection).map(|(a, b)| a.min(*b)).collect(), - _ => selection.clone(), - }; - doc.channels[i].surface = plane_surface(&vals, area, fmt); - if let Some(n) = &name { - doc.channels[i].name = n.clone(); - } - Ok(i) - } - } - }); - if let Some(i) = prev { - s.set_active(i); - } - let i = r?; - let name = s.documents()[di].doc.channels[i].name.clone(); - Ok(json!({ "channel": i, "name": name, "document": di })) -} - -fn load_selection(s: &mut Session, p: &Value) -> Result { - let cmd = "select.loadSelection"; - let mode = match operation(p, "operation") { - "new" | "replace" => SelectionMode::Replace, - "add" => SelectionMode::Add, - "subtract" => SelectionMode::Subtract, - "intersect" => SelectionMode::Intersect, - other => return Err(bad(cmd, format!("unknown operation `{other}`"))), - }; - if p.get("channel").is_none() { - return Err(bad(cmd, "missing `channel`")); - } - // `"targeted"`: the Channels panel's target, as a Photoshop action's "load the target - // channel" step records it. - let mut targeted = p.clone(); - if p.get("channel").and_then(Value::as_str) == Some("targeted") { - let st = s.active().ok_or(EngineError::NoDocument)?; - targeted["channel"] = match st.channel_view.target { - ChannelTarget::Composite => json!("composite"), - ChannelTarget::Color(k) => json!({ "color": k }), - ChannelTarget::Alpha(i) => json!(i), - ChannelTarget::LayerMask => json!("mask"), - ChannelTarget::VectorMask => json!("vectorMask"), - }; - } - let p = &targeted; - // Composite and colour channels load their luminosity / values, as ⌘-clicking them does. - let plane = source(s, p, cmd, true)?.into_iter().next().ok_or_else(|| bad(cmd, "the channel has no pixels"))?; - let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; - let label = match p.get("channel").and_then(|v| parse_ref(v, doc)) { - Some(ChanRef::Transparency) => "Load Transparency", - Some(ChanRef::LayerMask) => "Load Layer Mask", - _ => "Load Selection", - }; - let selected = s.edit(label, |doc, _| { - doc.selection = sel::combine(doc.selection.as_ref(), &plane, doc.bounds(), mode); - Ok(doc.selection.is_some()) - })?; - Ok(json!({ "selected": selected })) -} - -// --------------------------------------------------------------------------------------------- -// Quick Mask - -/// Quick Mask channel for the current selection: white where selected. No selection is an empty -/// mask that shows no colour: white (nothing masked, as in Photoshop) when the colour indicates -/// masked areas, black (nothing selected) when it indicates selected areas. White and "no -/// selection" are told apart by [`Document::quick_mask_unselected`]. -fn quick_mask_from(doc: &Document, o: &QuickMaskOptions) -> AlphaChannel { - let area = doc.bounds(); - let fmt = channel_format(doc); - let surface = match &doc.selection { - Some(s) => plane_surface(&sel::mask_from_surface(Some(s), area), area, fmt), - None => unselected_surface(area, fmt, o.indicates), - }; - AlphaChannel { color: o.color, opacity: o.opacity, indicates: o.indicates, ..AlphaChannel::new("Quick Mask", surface) } -} - -/// The colourless, nothing-selected Quick Mask for `indicates`. -fn unselected_surface(area: Rect, fmt: PixelFormat, indicates: ColorIndicates) -> Surface { - let mut s = Surface::new(fmt); - if indicates != ColorIndicates::SelectedAreas { - s.fill_rect(area, &[1.0]); - } - s -} - -/// Every pixel of `vals` reads as `target` on the 8-bit grid. -fn uniform(vals: &[f32], target: f32) -> bool { - vals.iter().all(|v| (v - target).abs() <= 0.5 / 255.0) -} - -/// The selection a Quick Mask channel turns back into. All white is Select All, unless Quick -/// Mask was entered with no selection and the white is its untouched masked-areas start. -fn selection_from(doc: &Document, ch: &AlphaChannel) -> Option { - let area = doc.bounds(); - let vals = read_plane(&ch.surface, area); - if doc.quick_mask_unselected && ch.indicates != ColorIndicates::SelectedAreas && uniform(&vals, 1.0) { - return None; - } - sel::combine(None, &vals, area, SelectionMode::Replace) -} - -fn quick_mask(s: &mut Session, p: &Value) -> Result { - let on = s.active().ok_or(EngineError::NoDocument)?.doc.quick_mask.is_some(); - let want = p.get("on").and_then(Value::as_bool).unwrap_or(!on); - if want == on { - return Ok(json!({ "quickMask": on })); - } - let opts = s.quick_mask_options; - if want { - s.edit("Edit in Quick Mask", |doc, _| { - doc.quick_mask = Some(quick_mask_from(doc, &opts)); - doc.quick_mask_unselected = doc.selection.is_none(); - doc.selection = None; - Ok(()) - })?; - if let Some(st) = s.active_mut() { - st.channel_view.target = ChannelTarget::Composite; - st.channel_view.quick_mask_hidden = false; - } - } else { - s.edit("Exit Quick Mask", |doc, _| { - if let Some(q) = doc.quick_mask.take() { - doc.selection = selection_from(doc, &q); - } - Ok(()) - })?; - } - Ok(json!({ "quickMask": want })) -} - -// --------------------------------------------------------------------------------------------- -// Channel management - -fn indicates_param(v: Option<&Value>) -> Option { - match v?.as_str()? { - "masked" | "maskedAreas" => Some(ColorIndicates::MaskedAreas), - "selected" | "selectedAreas" => Some(ColorIndicates::SelectedAreas), - _ => None, - } -} - -fn color_value(cmd: &str, p: &Value, key: &str) -> Result> { - if p.get(key).is_none() { - return Ok(None); - } - let c = crate::commands::color_param(cmd, p, key, [1.0, 0.0, 0.0, 1.0])?; - Ok(Some(Color::rgb(c[0], c[1], c[2]))) -} - -fn new_channel(s: &mut Session, p: &Value) -> Result { - let fill = p.get("fill").and_then(Value::as_str).unwrap_or("black").to_string(); - let name = p.get("name").and_then(Value::as_str).map(str::to_string); - let indicates = indicates_param(p.get("indicates")); - let color = color_value("channel.new", p, "color")?; - let opacity = p.get("opacity").and_then(Value::as_f64).map(|v| (v as f32 / 100.0).clamp(0.0, 1.0)); - let i = s.edit("New Channel", |doc, _| { - let area = doc.bounds(); - let fmt = channel_format(doc); - let surface = match fill.as_str() { - "white" => plane_surface(&vec![1.0; area.width() as usize * area.height() as usize], area, fmt), - "selection" => plane_surface(&sel::mask_from_surface(doc.selection.as_ref(), area), area, fmt), - _ => Surface::new(fmt), - }; - let mut ch = AlphaChannel::new(name.clone().unwrap_or_else(|| next_alpha_name(doc, "Alpha")), surface); - if let Some(v) = indicates { - ch.indicates = v; - } - if let Some(c) = color { - ch.color = c; - } - if let Some(o) = opacity { - ch.opacity = o; - } - doc.channels.push(ch); - Ok(doc.channels.len() - 1) - })?; - // Photoshop targets and shows a new channel on its own. - target(s, ChannelTarget::Alpha(i)); - Ok(json!({ "channel": i })) -} - -fn new_spot(s: &mut Session, p: &Value) -> Result { - let color = color_value("channel.newSpot", p, "color")?.unwrap_or(Color::rgb(1.0, 0.0, 0.0)); - let solidity = p.get("solidity").and_then(Value::as_f64).unwrap_or(0.0).clamp(0.0, 100.0) as f32 / 100.0; - let name = p.get("name").and_then(Value::as_str).map(str::to_string); - let from_sel = p.get("fromSelection").and_then(Value::as_bool).unwrap_or(true); - let i = s.edit("New Spot Channel", |doc, _| { - let area = doc.bounds(); - let fmt = channel_format(doc); - let surface = if from_sel && doc.selection.is_some() { - plane_surface(&sel::mask_from_surface(doc.selection.as_ref(), area), area, fmt) - } else { - Surface::new(fmt) - }; - let name = name.clone().unwrap_or_else(|| next_alpha_name(doc, "Spot Color")); - doc.channels.push(AlphaChannel { spot: Some((color, solidity)), ..AlphaChannel::new(name, surface) }); - Ok(doc.channels.len() - 1) - })?; - if let Some(st) = s.active_mut() { - st.channel_view.set_alpha_visible(i, true); - touch(st); - } - Ok(json!({ "channel": i })) -} - -fn duplicate_channel(s: &mut Session, p: &Value) -> Result { - let cmd = "channel.duplicate"; - let src = s.active().ok_or(EngineError::NoDocument)?; - let area = src.doc.bounds(); - let r = p.get("channel").and_then(|v| parse_ref(v, &src.doc)).ok_or_else(|| bad(cmd, "missing or unknown `channel`"))?; - let mut ch = match r { - ChanRef::Alpha(i) => src.doc.channels.get(i).cloned().ok_or_else(|| bad(cmd, format!("no alpha channel {i}")))?, - ChanRef::QuickMask => src.doc.quick_mask.clone().ok_or_else(|| bad(cmd, "not in Quick Mask mode"))?, - other => { - let plane = gray_plane(&src.doc, None, src.active_layer, other)?; - AlphaChannel::new(String::new(), plane_surface(&plane, area, channel_format(&src.doc))) - } - }; - let base = match r { - ChanRef::Alpha(_) | ChanRef::QuickMask => ch.name.clone(), - ChanRef::Color(k) => color_names(edit_mode(&src.doc))[k].to_string(), - _ => composite_name(edit_mode(&src.doc)).to_string(), - }; - ch.name = p.get("name").and_then(Value::as_str).map_or_else(|| format!("{base} copy"), str::to_string); - if p.get("invert").and_then(Value::as_bool).unwrap_or(false) { - let v: Vec = read_plane(&ch.surface, area).into_iter().map(|v| 1.0 - v).collect(); - ch.surface = plane_surface(&v, area, ch.surface.format()); - } - match p.get("document") { - Some(Value::String(x)) if x == "new" => { - // Photoshop makes a multichannel document; ours is grayscale with the channel as pixels. - let doc = gray_document(&ch.name, &src.doc, &read_plane(&ch.surface, area)); - let i = s.add_document(doc, None); - Ok(json!({ "document": i })) - } - _ => { - let di = doc_index(s, p, "document")?; - if s.documents()[di].doc.size != src.doc.size { - return Err(bad(cmd, "the destination document must have the same size")); - } - let prev = s.active_index(); - s.set_active(di); - let r = s.edit("Duplicate Channel", |doc, _| { - let fmt = channel_format(doc); - if ch.surface.format() != fmt { - ch.surface = ch.surface.convert(fmt); - } - doc.channels.push(ch); - Ok(doc.channels.len() - 1) - }); - if let Some(i) = prev { - s.set_active(i); - } - Ok(json!({ "channel": r?, "document": di })) - } - } -} - -/// A one-layer grayscale document whose pixels are `plane` (Split Channels, Duplicate Channel -/// to a new document). -fn gray_document(name: &str, like: &Document, plane: &[f32]) -> Document { - let mut d = Document::new(name, like.size, ColorMode::Grayscale, like.depth); - d.resolution_dpi = like.resolution_dpi; - let fmt = d.pixel_format(); - let mut bg = Layer::raster("Background", fmt); - bg.locks.transparency = true; - bg.locks.position = true; - if let Some(s) = bg.surface_mut() { - let data: Vec = plane.iter().flat_map(|v| [v.clamp(0.0, 1.0), 1.0]).collect(); - s.write_region(like.bounds(), &data); - s.prune(); - } - d.layers.push(bg); - d -} - -fn delete_channel(s: &mut Session, p: &Value) -> Result { - let cmd = "channel.delete"; - let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; - let i = match p.get("channel") { - Some(_) => alpha_index(doc, p, "channel", cmd)?, - None => match s.active().ok_or(EngineError::NoDocument)?.channel_view.target { - ChannelTarget::Alpha(i) => i, - _ => return Err(bad(cmd, "missing `channel`")), - }, - }; - // `edit` validates the view against the shorter channel list before we can remap it. - // Keep the original indices and eyes so a surviving final channel is not discarded. - let view = s.active().ok_or(EngineError::NoDocument)?.channel_view.clone(); - s.edit("Delete Channel", |doc, _| { - doc.channels.remove(i); - Ok(()) - })?; - if let Some(st) = s.active_mut() { - st.channel_view = view; - let v = &mut st.channel_view; - if i < v.alpha_visible.len() { - v.alpha_visible.remove(i); - } - v.target = match v.target { - ChannelTarget::Alpha(t) if t == i => { - v.color_hidden.clear(); - ChannelTarget::Composite - } - ChannelTarget::Alpha(t) if t > i => ChannelTarget::Alpha(t - 1), - t => t, - }; - fix_view_now(st); - } - Ok(Value::Null) -} - -fn fix_view_now(st: &mut DocState) { - fix_view(st); - touch(st); -} - -fn rename_channel(s: &mut Session, p: &Value) -> Result { - let cmd = "channel.rename"; - let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; - let i = alpha_index(doc, p, "channel", cmd)?; - let name = p.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad(cmd, "missing `name`"))?.to_string(); - s.edit("Rename Channel", |doc, _| { - doc.channels[i].name = name; - Ok(()) - })?; - Ok(Value::Null) -} - -fn move_channel(s: &mut Session, p: &Value) -> Result { - let cmd = "channel.move"; - let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; - let n = doc.channels.len(); - let i = alpha_index(doc, p, "channel", cmd)?; - let to = p.get("to").and_then(Value::as_u64).map(|v| (v as usize).min(n - 1)).ok_or_else(|| bad(cmd, "missing `to`"))?; - if to == i { - return Ok(json!({ "channel": i })); - } - s.edit("Channel Order", |doc, _| { - let c = doc.channels.remove(i); - doc.channels.insert(to, c); - Ok(()) - })?; - if let Some(st) = s.active_mut() { - let v = &mut st.channel_view; - v.alpha_visible.resize(n, false); - let vis = v.alpha_visible.remove(i); - v.alpha_visible.insert(to, vis); - let remap = |t: usize| { - if t == i { - to - } else if i < t && t <= to { - t - 1 - } else if to <= t && t < i { - t + 1 - } else { - t - } - }; - if let ChannelTarget::Alpha(t) = v.target { - v.target = ChannelTarget::Alpha(remap(t)); - } - touch(st); - } - Ok(json!({ "channel": to })) -} - -/// Make `t` the edit target and show it the way Photoshop does when its row is clicked. -fn target(s: &mut Session, t: ChannelTarget) { - if let Some(st) = s.active_mut() { - let colors = color_count(&st.doc); - let n = st.doc.channels.len(); - let v = &mut st.channel_view; - v.target = t; - match t { - // Like clicking RGB in Photoshop: the alpha overlays go away with their eyes. - ChannelTarget::Composite => { - v.color_hidden.clear(); - v.alpha_visible.clear(); - } - ChannelTarget::LayerMask | ChannelTarget::VectorMask => v.color_hidden.clear(), - ChannelTarget::Color(k) => { - v.color_hidden = (0..colors).map(|c| c != k).collect(); - v.alpha_visible.clear(); - } - ChannelTarget::Alpha(i) => { - v.color_hidden = vec![true; colors]; - v.alpha_visible = (0..n).map(|c| c == i).collect(); - } - } - fix_view_now(st); - } - s.tools.target_mask(t == ChannelTarget::LayerMask); -} - -fn parse_target(s: &Session, p: &Value, cmd: &str) -> Result { - let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; - match p.get("channel").map_or(Some(ChanRef::Composite), |v| parse_ref(v, doc)) { - Some(ChanRef::Composite) => Ok(ChannelTarget::Composite), - Some(ChanRef::Color(k)) if k < color_count(doc) && color_count(doc) > 1 => Ok(ChannelTarget::Color(k)), - Some(ChanRef::Alpha(i)) if i < doc.channels.len() => Ok(ChannelTarget::Alpha(i)), - Some(ChanRef::LayerMask) => { - let active = crate::active_layer_of(s).map_err(|e| bad(cmd, e))?; - if active.mask.is_none() { - return Err(bad(cmd, "the active layer has no layer mask")); - } - Ok(ChannelTarget::LayerMask) - } - Some(ChanRef::VectorMask) => { - let active = crate::active_layer_of(s).map_err(|e| bad(cmd, e))?; - if active.vector_mask.is_none() { - return Err(bad(cmd, "the active layer has no vector mask")); - } - Ok(ChannelTarget::VectorMask) - } - _ => Err(bad(cmd, "`channel` must be \"composite\", \"mask\", \"vectorMask\", a colour channel name or an alpha channel")), - } -} - -fn target_cmd(s: &mut Session, p: &Value) -> Result { - let t = parse_target(s, p, "channel.target")?; - target(s, t); - Ok(list(s)) -} - -/// The channel shortcuts' modifier as the platform writes it, for error messages (`⌘4`, `Ctrl+4`). -const SLOT_KEY: &str = if cfg!(target_os = "macos") { "⌘" } else { "Ctrl+" }; - -/// ⌘2 composite, ⌘3… colour channels then alpha channels (Photoshop CC defaults). -fn target_slot(s: &mut Session, slot: usize) -> Result { - let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; - let colors = color_count(doc); - let shown_colors = if colors > 1 { colors } else { 0 }; - let t = match slot { - 2 => ChannelTarget::Composite, - n if n - 3 < shown_colors => ChannelTarget::Color(n - 3), - n if n - 3 - shown_colors < doc.channels.len() => ChannelTarget::Alpha(n - 3 - shown_colors), - _ => return Err(EngineError::Other(format!("no channel for {SLOT_KEY}{slot}"))), - }; - target(s, t); - Ok(list(s)) -} - -fn set_visible(s: &mut Session, p: &Value) -> Result { - let cmd = "channel.setVisible"; - let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; - let r = p.get("channel").and_then(|v| parse_ref(v, doc)).ok_or_else(|| bad(cmd, "missing or unknown `channel`"))?; - let colors = color_count(doc); - let n = doc.channels.len(); - let st = s.active_mut().ok_or(EngineError::NoDocument)?; - let v = &mut st.channel_view; - let visible = |cur: bool| p.get("visible").and_then(Value::as_bool).unwrap_or(!cur); - match r { - ChanRef::Composite => { - let all = v.visible_colors(colors) == colors; - let on = visible(all); - v.color_hidden = vec![!on; colors]; - } - ChanRef::Color(k) if k < colors => { - let on = visible(v.color_visible(k)); - v.set_color_visible(k, on); - } - ChanRef::Alpha(i) if i < n => { - let on = visible(v.alpha_shown(i)); - v.set_alpha_visible(i, on); - } - ChanRef::QuickMask => v.quick_mask_hidden = !visible(!v.quick_mask_hidden), - _ => return Err(bad(cmd, "that channel has no visibility")), - } - fix_view_now(st); - Ok(list(s)) -} - -fn options(s: &mut Session, p: &Value) -> Result { - let cmd = "channel.options"; - let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; - let r = p.get("channel").and_then(|v| parse_ref(v, doc)).ok_or_else(|| bad(cmd, "missing or unknown `channel`"))?; - let name = p.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()).map(str::to_string); - let color = color_value(cmd, p, "color")?; - let opacity = p.get("opacity").and_then(Value::as_f64).map(|v| (v as f32 / 100.0).clamp(0.0, 1.0)); - let solidity = p.get("solidity").and_then(Value::as_f64).map(|v| (v as f32 / 100.0).clamp(0.0, 1.0)); - let kind = p.get("indicates").and_then(Value::as_str).map(str::to_string); - let display_only = name.is_none() && kind.is_none() && solidity.is_none(); - let apply = move |ch: &mut AlphaChannel| -> Result<()> { - if let Some(n) = &name { - ch.name = n.clone(); - } - match kind.as_deref() { - Some("spot") => { - let (c, sol) = ch.spot.unwrap_or((ch.color, 0.0)); - ch.spot = Some((color.unwrap_or(c), solidity.unwrap_or(sol))); - return Ok(()); - } - Some(k) => { - ch.indicates = indicates_param(Some(&json!(k))).ok_or_else(|| bad(cmd, format!("unknown `indicates` {k}")))?; - ch.spot = None; - } - None => {} - } - match &mut ch.spot { - Some((c, sol)) => { - *c = color.unwrap_or(*c); - *sol = solidity.or(opacity).unwrap_or(*sol); - } - None => { - ch.color = color.unwrap_or(ch.color); - ch.opacity = opacity.unwrap_or(ch.opacity); - } - } - Ok(()) - }; - match r { - ChanRef::Alpha(i) if i < doc.channels.len() => { - s.edit("Channel Options", |doc, _| apply(&mut doc.channels[i]))?; - } - ChanRef::QuickMask => { - // Quick Mask Options persist for the session; the live Quick Mask follows them. - let mut probe = AlphaChannel { - color: s.quick_mask_options.color, - opacity: s.quick_mask_options.opacity, - indicates: s.quick_mask_options.indicates, - ..AlphaChannel::new("Quick Mask", Surface::new(PixelFormat::GRAY8)) - }; - apply(&mut probe)?; - if probe.spot.is_some() { - return Err(bad(cmd, "Quick Mask can't be a spot channel")); - } - s.quick_mask_options = QuickMaskOptions { color: probe.color, opacity: probe.opacity, indicates: probe.indicates }; - if s.active().is_some_and(|d| d.doc.quick_mask.is_some()) { - let o = s.quick_mask_options; - s.edit("Quick Mask Options", |doc, _| { - let area = doc.bounds(); - let fmt = channel_format(doc); - let unselected = doc.quick_mask_unselected; - if let Some(q) = &mut doc.quick_mask { - // An untouched no-selection mask stays colourless (nothing selected) - // when the colour switches between masked and selected areas. - if unselected && q.indicates != o.indicates { - let empty = if q.indicates == ColorIndicates::SelectedAreas { 0.0 } else { 1.0 }; - if uniform(&read_plane(&q.surface, area), empty) { - q.surface = unselected_surface(area, fmt, o.indicates); - } - } - q.color = o.color; - q.opacity = o.opacity; - q.indicates = o.indicates; - } - Ok(()) - })?; - } - } - ChanRef::LayerMask => { - // Layer Mask Display Options: only the rubylith's colour and opacity, for every mask. - if !display_only { - return Err(bad(cmd, "a layer mask's options are only `color` and `opacity`")); - } - // A preference, kept across restarts; not an undo step. - if color.is_some() || opacity.is_some() { - s.edit_prefs(|prefs| { - let o = &mut prefs.layer_mask_overlay; - if let Some(c) = color { - o.color = crate::adjust_params::hex(c.to_rgb()); - } - if let Some(a) = opacity { - o.opacity = (a * 100.0).round(); - } - }); - } - let o = serde_json::to_value(&s.prefs().layer_mask_overlay).unwrap_or(Value::Null); - let mut out = list(s); - if let Some(m) = out.as_object_mut() { - m.insert("layerMaskOverlay".into(), o); - } - return Ok(out); - } - _ => return Err(bad(cmd, "`channel` must be an alpha/spot channel, \"quickMask\" or \"mask\"")), - } - Ok(list(s)) -} - -/// Merge Spot Channel: flattens the image and prints the spot ink into the colour channels. -fn merge_spot(s: &mut Session, p: &Value) -> Result { - let cmd = "channel.mergeSpot"; - let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; - let i = match p.get("channel") { - Some(_) => alpha_index(doc, p, "channel", cmd)?, - None => match s.active().ok_or(EngineError::NoDocument)?.channel_view.target { - ChannelTarget::Alpha(i) => i, - _ => doc.channels.iter().position(|c| c.spot.is_some()).ok_or_else(|| bad(cmd, "no spot channel"))?, - }, - }; - let (ink, solidity) = doc.channels[i].spot.ok_or_else(|| bad(cmd, "not a spot channel"))?; - s.edit("Merge Spot Channel", |doc, active| { - let area = doc.bounds(); - let fmt = doc.pixel_format(); - let comp = photocraft_compose::render(doc, area); - let k = read_plane(&doc.channels[i].surface, area); - let ink = ink.to_rgb(); - // Ink over the image: opaque at 100% solidity, multiplied (transparent ink) at 0%. - let data: Vec = comp - .px - .iter() - .zip(&k) - .flat_map(|(c, &v)| { - let rgb: [f32; 3] = std::array::from_fn(|j| { - let over = solidity * ink[j] + (1.0 - solidity) * c[j] * ink[j]; - c[j] + (over - c[j]) * v.clamp(0.0, 1.0) - }); - from_rgba(&fmt, [rgb[0], rgb[1], rgb[2], 1.0]) - }) - .collect(); - let mut bg = Layer::raster("Background", fmt); - bg.locks.transparency = true; - bg.locks.position = true; - if let Some(sf) = bg.surface_mut() { - sf.write_region(area, &data); - sf.prune(); - } - let id = bg.id; - doc.layers = vec![bg]; - doc.channels.remove(i); - *active = Some(id); - Ok(()) - })?; - if let Some(st) = s.active_mut() { - st.channel_view = ChannelView::default(); - fix_view_now(st); - } - Ok(Value::Null) -} - -/// Split Channels: one grayscale document per colour and alpha channel; closes the original. -fn split(s: &mut Session, p: &Value) -> Result { - let idx = s.active_index().ok_or(EngineError::NoDocument)?; - let doc = s.documents()[idx].doc.clone(); - let area = doc.bounds(); - let (px, n) = native_pixels(&doc, None)?; - let mode = edit_mode(&doc); - let names = color_names(mode); - let short = |name: &str| name.chars().next().map(|c| c.to_ascii_uppercase().to_string()).unwrap_or_default(); - let mut docs: Vec = Vec::new(); - for (c, name) in names.iter().enumerate() { - let plane: Vec = px.chunks_exact(n).map(|p| p[c]).collect(); - docs.push(gray_document(&format!("{}_{}", doc.name, short(name)), &doc, &plane)); - } - for ch in &doc.channels { - docs.push(gray_document(&format!("{}_{}", doc.name, ch.name), &doc, &read_plane(&ch.surface, area))); - } - if p.get("closeOriginal").and_then(Value::as_bool).unwrap_or(true) { - s.close(idx); - } - let made: Vec = docs.into_iter().map(|d| s.add_document(d, None)).collect(); - Ok(json!({ "documents": made })) -} - -/// Open grayscale documents with the active document's size, active first. -fn mergeable(s: &Session) -> Vec { - let Some(a) = s.active() else { return Vec::new() }; - let ok = |d: &DocState| d.doc.mode == ColorMode::Grayscale && d.doc.size == a.doc.size; - let mut v: Vec = s.active_index().into_iter().filter(|_| ok(a)).collect(); - v.extend(s.documents().iter().enumerate().filter(|(i, d)| Some(*i) != s.active_index() && ok(d)).map(|(i, _)| i)); - v -} - -/// Merge Channels: grayscale documents of one size become the channels of an RGB, CMYK or Lab -/// document (extra documents become alpha channels); the sources close. -fn merge(s: &mut Session, p: &Value) -> Result { - let cmd = "channel.merge"; - let mode = match p.get("mode").and_then(Value::as_str).unwrap_or("rgb") { - "rgb" => ColorMode::Rgb, - "cmyk" => ColorMode::Cmyk, - "lab" => ColorMode::Lab, - other => return Err(bad(cmd, format!("unknown mode `{other}`"))), - }; - let srcs: Vec = match p.get("documents").and_then(Value::as_array) { - Some(a) => a - .iter() - .map(|v| v.as_u64().map(|i| i as usize).filter(|i| *i < s.documents().len()).ok_or_else(|| bad(cmd, "bad document index"))) - .collect::>()?, - None => mergeable(s).into_iter().take(mode.color_channels()).collect(), - }; - if srcs.len() < mode.color_channels() { - return Err(bad(cmd, format!("{mode:?} needs {} grayscale documents, got {}", mode.color_channels(), srcs.len()))); - } - // Each source closes by its *current* index, so a repeated index would shift the later - // removals onto a document that was never named (#934). Refuse it rather than guess. - let mut seen = std::collections::HashSet::new(); - if let Some(dup) = srcs.iter().find(|i| !seen.insert(**i)) { - return Err(bad(cmd, format!("document {dup} is listed more than once"))); - } - let Some(first) = srcs.first().and_then(|&i| s.documents().get(i)).map(|d| d.doc.clone()) else { - return Err(bad(cmd, "bad document index")); - }; - let mut planes = Vec::new(); - for &i in &srcs { - let d = &s.documents()[i].doc; - if d.size != first.size || d.mode != ColorMode::Grayscale { - return Err(bad(cmd, format!("\"{}\" is not a grayscale document of the same size", d.name))); - } - planes.push(gray_plane(d, None, None, ChanRef::Composite)?); - } - let mut out = Document::new(p.get("name").and_then(Value::as_str).unwrap_or("Untitled"), first.size, mode, first.depth); - out.resolution_dpi = first.resolution_dpi; - let fmt = out.pixel_format(); - let cc = mode.color_channels(); - let npx = planes[0].len(); - let mut data = Vec::with_capacity(npx * fmt.channels()); - for i in 0..npx { - for pl in &planes[..cc] { - data.push(pl[i].clamp(0.0, 1.0)); - } - data.push(1.0); - } - let mut bg = Layer::raster("Background", fmt); - bg.locks.transparency = true; - bg.locks.position = true; - if let Some(sf) = bg.surface_mut() { - sf.write_region(out.bounds(), &data); - sf.prune(); - } - out.layers.push(bg); - let area = out.bounds(); - let cf = channel_format(&out); - for (k, pl) in planes[cc..].iter().enumerate() { - out.channels.push(AlphaChannel::new(format!("Alpha {}", k + 1), plane_surface(pl, area, cf))); - } - let mut close: Vec = srcs.clone(); - close.sort_unstable(); - for i in close.into_iter().rev() { - s.close(i); - } - let i = s.add_document(out, None); - Ok(json!({ "document": i })) -} - -// --------------------------------------------------------------------------------------------- -// Apply Image / Calculations - -fn apply_image(s: &mut Session, p: &Value) -> Result { - let cmd = "image.applyImage"; - let blending = Blending::parse(p).map_err(|e| bad(cmd, e))?; - let opacity = p.get("opacity").and_then(Value::as_f64).unwrap_or(100.0).clamp(0.0, 100.0) as f32 / 100.0; - let preserve = p.get("preserveTransparency").and_then(Value::as_bool).unwrap_or(false); - let src_spec = source_spec(p, "source", "source").unwrap_or_else(|| json!({})); - let src = source(s, &src_spec, cmd, false)?; - let mask = mask_plane(s, p, cmd)?; - let layer = s.active().and_then(|d| d.active_layer); - s.edit("Apply Image", |doc, _| { - let area = doc.bounds(); - let selection = doc.selection.as_ref().map(|m| sel::mask_from_surface(Some(m), area)); - let weight = |i: usize| opacity * mask.as_ref().map_or(1.0, |m| m[i]) * selection.as_ref().map_or(1.0, |m| m[i]); - let mask_target = target_of(p) == Target::Mask; - if is_channel_target(p) || mask_target { - // A grayscale target gets the luminosity of a colour source (one plane). - let srcp = - if src.len() == 1 { src[0].clone() } else { (0..src[0].len()).map(|i| src.iter().map(|pl| pl[i]).sum::() / src.len() as f32).collect() }; - let (surf, _) = target_surface(doc, layer, p)?; - let base = read_plane(surf, area); - let out: Vec = base.iter().enumerate().map(|(i, &b)| b + (blending.apply(b, srcp[i]) - b) * weight(i)).collect(); - if mask_target { - // A layer mask keeps its default (reveal or hide) outside the canvas. - if surf.channels() != 1 { - return Err(EngineError::Other("the layer mask is not a grayscale surface".into())); - } - surf.write_region(area, &out); - surf.prune(); - } else { - *surf = plane_surface(&out, area, surf.format()); - } - return Ok(()); - } - let id = layer.ok_or_else(|| EngineError::Other("no active layer".into()))?; - let fmt = doc.pixel_format(); - let surf = crate::commands::paint_surface(doc, id, &Value::Null)?; - let sf = surf.format(); - if sf != fmt { - return Err(EngineError::Other("the target layer's format doesn't match the document".into())); - } - let n = sf.channels(); - let colors = sf.mode.color_channels(); - let mut v = surf.read_region(area); - for (i, px) in v.chunks_exact_mut(n).enumerate() { - let base_a = if sf.alpha { px[colors].clamp(0.0, 1.0) } else { 1.0 }; - let mut w = weight(i); - if preserve { - w *= base_a; - } - if w <= 0.0 { - continue; - } - // Painted over the layer like a brush: the blend only acts where the layer has - // pixels (where it is transparent the source shows as is), and the alpha grows by - // source-over, so applying to an empty layer copies the source in any mode. - let out_a = if preserve { base_a } else { w + base_a * (1.0 - w) }; - for (c, b) in px[..colors].iter_mut().enumerate() { - let top = src.get(c).unwrap_or(&src[0])[i]; - let blended = top + (blending.apply(*b, top) - top) * base_a; - *b = if preserve { *b + (blended - *b) * w } else { (w * blended + base_a * (1.0 - w) * *b) / out_a }; - } - if sf.alpha { - px[colors] = out_a; - } - } - surf.write_region(area, &v); - surf.prune(); - Ok(()) - })?; - Ok(Value::Null) -} - -fn calculations(s: &mut Session, p: &Value) -> Result { - let cmd = "image.calculations"; - let blending = Blending::parse(p).map_err(|e| bad(cmd, e))?; - let opacity = p.get("opacity").and_then(Value::as_f64).unwrap_or(100.0).clamp(0.0, 100.0) as f32 / 100.0; - let s1 = source(s, &source_spec(p, "source1", "source1").unwrap_or_else(|| json!({})), cmd, true)?.remove(0); - let s2 = source(s, &source_spec(p, "source2", "source2").unwrap_or_else(|| json!({})), cmd, true)?.remove(0); - let mask = mask_plane(s, p, cmd)?; - // Source 1 is blended onto Source 2. - let out: Vec = - s2.iter().zip(&s1).enumerate().map(|(i, (&b, &t))| b + (blending.apply(b, t) - b) * opacity * mask.as_ref().map_or(1.0, |m| m[i])).collect(); - let name = p.get("name").and_then(Value::as_str).map(str::to_string); - match p.get("result").and_then(Value::as_str).unwrap_or("newChannel") { - "newChannel" => { - let i = s.edit("Calculations", |doc, _| { - let name = name.clone().unwrap_or_else(|| next_alpha_name(doc, "Alpha")); - let area = doc.bounds(); - let fmt = channel_format(doc); - doc.channels.push(AlphaChannel::new(name, plane_surface(&out, area, fmt))); - Ok(doc.channels.len() - 1) - })?; - Ok(json!({ "channel": i })) - } - "newDocument" => { - let like = s.active().ok_or(EngineError::NoDocument)?.doc.clone(); - let d = gray_document(name.as_deref().unwrap_or("Untitled"), &like, &out); - let i = s.add_document(d, None); - Ok(json!({ "document": i })) - } - "selection" => { - let selected = s.edit("Calculations", |doc, _| { - doc.selection = sel::combine(None, &out, doc.bounds(), SelectionMode::Replace); - Ok(doc.selection.is_some()) - })?; - Ok(json!({ "selected": selected })) - } - other => Err(bad(cmd, format!("unknown result `{other}` (newChannel|newDocument|selection)"))), - } -} - -// --------------------------------------------------------------------------------------------- -// State as JSON - -/// The Channels panel rows and view state of a document (also part of `inspect`). -pub fn channels_json(st: &DocState) -> Value { - let doc = &st.doc; - let mode = edit_mode(doc); - let v = &st.channel_view; - let colors = color_count(doc); - json!({ - "composite": composite_name(mode), - "colors": color_names(mode).iter().enumerate().map(|(k, n)| json!({ "name": n, "visible": v.color_visible(k) })).collect::>(), - "alpha": doc.channels.iter().enumerate().map(|(i, c)| json!({ - "index": i, - "name": c.name, - "visible": v.alpha_shown(i), - "spot": c.spot.map(|(col, sol)| json!({ "color": col.to_rgb(), "solidity": sol })), - "color": c.color.to_rgb(), - "opacity": c.opacity, - "indicates": c.indicates, - })).collect::>(), - "quickMask": doc.quick_mask.as_ref().map(|q| json!({ "visible": !v.quick_mask_hidden, "color": q.color.to_rgb(), "opacity": q.opacity, "indicates": q.indicates })), - "target": v.target, - "compositeVisible": v.visible_colors(colors) == colors, - "layerMaskView": crate::mask_view_cmds::view_json(st), - }) -} - -fn list(s: &Session) -> Value { - s.active().map(channels_json).unwrap_or(Value::Null) -} - -// --------------------------------------------------------------------------------------------- -// Registry - -macro_rules! spec { - ($id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $en:expr, $run:expr) => { - CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run, journal: true } - }; -} - -pub fn specs() -> Vec { - vec![ - spec!( - "select.saveSelection", - "Save Selection…", - ["Select"], - None, - r##"{"name":str?,"channel":"new"|index|name="new","document":index?,"operation":"new|replace|add|subtract|intersect"="new"}"##, - has_selection, - save_selection - ), - spec!( - "select.loadSelection", - "Load Selection…", - ["Select"], - None, - r##"{"channel":index|name|"composite"|"red|green|blue|…"|"transparency"|"mask"|"vectorMask"|"quickMask"|"selection"|"targeted" (the Channels panel's target),"layer":id?,"document":index?,"invert":bool=false,"operation":"new|add|subtract|intersect"="new"}"##, - has_doc, - load_selection - ), - spec!("select.editInQuickMaskMode", "Edit in Quick Mask Mode", ["Select"], Some("Q"), r##"{"on":bool?=toggle}"##, has_doc, quick_mask), - spec!( - "image.applyImage", - "Apply Image…", - ["Image"], - None, - r##"{"source":{"document":index?,"layer":id|name|"merged"="merged","channel":"composite"|"red|…"|index|"selection"|"transparency"|"mask"="composite","invert":bool=false},"blending":"normal|multiply|screen|overlay|softLight|hardLight|colorDodge|colorBurn|darken|lighten|difference|exclusion|linearBurn|linearDodge|add|subtract|…"="multiply","opacity":0..100=100,"scale":1..2=1,"offset":-255..255=0,"preserveTransparency":bool=false,"mask":{"document","layer","channel","invert"}?,"sourceChannel|sourceDocument|sourceLayer|sourceInvert|maskChannel|…":flat form of source/mask?}"##, - has_apply_target, - apply_image - ), - spec!( - "image.calculations", - "Calculations…", - ["Image"], - None, - r##"{"source1":{"document","layer","channel","invert"},"source2":{…},"blending":"multiply|…"="multiply","opacity":0..100=100,"scale":1..2=1,"offset":-255..255=0,"mask":{…}?,"result":"newChannel|newDocument|selection"="newChannel","name":str?}"##, - has_doc, - calculations - ), - spec!( - "channel.new", - "New Channel…", - [], - None, - r##"{"name":str?,"fill":"black|white|selection"="black","color":"#rrggbb"="#ff0000","opacity":0..100=50,"indicates":"masked|selected"="masked"}"##, - has_doc, - new_channel - ), - spec!( - "channel.newSpot", - "New Spot Channel…", - [], - None, - r##"{"name":str?,"color":"#rrggbb"="#ff0000","solidity":0..100=0,"fromSelection":bool=true}"##, - has_doc, - new_spot - ), - spec!( - "channel.duplicate", - "Duplicate Channel…", - [], - None, - r##"{"channel":index|name|"red|…"|"composite"|"quickMask","name":str?,"document":index|"new"?=active,"invert":bool=false}"##, - has_doc, - duplicate_channel - ), - spec!("channel.delete", "Delete Channel", [], None, r##"{"channel":index|name?=targeted}"##, has_channels, delete_channel), - spec!("channel.rename", "Rename Channel", [], None, r##"{"channel":index|name,"name":str}"##, has_channels, rename_channel), - spec!("channel.move", "Reorder Channel", [], None, r##"{"channel":index|name,"to":index}"##, has_channels, move_channel), - spec!( - "channel.target", - "Target Channel", - [], - None, - r##"{"channel":"composite"|"mask"|"vectorMask"|"red|green|blue|…"|index|name="composite"}"##, - has_doc, - target_cmd - ), - spec!( - "channel.setVisible", - "Channel Visibility", - [], - None, - r##"{"channel":"composite"|"red|…"|index|name|"quickMask","visible":bool?=toggle}"##, - has_doc, - set_visible - ), - spec!( - "channel.options", - "Channel Options…", - [], - None, - r##"{"channel":index|name|"quickMask"|"mask","name":str?,"indicates":"masked|selected|spot"?,"color":"#rrggbb"?,"opacity":0..100?,"solidity":0..100?} ("mask": Layer Mask Display Options, the rubylith's color and opacity for every layer mask, kept in the preferences as layerMaskOverlay; not an undo step; returns them as layerMaskOverlay)"##, - has_doc, - options - ), - spec!("channel.mergeSpot", "Merge Spot Channel", [], None, r##"{"channel":index|name?=targeted or first spot}"##, has_spot, merge_spot), - spec!("channel.split", "Split Channels", [], None, r##"{"closeOriginal":bool=true}"##, can_split, split), - spec!( - "channel.merge", - "Merge Channels…", - [], - None, - r##"{"mode":"rgb|cmyk|lab"="rgb","documents":[index,…]?=open grayscale docs of the active size,"name":str?}"##, - can_merge, - merge - ), - CommandSpec { - id: "channel.list", - label: "Channels", - menu: &[], - shortcut: None, - params: "{}", - enabled: has_doc, - run: |s, _| Ok(list(s)), - journal: false, - }, - spec!("channel.target.composite", "Target Composite Channel", [], Some("Cmd+2"), "{}", has_doc, |s, _| target_slot(s, 2)), - // ⌘\ targets the active layer's mask, as clicking its thumbnail does. - spec!("channel.target.layerMask", "Target Layer Mask", [], Some("Cmd+\\"), "{}", has_layer_mask, |s, _| target_cmd( - s, - &serde_json::json!({"channel": "mask"}) - )), - // ⌘⌥2 loads the image's luminosity as a selection (⌘-click on the composite channel). - spec!("select.loadLuminosity", "Load Luminosity", [], Some("Cmd+Alt+2"), "{}", has_doc, |s, _| load_selection( - s, - &serde_json::json!({"channel": "composite"}) - )), - spec!("channel.target.slot3", "Target Channel 3", [], Some("Cmd+3"), "{}", slot_ok::<3>, |s, _| target_slot(s, 3)), - spec!("channel.target.slot4", "Target Channel 4", [], Some("Cmd+4"), "{}", slot_ok::<4>, |s, _| target_slot(s, 4)), - spec!("channel.target.slot5", "Target Channel 5", [], Some("Cmd+5"), "{}", slot_ok::<5>, |s, _| target_slot(s, 5)), - spec!("channel.target.slot6", "Target Channel 6", [], Some("Cmd+6"), "{}", slot_ok::<6>, |s, _| target_slot(s, 6)), - spec!("channel.target.slot7", "Target Channel 7", [], Some("Cmd+7"), "{}", slot_ok::<7>, |s, _| target_slot(s, 7)), - spec!("channel.target.slot8", "Target Channel 8", [], Some("Cmd+8"), "{}", slot_ok::<8>, |s, _| target_slot(s, 8)), - spec!("channel.target.slot9", "Target Channel 9", [], Some("Cmd+9"), "{}", slot_ok::<9>, |s, _| target_slot(s, 9)), - ] -} - -/// Target Layer Mask: the active layer has a mask. -fn has_layer_mask(s: &Session) -> std::result::Result<(), String> { - let st = s.active().ok_or("no document open")?; - let layer = st.active_layer.and_then(|id| st.doc.layer(id)).ok_or("no active layer")?; - layer.mask.as_ref().map(|_| ()).ok_or_else(|| "the active layer has no layer mask".to_string()) -} - -fn slot_ok(s: &Session) -> std::result::Result<(), String> { - let d = s.active().ok_or("no document open")?; - let colors = color_count(&d.doc); - let shown = if colors > 1 { colors } else { 0 }; - if N - 3 < shown + d.doc.channels.len() { Ok(()) } else { Err(format!("no channel for {SLOT_KEY}{N}")) } -} - -fn has_apply_target(s: &Session) -> std::result::Result<(), String> { - if edits_channel(s) { - return Ok(()); - } - let d = s.active().ok_or("no document open")?; - let l = d.active_layer.and_then(|id| d.doc.layer(id)).ok_or("no active layer")?; - if matches!(l.content, LayerContent::Raster(_)) { - Ok(()) - } else { - Err(format!("Apply Image needs a pixel layer (active layer is {} {} layer)", l.content.article(), l.content.kind_name())) - } -} diff --git a/crates/engine/src/commands.rs b/crates/engine/src/cmd.rs similarity index 70% rename from crates/engine/src/commands.rs rename to crates/engine/src/cmd.rs index 8c1c6937d7..38ede534b1 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/cmd.rs @@ -27,98 +27,6 @@ pub struct CommandSpec { pub journal: bool, } -pub(crate) fn always(_: &Session) -> std::result::Result<(), String> { - Ok(()) -} -fn has_doc(s: &Session) -> std::result::Result<(), String> { - s.active().map(|_| ()).ok_or_else(|| "no document open".into()) -} -fn has_layer(s: &Session) -> std::result::Result<(), String> { - let d = s.active().ok_or("no document open")?; - d.active_layer.filter(|id| d.doc.layer(*id).is_some()).map(|_| ()).ok_or_else(|| "no active layer".into()) -} -fn has_pixel_layer(s: &Session) -> std::result::Result<(), String> { - let l = crate::active_layer_of(s)?; - if matches!(l.content, LayerContent::Raster(_)) { - Ok(()) - } else { - Err(format!("active layer is {} {} layer, not a pixel layer", l.content.article(), l.content.kind_name())) - } -} -/// A pixel layer, or a targeted alpha channel / Quick Mask (adjustments and fills apply to it). -fn has_pixel_or_channel(s: &Session) -> std::result::Result<(), String> { - if crate::channel_cmds::edits_channel(s) { - return Ok(()); - } - has_pixel_layer(s) -} -/// A layer that can be painted: pixels, or any layer with a mask (paint with `"target":"mask"`). -pub(crate) fn has_paintable(s: &Session) -> std::result::Result<(), String> { - if crate::channel_cmds::edits_channel(s) { - return Ok(()); - } - let l = crate::active_layer_of(s)?; - if matches!(l.content, LayerContent::Raster(_)) || l.mask.is_some() { - Ok(()) - } else { - Err(format!("active layer is {} {} layer without a mask", l.content.article(), l.content.kind_name())) - } -} - -/// Surface a paint command writes to: the layer's pixels, its mask with `"target":"mask"`, or a -/// smart object's filter mask with `"target":"filterMask"`. -pub(crate) fn paint_surface<'a>(doc: &'a mut Document, id: LayerId, p: &Value) -> Result<&'a mut photocraft_raster::Surface> { - if is_mask_target(p) { - check_all_unlocked(doc, id)?; - } else { - check_pixels_unlocked(doc, id)?; - } - if crate::channel_cmds::target_of(p) == crate::channel_cmds::Target::FilterMask { - return crate::smart_cmds::filter_mask_surface(doc, id); - } - let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; - if is_mask_target(p) { - l.mask.as_mut().map(|m| &mut m.surface).ok_or_else(|| EngineError::Other("layer has no mask".into())) - } else { - l.surface_mut().ok_or_else(|| EngineError::Other("not a pixel layer".into())) - } -} - -pub(crate) fn check_all_unlocked(doc: &Document, id: LayerId) -> Result<()> { - let locks = doc.effective_locks(id); - let l = doc.layer(id).ok_or(EngineError::NoLayer(id))?; - if locks.all { - return Err(EngineError::Other(format!("Could not complete your request because the layer \"{}\" is locked", l.name))); - } - Ok(()) -} - -/// Refuse a layer whose pixels are locked (directly or through a group), with Photoshop's message. -pub(crate) fn check_pixels_unlocked(doc: &Document, id: LayerId) -> Result<()> { - let locks = doc.effective_locks(id); - let l = doc.layer(id).ok_or(EngineError::NoLayer(id))?; - if locks.pixels || locks.all { - return Err(EngineError::Other(format!("Could not complete your request because the layer \"{}\" is locked", l.name))); - } - Ok(()) -} - -/// The params target a grayscale mask of the layer: its layer mask (`"mask"`) or, on a smart -/// object, its filter mask (`"filterMask"`). -pub(crate) fn is_mask_target(p: &Value) -> bool { - matches!(p.get("target").and_then(Value::as_str), Some("mask" | "filterMask")) -} - -fn can_undo(s: &Session) -> std::result::Result<(), String> { - s.active().filter(|d| d.history.can_undo()).map(|_| ()).ok_or_else(|| "nothing to undo".into()) -} -fn can_redo(s: &Session) -> std::result::Result<(), String> { - s.active().filter(|d| d.history.can_redo()).map(|_| ()).ok_or_else(|| "nothing to redo".into()) -} -fn has_selection(s: &Session) -> std::result::Result<(), String> { - s.active().filter(|d| d.doc.selection.is_some()).map(|_| ()).ok_or_else(|| "no selection".into()) -} - /// Image › Image Rotation by a right angle or a flip (pixels, vectors, guides, … all move). fn turn(s: &mut Session, label: &str, t: crate::canvas_geom::Turn) -> Result { if let Some(d) = s.active() { @@ -141,6 +49,125 @@ macro_rules! cmd { }; } +pub mod actions_cmds; +pub mod actions_edit_cmds; +pub mod adjust_cmds; +mod adjust_params; +pub mod align_cmds; +pub mod analysis_cmds; +pub mod artboard_cmds; +pub mod atn_cmds; +pub mod automate_cmds; +pub mod background_cmds; +pub mod brush_cmds; +pub mod brush_key_cmds; +pub mod brush_preset_cmds; +pub mod channel_cmds; +pub mod color_cmds; +pub mod color_to_alpha_cmds; +pub mod comps_cmds; +pub mod contour_lib_cmds; +pub mod cutout_cmds; +pub mod distort_cmds; +pub mod document_preset_cmds; +pub mod edit_cmds; +pub mod edit_menu_cmds; +mod enabled; +pub mod eraser_cmds; +pub mod export_preset_cmds; +pub mod exr_cmds; +pub mod extra_cmds; +pub mod face_cmds; +pub mod file_cmds; +pub mod fill_cmds; +pub mod fill_key_cmds; +pub mod float_cmds; +pub(super) mod frame_cmds; +pub mod fx_view_cmds; +pub mod fx_visibility_cmds; +pub mod gallery_cmds; +pub mod gradient_fill_cmds; +pub mod group_view_cmds; +pub mod history_cmds; +pub mod history_menu_cmds; +pub mod history_select_cmds; +pub mod history_source_cmds; +pub mod image_cmds; +pub mod layer_copy_cmds; +pub mod layer_label_cmds; +pub mod layer_list_cmds; +pub mod layer_mask_props_cmds; +pub mod layer_menu_cmds; +pub mod layer_multi_cmds; +pub mod layer_nav_cmds; +mod layer_params; +pub mod layer_xmp_cmds; +pub mod lens_cmds; +pub mod magnetic_cmds; +pub mod mask_view_cmds; +pub(super) mod migrate_cmds; +pub mod mode_cmds; +pub mod multichannel_cmds; +pub mod notes_cmds; +mod ops; +pub mod paint_cmds; +mod params; +pub(super) mod path_edit_cmds; +pub mod pattern_cmds; +pub mod pattern_fill_cmds; +pub mod perspective_crop_cmds; +pub mod photo_cmds; +pub mod pick_cmds; +pub mod plugin_cmds; +pub mod preset_import_cmds; +pub mod print_cmds; +pub mod rasterize_style_cmds; +pub mod redeye_cmds; +pub mod render_cmds; +pub mod retouch_cmds; +pub mod sample_cmds; +pub mod sampler_cmds; +pub mod select_extra_cmds; +pub mod selection_cmds; +pub mod slice_cmds; +pub mod smart_cmds; +pub mod smartselect_cmds; +pub mod solid_fill_cmds; +pub mod stamp_cmds; +pub mod style_asl_cmds; +pub mod swatch_cmds; +pub mod symmetry_cmds; +pub(super) mod timeline_cmds; +pub mod transform_cmds; +pub(super) mod trap_cmds; +pub mod type_area_cmds; +pub mod type_caret_cmds; +pub mod type_cmds; +pub mod type_extra_cmds; +pub mod type_mask_cmds; +pub mod type_spell_cmds; +pub mod type_styles_cmds; +pub mod updates_cmds; +pub(super) mod variables_cmds; +pub mod vector_cmds; +pub(super) mod video_cmds; +pub mod vp_cmds; +pub mod warp_cmds; +pub mod web_cmds; +pub(super) mod wia_cmds; + +pub(crate) use adjust_params::inject_kind; +use adjust_params::{adjust_mode, destructive_adjust, doc_mode, gray_tone_params, new_adjustment}; +pub use adjust_params::{adjustment_from_params, adjustment_kind}; +pub(crate) use enabled::{always, check_all_unlocked, check_pixels_unlocked, has_paintable, is_mask_target, paint_surface}; +use enabled::{can_redo, can_undo, has_doc, has_layer, has_pixel_layer, has_pixel_or_channel, has_selection}; +pub use layer_params::blend_from_str; +pub(crate) use layer_params::{NEW_LAYER_PATH, explicit_layer, layer_listing, layer_panel_option, layer_param, mask_at_depth, mask_new_layer, selection_mask}; +use ops::{arrange, merge_group, set_mask, set_mask_and_deselect}; +pub(crate) use ops::{layer_copy, translate_layer}; +use params::{bad, set_clipped}; +pub(crate) use params::{check_f32_values, color_param, int, int_i32, parse_hex, u32_id, u32_id_param}; + pub fn command_specs() -> &'static [CommandSpec] { ®istry().specs } @@ -206,336 +233,6 @@ fn registry() -> &'static Registry { REGISTRY.get_or_init(|| Registry::new(build())) } -// ---------- param helpers ---------- - -fn bad(cmd: &str, msg: impl Into) -> EngineError { - EngineError::BadParams { cmd: cmd.into(), msg: msg.into() } -} -/// Integer parameter that also accepts JSON floats (UIs send `12.0`); rounds. -pub(crate) fn int(p: &Value, key: &str) -> Option { - p.get(key).and_then(|v| v.as_i64().or_else(|| v.as_f64().filter(|f| f.is_finite()).map(|f| f.round() as i64))) -} - -/// [`int`] narrowed to `i32` for geometry: `None` when absent, and a bad-params error when the -/// value would wrap through `as i32` — out-of-range integers truncate by multiples of 2^32, -/// which silently relocates geometry (`dx = 2^32 + 50` moves 50 px, `3e9` goes negative) -/// instead of erroring. -pub(crate) fn int_i32(cmd: &str, p: &Value, key: &str) -> Result> { - match int(p, key) { - None => Ok(None), - Some(v) => i32::try_from(v).map(Some).map_err(|_| bad(cmd, format!("`{key}` = {v} is outside the 32-bit coordinate range"))), - } -} - -/// An id (layer comp, slice, style…) from a JSON value: a bad-params error unless it is a whole -/// number in `u32` range. `as u32` would wrap `2^32 + 1` to `1` and target a real item. -pub(crate) fn u32_id(cmd: &str, key: &str, v: &Value) -> Result { - v.as_u64().and_then(|n| u32::try_from(n).ok()).ok_or_else(|| bad(cmd, format!("`{key}` = {v} is not a valid id (0..={})", u32::MAX))) -} - -/// [`u32_id`] of `p[key]`: `None` when absent. -pub(crate) fn u32_id_param(cmd: &str, p: &Value, key: &str) -> Result> { - p.get(key).map(|v| u32_id(cmd, key, v)).transpose() -} - -/// JSON numbers may be finite f64 values but overflow when stored in a document's f32 field. -pub(crate) fn finite_f32(cmd: &str, key: &str, value: f64) -> Result { - let narrowed = value as f32; - if narrowed.is_finite() { Ok(narrowed) } else { Err(bad(cmd, format!("`{key}` must fit a finite 32-bit number"))) } -} - -/// Effect/type parameters contain nested colour arrays and snapshots as well as scalars. -/// Validate before parsing or editing, including numbers hidden in an effect snapshot. -pub(crate) fn check_f32_values(cmd: &str, value: &Value) -> Result<()> { - // Bound the call stack, without allocating a work list proportional to an input array. - fn check(cmd: &str, value: &Value, depth: usize) -> Result<()> { - if depth > 64 { - return Err(bad(cmd, "parameters nested deeper than 64 levels")); - } - match value { - Value::Number(n) => { - finite_f32(cmd, "number", n.as_f64().ok_or_else(|| bad(cmd, "invalid number"))?)?; - } - Value::Array(a) => { - for v in a { - check(cmd, v, depth + 1)?; - } - } - Value::Object(o) => { - for v in o.values() { - check(cmd, v, depth + 1)?; - } - } - _ => {} - } - Ok(()) - } - check(cmd, value, 0) -} - -pub(crate) fn color_param(cmd: &str, p: &Value, key: &str, default: [f32; 4]) -> Result<[f32; 4]> { - Ok(match p.get(key) { - Some(Value::Array(a)) if a.len() >= 3 => { - let mut out = [0.0, 0.0, 0.0, 1.0]; - for (slot, value) in out.iter_mut().zip(a) { - *slot = finite_f32(cmd, key, value.as_f64().unwrap_or(0.0))?; - } - out - } - Some(Value::String(s)) => parse_hex(s).unwrap_or(default), - _ => default, - }) -} -pub(crate) fn parse_hex(s: &str) -> Option<[f32; 4]> { - let s = s.trim_start_matches('#'); - // `from_str_radix` accepts a leading '+', so "+f" would read as 0x0f. - if !s.bytes().all(|c| c.is_ascii_hexdigit()) { - return None; - } - let b = |i: usize| u8::from_str_radix(s.get(i..i + 2)?, 16).ok().map(|v| v as f32 / 255.0); - match s.len() { - 6 => Some([b(0)?, b(2)?, b(4)?, 1.0]), - 8 => Some([b(0)?, b(2)?, b(4)?, b(6)?]), - _ => None, - } -} -/// Layer › Create / Release Clipping Mask. With a `layer` param, just that layer. Otherwise, as in -/// Photoshop, the selection (#1248): Create clips every selected layer except the lowest, which -/// becomes the base; Release releases every selected layer. Releasing a clipped layer also -/// releases the clipped layers above it in its group, as Adobe documents ("removes the selected -/// layer and any layers above it from the clipping mask"), so none is left clipped to a layer -/// that is no longer clipped. One history step either way. -fn set_clipped(s: &mut Session, p: &Value, clip: bool) -> Result { - let label = if clip { "Create Clipping Mask" } else { "Release Clipping Mask" }; - let ids: Vec = if p.get("layer").is_some() { - vec![layer_param(s, p)?] - } else { - let selected = s.active().ok_or(EngineError::NoDocument)?.selected_layers(); - match (clip, selected.as_slice()) { - (_, []) => vec![layer_param(s, p)?], - (_, [one]) => vec![*one], - (true, [_base, rest @ ..]) => rest.to_vec(), - (false, all) => all.to_vec(), - } - }; - let ids = if clip { - ids - } else { - let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; - let mut all = ids.clone(); - for id in ids.iter().filter(|id| doc.layer(**id).is_some_and(|l| l.clipped)) { - for above in crate::clip_group::clipped_above(doc, *id) { - if !all.contains(&above) { - all.push(above); - } - } - } - all - }; - s.edit(label, |doc, _| { - for id in &ids { - doc.layer_mut(*id).ok_or(EngineError::NoLayer(*id))?.clipped = clip; - } - Ok(()) - })?; - Ok(json!({"layers": ids.iter().map(|id| id.0).collect::>()})) -} - -/// The layer a command's `"layer"` param names: an id, or a name (the topmost layer of that -/// name, as Photoshop's "select layer by name" action step finds it, so a loaded action replays -/// in another document; a name that matches no layer exactly matches regardless of case, so -/// `"background"` finds the Background). `None` when the param is absent. -pub(crate) fn explicit_layer(s: &Session, p: &Value) -> Result> { - match p.get("layer") { - Some(Value::Number(n)) => { - n.as_u64().map(|id| Some(LayerId(id))).ok_or_else(|| EngineError::Other(format!("layer id {n} is not a non-negative integer"))) - } - Some(Value::String(name)) => { - let d = s.active().ok_or(EngineError::NoDocument)?; - let layers = d.doc.walk(); - let mut top_down = layers.iter().rev(); - top_down - .clone() - .find(|(_, _, l)| l.name == *name) - .or_else(|| top_down.find(|(_, _, l)| l.name.to_lowercase() == name.to_lowercase())) - .map(|(_, _, l)| Some(l.id)) - .ok_or_else(|| EngineError::Other(format!("no layer named \"{name}\"; {}", layer_listing(&d.doc)))) - } - Some(Value::Null) | None => Ok(None), - Some(other) => Err(EngineError::Other(format!("`layer` must be an id or a name, not {other}"))), - } -} - -/// The layers of `doc` as a caller can name them, for an error about a layer that isn't there: -/// `the document's layers are 2 "Background", 3 "Layer 1"` (top-down, at most 20). -pub(crate) fn layer_listing(doc: &Document) -> String { - const MAX: usize = 20; - let layers = doc.walk(); - if layers.is_empty() { - return "the document has no layers".into(); - } - // Names are unbounded input: each one is cut at NAME characters so the error stays short. - const NAME: usize = 64; - let name = |n: &str| match n.char_indices().nth(NAME) { - Some((cut, _)) => format!("{}…", &n[..cut]), - None => n.to_string(), - }; - let mut list: Vec = layers.iter().rev().take(MAX).map(|(_, _, l)| format!("{} {:?}", l.id.0, name(&l.name))).collect(); - if layers.len() > MAX { - list.push(format!("… {} more (see `document.inspect`)", layers.len() - MAX)); - } - format!("the document's layers are {} (a `layer` param takes an id or a name)", list.join(", ")) -} - -/// The layer a command targets: [`explicit_layer`], else the active layer. -pub(crate) fn layer_param(s: &Session, p: &Value) -> Result { - match explicit_layer(s, p)? { - Some(id) => Ok(id), - None => s.active().and_then(|d| d.active_layer).ok_or(EngineError::Other("no active layer".into())), - } -} -pub fn blend_from_str(s: &str) -> Option { - let norm = |x: &str| x.to_ascii_lowercase().replace([' ', '_', '-', '(', ')'], ""); - let want = norm(s); - std::iter::once(BlendMode::PassThrough).chain(BlendMode::layer_modes()).find(|m| norm(m.label()) == want || norm(&format!("{m:?}")) == want) -} - -/// The active selection as the mask of a layer being created, or None without a selection. -/// Photoshop masks a new adjustment or fill layer with the selection, so the adjustment acts on -/// the selected area only (#1250); the selection itself stays, as Reveal Selection leaves it. -pub(crate) fn selection_mask(doc: &Document) -> Result> { - doc.selection.as_ref().map(|sel| mask_at_depth(LayerMask { surface: sel.clone(), ..LayerMask::reveal_all() }, doc.depth)).transpose() -} - -/// New pixel masks use the document's depth, as PSD saves/imports do. Otherwise a later soft -/// brush stroke quantizes differently depending on whether the document reopened as PSD or -/// native. Converting a selection keeps its coverage and does not alter the selection itself. -pub(crate) fn mask_at_depth(mut mask: LayerMask, depth: SampleType) -> Result { - let format = mask.surface.format().with_sample(depth); - if mask.surface.format() != format { - mask.surface = mask.surface.try_convert(format)?; - } - Ok(mask) -} - -/// Options from the Layers Panel flyout live in preferences so headless/keyboard commands -/// behave exactly like pointer-triggered commands. Old preferences preserve Photoshop defaults. -pub(crate) fn layer_panel_option(s: &Session, key: &str, fallback: bool) -> bool { - s.prefs().dialogs.get("ui.layersPanelOptions").and_then(|v| v.get(key)).and_then(Value::as_bool).unwrap_or(fallback) -} - -/// Mask a fill or adjustment layer being created, as Photoshop does: the path selected in the -/// Paths panel (`"path"`: `"work"`, a saved path's name or a path object) becomes its vector -/// mask, which makes a Solid Color fill a shape (#1419); without one, the selection becomes its -/// layer mask ([`selection_mask`]); without either, a white mask reveals the whole layer (#1768). -/// A path that isn't there is an error. -pub(crate) fn mask_new_layer(doc: &Document, l: &mut Layer, p: &Value, cmd: &str, default_mask: bool) -> Result<()> { - let path = match p.get("path") { - None | Some(Value::Null) => None, - Some(Value::String(n)) if crate::vector_cmds::is_work(Some(n)) => Some(doc.work_path.clone().ok_or_else(|| bad(cmd, "no work path"))?), - Some(Value::String(n)) => { - Some(doc.paths.iter().find(|sp| sp.name == *n).map(|sp| sp.path.clone()).ok_or_else(|| bad(cmd, format!("no path named \"{n}\"")))?) - } - Some(v) => Some(crate::vector_cmds::parse_path(v).map_err(|e| bad(cmd, e))?), - }; - match path { - Some(path) => l.vector_mask = Some(photocraft_doc::VectorMask::new(path)), - None => { - l.mask = selection_mask(doc)?.or_else(|| default_mask.then(LayerMask::reveal_all)).map(|mask| mask_at_depth(mask, doc.depth)).transpose()?; - } - } - Ok(()) -} - -/// The `"path"` param of the new fill and adjustment layer commands ([`mask_new_layer`]). -pub(crate) const NEW_LAYER_PATH: &str = - r##""path":"work"|saved path name|{…path}? (the active path: becomes the vector mask; else the selection is the layer mask, or white with no selection)"##; - -/// Add an adjustment layer above the active one; it takes the mask `mask_new_layer` builds from `p` (a path, the selection, or the default white mask). -fn new_adjustment(s: &mut Session, adj: Adjustment, p: &Value, cmd: &str) -> Result { - let label = format!("New {} Layer", adj.label()); - let name = adj.label().to_string(); - let id = s.edit(&label, |doc, active| { - let mut l = Layer::new(doc.next_layer_name(&name), LayerContent::Adjustment(adj)); - mask_new_layer(doc, &mut l, p, cmd, true)?; - let id = doc.insert_above(*active, l); - *active = Some(id); - Ok(id) - })?; - Ok(json!({ "layer": id.0 })) -} - -/// Apply `adj` in place to the targeted layer mask, the targeted alpha channel or Quick Mask, or else the active layer's pixels, as one history step named `label`. -fn destructive_adjust(s: &mut Session, label: &str, adj: Adjustment, p: &Value) -> Result { - if is_mask_target(p) { - // The targeted layer mask (#780): ⌘I inverts it, as in Photoshop. - let id = layer_param(s, &Value::Null)?; - return s.edit(label, |doc, _| { - check_all_unlocked(doc, id)?; - let sel = doc.selection.clone(); - pixels::adjust_mask(paint_surface(doc, id, p)?, &adj, sel.as_ref()).map_err(EngineError::Other)?; - Ok(Value::Null) - }); - } - if crate::channel_cmds::is_channel_target(p) { - // Alpha channel / Quick Mask target: the adjustment runs on the grayscale channel as on - // a layer mask, its unstored black included, so ⌘I in Quick Mask inverts it all (#6095). - return s.edit(label, |doc, _| { - let sel = doc.selection.clone(); - if let Some(surf) = crate::channel_cmds::channel_surface_for_filter(doc, None, p)? { - pixels::adjust_mask(surf, &adj, sel.as_ref()).map_err(EngineError::Other)?; - } - Ok(Value::Null) - }); - } - let id = layer_param(s, &Value::Null)?; - s.edit(label, |doc, _| { - let sel = doc.selection.clone(); - let mode = doc.mode; - let surf = paint_surface(doc, id, &Value::Null)?; - pixels::adjust_surface(surf, &adj, sel.as_ref(), mode).map_err(EngineError::Other)?; - Ok(()) - })?; - Ok(Value::Null) -} - -/// Lenient adjustment from params for previews: bad params fall back to the kind's defaults. -/// Commands use the checked [`crate::adjust_params::from_params`]. -pub fn adjustment_from_params(kind: &str, p: &Value) -> Adjustment { - crate::adjust_params::from_params(kind, p, None, ColorMode::Rgb) - .or_else(|_| crate::adjust_params::default_for(kind, ColorMode::Rgb)) - .unwrap_or(Adjustment::Invert) -} - -fn doc_mode(s: &Session) -> ColorMode { - s.active().map_or(ColorMode::Rgb, |d| d.doc.mode) -} - -/// The colour mode a destructive adjustment parses its tone space in: a targeted layer mask, -/// saved channel or Quick Mask holds gray levels whatever the document's mode, so Curves and -/// Levels stay in the neutral space instead of Lab (where the composite is ignored) or CMYK -/// (where the curve runs on the inks) (#5335). -fn adjust_mode(s: &Session, p: &Value) -> ColorMode { - if is_mask_target(p) || crate::channel_cmds::is_channel_target(p) { ColorMode::Grayscale } else { doc_mode(s) } -} - -/// Tone params for a gray plane target: the document-space channel records are dropped, because -/// those keys select the Lab or CMYK tone space and a plane only holds levels (#5335). -fn gray_tone_params(p: &Value) -> Value { - match p { - Value::Object(m) => { - let mut o = Map::new(); - for (k, v) in m { - if !matches!(k.as_str(), "cyan" | "magenta" | "yellow" | "black" | "lightness" | "a" | "b") { - o.insert(k.clone(), v.clone()); - } - } - Value::Object(o) - } - other => other.clone(), - } -} - // ---------- the table ---------- #[allow(clippy::too_many_lines)] @@ -1623,198 +1320,6 @@ fn test_panic_command() -> CommandSpec { CommandSpec { id: "test.panic", label: "Test Panic", menu: &[], shortcut: None, params: r##"{}"##, enabled: |_: &Session| Ok(()), run, journal: false } } -/// Commands generated from a table share one `run` fn; the kind is recovered from the id. -pub(crate) fn inject_kind(id: &str, params: Value) -> Value { - let kind = id.strip_prefix("layer.newAdjustmentLayer.").or_else(|| id.strip_prefix("image.adjustments.")); - match (kind, params) { - (Some(k), Value::Object(mut m)) => { - m.insert("__kind".into(), Value::String(k.into())); - Value::Object(m) - } - (Some(k), _) => json!({ "__kind": k }), - (None, p) => p, - } -} - -pub fn adjustment_kind(a: &Adjustment) -> &'static str { - match a { - Adjustment::BrightnessContrast { .. } => "brightnessContrast", - Adjustment::Levels { .. } => "levels", - Adjustment::Curves { .. } => "curves", - Adjustment::Exposure { .. } => "exposure", - Adjustment::Vibrance { .. } => "vibrance", - Adjustment::HueSaturation { .. } => "hueSaturation", - Adjustment::ColorBalance { .. } => "colorBalance", - Adjustment::BlackWhite { .. } => "blackWhite", - Adjustment::PhotoFilter { .. } => "photoFilter", - Adjustment::ChannelMixer { .. } => "channelMixer", - Adjustment::Posterize { .. } => "posterize", - Adjustment::Threshold { .. } => "threshold", - Adjustment::GradientMap { .. } => "gradientMap", - Adjustment::SelectiveColor { .. } => "selectiveColor", - Adjustment::ColorLookup { .. } => "colorLookup", - Adjustment::Unsupported { .. } => "unsupported", - _ => "invert", - } -} - -fn arrange(s: &mut Session, p: &Value, delta: i32) -> Result { - let id = layer_param(s, p)?; - s.edit("Arrange", |doc, _| { - // The Background stays at the bottom: it doesn't move and nothing goes below it. - let bg = crate::background_cmds::background_id(doc); - if bg == Some(id) { - return Err(EngineError::Other("the Background layer can't be moved".into())); - } - let steps = match delta { - i32::MAX => 10_000, - i32::MIN => -10_000, - d => d, - }; - let dir = steps.signum(); - let before = crate::clip_group::Before::read(doc, &[id]); - let mut moved = false; - for _ in 0..steps.abs() { - if !doc.shift(id, dir) { - break; - } - if crate::background_cmds::keep_background_at_bottom(bg, doc).is_err() { - doc.shift(id, -dir); - break; - } - moved = true; - } - if !moved { - return Err(EngineError::Other("layer can't move further".into())); - } - crate::clip_group::settle(doc, &[id], &before, false); - Ok(()) - })?; - Ok(Value::Null) -} - -/// Add (`Some`) or remove (`None`) a layer mask. Adding acts on every selected layer that can take -/// one ([`crate::layer_multi_cmds::mask_targets`]), in one history step. -fn set_mask(s: &mut Session, p: &Value, label: &str, mask: Option) -> Result { - set_mask_with(s, p, label, mask, false) -} - -/// [`set_mask`] that also drops the selection the mask was made from, in the same history step. -fn set_mask_and_deselect(s: &mut Session, p: &Value, label: &str, mask: LayerMask) -> Result { - set_mask_with(s, p, label, Some(mask), true) -} - -fn set_mask_with(s: &mut Session, p: &Value, label: &str, mask: Option, deselect: bool) -> Result { - let ids = if mask.is_some() { crate::layer_multi_cmds::mask_targets(s, p)? } else { vec![layer_param(s, p)?] }; - s.edit(label, |doc, _| { - let mask = mask.clone().map(|mask| mask_at_depth(mask, doc.depth)).transpose()?; - for id in &ids { - check_all_unlocked(doc, *id)?; - if mask.is_some() { - crate::extra_cmds::background_to_layer_for_mask(doc, *id); - } - doc.layer_mut(*id).ok_or(EngineError::NoLayer(*id))?.mask = mask.clone(); - } - if deselect { - doc.selection = None; - } - Ok(()) - })?; - Ok(Value::Null) -} - -/// Move a layer's pixels, linked mask and type by whole pixels (vectors move via -/// `vector_cmds::translate_vectors`). -pub(crate) fn translate_layer(doc: &Document, l: &mut Layer, dx: i32, dy: i32) { - use crate::layer_multi_cmds::shift_surface as translate_surface; - // Linked patterns in the layer's effects move with it. - if let Some(r) = &mut l.effects.reference { - *r = (r.0 + f64::from(dx), r.1 + f64::from(dy)); - } - if let Some(m) = &mut l.mask - && m.linked - { - m.surface = translate_surface(&m.surface, dx, dy); - } - match &mut l.content { - LayerContent::Raster(s) => *s = translate_surface(s, dx, dy), - LayerContent::Text(t) => { - t.transform = photocraft_geom::Affine::translate(dx as f64, dy as f64).mul(&t.transform); - // A whole-pixel move shifts the rendered text and its PSD position as they are. - // Re-rendering would replace Photoshop's rendering of imported type, and drop the - // text when its font is missing (artboard export, moving type with the Move tool). - let raw = t.psd_raw.as_deref().map(|r| photocraft_text::psd::translate_tysh(r, f64::from(dx), f64::from(dy))); - match (&mut t.cache, raw) { - (Some(c), Some(Some(r))) => { - *c = translate_surface(c, dx, dy); - t.psd_raw = Some(std::sync::Arc::new(r)); - } - (Some(c), None) => *c = translate_surface(c, dx, dy), - _ => crate::type_cmds::refresh(doc, t), - } - } - LayerContent::Group(g) => { - // Moving an artboard moves the board with its contents. - if let Some(a) = &mut g.artboard { - a.rect = a.rect.translate(dx, dy); - } - for c in &mut g.children { - translate_layer(doc, c, dx, dy); - } - } - LayerContent::Smart(sm) => crate::smart_cmds::shift_smart(sm, dx, dy), - _ => {} - } -} - -/// A copy of layer `id` as Layer › Duplicate Layer makes it, not yet in the document: a fresh id, -/// "… copy" appended to the name, and a copy of the Background layer is an ordinary, unlocked -/// layer (Photoshop). -pub(crate) fn layer_copy(doc: &Document, id: LayerId, add_copy: bool) -> Result { - let src = doc.layer(id).ok_or(EngineError::NoLayer(id))?; - // A copy of the Background layer is an ordinary, unlocked layer (Photoshop). - let from_background = doc.is_background(id); - let mut dup = src.duplicate(); - if add_copy { - dup.name = doc.copy_name(&dup.name); - } - if from_background { - dup.locks = Default::default(); - } - Ok(dup) -} - -/// Layer › Merge Group (⌘E with a group selected, #3832): the group's visible contents, as they -/// show, become one pixel layer in its place, named after it. Like Photoshop, the layer keeps the -/// group's opacity, blend mode (Pass Through becomes Normal), clipping and locks; the group's mask -/// and style are applied to the pixels. -fn merge_group(s: &mut Session, id: LayerId) -> Result { - s.edit("Merge Group", |doc, active| { - let group = doc.layer(id).ok_or(EngineError::NoLayer(id))?.clone(); - if !group.visible { - return Err(EngineError::Other("the group is hidden".into())); - } - let fmt = doc.pixel_format(); - let fmt = photocraft_color::PixelFormat::new(fmt.mode, fmt.sample, true); - let mut solo = group.clone(); - solo.opacity = 1.0; - solo.blend = photocraft_doc::BlendMode::Normal; - solo.clipped = false; - let mut tmp = doc.clone(); - tmp.layers = vec![solo]; - let mut merged = Layer::new(group.name.clone(), LayerContent::Raster(pixels::composite_layers_uncropped(&tmp, fmt))); - merged.id = group.id; - merged.opacity = group.opacity; - merged.blend = if group.blend == photocraft_doc::BlendMode::PassThrough { photocraft_doc::BlendMode::Normal } else { group.blend }; - merged.clipped = group.clipped; - merged.locks = group.locks; - *doc.layer_mut(id).ok_or(EngineError::NoLayer(id))? = merged; - *active = Some(id); - Ok(()) - })?; - Ok(json!({ "layer": id.0 })) -} - #[cfg(test)] mod registry_tests { use super::*; diff --git a/crates/engine/src/cmd/actions_cmds.rs b/crates/engine/src/cmd/actions_cmds.rs new file mode 100644 index 0000000000..4dcb8bb8b9 --- /dev/null +++ b/crates/engine/src/cmd/actions_cmds.rs @@ -0,0 +1,796 @@ +//! Window › Actions, as engine commands (`actions.record` / `stop` / `play` / `list` / `get` / +//! `delete` / `move` / `rename` / `toggle`). +//! +//! The list lives on [`Session`] so the panel, the CLI, the control channel and MCP share one +//! copy. Recording copies replayable journal entries (commands whose [`CommandSpec::journal`] is +//! set, except action-editing commands and the already-expanded `edit.transform.again` and +//! `edit.transform.againCopy`) into an action. A replayable command's journal entry replaces the +//! entries of the commands it ran on its own behalf, so they are recorded once (#3067). Playback +//! runs those steps with [`Session::execute`] and stops at the first error, leaving one history +//! step per step that ran. Steps switched off with `actions.toggle` (the Actions panel check +//! marks) are skipped by playback, Batch and droplets. +//! +//! An untrusted session installs [`Session::authorize`]. `actions.play` calls it for every nested +//! step, because the outer `actions.play` id would otherwise hide a recorded `file.*` command from +//! the top-level check. + +use std::collections::BTreeSet; + +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; + +use crate::commands::CommandSpec; +use crate::{EngineError, Result, Session}; + +fn bad(cmd: &str, msg: impl Into) -> EngineError { + EngineError::BadParams { cmd: cmd.into(), msg: msg.into() } +} + +/// One recorded action. `steps` is the `[[id, params], …]` shape `file.automate.batch` and +/// droplets already accept. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct Action { + pub name: String, + #[serde(default)] + pub steps: Vec<(String, Value)>, + /// Indices of steps excluded from playback (unchecked in the Actions panel). + #[serde(default, skip_serializing_if = "BTreeSet::is_empty")] + pub disabled: BTreeSet, + /// Indices of steps whose dialog Photoshop shows during playback (the panel's dialog + /// toggle column). Headless playback runs them with their recorded params; the flag is + /// kept so Save Actions writes it back. + #[serde(default, skip_serializing_if = "BTreeSet::is_empty")] + pub dialogs: BTreeSet, + /// The action set the action belongs to: the folder Photoshop shows in the Actions panel, + /// filled by Load Actions (`actions.load`) and written by Save Actions (`actions.save`). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub set: Option, + /// Button Mode colour. Empty is none; otherwise one of [`BUTTON_COLORS`]. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub color: String, +} + +/// Button Mode colours, in Photoshop's order. Empty is no colour. +pub const BUTTON_COLORS: [&str; 8] = ["", "red", "orange", "yellow", "green", "blue", "violet", "gray"]; + +impl Action { + pub fn new(name: impl Into, steps: Vec<(String, Value)>) -> Self { + Self { name: name.into(), steps, disabled: BTreeSet::new(), dialogs: BTreeSet::new(), set: None, color: String::new() } + } + + /// Apply `f` to every per-step index set (`disabled`, `dialogs`) after steps moved. + pub(crate) fn remap_steps(&mut self, f: impl Fn(usize) -> Option) { + self.disabled = self.disabled.iter().filter_map(|&i| f(i)).collect(); + self.dialogs = self.dialogs.iter().filter_map(|&i| f(i)).collect(); + } + + pub fn step_enabled(&self, step: usize) -> bool { + !self.disabled.contains(&step) + } + + /// The steps playback runs, with their indices in `steps`. + pub fn enabled_steps(&self) -> impl Iterator { + self.steps.iter().enumerate().filter(|(i, _)| self.step_enabled(*i)) + } +} + +/// On-disk form of [`ActionState::list`] (`actions.json` in the preset store). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct ActionsFile { + pub version: u32, + pub actions: Vec, +} + +pub const MAX_PLAYBACK_STEPS: u64 = 100_000; + +/// Actions list and the recording / playback flags. Only `list` is persisted. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct ActionState { + pub list: Vec, + /// Journal length when recording started, and the action index being recorded into. + #[serde(skip)] + pub recording: Option<(usize, usize)>, + /// Nesting depth of `actions.play`, bounded by the playback stack limit. + #[serde(skip)] + pub playing: u8, + /// Active action names, for cycle detection in engine and desktop playback. + #[serde(skip)] + pub playback_stack: Vec, + /// Number of steps executed by the current top-level playback tree. + #[serde(skip)] + pub playback_steps: u64, + /// How many scripts (`file.scripts.browse`) are running inside one another. + #[serde(skip)] + pub script_depth: u8, + /// Steps run by the current top-level script and everything it calls. + #[serde(skip)] + pub script_steps: u64, + /// Bumped whenever `list` changes, so the preset store can skip unchanged writes. + #[serde(skip)] + pub rev: u64, + /// Bumped by each `actions.record`, so a background job knows whether the recording it was + /// started in is still the one running when its result lands. + #[serde(skip)] + pub take: u64, +} + +impl ActionState { + pub(crate) fn touch(&mut self) { + self.rev = self.rev.saturating_add(1); + } +} + +/// Replay commands and named action calls, excluding edits to the action definitions and the +/// already-expanded Again wrapper. +pub fn replayable(id: &str) -> bool { + // Again and Again on a Copy journal their concrete steps (`edit.transform`, after + // `layer.duplicate` for the copy) and record those: the wrappers look up the last transform in + // the journal, so they fail where no transform ran yet, e.g. an action played in a new session. + id == "actions.play" + || (!id.starts_with("actions.") + // Browse executes its steps through Session::execute, so those concrete + // commands are already journaled. Recording the wrapper as well replays + // every script edit twice (#3057). + && !matches!(id, "edit.transform.again" | "edit.transform.againCopy" | "file.scripts.browse") + && (shell_view_command(id) || shell_save_command(id) || crate::commands::find(id).is_some_and(|c| c.journal))) +} + +/// File › Save, Save As and Save a Copy, and File › Export › Export As, recorded by the desktop +/// shell once the file has a path (#2032, #4373, #7207). The shell replays them; batch and +/// droplets write to their destination folder instead. +pub fn shell_save_command(id: &str) -> bool { + matches!(id, "file.save" | "file.saveAs" | "file.saveACopy" | "file.export.exportAs") +} + +/// The failure for a played Save step whose document `target` (the one active when the step +/// started) is no longer open: a Save Document script event closed it. Playback stops there, so +/// the next step without a document, such as the Close half of an imported Close with Save: Yes, +/// doesn't act on whichever document is active now (#7367). +pub fn save_target_closed(s: &Session, id: &str, target: Option) -> Option { + let target = target.filter(|_| shell_save_command(id))?; + (!s.documents().iter().any(|d| d.doc.id == target)).then(|| { + "the document was closed during the save (by a Save Document script event); playback stopped so later steps don't act on another document".into() + }) +} + +/// Charge one step against the complete nested playback tree. +pub fn consume_playback_step(s: &mut Session) -> bool { + // Inside a script the step also counts against the script's total: each top-level playback + // resets its own counter, so a script playing actions in a row would never reach the limit. + if s.actions.script_depth > 0 { + if s.actions.script_steps >= crate::automate_cmds::MAX_SCRIPT_STEPS { + return false; + } + s.actions.script_steps += 1; + } + if s.actions.playback_steps >= MAX_PLAYBACK_STEPS { + false + } else { + s.actions.playback_steps += 1; + true + } +} +/// View-only menu commands recorded by the desktop shell. Headless playback reports +/// them as unsupported instead of silently dropping them; Batch and droplets skip them. +pub fn shell_view_command(id: &str) -> bool { + matches!(id, "view.fitOnScreen" | "view.actualPixels" | "view.zoomIn" | "view.zoomOut") +} + +/// Shared validation for headless and shell playback. Does not start playback. +pub fn playback_plan(s: &Session, p: &Value) -> Result<(Action, usize)> { + if s.actions.playing > 0 && s.actions.playback_stack.is_empty() { + return Err(bad("actions.play", "an action is already playing")); + } + let idx = resolve(&s.actions.list, p, "actions.play")?; + let action = s.actions.list.get(idx).cloned().ok_or_else(|| bad("actions.play", "no such action"))?; + if s.actions.playback_stack.iter().any(|name| name == &action.name) || s.actions.recording.is_some_and(|(_, i)| i == idx) { + return Err(bad("actions.play", format!("recursive action call to `{}`", action.name))); + } + if s.actions.playback_stack.len() >= 16 { + return Err(bad("actions.play", "action nesting exceeds 16 levels")); + } + let from = from_step(p, action.steps.len())?; + Ok((action, from)) +} + +/// The actions that `steps` call through Play Action steps and the branches of Conditional steps, +/// followed transitively, in list order, so a droplet can run without the Actions panel that made +/// it (#2794, #6804). Index references in `steps` and in the copies become names, which resolve +/// without the rest of the list. A target that doesn't resolve is left alone: it fails at +/// playback, as it would have before. +pub fn called_actions(list: &[Action], steps: &mut [(String, Value)]) -> Vec { + fn targets(list: &[Action], steps: &mut [(String, Value)], depth: usize, queue: &mut Vec<(usize, usize)>) { + for (id, params) in steps.iter_mut() { + match id.as_str() { + "actions.play" => { + let Ok(i) = resolve(list, params, "actions.play") else { continue }; + if let (Some(action), Some(obj)) = (list.get(i), params.as_object_mut()) { + obj.insert("action".into(), json!(action.name)); + } + queue.push((i, depth)); + } + // Conditional branches only take names, so there is nothing to rewrite. + "actions.conditional" => { + for key in ["then", "else"] { + let Some(name) = params.get(key).and_then(Value::as_str) else { continue }; + if let Some(i) = list.iter().position(|a| a.name == name) { + queue.push((i, depth)); + } + } + } + _ => {} + } + } + } + let mut queue = Vec::new(); + targets(list, steps, 1, &mut queue); + let mut found = std::collections::BTreeMap::new(); + while let Some((i, depth)) = queue.pop() { + // Playback stops at 16 levels, so deeper calls never run. + if depth > 16 || found.contains_key(&i) { + continue; + } + let Some(mut action) = list.get(i).cloned() else { continue }; + targets(list, &mut action.steps, depth + 1, &mut queue); + found.insert(i, action); + } + found.into_values().collect() +} + +fn always(_: &Session) -> std::result::Result<(), String> { + Ok(()) +} + +fn num(v: &Value) -> Option { + v.as_i64().or_else(|| v.as_f64().filter(|f| f.is_finite()).map(|f| f.round() as i64)) +} + +pub(crate) fn resolve(list: &[Action], p: &Value, cmd: &str) -> Result { + let Some(v) = p.get("action") else { + return Err(bad(cmd, "needs \"action\" (a name or an index)")); + }; + if let Some(i) = num(v) { + if i < 0 { + return Err(bad(cmd, "action index is negative")); + } + let Some(i) = usize::try_from(i).ok() else { + return Err(bad(cmd, "action index is out of range")); + }; + if i >= list.len() { + return Err(bad(cmd, format!("no action at index {i}"))); + } + return Ok(i); + } + match v.as_str() { + Some(name) if !name.is_empty() => list.iter().position(|a| a.name == name).ok_or_else(|| bad(cmd, format!("no action named `{name}`"))), + Some(_) => Err(bad(cmd, "action name is empty")), + None => Err(bad(cmd, "\"action\" must be a name or an index")), + } +} + +fn from_step(p: &Value, len: usize) -> Result { + let Some(v) = p.get("from") else { return Ok(0) }; + if v.is_null() { + return Ok(0); + } + let Some(i) = num(v) else { + return Err(bad("actions.play", "\"from\" must be a step index")); + }; + if i < 0 { + return Err(bad("actions.play", "\"from\" is negative")); + } + let Some(i) = usize::try_from(i).ok() else { + return Err(bad("actions.play", "\"from\" is out of range")); + }; + if i > len { + return Err(bad("actions.play", format!("\"from\" {i} is past the last step ({len})"))); + } + Ok(i) +} + +fn list(s: &mut Session, _p: &Value) -> Result { + let actions: Vec = s.actions.list.iter().map(|a| json!({"name": a.name, "steps": a.steps.len(), "set": a.set})).collect(); + let recording = s.actions.recording.and_then(|(_, i)| s.actions.list.get(i).map(|a| a.name.clone())); + Ok(json!({"actions": actions, "recording": recording})) +} + +fn get(s: &mut Session, p: &Value) -> Result { + let idx = resolve(&s.actions.list, p, "actions.get")?; + let action = &s.actions.list[idx]; + let steps: Vec = action.steps.iter().map(|(id, params)| json!([id, params])).collect(); + Ok(json!({"name": action.name, "steps": steps, "disabled": action.disabled, "dialogs": action.dialogs, "set": action.set, "color": action.color})) +} + +fn record(s: &mut Session, p: &Value) -> Result { + not_playing(s, "actions.record")?; + if s.actions.recording.is_some() { + return Err(bad("actions.record", "already recording; stop first")); + } + let idx = if p.get("action").is_some() { + resolve(&s.actions.list, p, "actions.record")? + } else { + let name = match p.get("name") { + None | Some(Value::Null) => { + let mut n = s.actions.list.len().saturating_add(1); + while s.actions.list.iter().any(|a| a.name == format!("Action {n}")) { + n = n.checked_add(1).ok_or_else(|| bad("actions.record", "cannot allocate a unique action name"))?; + } + format!("Action {n}") + } + Some(Value::String(n)) if !n.is_empty() => n.clone(), + Some(Value::String(_)) => return Err(bad("actions.record", "\"name\" is empty")), + Some(_) => return Err(bad("actions.record", "\"name\" must be a string")), + }; + if s.actions.list.iter().any(|action| action.name == name) { + return Err(bad("actions.record", "an action with this name already exists")); + } + s.actions.list.push(Action::new(name, Vec::new())); + s.actions.touch(); + s.actions.list.len() - 1 + }; + s.actions.recording = Some((s.journal.len(), idx)); + s.actions.take = s.actions.take.wrapping_add(1); + let name = s.actions.list.get(idx).map(|a| a.name.clone()).unwrap_or_default(); + Ok(json!({"action": name, "index": idx})) +} + +/// Replayable journal entries not yet committed to this action while recording. +pub fn pending_steps(s: &Session, action: usize) -> impl Iterator { + let from = s.actions.recording.filter(|(_, i)| *i == action).map_or(s.journal.len(), |(from, _)| from); + s.journal.iter().skip(from).filter(|(id, _)| replayable(id)) +} + +pub(crate) fn flush_recording(s: &mut Session) -> Result<()> { + let Some((_, idx)) = s.actions.recording else { return Ok(()) }; + if idx >= s.actions.list.len() { + return Err(bad("actions.stop", "the action being recorded no longer exists")); + } + let steps: Vec<_> = pending_steps(s, idx).cloned().collect(); + s.actions.recording = Some((s.journal.len(), idx)); + if !steps.is_empty() { + s.actions.list[idx].steps.extend(steps); + s.actions.touch(); + } + Ok(()) +} + +fn stop(s: &mut Session, _p: &Value) -> Result { + not_playing(s, "actions.stop")?; + let Some((_, idx)) = s.actions.recording else { + return Err(bad("actions.stop", "not recording")); + }; + flush_recording(s)?; + s.actions.recording = None; + let action = &s.actions.list[idx]; + Ok(json!({"action": action.name, "steps": action.steps.len()})) +} + +/// A step Photoshop plays as a silent no-op although its menu item is greyed: Deselect with an +/// open document and nothing selected (actions often start with it to clear any selection, #6744). +fn noop_step(s: &Session, id: &str) -> bool { + id == "select.deselect" && s.active().is_some_and(|d| d.doc.selection.is_none()) +} + +fn run_recorded(s: &mut Session, action: &Action, from: usize) -> (u64, Option) { + let mut ran = 0u64; + let mut failed = None; + for (i, (id, params)) in action.enabled_steps().skip_while(|(i, _)| *i < from) { + if !consume_playback_step(s) { + failed = Some(json!({"step": i, "id": id, "error": format!("action playback exceeded the {}-step limit", MAX_PLAYBACK_STEPS)})); + break; + } + if let Some(auth) = s.authorize + && let Err(e) = auth(id, params) + { + failed = Some(json!({"step": i, "id": id, "error": e.to_string()})); + break; + } + if noop_step(s, id) { + ran += 1; + continue; + } + match s.execute(id, params.clone()) { + Ok(value) => { + if let Some(error) = nested_failure(id, &value) { + failed = Some(json!({"step": i, "id": id, "error": error})); + break; + } + ran += 1; + } + Err(e) => { + failed = Some(json!({"step": i, "id": id, "error": e.to_string()})); + break; + } + } + } + (ran, failed) +} + +/// Suspend recording while a called action executes. Keep its commands in the journal +/// for diagnostics, but record just the named call in the parent action. +pub fn begin_playback(s: &mut Session, action: &Action) -> Result> { + flush_recording(s)?; + if s.actions.playing == 0 { + s.actions.playback_steps = 0; + } + let recording = s.actions.recording.take(); + s.actions.playing = s.actions.playing.saturating_add(1); + s.actions.playback_stack.push(action.name.clone()); + Ok(recording) +} + +pub fn finish_playback(s: &mut Session, recording: Option<(usize, usize)>, action: &Action, from: usize) { + s.actions.playback_stack.pop(); + s.actions.playing = s.actions.playing.saturating_sub(1); + if let Some((_, idx)) = recording { + restore_recording(s, idx, &action.name, from); + } +} + +/// Resume recording into action `idx` and journal the named call that suspended it. +pub fn restore_recording(s: &mut Session, idx: usize, action: &str, from: usize) { + s.actions.recording = Some((s.journal.len(), idx)); + let mut params = json!({"action": action}); + if from > 0 { + params["from"] = json!(from); + } + s.journal.push(("actions.play".into(), params)); +} + +/// Nested playback returns a structured failure even though the command itself succeeded. +/// Promote it to the caller's failed step so no later parent steps run after a child fails. +pub fn nested_failure(id: &str, value: &Value) -> Option { + (id == "actions.play" || id == "actions.conditional").then(|| value.get("failed")).flatten().map(|failure| { + format!( + "action `{}` step {} failed: {}", + value.get("action").and_then(Value::as_str).unwrap_or(""), + failure.get("step").and_then(Value::as_u64).unwrap_or(0).saturating_add(1), + failure.get("error").and_then(Value::as_str).unwrap_or("unknown error") + ) + }) +} + +fn play(s: &mut Session, p: &Value) -> Result { + let (action, from) = playback_plan(s, p)?; + let recording = begin_playback(s, &action)?; + let (ran, failed) = run_recorded(s, &action, from); + finish_playback(s, recording, &action, from); + Ok(match failed { + Some(f) => json!({"action": action.name, "ran": ran, "failed": f}), + None => json!({"action": action.name, "ran": ran}), + }) +} + +pub(crate) fn not_playing(s: &Session, cmd: &str) -> Result<()> { + if s.actions.playing > 0 { Err(bad(cmd, "cannot edit actions during playback")) } else { Ok(()) } +} + +/// Move to a final zero-based index, either in an action's steps or in the action list. +fn move_item(s: &mut Session, p: &Value) -> Result { + not_playing(s, "actions.move")?; + let idx = resolve(&s.actions.list, p, "actions.move")?; + let index = |key: &str| -> Result { + p.get(key) + .and_then(Value::as_u64) + .and_then(|n| usize::try_from(n).ok()) + .ok_or_else(|| bad("actions.move", format!("{key} must be a non-negative integer"))) + }; + let to = index("to")?; + if p.get("step").is_some() { + let step = index("step")?; + let len = s.actions.list[idx].steps.len().saturating_add(pending_steps(s, idx).count()); + if step >= len || to >= len { + return Err(bad("actions.move", "step or destination is out of range")); + } + if s.actions.recording.is_some_and(|(_, i)| i == idx) { + flush_recording(s)?; + } + let action = &mut s.actions.list[idx]; + let moved = action.steps.remove(step); + action.steps.insert(to, moved); + action.remap_steps(|i| Some(moved_index(i, step, to))); + let result = json!({"action": action.name, "step": to}); + s.actions.touch(); + Ok(result) + } else { + if to >= s.actions.list.len() { + return Err(bad("actions.move", "destination is out of range")); + } + let moved = s.actions.list.remove(idx); + let result = json!({"action": moved.name, "index": to}); + s.actions.list.insert(to, moved); + if let Some((_, recording)) = s.actions.recording.as_mut() { + *recording = moved_index(*recording, idx, to); + } + s.actions.touch(); + Ok(result) + } +} + +/// Follow a selected/recording row when a list item is moved. +pub fn moved_index(index: usize, from: usize, to: usize) -> usize { + if index == from { + to + } else if from < index && index <= to { + index - 1 + } else if to <= index && index < from { + index + 1 + } else { + index + } +} + +fn delete(s: &mut Session, p: &Value) -> Result { + not_playing(s, "actions.delete")?; + let idx = resolve(&s.actions.list, p, "actions.delete")?; + if let Some(step) = p.get("step") { + let step = step.as_u64().and_then(|i| usize::try_from(i).ok()).ok_or_else(|| bad("actions.delete", "step must be a non-negative integer"))?; + let len = s.actions.list[idx].steps.len().saturating_add(pending_steps(s, idx).count()); + if step >= len { + return Err(bad("actions.delete", "step is out of range")); + } + // Commit pending entries before editing the action; never erase the command + // journal or undo the edit that produced the deleted recording step. + if s.actions.recording.is_some_and(|(_, i)| i == idx) { + flush_recording(s)?; + } + let action = &mut s.actions.list[idx]; + action.steps.remove(step); + action.remap_steps(|i| { + if i == step { + None + } else if i > step { + Some(i - 1) + } else { + Some(i) + } + }); + let result = json!({"action": action.name, "deletedStep": step, "steps": action.steps.len()}); + s.actions.touch(); + return Ok(result); + } + if s.actions.recording.is_some() { + return Err(bad("actions.delete", "stop recording before deleting an action")); + } + let name = s.actions.list.remove(idx).name; + s.actions.touch(); + // Its function key goes with it, or the next action given the same name would inherit it. + let key = format!("{PLAY_SHORTCUT_PREFIX}{name}"); + if s.prefs().shortcuts.contains_key(&key) { + s.edit_prefs(|prefs| { + prefs.shortcuts.remove(&key); + }); + } + Ok(json!({"deleted": name})) +} + +/// The Actions panel check marks. With `step`, switch one step on or off; without it, switch +/// every step (all on unless all already are, like clicking the action's check mark). +fn toggle(s: &mut Session, p: &Value) -> Result { + let cmd = "actions.toggle"; + not_playing(s, cmd)?; + let idx = resolve(&s.actions.list, p, cmd)?; + let enabled = match p.get("enabled") { + None | Some(Value::Null) => None, + Some(Value::Bool(b)) => Some(*b), + Some(_) => return Err(bad(cmd, "\"enabled\" must be true or false")), + }; + let step = match p.get("step") { + None | Some(Value::Null) => None, + Some(v) => Some(v.as_u64().and_then(|i| usize::try_from(i).ok()).ok_or_else(|| bad(cmd, "step must be a non-negative integer"))?), + }; + let len = s.actions.list[idx].steps.len().saturating_add(pending_steps(s, idx).count()); + if step.is_some_and(|step| step >= len) { + return Err(bad(cmd, "step is out of range")); + } + if s.actions.recording.is_some_and(|(_, i)| i == idx) { + flush_recording(s)?; + } + let action = &mut s.actions.list[idx]; + match step { + Some(step) => { + if enabled.unwrap_or(!action.step_enabled(step)) { + action.disabled.remove(&step); + } else { + action.disabled.insert(step); + } + } + None if enabled.unwrap_or(!action.disabled.is_empty()) => action.disabled.clear(), + None => action.disabled = (0..action.steps.len()).collect(), + } + let result = json!({"action": action.name, "disabled": action.disabled}); + s.actions.touch(); + Ok(result) +} + +/// Prefix of the persisted shortcut override that plays a named action (`actions.play:`). +pub const PLAY_SHORTCUT_PREFIX: &str = "actions.play:"; + +/// Rename an action in place. Nested `actions.play` steps and `actions.conditional` branches +/// that call it by name, and its function-key binding, follow the new name so nothing silently +/// stops working. +fn rename(s: &mut Session, p: &Value) -> Result { + not_playing(s, "actions.rename")?; + let idx = resolve(&s.actions.list, p, "actions.rename")?; + let name = match p.get("name") { + Some(Value::String(n)) if !n.trim().is_empty() => n.clone(), + Some(Value::String(_)) => return Err(bad("actions.rename", "\"name\" is empty")), + Some(_) => return Err(bad("actions.rename", "\"name\" must be a string")), + None => return Err(bad("actions.rename", "needs \"name\"")), + }; + let old = s.actions.list.get(idx).map(|a| a.name.clone()).ok_or_else(|| bad("actions.rename", "no such action"))?; + if old == name { + return Ok(json!({"action": name, "index": idx})); + } + if s.actions.list.iter().any(|a| a.name == name) { + return Err(bad("actions.rename", "an action with this name already exists")); + } + let pending = s.actions.recording.map_or(s.journal.len(), |(start, _)| start); + let calls = s.actions.list.iter_mut().flat_map(|a| a.steps.iter_mut()).chain(s.journal.iter_mut().skip(pending)); + for (id, params) in calls { + let keys: &[&str] = match id.as_str() { + "actions.play" => &["action"], + "actions.conditional" => &["then", "else"], + _ => &[], + }; + for key in keys { + if params.get(*key).and_then(Value::as_str) == Some(old.as_str()) { + params[*key] = json!(name); + } + } + } + if let Some(action) = s.actions.list.get_mut(idx) { + action.name = name.clone(); + } + s.actions.touch(); + let (from, to) = (format!("{PLAY_SHORTCUT_PREFIX}{old}"), format!("{PLAY_SHORTCUT_PREFIX}{name}")); + if s.prefs().shortcuts.contains_key(&from) { + s.edit_prefs(|prefs| { + if let Some(key) = prefs.shortcuts.remove(&from) { + prefs.shortcuts.insert(to, key); + } + }); + } + Ok(json!({"action": name, "index": idx})) +} + +fn set_color(s: &mut Session, p: &Value) -> Result { + let cmd = "actions.setColor"; + not_playing(s, cmd)?; + let idx = resolve(&s.actions.list, p, cmd)?; + let Some(color) = p.get("color").and_then(Value::as_str) else { + return Err(bad(cmd, "needs \"color\"")); + }; + if !BUTTON_COLORS.contains(&color) { + return Err(bad(cmd, "color must be empty, red, orange, yellow, green, blue, violet, or gray")); + } + let Some(action) = s.actions.list.get_mut(idx) else { + return Err(bad(cmd, "no such action")); + }; + action.color = color.to_string(); + let name = action.name.clone(); + s.actions.touch(); + Ok(json!({"action": name, "color": color})) +} + +pub fn specs() -> Vec { + vec![ + CommandSpec { + id: "actions.move", + label: "Move Action or Step", + menu: &[], + shortcut: None, + params: r##"{"action":name|index, "step":index?, "to":index}. Move a step within its action, or the action itself. to is the final zero-based index. Pending recorded steps can be moved."##, + enabled: always, + run: move_item, + journal: false, + }, + CommandSpec { + id: "actions.list", + label: "List Actions", + menu: &[], + shortcut: None, + params: "{} → {actions:[{name, steps:count, set:name|null}], recording:name|null}", + enabled: always, + run: list, + journal: false, + }, + CommandSpec { + id: "actions.get", + label: "Get Action", + menu: &[], + shortcut: None, + params: r##"{"action":name|index} → {name, steps:[[id, params]…], disabled:[step…], dialogs:[step…], set:name|null, color:str} (steps is the shape file.automate.batch and droplets take; disabled lists the 0-based steps playback skips; dialogs the steps whose dialog Photoshop would show; set the action set from Load Actions; color is the Button Mode swatch, or empty)"##, + enabled: always, + run: get, + journal: false, + }, + CommandSpec { + id: "actions.record", + label: "Record Action", + menu: &[], + shortcut: None, + params: r##"{"name":str? (new action, default "Action N")} or {"action":name|index} (append) → {action, index}"##, + enabled: always, + run: record, + journal: false, + }, + CommandSpec { + id: "actions.stop", + label: "Stop Recording", + menu: &[], + shortcut: None, + params: "{} → {action, steps:count} (steps recorded since actions.record, queries and action-editing commands omitted)", + enabled: always, + run: stop, + journal: false, + }, + CommandSpec { + id: "actions.play", + label: "Play Action", + menu: &[], + shortcut: None, + params: r##"{"action":name|index, "from":step?} → {action, ran, failed?:{step, id, error}}. step and from are 0-based; steps switched off with actions.toggle are skipped. Stops at the first error (the command still returns ok, with failed set) and leaves one history step per step that ran. Nested calls are supported up to 16 levels; cycles are rejected. Recording stores a named call rather than its expanded commands. Each step is checked with Session::authorize when one is installed."##, + enabled: always, + run: play, + journal: false, + }, + CommandSpec { + id: "actions.delete", + label: "Delete Action", + menu: &[], + shortcut: None, + params: r##"{"action":name|index, "step":index?} → {deleted:name} or {action, deletedStep, steps:count}. step is 0-based, including pending recorded steps. Whole-action deletion is refused while recording."##, + enabled: always, + run: delete, + journal: false, + }, + CommandSpec { + id: "actions.toggle", + label: "Toggle Action Steps", + menu: &[], + shortcut: None, + params: r##"{"action":name|index, "step":index?, "enabled":bool?} → {action, disabled:[step…]}. Switch one 0-based step (including pending recorded steps) on or off for playback, Batch and droplets; omitted enabled flips it. Without step, switch every step: on unless all already are, or as enabled says."##, + enabled: always, + run: toggle, + journal: false, + }, + CommandSpec { + id: "actions.rename", + label: "Rename Action", + menu: &[], + shortcut: None, + params: r##"{"action":name|index, "name":str} → {action, index}. The name must not be empty or whitespace-only and must be unique. Nested Play Action steps and the action's function key follow the rename."##, + enabled: always, + run: rename, + journal: false, + }, + CommandSpec { + id: "actions.setColor", + label: "Set Action Color", + menu: &[], + shortcut: None, + params: r##"{"action":name|index, "color":""|"red"|"orange"|"yellow"|"green"|"blue"|"violet"|"gray"} → {action, color}. The Button Mode colour. Empty clears it."##, + enabled: always, + run: set_color, + journal: false, + }, + ] +} + +#[cfg(test)] +mod tests; + +#[cfg(test)] +mod security_tests { + use super::*; + + #[test] + fn playback_budget_is_shared_by_nested_calls() { + let mut session = Session::new(); + session.actions.playback_steps = MAX_PLAYBACK_STEPS - 1; + assert!(consume_playback_step(&mut session)); + assert!(!consume_playback_step(&mut session)); + } +} diff --git a/crates/engine/src/cmd/actions_cmds/tests.rs b/crates/engine/src/cmd/actions_cmds/tests.rs new file mode 100644 index 0000000000..b7974784b6 --- /dev/null +++ b/crates/engine/src/cmd/actions_cmds/tests.rs @@ -0,0 +1,1042 @@ +use super::*; +use serde_json::json; + +fn pixel(s: &Session, layer: usize, x: i32, y: i32) -> Vec { + s.active().unwrap().doc.layers[layer].surface().unwrap().pixel(x, y) +} + +#[test] +fn deselect_with_nothing_selected_is_a_noop_in_playback() { + // #6744: imported actions often start with Deselect; with no selection Photoshop plays on. + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + let before = s.active().unwrap().history.past_len(); + // Outside playback the command stays disabled, like Photoshop's greyed menu item. + assert!(s.execute("select.deselect", json!({})).is_err()); + assert!(s.active().unwrap().doc.selection.is_none()); + assert_eq!(s.active().unwrap().history.past_len(), before, "rejection adds no history step"); + let deselect = crate::commands::find("select.deselect").unwrap(); + assert_eq!((deselect.run)(&mut s, &json!({})).unwrap(), Value::Null); + assert_eq!(s.active().unwrap().history.past_len(), before, "no history step"); + + let steps = vec![("select.deselect".to_string(), json!({})), ("layer.new.layer".to_string(), json!({"name": "A"}))]; + s.actions.list.push(Action::new("Clear", steps)); + let played = s.execute("actions.play", json!({"action": 0})).unwrap(); + assert_eq!(played["ran"], 2, "{played}"); + assert_eq!(s.active().unwrap().doc.layers.last().unwrap().name, "A"); +} + +#[test] +fn unchecked_steps_are_skipped_and_follow_move_and_delete() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + let step = |name: &str| ("layer.new.layer".to_string(), json!({"name": name})); + s.actions.list.push(Action::new("Three", vec![step("A"), step("B"), step("C")])); + let names = |s: &Session| s.active().unwrap().doc.layers.iter().skip(1).map(|l| l.name.clone()).collect::>(); + + assert_eq!(s.execute("actions.toggle", json!({"action": "Three", "step": 1})).unwrap()["disabled"], json!([1])); + let played = s.execute("actions.play", json!({"action": 0})).unwrap(); + assert_eq!(played["ran"], 2); + assert_eq!(names(&s), ["A", "C"], "the unchecked step is skipped"); + assert_eq!(s.execute("actions.get", json!({"action": 0})).unwrap()["disabled"], json!([1])); + + // Moving step 3 to the top keeps B (now step 2) unchecked; deleting the moved step shifts it to 1. + s.execute("actions.move", json!({"action": 0, "step": 2, "to": 0})).unwrap(); + let ids: Vec<_> = s.actions.list[0].steps.iter().map(|(_, p)| p["name"].as_str().unwrap()).collect(); + assert_eq!((ids, s.actions.list[0].disabled.iter().copied().collect::>()), (vec!["C", "A", "B"], vec![2])); + s.execute("actions.delete", json!({"action": 0, "step": 0})).unwrap(); + assert_eq!(s.actions.list[0].steps, [step("A"), step("B")], "deleting removes only that step"); + assert_eq!(s.actions.list[0].disabled.iter().copied().collect::>(), [1]); + + // The action's own check: all on unless all already are. + s.execute("actions.toggle", json!({"action": 0})).unwrap(); + assert!(s.actions.list[0].disabled.is_empty()); + s.execute("actions.toggle", json!({"action": 0})).unwrap(); + assert_eq!(s.actions.list[0].disabled.len(), 2); + s.execute("actions.toggle", json!({"action": 0, "step": 0, "enabled": true})).unwrap(); + assert_eq!(s.actions.list[0].disabled.iter().copied().collect::>(), [1]); + + for bad in [ + json!({"action": 0, "step": 2}), + json!({"action": 0, "step": -1}), + json!({"action": 0, "step": "x"}), + json!({"action": 0, "step": 0, "enabled": "yes"}), + json!({"action": 7, "step": 0}), + json!({}), + ] { + assert!(s.execute("actions.toggle", bad.clone()).is_err(), "{bad}"); + } + assert_eq!(s.actions.list[0].disabled.iter().copied().collect::>(), [1], "rejected toggles change nothing"); +} + +#[test] +fn rename_keeps_calls_and_function_key_and_rejects_bad_names() { + let mut s = Session::new(); + s.actions.list.push(Action { + name: "Action 1".into(), + steps: vec![("layer.new.layer".into(), json!({}))], + disabled: Default::default(), + ..Default::default() + }); + s.actions.list.push(Action { + name: "Caller".into(), + steps: vec![("actions.play".into(), json!({"action": "Action 1"}))], + disabled: Default::default(), + ..Default::default() + }); + s.edit_prefs(|p| p.shortcuts.insert(format!("{PLAY_SHORTCUT_PREFIX}Action 1"), "F2".into())); + assert_eq!(s.execute("actions.rename", json!({"action": 0, "name": "Sepia"})).unwrap()["action"], "Sepia"); + assert_eq!(s.execute("actions.list", json!({})).unwrap()["actions"][0]["name"], "Sepia"); + assert_eq!(s.actions.list[1].steps[0].1["action"], "Sepia"); + assert_eq!(s.prefs().shortcuts.get("actions.play:Sepia").map(String::as_str), Some("F2")); + assert!(!s.prefs().shortcuts.contains_key("actions.play:Action 1")); + for bad in [ + json!({"action": 0, "name": ""}), + json!({"action": 0, "name": " "}), + json!({"action": 0, "name": "Caller"}), + json!({"action": 0, "name": 7}), + json!({"action": 9, "name": "X"}), + json!({"action": 0}), + ] { + assert!(s.execute("actions.rename", bad.clone()).is_err(), "{bad}"); + } + assert_eq!(s.actions.list[0].name, "Sepia"); +} + +#[test] +fn rename_follows_conditional_branches() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + for name in ["B", "Other"] { + s.actions.list.push(Action { name: name.into(), steps: vec![("layer.new.layer".into(), json!({}))], ..Default::default() }); + } + s.actions.list.push(Action { + name: "Main".into(), + steps: vec![ + ("actions.conditional".into(), json!({"if": "always", "then": "B", "else": "Other"})), + ("actions.conditional".into(), json!({"if": "never", "then": "Other", "else": "B"})), + ], + ..Default::default() + }); + s.execute("actions.rename", json!({"action": "B", "name": "C"})).unwrap(); + let steps = &s.actions.list[2].steps; + assert_eq!(steps[0].1, json!({"if": "always", "then": "C", "else": "Other"})); + assert_eq!(steps[1].1, json!({"if": "never", "then": "Other", "else": "C"})); + let r = s.execute("actions.play", json!({"action": "Main"})).unwrap(); + assert!(r.get("failed").is_none(), "{r}"); +} + +#[test] +fn delete_action_drops_its_function_key_but_deleting_a_step_keeps_it() { + let mut s = Session::new(); + let key = format!("{PLAY_SHORTCUT_PREFIX}Action 1"); + s.actions.list.push(Action::new("Action 1", vec![("layer.new.layer".into(), json!({})), ("layer.new.layer".into(), json!({}))])); + s.edit_prefs(|p| p.shortcuts.insert(key.clone(), "F2".into())); + s.execute("actions.delete", json!({"action": 0, "step": 0})).unwrap(); + assert_eq!(s.prefs().shortcuts.get(&key).map(String::as_str), Some("F2"), "deleting a step keeps the key"); + assert_eq!(s.execute("actions.delete", json!({"action": 0})).unwrap()["deleted"], "Action 1"); + assert!(!s.prefs().shortcuts.contains_key(&key), "the deleted action's function key is gone"); + s.execute("actions.record", json!({})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + assert_eq!(s.actions.list[0].name, "Action 1"); + assert!(!s.prefs().shortcuts.contains_key(&key), "a new action with the same name starts unbound"); +} + +fn record_red(s: &mut Session, depth: u32) { + s.execute("file.new", json!({"width": 40, "height": 40, "depth": depth})).unwrap(); + s.execute("actions.record", json!({"name": "Red"})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + let _ = s.execute("document.pixel", json!({"x": 1, "y": 1})); + let _ = s.execute("actions.list", json!({})); + s.execute("actions.stop", json!({})).unwrap(); +} + +fn translated_square(s: &mut Session, depth: u32) { + s.execute("file.new", json!({"width": 20, "height": 8, "depth": depth, "background": "transparent"})).unwrap(); + s.edit("red square", |doc, _| { + doc.layers[0].surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(0, 2, 2, 4), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 4, 0], "interpolation": "nearest"})).unwrap(); + assert_eq!(pixel(s, 0, 4, 2), vec![1.0, 0.0, 0.0, 1.0]); +} + +#[test] +fn record_transform_again_replays_one_concrete_transform_at_each_depth() { + for depth in [8, 16, 32] { + let mut s = Session::new(); + translated_square(&mut s, depth); + let from = s.journal.len(); + s.execute("actions.record", json!({"name": "Again"})).unwrap(); + s.execute("edit.transform.again", json!({})).unwrap(); + let ids: Vec<&str> = s.journal.iter().skip(from).map(|(id, _)| id.as_str()).collect(); + assert_eq!(ids, ["edit.transform", "edit.transform.again"], "both commands stay in the journal during recording"); + let live_count = s.journal.iter().skip(from).filter(|(id, _)| replayable(id)).count(); + s.execute("actions.stop", json!({})).unwrap(); + let recorded = s.execute("actions.get", json!({"action": "Again"})).unwrap(); + let steps = recorded["steps"].as_array().unwrap(); + assert_eq!(steps.len(), 1, "depth {depth}: record the concrete transform once"); + assert_eq!(live_count, 1, "depth {depth}: the live Actions count agrees"); + assert_eq!(steps[0][0], "edit.transform"); + assert_eq!(steps[0][1]["matrix"], json!([1, 0, 0, 1, 4, 0])); + assert_eq!(steps[0][1]["interpolation"], "nearest"); + + translated_square(&mut s, depth); + let before = s.active().unwrap().history.past_len(); + let played = s.execute("actions.play", json!({"action": "Again"})).unwrap(); + assert!(played.get("failed").is_none(), "depth {depth}: {played}"); + assert_eq!(played["ran"], 1, "depth {depth}: apply the recorded transform once"); + assert_eq!(s.active().unwrap().history.past_len(), before + 1, "depth {depth}: one undo step"); + assert_eq!(pixel(&s, 0, 8, 2), vec![1.0, 0.0, 0.0, 1.0], "depth {depth}: moved four pixels"); + assert_eq!(pixel(&s, 0, 12, 2), vec![0.0; 4], "depth {depth}: no second transform"); + assert!(s.undo()); + assert_eq!(pixel(&s, 0, 4, 2), vec![1.0, 0.0, 0.0, 1.0]); + assert_eq!(pixel(&s, 0, 8, 2), vec![0.0; 4]); + assert!(s.redo()); + assert_eq!(pixel(&s, 0, 8, 2), vec![1.0, 0.0, 0.0, 1.0]); + assert_eq!(pixel(&s, 0, 4, 2), vec![0.0; 4]); + } +} + +#[test] +fn record_transform_again_on_a_copy_replays_in_a_session_without_a_transform() { + for depth in [8, 16] { + let mut s = Session::new(); + translated_square(&mut s, depth); + s.execute("actions.record", json!({"name": "Step"})).unwrap(); + s.execute("edit.transform.againCopy", json!({})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + let got = s.execute("actions.get", json!({"action": "Step"})).unwrap(); + let ids: Vec<&str> = got["steps"].as_array().unwrap().iter().map(|st| st[0].as_str().unwrap()).collect(); + assert_eq!(ids, ["layer.duplicate", "edit.transform"], "depth {depth}: the concrete steps, not the wrapper"); + let action = s.actions.list[0].clone(); + + // A new session has no transform to repeat: the concrete steps still play. + let mut fresh = Session::new(); + fresh.execute("file.new", json!({"width": 20, "height": 8, "depth": depth, "background": "transparent"})).unwrap(); + fresh + .edit("red square", |doc, _| { + doc.layers[0].surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(4, 2, 6, 4), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + fresh.actions.list.push(action); + let played = fresh.execute("actions.play", json!({"action": "Step"})).unwrap(); + assert!(played.get("failed").is_none(), "depth {depth}: {played}"); + assert_eq!(played["ran"], 2, "depth {depth}"); + assert_eq!(fresh.active().unwrap().doc.layers.len(), 2, "depth {depth}: one copy"); + assert_eq!(pixel(&fresh, 0, 4, 2), vec![1.0, 0.0, 0.0, 1.0], "depth {depth}: the original stays"); + assert_eq!(pixel(&fresh, 1, 8, 2), vec![1.0, 0.0, 0.0, 1.0], "depth {depth}: the copy moved four pixels"); + assert_eq!(pixel(&fresh, 1, 4, 2), vec![0.0; 4], "depth {depth}: moved once"); + } +} + +#[test] +fn record_drops_the_steps_of_a_command_that_failed_and_was_taken_back() { + // Transform Again on a Copy of a position-locked layer duplicates it, fails to move the + // copy and takes the copy back: nothing is left to record. + let mut s = Session::new(); + translated_square(&mut s, 8); + let id = s.active().unwrap().active_layer.unwrap(); + s.execute("layer.setProps", json!({"layer": id.0, "locks": {"position": true}})).unwrap(); + s.execute("actions.record", json!({"name": "Locked"})).unwrap(); + assert!(s.execute("edit.transform.againCopy", json!({})).is_err()); + assert_eq!(s.execute("actions.stop", json!({})).unwrap()["steps"], 0, "no Duplicate step for a copy that was taken back"); + + // Straighten rolls back when its crop is refused after the rotation ran. + ruled_background(&mut s, 8); + s.execute("image.analysis.rulerTool", json!({"start": [10, 30], "end": [70, 25]})).unwrap(); + s.authorize = Some(|id, _| if id == "image.crop" { Err(EngineError::Other("refused".into())) } else { Ok(()) }); + s.execute("actions.record", json!({"name": "Refused"})).unwrap(); + assert!(s.execute("image.analysis.straightenLayer", json!({})).is_err()); + assert_eq!(s.active().unwrap().doc.size.width, 80, "the rotation was taken back"); + assert_eq!(s.execute("actions.stop", json!({})).unwrap()["steps"], 0, "no rotation step for a rotation that was taken back"); +} + +#[test] +fn record_script_that_plays_an_action_keeps_each_step_once() { + let mut s = Session::new(); + translated_square(&mut s, 8); + s.execute("actions.record", json!({"name": "Inner"})).unwrap(); + s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 1, 0], "interpolation": "nearest"})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + + // Browse records the concrete steps it ran, not itself (#3057): the script's transform and + // the action call, each once, in order. + let script = json!({"steps": [["edit.transform", {"matrix": [1, 0, 0, 1, 2, 0], "interpolation": "nearest"}], ["actions.play", {"action": "Inner"}]]}); + s.execute("actions.record", json!({"name": "Outer"})).unwrap(); + s.execute("file.scripts.browse", script.clone()).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + let got = s.execute("actions.get", json!({"action": "Outer"})).unwrap(); + assert_eq!(got["steps"], script["steps"]); +} + +#[test] +fn record_explicit_transform_keeps_one_replayable_step() { + let mut s = Session::new(); + translated_square(&mut s, 8); + s.execute("actions.record", json!({"name": "Move"})).unwrap(); + s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 4, 0], "interpolation": "nearest"})).unwrap(); + assert_eq!(s.execute("actions.stop", json!({})).unwrap()["steps"], 1); + let recorded = s.execute("actions.get", json!({"action": "Move"})).unwrap(); + assert_eq!(recorded["steps"][0][0], "edit.transform"); + + translated_square(&mut s, 8); + let before = s.active().unwrap().history.past_len(); + let played = s.execute("actions.play", json!({"action": "Move"})).unwrap(); + assert!(played.get("failed").is_none(), "{played}"); + assert_eq!(played["ran"], 1); + assert_eq!(s.active().unwrap().history.past_len(), before + 1); + assert_eq!(pixel(&s, 0, 8, 2), vec![1.0, 0.0, 0.0, 1.0]); + assert_eq!(pixel(&s, 0, 12, 2), vec![0.0; 4]); +} + +/// A Background with a red bar and a slanted ruler line, ready for Straighten. +fn ruled_background(s: &mut Session, depth: u32) { + s.execute("file.new", json!({"width": 80, "height": 60, "depth": depth})).unwrap(); + s.edit("red bar", |doc, _| { + doc.layers[0].surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(10, 20, 60, 8), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); +} + +#[test] +fn record_command_that_runs_commands_replays_it_once() { + // Straighten Layer runs Image Rotation and Crop itself: only its own call is recorded, + // so playback rotates once, not three times (rotate, crop, then straighten again). + for depth in [8, 16] { + let mut s = Session::new(); + ruled_background(&mut s, depth); + s.execute("actions.record", json!({"name": "Level"})).unwrap(); + s.execute("image.analysis.rulerTool", json!({"start": [10, 30], "end": [70, 25]})).unwrap(); + s.execute("image.analysis.straightenLayer", json!({})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + let got = s.execute("actions.get", json!({"action": "Level"})).unwrap(); + let ids: Vec<&str> = got["steps"].as_array().unwrap().iter().map(|st| st[0].as_str().unwrap()).collect(); + assert_eq!(ids, ["image.analysis.rulerTool", "image.analysis.straightenLayer"], "depth {depth}"); + let direct = s.active().unwrap().doc.clone(); + + ruled_background(&mut s, depth); + let before = s.active().unwrap().history.past_len(); + let played = s.execute("actions.play", json!({"action": "Level"})).unwrap(); + assert!(played.get("failed").is_none(), "depth {depth}: {played}"); + assert_eq!(played["ran"], 2, "depth {depth}"); + assert_eq!(s.active().unwrap().history.past_len(), before + 1, "depth {depth}: one Straighten step (the ruler is no step)"); + let replayed = s.active().unwrap().doc.clone(); + assert_eq!(replayed.size, direct.size, "depth {depth}: rotated and cropped once"); + let r = photocraft_geom::Rect::new(0, 0, direct.size.width as i32, direct.size.height as i32); + let px = |d: &photocraft_doc::Document| d.layers[0].surface().unwrap().read_region(r); + assert_eq!(px(&replayed), px(&direct), "depth {depth}: same pixels as the direct run"); + } +} + +#[test] +fn record_keeps_only_replayable_steps() { + let mut s = Session::new(); + record_red(&mut s, 8); + let got = s.execute("actions.get", json!({"action": "Red"})).unwrap(); + let ids: Vec<&str> = got["steps"].as_array().unwrap().iter().map(|st| st[0].as_str().unwrap()).collect(); + assert_eq!(ids, ["layer.new.layer", "select.rect", "edit.fill"]); + assert!(s.journal.iter().all(|(id, _)| !id.starts_with("actions."))); + let listed = s.execute("actions.list", json!({})).unwrap(); + assert_eq!(listed["actions"][0]["steps"], 3); + assert!(listed["recording"].is_null()); +} + +#[test] +fn play_on_another_document_matches_pixels_at_each_depth() { + for depth in [8, 16, 32] { + let mut s = Session::new(); + record_red(&mut s, depth); + s.execute("file.new", json!({"width": 40, "height": 40, "depth": depth})).unwrap(); + let before = s.active().unwrap().history.past_len(); + let r = s.execute("actions.play", json!({"action": 0})).unwrap(); + assert!(r.get("failed").is_none(), "depth {depth}: {r}"); + assert_eq!(r["ran"], 3, "depth {depth}"); + assert_eq!(s.active().unwrap().doc.layers.len(), 2, "depth {depth}"); + assert_eq!(s.active().unwrap().history.past_len(), before + 3, "depth {depth}: one history step per played step"); + let px = pixel(&s, 1, 5, 5); + assert!(px.iter().zip([1.0, 0.0, 0.0, 1.0]).all(|(a, b)| (a - b).abs() < 1.0e-5), "depth {depth}: {px:?}"); + assert_eq!(s.actions.playing, 0); + } +} + +#[test] +fn recorded_layer_selection_replays_by_name_on_another_document() { + for depth in [8, 16, 32] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8, "depth": depth})).unwrap(); + let original = s.active().unwrap().active_layer.unwrap(); + s.execute("layer.setProps", json!({"name": "Photo"})).unwrap(); + s.execute("layer.new.layer", json!({"name": "LogoBase"})).unwrap(); + s.execute("actions.record", json!({"name": "Duplicate photo"})).unwrap(); + s.execute("layer.select", json!({"layer": original.0, "mode": "replace"})).unwrap(); + // The target name must be captured now, not when recording stops. + s.execute("layer.setProps", json!({"name": "Retouched"})).unwrap(); + s.execute("layer.duplicate", json!({})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + assert_eq!(s.actions.list[0].steps[0].1, json!({"name":"Photo", "mode":"replace"})); + // Persisted actions must work in an entirely different session too. + let saved = serde_json::to_string(&s.actions.list).unwrap(); + let mut replay = Session::new(); + replay.actions.list = serde_json::from_str(&saved).unwrap(); + replay.execute("file.new", json!({"width": 8, "height": 8, "depth": depth})).unwrap(); + replay.execute("layer.setProps", json!({"name": "Photo"})).unwrap(); + let target = replay.active().unwrap().active_layer.unwrap(); + assert_ne!(original, target); + replay.execute("layer.new.layer", json!({"name": "LogoBase"})).unwrap(); + let result = replay.execute("actions.play", json!({"action": 0})).unwrap(); + assert!(result.get("failed").is_none(), "{result}"); + assert_eq!(result["ran"], 3); + assert_eq!(replay.active().unwrap().doc.layer(target).unwrap().name, "Retouched"); + let active = replay.active().unwrap().active_layer.unwrap(); + assert_eq!(replay.active().unwrap().doc.layer(active).unwrap().name, "Retouched copy"); + } +} + +/// #7845: dragging a layer in the Layers panel while recording keeps the drop target by name, +/// so the action plays on another document (whose layer ids differ) instead of failing with +/// "no such layer". The reporter's steps, replayed on a new document. +#[test] +fn recorded_layer_drag_replays_on_another_document() { + for depth in [8, 16, 32] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16, "depth": depth})).unwrap(); + s.execute("actions.record", json!({"name": "Retouch"})).unwrap(); + s.execute("layer.stampVisible", json!({})).unwrap(); + let layer1 = s.active().unwrap().active_layer.unwrap(); + s.execute("layer.new.layerViaCopy", json!({})).unwrap(); + let layer2 = s.active().unwrap().active_layer.unwrap(); + s.execute("layer.select", json!({"layer": layer1.0, "mode": "replace"})).unwrap(); + s.execute("filter.noise.median", json!({"radius": 6})).unwrap(); + s.execute("layer.new.layerViaCopy", json!({})).unwrap(); + let copy = s.active().unwrap().active_layer.unwrap(); + s.execute("layer.moveTo", json!({"layer": copy.0, "target": layer2.0, "position": "above"})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + let (id, step) = s.actions.list[0].steps.last().unwrap(); + assert_eq!((id.as_str(), step), ("layer.moveTo", &json!({"target": "Layer 1 copy", "position": "above"}))); + let names = |s: &Session| s.active().unwrap().doc.layers.iter().rev().map(|l| l.name.clone()).collect::>(); + let recorded = names(&s); + let saved = serde_json::to_string(&s.actions.list).unwrap(); + let mut replay = Session::new(); + replay.actions.list = serde_json::from_str(&saved).unwrap(); + replay.execute("file.new", json!({"width": 16, "height": 16, "depth": depth})).unwrap(); + let result = replay.execute("actions.play", json!({"action": 0})).unwrap(); + assert!(result.get("failed").is_none(), "{depth}: {result}"); + assert_eq!(names(&replay), recorded, "{depth}: the same stack"); + } + // Several layers of the drop target's name: the recorded occurrence picks the right one. + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Twin"})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Twin"})).unwrap(); + let upper = s.active().unwrap().active_layer.unwrap(); + s.execute("layer.new.layer", json!({"name": "Mover"})).unwrap(); + let mover = s.active().unwrap().active_layer.unwrap(); + s.execute("actions.record", json!({"name": "Drop"})).unwrap(); + s.execute("layer.moveTo", json!({"layer": mover.0, "target": upper.0, "position": "below"})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + assert_eq!(s.actions.list[0].steps[0].1, json!({"target": "Twin", "targetOccurrence": 1, "position": "below"})); + // The moved layer shares the target's name: the occurrence counts the other "Twin"s only, + // so it means the same layer before the move (on replay) as after it (when recorded). + let build = |s: &mut Session| { + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + for _ in 0..3 { + s.execute("layer.new.layer", json!({"name": "Twin"})).unwrap(); + } + s.active().unwrap().doc.layers.iter().map(|l| l.id).collect::>() + }; + let mut s = Session::new(); + let ids = build(&mut s); + let (lowest, top) = (ids[1], ids[3]); + s.execute("actions.record", json!({"name": "Twins"})).unwrap(); + s.execute("layer.moveTo", json!({"layer": top.0, "target": lowest.0, "position": "below"})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + assert_eq!(s.actions.list[0].steps[0].1, json!({"target": "Twin", "targetOccurrence": 0, "position": "below"})); + let order = |s: &Session| s.active().unwrap().doc.layers.iter().map(|l| l.id).collect::>(); + let want: Vec<_> = order(&s).iter().map(|id| ids.iter().position(|x| x == id).unwrap()).collect(); + let saved = serde_json::to_string(&s.actions.list).unwrap(); + let mut replay = Session::new(); + replay.actions.list = serde_json::from_str(&saved).unwrap(); + let ids2 = build(&mut replay); + let result = replay.execute("actions.play", json!({"action": 0})).unwrap(); + assert!(result.get("failed").is_none(), "{result}"); + let got: Vec<_> = order(&replay).iter().map(|id| ids2.iter().position(|x| x == id).unwrap()).collect(); + assert_eq!(got, want, "the same layer became the lowest"); + // A moved group holding a same-named layer: its contents don't count either, or moving the + // group past another "Twin" would shift the occurrence between recording and replay. + let build_group = |s: &mut Session| { + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Twin"})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Twin"})).unwrap(); + s.execute("layer.groupLayers", json!({})).unwrap(); + let group = s.active().unwrap().active_layer.unwrap(); + s.execute("layer.new.layer", json!({"name": "Twin"})).unwrap(); + let top = s.active().unwrap().active_layer.unwrap(); + s.execute("layer.select", json!({"layer": group.0, "mode": "replace"})).unwrap(); + (group, top) + }; + let mut g = Session::new(); + let (group, top) = build_group(&mut g); + g.execute("actions.record", json!({"name": "Group"})).unwrap(); + g.execute("layer.moveTo", json!({"layer": group.0, "target": top.0, "position": "above"})).unwrap(); + g.execute("actions.stop", json!({})).unwrap(); + let recorded = g.actions.list[0].steps[0].1.clone(); + let saved = serde_json::to_string(&g.actions.list).unwrap(); + let mut replay = Session::new(); + replay.actions.list = serde_json::from_str(&saved).unwrap(); + let (group2, _) = build_group(&mut replay); + let result = replay.execute("actions.play", json!({"action": 0})).unwrap(); + assert!(result.get("failed").is_none(), "{recorded}: {result}"); + let top_layer = |s: &Session| s.active().unwrap().doc.layers.last().map(|l| l.id); + assert_eq!(top_layer(&replay), Some(group2), "{recorded}: the group went to the top"); + // Several moved layers named like the target are left out too, so the name is unambiguous. + let mut m = Session::new(); + m.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + let a = photocraft_doc::LayerId(m.execute("layer.new.layer", json!({"name": "Twin"})).unwrap()["layer"].as_u64().unwrap()); + let b = photocraft_doc::LayerId(m.execute("layer.new.layer", json!({"name": "Twin"})).unwrap()["layer"].as_u64().unwrap()); + let target = photocraft_doc::LayerId(m.execute("layer.new.layer", json!({"name": "Twin"})).unwrap()["layer"].as_u64().unwrap()); + m.execute("layer.moveTo", json!({"layers": [a.0, b.0], "target": "Twin", "position": "above"})).unwrap(); + assert_eq!(m.active().unwrap().doc.layers.last().map(|l| l.id), Some(b), "both moved above the third Twin"); + assert_eq!(m.active().unwrap().doc.layers.iter().rev().nth(2).map(|l| l.id), Some(target)); + // An ⌥-drag copy of the selected layer beside itself replays by name too. + let mut c = Session::new(); + c.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + let src = photocraft_doc::LayerId(c.execute("layer.new.layer", json!({"name": "Solo"})).unwrap()["layer"].as_u64().unwrap()); + c.execute("actions.record", json!({"name": "Copy"})).unwrap(); + c.execute("layer.moveTo", json!({"layer": src.0, "target": src.0, "position": "above", "copy": true})).unwrap(); + c.execute("actions.stop", json!({})).unwrap(); + assert_eq!(c.actions.list[0].steps[0].1, json!({"target": "Solo", "position": "above", "copy": true})); + let saved = serde_json::to_string(&c.actions.list).unwrap(); + let mut replay = Session::new(); + replay.actions.list = serde_json::from_str(&saved).unwrap(); + replay.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + replay.execute("layer.new.layer", json!({"name": "Solo"})).unwrap(); + let before = replay.active().unwrap().doc.layers.len(); + let result = replay.execute("actions.play", json!({"action": 0})).unwrap(); + assert!(result.get("failed").is_none(), "{result}"); + assert_eq!(replay.active().unwrap().doc.layers.len(), before + 1, "one copy"); + // Copying a group holding a layer named like the target: the new copy's contents (made + // before the step is recorded) don't count, so the occurrence matches the replay. + let build_copy = |s: &mut Session| { + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Twin"})).unwrap(); + s.execute("layer.groupLayers", json!({})).unwrap(); + let group = s.active().unwrap().active_layer.unwrap(); + let a = photocraft_doc::LayerId(s.execute("layer.new.layer", json!({"name": "Twin"})).unwrap()["layer"].as_u64().unwrap()); + let b = photocraft_doc::LayerId(s.execute("layer.new.layer", json!({"name": "Twin"})).unwrap()["layer"].as_u64().unwrap()); + s.execute("layer.select", json!({"layer": group.0, "mode": "replace"})).unwrap(); + (group, a, b) + }; + let mut gc = Session::new(); + let (group, a, _) = build_copy(&mut gc); + gc.execute("actions.record", json!({"name": "Copy group"})).unwrap(); + // Below `a`: the copy's "Twin" then comes before `a` in document order. + gc.execute("layer.moveTo", json!({"layer": group.0, "target": a.0, "position": "below", "copy": true})).unwrap(); + gc.execute("actions.stop", json!({})).unwrap(); + let saved = serde_json::to_string(&gc.actions.list).unwrap(); + let mut replay = Session::new(); + replay.actions.list = serde_json::from_str(&saved).unwrap(); + let (_, a2, _) = build_copy(&mut replay); + let result = replay.execute("actions.play", json!({"action": 0})).unwrap(); + assert!(result.get("failed").is_none(), "{result}"); + let layers = &replay.active().unwrap().doc.layers; + let at = layers.iter().position(|l| l.id == a2).unwrap(); + let below = at.checked_sub(1).and_then(|i| layers.get(i)).map(|l| l.name.as_str()); + assert_eq!(below, Some("Group 1 copy"), "the copy landed below the same Twin"); + // A drag of several layers keeps its ids (not covered by name). + s.execute("actions.record", json!({"name": "Several"})).unwrap(); + s.execute("layer.moveTo", json!({"layers": [ids[2].0, ids[3].0], "target": ids[1].0, "position": "above"})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + assert_eq!(s.actions.list[1].steps[0].1["target"], json!(ids[1].0)); + // Bad targets are errors, not panics. + for bad in [ + json!({"target": "Nobody"}), + json!({"target": "Twin"}), + json!({"target": "Twin", "targetOccurrence": 9}), + json!({"target": "Twin", "targetOccurrence": -1}), + json!({"target": true}), + ] { + assert!(s.execute("layer.moveTo", bad.clone()).is_err(), "{bad}"); + } +} + +/// An Alt-drag copy records `inPlace` (#7200), which only matters for an artboard: a plain +/// layer's recorded copy must still export to .atn, while an artboard's must be refused rather +/// than exported as a copy beside the original. +#[test] +fn recorded_in_place_duplicate_keeps_in_place_only_for_artboards() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + s.execute("actions.record", json!({"name": "Layer copy"})).unwrap(); + s.execute("layer.duplicate", json!({"inPlace": true})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + s.execute("layer.new.artboard", json!({"name": "Board", "rect": [0, 0, 8, 8]})).unwrap(); + s.execute("actions.record", json!({"name": "Board copy"})).unwrap(); + s.execute("layer.duplicate", json!({"inPlace": true})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + assert_eq!(s.actions.list[0].steps, vec![("layer.duplicate".to_string(), json!({}))]); + assert_eq!(s.actions.list[1].steps, vec![("layer.duplicate".to_string(), json!({"inPlace": true}))]); + assert!(crate::atn_cmds::export("Audit", &[&s.actions.list[0]], &[], false).is_ok()); + assert!(crate::atn_cmds::export("Audit", &[&s.actions.list[1]], &[], false).is_err()); + // Several selected layers are copied together: one artboard among them keeps `inPlace`. + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + let photo = s.active().unwrap().active_layer.unwrap(); + s.execute("layer.new.layer", json!({"name": "Logo"})).unwrap(); + s.execute("layer.select", json!({"layer": photo.0, "mode": "add"})).unwrap(); + s.execute("actions.record", json!({"name": "Layers copy"})).unwrap(); + s.execute("layer.duplicate", json!({"inPlace": true})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + assert_eq!(s.active().unwrap().selected_layers().len(), 2, "both layers were copied"); + s.execute("layer.new.artboard", json!({"name": "Board", "rect": [0, 0, 8, 8]})).unwrap(); + s.execute("layer.select", json!({"layer": photo.0, "mode": "add"})).unwrap(); + s.execute("actions.record", json!({"name": "Mixed copy"})).unwrap(); + s.execute("layer.duplicate", json!({"inPlace": true})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + assert_eq!(s.actions.list[0].steps, vec![("layer.duplicate".to_string(), json!({}))]); + assert_eq!(s.actions.list[1].steps, vec![("layer.duplicate".to_string(), json!({"inPlace": true}))]); +} + +#[test] +fn named_selection_preserves_modes_and_duplicate_occurrences() { + let mut s = Session::new(); + s.execute("file.new", json!({"width":4,"height":4})).unwrap(); + s.execute("layer.setProps", json!({"name":"Photo"})).unwrap(); + let first = s.active().unwrap().active_layer.unwrap(); + s.execute("layer.new.group", json!({"name":"Group"})).unwrap(); + // A duplicate nested in a group must be found even when that group is collapsed. + let second = s + .edit("child", |doc, active| { + let child = photocraft_doc::Layer::raster("Photo", doc.pixel_format()); + let id = child.id; + if let photocraft_doc::LayerContent::Group(group) = &mut doc.layer_mut(active.unwrap()).unwrap().content { + group.children.push(child); + group.expanded = false; + } + Ok(id) + }) + .unwrap(); + s.execute("actions.record", json!({"name":"Select duplicates"})).unwrap(); + s.execute("layer.select", json!({"layer":first.0})).unwrap(); + s.execute("layer.select", json!({"layer":second.0,"mode":"add"})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + assert_eq!(s.actions.list[0].steps[0].1, json!({"name":"Photo","occurrence":0})); + assert_eq!(s.actions.list[0].steps[1].1, json!({"name":"Photo","occurrence":1,"mode":"add"})); + s.execute("layer.select", json!({"layer":first.0})).unwrap(); + let r = s.execute("actions.play", json!({"action":0})).unwrap(); + assert!(r.get("failed").is_none(), "{r}"); + assert_eq!(s.active().unwrap().selected_layers(), vec![first, second]); + s.execute("layer.select", json!({"name":"Photo","occurrence":1,"mode":"toggle"})).unwrap(); + assert_eq!(s.active().unwrap().selected_layers(), vec![first]); + s.execute("layer.select", json!({"name":"Photo","occurrence":1,"mode":"range"})).unwrap(); + assert!(s.active().unwrap().selected_layers().contains(&second)); + // Main's imported .atn steps use a string-valued `layer` and choose the topmost match. + s.execute("layer.select", json!({"layer":"Photo"})).unwrap(); + assert_eq!(s.active().unwrap().selected_layers(), vec![second]); + s.execute("layer.select", json!({"name":"Photo","occurrence":0,"mode":"add"})).unwrap(); + s.execute("layer.select", json!({"name":"Photo","occurrence":1,"mode":"remove"})).unwrap(); + assert_eq!(s.active().unwrap().selected_layers(), vec![first]); + // Removing an unselected layer does not add it; removing the last target keeps it. + s.execute("layer.select", json!({"layer":"Photo","mode":"remove"})).unwrap(); + s.execute("layer.select", json!({"name":"Photo","occurrence":0,"mode":"remove"})).unwrap(); + assert_eq!(s.active().unwrap().selected_layers(), vec![first]); + for p in [ + json!({"name":"absent"}), + json!({"name":"Photo"}), + json!({"name":1}), + json!({"name":"Photo","occurrence":-1}), + json!({"name":"Photo","occurrence":1.5}), + json!({"name":"Photo","occurrence":99}), + json!({"name":"Photo","layer":first.0}), + json!({"layer":first.0,"occurrence":0}), + ] { + let before = s.active().unwrap().selected_layers(); + assert!(s.execute("layer.select", p.clone()).is_err(), "{p}"); + assert_eq!(s.active().unwrap().selected_layers(), before); + } + s.actions.list.push(Action { + name: "Missing".into(), + steps: vec![("layer.select".into(), json!({"name":"absent"})), ("layer.duplicate".into(), json!({}))], + disabled: Default::default(), + ..Default::default() + }); + let before = s.active().unwrap().doc.walk().len(); + let result = s.execute("actions.play", json!({"action":"Missing"})).unwrap(); + assert_eq!(result["ran"], 0); + assert!(result["failed"]["error"].as_str().unwrap().contains("absent")); + assert_eq!(s.active().unwrap().doc.walk().len(), before); +} + +#[test] +fn play_stops_at_the_failing_step_and_reports_it() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16})).unwrap(); + s.execute("actions.record", json!({})).unwrap(); + s.execute("layer.new.layer", json!({"name": "One"})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + s.actions.list[0].steps.push(("not.a.command".into(), json!({}))); + s.execute("file.new", json!({"width": 16, "height": 16})).unwrap(); + let r = s.execute("actions.play", json!({"action": "Action 1"})).unwrap(); + assert_eq!(r["ran"], 1); + assert_eq!(r["failed"]["step"], 1); + assert_eq!(r["failed"]["id"], "not.a.command"); + assert!(r["failed"]["error"].as_str().unwrap().contains("unknown command")); + assert_eq!(s.active().unwrap().doc.layers.len(), 2, "the step before the failure is kept"); + assert_eq!(s.actions.playing, 0); + // A later play still runs. + assert_eq!(s.execute("actions.play", json!({"action": 0, "from": 1})).unwrap()["ran"], 0); +} + +#[test] +fn play_refuses_recursion() { + let mut s = Session::new(); + s.actions.list.push(Action { + name: "Loop".into(), + steps: vec![("actions.play".into(), json!({"action": "Loop"}))], + disabled: Default::default(), + ..Default::default() + }); + let r = s.execute("actions.play", json!({"action": "Loop"})).unwrap(); + assert_eq!(r["ran"], 0); + assert_eq!(r["failed"]["id"], "actions.play"); + assert!(r["failed"]["error"].as_str().unwrap().contains("recursive action"), "{r}"); + assert_eq!(s.actions.playing, 0); +} + +#[test] +fn play_checks_each_step_with_the_authorize_hook() { + fn deny_file(id: &str, _: &Value) -> Result<()> { + if id.starts_with("file.") { Err(EngineError::Other(format!("automation command `{id}` is disabled"))) } else { Ok(()) } + } + let mut s = Session::new(); + s.authorize = Some(deny_file); + s.actions.list.push(Action { + name: "Open".into(), + steps: vec![("file.open".into(), json!({"path": "/etc/passwd"})), ("layer.new.layer".into(), json!({}))], + disabled: Default::default(), + ..Default::default() + }); + let r = s.execute("actions.play", json!({"action": "Open"})).unwrap(); + assert_eq!(r["ran"], 0); + assert_eq!(r["failed"]["step"], 0); + assert_eq!(r["failed"]["id"], "file.open"); + assert!(r["failed"]["error"].as_str().unwrap().contains("disabled"), "{r}"); + assert!(s.documents().is_empty(), "the refused step does not open a document"); +} + +#[test] +fn append_delete_and_from_step() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap(); + let started = s.execute("actions.record", json!({"name": "Grow"})).unwrap(); + assert_eq!(started["index"], 0); + s.execute("layer.new.layer", json!({"name": "One"})).unwrap(); + assert!(s.execute("actions.record", json!({})).is_err(), "already recording"); + assert!(s.execute("actions.delete", json!({"action": 0})).is_err(), "delete while recording"); + let stopped = s.execute("actions.stop", json!({})).unwrap(); + assert_eq!(stopped["steps"], 1); + s.execute("actions.record", json!({"action": "Grow"})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Two"})).unwrap(); + assert_eq!(s.execute("actions.stop", json!({})).unwrap()["steps"], 2); + assert!(s.execute("actions.stop", json!({})).is_err(), "not recording"); + let before = s.active().unwrap().doc.layers.len(); + let r = s.execute("actions.play", json!({"action": "Grow", "from": 1})).unwrap(); + assert_eq!(r["ran"], 1); + assert_eq!(s.active().unwrap().doc.layers.len(), before + 1); + assert_eq!(s.execute("actions.delete", json!({"action": "Grow"})).unwrap()["deleted"], "Grow"); + assert!(s.actions.list.is_empty()); + assert!(s.execute("actions.get", json!({"action": "Grow"})).is_err()); +} + +#[test] +fn delete_one_step_while_recording_keeps_journal_and_remaining_steps() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + s.execute("actions.record", json!({"name": "Edit"})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Kept"})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Removed"})).unwrap(); + let journal = s.journal.clone(); + let rev = s.actions.rev; + let before = s.actions.clone(); + for step in [json!(-1), json!(2), json!(0.5), json!(null), json!("0"), json!(u64::MAX)] { + assert!(s.execute("actions.delete", json!({"action": 0, "step": step})).is_err()); + assert_eq!(s.actions, before, "invalid deletion is atomic"); + } + assert_eq!(pending_steps(&s, 0).count(), 2); + let result = s.execute("actions.delete", json!({"action": 0, "step": 1})).unwrap(); + assert_eq!(result["steps"], 1); + assert_eq!(s.journal, journal, "deleting a recording does not erase executed commands"); + assert_eq!(s.active().unwrap().doc.layers.len(), 3, "it does not undo document edits"); + assert!(s.actions.recording.is_some()); + assert!(s.actions.rev > rev); + s.execute("layer.new.layer", json!({"name": "After"})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + assert_eq!(s.actions.list[0].steps.iter().map(|(_, p)| p["name"].as_str().unwrap()).collect::>(), ["Kept", "After"]); + s.execute("actions.delete", json!({"action": "Edit", "step": 0})).unwrap(); + assert_eq!(s.actions.list[0].steps[0].1["name"], "After"); + let saved = serde_json::to_string(&s.actions.list).unwrap(); + s.actions.list = serde_json::from_str(&saved).unwrap(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + assert_eq!(s.execute("actions.play", json!({"action": 0})).unwrap()["ran"], 1); + assert_eq!(s.active().unwrap().doc.layers[1].name, "After"); + s.execute("actions.delete", json!({"action": 0, "step": 0})).unwrap(); + assert_eq!(s.actions.list.len(), 1, "an empty action still exists"); + assert!(s.actions.list[0].steps.is_empty()); +} + +#[test] +fn nested_call_records_one_named_step_and_tracks_child_edits() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 4, "height": 4})).unwrap(); + s.actions.list.push(Action { + name: "Child".into(), + steps: vec![("layer.new.layer".into(), json!({"name": "Child layer"}))], + disabled: Default::default(), + ..Default::default() + }); + s.execute("actions.record", json!({"name": "Parent"})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Before"})).unwrap(); + s.execute("actions.play", json!({"action": 0})).unwrap(); + assert_eq!(pending_steps(&s, 1).cloned().collect::>(), [("actions.play".into(), json!({"action": "Child"}))]); + s.execute("layer.new.layer", json!({"name": "After"})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + assert_eq!(s.actions.list[1].steps.iter().map(|st| st.0.as_str()).collect::>(), ["layer.new.layer", "actions.play", "layer.new.layer"]); + s.actions.list[0].steps.push(("layer.new.layer".into(), json!({"name": "Added later"}))); + s.execute("actions.move", json!({"action": "Child", "to": 1})).unwrap(); + let saved = serde_json::to_string(&s.actions.list).unwrap(); + s.actions.list = serde_json::from_str(&saved).unwrap(); + s.execute("file.new", json!({"width": 4, "height": 4})).unwrap(); + let result = s.execute("actions.play", json!({"action": "Parent"})).unwrap(); + assert!(result.get("failed").is_none(), "{result}"); + assert_eq!(s.active().unwrap().doc.layers.iter().skip(1).map(|l| l.name.as_str()).collect::>(), ["Before", "Child layer", "Added later", "After"]); + assert!(s.actions.playback_stack.is_empty()); +} + +#[test] +fn nested_failure_cycles_depth_and_authorization_stop_parent() { + let mut s = Session::new(); + s.actions.list.push(Action { + name: "A".into(), + steps: vec![("actions.play".into(), json!({"action": "B"})), ("file.new".into(), json!({"width": 2,"height": 2}))], + disabled: Default::default(), + ..Default::default() + }); + s.actions.list.push(Action { + name: "B".into(), + steps: vec![("actions.play".into(), json!({"action": "A"}))], + disabled: Default::default(), + ..Default::default() + }); + let r = s.execute("actions.play", json!({"action": "A"})).unwrap(); + assert!(r["failed"]["error"].as_str().unwrap().contains("recursive")); + assert!(s.documents().is_empty()); + s.actions.list[1].steps = vec![("file.new".into(), json!({"width": 2,"height": 2}))]; + s.authorize = Some(|id, _| if id == "file.new" { Err(EngineError::Other("denied nested file".into())) } else { Ok(()) }); + let r = s.execute("actions.play", json!({"action": "A"})).unwrap(); + assert!(r["failed"]["error"].as_str().unwrap().contains("denied nested file")); + assert!(s.documents().is_empty()); + s.authorize = None; + s.actions.list.clear(); + for i in 0..17 { + s.actions.list.push(Action { + name: format!("N{i}"), + steps: if i < 16 { vec![("actions.play".into(), json!({"action":format!("N{}", i + 1)}))] } else { vec![] }, + disabled: Default::default(), + ..Default::default() + }); + } + let r = s.execute("actions.play", json!({"action": "N0"})).unwrap(); + assert!(r["failed"]["error"].as_str().unwrap().contains("16 levels")); + assert_eq!(s.actions.playing, 0); + assert!(s.actions.playback_stack.is_empty()); + s.actions.list[15].steps.clear(); + assert!(s.execute("actions.play", json!({"action": "N0"})).unwrap().get("failed").is_none()); +} + +#[test] +fn move_pending_steps_is_atomic_persists_and_changes_playback_order() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 4, "height": 4})).unwrap(); + s.execute("actions.record", json!({"name": "Order"})).unwrap(); + for name in ["One", "Two", "Three"] { + s.execute("layer.new.layer", json!({"name": name})).unwrap(); + } + let before = s.actions.clone(); + for params in [ + json!({"action":0,"step":0,"to":3}), + json!({"action":0,"step":99,"to":0}), + json!({"action":0,"step":0.5,"to":0}), + json!({"action":0,"to":-1}), + json!({"action":0,"to":null}), + ] { + assert!(s.execute("actions.move", params).is_err()); + assert_eq!(s.actions, before); + } + let journal = s.journal.clone(); + s.execute("actions.move", json!({"action":0,"step":0,"to":2})).unwrap(); + s.execute("actions.move", json!({"action":0,"step":1,"to":0})).unwrap(); + assert_eq!(s.journal, journal); + s.execute("layer.new.layer", json!({"name":"Four"})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + assert_eq!(s.actions.list[0].steps.iter().map(|st| st.1["name"].as_str().unwrap()).collect::>(), ["Three", "Two", "One", "Four"]); + s.execute("file.new", json!({"width":4,"height":4})).unwrap(); + s.execute("actions.play", json!({"action":0})).unwrap(); + assert_eq!(s.active().unwrap().doc.layers.iter().skip(1).map(|l| l.name.as_str()).collect::>(), ["Three", "Two", "One", "Four"]); +} + +#[test] +fn new_names_do_not_collide_with_named_calls() { + let mut s = Session::new(); + s.actions.list.push(Action { name: "Action 2".into(), steps: vec![], disabled: Default::default(), ..Default::default() }); + assert_eq!(s.execute("actions.record", json!({})).unwrap()["action"], "Action 3"); + s.execute("actions.stop", json!({})).unwrap(); + assert!(s.execute("actions.record", json!({"name":"Action 2"})).is_err()); + assert!(s.actions.recording.is_none()); +} + +#[test] +fn moving_action_keeps_recording_attached_to_it() { + let mut s = Session::new(); + s.execute("file.new", json!({"width":4,"height":4})).unwrap(); + for name in ["A", "B", "C"] { + s.actions.list.push(Action { name: name.into(), steps: vec![], disabled: Default::default(), ..Default::default() }); + } + s.execute("actions.record", json!({"action":"B"})).unwrap(); + s.execute("layer.new.layer", json!({"name":"before"})).unwrap(); + s.execute("actions.move", json!({"action":"B","to":2})).unwrap(); + s.execute("actions.move", json!({"action":"A","to":2})).unwrap(); + s.execute("layer.new.layer", json!({"name":"after"})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + assert_eq!(s.actions.list[1].name, "B"); + assert_eq!(s.actions.list[1].steps.len(), 2); +} + +#[test] +fn bad_params_do_not_panic() { + let mut s = Session::new(); + let junk = [ + Value::Null, + json!([]), + json!("x"), + json!(1), + json!({"action": true}), + json!({"action": -1}), + json!({"action": 99}), + json!({"action": ""}), + json!({"name": 1}), + json!({"name": ""}), + json!({"from": "start"}), + json!({"from": -3}), + json!({"action": "missing", "from": 4}), + ]; + for id in ["actions.list", "actions.get", "actions.record", "actions.stop", "actions.play", "actions.delete", "actions.move"] { + for p in &junk { + let _ = s.execute(id, p.clone()); + } + } + assert_eq!(s.actions.playing, 0); + assert!(crate::commands::command_specs().iter().any(|c| c.id == "actions.play" && !c.journal && c.menu.is_empty())); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn actions_persist_with_the_preset_store() { + let dir = std::env::temp_dir().join(format!("pc-actions-{}-persist", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut s = Session::new(); + let warnings = s.attach_preset_store(crate::preset_store::open_dir(&dir)); + assert!(warnings.iter().all(|w| !w.contains("actions")), "{warnings:?}"); + s.execute("file.new", json!({"width": 4, "height": 4})).unwrap(); + s.execute("actions.record", json!({"name": "Kept"})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + drop(s); + + let mut t = Session::new(); + t.attach_preset_store(crate::preset_store::open_dir(&dir)); + let listed = t.execute("actions.list", json!({})).unwrap(); + assert_eq!(listed["actions"][0]["name"], "Kept"); + assert_eq!(listed["actions"][0]["steps"], 1); + assert_eq!(t.execute("actions.get", json!({"action": "Kept"})).unwrap()["steps"][0][0], "layer.new.layer"); + + // An action created before the store finishes loading is kept, and a different one on + // disk is merged in. + let mut early = Session::new(); + early.execute("actions.record", json!({"name": "Early"})).unwrap(); + early.execute("actions.stop", json!({})).unwrap(); + early.attach_preset_store(crate::preset_store::open_dir(&dir)); + let names: Vec = early.actions.list.iter().map(|a| a.name.clone()).collect(); + assert!(names.contains(&"Early".into()) && names.contains(&"Kept".into()), "{names:?}"); + + std::fs::write(dir.join("actions.json"), b"{").unwrap(); + let mut bad = Session::new(); + let warnings = bad.attach_preset_store(crate::preset_store::open_dir(&dir)); + assert!(warnings.iter().any(|w| w.contains("actions")), "{warnings:?}"); + assert!(bad.actions.list.is_empty()); + let _ = std::fs::remove_dir_all(&dir); +} + +/// AUTO-219-4: a recording made on one document replays on a second one — a crop, a filter, +/// a selection fill and styled text all act on the document the replay runs in. +#[test] +fn a_recorded_edit_run_replays_on_a_second_document() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 64, "height": 64, "background": "white"})).unwrap(); + s.execute("actions.record", json!({"name": "Studio"})).unwrap(); + s.execute("image.crop", json!({"x": 8, "y": 8, "width": 48, "height": 48})).unwrap(); + s.execute("filter.blur.gaussianBlur", json!({"radius": 2})).unwrap(); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 12, "height": 12})).unwrap(); + s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s.execute("type.create", json!({"x": 10, "y": 36, "text": "Hi", "size": 12, "color": "#000000"})).unwrap(); + s.execute("type.setStyle", json!({"fauxBold": true})).unwrap(); + let stopped = s.execute("actions.stop", json!({})).unwrap(); + let steps = stopped["steps"].as_u64().unwrap(); + assert!(steps >= 7, "the recording keeps every family: {stopped}"); + + // The second document: a different size, background and name. The replay must act here. + s.execute("file.new", json!({"width": 100, "height": 80, "background": "black", "name": "Second"})).unwrap(); + let played = s.execute("actions.play", json!({"action": "Studio"})).unwrap(); + assert!(played.get("failed").is_none(), "replay: {played}"); + assert_eq!(played["ran"].as_u64(), Some(steps), "every step ran: {played}"); + let d = &s.active().unwrap().doc; + assert_eq!((d.size.width, d.size.height), (48, 48), "the crop replayed onto the second document"); + assert_eq!(pixel(&s, 0, 16, 16), vec![1.0, 0.0, 0.0, 1.0], "the selection fill replayed"); + assert_eq!(pixel(&s, 0, 2, 2), vec![0.0, 0.0, 0.0, 1.0], "outside the selection stays black"); + let last = d.layers.last().unwrap(); + match &last.content { + photocraft_doc::LayerContent::Text(t) => { + assert_eq!(t.text, "Hi", "the styled text replayed"); + assert!(t.char_runs().iter().any(|r| r.style.faux_bold), "the bold run replayed"); + } + other => panic!("expected the recorded type layer, got {other:?}"), + } + // The first document is untouched. + let first = &s.documents()[0].doc; + assert_eq!((first.size.width, first.size.height), (48, 48), "the recording document keeps its own crop"); +} + +#[test] +fn button_color_is_one_of_the_photoshop_swatches() { + let mut s = Session::new(); + s.execute("actions.record", json!({"name": "Print"})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + let set = s.execute("actions.setColor", json!({"action": "Print", "color": "blue"})).unwrap(); + assert_eq!(set["color"], "blue"); + assert_eq!(s.actions.list[0].color, "blue"); + assert_eq!(s.execute("actions.get", json!({"action": 0})).unwrap()["color"], "blue"); + let saved = serde_json::to_string(&s.actions.list).unwrap(); + assert!(saved.contains("blue")); + s.execute("actions.setColor", json!({"action": 0, "color": ""})).unwrap(); + assert!(s.actions.list[0].color.is_empty()); + assert!(!serde_json::to_string(&s.actions.list).unwrap().contains("color"), "an empty colour is omitted"); + for bad in [json!({"action": 0, "color": "pink"}), json!({"action": 0}), json!({"action": 4, "color": "red"}), json!({"color": "red"})] { + assert!(s.execute("actions.setColor", bad).is_err()); + } + assert!(s.actions.list[0].color.is_empty(), "rejected colours change nothing"); +} diff --git a/crates/engine/src/actions_edit_cmds.rs b/crates/engine/src/cmd/actions_edit_cmds.rs similarity index 100% rename from crates/engine/src/actions_edit_cmds.rs rename to crates/engine/src/cmd/actions_edit_cmds.rs diff --git a/crates/engine/src/adjust_cmds.rs b/crates/engine/src/cmd/adjust_cmds.rs similarity index 100% rename from crates/engine/src/adjust_cmds.rs rename to crates/engine/src/cmd/adjust_cmds.rs diff --git a/crates/engine/src/adjust_cmds/tests.rs b/crates/engine/src/cmd/adjust_cmds/tests.rs similarity index 100% rename from crates/engine/src/adjust_cmds/tests.rs rename to crates/engine/src/cmd/adjust_cmds/tests.rs diff --git a/crates/engine/src/cmd/adjust_params.rs b/crates/engine/src/cmd/adjust_params.rs new file mode 100644 index 0000000000..d70ff79dcb --- /dev/null +++ b/crates/engine/src/cmd/adjust_params.rs @@ -0,0 +1,123 @@ +use super::enabled::{check_all_unlocked, is_mask_target, paint_surface}; +use super::layer_params::{layer_param, mask_new_layer}; +use super::*; + +/// Add an adjustment layer above the active one; it takes the mask `mask_new_layer` builds from `p` (a path, the selection, or the default white mask). +pub(super) fn new_adjustment(s: &mut Session, adj: Adjustment, p: &Value, cmd: &str) -> Result { + let label = format!("New {} Layer", adj.label()); + let name = adj.label().to_string(); + let id = s.edit(&label, |doc, active| { + let mut l = Layer::new(doc.next_layer_name(&name), LayerContent::Adjustment(adj)); + mask_new_layer(doc, &mut l, p, cmd, true)?; + let id = doc.insert_above(*active, l); + *active = Some(id); + Ok(id) + })?; + Ok(json!({ "layer": id.0 })) +} + +/// Apply `adj` in place to the targeted layer mask, the targeted alpha channel or Quick Mask, or else the active layer's pixels, as one history step named `label`. +pub(super) fn destructive_adjust(s: &mut Session, label: &str, adj: Adjustment, p: &Value) -> Result { + if is_mask_target(p) { + // The targeted layer mask (#780): ⌘I inverts it, as in Photoshop. + let id = layer_param(s, &Value::Null)?; + return s.edit(label, |doc, _| { + check_all_unlocked(doc, id)?; + let sel = doc.selection.clone(); + pixels::adjust_mask(paint_surface(doc, id, p)?, &adj, sel.as_ref()).map_err(EngineError::Other)?; + Ok(Value::Null) + }); + } + if crate::channel_cmds::is_channel_target(p) { + // Alpha channel / Quick Mask target: the adjustment runs on the grayscale channel as on + // a layer mask, its unstored black included, so ⌘I in Quick Mask inverts it all (#6095). + return s.edit(label, |doc, _| { + let sel = doc.selection.clone(); + if let Some(surf) = crate::channel_cmds::channel_surface_for_filter(doc, None, p)? { + pixels::adjust_mask(surf, &adj, sel.as_ref()).map_err(EngineError::Other)?; + } + Ok(Value::Null) + }); + } + let id = layer_param(s, &Value::Null)?; + s.edit(label, |doc, _| { + let sel = doc.selection.clone(); + let mode = doc.mode; + let surf = paint_surface(doc, id, &Value::Null)?; + pixels::adjust_surface(surf, &adj, sel.as_ref(), mode).map_err(EngineError::Other)?; + Ok(()) + })?; + Ok(Value::Null) +} + +/// Lenient adjustment from params for previews: bad params fall back to the kind's defaults. +/// Commands use the checked [`crate::adjust_params::from_params`]. +pub fn adjustment_from_params(kind: &str, p: &Value) -> Adjustment { + crate::adjust_params::from_params(kind, p, None, ColorMode::Rgb) + .or_else(|_| crate::adjust_params::default_for(kind, ColorMode::Rgb)) + .unwrap_or(Adjustment::Invert) +} + +pub(super) fn doc_mode(s: &Session) -> ColorMode { + s.active().map_or(ColorMode::Rgb, |d| d.doc.mode) +} + +/// The colour mode a destructive adjustment parses its tone space in: a targeted layer mask, +/// saved channel or Quick Mask holds gray levels whatever the document's mode, so Curves and +/// Levels stay in the neutral space instead of Lab (where the composite is ignored) or CMYK +/// (where the curve runs on the inks) (#5335). +pub(super) fn adjust_mode(s: &Session, p: &Value) -> ColorMode { + if is_mask_target(p) || crate::channel_cmds::is_channel_target(p) { ColorMode::Grayscale } else { doc_mode(s) } +} + +/// Tone params for a gray plane target: the document-space channel records are dropped, because +/// those keys select the Lab or CMYK tone space and a plane only holds levels (#5335). +pub(super) fn gray_tone_params(p: &Value) -> Value { + match p { + Value::Object(m) => { + let mut o = Map::new(); + for (k, v) in m { + if !matches!(k.as_str(), "cyan" | "magenta" | "yellow" | "black" | "lightness" | "a" | "b") { + o.insert(k.clone(), v.clone()); + } + } + Value::Object(o) + } + other => other.clone(), + } +} + +/// Commands generated from a table share one `run` fn; the kind is recovered from the id. +pub(crate) fn inject_kind(id: &str, params: Value) -> Value { + let kind = id.strip_prefix("layer.newAdjustmentLayer.").or_else(|| id.strip_prefix("image.adjustments.")); + match (kind, params) { + (Some(k), Value::Object(mut m)) => { + m.insert("__kind".into(), Value::String(k.into())); + Value::Object(m) + } + (Some(k), _) => json!({ "__kind": k }), + (None, p) => p, + } +} + +pub fn adjustment_kind(a: &Adjustment) -> &'static str { + match a { + Adjustment::BrightnessContrast { .. } => "brightnessContrast", + Adjustment::Levels { .. } => "levels", + Adjustment::Curves { .. } => "curves", + Adjustment::Exposure { .. } => "exposure", + Adjustment::Vibrance { .. } => "vibrance", + Adjustment::HueSaturation { .. } => "hueSaturation", + Adjustment::ColorBalance { .. } => "colorBalance", + Adjustment::BlackWhite { .. } => "blackWhite", + Adjustment::PhotoFilter { .. } => "photoFilter", + Adjustment::ChannelMixer { .. } => "channelMixer", + Adjustment::Posterize { .. } => "posterize", + Adjustment::Threshold { .. } => "threshold", + Adjustment::GradientMap { .. } => "gradientMap", + Adjustment::SelectiveColor { .. } => "selectiveColor", + Adjustment::ColorLookup { .. } => "colorLookup", + Adjustment::Unsupported { .. } => "unsupported", + _ => "invert", + } +} diff --git a/crates/engine/src/cmd/align_cmds.rs b/crates/engine/src/cmd/align_cmds.rs new file mode 100644 index 0000000000..869d29b724 --- /dev/null +++ b/crates/engine/src/cmd/align_cmds.rs @@ -0,0 +1,361 @@ +//! Edit › Auto-Align Layers and Auto-Blend Layers, on the selected pixel layers. +//! +//! Both share Photomerge's registration and blending ([`photocraft_algo::panorama`] via +//! `photo_cmds`). Auto-Align matches Harris / steered-BRIEF features between every pair of +//! layers, chains the verified pairs from the reference layer (maximum spanning tree) and +//! bundle-adjusts all of them, then warps each layer. Layers that nearly coincide (a focus or +//! exposure bracket) have nothing to match and register by intensity instead +//! ([`photocraft_algo::direct`], `registration`: auto falls back to it, or ask for it). Projections: Auto, Perspective +//! (homography), Cylindrical and Spherical (rigid motion on the cylinder / sphere, focal length +//! from the homographies or EXIF), Collage (similarity) and Reposition (translation). The +//! reference stays put in the planar projections. +//! +//! Auto-Blend gives each selected layer a mask so the composite shows, per pixel, the sharpest +//! layer (Stack Images, for focus stacking) or one layer per region with seams routed where the +//! layers agree (Panorama). With Seamless Tones and Colors it also adds a merged layer: the +//! panorama blended with Laplacian pyramids so transitions are invisible, the stack fused on the +//! Laplacian pyramid, each coefficient from the layer sharpest at that scale +//! ([`pyramid::fuse_stack`]; `haloControl` keeps a bright object's defocused glow out of the +//! coarse levels). +//! Stack Images can also add a hidden Depth layer, the layer each pixel is sharpest in by depth +//! from focus ([`photocraft_algo::dff`]): black = the bottom layer, white = the top, so that once +//! on a layer mask it drives Lens Blur's depth map. + +use photocraft_algo::panorama::Layout; +use photocraft_algo::pyramid; +use photocraft_algo::transform::Interp; +use photocraft_algo::warp::warp_mesh_gray; +use photocraft_doc::{Document, Layer, LayerContent, LayerId, LayerMask}; +use photocraft_geom::Rect; +use photocraft_raster::{Surface, to_rgba}; +use serde_json::{Value, json}; + +use crate::commands::CommandSpec; +use crate::photo_cmds::{NO_DETAIL, plane_matrix, register, register_direct, seam_blend, seam_order, warp_placed}; +use crate::{EngineError, Result, Session}; + +fn bad(cmd: &str, msg: impl Into) -> EngineError { + EngineError::BadParams { cmd: cmd.into(), msg: msg.into() } +} + +/// The selected raster layers, bottom to top. +fn selected_pixel_layers(s: &Session) -> Vec { + let Some(st) = s.active() else { return Vec::new() }; + st.selected_layers().into_iter().filter(|id| st.doc.layer(*id).is_some_and(|l| matches!(l.content, LayerContent::Raster(_)))).collect() +} + +/// Whether a lock keeps the layer `id` from being moved or warped: lock all, position or pixels. +/// The Background's own position lock doesn't count: like Free Transform, Auto-Align turns the +/// Background into a normal layer when it has to move it (Photoshop). +fn pinned(doc: &Document, id: LayerId) -> bool { + let l = doc.effective_locks(id); + l.all || l.pixels || (l.position && !doc.is_background(id)) +} + +fn two_layers(s: &Session) -> std::result::Result<(), String> { + s.active().ok_or("no document open")?; + if selected_pixel_layers(s).len() < 2 { Err("select two or more pixel layers in the Layers panel".into()) } else { Ok(()) } +} + +fn auto_align(s: &mut Session, p: &Value) -> Result { + let cmd = "edit.autoAlignLayers"; + let ids = selected_pixel_layers(s); + if ids.len() < 2 { + return Err(bad(cmd, "select two or more pixel layers")); + } + let projection = p.get("projection").and_then(Value::as_str).unwrap_or("auto"); + let layout = Layout::parse(projection) + .ok_or_else(|| bad(cmd, format!("unknown projection `{projection}` (auto|perspective|cylindrical|spherical|collage|reposition)")))?; + let st = s.active().ok_or(EngineError::NoDocument)?; + let doc = st.doc.clone(); + let reference = match p.get("reference").and_then(Value::as_u64) { + Some(r) if ids.contains(&LayerId(r)) => LayerId(r), + Some(r) => return Err(bad(cmd, format!("reference {r} is not a selected pixel layer"))), + // As in Photoshop, a locked layer stays put: it becomes the reference (#7080). + None => ids.iter().copied().find(|id| pinned(&doc, *id)).unwrap_or(ids[0]), + }; + let ref_idx = ids.iter().position(|i| *i == reference).unwrap_or(0); + let area = doc.bounds(); + let surfs: Vec<&Surface> = ids.iter().map(|id| doc.layer(*id).and_then(|l| l.surface()).ok_or(EngineError::NoLayer(*id))).collect::>()?; + let images: Vec<(&Surface, Rect)> = surfs.iter().map(|s| (*s, area)).collect(); + let focal35 = doc.metadata.exif.as_ref().and_then(|e| photocraft_algo::exif::read(e).focal_length_35mm); + let geometric = p.get("geometricCorrection").and_then(Value::as_bool).unwrap_or(false); + let registration = p.get("registration").and_then(Value::as_str).unwrap_or("auto"); + if !matches!(registration, "auto" | "features" | "intensity") { + return Err(bad(cmd, "`registration` must be auto|features|intensity")); + } + let no_detail = || EngineError::Other(NO_DETAIL.into()); + // Features first (a panorama); layers that nearly coincide (a focus or exposure bracket) have + // nothing to match, and register by intensity instead. + let by_features = (registration != "intensity").then(|| register(&images, layout, Some(ref_idx), geometric, focal35)).flatten(); + let (al, used) = match (by_features, registration) { + (Some(al), _) => (al, "features"), + (None, "features") => return Err(no_detail()), + (None, _) => ( + register_direct(&images, layout, ref_idx).map_err(|m| if registration == "intensity" && m != NO_DETAIL { bad(cmd, m) } else { no_detail() })?, + "intensity", + ), + }; + let interp = Interp::parse(p.get("interpolation").and_then(Value::as_str).unwrap_or("bicubic")); + let planar = matches!(al.layout, Layout::Perspective | Layout::Collage | Layout::Reposition); + let mut inliers = vec![0usize; ids.len()]; + for &(a, b, n) in &al.pairs { + inliers[a] += n; + inliers[b] += n; + } + // Everything but the reference moves in planar layouts; every layer is reprojected otherwise. + let moves: Vec = (0..ids.len()).filter(|&i| al.placements[i].is_some() && (i != ref_idx || !planar)).collect(); + let failed: Vec = (0..ids.len()).filter(|&i| al.placements[i].is_none()).map(|i| ids[i].0).collect(); + if moves.is_empty() { + return Err(EngineError::Other("Auto-Align couldn't find enough matching detail between the layers".into())); + } + if let Some(l) = moves.iter().find(|&&i| pinned(&doc, ids[i])).and_then(|&i| doc.layer(ids[i])) { + return Err(EngineError::Other(format!("Auto-Align can't move the locked layer \"{}\"", l.name))); + } + let warped: Vec<(LayerId, Surface, Option)> = moves + .iter() + .map(|&i| { + let pl = al.placements[i].as_ref().ok_or_else(|| EngineError::Other("Auto-Align lost a layer's placement".into()))?; + let l = doc.layer(ids[i]).ok_or(EngineError::NoLayer(ids[i]))?; + let surf = l.surface().ok_or(EngineError::NoLayer(ids[i]))?; + let b = surf.content_bounds(); + let px = if b.is_empty() { surf.clone() } else { warp_placed(surf, b, (0.0, 0.0), pl, (0.0, 0.0), interp)? }; + // Masks warp as masks: one grey channel whose outside keeps its default (reveal-all + // stays revealed), not as colour, which would come back grey + alpha reading 0 outside. + let mask = match l.mask.as_ref() { + Some(m) => Some(match plane_matrix(pl, (0.0, 0.0)) { + Some(h) => crate::transform_cmds::warp_gray(&m.surface, &h, Interp::Bilinear)?, + None => warp_mesh_gray(&m.surface, &|x, y| pl.forward(x, y), Interp::Bilinear), + }), + None => None, + }; + Ok((ids[i], px, mask)) + }) + .collect::>()?; + s.edit("Auto-Align Layers", |doc, _| { + for (id, px, mask) in &warped { + // Photoshop turns the Background into a normal layer before moving it. + crate::extra_cmds::background_to_layer(doc, *id); + let l = doc.layer_mut(*id).ok_or(EngineError::NoLayer(*id))?; + if let Some(surf) = l.surface_mut() { + *surf = px.clone(); + } + if let (Some(m), Some(ms)) = (&mut l.mask, mask) { + m.surface = ms.clone(); + } + } + Ok(()) + })?; + let model = match al.layout { + Layout::Reposition => "reposition", + Layout::Collage => "collage", + Layout::Perspective | Layout::Auto => "perspective", + Layout::Cylindrical => "cylindrical", + Layout::Spherical => "spherical", + }; + let aligned: Vec = moves + .iter() + .filter_map(|&i| { + let pl = al.placements[i].as_ref()?; + Some(json!({"layer": ids[i].0, "model": model, "matches": inliers[i], "matrix": plane_matrix(pl, (0.0, 0.0)).map(|h| h.0.to_vec())})) + }) + .collect(); + Ok( + json!({"reference": reference.0, "layout": al.layout.name(), "registration": used, "focal": al.focal, "rms": al.rms, "aligned": aligned, "failed": failed}), + ) +} + +/// The most memory Auto-Blend's working buffers may take past the canvas: a bound independent +/// of the layers' own bounding boxes, which a sparse layer (a dot at each far corner) can make +/// arbitrarily large, and of how many layers are blended. +const MAX_BLEND_BYTES: u64 = 4 << 30; + +/// What Auto-Blend's buffers hold per work-area pixel, as f32: each layer's pixels, luminance, +/// alpha and mask weight, plus the merged picture and the depth map. +fn blend_bytes_per_pixel(layers: u64, channels: u64) -> u64 { + layers.saturating_mul(channels.saturating_add(3)).saturating_add(channels.saturating_mul(2)).saturating_mul(4) +} + +/// Auto-Blend's buffers, for allocation errors. +const BLEND_BUFFERS: &str = "Auto-Blend Layers"; + +fn auto_blend(s: &mut Session, p: &Value) -> Result { + let cmd = "edit.autoBlendLayers"; + let ids = selected_pixel_layers(s); + if ids.len() < 2 { + return Err(bad(cmd, "select two or more pixel layers")); + } + let method = p.get("method").and_then(Value::as_str).unwrap_or("panorama"); + if !matches!(method, "panorama" | "stack") { + return Err(bad(cmd, "`method` must be panorama|stack")); + } + let seamless = p.get("seamlessTones").and_then(Value::as_bool).unwrap_or(true); + let halo = match p.get("haloControl") { + None | Some(Value::Null) => pyramid::StackFusion::default().halo, + Some(v) => match v.as_f64() { + Some(h) if (0.0..=f64::from(pyramid::HALO_MAX)).contains(&h) => h as f32, + _ => return Err(bad(cmd, format!("`haloControl` must be a number from 0 to {}", pyramid::HALO_MAX))), + }, + }; + let want_depth = p.get("depthMap").and_then(Value::as_bool).unwrap_or(false); + if want_depth && method != "stack" { + return Err(bad(cmd, "`depthMap` needs `method`: stack")); + } + let st = s.active().ok_or(EngineError::NoDocument)?; + let doc: std::sync::Arc = st.doc.clone(); + let mut union = Rect::EMPTY; + let mut content_px = 0u64; + let px_of = |r: &Rect| u64::from(r.width()) * u64::from(r.height()); + for id in &ids { + if let Some(b) = doc.layer(*id).and_then(|l| l.surface()).map(|s| s.content_bounds()) { + union = union.union(&b); + content_px = content_px.saturating_add(px_of(&b)); + } + } + // The whole layers, past the canvas too (#5745): Auto-Align leaves a panorama's layers + // partly off the canvas, and Photoshop masks and blends all of each layer, so Reveal All + // shows the whole panorama. Layers so far apart that their bounds are mostly empty, or + // whose buffers would exceed `MAX_BLEND_BYTES`, keep to the canvas. + let canvas = doc.bounds(); + let channels = ids.iter().filter_map(|id| doc.layer(*id).and_then(|l| l.surface()).map(|s| s.channels() as u64)).max().unwrap_or(4); + let per_px = blend_bytes_per_pixel(ids.len() as u64, channels); + let fits = px_of(&union).saturating_mul(per_px) <= MAX_BLEND_BYTES && px_of(&union) <= content_px.max(px_of(&canvas)).saturating_mul(2); + let area = if fits { union } else { union.intersect(&canvas) }; + if area.is_empty() { + return Err(EngineError::Other("the selected layers are empty".into())); + } + let (w, h) = (area.width() as usize, area.height() as usize); + let mut imgs: Vec> = Vec::new(); + let mut luma: Vec> = Vec::new(); + let mut alpha: Vec> = Vec::new(); + let mut fmt = None; + for id in &ids { + let l = doc.layer(*id).ok_or(EngineError::NoLayer(*id))?; + let surf = l.surface().ok_or(EngineError::NoLayer(*id))?; + let (px, f) = (crate::allocation::read_region(surf, area, BLEND_BUFFERS)?, surf.format()); + let n = f.channels(); + let (mut lv, mut av) = (crate::allocation::filled(w * h, 0.0f32, BLEND_BUFFERS)?, crate::allocation::filled(w * h, 0.0f32, BLEND_BUFFERS)?); + for i in 0..w * h { + let c = to_rgba(&f, &px[i * n..(i + 1) * n]); + lv[i] = 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]; + av[i] = c[3]; + } + if fmt.is_some_and(|g: photocraft_color::PixelFormat| g != f) { + return Err(EngineError::Other("the layers have different pixel formats".into())); + } + fmt = Some(f); + imgs.push(px); + luma.push(lv); + alpha.push(av); + } + let fmt = fmt.ok_or(EngineError::NoDocument)?; + let (weights, blended) = if method == "stack" { + let weights = pyramid::stack_weights(w, h, &luma, &alpha); + let blended = seamless.then(|| { + let refs: Vec<&[f32]> = imgs.iter().map(Vec::as_slice).collect(); + let p = pyramid::StackFusion { halo, ..Default::default() }; + pyramid::fuse_stack(w, h, fmt.channels(), &refs, &luma, &alpha, p) + }); + (weights, blended) + } else { + // Panorama: seams routed through agreement, multi-band blended (photo_cmds). + let surfs: Vec = + ids.iter().map(|id| doc.layer(*id).and_then(|l| l.surface()).cloned().ok_or(EngineError::NoLayer(*id))).collect::>()?; + let order = seam_order(&surfs, 0); + // Seamless Tones and Colors also evens out exposure and colour between the layers (gain + // compensation over their overlaps), as in Photomerge. + let b = seam_blend(&surfs, area, &order, seamless, seamless, None); + let weights: Vec> = b.layers.iter().map(|(_, m)| m.read_region(area)).collect(); + let blended = seamless.then(|| b.composite.read_region(area)); + (weights, blended) + }; + // The depth map: the layer each pixel is sharpest in, from the focus volume guided by the + // merged picture (or, without one, by the per-pixel pick), as a hidden gray layer, black = + // the bottom layer, white = the top, ready for Lens Blur's depth map once on a mask. + let depth_px = want_depth.then(|| { + let n = fmt.channels(); + let guide: Vec = match &blended { + Some(px) => (0..w * h) + .map(|i| { + let c = to_rgba(&fmt, &px[i * n..(i + 1) * n]); + 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2] + }) + .collect(), + None => (0..w * h).map(|i| luma.iter().zip(&weights).map(|(l, wt)| l[i] * wt[i]).sum()).collect(), + }; + let refs: Vec<&[f32]> = luma.iter().map(Vec::as_slice).collect(); + let dm = photocraft_algo::dff::depth_from_focus(&refs, &guide, w, h, &photocraft_algo::dff::DepthParams::default()); + let scale = 1.0 / (ids.len() - 1).max(1) as f32; + let mut out = vec![0.0f32; w * h * n]; + for (i, d) in dm.depth.iter().enumerate() { + let g = (d * scale).clamp(0.0, 1.0); + photocraft_raster::from_rgba_into(&fmt, [g, g, g, 1.0], &mut out[i * n..(i + 1) * n]); + } + out + }); + let top = *ids.last().ok_or_else(|| EngineError::Other("Auto-Blend needs two or more layers".into()))?; + let label = "Auto-Blend Layers"; + let (new_layer, depth_layer) = s.edit(label, |doc, active| { + for (id, wt) in ids.iter().zip(&weights) { + // The Background can't have a mask: it becomes a normal layer first, as in Photoshop. + crate::extra_cmds::background_to_layer_for_mask(doc, *id); + let l = doc.layer_mut(*id).ok_or(EngineError::NoLayer(*id))?; + let mut mask = LayerMask::hide_all(); + mask.surface.write_region(area, wt); + mask.surface.prune(); + l.mask = Some(mask); + } + let mut below = top; + let depth_id = depth_px.as_ref().map(|px| { + let mut l = Layer::raster(doc.next_layer_name("Depth"), fmt); + l.visible = false; + if let Some(surf) = l.surface_mut() { + surf.write_region(area, px); + surf.prune(); + } + below = doc.insert_above(Some(below), l); + below + }); + let Some(px) = &blended else { + if depth_id.is_some() { + *active = depth_id; + } + return Ok((None, depth_id)); + }; + let mut l = Layer::raster(doc.next_layer_name("Blended"), fmt); + if let Some(surf) = l.surface_mut() { + surf.write_region(area, px); + surf.prune(); + } + let nid = doc.insert_above(Some(below), l); + *active = Some(nid); + Ok((Some(nid), depth_id)) + })?; + Ok(json!({"method": method, "layers": ids.iter().map(|i| i.0).collect::>(), "blended": new_layer.map(|l| l.0), "depth": depth_layer.map(|l| l.0)})) +} + +macro_rules! spec { + ($id:literal, $label:literal, $params:literal, $run:expr) => { + CommandSpec { id: $id, label: $label, menu: &["Edit"], shortcut: None, params: $params, enabled: two_layers, run: $run, journal: true } + }; +} + +pub fn specs() -> Vec { + vec![ + spec!( + "edit.autoAlignLayers", + "Auto-Align Layers…", + r##"{"projection":"auto|perspective|cylindrical|spherical|collage|reposition","reference":layer id?=the locked selected layer, else the bottom selected layer,"geometricCorrection":bool=false,"interpolation":"bicubic|bilinear|nearest","registration":"auto|features|intensity"}"##, + auto_align + ), + spec!( + "edit.autoBlendLayers", + "Auto-Blend Layers…", + r##"{"method":"panorama|stack","seamlessTones":bool=true,"haloControl":0..8=2,"depthMap":bool=false}"##, + auto_blend + ), + ] +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/align_cmds/tests.rs b/crates/engine/src/cmd/align_cmds/tests.rs new file mode 100644 index 0000000000..e456a70814 --- /dev/null +++ b/crates/engine/src/cmd/align_cmds/tests.rs @@ -0,0 +1,585 @@ +use super::*; + +/// Deterministic texture written into a layer at offset (dx, dy). +fn texture_layer(s: &mut Session, name: &str, dx: i32, dy: i32) -> LayerId { + s.execute("layer.new.layer", json!({"name": name})).unwrap(); + let id = s.active().unwrap().active_layer.unwrap(); + paint_texture(s, id, dx, dy); + id +} + +/// Writes the deterministic texture into layer `id` at offset (dx, dy). +fn paint_texture(s: &mut Session, id: LayerId, dx: i32, dy: i32) { + s.edit("tex", |doc, _| { + let surf = doc.layer_mut(id).unwrap().surface_mut().unwrap(); + let mut seed = 99u64; + let mut rnd = || { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (seed >> 33) as f64 / (1u64 << 31) as f64 + }; + surf.fill_rect(Rect::new(dx, dy, dx + 240, dy + 180), &[0.4, 0.4, 0.4, 1.0]); + for _ in 0..120 { + let (x, y) = ((rnd() * 220.0) as i32, (rnd() * 160.0) as i32); + let (sw, sh) = (4 + (rnd() * 14.0) as i32, 4 + (rnd() * 10.0) as i32); + let v = rnd() as f32; + surf.fill_rect(Rect::new(dx + x, dy + y, dx + x + sw, dy + y + sh), &[v, 1.0 - v, v * 0.5, 1.0]); + } + Ok(()) + }) + .unwrap(); +} + +fn select(s: &mut Session, ids: &[LayerId]) { + s.execute("layer.select", json!({"layer": ids[0].0})).unwrap(); + for id in &ids[1..] { + s.execute("layer.select", json!({"layer": id.0, "mode": "add"})).unwrap(); + } +} + +#[test] +fn auto_align_repositions_at_all_depths() { + for depth in [8, 16, 32] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 300, "height": 240, "depth": depth, "background": "transparent"})).unwrap(); + let a = texture_layer(&mut s, "A", 20, 20); + let b = texture_layer(&mut s, "B", 31, 13); + assert!(!s.is_enabled("edit.autoAlignLayers"), "one layer selected"); + select(&mut s, &[a, b]); + assert!(s.is_enabled("edit.autoAlignLayers")); + let r = s.execute("edit.autoAlignLayers", json!({"projection": "reposition"})).unwrap(); + assert_eq!(r["reference"], a.0); + let bb = s.active().unwrap().doc.layer(b).unwrap().surface().unwrap().content_bounds(); + assert!((bb.x0 - 20).abs() <= 1 && (bb.y0 - 20).abs() <= 1, "depth {depth}: {bb:?} {r}"); + s.undo(); + let bb = s.active().unwrap().doc.layer(b).unwrap().surface().unwrap().content_bounds(); + assert_eq!((bb.x0, bb.y0), (31, 13)); + } +} + +#[test] +fn auto_align_auto_projection_and_errors() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 300, "height": 240, "background": "transparent"})).unwrap(); + let a = texture_layer(&mut s, "A", 20, 20); + let b = texture_layer(&mut s, "B", 26, 25); + select(&mut s, &[a, b]); + let r = s.execute("edit.autoAlignLayers", json!({})).unwrap(); + let m = r["aligned"][0]["matrix"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect::>(); + assert!((m[2] + 6.0).abs() < 1.0 && (m[5] + 5.0).abs() < 1.0, "{r}"); + assert!(s.execute("edit.autoAlignLayers", json!({"projection": "sideways"})).is_err()); + assert!(s.execute("edit.autoAlignLayers", json!({"reference": u64::MAX})).is_err()); +} + +/// As in Photoshop, a locked layer stays where it is: it becomes the reference and the +/// others move onto it (#7080). +#[test] +fn auto_align_keeps_a_locked_layer_as_the_reference() { + for lock in ["all", "position", "pixels"] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 300, "height": 240, "background": "transparent"})).unwrap(); + let a = texture_layer(&mut s, "A", 20, 20); + let b = texture_layer(&mut s, "B", 31, 13); + s.edit("lock", |doc, _| { + doc.layer_mut(b).unwrap().locks.set(lock, true); + Ok(()) + }) + .unwrap(); + select(&mut s, &[a, b]); + let r = s.execute("edit.autoAlignLayers", json!({"projection": "reposition"})).unwrap(); + assert_eq!(r["reference"], b.0, "{lock}: {r}"); + let doc = &s.active().unwrap().doc; + let bb = doc.layer(b).unwrap().surface().unwrap().content_bounds(); + assert_eq!((bb.x0, bb.y0), (31, 13), "{lock}: the locked layer stays put"); + let ab = doc.layer(a).unwrap().surface().unwrap().content_bounds(); + assert!((ab.x0 - 31).abs() <= 1 && (ab.y0 - 13).abs() <= 1, "{lock}: {ab:?} {r}"); + // An explicit reference that would move the locked layer is refused. + s.undo(); + assert!(s.execute("edit.autoAlignLayers", json!({"projection": "reposition", "reference": a.0})).is_err()); + // Two locked layers: nothing may move. + s.edit("lock", |doc, _| { + doc.layer_mut(a).unwrap().locks.set(lock, true); + Ok(()) + }) + .unwrap(); + assert!(s.execute("edit.autoAlignLayers", json!({"projection": "reposition"})).is_err()); + let bb = s.active().unwrap().doc.layer(a).unwrap().surface().unwrap().content_bounds(); + assert_eq!((bb.x0, bb.y0), (20, 20)); + } +} + +/// The Background doesn't block Auto-Align: when a projection reprojects every layer +/// (Cylindrical, Spherical, or Auto choosing one), or another layer is the reference, it +/// becomes a normal layer ("Layer 0") and moves, as in Photoshop and as Free Transform does. +#[test] +fn auto_align_moves_the_background_as_a_normal_layer() { + let setup = || { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 300, "height": 240, "background": "white"})).unwrap(); + let bg = s.active().unwrap().doc.background().unwrap().id; + paint_texture(&mut s, bg, 20, 20); + let b = texture_layer(&mut s, "B", 31, 13); + select(&mut s, &[bg, b]); + (s, bg, b) + }; + for projection in ["cylindrical", "spherical", "auto"] { + let (mut s, bg, b) = setup(); + let r = s.execute("edit.autoAlignLayers", json!({"projection": projection})).unwrap_or_else(|e| panic!("{projection}: {e}")); + let doc = &s.active().unwrap().doc; + let moved = r["aligned"].as_array().unwrap().iter().any(|a| a["layer"] == bg.0); + assert_eq!(moved, projection != "auto" || r["layout"] != "perspective", "{projection}: {r}"); + assert_eq!(doc.is_background(bg), !moved, "{projection}: a moved Background is a normal layer: {r}"); + if moved { + assert_eq!(doc.layer(bg).unwrap().name, "Layer 0", "{projection}"); + } + assert!(doc.layer(b).is_some(), "{projection}"); + s.undo(); + assert!(s.active().unwrap().doc.is_background(bg), "{projection}: undo restores the Background"); + } + // Planar, with the other layer as the reference: the Background moves onto it. + let (mut s, bg, b) = setup(); + s.execute("edit.autoAlignLayers", json!({"projection": "reposition", "reference": b.0})).unwrap(); + let doc = &s.active().unwrap().doc; + assert!(!doc.is_background(bg)); + // Default reference: the Background (bottom) stays put and stays the Background. + let (mut s, bg, b) = setup(); + let r = s.execute("edit.autoAlignLayers", json!({"projection": "reposition"})).unwrap(); + assert_eq!(r["reference"], bg.0, "{r}"); + let doc = &s.active().unwrap().doc; + assert!(doc.is_background(bg)); + let bb = doc.layer(b).unwrap().surface().unwrap().content_bounds(); + assert!((bb.x0 - 20).abs() <= 1 && (bb.y0 - 20).abs() <= 1, "{bb:?} {r}"); +} + +/// The moving layer's mask is warped as a mask: one grey channel whose outside keeps its +/// default (reveal-all stays revealed, hide-all stays hidden), for planar and mesh warps. +#[test] +fn auto_align_warps_layer_masks_keeping_their_default() { + for (projection, reveal) in [("reposition", true), ("reposition", false), ("cylindrical", true)] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 300, "height": 240, "background": "transparent"})).unwrap(); + let a = texture_layer(&mut s, "A", 20, 20); + let b = texture_layer(&mut s, "B", 31, 13); + let (inside, outside) = if reveal { (0.0, 1.0) } else { (1.0, 0.0) }; + s.edit("mask", |doc, _| { + let mut m = if reveal { LayerMask::reveal_all() } else { LayerMask::hide_all() }; + m.surface.fill_rect(Rect::new(100, 100, 110, 110), &[inside]); + doc.layer_mut(b).unwrap().mask = Some(m); + Ok(()) + }) + .unwrap(); + select(&mut s, &[a, b]); + let r = s.execute("edit.autoAlignLayers", json!({"projection": projection})).unwrap(); + let doc = &s.active().unwrap().doc; + let m = doc.layer(b).unwrap().mask.as_ref().unwrap(); + assert_eq!(m.surface.format().channels(), 1, "{projection}: {r}"); + assert_eq!(m.value(250, 200), outside, "{projection} reveal={reveal}: {r}"); + assert_eq!(m.value(5, 5), outside, "{projection} reveal={reveal}: {r}"); + if projection == "reposition" { + // The square moved with the layer (by about (-11, +7)). + assert!((m.value(94, 112) - inside).abs() < 0.01, "{r}"); + } + } +} + +#[test] +fn auto_blend_panorama_masks_and_seamless_layer() { + for depth in [8, 16, 32] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 200, "height": 60, "depth": depth, "background": "transparent"})).unwrap(); + s.execute("layer.new.layer", json!({"name": "left"})).unwrap(); + s.edit("l", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(0, 0, 130, 60), &[0.2, 0.3, 0.8, 1.0]); + Ok(()) + }) + .unwrap(); + let left = s.active().unwrap().active_layer.unwrap(); + s.execute("layer.new.layer", json!({"name": "right"})).unwrap(); + s.edit("r", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(70, 0, 200, 60), &[0.9, 0.6, 0.2, 1.0]); + Ok(()) + }) + .unwrap(); + let right = s.active().unwrap().active_layer.unwrap(); + select(&mut s, &[left, right]); + let r = s.execute("edit.autoBlendLayers", json!({"method": "panorama"})).unwrap(); + let doc = &s.active().unwrap().doc; + let ml = doc.layer(left).unwrap().mask.as_ref().unwrap(); + let mr = doc.layer(right).unwrap().mask.as_ref().unwrap(); + assert_eq!((ml.value(10, 30), mr.value(10, 30)), (1.0, 0.0), "depth {depth}"); + assert_eq!((ml.value(190, 30), mr.value(190, 30)), (0.0, 1.0)); + let blended = LayerId(r["blended"].as_u64().unwrap()); + let px = doc.layer(blended).unwrap().surface().unwrap().pixel(5, 30); + assert!((px[2] - 0.8).abs() < 0.02, "{px:?}"); + s.undo(); + assert!(s.active().unwrap().doc.layer(left).unwrap().mask.is_none()); + } +} + +/// #5745: the Background can't take a mask, so Auto-Blend turns it into a normal layer first. +#[test] +fn auto_blend_turns_the_background_into_a_layer() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 200, "height": 60, "background": "white"})).unwrap(); + let bg = s.active().unwrap().doc.background().unwrap().id; + s.execute("layer.new.layer", json!({"name": "right"})).unwrap(); + s.edit("r", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(70, 0, 200, 60), &[0.9, 0.6, 0.2, 1.0]); + Ok(()) + }) + .unwrap(); + let right = s.active().unwrap().active_layer.unwrap(); + select(&mut s, &[bg, right]); + s.execute("edit.autoBlendLayers", json!({"method": "panorama"})).unwrap(); + let doc = &s.active().unwrap().doc; + assert!(!doc.is_background(bg), "the Background became a layer to take its mask"); + assert!(doc.layer(bg).unwrap().mask.is_some()); + s.undo(); + assert!(s.active().unwrap().doc.is_background(bg), "undo restores the Background"); +} + +/// Seamless Tones and Colors evens out a 10% exposure step between two panorama layers. +#[test] +fn auto_blend_panorama_seamless_matches_exposure() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 200, "height": 60, "background": "transparent"})).unwrap(); + let mut ids = Vec::new(); + for (name, x0, x1, gain) in [("left", 0, 130, 1.0f32), ("right", 70, 200, 1.1)] { + s.execute("layer.new.layer", json!({ "name": name })).unwrap(); + s.edit(name, |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(x0, 0, x1, 60), &[0.2 * gain, 0.4 * gain, 0.5 * gain, 1.0]); + Ok(()) + }) + .unwrap(); + ids.push(s.active().unwrap().active_layer.unwrap()); + } + select(&mut s, &ids); + let r = s.execute("edit.autoBlendLayers", json!({"method": "panorama"})).unwrap(); + let doc = &s.active().unwrap().doc; + let blended = doc.layer(LayerId(r["blended"].as_u64().unwrap())).unwrap().surface().unwrap(); + let (a, b) = (blended.pixel(10, 30), blended.pixel(190, 30)); + // 0.5 vs 0.55 without gain compensation. + assert!((a[2] - b[2]).abs() < 0.015, "{a:?} {b:?}"); +} + +/// #5745: the top layer hangs off the canvas's right edge, so cropped to the canvas it lies +/// wholly over the bottom one. It used to get an all-black mask; now it shows on its side. +#[test] +fn auto_blend_panorama_of_a_layer_the_canvas_crops_to_all_overlap() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 200, "height": 60, "background": "transparent"})).unwrap(); + s.execute("layer.new.layer", json!({"name": "left"})).unwrap(); + s.edit("l", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(0, 0, 200, 60), &[0.2, 0.4, 0.5, 1.0]); + Ok(()) + }) + .unwrap(); + let left = s.active().unwrap().active_layer.unwrap(); + s.execute("layer.new.layer", json!({"name": "right"})).unwrap(); + s.edit("r", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(120, 0, 320, 60), &[0.2, 0.4, 0.5, 1.0]); + Ok(()) + }) + .unwrap(); + let right = s.active().unwrap().active_layer.unwrap(); + select(&mut s, &[left, right]); + s.execute("edit.autoBlendLayers", json!({"method": "panorama", "seamlessTones": false})).unwrap(); + let doc = &s.active().unwrap().doc; + let ml = doc.layer(left).unwrap().mask.as_ref().unwrap(); + let mr = doc.layer(right).unwrap().mask.as_ref().unwrap(); + assert_eq!((ml.value(10, 30), mr.value(10, 30)), (1.0, 0.0)); + assert_eq!((ml.value(195, 30), mr.value(195, 30)), (0.0, 1.0)); + for x in 0..200 { + assert_eq!(ml.value(x, 30) + mr.value(x, 30), 1.0, "x {x} shows one layer"); + } +} + +/// #5745: a layer Auto-Align left partly off the canvas is masked and blended over all of +/// its bounds, not cut off at the canvas edge. +#[test] +fn auto_blend_panorama_masks_past_the_canvas() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 200, "height": 60, "background": "transparent"})).unwrap(); + s.execute("layer.new.layer", json!({"name": "left"})).unwrap(); + s.edit("l", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(0, 0, 150, 60), &[0.2, 0.4, 0.5, 1.0]); + Ok(()) + }) + .unwrap(); + let left = s.active().unwrap().active_layer.unwrap(); + s.execute("layer.new.layer", json!({"name": "right"})).unwrap(); + s.edit("r", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(120, 0, 320, 60), &[0.2, 0.4, 0.5, 1.0]); + Ok(()) + }) + .unwrap(); + let right = s.active().unwrap().active_layer.unwrap(); + select(&mut s, &[left, right]); + let r = s.execute("edit.autoBlendLayers", json!({"method": "panorama"})).unwrap(); + let doc = &s.active().unwrap().doc; + let ml = doc.layer(left).unwrap().mask.as_ref().unwrap(); + let mr = doc.layer(right).unwrap().mask.as_ref().unwrap(); + assert_eq!((ml.value(10, 30), mr.value(10, 30)), (1.0, 0.0)); + assert_eq!((ml.value(300, 30), mr.value(300, 30)), (0.0, 1.0), "off the canvas"); + let blended = doc.layer(LayerId(r["blended"].as_u64().unwrap())).unwrap().surface().unwrap(); + assert_eq!(blended.pixel(300, 30)[3], 1.0, "the merged layer covers the off-canvas part"); +} + +/// A sparse layer whose bounds are huge (a dot at each far corner) raises its own content +/// estimate, so the extent past the canvas is capped independently: it keeps to the canvas. +#[test] +fn auto_blend_sparse_huge_bounds_keep_to_the_canvas() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 200, "height": 200, "background": "transparent"})).unwrap(); + s.execute("layer.new.layer", json!({"name": "a"})).unwrap(); + s.edit("a", |doc, active| { + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + surf.fill_rect(Rect::new(0, 0, 150, 200), &[0.2, 0.4, 0.5, 1.0]); + surf.fill_rect(Rect::new(100_000, 100_000, 100_001, 100_001), &[0.2, 0.4, 0.5, 1.0]); + Ok(()) + }) + .unwrap(); + let a = s.active().unwrap().active_layer.unwrap(); + s.execute("layer.new.layer", json!({"name": "b"})).unwrap(); + s.edit("b", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(50, 0, 200, 200), &[0.2, 0.4, 0.5, 1.0]); + Ok(()) + }) + .unwrap(); + let b = s.active().unwrap().active_layer.unwrap(); + select(&mut s, &[a, b]); + let r = s.execute("edit.autoBlendLayers", json!({"method": "panorama"})).unwrap(); + let doc = &s.active().unwrap().doc; + let bb = doc.layer(LayerId(r["blended"].as_u64().unwrap())).unwrap().surface().unwrap().content_bounds(); + assert!(bb.x1 <= 200 && bb.y1 <= 200, "{bb:?}"); +} + +/// The budget past the canvas counts every layer's buffers, not just the work-area pixels. +#[test] +fn auto_blend_budget_counts_layers_and_channels() { + // Two RGBA layers: 4 bytes × (2 layers × (4 channels + luma, alpha, weight) + merged + depth). + assert_eq!(blend_bytes_per_pixel(2, 4), 88); + assert!(blend_bytes_per_pixel(5, 4) > blend_bytes_per_pixel(2, 4)); + // A 2^27-pixel area would need about 11 GiB for just two RGBA layers: it keeps to the canvas. + assert!((1u64 << 27).saturating_mul(blend_bytes_per_pixel(2, 4)) > MAX_BLEND_BYTES); + assert_eq!(blend_bytes_per_pixel(u64::MAX, 4), u64::MAX, "saturates instead of overflowing"); +} + +#[test] +fn auto_blend_stack_without_seamless() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 64, "height": 64, "background": "transparent"})).unwrap(); + s.execute("layer.new.layer", json!({"name": "sharp"})).unwrap(); + s.edit("checker", |doc, active| { + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + for y in (0..64).step_by(2) { + for x in (0..64).step_by(2) { + let v = if (x / 2 + y / 2) % 2 == 0 { 0.1 } else { 0.9 }; + surf.fill_rect(Rect::new(x, y, x + 2, y + 2), &[v, v, v, 1.0]); + } + } + Ok(()) + }) + .unwrap(); + let a = s.active().unwrap().active_layer.unwrap(); + s.execute("layer.new.layer", json!({"name": "flat"})).unwrap(); + s.edit("flat", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(0, 0, 64, 64), &[0.5, 0.5, 0.5, 1.0]); + Ok(()) + }) + .unwrap(); + let flat = s.active().unwrap().active_layer.unwrap(); + select(&mut s, &[a, flat]); + let r = s.execute("edit.autoBlendLayers", json!({"method": "stack", "seamlessTones": false})).unwrap(); + assert!(r["blended"].is_null()); + let doc = &s.active().unwrap().doc; + // The detailed layer is sharper everywhere. + let shown = (0..64).filter(|x| doc.layer(a).unwrap().mask.as_ref().unwrap().value(*x, 32) > 0.5).count(); + assert_eq!(shown, 64); + assert_eq!(doc.layer(flat).unwrap().mask.as_ref().unwrap().value(10, 10), 0.0); + assert!(s.execute("edit.autoBlendLayers", json!({"method": "sideways"})).is_err()); +} + +/// A smooth layer (soft blobs on a gradient) and the same picture a few pixels away: the +/// intensity registration finds the shift to a fraction of a pixel at every motion model. +fn smooth_layer(s: &mut Session, name: &str, dx: i32, dy: i32) -> LayerId { + s.execute("layer.new.layer", json!({"name": name})).unwrap(); + s.edit("smooth", |doc, active| { + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + for y in 0..150 { + for x in 0..200 { + let (u, v) = ((x - dx) as f32, (y - dy) as f32); + let blob = (-((u - 90.0).powi(2) + (v - 70.0).powi(2)) / (2.0 * 25.0f32.powi(2))).exp(); + let blob2 = (-((u - 150.0).powi(2) + (v - 40.0).powi(2)) / (2.0 * 15.0f32.powi(2))).exp(); + let g = 0.2 + 0.5 * blob + 0.25 * blob2 + 0.001 * u; + surf.fill_rect(Rect::new(x, y, x + 1, y + 1), &[g, g * 0.8, g * 0.6, 1.0]); + } + } + Ok(()) + }) + .unwrap(); + s.active().unwrap().active_layer.unwrap() +} + +#[test] +fn auto_align_registers_a_smooth_bracket_by_intensity() { + for depth in [8, 16, 32] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 200, "height": 150, "depth": depth, "background": "transparent"})).unwrap(); + let a = smooth_layer(&mut s, "A", 0, 0); + let b = smooth_layer(&mut s, "B", 4, 3); + select(&mut s, &[a, b]); + assert!(s.execute("edit.autoAlignLayers", json!({"registration": "sideways"})).is_err()); + assert!(s.execute("edit.autoAlignLayers", json!({"projection": "cylindrical", "registration": "intensity"})).is_err()); + for (params, model) in [ + (json!({"projection": "reposition", "registration": "intensity"}), "reposition"), + (json!({"registration": "intensity"}), "collage"), + (json!({"projection": "perspective", "registration": "intensity"}), "perspective"), + ] { + let r = s.execute("edit.autoAlignLayers", params).unwrap(); + assert_eq!(r["registration"], "intensity", "depth {depth}: {r}"); + assert_eq!(r["aligned"][0]["model"], model); + let m = r["aligned"][0]["matrix"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect::>(); + assert!((m[2] + 4.0).abs() < 0.25 && (m[5] + 3.0).abs() < 0.25, "depth {depth} {model}: {r}"); + // B now shows A's picture. + let doc = &s.active().unwrap().doc; + let (pa, pb) = (doc.layer(a).unwrap().surface().unwrap().pixel(90, 70), doc.layer(b).unwrap().surface().unwrap().pixel(90, 70)); + assert!((pa[0] - pb[0]).abs() < 0.02, "depth {depth} {model}: {pa:?} vs {pb:?}"); + s.undo(); + } + } +} + +/// Layers with nothing in common are no fit: the intensity registration says so instead of +/// moving them by whatever pose its search box ends at. +#[test] +fn auto_align_rejects_unrelated_layers_instead_of_guessing_a_pose() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 200, "height": 150, "depth": 8, "background": "transparent"})).unwrap(); + let a = smooth_layer(&mut s, "A", 0, 0); + s.execute("layer.new.layer", json!({"name": "stripes"})).unwrap(); + s.edit("stripes", |doc, active| { + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + for y in 0..150 { + for x in 0..200 { + let g = if (x / 7 + y / 11) % 2 == 0 { 0.9 } else { 0.1 }; + surf.fill_rect(Rect::new(x, y, x + 1, y + 1), &[g, g, g, 1.0]); + } + } + Ok(()) + }) + .unwrap(); + let b = s.active().unwrap().active_layer.unwrap(); + select(&mut s, &[a, b]); + for registration in ["intensity", "auto"] { + let err = s.execute("edit.autoAlignLayers", json!({"registration": registration})).unwrap_err().to_string(); + assert_eq!(err, NO_DETAIL, "{registration}"); + } + // A layer that is mostly empty overlaps too little to be placed. + let c = smooth_layer(&mut s, "C", 2, 1); + s.edit("hole", |doc, _| { + let surf = doc.layer_mut(c).unwrap().surface_mut().unwrap(); + surf.fill_rect(Rect::new(0, 0, 200, 120), &[0.0, 0.0, 0.0, 0.0]); + Ok(()) + }) + .unwrap(); + select(&mut s, &[a, c]); + assert_eq!(s.execute("edit.autoAlignLayers", json!({"registration": "intensity"})).unwrap_err().to_string(), NO_DETAIL); +} + +/// Two layers, each sharp on one half: the merged layer takes each half from the sharp layer. +#[test] +fn auto_blend_stack_fuses_the_sharp_halves() { + let checker = |x: i32, y: i32| if (x / 3 + y / 3) % 2 == 0 { 0.2 } else { 0.8 }; + for depth in [8, 16, 32] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 96, "height": 64, "depth": depth, "background": "transparent"})).unwrap(); + let mut ids = Vec::new(); + for (name, sharp_left) in [("left", true), ("right", false)] { + s.execute("layer.new.layer", json!({"name": name})).unwrap(); + s.edit(name, |doc, active| { + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + for y in 0..64 { + for x in 0..96 { + // The sharp half is the checker, the other half its local mean (flat gray). + let v = if (x < 48) == sharp_left { checker(x, y) } else { 0.5 }; + surf.fill_rect(Rect::new(x, y, x + 1, y + 1), &[v, v, v, 1.0]); + } + } + Ok(()) + }) + .unwrap(); + ids.push(s.active().unwrap().active_layer.unwrap()); + } + select(&mut s, &ids); + for halo in [0.0, 2.0] { + let r = s.execute("edit.autoBlendLayers", json!({"method": "stack", "haloControl": halo})).unwrap(); + let doc = &s.active().unwrap().doc; + let blended = doc.layer(LayerId(r["blended"].as_u64().unwrap())).unwrap().surface().unwrap(); + for (x, y) in [(10, 20), (20, 40), (76, 20), (85, 40)] { + let px = blended.pixel(x, y); + assert!((px[0] - checker(x, y)).abs() < 0.08, "depth {depth} halo {halo} ({x},{y}): {px:?}"); + assert!((px[3] - 1.0).abs() < 1e-3, "{px:?}"); + } + // The masks still pick per pixel. + assert_eq!(doc.layer(ids[0]).unwrap().mask.as_ref().unwrap().value(10, 20), 1.0); + assert_eq!(doc.layer(ids[1]).unwrap().mask.as_ref().unwrap().value(85, 40), 1.0); + s.undo(); + assert!(s.active().unwrap().doc.layer(ids[0]).unwrap().mask.is_none()); + } + for bad in [json!(-1), json!(9), json!("hard")] { + assert!(s.execute("edit.autoBlendLayers", json!({"method": "stack", "haloControl": bad})).is_err(), "{bad}"); + } + } +} + +/// Three layers, each sharp in one third: the Depth layer says which, black to white from +/// the bottom layer to the top, hidden, and undone with the rest. +#[test] +fn auto_blend_stack_depth_map() { + for depth in [8, 16, 32] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 96, "height": 48, "depth": depth, "background": "transparent"})).unwrap(); + let mut ids = Vec::new(); + for k in 0..3 { + s.execute("layer.new.layer", json!({"name": format!("L{k}")})).unwrap(); + s.edit("third", |doc, active| { + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + for y in 0..48 { + for x in 0..96 { + let v = if x / 32 == k && ((x / 2) + (y / 2)) % 2 == 0 { + 0.2 + } else if x / 32 == k { + 0.8 + } else { + 0.5 + }; + surf.fill_rect(Rect::new(x, y, x + 1, y + 1), &[v, v, v, 1.0]); + } + } + Ok(()) + }) + .unwrap(); + ids.push(s.active().unwrap().active_layer.unwrap()); + } + select(&mut s, &ids); + assert!(s.execute("edit.autoBlendLayers", json!({"method": "panorama", "depthMap": true})).is_err()); + for seamless in [false, true] { + let r = s.execute("edit.autoBlendLayers", json!({"method": "stack", "seamlessTones": seamless, "depthMap": true})).unwrap(); + let doc = &s.active().unwrap().doc; + let d = doc.layer(LayerId(r["depth"].as_u64().unwrap())).unwrap(); + assert!(!d.visible && d.name.starts_with("Depth"), "depth {depth}: {} visible {} {r}", d.name, d.visible); + let surf = d.surface().unwrap(); + for (x, want) in [(8, 0.0), (48, 0.5), (88, 1.0)] { + let px = surf.pixel(x, 24); + assert!((px[0] - want).abs() < 0.2 && (px[3] - 1.0).abs() < 1e-3, "depth {depth} seamless {seamless} x {x}: {px:?}"); + } + assert_eq!(r["blended"].is_null(), !seamless); + if seamless { + // The merged layer sits above the depth layer and is the active one. + assert_eq!(s.active().unwrap().active_layer, Some(LayerId(r["blended"].as_u64().unwrap()))); + } + s.undo(); + assert!(s.active().unwrap().doc.layer(LayerId(r["depth"].as_u64().unwrap())).is_none()); + } + } +} diff --git a/crates/engine/src/analysis_cmds.rs b/crates/engine/src/cmd/analysis_cmds.rs similarity index 100% rename from crates/engine/src/analysis_cmds.rs rename to crates/engine/src/cmd/analysis_cmds.rs diff --git a/crates/engine/src/analysis_cmds/tests.rs b/crates/engine/src/cmd/analysis_cmds/tests.rs similarity index 100% rename from crates/engine/src/analysis_cmds/tests.rs rename to crates/engine/src/cmd/analysis_cmds/tests.rs diff --git a/crates/engine/src/artboard_cmds.rs b/crates/engine/src/cmd/artboard_cmds.rs similarity index 100% rename from crates/engine/src/artboard_cmds.rs rename to crates/engine/src/cmd/artboard_cmds.rs diff --git a/crates/engine/src/artboard_cmds/tests.rs b/crates/engine/src/cmd/artboard_cmds/tests.rs similarity index 100% rename from crates/engine/src/artboard_cmds/tests.rs rename to crates/engine/src/cmd/artboard_cmds/tests.rs diff --git a/crates/engine/src/cmd/atn_cmds.rs b/crates/engine/src/cmd/atn_cmds.rs new file mode 100644 index 0000000000..32e5405d1a --- /dev/null +++ b/crates/engine/src/cmd/atn_cmds.rs @@ -0,0 +1,146 @@ +//! Photoshop Actions files (`.atn`): Load Actions (`actions.load`) and Save Actions +//! (`actions.save`), plus the two step commands a Photoshop set needs: `actions.stopMessage` +//! (Photoshop's Insert Stop) and `actions.photoshopStep` (a step PhotoCraft has no command for +//! yet, kept verbatim so Save Actions writes it back unchanged). +//! +//! Parsing and writing live in `photocraft-psd` (`atn`); this module maps Photoshop *events* +//! (`gaussianBlur` with `Rds`, `make` of an adjustment layer, `set` of the selection…) onto +//! PhotoCraft commands and back. An event is keyed by both its four-character code (`GsnB`, +//! older files) and its string name (`gaussianBlur`, Photoshop 2024 and later), as the two are +//! interchangeable in Photoshop. The table ([`EVENTS`]) is bidirectional: a step that was +//! imported exports to the same event. Events outside it become `actions.photoshopStep` steps, +//! which fail at playback with the step's Photoshop name, so an action never silently skips +//! work; tool selections and other steps with no document effect are imported switched off. +//! +//! Layer references by name (`select` of layer "Shadow") become `{"layer": "Shadow"}`, which +//! `commands::layer_param` resolves in whatever document the action plays on (#219). A switch +//! to another open document (`select` of `Dcmn` by offset) becomes `document.activate +//! {"offset"}`, the tab that many places from the active one (#7103). + +use photocraft_psd::atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}; +use photocraft_psd::descriptor::{Class, Descriptor, Id, ReferenceItem, UnicodeString, Value as D}; +use serde_json::{Map, Value, json}; + +use crate::actions_cmds::Action; +use crate::commands::CommandSpec; +use crate::{EngineError, Result, Session}; + +mod adjustments; +mod convert; +mod descriptors; +mod events; +mod fields; +mod files; +mod steps_doc; +mod steps_image; +mod steps_layer; +mod steps_make; +mod tables; + +#[cfg(test)] +use adjustments::selective_from; +pub use convert::{Imported, Skipped, Unsupported, export, function_key_name, import, parse_function_key}; +#[cfg(test)] +use convert::{MAX_NAME_CHARS, export_item, normalise}; +#[cfg(test)] +use descriptors::{ + PCT, PT, PX, ang, class, class_ref, code, color_desc, color_hex, desc, enm, get_bool, get_enum, get_list, get_num, get_obj, get_ref, layer_ref, long, + name_ref, path_text, path_value, pct, px, target_ref, text, trimmed, +}; +use descriptors::{jbool, jstr}; +#[cfg(test)] +use events::{EVENTS, event_and_descriptor, event_for}; +#[cfg(test)] +use fields::Mapped; +use files::{load, save}; +#[cfg(test)] +use steps_doc::crop_from; +#[cfg(test)] +use steps_image::transform_to; +#[cfg(test)] +use steps_layer::quick_mask_ref; +#[cfg(test)] +use steps_make::make_from; +#[cfg(test)] +use tables::{blend_label, blend_ps, channel_ref}; + +/// A step PhotoCraft cannot play yet, kept verbatim (`{"event", "name", "descriptor": base64}`). +pub const PHOTOSHOP_STEP: &str = "actions.photoshopStep"; +/// Photoshop's Insert Stop: `{"message", "allowContinue"}`. +pub const STOP_MESSAGE: &str = "actions.stopMessage"; +/// The set name Save Actions uses for actions that came from no set. +pub const DEFAULT_SET: &str = "PhotoCraft Actions"; + +fn bad(cmd: &str, msg: impl Into) -> EngineError { + EngineError::BadParams { cmd: cmd.into(), msg: msg.into() } +} + +fn always(_: &Session) -> std::result::Result<(), String> { + Ok(()) +} + +fn stop_message(_: &mut Session, p: &Value) -> Result { + let message = jstr(p, "message").unwrap_or("Stop").to_string(); + if jbool(p, "allowContinue").unwrap_or(false) { + Ok(json!({"message": message, "continued": true})) + } else { + Err(EngineError::Other(format!("stopped by the action: {message}"))) + } +} + +fn photoshop_step_run(_: &mut Session, p: &Value) -> Result { + let name = jstr(p, "name").filter(|n| !n.is_empty()).unwrap_or("this step"); + let event = jstr(p, "event").unwrap_or("?"); + Err(EngineError::Other(format!("Photoshop step \"{name}\" ({event}) has no PhotoCraft equivalent yet; switch it off in the Actions panel to skip it"))) +} + +pub fn specs() -> Vec { + vec![ + CommandSpec { + id: "actions.load", + label: "Load Actions…", + menu: &[], + shortcut: None, + params: r##"{"path":".atn file"?,"data":base64 bytes?,"set":name? (override the file's set name),"replace":bool=true (replace the actions of a set of the same name)} → {set, actions:[names], steps, unsupported:[{action, step, event, name}], functionKeys:[{action, key}], warnings}. Photoshop steps PhotoCraft cannot play become actions.photoshopStep steps (kept for Save Actions; they fail at playback with the step's name); tool selections and other steps with no document effect are imported switched off. Layer references by name replay in any document."##, + enabled: always, + run: load, + journal: false, + }, + CommandSpec { + id: "actions.save", + label: "Save Actions…", + menu: &[], + shortcut: None, + params: r##"{"path":".atn file"? (else the bytes come back as base64 `data`),"set":name? (that set's actions; default: every action, as the set "PhotoCraft Actions"),"action":name|index? (one action),"skipUnsupported":bool=false (leave out steps with no Photoshop equivalent instead of failing)} → {set, actions:[names], steps, bytes, skipped:[{action, step, id}], path|data}"##, + enabled: always, + run: save, + journal: false, + }, + CommandSpec { + id: STOP_MESSAGE, + label: "Stop", + menu: &[], + shortcut: None, + params: r##"{"message":str,"allowContinue":bool=false} (Photoshop's Insert Stop: a step that shows the message; headless playback continues when allowContinue is set and otherwise stops the action with the message)"##, + enabled: always, + run: stop_message, + journal: true, + }, + CommandSpec { + id: PHOTOSHOP_STEP, + label: "Photoshop Step", + menu: &[], + shortcut: None, + params: r##"{"event":id,"name":str,"descriptor":base64?} (a step from a .atn file PhotoCraft has no command for: fails at playback, written back by actions.save)"##, + enabled: always, + run: photoshop_step_run, + journal: true, + }, + ] +} + +#[cfg(test)] +mod tests; + +#[cfg(test)] +mod layer_props_tests; diff --git a/crates/engine/src/cmd/atn_cmds/adjustments.rs b/crates/engine/src/cmd/atn_cmds/adjustments.rs new file mode 100644 index 0000000000..321ca5ebc4 --- /dev/null +++ b/crates/engine/src/cmd/atn_cmds/adjustments.rs @@ -0,0 +1,515 @@ +use super::descriptors::{color_desc, color_hex, desc, enm, get_bool, get_enum, get_list, get_num, get_obj, jbool, jnum, jstr, long, num, pct, text}; +use super::fields::{F, Kind, Mapped, fields_from, fields_to, step}; +use super::tables::{CHANNELS, channel_key, channel_ref, lookup, lookup_back}; +use super::*; + +// ------------------------------------------------------------------ adjustments + +/// The `Adjs` entries of a per-channel adjustment (Levels, Curves): `(channel key, entry)`. +fn per_channel(d: &Descriptor) -> Option, &Descriptor)>> { + get_list(d, "Adjs")? + .iter() + .map(|v| match v { + D::Descriptor(e) => Some((channel_key(e)?, e)), + _ => None, + }) + .collect() +} + +pub(super) fn levels_from(d: &Descriptor) -> Option { + if get_bool(d, "Auto") == Some(true) { + return None; + } + let mut out = Map::new(); + for (chan, e) in per_channel(d)? { + let mut m = Map::new(); + if let Some(i) = get_list(e, "Inpt") { + if let Some(v) = i.first().and_then(num) { + m.insert("inBlack".into(), v.into()); + } + if let Some(v) = i.get(1).and_then(num) { + m.insert("inWhite".into(), v.into()); + } + } + if let Some(o) = get_list(e, "Otpt") { + if let Some(v) = o.first().and_then(num) { + m.insert("outBlack".into(), v.into()); + } + if let Some(v) = o.get(1).and_then(num) { + m.insert("outWhite".into(), v.into()); + } + } + if let Some(g) = get_num(e, "Gmm ") { + m.insert("gamma".into(), g.into()); + } + match chan { + None => out.extend(m), + Some(k) => { + out.insert(k.into(), Value::Object(m)); + } + } + } + Some(Value::Object(out)) +} + +fn levels_entry(chan: Option<&str>, p: &Value) -> Descriptor { + let mut e = desc("LvlA").with("Chnl", channel_ref(chan)); + if jnum(p, "inBlack").is_some() || jnum(p, "inWhite").is_some() { + e = e.with("Inpt", D::List(vec![long(jnum(p, "inBlack").unwrap_or(0.0)), long(jnum(p, "inWhite").unwrap_or(255.0))])); + } + if let Some(g) = jnum(p, "gamma") { + e = e.with("Gmm ", D::Double(g)); + } + if jnum(p, "outBlack").is_some() || jnum(p, "outWhite").is_some() { + e = e.with("Otpt", D::List(vec![long(jnum(p, "outBlack").unwrap_or(0.0)), long(jnum(p, "outWhite").unwrap_or(255.0))])); + } + e +} + +pub(super) fn levels_to(p: &Value) -> Option { + let mut entries = vec![D::Descriptor(levels_entry(None, p))]; + for (_, k) in CHANNELS { + if let Some(c) = p.get(*k).filter(|v| v.is_object()) { + entries.push(D::Descriptor(levels_entry(Some(k), c))); + } + } + Some(desc("Lvls").with("presetKind", enm("presetKindType", "presetKindCustom")).with("Adjs", D::List(entries))) +} + +fn curve_points(e: &Descriptor) -> Option { + let pts: Option> = get_list(e, "Crv ")? + .iter() + .map(|v| match v { + D::Descriptor(pt) => Some(json!([get_num(pt, "Hrzn")?, get_num(pt, "Vrtc")?])), + _ => None, + }) + .collect(); + pts.map(Value::Array) +} + +fn curves_from(d: &Descriptor) -> Option { + let mut out = Map::new(); + for (chan, e) in per_channel(d)? { + let pts = curve_points(e)?; + out.insert(chan.unwrap_or("points").into(), pts); + } + Some(Value::Object(out)) +} + +fn curve_entry(chan: Option<&str>, pts: &Value) -> Option { + let list: Option> = pts + .as_array()? + .iter() + .map(|pt| { + let a = pt.as_array()?; + Some(D::Descriptor(desc("Pnt ").with("Hrzn", D::Double(a.first()?.as_f64()?)).with("Vrtc", D::Double(a.get(1)?.as_f64()?)))) + }) + .collect(); + Some(desc("CrvA").with("Chnl", channel_ref(chan)).with("Crv ", D::List(list?))) +} + +fn curves_to(p: &Value) -> Option { + let mut entries = Vec::new(); + if let Some(pts) = p.get("points") { + entries.push(D::Descriptor(curve_entry(None, pts)?)); + } + for (_, k) in CHANNELS { + if let Some(pts) = p.get(*k) { + entries.push(D::Descriptor(curve_entry(Some(k), pts)?)); + } + } + Some(desc("Crvs").with("presetKind", enm("presetKindType", "presetKindCustom")).with("Adjs", D::List(entries))) +} + +/// The hue key of a Hue/Saturation adjustment (`Hst2`): Photoshop's `H ` (#8302). +const HUE_KEY: &str = "H "; + +pub(super) const HUE_RANGES: [&str; 6] = ["reds", "yellows", "greens", "cyans", "blues", "magentas"]; + +fn hue_sat_from(d: &Descriptor) -> Option { + let mut out = Map::new(); + if let Some(c) = get_bool(d, "Clrz") { + out.insert("colorize".into(), c.into()); + } + for e in get_list(d, "Adjs").unwrap_or(&[]) { + let D::Descriptor(e) = e else { return None }; + let mut m = Map::new(); + // Photoshop's hue key is `H ` (stringID "hue", #8302); PhotoCraft wrote `Hue ` before, + // so its own older files still read. + let hue = get_num(e, HUE_KEY).or_else(|| get_num(e, "Hue ")); + for (param, v) in [("hue", hue), ("saturation", get_num(e, "Strt")), ("lightness", get_num(e, "Lght"))] { + if let Some(v) = v { + m.insert(param.into(), v.into()); + } + } + match get_num(e, "LclR") { + None => out.extend(m), + Some(r) => { + let name = *HUE_RANGES.get((r as usize).checked_sub(1)?)?; + if let (Some(a), Some(b), Some(c), Some(dd)) = (get_num(e, "BgnR"), get_num(e, "BgnS"), get_num(e, "EndS"), get_num(e, "EndR")) { + m.insert("range".into(), json!([a, b, c, dd])); + } + out.insert(name.into(), Value::Object(m)); + } + } + } + Some(Value::Object(out)) +} + +fn hue_entry(p: &Value, range: Option<(usize, &Value)>) -> Option { + let mut e = desc("Hst2"); + if let Some((i, r)) = range { + e = e.with("LclR", long(i as f64 + 1.0)); + if let Some(a) = r.get("range").and_then(Value::as_array) + && a.len() == 4 + { + for (k, v) in ["BgnR", "BgnS", "EndS", "EndR"].iter().zip(a) { + e = e.with(k, long(v.as_f64()?)); + } + } + } + for (key, param) in [(HUE_KEY, "hue"), ("Strt", "saturation"), ("Lght", "lightness")] { + e = e.with(key, long(jnum(p, param).unwrap_or(0.0))); + } + Some(e) +} + +// Exporters leave out a param the step doesn't set only where Photoshop plays the missing key +// as PhotoCraft's default (checked against Photoshop: Fill opacity and mode, Crop delete, +// Selective Color method, Channel Mixer monochrome, Paint Bucket contiguous; Gradient Map +// reverse and dither, which Photoshop itself leaves out when off). Elsewhere they +// write PhotoCraft's default, as Photoshop plays a missing key differently (Color Balance +// preserve luminosity off, Canvas Size anchored top left, Apply Image Normal) or refuses the +// step (Paint Bucket without a tolerance). +fn hue_sat_to(p: &Value) -> Option { + let d = desc("HStr").with("presetKind", enm("presetKindType", "presetKindCustom")).with("Clrz", D::Boolean(jbool(p, "colorize").unwrap_or(false))); + let mut entries = vec![D::Descriptor(hue_entry(p, None)?)]; + for (i, name) in HUE_RANGES.iter().enumerate() { + if let Some(r) = p.get(*name).filter(|v| v.is_object()) { + entries.push(D::Descriptor(hue_entry(r, Some((i, r)))?)); + } + } + Some(d.with("Adjs", D::List(entries))) +} + +fn triple(d: &Descriptor, k: &str) -> Option { + let l = get_list(d, k)?; + let v: Option> = l.iter().map(num).collect(); + Some(json!(v?)) +} + +fn triple_to(p: &Value, k: &str) -> Option { + Some(D::List(p.get(k)?.as_array()?.iter().map(|v| v.as_f64().map(long)).collect::>>()?)) +} + +fn color_balance_from(d: &Descriptor) -> Option { + let mut out = Map::new(); + for (key, param) in [("ShdL", "shadows"), ("MdtL", "midtones"), ("HghL", "highlights")] { + if let Some(v) = triple(d, key) { + out.insert(param.into(), v); + } + } + if let Some(b) = get_bool(d, "PrsL") { + out.insert("preserveLuminosity".into(), b.into()); + } + Some(Value::Object(out)) +} + +fn color_balance_to(p: &Value) -> Option { + let mut d = desc("ClrB"); + for (key, param) in [("ShdL", "shadows"), ("MdtL", "midtones"), ("HghL", "highlights")] { + d = d.with(key, triple_to(p, param).unwrap_or_else(|| D::List(vec![long(0.0), long(0.0), long(0.0)]))); + } + Some(d.with("PrsL", D::Boolean(jbool(p, "preserveLuminosity").unwrap_or(true)))) +} + +const BW: &[F] = &[ + F("Rd ", "reds", Kind::Long), + F("Yllw", "yellows", Kind::Long), + F("Grn ", "greens", Kind::Long), + F("Cyn ", "cyans", Kind::Long), + F("Bl ", "blues", Kind::Long), + F("Mgnt", "magentas", Kind::Long), + F("useTint", "tint", Kind::Bool), + F("tintColor", "tintColor", Kind::Color), +]; + +fn mixer_channel(e: &Descriptor) -> Option { + Some(json!([get_num(e, "Rd ").unwrap_or(0.0), get_num(e, "Grn ").unwrap_or(0.0), get_num(e, "Bl ").unwrap_or(0.0), get_num(e, "Cnst").unwrap_or(0.0)])) +} + +fn channel_mixer_from(d: &Descriptor) -> Option { + let mut out = Map::new(); + for (key, param) in [("Rd ", "red"), ("Grn ", "green"), ("Bl ", "blue"), ("Gry ", "gray")] { + if let Some(e) = get_obj(d, key) { + out.insert(param.into(), mixer_channel(e)?); + } + } + if let Some(m) = get_bool(d, "Mnch") { + out.insert("monochrome".into(), m.into()); + } + Some(Value::Object(out)) +} + +fn channel_mixer_to(p: &Value) -> Option { + let mut d = desc("ChnM").with("presetKind", enm("presetKindType", "presetKindCustom")); + for (key, param) in [("Rd ", "red"), ("Grn ", "green"), ("Bl ", "blue"), ("Gry ", "gray")] { + if let Some(a) = p.get(param).and_then(Value::as_array) { + let v = |i: usize| a.get(i).and_then(Value::as_f64).unwrap_or(0.0); + d = d.with(key, D::Descriptor(desc("ChMx").with("Rd ", pct(v(0))).with("Grn ", pct(v(1))).with("Bl ", pct(v(2))).with("Cnst", pct(v(3))))); + } + } + if let Some(m) = jbool(p, "monochrome") { + d = d.with("Mnch", D::Boolean(m)); + } + Some(d) +} + +/// Photoshop's `Clrs` colour-range enumeration. Yellows is `Ylws` (`Yllw` is the yellow ink +/// key); earlier PhotoCraft builds wrote `Yllw`, which import still reads (#6745). +const SELECTIVE_RANGES: &[(&str, &str)] = &[ + ("Rds", "reds"), + ("Ylws", "yellows"), + ("Grns", "greens"), + ("Cyns", "cyans"), + ("Bls", "blues"), + ("Mgnt", "magentas"), + ("Whts", "whites"), + ("Ntrl", "neutrals"), + ("Blks", "blacks"), +]; + +pub(super) fn selective_from(d: &Descriptor) -> Option { + let mut out = Map::new(); + if let Some(m) = get_enum(d, "Mthd") { + out.insert("method".into(), (if m == "Absl" { "absolute" } else { "relative" }).into()); + } + for e in get_list(d, "ClrC").unwrap_or(&[]) { + let D::Descriptor(e) = e else { return None }; + let range = get_enum(e, "Clrs")?; + let name = lookup(SELECTIVE_RANGES, if range == "Yllw" { "Ylws" } else { &range })?; + let v = |k: &str| get_num(e, k).unwrap_or(0.0); + out.insert(name.into(), json!([v("Cyn "), v("Mgnt"), v("Yllw"), v("Blck")])); + } + Some(Value::Object(out)) +} + +fn selective_to(p: &Value) -> Option { + // Match command execution: scalar components override only the selected range, `relative` + // takes precedence over `method`, and invalid values must not become a different edit. + let photocraft_doc::Adjustment::SelectiveColor { relative, adjustments } = crate::adjust_cmds::selective_from_params(p, None).ok()? else { + return None; + }; + let mut list = Vec::new(); + for (name, row) in crate::adjust_cmds::RANGES.into_iter().zip(adjustments) { + if p.get(name).is_some_and(|v| !v.is_null()) || jstr(p, "colors") == Some(name) { + let ps = lookup_back(SELECTIVE_RANGES, name)?; + let [cyan, magenta, yellow, black] = row.map(f64::from); + list.push(D::Descriptor( + desc("ClrC") + .with("Clrs", enm("Clrs", ps)) + .with("Cyn ", pct(cyan)) + .with("Mgnt", pct(magenta)) + .with("Yllw", pct(yellow)) + .with("Blck", pct(black)), + )); + } + } + Some( + desc("SlcC") + .with("presetKind", enm("presetKindType", "presetKindCustom")) + .with("Mthd", enm("CrcM", if relative { "Rltv" } else { "Absl" })) + .with("ClrC", D::List(list)), + ) +} + +/// Gradient Map: the gradient's colour stops at 0..4096 → `stops: [[0..1, "#rrggbb"], …]`. +fn gradient_map_from(d: &Descriptor) -> Option { + let grad = get_obj(d, "Grad")?; + let stops: Option> = get_list(grad, "Clrs")? + .iter() + .map(|v| match v { + D::Descriptor(stop) => Some(json!([(get_num(stop, "Lctn")? / 4096.0).clamp(0.0, 1.0), color_hex(get_obj(stop, "Clr ")?)?])), + _ => None, + }) + .collect(); + let mut out = json!({"stops": stops?}); + if let Some(r) = get_bool(d, "Rvrs") { + out["reverse"] = json!(r); + } + if let Some(dd) = get_bool(d, "Dthr") { + out["dither"] = json!(dd); + } + Some(out) +} + +fn gradient_map_to(p: &Value) -> Option { + let stops: Option> = p + .get("stops")? + .as_array()? + .iter() + .map(|st| { + let a = st.as_array()?; + Some(D::Descriptor( + desc("Clrt") + .with("Clr ", D::Descriptor(color_desc(a.get(1)?.as_str()?)?)) + .with("Type", enm("Clry", "UsrS")) + .with("Lctn", long((a.first()?.as_f64()? * 4096.0).round())) + .with("Mdpn", long(50.0)), + )) + }) + .collect(); + let transparency = D::List(vec![ + D::Descriptor(desc("TrnS").with("Opct", pct(100.0)).with("Lctn", long(0.0)).with("Mdpn", long(50.0))), + D::Descriptor(desc("TrnS").with("Opct", pct(100.0)).with("Lctn", long(4096.0)).with("Mdpn", long(50.0))), + ]); + let grad = desc("Grdn") + .with("Nm ", text("Custom")) + .with("GrdF", enm("GrdF", "CstS")) + .with("Intr", D::Double(4096.0)) + .with("Clrs", D::List(stops?)) + .with("Trns", transparency); + let mut d = desc("GdMp").with("Grad", D::Descriptor(grad)); + if let Some(r) = jbool(p, "reverse") { + d = d.with("Rvrs", D::Boolean(r)); + } + if let Some(dd) = jbool(p, "dither") { + d = d.with("Dthr", D::Boolean(dd)); + } + Some(d) +} + +/// An adjustment: its Photoshop class (usually also the direct event's code; Black & White and +/// Photo Filter run by name), the command suffix (`image.adjustments.`, `layer.newAdjustmentLayer.`), and +/// the converters between the adjustment descriptor and the command params. +pub(super) struct Adjustment { + pub(super) class: &'static str, + pub(super) suffix: &'static str, + pub(super) from: fn(&Descriptor) -> Option, + pub(super) to: fn(&Value) -> Option, +} + +macro_rules! adj_fields { + ($class:literal, $suffix:literal, $fields:expr) => { + Adjustment { class: $class, suffix: $suffix, from: |d| fields_from(d, $fields).map(Value::Object), to: |p| fields_to(p, $fields, desc($class)) } + }; +} + +const ADJUSTMENTS: &[Adjustment] = &[ + Adjustment { class: "Lvls", suffix: "levels", from: levels_from, to: levels_to }, + Adjustment { class: "Crvs", suffix: "curves", from: curves_from, to: curves_to }, + Adjustment { class: "HStr", suffix: "hueSaturation", from: hue_sat_from, to: hue_sat_to }, + adj_fields!("BrgC", "brightnessContrast", &[F("Brgh", "brightness", Kind::Long), F("Cntr", "contrast", Kind::Long), F("useLegacy", "legacy", Kind::Bool)]), + adj_fields!("Thrs", "threshold", &[F("Lvl ", "level", Kind::Long)]), + adj_fields!("Pstr", "posterize", &[F("Lvls", "levels", Kind::Long)]), + adj_fields!("Invr", "invert", &[]), + Adjustment { class: "ClrB", suffix: "colorBalance", from: color_balance_from, to: color_balance_to }, + adj_fields!("Vbrn", "vibrance", &[F("vibrance", "vibrance", Kind::Long), F("Strt", "saturation", Kind::Long)]), + adj_fields!("Exps", "exposure", &[F("Exps", "exposure", Kind::Dbl), F("Ofst", "offset", Kind::Dbl), F("gammaCorrection", "gamma", Kind::Dbl)]), + Adjustment { class: "PhtF", suffix: "photoFilter", from: |d| fields_from(d, PHOTO_FILTER_FIELDS).map(Value::Object), to: photo_filter_to }, + adj_fields!("BanW", "blackWhite", BW), + Adjustment { class: "ChnM", suffix: "channelMixer", from: channel_mixer_from, to: channel_mixer_to }, + Adjustment { class: "SlcC", suffix: "selectiveColor", from: selective_from, to: selective_to }, + Adjustment { class: "GdMp", suffix: "gradientMap", from: gradient_map_from, to: gradient_map_to }, +]; + +/// Adjustment classes PhotoCraft once exported, with the class Photoshop uses. Measured in +/// Photoshop (#8481): a Make whose Black & White type is `BlnW` fails ("the command Make is not +/// currently available"), `BanW` runs. Import keeps accepting them so actions saved before still +/// load; export never writes them. +const LEGACY_CLASSES: &[(&str, &str)] = &[("BlnW", "BanW")]; + +/// The adjustment with Photoshop class `c`, or the one an old PhotoCraft class stands for. +pub(super) fn adjustment_by_class(c: &str) -> Option<&'static Adjustment> { + let c = c.trim_end(); + let c = LEGACY_CLASSES.iter().find(|(old, _)| *old == c).map_or(c, |(_, class)| class); + ADJUSTMENTS.iter().find(|a| a.class.trim_end() == c) +} + +const PHOTO_FILTER_FIELDS: &[F] = &[F("Clr ", "color", Kind::Color), F("Dnst", "density", Kind::Long), F("PrsL", "preserveLuminosity", Kind::Bool)]; + +/// A `PhtF` step whose params carry a `filter` preset without an explicit `color`: the descriptor +/// form is colour-only (Photoshop stores no preset key — the `phfl` notes in `crates/io` conclude +/// the same from its CS2 oracles), so the resolved colour must be written, or re-imported playback +/// falls back to the default warming filter. With both present, the explicit colour wins, as when +/// running the command. An unknown preset id keeps the old export (no colour) instead of failing. +fn photo_filter_to(p: &Value) -> Option { + let mut p = p.clone(); + if p.get("color").is_none() { + let hex = p.get("filter").and_then(Value::as_str).and_then(preset_color); + if let (Some(hex), Some(o)) = (hex, p.as_object_mut()) { + o.insert("color".into(), hex.into()); + } + } + fields_to(&p, PHOTO_FILTER_FIELDS, desc("PhtF")) +} + +/// The preset id's resolved `#rrggbb`, or none (no id given, or an unknown one). +fn preset_color(id: &str) -> Option { + crate::adjust_params::PHOTO_FILTERS.iter().find(|f| f.0 == id).map(|(_, _, rgb)| format!("#{:02x}{:02x}{:02x}", rgb[0], rgb[1], rgb[2])) +} + +pub(super) fn adjustment_by_suffix(suffix: &str) -> Option<&'static Adjustment> { + ADJUSTMENTS.iter().find(|a| a.suffix == suffix) +} + +// Events whose target depends on the descriptor (`make`, `set`, `select`…): custom converters. + +pub(super) fn adjustment_steps(a: &Adjustment, prefix: &str, type_desc: Option<&Descriptor>) -> Mapped { + let params = match type_desc { + Some(t) if get_enum(t, "presetKind").as_deref() != Some("presetKindDefault") => match (a.from)(t) { + Some(p) => p, + None => return Mapped::Unsupported { harmless: false }, + }, + _ => json!({}), + }; + step(&format!("{prefix}{}", a.suffix), params) +} + +/// Shadows/Highlights (`adaptCorrect`, #5830): the shadow and highlight tones are `shadowMode` +/// and `highlightMode` objects (amount and width in %, radius in px), then the black and white +/// clips (%), midtone contrast (`center`) and colour correction. Each key is read as its char ID +/// or its string ID, whichever the file used; absent keys keep the command's defaults. +const SHADOWS_HIGHLIGHTS_TONES: [(&str, &str, &str); 2] = [("sdwM", "shadowMode", "shadow"), ("hglM", "highlightMode", "highlight")]; + +const SHADOWS_HIGHLIGHTS_TONE: [(&str, &str, &str); 3] = [("Amnt", "amount", "Amount"), ("Wdth", "width", "Tone"), ("Rds ", "radius", "Radius")]; + +const SHADOWS_HIGHLIGHTS: [(&str, &str, &str); 4] = + [("BlcC", "blackClip", "blackClip"), ("WhtC", "whiteClip", "whiteClip"), ("Cntr", "center", "midtone"), ("ClrC", "colorCorrection", "color")]; + +pub(super) fn shadows_highlights_from(d: &Descriptor) -> Mapped { + let mut m = Map::new(); + for (code, name, prefix) in SHADOWS_HIGHLIGHTS_TONES { + let Some(t) = get_obj(d, code).or_else(|| get_obj(d, name)) else { continue }; + for (code, name, suffix) in SHADOWS_HIGHLIGHTS_TONE { + if let Some(v) = get_num(t, code).or_else(|| get_num(t, name)) { + m.insert(format!("{prefix}{suffix}"), Value::from(v)); + } + } + } + for (code, name, param) in SHADOWS_HIGHLIGHTS { + if let Some(v) = get_num(d, code).or_else(|| get_num(d, name)) { + m.insert(param.into(), Value::from(v)); + } + } + step("image.adjustments.shadowsHighlights", Value::Object(m)) +} + +pub(super) fn shadows_highlights_to(_: &str, p: &Value) -> Option { + let mut d = desc("null"); + for (_, name, prefix) in SHADOWS_HIGHLIGHTS_TONES { + let mut t = desc("adaptCorrectTones"); + for (_, key, suffix) in SHADOWS_HIGHLIGHTS_TONE { + if let Some(v) = jnum(p, &format!("{prefix}{suffix}")) { + t = t.with(key, if suffix == "Radius" { long(v) } else { pct(v) }); + } + } + d = d.with(name, D::Descriptor(t)); + } + for (_, key, param) in SHADOWS_HIGHLIGHTS { + if let Some(v) = jnum(p, param) { + d = d.with(key, if matches!(param, "midtone" | "color") { long(v) } else { D::Double(v) }); + } + } + Some(d) +} diff --git a/crates/engine/src/cmd/atn_cmds/convert.rs b/crates/engine/src/cmd/atn_cmds/convert.rs new file mode 100644 index 0000000000..b23c578ac6 --- /dev/null +++ b/crates/engine/src/cmd/atn_cmds/convert.rs @@ -0,0 +1,273 @@ +use super::descriptors::{desc, get_obj, jstr}; +use super::events::{event_and_descriptor, event_for}; +use super::fields::Mapped; +use super::*; + +// ------------------------------------------------------------------ import + +/// A step with no PhotoCraft equivalent. +#[derive(Clone, Debug, PartialEq, serde::Serialize)] +pub struct Unsupported { + pub action: String, + pub step: usize, + pub event: String, + pub name: String, +} + +/// What a `.atn` file imports to. +#[derive(Clone, Debug, Default)] +pub struct Imported { + pub set: String, + pub actions: Vec, + /// Function keys the file assigns, as `(action name, key)`. + pub function_keys: Vec<(String, String)>, + pub unsupported: Vec, + pub warnings: Vec, +} + +fn photoshop_step(item: &AtnItem) -> (String, Value) { + let descriptor = item.descriptor.as_ref().map(|d| photocraft_paint::tile::b64_encode(&d.to_bytes())); + let event_kind = match &item.event { + AtnEvent::Code(_) => "code", + AtnEvent::Name(_) => "name", + }; + (PHOTOSHOP_STEP.into(), json!({"event": item.event.id(), "eventKind": event_kind, "name": item.label(), "descriptor": descriptor})) +} + +/// Integral floats become integers (`2.0` → `2`), as the commands' own docs and recordings +/// use, so an imported step reads and compares like a recorded one. +pub(super) fn normalise(v: &mut Value) { + match v { + Value::Number(n) => { + if let Some(f) = n.as_f64() + && f.fract() == 0.0 + && f.abs() < 9.0e15 + && n.as_i64().is_none() + { + *v = Value::from(f as i64); + } + } + Value::Array(a) => a.iter_mut().for_each(normalise), + Value::Object(o) => o.values_mut().for_each(normalise), + _ => {} + } +} + +/// Longest action or set name kept (Photoshop's own limit is 255). A file's names are lengths it +/// chooses, and each is copied into every action and every unsupported-step diagnostic. +pub(super) const MAX_NAME_CHARS: usize = 1024; + +pub(super) fn clip_name(s: &str) -> String { + s.chars().take(MAX_NAME_CHARS).collect() +} + +fn convert_action(a: &AtnAction, set: &str, unsupported: &mut Vec) -> Action { + let name = clip_name(&a.name.to_string_lossy()); + let mut action = Action::new(name.clone(), Vec::new()); + action.set = Some(clip_name(set)); + for (i, item) in a.items.iter().enumerate() { + let mapped = match (event_for(&item.event), &item.descriptor) { + (Some(e), Some(d)) => (e.from)(d), + (Some(e), None) => (e.from)(&Descriptor::default()), + (None, _) => Mapped::Unsupported { harmless: false }, + }; + let (new_steps, enabled) = match mapped { + Mapped::Steps(s) => (s, item.enabled), + Mapped::Unsupported { harmless } => { + unsupported.push(Unsupported { action: name.clone(), step: i, event: item.event.id(), name: item.label() }); + (vec![photoshop_step(item)], item.enabled && !harmless) + } + }; + for mut s in new_steps { + normalise(&mut s.1); + let idx = action.steps.len(); + action.steps.push(s); + if !enabled { + action.disabled.insert(idx); + } + if item.with_dialog { + action.dialogs.insert(idx); + } + } + } + action +} + +/// Convert a `.atn` file. Fails only when the file is unreadable: every step imports, as a +/// command or as a kept Photoshop step. +pub fn import(bytes: &[u8]) -> std::result::Result { + let file = atn::parse(bytes).map_err(|e| e.to_string())?; + let set = file.name.to_string_lossy(); + let set = if set.trim().is_empty() { DEFAULT_SET.to_string() } else { clip_name(&set) }; + let mut out = Imported { set: set.clone(), warnings: file.warnings.clone(), ..Default::default() }; + for a in &file.actions { + let action = convert_action(a, &set, &mut out.unsupported); + if a.function_key > 0 { + out.function_keys.push((action.name.clone(), function_key_name(a.function_key, a.shift, a.command))); + } + out.actions.push(action); + } + Ok(out) +} + +// ------------------------------------------------------------------ export + +/// A step Save Actions could not express as a Photoshop event. +#[derive(Clone, Debug, PartialEq, serde::Serialize)] +pub struct Skipped { + pub action: String, + pub step: usize, + pub id: String, +} + +pub(super) fn export_item(id: &str, params: &Value, set: &str) -> Option { + if id == PHOTOSHOP_STEP { + let event = jstr(params, "event")?; + let event = match params.get("eventKind") { + Some(Value::String(kind)) if kind == "code" => AtnEvent::Code(event.as_bytes().try_into().ok()?), + Some(Value::String(kind)) if kind == "name" => AtnEvent::name(event), + Some(_) => return None, + // Older PhotoCraft action data did not retain the event kind. Keep its previous + // best-effort export behavior for compatibility. + None => match event.as_bytes() { + [a, b, c, d] => AtnEvent::Code([*a, *b, *c, *d]), + _ => AtnEvent::name(event), + }, + }; + let descriptor = match jstr(params, "descriptor") { + Some(b64) => Some(Descriptor::from_bytes(&photocraft_paint::tile::b64_decode(b64)?).ok()?), + None => None, + }; + return Some(AtnItem { event, dictionary: jstr(params, "name").unwrap_or("").as_bytes().to_vec(), descriptor, ..Default::default() }); + } + let mut params = params.clone(); + if (id == "actions.play" || id == "actions.conditional") && params.get("set").is_none() { + params["set"] = json!(set); + } + let (e, descriptor) = event_and_descriptor(id, ¶ms)?; + let event = if e.code.is_empty() { AtnEvent::name(e.name) } else { AtnEvent::Code(e.code.as_bytes().try_into().ok()?) }; + Some(AtnItem { event, dictionary: e.label.as_bytes().to_vec(), descriptor: Some(descriptor), ..Default::default() }) +} + +/// Photoshop applies only the rename when a Set mixes it with opacity or blend mode (#8304). +/// Write each layer property separately, renaming last so named references still resolve. +fn export_items(id: &str, params: &Value, set: &str) -> Option> { + let item = export_item(id, params, set)?; + if id != "layer.setProps" { + return Some(vec![item]); + } + let descriptor = item.descriptor.as_ref()?; + let properties = get_obj(descriptor, "T ")?; + if properties.items.len() <= 1 { + return Some(vec![item]); + } + let target = descriptor.get("null")?; + let mut items = Vec::with_capacity(properties.items.len()); + for (key, value) in properties.items.iter().filter(|(k, _)| !k.is("Nm ")).chain(properties.items.iter().filter(|(k, _)| k.is("Nm "))) { + let mut property = properties.clone(); + property.items = vec![(key.clone(), value.clone())]; + let descriptor = desc("null").with("null", target.clone()).with("T ", D::Descriptor(property)); + items.push(AtnItem { descriptor: Some(descriptor), ..item.clone() }); + } + Some(items) +} + +/// An action's key as a shortcut string: `F5`, with Photoshop's Shift and Command options +/// `Shift+F5`, `Cmd+F5` or `Cmd+Shift+F5` (#7646). +pub fn function_key_name(key: u16, shift: bool, command: bool) -> String { + format!("{}{}F{key}", if command { "Cmd+" } else { "" }, if shift { "Shift+" } else { "" }) +} + +/// The `.atn` function key (1…15), Shift and Command of a shortcut string, or `None` for +/// anything else. +pub fn parse_function_key(key: &str) -> Option<(u16, bool, bool)> { + let (mut shift, mut command) = (false, false); + let mut rest = key; + loop { + if let Some(r) = rest.strip_prefix("Cmd+").filter(|_| !command) { + (command, rest) = (true, r); + } else if let Some(r) = rest.strip_prefix("Shift+").filter(|_| !shift) { + (shift, rest) = (true, r); + } else { + break; + } + } + let n = rest.strip_prefix('F')?.parse::().ok().filter(|n| (1..=15).contains(n))?; + Some((n, shift, command)) +} + +/// The `.atn` bytes of `actions` as the set `set`. `function_keys` gives each action's key +/// (`F1`…`F15`, with `Shift+` and `Cmd+` as [`function_key_name`] writes them). Steps with no Photoshop equivalent are an error unless `skip_unsupported`. +pub fn export( + set: &str, + actions: &[&Action], + function_keys: &[(String, String)], + skip_unsupported: bool, +) -> std::result::Result<(Vec, Vec), String> { + let mut skipped = Vec::new(); + let mut file = AtnFile { name: UnicodeString::new_nul(set), expanded: true, actions: Vec::new(), warnings: Vec::new() }; + for a in actions { + let mut out = AtnAction { name: UnicodeString::new_nul(&a.name), expanded: false, ..Default::default() }; + if let Some((n, shift, command)) = function_keys.iter().find(|(n, _)| n == &a.name).and_then(|(_, key)| parse_function_key(key)) { + (out.function_key, out.shift, out.command) = (n, shift, command); + } + for (i, (id, params)) in a.steps.iter().enumerate() { + let Some(items) = export_items(id, params, set) else { + if skip_unsupported { + skipped.push(Skipped { action: a.name.clone(), step: i, id: id.clone() }); + continue; + } + let step_name = match params.get("layer") { + Some(Value::Number(n)) => format!("`{id}` with numeric layer {n}"), + _ => format!("`{id}`"), + }; + return Err(format!( + "step {} of `{}` ({step_name}) has no Photoshop equivalent; pass \"skipUnsupported\": true to leave it out", + i + 1, + a.name + )); + }; + for mut item in items { + item.enabled = a.step_enabled(i); + item.with_dialog = a.dialogs.contains(&i); + item.dialog_options = if item.with_dialog { 2 } else { 0 }; + out.items.push(item); + } + } + file.actions.push(out); + } + let bytes = atn::write(&file).map_err(|e| e.to_string())?; + Ok((bytes, skipped)) +} + +// ------------------------------------------------------------------ commands + +/// Assigns names not already used, as `name`, `name 2`, `name 3`… A plain linear scan of the +/// taken list per candidate is cubic when an action file repeats one base name many times, so +/// membership uses a set and the next suffix to try is cached per base name. +pub(super) struct UniqueNames { + taken: std::collections::HashSet, + next_suffix: std::collections::HashMap, +} + +impl UniqueNames { + pub(super) fn new>(existing: I) -> Self { + UniqueNames { taken: existing.into_iter().collect(), next_suffix: std::collections::HashMap::new() } + } + + /// Reserves and returns a unique name derived from `name`, recording it as taken. + pub(super) fn claim(&mut self, name: &str) -> String { + if self.taken.insert(name.to_string()) { + return name.to_string(); + } + let mut i = self.next_suffix.get(name).copied().unwrap_or(2); + loop { + let candidate = format!("{name} {i}"); + i += 1; + if self.taken.insert(candidate.clone()) { + self.next_suffix.insert(name.to_string(), i); + return candidate; + } + } + } +} diff --git a/crates/engine/src/cmd/atn_cmds/descriptors.rs b/crates/engine/src/cmd/atn_cmds/descriptors.rs new file mode 100644 index 0000000000..0fbecf60da --- /dev/null +++ b/crates/engine/src/cmd/atn_cmds/descriptors.rs @@ -0,0 +1,266 @@ +use super::*; + +// ------------------------------------------------------------------ descriptor access + +pub(super) fn num(v: &D) -> Option { + match v { + D::Integer(i) => Some(f64::from(*i)), + D::LargeInteger(i) => Some(*i as f64), + D::Double(d) | D::UnitFloat { value: d, .. } => Some(*d), + _ => None, + } + .filter(|f| f.is_finite()) +} + +pub(super) fn trimmed(id: &Id) -> String { + String::from_utf8_lossy(id.as_bytes()).trim_end().to_string() +} + +pub(super) fn get_num(d: &Descriptor, k: &str) -> Option { + d.get(k).and_then(num) +} + +pub(super) fn get_bool(d: &Descriptor, k: &str) -> Option { + match d.get(k) { + Some(D::Boolean(b)) => Some(*b), + _ => None, + } +} + +pub(super) fn get_text(d: &Descriptor, k: &str) -> Option { + match d.get(k) { + Some(D::Text(t)) => Some(t.to_string_lossy()), + _ => None, + } +} + +/// An enumerated value's id, trailing spaces removed (`Ordn.Trgt` → `"Trgt"`). +pub(super) fn get_enum(d: &Descriptor, k: &str) -> Option { + match d.get(k) { + Some(D::Enumerated { value, .. }) => Some(trimmed(value)), + _ => None, + } +} + +pub(super) fn get_obj<'a>(d: &'a Descriptor, k: &str) -> Option<&'a Descriptor> { + match d.get(k) { + Some(D::Descriptor(o) | D::GlobalObject(o)) => Some(o), + _ => None, + } +} + +pub(super) fn get_list<'a>(d: &'a Descriptor, k: &str) -> Option<&'a [D]> { + match d.get(k) { + Some(D::List(l)) => Some(l), + _ => None, + } +} + +pub(super) fn get_ref<'a>(d: &'a Descriptor, k: &str) -> Option<&'a [ReferenceItem]> { + match d.get(k) { + Some(D::Reference(r)) => Some(r), + _ => None, + } +} + +/// The class of a reference's first item, trimmed (`Lyr`, `Chnl`, `AdjL`…). +pub(super) fn ref_class(r: &[ReferenceItem]) -> Option { + Some(trimmed(match r.first()? { + ReferenceItem::Property { class, .. } + | ReferenceItem::Class(class) + | ReferenceItem::Enumerated { class, .. } + | ReferenceItem::Offset { class, .. } + | ReferenceItem::Identifier { class, .. } + | ReferenceItem::Index { class, .. } + | ReferenceItem::Name { class, .. } => &class.class_id, + })) +} + +/// How a reference names its target: the ordinal (`Trgt`, `Frnt`…), a name, a property… +pub(super) enum Target { + Ordinal(String), + Name(String), + Property(String), + Class, + Offset(i32), + Index(u32), + Other, +} + +pub(super) fn target(r: &[ReferenceItem]) -> Target { + match r.first() { + Some(ReferenceItem::Enumerated { value, .. }) => Target::Ordinal(trimmed(value)), + Some(ReferenceItem::Name { name, .. }) => Target::Name(name.to_string_lossy()), + Some(ReferenceItem::Property { key, .. }) => Target::Property(trimmed(key)), + Some(ReferenceItem::Class(_)) => Target::Class, + Some(ReferenceItem::Offset { offset, .. }) => Target::Offset(*offset), + Some(ReferenceItem::Index { index, .. }) => Target::Index(*index), + _ => Target::Other, + } +} + +/// `{"layer": name}` for a reference that names a layer, `{}` for the target layer, `None` +/// for anything else (an index or id: meaningless in another document). +pub(super) fn layer_target(r: &[ReferenceItem]) -> Option> { + let mut m = Map::new(); + match target(r) { + Target::Ordinal(o) if o == "Trgt" => {} + Target::Name(n) => { + m.insert("layer".into(), json!(n)); + } + Target::Property(p) if p == "Bckg" => { + m.insert("layer".into(), json!("Background")); + } + _ => return None, + } + Some(m) +} + +// ------------------------------------------------------------------ descriptor building + +/// A Photoshop id: codes shorter than four characters are space-padded (`H `, `Rd `), +/// longer names stay strings. +pub(super) fn code(s: &str) -> Id { + if s.len() < 4 { Id::new(&format!("{s:<4}")) } else { Id::new(s) } +} + +pub(super) fn class(c: &str) -> Class { + Class { name: UnicodeString::new_nul(""), class_id: code(c) } +} + +/// The pixel and percent units of a `UntF` value. +pub(super) const PX: [u8; 4] = *b"#Pxl"; + +pub(super) const PCT: [u8; 4] = *b"#Prc"; + +/// Points (1/72 in): what Photoshop calls "relative" units. +pub(super) const PT: [u8; 4] = *b"#Rlt"; + +pub(super) fn px(v: f64) -> D { + D::UnitFloat { unit: PX, value: v } +} + +pub(super) fn pct(v: f64) -> D { + D::UnitFloat { unit: *b"#Prc", value: v } +} + +pub(super) fn ang(v: f64) -> D { + D::UnitFloat { unit: *b"#Ang", value: v } +} + +pub(super) fn long(v: f64) -> D { + D::Integer(v.round().clamp(f64::from(i32::MIN), f64::from(i32::MAX)) as i32) +} + +pub(super) fn text(s: &str) -> D { + D::Text(UnicodeString::new_nul(s)) +} + +pub(super) fn enm(ty: &str, v: &str) -> D { + D::Enumerated { type_id: code(ty), value: code(v) } +} + +pub(super) fn target_ref(cls: &str) -> D { + D::Reference(vec![ReferenceItem::Enumerated { class: class(cls), type_id: Id::new("Ordn"), value: Id::new("Trgt") }]) +} + +pub(super) fn name_ref(cls: &str, name: &str) -> D { + D::Reference(vec![ReferenceItem::Name { class: class(cls), name: UnicodeString::new_nul(name) }]) +} + +pub(super) fn class_ref(cls: &str) -> D { + D::Reference(vec![ReferenceItem::Class(class(cls))]) +} + +/// The `null` reference for a command's `layer` param: by name, else the target layer. +pub(super) fn layer_ref(p: &Value) -> Option { + match p.get("layer") { + None | Some(Value::Null) => Some(target_ref("Lyr ")), + Some(Value::String(n)) => Some(name_ref("Lyr ", n)), + _ => None, + } +} + +pub(super) fn desc(cls: &str) -> Descriptor { + Descriptor::new(cls) +} + +// ------------------------------------------------------------------ JSON access + +pub(super) fn jnum(p: &Value, k: &str) -> Option { + p.get(k).and_then(Value::as_f64).filter(|f| f.is_finite()) +} + +pub(super) fn jbool(p: &Value, k: &str) -> Option { + p.get(k).and_then(Value::as_bool) +} + +pub(super) fn jstr<'a>(p: &'a Value, k: &str) -> Option<&'a str> { + p.get(k).and_then(Value::as_str) +} + +// ------------------------------------------------------------------ colours and enums + +/// A Photoshop colour object as `#rrggbb`: `RGBC` (0..255), `HSBC`, `Grsc`. +pub(super) fn color_hex(c: &Descriptor) -> Option { + let hex = |r: f64, g: f64, b: f64| { + format!("#{:02x}{:02x}{:02x}", r.round().clamp(0.0, 255.0) as u8, g.round().clamp(0.0, 255.0) as u8, b.round().clamp(0.0, 255.0) as u8) + }; + if let (Some(r), Some(g), Some(b)) = (get_num(c, "Rd "), get_num(c, "Grn "), get_num(c, "Bl ")) { + return Some(hex(r, g, b)); + } + if let (Some(h), Some(s), Some(v)) = (get_num(c, "H "), get_num(c, "Strt"), get_num(c, "Brgh")) { + let (s, v) = ((s / 100.0).clamp(0.0, 1.0), (v / 100.0).clamp(0.0, 1.0)); + let h = h.rem_euclid(360.0) / 60.0; + let i = h.floor(); + let f = h - i; + let (p, q, t) = (v * (1.0 - s), v * (1.0 - s * f), v * (1.0 - s * (1.0 - f))); + let (r, g, b) = match i as i32 { + 0 => (v, t, p), + 1 => (q, v, p), + 2 => (p, v, t), + 3 => (p, q, v), + 4 => (t, p, v), + _ => (v, p, q), + }; + return Some(hex(r * 255.0, g * 255.0, b * 255.0)); + } + get_num(c, "Gry ").map(|g| { + let v = 255.0 - g * 2.55; + hex(v, v, v) + }) +} + +pub(super) fn color_desc(hex: &str) -> Option { + let h = hex.strip_prefix('#')?; + if h.len() != 6 || !h.is_ascii() { + return None; + } + let ch = |i: usize| u8::from_str_radix(h.get(i..i + 2)?, 16).ok().map(f64::from); + Some(desc("RGBC").with("Rd ", D::Double(ch(0)?)).with("Grn ", D::Double(ch(2)?)).with("Bl ", D::Double(ch(4)?))) +} + +/// A `Pth ` value's text: Photoshop stores `"txtu"`, a little-endian total length, a +/// little-endian UTF-16 unit count and the units (NUL-terminated). +pub(super) fn path_text(v: &D) -> Option { + let D::Path(b) = v else { return None }; + if b.get(0..4)? != b"txtu" { + return None; + } + let n = u32::from_le_bytes(b.get(8..12)?.try_into().ok()?) as usize; + let units: Vec = b.get(12..12usize.checked_add(n.checked_mul(2)?)?)?.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).collect(); + let text = String::from_utf16_lossy(&units); + let text = text.trim_end_matches('\0'); + (!text.is_empty()).then(|| text.to_string()) +} + +pub(super) fn path_value(text: &str) -> D { + let units: Vec = text.encode_utf16().chain(std::iter::once(0)).collect(); + let mut b = b"txtu".to_vec(); + b.extend_from_slice(&((12 + units.len() * 2) as u32).to_le_bytes()); + b.extend_from_slice(&(units.len() as u32).to_le_bytes()); + for u in units { + b.extend_from_slice(&u.to_le_bytes()); + } + D::Path(b) +} diff --git a/crates/engine/src/cmd/atn_cmds/events.rs b/crates/engine/src/cmd/atn_cmds/events.rs new file mode 100644 index 0000000000..6d2fbc4382 --- /dev/null +++ b/crates/engine/src/cmd/atn_cmds/events.rs @@ -0,0 +1,609 @@ +use super::adjustments::{adjustment_by_class, adjustment_steps, levels_from, levels_to, shadows_highlights_from, shadows_highlights_to}; +use super::descriptors::{desc, get_bool, get_ref, jbool, layer_ref, layer_target, ref_class}; +use super::fields::{F, Kind, Mapped, fields_from, fields_to, none, step}; +use super::steps_doc::{ + align_from, align_to, canvas_size_from, canvas_size_to, close_from, close_to, conditional_from, conditional_to, convert_mode_from, convert_mode_to, + crop_from, crop_to, export_from, export_to, image_size_from, image_size_to, merge_visible_from, merge_visible_to, open_from, open_to, paste_from, paste_to, + place_from, place_to, profile_from, profile_to, purge_from, purge_to, reset_from, reset_to, save_from, save_to, stop_from, stop_to, +}; +use super::steps_image::{ + GALLERY_IDS, REFINE_EDGE, RIPPLE_SIZE, SMART_BRUSH, apply_image_from, apply_image_to, color_range_from, color_range_to, gallery_from, gallery_to, + has_refine_strokes, radial_blur_from, radial_blur_to, refine_edge_to, transform_from, transform_to, +}; +use super::steps_layer::{ + STROKE, apply_comp_from, apply_comp_to, clear_from, clear_to, delete_from, delete_to, duplicate_from, duplicate_to, fill_from, fill_to, flip_from, flip_to, + move_from, move_to, play_from, play_to, rotate_from, rotate_to, select_from, select_to, stroke_to, visibility_from, visibility_to, +}; +use super::steps_make::{make_from, make_to, set_from, set_to}; +use super::tables::{NOISE, OFFSET_FILL, SMART_BLUR_MODE, SMART_BLUR_QUALITY, TRIM}; +use super::*; + +/// An event: code (empty when Photoshop only has a string name), string name, the panel +/// label, the command ids it exports (the first is the one simple events import to), and the +/// two converters. +pub(super) struct Event { + pub(super) code: &'static str, + pub(super) name: &'static str, + pub(super) label: &'static str, + pub(super) ids: &'static [&'static str], + pub(super) from: fn(&Descriptor) -> Mapped, + to: fn(&str, &Value) -> Option, +} + +macro_rules! ev { + ($code:literal, $name:literal, $label:literal, $id:literal, $fields:expr) => { + ev!($code, $name, $label, $id, $fields, unless | _ | false) + }; + // `unless`: params the descriptor can't carry, so such a step isn't exported (it would replay + // differently) rather than losing them. + ($code:literal, $name:literal, $label:literal, $id:literal, $fields:expr, unless $skip:expr) => { + Event { + code: $code, + name: $name, + label: $label, + ids: &[$id], + from: |d| match fields_from(d, $fields) { + Some(m) => step($id, Value::Object(m)), + None => Mapped::Unsupported { harmless: false }, + }, + to: |_, p| if pixel_target(p) && !($skip)(p) && holds_its_settings($id, p) { fields_to(p, $fields, desc("null")) } else { None }, + } + }; +} + +/// Minimum / Maximum with Preserve: Roundness. The descriptor here maps the radius only, and +/// Photoshop's encoding of the shape isn't verified, so such a step is not exported: it would +/// replay as the default Squareness (#7233). +fn preserves_roundness(p: &Value) -> bool { + p.get("preserve").and_then(Value::as_str) == Some("roundness") +} + +/// Whether any of the boolean `flags` is on in `p` (present, not null and not `false`). +fn flag_set(p: &Value, flags: &[&str]) -> bool { + flags.iter().any(|f| p.get(*f).is_some_and(|v| !v.is_null() && *v != Value::Bool(false))) +} + +/// Select > Modify with "Apply effect at canvas bounds": the descriptor has no field for it, so such a +/// step is not exported (it would replay without the option). +fn applies_at_canvas_bounds(p: &Value) -> bool { + flag_set(p, &["applyAtCanvasBounds"]) +} + +/// Settings a mapped event has no field for, by command: `(param, the value the event plays as)`. +/// Photoshop's event has nowhere to put these, so a step that sets one cannot be written: it +/// would import as a different edit, silently. Such a step is refused, the way [`pixel_target`] +/// refuses a filter aimed at a mask -- and no key Photoshop does not define is invented for it, +/// which the clean-room rule forbids and which would make the file wrong in another reader. +/// +/// A step that leaves the setting at the value the event plays as exports as before. +/// How a setting the event cannot carry behaves once the step is replayed without it. Which of +/// the two a setting takes follows the command's own reading of it, not the parameter spec. +enum Lost { + /// Replay uses this value, so only a step already at it survives. Numbers and strings are + /// both compared as written, since the commands below read these settings as written. + ReplaysAs(&'static str), + /// The command reads only this one spelling as anything other than what replay does, so every + /// other value survives -- a differently cased one included, because it too plays as replay's. + DiffersAt(&'static str), +} + +const UNHOLDABLE: &[(&str, &[(&str, Lost)])] = &[ + // Crst carries ClSz only; replay seeds the pattern from 0 (#7668). + ("filter.pixelate.crystallize", &[("seed", Lost::ReplaysAs("0"))]), + // RdlB carries Amnt, BlrM and BlrQ; replay spins or zooms about the middle of the layer. + ("filter.blur.radialBlur", &[("centerX", Lost::ReplaysAs("0.5")), ("centerY", Lost::ReplaysAs("0.5"))]), + // Mnm /Mxm carry Rds only; replay keeps squareness, and so does the command for anything but + // the exact string "roundness" -- see `preserve` in filters.rs. + ("filter.other.minimum", &[("preserve", Lost::DiffersAt("roundness"))]), + ("filter.other.maximum", &[("preserve", Lost::DiffersAt("roundness"))]), +]; + +/// Whether every setting of `p` that its event cannot hold would play the same without it +/// (see [`UNHOLDABLE`]). +fn holds_its_settings(id: &str, p: &Value) -> bool { + let Some((_, settings)) = UNHOLDABLE.iter().find(|(cmd, _)| *cmd == id) else { return true }; + settings.iter().all(|(param, lost)| match (p.get(param), lost) { + (None | Some(Value::Null), _) => true, + (Some(v), Lost::ReplaysAs(played)) => v.as_str() == Some(played) || v.as_f64().is_some_and(|n| played.parse::().is_ok_and(|d| n == d)), + (Some(v), Lost::DiffersAt(spelling)) => v.as_str() != Some(spelling), + }) +} + +/// Whether `p` edits the layer's pixels: no `"target"` or `"target":"pixels"`. Photoshop's +/// descriptor for a plain event has no field for a mask, Quick Mask or channel target, so such +/// a step can't be exported faithfully. +pub(super) fn pixel_target(p: &Value) -> bool { + p.get("target").is_none_or(|t| t.as_str() == Some("pixels")) +} + +fn levels_event_from(d: &Descriptor) -> Mapped { + if get_bool(d, "Auto") == Some(true) { + return none("image.autoTone"); + } + if get_bool(d, "AuCo") == Some(true) { + return none("image.autoContrast"); + } + match levels_from(d) { + Some(p) => step("image.adjustments.levels", p), + None => Mapped::Unsupported { harmless: false }, + } +} + +fn levels_event_to(id: &str, p: &Value) -> Option { + Some(match id { + "image.autoTone" => desc("null").with("Auto", D::Boolean(true)), + "image.autoContrast" => desc("null").with("AuCo", D::Boolean(true)), + _ => levels_to(p)?, + }) +} + +/// A direct adjustment event (Image › Adjustments › …). The command id is `image.adjustments.` +/// unless it is given. +macro_rules! adjustment_event { + ($code:literal, $class:literal, $name:literal, $label:literal) => { + adjustment_event!($code, $class, $name, $label, concat!("image.adjustments.", $name)) + }; + ($code:literal, $class:literal, $name:literal, $label:literal, $id:expr) => { + Event { + code: $code, + name: $name, + label: $label, + ids: &[$id], + from: |d| match adjustment_by_class($class) { + Some(a) => adjustment_steps(a, "image.adjustments.", Some(d)), + None => Mapped::Unsupported { harmless: false }, + }, + to: |_, p| adjustment_by_class($class).and_then(|a| (a.to)(p)), + } + }; +} + +/// Create / Release Clipping Mask (`groupEvent` / `ungroup`) on the target or a named layer. +fn clipping_from(d: &Descriptor, id: &str) -> Mapped { + match get_ref(d, "null") { + None => none(id), + Some(r) if ref_class(r).as_deref() == Some("Lyr") => match layer_target(r) { + Some(p) => step(id, Value::Object(p)), + None => Mapped::Unsupported { harmless: false }, + }, + Some(_) => Mapped::Unsupported { harmless: false }, + } +} + +fn clipping_to(_: &str, p: &Value) -> Option { + Some(desc("null").with("null", layer_ref(p)?)) +} + +/// A clipping mask event: `clipping_from` / `clipping_to` with one command id. +macro_rules! clipping_event { + ($code:literal, $name:literal, $label:literal, $id:literal) => { + Event { code: $code, name: $name, label: $label, ids: &[$id], from: |d| clipping_from(d, $id), to: clipping_to } + }; +} + +/// Every Photoshop event PhotoCraft maps. The order matters only for the panel label. +pub(super) const EVENTS: &[Event] = &[ + // Filters. + ev!("GsnB", "gaussianBlur", "Gaussian Blur", "filter.blur.gaussianBlur", &[F("Rds ", "radius", Kind::Px)]), + ev!( + "UnsM", + "unsharpMask", + "Unsharp Mask", + "filter.sharpen.unsharpMask", + &[F("Amnt", "amount", Kind::Pct), F("Rds ", "radius", Kind::Px), F("Thsh", "threshold", Kind::Long)] + ), + ev!( + "AdNs", + "addNoise", + "Add Noise", + "filter.noise.addNoise", + &[ + F("Dstr", "distribution", Kind::Enum("Dstr", NOISE)), + F("Nose", "amount", Kind::Pct), + F("Mnch", "monochromatic", Kind::Bool), + F("FlRs", "seed", Kind::Long) + ] + ), + ev!("Mdn ", "median", "Median", "filter.noise.median", &[F("Rds ", "radius", Kind::Px)]), + ev!("DstS", "dustAndScratches", "Dust & Scratches", "filter.noise.dustAndScratches", &[F("Rds ", "radius", Kind::Px), F("Thsh", "threshold", Kind::Long)]), + ev!("Dspc", "despeckle", "Despeckle", "filter.noise.despeckle", &[]), + // Photoshop records Emboss's angle, height and amount as plain integers (#7946). + ev!( + "Embs", + "emboss", + "Emboss", + "filter.stylize.emboss", + &[F("Angl", "angle", Kind::Long), F("Hght", "height", Kind::Long), F("Amnt", "amount", Kind::Long)] + ), + ev!("MtnB", "motionBlur", "Motion Blur", "filter.blur.motionBlur", &[F("Angl", "angle", Kind::Ang), F("Dstn", "distance", Kind::Px)]), + ev!("", "boxblur", "Box Blur", "filter.blur.boxBlur", &[F("Rds ", "radius", Kind::Px)]), + ev!("", "surfaceBlur", "Surface Blur", "filter.blur.surfaceBlur", &[F("Rds ", "radius", Kind::Px), F("Thsh", "threshold", Kind::Long)]), + ev!( + "SmrB", + "smartBlur", + "Smart Blur", + "filter.blur.smartBlur", + &[ + F("Rds ", "radius", Kind::Dbl), + F("Thsh", "threshold", Kind::Dbl), + F("SmBQ", "quality", Kind::Enum("SmBQ", SMART_BLUR_QUALITY)), + F("SmBM", "mode", Kind::Enum("SmBM", SMART_BLUR_MODE)) + ] + ), + Event { code: "RdlB", name: "radialBlur", label: "Radial Blur", ids: &["filter.blur.radialBlur"], from: radial_blur_from, to: radial_blur_to }, + ev!("Blr ", "blur", "Blur", "filter.blur.blur", &[]), + ev!("BlrM", "blurMore", "Blur More", "filter.blur.blurMore", &[]), + ev!("Shrp", "sharpen", "Sharpen", "filter.sharpen.sharpen", &[]), + ev!("ShrM", "sharpenMore", "Sharpen More", "filter.sharpen.sharpenMore", &[]), + ev!("ShrE", "sharpenEdges", "Sharpen Edges", "filter.sharpen.sharpenEdges", &[]), + ev!("HghP", "highPass", "High Pass", "filter.other.highPass", &[F("Rds ", "radius", Kind::Px)]), + ev!("Mnm ", "minimum", "Minimum", "filter.other.minimum", &[F("Rds ", "radius", Kind::Px)], unless preserves_roundness), + ev!("Mxm ", "maximum", "Maximum", "filter.other.maximum", &[F("Rds ", "radius", Kind::Px)], unless preserves_roundness), + ev!( + "Ofst", + "offset", + "Offset", + "filter.other.offset", + &[F("Hrzn", "horizontal", Kind::Long), F("Vrtc", "vertical", Kind::Long), F("Fl ", "undefinedAreas", Kind::Enum("FlMd", OFFSET_FILL))] + ), + ev!("Rple", "ripple", "Ripple", "filter.distort.ripple", &[F("Amnt", "amount", Kind::ExactLong), F("RplS", "size", Kind::Enum("RplS", RIPPLE_SIZE))]), + ev!("Crst", "crystallize", "Crystallize", "filter.pixelate.crystallize", &[F("ClSz", "cellSize", Kind::ExactLong)]), + Event { code: "GEfc", name: "filterGallery", label: "Filter Gallery", ids: GALLERY_IDS, from: gallery_from, to: gallery_to }, + // Adjustments (Image › Adjustments). + Event { + code: "", + name: "adaptCorrect", + label: "Shadows/Highlights", + ids: &["image.adjustments.shadowsHighlights"], + from: shadows_highlights_from, + to: shadows_highlights_to, + }, + Event { + code: "Lvls", + name: "levels", + label: "Levels", + ids: &["image.adjustments.levels", "image.autoTone", "image.autoContrast"], + from: levels_event_from, + to: levels_event_to, + }, + adjustment_event!("Crvs", "Crvs", "curves", "Curves"), + adjustment_event!("HStr", "HStr", "hueSaturation", "Hue/Saturation"), + adjustment_event!("BrgC", "BrgC", "brightnessEvent", "Brightness/Contrast", "image.adjustments.brightnessContrast"), + adjustment_event!("Thrs", "Thrs", "threshold", "Threshold"), + adjustment_event!("Pstr", "Pstr", "posterize", "Posterize"), + adjustment_event!("Invr", "Invr", "invert", "Invert"), + adjustment_event!("ClrB", "ClrB", "colorBalance", "Color Balance"), + adjustment_event!("Vbrn", "Vbrn", "vibrance", "Vibrance"), + adjustment_event!("Exps", "Exps", "exposure", "Exposure"), + // Photoshop runs Photo Filter by name only: `PhtF` is the class, not an event (#8301). + adjustment_event!("", "PhtF", "photoFilter", "Photo Filter"), + adjustment_event!("", "BanW", "blackAndWhite", "Black & White", "image.adjustments.blackWhite"), + adjustment_event!("ChnM", "ChnM", "channelMixer", "Channel Mixer"), + adjustment_event!("GdMp", "GdMp", "gradientMapEvent", "Gradient Map", "image.adjustments.gradientMap"), + adjustment_event!("SlcC", "SlcC", "selectiveColor", "Selective Color"), + ev!("Dstt", "desaturate", "Desaturate", "image.adjustments.desaturate", &[]), + ev!("Eqlz", "equalize", "Equalize", "image.adjustments.equalize", &[]), + ev!("", "autoColor", "Auto Color", "image.autoColor", &[]), + // Image. + Event { code: "ImgS", name: "imageSize", label: "Image Size", ids: &["image.imageSize"], from: image_size_from, to: image_size_to }, + Event { code: "CnvS", name: "canvasSize", label: "Canvas Size", ids: &["image.canvasSize"], from: canvas_size_from, to: canvas_size_to }, + Event { + code: "Rtte", + name: "rotateEventEnum", + label: "Rotate", + ids: &[ + "image.imageRotation.90cw", + "image.imageRotation.90ccw", + "image.imageRotation.180", + "image.rotation.arbitrary", + "edit.transform.rotate90Cw", + "edit.transform.rotate90Ccw", + "edit.transform.rotate180", + ], + from: rotate_from, + to: rotate_to, + }, + Event { + code: "Flip", + name: "flip", + label: "Flip", + ids: &[ + "image.imageRotation.flipCanvasHorizontal", + "image.imageRotation.flipCanvasVertical", + "edit.transform.flipHorizontal", + "edit.transform.flipVertical", + ], + from: flip_from, + to: flip_to, + }, + Event { code: "Crop", name: "crop", label: "Crop", ids: &["image.crop"], from: crop_from, to: crop_to }, + ev!( + "", + "trim", + "Trim", + "image.trim", + &[ + F("trimBasedOn", "basedOn", Kind::Enum("trimBasedOn", TRIM)), + F("Top ", "top", Kind::Bool), + F("Btom", "bottom", Kind::Bool), + F("Left", "left", Kind::Bool), + F("Rght", "right", Kind::Bool) + ] + ), + ev!("RvlA", "revealAll", "Reveal All", "image.revealAll", &[]), + Event { + code: "CnvM", + name: "convertMode", + label: "Convert Mode", + ids: &[ + "image.mode.rgb", + "image.mode.grayscale", + "image.mode.cmyk", + "image.mode.lab", + "image.mode.multichannel", + "image.mode.bits8", + "image.mode.bits16", + "image.mode.bits32", + "image.mode.bitmap", + ], + from: convert_mode_from, + to: convert_mode_to, + }, + Event { code: "Dplc", name: "duplicate", label: "Duplicate", ids: &["layer.duplicate", "image.duplicate"], from: duplicate_from, to: duplicate_to }, + // Layers. + Event { + code: "Mk ", + name: "make", + label: "Make", + ids: &[ + "layer.new.layer", + "layer.new.group", + "layer.groupLayers", + "layer.duplicate", + "layer.new.layerViaCopy", + "layer.new.layerViaCut", + "layer.newFillLayer.solidColor", + "layer.newFillLayer.pattern", + "layer.newAdjustmentLayer.levels", + "layer.newAdjustmentLayer.curves", + "layer.newAdjustmentLayer.hueSaturation", + "layer.newAdjustmentLayer.brightnessContrast", + "layer.newAdjustmentLayer.threshold", + "layer.newAdjustmentLayer.posterize", + "layer.newAdjustmentLayer.invert", + "layer.newAdjustmentLayer.colorBalance", + "layer.newAdjustmentLayer.vibrance", + "layer.newAdjustmentLayer.exposure", + "layer.newAdjustmentLayer.photoFilter", + "layer.newAdjustmentLayer.blackWhite", + "layer.newAdjustmentLayer.channelMixer", + "layer.newAdjustmentLayer.selectiveColor", + "layer.newAdjustmentLayer.gradientMap", + "layer.layerMask.revealAll", + "layer.layerMask.hideAll", + "layer.layerMask.revealSelection", + "layer.layerMask.hideSelection", + "file.new", + "file.newFromClipboard", + ], + from: make_from, + to: make_to, + }, + Event { + code: "setd", + name: "set", + label: "Set", + ids: &[ + "select.all", + "select.deselect", + "select.reselect", + "select.loadSelection", + "select.rect", + "select.lasso", + "select.editInQuickMaskMode", + "tools.setColors", + "layer.setProps", + "layer.renameLayer", + "layer.setLabelColor", + "layer.setAdjustment", + "layer.fill.pattern.set", + "layer.new.layerFromBackground", + ], + from: set_from, + to: set_to, + }, + Event { + code: "slct", + name: "select", + label: "Select", + ids: &[ + "layer.select", + "layer.selectAbove", + "layer.selectBelow", + "layer.addAboveToSelection", + "layer.addBelowToSelection", + "layer.selectTop", + "layer.selectBottom", + "channel.target", + "edit.undo", + "edit.redo", + "view.fitOnScreen", + "view.actualPixels", + "view.zoomIn", + "view.zoomOut", + "document.activate", + ], + from: select_from, + to: select_to, + }, + Event { code: "Dlt ", name: "delete", label: "Delete", ids: &["layer.delete", "edit.clear", "layer.layerMask.delete"], from: delete_from, to: delete_to }, + Event { code: "", name: "clearEvent", label: "Clear", ids: &["select.editInQuickMaskMode"], from: clear_from, to: clear_to }, + Event { + code: "Trnf", + name: "transform", + label: "Transform", + ids: &["edit.transform", "select.transformSelection"], + from: transform_from, + to: transform_to, + }, + Event { code: "AppI", name: "applyImageEvent", label: "Apply Image", ids: &["image.applyImage"], from: apply_image_from, to: apply_image_to }, + ev!("", "newPlacedLayer", "Convert to Smart Object", "layer.smartObjects.convertToSmartObject", &[]), + ev!("", "placedLayerEditContents", "Edit Contents", "layer.smartObjects.editContents", &[]), + ev!("", "updatePlacedLayer", "Update Smart Objects", "layer.smartObjects.updateModifiedContent", &[]), + Event { code: "Hd ", name: "hide", label: "Hide", ids: &["layer.hideLayers"], from: |d| visibility_from(d, "layer.hideLayers"), to: visibility_to }, + Event { code: "Shw ", name: "show", label: "Show", ids: &["layer.showLayers"], from: |d| visibility_from(d, "layer.showLayers"), to: visibility_to }, + Event { + code: "move", + name: "move", + label: "Move", + ids: &["layer.translate", "layer.arrange.bringToFront", "layer.arrange.sendToBack", "layer.arrange.bringForward", "layer.arrange.sendBackward"], + from: move_from, + to: move_to, + }, + ev!("FltI", "flattenImage", "Flatten Image", "layer.flattenImage", &[]), + Event { + code: "MrgV", + name: "mergeVisible", + label: "Merge Visible", + ids: &["layer.mergeVisible", "layer.stampVisible"], + from: merge_visible_from, + to: merge_visible_to, + }, + ev!("Mrg2", "mergeLayersNew", "Merge Layers", "layer.mergeLayers", &[]), + clipping_event!("Ungr", "ungroup", "Release Clipping Mask", "layer.releaseClippingMask"), + ev!("CpTL", "copyToLayer", "Layer Via Copy", "layer.new.layerViaCopy", &[]), + ev!("CtTL", "cutToLayer", "Layer Via Cut", "layer.new.layerViaCut", &[]), + ev!("", "rasterizeLayer", "Rasterize", "layer.rasterize.layer", &[]), + ev!("", "selectAllLayers", "Select All Layers", "select.allLayers", &[]), + ev!("", "selectNoLayers", "Deselect Layers", "select.deselectLayers", &[]), + clipping_event!("GrpL", "groupEvent", "Create Clipping Mask", "layer.createClippingMask"), + ev!("", "ungroupLayersEvent", "Ungroup Layers", "layer.ungroupLayers", &[]), + ev!("", "copyEffects", "Copy Layer Style", "layer.layerStyle.copyLayerStyle", &[]), + ev!("", "pasteEffects", "Paste Layer Style", "layer.layerStyle.pasteLayerStyle", &[]), + Event { + code: "", + name: "collapseAllGroupsEvent", + label: "Collapse All Groups", + ids: &["layer.setExpanded"], + from: |_| step("layer.setExpanded", json!({"all": true, "expanded": false})), + to: |_, p| (jbool(p, "all") == Some(true) && jbool(p, "expanded") == Some(false)).then(|| desc("null")), + }, + ev!("Dfrg", "defringe", "Defringe", "layer.matting.defringe", &[F("Wdth", "width", Kind::Px)]), + Event { + code: "Algn", + name: "align", + label: "Align", + ids: &[ + "layer.align.leftEdges", + "layer.align.horizontalCenters", + "layer.align.rightEdges", + "layer.align.topEdges", + "layer.align.verticalCenters", + "layer.align.bottomEdges", + ], + from: align_from, + to: align_to, + }, + // Selection. + ev!("Invs", "inverse", "Inverse", "select.inverse", &[]), + ev!("Fthr", "feather", "Feather", "select.modify.feather", &[F("Rds ", "radius", Kind::Px)], unless applies_at_canvas_bounds), + ev!("Expn", "expand", "Expand", "select.modify.expand", &[F("By ", "radius", Kind::Px)], unless applies_at_canvas_bounds), + ev!("Cntc", "contract", "Contract", "select.modify.contract", &[F("By ", "radius", Kind::Px)], unless applies_at_canvas_bounds), + ev!("Smth", "smoothness", "Smooth", "select.modify.smooth", &[F("Rds ", "radius", Kind::Px)], unless applies_at_canvas_bounds), + ev!("Brdr", "border", "Border", "select.modify.border", &[F("Wdth", "radius", Kind::Px)]), + ev!("Grow", "grow", "Grow", "select.grow", &[F("Tlrn", "tolerance", Kind::Long)]), + ev!("Smlr", "similar", "Similar", "select.similar", &[F("Tlrn", "tolerance", Kind::Long)]), + // `refineSelectionEdge` has no Sample All Layers, so a step with it exports as + // `smartBrushWorkspace` instead of dropping it. + Event { + code: "", + name: "refineSelectionEdge", + label: "Select and Mask", + ids: &["select.refineEdge"], + from: |d| match fields_from(d, REFINE_EDGE) { + Some(m) => step("select.refineEdge", Value::Object(m)), + None => Mapped::Unsupported { harmless: false }, + }, + to: refine_edge_to, + }, + ev!("", "smartBrushWorkspace", "Select and Mask", "select.refineEdge", SMART_BRUSH, unless has_refine_strokes), + ev!("", "autoCutout", "Select Subject", "select.subject", &[F("sampleAllLayers", "sampleAllLayers", Kind::Bool)]), + Event { code: "ClrR", name: "colorRange", label: "Color Range", ids: &["select.colorRange"], from: color_range_from, to: color_range_to }, + // Edit. + Event { code: "Fl ", name: "fill", label: "Fill", ids: &["edit.fill", "paint.bucket"], from: fill_from, to: fill_to }, + Event { + code: "Strk", + name: "stroke", + label: "Stroke", + ids: &["edit.stroke"], + from: |d| match fields_from(d, STROKE) { + Some(m) => step("edit.stroke", Value::Object(m)), + None => Mapped::Unsupported { harmless: false }, + }, + to: stroke_to, + }, + ev!("copy", "copyEvent", "Copy", "edit.copy", &[]), + ev!("CpyM", "copyMerged", "Copy Merged", "edit.copyMerged", &[]), + ev!("cut ", "cut", "Cut", "edit.cut", &[]), + Event { code: "past", name: "paste", label: "Paste", ids: &["edit.paste", "edit.pasteSpecial.pasteInPlace"], from: paste_from, to: paste_to }, + Event { + code: "Prge", + name: "purge", + label: "Purge", + ids: &["edit.purge.all", "edit.purge.clipboard", "edit.purge.histories", "edit.purge.undo"], + from: purge_from, + to: purge_to, + }, + Event { code: "Rset", name: "reset", label: "Reset", ids: &["tools.defaultColors"], from: reset_from, to: reset_to }, + ev!("Exch", "exchange", "Exchange", "tools.swapColors", &[]), + Event { + code: "", + name: "assignProfile", + label: "Assign Profile", + ids: &["edit.assignProfile"], + from: |d| profile_from(d, "edit.assignProfile"), + to: profile_to, + }, + Event { + code: "", + name: "convertToProfile", + label: "Convert to Profile", + ids: &["edit.convertToProfile"], + from: |d| profile_from(d, "edit.convertToProfile"), + to: profile_to, + }, + // File and actions. + Event { code: "Cls ", name: "close", label: "Close", ids: &["file.close"], from: close_from, to: close_to }, + Event { code: "Expr", name: "export", label: "Export", ids: &["file.export.saveForWebLegacy"], from: export_from, to: export_to }, + Event { code: "Plc ", name: "placeEvent", label: "Place", ids: &["file.placeEmbedded", "file.placeLinked"], from: place_from, to: place_to }, + Event { code: "Opn ", name: "open", label: "Open", ids: &["file.openAs"], from: open_from, to: open_to }, + Event { code: "", name: "conditional", label: "If", ids: &["actions.conditional"], from: conditional_from, to: conditional_to }, + Event { code: "save", name: "save", label: "Save", ids: &["file.save", "file.saveAs", "file.saveACopy"], from: save_from, to: save_to }, + ev!("Rvrt", "revert", "Revert", "file.revert", &[]), + Event { code: "Ply ", name: "play", label: "Play", ids: &["actions.play"], from: play_from, to: play_to }, + Event { code: "", name: "applyComp", label: "Apply Layer Comp", ids: &["layerComp.apply"], from: apply_comp_from, to: apply_comp_to }, + Event { code: "Stop", name: "stop", label: "Stop", ids: &[STOP_MESSAGE], from: stop_from, to: stop_to }, +]; + +/// Four-char codes PhotoCraft once exported for events Photoshop only runs by name (or by +/// another code), with the name they stand for. Measured in Photoshop: `executeAction` with +/// these codes fails ("the command is not currently available"), and `Fltn` is the +/// `flatness` property, not the flatten event. Import keeps accepting them so actions saved +/// before still load; export never writes them. +const LEGACY_CODES: &[(&str, &str)] = + &[("BoxB", "boxblur"), ("SrfB", "surfaceBlur"), ("Fltn", "flattenImage"), ("BlnW", "blackAndWhite"), ("PhtF", "photoFilter")]; + +pub(super) fn event_for(item: &AtnEvent) -> Option<&'static Event> { + let id = item.id(); + let find = |id: &str| EVENTS.iter().find(|e| (!e.code.is_empty() && e.code.trim_end() == id.trim_end()) || e.name == id); + find(&id).or_else(|| match item { + AtnEvent::Code(_) => LEGACY_CODES.iter().find(|(code, _)| *code == id).and_then(|(_, name)| find(name)), + AtnEvent::Name(_) => None, + }) +} + +/// The event `id` exports as: the first event listing it whose converter accepts the params +/// (Quick Mask on is a `set`, off a `clearEvent`). +pub(super) fn event_and_descriptor(id: &str, params: &Value) -> Option<(&'static Event, Descriptor)> { + EVENTS.iter().filter(|e| e.ids.contains(&id)).find_map(|e| (e.to)(id, params).map(|d| (e, d))) +} diff --git a/crates/engine/src/cmd/atn_cmds/fields.rs b/crates/engine/src/cmd/atn_cmds/fields.rs new file mode 100644 index 0000000000..8dd32a283c --- /dev/null +++ b/crates/engine/src/cmd/atn_cmds/fields.rs @@ -0,0 +1,113 @@ +use super::descriptors::{ang, color_desc, color_hex, enm, get_bool, get_enum, get_num, get_obj, long, pct, px}; +use super::tables::{blend_label, blend_ps, lookup, lookup_back}; +use super::*; + +// ------------------------------------------------------------------ field tables + +#[derive(Clone, Copy)] +pub(super) enum Kind { + Px, + Pct, + Ang, + Long, + /// An integer field whose value must survive conversion without rounding or saturation. + ExactLong, + Dbl, + Bool, + /// An enumeration: its type id and the Photoshop ↔ PhotoCraft value pairs. + Enum(&'static str, &'static [(&'static str, &'static str)]), + /// A blend mode (`BlnM`). + Blend, + /// A colour object ↔ `#rrggbb`. + Color, +} + +/// One descriptor key ↔ one command param. +pub(super) struct F(pub(super) &'static str, pub(super) &'static str, pub(super) Kind); + +/// Import mapped descriptor fields, leaving absent values to command defaults. +/// Return `None` when a present enum, blend mode or colour cannot be represented. +pub(super) fn fields_from(d: &Descriptor, fields: &[F]) -> Option> { + let mut m = Map::new(); + for F(key, param, kind) in fields { + let v = match kind { + Kind::Px | Kind::Pct | Kind::Ang | Kind::Long | Kind::ExactLong | Kind::Dbl => get_num(d, key).map(Value::from), + Kind::Bool => get_bool(d, key).map(Value::from), + Kind::Enum(_, table) => match get_enum(d, key) { + Some(e) => Some(Value::from(lookup(table, &e)?)), + None => None, + }, + Kind::Blend => match get_enum(d, key) { + Some(e) => Some(Value::from(blend_label(&e)?)), + None => None, + }, + Kind::Color => match get_obj(d, key) { + Some(c) => Some(Value::from(color_hex(c)?)), + None => None, + }, + }; + if let Some(v) = v { + m.insert((*param).into(), v); + } + } + Some(m) +} + +/// Export supplied mapped params, omitting absent values to preserve event defaults. +/// Return `None` for unsupported values; `ExactLong` also rejects rounding or saturation. +pub(super) fn fields_to(p: &Value, fields: &[F], mut d: Descriptor) -> Option { + for F(key, param, kind) in fields { + let Some(v) = p.get(param) else { continue }; + let out = match kind { + Kind::Px => px(v.as_f64()?), + Kind::Pct => pct(v.as_f64()?), + Kind::Ang => ang(v.as_f64()?), + // A value outside the descriptor's 32-bit integer refuses the step rather than being + // clamped to another value (an Add Noise seed above i32::MAX replayed as i32::MAX, #7287). + Kind::Long => { + let n = v.as_f64()?.round(); + if !(f64::from(i32::MIN)..=f64::from(i32::MAX)).contains(&n) { + return None; + } + long(n) + } + Kind::ExactLong => { + let number = v.as_f64()?; + let integer = number as i32; + if f64::from(integer) != number { + return None; + } + D::Integer(integer) + } + Kind::Dbl => D::Double(v.as_f64()?), + Kind::Bool => D::Boolean(v.as_bool()?), + Kind::Enum(ty, table) => enm(ty, lookup_back(table, v.as_str()?)?), + Kind::Blend => enm("BlnM", blend_ps(v.as_str()?)?), + Kind::Color => D::Descriptor(color_desc(v.as_str()?)?), + }; + d = d.with(key, out); + } + Some(d) +} + +// ------------------------------------------------------------------ the event table + +/// What one Photoshop step maps to. +pub(super) enum Mapped { + /// One or more PhotoCraft steps (a `make` with a name becomes new layer + rename). + Steps(Vec<(String, Value)>), + /// No PhotoCraft equivalent; `harmless` steps (tool selections…) are imported switched off. + Unsupported { harmless: bool }, +} + +pub(super) fn step(id: &str, params: Value) -> Mapped { + Mapped::Steps(vec![(id.to_string(), params)]) +} + +pub(super) fn steps(v: Vec<(&str, Value)>) -> Mapped { + Mapped::Steps(v.into_iter().map(|(id, p)| (id.to_string(), p)).collect()) +} + +pub(super) fn none(id: &str) -> Mapped { + step(id, json!({})) +} diff --git a/crates/engine/src/cmd/atn_cmds/files.rs b/crates/engine/src/cmd/atn_cmds/files.rs new file mode 100644 index 0000000000..9666a443bb --- /dev/null +++ b/crates/engine/src/cmd/atn_cmds/files.rs @@ -0,0 +1,140 @@ +use super::convert::{UniqueNames, export, import}; +use super::*; + +pub(super) fn load(s: &mut Session, p: &Value) -> Result { + let cmd = "actions.load"; + if s.actions.recording.is_some() || s.actions.playing > 0 { + return Err(bad(cmd, "stop recording or playing before loading actions")); + } + let (bytes, _) = crate::preset_import_cmds::file_bytes(p, cmd, ".atn file")?; + let mut imp = import(&bytes).map_err(|e| bad(cmd, e))?; + match p.get("set") { + None | Some(Value::Null) => {} + Some(Value::String(n)) if !n.trim().is_empty() => { + imp.set = n.trim().to_string(); + for a in &mut imp.actions { + a.set = Some(imp.set.clone()); + } + } + Some(_) => return Err(bad(cmd, "`set` must be a non-empty string")), + } + let replace = match p.get("replace") { + None | Some(Value::Null) => true, + Some(Value::Bool(b)) => *b, + Some(_) => return Err(bad(cmd, "`replace` must be true or false")), + }; + if replace { + s.actions.list.retain(|a| a.set.as_deref() != Some(imp.set.as_str())); + } + let mut taken = UniqueNames::new(s.actions.list.iter().map(|a| a.name.clone())); + let mut names = Vec::with_capacity(imp.actions.len()); + // The file's name of each action that had to be renamed, and its new name. + let mut renamed: std::collections::HashMap = std::collections::HashMap::new(); + let mut steps = 0usize; + let mut added = Vec::with_capacity(imp.actions.len()); + for mut a in imp.actions { + let name = taken.claim(&a.name); + if name != a.name { + renamed.entry(a.name.clone()).or_insert_with(|| name.clone()); + } + a.name = name.clone(); + steps = steps.saturating_add(a.steps.len()); + names.push(name); + added.push(a); + } + // Play and Conditional steps call actions by name: follow the renames in the actions just + // loaded, each target looked up once by the name the file gave it. + for a in &mut added { + for (id, params) in &mut a.steps { + let keys: &[&str] = match id.as_str() { + "actions.play" => &["action"], + "actions.conditional" => &["then", "else"], + _ => &[], + }; + for key in keys { + if let Some(to) = params.get(*key).and_then(Value::as_str).and_then(|n| renamed.get(n)) { + params[*key] = json!(to); + } + } + } + } + s.actions.list.extend(added); + let keys: Vec<(String, String)> = imp.function_keys.into_iter().map(|(n, k)| (renamed.get(&n).cloned().unwrap_or(n), k)).collect(); + if !keys.is_empty() { + s.edit_prefs(|prefs| { + for (name, key) in &keys { + // A function key belongs to one action. + prefs.shortcuts.retain(|k, v| !(k.starts_with(crate::actions_cmds::PLAY_SHORTCUT_PREFIX) && v == key)); + prefs.shortcuts.insert(format!("{}{name}", crate::actions_cmds::PLAY_SHORTCUT_PREFIX), key.clone()); + } + }); + } + s.actions.touch(); + Ok(json!({ + "set": imp.set, + "actions": names, + "steps": steps, + "unsupported": imp.unsupported, + "functionKeys": keys.iter().map(|(n, k)| json!({"action": n, "key": k})).collect::>(), + "warnings": imp.warnings, + })) +} + +pub(super) fn save(s: &mut Session, p: &Value) -> Result { + let cmd = "actions.save"; + crate::actions_cmds::flush_recording(s)?; + let skip = match p.get("skipUnsupported") { + None | Some(Value::Null) => false, + Some(Value::Bool(b)) => *b, + Some(_) => return Err(bad(cmd, "`skipUnsupported` must be true or false")), + }; + let set_param = match p.get("set") { + None | Some(Value::Null) => None, + Some(Value::String(n)) if !n.trim().is_empty() => Some(n.trim().to_string()), + Some(_) => return Err(bad(cmd, "`set` must be a non-empty string")), + }; + let (set, actions): (String, Vec<&Action>) = if p.get("action").is_some() { + let idx = crate::actions_cmds::resolve(&s.actions.list, p, cmd)?; + let a = &s.actions.list[idx]; + (set_param.or_else(|| a.set.clone()).unwrap_or_else(|| a.name.clone()), vec![a]) + } else if let Some(set) = set_param { + let list: Vec<&Action> = s.actions.list.iter().filter(|a| a.set.as_deref() == Some(set.as_str())).collect(); + if list.is_empty() { + return Err(bad(cmd, format!("no actions in a set named `{set}`"))); + } + (set, list) + } else { + (DEFAULT_SET.to_string(), s.actions.list.iter().collect()) + }; + if actions.is_empty() { + return Err(bad(cmd, "there are no actions to save")); + } + let names: Vec = actions.iter().map(|a| a.name.clone()).collect(); + let keys: Vec<(String, String)> = + s.prefs().shortcuts.iter().filter_map(|(k, v)| k.strip_prefix(crate::actions_cmds::PLAY_SHORTCUT_PREFIX).map(|n| (n.to_string(), v.clone()))).collect(); + let (bytes, skipped) = export(&set, &actions, &keys, skip).map_err(|e| bad(cmd, e))?; + let steps: usize = actions.iter().map(|a| a.steps.len()).sum::().saturating_sub(skipped.len()); + let mut out = json!({"set": set, "actions": names, "steps": steps, "bytes": bytes.len(), "skipped": skipped}); + match p.get("path") { + None | Some(Value::Null) => { + out["data"] = json!(photocraft_paint::tile::b64_encode(&bytes)); + } + Some(Value::String(path)) if !path.trim().is_empty() => { + write_file(path, &bytes).map_err(|e| EngineError::Other(format!("{path}: {e}")))?; + out["path"] = json!(path); + } + Some(_) => return Err(bad(cmd, "`path` must be a non-empty string")), + } + Ok(out) +} + +#[cfg(not(target_arch = "wasm32"))] +fn write_file(path: &str, bytes: &[u8]) -> std::io::Result<()> { + // Atomic replacement (temporary file + rename): a failed write keeps the previous ATN (#7290). + photocraft_format::atomic_write(std::path::Path::new(path), bytes) +} + +#[cfg(target_arch = "wasm32")] +fn write_file(path: &str, _bytes: &[u8]) -> std::io::Result<()> { + Err(std::io::Error::other(format!("cannot write paths on the web ({path}); omit `path` to get the bytes back as `data`"))) +} diff --git a/crates/engine/src/atn_cmds/layer_props_tests.rs b/crates/engine/src/cmd/atn_cmds/layer_props_tests.rs similarity index 100% rename from crates/engine/src/atn_cmds/layer_props_tests.rs rename to crates/engine/src/cmd/atn_cmds/layer_props_tests.rs diff --git a/crates/engine/src/cmd/atn_cmds/steps_doc.rs b/crates/engine/src/cmd/atn_cmds/steps_doc.rs new file mode 100644 index 0000000000..36100c1066 --- /dev/null +++ b/crates/engine/src/cmd/atn_cmds/steps_doc.rs @@ -0,0 +1,558 @@ +use super::convert::clip_name; +use super::descriptors::{ + PCT, PX, Target, ang, class, color_desc, color_hex, desc, enm, get_bool, get_enum, get_num, get_obj, get_ref, get_text, jbool, jnum, jstr, long, path_text, + path_value, pct, px, target, target_ref, text, trimmed, +}; +use super::fields::{Mapped, none, step, steps}; +use super::tables::{ALIGN, EXTENSION, INTENT, INTERPOLATION, MODES, PROFILES, PURGE, SAVE_FORMATS, lookup, lookup_back}; +use super::*; + +/// `placeEvent`: File › Place Embedded / Linked, with the file and the recorded scale. +pub(super) fn place_from(d: &Descriptor) -> Mapped { + let Some(path) = d.get("null").and_then(path_text) else { return Mapped::Unsupported { harmless: false } }; + let mut p = json!({"path": path}); + if let Some(w) = get_num(d, "Wdth") { + p["scale"] = json!(w); + } + step(if get_bool(d, "Lnkd") == Some(true) { "file.placeLinked" } else { "file.placeEmbedded" }, p) +} + +pub(super) fn place_to(id: &str, p: &Value) -> Option { + let mut d = desc("null").with("null", path_value(jstr(p, "path")?)).with("FTcs", enm("QCSt", "Qcsa")); + if let Some(s) = jnum(p, "scale") { + d = d.with("Wdth", pct(s)).with("Hght", pct(s)); + } + Some(d.with("Lnkd", D::Boolean(id == "file.placeLinked")).with("Antl", D::Boolean(true))) +} + +/// `open`: File › Open of a recorded path. +pub(super) fn open_from(d: &Descriptor) -> Mapped { + match d.get("null").and_then(path_text) { + Some(path) => step("file.openAs", json!({"path": path})), + None => Mapped::Unsupported { harmless: false }, + } +} + +pub(super) fn open_to(_: &str, p: &Value) -> Option { + Some(desc("null").with("null", path_value(jstr(p, "path")?))) +} + +fn path_extension(path: &str) -> Option { + let name = path.rsplit(['/', '\\']).next()?; + let (stem, ext) = name.rsplit_once('.')?; + (!stem.is_empty() && !ext.is_empty()).then(|| ext.to_ascii_lowercase()) +} + +/// `save`: a plain Save, or a Save As (`As` format, `In` destination, `Cpy` As a Copy). +/// Only a destination that is a file of the recorded format imports: a folder (#5430), a missing +/// or unknown format or a mismatched extension stays a kept Photoshop step, so playback stops +/// before writing rather than saving over the played file (#7102). +pub(super) fn save_from(d: &Descriptor) -> Mapped { + let unsupported = Mapped::Unsupported { harmless: false }; + if d.get("As ").is_none() && d.get("In ").is_none() { + return step("file.save", json!({})); + } + // A Save As needs a format descriptor to check the destination against: without one (or + // with a format that isn't a descriptor) the step is kept. + let Some(format) = get_obj(d, "As ") else { return unsupported }; + let Some(path) = d.get("In ").and_then(path_text) else { return unsupported }; + if get_bool(d, "DIDr") == Some(true) { + return unsupported; + } + let Some(ext) = path_extension(&path) else { return unsupported }; + let class = trimmed(&format.class_id); + let Some((_, exts)) = SAVE_FORMATS.iter().find(|(c, _)| *c == class) else { return unsupported }; + if !exts.contains(&ext.as_str()) { + return unsupported; + } + step(if get_bool(d, "Cpy ") == Some(true) { "file.saveACopy" } else { "file.saveAs" }, json!({"path": path})) +} + +pub(super) fn save_to(id: &str, p: &Value) -> Option { + if id == "file.save" { + return Some(desc("null")); + } + let path = jstr(p, "path")?; + let ext = path_extension(path)?; + let (class, _) = SAVE_FORMATS.iter().find(|(_, exts)| exts.contains(&ext.as_str()))?; + let d = desc("null").with("As ", D::Descriptor(desc(class))).with("In ", path_value(path)); + Some(if id == "file.saveACopy" { d.with("Cpy ", D::Boolean(true)) } else { d }) +} + +/// Photoshop's four-character condition codes that differ from the string ids. +const CONDITION_CODES: &[(&str, &str)] = &[("Lyrs", "hasLayers")]; + +/// `conditional`: Insert Conditional, with its Then and Else actions by name. +pub(super) fn conditional_from(d: &Descriptor) -> Mapped { + let Some(c) = get_enum(d, "null") else { return Mapped::Unsupported { harmless: false } }; + let condition = lookup(CONDITION_CODES, &c).unwrap_or(c.as_str()); + if !crate::actions_edit_cmds::CONDITIONS.contains(&condition) { + return Mapped::Unsupported { harmless: false }; + } + let branch = |key: &str| match get_ref(d, key).map(target) { + // Clipped like the stored action names, so the load-time rename map finds it. + Some(Target::Name(n)) => Some(clip_name(&n)), + _ => None, + }; + step("actions.conditional", json!({"if": condition, "then": branch("then"), "else": branch("else")})) +} + +pub(super) fn conditional_to(_: &str, p: &Value) -> Option { + let condition = jstr(p, "if")?; + let code = lookup_back(CONDITION_CODES, condition).unwrap_or(condition); + let mut d = desc("null").with("null", enm("Cndt", code)); + for key in ["then", "else"] { + if let Some(name) = jstr(p, key) { + let mut items = vec![ReferenceItem::Name { class: class("Actn"), name: UnicodeString::new_nul(name) }]; + if let Some(set) = jstr(p, "set") { + items.push(ReferenceItem::Name { class: class("ASet"), name: UnicodeString::new_nul(set) }); + } + d = d.with(key, D::Reference(items)); + } + } + Some(d) +} + +/// `close`: Photoshop's Save prompt answer becomes a Save step before the Close. +pub(super) fn close_from(d: &Descriptor) -> Mapped { + if get_enum(d, "Svng").as_deref() == Some("Ys") { steps(vec![("file.save", json!({})), ("file.close", json!({}))]) } else { none("file.close") } +} + +/// A Close of an explicit document has no mapping here: written as a plain Close it would +/// close the active document on playback, so it is left to `skipUnsupported`. +pub(super) fn close_to(_: &str, p: &Value) -> Option { + if p.get("document").is_some_and(|d| !d.is_null()) { + return None; + } + Some(desc("null").with("Svng", enm("YsN ", "N "))) +} + +const WEB_FORMATS: &[(&str, &str)] = &[("PN24", "png24"), ("PN8", "png8"), ("JPEG", "jpeg"), ("GIFf", "gif"), ("WBMP", "wbmp")]; + +/// `export` (Save for Web): needs the destination path (`In`), as the command writes a file. +pub(super) fn export_from(d: &Descriptor) -> Mapped { + let unsupported = Mapped::Unsupported { harmless: false }; + let Some(u) = get_obj(d, "Usng") else { return unsupported }; + let Some(path) = d.get("In ").and_then(path_text) else { return unsupported }; + let mut p = json!({"path": path}); + if let Some(f) = get_enum(u, "Fmt ") { + match lookup(WEB_FORMATS, &f) { + Some(f) => p["format"] = json!(f), + None => return unsupported, + } + } + for (key, param) in [("Intr", "interlaced"), ("Trns", "transparency"), ("EICC", "embedIcc"), ("Prgr", "progressive"), ("Optm", "optimized")] { + if let Some(b) = get_bool(u, key) { + p[param] = json!(b); + } + } + for (key, param) in [("Qlty", "quality"), ("NCol", "colors")] { + if let Some(v) = get_num(u, key) { + p[param] = json!(v); + } + } + if get_bool(u, "Mtt ") == Some(false) { + p["matte"] = json!("none"); + } else if let (Some(r), Some(g), Some(b)) = (get_num(u, "MttR"), get_num(u, "MttG"), get_num(u, "MttB")) { + p["matte"] = + json!(format!("#{:02x}{:02x}{:02x}", r.round().clamp(0.0, 255.0) as u8, g.round().clamp(0.0, 255.0) as u8, b.round().clamp(0.0, 255.0) as u8)); + } + step("file.export.saveForWebLegacy", p) +} + +pub(super) fn export_to(_: &str, p: &Value) -> Option { + let path = jstr(p, "path")?; + let mut u = desc("SaveForWeb").with("Op ", enm("SWOp", "OpSa")).with("Fmt ", enm("IRFm", lookup_back(WEB_FORMATS, jstr(p, "format").unwrap_or("png24"))?)); + for (key, param, default) in [ + ("Intr", "interlaced", false), + ("Trns", "transparency", true), + ("EICC", "embedIcc", false), + ("Prgr", "progressive", false), + ("Optm", "optimized", true), + ] { + u = u.with(key, D::Boolean(jbool(p, param).unwrap_or(default))); + } + if let Some(q) = jnum(p, "quality") { + u = u.with("Qlty", long(q)); + } + if let Some(c) = jnum(p, "colors") { + u = u.with("NCol", long(c)); + } + match jstr(p, "matte") { + Some("none") => u = u.with("Mtt ", D::Boolean(false)), + matte => { + let c = color_desc(matte.unwrap_or("#ffffff"))?; + u = u + .with("Mtt ", D::Boolean(true)) + .with("MttR", get_num(&c, "Rd ").map(long)?) + .with("MttG", get_num(&c, "Grn ").map(long)?) + .with("MttB", get_num(&c, "Bl ").map(long)?); + } + } + Some(desc("null").with("Usng", D::Descriptor(u)).with("In ", path_value(path))) +} + +pub(super) fn convert_mode_from(d: &Descriptor) -> Mapped { + if let Some(depth) = get_num(d, "Dpth") { + return match depth as i64 { + 8 => none("image.mode.bits8"), + 16 => none("image.mode.bits16"), + 32 => none("image.mode.bits32"), + _ => Mapped::Unsupported { harmless: false }, + }; + } + // The mode as an enumeration (`ClrS.Grys`), a class (`Grys`), or an object of the mode's + // class holding its options (`BtmM {Rslt, Mthd}`, `Grys {Rt}` from Bitmap). + let (mode, options) = match d.get("T ") { + Some(D::Enumerated { value, .. }) => (trimmed(value), None), + Some(D::Class(c)) => (trimmed(&c.class_id), None), + Some(D::Descriptor(o)) => (trimmed(&o.class_id), Some(o)), + _ => return Mapped::Unsupported { harmless: false }, + }; + if mode == "BtmM" { + return bitmap_from(options); + } + // Bitmap to Grayscale records a size ratio; only 1 keeps the pixels as they are. + if options.and_then(|o| get_num(o, "Rt ")).is_some_and(|r| (r - 1.0).abs() > 1e-9) { + return Mapped::Unsupported { harmless: false }; + } + match lookup(MODES, &mode) { + Some(m) => none(&format!("image.mode.{m}")), + None => Mapped::Unsupported { harmless: false }, + } +} + +const BITMAP_METHOD: &[(&str, &str)] = &[("Thrh", "threshold"), ("PtnD", "pattern"), ("DfnD", "diffusion")]; + +/// Image › Mode › Bitmap. Its Output resolution resamples the image, keeping the print size, +/// before the conversion; at the document's own resolution that is a no-op. Halftone screens +/// and custom patterns stay unsupported. +fn bitmap_from(options: Option<&Descriptor>) -> Mapped { + let Some(o) = options else { return none("image.mode.bitmap") }; + let method = match get_enum(o, "Mthd") { + None => "diffusion", + Some(m) => match lookup(BITMAP_METHOD, &m) { + Some(m) => m, + None => return Mapped::Unsupported { harmless: false }, + }, + }; + let convert = ("image.mode.bitmap", json!({"method": method})); + match get_num(o, "Rslt") { + Some(r) => steps(vec![("image.imageSize", json!({"resolution": r, "resample": "bicubic", "keepPrintSize": true})), convert]), + None => steps(vec![convert]), + } +} + +fn bitmap_to(p: &Value) -> Option { + let method = lookup_back(BITMAP_METHOD, jstr(p, "method").unwrap_or("diffusion"))?; + Some(desc("null").with("T ", D::Descriptor(desc("BtmM").with("Mthd", enm("Mthd", method))))) +} + +pub(super) fn convert_mode_to(id: &str, p: &Value) -> Option { + Some(match id { + "image.mode.bits8" => desc("null").with("Dpth", long(8.0)), + "image.mode.bits16" => desc("null").with("Dpth", long(16.0)), + "image.mode.bits32" => desc("null").with("Dpth", long(32.0)), + "image.mode.bitmap" => bitmap_to(p)?, + _ => desc("null").with("T ", enm("ClrS", lookup_back(MODES, id.strip_prefix("image.mode.")?)?)), + }) +} + +pub(super) fn canvas_size_from(d: &Descriptor) -> Mapped { + let mut p = Map::new(); + for (k, param) in [("Wdth", "width"), ("Hght", "height")] { + match d.get(k) { + Some(D::UnitFloat { unit: PX, value }) => { + p.insert(param.into(), value.round().into()); + } + Some(_) => return Mapped::Unsupported { harmless: false }, + None => {} + } + } + if let Some(r) = get_bool(d, "Rltv") { + p.insert("relative".into(), r.into()); + } + let v = get_enum(d, "Vrtc").unwrap_or_else(|| "Cntr".into()); + let h = get_enum(d, "Hrzn").unwrap_or_else(|| "Cntr".into()); + let anchor = match (v.as_str(), h.as_str()) { + ("Top", "Left") => "topLeft", + ("Top", "Cntr") => "top", + ("Top", "Rght") => "topRight", + ("Cntr", "Left") => "left", + ("Cntr", "Cntr") => "center", + ("Cntr", "Rght") => "right", + ("Bttm", "Left") => "bottomLeft", + ("Bttm", "Cntr") => "bottom", + ("Bttm", "Rght") => "bottomRight", + _ => return Mapped::Unsupported { harmless: false }, + }; + p.insert("anchor".into(), anchor.into()); + if let Some(c) = get_enum(d, "canvasExtensionColorType") { + match lookup(EXTENSION, &c) { + Some(c) => { + p.insert("extensionColor".into(), c.into()); + } + None => match get_obj(d, "canvasExtensionColor").and_then(color_hex) { + Some(hex) => { + p.insert("extensionColor".into(), hex.into()); + } + None => return Mapped::Unsupported { harmless: false }, + }, + } + } + step("image.canvasSize", Value::Object(p)) +} + +pub(super) fn canvas_size_to(_: &str, p: &Value) -> Option { + let anchor = jstr(p, "anchor").unwrap_or("center"); + let v = if anchor.starts_with("top") { + "Top " + } else if anchor.starts_with("bottom") { + "Bttm" + } else { + "Cntr" + }; + let h = if anchor.to_ascii_lowercase().ends_with("left") { + "Left" + } else if anchor.to_ascii_lowercase().ends_with("right") { + "Rght" + } else { + "Cntr" + }; + let mut d = desc("null"); + if let Some(r) = jbool(p, "relative") { + d = d.with("Rltv", D::Boolean(r)); + } + if let Some(w) = jnum(p, "width") { + d = d.with("Wdth", px(w)); + } + if let Some(hh) = jnum(p, "height") { + d = d.with("Hght", px(hh)); + } + d = d.with("Hrzn", enm("HrzL", h)).with("Vrtc", enm("VrtL", v)); + if let Some(c) = jstr(p, "extensionColor") { + d = match lookup_back(EXTENSION, c) { + Some(e) => d.with("canvasExtensionColorType", enm("canvasExtensionColorType", e)), + None => d.with("canvasExtensionColorType", enm("canvasExtensionColorType", "Othr")).with("canvasExtensionColor", D::Descriptor(color_desc(c)?)), + }; + } + Some(d) +} + +pub(super) fn image_size_from(d: &Descriptor) -> Mapped { + let mut p = Map::new(); + let mut percent: Option = None; + for (k, param) in [("Wdth", "width"), ("Hght", "height")] { + match d.get(k) { + Some(D::UnitFloat { unit: PX, value }) => { + p.insert(param.into(), value.round().into()); + } + // Percent scales both sides at playback; two different percentages, or physical + // units, need the document's size and resolution and stay unsupported. + Some(D::UnitFloat { unit: PCT, value }) => match percent { + Some(other) if (other - value).abs() > 1e-9 => return Mapped::Unsupported { harmless: false }, + _ => percent = Some(*value), + }, + Some(_) => return Mapped::Unsupported { harmless: false }, + None => {} + } + } + if let Some(pc) = percent { + p.insert("percent".into(), pc.into()); + } + if let Some(r) = get_num(d, "Rslt") { + p.insert("resolution".into(), r.into()); + } + if let Some(i) = get_enum(d, "Intr") { + match lookup(INTERPOLATION, &i) { + Some(i) => { + p.insert("resample".into(), i.into()); + // Resample on with only the resolution changed: Photoshop keeps the print size. + if p.contains_key("resolution") && !p.contains_key("width") && !p.contains_key("height") && !p.contains_key("percent") { + p.insert("keepPrintSize".into(), true.into()); + } + } + None => return Mapped::Unsupported { harmless: false }, + } + } else if p.contains_key("resolution") && !p.contains_key("width") && !p.contains_key("height") && !p.contains_key("percent") { + p.insert("resample".into(), "none".into()); + } + if p.is_empty() { + return Mapped::Unsupported { harmless: false }; + } + step("image.imageSize", Value::Object(p)) +} + +pub(super) fn image_size_to(_: &str, p: &Value) -> Option { + // Resolution only with Resample on imports as keep-print-size; a command without it cannot be told apart. + if jnum(p, "resolution").is_some() + && jnum(p, "width").is_none() + && jnum(p, "height").is_none() + && jnum(p, "percent").is_none() + && jstr(p, "resample").is_some_and(|r| r != "none") + && jbool(p, "keepPrintSize") != Some(true) + { + return None; + } + let mut d = desc("null"); + // `resample: "none"` changes the resolution only and the command ignores any size then. The + // descriptor has no "none" (it is the absence of `Intr`), so writing the ignored size would + // turn the step into a pixel resize on playback (#7189). + let resolution_only = jstr(p, "resample") == Some("none"); + if resolution_only && jnum(p, "resolution").is_none() { + // Nothing left to record: the step changes nothing. + return None; + } + if let Some(pc) = jnum(p, "percent").filter(|_| !resolution_only) { + d = d.with("Wdth", pct(pc)).with("Hght", pct(pc)).with("CnsP", D::Boolean(true)); + } + if let Some(w) = jnum(p, "width").filter(|_| !resolution_only) { + d = d.with("Wdth", px(w)); + } + if let Some(h) = jnum(p, "height").filter(|_| !resolution_only) { + d = d.with("Hght", px(h)); + } + if let Some(r) = jnum(p, "resolution") { + d = d.with("Rslt", D::UnitFloat { unit: *b"#Rsl", value: r }); + } + if let Some(i) = jstr(p, "resample").filter(|r| *r != "none") { + d = d.with("Intr", enm("Intp", lookup_back(INTERPOLATION, i)?)); + } + Some(d) +} + +pub(super) fn crop_from(d: &Descriptor) -> Mapped { + let mut p = Map::new(); + if let Some(t) = get_obj(d, "To ") { + // Pixels only, like Canvas Size: a side in percent or points needs the document's size + // or resolution and must not be played as pixels. + let side = |k: &str| match t.get(k) { + Some(D::UnitFloat { unit: PX, value }) if value.is_finite() => Some(*value), + _ => None, + }; + let (Some(top), Some(left), Some(bottom), Some(right)) = (side("Top "), side("Left"), side("Btom"), side("Rght")) else { + return Mapped::Unsupported { harmless: false }; + }; + p.insert("x".into(), left.round().into()); + p.insert("y".into(), top.round().into()); + p.insert("width".into(), (right - left).round().into()); + p.insert("height".into(), (bottom - top).round().into()); + } + if let Some(a) = get_num(d, "Angl") { + p.insert("angle".into(), a.into()); + } + if let Some(del) = get_bool(d, "Dlt ") { + p.insert("deleteCroppedPixels".into(), del.into()); + } + step("image.crop", Value::Object(p)) +} + +pub(super) fn crop_to(_: &str, p: &Value) -> Option { + // The W x H x Resolution output options have no field here: refuse rather than export a plain + // rectangle crop that keeps the old size and resolution on replay. + if ["targetWidth", "targetHeight", "resolution"].iter().any(|k| p.get(k).is_some_and(|v| !v.is_null())) { + return None; + } + let mut d = desc("null"); + if let (Some(x), Some(y), Some(w), Some(h)) = (jnum(p, "x"), jnum(p, "y"), jnum(p, "width"), jnum(p, "height")) { + d = d.with("To ", D::Descriptor(desc("Rctn").with("Top ", px(y)).with("Left", px(x)).with("Btom", px(y + h)).with("Rght", px(x + w)))); + } + if let Some(a) = jnum(p, "angle") { + d = d.with("Angl", ang(a)); + } + if let Some(del) = jbool(p, "deleteCroppedPixels") { + d = d.with("Dlt ", D::Boolean(del)); + } + Some(d) +} + +pub(super) fn stop_from(d: &Descriptor) -> Mapped { + step(STOP_MESSAGE, json!({"message": get_text(d, "Msge").unwrap_or_default(), "allowContinue": get_bool(d, "Cntn").unwrap_or(false)})) +} + +pub(super) fn stop_to(_: &str, p: &Value) -> Option { + Some(desc("null").with("Msge", text(jstr(p, "message").unwrap_or(""))).with("Cntn", D::Boolean(jbool(p, "allowContinue").unwrap_or(false)))) +} + +pub(super) fn paste_from(d: &Descriptor) -> Mapped { + none(if get_bool(d, "inPlace") == Some(true) { "edit.pasteSpecial.pasteInPlace" } else { "edit.paste" }) +} + +pub(super) fn paste_to(id: &str, _: &Value) -> Option { + let mut d = desc("null"); + if id == "edit.pasteSpecial.pasteInPlace" { + d = d.with("inPlace", D::Boolean(true)); + } + Some(d.with("AntA", enm("Annt", "Anno"))) +} + +pub(super) fn merge_visible_from(d: &Descriptor) -> Mapped { + none(if get_bool(d, "Dplc") == Some(true) { "layer.stampVisible" } else { "layer.mergeVisible" }) +} + +pub(super) fn merge_visible_to(id: &str, _: &Value) -> Option { + Some(if id == "layer.stampVisible" { desc("null").with("Dplc", D::Boolean(true)) } else { desc("null") }) +} + +pub(super) fn align_from(d: &Descriptor) -> Mapped { + match get_enum(d, "Usng").and_then(|u| lookup(ALIGN, &u)) { + Some(a) => step(&format!("layer.align.{a}"), if get_bool(d, "alignToCanvas") == Some(true) { json!({"to": "canvas"}) } else { json!({}) }), + None => Mapped::Unsupported { harmless: false }, + } +} + +pub(super) fn align_to(id: &str, p: &Value) -> Option { + let a = lookup_back(ALIGN, id.strip_prefix("layer.align.")?)?; + Some(desc("null").with("null", target_ref("Lyr ")).with("Usng", enm("ADSt", a)).with("alignToCanvas", D::Boolean(jstr(p, "to") == Some("canvas")))) +} + +pub(super) fn purge_from(d: &Descriptor) -> Mapped { + match get_enum(d, "null").and_then(|u| lookup(PURGE, &u)) { + Some(p) => none(&format!("edit.purge.{p}")), + None => Mapped::Unsupported { harmless: true }, + } +} + +pub(super) fn purge_to(id: &str, _: &Value) -> Option { + Some(desc("null").with("null", enm("PrgI", lookup_back(PURGE, id.strip_prefix("edit.purge.")?)?))) +} + +pub(super) fn reset_from(d: &Descriptor) -> Mapped { + match get_ref(d, "null").map(target) { + Some(Target::Property(p)) if p == "Clrs" => none("tools.defaultColors"), + _ => Mapped::Unsupported { harmless: true }, + } +} + +pub(super) fn reset_to(_: &str, _: &Value) -> Option { + Some(desc("null").with("null", D::Reference(vec![ReferenceItem::Property { class: class("Clr "), key: Id::new("Clrs") }]))) +} + +pub(super) fn profile_from(d: &Descriptor, id: &str) -> Mapped { + let name = get_text(d, "T ").or_else(|| get_text(d, "profile")); + let Some(profile) = name.as_deref().and_then(|n| lookup(PROFILES, n)) else { return Mapped::Unsupported { harmless: false } }; + let mut p = json!({"profile": profile}); + if id == "edit.convertToProfile" { + if let Some(i) = get_enum(d, "Inte").and_then(|i| lookup(INTENT, &i)) { + p["intent"] = json!(i); + } + if let Some(b) = get_bool(d, "MpBl") { + p["bpc"] = json!(b); + } + } + step(id, p) +} + +pub(super) fn profile_to(id: &str, p: &Value) -> Option { + let name = lookup_back(PROFILES, jstr(p, "profile")?)?; + let mut d = desc("null").with("null", target_ref("Dcmn")); + if id == "edit.convertToProfile" { + d = d + .with("T ", text(name)) + .with("Inte", enm("Inte", lookup_back(INTENT, jstr(p, "intent").unwrap_or("relative"))?)) + .with("MpBl", D::Boolean(jbool(p, "bpc").unwrap_or(true))); + } else { + d = d.with("profile", text(name)); + } + Some(d) +} diff --git a/crates/engine/src/cmd/atn_cmds/steps_image.rs b/crates/engine/src/cmd/atn_cmds/steps_image.rs new file mode 100644 index 0000000000..bb8e1c82fd --- /dev/null +++ b/crates/engine/src/cmd/atn_cmds/steps_image.rs @@ -0,0 +1,453 @@ +use super::descriptors::{ + PX, Target, ang, class, code, desc, enm, get_bool, get_enum, get_num, get_obj, get_ref, jbool, jnum, jstr, layer_ref, layer_target, long, pct, px, + ref_class, target, trimmed, +}; +use super::events::pixel_target; +use super::fields::{F, Kind, Mapped, fields_from, fields_to, step}; +use super::tables::{CHANNELS, INTERPOLATION, RADIAL_METHOD, RADIAL_QUALITY, lookup, lookup_back}; +use super::*; + +/// `transform`: Photoshop records a Free Transform relative to the frame (offset of its centre, +/// width/height in percent, angle). A layer moved only becomes `layer.translate`; anything +/// else is `edit.transform`'s relative form; the selection's frame is `select.transformSelection`. +pub(super) fn transform_from(d: &Descriptor) -> Mapped { + // No reference (a smart object replaced in place, `replaceLayer`) means the target layer. + let target_layer = [ReferenceItem::Enumerated { class: class("Lyr "), type_id: code("Ordn"), value: code("Trgt") }]; + let r: &[ReferenceItem] = get_ref(d, "null").unwrap_or(&target_layer); + let unsupported = Mapped::Unsupported { harmless: false }; + let mut p = Map::new(); + if let Some(o) = get_obj(d, "Ofst") { + let in_px = |k: &str| matches!(o.get(k), Some(D::UnitFloat { unit: PX, .. })); + if !in_px("Hrzn") || !in_px("Vrtc") { + return unsupported; + } + if let Some(x) = get_num(o, "Hrzn") { + p.insert("dx".into(), x.into()); + } + if let Some(y) = get_num(o, "Vrtc") { + p.insert("dy".into(), y.into()); + } + } + for (key, param) in [("Wdth", "scaleX"), ("Hght", "scaleY"), ("Angl", "rotate")] { + if let Some(v) = get_num(d, key) { + p.insert(param.into(), v.into()); + } + } + if d.get("Skew").is_some() || d.get("Usng").is_some() { + return unsupported; + } + // A whole-pixel move is a plain `layer.translate`; a fractional one needs `edit.transform` + // to keep its sub-pixel placement and interpolation. + let whole_pixels = ["dx", "dy"].iter().all(|k| p.get(*k).and_then(Value::as_f64).is_none_or(|v| v.fract() == 0.0)); + let geometry_only = p.keys().all(|k| k == "dx" || k == "dy") && whole_pixels; + // The resampling applies to a selection as much as to a layer (#7515). + // Photoshop's bicubic variants are kept (the transforms render them as Bicubic, and they export + // back unchanged); Automatic and Preserve Details become the nearest bicubic choice. Dropping + // them fell back to the command's default, bilinear for a selection (#8697). + let interpolation = get_enum(d, "Intr").and_then(|i| lookup(INTERPOLATION, &i)).and_then(|i| match i { + "bicubic" | "bilinear" | "nearest" | "bicubicSharper" | "bicubicSmoother" | "bicubicAutomatic" => Some(i), + "automatic" => Some("bicubicAutomatic"), + "preserveDetails" => Some("bicubic"), + _ => None, + }); + match (ref_class(r).as_deref(), target(r)) { + (Some("Chnl"), Target::Property(prop)) if prop == "fsel" => { + if let Some(i) = interpolation { + p.insert("interpolation".into(), i.into()); + } + step("select.transformSelection", Value::Object(p)) + } + (Some("Lyr"), _) => { + let Some(mut lp) = layer_target(r) else { return unsupported }; + if geometry_only { + lp.insert("dx".into(), p.get("dx").and_then(Value::as_f64).unwrap_or(0.0).into()); + lp.insert("dy".into(), p.get("dy").and_then(Value::as_f64).unwrap_or(0.0).into()); + return step("layer.translate", Value::Object(lp)); + } + lp.extend(p); + if let Some(i) = interpolation { + lp.insert("interpolation".into(), i.into()); + } + step("edit.transform", Value::Object(lp)) + } + _ => unsupported, + } +} + +pub(super) fn transform_to(id: &str, p: &Value) -> Option { + let given = |k: &str| p.get(k).is_some_and(|v| !v.is_null()); + if ["quad", "corners", "matrix", "rect"].iter().any(|k| given(k)) { + return None; + } + // The descriptor scales and rotates about the centre (`FTcs` average) without skew or warp: + // another reference point, a skew or a warp would replay as a different transform (#7516, + // #7517, #7518, #7519). + let nonzero = |k: &str| p.get(k).is_some_and(|v| !v.is_null() && v.as_f64() != Some(0.0)); + let off_centre = p.get("reference").is_some_and(|v| !v.is_null() && *v != json!("center")); + if nonzero("skewX") || nonzero("skewY") || off_centre || ["warp", "style", "mesh", "grid"].iter().any(|k| given(k)) { + return None; + } + let target = match id { + // The `Trnf` descriptor has no field for a mask, Quick Mask or alpha channel target; a + // layer reference would transform the layer's pixels instead. + "edit.transform" if !pixel_target(p) => return None, + "edit.transform" => layer_ref(p)?, + "select.transformSelection" => D::Reference(vec![ReferenceItem::Property { class: class("Chnl"), key: code("fsel") }]), + _ => return None, + }; + let mut d = desc("null").with("null", target).with("FTcs", enm("QCSt", "Qcsa")); + d = d.with("Ofst", D::Descriptor(desc("Ofst").with("Hrzn", px(jnum(p, "dx").unwrap_or(0.0))).with("Vrtc", px(jnum(p, "dy").unwrap_or(0.0))))); + for (key, param) in [("Wdth", "scaleX"), ("Hght", "scaleY")] { + if let Some(v) = jnum(p, param) { + d = d.with(key, pct(v)); + } + } + if let Some(a) = jnum(p, "rotate") { + d = d.with("Angl", ang(a)); + } + if let Some(i) = jstr(p, "interpolation").and_then(|i| lookup_back(INTERPOLATION, i)) { + d = d.with("Intr", enm("Intp", i)); + } + Some(d) +} + +/// `Clcn` (Apply Image / Calculations blending) ↔ `image.applyImage`'s `blending`. +const CALC_BLEND: &[(&str, &str)] = &[ + ("Nrml", "normal"), + ("Mltp", "multiply"), + ("Scrn", "screen"), + ("Ovrl", "overlay"), + ("SftL", "softLight"), + ("HrdL", "hardLight"), + ("CDdg", "colorDodge"), + ("CBrn", "colorBurn"), + ("Drkn", "darken"), + ("Lghn", "lighten"), + ("Dfrn", "difference"), + ("Xclu", "exclusion"), + ("linearBurn", "linearBurn"), + ("linearDodge", "linearDodge"), + ("Add ", "add"), + ("Sbtr", "subtract"), +]; + +const SOURCE_CHANNELS: &[(&str, &str)] = + &[("RGB", "composite"), ("CMYK", "composite"), ("Lab", "composite"), ("Trsp", "transparency"), ("Msk", "mask"), ("fsel", "selection")]; + +pub(super) fn apply_image_from(d: &Descriptor) -> Mapped { + let unsupported = Mapped::Unsupported { harmless: false }; + let Some(with) = get_obj(d, "With") else { return unsupported }; + let Some(r) = get_ref(with, "T ") else { return unsupported }; + let mut source = Map::new(); + for item in r { + match item { + ReferenceItem::Enumerated { class, value, .. } if class.class_id.is("Chnl") => { + let v = trimmed(value); + let Some(channel) = lookup(SOURCE_CHANNELS, &v).or_else(|| lookup(CHANNELS, &v)) else { return unsupported }; + source.insert("channel".into(), channel.into()); + } + // A named (alpha) channel. + ReferenceItem::Name { class, name } if class.class_id.is("Chnl") => { + source.insert("channel".into(), name.to_string_lossy().into()); + } + ReferenceItem::Name { class, name } if class.class_id.is("Lyr ") => { + source.insert("layer".into(), name.to_string_lossy().into()); + } + ReferenceItem::Enumerated { class, value, .. } if class.class_id.is("Lyr ") && trimmed(value) == "Mrgd" => { + source.insert("layer".into(), "merged".into()); + } + _ => return unsupported, + } + } + if let Some(i) = get_bool(with, "Invr") { + source.insert("invert".into(), i.into()); + } + let mut p = json!({"source": source}); + if let Some(c) = get_enum(with, "Clcl") { + match lookup(CALC_BLEND, &c) { + Some(b) => p["blending"] = json!(b), + None => return unsupported, + } + } + for (key, param) in [("Scl ", "scale"), ("Ofst", "offset"), ("Opct", "opacity")] { + if let Some(v) = get_num(with, key) { + p[param] = json!(v); + } + } + if let Some(t) = get_bool(with, "PrsT") { + p["preserveTransparency"] = json!(t); + } + step("image.applyImage", p) +} + +/// Apply Image's source channel as a `Chnl` reference item. The dialog sends Channels-panel names +/// ("RGB", "Red", "Alpha 1"), which the command reads case-insensitively: the composite names map to +/// the composite, colour names to their enumeration, and any other name to a named (alpha) channel, +/// as Photoshop records it. +fn apply_image_channel(channel: &str) -> Option { + let l = channel.to_ascii_lowercase(); + let key = match l.as_str() { + "rgb" | "cmyk" | "lab" | "merged" => "composite", + "layermask" => "mask", + // Sources the command knows by keyword but Photoshop has no channel for. + "quickmask" | "quick mask" | "vectormask" | "vector mask" => return None, + other => other, + }; + Some(match lookup_back(SOURCE_CHANNELS, key).or_else(|| lookup_back(CHANNELS, key)) { + Some(chan) => ReferenceItem::Enumerated { class: class("Chnl"), type_id: code("Chnl"), value: code(chan) }, + None if !channel.trim().is_empty() => ReferenceItem::Name { class: class("Chnl"), name: UnicodeString::new_nul(channel) }, + None => return None, + }) +} + +pub(super) fn apply_image_to(_: &str, p: &Value) -> Option { + // The optional blending mask has no descriptor mapping: refuse it rather than drop it, + // which would widen the edit to the whole layer. + let mask_channel = match p.get("mask") { + Some(m) => m.get("channel"), + None => p.get("maskChannel"), + }; + if mask_channel.is_some_and(|c| !(c.is_null() || c == "none" || c == "")) { + return None; + } + // The Apply Image dialog sends flat `sourceLayer`/`sourceChannel`/`sourceInvert` fields; read + // them as the command does, or the export would quietly reset them to the merged composite. + let source = crate::channel_cmds::source_spec(p, "source", "source").unwrap_or(json!({})); + // A source from another open document has no event form here: skip the step, don't rewrite it. + if source.get("document").is_some_and(|d| !d.is_null()) { + return None; + } + // A layer id or channel index has no name to record: refuse it rather than write the composite. + let not_name = |k: &str| source.get(k).is_some_and(|v| !(v.is_null() || v.is_string())); + if !source.is_object() || not_name("layer") || not_name("channel") { + return None; + } + let mut items = vec![apply_image_channel(jstr(&source, "channel").unwrap_or("composite"))?]; + match jstr(&source, "layer") { + Some("merged") | None => items.push(ReferenceItem::Enumerated { class: class("Lyr "), type_id: code("Ordn"), value: code("Mrgd") }), + Some(name) => items.push(ReferenceItem::Name { class: class("Lyr "), name: UnicodeString::new_nul(name) }), + } + let mut with = desc("null").with("T ", D::Reference(items)); + if let Some(i) = jbool(&source, "invert") { + with = with.with("Invr", D::Boolean(i)); + } + with = with.with("Clcl", enm("Clcn", lookup_back(CALC_BLEND, jstr(p, "blending").unwrap_or("multiply"))?)); + if let Some(v) = jnum(p, "opacity") { + with = with.with("Opct", pct(v)); + } + if let Some(v) = jnum(p, "scale") { + with = with.with("Scl ", D::Double(v)); + } + if let Some(v) = jnum(p, "offset") { + with = with.with("Ofst", D::Double(v)); + } + if let Some(t) = jbool(p, "preserveTransparency") { + with = with.with("PrsT", D::Boolean(t)); + } + Some(desc("null").with("With", D::Descriptor(with))) +} + +pub(super) const RIPPLE_SIZE: &[(&str, &str)] = &[("Sml", "small"), ("Mdm", "medium"), ("Lrg", "large")]; + +/// Whether a Select and Mask step carries Refine Edge Brush strokes or the workspace's tool +/// edits (Quick Selection, Brush, Lasso…), which no descriptor holds. +pub(super) fn has_refine_strokes(p: &Value) -> bool { + p.get("refineStrokes").is_some_and(|v| !v.is_null() && v.as_array().is_none_or(|a| !a.is_empty())) || crate::select_mask_edits::has_edits(p) +} + +/// Select and Mask to Photoshop. The descriptor has no field for the Refine Edge Brush or the +/// workspace's tools, so a step with `refineStrokes` or `edits` can't be exported faithfully. One with `sampleAllLayers` is not +/// exported here either: it exports as `smartBrushWorkspace`. +pub(super) fn refine_edge_to(_: &str, p: &Value) -> Option { + if !pixel_target(p) || p.get("sampleAllLayers").is_some() || has_refine_strokes(p) { + return None; + } + fields_to(p, REFINE_EDGE, desc("null")) +} + +/// Select and Mask (`refineSelectionEdge`). Smart Radius, decontamination and the output follow +/// Photoshop's; the edge itself is PhotoCraft's own matting, so results differ in detail. +pub(super) const REFINE_EDGE: &[F] = &[ + F("refineEdgeBorderRadius", "radius", Kind::Px), + F("refineEdgeAutoRadius", "smartRadius", Kind::Bool), + F("refineEdgeSmooth", "smooth", Kind::Long), + F("refineEdgeFeatherRadius", "feather", Kind::Px), + F("refineEdgeBorderContrast", "contrast", Kind::Pct), + F("refineEdgeChoke", "shiftEdge", Kind::Pct), + F("refineEdgeDecontaminate", "decontaminate", Kind::Bool), + F("refineEdgeDeconAmount", "amount", Kind::Pct), + F("refineEdgeOutput", "output", Kind::Enum("refineEdgeOutput", REFINE_OUTPUT)), +]; + +const REFINE_OUTPUT: &[(&str, &str)] = &[ + ("refineEdgeOutputSelection", "selection"), + ("refineEdgeOutputUserMask", "layerMask"), + ("refineEdgeOutputNewLayer", "newLayer"), + ("refineEdgeOutputNewLayerWithMask", "newLayerWithMask"), + ("refineEdgeOutputNewDocument", "newDocument"), + ("refineEdgeOutputNewDocumentWithMask", "newDocumentWithMask"), +]; + +/// Filter Gallery effects (`GEfc` with the effect in `GEfk`): Photoshop's effect code, the +/// command, and its fields. A stack of several effects stays unsupported. +const GALLERY: &[(&str, &str, &[F])] = &[("Spt", "filter.gallery.spatter", &[F("SprR", "sprayRadius", Kind::Long), F("Smth", "smoothness", Kind::Long)])]; + +pub(super) const GALLERY_IDS: &[&str] = &["filter.gallery.spatter"]; + +pub(super) fn gallery_from(d: &Descriptor) -> Mapped { + let Some(effect) = get_enum(d, "GEfk") else { return Mapped::Unsupported { harmless: false } }; + match GALLERY.iter().find(|(code, _, _)| *code == effect).and_then(|(_, id, fields)| Some((*id, fields_from(d, fields)?))) { + Some((id, p)) => step(id, Value::Object(p)), + None => Mapped::Unsupported { harmless: false }, + } +} + +pub(super) fn gallery_to(id: &str, p: &Value) -> Option { + let (code, _, fields) = GALLERY.iter().find(|(_, cmd, _)| *cmd == id)?; + fields_to(p, fields, desc("null").with("GEfk", enm("GEft", code))) +} + +/// Select and Mask as Photoshop CC 2015.5 and later record it (`smartBrushWorkspace`); the +/// older Refine Edge event is [`REFINE_EDGE`], which is also what Select and Mask exports as. +pub(super) const SMART_BRUSH: &[F] = &[ + F("smartBrushRadius", "radius", Kind::Px), + F("smartBrushUseSmartRadius", "smartRadius", Kind::Bool), + F("smartBrushSmooth", "smooth", Kind::Long), + F("smartBrushFeather", "feather", Kind::Px), + F("smartBrushContrast", "contrast", Kind::Pct), + F("smartBrushShiftEdge", "shiftEdge", Kind::Pct), + F("smartBrushDecontaminate", "decontaminate", Kind::Bool), + F("smartBrushDeconAmount", "amount", Kind::Pct), + F("refineEdgeOutput", "output", Kind::Enum("refineEdgeOutput", REFINE_OUTPUT)), + F("sampleAllLayers", "sampleAllLayers", Kind::Bool), +]; + +/// Select › Color Range's `Clrs` presets ↔ `select.colorRange`'s `select`. +const COLOR_RANGE: &[(&str, &str)] = &[ + ("Rds", "reds"), + ("Ylws", "yellows"), + ("Grns", "greens"), + ("Cyns", "cyans"), + ("Bls", "blues"), + ("Mgnt", "magentas"), + ("Hghl", "highlights"), + ("Mdtn", "midtones"), + ("Shdw", "shadows"), + ("OtOf", "outOfGamut"), + ("skinTone", "skinTones"), +]; + +/// The Color Range keys the converter reads (or that don't change a preset's result: +/// `colorModel` is the model of sampled colours). +const COLOR_RANGE_KEYS: &[&str] = &[ + "Clrs", + "Fzns", + "Invr", + "colorModel", + "shadowsFuzziness", + "shadowsUpperLimit", + "midtonesFuzziness", + "midtonesLowerLimit", + "midtonesUpperLimit", + "highlightsFuzziness", + "highlightsLowerLimit", +]; + +/// Color Range (`ClrR`) with a preset. Sampled Colors records Lab minimum and maximum colours, +/// which `select.colorRange` (eyedropper points on the image) can't reproduce, and an unknown +/// key (Detect Faces, Localized Color Clusters…) could change the result: both stay +/// unsupported. +pub(super) fn color_range_from(d: &Descriptor) -> Mapped { + let unsupported = Mapped::Unsupported { harmless: false }; + if d.items.iter().any(|(k, _)| !COLOR_RANGE_KEYS.contains(&trimmed(k).as_str())) { + return unsupported; + } + let Some(preset) = get_enum(d, "Clrs").and_then(|c| lookup(COLOR_RANGE, &c)) else { return unsupported }; + let mut p = Map::new(); + p.insert("select".into(), preset.into()); + let key = |suffix: &str| get_num(d, &format!("{preset}{suffix}")); + match preset { + "skinTones" => { + if let Some(f) = get_num(d, "Fzns") { + p.insert("fuzziness".into(), f.into()); + } + } + "shadows" | "midtones" | "highlights" => { + if let Some(f) = key("Fuzziness") { + p.insert("fuzziness".into(), f.into()); + } + let range = match (preset, key("LowerLimit"), key("UpperLimit")) { + ("shadows", _, hi) => hi.map(Value::from), + ("highlights", lo, _) => lo.map(Value::from), + (_, Some(lo), Some(hi)) => Some(json!([lo, hi])), + (_, None, None) => None, + _ => return unsupported, + }; + if let Some(r) = range { + p.insert("tonalRange".into(), r); + } + } + _ => {} + } + if get_bool(d, "Invr") == Some(true) { + p.insert("invert".into(), true.into()); + } + step("select.colorRange", Value::Object(p)) +} + +pub(super) fn color_range_to(_: &str, p: &Value) -> Option { + let preset = jstr(p, "select")?; + if p.as_object()?.keys().any(|k| !matches!(k.as_str(), "select" | "fuzziness" | "tonalRange" | "invert")) { + return None; + } + let mut d = desc("null").with("Clrs", enm("Clrs", lookup_back(COLOR_RANGE, preset)?)); + let tonal = matches!(preset, "shadows" | "midtones" | "highlights"); + if let Some(f) = jnum(p, "fuzziness") { + match preset { + "skinTones" => d = d.with("Fzns", long(f)), + _ if tonal => d = d.with(&format!("{preset}Fuzziness"), long(f)), + _ => {} + } + } + if let Some(r) = p.get("tonalRange") { + match preset { + "shadows" => d = d.with("shadowsUpperLimit", long(r.as_f64()?)), + "highlights" => d = d.with("highlightsLowerLimit", long(r.as_f64()?)), + "midtones" => { + let a = r.as_array()?; + d = d.with("midtonesLowerLimit", long(a.first()?.as_f64()?)).with("midtonesUpperLimit", long(a.get(1)?.as_f64()?)); + } + _ => return None, + } + } + if jbool(p, "invert") == Some(true) { + d = d.with("Invr", D::Boolean(true)); + } + Some(d) +} + +const RADIAL_BLUR_FIELDS: &[F] = + &[F("Amnt", "amount", Kind::Long), F("BlrM", "method", Kind::Enum("BlrM", RADIAL_METHOD)), F("BlrQ", "quality", Kind::Enum("BlrQ", RADIAL_QUALITY))]; + +pub(super) fn radial_blur_from(d: &Descriptor) -> Mapped { + match fields_from(d, RADIAL_BLUR_FIELDS) { + Some(m) => step("filter.blur.radialBlur", Value::Object(m)), + None => Mapped::Unsupported { harmless: false }, + } +} + +pub(super) fn radial_blur_to(_: &str, p: &Value) -> Option { + if !pixel_target(p) { + return None; + } + // Photoshop's Radial Blur has no center parameter and always blurs from the center (0.5, 0.5). + // An explicit center must match 0.5 exactly; any non-default center cannot be faithfully exported. + let is_default_center = |k: &str| match p.get(k) { + None | Some(Value::Null) => true, + Some(v) => v.as_f64() == Some(0.5), + }; + if !is_default_center("centerX") || !is_default_center("centerY") { + return None; + } + fields_to(p, RADIAL_BLUR_FIELDS, desc("null")) +} diff --git a/crates/engine/src/cmd/atn_cmds/steps_layer.rs b/crates/engine/src/cmd/atn_cmds/steps_layer.rs new file mode 100644 index 0000000000..36e77d624b --- /dev/null +++ b/crates/engine/src/cmd/atn_cmds/steps_layer.rs @@ -0,0 +1,576 @@ +use super::convert::clip_name; +use super::descriptors::{ + PT, PX, Target, ang, class, code, color_desc, color_hex, desc, enm, get_bool, get_enum, get_num, get_obj, get_ref, get_text, jbool, jnum, jstr, layer_ref, + layer_target, long, name_ref, pct, px, ref_class, target, target_ref, text, trimmed, +}; +use super::events::pixel_target; +use super::fields::{F, Kind, Mapped, fields_to, none, step, steps}; +use super::steps_make::is_tool_class; +use super::tables::{FILL_CONTENTS, INTERPOLATION, MENU_ITEMS, STROKE_LOCATION, blend_label, blend_ps, lookup, lookup_back}; +use super::*; + +pub(super) fn select_from(d: &Descriptor) -> Mapped { + let Some(r) = get_ref(d, "null") else { return Mapped::Unsupported { harmless: false } }; + match (ref_class(r).as_deref(), target(r)) { + (Some("Lyr"), Target::Name(n)) => { + let mut p = json!({"layer": n}); + match get_enum(d, "selectionModifier").as_deref() { + Some("addToSelection") => p["mode"] = json!("add"), + Some("removeFromSelection") => p["mode"] = json!("remove"), + // Shift-click: select everything between the active layer and this one. + Some("addToSelectionContinuous") => p["mode"] = json!("range"), + _ => {} + } + step("layer.select", p) + } + // The Channels panel: the active layer's mask, or back to the composite (`RGB`, `CMYK`…). + (Some("Chnl"), Target::Ordinal(o)) => match o.as_str() { + "Msk" => step("channel.target", json!({"channel": "mask"})), + "RGB" | "CMYK" | "Lab" | "Gry" => step("channel.target", json!({"channel": "composite"})), + // Re-selecting the channel that is already targeted changes nothing. + "Trgt" => Mapped::Unsupported { harmless: true }, + _ => Mapped::Unsupported { harmless: false }, + }, + // History › Step Backward / Step Forward. + (Some("HstS"), Target::Ordinal(o)) if o == "Prvs" => none("edit.undo"), + (Some("HstS"), Target::Ordinal(o)) if o == "Nxt" => none("edit.redo"), + (Some("Lyr"), Target::Ordinal(o)) => { + // Shift+Alt+[ / ] add the next layer to the selection instead of replacing it. + let add = get_enum(d, "selectionModifier").as_deref() == Some("addToSelection"); + match (o.as_str(), add) { + ("Frwr", false) => none("layer.selectAbove"), + ("Frwr", true) => none("layer.addAboveToSelection"), + ("Bckw", false) => none("layer.selectBelow"), + ("Bckw", true) => none("layer.addBelowToSelection"), + ("Frnt", _) => none("layer.selectTop"), + ("Back", _) => none("layer.selectBottom"), + _ => Mapped::Unsupported { harmless: false }, + } + } + (Some(c), Target::Class) if is_tool_class(c) => Mapped::Unsupported { harmless: true }, + // A menu item chosen while recording (`Mn`): the View menu's zoom items replay. + (Some("Mn"), Target::Ordinal(item)) => match lookup(MENU_ITEMS, &item) { + Some(id) => none(id), + None => Mapped::Unsupported { harmless: false }, + }, + // Switching to another open document: its offset from the active one, -1 for the previous + // tab and 1 for the next (a template action copies from one and pastes into the other, #7103). + (Some("Dcmn"), Target::Offset(o)) => step("document.activate", json!({"offset": o})), + _ => Mapped::Unsupported { harmless: false }, + } +} + +pub(super) fn select_to(id: &str, p: &Value) -> Option { + let ord = |o: &str| D::Reference(vec![ReferenceItem::Enumerated { class: class("Lyr "), type_id: code("Ordn"), value: code(o) }]); + let enumerated = |cls: &str, ty: &str, v: &str| D::Reference(vec![ReferenceItem::Enumerated { class: class(cls), type_id: code(ty), value: code(v) }]); + Some(match id { + "layer.select" => { + if p.get("occurrence").is_some() { + return None; + } + let name = jstr(p, "name").or_else(|| jstr(p, "layer"))?; + let mut d = desc("null").with("null", name_ref("Lyr ", name)); + match jstr(p, "mode") { + None | Some("replace") => {} + Some("add") => d = d.with("selectionModifier", enm("selectionModifierType", "addToSelection")), + Some("remove") => d = d.with("selectionModifier", enm("selectionModifierType", "removeFromSelection")), + Some("range") => d = d.with("selectionModifier", enm("selectionModifierType", "addToSelectionContinuous")), + Some(_) => return None, + } + d.with("MkVs", D::Boolean(false)) + } + "channel.target" => { + let v = match jstr(p, "channel") { + Some("mask") => "Msk ", + None | Some("composite") => "RGB ", + Some(_) => return None, + }; + desc("null").with("null", enumerated("Chnl", "Chnl", v)).with("MkVs", D::Boolean(false)) + } + "edit.undo" => desc("null").with("null", enumerated("HstS", "Ordn", "Prvs")), + "edit.redo" => desc("null").with("null", enumerated("HstS", "Ordn", "Nxt ")), + "layer.selectAbove" => desc("null").with("null", ord("Frwr")), + "layer.selectBelow" => desc("null").with("null", ord("Bckw")), + "layer.addAboveToSelection" => desc("null").with("null", ord("Frwr")).with("selectionModifier", enm("selectionModifierType", "addToSelection")), + "layer.addBelowToSelection" => desc("null").with("null", ord("Bckw")).with("selectionModifier", enm("selectionModifierType", "addToSelection")), + "layer.selectTop" => desc("null").with("null", ord("Frnt")), + "layer.selectBottom" => desc("null").with("null", ord("Back")), + // An absolute tab index has no Photoshop equivalent; an offset is what Photoshop records. + "document.activate" if p.get("document").is_none_or(Value::is_null) => { + let offset = i32::try_from(p.get("offset")?.as_i64()?).ok()?; + desc("null").with("null", D::Reference(vec![ReferenceItem::Offset { class: class("Dcmn"), offset }])) + } + _ => { + let item = lookup_back(MENU_ITEMS, id)?; + desc("null").with("null", D::Reference(vec![ReferenceItem::Enumerated { class: class("Mn "), type_id: code("MnIt"), value: code(item) }])) + } + }) +} + +pub(super) fn delete_from(d: &Descriptor) -> Mapped { + match get_ref(d, "null") { + None => none("edit.clear"), + Some(r) if ref_class(r).as_deref() == Some("Lyr") => match layer_target(r) { + Some(p) => step("layer.delete", Value::Object(p)), + None => Mapped::Unsupported { harmless: false }, + }, + // The targeted channel of a layer is its mask (what Photoshop records after making an + // adjustment layer over a selection and discarding the mask). + Some(r) if ref_class(r).as_deref() == Some("Chnl") && matches!(target(r), Target::Ordinal(o) if o == "Trgt") => none("layer.layerMask.delete"), + Some(_) => Mapped::Unsupported { harmless: false }, + } +} + +pub(super) fn quick_mask_ref() -> D { + D::Reference(vec![ + ReferenceItem::Property { class: class("Prpr"), key: code("QucM") }, + ReferenceItem::Enumerated { class: class("Dcmn"), type_id: code("Ordn"), value: code("Trgt") }, + ]) +} + +pub(super) fn clear_from(d: &Descriptor) -> Mapped { + match get_ref(d, "null").map(target) { + Some(Target::Property(p)) if p == "QucM" => step("select.editInQuickMaskMode", json!({"on": false})), + None => none("edit.clear"), + _ => Mapped::Unsupported { harmless: false }, + } +} + +pub(super) fn clear_to(id: &str, p: &Value) -> Option { + match id { + "select.editInQuickMaskMode" if jbool(p, "on") == Some(false) => Some(desc("null").with("null", quick_mask_ref())), + _ => None, + } +} + +pub(super) fn delete_to(id: &str, p: &Value) -> Option { + Some(match id { + "edit.clear" => desc("null"), + "layer.delete" => desc("null").with("null", layer_ref(p)?), + "layer.layerMask.delete" => desc("null").with("null", target_ref("Chnl")), + _ => return None, + }) +} + +/// `hide` / `show` take a list of references (or one). +pub(super) fn visibility_from(d: &Descriptor, id: &str) -> Mapped { + let refs: Vec<&[ReferenceItem]> = match d.get("null") { + Some(D::List(l)) => l.iter().filter_map(|v| if let D::Reference(r) = v { Some(r.as_slice()) } else { None }).collect(), + Some(D::Reference(r)) => vec![r.as_slice()], + _ => return Mapped::Unsupported { harmless: false }, + }; + let mut v = Vec::new(); + for r in refs { + match layer_target(r) { + Some(p) => v.push((id, Value::Object(p))), + None => return Mapped::Unsupported { harmless: false }, + } + } + if v.is_empty() { Mapped::Unsupported { harmless: false } } else { steps(v) } +} + +pub(super) fn visibility_to(_: &str, p: &Value) -> Option { + Some(desc("null").with("null", D::List(vec![layer_ref(p)?]))) +} + +pub(super) fn move_from(d: &Descriptor) -> Mapped { + let Some(r) = get_ref(d, "null") else { return Mapped::Unsupported { harmless: false } }; + // The selection outline nudged. + if ref_class(r).as_deref() == Some("Chnl") && matches!(target(r), Target::Property(p) if p == "fsel") { + return match get_obj(d, "T ") { + Some(t) if matches!(t.get("Hrzn"), Some(D::UnitFloat { unit: PX, .. })) => match (get_num(t, "Hrzn"), get_num(t, "Vrtc")) { + (Some(dx), Some(dy)) => step("select.transformSelection", json!({"dx": dx.round(), "dy": dy.round()})), + _ => Mapped::Unsupported { harmless: false }, + }, + _ => Mapped::Unsupported { harmless: false }, + }; + } + if ref_class(r).as_deref() != Some("Lyr") { + return Mapped::Unsupported { harmless: false }; + } + let Some(mut p) = layer_target(r) else { return Mapped::Unsupported { harmless: false } }; + match d.get("T ") { + Some(D::Descriptor(t)) => { + let unit = |k: &str| match t.get(k) { + Some(D::UnitFloat { unit, .. }) => Some(*unit), + _ => None, + }; + let (Some(dx), Some(dy)) = (get_num(t, "Hrzn"), get_num(t, "Vrtc")) else { return Mapped::Unsupported { harmless: false } }; + match (unit("Hrzn"), unit("Vrtc")) { + (Some(PX), Some(PX)) => { + p.insert("dx".into(), dx.round().into()); + p.insert("dy".into(), dy.round().into()); + } + // A nudge recorded with the rulers in other units: points, converted to pixels + // at the resolution of the document the action plays on. + (Some(PT), Some(PT)) => { + p.insert("dx".into(), dx.into()); + p.insert("dy".into(), dy.into()); + p.insert("units".into(), "pt".into()); + } + _ => return Mapped::Unsupported { harmless: false }, + } + step("layer.translate", Value::Object(p)) + } + Some(D::Reference(t)) => { + let id = match target(t) { + Target::Ordinal(o) if o == "Frnt" => "layer.arrange.bringToFront", + Target::Ordinal(o) if o == "Back" => "layer.arrange.sendToBack", + Target::Ordinal(o) if o == "Nxt" => "layer.arrange.bringForward", + Target::Ordinal(o) if o == "Prvs" => "layer.arrange.sendBackward", + Target::Offset(1) => "layer.arrange.bringForward", + Target::Offset(-1) => "layer.arrange.sendBackward", + // Index 0 is the bottom of the stack. + Target::Index(0) => "layer.arrange.sendToBack", + _ => return Mapped::Unsupported { harmless: false }, + }; + step(id, Value::Object(p)) + } + _ => Mapped::Unsupported { harmless: false }, + } +} + +pub(super) fn move_to(id: &str, p: &Value) -> Option { + let ord = |o: &str| D::Reference(vec![ReferenceItem::Enumerated { class: class("Lyr "), type_id: code("Ordn"), value: code(o) }]); + let t = match id { + "layer.translate" => { + let unit = match jstr(p, "units") { + None | Some("px") => PX, + Some("pt") => PT, + Some(_) => return None, + }; + let v = |k: &str| D::UnitFloat { unit, value: jnum(p, k).unwrap_or(0.0) }; + D::Descriptor(desc("Ofst").with("Hrzn", v("dx")).with("Vrtc", v("dy"))) + } + "layer.arrange.bringToFront" => ord("Frnt"), + "layer.arrange.sendToBack" => ord("Back"), + "layer.arrange.bringForward" => ord("Nxt "), + "layer.arrange.sendBackward" => ord("Prvs"), + _ => return None, + }; + Some(desc("null").with("null", layer_ref(p)?).with("T ", t)) +} + +pub(super) fn duplicate_from(d: &Descriptor) -> Mapped { + let Some(r) = get_ref(d, "null") else { return Mapped::Unsupported { harmless: false } }; + match ref_class(r).as_deref() { + Some("Lyr") => { + // A `T` document reference (duplicate into another open document) has no + // replayable meaning here: keep the step verbatim rather than misplay it. + if get_ref(d, "T ").is_some() { + return Mapped::Unsupported { harmless: false }; + } + let Some(mut p) = layer_target(r) else { return Mapped::Unsupported { harmless: false } }; + if let Some(n) = get_text(d, "Nm ") { + p.insert("name".into(), n.into()); + } + step("layer.duplicate", Value::Object(p)) + } + Some("Dcmn") => { + let mut p = Map::new(); + if let Some(n) = get_text(d, "Nm ") { + p.insert("name".into(), n.into()); + } + if let Some(m) = get_bool(d, "Mrgd") { + p.insert("mergedOnly".into(), m.into()); + } + step("image.duplicate", Value::Object(p)) + } + _ => Mapped::Unsupported { harmless: false }, + } +} + +pub(super) fn duplicate_to(id: &str, p: &Value) -> Option { + // Duplicate into a new document is a `Mk` (handled above); let it fall through. + if id == "layer.duplicate" && jstr(p, "document") == Some("new") { + return None; + } + // Photoshop's Duplicate has no in-place flag: a plain one would place the artboard copy beside + // the original on playback. + if id == "layer.duplicate" && jbool(p, "inPlace") == Some(true) { + return None; + } + let mut d = match id { + "layer.duplicate" => desc("null").with("null", layer_ref(p)?), + "image.duplicate" => { + desc("null").with("null", D::Reference(vec![ReferenceItem::Enumerated { class: class("Dcmn"), type_id: Id::new("Ordn"), value: Id::new("Frst") }])) + } + _ => return None, + }; + if let Some(n) = jstr(p, "name") { + d = d.with("Nm ", text(n)); + } + if let Some(m) = jbool(p, "mergedOnly") { + d = d.with("Mrgd", D::Boolean(m)); + } + Some(d) +} + +/// Only a comp name in the active document is portable across action playback. +pub(super) fn apply_comp_from(d: &Descriptor) -> Mapped { + match get_ref(d, "null") { + Some([ReferenceItem::Name { class, name }]) if trimmed(&class.class_id) == "compsClass" => { + step("layerComp.apply", json!({"comp": name.to_string_lossy()})) + } + _ => Mapped::Unsupported { harmless: false }, + } +} + +pub(super) fn apply_comp_to(_: &str, p: &Value) -> Option { + Some(desc("null").with("null", name_ref("compsClass", jstr(p, "comp")?))) +} + +pub(super) fn play_from(d: &Descriptor) -> Mapped { + match get_ref(d, "null").map(target) { + Some(Target::Name(n)) => step("actions.play", json!({"action": clip_name(&n)})), + _ => Mapped::Unsupported { harmless: false }, + } +} + +pub(super) fn play_to(_: &str, p: &Value) -> Option { + let name = jstr(p, "action")?; + // The Play Action descriptor written here carries no starting step, so a call from a later step is not a whole call. + if p.get("from").is_some_and(|v| !v.is_null() && v.as_f64() != Some(0.0)) { + return None; + } + let mut items = vec![ReferenceItem::Name { class: class("Actn"), name: UnicodeString::new_nul(name) }]; + if let Some(set) = jstr(p, "set") { + items.push(ReferenceItem::Name { class: class("ASet"), name: UnicodeString::new_nul(set) }); + } + Some(desc("null").with("null", D::Reference(items))) +} + +pub(super) fn fill_from(d: &Descriptor) -> Mapped { + if let Some(from) = get_obj(d, "From") { + // The Paint Bucket tool's click: its point is in pixels, or in percent of the canvas + // (not replayable without the document size). + let in_px = |k: &str| matches!(from.get(k), Some(D::UnitFloat { unit: PX, .. })); + let (Some(x), Some(y)) = (get_num(from, "Hrzn"), get_num(from, "Vrtc")) else { return Mapped::Unsupported { harmless: false } }; + if !in_px("Hrzn") || !in_px("Vrtc") { + return Mapped::Unsupported { harmless: false }; + } + let mut p = json!({"x": x.round(), "y": y.round()}); + match get_enum(d, "Usng").as_deref() { + Some("FrgC") | None => {} + Some("Pttn") => p["contents"] = json!("pattern"), + Some("Clr") => match get_obj(d, "Clr ").and_then(color_hex) { + Some(c) => p["color"] = json!(c), + None => return Mapped::Unsupported { harmless: false }, + }, + Some(_) => return Mapped::Unsupported { harmless: false }, + } + if let Some(t) = get_num(d, "Tlrn") { + p["tolerance"] = json!(t); + } + if let Some(c) = get_bool(d, "Cntg") { + p["contiguous"] = json!(c); + } + if let Some(a) = get_bool(d, "AntA") { + p["antiAlias"] = json!(a); + } + if let Some(m) = get_bool(d, "Mrgd") { + p["sampleAllLayers"] = json!(m); + } + if let Some(o) = get_num(d, "Opct") { + p["opacity"] = json!(o); + } + return step("paint.bucket", p); + } + let Some(contents) = get_enum(d, "Usng").and_then(|u| lookup(FILL_CONTENTS, &u)) else { return Mapped::Unsupported { harmless: false } }; + let mut p = json!({"contents": contents}); + if contents == "color" { + match get_obj(d, "Clr ").and_then(color_hex) { + Some(c) => p["color"] = json!(c), + None => return Mapped::Unsupported { harmless: false }, + } + } + if let Some(o) = get_num(d, "Opct") { + p["opacity"] = json!(o); + } + if let Some(m) = get_enum(d, "Md ") { + match blend_label(&m) { + Some(l) => p["mode"] = json!(l), + None => return Mapped::Unsupported { harmless: false }, + } + } + if let Some(t) = get_bool(d, "PrsT") { + p["preserveTransparency"] = json!(t); + } + step("edit.fill", p) +} + +pub(super) fn fill_to(id: &str, p: &Value) -> Option { + if id == "paint.bucket" { + let mut d = desc("null").with("From", D::Descriptor(desc("Pnt ").with("Hrzn", px(jnum(p, "x")?)).with("Vrtc", px(jnum(p, "y")?)))); + d = d.with("Tlrn", long(jnum(p, "tolerance").unwrap_or(32.0))).with("AntA", D::Boolean(jbool(p, "antiAlias").unwrap_or(true))); + // `source` is the command's older name for `contents`. + d = if p.get("contents").or_else(|| p.get("source")).and_then(Value::as_str) == Some("pattern") { + // `Pttn` names no pattern and holds no placement: a chosen pattern, a scale, an angle + // or a phase would replay with the current pattern at its defaults (#7543, #7544, + // #7545, #7546). + let num = |k: &str, default: f64| p.get(k).is_some_and(|v| !v.is_null() && v.as_f64() != Some(default)); + let phase = p.get("phase").is_some_and(|v| !v.is_null() && v.as_array().is_none_or(|a| a.iter().any(|c| c.as_f64() != Some(0.0)))); + if p.get("pattern").is_some_and(|v| !v.is_null()) || num("scale", 100.0) || num("angle", 0.0) || phase { + return None; + } + d.with("Usng", enm("FlCn", "Pttn")) + } else { + // An explicit colour overrides the foreground (#7199): it travels as Fill's `Clr `. + match bucket_color(p.get("color"))? { + Some(c) => d.with("Usng", enm("FlCn", "Clr ")).with("Clr ", D::Descriptor(c)), + None => d.with("Usng", enm("FlCn", "FrgC")), + } + }; + if let Some(o) = jnum(p, "opacity") { + d = d.with("Opct", pct(o)); + } + if let Some(c) = jbool(p, "contiguous") { + d = d.with("Cntg", D::Boolean(c)); + } + if let Some(m) = jbool(p, "sampleAllLayers") { + d = d.with("Mrgd", D::Boolean(m)); + } + return Some(d); + } + let contents = jstr(p, "contents").unwrap_or("color"); + let mut d = desc("null").with("Usng", enm("FlCn", lookup_back(FILL_CONTENTS, contents)?)); + if contents == "color" { + d = d.with("Clr ", D::Descriptor(color_desc(jstr(p, "color")?)?)); + } + if let Some(o) = jnum(p, "opacity") { + d = d.with("Opct", pct(o)); + } + if let Some(m) = jstr(p, "mode") { + d = d.with("Md ", enm("BlnM", blend_ps(m)?)); + } + if let Some(t) = jbool(p, "preserveTransparency") { + d = d.with("PrsT", D::Boolean(t)); + } + Some(d) +} + +/// The Paint Bucket's `color` as `paint.bucket` reads it (`[r, g, b(, a)]` in 0..=1 or +/// `#rrggbb(aa)`): `Some(None)` when it fills with the foreground (no colour, or a string the +/// command doesn't read), `None` when the colour can't be written (not opaque, or outside 0..=1). +fn bucket_color(v: Option<&Value>) -> Option> { + let rgba = match v { + Some(Value::Array(a)) if a.len() >= 3 => { + let c: Vec = a.iter().map(|x| x.as_f64().unwrap_or(0.0)).collect(); + [*c.first()?, *c.get(1)?, *c.get(2)?, c.get(3).copied().unwrap_or(1.0)] + } + Some(Value::String(h)) => { + let h = h.trim_start_matches('#'); + let c = |i: usize| h.get(i..i + 2).and_then(|x| u8::from_str_radix(x, 16).ok()).map(|v| f64::from(v) / 255.0); + let (Some(r), Some(g), Some(b)) = (c(0), c(2), c(4)) else { return Some(None) }; + [r, g, b, c(6).unwrap_or(1.0)] + } + _ => return Some(None), + }; + if rgba[3] != 1.0 || !rgba.iter().all(|v| (0.0..=1.0).contains(v)) { + return None; + } + Some(Some(desc("RGBC").with("Rd ", D::Double(rgba[0] * 255.0)).with("Grn ", D::Double(rgba[1] * 255.0)).with("Bl ", D::Double(rgba[2] * 255.0)))) +} + +/// Preserve the command's effective integer width instead of rounding its input again. +pub(super) fn stroke_to(_: &str, p: &Value) -> Option { + if !pixel_target(p) { + return None; + } + let mut params = if p.is_null() { Map::new() } else { p.as_object()?.clone() }; + params.insert("width".into(), Value::from(crate::extra_cmds::stroke_width(p))); + fields_to(&Value::Object(params), STROKE, desc("null")) +} + +pub(super) const STROKE: &[F] = &[ + F("Wdth", "width", Kind::Long), + F("Lctn", "location", Kind::Enum("StrL", STROKE_LOCATION)), + F("Opct", "opacity", Kind::Pct), + F("Md ", "mode", Kind::Blend), + F("Clr ", "color", Kind::Color), + F("PrsT", "preserveTransparency", Kind::Bool), +]; + +/// Whether an event's `null` reference targets a layer (Edit › Transform) rather than the +/// document (Image › Image Rotation). +fn targets_layer(d: &Descriptor) -> bool { + get_ref(d, "null").and_then(ref_class).as_deref() == Some("Lyr") +} + +pub(super) fn rotate_from(d: &Descriptor) -> Mapped { + let Some(angle) = get_num(d, "Angl") else { return Mapped::Unsupported { harmless: false } }; + let a = angle.rem_euclid(360.0); + let (layer, doc) = if (a - 90.0).abs() < 1e-6 { + ("edit.transform.rotate90Cw", "image.imageRotation.90cw") + } else if (a - 270.0).abs() < 1e-6 { + ("edit.transform.rotate90Ccw", "image.imageRotation.90ccw") + } else if (a - 180.0).abs() < 1e-6 { + ("edit.transform.rotate180", "image.imageRotation.180") + } else if targets_layer(d) { + return Mapped::Unsupported { harmless: false }; + } else { + let mut p = json!({"angle": angle.abs(), "direction": if angle < 0.0 { "ccw" } else { "cw" }}); + if let Some(i) = get_enum(d, "Intr").and_then(|i| lookup(INTERPOLATION, &i)).filter(|i| matches!(*i, "bicubic" | "bilinear" | "nearest")) { + p["interpolation"] = i.into(); + } + return step("image.rotation.arbitrary", p); + }; + none(if targets_layer(d) { layer } else { doc }) +} + +pub(super) fn rotate_to(id: &str, p: &Value) -> Option { + let (angle, layer) = match id { + "edit.transform.rotate90Cw" => (90.0, true), + "edit.transform.rotate90Ccw" => (-90.0, true), + "edit.transform.rotate180" => (180.0, true), + "image.imageRotation.90cw" => (90.0, false), + "image.imageRotation.90ccw" => (-90.0, false), + "image.imageRotation.180" => (180.0, false), + "image.rotation.arbitrary" => (jnum(p, "angle")? * if jstr(p, "direction") == Some("ccw") { -1.0 } else { 1.0 }, false), + _ => return None, + }; + let mut d = desc("null"); + if layer { + d = d.with("null", target_ref("Lyr ")); + } + d = d.with("Angl", ang(angle)); + if id == "image.rotation.arbitrary" + && let Some(i) = p.get("interpolation") + { + // The command resamples with nearest, bilinear or bicubic; any other value can't be + // carried faithfully, so refuse rather than replay with a different interpolation. + let i = match i.as_str()? { + "nearestNeighbor" => "nearest", + i @ ("bicubic" | "bilinear" | "nearest") => i, + _ => return None, + }; + d = d.with("Intr", enm("Intp", lookup_back(INTERPOLATION, i)?)); + } + Some(d) +} + +pub(super) fn flip_from(d: &Descriptor) -> Mapped { + let Some(axis) = get_enum(d, "Axis") else { return Mapped::Unsupported { harmless: false } }; + let horizontal = axis == "Hrzn"; + none(match (targets_layer(d), horizontal) { + (true, true) => "edit.transform.flipHorizontal", + (true, false) => "edit.transform.flipVertical", + (false, true) => "image.imageRotation.flipCanvasHorizontal", + (false, false) => "image.imageRotation.flipCanvasVertical", + }) +} + +pub(super) fn flip_to(id: &str, _: &Value) -> Option { + let (layer, axis) = match id { + "edit.transform.flipHorizontal" => (true, "Hrzn"), + "edit.transform.flipVertical" => (true, "Vrtc"), + "image.imageRotation.flipCanvasHorizontal" => (false, "Hrzn"), + "image.imageRotation.flipCanvasVertical" => (false, "Vrtc"), + _ => return None, + }; + let mut d = desc("null"); + if layer { + d = d.with("null", target_ref("Lyr ")); + } + Some(d.with("Axis", enm("Ornt", axis))) +} diff --git a/crates/engine/src/cmd/atn_cmds/steps_make.rs b/crates/engine/src/cmd/atn_cmds/steps_make.rs new file mode 100644 index 0000000000..696a1f17f8 --- /dev/null +++ b/crates/engine/src/cmd/atn_cmds/steps_make.rs @@ -0,0 +1,607 @@ +use super::adjustments::{HUE_RANGES, adjustment_by_class, adjustment_by_suffix, adjustment_steps}; +use super::descriptors::{ + PX, Target, ang, class, class_ref, code, color_desc, color_hex, desc, enm, get_bool, get_enum, get_list, get_num, get_obj, get_ref, get_text, jbool, jnum, + jstr, layer_ref, layer_target, long, name_ref, pct, px, ref_class, target, target_ref, text, trimmed, +}; +use super::fields::{Mapped, none, step, steps}; +use super::steps_layer::quick_mask_ref; +use super::tables::{LABEL_COLORS, MODES, blend_label, blend_ps, lookup, lookup_back}; +use super::*; + +/// A `patternLayer` descriptor's pattern, scale, angle and link as the params of +/// `layer.newFillLayer.pattern` / `layer.fill.pattern.set`. The pattern goes by name: ids differ +/// between Photoshop's library and one rebuilt from the same `.pat` file. None for a pattern +/// recorded without a name or id. +fn pattern_params(t: &Descriptor) -> Option> { + let mut p = Map::new(); + if let Some(ptrn) = get_obj(t, "Ptrn") { + let key = get_text(ptrn, "Nm ").filter(|n| !n.is_empty()).or_else(|| get_text(ptrn, "Idnt").filter(|i| !i.is_empty()))?; + p.insert("pattern".into(), key.into()); + } + if let Some(s) = get_num(t, "Scl ") { + p.insert("scale".into(), s.into()); + } + if let Some(a) = get_num(t, "Angl") { + p.insert("angle".into(), a.into()); + } + if let Some(l) = get_bool(t, "Algn") { + p.insert("link".into(), l.into()); + } + Some(p) +} + +/// The `patternLayer` descriptor for [`pattern_params`]' params. +fn pattern_desc(p: &Value) -> Option { + let mut t = desc("patternLayer"); + if let Some(n) = jstr(p, "pattern") { + t = t.with("Ptrn", D::Descriptor(desc("Ptrn").with("Nm ", text(n)))); + } + if let Some(s) = jnum(p, "scale") { + t = t.with("Scl ", pct(s)); + } + if let Some(a) = jnum(p, "angle") { + t = t.with("Angl", ang(a)); + } + if let Some(l) = jbool(p, "link") { + t = t.with("Algn", D::Boolean(l)); + } + if p.get("phase").is_some() { + return None; + } + Some(t) +} + +/// Layer › Layer Mask: the `UsrM` value of an Add Layer Mask `Mk` ↔ its command. +const MASK_USING: &[(&str, &str)] = &[ + ("RvlA", "layer.layerMask.revealAll"), + ("HdAl", "layer.layerMask.hideAll"), + ("RvlS", "layer.layerMask.revealSelection"), + ("HdSl", "layer.layerMask.hideSelection"), +]; + +pub(super) fn make_from(d: &Descriptor) -> Mapped { + // Duplicate layer/group into a new document: `Mk` with a document class, a layer + // `Usng`, an optional `Nm` (the new document's name) and an optional `LyrN` + // (the copy's name). A `Dplc` with a `T` document reference (duplicate into another + // open document) stays a kept Photoshop step: document indices mean nothing at replay. + if let Some(r) = get_ref(d, "null") + && ref_class(r).as_deref() == Some("Dcmn") + && matches!(target(r), Target::Class) + && let Some(u) = get_ref(d, "Usng") + && matches!(ref_class(u).as_deref(), Some("Lyr") | Some("layerSection")) + && let Some(mut p) = layer_target(u) + { + p.insert("document".into(), "new".into()); + if let Some(n) = get_text(d, "Nm ") { + p.insert("documentName".into(), n.into()); + } + if let Some(n) = get_text(d, "LyrN") { + p.insert("name".into(), n.into()); + } + return step("layer.duplicate", Value::Object(p)); + } + // Add Layer Mask: a `Chnl` class made at the mask channel, `Usng` what it reveals. + if let Some(D::Class(c)) = d.get("Nw ") + && trimmed(&c.class_id) == "Chnl" + { + // The target layer's mask only: a further item (a `Lyr` by name…) puts it on another layer. + let at_mask = get_ref(d, "At ") + .is_some_and(|r| r.len() == 1 && ref_class(r).as_deref() == Some("Chnl") && matches!(target(r), Target::Ordinal(o) if o == "Msk")); + return match get_enum(d, "Usng").and_then(|u| lookup(MASK_USING, &u)) { + Some(id) if at_mask => none(id), + _ => Mapped::Unsupported { harmless: false }, + }; + } + if let Some(nw) = get_obj(d, "Nw ") { + // Layer via Copy / Cut (`Usng` = the selection), or a new document. + if get_enum(d, "Usng").as_deref() == Some("Slct") { + let id = if get_bool(d, "Cpy ") == Some(true) { "layer.new.layerViaCopy" } else { "layer.new.layerViaCut" }; + let mut v = vec![(id, json!({}))]; + if let Some(n) = get_text(nw, "Nm ") { + v.push(("layer.setProps", json!({"name": n}))); + } + return steps(v); + } + if get_text(nw, "preset").is_some() { + return none("file.newFromClipboard"); + } + if let (Some(w), Some(h)) = (get_num(nw, "Wdth"), get_num(nw, "Hght")) { + let res = get_num(nw, "Rslt").unwrap_or(72.0); + // Dimensions are in points (`#Rlt`) unless given in pixels. + let to_px = |k: &str, v: f64| match nw.get(k) { + Some(D::UnitFloat { unit: PX, .. }) => v, + _ => v * res / 72.0, + }; + let mut p = json!({"width": to_px("Wdth", w).round(), "height": to_px("Hght", h).round(), "resolution": res}); + if let Some(n) = get_text(nw, "Nm ") { + p["name"] = json!(n); + } + if let Some(D::Class(c)) = nw.get("Md ") + && let Some(m) = lookup(MODES, &trimmed(&c.class_id)) + { + p["mode"] = json!(m); + } + if let Some(depth) = get_num(nw, "Dpth") { + p["depth"] = json!(depth); + } + if let Some(f) = get_enum(nw, "Fl ") { + p["background"] = json!(match f.as_str() { + "Wht" => "white", + "BckC" => "backgroundColor", + "Trns" => "transparent", + _ => "white", + }); + } + return step("file.new", p); + } + return Mapped::Unsupported { harmless: false }; + } + let Some(r) = get_ref(d, "null") else { return Mapped::Unsupported { harmless: false } }; + let using = get_obj(d, "Usng"); + let type_desc = using.and_then(|u| get_obj(u, "Type")); + match ref_class(r).as_deref() { + Some("Lyr") => { + let mut p = Map::new(); + if let Some(u) = using { + if let Some(n) = get_text(u, "Nm ") { + p.insert("name".into(), n.into()); + } + if let Some(o) = get_num(u, "Opct") { + p.insert("opacity".into(), (o / 100.0).into()); + } + if let Some(m) = get_enum(u, "Md ").and_then(|m| blend_label(&m)) { + p.insert("mode".into(), m.into()); + } + } + step("layer.new.layer", Value::Object(p)) + } + Some("AdjL") => match type_desc.and_then(|t| adjustment_by_class(&trimmed(&t.class_id))) { + Some(a) => adjustment_steps(a, "layer.newAdjustmentLayer.", type_desc), + None => Mapped::Unsupported { harmless: false }, + }, + Some("contentLayer") => match type_desc { + Some(t) if t.class_id.is("solidColorLayer") => match get_obj(t, "Clr ").and_then(color_hex) { + Some(c) => step("layer.newFillLayer.solidColor", json!({"color": c})), + None => none("layer.newFillLayer.solidColor"), + }, + Some(t) if t.class_id.is("patternLayer") => match pattern_params(t) { + Some(p) => step("layer.newFillLayer.pattern", Value::Object(p)), + None => Mapped::Unsupported { harmless: false }, + }, + _ => Mapped::Unsupported { harmless: false }, + }, + Some("layerSection") => { + let mut p = Map::new(); + if let Some(n) = using.and_then(|u| get_text(u, "Nm ")) { + p.insert("name".into(), n.into()); + } + match get_ref(d, "From") { + // A named source layer stays the source (#7236); a target reference and an + // index/id source (our exporter never writes those) keep the old implicit + // import: the group lands on the current selection at playback. + Some(r) => { + if let Some(t) = layer_target(r) { + p.extend(t); + } + step("layer.groupLayers", Value::Object(p)) + } + None => step("layer.new.group", Value::Object(p)), + } + } + _ => Mapped::Unsupported { harmless: false }, + } +} + +pub(super) fn make_to(id: &str, p: &Value) -> Option { + let with_name = |cls: &str| { + let mut u = desc(cls); + if let Some(n) = jstr(p, "name") { + u = u.with("Nm ", text(n)); + } + u + }; + Some(match id { + "layer.new.layer" => { + // The descriptor carries the name, opacity and mode only. A step that also clips to + // the layer below, labels the layer, fills it with the neutral colour or places it + // below the active layer would replay as a different layer, so it isn't exported + // (strict export fails, a partial one skips it: #7502, #7512, #7513, #7514). + let set = |key: &str, default: Value| p.get(key).is_some_and(|v| !v.is_null() && *v != default); + if set("clipToPrevious", Value::Bool(false)) + || set("color", json!("none")) + || set("fillNeutral", Value::Bool(false)) + || set("position", json!("above")) + { + return None; + } + let mut u = with_name("Lyr "); + if let Some(o) = jnum(p, "opacity") { + u = u.with("Opct", pct(o * 100.0)); + } + if let Some(m) = jstr(p, "mode").and_then(blend_ps) { + u = u.with("Md ", enm("BlnM", m)); + } + desc("null").with("null", class_ref("Lyr ")).with("Usng", D::Descriptor(u)) + } + "layer.new.group" => desc("null").with("null", class_ref("layerSection")).with("Usng", D::Descriptor(with_name("layerSection"))), + "layer.groupLayers" => { + // An explicit source layer goes in by name like every other layer reference; a + // step without one keeps the target-layer form (#7236). + desc("null").with("null", class_ref("layerSection")).with("From", layer_ref(p)?).with("Usng", D::Descriptor(with_name("layerSection"))) + } + "layer.new.layerViaCopy" | "layer.new.layerViaCut" => { + let mut d = desc("null").with("Nw ", D::Descriptor(desc("Lyr "))).with("Usng", enm("ArSl", "Slct")); + if id == "layer.new.layerViaCopy" { + d = d.with("Cpy ", D::Boolean(true)); + } + d + } + "layer.newFillLayer.solidColor" => { + let mut t = desc("solidColorLayer"); + // The descriptor's colour is opaque RGB: a colour with alpha, or one it can't parse, + // would replay as the default black (#7507). + if let Some(c) = p.get("color").filter(|v| !v.is_null()) { + t = t.with("Clr ", D::Descriptor(c.as_str().and_then(color_desc)?)); + } + desc("null").with("null", class_ref("contentLayer")).with("Usng", D::Descriptor(desc("contentLayer").with("Type", D::Descriptor(t)))) + } + "layer.newFillLayer.pattern" => { + if p.get("path").is_some() { + return None; + } + let t = pattern_desc(p)?; + desc("null").with("null", class_ref("contentLayer")).with("Usng", D::Descriptor(desc("contentLayer").with("Type", D::Descriptor(t)))) + } + "layer.duplicate" => { + // Duplicate into a new document is a `Mk`, not a `Dplc` (see `make_from`). + // Anything else falls through to the `Dplc` event below. + if jstr(p, "document") != Some("new") { + return None; + } + let mut d = desc("null").with("null", class_ref("Dcmn")).with("Usng", layer_ref(p)?); + if let Some(n) = jstr(p, "documentName") { + d = d.with("Nm ", text(n)); + } + if let Some(n) = jstr(p, "name") { + d = d.with("LyrN", text(n)); + } + d + } + "layer.layerMask.revealAll" | "layer.layerMask.hideAll" | "layer.layerMask.revealSelection" | "layer.layerMask.hideSelection" => { + // Photoshop adds the mask to the target layer only. + if p.get("layer").is_some() { + return None; + } + let at = D::Reference(vec![ReferenceItem::Enumerated { class: class("Chnl"), type_id: code("Chnl"), value: code("Msk ") }]); + desc("null").with("Nw ", D::Class(class("Chnl"))).with("At ", at).with("Usng", enm("UsrM", lookup_back(MASK_USING, id)?)) + } + "file.newFromClipboard" => desc("null").with("Nw ", D::Descriptor(desc("Dcmn").with("preset", text("Clipboard")))), + "file.new" => { + let mut n = desc("Dcmn"); + if let Some(name) = jstr(p, "name") { + n = n.with("Nm ", text(name)); + } + if let Some(m) = jstr(p, "mode").and_then(|m| lookup_back(MODES, if m == "gray" { "grayscale" } else { m })) { + n = n.with("Md ", D::Class(class(m))); + } + n = n.with("Wdth", px(jnum(p, "width").unwrap_or(1920.0))).with("Hght", px(jnum(p, "height").unwrap_or(1080.0))); + n = n.with("Rslt", D::UnitFloat { unit: *b"#Rsl", value: jnum(p, "resolution").unwrap_or(72.0) }); + // `Fl ` is white, transparent or Photoshop's own background colour: black, a hex + // colour or a given `backgroundColor` would replay as something else (#7503). + if p.get("backgroundColor").is_some_and(|v| !v.is_null()) { + return None; + } + let fill = match p.get("background").filter(|v| !v.is_null()) { + None => "Wht ", + Some(b) => match b.as_str()? { + "white" => "Wht ", + "transparent" => "Trns", + "backgroundColor" => "BckC", + _ => return None, + }, + }; + n = n.with("Fl ", enm("Fl ", fill)).with("Dpth", long(jnum(p, "depth").unwrap_or(8.0))); + desc("null").with("Nw ", D::Descriptor(n)) + } + _ => { + let suffix = id.strip_prefix("layer.newAdjustmentLayer.")?; + let a = adjustment_by_suffix(suffix)?; + let t = if p.as_object().is_some_and(|o| o.is_empty()) { + desc(a.class).with("presetKind", enm("presetKindType", "presetKindDefault")) + } else { + (a.to)(p)? + }; + desc("null").with("null", class_ref("AdjL")).with("Usng", D::Descriptor(desc("AdjL").with("Type", D::Descriptor(t)))) + } + }) +} + +pub(super) fn set_from(d: &Descriptor) -> Mapped { + let Some(r) = get_ref(d, "null") else { return Mapped::Unsupported { harmless: false } }; + let unsupported = Mapped::Unsupported { harmless: false }; + match (ref_class(r).as_deref(), target(r)) { + (Some("Chnl"), Target::Property(p)) if p == "fsel" => match d.get("T ") { + Some(D::Enumerated { value, .. }) => match trimmed(value).as_str() { + "Al" => none("select.all"), + "None" => none("select.deselect"), + "Prvs" => none("select.reselect"), + _ => unsupported, + }, + Some(D::Reference(t)) => match (ref_class(t).as_deref(), target(t)) { + (Some("Chnl"), Target::Ordinal(o)) if o == "Trsp" => step("select.loadSelection", json!({"channel": "transparency"})), + // ⌘-click on the targeted channel (a layer mask after `select` of `Msk`). + (Some("Chnl"), Target::Ordinal(o)) if o == "Trgt" => step("select.loadSelection", json!({"channel": "targeted"})), + (Some("Chnl"), Target::Name(n)) => step("select.loadSelection", json!({"channel": n})), + _ => unsupported, + }, + Some(D::Descriptor(t)) if t.class_id.is("Plgn") => { + let pts: Option> = get_list(t, "Pts ") + .unwrap_or(&[]) + .iter() + .map(|v| match v { + D::Descriptor(pt) => Some(json!([get_num(pt, "Hrzn")?, get_num(pt, "Vrtc")?])), + _ => None, + }) + .collect(); + match pts { + Some(pts) if pts.len() >= 3 => step("select.lasso", json!({"points": pts})), + _ => unsupported, + } + } + Some(D::Descriptor(t)) if t.class_id.is("Rctn") || t.class_id.is("Elps") => { + let (Some(top), Some(left), Some(bottom), Some(right)) = (get_num(t, "Top "), get_num(t, "Left"), get_num(t, "Btom"), get_num(t, "Rght")) + else { + return unsupported; + }; + let mut p = json!({"x": left.round(), "y": top.round(), "width": (right - left).round().max(0.0), "height": (bottom - top).round().max(0.0)}); + if t.class_id.is("Elps") { + p["ellipse"] = json!(true); + } + step("select.rect", p) + } + _ => unsupported, + }, + // Quick Mask mode on (`set` of the document's quick-mask property); `clearEvent` turns it off. + (Some("Prpr"), Target::Property(p)) if p == "QucM" => step("select.editInQuickMaskMode", json!({"on": true})), + // Layer › New › Layer From Background (Photoshop records the New Layer dialog's values + // as a `set` of the Background); values other than the defaults then apply to the layer. + (Some("Lyr"), Target::Property(p)) if p == "Bckg" => { + // On an image that opened as a normal layer there is no Background to convert; + // Photoshop stops there, but the step's purpose (an editable layer) is met. + // Photoshop's `set` of another layer doesn't target it: the selected layer stays. + let mut v = vec![("layer.new.layerFromBackground", json!({"ifPresent": true, "select": false}))]; + let mut props = Map::new(); + props.insert("layer".into(), "Layer 0".into()); + if let Some(t) = get_obj(d, "T ") { + if let Some(n) = get_text(t, "Nm ") { + props.insert("name".into(), n.into()); + } + if let Some(o) = get_num(t, "Opct").filter(|o| (o - 100.0).abs() > 1e-9) { + props.insert("opacity".into(), (o / 100.0).into()); + } + match get_enum(t, "Md ").as_deref() { + None | Some("Nrml") => {} + Some(m) => match blend_label(m) { + Some(label) => { + props.insert("blend".into(), label.into()); + } + None => return unsupported, + }, + } + } + if props.len() > 1 { + v.push(("layer.setProps", Value::Object(props))); + } + steps(v) + } + // The toolbox colours. + (Some("Clr"), Target::Property(p)) if p == "FrgC" || p == "BckC" => match get_obj(d, "T ").and_then(color_hex) { + Some(hex) => step("tools.setColors", json!({(if p == "FrgC" { "foreground" } else { "background" }): hex})), + None => unsupported, + }, + (Some("Lyr"), _) => { + let Some(mut p) = layer_target(r) else { return unsupported }; + let Some(t) = get_obj(d, "T ") else { return unsupported }; + let mut v = Vec::new(); + if let Some(c) = get_enum(t, "Clr ").and_then(|c| lookup(LABEL_COLORS, &c)) { + let mut lp = p.clone(); + lp.insert("color".into(), c.into()); + v.push(("layer.setLabelColor", Value::Object(lp))); + } + if let Some(n) = get_text(t, "Nm ") { + p.insert("name".into(), n.into()); + } + if let Some(o) = get_num(t, "Opct") { + p.insert("opacity".into(), (o / 100.0).into()); + } + if let Some(f) = get_num(t, "fillOpacity") { + p.insert("fill".into(), (f / 100.0).into()); + } + if let Some(m) = get_enum(t, "Md ") { + let Some(label) = blend_label(&m) else { return unsupported }; + p.insert("blend".into(), label.into()); + } + if let Some(vis) = get_bool(t, "Vsbl") { + p.insert("visible".into(), vis.into()); + } + if p.keys().any(|k| k != "layer") { + v.push(("layer.setProps", Value::Object(p))); + } + if v.is_empty() { unsupported } else { steps(v) } + } + // A Pattern Fill layer's pattern (double-click its thumbnail). + (Some("contentLayer"), Target::Ordinal(o)) if o == "Trgt" => match get_obj(d, "T ") { + Some(t) if t.class_id.is("patternLayer") => match pattern_params(t) { + Some(p) if !p.is_empty() => step("layer.fill.pattern.set", Value::Object(p)), + _ => unsupported, + }, + _ => unsupported, + }, + (Some("AdjL"), Target::Ordinal(o)) if o == "Trgt" => { + match get_obj(d, "T ").and_then(|t| adjustment_by_class(&trimmed(&t.class_id)).map(|a| (a, t))) { + Some((a, t)) => match (a.from)(t) { + // `kind` names the adjustment so Save Actions can write the class back. + // Not on an empty set (Photoshop's "reset to default"): params with any key + // merge, none reset. + Some(mut p) => { + if let Some(o) = p.as_object_mut().filter(|o| !o.is_empty()) { + o.insert("kind".into(), json!(a.suffix)); + } + step("layer.setAdjustment", p) + } + None => unsupported, + }, + None => unsupported, + } + } + _ => unsupported, + } +} + +pub(super) fn set_to(id: &str, p: &Value) -> Option { + let fsel = D::Reference(vec![ReferenceItem::Property { class: class("Chnl"), key: Id::new("fsel") }]); + let sel = |t: D| desc("null").with("null", fsel.clone()).with("T ", t); + Some(match id { + "select.all" => sel(enm("Ordn", "Al ")), + "select.deselect" => sel(enm("Ordn", "None")), + "select.reselect" => sel(enm("Ordn", "Prvs")), + // The descriptor loads a plain new selection: inverting it or combining it with the current + // one (add, subtract, intersect) would be lost (#7506). + "select.loadSelection" + if p.get("invert").is_some_and(|v| *v != Value::Bool(false) && !v.is_null()) + || p.get("operation").is_some_and(|v| *v != json!("new") && !v.is_null()) => + { + return None; + } + "select.loadSelection" => match jstr(p, "channel")? { + "transparency" => sel(D::Reference(vec![ReferenceItem::Enumerated { class: class("Chnl"), type_id: Id::new("Chnl"), value: Id::new("Trsp") }])), + "targeted" => sel(D::Reference(vec![ReferenceItem::Enumerated { class: class("Chnl"), type_id: Id::new("Ordn"), value: Id::new("Trgt") }])), + name => sel(name_ref("Chnl", name)), + }, + "select.lasso" => { + let pts: Option> = p + .get("points")? + .as_array()? + .iter() + .map(|pt| { + let a = pt.as_array()?; + Some(D::Descriptor(desc("Pnt ").with("Hrzn", px(a.first()?.as_f64()?)).with("Vrtc", px(a.get(1)?.as_f64()?)))) + }) + .collect(); + sel(D::Descriptor(desc("Plgn").with("Pts ", D::List(pts?)))) + } + "select.editInQuickMaskMode" => { + if jbool(p, "on") != Some(true) { + return None; + } + desc("null").with("null", quick_mask_ref()) + } + "tools.setColors" => { + // One colour per Photoshop step: a step that sets both (or any other key) doesn't + // export rather than lose one. + if p.as_object().is_some_and(|o| o.keys().any(|k| k != "foreground" && k != "background")) { + return None; + } + let (key, hex) = match (jstr(p, "foreground"), jstr(p, "background")) { + (Some(f), None) => ("FrgC", f), + (None, Some(b)) => ("BckC", b), + _ => return None, + }; + desc("null") + .with("null", D::Reference(vec![ReferenceItem::Property { class: class("Clr "), key: code(key) }])) + .with("T ", D::Descriptor(color_desc(hex)?)) + } + "select.rect" => { + match jstr(p, "mode") { + None | Some("replace") => {} + Some(_) => return None, + } + let (x, y, w, h) = (jnum(p, "x")?, jnum(p, "y")?, jnum(p, "width")?, jnum(p, "height")?); + let cls = if jbool(p, "ellipse") == Some(true) { "Elps" } else { "Rctn" }; + sel(D::Descriptor(desc(cls).with("Top ", px(y)).with("Left", px(x)).with("Btom", px(y + h)).with("Rght", px(x + w)))) + } + "layer.setProps" | "layer.renameLayer" | "layer.setLabelColor" => { + // Only these keys map onto the `Lyr ` descriptor; locks, clipping, Advanced Blending + // channels or an explicit `layers` list would be dropped (#7196, #7246). + const MAPPED: [&str; 7] = ["layer", "name", "opacity", "fill", "blend", "visible", "color"]; + if p.as_object().is_some_and(|m| m.iter().any(|(k, v)| !v.is_null() && !MAPPED.contains(&k.as_str()))) { + return None; + } + let mut t = desc("Lyr "); + if let Some(n) = jstr(p, "name") { + t = t.with("Nm ", text(n)); + } + if let Some(o) = jnum(p, "opacity") { + t = t.with("Opct", pct(o * 100.0)); + } + if let Some(f) = jnum(p, "fill") { + t = t.with("fillOpacity", pct(f * 100.0)); + } + if let Some(m) = jstr(p, "blend") { + t = t.with("Md ", enm("BlnM", blend_ps(m)?)); + } + if let Some(v) = jbool(p, "visible") { + t = t.with("Vsbl", D::Boolean(v)); + } + if let Some(c) = jstr(p, "color") { + t = t.with("Clr ", enm("Clr ", lookup_back(LABEL_COLORS, c)?)); + } + if t.items.is_empty() { + return None; + } + desc("null").with("null", layer_ref(p)?).with("T ", D::Descriptor(t)) + } + "layer.new.layerFromBackground" => { + let bckg = D::Reference(vec![ReferenceItem::Property { class: class("Lyr "), key: Id::new("Bckg") }]); + desc("null").with("null", bckg).with("T ", D::Descriptor(desc("Lyr ").with("Opct", pct(100.0)).with("Md ", enm("BlnM", "Nrml")))) + } + "layer.fill.pattern.set" => { + if p.get("layer").is_some() || p.get("document").is_some() { + return None; + } + desc("null").with("null", target_ref("contentLayer")).with("T ", D::Descriptor(pattern_desc(p)?)) + } + "layer.setAdjustment" => { + // The adjustment kind isn't in the params: Photoshop needs it, so only steps that + // name one (`kind`) export. + let kind = jstr(p, "kind")?; + // `layer.setAdjustment` changes only the settings it names. Color Balance and + // Hue/Saturation descriptors carry every setting, filling absent ones with defaults, + // so a partial edit would replay as one that also resets the rest (#8531). + // Present and of the shape the writer reads: anything else it would write as 0. + let number = |p: &Value, k: &str| p.get(k).and_then(Value::as_f64).is_some_and(f64::is_finite); + let numbers = |p: &Value, keys: &[&str]| keys.iter().all(|k| number(p, k)); + let flag = |k: &str| p.get(k).is_some_and(Value::is_boolean); + let triplet = + |k: &str| p.get(k).and_then(Value::as_array).is_some_and(|a| a.len() == 3 && a.iter().all(|v| v.as_f64().is_some_and(f64::is_finite))); + let complete = match kind { + "colorBalance" => ["shadows", "midtones", "highlights"].iter().all(|k| triplet(k)) && flag("preserveLuminosity"), + // Every colour range written carries its own hue, saturation and lightness too. + "hueSaturation" => { + flag("colorize") + && numbers(p, &["hue", "saturation", "lightness"]) + && HUE_RANGES.iter().filter_map(|r| p.get(*r).filter(|v| !v.is_null())).all(|r| { + // Bounds, when given, are the four whole numbers `hue_entry` writes (as integers); + // otherwise it drops or rounds them. + let bounds = r.get("range").filter(|v| !v.is_null()).is_none_or(|v| { + v.as_array().is_some_and(|a| a.len() == 4 && a.iter().all(|b| b.as_f64().is_some_and(|b| b.is_finite() && b.fract() == 0.0))) + }); + r.is_object() && numbers(r, &["hue", "saturation", "lightness"]) && bounds + }) + } + _ => true, + }; + if !complete { + return None; + } + let a = adjustment_by_suffix(kind)?; + desc("null").with("null", target_ref("AdjL")).with("T ", D::Descriptor((a.to)(p)?)) + } + _ => return None, + }) +} + +/// Tool classes Photoshop records when an action switches tools: no document effect. +pub(super) fn is_tool_class(c: &str) -> bool { + c.ends_with("Tl") || c.ends_with("Tool") +} diff --git a/crates/engine/src/cmd/atn_cmds/tables.rs b/crates/engine/src/cmd/atn_cmds/tables.rs new file mode 100644 index 0000000000..13b4bb9e8d --- /dev/null +++ b/crates/engine/src/cmd/atn_cmds/tables.rs @@ -0,0 +1,180 @@ +use super::descriptors::{Target, class, code, get_ref, target}; +use super::*; + +/// Photoshop's `BlnM` enumeration ↔ PhotoCraft's blend mode labels. +const BLEND_MODES: &[(&str, &str)] = &[ + ("Nrml", "Normal"), + ("normal", "Normal"), + ("Dslv", "Dissolve"), + ("dissolve", "Dissolve"), + ("Drkn", "Darken"), + ("darken", "Darken"), + ("Mltp", "Multiply"), + ("multiply", "Multiply"), + ("CBrn", "Color Burn"), + ("colorBurn", "Color Burn"), + ("linearBurn", "Linear Burn"), + ("darkerColor", "Darker Color"), + ("Lghn", "Lighten"), + ("lighten", "Lighten"), + ("Scrn", "Screen"), + ("screen", "Screen"), + ("CDdg", "Color Dodge"), + ("colorDodge", "Color Dodge"), + ("linearDodge", "Linear Dodge (Add)"), + ("lighterColor", "Lighter Color"), + ("Ovrl", "Overlay"), + ("overlay", "Overlay"), + ("SftL", "Soft Light"), + ("softLight", "Soft Light"), + ("HrdL", "Hard Light"), + ("hardLight", "Hard Light"), + ("vividLight", "Vivid Light"), + ("linearLight", "Linear Light"), + ("pinLight", "Pin Light"), + ("hardMix", "Hard Mix"), + ("Dfrn", "Difference"), + ("difference", "Difference"), + ("Xclu", "Exclusion"), + ("exclusion", "Exclusion"), + ("blendSubtraction", "Subtract"), + ("blendDivide", "Divide"), + ("H", "Hue"), + ("hue", "Hue"), + ("Strt", "Saturation"), + ("saturation", "Saturation"), + ("Clr", "Color"), + ("color", "Color"), + ("Lmns", "Luminosity"), + ("luminosity", "Luminosity"), + ("PsTh", "Pass Through"), + ("passThrough", "Pass Through"), +]; + +pub(super) fn blend_label(ps: &str) -> Option<&'static str> { + BLEND_MODES.iter().find(|(k, _)| *k == ps).map(|(_, v)| *v) +} + +pub(super) fn blend_ps(label: &str) -> Option<&'static str> { + crate::commands::blend_from_str(label).and_then(|m| BLEND_MODES.iter().find(|(_, v)| crate::commands::blend_from_str(v) == Some(m))).map(|(k, _)| *k) +} + +/// Photoshop ↔ PhotoCraft value tables; Photoshop codes compare without their space padding. +pub(super) fn lookup<'a>(table: &'a [(&'a str, &'a str)], key: &str) -> Option<&'a str> { + table.iter().find(|(k, _)| k.trim_end() == key.trim_end()).map(|(_, v)| *v) +} + +pub(super) fn lookup_back<'a>(table: &'a [(&'a str, &'a str)], value: &str) -> Option<&'a str> { + table.iter().find(|(_, v)| *v == value).map(|(k, _)| *k) +} + +/// `Chnl` enumeration ↔ the per-channel keys of the adjustment commands. +pub(super) const CHANNELS: &[(&str, &str)] = &[ + ("Rd", "red"), + ("Grn", "green"), + ("Bl", "blue"), + ("Gry", "gray"), + ("Cyn", "cyan"), + ("Mgnt", "magenta"), + ("Yllw", "yellow"), + ("Blck", "black"), + ("Lmnc", "lightness"), + ("A", "a"), + ("B", "b"), +]; + +/// The channel an adjustment entry's `Chnl` reference names: `None` = the composite. +pub(super) fn channel_key(d: &Descriptor) -> Option> { + let r = get_ref(d, "Chnl")?; + Some(match target(r) { + Target::Ordinal(o) if o == "Trgt" || o == "Cmps" => None, + Target::Ordinal(o) => Some(lookup(CHANNELS, &o)?), + _ => return None, + }) +} + +/// A Levels or Curves entry's channel: `Chnl.Cmps` for the composite, as Photoshop records it. +/// Photoshop silently skips a Set whose composite is `Ordn.Trgt` (#8543). +pub(super) fn channel_ref(key: Option<&str>) -> D { + let value = key.and_then(|k| lookup_back(CHANNELS, k)); + D::Reference(vec![ReferenceItem::Enumerated { class: class("Chnl"), type_id: code("Chnl"), value: code(value.unwrap_or("Cmps")) }]) +} + +pub(super) const INTERPOLATION: &[(&str, &str)] = &[ + ("Bcbc", "bicubic"), + ("Blnr", "bilinear"), + ("Nrst", "nearest"), + ("bicubicSharper", "bicubicSharper"), + ("bicubicSmoother", "bicubicSmoother"), + ("bicubicAutomatic", "bicubicAutomatic"), + ("automaticInterpolation", "automatic"), + ("preserveDetailsUpscale", "preserveDetails"), + ("deepUpscale", "preserveDetails"), +]; + +pub(super) const NOISE: &[(&str, &str)] = &[("Unfr", "uniform"), ("Gsn ", "gaussian")]; + +pub(super) const OFFSET_FILL: &[(&str, &str)] = &[("Wrp ", "wrap"), ("Rpt ", "repeat"), ("Bckg", "transparent")]; + +pub(super) const TRIM: &[(&str, &str)] = &[("Trns", "transparent"), ("topLeftPixelColor", "topLeft"), ("bottomRightPixelColor", "bottomRight")]; + +pub(super) const EXTENSION: &[(&str, &str)] = &[("Bckg", "background"), ("Frgd", "foreground"), ("Wht ", "white"), ("Blck", "black"), ("Trns", "transparent")]; + +pub(super) const FILL_CONTENTS: &[(&str, &str)] = &[ + ("FrgC", "foreground"), + ("BckC", "background"), + ("Wht ", "white"), + ("Blck", "black"), + ("Gry ", "gray"), + ("Clr ", "color"), + ("HstS", "history"), + ("contentAware", "contentAware"), +]; + +pub(super) const STROKE_LOCATION: &[(&str, &str)] = &[("Insd", "inside"), ("Cntr", "center"), ("OtsF", "outside")]; + +pub(super) const INTENT: &[(&str, &str)] = &[("Img ", "perceptual"), ("Clrm", "relative"), ("Grp ", "saturation"), ("AbsC", "absolute")]; + +pub(super) const PROFILES: &[(&str, &str)] = + &[("sRGB IEC61966-2.1", "srgb"), ("Display P3", "display-p3"), ("Adobe RGB (1998)", "adobe-rgb-compat"), ("ProPhoto RGB", "prophoto-compat")]; + +/// Smart Blur quality. Photoshop's codes come first, so they are what an export writes (measured in +/// Photoshop: `Hgh `/`Mdm `/`Low ` play back as its fallback, low quality). The old codes after +/// them still read, for actions PhotoCraft wrote before. +pub(super) const SMART_BLUR_QUALITY: &[(&str, &str)] = + &[("SBQL", "low"), ("SBQM", "medium"), ("SBQH", "high"), ("Hgh ", "high"), ("Mdm ", "medium"), ("Low ", "low")]; + +pub(super) const SMART_BLUR_MODE: &[(&str, &str)] = &[("SBMN", "normal"), ("SBME", "edgeOnly"), ("SBMO", "overlayEdge")]; + +pub(super) const RADIAL_METHOD: &[(&str, &str)] = &[("Spn ", "spin"), ("Zm ", "zoom")]; + +pub(super) const RADIAL_QUALITY: &[(&str, &str)] = &[("Drft", "draft"), ("Gd ", "good"), ("Bst ", "best")]; + +pub(super) const LABEL_COLORS: &[(&str, &str)] = + &[("None", "none"), ("Rd", "red"), ("Orng", "orange"), ("Ylw", "yellow"), ("Grn", "green"), ("Bl", "blue"), ("Vlt", "violet"), ("Gry", "gray")]; + +pub(super) const ALIGN: &[(&str, &str)] = + &[("AdLf", "leftEdges"), ("AdCH", "horizontalCenters"), ("AdRg", "rightEdges"), ("AdTp", "topEdges"), ("AdCV", "verticalCenters"), ("AdBt", "bottomEdges")]; + +pub(super) const PURGE: &[(&str, &str)] = &[("Al", "all"), ("Clpb", "clipboard"), ("Hsty", "histories"), ("Undo", "undo")]; + +pub(super) const MODES: &[(&str, &str)] = &[("RGBM", "rgb"), ("Grys", "grayscale"), ("CMYM", "cmyk"), ("LbCM", "lab"), ("Mltc", "multichannel")]; + +/// `MnIt` menu-item codes ↔ the shell's view commands. +pub(super) const MENU_ITEMS: &[(&str, &str)] = + &[("FtOn", "view.fitOnScreen"), ("ActP", "view.actualPixels"), ("ZmIn", "view.zoomIn"), ("ZmOt", "view.zoomOut")]; + +/// Save As format classes (`As`) and the extensions PhotoCraft saves them under. The first +/// extension of a class is the one exported, and the first class of an extension is the one +/// written back. `WebPFormat` is Photoshop's built-in WebP (checked against Photoshop 2026); the +/// Google classes come from the older WebPShop plug-in and are only read. +pub(super) const SAVE_FORMATS: &[(&str, &[&str])] = &[ + ("Pht3", &["psd"]), + ("PNGF", &["png"]), + ("JPEG", &["jpg", "jpeg"]), + ("TIFF", &["tif", "tiff"]), + ("BMPF", &["bmp"]), + ("WebPFormat", &["webp"]), + ("Google WebPShop", &["webp"]), + ("Google WebP", &["webp"]), +]; diff --git a/crates/engine/src/atn_cmds/tests.rs b/crates/engine/src/cmd/atn_cmds/tests.rs similarity index 100% rename from crates/engine/src/atn_cmds/tests.rs rename to crates/engine/src/cmd/atn_cmds/tests.rs diff --git a/crates/engine/src/automate_cmds.rs b/crates/engine/src/cmd/automate_cmds.rs similarity index 100% rename from crates/engine/src/automate_cmds.rs rename to crates/engine/src/cmd/automate_cmds.rs diff --git a/crates/engine/src/automate_cmds/tests.rs b/crates/engine/src/cmd/automate_cmds/tests.rs similarity index 100% rename from crates/engine/src/automate_cmds/tests.rs rename to crates/engine/src/cmd/automate_cmds/tests.rs diff --git a/crates/engine/src/background_cmds.rs b/crates/engine/src/cmd/background_cmds.rs similarity index 100% rename from crates/engine/src/background_cmds.rs rename to crates/engine/src/cmd/background_cmds.rs diff --git a/crates/engine/src/brush_cmds.rs b/crates/engine/src/cmd/brush_cmds.rs similarity index 100% rename from crates/engine/src/brush_cmds.rs rename to crates/engine/src/cmd/brush_cmds.rs diff --git a/crates/engine/src/brush_cmds/mixer_live.rs b/crates/engine/src/cmd/brush_cmds/mixer_live.rs similarity index 100% rename from crates/engine/src/brush_cmds/mixer_live.rs rename to crates/engine/src/cmd/brush_cmds/mixer_live.rs diff --git a/crates/engine/src/brush_cmds/mixer_live_tests.rs b/crates/engine/src/cmd/brush_cmds/mixer_live_tests.rs similarity index 100% rename from crates/engine/src/brush_cmds/mixer_live_tests.rs rename to crates/engine/src/cmd/brush_cmds/mixer_live_tests.rs diff --git a/crates/engine/src/brush_cmds/tests.rs b/crates/engine/src/cmd/brush_cmds/tests.rs similarity index 100% rename from crates/engine/src/brush_cmds/tests.rs rename to crates/engine/src/cmd/brush_cmds/tests.rs diff --git a/crates/engine/src/brush_key_cmds.rs b/crates/engine/src/cmd/brush_key_cmds.rs similarity index 100% rename from crates/engine/src/brush_key_cmds.rs rename to crates/engine/src/cmd/brush_key_cmds.rs diff --git a/crates/engine/src/brush_preset_cmds.rs b/crates/engine/src/cmd/brush_preset_cmds.rs similarity index 54% rename from crates/engine/src/brush_preset_cmds.rs rename to crates/engine/src/cmd/brush_preset_cmds.rs index 1c126ec477..cd54b1ff61 100644 --- a/crates/engine/src/brush_preset_cmds.rs +++ b/crates/engine/src/cmd/brush_preset_cmds.rs @@ -486,331 +486,4 @@ pub fn specs() -> Vec { } #[cfg(test)] -mod tests { - use super::*; - - fn names(s: &Session, g: &str) -> Vec { - s.tools.presets.iter().filter(|x| x.group == g).map(|x| x.name.clone()).collect() - } - - fn with_groups() -> Session { - let mut s = Session::new(); - for (n, g) in [("A1", "Alpha"), ("A2", "Alpha"), ("A3", "Alpha"), ("B1", "Beta"), ("B2", "Beta")] { - s.tools.presets.push(BrushPreset { - name: n.into(), - brush: Default::default(), - builtin: false, - group: g.into(), - folder: Vec::new(), - captures: Default::default(), - }); - } - s - } - - #[test] - fn move_within_and_between_groups() { - let mut s = with_groups(); - let r = s.execute("brush.presets.move", json!({"name": "A3", "before": "A1"})).unwrap(); - assert_eq!(r, json!({"name": "A3", "group": "Alpha", "folder": [], "index": 0})); - assert_eq!(names(&s, "Alpha"), ["A3", "A1", "A2"]); - s.execute("brush.presets.move", json!({"name": "A3", "index": 99})).unwrap(); - assert_eq!(names(&s, "Alpha"), ["A1", "A2", "A3"]); - s.execute("brush.presets.move", json!({"name": "A1", "index": 1})).unwrap(); - assert_eq!(names(&s, "Alpha"), ["A2", "A1", "A3"]); - // Into another group, before a member (the group comes from `before`). - s.execute("brush.presets.move", json!({"name": "A1", "before": "B2"})).unwrap(); - assert_eq!((names(&s, "Alpha"), names(&s, "Beta")), (vec!["A2".to_string(), "A3".into()], vec!["B1".to_string(), "A1".into(), "B2".into()])); - // Into a group by name (appended), and into a new group. - s.execute("brush.presets.move", json!({"name": "A2", "group": "Beta"})).unwrap(); - assert_eq!(names(&s, "Beta"), ["B1", "A1", "B2", "A2"]); - s.execute("brush.presets.move", json!({"name": "A3", "group": "Gamma"})).unwrap(); - assert_eq!(group_order(&s.tools.presets).last().map(String::as_str), Some("Gamma")); - assert!(names(&s, "Alpha").is_empty()); - // A built-in moved to another group becomes the user's. - let b = s.tools.presets.iter().find(|x| x.builtin).unwrap().name.clone(); - s.execute("brush.presets.move", json!({"name": b, "group": "Beta", "index": 0})).unwrap(); - let moved = photocraft_paint::presets::find(&s.tools.presets, &b).unwrap(); - assert!(!moved.builtin && moved.group == "Beta"); - assert_eq!(names(&s, "Beta")[0], b); - } - - #[test] - fn groups_move_rename_and_delete() { - let mut s = with_groups(); - let order = group_order(&s.tools.presets); - let n = order.len(); - assert_eq!(&order[n - 2..], ["Alpha", "Beta"]); - let r = s.execute("brush.presets.moveGroup", json!({"group": "Beta", "index": 0})).unwrap(); - assert_eq!(r["index"], 0); - assert_eq!(group_order(&s.tools.presets)[0], "Beta"); - assert_eq!(names(&s, "Beta"), ["B1", "B2"], "a group moves as a block, in order"); - s.execute("brush.presets.moveGroup", json!({"group": "Alpha", "before": "Beta"})).unwrap(); - assert_eq!(&group_order(&s.tools.presets)[..2], ["Alpha", "Beta"]); - s.execute("brush.presets.moveGroup", json!({"group": "Alpha"})).unwrap(); - assert_eq!(group_order(&s.tools.presets).last().map(String::as_str), Some("Alpha")); - s.execute("brush.presets.renameGroup", json!({"group": "Alpha", "newName": "First"})).unwrap(); - assert_eq!(names(&s, "First"), ["A1", "A2", "A3"]); - assert!(s.execute("brush.presets.renameGroup", json!({"group": "First", "newName": "Beta"})).is_err()); - let r = s.execute("brush.presets.deleteGroup", json!({"group": "First"})).unwrap(); - assert_eq!(r["deleted"], 3); - assert!(names(&s, "First").is_empty()); - } - - #[test] - fn rename_checks_names() { - let mut s = with_groups(); - s.execute("brush.presets.rename", json!({"name": "a1", "newName": "Alpha One"})).unwrap(); - assert!(photocraft_paint::presets::find(&s.tools.presets, "Alpha One").is_some()); - assert!(s.execute("brush.presets.rename", json!({"name": "A2", "newName": "alpha one"})).is_err()); - // Case-only renames of itself are fine. - s.execute("brush.presets.rename", json!({"name": "Alpha One", "newName": "ALPHA ONE"})).unwrap(); - let b = s.tools.presets.iter().find(|x| x.builtin).unwrap().name.clone(); - s.execute("brush.presets.rename", json!({"name": b, "newName": "My Round"})).unwrap(); - assert!(!photocraft_paint::presets::find(&s.tools.presets, "My Round").unwrap().builtin); - } - - #[test] - fn bad_params_fail_without_changes() { - let mut s = with_groups(); - let before = s.tools.presets.clone(); - let long = "x".repeat(MAX_NAME + 1); - for (id, p) in [ - ("brush.presets.move", json!({})), - ("brush.presets.move", json!({"name": "Nope"})), - ("brush.presets.move", json!({"name": "A1", "before": "A1"})), - ("brush.presets.move", json!({"name": "A1", "before": "Nope"})), - ("brush.presets.move", json!({"name": "A1", "group": "Alpha", "before": "B1"})), - ("brush.presets.move", json!({"name": "A1", "index": -1})), - ("brush.presets.move", json!({"name": "A1", "index": "first"})), - ("brush.presets.move", json!({"name": "A1", "group": 7})), - ("brush.presets.move", json!({"name": "A1", "group": long})), - ("brush.presets.rename", json!({"name": "A1"})), - ("brush.presets.rename", json!({"name": "A1", "newName": " "})), - ("brush.presets.rename", json!({"name": "A1", "newName": long})), - ("brush.presets.moveGroup", json!({"group": "Nope"})), - ("brush.presets.moveGroup", json!({"group": "Alpha", "before": "Alpha"})), - ("brush.presets.moveGroup", json!({"group": "Alpha", "index": 1.5})), - ("brush.presets.renameGroup", json!({"group": "Alpha"})), - ("brush.presets.deleteGroup", json!({"group": null})), - ("brush.presets.deleteGroup", json!({"group": "Nope"})), - ] { - assert!(s.execute(id, p.clone()).is_err(), "{id} {p}"); - } - assert_eq!(s.tools.presets, before); - // Huge indices clamp to the end. - s.execute("brush.presets.move", json!({"name": "A1", "index": u64::MAX})).unwrap(); - s.execute("brush.presets.moveGroup", json!({"group": "Alpha", "index": u64::MAX})).unwrap(); - } - - /// Group "Set": S0 at its top level, folders Ink (I1, I2; subfolder Fine: F1) and Dry (D1). - fn with_folders() -> Session { - let mut s = Session::new(); - for (n, f) in [("S0", &[][..]), ("I1", &["Ink"][..]), ("F1", &["Ink", "Fine"][..]), ("I2", &["Ink"][..]), ("D1", &["Dry"][..])] { - let folder = f.iter().map(|x| x.to_string()).collect(); - s.tools.presets.push(BrushPreset { - name: n.into(), - brush: Default::default(), - builtin: false, - group: "Set".into(), - folder, - captures: Default::default(), - }); - } - s - } - - fn folder_of(s: &Session, n: &str) -> Vec { - photocraft_paint::presets::find(&s.tools.presets, n).unwrap().folder.clone() - } - - #[test] - fn presets_move_between_folders() { - let mut s = with_folders(); - // `before` brings its folder. - let r = s.execute("brush.presets.move", json!({"name": "D1", "before": "I2"})).unwrap(); - assert_eq!(r["folder"], json!(["Ink"])); - assert_eq!(folder_of(&s, "D1"), ["Ink"]); - // An explicit folder, appended at the end of it. - s.execute("brush.presets.move", json!({"name": "S0", "folder": ["Ink", "Fine"]})).unwrap(); - assert_eq!(folder_of(&s, "S0"), ["Ink", "Fine"]); - let pos = |n: &str| s.tools.presets.iter().position(|x| x.name == n).unwrap(); - assert_eq!(pos("S0"), pos("F1") + 1); - // Within its group without a folder keeps its folder; to another group without one lands - // at that group's top level; `folder: []` is the group's top level. - s.execute("brush.presets.move", json!({"name": "S0", "index": 0})).unwrap(); - assert_eq!(folder_of(&s, "S0"), ["Ink", "Fine"]); - s.execute("brush.presets.move", json!({"name": "S0", "group": "Other"})).unwrap(); - assert!(folder_of(&s, "S0").is_empty()); - s.execute("brush.presets.move", json!({"name": "I1", "folder": []})).unwrap(); - assert!(folder_of(&s, "I1").is_empty()); - // `before` in another folder than the one named. - assert!(s.execute("brush.presets.move", json!({"name": "I1", "folder": ["Dry"], "before": "I2"})).is_err()); - assert_eq!(subfolder_order(&s.tools.presets, "Set", &[]), ["Ink"]); - } - - #[test] - fn folders_move_rename_and_delete() { - let mut s = with_folders(); - assert_eq!(subfolder_order(&s.tools.presets, "Set", &[]), ["Ink", "Dry"]); - // Move Dry before Ink: the whole folder moves as a block. - let r = s.execute("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Dry"], "before": "Ink"})).unwrap(); - assert_eq!(r, json!({"group": "Set", "folder": ["Dry"], "index": 0})); - assert_eq!(subfolder_order(&s.tools.presets, "Set", &[]), ["Dry", "Ink"]); - s.execute("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Dry"]})).unwrap(); - assert_eq!(subfolder_order(&s.tools.presets, "Set", &[]), ["Ink", "Dry"]); - s.execute("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Dry"], "index": 0})).unwrap(); - assert_eq!(subfolder_order(&s.tools.presets, "Set", &[]), ["Dry", "Ink"]); - let ink: Vec<&str> = s.tools.presets.iter().filter(|x| x.folder.first().is_some_and(|f| f == "Ink")).map(|x| x.name.as_str()).collect(); - assert_eq!(ink, ["I1", "F1", "I2"], "presets keep their order inside a moved folder"); - // Rename a nested folder: every preset below it follows. - let r = s.execute("brush.presets.renameGroup", json!({"group": "Set", "folder": ["Ink"], "newName": "Inks"})).unwrap(); - assert_eq!(r["folder"], json!(["Inks"])); - assert_eq!(folder_of(&s, "F1"), ["Inks", "Fine"]); - assert!(s.execute("brush.presets.renameGroup", json!({"group": "Set", "folder": ["Inks"], "newName": "Dry"})).is_err()); - // Renaming the group keeps the folders. - s.execute("brush.presets.renameGroup", json!({"group": "Set", "newName": "Kit"})).unwrap(); - assert_eq!(folder_of(&s, "F1"), ["Inks", "Fine"]); - // Delete a nested folder: only the presets in it (and below) go. - let r = s.execute("brush.presets.deleteGroup", json!({"group": "Kit", "folder": ["Inks"]})).unwrap(); - assert_eq!(r["deleted"], 3); - assert!(photocraft_paint::presets::find(&s.tools.presets, "S0").is_some()); - assert!(photocraft_paint::presets::find(&s.tools.presets, "D1").is_some()); - } - - #[test] - fn bad_folder_params_fail_without_changes() { - let mut s = with_folders(); - let before = s.tools.presets.clone(); - let long = "x".repeat(MAX_NAME + 1); - let deep: Vec<&str> = vec!["a"; MAX_FOLDER_DEPTH + 1]; - for (id, p) in [ - ("brush.presets.move", json!({"name": "S0", "folder": "Ink"})), - ("brush.presets.move", json!({"name": "S0", "folder": [""]})), - ("brush.presets.move", json!({"name": "S0", "folder": [7]})), - ("brush.presets.move", json!({"name": "S0", "folder": [long]})), - ("brush.presets.move", json!({"name": "S0", "folder": deep})), - ("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Nope"]})), - ("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Ink"], "before": "Ink"})), - ("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Ink"], "before": "Nope"})), - ("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Ink"], "before": 3})), - ("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Ink"], "index": -2})), - ("brush.presets.renameGroup", json!({"group": "Set", "folder": ["Ink"], "newName": ""})), - ("brush.presets.renameGroup", json!({"group": "Set", "folder": ["Ink", "Nope"], "newName": "x"})), - ("brush.presets.deleteGroup", json!({"group": "Set", "folder": ["Dry", "Nope"]})), - ("brush.presets.deleteGroup", json!({"group": "Nope", "folder": ["Dry"]})), - ] { - assert!(s.execute(id, p.clone()).is_err(), "{id} {p}"); - } - assert_eq!(s.tools.presets, before); - s.execute("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Ink", "Fine"], "index": u64::MAX})).unwrap(); - } - - fn paths(s: &Session) -> Vec { - s.tools.presets.iter().filter(|x| !x.builtin).map(|x| format!("{}:{}:{}", x.group, x.folder.join("/"), x.name)).collect() - } - - /// `with_folders` plus group "Other" holding O1, and folder Box (B1) in it. - fn with_two_groups() -> Session { - let mut s = with_folders(); - for (n, f) in [("O1", &[][..]), ("B1", &["Box"][..])] { - let folder = f.iter().map(|x| x.to_string()).collect(); - s.tools.presets.push(BrushPreset { - name: n.into(), - brush: Default::default(), - builtin: false, - group: "Other".into(), - folder, - captures: Default::default(), - }); - } - s - } - - #[test] - fn folders_move_into_folders_and_groups() { - let mut s = with_two_groups(); - // A nested folder into a sibling folder: its subtree follows, order kept. - let r = s.execute("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Dry"], "into": {"group": "Set", "folder": ["Ink", "Fine"]}})).unwrap(); - assert_eq!(r, json!({"group": "Set", "folder": ["Ink", "Fine", "Dry"], "index": 0})); - assert_eq!(folder_of(&s, "D1"), ["Ink", "Fine", "Dry"]); - // Into another group, before one of its folders. - let r = s.execute("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Ink"], "into": {"group": "Other"}, "before": "Box"})).unwrap(); - assert_eq!(r["folder"], json!(["Ink"])); - assert_eq!(paths(&s), ["Set::S0", "Other::O1", "Other:Ink:I1", "Other:Ink/Fine:F1", "Other:Ink/Fine/Dry:D1", "Other:Ink:I2", "Other:Box:B1"]); - // Out to the top level: the folder becomes a group of its own. - let r = s.execute("brush.presets.moveGroup", json!({"group": "Other", "folder": ["Ink", "Fine"], "into": {}})).unwrap(); - assert_eq!(r["group"], "Fine"); - assert_eq!(folder_of(&s, "D1"), ["Dry"]); - assert_eq!(photocraft_paint::presets::find(&s.tools.presets, "F1").unwrap().group, "Fine"); - // A whole group into another group's folder. - s.execute("brush.presets.moveGroup", json!({"group": "Fine", "into": {"group": "Set"}})).unwrap(); - assert!(names(&s, "Fine").is_empty()); - assert_eq!(folder_of(&s, "D1"), ["Fine", "Dry"]); - assert_eq!(subfolder_order(&s.tools.presets, "Set", &[]), ["Fine"]); - } - - #[test] - fn bad_moves_into_folders_fail_without_changes() { - let mut s = with_two_groups(); - // A chain 31 deep under Set/Deep. - let deep: Vec = std::iter::once("Deep".to_string()).chain((0..30).map(|i| format!("d{i}"))).collect(); - s.tools.presets.push(BrushPreset { - name: "Z".into(), - brush: Default::default(), - builtin: false, - group: "Set".into(), - folder: deep.clone(), - captures: Default::default(), - }); - s.tools.presets.push(BrushPreset { - name: "Y".into(), - brush: Default::default(), - builtin: false, - group: "Other".into(), - folder: vec!["Dry".into()], - captures: Default::default(), - }); - let before = s.tools.presets.clone(); - let deep_json = json!(deep); - for p in [ - // Into itself or its own descendant. - json!({"group": "Set", "folder": ["Ink"], "into": {"group": "Set", "folder": ["Ink"]}}), - json!({"group": "Set", "folder": ["Ink"], "into": {"group": "Set", "folder": ["Ink", "Fine"]}}), - json!({"group": "Set", "into": {"group": "Set", "folder": ["Dry"]}}), - json!({"group": "Set", "into": {"group": "Set"}}), - // A group already at the top level; the ungrouped presets. - json!({"group": "Set", "into": {}}), - // A name clash at the destination. - json!({"group": "Set", "folder": ["Dry"], "into": {"group": "Other"}}), - json!({"group": "Other", "folder": ["Box"], "into": {"group": "Set", "folder": ["Ink"]}, "before": "Nope"}), - json!({"group": "Set", "folder": ["Dry"], "into": {"group": "Set", "folder": ["Ink"]}, "index": 0}), - // Missing destinations and bad shapes. - json!({"group": "Set", "folder": ["Dry"], "into": {"group": "Nope"}}), - json!({"group": "Set", "folder": ["Dry"], "into": {"group": "Other", "folder": ["Nope"]}}), - json!({"group": "Set", "folder": ["Dry"], "into": {"folder": ["Box"]}}), - json!({"group": "Set", "folder": ["Dry"], "into": "Other"}), - json!({"group": "Set", "folder": ["Dry"], "into": {"group": 5}}), - json!({"group": "Set", "folder": ["Dry"], "into": {"group": "Other"}, "before": 3}), - // Deeper than MAX_FOLDER_DEPTH once moved (Ink/Fine is 2 deep: 2 + 31 > 32). - json!({"group": "Set", "folder": ["Deep"], "into": {"group": "Set", "folder": ["Ink", "Fine"]}}), - json!({"group": "Set", "folder": ["Ink"], "into": {"group": "Set", "folder": deep_json}}), - ] { - assert!(s.execute("brush.presets.moveGroup", p.clone()).is_err(), "{p}"); - } - assert_eq!(s.tools.presets, before); - // Ink/Fine into Set itself: a clash with nothing, so it moves up a level. - s.execute("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Ink", "Fine"], "into": {"group": "Set"}})).unwrap(); - assert_eq!(folder_of(&s, "F1"), ["Fine"]); - // An ungrouped preset's group can't move. - s.tools.presets.push(BrushPreset { - name: "U".into(), - brush: Default::default(), - builtin: false, - group: String::new(), - folder: Vec::new(), - captures: Default::default(), - }); - assert!(s.execute("brush.presets.moveGroup", json!({"group": "", "into": {"group": "Set"}})).is_err()); - } -} +mod tests; diff --git a/crates/engine/src/cmd/brush_preset_cmds/tests.rs b/crates/engine/src/cmd/brush_preset_cmds/tests.rs new file mode 100644 index 0000000000..eeed131bc7 --- /dev/null +++ b/crates/engine/src/cmd/brush_preset_cmds/tests.rs @@ -0,0 +1,326 @@ +use super::*; + +fn names(s: &Session, g: &str) -> Vec { + s.tools.presets.iter().filter(|x| x.group == g).map(|x| x.name.clone()).collect() +} + +fn with_groups() -> Session { + let mut s = Session::new(); + for (n, g) in [("A1", "Alpha"), ("A2", "Alpha"), ("A3", "Alpha"), ("B1", "Beta"), ("B2", "Beta")] { + s.tools.presets.push(BrushPreset { + name: n.into(), + brush: Default::default(), + builtin: false, + group: g.into(), + folder: Vec::new(), + captures: Default::default(), + }); + } + s +} + +#[test] +fn move_within_and_between_groups() { + let mut s = with_groups(); + let r = s.execute("brush.presets.move", json!({"name": "A3", "before": "A1"})).unwrap(); + assert_eq!(r, json!({"name": "A3", "group": "Alpha", "folder": [], "index": 0})); + assert_eq!(names(&s, "Alpha"), ["A3", "A1", "A2"]); + s.execute("brush.presets.move", json!({"name": "A3", "index": 99})).unwrap(); + assert_eq!(names(&s, "Alpha"), ["A1", "A2", "A3"]); + s.execute("brush.presets.move", json!({"name": "A1", "index": 1})).unwrap(); + assert_eq!(names(&s, "Alpha"), ["A2", "A1", "A3"]); + // Into another group, before a member (the group comes from `before`). + s.execute("brush.presets.move", json!({"name": "A1", "before": "B2"})).unwrap(); + assert_eq!((names(&s, "Alpha"), names(&s, "Beta")), (vec!["A2".to_string(), "A3".into()], vec!["B1".to_string(), "A1".into(), "B2".into()])); + // Into a group by name (appended), and into a new group. + s.execute("brush.presets.move", json!({"name": "A2", "group": "Beta"})).unwrap(); + assert_eq!(names(&s, "Beta"), ["B1", "A1", "B2", "A2"]); + s.execute("brush.presets.move", json!({"name": "A3", "group": "Gamma"})).unwrap(); + assert_eq!(group_order(&s.tools.presets).last().map(String::as_str), Some("Gamma")); + assert!(names(&s, "Alpha").is_empty()); + // A built-in moved to another group becomes the user's. + let b = s.tools.presets.iter().find(|x| x.builtin).unwrap().name.clone(); + s.execute("brush.presets.move", json!({"name": b, "group": "Beta", "index": 0})).unwrap(); + let moved = photocraft_paint::presets::find(&s.tools.presets, &b).unwrap(); + assert!(!moved.builtin && moved.group == "Beta"); + assert_eq!(names(&s, "Beta")[0], b); +} + +#[test] +fn groups_move_rename_and_delete() { + let mut s = with_groups(); + let order = group_order(&s.tools.presets); + let n = order.len(); + assert_eq!(&order[n - 2..], ["Alpha", "Beta"]); + let r = s.execute("brush.presets.moveGroup", json!({"group": "Beta", "index": 0})).unwrap(); + assert_eq!(r["index"], 0); + assert_eq!(group_order(&s.tools.presets)[0], "Beta"); + assert_eq!(names(&s, "Beta"), ["B1", "B2"], "a group moves as a block, in order"); + s.execute("brush.presets.moveGroup", json!({"group": "Alpha", "before": "Beta"})).unwrap(); + assert_eq!(&group_order(&s.tools.presets)[..2], ["Alpha", "Beta"]); + s.execute("brush.presets.moveGroup", json!({"group": "Alpha"})).unwrap(); + assert_eq!(group_order(&s.tools.presets).last().map(String::as_str), Some("Alpha")); + s.execute("brush.presets.renameGroup", json!({"group": "Alpha", "newName": "First"})).unwrap(); + assert_eq!(names(&s, "First"), ["A1", "A2", "A3"]); + assert!(s.execute("brush.presets.renameGroup", json!({"group": "First", "newName": "Beta"})).is_err()); + let r = s.execute("brush.presets.deleteGroup", json!({"group": "First"})).unwrap(); + assert_eq!(r["deleted"], 3); + assert!(names(&s, "First").is_empty()); +} + +#[test] +fn rename_checks_names() { + let mut s = with_groups(); + s.execute("brush.presets.rename", json!({"name": "a1", "newName": "Alpha One"})).unwrap(); + assert!(photocraft_paint::presets::find(&s.tools.presets, "Alpha One").is_some()); + assert!(s.execute("brush.presets.rename", json!({"name": "A2", "newName": "alpha one"})).is_err()); + // Case-only renames of itself are fine. + s.execute("brush.presets.rename", json!({"name": "Alpha One", "newName": "ALPHA ONE"})).unwrap(); + let b = s.tools.presets.iter().find(|x| x.builtin).unwrap().name.clone(); + s.execute("brush.presets.rename", json!({"name": b, "newName": "My Round"})).unwrap(); + assert!(!photocraft_paint::presets::find(&s.tools.presets, "My Round").unwrap().builtin); +} + +#[test] +fn bad_params_fail_without_changes() { + let mut s = with_groups(); + let before = s.tools.presets.clone(); + let long = "x".repeat(MAX_NAME + 1); + for (id, p) in [ + ("brush.presets.move", json!({})), + ("brush.presets.move", json!({"name": "Nope"})), + ("brush.presets.move", json!({"name": "A1", "before": "A1"})), + ("brush.presets.move", json!({"name": "A1", "before": "Nope"})), + ("brush.presets.move", json!({"name": "A1", "group": "Alpha", "before": "B1"})), + ("brush.presets.move", json!({"name": "A1", "index": -1})), + ("brush.presets.move", json!({"name": "A1", "index": "first"})), + ("brush.presets.move", json!({"name": "A1", "group": 7})), + ("brush.presets.move", json!({"name": "A1", "group": long})), + ("brush.presets.rename", json!({"name": "A1"})), + ("brush.presets.rename", json!({"name": "A1", "newName": " "})), + ("brush.presets.rename", json!({"name": "A1", "newName": long})), + ("brush.presets.moveGroup", json!({"group": "Nope"})), + ("brush.presets.moveGroup", json!({"group": "Alpha", "before": "Alpha"})), + ("brush.presets.moveGroup", json!({"group": "Alpha", "index": 1.5})), + ("brush.presets.renameGroup", json!({"group": "Alpha"})), + ("brush.presets.deleteGroup", json!({"group": null})), + ("brush.presets.deleteGroup", json!({"group": "Nope"})), + ] { + assert!(s.execute(id, p.clone()).is_err(), "{id} {p}"); + } + assert_eq!(s.tools.presets, before); + // Huge indices clamp to the end. + s.execute("brush.presets.move", json!({"name": "A1", "index": u64::MAX})).unwrap(); + s.execute("brush.presets.moveGroup", json!({"group": "Alpha", "index": u64::MAX})).unwrap(); +} + +/// Group "Set": S0 at its top level, folders Ink (I1, I2; subfolder Fine: F1) and Dry (D1). +fn with_folders() -> Session { + let mut s = Session::new(); + for (n, f) in [("S0", &[][..]), ("I1", &["Ink"][..]), ("F1", &["Ink", "Fine"][..]), ("I2", &["Ink"][..]), ("D1", &["Dry"][..])] { + let folder = f.iter().map(|x| x.to_string()).collect(); + s.tools.presets.push(BrushPreset { + name: n.into(), + brush: Default::default(), + builtin: false, + group: "Set".into(), + folder, + captures: Default::default(), + }); + } + s +} + +fn folder_of(s: &Session, n: &str) -> Vec { + photocraft_paint::presets::find(&s.tools.presets, n).unwrap().folder.clone() +} + +#[test] +fn presets_move_between_folders() { + let mut s = with_folders(); + // `before` brings its folder. + let r = s.execute("brush.presets.move", json!({"name": "D1", "before": "I2"})).unwrap(); + assert_eq!(r["folder"], json!(["Ink"])); + assert_eq!(folder_of(&s, "D1"), ["Ink"]); + // An explicit folder, appended at the end of it. + s.execute("brush.presets.move", json!({"name": "S0", "folder": ["Ink", "Fine"]})).unwrap(); + assert_eq!(folder_of(&s, "S0"), ["Ink", "Fine"]); + let pos = |n: &str| s.tools.presets.iter().position(|x| x.name == n).unwrap(); + assert_eq!(pos("S0"), pos("F1") + 1); + // Within its group without a folder keeps its folder; to another group without one lands + // at that group's top level; `folder: []` is the group's top level. + s.execute("brush.presets.move", json!({"name": "S0", "index": 0})).unwrap(); + assert_eq!(folder_of(&s, "S0"), ["Ink", "Fine"]); + s.execute("brush.presets.move", json!({"name": "S0", "group": "Other"})).unwrap(); + assert!(folder_of(&s, "S0").is_empty()); + s.execute("brush.presets.move", json!({"name": "I1", "folder": []})).unwrap(); + assert!(folder_of(&s, "I1").is_empty()); + // `before` in another folder than the one named. + assert!(s.execute("brush.presets.move", json!({"name": "I1", "folder": ["Dry"], "before": "I2"})).is_err()); + assert_eq!(subfolder_order(&s.tools.presets, "Set", &[]), ["Ink"]); +} + +#[test] +fn folders_move_rename_and_delete() { + let mut s = with_folders(); + assert_eq!(subfolder_order(&s.tools.presets, "Set", &[]), ["Ink", "Dry"]); + // Move Dry before Ink: the whole folder moves as a block. + let r = s.execute("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Dry"], "before": "Ink"})).unwrap(); + assert_eq!(r, json!({"group": "Set", "folder": ["Dry"], "index": 0})); + assert_eq!(subfolder_order(&s.tools.presets, "Set", &[]), ["Dry", "Ink"]); + s.execute("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Dry"]})).unwrap(); + assert_eq!(subfolder_order(&s.tools.presets, "Set", &[]), ["Ink", "Dry"]); + s.execute("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Dry"], "index": 0})).unwrap(); + assert_eq!(subfolder_order(&s.tools.presets, "Set", &[]), ["Dry", "Ink"]); + let ink: Vec<&str> = s.tools.presets.iter().filter(|x| x.folder.first().is_some_and(|f| f == "Ink")).map(|x| x.name.as_str()).collect(); + assert_eq!(ink, ["I1", "F1", "I2"], "presets keep their order inside a moved folder"); + // Rename a nested folder: every preset below it follows. + let r = s.execute("brush.presets.renameGroup", json!({"group": "Set", "folder": ["Ink"], "newName": "Inks"})).unwrap(); + assert_eq!(r["folder"], json!(["Inks"])); + assert_eq!(folder_of(&s, "F1"), ["Inks", "Fine"]); + assert!(s.execute("brush.presets.renameGroup", json!({"group": "Set", "folder": ["Inks"], "newName": "Dry"})).is_err()); + // Renaming the group keeps the folders. + s.execute("brush.presets.renameGroup", json!({"group": "Set", "newName": "Kit"})).unwrap(); + assert_eq!(folder_of(&s, "F1"), ["Inks", "Fine"]); + // Delete a nested folder: only the presets in it (and below) go. + let r = s.execute("brush.presets.deleteGroup", json!({"group": "Kit", "folder": ["Inks"]})).unwrap(); + assert_eq!(r["deleted"], 3); + assert!(photocraft_paint::presets::find(&s.tools.presets, "S0").is_some()); + assert!(photocraft_paint::presets::find(&s.tools.presets, "D1").is_some()); +} + +#[test] +fn bad_folder_params_fail_without_changes() { + let mut s = with_folders(); + let before = s.tools.presets.clone(); + let long = "x".repeat(MAX_NAME + 1); + let deep: Vec<&str> = vec!["a"; MAX_FOLDER_DEPTH + 1]; + for (id, p) in [ + ("brush.presets.move", json!({"name": "S0", "folder": "Ink"})), + ("brush.presets.move", json!({"name": "S0", "folder": [""]})), + ("brush.presets.move", json!({"name": "S0", "folder": [7]})), + ("brush.presets.move", json!({"name": "S0", "folder": [long]})), + ("brush.presets.move", json!({"name": "S0", "folder": deep})), + ("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Nope"]})), + ("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Ink"], "before": "Ink"})), + ("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Ink"], "before": "Nope"})), + ("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Ink"], "before": 3})), + ("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Ink"], "index": -2})), + ("brush.presets.renameGroup", json!({"group": "Set", "folder": ["Ink"], "newName": ""})), + ("brush.presets.renameGroup", json!({"group": "Set", "folder": ["Ink", "Nope"], "newName": "x"})), + ("brush.presets.deleteGroup", json!({"group": "Set", "folder": ["Dry", "Nope"]})), + ("brush.presets.deleteGroup", json!({"group": "Nope", "folder": ["Dry"]})), + ] { + assert!(s.execute(id, p.clone()).is_err(), "{id} {p}"); + } + assert_eq!(s.tools.presets, before); + s.execute("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Ink", "Fine"], "index": u64::MAX})).unwrap(); +} + +fn paths(s: &Session) -> Vec { + s.tools.presets.iter().filter(|x| !x.builtin).map(|x| format!("{}:{}:{}", x.group, x.folder.join("/"), x.name)).collect() +} + +/// `with_folders` plus group "Other" holding O1, and folder Box (B1) in it. +fn with_two_groups() -> Session { + let mut s = with_folders(); + for (n, f) in [("O1", &[][..]), ("B1", &["Box"][..])] { + let folder = f.iter().map(|x| x.to_string()).collect(); + s.tools.presets.push(BrushPreset { + name: n.into(), + brush: Default::default(), + builtin: false, + group: "Other".into(), + folder, + captures: Default::default(), + }); + } + s +} + +#[test] +fn folders_move_into_folders_and_groups() { + let mut s = with_two_groups(); + // A nested folder into a sibling folder: its subtree follows, order kept. + let r = s.execute("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Dry"], "into": {"group": "Set", "folder": ["Ink", "Fine"]}})).unwrap(); + assert_eq!(r, json!({"group": "Set", "folder": ["Ink", "Fine", "Dry"], "index": 0})); + assert_eq!(folder_of(&s, "D1"), ["Ink", "Fine", "Dry"]); + // Into another group, before one of its folders. + let r = s.execute("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Ink"], "into": {"group": "Other"}, "before": "Box"})).unwrap(); + assert_eq!(r["folder"], json!(["Ink"])); + assert_eq!(paths(&s), ["Set::S0", "Other::O1", "Other:Ink:I1", "Other:Ink/Fine:F1", "Other:Ink/Fine/Dry:D1", "Other:Ink:I2", "Other:Box:B1"]); + // Out to the top level: the folder becomes a group of its own. + let r = s.execute("brush.presets.moveGroup", json!({"group": "Other", "folder": ["Ink", "Fine"], "into": {}})).unwrap(); + assert_eq!(r["group"], "Fine"); + assert_eq!(folder_of(&s, "D1"), ["Dry"]); + assert_eq!(photocraft_paint::presets::find(&s.tools.presets, "F1").unwrap().group, "Fine"); + // A whole group into another group's folder. + s.execute("brush.presets.moveGroup", json!({"group": "Fine", "into": {"group": "Set"}})).unwrap(); + assert!(names(&s, "Fine").is_empty()); + assert_eq!(folder_of(&s, "D1"), ["Fine", "Dry"]); + assert_eq!(subfolder_order(&s.tools.presets, "Set", &[]), ["Fine"]); +} + +#[test] +fn bad_moves_into_folders_fail_without_changes() { + let mut s = with_two_groups(); + // A chain 31 deep under Set/Deep. + let deep: Vec = std::iter::once("Deep".to_string()).chain((0..30).map(|i| format!("d{i}"))).collect(); + s.tools.presets.push(BrushPreset { + name: "Z".into(), + brush: Default::default(), + builtin: false, + group: "Set".into(), + folder: deep.clone(), + captures: Default::default(), + }); + s.tools.presets.push(BrushPreset { + name: "Y".into(), + brush: Default::default(), + builtin: false, + group: "Other".into(), + folder: vec!["Dry".into()], + captures: Default::default(), + }); + let before = s.tools.presets.clone(); + let deep_json = json!(deep); + for p in [ + // Into itself or its own descendant. + json!({"group": "Set", "folder": ["Ink"], "into": {"group": "Set", "folder": ["Ink"]}}), + json!({"group": "Set", "folder": ["Ink"], "into": {"group": "Set", "folder": ["Ink", "Fine"]}}), + json!({"group": "Set", "into": {"group": "Set", "folder": ["Dry"]}}), + json!({"group": "Set", "into": {"group": "Set"}}), + // A group already at the top level; the ungrouped presets. + json!({"group": "Set", "into": {}}), + // A name clash at the destination. + json!({"group": "Set", "folder": ["Dry"], "into": {"group": "Other"}}), + json!({"group": "Other", "folder": ["Box"], "into": {"group": "Set", "folder": ["Ink"]}, "before": "Nope"}), + json!({"group": "Set", "folder": ["Dry"], "into": {"group": "Set", "folder": ["Ink"]}, "index": 0}), + // Missing destinations and bad shapes. + json!({"group": "Set", "folder": ["Dry"], "into": {"group": "Nope"}}), + json!({"group": "Set", "folder": ["Dry"], "into": {"group": "Other", "folder": ["Nope"]}}), + json!({"group": "Set", "folder": ["Dry"], "into": {"folder": ["Box"]}}), + json!({"group": "Set", "folder": ["Dry"], "into": "Other"}), + json!({"group": "Set", "folder": ["Dry"], "into": {"group": 5}}), + json!({"group": "Set", "folder": ["Dry"], "into": {"group": "Other"}, "before": 3}), + // Deeper than MAX_FOLDER_DEPTH once moved (Ink/Fine is 2 deep: 2 + 31 > 32). + json!({"group": "Set", "folder": ["Deep"], "into": {"group": "Set", "folder": ["Ink", "Fine"]}}), + json!({"group": "Set", "folder": ["Ink"], "into": {"group": "Set", "folder": deep_json}}), + ] { + assert!(s.execute("brush.presets.moveGroup", p.clone()).is_err(), "{p}"); + } + assert_eq!(s.tools.presets, before); + // Ink/Fine into Set itself: a clash with nothing, so it moves up a level. + s.execute("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Ink", "Fine"], "into": {"group": "Set"}})).unwrap(); + assert_eq!(folder_of(&s, "F1"), ["Fine"]); + // An ungrouped preset's group can't move. + s.tools.presets.push(BrushPreset { + name: "U".into(), + brush: Default::default(), + builtin: false, + group: String::new(), + folder: Vec::new(), + captures: Default::default(), + }); + assert!(s.execute("brush.presets.moveGroup", json!({"group": "", "into": {"group": "Set"}})).is_err()); +} diff --git a/crates/engine/src/cmd/channel_cmds.rs b/crates/engine/src/cmd/channel_cmds.rs new file mode 100644 index 0000000000..6beb64542e --- /dev/null +++ b/crates/engine/src/cmd/channel_cmds.rs @@ -0,0 +1,296 @@ +//! Channels: alpha and spot channels, Select › Save / Load Selection, Quick Mask, channel +//! targeting and visibility (the Channels panel), Image › Apply Image / Calculations, and the +//! Channels panel menu (Split / Merge Channels, Merge Spot Channel). +//! +//! Alpha channels live in [`Document::channels`] (white = selected). Quick Mask is a temporary +//! channel in [`Document::quick_mask`], so entering and leaving it are history steps like in +//! Photoshop. Which channel is targeted and which are visible is view state on +//! [`DocState::channel_view`] (not history), like the active layer. +//! +//! Pixel commands (`paint.*`, `filter.*`, `image.adjustments.*`, `edit.fill`) take +//! `"target": {"channel": i}` or `"target": "quickMask"`; [`Session::execute`] fills that in from the +//! targeted channel when the caller didn't pass a target. Targeting a single colour channel keeps +//! those commands from touching the other colour channels of the layer ([`restrict_to_color`]). + +use photocraft_algo::selection::{self as sel, SelectionMode}; +use photocraft_color::{BlendMode, Color, ColorMode, PixelFormat, blend::blend_channel}; +use photocraft_doc::{AlphaChannel, ColorIndicates, Document, Layer, LayerContent, LayerId}; +use photocraft_geom::{Rect, TileCoord}; +use photocraft_raster::{Surface, from_rgba, to_rgba}; +use serde::Serialize; +use serde_json::{Value, json}; + +use crate::commands::CommandSpec; +use crate::{DocState, EngineError, Result, Session}; + +#[cfg(test)] +mod tests; + +// --------------------------------------------------------------------------------------------- +// Enabled predicates + +fn has_doc(s: &Session) -> std::result::Result<(), String> { + s.active().map(|_| ()).ok_or_else(|| "no document open".into()) +} +fn has_channels(s: &Session) -> std::result::Result<(), String> { + has_doc(s)?; + if s.active().is_some_and(|d| !d.doc.channels.is_empty()) { Ok(()) } else { Err("the document has no alpha channels".into()) } +} +fn has_selection(s: &Session) -> std::result::Result<(), String> { + has_doc(s)?; + if s.active().is_some_and(|d| d.doc.selection.is_some()) { Ok(()) } else { Err("no selection".into()) } +} +fn has_spot(s: &Session) -> std::result::Result<(), String> { + has_doc(s)?; + if s.active().is_some_and(|d| d.doc.channels.iter().any(|c| c.spot.is_some())) { Ok(()) } else { Err("the document has no spot channels".into()) } +} +fn can_split(s: &Session) -> std::result::Result<(), String> { + let d = s.active().ok_or("no document open")?; + if color_count(&d.doc) + d.doc.channels.len() < 2 { Err("only one channel to split".into()) } else { Ok(()) } +} +fn can_merge(s: &Session) -> std::result::Result<(), String> { + has_doc(s)?; + if mergeable(s).len() >= 2 { Ok(()) } else { Err("Merge Channels needs at least two open grayscale documents of the same size".into()) } +} + +// --------------------------------------------------------------------------------------------- +// Save / Load Selection + +fn operation<'a>(p: &'a Value, key: &str) -> &'a str { + p.get(key).and_then(Value::as_str).unwrap_or("new") +} + +// --------------------------------------------------------------------------------------------- +// State as JSON + +/// The Channels panel rows and view state of a document (also part of `inspect`). +pub fn channels_json(st: &DocState) -> Value { + let doc = &st.doc; + let mode = edit_mode(doc); + let v = &st.channel_view; + let colors = color_count(doc); + json!({ + "composite": composite_name(mode), + "colors": color_names(mode).iter().enumerate().map(|(k, n)| json!({ "name": n, "visible": v.color_visible(k) })).collect::>(), + "alpha": doc.channels.iter().enumerate().map(|(i, c)| json!({ + "index": i, + "name": c.name, + "visible": v.alpha_shown(i), + "spot": c.spot.map(|(col, sol)| json!({ "color": col.to_rgb(), "solidity": sol })), + "color": c.color.to_rgb(), + "opacity": c.opacity, + "indicates": c.indicates, + })).collect::>(), + "quickMask": doc.quick_mask.as_ref().map(|q| json!({ "visible": !v.quick_mask_hidden, "color": q.color.to_rgb(), "opacity": q.opacity, "indicates": q.indicates })), + "target": v.target, + "compositeVisible": v.visible_colors(colors) == colors, + "layerMaskView": crate::mask_view_cmds::view_json(st), + }) +} + +fn list(s: &Session) -> Value { + s.active().map(channels_json).unwrap_or(Value::Null) +} + +// --------------------------------------------------------------------------------------------- +// Registry + +macro_rules! spec { + ($id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $en:expr, $run:expr) => { + CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run, journal: true } + }; +} + +mod calc; +mod manage; +mod planes; +mod refs; +mod selection; +mod spot; +mod targeting; +mod view; + +use calc::{apply_image, calculations}; +use manage::{delete_channel, duplicate_channel, move_channel, new_channel, new_spot, options, rename_channel, set_visible}; +use planes::edit_mode; +pub use planes::{ + GraySurface, IsolatedCurveChannel, channel_format, color_count, filter_mask_curve_channel, isolated_curve_channel, isolated_curve_channel_for, + next_alpha_name, +}; +pub(crate) use refs::source_spec; +pub use refs::{Blending, ChanRef, parse_ref}; +use selection::{load_selection, quick_mask, save_selection}; +use spot::{merge, merge_spot, mergeable, split}; +use targeting::{SLOT_KEY, target_cmd, target_slot}; +pub(crate) use targeting::{ + Target, channel_surface_for_filter, clear_channel, clear_color_channel, color_restriction, edits_channel, filter_mask_layer, inject_target, + is_channel_target, mask_target_enabled, read_target_surface, restrict_to_color, routed, target_of, target_surface, targeted_channel, targeted_color, +}; +pub use targeting::{follows_filter_mask, follows_target}; +pub(crate) use view::fix_view; +pub use view::{ChannelTarget, ChannelView, QuickMaskOptions, color_names, composite_name}; + +pub fn specs() -> Vec { + vec![ + spec!( + "select.saveSelection", + "Save Selection…", + ["Select"], + None, + r##"{"name":str?,"channel":"new"|index|name="new","document":index?,"operation":"new|replace|add|subtract|intersect"="new"}"##, + has_selection, + save_selection + ), + spec!( + "select.loadSelection", + "Load Selection…", + ["Select"], + None, + r##"{"channel":index|name|"composite"|"red|green|blue|…"|"transparency"|"mask"|"vectorMask"|"quickMask"|"selection"|"targeted" (the Channels panel's target),"layer":id?,"document":index?,"invert":bool=false,"operation":"new|add|subtract|intersect"="new"}"##, + has_doc, + load_selection + ), + spec!("select.editInQuickMaskMode", "Edit in Quick Mask Mode", ["Select"], Some("Q"), r##"{"on":bool?=toggle}"##, has_doc, quick_mask), + spec!( + "image.applyImage", + "Apply Image…", + ["Image"], + None, + r##"{"source":{"document":index?,"layer":id|name|"merged"="merged","channel":"composite"|"red|…"|index|"selection"|"transparency"|"mask"="composite","invert":bool=false},"blending":"normal|multiply|screen|overlay|softLight|hardLight|colorDodge|colorBurn|darken|lighten|difference|exclusion|linearBurn|linearDodge|add|subtract|…"="multiply","opacity":0..100=100,"scale":1..2=1,"offset":-255..255=0,"preserveTransparency":bool=false,"mask":{"document","layer","channel","invert"}?,"sourceChannel|sourceDocument|sourceLayer|sourceInvert|maskChannel|…":flat form of source/mask?}"##, + has_apply_target, + apply_image + ), + spec!( + "image.calculations", + "Calculations…", + ["Image"], + None, + r##"{"source1":{"document","layer","channel","invert"},"source2":{…},"blending":"multiply|…"="multiply","opacity":0..100=100,"scale":1..2=1,"offset":-255..255=0,"mask":{…}?,"result":"newChannel|newDocument|selection"="newChannel","name":str?}"##, + has_doc, + calculations + ), + spec!( + "channel.new", + "New Channel…", + [], + None, + r##"{"name":str?,"fill":"black|white|selection"="black","color":"#rrggbb"="#ff0000","opacity":0..100=50,"indicates":"masked|selected"="masked"}"##, + has_doc, + new_channel + ), + spec!( + "channel.newSpot", + "New Spot Channel…", + [], + None, + r##"{"name":str?,"color":"#rrggbb"="#ff0000","solidity":0..100=0,"fromSelection":bool=true}"##, + has_doc, + new_spot + ), + spec!( + "channel.duplicate", + "Duplicate Channel…", + [], + None, + r##"{"channel":index|name|"red|…"|"composite"|"quickMask","name":str?,"document":index|"new"?=active,"invert":bool=false}"##, + has_doc, + duplicate_channel + ), + spec!("channel.delete", "Delete Channel", [], None, r##"{"channel":index|name?=targeted}"##, has_channels, delete_channel), + spec!("channel.rename", "Rename Channel", [], None, r##"{"channel":index|name,"name":str}"##, has_channels, rename_channel), + spec!("channel.move", "Reorder Channel", [], None, r##"{"channel":index|name,"to":index}"##, has_channels, move_channel), + spec!( + "channel.target", + "Target Channel", + [], + None, + r##"{"channel":"composite"|"mask"|"vectorMask"|"red|green|blue|…"|index|name="composite"}"##, + has_doc, + target_cmd + ), + spec!( + "channel.setVisible", + "Channel Visibility", + [], + None, + r##"{"channel":"composite"|"red|…"|index|name|"quickMask","visible":bool?=toggle}"##, + has_doc, + set_visible + ), + spec!( + "channel.options", + "Channel Options…", + [], + None, + r##"{"channel":index|name|"quickMask"|"mask","name":str?,"indicates":"masked|selected|spot"?,"color":"#rrggbb"?,"opacity":0..100?,"solidity":0..100?} ("mask": Layer Mask Display Options, the rubylith's color and opacity for every layer mask, kept in the preferences as layerMaskOverlay; not an undo step; returns them as layerMaskOverlay)"##, + has_doc, + options + ), + spec!("channel.mergeSpot", "Merge Spot Channel", [], None, r##"{"channel":index|name?=targeted or first spot}"##, has_spot, merge_spot), + spec!("channel.split", "Split Channels", [], None, r##"{"closeOriginal":bool=true}"##, can_split, split), + spec!( + "channel.merge", + "Merge Channels…", + [], + None, + r##"{"mode":"rgb|cmyk|lab"="rgb","documents":[index,…]?=open grayscale docs of the active size,"name":str?}"##, + can_merge, + merge + ), + CommandSpec { + id: "channel.list", + label: "Channels", + menu: &[], + shortcut: None, + params: "{}", + enabled: has_doc, + run: |s, _| Ok(list(s)), + journal: false, + }, + spec!("channel.target.composite", "Target Composite Channel", [], Some("Cmd+2"), "{}", has_doc, |s, _| target_slot(s, 2)), + // ⌘\ targets the active layer's mask, as clicking its thumbnail does. + spec!("channel.target.layerMask", "Target Layer Mask", [], Some("Cmd+\\"), "{}", has_layer_mask, |s, _| target_cmd( + s, + &serde_json::json!({"channel": "mask"}) + )), + // ⌘⌥2 loads the image's luminosity as a selection (⌘-click on the composite channel). + spec!("select.loadLuminosity", "Load Luminosity", [], Some("Cmd+Alt+2"), "{}", has_doc, |s, _| load_selection( + s, + &serde_json::json!({"channel": "composite"}) + )), + spec!("channel.target.slot3", "Target Channel 3", [], Some("Cmd+3"), "{}", slot_ok::<3>, |s, _| target_slot(s, 3)), + spec!("channel.target.slot4", "Target Channel 4", [], Some("Cmd+4"), "{}", slot_ok::<4>, |s, _| target_slot(s, 4)), + spec!("channel.target.slot5", "Target Channel 5", [], Some("Cmd+5"), "{}", slot_ok::<5>, |s, _| target_slot(s, 5)), + spec!("channel.target.slot6", "Target Channel 6", [], Some("Cmd+6"), "{}", slot_ok::<6>, |s, _| target_slot(s, 6)), + spec!("channel.target.slot7", "Target Channel 7", [], Some("Cmd+7"), "{}", slot_ok::<7>, |s, _| target_slot(s, 7)), + spec!("channel.target.slot8", "Target Channel 8", [], Some("Cmd+8"), "{}", slot_ok::<8>, |s, _| target_slot(s, 8)), + spec!("channel.target.slot9", "Target Channel 9", [], Some("Cmd+9"), "{}", slot_ok::<9>, |s, _| target_slot(s, 9)), + ] +} + +/// Target Layer Mask: the active layer has a mask. +fn has_layer_mask(s: &Session) -> std::result::Result<(), String> { + let st = s.active().ok_or("no document open")?; + let layer = st.active_layer.and_then(|id| st.doc.layer(id)).ok_or("no active layer")?; + layer.mask.as_ref().map(|_| ()).ok_or_else(|| "the active layer has no layer mask".to_string()) +} + +fn slot_ok(s: &Session) -> std::result::Result<(), String> { + let d = s.active().ok_or("no document open")?; + let colors = color_count(&d.doc); + let shown = if colors > 1 { colors } else { 0 }; + if N - 3 < shown + d.doc.channels.len() { Ok(()) } else { Err(format!("no channel for {SLOT_KEY}{N}")) } +} + +fn has_apply_target(s: &Session) -> std::result::Result<(), String> { + if edits_channel(s) { + return Ok(()); + } + let d = s.active().ok_or("no document open")?; + let l = d.active_layer.and_then(|id| d.doc.layer(id)).ok_or("no active layer")?; + if matches!(l.content, LayerContent::Raster(_)) { + Ok(()) + } else { + Err(format!("Apply Image needs a pixel layer (active layer is {} {} layer)", l.content.article(), l.content.kind_name())) + } +} diff --git a/crates/engine/src/cmd/channel_cmds/calc.rs b/crates/engine/src/cmd/channel_cmds/calc.rs new file mode 100644 index 0000000000..57e71cb360 --- /dev/null +++ b/crates/engine/src/cmd/channel_cmds/calc.rs @@ -0,0 +1,119 @@ +use super::manage::gray_document; +use super::planes::{channel_format, next_alpha_name, plane_surface, read_plane}; +use super::refs::{Blending, bad, mask_plane, source, source_spec}; +use super::targeting::{Target, is_channel_target, target_of, target_surface}; +use super::*; + +// --------------------------------------------------------------------------------------------- +// Apply Image / Calculations + +pub(super) fn apply_image(s: &mut Session, p: &Value) -> Result { + let cmd = "image.applyImage"; + let blending = Blending::parse(p).map_err(|e| bad(cmd, e))?; + let opacity = p.get("opacity").and_then(Value::as_f64).unwrap_or(100.0).clamp(0.0, 100.0) as f32 / 100.0; + let preserve = p.get("preserveTransparency").and_then(Value::as_bool).unwrap_or(false); + let src_spec = source_spec(p, "source", "source").unwrap_or_else(|| json!({})); + let src = source(s, &src_spec, cmd, false)?; + let mask = mask_plane(s, p, cmd)?; + let layer = s.active().and_then(|d| d.active_layer); + s.edit("Apply Image", |doc, _| { + let area = doc.bounds(); + let selection = doc.selection.as_ref().map(|m| sel::mask_from_surface(Some(m), area)); + let weight = |i: usize| opacity * mask.as_ref().map_or(1.0, |m| m[i]) * selection.as_ref().map_or(1.0, |m| m[i]); + let mask_target = target_of(p) == Target::Mask; + if is_channel_target(p) || mask_target { + // A grayscale target gets the luminosity of a colour source (one plane). + let srcp = + if src.len() == 1 { src[0].clone() } else { (0..src[0].len()).map(|i| src.iter().map(|pl| pl[i]).sum::() / src.len() as f32).collect() }; + let (surf, _) = target_surface(doc, layer, p)?; + let base = read_plane(surf, area); + let out: Vec = base.iter().enumerate().map(|(i, &b)| b + (blending.apply(b, srcp[i]) - b) * weight(i)).collect(); + if mask_target { + // A layer mask keeps its default (reveal or hide) outside the canvas. + if surf.channels() != 1 { + return Err(EngineError::Other("the layer mask is not a grayscale surface".into())); + } + surf.write_region(area, &out); + surf.prune(); + } else { + *surf = plane_surface(&out, area, surf.format()); + } + return Ok(()); + } + let id = layer.ok_or_else(|| EngineError::Other("no active layer".into()))?; + let fmt = doc.pixel_format(); + let surf = crate::commands::paint_surface(doc, id, &Value::Null)?; + let sf = surf.format(); + if sf != fmt { + return Err(EngineError::Other("the target layer's format doesn't match the document".into())); + } + let n = sf.channels(); + let colors = sf.mode.color_channels(); + let mut v = surf.read_region(area); + for (i, px) in v.chunks_exact_mut(n).enumerate() { + let base_a = if sf.alpha { px[colors].clamp(0.0, 1.0) } else { 1.0 }; + let mut w = weight(i); + if preserve { + w *= base_a; + } + if w <= 0.0 { + continue; + } + // Painted over the layer like a brush: the blend only acts where the layer has + // pixels (where it is transparent the source shows as is), and the alpha grows by + // source-over, so applying to an empty layer copies the source in any mode. + let out_a = if preserve { base_a } else { w + base_a * (1.0 - w) }; + for (c, b) in px[..colors].iter_mut().enumerate() { + let top = src.get(c).unwrap_or(&src[0])[i]; + let blended = top + (blending.apply(*b, top) - top) * base_a; + *b = if preserve { *b + (blended - *b) * w } else { (w * blended + base_a * (1.0 - w) * *b) / out_a }; + } + if sf.alpha { + px[colors] = out_a; + } + } + surf.write_region(area, &v); + surf.prune(); + Ok(()) + })?; + Ok(Value::Null) +} + +pub(super) fn calculations(s: &mut Session, p: &Value) -> Result { + let cmd = "image.calculations"; + let blending = Blending::parse(p).map_err(|e| bad(cmd, e))?; + let opacity = p.get("opacity").and_then(Value::as_f64).unwrap_or(100.0).clamp(0.0, 100.0) as f32 / 100.0; + let s1 = source(s, &source_spec(p, "source1", "source1").unwrap_or_else(|| json!({})), cmd, true)?.remove(0); + let s2 = source(s, &source_spec(p, "source2", "source2").unwrap_or_else(|| json!({})), cmd, true)?.remove(0); + let mask = mask_plane(s, p, cmd)?; + // Source 1 is blended onto Source 2. + let out: Vec = + s2.iter().zip(&s1).enumerate().map(|(i, (&b, &t))| b + (blending.apply(b, t) - b) * opacity * mask.as_ref().map_or(1.0, |m| m[i])).collect(); + let name = p.get("name").and_then(Value::as_str).map(str::to_string); + match p.get("result").and_then(Value::as_str).unwrap_or("newChannel") { + "newChannel" => { + let i = s.edit("Calculations", |doc, _| { + let name = name.clone().unwrap_or_else(|| next_alpha_name(doc, "Alpha")); + let area = doc.bounds(); + let fmt = channel_format(doc); + doc.channels.push(AlphaChannel::new(name, plane_surface(&out, area, fmt))); + Ok(doc.channels.len() - 1) + })?; + Ok(json!({ "channel": i })) + } + "newDocument" => { + let like = s.active().ok_or(EngineError::NoDocument)?.doc.clone(); + let d = gray_document(name.as_deref().unwrap_or("Untitled"), &like, &out); + let i = s.add_document(d, None); + Ok(json!({ "document": i })) + } + "selection" => { + let selected = s.edit("Calculations", |doc, _| { + doc.selection = sel::combine(None, &out, doc.bounds(), SelectionMode::Replace); + Ok(doc.selection.is_some()) + })?; + Ok(json!({ "selected": selected })) + } + other => Err(bad(cmd, format!("unknown result `{other}` (newChannel|newDocument|selection)"))), + } +} diff --git a/crates/engine/src/cmd/channel_cmds/manage.rs b/crates/engine/src/cmd/channel_cmds/manage.rs new file mode 100644 index 0000000000..0aaa045cc7 --- /dev/null +++ b/crates/engine/src/cmd/channel_cmds/manage.rs @@ -0,0 +1,380 @@ +use super::planes::{channel_format, color_count, edit_mode, next_alpha_name, plane_surface, read_plane}; +use super::refs::{ChanRef, alpha_index, bad, doc_index, gray_plane, parse_ref}; +use super::selection::{uniform, unselected_surface}; +use super::targeting::target; +use super::view::{ChannelTarget, QuickMaskOptions, color_names, composite_name, fix_view, touch}; +use super::*; + +// --------------------------------------------------------------------------------------------- +// Channel management + +fn indicates_param(v: Option<&Value>) -> Option { + match v?.as_str()? { + "masked" | "maskedAreas" => Some(ColorIndicates::MaskedAreas), + "selected" | "selectedAreas" => Some(ColorIndicates::SelectedAreas), + _ => None, + } +} + +fn color_value(cmd: &str, p: &Value, key: &str) -> Result> { + if p.get(key).is_none() { + return Ok(None); + } + let c = crate::commands::color_param(cmd, p, key, [1.0, 0.0, 0.0, 1.0])?; + Ok(Some(Color::rgb(c[0], c[1], c[2]))) +} + +pub(super) fn new_channel(s: &mut Session, p: &Value) -> Result { + let fill = p.get("fill").and_then(Value::as_str).unwrap_or("black").to_string(); + let name = p.get("name").and_then(Value::as_str).map(str::to_string); + let indicates = indicates_param(p.get("indicates")); + let color = color_value("channel.new", p, "color")?; + let opacity = p.get("opacity").and_then(Value::as_f64).map(|v| (v as f32 / 100.0).clamp(0.0, 1.0)); + let i = s.edit("New Channel", |doc, _| { + let area = doc.bounds(); + let fmt = channel_format(doc); + let surface = match fill.as_str() { + "white" => plane_surface(&vec![1.0; area.width() as usize * area.height() as usize], area, fmt), + "selection" => plane_surface(&sel::mask_from_surface(doc.selection.as_ref(), area), area, fmt), + _ => Surface::new(fmt), + }; + let mut ch = AlphaChannel::new(name.clone().unwrap_or_else(|| next_alpha_name(doc, "Alpha")), surface); + if let Some(v) = indicates { + ch.indicates = v; + } + if let Some(c) = color { + ch.color = c; + } + if let Some(o) = opacity { + ch.opacity = o; + } + doc.channels.push(ch); + Ok(doc.channels.len() - 1) + })?; + // Photoshop targets and shows a new channel on its own. + target(s, ChannelTarget::Alpha(i)); + Ok(json!({ "channel": i })) +} + +pub(super) fn new_spot(s: &mut Session, p: &Value) -> Result { + let color = color_value("channel.newSpot", p, "color")?.unwrap_or(Color::rgb(1.0, 0.0, 0.0)); + let solidity = p.get("solidity").and_then(Value::as_f64).unwrap_or(0.0).clamp(0.0, 100.0) as f32 / 100.0; + let name = p.get("name").and_then(Value::as_str).map(str::to_string); + let from_sel = p.get("fromSelection").and_then(Value::as_bool).unwrap_or(true); + let i = s.edit("New Spot Channel", |doc, _| { + let area = doc.bounds(); + let fmt = channel_format(doc); + let surface = if from_sel && doc.selection.is_some() { + plane_surface(&sel::mask_from_surface(doc.selection.as_ref(), area), area, fmt) + } else { + Surface::new(fmt) + }; + let name = name.clone().unwrap_or_else(|| next_alpha_name(doc, "Spot Color")); + doc.channels.push(AlphaChannel { spot: Some((color, solidity)), ..AlphaChannel::new(name, surface) }); + Ok(doc.channels.len() - 1) + })?; + if let Some(st) = s.active_mut() { + st.channel_view.set_alpha_visible(i, true); + touch(st); + } + Ok(json!({ "channel": i })) +} + +pub(super) fn duplicate_channel(s: &mut Session, p: &Value) -> Result { + let cmd = "channel.duplicate"; + let src = s.active().ok_or(EngineError::NoDocument)?; + let area = src.doc.bounds(); + let r = p.get("channel").and_then(|v| parse_ref(v, &src.doc)).ok_or_else(|| bad(cmd, "missing or unknown `channel`"))?; + let mut ch = match r { + ChanRef::Alpha(i) => src.doc.channels.get(i).cloned().ok_or_else(|| bad(cmd, format!("no alpha channel {i}")))?, + ChanRef::QuickMask => src.doc.quick_mask.clone().ok_or_else(|| bad(cmd, "not in Quick Mask mode"))?, + other => { + let plane = gray_plane(&src.doc, None, src.active_layer, other)?; + AlphaChannel::new(String::new(), plane_surface(&plane, area, channel_format(&src.doc))) + } + }; + let base = match r { + ChanRef::Alpha(_) | ChanRef::QuickMask => ch.name.clone(), + ChanRef::Color(k) => color_names(edit_mode(&src.doc))[k].to_string(), + _ => composite_name(edit_mode(&src.doc)).to_string(), + }; + ch.name = p.get("name").and_then(Value::as_str).map_or_else(|| format!("{base} copy"), str::to_string); + if p.get("invert").and_then(Value::as_bool).unwrap_or(false) { + let v: Vec = read_plane(&ch.surface, area).into_iter().map(|v| 1.0 - v).collect(); + ch.surface = plane_surface(&v, area, ch.surface.format()); + } + match p.get("document") { + Some(Value::String(x)) if x == "new" => { + // Photoshop makes a multichannel document; ours is grayscale with the channel as pixels. + let doc = gray_document(&ch.name, &src.doc, &read_plane(&ch.surface, area)); + let i = s.add_document(doc, None); + Ok(json!({ "document": i })) + } + _ => { + let di = doc_index(s, p, "document")?; + if s.documents()[di].doc.size != src.doc.size { + return Err(bad(cmd, "the destination document must have the same size")); + } + let prev = s.active_index(); + s.set_active(di); + let r = s.edit("Duplicate Channel", |doc, _| { + let fmt = channel_format(doc); + if ch.surface.format() != fmt { + ch.surface = ch.surface.convert(fmt); + } + doc.channels.push(ch); + Ok(doc.channels.len() - 1) + }); + if let Some(i) = prev { + s.set_active(i); + } + Ok(json!({ "channel": r?, "document": di })) + } + } +} + +/// A one-layer grayscale document whose pixels are `plane` (Split Channels, Duplicate Channel +/// to a new document). +pub(super) fn gray_document(name: &str, like: &Document, plane: &[f32]) -> Document { + let mut d = Document::new(name, like.size, ColorMode::Grayscale, like.depth); + d.resolution_dpi = like.resolution_dpi; + let fmt = d.pixel_format(); + let mut bg = Layer::raster("Background", fmt); + bg.locks.transparency = true; + bg.locks.position = true; + if let Some(s) = bg.surface_mut() { + let data: Vec = plane.iter().flat_map(|v| [v.clamp(0.0, 1.0), 1.0]).collect(); + s.write_region(like.bounds(), &data); + s.prune(); + } + d.layers.push(bg); + d +} + +pub(super) fn delete_channel(s: &mut Session, p: &Value) -> Result { + let cmd = "channel.delete"; + let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; + let i = match p.get("channel") { + Some(_) => alpha_index(doc, p, "channel", cmd)?, + None => match s.active().ok_or(EngineError::NoDocument)?.channel_view.target { + ChannelTarget::Alpha(i) => i, + _ => return Err(bad(cmd, "missing `channel`")), + }, + }; + // `edit` validates the view against the shorter channel list before we can remap it. + // Keep the original indices and eyes so a surviving final channel is not discarded. + let view = s.active().ok_or(EngineError::NoDocument)?.channel_view.clone(); + s.edit("Delete Channel", |doc, _| { + doc.channels.remove(i); + Ok(()) + })?; + if let Some(st) = s.active_mut() { + st.channel_view = view; + let v = &mut st.channel_view; + if i < v.alpha_visible.len() { + v.alpha_visible.remove(i); + } + v.target = match v.target { + ChannelTarget::Alpha(t) if t == i => { + v.color_hidden.clear(); + ChannelTarget::Composite + } + ChannelTarget::Alpha(t) if t > i => ChannelTarget::Alpha(t - 1), + t => t, + }; + fix_view_now(st); + } + Ok(Value::Null) +} + +pub(super) fn fix_view_now(st: &mut DocState) { + fix_view(st); + touch(st); +} + +pub(super) fn rename_channel(s: &mut Session, p: &Value) -> Result { + let cmd = "channel.rename"; + let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; + let i = alpha_index(doc, p, "channel", cmd)?; + let name = p.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad(cmd, "missing `name`"))?.to_string(); + s.edit("Rename Channel", |doc, _| { + doc.channels[i].name = name; + Ok(()) + })?; + Ok(Value::Null) +} + +pub(super) fn move_channel(s: &mut Session, p: &Value) -> Result { + let cmd = "channel.move"; + let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; + let n = doc.channels.len(); + let i = alpha_index(doc, p, "channel", cmd)?; + let to = p.get("to").and_then(Value::as_u64).map(|v| (v as usize).min(n - 1)).ok_or_else(|| bad(cmd, "missing `to`"))?; + if to == i { + return Ok(json!({ "channel": i })); + } + s.edit("Channel Order", |doc, _| { + let c = doc.channels.remove(i); + doc.channels.insert(to, c); + Ok(()) + })?; + if let Some(st) = s.active_mut() { + let v = &mut st.channel_view; + v.alpha_visible.resize(n, false); + let vis = v.alpha_visible.remove(i); + v.alpha_visible.insert(to, vis); + let remap = |t: usize| { + if t == i { + to + } else if i < t && t <= to { + t - 1 + } else if to <= t && t < i { + t + 1 + } else { + t + } + }; + if let ChannelTarget::Alpha(t) = v.target { + v.target = ChannelTarget::Alpha(remap(t)); + } + touch(st); + } + Ok(json!({ "channel": to })) +} + +pub(super) fn set_visible(s: &mut Session, p: &Value) -> Result { + let cmd = "channel.setVisible"; + let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; + let r = p.get("channel").and_then(|v| parse_ref(v, doc)).ok_or_else(|| bad(cmd, "missing or unknown `channel`"))?; + let colors = color_count(doc); + let n = doc.channels.len(); + let st = s.active_mut().ok_or(EngineError::NoDocument)?; + let v = &mut st.channel_view; + let visible = |cur: bool| p.get("visible").and_then(Value::as_bool).unwrap_or(!cur); + match r { + ChanRef::Composite => { + let all = v.visible_colors(colors) == colors; + let on = visible(all); + v.color_hidden = vec![!on; colors]; + } + ChanRef::Color(k) if k < colors => { + let on = visible(v.color_visible(k)); + v.set_color_visible(k, on); + } + ChanRef::Alpha(i) if i < n => { + let on = visible(v.alpha_shown(i)); + v.set_alpha_visible(i, on); + } + ChanRef::QuickMask => v.quick_mask_hidden = !visible(!v.quick_mask_hidden), + _ => return Err(bad(cmd, "that channel has no visibility")), + } + fix_view_now(st); + Ok(list(s)) +} + +pub(super) fn options(s: &mut Session, p: &Value) -> Result { + let cmd = "channel.options"; + let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; + let r = p.get("channel").and_then(|v| parse_ref(v, doc)).ok_or_else(|| bad(cmd, "missing or unknown `channel`"))?; + let name = p.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()).map(str::to_string); + let color = color_value(cmd, p, "color")?; + let opacity = p.get("opacity").and_then(Value::as_f64).map(|v| (v as f32 / 100.0).clamp(0.0, 1.0)); + let solidity = p.get("solidity").and_then(Value::as_f64).map(|v| (v as f32 / 100.0).clamp(0.0, 1.0)); + let kind = p.get("indicates").and_then(Value::as_str).map(str::to_string); + let display_only = name.is_none() && kind.is_none() && solidity.is_none(); + let apply = move |ch: &mut AlphaChannel| -> Result<()> { + if let Some(n) = &name { + ch.name = n.clone(); + } + match kind.as_deref() { + Some("spot") => { + let (c, sol) = ch.spot.unwrap_or((ch.color, 0.0)); + ch.spot = Some((color.unwrap_or(c), solidity.unwrap_or(sol))); + return Ok(()); + } + Some(k) => { + ch.indicates = indicates_param(Some(&json!(k))).ok_or_else(|| bad(cmd, format!("unknown `indicates` {k}")))?; + ch.spot = None; + } + None => {} + } + match &mut ch.spot { + Some((c, sol)) => { + *c = color.unwrap_or(*c); + *sol = solidity.or(opacity).unwrap_or(*sol); + } + None => { + ch.color = color.unwrap_or(ch.color); + ch.opacity = opacity.unwrap_or(ch.opacity); + } + } + Ok(()) + }; + match r { + ChanRef::Alpha(i) if i < doc.channels.len() => { + s.edit("Channel Options", |doc, _| apply(&mut doc.channels[i]))?; + } + ChanRef::QuickMask => { + // Quick Mask Options persist for the session; the live Quick Mask follows them. + let mut probe = AlphaChannel { + color: s.quick_mask_options.color, + opacity: s.quick_mask_options.opacity, + indicates: s.quick_mask_options.indicates, + ..AlphaChannel::new("Quick Mask", Surface::new(PixelFormat::GRAY8)) + }; + apply(&mut probe)?; + if probe.spot.is_some() { + return Err(bad(cmd, "Quick Mask can't be a spot channel")); + } + s.quick_mask_options = QuickMaskOptions { color: probe.color, opacity: probe.opacity, indicates: probe.indicates }; + if s.active().is_some_and(|d| d.doc.quick_mask.is_some()) { + let o = s.quick_mask_options; + s.edit("Quick Mask Options", |doc, _| { + let area = doc.bounds(); + let fmt = channel_format(doc); + let unselected = doc.quick_mask_unselected; + if let Some(q) = &mut doc.quick_mask { + // An untouched no-selection mask stays colourless (nothing selected) + // when the colour switches between masked and selected areas. + if unselected && q.indicates != o.indicates { + let empty = if q.indicates == ColorIndicates::SelectedAreas { 0.0 } else { 1.0 }; + if uniform(&read_plane(&q.surface, area), empty) { + q.surface = unselected_surface(area, fmt, o.indicates); + } + } + q.color = o.color; + q.opacity = o.opacity; + q.indicates = o.indicates; + } + Ok(()) + })?; + } + } + ChanRef::LayerMask => { + // Layer Mask Display Options: only the rubylith's colour and opacity, for every mask. + if !display_only { + return Err(bad(cmd, "a layer mask's options are only `color` and `opacity`")); + } + // A preference, kept across restarts; not an undo step. + if color.is_some() || opacity.is_some() { + s.edit_prefs(|prefs| { + let o = &mut prefs.layer_mask_overlay; + if let Some(c) = color { + o.color = crate::adjust_params::hex(c.to_rgb()); + } + if let Some(a) = opacity { + o.opacity = (a * 100.0).round(); + } + }); + } + let o = serde_json::to_value(&s.prefs().layer_mask_overlay).unwrap_or(Value::Null); + let mut out = list(s); + if let Some(m) = out.as_object_mut() { + m.insert("layerMaskOverlay".into(), o); + } + return Ok(out); + } + _ => return Err(bad(cmd, "`channel` must be an alpha/spot channel, \"quickMask\" or \"mask\"")), + } + Ok(list(s)) +} diff --git a/crates/engine/src/cmd/channel_cmds/planes.rs b/crates/engine/src/cmd/channel_cmds/planes.rs new file mode 100644 index 0000000000..f434a2fa7b --- /dev/null +++ b/crates/engine/src/cmd/channel_cmds/planes.rs @@ -0,0 +1,138 @@ +use super::view::{ChannelTarget, color_names}; +use super::*; + +/// The Curves dialog's Channel popup lists only this channel when the Channels panel has a +/// single non-composite target (a colour component, layer mask, saved channel or Quick Mask). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct IsolatedCurveChannel { + /// Channels-panel name, including a custom alpha name or "{layer} Mask". + pub name: String, + /// Curves param key: empty = composite `points`; otherwise `red`/`green`/… + pub key: &'static str, + /// Index into the tone-space histograms (composite = 0 for RGB/CMYK). + pub hist: usize, + /// Colour components keep their curve tint; masks and alphas do not. + pub tint: bool, + /// Built-in labels (colour channels, Quick Mask) follow the interface language; a custom + /// alpha name or a "{layer} Mask" keeps the layer name, so it stays exactly as entered (#5335). + pub translate: bool, + /// The gray plane this target edits, whatever the document's colour mode; its surface is + /// what the dialog's histogram must describe (#5335). None for colour components. + pub gray: Option, +} + +/// A grayscale plane Curves can target: the dialog parses and previews its curves in gray levels +/// even in Lab and CMYK documents (#5335). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum GraySurface { + /// The active layer's layer mask. + LayerMask, + /// A saved channel, as an index into [`Document::channels`]. + Alpha(usize), + /// The Quick Mask. + QuickMask, + /// The active smart object's filter mask (FILE-215-3). + FilterMask, +} + +/// Isolated Curves channel for the active document, matching [`inject_target`]. +pub fn isolated_curve_channel(st: &DocState) -> Option { + isolated_curve_channel_for(st, false) +} + +/// [`isolated_curve_channel`] with the Layers panel's mask target added: clicking a mask +/// thumbnail targets it without touching the Channels panel, and both ways of selecting the mask +/// must give the same Curves dropdown (#5335). +pub fn isolated_curve_channel_for(st: &DocState, layers_panel_mask: bool) -> Option { + let doc = &st.doc; + let mode = edit_mode(doc); + match st.channel_view.target { + ChannelTarget::Color(k) => { + let names = color_names(mode); + let keys = crate::adjust_params::channel_keys(crate::adjust_params::default_space(mode)); + let name = names.get(k)?.to_string(); + let key = *keys.get(k)?; + let hist = if matches!(mode, ColorMode::Lab) { k } else { k.saturating_add(1) }; + Some(IsolatedCurveChannel { name, key, hist, tint: true, translate: true, gray: None }) + } + ChannelTarget::Alpha(i) => doc.channels.get(i).map(|c| IsolatedCurveChannel { + name: c.name.clone(), + key: "", + hist: 0, + tint: false, + translate: false, + gray: Some(GraySurface::Alpha(i)), + }), + ChannelTarget::Composite if doc.quick_mask.is_some() => { + Some(IsolatedCurveChannel { name: "Quick Mask".into(), key: "", hist: 0, tint: false, translate: true, gray: Some(GraySurface::QuickMask) }) + } + ChannelTarget::LayerMask => layer_mask_curve_channel(st), + ChannelTarget::Composite if crate::mask_view_cmds::current(st).is_some_and(|v| v.filter) => filter_mask_curve_channel(st), + ChannelTarget::Composite if crate::mask_view_cmds::current(st).is_some() || layers_panel_mask => layer_mask_curve_channel(st), + _ => None, + } +} + +fn layer_mask_curve_channel(st: &DocState) -> Option { + let layer = st.active_layer.and_then(|id| st.doc.layer(id))?; + layer.mask.as_ref()?; + let name = format!("{} Mask", layer.name); + Some(IsolatedCurveChannel { name, key: "", hist: 0, tint: false, translate: false, gray: Some(GraySurface::LayerMask) }) +} + +/// The Curves target when the active smart object's filter mask is targeted (its thumbnail on the +/// Smart Filters row, FILE-215-3): a gray plane, though the mask may not exist until the first edit. +pub fn filter_mask_curve_channel(st: &DocState) -> Option { + let layer = st.active_layer.and_then(|id| st.doc.layer(id))?; + crate::smart_cmds::filter_mask_paintable(layer).ok()?; + let name = format!("{} Filter Mask", layer.name); + Some(IsolatedCurveChannel { name, key: "", hist: 0, tint: false, translate: false, gray: Some(GraySurface::FilterMask) }) +} + +pub(super) fn edit_mode(doc: &Document) -> ColorMode { + doc.pixel_format().mode +} + +pub fn color_count(doc: &Document) -> usize { + edit_mode(doc).color_channels() +} + +/// Pixel format of alpha channels: grayscale at the document depth, no transparency. +pub fn channel_format(doc: &Document) -> PixelFormat { + PixelFormat::new(ColorMode::Grayscale, doc.depth, false) +} + +/// Next free "`base` N" name (Alpha 1, Spot Color 2, …). +pub fn next_alpha_name(doc: &Document, base: &str) -> String { + // `channels.len() + 1` candidates always include a free one. + (1..=doc.channels.len() + 1).map(|n| format!("{base} {n}")).find(|n| !doc.channels.iter().any(|c| &c.name == n)).unwrap_or_else(|| base.to_string()) +} + +// --------------------------------------------------------------------------------------------- +// Planes: one grayscale value per canvas pixel + +pub(super) fn read_plane(s: &Surface, r: Rect) -> Vec { + let mut v = Vec::new(); + s.read_region_into(r, &mut v); + let ch = s.channels(); + if ch > 1 { v.chunks_exact(ch).map(|p| p[0]).collect() } else { v } +} + +pub(super) fn plane_surface(vals: &[f32], r: Rect, fmt: PixelFormat) -> Surface { + let mut s = Surface::new(fmt); + let clamped: Vec = vals.iter().map(|v| v.clamp(0.0, 1.0)).collect(); + s.write_region(r, &clamped); + s.prune(); + s +} + +/// Make every canvas pixel of `s` explicit so filters and adjustments that work on the content +/// bounds also see the untouched (default-valued) parts of a channel. +pub(super) fn materialize(s: &mut Surface, r: Rect) { + let v = s.read_region(r); + s.write_region(r, &v); +} + +pub(super) fn luminosity(rgba: [f32; 4]) -> f32 { + 0.299 * rgba[0] + 0.587 * rgba[1] + 0.114 * rgba[2] +} diff --git a/crates/engine/src/cmd/channel_cmds/refs.rs b/crates/engine/src/cmd/channel_cmds/refs.rs new file mode 100644 index 0000000000..876fa0b49b --- /dev/null +++ b/crates/engine/src/cmd/channel_cmds/refs.rs @@ -0,0 +1,291 @@ +use super::planes::{color_count, edit_mode, luminosity, read_plane}; +use super::view::{color_names, composite_name}; +use super::*; + +// --------------------------------------------------------------------------------------------- +// Channel references + +/// A channel named in params: `"composite"`, a colour name (`"red"`, `"cyan"`, `"lightness"`…), +/// an alpha index (number) or name, `"quickMask"`, `"selection"`, `"transparency"`, `"mask"`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ChanRef { + Composite, + Color(usize), + Alpha(usize), + QuickMask, + Selection, + Transparency, + LayerMask, + /// The layer's vector mask, rasterized (⌘-click its thumbnail, #196). + VectorMask, +} + +pub fn parse_ref(v: &Value, doc: &Document) -> Option { + let mode = edit_mode(doc); + match v { + Value::Number(n) => n.as_u64().map(|i| ChanRef::Alpha(i as usize)), + Value::Object(o) => { + if let Some(k) = o.get("color").and_then(Value::as_u64) { + Some(ChanRef::Color(k as usize)) + } else { + o.get("alpha").and_then(Value::as_u64).map(|i| ChanRef::Alpha(i as usize)) + } + } + Value::String(s) => { + let l = s.to_ascii_lowercase(); + match l.as_str() { + "composite" | "merged" => return Some(ChanRef::Composite), + "quickmask" | "quick mask" => return Some(ChanRef::QuickMask), + "selection" => return Some(ChanRef::Selection), + "transparency" => return Some(ChanRef::Transparency), + "mask" | "layermask" => return Some(ChanRef::LayerMask), + "vectormask" | "vector mask" => return Some(ChanRef::VectorMask), + _ => {} + } + if l == composite_name(mode).to_ascii_lowercase() { + return Some(ChanRef::Composite); + } + if let Some(k) = color_names(mode).iter().position(|n| n.eq_ignore_ascii_case(&l)) { + return Some(if color_names(mode).len() == 1 { ChanRef::Composite } else { ChanRef::Color(k) }); + } + doc.channels.iter().position(|c| c.name == *s).map(ChanRef::Alpha) + } + _ => None, + } +} + +pub(super) fn bad(cmd: &str, msg: impl Into) -> EngineError { + EngineError::BadParams { cmd: cmd.into(), msg: msg.into() } +} + +pub(super) fn doc_index(s: &Session, p: &Value, key: &str) -> Result { + match crate::commands::int(p, key).and_then(|v| u64::try_from(v).ok()) { + Some(i) if (i as usize) < s.documents().len() => Ok(i as usize), + Some(i) => Err(EngineError::Other(format!("no open document {i}"))), + None => s.active_index().ok_or(EngineError::NoDocument), + } +} + +/// Alpha channel index from `p[key]` (number or name), checked against the document. +pub(super) fn alpha_index(doc: &Document, p: &Value, key: &str, cmd: &str) -> Result { + match p.get(key).and_then(|v| parse_ref(v, doc)) { + Some(ChanRef::Alpha(i)) if i < doc.channels.len() => Ok(i), + Some(ChanRef::Alpha(i)) => Err(bad(cmd, format!("no alpha channel {i} (document has {})", doc.channels.len()))), + _ => Err(bad(cmd, format!("`{key}` must name an alpha channel (index or name)"))), + } +} + +// --------------------------------------------------------------------------------------------- +// Sources (Load Selection, Apply Image, Calculations) + +/// Native pixel values of a layer or of the merged image over the canvas. +pub(super) fn native_pixels(doc: &Document, layer: Option) -> Result<(Vec, usize)> { + let r = doc.bounds(); + let fmt = doc.pixel_format(); + let n = fmt.channels(); + match layer { + Some(id) => { + let l = doc.layer(id).ok_or(EngineError::NoLayer(id))?; + let s = l.surface().ok_or_else(|| EngineError::Other(format!("layer \"{}\" has no pixels", l.name)))?; + if s.format() == fmt { + return Ok((s.read_region(r), n)); + } + let raw = s.read_region(r); + let sf = s.format(); + Ok((raw.chunks_exact(sf.channels()).flat_map(|p| from_rgba(&fmt, to_rgba(&sf, p))).collect(), n)) + } + None => { + let buf = photocraft_compose::render(doc, r); + Ok((buf.px.iter().flat_map(|p| from_rgba(&fmt, *p)).collect(), n)) + } + } +} + +/// `"layer"` param of a source: a layer id, a layer name (the topmost of that name, as a loaded +/// Photoshop action refers to it), or `"merged"` (default). An unknown name is an error. +fn source_layer(doc: &Document, p: &Value, cmd: &str) -> Result> { + match p.get("layer") { + Some(Value::Number(n)) => Ok(n.as_u64().map(LayerId)), + Some(Value::String(name)) if !name.is_empty() && name != "merged" => doc + .walk() + .into_iter() + .rev() + .find(|(_, _, l)| l.name == *name) + .map(|(_, _, l)| Some(l.id)) + .ok_or_else(|| bad(cmd, format!("no source layer named \"{name}\""))), + _ => Ok(None), + } +} + +/// Planes of channel `r` from document `doc` (`layer` = None: merged). A composite gives one +/// plane per colour channel; everything else gives one plane. +fn ref_planes(doc: &Document, layer: Option, active: Option, r: ChanRef) -> Result>> { + let area = doc.bounds(); + let colors = color_count(doc); + Ok(match r { + ChanRef::Composite | ChanRef::Color(_) => { + let (px, n) = native_pixels(doc, layer)?; + let planes: Vec> = (0..colors).map(|c| px.chunks_exact(n).map(|p| p[c]).collect()).collect(); + match r { + ChanRef::Color(k) => vec![planes.get(k).cloned().ok_or_else(|| EngineError::Other(format!("no colour channel {k}")))?], + _ => planes, + } + } + ChanRef::Alpha(i) => vec![read_plane(&doc.channels.get(i).ok_or_else(|| EngineError::Other(format!("no alpha channel {i}")))?.surface, area)], + ChanRef::QuickMask => vec![read_plane(&doc.quick_mask.as_ref().ok_or_else(|| EngineError::Other("not in Quick Mask mode".into()))?.surface, area)], + ChanRef::Selection => vec![sel::mask_from_surface(doc.selection.as_ref(), area)], + ChanRef::Transparency => { + let id = layer.or(active).ok_or_else(|| EngineError::Other("transparency needs a layer".into()))?; + let l = doc.layer(id).ok_or(EngineError::NoLayer(id))?; + match l.surface() { + Some(s) => { + let mut px = vec![[0.0f32; 4]; area.width() as usize * area.height() as usize]; + s.read_rgba_into(area, &mut px); + vec![px.iter().map(|p| p[3]).collect()] + } + // A shape can have no pixel cache yet (for example after loading a document). + // Use its existing renderer rather than treating it as a canvas-wide fill. + None => match &l.content { + LayerContent::Shape(shape) => vec![ + photocraft_vector::CompiledShape::new(shape, photocraft_vector::DEFAULT_TOLERANCE, area) + .render_rgba(area) + .into_iter() + .map(|p| p[3]) + .collect(), + ], + // Adjustment and fill layers cover the whole canvas. + _ => vec![vec![1.0; area.width() as usize * area.height() as usize]], + }, + } + } + ChanRef::LayerMask => { + let id = layer.or(active).ok_or_else(|| EngineError::Other("layer mask needs a layer".into()))?; + let l = doc.layer(id).ok_or(EngineError::NoLayer(id))?; + let m = l.mask.as_ref().ok_or_else(|| EngineError::Other(format!("layer \"{}\" has no mask", l.name)))?; + vec![read_plane(&m.surface, area)] + } + ChanRef::VectorMask => { + let id = layer.or(active).ok_or_else(|| EngineError::Other("vector mask needs a layer".into()))?; + let l = doc.layer(id).ok_or(EngineError::NoLayer(id))?; + let m = l.vector_mask.as_ref().ok_or_else(|| EngineError::Other(format!("layer \"{}\" has no vector mask", l.name)))?; + // The path's shape, whether or not the mask is enabled (as Photoshop loads it). + let shape = photocraft_doc::VectorMask { enabled: true, density: 1.0, feather: 0.0, ..m.clone() }; + vec![photocraft_vector::vector_mask_values(&shape, area)] + } + }) +} + +/// One grayscale plane (composites reduce to luminosity, as in Calculations). +pub(super) fn gray_plane(doc: &Document, layer: Option, active: Option, r: ChanRef) -> Result> { + let mut planes = ref_planes(doc, layer, active, r)?; + if planes.len() == 1 + && let Some(only) = planes.pop() + { + return Ok(only); + } + let fmt = doc.pixel_format(); + let n = planes.first().map_or(0, Vec::len); + let mut px = vec![0.0f32; fmt.channels()]; + Ok((0..n) + .map(|i| { + for (c, p) in planes.iter().enumerate() { + px[c] = p[i]; + } + if fmt.alpha { + px[planes.len()] = 1.0; + } + luminosity(to_rgba(&fmt, &px)) + }) + .collect()) +} + +/// A source spec `{document?, layer?, channel, invert?}`, reduced to planes over the canvas of +/// the active document (sizes must match, as in Photoshop). +pub(super) fn source(s: &Session, p: &Value, cmd: &str, gray: bool) -> Result>> { + let di = doc_index(s, p, "document")?; + let st = &s.documents()[di]; + let target = s.active().ok_or(EngineError::NoDocument)?; + if st.doc.size != target.doc.size { + return Err(bad(cmd, format!("source document \"{}\" is {}×{}; it must match the target size", st.doc.name, st.doc.size.width, st.doc.size.height))); + } + let r = p.get("channel").map_or(Some(ChanRef::Composite), |v| parse_ref(v, &st.doc)).ok_or_else(|| bad(cmd, "unknown `channel`"))?; + let layer = source_layer(&st.doc, p, cmd)?; + let mut planes = if gray { vec![gray_plane(&st.doc, layer, st.active_layer, r)?] } else { ref_planes(&st.doc, layer, st.active_layer, r)? }; + // Guard every caller (`.remove(0)` / `src[0]`) against an empty source. + if planes.is_empty() { + return Err(bad(cmd, "the source has no channels")); + } + if p.get("invert").and_then(Value::as_bool).unwrap_or(false) { + for pl in &mut planes { + for v in pl.iter_mut() { + *v = 1.0 - *v; + } + } + } + Ok(planes) +} + +// --------------------------------------------------------------------------------------------- +// Blending (Apply Image / Calculations) + +/// Apply Image / Calculations blending: the separable layer modes plus Add and Subtract with +/// scale and offset. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Blending { + Mode(BlendMode), + Add { scale: f32, offset: f32 }, + Subtract { scale: f32, offset: f32 }, +} + +impl Blending { + pub fn parse(p: &Value) -> std::result::Result { + let name = p.get("blending").and_then(Value::as_str).unwrap_or("multiply"); + let scale = p.get("scale").and_then(Value::as_f64).unwrap_or(1.0).clamp(1.0, 2.0) as f32; + let offset = p.get("offset").and_then(Value::as_f64).unwrap_or(0.0).clamp(-255.0, 255.0) as f32 / 255.0; + match name.to_ascii_lowercase().as_str() { + "add" => Ok(Blending::Add { scale, offset }), + "subtract" => Ok(Blending::Subtract { scale, offset }), + other => match crate::commands::blend_from_str(other) { + Some(m) if m.is_separable() && !matches!(m, BlendMode::Dissolve | BlendMode::PassThrough) => Ok(Blending::Mode(m)), + _ => Err(format!("unsupported blending `{other}`")), + }, + } + } + + /// Blend `top` (the source) onto `base` (the target). + pub fn apply(self, base: f32, top: f32) -> f32 { + match self { + Blending::Mode(m) => blend_channel(m, base, top), + Blending::Add { scale, offset } => (base + top) / scale + offset, + Blending::Subtract { scale, offset } => (base - top) / scale + offset, + } + .clamp(0.0, 1.0) + } +} + +/// A source spec from `p[key]`, or from flat `Document` / `Layer` / +/// `Channel` / `Invert` keys (what the generic dialog form sends). +pub(crate) fn source_spec(p: &Value, key: &str, prefix: &str) -> Option { + if let Some(v) = p.get(key) { + return Some(v.clone()); + } + let mut m = serde_json::Map::new(); + for (k, field) in [("document", "Document"), ("layer", "Layer"), ("channel", "Channel"), ("invert", "Invert")] { + match p.get(format!("{prefix}{field}")) { + None | Some(Value::Null) => {} + Some(Value::String(s)) if s.is_empty() || (k == "layer" && s == "merged") => {} + Some(v) => { + m.insert(k.into(), v.clone()); + } + } + } + (!m.is_empty()).then_some(Value::Object(m)) +} + +pub(super) fn mask_plane(s: &Session, p: &Value, cmd: &str) -> Result>> { + match source_spec(p, "mask", "mask") { + None | Some(Value::Null) | Some(Value::Bool(false)) => Ok(None), + Some(m) if m.get("channel").is_none_or(|c| c == "none") => Ok(None), + Some(m) => Ok(Some(source(s, &m, cmd, true)?.remove(0))), + } +} diff --git a/crates/engine/src/cmd/channel_cmds/selection.rs b/crates/engine/src/cmd/channel_cmds/selection.rs new file mode 100644 index 0000000000..9a24b9fe56 --- /dev/null +++ b/crates/engine/src/cmd/channel_cmds/selection.rs @@ -0,0 +1,173 @@ +use super::planes::{channel_format, next_alpha_name, plane_surface, read_plane}; +use super::refs::{ChanRef, bad, doc_index, parse_ref, source}; +use super::view::{ChannelTarget, QuickMaskOptions}; +use super::*; + +pub(super) fn save_selection(s: &mut Session, p: &Value) -> Result { + let cmd = "select.saveSelection"; + let op = p.get("operation").and_then(Value::as_str).unwrap_or("new").to_string(); + if !matches!(op.as_str(), "new" | "replace" | "add" | "subtract" | "intersect") { + return Err(bad(cmd, format!("unknown operation `{op}`"))); + } + let di = doc_index(s, p, "document")?; + let src = s.active().ok_or(EngineError::NoDocument)?; + let area = src.doc.bounds(); + let selection = sel::mask_from_surface(src.doc.selection.as_ref(), area); + if s.documents()[di].doc.size != src.doc.size { + return Err(bad(cmd, "the destination document must have the same size")); + } + let channel = p.get("channel").cloned().unwrap_or(Value::Null); + let name = p.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()).map(str::to_string); + let prev = s.active_index(); + s.set_active(di); + let r = s.edit("Save Selection", |doc, _| { + let fmt = channel_format(doc); + let existing = match &channel { + Value::Null => None, + Value::String(x) if x == "new" => None, + v => match parse_ref(v, doc) { + Some(ChanRef::Alpha(i)) if i < doc.channels.len() => Some(i), + _ => return Err(bad(cmd, "`channel` must be \"new\" or an existing alpha channel")), + }, + }; + match (existing, op.as_str()) { + (None, _) | (_, "new") => { + let name = name.clone().unwrap_or_else(|| next_alpha_name(doc, "Alpha")); + doc.channels.push(AlphaChannel::new(name, plane_surface(&selection, area, fmt))); + Ok(doc.channels.len() - 1) + } + (Some(i), op) => { + let old = read_plane(&doc.channels[i].surface, area); + let vals: Vec = match op { + "add" => old.iter().zip(&selection).map(|(a, b)| a.max(*b)).collect(), + "subtract" => old.iter().zip(&selection).map(|(a, b)| (a - b).max(0.0)).collect(), + "intersect" => old.iter().zip(&selection).map(|(a, b)| a.min(*b)).collect(), + _ => selection.clone(), + }; + doc.channels[i].surface = plane_surface(&vals, area, fmt); + if let Some(n) = &name { + doc.channels[i].name = n.clone(); + } + Ok(i) + } + } + }); + if let Some(i) = prev { + s.set_active(i); + } + let i = r?; + let name = s.documents()[di].doc.channels[i].name.clone(); + Ok(json!({ "channel": i, "name": name, "document": di })) +} + +pub(super) fn load_selection(s: &mut Session, p: &Value) -> Result { + let cmd = "select.loadSelection"; + let mode = match operation(p, "operation") { + "new" | "replace" => SelectionMode::Replace, + "add" => SelectionMode::Add, + "subtract" => SelectionMode::Subtract, + "intersect" => SelectionMode::Intersect, + other => return Err(bad(cmd, format!("unknown operation `{other}`"))), + }; + if p.get("channel").is_none() { + return Err(bad(cmd, "missing `channel`")); + } + // `"targeted"`: the Channels panel's target, as a Photoshop action's "load the target + // channel" step records it. + let mut targeted = p.clone(); + if p.get("channel").and_then(Value::as_str) == Some("targeted") { + let st = s.active().ok_or(EngineError::NoDocument)?; + targeted["channel"] = match st.channel_view.target { + ChannelTarget::Composite => json!("composite"), + ChannelTarget::Color(k) => json!({ "color": k }), + ChannelTarget::Alpha(i) => json!(i), + ChannelTarget::LayerMask => json!("mask"), + ChannelTarget::VectorMask => json!("vectorMask"), + }; + } + let p = &targeted; + // Composite and colour channels load their luminosity / values, as ⌘-clicking them does. + let plane = source(s, p, cmd, true)?.into_iter().next().ok_or_else(|| bad(cmd, "the channel has no pixels"))?; + let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; + let label = match p.get("channel").and_then(|v| parse_ref(v, doc)) { + Some(ChanRef::Transparency) => "Load Transparency", + Some(ChanRef::LayerMask) => "Load Layer Mask", + _ => "Load Selection", + }; + let selected = s.edit(label, |doc, _| { + doc.selection = sel::combine(doc.selection.as_ref(), &plane, doc.bounds(), mode); + Ok(doc.selection.is_some()) + })?; + Ok(json!({ "selected": selected })) +} + +// --------------------------------------------------------------------------------------------- +// Quick Mask + +/// Quick Mask channel for the current selection: white where selected. No selection is an empty +/// mask that shows no colour: white (nothing masked, as in Photoshop) when the colour indicates +/// masked areas, black (nothing selected) when it indicates selected areas. White and "no +/// selection" are told apart by [`Document::quick_mask_unselected`]. +fn quick_mask_from(doc: &Document, o: &QuickMaskOptions) -> AlphaChannel { + let area = doc.bounds(); + let fmt = channel_format(doc); + let surface = match &doc.selection { + Some(s) => plane_surface(&sel::mask_from_surface(Some(s), area), area, fmt), + None => unselected_surface(area, fmt, o.indicates), + }; + AlphaChannel { color: o.color, opacity: o.opacity, indicates: o.indicates, ..AlphaChannel::new("Quick Mask", surface) } +} + +/// The colourless, nothing-selected Quick Mask for `indicates`. +pub(super) fn unselected_surface(area: Rect, fmt: PixelFormat, indicates: ColorIndicates) -> Surface { + let mut s = Surface::new(fmt); + if indicates != ColorIndicates::SelectedAreas { + s.fill_rect(area, &[1.0]); + } + s +} + +/// Every pixel of `vals` reads as `target` on the 8-bit grid. +pub(super) fn uniform(vals: &[f32], target: f32) -> bool { + vals.iter().all(|v| (v - target).abs() <= 0.5 / 255.0) +} + +/// The selection a Quick Mask channel turns back into. All white is Select All, unless Quick +/// Mask was entered with no selection and the white is its untouched masked-areas start. +fn selection_from(doc: &Document, ch: &AlphaChannel) -> Option { + let area = doc.bounds(); + let vals = read_plane(&ch.surface, area); + if doc.quick_mask_unselected && ch.indicates != ColorIndicates::SelectedAreas && uniform(&vals, 1.0) { + return None; + } + sel::combine(None, &vals, area, SelectionMode::Replace) +} + +pub(super) fn quick_mask(s: &mut Session, p: &Value) -> Result { + let on = s.active().ok_or(EngineError::NoDocument)?.doc.quick_mask.is_some(); + let want = p.get("on").and_then(Value::as_bool).unwrap_or(!on); + if want == on { + return Ok(json!({ "quickMask": on })); + } + let opts = s.quick_mask_options; + if want { + s.edit("Edit in Quick Mask", |doc, _| { + doc.quick_mask = Some(quick_mask_from(doc, &opts)); + doc.quick_mask_unselected = doc.selection.is_none(); + doc.selection = None; + Ok(()) + })?; + if let Some(st) = s.active_mut() { + st.channel_view.target = ChannelTarget::Composite; + st.channel_view.quick_mask_hidden = false; + } + } else { + s.edit("Exit Quick Mask", |doc, _| { + if let Some(q) = doc.quick_mask.take() { + doc.selection = selection_from(doc, &q); + } + Ok(()) + })?; + } + Ok(json!({ "quickMask": want })) +} diff --git a/crates/engine/src/cmd/channel_cmds/spot.rs b/crates/engine/src/cmd/channel_cmds/spot.rs new file mode 100644 index 0000000000..a3fefee98a --- /dev/null +++ b/crates/engine/src/cmd/channel_cmds/spot.rs @@ -0,0 +1,160 @@ +use super::manage::{fix_view_now, gray_document}; +use super::planes::{channel_format, edit_mode, plane_surface, read_plane}; +use super::refs::{ChanRef, alpha_index, bad, gray_plane, native_pixels}; +use super::view::{ChannelTarget, ChannelView, color_names}; +use super::*; + +/// Merge Spot Channel: flattens the image and prints the spot ink into the colour channels. +pub(super) fn merge_spot(s: &mut Session, p: &Value) -> Result { + let cmd = "channel.mergeSpot"; + let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; + let i = match p.get("channel") { + Some(_) => alpha_index(doc, p, "channel", cmd)?, + None => match s.active().ok_or(EngineError::NoDocument)?.channel_view.target { + ChannelTarget::Alpha(i) => i, + _ => doc.channels.iter().position(|c| c.spot.is_some()).ok_or_else(|| bad(cmd, "no spot channel"))?, + }, + }; + let (ink, solidity) = doc.channels[i].spot.ok_or_else(|| bad(cmd, "not a spot channel"))?; + s.edit("Merge Spot Channel", |doc, active| { + let area = doc.bounds(); + let fmt = doc.pixel_format(); + let comp = photocraft_compose::render(doc, area); + let k = read_plane(&doc.channels[i].surface, area); + let ink = ink.to_rgb(); + // Ink over the image: opaque at 100% solidity, multiplied (transparent ink) at 0%. + let data: Vec = comp + .px + .iter() + .zip(&k) + .flat_map(|(c, &v)| { + let rgb: [f32; 3] = std::array::from_fn(|j| { + let over = solidity * ink[j] + (1.0 - solidity) * c[j] * ink[j]; + c[j] + (over - c[j]) * v.clamp(0.0, 1.0) + }); + from_rgba(&fmt, [rgb[0], rgb[1], rgb[2], 1.0]) + }) + .collect(); + let mut bg = Layer::raster("Background", fmt); + bg.locks.transparency = true; + bg.locks.position = true; + if let Some(sf) = bg.surface_mut() { + sf.write_region(area, &data); + sf.prune(); + } + let id = bg.id; + doc.layers = vec![bg]; + doc.channels.remove(i); + *active = Some(id); + Ok(()) + })?; + if let Some(st) = s.active_mut() { + st.channel_view = ChannelView::default(); + fix_view_now(st); + } + Ok(Value::Null) +} + +/// Split Channels: one grayscale document per colour and alpha channel; closes the original. +pub(super) fn split(s: &mut Session, p: &Value) -> Result { + let idx = s.active_index().ok_or(EngineError::NoDocument)?; + let doc = s.documents()[idx].doc.clone(); + let area = doc.bounds(); + let (px, n) = native_pixels(&doc, None)?; + let mode = edit_mode(&doc); + let names = color_names(mode); + let short = |name: &str| name.chars().next().map(|c| c.to_ascii_uppercase().to_string()).unwrap_or_default(); + let mut docs: Vec = Vec::new(); + for (c, name) in names.iter().enumerate() { + let plane: Vec = px.chunks_exact(n).map(|p| p[c]).collect(); + docs.push(gray_document(&format!("{}_{}", doc.name, short(name)), &doc, &plane)); + } + for ch in &doc.channels { + docs.push(gray_document(&format!("{}_{}", doc.name, ch.name), &doc, &read_plane(&ch.surface, area))); + } + if p.get("closeOriginal").and_then(Value::as_bool).unwrap_or(true) { + s.close(idx); + } + let made: Vec = docs.into_iter().map(|d| s.add_document(d, None)).collect(); + Ok(json!({ "documents": made })) +} + +/// Open grayscale documents with the active document's size, active first. +pub(super) fn mergeable(s: &Session) -> Vec { + let Some(a) = s.active() else { return Vec::new() }; + let ok = |d: &DocState| d.doc.mode == ColorMode::Grayscale && d.doc.size == a.doc.size; + let mut v: Vec = s.active_index().into_iter().filter(|_| ok(a)).collect(); + v.extend(s.documents().iter().enumerate().filter(|(i, d)| Some(*i) != s.active_index() && ok(d)).map(|(i, _)| i)); + v +} + +/// Merge Channels: grayscale documents of one size become the channels of an RGB, CMYK or Lab +/// document (extra documents become alpha channels); the sources close. +pub(super) fn merge(s: &mut Session, p: &Value) -> Result { + let cmd = "channel.merge"; + let mode = match p.get("mode").and_then(Value::as_str).unwrap_or("rgb") { + "rgb" => ColorMode::Rgb, + "cmyk" => ColorMode::Cmyk, + "lab" => ColorMode::Lab, + other => return Err(bad(cmd, format!("unknown mode `{other}`"))), + }; + let srcs: Vec = match p.get("documents").and_then(Value::as_array) { + Some(a) => a + .iter() + .map(|v| v.as_u64().map(|i| i as usize).filter(|i| *i < s.documents().len()).ok_or_else(|| bad(cmd, "bad document index"))) + .collect::>()?, + None => mergeable(s).into_iter().take(mode.color_channels()).collect(), + }; + if srcs.len() < mode.color_channels() { + return Err(bad(cmd, format!("{mode:?} needs {} grayscale documents, got {}", mode.color_channels(), srcs.len()))); + } + // Each source closes by its *current* index, so a repeated index would shift the later + // removals onto a document that was never named (#934). Refuse it rather than guess. + let mut seen = std::collections::HashSet::new(); + if let Some(dup) = srcs.iter().find(|i| !seen.insert(**i)) { + return Err(bad(cmd, format!("document {dup} is listed more than once"))); + } + let Some(first) = srcs.first().and_then(|&i| s.documents().get(i)).map(|d| d.doc.clone()) else { + return Err(bad(cmd, "bad document index")); + }; + let mut planes = Vec::new(); + for &i in &srcs { + let d = &s.documents()[i].doc; + if d.size != first.size || d.mode != ColorMode::Grayscale { + return Err(bad(cmd, format!("\"{}\" is not a grayscale document of the same size", d.name))); + } + planes.push(gray_plane(d, None, None, ChanRef::Composite)?); + } + let mut out = Document::new(p.get("name").and_then(Value::as_str).unwrap_or("Untitled"), first.size, mode, first.depth); + out.resolution_dpi = first.resolution_dpi; + let fmt = out.pixel_format(); + let cc = mode.color_channels(); + let npx = planes[0].len(); + let mut data = Vec::with_capacity(npx * fmt.channels()); + for i in 0..npx { + for pl in &planes[..cc] { + data.push(pl[i].clamp(0.0, 1.0)); + } + data.push(1.0); + } + let mut bg = Layer::raster("Background", fmt); + bg.locks.transparency = true; + bg.locks.position = true; + if let Some(sf) = bg.surface_mut() { + sf.write_region(out.bounds(), &data); + sf.prune(); + } + out.layers.push(bg); + let area = out.bounds(); + let cf = channel_format(&out); + for (k, pl) in planes[cc..].iter().enumerate() { + out.channels.push(AlphaChannel::new(format!("Alpha {}", k + 1), plane_surface(pl, area, cf))); + } + let mut close: Vec = srcs.clone(); + close.sort_unstable(); + for i in close.into_iter().rev() { + s.close(i); + } + let i = s.add_document(out, None); + Ok(json!({ "document": i })) +} diff --git a/crates/engine/src/cmd/channel_cmds/targeting.rs b/crates/engine/src/cmd/channel_cmds/targeting.rs new file mode 100644 index 0000000000..ce131cd43a --- /dev/null +++ b/crates/engine/src/cmd/channel_cmds/targeting.rs @@ -0,0 +1,431 @@ +use super::manage::fix_view_now; +use super::planes::{color_count, materialize}; +use super::refs::{ChanRef, bad, parse_ref}; +use super::view::ChannelTarget; +use super::*; + +// --------------------------------------------------------------------------------------------- +// Targets for pixel commands + +/// Where a pixel command writes, from its `"target"` param. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Target { + Pixels, + Mask, + /// A smart object's filter mask (`"target":"filterMask"`): where it is black the smart + /// filters don't show (FILE-215-3). + FilterMask, + Alpha(usize), + QuickMask, +} + +pub(crate) fn target_of(p: &Value) -> Target { + match p.get("target") { + Some(Value::String(s)) => match s.as_str() { + "mask" => Target::Mask, + "filterMask" => Target::FilterMask, + "quickMask" => Target::QuickMask, + _ => Target::Pixels, + }, + Some(Value::Object(o)) => o.get("channel").and_then(Value::as_u64).map_or(Target::Pixels, |i| Target::Alpha(i as usize)), + _ => Target::Pixels, + } +} + +/// The target is an alpha channel or the Quick Mask (no layer involved). +pub(crate) fn is_channel_target(p: &Value) -> bool { + matches!(target_of(p), Target::Alpha(_) | Target::QuickMask) +} + +/// The surface a pixel command writes to and whether the layer's transparency is locked. +pub(crate) fn target_surface<'a>(doc: &'a mut Document, layer: Option, p: &Value) -> Result<(&'a mut Surface, bool)> { + match target_of(p) { + Target::Alpha(i) => { + let n = doc.channels.len(); + doc.channels.get_mut(i).map(|c| (&mut c.surface, false)).ok_or_else(|| EngineError::Other(format!("no alpha channel {i} (document has {n})"))) + } + Target::QuickMask => doc.quick_mask.as_mut().map(|c| (&mut c.surface, false)).ok_or_else(|| EngineError::Other("not in Quick Mask mode".into())), + t => { + let id = layer.ok_or_else(|| EngineError::Other("no active layer".into()))?; + let lock = doc.effective_locks(id).transparency && t == Target::Pixels; + Ok((crate::commands::paint_surface(doc, id, p)?, lock)) + } + } +} + +pub(crate) fn read_target_surface<'a>(doc: &'a Document, layer: Option, p: &Value) -> Result<&'a Surface> { + match target_of(p) { + Target::Alpha(i) => { + let n = doc.channels.len(); + doc.channels.get(i).map(|c| &c.surface).ok_or_else(|| EngineError::Other(format!("no alpha channel {i} (document has {n})"))) + } + Target::QuickMask => doc.quick_mask.as_ref().map(|c| &c.surface).ok_or_else(|| EngineError::Other("not in Quick Mask mode".into())), + Target::Pixels => { + let id = layer.ok_or_else(|| EngineError::Other("no active layer".into()))?; + doc.layer(id).and_then(Layer::surface).ok_or(EngineError::NoLayer(id)) + } + Target::Mask => { + let id = layer.ok_or_else(|| EngineError::Other("no active layer".into()))?; + doc.layer(id).and_then(|l| l.mask.as_ref()).map(|m| &m.surface).ok_or(EngineError::NoLayer(id)) + } + Target::FilterMask => { + let id = layer.ok_or_else(|| EngineError::Other("no active layer".into()))?; + doc.layer(id) + .and_then(|l| crate::mask_view_cmds::viewed_mask(l, true)) + .map(|m| &m.surface) + .ok_or_else(|| EngineError::Other("the layer has no filter mask".into())) + } + } +} + +/// The grayscale surface filters and adjustments edit instead of the layer's pixels (made explicit +/// over the canvas), if the params target one: an alpha channel, the Quick Mask, or the mask of +/// `layer`. +pub(crate) fn channel_surface_for_filter<'a>(doc: &'a mut Document, layer: Option, p: &Value) -> Result> { + if target_of(p) == Target::Pixels { + return Ok(None); + } + let b = doc.bounds(); + let (surf, _) = target_surface(doc, layer, p)?; + materialize(surf, b); + Ok(Some(surf)) +} + +/// Commands that edit a targeted layer mask in place of the layer: the Image › Adjustments table, +/// the filters and the fills (Edit › Fill and its keys). A mask target enables them on any layer +/// with a mask, so ⌘I inverts an adjustment layer's mask (#780) and Fill fills it (#2456) as in +/// Photoshop. +fn edits_mask(id: &str) -> bool { + id.strip_prefix("image.adjustments.").is_some_and(|kind| crate::adjust_params::default_for(kind, ColorMode::Rgb).is_ok()) + || crate::filters::params_for(id, &Value::Null).is_some() + || id == "edit.fill" + // Copying a targeted mask (#2928). + || id == "edit.copy" + || crate::fill_key_cmds::IDS.contains(&id) +} + +/// The precondition of `id` when `p` targets the active layer's mask (`"target":"mask"`): the +/// layer needs a mask. None when another precondition applies. +pub(crate) fn mask_target_enabled(s: &Session, id: &str, p: &Value) -> Option> { + match target_of(p) { + // The commands that paint, fill, filter or adjust the filter mask need a smart object with + // smart filters, not a pixel layer. Paste keeps its own check (something to paste). + Target::FilterMask if follows_filter_mask(id) && !PASTE_IDS.contains(&id) => { + Some(crate::active_layer_of(s).and_then(crate::smart_cmds::filter_mask_paintable)) + } + Target::Mask if edits_mask(id) => { + Some(crate::active_layer_of(s).and_then(|l| if l.mask.is_some() { Ok(()) } else { Err("the active layer has no layer mask".into()) })) + } + _ => None, + } +} + +/// Whether command `id` edits the targeted channel or mask when its params name no `"target"` +/// (filters, adjustments, paint and fill commands); the shell adds its mask target to these. +pub fn follows_target(id: &str) -> bool { + // Moving the selected pixels (⌘-drag, Move tool) moves the targeted mask's, not the layer's. + // Moving a layer with its unlinked mask targeted moves the mask alone (`layer.translate`). + routed(id) || id == "select.float" || id == "layer.translate" +} + +/// Whether command `id` edits a smart object's targeted filter mask (`"target":"filterMask"`): +/// every routed command but those that act on the smart object itself while its filter mask is +/// targeted (Edit › Transform, Apply Image, Convert for Smart Filters, Last Filter, Liquify, the +/// lens filters and Vanishing Point, which add a smart filter, the render filters that make a new +/// layer, and Desaturate), so neither the shell nor the engine sends those the filter mask. +pub fn follows_filter_mask(id: &str) -> bool { + routed(id) + && !id.starts_with("edit.transform.") + && !matches!( + id, + "image.applyImage" + | "image.adjustments.desaturate" + | "filter.vanishingPoint" + | "filter.render.flame" + | "filter.render.tree" + | "filter.render.pictureFrame" + | "filter.convertForSmartFilters" + | "filter.lastFilter" + | crate::distort_cmds::LIQUIFY + | crate::lens_cmds::LENS + | crate::lens_cmds::WIDE + | crate::lens_cmds::RAW + ) +} + +/// The paint and retouch tools that follow the targeted channel or mask. +const PAINT_IDS: &[&str] = &[ + "paint.stroke", + "paint.pencil", + "paint.bucket", + "paint.gradient", + "paint.mixerBrush", + "paint.cloneStamp", + "paint.patternStamp", + "paint.healingBrush", + "paint.spotHealing", + "paint.dodge", + "paint.burn", + "paint.sponge", + "paint.blur", + "paint.sharpen", + "paint.smudge", + "paint.historyBrush", + "paint.artHistoryBrush", + "paint.redEye", + "paint.remove", +]; + +/// Pasting into a targeted mask or channel (#1035). +const PASTE_IDS: &[&str] = &["edit.paste", "edit.pasteSpecial.pasteInPlace", "edit.pasteSpecial.pasteInto", "edit.pasteSpecial.pasteOutside"]; + +/// Commands whose target follows the Channels panel. +pub(crate) fn routed(id: &str) -> bool { + id.starts_with("filter.") + || id == "plugin.run" + || id.starts_with("image.adjustments.") + || matches!(id, "edit.fill" | "image.applyImage") + || crate::fill_key_cmds::IDS.contains(&id) + || PAINT_IDS.contains(&id) + // Pasting into a targeted mask or channel (#1035); Copy takes a targeted mask (#2928). + || id == "edit.copy" + || PASTE_IDS.contains(&id) + // Edit › Transform › Rotate/Flip turn a targeted mask or channel (#2835). + || matches!( + id, + "edit.transform.rotate180" + | "edit.transform.rotate90Cw" + | "edit.transform.rotate90Ccw" + | "edit.transform.flipHorizontal" + | "edit.transform.flipVertical" + ) +} + +/// Fill in `"target"` from the targeted channel (or Quick Mask mode) when the caller gave none. +pub(crate) fn inject_target(s: &Session, id: &str, params: Value) -> Value { + if !routed(id) || params.get("target").is_some() { + return params; + } + let Some(st) = s.active() else { return params }; + let t = match st.channel_view.target { + ChannelTarget::Alpha(i) if i < st.doc.channels.len() => json!({ "channel": i }), + ChannelTarget::Composite if st.doc.quick_mask.is_some() => json!("quickMask"), + ChannelTarget::LayerMask => json!("mask"), + // Viewing the active layer's mask (⌥-click): pixel commands edit the mask. + // A shown filter mask takes only the commands that edit it; the rest act on the smart object. + ChannelTarget::Composite if crate::mask_view_cmds::current(st).is_some_and(|v| v.filter) => { + if !follows_filter_mask(id) { + return params; + } + json!("filterMask") + } + ChannelTarget::Composite if crate::mask_view_cmds::current(st).is_some() => json!("mask"), + _ => return params, + }; + match params { + Value::Object(mut m) => { + m.insert("target".into(), t); + Value::Object(m) + } + _ => json!({ "target": t }), + } +} + +/// The smart object whose filter mask command `id` with `params` edits (`"target":"filterMask"`): +/// its `"layer"` param, else the active layer. None for a command that doesn't edit the filter +/// mask, so moving the smart object doesn't re-render its filters. +pub(crate) fn filter_mask_layer(s: &Session, id: &str, params: &Value) -> Option { + if target_of(params) != Target::FilterMask || !follows_filter_mask(id) { + return None; + } + params.get("layer").and_then(Value::as_u64).map(LayerId).or_else(|| s.active()?.active_layer) +} + +/// The colour channel pixel commands are limited to, if a single colour channel is targeted. +pub(crate) fn color_restriction(s: &Session, id: &str, params: &Value) -> Option { + if !routed(id) || is_channel_target(params) || crate::commands::is_mask_target(params) { + return None; + } + match s.active()?.channel_view.target { + ChannelTarget::Color(k) => Some(k), + _ => None, + } +} + +/// After a pixel edit with colour channel `k` targeted, put the other channels (and the layer's +/// transparency) of layer `id` back as they were. Only changed tiles are touched. +pub(crate) fn restrict_to_color(before: &Document, after: &mut Document, id: LayerId, k: usize) { + let Some(old) = before.layer(id).and_then(Layer::surface) else { return }; + let Some(new) = after.layer_mut(id).and_then(Layer::surface_mut) else { return }; + if old.format() != new.format() { + return; + } + let mut coords: Vec = new.tiles().filter(|(c, t)| old.tile(**c).is_none_or(|o| !std::sync::Arc::ptr_eq(o, t))).map(|(c, _)| *c).collect(); + coords.extend(old.tiles().filter(|(c, _)| new.tile(**c).is_none()).map(|(c, _)| *c)); + let n = new.channels(); + for c in coords { + let r = c.rect(); + let o = old.read_region(r); + let mut v = new.read_region(r); + for (pn, po) in v.chunks_exact_mut(n).zip(o.chunks_exact(n)) { + for ch in 0..n { + if ch != k { + pn[ch] = po[ch]; + } + } + } + new.write_region(r, &v); + } + new.prune(); +} + +/// The colour channel Clear is limited to: the Channels panel targets a single one. +pub(crate) fn targeted_color(s: &Session) -> Option { + match s.active()?.channel_view.target { + ChannelTarget::Color(k) => Some(k), + _ => None, + } +} + +/// Clear (Delete) with colour channel `k` of layer `id` targeted (#2720): fill the selected area +/// (or the canvas) of that channel only with the background colour's value for it, as Photoshop +/// does. A channel has no transparency of its own, so the other channels and the layer's alpha +/// stay; partly selected pixels blend. +pub(crate) fn clear_color_channel(doc: &mut Document, id: LayerId, k: usize, background: [f32; 4]) -> Result<()> { + let canvas = doc.bounds(); + let sel = doc.selection.clone(); + let area = sel.as_ref().map_or(canvas, |m| m.content_bounds().intersect(&canvas)); + let surf = crate::commands::paint_surface(doc, id, &Value::Null)?; + let fmt = surf.format(); + let n = fmt.channels(); + // The background colour in the layer's colour model, so `k` picks the right component. + let Some(v) = from_rgba(&fmt, [background[0], background[1], background[2], 1.0]).get(k).copied().filter(|_| k < n) else { + return Err(EngineError::Other(format!("no colour channel {k} in this layer"))); + }; + if area.is_empty() { + return Ok(()); + } + let cover = + sel.as_ref().map(|m| crate::allocation::read_region(m, area, "clearing a channel selection").map(|v| (v, m.format().channels().max(1)))).transpose()?; + let mut px = crate::allocation::read_region(surf, area, "clearing a channel")?; + for (i, p) in px.chunks_exact_mut(n).enumerate() { + let w = cover.as_ref().map_or(1.0, |(m, mk)| m.get(i * mk).copied().unwrap_or(0.0)); + if let Some(c) = p.get_mut(k) { + *c += (v - *c) * w.clamp(0.0, 1.0); + } + } + surf.try_write_region(area, &px)?; + surf.prune(); + Ok(()) +} + +/// The alpha channel or Quick Mask the Channels panel targets, as `"target"` params: Clear +/// (Delete) fills it instead of the layer (#2734). +pub(crate) fn targeted_channel(s: &Session) -> Option { + let st = s.active()?; + let t = match st.channel_view.target { + ChannelTarget::Alpha(i) if i < st.doc.channels.len() => json!({ "channel": i }), + ChannelTarget::Composite if st.doc.quick_mask.is_some() => json!("quickMask"), + _ => return None, + }; + Some(json!({ "target": t })) +} + +/// Clear (Delete) with an alpha channel or the Quick Mask targeted (`target` from +/// [`targeted_channel`]): fill the selected area (or the canvas) of it with the background colour, +/// as gray, as Photoshop does. Partly selected pixels blend. +pub(crate) fn clear_channel(doc: &mut Document, target: &Value, background: [f32; 4]) -> Result<()> { + let canvas = doc.bounds(); + let sel = doc.selection.clone(); + let area = sel.as_ref().map_or(canvas, |m| m.content_bounds().intersect(&canvas)); + if area.is_empty() { + return Ok(()); + } + let (surf, _) = target_surface(doc, None, target)?; + crate::fill_cmds::fill_color(surf, area, [background[0], background[1], background[2], 1.0], sel.as_ref()) +} + +/// The active document targets an alpha channel or is in Quick Mask mode, so pixel commands +/// work without a pixel layer. +pub(crate) fn edits_channel(s: &Session) -> bool { + s.active().is_some_and(|st| { + st.doc.quick_mask.is_some() && st.channel_view.target == ChannelTarget::Composite + || matches!(st.channel_view.target, ChannelTarget::Alpha(i) if i < st.doc.channels.len()) + }) +} + +/// Make `t` the edit target and show it the way Photoshop does when its row is clicked. +pub(super) fn target(s: &mut Session, t: ChannelTarget) { + if let Some(st) = s.active_mut() { + let colors = color_count(&st.doc); + let n = st.doc.channels.len(); + let v = &mut st.channel_view; + v.target = t; + match t { + // Like clicking RGB in Photoshop: the alpha overlays go away with their eyes. + ChannelTarget::Composite => { + v.color_hidden.clear(); + v.alpha_visible.clear(); + } + ChannelTarget::LayerMask | ChannelTarget::VectorMask => v.color_hidden.clear(), + ChannelTarget::Color(k) => { + v.color_hidden = (0..colors).map(|c| c != k).collect(); + v.alpha_visible.clear(); + } + ChannelTarget::Alpha(i) => { + v.color_hidden = vec![true; colors]; + v.alpha_visible = (0..n).map(|c| c == i).collect(); + } + } + fix_view_now(st); + } + s.tools.target_mask(t == ChannelTarget::LayerMask); +} + +fn parse_target(s: &Session, p: &Value, cmd: &str) -> Result { + let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; + match p.get("channel").map_or(Some(ChanRef::Composite), |v| parse_ref(v, doc)) { + Some(ChanRef::Composite) => Ok(ChannelTarget::Composite), + Some(ChanRef::Color(k)) if k < color_count(doc) && color_count(doc) > 1 => Ok(ChannelTarget::Color(k)), + Some(ChanRef::Alpha(i)) if i < doc.channels.len() => Ok(ChannelTarget::Alpha(i)), + Some(ChanRef::LayerMask) => { + let active = crate::active_layer_of(s).map_err(|e| bad(cmd, e))?; + if active.mask.is_none() { + return Err(bad(cmd, "the active layer has no layer mask")); + } + Ok(ChannelTarget::LayerMask) + } + Some(ChanRef::VectorMask) => { + let active = crate::active_layer_of(s).map_err(|e| bad(cmd, e))?; + if active.vector_mask.is_none() { + return Err(bad(cmd, "the active layer has no vector mask")); + } + Ok(ChannelTarget::VectorMask) + } + _ => Err(bad(cmd, "`channel` must be \"composite\", \"mask\", \"vectorMask\", a colour channel name or an alpha channel")), + } +} + +pub(super) fn target_cmd(s: &mut Session, p: &Value) -> Result { + let t = parse_target(s, p, "channel.target")?; + target(s, t); + Ok(list(s)) +} + +/// The channel shortcuts' modifier as the platform writes it, for error messages (`⌘4`, `Ctrl+4`). +pub(super) const SLOT_KEY: &str = if cfg!(target_os = "macos") { "⌘" } else { "Ctrl+" }; + +/// ⌘2 composite, ⌘3… colour channels then alpha channels (Photoshop CC defaults). +pub(super) fn target_slot(s: &mut Session, slot: usize) -> Result { + let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; + let colors = color_count(doc); + let shown_colors = if colors > 1 { colors } else { 0 }; + let t = match slot { + 2 => ChannelTarget::Composite, + n if n - 3 < shown_colors => ChannelTarget::Color(n - 3), + n if n - 3 - shown_colors < doc.channels.len() => ChannelTarget::Alpha(n - 3 - shown_colors), + _ => return Err(EngineError::Other(format!("no channel for {SLOT_KEY}{slot}"))), + }; + target(s, t); + Ok(list(s)) +} diff --git a/crates/engine/src/channel_cmds/tests.rs b/crates/engine/src/cmd/channel_cmds/tests.rs similarity index 100% rename from crates/engine/src/channel_cmds/tests.rs rename to crates/engine/src/cmd/channel_cmds/tests.rs diff --git a/crates/engine/src/cmd/channel_cmds/view.rs b/crates/engine/src/cmd/channel_cmds/view.rs new file mode 100644 index 0000000000..12afd4e9ce --- /dev/null +++ b/crates/engine/src/cmd/channel_cmds/view.rs @@ -0,0 +1,158 @@ +use super::planes::color_count; +use super::*; + +// --------------------------------------------------------------------------------------------- +// View state + +/// What pixel commands edit (Channels panel click / ⌘2…⌘9). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase", tag = "kind", content = "index")] +pub enum ChannelTarget { + /// The layers (all colour channels). In Quick Mask mode this edits the Quick Mask. + #[default] + Composite, + /// One colour channel of the active layer (index into the pixel format's colour channels). + Color(usize), + /// An alpha or spot channel (index into [`Document::channels`]). + Alpha(usize), + /// The active layer's layer mask. + LayerMask, + /// The active layer's vector mask. + VectorMask, +} + +/// Per-document Channels panel state: the target and the eye toggles. Not part of history. +#[derive(Clone, Debug, Default, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ChannelView { + pub target: ChannelTarget, + /// Hidden colour channels (missing entries are visible). + pub color_hidden: Vec, + /// Visible alpha channels (missing entries are hidden). + pub alpha_visible: Vec, + pub quick_mask_hidden: bool, + /// ⌥-click view of the active layer's mask (#196); see [`crate::mask_view_cmds`]. + pub layer_mask: Option, +} + +impl ChannelView { + pub fn color_visible(&self, k: usize) -> bool { + !self.color_hidden.get(k).copied().unwrap_or(false) + } + pub fn alpha_shown(&self, i: usize) -> bool { + self.alpha_visible.get(i).copied().unwrap_or(false) + } + pub fn set_color_visible(&mut self, k: usize, v: bool) { + if self.color_hidden.len() <= k { + self.color_hidden.resize(k + 1, false); + } + self.color_hidden[k] = !v; + } + pub fn set_alpha_visible(&mut self, i: usize, v: bool) { + if self.alpha_visible.len() <= i { + self.alpha_visible.resize(i + 1, false); + } + self.alpha_visible[i] = v; + } + /// Number of visible colour channels out of `colors`. + pub fn visible_colors(&self, colors: usize) -> usize { + (0..colors).filter(|k| self.color_visible(*k)).count() + } + /// True when the canvas shows just the normal composite (nothing extra to draw). + pub fn is_plain(&self, doc: &Document) -> bool { + let colors = color_count(doc); + self.visible_colors(colors) == colors + && !(0..doc.channels.len()).any(|i| self.alpha_shown(i)) + && (doc.quick_mask.is_none() || self.quick_mask_hidden) + && self.shown_layer_mask(doc).is_none() + } + /// The layer mask shown on the canvas (#196) and how, if its layer still has a mask. + pub fn shown_layer_mask<'a>(&self, doc: &'a Document) -> Option<(&'a photocraft_doc::LayerMask, crate::mask_view_cmds::MaskViewMode)> { + let v = self.layer_mask?; + Some((crate::mask_view_cmds::viewed_mask(doc.layer(v.layer)?, v.filter)?, v.mode)) + } +} + +/// Session-wide Quick Mask Options (double-click the Quick Mask button in Photoshop). +#[derive(Clone, Copy, Debug, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct QuickMaskOptions { + pub color: Color, + pub opacity: f32, + pub indicates: ColorIndicates, +} + +impl Default for QuickMaskOptions { + fn default() -> Self { + Self { color: AlphaChannel::DEFAULT_COLOR, opacity: 0.5, indicates: ColorIndicates::MaskedAreas } + } +} + +/// Keep the view valid after the document changed (undo, deleted channels, mode changes). +pub(crate) fn fix_view(st: &mut DocState) { + let n = st.doc.channels.len(); + let colors = color_count(&st.doc); + let quick = st.doc.quick_mask.is_some(); + { + let v = &mut st.channel_view; + v.alpha_visible.truncate(n); + v.color_hidden.truncate(colors); + match v.target { + ChannelTarget::Alpha(i) if i >= n => v.target = ChannelTarget::Composite, + ChannelTarget::Color(k) if k >= colors || colors < 2 => v.target = ChannelTarget::Composite, + ChannelTarget::LayerMask if st.active_layer.and_then(|id| st.doc.layer(id)).is_none_or(|l| l.mask.is_none()) => { + v.target = ChannelTarget::Composite; + } + ChannelTarget::VectorMask if st.active_layer.and_then(|id| st.doc.layer(id)).is_none_or(|l| l.vector_mask.is_none()) => { + v.target = ChannelTarget::Composite; + } + _ => {} + } + } + crate::mask_view_cmds::fix(st); + // An alpha/spot eye, Quick Mask, or the active layer's mask can be the only thing on the + // canvas (so R, G and B can all be off). Otherwise the colour channels come back. + let active = st.active_layer; + let shown = { + let doc = &st.doc; + let v = &st.channel_view; + (0..n).any(|i| v.alpha_shown(i)) || (quick && !v.quick_mask_hidden) || active.is_some_and(|id| doc.layer(id).is_some_and(|l| l.mask.is_some())) + }; + if st.channel_view.visible_colors(colors) == 0 && !shown { + st.channel_view.color_hidden.clear(); + } +} + +/// Bump the revision for a view-only change without dirtying a clean document. +pub(super) fn touch(st: &mut DocState) { + let clean = st.saved_revision == st.revision; + st.revision += 1; + st.view_revision += 1; + if clean { + st.saved_revision = st.revision; + } + st.last_damage = None; +} + +// --------------------------------------------------------------------------------------------- +// Channel names and formats + +/// Colour channel names of a document mode (the rows under the composite). +pub fn color_names(mode: ColorMode) -> &'static [&'static str] { + match mode { + ColorMode::Cmyk => &["Cyan", "Magenta", "Yellow", "Black"], + ColorMode::Lab => &["Lightness", "a", "b"], + ColorMode::Grayscale => &["Gray"], + _ => &["Red", "Green", "Blue"], + } +} + +/// Name of the composite row. +pub fn composite_name(mode: ColorMode) -> &'static str { + match mode { + ColorMode::Cmyk => "CMYK", + ColorMode::Lab => "Lab", + ColorMode::Grayscale => "Gray", + _ => "RGB", + } +} diff --git a/crates/engine/src/color_cmds.rs b/crates/engine/src/cmd/color_cmds.rs similarity index 100% rename from crates/engine/src/color_cmds.rs rename to crates/engine/src/cmd/color_cmds.rs diff --git a/crates/engine/src/color_to_alpha_cmds.rs b/crates/engine/src/cmd/color_to_alpha_cmds.rs similarity index 100% rename from crates/engine/src/color_to_alpha_cmds.rs rename to crates/engine/src/cmd/color_to_alpha_cmds.rs diff --git a/crates/engine/src/comps_cmds.rs b/crates/engine/src/cmd/comps_cmds.rs similarity index 100% rename from crates/engine/src/comps_cmds.rs rename to crates/engine/src/cmd/comps_cmds.rs diff --git a/crates/engine/src/comps_cmds/tests.rs b/crates/engine/src/cmd/comps_cmds/tests.rs similarity index 100% rename from crates/engine/src/comps_cmds/tests.rs rename to crates/engine/src/cmd/comps_cmds/tests.rs diff --git a/crates/engine/src/contour_lib_cmds.rs b/crates/engine/src/cmd/contour_lib_cmds.rs similarity index 100% rename from crates/engine/src/contour_lib_cmds.rs rename to crates/engine/src/cmd/contour_lib_cmds.rs diff --git a/crates/engine/src/cutout_cmds.rs b/crates/engine/src/cmd/cutout_cmds.rs similarity index 100% rename from crates/engine/src/cutout_cmds.rs rename to crates/engine/src/cmd/cutout_cmds.rs diff --git a/crates/engine/src/distort_cmds.rs b/crates/engine/src/cmd/distort_cmds.rs similarity index 100% rename from crates/engine/src/distort_cmds.rs rename to crates/engine/src/cmd/distort_cmds.rs diff --git a/crates/engine/src/distort_cmds/tests.rs b/crates/engine/src/cmd/distort_cmds/tests.rs similarity index 100% rename from crates/engine/src/distort_cmds/tests.rs rename to crates/engine/src/cmd/distort_cmds/tests.rs diff --git a/crates/engine/src/document_preset_cmds.rs b/crates/engine/src/cmd/document_preset_cmds.rs similarity index 100% rename from crates/engine/src/document_preset_cmds.rs rename to crates/engine/src/cmd/document_preset_cmds.rs diff --git a/crates/engine/src/cmd/edit_cmds.rs b/crates/engine/src/cmd/edit_cmds.rs new file mode 100644 index 0000000000..eb77590999 --- /dev/null +++ b/crates/engine/src/cmd/edit_cmds.rs @@ -0,0 +1,1111 @@ +//! Everyday Photoshop commands: clipboard (Cut/Copy/Copy Merged/Paste/Paste in Place), Layer via +//! Copy/Cut, Merge Visible, Auto Tone/Contrast/Color, Toggle Last State and Transform Again. + +use photocraft_color::{ColorMode, PixelFormat}; +use photocraft_doc::adjust::LevelsChannel; +use photocraft_doc::{Adjustment, DocId, Document, Layer, LayerContent, LayerId}; +use photocraft_geom::Rect; +use photocraft_raster::Surface; +use serde_json::{Value, json}; + +use crate::commands::CommandSpec; +use crate::{EngineError, Result, Session}; + +/// The paste commands' `"target"` param (for `concat!` into their params docs). +macro_rules! paste_target { + () => { + r#""target":"pixels"|"mask"|"quickMask"|{"channel":i}=Channels panel target (not pixels: the luminosity pasted into that mask or channel)"# + }; +} +pub(crate) use paste_target; + +/// Pixels on the session clipboard, with where they came from (for Paste in Place). +#[derive(Clone, Debug)] +pub struct Clip { + pub surface: Surface, + pub bounds: Rect, + /// The copied layer itself, when Copy took a whole layer that Paste should recreate rather + /// than rasterize (see [`whole_layer`]): a scratch document in the source's colour holding it. + /// `surface` still holds its pixels, for Paste Into, masks, channels and other apps. + pub layers: Option>, + /// The source document's resolution (ppi): File › New from the clipboard takes it, as + /// Photoshop's Clipboard preset does. None for an image from another app. + pub resolution: Option, + /// The document the pixels were copied from: Paste keeps them in place only there, and + /// centres them in any other (#8945). None for an image from another app. + pub source: Option, +} + +/// Photoshop's layer-based copy (CC 2018 on): with no selection, Copy takes the active layer +/// whole when it is a smart object (#2428), a type or shape layer, or a group (its whole subtree) +/// (#2670), so Paste recreates it instead of its pixels. Fill and adjustment layers have no +/// pixels of their own, so they are taken whole too rather than refused (#2344). Pixel layers +/// still copy their pixels; several selected layers are [`multi_copy_ids`]. +fn takes_whole(d: &crate::DocState, id: LayerId) -> bool { + d.doc.selection.is_none() + && d.selected_layers().len() <= 1 + && crate::layer_copy_cmds::layered(d.doc.mode) + && d.doc.layer(id).is_some_and(|l| !matches!(l.content, LayerContent::Raster(_))) +} + +/// A scratch document in the source's colour, to hold copied layers. +fn scratch_doc(doc: &Document) -> Document { + let mut copies = Document::new("", doc.size, doc.mode, doc.depth); + copies.icc_profile = doc.icc_profile.clone(); + copies.resolution_dpi = doc.resolution_dpi; + copies.patterns = doc.patterns.clone(); + copies +} + +/// Scope linked records to the copied layer tree: a PSD block can also hold files belonging +/// to unselected or hidden layers, which must not follow this copy into a native save. +fn copy_linked_sources(source: &Document, copies: &mut Document) -> Result<()> { + fn collect<'a>(layers: &'a [Layer], depth: usize, paths: &mut std::collections::HashSet<&'a str>) -> Result<()> { + if depth > photocraft_doc::MAX_GROUP_DEPTH { + return Err(EngineError::Other("can't copy linked smart objects from layers nested too deeply".into())); + } + for layer in layers { + if let LayerContent::Smart(sm) = &layer.content + && let photocraft_doc::SmartSource::Linked { path } = &sm.source + { + paths.try_reserve(1).map_err(|_| EngineError::Other("not enough memory to copy smart-object source IDs".into()))?; + paths.insert(path); + } + if let Some(children) = layer.children().filter(|children| !children.is_empty()) { + collect(children, depth + 1, paths)?; + } + } + Ok(()) + } + let mut paths = std::collections::HashSet::new(); + collect(&copies.layers, 0, &mut paths)?; + if paths.is_empty() { + return Ok(()); + } + for (signature, key, data) in &source.metadata.psd_global_blocks { + if !matches!(key, b"lnk2" | b"lnk3" | b"lnkD" | b"lnkE") { + continue; + } + let selected = photocraft_io::linked::select_items(data, &|uuid, _| paths.contains(uuid)) + .map_err(|e| EngineError::Other(format!("Could not copy smart-object contents: {e}; the clipboard was not changed")))?; + let selected = selected.map(std::sync::Arc::new).unwrap_or_else(|| data.clone()); + if !selected.is_empty() { + copies.metadata.psd_global_blocks.try_reserve(1).map_err(|_| EngineError::Other("not enough memory to copy smart-object source records".into()))?; + copies.metadata.psd_global_blocks.push((*signature, *key, selected)); + } + } + Ok(()) +} + +/// The layer Copy takes whole ([`takes_whole`]): a scratch document in the source's colour +/// holding it. +fn whole_layer(d: &crate::DocState, id: LayerId) -> Option> { + let l = d.doc.layer(id).filter(|_| takes_whole(d, id))?; + let mut copies = scratch_doc(&d.doc); + copies.layers.push(l.clone()); + Some(Box::new(copies)) +} + +/// The layers Copy takes when several are selected and nothing is selected in the pixels +/// (Photoshop, #2478): the selected layers that no selected group already carries, bottom-to-top. +/// Empty otherwise, and for a single layer ([`takes_whole`] decides that case). +fn multi_copy_ids(d: &crate::DocState) -> Vec { + if d.doc.selection.is_some() || !crate::layer_copy_cmds::layered(d.doc.mode) { + return Vec::new(); + } + let selected = d.selected_layers(); + if selected.len() < 2 { + return Vec::new(); + } + crate::layer_multi_cmds::top_level(&d.doc, &selected) +} + +/// Every selected layer, whole ([`multi_copy_ids`]), in a scratch document: Paste recreates them +/// all, each with its mask, styles and content. The Background becomes an ordinary layer, as in +/// Photoshop's Duplicate Layer. +fn whole_layers(d: &crate::DocState, ids: &[LayerId]) -> Option> { + let mut copies = scratch_doc(&d.doc); + for id in ids { + let mut l = d.doc.layer(*id)?.clone(); + if d.doc.is_background(*id) { + l.name = "Layer 0".into(); + l.locks = Default::default(); + } + copies.layers.push(l); + } + Some(Box::new(copies)) +} + +fn has_doc(s: &Session) -> std::result::Result<(), String> { + s.active().map(|_| ()).ok_or_else(|| "no document open".into()) +} + +/// Paste and New from Clipboard need only a clipboard: with no document open, they make one. +fn has_clip_only(s: &Session) -> std::result::Result<(), String> { + s.clipboard.as_ref().map(|_| ()).ok_or_else(|| "the clipboard is empty".into()) +} + +fn active_layer(s: &Session) -> std::result::Result<&Layer, String> { + let d = s.active().ok_or("no document open")?; + d.active_layer.and_then(|id| d.doc.layer(id)).ok_or_else(|| "no active layer".into()) +} + +/// Cut and Layer via Cut edit the pixels, so they need a pixel layer. +fn has_pixels(s: &Session) -> std::result::Result<(), String> { + match active_layer(s)?.content { + LayerContent::Raster(_) => Ok(()), + LayerContent::Smart(_) => Err("the smart object is not directly editable".into()), + _ => Err("the active layer has no pixels".into()), + } +} + +/// Copy only reads: any layer that shows pixels will do, so a smart object, type or shape layer +/// copies what it shows (Photoshop). +fn has_layer_pixels(s: &Session) -> std::result::Result<(), String> { + active_layer(s)?.surface().map(|_| ()).ok_or_else(|| "the active layer has no pixels".into()) +} + +/// Copy: a targeted alpha channel (#2307), a layer with pixels, or one taken whole (a group with +/// no selection, #2670). +fn can_copy(s: &Session) -> std::result::Result<(), String> { + if crate::channel_clip::copies_alpha_channel(s) || s.active().is_some_and(|d| !multi_copy_ids(d).is_empty()) { + return Ok(()); + } + has_layer_pixels(s).or_else(|e| s.active().and_then(|d| d.active_layer.filter(|id| takes_whole(d, *id))).map(|_| ()).ok_or(e)) +} + +fn has_clip(s: &Session) -> std::result::Result<(), String> { + has_doc(s)?; + s.clipboard.as_ref().map(|_| ()).ok_or_else(|| "the clipboard is empty".into()) +} + +fn active_id(s: &Session) -> Result { + s.active().and_then(|d| d.active_layer).ok_or(EngineError::Other("no active layer".into())) +} + +/// The pixels of `src` inside the selection (or all of them), as a straight-alpha surface. +/// +/// Built tile by tile (#4516). A source tile that the copy takes whole (inside the canvas, fully +/// selected or no selection, already in the clip's format) is shared copy-on-write, so a plain +/// Copy or Select All, Copy costs a pointer per tile; only the other tiles are read and written, +/// one at a time, instead of the whole area as one `f32` buffer. +fn lift(src: &Surface, sel: Option<&Surface>, canvas: Rect) -> Result { + let fmt = src.format(); + let with_alpha = PixelFormat::new(fmt.mode, fmt.sample, true); + let area = match sel { + Some(m) => m.content_bounds().intersect(&canvas), + None => src.content_bounds().intersect(&canvas), + }; + let mut out = Surface::new(with_alpha); + if area.is_empty() { + return Ok(Clip { surface: out, bounds: Rect::EMPTY, layers: None, resolution: None, source: None }); + } + // Only the selected area is read: converting the whole layer (a 24 MP Background gaining + // alpha) cost about a second per Layer via Copy (#668). + let mut shared = Vec::new(); + for tc in area.tiles() { + let tr = tc.rect().intersect(&area); + if fmt.alpha + && tr == tc.rect() + && let Some(tile) = src.tile(tc) + && sel.is_none_or(|m| crate::fill_cmds::Mask::of(m, tc).full(tr)) + { + // Reading and writing it back would give the same bytes. + shared.push((tc, tile.clone())); + continue; + } + let px = lift_region(src, sel, tr, with_alpha.channels())?; + out.try_write_region(tr, &px).map_err(|e| EngineError::Other(format!("not enough memory while copying pixels ({e}); the document was not changed")))?; + } + out.put_tiles(shared); + out.prune(); + let bounds = out.content_bounds(); + Ok(Clip { surface: out, bounds, layers: None, resolution: None, source: None }) +} + +/// [`lift`] over one rectangle: `src`'s pixels with alpha (`n` channels), the selection +/// multiplied into it. +fn lift_region(src: &Surface, sel: Option<&Surface>, r: Rect, n: usize) -> Result> { + let fmt = src.format(); + let mut px = if fmt.alpha { + crate::allocation::read_region(src, r, "copying pixels")? + } else { + let opaque = crate::allocation::read_region(src, r, "copying pixels")?; + let k = fmt.channels(); + let len = opaque + .len() + .checked_div(k.max(1)) + .and_then(|pixels| pixels.checked_mul(n)) + .ok_or_else(|| EngineError::Other("not enough memory for copying pixels (requested size overflowed); the document was not changed".into()))?; + let mut v = crate::allocation::filled(len, 0.0, "copying pixels")?; + let mut at = 0; + for p in opaque.chunks_exact(k.max(1)) { + let Some(dst) = v.get_mut(at..at + k.max(1)) else { break }; + dst.copy_from_slice(p); + at += k.max(1); + if let Some(alpha) = v.get_mut(at) { + *alpha = 1.0; + } + at += 1; + } + v + }; + if let Some(m) = sel { + let mask = crate::allocation::read_region(m, r, "applying the selection to copied pixels")?; + let mk = m.format().channels().max(1); + for (p, a) in px.chunks_exact_mut(n.max(1)).zip(mask.chunks_exact(mk)) { + if let Some(alpha) = p.last_mut() { + *alpha *= a[0]; + } + } + } + Ok(px) +} + +/// Merged composite of the visible document as a surface in the document's format. +fn merged_surface(doc: &Document) -> Surface { + let fmt = doc.pixel_format(); + photocraft_compose::flatten_to_surface(doc, PixelFormat::new(fmt.mode, fmt.sample, true), None) +} + +fn copy(s: &mut Session, merged: bool) -> Result { + let d = s.active().ok_or(EngineError::NoDocument)?; + let canvas = d.doc.bounds(); + let clip = if merged { + lift(&merged_surface(&d.doc), d.doc.selection.as_ref(), canvas)? + } else { + let id = d.active_layer.ok_or(EngineError::Other("no active layer".into()))?; + let several = multi_copy_ids(d); + let mut layers = if several.is_empty() { whole_layer(d, id) } else { whole_layers(d, &several) }; + if let Some(copies) = &mut layers { + copy_linked_sources(&d.doc, copies)?; + } + match (d.doc.layer(id).and_then(Layer::surface).filter(|_| several.is_empty()), &layers) { + (Some(surf), _) => Clip { layers, ..lift(surf, d.doc.selection.as_ref(), canvas)? }, + // A group or fill layer has no pixels of its own: the clipboard pixels are what it + // shows. Adjustment layers show nothing by themselves, so their clip spans the canvas + // they apply to: Paste places them as a full-canvas layer, and the UI still mirrors + // the clip to the OS clipboard (an empty clip would let a stale OS image replace it). + (None, Some(copies)) => { + let mut shown = (**copies).clone(); + for l in &mut shown.layers { + l.visible = true; + } + let clip = lift(&merged_surface(&shown), None, canvas)?; + let bounds = if clip.bounds.is_empty() { canvas } else { clip.bounds }; + Clip { layers, bounds, ..clip } + } + (None, None) => return Err(EngineError::Other("the active layer has no pixels".into())), + } + }; + if clip.bounds.is_empty() { + return Err(EngineError::Other("Could not copy: the selected area is empty".into())); + } + let b = clip.bounds; + let clip = Clip { resolution: Some(d.doc.resolution_dpi), source: Some(d.doc.id), ..clip }; + s.clipboard = Some(clip); + Ok(json!({"bounds": [b.x0, b.y0, b.width(), b.height()]})) +} + +/// Copy the targeted layer mask (`"target":"mask"`, #2928) or smart-filter mask +/// (`"target":"filterMask"`): the mask's values as a +/// grayscale clip, inside the selection or the whole canvas — an untouched mask copies at its +/// default value, so a plain Reveal All / Hide All mask transfers too. Paste then writes into +/// another layer's mask (targeted, #1035), in this or another document. +fn copy_mask(s: &mut Session, filter: bool) -> Result { + let d = s.active().ok_or(EngineError::NoDocument)?; + let canvas = d.doc.bounds(); + let id = d.active_layer.ok_or_else(|| EngineError::Other("no active layer".into()))?; + let layer = d.doc.layer(id).ok_or(EngineError::NoLayer(id))?; + let mask = crate::mask_view_cmds::viewed_mask(layer, filter) + .ok_or_else(|| EngineError::Other(if filter { "the active layer has no filter mask" } else { "the active layer has no layer mask" }.into()))?; + let sel = d.doc.selection.as_ref(); + let area = sel.map_or(canvas, |m| m.content_bounds().intersect(&canvas)); + if area.is_empty() { + return Err(EngineError::Other("Could not copy: the selected area is empty".into())); + } + let n = mask.surface.format().channels().max(1); + let values = crate::allocation::read_region(&mask.surface, area, "copying the mask")?; + let len = values + .len() + .checked_div(n) + .and_then(|pixels| pixels.checked_mul(2)) + .ok_or_else(|| EngineError::Other("not enough memory for copying the mask (requested size overflowed); the document was not changed".into()))?; + let cover = sel.map(|m| (m.read_region(area), m.format().channels().max(1))); + let mut px = crate::allocation::filled(len, 0.0, "copying the mask")?; + for (i, p) in values.chunks_exact(n).enumerate() { + px[i * 2] = p.first().copied().unwrap_or(0.0); + px[i * 2 + 1] = cover.as_ref().map_or(1.0, |(m, mk)| m.get(i * mk).copied().unwrap_or(0.0)); + } + let fmt = PixelFormat::new(ColorMode::Grayscale, mask.surface.format().sample, true); + let mut surface = Surface::new(fmt); + surface + .try_write_region(area, &px) + .map_err(|e| EngineError::Other(format!("not enough memory while copying the mask ({e}); the document was not changed")))?; + surface.prune(); + let bounds = surface.content_bounds(); + if bounds.is_empty() { + return Err(EngineError::Other("Could not copy: the selected area is empty".into())); + } + let b = bounds; + let (resolution, source) = (Some(d.doc.resolution_dpi), Some(d.doc.id)); + s.clipboard = Some(Clip { surface, bounds: b, layers: None, resolution, source }); + Ok(json!({"bounds": [b.x0, b.y0, b.width(), b.height()], "target": if filter { "filterMask" } else { "mask" }})) +} + +fn clear_selected(doc: &mut Document, id: LayerId, background: [f32; 4]) -> Result<()> { + let sel = doc.selection.clone(); + let canvas = doc.bounds(); + let area = sel.as_ref().map_or(canvas, |m| m.content_bounds().intersect(&canvas)); + clear_area(doc, id, area, sel.as_ref(), background) +} + +/// Cut / Clear on a layer: makes the selected pixels transparent. The Background can't hold +/// transparency, so there the area is filled with the background colour instead (Photoshop). +pub(crate) fn clear_area(doc: &mut Document, id: LayerId, area: Rect, sel: Option<&Surface>, background: [f32; 4]) -> Result<()> { + doc.layer(id).ok_or(EngineError::NoLayer(id))?; + let bg = doc.is_background(id); + let surf = crate::commands::paint_surface(doc, id, &Value::Null)?; + if bg { + crate::pixels::try_fill_surface(surf, area, background, sel, true)?; + } else { + crate::pixels::try_clear_surface(surf, area, sel)?; + } + surf.prune(); + Ok(()) +} + +/// Paste as a new layer (or into the targeted mask or channel: [`paste_to_target`]). `in_place` keeps the original position; otherwise the pixels are centred +/// on `center` (the view centre from the UI) or the canvas, unless they already overlap the canvas. +fn paste(s: &mut Session, p: &Value, in_place: bool) -> Result { + crate::allocation::checkpoint("pasting pixels")?; + let clip = s.clipboard.clone().ok_or(EngineError::Other("the clipboard is empty".into()))?; + let Some(d) = s.active() else { + // Nothing open to paste into: the clipboard becomes a document of its own (#368). + return new_from_clipboard(s); + }; + if crate::channel_cmds::target_of(p) != crate::channel_cmds::Target::Pixels { + return paste_to_target(s, p, in_place, None, "Paste"); + } + // A targeted colour channel takes the paste instead of a new layer (#2307). + if let Some(k) = crate::channel_clip::paste_color_target(s, p) { + return crate::channel_clip::paste(s, p, k, in_place, None, "Paste"); + } + let canvas = d.doc.bounds(); + let fmt = d.doc.pixel_format(); + let (dx, dy) = paste_offset(&clip, d.doc.id, canvas, p, in_place); + if let Some(layers) = clip.layers.as_deref().filter(|_| crate::layer_copy_cmds::layered(d.doc.mode)) { + return paste_layers(s, layers, dx, dy); + } + let moved = shifted(&clip.surface, dx, dy); + let target = PixelFormat::new(fmt.mode, fmt.sample, true); + let surf = if moved.format() == target { moved } else { moved.convert(target) }; + let id = s.edit("Paste", |doc, active| { + let mut l = Layer::raster(doc.next_layer_name("Layer"), target); + *crate::pixels_mut(&mut l)? = surf; + let id = doc.insert_above(*active, l); + *active = Some(id); + doc.selection = None; + Ok(id) + })?; + // `edit` reports only where the pasted pixels land as damage, not the whole document (#2901). + Ok(json!({"layer": id.0, "offset": [dx, dy]})) +} + +/// Paste of a whole copied layer ([`whole_layer`]): fresh copies (a group's children too), +/// converted to the document's colour, moved as the pixels would be, above the active layer. A pasted smart object gets its +/// own contents, independent of the copied one (as across documents). +fn paste_layers(s: &mut Session, layers: &Document, dx: i32, dy: i32) -> Result { + let d = s.active().ok_or(EngineError::NoDocument)?; + let mut copies = layers.clone(); + for l in &mut copies.layers { + *l = l.duplicate(); + } + crate::layer_copy_cmds::adapt_copies(s, &mut copies, &d.doc)?; + crate::layer_copy_cmds::translate_copies(&mut copies, &d.doc, dx, dy); + let patterns: Vec<_> = copies.patterns.iter().filter(|pat| !d.doc.patterns.iter().any(|q| q.id == pat.id)).cloned().collect(); + // A copied smart object may name a PSD-embedded linked file; land its `lnk` block too (#3584). + let mut linked = Vec::new(); + for (signature, key, data) in copies.metadata.psd_global_blocks.iter().filter(|(_, k, _)| matches!(k, b"lnk2" | b"lnk3" | b"lnkD" | b"lnkE")) { + if d.doc.metadata.psd_global_blocks.iter().any(|(_, dk, dd)| dk == key && std::sync::Arc::ptr_eq(dd, data)) { + continue; + } + // The clipboard may contain a subset of a destination block. Compare complete records, + // so copying one layer in the same document does not duplicate large embedded files. + let missing = photocraft_io::linked::select_items(data, &|_, raw| { + !d.doc.metadata.psd_global_blocks.iter().any(|(_, dk, dd)| dk == key && photocraft_io::linked::contains_item(dd, raw)) + }) + .map_err(|e| EngineError::Other(format!("Could not paste smart-object contents: {e}; the document was not changed")))?; + let missing = missing.map(std::sync::Arc::new).unwrap_or_else(|| data.clone()); + if !missing.is_empty() { + linked.try_reserve(1).map_err(|_| EngineError::Other("not enough memory to paste smart-object source records".into()))?; + linked.push((*signature, *key, missing)); + } + } + let id = s.edit("Paste", |doc, active| { + doc.patterns.extend(patterns); + doc.metadata.psd_global_blocks.extend(linked); + for l in copies.layers { + *active = Some(doc.insert_above(*active, l)); + } + doc.selection = None; + active.ok_or(EngineError::Other("nothing to paste".into())) + })?; + Ok(json!({"layer": id.0, "offset": [dx, dy]})) +} + +/// How far a paste moves the clipboard pixels: not at all in place (or when they lie on the +/// canvas and no `center` is given), else onto `center` (the view centre from the UI) or the +/// canvas centre, then kept on the canvas as Photoshop keeps it: pixels that fit stay wholly +/// inside, larger ones start at the canvas's top-left corner (#6759). `"clampToCanvas": false` +/// skips that, for Paste Into / Outside, which centre on the selection. +pub(crate) fn paste_offset(clip: &Clip, doc: DocId, canvas: Rect, p: &Value, in_place: bool) -> (i32, i32) { + let home = clip.source == Some(doc); + if in_place || (home && clip.bounds.intersect(&canvas) == clip.bounds && p.get("center").is_none()) { + return (0, 0); + } + let c = p.get("center").and_then(Value::as_array).filter(|a| a.len() >= 2).map(|a| (a[0].as_f64().unwrap_or(0.0), a[1].as_f64().unwrap_or(0.0))); + let (cx, cy) = c.unwrap_or((mid(canvas.x0, canvas.x1), mid(canvas.y0, canvas.y1))); + let b = clip.bounds; + let (dx, dy) = ((cx - mid(b.x0, b.x1)).round(), (cy - mid(b.y0, b.y1)).round()); + if p.get("clampToCanvas").and_then(Value::as_bool) == Some(false) || b.is_empty() { + return (dx as i32, dy as i32); + } + (clamp_shift(dx, b.x0, b.x1, canvas.x0, canvas.x1), clamp_shift(dy, b.y0, b.y1, canvas.y0, canvas.y1)) +} + +/// The midpoint of `a..b`, each edge converted before adding so extreme coordinates can't overflow. +fn mid(a: i32, b: i32) -> f64 { + (f64::from(a) + f64::from(b)) / 2.0 +} + +/// Shift `d` of the span `b0..b1` along one axis, changed as little as needed to keep the span +/// inside `c0..c1` when it fits; a span longer than the canvas starts at `c0`. +fn clamp_shift(d: f64, b0: i32, b1: i32, c0: i32, c1: i32) -> i32 { + let (b0, b1, c0, c1) = (i64::from(b0), i64::from(b1), i64::from(c0), i64::from(c1)); + // `as` saturates a NaN or out-of-range shift, then the clamp brings it into range. + let start = if b1 - b0 <= c1 - c0 { b0.saturating_add(d as i64).clamp(c0, c1 - (b1 - b0)) } else { c0 }; + i32::try_from(start - b0).unwrap_or(if start > b0 { i32::MAX } else { i32::MIN }) +} + +pub(crate) fn shifted(surface: &Surface, dx: i32, dy: i32) -> Surface { + if dx == 0 && dy == 0 { surface.clone() } else { photocraft_algo::resample::translate_surface(surface, dx, dy) } +} + +/// Paste into the targeted layer mask, alpha channel or Quick Mask (`"target"`) instead of as a +/// new layer (Photoshop, #1035): the pasted pixels' luminosity, placed as a paste places them, +/// over what was there. Their transparency, and `limit` (Paste Into / Outside), let it show +/// through. One history step. +pub(crate) fn paste_to_target(s: &mut Session, p: &Value, in_place: bool, limit: Option<&Surface>, label: &str) -> Result { + crate::allocation::checkpoint("pasting pixels")?; + let clip = s.clipboard.clone().ok_or(EngineError::Other("the clipboard is empty".into()))?; + let d = s.active().ok_or(EngineError::NoDocument)?; + let canvas = d.doc.bounds(); + let layer = d.active_layer; + let (dx, dy) = paste_offset(&clip, d.doc.id, canvas, p, in_place); + let src = shifted(&clip.surface, dx, dy); + let area = src.content_bounds().intersect(&canvas); + s.edit(label, |doc, _| { + let (surf, _) = crate::channel_cmds::target_surface(doc, layer, p)?; + crate::fill_cmds::composite_over(surf, &src, area, limit)?; + surf.prune(); + doc.selection = None; + Ok(()) + })?; + Ok(json!({"target": p.get("target"), "offset": [dx, dy]})) +} + +/// A new document the size of the clipboard image, holding it as its one layer, in the pixel +/// format it was copied in (#368). +fn new_from_clipboard(s: &mut Session) -> Result { + let clip = s.clipboard.clone().ok_or(EngineError::Other("the clipboard is empty".into()))?; + let b = clip.bounds; + let (w, h) = (b.width(), b.height()); + if w == 0 || h == 0 { + return Err(EngineError::Other("the clipboard image has no size".into())); + } + let (Some(dx), Some(dy)) = (b.x0.checked_neg(), b.y0.checked_neg()) else { + return Err(EngineError::Other("the clipboard origin is outside the coordinate range for a new document".into())); + }; + let fmt = clip.surface.format(); + let target = PixelFormat::new(fmt.mode, fmt.sample, true); + let moved = if dx == 0 && dy == 0 { clip.surface } else { photocraft_algo::resample::translate_surface(&clip.surface, dx, dy) }; + let mut doc = Document::new("Untitled", photocraft_geom::Size::new(w, h), fmt.mode, fmt.sample); + if let Some(r) = clip.resolution.filter(|r| r.is_finite() && *r > 0.0) { + doc.resolution_dpi = r; + } + let mut l = Layer::raster(doc.next_layer_name("Layer"), target); + *crate::pixels_mut(&mut l)? = if moved.format() == target { moved } else { moved.convert(target) }; + doc.layers.push(l); + let i = s.add_document(doc, None); + // Clipboard content has never been saved; closing this tab must ask before discarding it. + if let Some(st) = s.active_mut() { + st.saved_revision = 0; + } + Ok(json!({"document": i, "width": w, "height": h})) +} + +fn layer_via(s: &mut Session, cut: bool) -> Result { + let d = s.active().ok_or(EngineError::NoDocument)?; + let id = active_id(s)?; + let has_sel = d.doc.selection.is_some(); + if !has_sel && !cut && crate::layer_multi_cmds::multi(s, &Value::Null) { + // No selection, several layers selected: copy every one of them (Photoshop, #2777). + return crate::layer_multi_cmds::duplicate_selected(s, true, "Layer Via Copy"); + } + if !has_sel && !cut { + // No selection: Layer via Copy duplicates the whole layer (Photoshop). + let nid = s.edit("Layer Via Copy", |doc, active| { + let src = doc.layer(id).ok_or(EngineError::NoLayer(id))?; + let mut dup = src.duplicate(); + dup.name = doc.copy_name(&src.name); + dup.locks = Default::default(); + let nid = doc.insert_above(Some(id), dup); + *active = Some(nid); + Ok(nid) + })?; + return Ok(json!({"layer": nid.0})); + } + let surf = d.doc.layer(id).and_then(Layer::surface).ok_or(EngineError::Other("the active layer has no pixels".into()))?; + let clip = lift(surf, d.doc.selection.as_ref(), d.doc.bounds())?; + if clip.bounds.is_empty() { + return Err(EngineError::Other("Could not complete the command: the selected area is empty".into())); + } + let bg = s.tools.background; + let label = if cut { "Layer Via Cut" } else { "Layer Via Copy" }; + let nid = s.edit(label, |doc, active| { + if cut { + clear_selected(doc, id, bg)?; + } + let mut l = Layer::raster(doc.next_layer_name("Layer"), clip.surface.format()); + *crate::pixels_mut(&mut l)? = clip.surface; + let nid = doc.insert_above(Some(id), l); + *active = Some(nid); + // Photoshop deselects: a following Free Transform moves the whole new layer (#1096). + doc.selection = None; + Ok(nid) + })?; + Ok(json!({"layer": nid.0})) +} + +fn merge_visible(s: &mut Session) -> Result { + s.edit("Merge Visible", |doc, active| { + let visible: Vec = doc.layers.iter().enumerate().filter(|(_, l)| l.visible).map(|(i, _)| i).collect(); + if visible.len() < 2 && !visible.iter().any(|i| doc.layers[*i].is_group()) { + return Err(EngineError::Other("there are not enough visible layers to merge".into())); + } + let lowest = visible[0]; + let base = doc.layers[lowest].clone(); + let is_background = lowest == 0 && doc.is_background(base.id); + // Composite of visible layers only (hidden ones stay where they are). + let mut solo = doc.clone(); + solo.layers.retain(|l| l.visible); + let fmt = doc.pixel_format(); + let fmt = if is_background { fmt } else { PixelFormat::new(fmt.mode, fmt.sample, true) }; + let mut merged = Layer::raster(base.name.clone(), fmt); + merged.locks = base.locks; + *crate::pixels_mut(&mut merged)? = crate::pixels::composite_layers(&solo, fmt, is_background.then_some([1.0, 1.0, 1.0])); + let mid = merged.id; + let mut out = Vec::with_capacity(doc.layers.len()); + for (i, l) in doc.layers.drain(..).enumerate() { + if i == lowest { + out.push(merged.clone()); + } else if !l.visible { + out.push(l); + } + } + doc.layers = out; + *active = Some(mid); + Ok(()) + })?; + Ok(Value::Null) +} + +/// Histogram of a pixel layer (8-bit bins per channel: R, G, B) inside the selection. +fn histograms(surf: &Surface, area: Rect) -> [[u64; 256]; 3] { + let mut h = [[0u64; 256]; 3]; + let step = ((area.width() as u64 * area.height() as u64) / 4_000_000).max(1) as usize; // sample big images + let mut row = vec![[0u8; 4]; area.width() as usize]; + for y in (area.y0..area.y1).step_by(step.isqrt().max(1)) { + surf.read_rgba8_into(Rect::new(area.x0, y, area.x1, y + 1), &mut row); + for p in row.iter().step_by(step.isqrt().max(1)) { + if p[3] == 0 { + continue; + } + for c in 0..3 { + h[c][p[c] as usize] += 1; + } + } + } + h +} + +/// Black and white points with `clip` (fraction) clipped at each end. +fn clip_points(h: &[u64; 256], clip: f64) -> (f32, f32) { + let total: u64 = h.iter().sum(); + if total == 0 { + return (0.0, 1.0); + } + let lim = (total as f64 * clip) as u64; + let (mut acc, mut lo) = (0u64, 0usize); + while lo < 254 && acc + h[lo] <= lim { + acc += h[lo]; + lo += 1; + } + let (mut acc, mut hi) = (0u64, 255usize); + while hi > lo + 1 && acc + h[hi] <= lim { + acc += h[hi]; + hi -= 1; + } + (lo as f32 / 255.0, hi as f32 / 255.0) +} + +fn median(h: &[u64; 256]) -> f32 { + let total: u64 = h.iter().sum(); + let mut acc = 0; + for (i, v) in h.iter().enumerate() { + acc += v; + if acc * 2 >= total { + return i as f32 / 255.0; + } + } + 0.5 +} + +/// Image › Auto Tone / Auto Contrast / Auto Color (0.1% clipping, Photoshop's defaults). +fn auto_adjust(s: &mut Session, kind: &str) -> Result { + let id = active_id(s)?; + let d = s.active().ok_or(EngineError::NoDocument)?; + let surf = d.doc.layer(id).and_then(Layer::surface).ok_or(EngineError::Other("the active layer has no pixels".into()))?; + let area = d.doc.selection.as_ref().map_or(d.doc.bounds(), |m| m.content_bounds()).intersect(&d.doc.bounds()); + let h = histograms(surf, area); + let clip = 0.001; + let mut per = [LevelsChannel::default(), LevelsChannel::default(), LevelsChannel::default()]; + match kind { + "contrast" => { + // Same points for all channels (preserves colour), from the combined histogram. + let mut all = [0u64; 256]; + for c in &h { + for (a, v) in all.iter_mut().zip(c) { + *a += v; + } + } + let (lo, hi) = clip_points(&all, clip); + for p in &mut per { + (p.in_black, p.in_white) = (lo, hi); + } + } + _ => { + for (c, p) in per.iter_mut().enumerate() { + (p.in_black, p.in_white) = clip_points(&h[c], clip); + } + if kind == "color" { + // Neutralise midtones: move each channel's median onto the average median. + let meds: Vec = (0..3).map(|c| median(&h[c])).collect(); + let target = meds.iter().sum::() / 3.0; + for (c, p) in per.iter_mut().enumerate() { + let t = ((meds[c] - p.in_black) / (p.in_white - p.in_black).max(1e-3)).clamp(0.02, 0.98); + let want = ((target - p.in_black) / (p.in_white - p.in_black).max(1e-3)).clamp(0.02, 0.98); + // out = t^(1/g) = want → g = ln t / ln want + p.gamma = (t.ln() / want.ln()).clamp(0.1, 9.99); + } + } + } + } + let adj = Adjustment::Levels { master: LevelsChannel::default(), per_channel: per, space: Default::default(), black: LevelsChannel::default() }; + let label = match kind { + "contrast" => "Auto Contrast", + "color" => "Auto Color", + _ => "Auto Tone", + }; + s.edit(label, |doc, _| { + let sel = doc.selection.clone(); + let mode = doc.mode; + let surf = crate::commands::paint_surface(doc, id, &Value::Null)?; + crate::pixels::adjust_surface(surf, &adj, sel.as_ref(), mode).map_err(EngineError::Other)?; + Ok(()) + })?; + Ok(Value::Null) +} + +fn toggle_last_state(s: &mut Session) -> Result { + let st = s.active().ok_or(EngineError::NoDocument)?; + let redo = st.history.can_redo(); + Ok(json!(if redo { s.redo() } else { s.undo() })) +} + +/// Edit › Transform › Again: replay the last `edit.transform` on the active layer. +fn transform_again(s: &mut Session) -> Result { + let p = transform_again_params(s)?; + s.execute("edit.transform", p) +} + +/// Transform Again on a copy (⌥⇧⌘T, no menu item): duplicates the active layer and repeats the +/// last transform on the copy, as one history step, so pressing it again steps and repeats +/// (#352). The transform is worked out before anything changes, so a refusal leaves no copy. +fn transform_again_copy(s: &mut Session) -> Result { + let p = transform_again_params(s)?; + let id = active_id(s)?; + let journal = s.journal.len(); + // The steps are recorded (Again on a Copy is not replayable itself): with one layer selected, + // "duplicate the current layer" plays back on any document, a layer id only on this one. + let dup = if crate::layer_multi_cmds::multi(s, &Value::Null) { json!({"layer": id.0}) } else { json!({}) }; + s.execute("layer.duplicate", dup)?; + match s.execute("edit.transform", p) { + Ok(r) => { + let st = s.active_mut().ok_or(EngineError::NoDocument)?; + st.history.purge_last(); + st.history.set_current_label("Transform Again"); + Ok(r) + } + Err(e) => { + // The copy (e.g. of a layer whose position is locked) couldn't be transformed: take + // it back, leaving nothing to redo and no Duplicate step to record. + s.undo(); + s.journal.truncate(journal); + if let Some(st) = s.active_mut() { + st.history.clear_redo(); + } + Err(e) + } + } +} + +/// The `edit.transform` params that repeat the last transform on the active layer. +fn transform_again_params(s: &Session) -> Result { + let (_, last) = + s.journal.iter().rev().find(|(id, _)| id == "edit.transform").cloned().ok_or(EngineError::Other("there is no transform to repeat".into()))?; + let (rect, quad) = (last.get("rect").cloned(), last.get("quad").cloned()); + let mut p = json!({"interpolation": last.get("interpolation").cloned().unwrap_or(json!("bicubic"))}); + match (rect, quad, last.get("matrix").cloned()) { + (Some(r), Some(q), _) => { + let v = |x: &Value| -> Vec { x.as_array().map(|a| a.iter().filter_map(Value::as_f64).collect()).unwrap_or_default() }; + let r = v(&r); + let q: Vec> = q.as_array().map(|a| a.iter().map(v).collect()).unwrap_or_default(); + if r.len() != 4 || q.len() != 4 || q.iter().any(|row| row.len() < 2) { + return Err(EngineError::Other("the last transform can't be repeated".into())); + } + let h = photocraft_algo::transform::Homography::rect_to_quad( + [r[0], r[1], r[2], r[3]], + [[q[0][0], q[0][1]], [q[1][0], q[1][1]], [q[2][0], q[2][1]], [q[3][0], q[3][1]]], + ) + .ok_or(EngineError::Other("the last transform can't be repeated".into()))?; + let d = s.active().ok_or(EngineError::NoDocument)?; + let l = d.doc.layer(active_id(s)?).ok_or(EngineError::Other("no active layer".into()))?; + let b = crate::transform_cmds::transform_bounds(&d.doc, l); + if b.is_empty() { + return Err(EngineError::Other("nothing to transform".into())); + } + let nr = [b.x0 as f64, b.y0 as f64, b.x1 as f64, b.y1 as f64]; + let corners = [(nr[0], nr[1]), (nr[2], nr[1]), (nr[2], nr[3]), (nr[0], nr[3])].map(|(x, y)| { + let (a, b) = h.apply(x, y); + [a, b] + }); + p["rect"] = json!(nr); + p["quad"] = json!(corners); + } + (_, _, Some(m)) => p["matrix"] = m, + _ => return Err(EngineError::Other("the last transform can't be repeated".into())), + } + Ok(p) +} + +/// Guides further than this from the canvas origin are refused: far past any document (300000 px) +/// yet well within f32 precision. +const MAX_GUIDE_PX: f64 = 1_000_000.0; + +/// A guide `position` in document pixels: a number of pixels, or text with a unit as in Photoshop's +/// New Guide dialog ("50%", "2.5 cm", "12 pt"). Percent is of the document's width for a vertical +/// guide and its height for a horizontal one; points and picas follow Units & Rulers › Point Size. +/// `None` when there is no `position`. +fn guide_position(s: &Session, p: &Value, vertical: bool) -> Result> { + let Some(v) = p.get("position") else { return Ok(None) }; + let px = match (v.as_f64(), v.as_str()) { + (Some(n), _) => n, + (None, Some(text)) => { + let (n, unit) = crate::prefs::Unit::parse_length(text).ok_or_else(|| { + EngineError::Other(format!("`position` {text:?} is not a length: give a number of pixels, or a number with px, in, cm, mm, pt, pc or %")) + })?; + let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; + let extent = if vertical { doc.size.width } else { doc.size.height }; + unit.unwrap_or(crate::prefs::Unit::Pixels).to_px(n, doc.resolution_dpi as f64, extent as f64, s.prefs().units_and_rulers.point_size.per_inch()) + } + _ => return Err(EngineError::Other("`position` must be a number of pixels or text with a unit".into())), + }; + if !px.is_finite() || px.abs() > MAX_GUIDE_PX { + return Err(EngineError::Other(format!("`position` is out of range (at most {MAX_GUIDE_PX} px from the canvas origin)"))); + } + Ok(Some(px)) +} + +/// Photoshop's guide colours, in its order, by the names `view.newGuide` takes: New Guide's and +/// New Guide Layout's Color lists. Cyan (the default guide colour in Preferences, so a guide +/// dragged from a ruler reads as Cyan), Magenta and Yellow are the values New Guide Layout first +/// shipped with; the rest approximate Photoshop's on screen, rounded to web-safe steps. +pub const GUIDE_COLORS: [(&str, [u8; 3]); 9] = [ + ("lightBlue", [0x33, 0x66, 0xff]), + ("lightRed", [0xff, 0x33, 0x33]), + ("green", [0x33, 0xff, 0x33]), + ("mediumBlue", [0x33, 0x33, 0xff]), + ("yellow", [0xff, 0xcc, 0x00]), + ("magenta", [0xff, 0x00, 0xff]), + ("cyan", [0x4a, 0xff, 0xff]), + ("lightGray", [0xe7, 0xe7, 0xe7]), + ("black", [0x00, 0x00, 0x00]), +]; + +/// A guide `color`: one of [`GUIDE_COLORS`]' names or `"#rrggbb"`. `None` when there is no `color` +/// (the guide uses Preferences › Guides, Grid & Slices › Guide colour). +fn guide_color(p: &Value) -> Result> { + let Some(v) = p.get("color") else { return Ok(None) }; + let text = v.as_str().ok_or(EngineError::Other("`color` must be a colour name or \"#rrggbb\"".into()))?; + GUIDE_COLORS.iter().find(|(name, ..)| name.eq_ignore_ascii_case(text)).map(|(.., rgb)| *rgb).or_else(|| crate::prefs::parse_hex(text)).map(Some).ok_or_else( + || EngineError::Other(format!("`color` {text:?} is not a guide colour: use \"#rrggbb\" or one of {}", GUIDE_COLORS.map(|c| c.0).join(", "))), + ) +} + +/// Edit Selected Guides (the guide context menu): change one guide's orientation, position and +/// colour in one history step. A guide that keeps its orientation keeps its index; one that turns +/// goes to the end of the other list. Without `color` it keeps its own colour, or none. +fn edit_guide(s: &mut Session, p: &Value) -> Result { + let orientation = |key: &str| match p.get(key).map(|v| v.as_str()) { + None => Ok(None), + Some(Some("horizontal")) => Ok(Some(false)), + Some(Some("vertical")) => Ok(Some(true)), + Some(_) => Err(EngineError::Other(format!("`{key}` must be \"horizontal\" or \"vertical\""))), + }; + let from = orientation("orientation")?.unwrap_or(false); + let to = orientation("newOrientation")?.unwrap_or(from); + let index = p.get("index").and_then(Value::as_u64).ok_or(EngineError::Other("missing `index`".into()))?; + let pos = guide_position(s, p, to)?; + let color = guide_color(p)?; + s.edit("Edit Guide", |doc, _| { + let guides = &mut doc.guides; + let list = if from { &guides.vertical } else { &guides.horizontal }; + let i = usize::try_from(index).ok().filter(|i| *i < list.len()).ok_or(EngineError::Other("no such guide".into()))?; + let old = list[i]; + let at = pos.unwrap_or(old); + let rgb = color.or_else(|| guides.color(from, old)); + if from == to { + let list = if from { &mut guides.vertical } else { &mut guides.horizontal }; + list[i] = at; + } else { + (if from { &mut guides.vertical } else { &mut guides.horizontal }).remove(i); + (if to { &mut guides.vertical } else { &mut guides.horizontal }).push(at); + } + guides.prune_colors(); + if rgb.is_some() { + guides.set_color(to, at, rgb); + } + Ok(()) + })?; + Ok(Value::Null) +} + +/// View › New Guide / guide moves (undoable, like Photoshop's "New Guide"/"Move Guide" states). +fn guide_cmd(s: &mut Session, p: &Value, op: &str) -> Result { + let vertical = p.get("orientation").and_then(Value::as_str).unwrap_or("horizontal") == "vertical"; + let pos = guide_position(s, p, vertical)?; + let color = if op == "new" { guide_color(p)? } else { None }; + let index = p.get("index").and_then(Value::as_u64).map(|v| v as usize); + let label = match op { + "new" => "New Guide", + "move" => "Move Guide", + "delete" => "Delete Guide", + _ => "Clear Guides", + }; + s.edit(label, |doc, _| { + let guides = &mut doc.guides; + let g = if vertical { &mut guides.vertical } else { &mut guides.horizontal }; + match op { + "new" => { + let at = pos.ok_or(EngineError::Other("missing `position`".into()))?; + g.push(at); + if color.is_some() { + guides.set_color(vertical, at, color); + } + } + "move" => { + let i = index.filter(|i| *i < g.len()).ok_or(EngineError::Other("no such guide".into()))?; + let to = pos.ok_or(EngineError::Other("missing `position`".into()))?; + let from = std::mem::replace(&mut g[i], to); + // The guide takes its colour along; another guide left at the old position keeps it. + if let Some(rgb) = guides.color(vertical, from) { + guides.set_color(vertical, to, Some(rgb)); + } + guides.prune_colors(); + } + "delete" => { + let i = index.filter(|i| *i < g.len()).ok_or(EngineError::Other("no such guide".into()))?; + g.remove(i); + guides.prune_colors(); + } + _ => { + guides.horizontal.clear(); + guides.vertical.clear(); + guides.colors.clear(); + } + } + Ok(()) + })?; + Ok(Value::Null) +} + +/// Farthest the ruler zero point may sit from the image, in document pixels. +const MAX_RULER_ORIGIN: f64 = 1.0e7; + +/// Move the rulers' zero point (`view.setRulerOrigin`), or put it back at the image's top-left +/// (`view.resetRulerOrigin`, `p` = None). Undoable like the guides. +fn ruler_origin_cmd(s: &mut Session, p: Option<&Value>) -> Result { + let origin = match p { + None => [0.0, 0.0], + Some(p) => { + let axis = |k: &str| { + p.get(k) + .and_then(Value::as_f64) + .filter(|v| v.is_finite() && v.abs() <= MAX_RULER_ORIGIN) + .ok_or_else(|| EngineError::Other(format!("`{k}` must be a number of pixels within ±{MAX_RULER_ORIGIN}"))) + }; + [axis("x")?, axis("y")?] + } + }; + let label = if p.is_some() { "Set Ruler Origin" } else { "Reset Ruler Origin" }; + s.edit(label, |doc, _| { + doc.ruler_origin = origin; + Ok(()) + })?; + Ok(json!({"x": origin[0], "y": origin[1]})) +} + +pub fn specs() -> Vec { + macro_rules! spec { + ($id:expr, $label:expr, $menu:expr, $sc:expr, $params:expr, $enabled:expr, $run:expr) => { + CommandSpec { id: $id, label: $label, menu: $menu, shortcut: $sc, params: $params, enabled: $enabled, journal: true, run: $run } + }; + } + vec![ + spec!("edit.cut", "Cut", &["Edit"], Some("Cmd+X"), "{} (a targeted colour channel cuts that channel only)", has_pixels, |s, p| { + // Refuse a locked layer before copying, so a refused Cut leaves the clipboard alone. + let id = active_id(s)?; + crate::commands::check_pixels_unlocked(&s.active().ok_or(EngineError::NoDocument)?.doc, id)?; + // A targeted colour channel cuts that channel only (#2698). + if let Some(k) = crate::channel_clip::paste_color_target(s, p) { + return crate::channel_clip::cut(s, id, k); + } + let r = copy(s, false)?; + let bg = s.tools.background; + s.edit("Cut Pixels", |doc, _| clear_selected(doc, id, bg))?; + Ok(r) + }), + spec!( + "edit.copy", + "Copy", + &["Edit"], + Some("Cmd+C"), + r##"{"target":"mask|filterMask"? = the targeted mask, copied as grayscale (#2928)} (a targeted colour or alpha channel copies that channel, as grayscale)"##, + can_copy, + |s, p| { + if crate::commands::is_mask_target(p) { + return copy_mask(s, crate::channel_cmds::target_of(p) == crate::channel_cmds::Target::FilterMask); + } + match crate::channel_clip::copy(s)? { + Some(r) => Ok(r), + None => copy(s, false), + } + } + ), + spec!("edit.copyMerged", "Copy Merged", &["Edit"], Some("Cmd+Shift+C"), "{}", has_doc, |s, _| copy(s, true)), + spec!( + "edit.paste", + "Paste", + &["Edit"], + Some("Cmd+V"), + concat!( + r#"{"center":[x,y]? (view centre; default keeps the position when it overlaps the canvas),"clampToCanvas":bool=true (keep the paste on the canvas, or at its top-left when larger),"#, + paste_target!(), + "} (with no document open: a new document from the clipboard)" + ), + has_clip_only, + |s, p| paste(s, p, false) + ), + spec!( + "file.newFromClipboard", + "New from Clipboard", + &["File"], + None, + "{} (a new document the size of the clipboard image, holding it as one layer)", + has_clip_only, + |s, _| new_from_clipboard(s) + ), + spec!( + "edit.pasteSpecial.pasteInPlace", + "Paste in Place", + &["Edit", "Paste Special"], + Some("Cmd+Shift+V"), + concat!("{", paste_target!(), "}"), + has_clip, + |s, p| paste(s, p, true) + ), + spec!("layer.new.layerViaCopy", "Layer via Copy", &["Layer", "New"], Some("Cmd+J"), "{}", has_doc, |s, _| layer_via(s, false)), + spec!("layer.new.layerViaCut", "Layer via Cut", &["Layer", "New"], Some("Cmd+Shift+J"), "{}", has_pixels, |s, _| layer_via(s, true)), + spec!("layer.mergeVisible", "Merge Visible", &["Layer"], Some("Cmd+Shift+E"), "{}", has_doc, |s, _| merge_visible(s)), + spec!("image.autoTone", "Auto Tone", &["Image"], Some("Cmd+Shift+L"), "{}", has_pixels, |s, _| auto_adjust(s, "tone")), + spec!("image.autoContrast", "Auto Contrast", &["Image"], Some("Cmd+Alt+Shift+L"), "{}", has_pixels, |s, _| auto_adjust(s, "contrast")), + spec!("image.autoColor", "Auto Color", &["Image"], Some("Cmd+Shift+B"), "{}", has_pixels, |s, _| auto_adjust(s, "color")), + spec!("edit.toggleLastState", "Toggle Last State", &["Edit"], Some("Cmd+Alt+Z"), "{}", has_doc, |s, _| toggle_last_state(s)), + spec!("edit.transform.again", "Again", &["Edit", "Transform"], Some("Cmd+Shift+T"), "{}", has_doc, |s, _| transform_again(s)), + spec!( + "edit.transform.againCopy", + "Transform Again on a Copy", + &[], + Some("Cmd+Alt+Shift+T"), + "{} (duplicates the active layer and repeats the last transform on the copy: step and repeat)", + has_doc, + |s, _| transform_again_copy(s) + ), + spec!( + "view.newGuide", + "New Guide…", + &["View"], + None, + r##"{"orientation":"horizontal|vertical","position":px or "","color":"lightBlue|lightRed|green|mediumBlue|yellow|magenta|cyan|lightGray|black" or "#rrggbb"?} (units px, in, cm, mm, pt, pc or %; % is of the width for a vertical guide, the height for a horizontal one; without a color the guide uses the guide colour in Preferences)"##, + has_doc, + |s, p| guide_cmd(s, p, "new") + ), + spec!( + "view.moveGuide", + "Move Guide", + &[], + None, + r##"{"orientation":"horizontal|vertical","index":n,"position":px or ""} (units as for view.newGuide)"##, + has_doc, + |s, p| guide_cmd(s, p, "move") + ), + spec!( + "view.editGuide", + "Edit Guide", + &[], + None, + r##"{"orientation":"horizontal|vertical","index":n,"newOrientation":"horizontal|vertical"?,"position":px or ""?,"color":name or "#rrggbb"?} (Edit Selected Guides: units and colours as for view.newGuide; % is of the new orientation's extent; whatever is left out stays as it was)"##, + has_doc, + edit_guide + ), + spec!("view.deleteGuide", "Delete Guide", &[], None, r##"{"orientation":"horizontal|vertical","index":n}"##, has_doc, |s, p| guide_cmd(s, p, "delete")), + spec!("view.clearGuides", "Clear Guides", &["View"], None, "{}", has_doc, |s, p| guide_cmd(s, p, "clear")), + spec!( + "view.setRulerOrigin", + "Set Ruler Origin", + &[], + None, + r##"{"x":px,"y":px} (the rulers' zero point in document pixels; the rulers and Info panel measure from it)"##, + has_doc, + |s, p| ruler_origin_cmd(s, Some(p)) + ), + spec!("view.resetRulerOrigin", "Reset Ruler Origin", &[], None, "{} (zero point back at the image's top-left)", has_doc, |s, _| ruler_origin_cmd( + s, None + )), + ] +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/edit_cmds/tests.rs b/crates/engine/src/cmd/edit_cmds/tests.rs new file mode 100644 index 0000000000..e632d9fb71 --- /dev/null +++ b/crates/engine/src/cmd/edit_cmds/tests.rs @@ -0,0 +1,1465 @@ +use super::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 100, "height": 100})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.edit("paint", |doc, a| { + doc.layer_mut(a.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(10, 10, 50, 30), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + s +} + +#[test] +fn new_clipboard_document_rejects_an_unrepresentable_origin() { + let mut s = Session::new(); + let mut surface = Surface::new(PixelFormat::RGBA8); + surface.write_pixel(i32::MIN, 0, &[1.0, 0.0, 0.0, 1.0]); + s.clipboard = Some(Clip { surface, bounds: Rect::from_xywh(i32::MIN, 0, 1, 1), layers: None, resolution: None, source: None }); + let result = new_from_clipboard(&mut s); + assert!(result.unwrap_err().to_string().contains("clipboard origin")); + assert!(s.execute("file.newFromClipboard", json!({})).is_err()); + assert!(s.documents().is_empty()); + assert_eq!(s.clipboard.as_ref().unwrap().surface.rgba(i32::MIN, 0), [1.0, 0.0, 0.0, 1.0]); +} + +/// #8945: pixels copied in one document land in place when pasted back into it, and centred +/// in another, even where their old position would fit (Photoshop's Paste). +#[test] +fn paste_centres_pixels_from_another_document() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 40, "height": 30, "background": "white"})).unwrap(); + s.execute("select.all", json!({})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + let r = s.execute("edit.paste", json!({})).unwrap(); + assert_eq!(r["offset"], json!([0, 0]), "back into its own document: in place"); + s.execute("file.new", json!({"width": 100, "height": 80, "background": "white"})).unwrap(); + let r = s.execute("edit.paste", json!({})).unwrap(); + assert_eq!(r["offset"], json!([30, 25]), "into another document: centred"); + // An image from another app has no source document: centred too. + s.clipboard = s.clipboard.take().map(|c| Clip { source: None, ..c }); + let r = s.execute("edit.paste", json!({})).unwrap(); + assert_eq!(r["offset"], json!([30, 25])); + // Paste in Place still keeps the position. + let r = s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap(); + assert_eq!(r["offset"], json!([0, 0])); +} + +#[test] +fn paste_centers_clipboard_bounds_near_coordinate_limits() { + for origin in [i32::MAX - 512, i32::MIN + 512] { + let clip = + Clip { surface: Surface::new(PixelFormat::RGBA8), bounds: Rect::from_xywh(origin, origin, 2, 2), layers: None, resolution: None, source: None }; + let (dx, dy) = paste_offset(&clip, DocId(1), Rect::new(0, 0, 20, 20), &json!({}), false); + assert_eq!(i64::from(origin) + i64::from(dx), 9); + assert_eq!(i64::from(origin) + i64::from(dy), 9); + let clip = Clip { bounds: Rect::new(0, 0, 2, 2), ..clip }; + let (dx, dy) = paste_offset(&clip, DocId(1), Rect::from_xywh(origin, origin, 20, 20), &json!({}), false); + assert_eq!(dx, origin + 9); + assert_eq!(dy, origin + 9); + } +} + +#[test] +fn injected_clear_buffer_failure_leaves_the_document_unchanged() { + let mut s = session(); + let st = s.active().unwrap(); + let id = st.active_layer.unwrap(); + let before = st.doc.layer(id).unwrap().surface().unwrap().clone(); + let revision = st.revision; + + crate::allocation::fail_next_for_test(); + let result = s.execute("edit.clear", json!({})); + + assert!(result.as_ref().is_err_and(|e| e.to_string().contains("not enough memory for erasing pixels"))); + let st = s.active().unwrap(); + assert_eq!(st.doc.layer(id).unwrap().surface(), Some(&before)); + assert_eq!(st.revision, revision); +} + +#[test] +fn injected_copy_buffer_failure_does_not_change_document_or_clipboard() { + let mut s = session(); + let st = s.active().unwrap(); + let id = st.active_layer.unwrap(); + let before = st.doc.layer(id).unwrap().surface().unwrap().clone(); + let revision = st.revision; + + crate::allocation::fail_next_for_test(); + let result = s.execute("edit.copy", json!({})); + + assert!(result.as_ref().is_err_and(|e| e.to_string().contains("not enough memory for copying pixels"))); + let st = s.active().unwrap(); + assert_eq!(st.doc.layer(id).unwrap().surface(), Some(&before)); + assert_eq!(st.revision, revision); + assert!(s.clipboard.is_none()); +} + +#[test] +fn injected_fill_result_reservation_failure_keeps_pixels_and_history() { + let mut s = session(); + let st = s.active().unwrap(); + let id = st.active_layer.unwrap(); + let before = st.doc.layer(id).unwrap().surface().unwrap().clone(); + let revision = st.revision; + let history_len = st.history.past_len(); + + crate::allocation::fail_next_for_test(); + let result = s.execute("edit.fill", json!({"color": "#00ff00"})); + + assert!(result.as_ref().is_err_and(|e| e.to_string().contains("not enough memory for blending pixels"))); + let st = s.active().unwrap(); + assert_eq!(st.doc.layer(id).unwrap().surface(), Some(&before)); + assert_eq!(st.revision, revision); + assert_eq!(st.history.past_len(), history_len); +} + +#[test] +fn injected_paste_failure_does_not_change_document_or_clipboard() { + let mut s = session(); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 8, "height": 8})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + let before_clip = s.clipboard.clone(); + let st = s.active().unwrap(); + let before_doc = (*st.doc).clone(); + let revision = st.revision; + let history_len = st.history.past_len(); + + crate::allocation::fail_next_for_test(); + let result = s.execute("edit.paste", json!({})); + + assert!(result.as_ref().is_err_and(|e| e.to_string().contains("not enough memory for pasting pixels"))); + let st = s.active().unwrap(); + assert_eq!(*st.doc, before_doc); + assert_eq!(st.revision, revision); + assert_eq!(st.history.past_len(), history_len); + let after_clip = s.clipboard.as_ref().expect("clipboard remains available"); + let before_clip = before_clip.as_ref().expect("clipboard was populated"); + assert_eq!(after_clip.bounds, before_clip.bounds); + assert_eq!(after_clip.surface, before_clip.surface); +} + +#[test] +fn injected_transform_failure_keeps_pixels_and_history() { + let mut s = session(); + let st = s.active().unwrap(); + let id = st.active_layer.unwrap(); + let before = st.doc.layer(id).unwrap().surface().unwrap().clone(); + let revision = st.revision; + let history_len = st.history.past_len(); + + crate::allocation::fail_next_for_test(); + let result = s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 20, 30]})); + + assert!(result.as_ref().is_err_and(|e| e.to_string().contains("not enough memory for transforming pixels"))); + let st = s.active().unwrap(); + assert_eq!(st.doc.layer(id).unwrap().surface(), Some(&before)); + assert_eq!(st.revision, revision); + assert_eq!(st.history.past_len(), history_len); +} + +fn active_bounds(s: &Session) -> Rect { + let st = s.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds() +} + +/// New from Clipboard takes the copied document's resolution (Photoshop's Clipboard preset), +/// so a later Image Size by resolution scales from the right size. +#[test] +fn new_from_clipboard_keeps_the_source_resolution() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 60, "height": 40, "resolution": 300})).unwrap(); + s.execute("select.all", json!({})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + s.execute("file.newFromClipboard", json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc.resolution_dpi, 300.0); +} + +/// #368: the clipboard as a document of its own, from New from Clipboard or a Paste with +/// nothing open, at every depth. +#[test] +fn new_from_clipboard_and_paste_with_no_document() { + for depth in [8, 16, 32] { + let mut s = Session::new(); + assert!(!s.is_enabled("file.newFromClipboard") && !s.is_enabled("edit.paste"), "nothing copied yet"); + assert!(s.execute("file.newFromClipboard", json!({})).is_err()); + s.execute("file.new", json!({"width": 100, "height": 100, "depth": depth})).unwrap(); + assert!(!s.active().unwrap().is_dirty(), "an untouched blank document is clean"); + s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + s.execute("select.rect", json!({"x": 10, "y": 20, "width": 30, "height": 15})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + // With a document open: a second document, sized to the copy, its pixels at the origin. + let r = s.execute("file.newFromClipboard", json!({})).unwrap(); + assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(30), Some(15)), "{r}"); + assert_eq!(s.documents().len(), 2); + assert!(s.active().unwrap().is_dirty(), "a document made from clipboard pixels needs saving (#4665)"); + let d = &s.active().unwrap().doc; + assert_eq!((d.size.width, d.size.height, d.layers.len()), (30, 15, 1)); + assert_eq!(d.pixel_format().sample, s.documents()[0].doc.pixel_format().sample, "{depth}-bit kept"); + assert_eq!(active_bounds(&s), Rect::new(0, 0, 30, 15)); + let px = d.layers[0].surface().unwrap().rgba(0, 0); + assert!(px[0] > 0.99 && px[1] < 0.01 && px[3] > 0.99, "{px:?}"); + // With nothing open, Paste makes the document too. + while s.active().is_some() { + s.execute("file.close", json!({})).unwrap(); + } + assert!(s.is_enabled("edit.paste") && !s.is_enabled("edit.pasteSpecial.pasteInPlace")); + s.execute("edit.paste", json!({})).unwrap(); + assert_eq!(s.documents().len(), 1); + assert!(s.active().unwrap().is_dirty(), "Paste with no tab also needs a save prompt"); + assert_eq!(active_bounds(&s), Rect::new(0, 0, 30, 15)); + assert!(s.execute("edit.pasteSpecial.pasteInPlace", json!({})).is_ok(), "into the new document"); + } +} + +#[test] +fn copy_paste_in_place_and_centred() { + let mut s = session(); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap(); + assert_eq!(active_bounds(&s), Rect::new(10, 10, 30, 30)); + assert!(s.active().unwrap().doc.selection.is_none()); + s.execute("edit.paste", json!({"center": [70, 70]})).unwrap(); + assert_eq!(active_bounds(&s), Rect::new(60, 60, 80, 80)); + assert_eq!(s.active().unwrap().doc.layers.len(), 4); +} + +/// A `w`×`h` document with an opaque `cw`×`ch` image from another app on the clipboard. +fn external_clip_session(w: i32, h: i32, cw: i32, ch: i32) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": w, "height": h})).unwrap(); + let mut surface = Surface::new(PixelFormat::RGBA8); + surface.fill_rect(Rect::new(0, 0, cw, ch), &[1.0, 0.0, 0.0, 1.0]); + s.clipboard = Some(Clip { surface, bounds: Rect::new(0, 0, cw, ch), layers: None, resolution: None, source: None }); + s +} + +/// #6759: wherever the view is centred, a paste that fits the canvas stays wholly on it. +#[test] +fn paste_that_fits_stays_on_the_canvas() { + for (w, h, center, want) in [ + (60, 100, [40.0, 45.0], Rect::new(0, 0, 60, 100)), + (60, 100, [-500.0, 900.0], Rect::new(0, 0, 60, 100)), + (100, 100, [10.0, 80.0], Rect::new(0, 0, 60, 100)), + (100, 100, [95.0, 50.0], Rect::new(40, 0, 100, 100)), + (100, 120, [50.0, 60.0], Rect::new(20, 10, 80, 110)), + ] { + let mut s = external_clip_session(w, h, 60, 100); + s.execute("edit.paste", json!({ "center": center })).unwrap(); + assert_eq!(active_bounds(&s), want, "{w}x{h} canvas, view centre {center:?}"); + } +} + +/// #6759: a paste larger than the canvas starts at its top-left corner, wherever the view is. +#[test] +fn paste_larger_than_the_canvas_starts_at_its_top_left() { + for center in [[0.0, 0.0], [25.0, 20.0], [1000.0, 1000.0], [-1000.0, 30.0]] { + let mut s = external_clip_session(50, 40, 60, 100); + s.execute("edit.paste", json!({ "center": center })).unwrap(); + assert_eq!(active_bounds(&s), Rect::new(0, 0, 60, 100), "view centre {center:?}"); + } + // Wider but not taller: at the left edge, and wholly inside vertically. + for (center, want) in + [([500.0, 500.0], Rect::new(0, 100, 60, 200)), ([-500.0, -500.0], Rect::new(0, 0, 60, 100)), ([25.0, 120.0], Rect::new(0, 70, 60, 170))] + { + let mut s = external_clip_session(50, 200, 60, 100); + s.execute("edit.paste", json!({ "center": center })).unwrap(); + assert_eq!(active_bounds(&s), want, "view centre {center:?}"); + } +} + +/// Paste Into centres on the selection even where that runs off the canvas. +#[test] +fn paste_into_is_not_clamped_to_the_canvas() { + let mut s = session(); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 40, "height": 20})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + s.execute("select.rect", json!({"x": 90, "y": 90, "width": 10, "height": 10})).unwrap(); + s.execute("edit.pasteSpecial.pasteInto", json!({})).unwrap(); + assert_eq!(active_bounds(&s), Rect::new(75, 85, 115, 105)); +} + +/// The clamp never overflows or panics: NaN, infinite and `i32`-limit shifts saturate (Rule 9). +#[test] +fn paste_offset_clamp_survives_extreme_coordinates() { + assert_eq!(clamp_shift(f64::NAN, 0, 10, 0, 100), 0); + assert_eq!(clamp_shift(f64::INFINITY, 0, 10, 0, 100), 90); + assert_eq!(clamp_shift(f64::NEG_INFINITY, i32::MIN, i32::MAX, 0, 1), i32::MAX); + assert_eq!(clamp_shift(1e30, i32::MIN, i32::MIN + 1, i32::MAX - 1, i32::MAX), i32::MAX); + let clip = Clip { + surface: Surface::new(PixelFormat::RGBA8), + bounds: Rect::new(i32::MAX - 2, i32::MAX - 2, i32::MAX, i32::MAX), + layers: None, + resolution: None, + source: None, + }; + let (dx, dy) = paste_offset(&clip, DocId(1), Rect::new(i32::MIN, i32::MIN, i32::MIN + 4, i32::MIN + 4), &json!({}), false); + assert_eq!((dx, dy), (i32::MIN, i32::MIN), "an unrepresentable shift saturates instead of wrapping"); +} + +#[test] +fn paste_with_malformed_center_does_not_panic() { + // A short/empty `center` array must not panic (Rule 9) — it falls back to the canvas centre. + let mut s = session(); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + for center in [json!([5]), json!([]), json!("nope"), json!([1, 2, 3])] { + // Fresh clipboard each time is unnecessary; copy persists. Must return Ok, never panic. + assert!(s.execute("edit.paste", json!({ "center": center })).is_ok(), "center={center}"); + } +} + +#[test] +fn copy_paste_between_documents() { + // Copy in one tab, paste into another: the clipboard is shared across documents. + let mut s = session(); // doc A (100x100): red rect at (10,10)-(50,30) + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 40, "height": 20})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + // Open a second document (a new tab), which becomes active. + s.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); + assert_eq!(s.active_index().unwrap(), 1, "the new document is the active tab"); + let before = s.active().unwrap().doc.layers.len(); + s.execute("edit.paste", json!({})).unwrap(); + assert_eq!(s.active_index().unwrap(), 1, "paste stays in the second tab"); + let d = &s.active().unwrap().doc; + assert_eq!(d.layers.len(), before + 1, "pasted layer added to the second document"); + let pasted = d.layers.last().unwrap().surface().unwrap(); + let cb = pasted.content_bounds(); + let (cx, cy) = (cb.x0 + cb.width() as i32 / 2, cb.y0 + cb.height() as i32 / 2); + let mut px = [[0.0f32; 4]; 1]; + pasted.read_rgba_into(Rect::new(cx, cy, cx + 1, cy + 1), &mut px); + assert!(px[0][0] > 0.9 && px[0][1] < 0.1 && px[0][2] < 0.1, "pasted content is red: {:?}", px[0]); +} + +/// #2901 (P10/P11): Paste, Paste in Place and Paste Into recomposite only where the pasted +/// layer draws, not the whole document; nothing outside that changes, and undo brings back +/// exactly the old pixels. +#[test] +fn paste_damages_only_the_pasted_layer() { + let render = |s: &Session| photocraft_compose::render(&s.active().unwrap().doc, s.active().unwrap().doc.bounds()); + for depth in [8, 16, 32] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 60, "height": 50, "depth": depth, "background": "white"})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("select.rect", json!({"x": 5, "y": 5, "width": 10, "height": 8})).unwrap(); + s.execute("edit.fill", json!({"color": "#3366cc"})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + // Half transparent, so an opaque copy pasted in place over it shows. + s.execute("layer.setProps", json!({"opacity": 0.5})).unwrap(); + for (id, p) in [ + ("edit.paste", json!({"center": [40, 30]})), + ("edit.pasteSpecial.pasteInPlace", json!({})), + ("edit.pasteSpecial.pasteInto", json!({"center": [40, 30]})), + ] { + s.execute("select.rect", json!({"x": 36, "y": 27, "width": 6, "height": 4})).unwrap(); + let shown = render(&s); + s.execute(id, p).unwrap(); + let st = s.active().unwrap(); + let area = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds(); + let damage = st.last_damage.unwrap_or_else(|| panic!("{depth}-bit {id}: bounded damage")); + assert!(!damage.is_empty() && damage.intersect(&area) == damage, "{depth}-bit {id}: {damage:?} within {area:?}"); + let now = render(&s); + assert_ne!(now, shown, "{depth}-bit {id}: the paste shows"); + let w = shown.rect.width() as usize; + for (i, (a, b)) in shown.px.iter().zip(&now.px).enumerate() { + if !damage.contains((i % w) as i32, (i / w) as i32) { + assert_eq!(a, b, "{depth}-bit {id}: pixel {i} outside the damage changed"); + } + } + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(render(&s), shown, "{depth}-bit {id}: undo"); + } + } +} + +/// #1035: a `depth`-bit document with a blue-grey square copied from layer `src` (at +/// (5,5)-(15,15)) and an active layer `m` above it with a hide-all mask. +fn mask_target_session(depth: u32) -> (Session, LayerId, LayerId) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 40, "height": 40, "depth": depth})).unwrap(); + let src = LayerId(s.execute("layer.new.layer", json!({"name": "src"})).unwrap()["layer"].as_u64().unwrap()); + s.execute("select.rect", json!({"x": 5, "y": 5, "width": 10, "height": 10})).unwrap(); + s.execute("edit.fill", json!({"color": "#3366cc"})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + let m = LayerId(s.execute("layer.new.layer", json!({"name": "m"})).unwrap()["layer"].as_u64().unwrap()); + s.execute("layer.layerMask.hideAll", json!({})).unwrap(); + (s, src, m) +} + +/// The luminosity of `src`'s pixel at (`x`, `y`): what a paste into a mask writes there. +fn luminosity(s: &Session, src: LayerId, x: i32, y: i32) -> f32 { + let p = s.active().unwrap().doc.layer(src).unwrap().surface().unwrap().rgba(x, y); + photocraft_color::convert::rgb_to_gray([p[0], p[1], p[2]]) +} + +fn mask_at(s: &Session, id: LayerId, x: i32, y: i32) -> f32 { + s.active().unwrap().doc.layer(id).unwrap().mask.as_ref().unwrap().value(x, y) +} + +#[test] +fn paste_into_a_targeted_mask_writes_the_luminosity_in_one_step() { + for depth in [8, 16, 32] { + let (mut s, src, m) = mask_target_session(depth); + let lum = luminosity(&s, src, 10, 10); + assert!(lum > 0.05 && lum < 0.95, "{depth}-bit: a mid grey ({lum})"); + let (layers, steps) = (s.active().unwrap().doc.layer_count(), s.active().unwrap().history.past_len()); + s.execute("edit.pasteSpecial.pasteInPlace", json!({"target": "mask"})).unwrap(); + let st = s.active().unwrap(); + assert_eq!(st.doc.layer_count(), layers, "{depth}-bit: no new layer"); + assert_eq!(st.history.past_len(), steps + 1, "{depth}-bit: one history step"); + assert_eq!(st.active_layer, Some(m)); + assert!((mask_at(&s, m, 10, 10) - lum).abs() < 2.0 / 255.0, "{depth}-bit: {} vs {lum}", mask_at(&s, m, 10, 10)); + assert_eq!(mask_at(&s, m, 20, 20), 0.0, "{depth}-bit: the mask outside the paste is unchanged"); + assert!(st.doc.layer(m).unwrap().surface().unwrap().content_bounds().is_empty(), "{depth}-bit: the pixels are untouched"); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(mask_at(&s, m, 10, 10), 0.0, "{depth}-bit: undo restores the mask"); + } +} + +#[test] +fn copy_with_the_mask_targeted_takes_the_mask_as_grayscale() { + for depth in [8, 16, 32] { + let (mut s, _, m) = mask_target_session(depth); + s.edit("paint mask", |doc, _| { + doc.layer_mut(m).unwrap().mask.as_mut().unwrap().surface.fill_rect(Rect::new(6, 6, 16, 12), &[0.75]); + Ok(()) + }) + .unwrap(); + let steps = s.active().unwrap().history.past_len(); + let r = s.execute("edit.copy", json!({"target": "mask"})).unwrap(); + assert_eq!(r["bounds"], json!([0, 0, 40, 40]), "{depth}-bit: a mask copies whole, as in Photoshop"); + assert_eq!(s.active().unwrap().history.past_len(), steps, "{depth}-bit: copy adds no history step"); + let clip = s.clipboard.clone().unwrap(); + let px = clip.surface.rgba(10, 10); + assert!((px[0] - 0.75).abs() < 2.0 / 255.0, "{depth}-bit: {} vs 0.75", px[0]); + assert!(clip.surface.rgba(30, 30)[0] < 0.01, "{depth}-bit: the hidden area copies as black"); + assert!(px[3] > 0.99, "{depth}-bit: the copy is opaque"); + // Paste it into another layer's reveal-all mask: it replaces that mask (the request + // in #2928): the square, and the black around it, land. + let m2 = LayerId(s.execute("layer.new.layer", json!({"name": "m2"})).unwrap()["layer"].as_u64().unwrap()); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + s.execute("edit.pasteSpecial.pasteInPlace", json!({"target": "mask"})).unwrap(); + assert!((mask_at(&s, m2, 10, 10) - 0.75).abs() < 2.0 / 255.0, "{depth}-bit: the copied mask lands"); + assert!(mask_at(&s, m2, 30, 30) < 0.01, "{depth}-bit: the copied black replaces the reveal-all"); + } +} + +#[test] +fn an_untouched_mask_copies_the_whole_canvas_at_its_default() { + let (mut s, _, _) = mask_target_session(8); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + let r = s.execute("edit.copy", json!({"target": "mask"})).unwrap(); + assert_eq!(r["bounds"], json!([0, 0, 40, 40]), "a plain Reveal All mask still transfers"); + assert!(s.clipboard.clone().unwrap().surface.rgba(20, 20)[0] > 0.99); +} + +#[test] +fn mask_copy_takes_only_the_selection() { + let (mut s, _, m) = mask_target_session(8); + s.edit("paint mask", |doc, _| { + doc.layer_mut(m).unwrap().mask.as_mut().unwrap().surface.fill_rect(Rect::new(6, 6, 16, 12), &[0.75]); + Ok(()) + }) + .unwrap(); + s.execute("select.rect", json!({"x": 8, "y": 8, "width": 4, "height": 4})).unwrap(); + let r = s.execute("edit.copy", json!({"target": "mask"})).unwrap(); + assert_eq!(r["bounds"], json!([8, 8, 4, 4])); + let clip = s.clipboard.clone().unwrap(); + assert!((clip.surface.rgba(9, 9)[0] - 0.75).abs() < 2.0 / 255.0); + assert!(clip.surface.rgba(5, 5)[3] < 0.01, "nothing outside the selection"); +} + +#[test] +fn mask_copy_needs_a_mask_and_fails_gracefully() { + let mut s = Session::new(); + assert!(s.execute("edit.copy", json!({"target": "mask"})).is_err(), "no document"); + s.execute("file.new", json!({"width": 20, "height": 20})).unwrap(); + assert!(s.execute("edit.copy", json!({"target": "mask"})).is_err(), "the layer has no mask"); + assert!(s.clipboard.is_none(), "a refused copy leaves the clipboard alone"); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + assert!(s.execute("edit.copy", json!({"target": "mask"})).is_ok()); + // An adjustment layer has no pixels of its own: Copy takes the layer whole (#2344), and + // its mask while that is targeted (#2928). + s.execute("file.new", json!({"width": 20, "height": 20})).unwrap(); + let a = s.execute("layer.newAdjustmentLayer.levels", json!({})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.select", json!({"layer": a})).unwrap(); + assert!(s.is_enabled("edit.copy"), "the layer itself can be copied"); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + assert!(s.is_enabled_with("edit.copy", &json!({"target": "mask"})), "the mask can be copied"); +} + +#[test] +fn a_copied_mask_travels_to_another_document() { + let (mut s, _, m) = mask_target_session(8); + s.edit("paint mask", |doc, _| { + doc.layer_mut(m).unwrap().mask.as_mut().unwrap().surface.fill_rect(Rect::new(6, 6, 16, 12), &[0.75]); + Ok(()) + }) + .unwrap(); + s.execute("edit.copy", json!({"target": "mask"})).unwrap(); + s.execute("file.new", json!({"width": 40, "height": 40})).unwrap(); + let n = LayerId(s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap()); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + s.execute("edit.pasteSpecial.pasteInPlace", json!({"target": "mask"})).unwrap(); + assert!((mask_at(&s, n, 10, 10) - 0.75).abs() < 2.0 / 255.0, "the mask arrived in the second document"); + assert!(mask_at(&s, n, 30, 30) < 0.01, "it replaced the reveal-all mask there"); +} + +#[test] +fn paste_follows_the_mask_view_and_is_placed_like_a_paste() { + let (mut s, src, m) = mask_target_session(8); + let lum = luminosity(&s, src, 10, 10); + // ⌥-click the mask thumbnail: the canvas shows the mask, and pasting targets it. + s.execute(crate::mask_view_cmds::ID, json!({"layer": m.0, "mode": "gray"})).unwrap(); + let r = s.execute("edit.paste", json!({"center": [30, 30]})).unwrap(); + assert_eq!(r["offset"], json!([20, 20])); + assert!((mask_at(&s, m, 30, 30) - lum).abs() < 2.0 / 255.0); + assert_eq!(mask_at(&s, m, 10, 10), 0.0); + assert_eq!(s.active().unwrap().doc.layers.len(), 3, "Background, src, m"); +} + +#[test] +fn paste_into_and_outside_a_targeted_mask_keep_to_the_selection() { + let (mut s, src, m) = mask_target_session(16); + let lum = luminosity(&s, src, 10, 10); + // The paste is centred on the selection, so lands in place: only the selection takes it. + s.execute("select.rect", json!({"x": 8, "y": 8, "width": 4, "height": 4})).unwrap(); + s.execute("edit.pasteSpecial.pasteInto", json!({"target": "mask"})).unwrap(); + assert!((mask_at(&s, m, 9, 9) - lum).abs() < 2.0 / 255.0); + assert_eq!(mask_at(&s, m, 7, 7), 0.0, "pasted, but outside the selection"); + assert!(s.active().unwrap().doc.selection.is_none()); + assert_eq!(s.active().unwrap().doc.layers.len(), 3, "no new layer"); + s.execute("layer.layerMask.hideAll", json!({})).unwrap(); + s.execute("select.rect", json!({"x": 8, "y": 8, "width": 4, "height": 4})).unwrap(); + s.execute("edit.pasteSpecial.pasteOutside", json!({"target": "mask"})).unwrap(); + assert_eq!(mask_at(&s, m, 9, 9), 0.0, "Paste Outside leaves the selection alone"); + assert!((mask_at(&s, m, 7, 7) - lum).abs() < 2.0 / 255.0); +} + +#[test] +fn paste_follows_a_targeted_alpha_channel() { + let (mut s, src, _) = mask_target_session(8); + let lum = luminosity(&s, src, 10, 10); + s.execute("channel.new", json!({})).unwrap(); + s.execute("edit.pasteSpecial.pasteInPlace", json!({"target": {"channel": 0}})).unwrap(); + let c = &s.active().unwrap().doc.channels[0].surface; + assert!((c.sample_channel(10, 10, 0) - lum).abs() < 2.0 / 255.0); + assert_eq!(s.active().unwrap().doc.layers.len(), 3, "no new layer"); +} + +#[test] +fn paste_into_a_missing_mask_or_channel_is_an_error() { + let (mut s, _, m) = mask_target_session(8); + s.edit("drop mask", |doc, _| { + doc.layer_mut(m).unwrap().mask = None; + Ok(()) + }) + .unwrap(); + let layers = s.active().unwrap().doc.layer_count(); + for target in [json!("mask"), json!({"channel": 7}), json!("quickMask")] { + for id in ["edit.paste", "edit.pasteSpecial.pasteInPlace"] { + assert!(s.execute(id, json!({ "target": target })).is_err(), "{id} {target}"); + } + } + assert_eq!(s.active().unwrap().doc.layer_count(), layers, "nothing pasted as a layer"); +} + +#[test] +fn paste_between_different_color_modes() { + // Copy from an RGB document, paste into a Grayscale one: the clipboard converts to the + // target document's format (a realistic between-tabs case that must not panic). + let mut s = session(); // RGB, red rect + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 40, "height": 20})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + s.execute("file.new", json!({"width": 120, "height": 120, "mode": "gray"})).unwrap(); + s.execute("edit.paste", json!({})).unwrap(); + let d = &s.active().unwrap().doc; + assert_eq!(d.mode, photocraft_doc::ColorMode::Grayscale); + let pasted = d.layers.last().unwrap().surface().unwrap(); + assert_eq!(pasted.format().mode, photocraft_color::ColorMode::Grayscale, "pasted layer is grayscale"); + assert!(!pasted.content_bounds().is_empty(), "pasted content exists"); +} + +#[test] +fn transform_scale_grows_content() { + let mut s = session(); // red rect (10,10)-(50,30): 40x20 + s.execute("edit.transform", json!({"matrix": [2, 0, 0, 2, 0, 0]})).unwrap(); + let d = &s.active().unwrap().doc; + let cb = d.layers.last().unwrap().surface().unwrap().content_bounds(); + // Scaled ~2x about the origin (≈ 80x40 at ≈ (20,20)); allow ~1px bilinear edge bleed. + assert!((cb.x0 - 20).abs() <= 2 && (cb.y0 - 20).abs() <= 2, "origin ~ (20,20): {cb:?}"); + assert!((cb.width() as i32 - 80).abs() <= 3 && (cb.height() as i32 - 40).abs() <= 3, "size ~ 80x40: {cb:?}"); +} + +#[test] +fn cut_and_clear_on_the_background_fill_with_the_background_colour() { + // The Background keeps its transparency lock: cutting fills with the background colour. + let fresh = || { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 40, "height": 30})).unwrap(); + s.tools.background = [1.0, 0.0, 0.0, 1.0]; + s.execute("select.rect", json!({"x": 5, "y": 5, "width": 10, "height": 10})).unwrap(); + s + }; + let px = |s: &Session, i: usize, x: i32, y: i32| s.active().unwrap().doc.layers[i].surface().unwrap().pixel(x, y); + for cmd in ["edit.cut", "edit.clear", "layer.new.layerViaCut"] { + let mut s = fresh(); + s.execute(cmd, json!({})).unwrap(); + let d = &s.active().unwrap().doc; + assert!(d.is_background(d.layers[0].id), "{cmd}: still the Background"); + assert_eq!(px(&s, 0, 8, 8), vec![1.0, 0.0, 0.0, 1.0], "{cmd}: cut area is the background colour"); + assert_eq!(px(&s, 0, 30, 20), vec![1.0, 1.0, 1.0, 1.0], "{cmd}: outside untouched"); + } + // Layer via Cut still lifts the original pixels onto the new layer. + let mut s = fresh(); + s.execute("layer.new.layerViaCut", json!({})).unwrap(); + assert_eq!(px(&s, 1, 8, 8), vec![1.0, 1.0, 1.0, 1.0]); + // Once it's a normal layer, cutting makes transparency again. + let mut s = fresh(); + s.execute("layer.new.layerFromBackground", json!({})).unwrap(); + s.execute("edit.clear", json!({})).unwrap(); + assert_eq!(px(&s, 0, 8, 8)[3], 0.0); +} + +#[test] +fn layer_via_copy_of_a_background_keeps_colour_and_partial_selection() { + // #668: lift reads only the selected area now; the result must be what converting the + // whole layer gave: the colour, with the selection's coverage as alpha. + for depth in [8, 16, 32] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 40, "height": 30, "depth": depth, "background": "#336699"})).unwrap(); + s.edit("partial selection", |doc, _| { + let mut m = photocraft_raster::Surface::new(PixelFormat::GRAY8); + m.fill_rect(Rect::new(5, 5, 15, 15), &[1.0]); + m.fill_rect(Rect::new(15, 5, 20, 15), &[0.5]); + doc.selection = Some(m); + Ok(()) + }) + .unwrap(); + let id = s.execute("layer.new.layerViaCopy", json!({})).unwrap()["layer"].as_u64().unwrap(); + let d = s.active().unwrap(); + let surf = d.doc.layer(LayerId(id)).unwrap().surface().unwrap(); + assert!(surf.format().alpha, "@{depth}"); + let full = surf.read_region(Rect::new(6, 6, 7, 7)); + let half = surf.read_region(Rect::new(16, 6, 17, 7)); + for (got, want) in full.iter().zip([0.2, 0.4, 0.6, 1.0]) { + assert!((got - want).abs() < 0.01, "@{depth}: {full:?}"); + } + assert!((half[3] - 0.5).abs() < 0.01 && (half[0] - 0.2).abs() < 0.01, "@{depth}: {half:?}"); + assert_eq!(surf.content_bounds(), Rect::new(5, 5, 20, 15), "@{depth}"); + } +} + +#[test] +fn cut_clears_and_layer_via_copy_cut() { + let mut s = session(); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 20})).unwrap(); + s.execute("edit.cut", json!({})).unwrap(); + assert_eq!(active_bounds(&s), Rect::new(20, 10, 50, 30)); + let mut s = session(); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 20})).unwrap(); + s.execute("layer.new.layerViaCut", json!({})).unwrap(); + assert_eq!(active_bounds(&s), Rect::new(10, 10, 20, 30)); + let d = &s.active().unwrap().doc; + assert_eq!(d.layers[1].surface().unwrap().content_bounds(), Rect::new(20, 10, 50, 30)); + // Without a selection ⌘J duplicates the layer. + let mut s = session(); + s.execute("layer.new.layerViaCopy", json!({})).unwrap(); + let d = &s.active().unwrap().doc; + assert_eq!(d.layers.len(), 3); + assert!(d.layers[2].name.ends_with("copy")); +} + +/// #1096: Layer via Copy and Cut deselect, as Photoshop does, so a following Free Transform +/// moves the whole new layer; one undo brings back both the selection and the old layers. +#[test] +fn layer_via_copy_and_cut_deselect_in_one_step() { + for cmd in ["layer.new.layerViaCopy", "layer.new.layerViaCut"] { + let mut s = session(); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 20})).unwrap(); + let (layers, steps) = (s.active().unwrap().doc.layers.len(), s.active().unwrap().history.past_len()); + s.execute(cmd, json!({})).unwrap(); + let st = s.active().unwrap(); + assert!(st.doc.selection.is_none(), "{cmd}: deselected"); + assert_eq!((st.doc.layers.len(), st.history.past_len()), (layers + 1, steps + 1), "{cmd}"); + assert!(s.undo()); + let st = s.active().unwrap(); + assert_eq!(st.doc.layers.len(), layers, "{cmd}: undo removes the layer"); + assert!(st.doc.selection.is_some(), "{cmd}: and restores the selection"); + } +} + +/// #2777: with several layers selected and no pixel selection, Layer via Copy (Cmd+J) copies +/// every selected layer in one step, each copy above its original and the copies selected. +/// With a pixel selection it still copies the active layer's selected pixels only. +#[test] +fn layer_via_copy_duplicates_every_selected_layer() { + let mut s = session(); + let a = s.active().unwrap().active_layer.unwrap(); + let b = LayerId(s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap()); + s.execute("layer.select", json!({"layer": a.0})).unwrap(); + s.execute("layer.select", json!({"layer": b.0, "mode": "toggle"})).unwrap(); + let steps = s.active().unwrap().history.past_len(); + s.execute("layer.new.layerViaCopy", json!({})).unwrap(); + let st = s.active().unwrap(); + let ids: Vec = st.doc.layers.iter().map(|l| l.id).collect(); + assert_eq!(ids.len(), 5, "background, a, a copy, b, b copy"); + assert_eq!((ids[1], ids[3]), (a, b), "each copy sits above its original"); + let mut selected = st.selected_layers(); + selected.sort_by_key(|l| l.0); + assert_eq!(selected, vec![ids[2], ids[4]], "the copies become the selection"); + assert_eq!(st.history.past_len(), steps + 1, "one undo step"); + assert!(s.undo()); + s.execute("layer.select", json!({"layer": b.0})).unwrap(); + s.execute("layer.select", json!({"layer": a.0, "mode": "toggle"})).unwrap(); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); + s.execute("layer.new.layerViaCopy", json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc.layers.len(), 4, "a pixel selection copies one layer's pixels"); +} + +fn active_content(s: &Session) -> LayerContent { + let st = s.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().content.clone() +} + +/// #541, #2428: with no selection, Copy takes a smart object whole and Paste makes a smart +/// object again, with contents of its own; with a selection, the selected pixels paste as +/// pixels. Cut edits pixels, so it's refused; Layer via Copy and Duplicate Layer copy the layer. +#[test] +fn copy_a_smart_object_layer() { + let mut s = session(); + s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + let LayerContent::Smart(original) = active_content(&s) else { panic!("smart object") }; + assert!(s.is_enabled("edit.copy")); + assert_eq!(s.execute("edit.copy", json!({})).unwrap()["bounds"], json!([10, 10, 40, 20]), "no selection: the whole layer"); + s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap(); + let LayerContent::Smart(pasted) = active_content(&s) else { panic!("the paste is a smart object (#2428)") }; + assert_eq!(pasted.source, original.source, "the same contents"); + assert_ne!(pasted.contents_id, original.contents_id, "but not linked to the copied one"); + assert_eq!(active_bounds(&s), Rect::new(10, 10, 50, 30)); + s.execute("edit.paste", json!({"center": [70, 70]})).unwrap(); + assert!(matches!(active_content(&s), LayerContent::Smart(_))); + assert_eq!(active_bounds(&s), Rect::new(50, 60, 90, 80), "placed as pasted pixels are"); + s.undo(); + s.undo(); + assert!(matches!(active_content(&s), LayerContent::Smart(_))); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap(); + assert_eq!(s.execute("edit.copy", json!({})).unwrap()["bounds"], json!([10, 10, 10, 10]), "only the selected part"); + s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap(); + assert!(matches!(active_content(&s), LayerContent::Raster(_)), "a selection copies pixels"); + assert_eq!(active_bounds(&s), Rect::new(10, 10, 20, 20)); + s.undo(); + let cut = s.execute("edit.cut", json!({})).unwrap_err().to_string(); + assert!(cut.contains("not directly editable"), "{cut}"); + assert!(matches!(active_content(&s), LayerContent::Smart(_))); + s.execute("select.deselect", json!({})).unwrap(); + s.execute("layer.new.layerViaCopy", json!({})).unwrap(); + assert!(matches!(active_content(&s), LayerContent::Smart(_)), "⌘J without a selection duplicates the smart object"); + s.execute("layer.duplicate", json!({})).unwrap(); + assert!(matches!(active_content(&s), LayerContent::Smart(_))); + assert_eq!(s.active().unwrap().doc.layers.len(), 4); +} + +/// #2478: with several layers selected and no pixel selection, Copy takes every one of them +/// and Paste recreates them all, in order, as one undo step; with a pixel selection Copy still +/// takes the active layer's selected pixels only. +#[test] +fn copy_and_paste_several_selected_layers() { + let mut s = session(); + let a = s.active().unwrap().active_layer.unwrap(); + let b = LayerId(s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap()); + s.edit("paint", |doc, _| { + doc.layer_mut(b).unwrap().surface_mut().unwrap().fill_rect(Rect::new(60, 60, 80, 90), &[0.0, 0.0, 1.0, 1.0]); + Ok(()) + }) + .unwrap(); + s.execute("layer.select", json!({"layer": a.0})).unwrap(); + s.execute("layer.select", json!({"layer": b.0, "mode": "toggle"})).unwrap(); + assert!(s.is_enabled("edit.copy")); + assert_eq!(s.execute("edit.copy", json!({})).unwrap()["bounds"], json!([10, 10, 70, 80]), "both layers' pixels"); + let before = s.active().unwrap().doc.layers.len(); + let steps = s.active().unwrap().history.past_len(); + s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap(); + let st = s.active().unwrap(); + assert_eq!(st.doc.layers.len(), before + 2, "every selected layer is pasted"); + assert_eq!(st.history.past_len(), steps + 1, "one undo step"); + let n = st.doc.layers.len(); + let (pa, pb) = (st.doc.layers[n - 2].surface().unwrap(), st.doc.layers[n - 1].surface().unwrap()); + assert_eq!(pa.content_bounds(), Rect::new(10, 10, 50, 30), "the lower layer first"); + assert_eq!(pb.content_bounds(), Rect::new(60, 60, 80, 90)); + assert!(s.undo()); + assert_eq!(s.active().unwrap().doc.layers.len(), before); + + // A pixel selection takes the active layer's selected pixels, as a single layer. + s.execute("layer.select", json!({"layer": a.0})).unwrap(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 30, "height": 30})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc.layers.len(), before + 1); +} + +/// #2478, #3588: several layers copied in one document paste into another, in that document's +/// bit depth and with their own pixels, in order, as one undo step. +#[test] +fn paste_several_layers_into_another_document() { + for depth in [16, 32] { + let mut s = session(); + let a = s.active().unwrap().active_layer.unwrap(); + let b = LayerId(s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap()); + s.edit("paint", |doc, _| { + doc.layer_mut(b).unwrap().surface_mut().unwrap().fill_rect(Rect::new(60, 60, 80, 90), &[0.0, 0.0, 1.0, 1.0]); + Ok(()) + }) + .unwrap(); + s.execute("layer.select", json!({"layer": a.0})).unwrap(); + s.execute("layer.select", json!({"layer": b.0, "mode": "toggle"})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + + s.execute("file.new", json!({"width": 120, "height": 120, "depth": depth})).unwrap(); + assert_eq!(s.active_index().unwrap(), 1, "the new document is the active tab"); + let (before, steps) = (s.active().unwrap().doc.layers.len(), s.active().unwrap().history.past_len()); + s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap(); + let st = s.active().unwrap(); + assert_eq!(st.doc.layers.len(), before + 2, "{depth}-bit: both layers arrive"); + assert_eq!(st.history.past_len(), steps + 1, "{depth}-bit: one undo step"); + let n = st.doc.layers.len(); + let (pa, pb) = (st.doc.layers[n - 2].surface().unwrap(), st.doc.layers[n - 1].surface().unwrap()); + assert_eq!(pa.format().sample, st.doc.depth, "{depth}-bit: converted to the target depth"); + assert_eq!(pb.format().sample, st.doc.depth, "{depth}-bit: converted to the target depth"); + assert_eq!(pa.content_bounds(), Rect::new(10, 10, 50, 30), "{depth}-bit: the lower layer first"); + assert_eq!(pb.content_bounds(), Rect::new(60, 60, 80, 90)); + let (mut red, mut blue) = ([[0.0f32; 4]; 1], [[0.0f32; 4]; 1]); + pa.read_rgba_into(Rect::new(20, 20, 21, 21), &mut red); + pb.read_rgba_into(Rect::new(70, 70, 71, 71), &mut blue); + assert!(red[0][0] > 0.9 && red[0][1] < 0.1 && red[0][2] < 0.1, "{depth}-bit: red kept: {:?}", red[0]); + assert!(blue[0][2] > 0.9 && blue[0][0] < 0.1 && blue[0][1] < 0.1, "{depth}-bit: blue kept: {:?}", blue[0]); + assert!(s.undo()); + assert_eq!(s.active().unwrap().doc.layers.len(), before, "{depth}-bit: undo removes both"); + assert_eq!(s.documents().len(), 2, "the source document is untouched"); + } +} + +/// #2478: the Background in a multi-layer copy pastes as an ordinary, unlocked layer. +#[test] +fn copying_the_background_with_another_layer_pastes_an_ordinary_layer() { + let mut s = session(); + let a = s.active().unwrap().active_layer.unwrap(); + let bg = s.active().unwrap().doc.layers[0].id; + s.execute("layer.select", json!({"layer": a.0})).unwrap(); + s.execute("layer.select", json!({"layer": bg.0, "mode": "toggle"})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap(); + let st = s.active().unwrap(); + assert_eq!(st.doc.layers.len(), 4); + let pasted = &st.doc.layers[st.doc.layers.len() - 2]; + assert!(!st.doc.is_background(pasted.id)); + assert_eq!(pasted.locks, Default::default()); + assert!(st.doc.is_background(st.doc.layers[0].id), "the real Background is untouched"); +} + +/// #2428: a smart object copied in one document pastes into another as a smart object, in +/// that document's bit depth. +#[test] +fn paste_a_smart_object_into_another_document() { + let mut s = session(); + s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + s.execute("file.new", json!({"width": 60, "height": 40, "depth": 16})).unwrap(); + s.execute("edit.paste", json!({})).unwrap(); + let LayerContent::Smart(sm) = active_content(&s) else { panic!("the paste is a smart object") }; + assert_eq!(sm.cache.map(|c| c.format().sample), Some(s.active().unwrap().doc.depth), "converted to 16 bits"); + assert_eq!(active_bounds(&s), Rect::new(10, 10, 50, 30), "on the canvas: in place"); +} + +/// #3584: a PSD-embedded linked smart object (its bytes in the document's `lnk2` block, its +/// source a uuid) can still be opened after Copy + Paste into another document. +#[test] +fn paste_keeps_a_psd_embedded_smart_object_openable() { + use std::sync::Arc; + let mut s = session(); + s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + let outer = s.active().unwrap().active_layer.unwrap(); + s.edit("embedded linked source", |doc, _| { + let LayerContent::Smart(sm) = &mut doc.layer_mut(outer).ok_or(EngineError::NoDocument)?.content else { + return Err(EngineError::Other("not a smart object".into())); + }; + sm.source = photocraft_doc::SmartSource::Linked { path: "uuid-1".into() }; + let linked = photocraft_io::linked::LinkedFile { uuid: "uuid-1".into(), file_name: "in.png".into(), bytes: vec![1, 2, 3, 4] }; + doc.metadata.psd_global_blocks.push((*b"8BIM", *b"lnk2", Arc::new(photocraft_io::linked::encode_linked_file(&linked)))); + Ok(()) + }) + .unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + s.execute("file.new", json!({"width": 40, "height": 30})).unwrap(); + s.execute("edit.paste", json!({})).unwrap(); + let LayerContent::Smart(sm) = active_content(&s) else { panic!("the paste is a smart object") }; + assert!( + crate::smart_cmds::source_bytes(&s.active().unwrap().doc.metadata, &sm.source).is_some(), + "the pasted PSD-embedded linked source must resolve (#3584)" + ); +} + +/// Type and shape layers copy their rendered pixels too; groups and adjustments have none. +#[test] +fn copy_reads_any_layer_that_shows_pixels() { + let mut s = session(); + s.execute("type.create", json!({"text": "Hi", "size": 30, "x": 20, "y": 60})).unwrap(); + assert!(!s.is_enabled("edit.cut")); + assert!(s.execute("edit.copy", json!({})).is_ok()); + s.execute("layer.groupLayers", json!({})).unwrap(); + assert!(s.is_enabled("edit.copy"), "no selection: the group is copied whole (#2670)"); + s.execute("select.all", json!({})).unwrap(); + assert!(!s.is_enabled("edit.copy")); +} + +/// #2670: with no selection, Copy takes a type layer, a shape layer or a group whole and +/// Paste recreates it, into another document too (with fresh ids, in its bit depth); with a +/// selection, Copy takes pixels. +#[test] +fn copy_paste_keeps_type_shape_and_group_layers() { + let mut s = session(); + s.execute("type.create", json!({"text": "Hi", "size": 30, "x": 20, "y": 60})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap(); + let LayerContent::Text(t) = active_content(&s) else { panic!("the paste is a type layer") }; + assert_eq!(t.text, "Hi"); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 100, "height": 100})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + s.execute("edit.paste", json!({})).unwrap(); + assert!(matches!(active_content(&s), LayerContent::Raster(_)), "a selection copies pixels"); + s.execute("shape.create", json!({"kind": "rect", "rect": [10, 10, 40, 20], "fill": "#ff0000"})).unwrap(); + s.execute("layer.groupLayers", json!({})).unwrap(); + let LayerContent::Group(src) = active_content(&s) else { panic!("a group") }; + s.execute("edit.copy", json!({})).unwrap(); + s.execute("file.new", json!({"width": 60, "height": 40, "depth": 16})).unwrap(); + s.execute("edit.paste", json!({})).unwrap(); + let LayerContent::Group(g) = active_content(&s) else { panic!("the paste is a group") }; + let [shape] = g.children.as_slice() else { panic!("one child") }; + assert!(matches!(shape.content, LayerContent::Shape(_)), "the shape stays a shape"); + assert_ne!(shape.id, src.children[0].id, "fresh ids"); + assert_eq!(shape.surface().map(|c| c.format().sample), Some(s.active().unwrap().doc.depth), "converted to 16 bits"); +} + +#[test] +fn cross_document_group_paste_renders_shapes_on_destination_canvas() { + for (copy_to_document, depth) in [(false, 8), (true, 16)] { + let mut s = Session::new(); + s.execute("file.new", json!({"width":100,"height":100})).unwrap(); + let mut ids = Vec::new(); + for x in [10, 50] { + s.execute("shape.create", json!({"kind":"rect","rect":[x,20,20,30],"fill":"#ff0000"})).unwrap(); + s.execute("layer.layerStyle.dropShadow", json!({"size":4,"distance":3})).unwrap(); + ids.push(s.active().unwrap().active_layer.unwrap()); + } + s.active_mut().unwrap().selected_layers = ids; + s.execute("layer.groupLayers", json!({})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + s.execute("file.new", json!({"width":800,"height":600,"depth":depth})).unwrap(); + if copy_to_document { + s.execute("layer.copyToDocument", json!({"source":0,"document":1,"center":true})).unwrap(); + } else { + s.execute("edit.paste", json!({"center":[400,300]})).unwrap(); + } + let st = s.active().unwrap(); + let group = st.doc.layer(st.active_layer.unwrap()).unwrap(); + assert!(!crate::transform_cmds::transform_bounds(&st.doc, group).is_empty()); + assert_eq!(group.children().unwrap().len(), 2); + for child in group.children().unwrap() { + let LayerContent::Shape(shape) = &child.content else { panic!("shape") }; + let cache = shape.cache.as_ref().unwrap(); + assert_eq!(cache.format().sample, st.doc.depth); + assert!(!cache.content_bounds().is_empty(), "destination cache must not be clipped to source canvas"); + assert!(cache.content_bounds().x0 > 100); + let fresh = photocraft_vector::render_shape(shape, st.doc.pixel_format(), st.doc.bounds()); + assert_eq!(cache, &fresh); + } + let before = st.doc.clone(); + s.execute("layer.translate", json!({"dx":10,"dy":10})).unwrap(); + assert_ne!(s.active().unwrap().doc, before); + assert!(s.undo()); + assert_eq!(s.active().unwrap().doc, before); + } +} + +#[test] +fn paste_repairs_uncached_shapes_before_transform_and_effect_rendering() { + let mut s = session(); + s.execute("shape.create", json!({"kind":"rect","rect":[10,10,40,20],"fill":"#ff0000"})).unwrap(); + s.execute("layer.layerStyle.dropShadow", json!({"size":4,"distance":3})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + let layers = s.clipboard.as_mut().unwrap().layers.as_mut().unwrap(); + let LayerContent::Shape(sh) = &mut layers.layers[0].content else { panic!("shape") }; + sh.cache = None; + s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap(); + let st = s.active().unwrap(); + let layer = st.doc.layer(st.active_layer.unwrap()).unwrap(); + let LayerContent::Shape(sh) = &layer.content else { panic!("shape") }; + assert!(sh.cache.is_some()); + assert!(!crate::transform_cmds::transform_bounds(&st.doc, layer).is_empty()); + let expected = photocraft_vector::render_shape(sh, st.doc.pixel_format(), st.doc.bounds()); + assert_eq!(sh.cache.as_ref().unwrap(), &expected); + let rendered = photocraft_compose::render_layer_in(&st.doc, layer, st.doc.bounds()); + let mut fresh_doc = (*st.doc).clone(); + let snapshot = fresh_doc.clone(); + if let LayerContent::Shape(shape) = &mut fresh_doc.layer_mut(layer.id).unwrap().content { + crate::vector_cmds::refresh_shape(&snapshot, shape); + } + let fresh = photocraft_compose::render_layer_in(&fresh_doc, fresh_doc.layer(layer.id).unwrap(), fresh_doc.bounds()); + assert_eq!(rendered.px, fresh.px, "pasted effects match a freshly rebuilt shape"); + assert!(s.undo()); + assert!(s.redo()); + let st = s.active().unwrap(); + assert!(st.doc.layer(st.active_layer.unwrap()).unwrap().surface().is_some()); +} + +/// #2344: fill and adjustment layers have no pixels of their own, so with no selection Copy +/// takes them whole and Paste recreates them, in the same or another document, in one step. +#[test] +fn copy_paste_keeps_fill_and_adjustment_layers() { + for (depth, other) in [(8, 16), (16, 32), (32, 8)] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 60, "height": 40, "depth": depth})).unwrap(); + s.execute("layer.newFillLayer.gradient", json!({"from": "#000000", "to": "#ffffff", "angle": 0})).unwrap(); + let LayerContent::Fill(fill) = active_content(&s) else { panic!("a fill layer") }; + let src = s.active().unwrap().active_layer.unwrap(); + assert!(s.is_enabled("edit.copy"), "{depth}-bit: a fill layer can be copied"); + assert_eq!(s.execute("edit.copy", json!({})).unwrap()["bounds"], json!([0, 0, 60, 40]), "{depth}-bit: what it shows"); + let clip = s.clipboard.clone().unwrap(); + assert!(clip.surface.rgba(59, 20)[0] > clip.surface.rgba(0, 20)[0], "{depth}-bit: the clip holds the gradient's pixels"); + let steps = s.active().unwrap().history.past_len(); + s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap(); + assert_eq!(s.active().unwrap().history.past_len(), steps + 1, "{depth}-bit: one history step"); + assert_eq!(active_content(&s), LayerContent::Fill(fill.clone()), "{depth}-bit: the paste is the same fill layer"); + assert_ne!(s.active().unwrap().active_layer, Some(src), "{depth}-bit: a new layer"); + s.undo(); + assert_eq!(s.active().unwrap().active_layer, Some(src), "{depth}-bit: undo removes the paste"); + s.redo(); + assert!(matches!(active_content(&s), LayerContent::Fill(_)), "{depth}-bit: redo brings it back"); + + s.execute("layer.newAdjustmentLayer.levels", json!({})).unwrap(); + let LayerContent::Adjustment(levels) = active_content(&s) else { panic!("an adjustment layer") }; + assert_eq!(s.execute("edit.copy", json!({})).unwrap()["bounds"], json!([0, 0, 60, 40]), "{depth}-bit: it applies to the canvas"); + s.execute("file.new", json!({"width": 30, "height": 30, "depth": other})).unwrap(); + s.execute("edit.paste", json!({})).unwrap(); + assert_eq!(active_content(&s), LayerContent::Adjustment(levels), "{depth}-bit: the same Levels layer in the {other}-bit document"); + assert_eq!(s.active().unwrap().doc.layers.len(), 2, "{depth}-bit: pasted above the Background"); + } +} + +/// #2344: several adjustment layers, which show nothing alone, still copy and paste together. +#[test] +fn several_adjustment_layers_copy_together() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 40, "height": 40})).unwrap(); + let a = s.execute("layer.newAdjustmentLayer.levels", json!({})).unwrap()["layer"].as_u64().unwrap(); + let b = s.execute("layer.newAdjustmentLayer.levels", json!({})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.select", json!({"layer": a})).unwrap(); + s.execute("layer.select", json!({"layer": b, "mode": "toggle"})).unwrap(); + assert_eq!(s.execute("edit.copy", json!({})).unwrap()["bounds"], json!([0, 0, 40, 40])); + s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap(); + let d = &s.active().unwrap().doc; + assert_eq!(d.layers.len(), 5, "both are pasted"); + assert!(d.layers[3..].iter().all(|l| matches!(l.content, LayerContent::Adjustment(_)))); +} + +#[test] +fn merge_visible_keeps_hidden_layers() { + let mut s = session(); + s.execute("layer.new.layer", json!({})).unwrap(); + let hidden = s.active().unwrap().active_layer.unwrap(); + s.execute("layer.setProps", json!({"layer": hidden.0, "visible": false})).unwrap(); + s.execute("layer.mergeVisible", json!({})).unwrap(); + let d = &s.active().unwrap().doc; + assert_eq!(d.layers.len(), 2); + assert_eq!(d.layers[0].name, "Background"); + assert_eq!(d.layers[1].id, hidden); + assert_eq!(d.layers[0].surface().unwrap().pixel(20, 20)[..3], [1.0, 0.0, 0.0]); +} + +#[test] +fn auto_tone_stretches_a_low_contrast_layer() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); + s.edit("grey ramp", |doc, _| { + let surf = doc.layers[0].surface_mut().unwrap(); + for x in 0..64 { + let v = 0.3 + 0.4 * x as f32 / 63.0; + surf.fill_rect(Rect::new(x, 0, x + 1, 64), &[v, v * 0.9, v * 0.8, 1.0]); + } + Ok(()) + }) + .unwrap(); + for cmd in ["image.autoTone", "image.autoContrast", "image.autoColor"] { + s.execute(cmd, json!({})).unwrap(); + let d = &s.active().unwrap().doc; + let (a, b) = (d.layers[0].surface().unwrap().pixel(0, 0), d.layers[0].surface().unwrap().pixel(63, 0)); + // Auto Contrast keeps colour (shared points): only the extreme channels reach 0 and 1. + let (lo, hi) = if cmd == "image.autoContrast" { (a[2], b[0]) } else { (a[0], b[0]) }; + assert!(lo < 0.05 && hi > 0.95, "{cmd}: {a:?} {b:?}"); + s.undo(); + } +} + +/// #352: ⌥⇧⌘T steps and repeats: each press adds a copy one transform further on, and each +/// is one undo step. +#[test] +fn transform_again_on_a_copy_steps_and_repeats() { + let mut s = session(); + assert!(s.execute("edit.transform.againCopy", json!({})).is_err(), "nothing to repeat yet"); + assert_eq!(s.active().unwrap().doc.layers.len(), 2, "a refusal leaves no copy"); + s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 10, 0]})).unwrap(); + let steps = s.active().unwrap().history.past_len(); + for (i, x) in [30, 40].into_iter().enumerate() { + s.execute("edit.transform.againCopy", json!({})).unwrap(); + let d = &s.active().unwrap().doc; + assert_eq!(d.layers.len(), 3 + i); + assert_eq!(active_bounds(&s), Rect::new(x, 10, x + 40, 30), "the copy moved one step further"); + assert_eq!(s.active().unwrap().history.past_len(), steps + 1 + i, "one history step per press"); + } + assert_eq!(s.active().unwrap().history.undo_label(), Some("Transform Again")); + // The original and the first copy stay where they were. + let d = &s.active().unwrap().doc; + let b = |i: usize| d.layers[i].surface().unwrap().content_bounds(); + assert_eq!((b(1), b(2)), (Rect::new(20, 10, 60, 30), Rect::new(30, 10, 70, 30))); + // Undo removes the copy and its move together. + s.undo(); + assert_eq!(s.active().unwrap().doc.layers.len(), 3); + assert_eq!(active_bounds(&s), Rect::new(30, 10, 70, 30)); + // A copy that can't move (position locked) is taken back. + let id = s.active().unwrap().active_layer.unwrap(); + s.execute("layer.setProps", json!({"layer": id.0, "locks": {"position": true}})).unwrap(); + let layers = s.active().unwrap().doc.layers.len(); + assert!(s.execute("edit.transform.againCopy", json!({})).unwrap_err().to_string().contains("locked")); + assert_eq!(s.active().unwrap().doc.layers.len(), layers); + assert!(!s.active().unwrap().history.can_redo(), "nothing to redo"); +} + +#[test] +fn toggle_last_state_and_transform_again() { + let mut s = session(); + s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 10, 0]})).unwrap(); + s.execute("edit.transform.again", json!({})).unwrap(); + assert_eq!(active_bounds(&s), Rect::new(30, 10, 70, 30)); + s.execute("edit.toggleLastState", json!({})).unwrap(); + assert_eq!(active_bounds(&s), Rect::new(20, 10, 60, 30)); + s.execute("edit.toggleLastState", json!({})).unwrap(); + assert_eq!(active_bounds(&s), Rect::new(30, 10, 70, 30)); +} + +#[test] +fn guides_are_undoable() { + let mut s = session(); + s.execute("view.newGuide", json!({"orientation": "vertical", "position": 40})).unwrap(); + s.execute("view.newGuide", json!({"orientation": "horizontal", "position": 12.5})).unwrap(); + s.execute("view.moveGuide", json!({"orientation": "vertical", "index": 0, "position": 60})).unwrap(); + let g = &s.active().unwrap().doc.guides; + assert_eq!((g.vertical.clone(), g.horizontal.clone()), (vec![60.0], vec![12.5])); + s.execute("view.deleteGuide", json!({"orientation": "horizontal", "index": 0})).unwrap(); + s.undo(); + assert_eq!(s.active().unwrap().doc.guides.horizontal, vec![12.5]); + s.execute("view.clearGuides", json!({})).unwrap(); + assert!(s.active().unwrap().doc.guides.vertical.is_empty()); + assert!(s.execute("view.moveGuide", json!({"orientation": "vertical", "index": 3, "position": 1})).is_err()); +} + +/// #2955: the rulers' zero point is set and reset by command, undoable, and bad params are +/// refused without touching the document. +#[test] +fn ruler_origin_is_set_reset_and_undoable() { + let mut s = session(); + assert_eq!(s.active().unwrap().doc.ruler_origin, [0.0, 0.0]); + assert_eq!(s.execute("view.setRulerOrigin", json!({"x": 40, "y": 12.5})).unwrap(), json!({"x": 40.0, "y": 12.5})); + assert_eq!(s.active().unwrap().doc.ruler_origin, [40.0, 12.5]); + s.execute("view.resetRulerOrigin", json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc.ruler_origin, [0.0, 0.0]); + s.undo(); + assert_eq!(s.active().unwrap().doc.ruler_origin, [40.0, 12.5]); + for bad in [json!({}), json!({"x": 1}), json!({"x": "a", "y": 2}), json!({"x": 1e300, "y": 0}), json!({"x": -2e7, "y": 0}), json!(null), json!([1, 2])] { + assert!(s.execute("view.setRulerOrigin", bad.clone()).is_err(), "{bad} is refused"); + } + assert_eq!(s.active().unwrap().doc.ruler_origin, [40.0, 12.5]); + let mut empty = Session::new(); + assert!(empty.execute("view.setRulerOrigin", json!({"x": 1, "y": 2})).is_err()); + assert!(empty.execute("view.resetRulerOrigin", json!({})).is_err()); +} + +/// The last guide added in `orientation` for `position`. +fn new_guide(s: &mut Session, orientation: &str, position: Value) -> f64 { + s.execute("view.newGuide", json!({"orientation": orientation, "position": position})).unwrap(); + let g = &s.active().unwrap().doc.guides; + *if orientation == "vertical" { &g.vertical } else { &g.horizontal }.last().unwrap() +} + +#[test] +fn guide_positions_take_photoshop_units() { + let mut s = Session::new(); + // 4 × 2 inches at 100 ppi. + s.execute("file.new", json!({"width": 400, "height": 200, "resolution": 100})).unwrap(); + // Percent follows the guide's own axis: the width for a vertical guide, the height for a horizontal one. + assert_eq!(new_guide(&mut s, "vertical", json!("50%")), 200.0); + assert_eq!(new_guide(&mut s, "horizontal", json!("50%")), 100.0); + for one_inch in ["1in", "1 in", "2.54cm", "25.4 mm", "72pt", "6pc", "100px", "100", "1,0 inch"] { + assert!((new_guide(&mut s, "vertical", json!(one_inch)) - 100.0).abs() < 1e-3, "{one_inch}"); + } + // Fractional and negative positions are kept; a plain number is pixels, as before. + assert_eq!(new_guide(&mut s, "horizontal", json!("12.5px")), 12.5); + assert_eq!(new_guide(&mut s, "vertical", json!("-10px")), -10.0); + assert_eq!(new_guide(&mut s, "vertical", json!(40)), 40.0); + // Points and picas follow Units & Rulers › Point Size. + s.execute("prefs.set", json!({"path": "unitsAndRulers.pointSize", "value": "traditional"})).unwrap(); + assert!((new_guide(&mut s, "vertical", json!("72.27pt")) - 100.0).abs() < 1e-3); + // A guide moved with a unit lands where a new one would. + s.execute("view.moveGuide", json!({"orientation": "horizontal", "index": 0, "position": "25%"})).unwrap(); + assert_eq!(s.active().unwrap().doc.guides.horizontal[0], 50.0); +} + +#[test] +fn new_guides_keep_their_own_colour_through_moves_deletes_and_undo() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 400, "height": 200})).unwrap(); + let color = |s: &Session, vertical: bool, p: f64| s.active().unwrap().doc.guides.color(vertical, p); + // Without a colour a guide uses the preference colour, as ruler-drag guides always did. + s.execute("view.newGuide", json!({"orientation": "vertical", "position": 10})).unwrap(); + assert_eq!(color(&s, true, 10.0), None); + assert!(s.active().unwrap().doc.guides.colors.is_empty()); + s.execute("view.newGuide", json!({"orientation": "vertical", "position": 20, "color": "magenta"})).unwrap(); + s.execute("view.newGuide", json!({"orientation": "horizontal", "position": 20, "color": "#123456"})).unwrap(); + s.execute("view.newGuide", json!({"orientation": "vertical", "position": 30, "color": "LightBlue"})).unwrap(); + assert_eq!(color(&s, true, 20.0), Some([0xff, 0x00, 0xff])); + assert_eq!(color(&s, false, 20.0), Some([0x12, 0x34, 0x56]), "the same position across is a different guide"); + assert_eq!(color(&s, true, 30.0), Some([0x33, 0x66, 0xff]), "names are case-insensitive"); + // Moving takes the colour along. + s.execute("view.moveGuide", json!({"orientation": "vertical", "index": 1, "position": 25})).unwrap(); + assert_eq!((color(&s, true, 20.0), color(&s, true, 25.0)), (None, Some([0xff, 0x00, 0xff]))); + // Undo restores it where it was. + s.undo(); + assert_eq!((color(&s, true, 20.0), color(&s, true, 25.0)), (Some([0xff, 0x00, 0xff]), None)); + // Deleting drops it; clearing drops them all. + s.execute("view.deleteGuide", json!({"orientation": "vertical", "index": 2})).unwrap(); + assert_eq!(color(&s, true, 30.0), None); + assert_eq!(s.active().unwrap().doc.guides.colors.len(), 2); + s.execute("view.clearGuides", json!({})).unwrap(); + assert!(s.active().unwrap().doc.guides.colors.is_empty()); +} + +#[test] +fn moving_one_of_two_coloured_guides_at_one_position_leaves_the_other_its_colour() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 400, "height": 200})).unwrap(); + for _ in 0..2 { + s.execute("view.newGuide", json!({"orientation": "vertical", "position": 50, "color": "green"})).unwrap(); + } + s.execute("view.moveGuide", json!({"orientation": "vertical", "index": 0, "position": 60})).unwrap(); + let g = &s.active().unwrap().doc.guides; + assert_eq!((g.color(true, 50.0), g.color(true, 60.0)), (Some([0x33, 0xff, 0x33]), Some([0x33, 0xff, 0x33]))); +} + +#[test] +fn cyan_is_the_default_guide_colour_so_ruler_guides_read_as_cyan() { + let default = crate::prefs::Preferences::default().guides_grid_and_slices.guide_color; + let cyan = GUIDE_COLORS.iter().find(|(name, ..)| *name == "cyan").map(|(.., rgb)| *rgb); + assert_eq!(cyan, crate::prefs::parse_hex(&default)); +} + +#[test] +fn bad_guide_colours_are_refused_without_a_guide() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 400, "height": 200})).unwrap(); + let undo_before = s.active().unwrap().history.can_undo(); + for bad in [json!("puce"), json!("#12345"), json!("#gggggg"), json!(""), json!(7), json!(null), json!(["cyan"])] { + assert!(s.execute("view.newGuide", json!({"orientation": "vertical", "position": 10, "color": bad.clone()})).is_err(), "{bad}"); + } + let g = &s.active().unwrap().doc.guides; + assert!(g.vertical.is_empty() && g.colors.is_empty()); + assert_eq!(s.active().unwrap().history.can_undo(), undo_before); +} + +#[test] +fn editing_a_guide_changes_what_is_given_in_one_undoable_step() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 400, "height": 200})).unwrap(); + s.execute("view.newGuide", json!({"orientation": "vertical", "position": 10})).unwrap(); + s.execute("view.newGuide", json!({"orientation": "vertical", "position": 20, "color": "magenta"})).unwrap(); + s.execute("view.newGuide", json!({"orientation": "vertical", "position": 30})).unwrap(); + let guides = |s: &Session| s.active().unwrap().doc.guides.clone(); + // Position only: the guide keeps its index and its own colour. + s.execute("view.editGuide", json!({"orientation": "vertical", "index": 1, "position": "50%"})).unwrap(); + let g = guides(&s); + assert_eq!(g.vertical, vec![10.0, 200.0, 30.0]); + assert_eq!((g.color(true, 20.0), g.color(true, 200.0)), (None, Some([0xff, 0x00, 0xff]))); + // Colour only: an uncoloured guide gets one; the position stays. + s.execute("view.editGuide", json!({"orientation": "vertical", "index": 0, "color": "#123456"})).unwrap(); + assert_eq!(guides(&s).color(true, 10.0), Some([0x12, 0x34, 0x56])); + // Turning it: % is of the new orientation's extent, and the colour goes along. + s.execute("view.editGuide", json!({"orientation": "vertical", "index": 1, "newOrientation": "horizontal", "position": "25%"})).unwrap(); + let g = guides(&s); + assert_eq!((g.vertical.clone(), g.horizontal.clone()), (vec![10.0, 30.0], vec![50.0])); + assert_eq!((g.color(true, 200.0), g.color(false, 50.0)), (None, Some([0xff, 0x00, 0xff]))); + // One step each: undo restores the vertical guide with its colour. + s.undo(); + let g = guides(&s); + assert_eq!((g.vertical.clone(), g.horizontal.is_empty()), (vec![10.0, 200.0, 30.0], true)); + assert_eq!(g.color(true, 200.0), Some([0xff, 0x00, 0xff])); +} + +#[test] +fn bad_guide_edits_are_refused_without_a_history_step() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 400, "height": 200})).unwrap(); + s.execute("view.newGuide", json!({"orientation": "vertical", "position": 10, "color": "green"})).unwrap(); + let before = s.active().unwrap().doc.guides.clone(); + for bad in [ + json!({}), + json!({"orientation": "vertical"}), + json!({"orientation": "vertical", "index": 1}), + json!({"orientation": "horizontal", "index": 0}), + json!({"orientation": "vertical", "index": -1}), + json!({"orientation": "vertical", "index": "0"}), + json!({"orientation": "vertical", "index": u64::MAX}), + json!({"orientation": "diagonal", "index": 0}), + json!({"orientation": "vertical", "index": 0, "newOrientation": 3}), + json!({"orientation": "vertical", "index": 0, "position": "far"}), + json!({"orientation": "vertical", "index": 0, "position": 1e12}), + json!({"orientation": "vertical", "index": 0, "color": "puce"}), + ] { + assert!(s.execute("view.editGuide", bad.clone()).is_err(), "{bad}"); + } + assert_eq!(s.active().unwrap().doc.guides, before); + assert_eq!(s.active().unwrap().history.undo_label(), Some("New Guide")); +} + +#[test] +fn bad_guide_positions_are_refused_without_a_guide() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 400, "height": 200, "resolution": 100})).unwrap(); + let undo_before = s.active().unwrap().history.can_undo(); + for bad in [ + json!("abc"), + json!("50 furlongs"), + json!(""), + json!("%"), + json!("NaN"), + json!("inf"), + json!("1e400"), + json!("2000000px"), + json!(1e300), + json!(true), + json!([1]), + ] { + assert!(s.execute("view.newGuide", json!({"orientation": "vertical", "position": bad.clone()})).is_err(), "{bad}"); + } + assert!(s.execute("view.newGuide", json!({"orientation": "vertical"})).is_err(), "no position"); + let g = &s.active().unwrap().doc.guides; + assert!(g.vertical.is_empty() && g.horizontal.is_empty()); + assert_eq!(s.active().unwrap().history.can_undo(), undo_before, "a refused guide records no history step"); +} + +/// Guides keep their exact place (#2918): 1 cm at 300 ppi through New Guide and .pcraft, and +/// a 1/32 px PSD position past 2^19 px, where f32 has no 1/32 steps left. +#[test] +fn guides_keep_sub_pixel_positions_through_pcraft_and_psd() { + let (cm, far) = (300.0 / 2.54, 600_000.031_25); + let mut s = session(); + s.execute("view.newGuide", json!({"orientation": "horizontal", "position": cm})).unwrap(); + s.execute("view.newGuide", json!({"orientation": "vertical", "position": far})).unwrap(); + fn wide(v: impl Into) -> f64 { + v.into() + } + let exact = |g: &photocraft_doc::Guides| (wide(g.horizontal[0]), wide(g.vertical[0])); + let doc = &s.active().unwrap().doc; + assert_eq!(exact(&doc.guides), (cm, far)); + let pcraft = photocraft_format::save_to_bytes(doc, &Default::default()).unwrap(); + assert_eq!(exact(&photocraft_format::load_from_bytes(&pcraft).unwrap().guides), (cm, far)); + let psd = photocraft_io::export(doc, "psd", &Default::default()).unwrap().bytes; + let back = photocraft_io::import("g.psd", &psd).unwrap().document.guides; + assert_eq!(wide(back.vertical[0]), far, "1032 stores 1/32 px"); +} + +/// `lift` as it was before #4516: the whole area through one `f32` buffer. The oracle for +/// the tiled version. +fn lift_reference(src: &Surface, sel: Option<&Surface>, canvas: Rect) -> Clip { + let fmt = src.format(); + let with_alpha = PixelFormat::new(fmt.mode, fmt.sample, true); + let area = match sel { + Some(m) => m.content_bounds().intersect(&canvas), + None => src.content_bounds().intersect(&canvas), + }; + let mut out = Surface::new(with_alpha); + if area.is_empty() { + return Clip { surface: out, bounds: Rect::EMPTY, layers: None, resolution: None, source: None }; + } + let px = lift_region(src, sel, area, with_alpha.channels()).unwrap(); + out.try_write_region(area, &px).unwrap(); + out.prune(); + let bounds = out.content_bounds(); + Clip { surface: out, bounds, layers: None, resolution: None, source: None } +} + +fn noise(fmt: PixelFormat, r: Rect, seed: u32) -> Surface { + let mut s = Surface::new(fmt); + let n = r.width() as usize * r.height() as usize * fmt.channels(); + let data: Vec = (0..n as u32) + .map(|i| { + let mut h = seed.wrapping_mul(0x9e37_79b9) ^ i.wrapping_mul(0x85eb_ca6b); + h ^= h >> 13; + h = h.wrapping_mul(0xc2b2_ae35); + (h >> 16) as f32 / 65535.0 + }) + .collect(); + s.write_region(r, &data); + s +} + +fn assert_same_clip(a: &Clip, b: &Clip, what: &str) { + assert_eq!(a.bounds, b.bounds, "{what}: bounds"); + assert_eq!(a.surface.format(), b.surface.format(), "{what}: format"); + let r = a.bounds.union(&b.bounds); + if !r.is_empty() { + let (pa, pb) = (a.surface.read_region(r), b.surface.read_region(r)); + assert!(pa.iter().zip(&pb).all(|(x, y)| x.to_bits() == y.to_bits()), "{what}: pixels differ"); + } +} + +/// The tiled `lift` gives exactly the old result (#4516): with and without alpha, at every +/// depth, with no selection, Select All, a partial feathered selection and a selection off +/// the tile grid, and for content reaching past the canvas. +#[test] +fn tiled_lift_matches_the_whole_area_lift() { + use photocraft_color::{ColorMode, SampleType}; + let canvas = Rect::new(0, 0, 700, 600); + for sample in [SampleType::U8, SampleType::U16, SampleType::F32] { + for alpha in [true, false] { + let fmt = PixelFormat::new(ColorMode::Rgb, sample, alpha); + let src = noise(fmt, Rect::new(-40, -30, 760, 640), 7); + let mut all = Surface::new(PixelFormat::GRAY8); + all.fill_rect(canvas, &[1.0]); + let mut partial = Surface::new(PixelFormat::GRAY8); + partial.fill_rect(Rect::new(100, 50, 600, 550), &[1.0]); + partial.write_region(Rect::new(90, 40, 610, 50), &vec![0.5; 520 * 10]); + let off_grid = noise(PixelFormat::GRAY8, Rect::new(13, 270, 333, 290), 9); + for (name, sel) in [("no selection", None), ("select all", Some(&all)), ("partial", Some(&partial)), ("off grid", Some(&off_grid))] { + let what = format!("{sample:?} alpha {alpha} {name}"); + let new = lift(&src, sel, canvas).unwrap(); + assert_same_clip(&new, &lift_reference(&src, sel, canvas), &what); + } + } + } +} + +/// Copy shares the layer's whole tiles instead of copying them. +#[test] +fn copy_shares_whole_tiles_with_the_layer() { + let src = noise(PixelFormat::RGBA8, Rect::new(0, 0, 1024, 768), 3); + let canvas = Rect::new(0, 0, 1024, 768); + let mut all = Surface::new(PixelFormat::GRAY8); + all.fill_rect(canvas, &[1.0]); + for sel in [None, Some(&all)] { + let clip = lift(&src, sel, canvas).unwrap(); + let shared = src.tiles().filter(|(c, t)| clip.surface.tile(**c).is_some_and(|o| std::sync::Arc::ptr_eq(o, t))).count(); + assert_eq!(shared, src.tile_count(), "every tile is shared"); + } +} diff --git a/crates/engine/src/cmd/edit_menu_cmds.rs b/crates/engine/src/cmd/edit_menu_cmds.rs new file mode 100644 index 0000000000..f7603d2908 --- /dev/null +++ b/crates/engine/src/cmd/edit_menu_cmds.rs @@ -0,0 +1,407 @@ +//! The rest of Photoshop's Edit menu: Fade, Purge, Content-Aware Fill and Scale, Define Brush +//! Preset / Custom Shape, Find and Replace Text, the Preset Manager and preset export/import. +//! Auto-Align and Auto-Blend Layers live in [`crate::align_cmds`]. +//! +//! Check Spelling is not implemented: it needs a word list per language, and no permissively +//! licensed dictionary small enough to bundle (or a pure-Rust checker with one) was available. + +use photocraft_color::{BlendMode, PixelFormat}; +use photocraft_doc::vector::Path; +use photocraft_doc::{DocId, Document, Layer, LayerContent, LayerId}; +use photocraft_geom::Rect; +use photocraft_raster::{Surface, from_rgba_into, to_rgba}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; + +use crate::channel_cmds::Target; +use crate::commands::{CommandSpec, blend_from_str, int, layer_param}; +use crate::{EngineError, Result, Session}; + +// ------------------------------------------------------------------ state + +/// What Edit › Fade would fade: the result of the last filter, adjustment or paint command. +#[derive(Clone, Debug, PartialEq)] +pub struct FadeSource { + pub doc: DocId, + /// Document revision right after the command; any later change disables Fade. + pub revision: u64, + pub target: FadeTarget, + pub label: String, +} + +/// What the faded command changed, and so what Fade blends back. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum FadeTarget { + /// A layer's pixels. + Pixels(LayerId), + /// A layer's layer mask. + Mask(LayerId), + /// An alpha or spot channel (index into [`Document::channels`]). + Channel(usize), + /// The Quick Mask. + QuickMask, +} + +/// A custom shape (Edit › Define Custom Shape), usable by the Custom Shape tool. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct CustomShape { + pub name: String, + pub path: Path, +} + +/// Edit-menu state kept by the session. +#[derive(Clone, Debug, Default)] +pub struct EditState { + pub fade: Option, + /// Custom shape library (the vector tools read it). + pub custom_shapes: Vec, + /// Find and Replace Text position: (layer, byte offset after the current match). + pub find_cursor: Option<(LayerId, usize, usize)>, +} + +/// Commands whose result Edit › Fade can blend back against the previous state. +fn fadeable(id: &str) -> bool { + id.starts_with("filter.") + || id.starts_with("image.adjustments.") + || id.starts_with("paint.") + || matches!(id, "edit.fill" | "edit.stroke" | "edit.contentAwareFill" | "image.autoTone" | "image.autoContrast" | "image.autoColor") +} + +/// Called after every successful command: remember a fadeable result. +pub(crate) fn after_command(s: &mut Session, id: &str, params: &Value) { + if !fadeable(id) { + return; + } + let Some(st) = s.active() else { return }; + let label = st.history.undo_label().unwrap_or(id).to_string(); + // An alpha channel or the Quick Mask took the edit instead of the layer when the command ran + // on it (#7382): its explicit `target`, or the one the Channels panel gave it. Only commands + // routed to channels edit them; the others edit the layer whatever `target` says. + let run = crate::channel_cmds::inject_target(s, id, params.clone()); + let channel = match crate::channel_cmds::target_of(&run) { + _ if !crate::channel_cmds::routed(id) => None, + Target::Alpha(i) if i < st.doc.channels.len() => Some(FadeTarget::Channel(i)), + Target::QuickMask if st.doc.quick_mask.is_some() => Some(FadeTarget::QuickMask), + _ => None, + }; + if let Some(target) = channel { + s.edit_state.fade = Some(FadeSource { doc: st.doc.id, revision: st.revision, target, label }); + return; + } + let Some(layer) = st.active_layer else { return }; + let mask = st.doc.layer(layer).is_some_and(|l| l.mask.is_some()) + && st.history.state(st.history.past_len().wrapping_sub(1)).is_some_and(|prev| { + // The mask changed and the pixels didn't: the command painted the mask. + let now = st.doc.layer(layer); + let was = prev.layer(layer); + let surf_eq = |a: Option<&Surface>, b: Option<&Surface>| match (a, b) { + (Some(a), Some(b)) => a.format() == b.format() && a.default_pixel() == b.default_pixel() && crate_fingerprint(a) == crate_fingerprint(b), + (None, None) => true, + _ => false, + }; + surf_eq(now.and_then(|l| l.surface()), was.and_then(|l| l.surface())) + && !surf_eq(now.and_then(|l| l.mask.as_ref().map(|m| &m.surface)), was.and_then(|l| l.mask.as_ref().map(|m| &m.surface))) + }); + let target = if mask { FadeTarget::Mask(layer) } else { FadeTarget::Pixels(layer) }; + s.edit_state.fade = Some(FadeSource { doc: st.doc.id, revision: st.revision, target, label }); +} + +/// Tile identity of a surface (pointer equality of its COW tiles). +fn crate_fingerprint(s: &Surface) -> u64 { + s.tiles().fold(s.tile_count() as u64, |h, (c, t)| { + (h ^ std::sync::Arc::as_ptr(t) as usize as u64 ^ ((c.tx as u64) << 32 | c.ty as u32 as u64)).wrapping_mul(0x100_0000_01b3) + }) +} + +// ------------------------------------------------------------------ helpers + +fn bad(cmd: &str, msg: impl Into) -> EngineError { + EngineError::BadParams { cmd: cmd.into(), msg: msg.into() } +} + +fn f32_or(p: &Value, k: &str, d: f32) -> f32 { + p.get(k).and_then(Value::as_f64).map_or(d, |v| v as f32) +} + +fn str_or<'a>(p: &'a Value, k: &str, d: &'a str) -> &'a str { + p.get(k).and_then(Value::as_str).unwrap_or(d) +} + +fn bool_or(p: &Value, k: &str, d: bool) -> bool { + p.get(k).and_then(Value::as_bool).unwrap_or(d) +} + +fn always(_: &Session) -> std::result::Result<(), String> { + Ok(()) +} + +fn pixel_layer(s: &Session) -> std::result::Result { + let d = s.active().ok_or("no document open")?; + let id = d.active_layer.ok_or("no active layer")?; + pixel_layer_id(s, id) +} + +/// `id` if it is an unlocked pixel layer of the active document. +fn pixel_layer_id(s: &Session, id: LayerId) -> std::result::Result { + let d = s.active().ok_or("no document open")?; + let l = d.doc.layer(id).ok_or("no active layer")?; + if !matches!(l.content, LayerContent::Raster(_)) { + return Err(format!("active layer is {} {} layer, not a pixel layer", l.content.article(), l.content.kind_name())); + } + let locks = d.doc.effective_locks(id); + if locks.all || locks.pixels { + return Err(format!("the layer \"{}\" is locked", l.name)); + } + Ok(id) +} + +fn writable_surface(doc: &mut Document, id: LayerId) -> Result<&mut Surface> { + let locks = doc.effective_locks(id); + let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; + if locks.all || locks.pixels { + return Err(EngineError::Other(format!("Could not complete your request because the layer \"{}\" is locked", l.name))); + } + l.surface_mut().ok_or_else(|| EngineError::Other("not a pixel layer".into())) +} + +fn surface_of(doc: &Document, target: FadeTarget) -> Option<&Surface> { + match target { + FadeTarget::Pixels(id) => doc.layer(id)?.surface(), + FadeTarget::Mask(id) => doc.layer(id)?.mask.as_ref().map(|m| &m.surface), + FadeTarget::Channel(i) => doc.channels.get(i).map(|c| &c.surface), + FadeTarget::QuickMask => doc.quick_mask.as_ref().map(|c| &c.surface), + } +} + +fn surface_of_mut(doc: &mut Document, target: FadeTarget) -> Option<&mut Surface> { + match target { + FadeTarget::Pixels(id) => doc.layer_mut(id)?.surface_mut(), + FadeTarget::Mask(id) => doc.layer_mut(id)?.mask.as_mut().map(|m| &mut m.surface), + FadeTarget::Channel(i) => doc.channels.get_mut(i).map(|c| &mut c.surface), + FadeTarget::QuickMask => doc.quick_mask.as_mut().map(|c| &mut c.surface), + } +} + +fn export_import(s: &mut Session, p: &Value) -> Result { + let cmd = "edit.presets.exportImportPresets"; + let kinds: Vec = p + .get("kinds") + .and_then(Value::as_array) + .map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect()) + .unwrap_or_else(|| ["brushes", "customShapes", "tools"].iter().map(ToString::to_string).collect()); + let want = |k: &str| kinds.iter().any(|x| x == k); + match str_or(p, "action", "export") { + "export" => { + let file = PresetFile { + format: PRESET_FORMAT.into(), + version: 1, + brushes: if want("brushes") { + let mut out: Vec = + s.tools.presets.iter().filter(|b| !b.builtin || bool_or(p, "includeBuiltins", false)).cloned().collect(); + // The file embeds every bitmap: load the tips the preset store keeps (#1843). + for b in &mut out { + s.load_brush_tips(&mut b.brush).map_err(|e| bad(cmd, format!("brush preset `{}`: {e}", b.name)))?; + } + out + } else { + Vec::new() + }, + custom_shapes: if want("customShapes") { s.edit_state.custom_shapes.clone() } else { Vec::new() }, + tool_presets: if want("tools") { + let builtins = crate::presets::tools::builtin(); + s.presets.tool_presets.iter().filter(|preset| bool_or(p, "includeBuiltins", false) || !builtins.contains(preset)).cloned().collect() + } else { + Vec::new() + }, + }; + Ok(json!({"data": file, "brushes": file.brushes.len(), "customShapes": file.custom_shapes.len(), "tools": file.tool_presets.len()})) + } + "import" => { + let data = p.get("data").cloned().ok_or_else(|| bad(cmd, "missing `data` (an exported preset file)"))?; + let data = match data { + Value::String(text) => serde_json::from_str(&text).map_err(|e| bad(cmd, format!("not a preset file: {e}")))?, + v => v, + }; + let file: PresetFile = serde_json::from_value(data).map_err(|e| bad(cmd, format!("not a preset file: {e}")))?; + if file.format != PRESET_FORMAT { + return Err(bad(cmd, format!("not a preset file (format `{}`)", file.format))); + } + // Validate the whole tool import before changing any preset library. + let mut tools = s.presets.tool_presets.clone(); + let nt = if want("tools") { file.tool_presets.len() } else { 0 }; + if nt > crate::presets::tools::MAX_PRESETS { + return Err(bad(cmd, "too many tool presets")); + } + if want("tools") { + for mut preset in file.tool_presets { + preset.name = crate::presets::tools::checked_name(&preset.name, cmd)?; + if preset.tool.trim().is_empty() || !preset.options.is_object() { + return Err(bad(cmd, "tool presets require a non-empty tool and an options object")); + } + if let Some(old) = tools.iter_mut().find(|old| old.name == preset.name && old.tool.eq_ignore_ascii_case(&preset.tool)) { + *old = preset; + } else if tools.iter().any(|old| old.name == preset.name) { + return Err(bad(cmd, "a preset of that name belongs to another tool; rename it before importing")); + } else if tools.len() < crate::presets::tools::MAX_PRESETS { + tools.push(preset); + } else { + return Err(bad(cmd, "too many tool presets")); + } + } + } + let (mut nb, mut ns) = (0, 0); + if want("brushes") { + for mut b in file.brushes { + // Nested folders as the commands bound them (a hand-edited file can't build an + // absurd tree). + b.folder.retain(|f| !f.trim().is_empty()); + b.folder.truncate(crate::brush_preset_cmds::MAX_FOLDER_DEPTH); + match s.tools.presets.iter_mut().find(|x| x.name == b.name) { + Some(x) => *x = b, + None => s.tools.presets.push(b), + } + nb += 1; + } + s.brush_presets_changed(); + } + if want("customShapes") { + for c in file.custom_shapes { + match s.edit_state.custom_shapes.iter_mut().find(|x| x.name == c.name) { + Some(x) => *x = c, + None => s.edit_state.custom_shapes.push(c), + } + ns += 1; + } + } + if want("tools") { + s.presets.tool_presets = tools; + s.presets_changed(); + } + Ok(json!({"brushes": nb, "customShapes": ns, "tools": nt})) + } + other => Err(bad(cmd, format!("unknown action `{other}` (export|import)"))), + } +} + +// ------------------------------------------------------------------ specs + +macro_rules! spec { + ($id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $en:expr, $run:expr) => { + CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run, journal: true } + }; +} + +mod content_aware; +mod content_aware_scale; +mod fade; +mod find_replace; +mod presets; +mod purge; + +pub(crate) use content_aware::channel_mask; +pub use content_aware::{CafPlan, FillEdit, MAX_CAF_EDITS, MAX_CAF_POINTS, SelOp, content_aware_plan, content_aware_plan_with}; +use content_aware::{can_caf, content_aware_fill, delete_and_fill}; +pub use content_aware_scale::ContentAwareScalePreview; +use content_aware_scale::content_aware_scale; +pub use fade::fade_surface; +use fade::{can_fade, fade}; +pub use find_replace::find_matches; +use find_replace::{find_replace, has_type_layer}; +pub(crate) use presets::current_path; +pub use presets::{PRESET_FORMAT, PresetFile}; +use presets::{can_define_shape, define_brush_preset, define_custom_shape, preset_manager}; +use purge::{can_purge_all, can_purge_clipboard, can_purge_histories, can_purge_undo, purge}; + +pub fn specs() -> Vec { + vec![ + spec!( + "edit.fade", + "Fade…", + ["Edit"], + Some("Cmd+Shift+F"), + r##"{"opacity":0..100=100,"mode":"normal|multiply|screen|overlay|softLight|hardLight|darken|lighten|difference|color|luminosity"}"##, + can_fade, + fade + ), + spec!("edit.purge.undo", "Undo", ["Edit", "Purge"], None, "{}", can_purge_undo, |s, _| purge(s, "undo")), + spec!("edit.purge.clipboard", "Clipboard", ["Edit", "Purge"], None, "{}", can_purge_clipboard, |s, _| purge(s, "clipboard")), + spec!("edit.purge.histories", "Histories", ["Edit", "Purge"], None, "{}", can_purge_histories, |s, _| purge(s, "histories")), + spec!("edit.purge.videoCache", "Video Cache", ["Edit", "Purge"], None, "{}", always, |_, _| Ok( + json!({"purged": [], "bytes": 0, "message": "nothing to purge (no video layers)"}) + )), + spec!("edit.purge.all", "All", ["Edit", "Purge"], None, "{}", can_purge_all, |s, _| purge(s, "all")), + spec!( + "edit.contentAwareFill", + "Content-Aware Fill…", + ["Edit"], + None, + r##"{"sampling":"auto|rectangular|custom","margin":px?,"area":[x,y,w,h]?,"channel":index|name?,"samplingStrokes":[{"mode":"add|subtract","size":px,"points":[[x,y],…]}]? (the workspace's Sampling Brush, after the sampling option's area; added strokes may lie outside the window),"fillEdits":[{"op":"new|add|subtract|intersect","points":[[x,y],…]}|{"op":"expand|contract","by":px}]? (the workspace's lasso edits of the fill area, in order),"sampleAllLayers":bool=false,"colorAdaptation":"default|none|high|veryHigh","rotationAdaptation":"none|low|medium|high|full","scale":bool=false,"mirror":bool=false,"output":"current|new|duplicate","layer":id?=active (the layer filled and sampled),"seed":u64=1}"##, + can_caf, + content_aware_fill + ), + spec!("edit.deleteAndFillSelection", "Delete and Fill Selection", [], None, "{}", can_caf, delete_and_fill), + spec!( + "edit.contentAwareScale", + "Content-Aware Scale", + ["Edit"], + Some("Cmd+Alt+Shift+C"), + r##"{"width":px?,"height":px?,"scaleX":1..400=100,"scaleY":1..400=100,"x":px?,"y":px?,"amount":0..100=100,"protect":"none"|channel index|name,"protectSkinTones":bool=false}"##, + |s| pixel_layer(s).map(|_| ()), + content_aware_scale + ), + spec!( + "edit.defineBrushPreset", + "Define Brush Preset…", + ["Edit"], + None, + r##"{"name":text}"##, + |s| if s.is_enabled("brush.defineFromSelection") { Ok(()) } else { Err("select pixels to define a brush from".into()) }, + define_brush_preset + ), + spec!( + "edit.defineCustomShape", + "Define Custom Shape…", + ["Edit"], + None, + r##"{"name":text,"path":"work|"?}"##, + can_define_shape, + define_custom_shape + ), + spec!( + "edit.findAndReplaceText", + "Find and Replace Text…", + ["Edit"], + None, + r##"{"find":text,"replace":text,"action":"changeAll|find|change|changeFind","caseSensitive":bool=false,"wholeWord":bool=false,"forward":bool=true,"allLayers":bool=true}"##, + has_type_layer, + find_replace + ), + spec!( + "edit.presets.presetManager", + "Preset Manager…", + ["Edit", "Presets"], + None, + r##"{"action":"list|rename|delete|move","kind":"brushes|customShapes|patterns","index":n?,"name":str?,"newName":str?,"to":n?}"##, + always, + preset_manager + ), + spec!( + "edit.presets.exportImportPresets", + "Export/Import Presets…", + ["Edit", "Presets"], + None, + r##"{"action":"export|import","kinds":["brushes","customShapes","tools"]?,"data":json (import),"includeBuiltins":bool=false}"##, + always, + export_import + ), + ] +} + +/// The custom shape library (for the Custom Shape tool). +pub fn custom_shapes(s: &Session) -> &[CustomShape] { + &s.edit_state.custom_shapes +} + +#[cfg(test)] +#[path = "edit_menu_cmds/tests.rs"] +mod tests; diff --git a/crates/engine/src/cmd/edit_menu_cmds/content_aware.rs b/crates/engine/src/cmd/edit_menu_cmds/content_aware.rs new file mode 100644 index 0000000000..0fe3cedd3f --- /dev/null +++ b/crates/engine/src/cmd/edit_menu_cmds/content_aware.rs @@ -0,0 +1,531 @@ +use super::*; + +// ------------------------------------------------------------------ Content-Aware Fill + +pub(super) fn can_caf(s: &Session) -> std::result::Result<(), String> { + pixel_layer(s)?; + let d = s.active().ok_or("no document open")?; + if d.doc.selection.as_ref().is_none_or(|m| m.content_bounds().is_empty()) { + return Err("make a selection around what to remove".into()); + } + Ok(()) +} + +/// Mask surface (gray) of an alpha channel by index or name. +pub(crate) fn channel_mask<'a>(doc: &'a Document, v: &Value) -> Option<&'a Surface> { + match v { + Value::Number(n) => doc.channels.get(n.as_u64()? as usize).map(|c| &c.surface), + Value::String(name) => doc.channels.iter().find(|c| c.name == *name).map(|c| &c.surface), + _ => None, + } +} + +/// `key` as an `[x, y, w, h]` rectangle. The saturating float→int casts bound each component; +/// the additions saturate too — `area: [1e30, 0, 1e30, 10]` is a whole-canvas window, not an +/// overflow (it panicked in debug builds before the `saturating_add`). +fn rect_param(p: &Value, key: &str, cmd: &str) -> Result { + let a = p.get(key).and_then(Value::as_array).ok_or_else(|| bad(cmd, format!("`{key}` must be [x, y, w, h]")))?; + let n = |i: usize| { + a.get(i) + .and_then(Value::as_f64) + .filter(|f| f.is_finite()) + .map(|v| v.round() as i32) + .ok_or_else(|| bad(cmd, format!("`{key}` must be four finite numbers"))) + }; + let (x, y, w, h) = (n(0)?, n(1)?, n(2)?, n(3)?); + Ok(Rect::new(x, y, x.saturating_add(w.max(0)), y.saturating_add(h.max(0)))) +} + +pub(super) fn content_aware_fill(s: &mut Session, p: &Value) -> Result { + content_aware_fill_as(s, p, "edit.contentAwareFill", "Content-Aware Fill") +} + +/// Delete and Fill Selection (#1286): Photoshop's one-click removal from the selection-tool +/// context menu. Content-Aware Fill into the layer, no dialog, sampling as Edit › Fill does (the +/// whole window, measured on Photoshop 25.4) with the default colour adaptation. +pub(super) fn delete_and_fill(s: &mut Session, _: &Value) -> Result { + content_aware_fill_as(s, &json!({"sampling": "rectangular"}), "edit.deleteAndFillSelection", "Delete and Fill Selection") +} + +/// Everything one Content-Aware Fill needs, worked out from the document and the command's +/// params. The Content-Aware Fill workspace runs exactly this for its preview, so what it shows +/// is what OK and Apply write. +pub struct CafPlan { + pub layer: LayerId, + /// The rectangle worked on: the sampling window, and any sampling-brush strokes or custom + /// area beyond it. + pub rect: Rect, + /// Photoshop's sampling window around the fill area (`content_aware::sampling_window`). + pub window: Rect, + pub fmt: PixelFormat, + /// What is sampled over `rect`: the target's pixels, or with Sample All Layers the visible + /// composite in the target's encoding. + pub img: Vec, + /// The target's own pixels over `rect` when they differ from `img` (Sample All Layers); see + /// [`CafPlan::layer_pixels`]. + pub layer_px: Option>, + /// The fill area (selection coverage, after the workspace's lasso edits) over `rect`. + pub cover: Vec, + pub hole: Vec, + /// What may be copied from: the sampling option's area before the brush strokes, and after. + pub base: Vec, + pub source: Vec, + pub opts: photocraft_algo::content_aware::FillOptions, + pub output: String, +} + +impl CafPlan { + /// The target layer's pixels over `rect`. + pub fn layer_pixels(&self) -> &[f32] { + self.layer_px.as_deref().unwrap_or(&self.img) + } +} + +/// The workspace's lasso edits of the fill area: `{"op": "new|add|subtract|intersect", "points": +/// [[x, y], ...]}` or `{"op": "expand|contract", "by": px}`, applied in order. +#[derive(Clone, Debug, PartialEq)] +pub enum FillEdit { + Lasso { op: SelOp, points: Vec<[f64; 2]> }, + Grow(i32), +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SelOp { + New, + Add, + Subtract, + Intersect, +} + +/// Most `fillEdits` and `samplingStrokes` one fill takes, and most points in all of them +/// together: the strokes and lassos are painted pixel by pixel, segment by segment. +pub const MAX_CAF_EDITS: usize = 1_000; + +pub const MAX_CAF_POINTS: usize = 200_000; + +fn points_param(v: &Value, cmd: &str, what: &str, budget: &mut usize) -> Result> { + let a = v.get("points").and_then(Value::as_array).ok_or_else(|| bad(cmd, format!("{what} needs `points` [[x, y], ...]")))?; + *budget = budget.checked_sub(a.len()).ok_or_else(|| bad(cmd, format!("at most {MAX_CAF_POINTS} points in all fill edits and sampling strokes")))?; + a.iter() + .map(|p| { + let x = p.get(0).and_then(Value::as_f64).filter(|v| v.is_finite() && v.abs() < 1e7); + let y = p.get(1).and_then(Value::as_f64).filter(|v| v.is_finite() && v.abs() < 1e7); + match (x, y) { + (Some(x), Some(y)) => Ok([x, y]), + _ => Err(bad(cmd, format!("{what} points must be pairs of finite numbers"))), + } + }) + .collect() +} + +/// `p[key]` as an array of at most [`MAX_CAF_EDITS`] entries (empty when absent). +fn edits_param<'a>(p: &'a Value, key: &str, cmd: &str) -> Result<&'a [Value]> { + let Some(a) = p.get(key) else { return Ok(&[]) }; + let a = a.as_array().ok_or_else(|| bad(cmd, format!("`{key}` must be an array")))?; + if a.len() > MAX_CAF_EDITS { + return Err(bad(cmd, format!("`{key}` takes at most {MAX_CAF_EDITS} entries"))); + } + Ok(a) +} + +fn fill_edits(p: &Value, cmd: &str, budget: &mut usize) -> Result> { + edits_param(p, "fillEdits", cmd)? + .iter() + .map(|e| { + let op = e.get("op").and_then(Value::as_str).unwrap_or(""); + Ok(match op { + "expand" | "contract" => { + let by = e + .get("by") + .and_then(Value::as_f64) + .filter(|v| v.is_finite() && (0.0..=1000.0).contains(v)) + .ok_or_else(|| bad(cmd, "`by` must be 0..1000 px"))?; + FillEdit::Grow(if op == "expand" { by.round() as i32 } else { -(by.round() as i32) }) + } + "new" | "add" | "subtract" | "intersect" => FillEdit::Lasso { + op: match op { + "new" => SelOp::New, + "add" => SelOp::Add, + "subtract" => SelOp::Subtract, + _ => SelOp::Intersect, + }, + points: points_param(e, cmd, "a lasso edit", budget)?, + }, + o => return Err(bad(cmd, format!("unknown fill edit `{o}` (new|add|subtract|intersect|expand|contract)"))), + }) + }) + .collect() +} + +fn sampling_strokes(p: &Value, cmd: &str, budget: &mut usize) -> Result> { + edits_param(p, "samplingStrokes", cmd)? + .iter() + .map(|e| { + let add = match e.get("mode").and_then(Value::as_str).unwrap_or("add") { + "add" => true, + "subtract" => false, + o => return Err(bad(cmd, format!("unknown stroke mode `{o}` (add|subtract)"))), + }; + let size = e + .get("size") + .and_then(Value::as_f64) + .filter(|v| v.is_finite() && (1.0..=5000.0).contains(v)) + .ok_or_else(|| bad(cmd, "a stroke's `size` must be 1..5000 px"))?; + Ok(photocraft_algo::content_aware::SamplingStroke { add, size, points: points_param(e, cmd, "a sampling stroke", budget)? }) + }) + .collect() +} + +/// A Content-Aware Fill's params, checked against the document before any pixel is read. +struct CafParams<'a> { + sel: &'a Surface, + /// The selection's bounds on the canvas. + sb: Rect, + edits: Vec, + strokes: Vec, + sampling: String, + custom_mask: Option<&'a Surface>, + custom_rect: Option, + opts: photocraft_algo::content_aware::FillOptions, + output: String, + surf: &'a Surface, +} + +fn caf_params<'a>(doc: &'a Document, id: LayerId, p: &Value, cmd: &str) -> Result> { + use photocraft_algo::content_aware::{FillOptions, color_level, rotation_level}; + let sel = doc.selection.as_ref().ok_or_else(|| bad(cmd, "no selection"))?; + let sb = sel.content_bounds().intersect(&doc.bounds()); + if sb.is_empty() { + return Err(bad(cmd, "the selection is outside the canvas")); + } + let mut budget = MAX_CAF_POINTS; + let edits = fill_edits(p, cmd, &mut budget)?; + let strokes = sampling_strokes(p, cmd, &mut budget)?; + let sampling = str_or(p, "sampling", "auto").to_string(); + let custom_mask: Option<&Surface> = p.get("channel").and_then(|v| channel_mask(doc, v)); + let custom_rect = if p.get("area").is_some() { Some(rect_param(p, "area", cmd)?) } else { None }; + match sampling.as_str() { + "auto" | "rectangular" => {} + // The workspace's Custom: only what the Sampling Brush adds. + "custom" if custom_rect.is_some() || custom_mask.is_some() || strokes.iter().any(|s| s.add) => {} + "custom" => return Err(bad(cmd, "custom sampling needs `area` [x,y,w,h], `channel` (alpha channel index or name) or `samplingStrokes`")), + other => return Err(bad(cmd, format!("unknown sampling `{other}` (auto|rectangular|custom)"))), + } + let opts = FillOptions { + color_adaptation: color_level(str_or(p, "colorAdaptation", "default")), + rotations: rotation_level(str_or(p, "rotationAdaptation", "none")), + scale: bool_or(p, "scale", false), + mirror: bool_or(p, "mirror", false), + seed: p.get("seed").and_then(Value::as_u64).unwrap_or(1), + }; + let output = str_or(p, "output", "current").to_string(); + if !matches!(output.as_str(), "current" | "new" | "duplicate") { + return Err(bad(cmd, "`output` must be current|new|duplicate")); + } + let surf = doc.layer(id).and_then(|l| l.surface()).ok_or(EngineError::NoLayer(id))?; + Ok(CafParams { sel, sb, edits, strokes, sampling, custom_mask, custom_rect, opts, output, surf }) +} + +/// Work out a Content-Aware Fill (see [`CafPlan`]) on layer `id` of `doc`. +pub fn content_aware_plan(doc: &Document, id: LayerId, p: &Value, cmd: &str) -> Result { + content_aware_plan_with(doc, id, p, cmd, &photocraft_raster::Interrupt::NONE) +} + +/// [`content_aware_plan`], asking `ctl` row by row whether to stop ([`EngineError::Cancelled`]). +pub fn content_aware_plan_with(doc: &Document, id: LayerId, p: &Value, cmd: &str, ctl: &photocraft_raster::Interrupt) -> Result { + use photocraft_algo::content_aware::{auto_sampling_with, grow_mask, paint_strokes, polygon_mask}; + use rayon::prelude::*; + + use crate::fill_cmds::{read_window, read_window_mask}; + let CafParams { sel, sb, edits, strokes, sampling, custom_mask, custom_rect, opts, output, surf } = caf_params(doc, id, p, cmd)?; + let canvas = doc.bounds(); + let cancel = || ctl.cancelled(); + let stop = || if ctl.cancelled() { Err(EngineError::Cancelled) } else { Ok(()) }; + // The fill area: the selection, then the lasso edits, over a rectangle that holds them all. + let grow: i32 = edits.iter().map(|e| if let FillEdit::Grow(b) = e { b.max(&0) } else { &0 }).sum(); + let reach = edits.iter().fold(sb, |r, e| match e { + FillEdit::Lasso { points, .. } => { + points.iter().fold(r, |r, q| r.union(&Rect::new(q[0].floor() as i32, q[1].floor() as i32, q[0].floor() as i32 + 1, q[1].floor() as i32 + 1))) + } + FillEdit::Grow(_) => r, + }); + let er = reach.inflate(grow.saturating_add(1)).intersect(&canvas); + let (ew, eh) = crate::fill_cmds::window_size(er)?; + let ecover = read_window_mask(sel, er, &cancel).ok_or(EngineError::Cancelled)?; + let mut ehole: Vec = ecover.par_iter().map(|c| *c > 0.0).collect(); + for e in &edits { + stop()?; + match e { + FillEdit::Lasso { op, points } => { + let m = polygon_mask(er, points); + for (h, v) in ehole.iter_mut().zip(&m) { + *h = match op { + SelOp::New => *v, + SelOp::Add => *h || *v, + SelOp::Subtract => *h && !*v, + SelOp::Intersect => *h && *v, + }; + } + } + FillEdit::Grow(by) => ehole = grow_mask(&ehole, ew, eh, *by), + } + } + let (bx0, by0, bx1, by1) = mask_bounds(ew, eh, &ehole); + if bx1 <= bx0 { + return Err(bad(cmd, "the fill area is empty")); + } + let hb = Rect::new(er.x0 + bx0 as i32, er.y0 + by0 as i32, er.x0 + bx1 as i32, er.y0 + by1 as i32); + // Photoshop's window (`content_aware::sampling_window`) for Auto and Rectangular; `margin` + // asks for a rectangle that far around the fill area instead. + let window = match sampling.as_str() { + "rectangular" => match int(p, "margin") { + Some(m) => hb.inflate(m.clamp(0, 100_000) as i32), + None => crate::fill_cmds::sampling_window(hb, canvas), + }, + "custom" => match (custom_rect, custom_mask) { + (Some(r), _) => r, + (None, Some(m)) => m.content_bounds(), + (None, None) => hb, + } + .union(&hb) + .inflate(4), + _ => crate::fill_cmds::sampling_window(hb, canvas), + } + .intersect(&canvas); + // Strokes that add to the sampling area may reach past the window. + let rect = strokes.iter().filter(|s| s.add).fold(window, |r, s| r.union(&s.bounds())).intersect(&canvas); + let fmt = surf.format(); + // Photoshop's Sample All Layers checkbox is off unless the caller asks. When the active + // layer has no pixels in the window there is nothing to sample, so that case uses the + // visible composite (#4026). An explicit false still reads only this layer. + let sample_all = match p.get("sampleAllLayers").and_then(Value::as_bool) { + Some(v) => v, + None => surf.content_bounds().intersect(&window).is_empty(), + }; + let n = fmt.channels(); + // Refuse a window too large to read before allocating for it, whatever the sampling (#963). + let (w, h) = crate::fill_cmds::window_size(rect)?; + let pixels = read_window(surf, rect, &cancel).ok_or(EngineError::Cancelled)?; + let (img, layer_px) = if sample_all { + stop()?; + (crate::retouch_cmds::composite_region(doc, Some(id), crate::retouch_cmds::SampleLayers::All, rect, fmt).data, Some(pixels)) + } else { + (pixels, None) + }; + stop()?; + let mut cover = vec![0.0f32; w * h]; + let mut hole = vec![false; w * h]; + cover.par_chunks_mut(w.max(1)).zip(hole.par_chunks_mut(w.max(1))).enumerate().try_for_each(|(y, (crow, hrow))| { + stop()?; + let dy = rect.y0 + y as i32; + if dy < er.y0 || dy >= er.y1 { + return Ok(()); + } + for (x, (c, hl)) in crow.iter_mut().zip(hrow.iter_mut()).enumerate() { + let dx = rect.x0 + x as i32; + if dx >= er.x0 && dx < er.x1 { + let j = (dy - er.y0) as usize * ew + (dx - er.x0) as usize; + let (eh, ec) = (ehole.get(j).copied().unwrap_or(false), ecover.get(j).copied().unwrap_or(0.0)); + *hl = eh; + // Pixels the lasso added are filled outright; selected ones by their coverage. + *c = if eh { if ec > 0.0 { ec } else { 1.0 } } else { 0.0 }; + } + } + Ok::<(), EngineError>(()) + })?; + drop((ecover, ehole)); + // The sampling option's area: Auto keeps what looks like the surroundings within the window, + // Rectangular the whole window, Custom the given area (or nothing, for the brush to add to). + let mut base = vec![false; w * h]; + match sampling.as_str() { + "auto" | "rectangular" => { + let (ww, wh) = (window.width() as usize, window.height() as usize); + let (ox, oy) = ((window.x0 - rect.x0) as usize, (window.y0 - rect.y0) as usize); + let area: Vec = match sampling.as_str() { + "auto" if window == rect => auto_sampling_with(w, h, n, &img, &hole, ctl).map_err(|_| EngineError::Cancelled)?, + "auto" => { + let mut wimg = vec![0.0f32; ww * wh * n]; + let mut whole = vec![false; ww * wh]; + for y in 0..wh { + let s = ((oy + y) * w + ox) * n; + wimg[y * ww * n..(y + 1) * ww * n].copy_from_slice(&img[s..s + ww * n]); + whole[y * ww..(y + 1) * ww].copy_from_slice(&hole[(oy + y) * w + ox..(oy + y) * w + ox + ww]); + } + auto_sampling_with(ww, wh, n, &wimg, &whole, ctl).map_err(|_| EngineError::Cancelled)? + } + _ => vec![true; ww * wh], + }; + for y in 0..wh { + base[(oy + y) * w + ox..(oy + y) * w + ox + ww].copy_from_slice(&area[y * ww..(y + 1) * ww]); + } + } + _ => match (custom_rect, custom_mask) { + (Some(r), _) => base.par_iter_mut().enumerate().for_each(|(i, b)| *b = r.contains(rect.x0 + (i % w) as i32, rect.y0 + (i / w) as i32)), + (None, Some(m)) => { + let v = read_window_mask(m, rect, &cancel).ok_or(EngineError::Cancelled)?; + base.par_iter_mut().zip(&v).for_each(|(b, v)| *b = *v > 0.5); + } + (None, None) => {} + }, + } + stop()?; + base.par_iter_mut().zip(&hole).for_each(|(b, h)| *b &= !*h); + let mut source = base.clone(); + paint_strokes(&mut source, rect, &strokes); + source.par_iter_mut().zip(&hole).for_each(|(s, h)| *s &= !*h); + Ok(CafPlan { layer: id, rect, window, fmt, img, layer_px, cover, hole, base, source, opts, output }) +} + +fn content_aware_fill_as(s: &mut Session, p: &Value, cmd: &'static str, label: &'static str) -> Result { + use photocraft_algo::content_aware::fill_owned; + // The workspace names the layer it opened on: after an Apply to a new layer that one is + // active, but the fill still samples the original. + let id = match p.get("layer").and_then(Value::as_u64) { + Some(l) => pixel_layer_id(s, LayerId(l)), + None => pixel_layer(s), + } + .map_err(EngineError::Other)?; + let st = s.active().ok_or(EngineError::NoDocument)?; + let doc = st.doc.clone(); + // Check the params before the job starts. + caf_params(&doc, id, p, cmd)?; + let p = p.clone(); + // A background job when started with `Session::start` (#210): working out the fill area and + // the sampling area, reading the pixels and the PatchMatch fill run on a worker against the + // document snapshot, cancellable per row band. + crate::jobs::run( + s, + label, + true, + move |ctx| { + use rayon::prelude::*; + ctx.progress(0.0, label); + let cancel = || ctx.cancelled(); + let plan = content_aware_plan_with(&doc, id, &p, cmd, &photocraft_raster::Interrupt::cancel_only(&cancel))?; + let CafPlan { layer, rect, fmt, img, layer_px, cover, hole, source, opts, output, .. } = plan; + // Patches come only from the sampling area outside the fill area. With none (a + // Rectangular `margin` of 0, a Custom area inside the selection or off the canvas) + // the fill would be black (#6532), so refuse instead. The workspace's preview builds + // the same plan and may show an empty area while the Sampling Brush adds to it. + if !source.iter().any(|s| *s) { + return Err(bad(cmd, "nothing to sample from: the sampling area has no pixels outside the fill area")); + } + let (w, h) = (rect.width() as usize, rect.height() as usize); + let n = fmt.channels(); + // The fill changes only the fill area: keep the layer's pixels and the coverage over + // its bounds for the apply step, and fill the sampled pixels themselves. + let (bx0, by0, bx1, by1) = mask_bounds(w, h, &hole); + let own = layer_px.as_deref().unwrap_or(&img); + let original: Vec = (by0..by1).flat_map(|y| own[(y * w + bx0) * n..(y * w + bx1) * n].iter().copied()).collect(); + let cover: Vec = (by0..by1).flat_map(|y| cover[y * w + bx0..y * w + bx1].iter().copied()).collect(); + let n_hole = cover.iter().filter(|c| **c > 0.0).count(); + ctx.check()?; + let mut filled = ctx.stage(0.05, 1.0, label, |ctl| fill_owned(w, h, n, img, &hole, &source, &opts, ctl)).map_err(|_| EngineError::Cancelled)?; + // Sampled from all layers: outside the fill area the window keeps the layer's pixels. + if let Some(own) = layer_px { + filled.par_chunks_mut(n.max(1)).zip(own.par_chunks(n.max(1))).zip(hole.par_iter()).for_each(|((f, o), h)| { + if !*h { + f.copy_from_slice(o); + } + }); + } + Ok((layer, rect, fmt, output, FilledWindow { filled, bounds: (bx0, by0, bx1, by1), original, cover, n_hole })) + }, + move |s, (layer, rect, fmt, output, done)| apply_content_aware_fill(s, label, layer, &output, fmt, rect, done), + ) +} + +/// A Content-Aware Fill's result for its apply step: the filled window (the same as the +/// original outside the selected pixels) and, over the bounds of the selected pixels (in window +/// coordinates), the original pixels and the selection's coverage. +struct FilledWindow { + filled: Vec, + bounds: (usize, usize, usize, usize), + original: Vec, + cover: Vec, + n_hole: usize, +} + +/// `f(window index, index over the bounds, coverage)` for each selected pixel of a +/// [`FilledWindow`] (`w` wide). +fn each_selected(w: usize, (bx0, by0, bx1, by1): (usize, usize, usize, usize), cover: &[f32], mut f: impl FnMut(usize, usize, f32)) { + let bw = bx1.saturating_sub(bx0); + for y in by0..by1 { + for x in bx0..bx1 { + let k = (y - by0) * bw + (x - bx0); + if let Some(&c) = cover.get(k) + && c > 0.0 + { + f(y * w + x, k, c); + } + } + } +} + +/// Bounds `(x0, y0, x1, y1)` of the set cells of a `w × h` mask (all zero when there are none). +fn mask_bounds(w: usize, h: usize, m: &[bool]) -> (usize, usize, usize, usize) { + use rayon::prelude::*; + if w == 0 { + return (0, 0, 0, 0); + } + let rows: Vec> = + m.par_chunks(w).take(h).map(|row| Some((row.iter().position(|v| *v)?, row.iter().rposition(|v| *v)? + 1))).collect(); + let mut b: Option<(usize, usize, usize, usize)> = None; + for (y, span) in rows.into_iter().enumerate() { + if let Some((x0, x1)) = span { + b = Some(b.map_or((x0, y, x1, y + 1), |(bx0, by0, bx1, _)| (bx0.min(x0), by0, bx1.max(x1), y + 1))); + } + } + b.unwrap_or((0, 0, 0, 0)) +} + +/// Write a Content-Aware Fill result (the job's apply step): into the layer, a new layer or a +/// duplicate, as one undo step. +fn apply_content_aware_fill(s: &mut Session, label: &str, id: LayerId, output: &str, fmt: PixelFormat, window: Rect, done: FilledWindow) -> Result { + let n = fmt.channels(); + let (w, h) = (window.width() as usize, window.height() as usize); + let FilledWindow { mut filled, bounds, original, cover, n_hole } = done; + let layer = s.edit(label, |doc, active| { + let target = match output { + "new" => { + let mut l = Layer::raster(doc.next_layer_name("Content-Aware Fill"), PixelFormat { alpha: true, ..fmt }); + let mut px = vec![0.0f32; w * h * n.max(1)]; + let lf = l.surface().map(|s| s.format()).unwrap_or(fmt); + let ln = lf.channels(); + px.resize(w * h * ln, 0.0); + each_selected(w, bounds, &cover, |i, _, c| { + let rgba = to_rgba(&fmt, &filled[i * n..(i + 1) * n]); + let mut enc = [0.0f32; 8]; + from_rgba_into(&lf, [rgba[0], rgba[1], rgba[2], rgba[3] * c], &mut enc); + px[i * ln..(i + 1) * ln].copy_from_slice(&enc[..ln]); + }); + if let Some(s) = l.surface_mut() { + s.write_region(window, &px); + s.prune(); + } + let nid = doc.insert_above(Some(id), l); + *active = Some(nid); + return Ok(nid); + } + "duplicate" => { + let mut dup = doc.layer(id).ok_or(EngineError::NoLayer(id))?.duplicate(); + dup.name = doc.copy_name(&dup.name); + let nid = doc.insert_above(Some(id), dup); + *active = Some(nid); + nid + } + _ => id, + }; + let surf = writable_surface(doc, target)?; + // The fill blended in by the coverage (elsewhere it is the original). + each_selected(w, bounds, &cover, |i, k, c| { + for ch in 0..n { + let (j, o) = (i * n + ch, k * n + ch); + filled[j] = original[o] + (filled[j] - original[o]) * c; + } + }); + surf.write_region(window, &filled); + Ok(target) + })?; + Ok(json!({"layer": layer.0, "filled": n_hole, "window": [window.x0, window.y0, window.width(), window.height()]})) +} diff --git a/crates/engine/src/cmd/edit_menu_cmds/content_aware_scale.rs b/crates/engine/src/cmd/edit_menu_cmds/content_aware_scale.rs new file mode 100644 index 0000000000..998f30821a --- /dev/null +++ b/crates/engine/src/cmd/edit_menu_cmds/content_aware_scale.rs @@ -0,0 +1,202 @@ +use super::content_aware::channel_mask; +use super::*; + +// ------------------------------------------------------------------ Content-Aware Scale + +/// Reach of Content-Aware Scale's `x`/`y`: the largest document side. +const CAS_POSITION_LIMIT: f64 = 300_000.0; + +/// What Content-Aware Scale does, read from its params against the active document: the +/// command and the transform box's live preview ([`ContentAwareScalePreview`]) share it. +struct CasPlan { + doc: std::sync::Arc, + layer: LayerId, + /// The area scaled: the selection's bounds, else the layer's content. + region: Rect, + /// Where the result goes: `x`, `y` (default: the region's corner), `width`, `height`. + dst: Rect, + amount: f32, + protect: Option, + skin_tones: bool, +} + +fn cas_plan(s: &Session, p: &Value) -> Result { + let cmd = "edit.contentAwareScale"; + let id = pixel_layer(s).map_err(EngineError::Other)?; + let st = s.active().ok_or(EngineError::NoDocument)?; + let doc = st.doc.clone(); + let surf = doc.layer(id).and_then(|l| l.surface()).ok_or(EngineError::NoLayer(id))?; + let region = match &doc.selection { + Some(sel) => sel.content_bounds().intersect(&doc.bounds()), + None => surf.content_bounds(), + }; + if region.is_empty() { + return Err(EngineError::Other("nothing to scale: the layer is empty".into())); + } + let (w, h) = (region.width() as usize, region.height() as usize); + let dim = |k: &str, pct: &str, cur: usize| -> Result { + let v = match (p.get(k).and_then(Value::as_f64), p.get(pct).and_then(Value::as_f64)) { + (Some(px), _) => px, + (None, Some(pc)) => cur as f64 * pc / 100.0, + (None, None) => cur as f64, + }; + if !(1.0..=60_000.0).contains(&v) { + return Err(bad(cmd, format!("`{k}` must be 1..60000 px"))); + } + Ok(v.round() as u32) + }; + let (nw, nh) = (dim("width", "scaleX", w)?, dim("height", "scaleY", h)?); + let at = |k: &str, cur: i32| -> Result { + match p.get(k).filter(|v| !v.is_null()) { + None => Ok(cur), + Some(v) => match v.as_f64() { + Some(x) if (-CAS_POSITION_LIMIT..=CAS_POSITION_LIMIT).contains(&x) => Ok(x.round() as i32), + _ => Err(bad(cmd, format!("`{k}` must be a number of px within ±300000"))), + }, + } + }; + let dst = Rect::from_xywh(at("x", region.x0)?, at("y", region.y0)?, nw, nh); + let amount = f32_or(p, "amount", 100.0).clamp(0.0, 100.0) / 100.0; + // Protection: an alpha channel and/or skin tones. + let protect = match p.get("protect").filter(|v| !v.is_null() && v.as_str() != Some("none")) { + Some(v) => Some(channel_mask(&doc, v).cloned().ok_or_else(|| bad(cmd, "`protect` must name an alpha channel (index or name) or \"none\""))?), + None => None, + }; + let skin_tones = bool_or(p, "protectSkinTones", false); + Ok(CasPlan { doc, layer: id, region, dst, amount: if amount.is_finite() { amount } else { 1.0 }, protect, skin_tones }) +} + +/// The scaled pixels: `img` (`w`×`h`, `fmt`) seam-carved to `nw`×`nh` where the protection +/// (`protect`, one value per pixel, and the skin tones when asked) steers the seams, blended with +/// a plain resample by `amount` (0..1). Checks `ctx` for cancellation before every seam. +#[allow(clippy::too_many_arguments)] +fn cas_pixels( + ctx: &crate::jobs::JobCtx, + label: &str, + img: &[f32], + (w, h): (usize, usize), + fmt: PixelFormat, + mut protect: Option>, + skin_tones: bool, + (nw, nh): (usize, usize), + amount: f32, +) -> Result> { + use photocraft_algo::seam::{carve_with, resize_bilinear, skin_mask}; + let n = fmt.channels(); + if skin_tones { + let rgba: Vec = img.chunks_exact(n).flat_map(|px| to_rgba(&fmt, px)).collect(); + let skin = skin_mask(w, h, 4, &rgba); + protect = Some(match protect { + Some(pm) => pm.iter().zip(&skin).map(|(a, b)| a.max(*b)).collect(), + None => skin, + }); + } + ctx.check()?; + let carved = if amount > 0.0 { + ctx.stage(0.05, 0.95, label, |ctl| carve_with(w, h, n, img, protect.as_deref(), nw, nh, ctl)).map_err(|_| EngineError::Cancelled)? + } else { + Vec::new() + }; + let plain = if amount < 1.0 { resize_bilinear(w, h, n, img, nw, nh) } else { Vec::new() }; + Ok(match (carved.is_empty(), plain.is_empty()) { + (false, true) => carved, + (true, false) => plain, + _ => carved.iter().zip(&plain).map(|(c, l)| l + (c - l) * amount).collect::>(), + }) +} + +pub(super) fn content_aware_scale(s: &mut Session, p: &Value) -> Result { + let CasPlan { doc, layer: id, region, dst, amount, protect: protect_mask, skin_tones } = cas_plan(s, p)?; + let (w, h) = (region.width() as usize, region.height() as usize); + let (nw, nh) = (dst.width() as usize, dst.height() as usize); + let label = "Content-Aware Scale"; + // A background job when started with `Session::start` (#210): seam carving runs on a worker + // against the document snapshot and checks for cancellation before every seam. + crate::jobs::run( + s, + label, + true, + move |ctx| { + ctx.progress(0.0, label); + let surf = doc.layer(id).and_then(|l| l.surface()).ok_or(EngineError::NoLayer(id))?; + let img = surf.read_region(region); + let protect: Option> = + protect_mask.map(|m| (0..w * h).map(|i| m.sample_channel(region.x0 + (i % w) as i32, region.y0 + (i / w) as i32, 0)).collect()); + cas_pixels(ctx, label, &img, (w, h), surf.format(), protect, skin_tones, (nw, nh), amount) + }, + move |s, out| { + s.edit(label, |doc, _| { + let surf = writable_surface(doc, id)?; + crate::pixels::try_clear_surface(surf, region, None)?; + surf.write_region(dst, &out); + surf.prune(); + Ok(()) + })?; + Ok(json!({"from": [w, h], "to": [nw, nh], "bounds": [dst.x0, dst.y0, nw, nh]})) + }, + ) +} + +/// Content-Aware Scale on a reduced copy, for the transform box's live preview (#3096): the +/// command's own carving, on the area scaled down so the longer of its sides before and after +/// is at most `max_side` px. Prepared from the session ([`ContentAwareScalePreview::new`]) and +/// [`run`](ContentAwareScalePreview::run) on any thread. +pub struct ContentAwareScalePreview { + plan: CasPlan, + max_side: u32, +} + +impl ContentAwareScalePreview { + /// `p` takes `edit.contentAwareScale`'s params; the same ones fail the same way. + pub fn new(s: &Session, p: &Value, max_side: u32) -> Result { + Ok(Self { plan: cas_plan(s, p)?, max_side: max_side.max(1) }) + } + + /// The area scaled, in document px. + pub fn region(&self) -> Rect { + self.plan.region + } + + /// The reduced sizes of the area before and after: `[w, h, new w, new h]`. + fn reduced(&self) -> [usize; 4] { + let (region, dst) = (self.plan.region, self.plan.dst); + let (w, h, nw, nh) = (region.width(), region.height(), dst.width(), dst.height()); + let k = (f64::from(w.max(h).max(nw).max(nh)) / f64::from(self.max_side)).max(1.0); + let side = |v: u32| ((f64::from(v) / k).round() as usize).max(1); + [side(w), side(h), side(nw), side(nh)] + } + + /// The size of [`run`](Self::run)'s result, px. + pub fn size(&self) -> [u32; 2] { + let [_, _, w, h] = self.reduced(); + [w as u32, h as u32] + } + + /// The scaled pixels at the reduced size ([`size`](Self::size)), in the layer's format, as a + /// surface with its corner at the origin. Checks `ctx` for cancellation before every seam. + pub fn run(&self, ctx: &crate::jobs::JobCtx) -> Result { + let CasPlan { doc, layer, region, dst: _, amount, protect, skin_tones } = &self.plan; + let surf = doc.layer(*layer).and_then(|l| l.surface()).ok_or(EngineError::NoLayer(*layer))?; + let fmt = surf.format(); + let n = fmt.channels(); + let (w, h) = (region.width(), region.height()); + let [pw, ph, pnw, pnh] = self.reduced(); + // Nearest samples of the area (and of the protecting channel) at the reduced size. + let src_x: Vec = (0..pw).map(|i| region.x0 + (((i as f64 + 0.5) * f64::from(w) / pw as f64) as i32).min(w as i32 - 1)).collect(); + let src_y = |j: usize| region.y0 + (((j as f64 + 0.5) * f64::from(h) / ph as f64) as i32).min(h as i32 - 1); + let mut img = Vec::with_capacity(pw * ph * n); + for j in 0..ph { + ctx.check()?; + let row = surf.read_region(Rect::from_xywh(region.x0, src_y(j), w, 1)); + for &x in &src_x { + let at = (x - region.x0) as usize * n; + img.extend_from_slice(row.get(at..at + n).ok_or_else(|| EngineError::Other("preview read out of bounds".into()))?); + } + } + let protect = protect.as_ref().map(|m| (0..pw * ph).map(|i| m.sample_channel(src_x[i % pw], src_y(i / pw), 0)).collect()); + let out = cas_pixels(ctx, "Content-Aware Scale", &img, (pw, ph), fmt, protect, *skin_tones, (pnw, pnh), *amount)?; + let mut s = Surface::new(fmt); + s.write_region(Rect::from_xywh(0, 0, pnw as u32, pnh as u32), &out); + Ok(s) + } +} diff --git a/crates/engine/src/cmd/edit_menu_cmds/fade.rs b/crates/engine/src/cmd/edit_menu_cmds/fade.rs new file mode 100644 index 0000000000..5ab5e4455b --- /dev/null +++ b/crates/engine/src/cmd/edit_menu_cmds/fade.rs @@ -0,0 +1,90 @@ +use super::*; + +// ------------------------------------------------------------------ Fade + +pub(super) fn can_fade(s: &Session) -> std::result::Result<(), String> { + let st = s.active().ok_or("no document open")?; + let f = s.edit_state.fade.as_ref().ok_or("nothing to fade")?; + if f.doc != st.doc.id || f.revision != st.revision || !st.history.can_undo() { + return Err("Fade is only available right after a filter, adjustment or painting step".into()); + } + if surface_of(&st.doc, f.target).is_none() { + return Err(match f.target { + FadeTarget::Pixels(_) | FadeTarget::Mask(_) => "the faded layer no longer exists".into(), + FadeTarget::Channel(_) | FadeTarget::QuickMask => "the faded channel no longer exists".into(), + }); + } + Ok(()) +} + +/// Blend `after` back towards `before` over `area`: `before + opacity × (B(before, after) − before)` +/// with blend mode `mode` (premultiplied, so alpha changes fade too). +pub fn fade_surface(before: &Surface, after: &mut Surface, area: Rect, mode: BlendMode, opacity: f32) -> Result<()> { + let fmt = after.format(); + let n = fmt.channels(); + if area.is_empty() || n == 0 { + return Ok(()); + } + let b = crate::allocation::read_region(before, area, "fading pixels")?; + let mut a = crate::allocation::read_region(after, area, "fading pixels")?; + let k = opacity.clamp(0.0, 1.0); + let lerp_premul = |pb: &[f32], pa: &[f32], out: &mut [f32], alpha: bool| { + let m = out.len(); + if !alpha { + for c in 0..m { + out[c] = pb[c] + (pa[c] - pb[c]) * k; + } + return; + } + let (ab, aa) = (pb[m - 1], pa[m - 1]); + let ao = ab + (aa - ab) * k; + for c in 0..m - 1 { + let pm = pb[c] * ab + (pa[c] * aa - pb[c] * ab) * k; + out[c] = if ao > 1e-9 { pm / ao } else { 0.0 }; + } + out[m - 1] = ao; + }; + let mut tmp = crate::allocation::filled(n, 0.0f32, "fading pixels")?; + for (pa, pb) in a.chunks_exact_mut(n).zip(b.chunks_exact(n)) { + if mode == BlendMode::Normal || n == 1 { + lerp_premul(pb, pa, &mut tmp, fmt.alpha); + pa.copy_from_slice(&tmp); + } else { + let rb = to_rgba(&fmt, pb); + let ra = to_rgba(&fmt, pa); + let blended = photocraft_color::blend::composite(mode, rb, ra, 1.0); + let mut o = [0.0f32; 4]; + lerp_premul(&rb, &blended, &mut o, true); + let mut enc = [0.0f32; 8]; + from_rgba_into(&fmt, o, &mut enc); + pa.copy_from_slice(&enc[..n]); + } + } + after.try_write_region(area, &a)?; + Ok(()) +} + +pub(super) fn fade(s: &mut Session, p: &Value) -> Result { + let cmd = "edit.fade"; + let src = s.edit_state.fade.clone().ok_or_else(|| bad(cmd, "nothing to fade"))?; + let opacity = f32_or(p, "opacity", 100.0).clamp(0.0, 100.0) / 100.0; + let mode = blend_from_str(str_or(p, "mode", "normal")).ok_or_else(|| bad(cmd, "unknown blend mode"))?; + let st = s.active().ok_or(EngineError::NoDocument)?; + let prev = st.history.past_len().checked_sub(1).and_then(|i| st.history.state(i)).ok_or_else(|| bad(cmd, "no previous state"))?; + let before = surface_of(&prev, src.target).cloned().ok_or_else(|| EngineError::Other("the layer or channel did not exist before this step".into()))?; + let now = surface_of(&st.doc, src.target).ok_or_else(|| EngineError::Other("the faded layer or channel no longer exists".into()))?; + if now.format() != before.format() { + return Err(EngineError::Other("can't fade a step that changed the layer's pixel format".into())); + } + // A uniform mask can change every pixel without storing a single tile. In that case + // the content bounds are empty, but Fade must still blend across the canvas. + let area = if before.default_pixel() != now.default_pixel() { st.doc.bounds() } else { before.content_bounds().union(&now.content_bounds()) }; + let label = format!("Fade {}", src.label); + s.edit(&label, |doc, _| { + let surf = surface_of_mut(doc, src.target).ok_or_else(|| EngineError::Other("the faded layer or channel no longer exists".into()))?; + fade_surface(&before, surf, area, mode, opacity)?; + surf.prune(); + Ok(()) + })?; + Ok(json!({"faded": src.label, "opacity": opacity * 100.0, "mode": mode.label()})) +} diff --git a/crates/engine/src/cmd/edit_menu_cmds/find_replace.rs b/crates/engine/src/cmd/edit_menu_cmds/find_replace.rs new file mode 100644 index 0000000000..91f16950f1 --- /dev/null +++ b/crates/engine/src/cmd/edit_menu_cmds/find_replace.rs @@ -0,0 +1,163 @@ +use super::*; + +// ------------------------------------------------------------------ Find and Replace Text + +/// Byte ranges of `find` in `text` (case-insensitive unless `case`; whole words only with `whole`). +pub fn find_matches(text: &str, find: &str, case: bool, whole: bool) -> Vec<(usize, usize)> { + if find.is_empty() { + return Vec::new(); + } + let norm = |c: char| -> String { if case { c.to_string() } else { c.to_lowercase().collect() } }; + let needle: String = find.chars().map(norm).collect(); + let mut out = Vec::new(); + let mut at = 0; + while at < text.len() { + // Compare char by char so case folding that changes byte lengths stays aligned. + let mut hay = String::new(); + let mut end = at; + for (i, c) in text[at..].char_indices() { + if hay.len() >= needle.len() { + break; + } + hay.push_str(&norm(c)); + end = at + i + c.len_utf8(); + } + if hay == needle { + let word = |c: Option| c.is_some_and(|c| c.is_alphanumeric() || c == '_'); + let before = text[..at].chars().next_back(); + let after = text[end..].chars().next(); + if !whole || (!word(before) && !word(after)) { + out.push((at, end)); + at = end; + continue; + } + } + at += text[at..].chars().next().map_or(1, char::len_utf8); + } + out +} + +fn type_layers(doc: &Document, forward: bool) -> Vec { + // Layers panel order: top first. + let mut ids: Vec = + doc.walk().into_iter().rev().filter(|(p, _, l)| matches!(l.content, LayerContent::Text(_)) && !doc.locks_at(p).all).map(|(_, _, l)| l.id).collect(); + if !forward { + ids.reverse(); + } + ids +} + +pub(super) fn has_type_layer(s: &Session) -> std::result::Result<(), String> { + let d = s.active().ok_or("no document open")?; + if type_layers(&d.doc, true).is_empty() { Err("the document has no type layers".into()) } else { Ok(()) } +} + +pub(super) fn find_replace(s: &mut Session, p: &Value) -> Result { + let cmd = "edit.findAndReplaceText"; + let find = p.get("find").and_then(Value::as_str).filter(|f| !f.is_empty()).ok_or_else(|| bad(cmd, "missing `find`"))?.to_string(); + let replace = str_or(p, "replace", "").to_string(); + let (case, whole, forward, all_layers) = + (bool_or(p, "caseSensitive", false), bool_or(p, "wholeWord", false), bool_or(p, "forward", true), bool_or(p, "allLayers", true)); + let action = str_or(p, "action", "changeAll").to_string(); + let st = s.active().ok_or(EngineError::NoDocument)?; + let mut layers = type_layers(&st.doc, forward); + if !all_layers { + let active = layer_param(s, p).ok(); + layers.retain(|id| Some(*id) == active); + } + let text_of = |doc: &Document, id: LayerId| -> Option { + match &doc.layer(id)?.content { + LayerContent::Text(t) => Some(t.text.clone()), + _ => None, + } + }; + match action.as_str() { + "changeAll" => { + let doc = st.doc.clone(); + let plan: Vec<(LayerId, Vec<(usize, usize)>)> = + layers.iter().filter_map(|id| Some((*id, find_matches(&text_of(&doc, *id)?, &find, case, whole)))).filter(|(_, m)| !m.is_empty()).collect(); + let count: usize = plan.iter().map(|(_, m)| m.len()).sum(); + if count == 0 { + return Ok(json!({"count": 0, "layers": 0})); + } + s.edit("Replace All Text", |doc, _| { + let (dpi, format) = (doc.resolution_dpi, doc.pixel_format()); + for (id, matches) in &plan { + if let Some(LayerContent::Text(t)) = doc.layer_mut(*id).map(|l| &mut l.content) { + for (a, b) in matches.iter().rev() { + crate::type_cmds::replace_text(t, *a, *b, &replace); + } + crate::type_cmds::refresh_at(dpi, format, t); + } + } + Ok(()) + })?; + s.edit_state.find_cursor = None; + Ok(json!({"count": count, "layers": plan.len()})) + } + "find" | "change" | "changeFind" => { + let doc = st.doc.clone(); + let cursor = s.edit_state.find_cursor; + let mut changed = None; + if action != "find" + && let Some((id, a, b)) = cursor + && text_of(&doc, id).is_some_and(|t| find_matches(&t, &find, case, whole).contains(&(a, b))) + { + crate::type_cmds::check_text_unlocked(&doc, id)?; + s.edit("Replace Text", |doc, _| { + let (dpi, format) = (doc.resolution_dpi, doc.pixel_format()); + if let Some(LayerContent::Text(t)) = doc.layer_mut(id).map(|l| &mut l.content) { + crate::type_cmds::replace_text(t, a, b, &replace); + crate::type_cmds::refresh_at(dpi, format, t); + } + Ok(()) + })?; + let end = a + replace.len(); + // Collapse the cursor on the side the search moves away from, so the next search + // skips the replaced text even when the replacement still matches. + let c = if forward { end } else { a }; + s.edit_state.find_cursor = Some((id, c, c)); + changed = Some((id, a, end)); + if action == "change" { + return Ok(json!({"changed": {"layer": id.0, "start": a, "end": end}})); + } + } + // Find the next match after the cursor (wrapping through the layers). + let doc = s.active().ok_or(EngineError::NoDocument)?.doc.clone(); + let cursor = s.edit_state.find_cursor; + let start = cursor.and_then(|(id, _, _)| layers.iter().position(|l| *l == id)).unwrap_or(0); + for k in 0..=layers.len() { + // `allLayers: false` with a non-type layer active leaves no layers to search (#703). + let Some(&id) = layers.get((start + k) % layers.len().max(1)) else { break }; + let Some(text) = text_of(&doc, id) else { continue }; + let ms = find_matches(&text, &find, case, whole); + let hit = match (k, cursor) { + (0, Some((cid, a, b))) if cid == id => { + if forward { + ms.into_iter().find(|m| m.0 >= b) + } else { + ms.into_iter().rev().find(|m| m.1 <= a) + } + } + _ => { + if forward { + ms.into_iter().next() + } else { + ms.into_iter().next_back() + } + } + }; + if let Some((a, b)) = hit { + s.edit_state.find_cursor = Some((id, a, b)); + let _ = s.select_layer(id); + return Ok( + json!({"found": {"layer": id.0, "start": a, "end": b, "text": &text[a..b]}, "changed": changed.map(|(l, a, b)| json!({"layer": l.0, "start": a, "end": b}))}), + ); + } + } + s.edit_state.find_cursor = None; + Ok(json!({"found": null, "changed": changed.map(|(l, a, b)| json!({"layer": l.0, "start": a, "end": b}))})) + } + other => Err(bad(cmd, format!("unknown action `{other}` (find|change|changeFind|changeAll)"))), + } +} diff --git a/crates/engine/src/cmd/edit_menu_cmds/presets.rs b/crates/engine/src/cmd/edit_menu_cmds/presets.rs new file mode 100644 index 0000000000..8f26426287 --- /dev/null +++ b/crates/engine/src/cmd/edit_menu_cmds/presets.rs @@ -0,0 +1,150 @@ +use super::*; + +// ------------------------------------------------------------------ Define Brush / Custom Shape + +pub(super) fn define_brush_preset(s: &mut Session, p: &Value) -> Result { + let name = match p.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()) { + Some(n) => n.to_string(), + None => { + let n = s.tools.presets.iter().filter(|b| b.name.starts_with("Sampled Brush")).count() + 1; + format!("Sampled Brush {n}") + } + }; + s.execute("brush.defineFromSelection", json!({"name": name})) +} + +/// The path Define Custom Shape uses: `"work"`, a saved path name, else the work path, the +/// active shape layer, the active layer's vector mask, or the last saved path. +pub(crate) fn current_path(doc: &Document, active: Option, spec: Option<&str>) -> Option { + let ok = |p: &Path| !p.subpaths.is_empty(); + match spec { + Some("work") => return doc.work_path.clone().filter(ok), + Some(name) => return doc.paths.iter().find(|n| n.name == name).map(|n| n.path.clone()).filter(ok), + None => {} + } + if let Some(p) = doc.work_path.clone().filter(ok) { + return Some(p); + } + if let Some(l) = active.and_then(|id| doc.layer(id)) { + if let LayerContent::Shape(sh) = &l.content + && ok(&sh.path) + { + return Some(sh.path.clone()); + } + if let Some(vm) = l.vector_mask.as_ref().filter(|v| ok(&v.path)) { + return Some(vm.path.clone()); + } + } + doc.paths.last().map(|n| n.path.clone()).filter(ok) +} + +pub(super) fn can_define_shape(s: &Session) -> std::result::Result<(), String> { + let d = s.active().ok_or("no document open")?; + current_path(&d.doc, d.active_layer, None).map(|_| ()).ok_or_else(|| "select a path or shape layer first".into()) +} + +pub(super) fn define_custom_shape(s: &mut Session, p: &Value) -> Result { + let st = s.active().ok_or(EngineError::NoDocument)?; + let path = current_path(&st.doc, st.active_layer, p.get("path").and_then(Value::as_str)).ok_or_else(|| bad("edit.defineCustomShape", "no such path"))?; + let name = p + .get("name") + .and_then(Value::as_str) + .map(str::trim) + .filter(|n| !n.is_empty()) + .map(str::to_string) + .unwrap_or_else(|| format!("Shape {}", s.edit_state.custom_shapes.len() + 1)); + let shapes = &mut s.edit_state.custom_shapes; + match shapes.iter_mut().find(|c| c.name == name) { + Some(c) => c.path = path, + None => shapes.push(CustomShape { name: name.clone(), path }), + } + Ok(json!({"name": name, "count": shapes.len()})) +} + +// ------------------------------------------------------------------ presets + +/// Libraries the Preset Manager edits (patterns export as `.pat` with `pattern.export`). +const PRESET_KINDS: [&str; 3] = ["brushes", "customShapes", "patterns"]; + +fn preset_names(s: &Session, kind: &str) -> Option> { + Some(match kind { + "brushes" => s.tools.presets.iter().map(|b| b.name.clone()).collect(), + "customShapes" => s.edit_state.custom_shapes.iter().map(|c| c.name.clone()).collect(), + "patterns" => s.patterns.items.iter().map(|p| p.name.clone()).collect(), + _ => return None, + }) +} + +fn preset_index(s: &Session, kind: &str, p: &Value) -> Result { + let names = preset_names(s, kind).ok_or_else(|| bad("edit.presets.presetManager", format!("unknown preset kind `{kind}` ({})", PRESET_KINDS.join("|"))))?; + if let Some(i) = p.get("index").and_then(Value::as_u64) { + return if (i as usize) < names.len() { Ok(i as usize) } else { Err(bad("edit.presets.presetManager", format!("no preset {i}"))) }; + } + let name = p.get("name").and_then(Value::as_str).ok_or_else(|| bad("edit.presets.presetManager", "give `index` or `name`"))?; + names.iter().position(|n| n == name).ok_or_else(|| bad("edit.presets.presetManager", format!("no preset named `{name}`"))) +} + +pub(super) fn preset_manager(s: &mut Session, p: &Value) -> Result { + let cmd = "edit.presets.presetManager"; + let action = str_or(p, "action", "list"); + if action == "list" { + let kinds: Vec<&str> = match p.get("kind").and_then(Value::as_str) { + Some(k) => vec![k], + None => PRESET_KINDS.to_vec(), + }; + let mut out = serde_json::Map::new(); + for k in kinds { + out.insert(k.to_string(), json!(preset_names(s, k).ok_or_else(|| bad(cmd, format!("unknown preset kind `{k}`")))?)); + } + return Ok(Value::Object(out)); + } + let kind = p.get("kind").and_then(Value::as_str).ok_or_else(|| bad(cmd, "missing `kind`"))?.to_string(); + let i = preset_index(s, &kind, p)?; + match action { + "rename" => { + let new = + p.get("newName").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad(cmd, "missing `newName`"))?.to_string(); + match kind.as_str() { + // Same rules as Brush Settings: no duplicate names (case-insensitive), the current + // preset follows, a renamed built-in is the user's preset now (and persists as one). + "brushes" => crate::brush_preset_cmds::rename_at(s, i, &new, cmd)?, + "patterns" => s.patterns.items[i].name = new, + _ => s.edit_state.custom_shapes[i].name = new, + } + } + "delete" => match kind.as_str() { + "brushes" => { + let gone = s.tools.presets.remove(i); + crate::brush_cmds::forget_deleted_preset(s, &gone.name); + } + "patterns" => drop(s.patterns.items.remove(i)), + _ => drop(s.edit_state.custom_shapes.remove(i)), + }, + "move" => { + let to = p.get("to").and_then(Value::as_u64).ok_or_else(|| bad(cmd, "missing `to`"))? as usize; + match kind.as_str() { + "brushes" => crate::move_item(&mut s.tools.presets, i, to), + "patterns" => crate::move_item(&mut s.patterns.items, i, to), + _ => crate::move_item(&mut s.edit_state.custom_shapes, i, to), + }; + } + other => return Err(bad(cmd, format!("unknown action `{other}` (list|rename|delete|move)"))), + } + if kind == "brushes" { + s.brush_presets_changed(); + } + Ok(json!({kind.clone(): preset_names(s, &kind)})) +} + +/// Exported preset file (`.pcpresets`, JSON). +#[derive(Clone, Debug, Default, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct PresetFile { + pub format: String, + pub version: u32, + pub brushes: Vec, + pub custom_shapes: Vec, + pub tool_presets: Vec, +} + +pub const PRESET_FORMAT: &str = "photocraft-presets"; diff --git a/crates/engine/src/cmd/edit_menu_cmds/purge.rs b/crates/engine/src/cmd/edit_menu_cmds/purge.rs new file mode 100644 index 0000000000..a422e82bfb --- /dev/null +++ b/crates/engine/src/cmd/edit_menu_cmds/purge.rs @@ -0,0 +1,95 @@ +use super::*; + +// ------------------------------------------------------------------ Purge + +fn history_bytes(s: &Session, all: bool) -> usize { + let docs: Vec<&crate::DocState> = if all { s.documents().iter().collect() } else { s.active().into_iter().collect() }; + // Purge keeps the snapshots, so the tiles they share with the states aren't freed. + docs.iter() + .map(|d| { + let snaps: Vec<&photocraft_doc::Document> = d.snapshots.iter().map(|s| &*s.doc).collect(); + d.history.unique_bytes_besides(&d.doc, &snaps) + }) + .sum() +} + +fn clip_bytes(s: &Session) -> usize { + s.clipboard.as_ref().map_or(0, |c| c.surface.tiles().map(|(_, t)| t.bytes().len()).sum()) +} + +pub(super) fn purge(s: &mut Session, what: &str) -> Result { + let mut freed = 0usize; + let mut items: Vec<&str> = Vec::new(); + if matches!(what, "undo" | "all") && s.active().is_some_and(|d| d.history.can_undo()) { + let before = history_bytes(s, false); + if let Some(st) = s.active_mut() { + st.history.purge_last(); + } + freed += before.saturating_sub(history_bytes(s, false)); + items.push("undo"); + } + if matches!(what, "clipboard" | "all") && (s.clipboard.is_some() || s.style_clipboard.is_some()) { + freed += clip_bytes(s); + s.clipboard = None; + s.style_clipboard = None; + items.push("clipboard"); + } + if matches!(what, "histories" | "all") { + let b = history_bytes(s, true); + if s.documents().iter().any(|d| d.history.can_undo() || d.history.can_redo()) { + for st in &mut s.docs { + st.history.clear(); + st.coalesce = None; + } + freed += b; + items.push("histories"); + } + } + if what == "all" { + let fx = photocraft_compose::purge_effect_cache(); + if fx > 0 { + freed += fx; + items.push("effect cache"); + } + let masks = photocraft_compose::masks::purge_cache(); + if masks > 0 { + freed = freed.saturating_add(masks); + items.push("mask cache"); + } + let stages = crate::smart_cmds::purge_stack_cache(); + if stages > 0 { + freed = freed.saturating_add(stages); + items.push("smart filter cache"); + } + let strokes = photocraft_compose::shape_split::purge_cache(); + if strokes > 0 { + freed = freed.saturating_add(strokes); + items.push("shape stroke cache"); + } + } + s.edit_state.fade = None; + let msg = if items.is_empty() { "nothing to purge".to_string() } else { format!("purged {}", items.join(", ")) }; + Ok(json!({"purged": items, "bytes": freed, "message": msg})) +} + +pub(super) fn can_purge_undo(s: &Session) -> std::result::Result<(), String> { + s.active().filter(|d| d.history.can_undo()).map(|_| ()).ok_or_else(|| "nothing to purge".into()) +} + +pub(super) fn can_purge_clipboard(s: &Session) -> std::result::Result<(), String> { + if s.clipboard.is_some() || s.style_clipboard.is_some() { Ok(()) } else { Err("the clipboard is empty".into()) } +} + +pub(super) fn can_purge_histories(s: &Session) -> std::result::Result<(), String> { + if s.documents().iter().any(|d| d.history.can_undo() || d.history.can_redo()) { Ok(()) } else { Err("no history to purge".into()) } +} + +pub(super) fn can_purge_all(s: &Session) -> std::result::Result<(), String> { + can_purge_histories(s).or_else(|_| can_purge_clipboard(s)).or_else(|_| { + if photocraft_compose::effect_cache_bytes() > 0 || photocraft_compose::masks::cache_bytes() > 0 || crate::smart_cmds::stack_cache_bytes() > 0 { + Ok(()) + } else { + Err("nothing to purge".into()) + } + }) +} diff --git a/crates/engine/src/edit_menu_cmds/tests.rs b/crates/engine/src/cmd/edit_menu_cmds/tests.rs similarity index 100% rename from crates/engine/src/edit_menu_cmds/tests.rs rename to crates/engine/src/cmd/edit_menu_cmds/tests.rs diff --git a/crates/engine/src/cmd/enabled.rs b/crates/engine/src/cmd/enabled.rs new file mode 100644 index 0000000000..c609b9e0ba --- /dev/null +++ b/crates/engine/src/cmd/enabled.rs @@ -0,0 +1,100 @@ +use super::*; + +pub(crate) fn always(_: &Session) -> std::result::Result<(), String> { + Ok(()) +} + +pub(super) fn has_doc(s: &Session) -> std::result::Result<(), String> { + s.active().map(|_| ()).ok_or_else(|| "no document open".into()) +} + +pub(super) fn has_layer(s: &Session) -> std::result::Result<(), String> { + let d = s.active().ok_or("no document open")?; + d.active_layer.filter(|id| d.doc.layer(*id).is_some()).map(|_| ()).ok_or_else(|| "no active layer".into()) +} + +pub(super) fn has_pixel_layer(s: &Session) -> std::result::Result<(), String> { + let l = crate::active_layer_of(s)?; + if matches!(l.content, LayerContent::Raster(_)) { + Ok(()) + } else { + Err(format!("active layer is {} {} layer, not a pixel layer", l.content.article(), l.content.kind_name())) + } +} + +/// A pixel layer, or a targeted alpha channel / Quick Mask (adjustments and fills apply to it). +pub(super) fn has_pixel_or_channel(s: &Session) -> std::result::Result<(), String> { + if crate::channel_cmds::edits_channel(s) { + return Ok(()); + } + has_pixel_layer(s) +} + +/// A layer that can be painted: pixels, or any layer with a mask (paint with `"target":"mask"`). +pub(crate) fn has_paintable(s: &Session) -> std::result::Result<(), String> { + if crate::channel_cmds::edits_channel(s) { + return Ok(()); + } + let l = crate::active_layer_of(s)?; + if matches!(l.content, LayerContent::Raster(_)) || l.mask.is_some() { + Ok(()) + } else { + Err(format!("active layer is {} {} layer without a mask", l.content.article(), l.content.kind_name())) + } +} + +/// Surface a paint command writes to: the layer's pixels, its mask with `"target":"mask"`, or a +/// smart object's filter mask with `"target":"filterMask"`. +pub(crate) fn paint_surface<'a>(doc: &'a mut Document, id: LayerId, p: &Value) -> Result<&'a mut photocraft_raster::Surface> { + if is_mask_target(p) { + check_all_unlocked(doc, id)?; + } else { + check_pixels_unlocked(doc, id)?; + } + if crate::channel_cmds::target_of(p) == crate::channel_cmds::Target::FilterMask { + return crate::smart_cmds::filter_mask_surface(doc, id); + } + let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; + if is_mask_target(p) { + l.mask.as_mut().map(|m| &mut m.surface).ok_or_else(|| EngineError::Other("layer has no mask".into())) + } else { + l.surface_mut().ok_or_else(|| EngineError::Other("not a pixel layer".into())) + } +} + +pub(crate) fn check_all_unlocked(doc: &Document, id: LayerId) -> Result<()> { + let locks = doc.effective_locks(id); + let l = doc.layer(id).ok_or(EngineError::NoLayer(id))?; + if locks.all { + return Err(EngineError::Other(format!("Could not complete your request because the layer \"{}\" is locked", l.name))); + } + Ok(()) +} + +/// Refuse a layer whose pixels are locked (directly or through a group), with Photoshop's message. +pub(crate) fn check_pixels_unlocked(doc: &Document, id: LayerId) -> Result<()> { + let locks = doc.effective_locks(id); + let l = doc.layer(id).ok_or(EngineError::NoLayer(id))?; + if locks.pixels || locks.all { + return Err(EngineError::Other(format!("Could not complete your request because the layer \"{}\" is locked", l.name))); + } + Ok(()) +} + +/// The params target a grayscale mask of the layer: its layer mask (`"mask"`) or, on a smart +/// object, its filter mask (`"filterMask"`). +pub(crate) fn is_mask_target(p: &Value) -> bool { + matches!(p.get("target").and_then(Value::as_str), Some("mask" | "filterMask")) +} + +pub(super) fn can_undo(s: &Session) -> std::result::Result<(), String> { + s.active().filter(|d| d.history.can_undo()).map(|_| ()).ok_or_else(|| "nothing to undo".into()) +} + +pub(super) fn can_redo(s: &Session) -> std::result::Result<(), String> { + s.active().filter(|d| d.history.can_redo()).map(|_| ()).ok_or_else(|| "nothing to redo".into()) +} + +pub(super) fn has_selection(s: &Session) -> std::result::Result<(), String> { + s.active().filter(|d| d.doc.selection.is_some()).map(|_| ()).ok_or_else(|| "no selection".into()) +} diff --git a/crates/engine/src/eraser_cmds.rs b/crates/engine/src/cmd/eraser_cmds.rs similarity index 100% rename from crates/engine/src/eraser_cmds.rs rename to crates/engine/src/cmd/eraser_cmds.rs diff --git a/crates/engine/src/eraser_cmds/tests.rs b/crates/engine/src/cmd/eraser_cmds/tests.rs similarity index 100% rename from crates/engine/src/eraser_cmds/tests.rs rename to crates/engine/src/cmd/eraser_cmds/tests.rs diff --git a/crates/engine/src/export_preset_cmds.rs b/crates/engine/src/cmd/export_preset_cmds.rs similarity index 100% rename from crates/engine/src/export_preset_cmds.rs rename to crates/engine/src/cmd/export_preset_cmds.rs diff --git a/crates/engine/src/exr_cmds.rs b/crates/engine/src/cmd/exr_cmds.rs similarity index 100% rename from crates/engine/src/exr_cmds.rs rename to crates/engine/src/cmd/exr_cmds.rs diff --git a/crates/engine/src/extra_cmds.rs b/crates/engine/src/cmd/extra_cmds.rs similarity index 53% rename from crates/engine/src/extra_cmds.rs rename to crates/engine/src/cmd/extra_cmds.rs index d5364cfd88..4a3190ec72 100644 --- a/crates/engine/src/extra_cmds.rs +++ b/crates/engine/src/cmd/extra_cmds.rs @@ -1058,825 +1058,4 @@ pub fn specs() -> Vec { } #[cfg(test)] -mod tests { - use super::*; - - fn session(depth: u32) -> Session { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 40, "height": 30, "depth": depth})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s - } - - fn doc(s: &Session) -> &Document { - &s.active().unwrap().doc - } - - #[test] - fn equalize_average_and_clouds_edit_the_targeted_channel() { - // #935: these four ran through `map_pixels`, which always rewrote the active layer, so - // with an alpha channel or the Quick Mask targeted they changed the layer and left the - // channel alone. - let cmds = ["image.adjustments.equalize", "filter.blur.average", "filter.render.clouds", "filter.render.differenceClouds"]; - for depth in [8, 16, 32] { - for target in ["quickMask", "alpha", "mask"] { - for cmd in cmds { - let mut s = session(depth); - s.tools.foreground = [0.0, 0.0, 0.0, 1.0]; - s.tools.background = [1.0, 1.0, 1.0, 1.0]; - s.execute("edit.fill", json!({"contents": "color", "color": "#808080"})).unwrap(); - let p = match target { - "quickMask" => { - s.execute("select.editInQuickMaskMode", json!({"on": true})).unwrap(); - json!({"seed": 1}) - } - "alpha" => { - s.execute("channel.new", json!({"fill": "white"})).unwrap(); - s.execute("channel.target", json!({"channel": 0})).unwrap(); - json!({"seed": 1}) - } - _ => { - s.execute("layer.layerMask.revealAll", json!({})).unwrap(); - json!({"seed": 1, "target": "mask"}) - } - }; - // Two levels in the target, so Equalize and Average have something to change. - let edit_target = json!({ "target": if target == "alpha" { json!({"channel": 0}) } else { json!(target) } }); - s.edit("levels", |doc, active| { - let (surf, _) = crate::channel_cmds::target_surface(doc, *active, &edit_target).unwrap(); - surf.fill_rect(Rect::new(0, 0, 20, 30), &[0.4]); - surf.fill_rect(Rect::new(20, 0, 40, 30), &[0.5]); - Ok(()) - }) - .unwrap(); - let full = Rect::new(0, 0, 40, 30); - let read = |s: &Session| { - let d = doc(s); - let layer = d.layer(s.active().unwrap().active_layer.unwrap()).unwrap(); - let t = match target { - "quickMask" => d.quick_mask.as_ref().unwrap().surface.read_region(full), - "alpha" => d.channels[0].surface.read_region(full), - _ => layer.mask.as_ref().unwrap().surface.read_region(full), - }; - (layer.surface().unwrap().read_region(full), t) - }; - let ((layer0, target0), past) = (read(&s), s.active().unwrap().history.past_len()); - s.execute(cmd, p).unwrap(); - let (layer1, target1) = read(&s); - let case = format!("{cmd} on {target} at {depth}"); - assert_eq!(layer1, layer0, "{case}: the layer is untouched"); - assert_ne!(target1, target0, "{case}: the target changed"); - assert_eq!(s.active().unwrap().history.past_len(), past + 1, "{case}"); - s.undo(); - assert_eq!(read(&s).1, target0, "{case}: undo restores the target"); - } - } - } - } - - fn active(s: &Session) -> &Layer { - let d = s.active().unwrap(); - d.doc.layer(d.active_layer.unwrap()).unwrap() - } - - fn pixel(s: &Session, x: i32, y: i32) -> Vec { - active(s).surface().unwrap().pixel(x, y) - } - - fn paint_square(s: &mut Session, r: Rect, c: [f32; 4]) { - s.edit("paint", |doc, a| { - doc.layer_mut(a.unwrap()).unwrap().surface_mut().unwrap().fill_rect(r, &c); - Ok(()) - }) - .unwrap(); - } - - #[test] - fn stroke_locations_at_several_depths() { - for depth in [8, 16, 32] { - for (loc, inside, outside) in [("inside", 1.0, 0.0), ("outside", 0.0, 1.0), ("center", 1.0, 1.0)] { - let mut s = session(depth); - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); - s.execute("edit.stroke", json!({"width": 2, "color": "#ff0000", "location": loc})).unwrap(); - assert!((pixel(&s, 10, 15)[3] - inside).abs() < 0.02, "{depth} {loc} inside {:?}", pixel(&s, 10, 15)); - assert!((pixel(&s, 9, 15)[3] - outside).abs() < 0.02, "{depth} {loc} outside {:?}", pixel(&s, 9, 15)); - assert_eq!(pixel(&s, 15, 15)[3], 0.0, "centre untouched"); - } - } - // Without a selection the layer's opaque edge is stroked. - let mut s = session(8); - paint_square(&mut s, Rect::new(10, 10, 20, 20), [0.0, 0.0, 1.0, 1.0]); - s.execute("edit.stroke", json!({"width": 3, "color": "#00ff00", "location": "outside"})).unwrap(); - assert_eq!(pixel(&s, 8, 15), vec![0.0, 1.0, 0.0, 1.0]); - assert_eq!(pixel(&s, 15, 15), vec![0.0, 0.0, 1.0, 1.0]); - } - - /// Photoshop's Edit › Stroke on a selection (checked by hand): Center puts ceil(w/2) px inside - /// and floor(w/2) outside (1 px is all inside), fractional widths round up, and every stroked - /// pixel is fully opaque, on every edge, horizontal ones included. Inside and Outside are - /// w px on their side. - #[test] - fn stroke_widths_are_whole_opaque_pixels_like_photoshop() { - // Selection x 10..30, y 10..30; the edge pixels inside are 10 and 29 on each axis. - let band = |loc: &str, w: i32| -> (i32, i32) { - match loc { - "inside" => (w, 0), - "outside" => (0, w), - _ => ((w + 1) / 2, w / 2), - } - }; - let mut wrong = Vec::new(); - for depth in [8, 16, 32] { - for loc in ["center", "inside", "outside"] { - for (param, w) in [(json!(1), 1), (json!(2), 2), (json!(3), 3), (json!(4), 4), (json!(5), 5), (json!(0.5), 1), (json!(2.5), 3)] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 50, "height": 50, "depth": depth})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); - s.execute("edit.stroke", json!({"width": param, "color": "#ff0000", "location": loc})).unwrap(); - let (inside, outside) = band(loc, w); - // (edge pixel inside, step inward) for left, right, top and bottom; the other - // coordinate is the middle of the edge. - for (name, first_in, inward, horizontal) in - [("left", 10, 1, false), ("right", 29, -1, false), ("top", 10, 1, true), ("bottom", 29, -1, true)] - { - for k in -7..7 { - // k ≥ 0: k px inside from the edge; k < 0: -k px outside. - let c = first_in + k * inward; - let (x, y) = if horizontal { (20, c) } else { (c, 20) }; - let want = if (k >= 0 && k < inside) || (k < 0 && -k <= outside) { 1.0 } else { 0.0 }; - let a = pixel(&s, x, y)[3]; - if (a - want).abs() > 0.004 { - wrong.push(format!("{depth}-bit {loc} width {param} {name} edge, {k:+} px: alpha {a}, want {want}")); - } - } - } - } - } - } - assert!(wrong.is_empty(), "{} pixels differ from Photoshop:\n{}", wrong.len(), wrong.iter().take(40).cloned().collect::>().join("\n")); - } - - /// Photoshop's 6 px Outside stroke of a 14 px circle selection made without anti-aliasing, - /// read pixel by pixel from Photoshop (`#` stroked, `.` not; the hole is the selection). A - /// hard selection gives a hard stroke: a pixel is stroked when its centre is less than - /// width + 1 from a selected pixel's centre (no partial pixels on the curve). - const PS_CIRCLE_OUTSIDE_6: [&str; 31] = [ - "..................................", - "..................................", - "...........############...........", - "..........##############..........", - ".........################.........", - "........##################........", - ".......####################.......", - "......######################......", - ".....#########......#########.....", - "....#########........#########....", - "....########..........########....", - "....#######............#######....", - "....######..............######....", - "....######..............######....", - "....######..............######....", - "....######..............######....", - "....######..............######....", - "....######..............######....", - "....#######............#######....", - "....########..........########....", - "....#########........#########....", - ".....#########......#########.....", - "......######################......", - ".......####################.......", - "........##################........", - ".........################.........", - "..........##############..........", - "...........############...........", - "..................................", - "..................................", - "..................................", - ]; - - /// Photoshop's 3 px Inside stroke of the same 14 px hard circle (the selection is the ring - /// plus its hole). Inside, a pixel is stroked when its centre is less than width + ½ from an - /// unselected pixel's: that offset is the one fitting this, the 5 px and the 6 px samples - /// (any value from +0.41 to +0.60), so 6 px fills this circle (its deepest pixel is 6.4 px in). - const PS_CIRCLE_INSIDE_3: [&str; 17] = [ - "...................", - "......######.......", - ".....########......", - "....##########.....", - "...####....####....", - "..####......####...", - "..###........###...", - "..###........###...", - "..###........###...", - "..###........###...", - "..####......####...", - "...####....####....", - "....##########.....", - ".....########......", - "......######.......", - "...................", - "...................", - ]; - - /// The selection of a Photoshop sample grid: an Outside stroke's hole, or an Inside stroke's - /// ring and hole. - fn grid_selection(rows: &[&str], outside: bool) -> Vec { - let (w, h) = (rows[0].len(), rows.len()); - let mut mask = vec![0.0f32; w * h]; - for (y, row) in rows.iter().enumerate() { - let b = row.as_bytes(); - if let (Some(first), Some(last)) = (b.iter().position(|c| *c == b'#'), b.iter().rposition(|c| *c == b'#')) { - for x in first..=last { - if !outside || b[x] == b'.' { - mask[y * w + x] = 1.0; - } - } - } - } - mask - } - - /// Strokes `mask` as the selection of a `w` × `h` layer and returns its alpha per pixel. - fn stroke_alpha(mask: &[f32], w: usize, h: usize, depth: u32, params: Value) -> Vec { - let mut s = Session::new(); - s.execute("file.new", json!({"width": w, "height": h, "depth": depth})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.edit("select", |doc, _| { - doc.selection = Some(sel::mask_to_surface(mask, doc.bounds())); - Ok(()) - }) - .unwrap(); - s.execute("edit.stroke", params).unwrap(); - (0..h).flat_map(|y| (0..w).map(move |x| (x, y))).map(|(x, y)| pixel(&s, x as i32, y as i32)[3]).collect() - } - - #[test] - fn a_hard_circle_strokes_inside_like_photoshop() { - let rows = PS_CIRCLE_INSIDE_3; - let (w, h) = (rows[0].len(), rows.len()); - let mask = grid_selection(&rows, false); - for depth in [8, 16, 32] { - let got = stroke_alpha(&mask, w, h, depth, json!({"width": 3, "color": "#000000", "location": "inside"})); - let wrong: Vec = rows - .iter() - .enumerate() - .flat_map(|(y, row)| row.bytes().enumerate().map(move |(x, c)| (x, y, c))) - .filter_map(|(x, y, c)| { - let want = if c == b'#' { 1.0 } else { 0.0 }; - let a = got[y * w + x]; - ((a - want).abs() > 0.004).then(|| format!("({x}, {y}): {a}, Photoshop {want}")) - }) - .collect(); - assert!(wrong.is_empty(), "{depth}-bit: {} pixels differ from Photoshop: {wrong:?}", wrong.len()); - // Checked in Photoshop: a 5 px Inside stroke leaves a plus-shaped hole of 12 pixels in - // the middle (rows 2, 4, 4, 2 wide), and 6 px fills the whole circle. - let hole = [(8, 6), (9, 6), (7, 7), (8, 7), (9, 7), (10, 7), (7, 8), (8, 8), (9, 8), (10, 8), (8, 9), (9, 9)]; - let five = stroke_alpha(&mask, w, h, depth, json!({"width": 5, "color": "#000000", "location": "inside"})); - for (i, m) in mask.iter().enumerate() { - let stroked = *m > 0.0 && !hole.contains(&(i % w, i / w)); - assert_eq!(five[i] > 0.996, stroked, "{depth}-bit 5 px Inside at ({}, {})", i % w, i / w); - } - let full = stroke_alpha(&mask, w, h, depth, json!({"width": 6, "color": "#000000", "location": "inside"})); - for (i, m) in mask.iter().enumerate() { - assert_eq!(full[i] > 0.996, *m > 0.0, "{depth}-bit 6 px Inside at ({}, {})", i % w, i / w); - } - } - } - - #[test] - fn a_hard_circle_strokes_like_photoshop() { - let rows = PS_CIRCLE_OUTSIDE_6; - let (w, h) = (rows[0].len(), rows.len()); - // The selection: the `.` cells enclosed by the ring on each row. - let mask = grid_selection(&rows, true); - for depth in [8, 16, 32] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": w, "height": h, "depth": depth})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.edit("select", |doc, _| { - doc.selection = Some(sel::mask_to_surface(&mask, doc.bounds())); - Ok(()) - }) - .unwrap(); - s.execute("edit.stroke", json!({"width": 6, "color": "#000000", "location": "outside"})).unwrap(); - let mut wrong = Vec::new(); - for (y, row) in rows.iter().enumerate() { - for (x, c) in row.bytes().enumerate() { - let want = if c == b'#' { 1.0 } else { 0.0 }; - let a = pixel(&s, x as i32, y as i32)[3]; - if (a - want).abs() > 0.004 { - wrong.push(format!("({x}, {y}): {a}, Photoshop {want}")); - } - } - } - assert!(wrong.is_empty(), "{depth}-bit: {} pixels differ from Photoshop: {wrong:?}", wrong.len()); - } - } - - /// Select All, then Stroke › Inside draws a border around the canvas (a common Photoshop - /// technique): the canvas edge is a selection edge like any other, on all four sides. - #[test] - fn stroking_a_selection_at_the_canvas_edge_draws_that_edge() { - for depth in [8, 16, 32] { - for (loc, w, inside) in [("inside", 3, 3), ("center", 3, 2), ("center", 1, 1)] { - let mut s = session(depth); - s.execute("select.all", json!({})).unwrap(); - s.execute("edit.stroke", json!({"width": w, "color": "#ff0000", "location": loc})).unwrap(); - // 40 × 30 canvas: k px in from each side, in the middle of the side. - for name in ["left", "right", "top", "bottom"] { - for k in 0..6 { - let (x, y) = match name { - "left" => (k, 15), - "right" => (39 - k, 15), - "top" => (20, k), - _ => (20, 29 - k), - }; - let want = if k < inside { 1.0 } else { 0.0 }; - let a = pixel(&s, x, y)[3]; - assert!((a - want).abs() < 0.004, "{depth}-bit {loc} {w} px, {name} side, {k} px in: alpha {a}, want {want}"); - } - } - } - } - } - - #[test] - fn stroke_uses_fill_blending_and_preserves_transparency_at_every_depth() { - for depth in [8, 16, 32] { - let mut s = session(depth); - paint_square(&mut s, Rect::new(10, 10, 20, 20), [0.5, 0.5, 0.5, 1.0]); - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); - - let past = s.active().unwrap().history.past_len(); - s.execute( - "edit.stroke", - json!({"width": 2, "color": "#ffffff", "location": "inside", "mode": "multiply", "opacity": 100, "preserveTransparency": true}), - ) - .unwrap(); - assert_eq!(s.active().unwrap().history.past_len(), past + 1, "Stroke is one history step"); - let edge = pixel(&s, 10, 15); - assert!((edge[0] - 0.5).abs() < 0.015, "{depth}-bit Multiply must preserve gray: {edge:?}"); - assert_eq!(edge[3], 1.0); - - s.execute("edit.stroke", json!({"width": 2, "color": "#ffffff", "location": "outside", "preserveTransparency": true})).unwrap(); - assert_eq!(pixel(&s, 9, 15)[3], 0.0, "{depth}-bit transparency lock prevents new outer pixels"); - - s.execute("edit.stroke", json!({"width": 2, "color": "#ffffff", "location": "outside", "opacity": 50})).unwrap(); - let out = pixel(&s, 9, 15); - assert!((out[3] - 0.5).abs() < 0.015, "{depth}-bit 50% stroke opacity: {out:?}"); - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(pixel(&s, 9, 15)[3], 0.0); - } - } - - #[test] - fn stroke_rejects_invalid_blending_options_without_modifying_the_document() { - let mut s = session(8); - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); - let past = s.active().unwrap().history.past_len(); - for params in [ - json!({"mode": "unknown-mode"}), - json!({"mode": 42}), - json!({"mode": "passThrough"}), - json!({"opacity": "lots"}), - json!({"preserveTransparency": "true"}), - ] { - assert!(s.execute("edit.stroke", params.clone()).is_err(), "{params}"); - assert_eq!(s.active().unwrap().history.past_len(), past, "{params} should not create a history step"); - } - } - - #[test] - fn transform_presets_are_exact() { - let mut s = session(8); - paint_square(&mut s, Rect::new(10, 10, 20, 14), [1.0, 0.0, 0.0, 1.0]); - paint_square(&mut s, Rect::new(10, 10, 11, 11), [0.0, 1.0, 0.0, 1.0]); - s.execute("edit.transform.flipHorizontal", json!({})).unwrap(); - assert_eq!(active(&s).surface().unwrap().content_bounds(), Rect::new(10, 10, 20, 14)); - assert_eq!(pixel(&s, 19, 10), vec![0.0, 1.0, 0.0, 1.0]); - s.execute("edit.transform.flipVertical", json!({})).unwrap(); - assert_eq!(pixel(&s, 19, 13), vec![0.0, 1.0, 0.0, 1.0]); - s.execute("edit.transform.rotate180", json!({})).unwrap(); - assert_eq!(pixel(&s, 10, 10), vec![0.0, 1.0, 0.0, 1.0]); - s.execute("edit.transform.rotate90Cw", json!({})).unwrap(); - let b = active(&s).surface().unwrap().content_bounds(); - assert_eq!((b.width(), b.height()), (4, 10)); - // Top-left corner goes to the top-right after a clockwise turn. - assert_eq!(pixel(&s, b.x1 - 1, b.y0), vec![0.0, 1.0, 0.0, 1.0]); - s.execute("edit.transform.rotate90Ccw", json!({})).unwrap(); - assert_eq!(active(&s).surface().unwrap().content_bounds(), Rect::new(10, 10, 20, 14)); - assert_eq!(pixel(&s, 10, 10), vec![0.0, 1.0, 0.0, 1.0]); - } - - /// #6928: with a selection, the presets flip and turn about the selection's own bounds, as - /// in Photoshop: Select All mirrors across the canvas, a marquee across its own centre. - /// Without a selection they keep turning about the content (above). - #[test] - fn transform_presets_turn_about_the_selection() { - let mut s = session(8); - paint_square(&mut s, Rect::new(10, 10, 20, 14), [1.0, 0.0, 0.0, 1.0]); - paint_square(&mut s, Rect::new(10, 10, 11, 11), [0.0, 1.0, 0.0, 1.0]); - let green = vec![0.0, 1.0, 0.0, 1.0]; - // Select All on the 40 × 30 canvas: across the canvas's centre lines. - s.execute("select.all", json!({})).unwrap(); - let past = s.active().unwrap().history.past_len(); - s.execute("edit.transform.flipHorizontal", json!({})).unwrap(); - assert_eq!(active(&s).surface().unwrap().content_bounds(), Rect::new(20, 10, 30, 14)); - assert_eq!(pixel(&s, 29, 10), green); - assert_eq!(s.active().unwrap().history.past_len(), past + 1, "one undo step"); - s.execute("edit.transform.flipVertical", json!({})).unwrap(); - assert_eq!(active(&s).surface().unwrap().content_bounds(), Rect::new(20, 16, 30, 20)); - assert_eq!(pixel(&s, 29, 19), green); - s.execute("edit.transform.rotate180", json!({})).unwrap(); - assert_eq!(active(&s).surface().unwrap().content_bounds(), Rect::new(10, 10, 20, 14)); - assert_eq!(pixel(&s, 10, 10), green); - // A marquee (0, 0)–(24, 30) holding the whole square: across x = 12. - s.execute("select.rect", json!({"x": 0, "y": 0, "width": 24, "height": 30})).unwrap(); - s.execute("edit.transform.flipHorizontal", json!({})).unwrap(); - assert_eq!(active(&s).surface().unwrap().content_bounds(), Rect::new(4, 10, 14, 14)); - assert_eq!(pixel(&s, 13, 10), green); - // Undo puts it back where it was. - s.undo(); - assert_eq!(active(&s).surface().unwrap().content_bounds(), Rect::new(10, 10, 20, 14)); - // A targeted alpha channel turns about the selection's bounds too. - s.execute("channel.new", json!({})).unwrap(); - s.edit("paint channel", |doc, _| { - doc.channels[0].surface.fill_rect(Rect::new(10, 10, 20, 20), &[1.0]); - Ok(()) - }) - .unwrap(); - s.execute("channel.target", json!({"channel": 0})).unwrap(); - s.execute("select.all", json!({})).unwrap(); - s.execute("edit.transform.flipHorizontal", json!({})).unwrap(); - assert_eq!(s.active().unwrap().doc.channels[0].surface.content_bounds(), Rect::new(20, 10, 30, 20)); - } - - #[test] - fn reselect_restores_the_last_selection() { - let mut s = session(8); - assert!(!s.is_enabled("select.reselect")); - s.execute("select.rect", json!({"x": 2, "y": 3, "width": 5, "height": 6})).unwrap(); - s.execute("select.deselect", json!({})).unwrap(); - assert!(doc(&s).selection.is_none()); - s.execute("select.reselect", json!({})).unwrap(); - assert_eq!(doc(&s).selection.as_ref().unwrap().content_bounds(), Rect::new(2, 3, 7, 9)); - assert!(!s.is_enabled("select.reselect"), "nothing to reselect while a selection exists"); - } - - #[test] - fn equalize_spreads_values() { - for depth in [8, 16] { - let mut s = session(depth); - paint_square(&mut s, Rect::new(0, 0, 40, 15), [0.4, 0.4, 0.4, 1.0]); - paint_square(&mut s, Rect::new(0, 15, 40, 30), [0.5, 0.5, 0.5, 1.0]); - s.execute("image.adjustments.equalize", json!({})).unwrap(); - let (dark, light) = (pixel(&s, 1, 1)[0], pixel(&s, 1, 20)[0]); - assert!(dark < 0.05 && light > 0.95, "{depth}: {dark} {light}"); - } - } - - /// A selection masks Clouds but doesn't change their size: inside it they are the canvas's - /// clouds, as when Clouds sized itself by the document (before it became a filter). - #[test] - fn clouds_in_a_selection_are_the_canvas_clouds() { - // Big enough that the canvas (cloud size 100 px) and the selection (16 px) size differently. - let big = |depth: u32| { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 400, "height": 300, "depth": depth})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s - }; - for depth in [8, 16, 32] { - let mut whole = big(depth); - whole.execute("filter.render.clouds", json!({"seed": 4})).unwrap(); - let mut s = big(depth); - s.execute("select.rect", json!({"x": 50, "y": 40, "width": 60, "height": 50})).unwrap(); - s.execute("filter.render.clouds", json!({"seed": 4})).unwrap(); - for (x, y) in [(50, 40), (75, 60), (100, 85), (109, 89)] { - let (a, b) = (pixel(&s, x, y), pixel(&whole, x, y)); - assert!((0..4).all(|c| (a[c] - b[c]).abs() < 1e-3), "depth {depth} at {x},{y}: {a:?} vs {b:?}"); - } - assert_eq!(pixel(&s, 300, 200)[3], 0.0, "outside the selection the layer stays empty"); - } - } - - #[test] - fn average_and_clouds() { - let mut s = session(8); - paint_square(&mut s, Rect::new(0, 0, 20, 30), [1.0, 0.0, 0.0, 1.0]); - paint_square(&mut s, Rect::new(20, 0, 40, 30), [0.0, 0.0, 1.0, 1.0]); - s.execute("filter.blur.average", json!({})).unwrap(); - let p = pixel(&s, 5, 5); - assert!((p[0] - 0.5).abs() < 0.01 && (p[2] - 0.5).abs() < 0.01, "{p:?}"); - s.execute("filter.render.clouds", json!({"seed": 3})).unwrap(); - let vals: Vec = (0..40).map(|x| pixel(&s, x, 12)[0]).collect(); - let (lo, hi) = vals.iter().fold((1.0f32, 0.0f32), |(a, b), v| (a.min(*v), b.max(*v))); - assert!(hi - lo > 0.05, "clouds vary: {lo}..{hi}"); - assert!(vals.windows(2).all(|w| (w[0] - w[1]).abs() < 0.2), "clouds are smooth"); - // Difference Clouds over itself with the same seed cancels to black. - s.execute("filter.render.differenceClouds", json!({"seed": 3})).unwrap(); - assert!(pixel(&s, 7, 7)[..3].iter().all(|v| *v < 0.01), "{:?}", pixel(&s, 7, 7)); - } - - #[test] - fn paste_into_masks_to_the_selection() { - let mut s = session(8); - paint_square(&mut s, Rect::new(0, 0, 10, 10), [1.0, 0.0, 0.0, 1.0]); - s.execute("select.all", json!({})).unwrap(); - s.execute("edit.copy", json!({})).unwrap(); - let steps = s.active().unwrap().history.past_len(); - s.execute("select.rect", json!({"x": 20, "y": 10, "width": 8, "height": 8})).unwrap(); - s.execute("edit.pasteSpecial.pasteInto", json!({})).unwrap(); - let l = active(&s); - let m = l.mask.as_ref().unwrap(); - assert!(!m.linked); - assert_eq!(m.surface.content_bounds(), Rect::new(20, 10, 28, 18)); - assert_eq!(m.value(0, 0), 0.0); - assert!(doc(&s).selection.is_none()); - assert_eq!(s.active().unwrap().history.past_len(), steps + 2, "select + one Paste Into step"); - // Paste Outside reveals everything but the selection. - s.execute("select.rect", json!({"x": 20, "y": 10, "width": 8, "height": 8})).unwrap(); - s.execute("edit.pasteSpecial.pasteOutside", json!({})).unwrap(); - let m = active(&s).mask.as_ref().unwrap(); - assert_eq!((m.value(0, 0), m.value(22, 12)), (1.0, 0.0)); - } - - #[test] - fn option_click_eye_shows_one_layer_then_restores() { - let mut s = session(8); - s.execute("layer.new.layer", json!({})).unwrap(); - let ids: Vec = doc(&s).layers.iter().map(|l| l.id).collect(); - // Background, Layer 1 (hidden beforehand), Layer 2. - s.execute("layer.hideLayers", json!({"layer": ids[1].0})).unwrap(); - let vis = |s: &Session| doc(s).layers.iter().map(|l| l.visible).collect::>(); - assert_eq!(s.execute("layer.showOnly", json!({"layer": ids[1].0})).unwrap()["shownAlone"], true); - assert_eq!(vis(&s), [false, true, false]); - // Another eye moves the solo; the original snapshot survives. - s.execute("layer.showOnly", json!({"layer": ids[2].0})).unwrap(); - assert_eq!(vis(&s), [false, false, true]); - assert_eq!(s.execute("layer.showOnly", json!({"layer": ids[2].0})).unwrap()["shownAlone"], false); - assert_eq!(vis(&s), [true, false, true], "restored, with Layer 1 still hidden"); - // One history step each way. - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(vis(&s), [false, false, true]); - } - - #[test] - fn show_only_keeps_groups_and_their_contents() { - let mut s = session(8); - s.execute("layer.new.layer", json!({})).unwrap(); - let inner = active(&s).id; - let group = s.execute("layer.groupLayers", json!({"layer": inner.0})).unwrap()["layer"].as_u64().map(LayerId).unwrap(); - let shown = |s: &Session| doc(s).walk().iter().map(|(_, _, l)| l.visible).collect::>(); - // Background, Layer 1, Group 1, Layer 2 (inside the group). - s.execute("layer.showOnly", json!({"layer": inner.0})).unwrap(); - assert_eq!(shown(&s), [false, false, true, true], "the enclosing group stays visible"); - // An undo ends the solo, so the next ⌥-click solos again from the current state. - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(s.execute("layer.showOnly", json!({"layer": inner.0})).unwrap()["shownAlone"], true); - s.execute("edit.undo", json!({})).unwrap(); - // Showing a group alone leaves its contents as they are. - s.execute("layer.setProps", json!({"layer": inner.0, "visible": false})).unwrap(); - s.execute("layer.showOnly", json!({"layer": group.0})).unwrap(); - assert_eq!(shown(&s), [false, false, true, false]); - s.execute("layer.showOnly", json!({"layer": group.0})).unwrap(); - assert_eq!(shown(&s), [true, true, true, false]); - } - - #[test] - fn show_only_without_a_snapshot_shows_every_layer() { - let mut s = session(16); - let bg = doc(&s).layers[0].id; - s.execute("layer.hideLayers", json!({"layer": bg.0})).unwrap(); - // Layer 1 is already the only visible layer: ⌥-clicking it shows everything. - assert_eq!(s.execute("layer.showOnly", json!({})).unwrap()["shownAlone"], false); - assert!(doc(&s).layers.iter().all(|l| l.visible)); - assert!(s.execute("layer.showOnly", json!({"layer": u64::MAX})).is_err()); - assert!(Session::new().execute("layer.showOnly", json!({})).is_err()); - } - - #[test] - fn a_mask_turns_the_background_into_a_layer() { - for (cmd, needs_selection) in [ - ("layer.layerMask.revealAll", false), - ("layer.layerMask.hideAll", false), - ("layer.layerMask.revealSelection", true), - ("layer.layerMask.hideSelection", true), - ] { - let mut s = session(8); - let bg = doc(&s).layers[0].id; - if needs_selection { - s.execute("select.rect", json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap(); - } - s.execute(cmd, json!({"layer": bg.0})).unwrap(); - let l = &doc(&s).layers[0]; - assert!(l.mask.is_some() && l.name == "Layer 0" && !l.locks.transparency && !l.locks.position, "{cmd}"); - assert!(!s.is_enabled("layer.new.layerFromBackground"), "{cmd}"); - // One step: undo brings the locked Background back, without a mask. - assert!(s.undo()); - let l = &doc(&s).layers[0]; - assert!(l.mask.is_none() && l.name == "Background" && l.locks.transparency, "{cmd}"); - } - // Other layers keep their name and locks. - let mut s = session(8); - let top = doc(&s).layers[1].id; - s.execute("layer.setProps", json!({"layer": top.0, "locks": {"position": true}})).unwrap(); - s.execute("layer.layerMask.revealAll", json!({"layer": top.0})).unwrap(); - let l = doc(&s).layer(top).unwrap(); - assert!(l.mask.is_some() && l.name != "Layer 0" && l.locks.position); - assert_eq!(doc(&s).layers[0].name, "Background"); - } - - #[test] - fn hide_layers_toggles_once_every_target_is_hidden() { - let mut s = session(8); - s.execute("layer.new.layer", json!({})).unwrap(); - let b = active(&s).id; - let visible = |s: &Session| doc(s).layer(b).unwrap().visible; - // Select › All Layers leaves out the Background, as in Photoshop. - let all = |s: &Session| crate::layer_multi_cmds::selected(s).iter().map(|id| doc(s).layer(*id).unwrap().visible).collect::>(); - s.execute("layer.hideLayers", json!({})).unwrap(); - assert!(!visible(&s)); - s.execute("layer.hideLayers", json!({})).unwrap(); - assert!(visible(&s), "⌘, again shows it"); - // Several selected: any one still shown means hide them all; then they all come back. - s.execute("layer.hideLayers", json!({"layer": b.0})).unwrap(); - s.execute("select.allLayers", json!({})).unwrap(); - assert!(all(&s).len() > 1); - s.execute("layer.hideLayers", json!({})).unwrap(); - assert!(all(&s).iter().all(|v| !v)); - s.execute("layer.hideLayers", json!({})).unwrap(); - assert!(all(&s).iter().all(|v| *v)); - } - - #[test] - fn slash_toggles_lock_transparent_pixels_but_not_on_the_background() { - let mut s = session(8); - let bg = doc(&s).layers[0].id; - assert!(doc(&s).is_background(bg)); - s.execute("layer.new.layer", json!({})).unwrap(); - let top = active(&s).id; - let locked = |s: &Session, id: LayerId| doc(s).layer(id).unwrap().locks.transparency; - assert_eq!(s.execute("layer.toggleLockTransparency", json!({})).unwrap()["locked"], true); - assert!(locked(&s, top)); - s.execute("layer.toggleLockTransparency", json!({})).unwrap(); - assert!(!locked(&s, top)); - s.undo(); - assert!(locked(&s, top), "one undoable step each"); - let bg_locks = doc(&s).layer(bg).unwrap().locks; - assert!(s.execute("layer.toggleLockTransparency", json!({"layer": bg.0})).is_err()); - assert_eq!(doc(&s).layer(bg).unwrap().locks, bg_locks, "the Background is left alone"); - assert!(s.execute("layer.toggleLockTransparency", json!({"layer": u64::MAX})).is_err()); - } - - #[test] - fn layer_utilities() { - let mut s = session(8); - // Layer from Background. - assert!(s.is_enabled("layer.new.layerFromBackground")); - s.execute("layer.new.layerFromBackground", json!({})).unwrap(); - assert_eq!(doc(&s).layers[0].name, "Layer 0"); - assert!(!doc(&s).layers[0].locks.transparency); - assert!(!s.is_enabled("layer.new.layerFromBackground")); - // Copy / paste style and hide all effects. - s.execute("layer.layerStyle.dropShadow", json!({})).unwrap(); - s.execute("layer.layerStyle.copyLayerStyle", json!({})).unwrap(); - let top = doc(&s).layers[1].id; - s.execute("layer.layerStyle.pasteLayerStyle", json!({"layer": top.0})).unwrap(); - assert_eq!(doc(&s).layers[1].effects.items.len(), 1); - s.execute("layer.layerStyle.hideAllEffects", json!({})).unwrap(); - assert!(doc(&s).walk().iter().all(|(_, _, l)| l.effects.items.is_empty() || !l.effects.enabled)); - // Mask toggles. - s.execute("layer.layerMask.revealAll", json!({})).unwrap(); - s.execute("layer.layerMask.enabled", json!({})).unwrap(); - assert!(!active(&s).mask.as_ref().unwrap().enabled); - s.execute("layer.layerMask.linked", json!({"linked": false})).unwrap(); - assert!(!active(&s).mask.as_ref().unwrap().linked); - // Hide, delete hidden, delete empty. - s.execute("layer.new.layer", json!({})).unwrap(); - s.execute("layer.hideLayers", json!({})).unwrap(); - assert!(!active(&s).visible); - assert_eq!(s.execute("layer.delete.hiddenLayers", json!({})).unwrap()["deleted"], 1); - s.execute("layer.new.layer", json!({})).unwrap(); - let n = doc(&s).layer_count(); - assert_eq!(s.execute("file.scripts.deleteAllEmptyLayers", json!({})).unwrap()["deleted"], 1); - assert_eq!(doc(&s).layer_count(), n - 1); - } - - #[test] - fn ungroup_restores_children_in_order() { - let mut s = session(8); - let a = active(&s).id; - s.execute("layer.groupLayers", json!({})).unwrap(); - assert!(active(&s).is_group()); - s.execute("layer.ungroupLayers", json!({})).unwrap(); - assert_eq!(s.active().unwrap().active_layer, Some(a)); - assert!(doc(&s).layers.iter().all(|l| !l.is_group())); - assert_eq!(doc(&s).layers.len(), 2); - } - - #[test] - fn reveal_all_grows_the_canvas() { - let mut s = session(8); - s.execute("layer.translate", json!({"dx": 0, "dy": 0})).ok(); - paint_square(&mut s, Rect::new(-5, 0, 10, 10), [1.0, 0.0, 0.0, 1.0]); - assert_eq!(reveal_all_bounds(doc(&s)), Rect::new(-5, 0, 40, 30)); - let steps = s.active().unwrap().history.past_len(); - s.execute("image.revealAll", json!({})).unwrap(); - assert_eq!((doc(&s).size.width, doc(&s).size.height), (45, 30)); - let history = &s.active().unwrap().history; - assert_eq!(history.past_len(), steps + 1, "one step"); - assert_eq!(history.entries().last().map(String::as_str), Some("Reveal All"), "named as in Photoshop, not Crop"); - assert_eq!(s.execute("image.revealAll", json!({})).unwrap()["changed"], false); - } - - #[test] - fn reveal_all_skips_erased_pixels() { - // #9379: the Eraser only clears alpha, so erased pixels keep their colour bytes; Reveal - // All grew the canvas to them although nothing there is visible. - // No Background: its off-canvas pixels are opaque and would be revealed anyway. - for depth in [8, 16, 32] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 40, "height": 30, "depth": depth, "background": "transparent"})).unwrap(); - paint_square(&mut s, Rect::new(0, 0, 40, 30), [1.0, 0.0, 0.0, 1.0]); - let erase = json!({"points": [[32, -10], [32, 40]], "size": 28, "erase": true, "brush": {"hardness": 1.0}}); - s.execute("paint.stroke", erase).unwrap(); - assert_eq!(pixel(&s, 30, 15)[3], 0.0, "{depth}: erased"); - s.execute("image.canvasSize", json!({"width": 20, "height": 30, "anchor": "topLeft"})).unwrap(); - assert_eq!(s.execute("image.revealAll", json!({})).unwrap()["changed"], false, "{depth}"); - assert_eq!((doc(&s).size.width, doc(&s).size.height), (20, 30), "{depth}"); - // A pixel that is only partly erased is still there to reveal. - paint_square(&mut s, Rect::new(25, 5, 26, 6), [0.0, 0.0, 1.0, 0.5]); - assert_eq!(s.execute("image.revealAll", json!({})).unwrap()["changed"], true, "{depth}"); - assert_eq!((doc(&s).size.width, doc(&s).size.height), (26, 30), "{depth}"); - } - } - - #[test] - fn rasterize_fill_and_all_in_one_step() { - let mut s = session(8); - s.execute("layer.newFillLayer.solidColor", json!({"color": "#00ff00"})).unwrap(); - s.execute("layer.newFillLayer.solidColor", json!({"color": "#0000ff"})).unwrap(); - s.execute("layer.rasterize.fillContent", json!({})).unwrap(); - assert!(matches!(active(&s).content, LayerContent::Raster(_))); - assert_eq!(pixel(&s, 3, 3), vec![0.0, 0.0, 1.0, 1.0]); - assert!(s.execute("layer.rasterize.type", json!({})).is_err()); - let steps = s.active().unwrap().history.past_len(); - assert_eq!(s.execute("layer.rasterize.allLayers", json!({})).unwrap()["rasterized"], 1); - assert_eq!(s.active().unwrap().history.past_len(), steps + 1); - assert!(doc(&s).walk().iter().all(|(_, _, l)| !matches!(l.content, LayerContent::Fill(_)))); - } - - #[test] - fn rasterize_smart_object_layer() { - let mut s = session(8); - s.execute("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap(); - let px_before = pixel(&s, 5, 5); - s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - assert!(matches!(active(&s).content, LayerContent::Smart(_))); - s.execute("layer.rasterize.smartObject", json!({})).unwrap(); - assert!(matches!(active(&s).content, LayerContent::Raster(_))); - let px_after = pixel(&s, 5, 5); - assert_eq!(px_after, px_before); - - // Case 2: New layer above background - let mut s2 = session(8); - s2.execute("layer.new.layer", json!({})).unwrap(); - s2.execute("select.rect", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); - s2.execute("edit.fill", json!({"contents": "color", "color": "#00ff00"})).unwrap(); - s2.execute("select.deselect", json!({})).unwrap(); - let px_mid = pixel(&s2, 20, 20); - assert_eq!(px_mid[1], 1.0); // green - s2.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - assert!(matches!(active(&s2).content, LayerContent::Smart(_))); - s2.execute("layer.rasterize.smartObject", json!({})).unwrap(); - assert!(matches!(active(&s2).content, LayerContent::Raster(_))); - let px_after_rast = pixel(&s2, 20, 20); - assert_eq!(px_after_rast, px_mid); - - // Case 3: Shape layer converted to smart object then rasterized - let mut s3 = session(8); - s3.execute("shape.create", json!({"kind": "rect", "rect": [10, 10, 40, 40], "fill": "#0000ff"})).unwrap(); - let px_shape = pixel(&s3, 20, 20); - s3.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - assert!(matches!(active(&s3).content, LayerContent::Smart(_))); - s3.execute("layer.rasterize.layer", json!({})).unwrap(); - assert!(matches!(active(&s3).content, LayerContent::Raster(_))); - let px_after_shape = pixel(&s3, 20, 20); - assert_eq!(px_after_shape, px_shape); - - // Case 4: Transformed smart object - let mut s4 = session(8); - s4.execute("layer.new.layer", json!({})).unwrap(); - s4.execute("select.rect", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); - s4.execute("edit.fill", json!({"contents": "color", "color": "#ffff00"})).unwrap(); - s4.execute("select.deselect", json!({})).unwrap(); - s4.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - // Move smart object by 10, 10 - s4.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 10, 10]})).unwrap(); - s4.execute("layer.rasterize.smartObject", json!({})).unwrap(); - assert!(matches!(active(&s4).content, LayerContent::Raster(_))); - assert_eq!(pixel(&s4, 30, 30), vec![1.0, 1.0, 0.0, 1.0]); - } -} +mod tests; diff --git a/crates/engine/src/cmd/extra_cmds/tests.rs b/crates/engine/src/cmd/extra_cmds/tests.rs new file mode 100644 index 0000000000..97243efd58 --- /dev/null +++ b/crates/engine/src/cmd/extra_cmds/tests.rs @@ -0,0 +1,818 @@ +use super::*; + +fn session(depth: u32) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 40, "height": 30, "depth": depth})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s +} + +fn doc(s: &Session) -> &Document { + &s.active().unwrap().doc +} + +#[test] +fn equalize_average_and_clouds_edit_the_targeted_channel() { + // #935: these four ran through `map_pixels`, which always rewrote the active layer, so + // with an alpha channel or the Quick Mask targeted they changed the layer and left the + // channel alone. + let cmds = ["image.adjustments.equalize", "filter.blur.average", "filter.render.clouds", "filter.render.differenceClouds"]; + for depth in [8, 16, 32] { + for target in ["quickMask", "alpha", "mask"] { + for cmd in cmds { + let mut s = session(depth); + s.tools.foreground = [0.0, 0.0, 0.0, 1.0]; + s.tools.background = [1.0, 1.0, 1.0, 1.0]; + s.execute("edit.fill", json!({"contents": "color", "color": "#808080"})).unwrap(); + let p = match target { + "quickMask" => { + s.execute("select.editInQuickMaskMode", json!({"on": true})).unwrap(); + json!({"seed": 1}) + } + "alpha" => { + s.execute("channel.new", json!({"fill": "white"})).unwrap(); + s.execute("channel.target", json!({"channel": 0})).unwrap(); + json!({"seed": 1}) + } + _ => { + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + json!({"seed": 1, "target": "mask"}) + } + }; + // Two levels in the target, so Equalize and Average have something to change. + let edit_target = json!({ "target": if target == "alpha" { json!({"channel": 0}) } else { json!(target) } }); + s.edit("levels", |doc, active| { + let (surf, _) = crate::channel_cmds::target_surface(doc, *active, &edit_target).unwrap(); + surf.fill_rect(Rect::new(0, 0, 20, 30), &[0.4]); + surf.fill_rect(Rect::new(20, 0, 40, 30), &[0.5]); + Ok(()) + }) + .unwrap(); + let full = Rect::new(0, 0, 40, 30); + let read = |s: &Session| { + let d = doc(s); + let layer = d.layer(s.active().unwrap().active_layer.unwrap()).unwrap(); + let t = match target { + "quickMask" => d.quick_mask.as_ref().unwrap().surface.read_region(full), + "alpha" => d.channels[0].surface.read_region(full), + _ => layer.mask.as_ref().unwrap().surface.read_region(full), + }; + (layer.surface().unwrap().read_region(full), t) + }; + let ((layer0, target0), past) = (read(&s), s.active().unwrap().history.past_len()); + s.execute(cmd, p).unwrap(); + let (layer1, target1) = read(&s); + let case = format!("{cmd} on {target} at {depth}"); + assert_eq!(layer1, layer0, "{case}: the layer is untouched"); + assert_ne!(target1, target0, "{case}: the target changed"); + assert_eq!(s.active().unwrap().history.past_len(), past + 1, "{case}"); + s.undo(); + assert_eq!(read(&s).1, target0, "{case}: undo restores the target"); + } + } + } +} + +fn active(s: &Session) -> &Layer { + let d = s.active().unwrap(); + d.doc.layer(d.active_layer.unwrap()).unwrap() +} + +fn pixel(s: &Session, x: i32, y: i32) -> Vec { + active(s).surface().unwrap().pixel(x, y) +} + +fn paint_square(s: &mut Session, r: Rect, c: [f32; 4]) { + s.edit("paint", |doc, a| { + doc.layer_mut(a.unwrap()).unwrap().surface_mut().unwrap().fill_rect(r, &c); + Ok(()) + }) + .unwrap(); +} + +#[test] +fn stroke_locations_at_several_depths() { + for depth in [8, 16, 32] { + for (loc, inside, outside) in [("inside", 1.0, 0.0), ("outside", 0.0, 1.0), ("center", 1.0, 1.0)] { + let mut s = session(depth); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); + s.execute("edit.stroke", json!({"width": 2, "color": "#ff0000", "location": loc})).unwrap(); + assert!((pixel(&s, 10, 15)[3] - inside).abs() < 0.02, "{depth} {loc} inside {:?}", pixel(&s, 10, 15)); + assert!((pixel(&s, 9, 15)[3] - outside).abs() < 0.02, "{depth} {loc} outside {:?}", pixel(&s, 9, 15)); + assert_eq!(pixel(&s, 15, 15)[3], 0.0, "centre untouched"); + } + } + // Without a selection the layer's opaque edge is stroked. + let mut s = session(8); + paint_square(&mut s, Rect::new(10, 10, 20, 20), [0.0, 0.0, 1.0, 1.0]); + s.execute("edit.stroke", json!({"width": 3, "color": "#00ff00", "location": "outside"})).unwrap(); + assert_eq!(pixel(&s, 8, 15), vec![0.0, 1.0, 0.0, 1.0]); + assert_eq!(pixel(&s, 15, 15), vec![0.0, 0.0, 1.0, 1.0]); +} + +/// Photoshop's Edit › Stroke on a selection (checked by hand): Center puts ceil(w/2) px inside +/// and floor(w/2) outside (1 px is all inside), fractional widths round up, and every stroked +/// pixel is fully opaque, on every edge, horizontal ones included. Inside and Outside are +/// w px on their side. +#[test] +fn stroke_widths_are_whole_opaque_pixels_like_photoshop() { + // Selection x 10..30, y 10..30; the edge pixels inside are 10 and 29 on each axis. + let band = |loc: &str, w: i32| -> (i32, i32) { + match loc { + "inside" => (w, 0), + "outside" => (0, w), + _ => ((w + 1) / 2, w / 2), + } + }; + let mut wrong = Vec::new(); + for depth in [8, 16, 32] { + for loc in ["center", "inside", "outside"] { + for (param, w) in [(json!(1), 1), (json!(2), 2), (json!(3), 3), (json!(4), 4), (json!(5), 5), (json!(0.5), 1), (json!(2.5), 3)] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 50, "height": 50, "depth": depth})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + s.execute("edit.stroke", json!({"width": param, "color": "#ff0000", "location": loc})).unwrap(); + let (inside, outside) = band(loc, w); + // (edge pixel inside, step inward) for left, right, top and bottom; the other + // coordinate is the middle of the edge. + for (name, first_in, inward, horizontal) in [("left", 10, 1, false), ("right", 29, -1, false), ("top", 10, 1, true), ("bottom", 29, -1, true)] { + for k in -7..7 { + // k ≥ 0: k px inside from the edge; k < 0: -k px outside. + let c = first_in + k * inward; + let (x, y) = if horizontal { (20, c) } else { (c, 20) }; + let want = if (k >= 0 && k < inside) || (k < 0 && -k <= outside) { 1.0 } else { 0.0 }; + let a = pixel(&s, x, y)[3]; + if (a - want).abs() > 0.004 { + wrong.push(format!("{depth}-bit {loc} width {param} {name} edge, {k:+} px: alpha {a}, want {want}")); + } + } + } + } + } + } + assert!(wrong.is_empty(), "{} pixels differ from Photoshop:\n{}", wrong.len(), wrong.iter().take(40).cloned().collect::>().join("\n")); +} + +/// Photoshop's 6 px Outside stroke of a 14 px circle selection made without anti-aliasing, +/// read pixel by pixel from Photoshop (`#` stroked, `.` not; the hole is the selection). A +/// hard selection gives a hard stroke: a pixel is stroked when its centre is less than +/// width + 1 from a selected pixel's centre (no partial pixels on the curve). +const PS_CIRCLE_OUTSIDE_6: [&str; 31] = [ + "..................................", + "..................................", + "...........############...........", + "..........##############..........", + ".........################.........", + "........##################........", + ".......####################.......", + "......######################......", + ".....#########......#########.....", + "....#########........#########....", + "....########..........########....", + "....#######............#######....", + "....######..............######....", + "....######..............######....", + "....######..............######....", + "....######..............######....", + "....######..............######....", + "....######..............######....", + "....#######............#######....", + "....########..........########....", + "....#########........#########....", + ".....#########......#########.....", + "......######################......", + ".......####################.......", + "........##################........", + ".........################.........", + "..........##############..........", + "...........############...........", + "..................................", + "..................................", + "..................................", +]; + +/// Photoshop's 3 px Inside stroke of the same 14 px hard circle (the selection is the ring +/// plus its hole). Inside, a pixel is stroked when its centre is less than width + ½ from an +/// unselected pixel's: that offset is the one fitting this, the 5 px and the 6 px samples +/// (any value from +0.41 to +0.60), so 6 px fills this circle (its deepest pixel is 6.4 px in). +const PS_CIRCLE_INSIDE_3: [&str; 17] = [ + "...................", + "......######.......", + ".....########......", + "....##########.....", + "...####....####....", + "..####......####...", + "..###........###...", + "..###........###...", + "..###........###...", + "..###........###...", + "..####......####...", + "...####....####....", + "....##########.....", + ".....########......", + "......######.......", + "...................", + "...................", +]; + +/// The selection of a Photoshop sample grid: an Outside stroke's hole, or an Inside stroke's +/// ring and hole. +fn grid_selection(rows: &[&str], outside: bool) -> Vec { + let (w, h) = (rows[0].len(), rows.len()); + let mut mask = vec![0.0f32; w * h]; + for (y, row) in rows.iter().enumerate() { + let b = row.as_bytes(); + if let (Some(first), Some(last)) = (b.iter().position(|c| *c == b'#'), b.iter().rposition(|c| *c == b'#')) { + for x in first..=last { + if !outside || b[x] == b'.' { + mask[y * w + x] = 1.0; + } + } + } + } + mask +} + +/// Strokes `mask` as the selection of a `w` × `h` layer and returns its alpha per pixel. +fn stroke_alpha(mask: &[f32], w: usize, h: usize, depth: u32, params: Value) -> Vec { + let mut s = Session::new(); + s.execute("file.new", json!({"width": w, "height": h, "depth": depth})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.edit("select", |doc, _| { + doc.selection = Some(sel::mask_to_surface(mask, doc.bounds())); + Ok(()) + }) + .unwrap(); + s.execute("edit.stroke", params).unwrap(); + (0..h).flat_map(|y| (0..w).map(move |x| (x, y))).map(|(x, y)| pixel(&s, x as i32, y as i32)[3]).collect() +} + +#[test] +fn a_hard_circle_strokes_inside_like_photoshop() { + let rows = PS_CIRCLE_INSIDE_3; + let (w, h) = (rows[0].len(), rows.len()); + let mask = grid_selection(&rows, false); + for depth in [8, 16, 32] { + let got = stroke_alpha(&mask, w, h, depth, json!({"width": 3, "color": "#000000", "location": "inside"})); + let wrong: Vec = rows + .iter() + .enumerate() + .flat_map(|(y, row)| row.bytes().enumerate().map(move |(x, c)| (x, y, c))) + .filter_map(|(x, y, c)| { + let want = if c == b'#' { 1.0 } else { 0.0 }; + let a = got[y * w + x]; + ((a - want).abs() > 0.004).then(|| format!("({x}, {y}): {a}, Photoshop {want}")) + }) + .collect(); + assert!(wrong.is_empty(), "{depth}-bit: {} pixels differ from Photoshop: {wrong:?}", wrong.len()); + // Checked in Photoshop: a 5 px Inside stroke leaves a plus-shaped hole of 12 pixels in + // the middle (rows 2, 4, 4, 2 wide), and 6 px fills the whole circle. + let hole = [(8, 6), (9, 6), (7, 7), (8, 7), (9, 7), (10, 7), (7, 8), (8, 8), (9, 8), (10, 8), (8, 9), (9, 9)]; + let five = stroke_alpha(&mask, w, h, depth, json!({"width": 5, "color": "#000000", "location": "inside"})); + for (i, m) in mask.iter().enumerate() { + let stroked = *m > 0.0 && !hole.contains(&(i % w, i / w)); + assert_eq!(five[i] > 0.996, stroked, "{depth}-bit 5 px Inside at ({}, {})", i % w, i / w); + } + let full = stroke_alpha(&mask, w, h, depth, json!({"width": 6, "color": "#000000", "location": "inside"})); + for (i, m) in mask.iter().enumerate() { + assert_eq!(full[i] > 0.996, *m > 0.0, "{depth}-bit 6 px Inside at ({}, {})", i % w, i / w); + } + } +} + +#[test] +fn a_hard_circle_strokes_like_photoshop() { + let rows = PS_CIRCLE_OUTSIDE_6; + let (w, h) = (rows[0].len(), rows.len()); + // The selection: the `.` cells enclosed by the ring on each row. + let mask = grid_selection(&rows, true); + for depth in [8, 16, 32] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": w, "height": h, "depth": depth})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.edit("select", |doc, _| { + doc.selection = Some(sel::mask_to_surface(&mask, doc.bounds())); + Ok(()) + }) + .unwrap(); + s.execute("edit.stroke", json!({"width": 6, "color": "#000000", "location": "outside"})).unwrap(); + let mut wrong = Vec::new(); + for (y, row) in rows.iter().enumerate() { + for (x, c) in row.bytes().enumerate() { + let want = if c == b'#' { 1.0 } else { 0.0 }; + let a = pixel(&s, x as i32, y as i32)[3]; + if (a - want).abs() > 0.004 { + wrong.push(format!("({x}, {y}): {a}, Photoshop {want}")); + } + } + } + assert!(wrong.is_empty(), "{depth}-bit: {} pixels differ from Photoshop: {wrong:?}", wrong.len()); + } +} + +/// Select All, then Stroke › Inside draws a border around the canvas (a common Photoshop +/// technique): the canvas edge is a selection edge like any other, on all four sides. +#[test] +fn stroking_a_selection_at_the_canvas_edge_draws_that_edge() { + for depth in [8, 16, 32] { + for (loc, w, inside) in [("inside", 3, 3), ("center", 3, 2), ("center", 1, 1)] { + let mut s = session(depth); + s.execute("select.all", json!({})).unwrap(); + s.execute("edit.stroke", json!({"width": w, "color": "#ff0000", "location": loc})).unwrap(); + // 40 × 30 canvas: k px in from each side, in the middle of the side. + for name in ["left", "right", "top", "bottom"] { + for k in 0..6 { + let (x, y) = match name { + "left" => (k, 15), + "right" => (39 - k, 15), + "top" => (20, k), + _ => (20, 29 - k), + }; + let want = if k < inside { 1.0 } else { 0.0 }; + let a = pixel(&s, x, y)[3]; + assert!((a - want).abs() < 0.004, "{depth}-bit {loc} {w} px, {name} side, {k} px in: alpha {a}, want {want}"); + } + } + } + } +} + +#[test] +fn stroke_uses_fill_blending_and_preserves_transparency_at_every_depth() { + for depth in [8, 16, 32] { + let mut s = session(depth); + paint_square(&mut s, Rect::new(10, 10, 20, 20), [0.5, 0.5, 0.5, 1.0]); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); + + let past = s.active().unwrap().history.past_len(); + s.execute( + "edit.stroke", + json!({"width": 2, "color": "#ffffff", "location": "inside", "mode": "multiply", "opacity": 100, "preserveTransparency": true}), + ) + .unwrap(); + assert_eq!(s.active().unwrap().history.past_len(), past + 1, "Stroke is one history step"); + let edge = pixel(&s, 10, 15); + assert!((edge[0] - 0.5).abs() < 0.015, "{depth}-bit Multiply must preserve gray: {edge:?}"); + assert_eq!(edge[3], 1.0); + + s.execute("edit.stroke", json!({"width": 2, "color": "#ffffff", "location": "outside", "preserveTransparency": true})).unwrap(); + assert_eq!(pixel(&s, 9, 15)[3], 0.0, "{depth}-bit transparency lock prevents new outer pixels"); + + s.execute("edit.stroke", json!({"width": 2, "color": "#ffffff", "location": "outside", "opacity": 50})).unwrap(); + let out = pixel(&s, 9, 15); + assert!((out[3] - 0.5).abs() < 0.015, "{depth}-bit 50% stroke opacity: {out:?}"); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(pixel(&s, 9, 15)[3], 0.0); + } +} + +#[test] +fn stroke_rejects_invalid_blending_options_without_modifying_the_document() { + let mut s = session(8); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); + let past = s.active().unwrap().history.past_len(); + for params in [ + json!({"mode": "unknown-mode"}), + json!({"mode": 42}), + json!({"mode": "passThrough"}), + json!({"opacity": "lots"}), + json!({"preserveTransparency": "true"}), + ] { + assert!(s.execute("edit.stroke", params.clone()).is_err(), "{params}"); + assert_eq!(s.active().unwrap().history.past_len(), past, "{params} should not create a history step"); + } +} + +#[test] +fn transform_presets_are_exact() { + let mut s = session(8); + paint_square(&mut s, Rect::new(10, 10, 20, 14), [1.0, 0.0, 0.0, 1.0]); + paint_square(&mut s, Rect::new(10, 10, 11, 11), [0.0, 1.0, 0.0, 1.0]); + s.execute("edit.transform.flipHorizontal", json!({})).unwrap(); + assert_eq!(active(&s).surface().unwrap().content_bounds(), Rect::new(10, 10, 20, 14)); + assert_eq!(pixel(&s, 19, 10), vec![0.0, 1.0, 0.0, 1.0]); + s.execute("edit.transform.flipVertical", json!({})).unwrap(); + assert_eq!(pixel(&s, 19, 13), vec![0.0, 1.0, 0.0, 1.0]); + s.execute("edit.transform.rotate180", json!({})).unwrap(); + assert_eq!(pixel(&s, 10, 10), vec![0.0, 1.0, 0.0, 1.0]); + s.execute("edit.transform.rotate90Cw", json!({})).unwrap(); + let b = active(&s).surface().unwrap().content_bounds(); + assert_eq!((b.width(), b.height()), (4, 10)); + // Top-left corner goes to the top-right after a clockwise turn. + assert_eq!(pixel(&s, b.x1 - 1, b.y0), vec![0.0, 1.0, 0.0, 1.0]); + s.execute("edit.transform.rotate90Ccw", json!({})).unwrap(); + assert_eq!(active(&s).surface().unwrap().content_bounds(), Rect::new(10, 10, 20, 14)); + assert_eq!(pixel(&s, 10, 10), vec![0.0, 1.0, 0.0, 1.0]); +} + +/// #6928: with a selection, the presets flip and turn about the selection's own bounds, as +/// in Photoshop: Select All mirrors across the canvas, a marquee across its own centre. +/// Without a selection they keep turning about the content (above). +#[test] +fn transform_presets_turn_about_the_selection() { + let mut s = session(8); + paint_square(&mut s, Rect::new(10, 10, 20, 14), [1.0, 0.0, 0.0, 1.0]); + paint_square(&mut s, Rect::new(10, 10, 11, 11), [0.0, 1.0, 0.0, 1.0]); + let green = vec![0.0, 1.0, 0.0, 1.0]; + // Select All on the 40 × 30 canvas: across the canvas's centre lines. + s.execute("select.all", json!({})).unwrap(); + let past = s.active().unwrap().history.past_len(); + s.execute("edit.transform.flipHorizontal", json!({})).unwrap(); + assert_eq!(active(&s).surface().unwrap().content_bounds(), Rect::new(20, 10, 30, 14)); + assert_eq!(pixel(&s, 29, 10), green); + assert_eq!(s.active().unwrap().history.past_len(), past + 1, "one undo step"); + s.execute("edit.transform.flipVertical", json!({})).unwrap(); + assert_eq!(active(&s).surface().unwrap().content_bounds(), Rect::new(20, 16, 30, 20)); + assert_eq!(pixel(&s, 29, 19), green); + s.execute("edit.transform.rotate180", json!({})).unwrap(); + assert_eq!(active(&s).surface().unwrap().content_bounds(), Rect::new(10, 10, 20, 14)); + assert_eq!(pixel(&s, 10, 10), green); + // A marquee (0, 0)–(24, 30) holding the whole square: across x = 12. + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 24, "height": 30})).unwrap(); + s.execute("edit.transform.flipHorizontal", json!({})).unwrap(); + assert_eq!(active(&s).surface().unwrap().content_bounds(), Rect::new(4, 10, 14, 14)); + assert_eq!(pixel(&s, 13, 10), green); + // Undo puts it back where it was. + s.undo(); + assert_eq!(active(&s).surface().unwrap().content_bounds(), Rect::new(10, 10, 20, 14)); + // A targeted alpha channel turns about the selection's bounds too. + s.execute("channel.new", json!({})).unwrap(); + s.edit("paint channel", |doc, _| { + doc.channels[0].surface.fill_rect(Rect::new(10, 10, 20, 20), &[1.0]); + Ok(()) + }) + .unwrap(); + s.execute("channel.target", json!({"channel": 0})).unwrap(); + s.execute("select.all", json!({})).unwrap(); + s.execute("edit.transform.flipHorizontal", json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc.channels[0].surface.content_bounds(), Rect::new(20, 10, 30, 20)); +} + +#[test] +fn reselect_restores_the_last_selection() { + let mut s = session(8); + assert!(!s.is_enabled("select.reselect")); + s.execute("select.rect", json!({"x": 2, "y": 3, "width": 5, "height": 6})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + assert!(doc(&s).selection.is_none()); + s.execute("select.reselect", json!({})).unwrap(); + assert_eq!(doc(&s).selection.as_ref().unwrap().content_bounds(), Rect::new(2, 3, 7, 9)); + assert!(!s.is_enabled("select.reselect"), "nothing to reselect while a selection exists"); +} + +#[test] +fn equalize_spreads_values() { + for depth in [8, 16] { + let mut s = session(depth); + paint_square(&mut s, Rect::new(0, 0, 40, 15), [0.4, 0.4, 0.4, 1.0]); + paint_square(&mut s, Rect::new(0, 15, 40, 30), [0.5, 0.5, 0.5, 1.0]); + s.execute("image.adjustments.equalize", json!({})).unwrap(); + let (dark, light) = (pixel(&s, 1, 1)[0], pixel(&s, 1, 20)[0]); + assert!(dark < 0.05 && light > 0.95, "{depth}: {dark} {light}"); + } +} + +/// A selection masks Clouds but doesn't change their size: inside it they are the canvas's +/// clouds, as when Clouds sized itself by the document (before it became a filter). +#[test] +fn clouds_in_a_selection_are_the_canvas_clouds() { + // Big enough that the canvas (cloud size 100 px) and the selection (16 px) size differently. + let big = |depth: u32| { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 400, "height": 300, "depth": depth})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s + }; + for depth in [8, 16, 32] { + let mut whole = big(depth); + whole.execute("filter.render.clouds", json!({"seed": 4})).unwrap(); + let mut s = big(depth); + s.execute("select.rect", json!({"x": 50, "y": 40, "width": 60, "height": 50})).unwrap(); + s.execute("filter.render.clouds", json!({"seed": 4})).unwrap(); + for (x, y) in [(50, 40), (75, 60), (100, 85), (109, 89)] { + let (a, b) = (pixel(&s, x, y), pixel(&whole, x, y)); + assert!((0..4).all(|c| (a[c] - b[c]).abs() < 1e-3), "depth {depth} at {x},{y}: {a:?} vs {b:?}"); + } + assert_eq!(pixel(&s, 300, 200)[3], 0.0, "outside the selection the layer stays empty"); + } +} + +#[test] +fn average_and_clouds() { + let mut s = session(8); + paint_square(&mut s, Rect::new(0, 0, 20, 30), [1.0, 0.0, 0.0, 1.0]); + paint_square(&mut s, Rect::new(20, 0, 40, 30), [0.0, 0.0, 1.0, 1.0]); + s.execute("filter.blur.average", json!({})).unwrap(); + let p = pixel(&s, 5, 5); + assert!((p[0] - 0.5).abs() < 0.01 && (p[2] - 0.5).abs() < 0.01, "{p:?}"); + s.execute("filter.render.clouds", json!({"seed": 3})).unwrap(); + let vals: Vec = (0..40).map(|x| pixel(&s, x, 12)[0]).collect(); + let (lo, hi) = vals.iter().fold((1.0f32, 0.0f32), |(a, b), v| (a.min(*v), b.max(*v))); + assert!(hi - lo > 0.05, "clouds vary: {lo}..{hi}"); + assert!(vals.windows(2).all(|w| (w[0] - w[1]).abs() < 0.2), "clouds are smooth"); + // Difference Clouds over itself with the same seed cancels to black. + s.execute("filter.render.differenceClouds", json!({"seed": 3})).unwrap(); + assert!(pixel(&s, 7, 7)[..3].iter().all(|v| *v < 0.01), "{:?}", pixel(&s, 7, 7)); +} + +#[test] +fn paste_into_masks_to_the_selection() { + let mut s = session(8); + paint_square(&mut s, Rect::new(0, 0, 10, 10), [1.0, 0.0, 0.0, 1.0]); + s.execute("select.all", json!({})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + let steps = s.active().unwrap().history.past_len(); + s.execute("select.rect", json!({"x": 20, "y": 10, "width": 8, "height": 8})).unwrap(); + s.execute("edit.pasteSpecial.pasteInto", json!({})).unwrap(); + let l = active(&s); + let m = l.mask.as_ref().unwrap(); + assert!(!m.linked); + assert_eq!(m.surface.content_bounds(), Rect::new(20, 10, 28, 18)); + assert_eq!(m.value(0, 0), 0.0); + assert!(doc(&s).selection.is_none()); + assert_eq!(s.active().unwrap().history.past_len(), steps + 2, "select + one Paste Into step"); + // Paste Outside reveals everything but the selection. + s.execute("select.rect", json!({"x": 20, "y": 10, "width": 8, "height": 8})).unwrap(); + s.execute("edit.pasteSpecial.pasteOutside", json!({})).unwrap(); + let m = active(&s).mask.as_ref().unwrap(); + assert_eq!((m.value(0, 0), m.value(22, 12)), (1.0, 0.0)); +} + +#[test] +fn option_click_eye_shows_one_layer_then_restores() { + let mut s = session(8); + s.execute("layer.new.layer", json!({})).unwrap(); + let ids: Vec = doc(&s).layers.iter().map(|l| l.id).collect(); + // Background, Layer 1 (hidden beforehand), Layer 2. + s.execute("layer.hideLayers", json!({"layer": ids[1].0})).unwrap(); + let vis = |s: &Session| doc(s).layers.iter().map(|l| l.visible).collect::>(); + assert_eq!(s.execute("layer.showOnly", json!({"layer": ids[1].0})).unwrap()["shownAlone"], true); + assert_eq!(vis(&s), [false, true, false]); + // Another eye moves the solo; the original snapshot survives. + s.execute("layer.showOnly", json!({"layer": ids[2].0})).unwrap(); + assert_eq!(vis(&s), [false, false, true]); + assert_eq!(s.execute("layer.showOnly", json!({"layer": ids[2].0})).unwrap()["shownAlone"], false); + assert_eq!(vis(&s), [true, false, true], "restored, with Layer 1 still hidden"); + // One history step each way. + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(vis(&s), [false, false, true]); +} + +#[test] +fn show_only_keeps_groups_and_their_contents() { + let mut s = session(8); + s.execute("layer.new.layer", json!({})).unwrap(); + let inner = active(&s).id; + let group = s.execute("layer.groupLayers", json!({"layer": inner.0})).unwrap()["layer"].as_u64().map(LayerId).unwrap(); + let shown = |s: &Session| doc(s).walk().iter().map(|(_, _, l)| l.visible).collect::>(); + // Background, Layer 1, Group 1, Layer 2 (inside the group). + s.execute("layer.showOnly", json!({"layer": inner.0})).unwrap(); + assert_eq!(shown(&s), [false, false, true, true], "the enclosing group stays visible"); + // An undo ends the solo, so the next ⌥-click solos again from the current state. + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(s.execute("layer.showOnly", json!({"layer": inner.0})).unwrap()["shownAlone"], true); + s.execute("edit.undo", json!({})).unwrap(); + // Showing a group alone leaves its contents as they are. + s.execute("layer.setProps", json!({"layer": inner.0, "visible": false})).unwrap(); + s.execute("layer.showOnly", json!({"layer": group.0})).unwrap(); + assert_eq!(shown(&s), [false, false, true, false]); + s.execute("layer.showOnly", json!({"layer": group.0})).unwrap(); + assert_eq!(shown(&s), [true, true, true, false]); +} + +#[test] +fn show_only_without_a_snapshot_shows_every_layer() { + let mut s = session(16); + let bg = doc(&s).layers[0].id; + s.execute("layer.hideLayers", json!({"layer": bg.0})).unwrap(); + // Layer 1 is already the only visible layer: ⌥-clicking it shows everything. + assert_eq!(s.execute("layer.showOnly", json!({})).unwrap()["shownAlone"], false); + assert!(doc(&s).layers.iter().all(|l| l.visible)); + assert!(s.execute("layer.showOnly", json!({"layer": u64::MAX})).is_err()); + assert!(Session::new().execute("layer.showOnly", json!({})).is_err()); +} + +#[test] +fn a_mask_turns_the_background_into_a_layer() { + for (cmd, needs_selection) in [ + ("layer.layerMask.revealAll", false), + ("layer.layerMask.hideAll", false), + ("layer.layerMask.revealSelection", true), + ("layer.layerMask.hideSelection", true), + ] { + let mut s = session(8); + let bg = doc(&s).layers[0].id; + if needs_selection { + s.execute("select.rect", json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap(); + } + s.execute(cmd, json!({"layer": bg.0})).unwrap(); + let l = &doc(&s).layers[0]; + assert!(l.mask.is_some() && l.name == "Layer 0" && !l.locks.transparency && !l.locks.position, "{cmd}"); + assert!(!s.is_enabled("layer.new.layerFromBackground"), "{cmd}"); + // One step: undo brings the locked Background back, without a mask. + assert!(s.undo()); + let l = &doc(&s).layers[0]; + assert!(l.mask.is_none() && l.name == "Background" && l.locks.transparency, "{cmd}"); + } + // Other layers keep their name and locks. + let mut s = session(8); + let top = doc(&s).layers[1].id; + s.execute("layer.setProps", json!({"layer": top.0, "locks": {"position": true}})).unwrap(); + s.execute("layer.layerMask.revealAll", json!({"layer": top.0})).unwrap(); + let l = doc(&s).layer(top).unwrap(); + assert!(l.mask.is_some() && l.name != "Layer 0" && l.locks.position); + assert_eq!(doc(&s).layers[0].name, "Background"); +} + +#[test] +fn hide_layers_toggles_once_every_target_is_hidden() { + let mut s = session(8); + s.execute("layer.new.layer", json!({})).unwrap(); + let b = active(&s).id; + let visible = |s: &Session| doc(s).layer(b).unwrap().visible; + // Select › All Layers leaves out the Background, as in Photoshop. + let all = |s: &Session| crate::layer_multi_cmds::selected(s).iter().map(|id| doc(s).layer(*id).unwrap().visible).collect::>(); + s.execute("layer.hideLayers", json!({})).unwrap(); + assert!(!visible(&s)); + s.execute("layer.hideLayers", json!({})).unwrap(); + assert!(visible(&s), "⌘, again shows it"); + // Several selected: any one still shown means hide them all; then they all come back. + s.execute("layer.hideLayers", json!({"layer": b.0})).unwrap(); + s.execute("select.allLayers", json!({})).unwrap(); + assert!(all(&s).len() > 1); + s.execute("layer.hideLayers", json!({})).unwrap(); + assert!(all(&s).iter().all(|v| !v)); + s.execute("layer.hideLayers", json!({})).unwrap(); + assert!(all(&s).iter().all(|v| *v)); +} + +#[test] +fn slash_toggles_lock_transparent_pixels_but_not_on_the_background() { + let mut s = session(8); + let bg = doc(&s).layers[0].id; + assert!(doc(&s).is_background(bg)); + s.execute("layer.new.layer", json!({})).unwrap(); + let top = active(&s).id; + let locked = |s: &Session, id: LayerId| doc(s).layer(id).unwrap().locks.transparency; + assert_eq!(s.execute("layer.toggleLockTransparency", json!({})).unwrap()["locked"], true); + assert!(locked(&s, top)); + s.execute("layer.toggleLockTransparency", json!({})).unwrap(); + assert!(!locked(&s, top)); + s.undo(); + assert!(locked(&s, top), "one undoable step each"); + let bg_locks = doc(&s).layer(bg).unwrap().locks; + assert!(s.execute("layer.toggleLockTransparency", json!({"layer": bg.0})).is_err()); + assert_eq!(doc(&s).layer(bg).unwrap().locks, bg_locks, "the Background is left alone"); + assert!(s.execute("layer.toggleLockTransparency", json!({"layer": u64::MAX})).is_err()); +} + +#[test] +fn layer_utilities() { + let mut s = session(8); + // Layer from Background. + assert!(s.is_enabled("layer.new.layerFromBackground")); + s.execute("layer.new.layerFromBackground", json!({})).unwrap(); + assert_eq!(doc(&s).layers[0].name, "Layer 0"); + assert!(!doc(&s).layers[0].locks.transparency); + assert!(!s.is_enabled("layer.new.layerFromBackground")); + // Copy / paste style and hide all effects. + s.execute("layer.layerStyle.dropShadow", json!({})).unwrap(); + s.execute("layer.layerStyle.copyLayerStyle", json!({})).unwrap(); + let top = doc(&s).layers[1].id; + s.execute("layer.layerStyle.pasteLayerStyle", json!({"layer": top.0})).unwrap(); + assert_eq!(doc(&s).layers[1].effects.items.len(), 1); + s.execute("layer.layerStyle.hideAllEffects", json!({})).unwrap(); + assert!(doc(&s).walk().iter().all(|(_, _, l)| l.effects.items.is_empty() || !l.effects.enabled)); + // Mask toggles. + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + s.execute("layer.layerMask.enabled", json!({})).unwrap(); + assert!(!active(&s).mask.as_ref().unwrap().enabled); + s.execute("layer.layerMask.linked", json!({"linked": false})).unwrap(); + assert!(!active(&s).mask.as_ref().unwrap().linked); + // Hide, delete hidden, delete empty. + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("layer.hideLayers", json!({})).unwrap(); + assert!(!active(&s).visible); + assert_eq!(s.execute("layer.delete.hiddenLayers", json!({})).unwrap()["deleted"], 1); + s.execute("layer.new.layer", json!({})).unwrap(); + let n = doc(&s).layer_count(); + assert_eq!(s.execute("file.scripts.deleteAllEmptyLayers", json!({})).unwrap()["deleted"], 1); + assert_eq!(doc(&s).layer_count(), n - 1); +} + +#[test] +fn ungroup_restores_children_in_order() { + let mut s = session(8); + let a = active(&s).id; + s.execute("layer.groupLayers", json!({})).unwrap(); + assert!(active(&s).is_group()); + s.execute("layer.ungroupLayers", json!({})).unwrap(); + assert_eq!(s.active().unwrap().active_layer, Some(a)); + assert!(doc(&s).layers.iter().all(|l| !l.is_group())); + assert_eq!(doc(&s).layers.len(), 2); +} + +#[test] +fn reveal_all_grows_the_canvas() { + let mut s = session(8); + s.execute("layer.translate", json!({"dx": 0, "dy": 0})).ok(); + paint_square(&mut s, Rect::new(-5, 0, 10, 10), [1.0, 0.0, 0.0, 1.0]); + assert_eq!(reveal_all_bounds(doc(&s)), Rect::new(-5, 0, 40, 30)); + let steps = s.active().unwrap().history.past_len(); + s.execute("image.revealAll", json!({})).unwrap(); + assert_eq!((doc(&s).size.width, doc(&s).size.height), (45, 30)); + let history = &s.active().unwrap().history; + assert_eq!(history.past_len(), steps + 1, "one step"); + assert_eq!(history.entries().last().map(String::as_str), Some("Reveal All"), "named as in Photoshop, not Crop"); + assert_eq!(s.execute("image.revealAll", json!({})).unwrap()["changed"], false); +} + +#[test] +fn reveal_all_skips_erased_pixels() { + // #9379: the Eraser only clears alpha, so erased pixels keep their colour bytes; Reveal + // All grew the canvas to them although nothing there is visible. + // No Background: its off-canvas pixels are opaque and would be revealed anyway. + for depth in [8, 16, 32] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 40, "height": 30, "depth": depth, "background": "transparent"})).unwrap(); + paint_square(&mut s, Rect::new(0, 0, 40, 30), [1.0, 0.0, 0.0, 1.0]); + let erase = json!({"points": [[32, -10], [32, 40]], "size": 28, "erase": true, "brush": {"hardness": 1.0}}); + s.execute("paint.stroke", erase).unwrap(); + assert_eq!(pixel(&s, 30, 15)[3], 0.0, "{depth}: erased"); + s.execute("image.canvasSize", json!({"width": 20, "height": 30, "anchor": "topLeft"})).unwrap(); + assert_eq!(s.execute("image.revealAll", json!({})).unwrap()["changed"], false, "{depth}"); + assert_eq!((doc(&s).size.width, doc(&s).size.height), (20, 30), "{depth}"); + // A pixel that is only partly erased is still there to reveal. + paint_square(&mut s, Rect::new(25, 5, 26, 6), [0.0, 0.0, 1.0, 0.5]); + assert_eq!(s.execute("image.revealAll", json!({})).unwrap()["changed"], true, "{depth}"); + assert_eq!((doc(&s).size.width, doc(&s).size.height), (26, 30), "{depth}"); + } +} + +#[test] +fn rasterize_fill_and_all_in_one_step() { + let mut s = session(8); + s.execute("layer.newFillLayer.solidColor", json!({"color": "#00ff00"})).unwrap(); + s.execute("layer.newFillLayer.solidColor", json!({"color": "#0000ff"})).unwrap(); + s.execute("layer.rasterize.fillContent", json!({})).unwrap(); + assert!(matches!(active(&s).content, LayerContent::Raster(_))); + assert_eq!(pixel(&s, 3, 3), vec![0.0, 0.0, 1.0, 1.0]); + assert!(s.execute("layer.rasterize.type", json!({})).is_err()); + let steps = s.active().unwrap().history.past_len(); + assert_eq!(s.execute("layer.rasterize.allLayers", json!({})).unwrap()["rasterized"], 1); + assert_eq!(s.active().unwrap().history.past_len(), steps + 1); + assert!(doc(&s).walk().iter().all(|(_, _, l)| !matches!(l.content, LayerContent::Fill(_)))); +} + +#[test] +fn rasterize_smart_object_layer() { + let mut s = session(8); + s.execute("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap(); + let px_before = pixel(&s, 5, 5); + s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + assert!(matches!(active(&s).content, LayerContent::Smart(_))); + s.execute("layer.rasterize.smartObject", json!({})).unwrap(); + assert!(matches!(active(&s).content, LayerContent::Raster(_))); + let px_after = pixel(&s, 5, 5); + assert_eq!(px_after, px_before); + + // Case 2: New layer above background + let mut s2 = session(8); + s2.execute("layer.new.layer", json!({})).unwrap(); + s2.execute("select.rect", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + s2.execute("edit.fill", json!({"contents": "color", "color": "#00ff00"})).unwrap(); + s2.execute("select.deselect", json!({})).unwrap(); + let px_mid = pixel(&s2, 20, 20); + assert_eq!(px_mid[1], 1.0); // green + s2.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + assert!(matches!(active(&s2).content, LayerContent::Smart(_))); + s2.execute("layer.rasterize.smartObject", json!({})).unwrap(); + assert!(matches!(active(&s2).content, LayerContent::Raster(_))); + let px_after_rast = pixel(&s2, 20, 20); + assert_eq!(px_after_rast, px_mid); + + // Case 3: Shape layer converted to smart object then rasterized + let mut s3 = session(8); + s3.execute("shape.create", json!({"kind": "rect", "rect": [10, 10, 40, 40], "fill": "#0000ff"})).unwrap(); + let px_shape = pixel(&s3, 20, 20); + s3.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + assert!(matches!(active(&s3).content, LayerContent::Smart(_))); + s3.execute("layer.rasterize.layer", json!({})).unwrap(); + assert!(matches!(active(&s3).content, LayerContent::Raster(_))); + let px_after_shape = pixel(&s3, 20, 20); + assert_eq!(px_after_shape, px_shape); + + // Case 4: Transformed smart object + let mut s4 = session(8); + s4.execute("layer.new.layer", json!({})).unwrap(); + s4.execute("select.rect", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + s4.execute("edit.fill", json!({"contents": "color", "color": "#ffff00"})).unwrap(); + s4.execute("select.deselect", json!({})).unwrap(); + s4.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + // Move smart object by 10, 10 + s4.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 10, 10]})).unwrap(); + s4.execute("layer.rasterize.smartObject", json!({})).unwrap(); + assert!(matches!(active(&s4).content, LayerContent::Raster(_))); + assert_eq!(pixel(&s4, 30, 30), vec![1.0, 1.0, 0.0, 1.0]); +} diff --git a/crates/engine/src/face_cmds.rs b/crates/engine/src/cmd/face_cmds.rs similarity index 100% rename from crates/engine/src/face_cmds.rs rename to crates/engine/src/cmd/face_cmds.rs diff --git a/crates/engine/src/cmd/file_cmds.rs b/crates/engine/src/cmd/file_cmds.rs new file mode 100644 index 0000000000..efdd3ad8bf --- /dev/null +++ b/crates/engine/src/cmd/file_cmds.rs @@ -0,0 +1,445 @@ +//! File-menu commands beyond New/Close: Close All / Others, Revert, Save a Copy, Open As, Place +//! Embedded / Linked, File Info, the Automate and Scripts items (Fit Image, Conditional Mode +//! Change, Batch, Image Processor, Load Files into Stack, Flatten All Layer Effects / Masks), +//! Export › Layers to Files and Color Lookup Tables, plus the document-level guide layouts of the +//! View menu (New Guide Layout, New Guides From Shape, Clear Canvas Guides). +//! +//! Commands that touch the file system take explicit paths (the UI asks for them with its own +//! pickers) and are unavailable on the web, where there is no file system; their byte-level +//! cores ([`place_bytes`], [`open_bytes_as`]) work everywhere. + +use std::sync::Arc; + +use photocraft_algo::resample::{Resample, resize_surface, translate_surface}; +use photocraft_color::{ColorMode, PixelFormat}; +use photocraft_doc::{Affine, Document, Layer, LayerContent, LayerId, SmartObject, SmartSource}; +use photocraft_geom::Rect; +use photocraft_raster::{Surface, from_rgba_into}; +use serde_json::{Value, json}; + +use crate::commands::{CommandSpec, layer_param}; +use crate::{EngineError, Result, Session}; + +mod batch_run; +mod export; +mod info; +mod open; +mod paths; +mod processing; +mod save; + +pub use batch_run::OutputClaims; +pub(crate) use batch_run::{BatchInput, batch_inputs, batch_keeps_step, batch_save_point, process_files}; +#[cfg(test)] +pub(crate) use batch_run::{MAX_SUBFOLDER_DEPTH, list_images_tree}; +use batch_run::{batch, same_format}; +pub use export::{LayerExportReport, SkippedExportLayer, bake_cube, export_layers_report_with, export_layers_with}; +use export::{color_lookup_tables, layers_to_files, push_unique}; +use info::file_info; +pub use info::{CAMERA_FIELDS, camera_data, read_file_info, write_file_info}; +#[cfg(test)] +use info::{exposure_text, find_element}; +pub use open::{PLACE_EMBEDDED, open_bytes_as, place_bytes, raw_defaults}; +use open::{close_all, close_others, open_as, place, revert}; +pub(crate) use open::{import, tag_exr_colorspace}; +use paths::is_file; +#[cfg(test)] +use paths::openable_name; +pub use paths::{extension, holds, holds_at, is_template, layered_extension, list_images, losses_at, same_file, saves_in_place, template_name, untitled_name}; +pub(crate) use paths::{file_name, forward_slashes, is_windows_device_name, join, portable_device_name, read_file, sanitize, stem, write_file}; +use processing::{conditional_mode_change, fit_image, flatten_all_effects, flatten_all_masks, image_processor, load_files_into_stack}; +use save::save_a_copy; +pub(crate) use save::{SaveOpts, encode, save_doc}; +pub use save::{dds_param, dpx_bits_param, jpeg_format_param, jpeg_quality, tga_bits_param, tiff_compression_param, tiff_would_write_layers}; + +mod batch_naming; + +// ---------- predicates ---------- + +fn has_doc(s: &Session) -> std::result::Result<(), String> { + s.active().map(|_| ()).ok_or_else(|| "no document open".into()) +} + +/// The file system is reachable (not on the web). +pub(crate) fn native(_: &Session) -> std::result::Result<(), String> { + if cfg!(target_arch = "wasm32") { Err("not available on the web (no file system)".into()) } else { Ok(()) } +} + +pub(crate) fn native_doc(s: &Session) -> std::result::Result<(), String> { + native(s)?; + has_doc(s) +} + +fn can_revert(s: &Session) -> std::result::Result<(), String> { + native(s)?; + let d = s.active().ok_or("no document open")?; + let path = d.path.as_deref().ok_or("the document has never been saved")?; + if !is_file(path) { + return Err(format!("{path} is not a file on disk")); + } + Ok(()) +} + +fn has_adjustments(s: &Session) -> std::result::Result<(), String> { + let d = s.active().ok_or("no document open")?; + if d.doc.layers.iter().any(|l| l.visible && matches!(l.content, LayerContent::Adjustment(_))) { + Ok(()) + } else { + Err("the document has no visible adjustment layers to export".into()) + } +} + +fn has_shape(s: &Session) -> std::result::Result<(), String> { + let d = s.active().ok_or("no document open")?; + match d.active_layer.and_then(|id| d.doc.layer(id)).map(|l| &l.content) { + Some(LayerContent::Shape(_)) => Ok(()), + _ => Err("the active layer is not a shape layer".into()), + } +} + +impl crate::DocState { + /// Complete a successful document save. File identity is not a history step; callers must + /// finish the write first and must not call this for a copy or export. + pub fn saved_to(&mut self, path: String) { + let name = file_name(&path); + if self.doc.name != name { + Arc::make_mut(&mut self.doc).name = name; + } + self.path = Some(path); + self.saved_revision = self.revision; + } +} + +pub(crate) fn str_param<'a>(p: &'a Value, key: &str, cmd: &str) -> Result<&'a str> { + p.get(key).and_then(Value::as_str).filter(|v| !v.is_empty()).ok_or_else(|| EngineError::BadParams { cmd: cmd.into(), msg: format!("missing \"{key}\"") }) +} + +pub(crate) fn f64_param(p: &Value, key: &str) -> Option { + p.get(key).and_then(Value::as_f64).filter(|v| v.is_finite()) +} + +/// A size parameter; zero or negative means "not set" (dialogs send 0 for empty fields). +fn size_param(p: &Value, key: &str) -> Option { + f64_param(p, key).filter(|v| *v > 0.0) +} + +// ---------- pixels ---------- + +/// A composite buffer as a surface in `fmt` (straight RGBA → the format's model and depth). +pub(crate) fn buffer_surface(buf: &photocraft_compose::Buffer, fmt: PixelFormat) -> Surface { + let n = fmt.channels(); + let mut data = vec![0.0f32; buf.px.len() * n]; + for (p, out) in buf.px.iter().zip(data.chunks_exact_mut(n)) { + from_rgba_into(&fmt, *p, out); + } + let mut s = Surface::new(fmt); + if !buf.rect.is_empty() { + s.write_region(buf.rect, &data); + } + s.prune(); + s +} + +/// The flattened image of `doc` as a surface in `fmt`, placed at the origin. +pub(crate) fn flattened(doc: &Document, fmt: PixelFormat) -> Surface { + photocraft_compose::flatten_to_surface(doc, fmt, None) +} + +/// [`flattened`] for documents that came from a file (Save a Copy, Place, Load Files into Stack): +/// a sparse bundle declares its canvas, and one the size of the format allows would be rendered +/// in full, however little it holds. Refused past the compositor's own per-render limit. +pub(crate) fn flattened_checked(doc: &Document, fmt: PixelFormat, cmd: &str) -> Result { + let b = doc.bounds(); + if u64::from(b.width()) * u64::from(b.height()) > photocraft_compose::MAX_RENDER_PIXELS { + return Err(EngineError::BadParams { cmd: cmd.into(), msg: format!("the document's {}×{} canvas is too large to flatten", b.width(), b.height()) }); + } + Ok(flattened(doc, fmt)) +} + +fn new_guide_layout(s: &mut Session, p: &Value) -> Result { + crate::guide_layout::apply(s, p) +} + +fn guides_from_shape(s: &mut Session, p: &Value) -> Result { + let id = layer_param(s, p)?; + let d = s.active().ok_or(EngineError::NoDocument)?; + let l = d.doc.layer(id).ok_or(EngineError::NoLayer(id))?; + let LayerContent::Shape(sh) = &l.content else { return Err(EngineError::Other("the layer is not a shape layer".into())) }; + let (x0, y0, x1, y1) = sh.path.control_bounds().ok_or(EngineError::Other("the shape has no path".into()))?; + s.edit("New Guides From Shape", |doc, _| { + for x in [x0, (x0 + x1) / 2.0, x1] { + push_unique(&mut doc.guides.vertical, x); + } + for y in [y0, (y0 + y1) / 2.0, y1] { + push_unique(&mut doc.guides.horizontal, y); + } + Ok(()) + })?; + Ok(json!({"bounds": [x0, y0, x1, y1]})) +} + +fn clear_canvas_guides(s: &mut Session) -> Result { + let d = s.active().ok_or(EngineError::NoDocument)?; + // Guides inside an artboard belong to it (View › Clear Selected Artboard Guides); the rest + // are canvas guides. Without artboards every guide is a canvas guide. + let boards: Vec = d.doc.artboards().iter().map(|b| b.2.rect).collect(); + let in_x = move |x: f64| boards.iter().any(|r| x > f64::from(r.x0) && x < f64::from(r.x1)); + let boards_y: Vec = d.doc.artboards().iter().map(|b| b.2.rect).collect(); + let in_y = move |y: f64| boards_y.iter().any(|r| y > f64::from(r.y0) && y < f64::from(r.y1)); + let n = d.doc.guides.vertical.iter().filter(|x| !in_x(**x)).count() + d.doc.guides.horizontal.iter().filter(|y| !in_y(**y)).count(); + if n == 0 { + return Ok(json!({"cleared": 0})); + } + s.edit("Clear Canvas Guides", |doc, _| { + doc.guides.vertical.retain(|x| in_x(*x)); + doc.guides.horizontal.retain(|y| in_y(*y)); + doc.guides.prune_colors(); + Ok(()) + })?; + Ok(json!({"cleared": n})) +} + +// ---------- registry ---------- + +pub fn specs() -> Vec { + macro_rules! spec { + ($id:expr, $label:expr, $menu:expr, $sc:expr, $params:expr, $enabled:expr, $run:expr) => { + CommandSpec { id: $id, label: $label, menu: $menu, shortcut: $sc, params: $params, enabled: $enabled, journal: true, run: $run } + }; + } + vec![ + spec!("file.closeAll", "Close All", &["File"], Some("Cmd+Alt+W"), "{}", has_doc, |s, _| close_all(s)), + spec!( + "file.closeOthers", + "Close Others", + &["File"], + Some("Cmd+Alt+P"), + r##"{"document":index? (the one to keep; default active)}"##, + has_doc, + close_others + ), + // The document tab's menu (UI-217-6): the tab's own file in the platform file manager. + // Not a Photoshop menu-bar item; enabled when the target document has a saved path. + spec!("file.revealInFinder", "Reveal in Finder", &[], None, r##"{"document":index? (default active),"dryRun":bool=false}"##, native_doc, |s, p| { + let i = match p.get("document") { + Some(v) => v + .as_u64() + .and_then(|v| usize::try_from(v).ok()) + .ok_or_else(|| EngineError::BadParams { cmd: "file.revealInFinder".into(), msg: "`document` must be an index".into() })?, + None => s.active_index().ok_or(EngineError::NoDocument)?, + }; + let path = s + .documents() + .get(i) + .and_then(|d| d.path.clone()) + .ok_or_else(|| EngineError::BadParams { cmd: "file.revealInFinder".into(), msg: format!("document {i} has no saved file") })?; + crate::layer_menu_cmds::reveal(&path, p.get("dryRun").and_then(Value::as_bool).unwrap_or(false)) + }), + spec!("file.revert", "Revert", &["File"], Some("F12"), "{} (reloads the saved file as one undoable step)", can_revert, |s, _| revert(s)), + spec!( + "file.saveACopy", + "Save a Copy…", + &["File"], + Some("Cmd+Alt+S"), + r##"{"path":str (format from the extension),"quality":0..12? (JPEG),"jpegFormat":"baseline|optimized|progressive"? (JPEG; default baseline),"layers":bool=true,"overwrite":bool=false (replace the document's own file),"tiffLayers":bool=false (TIFF: keep the layers; flat by default),"tiffCompression":"none|lzw|zip"? (TIFF: image compression; unset, none),"tgaBits":24|32? (TGA: 32 writes the alpha channel, or else the transparency, as the alpha; unset, 32 with an alpha channel or transparency, else 24),"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain)}"##, + native_doc, + save_a_copy + ), + spec!( + "file.openAs", + "Open As…", + &["File"], + Some("Cmd+Alt+Shift+O"), + r##"{"path":str,"as":"psd|png|jpg|tiff|…"? (decode as this format)}"##, + native, + open_as + ), + spec!( + "file.placeEmbedded", + "Place Embedded…", + &["File"], + None, + r##"{"path":str,"scale":%? (default: fit when larger than the canvas),"fit":bool? (default: Preferences > General > Resize Image During Place),"smartObject":bool? (default: Preferences > General > Always Create Smart Objects When Placing),"center":[x,y]?}"##, + native_doc, + |s, p| place(s, p, false) + ), + spec!( + "file.placeLinked", + "Place Linked…", + &["File"], + None, + r##"{"path":str,"scale":%?,"fit":bool? (default: Preferences > General > Resize Image During Place),"center":[x,y]?}"##, + native_doc, + |s, p| place(s, p, true) + ), + spec!( + "file.fileInfo", + "File Info…", + &["File"], + Some("Cmd+Alt+Shift+I"), + r##"{"title":str?,"author":str?,"authorTitle":str?,"description":str?,"keywords":[str]|"a; b"?,"copyright":str?,"copyrightStatus":"unknown|copyrighted|publicDomain"?,"copyrightUrl":str?} (no keys: read; the result also has read-only "camera":{"make","model","dateTaken","exposure","fNumber","iso","focalLength","focalLength35mm","lens"}, present keys only)"##, + has_doc, + file_info + ), + spec!( + "file.automate.fitImage", + "Fit Image…", + &["File", "Automate"], + None, + r##"{"width":px,"height":px,"dontEnlarge":bool=false,"resample":"automatic|preserveDetails|bicubicSmoother|bicubicSharper|bicubicAutomatic|bicubic|nearest|bilinear|lanczos"="bicubic"}"##, + has_doc, + fit_image + ), + spec!( + "file.automate.conditionalModeChange", + "Conditional Mode Change…", + &["File", "Automate"], + None, + r##"{"from":["rgb","grayscale","cmyk","lab","indexed","bitmap",…]|"any"="any","to":"rgb|grayscale|cmyk|lab"}"##, + has_doc, + conditional_mode_change + ), + spec!( + "file.automate.batch", + "Batch…", + &["File", "Automate"], + None, + r##"{"steps":[[commandId,params]|{"command":id,"params":{}}…] (a recorded action; a Save, Save As or Save a Copy step marks the document written to output, in this command's format and options: as the save found it if it was closed or another document is active at the end, else as the action leaves it; with no such step, the active document at the end),"input":folder|[paths],"includeSubfolders":bool=false (a folder input also takes the images in its subfolders, up to 32 levels and 100000 files; each result keeps its subfolder under output),"output":folder,"format":"same|png|jpg|psd|tiff|…"="same","quality":0..12?,"jpegFormat":"baseline|optimized|progressive"?,"naming":string? (blank keeps source names; {name}, {serial} padded to 3 digits, {date} as YYYY-MM-DD UTC; extension added automatically),"startingSerial":1..4294967295=1 (input position, including failed inputs),"tiffLayers":bool=false,"tiffCompression":"none|lzw|zip"?,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"calledActions":[{"name","steps"}…]? (the actions Play Action steps call; default: the session's)} → {files, errors} (an input whose output name was already written in the run goes to errors)"##, + native, + batch + ), + spec!( + "file.scripts.imageProcessor", + "Image Processor…", + &["File", "Scripts"], + None, + r##"{"input":folder|[paths],"includeSubfolders":bool=false (a folder input also takes the images in its subfolders, up to 32 levels and 100000 files; each result keeps its subfolder under output),"output":folder,"format":"jpg|png|psd|tiff|…"="jpg","quality":0..12=8,"jpegFormat":"baseline|optimized|progressive"?,"tiffLayers":bool=false,"tiffCompression":"none|lzw|zip"?,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"width":px?,"height":px? (fit, never enlarge),"convertToSrgb":bool=false} → {files, errors} (an input whose output name was already written in the run goes to errors)"##, + native, + image_processor + ), + spec!( + "file.scripts.loadFilesIntoStack", + "Load Files into Stack…", + &["File", "Scripts"], + None, + r##"{"paths":[str]|folder,"align":bool=false (Auto-Align Layers on them first),"createSmartObject":bool=false} → new document with one layer per file (inside one smart object with createSmartObject)"##, + native, + load_files_into_stack + ), + spec!("file.scripts.flattenAllLayerEffects", "Flatten All Layer Effects", &["File", "Scripts"], None, "{}", has_doc, |s, _| flatten_all_effects(s)), + spec!( + "file.scripts.flattenAllMasks", + "Flatten All Masks", + &["File", "Scripts"], + None, + "{} (pixel layers; masks on other layer kinds are left)", + has_doc, + |s, _| flatten_all_masks(s) + ), + spec!( + "file.export.layersToFiles", + "Layers to Files…", + &["File", "Export"], + None, + r##"{"dir":folder,"format":"png|jpg|psd|tiff|…"="png","prefix":str=document name,"visibleOnly":bool=true,"quality":0..12?,"jpegFormat":"baseline|optimized|progressive"?,"tiffLayers":bool=false,"tiffCompression":"none|lzw|zip"?,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain)} → {files}"##, + native_doc, + layers_to_files + ), + spec!( + "file.export.colorLookupTables", + "Color Lookup Tables…", + &["File", "Export"], + None, + r##"{"path":str? (.cube; omit to return the text),"size":2..129=33,"title":str?,"scope":"all|selected"="all","layers":[id,…]?} (selected layer IDs use original document stacking; masks are spatial and omitted)"##, + has_adjustments, + color_lookup_tables + ), + spec!( + "view.newGuideLayout", + "New Guide Layout…", + &["View"], + None, + r##"{"columns":n=0,"width":len?,"gutter":len=0,"rows":n=0,"height":len?,"rowGutter":len=gutter,"margin":len|[top,left,bottom,right]=0,"centerColumns":bool=false,"clearExisting":bool=false,"target":"document|selectedArtboards"="document"} (len: pixels, or text with px, in, cm, mm, pt, pc or % as typed in Photoshop, e.g. "1 cm"; % is of the target's width for columns, gutters and left/right margins, its height for rows and top/bottom margins)"##, + has_doc, + new_guide_layout + ), + spec!("view.newGuidesFromShape", "New Guides From Shape", &["View"], None, r##"{"layer":id?}"##, has_shape, guides_from_shape), + spec!("view.clearCanvasGuides", "Clear Canvas Guides", &["View"], None, "{}", has_doc, |s, _| clear_canvas_guides(s)), + ] +} + +#[cfg(test)] +#[path = "file_cmds/tests.rs"] +mod tests; + +#[cfg(test)] +mod aces_exr_tests { + use super::*; + + /// File Handling › "Open color-less EXR as ACEScg": off, an EXR opens on io's linear-sRGB + /// default; on, it opens as ACEScg — the working space ACES render pipelines write. + #[test] + fn exr_aces_cg_preference_retags_the_opened_document() { + let image = photocraft_codecs::Image::from_f32( + 4, + 4, + photocraft_codecs::ChannelLayout::Rgb, + &[ + 0.25, 0.5, 0.75, 1.0, 0.25, 0.5, 0.75, 1.0, 0.25, 0.5, 0.75, 1.0, 0.25, 0.5, 0.75, 1.0, 0.25, 0.5, 0.75, 1.0, 0.25, 0.5, 0.75, 1.0, 0.25, 0.5, + 0.75, 1.0, 0.25, 0.5, 0.75, 1.0, 0.25, 0.5, 0.75, 1.0, 0.25, 0.5, 0.75, 1.0, 0.25, 0.5, 0.75, 1.0, 0.25, 0.5, 0.75, 1.0, + ], + ) + .unwrap(); + let bytes = photocraft_codecs::encode(&image, photocraft_codecs::Format::OpenExr, &photocraft_codecs::EncodeOptions::default()).unwrap(); + + let linear = photocraft_cms::Builtin::LinearSrgb.profile().to_bytes(); + let aces = photocraft_cms::Builtin::AcesCg.profile().to_bytes(); + + // Off (the default): io's linear-sRGB tagging stays. + let mut s = Session::new(); + open_bytes_as(&mut s, "shot.exr", &bytes, None, None).unwrap(); + let d = &s.active().unwrap().doc; + assert_eq!(d.icc_profile.as_deref().map(|v| v.as_slice()), Some(linear.as_slice())); + + // On: the same file opens as ACEScg. + let mut s = Session::new(); + s.prefs.edit(|p| p.file_handling.exr_aces_cg = true); + open_bytes_as(&mut s, "shot.exr", &bytes, None, None).unwrap(); + let d = &s.active().unwrap().doc; + assert_eq!(d.icc_profile.as_deref().map(|v| v.as_slice()), Some(aces.as_slice())); + } + + /// The desktop app opens files as background jobs (File > Open, drag-drop, Open Recent): + /// the ACEScg preference applies there too, not only to `file.openAs`. + #[test] + fn exr_aces_cg_preference_applies_to_background_opens() { + use crate::jobs::{OpenSource, Started}; + let image = photocraft_codecs::Image::from_f32(4, 4, photocraft_codecs::ChannelLayout::Rgb, &[0.5; 48]).unwrap(); + let bytes = + std::sync::Arc::new(photocraft_codecs::encode(&image, photocraft_codecs::Format::OpenExr, &photocraft_codecs::EncodeOptions::default()).unwrap()); + let linear = photocraft_cms::Builtin::LinearSrgb.profile().to_bytes(); + let aces = photocraft_cms::Builtin::AcesCg.profile().to_bytes(); + for (on, want) in [(false, &linear), (true, &aces)] { + let mut s = Session::new(); + s.prefs.edit(|p| p.file_handling.exr_aces_cg = on); + let v = match s.start_open("shot.exr", OpenSource::Bytes(std::sync::Arc::clone(&bytes))).unwrap() { + Started::Job(id) => s.wait_job(id).unwrap(), + Started::Done(v) => v, + }; + // ACEScg isn't the working space, so Ask When Opening holds it for the prompt, which + // names the ACEScg profile; linear sRGB (io's HDR default) opens without asking. + let profile = match v.get("held").and_then(Value::as_u64) { + Some(held) => { + assert!(on, "{v}"); + assert!(v["color"]["embedded"].as_str().unwrap().starts_with("ACEScg"), "{v}"); + s.take_held_open(held).unwrap().0.icc_profile + } + None => { + assert!(v.get("document").is_some(), "{v}"); + s.active().unwrap().doc.icc_profile.clone() + } + }; + assert_eq!(profile.as_deref().map(|v| v.as_slice()), Some(want.as_slice()), "exr_aces_cg = {on}"); + } + } +} diff --git a/crates/engine/src/file_cmds/batch_naming.rs b/crates/engine/src/cmd/file_cmds/batch_naming.rs similarity index 100% rename from crates/engine/src/file_cmds/batch_naming.rs rename to crates/engine/src/cmd/file_cmds/batch_naming.rs diff --git a/crates/engine/src/cmd/file_cmds/batch_run.rs b/crates/engine/src/cmd/file_cmds/batch_run.rs new file mode 100644 index 0000000000..24685387f0 --- /dev/null +++ b/crates/engine/src/cmd/file_cmds/batch_run.rs @@ -0,0 +1,326 @@ +use super::open::import_at_raw_ppi; +use super::paths::{extension, file_name, join, list_images, read_file, stem}; +use super::processing::parse_steps; +use super::save::{SaveOpts, save_doc}; +use super::*; + +/// Inputs of a batch command: `"input"` is a folder or an array of files. +pub(crate) fn batch_inputs(p: &Value, cmd: &str) -> Result> { + match p.get("input").or_else(|| p.get("files")) { + Some(Value::Array(a)) => Ok(a.iter().filter_map(Value::as_str).map(str::to_string).collect()), + Some(Value::String(dir)) => list_images(dir), + _ => Err(EngineError::BadParams { cmd: cmd.into(), msg: "missing \"input\" (folder or array of files)".into() }), + } +} + +/// One input of a batch run: the file, and the folder it sits in relative to the input folder +/// (`""` at the top level, `"a/b"` two levels down), which its result keeps under `output`. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct BatchInput { + pub path: String, + pub rel_dir: String, +} + +/// Subfolders below a batch input folder are walked at most this deep ("Include All Subfolders"). +pub(crate) const MAX_SUBFOLDER_DEPTH: usize = 32; + +/// A batch over subfolders lists at most this many files; a larger tree is an error, not a run +/// that silently stops partway. +pub(crate) const MAX_SUBFOLDER_FILES: usize = 100_000; + +/// [`batch_inputs`] for the commands whose Photoshop dialog has "Include All Subfolders" (Batch, +/// Image Processor): with `"includeSubfolders": true` a folder input also yields the images in its +/// subfolders, each tagged with its relative folder. `output` (when inside the input folder, as +/// the dialog's default `/batch` is) is not walked, so a rerun doesn't process its results. +pub(crate) fn batch_inputs_tree(p: &Value, cmd: &str, output: &str) -> Result> { + let recurse = match p.get("includeSubfolders") { + None | Some(Value::Null) => false, + Some(Value::Bool(b)) => *b, + Some(_) => return Err(EngineError::BadParams { cmd: cmd.into(), msg: "\"includeSubfolders\" must be true or false".into() }), + }; + match p.get("input").or_else(|| p.get("files")) { + Some(Value::String(dir)) if recurse => list_images_tree(dir, output, cmd), + _ => Ok(batch_inputs(p, cmd)?.into_iter().map(|path| BatchInput { path, rel_dir: String::new() }).collect()), + } +} + +/// The images under `dir` and its subfolders: each folder's files sorted by name, then its +/// subfolders in name order (depth first). Bounded by [`MAX_SUBFOLDER_DEPTH`] and +/// [`MAX_SUBFOLDER_FILES`]; a folder reached twice (a symlink loop) is walked once, and `skip` +/// (the output folder) is left out. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn list_images_tree(dir: &str, skip: &str, cmd: &str) -> Result> { + use std::path::{Path, PathBuf}; + let canon = |p: &Path| std::fs::canonicalize(p).ok(); + let root = Path::new(dir); + let root_canon = canon(root).ok_or_else(|| EngineError::Other(format!("{dir}: cannot open the folder")))?; + let skip = if skip.is_empty() { None } else { canon(Path::new(skip)) }; + let mut seen = std::collections::HashSet::new(); + seen.insert(root_canon); + let mut out = Vec::new(); + // Depth first with an explicit stack (no recursion): (folder, relative folder, depth). + let mut stack: Vec<(PathBuf, String, usize)> = vec![(root.to_path_buf(), String::new(), 0)]; + while let Some((folder, rel, depth)) = stack.pop() { + let shown = folder.to_string_lossy().into_owned(); + // The top folder must be readable; a subfolder that isn't is skipped. + let files = match list_images(&shown) { + Ok(f) => f, + Err(e) if depth == 0 => return Err(e), + Err(_) => continue, + }; + if out.len().saturating_add(files.len()) > MAX_SUBFOLDER_FILES { + return Err(EngineError::BadParams { cmd: cmd.into(), msg: format!("{dir} holds more than {MAX_SUBFOLDER_FILES} images with its subfolders") }); + } + out.extend(files.into_iter().map(|path| BatchInput { path, rel_dir: rel.clone() })); + if depth >= MAX_SUBFOLDER_DEPTH { + continue; + } + let Ok(rd) = std::fs::read_dir(&folder) else { continue }; + let mut subs: Vec<(String, PathBuf)> = rd + .filter_map(|e| e.ok()) + .map(|e| e.path()) + .filter(|p| p.is_dir()) + .filter_map(|p| Some((p.file_name()?.to_string_lossy().into_owned(), p))) + .collect(); + subs.sort(); + // Pushed in reverse so the stack pops them in name order. + for (name, sub) in subs.into_iter().rev() { + let Some(c) = canon(&sub) else { continue }; + if skip.as_ref() == Some(&c) || !seen.insert(c) { + continue; + } + let rel = if rel.is_empty() { name } else { format!("{rel}/{name}") }; + stack.push((sub, rel, depth + 1)); + } + } + Ok(out) +} + +#[cfg(target_arch = "wasm32")] +pub(crate) fn list_images_tree(dir: &str, _skip: &str, _cmd: &str) -> Result> { + Err(EngineError::Other(format!("cannot list {dir}: no file system on the web"))) +} + +/// Opens each input in a scratch session, runs `f` on it and saves it to `output` as `format` +/// (`"same"` keeps the input's extension). Errors per file are collected, not fatal. +pub(crate) fn process_files( + s: &Session, + inputs: &[String], + output: &str, + format: &str, + save: SaveOpts, + suffix: &str, + f: &dyn Fn(&mut Session) -> Result<()>, +) -> Value { + let inputs: Vec = inputs.iter().map(|path| BatchInput { path: path.clone(), rel_dir: String::new() }).collect(); + process_tree(s, &inputs, output, format, save, suffix, &|scratch, _| f(scratch).map(|()| false)) +} + +/// [`process_files`] for inputs from subfolders: each result goes to its input's relative folder +/// under `output` (created as needed), so `a/x.png` and `b/x.png` don't collide. `f` gets the +/// output path and returns `true` when it wrote the result there itself (Batch writes what a +/// recorded save marked); otherwise the active document is saved after it. +pub(crate) fn process_tree( + s: &Session, + inputs: &[BatchInput], + output: &str, + format: &str, + save: SaveOpts, + suffix: &str, + f: &dyn Fn(&mut Session, &str) -> Result, +) -> Value { + let outputs = inputs.iter().map(|BatchInput { path, rel_dir }| { + let ext = if format == "same" { same_format(path) } else { format.trim_start_matches('.').to_ascii_lowercase() }; + (path.as_str(), join(&join(output, rel_dir), &format!("{}{suffix}.{ext}", stem(path)))) + }); + process_outputs(s, outputs, save, f) +} + +/// The extension a batch output takes with Format "Same": the input's own, except for formats +/// PhotoCraft opens but can't write, camera raws above all (#5799: a folder of ARWs failed on +/// every file). Those are saved as PSD, the format Photoshop's Save As offers for a raw. An input +/// whose file name has no extension (a dot in a folder name doesn't count) is saved as PNG. +pub(super) fn same_format(path: &str) -> String { + const IMPORT_ONLY: &[&str] = &["pdn", "kra", "krz", "af", "afdesign", "afphoto", "afpub", "heic", "heif", "hif", "svg", "svgz", "cin", "pcx", "xpm"]; + let ext = extension(path).unwrap_or_else(|| "png".into()); + if photocraft_io::raw::EXTENSIONS.contains(&ext.as_str()) || IMPORT_ONLY.contains(&ext.as_str()) { "psd".into() } else { ext } +} + +#[cfg(test)] +#[test] +fn same_format_takes_the_file_names_extension() { + assert_eq!(same_format("/in/a.PNG"), "png"); + assert_eq!(same_format("/in/IMG_0001.ARW"), "psd"); + assert_eq!(same_format("/in/a.kra"), "psd"); + assert_eq!(same_format("/in/IMG_0001.HEIC"), "psd"); + assert_eq!(same_format("/in/logo.svg"), "psd"); + assert_eq!(same_format("/in/scan.cin"), "psd"); + // No extension in the file name: PNG, not the path after a dot in a folder name. + assert_eq!(same_format("/in/v1.2/scan"), "png"); + assert_eq!(same_format("C:\\in.d\\scan"), "png"); + assert_eq!(same_format("/in/.hidden"), "png"); +} + +fn process_outputs<'a>( + s: &Session, + outputs: impl IntoIterator, + save: SaveOpts, + f: &dyn Fn(&mut Session, &str) -> Result, +) -> Value { + // The scratch sessions have default preferences; a raw opens at the user's Raw Defaults. + let raw_ppi = s.prefs().raw_defaults.resolution; + let mut files = Vec::new(); + let mut errors = Vec::new(); + let mut written = OutputClaims::default(); + for (path, out) in outputs { + let r = (|| -> Result<()> { + written.check(&out).map_err(EngineError::Other)?; + let bytes = read_file(path)?; + let mut scratch = Session::new(); + let doc = import_at_raw_ppi(raw_ppi, &file_name(path), &bytes)?; + scratch.add_document(doc, Some(path.to_string())); + if !f(&mut scratch, &out)? { + let d = scratch.active().ok_or(EngineError::NoDocument)?; + save_doc(&d.doc, &out, save)?; + } + Ok(()) + })(); + match r { + Ok(()) => { + written.record(&out, path); + files.push(out); + } + Err(e) => errors.push(json!({"file": path, "error": e.to_string()})), + } + } + json!({"files": files, "errors": errors}) +} + +/// The output paths a batch run has written, so a later input whose output name matches an +/// earlier one's (`a.png` and `a.jpg` saved as JPEG, or the same name in two input folders) is +/// reported instead of silently replacing that result (#420, #422). Names are compared ignoring +/// case, because macOS and Windows file systems do. +#[derive(Default)] +pub struct OutputClaims(pub(super) std::collections::HashMap); + +impl OutputClaims { + /// `Err` (naming the earlier input) when `out` was already written in this run. + pub fn check(&self, out: &str) -> std::result::Result<(), String> { + match self.0.get(&out.to_lowercase()) { + Some(first) => Err(format!("not written: {out} already holds the result of {first} from this run (same output name)")), + None => Ok(()), + } + } + /// Remember that `input`'s result was written to `out`. + pub fn record(&mut self, out: &str, input: &str) { + self.0.insert(out.to_lowercase(), input.to_string()); + } +} + +/// A recorded Save, Save As or Save a Copy, which marks the result Batch writes to its destination +/// (Photoshop's "Override Action 'Save As' Commands"). +pub(crate) fn batch_save_point(id: &str) -> bool { + matches!(id, "file.save" | "file.saveAs" | "file.saveACopy") +} + +/// Whether Batch and droplets keep a recorded step: save points mark the result, while other +/// shell-only saves and view steps (zoom, fit) don't change the output (#2752). +pub(crate) fn batch_keeps_step(id: &str) -> bool { + (batch_save_point(id) || !crate::actions_cmds::shell_save_command(id)) && !crate::actions_cmds::shell_view_command(id) +} + +pub(super) fn batch(s: &mut Session, p: &Value) -> Result { + let cmd = "file.automate.batch"; + let mut steps = + parse_steps(p.get("steps").or_else(|| p.get("action")).ok_or_else(|| EngineError::BadParams { cmd: cmd.into(), msg: "missing \"steps\"".into() })?)?; + // Each result goes to the destination folder, which overrides the action's recorded Save / + // Save As steps: they only mark the result. + steps.retain(|(id, _)| batch_keeps_step(id) && id != "file.export.quickExport"); + if let Some((id, _)) = steps.iter().find(|(id, _)| !batch_save_point(id) && crate::commands::find(id).is_none()) { + return Err(EngineError::BadParams { cmd: cmd.into(), msg: format!("unknown command `{id}` in the action") }); + } + let output = str_param(p, "output", cmd)?.to_string(); + let inputs = batch_inputs_tree(p, cmd, &output)?; + let format = p.get("format").and_then(Value::as_str).unwrap_or("same").to_string(); + // Steps that call another action play it from the caller's actions; the playback stack comes + // along so an action that batches itself is caught as a recursive call. + let list = match p.get("calledActions") { + None | Some(Value::Null) => s.actions.list.clone(), + // A droplet brings the actions it calls (#2794) and runs with those alone. + Some(v) => { + let list: Vec = + serde_json::from_value(v.clone()).map_err(|e| EngineError::BadParams { cmd: cmd.into(), msg: format!("\"calledActions\": {e}") })?; + if list.len() > 4096 { + return Err(EngineError::BadParams { cmd: cmd.into(), msg: "\"calledActions\" holds more than 4096 actions".into() }); + } + list + } + }; + // A batch inside a played action charges its inputs × steps (at least one each: an input is read, + // decoded and saved even with no steps) to the playback tree it is in and + // hands the count on, so a batch of batches can't multiply past the limit. A top-level batch + // is not limited by it. + let mut playback_steps = 0; + if s.actions.playing > 0 { + playback_steps = s.actions.playback_steps.saturating_add((steps.len().max(1) as u64).saturating_mul(inputs.len() as u64)); + if playback_steps > crate::actions_cmds::MAX_PLAYBACK_STEPS { + return Err(EngineError::BadParams { cmd: cmd.into(), msg: "this batch would exceed the playback step limit of the action that runs it".into() }); + } + s.actions.playback_steps = playback_steps; + } + let actions = crate::actions_cmds::ActionState { + list, + playing: s.actions.playing, + playback_stack: s.actions.playback_stack.clone(), + playback_steps, + ..Default::default() + }; + let names = batch_naming::plan(&inputs, &output, &format, p)?; + let save = SaveOpts::from_params(s, p, cmd)?; + let authorize = s.authorize; + // Each input runs in its own scratch session, so what the played steps spend is carried from + // one input to the next (failed or not) and back to this session, not restarted per input. + let carried = std::cell::Cell::new(playback_steps); + let carried = &carried; + let run = move |scratch: &mut Session, out: &str| { + scratch.authorize = authorize; + scratch.actions = actions.clone(); + scratch.actions.playback_steps = carried.get(); + let result = (|| { + // The document as the last recorded save found it, written once the action has run so a + // failing step still writes nothing. + let mut saved: Option> = None; + for (id, params) in &steps { + if batch_save_point(id) { + saved = Some(scratch.active().ok_or(EngineError::NoDocument)?.doc.clone()); + continue; + } + let r = scratch.execute(id, params.clone())?; + // A failed step inside a called action makes this file an error, not a saved result. + if let Some(error) = crate::actions_cmds::nested_failure(id, &r) { + return Err(EngineError::Other(error)); + } + } + // While the saved document is still open the steps after the save reach the result too + // (#3058), so it is saved after the action as usual. Closed after its save, or with another + // document left active, it is written as the save found it. + match saved { + Some(doc) if scratch.active().is_none_or(|d| d.doc.id != doc.id) => { + save_doc(&doc, out, save)?; + Ok(true) + } + _ => Ok(false), + } + })(); + carried.set(scratch.actions.playback_steps); + result + }; + let r = match names { + Some(names) => process_outputs(s, inputs.iter().map(|i| i.path.as_str()).zip(names), save, &run), + None => process_tree(s, &inputs, &output, &format, save, "", &run), + }; + if s.actions.playing > 0 { + s.actions.playback_steps = carried.get(); + } + Ok(r) +} diff --git a/crates/engine/src/cmd/file_cmds/export.rs b/crates/engine/src/cmd/file_cmds/export.rs new file mode 100644 index 0000000000..ef6ad0e056 --- /dev/null +++ b/crates/engine/src/cmd/file_cmds/export.rs @@ -0,0 +1,231 @@ +use super::paths::{join, sanitize, stem, write_file}; +use super::save::{SaveOpts, encode}; +use super::*; + +// ---------- Export ---------- + +pub(super) fn layers_to_files(s: &mut Session, p: &Value) -> Result { + let cmd = "file.export.layersToFiles"; + let dir = str_param(p, "dir", cmd).or_else(|_| str_param(p, "output", cmd))?.to_string(); + let report = export_layers_report_with(s, p, |name, bytes| write_file(&join(&dir, name), bytes))?; + let files: Vec = report.files.iter().map(|name| join(&dir, name)).collect(); + Ok(json!({"files": files, "skipped": report.skipped})) +} + +/// The bodies of `file.export.layersToFiles`, streamed to `write` as a single-component filename +/// plus its bytes: one file per exported layer (top to bottom, like Photoshop's numbering), +/// encoded but never touched as a path. Automation writes exactly these bytes beneath its write +/// root (#3216), so the two paths cannot drift. Returns the filenames written, in order. +pub fn export_layers_with(s: &Session, p: &Value, write: impl FnMut(&str, &[u8]) -> Result<()>) -> Result> { + export_layers_report_with(s, p, write).map(|report| report.files) +} + +/// A top-level layer omitted from a successful Layers to Files export. +#[derive(Debug, serde::Serialize)] +pub struct SkippedExportLayer { + /// Session layer id (names need not be unique). + pub layer: u64, + /// Original name, not the sanitized filename component. + pub name: String, + /// Why the layer produced no file. + pub reason: &'static str, +} + +/// Filenames written and layers skipped, each in top-to-bottom order. +#[derive(Debug, Default)] +pub struct LayerExportReport { + pub files: Vec, + pub skipped: Vec, +} + +/// The same export as [`export_layers_with`], with an explanation for every omitted top-level +/// layer. Groups export merged, so their children are not separate exports or skips. Encoding +/// and write failures remain errors, never successful skips. Existing numbering is preserved. +pub fn export_layers_report_with(s: &Session, p: &Value, mut write: impl FnMut(&str, &[u8]) -> Result<()>) -> Result { + let cmd = "file.export.layersToFiles"; + let format = p.get("format").and_then(Value::as_str).unwrap_or("png").trim_start_matches('.').to_ascii_lowercase(); + let visible_only = p.get("visibleOnly").and_then(Value::as_bool).unwrap_or(true); + // Callers outside `Session::execute` (headless workspace exports) carry the session's gate + // into `encode`, so a PSD embeds no file a linked smart object names. + let _authorization = crate::jobs::render_authorization_scope(s.authorize); + let save = SaveOpts::from_params(s, p, cmd)?; + let d = s.active().ok_or(EngineError::NoDocument)?; + let prefix = p.get("prefix").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| stem(&d.doc.name)); + let doc = d.doc.clone(); + let mut report = LayerExportReport::default(); + // Hidden layers never consumed a filename index; adjustments that pass the visibility + // filter did. Keep those filenames stable while reporting both kinds of omission. + let mut i = 0usize; + for l in doc.layers.iter().rev() { + if !l.visible && visible_only { + report.skipped.push(SkippedExportLayer { layer: l.id.0, name: l.name.clone(), reason: "hidden by visibleOnly" }); + continue; + } + let index = i; + i += 1; + if matches!(l.content, LayerContent::Adjustment(_)) { + report.skipped.push(SkippedExportLayer { layer: l.id.0, name: l.name.clone(), reason: "adjustment layer has no pixels of its own" }); + continue; + } + let mut one = (*doc).clone(); + let mut only = l.clone(); + only.visible = true; + only.clipped = false; + one.layers = vec![only]; + let name = format!("{}_{:04}_{}.{format}", sanitize(&prefix), index, sanitize(&l.name)); + let (bytes, _warnings) = encode(&one, &name, save)?; + write(&name, &bytes)?; + report.files.push(name); + } + Ok(report) +} + +/// Adjustment layers that can be represented as an RGB-only LUT, in document stack order. +/// A LUT has no spatial coordinates, so masks and clipping geometry are deliberately stripped +/// at bake time. Group adjustments need their enclosing group's compositing semantics and are +/// not silently flattened as independent layers. +fn lut_layers<'a>(doc: &'a Document, ids: Option<&[LayerId]>) -> Result> { + const CMD: &str = "file.export.colorLookupTables"; + let mut selected = Vec::new(); + if let Some(ids) = ids { + if ids.is_empty() { + return Err(EngineError::BadParams { cmd: CMD.into(), msg: "select at least one adjustment layer".into() }); + } + for id in ids { + if selected.contains(id) { + return Err(EngineError::BadParams { cmd: CMD.into(), msg: format!("duplicate layer id {}", id.0) }); + } + let Some(layer) = doc.layer(*id) else { return Err(EngineError::NoLayer(*id)) }; + if !matches!(layer.content, LayerContent::Adjustment(_)) { + return Err(EngineError::BadParams { cmd: CMD.into(), msg: format!("layer {} is not an adjustment layer", id.0) }); + } + if !layer.visible { + return Err(EngineError::BadParams { cmd: CMD.into(), msg: format!("layer {} is hidden", id.0) }); + } + if !doc.layers.iter().any(|root| root.id == *id) { + return Err(EngineError::BadParams { + cmd: CMD.into(), + msg: format!("layer {} is nested in a group; export top-level adjustment layers", id.0), + }); + } + selected.push(*id); + } + } + let mut layers = Vec::new(); + for l in &doc.layers { + if l.visible && matches!(l.content, LayerContent::Adjustment(_)) && (ids.is_none() || selected.contains(&l.id)) { + layers.push(l); + } + } + if layers.is_empty() { + return Err(EngineError::BadParams { cmd: CMD.into(), msg: "no visible adjustment layers to export".into() }); + } + Ok(layers) +} + +/// Bake the chosen adjustment stack against an identity RGB lattice. +/// Source order always follows the document stack, even if an explicit list is reversed. +fn bake_cube_layers(size: usize, title: &str, layers: &[&Layer]) -> String { + let n = size; + let (w, h) = ((n * n) as u32, n as u32); + let mut lattice = Document::new("lut", photocraft_doc::Size::new(w, h), ColorMode::Rgb, photocraft_color::SampleType::F32); + let fmt = lattice.pixel_format(); + let step = 1.0 / (n - 1) as f32; + let mut data = Vec::with_capacity((w * h) as usize * fmt.channels()); + for g in 0..n { + for b in 0..n { + for r in 0..n { + let mut px = [0.0f32; 8]; + let k = from_rgba_into(&fmt, [r as f32 * step, g as f32 * step, b as f32 * step, 1.0], &mut px); + data.extend_from_slice(&px[..k]); + } + } + } + let mut surf = Surface::new(fmt); + surf.write_region(Rect::new(0, 0, w as i32, h as i32), &data); + lattice.layers.push(Layer::new("Lattice", LayerContent::Raster(surf))); + for l in layers { + let mut a = (*l).clone(); + // Masks and clipping are spatial; a LUT is the adjustment stack's colour mapping. + a.mask = None; + a.vector_mask = None; + a.clipped = false; + lattice.layers.push(a); + } + let out = photocraft_compose::flatten(&lattice); + let mut s = format!("TITLE \"{}\"\n# Created by PhotoCraft\nLUT_3D_SIZE {n}\nDOMAIN_MIN 0.0 0.0 0.0\nDOMAIN_MAX 1.0 1.0 1.0\n", title.replace('"', "'")); + // .cube order: red changes fastest, then green, then blue. + for b in 0..n { + for g in 0..n { + for r in 0..n { + let (x, y) = (b * n + r, g); + let px = out.px[y * w as usize + x]; + s.push_str(&format!("{:.6} {:.6} {:.6}\n", px[0].clamp(0.0, 1.0), px[1].clamp(0.0, 1.0), px[2].clamp(0.0, 1.0))); + } + } + } + s +} + +/// Backwards-compatible helper for exporting all visible top-level adjustments. +pub fn bake_cube(doc: &Document, size: usize, title: &str) -> String { + let layers: Vec<&Layer> = doc.layers.iter().filter(|l| l.visible && matches!(l.content, LayerContent::Adjustment(_))).collect(); + bake_cube_layers(size.clamp(2, photocraft_cms::lutfile::MAX_SIZE), title, &layers) +} + +/// Export either the whole visible stack (backward-compatible default), the Layers panel's +/// current selection, or an explicit list supplied by scripts/CLI/automation. +pub(super) fn color_lookup_tables(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "file.export.colorLookupTables"; + let d = s.active().ok_or(EngineError::NoDocument)?; + let size = match p.get("size") { + None | Some(Value::Null) => 33, + Some(v) => v.as_u64().ok_or_else(|| EngineError::BadParams { cmd: CMD.into(), msg: "size must be an integer".into() })?, + }; + if !(2..=photocraft_cms::lutfile::MAX_SIZE as u64).contains(&size) { + return Err(EngineError::BadParams { cmd: CMD.into(), msg: format!("size must be 2..={}", photocraft_cms::lutfile::MAX_SIZE) }); + } + let scope = match p.get("scope") { + None | Some(Value::Null) => "all", + Some(Value::String(s)) => s.as_str(), + Some(_) => return Err(EngineError::BadParams { cmd: CMD.into(), msg: "scope must be all or selected".into() }), + }; + if !matches!(scope, "all" | "selected") { + return Err(EngineError::BadParams { cmd: CMD.into(), msg: "scope must be all or selected".into() }); + } + if p.get("layers").is_some() && scope == "selected" { + return Err(EngineError::BadParams { cmd: CMD.into(), msg: "use either layers or scope=selected, not both".into() }); + } + let explicit: Option> = if let Some(v) = p.get("layers") { + let Some(a) = v.as_array() else { return Err(EngineError::BadParams { cmd: CMD.into(), msg: "layers must be an array of layer IDs".into() }) }; + let mut out = Vec::with_capacity(a.len()); + for id in a { + let Some(id) = id.as_u64() else { return Err(EngineError::BadParams { cmd: CMD.into(), msg: "layer IDs must be unsigned integers".into() }) }; + out.push(LayerId(id)); + } + Some(out) + } else if scope == "selected" { + Some(d.selected_layers()) + } else { + None + }; + let layers = lut_layers(&d.doc, explicit.as_deref())?; + let count = layers.len(); + let title = p.get("title").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| stem(&d.doc.name)); + let cube = bake_cube_layers(size as usize, &title, &layers); + match p.get("path").and_then(Value::as_str) { + Some(path) => { + write_file(path, cube.as_bytes())?; + Ok(json!({"path": path, "size": size, "layerCount": count})) + } + None => Ok(json!({"cube": cube, "size": size, "layerCount": count})), + } +} + +// ---------- guides ---------- + +pub(super) fn push_unique(v: &mut Vec, x: f64) { + if !v.iter().any(|g| (g - x).abs() < 0.01) { + v.push(x); + } +} diff --git a/crates/engine/src/cmd/file_cmds/info.rs b/crates/engine/src/cmd/file_cmds/info.rs new file mode 100644 index 0000000000..e038d0c097 --- /dev/null +++ b/crates/engine/src/cmd/file_cmds/info.rs @@ -0,0 +1,337 @@ +use super::*; + +// ---------- File Info (XMP) ---------- + +/// The File Info fields we edit, as (JSON key, XMP property, container kind). +const INFO_FIELDS: [(&str, &str, &str); 6] = [ + ("title", "dc:title", "Alt"), + ("author", "dc:creator", "Seq"), + ("description", "dc:description", "Alt"), + ("keywords", "dc:subject", "Bag"), + ("copyright", "dc:rights", "Alt"), + ("authorTitle", "photoshop:AuthorsPosition", ""), +]; + +fn xml_escape(s: &str) -> String { + s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """) +} + +fn xml_unescape(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + let mut rest = s; + while let Some(i) = rest.find('&') { + out.push_str(&rest[..i]); + rest = &rest[i..]; + let decoded = rest.as_bytes().iter().take(13).position(|&b| b == b';').and_then(|e| { + let c = match &rest[1..e] { + "lt" => '<', + "gt" => '>', + "quot" => '"', + "apos" => '\'', + "amp" => '&', + n => { + let n = n.strip_prefix('#')?; + let code = match n.strip_prefix(['x', 'X']) { + Some(h) => u32::from_str_radix(h, 16).ok()?, + None => n.parse().ok()?, + }; + char::from_u32(code)? + } + }; + Some((c, e + 1)) + }); + match decoded { + Some((c, len)) => { + out.push(c); + rest = &rest[len..]; + } + None => { + out.push('&'); + rest = &rest[1..]; + } + } + } + out.push_str(rest); + out +} + +/// The element `…` (first occurrence) as (start, end, inner). +pub(super) fn find_element<'a>(xmp: &'a str, tag: &str) -> Option<(usize, usize, &'a str)> { + let open = format!("<{tag}"); + let mut from = 0; + while let Some(i) = xmp[from..].find(&open).map(|i| i + from) { + let after = xmp[i + open.len()..].chars().next(); + if matches!(after, Some('>' | ' ' | '/' | '\n' | '\r' | '\t')) { + let gt = xmp[i..].find('>')? + i; + if xmp[..gt].ends_with('/') { + return Some((i, gt + 1, "")); + } + let close = format!(""); + let c = xmp[gt..].find(&close)? + gt; + return Some((i, c + close.len(), &xmp[gt + 1..c])); + } + from = i + open.len(); + } + None +} + +/// `rdf:li` values of a container (or the element text for simple properties). +fn li_values(inner: &str) -> Vec { + let mut out = Vec::new(); + let mut rest = inner; + while let Some((a, b, v)) = find_element(rest, "rdf:li") { + out.push(xml_unescape(v.trim())); + rest = &rest[b..]; + let _ = a; + } + if out.is_empty() && !inner.contains('<') && !inner.trim().is_empty() { + out.push(xml_unescape(inner.trim())); + } + out +} + +/// Attribute form `prop="value"` on an `rdf:Description`. +fn find_attr<'a>(xmp: &'a str, prop: &str) -> Option<(usize, usize, &'a str)> { + let key = format!(" {prop}=\""); + let i = xmp.find(&key)?; + let v0 = i + key.len(); + let v1 = xmp[v0..].find('"')? + v0; + Some((i, v1 + 1, &xmp[v0..v1])) +} + +/// File Info fields read from an XMP packet. +pub fn read_file_info(xmp: Option<&str>) -> Value { + let mut m = serde_json::Map::new(); + let x = xmp.unwrap_or(""); + for (key, prop, kind) in INFO_FIELDS { + let vals = match find_element(x, prop) { + Some((_, _, inner)) => li_values(inner), + None => find_attr(x, prop).map(|(_, _, v)| vec![xml_unescape(v)]).unwrap_or_default(), + }; + let v = if kind == "Bag" { + json!(vals) + } else if kind == "Seq" { + json!(vals.join("; ")) + } else { + json!(vals.into_iter().next().unwrap_or_default()) + }; + m.insert(key.into(), v); + } + let marked = + find_element(x, "xmpRights:Marked").map(|(_, _, v)| v.trim().to_string()).or_else(|| find_attr(x, "xmpRights:Marked").map(|(_, _, v)| v.to_string())); + m.insert( + "copyrightStatus".into(), + json!(match marked.as_deref() { + Some("True") => "copyrighted", + Some("False") => "publicDomain", + _ => "unknown", + }), + ); + let url = find_element(x, "xmpRights:WebStatement") + .map(|(_, _, v)| xml_unescape(v.trim())) + .or_else(|| find_attr(x, "xmpRights:WebStatement").map(|(_, _, v)| xml_unescape(v))); + m.insert("copyrightUrl".into(), json!(url.unwrap_or_default())); + Value::Object(m) +} + +/// File Info's read-only Camera Data, as (result key, English label) in display order. +pub const CAMERA_FIELDS: [(&str, &str); 9] = [ + ("make", "Make"), + ("model", "Model"), + ("dateTaken", "Date Taken"), + ("exposure", "Exposure"), + ("fNumber", "F-Stop"), + ("iso", "ISO Speed"), + ("focalLength", "Focal Length"), + ("focalLength35mm", "Focal Length (35 mm)"), + ("lens", "Lens"), +]; + +/// `v` with at most `decimals` decimals and no trailing zeros (33.10 → "33.1", 8.0 → "8"). +fn short_num(v: f64, decimals: usize) -> String { + let s = format!("{v:.decimals$}"); + if s.contains('.') { s.trim_end_matches('0').trim_end_matches('.').to_string() } else { s } +} + +/// `v` to three significant digits, with no trailing zeros (0.031714 → "0.0317", 0.4 → "0.4"). +/// Two decimals threw away most of a slow shutter speed: a stored 0.031714 s printed as "0.03 s", +/// which is 5 % off, and a stored 0.0215 s printed as "0.02 s", 7 % off (#6958). +fn sig3(v: f64) -> String { + let magnitude = v.abs().log10().floor(); + // Clamped at both ends: a value at the large end must not ask for a negative field width, and + // at the small end the field is widened rather than truncated, so a positive exposure never + // reads as "0 s". 320 is beyond f64's decimal range, so it always terminates. + let decimals = if magnitude.is_finite() { (2.0 - magnitude).clamp(0.0, 320.0) } else { 0.0 }; + short_num(v, decimals as usize) +} + +/// Exposure time as cameras print it: "1/250 s" for fractions of a second, "0.4 s" or "2 s" +/// when the reciprocal isn't a whole number or the exposure is a second or longer. +pub(super) fn exposure_text(t: f64) -> Option { + if !(t.is_finite() && t > 0.0) { + return None; + } + let r = 1.0 / t; + let n = r.round(); + // Below 1/10 s the reciprocal is above 10, so its nearest whole number puts the shown time + // within 5 % of the stored one, and is the form a photographer expects ("1/32 s"). The test + // used to be relative to the reciprocal, so it shrank as the exposure slowed: under 1/50 s it + // fell below half a rounding step and nearly every fraction fell through to the decimal form + // (#6958). Above 1/10 s the fraction is only right when the reciprocal is very nearly whole + // (1/2 s, 1/4 s) — 0.4 s stays "0.4 s" rather than becoming "1/3 s". + let fraction = n.is_finite() && (1.0..=1e9).contains(&n) && (t < 0.1 || (t < 1.0 && n > 1.0 && (r - n).abs() <= r * 0.01)); + if fraction { + return Some(format!("1/{} s", n as u64)); + } + Some(format!("{} s", sig3(t))) +} + +/// EXIF (`2024:02:17 12:40:19`) or XMP (`2024-02-17T12:40:19.00+01:00`) dates as +/// `2024-02-17 12:40:19`; anything else is shown as stored. +fn date_text(s: &str) -> String { + let b = s.trim().as_bytes(); + let digits = |r: &[usize]| r.iter().all(|&i| b.get(i).is_some_and(u8::is_ascii_digit)); + let sep = |i: usize, set: &[u8]| b.get(i).is_some_and(|c| set.contains(c)); + let ch = |i: usize| b.get(i).map_or('0', |&c| c as char); + let part = |r: std::ops::Range| r.map(ch).collect::(); + if !(digits(&[0, 1, 2, 3, 5, 6, 8, 9]) && sep(4, b":-") && sep(7, b":-")) { + return s.trim().to_string(); + } + let date = format!("{}-{}-{}", part(0..4), part(5..7), part(8..10)); + if digits(&[11, 12, 14, 15, 17, 18]) && sep(10, b" T") && sep(13, b":") && sep(16, b":") { format!("{date} {}", part(11..19)) } else { date } +} + +/// A single XMP value: the first `rdf:li` of a container, element text or attribute. +fn xmp_value(x: &str, prop: &str) -> Option { + let v = match find_element(x, prop) { + Some((_, _, inner)) => li_values(inner).into_iter().next(), + None => find_attr(x, prop).map(|(_, _, v)| xml_unescape(v)), + }?; + let v = v.trim().to_string(); + (!v.is_empty()).then_some(v) +} + +/// An XMP number: a rational "331/10" or a decimal. +fn xmp_number(x: &str, prop: &str) -> Option { + let v = xmp_value(x, prop)?; + let n = match v.split_once('/') { + Some((a, b)) => { + let (a, b) = (a.trim().parse::().ok()?, b.trim().parse::().ok()?); + (b != 0.0).then(|| a / b)? + } + None => v.parse::().ok()?, + }; + n.is_finite().then_some(n) +} + +/// File Info's read-only Camera Data (keys of [`CAMERA_FIELDS`], present ones only), formatted +/// for display. Read from the EXIF block (JPEG APP1, PSD resource 1058, …); properties it lacks +/// fall back to the XMP `tiff:`/`exif:`/`aux:` copies (files without an EXIF block). +pub fn camera_data(exif: Option<&[u8]>, xmp: Option<&str>) -> Value { + let e = exif.map(photocraft_algo::exif::read).unwrap_or_default(); + let x = xmp.unwrap_or(""); + let text = |v: Option, props: &[&str]| v.or_else(|| props.iter().find_map(|p| xmp_value(x, p))); + let num = + |v: Option, props: &[&str]| v.filter(|v| v.is_finite() && *v > 0.0).or_else(|| props.iter().find_map(|p| xmp_number(x, p))).filter(|v| *v > 0.0); + let values = [ + text(e.make, &["tiff:Make"]), + text(e.model, &["tiff:Model"]), + text(e.date_taken, &["exif:DateTimeOriginal"]).map(|d| date_text(&d)), + num(e.exposure_time, &["exif:ExposureTime"]).and_then(exposure_text), + num(e.f_number, &["exif:FNumber"]).map(|n| format!("f/{}", short_num(n, 1))), + num(e.iso, &["exif:ISOSpeedRatings", "exifEX:PhotographicSensitivity"]).map(|n| format!("ISO {}", n.round())), + num(e.focal_length, &["exif:FocalLength"]).map(|f| format!("{} mm", short_num(f, 1))), + num(e.focal_length_35mm, &["exif:FocalLengthIn35mmFilm"]).map(|f| format!("{} mm", short_num(f, 1))), + text(e.lens, &["exifEX:LensModel", "aux:Lens"]), + ]; + let mut m = serde_json::Map::new(); + for ((key, _), v) in CAMERA_FIELDS.into_iter().zip(values) { + // Hostile files can carry megabytes of "lens name"; the dialog shows a line. + if let Some(v) = v.map(|v| v.chars().take(200).collect::()).filter(|v| !v.is_empty()) { + m.insert(key.into(), json!(v)); + } + } + Value::Object(m) +} + +/// Rewrites only changed File Info fields of an XMP packet (creating one when there is none), +/// keeping the other properties verbatim. Edited properties move into their own +/// `rdf:Description` (several descriptions per packet are valid XMP). +pub fn write_file_info(xmp: Option<&str>, info: &Value) -> String { + let cur = read_file_info(xmp); + // The dialog submits all fields, including unchanged language alternatives. + let changed = |key: &str| info.get(key).is_some_and(|v| cur.get(key) != Some(v)); + let mut x = xmp.filter(|s| s.contains("")).map(str::to_string).unwrap_or_else(|| { + "\n\n \n \n\n".to_string() + }); + for (key, prop, _) in INFO_FIELDS.into_iter().chain([("copyrightStatus", "xmpRights:Marked", ""), ("copyrightUrl", "xmpRights:WebStatement", "")]) { + if !changed(key) { + continue; + } + while let Some((a, b, _)) = find_element(&x, prop) { + x.replace_range(a..b, ""); + } + while let Some((a, b, _)) = find_attr(&x, prop) { + x.replace_range(a..b, ""); + } + } + let get = |k: &str| info.get(k).filter(|_| changed(k)).cloned().unwrap_or(Value::Null); + let mut body = String::new(); + for (key, prop, kind) in INFO_FIELDS { + let vals: Vec = match get(key) { + Value::Array(a) => a.iter().filter_map(|v| v.as_str()).map(str::to_string).filter(|v| !v.is_empty()).collect(), + Value::String(s) if kind == "Bag" || kind == "Seq" => s.split([';', ',']).map(|v| v.trim().to_string()).filter(|v| !v.is_empty()).collect(), + Value::String(s) if !s.is_empty() => vec![s], + _ => Vec::new(), + }; + if vals.is_empty() { + continue; + } + let items: String = vals + .iter() + .map(|v| { + if kind == "Alt" { format!("{}", xml_escape(v)) } else { format!("{}", xml_escape(v)) } + }) + .collect(); + if kind.is_empty() { + body.push_str(&format!(" <{prop}>{}\n", xml_escape(&vals[0]))); + } else { + body.push_str(&format!(" <{prop}>{items}\n")); + } + } + match get("copyrightStatus").as_str() { + Some("copyrighted") => body.push_str(" True\n"), + Some("publicDomain") => body.push_str(" False\n"), + _ => {} + } + if let Some(u) = get("copyrightUrl").as_str().filter(|u| !u.is_empty()) { + body.push_str(&format!(" {}\n", xml_escape(u))); + } + if !body.is_empty() { + let desc = format!( + " \n{body} \n " + ); + let at = x.rfind("").unwrap_or(x.len()); + x.insert_str(at, &desc); + } + x +} + +pub(super) fn file_info(s: &mut Session, p: &Value) -> Result { + let keys = ["title", "author", "authorTitle", "description", "keywords", "copyright", "copyrightStatus", "copyrightUrl"]; + let edits = p.as_object().is_some_and(|m| m.keys().any(|k| keys.contains(&k.as_str()))); + if edits { + let xmp = s.active().ok_or(EngineError::NoDocument)?.doc.metadata.xmp.clone(); + let new = write_file_info(xmp.as_deref(), p); + s.edit("File Info", |doc, _| { + doc.metadata.xmp = Some(new.into()); + Ok(()) + })?; + } + let d = s.active().ok_or(EngineError::NoDocument)?; + let mut info = read_file_info(d.doc.metadata.xmp.as_deref()); + if let Value::Object(m) = &mut info { + m.insert("camera".into(), camera_data(d.doc.metadata.exif.as_deref().map(Vec::as_slice), d.doc.metadata.xmp.as_deref())); + } + Ok(info) +} diff --git a/crates/engine/src/cmd/file_cmds/open.rs b/crates/engine/src/cmd/file_cmds/open.rs new file mode 100644 index 0000000000..d95174ad9d --- /dev/null +++ b/crates/engine/src/cmd/file_cmds/open.rs @@ -0,0 +1,226 @@ +use super::paths::{file_name, read_file, stem, template_name}; +use super::*; + +pub(crate) fn import(name: &str, bytes: &[u8]) -> Result { + import_result(name, bytes).map(|r| r.document) +} + +/// [`import`] for a file that becomes a document of its own (Revert, Load Files into Stack; +/// Batch's scratch sessions use [`import_at_raw_ppi`]): a developed raw gets Preferences › Raw +/// Defaults › Resolution, as it does through File › Open. +pub(crate) fn import_opened(s: &Session, name: &str, bytes: &[u8]) -> Result { + import_at_raw_ppi(s.prefs().raw_defaults.resolution, name, bytes) +} + +pub(super) fn import_at_raw_ppi(raw_ppi: f64, name: &str, bytes: &[u8]) -> Result { + let r = import_result(name, bytes)?; + let mut doc = r.document; + raw_resolution(raw_ppi, &r.warnings, &mut doc); + Ok(doc) +} + +fn import_result(name: &str, bytes: &[u8]) -> Result { + crate::allocation::checkpoint("importing document")?; + let r = photocraft_io::import(name, bytes).map_err(|e| EngineError::Other(format!("{name}: {e}")))?; + // Auxiliary imports return only a document and cannot surface the preview's fidelity warning. + // Open has its own warning-preserving path; never silently place or process a thumbnail. + if r.preview_only { + return Err(EngineError::Other(format!( + "{name}: only this Affinity file's embedded preview could be read; open it with File › Open to see the warning, or export PSD or PNG from Affinity before using it here" + ))); + } + Ok(r) +} + +// ---------- close / revert / save a copy / open as ---------- + +pub(super) fn close_all(s: &mut Session) -> Result { + let n = s.documents().len(); + while !s.documents().is_empty() { + s.close(s.documents().len() - 1); + } + Ok(json!({"closed": n})) +} + +pub(super) fn close_others(s: &mut Session, p: &Value) -> Result { + let keep = p.get("document").and_then(Value::as_u64).map(|v| v as usize).or(s.active_index()).ok_or(EngineError::NoDocument)?; + if keep >= s.documents().len() { + return Err(EngineError::BadParams { cmd: "file.closeOthers".into(), msg: format!("no document {keep}") }); + } + let n = s.documents().len() - 1; + for i in (0..s.documents().len()).rev() { + if i != keep { + s.close(i); + } + } + s.set_active(0); + Ok(json!({"closed": n})) +} + +/// File › Revert: reload the saved file as one history step (undoable, like Photoshop's +/// "Revert" history state); the document is clean afterwards. +pub(super) fn revert(s: &mut Session) -> Result { + let path = s.active().and_then(|d| d.path.clone()).ok_or(EngineError::Other("the document has never been saved".into()))?; + let bytes = read_file(&path)?; + let fresh = import_opened(s, &file_name(&path), &bytes)?; + s.edit("Revert", |doc, active| { + let (id, name) = (doc.id, doc.name.clone()); + *doc = fresh; + // Keep the identity (colour state, views and caches are keyed by it) and the tab name. + doc.id = id; + doc.name = name; + *active = doc.top_layer(); + Ok(()) + })?; + let st = s.active_mut().ok_or(EngineError::NoDocument)?; + st.saved_revision = st.revision; + Ok(json!({"path": path, "layers": st.doc.layers.len()})) +} + +/// Open a file's bytes, decoding them as the format `as_ext` (Open As) when given. +/// EXR/HDR rarely states its colour space, so io tags it with the linear-sRGB default. +/// With File Handling's ACEScg option on, such an EXR opens as ACEScg instead (AP1, +/// linear) — the working space ACES render pipelines write. Only the io default is +/// replaced; an embedded or EXIF-declared profile is kept untouched. +pub(crate) fn tag_exr_colorspace(s: &Session, name: &str, doc: &mut Document) { + if !name.to_ascii_lowercase().ends_with(".exr") || !s.prefs.get().file_handling.exr_aces_cg { + return; + } + let linear = photocraft_cms::Builtin::LinearSrgb.profile().to_bytes(); + if doc.icc_profile.as_ref().map(|v| v.as_slice()) == Some(linear.as_slice()) { + doc.icc_profile = Some(photocraft_cms::Builtin::AcesCg.profile().to_bytes()); + } +} + +/// Edit › Preferences › Raw Defaults › Resolution: the ppi a raw developed on open gets, as +/// Camera Raw's workflow options set it (the raw itself states none). `warnings` are the +/// import's notes, which say whether the raw was developed or only its preview opened. +pub fn raw_defaults(s: &Session, warnings: &[String], doc: &mut Document) { + raw_resolution(s.prefs().raw_defaults.resolution, warnings, doc); +} + +fn raw_resolution(ppi: f64, warnings: &[String], doc: &mut Document) { + if ppi.is_finite() && warnings.iter().any(|w| w.contains(photocraft_io::raw::DEVELOPED_NOTE)) { + doc.resolution_dpi = ppi.clamp(1.0, 10_000.0) as f32; + } +} + +pub fn open_bytes_as(s: &mut Session, name: &str, bytes: &[u8], as_ext: Option<&str>, path: Option) -> Result { + crate::allocation::checkpoint("importing document")?; + let decode_name = match as_ext { + Some(ext) => format!("{}.{}", stem(name), ext.trim_start_matches('.')), + None => name.to_string(), + }; + let r = photocraft_io::import(&decode_name, bytes).map_err(|e| EngineError::Other(format!("{decode_name}: {e}")))?; + let mut doc = r.document; + tag_exr_colorspace(s, &decode_name, &mut doc); + raw_defaults(s, &r.warnings, &mut doc); + let path = match template_name(s, name) { + Some(untitled) => { + doc.name = untitled; + None + } + None => { + doc.name = file_name(name); + path + } + }; + // Color Settings policies (preserve / convert / discard the embedded profile). + let (i, color) = s.open_document(doc, path.filter(|_| !r.source_read_only)); + if let Some(st) = s.active_mut() { + st.source_read_only = r.source_read_only; + } + // Import notes (e.g. how a camera raw was developed, or that only its preview opened). + Ok(json!({"document": i, "color": color, "warnings": r.warnings})) +} + +pub(super) fn open_as(s: &mut Session, p: &Value) -> Result { + let path = str_param(p, "path", "file.openAs")?.to_string(); + let bytes = read_file(&path)?; + let as_ext = p.get("as").or_else(|| p.get("format")).and_then(Value::as_str); + open_bytes_as(s, &path, &bytes, as_ext, Some(path.clone())) +} + +// ---------- place ---------- + +/// History label of an embedded place. +pub const PLACE_EMBEDDED: &str = "Place Embedded"; + +/// Place a file's bytes as a smart object layer, centred, and (with Preferences ▸ General ▸ +/// Resize Image During Place, on by default) scaled down to fit when larger than the canvas. +/// `linked` makes it a linked smart object that refers to that path instead of embedding the bytes. +/// With Preferences ▸ General ▸ Always Create Smart Objects When Placing off, an embedded place +/// lands as a plain pixel layer instead (an explicit `"smartObject": false` asks for one). +pub fn place_bytes(s: &mut Session, name: &str, bytes: Vec, linked: Option, p: &Value) -> Result { + let d = s.active().ok_or(EngineError::NoDocument)?; + let (cw, ch) = (d.doc.size.width as f64, d.doc.size.height as f64); + let fmt = d.doc.pixel_format(); + let vector = photocraft_io::svg::is_svg(&bytes); + let opts = crate::jobs::import_options(s.prefs()); + let imported = photocraft_io::import_with_options(name, &bytes, &opts).map_err(|e| EngineError::Other(format!("{name}: {e}")))?; + if imported.preview_only { + return Err(EngineError::Other(format!( + "{name}: only this Affinity file's embedded preview could be read; open it with File › Open to see the warning, or export PSD or PNG from Affinity before using it here" + ))); + } + let src = imported.document; + let (w, h) = (src.size.width as f64, src.size.height as f64); + // The implicit `fit` is Preferences ▸ General ▸ Resize Image During Place (on by default). + let fit = p.get("fit").and_then(Value::as_bool).unwrap_or(s.prefs().general.resize_image_during_place); + let scale = match f64_param(p, "scale") { + Some(k) => (k / 100.0).max(1e-4), + None if fit && (w > cw || h > ch) => (cw / w).min(ch / h), + None => 1.0, + }; + let center = match p.get("center").and_then(Value::as_array) { + Some(c) if c.len() == 2 => (c[0].as_f64().unwrap_or(cw / 2.0), c[1].as_f64().unwrap_or(ch / 2.0)), + _ => (cw / 2.0, ch / 2.0), + }; + let (dx, dy) = ((center.0 - w * scale / 2.0).round(), (center.1 - h * scale / 2.0).round()); + let mut px = flattened_checked(&src, fmt, "file.place")?; + if (scale - 1.0).abs() > 1e-9 { + px = resize_surface(&px, scale, scale, Resample::Bicubic); + } + let px = translate_surface(&px, dx as i32, dy as i32); + // Preferences ▸ General ▸ Always Create Smart Objects When Placing (on by default): off, an + // embedded place lands as a plain pixel layer. A linked place is always a smart object. + let smart = linked.is_some() || p.get("smartObject").and_then(Value::as_bool).unwrap_or(s.prefs().general.always_create_smart_objects_when_placing); + let source = match linked { + Some(path) => SmartSource::Linked { path }, + None => SmartSource::Embedded { file_name: file_name(name), bytes: Arc::new(bytes) }, + }; + let layer_name = stem(name); + let label = if matches!(&source, SmartSource::Linked { .. }) { "Place Linked" } else { PLACE_EMBEDDED }; + let id = s.edit(label, |doc, active| { + let layer = if smart { + let mut so = SmartObject::new(source, Affine { m: [scale, 0.0, 0.0, scale, dx, dy] }, Some(px)); + // A vector source (SVG) renders at its placement scale instead of as a resampled raster. + if vector && let Some(sharp) = crate::smart_cmds::render(doc, &so)? { + so.cache = Some(sharp); + } + Layer::new(layer_name, LayerContent::Smart(so)) + } else { + Layer::new(layer_name, LayerContent::Raster(px)) + }; + let id = doc.insert_above(*active, layer); + *active = Some(id); + Ok(id) + })?; + Ok(json!({"layer": id.0, "scale": scale * 100.0, "bounds": [dx, dy, dx + w * scale, dy + h * scale], "smartObject": smart})) +} + +pub(super) fn place(s: &mut Session, p: &Value, linked: bool) -> Result { + let cmd = if linked { "file.placeLinked" } else { "file.placeEmbedded" }; + let path = str_param(p, "path", cmd)?.to_string(); + let bytes = read_file(&path)?; + // The link is stored absolute: a relative one would later be taken from the document's + // folder (`doc_path`), not the working directory the path was given in. + let link = linked.then(|| { + if std::path::Path::new(&path).is_relative() { + std::path::absolute(&path).map_or_else(|_| path.clone(), |a| a.to_string_lossy().into_owned()) + } else { + path.clone() + } + }); + place_bytes(s, &path, bytes, link, p) +} diff --git a/crates/engine/src/cmd/file_cmds/paths.rs b/crates/engine/src/cmd/file_cmds/paths.rs new file mode 100644 index 0000000000..7046393150 --- /dev/null +++ b/crates/engine/src/cmd/file_cmds/paths.rs @@ -0,0 +1,228 @@ +use super::*; + +// ---------- file system (native only) ---------- + +#[cfg(not(target_arch = "wasm32"))] +pub(super) fn is_file(path: &str) -> bool { + std::path::Path::new(path).is_file() +} + +#[cfg(target_arch = "wasm32")] +pub(super) fn is_file(_path: &str) -> bool { + false +} + +#[cfg(not(target_arch = "wasm32"))] +/// Every file the engine opens is read here: in bounded reads, with a clear error when it does +/// not fit in memory (see [`photocraft_format::read`]). +pub(crate) fn read_file(path: &str) -> Result> { + photocraft_format::read_file(std::path::Path::new(path)).map_err(|e| EngineError::Other(format!("{path}: {e}"))) +} + +#[cfg(target_arch = "wasm32")] +pub(crate) fn read_file(path: &str) -> Result> { + Err(EngineError::Other(format!("cannot read {path}: no file system on the web"))) +} + +#[cfg(not(target_arch = "wasm32"))] +/// Every file the engine writes goes through here: crash-safe (temp file + fsync + rename, see +/// [`photocraft_format::atomic`]), so a failed save never destroys the previous file. +pub(crate) fn write_file(path: &str, bytes: &[u8]) -> Result<()> { + photocraft_format::atomic_write(std::path::Path::new(path), bytes).map_err(|e| EngineError::Other(e.to_string())) +} + +#[cfg(target_arch = "wasm32")] +pub(crate) fn write_file(path: &str, _bytes: &[u8]) -> Result<()> { + Err(EngineError::Other(format!("cannot write {path}: no file system on the web"))) +} + +/// Files of a folder that look like images we can open, sorted by name. +#[cfg(not(target_arch = "wasm32"))] +pub fn list_images(dir: &str) -> Result> { + let rd = std::fs::read_dir(dir).map_err(|e| EngineError::Other(format!("{dir}: {e}")))?; + let mut out: Vec = rd + .filter_map(|e| e.ok()) + .map(|e| e.path()) + .filter(|p| p.is_file() && openable_name(&p.to_string_lossy())) + .map(|p| p.to_string_lossy().into_owned()) + .collect(); + out.sort(); + Ok(out) +} + +#[cfg(target_arch = "wasm32")] +pub fn list_images(dir: &str) -> Result> { + Err(EngineError::Other(format!("cannot list {dir}: no file system on the web"))) +} + +/// Whether a folder entry is one the batch commands open: an `OPENABLE` extension, or GIMP's +/// gzipped `.xcf.gz`, whose last extension alone says nothing. +#[cfg(not(target_arch = "wasm32"))] +pub(super) fn openable_name(path: &str) -> bool { + let lower = file_name(path).to_ascii_lowercase(); + lower.ends_with(".xcf.gz") || lower.rsplit_once('.').is_some_and(|(_, ext)| OPENABLE.contains(&ext)) +} + +/// Extensions the batch commands pick up from a folder. +#[cfg(not(target_arch = "wasm32"))] +const OPENABLE: &[&str] = &[ + "pdn", "ora", "xcf", "xcfgz", "kra", "krz", "psd", "psb", "pcraft", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "exr", "hdr", "qoi", + "ico", "pnm", "ppm", "pgm", "fits", "fit", "fts", "dpx", "heic", "heif", "hif", "dng", "cr2", "nef", "nrw", "arw", "pef", "svg", "svgz", "af", "afdesign", + "afphoto", "afpub", +]; + +pub(crate) fn file_name(path: &str) -> String { + path.rsplit(['/', '\\']).next().unwrap_or(path).to_string() +} + +/// The lower-case extension of the file name in `path` (none for `.hidden` or `name`). +pub fn extension(path: &str) -> Option { + file_name(path).rsplit_once('.').filter(|(base, ext)| !base.is_empty() && !ext.is_empty()).map(|(_, ext)| ext.to_ascii_lowercase()) +} + +/// Whether a save without a new path may write back to `path` as far as its format goes: only +/// layered files (PSD, PSB, OpenRaster, .pcraft). A flat file goes through Save As instead, so it +/// is never flattened over the original. Whether this document fits is [`holds_at`]. +pub fn saves_in_place(path: &str) -> bool { + extension(path).is_some_and(|ext| layered_extension(&ext)) +} + +/// Whether the lower-case extension `ext` names a layered document format (PSD, PSB, OpenRaster, +/// .pcraft). A save to one becomes the document's file; any other format is a copy for automation +/// saves, desktop and headless alike (#1547, #2579). +pub fn layered_extension(ext: &str) -> bool { + matches!(ext, "psd" | "psb" | "pcraft" | "ora") +} + +/// Whether a file in format `ext` (lower-case) holds the whole of `doc`, so it can be the +/// document's own file: PSD, PSB and .pcraft always; OpenRaster only when it drops nothing (no +/// adjustment layers, styles, masks…, [`photocraft_io::ora_losses`]). A save to a format that +/// doesn't hold the document is a copy, and File › Save goes through Save As, so an editable +/// original is never overwritten with less than it had (#3806). +pub fn holds(doc: &photocraft_doc::Document, ext: &str) -> bool { + match ext { + "psd" | "psb" | "pcraft" => true, + "ora" => photocraft_io::ora_losses(doc).is_empty(), + _ => false, + } +} + +/// [`holds`] for the file at `path`. +pub fn holds_at(doc: &photocraft_doc::Document, path: &str) -> bool { + extension(path).is_some_and(|ext| holds(doc, &ext)) +} + +/// What a save of `doc` to `path` would leave out when its format can't hold it: OpenRaster's +/// [`photocraft_io::ora_losses`]; empty for other formats. +pub fn losses_at(doc: &photocraft_doc::Document, path: &str) -> Vec { + match extension(path).as_deref() { + Some("ora") => photocraft_io::ora_losses(doc), + _ => Vec::new(), + } +} + +/// Whether `path` names a document template (.psdt). A template opens as a new untitled document +/// without its path, so a save never writes over the template. +pub fn is_template(path: &str) -> bool { + extension(path).as_deref() == Some("psdt") +} + +/// The first "`base`-N" that isn't `taken`. +pub fn untitled_name(base: &str, taken: impl Fn(&str) -> bool) -> String { + (1..).map(|i| format!("{base}-{i}")).find(|n| !taken(n)).unwrap_or_default() +} + +/// The name a document opened from `path` gets when `path` is a template: the first "Untitled-N" +/// no open document has. +pub fn template_name(s: &Session, path: &str) -> Option { + is_template(path).then(|| untitled_name("Untitled", |n| s.documents().iter().any(|d| d.doc.name == n))) +} + +pub(crate) fn stem(path: &str) -> String { + let n = file_name(path); + match n.rfind('.') { + Some(i) if i > 0 => n[..i].to_string(), + _ => n, + } +} + +/// Whether `a` and `b` name the same file: the same text, or, when both exist, the same file on +/// disk (a hard link, a different case on a case-insensitive volume, `./` or `..` in one of them). +pub fn same_file(a: impl AsRef, b: impl AsRef) -> bool { + let (a, b) = (a.as_ref(), b.as_ref()); + if a == b { + return true; + } + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + if let (Ok(x), Ok(y)) = (std::fs::metadata(a), std::fs::metadata(b)) { + return x.dev() == y.dev() && x.ino() == y.ino(); + } + } + #[cfg(windows)] + { + // The volume serial number and file index of each, as unix compares dev and inode, so a + // hard link (another name for the file) is the same file. + if let Ok(same) = same_file::is_same_file(a, b) { + return same; + } + // Should a file not open: NTFS and FAT compare names without case. + if let (Ok(x), Ok(y)) = (std::fs::canonicalize(a), std::fs::canonicalize(b)) { + return x.to_string_lossy().to_lowercase() == y.to_string_lossy().to_lowercase(); + } + } + false +} + +/// A path as command results report it: `/` between components, whatever the platform. +/// +/// `join` already builds with `/`, but a directory from the caller or from `std::path::absolute` +/// carries the native separator, which would leave a reported path mixed. The control channel +/// takes `/` and rejects alternate separators (`AuthorizedWorkspace` in `crates/automation`), so +/// a result spelt this way can be handed straight back to it. Verbatim and UNC prefixes keep +/// theirs: Win32 does not accept `/` after a leading `\\`. +pub(crate) fn forward_slashes(path: String) -> String { + if path.starts_with(r"\\") { path } else { path.replace('\\', "/") } +} + +pub(crate) fn join(dir: &str, name: &str) -> String { + if dir.is_empty() { + name.to_string() + } else if dir.ends_with('/') || dir.ends_with('\\') { + format!("{dir}{name}") + } else { + format!("{dir}/{name}") + } +} + +/// A file-name-safe version of a layer name. A Windows device name (`nul`, `con.v2`) gets a `_` +/// before its first dot, so the file or folder is usable on Windows, wherever it was written. +pub(crate) fn sanitize(name: &str) -> String { + let s: String = name.chars().map(|c| if c.is_alphanumeric() || matches!(c, '-' | '_' | ' ' | '.') { c } else { '_' }).collect(); + let s = s.trim().trim_matches('.').to_string(); + if s.is_empty() { "layer".into() } else { portable_device_name(s) } +} + +/// `name` with a `_` before its first dot when it is a Windows device name (`nul` → `nul_`, +/// `com1.v2` → `com1_.v2`); a `_` at the end would leave the device stem in place. +pub(crate) fn portable_device_name(name: String) -> String { + if !is_windows_device_name(&name) { + return name; + } + match name.split_once('.') { + Some((device, rest)) => format!("{device}_.{rest}"), + None => format!("{name}_"), + } +} + +/// Whether `component` names a Windows device (`CON`, `NUL`, `COM1`…, with any extension): +/// Windows opens the device instead of a file or folder of that name. `COM` and `LPT` take the +/// superscript digits ¹ ² ³ as well, as Windows does. +pub(crate) fn is_windows_device_name(component: &str) -> bool { + let stem = component.split('.').next().unwrap_or(component).trim_end_matches(' ').to_ascii_uppercase(); + let port = |n: &str| matches!(n, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "¹" | "²" | "³"); + matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL" | "CLOCK$" | "CONIN$" | "CONOUT$") + || stem.strip_prefix("COM").is_some_and(port) + || stem.strip_prefix("LPT").is_some_and(port) +} diff --git a/crates/engine/src/cmd/file_cmds/processing.rs b/crates/engine/src/cmd/file_cmds/processing.rs new file mode 100644 index 0000000000..b9718aab70 --- /dev/null +++ b/crates/engine/src/cmd/file_cmds/processing.rs @@ -0,0 +1,251 @@ +use super::batch_run::{batch_inputs_tree, process_tree}; +use super::open::import_opened; +use super::paths::{file_name, list_images, read_file, stem}; +use super::save::SaveOpts; +use super::*; + +// ---------- Automate ---------- + +pub(super) fn fit_image(s: &mut Session, p: &Value) -> Result { + let d = s.active().ok_or(EngineError::NoDocument)?; + let (w, h) = (d.doc.size.width as f64, d.doc.size.height as f64); + let bw = size_param(p, "width").unwrap_or(w); + let bh = size_param(p, "height").unwrap_or(h); + let k = (bw / w).min(bh / h); + if (k > 1.0 && p.get("dontEnlarge").and_then(Value::as_bool).unwrap_or(false)) || ((w * k).round() == w && (h * k).round() == h) { + return Ok(json!({"width": w, "height": h, "changed": false})); + } + let (nw, nh) = ((w * k).round().max(1.0), (h * k).round().max(1.0)); + let resample = p.get("resample").and_then(Value::as_str).unwrap_or("bicubic"); + s.execute("image.imageSize", json!({"width": nw, "height": nh, "resample": resample}))?; + Ok(json!({"width": nw, "height": nh, "changed": true})) +} + +fn mode_name(m: ColorMode) -> &'static str { + match m { + ColorMode::Bitmap => "bitmap", + ColorMode::Grayscale => "grayscale", + ColorMode::Duotone => "duotone", + ColorMode::Indexed => "indexed", + ColorMode::Rgb => "rgb", + ColorMode::Cmyk => "cmyk", + ColorMode::Lab => "lab", + ColorMode::Multichannel => "multichannel", + } +} + +pub(super) fn conditional_mode_change(s: &mut Session, p: &Value) -> Result { + let cmd = "file.automate.conditionalModeChange"; + let to = str_param(p, "to", cmd)?.to_ascii_lowercase(); + let to = match to.as_str() { + "gray" | "grayscale" => "grayscale", + "rgb" => "rgb", + "cmyk" => "cmyk", + "lab" => "lab", + other => return Err(EngineError::BadParams { cmd: cmd.into(), msg: format!("unsupported target mode \"{other}\" (rgb, grayscale, cmyk, lab)") }), + }; + let cur = mode_name(s.active().ok_or(EngineError::NoDocument)?.doc.mode); + // One spelling per source mode, for the array and the single-string forms alike (#7042). + let norm = |v: &str| { + let v = v.to_ascii_lowercase(); + if v == "gray" { "grayscale".to_string() } else { v } + }; + let from: Vec = match p.get("from") { + Some(Value::Array(a)) => a.iter().filter_map(Value::as_str).map(norm).collect(), + Some(Value::String(v)) => vec![norm(v)], + _ => vec!["any".into()], + }; + if cur == to || !(from.iter().any(|f| f == "any" || f == cur)) { + return Ok(json!({"changed": false, "mode": cur})); + } + s.execute(&format!("image.mode.{to}"), json!({}))?; + Ok(json!({"changed": true, "mode": to})) +} + +/// One `[id, params]` / `{command, params}` / `{id, params}` step of an action. +pub(super) fn parse_steps(v: &Value) -> Result> { + let bad = |m: &str| EngineError::BadParams { cmd: "file.automate.batch".into(), msg: m.into() }; + let arr = v.as_array().ok_or_else(|| bad("\"steps\" must be an array"))?; + arr.iter() + .map(|st| match st { + Value::Array(a) if !a.is_empty() => { + Ok((a[0].as_str().ok_or_else(|| bad("step id must be a string"))?.to_string(), a.get(1).cloned().unwrap_or(json!({})))) + } + Value::Object(o) => { + let id = o.get("command").or_else(|| o.get("id")).and_then(Value::as_str).ok_or_else(|| bad("step needs \"command\""))?; + Ok((id.to_string(), o.get("params").cloned().unwrap_or(json!({})))) + } + Value::String(id) => Ok((id.clone(), json!({}))), + _ => Err(bad("each step is [id, params] or {\"command\", \"params\"}")), + }) + .collect() +} + +pub(super) fn image_processor(s: &mut Session, p: &Value) -> Result { + let cmd = "file.scripts.imageProcessor"; + let output = str_param(p, "output", cmd)?.to_string(); + let inputs = batch_inputs_tree(p, cmd, &output)?; + let format = p.get("format").and_then(Value::as_str).unwrap_or("jpg").to_string(); + let fit = match (size_param(p, "width"), size_param(p, "height")) { + (None, None) => None, + (w, h) => Some(json!({"width": w.unwrap_or(1e9), "height": h.unwrap_or(1e9), "dontEnlarge": true})), + }; + let to_srgb = p.get("convertToSrgb").and_then(Value::as_bool).unwrap_or(false); + let r = process_tree(s, &inputs, &output, &format, SaveOpts::from_params(s, p, cmd)?.or_quality(8.0), "", &|scratch, _| { + if to_srgb && scratch.active().is_some_and(|d| d.doc.mode != ColorMode::Rgb) { + scratch.execute("image.mode.rgb", json!({}))?; + } + if let Some(fp) = &fit { + fit_image(scratch, fp)?; + } + Ok(false) + }); + Ok(r) +} + +pub(super) fn load_files_into_stack(s: &mut Session, p: &Value) -> Result { + let cmd = "file.scripts.loadFilesIntoStack"; + let paths: Vec = match p.get("paths").or_else(|| p.get("input")) { + Some(Value::Array(a)) => a.iter().filter_map(Value::as_str).map(str::to_string).collect(), + Some(Value::String(dir)) => list_images(dir)?, + _ => return Err(EngineError::BadParams { cmd: cmd.into(), msg: "missing \"paths\"".into() }), + }; + if paths.is_empty() { + return Err(EngineError::BadParams { cmd: cmd.into(), msg: "no files to load".into() }); + } + let mut docs = Vec::new(); + for path in &paths { + let bytes = read_file(path)?; + docs.push((file_name(path), import_opened(s, &file_name(path), &bytes)?)); + } + let first = &docs[0].1; + let w = docs.iter().map(|(_, d)| d.size.width).max().unwrap_or(1); + let h = docs.iter().map(|(_, d)| d.size.height).max().unwrap_or(1); + let mut stack = Document::new(stem(&paths[0]), photocraft_doc::Size::new(w, h), first.mode, first.depth); + stack.resolution_dpi = first.resolution_dpi; + stack.icc_profile = first.icc_profile.clone(); + let fmt = stack.pixel_format(); + // First file at the bottom, like Photoshop's script. + for (name, d) in &docs { + stack.layers.push(Layer::new(name.clone(), LayerContent::Raster(flattened_checked(d, fmt, cmd)?))); + } + let n = stack.layers.len(); + let smart = p.get("createSmartObject").and_then(Value::as_bool).unwrap_or(false); + // "Attempt to Automatically Align Source Images": Auto-Align Layers on the loaded layers, before + // they go into the smart object. + let align = p.get("align").and_then(Value::as_bool).unwrap_or(false) && n > 1; + if smart && !align { + // "Create Smart Object after Loading Layers": the layers go inside one smart object, ready + // for Layer › Smart Objects › Stack Mode. Like Photoshop, they sit at the top level of the + // contents, with no wrapper group. + let layers = std::mem::take(&mut stack.layers); + let smart = crate::smart_cmds::layers_to_smart(&stack, &stem(&paths[0]), layers)?; + stack.layers = vec![smart]; + } + let i = s.add_document(stack, None); + if align { + s.execute("select.allLayers", json!({}))?; + s.execute("edit.autoAlignLayers", json!({"projection": "auto"}))?; + if smart { + let name = s.active().map(|d| d.doc.name.clone()).unwrap_or_default(); + s.edit("Convert to Smart Object", |doc, active| { + let layers = std::mem::take(&mut doc.layers); + let smart = crate::smart_cmds::layers_to_smart(doc, &name, layers)?; + *active = Some(smart.id); + doc.layers = vec![smart]; + Ok(()) + })?; + if let Some(st) = s.active_mut() { + st.selected_layers = st.active_layer.into_iter().collect(); + } + } + } + Ok(json!({"document": i, "layers": n})) +} + +// ---------- Scripts: flatten effects / masks ---------- + +fn has_live_effects(l: &Layer) -> bool { + l.effects.enabled && l.effects.items.iter().any(|e| e.enabled()) +} + +/// The layer of `doc` rendered alone (keeping what `keep` says) with the document's Global Light, +/// patterns and canvas, as a surface in the document's format. With `apply_mask` off the layer's +/// pixel and vector masks are left out of the render, so a caller that keeps them live on the +/// baked raster does not mask the pixels twice. +fn bake(doc: &Document, l: &Layer, keep_effects: bool, apply_mask: bool) -> Surface { + let canvas = doc.bounds(); + let mut tmp = l.clone(); + tmp.opacity = 1.0; + tmp.blend = photocraft_color::BlendMode::Normal; + tmp.visible = true; + tmp.clipped = false; + if !keep_effects { + tmp.effects.items.clear(); + tmp.fill_opacity = 1.0; + } + if !apply_mask { + tmp.mask = None; + tmp.vector_mask = None; + } + // Render over the union of the canvas and the content so off-canvas pixels survive. + let area = l.surface().map_or(canvas, |s| s.content_bounds().union(&canvas)); + let area = if keep_effects { area.inflate(256) } else { area }; + buffer_surface(&photocraft_compose::render_layer_in(doc, &tmp, area), doc.pixel_format()) +} + +fn walk_ids(doc: &Document) -> Vec { + doc.walk().into_iter().map(|(_, _, l)| l.id).collect() +} + +pub(super) fn flatten_all_effects(s: &mut Session) -> Result { + let mut n = 0; + s.edit("Flatten All Layer Effects", |doc, _| { + for id in walk_ids(doc) { + let Some(l) = doc.layer(id) else { continue }; + if !has_live_effects(l) || matches!(l.content, LayerContent::Group(_) | LayerContent::Adjustment(_)) { + continue; + } + // The pixel and vector masks stay on the layer (baking must not destroy them), so the + // pixels are baked without them and each mask then applies once to the baked raster. + let px = bake(doc, l, true, false); + let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; + l.content = LayerContent::Raster(px); + l.effects = Default::default(); + l.fill_opacity = 1.0; + l.fill_cache = None; + l.psd_blocks.retain(|(k, _)| !matches!(k, b"TySh" | b"SoLd" | b"PlLd" | b"SoLE" | b"vmsk" | b"vsms" | b"vogk" | b"vscg" | b"vstk")); + n += 1; + } + Ok(()) + })?; + Ok(json!({"flattened": n})) +} + +pub(super) fn flatten_all_masks(s: &mut Session) -> Result { + let (mut n, mut skipped) = (0, 0); + s.edit("Flatten All Masks", |doc, _| { + for id in walk_ids(doc) { + let Some(l) = doc.layer(id) else { continue }; + let masked = l.mask.as_ref().is_some_and(|m| m.enabled) || l.vector_mask.is_some(); + if !masked { + continue; + } + if !matches!(l.content, LayerContent::Raster(_)) { + // Masks on groups, adjustment, type, shape and smart layers have no pixels to + // fold into; Photoshop's script leaves them too. + skipped += 1; + continue; + } + let px = bake(doc, l, false, true); + let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; + l.content = LayerContent::Raster(px); + l.mask = None; + l.vector_mask = None; + l.psd_blocks.retain(|(k, _)| !matches!(k, b"vmsk" | b"vsms")); + n += 1; + } + Ok(()) + })?; + Ok(json!({"flattened": n, "skipped": skipped})) +} diff --git a/crates/engine/src/cmd/file_cmds/save.rs b/crates/engine/src/cmd/file_cmds/save.rs new file mode 100644 index 0000000000..25104a7b13 --- /dev/null +++ b/crates/engine/src/cmd/file_cmds/save.rs @@ -0,0 +1,235 @@ +use super::paths::{same_file, write_file}; +use super::*; + +/// Whether saving `doc` as a TIFF writes Photoshop layer data (anything beyond a lone +/// Background layer). The UI asks before such a save when the "ask before saving layered TIFF" +/// preference is on; see `photocraft_io::tiff_layers`. +pub fn tiff_would_write_layers(doc: &Document) -> bool { + photocraft_io::tiff_layers::would_write_layers(doc) +} + +/// What a headless save writes beyond the format: JPEG quality and format, TIFF layers, Targa +/// bits, DPX bits, DDS compression and mipmaps, PSD previews and the PSD merged image. +#[derive(Debug, Clone, Copy)] +pub(crate) struct SaveOpts { + /// Photoshop's 0–12 JPEG scale. + pub quality: Option, + /// JPEG Options › Format Options (`"jpegFormat"`); unset, Baseline ("Standard"). + pub jpeg_format: Option, + /// TIFF: keep the layers. Off unless a command's params ask (`"tiffLayers": true`). + pub tiff_layers: bool, + /// Targa: 24 or 32 bits per pixel (`"tgaBits"`); unset, 32 with an alpha channel or + /// transparency, else 24. + pub tga_bits: Option, + /// DPX: 8, 10, 12 or 16 bits per sample (`"dpxBits"`); unset, 8 for an 8-bit document, else 16. + pub dpx_bits: Option, + /// TIFF: the image compression (`"tiffCompression": "none" | "lzw" | "zip"`); unset, none. + pub tiff_compression: Option, + /// DDS: the compression and whether to write the mip chain (`"ddsCompression"`, + /// `"ddsMipmaps"`); unset, uncompressed without mipmaps. + pub dds: photocraft_io::DdsOptions, + /// PSD/PSB: embed the thumbnail resource (Preferences › File Handling › Image Previews). + pub image_previews: bool, + /// PSD/PSB: write the real merged image (Preferences › File Handling › Maximize PSD and PSB + /// File Compatibility). + pub psd_maximize_compatibility: bool, +} + +impl Default for SaveOpts { + fn default() -> Self { + SaveOpts { + quality: None, + jpeg_format: None, + tiff_layers: false, + tga_bits: None, + dpx_bits: None, + tiff_compression: None, + dds: photocraft_io::DdsOptions::default(), + image_previews: true, + psd_maximize_compatibility: true, + } + } +} + +impl SaveOpts { + /// `quality`, `jpegFormat`, `tiffLayers` and `tgaBits` from command `cmd`'s params (a + /// `jpegFormat` it doesn't name or a `tgaBits` other than 24 or 32 is an error); the image + /// previews and the PSD merged image from the session's File Handling preferences (Ask When + /// Saving has no dialog here, so it saves them, as Photoshop's Save As checkbox and its + /// Maximize Compatibility checkbox both start on). + pub(crate) fn from_params(s: &Session, p: &Value, cmd: &str) -> Result { + let file_handling = &s.prefs().file_handling; + Ok(SaveOpts { + quality: f64_param(p, "quality"), + jpeg_format: jpeg_format_param(p, cmd)?, + tiff_layers: p.get("tiffLayers").and_then(Value::as_bool).unwrap_or(false), + tga_bits: tga_bits_param(p, cmd)?, + dpx_bits: dpx_bits_param(p, cmd)?, + tiff_compression: tiff_compression_param(p, cmd)?, + dds: dds_param(p, cmd)?.unwrap_or_default(), + image_previews: file_handling.image_previews != crate::prefs::Ask::Never, + psd_maximize_compatibility: file_handling.maximize_psd_compatibility != crate::prefs::Ask::Never, + }) + } + + pub(crate) fn or_quality(mut self, q: f64) -> Self { + self.quality = self.quality.or(Some(q)); + self + } +} + +impl From> for SaveOpts { + fn from(quality: Option) -> Self { + SaveOpts { quality, ..Default::default() } + } +} + +/// The Targa bits per pixel in `p` (`"tgaBits": 24 | 32`; absent or null: the automatic choice). +/// Anything else is a bad parameter of command `cmd`. Shared by every save that takes it (the +/// engine's commands, the app's Save As and control channel, the headless server). +pub fn tga_bits_param(p: &Value, cmd: &str) -> Result> { + match p.get("tgaBits") { + None | Some(Value::Null) => Ok(None), + Some(v) => v + .as_u64() + .and_then(photocraft_io::TgaBits::from_bits) + .map(Some) + .ok_or_else(|| EngineError::BadParams { cmd: cmd.into(), msg: format!("`tgaBits` must be 24 or 32, got {v}") }), + } +} + +/// The TIFF compression in `p` (`"tiffCompression": "none" | "lzw" | "zip"`, Photoshop's TIFF +/// Options; absent or null: none). Anything else is a bad parameter of command `cmd` (#5301). +pub fn tiff_compression_param(p: &Value, cmd: &str) -> Result> { + use photocraft_codecs::TiffCompression; + match p.get("tiffCompression") { + None | Some(Value::Null) => Ok(None), + Some(v) => match v.as_str() { + Some("none") => Ok(Some(TiffCompression::None)), + Some("lzw") => Ok(Some(TiffCompression::Lzw)), + Some("zip") => Ok(Some(TiffCompression::Deflate)), + _ => Err(EngineError::BadParams { cmd: cmd.into(), msg: format!("`tiffCompression` must be \"none\", \"lzw\" or \"zip\", got {v}") }), + }, + } +} + +/// The JPEG format in `p` (`"jpegFormat": "baseline" | "optimized" | "progressive"`; absent or +/// null: Baseline). Anything else is a bad parameter of command `cmd`. Shared like +/// [`tga_bits_param`]. +pub fn jpeg_format_param(p: &Value, cmd: &str) -> Result> { + match p.get("jpegFormat") { + None | Some(Value::Null) => Ok(None), + Some(v) => v.as_str().and_then(photocraft_codecs::JpegFormat::parse).map(Some).ok_or_else(|| EngineError::BadParams { + cmd: cmd.into(), + msg: format!("`jpegFormat` must be \"baseline\", \"optimized\" or \"progressive\", got {v}"), + }), + } +} + +/// Photoshop's 0–12 JPEG quality as the encoder's 1–100 (0 → 1, 12 → 100, linear between; out of +/// range is clamped, and NaN or infinite is 100). +pub fn jpeg_quality(q: f64) -> u8 { + if q.is_finite() { (q.clamp(0.0, 12.0) / 12.0 * 99.0 + 1.0).round() as u8 } else { 100 } +} + +/// The DPX bits per sample in `p` (`"dpxBits": 8 | 10 | 12 | 16`; absent or null: the document's +/// depth). Anything else is a bad parameter of command `cmd`. +pub fn dpx_bits_param(p: &Value, cmd: &str) -> Result> { + match p.get("dpxBits") { + None | Some(Value::Null) => Ok(None), + Some(v) => v + .as_u64() + .and_then(photocraft_io::DpxBits::from_bits) + .map(Some) + .ok_or_else(|| EngineError::BadParams { cmd: cmd.into(), msg: format!("`dpxBits` must be 8, 10, 12 or 16, got {v}") }), + } +} + +/// The DDS options in `p`: `"ddsCompression": "none" | "bc1" | "bc2" | "bc3"` (or the DXT names) +/// and `"ddsMipmaps": bool`. `None` when neither is given (Save As then asks); either alone +/// leaves the other at its default (uncompressed, no mipmaps). Anything else is a bad parameter +/// of command `cmd`. +pub fn dds_param(p: &Value, cmd: &str) -> Result> { + let bad = |msg: String| EngineError::BadParams { cmd: cmd.into(), msg }; + let compression = match p.get("ddsCompression") { + None | Some(Value::Null) => None, + Some(v) => Some( + v.as_str() + .and_then(photocraft_io::DdsCompression::from_name) + .ok_or_else(|| bad(format!("`ddsCompression` must be \"none\", \"bc1\", \"bc2\" or \"bc3\", got {v}")))?, + ), + }; + let mipmaps = match p.get("ddsMipmaps") { + None | Some(Value::Null) => None, + Some(v) => Some(v.as_bool().ok_or_else(|| bad(format!("`ddsMipmaps` must be true or false, got {v}")))?), + }; + if compression.is_none() && mipmaps.is_none() { + return Ok(None); + } + Ok(Some(photocraft_io::DdsOptions { compression: compression.unwrap_or_default(), mipmaps: mipmaps.unwrap_or(false) })) +} + +/// Encodes `doc` for `path`'s extension. +pub(crate) fn encode(doc: &Document, path: &str, save: impl Into) -> Result<(Vec, Vec)> { + crate::allocation::checkpoint("saving document")?; + let save = save.into(); + let mut opts = photocraft_io::ExportOptions { + tiff_layers: save.tiff_layers, + tga_bits: save.tga_bits, + image_previews: save.image_previews, + psd_maximize_compatibility: save.psd_maximize_compatibility, + // Linked files a PSD embeds are resolved against the document being worked on. + document_path: crate::doc_path::current(), + // An untrusted session's stored paths are document data: embed none of them. + read_linked_files: !crate::jobs::authorization_installed(), + ..Default::default() + }; + // No quality chosen: write the file the way it was opened (a JPEG at its own quality, a WebP + // lossy or lossless as it was), as Photoshop's Save does. + photocraft_io::apply_file_encoding(doc, &mut opts.encode); + opts.encode.dpx_bits = save.dpx_bits; + if let Some(c) = save.tiff_compression { + opts.encode.tiff_compression = c; + } + opts.encode.dds = save.dds; + if let Some(q) = save.quality { + let q = jpeg_quality(q); + opts.encode.jpeg_quality = q; + // A quality on a WebP save asks for the lossy encoder; the default WebP stays lossless. + opts.encode.webp_quality = q; + opts.encode.webp_lossless = false; + } + if let Some(f) = save.jpeg_format { + opts.encode.jpeg_format = f; + } + photocraft_io::export(doc, path, &opts).map(|r| (r.bytes, r.warnings)).map_err(|e| EngineError::Other(format!("{path}: {e}"))) +} + +pub(crate) fn save_doc(doc: &Document, path: &str, save: impl Into) -> Result> { + let (bytes, warnings) = encode(doc, path, save)?; + write_file(path, &bytes)?; + Ok(warnings) +} + +pub(super) fn save_a_copy(s: &mut Session, p: &Value) -> Result { + let path = str_param(p, "path", "file.saveACopy")?.to_string(); + let d = s.active().ok_or(EngineError::NoDocument)?; + // A copy over the document's own file replaces it, and a flat or lossy format can't be + // undone, so it takes an explicit `overwrite` (#7437). The desktop dialog writes through the + // shell, after the OS has confirmed the replace. + if d.path.as_deref().is_some_and(|own| same_file(&path, own)) && p.get("overwrite").and_then(Value::as_bool) != Some(true) { + return Err(EngineError::BadParams { + cmd: "file.saveACopy".into(), + msg: "`path` is the document's own file, so the copy would replace it: choose another path, or pass \"overwrite\": true".into(), + }); + } + let mut doc = (*d.doc).clone(); + if p.get("layers").and_then(Value::as_bool) == Some(false) { + // "Layers" unchecked in Save a Copy: write the flattened image. + let fmt = doc.pixel_format(); + let px = flattened_checked(&doc, fmt, "file.saveACopy")?; + doc.layers = vec![Layer::new("Background", LayerContent::Raster(px))]; + } + let warnings = save_doc(&doc, &path, SaveOpts::from_params(s, p, "file.saveACopy")?)?; + Ok(json!({"path": path, "warnings": warnings})) +} diff --git a/crates/engine/src/file_cmds/tests.rs b/crates/engine/src/cmd/file_cmds/tests.rs similarity index 100% rename from crates/engine/src/file_cmds/tests.rs rename to crates/engine/src/cmd/file_cmds/tests.rs diff --git a/crates/engine/src/fill_cmds.rs b/crates/engine/src/cmd/fill_cmds.rs similarity index 57% rename from crates/engine/src/fill_cmds.rs rename to crates/engine/src/cmd/fill_cmds.rs index 574241681a..35d25119a9 100644 --- a/crates/engine/src/fill_cmds.rs +++ b/crates/engine/src/cmd/fill_cmds.rs @@ -505,322 +505,4 @@ fn blend_tile(bytes: &mut [u8], fmt: &photocraft_color::PixelFormat, origin: Rec } #[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - - fn session() -> Session { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 40, "height": 30, "background": "transparent"})).unwrap(); - s - } - - fn px(s: &Session, x: i32, y: i32) -> [f32; 4] { - let st = s.active().unwrap(); - let l = st.doc.layer(st.active_layer.unwrap()).unwrap(); - l.surface().unwrap().rgba(x, y) - } - - fn close(a: [f32; 4], b: [f32; 4]) -> bool { - a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1.5 / 255.0) - } - - #[test] - fn history_fill_reads_only_the_selection_inside_the_canvas() { - let mut s = session(); - s.edit("selection", |doc, _| { - let mut selection = Surface::new(photocraft_color::PixelFormat::GRAY8); - selection.write_pixel(-2_000_000_000, -2_000_000_000, &[1.0]); - selection.write_pixel(4, 4, &[1.0]); - doc.selection = Some(selection); - Ok(()) - }) - .unwrap(); - // Reading the full sparse selection rectangle overflows the allocation size; - // only its intersection with this small canvas is meaningful to Fill. - s.execute(CMD, json!({"contents": "history"})).unwrap(); - assert!(s.undo()); - assert!(s.active().unwrap().doc.selection.as_ref().unwrap().sample_channel(4, 4, 0) > 0.0); - } - - #[test] - fn every_constant_contents() { - let mut s = session(); - s.execute("tools.setColors", json!({"foreground": [1.0, 0.0, 0.0, 1.0], "background": [0.0, 0.0, 1.0, 1.0]})).unwrap(); - for (c, want) in [ - ("foreground", [1.0, 0.0, 0.0, 1.0]), - ("background", [0.0, 0.0, 1.0, 1.0]), - ("black", [0.0, 0.0, 0.0, 1.0]), - ("gray", [128.0 / 255.0, 128.0 / 255.0, 128.0 / 255.0, 1.0]), - ("white", [1.0; 4]), - ] { - s.execute(CMD, json!({"contents": c})).unwrap(); - assert!(close(px(&s, 5, 5), want), "{c}: {:?}", px(&s, 5, 5)); - } - s.execute(CMD, json!({"contents": "color", "color": "#00ff00"})).unwrap(); - assert!(close(px(&s, 5, 5), [0.0, 1.0, 0.0, 1.0])); - // The old form: a colour, or the foreground. - s.execute(CMD, json!({"color": "#ffff00"})).unwrap(); - assert!(close(px(&s, 5, 5), [1.0, 1.0, 0.0, 1.0])); - } - - #[test] - fn opacity_mode_and_preserve_transparency() { - let mut s = session(); - s.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 30})).unwrap(); - s.execute(CMD, json!({"contents": "white"})).unwrap(); - s.execute("select.deselect", json!({})).unwrap(); - // Preserve Transparency: the empty right half stays empty. - s.execute(CMD, json!({"contents": "black", "opacity": 50, "preserveTransparency": true})).unwrap(); - assert!(close(px(&s, 5, 5), [0.5, 0.5, 0.5, 1.0]), "{:?}", px(&s, 5, 5)); - assert_eq!(px(&s, 30, 5)[3], 0.0); - // Multiply with white leaves the grey. - s.execute(CMD, json!({"contents": "white", "mode": "multiply", "preserveTransparency": true})).unwrap(); - assert!(close(px(&s, 5, 5), [0.5, 0.5, 0.5, 1.0])); - // Without it, the transparent half is filled. - s.execute(CMD, json!({"contents": "white", "opacity": 100})).unwrap(); - assert_eq!(px(&s, 30, 5), [1.0; 4]); - // Dissolve paints whole pixels only. - s.execute(CMD, json!({"contents": "black", "mode": "dissolve", "opacity": 50})).unwrap(); - let st = s.active().unwrap(); - let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); - let blacks = (0..40).flat_map(|x| (0..30).map(move |y| (x, y))).filter(|&(x, y)| surf.rgba(x, y)[0] < 0.01).count(); - assert!(blacks > 300 && blacks < 900, "{blacks}"); - assert!((0..40).all(|x| { - let v = surf.rgba(x, 3)[0]; - v.is_finite() && !(0.01..=0.99).contains(&v) - })); - } - - #[test] - fn preserve_transparency_blends_source_atop_on_semi_transparent_pixels() { - // White at 50%, then black at 50% keeping alpha: Photoshop gives (127,127,127,128), the - // colour moved halfway, at every depth and in non-Normal modes too (#5783). - for depth in [8, 16, 32] { - for mode in ["normal", "multiply"] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 8, "height": 8, "depth": depth, "background": "transparent"})).unwrap(); - s.execute(CMD, json!({"contents": "white", "opacity": 50})).unwrap(); - s.execute(CMD, json!({"contents": "black", "opacity": 50, "mode": mode, "preserveTransparency": true})).unwrap(); - assert!(close(px(&s, 3, 3), [0.5, 0.5, 0.5, 0.5]), "{depth} {mode} {:?}", px(&s, 3, 3)); - } - } - } - - #[test] - fn history_pattern_and_content_aware() { - let mut s = session(); - s.execute(CMD, json!({"contents": "white"})).unwrap(); - s.execute(CMD, json!({"contents": "black"})).unwrap(); - // History: back to state 1 (after the white fill). - s.execute(CMD, json!({"contents": "history", "state": 1})).unwrap(); - assert_eq!(px(&s, 5, 5), [1.0; 4]); - // The default source is the oldest state: the empty layer. - s.execute(CMD, json!({"contents": "history"})).unwrap(); - assert_eq!(px(&s, 5, 5)[3], 0.0); - assert!(s.execute(CMD, json!({"contents": "history", "state": 999})).is_err()); - let r = s.execute(CMD, json!({"contents": "pattern", "pattern": "Diagonal Lines"})).unwrap(); - assert!(r["pattern"].is_string()); - assert!(px(&s, 5, 5)[3] > 0.0); - // Content-Aware fills the hole from what is around it. - s.execute(CMD, json!({"contents": "color", "color": "#336699"})).unwrap(); - s.execute("select.rect", json!({"x": 15, "y": 10, "width": 6, "height": 6})).unwrap(); - s.execute(CMD, json!({"contents": "white"})).unwrap(); - s.execute(CMD, json!({"contents": "contentAware", "colorAdaptation": false})).unwrap(); - assert!(close(px(&s, 17, 12), [0x33 as f32 / 255.0, 0x66 as f32 / 255.0, 0x99 as f32 / 255.0, 1.0]), "{:?}", px(&s, 17, 12)); - } - - #[test] - fn history_fill_reads_a_source_when_its_pixels_were_locked() { - // Given a white layer locked in history state 1, then unlocked and filled red. - let mut s = Session::new(); - s.execute("file.new", json!({"width": 16, "height": 16, "background": "white"})).unwrap(); - s.execute("layer.lockLayers", json!({"pixels": true})).unwrap(); - s.execute("layer.lockLayers", json!({"pixels": false})).unwrap(); - s.execute(CMD, json!({"color": "#ff0000"})).unwrap(); - - // When Fill reads the locked historical pixels. - let result = s.execute(CMD, json!({"contents": "history", "state": 1})); - - // Then it restores white; the historical lock limits edits, not reads. - assert!(result.is_ok(), "{result:?}"); - assert!(close(px(&s, 8, 8), [1.0; 4]), "{:?}", px(&s, 8, 8)); - } - - #[test] - fn history_fill_refuses_a_locked_destination_when_source_is_unlocked() { - // Given an unlocked white source and a red, currently locked destination. - let mut s = Session::new(); - s.execute("file.new", json!({"width": 16, "height": 16, "background": "white"})).unwrap(); - s.execute(CMD, json!({"color": "#ff0000"})).unwrap(); - s.execute("layer.lockLayers", json!({"pixels": true})).unwrap(); - - // When Fill reads the unlocked source and attempts to write to the locked destination. - let result = s.execute(CMD, json!({"contents": "history", "state": 0})); - - // Then the destination lock still rejects the edit and preserves red pixels. - assert!(result.is_err()); - assert!(close(px(&s, 8, 8), [1.0, 0.0, 0.0, 1.0]), "{:?}", px(&s, 8, 8)); - } - - /// `cargo test -p photocraft-engine --release --lib fill_cmds::tests::timing_24mp -- --ignored --nocapture` - #[test] - #[ignore] - fn timing_24mp() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 6000, "height": 4000, "background": "white"})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.execute(CMD, json!({"contents": "white"})).unwrap(); - let time = |s: &mut Session, label: &str, p: Value| { - let mut v = Vec::new(); - for i in 0..5 { - let mut p = p.clone(); - if p.get("contents").is_none() { - p["color"] = json!(if i % 2 == 0 { "#336699" } else { "#996633" }); - } - let t = std::time::Instant::now(); - s.execute(CMD, p).unwrap(); - v.push(t.elapsed().as_secs_f64() * 1000.0); - } - v.sort_by(f64::total_cmp); - println!("{label:<48} median {:>8.1} ms min {:>8.1} ms", v[2], v[0]); - }; - time(&mut s, "colour, no selection", json!({})); - time(&mut s, "colour, preserve transparency", json!({"preserveTransparency": true})); - time(&mut s, "colour 50% multiply", json!({"opacity": 50, "mode": "multiply"})); - s.execute("select.rect", json!({"x": 100, "y": 100, "width": 5000, "height": 3000})).unwrap(); - time(&mut s, "colour, 15 MP rectangle selection", json!({})); - s.execute("select.deselect", json!({})).unwrap(); - // The old per-pixel f32 path, for comparison. - let st = s.active().unwrap(); - let mut surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().clone(); - let t = std::time::Instant::now(); - crate::pixels::try_fill_surface(&mut surf, Rect::new(0, 0, 6000, 4000), [0.2, 0.4, 0.6, 1.0], None, false).unwrap(); - println!("{:<48} {:>8.1} ms", "fallible fill_surface, no selection", t.elapsed().as_secs_f64() * 1000.0); - } - - #[test] - fn bad_params_are_errors() { - let mut s = session(); - for p in [ - json!({"contents": "plaid"}), - json!({"contents": 3}), - json!({"mode": "sideways"}), - json!({"mode": "passThrough"}), - json!({"opacity": "lots"}), - json!({"preserveTransparency": "yes"}), - json!({"contents": "contentAware"}), - json!({"contents": "pattern", "pattern": "no such pattern"}), - json!({"contents": "history", "state": -1}), - json!({"contents": "contentAware", "colorAdaptation": 1}), - ] { - assert!(s.execute(CMD, p.clone()).is_err(), "{p}"); - } - // Everything selected leaves nothing to sample from. - s.execute("select.all", json!({})).unwrap(); - assert!(s.execute(CMD, json!({"contents": "contentAware"})).is_err()); - // Out-of-range opacity is clamped. - s.execute(CMD, json!({"contents": "white", "opacity": 1e300})).unwrap(); - } - - /// A session whose canvas is `size` and whose selection is the given (sparse) rectangles, as - /// a loaded `.pcraft` can declare (#963): the canvas size is not capped on load and the - /// selection tiles can lie far apart. Nothing here allocates more than a few tiles. - fn huge_selection(size: (u32, u32), rects: &[Rect]) -> Session { - let mut s = session(); - s.execute(CMD, json!({"contents": "color", "color": "#336699"})).unwrap(); - let st = s.active_mut().unwrap(); - let doc = std::sync::Arc::make_mut(&mut st.doc); - doc.size = photocraft_geom::Size::new(size.0, size.1); - let mut sel = Surface::new(photocraft_color::PixelFormat::GRAY8); - for r in rects { - sel.fill_rect(*r, &[1.0]); - } - doc.selection = Some(sel); - s - } - - /// Content-Aware fill on a selection whose extent overflows the sampling-window arithmetic - /// (#963) returns the size error and leaves the document and history untouched. - #[test] - fn content_aware_huge_extent_is_an_error() { - // Largest extent whose `ext * 3` still fits in u32. - const EDGE: i32 = (u32::MAX / 3) as i32; - let max = i32::MAX; - let cases: [(&str, (u32, u32), Vec); 7] = [ - // The issue's repro: a second selection tile 5 600 000 tiles to the right. - ("issue repro", (2_000_000_000, 2_000_000_000), vec![Rect::new(0, 0, 8, 8), Rect::new(5_600_000 * TILE_SIZE, 0, 5_600_000 * TILE_SIZE + 8, 8)]), - ("wide, just above", (2_000_000_000, 2_000_000_000), vec![Rect::new(0, 0, 1, 1), Rect::new(EDGE, 0, EDGE + 1, 1)]), - ("tall, just above", (2_000_000_000, 2_000_000_000), vec![Rect::new(0, 0, 1, 1), Rect::new(0, EDGE, 1, EDGE + 1)]), - ("wide, just below", (2_000_000_000, 2_000_000_000), vec![Rect::new(0, 0, 1, 1), Rect::new(EDGE - 1, 0, EDGE, 1)]), - ("tall, just below", (2_000_000_000, 2_000_000_000), vec![Rect::new(0, 0, 1, 1), Rect::new(0, EDGE - 1, 1, EDGE)]), - // The largest canvas a Rect can hold, selected corner to corner, plus a piece off the - // canvas at the most negative coordinate. - ( - "extreme coordinates", - (max as u32, max as u32), - vec![Rect::new(i32::MIN, i32::MIN, i32::MIN + 1, i32::MIN + 1), Rect::new(0, 0, 1, 1), Rect::new(max - 2, max - 2, max - 1, max - 1)], - ), - // A canvas wider than a Rect can hold is treated as empty, never as a panic. - ("canvas beyond i32", (u32::MAX, u32::MAX), vec![Rect::new(0, 0, 1, 1), Rect::new(max - 2, 0, max - 1, 1)]), - ]; - for (name, size, rects) in cases { - let mut s = huge_selection(size, &rects); - let before = s.active().unwrap().doc.clone(); - let past = s.active().unwrap().history.past_len(); - let r = s.execute(CMD, json!({"contents": "contentAware", "colorAdaptation": false})); - let err = r.expect_err(name).to_string(); - assert!(!err.contains("internal error"), "{name}: {err}"); - if name != "canvas beyond i32" { - assert!(err.contains("too large for Content-Aware fill"), "{name}: {err}"); - } - let st = s.active().unwrap(); - assert!(std::sync::Arc::ptr_eq(&before, &st.doc), "{name}: the document changed"); - assert_eq!(st.history.past_len(), past, "{name}: a history step was recorded"); - assert!(close(px(&s, 5, 5), [0x33 as f32 / 255.0, 0x66 as f32 / 255.0, 0x99 as f32 / 255.0, 1.0]), "{name}"); - } - // Control: an ordinary selection still fills from its surroundings. - let mut s = huge_selection((40, 30), &[Rect::new(15, 10, 21, 16)]); - s.execute(CMD, json!({"contents": "white"})).unwrap(); - s.execute(CMD, json!({"contents": "contentAware", "colorAdaptation": false})).unwrap(); - assert!(close(px(&s, 17, 12), [0x33 as f32 / 255.0, 0x66 as f32 / 255.0, 0x99 as f32 / 255.0, 1.0]), "{:?}", px(&s, 17, 12)); - } - - /// A Stroke, Fill or Clear inside a selection keeps the tiles the selection doesn't reach as - /// they were (shared with the history), instead of storing a copy of each (#4517). - #[test] - fn unselected_tiles_stay_shared() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 1024, "height": 1024, "background": "white"})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.execute("edit.fill", json!({"color": "#336699"})).unwrap(); - let id = s.active().unwrap().active_layer.unwrap(); - let surf = |s: &Session| s.active().unwrap().doc.layer(id).unwrap().surface().unwrap().clone(); - for (cmd, params) in [ - ("edit.fill", json!({"color": "#ff0000"})), - ("edit.stroke", json!({"width": 4, "color": "#00ff00", "location": "inside"})), - ("edit.clear", json!({})), - ] { - // Two small selections in opposite corners (256 px tiles): the selection's bounds - // span every tile, but only the two corner tiles have anything selected. - s.execute("select.rect", json!({"x": 20, "y": 20, "width": 100, "height": 100})).unwrap(); - s.execute("select.rect", json!({"x": 900, "y": 900, "width": 100, "height": 100, "mode": "add"})).unwrap(); - let before = surf(&s); - s.execute(cmd, params).unwrap(); - let after = surf(&s); - let corners = [photocraft_geom::Rect::new(0, 0, 256, 256), photocraft_geom::Rect::new(768, 768, 1024, 1024)]; - let mut kept = 0; - for (c, t) in before.tiles() { - if corners.iter().all(|r| c.rect().intersect(r).is_empty()) { - assert!(after.tile(*c).is_some_and(|a| std::sync::Arc::ptr_eq(a, t)), "{cmd}: unselected tile {c:?} was copied"); - kept += 1; - } - } - assert_eq!(kept, 14, "{cmd}: the 14 tiles between the corners"); - for r in corners { - assert_ne!(before.read_region(r), after.read_region(r), "{cmd} changed the selected corner {r:?}"); - } - s.execute("select.deselect", json!({})).unwrap(); - } - } -} +mod tests; diff --git a/crates/engine/src/cmd/fill_cmds/tests.rs b/crates/engine/src/cmd/fill_cmds/tests.rs new file mode 100644 index 0000000000..bf46b6f4a6 --- /dev/null +++ b/crates/engine/src/cmd/fill_cmds/tests.rs @@ -0,0 +1,315 @@ +use super::*; +use serde_json::json; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 40, "height": 30, "background": "transparent"})).unwrap(); + s +} + +fn px(s: &Session, x: i32, y: i32) -> [f32; 4] { + let st = s.active().unwrap(); + let l = st.doc.layer(st.active_layer.unwrap()).unwrap(); + l.surface().unwrap().rgba(x, y) +} + +fn close(a: [f32; 4], b: [f32; 4]) -> bool { + a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1.5 / 255.0) +} + +#[test] +fn history_fill_reads_only_the_selection_inside_the_canvas() { + let mut s = session(); + s.edit("selection", |doc, _| { + let mut selection = Surface::new(photocraft_color::PixelFormat::GRAY8); + selection.write_pixel(-2_000_000_000, -2_000_000_000, &[1.0]); + selection.write_pixel(4, 4, &[1.0]); + doc.selection = Some(selection); + Ok(()) + }) + .unwrap(); + // Reading the full sparse selection rectangle overflows the allocation size; + // only its intersection with this small canvas is meaningful to Fill. + s.execute(CMD, json!({"contents": "history"})).unwrap(); + assert!(s.undo()); + assert!(s.active().unwrap().doc.selection.as_ref().unwrap().sample_channel(4, 4, 0) > 0.0); +} + +#[test] +fn every_constant_contents() { + let mut s = session(); + s.execute("tools.setColors", json!({"foreground": [1.0, 0.0, 0.0, 1.0], "background": [0.0, 0.0, 1.0, 1.0]})).unwrap(); + for (c, want) in [ + ("foreground", [1.0, 0.0, 0.0, 1.0]), + ("background", [0.0, 0.0, 1.0, 1.0]), + ("black", [0.0, 0.0, 0.0, 1.0]), + ("gray", [128.0 / 255.0, 128.0 / 255.0, 128.0 / 255.0, 1.0]), + ("white", [1.0; 4]), + ] { + s.execute(CMD, json!({"contents": c})).unwrap(); + assert!(close(px(&s, 5, 5), want), "{c}: {:?}", px(&s, 5, 5)); + } + s.execute(CMD, json!({"contents": "color", "color": "#00ff00"})).unwrap(); + assert!(close(px(&s, 5, 5), [0.0, 1.0, 0.0, 1.0])); + // The old form: a colour, or the foreground. + s.execute(CMD, json!({"color": "#ffff00"})).unwrap(); + assert!(close(px(&s, 5, 5), [1.0, 1.0, 0.0, 1.0])); +} + +#[test] +fn opacity_mode_and_preserve_transparency() { + let mut s = session(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 30})).unwrap(); + s.execute(CMD, json!({"contents": "white"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + // Preserve Transparency: the empty right half stays empty. + s.execute(CMD, json!({"contents": "black", "opacity": 50, "preserveTransparency": true})).unwrap(); + assert!(close(px(&s, 5, 5), [0.5, 0.5, 0.5, 1.0]), "{:?}", px(&s, 5, 5)); + assert_eq!(px(&s, 30, 5)[3], 0.0); + // Multiply with white leaves the grey. + s.execute(CMD, json!({"contents": "white", "mode": "multiply", "preserveTransparency": true})).unwrap(); + assert!(close(px(&s, 5, 5), [0.5, 0.5, 0.5, 1.0])); + // Without it, the transparent half is filled. + s.execute(CMD, json!({"contents": "white", "opacity": 100})).unwrap(); + assert_eq!(px(&s, 30, 5), [1.0; 4]); + // Dissolve paints whole pixels only. + s.execute(CMD, json!({"contents": "black", "mode": "dissolve", "opacity": 50})).unwrap(); + let st = s.active().unwrap(); + let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); + let blacks = (0..40).flat_map(|x| (0..30).map(move |y| (x, y))).filter(|&(x, y)| surf.rgba(x, y)[0] < 0.01).count(); + assert!(blacks > 300 && blacks < 900, "{blacks}"); + assert!((0..40).all(|x| { + let v = surf.rgba(x, 3)[0]; + v.is_finite() && !(0.01..=0.99).contains(&v) + })); +} + +#[test] +fn preserve_transparency_blends_source_atop_on_semi_transparent_pixels() { + // White at 50%, then black at 50% keeping alpha: Photoshop gives (127,127,127,128), the + // colour moved halfway, at every depth and in non-Normal modes too (#5783). + for depth in [8, 16, 32] { + for mode in ["normal", "multiply"] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8, "depth": depth, "background": "transparent"})).unwrap(); + s.execute(CMD, json!({"contents": "white", "opacity": 50})).unwrap(); + s.execute(CMD, json!({"contents": "black", "opacity": 50, "mode": mode, "preserveTransparency": true})).unwrap(); + assert!(close(px(&s, 3, 3), [0.5, 0.5, 0.5, 0.5]), "{depth} {mode} {:?}", px(&s, 3, 3)); + } + } +} + +#[test] +fn history_pattern_and_content_aware() { + let mut s = session(); + s.execute(CMD, json!({"contents": "white"})).unwrap(); + s.execute(CMD, json!({"contents": "black"})).unwrap(); + // History: back to state 1 (after the white fill). + s.execute(CMD, json!({"contents": "history", "state": 1})).unwrap(); + assert_eq!(px(&s, 5, 5), [1.0; 4]); + // The default source is the oldest state: the empty layer. + s.execute(CMD, json!({"contents": "history"})).unwrap(); + assert_eq!(px(&s, 5, 5)[3], 0.0); + assert!(s.execute(CMD, json!({"contents": "history", "state": 999})).is_err()); + let r = s.execute(CMD, json!({"contents": "pattern", "pattern": "Diagonal Lines"})).unwrap(); + assert!(r["pattern"].is_string()); + assert!(px(&s, 5, 5)[3] > 0.0); + // Content-Aware fills the hole from what is around it. + s.execute(CMD, json!({"contents": "color", "color": "#336699"})).unwrap(); + s.execute("select.rect", json!({"x": 15, "y": 10, "width": 6, "height": 6})).unwrap(); + s.execute(CMD, json!({"contents": "white"})).unwrap(); + s.execute(CMD, json!({"contents": "contentAware", "colorAdaptation": false})).unwrap(); + assert!(close(px(&s, 17, 12), [0x33 as f32 / 255.0, 0x66 as f32 / 255.0, 0x99 as f32 / 255.0, 1.0]), "{:?}", px(&s, 17, 12)); +} + +#[test] +fn history_fill_reads_a_source_when_its_pixels_were_locked() { + // Given a white layer locked in history state 1, then unlocked and filled red. + let mut s = Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16, "background": "white"})).unwrap(); + s.execute("layer.lockLayers", json!({"pixels": true})).unwrap(); + s.execute("layer.lockLayers", json!({"pixels": false})).unwrap(); + s.execute(CMD, json!({"color": "#ff0000"})).unwrap(); + + // When Fill reads the locked historical pixels. + let result = s.execute(CMD, json!({"contents": "history", "state": 1})); + + // Then it restores white; the historical lock limits edits, not reads. + assert!(result.is_ok(), "{result:?}"); + assert!(close(px(&s, 8, 8), [1.0; 4]), "{:?}", px(&s, 8, 8)); +} + +#[test] +fn history_fill_refuses_a_locked_destination_when_source_is_unlocked() { + // Given an unlocked white source and a red, currently locked destination. + let mut s = Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16, "background": "white"})).unwrap(); + s.execute(CMD, json!({"color": "#ff0000"})).unwrap(); + s.execute("layer.lockLayers", json!({"pixels": true})).unwrap(); + + // When Fill reads the unlocked source and attempts to write to the locked destination. + let result = s.execute(CMD, json!({"contents": "history", "state": 0})); + + // Then the destination lock still rejects the edit and preserves red pixels. + assert!(result.is_err()); + assert!(close(px(&s, 8, 8), [1.0, 0.0, 0.0, 1.0]), "{:?}", px(&s, 8, 8)); +} + +/// `cargo test -p photocraft-engine --release --lib fill_cmds::tests::timing_24mp -- --ignored --nocapture` +#[test] +#[ignore] +fn timing_24mp() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 6000, "height": 4000, "background": "white"})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute(CMD, json!({"contents": "white"})).unwrap(); + let time = |s: &mut Session, label: &str, p: Value| { + let mut v = Vec::new(); + for i in 0..5 { + let mut p = p.clone(); + if p.get("contents").is_none() { + p["color"] = json!(if i % 2 == 0 { "#336699" } else { "#996633" }); + } + let t = std::time::Instant::now(); + s.execute(CMD, p).unwrap(); + v.push(t.elapsed().as_secs_f64() * 1000.0); + } + v.sort_by(f64::total_cmp); + println!("{label:<48} median {:>8.1} ms min {:>8.1} ms", v[2], v[0]); + }; + time(&mut s, "colour, no selection", json!({})); + time(&mut s, "colour, preserve transparency", json!({"preserveTransparency": true})); + time(&mut s, "colour 50% multiply", json!({"opacity": 50, "mode": "multiply"})); + s.execute("select.rect", json!({"x": 100, "y": 100, "width": 5000, "height": 3000})).unwrap(); + time(&mut s, "colour, 15 MP rectangle selection", json!({})); + s.execute("select.deselect", json!({})).unwrap(); + // The old per-pixel f32 path, for comparison. + let st = s.active().unwrap(); + let mut surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().clone(); + let t = std::time::Instant::now(); + crate::pixels::try_fill_surface(&mut surf, Rect::new(0, 0, 6000, 4000), [0.2, 0.4, 0.6, 1.0], None, false).unwrap(); + println!("{:<48} {:>8.1} ms", "fallible fill_surface, no selection", t.elapsed().as_secs_f64() * 1000.0); +} + +#[test] +fn bad_params_are_errors() { + let mut s = session(); + for p in [ + json!({"contents": "plaid"}), + json!({"contents": 3}), + json!({"mode": "sideways"}), + json!({"mode": "passThrough"}), + json!({"opacity": "lots"}), + json!({"preserveTransparency": "yes"}), + json!({"contents": "contentAware"}), + json!({"contents": "pattern", "pattern": "no such pattern"}), + json!({"contents": "history", "state": -1}), + json!({"contents": "contentAware", "colorAdaptation": 1}), + ] { + assert!(s.execute(CMD, p.clone()).is_err(), "{p}"); + } + // Everything selected leaves nothing to sample from. + s.execute("select.all", json!({})).unwrap(); + assert!(s.execute(CMD, json!({"contents": "contentAware"})).is_err()); + // Out-of-range opacity is clamped. + s.execute(CMD, json!({"contents": "white", "opacity": 1e300})).unwrap(); +} + +/// A session whose canvas is `size` and whose selection is the given (sparse) rectangles, as +/// a loaded `.pcraft` can declare (#963): the canvas size is not capped on load and the +/// selection tiles can lie far apart. Nothing here allocates more than a few tiles. +fn huge_selection(size: (u32, u32), rects: &[Rect]) -> Session { + let mut s = session(); + s.execute(CMD, json!({"contents": "color", "color": "#336699"})).unwrap(); + let st = s.active_mut().unwrap(); + let doc = std::sync::Arc::make_mut(&mut st.doc); + doc.size = photocraft_geom::Size::new(size.0, size.1); + let mut sel = Surface::new(photocraft_color::PixelFormat::GRAY8); + for r in rects { + sel.fill_rect(*r, &[1.0]); + } + doc.selection = Some(sel); + s +} + +/// Content-Aware fill on a selection whose extent overflows the sampling-window arithmetic +/// (#963) returns the size error and leaves the document and history untouched. +#[test] +fn content_aware_huge_extent_is_an_error() { + // Largest extent whose `ext * 3` still fits in u32. + const EDGE: i32 = (u32::MAX / 3) as i32; + let max = i32::MAX; + let cases: [(&str, (u32, u32), Vec); 7] = [ + // The issue's repro: a second selection tile 5 600 000 tiles to the right. + ("issue repro", (2_000_000_000, 2_000_000_000), vec![Rect::new(0, 0, 8, 8), Rect::new(5_600_000 * TILE_SIZE, 0, 5_600_000 * TILE_SIZE + 8, 8)]), + ("wide, just above", (2_000_000_000, 2_000_000_000), vec![Rect::new(0, 0, 1, 1), Rect::new(EDGE, 0, EDGE + 1, 1)]), + ("tall, just above", (2_000_000_000, 2_000_000_000), vec![Rect::new(0, 0, 1, 1), Rect::new(0, EDGE, 1, EDGE + 1)]), + ("wide, just below", (2_000_000_000, 2_000_000_000), vec![Rect::new(0, 0, 1, 1), Rect::new(EDGE - 1, 0, EDGE, 1)]), + ("tall, just below", (2_000_000_000, 2_000_000_000), vec![Rect::new(0, 0, 1, 1), Rect::new(0, EDGE - 1, 1, EDGE)]), + // The largest canvas a Rect can hold, selected corner to corner, plus a piece off the + // canvas at the most negative coordinate. + ( + "extreme coordinates", + (max as u32, max as u32), + vec![Rect::new(i32::MIN, i32::MIN, i32::MIN + 1, i32::MIN + 1), Rect::new(0, 0, 1, 1), Rect::new(max - 2, max - 2, max - 1, max - 1)], + ), + // A canvas wider than a Rect can hold is treated as empty, never as a panic. + ("canvas beyond i32", (u32::MAX, u32::MAX), vec![Rect::new(0, 0, 1, 1), Rect::new(max - 2, 0, max - 1, 1)]), + ]; + for (name, size, rects) in cases { + let mut s = huge_selection(size, &rects); + let before = s.active().unwrap().doc.clone(); + let past = s.active().unwrap().history.past_len(); + let r = s.execute(CMD, json!({"contents": "contentAware", "colorAdaptation": false})); + let err = r.expect_err(name).to_string(); + assert!(!err.contains("internal error"), "{name}: {err}"); + if name != "canvas beyond i32" { + assert!(err.contains("too large for Content-Aware fill"), "{name}: {err}"); + } + let st = s.active().unwrap(); + assert!(std::sync::Arc::ptr_eq(&before, &st.doc), "{name}: the document changed"); + assert_eq!(st.history.past_len(), past, "{name}: a history step was recorded"); + assert!(close(px(&s, 5, 5), [0x33 as f32 / 255.0, 0x66 as f32 / 255.0, 0x99 as f32 / 255.0, 1.0]), "{name}"); + } + // Control: an ordinary selection still fills from its surroundings. + let mut s = huge_selection((40, 30), &[Rect::new(15, 10, 21, 16)]); + s.execute(CMD, json!({"contents": "white"})).unwrap(); + s.execute(CMD, json!({"contents": "contentAware", "colorAdaptation": false})).unwrap(); + assert!(close(px(&s, 17, 12), [0x33 as f32 / 255.0, 0x66 as f32 / 255.0, 0x99 as f32 / 255.0, 1.0]), "{:?}", px(&s, 17, 12)); +} + +/// A Stroke, Fill or Clear inside a selection keeps the tiles the selection doesn't reach as +/// they were (shared with the history), instead of storing a copy of each (#4517). +#[test] +fn unselected_tiles_stay_shared() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 1024, "height": 1024, "background": "white"})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("edit.fill", json!({"color": "#336699"})).unwrap(); + let id = s.active().unwrap().active_layer.unwrap(); + let surf = |s: &Session| s.active().unwrap().doc.layer(id).unwrap().surface().unwrap().clone(); + for (cmd, params) in + [("edit.fill", json!({"color": "#ff0000"})), ("edit.stroke", json!({"width": 4, "color": "#00ff00", "location": "inside"})), ("edit.clear", json!({}))] + { + // Two small selections in opposite corners (256 px tiles): the selection's bounds + // span every tile, but only the two corner tiles have anything selected. + s.execute("select.rect", json!({"x": 20, "y": 20, "width": 100, "height": 100})).unwrap(); + s.execute("select.rect", json!({"x": 900, "y": 900, "width": 100, "height": 100, "mode": "add"})).unwrap(); + let before = surf(&s); + s.execute(cmd, params).unwrap(); + let after = surf(&s); + let corners = [photocraft_geom::Rect::new(0, 0, 256, 256), photocraft_geom::Rect::new(768, 768, 1024, 1024)]; + let mut kept = 0; + for (c, t) in before.tiles() { + if corners.iter().all(|r| c.rect().intersect(r).is_empty()) { + assert!(after.tile(*c).is_some_and(|a| std::sync::Arc::ptr_eq(a, t)), "{cmd}: unselected tile {c:?} was copied"); + kept += 1; + } + } + assert_eq!(kept, 14, "{cmd}: the 14 tiles between the corners"); + for r in corners { + assert_ne!(before.read_region(r), after.read_region(r), "{cmd} changed the selected corner {r:?}"); + } + s.execute("select.deselect", json!({})).unwrap(); + } +} diff --git a/crates/engine/src/fill_key_cmds.rs b/crates/engine/src/cmd/fill_key_cmds.rs similarity index 100% rename from crates/engine/src/fill_key_cmds.rs rename to crates/engine/src/cmd/fill_key_cmds.rs diff --git a/crates/engine/src/float_cmds.rs b/crates/engine/src/cmd/float_cmds.rs similarity index 100% rename from crates/engine/src/float_cmds.rs rename to crates/engine/src/cmd/float_cmds.rs diff --git a/crates/engine/src/float_cmds/tests.rs b/crates/engine/src/cmd/float_cmds/tests.rs similarity index 100% rename from crates/engine/src/float_cmds/tests.rs rename to crates/engine/src/cmd/float_cmds/tests.rs diff --git a/crates/engine/src/frame_cmds.rs b/crates/engine/src/cmd/frame_cmds.rs similarity index 100% rename from crates/engine/src/frame_cmds.rs rename to crates/engine/src/cmd/frame_cmds.rs diff --git a/crates/engine/src/fx_view_cmds.rs b/crates/engine/src/cmd/fx_view_cmds.rs similarity index 100% rename from crates/engine/src/fx_view_cmds.rs rename to crates/engine/src/cmd/fx_view_cmds.rs diff --git a/crates/engine/src/fx_visibility_cmds.rs b/crates/engine/src/cmd/fx_visibility_cmds.rs similarity index 100% rename from crates/engine/src/fx_visibility_cmds.rs rename to crates/engine/src/cmd/fx_visibility_cmds.rs diff --git a/crates/engine/src/gallery_cmds.rs b/crates/engine/src/cmd/gallery_cmds.rs similarity index 100% rename from crates/engine/src/gallery_cmds.rs rename to crates/engine/src/cmd/gallery_cmds.rs diff --git a/crates/engine/src/gallery_cmds/tests.rs b/crates/engine/src/cmd/gallery_cmds/tests.rs similarity index 100% rename from crates/engine/src/gallery_cmds/tests.rs rename to crates/engine/src/cmd/gallery_cmds/tests.rs diff --git a/crates/engine/src/gradient_fill_cmds.rs b/crates/engine/src/cmd/gradient_fill_cmds.rs similarity index 100% rename from crates/engine/src/gradient_fill_cmds.rs rename to crates/engine/src/cmd/gradient_fill_cmds.rs diff --git a/crates/engine/src/gradient_fill_cmds/tests.rs b/crates/engine/src/cmd/gradient_fill_cmds/tests.rs similarity index 100% rename from crates/engine/src/gradient_fill_cmds/tests.rs rename to crates/engine/src/cmd/gradient_fill_cmds/tests.rs diff --git a/crates/engine/src/group_view_cmds.rs b/crates/engine/src/cmd/group_view_cmds.rs similarity index 100% rename from crates/engine/src/group_view_cmds.rs rename to crates/engine/src/cmd/group_view_cmds.rs diff --git a/crates/engine/src/history_cmds.rs b/crates/engine/src/cmd/history_cmds.rs similarity index 100% rename from crates/engine/src/history_cmds.rs rename to crates/engine/src/cmd/history_cmds.rs diff --git a/crates/engine/src/history_menu_cmds.rs b/crates/engine/src/cmd/history_menu_cmds.rs similarity index 100% rename from crates/engine/src/history_menu_cmds.rs rename to crates/engine/src/cmd/history_menu_cmds.rs diff --git a/crates/engine/src/history_select_cmds.rs b/crates/engine/src/cmd/history_select_cmds.rs similarity index 100% rename from crates/engine/src/history_select_cmds.rs rename to crates/engine/src/cmd/history_select_cmds.rs diff --git a/crates/engine/src/history_source_cmds.rs b/crates/engine/src/cmd/history_source_cmds.rs similarity index 100% rename from crates/engine/src/history_source_cmds.rs rename to crates/engine/src/cmd/history_source_cmds.rs diff --git a/crates/engine/src/cmd/image_cmds.rs b/crates/engine/src/cmd/image_cmds.rs new file mode 100644 index 0000000000..17f87691c8 --- /dev/null +++ b/crates/engine/src/cmd/image_cmds.rs @@ -0,0 +1,1041 @@ +//! Image menu: Image Size, Canvas Size, Crop, Trim, Mode (colour model and +//! bit depth) conversions, Duplicate. + +use std::convert::Infallible; + +use photocraft_algo::resample::{Resample, crop_surface, resize_surface_in_canvas, translate_surface}; +use photocraft_color::{ColorMode, SampleType}; +use photocraft_doc::{Document, Effect, Effects, FxPaint, Layer, LayerContent, LayerId, Size}; +use photocraft_geom::Rect; +use photocraft_raster::Surface; +use serde_json::{Value, json}; + +use crate::commands::CommandSpec; +use crate::{EngineError, Result, Session}; + +fn has_doc(s: &Session) -> std::result::Result<(), String> { + s.active().map(|_| ()).ok_or_else(|| "no document open".into()) +} + +/// Applies `f` to every pixel surface of a layer tree: content (raster or +/// cached text/shape/smart pixels), fill caches, stored video frames (current and original), +/// and (if `masks`) masks. +pub(crate) fn for_each_surface(layers: &mut [Layer], masks: bool, f: &mut dyn FnMut(&mut Surface, bool)) { + for l in layers { + if masks && let Some(m) = &mut l.mask { + f(&mut m.surface, true); + } + if let Some(fc) = &mut l.fill_cache { + f(&mut fc.surface, false); + } + // The displayed content is only a copy of the frame at the playhead; the other frames + // would keep the old geometry and depth and come back stale when scrubbing (#4956). + if let Some(v) = &mut l.video { + for frame in v.frames.iter_mut().chain(v.original_frames.iter_mut().flatten()) { + f(frame, false); + } + } + match &mut l.content { + LayerContent::Raster(s) => f(s, false), + LayerContent::Text(t) => { + if let Some(c) = &mut t.cache { + f(c, false) + } + } + LayerContent::Shape(sh) => { + if let Some(c) = &mut sh.cache { + f(c, false) + } + } + LayerContent::Smart(sm) => { + if let Some(c) = &mut sm.cache { + f(c, false) + } + // Selection-derived smart-filter masks live in document coordinates. Every + // canvas resize/translation must carry them with the smart object's cache; + // otherwise toggling a filter recomputes its coverage at stale positions (#3077). + if masks && let Some(mask) = &mut sm.filter_mask { + f(&mut mask.surface, true); + } + } + LayerContent::Group(g) => for_each_surface(&mut g.children, masks, f), + _ => {} + } + } +} + +/// Drops every fill cache of a layer tree. A fill layer covers the whole canvas, but its cache +/// (the pixels a PSD stored) only the old one: after the canvas grows the fill must re-render +/// from its model, or the added area stays transparent (#7362). +fn drop_fill_caches(layers: &mut [Layer]) { + for l in layers { + l.fill_cache = None; + if let LayerContent::Group(g) = &mut l.content { + drop_fill_caches(&mut g.children); + } + } +} + +/// Converts every pixel surface of a layer tree (masks included) to `depth`. +pub(crate) fn convert_layers_depth(layers: &mut [Layer], depth: SampleType) { + for_each_surface(layers, true, &mut |surf, _| { + let f = surf.format().with_sample(depth); + *surf = surf.convert(f); + }); +} + +pub(crate) fn for_each_layer(layers: &mut [Layer], f: &mut dyn FnMut(&mut Layer)) { + for l in layers { + f(l); + if let Some(ch) = l.children_mut() { + for_each_layer(ch, f); + } + } +} + +/// Assign new layer ids to a copied document and update every saved layer reference. +/// +/// A document copy needs fresh identities, but its comps and variable definitions must +/// still target the copied layers. Deliberately leave references to already-deleted +/// layers untouched so their missing-layer warnings remain meaningful. The same applies +/// to Last Document State. +pub(crate) fn reidentify_copied_layers(doc: &mut Document) { + let mut ids = std::collections::HashMap::new(); + for_each_layer(&mut doc.layers, &mut |layer| { + let previous = layer.id; + layer.id = LayerId::fresh(); + ids.insert(previous, layer.id); + }); + + let remap = |comp: &mut photocraft_doc::LayerComp| { + for state in &mut comp.states { + if let Some(&new_id) = ids.get(&state.layer) { + state.layer = new_id; + } + } + }; + for comp in &mut doc.layer_comps { + remap(comp); + } + if let Some(last) = &mut doc.last_document_state { + remap(last); + } + for def in &mut doc.variables.defs { + if let Some(&new_id) = ids.get(&def.layer) { + def.layer = new_id; + } + } + for slice in &mut doc.slices.list { + if let Some(&new_id) = slice.layer.and_then(|layer| ids.get(&layer)) { + slice.layer = Some(new_id); + } + } +} + +/// Scale every size and distance of a style by `k` (Image Size's Scale Styles, Layer Style › +/// Scale Effects, and previews that draw a style at a reduced resolution). +pub fn scale_effects(fx: &mut Effects, k: f32) { + for e in &mut fx.items { + match e { + Effect::DropShadow(s) | Effect::InnerShadow(s) => { + s.distance *= k; + s.size *= k; + } + Effect::OuterGlow(g) | Effect::InnerGlow(g) => g.size *= k, + Effect::Stroke(s) => s.size *= k, + Effect::Satin(s) => { + s.distance *= k; + s.size *= k; + } + Effect::BevelEmboss(b) => { + b.size *= k; + b.soften *= k; + } + Effect::PatternOverlay { scale, .. } => *scale *= k, + Effect::GradientOverlay { .. } | Effect::ColorOverlay { .. } => {} + } + if let Effect::Stroke(s) = e + && let FxPaint::Pattern { scale, .. } = &mut s.paint + { + *scale *= k; + } + } + // Effects changed: the preserved PSD block no longer applies. + if k != 1.0 { + fx.psd_raw = None; + } +} + +/// Image Size's resampling methods; `None` changes the resolution only. +#[derive(Clone, Copy)] +enum Method { + None, + Filter(Resample), + /// Photoshop's Automatic: Preserve Details where the image grows, Bicubic Sharper otherwise. + Automatic, +} + +fn parse_resample(s: &str) -> Method { + Method::Filter(match s { + "none" => return Method::None, + "automatic" => return Method::Automatic, + "nearest" | "nearestNeighbor" => Resample::Nearest, + "bilinear" => Resample::Bilinear, + "bicubicSmoother" => Resample::BicubicSmoother, + "bicubicSharper" => Resample::BicubicSharper, + "bicubicAutomatic" => Resample::BicubicAutomatic, + "lanczos" => Resample::Lanczos, + "preserveDetails" => Resample::PreserveDetails, + _ => Resample::Bicubic, + }) +} + +/// The largest raster Image Size resamples to: the decoders' default allocation budget. +const MAX_RESAMPLE_BYTES: u64 = if cfg!(target_pointer_width = "64") { 8 << 30 } else { 2 << 30 }; + +/// Image → Image Size. +fn image_size(s: &mut Session, p: &Value) -> Result { + let d = s.active().ok_or(EngineError::NoDocument)?; + let (ow, oh) = (d.doc.size.width, d.doc.size.height); + let resample = parse_resample(p.get("resample").and_then(Value::as_str).unwrap_or("bicubic")); + // An Indexed Color document holds only its colour table's colours, and a save quantises to + // them: interpolation showed blends that the saved file didn't have (#6019). + let resample = match resample { + Method::Filter(_) | Method::Automatic if d.doc.mode == ColorMode::Indexed => Method::Filter(Resample::Nearest), + m => m, + }; + let mut pw = p.get("width").and_then(Value::as_f64); + let mut ph = p.get("height").and_then(Value::as_f64); + // `percent` scales both sides (what a Photoshop action records as "200%"); an explicit side wins. + if let Some(pc) = p.get("percent") { + let pc = pc.as_f64().filter(|v| v.is_finite() && *v > 0.0).ok_or_else(|| bad("image.imageSize", "`percent` must be a positive number"))?; + pw = pw.or(Some(ow as f64 * pc / 100.0)); + ph = ph.or(Some(oh as f64 * pc / 100.0)); + } + // `keepPrintSize`: only the resolution given, the pixels follow it (Photoshop's Image Size + // with Resample on, as an action records it). + if p.get("keepPrintSize").and_then(Value::as_bool) == Some(true) + && pw.is_none() + && ph.is_none() + && let Some(r) = p.get("resolution").and_then(Value::as_f64) + { + let r = r.clamp(1.0, 10_000.0); + let old = f64::from(d.doc.resolution_dpi).max(1.0); + pw = Some(ow as f64 * r / old); + ph = Some(oh as f64 * r / old); + } + // Missing dimension keeps the aspect ratio. + let (nw, nh) = match (pw, ph) { + (Some(w), Some(h)) => (w, h), + (Some(w), None) => (w, w * oh as f64 / ow.max(1) as f64), + (None, Some(h)) => (h * ow as f64 / oh.max(1) as f64, h), + (None, None) => (ow as f64, oh as f64), + }; + let (nw, nh) = (nw.round().clamp(1.0, 300_000.0) as u32, nh.round().clamp(1.0, 300_000.0) as u32); + // Each side may reach 300000 px, but resampling writes real pixels: refuse a canvas whose + // raster alone would pass the budget, before allocating any of it (#1544). + if !matches!(resample, Method::None) && (nw, nh) != (ow, oh) { + check_resample_budget("image.imageSize", &d.doc, nw, nh, ", or turn Resample off to change only the resolution")?; + } + let dpi = p.get("resolution").and_then(Value::as_f64).map(|v| v as f32); + if !matches!(resample, Method::None) && (nw, nh) != (ow, oh) { + // Color Sampler points scale with the pixels (same map `transform_geometry` applies). + let (sx, sy) = (f64::from(nw) / f64::from(ow.max(1)), f64::from(nh) / f64::from(oh.max(1))); + s.set_sampler_map(photocraft_geom::Affine { m: [sx, 0.0, 0.0, sy, 0.0, 0.0] }); + } + s.edit("Image Size", |doc, _| { + if let Some(r) = dpi { + // Type keeps its pixel size; resampling below then scales it with the pixels. + crate::canvas_geom::set_resolution(doc, r.clamp(1.0, 10_000.0)); + } + let filter = match resample { + Method::None => return Ok(()), + Method::Filter(f) => f, + Method::Automatic if nw > ow || nh > oh => Resample::PreserveDetails, + Method::Automatic => Resample::BicubicSharper, + }; + resample_doc(doc, nw, nh, filter); + Ok(()) + })?; + // The size the document has now: without resampling `width`/`height` are ignored (#1815). + let size = s.active().ok_or(EngineError::NoDocument)?.doc.size; + Ok(json!({ "width": size.width, "height": size.height })) +} + +/// Refuses to resample `doc` to `nw` x `nh` px when the raster alone would pass the budget, before +/// allocating any of it (#1544). `hint` ends the message with what the caller can do instead. +pub(crate) fn check_resample_budget(cmd: &str, doc: &Document, nw: u32, nh: u32, hint: &str) -> Result<()> { + let bpp = doc.pixel_format().bytes_per_pixel().max(1) as u64; + let bytes = u64::from(nw).saturating_mul(u64::from(nh)).saturating_mul(bpp); + if bytes <= MAX_RESAMPLE_BYTES { + return Ok(()); + } + let mp = u64::from(nw).saturating_mul(u64::from(nh)) / 1_000_000; + let max_mp = MAX_RESAMPLE_BYTES / bpp / 1_000_000; + Err(bad(cmd, format!("{nw} x {nh} px is {mp} megapixels; resampling at this bit depth is limited to {max_mp} megapixels. Choose a smaller size{hint}"))) +} + +/// Like [`check_resample_budget`] for a command that, besides resampling the document to +/// `nw` x `nh` px, holds `work_bytes_per_px` more bytes per pixel of full-canvas working buffers +/// (a composite, a mask, an output layer) at once. +pub(crate) fn check_working_budget(cmd: &str, doc: &Document, nw: u32, nh: u32, work_bytes_per_px: u64, hint: &str) -> Result<()> { + let bpp = (doc.pixel_format().bytes_per_pixel().max(1) as u64).saturating_add(work_bytes_per_px); + let px = u64::from(nw).saturating_mul(u64::from(nh)); + if px.saturating_mul(bpp) <= MAX_RESAMPLE_BYTES { + return Ok(()); + } + let max_mp = MAX_RESAMPLE_BYTES / bpp / 1_000_000; + Err(bad(cmd, format!("{nw} x {nh} px is {} megapixels; this conversion is limited to {max_mp} megapixels. Choose a smaller size{hint}", px / 1_000_000))) +} + +/// Resamples the whole document (pixels, masks, channels, selection, effects, vectors, guides) to +/// `nw` x `nh` px with `filter`: the body of Image Size, shared by the Crop tool's W x H x Resolution +/// mode. Callers check [`check_resample_budget`] first. +pub(crate) fn resample_doc(doc: &mut Document, nw: u32, nh: u32, filter: Resample) { + let (ow, oh) = (doc.size.width, doc.size.height); + let (sx, sy) = (nw as f64 / ow.max(1) as f64, nh as f64 / oh.max(1) as f64); + if (sx - 1.0).abs() < 1e-12 && (sy - 1.0).abs() < 1e-12 { + return; + } + // Content that reaches the canvas edge keeps it: a Background stays opaque to the border. + let canvas = Rect::from_xywh(0, 0, ow, oh); + let taken = crate::smart_cmds::take_caches(&mut doc.layers); + for_each_surface(&mut doc.layers, true, &mut |surf, is_mask| { + *surf = resize_surface_in_canvas(surf, sx, sy, if is_mask { Resample::Bilinear } else { filter }, canvas); + }); + let k = ((sx + sy) / 2.0) as f32; + for_each_layer(&mut doc.layers, &mut |l| { + scale_effects(&mut l.effects, k); + // Canvas resampling scales the whole appearance, including shape strokes (#8341). + // Dash lengths and offsets are already expressed in multiples of this width. + if let LayerContent::Shape(sh) = &mut l.content + && let Some(stroke) = &mut sh.stroke + { + stroke.width *= k; + } + }); + for ch in doc.channels.iter_mut().chain(doc.quick_mask.as_mut()) { + ch.surface = resize_surface_in_canvas(&ch.surface, sx, sy, Resample::Bilinear, canvas); + } + if let Some(sel) = &doc.selection { + doc.selection = Some(resize_surface_in_canvas(sel, sx, sy, Resample::Bilinear, canvas)); + } + // Vector geometry, guides and marks scale with the pixels; vectors re-render sharp. + crate::canvas_geom::transform_geometry(doc, &photocraft_geom::Affine { m: [sx, 0.0, 0.0, sy, 0.0, 0.0] }); + doc.size = Size::new(nw, nh); + crate::canvas_geom::refresh(doc, crate::canvas_geom::Refresh::All); + let Ok(()) = crate::smart_cmds::restore_unrendered(doc, taken, |c| Ok::<_, Infallible>(resize_surface_in_canvas(c, sx, sy, filter, canvas))); +} + +fn bad(cmd: &str, msg: impl Into) -> EngineError { + EngineError::BadParams { cmd: cmd.into(), msg: msg.into() } +} + +/// The flattened document, or an error when the canvas is over the compositor's render cap +/// ([`photocraft_compose::MAX_RENDER_PIXELS`]; `flatten` returns an empty buffer then). +fn flatten_whole(doc: &Document, cmd: &str) -> Result { + let buf = photocraft_compose::flatten(doc); + let (w, h) = (doc.size.width, doc.size.height); + if buf.px.len() as u64 != u64::from(w) * u64::from(h) { + return Err(bad(cmd, format!("the document ({w} x {h} px) is too large to flatten (limit {} pixels)", photocraft_compose::MAX_RENDER_PIXELS))); + } + Ok(buf) +} + +/// Moves every surface, channel, selection and guide by `(dx, dy)`. +/// +/// Fails, before moving anything, when some pixels would land outside the i32 coordinate +/// range: the surface copy saturates its target rectangle there, which no longer matches +/// the pixel data and panics (#959). +pub(crate) fn translate_doc(doc: &mut Document, cmd: &str, dx: i32, dy: i32) -> Result<()> { + if dx == 0 && dy == 0 { + return Ok(()); + } + let fits = |r: Rect| { + r.is_empty() || (r.x0.checked_add(dx).is_some() && r.x1.checked_add(dx).is_some() && r.y0.checked_add(dy).is_some() && r.y1.checked_add(dy).is_some()) + }; + let mut ok = true; + for_each_surface(&mut doc.layers, true, &mut |surf, _| ok = ok && fits(surf.content_bounds())); + ok = ok + && doc.channels.iter().chain(doc.quick_mask.as_ref()).all(|ch| fits(ch.surface.content_bounds())) + && doc.selection.as_ref().is_none_or(|sel| fits(sel.content_bounds())); + if !ok { + return Err(bad(cmd, format!("moving the document by ({dx}, {dy}) would push its pixels outside the 32-bit coordinate range"))); + } + for_each_surface(&mut doc.layers, true, &mut |surf, _| *surf = translate_surface(surf, dx, dy)); + for ch in doc.channels.iter_mut().chain(doc.quick_mask.as_mut()) { + ch.surface = translate_surface(&ch.surface, dx, dy); + } + if let Some(sel) = &doc.selection { + doc.selection = Some(translate_surface(sel, dx, dy)); + } + // Type, shapes, smart objects, vector masks, paths, guides, slices, notes… (caches above + // are already translated exactly, so nothing needs re-rendering for the move itself). + crate::canvas_geom::transform_geometry(doc, &photocraft_geom::Affine::translate(f64::from(dx), f64::from(dy))); + Ok(()) +} + +/// Delete Cropped Pixels on a layer tree: crops pixel-layer data only to `r`. Type and smart +/// objects move by shifting their rendered pixels, so cutting those would clip them at the old +/// edge. A video layer's stored frames are its pixels too: the displayed content is only the frame +/// at the playhead, so the others would bring the cropped pixels back when scrubbing (#4956). +fn delete_cropped_pixels(layers: &mut [Layer], r: Rect) { + for_each_layer(layers, &mut |l| { + if let Some(fc) = &mut l.fill_cache { + fc.surface = crop_surface(&fc.surface, r); + } + if let Some(v) = &mut l.video { + for frame in v.frames.iter_mut().chain(v.original_frames.iter_mut().flatten()) { + *frame = crop_surface(frame, r); + } + } + if let LayerContent::Raster(s) = &mut l.content { + *s = crop_surface(s, r); + } + }); +} + +/// Crops the document to `r` (in current document coordinates). +/// A frame that extends past the canvas fills the Background's new area with `extension` (the +/// background colour, as Photoshop's Crop tool does); other layers get transparent pixels there. +fn crop_doc(doc: &mut Document, cmd: &str, r: Rect, delete_pixels: bool, extension: [f32; 4]) -> Result<()> { + // The origin moves to (0, 0); `-i32::MIN` has no i32 value (#959). + let (Some(dx), Some(dy)) = (r.x0.checked_neg(), r.y0.checked_neg()) else { + return Err(bad(cmd, format!("the crop origin ({}, {}) can't be moved to (0, 0) within the 32-bit coordinate range", r.x0, r.y0))); + }; + let old_canvas = doc.bounds(); + let extends = r.x0 < old_canvas.x0 || r.y0 < old_canvas.y0 || r.x1 > old_canvas.x1 || r.y1 > old_canvas.y1; + if delete_pixels { + delete_cropped_pixels(&mut doc.layers, r); + } + translate_doc(doc, cmd, dx, dy)?; + doc.size = Size::new(r.width(), r.height()); + // A Background cannot hold transparent pixels: like an opaque Canvas Size extension, the area + // an extending Crop adds is filled with the extension (background) colour. + if extends + && let Some(bg) = doc.background_mut() + && let LayerContent::Raster(surf) = &mut bg.content + { + let old = old_canvas.translate(dx, dy); + let px = photocraft_raster::from_rgba(&surf.format(), [extension[0], extension[1], extension[2], 1.0]); + fill_background_extension(surf, Rect::from_xywh(0, 0, r.width(), r.height()), old, &px); + } + if extends { + drop_fill_caches(&mut doc.layers); + } + crate::canvas_geom::refresh(doc, crate::canvas_geom::Refresh::Shapes); + Ok(()) +} + +/// Fills the area an extension adds to the Background's `canvas` (all of it outside the `old` +/// canvas, and any gap there) with `px`, under the pixels the Background already holds there: +/// those a crop with Delete Cropped Pixels off hid show again instead of being painted over (#7086). +/// Only the added strips are touched, so the cost follows the added area, not the canvas. +fn fill_background_extension(surf: &mut Surface, canvas: Rect, old: Rect, px: &[f32]) { + let keep = surf.content_bounds().intersect(&old).intersect(&canvas); + let strips = if keep.is_empty() { + vec![canvas] + } else { + vec![ + Rect::new(canvas.x0, canvas.y0, canvas.x1, keep.y0), + Rect::new(canvas.x0, keep.y1, canvas.x1, canvas.y1), + Rect::new(canvas.x0, keep.y0, keep.x0, keep.y1), + Rect::new(keep.x1, keep.y0, canvas.x1, keep.y1), + ] + }; + let n = surf.channels(); + let a = n.saturating_sub(1); + let pa = px.get(a).copied().unwrap_or(1.0); + // Without an alpha channel hidden pixels can't be told from empty ones: fill the strips. + let has_alpha = surf.format().alpha; + for strip in strips.into_iter().filter(|r| !r.is_empty()) { + if !has_alpha || !surf.has_tiles_in(strip) { + surf.fill_rect(strip, px); + continue; + } + // The Background's own pixels over `px` (source-over). + let mut d = surf.read_region(strip); + for p in d.chunks_exact_mut(n) { + let ta = p.get(a).copied().unwrap_or(0.0); + let oa = ta + pa * (1.0 - ta); + for (c, &f) in p.iter_mut().zip(px).take(a) { + *c = if oa > 0.0 { (*c * ta + f * pa * (1.0 - ta)) / oa } else { 0.0 }; + } + if let Some(alpha) = p.get_mut(a) { + *alpha = oa; + } + } + surf.write_region(strip, &d); + } +} + +/// The nine documented canvas-size anchors, in the order the command lists them, each mapped to +/// its (x, y) factor (0.0 = top/left edge, 0.5 = centre, 1.0 = bottom/right edge). +const ANCHORS: [(&str, (f64, f64)); 9] = [ + ("topLeft", (0.0, 0.0)), + ("top", (0.5, 0.0)), + ("topRight", (1.0, 0.0)), + ("left", (0.0, 0.5)), + ("center", (0.5, 0.5)), + ("right", (1.0, 0.5)), + ("bottomLeft", (0.0, 1.0)), + ("bottom", (0.5, 1.0)), + ("bottomRight", (1.0, 1.0)), +]; + +/// Resolves an anchor name to its (x, y) factors, matching the nine documented values exactly. +/// Anything else is an error naming `anchor` and listing them, rather than resolving the two axes +/// independently (which let a misspelling like `"topleft"` land between two valid anchors, #2946). +fn anchor_factors(cmd: &str, a: &str) -> Result<(f64, f64)> { + ANCHORS.iter().find(|(name, _)| *name == a).map(|&(_, f)| f).ok_or_else(|| { + let names = ANCHORS.iter().map(|&(n, _)| n).collect::>().join("|"); + bad(cmd, format!("`anchor` must be one of {names}")) + }) +} + +fn extension_color(s: &Session, p: &Value) -> [f32; 4] { + match p.get("extensionColor").and_then(Value::as_str).unwrap_or("background") { + "foreground" => s.tools.foreground, + "white" => [1.0; 4], + "black" => [0.0, 0.0, 0.0, 1.0], + "transparent" => [0.0; 4], + hex if hex.starts_with('#') => { + let h = hex.trim_start_matches('#'); + let c = |i: usize| h.get(i..i + 2).and_then(|x| u8::from_str_radix(x, 16).ok()).map_or(0.0, |v| f32::from(v) / 255.0); + [c(0), c(2), c(4), 1.0] + } + _ => s.tools.background, + } +} + +/// Image → Canvas Size. +fn canvas_size(s: &mut Session, p: &Value) -> Result { + let d = s.active().ok_or(EngineError::NoDocument)?; + let (ow, oh) = (d.doc.size.width as f64, d.doc.size.height as f64); + let relative = p.get("relative").and_then(Value::as_bool).unwrap_or(false); + let w = p.get("width").and_then(Value::as_f64).unwrap_or(if relative { 0.0 } else { ow }); + let h = p.get("height").and_then(Value::as_f64).unwrap_or(if relative { 0.0 } else { oh }); + let (nw, nh) = if relative { (ow + w, oh + h) } else { (w, h) }; + let (nw, nh) = (nw.round().clamp(1.0, 300_000.0) as u32, nh.round().clamp(1.0, 300_000.0) as u32); + let (ax, ay) = anchor_factors("image.canvasSize", p.get("anchor").and_then(Value::as_str).unwrap_or("center"))?; + let dx = ((nw as f64 - ow) * ax).round() as i32; + let dy = ((nh as f64 - oh) * ay).round() as i32; + let ext = extension_color(s, p); + s.set_sampler_map(photocraft_geom::Affine::translate(f64::from(dx), f64::from(dy))); + s.edit("Canvas Size", |doc, _| { + translate_doc(doc, "image.canvasSize", dx, dy)?; + doc.size = Size::new(nw, nh); + if nw > ow as u32 || nh > oh as u32 { + drop_fill_caches(&mut doc.layers); + } + crate::canvas_geom::refresh(doc, crate::canvas_geom::Refresh::Shapes); + let canvas = doc.bounds(); + let old = Rect::from_xywh(dx, dy, ow as u32, oh as u32); + // A Background cannot contain transparent pixels. When a transparent + // extension adds canvas area, make it a normal paintable layer first. + // A shrink or no-op resize must not silently convert the Background. + if ext[3] == 0.0 + && (nw > ow as u32 || nh > oh as u32) + && let Some(bg) = doc.background_mut() + { + crate::extra_cmds::unlock_background(bg); + } + // The locked Background layer is extended with the extension colour. + if ext[3] > 0.0 + && let Some(bg) = doc.background_mut() + && let LayerContent::Raster(surf) = &mut bg.content + { + let px = photocraft_raster::from_rgba(&surf.format(), ext); + fill_background_extension(surf, canvas, old, &px); + } + Ok(()) + })?; + Ok(json!({ "width": nw, "height": nh, "offset": [dx, dy] })) +} + +/// The largest side an explicit crop may give the canvas (the `file.new` and Canvas Size limit). +const MAX_CROP_SIDE: i32 = 300_000; + +/// Image → Crop (to the selection bounds). +fn crop(s: &mut Session, p: &Value) -> Result { + let delete = p.get("deleteCroppedPixels").and_then(Value::as_bool).unwrap_or(true); + // The Crop tool's Fill: Content-Aware Fill of what the crop uncovers (#3823). + let content_aware = match p.get("contentAware") { + None | Some(Value::Null) => false, + Some(Value::Bool(b)) => *b, + Some(v) => return Err(bad("image.crop", format!("`contentAware` must be true or false, not {v}"))), + }; + // Values beyond i32 would wrap through the narrowing casts into a rectangle unrelated to + // the numbers passed; reject them (see `commands::int_i32`). + let explicit = match ( + crate::commands::int_i32("image.crop", p, "x")?, + crate::commands::int_i32("image.crop", p, "y")?, + crate::commands::int_i32("image.crop", p, "width")?, + crate::commands::int_i32("image.crop", p, "height")?, + ) { + (Some(x), Some(y), Some(w), Some(h)) if w > 0 && h > 0 => { + // The new canvas size: refuse what File › New, Image Size and Canvas Size won't make, + // before anything changes. Unbounded, a following full-canvas flatten (Trim, Duplicate + // Merged) aborted on allocation (#960). + if w > MAX_CROP_SIDE || h > MAX_CROP_SIDE { + return Err(bad("image.crop", format!("{w} x {h} exceeds the {MAX_CROP_SIDE} px limit per side"))); + } + // A far edge past i32::MAX used to saturate, silently cropping less than asked (#959). + let end = |o: i32, len: i32, ko: &str, kl: &str| { + o.checked_add(len) + .ok_or_else(|| bad("image.crop", format!("`{ko}` + `{kl}` = {} is outside the 32-bit coordinate range", i64::from(o) + i64::from(len)))) + }; + Some(Rect::new(x, y, end(x, w, "x", "width")?, end(y, h, "y", "height")?)) + } + _ => None, + }; + let target = crop_target(p)?; + if let Some((tw, th)) = target.size { + let d = s.active().ok_or(EngineError::NoDocument)?; + check_resample_budget("image.crop", &d.doc, tw, th, "")?; + } + if let Some(a) = crop_angle(p)? { + let rect = explicit.ok_or_else(|| bad("image.crop", "an `angle` needs an explicit `x`, `y`, `width` and `height`"))?; + return rotated_crop(s, rect, a, delete, content_aware, &target); + } + // An explicit rectangle (the Crop tool) may extend past the canvas; a selection crop is clamped. + let r = explicit + .or_else(|| s.active().and_then(|d| d.doc.selection.as_ref().map(|sel| sel.content_bounds().intersect(&d.doc.bounds())))) + .unwrap_or(Rect::EMPTY); + if r.is_empty() { + return Err(EngineError::Other("nothing to crop: pass x/y/width/height or make a selection".into())); + } + s.set_sampler_map(target.sampler_map(r)); + let extension = s.tools.background; + s.edit("Crop", |doc, active| { + let original = doc.size; + crop_doc(doc, "image.crop", r, delete, extension)?; + // A straight crop fills all of the area past the old canvas, pixels an earlier Delete Cropped + // Pixels off crop hid there included, as Photoshop does; only a turned frame keeps them (#8060). + if content_aware { + crate::crop_fill::fill_uncovered(doc, *active, &crate::crop_fill::Coverage::crop(r, original.width, original.height))?; + } + doc.selection = None; + target.apply(doc); + Ok(()) + })?; + Ok(crop_result(s, json!({ "x": r.x0, "y": r.y0, "width": r.width(), "height": r.height() }))) +} + +/// The Crop tool's W x H x Resolution: the size (px) the cropped area is resampled to and the +/// resolution the document gets, both optional. +struct CropTarget { + size: Option<(u32, u32)>, + resolution: Option, + filter: Resample, +} + +impl CropTarget { + /// Applies the target to a document that has just been cropped (inside the crop's history step). + fn apply(&self, doc: &mut Document) { + if let Some((w, h)) = self.size { + // As for Image Size: an Indexed Color document holds only its colour table's colours (#6019). + let filter = if doc.mode == ColorMode::Indexed { Resample::Nearest } else { self.filter }; + resample_doc(doc, w, h, filter); + } + if let Some(r) = self.resolution { + doc.resolution_dpi = r; + } + } + + /// Where Color Sampler points go: shifted by the crop's origin, then scaled with the pixels + /// when [`Self::apply`] resamples the cropped area `r` (as Image Size scales them). + fn sampler_map(&self, r: Rect) -> photocraft_geom::Affine { + let shift = photocraft_geom::Affine::translate(-f64::from(r.x0), -f64::from(r.y0)); + match self.size { + Some((w, h)) if r.width() > 0 && r.height() > 0 => { + let (sx, sy) = (f64::from(w) / f64::from(r.width()), f64::from(h) / f64::from(r.height())); + shift.then(&photocraft_geom::Affine { m: [sx, 0.0, 0.0, sy, 0.0, 0.0] }) + } + _ => shift, + } + } +} + +/// The highest resolution (ppi) a crop may set, as for Image Size. +const MAX_CROP_RESOLUTION: f64 = 10_000.0; + +/// `image.crop`'s optional `targetWidth`/`targetHeight` (whole px, both or neither), `resolution` +/// (ppi) and `resample` (as for `image.imageSize`; "none" is refused with a target size). +fn crop_target(p: &Value) -> Result { + const CMD: &str = "image.crop"; + let side = |key: &str| -> Result> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + // Whole-number floats (`100.0`) count too, as for the crop rectangle. + Some(v) => v + .as_u64() + .or_else(|| v.as_f64().filter(|f| f.fract() == 0.0 && (0.0..=f64::from(MAX_CROP_SIDE)).contains(f)).map(|f| f as u64)) + .and_then(|n| u32::try_from(n).ok()) + .filter(|n| (1..=MAX_CROP_SIDE as u32).contains(n)) + .map(Some) + .ok_or_else(|| bad(CMD, format!("`{key}` = {v} must be a whole number of pixels from 1 to {MAX_CROP_SIDE}"))), + } + }; + let size = match (side("targetWidth")?, side("targetHeight")?) { + (Some(w), Some(h)) => Some((w, h)), + (None, None) => None, + _ => return Err(bad(CMD, "`targetWidth` and `targetHeight` go together")), + }; + let resolution = match p.get("resolution") { + None | Some(Value::Null) => None, + Some(v) => { + let r = v.as_f64().filter(|r| r.is_finite() && (1.0..=MAX_CROP_RESOLUTION).contains(r)); + Some(r.ok_or_else(|| bad(CMD, format!("`resolution` = {v} must be a number of pixels per inch from 1 to {MAX_CROP_RESOLUTION}")))? as f32) + } + }; + let filter = match p.get("resample") { + None | Some(Value::Null) => Some(Resample::Bicubic), + Some(v) => match parse_resample(v.as_str().ok_or_else(|| bad(CMD, "`resample` must be a string"))?) { + Method::None => None, + Method::Filter(f) => Some(f), + // The direction is known only once the frame is: bicubic's own automatic choice. + Method::Automatic => Some(Resample::BicubicAutomatic), + }, + }; + let filter = match (filter, size) { + (Some(f), _) => f, + (None, None) => Resample::Bicubic, + (None, Some(_)) => return Err(bad(CMD, "a `targetWidth` x `targetHeight` crop needs resampling: `resample` can't be \"none\"")), + }; + Ok(CropTarget { size, resolution, filter }) +} + +/// A crop's result: the frame it cropped to, plus the document's size and resolution afterwards. +fn crop_result(s: &Session, mut frame: Value) -> Value { + if let (Some(d), Some(o)) = (s.active(), frame.as_object_mut()) { + o.insert("documentWidth".into(), json!(d.doc.size.width)); + o.insert("documentHeight".into(), json!(d.doc.size.height)); + o.insert("resolution".into(), json!(d.doc.resolution_dpi)); + } + frame +} + +/// The largest crop angle accepted (degrees), as for Image Rotation › Arbitrary. +const MAX_CROP_ANGLE: f64 = 3600.0; + +/// `image.crop`'s optional `angle` in degrees, normalised to (-180, 180]; `None` when it is absent, +/// null or (after normalising) zero, so an unrotated crop takes the plain, resampling-free path. +fn crop_angle(p: &Value) -> Result> { + let a = match p.get("angle") { + None | Some(Value::Null) => return Ok(None), + Some(v) => v.as_f64().ok_or_else(|| bad("image.crop", "`angle` must be a number of degrees"))?, + }; + if !a.is_finite() || a.abs() > MAX_CROP_ANGLE { + return Err(bad("image.crop", format!("`angle` must be a finite number of degrees within ±{MAX_CROP_ANGLE}"))); + } + let a = a.rem_euclid(360.0); + let a = if a > 180.0 { a - 360.0 } else { a }; + Ok((a.abs() >= 1e-9).then_some(a)) +} + +/// The Crop tool's rotated frame: `r` (document px) turned clockwise on screen by `angle` degrees +/// about its centre. The document is rotated counter-clockwise by `angle` (Image Rotation › +/// Arbitrary: the canvas grows to fit, the Background fills what the rotation uncovers with the +/// background colour, other layers keep transparency there and every pixel of theirs), which makes +/// the frame upright, then cropped to it (`deleteCroppedPixels` as for an unrotated crop), all in +/// one undo step. With `content_aware`, the corners the rotation uncovers (and any area past the +/// rotated image) are then filled from their surroundings, in the same step (#3823). +fn rotated_crop(s: &mut Session, r: Rect, angle: f64, delete: bool, content_aware: bool, crop_target: &CropTarget) -> Result { + const CMD: &str = "image.crop"; + let size = s.active().ok_or(EngineError::NoDocument)?.doc.size; + let (w, h) = (f64::from(r.width()), f64::from(r.height())); + let (cx, cy) = (f64::from(r.x0) + w / 2.0, f64::from(r.y0) + h / 2.0); + // Where the frame's centre lands: the rotation `image.rotation.arbitrary` applies, clockwise + // by `-angle` (x' = c·x − s·y, y' = s·x + c·y) about the old and new canvas centres. + let new = crate::mode_cmds::rotated_size(size, -angle); + let (sn, cs) = (-angle).to_radians().sin_cos(); + let (dx, dy) = (cx - f64::from(size.width) / 2.0, cy - f64::from(size.height) / 2.0); + let (ncx, ncy) = (f64::from(new.width) / 2.0 + cs * dx - sn * dy, f64::from(new.height) / 2.0 + sn * dx + cs * dy); + let (x, y) = ((ncx - w / 2.0).round(), (ncy - h / 2.0).round()); + let far = || bad(CMD, "the rotated frame is outside the 32-bit coordinate range"); + let limit = f64::from(i32::MAX / 2); + if !(x.is_finite() && y.is_finite()) || x.abs() > limit || y.abs() > limit { + return Err(far()); + } + let (x, y) = (x as i32, y as i32); + let end = |o: i32, len: u32| i32::try_from(len).ok().and_then(|l| o.checked_add(l)); + let (Some(x1), Some(y1)) = (end(x, r.width()), end(y, r.height())) else { return Err(far()) }; + let target = Rect::new(x, y, x1, y1); + // The cropped canvas back to the original document: undo the crop's offset, then the rotation + // (x = c·(x' − nx) + s·(y' − ny) + cx, y = −s·(x' − nx) + c·(y' − ny) + cy). + let (ox, oy) = (f64::from(target.x0) - f64::from(new.width) / 2.0, f64::from(target.y0) - f64::from(new.height) / 2.0); + let (ocx, ocy) = (f64::from(size.width) / 2.0, f64::from(size.height) / 2.0); + let coverage = crate::crop_fill::Coverage { + map: [cs, sn, -sn, cs, cs * ox + sn * oy + ocx, -sn * ox + cs * oy + ocy], + width: f64::from(size.width), + height: f64::from(size.height), + rotated: true, + held: None, + }; + // The pixels before the turn: under a turned frame a Delete Cropped Pixels off crop's hidden ones + // count as image, as in Photoshop (a straight crop fills over them) (#8060). + let coverage = if content_aware { + let d = s.active().ok_or(EngineError::NoDocument)?; + coverage.holding(&d.doc, d.active_layer) + } else { + coverage + }; + crate::analysis_cmds::compound(s, "Crop", |s| { + // Pixels the crop deletes needn't be turned first: keeping only what lands in the frame + // makes the rotation cost the frame's size, not the canvas's (a small turned crop of a + // 10 MP photo took over half a second). + if delete { + let keep = turned_crop_source(size, new, angle, target); + s.edit("Crop", |doc, _| { + // Type and smart objects stay whole, as in the crop itself: the rotation re-renders + // them, but a smart object whose source is unavailable keeps its cache. + delete_cropped_pixels(&mut doc.layers, keep); + for_each_layer(&mut doc.layers, &mut |l| { + if let Some(m) = &mut l.mask { + m.surface = crop_surface(&m.surface, keep); + } + }); + for ch in doc.channels.iter_mut().chain(doc.quick_mask.as_mut()) { + ch.surface = crop_surface(&ch.surface, keep); + } + // The crop drops the selection anyway. + doc.selection = None; + Ok(()) + })?; + } + crate::mode_cmds::rotate_arbitrary(s, &json!({"angle": angle, "direction": "ccw"}))?; + // Color Sampler points follow the crop's origin shift too (the rotation moved them above). + s.set_sampler_map(crop_target.sampler_map(target)); + let extension = s.tools.background; + s.edit("Crop", |doc, active| { + crop_doc(doc, CMD, target, delete, extension)?; + if content_aware { + crate::crop_fill::fill_uncovered(doc, *active, &coverage)?; + } + doc.selection = None; + crop_target.apply(doc); + Ok(()) + }) + })?; + Ok(crop_result(s, json!({ "x": r.x0, "y": r.y0, "width": r.width(), "height": r.height(), "angle": angle }))) +} + +/// The pixels a turned crop reads, in document coordinates before the turn: the source of the +/// `target` frame (on the `new` canvas the rotation by `-angle` makes of `old`), grown by the widest +/// interpolation kernel's reach so every sample the frame's pixels take is kept. +fn turned_crop_source(old: Size, new: Size, angle: f64, target: Rect) -> Rect { + const KERNEL_REACH: f64 = 4.0; + // The inverse of `rotate_arbitrary`'s map: x = c·u + s·v + cx, y = −s·u + c·v + cy, where + // (u, v) is the point relative to the new canvas's centre. + let (sn, cs) = (-angle).to_radians().sin_cos(); + let (cx, cy) = (f64::from(old.width) / 2.0, f64::from(old.height) / 2.0); + let (nx, ny) = (f64::from(new.width) / 2.0, f64::from(new.height) / 2.0); + let (mut x0, mut y0, mut x1, mut y1) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY); + for (px, py) in [(target.x0, target.y0), (target.x1, target.y0), (target.x0, target.y1), (target.x1, target.y1)] { + let (u, v) = (f64::from(px) - nx, f64::from(py) - ny); + let (x, y) = (cs * u + sn * v + cx, -sn * u + cs * v + cy); + (x0, y0, x1, y1) = (x0.min(x), y0.min(y), x1.max(x), y1.max(y)); + } + // `as` saturates: a frame near the coordinate limits keeps more, never less. + Rect::new((x0 - KERNEL_REACH).floor() as i32, (y0 - KERNEL_REACH).floor() as i32, (x1 + KERNEL_REACH).ceil() as i32, (y1 + KERNEL_REACH).ceil() as i32) +} + +/// Image → Trim. +fn trim(s: &mut Session, p: &Value) -> Result { + let d = s.active().ok_or(EngineError::NoDocument)?; + let canvas = d.doc.bounds(); + let buf = flatten_whole(&d.doc, "image.trim")?; + let based = p.get("basedOn").and_then(Value::as_str).unwrap_or("transparent"); + let w = canvas.width() as usize; + let reference = match based { + "topLeft" => buf.px.first().copied(), + "bottomRight" => buf.px.last().copied(), + _ => None, + }; + let differs = |q: [f32; 4]| match reference { + None => q[3] > 0.0, + Some(r) => (0..4).any(|c| (q[c] * q[3] - r[c] * r[3]).abs() > 0.5 / 255.0 || (c == 3 && (q[3] - r[3]).abs() > 0.5 / 255.0)), + }; + let mut b = Rect::EMPTY; + for (i, q) in buf.px.iter().enumerate() { + if differs(*q) { + let (x, y) = ((i % w) as i32, (i / w) as i32); + b = if b.is_empty() { Rect::new(x, y, x + 1, y + 1) } else { b.union(&Rect::new(x, y, x + 1, y + 1)) }; + } + } + if b.is_empty() { + return Err(EngineError::Other("nothing to trim to".into())); + } + let side = |k: &str| p.get(k).and_then(Value::as_bool).unwrap_or(true); + let r = Rect::new( + if side("left") { b.x0 } else { canvas.x0 }, + if side("top") { b.y0 } else { canvas.y0 }, + if side("right") { b.x1 } else { canvas.x1 }, + if side("bottom") { b.y1 } else { canvas.y1 }, + ); + s.set_sampler_map(photocraft_geom::Affine::translate(-f64::from(r.x0), -f64::from(r.y0))); + let extension = s.tools.background; + s.edit("Trim", |doc, _| crop_doc(doc, "image.trim", r, true, extension))?; + Ok(json!({ "x": r.x0, "y": r.y0, "width": r.width(), "height": r.height() })) +} + +/// Image → Mode → colour model, through the CMS (see [`crate::color_cmds::convert_mode`]). +fn convert_mode(s: &mut Session, mode: ColorMode, p: &Value) -> Result { + crate::color_cmds::convert_mode(s, mode, p) +} + +/// Image → Mode → 8/16/32 Bits/Channel. +fn convert_depth(s: &mut Session, depth: SampleType) -> Result { + let current = s.active().ok_or(EngineError::NoDocument)?.doc.depth; + if current == depth { + // History::record clears redo even when an edit closure leaves the document unchanged. + return Ok(Value::Null); + } + s.edit("Bit Depth", |doc, _| { + change_depth(doc, depth); + Ok(()) + })?; + Ok(Value::Null) +} + +pub(crate) fn change_depth(doc: &mut Document, depth: SampleType) { + let current = doc.depth; + // 32-bit documents hold linear light (as Photoshop's do: grey 128 becomes 0.2159, measured + // in Photoshop 27.11), so the colour samples cross the document's tone curve when the + // depth crosses 32 bits: decoded after widening, encoded before narrowing (so no linear + // value is quantised to 8 or 16 bits). Masks, alpha and channels are not colour. + let crosses = (current == SampleType::F32) != (depth == SampleType::F32) && matches!(doc.mode, ColorMode::Rgb | ColorMode::Grayscale); + let to_linear = depth == SampleType::F32; + let transfer = photocraft_compose::adjust::Transfer::for_document(doc.mode, if to_linear { current } else { depth }); + if crosses && !to_linear { + for_each_surface(&mut doc.layers, false, &mut |surf, _| surf.map_color(|v| transfer.encode(v).clamp(0.0, 1.0))); + } + convert_layers_depth(&mut doc.layers, depth); + if crosses && to_linear { + for_each_surface(&mut doc.layers, false, &mut |surf, _| surf.map_color(|v| transfer.decode(v))); + } + for ch in doc.channels.iter_mut().chain(doc.quick_mask.as_mut()) { + let f = ch.surface.format().with_sample(depth); + ch.surface = ch.surface.convert(f); + } + doc.depth = depth; +} + +/// Image → Duplicate. +fn duplicate(s: &mut Session, p: &Value) -> Result { + let d = s.active().ok_or(EngineError::NoDocument)?; + let mut doc = (*d.doc).clone(); + doc.id = photocraft_doc::DocId::fresh(); + doc.name = p.get("name").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| format!("{} copy", d.doc.name)); + if p.get("mergedOnly").and_then(Value::as_bool).unwrap_or(false) { + let buf = flatten_whole(&doc, "image.duplicate")?; + let fmt = doc.pixel_format(); + let mut surf = Surface::new(fmt); + let vals: Vec = buf.px.iter().flat_map(|q| photocraft_raster::from_rgba(&fmt, *q)).collect(); + surf.write_region(doc.bounds(), &vals); + surf.prune(); + // As Photoshop: a source with a Background gives one (opaque, locked); otherwise a plain + // "Layer 1" that keeps the composite's transparency. + let has_background = doc.background().is_some(); + let mut merged = Layer::new(if has_background { "Background" } else { "Layer 1" }, LayerContent::Raster(surf)); + merged.locks.transparency = has_background; + merged.locks.position = has_background; + doc.layers = vec![merged]; + // A merged-only copy has no original layers for saved comps to restore. + // Don't carry dangling comp state into a single-layer flattened document. + doc.layer_comps.clear(); + doc.last_applied_comp = None; + doc.last_document_state = None; + // Likewise, variables drove template layers that no longer exist: drop the whole + // binding set (defs, data sets and the active index) on the flattened copy. + doc.variables = photocraft_doc::Variables::default(); + } + reidentify_copied_layers(&mut doc); + let name = doc.name.clone(); + let index = s.add_document(doc, None); + Ok(json!({ "document": index, "name": name })) +} + +macro_rules! spec { + ($id:literal, $label:literal, [$($m:literal),*], $params:literal, $en:expr, $run:expr) => { + CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: None, params: $params, enabled: $en, run: $run, journal: true } + }; +} + +/// Image menu command specs. +pub fn specs() -> Vec { + vec![ + spec!( + "image.imageSize", + "Image Size…", + ["Image"], + r##"{"width":px,"height":px,"percent":%? (both sides; an explicit side wins),"resolution":ppi,"keepPrintSize":bool=false (with only a resolution: resample the pixels to keep the print size),"resample":"automatic|preserveDetails|bicubicSmoother|bicubicSharper|bicubicAutomatic|bicubic|nearest|bilinear|lanczos|none"="bicubic"} → {width,height} (the document's size after the command; "none" changes the resolution only)"##, + has_doc, + image_size + ), + spec!( + "image.canvasSize", + "Canvas Size…", + ["Image"], + r##"{"width":px,"height":px,"relative":bool=false,"anchor":"topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight"="center","extensionColor":"background|foreground|white|black|transparent|#rrggbb"="background"}"##, + has_doc, + canvas_size + ), + spec!( + "image.crop", + "Crop", + ["Image"], + r##"{"x":px,"y":px,"width":px,"height":px,"angle":-3600..3600=0,"deleteCroppedPixels":bool=true,"contentAware":bool=false,"targetWidth":px,"targetHeight":px,"resolution":ppi,"resample":"bicubic|bilinear|nearest|lanczos|preserveDetails"="bicubic"} → {x,y,width,height,documentWidth,documentHeight,resolution} (targetWidth/targetHeight, both or neither: the cropped area is resampled to exactly that size, as Image Size, in the same undo step; resolution: the document's new ppi; contentAware: the Crop tool's Fill › Content-Aware Fill, the area a rotated or extending crop uncovers filled from its surroundings on the Background, else the active pixel layer)"##, + has_doc, + crop + ), + spec!( + "image.trim", + "Trim…", + ["Image"], + r##"{"basedOn":"transparent|topLeft|bottomRight"="transparent","top":bool=true,"bottom":bool=true,"left":bool=true,"right":bool=true}"##, + has_doc, + trim + ), + spec!( + "image.mode.rgb", + "RGB Color", + ["Image", "Mode"], + r##"{"profile":"|working|/path/to/profile.icc"=working,"intent":"perceptual|relative|saturation|absolute"="relative","bpc":bool=true}"##, + has_doc, + |s, p| convert_mode(s, ColorMode::Rgb, p) + ), + spec!( + "image.mode.grayscale", + "Grayscale", + ["Image", "Mode"], + r##"{"profile":"|working|/path/to/profile.icc"=working,"intent":"perceptual|relative|saturation|absolute"="relative","bpc":bool=true}"##, + has_doc, + |s, p| convert_mode(s, ColorMode::Grayscale, p) + ), + spec!( + "image.mode.cmyk", + "CMYK Color", + ["Image", "Mode"], + r##"{"profile":"|working|/path/to/profile.icc"=working,"intent":"perceptual|relative|saturation|absolute"="relative","bpc":bool=true}"##, + has_doc, + |s, p| convert_mode(s, ColorMode::Cmyk, p) + ), + spec!( + "image.mode.lab", + "Lab Color", + ["Image", "Mode"], + r##"{"profile":"|working|/path/to/profile.icc"=working,"intent":"perceptual|relative|saturation|absolute"="relative","bpc":bool=true}"##, + has_doc, + |s, p| convert_mode(s, ColorMode::Lab, p) + ), + spec!("image.mode.bits8", "8 Bits/Channel", ["Image", "Mode"], "{}", has_doc, |s, _| convert_depth(s, SampleType::U8)), + spec!("image.mode.bits16", "16 Bits/Channel", ["Image", "Mode"], "{}", has_doc, |s, _| convert_depth(s, SampleType::U16)), + spec!("image.mode.bits32", "32 Bits/Channel", ["Image", "Mode"], "{}", has_doc, |s, _| convert_depth(s, SampleType::F32)), + spec!("image.duplicate", "Duplicate…", ["Image"], r##"{"name":str,"mergedOnly":bool=false}"##, has_doc, duplicate), + ] +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/image_cmds/tests.rs b/crates/engine/src/cmd/image_cmds/tests.rs new file mode 100644 index 0000000000..3061ce69c0 --- /dev/null +++ b/crates/engine/src/cmd/image_cmds/tests.rs @@ -0,0 +1,963 @@ +use super::*; + +#[test] +fn crop_rejects_rectangles_that_would_wrap() { + let mut s = session(); + // 2^32 + 100 wrapped to `x = 100` through the narrowing casts: a crop rectangle + // somewhere unrelated to the numbers passed. + let err = s.execute("image.crop", json!({"x": 4_294_967_396_i64, "y": 0, "width": 10, "height": 10})).unwrap_err(); + assert!(err.to_string().contains("32-bit"), "{err}"); + // In-range rectangles past the canvas still work (clamped by the crop itself). + s.execute("image.crop", json!({"x": -10, "y": -10, "width": 1000, "height": 1000})).unwrap(); +} + +/// A crop whose translation to the origin can't be represented in i32 is rejected before +/// anything changes (#959): `-i32::MIN` overflowed the negation in `crop_doc`, `x + width` +/// past i32::MAX silently shortened the crop, and an origin one past i32::MIN moved the +/// layer pixels beyond i32::MAX (a length-mismatch panic while translating surfaces). +#[test] +fn crop_rejects_origins_that_cannot_move_to_zero() { + const MIN: i64 = i32::MIN as i64; + const MAX: i64 = i32::MAX as i64; + let cases = [ + json!({"x": MIN, "y": 0, "width": 1, "height": 1}), + json!({"x": 0, "y": MIN, "width": 1, "height": 1}), + json!({"x": MIN, "y": MIN, "width": 1, "height": 1}), + json!({"x": MIN, "y": 0, "width": 1, "height": 1, "deleteCroppedPixels": false}), + json!({"x": MAX - 5, "y": 0, "width": 10, "height": 1}), + json!({"x": 0, "y": MAX - 5, "width": 1, "height": 10}), + json!({"x": MIN + 1, "y": 0, "width": 1, "height": 1, "deleteCroppedPixels": false}), + json!({"x": 0, "y": MIN + 1, "width": 1, "height": 1, "deleteCroppedPixels": false}), + ]; + for p in cases { + let mut s = session(); + let before = s.active().unwrap().doc.clone(); + let (rev, steps) = (s.active().unwrap().revision, s.active().unwrap().history.entries().len()); + let err = s.execute("image.crop", p.clone()).unwrap_err(); + assert!(matches!(err, EngineError::BadParams { .. }), "{p}: {err}"); + assert!(err.to_string().contains("32-bit"), "{p}: {err}"); + let st = s.active().unwrap(); + assert!(std::sync::Arc::ptr_eq(&st.doc, &before), "{p}: document changed"); + assert_eq!(st.doc.size, Size::new(40, 20), "{p}"); + assert_eq!(st.doc.layers[1].surface().unwrap().content_bounds(), Rect::new(10, 5, 20, 15), "{p}"); + assert_eq!((st.revision, st.history.entries().len()), (rev, steps), "{p}: history step recorded"); + } + // Control: a legal negative origin past the canvas still crops (and extends) the canvas. + let mut s = session(); + s.execute("image.crop", json!({"x": -10, "y": -5, "width": 60, "height": 30})).unwrap(); + assert_eq!(doc(&s).size, Size::new(60, 30)); + assert_eq!(doc(&s).layers[1].surface().unwrap().pixel(20, 10), vec![1.0, 0.0, 0.0, 1.0]); + // A far-off crop that deletes the (non-overlapping) pixels has nothing left to move. + let mut s = session(); + s.execute("image.crop", json!({"x": MIN + 1, "y": 0, "width": 1, "height": 1})).unwrap(); + assert_eq!(doc(&s).size, Size::new(1, 1)); +} + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 40, "height": 20})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.edit("paint", |doc, active| { + let l = doc.layer_mut(active.unwrap()).unwrap(); + l.surface_mut().unwrap().fill_rect(Rect::new(10, 5, 20, 15), &[1.0, 0.0, 0.0, 1.0]); + l.mask = Some(photocraft_doc::LayerMask::reveal_all()); + l.effects.items.push(Effect::default_drop_shadow()); + Ok(()) + }) + .unwrap(); + s +} + +fn doc(s: &Session) -> &Document { + &s.active().unwrap().doc +} + +/// Document-wide conversions must move every stored video frame, not just the displayed one (#4956). +#[test] +fn crop_moves_stored_video_frames() { + let mut s = session(); + s.edit("video", |doc, active| { + let l = doc.layer_mut(active.unwrap()).unwrap(); + let frame = l.surface().unwrap().clone(); + let mut v = photocraft_doc::VideoData::new(vec![frame.clone(), frame.clone()], 24.0); + v.original_frames = Some(vec![frame.clone(), frame]); + l.video = Some(v); + Ok(()) + }) + .unwrap(); + s.execute("image.crop", json!({"x": -10, "y": -5, "width": 60, "height": 30})).unwrap(); + let v = doc(&s).layers[1].video.as_ref().unwrap(); + let red = vec![1.0, 0.0, 0.0, 1.0]; + for frame in v.frames.iter().chain(v.original_frames.iter().flatten()) { + assert_eq!(frame.pixel(20, 10), red); + assert_eq!(frame.pixel(5, 5)[3], 0.0); + } +} + +/// Delete Cropped Pixels on a shrinking crop deletes the cropped area from every stored video +/// frame (and the original footage), not just the displayed one (#4956). +#[test] +fn delete_cropped_pixels_crops_stored_video_frames() { + let mut s = session(); + s.edit("video", |doc, active| { + let l = doc.layer_mut(active.unwrap()).unwrap(); + let red = l.surface().unwrap().clone(); + let mut blue = red.clone(); + blue.fill_rect(Rect::new(0, 0, 40, 20), &[0.0, 0.0, 1.0, 1.0]); + let mut v = photocraft_doc::VideoData::new(vec![red.clone(), blue.clone()], 24.0); + v.original_frames = Some(vec![red, blue]); + l.video = Some(v); + Ok(()) + }) + .unwrap(); + s.execute("image.crop", json!({"x": 15, "y": 0, "width": 25, "height": 20, "deleteCroppedPixels": true})).unwrap(); + assert_eq!(doc(&s).size, Size::new(25, 20)); + let v = doc(&s).layers[1].video.as_ref().unwrap(); + let originals = v.original_frames.as_ref().unwrap(); + assert_eq!((v.frames.len(), originals.len()), (2, 2)); + for frames in [&v.frames, originals] { + // The red square (10..20, 5..15) keeps only its right half; the full blue frame + // keeps exactly the 25×20 crop. + assert_eq!(frames[0].content_bounds(), Rect::new(0, 5, 5, 15)); + assert_eq!(frames[0].pixel(2, 10), vec![1.0, 0.0, 0.0, 1.0]); + assert_eq!(frames[1].content_bounds(), Rect::new(0, 0, 25, 20)); + assert_eq!(frames[1].pixel(24, 19), vec![0.0, 0.0, 1.0, 1.0]); + } +} + +/// Resample on with only a new resolution keeps the print size, as Photoshop's Image Size +/// does (an action's `imageSize` with `Rslt` alone); without `keepPrintSize` only the +/// resolution changes. +#[test] +fn image_size_keep_print_size_resamples_to_the_resolution() { + let mut s = session(); + s.execute("image.imageSize", json!({"resolution": 144, "resample": "bicubic"})).unwrap(); + assert_eq!((doc(&s).size, doc(&s).resolution_dpi), (Size::new(40, 20), 144.0)); + s.execute("image.imageSize", json!({"resolution": 288, "resample": "bicubic", "keepPrintSize": true})).unwrap(); + assert_eq!((doc(&s).size, doc(&s).resolution_dpi), (Size::new(80, 40), 288.0)); + // An explicit side still wins. + s.execute("image.imageSize", json!({"width": 20, "resolution": 72, "resample": "bicubic", "keepPrintSize": true})).unwrap(); + assert_eq!(doc(&s).size, Size::new(20, 10)); +} + +#[test] +fn image_size_scales_everything() { + for resample in ["bicubic", "bicubicSmoother", "bicubicSharper", "bicubicAutomatic", "automatic", "bilinear", "nearest", "lanczos", "preserveDetails"] { + let mut s = session(); + s.execute("image.imageSize", json!({"width": 80, "resample": resample})).unwrap(); + let d = doc(&s); + assert_eq!(d.size, Size::new(80, 40), "{resample}"); + let l = &d.layers[1]; + let b = l.surface().unwrap().content_bounds(); + assert!((b.x0 - 20).abs() <= 1 && (b.x1 - 40).abs() <= 1, "{resample} {b:?}"); + let Effect::DropShadow(sh) = &l.effects.items[0] else { panic!() }; + assert_eq!(sh.distance, 10.0); + assert_eq!(l.mask.as_ref().unwrap().surface.default_pixel(), vec![1.0]); + } +} + +/// #6019: Image Size on an Indexed Color document makes no colours the colour table doesn't have. +#[test] +fn image_size_resamples_indexed_color_with_nearest_neighbor() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 2, "height": 1})).unwrap(); + s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + s.execute("select.rect", json!({"x": 1, "y": 0, "width": 1, "height": 1})).unwrap(); + s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s.execute("image.mode.indexedColor", json!({})).unwrap(); + for resample in ["bicubic", "automatic", "bilinear", "lanczos", "preserveDetails"] { + s.execute("image.imageSize", json!({"width": 8, "resample": resample})).unwrap(); + let st = s.active().unwrap(); + let surf = st.doc.layers[0].surface().unwrap(); + for x in 0..8 { + let px = surf.pixel(x, 0); + assert!(px[..3] == [1.0, 0.0, 0.0] || px[..3] == [0.0, 0.0, 1.0], "{resample}: no blended colour at x {x}: {px:?}"); + } + s.execute("history.undo", json!({})).unwrap(); + } +} + +/// The canvas border stays opaque after Image Size (it used to fade into transparency, so a +/// Background or a 200 % export got a translucent frame), and a full selection stays full. +/// #1544: 64 x 48 to 300000 x 300000 (90 billion pixels) started allocating resampled bands +/// without a budget. It is refused before any allocation and the document is untouched; a +/// change of resolution only, and an ordinary resize, still work. +#[test] +fn image_size_refuses_a_raster_past_the_budget() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 64, "height": 48})).unwrap(); + let before = (doc(&s).size, s.active().unwrap().history.past_len()); + let err = s.execute("image.imageSize", json!({"width": 300_000, "height": 300_000})).unwrap_err().to_string(); + assert!(err.contains("megapixels"), "{err}"); + assert_eq!((doc(&s).size, s.active().unwrap().history.past_len()), before); + s.execute("image.imageSize", json!({"width": 300_000, "height": 300_000, "resample": "none", "resolution": 300})).unwrap(); + s.execute("image.imageSize", json!({"width": 128, "height": 96})).unwrap(); + assert_eq!(doc(&s).size, Size::new(128, 96)); +} + +#[test] +fn image_size_keeps_canvas_edges_opaque() { + for depth in [8, 16, 32] { + for (w, resample) in + [(60, "bicubic"), (41, "lanczos"), (15, "bilinear"), (77, "preserveDetails"), (21, "bicubicSharper"), (47, "automatic"), (9, "bicubicAutomatic")] + { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 30, "height": 20, "depth": depth, "background": "#336699"})).unwrap(); + s.execute("select.all", json!({})).unwrap(); + s.execute("image.imageSize", json!({"width": w, "resample": resample})).unwrap(); + let d = doc(&s); + let flat = photocraft_compose::flatten(d); + let (w, h) = (flat.rect.width() as usize, flat.rect.height() as usize); + let mid = flat.px[(h / 2) * w + w / 2]; + assert!((mid[3] - 1.0).abs() < 1e-3, "{depth} {resample}: {mid:?}"); + for p in &flat.px { + let off = p.iter().zip(mid).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); + assert!(off < 0.01, "{depth} {resample} {w}: {p:?} vs {mid:?}"); + } + let sel = d.selection.as_ref().unwrap(); + let (x1, y1) = (d.size.width as i32 - 1, d.size.height as i32 - 1); + for (x, y) in [(0, 0), (x1, 0), (0, y1), (x1, y1)] { + assert!(sel.pixel(x, y)[0] > 0.99, "{depth} {resample}: selection at ({x},{y})"); + } + } + } +} + +#[test] +fn resolution_only_change() { + let mut s = session(); + let r = s.execute("image.imageSize", json!({"resolution": 300, "resample": "none", "width": 999})).unwrap(); + assert_eq!(doc(&s).size, Size::new(40, 20)); + assert_eq!(doc(&s).resolution_dpi, 300.0); + // #1815: the result is the size the document has, not the ignored request. + assert_eq!(r, json!({"width": 40, "height": 20})); +} + +/// Type keeps its pixel size across a resolution change: resampled 2x at twice the ppi it is +/// twice as tall (not 4x), with Resample off it stays, and a later re-render doesn't jump. +#[test] +fn image_size_with_a_new_resolution_scales_type_with_the_pixels_only() { + for (params, k) in [(json!({"width": 200, "height": 200, "resolution": 144}), 2), (json!({"resolution": 144, "resample": "none"}), 1)] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 100, "height": 100})).unwrap(); + s.execute("type.create", json!({"x": 10, "y": 50, "text": "Hi", "size": 12})).unwrap(); + let height = |s: &Session| doc(s).layers.last().unwrap().surface().unwrap().content_bounds().height(); + let h0 = height(&s); + assert!(h0 > 4, "{h0}"); + s.execute("image.imageSize", params.clone()).unwrap(); + assert!(height(&s).abs_diff(h0 * k) <= 2, "{params}: {h0} -> {}", height(&s)); + let d = doc(&s); + let LayerContent::Text(t) = &d.layers.last().unwrap().content else { panic!("type layer") }; + let mut t = t.clone(); + crate::type_cmds::refresh(d, &mut t); + let after = t.cache.unwrap().content_bounds().height(); + assert!(after.abs_diff(h0 * k) <= 2, "{params}: re-rendered {h0} -> {after}"); + } +} + +#[test] +fn image_size_reports_the_size_it_applied() { + // #1815: every path reports the document's size afterwards, at every depth. + for depth in [8, 16, 32] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 64, "height": 48, "depth": depth})).unwrap(); + let size = |s: &Session| json!({"width": doc(s).size.width, "height": doc(s).size.height}); + for p in [ + json!({"width": 999, "height": 777, "resample": "none", "resolution": 150}), + json!({"width": 32}), + json!({"height": 96, "resample": "nearest"}), + json!({"width": 96, "height": 72, "resample": "none"}), + json!({}), + ] { + let r = s.execute("image.imageSize", p.clone()).unwrap(); + assert_eq!(r, size(&s), "{depth}-bit {p}"); + } + // 64×48 → (none) → 32×24 → 128×96 (aspect kept) → (none) → unchanged. + assert_eq!(doc(&s).size, Size::new(128, 96), "{depth}-bit"); + } +} + +/// #1114: nearest neighbor reduction keeps source values without averaging. +#[test] +fn nearest_neighbor_reduction_keeps_source_values() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + s.execute("tools.setColors", json!({"foreground": "#000000", "background": "#ffffff"})).unwrap(); + for y in 0..8 { + for x in 0..8 { + if (x + y) % 2 == 0 { + s.execute("select.rect", json!({"x": x, "y": y, "width": 1, "height": 1})).unwrap(); + s.execute("edit.fill", json!({"contents": "foreground"})).unwrap(); + } + } + } + s.execute("select.deselect", json!({})).unwrap(); + let st = s.active().unwrap(); + let before = st.doc.layers[0].surface().unwrap().rgba(0, 0); + assert!(before[0] < 0.01, "setup: (0,0) should be black, got {before:?}"); + s.execute("image.imageSize", json!({"width": 4, "height": 4, "resample": "nearest"})).unwrap(); + let st = s.active().unwrap(); + let surf = st.doc.layers[0].surface().unwrap(); + for (x, y) in [(0, 0), (1, 1), (2, 3)] { + let v = surf.rgba(x, y)[0]; + assert!(v.is_finite() && !(0.01..=0.99).contains(&v), "nearest produced an averaged value {v} at ({x},{y})"); + } +} + +#[test] +fn canvas_size_anchors_and_extends_background() { + let mut s = session(); + s.execute("image.canvasSize", json!({"width": 60, "height": 30, "anchor": "topLeft", "extensionColor": "#00ff00"})).unwrap(); + let d = doc(&s); + assert_eq!(d.size, Size::new(60, 30)); + assert_eq!(d.layers[1].surface().unwrap().content_bounds(), Rect::new(10, 5, 20, 15)); + let bg = d.layers[0].surface().unwrap(); + assert_eq!(bg.pixel(50, 25), vec![0.0, 1.0, 0.0, 1.0]); + assert_eq!(bg.pixel(5, 5), vec![1.0, 1.0, 1.0, 1.0]); + let mut s = session(); + s.execute("image.canvasSize", json!({"width": 20, "height": 10, "relative": true, "anchor": "center"})).unwrap(); + assert_eq!(doc(&s).layers[1].surface().unwrap().content_bounds(), Rect::new(20, 10, 30, 20)); +} + +#[test] +fn canvas_size_anchor_offsets_and_rejects_unlisted() { + // 64x48 -> 100x80: dx spans 36 and dy spans 32, so each anchor factor lands on a known + // offset. All nine documented values must anchor exactly where they do today (#2946). + let expected = [ + ("topLeft", [0, 0]), + ("top", [18, 0]), + ("topRight", [36, 0]), + ("left", [0, 16]), + ("center", [18, 16]), + ("right", [36, 16]), + ("bottomLeft", [0, 32]), + ("bottom", [18, 32]), + ("bottomRight", [36, 32]), + ]; + for (anchor, off) in expected { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 64, "height": 48, "background": "white"})).unwrap(); + let r = s.execute("image.canvasSize", json!({"width": 100, "height": 80, "anchor": anchor})).unwrap(); + assert_eq!(r["offset"], json!(off), "anchor {anchor}"); + } + // An omitted anchor still defaults to center. + let mut s = Session::new(); + s.execute("file.new", json!({"width": 64, "height": 48, "background": "white"})).unwrap(); + assert_eq!(s.execute("image.canvasSize", json!({"width": 100, "height": 80})).unwrap()["offset"], json!([18, 16])); + // A misspelling or unknown value is a BadParams error naming `anchor`, never an anchor + // between two of the nine (the old independent-axis matching produced top-centre etc.). + for anchor in ["topleft", "TopLeft", "TOPLEFT", "bottomleft", "bottomright", "middle", "", "NOPE"] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 64, "height": 48, "background": "white"})).unwrap(); + let err = s.execute("image.canvasSize", json!({"width": 100, "height": 80, "anchor": anchor})).unwrap_err(); + assert!(matches!(err, EngineError::BadParams { .. }), "anchor {anchor:?} must be rejected, got {err:?}"); + assert!(err.to_string().contains("anchor"), "the error for {anchor:?} must name `anchor`: {err}"); + } +} + +#[test] +fn crop_to_selection_and_trim() { + let mut s = session(); + assert!(s.execute("image.crop", json!({})).is_err(), "no selection, no rect"); + s.execute("select.rect", json!({"x": 5, "y": 2, "width": 20, "height": 10})).unwrap(); + s.execute("image.crop", json!({})).unwrap(); + let d = doc(&s); + assert_eq!(d.size, Size::new(20, 10)); + assert!(d.selection.is_none()); + assert_eq!(d.layers[1].surface().unwrap().content_bounds(), Rect::new(5, 3, 15, 10)); + // Trim transparent: hide the background, trim to the red square. + let mut s = session(); + s.execute("layer.setProps", json!({"layer": doc(&s).layers[0].id.0, "visible": false})).unwrap(); + s.execute("image.trim", json!({"basedOn": "transparent"})).unwrap(); + // The red square (10×10) plus its drop shadow (distance 5, size 5). + let size = doc(&s).size; + assert!(size.width > 10 && size.width < 30 && size.height > 10 && size.height < 25, "{size:?}"); +} + +#[test] +fn crop_to_explicit_rect_can_extend_canvas() { + let mut s = session(); + s.execute("image.crop", json!({"x": 10, "y": 5, "width": 10, "height": 10})).unwrap(); + assert_eq!(doc(&s).size, Size::new(10, 10)); + assert_eq!(doc(&s).layers[1].surface().unwrap().pixel(0, 0), vec![1.0, 0.0, 0.0, 1.0]); + let mut s = session(); + s.execute("image.crop", json!({"x": -10, "y": 0, "width": 60, "height": 20})).unwrap(); + assert_eq!(doc(&s).size, Size::new(60, 20)); + assert_eq!(doc(&s).layers[1].surface().unwrap().pixel(20, 5), vec![1.0, 0.0, 0.0, 1.0]); +} + +#[test] +fn crop_extension_fills_the_background_with_the_background_colour() { + let mut shrink = Session::new(); + shrink.execute("file.new", json!({"width": 16, "height": 16, "background": "#ff0000"})).unwrap(); + shrink.execute("image.crop", json!({"x": 2, "y": 0, "width": 12, "height": 16})).unwrap(); + let layer = &doc(&shrink).layers[0]; + assert_eq!(layer.name, "Background", "a shrink-only crop keeps the Background"); + assert!(layer.locks.transparency && layer.locks.position); + + let mut s = Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16, "background": "#ff0000"})).unwrap(); + s.tools.background = [0.0, 1.0, 0.0, 1.0]; + s.execute("image.crop", json!({"x": -4, "y": 0, "width": 20, "height": 16})).unwrap(); + let layer = &doc(&s).layers[0]; + assert_eq!(layer.name, "Background", "an extending crop keeps the Background (#3081)"); + assert!(layer.locks.transparency && layer.locks.position); + assert_eq!(layer.surface().unwrap().rgba(1, 8), [0.0, 1.0, 0.0, 1.0], "the added border takes the background colour"); + assert_eq!(layer.surface().unwrap().rgba(8, 8), [1.0, 0.0, 0.0, 1.0], "the original pixels stay"); + + s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap(); + let layer = &doc(&s).layers[0]; + assert_eq!(layer.surface().unwrap().rgba(1, 8), [0.0, 0.0, 1.0, 1.0], "Fill paints the extended border"); + assert_eq!(layer.surface().unwrap().rgba(8, 8), [0.0, 0.0, 1.0, 1.0]); + + s.execute("edit.undo", json!({})).unwrap(); + s.execute("edit.undo", json!({})).unwrap(); + let layer = &doc(&s).layers[0]; + assert_eq!(doc(&s).size, Size::new(16, 16)); + assert_eq!(layer.surface().unwrap().rgba(8, 8), [1.0, 0.0, 0.0, 1.0]); + assert_eq!(layer.surface().unwrap().content_bounds(), Rect::new(0, 0, 16, 16), "undo removes the filled border"); + + // A normal layer gets transparent pixels in the added area. + let mut s = Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16, "background": "#ff0000"})).unwrap(); + s.execute("layer.new.layerFromBackground", json!({})).unwrap(); + s.execute("image.crop", json!({"x": -4, "y": 0, "width": 20, "height": 16})).unwrap(); + assert_eq!(doc(&s).layers[0].surface().unwrap().rgba(1, 8), [0.0; 4]); +} + +/// Delete Cropped Pixels deletes pixel-layer data only: type and smart objects keep what lies +/// outside the frame, so moving them later doesn't show them cut at the old edge. +#[test] +fn delete_cropped_pixels_keeps_type_and_smart_objects_whole() { + let mut s = session(); + s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + s.execute("type.create", json!({"x": 10, "y": 15, "text": "Hi", "size": 12})).unwrap(); + let bounds = |s: &Session| -> Vec { doc(s).layers[1..].iter().map(|l| l.surface().unwrap().content_bounds()).collect() }; + let before = bounds(&s); + assert!(before.iter().all(|b| b.x0 < 15 && b.x1 > 15), "both cross the crop edge: {before:?}"); + s.execute("image.crop", json!({"x": 15, "y": 0, "width": 25, "height": 20})).unwrap(); + assert!(matches!(doc(&s).layers[1].content, LayerContent::Smart(_)) && matches!(doc(&s).layers[2].content, LayerContent::Text(_))); + assert_eq!(bounds(&s), before.iter().map(|b| b.translate(-15, 0)).collect::>()); +} + +/// A turned crop deleting pixels keeps type and smart objects whole too, also a smart object +/// whose source is unavailable (the rotation can't re-render it, so it keeps its cache): each +/// ends up exactly as the same turned crop with Delete Cropped Pixels off leaves it. +#[test] +fn turned_crop_deleting_pixels_keeps_type_and_smart_objects_whole() { + let [deleted, kept] = [true, false].map(|delete| { + let mut s = session(); + s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + s.edit("unlink", |doc, active| { + if let LayerContent::Smart(sm) = &mut doc.layer_mut(active.unwrap()).unwrap().content { + sm.source = photocraft_doc::SmartSource::Linked { path: "missing-photocraft-test-source.psd".into() }; + } + Ok(()) + }) + .unwrap(); + s.execute("type.create", json!({"x": 10, "y": 15, "text": "Hi", "size": 12})).unwrap(); + s.execute("image.crop", json!({"x": 20, "y": 0, "width": 20, "height": 20, "angle": 2.0, "deleteCroppedPixels": delete})).unwrap(); + s + }); + let (a, b) = (doc(&deleted), doc(&kept)); + assert!(matches!(a.layers[1].content, LayerContent::Smart(_)) && matches!(a.layers[2].content, LayerContent::Text(_))); + for i in [1, 2] { + let (sa, sb) = (a.layers[i].surface().unwrap(), b.layers[i].surface().unwrap()); + let r = sb.content_bounds(); + assert!(r.x0 < 0, "layer {i} reaches past the crop's left edge: {r:?}"); + assert_eq!(sa.content_bounds(), r, "layer {i}"); + assert_eq!(sa.read_region(r), sb.read_region(r), "layer {i}"); + } +} + +/// The Background keeps the pixels a crop with Delete Cropped Pixels off hid: extending the +/// canvas over them again (Reveal All, Canvas Size) shows them rather than painting them over +/// with the background colour (#7086). +#[test] +fn extending_the_canvas_keeps_the_backgrounds_hidden_pixels() { + for depth in [8, 16, 32] { + let hidden = |s: &mut Session| { + s.execute("file.new", json!({"width": 100, "height": 100, "depth": depth, "background": "white"})).unwrap(); + s.edit("paint", |doc, _| { + let bg = doc.background_mut().unwrap(); + bg.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 50, 100), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + s.execute("image.crop", json!({"x": 50, "y": 0, "width": 50, "height": 100, "deleteCroppedPixels": false})).unwrap(); + s.tools.background = [0.0, 0.0, 0.0, 1.0]; + }; + let mut s = Session::new(); + hidden(&mut s); + s.execute("image.revealAll", json!({})).unwrap(); + let surf = doc(&s).background().unwrap().surface().unwrap(); + assert_eq!(doc(&s).size, Size::new(100, 100), "{depth}-bit"); + assert_eq!(surf.rgba(10, 50), [1.0, 0.0, 0.0, 1.0], "{depth}-bit: Reveal All shows the hidden red half"); + assert_eq!(surf.rgba(80, 50), [1.0, 1.0, 1.0, 1.0], "{depth}-bit"); + + // Canvas Size wider than the hidden pixels: they show, the rest takes the colour. + let mut s = Session::new(); + hidden(&mut s); + s.execute("image.canvasSize", json!({"width": 120, "height": 100, "anchor": "right"})).unwrap(); + let surf = doc(&s).background().unwrap().surface().unwrap(); + assert_eq!(surf.rgba(5, 50), [0.0, 0.0, 0.0, 1.0], "{depth}-bit: past the hidden pixels the background colour"); + assert_eq!(surf.rgba(30, 50), [1.0, 0.0, 0.0, 1.0], "{depth}-bit: Canvas Size shows the hidden red half"); + assert_eq!(surf.rgba(100, 50), [1.0, 1.0, 1.0, 1.0], "{depth}-bit"); + } +} + +/// A Background without an alpha channel (a Grayscale PSD import) has no hidden pixels to tell +/// from empty ones: the added area takes the colour, the kept area stays (#7086). +#[test] +fn an_alpha_less_background_extension_takes_the_colour() { + let mut surf = Surface::new(photocraft_color::PixelFormat::GRAY8); + surf.fill_rect(Rect::new(-50, 0, 100, 100), &[0.6]); + let kept = surf.pixel(50, 50); + fill_background_extension(&mut surf, Rect::new(-60, 0, 100, 100), Rect::new(0, 0, 100, 100), &[0.0]); + assert_eq!(surf.pixel(-55, 50), vec![0.0], "past the old pixels the colour"); + assert_eq!(surf.pixel(-30, 50), vec![0.0], "no alpha: the added area takes the colour"); + assert_eq!(surf.pixel(50, 50), kept, "the kept area is unchanged"); +} + +/// A document (`mode`, `depth`) with a white Background and a layer holding a red pixel at +/// (12, 8) and a blue one at (30, 3). +fn marked(mode: &str, depth: u32) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 40, "height": 20, "mode": mode, "depth": depth, "background": "white"})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + for (x, y, c) in [(12, 8, "#ff0000"), (30, 3, "#0000ff")] { + s.execute("select.rect", json!({"x": x, "y": y, "width": 1, "height": 1})).unwrap(); + s.execute("edit.fill", json!({"color": c})).unwrap(); + } + s.execute("select.deselect", json!({})).unwrap(); + s +} + +fn layer_rgba(s: &Session, layer: usize, x: i32, y: i32) -> [f32; 4] { + doc(s).layers[layer].surface().unwrap().rgba(x, y) +} + +/// #1792: a frame turned 90° clockwise crops what Image Rotation › Arbitrary 90° CCW and a +/// plain crop give, in one undo step that restores the document, at 8, 16 and 32 bits. +#[test] +fn crop_at_90_degrees_is_rotate_then_crop_in_one_step() { + for depth in [8, 16, 32] { + let mut s = marked("rgb", depth); + let before = doc(&s).clone(); + let past = s.active().unwrap().history.past_len(); + // The 10 × 20 frame at (10, 0), turned 90° about (15, 10), covers x 5..25, y 5..15. + let r = s.execute("image.crop", json!({"x": 10, "y": 0, "width": 10, "height": 20, "angle": 90})).unwrap(); + assert_eq!(r["angle"], json!(90.0), "{depth}"); + assert_eq!(doc(&s).size, Size::new(10, 20), "{depth}"); + assert_eq!(s.active().unwrap().history.past_len(), past + 1, "{depth}: one undo step"); + // (12, 8) is 2.5 left of and 1.5 above the centre: in the upright frame, 1.5 left of + // and 2.5 below its centre (5, 10). + let red = layer_rgba(&s, 1, 3, 12); + assert!(red[0] > 0.9 && red[1] < 0.1 && red[3] > 0.9, "{depth}: {red:?}"); + let mut reference = marked("rgb", depth); + reference.execute("image.rotation.arbitrary", json!({"angle": 90, "direction": "ccw"})).unwrap(); + reference.execute("image.crop", json!({"x": 5, "y": 15, "width": 10, "height": 20})).unwrap(); + for l in 0..2 { + for y in 0..20 { + for x in 0..10 { + let (a, b) = (layer_rgba(&s, l, x, y), layer_rgba(&reference, l, x, y)); + // A fully transparent pixel's colour is invisible, and the turned crop + // doesn't turn the pixels it deletes, which the warp spreads colour from. + let n = if b[3] > 1e-3 { 4 } else { 1 }; + assert!(a.iter().rev().zip(b.iter().rev()).take(n).all(|(p, q)| (p - q).abs() < 1e-3), "{depth} layer {l} ({x}, {y}): {a:?} vs {b:?}"); + } + } + } + s.execute("edit.undo", json!({})).unwrap(); + let d = doc(&s); + assert_eq!(d.size, before.size, "{depth}"); + assert_eq!(d.depth, before.depth); + for y in 0..20 { + for x in 0..40 { + assert_eq!(layer_rgba(&s, 1, x, y), before.layers[1].surface().unwrap().rgba(x, y), "{depth} undo at ({x}, {y})"); + } + } + } +} + +/// A slightly turned frame keeps its own size, the pixel under its centre and the Background's +/// colour; the turn's sign matters (a counter-clockwise frame is a negative angle). +#[test] +fn crop_at_a_small_angle_keeps_the_frame_size_in_every_mode() { + for (mode, depth) in [("rgb", 8), ("rgb", 16), ("rgb", 32), ("grayscale", 16), ("cmyk", 8), ("lab", 16)] { + for angle in [5.0, -7.5, 365.0] { + let mut s = marked(mode, depth); + s.execute("image.crop", json!({"x": 2, "y": 1, "width": 21, "height": 15, "angle": angle})).unwrap(); + let d = doc(&s); + assert_eq!(d.size, Size::new(21, 15), "{mode} {depth} {angle}"); + assert_eq!(d.depth.bytes() * 8, depth as usize, "{mode} {depth}"); + assert_eq!(format!("{:?}", d.mode).to_lowercase(), mode, "{mode} {depth}"); + assert_eq!(d.layers.len(), 2); + // The frame's centre (12.5, 8.5) is the red pixel (the layer's only paint nearby); + // it stays at the centre, its colour kept. + let want = layer_rgba(&marked(mode, depth), 1, 12, 8); + let red = layer_rgba(&s, 1, 10, 7); + assert!(red[3] > 0.5 && (0..3).all(|c| (red[c] - want[c]).abs() < 0.2), "{mode} {depth} {angle}: {red:?} vs {want:?}"); + // The Background stays opaque white inside the canvas it came from. + let bg = layer_rgba(&s, 0, 10, 7); + assert!(bg.iter().all(|v| (v - 1.0).abs() < 0.02), "{mode} {depth} {angle}: {bg:?}"); + } + } +} + +/// A turned crop that deletes the cropped pixels turns only what lands in the frame; inside the +/// new canvas every layer, mask and channel is exactly what turning everything gives (the +/// frame spans several tiles, at several depths and angles). +#[test] +fn turned_crop_deleting_pixels_matches_turning_the_whole_canvas() { + use photocraft_color::PixelFormat; + let pixels = || (0..500).flat_map(|y| (0..700).map(move |x| (x, y))); + for depth in [8, 16, 32] { + for angle in [3.0, -7.5, 33.0, 181.0] { + let mut sessions = [true, false].map(|delete| { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 700, "height": 500, "depth": depth, "background": "white"})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.edit("paint", |doc, active| { + let wave = |x: i32, y: i32, k: i32| ((x * 7 + y * 13 + k * 31) % 97) as f32 / 96.0; + let all = Rect::new(0, 0, 700, 500); + let rgba: Vec = pixels().flat_map(|(x, y)| [wave(x, y, 0), wave(x, y, 1), wave(x, y, 2), wave(y, x, 3)]).collect(); + let gray: Vec = pixels().map(|(x, y)| wave(y, x, 4)).collect(); + let l = doc.layer_mut(active.unwrap()).unwrap(); + l.surface_mut().unwrap().write_region(all, &rgba); + let mut mask = photocraft_doc::LayerMask::reveal_all(); + mask.surface.write_region(all, &gray); + l.mask = Some(mask); + let bg = doc.background_mut().unwrap().surface_mut().unwrap(); + bg.write_region(all, &pixels().flat_map(|(x, y)| [wave(x, y, 5), wave(x, y, 6), wave(x, y, 7), 1.0]).collect::>()); + let fmt = PixelFormat::new(ColorMode::Grayscale, doc.pixel_format().sample, false); + let mut ch = Surface::new(fmt); + ch.write_region(all, &gray); + doc.channels.push(photocraft_doc::AlphaChannel::new("Alpha 1", ch)); + Ok(()) + }) + .unwrap(); + let p = json!({"x": 150, "y": 120, "width": 330, "height": 290, "angle": angle, "deleteCroppedPixels": delete}); + s.execute("image.crop", p).unwrap(); + s + }); + let [deleted, kept] = &mut sessions; + let (a, b) = (doc(deleted), doc(kept)); + assert_eq!(a.size, b.size, "{depth} {angle}"); + let canvas = a.bounds(); + for (la, lb) in a.layers.iter().zip(&b.layers) { + let (sa, sb) = (la.surface().unwrap(), lb.surface().unwrap()); + assert!(sa.to_interleaved(canvas) == sb.to_interleaved(canvas), "{depth} {angle}: layer {}", la.name); + if let (Some(ma), Some(mb)) = (&la.mask, &lb.mask) { + assert!(ma.surface.to_interleaved(canvas) == mb.surface.to_interleaved(canvas), "{depth} {angle}: mask of {}", la.name); + } + } + assert!(a.channels[0].surface.to_interleaved(canvas) == b.channels[0].surface.to_interleaved(canvas), "{depth} {angle}: alpha channel"); + // Deleting keeps nothing past the canvas. + let layer = a.layers[1].surface().unwrap(); + assert!(canvas.contains_rect(&layer.content_bounds()), "{depth} {angle}: {:?}", layer.content_bounds()); + } + } +} + +/// Angle 0 (or a whole turn) is the plain crop: no resampling, the same document. +#[test] +fn crop_at_angle_zero_is_the_plain_crop() { + let mut plain = marked("rgb", 16); + plain.execute("image.crop", json!({"x": 3, "y": 2, "width": 30, "height": 10})).unwrap(); + for angle in [json!(0), json!(0.0), json!(360), json!(-720), json!(null)] { + let mut s = marked("rgb", 16); + let r = s.execute("image.crop", json!({"x": 3, "y": 2, "width": 30, "height": 10, "angle": angle})).unwrap(); + assert!(r.get("angle").is_none(), "{angle}: {r}"); + assert_eq!(doc(&s).size, Size::new(30, 10)); + for l in 0..2 { + for y in 0..10 { + for x in 0..30 { + assert_eq!(layer_rgba(&s, l, x, y), layer_rgba(&plain, l, x, y), "{angle} layer {l} ({x}, {y})"); + } + } + } + } +} + +/// Bad angles fail cleanly, before anything changes. +#[test] +fn crop_angle_rejects_bad_values_without_changing_the_document() { + let bad = [ + json!({"x": 0, "y": 0, "width": 10, "height": 10, "angle": "NaN"}), + json!({"x": 0, "y": 0, "width": 10, "height": 10, "angle": "12"}), + json!({"x": 0, "y": 0, "width": 10, "height": 10, "angle": [1]}), + json!({"x": 0, "y": 0, "width": 10, "height": 10, "angle": true}), + json!({"x": 0, "y": 0, "width": 10, "height": 10, "angle": 1e308}), + json!({"x": 0, "y": 0, "width": 10, "height": 10, "angle": -3601}), + json!({"x": 0, "y": 0, "width": 10, "height": 10, "angle": f64::MAX}), + // An angle needs the frame: a selection crop has none. + json!({"angle": 10}), + json!({"x": 0, "y": 0, "width": 0, "height": 10, "angle": 10}), + json!({"x": 0, "y": 0, "width": 300_001, "height": 10, "angle": 10}), + json!({"x": i32::MAX - 5, "y": 0, "width": 10, "height": 10, "angle": 10}), + ]; + for p in bad { + let mut s = marked("rgb", 8); + s.execute("select.all", json!({})).unwrap(); + let before = doc(&s).clone(); + let past = s.active().unwrap().history.past_len(); + assert!(s.execute("image.crop", p.clone()).is_err(), "{p}"); + assert_eq!(doc(&s).size, before.size, "{p}"); + assert_eq!(s.active().unwrap().history.past_len(), past, "{p}"); + } + // Far-off but representable frames turn and crop without panicking. + for (x, y) in [(-1_000_000, 0), (0, 1_000_000), (i32::MIN / 4, i32::MAX / 4)] { + let mut s = marked("rgb", 8); + s.execute("image.crop", json!({"x": x, "y": y, "width": 4, "height": 3, "angle": 33.3})).unwrap(); + assert_eq!(doc(&s).size, Size::new(4, 3)); + } +} + +#[test] +fn crop_refuses_a_canvas_side_past_the_new_document_limit() { + // #960: an unbounded explicit crop left a canvas that a later Trim or Duplicate Merged + // could only abort on allocating. + for (w, h) in [(100_000_000, 100_000_000), (300_001, 10), (10, 300_001)] { + let mut s = session(); + let (size, past) = (doc(&s).size, s.active().unwrap().history.past_len()); + let err = s.execute("image.crop", json!({"x": 0, "y": 0, "width": w, "height": h})).unwrap_err(); + assert!(err.to_string().contains("300000 px limit"), "{w} x {h}: {err}"); + assert_eq!((doc(&s).size, s.active().unwrap().history.past_len()), (size, past), "{w} x {h}: nothing changed"); + } + // At the limit it still extends the canvas (the tiles stay lazy). + let mut s = session(); + s.execute("image.crop", json!({"x": 0, "y": 0, "width": 300_000, "height": 2})).unwrap(); + assert_eq!(doc(&s).size, Size::new(300_000, 2)); +} + +/// #2443: the Crop tool's W x H x Resolution crops, resamples the cropped area to exactly the +/// target size and sets the resolution, in one undo step, at 8 and 16 bits. +#[test] +fn crop_to_a_target_size_and_resolution_is_one_step() { + for depth in [8, 16] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 400, "height": 300, "resolution": 72, "depth": depth})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.edit("paint", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(100, 100, 200, 225), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + let past = s.active().unwrap().history.past_len(); + // 4 x 5 in at 300 ppi from a 100 x 125 px frame. + let r = s + .execute("image.crop", json!({"x": 100, "y": 100, "width": 100, "height": 125, "targetWidth": 1200, "targetHeight": 1500, "resolution": 300})) + .unwrap(); + assert_eq!((r["documentWidth"].as_u64(), r["documentHeight"].as_u64()), (Some(1200), Some(1500)), "{depth}: {r}"); + assert_eq!(r["resolution"].as_f64(), Some(300.0), "{depth}"); + let d = doc(&s); + assert_eq!(d.size, Size::new(1200, 1500), "{depth}"); + assert_eq!(d.resolution_dpi, 300.0, "{depth}"); + assert_eq!(d.layers[0].surface().unwrap().format().sample, if depth == 8 { SampleType::U8 } else { SampleType::U16 }); + // The red frame filled the crop; it fills the result. + let red = d.layers[1].surface().unwrap(); + for (x, y) in [(0, 0), (600, 750), (1199, 1499)] { + assert_eq!(red.pixel(x, y), vec![1.0, 0.0, 0.0, 1.0], "{depth}: ({x}, {y})"); + } + assert_eq!(s.active().unwrap().history.past_len(), past + 1, "{depth}: one history step"); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!((doc(&s).size, doc(&s).resolution_dpi), (Size::new(400, 300), 72.0), "{depth}: undo restores the original"); + } +} + +#[test] +fn crop_target_resamples_after_a_turned_crop_and_resolution_alone_keeps_the_pixels() { + let mut s = session(); + let past = s.active().unwrap().history.past_len(); + s.execute("image.crop", json!({"x": 10, "y": 0, "width": 10, "height": 20, "angle": 90, "targetWidth": 30, "targetHeight": 60, "resample": "nearest"})) + .unwrap(); + assert_eq!(doc(&s).size, Size::new(30, 60)); + assert_eq!(s.active().unwrap().history.past_len(), past + 1, "rotate, crop and resample: one step"); + let mut s = session(); + s.execute("image.crop", json!({"x": 2, "y": 3, "width": 30, "height": 10, "resolution": 150})).unwrap(); + assert_eq!((doc(&s).size, doc(&s).resolution_dpi), (Size::new(30, 10), 150.0)); +} + +/// #7722: a W x H crop of an Indexed Color document resamples like Image Size (#6019), with +/// Nearest Neighbor, so no pixel gets a blend that isn't in the colour table. +#[test] +fn crop_target_resamples_indexed_color_with_nearest_neighbor() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 2, "height": 1})).unwrap(); + s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + s.execute("select.rect", json!({"x": 1, "y": 0, "width": 1, "height": 1})).unwrap(); + s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s.execute("image.mode.indexedColor", json!({})).unwrap(); + for resample in [None, Some("bicubic"), Some("automatic"), Some("bilinear"), Some("lanczos")] { + let mut p = json!({"x": 0, "y": 0, "width": 2, "height": 1, "targetWidth": 8, "targetHeight": 1}); + if let Some(r) = resample { + p["resample"] = json!(r); + } + s.execute("image.crop", p).unwrap(); + let surf = doc(&s).layers[0].surface().unwrap(); + for x in 0..8 { + let px = surf.pixel(x, 0); + assert!(px[..3] == [1.0, 0.0, 0.0] || px[..3] == [0.0, 0.0, 1.0], "{resample:?}: no blended colour at x {x}: {px:?}"); + } + s.execute("history.undo", json!({})).unwrap(); + } +} + +#[test] +fn crop_target_accepts_whole_number_floats() { + // `json.dumps(100.0)` and many other JSON writers send whole numbers as floats. + let mut s = session(); + s.execute("image.crop", json!({"x": 0, "y": 0, "width": 20, "height": 10, "targetWidth": 40.0, "targetHeight": 20.0})).unwrap(); + assert_eq!(doc(&s).size, Size::new(40, 20)); +} + +#[test] +fn crop_target_rejects_bad_params_without_changing_the_document() { + let rect = json!({"x": 0, "y": 0, "width": 10, "height": 10}); + let bad_params = [ + json!({"targetWidth": 100}), + json!({"targetHeight": 100}), + json!({"targetWidth": 0, "targetHeight": 10}), + json!({"targetWidth": -5, "targetHeight": 10}), + json!({"targetWidth": 10.5, "targetHeight": 10}), + json!({"targetWidth": -1.0, "targetHeight": 10}), + json!({"targetWidth": 0.0, "targetHeight": 10}), + json!({"targetWidth": 1e39, "targetHeight": 10}), + json!({"targetWidth": 300_001.0, "targetHeight": 10}), + json!({"targetWidth": "10", "targetHeight": 10}), + json!({"targetWidth": 300_001, "targetHeight": 10}), + json!({"targetWidth": 4_294_967_306_u64, "targetHeight": 10}), + json!({"targetWidth": 300_000, "targetHeight": 300_000}), + json!({"targetWidth": 10, "targetHeight": 10, "resample": "none"}), + json!({"targetWidth": 10, "targetHeight": 10, "resample": 3}), + json!({"resolution": 0}), + json!({"resolution": -72}), + json!({"resolution": 1e9}), + json!({"resolution": "300"}), + ]; + for extra in bad_params { + let mut s = session(); + let (size, dpi, past) = (doc(&s).size, doc(&s).resolution_dpi, s.active().unwrap().history.past_len()); + let mut p = rect.clone(); + if let (Some(o), Some(e)) = (p.as_object_mut(), extra.as_object()) { + o.extend(e.clone()); + } + assert!(s.execute("image.crop", p.clone()).is_err(), "{p}"); + assert_eq!((doc(&s).size, doc(&s).resolution_dpi, s.active().unwrap().history.past_len()), (size, dpi, past), "{p}: nothing changed"); + } +} + +#[test] +fn trim_based_on_top_left_colour() { + let mut s = session(); + s.edit("no fx", |doc, _| { + doc.layers[1].effects.items.clear(); + Ok(()) + }) + .unwrap(); + s.execute("image.trim", json!({"basedOn": "topLeft"})).unwrap(); + assert_eq!(doc(&s).size, Size::new(10, 10)); +} + +#[test] +fn thirty_two_bit_holds_linear_light() { + // Photoshop 27.11: an 8-bit sRGB grey 128 becomes 0.2159 in 32 bits (and 32 → 0.0144), + // and comes back unchanged; alpha keeps its value. + let mut s = Session::new(); + s.execute("file.new", json!({"width": 4, "height": 1, "background": "white"})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.edit("paint", |doc, active| { + let l = doc.layer_mut(active.unwrap()).unwrap(); + l.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 2, 1), &[128.0 / 255.0, 32.0 / 255.0, 1.0, 0.5]); + Ok(()) + }) + .unwrap(); + s.execute("image.mode.bits32", json!({})).unwrap(); + let px = doc(&s).layers[1].surface().unwrap().pixel(0, 0); + for (got, want) in px.iter().zip([0.2159, 0.0144, 1.0, 128.0 / 255.0]) { + assert!((got - want).abs() < 2e-4, "{px:?}"); + } + s.execute("image.mode.bits8", json!({})).unwrap(); + let px = doc(&s).layers[1].surface().unwrap().pixel(0, 0); + for (got, want) in px.iter().zip([128.0 / 255.0, 32.0 / 255.0, 1.0, 128.0 / 255.0]) { + assert!((got - want).abs() < 0.6 / 255.0, "{px:?}"); + } +} + +#[test] +fn grayscale_conversion_matches_photoshop() { + // Photoshop 27.11, default Color Settings (working gray Dot Gain 20 %): Image > Mode > + // Grayscale turns sRGB 64 / 128 / 192 grey and pure red into 46 / 105 / 177 / 107. + let mut s = Session::new(); + s.execute("file.new", json!({"width": 4, "height": 1, "background": "white"})).unwrap(); + s.edit("paint", |doc, _| { + let l = doc.layers.first_mut().unwrap(); + let surf = l.surface_mut().unwrap(); + for (x, c) in [[64.0, 64.0, 64.0], [128.0, 128.0, 128.0], [192.0, 192.0, 192.0], [255.0, 0.0, 0.0]].iter().enumerate() { + surf.fill_rect(Rect::new(x as i32, 0, x as i32 + 1, 1), &[c[0] / 255.0, c[1] / 255.0, c[2] / 255.0, 1.0]); + } + Ok(()) + }) + .unwrap(); + s.execute("image.mode.grayscale", json!({})).unwrap(); + let surf = doc(&s).layers[0].surface().unwrap(); + for (x, want) in [46.0, 105.0, 177.0, 107.0].iter().enumerate() { + let got = surf.pixel(x as i32, 0)[0] * 255.0; + assert!((got - want).abs() <= 1.5, "pixel {x}: {got} vs {want}"); + } +} + +#[test] +fn mode_and_depth_conversions() { + let mut s = session(); + s.execute("image.mode.grayscale", json!({})).unwrap(); + assert_eq!(doc(&s).mode, ColorMode::Grayscale); + assert_eq!(doc(&s).layers[1].surface().unwrap().format().mode, ColorMode::Grayscale); + s.execute("image.mode.bits16", json!({})).unwrap(); + assert_eq!(doc(&s).depth, SampleType::U16); + assert_eq!(doc(&s).layers[1].surface().unwrap().format().sample, SampleType::U16); + assert_eq!(doc(&s).layers[1].mask.as_ref().unwrap().surface.format().sample, SampleType::U16); + s.execute("image.mode.cmyk", json!({})).unwrap(); + s.execute("image.mode.bits32", json!({})).unwrap(); + s.execute("image.mode.lab", json!({})).unwrap(); + s.execute("image.mode.rgb", json!({})).unwrap(); + s.execute("image.mode.bits8", json!({})).unwrap(); + let d = doc(&s); + assert_eq!((d.mode, d.depth), (ColorMode::Rgb, SampleType::U8)); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(doc(&s).depth, SampleType::F32); + let revision = s.active().unwrap().revision; + s.execute("image.mode.bits32", json!({})).unwrap(); + assert_eq!(s.active().unwrap().revision, revision, "an unchanged bit depth must preserve the history branch"); + assert!(s.redo(), "selecting the current depth must not discard the undone conversion"); + assert_eq!(doc(&s).depth, SampleType::U8); +} + +/// Duplicate › Merged Layers Only gives one locked Background when the source has one and a +/// plain "Layer 1" (keeping transparency) when it doesn't, as Photoshop does. +#[test] +fn merged_duplicate_is_a_background_only_when_the_source_has_one() { + let mut s = session(); + s.execute("image.duplicate", json!({"mergedOnly": true})).unwrap(); + let d = doc(&s); + assert!(d.is_background(d.layers[0].id), "source has a Background: the merged copy is one"); + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8, "background": "transparent"})).unwrap(); + s.execute("image.duplicate", json!({"mergedOnly": true})).unwrap(); + let d = doc(&s); + assert!(d.background().is_none(), "transparent source: no Background in the copy"); + assert_eq!(d.layers[0].name, "Layer 1"); +} + +#[test] +fn duplicate_document() { + let mut s = session(); + let r = s.execute("image.duplicate", json!({"mergedOnly": true})).unwrap(); + assert_eq!(r["document"], json!(1)); + assert_eq!(s.documents().len(), 2); + assert_eq!(doc(&s).layers.len(), 1); + assert!(doc(&s).name.ends_with("copy")); +} diff --git a/crates/engine/src/layer_copy_cmds.rs b/crates/engine/src/cmd/layer_copy_cmds.rs similarity index 100% rename from crates/engine/src/layer_copy_cmds.rs rename to crates/engine/src/cmd/layer_copy_cmds.rs diff --git a/crates/engine/src/layer_copy_cmds/tests.rs b/crates/engine/src/cmd/layer_copy_cmds/tests.rs similarity index 100% rename from crates/engine/src/layer_copy_cmds/tests.rs rename to crates/engine/src/cmd/layer_copy_cmds/tests.rs diff --git a/crates/engine/src/layer_label_cmds.rs b/crates/engine/src/cmd/layer_label_cmds.rs similarity index 100% rename from crates/engine/src/layer_label_cmds.rs rename to crates/engine/src/cmd/layer_label_cmds.rs diff --git a/crates/engine/src/layer_label_cmds/tests.rs b/crates/engine/src/cmd/layer_label_cmds/tests.rs similarity index 100% rename from crates/engine/src/layer_label_cmds/tests.rs rename to crates/engine/src/cmd/layer_label_cmds/tests.rs diff --git a/crates/engine/src/layer_list_cmds.rs b/crates/engine/src/cmd/layer_list_cmds.rs similarity index 100% rename from crates/engine/src/layer_list_cmds.rs rename to crates/engine/src/cmd/layer_list_cmds.rs diff --git a/crates/engine/src/layer_mask_props_cmds.rs b/crates/engine/src/cmd/layer_mask_props_cmds.rs similarity index 100% rename from crates/engine/src/layer_mask_props_cmds.rs rename to crates/engine/src/cmd/layer_mask_props_cmds.rs diff --git a/crates/engine/src/layer_mask_props_cmds/tests.rs b/crates/engine/src/cmd/layer_mask_props_cmds/tests.rs similarity index 100% rename from crates/engine/src/layer_mask_props_cmds/tests.rs rename to crates/engine/src/cmd/layer_mask_props_cmds/tests.rs diff --git a/crates/engine/src/layer_menu_cmds.rs b/crates/engine/src/cmd/layer_menu_cmds.rs similarity index 100% rename from crates/engine/src/layer_menu_cmds.rs rename to crates/engine/src/cmd/layer_menu_cmds.rs diff --git a/crates/engine/src/layer_menu_cmds/tests.rs b/crates/engine/src/cmd/layer_menu_cmds/tests.rs similarity index 100% rename from crates/engine/src/layer_menu_cmds/tests.rs rename to crates/engine/src/cmd/layer_menu_cmds/tests.rs diff --git a/crates/engine/src/cmd/layer_multi_cmds.rs b/crates/engine/src/cmd/layer_multi_cmds.rs new file mode 100644 index 0000000000..3966432975 --- /dev/null +++ b/crates/engine/src/cmd/layer_multi_cmds.rs @@ -0,0 +1,166 @@ +//! Multi-layer selection and the commands that act on it: ⌘/⇧-click selection, Select › All / +//! Deselect / Find Layers, Layer › Align and Distribute, Link Layers, Merge Layers, Group from +//! Layers, Arrange › Reverse, Lock Layers and Rename Layer. +//! +//! The selection itself lives in [`DocState::selected_layers`] (UI state, like the active layer): +//! changing it never adds a history step. Every structural change below is one history step. + +use photocraft_color::PixelFormat; +use photocraft_doc::{Document, Layer, LayerContent, LayerId, VideoData}; +use photocraft_geom::Rect; +use serde_json::{Value, json}; + +use crate::commands::{CommandSpec, int_i32}; +use crate::{DocState, EngineError, Result, Session}; + +mod align; +mod damage; +mod moves; +mod selection; +mod structure; + +use align::{align, distribute}; +pub use damage::{layer_bounds, layers_damage, same_pixels, selection_only_change, step_damage}; +pub(crate) use damage::{note_damage, note_inert_insert, note_insert}; +use moves::link_groups; +pub(crate) use moves::shift_surface; +#[cfg(test)] +pub(crate) use moves::with_links; +pub use moves::{move_targets, move_to, moved, moved_target, moves_mask_alone, preview_move, translate}; +use selection::{doc_state, find_layers, select_all_layers, select_linked}; +pub(crate) use selection::{mask_targets, recorded_step, reselect, targets, top_level}; +pub use selection::{select, selected, set_selection}; +pub(crate) use structure::{check_group_depth, deletion_neighbours}; +pub use structure::{delete_selected, duplicate_selected, group_layers, set_visible_selected}; +use structure::{link_layers, lock_layers, merge_layers, rename_layer, reverse}; + +// ---------- enabled predicates ---------- + +fn has_layer(s: &Session) -> std::result::Result<(), String> { + if selected(s).is_empty() { Err("no layer selected".into()) } else { Ok(()) } +} +fn has_doc(s: &Session) -> std::result::Result<(), String> { + doc_state(s).map(|_| ()) +} +fn two_plus(s: &Session) -> std::result::Result<(), String> { + if selected(s).len() >= 2 { Ok(()) } else { Err("select two or more layers".into()) } +} +fn can_align(s: &Session) -> std::result::Result<(), String> { + let d = doc_state(s)?; + match d.selected_layers().len() { + 0 => Err("no layer selected".into()), + // Photoshop aligns to an active selection however many layers are selected; without one, + // a single layer aligns to the canvas and 2+ align to each other. + _ => Ok(()), + } +} +fn can_distribute(s: &Session) -> std::result::Result<(), String> { + if selected(s).len() >= 3 { Ok(()) } else { Err("select three or more layers to distribute".into()) } +} +fn can_link(s: &Session) -> std::result::Result<(), String> { + let d = doc_state(s)?; + let sel = d.selected_layers(); + match sel.len() { + 0 => Err("no layer selected".into()), + 1 if d.doc.layer(sel[0]).is_none_or(|l| l.link_group.is_none()) => Err("select two or more layers to link".into()), + _ => Ok(()), + } +} +fn has_linked(s: &Session) -> std::result::Result<(), String> { + let d = doc_state(s)?; + if link_groups(&d.doc, &d.selected_layers()).is_empty() { Err("the selected layers are not linked".into()) } else { Ok(()) } +} + +fn bad(cmd: &str, msg: impl Into) -> EngineError { + EngineError::BadParams { cmd: cmd.into(), msg: msg.into() } +} + +/// Is more than one layer selected (so single-layer commands should act on the whole set)? +pub fn multi(s: &Session, p: &Value) -> bool { + p.get("layer").is_none() && selected(s).len() > 1 +} + +// ---------- registry ---------- + +pub fn specs() -> Vec { + macro_rules! spec { + ($id:expr, $label:expr, $menu:expr, $sc:expr, $params:expr, $enabled:expr, $run:expr) => { + CommandSpec { id: $id, label: $label, menu: $menu, shortcut: $sc, params: $params, enabled: $enabled, journal: true, run: $run } + }; + } + const ALIGN: &str = r##"{"to":"auto|layers|selection|canvas"="auto"} (auto: the active selection's bounds when there is one, however many layers are selected; else one layer aligns to the canvas and several to their combined bounds)"##; + vec![ + spec!("select.allLayers", "All Layers", &["Select"], Some("Cmd+Alt+A"), "{}", has_doc, |s, _| select_all_layers(s)), + spec!("select.deselectLayers", "Deselect Layers", &["Select"], None, "{}", has_doc, |s, _| { + set_selection(s, Vec::new(), None, None)?; + if let Some(st) = s.active_mut() { + st.active_layer = None; + st.selected_layers.clear(); + } + Ok(Value::Null) + }), + spec!("select.findLayers", "Find Layers", &["Select"], Some("Cmd+Alt+Shift+F"), r##"{"name":str (case-insensitive substring)}"##, has_doc, find_layers), + spec!("layer.selectLinkedLayers", "Select Linked Layers", &["Layer"], None, "{}", has_linked, |s, _| select_linked(s)), + spec!("layer.align.topEdges", "Top Edges", &["Layer", "Align"], None, ALIGN, can_align, |s, p| align(s, p, "topEdges")), + spec!("layer.align.verticalCenters", "Vertical Centers", &["Layer", "Align"], None, ALIGN, can_align, |s, p| align(s, p, "verticalCenters")), + spec!("layer.align.bottomEdges", "Bottom Edges", &["Layer", "Align"], None, ALIGN, can_align, |s, p| align(s, p, "bottomEdges")), + spec!("layer.align.leftEdges", "Left Edges", &["Layer", "Align"], None, ALIGN, can_align, |s, p| align(s, p, "leftEdges")), + spec!("layer.align.horizontalCenters", "Horizontal Centers", &["Layer", "Align"], None, ALIGN, can_align, |s, p| align(s, p, "horizontalCenters")), + spec!("layer.align.rightEdges", "Right Edges", &["Layer", "Align"], None, ALIGN, can_align, |s, p| align(s, p, "rightEdges")), + spec!("layer.distribute.topEdges", "Top Edges", &["Layer", "Distribute"], None, "{}", can_distribute, |s, _| distribute(s, "topEdges")), + spec!("layer.distribute.verticalCenters", "Vertical Centers", &["Layer", "Distribute"], None, "{}", can_distribute, |s, _| distribute( + s, + "verticalCenters" + )), + spec!("layer.distribute.bottomEdges", "Bottom Edges", &["Layer", "Distribute"], None, "{}", can_distribute, |s, _| distribute(s, "bottomEdges")), + spec!("layer.distribute.leftEdges", "Left Edges", &["Layer", "Distribute"], None, "{}", can_distribute, |s, _| distribute(s, "leftEdges")), + spec!("layer.distribute.horizontalCenters", "Horizontal Centers", &["Layer", "Distribute"], None, "{}", can_distribute, |s, _| distribute( + s, + "horizontalCenters" + )), + spec!("layer.distribute.rightEdges", "Right Edges", &["Layer", "Distribute"], None, "{}", can_distribute, |s, _| distribute(s, "rightEdges")), + spec!( + "layer.distribute.horizontally", + "Horizontally", + &["Layer", "Distribute"], + None, + "{} (equal horizontal gaps)", + can_distribute, + |s, _| distribute(s, "horizontally") + ), + spec!("layer.distribute.vertically", "Vertically", &["Layer", "Distribute"], None, "{} (equal vertical gaps)", can_distribute, |s, _| distribute( + s, + "vertically" + )), + spec!("layer.linkLayers", "Link Layers", &["Layer"], None, "{} (toggles: unlinks when the selection is already one link group)", can_link, |s, _| { + link_layers(s) + }), + spec!("layer.mergeLayers", "Merge Layers", &["Layer"], Some("Cmd+E"), "{} (one layer selected: Merge Down)", has_layer, |s, _| merge_layers(s)), + spec!( + "layer.new.groupFromLayers", + "Group from Layers…", + &["Layer", "New"], + None, + r##"{"layer":id?,"name":str?} (no layer: every selected layer)"##, + has_layer, + group_layers + ), + spec!("layer.arrange.reverse", "Reverse", &["Layer", "Arrange"], None, "{}", two_plus, |s, _| reverse(s)), + spec!( + "layer.lockLayers", + "Lock Layers…", + &["Layer"], + None, + r##"{"transparency":bool?,"pixels":bool?,"position":bool?,"artboard":bool?,"all":bool?} (none given: toggle lock all)"##, + has_layer, + lock_layers + ), + spec!("layer.renameLayer", "Rename Layer", &["Layer"], None, r##"{"layer":id?,"name":str}"##, has_layer, rename_layer), + ] +} + +#[cfg(test)] +mod tests; + +#[cfg(test)] +mod layers_panel_parity_tests; diff --git a/crates/engine/src/cmd/layer_multi_cmds/align.rs b/crates/engine/src/cmd/layer_multi_cmds/align.rs new file mode 100644 index 0000000000..b6a98f07a0 --- /dev/null +++ b/crates/engine/src/cmd/layer_multi_cmds/align.rs @@ -0,0 +1,162 @@ +use super::damage::layer_bounds; +use super::moves::{move_layers, with_links}; +use super::selection::{selected, top_level}; +use super::*; + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Edge { + Top, + VCenter, + Bottom, + Left, + HCenter, + Right, +} + +impl Edge { + fn parse(k: &str) -> Option { + Some(match k { + "topEdges" => Edge::Top, + "verticalCenters" => Edge::VCenter, + "bottomEdges" => Edge::Bottom, + "leftEdges" => Edge::Left, + "horizontalCenters" => Edge::HCenter, + "rightEdges" => Edge::Right, + _ => return None, + }) + } + fn vertical(self) -> bool { + matches!(self, Edge::Top | Edge::VCenter | Edge::Bottom) + } + /// The edge's coordinate, doubled so centres stay integral. + fn value2(self, r: &Rect) -> i64 { + let (a, b) = if self.vertical() { (r.y0, r.y1) } else { (r.x0, r.x1) }; + match self { + Edge::Top | Edge::Left => 2 * a as i64, + Edge::Bottom | Edge::Right => 2 * b as i64, + Edge::VCenter | Edge::HCenter => a as i64 + b as i64, + } + } + fn delta(self, d: i32) -> (i32, i32) { + if self.vertical() { (0, d) } else { (d, 0) } + } +} + +/// Selected top-level layers that have content bounds, bottom-to-top. +fn bounded_selection(doc: &Document, sel: &[LayerId]) -> Vec<(LayerId, Rect)> { + top_level(doc, sel).into_iter().filter_map(|id| Some((id, layer_bounds(doc.layer(id)?)?))).collect() +} + +pub(super) fn align(s: &mut Session, p: &Value, kind: &str) -> Result { + let cmd = format!("layer.align.{kind}"); + let edge = Edge::parse(kind).ok_or_else(|| bad(&cmd, "unknown edge"))?; + let sel = selected(s); + let to = p.get("to").and_then(Value::as_str).unwrap_or("auto").to_string(); + let before = s.active().ok_or(EngineError::NoDocument)?.doc.clone(); + let moved = s.edit("Align", |doc, _| { + let items = bounded_selection(doc, &sel); + if items.is_empty() { + return Err(EngineError::Other("the selected layers have no content to align".into())); + } + let target = match to.as_str() { + "canvas" => doc.bounds(), + "selection" => doc.selection.as_ref().map(|m| m.content_bounds()).ok_or_else(|| EngineError::Other("there is no selection to align to".into()))?, + "auto" | "layers" => match (&doc.selection, sel.len()) { + // Photoshop: with an active selection, the layers align to its bounds (Layer › Align + // Layers to Selection), however many are selected. + (Some(m), _) if to == "auto" && !m.content_bounds().is_empty() => m.content_bounds(), + // One layer with no selection aligns to the canvas (otherwise it would align to + // itself), or to the artboard it sits in, as in Photoshop (#7945). + (None, 1) if to == "auto" => items.first().map_or_else(|| doc.bounds(), |(id, _)| board_or_canvas(doc, *id)), + _ => items.iter().fold(Rect::EMPTY, |a, (_, b)| a.union(b)), + }, + other => return Err(bad(&cmd, format!("`to` must be auto|layers|selection|canvas, not `{other}`"))), + }; + if target.is_empty() { + return Err(EngineError::Other("nothing to align to".into())); + } + let t2 = edge.value2(&target); + let moves: Vec<(LayerId, i32, i32)> = items + .iter() + .flat_map(|(id, r)| { + let d = (t2 - edge.value2(r)).div_euclid(2) as i32; + let (dx, dy) = edge.delta(d); + // Linked layers travel with the layer they are linked to. + with_links(doc, &[*id]).into_iter().map(move |l| (l, dx, dy)) + }) + .collect(); + let moves = dedup_moves(doc, moves); + move_layers(doc, &before, &moves)?; + Ok(moves.iter().filter(|m| m.1 != 0 || m.2 != 0).count()) + })?; + Ok(json!({"moved": moved})) +} + +/// The bounds a lone layer aligns to: the artboard holding it, else the canvas. An artboard +/// itself aligns to the canvas. +fn board_or_canvas(doc: &Document, id: LayerId) -> Rect { + doc.artboard_of(id).filter(|board| *board != id).and_then(|board| doc.layer(board)?.artboard().map(|a| a.rect)).unwrap_or_else(|| doc.bounds()) +} + +/// One move per layer (first wins), skipping layers nested in another moved layer. +fn dedup_moves(doc: &Document, moves: Vec<(LayerId, i32, i32)>) -> Vec<(LayerId, i32, i32)> { + let mut out: Vec<(LayerId, i32, i32)> = Vec::new(); + for m in moves { + if !out.iter().any(|o| o.0 == m.0) { + out.push(m); + } + } + let ids: Vec = out.iter().map(|m| m.0).collect(); + let keep = top_level(doc, &ids); + out.retain(|m| keep.contains(&m.0)); + out +} + +pub(super) fn distribute(s: &mut Session, kind: &str) -> Result { + let sel = selected(s); + let kind = kind.to_string(); + let before = s.active().ok_or(EngineError::NoDocument)?.doc.clone(); + let moved = s.edit("Distribute", |doc, _| { + let mut items = bounded_selection(doc, &sel); + if items.len() < 3 { + return Err(EngineError::Other("distributing needs three or more layers with content".into())); + } + let n = items.len(); + let mut moves = Vec::new(); + match kind.as_str() { + "horizontally" | "vertically" => { + // Equal gaps between neighbours; the outermost layers stay put. + let v = kind == "vertically"; + let lo = |r: &Rect| if v { r.y0 } else { r.x0 } as i64; + let hi = |r: &Rect| if v { r.y1 } else { r.x1 } as i64; + items.sort_by_key(|(_, r)| (lo(r) + hi(r), lo(r))); + let span = hi(&items[n - 1].1) - lo(&items[0].1); + let total: i64 = items.iter().map(|(_, r)| hi(r) - lo(r)).sum(); + let gap = (span - total) as f64 / (n - 1) as f64; + let mut cursor = lo(&items[0].1) as f64; + for (id, r) in &items { + let want = cursor.round() as i64; + let d = (want - lo(r)) as i32; + moves.push(if v { (*id, 0, d) } else { (*id, d, 0) }); + cursor += (hi(r) - lo(r)) as f64 + gap; + } + } + k => { + let edge = Edge::parse(k).ok_or_else(|| bad("layer.distribute", format!("unknown kind `{k}`")))?; + items.sort_by_key(|(_, r)| edge.value2(r)); + let (first, last) = (edge.value2(&items[0].1) as f64, edge.value2(&items[n - 1].1) as f64); + for (i, (id, r)) in items.iter().enumerate() { + let want2 = first + (last - first) * i as f64 / (n - 1) as f64; + let d = ((want2 - edge.value2(r) as f64) / 2.0).round() as i32; + let (dx, dy) = edge.delta(d); + moves.push((*id, dx, dy)); + } + } + } + let moves: Vec<_> = moves.into_iter().flat_map(|(id, dx, dy)| with_links(doc, &[id]).into_iter().map(move |l| (l, dx, dy))).collect(); + let moves = dedup_moves(doc, moves); + move_layers(doc, &before, &moves)?; + Ok(moves.iter().filter(|m| m.1 != 0 || m.2 != 0).count()) + })?; + Ok(json!({"moved": moved})) +} diff --git a/crates/engine/src/cmd/layer_multi_cmds/damage.rs b/crates/engine/src/cmd/layer_multi_cmds/damage.rs new file mode 100644 index 0000000000..acc49ff88c --- /dev/null +++ b/crates/engine/src/cmd/layer_multi_cmds/damage.rs @@ -0,0 +1,517 @@ +use super::*; + +/// The document pixels an edit of the layers `ids` (moved, shown, hidden or restyled; contents +/// otherwise as they were) can have changed from `before` to `after`, or `None` for anywhere. +pub fn layers_damage(before: &Document, after: &Document, ids: &[LayerId]) -> Option { + let mut out = Rect::EMPTY; + for d in [before, after] { + let canvas = d.bounds(); + for id in ids { + // A layer gone from one side (never for a move) changes who knows what. + let (siblings, k, outer) = siblings_of(d, *id)?; + let b = photocraft_compose::change_bounds_in(siblings, k, outer, canvas)?; + if !b.is_empty() { + out = if out.is_empty() { b } else { out.union(&b) }; + } + } + } + Some(out) +} + +/// The sibling list holding layer `id` in `doc` (bottom→top), its index there, and the list +/// holding its parent group with the group's index (`None` at the top level). +type Siblings<'d> = (&'d [Layer], usize, Option<(&'d [Layer], usize)>); + +fn siblings_of(doc: &Document, id: LayerId) -> Option> { + let path = doc.path_of(id)?; + let (&k, parent) = path.split_last()?; + let Some((&g, grand)) = parent.split_last() else { return Some((doc.layers.as_slice(), k, None)) }; + let outer = if grand.is_empty() { doc.layers.as_slice() } else { doc.layer_at(grand)?.children()? }; + Some((outer.get(g)?.children()?, k, Some((outer, g)))) +} + +/// Report [`layers_damage`] as the active document's last change, so the canvas recomposites +/// only that (grown by the effect reach around it) instead of everything. +pub(crate) fn note_damage(s: &mut Session, before: &Document, ids: &[LayerId]) { + let Some(st) = s.active_mut() else { return }; + if before.size != st.doc.size { + return; + } + st.last_damage = layers_damage(before, &st.doc, ids); +} + +/// Whether two surfaces hold identical pixels: same format and default pixel, and the same +/// copy-on-write tile pointers at the same coordinates. Both documents stay alive during the +/// comparison, so tile addresses cannot be reused under it. +fn surfaces_equal(a: &photocraft_raster::Surface, b: &photocraft_raster::Surface) -> bool { + a.format() == b.format() + && a.default_pixel() == b.default_pixel() + && a.tile_count() == b.tile_count() + && a.tiles().zip(b.tiles()).all(|((ca, ta), (cb, tb))| ca == cb && std::sync::Arc::ptr_eq(ta, tb)) +} + +/// Byte blobs kept in `Arc`s (PSD raw blocks, embedded smart-object sources): pointer-identical +/// or content-equal (they are small compared to pixels, and undo steps rarely re-parse them). +fn blob_equal(x: &std::sync::Arc>, y: &std::sync::Arc>) -> bool { + std::sync::Arc::ptr_eq(x, y) || (x.len() == y.len() && x.as_slice() == y.as_slice()) +} + +fn blobs_equal(a: &Option>>, b: &Option>>) -> bool { + match (a, b) { + (None, None) => true, + (Some(x), Some(y)) => blob_equal(x, y), + _ => false, + } +} + +/// Layer masks (also the smart-filter mask): scalars plus tile-pointer surface identity. +fn masks_equal(a: &Option, b: &Option) -> bool { + match (a, b) { + (None, None) => true, + (Some(x), Some(y)) => { + x.enabled == y.enabled && x.linked == y.linked && x.density == y.density && x.feather == y.feather && surfaces_equal(&x.surface, &y.surface) + } + _ => false, + } +} + +fn texts_equal(a: &photocraft_doc::TextLayer, b: &photocraft_doc::TextLayer) -> bool { + a.text == b.text + && a.font_family == b.font_family + && a.size_pt == b.size_pt + && a.color == b.color + && a.transform == b.transform + && a.runs == b.runs + && a.paragraphs == b.paragraphs + && a.shape == b.shape + && a.orientation == b.orientation + && a.antialias == b.antialias + && a.warp == b.warp + && match (&a.cache, &b.cache) { + (None, None) => true, + (Some(x), Some(y)) => surfaces_equal(x, y), + _ => false, + } + && blobs_equal(&a.psd_raw, &b.psd_raw) +} + +fn smarts_equal(a: &photocraft_doc::SmartObject, b: &photocraft_doc::SmartObject) -> bool { + a.filters_enabled == b.filters_enabled + && a.transform == b.transform + && a.smart_filters == b.smart_filters + && a.stack_mode == b.stack_mode + && a.perspective == b.perspective + && a.warp == b.warp + && match (&a.source, &b.source) { + (photocraft_doc::SmartSource::Embedded { file_name: x, bytes: xb }, photocraft_doc::SmartSource::Embedded { file_name: y, bytes: yb }) => { + x == y && blob_equal(xb, yb) + } + (photocraft_doc::SmartSource::Linked { path: x }, photocraft_doc::SmartSource::Linked { path: y }) => x == y, + _ => false, + } + && match (&a.cache, &b.cache) { + (None, None) => true, + (Some(x), Some(y)) => surfaces_equal(x, y), + _ => false, + } + && blobs_equal(&a.psd_raw, &b.psd_raw) + && masks_equal(&a.filter_mask, &b.filter_mask) +} + +/// Extra alpha/spot channels (the image itself in Multichannel mode). +fn alpha_channels_equal(a: &photocraft_doc::AlphaChannel, b: &photocraft_doc::AlphaChannel) -> bool { + a.name == b.name && a.spot == b.spot && a.color == b.color && a.opacity == b.opacity && a.indicates == b.indicates && surfaces_equal(&a.surface, &b.surface) +} + +/// Whether two layers render to identical pixels in place. Everything the compositor reads is +/// compared structurally — no hashing, a hash collision would under-report damage; pixels are +/// identified by their copy-on-write tile pointers. Group children are deliberately *not* +/// compared here: the caller walks into them, so an edit inside a group damages only the +/// edited child's extent, not the whole group's. The destructure is exhaustive, so a new +/// `Layer` field fails to compile until it is classified: compared, or explicitly ignored +/// (name, locks, label, `psd_blocks`, `psd_id`, link group, XMP — none of them composite; video +/// bails out earlier in the walk). +fn layer_pixels_equal(a: &Layer, b: &Layer) -> bool { + let Layer { + id, + name: _, + visible, + locks: _, + blend, + opacity, + fill_opacity, + clipped, + mask, + vector_mask, + effects, + label: _, + content, + psd_blocks: _, + psd_id: _, + fill_cache, + link_group: _, + excluded_channels, + blend_if, + advanced, + video: _, + xmp: _, + } = a; + *id == b.id + && *visible == b.visible + && *blend == b.blend + && *opacity == b.opacity + && *fill_opacity == b.fill_opacity + && *clipped == b.clipped + && masks_equal(mask, &b.mask) + && *vector_mask == b.vector_mask + && *effects == b.effects + && *excluded_channels == b.excluded_channels + && *blend_if == b.blend_if + && *advanced == b.advanced + && match (content, &b.content) { + (LayerContent::Raster(x), LayerContent::Raster(y)) => surfaces_equal(x, y), + // Children are walked separately; only the group's own clipping frame counts. + (LayerContent::Group(x), LayerContent::Group(y)) => x.artboard == y.artboard, + (LayerContent::Fill(x), LayerContent::Fill(y)) => x == y, + (LayerContent::Adjustment(x), LayerContent::Adjustment(y)) => x == y, + (LayerContent::Text(x), LayerContent::Text(y)) => texts_equal(x, y), + (LayerContent::Shape(x), LayerContent::Shape(y)) => x == y, + (LayerContent::Smart(x), LayerContent::Smart(y)) => smarts_equal(x, y), + _ => false, + } + && match (fill_cache, &b.fill_cache) { + (None, None) => true, + (Some(x), Some(y)) => x.fill == y.fill && surfaces_equal(&x.surface, &y.surface), + _ => false, + } +} + +/// Document-level fields the compositor reads: all must match for a bounded damage claim. The +/// destructure is exhaustive, so a new `Document` field fails to compile until it is classified +/// here — compared when it composites, or explicitly ignored (the pixel-irrelevant allowlist: +/// identity, name, selection, guides, paths, layer comps, annotations, automation state). +fn doc_pixels_equal(a: &Document, b: &Document) -> bool { + let Document { + id: _, + name: _, + size, + resolution_dpi, + mode, + depth, + icc_profile, + layers: _, + channels, + guides: _, + ruler_origin: _, + selection: _, + metadata: _, + global_light, + paths: _, + work_path: _, + clipping_path: _, + quick_mask, + quick_mask_unselected: _, + patterns, + color_table, + duotone, + layer_comps: _, + last_applied_comp: _, + last_document_state: _, + measurement: _, + notes: _, + text_styles: _, + slices: _, + variables: _, + timeline: _, + file_encoding: _, + } = a; + *size == b.size + && resolution_dpi.to_bits() == b.resolution_dpi.to_bits() + && *mode == b.mode + && *depth == b.depth + && icc_profile.as_deref() == b.icc_profile.as_deref() + && channels.len() == b.channels.len() + && channels.iter().zip(&b.channels).all(|(x, y)| alpha_channels_equal(x, y)) + && *global_light == b.global_light + && match (quick_mask, &b.quick_mask) { + (None, None) => true, + (Some(x), Some(y)) => alpha_channels_equal(x, y), + _ => false, + } + && *patterns == b.patterns + && *color_table == b.color_table + && *duotone == b.duotone +} + +/// Whether `a` and `b` composite to the same pixels: they differ at most in fields the +/// compositor never reads (selection, guides, paths, names, …), by the same classification as +/// [`step_damage`] but without computing any bounds. Cheap: pixels compare by tile pointer. +/// Conservative (`false`) past a nesting depth no real document reaches. +pub fn same_pixels(a: &Document, b: &Document) -> bool { + pixels_equal_with(a, b, |_, _| false) +} + +/// [`same_pixels`], with video layers equal when `video_equal` says their frame stacks are. +fn pixels_equal_with(a: &Document, b: &Document, video_equal: fn(&VideoData, &VideoData) -> bool) -> bool { + fn walk(xs: &[Layer], ys: &[Layer], depth: usize, video_equal: fn(&VideoData, &VideoData) -> bool) -> bool { + depth < 256 + && xs.len() == ys.len() + && xs.iter().zip(ys).all(|(x, y)| { + layer_pixels_equal(x, y) + && match (&x.video, &y.video) { + (None, None) => true, + (Some(vx), Some(vy)) => video_equal(vx, vy), + _ => false, + } + && match (x.children(), y.children()) { + (Some(xc), Some(yc)) => walk(xc, yc, depth + 1, video_equal), + (None, None) => true, + _ => false, + } + }) + } + doc_pixels_equal(a, b) && walk(&a.layers, &b.layers, 0, video_equal) +} + +/// Whether two video layers hold the same frames: the same settings and stack shape +/// (`VideoData`'s own, shallow equality) and the same tile pointers in every frame, painted and +/// original. Pointer compares only, like [`surfaces_equal`]. +fn video_frames_equal(a: &VideoData, b: &VideoData) -> bool { + let frames = |x: &[photocraft_raster::Surface], y: &[photocraft_raster::Surface]| x.len() == y.len() && x.iter().zip(y).all(|(f, g)| surfaces_equal(f, g)); + *a == *b + && frames(&a.frames, &b.frames) + && match (&a.original_frames, &b.original_frames) { + (Some(x), Some(y)) => frames(x, y), + (None, None) => true, + _ => false, + } +} + +/// Whether `a` and `b` differ at most in their selection (#6865): a selection step, which must +/// not mark a clean document modified. Pixels compare by tile pointer (as in [`same_pixels`], +/// plus every frame of a video layer, whose own equality is shallow); every other field compares +/// structurally, where copy-on-write `Arc`s of `Eq` data short-circuit on pointer identity. The +/// destructure is exhaustive, so a new `Document` field fails to compile until it is classified. +pub fn selection_only_change(a: &Document, b: &Document) -> bool { + let Document { + id, + name, + size: _, + resolution_dpi: _, + mode: _, + depth: _, + icc_profile: _, + layers, + channels: _, + guides, + ruler_origin, + selection: _, + metadata, + global_light: _, + paths, + work_path, + clipping_path, + quick_mask: _, + quick_mask_unselected, + patterns: _, + color_table: _, + duotone: _, + layer_comps, + last_applied_comp, + last_document_state, + measurement, + notes, + text_styles, + slices, + variables, + timeline, + file_encoding, + } = a; + // The ignored fields above are the pixel ones `pixels_equal_with` already compares. + pixels_equal_with(a, b, video_frames_equal) + && *id == b.id + && *name == b.name + && *layers == b.layers + && *guides == b.guides + && *ruler_origin == b.ruler_origin + && *metadata == b.metadata + && *paths == b.paths + && *work_path == b.work_path + && *clipping_path == b.clipping_path + && *quick_mask_unselected == b.quick_mask_unselected + && *layer_comps == b.layer_comps + && *last_applied_comp == b.last_applied_comp + && *last_document_state == b.last_document_state + && *measurement == b.measurement + && *notes == b.notes + && *text_styles == b.text_styles + && *slices == b.slices + && *variables == b.variables + && *timeline == b.timeline + && *file_encoding == b.file_encoding +} + +/// Pixels a single history step can have changed between `a` and `b` (the documents on either +/// side of an edit, its undo or its redo): the union of the change bounds of every layer whose +/// pixels differ, so a local edit recomposites only that area instead of the whole canvas. A +/// layer only one side has (a duplicate, a paste, a deleted layer) counts where it draws (see +/// [`one_sided_bounds`]); one that draws nothing ([`inert_at`]) changes nothing. `None` +/// (composite everything) when the step touched anything the layer walk cannot bound: +/// document-level fields the compositor reads (canvas size, mode, depth, profile, global light, +/// patterns, channels, palettes), layer order and kind changes, layers added or removed that +/// reach outside their own bounds, layer properties that do (clipping, excluded channels — +/// what `layer.setProps` already reports as unbounded), and video layers. Inserting a copy of a +/// 12 MP layer used to recomposite every layer of the document (#2883, P8/P9 in +/// `perf/budgets.toml`). +pub fn step_damage(a: &Document, b: &Document) -> Option { + if !doc_pixels_equal(a, b) { + return None; + } + /// The list holding a sibling list's parent group, and the group's index there. + type Outer<'d> = Option<(&'d [Layer], usize)>; + fn walk(xs: &[Layer], ys: &[Layer], (ox, oy): (Outer, Outer), a: &Document, b: &Document, out: &mut Rect) -> bool { + // Pair the layers by id, stepping over layers only one side has: one that draws nothing + // changes no pixels (a new empty layer or group, #1771), any other only where it draws. + let one_sided = |layers: &[Layer], k: usize, outer: Outer, canvas: Rect, out: &mut Rect| { + let Some(r) = one_sided_bounds(layers, k, outer, canvas) else { return false }; + if !r.is_empty() { + *out = if out.is_empty() { r } else { out.union(&r) }; + } + true + }; + let (mut i, mut j) = (0, 0); + loop { + let (x, y) = match (xs.get(i), ys.get(j)) { + (None, None) => return true, + (Some(x), Some(y)) if x.id == y.id => (x, y), + _ if inert_at(ys, j) => { + j += 1; + continue; + } + _ if inert_at(xs, i) => { + i += 1; + continue; + } + (_, Some(y)) if xs.iter().all(|x| x.id != y.id) => { + if !one_sided(ys, j, oy, b.bounds(), out) { + return false; + } + j += 1; + continue; + } + (Some(x), _) if ys.iter().all(|y| y.id != x.id) => { + if !one_sided(xs, i, ox, a.bounds(), out) { + return false; + } + i += 1; + continue; + } + // Both sides have the layer, in another order. + _ => return false, + }; + let (xk, yk) = (i, j); + i += 1; + j += 1; + if x.video.is_some() || y.video.is_some() { + return false; + } + // Clipping and channel exclusion change how *other* layers render, outside this + // layer's own bounds; they have no bounded damage. + if x.clipped != y.clipped || x.excluded_channels != y.excluded_channels { + return false; + } + if !layer_pixels_equal(x, y) { + // Both sides' extents: a move changes pixels where it left and where it landed. + // A clipped adjustment reaches as far as its base (#6535). + let (Some(bx), Some(by)) = + (photocraft_compose::change_bounds_in(xs, xk, ox, a.bounds()), photocraft_compose::change_bounds_in(ys, yk, oy, b.bounds())) + else { + return false; + }; + *out = if out.is_empty() { bx.union(&by) } else { out.union(&bx).union(&by) }; + } + match (x.children(), y.children()) { + (Some(xc), Some(yc)) => { + if !walk(xc, yc, (Some((xs, xk)), Some((ys, yk))), a, b, out) { + return false; + } + } + (None, None) => {} + _ => return false, + } + } + } + let mut out = Rect::EMPTY; + if walk(&a.layers, &b.layers, (None, None), a, b, &mut out) { Some(out) } else { None } +} + +/// The pixels adding or removing `layers[k]` can change, when that is bounded: its change bounds +/// (`photocraft_compose::change_bounds_in`: not for an unclipped adjustment, or a pass-through +/// group holding one; a clipped adjustment's are its base's), provided it isn't the clipping base +/// of clipped layers above it (they would change base), and neither it nor anything inside it is +/// a video layer or excludes channels (both reach outside the layer's bounds, see +/// [`step_damage`]). +fn one_sided_bounds(layers: &[Layer], k: usize, outer: Option<(&[Layer], usize)>, canvas: Rect) -> Option { + fn contained(l: &Layer, depth: usize) -> bool { + depth < 256 && l.video.is_none() && l.excluded_channels == 0 && l.children().is_none_or(|c| c.iter().all(|c| contained(c, depth + 1))) + } + let l = layers.get(k)?; + let new_base = !l.clipped && layers.get(k + 1).is_some_and(|above| above.clipped); + if new_base || !contained(l, 0) { + return None; + } + photocraft_compose::change_bounds_in(layers, k, outer, canvas) +} + +/// Whether `layers[k]` draws nothing wherever it sits, so adding or removing it leaves the +/// composite as it was: an empty pixel layer (no tiles, transparent default) or an empty group, +/// in a Normal or Pass Through blend with no mask, vector mask, effects or Advanced Blending. +/// A clipping base that would gain or lose the clipped layers above it is not inert. +fn inert_at(layers: &[Layer], k: usize) -> bool { + let Some(l) = layers.get(k) else { return false }; + let empty = match &l.content { + LayerContent::Raster(s) => s.tile_count() == 0 && s.format().alpha && s.default_bytes().iter().all(|b| *b == 0), + LayerContent::Group(g) => g.children.is_empty() && g.artboard.is_none(), + _ => false, + }; + empty + && matches!(l.blend, photocraft_doc::BlendMode::Normal | photocraft_doc::BlendMode::PassThrough) + && l.mask.is_none() + && l.vector_mask.is_none() + && !photocraft_compose::effects::has_effects(l) + && l.fill_cache.is_none() + && l.video.is_none() + && l.advanced == photocraft_doc::AdvancedBlending::default() + && (l.clipped || layers.get(k + 1).is_none_or(|above| !above.clipped)) +} + +/// Report that adding layer `id` to the active document changed no pixels when it draws +/// nothing ([`inert_at`]), so the canvas doesn't recomposite every layer for it (#1771). Looks +/// only at the new layer and its neighbour, never at other layers' tiles. +pub(crate) fn note_inert_insert(s: &mut Session, id: LayerId) { + let Some(st) = s.active_mut() else { return }; + let Some(path) = st.doc.path_of(id) else { return }; + let Some((&k, parent)) = path.split_last() else { return }; + let siblings = if parent.is_empty() { Some(st.doc.layers.as_slice()) } else { st.doc.layer_at(parent).and_then(Layer::children) }; + if siblings.is_some_and(|sib| inert_at(sib, k)) { + st.last_damage = Some(Rect::EMPTY); + } +} + +/// Report the pixels a command made of more than one edit changed since `before` ([`step_damage`]), +/// so the canvas recomposites only where its new layers draw instead of the whole document. +/// A single [`Session::edit`] already reports its own damage: don't call this after one (#5695). +pub(crate) fn note_insert(s: &mut Session, before: &Document) { + let Some(st) = s.active_mut() else { return }; + st.last_damage = step_damage(before, &st.doc); +} + +/// Content bounds used by Align/Distribute: the layer's pixels (type and shape layers use their +/// rendered pixels), or the union of a group's children. Fill and adjustment layers have none. +pub fn layer_bounds(l: &Layer) -> Option { + let r = match &l.content { + LayerContent::Group(g) => g.children.iter().filter_map(layer_bounds).fold(Rect::EMPTY, |a, b| a.union(&b)), + _ => l.surface().map(|s| s.content_bounds()).unwrap_or(Rect::EMPTY), + }; + (!r.is_empty()).then_some(r) +} diff --git a/crates/engine/src/cmd/layer_multi_cmds/layers_panel_parity_tests.rs b/crates/engine/src/cmd/layer_multi_cmds/layers_panel_parity_tests.rs new file mode 100644 index 0000000000..3982eb9cff --- /dev/null +++ b/crates/engine/src/cmd/layer_multi_cmds/layers_panel_parity_tests.rs @@ -0,0 +1,313 @@ +use super::*; + +/// A 24×16 document with three layers, "Test 0" to "Test 2", above the Background; the last one is active. +fn new_session() -> (Session, Vec) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 24, "height": 16})).unwrap(); + let ids = (0..3).map(|n| LayerId(s.execute("layer.new.layer", json!({"name": format!("Test {n}")})).unwrap()["layer"].as_u64().unwrap())).collect(); + (s, ids) +} + +/// Set one Layers panel option in the preferences, as the Panel Options dialog does. +fn option(s: &mut Session, key: &str, enabled: bool) { + s.prefs.edit(|p| { + let val = p.dialogs.entry("ui.layersPanelOptions".into()).or_insert_with(|| json!({})); + if let Some(o) = val.as_object_mut() { + o.insert(key.to_owned(), json!(enabled)); + } + }); +} + +/// The drag preview equals the committed `layer.moveTo` result and never touches the document or its history. +#[test] +fn preview_matches_real_move_and_never_edits_document_or_history() { + let (mut s, ids) = new_session(); + let params = json!({"layer": ids[0].0, "target": ids[2].0, "position": "above"}); + let before = s.active().unwrap().doc.clone(); + let undo_before = s.active().unwrap().history.entries().len(); + let candidate = preview_move(&before, ¶ms, true).unwrap(); + assert_eq!(*before, *s.active().unwrap().doc); + assert_eq!(s.active().unwrap().history.entries().len(), undo_before); + s.execute("layer.moveTo", params).unwrap(); + assert_eq!(candidate, *s.active().unwrap().doc, "visual preview must match committed layer order"); +} + +/// A previewed ⌥-drag copy names its layers like the committed copy, with and without the "copy" suffix option. +#[test] +fn preview_copy_and_no_copy_suffix_option_match_committed_layers() { + let (mut s, ids) = new_session(); + option(&mut s, "addCopyToCopiedLayersAndGroups", false); + let params = json!({"layer": ids[0].0, "target": ids[2].0, "position": "below", "copy": true}); + let before = s.active().unwrap().doc.clone(); + let candidate = preview_move(&before, ¶ms, false).unwrap(); + s.execute("layer.moveTo", params).unwrap(); + let actual = &s.active().unwrap().doc; + assert_eq!(candidate.layers.iter().map(|l| l.name.as_str()).collect::>(), actual.layers.iter().map(|l| l.name.as_str()).collect::>()); + assert_eq!(actual.layer_count(), before.layer_count() + 1); + assert_eq!(actual.layers.iter().filter(|l| l.name == "Test 0").count(), 2); + let d = s.execute("layer.duplicate", json!({"layer": ids[1].0})).unwrap(); + let duplicate = LayerId(d["layer"].as_u64().unwrap()); + assert_eq!(s.active().unwrap().doc.layer(duplicate).unwrap().name, "Test 1"); + option(&mut s, "addCopyToCopiedLayersAndGroups", true); + let d = s.execute("layer.duplicate", json!({"layer": ids[1].0})).unwrap(); + assert!(s.active().unwrap().doc.layer(LayerId(d["layer"].as_u64().unwrap())).unwrap().name.contains("copy")); +} + +/// Drops the command refuses (or ignores) give no preview and leave the document alone; a multi-layer preview follows the committed stack order. +#[test] +fn preview_rejects_invalid_drop_unchanged() { + let (mut s, ids) = new_session(); + let before = s.active().unwrap().doc.clone(); + // Dropping a layer on itself is a no-op for the command, the others are errors. + for (p, command_rejects) in [ + (json!({"layer": ids[1].0, "target": ids[1].0, "position": "above"}), false), + (json!({"layer": ids[1].0, "target": 999999, "position": "below"}), true), + (json!({"layer": ids[1].0, "target": ids[2].0, "position": "into"}), true), + (json!({"layer": ids[1].0, "target": ids[2].0, "position": "invalid"}), true), + ] { + assert!(preview_move(&before, &p, true).is_none(), "{p}"); + let result = s.execute("layer.moveTo", p.clone()); + if command_rejects { + assert!(result.is_err(), "{p}"); + } else { + assert_eq!(result.unwrap(), Value::Null, "{p}"); + } + assert_eq!(*before, *s.active().unwrap().doc, "{p}"); + } + // Multi-layer preview and commit follow the same stack order regardless of params order. + let p = json!({"layers": [ids[2].0, ids[0].0], "target": ids[1].0, "position": "below"}); + let candidate = preview_move(&before, &p, true).unwrap(); + s.execute("layer.moveTo", p).unwrap(); + assert_eq!(candidate, *s.active().unwrap().doc); +} + +/// A 16×16 document holding `spec` (bottom to top, `*` = clipped) above its Background. Every +/// layer is a translucent, differently placed rectangle, so the stack order and the clip +/// groups both show in the composite. +fn clip_stack(spec: &str) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16})).unwrap(); + for (n, name) in spec.split_whitespace().enumerate() { + let id = LayerId(s.execute("layer.new.layer", json!({"name": name.trim_end_matches('*')})).unwrap()["layer"].as_u64().unwrap()); + let n = n as i32; + let colour = [(n % 3) as f32 * 0.5, ((n + 1) % 3) as f32 * 0.5, ((n + 2) % 3) as f32 * 0.5, 0.6]; + s.edit("paint", |doc, _| { + let layer = doc.layer_mut(id).unwrap(); + layer.clipped = name.ends_with('*'); + layer.surface_mut().unwrap().fill_rect(Rect::new(n * 2, 0, n * 2 + 10, 16), &colour); + Ok(()) + }) + .unwrap(); + } + s +} + +/// Every layer of `doc` from the bottom, `*` marking the clipped ones. +fn stack_text(doc: &Document) -> String { + doc.layers.iter().map(|l| format!("{}{}", l.name, if l.clipped { "*" } else { "" })).collect::>().join(" ") +} + +/// The id of the layer called `name`, searching the whole layer tree. +fn id_of(s: &Session, name: &str) -> u64 { + s.active().unwrap().doc.walk().into_iter().find(|(_, _, l)| l.name == name).unwrap().2.id.0 +} + +/// The preview of `params` and the committed `layer.moveTo` show the same stack (names, clip +/// flags) and the same composite, and both are `want`. +fn assert_preview_is_commit(mut s: Session, params: Value, want: &str) { + let before = s.active().unwrap().doc.clone(); + let preview = preview_move(&before, ¶ms, true).expect("the drop has a preview"); + s.execute("layer.moveTo", params.clone()).unwrap(); + let committed = &s.active().unwrap().doc; + assert_eq!(stack_text(&preview), want, "preview of {params}"); + assert_eq!(stack_text(committed), want, "commit of {params}"); + assert_eq!(photocraft_compose::flatten(&preview).px, photocraft_compose::flatten(committed).px, "composite of {params}"); +} + +/// Previewed moves join and release clipping groups exactly as the committed reorder does, copies included. +#[test] +fn preview_follows_clip_groups_like_the_committed_reorder() { + // The fixtures of `clip_group::reorder_joins_and_leaves_groups`. + for (spec, layers, target, pos, want) in [ + // A layer dropped into a clip group joins it. + ("B C1* C2* U", vec!["U"], "C1", "above", "Background B C1* U* C2*"), + ("B C1* C2* U V", vec!["U", "V"], "C1", "above", "Background B C1* U* V* C2*"), + // A clipped layer dropped off its group is released. + ("B C1* C2* U", vec!["C1"], "U", "above", "Background B C2* U C1"), + // A base moved away releases the layers clipped to it. + ("B C1* C2* U", vec!["B"], "U", "above", "Background C1 C2 U B"), + // A base moved up into its own group joins it, and the layers it left are released. + ("B C1* C2*", vec!["B"], "C1", "above", "Background C1 B* C2"), + ("X B C1* C2* U", vec!["B", "C1"], "U", "above", "Background X C2 U B C1*"), + ] { + let s = clip_stack(spec); + let ids: Vec = layers.iter().map(|n| id_of(&s, n)).collect(); + let t = id_of(&s, target); + assert_preview_is_commit(s, json!({"layers": ids, "target": t, "position": pos}), want); + } + // An option-drag copy joins the clip group it lands in too. + let s = clip_stack("B C1* C2* U"); + let (u, c1) = (id_of(&s, "U"), id_of(&s, "C1")); + assert_preview_is_commit(s, json!({"layer": u, "target": c1, "position": "above", "copy": true}), "Background B C1* U copy* C2* U"); +} + +/// Copying the locked Background in a preview gives the same unlocked copy, joining the clip group it lands in, as the command. +#[test] +fn preview_copies_the_background_like_the_committed_copy() { + let mut s = clip_stack("A B*"); + let (bg, a) = (s.active().unwrap().doc.background().unwrap().id, id_of(&s, "A")); + let before = s.active().unwrap().doc.clone(); + assert_ne!(before.layer(bg).unwrap().locks, Default::default(), "the Background is locked"); + let p = json!({"layer": bg.0, "target": a, "position": "above", "copy": true}); + let preview = preview_move(&before, &p, true).unwrap(); + s.execute("layer.moveTo", p).unwrap(); + let committed = &s.active().unwrap().doc; + // The copy is an ordinary, unlocked layer that joins the clip group it lands in. + assert_eq!(stack_text(committed), "Background A Background copy* B*"); + assert_eq!(stack_text(&preview), stack_text(committed)); + for doc in [&preview, committed] { + assert_eq!(doc.layers.get(2).unwrap().locks, Default::default()); + assert!(doc.layers.first().unwrap().locks != Default::default()); + } + assert_eq!(photocraft_compose::flatten(&preview).px, photocraft_compose::flatten(committed).px); +} + +/// A drop that would move the Background off the bottom has no preview, as the command refuses it. +#[test] +fn preview_refuses_what_would_leave_the_background_off_the_bottom() { + let mut s = clip_stack("A B"); + let (bg, a) = (s.active().unwrap().doc.background().unwrap().id, id_of(&s, "A")); + let before = s.active().unwrap().doc.clone(); + for p in [ + json!({"layer": a, "target": bg.0, "position": "below"}), + json!({"layer": bg.0, "target": bg.0, "position": "below", "copy": true}), + json!({"layer": a, "target": bg.0, "position": "below", "copy": true}), + ] { + assert!(preview_move(&before, &p, true).is_none(), "{p}"); + assert!(s.execute("layer.moveTo", p.clone()).is_err(), "{p}"); + assert_eq!(*before, *s.active().unwrap().doc, "{p}"); + } +} + +/// The UI runs commands through `start`; Expand New Effects applies there as well as to `execute`. +#[test] +fn expand_new_effects_applies_to_ui_start_dispatch_too() { + let (mut s, ids) = new_session(); + option(&mut s, "expandNewEffects", false); + let target = ids[0]; + let started = s.start("layer.layerStyle.dropShadow", json!({"layer": target.0})).unwrap(); + assert!(matches!(started, crate::jobs::Started::Done(_))); + assert!(s.active().unwrap().fx_collapsed.contains(&target)); +} + +/// New Solid Color and Gradient fill layers get the default mask only while Use Default Masks on Fill Layers is on. +#[test] +fn fill_layers_respect_use_default_masks_option() { + let (mut s, _) = new_session(); + option(&mut s, "useDefaultMasksOnFillLayers", false); + let new = s.execute("layer.newFillLayer.solidColor", json!({"color": "#112233"})).unwrap(); + let id = LayerId(new["layer"].as_u64().unwrap()); + assert!(s.active().unwrap().doc.layer(id).unwrap().mask.is_none()); + option(&mut s, "useDefaultMasksOnFillLayers", true); + let new = s.execute("layer.newFillLayer.gradient", json!({})).unwrap(); + let id = LayerId(new["layer"].as_u64().unwrap()); + assert!(s.active().unwrap().doc.layer(id).unwrap().mask.is_some()); +} + +/// With the option off only the default reveal-all mask goes away: an active selection still +/// becomes the layer mask and an explicit path still becomes the vector mask (path first). +#[test] +fn fill_layers_without_default_masks_keep_selection_and_explicit_path_masks() { + const KINDS: [(&str, &str); 3] = [ + ("layer.newFillLayer.solidColor", r##"{"color": "#112233"}"##), + ("layer.newFillLayer.gradient", "{}"), + ("layer.newFillLayer.pattern", r#"{"pattern": "Checkerboard"}"#), + ]; + let path = json!({"subpaths": [{"closed": true, "knots": [[2, 2], [10, 2], [10, 10], [2, 10]]}]}); + let (mut s, _) = new_session(); + option(&mut s, "useDefaultMasksOnFillLayers", false); + // Creates the fill layer; returns its raster mask and whether it has a vector mask. + let create = |s: &mut Session, cmd: &str, params: &str, path: Option<&Value>| { + let mut p: Value = serde_json::from_str(params).unwrap(); + if let Some(path) = path { + p["path"] = path.clone(); + } + let id = LayerId(s.execute(cmd, p).unwrap()["layer"].as_u64().unwrap()); + let l = s.active().unwrap().doc.layer(id).unwrap(); + (l.mask.clone(), l.vector_mask.is_some()) + }; + + for (cmd, params) in KINDS { + let (mask, vector) = create(&mut s, cmd, params, None); + assert!(mask.is_none() && !vector, "{cmd}: no selection, no path: no mask at all"); + } + + s.execute("select.rect", json!({"x": 4, "y": 4, "width": 8, "height": 6})).unwrap(); + for (cmd, params) in KINDS { + let (mask, vector) = create(&mut s, cmd, params, None); + let mask = mask.unwrap_or_else(|| panic!("{cmd}: the selection still becomes the layer mask")); + assert!(!vector, "{cmd}"); + assert!(mask.surface.pixel(6, 6)[0] > 0.99, "{cmd}: inside the selection reveals"); + assert!(mask.surface.pixel(20, 12)[0] < 0.01, "{cmd}: outside the selection hides"); + } + + // An explicit path wins over the selection, as with the option on. + for selected in [true, false] { + if !selected { + s.execute("select.deselect", json!({})).unwrap(); + } + for (cmd, params) in KINDS { + let (mask, vector) = create(&mut s, cmd, params, Some(&path)); + assert!(vector, "{cmd}: the explicit path becomes the vector mask (selection: {selected})"); + assert!(mask.is_none(), "{cmd}: no raster mask next to the vector mask (selection: {selected})"); + } + } +} + +/// Whether new effects start expanded is view state: it adds no history step, and editing an existing effect keeps its disclosure. +#[test] +fn expand_new_effects_is_view_state_and_keeps_edit_history_clean() { + let (mut s, ids) = new_session(); + option(&mut s, "expandNewEffects", false); + let target = ids[0]; + let history = s.active().unwrap().history.entries().len(); + s.execute("layer.layerStyle.dropShadow", json!({"layer": target.0, "size": 2})).unwrap(); + assert_eq!(s.active().unwrap().history.entries().len(), history + 1); + assert!(s.active().unwrap().fx_collapsed.contains(&target)); + option(&mut s, "expandNewEffects", true); + let other = ids[1]; + s.execute("layer.layerStyle.stroke", json!({"layer": other.0, "size": 2})).unwrap(); + assert!(!s.active().unwrap().fx_collapsed.contains(&other)); + // Editing the existing effect must not unexpectedly change its disclosure. + s.execute("layer.layerStyle.dropShadow", json!({"layer": target.0, "size": 5})).unwrap(); + assert!(s.active().unwrap().fx_collapsed.contains(&target)); +} + +/// The disclosure follows the layer the command changes, however the command names it: a +/// layer given by name is not the active one. +#[test] +fn expand_new_effects_follows_a_layer_named_by_its_name() { + let (mut s, ids) = new_session(); + option(&mut s, "expandNewEffects", false); + let (named, active) = (ids[0], ids[2]); + assert_eq!(s.active().unwrap().active_layer, Some(active)); + s.execute("layer.layerStyle.dropShadow", json!({"layer": "Test 0", "size": 2})).unwrap(); + assert!(s.active().unwrap().doc.layer(named).is_some_and(|l| !l.effects.items.is_empty())); + assert!(s.active().unwrap().fx_collapsed.contains(&named), "the named layer's new effects start collapsed"); + assert!(!s.active().unwrap().fx_collapsed.contains(&active), "the active layer is not the one changed"); +} + +/// Transfer Effects changes the layer it moves the effects to, so that is the layer whose +/// disclosure follows the option, not the active layer or the one the effects came from. +#[test] +fn expand_new_effects_follows_the_transfer_destination() { + let (mut s, ids) = new_session(); + let (from, to, active) = (ids[0], ids[1], ids[2]); + s.execute("layer.layerStyle.dropShadow", json!({"layer": from.0, "size": 2})).unwrap(); + option(&mut s, "expandNewEffects", false); + assert_eq!(s.active().unwrap().active_layer, Some(active)); + s.execute("layer.layerStyle.transferEffects", json!({"from": from.0, "to": to.0, "copy": true})).unwrap(); + assert!(s.active().unwrap().doc.layer(to).is_some_and(|l| !l.effects.items.is_empty())); + assert!(s.active().unwrap().fx_collapsed.contains(&to), "the destination's new effects start collapsed"); + assert!(!s.active().unwrap().fx_collapsed.contains(&active), "the active layer is not the one changed"); +} diff --git a/crates/engine/src/cmd/layer_multi_cmds/moves.rs b/crates/engine/src/cmd/layer_multi_cmds/moves.rs new file mode 100644 index 0000000000..a8f4a04918 --- /dev/null +++ b/crates/engine/src/cmd/layer_multi_cmds/moves.rs @@ -0,0 +1,428 @@ +use super::damage::note_damage; +use super::selection::{reselect, same_named_targets, selected, top_level}; +use super::structure::check_group_depth; +use super::*; + +/// A Layers-panel drag of the selected layer records its drop target by name (and which of +/// several same-named layers it is), as [`recorded_selection`] does: the id means nothing in the +/// document the action plays in later, so playback failed with "no such layer" (#7845). Drags of +/// several layers, or of a layer that isn't the selected one, keep their ids. +pub(super) fn recorded_move(s: &Session, mut p: Value, pre_selected: Option<&[LayerId]>) -> Value { + if p.get("layers").is_some() { + return p; + } + let Some(st) = s.active() else { return p }; + let moved = match p.get("layer") { + None => st.active_layer, + Some(v) => match v.as_u64().map(LayerId) { + Some(id) if pre_selected.map_or_else(|| st.selected_layers().as_slice() == [id], |sel| sel == [id]) => Some(id), + _ => return p, + }, + }; + if let Some(fields) = p.as_object_mut() { + fields.remove("layer"); + } + let Some(id) = p.get("target").and_then(Value::as_u64).map(LayerId) else { return p }; + let Some(layer) = st.doc.layer(id) else { return p }; + // A copy leaves its source where it is (it may even land beside it), so the source stays a + // candidate; the new copy (the active layer once the step has run, which is when it is + // recorded) is left out instead, as it doesn't exist yet when the step replays. + let copy = p.get("copy").and_then(Value::as_bool).unwrap_or(false); + let skip = if copy { st.active_layer.filter(|a| Some(*a) != moved) } else { moved }; + let matches = same_named_targets(&st.doc, &layer.name, skip.as_slice()); + let Some(occurrence) = matches.iter().position(|candidate| *candidate == id) else { return p }; + if let Some(fields) = p.as_object_mut() { + fields.insert("target".into(), json!(layer.name)); + if matches.len() > 1 { + fields.insert("targetOccurrence".into(), json!(occurrence)); + } + } + p +} + +/// `layer.moveTo`'s drop target: an id, or a name with `targetOccurrence` choosing among layers +/// that share it (in document order, the `moved` layers aside; required when several do). +fn move_target(s: &Session, p: &Value, moved: &[LayerId]) -> Result { + const CMD: &str = "layer.moveTo"; + match p.get("target") { + Some(Value::String(name)) => { + let occurrence = p + .get("targetOccurrence") + .map(|v| v.as_u64().and_then(|n| usize::try_from(n).ok()).ok_or_else(|| bad(CMD, "`targetOccurrence` must be a non-negative integer"))) + .transpose()?; + let st = s.active().ok_or(EngineError::NoDocument)?; + let matches = same_named_targets(&st.doc, name, moved); + if matches.len() > 1 && occurrence.is_none() { + return Err(bad(CMD, format!("multiple layers named `{name}`; specify `targetOccurrence`"))); + } + let index = occurrence.unwrap_or(0); + matches.get(index).copied().ok_or_else(|| bad(CMD, format!("no layer named `{name}` at occurrence {index}"))) + } + Some(v) => v.as_u64().map(LayerId).ok_or_else(|| bad(CMD, "`target` must be a layer id or name")), + None => Err(bad(CMD, "missing `target`")), + } +} + +// ---------- moving layers ---------- + +pub(super) fn link_groups(doc: &Document, ids: &[LayerId]) -> Vec { + let mut g: Vec = ids.iter().filter_map(|id| doc.layer(*id)?.link_group).collect(); + g.sort_unstable(); + g.dedup(); + g +} + +/// `ids` plus every layer linked to one of them. +pub(crate) fn with_links(doc: &Document, ids: &[LayerId]) -> Vec { + let groups = link_groups(doc, ids); + let mut out = ids.to_vec(); + if !groups.is_empty() { + for (_, _, l) in doc.walk() { + if l.link_group.is_some_and(|g| groups.contains(&g)) && !out.contains(&l.id) { + out.push(l.id); + } + } + } + out +} + +/// Move layers by whole pixels the way the Move tool does: pixels, linked masks, type and +/// vector content (shapes, linked vector masks) all move together. `before` is `doc` as it was +/// before any of the moves (the edit's starting document), read when type and shapes re-render. +pub(crate) fn move_layers(doc: &mut Document, before: &Document, moves: &[(LayerId, i32, i32)]) -> Result<()> { + for &(id, dx, dy) in moves { + if dx == 0 && dy == 0 { + continue; + } + let locks = doc.effective_locks(id); + let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; + if locks.position || locks.all { + return Err(EngineError::Other(format!("layer \"{}\" is position-locked", l.name))); + } + crate::commands::translate_layer(before, l, dx, dy); + crate::vector_cmds::translate_vectors(before, l, dx as f64, dy as f64); + } + Ok(()) +} + +/// Does a move aimed at the layer mask (`"target":"mask"`) move `l`'s mask alone? Only an +/// unlinked mask does (the chain off); a linked one moves with its layer, as in Photoshop. +pub fn moves_mask_alone(l: &Layer) -> bool { + l.mask.as_ref().is_some_and(|m| !m.linked) +} + +/// `layer.translate`: the explicit layer, or every selected layer, plus their linked layers. +/// With `"target":"mask"` a layer whose mask is unlinked moves that mask alone. +pub fn translate(s: &mut Session, p: &Value) -> Result { + let (dx, dy) = match p.get("units").and_then(Value::as_str) { + None | Some("px") => (int_i32("layer.translate", p, "dx")?.unwrap_or(0), int_i32("layer.translate", p, "dy")?.unwrap_or(0)), + // Points (1/72 in), as a Photoshop action records a nudge: whole pixels at this + // document's resolution. + Some("pt") => { + let dpi = s.active().map_or(72.0, |d| f64::from(d.doc.resolution_dpi)); + let to_px = |key: &str| -> Result { + let pt = match p.get(key) { + None => 0.0, + Some(v) => v.as_f64().filter(|f| f.is_finite()).ok_or_else(|| bad("layer.translate", format!("`{key}` must be a number")))?, + }; + let px = (pt * dpi / 72.0).round(); + if px.abs() > f64::from(i32::MAX) { + return Err(bad("layer.translate", format!("`{key}` = {pt} pt is outside the 32-bit coordinate range"))); + } + Ok(px as i32) + }; + (to_px("dx")?, to_px("dy")?) + } + Some(other) => return Err(bad("layer.translate", format!("unknown units `{other}` (px|pt)"))), + }; + let carry = match p.get("selection") { + None | Some(Value::Null) => false, + Some(v) => v.as_bool().ok_or_else(|| bad("layer.translate", "`selection` must be a boolean"))?, + }; + if dx == 0 && dy == 0 { + return Ok(Value::Null); + } + let roots = match crate::commands::explicit_layer(s, p)? { + Some(id) => vec![id], + None => selected(s), + }; + if roots.is_empty() { + return Err(EngineError::Other("no active layer".into())); + } + let mask_target = p.get("target").and_then(Value::as_str) == Some("mask"); + let before = s.active().ok_or(EngineError::NoDocument)?.doc.clone(); + let ids = s.edit("Move", |doc, _| { + let (alone, rest): (Vec, Vec) = roots.iter().partition(|id| mask_target && doc.layer(**id).is_some_and(moves_mask_alone)); + let mut ids = move_targets(doc, &rest); + if ids.is_empty() && alone.is_empty() { + return Err(EngineError::NoLayer(roots[0])); + } + let moves: Vec<_> = ids.iter().map(|&id| (id, dx, dy)).collect(); + move_layers(doc, &before, &moves)?; + for id in alone { + let locks = doc.effective_locks(id); + let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; + if locks.position || locks.all { + return Err(EngineError::Other(format!("layer \"{}\" is position-locked", l.name))); + } + if let Some(m) = &mut l.mask { + m.surface = shift_surface(&m.surface, dx, dy); + } + ids.push(id); + } + // A board moved past any canvas edge grows the canvas, as a new one does (#1531, #3070). + if ids.iter().any(|id| doc.layer(*id).is_some_and(|l| l.artboard().is_some())) { + crate::artboard_cmds::fit_canvas(doc); + } + // The Move tool carries the selection along when it moves several layers whole, as + // Photoshop does (#7538): one step, so Undo takes both back. + if carry { + doc.selection = doc.selection.as_ref().map(|sel| shift_surface(sel, dx, dy)); + } + Ok(ids) + })?; + note_damage(s, &before, &ids); + Ok(Value::Null) +} + +/// The layers a move of `roots` takes along: their linked layers, without layers whose group +/// is also moving (the group carries them). +pub fn move_targets(doc: &Document, roots: &[LayerId]) -> Vec { + top_level(doc, &with_links(doc, roots)) +} + +/// `doc` with the layers `ids` ([`move_targets`]) moved by whole pixels, as `layer.translate` +/// leaves them: the Move tool's live preview while it drags. Type, shape and smart-object pixels +/// shift as they are instead of re-rendering (the commit re-renders them), so a drag frame costs +/// copying the moving pixels only. +pub fn moved(doc: &Document, ids: &[LayerId], dx: i32, dy: i32) -> Result { + moved_target(doc, ids, dx, dy, false) +} + +/// [`moved`] for a drag aimed at the layer mask (`mask_target`): unlinked masks move alone. +pub fn moved_target(doc: &Document, ids: &[LayerId], dx: i32, dy: i32, mask_target: bool) -> Result { + let mut out = doc.clone(); + for &id in ids { + let locks = doc.effective_locks(id); + let l = out.layer_mut(id).ok_or(EngineError::NoLayer(id))?; + if locks.position || locks.all { + return Err(EngineError::Other(format!("layer \"{}\" is position-locked", l.name))); + } + if mask_target && moves_mask_alone(l) { + if let Some(m) = &mut l.mask { + m.surface = shift_surface(&m.surface, dx, dy); + } + continue; + } + shift_shown(doc, l, dx, dy); + } + Ok(out) +} + +/// `photocraft_algo::resample::translate_surface` with the content scan cached per tile (a Move +/// drag shifts the same layers every frame; scanning them each time cost more than the copy). +pub(crate) fn shift_surface(s: &photocraft_raster::Surface, dx: i32, dy: i32) -> photocraft_raster::Surface { + s.translated(dx, dy, photocraft_compose::bounds::content_bounds(s)) +} + +/// [`crate::commands::translate_layer`] plus the vector side, without re-rendering anything. +fn shift_shown(doc: &Document, l: &mut Layer, dx: i32, dy: i32) { + use self::shift_surface as translate_surface; + let a = photocraft_geom::Affine::translate(f64::from(dx), f64::from(dy)); + if let Some(r) = &mut l.effects.reference { + *r = (r.0 + f64::from(dx), r.1 + f64::from(dy)); + } + if let Some(m) = l.mask.as_mut().filter(|m| m.linked) { + m.surface = translate_surface(&m.surface, dx, dy); + } + if let Some(vm) = l.vector_mask.as_mut().filter(|v| v.linked) { + vm.path = vm.path.transform(&a); + } + match &mut l.content { + LayerContent::Raster(s) => *s = translate_surface(s, dx, dy), + LayerContent::Text(t) => { + t.transform = a.mul(&t.transform); + if let Some(c) = &mut t.cache { + *c = translate_surface(c, dx, dy); + } + } + LayerContent::Shape(sh) => crate::vector_cmds::shift_shape(doc, sh, f64::from(dx), f64::from(dy)), + LayerContent::Smart(sm) => crate::smart_cmds::shift_smart(sm, dx, dy), + LayerContent::Group(g) => { + if let Some(ab) = &mut g.artboard { + ab.rect = ab.rect.translate(dx, dy); + } + g.children.iter_mut().for_each(|c| shift_shown(doc, c, dx, dy)); + } + LayerContent::Adjustment(_) | LayerContent::Fill(_) => {} + } +} + +/// Reorder one or multiple layers to a single destination in one undoable edit. +/// +/// Explicit `layers` are ordered according to the source document, not caller ordering. +/// A transient snapshot for the Layers panel's "Preview on canvas when reordering layers". +/// Uses the same source ordering and insertion semantics as `move_to`, but never edits history. +/// Invalid/self-referential hover targets return None (the committed image stays visible). +pub fn preview_move(doc: &Document, p: &Value, add_copy: bool) -> Option { + let target = LayerId(p.get("target")?.as_u64()?); + let position = p.get("position")?.as_str()?; + if !matches!(position, "above" | "below" | "into") { + return None; + } + let copy = p.get("copy").and_then(Value::as_bool).unwrap_or(false); + let ids = if let Some(ids) = p.get("layers") { + ids.as_array()?.iter().map(|v| v.as_u64().map(LayerId)).collect::>>()? + } else { + vec![LayerId(p.get("layer")?.as_u64()?)] + }; + if ids.is_empty() || doc.layer(target).is_none() { + return None; + } + let moved_ids = top_level(doc, &ids); + if moved_ids.is_empty() || moved_ids.iter().any(|id| doc.layer(*id).is_none()) { + return None; + } + if moved_ids.len() == 1 && moved_ids[0] == target && !copy { + return None; + } + let target_path = doc.path_of(target)?; + for id in &moved_ids { + let path = doc.path_of(*id)?; + if target_path.starts_with(&path) && !(copy && *id == target && position != "into") { + return None; + } + } + if position == "into" && !doc.layer(target)?.is_group() { + return None; + } + // The very structural move the drop commits, so the preview shows the same clip groups, + // Background handling and group-depth refusals; a drop `move_to` would refuse has no preview. + let mut preview = doc.clone(); + apply_move(&mut preview, &moved_ids, target, position, copy, add_copy).ok()?; + Some(preview) +} + +/// The document-only part of `move_to`, shared with [`preview_move`] so the Layers panel's hover +/// preview cannot drift from what the drop commits. Moves (or, with `copy`, duplicates) the +/// top-level `moved_ids` to `pos` (`above`, `below` or `into`) `target`, then applies the +/// group-depth cap, the Background-stays-at-the-bottom rule and the clip-group rules +/// (`clip_group::settle`). Returns the ids of the new copies (empty for a move). On `Err` `doc` is +/// half edited: run it inside `Session::edit` or on a scratch copy. +fn apply_move(doc: &mut Document, moved_ids: &[LayerId], target: LayerId, pos: &str, copy: bool, add_copy: bool) -> Result> { + const CMD: &str = "layer.moveTo"; + let background = crate::background_cmds::background_id(doc); + let before = if copy { Default::default() } else { crate::clip_group::Before::read(doc, moved_ids) }; + let mut moved = Vec::with_capacity(moved_ids.len()); + for &id in moved_ids { + moved.push(if copy { crate::commands::layer_copy(doc, id, add_copy)? } else { doc.remove(id).ok_or(EngineError::NoLayer(id))? }); + } + let copies: Vec = if copy { moved.iter().map(|l| l.id).collect() } else { Vec::new() }; + // Look up the destination AFTER removing every source: its indices may have shifted. + let path = doc.path_of(target).ok_or(EngineError::NoLayer(target))?; + if pos == "into" { + let children = doc.layer_at_mut(&path).and_then(Layer::children_mut).ok_or_else(|| bad(CMD, "target is not a group"))?; + children.extend(moved); + } else { + let (&idx, parent) = path.split_last().ok_or(EngineError::NoLayer(target))?; + let siblings = if parent.is_empty() { + &mut doc.layers + } else { + doc.layer_at_mut(parent).and_then(Layer::children_mut).ok_or_else(|| bad(CMD, "target's parent is not a group"))? + }; + let at = if pos == "below" { idx } else { idx + 1 }; + siblings.splice(at..at, moved); + } + check_group_depth(doc, "Reorder Layer")?; + crate::background_cmds::keep_background_at_bottom(background, doc)?; + crate::clip_group::settle(doc, if copy { &copies } else { moved_ids }, &before, false); + Ok(copies) +} + +/// Selected descendants of a moved group remain inside their parent; only top-level +/// selected nodes are detached, and every reference is validated before editing. +pub fn move_to(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "layer.moveTo"; + let pos = p.get("position").and_then(Value::as_str).unwrap_or("above"); + if !matches!(pos, "above" | "below" | "into") { + return Err(bad(CMD, "position must be above, below, or into")); + } + // ⌥-drag in the Layers panel: duplicates land at the target and the layers stay put. + let copy = p.get("copy").and_then(Value::as_bool).unwrap_or(false); + + let batch = p.get("layers"); + if batch.is_some() && p.get("layer").is_some() { + return Err(bad(CMD, "give either `layer` or `layers`, not both")); + } + let requested = if let Some(raw) = batch { + let arr = raw.as_array().filter(|a| !a.is_empty()).ok_or_else(|| bad(CMD, "`layers` must be a nonempty array of ids"))?; + let mut ids = Vec::with_capacity(arr.len()); + for item in arr { + let id = LayerId(item.as_u64().ok_or_else(|| bad(CMD, "every layer id must be an unsigned integer"))?); + if ids.contains(&id) { + return Err(bad(CMD, "duplicate layer id")); + } + ids.push(id); + } + ids + } else { + vec![crate::commands::layer_param(s, p)?] + }; + // A copy moves nothing, so its source stays a candidate (⌥-dragging a layer beside itself). + let target = move_target(s, p, if copy { &[] } else { &requested })?; + let st = s.active().ok_or(EngineError::NoDocument)?; + let doc = &st.doc; + let target_path = doc.path_of(target).ok_or(EngineError::NoLayer(target))?; + for &id in &requested { + if doc.layer(id).is_none() { + return Err(EngineError::NoLayer(id)); + } + } + let moved_ids = top_level(doc, &requested); + if moved_ids.len() == 1 && moved_ids[0] == target && batch.is_none() && !copy { + // Preserve single-layer drag-to-self semantics. + return Ok(Value::Null); + } + // Also rejects dragging a selected group onto any of its descendants. + for id in &moved_ids { + let path = doc.path_of(*id).ok_or(EngineError::NoLayer(*id))?; + // A copy may land beside its own source (not inside it). + let beside_itself = copy && *id == target && pos != "into"; + if target_path.starts_with(&path) && !beside_itself { + return Err(bad(CMD, "target cannot be one of the moved layers or its descendant")); + } + } + if pos == "into" && doc.layer(target).is_none_or(|l| !l.is_group()) { + return Err(bad(CMD, "target is not a group")); + } + + let original_active = st.active_layer; + let add_copy = crate::commands::layer_panel_option(s, "addCopyToCopiedLayersAndGroups", true); + let (count, copies) = s.edit(if copy { "Duplicate Layer" } else { "Reorder Layers" }, |doc, active| { + let copies = apply_move(doc, &moved_ids, target, pos, copy, add_copy)?; + *active = if copy { + copies.last().copied() + } else if batch.is_some() { + original_active.filter(|id| requested.contains(id)).or_else(|| requested.last().copied()) + } else { + moved_ids.first().copied() + }; + Ok((moved_ids.len(), copies)) + })?; + if copy { + let ids: Vec = copies.iter().map(|id| id.0).collect(); + if batch.is_some() { + let active = copies.last().copied(); + reselect(s, copies, active); + return Ok(json!({"moved": count, "layers": ids})); + } + return Ok(json!({"layer": ids.first()})); + } + if batch.is_some() { + let active = original_active.filter(|id| requested.contains(id)).or_else(|| requested.last().copied()); + reselect(s, requested, active); + Ok(json!({"moved": count})) + } else { + Ok(Value::Null) + } +} diff --git a/crates/engine/src/cmd/layer_multi_cmds/selection.rs b/crates/engine/src/cmd/layer_multi_cmds/selection.rs new file mode 100644 index 0000000000..9400760c8e --- /dev/null +++ b/crates/engine/src/cmd/layer_multi_cmds/selection.rs @@ -0,0 +1,285 @@ +use super::moves::{link_groups, recorded_move}; +use super::*; + +// ---------- selection state ---------- + +pub(super) fn doc_state(s: &Session) -> std::result::Result<&DocState, String> { + s.active().ok_or_else(|| "no document open".into()) +} + +/// Selected layers of the active document, bottom-to-top. +pub fn selected(s: &Session) -> Vec { + s.active().map(DocState::selected_layers).unwrap_or_default() +} + +/// The layers a layer command acts on: the `layer` param when given, else every selected layer +/// (bottom-to-top), else the active layer. A single layer behaves exactly as before. +pub(crate) fn targets(s: &Session, p: &serde_json::Value) -> Result> { + if p.get("layer").is_some() { + return Ok(vec![crate::commands::layer_param(s, p)?]); + } + match selected(s) { + sel if sel.is_empty() => Ok(vec![crate::commands::layer_param(s, p)?]), + sel => Ok(sel), + } +} + +/// [`targets`] for a command that adds a layer mask: with several layers selected, those that can +/// take one (no layer mask yet, not the Background); one layer is taken as given. +pub(crate) fn mask_targets(s: &Session, p: &serde_json::Value) -> Result> { + let ids = targets(s, p)?; + if ids.len() < 2 { + return Ok(ids); + } + let d = s.active().ok_or(EngineError::NoDocument)?; + let ids: Vec = ids.into_iter().filter(|id| d.doc.layer(*id).is_some_and(|l| l.mask.is_none() && !d.doc.is_background(l.id))).collect(); + if ids.is_empty() { + return Err(EngineError::Other("none of the selected layers can take a layer mask".into())); + } + Ok(ids) +} + +/// Ids in `ids` that have no ancestor also in `ids` (a selected group already carries its +/// selected children), bottom-to-top. +pub(crate) fn top_level(doc: &Document, ids: &[LayerId]) -> Vec { + let walk = doc.walk(); + let paths: Vec<_> = walk.iter().filter(|(_, _, l)| ids.contains(&l.id)).map(|(p, _, l)| (p.clone(), l.id)).collect(); + paths.iter().filter(|(p, _)| !paths.iter().any(|(q, _)| q.len() < p.len() && p.starts_with(q))).map(|(_, id)| *id).collect() +} + +/// Replace the layer selection without a history step (like [`Session::select_layer`]). +pub fn set_selection(s: &mut Session, ids: Vec, active: Option, anchor: Option) -> Result<()> { + let st = s.active_mut().ok_or(EngineError::NoDocument)?; + if let Some(bad) = ids.iter().chain(active.iter()).find(|id| st.doc.layer(**id).is_none()) { + return Err(EngineError::NoLayer(*bad)); + } + let active = active.or_else(|| ids.last().copied()); + st.selected_layers = ids; + if let Some(a) = active + && !st.selected_layers.contains(&a) + { + st.selected_layers.push(a); + } + st.active_layer = active; + st.layer_anchor = anchor.or(active); + crate::fix_selection(st); + // Selecting layers is not an edit: keep a clean document clean. + let clean = st.saved_revision == st.revision; + st.revision += 1; + if clean { + st.saved_revision = st.revision; + } + st.last_damage = Some(Rect::EMPTY); + Ok(()) +} + +/// After a structural edit, make `ids` the selection (dropping any that no longer exist), which +/// is also what the edit's history state targets. +pub(crate) fn reselect(s: &mut Session, ids: Vec, active: Option) { + if let Some(st) = s.active_mut() { + st.selected_layers = ids; + if let Some(a) = active { + st.active_layer = Some(a); + st.layer_anchor = Some(a); + } + crate::fix_selection(st); + let layers = st.layer_target(); + st.history.set_current_layers(layers); + } +} + +/// Capture a selection target while its name is still known. Later renames/deletions must not +/// change an earlier recorded selection. Direct, non-recording calls retain their numeric IDs. +pub(crate) fn recorded_selection(s: &Session, mut p: Value) -> Value { + let Some(id) = p.get("layer").and_then(Value::as_u64).map(LayerId) else { return p }; + let Some(st) = s.active() else { return p }; + let Some(layer) = st.doc.layer(id) else { return p }; + let matches: Vec<_> = st.doc.walk().into_iter().filter(|(_, _, l)| l.name == layer.name).map(|(_, _, l)| l.id).collect(); + let Some(occurrence) = matches.iter().position(|candidate| *candidate == id) else { return p }; + if let Some(fields) = p.as_object_mut() { + fields.remove("layer"); + fields.insert("name".into(), json!(layer.name)); + if matches.len() > 1 { + fields.insert("occurrence".into(), json!(occurrence)); + } + } + p +} + +/// The layers named `name`, in document order, other than the ones being moved and (groups) their +/// contents. Moving layers never changes the others' order, so an occurrence counted among these +/// means the same layer before the move (when an action replays it) and after it (when the step +/// is recorded). +pub(super) fn same_named_targets(doc: &photocraft_doc::Document, name: &str, moved: &[LayerId]) -> Vec { + fn subtree(l: &Layer, out: &mut Vec, depth: usize) { + out.push(l.id); + if depth < 256 + && let Some(children) = l.children() + { + children.iter().for_each(|c| subtree(c, out, depth + 1)); + } + } + let mut skip = Vec::new(); + for l in moved.iter().filter_map(|id| doc.layer(*id)) { + subtree(l, &mut skip, 0); + } + doc.walk().into_iter().filter(|(_, _, l)| l.name == name && !skip.contains(&l.id)).map(|(_, _, l)| l.id).collect() +} + +/// Normalise parameters when recording an action step. +/// +/// For `layer.select`, captures the layer by name. For other commands, if a numeric `layer` +/// parameter references the document's sole selected layer, normalises it to the target form +/// (omitting `layer`) so that the recorded step applies to whatever layer is targeted when +/// replayed or exported to `.atn` (#7248). +pub(crate) fn recorded_step(s: &Session, id: &str, p: Value, pre_selected: Option<&[LayerId]>) -> Value { + if id == "layer.select" { + return recorded_selection(s, p); + } + if id == "layer.moveTo" { + return recorded_move(s, p, pre_selected); + } + let Some(layer_id) = p.get("layer").and_then(Value::as_u64).map(LayerId) else { return p }; + let is_sole_selected = match pre_selected { + Some(sel) => sel == [layer_id], + None => s.active().is_some_and(|st| st.selected_layers().as_slice() == [layer_id]), + }; + if is_sole_selected { + let mut p = p; + if let Some(fields) = p.as_object_mut() { + fields.remove("layer"); + } + return p; + } + p +} + +fn selection_target(s: &Session, p: &Value) -> Result { + let Some(name) = p.get("name") else { + if p.get("occurrence").is_some() { + return Err(bad("layer.select", "`occurrence` requires `name`")); + } + return crate::commands::explicit_layer(s, p)?.ok_or_else(|| bad("layer.select", "needs `layer` or `name`")); + }; + if p.get("layer").is_some() { + return Err(bad("layer.select", "use either `layer` or `name`, not both")); + } + let name = name.as_str().ok_or_else(|| bad("layer.select", "`name` must be a string"))?; + let occurrence = p + .get("occurrence") + .map(|v| v.as_u64().and_then(|n| usize::try_from(n).ok()).ok_or_else(|| bad("layer.select", "`occurrence` must be a non-negative integer"))) + .transpose()?; + let st = s.active().ok_or(EngineError::NoDocument)?; + let matches: Vec<_> = st.doc.walk().into_iter().filter(|(_, _, l)| l.name == name).map(|(_, _, l)| l.id).collect(); + if matches.len() > 1 && occurrence.is_none() { + return Err(bad("layer.select", format!("multiple layers named `{name}`; specify `occurrence`"))); + } + let index = occurrence.unwrap_or(0); + matches.get(index).copied().ok_or_else(|| bad("layer.select", format!("no layer named `{name}` at occurrence {index}"))) +} + +/// Layer rows follow the Layers panel's visual order, not Document::walk's storage order. +/// Closed groups hide their children unless both endpoints were selected programmatically. +fn range_order(layers: &[Layer], include_collapsed: bool, out: &mut Vec) { + for layer in layers.iter().rev() { + out.push(layer.id); + if let LayerContent::Group(group) = &layer.content + && (group.expanded || include_collapsed) + { + range_order(&group.children, include_collapsed, out); + } + } +} + +/// `layer.select`: `{"layer": id, "mode": "replace|toggle|range|add|remove"}`. +pub fn select(s: &mut Session, p: &Value) -> Result { + let id = selection_target(s, p)?; + let mode = p.get("mode").and_then(Value::as_str).unwrap_or("replace"); + let st = s.active().ok_or(EngineError::NoDocument)?; + if st.doc.layer(id).is_none() { + return Err(EngineError::NoLayer(id)); + } + let mut sel = st.selected_layers(); + match mode { + "replace" => s.select_layer(id)?, + "add" => { + if !sel.contains(&id) { + sel.push(id); + } + set_selection(s, sel, Some(id), Some(id))?; + } + "toggle" => { + if sel.contains(&id) { + if sel.len() == 1 { + // Photoshop keeps at least the clicked layer targeted. + return Ok(json!({"selected": [id.0]})); + } + sel.retain(|x| *x != id); + let active = if st.active_layer == Some(id) { sel.last().copied() } else { st.active_layer }; + set_selection(s, sel, active, active)?; + } else { + sel.push(id); + set_selection(s, sel, Some(id), Some(id))?; + } + } + // Toggle's removing half: a layer that isn't selected stays unselected (Photoshop's + // `removeFromSelection`, recorded by actions). + "remove" => { + if sel.contains(&id) && sel.len() > 1 { + sel.retain(|x| *x != id); + let active = if st.active_layer == Some(id) { sel.last().copied() } else { st.active_layer }; + set_selection(s, sel, active, active)?; + } + } + "range" => { + let anchor = st.layer_anchor.filter(|a| st.doc.layer(*a).is_some()).or(st.active_layer).unwrap_or(id); + let mut order = Vec::new(); + range_order(&st.doc.layers, false, &mut order); + // Engine clients may target a child of a collapsed group that the panel cannot + // click. Retain that capability by using expanded visual order for such calls. + if !order.contains(&anchor) || !order.contains(&id) { + order.clear(); + range_order(&st.doc.layers, true, &mut order); + } + let (a, b) = (order.iter().position(|x| *x == anchor).unwrap_or(0), order.iter().position(|x| *x == id).unwrap_or(0)); + let range = order[a.min(b)..=a.max(b)].to_vec(); + set_selection(s, range, Some(id), Some(anchor))?; + } + other => return Err(bad("layer.select", format!("unknown mode `{other}`"))), + } + Ok(json!({"selected": selected(s).iter().map(|l| l.0).collect::>()})) +} + +pub(super) fn select_all_layers(s: &mut Session) -> Result { + let d = s.active().ok_or(EngineError::NoDocument)?; + let ids: Vec = d.doc.walk().into_iter().filter(|(_, _, l)| !d.doc.is_background(l.id)).map(|(_, _, l)| l.id).collect(); + if ids.is_empty() { + return Err(EngineError::Other("there are no layers to select".into())); + } + let active = d.active_layer.filter(|a| ids.contains(a)).or(ids.last().copied()); + let n = ids.len(); + set_selection(s, ids, active, None)?; + Ok(json!({"selected": n})) +} + +pub(super) fn find_layers(s: &mut Session, p: &Value) -> Result { + let needle = p.get("name").and_then(Value::as_str).ok_or_else(|| bad("select.findLayers", "missing `name`"))?.to_lowercase(); + let d = s.active().ok_or(EngineError::NoDocument)?; + let ids: Vec = d.doc.walk().into_iter().filter(|(_, _, l)| l.name.to_lowercase().contains(&needle)).map(|(_, _, l)| l.id).collect(); + if ids.is_empty() { + return Err(EngineError::Other(format!("no layer name contains \"{needle}\""))); + } + let out = ids.iter().map(|l| l.0).collect::>(); + set_selection(s, ids, None, None)?; + Ok(json!({"selected": out})) +} + +pub(super) fn select_linked(s: &mut Session) -> Result { + let d = s.active().ok_or(EngineError::NoDocument)?; + let groups = link_groups(&d.doc, &d.selected_layers()); + let ids: Vec = d.doc.walk().into_iter().filter(|(_, _, l)| l.link_group.is_some_and(|g| groups.contains(&g))).map(|(_, _, l)| l.id).collect(); + let active = d.active_layer.filter(|a| ids.contains(a)).or(ids.last().copied()); + let n = ids.len(); + set_selection(s, ids, active, active)?; + Ok(json!({"selected": n})) +} diff --git a/crates/engine/src/cmd/layer_multi_cmds/structure.rs b/crates/engine/src/cmd/layer_multi_cmds/structure.rs new file mode 100644 index 0000000000..7800db630f --- /dev/null +++ b/crates/engine/src/cmd/layer_multi_cmds/structure.rs @@ -0,0 +1,288 @@ +use super::selection::{reselect, selected, top_level}; +use super::*; + +// ---------- structural commands ---------- + +pub(super) fn link_layers(s: &mut Session) -> Result { + let sel = selected(s); + let linked = s.edit("Link Layers", |doc, _| { + let groups: Vec> = sel.iter().map(|id| doc.layer(*id).and_then(|l| l.link_group)).collect(); + // Already one link group (or a single linked layer): unlink, like Photoshop's toggle. + let first = groups.first().copied().flatten(); + let unlink = first.is_some() && groups.iter().all(|g| *g == first); + // A loaded file can store any id up to u64::MAX, so the new id must not be a bare + // max + 1 (#961). Unlinking needs no new id at all. + let next = if unlink { None } else { Some(doc.unused_link_group().ok_or_else(|| bad("layer.linkLayers", "no free link group id is left"))?) }; + for id in &sel { + let l = doc.layer_mut(*id).ok_or(EngineError::NoLayer(*id))?; + l.link_group = next; + } + // A group left with a single member is no longer a link. + let mut counts = std::collections::HashMap::::new(); + for (_, _, l) in doc.walk() { + if let Some(g) = l.link_group { + *counts.entry(g).or_default() += 1; + } + } + let lonely: Vec = + doc.walk().iter().filter(|(_, _, l)| l.link_group.is_some_and(|g| counts.get(&g).is_some_and(|&c| c < 2))).map(|(_, _, l)| l.id).collect(); + for id in lonely { + if let Some(l) = doc.layer_mut(id) { + l.link_group = None; + } + } + Ok(!unlink) + })?; + Ok(json!({"linked": linked})) +} + +pub(super) fn lock_layers(s: &mut Session, p: &Value) -> Result { + let sel = selected(s); + let keys = ["transparency", "pixels", "position", "artboard", "all"]; + let given: Vec<(&str, bool)> = keys.iter().filter_map(|k| Some((*k, p.get(*k)?.as_bool()?))).collect(); + s.edit("Lock Layers", |doc, _| { + // No explicit locks: toggle "lock all" (on unless every selected layer is already locked). + let all_locked = sel.iter().all(|id| doc.layer(*id).is_some_and(|l| l.locks.all)); + let given: Vec<(&str, bool)> = if given.is_empty() { vec![("all", !all_locked)] } else { given.clone() }; + for id in &sel { + let l = doc.layer_mut(*id).ok_or(EngineError::NoLayer(*id))?; + for (k, v) in &given { + l.locks.set(k, *v); + } + } + Ok(()) + })?; + Ok(json!({"layers": sel.len()})) +} + +pub(super) fn rename_layer(s: &mut Session, p: &Value) -> Result { + let name = p.get("name").and_then(Value::as_str).filter(|n| !n.trim().is_empty()).ok_or_else(|| bad("layer.renameLayer", "missing `name`"))?.to_string(); + let id = crate::commands::layer_param(s, p)?; + s.edit("Rename Layer", |doc, _| { + doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?.name = name; + Ok(()) + })?; + Ok(Value::Null) +} + +pub(super) fn reverse(s: &mut Session) -> Result { + let sel = selected(s); + s.edit("Reverse", |doc, _| { + let background = crate::background_cmds::background_id(doc); + let ids = top_level(doc, &sel); + if ids.len() < 2 { + return Err(EngineError::Other("select two or more layers to reverse".into())); + } + let paths: Vec> = ids.iter().map(|id| doc.path_of(*id).ok_or(EngineError::NoLayer(*id))).collect::>()?; + let layers: Vec = ids.iter().map(|id| doc.layer(*id).cloned().ok_or(EngineError::NoLayer(*id))).collect::>()?; + // Slots are disjoint (no layer is nested in another), so writing whole layers back to the + // same paths never shifts another slot. + for (path, l) in paths.iter().zip(layers.into_iter().rev()) { + *doc.layer_at_mut(path).ok_or_else(|| EngineError::Other("layer tree changed".into()))? = l; + } + crate::background_cmds::keep_background_at_bottom(background, doc) + })?; + Ok(Value::Null) +} + +/// Refuses an edit that left `doc` nested deeper than [`photocraft_doc::MAX_GROUP_DEPTH`] +/// groups. Called at the end of a `Session::edit` closure, so an `Err` leaves the document and +/// history untouched. +pub(crate) fn check_group_depth(doc: &Document, what: &str) -> Result<()> { + if doc.max_group_depth() > photocraft_doc::MAX_GROUP_DEPTH { + return Err(EngineError::Other(format!("{what} would nest layers deeper than {} groups", photocraft_doc::MAX_GROUP_DEPTH))); + } + Ok(()) +} + +/// Group Layers (⌘G) / Group from Layers: the explicit layer, or every selected layer, moves +/// into a new, collapsed group placed where the top-most of them was. Bottom-to-top order is +/// preserved. +pub fn group_layers(s: &mut Session, p: &Value) -> Result { + let ids = match crate::commands::explicit_layer(s, p)? { + Some(id) => vec![id], + None => selected(s), + }; + if ids.is_empty() { + return Err(EngineError::Other("no layer selected".into())); + } + let name = p.get("name").and_then(Value::as_str).map(str::to_string); + let gid = s.edit("Group Layers", |doc, active| { + let ids = top_level(doc, &ids); + let top = *ids.last().ok_or(EngineError::NoLayer(LayerId(0)))?; + let name = name.unwrap_or_else(|| doc.next_layer_name("Group")); + // Photoshop creates the group collapsed, so the panel shows one row in place of the layers. + let mut group = Layer::group(name, vec![]); + if let LayerContent::Group(g) = &mut group.content { + g.expanded = false; + } + let gid = doc.insert_above(Some(top), group); + let mut children = Vec::with_capacity(ids.len()); + for id in &ids { + children.push(doc.remove(*id).ok_or(EngineError::NoLayer(*id))?); + } + *doc.layer_mut(gid).and_then(Layer::children_mut).ok_or(EngineError::NoLayer(gid))? = children; + check_group_depth(doc, "Group Layers")?; + *active = Some(gid); + Ok(gid) + })?; + reselect(s, vec![gid], Some(gid)); + Ok(json!({ "layer": gid.0 })) +} + +pub(super) fn merge_layers(s: &mut Session) -> Result { + let sel = selected(s); + if sel.len() < 2 { + // ⌘E on a lone group is Photoshop's Merge Group (#3832); on a layer, Merge Down. + if let Some(&id) = sel.first() + && s.active().and_then(|d| d.doc.layer(id)).is_some_and(|l| matches!(l.content, LayerContent::Group(_))) + { + return s.execute("layer.mergeGroup", json!({ "layer": id.0 })); + } + return s.execute("layer.mergeDown", json!({})); + } + let mid = s.edit("Merge Layers", |doc, active| { + let ids = top_level(doc, &sel); + let lowest_id = *ids.first().ok_or_else(|| EngineError::Other("Merge Layers needs two or more layers".into()))?; + let is_background = doc.is_background(lowest_id); + + let mut solo = doc.clone(); + solo.layers = ids.iter().filter_map(|id| doc.layer(*id)).filter(|l| l.visible).cloned().collect(); + if solo.layers.is_empty() { + return Err(EngineError::Other("the selected layers are all hidden".into())); + } + + if is_background { + let base = doc.layer(lowest_id).ok_or(EngineError::NoLayer(lowest_id))?.clone(); + let fmt = doc.pixel_format(); + let mut merged = Layer::raster(base.name.clone(), fmt); + merged.locks = base.locks; + merged.label = base.label; + merged.id = lowest_id; + merged.blend = base.blend; + merged.opacity = 1.0; + *crate::pixels_mut(&mut merged)? = crate::pixels::composite_layers(&solo, fmt, None); + for id in &ids[1..] { + doc.remove(*id); + } + *doc.layer_mut(lowest_id).ok_or(EngineError::NoLayer(lowest_id))? = merged; + *active = Some(lowest_id); + Ok(lowest_id) + } else { + let top_id = *ids.last().ok_or_else(|| EngineError::Other("Merge Layers needs two or more layers".into()))?; + let top = doc.layer(top_id).ok_or(EngineError::NoLayer(top_id))?.clone(); + let fmt = doc.pixel_format(); + let fmt = PixelFormat::new(fmt.mode, fmt.sample, true); + let mut merged = Layer::raster(top.name.clone(), fmt); + merged.locks = top.locks; + merged.label = top.label; + // Clipped layers of one chain merge into a layer still clipped to their base. Clipped + // layers of different chains don't: the result, at the top one's slot, would clip the + // lower chain's pixels to the upper chain's base. + let base = crate::clip_group::base_of(doc, top_id); + merged.clipped = base.is_some() && solo.layers.iter().all(|l| l.clipped && crate::clip_group::base_of(doc, l.id) == base); + *crate::pixels_mut(&mut merged)? = crate::pixels::composite_layers_uncropped(&solo, fmt); + let mid = merged.id; + // Hidden selected layers are discarded, as in Photoshop. + for id in &ids[..ids.len() - 1] { + doc.remove(*id); + } + *doc.layer_mut(top_id).ok_or(EngineError::NoLayer(top_id))? = merged; + *active = Some(mid); + Ok(mid) + } + })?; + reselect(s, vec![mid], Some(mid)); + Ok(json!({ "layer": mid.0 })) +} + +/// Next visible layer row below the deleted target, then rows above in reverse order. +/// Group headers precede their children in the UI, unlike Document::walk's storage order. +pub(crate) fn deletion_neighbours(doc: &Document, target: LayerId) -> Vec { + let rows = |expand_all: bool| { + let mut stack: Vec<&Layer> = doc.layers.iter().collect(); + let mut order = Vec::new(); + while let Some(layer) = stack.pop() { + order.push(layer.id); + if let LayerContent::Group(group) = &layer.content + && (expand_all || group.expanded) + { + stack.extend(group.children.iter()); + } + } + order + }; + let mut order = rows(false); + if !order.contains(&target) { + order = rows(true); + } + let Some(index) = order.iter().position(|id| *id == target) else { + return Vec::new(); + }; + order.iter().skip(index + 1).chain(order.iter().take(index).rev()).copied().collect() +} + +/// Delete Layer with several layers selected. +pub fn delete_selected(s: &mut Session) -> Result { + let sel = selected(s); + s.edit("Delete Layers", |doc, active| { + let ids = top_level(doc, &sel); + let neighbours = active.map(|id| deletion_neighbours(doc, id)).unwrap_or_default(); + let before = crate::clip_group::Before::read(doc, &ids); + for id in &ids { + doc.remove(*id).ok_or(EngineError::NoLayer(*id))?; + } + crate::clip_group::settle(doc, &[], &before, false); + if doc.layers.is_empty() { + return Err(EngineError::Other("a document must keep at least one layer".into())); + } + *active = neighbours.into_iter().find(|candidate| doc.layer(*candidate).is_some()); + Ok(()) + })?; + Ok(json!({"deleted": sel.len()})) +} + +/// Duplicate Layer with several layers selected: each copy goes above its original and the +/// copies become the selection. Artboard copies go beside their boards unless `in_place` +/// ([`crate::artboard_cmds::place_copy`]). `label` names the history step (Layer via Copy reuses +/// this path, #2777). +pub fn duplicate_selected(s: &mut Session, in_place: bool, label: &str) -> Result { + let sel = selected(s); + let old_active = s.active().and_then(|d| d.active_layer); + let add_copy = crate::commands::layer_panel_option(s, "addCopyToCopiedLayersAndGroups", true); + let (copies, active) = s.edit(label, |doc, active| { + let mut copies = Vec::new(); + let mut new_active = None; + for id in top_level(doc, &sel) { + // Match the single-layer duplicate path: Background copies become + // ordinary layers, while normal copies retain their original locks. + let dup = crate::commands::layer_copy(doc, id, add_copy)?; + let nid = doc.insert_above(Some(id), dup); + if !in_place { + crate::artboard_cmds::place_copy(doc, nid)?; + } + if Some(id) == old_active { + new_active = Some(nid); + } + copies.push(nid); + } + let a = new_active.or(copies.last().copied()); + *active = a; + Ok((copies, a)) + })?; + let out = copies.iter().map(|l| l.0).collect::>(); + reselect(s, copies, active); + Ok(json!({"layers": out, "layer": active.map(|l| l.0)})) +} + +/// Show/hide every selected layer in one step. +pub fn set_visible_selected(s: &mut Session, visible: bool) -> Result { + let sel = selected(s); + s.edit(if visible { "Show Layers" } else { "Hide Layers" }, |doc, _| { + for id in &sel { + doc.layer_mut(*id).ok_or(EngineError::NoLayer(*id))?.visible = visible; + } + Ok(()) + })?; + Ok(Value::Null) +} diff --git a/crates/engine/src/cmd/layer_multi_cmds/tests.rs b/crates/engine/src/cmd/layer_multi_cmds/tests.rs new file mode 100644 index 0000000000..e8dd5a98f3 --- /dev/null +++ b/crates/engine/src/cmd/layer_multi_cmds/tests.rs @@ -0,0 +1,1385 @@ +use super::*; + +#[test] +fn merge_with_background_preserves_background() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 20, "height": 20})).unwrap(); + let bg_id = s.active().unwrap().doc.layers[0].id; + assert!(s.active().unwrap().doc.is_background(bg_id)); + let l1 = LayerId(s.execute("layer.new.layer", json!({"name": "Generative Fill"})).unwrap()["layer"].as_u64().unwrap()); + set_selection(&mut s, vec![bg_id, l1], Some(l1), Some(bg_id)).unwrap(); + let res = s.execute("layer.mergeLayers", json!({})).unwrap(); + let mid = LayerId(res["layer"].as_u64().unwrap()); + assert_eq!(mid, bg_id); + let doc = &s.active().unwrap().doc; + assert_eq!(doc.layers.len(), 1); + assert!(doc.is_background(mid)); + assert_eq!(doc.layers[0].name, "Background"); +} + +#[test] +fn duplicates_are_numbered_not_stacked() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 20, "height": 20})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Layer 1"})).unwrap(); + let name = |s: &Session| { + let st = s.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().name.clone() + }; + s.execute("layer.duplicate", json!({})).unwrap(); + assert_eq!(name(&s), "Layer 1 copy"); + // Duplicating the copy (the active layer) numbers it rather than adding "copy" again. + s.execute("layer.duplicate", json!({})).unwrap(); + assert_eq!(name(&s), "Layer 1 copy 2"); + s.execute("layer.duplicate", json!({})).unwrap(); + assert_eq!(name(&s), "Layer 1 copy 3"); + let doc = &s.active().unwrap().doc; + assert_eq!(doc.copy_name("Layer 1"), "Layer 1 copy 4"); + // Names that merely contain "copy" keep it. + assert_eq!(doc.copy_name("Copywriting"), "Copywriting copy"); + assert_eq!(doc.copy_name("A copyedit"), "A copyedit copy"); +} + +fn session(depth: u32) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 100, "height": 80, "depth": depth})).unwrap(); + s +} + +fn doc(s: &Session) -> &Document { + &s.active().unwrap().doc +} + +/// New pixel layer with an opaque red rectangle. +fn rect_layer(s: &mut Session, r: Rect) -> LayerId { + let id = LayerId(s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap()); + s.edit("paint", |doc, _| { + doc.layer_mut(id).unwrap().surface_mut().unwrap().fill_rect(r, &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + id +} + +fn bounds(s: &Session, id: LayerId) -> Rect { + layer_bounds(doc(s).layer(id).unwrap()).unwrap() +} + +fn sel(s: &Session) -> Vec { + selected(s) +} + +fn damage(s: &Session) -> Option { + s.active().unwrap().last_damage +} + +/// A Photoshop action's nudge in points moves whole pixels at the document's resolution: +/// 0.36 pt is 1 px at 200 ppi and 1.5 → 2 px at 300 ppi. +#[test] +fn translate_in_points_follows_the_resolution() { + for (res, moved) in [(200, 1), (300, 2), (72, 0)] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 100, "height": 80, "resolution": res})).unwrap(); + let a = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); + s.execute("layer.translate", json!({"dx": 0.36, "dy": -0.36, "units": "pt"})).unwrap(); + assert_eq!(bounds(&s, a), Rect::new(10 + moved, 10 - moved, 20 + moved, 20 - moved), "{res} ppi"); + } + let mut s = session(8); + rect_layer(&mut s, Rect::new(10, 10, 20, 20)); + for bad in [json!({"dx": 1, "units": "in"}), json!({"dx": "x", "units": "pt"}), json!({"dx": 1e300, "units": "pt"})] { + assert!(s.execute("layer.translate", bad.clone()).is_err(), "{bad}"); + } +} + +/// `remove` deselects a selected layer, leaves an unselected one alone and never empties the +/// selection. +#[test] +fn select_remove_takes_a_layer_out_of_the_selection() { + let mut s = session(8); + let a = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); + let b = rect_layer(&mut s, Rect::new(30, 10, 40, 20)); + let c = rect_layer(&mut s, Rect::new(50, 10, 60, 20)); + s.execute("layer.select", json!({"layer": a.0})).unwrap(); + s.execute("layer.select", json!({"layer": b.0, "mode": "add"})).unwrap(); + s.execute("layer.select", json!({"layer": c.0, "mode": "remove"})).unwrap(); + assert_eq!(sel(&s).len(), 2, "an unselected layer stays out"); + s.execute("layer.select", json!({"layer": b.0, "mode": "remove"})).unwrap(); + assert_eq!(sel(&s), vec![a]); + s.execute("layer.select", json!({"layer": a.0, "mode": "remove"})).unwrap(); + assert_eq!(sel(&s), vec![a], "the last selected layer stays"); +} + +/// A mask with its chain off stays put while the layer moves; a linked one moves along. +#[test] +fn translate_leaves_an_unlinked_mask_in_place() { + for depth in [8, 16] { + let mut s = session(depth); + let a = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); + s.execute("layer.select", json!({"layer": a.0})).unwrap(); + s.execute("layer.layerMask.hideAll", json!({})).unwrap(); + s.edit("mask", |doc, _| { + doc.layer_mut(a).unwrap().mask.as_mut().unwrap().surface.fill_rect(Rect::new(12, 12, 18, 18), &[1.0]); + Ok(()) + }) + .unwrap(); + let mval = |s: &Session, x, y| doc(s).layer(a).unwrap().mask.as_ref().unwrap().surface.sample_channel(x, y, 0); + s.execute("layer.layerMask.linked", json!({"linked": false})).unwrap(); + s.execute("layer.translate", json!({"dx": 30, "dy": 0})).unwrap(); + assert!(mval(&s, 14, 14) > 0.9, "{depth}-bit: unlinked mask stays"); + assert!(mval(&s, 44, 14) < 0.1); + s.execute("edit.undo", json!({})).unwrap(); + s.execute("layer.layerMask.linked", json!({"linked": true})).unwrap(); + s.execute("layer.translate", json!({"dx": 30, "dy": 0})).unwrap(); + assert!(mval(&s, 44, 14) > 0.9, "{depth}-bit: linked mask moves"); + } +} + +/// Aimed at the mask, a move shifts an unlinked mask alone and leaves a linked one with its layer. +#[test] +fn translate_with_the_mask_targeted_moves_an_unlinked_mask_alone() { + for depth in [8, 16] { + let mut s = session(depth); + let a = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); + s.execute("layer.select", json!({"layer": a.0})).unwrap(); + s.execute("layer.layerMask.hideAll", json!({})).unwrap(); + s.edit("mask", |doc, _| { + doc.layer_mut(a).unwrap().mask.as_mut().unwrap().surface.fill_rect(Rect::new(12, 12, 18, 18), &[1.0]); + Ok(()) + }) + .unwrap(); + let mval = |s: &Session, x, y| doc(s).layer(a).unwrap().mask.as_ref().unwrap().surface.sample_channel(x, y, 0); + // Linked: the layer and its mask move together. + s.execute("layer.translate", json!({"dx": 30, "dy": 0, "target": "mask"})).unwrap(); + assert_eq!(bounds(&s, a), Rect::new(40, 10, 50, 20), "{depth}-bit"); + assert!(mval(&s, 44, 14) > 0.9); + s.execute("layer.layerMask.linked", json!({"linked": false})).unwrap(); + s.execute("layer.translate", json!({"dx": -30, "dy": 0, "target": "mask"})).unwrap(); + assert_eq!(bounds(&s, a), Rect::new(40, 10, 50, 20), "{depth}-bit: the layer stays"); + assert!(mval(&s, 14, 14) > 0.9, "the mask moved"); + assert!(mval(&s, 44, 14) < 0.1); + s.execute("edit.undo", json!({})).unwrap(); + assert!(mval(&s, 44, 14) > 0.9, "undo puts the mask back"); + } +} + +#[test] +fn moves_and_layer_props_report_only_their_area() { + let mut s = session(8); + let a = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); + s.execute("layer.select", json!({"layer": a.0})).unwrap(); + s.execute("layer.translate", json!({"dx": 5, "dy": -3})).unwrap(); + assert_eq!(damage(&s), Some(Rect::new(10, 7, 25, 20)), "where the layer was and is"); + s.execute("layer.setProps", json!({"layer": a.0, "visible": false})).unwrap(); + assert_eq!(damage(&s), Some(Rect::new(15, 7, 25, 17))); + s.execute("layer.setProps", json!({"layer": a.0, "opacity": 0.5, "blend": "Multiply"})).unwrap(); + assert_eq!(damage(&s), Some(Rect::new(15, 7, 25, 17))); + // Clipping changes reach the layers around: everything. + s.execute("layer.setProps", json!({"layer": a.0, "clipped": true})).unwrap(); + assert_eq!(damage(&s), None); + // An adjustment layer changes everything beneath it. + let adj = s.execute("layer.newAdjustmentLayer.invert", json!({})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.setProps", json!({"layer": adj, "visible": false})).unwrap(); + assert_eq!(damage(&s), None); + // The Background (opaque everywhere): everything. + let bg = doc(&s).layers[0].id; + s.execute("layer.setProps", json!({"layer": bg.0, "opacity": 0.5})).unwrap(); + let all = doc(&s).bounds(); + assert!(damage(&s).is_none_or(|r| r.contains_rect(&all)), "{:?}", damage(&s)); + // Bad params still fail cleanly. + assert!(s.execute("layer.setProps", json!({"layer": u64::MAX, "visible": true})).is_err()); + assert!(s.execute("layer.translate", json!({"layer": u64::MAX, "dx": 1})).is_err()); +} + +/// #1771: a new empty layer or group changes no pixels, so it (and undoing or redoing it) +/// must not make the canvas recomposite every layer of the document. +#[test] +fn new_empty_layers_and_groups_damage_nothing() { + for depth in [8, 16, 32] { + let mut s = session(depth); + let a = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); + let composite = |s: &Session| photocraft_compose::render(doc(s), doc(s).bounds()); + let shown = composite(&s); + s.execute("layer.new.layer", json!({})).unwrap(); + assert_eq!(damage(&s), Some(Rect::EMPTY), "{depth}-bit new layer"); + assert_eq!(composite(&s), shown, "an empty layer changes no pixels"); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(damage(&s), Some(Rect::EMPTY), "{depth}-bit undo New Layer"); + s.execute("edit.redo", json!({})).unwrap(); + assert_eq!(damage(&s), Some(Rect::EMPTY), "{depth}-bit redo New Layer"); + s.execute("layer.new.group", json!({})).unwrap(); + assert_eq!(damage(&s), Some(Rect::EMPTY), "{depth}-bit new group"); + // Inside a group too. + let child = s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap(); + let g = s.execute("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.select", json!({"layer": child})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + assert_eq!(damage(&s), Some(Rect::EMPTY), "{depth}-bit new layer in a group"); + assert!(doc(&s).layer(LayerId(g)).and_then(Layer::children).is_some_and(|c| c.len() == 2)); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(damage(&s), Some(Rect::EMPTY)); + // Undoing a step that painted still reports that area, not nothing. + s.execute("layer.select", json!({"layer": a.0})).unwrap(); + s.execute("layer.translate", json!({"dx": 5, "dy": 0})).unwrap(); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(damage(&s), Some(Rect::new(10, 10, 25, 20))); + } +} + +#[test] +fn new_layers_that_change_clipping_recomposite_everything() { + let mut s = session(8); + let base = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); + let clipped = rect_layer(&mut s, Rect::new(0, 0, 100, 80)); + s.edit("green", |doc, _| { + doc.layer_mut(clipped).unwrap().surface_mut().unwrap().fill_rect(Rect::new(0, 0, 100, 80), &[0.0, 1.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + s.execute("layer.setProps", json!({"layer": clipped.0, "clipped": true})).unwrap(); + // New Layer between a clipping base and its clipped layer joins their clip group (#2203), + // so it draws nothing; an empty layer there that stayed unclipped would become their base. + s.execute("layer.select", json!({"layer": base.0})).unwrap(); + let shown = photocraft_compose::render(doc(&s), doc(&s).bounds()); + let before = doc(&s).clone(); + s.execute("layer.new.layer", json!({})).unwrap(); + assert_eq!(damage(&s), Some(Rect::EMPTY)); + assert_eq!(photocraft_compose::render(doc(&s), doc(&s).bounds()), shown); + let mut split = before.clone(); + split.insert_above(Some(base), Layer::raster("split", split.pixel_format())); + assert_ne!(photocraft_compose::render(&split, split.bounds()), shown); + assert_eq!(step_damage(&before, &split), None); + assert_eq!(step_damage(&split, &before), None); + s.execute("edit.undo", json!({})).unwrap(); + // A step that adds a layer with pixels (Layer via Copy, paste…) changes where it draws. + let before = doc(&s).clone(); + let mut after = before.clone(); + let mut l = Layer::raster("painted", after.pixel_format()); + l.surface_mut().unwrap().fill_rect(Rect::new(1, 1, 2, 2), &[0.0, 1.0, 0.0, 1.0]); + after.insert_above(None, l); + assert_eq!(step_damage(&before, &after), Some(Rect::new(1, 1, 2, 2))); + assert_eq!(step_damage(&after, &before), Some(Rect::new(1, 1, 2, 2))); + // Unless it becomes the base of clipped layers above it. + let mut based = before.clone(); + let mut l = Layer::raster("base", based.pixel_format()); + l.surface_mut().unwrap().fill_rect(Rect::new(1, 1, 2, 2), &[0.0, 1.0, 0.0, 1.0]); + let under = based.layers.iter().position(|l| l.id == clipped).unwrap(); + based.layers.insert(under, l); + assert_eq!(step_damage(&before, &based), None); + assert_eq!(step_damage(&based, &before), None); + // An adjustment reaches every pixel below it. + let mut adjusted = before.clone(); + adjusted.insert_above(None, Layer::new("inv", LayerContent::Adjustment(photocraft_doc::Adjustment::Invert))); + assert_eq!(step_damage(&before, &adjusted), None); + assert_eq!(step_damage(&adjusted, &before), None); + // Empty layers draw nothing, in any blend mode. + let mut styled = before.clone(); + let mut l = Layer::raster("styled", styled.pixel_format()); + l.blend = photocraft_doc::BlendMode::Multiply; + styled.insert_above(None, l); + assert_eq!(step_damage(&before, &styled), Some(Rect::EMPTY)); + let mut plain = before.clone(); + plain.insert_above(None, Layer::raster("plain", plain.pixel_format())); + assert_eq!(step_damage(&before, &plain), Some(Rect::EMPTY)); + assert_eq!(step_damage(&plain, &before), Some(Rect::EMPTY)); +} + +/// #6535: hiding or showing an adjustment clipped to a layer recomposites only that base's +/// area, also on undo and redo and inside a group, and recompositing just that area gives +/// the same canvas as a full recomposite. +#[test] +fn toggling_a_clipped_adjustment_damages_only_its_base() { + let all = |s: &Session| photocraft_compose::render(doc(s), doc(s).bounds()); + // Recomposite only the reported damage over the previous canvas, as the view does. + let patched = |s: &Session, prev: &photocraft_compose::Buffer| { + let r = damage(s).expect("bounded damage"); + let mut out = prev.clone(); + if r.is_empty() { + return out; + } + let part = photocraft_compose::render(doc(s), r); + let w = out.rect.width() as usize; + for y in r.y0..r.y1 { + for x in r.x0..r.x1 { + let i = (y - out.rect.y0) as usize * w + (x - out.rect.x0) as usize; + let k = (y - r.y0) as usize * r.width() as usize + (x - r.x0) as usize; + out.px[i] = part.px[k]; + } + } + out + }; + for grouped in [false, true] { + let mut s = session(16); + let base_rect = Rect::new(10, 10, 30, 25); + let base = rect_layer(&mut s, base_rect); + let adj = LayerId(s.execute("layer.newAdjustmentLayer.invert", json!({})).unwrap()["layer"].as_u64().unwrap()); + s.execute("layer.createClippingMask", json!({"layer": adj.0})).unwrap(); + assert!(doc(&s).layer(adj).unwrap().clipped); + if grouped { + s.execute("layer.select", json!({"layer": base.0})).unwrap(); + s.execute("layer.select", json!({"layer": adj.0, "mode": "toggle"})).unwrap(); + s.execute("layer.groupLayers", json!({})).unwrap(); + assert!(doc(&s).path_of(adj).unwrap().len() == 2, "the pair sits in a group"); + } + let shown = all(&s); + s.execute("layer.hideLayers", json!({"layer": adj.0})).unwrap(); + assert!(!doc(&s).layer(adj).unwrap().visible); + assert_eq!(damage(&s), Some(base_rect), "grouped: {grouped}"); + let hidden = all(&s); + assert_ne!(hidden, shown); + assert_eq!(patched(&s, &shown), hidden); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(damage(&s), Some(base_rect)); + assert_eq!(patched(&s, &hidden), shown); + s.execute("edit.redo", json!({})).unwrap(); + assert_eq!(damage(&s), Some(base_rect)); + assert_eq!(patched(&s, &shown), hidden); + s.execute("layer.showLayers", json!({"layer": adj.0})).unwrap(); + assert_eq!(damage(&s), Some(base_rect)); + assert_eq!(patched(&s, &hidden), shown); + // layer.setProps reports its own damage. + s.execute("layer.setProps", json!({"layer": adj.0, "visible": false})).unwrap(); + assert_eq!(damage(&s), Some(base_rect)); + assert_eq!(patched(&s, &shown), hidden); + // Unclipped, the adjustment still reaches the whole canvas. + s.execute("layer.setProps", json!({"layer": adj.0, "visible": true})).unwrap(); + s.execute("layer.releaseClippingMask", json!({"layer": adj.0})).unwrap(); + s.execute("layer.hideLayers", json!({"layer": adj.0})).unwrap(); + assert_eq!(damage(&s), None); + } +} + +/// #6535: hiding a clipped adjustment inside a pass-through group that is itself a clip base +/// can switch the group between isolated and pass-through rendering, so the step damages the +/// whole group, on undo, redo and when the adjustment is deleted too. +#[test] +fn clipped_adjustment_in_pass_through_clip_base_damages_its_group() { + use photocraft_doc::{Adjustment, BlendMode}; + let solid = |name: &str, r: Rect, blend: BlendMode| { + let mut l = Layer::raster(name, PixelFormat::RGBA8); + l.surface_mut().unwrap().fill_rect(r, &[0.5, 0.5, 0.5, 1.0]); + l.blend = blend; + l + }; + let mut before = Document::with_background( + "t", + photocraft_geom::Size::new(10, 8), + photocraft_doc::ColorMode::Rgb, + photocraft_doc::SampleType::U8, + photocraft_color::Color::WHITE, + ); + before.layers.push(solid("bg", before.bounds(), BlendMode::Normal)); + let mut a = Layer::new("A", LayerContent::Adjustment(Adjustment::Invert)); + a.clipped = true; + let mut g = Layer::group("G", vec![solid("P", Rect::new(2, 1, 4, 3), BlendMode::Normal), a, solid("Q", Rect::new(6, 4, 8, 6), BlendMode::Multiply)]); + g.blend = BlendMode::PassThrough; + before.layers.push(g); + let mut x = solid("X", Rect::new(2, 1, 3, 2), BlendMode::Normal); + x.clipped = true; + before.layers.push(x); + let mut after = before.clone(); + let LayerContent::Group(g) = &mut after.layers[2].content else { panic!("group") }; + g.children[1].visible = false; + let group = Some(Rect::new(2, 1, 8, 6)); + assert_eq!(step_damage(&before, &after), group); + assert_eq!(step_damage(&after, &before), group); + let mut deleted = before.clone(); + let LayerContent::Group(g) = &mut deleted.layers[2].content else { panic!("group") }; + g.children.remove(1); + assert_eq!(step_damage(&before, &deleted), group); + let LayerContent::Group(g) = &before.layers[2].content else { panic!("group") }; + let ids = [g.children[1].id]; + assert_eq!(layers_damage(&before, &after, &ids), group); + // Without the layer clipped to the group it stays pass-through: just A's base. + before.layers.truncate(3); + after.layers.truncate(3); + assert_eq!(step_damage(&before, &after), Some(Rect::new(2, 1, 4, 3))); +} + +/// #2883 (P8/P9): a duplicate shares the source's tiles (no pixel copy) and recomposites only +/// where it draws; undo brings back exactly the old pixels. A copy that becomes the clipping +/// base of the layers above still recomposites everything. +#[test] +fn duplicate_shares_tiles_and_damages_only_the_copy() { + let render = |s: &Session| photocraft_compose::render(doc(s), doc(s).bounds()); + let tiles = + |s: &Session, id: LayerId| doc(s).layer(id).unwrap().surface().unwrap().tiles().map(|(c, t)| (*c, std::sync::Arc::as_ptr(t))).collect::>(); + for depth in [8, 16, 32] { + let mut s = session(depth); + let a = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); + s.execute("layer.setProps", json!({"layer": a.0, "opacity": 0.5})).unwrap(); + let shown = render(&s); + let copy = LayerId(s.execute("layer.duplicate", json!({"layer": a.0})).unwrap()["layer"].as_u64().unwrap()); + assert_eq!(damage(&s), Some(Rect::new(10, 10, 20, 20)), "{depth}-bit: only where the copy draws"); + assert!(!tiles(&s, a).is_empty()); + assert_eq!(tiles(&s, copy), tiles(&s, a), "{depth}-bit: the copy shares the source's tiles"); + let now = render(&s); + assert_ne!(now, shown, "the half-transparent copy darkens its area"); + let w = shown.rect.width() as usize; + for (i, (p, q)) in shown.px.iter().zip(&now.px).enumerate() { + if !Rect::new(10, 10, 20, 20).contains((i % w) as i32, (i / w) as i32) { + assert_eq!(p, q, "{depth}-bit: pixel {i} outside the damage changed"); + } + } + s.execute("edit.undo", json!({})).unwrap(); + assert!(doc(&s).layer(copy).is_none()); + assert_eq!(render(&s), shown); + // A clipping base's copy goes between it and its clipped layer and becomes their base. + let clipped = rect_layer(&mut s, Rect::new(0, 0, 50, 50)); + s.execute("layer.setProps", json!({"layer": clipped.0, "clipped": true})).unwrap(); + s.execute("layer.duplicate", json!({"layer": a.0})).unwrap(); + assert_eq!(damage(&s), None, "{depth}-bit: a new clipping base"); + } +} + +/// The composite of `after` equals `before`'s outside `damage`. +fn unchanged_outside(before: &Document, after: &Document, damage: Rect) -> bool { + let (x, y) = (photocraft_compose::render(before, before.bounds()), photocraft_compose::render(after, after.bounds())); + let w = before.bounds().width() as i32; + x.px.iter().zip(&y.px).enumerate().all(|(i, (p, q))| p == q || damage.contains(i as i32 % w, i as i32 / w)) +} + +/// Duplicate (one layer or several), paste and delete, and their undo and redo, recomposite +/// only where the layers draw; undoing a duplicate used to recomposite the whole document. +#[test] +fn duplicate_paste_and_delete_report_where_the_layer_draws() { + let mut s = session(8); + let a = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); + let full = doc(&s).bounds(); + let step = |s: &mut Session, id: &str, p: serde_json::Value| { + let before = doc(s).clone(); + s.execute(id, p).unwrap(); + let d = damage(s).unwrap_or_else(|| panic!("{id}: unbounded damage")); + assert!(d.width() < full.width(), "{id}: {d:?}"); + assert!(unchanged_outside(&before, doc(s), d), "{id}: pixels changed outside {d:?}"); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(damage(s), Some(d), "undo {id}"); + s.execute("edit.redo", json!({})).unwrap(); + assert_eq!(damage(s), Some(d), "redo {id}"); + }; + step(&mut s, "layer.duplicate", json!({"layer": a.0})); + s.execute("layer.select", json!({"layer": a.0})).unwrap(); + s.execute("select.rect", json!({"x": 12, "y": 12, "width": 4, "height": 4})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + step(&mut s, "edit.paste", json!({})); + // Duplicating several selected layers reports where the copies draw, too. + let b = rect_layer(&mut s, Rect::new(30, 30, 40, 40)); + s.execute("layer.select", json!({"layer": a.0})).unwrap(); + s.execute("layer.select", json!({"layer": b.0, "mode": "add"})).unwrap(); + step(&mut s, "layer.duplicate", json!({})); + assert_eq!(damage(&s), Some(Rect::new(10, 10, 40, 40)), "both copies, nothing else"); + step(&mut s, "layer.delete", json!({"layer": a.0})); +} + +#[test] +fn the_move_preview_matches_the_move() { + let mut s = session(8); + let a = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); + let before = s.active().unwrap().doc.clone(); + let ids = move_targets(&before, &[a]); + let shown = moved(&before, &ids, 7, 4).unwrap(); + s.execute("layer.translate", json!({"layer": a.0, "dx": 7, "dy": 4})).unwrap(); + assert_eq!(layer_bounds(shown.layer(a).unwrap()), Some(bounds(&s, a))); + // Locked layers don't move in the preview either. + let mut locked = (*before).clone(); + locked.layer_mut(a).unwrap().locks.position = true; + assert!(moved(&locked, &ids, 1, 1).is_err()); + assert!(moved(&before, &[LayerId(u64::MAX)], 1, 1).is_err()); +} + +#[test] +fn move_stroked_shape_across_canvas_edge_matches_fresh_render() { + let mut s = session(8); + let id = LayerId( + s.execute("shape.create", json!({"kind": "rect", "rect": [10, 10, 30, 30], "stroke": {"width": 4, "color": "#ff0000"}})).unwrap()["layer"] + .as_u64() + .unwrap(), + ); + let before = doc(&s).clone(); + let ids = move_targets(&before, &[id]); + + // Drag the stroked shape across the left canvas boundary: + let moved_doc = moved(&before, &ids, -25, 0).unwrap(); + let moved_layer = moved_doc.layer(id).unwrap(); + let LayerContent::Shape(sh) = &moved_layer.content else { panic!("not a shape") }; + let cached = sh.cache.as_ref().expect("cached render"); + + let mut fresh_sh = sh.clone(); + crate::vector_cmds::refresh_shape(&moved_doc, &mut fresh_sh); + let fresh = fresh_sh.cache.as_ref().expect("fresh render"); + + assert_eq!(cached, fresh, "dragged shape cached render must match fresh render across canvas edge"); + + // Drag it back inside the canvas: + let moved_back = moved(&moved_doc, &ids, 30, 0).unwrap(); + let back_layer = moved_back.layer(id).unwrap(); + let LayerContent::Shape(back_sh) = &back_layer.content else { panic!("not a shape") }; + let back_cached = back_sh.cache.as_ref().expect("cached render"); + + let mut fresh_back = back_sh.clone(); + crate::vector_cmds::refresh_shape(&moved_back, &mut fresh_back); + let fresh_back_render = fresh_back.cache.as_ref().expect("fresh render"); + + assert_eq!(back_cached, fresh_back_render, "cached render must match fresh render when dragged back"); +} + +fn select_all(s: &mut Session, ids: &[LayerId]) { + s.execute("layer.select", json!({"layer": ids[0].0})).unwrap(); + for id in &ids[1..] { + s.execute("layer.select", json!({"layer": id.0, "mode": "toggle"})).unwrap(); + } +} + +#[test] +fn toggle_and_range_selection() { + let mut s = session(8); + let a = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + let b = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + let c = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + let d = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + assert_eq!(sel(&s), vec![d]); + s.execute("layer.select", json!({"layer": b.0, "mode": "toggle"})).unwrap(); + assert_eq!(sel(&s), vec![b, d]); + assert_eq!(s.active().unwrap().active_layer, Some(b)); + // Toggling the active layer off hands "active" to a remaining member. + s.execute("layer.select", json!({"layer": b.0, "mode": "toggle"})).unwrap(); + assert_eq!(sel(&s), vec![d]); + assert_eq!(s.active().unwrap().active_layer, Some(d)); + // The last selected layer can't be toggled off. + s.execute("layer.select", json!({"layer": d.0, "mode": "toggle"})).unwrap(); + assert_eq!(sel(&s), vec![d]); + // Range from the anchor (a) to c. + s.execute("layer.select", json!({"layer": a.0})).unwrap(); + s.execute("layer.select", json!({"layer": c.0, "mode": "range"})).unwrap(); + assert_eq!(sel(&s), vec![a, b, c]); + // A second ⇧-click re-ranges from the same anchor. + s.execute("layer.select", json!({"layer": b.0, "mode": "range"})).unwrap(); + assert_eq!(sel(&s), vec![a, b]); + assert!(s.execute("layer.select", json!({"layer": b.0, "mode": "bogus"})).is_err()); + // Selection changes are not edits. + let history = s.active().unwrap().history.entries().len(); + s.execute("select.allLayers", json!({})).unwrap(); + assert_eq!(sel(&s), vec![a, b, c, d], "Select All Layers skips the locked Background"); + s.execute("select.deselectLayers", json!({})).unwrap(); + assert!(sel(&s).is_empty()); + assert_eq!(s.active().unwrap().history.entries().len(), history); + // Nothing selected: a no-op, not an error (#2457). + s.execute("select.deselectLayers", json!({})).unwrap(); + assert_eq!(s.active().unwrap().history.entries().len(), history); + // An explicit layer needs no active layer. + s.execute("layer.hideLayers", json!({"layer": a.0})).unwrap(); + assert!(!s.active().unwrap().doc.layer(a).unwrap().visible); + s.execute("layer.renameLayer", json!({"layer": a.0, "name": "x"})).unwrap(); + assert_eq!(s.active().unwrap().doc.layer(a).unwrap().name, "x"); + s.execute("layer.showLayers", json!({"layer": a.0})).unwrap(); + assert!(s.active().unwrap().doc.layer(a).unwrap().visible); + assert!(s.execute("layer.hideLayers", json!({"layer": u64::MAX})).is_err()); + assert!(s.execute("layer.hideLayers", json!({})).is_err()); + assert!(!s.is_enabled("layer.align.topEdges")); +} + +#[test] +fn find_layers_by_name() { + let mut s = session(8); + let a = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + let b = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + s.execute("layer.renameLayer", json!({"layer": a.0, "name": "Sky photo"})).unwrap(); + s.execute("layer.renameLayer", json!({"layer": b.0, "name": "Photo of sea"})).unwrap(); + assert_eq!(doc(&s).layer(a).unwrap().name, "Sky photo"); + let r = s.execute("select.findLayers", json!({"name": "PHOTO"})).unwrap(); + assert_eq!(r["selected"], json!([a.0, b.0])); + assert!(s.execute("select.findLayers", json!({"name": "nothing"})).is_err()); + assert!(s.execute("layer.renameLayer", json!({})).is_err()); +} + +#[test] +fn rename_layer_keeps_surrounding_spaces() { + let mut s = session(8); + let a = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + s.execute("layer.renameLayer", json!({"layer": a.0, "name": " black skin bw "})).unwrap(); + assert_eq!(doc(&s).layer(a).unwrap().name, " black skin bw "); + assert!(s.execute("layer.renameLayer", json!({"layer": a.0, "name": " "})).is_err()); + assert_eq!(doc(&s).layer(a).unwrap().name, " black skin bw "); +} + +#[test] +fn align_each_edge() { + for depth in [8, 16, 32] { + let cases: [(&str, [Rect; 2]); 6] = [ + ("topEdges", [Rect::new(10, 5, 20, 15), Rect::new(40, 5, 50, 25)]), + ("bottomEdges", [Rect::new(10, 20, 20, 30), Rect::new(40, 10, 50, 30)]), + // Union 5..30: centre 17.5; half-pixel offsets round towards the top. + ("verticalCenters", [Rect::new(10, 12, 20, 22), Rect::new(40, 7, 50, 27)]), + ("leftEdges", [Rect::new(10, 5, 20, 15), Rect::new(10, 10, 50, 30)]), + ("rightEdges", [Rect::new(40, 5, 50, 15), Rect::new(10, 10, 50, 30)]), + ("horizontalCenters", [Rect::new(25, 5, 35, 15), Rect::new(10, 10, 50, 30)]), + ]; + for (kind, want) in cases { + let mut s = session(depth); + let a = rect_layer(&mut s, Rect::new(10, 5, 20, 15)); + let b = rect_layer(&mut s, Rect::new(40, 10, 50, 30)); + // For the horizontal cases make b wide so it defines the target bounds. + if !matches!(kind, "topEdges" | "bottomEdges" | "verticalCenters") { + s.edit("wide", |doc, _| { + doc.layer_mut(b).unwrap().surface_mut().unwrap().fill_rect(Rect::new(10, 10, 50, 30), &[0.0, 1.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + } + select_all(&mut s, &[a, b]); + s.execute(&format!("layer.align.{kind}"), json!({})).unwrap(); + assert_eq!([bounds(&s, a), bounds(&s, b)], want, "{kind} at {depth}-bit"); + // Pixels moved, not just bounds. + let r = want[0]; + assert_eq!(doc(&s).layer(a).unwrap().surface().unwrap().pixel(r.x0, r.y0)[..4], [1.0, 0.0, 0.0, 1.0]); + // One undo restores the original positions. + s.undo(); + assert_eq!(bounds(&s, a), Rect::new(10, 5, 20, 15)); + } + } +} + +#[test] +fn align_single_layer_to_selection() { + for depth in [8, 16, 32] { + let mut s = session(depth); + let a = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); + assert!(s.is_enabled("layer.align.leftEdges"), "one layer aligns to the canvas"); + s.execute("select.rect", json!({"x": 50, "y": 40, "width": 30, "height": 30})).unwrap(); + assert!(s.is_enabled("layer.align.leftEdges")); + s.execute("layer.align.rightEdges", json!({})).unwrap(); + assert_eq!(bounds(&s, a), Rect::new(70, 10, 80, 20)); + s.execute("layer.align.verticalCenters", json!({})).unwrap(); + assert_eq!(bounds(&s, a), Rect::new(70, 50, 80, 60)); + s.execute("layer.align.topEdges", json!({"to": "canvas"})).unwrap(); + assert_eq!(bounds(&s, a), Rect::new(70, 0, 80, 10)); + } +} + +#[test] +fn align_single_layer_to_canvas() { + // Photoshop: a single selected layer with no active selection aligns to the canvas. + let mut s = session(8); // 100 x 80 + let a = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); // 10 x 10 + assert!(s.is_enabled("layer.align.horizontalCenters")); + s.execute("layer.align.horizontalCenters", json!({})).unwrap(); + assert_eq!(bounds(&s, a), Rect::new(45, 10, 55, 20), "centred on the 100px-wide canvas"); + s.execute("layer.align.verticalCenters", json!({})).unwrap(); + assert_eq!(bounds(&s, a), Rect::new(45, 35, 55, 45), "centred on the 80px-tall canvas"); + s.execute("layer.align.leftEdges", json!({})).unwrap(); + assert_eq!(bounds(&s, a), Rect::new(0, 35, 10, 45), "left edge to the canvas"); +} + +#[test] +fn distribute_uneven_layers() { + for depth in [8, 16, 32] { + let mut s = session(depth); + let a = rect_layer(&mut s, Rect::new(0, 0, 10, 10)); + let b = rect_layer(&mut s, Rect::new(12, 0, 32, 10)); // 20 wide + let c = rect_layer(&mut s, Rect::new(70, 0, 100, 10)); // 30 wide + select_all(&mut s, &[a, b, c]); + // Undo targets the layers its state had when it was created (#495): reselect. + assert!(s.is_enabled("layer.distribute.leftEdges")); + s.execute("layer.distribute.leftEdges", json!({})).unwrap(); + assert_eq!(bounds(&s, b), Rect::new(35, 0, 55, 10), "left edges 0, 35, 70"); + s.undo(); + select_all(&mut s, &[a, b, c]); + s.execute("layer.distribute.horizontalCenters", json!({})).unwrap(); + // centres 5 and 85 → middle centre 45 + assert_eq!(bounds(&s, b), Rect::new(35, 0, 55, 10)); + s.undo(); + select_all(&mut s, &[a, b, c]); + s.execute("layer.distribute.rightEdges", json!({})).unwrap(); + // right edges 10 and 100 → 55 + assert_eq!(bounds(&s, b), Rect::new(35, 0, 55, 10)); + s.undo(); + select_all(&mut s, &[a, b, c]); + s.execute("layer.distribute.horizontally", json!({})).unwrap(); + // span 100, widths 60 → gaps of 20: b at 30..50 + assert_eq!(bounds(&s, b), Rect::new(30, 0, 50, 10)); + assert_eq!(bounds(&s, a), Rect::new(0, 0, 10, 10)); + assert_eq!(bounds(&s, c), Rect::new(70, 0, 100, 10)); + s.undo(); + assert_eq!(bounds(&s, b), Rect::new(12, 0, 32, 10)); + } + // Vertical: tall layers with uneven heights. + let mut s = session(8); + let a = rect_layer(&mut s, Rect::new(0, 0, 10, 10)); + let b = rect_layer(&mut s, Rect::new(0, 50, 10, 54)); + let c = rect_layer(&mut s, Rect::new(0, 60, 10, 80)); + select_all(&mut s, &[a, b, c]); + s.execute("layer.distribute.vertically", json!({})).unwrap(); + // span 80, heights 34 → gaps 23: b at 33..37 + assert_eq!(bounds(&s, b), Rect::new(0, 33, 10, 37)); + s.undo(); + select_all(&mut s, &[a, b, c]); + s.execute("layer.distribute.topEdges", json!({})).unwrap(); + assert_eq!(bounds(&s, b), Rect::new(0, 30, 10, 34)); + s.undo(); + select_all(&mut s, &[a, b, c]); + s.execute("layer.distribute.bottomEdges", json!({})).unwrap(); + assert_eq!(bounds(&s, b), Rect::new(0, 41, 10, 45)); + s.undo(); + select_all(&mut s, &[a, b, c]); + s.execute("layer.distribute.verticalCenters", json!({})).unwrap(); + // centres 5 and 70 → 37.5, b is 4 tall → top 35.5 → rounds to 36 (35 for ties down) + let y0 = bounds(&s, b).y0; + assert!((35..=36).contains(&y0), "{y0}"); + // Two layers can't be distributed. + select_all(&mut s, &[a, b]); + assert!(!s.is_enabled("layer.distribute.leftEdges")); +} + +#[test] +fn merge_keeps_pixels_outside_the_canvas() { + // #5067: the merged layer was cropped to the 100x80 canvas. + let mut s = session(8); + let a = rect_layer(&mut s, Rect::new(-30, -20, 10, 10)); + let b = rect_layer(&mut s, Rect::new(90, 70, 140, 120)); + select_all(&mut s, &[a, b]); + let m = LayerId(s.execute("layer.mergeLayers", json!({})).unwrap()["layer"].as_u64().unwrap()); + let ml = doc(&s).layer(m).unwrap(); + assert_eq!(layer_bounds(ml).unwrap(), Rect::new(-30, -20, 140, 120)); + assert_eq!(ml.surface().unwrap().pixel(-10, -5)[3], 1.0); + assert_eq!(ml.surface().unwrap().pixel(130, 110)[3], 1.0); +} + +#[test] +fn merge_down_and_merge_group_keep_pixels_outside_the_canvas() { + let mut s = session(8); + let a = rect_layer(&mut s, Rect::new(-30, -20, 10, 10)); + let b = rect_layer(&mut s, Rect::new(90, 70, 140, 120)); + s.execute("layer.mergeDown", json!({"layer": b.0})).unwrap(); + assert_eq!(layer_bounds(doc(&s).layer(a).unwrap()).unwrap(), Rect::new(-30, -20, 140, 120)); + + let mut s = session(8); + let a = rect_layer(&mut s, Rect::new(-30, -20, 10, 10)); + let b = rect_layer(&mut s, Rect::new(90, 70, 140, 120)); + select_all(&mut s, &[a, b]); + let g = LayerId(s.execute("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap()); + s.execute("layer.mergeGroup", json!({"layer": g.0})).unwrap(); + assert_eq!(layer_bounds(doc(&s).layer(g).unwrap()).unwrap(), Rect::new(-30, -20, 140, 120)); +} + +#[test] +fn merge_selected_into_top_most() { + for depth in [8, 16, 32] { + let mut s = session(depth); + let a = rect_layer(&mut s, Rect::new(0, 0, 10, 10)); + let b = rect_layer(&mut s, Rect::new(20, 0, 30, 10)); + let c = rect_layer(&mut s, Rect::new(40, 0, 50, 10)); + s.execute("layer.renameLayer", json!({"layer": c.0, "name": "Top"})).unwrap(); + select_all(&mut s, &[a, c]); + let before = doc(&s).layer_count(); + let m = LayerId(s.execute("layer.mergeLayers", json!({})).unwrap()["layer"].as_u64().unwrap()); + let d = doc(&s); + assert_eq!(d.layer_count(), before - 1); + let ml = d.layer(m).unwrap(); + assert_eq!(ml.name, "Top"); + assert_eq!(layer_bounds(ml).unwrap(), Rect::new(0, 0, 50, 10)); + assert_eq!(ml.surface().unwrap().pixel(5, 5)[..4], [1.0, 0.0, 0.0, 1.0]); + assert_eq!(ml.surface().unwrap().pixel(25, 5)[3], 0.0, "b was not merged"); + assert!(d.layer(b).is_some() && d.layer(a).is_none()); + assert_eq!(d.layers.last().unwrap().id, m, "merged layer sits where the top-most was"); + assert_eq!(sel(&s), vec![m]); + s.undo(); + assert_eq!(doc(&s).layer_count(), before); + assert_eq!(sel(&s), vec![a, c], "undo selects the layers that were merged"); + // One layer selected: Merge Down. + s.execute("layer.select", json!({"layer": c.0})).unwrap(); + s.execute("layer.mergeLayers", json!({})).unwrap(); + assert_eq!(doc(&s).layer_count(), before - 1); + } +} + +#[test] +fn merging_group_children_preserves_their_composite() { + for depth in [8, 16, 32] { + let mut s = session(depth); + let lower = rect_layer(&mut s, Rect::new(10, 12, 40, 42)); + let upper = rect_layer(&mut s, Rect::new(25, 20, 55, 50)); + select_all(&mut s, &[lower, upper]); + let group = LayerId(s.execute("layer.groupLayers", json!({"name": "Merge test group"})).unwrap()["layer"].as_u64().unwrap()); + let doc_before = doc(&s); + let expected = photocraft_compose::render(doc_before, doc_before.bounds()); + let children = doc_before.layer(group).unwrap().children().unwrap().iter().map(|layer| layer.id).collect::>(); + + select_all(&mut s, &children); + s.execute("layer.mergeLayers", json!({})).unwrap(); + let doc_after = doc(&s); + let actual = photocraft_compose::render(doc_after, doc_after.bounds()); + assert_eq!(actual, expected, "depth {depth}: group merge changed rendered pixels"); + assert_eq!(doc_after.layer(group).unwrap().children().unwrap().len(), 1); + } +} + +#[test] +fn merging_keeps_layer_effects_outside_the_pixels() { + // A drop shadow reaches past the layer's pixels; the merge must render that far. + for depth in [8, 16, 32] { + let mut s = session(depth); + let lower = rect_layer(&mut s, Rect::new(10, 10, 30, 30)); + let upper = rect_layer(&mut s, Rect::new(40, 20, 60, 40)); + s.execute("layer.layerStyle.dropShadow", json!({"layer": upper.0, "blend": "normal", "distance": 12, "size": 4})).unwrap(); + let before = photocraft_compose::render(doc(&s), doc(&s).bounds()); + select_all(&mut s, &[lower, upper]); + s.execute("layer.mergeLayers", json!({})).unwrap(); + let after = photocraft_compose::render(doc(&s), doc(&s).bounds()); + let worst = before.px.iter().zip(&after.px).map(|(a, b)| a.iter().zip(b).map(|(x, y)| (x - y).abs()).fold(0.0f32, f32::max)).fold(0.0f32, f32::max); + assert!(worst <= 1.5 / 255.0, "depth {depth}: merge layers dropped the shadow (off by {worst})"); + } +} + +#[test] +fn merging_a_group_down_preserves_the_composite() { + for depth in [8, 16, 32] { + let mut s = session(depth); + let lower = rect_layer(&mut s, Rect::new(10, 12, 50, 52)); + let child_a = rect_layer(&mut s, Rect::new(24, 20, 64, 60)); + let child_b = rect_layer(&mut s, Rect::new(35, 28, 75, 68)); + select_all(&mut s, &[child_a, child_b]); + let group = LayerId(s.execute("layer.groupLayers", json!({"name": "Merge down group"})).unwrap()["layer"].as_u64().unwrap()); + let doc_before = doc(&s); + let expected = photocraft_compose::render(doc_before, doc_before.bounds()); + + s.execute("layer.mergeDown", json!({"layer": group.0})).unwrap(); + let doc_after = doc(&s); + let actual = photocraft_compose::render(doc_after, doc_after.bounds()); + assert_eq!(actual, expected, "depth {depth}: group merge down changed rendered pixels"); + assert!(doc_after.layer(lower).is_some()); + assert!(doc_after.layer(group).is_none()); + } +} + +#[test] +fn a_locked_group_locks_its_contents() { + let mut s = session(8); + let a = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + let g = s.execute("layer.new.groupFromLayers", json!({})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.setProps", json!({"layer": g, "locked": true})).unwrap(); + s.execute("layer.select", json!({"layer": a.0})).unwrap(); + for (cmd, p) in [ + ("layer.translate", json!({"dx": 1})), + ("paint.stroke", json!({"points": [[2, 2], [4, 4]]})), + ("edit.fill", json!({"color": "#00ff00"})), + ("edit.transform.flipHorizontal", json!({})), + ] { + assert!(s.execute(cmd, p).is_err(), "{cmd} edited a layer in a locked group"); + } + // Unlocking the group releases its contents. + s.execute("layer.setProps", json!({"layer": g, "locked": false})).unwrap(); + s.execute("layer.translate", json!({"dx": 1})).unwrap(); + assert_eq!(bounds(&s, a), Rect::new(1, 0, 6, 5)); +} + +#[test] +fn a_locked_group_keeps_a_grouped_background_locked() { + let mut s = session(8); + let bg = doc(&s).layers[0].id; + s.execute("layer.select", json!({"layer": bg.0})).unwrap(); + let g = s.execute("layer.new.groupFromLayers", json!({})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.setProps", json!({"layer": g, "locked": true})).unwrap(); + s.execute("layer.select", json!({"layer": bg.0})).unwrap(); + for (cmd, p) in [ + ("edit.transform.flipHorizontal", json!({})), + ("edit.transform.warp", json!({"style": "flag", "bend": 50})), + ("edit.puppetWarp", json!({"pins": [{"src": [30, 25], "dst": [36, 29]}]})), + ] { + let e = s.execute(cmd, p).unwrap_err().to_string(); + assert!(e.contains("locked"), "{cmd}: {e}"); + assert_eq!(doc(&s).layer(bg).unwrap().name, "Background", "{cmd}"); + } +} + +#[test] +fn group_from_layers_preserves_order() { + let mut s = session(8); + let a = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + let b = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + let c = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + let d = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + select_all(&mut s, &[c, a]); + let g = LayerId(s.execute("layer.new.groupFromLayers", json!({"name": "Pair"})).unwrap()["layer"].as_u64().unwrap()); + let docu = doc(&s); + let gl = docu.layer(g).unwrap(); + assert_eq!(gl.name, "Pair"); + assert!(matches!(&gl.content, LayerContent::Group(gr) if !gr.expanded), "created collapsed"); + assert_eq!(gl.children().unwrap().iter().map(|l| l.id).collect::>(), vec![a, c]); + // Root (bottom-to-top): Background, b, Pair (where c was), d. + assert_eq!(docu.layers.iter().map(|l| l.id).skip(1).collect::>(), vec![b, g, d]); + assert_eq!(sel(&s), vec![g]); + s.undo(); + assert_eq!(doc(&s).layers.len(), 5); + // ⌘G with several selected groups them too. + select_all(&mut s, &[b, d]); + let g = LayerId(s.execute("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap()); + assert_eq!(doc(&s).layers.len(), 4); + // Both create the group collapsed, as Photoshop does (#5571). + assert!(matches!(&doc(&s).layer(g).unwrap().content, LayerContent::Group(gr) if !gr.expanded)); +} + +#[test] +fn grouping_is_capped_at_the_document_nesting_limit() { + let mut s = session(8); + let a = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + select_all(&mut s, &[a]); + for _ in 0..photocraft_doc::MAX_GROUP_DEPTH { + s.execute("layer.groupLayers", json!({})).unwrap(); + } + assert_eq!(doc(&s).max_group_depth(), photocraft_doc::MAX_GROUP_DEPTH); + // One more wrapping group would pass the cap: rejected, document untouched. + let err = s.execute("layer.groupLayers", json!({})).unwrap_err(); + assert!(err.to_string().contains("deeper than 100"), "{err}"); + assert_eq!(doc(&s).max_group_depth(), photocraft_doc::MAX_GROUP_DEPTH); + // The rejected call recorded no history step: undo still lands one grouping earlier. + s.undo(); + assert_eq!(doc(&s).max_group_depth(), photocraft_doc::MAX_GROUP_DEPTH - 1); +} + +#[test] +fn select_linked_layers_excludes_an_unlinked_active_layer() { + for depth in [8, 16, 32] { + let mut s = session(depth); + let a = rect_layer(&mut s, Rect::new(0, 0, 10, 10)); + let b = rect_layer(&mut s, Rect::new(20, 20, 30, 30)); + let other = rect_layer(&mut s, Rect::new(50, 50, 60, 60)); + select_all(&mut s, &[a, b]); + s.execute("layer.linkLayers", json!({})).unwrap(); + s.execute("layer.select", json!({"layer": a.0})).unwrap(); + s.execute("layer.select", json!({"layer": other.0, "mode": "toggle"})).unwrap(); + assert_eq!(sel(&s), vec![a, other]); + assert_eq!(s.active().unwrap().active_layer, Some(other)); + let past = s.active().unwrap().history.past_len(); + let dirty = s.active().unwrap().is_dirty(); + + let result = s.execute("layer.selectLinkedLayers", json!({})).unwrap(); + assert_eq!(sel(&s), vec![a, b]); + assert_eq!(result["selected"], sel(&s).len()); + assert_eq!(s.active().unwrap().active_layer, Some(b)); + assert_eq!(s.active().unwrap().layer_anchor, Some(b)); + assert_eq!(s.active().unwrap().history.past_len(), past); + assert_eq!(s.active().unwrap().is_dirty(), dirty); + + // A following multi-layer delete must leave the unrelated layer intact. + s.execute("layer.delete", json!({})).unwrap(); + assert!(doc(&s).layer(a).is_none() && doc(&s).layer(b).is_none()); + assert!(doc(&s).layer(other).is_some()); + s.undo(); + assert!(doc(&s).layer(a).is_some() && doc(&s).layer(b).is_some()); + assert!(doc(&s).layer(other).is_some()); + } +} + +#[test] +fn select_linked_layers_preserves_a_linked_active_layer() { + for depth in [8, 16, 32] { + let mut s = session(depth); + let a = rect_layer(&mut s, Rect::new(0, 0, 10, 10)); + let b = rect_layer(&mut s, Rect::new(20, 20, 30, 30)); + select_all(&mut s, &[a, b]); + s.execute("layer.linkLayers", json!({})).unwrap(); + for active in [a, b] { + s.execute("layer.select", json!({"layer": active.0})).unwrap(); + let st = s.active_mut().unwrap(); + st.saved_revision = st.revision; + let past = st.history.past_len(); + for _ in 0..2 { + let result = s.execute("layer.selectLinkedLayers", json!({})).unwrap(); + assert_eq!(sel(&s), vec![a, b]); + assert_eq!(result["selected"], sel(&s).len()); + assert_eq!(s.active().unwrap().active_layer, Some(active)); + assert_eq!(s.active().unwrap().layer_anchor, Some(active)); + assert_eq!(s.active().unwrap().history.past_len(), past); + assert!(!s.active().unwrap().is_dirty()); + } + } + } +} + +#[test] +fn select_linked_layers_requires_a_linked_selection() { + let mut s = Session::new(); + assert!(!s.is_enabled("layer.selectLinkedLayers")); + assert!(s.execute("layer.selectLinkedLayers", json!({})).is_err()); + let mut s = session(8); + let before = sel(&s); + assert!(!s.is_enabled("layer.selectLinkedLayers")); + assert!(s.execute("layer.selectLinkedLayers", json!({})).is_err()); + assert_eq!(sel(&s), before); +} + +#[test] +fn translate_rejects_offsets_that_would_wrap() { + let mut s = session(8); + let a = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + select_all(&mut s, &[a]); + // 2^32 + 50 wrapped to `dx = 50` and 3e9 to a negative offset through `as i32`. + for dx in [4_294_967_346_i64, 3_000_000_000_i64] { + let err = s.execute("layer.translate", json!({"dx": dx, "dy": 0})).unwrap_err(); + assert!(err.to_string().contains("32-bit"), "{err}"); + } + assert_eq!(bounds(&s, a), Rect::new(0, 0, 5, 5), "the layer never moved"); + // Large in-range offsets still work. + s.execute("layer.translate", json!({"dx": -200_000, "dy": 200_000})).unwrap(); +} + +#[test] +fn link_layers_never_reuses_a_group_when_the_largest_id_is_u64_max() { + let mut s = session(8); + let a = rect_layer(&mut s, Rect::new(0, 0, 10, 10)); + let b = rect_layer(&mut s, Rect::new(20, 20, 30, 30)); + let c = rect_layer(&mut s, Rect::new(50, 50, 60, 60)); + let d = rect_layer(&mut s, Rect::new(70, 70, 80, 80)); + // A stored document can carry any id; `max + 1` once overflowed here. + let st = s.active_mut().unwrap(); + for id in [c, d] { + std::sync::Arc::make_mut(&mut st.doc).layer_mut(id).unwrap().link_group = Some(u64::MAX); + } + select_all(&mut s, &[a, b]); + assert_eq!(s.execute("layer.linkLayers", json!({})).unwrap()["linked"], true); + let g = doc(&s).layer(a).unwrap().link_group; + assert_eq!(g, Some(1)); + assert_eq!(doc(&s).layer(b).unwrap().link_group, g); + for id in [c, d] { + assert_eq!(doc(&s).layer(id).unwrap().link_group, Some(u64::MAX), "the existing group is untouched"); + } +} + +#[test] +fn undo_and_redo_report_only_the_edited_area() { + let mut s = session(8); + let a = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); + select_all(&mut s, &[a]); + // A pixel edit on one layer is bounded by that layer's extent on both sides. + s.edit("paint", |doc, _| { + doc.layer_mut(a).unwrap().surface_mut().unwrap().fill_rect(Rect::new(12, 12, 14, 14), &[0.0, 0.0, 1.0, 1.0]); + Ok(()) + }) + .unwrap(); + s.undo(); + assert_eq!(damage(&s), Some(Rect::new(10, 10, 20, 20))); + s.redo(); + assert_eq!(damage(&s), Some(Rect::new(10, 10, 20, 20))); + // A move reports where the layer was and where it landed. + s.execute("layer.translate", json!({"dx": 5, "dy": 0})).unwrap(); + s.undo(); + assert_eq!(damage(&s), Some(Rect::new(10, 10, 25, 20)), "union of where the layer was and is"); + s.redo(); + assert_eq!(damage(&s), Some(Rect::new(10, 10, 25, 20))); +} + +#[test] +fn undo_of_document_wide_steps_still_composites_everything() { + let mut s = session(8); + let _ = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); + // A canvas change has no bounded damage. + s.execute("image.crop", json!({"x": 0, "y": 0, "width": 30, "height": 25})).unwrap(); + assert_ne!(doc(&s).size, photocraft_doc::Size::new(100, 80)); + s.undo(); + assert_eq!(damage(&s), None, "a size change recomposites the whole canvas"); + // A layer removed and restored changes only where it draws. + let b = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + select_all(&mut s, &[b]); + s.execute("layer.delete", json!({})).unwrap(); + s.undo(); + assert_eq!(damage(&s), Some(Rect::new(0, 0, 5, 5))); +} + +#[test] +fn undo_of_compositor_read_document_fields_composites_everything() { + let mut s = session(8); + let _ = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); + // Global Light changes every effect's angle across the document. + s.execute("layer.layerStyle.globalLight", json!({"angle": 90.0})).unwrap(); + s.undo(); + assert_eq!(damage(&s), None, "a global-light change recomposites everything"); + // A mode change that keeps the pixel format (RGB → Indexed maps to RGB) neither. + s.execute("image.mode.indexedColor", json!({})).unwrap(); + s.undo(); + assert_eq!(damage(&s), None, "a mode change recomposites everything"); +} + +#[test] +fn undo_of_clipping_or_channel_exclusion_composites_everything() { + let mut s = session(8); + let _ = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); + let b = rect_layer(&mut s, Rect::new(12, 12, 30, 30)); + select_all(&mut s, &[b]); + // Clipping reaches the layers clipped above, outside this layer's bounds. + s.execute("layer.setProps", json!({"clipped": true})).unwrap(); + s.undo(); + assert_eq!(damage(&s), None, "a clipping change recomposites everything"); + s.execute("layer.setProps", json!({"channels": [true, false, true]})).unwrap(); + s.undo(); + assert_eq!(damage(&s), None, "an excluded-channel change recomposites everything"); +} + +#[test] +fn linked_layers_move_together_and_undo() { + for depth in [8, 16, 32] { + let mut s = session(depth); + let a = rect_layer(&mut s, Rect::new(0, 0, 10, 10)); + let b = rect_layer(&mut s, Rect::new(20, 20, 30, 30)); + let c = rect_layer(&mut s, Rect::new(50, 50, 60, 60)); + assert!(!s.is_enabled("layer.linkLayers")); + select_all(&mut s, &[a, b]); + assert_eq!(s.execute("layer.linkLayers", json!({})).unwrap()["linked"], true); + let g = doc(&s).layer(a).unwrap().link_group; + assert!(g.is_some() && doc(&s).layer(b).unwrap().link_group == g); + // Move only a: b follows, c stays. + s.execute("layer.select", json!({"layer": a.0})).unwrap(); + s.execute("layer.translate", json!({"dx": 5, "dy": 3})).unwrap(); + assert_eq!(bounds(&s, a), Rect::new(5, 3, 15, 13)); + assert_eq!(bounds(&s, b), Rect::new(25, 23, 35, 33)); + assert_eq!(bounds(&s, c), Rect::new(50, 50, 60, 60)); + s.undo(); + assert_eq!(bounds(&s, a), Rect::new(0, 0, 10, 10)); + assert_eq!(bounds(&s, b), Rect::new(20, 20, 30, 30)); + // Select Linked Layers from just a. + s.execute("layer.selectLinkedLayers", json!({})).unwrap(); + assert_eq!(sel(&s), vec![a, b]); + // Multi-selection translate moves all selected (c added, unlinked). + s.execute("layer.select", json!({"layer": c.0, "mode": "toggle"})).unwrap(); + s.execute("layer.translate", json!({"dx": -1, "dy": 0})).unwrap(); + assert_eq!(bounds(&s, c), Rect::new(49, 50, 59, 60)); + assert_eq!(bounds(&s, a), Rect::new(-1, 0, 9, 10)); + // Toggle: linking the same group again unlinks. + select_all(&mut s, &[a, b]); + assert_eq!(s.execute("layer.linkLayers", json!({})).unwrap()["linked"], false); + assert!(doc(&s).layer(a).unwrap().link_group.is_none()); + } +} + +/// Plain layers carrying stored link groups, as a loaded `.pcraft` or PSD can hold (#961). +fn stored_groups(s: &mut Session, groups: &[Option]) -> Vec { + let ids: Vec = groups.iter().map(|_| rect_layer(s, Rect::new(0, 0, 4, 4))).collect(); + s.edit("load groups", |doc, _| { + for (id, g) in ids.iter().zip(groups) { + doc.layer_mut(*id).unwrap().link_group = *g; + } + Ok(()) + }) + .unwrap(); + ids +} + +fn group(s: &Session, id: LayerId) -> Option { + doc(s).layer(id).unwrap().link_group +} + +/// Links `ids`, then checks they share one group no other layer uses (#961). +fn link_fresh(s: &mut Session, ids: &[LayerId]) -> u64 { + select_all(s, ids); + let past = s.active().unwrap().history.past_len(); + assert_eq!(s.execute("layer.linkLayers", json!({})).unwrap()["linked"], true); + assert_eq!(s.active().unwrap().history.past_len(), past + 1); + let g = group(s, ids[0]).expect("linked"); + assert!(ids.iter().all(|id| group(s, *id) == Some(g))); + let members = doc(s).walk().iter().filter(|(_, _, l)| l.link_group == Some(g)).count(); + assert_eq!(members, ids.len(), "group {g} is shared with unselected layers"); + g +} + +#[test] +fn link_layers_beside_a_maximal_stored_group() { + // The issue's repro: one layer stored at u64::MAX, link it with an unlinked one. + let mut s = session(8); + let ids = stored_groups(&mut s, &[Some(u64::MAX), None]); + assert_ne!(link_fresh(&mut s, &ids), u64::MAX); + // Unlink and relink the pair: with no groups left, numbering starts over at 1. + assert_eq!(s.execute("layer.linkLayers", json!({})).unwrap()["linked"], false); + assert!(ids.iter().all(|id| group(&s, *id).is_none())); + assert_eq!(link_fresh(&mut s, &ids), 1); + + // Two other layers linked beside an untouched maximal pair. + let mut s = session(8); + let ids = stored_groups(&mut s, &[Some(u64::MAX), Some(u64::MAX), None, None]); + let g = link_fresh(&mut s, &ids[2..]); + assert_ne!(g, u64::MAX); + assert_eq!((group(&s, ids[0]), group(&s, ids[1])), (Some(u64::MAX), Some(u64::MAX))); +} + +#[test] +fn unlink_a_maximal_stored_group() { + let mut s = session(8); + let ids = stored_groups(&mut s, &[Some(u64::MAX), Some(u64::MAX), None]); + select_all(&mut s, &ids[..2]); + assert_eq!(s.execute("layer.linkLayers", json!({})).unwrap()["linked"], false); + assert!(ids.iter().all(|id| group(&s, *id).is_none())); + s.undo(); + assert_eq!((group(&s, ids[0]), group(&s, ids[1])), (Some(u64::MAX), Some(u64::MAX))); + // Relinking all three gets a working group. + link_fresh(&mut s, &ids); +} + +#[test] +fn link_layers_when_every_group_is_huge() { + // Unselected groups at the top of the range, including the 0 a wrapped id would join. + let top = [u64::MAX, u64::MAX - 1, u64::MAX - 2, 0, 1, 2]; + let stored: Vec> = top.iter().flat_map(|g| [Some(*g), Some(*g)]).chain([None, None, None, None]).collect(); + let mut s = session(8); + let ids = stored_groups(&mut s, &stored); + let n = top.len() * 2; + let g = link_fresh(&mut s, &ids[n..n + 2]); + assert!(!top.contains(&g), "{g} collides with a stored group"); + // A second link gets yet another group, and existing groups never change. + let h = link_fresh(&mut s, &ids[n + 2..]); + assert!(!top.contains(&h) && h != g); + for (i, t) in top.iter().enumerate() { + assert_eq!((group(&s, ids[2 * i]), group(&s, ids[2 * i + 1])), (Some(*t), Some(*t))); + } + // Moving a newly linked layer leaves the group-0 pair alone. + assert_eq!(with_links(doc(&s), &[ids[n]]), vec![ids[n], ids[n + 1]]); +} + +#[test] +fn link_layers_near_the_maximum() { + // max + 1 still fits: the new group is u64::MAX itself. + let mut s = session(8); + let ids = stored_groups(&mut s, &[Some(u64::MAX - 1), Some(u64::MAX - 1), None, None, None, None]); + assert_eq!(link_fresh(&mut s, &ids[2..4]), u64::MAX); + // The next link no longer fits above the maximum and takes a free id instead. + let g = link_fresh(&mut s, &ids[4..]); + assert!(g != u64::MAX && g != u64::MAX - 1); +} + +#[test] +fn link_layers_assigns_working_groups() { + // Control: ordinary documents keep getting max + 1, starting at 1. + let mut s = session(8); + let ids = stored_groups(&mut s, &[None, None, None, None]); + assert_eq!(link_fresh(&mut s, &ids[..2]), 1); + assert_eq!(link_fresh(&mut s, &ids[2..]), 2); + assert_eq!(s.execute("layer.linkLayers", json!({})).unwrap()["linked"], false); + assert_eq!((group(&s, ids[2]), group(&s, ids[3])), (None, None)); + assert_eq!((group(&s, ids[0]), group(&s, ids[1])), (Some(1), Some(1))); +} + +#[test] +fn selection_pruned_after_delete_and_undo() { + let mut s = session(8); + let a = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + let b = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + let c = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + select_all(&mut s, &[a, c]); + // Deleting one layer explicitly prunes it from the set. + s.execute("layer.delete", json!({"layer": a.0})).unwrap(); + assert_eq!(sel(&s), vec![c]); + s.undo(); + assert!(sel(&s).iter().all(|id| doc(&s).layer(*id).is_some())); + // Deleting with several selected removes them all, then selects the layer below. + select_all(&mut s, &[a, c]); + s.execute("layer.delete", json!({})).unwrap(); + assert!(doc(&s).layer(a).is_none() && doc(&s).layer(c).is_none()); + assert_eq!(doc(&s).layer_count(), 2); + assert_eq!(sel(&s).len(), 1); + assert!(s.active().unwrap().selected_layers.iter().all(|id| doc(&s).layer(*id).is_some())); + s.undo(); + assert_eq!(doc(&s).layer_count(), 4); + let _ = b; + // Redo then undo again keeps the set valid. + s.redo(); + assert!(sel(&s).iter().all(|id| doc(&s).layer(*id).is_some())); +} + +#[test] +fn duplicate_hide_lock_and_reverse_selected() { + let mut s = session(8); + let a = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + let b = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + let c = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + select_all(&mut s, &[a, c]); + let r = s.execute("layer.duplicate", json!({})).unwrap(); + assert_eq!(r["layers"].as_array().unwrap().len(), 2); + assert_eq!(doc(&s).layer_count(), 6); + assert_eq!(sel(&s).len(), 2); + assert!(sel(&s).iter().all(|id| *id != a && *id != c)); + s.undo(); + select_all(&mut s, &[a, b]); + s.execute("layer.hideLayers", json!({})).unwrap(); + assert!(!doc(&s).layer(a).unwrap().visible && !doc(&s).layer(b).unwrap().visible && doc(&s).layer(c).unwrap().visible); + s.execute("layer.showLayers", json!({})).unwrap(); + assert!(doc(&s).layer(a).unwrap().visible); + s.execute("layer.lockLayers", json!({})).unwrap(); + assert!(doc(&s).layer(a).unwrap().locks.all && doc(&s).layer(b).unwrap().locks.all); + assert!(s.execute("layer.translate", json!({"dx": 1})).is_err(), "locked layers don't move"); + s.execute("layer.lockLayers", json!({})).unwrap(); + assert!(!doc(&s).layer(a).unwrap().locks.all); + s.execute("layer.lockLayers", json!({"position": true})).unwrap(); + assert!(doc(&s).layer(b).unwrap().locks.position && !doc(&s).layer(c).unwrap().locks.position); + // Reverse a, b, c. + select_all(&mut s, &[a, b, c]); + s.execute("layer.arrange.reverse", json!({})).unwrap(); + assert_eq!(doc(&s).layers.iter().skip(1).map(|l| l.id).collect::>(), vec![c, b, a]); + assert_eq!(s.active().unwrap().history.entries().last().map(|e| e.as_str()), Some("Reverse")); +} + +/// #4892: Lock Image Pixels includes Lock Transparent Pixels, so the two are never both on: +/// locking the pixels clears the transparency lock, which stays off while they are locked, +/// through both `layer.setProps` and `layer.lockLayers`. +#[test] +fn locking_pixels_clears_and_holds_off_the_transparency_lock() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + let id = LayerId(s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap()); + let locks = |s: &Session| doc(s).layer(id).unwrap().locks; + s.execute("layer.setProps", json!({"locks": {"transparency": true}})).unwrap(); + assert!(locks(&s).transparency); + s.execute("layer.setProps", json!({"locks": {"pixels": true}})).unwrap(); + assert!(locks(&s).pixels && !locks(&s).transparency, "locking the pixels clears the transparency lock"); + s.execute("layer.setProps", json!({"locks": {"transparency": true}})).unwrap(); + assert!(!locks(&s).transparency, "and it stays off while the pixels are locked"); + s.execute("layer.setProps", json!({"locks": {"transparency": true, "pixels": true}})).unwrap(); + assert!(locks(&s).pixels && !locks(&s).transparency, "both at once: the pixel lock wins"); + s.execute("layer.lockLayers", json!({"pixels": false})).unwrap(); + s.execute("layer.lockLayers", json!({"transparency": true})).unwrap(); + assert!(locks(&s).transparency && !locks(&s).pixels, "with the pixels unlocked it can be set again"); + s.execute("layer.lockLayers", json!({"pixels": true})).unwrap(); + assert!(locks(&s).pixels && !locks(&s).transparency); + assert!(s.execute("layer.setProps", json!({"locks": {"nope": true}})).is_err()); +} + +/// `document.inspect` lists the selected layers and marks them in the layer list. +#[test] +fn inspect_reports_selection() { + let mut s = session(8); + let a = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + let b = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + select_all(&mut s, &[a, b]); + let v = s.execute("document.inspect", json!({})).unwrap(); + assert_eq!(v["selectedLayers"], json!([a.0, b.0])); + assert_eq!(v["layers"][0]["selected"], true); +} + +/// #7538: `selection: true` moves the selection with the layers in the same step, as the Move +/// tool does with several layers selected; without it the selection stays. +#[test] +fn translate_can_carry_the_selection_in_the_same_step() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 100, "height": 100, "background": "transparent"})).unwrap(); + let a = s.active().unwrap().active_layer.unwrap(); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + let b = LayerId(s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap()); + s.execute("select.rect", json!({"x": 50, "y": 10, "width": 20, "height": 20})).unwrap(); + s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap(); + s.execute("layer.select", json!({"layer": a.0, "mode": "add"})).unwrap(); + s.execute("select.rect", json!({"x": 5, "y": 5, "width": 70, "height": 30})).unwrap(); + let sel = |s: &Session| s.active().unwrap().doc.selection.as_ref().map(|m| m.content_bounds()); + let bounds = |s: &Session, id: LayerId| s.active().unwrap().doc.layer(id).unwrap().surface().unwrap().content_bounds(); + let steps = s.active().unwrap().history.past_len(); + s.execute("layer.translate", json!({"dx": 7, "dy": 20, "selection": true})).unwrap(); + assert_eq!((bounds(&s, a), bounds(&s, b)), (Rect::new(17, 30, 37, 50), Rect::new(57, 30, 77, 50))); + assert_eq!(sel(&s), Some(Rect::new(12, 25, 82, 55)), "the selection came along"); + assert_eq!(s.active().unwrap().history.past_len(), steps + 1, "one step"); + s.undo(); + assert_eq!((sel(&s), bounds(&s, a)), (Some(Rect::new(5, 5, 75, 35)), Rect::new(10, 10, 30, 30)), "undone together"); + s.execute("layer.translate", json!({"dx": 7, "dy": 20})).unwrap(); + assert_eq!(sel(&s), Some(Rect::new(5, 5, 75, 35)), "without it the selection stays"); + let state = |s: &Session| (bounds(s, a), bounds(s, b), sel(s), s.active().unwrap().history.past_len()); + let before = state(&s); + for dx in [1, 0] { + assert!(s.execute("layer.translate", json!({"dx": dx, "selection": "yes"})).is_err(), "dx {dx}: a bad `selection` is an error"); + assert_eq!(state(&s), before, "dx {dx}: and changes nothing"); + } +} diff --git a/crates/engine/src/layer_nav_cmds.rs b/crates/engine/src/cmd/layer_nav_cmds.rs similarity index 100% rename from crates/engine/src/layer_nav_cmds.rs rename to crates/engine/src/cmd/layer_nav_cmds.rs diff --git a/crates/engine/src/cmd/layer_params.rs b/crates/engine/src/cmd/layer_params.rs new file mode 100644 index 0000000000..057be4a02c --- /dev/null +++ b/crates/engine/src/cmd/layer_params.rs @@ -0,0 +1,113 @@ +use super::params::bad; +use super::*; + +/// The layer a command's `"layer"` param names: an id, or a name (the topmost layer of that +/// name, as Photoshop's "select layer by name" action step finds it, so a loaded action replays +/// in another document; a name that matches no layer exactly matches regardless of case, so +/// `"background"` finds the Background). `None` when the param is absent. +pub(crate) fn explicit_layer(s: &Session, p: &Value) -> Result> { + match p.get("layer") { + Some(Value::Number(n)) => { + n.as_u64().map(|id| Some(LayerId(id))).ok_or_else(|| EngineError::Other(format!("layer id {n} is not a non-negative integer"))) + } + Some(Value::String(name)) => { + let d = s.active().ok_or(EngineError::NoDocument)?; + let layers = d.doc.walk(); + let mut top_down = layers.iter().rev(); + top_down + .clone() + .find(|(_, _, l)| l.name == *name) + .or_else(|| top_down.find(|(_, _, l)| l.name.to_lowercase() == name.to_lowercase())) + .map(|(_, _, l)| Some(l.id)) + .ok_or_else(|| EngineError::Other(format!("no layer named \"{name}\"; {}", layer_listing(&d.doc)))) + } + Some(Value::Null) | None => Ok(None), + Some(other) => Err(EngineError::Other(format!("`layer` must be an id or a name, not {other}"))), + } +} + +/// The layers of `doc` as a caller can name them, for an error about a layer that isn't there: +/// `the document's layers are 2 "Background", 3 "Layer 1"` (top-down, at most 20). +pub(crate) fn layer_listing(doc: &Document) -> String { + const MAX: usize = 20; + let layers = doc.walk(); + if layers.is_empty() { + return "the document has no layers".into(); + } + // Names are unbounded input: each one is cut at NAME characters so the error stays short. + const NAME: usize = 64; + let name = |n: &str| match n.char_indices().nth(NAME) { + Some((cut, _)) => format!("{}…", &n[..cut]), + None => n.to_string(), + }; + let mut list: Vec = layers.iter().rev().take(MAX).map(|(_, _, l)| format!("{} {:?}", l.id.0, name(&l.name))).collect(); + if layers.len() > MAX { + list.push(format!("… {} more (see `document.inspect`)", layers.len() - MAX)); + } + format!("the document's layers are {} (a `layer` param takes an id or a name)", list.join(", ")) +} + +/// The layer a command targets: [`explicit_layer`], else the active layer. +pub(crate) fn layer_param(s: &Session, p: &Value) -> Result { + match explicit_layer(s, p)? { + Some(id) => Ok(id), + None => s.active().and_then(|d| d.active_layer).ok_or(EngineError::Other("no active layer".into())), + } +} + +pub fn blend_from_str(s: &str) -> Option { + let norm = |x: &str| x.to_ascii_lowercase().replace([' ', '_', '-', '(', ')'], ""); + let want = norm(s); + std::iter::once(BlendMode::PassThrough).chain(BlendMode::layer_modes()).find(|m| norm(m.label()) == want || norm(&format!("{m:?}")) == want) +} + +/// The active selection as the mask of a layer being created, or None without a selection. +/// Photoshop masks a new adjustment or fill layer with the selection, so the adjustment acts on +/// the selected area only (#1250); the selection itself stays, as Reveal Selection leaves it. +pub(crate) fn selection_mask(doc: &Document) -> Result> { + doc.selection.as_ref().map(|sel| mask_at_depth(LayerMask { surface: sel.clone(), ..LayerMask::reveal_all() }, doc.depth)).transpose() +} + +/// New pixel masks use the document's depth, as PSD saves/imports do. Otherwise a later soft +/// brush stroke quantizes differently depending on whether the document reopened as PSD or +/// native. Converting a selection keeps its coverage and does not alter the selection itself. +pub(crate) fn mask_at_depth(mut mask: LayerMask, depth: SampleType) -> Result { + let format = mask.surface.format().with_sample(depth); + if mask.surface.format() != format { + mask.surface = mask.surface.try_convert(format)?; + } + Ok(mask) +} + +/// Options from the Layers Panel flyout live in preferences so headless/keyboard commands +/// behave exactly like pointer-triggered commands. Old preferences preserve Photoshop defaults. +pub(crate) fn layer_panel_option(s: &Session, key: &str, fallback: bool) -> bool { + s.prefs().dialogs.get("ui.layersPanelOptions").and_then(|v| v.get(key)).and_then(Value::as_bool).unwrap_or(fallback) +} + +/// Mask a fill or adjustment layer being created, as Photoshop does: the path selected in the +/// Paths panel (`"path"`: `"work"`, a saved path's name or a path object) becomes its vector +/// mask, which makes a Solid Color fill a shape (#1419); without one, the selection becomes its +/// layer mask ([`selection_mask`]); without either, a white mask reveals the whole layer (#1768). +/// A path that isn't there is an error. +pub(crate) fn mask_new_layer(doc: &Document, l: &mut Layer, p: &Value, cmd: &str, default_mask: bool) -> Result<()> { + let path = match p.get("path") { + None | Some(Value::Null) => None, + Some(Value::String(n)) if crate::vector_cmds::is_work(Some(n)) => Some(doc.work_path.clone().ok_or_else(|| bad(cmd, "no work path"))?), + Some(Value::String(n)) => { + Some(doc.paths.iter().find(|sp| sp.name == *n).map(|sp| sp.path.clone()).ok_or_else(|| bad(cmd, format!("no path named \"{n}\"")))?) + } + Some(v) => Some(crate::vector_cmds::parse_path(v).map_err(|e| bad(cmd, e))?), + }; + match path { + Some(path) => l.vector_mask = Some(photocraft_doc::VectorMask::new(path)), + None => { + l.mask = selection_mask(doc)?.or_else(|| default_mask.then(LayerMask::reveal_all)).map(|mask| mask_at_depth(mask, doc.depth)).transpose()?; + } + } + Ok(()) +} + +/// The `"path"` param of the new fill and adjustment layer commands ([`mask_new_layer`]). +pub(crate) const NEW_LAYER_PATH: &str = + r##""path":"work"|saved path name|{…path}? (the active path: becomes the vector mask; else the selection is the layer mask, or white with no selection)"##; diff --git a/crates/engine/src/layer_xmp_cmds.rs b/crates/engine/src/cmd/layer_xmp_cmds.rs similarity index 100% rename from crates/engine/src/layer_xmp_cmds.rs rename to crates/engine/src/cmd/layer_xmp_cmds.rs diff --git a/crates/engine/src/layer_xmp_cmds/tests.rs b/crates/engine/src/cmd/layer_xmp_cmds/tests.rs similarity index 100% rename from crates/engine/src/layer_xmp_cmds/tests.rs rename to crates/engine/src/cmd/layer_xmp_cmds/tests.rs diff --git a/crates/engine/src/lens_cmds.rs b/crates/engine/src/cmd/lens_cmds.rs similarity index 100% rename from crates/engine/src/lens_cmds.rs rename to crates/engine/src/cmd/lens_cmds.rs diff --git a/crates/engine/src/magnetic_cmds.rs b/crates/engine/src/cmd/magnetic_cmds.rs similarity index 100% rename from crates/engine/src/magnetic_cmds.rs rename to crates/engine/src/cmd/magnetic_cmds.rs diff --git a/crates/engine/src/magnetic_cmds/tests.rs b/crates/engine/src/cmd/magnetic_cmds/tests.rs similarity index 100% rename from crates/engine/src/magnetic_cmds/tests.rs rename to crates/engine/src/cmd/magnetic_cmds/tests.rs diff --git a/crates/engine/src/mask_view_cmds.rs b/crates/engine/src/cmd/mask_view_cmds.rs similarity index 100% rename from crates/engine/src/mask_view_cmds.rs rename to crates/engine/src/cmd/mask_view_cmds.rs diff --git a/crates/engine/src/mask_view_cmds/tests.rs b/crates/engine/src/cmd/mask_view_cmds/tests.rs similarity index 100% rename from crates/engine/src/mask_view_cmds/tests.rs rename to crates/engine/src/cmd/mask_view_cmds/tests.rs diff --git a/crates/engine/src/migrate_cmds.rs b/crates/engine/src/cmd/migrate_cmds.rs similarity index 100% rename from crates/engine/src/migrate_cmds.rs rename to crates/engine/src/cmd/migrate_cmds.rs diff --git a/crates/engine/src/mode_cmds.rs b/crates/engine/src/cmd/mode_cmds.rs similarity index 100% rename from crates/engine/src/mode_cmds.rs rename to crates/engine/src/cmd/mode_cmds.rs diff --git a/crates/engine/src/mode_cmds/tests.rs b/crates/engine/src/cmd/mode_cmds/tests.rs similarity index 100% rename from crates/engine/src/mode_cmds/tests.rs rename to crates/engine/src/cmd/mode_cmds/tests.rs diff --git a/crates/engine/src/multichannel_cmds.rs b/crates/engine/src/cmd/multichannel_cmds.rs similarity index 100% rename from crates/engine/src/multichannel_cmds.rs rename to crates/engine/src/cmd/multichannel_cmds.rs diff --git a/crates/engine/src/multichannel_cmds/tests.rs b/crates/engine/src/cmd/multichannel_cmds/tests.rs similarity index 100% rename from crates/engine/src/multichannel_cmds/tests.rs rename to crates/engine/src/cmd/multichannel_cmds/tests.rs diff --git a/crates/engine/src/notes_cmds.rs b/crates/engine/src/cmd/notes_cmds.rs similarity index 100% rename from crates/engine/src/notes_cmds.rs rename to crates/engine/src/cmd/notes_cmds.rs diff --git a/crates/engine/src/cmd/ops.rs b/crates/engine/src/cmd/ops.rs new file mode 100644 index 0000000000..776f47e020 --- /dev/null +++ b/crates/engine/src/cmd/ops.rs @@ -0,0 +1,160 @@ +use super::enabled::check_all_unlocked; +use super::layer_params::{layer_param, mask_at_depth}; +use super::*; + +pub(super) fn arrange(s: &mut Session, p: &Value, delta: i32) -> Result { + let id = layer_param(s, p)?; + s.edit("Arrange", |doc, _| { + // The Background stays at the bottom: it doesn't move and nothing goes below it. + let bg = crate::background_cmds::background_id(doc); + if bg == Some(id) { + return Err(EngineError::Other("the Background layer can't be moved".into())); + } + let steps = match delta { + i32::MAX => 10_000, + i32::MIN => -10_000, + d => d, + }; + let dir = steps.signum(); + let before = crate::clip_group::Before::read(doc, &[id]); + let mut moved = false; + for _ in 0..steps.abs() { + if !doc.shift(id, dir) { + break; + } + if crate::background_cmds::keep_background_at_bottom(bg, doc).is_err() { + doc.shift(id, -dir); + break; + } + moved = true; + } + if !moved { + return Err(EngineError::Other("layer can't move further".into())); + } + crate::clip_group::settle(doc, &[id], &before, false); + Ok(()) + })?; + Ok(Value::Null) +} + +/// Add (`Some`) or remove (`None`) a layer mask. Adding acts on every selected layer that can take +/// one ([`crate::layer_multi_cmds::mask_targets`]), in one history step. +pub(super) fn set_mask(s: &mut Session, p: &Value, label: &str, mask: Option) -> Result { + set_mask_with(s, p, label, mask, false) +} + +/// [`set_mask`] that also drops the selection the mask was made from, in the same history step. +pub(super) fn set_mask_and_deselect(s: &mut Session, p: &Value, label: &str, mask: LayerMask) -> Result { + set_mask_with(s, p, label, Some(mask), true) +} + +fn set_mask_with(s: &mut Session, p: &Value, label: &str, mask: Option, deselect: bool) -> Result { + let ids = if mask.is_some() { crate::layer_multi_cmds::mask_targets(s, p)? } else { vec![layer_param(s, p)?] }; + s.edit(label, |doc, _| { + let mask = mask.clone().map(|mask| mask_at_depth(mask, doc.depth)).transpose()?; + for id in &ids { + check_all_unlocked(doc, *id)?; + if mask.is_some() { + crate::extra_cmds::background_to_layer_for_mask(doc, *id); + } + doc.layer_mut(*id).ok_or(EngineError::NoLayer(*id))?.mask = mask.clone(); + } + if deselect { + doc.selection = None; + } + Ok(()) + })?; + Ok(Value::Null) +} + +/// Move a layer's pixels, linked mask and type by whole pixels (vectors move via +/// `vector_cmds::translate_vectors`). +pub(crate) fn translate_layer(doc: &Document, l: &mut Layer, dx: i32, dy: i32) { + use crate::layer_multi_cmds::shift_surface as translate_surface; + // Linked patterns in the layer's effects move with it. + if let Some(r) = &mut l.effects.reference { + *r = (r.0 + f64::from(dx), r.1 + f64::from(dy)); + } + if let Some(m) = &mut l.mask + && m.linked + { + m.surface = translate_surface(&m.surface, dx, dy); + } + match &mut l.content { + LayerContent::Raster(s) => *s = translate_surface(s, dx, dy), + LayerContent::Text(t) => { + t.transform = photocraft_geom::Affine::translate(dx as f64, dy as f64).mul(&t.transform); + // A whole-pixel move shifts the rendered text and its PSD position as they are. + // Re-rendering would replace Photoshop's rendering of imported type, and drop the + // text when its font is missing (artboard export, moving type with the Move tool). + let raw = t.psd_raw.as_deref().map(|r| photocraft_text::psd::translate_tysh(r, f64::from(dx), f64::from(dy))); + match (&mut t.cache, raw) { + (Some(c), Some(Some(r))) => { + *c = translate_surface(c, dx, dy); + t.psd_raw = Some(std::sync::Arc::new(r)); + } + (Some(c), None) => *c = translate_surface(c, dx, dy), + _ => crate::type_cmds::refresh(doc, t), + } + } + LayerContent::Group(g) => { + // Moving an artboard moves the board with its contents. + if let Some(a) = &mut g.artboard { + a.rect = a.rect.translate(dx, dy); + } + for c in &mut g.children { + translate_layer(doc, c, dx, dy); + } + } + LayerContent::Smart(sm) => crate::smart_cmds::shift_smart(sm, dx, dy), + _ => {} + } +} + +/// A copy of layer `id` as Layer › Duplicate Layer makes it, not yet in the document: a fresh id, +/// "… copy" appended to the name, and a copy of the Background layer is an ordinary, unlocked +/// layer (Photoshop). +pub(crate) fn layer_copy(doc: &Document, id: LayerId, add_copy: bool) -> Result { + let src = doc.layer(id).ok_or(EngineError::NoLayer(id))?; + // A copy of the Background layer is an ordinary, unlocked layer (Photoshop). + let from_background = doc.is_background(id); + let mut dup = src.duplicate(); + if add_copy { + dup.name = doc.copy_name(&dup.name); + } + if from_background { + dup.locks = Default::default(); + } + Ok(dup) +} + +/// Layer › Merge Group (⌘E with a group selected, #3832): the group's visible contents, as they +/// show, become one pixel layer in its place, named after it. Like Photoshop, the layer keeps the +/// group's opacity, blend mode (Pass Through becomes Normal), clipping and locks; the group's mask +/// and style are applied to the pixels. +pub(super) fn merge_group(s: &mut Session, id: LayerId) -> Result { + s.edit("Merge Group", |doc, active| { + let group = doc.layer(id).ok_or(EngineError::NoLayer(id))?.clone(); + if !group.visible { + return Err(EngineError::Other("the group is hidden".into())); + } + let fmt = doc.pixel_format(); + let fmt = photocraft_color::PixelFormat::new(fmt.mode, fmt.sample, true); + let mut solo = group.clone(); + solo.opacity = 1.0; + solo.blend = photocraft_doc::BlendMode::Normal; + solo.clipped = false; + let mut tmp = doc.clone(); + tmp.layers = vec![solo]; + let mut merged = Layer::new(group.name.clone(), LayerContent::Raster(pixels::composite_layers_uncropped(&tmp, fmt))); + merged.id = group.id; + merged.opacity = group.opacity; + merged.blend = if group.blend == photocraft_doc::BlendMode::PassThrough { photocraft_doc::BlendMode::Normal } else { group.blend }; + merged.clipped = group.clipped; + merged.locks = group.locks; + *doc.layer_mut(id).ok_or(EngineError::NoLayer(id))? = merged; + *active = Some(id); + Ok(()) + })?; + Ok(json!({ "layer": id.0 })) +} diff --git a/crates/engine/src/cmd/paint_cmds.rs b/crates/engine/src/cmd/paint_cmds.rs new file mode 100644 index 0000000000..b0cf8e571b --- /dev/null +++ b/crates/engine/src/cmd/paint_cmds.rs @@ -0,0 +1,199 @@ +//! Paint helpers: Paint Bucket and Gradient tool. + +use photocraft_algo::paint::{FillMode, GradientShape, bucket_fill_inks, bucket_fill_region_inks, paint_gradient}; +use serde_json::{Value, json}; + +use crate::commands::{CommandSpec, blend_from_str}; +use crate::presets::gradients; +use crate::{EngineError, Result, Session}; + +fn f(p: &Value, k: &str, d: f32) -> f32 { + p.get(k).and_then(Value::as_f64).map_or(d, |v| v as f32) +} +fn b(p: &Value, k: &str, d: bool) -> bool { + p.get(k).and_then(Value::as_bool).unwrap_or(d) +} +fn color(v: Option<&Value>, d: [f32; 4]) -> [f32; 4] { + match v { + Some(Value::Array(a)) if a.len() >= 3 => { + let c: Vec = a.iter().map(|x| x.as_f64().unwrap_or(0.0) as f32).collect(); + [c[0], c[1], c[2], c.get(3).copied().unwrap_or(1.0)] + } + Some(Value::String(h)) => { + let h = h.trim_start_matches('#'); + let c = |i: usize| h.get(i..i + 2).and_then(|x| u8::from_str_radix(x, 16).ok()).map(|v| f32::from(v) / 255.0); + match (c(0), c(2), c(4)) { + (Some(r), Some(g), Some(b)) => [r, g, b, c(6).unwrap_or(1.0)], + _ => d, + } + } + _ => d, + } +} +fn point(p: &Value, k: &str) -> Option<(f32, f32)> { + let a = p.get(k)?.as_array()?; + Some((a.first()?.as_f64()? as f32, a.get(1)?.as_f64()? as f32)) +} + +/// `opacity` (1..100 %) as a coverage in 0.01..=1, clamped like the Magic Eraser's: a value +/// above 1 would overshoot the blend (#4167). +fn opacity(p: &Value, cmd: &str) -> Result { + Ok(crate::eraser_cmds::number(p, cmd, "opacity", 100.0, 1.0..=100.0)? as f32 / 100.0) +} + +/// The Paint Bucket's `mode`: a blend mode (not Pass Through, a group's) or `clear`. +fn fill_mode(p: &Value) -> Result { + let bad = |msg: String| EngineError::BadParams { cmd: "paint.bucket".into(), msg }; + match p.get("mode") { + None | Some(Value::Null) => Ok(FillMode::Blend(photocraft_color::BlendMode::Normal)), + Some(Value::String(m)) if m.eq_ignore_ascii_case("clear") => Ok(FillMode::Clear), + Some(Value::String(m)) => blend_from_str(m) + .filter(|m| *m != photocraft_color::BlendMode::PassThrough) + .map(FillMode::Blend) + .ok_or_else(|| bad(format!("unknown blend mode `{m}`"))), + Some(v) => Err(bad(format!("`mode` must be a blend mode name or `clear`, not {v}"))), + } +} + +fn bucket(s: &mut Session, p: &Value) -> Result { + let fg = s.tools.foreground; + let c = color(p.get("color"), fg); + let (x, y) = (f(p, "x", 0.0).floor() as i32, f(p, "y", 0.0).floor() as i32); + let (tol, contiguous, aa) = (f(p, "tolerance", 32.0), b(p, "contiguous", true), b(p, "antiAlias", true)); + let opacity = opacity(p, "paint.bucket")?; + let mode = fill_mode(p)?; + let all = b(p, "sampleAllLayers", false) && crate::channel_cmds::target_of(p) == crate::channel_cmds::Target::Pixels; + // Other visible layers can define the region, but the fill still writes only to the target. + let region = if all { + let (area, img) = crate::selection_cmds::sample_rgba8(s, true)?; + let region = photocraft_algo::selection::wand_region(&img, area, (x, y), tol, contiguous, aa); + drop(img); + region + } else { + None + }; + // Fill source: foreground colour (default) or a pattern (the Paint Bucket "Fill" dropdown). + let source = p.get("contents").or_else(|| p.get("source")).and_then(Value::as_str).unwrap_or("foreground"); + let pattern = if source == "pattern" { + let pat = crate::pattern_cmds::resolve_param(s, "paint.bucket", p)?; + let tile = photocraft_compose::pattern::Tile::new(&pat) + .ok_or_else(|| EngineError::BadParams { cmd: "paint.bucket".into(), msg: "the pattern is empty or too large to paint".into() })?; + let (scale, angle, _, phase) = crate::pattern_cmds::placement("paint.bucket", p)?; + Some((tile, scale, angle, phase)) + } else { + None + }; + // A foreground picked as CMYK fills a CMYK document with the picked inks (#4196). + let inks = s.tools.picked_cmyk([c[0], c[1], c[2]]).filter(|_| c[3] >= 1.0 && pattern.is_none()); + let filled = s.edit("Paint Bucket", |doc, active| { + let area = doc.bounds(); + let sel = doc.selection.clone(); + let (surf, lock) = crate::channel_cmds::target_surface(doc, *active, p)?; + let ok = if all && region.is_none() { + false + } else if let Some((tile, scale, angle, phase)) = &pattern { + // Render the pattern over the canvas once, then sample it at each filled pixel. + let place = photocraft_compose::pattern::Placement::new(photocraft_geom::Rect::EMPTY, false, *phase, *scale, *angle); + let rendered = photocraft_compose::pattern::render(tile, &place, area); + let w = area.width() as usize; + let src = |px: i32, py: i32| rendered[(py - area.y0) as usize * w + (px - area.x0) as usize]; + if let Some(region) = ®ion { + bucket_fill_region_inks(surf, region, opacity, sel.as_ref(), lock, src, None, mode); + true + } else { + bucket_fill_inks(surf, area, (x, y), tol, contiguous, aa, opacity, sel.as_ref(), lock, src, None, mode) + } + } else if let Some(region) = ®ion { + bucket_fill_region_inks(surf, region, opacity, sel.as_ref(), lock, |_, _| c, inks, mode); + true + } else { + bucket_fill_inks(surf, area, (x, y), tol, contiguous, aa, opacity, sel.as_ref(), lock, |_, _| c, inks, mode) + }; + surf.prune(); + Ok(ok) + })?; + Ok(json!({ "filled": filled })) +} + +fn gradient(s: &mut Session, p: &Value) -> Result { + let from = point(p, "from").ok_or_else(|| EngineError::BadParams { cmd: "paint.gradient".into(), msg: "missing from".into() })?; + let to = point(p, "to").ok_or_else(|| EngineError::BadParams { cmd: "paint.gradient".into(), msg: "missing to".into() })?; + let shape = match p.get("style").and_then(Value::as_str).unwrap_or("linear") { + "radial" => GradientShape::Radial, + "angle" => GradientShape::Angle, + "reflected" => GradientShape::Reflected, + "diamond" => GradientShape::Diamond, + _ => GradientShape::Linear, + }; + let (fg, bg) = (s.tools.foreground, s.tools.background); + // A preset (`gradient`), explicit `stops`, or the current gradient (Gradients panel); the + // legacy `colors` list spaces its colours evenly. Explicit `transparency` applies to all. + let stops: Vec<(f32, [f32; 4])> = match gradients::tool_stops(s, p)? { + Some(st) => st, + None => { + let colors: Vec<[f32; 4]> = + p.get("colors").and_then(Value::as_array).map(|a| a.iter().map(|v| color(Some(v), fg)).collect()).unwrap_or_else(|| vec![fg, bg]); + let n = colors.len(); + let cs = colors.into_iter().enumerate().map(|(i, c)| (if n > 1 { i as f32 / (n - 1) as f32 } else { 0.0 }, c)).collect(); + gradients::apply_opacity(cs, &gradients::transparency_param(p, "paint.gradient")?.unwrap_or_default()) + } + }; + // Photoshop's interpolation (`method`, with `smoothness` 0..=100, default 100) baked into dense + // stops, as for Gradient Overlay: Photoshop 27.11's Classic black → white is 0.037 at t = 1/16 + // where straight stops give 0.0625. + let stops = match p.get("method").and_then(Value::as_str).and_then(photocraft_io::GradientMethod::from_name) { + Some(m) if stops.len() >= 2 => { + let colors = stops.iter().map(|(t, c)| (*t, photocraft_color::Color::rgba(c[0], c[1], c[2], c[3]))).collect(); + let mids = vec![0.5; stops.len() - 1]; + photocraft_io::bake_gradient(colors, &mids, (f(p, "smoothness", 100.0) / 100.0).clamp(0.0, 1.0), m) + .into_iter() + .map(|(t, c)| { + let rgb = c.to_rgb(); + (t, [rgb[0], rgb[1], rgb[2], c.alpha]) + }) + .collect() + } + _ => stops, + }; + let reverse = b(p, "reverse", false); + let opacity = opacity(p, "paint.gradient")?; + let blend = p.get("mode").and_then(Value::as_str).and_then(blend_from_str).unwrap_or(photocraft_color::BlendMode::Normal); + let dither = b(p, "dither", true); // Photoshop dithers gradients by default (reduces banding). + s.edit("Gradient", |doc, active| { + let sel = doc.selection.clone(); + let area = sel.as_ref().map(|m| m.content_bounds()).filter(|r| !r.is_empty()).unwrap_or_else(|| doc.bounds()).intersect(&doc.bounds()); + let (surf, lock) = crate::channel_cmds::target_surface(doc, *active, p)?; + paint_gradient(surf, area, from, to, shape, &stops, reverse, opacity, blend, dither, sel.as_ref(), lock); + Ok(()) + })?; + Ok(Value::Null) +} + +/// Paint helper command specs. +pub fn specs() -> Vec { + vec![ + CommandSpec { + id: "paint.bucket", + label: "Paint Bucket", + menu: &[], + shortcut: None, + params: r##"{"x":px,"y":px,"tolerance":0..255=32,"contiguous":bool=true,"antiAlias":bool=true,"sampleAllLayers":bool=false,"contents":"foreground|pattern"="foreground","color":"#rrggbb"=foreground,"pattern":id|name (contents=pattern),"scale":%=100,"angle":deg,"opacity":1..100=100,"mode":"normal|multiply|…|clear (erases the filled area)"="normal","target":"pixels"|"mask"|"filterMask"|"quickMask"|{"channel":i}=Channels panel target}"##, + enabled: crate::commands::has_paintable, + run: bucket, + journal: true, + }, + CommandSpec { + id: "paint.gradient", + label: "Gradient", + menu: &[], + shortcut: None, + params: r##"{"from":[x,y],"to":[x,y],"style":"linear|radial|angle|reflected|diamond"="linear","colors":["#rrggbb",…]? (evenly spaced),"gradient":preset name?,"stops":[[t,"#rrggbb"|"foreground"|"background"],…]?,"transparency":[[t,0..100],…]? (default: the current gradient, see gradient.presets.select),"method":"classic|perceptual|linear|smooth"? (Photoshop's interpolation; omitted: straight stops),"smoothness":0..100=100,"reverse":bool=false,"dither":bool=true,"opacity":1..100=100,"mode":"normal|multiply|…"="normal","target":"pixels"|"mask"|"filterMask"|"quickMask"|{"channel":i}=Channels panel target}"##, + enabled: crate::commands::has_paintable, + run: gradient, + journal: true, + }, + ] +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/paint_cmds/tests.rs b/crates/engine/src/cmd/paint_cmds/tests.rs new file mode 100644 index 0000000000..ba30e9d719 --- /dev/null +++ b/crates/engine/src/cmd/paint_cmds/tests.rs @@ -0,0 +1,330 @@ +use super::*; +use photocraft_geom::Rect; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 20, "height": 10})).unwrap(); + s +} + +fn px(s: &Session, x: i32, y: i32) -> Vec { + let d = s.active().unwrap(); + d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap().pixel(x, y) +} + +/// A visible wall on the Background with an empty, active layer above it. +fn bucket_layers(depth: u32) -> (Session, photocraft_doc::LayerId) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 20, "height": 10, "depth": depth, "background": "white"})).unwrap(); + let bottom = s.active().unwrap().active_layer.unwrap(); + s.edit("wall", |doc, _| { + doc.layer_mut(bottom).unwrap().surface_mut().unwrap().fill_rect(Rect::new(10, 0, 11, 10), &[0.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + (s, bottom) +} + +/// The options bar's Mode reaches the fill: Multiply over grey, Clear erases, a bad name or +/// Pass Through is an error and changes nothing. +#[test] +fn bucket_mode_multiplies_clears_and_rejects_bad_names() { + for depth in [8, 16, 32] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8, "depth": depth})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + let base = json!({"x": 1, "y": 1, "antiAlias": false, "tolerance": 0}); + let with = |extra: Value| { + let mut p = base.clone(); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + p + }; + s.execute("paint.bucket", with(json!({"color": "#808080"}))).unwrap(); + s.execute("paint.bucket", with(json!({"color": "#ff0000", "mode": "multiply"}))).unwrap(); + let p = px(&s, 3, 3); + assert!((p[0] - 0.5).abs() < 0.01 && p[1] < 0.01 && p[3] > 0.99, "depth {depth}: {p:?}"); + for bad in [json!("passThrough"), json!("sparkle"), json!(3)] { + assert!(s.execute("paint.bucket", with(json!({"mode": bad}))).is_err(), "{bad}"); + } + assert_eq!(px(&s, 3, 3), p, "a refused mode paints nothing"); + s.execute("paint.bucket", with(json!({"mode": "Clear", "opacity": 50}))).unwrap(); + assert!((px(&s, 3, 3)[3] - 0.5).abs() < 0.01, "depth {depth}: half cleared"); + } +} + +#[test] +fn bucket_sample_all_layers_uses_visible_boundaries_at_all_depths() { + for depth in [8, 16, 32] { + for all in [None, Some(false), Some(true)] { + let (mut s, bottom) = bucket_layers(depth); + let before = s.active().unwrap().doc.layer(bottom).unwrap().clone(); + let mut p = json!({"x": 2, "y": 2, "color": "#ff0000", "antiAlias": false, "tolerance": 0}); + if let Some(all) = all { + p["sampleAllLayers"] = json!(all); + } + assert_eq!(s.execute("paint.bucket", p.clone()).unwrap()["filled"], true); + assert_eq!(px(&s, 5, 5), vec![1.0, 0.0, 0.0, 1.0], "depth {depth}, all {all:?}"); + let beyond = if all == Some(true) { vec![0.0; 4] } else { vec![1.0, 0.0, 0.0, 1.0] }; + assert_eq!(px(&s, 15, 5), beyond, "depth {depth}, all {all:?}: sample flag controls the boundary"); + assert_eq!(s.active().unwrap().doc.layer(bottom).unwrap(), &before, "only the active layer is written"); + if all == Some(true) { + assert_eq!(px(&s, 10, 5), vec![0.0; 4], "wall itself is untouched"); + assert!(s.undo()); + p["contiguous"] = json!(false); + s.execute("paint.bucket", p).unwrap(); + assert_eq!(px(&s, 15, 5), vec![1.0, 0.0, 0.0, 1.0], "noncontiguous finds both white regions"); + assert_eq!(px(&s, 10, 5), vec![0.0; 4]); + assert!(s.undo()); + assert_eq!(s.execute("paint.bucket", json!({"x": -1, "y": 2, "sampleAllLayers": true})).unwrap()["filled"], false); + assert_eq!(px(&s, 5, 5), vec![0.0; 4], "an off-canvas sample does not fill the layer"); + } + } + } +} + +#[test] +fn bucket_sample_all_layers_ignores_hidden_layers() { + let (mut s, _) = bucket_layers(8); + s.edit("hidden wall", |doc, active| { + let l = doc.layer_mut(active.unwrap()).unwrap(); + l.surface_mut().unwrap().fill_rect(Rect::new(4, 0, 5, 10), &[0.0, 0.0, 0.0, 1.0]); + l.visible = false; + Ok(()) + }) + .unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("paint.bucket", json!({"x": 2, "y": 2, "color": "#ff0000", "antiAlias": false, "tolerance": 0, "sampleAllLayers": true})).unwrap(); + assert_eq!(px(&s, 4, 5), vec![1.0, 0.0, 0.0, 1.0], "hidden wall does not bound the fill"); + assert_eq!(px(&s, 8, 5), vec![1.0, 0.0, 0.0, 1.0]); + assert_eq!(px(&s, 15, 5), vec![0.0; 4], "visible wall still bounds the fill"); +} + +#[test] +fn bucket_sample_all_layers_keeps_selection_opacity_and_history() { + for depth in [8, 16, 32] { + let (mut s, _) = bucket_layers(depth); + s.execute("select.rect", json!({"x": 0, "y": 2, "width": 20, "height": 6})).unwrap(); + s.edit("feather", |doc, _| { + doc.selection.as_mut().unwrap().fill_rect(Rect::new(0, 2, 4, 8), &[0.5]); + Ok(()) + }) + .unwrap(); + let selection = s.active().unwrap().doc.selection.clone(); + s.execute("paint.bucket", json!({"x": 2, "y": 5, "color": "#ff0000", "antiAlias": false, "tolerance": 0, "opacity": 50, "sampleAllLayers": true})) + .unwrap(); + let (feathered, full) = (px(&s, 2, 5), px(&s, 6, 5)); + assert!((feathered[3] - 0.25).abs() < 0.005 && (full[3] - 0.5).abs() < 0.005, "depth {depth}: selection coverage multiplies opacity"); + assert_eq!(full[..3], [1.0, 0.0, 0.0]); + assert_eq!(px(&s, 6, 1), vec![0.0; 4], "outside selection"); + assert_eq!(px(&s, 15, 5), vec![0.0; 4], "outside sampled region"); + assert_eq!(s.active().unwrap().history.undo_label(), Some("Paint Bucket")); + assert!(s.undo()); + assert_eq!(px(&s, 2, 5), vec![0.0; 4]); + assert_eq!(s.active().unwrap().doc.selection, selection); + assert!(s.redo()); + assert_eq!(px(&s, 2, 5), feathered); + assert_eq!(px(&s, 6, 5), full); + assert_eq!(s.active().unwrap().doc.selection, selection); + } +} + +#[test] +fn bucket_sample_all_layers_pattern_uses_the_same_region() { + let (mut s, _) = bucket_layers(8); + s.execute( + "paint.bucket", + json!({"x": 2, "y": 2, "contents": "pattern", "pattern": "Diagonal Lines", "antiAlias": false, "tolerance": 0, "sampleAllLayers": true}), + ) + .unwrap(); + let left: Vec = (0..10).map(|x| px(&s, x, 0)[0]).collect(); + assert!(left.iter().any(|&r| r < 0.3) && left.iter().any(|&r| r > 0.9), "pattern varies inside the region: {left:?}"); + assert_eq!(px(&s, 10, 5), vec![0.0; 4], "wall untouched"); + assert_eq!(px(&s, 15, 5), vec![0.0; 4], "region past the wall untouched"); +} + +#[test] +fn bucket_sample_all_layers_mask_and_channel_targets_keep_their_own_boundaries() { + for target in [json!("mask"), json!({"channel": 0}), json!("quickMask")] { + for all in [false, true] { + let (mut s, _) = bucket_layers(8); + match crate::channel_cmds::target_of(&json!({"target": target})) { + crate::channel_cmds::Target::Mask => { + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + } + crate::channel_cmds::Target::Alpha(_) => { + s.execute("channel.new", json!({"fill": "white"})).unwrap(); + } + crate::channel_cmds::Target::QuickMask => { + s.execute("select.editInQuickMaskMode", json!({"on": true})).unwrap(); + } + _ => panic!("expected a grayscale target"), + } + let p = json!({"x": 2, "y": 2, "color": "#000000", "antiAlias": false, "tolerance": 0, "target": target, "sampleAllLayers": all}); + s.edit("target wall", |doc, active| { + let area = doc.bounds(); + let (surf, _) = crate::channel_cmds::target_surface(doc, *active, &p).unwrap(); + surf.fill_rect(area, &[1.0]); + surf.fill_rect(Rect::new(5, 0, 6, 10), &[0.0]); + Ok(()) + }) + .unwrap(); + s.execute("paint.bucket", p.clone()).unwrap(); + let d = &s.active().unwrap().doc; + let surf = match crate::channel_cmds::target_of(&p) { + crate::channel_cmds::Target::Mask => &d.layer(s.active().unwrap().active_layer.unwrap()).unwrap().mask.as_ref().unwrap().surface, + crate::channel_cmds::Target::Alpha(i) => &d.channels[i].surface, + crate::channel_cmds::Target::QuickMask => &d.quick_mask.as_ref().unwrap().surface, + _ => panic!("expected a grayscale target"), + }; + assert_eq!(surf.sample_channel(2, 5, 0), 0.0, "{target}, all {all}: filled target"); + assert_eq!(surf.sample_channel(7, 5, 0), 1.0, "{target}, all {all}: stopped at target wall"); + assert_eq!(px(&s, 2, 5), vec![0.0; 4], "layer pixels remain untouched"); + } + } +} + +#[test] +fn bucket_fill_contiguous() { + let mut s = session(); + s.edit("wall", |doc, _| { + doc.layers[0].surface_mut().unwrap().fill_rect(Rect::new(10, 0, 11, 10), &[0.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + s.execute("paint.bucket", json!({"x": 2, "y": 2, "color": "#ff0000", "antiAlias": false})).unwrap(); + assert_eq!(px(&s, 5, 5), vec![1.0, 0.0, 0.0, 1.0]); + assert_eq!(px(&s, 15, 5), vec![1.0, 1.0, 1.0, 1.0]); + s.execute("paint.bucket", json!({"x": 2, "y": 2, "color": "#0000ff", "contiguous": false, "antiAlias": false, "tolerance": 0})).unwrap(); + assert_eq!(px(&s, 5, 5), vec![0.0, 0.0, 1.0, 1.0]); +} + +/// #4196: the Paint Bucket and Edit > Stroke write a CMYK pick as its inks into a CMYK document, +/// not as its sRGB stand-in converted back (100/0/0/0 cyan would come out as about 100/28/0/17). +#[test] +fn bucket_and_stroke_write_a_cmyk_pick_as_its_inks() { + let cyan = [1.0f32, 0.0, 0.0, 0.0]; + let mut s = session(); + s.execute("image.mode.cmyk", json!({})).unwrap(); + let rgb = photocraft_color::convert::cmyk_to_rgb(cyan).map(|c| c.clamp(0.0, 1.0)); + s.execute("tools.setColors", json!({"foreground": rgb, "foregroundCmyk": cyan})).unwrap(); + let inks_at = |s: &Session, x: i32, y: i32| -> Vec { + let st = s.active().unwrap(); + let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); + surf.read_region(Rect::new(x, y, x + 1, y + 1)).into_iter().take(4).collect() + }; + let is_cyan = |got: &[f32]| got.iter().zip(cyan).all(|(a, b)| (a - b).abs() < 0.02); + s.execute("paint.bucket", json!({"x": 2, "y": 2, "antiAlias": false})).unwrap(); + let got = inks_at(&s, 5, 5); + assert!(is_cyan(&got), "bucket: {got:?}"); + s.execute("select.all", json!({})).unwrap(); + s.execute("edit.stroke", json!({"width": 2, "location": "inside", "color": rgb})).unwrap(); + let got = inks_at(&s, 0, 5); + assert!(is_cyan(&got), "stroke: {got:?}"); +} + +#[test] +fn bucket_fills_with_a_pattern() { + // Paint Bucket with contents="pattern" flood-fills the region with a pattern, not a colour. + let mut s = session(); + s.edit("wall", |doc, _| { + doc.layers[0].surface_mut().unwrap().fill_rect(Rect::new(10, 0, 11, 10), &[0.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + s.execute("paint.bucket", json!({"x": 2, "y": 2, "contents": "pattern", "pattern": "Diagonal Lines", "antiAlias": false, "tolerance": 0})).unwrap(); + // The filled region (left of the wall) now carries the pattern's light/dark variation, + // while the wall and the region past it are untouched. + let left: Vec<[f32; 4]> = (0..10) + .map(|x| { + let p = px(&s, x, 0); + [p[0], p[1], p[2], p[3]] + }) + .collect(); + assert!(left.iter().any(|p| p[0] < 0.3) && left.iter().any(|p| p[0] > 0.9), "pattern varies in the fill: {left:?}"); + assert_eq!(px(&s, 15, 5), vec![1.0, 1.0, 1.0, 1.0], "region past the wall untouched"); +} + +#[test] +fn gradient_tool_with_selection_and_reverse() { + let mut s = session(); + s.execute("paint.gradient", json!({"from": [0, 0], "to": [20, 0], "colors": ["#000000", "#ffffff"]})).unwrap(); + assert!(px(&s, 0, 5)[0] < 0.05 && px(&s, 19, 5)[0] > 0.95); + s.execute("paint.gradient", json!({"from": [0, 0], "to": [20, 0], "colors": ["#000000", "#ffffff"], "reverse": true})).unwrap(); + assert!(px(&s, 0, 5)[0] > 0.95); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 5, "height": 10})).unwrap(); + s.execute("paint.gradient", json!({"from": [0, 0], "to": [0, 10], "colors": ["#ff0000"]})).unwrap(); + assert_eq!(px(&s, 2, 5)[..3], [1.0, 0.0, 0.0]); + assert!(px(&s, 10, 5)[1] > 0.4, "outside the selection untouched"); + assert!(s.execute("paint.gradient", json!({"from": [0, 0]})).is_err()); +} + +#[test] +fn gradient_dither_breaks_banding() { + // A flat gradient (same colour both ends) is perfectly smooth with dither off, and gains + // per-pixel noise with dither on (which breaks 8-bit banding). + let run = |dither: bool| { + let mut s = session(); + s.execute("paint.gradient", json!({"from": [0, 0], "to": [19, 0], "colors": [[0.5, 0.5, 0.5, 1.0], [0.5, 0.5, 0.5, 1.0]], "dither": dither})).unwrap(); + (0..19).map(|x| px(&s, x, 5)[0]).collect::>() + }; + let smooth = run(false); + assert!(smooth.iter().all(|&v| v == smooth[0]), "no dither: perfectly flat"); + let noisy = run(true); + assert!(noisy.windows(2).any(|w| w[0] != w[1]), "dither: per-pixel variation"); +} + +/// The two commands under test, each painting #808080 over a white document. +fn grey_fill(cmd: &str, opacity: Value) -> Value { + match cmd { + "paint.bucket" => json!({"x": 2, "y": 2, "color": "#808080", "opacity": opacity}), + _ => json!({"from": [0, 0], "to": [19, 0], "colors": ["#808080", "#808080"], "dither": false, "opacity": opacity}), + } +} + +fn white(depth: u32) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 20, "height": 10, "depth": depth, "background": "white"})).unwrap(); + s +} + +/// Issue #4167: an opacity above 100 overshot the blend (200 painted near-black on white). +#[test] +fn bucket_and_gradient_clamp_opacity_like_the_magic_eraser() { + for cmd in ["paint.bucket", "paint.gradient"] { + for depth in [8, 16, 32] { + let mut full = white(depth); + full.execute(cmd, grey_fill(cmd, json!(100))).unwrap(); + let expected = px(&full, 5, 5); + assert!((expected[0] - 128.0 / 255.0).abs() < 0.01, "{cmd} depth {depth}: 100% paints #808080, got {expected:?}"); + for over in [200.0, 1e9] { + let mut s = white(depth); + s.execute(cmd, grey_fill(cmd, json!(over))).unwrap(); + assert_eq!(px(&s, 5, 5), expected, "{cmd} depth {depth}: opacity {over} clamps to 100"); + } + let (mut low, mut one) = (white(depth), white(depth)); + low.execute(cmd, grey_fill(cmd, json!(-50))).unwrap(); + one.execute(cmd, grey_fill(cmd, json!(1))).unwrap(); + assert_eq!(px(&low, 5, 5), px(&one, 5, 5), "{cmd} depth {depth}: opacity below 1 clamps to 1"); + assert!(px(&low, 5, 5).iter().all(|v| (0.0..=1.0).contains(v)), "{cmd} depth {depth}: no overshoot"); + } + } +} + +#[test] +fn bucket_and_gradient_reject_non_numeric_opacity_without_editing() { + for cmd in ["paint.bucket", "paint.gradient"] { + for bad in [json!("50"), json!(true), json!([50]), json!({"v": 50})] { + let mut s = white(8); + let (before, steps) = (px(&s, 5, 5), s.active().unwrap().history.past_len()); + let err = s.execute(cmd, grey_fill(cmd, bad.clone())).unwrap_err(); + assert!(matches!(err, EngineError::BadParams { .. }), "{cmd} {bad}: {err:?}"); + assert_eq!(px(&s, 5, 5), before, "{cmd} {bad}: pixels unchanged"); + assert_eq!(s.active().unwrap().history.past_len(), steps, "{cmd} {bad}: no history step"); + } + // An explicit null keeps the default (100%), like the Magic Eraser. + let mut s = white(8); + s.execute(cmd, grey_fill(cmd, Value::Null)).unwrap(); + assert!((px(&s, 5, 5)[0] - 128.0 / 255.0).abs() < 0.01, "{cmd}: null opacity is 100%"); + } +} diff --git a/crates/engine/src/cmd/params.rs b/crates/engine/src/cmd/params.rs new file mode 100644 index 0000000000..0ed899c073 --- /dev/null +++ b/crates/engine/src/cmd/params.rs @@ -0,0 +1,140 @@ +use super::layer_params::layer_param; +use super::*; + +// ---------- param helpers ---------- + +pub(super) fn bad(cmd: &str, msg: impl Into) -> EngineError { + EngineError::BadParams { cmd: cmd.into(), msg: msg.into() } +} + +/// Integer parameter that also accepts JSON floats (UIs send `12.0`); rounds. +pub(crate) fn int(p: &Value, key: &str) -> Option { + p.get(key).and_then(|v| v.as_i64().or_else(|| v.as_f64().filter(|f| f.is_finite()).map(|f| f.round() as i64))) +} + +/// [`int`] narrowed to `i32` for geometry: `None` when absent, and a bad-params error when the +/// value would wrap through `as i32` — out-of-range integers truncate by multiples of 2^32, +/// which silently relocates geometry (`dx = 2^32 + 50` moves 50 px, `3e9` goes negative) +/// instead of erroring. +pub(crate) fn int_i32(cmd: &str, p: &Value, key: &str) -> Result> { + match int(p, key) { + None => Ok(None), + Some(v) => i32::try_from(v).map(Some).map_err(|_| bad(cmd, format!("`{key}` = {v} is outside the 32-bit coordinate range"))), + } +} + +/// An id (layer comp, slice, style…) from a JSON value: a bad-params error unless it is a whole +/// number in `u32` range. `as u32` would wrap `2^32 + 1` to `1` and target a real item. +pub(crate) fn u32_id(cmd: &str, key: &str, v: &Value) -> Result { + v.as_u64().and_then(|n| u32::try_from(n).ok()).ok_or_else(|| bad(cmd, format!("`{key}` = {v} is not a valid id (0..={})", u32::MAX))) +} + +/// [`u32_id`] of `p[key]`: `None` when absent. +pub(crate) fn u32_id_param(cmd: &str, p: &Value, key: &str) -> Result> { + p.get(key).map(|v| u32_id(cmd, key, v)).transpose() +} + +/// JSON numbers may be finite f64 values but overflow when stored in a document's f32 field. +pub(crate) fn finite_f32(cmd: &str, key: &str, value: f64) -> Result { + let narrowed = value as f32; + if narrowed.is_finite() { Ok(narrowed) } else { Err(bad(cmd, format!("`{key}` must fit a finite 32-bit number"))) } +} + +/// Effect/type parameters contain nested colour arrays and snapshots as well as scalars. +/// Validate before parsing or editing, including numbers hidden in an effect snapshot. +pub(crate) fn check_f32_values(cmd: &str, value: &Value) -> Result<()> { + // Bound the call stack, without allocating a work list proportional to an input array. + fn check(cmd: &str, value: &Value, depth: usize) -> Result<()> { + if depth > 64 { + return Err(bad(cmd, "parameters nested deeper than 64 levels")); + } + match value { + Value::Number(n) => { + finite_f32(cmd, "number", n.as_f64().ok_or_else(|| bad(cmd, "invalid number"))?)?; + } + Value::Array(a) => { + for v in a { + check(cmd, v, depth + 1)?; + } + } + Value::Object(o) => { + for v in o.values() { + check(cmd, v, depth + 1)?; + } + } + _ => {} + } + Ok(()) + } + check(cmd, value, 0) +} + +pub(crate) fn color_param(cmd: &str, p: &Value, key: &str, default: [f32; 4]) -> Result<[f32; 4]> { + Ok(match p.get(key) { + Some(Value::Array(a)) if a.len() >= 3 => { + let mut out = [0.0, 0.0, 0.0, 1.0]; + for (slot, value) in out.iter_mut().zip(a) { + *slot = finite_f32(cmd, key, value.as_f64().unwrap_or(0.0))?; + } + out + } + Some(Value::String(s)) => parse_hex(s).unwrap_or(default), + _ => default, + }) +} + +pub(crate) fn parse_hex(s: &str) -> Option<[f32; 4]> { + let s = s.trim_start_matches('#'); + // `from_str_radix` accepts a leading '+', so "+f" would read as 0x0f. + if !s.bytes().all(|c| c.is_ascii_hexdigit()) { + return None; + } + let b = |i: usize| u8::from_str_radix(s.get(i..i + 2)?, 16).ok().map(|v| v as f32 / 255.0); + match s.len() { + 6 => Some([b(0)?, b(2)?, b(4)?, 1.0]), + 8 => Some([b(0)?, b(2)?, b(4)?, b(6)?]), + _ => None, + } +} + +/// Layer › Create / Release Clipping Mask. With a `layer` param, just that layer. Otherwise, as in +/// Photoshop, the selection (#1248): Create clips every selected layer except the lowest, which +/// becomes the base; Release releases every selected layer. Releasing a clipped layer also +/// releases the clipped layers above it in its group, as Adobe documents ("removes the selected +/// layer and any layers above it from the clipping mask"), so none is left clipped to a layer +/// that is no longer clipped. One history step either way. +pub(super) fn set_clipped(s: &mut Session, p: &Value, clip: bool) -> Result { + let label = if clip { "Create Clipping Mask" } else { "Release Clipping Mask" }; + let ids: Vec = if p.get("layer").is_some() { + vec![layer_param(s, p)?] + } else { + let selected = s.active().ok_or(EngineError::NoDocument)?.selected_layers(); + match (clip, selected.as_slice()) { + (_, []) => vec![layer_param(s, p)?], + (_, [one]) => vec![*one], + (true, [_base, rest @ ..]) => rest.to_vec(), + (false, all) => all.to_vec(), + } + }; + let ids = if clip { + ids + } else { + let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; + let mut all = ids.clone(); + for id in ids.iter().filter(|id| doc.layer(**id).is_some_and(|l| l.clipped)) { + for above in crate::clip_group::clipped_above(doc, *id) { + if !all.contains(&above) { + all.push(above); + } + } + } + all + }; + s.edit(label, |doc, _| { + for id in &ids { + doc.layer_mut(*id).ok_or(EngineError::NoLayer(*id))?.clipped = clip; + } + Ok(()) + })?; + Ok(json!({"layers": ids.iter().map(|id| id.0).collect::>()})) +} diff --git a/crates/engine/src/path_edit_cmds.rs b/crates/engine/src/cmd/path_edit_cmds.rs similarity index 100% rename from crates/engine/src/path_edit_cmds.rs rename to crates/engine/src/cmd/path_edit_cmds.rs diff --git a/crates/engine/src/pattern_cmds.rs b/crates/engine/src/cmd/pattern_cmds.rs similarity index 100% rename from crates/engine/src/pattern_cmds.rs rename to crates/engine/src/cmd/pattern_cmds.rs diff --git a/crates/engine/src/pattern_fill_cmds.rs b/crates/engine/src/cmd/pattern_fill_cmds.rs similarity index 100% rename from crates/engine/src/pattern_fill_cmds.rs rename to crates/engine/src/cmd/pattern_fill_cmds.rs diff --git a/crates/engine/src/perspective_crop_cmds.rs b/crates/engine/src/cmd/perspective_crop_cmds.rs similarity index 100% rename from crates/engine/src/perspective_crop_cmds.rs rename to crates/engine/src/cmd/perspective_crop_cmds.rs diff --git a/crates/engine/src/photo_cmds.rs b/crates/engine/src/cmd/photo_cmds.rs similarity index 71% rename from crates/engine/src/photo_cmds.rs rename to crates/engine/src/cmd/photo_cmds.rs index a1201ecc71..2aa2a383b8 100644 --- a/crates/engine/src/photo_cmds.rs +++ b/crates/engine/src/cmd/photo_cmds.rs @@ -991,360 +991,4 @@ pub fn specs() -> Vec { } #[cfg(test)] -mod tests { - use super::*; - - /// A textured RGB scene (deterministic blobs on a gradient). - fn scene(w: usize, h: usize, seed: u64) -> Vec<[f32; 4]> { - let mut z = seed; - let mut rnd = || { - z = z.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); - (z >> 33) as f64 / (1u64 << 31) as f64 - }; - let mut px: Vec<[f32; 4]> = (0..w * h) - .map(|i| { - let x = (i % w) as f32 / w as f32; - [0.3 + 0.2 * x, 0.35, 0.4 - 0.1 * x, 1.0] - }) - .collect(); - for _ in 0..(w * h / 700) { - let (cx, cy, r) = (rnd() * w as f64, rnd() * h as f64, 3.0 + rnd() * 9.0); - let col = [rnd() as f32, rnd() as f32, rnd() as f32, 1.0]; - for y in (cy - r).max(0.0) as usize..((cy + r) as usize + 1).min(h) { - for x in (cx - r).max(0.0) as usize..((cx + r) as usize + 1).min(w) { - if (x as f64 - cx).hypot(y as f64 - cy) < r { - px[y * w + x] = col; - } - } - } - } - px - } - - fn doc_from(name: &str, px: &[[f32; 4]], w: usize, h: usize, depth: SampleType) -> Document { - let mut d = Document::new(name, Size::new(w as u32, h as u32), ColorMode::Rgb, depth); - let fmt = d.pixel_format(); - let n = fmt.channels(); - let mut data = vec![0.0f32; w * h * n]; - for (q, o) in px.iter().zip(data.chunks_exact_mut(n)) { - photocraft_raster::from_rgba_into(&fmt, *q, o); - } - let mut s = Surface::new(fmt); - s.write_region(Rect::new(0, 0, w as i32, h as i32), &data); - d.layers.push(Layer::new("Background", LayerContent::Raster(s))); - d - } - - fn crop(px: &[[f32; 4]], sw: usize, x0: usize, y0: usize, w: usize, h: usize, gain: f32) -> Vec<[f32; 4]> { - (0..w * h) - .map(|i| { - let q = px[(y0 + i / w) * sw + x0 + i % w]; - [q[0] * gain, q[1] * gain, q[2] * gain, 1.0] - }) - .collect() - } - - #[test] - fn photomerge_open_documents_reposition_and_perspective() { - for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { - let (sw, sh) = (520, 220); - let sc = scene(sw, sh, 5); - let mut s = Session::new(); - // Three overlapping crops, the middle one 15 % brighter (gain compensation). - for (k, (x0, g)) in [(0usize, 1.0f32), (130, 1.15), (260, 1.0)].into_iter().enumerate() { - s.add_document(doc_from(&format!("img{k}"), &crop(&sc, sw, x0, 10, 220, 200, g), 220, 200, depth), None); - } - let r = s.execute("file.automate.photomerge", json!({"useOpenDocuments": true, "layout": "reposition"})).unwrap(); - assert_eq!(r["placed"].as_array().unwrap().len(), 3, "{r}"); - let (w, h) = (r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()); - assert!((w as i64 - 480).abs() <= 2 && (h as i64 - 200).abs() <= 2, "{depth:?} {w}×{h}"); - let d = &s.active().unwrap().doc; - assert_eq!(d.layers.len(), 3); - assert!(d.layers.iter().all(|l| l.mask.is_some())); - // Masks partition the panorama: every covered pixel is shown by exactly one layer. - for &(x, y) in &[(20, 100), (200, 50), (380, 150), (470, 120)] { - let shown: f32 = d.layers.iter().map(|l| l.mask.as_ref().unwrap().value(x, y) * l.surface().unwrap().rgba(x, y)[3]).sum(); - assert!((shown - 1.0).abs() < 0.01, "({x},{y}) {shown}"); - } - // The composite matches the scene up to the global gain. - let comp = photocraft_compose::flatten(d); - let at = |x: i32, y: i32| comp.px[(y * comp.rect.width() as i32 + x) as usize]; - let gains = r["photometric"]["gains"].as_array().unwrap(); - assert!(gains[1][0].as_f64().unwrap() > gains[0][0].as_f64().unwrap() * 1.05, "{r}"); - let probe = at(160, 100); - let truth = sc[110 * sw + 160]; - assert!((probe[1] - truth[1]).abs() < 0.08, "{probe:?} vs {truth:?}"); - } - // Perspective + no blending: plain layers, no masks. - let (sw, sh) = (520, 220); - let sc = scene(sw, sh, 8); - let mut s = Session::new(); - for (k, x0) in [0usize, 180].into_iter().enumerate() { - s.add_document(doc_from(&format!("p{k}"), &crop(&sc, sw, x0, 10, 260, 200, 1.0), 260, 200, SampleType::U8), None); - } - let r = s.execute("file.automate.photomerge", json!({"useOpenDocuments": true, "layout": "perspective", "blend": false})).unwrap(); - assert_eq!(r["layout"], "perspective"); - let d = &s.active().unwrap().doc; - assert!(d.layers.iter().all(|l| l.mask.is_none())); - assert!((r["width"].as_i64().unwrap() - 440).abs() <= 8, "{r}"); - assert!(s.execute("file.automate.photomerge", json!({"useOpenDocuments": true, "layout": "zigzag"})).is_err()); - let mut empty = Session::new(); - assert!(empty.execute("file.automate.photomerge", json!({})).is_err()); - } - - #[test] - fn photomerge_cylindrical_with_fill() { - let (sw, sh) = (900, 260); - let sc = scene(sw, sh, 21); - let f = 260.0f64; - let mut s = Session::new(); - let (tw, th) = (260usize, 200usize); - for (k, pan) in [-0.45f64, 0.0, 0.45].into_iter().enumerate() { - let px: Vec<[f32; 4]> = (0..tw * th) - .map(|i| { - let (dx, dy) = ((i % tw) as f64 - tw as f64 / 2.0, (i / tw) as f64 - th as f64 / 2.0); - let (u, v) = (sw as f64 / 2.0 + f * (dx.atan2(f) + pan), sh as f64 / 2.0 + f * dy / dx.hypot(f)); - sc[(v.round().clamp(0.0, sh as f64 - 1.0) as usize) * sw + u.round().clamp(0.0, sw as f64 - 1.0) as usize] - }) - .collect(); - s.add_document(doc_from(&format!("c{k}"), &px, tw, th, SampleType::U8), None); - } - let r = s.execute("file.automate.photomerge", json!({"useOpenDocuments": true, "layout": "cylindrical", "contentAwareFill": true})).unwrap(); - assert_eq!(r["layout"], "cylindrical"); - assert_eq!(r["placed"].as_array().unwrap().len(), 3, "{r}"); - let d = &s.active().unwrap().doc; - let top = d.layers.last().unwrap(); - assert_eq!(top.name, "Content-Aware Fill"); - // The fill layer is opaque everywhere (the bow-tie corners are filled). - let b = d.bounds(); - assert!(top.surface().unwrap().rgba(1, 1)[3] > 0.99 && top.surface().unwrap().rgba(b.x1 - 2, b.y1 - 2)[3] > 0.99); - } - - #[test] - fn hdr_merge_from_synthetic_exposures() { - let (w, h) = (96usize, 64usize); - let radiance: Vec<[f32; 3]> = (0..w * h) - .map(|i| { - let x = (i % w) as f32 / w as f32; - let b = 0.003 * 2f32.powf(x * 11.0) * (1.0 + 0.2 * ((i / w) as f32 * 0.3).sin()); - [b, b * 0.9, b * 0.7] - }) - .collect(); - let shoot = |dt: f32| -> Vec<[f32; 4]> { - radiance - .iter() - .map(|r| { - let f = |v: f32| photocraft_algo_srgb((v * dt).min(1.0)); - [f(r[0]), f(r[1]), f(r[2]), 1.0] - }) - .collect() - }; - let mut s = Session::new(); - for (k, dt) in [0.25f32, 1.0, 4.0].into_iter().enumerate() { - let mut d = doc_from(&format!("e{k}"), &shoot(dt), w, h, SampleType::U8); - d.metadata.exif = Some(std::sync::Arc::new(exif::build(&exif::CameraInfo { - exposure_time: Some(dt as f64 / 100.0), - f_number: Some(8.0), - iso: Some(100.0), - ..Default::default() - }))); - s.add_document(d, None); - } - let r = s.execute("file.automate.mergeToHdrPro", json!({"useOpenDocuments": true})).unwrap(); - assert_eq!(r["exposureSource"], "exif"); - let ev: Vec = r["ev"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect(); - assert!((ev[1] - 2.0).abs() < 1e-6 && (ev[2] - 4.0).abs() < 1e-6, "{ev:?}"); - let d = &s.active().unwrap().doc; - assert_eq!(d.depth, SampleType::F32); - assert!(d.is_background(d.layers[0].id), "the merged layer is a real (locked) Background"); - let l = d.layers[0].surface().unwrap(); - // Linear output: ratios across the ramp follow the radiance. - let (a, b) = (l.rgba(20, 30)[1] as f64, l.rgba(80, 30)[1] as f64); - let expect = radiance[30 * w + 80][1] as f64 / radiance[30 * w + 20][1] as f64; - assert!(((b / a) / expect).ln().abs() < 0.3, "{} vs {expect}", b / a); - assert!(r["stops"].as_f64().unwrap() > 7.0, "{r}"); - let out = r["document"].as_u64().unwrap() as usize; - s.close(out); - // 8-bit tone-mapped output with explicit EVs. - for method in ["localAdaptation", "exposureGamma", "highlightCompression", "equalizeHistogram"] { - let r = s - .execute("file.automate.mergeToHdrPro", json!({"paths": [], "useOpenDocuments": true, "exposures": [0, 2, 4], "mode": "8", "method": method})) - .unwrap(); - assert_eq!(r["exposureSource"], "params"); - let d = &s.active().unwrap().doc; - assert_eq!(d.depth, SampleType::U8); - let out = r["document"].as_u64().unwrap() as usize; - s.close(out); - } - assert!(s.execute("file.automate.mergeToHdrPro", json!({"useOpenDocuments": true, "exposures": [0, 1]})).is_err()); - } - - fn photocraft_algo_srgb(v: f32) -> f32 { - if v <= 0.003_130_8 { v * 12.92 } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 } - } - - /// A light scan with one dark tilted print on it. - fn scan_with_one_photo() -> Document { - let (w, h) = (300usize, 220usize); - let mut px = vec![[0.98f32, 0.98, 0.98, 1.0]; w * h]; - let (s, co) = 5.0f64.to_radians().sin_cos(); - for y in 0..h { - for x in 0..w { - let (dx, dy) = (x as f64 + 0.5 - 150.0, y as f64 + 0.5 - 110.0); - let (u, v) = (co * dx + s * dy, -s * dx + co * dy); - if u.abs() < 80.0 && v.abs() < 55.0 { - px[y * w + x] = [0.2 + (u / 160.0) as f32 * 0.3, 0.25, 0.3, 1.0]; - } - } - } - doc_from("scan", &px, w, h, SampleType::U8) - } - - #[test] - fn crop_and_straighten_keeps_duotone_inks() { - let mut s = Session::new(); - s.add_document(scan_with_one_photo(), None); - s.execute("image.mode.grayscale", json!({})).unwrap(); - s.execute( - "image.mode.duotone", - json!({"type": "duotone", "inks": [{"name": "Black", "color": [0, 0, 0]}, {"name": "Orange", "color": [255, 128, 0]}]}), - ) - .unwrap(); - let src = s.documents()[0].doc.duotone.clone(); - assert!(src.is_some()); - let r = s.execute("file.automate.cropAndStraightenPhotos", json!({})).unwrap(); - assert_eq!(r["photos"].as_array().unwrap().len(), 1, "{r}"); - let d = &s.documents()[1].doc; - assert_eq!(d.mode, ColorMode::Duotone); - assert_eq!(d.duotone, src); - } - - #[test] - fn crop_and_straighten_disabled_for_indexed() { - // Photoshop greys the command out for Indexed Color documents. - let mut s = Session::new(); - s.add_document(scan_with_one_photo(), None); - s.execute("image.mode.indexedColor", json!({})).unwrap(); - assert_eq!(s.documents()[0].doc.mode, ColorMode::Indexed); - assert!(!s.is_enabled("file.automate.cropAndStraightenPhotos")); - assert!(s.execute("file.automate.cropAndStraightenPhotos", json!({})).is_err()); - assert_eq!(s.documents().len(), 1); - } - - #[test] - fn crop_and_straighten_only_processes_the_selection() { - // Photoshop: with a selection, only the photos inside it are split off. - let (w, h) = (480usize, 340usize); - let mut px = vec![[0.98f32, 0.98, 0.98, 1.0]; w * h]; - // Upright photos: red 160x110 at (40, 60), blue 150x120 at (290, 180). - for (x0, y0, pw, ph, c) in [(40, 60, 160, 110, [0.6f32, 0.1, 0.1, 1.0]), (290, 180, 150, 120, [0.1, 0.2, 0.6, 1.0])] { - for y in y0..y0 + ph { - px[y * w + x0..y * w + x0 + pw].fill(c); - } - } - let mut s = Session::new(); - s.add_document(doc_from("scan", &px, w, h, SampleType::U8), None); - s.execute("select.rect", json!({"x": 270, "y": 160, "width": 190, "height": 160})).unwrap(); - let r = s.execute("file.automate.cropAndStraightenPhotos", json!({})).unwrap(); - let found = r["photos"].as_array().unwrap(); - assert_eq!(found.len(), 1, "{r}"); - assert_eq!(s.documents().len(), 2); - // The reported centre is in the scan's coordinates. - let c = &found[0]["center"]; - assert!((c[0].as_f64().unwrap() - 365.0).abs() < 3.0 && (c[1].as_f64().unwrap() - 240.0).abs() < 3.0, "{c}"); - let d = &s.documents()[1].doc; - assert!((d.size.width as i64 - 150).abs() <= 4 && (d.size.height as i64 - 120).abs() <= 4, "{:?}", d.size); - let q = d.layers[0].surface().unwrap().rgba(d.size.width as i32 / 2, d.size.height as i32 / 2); - assert!(q[2] > 0.5 && q[0] < 0.2, "{q:?}"); - // Without a selection both photos are found. - s.set_active(0); - s.execute("select.deselect", json!({})).unwrap(); - let r = s.execute("file.automate.cropAndStraightenPhotos", json!({})).unwrap(); - assert_eq!(r["photos"].as_array().unwrap().len(), 2, "{r}"); - } - - #[test] - fn crop_and_straighten_skips_photos_between_selected_regions() { - // Two selected rectangles: a photo in the gap between them lies inside - // their bounding box but outside the selection, so it is not split off. - let (w, h) = (480usize, 340usize); - let mut px = vec![[0.75f32, 0.75, 0.75, 1.0]; w * h]; - // Red 160x110 at (40, 60) and blue 150x120 at (290, 180) are selected; green 130x80 at (280, 50) is not. - for (x0, y0, pw, ph, c) in - [(40, 60, 160, 110, [0.6f32, 0.1, 0.1, 1.0]), (290, 180, 150, 120, [0.1, 0.2, 0.6, 1.0]), (280, 50, 130, 80, [0.1, 0.6, 0.1, 1.0])] - { - for y in y0..y0 + ph { - px[y * w + x0..y * w + x0 + pw].fill(c); - } - } - let mut s = Session::new(); - s.add_document(doc_from("scan", &px, w, h, SampleType::U8), None); - s.execute("select.rect", json!({"x": 20, "y": 40, "width": 200, "height": 150})).unwrap(); - s.execute("select.rect", json!({"x": 270, "y": 160, "width": 190, "height": 160, "mode": "add"})).unwrap(); - let r = s.execute("file.automate.cropAndStraightenPhotos", json!({})).unwrap(); - let found = r["photos"].as_array().unwrap(); - assert_eq!(found.len(), 2, "{r}"); - for f in found { - let c = &f["center"]; - let (cx, cy) = (c[0].as_f64().unwrap(), c[1].as_f64().unwrap()); - let near = |x: f64, y: f64| (cx - x).abs() < 3.0 && (cy - y).abs() < 3.0; - assert!(near(120.0, 115.0) || near(365.0, 240.0), "{c}"); - } - } - - #[test] - fn crop_and_straighten_refuses_a_selection_under_half_coverage() { - // A faint (strongly feathered) selection has no pixel at or above 50%: - // like Photoshop, nothing counts as selected, so no photo is split off - // from the unmasked bounding box. - let (w, h) = (480usize, 340usize); - let mut px = vec![[0.98f32, 0.98, 0.98, 1.0]; w * h]; - for y in 180..300 { - px[y * w + 290..y * w + 440].fill([0.1, 0.2, 0.6, 1.0]); - } - let mut s = Session::new(); - s.add_document(doc_from("scan", &px, w, h, SampleType::U8), None); - let mut m = Surface::new(photocraft_color::PixelFormat::GRAY8); - m.fill_rect(Rect::new(270, 160, 460, 320), &[0.3]); - std::sync::Arc::make_mut(&mut s.active_mut().unwrap().doc).selection = Some(m); - let e = s.execute("file.automate.cropAndStraightenPhotos", json!({})).unwrap_err(); - assert!(e.to_string().contains("50%"), "{e}"); - assert_eq!(s.documents().len(), 1); - } - - #[test] - fn crop_and_straighten_makes_documents() { - let (w, h) = (500usize, 360usize); - let mut px = vec![[0.98f32, 0.98, 0.98, 1.0]; w * h]; - let photos = [([140.0f64, 120.0f64], 160.0f64, 110.0f64, 6.0f64), ([360.0, 240.0], 150.0, 120.0, -9.0)]; - for (c, pw, ph, ang) in photos { - let (s, co) = ang.to_radians().sin_cos(); - for y in 0..h { - for x in 0..w { - let (dx, dy) = (x as f64 + 0.5 - c[0], y as f64 + 0.5 - c[1]); - let (u, v) = (co * dx + s * dy, -s * dx + co * dy); - if u.abs() < pw / 2.0 && v.abs() < ph / 2.0 { - px[y * w + x] = [0.2 + (u / pw) as f32 * 0.3, 0.3, 0.6, 1.0]; - } - } - } - } - let mut s = Session::new(); - s.add_document(doc_from("scan", &px, w, h, SampleType::U16), None); - assert!(s.is_enabled("file.automate.cropAndStraightenPhotos")); - let r = s.execute("file.automate.cropAndStraightenPhotos", json!({})).unwrap(); - let found = r["photos"].as_array().unwrap(); - assert_eq!(found.len(), 2, "{r}"); - assert_eq!(s.documents().len(), 3); - assert!((found[0]["angle"].as_f64().unwrap() - 6.0).abs() < 1.0); - let d = &s.documents()[1].doc; - assert!((d.size.width as i64 - 158).abs() <= 4 && (d.size.height as i64 - 108).abs() <= 4, "{:?}", d.size); - assert_eq!(d.depth, SampleType::U16); - // Upright: the photo's horizontal gradient runs along x. - let l = d.layers[0].surface().unwrap(); - let (a, b) = (l.rgba(10, d.size.height as i32 / 2)[0], l.rgba(d.size.width as i32 - 10, d.size.height as i32 / 2)[0]); - assert!(b > a + 0.15, "{a} {b}"); - let (c, e) = (l.rgba(d.size.width as i32 / 2, 6)[0], l.rgba(d.size.width as i32 / 2, d.size.height as i32 - 6)[0]); - assert!((c - e).abs() < 0.05); - } -} +mod tests; diff --git a/crates/engine/src/cmd/photo_cmds/tests.rs b/crates/engine/src/cmd/photo_cmds/tests.rs new file mode 100644 index 0000000000..8d0152a986 --- /dev/null +++ b/crates/engine/src/cmd/photo_cmds/tests.rs @@ -0,0 +1,352 @@ +use super::*; + +/// A textured RGB scene (deterministic blobs on a gradient). +fn scene(w: usize, h: usize, seed: u64) -> Vec<[f32; 4]> { + let mut z = seed; + let mut rnd = || { + z = z.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (z >> 33) as f64 / (1u64 << 31) as f64 + }; + let mut px: Vec<[f32; 4]> = (0..w * h) + .map(|i| { + let x = (i % w) as f32 / w as f32; + [0.3 + 0.2 * x, 0.35, 0.4 - 0.1 * x, 1.0] + }) + .collect(); + for _ in 0..(w * h / 700) { + let (cx, cy, r) = (rnd() * w as f64, rnd() * h as f64, 3.0 + rnd() * 9.0); + let col = [rnd() as f32, rnd() as f32, rnd() as f32, 1.0]; + for y in (cy - r).max(0.0) as usize..((cy + r) as usize + 1).min(h) { + for x in (cx - r).max(0.0) as usize..((cx + r) as usize + 1).min(w) { + if (x as f64 - cx).hypot(y as f64 - cy) < r { + px[y * w + x] = col; + } + } + } + } + px +} + +fn doc_from(name: &str, px: &[[f32; 4]], w: usize, h: usize, depth: SampleType) -> Document { + let mut d = Document::new(name, Size::new(w as u32, h as u32), ColorMode::Rgb, depth); + let fmt = d.pixel_format(); + let n = fmt.channels(); + let mut data = vec![0.0f32; w * h * n]; + for (q, o) in px.iter().zip(data.chunks_exact_mut(n)) { + photocraft_raster::from_rgba_into(&fmt, *q, o); + } + let mut s = Surface::new(fmt); + s.write_region(Rect::new(0, 0, w as i32, h as i32), &data); + d.layers.push(Layer::new("Background", LayerContent::Raster(s))); + d +} + +fn crop(px: &[[f32; 4]], sw: usize, x0: usize, y0: usize, w: usize, h: usize, gain: f32) -> Vec<[f32; 4]> { + (0..w * h) + .map(|i| { + let q = px[(y0 + i / w) * sw + x0 + i % w]; + [q[0] * gain, q[1] * gain, q[2] * gain, 1.0] + }) + .collect() +} + +#[test] +fn photomerge_open_documents_reposition_and_perspective() { + for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + let (sw, sh) = (520, 220); + let sc = scene(sw, sh, 5); + let mut s = Session::new(); + // Three overlapping crops, the middle one 15 % brighter (gain compensation). + for (k, (x0, g)) in [(0usize, 1.0f32), (130, 1.15), (260, 1.0)].into_iter().enumerate() { + s.add_document(doc_from(&format!("img{k}"), &crop(&sc, sw, x0, 10, 220, 200, g), 220, 200, depth), None); + } + let r = s.execute("file.automate.photomerge", json!({"useOpenDocuments": true, "layout": "reposition"})).unwrap(); + assert_eq!(r["placed"].as_array().unwrap().len(), 3, "{r}"); + let (w, h) = (r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()); + assert!((w as i64 - 480).abs() <= 2 && (h as i64 - 200).abs() <= 2, "{depth:?} {w}×{h}"); + let d = &s.active().unwrap().doc; + assert_eq!(d.layers.len(), 3); + assert!(d.layers.iter().all(|l| l.mask.is_some())); + // Masks partition the panorama: every covered pixel is shown by exactly one layer. + for &(x, y) in &[(20, 100), (200, 50), (380, 150), (470, 120)] { + let shown: f32 = d.layers.iter().map(|l| l.mask.as_ref().unwrap().value(x, y) * l.surface().unwrap().rgba(x, y)[3]).sum(); + assert!((shown - 1.0).abs() < 0.01, "({x},{y}) {shown}"); + } + // The composite matches the scene up to the global gain. + let comp = photocraft_compose::flatten(d); + let at = |x: i32, y: i32| comp.px[(y * comp.rect.width() as i32 + x) as usize]; + let gains = r["photometric"]["gains"].as_array().unwrap(); + assert!(gains[1][0].as_f64().unwrap() > gains[0][0].as_f64().unwrap() * 1.05, "{r}"); + let probe = at(160, 100); + let truth = sc[110 * sw + 160]; + assert!((probe[1] - truth[1]).abs() < 0.08, "{probe:?} vs {truth:?}"); + } + // Perspective + no blending: plain layers, no masks. + let (sw, sh) = (520, 220); + let sc = scene(sw, sh, 8); + let mut s = Session::new(); + for (k, x0) in [0usize, 180].into_iter().enumerate() { + s.add_document(doc_from(&format!("p{k}"), &crop(&sc, sw, x0, 10, 260, 200, 1.0), 260, 200, SampleType::U8), None); + } + let r = s.execute("file.automate.photomerge", json!({"useOpenDocuments": true, "layout": "perspective", "blend": false})).unwrap(); + assert_eq!(r["layout"], "perspective"); + let d = &s.active().unwrap().doc; + assert!(d.layers.iter().all(|l| l.mask.is_none())); + assert!((r["width"].as_i64().unwrap() - 440).abs() <= 8, "{r}"); + assert!(s.execute("file.automate.photomerge", json!({"useOpenDocuments": true, "layout": "zigzag"})).is_err()); + let mut empty = Session::new(); + assert!(empty.execute("file.automate.photomerge", json!({})).is_err()); +} + +#[test] +fn photomerge_cylindrical_with_fill() { + let (sw, sh) = (900, 260); + let sc = scene(sw, sh, 21); + let f = 260.0f64; + let mut s = Session::new(); + let (tw, th) = (260usize, 200usize); + for (k, pan) in [-0.45f64, 0.0, 0.45].into_iter().enumerate() { + let px: Vec<[f32; 4]> = (0..tw * th) + .map(|i| { + let (dx, dy) = ((i % tw) as f64 - tw as f64 / 2.0, (i / tw) as f64 - th as f64 / 2.0); + let (u, v) = (sw as f64 / 2.0 + f * (dx.atan2(f) + pan), sh as f64 / 2.0 + f * dy / dx.hypot(f)); + sc[(v.round().clamp(0.0, sh as f64 - 1.0) as usize) * sw + u.round().clamp(0.0, sw as f64 - 1.0) as usize] + }) + .collect(); + s.add_document(doc_from(&format!("c{k}"), &px, tw, th, SampleType::U8), None); + } + let r = s.execute("file.automate.photomerge", json!({"useOpenDocuments": true, "layout": "cylindrical", "contentAwareFill": true})).unwrap(); + assert_eq!(r["layout"], "cylindrical"); + assert_eq!(r["placed"].as_array().unwrap().len(), 3, "{r}"); + let d = &s.active().unwrap().doc; + let top = d.layers.last().unwrap(); + assert_eq!(top.name, "Content-Aware Fill"); + // The fill layer is opaque everywhere (the bow-tie corners are filled). + let b = d.bounds(); + assert!(top.surface().unwrap().rgba(1, 1)[3] > 0.99 && top.surface().unwrap().rgba(b.x1 - 2, b.y1 - 2)[3] > 0.99); +} + +#[test] +fn hdr_merge_from_synthetic_exposures() { + let (w, h) = (96usize, 64usize); + let radiance: Vec<[f32; 3]> = (0..w * h) + .map(|i| { + let x = (i % w) as f32 / w as f32; + let b = 0.003 * 2f32.powf(x * 11.0) * (1.0 + 0.2 * ((i / w) as f32 * 0.3).sin()); + [b, b * 0.9, b * 0.7] + }) + .collect(); + let shoot = |dt: f32| -> Vec<[f32; 4]> { + radiance + .iter() + .map(|r| { + let f = |v: f32| photocraft_algo_srgb((v * dt).min(1.0)); + [f(r[0]), f(r[1]), f(r[2]), 1.0] + }) + .collect() + }; + let mut s = Session::new(); + for (k, dt) in [0.25f32, 1.0, 4.0].into_iter().enumerate() { + let mut d = doc_from(&format!("e{k}"), &shoot(dt), w, h, SampleType::U8); + d.metadata.exif = Some(std::sync::Arc::new(exif::build(&exif::CameraInfo { + exposure_time: Some(dt as f64 / 100.0), + f_number: Some(8.0), + iso: Some(100.0), + ..Default::default() + }))); + s.add_document(d, None); + } + let r = s.execute("file.automate.mergeToHdrPro", json!({"useOpenDocuments": true})).unwrap(); + assert_eq!(r["exposureSource"], "exif"); + let ev: Vec = r["ev"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect(); + assert!((ev[1] - 2.0).abs() < 1e-6 && (ev[2] - 4.0).abs() < 1e-6, "{ev:?}"); + let d = &s.active().unwrap().doc; + assert_eq!(d.depth, SampleType::F32); + assert!(d.is_background(d.layers[0].id), "the merged layer is a real (locked) Background"); + let l = d.layers[0].surface().unwrap(); + // Linear output: ratios across the ramp follow the radiance. + let (a, b) = (l.rgba(20, 30)[1] as f64, l.rgba(80, 30)[1] as f64); + let expect = radiance[30 * w + 80][1] as f64 / radiance[30 * w + 20][1] as f64; + assert!(((b / a) / expect).ln().abs() < 0.3, "{} vs {expect}", b / a); + assert!(r["stops"].as_f64().unwrap() > 7.0, "{r}"); + let out = r["document"].as_u64().unwrap() as usize; + s.close(out); + // 8-bit tone-mapped output with explicit EVs. + for method in ["localAdaptation", "exposureGamma", "highlightCompression", "equalizeHistogram"] { + let r = s + .execute("file.automate.mergeToHdrPro", json!({"paths": [], "useOpenDocuments": true, "exposures": [0, 2, 4], "mode": "8", "method": method})) + .unwrap(); + assert_eq!(r["exposureSource"], "params"); + let d = &s.active().unwrap().doc; + assert_eq!(d.depth, SampleType::U8); + let out = r["document"].as_u64().unwrap() as usize; + s.close(out); + } + assert!(s.execute("file.automate.mergeToHdrPro", json!({"useOpenDocuments": true, "exposures": [0, 1]})).is_err()); +} + +fn photocraft_algo_srgb(v: f32) -> f32 { + if v <= 0.003_130_8 { v * 12.92 } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 } +} + +/// A light scan with one dark tilted print on it. +fn scan_with_one_photo() -> Document { + let (w, h) = (300usize, 220usize); + let mut px = vec![[0.98f32, 0.98, 0.98, 1.0]; w * h]; + let (s, co) = 5.0f64.to_radians().sin_cos(); + for y in 0..h { + for x in 0..w { + let (dx, dy) = (x as f64 + 0.5 - 150.0, y as f64 + 0.5 - 110.0); + let (u, v) = (co * dx + s * dy, -s * dx + co * dy); + if u.abs() < 80.0 && v.abs() < 55.0 { + px[y * w + x] = [0.2 + (u / 160.0) as f32 * 0.3, 0.25, 0.3, 1.0]; + } + } + } + doc_from("scan", &px, w, h, SampleType::U8) +} + +#[test] +fn crop_and_straighten_keeps_duotone_inks() { + let mut s = Session::new(); + s.add_document(scan_with_one_photo(), None); + s.execute("image.mode.grayscale", json!({})).unwrap(); + s.execute("image.mode.duotone", json!({"type": "duotone", "inks": [{"name": "Black", "color": [0, 0, 0]}, {"name": "Orange", "color": [255, 128, 0]}]})) + .unwrap(); + let src = s.documents()[0].doc.duotone.clone(); + assert!(src.is_some()); + let r = s.execute("file.automate.cropAndStraightenPhotos", json!({})).unwrap(); + assert_eq!(r["photos"].as_array().unwrap().len(), 1, "{r}"); + let d = &s.documents()[1].doc; + assert_eq!(d.mode, ColorMode::Duotone); + assert_eq!(d.duotone, src); +} + +#[test] +fn crop_and_straighten_disabled_for_indexed() { + // Photoshop greys the command out for Indexed Color documents. + let mut s = Session::new(); + s.add_document(scan_with_one_photo(), None); + s.execute("image.mode.indexedColor", json!({})).unwrap(); + assert_eq!(s.documents()[0].doc.mode, ColorMode::Indexed); + assert!(!s.is_enabled("file.automate.cropAndStraightenPhotos")); + assert!(s.execute("file.automate.cropAndStraightenPhotos", json!({})).is_err()); + assert_eq!(s.documents().len(), 1); +} + +#[test] +fn crop_and_straighten_only_processes_the_selection() { + // Photoshop: with a selection, only the photos inside it are split off. + let (w, h) = (480usize, 340usize); + let mut px = vec![[0.98f32, 0.98, 0.98, 1.0]; w * h]; + // Upright photos: red 160x110 at (40, 60), blue 150x120 at (290, 180). + for (x0, y0, pw, ph, c) in [(40, 60, 160, 110, [0.6f32, 0.1, 0.1, 1.0]), (290, 180, 150, 120, [0.1, 0.2, 0.6, 1.0])] { + for y in y0..y0 + ph { + px[y * w + x0..y * w + x0 + pw].fill(c); + } + } + let mut s = Session::new(); + s.add_document(doc_from("scan", &px, w, h, SampleType::U8), None); + s.execute("select.rect", json!({"x": 270, "y": 160, "width": 190, "height": 160})).unwrap(); + let r = s.execute("file.automate.cropAndStraightenPhotos", json!({})).unwrap(); + let found = r["photos"].as_array().unwrap(); + assert_eq!(found.len(), 1, "{r}"); + assert_eq!(s.documents().len(), 2); + // The reported centre is in the scan's coordinates. + let c = &found[0]["center"]; + assert!((c[0].as_f64().unwrap() - 365.0).abs() < 3.0 && (c[1].as_f64().unwrap() - 240.0).abs() < 3.0, "{c}"); + let d = &s.documents()[1].doc; + assert!((d.size.width as i64 - 150).abs() <= 4 && (d.size.height as i64 - 120).abs() <= 4, "{:?}", d.size); + let q = d.layers[0].surface().unwrap().rgba(d.size.width as i32 / 2, d.size.height as i32 / 2); + assert!(q[2] > 0.5 && q[0] < 0.2, "{q:?}"); + // Without a selection both photos are found. + s.set_active(0); + s.execute("select.deselect", json!({})).unwrap(); + let r = s.execute("file.automate.cropAndStraightenPhotos", json!({})).unwrap(); + assert_eq!(r["photos"].as_array().unwrap().len(), 2, "{r}"); +} + +#[test] +fn crop_and_straighten_skips_photos_between_selected_regions() { + // Two selected rectangles: a photo in the gap between them lies inside + // their bounding box but outside the selection, so it is not split off. + let (w, h) = (480usize, 340usize); + let mut px = vec![[0.75f32, 0.75, 0.75, 1.0]; w * h]; + // Red 160x110 at (40, 60) and blue 150x120 at (290, 180) are selected; green 130x80 at (280, 50) is not. + for (x0, y0, pw, ph, c) in + [(40, 60, 160, 110, [0.6f32, 0.1, 0.1, 1.0]), (290, 180, 150, 120, [0.1, 0.2, 0.6, 1.0]), (280, 50, 130, 80, [0.1, 0.6, 0.1, 1.0])] + { + for y in y0..y0 + ph { + px[y * w + x0..y * w + x0 + pw].fill(c); + } + } + let mut s = Session::new(); + s.add_document(doc_from("scan", &px, w, h, SampleType::U8), None); + s.execute("select.rect", json!({"x": 20, "y": 40, "width": 200, "height": 150})).unwrap(); + s.execute("select.rect", json!({"x": 270, "y": 160, "width": 190, "height": 160, "mode": "add"})).unwrap(); + let r = s.execute("file.automate.cropAndStraightenPhotos", json!({})).unwrap(); + let found = r["photos"].as_array().unwrap(); + assert_eq!(found.len(), 2, "{r}"); + for f in found { + let c = &f["center"]; + let (cx, cy) = (c[0].as_f64().unwrap(), c[1].as_f64().unwrap()); + let near = |x: f64, y: f64| (cx - x).abs() < 3.0 && (cy - y).abs() < 3.0; + assert!(near(120.0, 115.0) || near(365.0, 240.0), "{c}"); + } +} + +#[test] +fn crop_and_straighten_refuses_a_selection_under_half_coverage() { + // A faint (strongly feathered) selection has no pixel at or above 50%: + // like Photoshop, nothing counts as selected, so no photo is split off + // from the unmasked bounding box. + let (w, h) = (480usize, 340usize); + let mut px = vec![[0.98f32, 0.98, 0.98, 1.0]; w * h]; + for y in 180..300 { + px[y * w + 290..y * w + 440].fill([0.1, 0.2, 0.6, 1.0]); + } + let mut s = Session::new(); + s.add_document(doc_from("scan", &px, w, h, SampleType::U8), None); + let mut m = Surface::new(photocraft_color::PixelFormat::GRAY8); + m.fill_rect(Rect::new(270, 160, 460, 320), &[0.3]); + std::sync::Arc::make_mut(&mut s.active_mut().unwrap().doc).selection = Some(m); + let e = s.execute("file.automate.cropAndStraightenPhotos", json!({})).unwrap_err(); + assert!(e.to_string().contains("50%"), "{e}"); + assert_eq!(s.documents().len(), 1); +} + +#[test] +fn crop_and_straighten_makes_documents() { + let (w, h) = (500usize, 360usize); + let mut px = vec![[0.98f32, 0.98, 0.98, 1.0]; w * h]; + let photos = [([140.0f64, 120.0f64], 160.0f64, 110.0f64, 6.0f64), ([360.0, 240.0], 150.0, 120.0, -9.0)]; + for (c, pw, ph, ang) in photos { + let (s, co) = ang.to_radians().sin_cos(); + for y in 0..h { + for x in 0..w { + let (dx, dy) = (x as f64 + 0.5 - c[0], y as f64 + 0.5 - c[1]); + let (u, v) = (co * dx + s * dy, -s * dx + co * dy); + if u.abs() < pw / 2.0 && v.abs() < ph / 2.0 { + px[y * w + x] = [0.2 + (u / pw) as f32 * 0.3, 0.3, 0.6, 1.0]; + } + } + } + } + let mut s = Session::new(); + s.add_document(doc_from("scan", &px, w, h, SampleType::U16), None); + assert!(s.is_enabled("file.automate.cropAndStraightenPhotos")); + let r = s.execute("file.automate.cropAndStraightenPhotos", json!({})).unwrap(); + let found = r["photos"].as_array().unwrap(); + assert_eq!(found.len(), 2, "{r}"); + assert_eq!(s.documents().len(), 3); + assert!((found[0]["angle"].as_f64().unwrap() - 6.0).abs() < 1.0); + let d = &s.documents()[1].doc; + assert!((d.size.width as i64 - 158).abs() <= 4 && (d.size.height as i64 - 108).abs() <= 4, "{:?}", d.size); + assert_eq!(d.depth, SampleType::U16); + // Upright: the photo's horizontal gradient runs along x. + let l = d.layers[0].surface().unwrap(); + let (a, b) = (l.rgba(10, d.size.height as i32 / 2)[0], l.rgba(d.size.width as i32 - 10, d.size.height as i32 / 2)[0]); + assert!(b > a + 0.15, "{a} {b}"); + let (c, e) = (l.rgba(d.size.width as i32 / 2, 6)[0], l.rgba(d.size.width as i32 / 2, d.size.height as i32 - 6)[0]); + assert!((c - e).abs() < 0.05); +} diff --git a/crates/engine/src/pick_cmds.rs b/crates/engine/src/cmd/pick_cmds.rs similarity index 100% rename from crates/engine/src/pick_cmds.rs rename to crates/engine/src/cmd/pick_cmds.rs diff --git a/crates/engine/src/plugin_cmds.rs b/crates/engine/src/cmd/plugin_cmds.rs similarity index 100% rename from crates/engine/src/plugin_cmds.rs rename to crates/engine/src/cmd/plugin_cmds.rs diff --git a/crates/engine/src/plugin_cmds/tests.rs b/crates/engine/src/cmd/plugin_cmds/tests.rs similarity index 99% rename from crates/engine/src/plugin_cmds/tests.rs rename to crates/engine/src/cmd/plugin_cmds/tests.rs index 7c6ed635aa..5f93ce7909 100644 --- a/crates/engine/src/plugin_cmds/tests.rs +++ b/crates/engine/src/cmd/plugin_cmds/tests.rs @@ -2,7 +2,7 @@ use super::*; use photocraft_geom::Rect; /// The example Invert plug-in, built from `examples/plugins/invert-rs`. -const INVERT: &[u8] = include_bytes!("../../../plugins/tests/fixtures/invert.wasm"); +const INVERT: &[u8] = include_bytes!("../../../../plugins/tests/fixtures/invert.wasm"); const INVERT_ID: &str = "org.photocraft.example.invert"; fn b64(b: &[u8]) -> String { diff --git a/crates/engine/src/preset_import_cmds.rs b/crates/engine/src/cmd/preset_import_cmds.rs similarity index 100% rename from crates/engine/src/preset_import_cmds.rs rename to crates/engine/src/cmd/preset_import_cmds.rs diff --git a/crates/engine/src/print_cmds.rs b/crates/engine/src/cmd/print_cmds.rs similarity index 100% rename from crates/engine/src/print_cmds.rs rename to crates/engine/src/cmd/print_cmds.rs diff --git a/crates/engine/src/print_cmds/tests.rs b/crates/engine/src/cmd/print_cmds/tests.rs similarity index 99% rename from crates/engine/src/print_cmds/tests.rs rename to crates/engine/src/cmd/print_cmds/tests.rs index c4c211d16e..ab2e104a48 100644 --- a/crates/engine/src/print_cmds/tests.rs +++ b/crates/engine/src/cmd/print_cmds/tests.rs @@ -646,7 +646,7 @@ fn spool_transport_streams_pdf_and_propagates_refusal() { ).unwrap(); std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o700)).unwrap(); let result = std::process::Command::new(std::env::current_exe().unwrap()) - .args(["--exact", "print_cmds::tests::spool_transport_streams_pdf_and_propagates_refusal", "--nocapture"]) + .args(["--exact", "cmd::print_cmds::tests::spool_transport_streams_pdf_and_propagates_refusal", "--nocapture"]) .env(CHILD, dir.path()) .env("PATH", dir.path()) // The child spools into the fake `lp` above, so a shell that blocks real printing @@ -737,7 +737,7 @@ fn recording_spooler(preferred: bool, seen: &std::sync::Arc) -> EngineError { + EngineError::BadParams { cmd: cmd.into(), msg: msg.into() } +} + +/// A single stroke's accumulated coverage must stay at or under this many pixels (8192², so a +/// stroke corner to corner across a 24–36 MP canvas fits). Larger footprints return an error +/// instead of allocating. +const MAX_STROKE_PIXELS: u64 = 67_108_864; + +/// Refuse a stroke whose footprint would not fit the coverage budget, from the points and brush +/// size alone, before the renderer allocates anything for it. +fn reject_huge_stroke(cmd: &str, stroke: &Stroke) -> Result<()> { + // Dynamics place dabs beyond the input points, so half the tip is not the whole reach: + // Scattering offsets a centre by up to its amount times the tip size, and a Dual Brush dab + // reaches its own radius further. Pad by what those can add so this estimate does not fall + // short of what the renderer will cover. It is only the cheap early-out; the rendered extent + // is admitted for real in `coverage` below. + let b = &stroke.brush; + let size = f64::from(b.size.max(1.0)); + let scatter = if b.scattering.enabled { size * f64::from(b.scattering.scatter.jitter.max(0.0)) } else { 0.0 }; + let dual = if b.dual_brush.enabled { f64::from(b.dual_brush.size.max(0.0)) * 0.5 } else { 0.0 }; + let pad = size.mul_add(0.5, 4.0) + scatter + dual; + let mut min_x = f64::INFINITY; + let mut min_y = f64::INFINITY; + let mut max_x = f64::NEG_INFINITY; + let mut max_y = f64::NEG_INFINITY; + for q in &stroke.points { + min_x = min_x.min(q.x); + min_y = min_y.min(q.y); + max_x = max_x.max(q.x); + max_y = max_y.max(q.y); + } + if !min_x.is_finite() || !min_y.is_finite() || !max_x.is_finite() || !max_y.is_finite() { + return Err(bad(cmd, "point coordinates must be finite")); + } + let w = (max_x - min_x + pad * 2.0).ceil().max(1.0); + let h = (max_y - min_y + pad * 2.0).ceil().max(1.0); + if !w.is_finite() || !h.is_finite() || w > 1.0e9 || h > 1.0e9 { + return Err(bad(cmd, format!("stroke too large (at most {MAX_STROKE_PIXELS} px)"))); + } + let area = (w as u64).saturating_mul(h as u64); + if area > MAX_STROKE_PIXELS { + return Err(bad(cmd, format!("stroke too large ({w:.0}×{h:.0} px, at most {MAX_STROKE_PIXELS})"))); + } + Ok(()) +} + +/// The stroke's coverage, with the **rendered** extent admitted before the dense buffer exists. +/// +/// `reject_huge_stroke` estimates from the input points; this is the real bound. Rendering is +/// tiled, so it holds only the tiles the dabs touch; the extent is read from those tiles once +/// every dab is placed (tips, dynamics and scattering included) and checked against `max`, and +/// only a stroke that fits is made dense. `max` is a parameter so tests can inject a small budget. +fn coverage_within(cmd: &str, stroke: &Stroke, max: u64) -> Result<(Rect, Vec)> { + photocraft_paint::retouch::stroke_coverage_within(stroke, max).ok_or_else(|| bad(cmd, format!("stroke too large (at most {max} px)"))) +} + +/// [`coverage_within`] at the shared allowance. +fn coverage(cmd: &str, stroke: &Stroke) -> Result<(Rect, Vec)> { + coverage_within(cmd, stroke, MAX_STROKE_PIXELS) +} + +/// A pixel layer, a layer with a mask, or a targeted alpha channel / Quick Mask (as the Brush). +fn has_pixel_layer(s: &Session) -> std::result::Result<(), String> { + if crate::channel_cmds::edits_channel(s) { + return Ok(()); + } + let d = s.active().ok_or("no document open")?; + let l = d.active_layer.and_then(|id| d.doc.layer(id)).ok_or("no active layer")?; + if matches!(l.content, LayerContent::Raster(_)) || l.mask.is_some() { + Ok(()) + } else { + Err(format!("active layer is {} {} layer, not a pixel layer", l.content.article(), l.content.kind_name())) + } +} + +/// The stroke paints layer pixels (not a mask or channel), so other layers can be sampled. +fn targets_pixels(p: &Value) -> bool { + crate::channel_cmds::target_of(p) == crate::channel_cmds::Target::Pixels +} + +fn num(p: &Value, k: &str, d: f32) -> f32 { + p.get(k).and_then(Value::as_f64).map_or(d, |v| v as f32) +} +fn flag(p: &Value, k: &str, d: bool) -> bool { + p.get(k).and_then(Value::as_bool).unwrap_or(d) +} +fn string<'a>(p: &'a Value, k: &str, d: &'a str) -> &'a str { + p.get(k).and_then(Value::as_str).unwrap_or(d) +} +fn point(p: &Value, k: &str) -> Option<(f64, f64)> { + let a = p.get(k)?.as_array()?; + Some((a.first()?.as_f64()?, a.get(1)?.as_f64()?)) +} + +/// The brush a retouching stroke paints with: the tool's brush (`base`, its tip, hardness and +/// shape dynamics) with the shared params of `p` applied. UI previews of a stroke (the Spot Healing +/// Brush's trail) render their coverage with it, so they match what the command changes. +pub fn stroke_brush(base: &BrushSettings, p: &Value) -> BrushSettings { + let pct = |k: &str, d: f32, lo: f32, hi: f32| num(p, k, d).clamp(lo, hi) / 100.0; + BrushSettings { + size: num(p, "size", base.size).max(1.0), + hardness: pct("hardness", base.hardness * 100.0, 0.0, 100.0), + opacity: pct("opacity", 100.0, 1.0, 100.0), + flow: pct("flow", 100.0, 1.0, 100.0), + // Brush Settings › Brush Tip Shape › Spacing, as the Brush uses it (#2140). + spacing: pct("spacing", base.spacing * 100.0, 1.0, 1000.0), + erase: false, + ..base.clone() + } +} + +/// Parse the shared brush params into a stroke on a layer (`None` when an alpha channel or the +/// Quick Mask is targeted). +fn parse_brush(s: &Session, p: &Value, cmd: &str) -> Result<(Stroke, Option)> { + let pts: Vec = p + .get("points") + .and_then(Value::as_array) + .ok_or_else(|| bad(cmd, "missing `points`"))? + .iter() + .filter_map(|v| { + let a = v.as_array()?; + Some(StrokePoint::new(a.first()?.as_f64()?, a.get(1)?.as_f64()?, a.get(2).and_then(Value::as_f64).unwrap_or(1.0) as f32)) + }) + .collect(); + if pts.is_empty() { + return Err(bad(cmd, "`points` is empty")); + } + crate::brush_cmds::check_coords(&pts, cmd)?; + let brush = stroke_brush(&s.tools.brush, p); + crate::brush_cmds::validate_brush(&brush, cmd)?; + if crate::channel_cmds::is_channel_target(p) { + return Ok((Stroke { brush, points: pts }, None)); + } + let id = match p.get("layer").and_then(Value::as_u64) { + Some(id) => LayerId(id), + None => s.active().and_then(|d| d.active_layer).ok_or(EngineError::Other("no active layer".into()))?, + }; + Ok((Stroke { brush, points: pts }, Some(id))) +} + +/// Run `f` on the targeted surface (layer pixels, layer mask, alpha channel or Quick Mask: the +/// Brush's paint target) inside one undoable step. `f` gets the pre-stroke document (a cheap +/// copy-on-write snapshot), the surface, the selection and the transparency lock. +fn run_stroke( + s: &mut Session, + label: &str, + id: Option, + p: &Value, + f: impl FnOnce(&Document, &mut Surface, Option<&Surface>, bool) -> Result, +) -> Result { + let dmg = s.edit(label, |doc, _| { + let pre = doc.clone(); + let (surf, lock) = crate::channel_cmds::target_surface(doc, id, p)?; + // No prune: retouching only rewrites pixels inside the stroke, and scanning every tile of a + // large layer would dominate the cost of a dab. + f(&pre, surf, pre.selection.as_ref(), lock) + })?; + if let Some(st) = s.active_mut() { + st.last_damage = Some(dmg); + } + Ok(dmg) +} + +fn damage_json(r: Rect) -> Value { + json!([r.x0, r.y0, r.width(), r.height()]) +} + +// --------------------------------------------------------------------------------------------- +// Registry +// --------------------------------------------------------------------------------------------- + +/// The brush every retouching command shares, plus the tool's own params. +macro_rules! brush_params { + ($extra:literal) => { + concat!("{", r#""points":[[x,y,pressure?],…],"size":1..5000 px=tool size,"hardness":0..100=tool hardness,"opacity":1..100=100,"flow":1..100=100,"spacing":1..1000 (% of size)=Brush Settings spacing,"layer":id?=active,"target":"pixels"|"mask"|"filterMask"|"quickMask"|{"channel":i}=Channels panel target"#, $extra, "}") + }; +} + +mod clone; +mod dab; +mod heal; +mod sampling; + +pub use clone::{LiveRetouch, clone_preview, clone_preview_periodic}; +use clone::{blend_param, clamp_samples, clone_stamp}; +pub(crate) use dab::DabEffect; +pub use dab::LiveDab; +use dab::dab_cmd; +#[cfg(test)] +use heal::proximity_source_patch; +use heal::{heal_region, healing_brush, history_brush, history_source, spot_healing}; +use sampling::sample; +pub(crate) use sampling::{SampleLayers, composite_region}; + +/// Retouching command specs. +pub fn specs() -> Vec { + vec![ + CommandSpec { + id: "paint.cloneStamp", + label: "Clone Stamp", + menu: &[], + shortcut: None, + params: brush_params!( + r#","source":[sx,sy] (sampled under the first point) | "offset":[dx,dy],"aligned":bool=true,"sampleLayer":"current|currentAndBelow|all"="current","mode":"normal|multiply|…"="normal","wrap":bool=false (repeat source and stroke at document edges for Pattern Preview) → {"damage","offset","aligned","nextSource"}"# + ), + enabled: has_pixel_layer, + run: clone_stamp, + journal: true, + }, + CommandSpec { + id: "paint.patternStamp", + label: "Pattern Stamp", + menu: &[], + shortcut: None, + params: brush_params!( + r#","pattern":id|name?=Patterns panel current,"scale":1..1000 %=100,"angle":deg=0,"aligned":bool=true,"impressionist":bool=false,"mode":"normal|multiply|…"="normal","phase":[px,py]? → {"damage","phase","aligned","pattern"}"# + ), + enabled: pattern_stamp::enabled, + run: pattern_stamp::run, + journal: true, + }, + CommandSpec { + id: "paint.healingBrush", + label: "Healing Brush", + menu: &[], + shortcut: None, + params: brush_params!( + r#","source":[sx,sy] | "offset":[dx,dy],"aligned":bool=true,"sampleLayer":"current|currentAndBelow|all"="current","mode":"normal|…"="normal" → {"damage","offset","aligned","nextSource"}"# + ), + enabled: has_pixel_layer, + run: healing_brush, + journal: true, + }, + CommandSpec { + id: "paint.spotHealing", + label: "Spot Healing Brush", + menu: &[], + shortcut: None, + params: brush_params!(r#","type":"contentAware|createTexture|proximityMatch"="contentAware","sampleAllLayers":bool=false"#), + enabled: has_pixel_layer, + run: spot_healing, + journal: true, + }, + CommandSpec { + id: "paint.patch", + label: "Patch", + menu: &[], + shortcut: None, + params: r#"{"offset":[dx,dy] (how far the selection was dragged),"mode":"source|destination"="source","contentAware":bool=false (fill the selection content-aware from the dragged-to place; a background job),"structure":1..7=4 (content-aware: 3..7 copy the middle exactly, 1..2 re-synthesise more of it),"color":0..10=0 (content-aware: how far the copy's level adapts to the selection's surroundings),"sampleAllLayers":bool=false (content-aware),"layer":id?=active,"target":"pixels"|"mask"|"filterMask"|"quickMask"|{"channel":i}=Channels panel target} → {"damage","offset"}"#, + enabled: patch::enabled, + run: patch::patch, + journal: true, + }, + CommandSpec { + id: "paint.contentAwareMove", + label: "Content-Aware Move", + menu: &[], + shortcut: None, + params: r#"{"offset":[dx,dy] (how far the selection was dragged),"mode":"move|extend"="move","structure":1..7=4 (3..7 copy the content exactly but for a band about a patch wide along its edge; 2 widens the band, 1 re-synthesises the content too),"color":0..10=0 (0 keeps the content's level; higher values bring it towards its new place, by up to about 0.04 × color),"sampleAllLayers":bool=false,"scaleX":%=100,"scaleY":%=100 (Transform On Drop: 1..10000, negative flips),"rotate":deg=0 (Transform On Drop, clockwise; scale and rotation are about the selection's centre, before the offset; a transformed patch may reach past the canvas edge),"layer":id?=active,"target":"pixels"|"mask"|"filterMask"|"quickMask"|{"channel":i}=Channels panel target} → {"damage","offset","mode","transformed"?} (a background job; the selection moves, and is transformed, with the content)"#, + enabled: content_aware_move::enabled, + run: content_aware_move::content_aware_move, + journal: true, + }, + CommandSpec { + id: "paint.remove", + label: "Remove", + menu: &[], + shortcut: None, + params: brush_params!( + r#","strokes":[[[x,y,pressure?],…],…]? (several strokes removed together, as one job and one undo step; else "points"),"closeLoops":bool=true (a stroke around an object removes what it encloses),"sampleAllLayers":bool=false,"newLayer":bool=false (the fill goes to a new layer above the target, which stays as it was) → {"damage","layer"?} (a background job)"# + ), + enabled: has_pixel_layer, + run: remove::remove, + journal: true, + }, + CommandSpec { + id: "paint.dodge", + label: "Dodge", + menu: &[], + shortcut: None, + params: brush_params!(r#","range":"shadows|midtones|highlights"="midtones","exposure":1..100=50,"protectTones":bool=true"#), + enabled: has_pixel_layer, + run: |s, p| dab_cmd(s, p, "paint.dodge"), + journal: true, + }, + CommandSpec { + id: "paint.burn", + label: "Burn", + menu: &[], + shortcut: None, + params: brush_params!(r#","range":"shadows|midtones|highlights"="midtones","exposure":1..100=50,"protectTones":bool=true"#), + enabled: has_pixel_layer, + run: |s, p| dab_cmd(s, p, "paint.burn"), + journal: true, + }, + CommandSpec { + id: "paint.sponge", + label: "Sponge", + menu: &[], + shortcut: None, + params: brush_params!(r#","mode":"desaturate|saturate"="desaturate","vibrance":bool=true (flow = sponge strength)"#), + enabled: has_pixel_layer, + run: |s, p| dab_cmd(s, p, "paint.sponge"), + journal: true, + }, + CommandSpec { + id: "paint.blur", + label: "Blur", + menu: &[], + shortcut: None, + params: brush_params!(r#","strength":1..100=50,"sampleAllLayers":bool=false"#), + enabled: has_pixel_layer, + run: |s, p| dab_cmd(s, p, "paint.blur"), + journal: true, + }, + CommandSpec { + id: "paint.sharpen", + label: "Sharpen", + menu: &[], + shortcut: None, + params: brush_params!(r#","strength":1..100=50,"protectDetail":bool=true,"sampleAllLayers":bool=false"#), + enabled: has_pixel_layer, + run: |s, p| dab_cmd(s, p, "paint.sharpen"), + journal: true, + }, + CommandSpec { + id: "paint.smudge", + label: "Smudge", + menu: &[], + shortcut: None, + params: brush_params!(r#","strength":1..100=50,"fingerPainting":bool=false (starts with the foreground colour),"sampleAllLayers":bool=false"#), + enabled: has_pixel_layer, + run: |s, p| dab_cmd(s, p, "paint.smudge"), + journal: true, + }, + CommandSpec { + id: "paint.historyBrush", + label: "History Brush", + menu: &[], + shortcut: None, + params: brush_params!( + r#","state":row (a History panel row, as history.setSource: 0 = oldest state, then the current one, then the greyed redo states),"snapshot":id (a history.newSnapshot id; default: the History panel's source, else the oldest held state; a source of another canvas size is an error)"# + ), + enabled: has_pixel_layer, + run: history_brush, + journal: true, + }, + CommandSpec { + id: "paint.artHistoryBrush", + label: "Art History Brush", + menu: &[], + shortcut: None, + params: brush_params!( + r#","state":row (a History panel row, as history.setSource),"snapshot":id (a history.newSnapshot id; default: the History panel's source, as paint.historyBrush; a source of another canvas size is an error),"style":"tightShort|tightMedium|tightLong|looseMedium|looseLong|dab|tightCurl|looseCurl"="tightMedium","area":0..100=50,"tolerance":0..100=0"# + ), + enabled: has_pixel_layer, + run: art_history::run, + journal: true, + }, + ] +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/retouch_cmds/art_history.rs b/crates/engine/src/cmd/retouch_cmds/art_history.rs similarity index 100% rename from crates/engine/src/retouch_cmds/art_history.rs rename to crates/engine/src/cmd/retouch_cmds/art_history.rs diff --git a/crates/engine/src/cmd/retouch_cmds/clone.rs b/crates/engine/src/cmd/retouch_cmds/clone.rs new file mode 100644 index 0000000000..5e5ac27104 --- /dev/null +++ b/crates/engine/src/cmd/retouch_cmds/clone.rs @@ -0,0 +1,375 @@ +use super::heal::history_source; +use super::sampling::{SampleLayers, sample, sample_layers}; +use super::*; + +/// Where a clone stroke samples: `offset` / `source` params, else the active Clone Source slot, +/// with the slot's (or the call's) scale, rotation and flips (see `presets::clone_source`). +pub(super) fn clone_mapping(s: &mut Session, p: &Value, stroke: &Stroke, cmd: &str) -> Result { + let f = stroke.points[0]; + crate::presets::clone_source::mapping(s, p, (f.x, f.y), cmd) +} + +/// Source pixels for destination `rect`: a translated read, or a bilinear resample when the +/// clone source is scaled, rotated or flipped. +#[allow(clippy::too_many_arguments)] +pub(super) fn clone_sample( + pre: &Document, + id: Option, + surf: &Surface, + which: SampleLayers, + rect: Rect, + map: &crate::presets::clone_source::Mapping, + wrap: bool, + cmd: &str, +) -> Result { + let read = |rect| { + if wrap { periodic::sample(pre, id, surf, which, rect, cmd) } else { Ok(sample(pre, id, surf, which, rect)) } + }; + if map.is_translation() { + let off = map.offset(); + let src = rect.translate(off.0, off.1); + // `translate` saturates at the i32 edges, so a far source (issue #1111) yields a window + // smaller than `rect`; relabelling that as `rect` would index past the sampled pixels. + if src.width() != rect.width() || src.height() != rect.height() { + return Err(bad(cmd, format!("source offset [{}, {}] is too far: the sample window leaves the coordinate range", off.0, off.1))); + } + let mut r = read(src)?; + r.rect = rect; + return Ok(r); + } + let src = read(map.source_rect(rect))?; + Ok(crate::presets::clone_source::resample(&src, rect, map, alpha_index(&surf.format()))) +} + +/// Read-only clone overlay. Shares the stroke sampler without anchoring a source or editing history. +/// Both destination and transformed source allocations are bounded for interactive use. +pub fn clone_preview(s: &Session, rect: Rect, map: &crate::presets::clone_source::Mapping, sample_layer: &str) -> Result { + clone_preview_periodic(s, rect, map, sample_layer, false) +} + +/// Clone-source overlay with optional source repetition for View > Pattern Preview. +pub fn clone_preview_periodic( + s: &Session, + rect: Rect, + map: &crate::presets::clone_source::Mapping, + sample_layer: &str, + wrap: bool, +) -> Result { + if ![map.source.0, map.source.1, map.anchor.0, map.anchor.1].into_iter().chain(map.m).all(|v| v.is_finite() && v.abs() < 1_000_000.0) { + return Err(bad("clone.preview", "invalid preview mapping")); + } + if ![rect.x0, rect.y0, rect.x1, rect.y1].into_iter().all(|v| v.abs_diff(0) < 1_000_000) + || ![(rect.x0, rect.y0), (rect.x1, rect.y1), (rect.x0, rect.y1), (rect.x1, rect.y0)].into_iter().all(|(x, y)| { + let (x, y) = map.map(f64::from(x), f64::from(y)); + x.is_finite() && y.is_finite() && x.abs() < 1_000_000.0 && y.abs() < 1_000_000.0 + }) + { + return Err(bad("clone.preview", "preview coordinates exceed their budget")); + } + let bounded = |r: Rect| r.width() > 0 && r.height() > 0 && r.width() <= 1024 && r.height() <= 1024; + if !bounded(rect) || !bounded(map.source_rect(rect)) { + return Err(bad("clone.preview", "preview region exceeds its budget")); + } + let d = s.active().ok_or(EngineError::NoDocument)?; + let id = d.active_layer.ok_or_else(|| bad("clone.preview", "no active layer"))?; + let surf = d.doc.layer(id).and_then(|l| l.surface()).ok_or_else(|| bad("clone.preview", "no pixel surface"))?; + let which = sample_layers(&json!({"sampleLayer": sample_layer}), "clone.preview")?; + let region = clone_sample(&d.doc, Some(id), surf, which, rect, map, wrap, "clone.preview")?; + let px = region.data.chunks_exact(surf.format().channels()).map(|p| to_rgba(&surf.format(), p)).collect(); + Ok(photocraft_compose::Buffer { rect, px }) +} + +/// Result JSON shared by Clone Stamp and Healing Brush: the offset used and where the next stroke +/// should sample from if the UI keeps Photoshop's "Aligned" semantics. +pub(super) fn clone_result(dmg: Rect, off: (i32, i32), aligned: bool, p: &Value, stroke: &Stroke) -> Value { + let f = stroke.points[0]; + let source = point(p, "source").unwrap_or((f.x + off.0 as f64, f.y + off.1 as f64)); + // Aligned: the offset persists (next stroke samples at its own first point + offset). + // Non-aligned: every stroke restarts at the original source point. + json!({ "damage": damage_json(dmg), "offset": [off.0, off.1], "aligned": aligned, "nextSource": if aligned { Value::Null } else { json!([source.0, source.1]) } }) +} + +pub(super) fn blend_param(p: &Value, cmd: &str) -> Result { + match p.get("mode").and_then(Value::as_str) { + None => Ok(BlendMode::Normal), + Some(m) => blend_from_str(m).ok_or_else(|| bad(cmd, format!("unknown blend mode `{m}`"))), + } +} + +/// Clamp results into the storable range: integer depths to 0..1, float depths only below at 0; +/// alpha always 0..1. +pub(super) fn clamp_samples(fmt: &PixelFormat, data: &mut [f32]) { + let n = fmt.channels(); + let a = alpha_index(fmt); + let float = fmt.sample == SampleType::F32; + for px in data.chunks_exact_mut(n) { + for (c, v) in px.iter_mut().enumerate() { + *v = if Some(c) == a || !float { v.clamp(0.0, 1.0) } else { v.max(0.0) }; + } + } +} + +// --------------------------------------------------------------------------------------------- +// Clone Stamp / Healing Brush / History Brush +// --------------------------------------------------------------------------------------------- + +pub(super) fn clone_stamp(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "paint.cloneStamp"; + let (stroke, id) = parse_brush(s, p, CMD)?; + reject_huge_stroke(CMD, &stroke)?; + let which = sample_layers(p, CMD)?; + let mode = blend_param(p, CMD)?; + let aligned = flag(p, "aligned", true); + // The live stroke the canvas already drew for exactly this commit: take its pixels instead of + // rendering the stroke again (the hitch on release). + let live = s.live_commit.take().filter(|l| l.matches(s, CMD, p, &stroke.points)); + let from_live = live.is_some(); + let map = clone_mapping(s, p, &stroke, CMD)?; + let off = map.offset(); + let dmg = + run_stroke(s, "Clone Stamp", id, p, |pre, surf, sel, lock| { + if let Some(l) = live { + *surf = l.surface; + return Ok(l.bounds); + } + if flag(p, "wrap", false) { + let mut renderer = photocraft_paint::StrokeRenderer::new(&stroke.brush, None, 1.0); + renderer.push(&stroke.points); + renderer.finish(); + let before = surf.clone(); + let bounds = renderer.bounds(); + return periodic::Composite { target: surf, before: &before, tile: pre.bounds(), opacity: stroke.brush.opacity, selection: sel, lock, mode } + .draw(bounds, &stroke.brush, &stroke.points, |r| clone_sample(pre, id, &before, which, r, &map, true, CMD)); + } + let (bounds, cov) = coverage(CMD, &stroke)?; + // Samples come from the pre-stroke state, so pixels painted earlier in the stroke are never re-cloned. + let paint = clone_sample(pre, id, surf, which, bounds, &map, flag(p, "wrap", false), CMD)?; + Ok(apply_coverage(surf, bounds, &cov, stroke.brush.opacity, sel, lock, &paint, mode)) + })?; + let mut r = clone_result(dmg, off, aligned, p, &stroke); + if from_live { + r["fromLive"] = json!(true); + } + Ok(r) +} + +/// What a live retouching stroke paints through its coverage. +enum LivePaint { + /// The clone source (Clone Stamp; the Healing Brush shows its texture while drawing and + /// blends it on release). + Clone { which: SampleLayers, map: crate::presets::clone_source::Mapping, cmd: &'static str }, + /// The History Brush's history state. + History(Surface), + /// The Pattern Stamp's pattern, tiled from its aligned placement (Impressionist strokes are + /// laid dab by dab: `pattern_stamp::live_impressionist`). + Pattern { tile: std::sync::Arc, place: photocraft_compose::pattern::Placement }, +} + +/// A retouching stroke shown while it is drawn: the dabs so far composited onto a copy of the +/// active document as the command with the same params commits them (the same coverage, +/// sampling and blend): Clone Stamp, History Brush, and the Healing Brush's texture. +pub struct LiveRetouch { + /// The active document with the stroke so far. + pub doc: std::sync::Arc, + cmd: String, + renderer: photocraft_paint::StrokeRenderer, + pre: std::sync::Arc, + pre_surf: Surface, + id: Option, + params: Value, + paint: LivePaint, + mode: BlendMode, + opacity: f32, + sel: Option, + lock: bool, + /// Where the doc shows what finishing the stroke now would add (a lone first dab, the + /// smoothing catch-up), redrawn on every step as the Brush's live stroke does. + tail: Rect, + /// The document and revision the stroke started on. + base: (photocraft_doc::DocId, u64), + brush: Box, + /// Every point rendered so far, in order. + points: Vec, +} + +impl LiveRetouch { + /// Start a live stroke of `cmd` (`paint.cloneStamp`, `paint.healingBrush`, + /// `paint.historyBrush` or an aligned, non-Impressionist `paint.patternStamp`) from its + /// params; their `points` are rendered. + pub fn begin(s: &Session, cmd: &str, p: &Value) -> Result { + has_pixel_layer(s).map_err(EngineError::Other)?; + if cmd == "paint.patternStamp" { + let st = pattern_stamp::Setup::parse(s, p)?; + if st.impressionist { + return Err(bad(cmd, "Impressionist strokes are laid dab by dab (pattern_stamp::live_impressionist)")); + } + let paint = LivePaint::Pattern { place: st.placement(), tile: st.tile }; + return Self::with_paint(s, cmd, p, st.stroke, st.id, paint, st.mode); + } + let (stroke, id) = parse_brush(s, p, cmd)?; + let mode = blend_param(p, cmd)?; + let paint = match cmd { + "paint.cloneStamp" | "paint.healingBrush" => { + let f = *stroke.points.first().ok_or_else(|| bad(cmd, "`points` is empty"))?; + LivePaint::Clone { + which: sample_layers(p, cmd)?, + map: crate::presets::clone_source::resolve(s, p, (f.x, f.y), cmd)?.0, + cmd: if cmd == "paint.healingBrush" { "paint.healingBrush" } else { "paint.cloneStamp" }, + } + } + "paint.historyBrush" => LivePaint::History(history_source(s, id, p, cmd)?), + other => return Err(bad(other, "live retouching strokes are the Clone Stamp, Healing Brush, History Brush and Pattern Stamp")), + }; + Self::with_paint(s, cmd, p, stroke, id, paint, mode) + } + + /// Start a live stroke of `cmd` painting `paint` through `stroke`'s coverage. + fn with_paint(s: &Session, cmd: &str, p: &Value, stroke: Stroke, id: Option, paint: LivePaint, mode: BlendMode) -> Result { + let st = s.active().ok_or(EngineError::NoDocument)?; + let (pre, base) = (st.doc.clone(), (st.doc.id, st.revision)); + let mut doc = (*pre).clone(); + let sel = doc.selection.clone(); + let (surf, lock) = crate::channel_cmds::target_surface(&mut doc, id, p)?; + let pre_surf = surf.clone(); + // As `stroke_coverage`, which the commit uses. + let renderer = photocraft_paint::StrokeRenderer::new(&stroke.brush, None, 1.0); + let opacity = stroke.brush.opacity; + let brush = Box::new(stroke.brush.clone()); + let paint = match paint { + LivePaint::History(src) if src.format() != pre_surf.format() => LivePaint::History(src.convert(pre_surf.format())), + other => other, + }; + let mut live = Self { + doc: std::sync::Arc::new(doc), + cmd: cmd.into(), + renderer, + pre, + pre_surf, + id, + params: p.clone(), + paint, + mode, + opacity, + sel, + lock, + tail: Rect::EMPTY, + base, + brush, + points: Vec::new(), + }; + live.push(&stroke.points)?; + Ok(live) + } + + /// Everything the stroke has touched so far. + pub fn bounds(&self) -> Rect { + let bounds = self.renderer.bounds().union(&self.tail); + if self.cmd == "paint.cloneStamp" && flag(&self.params, "wrap", false) { + periodic::project(bounds, self.pre.bounds()).into_iter().fold(Rect::EMPTY, |a, b| a.union(&b)) + } else { + bounds + } + } + + /// Every point rendered so far, in order. + pub fn points(&self) -> &[StrokePoint] { + &self.points + } + + /// The finished stroke as its commit would take it over ([`Session::offer_live_retouch`]). + /// Only the Clone Stamp and History Brush draw what they commit (the Healing Brush blends on + /// release), and only while the brush, layer and clone source are still the ones the stroke + /// started with: the document revision doesn't cover those. + pub(crate) fn into_commit(mut self, s: &Session) -> Result { + let (stroke, id) = parse_brush(s, &self.params, &self.cmd)?; + let source_unchanged = match &self.paint { + LivePaint::Clone { map, .. } if self.cmd == "paint.cloneStamp" => { + let f = stroke.points.first().ok_or_else(|| bad(&self.cmd, "`points` is empty"))?; + crate::presets::clone_source::resolve(s, &self.params, (f.x, f.y), &self.cmd)?.0 == *map + } + LivePaint::History(_) if self.cmd == "paint.historyBrush" => true, + _ => return Err(bad(&self.cmd, "only Clone Stamp and History Brush strokes commit their live pixels")), + }; + if !source_unchanged || *self.brush != stroke.brush || id != self.id { + return Err(bad(&self.cmd, "the brush, layer or clone source changed during the stroke")); + } + let bounds = self.bounds(); + let (surf, _) = crate::channel_cmds::target_surface(std::sync::Arc::make_mut(&mut self.doc), self.id, &self.params)?; + let surface = surf.clone(); + Ok(crate::brush_cmds::LiveCommit { mixer: None, cmd: self.cmd, base: self.base, params: self.params, seed: None, points: self.points, surface, bounds }) + } + + /// Render more points; returns the rectangle that changed. Each changed area is redrawn from + /// the pre-stroke pixels with the stroke's coverage so far, so overlapping dabs build up as in + /// the commit, and pixels painted earlier in the stroke are never re-cloned. What finishing + /// the stroke now would add is drawn too (a lone first dab shows on the press), and redrawn on + /// every step. + /// Invalid coordinates reject the whole batch without changing the preview. + /// Only the position and pressure of `pts` are used: the commands take no tilt or times. + pub fn push(&mut self, pts: &[StrokePoint]) -> Result { + crate::brush_cmds::check_coords(pts, &self.cmd)?; + let pts: Vec<_> = pts.iter().map(|q| StrokePoint::new(q.x, q.y, q.pressure)).collect(); + self.points.extend_from_slice(&pts); + self.renderer.push(&pts); + if self.cmd == "paint.cloneStamp" && flag(&self.params, "wrap", false) { + return self.push_periodic(); + } + let old = std::mem::replace(&mut self.tail, Rect::EMPTY); + let mut dmg = Rect::EMPTY; + if !old.is_empty() { + // Back to the stroke without the previous tail. + let (surf, _) = crate::channel_cmds::target_surface(std::sync::Arc::make_mut(&mut self.doc), self.id, &self.params)?; + surf.write_region(old, &self.pre_surf.read_region(old)); + self.renderer.mark_dirty(old); + dmg = old; + } + let r = self.renderer.take_dirty_rect(); + let cov = self.renderer.coverage_in(r); + dmg = dmg.union(&self.composite(r, &cov)?); + if let Some(mut tail) = self.renderer.tail_preview() { + let r = tail.take_dirty_rect(); + let cov = tail.coverage_in(r); + self.tail = self.composite(r, &cov)?; + dmg = dmg.union(&self.tail); + } + Ok(dmg) + } + + fn push_periodic(&mut self) -> Result { + let mut dirty = self.renderer.take_dirty_rect().union(&self.tail); + let mut tail = self.renderer.tail_preview(); + self.tail = tail.as_mut().map_or(Rect::EMPTY, |t| t.take_dirty_rect()); + dirty = dirty.union(&self.tail); + let LivePaint::Clone { which, map, cmd } = &self.paint else { + return Err(bad(&self.cmd, "periodic painting requires a clone source")); + }; + let (surf, _) = crate::channel_cmds::target_surface(std::sync::Arc::make_mut(&mut self.doc), self.id, &self.params)?; + periodic::Composite { + target: surf, + before: &self.pre_surf, + tile: self.pre.bounds(), + opacity: self.opacity, + selection: self.sel.as_ref(), + lock: self.lock, + mode: self.mode, + } + .draw(dirty, &self.brush, &self.points, |r| clone_sample(&self.pre, self.id, &self.pre_surf, *which, r, map, true, cmd)) + } + + /// Redraw `r` from the pre-stroke pixels with the clone source through coverage `cov`. + fn composite(&mut self, r: Rect, cov: &[f32]) -> Result { + if r.is_empty() { + return Ok(r); + } + let paint = match &self.paint { + LivePaint::Clone { which, map, cmd } => { + clone_sample(&self.pre, self.id, &self.pre_surf, *which, r, map, *cmd == "paint.cloneStamp" && flag(&self.params, "wrap", false), cmd)? + } + LivePaint::History(src) => Region::read(src, r), + LivePaint::Pattern { tile, place } => pattern_stamp::paint_region(tile, place, &self.pre_surf.format(), r), + }; + let (surf, _) = crate::channel_cmds::target_surface(std::sync::Arc::make_mut(&mut self.doc), self.id, &self.params)?; + surf.write_region(r, &self.pre_surf.read_region(r)); + Ok(apply_coverage(surf, r, cov, self.opacity, self.sel.as_ref(), self.lock, &paint, self.mode).union(&r)) + } +} diff --git a/crates/engine/src/retouch_cmds/content_aware_move.rs b/crates/engine/src/cmd/retouch_cmds/content_aware_move.rs similarity index 100% rename from crates/engine/src/retouch_cmds/content_aware_move.rs rename to crates/engine/src/cmd/retouch_cmds/content_aware_move.rs diff --git a/crates/engine/src/cmd/retouch_cmds/dab.rs b/crates/engine/src/cmd/retouch_cmds/dab.rs new file mode 100644 index 0000000000..818c27a6f1 --- /dev/null +++ b/crates/engine/src/cmd/retouch_cmds/dab.rs @@ -0,0 +1,625 @@ +use super::sampling::{AllLayers, sample_all_layers}; +use super::*; + +// --------------------------------------------------------------------------------------------- +// Toning (Dodge / Burn / Sponge) and focus (Blur / Sharpen), Smudge +// --------------------------------------------------------------------------------------------- + +/// Per-dab strength such that one pass over a point totals roughly `e`, whatever the spacing +/// (about `1/spacing` dabs overlap each point on the stroke's centre line). +#[inline] +fn per_dab(e: f32, spacing: f32) -> f32 { + 1.0 - (1.0 - e.clamp(0.0, 1.0)).powf(spacing.clamp(0.01, 1.0)) +} + +/// Apply an RGB colour transform `f(rgb, strength)` to each covered pixel of a dab (through straight +/// RGBA, so it works for Gray/CMYK/Lab too; untouched pixels are never round-tripped). +fn color_dab(fmt: &PixelFormat, work: &mut Region, fp: &Footprint, strength: f32, spacing: f32, f: impl Fn([f32; 3], f32) -> [f32; 3]) { + let r = fp.rect.intersect(&work.rect); + let n = fmt.channels(); + let mut enc = [0.0f32; 8]; + for y in r.y0..r.y1 { + for x in r.x0..r.x1 { + let k = per_dab(fp.at(x, y) * strength, spacing); + if k <= 0.0 { + continue; + } + let px = work.px_mut(x, y); + let rgba = to_rgba(fmt, px); + let o = f([rgba[0], rgba[1], rgba[2]], k); + from_rgba_into(fmt, [o[0], o[1], o[2], rgba[3]], &mut enc); + let a = alpha_index(fmt); + for c in 0..n { + if Some(c) != a { + px[c] = enc[c]; + } + } + } + } +} + +/// Dodge and Burn: a stroke tones each pixel once, from its original colour, mixed in by the +/// stroke's coverage there (`toned` is the full-exposure colour). Dabs build up coverage as in a +/// brush stroke, capped at full coverage, so Exposure caps a stroke the way Opacity caps a paint +/// stroke: overlapping dabs and passes within one stroke don't compound the tone curve, and a +/// new stroke builds on the last. +fn tone_stroke(fmt: PixelFormat, toned: impl Fn([f32; 3]) -> [f32; 3] + 'static) -> DabEffect { + /// Side of the cells that remember, per touched pixel, the coverage applied so far and the + /// original pixel (copied from the working pixels the first time a dab reaches it). Dense + /// cells rather than a map per pixel: a map lookup per covered pixel made long strokes with + /// large brushes over ten times slower. + const CELL: i32 = 64; + struct Cell { + cov: Vec, + orig: Vec, + } + let mut cells: std::collections::HashMap<(i32, i32), Cell> = std::collections::HashMap::new(); + let a = alpha_index(&fmt); + let n = fmt.channels(); + Box::new(move |work, fp| { + let r = fp.rect.intersect(&work.rect); + if r.is_empty() { + return; + } + let mut enc = [0.0f32; 8]; + for cy in r.y0.div_euclid(CELL)..=(r.y1 - 1).div_euclid(CELL) { + for cx in r.x0.div_euclid(CELL)..=(r.x1 - 1).div_euclid(CELL) { + let cr = Rect::new(cx * CELL, cy * CELL, cx * CELL + CELL, cy * CELL + CELL); + let part = r.intersect(&cr); + if part.is_empty() { + continue; + } + let len = (CELL * CELL) as usize; + // Coverage -1: not touched yet, so `orig` isn't filled in for that pixel. + let cell = cells.entry((cx, cy)).or_insert_with(|| Cell { cov: vec![-1.0; len], orig: vec![0.0; len * n] }); + for y in part.y0..part.y1 { + for x in part.x0..part.x1 { + let k = fp.at(x, y).clamp(0.0, 1.0); + if k <= 0.0 { + continue; + } + let i = ((y - cr.y0) * CELL + (x - cr.x0)) as usize; + let (Some(prev), Some(src)) = (cell.cov.get_mut(i), cell.orig.get_mut(i * n..i * n + n)) else { continue }; + if *prev < 0.0 { + // First touch: the working pixel is still the original. + src.copy_from_slice(work.px(x, y)); + *prev = 0.0; + } + // Dabs build up the stroke's coverage as a brush stroke's do (flow), up + // to full coverage; the tone is applied once, from the original. + let k = *prev + k * (1.0 - *prev); + if k <= *prev { + continue; + } + *prev = k; + let o = to_rgba(&fmt, src); + let t = toned([o[0], o[1], o[2]]); + let m = [o[0] + (t[0] - o[0]) * k, o[1] + (t[1] - o[1]) * k, o[2] + (t[2] - o[2]) * k]; + from_rgba_into(&fmt, [m[0], m[1], m[2], o[3]], &mut enc); + let px = work.px_mut(x, y); + for c in 0..n { + if Some(c) != a { + px[c] = enc[c]; + } + } + } + } + } + } + }) +} + +fn tone_range(p: &Value, cmd: &str) -> Result { + match string(p, "range", "midtones") { + "shadows" => Ok(ToneRange::Shadows), + "midtones" => Ok(ToneRange::Midtones), + "highlights" => Ok(ToneRange::Highlights), + o => Err(bad(cmd, format!("unknown range `{o}` (shadows|midtones|highlights)"))), + } +} + +/// A sequential-dab tool's settings (Dodge, Burn, Sponge, Blur, Sharpen, Smudge), parsed once and +/// turned into its per-dab effect, for the commit and the live preview alike. +#[derive(Clone, Debug, PartialEq)] +enum DabTool { + Tone { burn: bool, range: ToneRange, exposure: f32, protect: bool }, + Sponge { saturate: bool, vibrance: bool }, + Focus { sharpen: bool, strength: f32, protect: bool, sigma: f32 }, + Smudge { strength: f32, finger: Option<[f32; 4]>, max_size: f32 }, +} + +/// One dab's edit of the working copy. +pub(crate) type DabEffect = Box; + +/// Pixels an effect reads beyond the dab it writes. Smudge's pickup is a fixed-size square, +/// independent of pressure, roundness and the dab's current angle. +#[derive(Clone, Copy)] +enum DabNeighborhood { + Halo(i32), + Smudge(i32), +} + +impl DabNeighborhood { + fn halo(self) -> i32 { + match self { + Self::Halo(radius) | Self::Smudge(radius) => radius, + } + } + + fn read_rect(self, rect: Rect, dab: &photocraft_paint::Dab) -> Rect { + match self { + Self::Halo(radius) => rect.inflate(radius), + Self::Smudge(radius) => { + let (x, y) = (dab.center.x.floor() as i32, dab.center.y.floor() as i32); + rect.union(&Rect::new( + x.saturating_sub(radius), + y.saturating_sub(radius), + x.saturating_add(radius).saturating_add(1), + y.saturating_add(radius).saturating_add(1), + )) + } + } + } +} + +impl DabTool { + /// The tool for `cmd` and its history label. + fn parse(s: &Session, cmd: &str, p: &Value, stroke: &Stroke) -> Result<(Self, &'static str)> { + Ok(match cmd { + "paint.dodge" | "paint.burn" => { + let burn = cmd == "paint.burn"; + let tool = Self::Tone { + burn, + range: tone_range(p, cmd)?, + exposure: num(p, "exposure", 50.0).clamp(1.0, 100.0) / 100.0, + protect: flag(p, "protectTones", true), + }; + (tool, if burn { "Burn Tool" } else { "Dodge Tool" }) + } + "paint.sponge" => { + let saturate = match string(p, "mode", "desaturate") { + "desaturate" => false, + "saturate" => true, + o => return Err(bad(cmd, format!("unknown mode `{o}` (desaturate|saturate)"))), + }; + (Self::Sponge { saturate, vibrance: flag(p, "vibrance", true) }, "Sponge Tool") + } + "paint.blur" | "paint.sharpen" => { + let sharpen = cmd == "paint.sharpen"; + let tool = Self::Focus { + sharpen, + strength: num(p, "strength", 50.0).clamp(1.0, 100.0) / 100.0, + protect: flag(p, "protectDetail", true), + sigma: (stroke.brush.size * 0.03).clamp(1.0, 4.0), + }; + (tool, if sharpen { "Sharpen Tool" } else { "Blur Tool" }) + } + "paint.smudge" => { + let finger = flag(p, "fingerPainting", false).then_some(s.tools.foreground); + (Self::Smudge { strength: num(p, "strength", 50.0).clamp(1.0, 100.0) / 100.0, finger, max_size: stroke.brush.size }, "Smudge Tool") + } + o => return Err(bad(o, "not a sequential-dab tool")), + }) + } + + /// How far around each dab the effect reads (Blur and Sharpen read a neighbourhood). + fn neighborhood(&self) -> DabNeighborhood { + match self { + Self::Focus { sigma, .. } => DabNeighborhood::Halo((sigma * 3.0).ceil() as i32 + 1), + Self::Smudge { max_size, .. } => DabNeighborhood::Smudge(Smudge::sampling_radius(*max_size)), + _ => DabNeighborhood::Halo(0), + } + } + + /// The per-dab effect on a working copy in `fmt`, for a brush of `spacing`. + fn effect(&self, fmt: PixelFormat, spacing: f32) -> DabEffect { + let sp = spacing; + match self.clone() { + Self::Tone { burn, range, exposure, protect } => tone_stroke(fmt, move |c| dodge_burn(c, exposure, range, burn, protect)), + // Flow is already in each dab's coverage; a full-flow pass moves colours half-way. + Self::Sponge { saturate, vibrance } => Box::new(move |work, fp| color_dab(&fmt, work, fp, 0.5, sp, |c, k| sponge(c, k, saturate, vibrance))), + Self::Focus { sharpen, strength, protect, sigma } => { + let a = alpha_index(&fmt); + Box::new(move |work, fp| { + let r = fp.rect.intersect(&work.rect); + if r.is_empty() { + return; + } + let (w, h, n) = (work.width(), work.height(), work.ch); + let win = ((r.x0 - work.rect.x0) as usize, (r.y0 - work.rect.y0) as usize, (r.x1 - work.rect.x0) as usize, (r.y1 - work.rect.y0) as usize); + let out = if sharpen { local_sharpen(&work.data, w, h, n, a, win, 1.0, protect) } else { local_blur(&work.data, w, h, n, a, win, sigma) }; + let rw = r.width() as usize; + // Row-parallel, like the blur itself (#5426). + let (wx0, wy0) = (work.rect.x0, work.rect.y0); + work.data.par_chunks_mut(w * n).enumerate().for_each(|(row, line)| { + let y = wy0 + row as i32; + if y < r.y0 || y >= r.y1 { + return; + } + for x in r.x0..r.x1 { + let k = per_dab(fp.at(x, y) * strength, sp); + if k <= 0.0 { + continue; + } + let o = ((y - r.y0) as usize * rw + (x - r.x0) as usize) * n; + let i = (x - wx0) as usize * n; + let px = &mut line[i..i + n]; + for c in 0..n { + px[c] += (out[o + c] - px[c]) * k; + } + } + }); + }) + } + Self::Smudge { strength, finger, max_size } => { + let finger_px = finger.map(|fg| photocraft_raster::from_rgba(&fmt, fg)); + // Premultiplied mixing: transparent pixels carry no colour, so no dark fringes. + let mut sm = Smudge::new(strength, finger_px, max_size).with_alpha(alpha_index(&fmt)); + Box::new(move |work, fp| sm.dab(work, fp)) + } + } + } +} + +/// Dodge, Burn, Sponge, Blur, Sharpen and Smudge: each dab edits a working copy in order +/// (`apply_dab_stroke`). Blur, Sharpen and Smudge can sample all layers. +pub(super) fn dab_cmd(s: &mut Session, p: &Value, cmd: &str) -> Result { + let (stroke, id) = parse_brush(s, p, cmd)?; + let (tool, label) = DabTool::parse(s, cmd, p, &stroke)?; + let all = matches!(tool, DabTool::Focus { .. } | DabTool::Smudge { .. }) && sample_all_layers(p); + // The live stroke the canvas already drew for exactly this commit (`LiveDab::into_commit`): + // take its pixels instead of running every dab again (the hitch on release). + let live = s.live_commit.take().filter(|l| l.matches(s, cmd, p, &stroke.points)); + let from_live = live.is_some(); + let dmg = run_stroke(s, label, id, p, |pre, surf, sel, lock| { + if let Some(l) = live { + *surf = l.surface; + return Ok(l.bounds); + } + let fmt = surf.format(); + let mut effect = tool.effect(fmt, stroke.brush.spacing); + let mut sampler = all.then(|| AllLayers::new(pre, fmt)); + Ok(apply_dab_stroke(surf, &stroke, sel, lock, tool.neighborhood().halo(), |work, fp| match &mut sampler { + Some(all) => all.dab(work, fp, |w, f| effect(w, f)), + None => effect(work, fp), + })) + })?; + let mut r = json!({ "damage": damage_json(dmg) }); + if from_live { + r["fromLive"] = json!(true); + } + Ok(r) +} + +/// Side of the tiles a live sequential-dab stroke keeps its working pixels in ([`WorkTiles`]). +const WORK_TILE: i32 = 128; + +/// The working copy of a live sequential-dab stroke: the target's native channels as `f32`, in +/// tiles copied from the pre-stroke surface the first time a dab writes to them. Unlike a +/// `Surface`, it isn't rounded to the document's depth between dabs, so each dab sees what the +/// commit's working copy (`apply_dab_stroke`) holds and the preview is the commit's pixels. +struct WorkTiles { + ch: usize, + tiles: std::collections::HashMap<(i32, i32), Vec>, +} + +impl WorkTiles { + fn new(ch: usize) -> Self { + Self { ch, tiles: std::collections::HashMap::new() } + } + + fn tile_rect((tx, ty): (i32, i32)) -> Rect { + Rect::new(tx * WORK_TILE, ty * WORK_TILE, tx * WORK_TILE + WORK_TILE, ty * WORK_TILE + WORK_TILE) + } + + /// The tiles `r` overlaps. + fn coords(r: Rect) -> impl Iterator { + let (x0, x1) = (r.x0.div_euclid(WORK_TILE), (r.x1 - 1).div_euclid(WORK_TILE)); + let (y0, y1) = (r.y0.div_euclid(WORK_TILE), (r.y1 - 1).div_euclid(WORK_TILE)); + let empty = r.is_empty(); + (y0..=y1).filter(move |_| !empty).flat_map(move |ty| (x0..=x1).map(move |tx| (tx, ty))) + } + + /// The working pixels of `r`: the pre-stroke pixels `pre` where no dab has written yet. + fn read(&self, pre: &Surface, r: Rect) -> Region { + let mut out = Region::new(r, self.ch); + let n = self.ch; + let mut buf = Vec::new(); + for c in Self::coords(r) { + let tr = Self::tile_rect(c); + let part = r.intersect(&tr); + let w = part.width() as usize * n; + let tile = self.tiles.get(&c); + if tile.is_none() { + pre.read_region_into(part, &mut buf); + } + for y in part.y0..part.y1 { + let src = match tile { + Some(t) => t.get(((y - tr.y0) * WORK_TILE + (part.x0 - tr.x0)) as usize * n..).and_then(|s| s.get(..w)), + None => buf.get((y - part.y0) as usize * w..).and_then(|s| s.get(..w)), + }; + let dst = out.index(part.x0, y) * n; + if let (Some(s), Some(d)) = (src, out.data.get_mut(dst..dst + w)) { + d.copy_from_slice(s); + } + } + } + out + } + + /// Store `region` as the working pixels of its rectangle. + fn write(&mut self, pre: &Surface, region: &Region) { + let (r, n) = (region.rect, self.ch); + for c in Self::coords(r) { + let tr = Self::tile_rect(c); + let tile = self.tiles.entry(c).or_insert_with(|| pre.read_region(tr)); + let part = r.intersect(&tr); + let w = part.width() as usize * n; + for y in part.y0..part.y1 { + let dst = ((y - tr.y0) * WORK_TILE + (part.x0 - tr.x0)) as usize * n; + let src = region.index(part.x0, y) * n; + if let (Some(s), Some(d)) = (region.data.get(src..src + w), tile.get_mut(dst..dst + w)) { + d.copy_from_slice(s); + } + } + } + } +} + +/// A Dodge, Burn, Sponge, Blur, Sharpen or Smudge stroke shown while it is drawn: each new dab +/// runs the tool's effect on a working copy of the target, in order, and the changed area is +/// mixed back over the original at the brush opacity, as `apply_dab_stroke` does on release. +/// The working copy keeps full precision ([`WorkTiles`]), so the pixels are the commit's, and the +/// commit takes them over ([`Session::offer_live_dab`]) instead of running every dab again. +/// Sample All Layers isn't previewed (its composite spans the whole stroke). +pub struct LiveDab { + /// The active document with the stroke so far. + pub doc: std::sync::Arc, + cmd: String, + renderer: photocraft_paint::StrokeRenderer, + done: usize, + effect: DabEffect, + neighborhood: DabNeighborhood, + pre_surf: Surface, + work: WorkTiles, + id: Option, + params: Value, + opacity: f32, + sel: Option, + lock: bool, + bounds: Rect, + /// Show the dabs finishing the stroke would add, so the preview at the last point is the + /// commit. Only for effects that a repeated dab doesn't change (Color Replacement): the + /// tail runs on a scratch copy at every push, so an effect that carries paint from dab to + /// dab (Smudge) would drift. + preview_tail: bool, + /// Where the shown tail is. + tail: Rect, + /// The tool and brush the stroke started with, which its commit must still have: the + /// document revision doesn't cover the session's brush or foreground colour. `None` for + /// strokes whose commit renders itself (Color Replacement). + tool: Option<(DabTool, Box)>, + /// The document and revision the stroke started on, for strokes started from the session's + /// active document ([`Self::with_effect`]); `None` for strokes on a prepared copy. + base: Option<(photocraft_doc::DocId, u64)>, + /// Every point rendered so far, in order. + points: Vec, +} + +impl LiveDab { + /// Start a live stroke of `cmd` from its params; their `points` are rendered. + pub fn begin(s: &Session, cmd: &str, p: &Value) -> Result { + has_pixel_layer(s).map_err(EngineError::Other)?; + if sample_all_layers(p) { + return Err(bad(cmd, "Sample All Layers strokes aren't previewed live")); + } + let (stroke, id) = parse_brush(s, p, cmd)?; + let (tool, _) = DabTool::parse(s, cmd, p, &stroke)?; + let (neighborhood, spacing, brush) = (tool.neighborhood(), stroke.brush.spacing, Box::new(stroke.brush.clone())); + let effect = tool.clone(); + let mut live = Self::with_neighborhood(s, cmd, p, stroke, id, neighborhood, |pre| effect.effect(pre.format(), spacing))?; + live.tool = Some((tool, brush)); + Ok(live) + } + + /// Start a live stroke of `cmd` that runs `effect` (made from the target before the stroke) + /// at each dab of `stroke`, reading `halo` pixels around it. `p` gives the target. + pub(crate) fn with_effect( + s: &Session, + cmd: &str, + p: &Value, + stroke: Stroke, + id: Option, + halo: i32, + effect: impl FnOnce(&Surface) -> DabEffect, + ) -> Result { + Self::with_neighborhood(s, cmd, p, stroke, id, DabNeighborhood::Halo(halo), effect) + } + + fn with_neighborhood( + s: &Session, + cmd: &str, + p: &Value, + stroke: Stroke, + id: Option, + neighborhood: DabNeighborhood, + effect: impl FnOnce(&Surface) -> DabEffect, + ) -> Result { + let st = s.active().ok_or(EngineError::NoDocument)?; + let base = (st.doc.id, st.revision); + let doc = (*st.doc).clone(); + let mut live = Self::with_neighborhood_on(doc, cmd, p, stroke, id, neighborhood, effect)?; + live.base = Some(base); + Ok(live) + } + + /// [`Self::with_effect`] on `doc`, a copy of the active document with what the commit's own + /// edit does first (the Background Eraser's Background turned into a normal layer, say). + pub(crate) fn with_effect_on( + doc: Document, + cmd: &str, + p: &Value, + stroke: Stroke, + id: Option, + halo: i32, + effect: impl FnOnce(&Surface) -> DabEffect, + ) -> Result { + Self::with_neighborhood_on(doc, cmd, p, stroke, id, DabNeighborhood::Halo(halo), effect) + } + + fn with_neighborhood_on( + mut doc: Document, + cmd: &str, + p: &Value, + stroke: Stroke, + id: Option, + neighborhood: DabNeighborhood, + effect: impl FnOnce(&Surface) -> DabEffect, + ) -> Result { + let sel = doc.selection.clone(); + let (surf, lock) = crate::channel_cmds::target_surface(&mut doc, id, p)?; + let pre_surf = surf.clone(); + let effect = effect(&pre_surf); + // `apply_dab_stroke` generates the same dabs (`dabs`: zoom 1, no smoothing scale). + let renderer = photocraft_paint::StrokeRenderer::new(&stroke.brush, None, 1.0).record_dabs(); + let mut live = Self { + doc: std::sync::Arc::new(doc), + cmd: cmd.into(), + renderer, + done: 0, + effect, + neighborhood, + work: WorkTiles::new(pre_surf.channels()), + pre_surf, + id, + params: p.clone(), + opacity: stroke.brush.opacity, + sel, + lock, + bounds: Rect::EMPTY, + preview_tail: false, + tail: Rect::EMPTY, + tool: None, + base: None, + points: Vec::new(), + }; + live.push(&stroke.points)?; + Ok(live) + } + + /// Also show the stroke's finishing dabs (see `preview_tail`). + pub(crate) fn with_tail_preview(mut self) -> Result { + self.preview_tail = true; + self.push(&[])?; + Ok(self) + } + + /// Everything the stroke has touched so far. + pub fn bounds(&self) -> Rect { + self.bounds + } + + /// Run the dabs the renderer has generated since the last call on the working copy; returns + /// the rectangle they changed. + fn run_new_dabs(&mut self) -> Rect { + let ctx = self.renderer.ctx.clone(); + let new: Vec<_> = self.renderer.dabs().get(self.done..).unwrap_or_default().to_vec(); + let mut dmg = Rect::EMPTY; + for (k, d) in new.iter().enumerate() { + let r = ctx.dab_rect(d, false); + if r.is_empty() { + continue; + } + let mut region = self.work.read(&self.pre_surf, self.neighborhood.read_rect(r, d)); + (self.effect)(&mut region, &ctx.footprint(d, self.done + k)); + self.work.write(&self.pre_surf, ®ion.crop(r)); + dmg = dmg.union(&r); + } + self.done += new.len(); + dmg + } + + /// Mix the working pixels of `r` back over the original into the shown document. + fn show(&mut self, r: Rect, work: &Region) -> Result<()> { + let (surf, _) = crate::channel_cmds::target_surface(std::sync::Arc::make_mut(&mut self.doc), self.id, &self.params)?; + photocraft_paint::retouch::mix_back(surf, &Region::read(&self.pre_surf, r), work, r, self.opacity, self.sel.as_ref(), self.lock); + Ok(()) + } + + /// Render more points; returns the rectangle that changed. + /// Invalid coordinates reject the whole batch without changing the preview. + /// Only the position and pressure of `pts` are used: the commands take no tilt or times. + pub fn push(&mut self, pts: &[StrokePoint]) -> Result { + crate::brush_cmds::check_coords(pts, &self.cmd)?; + let pts: Vec<_> = pts.iter().map(|q| StrokePoint::new(q.x, q.y, q.pressure)).collect(); + self.points.extend_from_slice(&pts); + self.renderer.push(&pts); + let dmg = self.run_new_dabs(); + let ctx = self.renderer.ctx.clone(); + // The finishing dabs, run on a scratch copy of the working pixels. + let mut tail = None; + if self.preview_tail { + let ds = self.renderer.tail_dabs(); + let r = ds.iter().fold(Rect::EMPTY, |a, d| a.union(&ctx.dab_rect(d, false))); + if !r.is_empty() { + let mut region = self.work.read(&self.pre_surf, r.inflate(self.neighborhood.halo())); + for (k, d) in ds.iter().enumerate() { + (self.effect)(&mut region, &ctx.footprint(d, self.done + k)); + } + tail = Some((r, region.crop(r))); + } + } + // Back to the stroke without the previous tail. + let old = std::mem::replace(&mut self.tail, Rect::EMPTY); + let shown = dmg.union(&old); + let tail_rect = tail.as_ref().map_or(Rect::EMPTY, |(r, _)| *r); + if shown.is_empty() && tail_rect.is_empty() { + return Ok(Rect::EMPTY); + } + self.bounds = self.bounds.union(&dmg).union(&tail_rect); + if !shown.is_empty() { + let work = self.work.read(&self.pre_surf, shown); + self.show(shown, &work)?; + } + if let Some((r, work)) = tail { + self.show(r, &work)?; + self.tail = r; + } + Ok(shown.union(&tail_rect)) + } + + /// The finished stroke as its commit would take it over ([`Session::offer_live_dab`]): the + /// finishing dabs are run, and the pixels are the ones the command with the same params and + /// points paints. Only while the brush, tool settings and layer are still the ones the stroke + /// started with: the document revision doesn't cover those. + pub(crate) fn into_commit(mut self, s: &Session) -> Result { + let (Some((tool, brush)), Some(base)) = (self.tool.take(), self.base) else { + return Err(bad(&self.cmd, "this stroke's commit renders itself")); + }; + let (stroke, id) = parse_brush(s, &self.params, &self.cmd)?; + let (now, _) = DabTool::parse(s, &self.cmd, &self.params, &stroke)?; + if now != tool || stroke.brush != *brush || id != self.id { + return Err(bad(&self.cmd, "the brush, tool options or layer changed during the stroke")); + } + self.renderer.finish(); + let dmg = self.run_new_dabs(); + let shown = dmg.union(&self.tail); + if !shown.is_empty() { + let work = self.work.read(&self.pre_surf, shown); + self.show(shown, &work)?; + } + self.bounds = self.bounds.union(&dmg); + let (surf, _) = crate::channel_cmds::target_surface(std::sync::Arc::make_mut(&mut self.doc), self.id, &self.params)?; + let surface = surf.clone(); + Ok(crate::brush_cmds::LiveCommit { + mixer: None, + cmd: self.cmd, + base, + params: self.params, + seed: None, + points: self.points, + surface, + bounds: self.bounds, + }) + } +} diff --git a/crates/engine/src/cmd/retouch_cmds/heal.rs b/crates/engine/src/cmd/retouch_cmds/heal.rs new file mode 100644 index 0000000000..79e42723e6 --- /dev/null +++ b/crates/engine/src/cmd/retouch_cmds/heal.rs @@ -0,0 +1,235 @@ +use super::clone::{blend_param, clamp_samples, clone_mapping, clone_result, clone_sample}; +use super::sampling::{SampleLayers, composite_region, sample_all_layers, sample_layers}; +use super::*; + +/// Grow a stroke's coverage map by `m` pixels of zero coverage (a Dirichlet boundary for the solve). +fn pad_coverage(bounds: Rect, cov: &[f32], m: i32) -> (Rect, Vec) { + let g = bounds.inflate(m); + let (w, gw) = (bounds.width() as usize, g.width() as usize); + let mut out = vec![0.0f32; gw * g.height() as usize]; + for (i, c) in cov.iter().enumerate() { + let (x, y) = (i % w + m as usize, i / w + m as usize); + out[y * gw + x] = *c; + } + (g, out) +} + +/// Seamless-clone `src` into `dst` over the mask (both regions cover the same rect). The solve runs +/// only on the mask's bounding box plus a one-pixel Dirichlet ring; the rest is `dst`. +pub(super) fn heal_region(fmt: &PixelFormat, src: &Region, dst: &Region, mask: &[bool]) -> Region { + let w = dst.width(); + let bbox = mask.iter().enumerate().filter(|(_, m)| **m).fold(Rect::EMPTY, |r, (i, _)| { + let (x, y) = (dst.rect.x0 + (i % w) as i32, dst.rect.y0 + (i / w) as i32); + r.union(&Rect::new(x, y, x + 1, y + 1)) + }); + let mut out = dst.clone(); + if bbox.is_empty() { + return out; + } + let r = bbox.inflate(1).intersect(&dst.rect); + let (s, d) = (src.crop(r), dst.crop(r)); + let m: Vec = (r.y0..r.y1).flat_map(|y| (r.x0..r.x1).map(move |x| (x, y))).map(|(x, y)| mask[dst.index(x, y)]).collect(); + let mut data = poisson::seamless_clone(d.width(), d.height(), d.ch, &s.data, &d.data, &m); + clamp_samples(fmt, &mut data); + let (n, rw) = (dst.ch, r.width() as usize); + for y in r.y0..r.y1 { + let o = out.index(r.x0, y) * n; + let i = (y - r.y0) as usize * rw * n; + out.data[o..o + rw * n].copy_from_slice(&data[i..i + rw * n]); + } + out +} + +pub(super) fn healing_brush(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "paint.healingBrush"; + let (stroke, id) = parse_brush(s, p, CMD)?; + reject_huge_stroke(CMD, &stroke)?; + let which = sample_layers(p, CMD)?; + let mode = blend_param(p, CMD)?; + let aligned = flag(p, "aligned", true); + let map = clone_mapping(s, p, &stroke, CMD)?; + let off = map.offset(); + let dmg = run_stroke(s, "Healing Brush", id, p, |pre, surf, sel, lock| { + let (bounds, cov) = coverage(CMD, &stroke)?; + let (g, cov) = pad_coverage(bounds, &cov, 2); + let fmt = surf.format(); + let src = clone_sample(pre, id, surf, which, g, &map, false, CMD)?; + // The destination the texture is fitted to: the layer itself, or what the user sees when + // sampling several layers (so healing onto an empty layer matches the composite). + let dst = if which == SampleLayers::Current { Region::read(surf, g) } else { composite_region(pre, id, which, g, fmt) }; + let mask: Vec = cov.iter().map(|c| *c > 0.0).collect(); + let healed = heal_region(&fmt, &src, &dst, &mask); + Ok(apply_coverage(surf, g, &cov, stroke.brush.opacity, sel, lock, &healed, mode)) + })?; + Ok(clone_result(dmg, off, aligned, p, &stroke)) +} + +/// The History Brush's source: the targeted surface (pixels, mask, channel) as it was in History +/// panel row `state` or snapshot `snapshot` (default: the source set in the History panel, +/// `history.setSource`, else the oldest state still held, the "Open" state unless trimmed). +pub(super) fn history_source(s: &Session, id: Option, p: &Value, cmd: &str) -> Result { + let st = s.active().ok_or(EngineError::NoDocument)?; + let source_doc = crate::history_source_cmds::paint_source(st, p, cmd)?; + crate::channel_cmds::read_target_surface(source_doc.as_ref(), id, p) + .cloned() + .map_err(|_| EngineError::Other("the target did not exist (as pixels, a mask or a channel) in that history state".into())) +} + +pub(super) fn history_brush(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "paint.historyBrush"; + let (stroke, id) = parse_brush(s, p, CMD)?; + let mode = blend_param(p, CMD)?; + // The coverage and the source region below are both dense over the stroke's bounds, so a + // thin stroke across a large canvas would still ask for the whole box. Refuse it from the + // points and brush size, before the source surface is cloned or anything is rendered (#4961). + reject_huge_stroke(CMD, &stroke)?; + let live = s.live_commit.take().filter(|l| l.matches(s, CMD, p, &stroke.points)); + let from_live = live.is_some(); + let src_surface = history_source(s, id, p, CMD)?; + let dmg = run_stroke(s, "History Brush", id, p, |_, surf, sel, lock| { + if let Some(l) = live { + *surf = l.surface; + return Ok(l.bounds); + } + let fmt = surf.format(); + let src = if src_surface.format() == fmt { src_surface } else { src_surface.convert(fmt) }; + let (bounds, cov) = coverage(CMD, &stroke)?; + let paint = Region::read(&src, bounds); + Ok(apply_coverage(surf, bounds, &cov, stroke.brush.opacity, sel, lock, &paint, mode)) + })?; + let mut r = json!({ "damage": damage_json(dmg) }); + if from_live { + r["fromLive"] = json!(true); + } + Ok(r) +} + +// --------------------------------------------------------------------------------------------- +// Spot Healing +// --------------------------------------------------------------------------------------------- + +/// Dilate a mask by `r` pixels (square structuring element). +fn dilate(w: usize, h: usize, m: &[bool], r: usize) -> Vec { + let mut tmp = vec![false; w * h]; + for y in 0..h { + for x in 0..w { + if m[y * w + x] { + for xx in x.saturating_sub(r)..(x + r + 1).min(w) { + tmp[y * w + xx] = true; + } + } + } + } + let mut out = vec![false; w * h]; + for y in 0..h { + for x in 0..w { + if tmp[y * w + x] { + for yy in y.saturating_sub(r)..(y + r + 1).min(h) { + out[yy * w + x] = true; + } + } + } + } + out +} + +/// Copy a translated Proximity Match patch from the *pre-healing* pixels. Reading +/// `out` here would make overlapping offsets repeatedly copy the pixels just written, +/// leaving streaks instead of the selected source texture. +pub(super) fn proximity_source_patch(img: &[f32], w: usize, h: usize, ch: usize, mask: &[bool], dx: i32, dy: i32) -> Option> { + if w == 0 || h == 0 || ch == 0 || mask.len() != w.checked_mul(h)? || img.len() != mask.len().checked_mul(ch)? { + return None; + } + let mut out = img.to_vec(); + for (p, masked) in mask.iter().enumerate() { + if !masked { + continue; + } + let x = i32::try_from(p % w).ok()?.checked_add(dx)?; + let y = i32::try_from(p / w).ok()?.checked_add(dy)?; + if x < 0 || y < 0 || x >= i32::try_from(w).ok()? || y >= i32::try_from(h).ok()? { + return None; + } + let src = (usize::try_from(y).ok()?.checked_mul(w)? + usize::try_from(x).ok()?).checked_mul(ch)?; + let dst = p.checked_mul(ch)?; + out.get_mut(dst..dst + ch)?.copy_from_slice(img.get(src..src + ch)?); + } + Some(out) +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum SpotType { + ContentAware, + CreateTexture, + ProximityMatch, +} + +/// Fill the stroke area with no source, then gradient-domain blend it into its surroundings. With +/// `all` (Sample All Layers) it heals what is visible, so it works on an empty layer above the image. +/// +/// Photoshop 25.4 (measured): a dab changes exactly the brush's footprint, and Content-Aware takes +/// its texture from around it, as Edit › Fill does from its window +/// ([`crate::fill_cmds::sampling_window`] of the stroke's bounds), which is what this samples. +fn spot_heal_surface(surf: &mut Surface, pre: &Document, stroke: &Stroke, kind: SpotType, all: bool, sel: Option<&Surface>, lock: bool) -> Result { + let (bounds, cov) = coverage("paint.spotHealing", stroke)?; + let size = stroke.brush.size; + let region_rect = crate::fill_cmds::sampling_window(bounds, pre.bounds()); + if region_rect.is_empty() { + return Ok(Rect::EMPTY); + } + // Proximity Match looks for its source anywhere in that window. + let margin = (region_rect.width().max(region_rect.height()) / 2) as i32; + let fmt = surf.format(); + let img = if all { composite_region(pre, None, SampleLayers::All, region_rect, fmt) } else { Region::read(surf, region_rect) }; + let (w, h, ch) = (img.width(), img.height(), img.ch); + let bw = bounds.width() as usize; + let mut stroke_cov = vec![0.0f32; w * h]; + for (i, c) in cov.iter().enumerate() { + let (x, y) = (bounds.x0 + (i % bw) as i32, bounds.y0 + (i / bw) as i32); + if region_rect.contains(x, y) { + stroke_cov[img.index(x, y)] = *c; + } + } + let hole: Vec = stroke_cov.iter().map(|c| *c > 0.0).collect(); + if !hole.iter().any(|h| *h) { + return Ok(Rect::EMPTY); + } + // Synthesise over a slightly larger domain than the Poisson region, so the solve's boundary pixels + // carry synthesised values that differ from the untouched surroundings: that mismatch is what the + // membrane corrects (otherwise the Dirichlet data would be all zero and the blend a no-op). + let domain = dilate(w, h, &hole, 2); + let heal_mask = dilate(w, h, &hole, 1); + let content_aware = + |img: &[f32]| inpaint::complete(w, h, ch, img, &domain, &CompleteParams::default()).unwrap_or_else(|| poisson::membrane_fill(w, h, ch, img, &domain)); + let filled = match kind { + SpotType::ContentAware => content_aware(&img.data), + SpotType::CreateTexture => inpaint::synthesize(w, h, ch, &img.data, &domain, (size / 4.0).clamp(6.0, 32.0) as usize, 0x5eed), + SpotType::ProximityMatch => { + let ring = (size / 8.0).clamp(3.0, 16.0) as usize; + match inpaint::best_offset(w, h, ch, &img.data, &domain, ring, margin) { + Some((dx, dy)) => proximity_source_patch(&img.data, w, h, ch, &domain, dx, dy).unwrap_or_else(|| content_aware(&img.data)), + None => content_aware(&img.data), + } + } + }; + let src = Region { rect: region_rect, ch, data: filled }; + let healed = heal_region(&fmt, &src, &img, &heal_mask); + let dmg = bounds.intersect(®ion_rect); + let dmg_cov: Vec = (dmg.y0..dmg.y1).flat_map(|y| (dmg.x0..dmg.x1).map(move |x| (x, y))).map(|(x, y)| stroke_cov[img.index(x, y)]).collect(); + Ok(apply_coverage(surf, dmg, &dmg_cov, stroke.brush.opacity, sel, lock, &healed, BlendMode::Normal)) +} + +pub(super) fn spot_healing(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "paint.spotHealing"; + let (stroke, id) = parse_brush(s, p, CMD)?; + reject_huge_stroke(CMD, &stroke)?; + let kind = match string(p, "type", "contentAware") { + "contentAware" => SpotType::ContentAware, + "createTexture" => SpotType::CreateTexture, + "proximityMatch" => SpotType::ProximityMatch, + o => return Err(bad(CMD, format!("unknown type `{o}` (contentAware|createTexture|proximityMatch)"))), + }; + let all = sample_all_layers(p); + let dmg = run_stroke(s, "Spot Healing Brush", id, p, |pre, surf, sel, lock| spot_heal_surface(surf, pre, &stroke, kind, all, sel, lock))?; + Ok(json!({ "damage": damage_json(dmg) })) +} diff --git a/crates/engine/src/retouch_cmds/patch.rs b/crates/engine/src/cmd/retouch_cmds/patch.rs similarity index 100% rename from crates/engine/src/retouch_cmds/patch.rs rename to crates/engine/src/cmd/retouch_cmds/patch.rs diff --git a/crates/engine/src/retouch_cmds/pattern_stamp.rs b/crates/engine/src/cmd/retouch_cmds/pattern_stamp.rs similarity index 100% rename from crates/engine/src/retouch_cmds/pattern_stamp.rs rename to crates/engine/src/cmd/retouch_cmds/pattern_stamp.rs diff --git a/crates/engine/src/retouch_cmds/periodic.rs b/crates/engine/src/cmd/retouch_cmds/periodic.rs similarity index 100% rename from crates/engine/src/retouch_cmds/periodic.rs rename to crates/engine/src/cmd/retouch_cmds/periodic.rs diff --git a/crates/engine/src/retouch_cmds/remove.rs b/crates/engine/src/cmd/retouch_cmds/remove.rs similarity index 100% rename from crates/engine/src/retouch_cmds/remove.rs rename to crates/engine/src/cmd/retouch_cmds/remove.rs diff --git a/crates/engine/src/cmd/retouch_cmds/sampling.rs b/crates/engine/src/cmd/retouch_cmds/sampling.rs new file mode 100644 index 0000000000..31ab9ae99c --- /dev/null +++ b/crates/engine/src/cmd/retouch_cmds/sampling.rs @@ -0,0 +1,97 @@ +use super::*; + +// --------------------------------------------------------------------------------------------- +// Sampling sources +// --------------------------------------------------------------------------------------------- + +/// Which pixels Clone Stamp / Healing Brush sample. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum SampleLayers { + Current, + CurrentAndBelow, + All, +} + +pub(super) fn sample_layers(p: &Value, cmd: &str) -> Result { + match string(p, "sampleLayer", "current") { + "current" => Ok(SampleLayers::Current), + "currentAndBelow" => Ok(SampleLayers::CurrentAndBelow), + "all" => Ok(SampleLayers::All), + o => Err(bad(cmd, format!("unknown sampleLayer `{o}` (current|currentAndBelow|all)"))), + } +} + +/// Composite pixels of `rect` in `fmt` (native channels): the whole document, or the target layer +/// and everything below it. +pub(crate) fn composite_region(pre: &Document, id: Option, which: SampleLayers, rect: Rect, fmt: PixelFormat) -> Region { + let mut doc = pre.clone(); + if which == SampleLayers::CurrentAndBelow + && let Some(id) = id + { + // Hide everything composited after (above) the target in the bottom-to-top walk. + let walk: Vec<(Vec, LayerId)> = pre.walk().into_iter().map(|(p, _, l)| (p, l.id)).collect(); + if let Some(pos) = walk.iter().position(|(_, l)| *l == id) { + for (path, _) in &walk[pos + 1..] { + if let Some(l) = doc.layer_at_mut(path) { + l.visible = false; + } + } + } + } + let buf = photocraft_compose::render(&doc, rect); + let n = fmt.channels(); + let mut out = Region::new(rect, n); + let mut enc = [0.0f32; 8]; + for (i, px) in buf.px.iter().enumerate() { + from_rgba_into(&fmt, *px, &mut enc); + out.data[i * n..(i + 1) * n].copy_from_slice(&enc[..n]); + } + out +} + +/// Pixels to sample at `rect` (document coordinates, already offset to the source position). +pub(super) fn sample(pre: &Document, id: Option, surf: &Surface, which: SampleLayers, rect: Rect) -> Region { + match which { + SampleLayers::Current => Region::read(surf, rect), + _ => composite_region(pre, id, which, rect, surf.format()), + } +} + +/// "Sample All Layers" for Spot Healing, Blur, Sharpen and Smudge (layer pixels only: a mask or +/// channel has nothing to sample from other layers). +pub(super) fn sample_all_layers(p: &Value) -> bool { + flag(p, "sampleAllLayers", false) && targets_pixels(p) +} + +/// Sample All Layers for the sequential-dab tools: each dab's effect runs on a copy of the visible +/// composite (kept across dabs, so a dab sees the earlier ones), and the result is laid onto the +/// layer under the dab. An empty layer above the image so picks up the blurred or smudged picture, +/// and pixels the effect didn't change look as before (they are what was already visible). +pub(super) struct AllLayers<'a> { + pre: &'a Document, + fmt: PixelFormat, + visible: Option, +} + +impl<'a> AllLayers<'a> { + pub(super) fn new(pre: &'a Document, fmt: PixelFormat) -> Self { + Self { pre, fmt, visible: None } + } + + pub(super) fn dab(&mut self, work: &mut Region, fp: &Footprint, effect: impl FnOnce(&mut Region, &Footprint)) { + let (pre, fmt) = (self.pre, self.fmt); + let visible = self.visible.get_or_insert_with(|| composite_region(pre, None, SampleLayers::All, work.rect, fmt)); + if visible.rect != work.rect || visible.ch != work.ch { + return effect(work, fp); + } + effect(visible, fp); + let r = fp.rect.intersect(&work.rect); + for y in r.y0..r.y1 { + for x in r.x0..r.x1 { + if fp.at(x, y) > 0.0 { + work.px_mut(x, y).copy_from_slice(visible.px(x, y)); + } + } + } + } +} diff --git a/crates/engine/src/retouch_cmds/tests.rs b/crates/engine/src/cmd/retouch_cmds/tests.rs similarity index 100% rename from crates/engine/src/retouch_cmds/tests.rs rename to crates/engine/src/cmd/retouch_cmds/tests.rs diff --git a/crates/engine/src/sample_cmds.rs b/crates/engine/src/cmd/sample_cmds.rs similarity index 100% rename from crates/engine/src/sample_cmds.rs rename to crates/engine/src/cmd/sample_cmds.rs diff --git a/crates/engine/src/cmd/sampler_cmds.rs b/crates/engine/src/cmd/sampler_cmds.rs new file mode 100644 index 0000000000..2326e43693 --- /dev/null +++ b/crates/engine/src/cmd/sampler_cmds.rs @@ -0,0 +1,204 @@ +//! Color Sampler points (#1046): numbered colour readings pinned to canvas pixels and listed in +//! the Info panel, so a fixed position can be compared instead of chasing the live pointer. +//! +//! Points are per-document view state ([`crate::DocState::color_samplers`]): they belong to their +//! document, are discarded when it closes, and are not saved to `.pcraft` or PSD. Placing, moving +//! and removing them changes no pixels and adds no History step, so they are not journaled. Each +//! point reads one composite pixel (no averaging); its values match the Info panel's pointer +//! readout (RGB 0–255 and colour-managed CMYK percentages, as in the Color Picker). + +use photocraft_doc::Document; +use serde_json::{Value, json}; + +use crate::commands::CommandSpec; +use crate::{DocState, EngineError, Result, Session}; + +/// Photoshop's Color Sampler limit: at most 10 points per document. +pub const MAX_SAMPLERS: usize = 10; + +fn bad(cmd: &str, msg: impl Into) -> EngineError { + EngineError::BadParams { cmd: cmd.into(), msg: msg.into() } +} + +fn has_doc(s: &Session) -> std::result::Result<(), String> { + s.active().map(|_| ()).ok_or_else(|| "no document open".into()) +} + +/// Colour-managed CMYK, in percent, as the Info panel shows it: the same conversion the Color +/// Picker uses (`photocraft_color::convert::rgb_to_cmyk`: the CMYK profile active on this thread, +/// else the built-in coated CMYK), so both panels agree (#8101). 32-bit samples can lie outside +/// 0..1, so each channel is clamped first (NaN reads as 0), like the RGB readout. +pub fn device_cmyk(r: f32, g: f32, b: f32) -> [i32; 4] { + let unit = |v: f32| if v.is_nan() { 0.0 } else { v.clamp(0.0, 1.0) }; + photocraft_color::convert::rgb_to_cmyk([unit(r), unit(g), unit(b)]).map(|v| (unit(v) * 100.0).round() as i32) +} + +/// The Info-panel values for a sample point at document pixel `pos`: composite RGB 0–255 and +/// colour-managed CMYK percentages (the document's CMYK profile when it has one). One composite +/// pixel, no averaging. +pub fn readout(doc: &Document, pos: [f64; 2]) -> ([i32; 3], [i32; 4]) { + let rgba = crate::sample_cmds::sample_color(doc, None, pos[0], pos[1], 1, crate::sample_cmds::SampleLayers::All); + let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as i32; + let cmyk = photocraft_color::convert::with_cmyk_space(photocraft_compose::cmyk_space(doc).as_ref(), || device_cmyk(rgba[0], rgba[1], rgba[2])); + ([q(rgba[0]), q(rgba[1]), q(rgba[2])], cmyk) +} + +/// One point as the list command reports it. +pub fn point_json(doc: &Document, index: usize, pos: [f64; 2]) -> Value { + let (rgb, cmyk) = readout(doc, pos); + json!({"index": index, "number": index + 1, "position": [pos[0], pos[1]], "rgb": rgb, "cmyk": cmyk}) +} + +fn list_json(doc: &Document, points: &[[f64; 2]]) -> Value { + json!({ + "max": MAX_SAMPLERS, + "samplers": points.iter().enumerate().map(|(i, p)| point_json(doc, i, *p)).collect::>(), + }) +} + +fn coord(cmd: &str, p: &Value, key: &str) -> Result { + p.get(key).and_then(Value::as_f64).filter(|v| v.is_finite()).ok_or_else(|| bad(cmd, format!("`{key}` must be a finite number (document pixels)"))) +} + +/// The pixel a point at document coordinate `(x, y)` sits on, if it is inside the canvas. Whole +/// pixels only: the click's fractional position floors to the pixel it lands on. +fn pixel(doc: &Document, x: f64, y: f64) -> Option<[f64; 2]> { + let (px, py) = (x.floor(), y.floor()); + if px < f64::from(i32::MIN) || px > f64::from(i32::MAX) || py < f64::from(i32::MIN) || py > f64::from(i32::MAX) { + return None; + } + doc.bounds().contains(px as i32, py as i32).then_some([px, py]) +} + +fn index_param(cmd: &str, p: &Value) -> Result { + p.get("index").and_then(Value::as_u64).and_then(|n| usize::try_from(n).ok()).ok_or_else(|| bad(cmd, "pass `index` (0-based)")) +} + +/// Apply a Color Sampler change to the active document: view state, so no history step and no +/// pixels. Bumps the revision (keeping a clean document clean) so UIs refresh. +fn change(s: &mut Session, f: impl FnOnce(&mut DocState) -> Result) -> Result { + let st = s.active_mut().ok_or(EngineError::NoDocument)?; + let r = f(st)?; + let clean = st.saved_revision == st.revision; + st.revision += 1; + if clean { + st.saved_revision = st.revision; + } + st.last_damage = Some(photocraft_geom::Rect::EMPTY); + Ok(r) +} + +fn add(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "view.colorSamplers.add"; + let x = coord(CMD, p, "x")?; + let y = coord(CMD, p, "y")?; + change(s, |st| { + let pos = pixel(&st.doc, x, y).ok_or_else(|| EngineError::Other("the sample point is outside the canvas".into()))?; + if st.color_samplers.len() >= MAX_SAMPLERS { + return Err(EngineError::Other(format!("Color Sampler limit reached: at most {MAX_SAMPLERS} points per document"))); + } + st.color_samplers.push(pos); + let i = st.color_samplers.len() - 1; + Ok(json!({"index": i, "count": st.color_samplers.len(), "point": point_json(&st.doc, i, pos)})) + }) +} + +fn move_point(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "view.colorSamplers.move"; + let i = index_param(CMD, p)?; + let x = coord(CMD, p, "x")?; + let y = coord(CMD, p, "y")?; + change(s, |st| { + let n = st.color_samplers.len(); + if i >= n { + return Err(bad(CMD, format!("no sample point {i} (the document has {n})"))); + } + let pos = pixel(&st.doc, x, y).ok_or_else(|| EngineError::Other("the sample point is outside the canvas".into()))?; + st.color_samplers[i] = pos; + Ok(json!({"index": i, "point": point_json(&st.doc, i, pos)})) + }) +} + +fn delete(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "view.colorSamplers.delete"; + let i = index_param(CMD, p)?; + change(s, |st| { + let n = st.color_samplers.len(); + if i >= n { + return Err(bad(CMD, format!("no sample point {i} (the document has {n})"))); + } + st.color_samplers.remove(i); + Ok(json!({"deleted": 1, "remaining": st.color_samplers.len()})) + }) +} + +fn clear(s: &mut Session, _p: &Value) -> Result { + change(s, |st| { + let n = st.color_samplers.len(); + st.color_samplers.clear(); + Ok(json!({"deleted": n, "remaining": 0})) + }) +} + +fn list(s: &mut Session, _p: &Value) -> Result { + let st = s.active().ok_or(EngineError::NoDocument)?; + Ok(list_json(&st.doc, &st.color_samplers)) +} + +pub fn specs() -> Vec { + vec![ + CommandSpec { + id: "view.colorSamplers.add", + label: "Add Color Sampler", + menu: &[], + shortcut: None, + params: r##"{"x":f64,"y":f64} → the new point {index, number, position, rgb, cmyk}; errors at the 10-point limit or off the canvas"##, + enabled: has_doc, + run: add, + journal: false, + }, + CommandSpec { + id: "view.colorSamplers.move", + label: "Move Color Sampler", + menu: &[], + shortcut: None, + params: r##"{"index":n,"x":f64,"y":f64}"##, + enabled: has_doc, + run: move_point, + journal: false, + }, + CommandSpec { + id: "view.colorSamplers.delete", + label: "Delete Color Sampler", + menu: &[], + shortcut: None, + params: r##"{"index":n}"##, + enabled: has_doc, + run: delete, + journal: false, + }, + CommandSpec { + id: "view.colorSamplers.clear", + label: "Clear Color Samplers", + menu: &[], + shortcut: None, + params: "{}", + enabled: has_doc, + run: clear, + journal: false, + }, + CommandSpec { + id: "view.colorSamplers.list", + label: "Color Samplers", + menu: &[], + shortcut: None, + params: r##"{} → {max, samplers:[{index, number, position, rgb, cmyk}]}"##, + enabled: has_doc, + run: list, + journal: false, + }, + ] +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/sampler_cmds/tests.rs b/crates/engine/src/cmd/sampler_cmds/tests.rs new file mode 100644 index 0000000000..14efb3e524 --- /dev/null +++ b/crates/engine/src/cmd/sampler_cmds/tests.rs @@ -0,0 +1,353 @@ +use super::*; +use photocraft_color::{ColorMode, SampleType}; +use photocraft_doc::{Layer, Size}; +use photocraft_geom::Rect; + +/// A 100×80 white document. +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 100, "height": 80, "background": "white"})).unwrap(); + s +} + +fn list(s: &mut Session) -> Value { + s.execute("view.colorSamplers.list", json!({})).unwrap() +} + +fn points(s: &mut Session) -> Vec { + list(s)["samplers"].as_array().cloned().unwrap_or_default() +} + +#[test] +fn add_reads_the_composite_pixel_and_lists_it() { + let mut s = session(); + let r = s.execute("view.colorSamplers.add", json!({"x": 5, "y": 6})).unwrap(); + assert_eq!(r["index"], 0); + assert_eq!(r["count"], 1); + assert_eq!(r["point"]["number"], 1); + assert_eq!(r["point"]["position"], json!([5.0, 6.0])); + assert_eq!(r["point"]["rgb"], json!([255, 255, 255])); + assert_eq!(r["point"]["cmyk"], json!([0, 0, 0, 0])); + let l = list(&mut s); + assert_eq!(l["max"], 10); + assert_eq!(l["samplers"].as_array().unwrap().len(), 1); + assert_eq!(l["samplers"][0]["position"], json!([5.0, 6.0])); +} + +#[test] +fn fractional_clicks_floor_to_the_pixel() { + let mut s = session(); + let r = s.execute("view.colorSamplers.add", json!({"x": 5.9, "y": 6.1})).unwrap(); + assert_eq!(r["point"]["position"], json!([5.0, 6.0])); +} + +#[test] +fn add_reads_an_actual_painted_pixel() { + // A black pixel at (3, 3) of an otherwise white document. + let mut s = session(); + s.edit("paint", |doc, _| { + let surf = doc.layers[0].surface_mut().unwrap(); + let black = photocraft_raster::from_rgba(&surf.format(), [0.0, 0.0, 0.0, 1.0]); + surf.fill_rect(Rect::new(3, 3, 4, 4), &black); + Ok(()) + }) + .unwrap(); + let r = s.execute("view.colorSamplers.add", json!({"x": 3, "y": 3})).unwrap(); + assert_eq!(r["point"]["rgb"], json!([0, 0, 0])); + assert_eq!(r["point"]["cmyk"], json!(device_cmyk(0.0, 0.0, 0.0)), "the profile's black, not the naive 0/0/0/100"); + // Painting over the point changes its readout (the list is computed live). + s.edit("paint", |doc, _| { + let surf = doc.layers[0].surface_mut().unwrap(); + let red = photocraft_raster::from_rgba(&surf.format(), [1.0, 0.0, 0.0, 1.0]); + surf.fill_rect(Rect::new(3, 3, 4, 4), &red); + Ok(()) + }) + .unwrap(); + assert_eq!(points(&mut s)[0]["rgb"], json!([255, 0, 0])); +} + +#[test] +fn ten_points_then_the_limit() { + let mut s = session(); + for i in 0..10 { + s.execute("view.colorSamplers.add", json!({"x": i, "y": 0})).unwrap(); + } + assert_eq!(points(&mut s).len(), 10); + let err = s.execute("view.colorSamplers.add", json!({"x": 20, "y": 0})).unwrap_err().to_string(); + assert!(err.contains("limit"), "{err}"); + assert_eq!(points(&mut s).len(), 10); +} + +#[test] +fn move_delete_and_clear() { + let mut s = session(); + s.execute("view.colorSamplers.add", json!({"x": 5, "y": 5})).unwrap(); + s.execute("view.colorSamplers.add", json!({"x": 50, "y": 50})).unwrap(); + let r = s.execute("view.colorSamplers.move", json!({"index": 0, "x": 10, "y": 20})).unwrap(); + assert_eq!(r["point"]["position"], json!([10.0, 20.0])); + assert_eq!(points(&mut s)[0]["position"], json!([10.0, 20.0])); + s.execute("view.colorSamplers.delete", json!({"index": 1})).unwrap(); + assert_eq!(points(&mut s).len(), 1); + // The remaining point is the moved #1. + assert_eq!(points(&mut s)[0]["position"], json!([10.0, 20.0])); + let r = s.execute("view.colorSamplers.clear", json!({})).unwrap(); + assert_eq!(r["deleted"], 1); + assert!(points(&mut s).is_empty()); +} + +#[test] +fn placing_and_moving_add_no_history_and_change_no_pixels() { + let mut s = session(); + let before = s.active().unwrap().doc.layers[0].surface().unwrap().pixel(5, 5); + let past = s.active().unwrap().history.past_len(); + s.execute("view.colorSamplers.add", json!({"x": 5, "y": 5})).unwrap(); + s.execute("view.colorSamplers.move", json!({"index": 0, "x": 9, "y": 9})).unwrap(); + s.execute("view.colorSamplers.delete", json!({"index": 0})).unwrap(); + assert_eq!(s.active().unwrap().history.past_len(), past, "no history steps"); + assert_eq!(s.active().unwrap().doc.layers[0].surface().unwrap().pixel(5, 5), before, "no pixels changed"); + assert!(!s.active().unwrap().is_dirty(), "a clean document stays clean"); +} + +#[test] +fn points_belong_to_their_document() { + let mut s = session(); + s.execute("view.colorSamplers.add", json!({"x": 5, "y": 5})).unwrap(); + s.execute("file.new", json!({"width": 40, "height": 40, "background": "white"})).unwrap(); + assert!(points(&mut s).is_empty(), "the new document has no points"); + s.execute("document.activate", json!({"document": 0})).unwrap(); + assert_eq!(points(&mut s).len(), 1, "the first document kept its point"); + // Closing the second document leaves the first's points alone. + s.execute("file.close", json!({"document": 1})).unwrap(); + assert_eq!(points(&mut s).len(), 1); + // Closing the first discards its points with it. + s.execute("file.close", json!({"document": 0})).unwrap(); + assert!(s.execute("view.colorSamplers.list", json!({})).is_err(), "no document open"); +} + +#[test] +fn a_crop_drops_points_outside_the_new_canvas() { + let mut s = session(); + s.execute("view.colorSamplers.add", json!({"x": 5, "y": 5})).unwrap(); + s.execute("view.colorSamplers.add", json!({"x": 50, "y": 50})).unwrap(); + s.execute("image.crop", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + let p = points(&mut s); + assert_eq!(p.len(), 1, "the outside point was removed"); + assert_eq!(p[0]["position"], json!([5.0, 5.0])); + assert_eq!(s.take_samplers_removed(), 1, "one removed point reported"); + assert_eq!(s.take_samplers_removed(), 0, "reported once"); +} + +#[test] +fn a_crop_moves_points_with_their_pixels() { + // A crop from a non-zero origin moves the canvas: the point follows its pixel. + let mut s = session(); + s.execute("view.colorSamplers.add", json!({"x": 50, "y": 40})).unwrap(); + s.execute("image.crop", json!({"x": 40, "y": 30, "width": 20, "height": 20})).unwrap(); + let p = points(&mut s); + assert_eq!(p.len(), 1); + assert_eq!(p[0]["position"], json!([10.0, 10.0]), "moved by (-40, -30)"); + assert_eq!(s.take_samplers_removed(), 0, "nothing removed"); +} + +#[test] +fn a_canvas_size_shift_moves_points() { + // Canvas Size anchored bottom-right shifts the canvas origin by (+20, +20). + let mut s = session(); + s.execute("view.colorSamplers.add", json!({"x": 30, "y": 30})).unwrap(); + s.execute("image.canvasSize", json!({"width": 120, "height": 100, "anchor": "bottomRight"})).unwrap(); + let p = points(&mut s); + assert_eq!(p.len(), 1); + assert_eq!(p[0]["position"], json!([50.0, 50.0]), "moved by the canvas shift"); +} + +#[test] +fn a_right_angle_rotation_moves_points() { + // 90° clockwise about the centre: pixel (x, y) of the 100×80 canvas goes to (79 - y, x). + let mut s = session(); + s.execute("view.colorSamplers.add", json!({"x": 50, "y": 40})).unwrap(); + s.execute("image.rotation.arbitrary", json!({"angle": 90, "direction": "cw"})).unwrap(); + let p = points(&mut s); + assert_eq!(p.len(), 1); + let pos = p[0]["position"].as_array().unwrap(); + let (x, y) = (pos[0].as_f64().unwrap(), pos[1].as_f64().unwrap()); + assert!((x - 39.0).abs() < 1e-6 && (y - 50.0).abs() < 1e-6, "{pos:?}"); +} + +#[test] +fn flips_and_right_angle_turns_keep_points_on_their_pixel() { + use crate::canvas_geom::Turn; + for (id, turn) in [ + ("image.imageRotation.flipCanvasHorizontal", Turn::FlipHorizontal), + ("image.imageRotation.flipCanvasVertical", Turn::FlipVertical), + ("image.imageRotation.180", Turn::Rotate180), + ("image.imageRotation.90cw", Turn::Cw90), + ("image.imageRotation.90ccw", Turn::Ccw90), + ] { + // A black pixel at (3, 3) of a white 100×80 document, with a point on it. + let mut s = session(); + s.edit("paint", |doc, _| { + let surf = doc.layers[0].surface_mut().unwrap(); + let black = photocraft_raster::from_rgba(&surf.format(), [0.0, 0.0, 0.0, 1.0]); + surf.fill_rect(Rect::new(3, 3, 4, 4), &black); + Ok(()) + }) + .unwrap(); + s.execute("view.colorSamplers.add", json!({"x": 3, "y": 3})).unwrap(); + s.execute(id, json!({})).unwrap(); + let (x, y) = turn.pixel_map(100, 80)(3, 3); + let p = points(&mut s); + assert_eq!(p.len(), 1, "{id}"); + assert_eq!(p[0]["position"], json!([f64::from(x), f64::from(y)]), "{id}"); + assert_eq!(p[0]["rgb"], json!([0, 0, 0]), "{id}"); + } +} + +#[test] +fn an_arbitrary_rotation_keeps_points_on_their_pixel() { + // The pixel at (3, 3) of the 100×80 document, and where each turn moves it. + for (angle, direction, at) in [(90, "cw", [76.0, 3.0]), (90, "ccw", [3.0, 96.0]), (180, "cw", [96.0, 76.0])] { + let mut s = session(); + s.edit("paint", |doc, _| { + let surf = doc.layers[0].surface_mut().unwrap(); + let black = photocraft_raster::from_rgba(&surf.format(), [0.0, 0.0, 0.0, 1.0]); + surf.fill_rect(Rect::new(3, 3, 4, 4), &black); + Ok(()) + }) + .unwrap(); + s.execute("view.colorSamplers.add", json!({"x": 3, "y": 3})).unwrap(); + s.execute("view.colorSamplers.add", json!({"x": 0, "y": 0})).unwrap(); + s.execute("image.rotation.arbitrary", json!({"angle": angle, "direction": direction})).unwrap(); + assert_eq!(s.take_samplers_removed(), 0, "{angle} {direction}: the corner point stays on the canvas"); + let p = points(&mut s); + assert_eq!(p.len(), 2, "{angle} {direction}: the corner point stays on the canvas"); + assert_eq!(p[0]["position"], json!(at), "{angle} {direction}"); + assert_eq!(p[0]["rgb"], json!([0, 0, 0]), "{angle} {direction}"); + } +} + +#[test] +fn a_rotated_crop_moves_points() { + // The crop frame is centred on the point's pixel; turned 90° that pixel lands at (10, 9). + let mut s = session(); + s.edit("paint", |doc, _| { + let surf = doc.layers[0].surface_mut().unwrap(); + let black = photocraft_raster::from_rgba(&surf.format(), [0.0, 0.0, 0.0, 1.0]); + surf.fill_rect(Rect::new(50, 40, 51, 41), &black); + Ok(()) + }) + .unwrap(); + s.execute("view.colorSamplers.add", json!({"x": 50, "y": 40})).unwrap(); + s.execute("image.crop", json!({"x": 40, "y": 30, "width": 20, "height": 20, "angle": 90})).unwrap(); + let p = points(&mut s); + assert_eq!(p.len(), 1); + assert_eq!(p[0]["position"], json!([10.0, 9.0])); + assert_eq!(p[0]["rgb"], json!([0, 0, 0])); +} + +#[test] +fn a_crop_to_a_target_size_scales_points() { + // The crop resamples the 20 x 20 area to 40 x 40: the point (10, 10 after the shift; 10, 9 + // turned 90°, as in `a_rotated_crop_moves_points`) doubles. + for (angle, at) in [(None, [20.0, 20.0]), (Some(90), [20.0, 18.0])] { + let mut s = session(); + s.execute("view.colorSamplers.add", json!({"x": 50, "y": 40})).unwrap(); + let mut p = json!({"x": 40, "y": 30, "width": 20, "height": 20, "targetWidth": 40, "targetHeight": 40}); + if let Some(a) = angle { + p["angle"] = json!(a); + } + s.execute("image.crop", p).unwrap(); + let p = points(&mut s); + assert_eq!(p.len(), 1, "angle {angle:?}"); + assert_eq!(p[0]["position"], json!(at), "angle {angle:?}"); + assert_eq!(s.take_samplers_removed(), 0, "angle {angle:?}"); + } +} + +#[test] +fn bad_params_and_no_document_are_errors_not_panics() { + let mut s = Session::new(); + for id in ["view.colorSamplers.add", "view.colorSamplers.move", "view.colorSamplers.delete", "view.colorSamplers.clear", "view.colorSamplers.list"] { + assert!(s.execute(id, json!({})).is_err(), "{id} without a document"); + } + let mut s = session(); + for (id, p) in [ + ("view.colorSamplers.add", json!({})), + ("view.colorSamplers.add", json!({"x": "a", "y": 1})), + ("view.colorSamplers.add", json!({"x": 1e300, "y": 1})), + ("view.colorSamplers.add", json!({"x": 5, "y": f64::NAN})), + ("view.colorSamplers.add", json!({"x": -1, "y": 5})), + ("view.colorSamplers.add", json!({"x": 5, "y": 1000})), + ("view.colorSamplers.move", json!({"index": 0, "x": 1, "y": 1})), + ("view.colorSamplers.delete", json!({"index": 0})), + ("view.colorSamplers.delete", json!({})), + ("view.colorSamplers.move", json!({"index": 4_294_967_296u64, "x": 1, "y": 1})), + ] { + assert!(matches!(s.execute(id, p.clone()), Err(EngineError::BadParams { .. }) | Err(EngineError::Other(_))), "{id} {p}"); + } + // An off-canvas point is refused and places nothing. + assert!(points(&mut s).is_empty()); +} + +/// The Info panel and the Color Picker read CMYK through one conversion (#8101): the +/// colour-managed `rgb_to_cmyk`, not a naive formula that disagrees with it by tens of percent. +#[test] +fn device_cmyk_agrees_with_the_color_picker_conversion() { + for rgb in [[1.0, 1.0, 1.0], [0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.5, 0.5, 0.5], [0.2, 0.6, 0.9], [1.0, 0.93, 0.0]] { + let picker = photocraft_color::convert::rgb_to_cmyk(rgb).map(|v| (v * 100.0).round() as i32); + assert_eq!(device_cmyk(rgb[0], rgb[1], rgb[2]), picker, "{rgb:?}"); + } + assert_eq!(device_cmyk(1.0, 1.0, 1.0), [0, 0, 0, 0]); + assert_ne!(device_cmyk(1.0, 0.0, 0.0), [0, 100, 100, 0], "pure red is not the naive 0/100/100/0"); +} + +/// 32-bit samples can lie outside 0..1 (or be NaN); the CMYK readout clamps them like the RGB +/// readout does instead of reporting K:-50% or C:120% (#4191). +#[test] +fn device_cmyk_clamps_out_of_range_and_nan_samples() { + assert_eq!(device_cmyk(1.5, 1.5, 1.5), [0, 0, 0, 0]); + assert_eq!(device_cmyk(2.0, 0.0, 0.0), device_cmyk(1.0, 0.0, 0.0)); + let in_range = |c: [i32; 4]| c.iter().all(|v| (0..=100).contains(v)); + for (r, g, b) in [(-0.2, 0.5, 0.5), (-1.0, -1.0, -1.0), (f32::NAN, 0.5, 0.5), (f32::NAN, f32::NAN, f32::NAN), (f32::INFINITY, f32::NEG_INFINITY, 0.5)] { + let c = device_cmyk(r, g, b); + assert!(in_range(c), "{r} {g} {b} -> {c:?}"); + } + assert_eq!(device_cmyk(f32::NAN, f32::NAN, f32::NAN), device_cmyk(0.0, 0.0, 0.0)); +} + +#[test] +fn hdr_pixel_on_a_32_bit_document_reads_in_range() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8, "depth": 32, "background": "white"})).unwrap(); + s.edit("paint", |doc, _| { + let surf = doc.layers[0].surface_mut().unwrap(); + let hdr = photocraft_raster::from_rgba(&surf.format(), [2.0, 2.0, 2.0, 1.0]); + surf.fill_rect(Rect::new(3, 3, 4, 4), &hdr); + Ok(()) + }) + .unwrap(); + let r = s.execute("view.colorSamplers.add", json!({"x": 3, "y": 3})).unwrap(); + assert_eq!(r["point"]["rgb"], json!([255, 255, 255])); + assert_eq!(r["point"]["cmyk"], json!([0, 0, 0, 0])); +} + +#[test] +fn points_work_at_every_depth_and_mode() { + for (mode, depth) in [("rgb", 8), ("rgb", 16), ("rgb", 32), ("grayscale", 8), ("cmyk", 8), ("lab", 8)] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 20, "height": 20, "mode": mode, "depth": depth, "background": "white"})).unwrap(); + let r = s.execute("view.colorSamplers.add", json!({"x": 10, "y": 10})).unwrap(); + let rgb = r["point"]["rgb"].as_array().unwrap(); + assert_eq!(rgb.len(), 3); + assert!(rgb.iter().all(|v| v.as_i64().is_some_and(|n| (0..=255).contains(&n))), "{mode} {depth}: {rgb:?}"); + } +} + +/// The mode and depth only affect the composite the readout samples, not the point model. +#[test] +fn document_helpers_are_not_disturbed() { + let mut d = Document::new("t", Size::new(4, 4), ColorMode::Rgb, SampleType::U8); + d.layers.push(Layer::raster("Background", d.pixel_format())); + assert_eq!(pixel(&d, 0.0, 0.0), Some([0.0, 0.0])); + assert_eq!(pixel(&d, 3.9, 3.9), Some([3.0, 3.0])); + assert_eq!(pixel(&d, 4.0, 0.0), None); +} diff --git a/crates/engine/src/select_extra_cmds.rs b/crates/engine/src/cmd/select_extra_cmds.rs similarity index 100% rename from crates/engine/src/select_extra_cmds.rs rename to crates/engine/src/cmd/select_extra_cmds.rs diff --git a/crates/engine/src/cmd/selection_cmds.rs b/crates/engine/src/cmd/selection_cmds.rs new file mode 100644 index 0000000000..4b8da7e796 --- /dev/null +++ b/crates/engine/src/cmd/selection_cmds.rs @@ -0,0 +1,713 @@ +//! Select menu and selection tools: Magic Wand, Color Range, Modify +//! (expand/contract/border/smooth/feather), Grow, Similar, Lasso. +//! Selections are grayscale coverage surfaces clipped to the canvas. + +use photocraft_algo::selection::{self as sel, SelectionMode}; +use photocraft_doc::Document; +use photocraft_geom::Rect; +use photocraft_raster::Surface; +use serde_json::{Value, json}; + +use crate::commands::CommandSpec; +use crate::{EngineError, Result, Session}; + +fn has_doc(s: &Session) -> std::result::Result<(), String> { + s.active().map(|_| ()).ok_or_else(|| "no document open".into()) +} +fn has_selection(s: &Session) -> std::result::Result<(), String> { + s.active().filter(|d| d.doc.selection.is_some()).map(|_| ()).ok_or_else(|| "no selection".into()) +} + +fn f(p: &Value, k: &str, d: f32) -> f32 { + p.get(k).and_then(Value::as_f64).map_or(d, |v| v as f32) +} +fn b(p: &Value, k: &str, d: bool) -> bool { + p.get(k).and_then(Value::as_bool).unwrap_or(d) +} +fn mode(p: &Value) -> SelectionMode { + SelectionMode::parse(p.get("mode").and_then(Value::as_str).unwrap_or("replace")) +} + +/// A Color Range replacement is scoped to the selection that was active when it opened. +/// Explicit add/subtract/intersect operations retain their normal selection-combine semantics. +fn scope_color_range(mask: &mut [f32], doc: &Document, area: Rect, m: SelectionMode) { + if m != SelectionMode::Replace { + return; + } + if let Some(selection) = doc.selection.as_ref() { + let previous = sel::mask_from_surface(Some(selection), area); + for (value, bound) in mask.iter_mut().zip(previous) { + *value = value.min(bound); + } + } +} + +/// RGBA pixels the tools sample: the composite, or the active layer. +fn sample_pixels(s: &Session, all_layers: bool) -> Result<(Rect, Vec<[f32; 4]>)> { + let d = s.active().ok_or(EngineError::NoDocument)?; + let area = d.doc.bounds(); + // Match the decoders' raster budget before either the layer or composite path allocates. + let len = area.size().area(); + let max_bytes: u64 = if cfg!(target_pointer_width = "64") { 8 << 30 } else { 2 << 30 }; + if len > max_bytes / std::mem::size_of::<[f32; 4]>() as u64 { + return Err(EngineError::Other("the canvas is too large to sample for a selection".into())); + } + let layer = d.active_layer.and_then(|id| d.doc.layer(id)).and_then(|l| l.surface()); + match (all_layers, layer) { + (false, Some(surf)) => { + let len = usize::try_from(len).map_err(|_| EngineError::Other("the canvas is too large to sample for a selection".into()))?; + let mut px = crate::allocation::filled(len, [0.0f32; 4], "sampling pixels for a selection")?; + surf.read_rgba_into(area, &mut px); + Ok((area, px)) + } + _ => Ok((area, photocraft_compose::render(&d.doc, area).px)), + } +} + +fn set_selection(s: &mut Session, label: &str, area: Rect, mask: Vec, m: SelectionMode) -> Result { + let selected = s.edit(label, |doc, _| { + doc.selection = sel::combine(doc.selection.as_ref(), &mask, area, m); + Ok(doc.selection.is_some()) + })?; + Ok(json!({ "selected": selected })) +} + +fn current_mask(doc: &Document) -> (Rect, Vec) { + let area = doc.bounds(); + (area, sel::mask_from_surface(doc.selection.as_ref(), area)) +} + +/// Grayscale the canvas is actually showing, as opaque RGBA, when that is not the colour +/// composite: a gray layer-mask view, or — with every colour channel hidden — the first +/// visible alpha, Quick Mask, or the active layer's mask. The Magic Wand selects from this +/// so a white alpha stays one region instead of breaking up along the RGB underneath. +fn shown_gray(s: &Session) -> Option<(Rect, Vec<[u8; 4]>)> { + let st = s.active()?; + let doc = &st.doc; + let area = doc.bounds(); + let v = &st.channel_view; + let colors_off = v.visible_colors(crate::channel_cmds::color_count(doc)) == 0; + let surf = if let Some((mask, crate::mask_view_cmds::MaskViewMode::Gray)) = v.shown_layer_mask(doc) { + &mask.surface + } else if colors_off { + if let Some(i) = (0..doc.channels.len()).find(|i| v.alpha_shown(*i)) { + &doc.channels[i].surface + } else if let Some(q) = doc.quick_mask.as_ref().filter(|_| !v.quick_mask_hidden) { + &q.surface + } else if let Some((mask, _)) = v.shown_layer_mask(doc) { + &mask.surface + } else { + &st.active_layer.and_then(|id| doc.layer(id))?.mask.as_ref()?.surface + } + } else { + return None; + }; + Some((area, sel::rgba8_image(surf, area))) +} + +/// 8-bit RGBA of the active layer (or the composite with `all_layers`) over the canvas. +pub(crate) fn sample_rgba8(s: &Session, all_layers: bool) -> Result<(Rect, Vec<[u8; 4]>)> { + let d = s.active().ok_or(EngineError::NoDocument)?; + let area = d.doc.bounds(); + let layer = d.active_layer.and_then(|id| d.doc.layer(id)).and_then(|l| l.surface()); + match (all_layers, layer) { + (false, Some(surf)) => Ok((area, sel::rgba8_image(surf, area))), + _ => { + let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; + Ok((area, photocraft_compose::render(&d.doc, area).px.iter().map(|p| p.map(q)).collect())) + } + } +} + +fn magic_wand(s: &mut Session, p: &Value) -> Result { + let (x, y) = (f(p, "x", 0.0).floor() as i32, f(p, "y", 0.0).floor() as i32); + let (area, img) = match shown_gray(s) { + Some(plane) => plane, + None => sample_rgba8(s, b(p, "sampleAllLayers", false))?, + }; + let region = sel::wand_region(&img, area, (x, y), f(p, "tolerance", 32.0), b(p, "contiguous", true), b(p, "antiAlias", true)); + drop(img); + let m = mode(p); + let selected = s.edit("Magic Wand", |doc, _| { + doc.selection = sel::combine_region(doc.selection.as_ref(), region.as_ref(), m); + Ok(doc.selection.is_some()) + })?; + Ok(json!({ "selected": selected })) +} + +fn parse_color(p: &Value) -> [f32; 3] { + match p.get("color") { + Some(Value::Array(a)) if a.len() >= 3 => [0, 1, 2].map(|i| a[i].as_f64().unwrap_or(0.0) as f32), + Some(Value::String(h)) => { + let h = h.trim_start_matches('#'); + let c = |i: usize| h.get(i..i + 2).and_then(|x| u8::from_str_radix(x, 16).ok()).map_or(0.0, |v| f32::from(v) / 255.0); + [c(0), c(2), c(4)] + } + _ => [0.0; 3], + } +} + +/// Eyedropper samples from `key` (`[[x, y], …]` in document pixels): the colour under each point +/// and where it was picked (area-local, for Localized Color Clusters). +fn eyedropper_samples(p: &Value, key: &str, area: Rect, px: &[[f32; 4]], bad: &impl Fn(String) -> EngineError) -> Result> { + let Some(pts) = p.get(key) else { return Ok(Vec::new()) }; + let pts = pts.as_array().ok_or_else(|| bad(format!("`{key}` must be [[x, y], …]")))?; + let w = area.width() as usize; + let mut out = Vec::with_capacity(pts.len().min(4096)); + for pt in pts { + let xy = pt.as_array().and_then(|a| match a.as_slice() { + [x, y] => Some((x.as_f64()?, y.as_f64()?)), + _ => None, + }); + let Some((x, y)) = xy.filter(|(x, y)| x.is_finite() && y.is_finite()) else { + return Err(bad(format!("bad point {pt} in `{key}` (want [x, y])"))); + }; + let (xi, yi) = (x.floor() as i32, y.floor() as i32); + let q = if area.contains(xi, yi) { px.get((yi - area.y0) as usize * w + (xi - area.x0) as usize) } else { None }; + let Some(&[r, g, b, _]) = q else { + return Err(bad(format!("point [{x}, {y}] in `{key}` is outside the canvas"))); + }; + out.push(sel::RangeSample { color: [r, g, b], at: Some(((xi - area.x0) as f32, (yi - area.y0) as f32)) }); + } + Ok(out) +} + +/// Composite RGB (the compositor's output profile for the document) → CIE Lab D50. +fn lab_transform(s: &Session) -> Result> { + let d = s.active().ok_or(EngineError::NoDocument)?; + let src = crate::color_cmds::composite_profile(&d.doc); + photocraft_cms::cached(&src, photocraft_cms::Builtin::LabD50.profile(), photocraft_cms::TransformOptions::default()) + .map_err(|e| EngineError::Other(format!("colour management: {e}"))) +} + +/// The Lab profile's normalised encoding (ICC v4) → L 0–100, a and b −128–127. +fn decode_lab(v: [f32; 3]) -> [f32; 3] { + [v[0] * 100.0, v[1] * 255.0 - 128.0, v[2] * 255.0 - 128.0] +} + +fn colour_to_lab(t: &photocraft_cms::Transform, rgb: [f32; 3]) -> [f32; 3] { + let mut out = [0.0f32; 3]; + t.eval(&rgb.map(|v| v.clamp(0.0, 1.0)), &mut out); + decode_lab(out) +} + +/// RGBA pixels → Lab + alpha (L, a, b, alpha). +fn pixels_to_lab(t: &photocraft_cms::Transform, px: &[[f32; 4]]) -> Vec<[f32; 4]> { + let src: Vec<[f32; 4]> = px.iter().map(|p| [p[0].clamp(0.0, 1.0), p[1].clamp(0.0, 1.0), p[2].clamp(0.0, 1.0), p[3]]).collect(); + let mut out = vec![[0.0f32; 4]; px.len()]; + t.convert_f32(src.as_flattened(), 4, out.as_flattened_mut(), 4, true); + for p in &mut out { + let [l, a, b] = decode_lab([p[0], p[1], p[2]]); + *p = [l, a, b, p[3]]; + } + out +} + +/// Prepared Sampled Colors query shared by the command and its interactive preview. +/// Samples always come from the original document; reducing an image must not change them. +pub struct ColorRangeSamples { + to_lab: std::sync::Arc, + range: sel::LabRange, + grid: bool, + fuzziness: f32, + localized: Option, + plus_at: Vec<(f32, f32)>, +} + +impl ColorRangeSamples { + /// Prepare the query without allocating a full-resolution composite. Point samples use + /// exactly the same compositor/profile as the final selection. + pub fn new(s: &Session, p: &Value) -> Result { + let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; + let area = doc.bounds(); + let bad = |msg: String| EngineError::BadParams { cmd: "select.colorRange".into(), msg }; + let sample = |key: &str| -> Result> { + let Some(pts) = p.get(key) else { return Ok(Vec::new()) }; + let pts = pts.as_array().ok_or_else(|| bad(format!("`{key}` must be [[x, y], …]")))?; + let mut samples = Vec::new(); + for point in pts { + let q = point.as_array().and_then(|v| match v.as_slice() { + [x, y] => Some((x.as_f64()?, y.as_f64()?)), + _ => None, + }); + let Some((x, y)) = q.filter(|(x, y)| x.is_finite() && y.is_finite()) else { + return Err(bad(format!("bad point {point} in `{key}` (want [x, y])"))); + }; + let (x, y) = (x.floor() as i32, y.floor() as i32); + if !area.contains(x, y) { + return Err(bad(format!("point [{x}, {y}] in `{key}` is outside the canvas"))); + } + let r = Rect::from_xywh(x, y, 1, 1); + let pixel = if !b(p, "sampleAllLayers", true) { + s.active().and_then(|d| d.active_layer.and_then(|id| d.doc.layer(id))).and_then(|l| l.surface()).map(|surf| { + let mut px = [[0.0; 4]]; + surf.read_rgba_into(r, &mut px); + px[0] + }) + } else { + None + }; + let px = match pixel { + Some(px) => px, + None => photocraft_compose::render(doc, r).px.first().copied().unwrap_or([0.0; 4]), + }; + samples.push(sel::RangeSample { color: [px[0], px[1], px[2]], at: Some(((x - area.x0) as f32, (y - area.y0) as f32)) }); + } + Ok(samples) + }; + Self::with_samples(s, p, area, &sample("points")?, &sample("subtractPoints")?) + } + + fn with_samples(s: &Session, p: &Value, area: Rect, plus: &[sel::RangeSample], minus: &[sel::RangeSample]) -> Result { + let bad = |msg: String| EngineError::BadParams { cmd: "select.colorRange".into(), msg }; + let fuzz = |d: f32| f(p, "fuzziness", d).max(0.0); + // The order the eyedropper clicks came in ("+" a point, "-" a subtracted point): + // Photoshop applies them one after another. Without it, all additions come first. + let order: Vec = match p.get("order") { + None => std::iter::repeat_n(true, plus.len()).chain(std::iter::repeat_n(false, minus.len())).collect(), + Some(o) => { + let o = o.as_array().ok_or_else(|| bad("`order` must be a list of \"+\" and \"-\"".into()))?; + let order = o + .iter() + .map(|v| match v.as_str() { + Some("+") => Ok(true), + Some("-") => Ok(false), + _ => Err(bad(format!("bad entry {v} in `order` (want \"+\" or \"-\")"))), + }) + .collect::>>()?; + if order.iter().filter(|x| **x).count() != plus.len() || order.iter().filter(|x| !**x).count() != minus.len() { + return Err(bad("`order` must list each of `points` (\"+\") and `subtractPoints` (\"-\") once".into())); + } + order + } + }; + let mut fixed: Vec<[f32; 3]> = Vec::new(); + if let Some(cs) = p.get("colors") { + let cs = cs.as_array().ok_or_else(|| bad("`colors` must be a list of colours".into()))?; + fixed.extend(cs.iter().map(|c| parse_color(&json!({ "color": c })))); + } + if p.get("color").is_some() { + fixed.push(parse_color(p)); + } + // Localized Color Clusters: Range is a percentage of the canvas's longer side. + let plus_at: Vec<(f32, f32)> = plus.iter().filter_map(|x| x.at).collect(); + let localized = if b(p, "localized", false) { + if plus_at.is_empty() { + return Err(bad("localized clusters need eyedropper `points`".into())); + } + Some(f(p, "range", 100.0).clamp(0.0, 100.0) / 100.0 * area.width().max(area.height()) as f32) + } else { + None + }; + // Photoshop compares colours in Lab, through the document's profile + // (sel::lab_range_coverage). The samples span one Lab box; "Add to Sample" grows it, + // "Subtract from Sample" reshapes it (sel::LabRange::subtract). + let to_lab = lab_transform(s)?; + // 8-bit documents are compared on the 8-bit Lab grid, samples and pixels alike. + let grid = s.active().is_some_and(|d| d.doc.depth == photocraft_doc::SampleType::U8); + let q = |c: [f32; 3]| if grid { sel::quantize_lab8(c) } else { c }; + let colour_to_lab = |t: &photocraft_cms::Transform, c: [f32; 3]| q(colour_to_lab(t, c)); + let foreground = || { + let [r, g, b, _] = s.tools.foreground; + sel::LabRange::point(colour_to_lab(&to_lab, [r, g, b])) + }; + let fixed_lab: Vec<[f32; 3]> = fixed.iter().map(|c| colour_to_lab(&to_lab, *c)).collect(); + let mut range = sel::LabRange::spanning(&fixed_lab); + let (mut pi, mut mi) = (plus.iter(), minus.iter()); + for add in order { + if add { + if let Some(x) = pi.next() { + let c = colour_to_lab(&to_lab, x.color); + range = Some(range.map_or(sel::LabRange::point(c), |r| r.grow(&c))); + } + } else if let Some(x) = mi.next() { + range = Some(range.unwrap_or_else(foreground).subtract(&colour_to_lab(&to_lab, x.color), fuzz(40.0))); + } + } + let range = range.unwrap_or_else(foreground); + Ok(Self { to_lab, range, grid, fuzziness: fuzz(40.0), localized, plus_at }) + } + + /// Coverage of a composite rectangle. `scale` is the original document pixels represented + /// by one input pixel; `origin` is in original document pixels (for a visible canvas crop). + pub fn coverage(&self, px: &[[f32; 4]], width: usize, scale: f32, origin: [f32; 2]) -> Vec { + let mut lab = pixels_to_lab(&self.to_lab, px); + if self.grid { + for p in &mut lab { + let [l, a, b] = sel::quantize_lab8([p[0], p[1], p[2]]); + *p = [l, a, b, p[3]]; + } + } + let scale = if scale.is_finite() && scale > 0.0 { scale } else { 1.0 }; + let points: Vec<_> = self.plus_at.iter().map(|(x, y)| ((x - origin[0]) / scale, (y - origin[1]) / scale)).collect(); + sel::color_range_lab(&lab, width, &self.range, self.fuzziness, self.grid, self.localized.map(|r| (r / scale, points.as_slice()))) + } +} + +fn color_range(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "select.colorRange"; + let bad = |msg: String| EngineError::BadParams { cmd: CMD.into(), msg }; + let preset = p.get("select").map_or(Some("sampledColors"), Value::as_str).ok_or_else(|| bad("`select` must be a string".into()))?; + let invert = b(p, "invert", false); + let selection_mode = mode(p); + let fuzz = |d: f32| f(p, "fuzziness", d).max(0.0); + // Photoshop's Detect Faces needs a face detector, which there is none of yet (#4455). + if b(p, "detectFaces", false) { + return Err(bad("detectFaces: face detection isn't available yet; select without it".into())); + } + let (area, mut mask) = match preset { + "sampledColors" => { + let (area, px) = sample_pixels(s, b(p, "sampleAllLayers", true))?; + let w = area.width() as usize; + // The dialog's eyedroppers: colours picked on the image, at their positions. + // Like Photoshop's, they may sample anywhere on the canvas: an active selection only + // limits the result (scope_color_range), not where colours are picked (#5244). + let plus = eyedropper_samples(p, "points", area, &px, &bad)?; + let minus = eyedropper_samples(p, "subtractPoints", area, &px, &bad)?; + let query = ColorRangeSamples::with_samples(s, p, area, &plus, &minus)?; + let mask = query.coverage(&px, w, 1.0, [0.0, 0.0]); + (area, mask) + } + "reds" | "yellows" | "greens" | "cyans" | "blues" | "magentas" => { + let center = match preset { + "reds" => 0.0, + "yellows" => 60.0, + "greens" => 120.0, + "cyans" => 180.0, + "blues" => 240.0, + _ => 300.0, + }; + let (area, px) = sample_pixels(s, b(p, "sampleAllLayers", true))?; + (area, sel::hue_range(&px, center)) + } + "skinTones" => { + let (area, px) = sample_pixels(s, b(p, "sampleAllLayers", true))?; + (area, sel::skin_tones(&px, fuzz(40.0).min(200.0))) + } + "highlights" | "midtones" | "shadows" => { + // Range in levels (Highlights / Shadows: one value, Midtones: [low, high]); Fuzziness + // is a percentage of the tonal scale. + let level = |v: &Value| v.as_f64().filter(|x| (0.0..=255.0).contains(x)).map(|x| x as f32); + let r = p.get("tonalRange"); + let (lo, hi) = match (preset, r) { + ("shadows", None) => (0.0, 65.0), + ("highlights", None) => (190.0, 255.0), + (_, None) => (105.0, 150.0), + ("shadows", Some(v)) => (0.0, level(v).ok_or_else(|| bad(format!("tonalRange: want a level 0..255 (got {v})")))?), + ("highlights", Some(v)) => (level(v).ok_or_else(|| bad(format!("tonalRange: want a level 0..255 (got {v})")))?, 255.0), + (_, Some(v)) => v + .as_array() + .and_then(|a| match a.as_slice() { + [l, h] => Some((level(l)?, level(h)?)), + _ => None, + }) + .filter(|(l, h)| l <= h) + .ok_or_else(|| bad(format!("tonalRange: want [low, high] levels 0..255 (got {v})")))?, + }; + let (area, px) = sample_pixels(s, b(p, "sampleAllLayers", true))?; + (area, sel::tone_range(&px, lo, hi, fuzz(20.0).min(100.0) / 100.0 * 255.0)) + } + "outOfGamut" => { + // Pixels the current proof setup (View › Proof Setup) can't reproduce, as the gamut + // warning shows them: judged on the composite. + let d = s.active().ok_or(EngineError::NoDocument)?; + let pv = s.color.proof(d.doc.id); + let (m, _) = crate::color_cmds::gamut_mask(&d.doc, &pv.setup, pv.gamut_threshold)?; + (d.doc.bounds(), m.iter().map(|v| f32::from(*v) / 255.0).collect()) + } + other => { + return Err(bad(format!( + "unknown select `{other}` (sampledColors, reds, yellows, greens, cyans, blues, magentas, highlights, midtones, shadows, skinTones, outOfGamut)" + ))); + } + }; + if invert { + for v in &mut mask { + *v = 1.0 - *v; + } + } + // Invert the colour result first, then constrain it to the original selection. + // Add mode must still be able to extend an existing selection intentionally. + scope_color_range(&mut mask, &s.active().ok_or(EngineError::NoDocument)?.doc, area, selection_mode); + set_selection(s, "Color Range", area, mask, selection_mode) +} + +fn modify(s: &mut Session, p: &Value, op: &str) -> Result { + // The dialogs' ranges (Photoshop's limits); anything else is refused, never clamped silently. + let (min, max): (f32, f32) = match op { + "border" => (1.0, 200.0), + "feather" => (0.1, 1000.0), + _ => (1.0, 500.0), + }; + let r = f(p, "radius", 1.0); + // Below the dialog's minimum (a negative or zero radius, #993) or above its maximum is + // refused: a clamp to 0 left the selection alone (Expand, Contract) or cleared it (Border) + // while reporting success. + if !(min..=max).contains(&r) { + return Err(EngineError::BadParams { cmd: format!("select.modify.{op}"), msg: format!("radius must be a number in {min}..{max}") }); + } + // Photoshop's "Apply effect at canvas bounds": when on, the canvas edge is a selection edge + // (Select All then Contract shrinks from the edges); when off, the selection is taken to + // continue past the canvas. Border has no such option: its band always follows the canvas edge, + // or a Select All would border to nothing. + let at_bounds = op == "border" || b(p, "applyAtCanvasBounds", false); + let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; + let area = doc.bounds(); + if area.size().area() > MAX_MODIFY_PIXELS as u64 { + return Err(EngineError::BadParams { cmd: format!("select.modify.{op}"), msg: "the selection is too large to modify".into() }); + } + let (_, m) = current_mask(doc); + let (w, h) = (area.width() as usize, area.height() as usize); + // Feather reaches 3σ = 3 r (σ = r, as in Photoshop); the others reach r. A margin past that + // keeps the canvas edge out of reach. A selection clear of the canvas edge needs none: both + // readings agree there. + let reach = if op == "feather" { r * 3.0 } else { r }; + let pad = if touches_edge(&m, w, h) { reach.ceil() as usize + 2 } else { 0 }; + let grown = |n: usize| pad.checked_mul(2).and_then(|p| n.checked_add(p)); + let (Some(pw), Some(ph)) = (grown(w), grown(h)) else { + return Err(EngineError::BadParams { cmd: format!("select.modify.{op}"), msg: "the selection is too large to modify".into() }); + }; + if pw.checked_mul(ph).is_none_or(|n| n > MAX_MODIFY_PIXELS) { + return Err(EngineError::BadParams { cmd: format!("select.modify.{op}"), msg: "the selection is too large to modify".into() }); + } + // Unpadded (the usual case) the mask is used as it is: two serial full-canvas copies were + // most of a 24 MP Feather or Smooth (#211). + let padded = if pad == 0 { m } else { pad_mask(&m, w, h, pad, at_bounds) }; + let out = match op { + "expand" => sel::expand(&padded, pw, ph, r), + "contract" => sel::contract(&padded, pw, ph, r), + "border" => sel::border(&padded, pw, ph, r), + "smooth" => sel::smooth(&padded, pw, ph, r), + _ => sel::feather(&padded, pw, ph, r), + }; + let out = if pad == 0 { out } else { crop_mask(&out, pw, pad, w, h) }; + let label = match op { + "expand" => "Expand Selection", + "contract" => "Contract Selection", + "border" => "Border Selection", + "smooth" => "Smooth Selection", + _ => "Feather Selection", + }; + set_selection(s, label, area, out, SelectionMode::Replace) +} + +/// The largest padded mask Modify works on (a 300000 × 300000 canvas is 9e10 pixels; this caps a +/// padded copy at ~4 GB of f32, beyond which the edit is refused rather than aborting on allocation). +const MAX_MODIFY_PIXELS: usize = 1 << 30; + +/// Whether any pixel on the outermost rows or columns of `m` (`w`×`h`) is selected. +fn touches_edge(m: &[f32], w: usize, h: usize) -> bool { + let sel = |x: usize, y: usize| m.get(y * w + x).is_some_and(|v| *v > 0.0); + (0..w).any(|x| sel(x, 0) || sel(x, h.saturating_sub(1))) || (0..h).any(|y| sel(0, y) || sel(w.saturating_sub(1), y)) +} + +/// `m` (`w`×`h`) with a `pad`-pixel margin: unselected when `outside_empty`, else the nearest +/// edge pixel repeated (the selection continues past the canvas). +fn pad_mask(m: &[f32], w: usize, h: usize, pad: usize, outside_empty: bool) -> Vec { + let pw = w + 2 * pad; + let mut out = vec![0.0f32; pw * (h + 2 * pad)]; + if w == 0 || h == 0 { + return out; + } + // Row by row (a copy and two fills), not sample by sample (#211). + for (py, row) in out.chunks_exact_mut(pw).enumerate() { + if outside_empty && !(pad..pad + h).contains(&py) { + continue; + } + let y = py.saturating_sub(pad).min(h - 1); + let (Some(src), Some((left, rest))) = (m.get(y * w..(y + 1) * w), row.split_at_mut_checked(pad)) else { continue }; + let Some((mid, right)) = rest.split_at_mut_checked(w) else { continue }; + mid.copy_from_slice(src); + if !outside_empty { + left.fill(src.first().copied().unwrap_or(0.0)); + right.fill(src.last().copied().unwrap_or(0.0)); + } + } + out +} + +/// The `w`×`h` centre of a mask padded by `pad_mask`. +fn crop_mask(m: &[f32], pw: usize, pad: usize, w: usize, h: usize) -> Vec { + let mut out = Vec::with_capacity(w.saturating_mul(h)); + for row in m.chunks_exact(pw.max(1)).skip(pad).take(h) { + out.extend_from_slice(row.get(pad..pad + w).unwrap_or_default()); + } + out +} + +/// Grow (contiguous) / Similar (anywhere): pixels whose colour lies within +/// the selected pixels' colour range widened by the tolerance. +fn grow_similar(s: &mut Session, p: &Value, contiguous: bool) -> Result { + let tol = f(p, "tolerance", 32.0) / 255.0; + let (area, px) = sample_pixels(s, b(p, "sampleAllLayers", false))?; + let (_, m) = current_mask(&s.active().ok_or(EngineError::NoDocument)?.doc); + let (mut lo, mut hi) = ([f32::MAX; 4], [f32::MIN; 4]); + for (q, v) in px.iter().zip(&m) { + if *v >= 0.5 { + for c in 0..4 { + lo[c] = lo[c].min(q[c]); + hi[c] = hi[c].max(q[c]); + } + } + } + if lo[0] > hi[0] { + return Err(EngineError::Other("selection is empty".into())); + } + let inside = |q: &[f32; 4]| (0..4).all(|c| q[c] >= lo[c] - tol - 1e-6 && q[c] <= hi[c] + tol + 1e-6); + let (w, h) = (area.width() as usize, area.height() as usize); + let mut out: Vec = m.iter().map(|v| if *v >= 0.5 { 1.0 } else { 0.0 }).collect(); + if contiguous { + let mut stack: Vec = (0..out.len()).filter(|i| out[*i] > 0.0).collect(); + while let Some(i) = stack.pop() { + let (x, y) = (i % w, i / w); + let n = [(x > 0).then(|| i - 1), (x + 1 < w).then(|| i + 1), (y > 0).then(|| i - w), (y + 1 < h).then(|| i + w)]; + for j in n.into_iter().flatten() { + if out[j] == 0.0 && inside(&px[j]) { + out[j] = 1.0; + stack.push(j); + } + } + } + } else { + for (o, q) in out.iter_mut().zip(&px) { + if inside(q) { + *o = 1.0; + } + } + } + set_selection(s, if contiguous { "Grow" } else { "Similar" }, area, out, SelectionMode::Replace) +} + +fn lasso(s: &mut Session, p: &Value) -> Result { + let pts: Vec<(f32, f32)> = p + .get("points") + .and_then(Value::as_array) + .map(|a| a.iter().filter_map(|q| Some((q.get(0)?.as_f64()? as f32, q.get(1)?.as_f64()? as f32))).collect()) + .unwrap_or_default(); + if pts.len() < 3 { + return Err(EngineError::BadParams { cmd: "select.lasso".into(), msg: "needs at least 3 points".into() }); + } + polygon_selection(s, "select.lasso", "Lasso", &pts, p) +} + +/// Selects the polygon `pts` with the lasso tools' `mode`, `antiAlias` and `feather` params, as +/// one history step called `label`. +pub(crate) fn polygon_selection(s: &mut Session, cmd: &str, label: &str, pts: &[(f32, f32)], p: &Value) -> Result { + let feather = f(p, "feather", 0.0); + // Select › Modify › Feather's range. + if !(0.0..=1000.0).contains(&feather) { + return Err(EngineError::BadParams { cmd: cmd.into(), msg: "feather must be a number in 0..1000".into() }); + } + let area = s.active().ok_or(EngineError::NoDocument)?.doc.bounds(); + if feather > 0.0 { + // The blur spreads past the polygon and isn't bit-identical over a smaller window. + let mut mask = sel::polygon(pts, area, b(p, "antiAlias", true)); + mask = sel::feather(&mask, area.width() as usize, area.height() as usize, feather); + return set_selection(s, label, area, mask, mode(p)); + } + // Only the rows the polygon spans (#4532): rows outside it are empty, and full-width rows + // keep `polygon`'s coverage bit-identical (its x arithmetic is relative to the area's left + // edge; its y samples are whole rows plus the same sub-row fractions). + let band = polygon_rows(pts, area); + let mask = sel::polygon(pts, band, b(p, "antiAlias", true)); + let m = mode(p); + let selected = s.edit(label, |doc, _| { + doc.selection = combine_band(doc.selection.as_ref(), &mask, band, m); + Ok(doc.selection.is_some()) + })?; + Ok(json!({ "selected": selected })) +} + +/// The full-width rows of `area` that points `pts` span (empty when none are finite). +fn polygon_rows(pts: &[(f32, f32)], area: Rect) -> Rect { + let ys = pts.iter().map(|p| p.1).filter(|y| y.is_finite()); + let (lo, hi) = ys.fold((f32::INFINITY, f32::NEG_INFINITY), |(lo, hi), y| (lo.min(y), hi.max(y))); + if lo > hi { + return Rect::EMPTY; + } + let clamp = |v: f32| v.clamp(area.y0 as f32, area.y1 as f32) as i32; + let (y0, y1) = (clamp(lo.floor()), clamp(hi.ceil() + 1.0)); + if y0 >= y1 { Rect::EMPTY } else { Rect::new(area.x0, y0, area.x1, y1) } +} + +/// [`sel::combine`] of a mask covering only `band` (zero elsewhere), giving exactly what the +/// whole-canvas combine gives: Replace and Intersect are empty outside the band, and Add and +/// Subtract keep the old selection there. +fn combine_band(old: Option<&Surface>, mask: &[f32], band: Rect, m: SelectionMode) -> Option { + let inside = sel::combine(old, mask, band, m); + let Some(old) = old.filter(|_| matches!(m, SelectionMode::Add | SelectionMode::Subtract)) else { return inside }; + if band.is_empty() { + return Some(old.clone()); + } + let values = inside.map_or_else(|| vec![0.0; band.width() as usize * band.height() as usize], |w| w.read_region(band)); + let mut s = old.clone(); + s.write_region(band, &values); + s.prune(); + (s.tile_count() > 0).then_some(s) +} + +macro_rules! spec { + ($id:literal, $label:literal, [$($m:literal),*], $params:literal, $en:expr, $run:expr) => { + CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: None, params: $params, enabled: $en, run: $run, journal: true } + }; +} + +/// Selection command specs. +pub fn specs() -> Vec { + vec![ + spec!( + "select.magicWand", + "Magic Wand", + [], + r##"{"x":px,"y":px,"tolerance":0..255=32,"contiguous":bool=true,"antiAlias":bool=true,"sampleAllLayers":bool=false,"mode":"replace|add|subtract|intersect"="replace"} (samples the visible alpha, Quick Mask, or layer mask when that is the picture)"##, + has_doc, + magic_wand + ), + spec!( + "select.colorRange", + "Color Range…", + ["Select"], + r##"{"select":"sampledColors|reds|yellows|greens|cyans|blues|magentas|highlights|midtones|shadows|skinTones|outOfGamut"="sampledColors","color":"#rrggbb"=foreground,"colors":["#rrggbb",…]?,"points":[[x,y],…]? (eyedropper samples),"subtractPoints":[[x,y],…]? (minus eyedropper),"order":["+"|"-",…]? (click order of points and subtractPoints; default all points first),"fuzziness":0..200=40 (tones: 0..100 %=20),"detectFaces":bool=false (not available yet: refused),"localized":bool=false,"range":0..100=100 (% of the longer side),"tonalRange":level|[lo,hi] (shadows 65, highlights 190, midtones [105,150]),"invert":bool=false,"sampleAllLayers":bool=true,"mode":"replace|add|subtract|intersect"="replace"}"##, + has_doc, + color_range + ), + spec!("select.modify.border", "Border…", ["Select", "Modify"], r##"{"radius":1..200=1}"##, has_selection, |s, p| modify(s, p, "border")), + spec!("select.modify.smooth", "Smooth…", ["Select", "Modify"], r##"{"radius":1..500=1,"applyAtCanvasBounds":bool=false}"##, has_selection, |s, p| { + modify(s, p, "smooth") + }), + spec!("select.modify.expand", "Expand…", ["Select", "Modify"], r##"{"radius":1..500=1,"applyAtCanvasBounds":bool=false}"##, has_selection, |s, p| { + modify(s, p, "expand") + }), + spec!( + "select.modify.contract", + "Contract…", + ["Select", "Modify"], + r##"{"radius":1..500=1,"applyAtCanvasBounds":bool=false}"##, + has_selection, + |s, p| modify(s, p, "contract") + ), + spec!( + "select.modify.feather", + "Feather…", + ["Select", "Modify"], + r##"{"radius":0.1..1000=1,"applyAtCanvasBounds":bool=false}"##, + has_selection, + |s, p| modify(s, p, "feather") + ), + spec!("select.grow", "Grow", ["Select"], r##"{"tolerance":0..255=32,"sampleAllLayers":bool=false}"##, has_selection, |s, p| grow_similar(s, p, true)), + spec!("select.similar", "Similar", ["Select"], r##"{"tolerance":0..255=32,"sampleAllLayers":bool=false}"##, has_selection, |s, p| grow_similar( + s, p, false + )), + spec!( + "select.lasso", + "Lasso", + [], + r##"{"points":[[x,y],…],"mode":"replace|add|subtract|intersect"="replace","antiAlias":bool=true,"feather":px=0}"##, + has_doc, + lasso + ), + ] +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/selection_cmds/tests.rs b/crates/engine/src/cmd/selection_cmds/tests.rs new file mode 100644 index 0000000000..602262dc7f --- /dev/null +++ b/crates/engine/src/cmd/selection_cmds/tests.rs @@ -0,0 +1,727 @@ +use super::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 40, "height": 30})).unwrap(); + s.edit("paint", |doc, _| { + let bg = doc.layers[0].surface_mut().unwrap(); + bg.fill_rect(Rect::new(5, 5, 15, 15), &[1.0, 0.0, 0.0, 1.0]); + bg.fill_rect(Rect::new(25, 5, 35, 15), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + s +} + +fn coverage(s: &Session, x: i32, y: i32) -> f32 { + s.active().unwrap().doc.selection.as_ref().map_or(0.0, |m| m.sample_channel(x, y, 0)) +} + +fn clear_selection(s: &mut Session) { + if s.active().unwrap().doc.selection.is_some() { + s.execute("select.deselect", json!({})).unwrap(); + } +} + +#[test] +fn color_range_skin_tones_selects_skin_not_cream_and_refuses_detect_faces() { + let mut s = session(); + let rgb = |c: [u8; 3]| [f32::from(c[0]) / 255.0, f32::from(c[1]) / 255.0, f32::from(c[2]) / 255.0, 1.0]; + s.edit("paint", |doc, _| { + let bg = doc.layers[0].surface_mut().unwrap(); + bg.fill_rect(Rect::new(0, 0, 40, 30), &rgb([252, 253, 247])); + bg.fill_rect(Rect::new(5, 5, 15, 15), &rgb([183, 119, 81])); + bg.fill_rect(Rect::new(25, 5, 35, 15), &rgb([231, 225, 202])); + Ok(()) + }) + .unwrap(); + s.execute("select.colorRange", json!({"select": "skinTones"})).unwrap(); + assert!(coverage(&s, 10, 10) > 0.95, "skin"); + assert!(coverage(&s, 30, 10) < 0.05, "cream"); + assert!(coverage(&s, 2, 2) < 0.05, "near-white background"); + // Subtracting skin from a selection of both squares keeps only the cream one. + s.execute("select.rect", json!({"x": 5, "y": 5, "width": 30, "height": 10})).unwrap(); + s.execute("select.colorRange", json!({"select": "skinTones", "mode": "subtract"})).unwrap(); + assert!(coverage(&s, 10, 10) < 0.05 && coverage(&s, 30, 10) > 0.95, "{} {}", coverage(&s, 10, 10), coverage(&s, 30, 10)); + let err = s.execute("select.colorRange", json!({"select": "skinTones", "detectFaces": true})).unwrap_err(); + assert!(err.to_string().contains("detectFaces"), "{err}"); +} + +#[test] +fn selection_sampling_refuses_oversized_canvases_before_reading_pixels() { + let mut s = Session::new(); + s.add_document( + photocraft_doc::Document::new( + "large", + photocraft_geom::Size::new(300_000, 300_000), + photocraft_color::ColorMode::Rgb, + photocraft_color::SampleType::U8, + ), + None, + ); + for all_layers in [false, true] { + assert!(sample_pixels(&s, all_layers).unwrap_err().to_string().contains("too large to sample")); + } + assert!(!s.active().unwrap().history.can_undo()); +} + +#[test] +fn selection_sampling_allocation_failure_keeps_the_selection() { + let mut s = session(); + s.execute("select.rect", json!({"x": 5, "y": 5, "width": 4, "height": 4})).unwrap(); + let before = s.active().unwrap().doc.clone(); + let history = s.active().unwrap().history.entries(); + crate::allocation::fail_next_for_test(); + let result = s.execute("select.similar", json!({"sampleAllLayers": false})); + let _ = crate::allocation::capacity::(0, "reset failpoint"); + assert!(result.is_err()); + assert_eq!(*s.active().unwrap().doc, *before); + assert_eq!(s.active().unwrap().history.entries(), history); +} + +#[test] +fn modify_rejects_oversized_canvases_before_reading_the_mask() { + let mut s = Session::new(); + let mut doc = photocraft_doc::Document::new( + "large", + photocraft_geom::Size::new(300_000, 300_000), + photocraft_color::ColorMode::Rgb, + photocraft_color::SampleType::U8, + ); + let mut selection = photocraft_raster::Surface::new(photocraft_color::PixelFormat::GRAY8); + selection.write_pixel(0, 0, &[1.0]); + doc.selection = Some(selection); + s.add_document(doc, None); + let before = s.active().unwrap().doc.clone(); + for op in ["expand", "contract", "border", "smooth", "feather"] { + let error = s.execute(&format!("select.modify.{op}"), json!({"radius": 1})).unwrap_err(); + assert!(error.to_string().contains("too large to modify")); + assert_eq!(*s.active().unwrap().doc, *before); + assert!(!s.active().unwrap().history.can_undo()); + } +} + +#[test] +fn color_range_replace_is_bounded_by_existing_selection() { + for params in [json!({"color": "#ff0000", "fuzziness": 0}), json!({"select": "reds"})] { + let mut s = session(); + // Both red squares match, but only the left is inside the original selection. + s.execute("select.rect", json!({"x": 5, "y": 5, "width": 10, "height": 10})).unwrap(); + s.execute("select.colorRange", params).unwrap(); + assert_eq!(coverage(&s, 10, 10), 1.0); + assert_eq!(coverage(&s, 30, 10), 0.0); + assert_eq!(coverage(&s, 2, 2), 0.0); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(coverage(&s, 10, 10), 1.0); + assert_eq!(coverage(&s, 30, 10), 0.0); + } +} + +#[test] +fn color_range_invert_and_partial_masks_stay_within_prior_selection() { + let mut s = session(); + s.execute("select.rect", json!({"x": 5, "y": 5, "width": 10, "height": 10})).unwrap(); + s.execute("select.colorRange", json!({"select": "highlights", "invert": true})).unwrap(); + assert_eq!(coverage(&s, 10, 10), 1.0, "inverted white excludes the white background"); + assert_eq!(coverage(&s, 20, 20), 0.0, "invert must not select outside the old boundary"); + + let mut s = session(); + s.edit("soft selection", |doc, _| { + let mut mask = vec![0.0; 40 * 30]; + mask[10 * 40 + 10] = 128.0 / 255.0; + doc.selection = Some(sel::mask_to_surface(&mask, doc.bounds())); + Ok(()) + }) + .unwrap(); + s.execute("select.colorRange", json!({"select": "reds"})).unwrap(); + assert!((coverage(&s, 10, 10) - 128.0 / 255.0).abs() < 0.001); + assert_eq!(coverage(&s, 30, 10), 0.0); +} + +#[test] +fn color_range_eyedropper_samples_anywhere_but_the_result_stays_in_the_selection() { + // #5244: as in Photoshop, a colour picked outside the active selection is accepted; only + // the result is limited to the selection. + let mut s = session(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 30})).unwrap(); + let outside = json!({"points": [[30, 10]], "fuzziness": 0}); + assert!(ColorRangeSamples::new(&s, &outside).is_ok()); + s.execute("select.colorRange", outside).unwrap(); + assert_eq!(coverage(&s, 10, 10), 1.0, "the red inside the selection is selected"); + assert_eq!(coverage(&s, 30, 10), 0.0, "the sampled red outside it stays out"); + assert_eq!(coverage(&s, 2, 2), 0.0, "white is not the sampled colour"); +} + +#[test] +fn color_range_eyedropper_respects_selection_but_add_can_extend_it() { + let mut s = session(); + s.execute("select.rect", json!({"x": 5, "y": 5, "width": 10, "height": 10})).unwrap(); + s.execute("select.colorRange", json!({"points": [[10, 10]], "fuzziness": 0})).unwrap(); + assert_eq!(coverage(&s, 10, 10), 1.0); + assert_eq!(coverage(&s, 30, 10), 0.0); + + // Explicitly adding a matching colour is still allowed to grow the selection. + s.execute("select.colorRange", json!({"points": [[30, 10]], "fuzziness": 0, "mode": "add"})).unwrap(); + assert_eq!(coverage(&s, 10, 10), 1.0); + assert_eq!(coverage(&s, 30, 10), 1.0); + + clear_selection(&mut s); + s.execute("select.colorRange", json!({"color": "#ff0000", "fuzziness": 0})).unwrap(); + assert_eq!(coverage(&s, 30, 10), 1.0, "an unbounded color range still searches the canvas"); +} + +#[test] +fn magic_wand_selects_the_visible_alpha_or_mask_not_the_rgb() { + let mut s = session(); + // Alpha covers the first red square and the pixels beside it. RGB would stop at the red. + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap(); + s.execute("channel.new", json!({"fill": "selection", "name": "Alpha"})).unwrap(); + s.execute("select.magicWand", json!({"x": 7, "y": 7, "tolerance": 0, "antiAlias": false})).unwrap(); + assert_eq!(coverage(&s, 7, 7), 1.0); + assert_eq!(coverage(&s, 2, 2), 1.0, "the white alpha includes pixels that are not the red square"); + assert_eq!(coverage(&s, 30, 10), 0.0, "outside the alpha stays unselected"); + // Colour channels back on: the wand reads RGB again. + s.execute("channel.setVisible", json!({"channel": "composite", "visible": true})).unwrap(); + s.execute("channel.setVisible", json!({"channel": 0, "visible": false})).unwrap(); + s.execute("select.magicWand", json!({"x": 7, "y": 7, "tolerance": 0, "antiAlias": false})).unwrap(); + assert_eq!(coverage(&s, 7, 7), 1.0); + assert_eq!(coverage(&s, 2, 2), 0.0, "RGB sampling stops at the red square"); + // Eyes off again, Alpha still the picture. + s.execute("channel.setVisible", json!({"channel": 0, "visible": true})).unwrap(); + s.execute("channel.setVisible", json!({"channel": "composite", "visible": false})).unwrap(); + s.execute("select.magicWand", json!({"x": 7, "y": 7, "tolerance": 0, "antiAlias": false})).unwrap(); + assert_eq!(coverage(&s, 2, 2), 1.0); + + let mut s = session(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap(); + s.execute("layer.layerMask.revealSelection", json!({})).unwrap(); + s.execute("view.layerMask", json!({"mode": "gray"})).unwrap(); + s.execute("select.magicWand", json!({"x": 7, "y": 7, "tolerance": 0, "antiAlias": false})).unwrap(); + assert_eq!(coverage(&s, 2, 2), 1.0, "gray mask view selects the mask"); + assert_eq!(coverage(&s, 30, 10), 0.0); + s.execute("view.layerMask", json!({"mode": "off"})).unwrap(); + for name in ["red", "green", "blue"] { + s.execute("channel.setVisible", json!({"channel": name, "visible": false})).unwrap(); + } + s.execute("select.magicWand", json!({"x": 7, "y": 7, "tolerance": 0, "antiAlias": false})).unwrap(); + assert_eq!(coverage(&s, 2, 2), 1.0, "a layer mask shown alone is what the wand reads"); + assert_eq!(coverage(&s, 30, 10), 0.0); +} + +#[test] +fn magic_wand_contiguous_and_modes() { + let mut s = session(); + s.execute("select.magicWand", json!({"x": 7, "y": 7, "antiAlias": false})).unwrap(); + assert_eq!(coverage(&s, 10, 10), 1.0); + assert_eq!(coverage(&s, 30, 10), 0.0); + s.execute("select.magicWand", json!({"x": 30, "y": 7, "mode": "add", "antiAlias": false})).unwrap(); + assert_eq!(coverage(&s, 30, 10), 1.0); + s.execute("select.magicWand", json!({"x": 7, "y": 7, "mode": "subtract", "antiAlias": false})).unwrap(); + assert_eq!(coverage(&s, 10, 10), 0.0); + s.execute("select.magicWand", json!({"x": 7, "y": 7, "contiguous": false, "antiAlias": false})).unwrap(); + assert_eq!(coverage(&s, 30, 10), 1.0); +} + +#[test] +fn color_range_prepared_query_matches_the_command_at_all_depths() { + use photocraft_doc::{Color, ColorMode, SampleType, Size}; + for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + for profile in [None, Some(photocraft_cms::Builtin::DisplayP3.profile().to_bytes())] { + let mut doc = Document::with_background("samples", Size::new(24, 12), ColorMode::Rgb, depth, Color::WHITE); + doc.icc_profile = profile; + let layer = doc.layers[0].surface_mut().unwrap(); + layer.fill_rect(Rect::new(0, 0, 8, 12), &[0.65, 0.3, 0.2, 1.0]); + layer.fill_rect(Rect::new(8, 0, 16, 12), &[0.2, 0.3, 0.65, 1.0]); + let mut s = Session::new(); + s.add_document(doc, None); + for p in [ + json!({"points": [[2, 3]], "fuzziness": 0}), + json!({"points": [[2, 3], [10, 3]], "subtractPoints": [[10, 3]], "order": ["+", "+", "-"], "fuzziness": 40}), + json!({"points": [[2, 3]], "localized": true, "range": 50, "fuzziness": 80}), + ] { + clear_selection(&mut s); + let q = ColorRangeSamples::new(&s, &p).unwrap(); + let doc = s.active().unwrap().doc.clone(); + let pixels = photocraft_compose::render(&doc, doc.bounds()); + let preview = q.coverage(&pixels.px, 24, 1.0, [0.0, 0.0]); + s.execute("select.colorRange", p).unwrap(); + let actual = current_mask(&s.active().unwrap().doc).1; + for (shown, selected) in preview.iter().zip(actual) { + let rounded = (shown.clamp(0.0, 1.0) * 255.0 + 0.5).floor() / 255.0; + assert_eq!(rounded, selected, "{depth:?}: original-pixel preview and OK differ"); + } + } + } + } +} + +#[test] +fn color_range_prepared_query_samples_visible_layers_not_the_active_layer() { + use photocraft_doc::{Layer, LayerContent}; + let mut s = session_colours(); + let doc = s.active().unwrap().doc.clone(); + let mut top = Layer::new("blue foreground", LayerContent::Raster(doc.layers[0].surface().unwrap().clone())); + top.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 40, 30), &[0.0, 0.0, 1.0, 1.0]); + let mut hidden = Layer::new("hidden green", LayerContent::Raster(top.surface().unwrap().clone())); + hidden.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 40, 30), &[0.0, 1.0, 0.0, 1.0]); + hidden.visible = false; + s.edit("layers", |doc, _| { + doc.layers.push(top); + doc.layers.push(hidden); + Ok(()) + }) + .unwrap(); + for all_layers in [false, true] { + clear_selection(&mut s); + let p = json!({"points": [[7, 7]], "sampleAllLayers": all_layers, "fuzziness": 0}); + let query = ColorRangeSamples::new(&s, &p).unwrap(); + let (area, px) = sample_pixels(&s, all_layers).unwrap(); + let shown = query.coverage(&px, area.width() as usize, 1.0, [0.0, 0.0]); + s.execute("select.colorRange", p).unwrap(); + assert_eq!(shown[7 * 40 + 7], coverage(&s, 7, 7)); + assert_eq!(shown[24 * 40 + 10], coverage(&s, 10, 24)); + } + for p in [json!({"points": [[-1, 0]]}), json!({"points": [[40, 1]]}), json!({"points": "wrong"}), json!({"points": [[null, 0]]})] { + assert!(ColorRangeSamples::new(&s, &p).is_err(), "{p}"); + } +} + +#[test] +fn color_range_selects_by_colour() { + let mut s = session(); + s.execute("select.colorRange", json!({"color": "#ff0000", "fuzziness": 40})).unwrap(); + // The sampled colour itself is fully selected (as with Photoshop's eyedropper). + assert_eq!(coverage(&s, 10, 10), 1.0); + assert_eq!(coverage(&s, 20, 20), 0.0); + s.execute("select.colorRange", json!({"color": "#ff0000", "fuzziness": 100})).unwrap(); + assert_eq!(coverage(&s, 10, 10), 1.0); + assert_eq!(coverage(&s, 20, 20), 0.0); +} + +#[test] +fn color_range_compares_in_lab_like_photoshop() { + // Photoshop weighs hue (Lab a/b) three times as much as lightness; a per-channel RGB + // distance can't tell a lighter shade from a redder one. + let mut s = Session::new(); + s.execute("file.new", json!({"width": 30, "height": 10})).unwrap(); + s.edit("paint", |doc, _| { + let bg = doc.layers[0].surface_mut().unwrap(); + let v = |c: u8| f32::from(c) / 255.0; + bg.fill_rect(Rect::new(0, 0, 10, 10), &[v(200), v(140), v(120), 1.0]); // skin + bg.fill_rect(Rect::new(10, 0, 20, 10), &[v(220), v(160), v(140), 1.0]); // lighter skin + bg.fill_rect(Rect::new(20, 0, 30, 10), &[v(220), v(140), v(120), 1.0]); // redder skin + Ok(()) + }) + .unwrap(); + s.execute("select.colorRange", json!({"points": [[5, 5]], "fuzziness": 40})).unwrap(); + assert!(coverage(&s, 5, 5) > 0.98); + // Both differ from the sample by 20 levels in one RGB channel, yet the lighter one is + // kept clearly more (about 0.55 vs 0.31). + let (lighter, redder) = (coverage(&s, 15, 5), coverage(&s, 25, 5)); + assert!(lighter > redder + 0.15 && redder > 0.0, "lighter {lighter}, redder {redder}"); +} + +#[test] +fn color_range_fuzziness_zero_selects_exact_match_only() { + // Sampled Colors at Fuzziness 0 selects only the exact match (TOOL-214-3, #214). + let mut s = Session::new(); + s.execute("file.new", json!({"width": 50, "height": 10})).unwrap(); + s.edit("paint", |doc, _| { + let bg = doc.layers[0].surface_mut().unwrap(); + let v = |c: u8| f32::from(c) / 255.0; + // Exact target color [200, 140, 120] + bg.fill_rect(Rect::new(0, 0, 10, 10), &[v(200), v(140), v(120), 1.0]); + // Off by 1 level in red [201, 140, 120] + bg.fill_rect(Rect::new(10, 0, 20, 10), &[v(201), v(140), v(120), 1.0]); + // Off by 1 level in green [200, 141, 120] + bg.fill_rect(Rect::new(20, 0, 30, 10), &[v(200), v(141), v(120), 1.0]); + // Off by 2 levels in blue [200, 140, 122] (crosses 8-bit Lab grid threshold) + bg.fill_rect(Rect::new(30, 0, 40, 10), &[v(200), v(140), v(122), 1.0]); + // Exact target color again at a different position + bg.fill_rect(Rect::new(40, 0, 50, 10), &[v(200), v(140), v(120), 1.0]); + Ok(()) + }) + .unwrap(); + + // Sampled via eyedropper point at [5, 5] with Fuzziness 0 + s.execute("select.colorRange", json!({"points": [[5, 5]], "fuzziness": 0})).unwrap(); + assert_eq!(coverage(&s, 5, 5), 1.0, "sampled pixel itself is fully selected"); + assert_eq!(coverage(&s, 45, 5), 1.0, "identical color elsewhere on canvas is fully selected"); + assert_eq!(coverage(&s, 15, 5), 0.0, "1 level off in red is unselected at fuzziness 0"); + assert_eq!(coverage(&s, 25, 5), 0.0, "1 level off in green is unselected at fuzziness 0"); + assert_eq!(coverage(&s, 35, 5), 0.0, "1 level off in blue is unselected at fuzziness 0"); + + // Sampled via hex color with Fuzziness 0 + s.execute("select.colorRange", json!({"color": "#c88c78", "fuzziness": 0})).unwrap(); + assert_eq!(coverage(&s, 5, 5), 1.0, "exact color match from hex is fully selected"); + assert_eq!(coverage(&s, 45, 5), 1.0, "identical color elsewhere on canvas is fully selected"); + assert_eq!(coverage(&s, 15, 5), 0.0, "1 level off in red is unselected for hex at fuzziness 0"); + assert_eq!(coverage(&s, 25, 5), 0.0, "1 level off in green is unselected for hex at fuzziness 0"); + assert_eq!(coverage(&s, 35, 5), 0.0, "1 level off in blue is unselected for hex at fuzziness 0"); +} + +/// Red squares (from `session`), a blue square, a black and a mid-grey strip on white. +fn session_colours() -> Session { + let mut s = session(); + s.edit("paint", |doc, _| { + let bg = doc.layers[0].surface_mut().unwrap(); + bg.fill_rect(Rect::new(5, 20, 15, 28), &[0.0, 0.0, 1.0, 1.0]); + bg.fill_rect(Rect::new(20, 20, 25, 28), &[0.0, 0.0, 0.0, 1.0]); + bg.fill_rect(Rect::new(30, 20, 35, 28), &[0.5, 0.5, 0.5, 1.0]); + Ok(()) + }) + .unwrap(); + s +} + +#[test] +fn color_range_several_samples_points_and_invert() { + let mut s = session_colours(); + // Several samples span one Lab box (Photoshop's Minimum/Maximum): red and blue take + // both squares, black, grey and white stay out. + s.execute("select.colorRange", json!({"colors": ["#ff0000", "#0000ff"], "fuzziness": 100})).unwrap(); + assert_eq!((coverage(&s, 10, 10), coverage(&s, 30, 10), coverage(&s, 10, 24)), (1.0, 1.0, 1.0)); + assert_eq!((coverage(&s, 2, 2), coverage(&s, 22, 24), coverage(&s, 32, 24)), (0.0, 0.0, 0.0)); + // Eyedropper point on the blue square; `invert` flips the result. + clear_selection(&mut s); + s.execute("select.colorRange", json!({"points": [[7, 22]], "fuzziness": 100, "invert": true})).unwrap(); + assert_eq!((coverage(&s, 10, 24), coverage(&s, 10, 10), coverage(&s, 2, 2)), (0.0, 1.0, 1.0)); + // Localized clusters: picked on the left red square, a 25% range (10 px) leaves the right one. + clear_selection(&mut s); + s.execute("select.colorRange", json!({"points": [[10, 10]], "fuzziness": 100, "localized": true, "range": 25})).unwrap(); + assert_eq!(coverage(&s, 10, 10), 1.0); + assert!(coverage(&s, 13, 10) > 0.5); + assert_eq!(coverage(&s, 30, 10), 0.0); + // Undo restores the empty selection that preceded the most recent Color Range. + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(coverage(&s, 2, 2), 0.0); +} + +#[test] +fn color_range_subtract_follows_photoshop_and_the_click_order() { + // Grey strips from dark to light; samples at both ends span the whole run. + let mut s = Session::new(); + s.execute("file.new", json!({"width": 50, "height": 10})).unwrap(); + s.edit("paint", |doc, _| { + let bg = doc.layers[0].surface_mut().unwrap(); + for (i, v) in [0.30f32, 0.40, 0.50, 0.60, 0.70].iter().enumerate() { + bg.fill_rect(Rect::new(i as i32 * 10, 0, i as i32 * 10 + 10, 10), &[*v, *v, *v, 1.0]); + } + Ok(()) + }) + .unwrap(); + let run = |s: &mut Session, extra: Value| { + clear_selection(s); + let mut p = json!({"points": [[5, 5], [45, 5]], "fuzziness": 10}); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + s.execute("select.colorRange", p).unwrap(); + (0..5).map(|i| coverage(s, i * 10 + 5, 5)).collect::>() + }; + assert!(run(&mut s, json!({})).iter().all(|v| *v > 0.99), "both samples span every strip"); + // Subtracting a colour inside the range moves the nearer edge onto it: the strips beyond + // it drop out, the subtracted grey itself stays selected (Photoshop does the same). + let cut = run(&mut s, json!({"subtractPoints": [[15, 5]]})); + assert!(cut[0] < 0.5 && cut[1] > 0.99 && cut[4] > 0.99, "{cut:?}"); + // Order matters: adding the dark strip back after the subtraction restores it. + let readd = run(&mut s, json!({"points": [[5, 5], [45, 5], [5, 5]], "subtractPoints": [[15, 5]], "order": ["+", "+", "-", "+"]})); + assert!(readd[0] > 0.99, "{readd:?}"); + let sub_last = run(&mut s, json!({"points": [[5, 5], [45, 5], [5, 5]], "subtractPoints": [[15, 5]], "order": ["+", "+", "+", "-"]})); + assert!(sub_last[0] < 0.5, "{sub_last:?}"); + // A malformed or inconsistent order is an error, never a panic. + clear_selection(&mut s); + for bad in [json!(["+"]), json!(["+", "+", "x"]), json!("+-"), json!(["-", "-", "+"])] { + assert!(s.execute("select.colorRange", json!({"points": [[5, 5], [45, 5]], "subtractPoints": [[15, 5]], "order": bad})).is_err(), "{bad}"); + } +} + +#[test] +fn color_range_presets() { + let mut s = session_colours(); + s.execute("select.colorRange", json!({"select": "reds"})).unwrap(); + assert_eq!((coverage(&s, 10, 10), coverage(&s, 30, 10)), (1.0, 1.0)); + assert_eq!((coverage(&s, 10, 24), coverage(&s, 2, 2), coverage(&s, 32, 24)), (0.0, 0.0, 0.0)); + clear_selection(&mut s); + s.execute("select.colorRange", json!({"select": "blues"})).unwrap(); + assert_eq!((coverage(&s, 10, 24), coverage(&s, 10, 10)), (1.0, 0.0)); + clear_selection(&mut s); + s.execute("select.colorRange", json!({"select": "greens"})).unwrap(); + assert!(s.active().unwrap().doc.selection.is_none() || coverage(&s, 10, 10) == 0.0); + // Tones: black is a shadow, white a highlight, 50% grey (128) a midtone. + clear_selection(&mut s); + s.execute("select.colorRange", json!({"select": "shadows"})).unwrap(); + assert_eq!((coverage(&s, 22, 24), coverage(&s, 2, 2), coverage(&s, 32, 24)), (1.0, 0.0, 0.0)); + clear_selection(&mut s); + s.execute("select.colorRange", json!({"select": "highlights"})).unwrap(); + assert_eq!((coverage(&s, 22, 24), coverage(&s, 2, 2)), (0.0, 1.0)); + clear_selection(&mut s); + s.execute("select.colorRange", json!({"select": "midtones", "fuzziness": 0})).unwrap(); + assert_eq!((coverage(&s, 32, 24), coverage(&s, 2, 2), coverage(&s, 22, 24)), (1.0, 0.0, 0.0)); + // A wider shadow range takes the grey too. + clear_selection(&mut s); + s.execute("select.colorRange", json!({"select": "shadows", "tonalRange": 140, "fuzziness": 0})).unwrap(); + assert_eq!(coverage(&s, 32, 24), 1.0); + // Modes combine as for the other selection commands. + s.execute("select.colorRange", json!({"select": "reds", "mode": "add"})).unwrap(); + assert_eq!((coverage(&s, 32, 24), coverage(&s, 10, 10)), (1.0, 1.0)); +} + +#[test] +fn color_range_out_of_gamut_matches_the_gamut_warning() { + let mut s = session(); + s.edit("paint", |doc, _| { + // Saturated sRGB blue is outside the default CMYK proof; mid grey is inside. + let bg = doc.layers[0].surface_mut().unwrap(); + bg.fill_rect(Rect::new(0, 20, 20, 30), &[0.0, 0.0, 1.0, 1.0]); + bg.fill_rect(Rect::new(20, 20, 40, 30), &[0.5, 0.5, 0.5, 1.0]); + Ok(()) + }) + .unwrap(); + s.execute("select.colorRange", json!({"select": "outOfGamut"})).unwrap(); + assert_eq!((coverage(&s, 5, 25), coverage(&s, 30, 25)), (1.0, 0.0)); + let warn = s.execute("view.gamutWarning", json!({"on": true})).unwrap(); + let sel = s.active().unwrap().doc.selection.clone().unwrap(); + let mut n = 0; + for y in 0..30 { + for x in 0..40 { + n += usize::from(sel.sample_channel(x, y, 0) > 0.5); + } + } + assert_eq!(warn["outOfGamut"].as_u64(), Some(n as u64)); +} + +#[test] +fn color_range_rejects_bad_params() { + let mut s = session_colours(); + for p in [ + json!({"select": "skin"}), + json!({"select": 3}), + json!({"points": [[100, 2]]}), + json!({"points": [[1]]}), + json!({"points": "here"}), + json!({"colors": "#ff0000"}), + json!({"localized": true}), + json!({"select": "midtones", "tonalRange": [200, 100]}), + json!({"select": "shadows", "tonalRange": 300}), + ] { + assert!(s.execute("select.colorRange", p.clone()).is_err(), "{p}"); + } + assert!(s.active().unwrap().doc.selection.is_none()); +} + +#[test] +fn modify_commands() { + let mut s = session(); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); + s.execute("select.modify.expand", json!({"radius": 2})).unwrap(); + assert_eq!(coverage(&s, 8, 15), 1.0); + s.execute("select.modify.contract", json!({"radius": 4})).unwrap(); + assert_eq!(coverage(&s, 11, 15), 0.0); + assert_eq!(coverage(&s, 15, 15), 1.0); + s.execute("select.modify.border", json!({"radius": 2})).unwrap(); + assert_eq!(coverage(&s, 15, 15), 0.0); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); + s.execute("select.modify.feather", json!({"radius": 4})).unwrap(); + let e = coverage(&s, 10, 15); + assert!(e > 0.2 && e < 0.8, "{e}"); + s.execute("select.modify.smooth", json!({"radius": 2})).unwrap(); + assert!(s.active().unwrap().doc.selection.is_some()); + assert!(!s.is_enabled("select.nothing")); + // Out-of-range or non-finite radii are refused and leave the selection alone. + for op in ["feather", "smooth", "expand", "contract", "border"] { + for r in [json!(1e300), json!(5000), json!(f64::MAX), json!(-5), json!(-0.5), json!(f64::MIN)] { + assert!(s.execute(&format!("select.modify.{op}"), json!({"radius": r})).is_err(), "{op} {r}"); + } + } + assert!(s.active().unwrap().doc.selection.is_some()); +} + +#[test] +fn modify_select_all_honours_canvas_bounds() { + let all = || { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 40, "height": 30})).unwrap(); + s.execute("select.all", json!({})).unwrap(); + s + }; + // Off (Photoshop's default): the selection continues past the canvas, so the edges stay. + for op in ["contract", "smooth", "expand", "feather"] { + let mut s = all(); + s.execute(&format!("select.modify.{op}"), json!({"radius": 4})).unwrap(); + assert_eq!(coverage(&s, 0, 15), 1.0, "{op}"); + assert_eq!(coverage(&s, 20, 0), 1.0, "{op}"); + } + // On: the canvas edge is a selection edge (#1277). + let mut s = all(); + s.execute("select.modify.contract", json!({"radius": 4, "applyAtCanvasBounds": true})).unwrap(); + assert_eq!(coverage(&s, 2, 15), 0.0); + assert_eq!(coverage(&s, 20, 28), 0.0); + assert_eq!(coverage(&s, 20, 15), 1.0); + let mut s = all(); + s.execute("select.modify.feather", json!({"radius": 4, "applyAtCanvasBounds": true})).unwrap(); + let e = coverage(&s, 0, 15); + assert!(e > 0.2 && e < 0.8, "{e}"); + assert_eq!(coverage(&s, 20, 15), 1.0); + let mut s = all(); + s.execute("select.modify.smooth", json!({"radius": 4, "applyAtCanvasBounds": true})).unwrap(); + assert!(coverage(&s, 0, 0) < 1.0); + // Border always follows the canvas edge: a band inside it, not an empty selection. + let mut s = all(); + s.execute("select.modify.border", json!({"radius": 4})).unwrap(); + assert!(coverage(&s, 0, 15) > 0.0); + assert_eq!(coverage(&s, 20, 15), 0.0); +} + +#[test] +fn modify_away_from_the_canvas_edge_ignores_canvas_bounds() { + for at in [false, true] { + let mut s = session(); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); + s.execute("select.modify.contract", json!({"radius": 4, "applyAtCanvasBounds": at})).unwrap(); + assert_eq!(coverage(&s, 11, 15), 0.0); + assert_eq!(coverage(&s, 15, 15), 1.0); + } +} + +#[test] +fn modify_refuses_radii_below_the_minimum() { + let mut s = session(); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); + // Below each dialog's minimum (1 px, Feather 0.1 px) is refused, not clamped to 0: a + // negative Border radius used to clear the selection and report success (#993). + let below = [ + ("border", -5.0), + ("border", 0.5), + ("smooth", -5.0), + ("smooth", 0.0), + ("expand", -5.0), + ("expand", 0.0), + ("contract", -5.0), + ("contract", 0.9), + ("feather", -5.0), + ("feather", 0.0), + ("feather", 0.05), + ]; + let before = current_mask(&s.active().unwrap().doc).1; + for (op, r) in below { + let err = s.execute(&format!("select.modify.{op}"), json!({"radius": r})).unwrap_err(); + assert!(matches!(err, EngineError::BadParams { .. }), "{op} {r}: {err}"); + assert!(current_mask(&s.active().unwrap().doc).1 == before, "{op} {r}: the selection changed"); + } + // The minimum itself is still accepted. + s.execute("select.modify.feather", json!({"radius": 0.1})).unwrap(); + s.execute("select.modify.expand", json!({"radius": 1})).unwrap(); + assert_eq!(coverage(&s, 9, 15), 1.0); +} + +#[test] +fn geometry_params_that_would_wrap_are_rejected() { + let mut s = session(); + // 2^32 + 50 wrapped to `x = 50` and 3e9 to a negative coordinate through `as i32`; + // both are bad-params errors now, whatever the front door (UI, CLI, control, MCP). + for x in [4_294_967_346_i64, 3_000_000_000_i64] { + let err = s.execute("select.rect", json!({"x": x, "y": 0, "width": 10, "height": 10})).unwrap_err(); + assert!(err.to_string().contains("32-bit"), "{err}"); + } + let err = s.execute("document.pixel", json!({"x": 4_294_967_346_i64, "y": 0})).unwrap_err(); + assert!(err.to_string().contains("32 bits"), "{err}"); + // In-range coordinates, including negative and past-canvas ones, are unaffected. + s.execute("select.rect", json!({"x": -100, "y": -100, "width": 500, "height": 500})).unwrap(); + s.execute("document.pixel", json!({"x": 0, "y": 0})).unwrap(); +} + +#[test] +fn grow_and_similar() { + let mut s = session(); + s.execute("select.rect", json!({"x": 6, "y": 6, "width": 2, "height": 2})).unwrap(); + s.execute("select.grow", json!({"tolerance": 5})).unwrap(); + assert_eq!(coverage(&s, 14, 14), 1.0); + assert_eq!(coverage(&s, 30, 10), 0.0); + s.execute("select.similar", json!({"tolerance": 5})).unwrap(); + assert_eq!(coverage(&s, 30, 10), 1.0); + assert_eq!(coverage(&s, 20, 20), 0.0); +} + +#[test] +fn lasso_polygon() { + let mut s = session(); + s.execute("select.lasso", json!({"points": [[0, 0], [20, 0], [0, 20]]})).unwrap(); + assert_eq!(coverage(&s, 2, 2), 1.0); + assert_eq!(coverage(&s, 18, 18), 0.0); + assert!(s.execute("select.lasso", json!({"points": [[0, 0], [1, 1]]})).is_err()); + s.execute("select.lasso", json!({"points": [[0, 0], [20, 0], [0, 20]], "mode": "subtract"})).unwrap(); + assert!(s.active().unwrap().doc.selection.is_none()); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(coverage(&s, 2, 2), 1.0); +} + +/// The previous per-sample padding and cropping, kept as the oracle for the row-wise ones. +fn old_pad_mask(m: &[f32], w: usize, h: usize, pad: usize, outside_empty: bool) -> Vec { + let pw = w + 2 * pad; + let mut out = vec![0.0f32; pw * (h + 2 * pad)]; + for (py, row) in out.chunks_exact_mut(pw).enumerate() { + let inside_y = (pad..pad + h).contains(&py); + if outside_empty && !inside_y { + continue; + } + let y = py.saturating_sub(pad).min(h - 1); + for (px, v) in row.iter_mut().enumerate() { + if outside_empty && !(pad..pad + w).contains(&px) { + continue; + } + *v = m.get(y * w + px.saturating_sub(pad).min(w - 1)).copied().unwrap_or(0.0); + } + } + out +} + +#[test] +fn row_wise_pad_and_crop_match_per_sample_ones() { + let mut seed = 0x2545_f491_4f6c_dd1du64; + let (w, h) = (37, 23); + let m: Vec = (0..w * h) + .map(|_| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed % 1000) as f32 / 999.0 + }) + .collect(); + for pad in [0, 1, 5, 40] { + for outside_empty in [false, true] { + let padded = pad_mask(&m, w, h, pad, outside_empty); + assert_eq!(padded, old_pad_mask(&m, w, h, pad, outside_empty), "pad {pad} {outside_empty}"); + assert_eq!(crop_mask(&padded, w + 2 * pad, pad, w, h), m, "pad {pad}"); + } + } +} + +/// The lasso over the polygon's rows gives exactly the whole-canvas result (#4532): random +/// polygons, partly off the canvas, with and without anti-aliasing, in every mode over an +/// existing selection. +#[test] +fn lasso_over_its_rows_matches_the_whole_canvas() { + let mut seed = 0x2545_f491_u32; + let mut rnd = |lo: f32, hi: f32| { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + lo + (seed % 10_000) as f32 / 10_000.0 * (hi - lo) + }; + for case in 0..24 { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 300, "height": 520})).unwrap(); + s.execute("select.rect", json!({"x": 40, "y": 60, "width": 200, "height": 300})).unwrap(); + let n = 3 + case % 7; + let pts: Vec<(f32, f32)> = (0..n).map(|_| (rnd(-30.0, 330.0), rnd(100.0, 420.0))).collect(); + let aa = case % 2 == 0; + let m = ["replace", "add", "subtract", "intersect"][case % 4]; + let doc = s.active().unwrap().doc.clone(); + let area = doc.bounds(); + let want = sel::combine(doc.selection.as_ref(), &sel::polygon(&pts, area, aa), area, SelectionMode::parse(m)); + let points: Vec<[f32; 2]> = pts.iter().map(|p| [p.0, p.1]).collect(); + s.execute("select.lasso", json!({"points": points, "antiAlias": aa, "mode": m})).unwrap(); + let got = s.active().unwrap().doc.selection.clone(); + let read = |x: &Option| x.as_ref().map(|s| s.read_region(area)); + assert_eq!(read(&got), read(&want), "case {case}: {m}, anti-alias {aa}, {pts:?}"); + } +} diff --git a/crates/engine/src/slice_cmds.rs b/crates/engine/src/cmd/slice_cmds.rs similarity index 100% rename from crates/engine/src/slice_cmds.rs rename to crates/engine/src/cmd/slice_cmds.rs diff --git a/crates/engine/src/slice_cmds/tests.rs b/crates/engine/src/cmd/slice_cmds/tests.rs similarity index 100% rename from crates/engine/src/slice_cmds/tests.rs rename to crates/engine/src/cmd/slice_cmds/tests.rs diff --git a/crates/engine/src/cmd/smart_cmds.rs b/crates/engine/src/cmd/smart_cmds.rs new file mode 100644 index 0000000000..f19813e3ab --- /dev/null +++ b/crates/engine/src/cmd/smart_cmds.rs @@ -0,0 +1,337 @@ +//! Smart Objects and Smart Filters: Layer › Smart Objects, Layer › Smart Filter and +//! Filter › Convert for Smart Filters. +//! +//! A smart object keeps its **source** (embedded file bytes, or a linked path) plus a +//! `transform` and a stack of smart filters; its `cache` is the rendered appearance the +//! compositors draw. The engine owns re-rendering (compose stays a pure function of the +//! document): +//! +//! ```text +//! source bytes ──decode + composite (cached by content hash)──► source image (source pixels) +//! ──transform (exact shift, or bicubic warp)──────► placed (document pixels) +//! ──each visible smart filter, blended (blend/opacity)──► filtered +//! ──filter mask mix (unfiltered ↔ filtered)───────► cache +//! ``` +//! +//! The placed stage and the result after each filter are cached too (`stack_cache`), so a +//! re-render starts from the deepest stage it shares with an earlier one. +//! +//! Converting a layer embeds it as an in-memory `.pcraft` bundle of a nested document (exactly +//! lossless, layered, any depth/model). PSD placed layers keep their source in the preserved +//! global `lnk2` block (found by uuid), and keep Photoshop's rendering until something changes, +//! so an unedited PSD still round-trips byte for byte. PSD export (`photocraft_io::smart_map`) +//! writes every smart object back as one: its source embedded in `lnk2` (a `.pcraft` source as a +//! PSB), its smart filters in `filterFX` and its filter mask in `FEid`. + +use std::sync::{Arc, Mutex}; + +use photocraft_algo::resample::translate_surface; +use photocraft_algo::transform::Homography; +use photocraft_color::{BlendMode, ColorMode, PixelFormat, SampleType}; +use photocraft_doc::{DocId, Document, Layer, LayerContent, LayerId, LayerMask, Metadata, SmartContentsId, SmartFilter, SmartObject, SmartSource}; +use photocraft_geom::{Affine, Rect, Size}; +use photocraft_raster::Surface; +use serde_json::{Value, json}; +use stack_cache::{Stage, StageKey}; + +use crate::commands::{CommandSpec, blend_from_str, layer_param}; +use crate::jobs::JobCtx; +use crate::{EngineError, Result, Session}; + +/// An open Edit Contents document and the shared contents it updates when saved or closed. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct SmartLink { + pub child: DocId, + pub parent: DocId, + pub layer: LayerId, + pub contents_id: SmartContentsId, +} + +/// PSD placed-layer keys that describe the smart object's source; stale once we change it. +const PLACED_KEYS: [&[u8; 4]; 3] = [b"SoLd", b"PlLd", b"SoLE"]; + +/// Command id of a Photoshop smart filter PhotoCraft does not implement (kept verbatim from PSD). +pub use photocraft_io::smart_map::UNSUPPORTED_FILTER; + +fn other(msg: impl Into) -> EngineError { + EngineError::Other(msg.into()) +} + +fn bad(cmd: &str, msg: impl Into) -> EngineError { + EngineError::BadParams { cmd: cmd.into(), msg: msg.into() } +} + +// ---------- source encoding / decoding ---------- + +/// Encodes a document as embedded smart-object contents: an in-memory `.pcraft` bundle. +pub fn encode_source(doc: &Document) -> Result> { + photocraft_format::save_to_bytes(doc, &Default::default()).map_err(|e| other(format!("can't encode smart object contents: {e}"))) +} + +/// Decodes smart-object contents (a `.pcraft` bundle, PSD/PSB, or any flat image format). +pub fn decode_source(file_name: &str, bytes: &[u8]) -> Result { + crate::file_cmds::import(file_name, bytes).map_err(|e| other(format!("can't read smart object contents \"{file_name}\": {e}"))) +} + +fn base_name(path: &str) -> String { + path.rsplit(['/', '\\']).next().unwrap_or(path).to_string() +} + +// ---------- enablement ---------- + +fn active_smart(s: &Session) -> std::result::Result<&SmartObject, String> { + let d = s.active().ok_or("no document open")?; + let id = d.active_layer.ok_or("no active layer")?; + match &d.doc.layer(id).ok_or("no active layer")?.content { + LayerContent::Smart(sm) => Ok(sm), + other => Err(format!("the active layer is {} {} layer, not a smart object", other.article(), other.kind_name())), + } +} +fn has_smart(s: &Session) -> std::result::Result<(), String> { + active_smart(s).map(|_| ()) +} +fn has_linked(s: &Session) -> std::result::Result<(), String> { + match active_smart(s)?.source { + SmartSource::Linked { .. } => Ok(()), + _ => Err("the smart object is embedded".into()), + } +} +fn has_doc(s: &Session) -> std::result::Result<(), String> { + s.active().map(|_| ()).ok_or_else(|| "no document open".into()) +} +fn has_smart_filters(s: &Session) -> std::result::Result<(), String> { + if active_smart(s)?.smart_filters.is_empty() { Err("the smart object has no smart filters".into()) } else { Ok(()) } +} +fn has_filter_mask(s: &Session) -> std::result::Result<(), String> { + active_smart(s)?.filter_mask.as_ref().map(|_| ()).ok_or_else(|| "the smart object has no filter mask".into()) +} +fn convertible(s: &Session) -> std::result::Result<(), String> { + let d = s.active().ok_or("no document open")?; + let id = d.active_layer.ok_or("no active layer")?; + d.doc.layer(id).map(|_| ()).ok_or_else(|| "no active layer".into()) +} +fn not_smart(s: &Session) -> std::result::Result<(), String> { + convertible(s)?; + if active_smart(s).is_ok() { Err("the layer is already a smart object".into()) } else { Ok(()) } +} + +/// Convert to Smart Object: refused only when the single targeted layer is already a smart +/// object. A multi-layer selection can still be combined (nesting any smart object in it). +fn convertible_to_smart(s: &Session) -> std::result::Result<(), String> { + convertible(s)?; + if crate::layer_multi_cmds::selected(s).len() <= 1 { not_smart(s) } else { Ok(()) } +} + +macro_rules! spec { + ($id:literal, $label:literal, $menu:expr, $params:literal, $en:expr, $run:expr) => { + CommandSpec { id: $id, label: $label, menu: $menu, shortcut: None, params: $params, enabled: $en, run: $run, journal: true } + }; +} + +mod contents; +mod filters; +mod placing; +mod rendering; +mod source; + +pub(crate) use contents::on_close; +pub use contents::{commit_child, contents_of, replace_contents_bytes, replace_contents_from_bytes}; +use contents::{edit_contents, export_contents, is_smart_child, path_param, replace_contents, set_source, update_all}; +#[cfg(test)] +use filters::smart_mut; +pub(crate) use filters::{add_smart_filter, filter_mask_paintable, filter_mask_surface, refresh_after_filter_mask_edit}; +use filters::{blending_options, delete_filter, edit_filters, move_filter, set_filter_params, set_filter_visible, smart, transfer_filters}; +use placing::{convert, detach_psd, shift_layer, via_copy}; +pub use placing::{layer_to_smart, layers_to_smart, placement}; +pub(crate) use placing::{set_placement, shift_smart, transform_placement}; +use rendering::refresh_or_fail; +pub(crate) use rendering::source_box; +pub use rendering::{apply_smart_filters, purge_stack_cache, refresh, refresh_layer, render, render_below_filter, stack_cache_bytes, stack_image}; +#[cfg(test)] +use rendering::{blend_surfaces, place, render_in}; +pub use source::{SourceImage, source_bytes, source_decode_count, source_image, svg_source_image}; +use source::{authorize_source, authorized_source_bytes}; +pub(crate) use source::{restore_unrendered, take_caches}; + +const SO: &[&str] = &["Layer", "Smart Objects"]; +const SF: &[&str] = &["Layer", "Smart Filter"]; + +pub fn specs() -> Vec { + vec![ + spec!( + "layer.smartObjects.convertToSmartObject", + "Convert to Smart Object", + SO, + r##"{"layer":id?} (default: combine selected layers)"##, + convertible_to_smart, + convert + ), + spec!( + "filter.convertForSmartFilters", + "Convert for Smart Filters", + &["Filter"], + r##"{"layer":id?} (default: combine selected layers)"##, + not_smart, + convert + ), + spec!("layer.smartObjects.newSmartObjectViaCopy", "New Smart Object via Copy", SO, r##"{"layer":id?}"##, has_smart, via_copy), + spec!("layer.smartObjects.rasterize", "Rasterize", SO, r##"{"layer":id?}"##, has_smart, |s, p| s.execute("layer.rasterize.smartObject", p.clone())), + spec!( + "layer.smartObjects.editContents", + "Edit Contents", + SO, + r##"{"layer":id?} → opens the contents as a new document; saving (layer.smartObjects.saveContents) or closing it updates the smart object"##, + has_smart, + edit_contents + ), + spec!("layer.smartObjects.saveContents", "Save Contents", &[], "{} (in an Edit Contents document)", is_smart_child, |s, _| { + let i = s.active_index().ok_or(EngineError::NoDocument)?; + Ok(json!({"updated": commit_child(s, i)?})) + }), + spec!("layer.smartObjects.replaceContents", "Replace Contents…", SO, r##"{"layer":id?,"path":str}"##, has_smart, replace_contents), + spec!( + "layer.smartObjects.exportContents", + "Export Contents…", + SO, + r##"{"layer":id?,"path":str (another extension than the contents' own exports them in that format)}"##, + has_smart, + export_contents + ), + spec!("layer.smartObjects.relinkToFile", "Relink to File…", SO, r##"{"layer":id?,"path":str}"##, has_smart, |s, p| { + let path = path_param("layer.smartObjects.relinkToFile", p)?.to_string(); + set_source(s, p, "Relink to File", false, |_, _| Ok(SmartSource::Linked { path })) + }), + spec!("layer.smartObjects.updateModifiedContent", "Update Modified Content", SO, r##"{"layer":id?}"##, has_linked, |s, p| { + let id = layer_param(s, p)?; + s.edit("Update Modified Content", |doc, _| refresh_or_fail(doc, id))?; + Ok(json!({"layer": id.0})) + }), + spec!( + "layer.smartObjects.updateChanged", + "Update Changed Linked Content", + &[], + "{} — re-render the active document's linked smart objects whose files changed on disk since they were last seen (size or modification time); the desktop app does this by itself every two seconds, as Photoshop does while a document is open. Files seen for the first time are only remembered. One Update Modified Content undo step per file → {updated: [layer ids]}", + |s| s.active().map(|_| ()).ok_or_else(|| "no document open".into()), + crate::link_watch::update_changed + ), + spec!( + "layer.smartObjects.updateAllModifiedContent", + "Update All Modified Content", + SO, + "{}", + |s| s.active().map(|_| ()).ok_or_else(|| "no document open".into()), + |s, _| update_all(s) + ), + spec!( + "layer.smartObjects.convertToLayers", + "Convert to Layers", + SO, + r##"{"layer":id?} (contents unpacked at the placement: one layer, or a group named after the smart object; smart filters are discarded)"##, + has_smart, + unpack::convert_to_layers + ), + spec!("layer.smartObjects.convertToEmbedded", "Convert to Embedded", SO, r##"{"layer":id?}"##, has_linked, |s, p| { + set_source(s, p, "Convert to Embedded", true, |meta, src| { + let (file_name, bytes) = source_bytes(meta, src).ok_or_else(|| other("the linked file can't be read"))?; + Ok(SmartSource::Embedded { file_name, bytes }) + }) + }), + spec!( + "layer.smartObjects.convertToLinked", + "Convert to Linked…", + SO, + r##"{"layer":id?,"path":str} (writes the contents there)"##, + has_smart, + |s, p| { + let path = path_param("layer.smartObjects.convertToLinked", p)?.to_string(); + set_source(s, p, "Convert to Linked", false, |meta, src| { + let (_, bytes) = source_bytes(meta, src).ok_or_else(|| other("the smart object's contents are unavailable"))?; + crate::file_cmds::write_file(&path, &bytes)?; + Ok(SmartSource::Linked { path }) + }) + } + ), + // Smart filters + spec!( + "layer.smartFilter.disableSmartFilters", + "Disable Smart Filters", + SF, + r##"{"layer":id?,"enabled":bool? (default: toggle)}"##, + has_smart_filters, + |s, p| { + edit_filters(s, p, "Disable Smart Filters", |sm| { + sm.filters_enabled = p.get("enabled").and_then(Value::as_bool).unwrap_or(!sm.filters_enabled); + Ok(()) + }) + } + ), + spec!("layer.smartFilter.deleteFilterMask", "Delete Filter Mask", SF, r##"{"layer":id?}"##, has_filter_mask, |s, p| { + edit_filters(s, p, "Delete Filter Mask", |sm| { + sm.filter_mask = None; + Ok(()) + }) + }), + spec!( + "layer.smartFilter.disableFilterMask", + "Disable Filter Mask", + SF, + r##"{"layer":id?,"enabled":bool? (default: toggle)}"##, + has_filter_mask, + |s, p| { + edit_filters(s, p, "Disable Filter Mask", |sm| { + if let Some(m) = &mut sm.filter_mask { + m.enabled = p.get("enabled").and_then(Value::as_bool).unwrap_or(!m.enabled); + } + Ok(()) + }) + } + ), + spec!( + "layer.smartFilter.blendingOptions", + "Blending Options…", + SF, + r##"{"layer":id?,"index":u32? (0 = bottom; default top),"blend":str?,"opacity":0..1?}"##, + has_smart_filters, + blending_options + ), + spec!("layer.smartFilter.clearSmartFilters", "Clear Smart Filters", SF, r##"{"layer":id?}"##, has_smart_filters, |s, p| { + edit_filters(s, p, "Clear Smart Filters", |sm| { + sm.smart_filters.clear(); + sm.filter_mask = None; + Ok(()) + }) + }), + spec!( + "layer.smartFilter.setVisible", + "Show/Hide Smart Filter", + &[], + r##"{"layer":id?,"index":u32?,"visible":bool? (default: toggle)}"##, + has_smart_filters, + set_filter_visible + ), + spec!( + "layer.smartFilter.setParams", + "Edit Smart Filter", + &[], + r##"{"layer":id?,"index":u32?,"params":{…} (merged)}"##, + has_smart_filters, + set_filter_params + ), + spec!("layer.smartFilter.delete", "Delete Smart Filter", &[], r##"{"layer":id?,"index":u32?}"##, has_smart_filters, delete_filter), + spec!("layer.smartFilter.move", "Move Smart Filter", &[], r##"{"layer":id?,"index":u32?,"to":u32}"##, has_smart_filters, move_filter), + spec!( + "layer.smartFilter.transfer", + "Move or Copy Smart Filters", + &[], + r##"{"from":id,"to":id,"filter":u32? (default: all, with the filter mask),"copy":bool=false}"##, + has_doc, + transfer_filters + ), + ] +} + +mod stack_cache; +mod unpack; + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/smart_cmds/contents.rs b/crates/engine/src/cmd/smart_cmds/contents.rs new file mode 100644 index 0000000000..393b03e8ac --- /dev/null +++ b/crates/engine/src/cmd/smart_cmds/contents.rs @@ -0,0 +1,204 @@ +use super::filters::{smart, smart_mut}; +use super::placing::detach_psd; +use super::rendering::{refresh, refresh_or_fail, unapplied_filters}; +use super::source::{authorized_source_bytes, source_bytes}; +use super::*; + +pub(super) fn path_param<'a>(cmd: &str, p: &'a Value) -> Result<&'a str> { + p.get("path").and_then(Value::as_str).filter(|s| !s.is_empty()).ok_or_else(|| bad(cmd, "pass `path`")) +} + +/// Instances sharing contents in this document, including those inside groups. +fn instances(doc: &Document, contents_id: SmartContentsId) -> Vec { + doc.walk().into_iter().filter_map(|(_, _, l)| matches!(&l.content, LayerContent::Smart(sm) if sm.contents_id == contents_id).then_some(l.id)).collect() +} + +/// Swaps shared contents, keeping each instance's transform and filters, and re-renders. +pub(super) fn set_source( + s: &mut Session, + p: &Value, + label: &str, + keep_psd: bool, + make: impl FnOnce(&Metadata, &SmartSource) -> Result, +) -> Result { + let id = layer_param(s, p)?; + let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; + let new = make(&doc.metadata, &smart(doc, id)?.source)?; + set_shared_source(s, id, label, keep_psd, new) +} + +// Keep the shared-instance transaction out of the per-command source-builder instantiations. +fn set_shared_source(s: &mut Session, id: LayerId, label: &str, keep_psd: bool, new: SmartSource) -> Result { + let (parent, contents_id, changed, warnings) = s.edit(label, |doc, _| { + let contents_id = smart(doc, id)?.contents_id; + let changed = instances(doc, contents_id); + let mut warnings = std::collections::BTreeSet::new(); + for &instance in &changed { + smart_mut(doc, instance)?.source = new.clone(); + if !keep_psd { + detach_psd(doc.layer_mut(instance).ok_or(EngineError::NoLayer(instance))?); + } + warnings + .extend(unapplied_filters(smart(doc, instance)?).into_iter().map(|n| format!("the {n} smart filter is not supported, so it was not applied"))); + refresh_or_fail(doc, instance)?; + } + Ok((doc.id, contents_id, changed, warnings)) + })?; + // An old editor must not overwrite newly replaced/relinked contents on close. Keep its + // document open, but the next Edit Contents opens the replacement source. + s.smart_links.retain(|l| l.parent != parent || l.contents_id != contents_id); + // Every instance changed, not only `layer`: list them, so a caller doesn't repeat the + // command once per copy (#4075). + Ok(json!({"layer": id.0, "instances": changed.iter().map(|l| l.0).collect::>(), "warnings": warnings})) +} + +pub(super) fn replace_contents(s: &mut Session, p: &Value) -> Result { + let path = path_param("layer.smartObjects.replaceContents", p)?.to_string(); + let bytes = photocraft_format::read_file(std::path::Path::new(&path)).map_err(|e| other(format!("can't read {path}: {e}")))?; + let id = layer_param(s, p)?; + replace_contents_bytes(s, id, &base_name(&path), bytes) +} + +/// Replace Contents with a file the caller already read, for the smart object `p` names (`layer`, +/// else the active layer): the body of the command minus its ambient path read (#8061). +pub fn replace_contents_from_bytes(s: &mut Session, p: &Value, file_name: &str, bytes: Vec) -> Result { + let id = layer_param(s, p)?; + replace_contents_bytes(s, id, file_name, bytes) +} + +/// Replace Contents from a file's name and bytes: what the desktop and web file pickers hand over. +pub fn replace_contents_bytes(s: &mut Session, id: LayerId, file_name: &str, bytes: Vec) -> Result { + decode_source(file_name, &bytes)?; // fail before touching the document + set_shared_source(s, id, "Replace Contents", false, SmartSource::Embedded { file_name: file_name.to_string(), bytes: Arc::new(bytes) }) +} + +/// The file name and bytes of smart object `id`'s contents. +pub fn contents_of(doc: &Document, id: LayerId) -> Result<(String, Arc>)> { + source_bytes(&doc.metadata, &smart(doc, id)?.source).ok_or_else(|| other("the smart object's contents are unavailable")) +} + +/// Writes the smart object's file as it is. To a path with another extension (a `.png` for +/// `.psb` or `.pcraft` contents) the contents are opened and exported in that format instead. +pub(super) fn export_contents(s: &mut Session, p: &Value) -> Result { + let path = path_param("layer.smartObjects.exportContents", p)?; + let id = layer_param(s, p)?; + let (name, bytes) = contents_of(&s.active().ok_or(EngineError::NoDocument)?.doc, id)?; + let ext = |f: &str| { + let e = std::path::Path::new(f).extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase); + e.map(|e| match e.as_str() { + "jpeg" => "jpg".to_string(), + "tiff" => "tif".to_string(), + _ => e, + }) + }; + if ext(path).is_none() || ext(path) == ext(&name) { + crate::file_cmds::write_file(path, &bytes)?; + return Ok(json!({"path": path, "fileName": name, "bytes": bytes.len(), "converted": false})); + } + let contents = decode_source(&name, &bytes)?; + let r = photocraft_io::export(&contents, path, &Default::default()).map_err(|e| other(format!("can't export the contents as {}: {e}", base_name(path))))?; + crate::file_cmds::write_file(path, &r.bytes)?; + Ok(json!({"path": path, "fileName": name, "bytes": r.bytes.len(), "converted": true, "warnings": r.warnings})) +} + +pub(super) fn edit_contents(s: &mut Session, p: &Value) -> Result { + let id = layer_param(s, p)?; + let st = s.active().ok_or(EngineError::NoDocument)?; + let parent = st.doc.id; + let contents_id = smart(&st.doc, id)?.contents_id; + // Already open for editing: switch to that document rather than opening another copy. + if let Some(index) = + s.smart_links.iter().find(|l| l.parent == parent && l.contents_id == contents_id).and_then(|l| s.documents().iter().position(|d| d.doc.id == l.child)) + { + s.set_active(index); + return Ok(json!({"document": index, "parentLayer": id.0})); + } + let source = &smart(&st.doc, id)?.source; + let (name, bytes) = authorized_source_bytes(s, "layer.smartObjects.editContents", &st.doc.metadata, source)? + .ok_or_else(|| other("the smart object's contents are unavailable"))?; + let mut child = decode_source(&name, &bytes)?; + // Bundles keep their document id; each open copy needs its own. + child.id = DocId::fresh(); + child.name = name; + let index = s.add_document(child, None); + // Admission may replace an ID already owned by another open document. + let child_id = s.documents().get(index).ok_or(EngineError::NoDocument)?.doc.id; + s.smart_links.retain(|l| l.child != child_id); + s.smart_links.push(SmartLink { child: child_id, parent, layer: id, contents_id }); + Ok(json!({"document": index, "parentLayer": id.0})) +} + +/// Writes an Edit Contents document back into all its parent instances (one undoable step in the +/// parent) and marks it saved. Returns false if `index` isn't an Edit Contents document. +pub fn commit_child(s: &mut Session, index: usize) -> Result { + let Some(st) = s.docs.get(index) else { return Ok(false) }; + let child = st.doc.clone(); + let Some(link) = s.smart_links.iter().find(|l| l.child == child.id).copied() else { return Ok(false) }; + let parent = s.docs.iter().position(|d| d.doc.id == link.parent).ok_or_else(|| other("the smart object's document was closed"))?; + let bytes = Arc::new(encode_source(&child)?); + let prev = s.active; + s.active = Some(parent); + s.note_active_change(); + let r = s.edit("Edit Contents", |doc, _| { + let ids = instances(doc, link.contents_id); + if ids.is_empty() { + return Err(other("the smart object's instances were removed")); + } + for id in ids { + let sm = smart_mut(doc, id)?; + let name = match &sm.source { + SmartSource::Embedded { file_name, .. } => file_name.as_str(), + SmartSource::Linked { .. } => child.name.as_str(), + }; + let stem = name.rsplit_once('.').map_or(name, |(stem, _)| stem); + sm.source = SmartSource::Embedded { file_name: format!("{stem}.pcraft"), bytes: bytes.clone() }; + detach_psd(doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?); + refresh_or_fail(doc, id)?; + } + Ok(()) + }); + s.active = prev; + s.note_active_change(); + r?; + if let Some(st) = s.docs.get_mut(index) { + st.saved_revision = st.revision; + } + Ok(true) +} + +/// Called before a document closes: an edited Edit Contents document updates its parent. +pub(crate) fn on_close(s: &mut Session, index: usize) { + let Some(st) = s.docs.get(index) else { return }; + let id = st.doc.id; + if st.is_dirty() && s.smart_links.iter().any(|l| l.child == id) { + let _ = commit_child(s, index); + } + s.smart_links.retain(|l| l.child != id && l.parent != id); +} + +pub(super) fn is_smart_child(s: &Session) -> std::result::Result<(), String> { + let d = s.active().ok_or("no document open")?; + if s.smart_links.iter().any(|l| l.child == d.doc.id) { Ok(()) } else { Err("this document isn't smart object contents".into()) } +} + +pub(super) fn update_all(s: &mut Session) -> Result { + let ids: Vec = s + .active() + .ok_or(EngineError::NoDocument)? + .doc + .walk() + .into_iter() + .filter(|(_, _, l)| matches!(&l.content, LayerContent::Smart(sm) if matches!(sm.source, SmartSource::Linked { .. }))) + .map(|(_, _, l)| l.id) + .collect(); + let mut updated = Vec::new(); + s.edit("Update All Modified Content", |doc, _| { + for id in &ids { + if refresh(doc, *id)? { + updated.push(id.0); + } + } + Ok(()) + })?; + Ok(json!({"updated": updated})) +} diff --git a/crates/engine/src/cmd/smart_cmds/filters.rs b/crates/engine/src/cmd/smart_cmds/filters.rs new file mode 100644 index 0000000000..e06cb61a48 --- /dev/null +++ b/crates/engine/src/cmd/smart_cmds/filters.rs @@ -0,0 +1,296 @@ +use super::rendering::{refresh_or_fail, refresh_or_fail_in}; +use super::source::source_bytes; +use super::*; + +pub(super) fn smart(doc: &Document, id: LayerId) -> Result<&SmartObject> { + match &doc.layer(id).ok_or(EngineError::NoLayer(id))?.content { + LayerContent::Smart(sm) => Ok(sm), + _ => Err(other("the layer is not a smart object")), + } +} + +pub(super) fn smart_mut(doc: &mut Document, id: LayerId) -> Result<&mut SmartObject> { + match &mut doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?.content { + LayerContent::Smart(sm) => Ok(sm), + _ => Err(other("the layer is not a smart object")), + } +} + +/// Whether `l`'s filter mask can be painted (`"target":"filterMask"`): a smart object with smart +/// filters. Its filter mask need not exist yet: painting starts it white (Reveal All), the mask +/// Photoshop adds with the first smart filter. +pub(crate) fn filter_mask_paintable(l: &Layer) -> std::result::Result<(), String> { + match &l.content { + LayerContent::Smart(sm) if !sm.smart_filters.is_empty() => Ok(()), + LayerContent::Smart(_) => Err(format!("smart object \"{}\" has no smart filters, so no filter mask", l.name)), + other => Err(format!("the active layer is {} {} layer, not a smart object", other.article(), other.kind_name())), + } +} + +/// The filter mask surface of smart object `id` for painting into, made white (Reveal All) first +/// when the object has smart filters but no filter mask yet. The caller re-renders the object +/// afterwards ([`refresh_after_filter_mask_edit`]). +pub(crate) fn filter_mask_surface(doc: &mut Document, id: LayerId) -> Result<&mut Surface> { + let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; + filter_mask_paintable(l).map_err(EngineError::Other)?; + let sm = smart_mut_of(l)?; + Ok(&mut sm.filter_mask.get_or_insert_with(LayerMask::reveal_all).surface) +} + +/// Re-renders smart object `id` after its filter mask was painted, filled or filtered, so the +/// stroke shows (where the mask is black the smart filters don't). Part of the same history step. +pub(crate) fn refresh_after_filter_mask_edit(doc: &mut Document, id: LayerId) -> Result<()> { + if matches!(doc.layer(id).map(|l| &l.content), Some(LayerContent::Smart(_))) { refresh_or_fail(doc, id) } else { Ok(()) } +} + +fn smart_mut_of(l: &mut Layer) -> Result<&mut SmartObject> { + match &mut l.content { + LayerContent::Smart(sm) => Ok(sm), + _ => Err(other("the layer is not a smart object")), + } +} + +fn mask_from_selection(sel: &Surface) -> LayerMask { + LayerMask { surface: sel.clone(), enabled: true, linked: true, density: 1.0, feather: 0.0 } +} + +/// Appends a smart filter (from a `filter.*` command) and re-renders. A selection becomes the +/// filter mask, as in Photoshop. Without a renderable source the filter is applied to the cached +/// pixels (and still recorded). +pub(crate) fn add_smart_filter(doc: &mut Document, id: LayerId, sf: photocraft_doc::SmartFilter, selection: Option<&Surface>) -> Result<()> { + let canvas = doc.bounds(); + let renderable = source_bytes(&doc.metadata, &smart(doc, id)?.source).is_some(); + let sm = smart_mut(doc, id)?; + if renderable { + if let Some(sel) = selection + && sm.filter_mask.is_none() + { + sm.filter_mask = Some(mask_from_selection(sel)); + } + sm.smart_filters.push(sf); + return refresh_or_fail(doc, id); + } + let bounds = selection.map(Surface::content_bounds).filter(|b| !b.is_empty()).unwrap_or(canvas); + let cache = sm.cache.as_ref().ok_or_else(|| other("smart object has no pixels"))?; + let out = crate::filters::apply_filter_to_surface(&sf.command, &sf.params, cache, bounds, selection, canvas)? + .ok_or_else(|| other(format!("unknown filter {}", sf.command)))?; + sm.cache = Some(out); + sm.smart_filters.push(sf); + Ok(()) +} + +// ---------- smart filter editing ---------- + +/// Edits the smart filters of a smart object and re-renders it. The edit itself is instant, so its +/// errors (a bad index, say) are reported at once; the re-render runs as a background job when +/// started with `Session::start`, so the window keeps drawing (with progress, cancellable) while +/// a long filter stack recomputes. +pub(super) fn edit_filters(s: &mut Session, p: &Value, label: &str, f: impl FnOnce(&mut SmartObject) -> Result<()>) -> Result { + let id = layer_param(s, p)?; + let mut edited = smart(&s.active().ok_or(EngineError::NoDocument)?.doc, id)?.clone(); + f(&mut edited)?; + crate::jobs::edit_job( + s, + label, + move |doc, _, ctx| { + *smart_mut(doc, id)? = edited; + refresh_or_fail_in(doc, id, ctx) + }, + move |()| json!({"layer": id.0}), + ) +} + +fn filter_index(cmd: &str, p: &Value, sm: &SmartObject) -> Result { + let n = sm.smart_filters.len(); + if n == 0 { + return Err(other("the smart object has no smart filters")); + } + match p.get("index") { + None => Ok(n - 1), + Some(v) => v.as_u64().map(|i| i as usize).filter(|i| *i < n).ok_or_else(|| bad(cmd, format!("`index` must be 0..{n} (0 = bottom filter)"))), + } +} + +pub(super) fn set_filter_visible(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "layer.smartFilter.setVisible"; + edit_filters(s, p, "Smart Filter Visibility", |sm| { + let i = filter_index(CMD, p, sm)?; + let f = &mut sm.smart_filters[i]; + f.visible = p.get("visible").and_then(Value::as_bool).unwrap_or(!f.visible); + Ok(()) + }) +} + +/// The Displace filter, whose map a smart filter keeps embedded in its params. +const DISPLACE: &str = "filter.distort.displace"; + +pub(super) fn set_filter_params(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "layer.smartFilter.setParams"; + let new = p.get("params").cloned().ok_or_else(|| bad(CMD, "pass `params` (merged into the filter's parameters)"))?; + let authorize = s.authorize; + // A Displace given another open document as its map embeds that one in place of the old + // (#7423). It is read here, before the edit, from the session; the request is authorized + // first, as the merged params are below. A new `mapPath` stays a path (read next to the + // document on each re-render) and only drops the old embedded map; an empty one, or a + // negative `mapDocument` (the dialog's "None"), names no map. + let new_map_asked = crate::filters_ext::map_document(&new).is_some(); + let new_path = crate::filters_ext::map_path(&new).is_some(); + let displace = { + let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; + let sm = smart(doc, layer_param(s, p)?)?; + sm.smart_filters.get(filter_index(CMD, p, sm)?).is_some_and(|f| f.command == DISPLACE) + }; + let new_map = if displace && new_map_asked { + // The old embedded map, if the edit passed it back, gives way to the one named. + let request = crate::filters_ext::displace_request(&new); + if let Some(gate) = authorize { + gate(DISPLACE, &request)?; + } + let mut fp = crate::filters::params_for(DISPLACE, &request).ok_or_else(|| bad(CMD, "unreadable Displace settings"))?; + crate::filters_ext::resolve(s, &mut fp, &request)?; + match fp { + photocraft_algo::FilterParams::Displace { map, .. } => map, + _ => None, + } + } else { + None + }; + edit_filters(s, p, "Edit Smart Filter", |sm| { + let i = filter_index(CMD, p, sm)?; + let f = &mut sm.smart_filters[i]; + if f.command == photocraft_io::smart_map::UNSUPPORTED_FILTER { + return Err(bad(CMD, "this smart filter isn't implemented in PhotoCraft: it is kept as is (it can be hidden, moved or deleted)")); + } + match (&mut f.params, new) { + (Value::Object(old), Value::Object(n)) => old.extend(n), + (slot, n) => *slot = n, + } + if f.command == DISPLACE { + if let Some(map) = &new_map { + f.params = photocraft_io::smart_map::displace_embed_map(&f.params, map) + .ok_or_else(|| bad(CMD, "the displacement map is too large to keep in a Smart Object's filter"))?; + } else if new_path { + f.params = photocraft_io::smart_map::displace_without_map(&f.params); + } + } + // Authorize the underlying command with the complete merged params, including paths + // already stored in the document, before committing the edit or starting a worker. + if let Some(gate) = authorize { + gate(&f.command, &f.params)?; + } + Ok(()) + }) +} + +pub(super) fn blending_options(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "layer.smartFilter.blendingOptions"; + let blend = match p.get("blend").and_then(Value::as_str) { + Some(b) => Some(blend_from_str(b).filter(|m| *m != BlendMode::PassThrough).ok_or_else(|| bad(CMD, format!("unknown blend mode `{b}`")))?), + None => None, + }; + let opacity = p.get("opacity").and_then(Value::as_f64).map(|o| if o > 1.0 { o / 100.0 } else { o } as f32); + edit_filters(s, p, "Smart Filter Blending Options", |sm| { + let i = filter_index(CMD, p, sm)?; + let f = &mut sm.smart_filters[i]; + if let Some(b) = blend { + f.blend = b; + } + if let Some(o) = opacity { + f.opacity = o.clamp(0.0, 1.0); + } + Ok(()) + }) +} + +pub(super) fn delete_filter(s: &mut Session, p: &Value) -> Result { + edit_filters(s, p, "Delete Smart Filter", |sm| { + let i = filter_index("layer.smartFilter.delete", p, sm)?; + sm.smart_filters.remove(i); + if sm.smart_filters.is_empty() { + sm.filter_mask = None; + } + Ok(()) + }) +} + +pub(super) fn move_filter(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "layer.smartFilter.move"; + edit_filters(s, p, "Move Smart Filter", |sm| { + let i = filter_index(CMD, p, sm)?; + let n = sm.smart_filters.len(); + let to = p.get("to").and_then(Value::as_u64).map(|t| t as usize).filter(|t| *t < n).ok_or_else(|| bad(CMD, format!("`to` must be 0..{n}")))?; + let f = sm.smart_filters.remove(i); + sm.smart_filters.insert(to, f); + Ok(()) + }) +} + +/// Dragging smart filters onto another smart object in the Layers panel (#4271): they move there, +/// or are copied with `copy` (⌥-drag in Photoshop). One filter (`filter`) lands on top of the +/// target's filters; all of them (the Smart Filters row) are added on top too, with the filter +/// mask when the target has none. Both smart objects are re-rendered in one undo step. +pub(super) fn transfer_filters(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "layer.smartFilter.transfer"; + let id_of = |key: &str| p.get(key).and_then(Value::as_u64).map(LayerId).ok_or_else(|| bad(CMD, format!("`{key}` must be a layer id"))); + let (from, to) = (id_of("from")?, id_of("to")?); + if from == to { + return Err(bad(CMD, "the smart filters are already on that layer")); + } + // The other `layer.smartFilter.*` commands name a filter `index`; here a guessed `index` + // would otherwise be dropped and every filter moved. + if p.get("index").is_some() { + return Err(bad(CMD, "name the filter with `filter` (no `filter`: all of them)")); + } + let copy = p.get("copy").and_then(Value::as_bool).unwrap_or(false); + let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; + let src = smart(doc, from)?; + smart(doc, to).map_err(|_| bad(CMD, "smart filters can only be dropped on a smart object"))?; + let n = src.smart_filters.len(); + if n == 0 { + return Err(other("the smart object has no smart filters")); + } + let index = match p.get("filter") { + None | Some(Value::Null) => None, + Some(v) => Some(v.as_u64().map(|i| i as usize).filter(|i| *i < n).ok_or_else(|| bad(CMD, format!("`filter` must be 0..{n} (0 = bottom filter)")))?), + }; + let (filters, mask) = match index { + Some(i) => (vec![src.smart_filters[i].clone()], None), + None => (src.smart_filters.clone(), src.filter_mask.clone()), + }; + let label = match (copy, index.is_some()) { + (true, true) => "Copy Smart Filter", + (true, false) => "Copy Smart Filters", + (false, true) => "Move Smart Filter", + (false, false) => "Move Smart Filters", + }; + crate::jobs::edit_job( + s, + label, + move |doc, _, ctx| { + let dst = smart_mut(doc, to)?; + dst.smart_filters.extend(filters); + if dst.filter_mask.is_none() { + dst.filter_mask = mask; + } + refresh_or_fail_in(doc, to, ctx)?; + if !copy { + let src = smart_mut(doc, from)?; + match index { + Some(i) => { + src.smart_filters.remove(i); + if src.smart_filters.is_empty() { + src.filter_mask = None; + } + } + None => { + src.smart_filters.clear(); + src.filter_mask = None; + } + } + refresh_or_fail_in(doc, from, ctx)?; + } + Ok(()) + }, + move |()| json!({"from": from.0, "to": to.0}), + ) +} diff --git a/crates/engine/src/cmd/smart_cmds/placing.rs b/crates/engine/src/cmd/smart_cmds/placing.rs new file mode 100644 index 0000000000..857cb90338 --- /dev/null +++ b/crates/engine/src/cmd/smart_cmds/placing.rs @@ -0,0 +1,269 @@ +use super::source::{SourceImage, buffer_to_surface, cache_key, cache_put, source_bytes}; +use super::*; + +/// Rounds float noise off a composed transform (scale 0.1 then 10 should be exactly 1), so +/// repeated transforms land back on exact, lossless placements. +pub(crate) fn snap_affine(a: Affine) -> Affine { + Affine { m: a.m.map(|v| if (v - v.round()).abs() < 1e-9 { v.round() } else { v }) } +} + +/// Where the smart object's source pixels land in the document: its projective map (Distort, +/// Perspective) or its affine transform. +pub fn placement(sm: &SmartObject) -> Homography { + sm.perspective.map(Homography).unwrap_or_else(|| affine_homography(&sm.transform)) +} + +pub(crate) fn affine_homography(a: &Affine) -> Homography { + let [a, b, c, d, e, f] = a.m; + Homography([a, c, e, b, d, f, 0.0, 0.0, 1.0]) +} + +/// Sets where the source lands. An affine map is stored exactly in `transform` (no +/// `perspective`); a projective one in `perspective`, with `transform` its affine approximation at +/// the source origin (for code that only needs scale and position). +pub(crate) fn set_placement(sm: &mut SmartObject, h: Homography) { + let m = h.0; + let n = if m[8].abs() > 1e-12 { m.map(|v| v / m[8]) } else { m }; + if n[6].abs() < 1e-12 && n[7].abs() < 1e-12 { + sm.transform = snap_affine(Affine { m: [n[0], n[3], n[1], n[4], n[2], n[5]] }); + sm.perspective = None; + return; + } + let h = Homography(n); + let (o, x, y) = (h.apply(0.0, 0.0), h.apply(1.0, 0.0), h.apply(0.0, 1.0)); + sm.transform = Affine { m: [x.0 - o.0, x.1 - o.1, y.0 - o.0, y.1 - o.1, o.0, o.1] }; + sm.perspective = Some(n); +} + +/// Composes `a` (document → document) onto the smart object's placement. +pub(crate) fn transform_placement(sm: &mut SmartObject, a: &Affine) { + match sm.perspective { + None => sm.transform = snap_affine(a.mul(&sm.transform)), + Some(_) => set_placement(sm, affine_homography(a).mul(&placement(sm))), + } +} + +/// Moves a smart object by whole pixels without re-rendering. +pub(crate) fn shift_smart(sm: &mut SmartObject, dx: i32, dy: i32) { + transform_placement(sm, &Affine::translate(dx as f64, dy as f64)); + if let Some(c) = &mut sm.cache { + *c = crate::layer_multi_cmds::shift_surface(c, dx, dy); + } + if let Some(m) = &mut sm.filter_mask { + m.surface = crate::layer_multi_cmds::shift_surface(&m.surface, dx, dy); + } +} + +/// Forget PSD placed-layer data that no longer describes the smart object (its source changed): +/// PSD export then writes fresh placed-layer blocks and embeds the new source. +pub(super) fn detach_psd(l: &mut Layer) { + if let LayerContent::Smart(sm) = &mut l.content { + sm.psd_raw = None; + } + l.psd_blocks.retain(|(k, _)| !PLACED_KEYS.contains(&k)); +} + +// ---------- conversion ---------- + +/// Moves a layer (any kind) by whole pixels without re-rendering anything. +pub(super) fn shift_layer(l: &mut Layer, dx: i32, dy: i32) { + if dx == 0 && dy == 0 { + return; + } + let a = Affine::translate(dx as f64, dy as f64); + let mv = |s: &Surface| translate_surface(s, dx, dy); + if let Some(m) = &mut l.mask { + m.surface = mv(&m.surface); + } + if let Some(vm) = &mut l.vector_mask { + vm.path = vm.path.transform(&a); + } + if let Some(fc) = &mut l.fill_cache { + fc.surface = mv(&fc.surface); + } + match &mut l.content { + LayerContent::Raster(s) => *s = mv(s), + LayerContent::Text(t) => { + t.transform = a.mul(&t.transform); + if let Some(c) = &mut t.cache { + *c = mv(c); + } + } + LayerContent::Shape(sh) => { + crate::vector_cmds::transform_shape(sh, &a); + if let Some(c) = &mut sh.cache { + *c = mv(c); + } + } + LayerContent::Smart(sm) => shift_smart(sm, dx, dy), + LayerContent::Group(g) => g.children.iter_mut().for_each(|c| shift_layer(c, dx, dy)), + LayerContent::Adjustment(_) | LayerContent::Fill(_) => {} + } +} + +fn subtree_bounds(l: &Layer, canvas: Rect) -> Rect { + match &l.content { + LayerContent::Group(g) => g.children.iter().map(|c| subtree_bounds(c, canvas)).fold(Rect::EMPTY, |a, b| a.union(&b)), + LayerContent::Adjustment(_) | LayerContent::Fill(_) => canvas, + _ => l.surface().map_or(Rect::EMPTY, Surface::content_bounds), + } +} + +fn any_layer(l: &Layer, f: &dyn Fn(&Layer) -> bool) -> bool { + f(l) || l.children().is_some_and(|c| c.iter().any(|c| any_layer(c, f))) +} + +/// Builds the smart-object layer replacing `l` in `doc`: the layer (with its mask, effects and +/// fill opacity) becomes a nested document cropped to its rendered bounds; visibility, opacity, +/// blend mode, clipping and label stay on the smart layer. The cache is the exact composite, so +/// the document looks the same before and after. +pub fn layer_to_smart(doc: &Document, l: &Layer) -> Result { + let background = doc.is_background(l.id); + let mut inner = l.clone(); + inner.visible = true; + inner.opacity = 1.0; + inner.clipped = false; + inner.locks = Default::default(); + if !(inner.is_group() && inner.blend == BlendMode::PassThrough) { + inner.blend = BlendMode::Normal; + } + if background { + inner.name = "Layer 0".into(); + } + let mut out = layers_to_smart(doc, &l.name, vec![inner])?; + if background { + out.name = "Layer 0".into(); + } + out.visible = l.visible; + out.opacity = l.opacity; + out.blend = if l.blend == BlendMode::PassThrough { BlendMode::Normal } else { l.blend }; + out.clipped = l.clipped; + out.label = l.label; + if !background { + out.locks = l.locks; + } + Ok(out) +} + +/// Builds a smart-object layer named `name` whose nested document holds `layers` (bottom to top) +/// at its top level, as Photoshop does when several layers are converted: no wrapper group. The +/// nested document is cropped to the rendered bounds and the cache is the exact composite (the +/// same as the layers inside a pass-through group). The smart layer is visible, opaque and Normal. +pub fn layers_to_smart(doc: &Document, name: &str, layers: Vec) -> Result { + let canvas = doc.bounds(); + let mut sub = Document::new(format!("{name}.pcraft"), doc.size, doc.mode, doc.depth); + sub.resolution_dpi = doc.resolution_dpi; + sub.icc_profile = doc.icc_profile.clone(); + sub.global_light = doc.global_light; + // Pattern fills and pattern layer effects reference document-level patterns by ID. + // Preserve those resources in the embedded document before rendering or saving it. + sub.patterns = doc.patterns.clone(); + if layers.iter().any(|l| any_layer(l, &|x| matches!(x.content, LayerContent::Smart(_)))) { + // Nested PSD placed layers find their embedded files here. + sub.metadata.psd_global_blocks = doc.metadata.psd_global_blocks.clone(); + } + let has_fx = layers.iter().any(|l| any_layer(l, &|x| x.effects.enabled && !x.effects.items.is_empty())); + let region = layers.iter().map(|l| subtree_bounds(l, canvas)).fold(canvas, |a, b| a.union(&b)).inflate(if has_fx { 256 } else { 0 }); + sub.layers = layers; + + let buf = photocraft_compose::render(&sub, region); + let w = region.width() as usize; + let mut b = Rect::EMPTY; + for (i, p) in buf.px.iter().enumerate() { + if p[3] > 0.0 { + let (x, y) = (region.x0 + (i % w) as i32, region.y0 + (i / w) as i32); + b = b.union(&Rect::new(x, y, x + 1, y + 1)); + } + } + if b.is_empty() { + return Err(other("the layer is empty, so there is nothing to convert")); + } + let fmt = doc.pixel_format(); + let mut cache = buffer_to_surface(&buf, fmt); + cache = photocraft_algo::resample::crop_surface(&cache, b); + cache.prune(); + + sub.layers.iter_mut().for_each(|l| shift_layer(l, -b.x0, -b.y0)); + sub.size = Size::new(b.width(), b.height()); + let bytes = encode_source(&sub)?; + // Seed the decode cache with the composite we already have. + cache_put(cache_key(&bytes, fmt), SourceImage { surface: Arc::new(translate_surface(&cache, -b.x0, -b.y0)), bounds: sub.bounds() }); + + let source = SmartSource::Embedded { file_name: sub.name.clone(), bytes: Arc::new(bytes) }; + Ok(Layer::new(name, LayerContent::Smart(SmartObject::new(source, Affine::translate(b.x0 as f64, b.y0 as f64), Some(cache))))) +} + +pub(super) fn convert(s: &mut Session, p: &Value) -> Result { + let ids = match p.get("layer").and_then(Value::as_u64) { + Some(id) => vec![LayerId(id)], + None => crate::layer_multi_cmds::selected(s), + }; + let new_id = s.edit("Convert to Smart Object", |doc, active| { + let ids = crate::layer_multi_cmds::top_level(doc, &ids); + let top = *ids.last().ok_or_else(|| other("no layer selected"))?; + let l = doc.layer(top).ok_or(EngineError::NoLayer(top))?; + let so = if ids.len() == 1 { + layer_to_smart(doc, l)? + } else { + let children = ids.iter().map(|id| doc.layer(*id).cloned().ok_or(EngineError::NoLayer(*id))).collect::>>()?; + layers_to_smart(doc, &l.name, children)? + }; + let new_id = so.id; + // As with Group Layers, place the result in the top selected root's parent. Insert + // before removal so paths shifting in other parents cannot discard unselected content. + doc.insert_above(Some(top), so); + for id in &ids { + doc.remove(*id).ok_or(EngineError::NoLayer(*id))?; + } + if let [only] = ids[..] { + retarget_layer_refs(doc, only, new_id); + } + *active = Some(new_id); + Ok(new_id) + })?; + crate::layer_multi_cmds::reselect(s, vec![new_id], Some(new_id)); + Ok(json!({"layer": new_id.0})) +} + +fn retarget_layer_refs(doc: &mut Document, from: LayerId, to: LayerId) { + let Some((fill_opacity, effects)) = doc.layer(to).map(|l| (l.fill_opacity, l.effects.clone())) else { return }; + for comp in doc.layer_comps.iter_mut().chain(doc.last_document_state.as_mut()) { + for state in comp.states.iter_mut().filter(|state| state.layer == from) { + state.layer = to; + if let Some(appearance) = &mut state.appearance { + appearance.fill_opacity = fill_opacity; + appearance.effects = effects.clone(); + } + } + } + for def in doc.variables.defs.iter_mut().filter(|def| def.layer == from) { + def.layer = to; + } + for slice in doc.slices.list.iter_mut().filter(|slice| slice.layer == Some(from)) { + slice.layer = Some(to); + } +} + +// ---------- contents ---------- + +pub(super) fn via_copy(s: &mut Session, p: &Value) -> Result { + let id = layer_param(s, p)?; + s.edit("New Smart Object via Copy", |doc, active| { + let src = doc.layer(id).ok_or(EngineError::NoLayer(id))?; + let mut copy = src.duplicate(); + copy.name = doc.copy_name(&src.name); + if let LayerContent::Smart(sm) = &mut copy.content { + // Independent contents: resolve to embedded bytes and drop the shared PSD uuid. + sm.contents_id = SmartContentsId::fresh(); + if let Some((file_name, bytes)) = source_bytes(&doc.metadata, &sm.source) { + sm.source = SmartSource::Embedded { file_name, bytes }; + } + } else { + return Err(other("the layer is not a smart object")); + } + detach_psd(&mut copy); + let new_id = doc.insert_above(Some(id), copy); + *active = Some(new_id); + Ok(json!({"layer": new_id.0})) + }) +} diff --git a/crates/engine/src/cmd/smart_cmds/rendering.rs b/crates/engine/src/cmd/smart_cmds/rendering.rs new file mode 100644 index 0000000000..b686cf3282 --- /dev/null +++ b/crates/engine/src/cmd/smart_cmds/rendering.rs @@ -0,0 +1,342 @@ +use super::filters::smart; +use super::source::{SourceImage, cache_get, cache_key, cache_put, source_bytes, source_image, source_surface, svg_source_image, vector_scale}; +use super::*; + +/// Layer › Smart Objects › Stack Mode: the source's layers (or, when it holds a single group, the +/// group's layers) combined per pixel with `mode`. Cached like [`source_image`], keyed by mode. +pub fn stack_image(file_name: &str, bytes: &[u8], fmt: PixelFormat, mode: photocraft_doc::StackMode) -> Result { + use photocraft_algo::stack::Stat; + let mut key = cache_key(bytes, fmt); + key.0 = *blake3::hash(&[&key.0[..], b"stack:", mode.id().as_bytes()].concat()).as_bytes(); + if let Some(img) = cache_get(&key) { + return Ok(img); + } + let doc = decode_source(file_name, bytes)?; + let layers: &[Layer] = match doc.layers.as_slice() { + [only] if only.is_group() => only.children().unwrap_or_default(), + all => all, + }; + let bounds = doc.bounds(); + let frames: Vec> = layers + .iter() + .filter(|l| l.visible) + .map(|l| { + let mut one = l.clone(); + one.blend = BlendMode::Normal; + one.clipped = false; + photocraft_compose::render_layer(&one, bounds).px + }) + .collect(); + if frames.is_empty() { + return Err(EngineError::Other("the smart object's contents have no visible layers".into())); + } + let stat = match mode { + photocraft_doc::StackMode::Entropy => Stat::Entropy, + photocraft_doc::StackMode::Kurtosis => Stat::Kurtosis, + photocraft_doc::StackMode::Maximum => Stat::Maximum, + photocraft_doc::StackMode::Mean => Stat::Mean, + photocraft_doc::StackMode::Median => Stat::Median, + photocraft_doc::StackMode::Minimum => Stat::Minimum, + photocraft_doc::StackMode::Range => Stat::Range, + photocraft_doc::StackMode::Skewness => Stat::Skewness, + photocraft_doc::StackMode::StandardDeviation => Stat::StandardDeviation, + photocraft_doc::StackMode::Summation => Stat::Summation, + photocraft_doc::StackMode::Variance => Stat::Variance, + }; + let buf = photocraft_compose::Buffer { rect: bounds, px: photocraft_algo::stack::combine(&frames, stat) }; + let img = SourceImage { surface: Arc::new(source_surface(&doc, &buf, fmt)?), bounds }; + cache_put(key, img.clone()); + Ok(img) +} + +// ---------- rendering ---------- + +/// Mix a filter's result with its input, without stacking the same pixel coverage twice. +pub(super) fn blend_surfaces(base: &Surface, top: &Surface, mode: BlendMode, opacity: f32) -> Surface { + if opacity <= 0.0 { + return base.clone(); + } + let fmt = base.format(); + let area = base.content_bounds().union(&top.content_bounds()); + let mut out = base.clone(); + if area.is_empty() { + return out; + } + let n = fmt.channels(); + let (b, t) = (base.read_region(area), top.read_region(area)); + // Alpha-preserving filters edit the same coverage. A non-Normal filter that + // changes coverage (e.g. blur) must also retain input-only pixels and admit + // filtered-only pixels, as Photoshop's Smart Filter blend oracles require. + // Classify the whole result so unchanged pixels do not switch blend rules + // independently at the edge of a blur. + let composite_coverage = mode != BlendMode::Normal && fmt.alpha && b.chunks_exact(n).zip(t.chunks_exact(n)).any(|(bp, tp)| bp.last() != tp.last()); + let mut o = vec![0.0f32; b.len()]; + for ((bp, tp), op) in b.chunks_exact(n).zip(t.chunks_exact(n)).zip(o.chunks_exact_mut(n)) { + let b = photocraft_raster::to_rgba(&fmt, bp); + let t = photocraft_raster::to_rgba(&fmt, tp); + if composite_coverage { + let rgba = photocraft_color::blend::composite(mode, b, t, opacity); + photocraft_raster::from_rgba_into(&fmt, rgba, op); + continue; + } + let cb = [b[0], b[1], b[2]]; + let ct = [t[0], t[1], t[2]]; + let color = if fmt.sample == photocraft_color::SampleType::F32 { + photocraft_color::blend::blend_rgb_hdr(mode, cb, ct) + } else { + photocraft_color::blend::blend_rgb(mode, cb, ct) + }; + // A filter edits this surface, rather than adding a second source-over layer. Mix + // premultiplied results so alpha-preserving filters keep coverage at every opacity, + // while Normal-mode filters that change coverage interpolate it too. + let a = b[3] + (t[3] - b[3]) * opacity; + let mut rgba = [0.0, 0.0, 0.0, a]; + if a > 0.0 { + for c in 0..3 { + rgba[c] = (cb[c] * b[3] * (1.0 - opacity) + color[c] * t[3] * opacity) / a; + } + } + photocraft_raster::from_rgba_into(&fmt, rgba, op); + } + out.write_region(area, &o); + out.prune(); + out +} + +/// Runs the smart filter stack on the placed (unfiltered) content. A filter the session's +/// authority denies surfaces its error (the trusted compositor path has no gate installed, so +/// this reads ambiently only when the caller established one and it refuses). +pub fn apply_smart_filters(placed: &Surface, sm: &SmartObject, canvas: Rect) -> Result { + if !sm.filters_enabled || !sm.smart_filters.iter().any(|f| f.visible) { + return Ok(placed.clone()); + } + let mut cur = placed.clone(); + // Edge pixels repeat at the canvas ∪ placed-content edge, as for layer filters. + let extent = canvas.union(&placed.content_bounds()); + for f in sm.smart_filters.iter().filter(|f| f.visible) { + cur = apply_smart_filter(f, &cur, filter_bounds(f, placed, canvas), extent)?; + } + Ok(match sm.filter_mask.as_ref().filter(|m| m.enabled) { + Some(m) => photocraft_compose::filter_mask::mix(placed, &cur, m), + None => cur, + }) +} + +/// The reference bounds of smart filter `f`. Render filters work within the smart object, as +/// Photoshop's do: Lens Flare's centre is a fraction of the object, and Clouds and Fibers fill it +/// and size their pattern by it. The object is its placed content's bounds (which leaves out +/// fully transparent edges of the source); the other filters use the canvas, as on a layer. +fn filter_bounds(f: &SmartFilter, placed: &Surface, canvas: Rect) -> Rect { + match placed.content_bounds() { + b if renders_in_object(f) && !b.is_empty() => b, + _ => canvas, + } +} + +fn renders_in_object(f: &SmartFilter) -> bool { + matches!(f.command.as_str(), "filter.render.clouds" | "filter.render.differenceClouds" | "filter.render.fibers" | "filter.render.lensFlare") +} + +/// One visible smart filter over `cur`, blended with its blend mode and opacity. `Err` when the +/// requesting session's authority denies the filter's params: callers surface the error instead of +/// rendering (and caching) unfiltered pixels. +fn apply_smart_filter(f: &SmartFilter, cur: &Surface, canvas: Rect, extent: Rect) -> Result { + let out = match crate::filters::apply_filter_to_surface(&f.command, &f.params, cur, canvas, None, extent)? { + // Unknown ids (e.g. Photoshop filters we don't implement) leave the pixels alone. + Some(out) => out, + None => cur.clone(), + }; + if f.blend == BlendMode::Normal && f.opacity >= 1.0 { Ok(out) } else { Ok(blend_surfaces(cur, &out, f.blend, f.opacity.clamp(0.0, 1.0))) } +} + +/// The source placed in document pixels, before any smart filter. +pub(super) fn place(name: &str, bytes: &[u8], fmt: PixelFormat, sm: &SmartObject) -> Result { + // A vector source is rendered at the placement's scale, and the placement is divided by + // that scale so the rendered pixels land where the source units would. + if sm.stack_mode.is_none() && sm.warp.is_none() && photocraft_io::svg::is_svg(bytes) { + let k = vector_scale(sm); + let img = svg_source_image(bytes, fmt, k)?; + return Ok(match &sm.perspective { + Some(p) => { + let [h0, h1, h2, h3, h4, h5, h6, h7, h8] = *p; + let h = Homography([h0 / k, h1 / k, h2, h3 / k, h4 / k, h5, h6 / k, h7 / k, h8]); + photocraft_algo::warp::place_source_projective(&img.surface, img.bounds, &h, None)? + } + None => { + let [a, b, c, d, e, f] = sm.transform.m; + let t = Affine { m: [a / k, b / k, c / k, d / k, e, f] }; + photocraft_algo::warp::place_source(&img.surface, img.bounds, &t, None)? + } + }); + } + let img = match sm.stack_mode { + Some(mode) => stack_image(name, bytes, fmt, mode)?, + None => source_image(name, bytes, fmt)?, + }; + // Through the warp (source space) and the transform in one pass; whole-pixel moves are exact. + Ok(match &sm.perspective { + Some(p) => photocraft_algo::warp::place_source_projective(&img.surface, img.bounds, &Homography(*p), sm.warp.as_ref())?, + None => photocraft_algo::warp::place_source(&img.surface, img.bounds, &sm.transform, sm.warp.as_ref())?, + }) +} + +/// The box of a smart object's source in source pixels (what its warp's `us`/`vs` span), or `None` +/// when the source can't be read. +pub(crate) fn source_box(doc: &Document, sm: &SmartObject) -> Option<[f64; 4]> { + let (name, bytes) = source_bytes(&doc.metadata, &sm.source)?; + let fmt = doc.pixel_format(); + let img = match sm.stack_mode { + Some(mode) => stack_image(&name, &bytes, fmt, mode), + None => source_image(&name, &bytes, fmt), + } + .ok()?; + let r = img.bounds; + Some([f64::from(r.x0), f64::from(r.y0), f64::from(r.x1), f64::from(r.y1)]) +} + +/// Renders a smart object from its source. `Ok(None)` when the source is unavailable (a missing +/// linked file, or a PSD placed layer without embedded data): callers keep the existing cache. +pub fn render(doc: &Document, sm: &SmartObject) -> Result> { + render_in(doc, sm, &JobCtx::new()) +} + +/// [`render`], reporting progress per smart filter to `ctx` and stopping between filters once it +/// is cancelled. Gives the same pixels as [`apply_smart_filters`] on the placed source, but +/// starts from the deepest stage of the stack already rendered (see [`stack_cache`]). +pub(super) fn render_in(doc: &Document, sm: &SmartObject, ctx: &JobCtx) -> Result> { + // Stored filters can come from a file or another layer. Check before looking up cached + // stages too: a trusted UI render may have populated this process-wide cache earlier. + for filter in sm.smart_filters.iter().filter(|f| sm.filters_enabled && f.visible) { + crate::jobs::authorize_render_command(&filter.command, &filter.params)?; + } + let Some((name, bytes)) = source_bytes(&doc.metadata, &sm.source) else { return Ok(None) }; + let (fmt, canvas) = (doc.pixel_format(), doc.bounds()); + let placed_key = stack_cache::placed_key(&bytes, fmt, sm, canvas); + let placed = || -> Result { + if let Some(stage) = stack_cache::get(&placed_key) { + return Ok(stage); + } + let surface = place(&name, &bytes, fmt, sm)?; + // Edge pixels repeat at the canvas ∪ placed-content edge, as for layer filters. + let stage = Stage { extent: canvas.union(&surface.content_bounds()), surface }; + stack_cache::put(placed_key, &stage); + Ok(stage) + }; + let filters: Vec<&SmartFilter> = sm.smart_filters.iter().filter(|f| sm.filters_enabled && f.visible).collect(); + if filters.is_empty() { + return Ok(Some(placed()?.surface)); + } + let keys: Vec = filters + .iter() + .scan(placed_key, |key, f| { + *key = stack_cache::filter_key(key, f); + Some(*key) + }) + .collect(); + let deepest = keys.iter().enumerate().rev().find_map(|(i, key)| stack_cache::get(key).map(|stage| (i + 1, stage))); + let (done, mut cur) = match deepest { + Some(hit) => hit, + None => (0, placed()?), + }; + let n = filters.len() as f32; + // The object's bounds, found once: the placed stage may have been evicted from the cache, and + // placing it again for every render filter would decode the source each time. + let mut object_bounds: Option = None; + for (i, (f, key)) in filters.iter().zip(&keys).enumerate().skip(done) { + ctx.check()?; + ctx.progress(i as f32 / n, ""); + let bounds = match object_bounds { + _ if !renders_in_object(f) => canvas, + Some(b) => b, + None => *object_bounds.insert(filter_bounds(f, &placed()?.surface, canvas)), + }; + cur = Stage { surface: apply_smart_filter(f, &cur.surface, bounds, cur.extent)?, extent: cur.extent }; + stack_cache::put(*key, &cur); + } + ctx.progress(1.0, ""); + Ok(Some(match sm.filter_mask.as_ref().filter(|m| m.enabled) { + Some(m) => photocraft_compose::filter_mask::mix(&placed()?.surface, &cur.surface, m), + None => cur.surface, + })) +} + +/// Bytes held by rendered smart filter stages. +pub fn stack_cache_bytes() -> usize { + stack_cache::bytes() +} + +/// Drop every rendered smart filter stage (Edit › Purge › All). Returns the bytes released. +pub fn purge_stack_cache() -> usize { + stack_cache::purge() +} + +/// The smart object's pixels below smart filter `index` (the input that filter edits): the placed +/// source and the filters under it, without the filter mask. `Ok(None)` when the source is +/// unavailable. +pub fn render_below_filter(doc: &Document, sm: &SmartObject, index: usize) -> Result> { + let mut below = sm.clone(); + below.smart_filters.truncate(index); + below.filter_mask = None; + render(doc, &below) +} + +/// Re-renders smart layer `l` (which lives in `doc`) in place. Returns false if its source is +/// unavailable or a visible filter can't be applied (the cache is then left alone). +pub fn refresh_layer(doc: &Document, l: &mut Layer) -> Result { + if matches!(&l.content, LayerContent::Smart(sm) if !unapplied_filters(sm).is_empty()) { + return Ok(false); + } + refresh_layer_in(doc, l, &JobCtx::new()) +} + +pub(super) fn unapplied_filters(sm: &SmartObject) -> Vec { + sm.smart_filters + .iter() + .filter(|f| sm.filters_enabled && f.visible && crate::commands::find(&f.command).is_none()) + .map(|f| f.params.get("name").and_then(Value::as_str).unwrap_or(&f.command).to_string()) + .collect() +} + +fn refresh_layer_in(doc: &Document, l: &mut Layer, ctx: &JobCtx) -> Result { + let LayerContent::Smart(sm) = &mut l.content else { return Ok(false) }; + match render_in(doc, sm, ctx)? { + Some(px) => { + sm.cache = Some(px); + Ok(true) + } + None => Ok(false), + } +} + +/// Re-renders the smart object `id` of `doc`. +pub fn refresh(doc: &mut Document, id: LayerId) -> Result { + refresh_in(doc, id, &JobCtx::new()) +} + +fn refresh_in(doc: &mut Document, id: LayerId, ctx: &JobCtx) -> Result { + let mut l = doc.layer(id).cloned().ok_or(EngineError::NoLayer(id))?; + if !matches!(l.content, LayerContent::Smart(_)) { + return Err(other("the layer is not a smart object")); + } + let ok = refresh_layer_in(doc, &mut l, ctx)?; + if ok && let Some(dst) = doc.layer_mut(id) { + dst.content = l.content; + } + Ok(ok) +} + +pub(super) fn refresh_or_fail(doc: &mut Document, id: LayerId) -> Result<()> { + refresh_or_fail_in(doc, id, &JobCtx::new()) +} + +pub(super) fn refresh_or_fail_in(doc: &mut Document, id: LayerId, ctx: &JobCtx) -> Result<()> { + if refresh_in(doc, id, ctx)? { + return Ok(()); + } + if let SmartSource::Linked { path } = &smart(doc, id)?.source + && let Err(why @ crate::doc_path::NotFollowed::Refused(_)) = crate::doc_path::resolve(path) + { + return Err(crate::doc_path::refusal("the linked file", path, why)); + } + Err(other("the smart object's contents are unavailable (missing linked file?), so it can't be re-rendered")) +} diff --git a/crates/engine/src/cmd/smart_cmds/source.rs b/crates/engine/src/cmd/smart_cmds/source.rs new file mode 100644 index 0000000000..0e0aaee477 --- /dev/null +++ b/crates/engine/src/cmd/smart_cmds/source.rs @@ -0,0 +1,217 @@ +use super::*; + +/// A linked file's bytes; `None` when it is missing or its path is not followed +/// ([`crate::doc_path::resolve`]). +/// +/// The path is document data, not a request parameter, so every read rechecks it with the gate +/// of the session the work is done for: a filter, transform or refresh re-renders from here, +/// not only the contents commands that judge it up front. A refused path is handled like a +/// missing file: the layer keeps its last rendering. +fn read_file(path: &str) -> Option> { + if path.is_empty() { + return None; + } + crate::jobs::authorize_render_command("layer.smartObjects.updateModifiedContent", &json!({"path": path})).ok()?; + photocraft_format::read_file(&crate::doc_path::resolve(path).ok()?).ok() +} + +/// The source file of a smart object: embedded bytes, the PSD's embedded linked-layer data (PSD +/// import keeps the placed layer's uuid as the path), or a linked file on disk. +pub fn source_bytes(meta: &Metadata, src: &SmartSource) -> Option<(String, Arc>)> { + embedded_source_bytes(meta, src).or_else(|| match src { + SmartSource::Linked { path } => read_file(path).map(|b| (base_name(path), Arc::new(b))), + SmartSource::Embedded { .. } => None, + }) +} + +/// Memory-only resolution also covers Photoshop's embedded files addressed by a `Linked` UUID. +fn embedded_source_bytes(meta: &Metadata, src: &SmartSource) -> Option<(String, Arc>)> { + match src { + SmartSource::Embedded { file_name, bytes } => Some((file_name.clone(), bytes.clone())), + SmartSource::Linked { path } => photocraft_io::linked::find_linked_file(meta, path).map(|f| (f.file_name, Arc::new(f.bytes))), + } +} + +/// The actual path is stored in the document, not in the command's params. Recheck it before +/// reading, reusing embedded PSD bytes rather than parsing their global blocks a second time. +pub(super) fn authorized_source_bytes(s: &Session, cmd: &str, meta: &Metadata, src: &SmartSource) -> Result>)>> { + if let Some(source) = embedded_source_bytes(meta, src) { + return Ok(Some(source)); + } + let SmartSource::Linked { path } = src else { return Ok(None) }; + if let Some(gate) = s.authorize { + gate(cmd, &json!({"path": path}))?; + } + Ok(read_file(path).map(|b| (base_name(path), Arc::new(b)))) +} + +/// Recheck a source's actual path before an untrusted command reads it: the path lives in the +/// document, not in the command's params. Embedded PSD UUIDs never reach the filesystem. +pub(super) fn authorize_source(s: &Session, cmd: &str, doc: &Document, src: &SmartSource) -> Result<()> { + if let (Some(gate), SmartSource::Linked { path }) = (s.authorize, src) + && embedded_source_bytes(&doc.metadata, src).is_none() + { + gate(cmd, &json!({"path": path}))?; + } + Ok(()) +} + +/// A decoded, composited source in its own pixel space (`bounds` starts at the origin). +#[derive(Clone, Debug)] +pub struct SourceImage { + pub surface: Arc, + pub bounds: Rect, +} + +type CacheKey = ([u8; 32], PixelFormat); + +struct CacheEntry { + key: CacheKey, + image: SourceImage, + decodes: u32, +} + +/// Decoded source composites by content hash, most recent last. Re-filtering or re-transforming +/// a smart object never decodes its contents again. +static SOURCE_CACHE: Mutex> = Mutex::new(Vec::new()); + +const CACHE_ENTRIES: usize = 32; + +const CACHE_BYTES: usize = 1 << 30; + +pub(super) fn cache_key(bytes: &[u8], fmt: PixelFormat) -> CacheKey { + (*blake3::hash(bytes).as_bytes(), fmt) +} + +pub(super) fn cache_get(key: &CacheKey) -> Option { + let mut c = SOURCE_CACHE.lock().ok()?; + let i = c.iter().position(|e| e.key == *key)?; + let e = c.remove(i); + let img = e.image.clone(); + c.push(e); + Some(img) +} + +pub(super) fn cache_put(key: CacheKey, image: SourceImage) { + let Ok(mut c) = SOURCE_CACHE.lock() else { return }; + let decodes = match c.iter().position(|e| e.key == key) { + Some(i) => c.remove(i).decodes + 1, + None => 1, + }; + c.push(CacheEntry { key, image, decodes }); + let size = |e: &CacheEntry| e.image.bounds.width() as usize * e.image.bounds.height() as usize * e.key.1.channels() * 4; + while c.len() > CACHE_ENTRIES || (c.len() > 1 && c.iter().map(size).sum::() > CACHE_BYTES) { + c.remove(0); + } +} + +/// How many times these contents were decoded at this pixel format (0 = never / evicted). +pub fn source_decode_count(bytes: &[u8], fmt: PixelFormat) -> u32 { + let key = cache_key(bytes, fmt); + SOURCE_CACHE.lock().ok().and_then(|c| c.iter().find(|e| e.key == key).map(|e| e.decodes)).unwrap_or(0) +} + +pub(crate) fn take_caches(layers: &mut [Layer]) -> Vec<(LayerId, Surface)> { + let mut out = Vec::new(); + for l in layers { + match &mut l.content { + LayerContent::Smart(sm) => out.extend(sm.cache.take().map(|c| (l.id, c))), + LayerContent::Group(g) => out.extend(take_caches(&mut g.children)), + _ => {} + } + } + out +} + +pub(crate) fn restore_unrendered( + doc: &mut Document, + taken: Vec<(LayerId, Surface)>, + mut fallback: impl FnMut(&Surface) -> std::result::Result, +) -> std::result::Result<(), E> { + for (id, cache) in taken { + if let Some(LayerContent::Smart(sm)) = doc.layer_mut(id).map(|l| &mut l.content) + && sm.cache.is_none() + { + sm.cache = Some(fallback(&cache)?); + } + } + Ok(()) +} + +pub(super) fn buffer_to_surface(buf: &photocraft_compose::Buffer, fmt: PixelFormat) -> Surface { + let n = fmt.channels(); + let mut data = vec![0.0f32; buf.px.len() * n]; + for (p, out) in buf.px.iter().zip(data.chunks_exact_mut(n)) { + photocraft_raster::from_rgba_into(&fmt, *p, out); + } + let mut s = Surface::new(fmt); + if !buf.rect.is_empty() { + s.write_region(buf.rect, &data); + } + s.prune(); + s +} + +pub(super) fn source_surface(src: &Document, buf: &photocraft_compose::Buffer, fmt: PixelFormat) -> Result { + let gray = fmt.mode == ColorMode::Grayscale && src.pixel_format().mode != ColorMode::Grayscale; + let linear = fmt.sample == SampleType::F32 && src.depth != SampleType::F32; + if !gray && !linear { + return Ok(buffer_to_surface(buf, fmt)); + } + let mut doc = Document::new(src.name.clone(), src.size, src.mode, src.depth); + doc.icc_profile = src.icc_profile.clone(); + doc.layers = vec![Layer::new("source", LayerContent::Raster(buffer_to_surface(buf, src.pixel_format())))]; + if gray { + let gray_profile = crate::color_cmds::working_profile(ColorMode::Grayscale); + crate::color_cmds::convert_document(&mut doc, &gray_profile, photocraft_cms::Intent::RelativeColorimetric, true)?; + } + if linear { + crate::image_cmds::change_depth(&mut doc, SampleType::F32); + } + let surface = doc.layers.pop().and_then(|l| match l.content { + LayerContent::Raster(s) => Some(s), + _ => None, + }); + let surface = surface.ok_or_else(|| other("the smart object's source could not be converted"))?; + Ok(if surface.format() == fmt { surface } else { surface.convert(fmt) }) +} + +/// An SVG source rendered at `scale` times its own size (cached per scale), so a vector smart +/// object stays sharp however it is placed. +pub fn svg_source_image(bytes: &[u8], fmt: PixelFormat, scale: f64) -> Result { + let mut h = blake3::Hasher::new(); + h.update(bytes); + h.update(&scale.to_bits().to_le_bytes()); + let key = (*h.finalize().as_bytes(), fmt); + if let Some(img) = cache_get(&key) { + return Ok(img); + } + let buf = photocraft_io::svg::rasterize(bytes, scale as f32).map_err(|e| other(format!("can't render the SVG smart object: {e}")))?; + let img = SourceImage { surface: Arc::new(buffer_to_surface(&buf, fmt)), bounds: buf.rect }; + cache_put(key, img.clone()); + Ok(img) +} + +/// The scale a vector source is rasterised at for its placement: the larger axis scale of the +/// transform in 1/16 steps (so nudges reuse the cache), between 1/16 and 64. +pub(super) fn vector_scale(sm: &SmartObject) -> f64 { + let [a, b, c, d, ..] = sm.transform.m; + let k = (a * a + b * b).sqrt().max((c * c + d * d).sqrt()); + if !k.is_finite() { + return 1.0; + } + ((k * 16.0).ceil() / 16.0).clamp(1.0 / 16.0, 64.0) +} + +/// The composited source image of `bytes` in pixel format `fmt` (decoded once, then cached). +pub fn source_image(file_name: &str, bytes: &[u8], fmt: PixelFormat) -> Result { + let key = cache_key(bytes, fmt); + if let Some(img) = cache_get(&key) { + return Ok(img); + } + let doc = decode_source(file_name, bytes)?; + let buf = photocraft_compose::flatten(&doc); + let img = SourceImage { surface: Arc::new(source_surface(&doc, &buf, fmt)?), bounds: doc.bounds() }; + cache_put(key, img.clone()); + Ok(img) +} diff --git a/crates/engine/src/smart_cmds/stack_cache.rs b/crates/engine/src/cmd/smart_cmds/stack_cache.rs similarity index 100% rename from crates/engine/src/smart_cmds/stack_cache.rs rename to crates/engine/src/cmd/smart_cmds/stack_cache.rs diff --git a/crates/engine/src/smart_cmds/tests.rs b/crates/engine/src/cmd/smart_cmds/tests.rs similarity index 100% rename from crates/engine/src/smart_cmds/tests.rs rename to crates/engine/src/cmd/smart_cmds/tests.rs diff --git a/crates/engine/src/smart_cmds/tests/filter_mask_paint.rs b/crates/engine/src/cmd/smart_cmds/tests/filter_mask_paint.rs similarity index 100% rename from crates/engine/src/smart_cmds/tests/filter_mask_paint.rs rename to crates/engine/src/cmd/smart_cmds/tests/filter_mask_paint.rs diff --git a/crates/engine/src/smart_cmds/tests/selection.rs b/crates/engine/src/cmd/smart_cmds/tests/selection.rs similarity index 100% rename from crates/engine/src/smart_cmds/tests/selection.rs rename to crates/engine/src/cmd/smart_cmds/tests/selection.rs diff --git a/crates/engine/src/smart_cmds/tests/stack_cache.rs b/crates/engine/src/cmd/smart_cmds/tests/stack_cache.rs similarity index 100% rename from crates/engine/src/smart_cmds/tests/stack_cache.rs rename to crates/engine/src/cmd/smart_cmds/tests/stack_cache.rs diff --git a/crates/engine/src/smart_cmds/unpack.rs b/crates/engine/src/cmd/smart_cmds/unpack.rs similarity index 100% rename from crates/engine/src/smart_cmds/unpack.rs rename to crates/engine/src/cmd/smart_cmds/unpack.rs diff --git a/crates/engine/src/cmd/smartselect_cmds.rs b/crates/engine/src/cmd/smartselect_cmds.rs new file mode 100644 index 0000000000..b8beea5a80 --- /dev/null +++ b/crates/engine/src/cmd/smartselect_cmds.rs @@ -0,0 +1,570 @@ +//! Smart selection commands: Quick Selection, Object Selection, Select Subject, Select and Mask +//! (Refine Edge) and Focus Area. The algorithms live in `photocraft_algo::segment` and +//! `photocraft_algo::matting`; these commands pick the pixels to analyse (active layer or +//! composite), run them, and store the result as the selection (or a mask / new layer). + +use photocraft_algo::matting::{self, RefineParams}; +use photocraft_algo::segment::{Sampler, SurfaceSampler, focus, grabcut, quick, subject}; +use photocraft_algo::selection::{Region, SelectionMode, combine_region}; +use photocraft_doc::{Document, Layer, LayerContent, LayerId, LayerMask}; +use photocraft_geom::Rect; +use serde_json::{Value, json}; + +use crate::commands::CommandSpec; +use crate::select_mask_edits; +use crate::{EngineError, Result, Session}; + +fn has_doc(s: &Session) -> std::result::Result<(), String> { + s.active().map(|_| ()).ok_or_else(|| "no document open".into()) +} +fn has_selection_or_mask(s: &Session) -> std::result::Result<(), String> { + let d = s.active().ok_or_else(|| "no document open".to_string())?; + if d.doc.selection.is_some() { + return Ok(()); + } + if let Some(l) = d.active_layer.and_then(|id| d.doc.layer(id)) + && l.mask.is_some() + { + return Ok(()); + } + Err("no selection or layer mask".into()) +} + +fn f(p: &Value, k: &str, d: f32) -> f32 { + p.get(k).and_then(Value::as_f64).map_or(d, |v| v as f32) +} +fn b(p: &Value, k: &str, d: bool) -> bool { + p.get(k).and_then(Value::as_bool).unwrap_or(d) +} +fn mode(p: &Value, default: &str) -> SelectionMode { + let m = p.get("mode").and_then(Value::as_str).unwrap_or(default); + SelectionMode::parse(if m == "new" { "replace" } else { m }) +} +fn bad(cmd: &str, msg: &str) -> EngineError { + EngineError::BadParams { cmd: cmd.into(), msg: msg.into() } +} + +/// Composite of all visible layers. +struct CompositeSampler<'a>(&'a Document); + +impl Sampler for CompositeSampler<'_> { + fn rgba(&self, r: Rect) -> Vec<[f32; 4]> { + photocraft_compose::render(self.0, r).px + } +} + +/// Runs `f` with a sampler over the active layer (or the composite with `all_layers`, or when the +/// active layer has no pixels). +fn with_sampler(s: &Session, all_layers: bool, f: impl FnOnce(&dyn Sampler, &Document) -> R) -> Result { + let d = s.active().ok_or(EngineError::NoDocument)?; + Ok(with_doc_sampler(&d.doc, d.active_layer, all_layers, f)) +} + +/// Runs `f` with a sampler over `layer`'s pixels in `doc` (or the composite with `all_layers`, or +/// when the layer has no pixels). +pub(crate) fn with_doc_sampler(doc: &Document, layer: Option, all_layers: bool, f: impl FnOnce(&dyn Sampler, &Document) -> R) -> R { + match (all_layers, layer.and_then(|id| doc.layer(id)).and_then(Layer::surface)) { + (false, Some(surf)) => f(&SurfaceSampler(surf), doc), + _ => f(&CompositeSampler(doc), doc), + } +} + +/// Stores `region` combined with the current selection by `m` as one history step. +/// Finding nothing never destroys work: the selection (and history) is left alone and the +/// caller gets `changed: false`, whatever the mode. (Select Subject and Object Selection run +/// heuristics that often find nothing on busy photos; clearing the selection then looks like +/// a dead button.) +fn apply(s: &mut Session, label: &str, region: Option<&Region>, m: SelectionMode) -> Result { + if region.is_none() { + // Nothing found: leave the selection (and history) alone. + let selected = s.active().ok_or(EngineError::NoDocument)?.doc.selection.is_some(); + return Ok(json!({ "selected": selected, "changed": false })); + } + let bbox = region.map(|r| r.bbox); + let selected = s.edit(label, |doc, _| { + doc.selection = combine_region(doc.selection.as_ref(), region, m); + Ok(doc.selection.is_some()) + })?; + Ok(json!({ "selected": selected, "changed": true, "bounds": bbox.map(|r| [r.x0, r.y0, r.width() as i32, r.height() as i32]) })) +} + +fn points(p: &Value) -> Vec<(f32, f32)> { + p.get("points") + .and_then(Value::as_array) + .map(|a| a.iter().filter_map(|q| Some((q.get(0)?.as_f64()? as f32, q.get(1)?.as_f64()? as f32))).collect()) + .unwrap_or_default() +} + +/// Auto-Enhance for Quick Selection: a light edge refinement that flows the edge towards image +/// edges and removes blockiness. +const ENHANCE: RefineParams = RefineParams { radius: 4.0, smart_radius: true, smooth: 15.0, feather: 0.0, contrast: 25.0, shift_edge: 0.0 }; + +fn quick_selection(s: &mut Session, p: &Value) -> Result { + let pts = points(p); + if pts.is_empty() { + return Err(bad("select.quick", "needs at least one point")); + } + let size = f(p, "size", 30.0).clamp(1.0, 5000.0); + let m = match p.get("mode").and_then(Value::as_str).unwrap_or("add") { + "subtract" => SelectionMode::Subtract, + "replace" | "new" => SelectionMode::Replace, + _ => SelectionMode::Add, + }; + let enhance = b(p, "enhanceEdge", false); + let region = with_sampler(s, b(p, "sampleAllLayers", false), |smp, doc| { + let canvas = doc.bounds(); + let r = quick::quick_select(smp, canvas, &pts, size)?; + if enhance { matting::refine_mask(smp, &matting::region_reader(&r), r.bbox, canvas, &ENHANCE) } else { Some(r) } + })?; + apply(s, "Quick Selection", region.as_ref(), m) +} + +fn rect_param(p: &Value) -> Option { + let a = p.get("rect")?.as_array()?; + let v: Vec = a.iter().filter_map(Value::as_f64).collect(); + if v.len() < 4 { + return None; + } + // Negative sizes (dragging up/left) are normalised. + let (x0, x1) = (v[0].min(v[0] + v[2]), v[0].max(v[0] + v[2])); + let (y0, y1) = (v[1].min(v[1] + v[3]), v[1].max(v[1] + v[3])); + Some(Rect::new(x0.floor() as i32, y0.floor() as i32, x1.ceil() as i32, y1.ceil() as i32)) +} + +fn point_param(p: &Value) -> Option<(f32, f32)> { + let a = p.get("point")?.as_array()?; + let (x, y) = (a.first()?.as_f64()? as f32, a.get(1)?.as_f64()? as f32); + (x.is_finite() && y.is_finite()).then_some((x, y)) +} + +/// The layer [`with_doc_sampler`] samples for `layer` / `all_layers`: `None` = the composite. +pub fn sampled_target(doc: &Document, layer: Option, all_layers: bool) -> Option { + layer.filter(|id| !all_layers && doc.layer(*id).and_then(Layer::surface).is_some()) +} + +/// Object Finder (#4087): the object Object Selection would select at document point `(x, y)`, +/// sampling `layer` (or the composite). Pure, so the UI can run it on a worker thread while the +/// pointer hovers; `select.object` with `"point"` commits the same result. +pub fn find_object(doc: &Document, layer: Option, all_layers: bool, x: f32, y: f32) -> Option { + with_doc_sampler(doc, layer, all_layers, |smp, doc| grabcut::object_at(smp, doc.bounds(), x, y, grabcut::OBJECT_AT_WORK_PX)) +} + +/// Most objects remembered by [`ObjectFinderCache`]. +pub const OBJECT_FINDER_ENTRIES: usize = 12; + +/// Object Finder results for one document's pixels (#4087): hovering over an object already +/// found, or clicking it, answers at once. Keyed like [`SubjectCache`] (valid while the pixels +/// are the same, the document held weakly) plus the sampled layer; a lookup hits any cached +/// object that covers the point, so one computation serves the whole object. +#[derive(Debug, Default)] +pub struct ObjectFinderCache { + doc: std::sync::Weak, + doc_id: Option, + target: Option, + regions: Vec>, +} + +impl ObjectFinderCache { + fn valid(&self, doc: &Document, target: Option) -> bool { + self.doc_id == Some(doc.id) && self.target == target && self.doc.upgrade().is_some_and(|old| crate::layer_multi_cmds::same_pixels(&old, doc)) + } + + /// A cached object of `doc` (sampling `target`) covering `(x, y)`. + pub fn lookup(&self, doc: &Document, target: Option, x: f32, y: f32) -> Option> { + if !x.is_finite() || !y.is_finite() || !self.valid(doc, target) { + return None; + } + let (px, py) = (x.floor() as i32, y.floor() as i32); + self.regions.iter().find(|r| r.at(px, py) >= 0.5).cloned() + } + + /// Remembers `region`, found in `doc` sampling `target`. A different document or pixels + /// start over; the oldest object is dropped beyond [`OBJECT_FINDER_ENTRIES`]. + pub fn insert(&mut self, doc: &std::sync::Arc, target: Option, region: std::sync::Arc) { + if !self.valid(doc, target) { + self.regions.clear(); + } + self.doc = std::sync::Arc::downgrade(doc); + self.doc_id = Some(doc.id); + self.target = target; + if self.regions.len() >= OBJECT_FINDER_ENTRIES { + self.regions.remove(0); + } + self.regions.push(region); + } + + /// Number of remembered objects. + pub fn len(&self) -> usize { + self.regions.len() + } + + /// Whether nothing is remembered. + pub fn is_empty(&self) -> bool { + self.regions.is_empty() + } + + /// Forget the results if they were computed from the document `id` (it is closing). + pub(crate) fn forget_doc(&mut self, id: photocraft_doc::DocId) { + if self.doc_id == Some(id) { + *self = Self::default(); + } + } + + /// Follows `doc` past a selection-only edit (same pixels), so the next lookup still hits. + fn follow(&mut self, doc: &std::sync::Arc) { + if self.doc_id == Some(doc.id) && self.doc.upgrade().is_some_and(|old| crate::layer_multi_cmds::same_pixels(&old, doc)) { + self.doc = std::sync::Arc::downgrade(doc); + } + } +} + +/// Object Selection samples only the active layer by default: when that layer has no pixels in +/// `area`, say so instead of quietly finding nothing (#5246; scripts often add an empty layer +/// above the photo first). +fn check_sampled_pixels(doc: &Document, layer: Option, all_layers: bool, area: Rect) -> Result<()> { + match empty_sampled_area(doc, layer, all_layers, area) { + Some(msg) => Err(bad("select.object", &format!("{msg}; set \"sampleAllLayers\": true or select a layer with pixels"))), + None => Ok(()), + } +} + +/// Why sampling `layer` (unless `all_layers`) can find nothing in `area`: the layer is empty, or has no pixels there. +/// `None` = there is something to sample. The click path reports it as an error, the Object Finder hover as a hint. +pub fn empty_sampled_area(doc: &Document, layer: Option, all_layers: bool, area: Rect) -> Option<&'static str> { + let surf = sampled_target(doc, layer, all_layers).and_then(|id| doc.layer(id)).and_then(Layer::surface)?; + if !surf.content_bounds().intersect(&area).is_empty() { + return None; + } + Some(if surf.content_bounds().is_empty() { "the active layer is empty" } else { "the active layer has no pixels in that area" }) +} + +/// `select.object` with `"point"`: the Object Finder's object under the point (cached). +fn object_at_point(s: &mut Session, p: &Value, (x, y): (f32, f32)) -> Result { + let all_layers = b(p, "sampleAllLayers", false); + let d = s.active().ok_or(EngineError::NoDocument)?; + check_sampled_pixels(&d.doc, d.active_layer, all_layers, Rect::from_xywh(x.floor() as i32, y.floor() as i32, 1, 1))?; + let target = sampled_target(&d.doc, d.active_layer, all_layers); + let region = match s.object_finder.lookup(&d.doc, target, x, y) { + Some(r) => Some(r), + None => { + let doc = std::sync::Arc::clone(&d.doc); + let found = find_object(&doc, d.active_layer, all_layers, x, y).map(std::sync::Arc::new); + if let Some(r) = &found { + s.object_finder.insert(&doc, target, std::sync::Arc::clone(r)); + } + found + } + }; + let out = apply(s, "Object Selection", region.as_deref(), mode(p, "replace"))?; + if let Some(d) = s.active() { + let doc = std::sync::Arc::clone(&d.doc); + s.object_finder.follow(&doc); + } + Ok(out) +} + +fn object_selection(s: &mut Session, p: &Value) -> Result { + if p.get("rect").is_none() + && let Some(pt) = point_param(p) + { + return object_at_point(s, p, pt); + } + let rect = rect_param(p).ok_or_else(|| bad("select.object", "needs \"rect\": [x, y, w, h] or \"point\": [x, y]"))?; + let all_layers = b(p, "sampleAllLayers", false); + let d = s.active().ok_or(EngineError::NoDocument)?; + check_sampled_pixels(&d.doc, d.active_layer, all_layers, rect)?; + let region = with_sampler(s, all_layers, |smp, doc| grabcut::object_select(smp, doc.bounds(), rect, 160_000))?; + apply(s, "Object Selection", region.as_ref(), mode(p, "replace")) +} + +/// Select Subject's last result (#2865), so running it again on unchanged pixels answers at +/// once instead of recomputing superpixels, saliency and GrabCut (P29). Keyed by the pixels it +/// was computed from: valid while [`same_pixels`](crate::layer_multi_cmds::same_pixels) (a +/// tile-pointer comparison) holds against that document, so selection-only edits such as +/// Deselect keep it. One entry per session; the document is held weakly, so the cache never +/// keeps a closed or edited document's tiles alive (the session also drops it on pixel edits +/// and when its document closes). Its memory is the mask: one byte per pixel of its bounds. +#[derive(Debug, Default)] +pub struct SubjectCache { + doc: std::sync::Weak, + doc_id: Option, + /// The sampled layer; `None` = the composite. + target: Option, + region: Option>, +} + +impl SubjectCache { + /// Forget the result if it was computed from the document `id` (it is closing). + pub(crate) fn forget_doc(&mut self, id: photocraft_doc::DocId) { + if self.doc_id == Some(id) { + *self = Self::default(); + } + } +} + +fn select_subject(s: &mut Session, p: &Value) -> Result { + let all_layers = b(p, "sampleAllLayers", true); + let d = s.active().ok_or(EngineError::NoDocument)?; + // What `with_doc_sampler` samples: the active layer's pixels, else the composite. + let target = d.active_layer.filter(|id| !all_layers && d.doc.layer(*id).and_then(Layer::surface).is_some()); + let c = &s.subject_cache; + let hit = c.target == target && c.doc.upgrade().is_some_and(|old| crate::layer_multi_cmds::same_pixels(&old, &d.doc)); + let region = if hit { + c.region.clone() + } else { + let doc = std::sync::Arc::clone(&d.doc); + let region = with_doc_sampler(&doc, d.active_layer, all_layers, |smp, doc| subject::select_subject(smp, doc.bounds())).map(std::sync::Arc::new); + s.subject_cache = SubjectCache { doc: std::sync::Arc::downgrade(&doc), doc_id: Some(doc.id), target, region: region.clone() }; + region + }; + let out = apply(s, "Select Subject", region.as_deref(), mode(p, "replace"))?; + // Follow the document past the selection edit just made (same pixels), so a short history + // dropping the older state doesn't turn the next repeat into a miss. + if let Some(d) = s.active() + && s.subject_cache.doc_id == Some(d.doc.id) + && s.subject_cache.doc.upgrade().is_some_and(|old| crate::layer_multi_cmds::same_pixels(&old, &d.doc)) + { + s.subject_cache.doc = std::sync::Arc::downgrade(&d.doc); + } + Ok(out) +} + +fn focus_area(s: &mut Session, p: &Value) -> Result { + let (range, noise) = (f(p, "range", 0.5).clamp(0.0, 1.0), f(p, "noise", 0.0).clamp(0.0, 1.0)); + let region = with_sampler(s, b(p, "sampleAllLayers", true), |smp, doc| focus::focus_area(smp, doc.bounds(), range, noise))?; + apply(s, "Focus Area", region.as_ref(), mode(p, "replace")) +} + +fn refine_params(p: &Value) -> RefineParams { + RefineParams { + radius: f(p, "radius", 0.0).clamp(0.0, 250.0), + smart_radius: b(p, "smartRadius", false), + smooth: f(p, "smooth", 0.0).clamp(0.0, 100.0), + feather: f(p, "feather", 0.0).clamp(0.0, 1000.0), + contrast: f(p, "contrast", 0.0).clamp(0.0, 100.0), + shift_edge: f(p, "shiftEdge", 0.0).clamp(-100.0, 100.0), + } +} + +/// Most Refine Edge Brush strokes, and points across them, one Select and Mask takes. +pub const MAX_STROKES: usize = 4096; +pub const MAX_STROKE_POINTS: usize = 100_000; + +/// The Refine Edge Brush strokes of `refineStrokes`: +/// `[{"points":[[x,y],…],"size":px,"mode":"add|subtract"}]`, in painting order. +fn refine_strokes(p: &Value) -> Result> { + const CMD: &str = "select.refineEdge"; + let Some(v) = p.get("refineStrokes").filter(|v| !v.is_null()) else { return Ok(Vec::new()) }; + let list = v.as_array().ok_or_else(|| bad(CMD, "refineStrokes must be an array of strokes"))?; + if list.len() > MAX_STROKES { + return Err(bad(CMD, &format!("refineStrokes holds more than {MAX_STROKES} strokes"))); + } + let mut total = 0usize; + let mut strokes = Vec::with_capacity(list.len()); + for stroke in list { + let o = stroke.as_object().ok_or_else(|| bad(CMD, "each refineStrokes entry must be {\"points\":[[x,y],…],\"size\":px,\"mode\":\"add|subtract\"}"))?; + let pts = o.get("points").and_then(Value::as_array).filter(|a| !a.is_empty()).ok_or_else(|| bad(CMD, "each stroke needs a non-empty points array"))?; + total = total.saturating_add(pts.len()); + if total > MAX_STROKE_POINTS { + return Err(bad(CMD, &format!("refineStrokes holds more than {MAX_STROKE_POINTS} points"))); + } + let points = pts + .iter() + .map(|pt| { + let xy = pt.as_array().filter(|a| a.len() == 2)?; + let (x, y) = (xy.first()?.as_f64()?, xy.get(1)?.as_f64()?); + let ok = |v: f64| v.is_finite() && v.abs() <= 1e7; + (ok(x) && ok(y)).then_some((x as f32, y as f32)) + }) + .collect::>>() + .ok_or_else(|| bad(CMD, "stroke points must be [x,y] pairs of finite numbers"))?; + let range = matting::BRUSH_SIZE_RANGE; + let size = match o.get("size") { + None => 30.0, + Some(v) => v + .as_f64() + .filter(|s| s.is_finite() && (f64::from(*range.start())..=f64::from(*range.end())).contains(s)) + .ok_or_else(|| bad(CMD, &format!("stroke size must be {}..{} px", range.start(), range.end())))? as f32, + }; + let add = match o.get("mode").map(|m| m.as_str()) { + None | Some(Some("add")) => true, + Some(Some("subtract")) => false, + Some(_) => return Err(bad(CMD, "stroke mode must be add|subtract")), + }; + strokes.push(matting::EdgeStroke { points, size, add }); + } + if matting::swept_area(&strokes) > matting::MAX_SWEPT_AREA { + return Err(bad(CMD, "refineStrokes paint too large an area")); + } + Ok(strokes) +} + +/// Select and Mask: applies the workspace's tool `edits` to the selection (or layer mask), refines +/// its edge, then outputs to the selection, a layer mask on the active layer, a new layer or a new +/// document (each with or without a mask). +/// Decontaminating colours needs new pixels, so it upgrades `selection` / `layerMask` output to +/// `newLayerWithMask` (as Photoshop does). New-layer outputs hide the source layer; new-document +/// outputs leave the source document untouched. +fn refine_edge(s: &mut Session, p: &Value) -> Result { + let params = refine_params(p); + let strokes = refine_strokes(p)?; + let decontaminate = b(p, "decontaminate", false); + let amount = f(p, "amount", 100.0).clamp(0.0, 100.0); + let d = s.active().ok_or(EngineError::NoDocument)?; + let active = d.active_layer.filter(|id| d.doc.layer(*id).is_some()); + let default_output = + if d.doc.selection.is_none() && active.and_then(|id| d.doc.layer(id)).and_then(|l| l.mask.as_ref()).is_some() { "layerMask" } else { "selection" }; + let mut output = p.get("output").and_then(Value::as_str).unwrap_or(default_output).to_string(); + if !matches!(output.as_str(), "selection" | "layerMask" | "newLayer" | "newLayerWithMask" | "newDocument" | "newDocumentWithMask") { + return Err(bad("select.refineEdge", "output must be selection|layerMask|newLayer|newLayerWithMask|newDocument|newDocumentWithMask")); + } + if decontaminate && matches!(output.as_str(), "selection" | "layerMask") { + output = "newLayerWithMask".into(); + } + let edits = select_mask_edits::parse(p)?; + // Before anything is painted: a thin stroke across a huge canvas paints few pixels but many tiles. + select_mask_edits::check_size(&edits, d.doc.bounds())?; + select_mask_edits::check_strokes(&strokes, d.doc.bounds())?; + let region = with_sampler(s, b(p, "sampleAllLayers", false), |smp, doc| { + let mask_surf = active.and_then(|id| doc.layer(id)).and_then(|l| l.mask.as_ref()).map(|m| &m.surface); + let target_mask = p.get("target").and_then(Value::as_str) == Some("mask"); + let start = if target_mask { mask_surf.or(doc.selection.as_ref()) } else { doc.selection.as_ref().or(mask_surf) }; + // The workspace's tool edits change the selection before its edge is refined. + let edited = if edits.is_empty() { None } else { select_mask_edits::apply(doc, active, start.cloned(), &edits) }; + let Some(sel) = (if edits.is_empty() { start } else { edited.as_ref() }) else { return Ok(None) }; + let brush = matting::EdgeBrush::new(&strokes, doc.bounds()); + // The refined result is dense over the selection's bounds: refuse what would not fit + // rather than allocate it (a thin edit across a huge canvas; the #8783 review). + let content = sel.content_bounds(); + let area = matting::refine_area(content, doc.bounds(), ¶ms, brush.as_ref()); + if u64::from(area.width()) * u64::from(area.height()) > matting::MAX_REFINE_AREA { + return Err(bad( + "select.refineEdge", + &format!("the selection is too large to refine ({} × {} px; at most {} px in all)", area.width(), area.height(), matting::MAX_REFINE_AREA), + )); + } + Ok(matting::refine_mask_brushed(smp, &matting::surface_reader(sel), content, doc.bounds(), ¶ms, brush.as_ref())) + })??; + let d = s.active().ok_or(EngineError::NoDocument)?; + let active = d.active_layer.filter(|id| d.doc.layer(*id).is_some()); + match output.as_str() { + "selection" => { + let selected = s.edit("Select and Mask", |doc, _| { + doc.selection = region.as_ref().map(matting::region_surface); + Ok(doc.selection.is_some()) + })?; + Ok(json!({ "output": output, "selected": selected })) + } + "layerMask" => { + let id = active.ok_or_else(|| EngineError::Other("no active layer".into()))?; + s.edit("Select and Mask", |doc, _| { + let surface = + region.as_ref().map(matting::region_surface).unwrap_or_else(|| photocraft_raster::Surface::new(photocraft_color::PixelFormat::GRAY8)); + crate::extra_cmds::background_to_layer_for_mask(doc, id); + let existing = doc.layer(id).and_then(|l| l.mask.as_ref()).cloned().unwrap_or_else(LayerMask::reveal_all); + doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?.mask = Some(LayerMask { surface, ..existing }); + doc.selection = None; + Ok(()) + })?; + Ok(json!({ "output": output, "layer": id.0, "selected": false })) + } + _ => { + let id = active.ok_or_else(|| EngineError::Other("no active layer".into()))?; + let src_layer = d.doc.layer(id).ok_or(EngineError::NoLayer(id))?; + let src = src_layer.surface().ok_or_else(|| { + EngineError::Other(format!("the active layer is {} {} layer without pixels", src_layer.content.article(), src_layer.content.kind_name())) + })?; + let name = d.doc.copy_name(&src_layer.name); + let empty = Region { bbox: Rect::EMPTY, mask: Vec::new() }; + let reg = region.as_ref().unwrap_or(&empty); + let pixels = if decontaminate { matting::decontaminate(src, reg, params.radius, amount) } else { src.clone() }; + let with_mask = matches!(output.as_str(), "newLayerWithMask" | "newDocumentWithMask"); + let (content, mask) = if with_mask { + (pixels, Some(LayerMask { surface: matting::region_surface(reg), ..LayerMask::reveal_all() })) + } else { + (matting::masked_copy(&pixels, reg), None) + }; + if output.starts_with("newDocument") { + // Same canvas, colour mode, depth and profile, so the pixels need no conversion. + let mut doc = Document::new("Untitled", d.doc.size, d.doc.mode, d.doc.depth); + doc.resolution_dpi = d.doc.resolution_dpi; + doc.icc_profile = d.doc.icc_profile.clone(); + doc.color_table = d.doc.color_table.clone(); + doc.duotone = d.doc.duotone.clone(); + let mut layer = Layer::new(src_layer.name.clone(), LayerContent::Raster(content)); + layer.mask = mask; + let layer_id = layer.id; + doc.layers.push(layer); + let i = s.add_document(doc, None); + return Ok(json!({ "output": output, "document": i, "layer": layer_id.0, "selected": false })); + } + let new_id = s.edit("Select and Mask", |doc, act| { + let mut layer = Layer::new(name, LayerContent::Raster(content)); + layer.mask = mask; + let nid = doc.insert_above(Some(id), layer); + if let Some(l) = doc.layer_mut(id) { + l.visible = false; + } + doc.selection = None; + *act = Some(nid); + Ok(nid) + })?; + Ok(json!({ "output": output, "layer": new_id.0, "selected": false })) + } + } +} + +macro_rules! spec { + ($id:literal, $label:literal, [$($m:literal),*], $params:literal, $en:expr, $run:expr) => { + CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: None, params: $params, enabled: $en, run: $run, journal: true } + }; +} + +/// Smart selection command specs. +pub fn specs() -> Vec { + vec![ + spec!( + "select.quick", + "Quick Selection", + [], + r##"{"points":[[x,y],…],"size":px=30,"mode":"add|subtract|replace"="add","sampleAllLayers":bool=false,"enhanceEdge":bool=false}"##, + has_doc, + quick_selection + ), + spec!( + "select.object", + "Object Selection", + [], + r##"{"rect":[x,y,w,h] | "point":[x,y],"mode":"replace|add|subtract|intersect"="replace","sampleAllLayers":bool=false} (point: the Object Finder's object under the point, as hovering previews it)"##, + has_doc, + object_selection + ), + spec!( + "select.subject", + "Subject", + ["Select"], + r##"{"sampleAllLayers":bool=true,"mode":"replace|add|subtract|intersect"="replace"}"##, + has_doc, + select_subject + ), + spec!( + "select.refineEdge", + "Refine Edge", + [], + r##"{"radius":px=0,"smartRadius":bool=false,"smooth":0..100=0,"feather":px=0,"contrast":0..100=0,"shiftEdge":-100..100=0,"decontaminate":bool=false,"amount":0..100=100,"output":"selection|layerMask|newLayer|newLayerWithMask|newDocument|newDocumentWithMask"="selection","sampleAllLayers":bool=false,"refineStrokes":[{"points":[[x,y],…],"size":px=30,"mode":"add|subtract"="add"},…]=[],"edits":[{"tool":"quick","points":[[x,y],…],"size":px=30,"mode":"add|subtract"="add","sampleAllLayers":bool=false} | {"tool":"brush","points":[[x,y],…],"size":px=30,"hardness":0..100=100,"mode":"add|subtract"="add"} | {"tool":"lasso","points":[[x,y],…≥3],"mode":"add|subtract"="add"} | {"tool":"object","rect":[x,y,w,h] | "point":[x,y],"mode":"add|subtract"="add","sampleAllLayers":bool=false} | {"tool":"subject","mode":"replace|add|subtract"="replace","sampleAllLayers":bool=true} | {"tool":"clear"} | {"tool":"invert"},…]=[]} (refineStrokes: the Refine Edge Brush, in painting order: add refines the painted area from the image, subtract keeps the original edge there; edits: the workspace's Quick Selection, Brush, Lasso, Object Selection, Select Subject, Clear Selection and Invert, applied in order to the selection before its edge is refined)"##, + has_selection_or_mask, + refine_edge + ), + spec!( + "select.focusArea", + "Focus Area…", + ["Select"], + r##"{"range":0..1=0.5,"noise":0..1=0,"sampleAllLayers":bool=true,"mode":"replace|add|subtract|intersect"="replace"}"##, + has_doc, + focus_area + ), + ] +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/smartselect_cmds/tests.rs b/crates/engine/src/cmd/smartselect_cmds/tests.rs new file mode 100644 index 0000000000..8cb19565b5 --- /dev/null +++ b/crates/engine/src/cmd/smartselect_cmds/tests.rs @@ -0,0 +1,677 @@ +use super::*; +use photocraft_algo::segment::Rng; + +/// A document whose background shows `px(x, y)` (RGB, 0–1), at the given depth. +fn session_with(w: u32, h: u32, depth: u32, px: impl Fn(u32, u32) -> [f32; 3]) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": w, "height": h, "depth": depth})).unwrap(); + s.edit("paint", |doc, _| { + let bg = doc.layers[0].surface_mut().unwrap(); + let n = bg.channels(); + let mut data = Vec::with_capacity((w * h) as usize * n); + for y in 0..h { + for x in 0..w { + let c = px(x, y); + data.extend_from_slice(&c[..n.min(3)]); + if n == 4 { + data.push(1.0); + } + } + } + bg.write_region(Rect::new(0, 0, w as i32, h as i32), &data); + Ok(()) + }) + .unwrap(); + s +} + +fn noise_field(w: u32, h: u32, seed: u64) -> Vec { + let mut rng = Rng::new(seed); + (0..w * h).map(|_| rng.normal()).collect() +} + +/// Warm textured left part (x < 60), cool right part. +fn two_regions(depth: u32) -> Session { + let nz = noise_field(140, 100, 1); + session_with(140, 100, depth, move |x, y| { + let n = 0.04 * nz[(y * 140 + x) as usize]; + if x < 60 { [0.8 + n, 0.5 + n, 0.3] } else { [0.2, 0.35 + n, 0.6 + n] }.map(|v| v.clamp(0.0, 1.0)) + }) +} + +/// Textured disc (centre (100, 80), radius 45) on a noisy background. +fn disc(depth: u32) -> (Session, impl Fn(i32, i32) -> bool) { + let nz = noise_field(200, 160, 2); + let inside = |x: i32, y: i32| { + let (dx, dy) = (x as f32 + 0.5 - 100.0, y as f32 + 0.5 - 80.0); + dx * dx + dy * dy <= 45.0 * 45.0 + }; + let s = session_with(200, 160, depth, move |x, y| { + let n = 0.05 * nz[(y * 200 + x) as usize]; + if inside(x as i32, y as i32) { + let t = ((x + y) as f32 * 0.35).sin() * 0.5 + 0.5; + [0.85 + 0.05 * t + n, 0.2 + 0.3 * t + n, 0.15 + n] + } else { + [0.25 + n, 0.45 + n, 0.7 + n] + } + .map(|v| v.clamp(0.0, 1.0)) + }); + (s, inside) +} + +fn cov(s: &Session, x: i32, y: i32) -> f32 { + s.active().unwrap().doc.selection.as_ref().map_or(0.0, |m| m.sample_channel(x, y, 0)) +} + +fn sel_iou(s: &Session, w: i32, h: i32, truth: impl Fn(i32, i32) -> bool) -> f32 { + let (mut i, mut u) = (0, 0); + for y in 0..h { + for x in 0..w { + let (a, b) = (cov(s, x, y) >= 0.5, truth(x, y)); + i += (a && b) as i32; + u += (a || b) as i32; + } + } + i as f32 / u.max(1) as f32 +} + +#[test] +fn quick_selection_add_subtract_undo() { + for depth in [8, 16] { + let mut s = two_regions(depth); + let r = s.execute("select.quick", json!({"points": [[20, 50], [35, 50]], "size": 8})).unwrap(); + assert_eq!(r["selected"], true); + for y in (0..100).step_by(7) { + for x in (0..140).step_by(3) { + let c = cov(&s, x, y); + if x < 57 { + assert!(c >= 0.5, "depth {depth}: ({x},{y}) not selected"); + } else if x > 62 { + assert!(c < 0.5, "depth {depth}: leaked to ({x},{y})"); + } + } + } + // A second stroke on the right adds it. + s.execute("select.quick", json!({"points": [[100, 50]], "size": 8})).unwrap(); + assert!(cov(&s, 130, 90) >= 0.5 && cov(&s, 10, 10) >= 0.5); + // Subtract the left region again. + s.execute("select.quick", json!({"points": [[20, 50]], "size": 8, "mode": "subtract"})).unwrap(); + assert!(cov(&s, 10, 10) < 0.5 && cov(&s, 130, 90) >= 0.5); + s.execute("edit.undo", json!({})).unwrap(); + assert!(cov(&s, 10, 10) >= 0.5); + assert!(s.execute("select.quick", json!({"points": []})).is_err()); + } +} + +#[test] +fn quick_selection_subtract_from_select_all_and_enhance() { + let mut s = two_regions(8); + s.execute("select.all", json!({})).unwrap(); + s.execute("select.quick", json!({"points": [[100, 30], [110, 70]], "size": 10, "mode": "subtract"})).unwrap(); + assert!(cov(&s, 10, 50) >= 0.99); + assert!(cov(&s, 120, 20) < 0.01 && cov(&s, 70, 90) < 0.01); + s.execute("select.deselect", json!({})).unwrap(); + s.execute("select.quick", json!({"points": [[20, 50]], "size": 8, "enhanceEdge": true})).unwrap(); + assert!(cov(&s, 10, 10) >= 0.5 && cov(&s, 100, 50) < 0.5); +} + +#[test] +fn empty_result_keeps_the_selection_in_every_mode() { + // Finding nothing must never wipe the selection, whatever the mode: Select Subject + // and Object Selection run heuristics that often miss on busy photos, and a missed + // Quick Selection dab must not destroy the work either. + for m in ["add", "subtract", "replace"] { + let mut s = two_regions(8); + s.execute("select.all", json!({})).unwrap(); + let r = s.execute("select.quick", json!({"points": [[-5000, -5000]], "size": 8, "mode": m})).unwrap(); + assert_eq!(r["changed"], false, "mode {m}"); + assert_eq!(r["selected"], true, "mode {m}"); + assert!(cov(&s, 10, 50) >= 0.99, "mode {m}: Select All survived an empty result"); + } + // Select Subject on a flat field finds nothing and keeps the selection too. + let mut s = session_with(140, 100, 8, |_, _| [0.5, 0.5, 0.5]); + s.execute("select.all", json!({})).unwrap(); + let r = s.execute("select.subject", json!({})).unwrap(); + assert_eq!(r["changed"], false); + assert!(cov(&s, 10, 10) >= 0.99); +} + +#[test] +fn object_selection_point_selects_the_object_under_it() { + for depth in [8, 16, 32] { + let (mut s, inside) = disc(depth); + let r = s.execute("select.object", json!({"point": [100, 80]})).unwrap(); + assert_eq!(r["changed"], true, "depth {depth}"); + let v = sel_iou(&s, 200, 160, &inside); + assert!(v > 0.9, "depth {depth}: IoU {v}"); + } + // The background is no object: nothing changes. + let (mut s, _) = disc(8); + let r = s.execute("select.object", json!({"point": [3, 3]})).unwrap(); + assert_eq!(r["changed"], false); + assert!(s.active().unwrap().doc.selection.is_none()); + assert!(s.execute("select.object", json!({"point": ["a", 1]})).is_err()); +} + +#[test] +fn object_selection_finds_a_large_foreground_at_each_depth_and_undoes() { + for depth in [8, 16, 32] { + let inside = |x: i32, y: i32| (10..190).contains(&x) && (8..152).contains(&y); + let mut s = session_with(200, 160, depth, |x, y| if inside(x as i32, y as i32) { [0.8, 0.2, 0.1] } else { [0.1, 0.2, 0.8] }); + let r = s.execute("select.object", json!({"point": [100, 80]})).unwrap(); + assert_eq!(r["changed"], true, "depth {depth}"); + assert!(sel_iou(&s, 200, 160, inside) > 0.95, "depth {depth}"); + s.execute("edit.undo", json!({})).unwrap(); + assert!(s.active().unwrap().doc.selection.is_none()); + let r = s.execute("select.object", json!({"point": [1, 1]})).unwrap(); + assert_eq!(r["changed"], false, "background at depth {depth}"); + assert!(s.active().unwrap().doc.selection.is_none()); + } +} + +#[test] +fn object_selection_point_honours_the_modes() { + let (mut s, _) = disc(8); + s.execute("select.all", json!({})).unwrap(); + s.execute("select.object", json!({"point": [100, 80], "mode": "subtract"})).unwrap(); + assert!(cov(&s, 100, 80) < 0.5 && cov(&s, 3, 3) >= 0.5); + s.execute("select.object", json!({"point": [100, 80], "mode": "add"})).unwrap(); + assert!(cov(&s, 100, 80) >= 0.5 && cov(&s, 3, 3) >= 0.5); + s.execute("select.object", json!({"point": [100, 80], "mode": "intersect"})).unwrap(); + assert!(cov(&s, 100, 80) >= 0.5 && cov(&s, 3, 3) < 0.5); +} + +#[test] +fn object_finder_cache_serves_the_whole_object_until_pixels_change() { + let (mut s, _) = disc(8); + let d = s.active().unwrap(); + let doc = std::sync::Arc::clone(&d.doc); + let target = sampled_target(&doc, d.active_layer, false); + assert!(s.object_finder.lookup(&doc, target, 100.0, 80.0).is_none()); + let r = std::sync::Arc::new(find_object(&doc, d.active_layer, false, 100.0, 80.0).unwrap()); + s.object_finder.insert(&doc, target, std::sync::Arc::clone(&r)); + // Any point on the object hits; the background and another target miss. + assert!(std::sync::Arc::ptr_eq(&s.object_finder.lookup(&doc, target, 120.0, 90.0).unwrap(), &r)); + assert!(s.object_finder.lookup(&doc, target, 3.0, 3.0).is_none()); + assert!(s.object_finder.lookup(&doc, Some(LayerId(u64::MAX)), 100.0, 80.0).is_none()); + // The click reuses it, and a selection-only edit keeps it. + s.execute("select.object", json!({"point": [110, 70]})).unwrap(); + assert_eq!(s.object_finder.len(), 1); + s.execute("select.deselect", json!({})).unwrap(); + let d = s.active().unwrap(); + assert!(s.object_finder.lookup(&std::sync::Arc::clone(&d.doc), target, 100.0, 80.0).is_some()); + // A pixel edit drops it. + s.execute("paint.pencil", json!({"points": [[5, 5], [30, 5]], "size": 4, "color": "#000000"})).unwrap(); + assert!(s.object_finder.is_empty()); +} + +#[test] +fn object_selection_disc() { + for depth in [8, 16, 32] { + let (mut s, inside) = disc(depth); + s.execute("select.object", json!({"rect": [40, 20, 120, 120]})).unwrap(); + let v = sel_iou(&s, 200, 160, &inside); + assert!(v > 0.95, "depth {depth}: IoU {v}"); + } + let (mut s, _) = disc(8); + assert!(s.execute("select.object", json!({"rect": [1, 2]})).is_err()); + // Negative width/height (drag up-left) work too. + s.execute("select.object", json!({"rect": [160, 140, -120, -120]})).unwrap(); + assert!(cov(&s, 100, 80) >= 0.5); +} + +#[test] +fn object_selection_on_an_empty_active_layer_says_so() { + // #5246: an empty layer above the photo used to find nothing without a word. + let (mut s, inside) = disc(8); + s.execute("layer.new.layer", json!({})).unwrap(); + for p in [json!({"rect": [40, 20, 120, 120]}), json!({"point": [100, 80]})] { + let e = s.execute("select.object", p.clone()).unwrap_err().to_string(); + assert!(e.contains("active layer is empty") && e.contains("sampleAllLayers"), "{p}: {e}"); + assert!(s.active().unwrap().doc.selection.is_none()); + } + // Sampling all layers finds the disc below. + s.execute("select.object", json!({"rect": [40, 20, 120, 120], "sampleAllLayers": true})).unwrap(); + assert!(sel_iou(&s, 200, 160, &inside) > 0.95); + // A layer with pixels elsewhere: the rectangle holds none of them. + s.execute("select.deselect", json!({})).unwrap(); + s.execute("paint.pencil", json!({"points": [[5, 5], [10, 5]], "size": 2, "color": "#000000"})).unwrap(); + let e = s.execute("select.object", json!({"rect": [60, 60, 100, 80]})).unwrap_err().to_string(); + assert!(e.contains("no pixels in that area"), "{e}"); +} + +#[test] +fn select_subject_centred_object() { + let (mut s, inside) = disc(8); + assert!(s.is_enabled("select.subject")); + s.execute("select.subject", json!({})).unwrap(); + let v = sel_iou(&s, 200, 160, inside); + assert!(v > 0.9, "IoU {v}"); + s.execute("edit.undo", json!({})).unwrap(); + assert!(s.active().unwrap().doc.selection.is_none()); +} + +/// #2865: a repeat on unchanged pixels reuses the last mask (an identical selection, even +/// after Deselect); sampling something else or a pixel edit computes it again. +#[test] +fn select_subject_repeat_reuses_the_mask_until_pixels_change() { + let (mut s, _) = disc(8); + let sel = |s: &Session| { + let mut v = Vec::new(); + s.active().unwrap().doc.selection.as_ref().unwrap().read_region_into(Rect::new(0, 0, 200, 160), &mut v); + v + }; + let cached = |s: &Session| s.subject_cache.region.clone().unwrap(); + s.execute("select.subject", json!({})).unwrap(); + let (first, mask) = (sel(&s), cached(&s)); + s.execute("select.deselect", json!({})).unwrap(); + s.execute("select.subject", json!({})).unwrap(); + assert!(std::sync::Arc::ptr_eq(&mask, &cached(&s)), "the repeat recomputed the mask"); + assert_eq!(sel(&s), first); + // Another sampled target (the layer rather than the composite) is a miss. + s.execute("select.subject", json!({"sampleAllLayers": false})).unwrap(); + assert!(!std::sync::Arc::ptr_eq(&mask, &cached(&s))); + // A pixel edit drops the entry; the next run recomputes it. + s.edit("paint", |doc, _| { + let bg = doc.layers[0].surface_mut().unwrap(); + let n = bg.channels(); + bg.write_region(Rect::new(0, 0, 1, 1), &vec![1.0; n]); + Ok(()) + }) + .unwrap(); + assert!(s.subject_cache.region.is_none()); + s.execute("select.subject", json!({})).unwrap(); + assert_eq!(sel(&s), first); +} + +/// A vertical Gaussian-blurred edge at x = 40 (warm left, cool right) with the left half selected. +fn blurred_edge_selected() -> Session { + blurred_edge_selected_at(8) +} + +fn blurred_edge_selected_at(depth: u32) -> Session { + let mut s = session_with(80, 40, depth, |x, _| { + let t = 1.0 / (1.0 + ((x as f32 + 0.5 - 40.0) / 1.8).exp()); + [0.9 * t + 0.1 * (1.0 - t), 0.8 * t + 0.2 * (1.0 - t), 0.2 * t + 0.6 * (1.0 - t)] + }); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 40, "height": 40})).unwrap(); + s +} + +fn soft_count(s: &photocraft_raster::Surface, y: i32) -> usize { + (0..80) + .filter(|x| { + let v = s.sample_channel(*x, y, 0); + v > 0.05 && v < 0.95 + }) + .count() +} + +#[test] +fn refine_edge_outputs_and_undo() { + // Selection output: the hard edge becomes a soft matte following the blur. + let mut s = blurred_edge_selected(); + assert!(s.is_enabled("select.refineEdge")); + s.execute("select.refineEdge", json!({"radius": 8})).unwrap(); + let sel = s.active().unwrap().doc.selection.clone().unwrap(); + assert!(soft_count(&sel, 20) >= 4, "selection edge not soft"); + assert!(sel.sample_channel(5, 20, 0) > 0.99 && sel.sample_channel(75, 20, 0) < 0.01); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(soft_count(s.active().unwrap().doc.selection.as_ref().unwrap(), 20), 0); + + // Layer mask output. + let layers_before = s.active().unwrap().doc.layer_count(); + let r = s.execute("select.refineEdge", json!({"radius": 8, "output": "layerMask"})).unwrap(); + let d = s.active().unwrap(); + let l = d.doc.layer(photocraft_doc::LayerId(r["layer"].as_u64().unwrap())).unwrap(); + let m = l.mask.as_ref().unwrap(); + assert!(soft_count(&m.surface, 20) >= 4); + assert!(m.value(5, 20) > 0.99 && m.value(75, 20) < 0.01); + assert!(d.doc.selection.is_none()); + assert_eq!(d.doc.layer_count(), layers_before); + s.execute("edit.undo", json!({})).unwrap(); + assert!(s.active().unwrap().doc.layers[0].mask.is_none()); + assert!(s.active().unwrap().doc.selection.is_some()); + + // Existing mask settings (density, feather, linked) are preserved + s.edit("set mask", |doc, _| { + doc.layers[0].mask = Some(photocraft_doc::LayerMask { + surface: photocraft_raster::Surface::new(photocraft_color::PixelFormat::GRAY8), + density: 0.75, + feather: 3.5, + linked: false, + enabled: true, + }); + Ok(()) + }) + .unwrap(); + let r = s.execute("select.refineEdge", json!({"radius": 8, "output": "layerMask"})).unwrap(); + let l = s.active().unwrap().doc.layer(photocraft_doc::LayerId(r["layer"].as_u64().unwrap())).unwrap(); + let m = l.mask.as_ref().unwrap(); + assert_eq!(m.density, 0.75); + assert_eq!(m.feather, 3.5); + assert!(!m.linked); + s.execute("edit.undo", json!({})).unwrap(); + s.edit("clear mask", |doc, _| { + doc.layers[0].mask = None; + Ok(()) + }) + .unwrap(); + + // New layer: pixels with the refined alpha; the source is hidden. + let r = s.execute("select.refineEdge", json!({"radius": 8, "feather": 1, "output": "newLayer"})).unwrap(); + let d = s.active().unwrap(); + let nid = photocraft_doc::LayerId(r["layer"].as_u64().unwrap()); + assert_eq!(d.active_layer, Some(nid)); + assert_eq!(d.doc.layer_count(), layers_before + 1); + let nl = d.doc.layer(nid).unwrap(); + let surf = nl.surface().unwrap(); + assert!(surf.format().alpha); + let a = |x: i32| surf.pixel(x, 20)[3]; + assert!(a(5) > 0.99 && a(75) == 0.0 && a(40) > 0.05 && a(40) < 0.95); + assert!(!d.doc.layers[0].visible); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc.layer_count(), layers_before); + assert!(s.active().unwrap().doc.layers[0].visible); + + // New layer with mask + decontamination (selection output upgrades to it). + let r = s.execute("select.refineEdge", json!({"radius": 8, "decontaminate": true, "amount": 100})).unwrap(); + assert_eq!(r["output"], "newLayerWithMask"); + let d = s.active().unwrap(); + let nl = d.doc.layer(photocraft_doc::LayerId(r["layer"].as_u64().unwrap())).unwrap(); + assert!(nl.mask.is_some()); + let px = nl.surface().unwrap().pixel(41, 20); + let orig = d.doc.layers[0].surface().unwrap().pixel(41, 20); + // The fringe colour moved towards the warm foreground (more red, less blue). + assert!(px[0] > orig[0] + 0.05 && px[2] < orig[2] - 0.05, "{px:?} vs {orig:?}"); + s.execute("edit.undo", json!({})).unwrap(); + assert!(s.execute("select.refineEdge", json!({"output": "bogus"})).is_err()); + s.execute("select.deselect", json!({})).unwrap(); + assert!(!s.is_enabled("select.refineEdge")); +} + +/// Output To New Document (with or without a layer mask) opens a document like the source, +/// at every depth, and leaves the source document as it was. +#[test] +fn refine_edge_outputs_to_a_new_document() { + for depth in [8, 16, 32] { + let mut s = blurred_edge_selected_at(depth); + s.edit("profile", |doc, _| { + doc.resolution_dpi = 300.0; + Ok(()) + }) + .unwrap(); + let before = s.active().unwrap().doc.clone(); + let r = s.execute("select.refineEdge", json!({"radius": 8, "output": "newDocument"})).unwrap(); + assert_eq!((r["output"].as_str(), r["document"].as_u64()), (Some("newDocument"), Some(1)), "depth {depth}"); + assert_eq!(s.active_index(), Some(1)); + let nd = &s.active().unwrap().doc; + assert_eq!((nd.size, nd.mode, nd.depth, nd.resolution_dpi), (before.size, before.mode, before.depth, 300.0)); + assert_eq!(nd.layers.len(), 1); + assert!(nd.selection.is_none() && nd.layers[0].mask.is_none()); + let surf = nd.layers[0].surface().unwrap(); + let a = |x: i32| surf.pixel(x, 20)[3]; + assert!(a(5) > 0.99 && a(75) == 0.0 && a(40) > 0.05 && a(40) < 0.95, "depth {depth}: {} {} {}", a(5), a(40), a(75)); + // The source is untouched: same layers, still visible, selection kept, no history step. + let src = &s.documents()[0]; + assert_eq!(src.doc.layers, before.layers); + assert_eq!(src.doc.selection, before.selection); + assert_eq!(src.history.undo_label(), Some("profile")); + + // With a layer mask: full pixels, the refined matte as the mask. + s.execute("file.close", json!({"document": 1})).unwrap(); + let r = s.execute("select.refineEdge", json!({"radius": 8, "output": "newDocumentWithMask"})).unwrap(); + assert_eq!(r["output"], "newDocumentWithMask"); + let nd = &s.active().unwrap().doc; + let l = &nd.layers[0]; + assert_eq!(l.surface().unwrap().pixel(75, 20), before.layers[0].surface().unwrap().pixel(75, 20), "depth {depth}"); + let m = l.mask.as_ref().unwrap(); + assert!(soft_count(&m.surface, 20) >= 4, "depth {depth}"); + assert!(m.value(5, 20) > 0.99 && m.value(75, 20) < 0.01, "depth {depth}"); + } +} + +#[test] +fn refine_edge_shift_and_contrast() { + let mut s = blurred_edge_selected(); + s.execute("select.refineEdge", json!({"shiftEdge": 100})).unwrap(); + assert!(cov(&s, 42, 20) > 0.99); + s.execute("edit.undo", json!({})).unwrap(); + s.execute("select.refineEdge", json!({"feather": 8, "contrast": 100})).unwrap(); + assert!(cov(&s, 38, 20) == 1.0 && cov(&s, 42, 20) == 0.0); +} + +/// The Refine Edge Brush adds strands beyond the radius band, at every depth, and rejects +/// malformed strokes. +#[test] +fn refine_edge_brush_strokes() { + for depth in [8, 16, 32] { + // Warm subject (x < 40) with warm strands every 4th column from x = 60, on blue. + let strand = |x: u32| x < 40 || ((60..84).contains(&x) && x.is_multiple_of(4)); + let mut s = session_with(120, 40, depth, |x, _| if strand(x) { [0.9, 0.7, 0.2] } else { [0.1, 0.3, 0.8] }); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 40, "height": 40})).unwrap(); + let stroke = json!([{"points": [[70, 5], [70, 35]], "size": 30}]); + s.execute("select.refineEdge", json!({"radius": 4, "refineStrokes": stroke})).unwrap(); + assert!(cov(&s, 64, 20) > 0.9 && cov(&s, 72, 20) > 0.9, "depth {depth}: strands {}", cov(&s, 64, 20)); + assert!(cov(&s, 66, 20) < 0.1 && cov(&s, 100, 20) < 0.01, "depth {depth}: background"); + s.execute("edit.undo", json!({})).unwrap(); + // Subtract over the same place paints the refinement out again. + let both = json!([{"points": [[70, 5], [70, 35]], "size": 30}, {"points": [[70, 5], [70, 35]], "size": 40, "mode": "subtract"}]); + s.execute("select.refineEdge", json!({"radius": 4, "refineStrokes": both})).unwrap(); + assert!(cov(&s, 64, 20) < 0.01, "depth {depth}"); + s.execute("edit.undo", json!({})).unwrap(); + for bad in [ + json!(7), + json!([5]), + json!([{"points": []}]), + json!([{"points": [[1, "x"]]}]), + json!([{"points": [[1, 2, 3]]}]), + json!([{"points": [[1, 2]], "size": 0}]), + json!([{"points": [[1, 2]], "size": 1e9}]), + json!([{"points": [[1, 2]], "mode": "xor"}]), + json!([{"points": [[0, 0], [1e6, 1e6], [0, 0], [1e6, 1e6]], "size": 5000}]), + ] { + assert!(s.execute("select.refineEdge", json!({"refineStrokes": bad})).is_err(), "{bad}"); + } + } +} + +#[test] +fn refine_edge_works_on_layer_mask_without_selection() { + let mut s = blurred_edge_selected(); + s.execute("layer.layerMask.revealSelection", json!({})).unwrap(); + assert!(s.active().unwrap().doc.selection.is_none()); + assert!(s.active().unwrap().doc.layers[0].mask.is_some()); + assert!(s.is_enabled("select.refineEdge")); + + let r = s.execute("select.refineEdge", json!({"radius": 8})).unwrap(); + assert_eq!(r["output"], "layerMask"); + let d = s.active().unwrap(); + let m = d.doc.layers[0].mask.as_ref().unwrap(); + assert!(soft_count(&m.surface, 20) >= 4); +} + +#[test] +fn focus_area_command() { + let nz = noise_field(160, 100, 3); + let mut blurred = vec![0.0f32; nz.len()]; + for y in 0..100i32 { + for x in 0..160i32 { + let mut a = 0.0; + for dy in -4..=4 { + for dx in -4..=4 { + a += nz[((y + dy).clamp(0, 99) * 160 + (x + dx).clamp(0, 159)) as usize]; + } + } + blurred[(y * 160 + x) as usize] = a / 81.0; + } + } + let mut s = session_with(160, 100, 8, move |x, y| { + let i = (y * 160 + x) as usize; + let v = 0.5 + 0.15 * if x < 80 { nz[i] } else { blurred[i] * 3.0 }; + [v, v, v].map(|c| c.clamp(0.0, 1.0)) + }); + s.execute("select.focusArea", json!({})).unwrap(); + assert!(cov(&s, 30, 50) >= 0.5 && cov(&s, 130, 50) < 0.5); +} +/// The selection as 8-bit coverage over `w × h`, to compare two selections exactly. +fn sel_bytes(s: &Session, w: i32, h: i32) -> Vec { + (0..h).flat_map(|y| (0..w).map(move |x| (cov(s, x, y) * 255.0).round() as u8)).collect() +} + +/// The #8783 review: a refine whose result would be dense over more than +/// [`matting::MAX_REFINE_AREA`] pixels is refused, not allocated: a thin Brush edit across a +/// huge canvas (its edited selection spans the canvas) and a selection of the whole canvas. +/// The selection stays as it was. +#[test] +fn refine_edge_refuses_a_selection_too_large_to_refine() { + let mut s = Session::new(); + s.add_document(Document::new("huge", photocraft_doc::Size::new(100_000, 100_000), photocraft_doc::ColorMode::Rgb, photocraft_color::SampleType::U8), None); + s.execute("select.rect", json!({"x": 10, "y": 60, "width": 10, "height": 10})).unwrap(); + let small = s.active().and_then(|d| d.doc.selection.clone()).expect("selected"); + let diagonal = json!({"edits": [{"tool": "brush", "points": [[0, 0], [99_999, 99_999]], "size": 1}]}); + let t = std::time::Instant::now(); + let e = s.execute("select.refineEdge", diagonal).expect_err("too large to refine"); + assert!(e.to_string().contains("too large to refine"), "{e}"); + assert!(s.active().and_then(|d| d.doc.selection.as_ref()) == Some(&small), "the selection is unchanged"); + // The small selection itself still refines. + s.execute("select.refineEdge", json!({"radius": 4})).unwrap(); + s.execute("edit.undo", json!({})).unwrap(); + s.execute("select.all", json!({})).unwrap(); + let all = s.active().and_then(|d| d.doc.selection.clone()).expect("selected"); + assert!(s.execute("select.refineEdge", json!({"radius": 4})).is_err()); + assert!(s.active().and_then(|d| d.doc.selection.as_ref()) == Some(&all)); + assert!(t.elapsed() < std::time::Duration::from_secs(20), "{:?}", t.elapsed()); +} + +/// The #8783 review: Brush and Lasso edits and Refine Edge Brush strokes that would paint +/// too many tiles of a huge canvas are refused before anything is painted, and the selection +/// stays as it was. +#[test] +fn refine_edge_refuses_edits_that_cross_too_many_tiles() { + let mut s = Session::new(); + s.add_document(Document::new("huge", photocraft_doc::Size::new(100_000, 100_000), photocraft_doc::ColorMode::Rgb, photocraft_color::SampleType::U8), None); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); + let before = s.active().and_then(|d| d.doc.selection.clone()).expect("selected"); + let zigzag: Vec<[f32; 2]> = (0..20).map(|i| [if i % 2 == 0 { 0.0 } else { 99_999.0 }, i as f32 * 5000.0]).collect(); + for p in [ + json!({"edits": [{"tool": "brush", "points": zigzag, "size": 1}]}), + json!({"edits": [{"tool": "lasso", "points": zigzag}]}), + json!({"refineStrokes": [{"points": zigzag, "size": 1}]}), + ] { + let e = s.execute("select.refineEdge", p.clone()).expect_err("refused"); + assert!(e.to_string().contains("too many tiles"), "{p}: {e}"); + assert!(s.active().and_then(|d| d.doc.selection.as_ref()) == Some(&before), "{p}: the selection is unchanged"); + } +} + +/// Select and Mask's own tools (#7069, #8148): each edit changes the selection before the +/// edge is refined, at every depth, and the whole run is one history step. +#[test] +fn refine_edge_edits_apply_each_tool_at_every_depth() { + for depth in [8, 16, 32] { + let mut s = two_regions(depth); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap(); + let start = sel_bytes(&s, 140, 100); + let run = |s: &mut Session, edits: Value| { + s.execute("select.refineEdge", json!({"edits": edits})).unwrap(); + let after = sel_bytes(s, 140, 100); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(sel_bytes(s, 140, 100), start, "depth {depth}: one undo restores the selection"); + after + }; + let at = |b: &[u8], x: usize, y: usize| b[y * 140 + x]; + // Quick Selection grows across the cool region; subtracting it again leaves the start. + let quick = run(&mut s, json!([{"tool": "quick", "points": [[100, 50], [110, 50]], "size": 8}])); + assert!(at(&quick, 120, 80) >= 128 && at(&quick, 5, 5) >= 128 && at(&quick, 40, 60) < 128, "depth {depth}: quick"); + let back = + run(&mut s, json!([{"tool": "quick", "points": [[100, 50]], "size": 8}, {"tool": "quick", "points": [[100, 50]], "size": 8, "mode": "subtract"}])); + assert!(at(&back, 120, 80) < 128 && at(&back, 5, 5) >= 128, "depth {depth}: quick subtract"); + // The Brush paints exactly where it goes. + let brush = run(&mut s, json!([{"tool": "brush", "points": [[30, 80], [60, 80]], "size": 10}])); + assert!(at(&brush, 45, 80) == 255 && at(&brush, 45, 90) == 0, "depth {depth}: brush"); + let erased = run(&mut s, json!([{"tool": "brush", "points": [[10, 10]], "size": 6, "mode": "subtract"}])); + assert!(at(&erased, 10, 10) == 0 && at(&erased, 2, 2) == 255, "depth {depth}: brush subtract"); + // Lasso adds and subtracts polygons. + let lasso = run(&mut s, json!([{"tool": "lasso", "points": [[50, 50], [90, 50], [90, 90], [50, 90]]}])); + assert!(at(&lasso, 70, 70) == 255 && at(&lasso, 95, 70) == 0 && at(&lasso, 5, 5) == 255, "depth {depth}: lasso"); + let cut = run(&mut s, json!([{"tool": "lasso", "points": [[0, 0], [10, 0], [10, 10], [0, 10]], "mode": "subtract"}])); + assert!(at(&cut, 5, 5) == 0 && at(&cut, 15, 15) == 255, "depth {depth}: lasso subtract"); + // Clear Selection, then Invert of nothing: everything. + let all = run(&mut s, json!([{"tool": "clear"}, {"tool": "invert"}])); + assert!(all.iter().all(|v| *v == 255), "depth {depth}: clear + invert"); + let inverted = run(&mut s, json!([{"tool": "invert"}])); + assert!(at(&inverted, 5, 5) == 0 && at(&inverted, 100, 50) == 255, "depth {depth}: invert"); + } +} + +/// Object Selection and Select Subject inside the workspace find what the standalone tools find. +#[test] +fn refine_edge_edits_object_and_subject() { + for depth in [8, 16, 32] { + let (mut s, inside) = disc(depth); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + s.execute("select.refineEdge", json!({"edits": [{"tool": "object", "rect": [40, 20, 120, 120]}, {"tool": "lasso", "points": [[0, 0], [10, 0], [10, 10], [0, 10]], "mode": "subtract"}]})).unwrap(); + let v = sel_iou(&s, 200, 160, &inside); + assert!(v > 0.95, "depth {depth}: object rect IoU {v}"); + s.execute("select.refineEdge", json!({"edits": [{"tool": "clear"}, {"tool": "object", "point": [3, 3]}, {"tool": "object", "point": [100, 80]}]})) + .unwrap(); + let v = sel_iou(&s, 200, 160, &inside); + assert!(v > 0.9, "depth {depth}: object point IoU {v} (the background point finds nothing)"); + } + let (mut s, inside) = disc(8); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + s.execute("select.refineEdge", json!({"edits": [{"tool": "subject"}]})).unwrap(); + let v = sel_iou(&s, 200, 160, &inside); + assert!(v > 0.9, "subject replaces the selection: IoU {v}"); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + s.execute("select.refineEdge", json!({"edits": [{"tool": "subject", "mode": "add"}]})).unwrap(); + assert!(cov(&s, 5, 5) >= 0.5 && cov(&s, 100, 80) >= 0.5, "subject added to the selection"); +} + +/// An edit gives what the standalone tool gives, then the edge is refined as usual, and the +/// result reaches every output. +#[test] +fn refine_edge_edits_match_the_tools_and_reach_the_outputs() { + let mut tool = two_regions(8); + tool.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap(); + tool.execute("select.quick", json!({"points": [[100, 50], [110, 50]], "size": 8})).unwrap(); + let mut ws = two_regions(8); + ws.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap(); + ws.execute("select.refineEdge", json!({"edits": [{"tool": "quick", "points": [[100, 50], [110, 50]], "size": 8}]})).unwrap(); + assert_eq!(sel_bytes(&ws, 140, 100), sel_bytes(&tool, 140, 100)); + // Refinement runs on the edited selection: Shift Edge contracts the brushed bar too. + let mut s = two_regions(8); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap(); + s.execute("select.refineEdge", json!({"shiftEdge": -100, "edits": [{"tool": "brush", "points": [[30, 80], [100, 80]], "size": 20}]})).unwrap(); + assert!(cov(&s, 60, 80) >= 0.5 && cov(&s, 60, 88) < 0.5 && cov(&s, 60, 72) < 0.5, "the 20 px bar shrank"); + // Layer mask and new-layer outputs take the edited selection. + let mut s = blurred_edge_selected(); + let r = s.execute("select.refineEdge", json!({"output": "layerMask", "edits": [{"tool": "invert"}]})).unwrap(); + assert_eq!(r["output"], "layerMask"); + let m = s.active().unwrap().doc.layers[0].mask.as_ref().unwrap(); + assert!(m.surface.sample_channel(10, 20, 0) < 0.01 && m.surface.sample_channel(70, 20, 0) > 0.99); + let mut s = blurred_edge_selected(); + let r = s.execute("select.refineEdge", json!({"output": "newLayerWithMask", "edits": [{"tool": "invert"}]})).unwrap(); + assert_eq!(r["output"], "newLayerWithMask"); + let d = s.active().unwrap(); + let m = d.doc.layers.iter().find_map(|l| l.mask.as_ref()).unwrap(); + assert!(m.surface.sample_channel(10, 20, 0) < 0.01 && m.surface.sample_channel(70, 20, 0) > 0.99); + // Clearing everything deselects. + let mut s = blurred_edge_selected(); + let r = s.execute("select.refineEdge", json!({"edits": [{"tool": "clear"}]})).unwrap(); + assert_eq!(r["selected"], false); + assert!(s.active().unwrap().doc.selection.is_none()); +} + +/// Bad edits are refused before anything changes. +#[test] +fn refine_edge_rejects_bad_edits_and_keeps_the_selection() { + let mut s = blurred_edge_selected(); + let before = sel_bytes(&s, 80, 40); + for bad in [json!(7), json!([{"tool": "nope"}]), json!([{"tool": "lasso", "points": [[0, 0]]}]), json!([{"tool": "brush", "points": [[0, 0]], "size": -1}])] + { + assert!(s.execute("select.refineEdge", json!({"edits": bad})).is_err(), "{bad}"); + assert_eq!(sel_bytes(&s, 80, 40), before, "{bad}"); + } +} diff --git a/crates/engine/src/solid_fill_cmds.rs b/crates/engine/src/cmd/solid_fill_cmds.rs similarity index 100% rename from crates/engine/src/solid_fill_cmds.rs rename to crates/engine/src/cmd/solid_fill_cmds.rs diff --git a/crates/engine/src/stamp_cmds.rs b/crates/engine/src/cmd/stamp_cmds.rs similarity index 100% rename from crates/engine/src/stamp_cmds.rs rename to crates/engine/src/cmd/stamp_cmds.rs diff --git a/crates/engine/src/style_asl_cmds.rs b/crates/engine/src/cmd/style_asl_cmds.rs similarity index 100% rename from crates/engine/src/style_asl_cmds.rs rename to crates/engine/src/cmd/style_asl_cmds.rs diff --git a/crates/engine/src/swatch_cmds.rs b/crates/engine/src/cmd/swatch_cmds.rs similarity index 100% rename from crates/engine/src/swatch_cmds.rs rename to crates/engine/src/cmd/swatch_cmds.rs diff --git a/crates/engine/src/swatch_cmds/tests.rs b/crates/engine/src/cmd/swatch_cmds/tests.rs similarity index 100% rename from crates/engine/src/swatch_cmds/tests.rs rename to crates/engine/src/cmd/swatch_cmds/tests.rs diff --git a/crates/engine/src/symmetry_cmds.rs b/crates/engine/src/cmd/symmetry_cmds.rs similarity index 100% rename from crates/engine/src/symmetry_cmds.rs rename to crates/engine/src/cmd/symmetry_cmds.rs diff --git a/crates/engine/src/symmetry_cmds/preset_tests.rs b/crates/engine/src/cmd/symmetry_cmds/preset_tests.rs similarity index 100% rename from crates/engine/src/symmetry_cmds/preset_tests.rs rename to crates/engine/src/cmd/symmetry_cmds/preset_tests.rs diff --git a/crates/engine/src/timeline_cmds.rs b/crates/engine/src/cmd/timeline_cmds.rs similarity index 100% rename from crates/engine/src/timeline_cmds.rs rename to crates/engine/src/cmd/timeline_cmds.rs diff --git a/crates/engine/src/cmd/transform_cmds.rs b/crates/engine/src/cmd/transform_cmds.rs new file mode 100644 index 0000000000..d1b9690312 --- /dev/null +++ b/crates/engine/src/cmd/transform_cmds.rs @@ -0,0 +1,876 @@ +//! Edit › Free Transform / Transform: projective transforms of layers (and the selection). + +use photocraft_algo::transform::{Homography, Interp, WARP_REACH, warp_output_clipped, warp_output_size, warp_surface, warp_surface_with}; +use photocraft_color::PixelFormat; +#[cfg(test)] +use photocraft_color::{ColorMode, SampleType}; +use photocraft_doc::{Document, Layer, LayerContent, LayerId, Locks}; +use photocraft_geom::{Affine, Rect}; +use photocraft_raster::{Interrupt, Surface}; +use serde_json::{Value, json}; +use std::sync::atomic::{AtomicU64, Ordering}; + +use crate::commands::CommandSpec; +use crate::{EngineError, Result, Session}; + +fn has_layer(s: &Session) -> std::result::Result<(), String> { + s.active().and_then(|d| d.active_layer).map(|_| ()).ok_or_else(|| "no active layer".into()) +} + +fn bad(msg: impl Into) -> EngineError { + EngineError::BadParams { cmd: "edit.transform".into(), msg: msg.into() } +} + +/// Layers a transform moves as a whole, even with a selection: groups, and the kinds that keep the +/// transform instead of pixels (type, shapes, smart objects). Only pixel layers move just the +/// selected pixels. +pub fn moves_whole(layer: &Layer) -> bool { + matches!(layer.content, LayerContent::Group(_) | LayerContent::Text(_) | LayerContent::Shape(_) | LayerContent::Smart(_)) +} + +/// Document-space bounds a transform of `layer` starts from (what Free Transform frames): the +/// content within the selection, or all of it for a layer that [`moves_whole`] (#2630). +/// Content scans are cached per tile: snapping asks for every layer's bounds per Move drag. +pub fn transform_bounds(doc: &Document, layer: &Layer) -> Rect { + let content = whole_layer_bounds(doc, layer); + match &doc.selection { + Some(sel) if !moves_whole(layer) => content.intersect(&sel.content_bounds()), + _ => content, + } +} + +/// The box Free Transform opens on `layer`, and the Move tool's transform controls show (#5297). +/// With a selection that limits the transform it is the selection's own bounds, as in Photoshop: +/// the box and the marching ants are one rectangle, however little of the selection the layer +/// fills. Empty, like [`transform_bounds`], when the selection holds none of the layer. +pub fn transform_frame(doc: &Document, layer: &Layer) -> Rect { + let b = transform_bounds(doc, layer); + if moves_whole(layer) { b } else { framed_by_selection(doc, b) } +} + +/// `bounds` (what a selection left of a transform's content), or the selection's own bounds. +fn framed_by_selection(doc: &Document, bounds: Rect) -> Rect { + match &doc.selection { + Some(sel) if !bounds.is_empty() => sel.content_bounds(), + _ => bounds, + } +} + +/// A group moves all its descendants, so its frame must not clip raster children to the selection. +pub(crate) fn whole_layer_bounds(doc: &Document, layer: &Layer) -> Rect { + let content = match &layer.content { + LayerContent::Group(g) => g.children.iter().map(|c| whole_layer_bounds(doc, c)).fold(Rect::EMPTY, |a, b| a.union(&b)), + // A soft shape (Density below 100 % or a Feather) renders past its path, over the whole + // canvas below 100 %: its frame follows the path and stroke, as in Photoshop (#5846). + LayerContent::Shape(sh) if sh.has_soft_mask() => photocraft_compose::soft_shape_frame(sh, doc.pixel_format(), doc.bounds()).unwrap_or(Rect::EMPTY), + _ => layer.surface().map_or(Rect::EMPTY, photocraft_compose::bounds::content_bounds), + }; + if content.is_empty() { layer.mask.as_ref().map_or(Rect::EMPTY, |m| photocraft_compose::bounds::content_bounds(&m.surface)) } else { content } +} + +/// Warp a surface whose pixels outside the content read as `default` (masks, selections): +/// warp the content with alpha, then flatten back onto the default value. +pub(crate) fn warp_gray(s: &Surface, h: &Homography, interp: Interp) -> Result { + let default = s.default_pixel().first().copied().unwrap_or(0.0); + let fmt = s.format(); + let src = s.content_bounds(); + let mut out = Surface::with_default(fmt, &[default]); + if src.is_empty() { + return Ok(out); + } + // Content-only copy (default 0 + alpha) so the "outside" is transparent during the warp. + let with_alpha = PixelFormat::new(fmt.mode, fmt.sample, true); + let mut tmp = Surface::new(with_alpha); + let v = crate::allocation::read_region(s, src, "transforming a mask or channel")?; + let mut lifted = + crate::allocation::filled(v.len().checked_mul(2).ok_or_else(|| bad("the mask is too large to transform"))?, 0.0, "transforming a mask or channel")?; + let (lifted_pairs, _) = lifted.as_chunks_mut::<2>(); + for (g, px) in v.iter().zip(lifted_pairs) { + px.copy_from_slice(&[*g, 1.0]); + } + tmp.try_write_region(src, &lifted)?; + let w = warp_surface(&tmp, src, h, interp)?; + // Clear the old content region, then composite the warped content over it. These are written as + // two sparse regions rather than one dense `src ∪ warped` block: a transform that moves the + // content far away (e.g. a huge translation) would otherwise allocate a buffer spanning both and + // hang/OOM. `Surface` is tile-sparse, so distant regions cost only their own tiles. + let old_len = (src.width() as usize).checked_mul(src.height() as usize).ok_or_else(|| bad("the mask is too large to transform"))?; + let old = crate::allocation::filled(old_len, default, "transforming a mask or channel")?; + out.try_write_region(src, &old)?; + let b = w.content_bounds(); + if !b.is_empty() { + let px = crate::allocation::read_region(&w, b, "flattening a transformed mask or channel")?; + let mut flat = crate::allocation::filled(px.len() / 2, 0.0, "flattening a transformed mask or channel")?; + for (p, f) in px.as_chunks::<2>().0.iter().zip(&mut flat) { + *f = p[0] * p[1] + default * (1.0 - p[1]); + } + out.try_write_region(b, &flat)?; + } + out.prune(); + Ok(out) +} + +/// Split a single-channel surface whose outside reads as its default (a mask, a channel) by a +/// selection: (the selected values as grey + alpha = selection, the surface with the selected +/// values replaced by the default). `None` for surfaces that aren't a single grey channel. +pub fn split_gray_selected(s: &Surface, sel: &Surface) -> Result> { + let fmt = s.format(); + if fmt.alpha || fmt.channels() != 1 { + return Ok(None); + } + let default = s.default_pixel().first().copied().unwrap_or(0.0); + let mut rest = s.clone(); + let mut lifted = Surface::new(PixelFormat::new(fmt.mode, fmt.sample, true)); + // Everything selected moves, including default-valued parts outside the painted content, so + // the moved region stays aligned with the moved pixels. + let area = sel.content_bounds(); + if area.is_empty() { + return Ok(Some((lifted, rest))); + } + let v = crate::allocation::read_region(s, area, "transforming a selected mask or channel")?; + let w = area.width() as usize; + let mut lp = crate::allocation::capacity( + v.len().checked_mul(2).ok_or_else(|| bad("the selected mask is too large to transform"))?, + "transforming a selected mask or channel", + )?; + let mut rp = crate::allocation::capacity(v.len(), "transforming a selected mask or channel")?; + for (i, g) in v.iter().enumerate() { + let (x, y) = (area.x0 + (i % w) as i32, area.y0 + (i / w) as i32); + let k = sel.sample_channel(x, y, 0); + lp.extend([*g, k]); + rp.push(g * (1.0 - k) + default * k); + } + lifted.try_write_region(area, &lp)?; + lifted.prune(); + rest.try_write_region(area, &rp)?; + rest.prune(); + Ok(Some((lifted, rest))) +} + +/// [`warp_gray`] limited to a selection: only the selected values move (the vacated area reads as +/// the default), as the selected pixels of the layer do. +pub(crate) fn warp_gray_selected(s: &Surface, sel: &Surface, h: &Homography, interp: Interp) -> Result { + move_gray_selected(s, sel, &|lifted, src| Ok(warp_surface(lifted, src, h, interp)?), &|s| warp_gray(s, h, interp)) +} + +/// [`warp_gray_selected`] with any geometric warp: `warp` moves the lifted grey + alpha values +/// (given their bounds), `whole` moves `s` when it isn't a single grey channel. +pub(crate) fn move_gray_selected( + s: &Surface, + sel: &Surface, + warp: &dyn Fn(&Surface, Rect) -> Result, + whole: &dyn Fn(&Surface) -> Result, +) -> Result { + let Some((lifted, mut out)) = split_gray_selected(s, sel)? else { return whole(s) }; + let src = lifted.content_bounds(); + if src.is_empty() { + return Ok(out); + } + let w = warp(&lifted, src)?; + let b = w.content_bounds(); + if !b.is_empty() { + let moved = crate::allocation::read_region(&w, b, "compositing transformed mask pixels")?; + let under = crate::allocation::read_region(&out, b, "compositing transformed mask pixels")?; + let mut flat = crate::allocation::filled(under.len(), 0.0, "compositing transformed mask pixels")?; + for (i, (p, u)) in moved.as_chunks::<2>().0.iter().zip(&under).enumerate() { + flat[i] = p[0] * p[1] + u * (1.0 - p[1]); + } + out.try_write_region(b, &flat)?; + } + out.prune(); + Ok(out) +} + +/// The surface Free Transform moves by itself when the params target one (`"target"`): an +/// unlinked layer mask, an alpha channel or the Quick Mask. `None` means the layer, with its +/// linked masks (a targeted *linked* mask moves together with its layer, as in Photoshop). +pub fn lone_target<'a>(doc: &'a Document, layer: Option, p: &Value) -> Result> { + use crate::channel_cmds::Target; + match crate::channel_cmds::target_of(p) { + Target::Pixels => Ok(None), + Target::Mask => { + let id = layer.ok_or_else(|| EngineError::Other("no active layer".into()))?; + let l = doc.layer(id).ok_or(EngineError::NoLayer(id))?; + let m = l.mask.as_ref().ok_or_else(|| EngineError::Other("layer has no mask".into()))?; + Ok((!m.linked).then_some(&m.surface)) + } + // A filter mask is not transformed on its own: the smart object transforms, as in Photoshop. + Target::FilterMask => Ok(None), + Target::Alpha(i) => doc + .channels + .get(i) + .map(|c| Some(&c.surface)) + .ok_or_else(|| EngineError::Other(format!("no alpha channel {i} (document has {})", doc.channels.len()))), + Target::QuickMask => doc.quick_mask.as_ref().map(|c| Some(&c.surface)).ok_or_else(|| EngineError::Other("not in Quick Mask mode".into())), + } +} + +/// [`lone_target`], mutably. +pub fn lone_target_mut<'a>(doc: &'a mut Document, layer: Option, p: &Value) -> Result> { + if lone_target(doc, layer, p)?.is_none() { + return Ok(None); + } + crate::channel_cmds::target_surface(doc, layer, p).map(|(s, _)| Some(s)) +} + +/// The frame Free Transform starts from on a lone target: its painted content (the whole canvas +/// when nothing is painted), within the selection. +pub fn target_bounds(doc: &Document, surf: &Surface) -> Rect { + let content = surf.content_bounds(); + let content = if content.is_empty() { doc.bounds() } else { content }; + match &doc.selection { + Some(sel) => content.intersect(&sel.content_bounds()), + None => content, + } +} + +/// The box Free Transform opens on a lone target: like [`transform_frame`], the selection's own +/// bounds when there is one (#5297). +pub fn target_frame(doc: &Document, surf: &Surface) -> Rect { + framed_by_selection(doc, target_bounds(doc, surf)) +} + +/// The locks `id` inherits from the groups around it. +pub(crate) fn group_locks(doc: &Document, id: LayerId) -> Locks { + doc.path_of(id).and_then(|p| Some(doc.locks_at(p.split_last()?.1))).unwrap_or_default() +} + +/// The locks a transform of `l` meets: its own and `group`'s (those it inherits). The Background's +/// position lock doesn't count: Photoshop turns it into a normal layer first. +fn transform_locks(l: &Layer, group: Locks, background: bool) -> Locks { + let mut own = l.locks; + if background { + own.position = false; + own.transparency = false; + } + own.union(group) +} + +/// Would a transform of the layer `id` be refused because it, a group around it, or (for a group) +/// a layer inside it is locked in place? The same rule [`transform_layer`] applies at commit, so +/// Free Transform can refuse before its box opens, as Photoshop does. +pub fn locked_for_transform(doc: &Document, id: LayerId) -> bool { + let Some(l) = doc.layer(id) else { return false }; + // An explicit stack rather than recursion: documents can nest deeply. + let mut stack = vec![(l, group_locks(doc, id), doc.is_background(id))]; + while let Some((l, group, background)) = stack.pop() { + let locks = transform_locks(l, group, background); + if locks.position || locks.all { + return true; + } + if let LayerContent::Group(g) = &l.content { + stack.extend(g.children.iter().map(|c| (c, locks, false))); + } + } + false +} + +/// The memory (bytes) a single Free Transform warp's result may take: Preferences › Performance › +/// Memory Usage, which [`Session::apply_prefs`] sets, rather than a fixed 2³⁰ px, so a stitched +/// layer of a few gigapixels transforms on a machine that has the memory for it (#7807). Only the +/// size of the result counts, not where it lands, so moving a layer far off the canvas stays +/// allowed as far as the warp reaches ([`WARP_REACH`]). A scale past it is refused rather than +/// clipped (#3773): the warp would otherwise fill every tile of a result up to 2²¹ px on a side +/// before anything could fail. +static BUDGET: AtomicU64 = AtomicU64::new((crate::prefs::DEFAULT_MEMORY_USAGE_MB as u64) << 20); + +/// Set the memory (bytes) one transform's result may take (see [`budget`]). +pub fn set_budget(bytes: u64) { + BUDGET.store(bytes, Ordering::Relaxed); +} + +/// The memory (bytes) one transform's result may take: Memory Usage. +pub fn budget() -> u64 { + BUDGET.load(Ordering::Relaxed) +} + +/// What [`check_budget`] holds a result to: [`budget`]. +#[cfg(not(test))] +fn active_budget() -> u64 { + budget() +} + +/// Tests use a far lower budget, so proving a refusal never comes near allocating the real one: +/// 2²⁰ px of the widest format (32-bit CMYK with alpha, 20 MB), so a result within the old 2²⁰ px +/// test limit still fits at any depth. +#[cfg(test)] +fn active_budget() -> u64 { + (1 << 20) * PixelFormat::new(ColorMode::Cmyk, SampleType::F32, true).bytes_per_pixel() as u64 +} + +/// Refuse a warp of the content inside `src` (pixels of `format`) by `h` whose result would take +/// more memory than the budget, or reach past where the warp places pixels (it would be clipped), +/// before anything is built. `what` names the surface in the message, which names the setting or +/// the reach rather than a shortage: nothing has been allocated yet. +pub(crate) fn check_budget(src: Rect, h: &Homography, what: &str, format: PixelFormat) -> Result<()> { + check_budget_with_limit(src, h, what, format, active_budget()) +} + +/// [`check_budget`] against `budget` bytes (the tests price the production budget with it). +fn check_budget_with_limit(src: Rect, h: &Homography, what: &str, format: PixelFormat, budget: u64) -> Result<()> { + let Some((w, ht)) = warp_output_size(src, h) else { return Ok(()) }; + // The warp writes each tile into the result as it goes, so the result is what it holds; it + // adds alpha to a format without it. + let bpp = PixelFormat::new(format.mode, format.sample, true).bytes_per_pixel() as u64; + let bytes = w.saturating_mul(ht).saturating_mul(bpp); + if bytes > budget { + let mb = |b: u64| b.div_ceil(1 << 20); + return Err(EngineError::Other(format!( + "too large to transform: the transformed {what} would be {w} x {ht} px ({} MB), more than the {} MB Memory Usage allows (Preferences › Performance); the document was not changed", + mb(bytes), + budget >> 20 + ))); + } + if warp_output_clipped(src, h) { + return Err(EngineError::Other(format!( + "too large to transform: the transformed {what} would reach past ±{WARP_REACH} px, the farthest a transform places pixels; the document was not changed" + ))); + } + Ok(()) +} + +/// [`check_budget`] for every warp [`transform_layer`] would make of `l` (for a group, of every +/// layer inside it), so a transform that doesn't fit is refused before any layer is built and a +/// group that partly fits isn't half-transformed. +fn check_layer_budget(doc_sel: Option<&Surface>, l: &Layer, h: &Homography) -> Result<()> { + if h.is_identity() { + return Ok(()); + } + // An explicit stack rather than recursion: documents can nest deeply. + let mut stack = vec![(l, doc_sel)]; + while let Some((l, sel)) = stack.pop() { + match &l.content { + LayerContent::Group(g) => stack.extend(g.children.iter().map(|c| (c, None))), + LayerContent::Text(_) | LayerContent::Shape(_) => {} + LayerContent::Smart(sm) => { + if let Some(c) = &sm.cache { + check_budget(c.content_bounds(), h, "smart object", c.format())?; + } + if let Some(m) = &sm.filter_mask { + check_budget(m.surface.content_bounds(), h, "smart filter mask", m.surface.format())?; + } + } + _ => { + if let Some(surf) = l.surface() { + // With a selection only the lifted pixels are warped (`split_selected`). + let src = match sel { + Some(sel) => surf.content_bounds().intersect(&sel.content_bounds()), + None => surf.content_bounds(), + }; + check_budget(src, h, &format!("layer \"{}\"", l.name), surf.format())?; + } + } + } + if let Some(m) = &l.mask + && m.linked + { + // With a selection only its region of the mask moves (`warp_gray_selected`). + let src = match sel.filter(|_| !moves_whole(l)) { + Some(sel) => sel.content_bounds(), + None => m.surface.content_bounds(), + }; + check_budget(src, h, "layer mask", m.surface.format())?; + } + } + Ok(()) +} + +/// `group` holds the locks `l` inherits from the groups around it ([`group_locks`]). A Background +/// is turned into a normal layer by the caller first ([`crate::extra_cmds::background_to_layer`]). +/// Refused, with `l` untouched, when a result would take more than [`budget`]. +pub(crate) fn transform_layer(doc_sel: Option<&Surface>, group: Locks, l: &mut Layer, h: &Homography, affine: Option, interp: Interp) -> Result<()> { + transform_layer_with(doc_sel, group, l, h, affine, interp, &Interrupt::NONE) +} + +/// [`transform_layer`] with progress and cancellation for the pixel warp (the slow part on a +/// large layer, #1015). +fn transform_layer_with( + doc_sel: Option<&Surface>, + group: Locks, + l: &mut Layer, + h: &Homography, + affine: Option, + interp: Interp, + ctl: &Interrupt, +) -> Result<()> { + check_layer_budget(doc_sel, l, h)?; + apply_transform(doc_sel, group, l, h, affine, interp, ctl) +} + +fn apply_transform( + doc_sel: Option<&Surface>, + group: Locks, + l: &mut Layer, + h: &Homography, + affine: Option, + interp: Interp, + ctl: &Interrupt, +) -> Result<()> { + crate::allocation::checkpoint("transforming pixels")?; + let locks = transform_locks(l, group, false); + if locks.position || locks.all { + return Err(EngineError::Other(format!("layer \"{}\" is locked", l.name))); + } + if h.is_identity() { + if let LayerContent::Group(g) = &mut l.content { + for c in g.children.iter_mut() { + apply_transform(None, locks, c, h, affine, interp, ctl)?; + } + } + return Ok(()); + } + // With a selection only the selected pixels move, and so only the same region of a linked + // mask (#205). Groups, type, shapes and smart objects move whole. + let mask_sel = doc_sel.filter(|_| !moves_whole(l)); + // The masks (and so a fill's frame) move, but a fill layer's cached render isn't warped: + // drop it, the fill re-renders from its model (as `transform_layer_geometry` does). + l.fill_cache = None; + match &mut l.content { + LayerContent::Group(g) => { + for c in g.children.iter_mut() { + apply_transform(None, locks, c, h, affine, interp, ctl)?; + } + } + LayerContent::Text(t) => { + let Some(a) = affine else { + return Err(EngineError::Other("Distort and Perspective need rasterized type (Type › Rasterize Type Layer)".into())); + }; + t.transform = a.mul(&t.transform); + } + LayerContent::Shape(sh) => match affine { + Some(a) => crate::vector_cmds::transform_shape(sh, &a), + // Distort and Perspective map the path and keep the shape (#3009). + None => crate::vector_cmds::map_shape(sh, Some(h), None)?, + }, + LayerContent::Smart(sm) => { + // Smart objects keep the transform and re-render from their source afterwards + // (`refresh_text`), so repeated transforms don't degrade the pixels. Distort and + // Perspective keep the full projective map, so the fourth corner survives re-renders. + match affine { + Some(a) => crate::smart_cmds::transform_placement(sm, &a), + None => crate::smart_cmds::set_placement(sm, h.mul(&crate::smart_cmds::placement(sm))), + } + // Fallback appearance for sources that can't be re-rendered. + if let Some(c) = &mut sm.cache { + let src = c.content_bounds(); + *c = warp_surface(c, src, h, interp)?; + } + if let Some(m) = &mut sm.filter_mask { + m.surface = warp_gray(&m.surface, h, interp)?; + } + } + _ => { + if let Some(surf) = l.surface_mut() { + *surf = match doc_sel { + // Only the selected pixels move: lift them, clear them, warp and paste back. The + // lifted pixels' own bounds are the edge a stretch repeats (#3773). + Some(sel) => { + let (lifted, mut rest) = split_selected(surf, sel)?; + let moved = warp_surface_with(&lifted, lifted.content_bounds(), h, interp, ctl)?.ok_or(EngineError::Cancelled)?; + composite_over(&mut rest, &moved); + rest.prune(); + rest + } + None => { + let src = surf.content_bounds(); + warp_surface_with(surf, src, h, interp, ctl)?.ok_or(EngineError::Cancelled)? + } + }; + } + } + } + if let Some(m) = l.mask.as_mut() + && m.linked + { + m.surface = match mask_sel { + Some(sel) => warp_gray_selected(&m.surface, sel, h, interp)?, + None => warp_gray(&m.surface, h, interp)?, + }; + } + if let Some(vm) = l.vector_mask.as_mut() + && vm.linked + { + vm.path = match affine { + Some(a) => vm.path.transform(&a), + None => crate::vector_cmds::map_path(&vm.path, Some(h), None)?, + }; + } + Ok(()) +} + +/// Split a layer surface by a selection: (selected pixels, everything else), both with alpha. +pub fn split_selected(surf: &Surface, sel: &Surface) -> Result<(Surface, Surface)> { + let fmt = surf.format(); + let with_alpha = PixelFormat::new(fmt.mode, fmt.sample, true); + let mut lifted = Surface::new(with_alpha); + let mut rest = surf.try_convert(with_alpha)?; + let src = surf.content_bounds(); + if src.is_empty() { + return Ok((lifted, rest)); + } + let n = with_alpha.channels(); + let px = crate::allocation::read_region(&rest, src, "transforming selected pixels")?; + let mut lp = crate::allocation::filled(px.len(), 0.0, "transforming selected pixels")?; + lp.copy_from_slice(&px); + let mut rp = px; + let w = src.width() as usize; + // A pixel the selection fully lifts out is reset to the surface's (transparent) default; + // keeping its colour would make `content_bounds` still count it, so the layer's bounds would + // include the area the pixels were moved from. + let mut rest_clear = rest.default_pixel(); + if rest_clear.last().is_some_and(|a| *a > 0.0) { + rest_clear.fill(0.0); + } + for (i, (l, r)) in lp.chunks_exact_mut(n).zip(rp.chunks_exact_mut(n)).enumerate() { + let (x, y) = (src.x0 + (i % w) as i32, src.y0 + (i / w) as i32); + let k = sel.sample_channel(x, y, 0); + l[n - 1] *= k; + r[n - 1] *= 1.0 - k; + // Likewise an unselected pixel leaves nothing in the lifted surface, so its bounds are the + // selected pixels' (what a stretch repeats at the edge, #3773). + if l[n - 1] <= 0.0 { + l.fill(0.0); + } + if r[n - 1] <= 0.0 { + r.iter_mut().zip(&rest_clear).for_each(|(d, c)| *d = *c); + } + } + lifted.try_write_region(src, &lp)?; + lifted.prune(); + rest.try_write_region(src, &rp)?; + Ok((lifted, rest)) +} + +pub(crate) fn refresh_text(doc: &Document, l: &mut Layer) { + match &mut l.content { + LayerContent::Text(t) => crate::type_cmds::refresh(doc, t), + LayerContent::Shape(sh) => crate::vector_cmds::refresh_shape(doc, sh), + LayerContent::Smart(_) => { + // Unavailable sources keep the warped cache. + let _ = crate::smart_cmds::refresh_layer(doc, l); + } + LayerContent::Group(g) => g.children.iter_mut().for_each(|c| refresh_text(doc, c)), + _ => {} + } +} + +/// Normal-blend `top` over `dst` (both straight alpha, same format). +/// Works tile by tile in parallel on `top`'s allocated tiles: fully opaque tiles share their +/// `Arc` directly with `dst`, and opaque/transparent pixels on border tiles copy encoded +/// bytes without a whole-region `f32` round trip. +pub(crate) fn composite_over(dst: &mut Surface, top: &Surface) { + use photocraft_color::{SampleType, read_sample}; + use photocraft_geom::TileCoord; + use photocraft_raster::Tile; + use rayon::prelude::*; + use std::sync::Arc; + + let fmt = dst.format(); + let n = fmt.channels(); + if n == 0 || !fmt.alpha || top.format() != fmt { + return; + } + let a = n - 1; + if top.default_pixel().get(a).is_none_or(|&ta| ta <= 0.0) { + let top_tiles: Vec<(TileCoord, Arc)> = top.tiles().map(|(&tc, t)| (tc, t.clone())).collect(); + if top_tiles.is_empty() { + return; + } + let bpp = fmt.bytes_per_pixel(); + let sb = fmt.sample.bytes(); + let alpha_off = bpp - sb; + let dst_empty_default = dst.default_bytes().iter().all(|&b| b == 0); + let dst_ref = &*dst; + let edits: Vec<(TileCoord, Arc)> = top_tiles + .into_par_iter() + .filter_map(|(tc, top_tile)| { + let tb = top_tile.bytes(); + let all_opaque = match fmt.sample { + SampleType::U8 => tb.chunks_exact(bpp).all(|px| px.get(alpha_off) == Some(&u8::MAX)), + SampleType::U16 => tb.chunks_exact(bpp).all(|px| px.get(alpha_off..bpp) == Some(&[u8::MAX, u8::MAX])), + SampleType::F32 => tb.chunks_exact(bpp).all(|px| read_sample(px, SampleType::F32, a) == 1.0), + }; + if all_opaque { + return Some((tc, top_tile)); + } + let all_transparent = match fmt.sample { + SampleType::U8 => tb.chunks_exact(bpp).all(|px| px.get(alpha_off) == Some(&0)), + SampleType::U16 => tb.chunks_exact(bpp).all(|px| px.get(alpha_off..bpp) == Some(&[0, 0])), + SampleType::F32 => tb.chunks_exact(bpp).all(|px| read_sample(px, SampleType::F32, a) <= 0.0), + }; + if all_transparent { + return None; + } + if dst_ref.tile(tc).is_none() && dst_empty_default { + let clean_zero = match fmt.sample { + SampleType::U8 => tb.chunks_exact(bpp).all(|px| px.get(alpha_off) != Some(&0) || px.iter().all(|&b| b == 0)), + SampleType::U16 => tb.chunks_exact(bpp).all(|px| px.get(alpha_off..bpp) != Some(&[0, 0]) || px.iter().all(|&b| b == 0)), + SampleType::F32 => tb.chunks_exact(bpp).all(|px| read_sample(px, SampleType::F32, a) > 0.0 || px.iter().all(|&b| b == 0)), + }; + if clean_zero { + return Some((tc, top_tile)); + } + } + let mut out_tile = match dst_ref.tile(tc) { + Some(dt) => (**dt).clone(), + None => dst_ref.try_default_tile().ok()?, + }; + let mut tp = [0.0f32; 8]; + let mut dp = [0.0f32; 8]; + for (out_px, top_px) in out_tile.bytes_mut().chunks_exact_mut(bpp).zip(tb.chunks_exact(bpp)) { + match fmt.sample { + SampleType::U8 => { + let ta_b = top_px[alpha_off]; + if ta_b == 0 { + continue; + } + if ta_b == u8::MAX { + out_px.copy_from_slice(top_px); + continue; + } + } + SampleType::U16 => { + if top_px[alpha_off..bpp] == [0, 0] { + continue; + } + if top_px[alpha_off..bpp] == [u8::MAX, u8::MAX] { + out_px.copy_from_slice(top_px); + continue; + } + } + SampleType::F32 => { + let ta = read_sample(top_px, SampleType::F32, a); + if ta <= 0.0 { + continue; + } + if ta == 1.0 { + out_px.copy_from_slice(top_px); + continue; + } + } + } + for c in 0..n { + tp[c] = read_sample(top_px, fmt.sample, c); + dp[c] = read_sample(out_px, fmt.sample, c); + } + let (ta, da) = (tp[a], dp[a]); + let oa = ta + da * (1.0 - ta); + if oa > 0.0 { + for c in 0..a { + dp[c] = (tp[c] * ta + dp[c] * da * (1.0 - ta)) / oa; + } + } + dp[a] = oa; + photocraft_raster::encode_pixel(&fmt, &dp[..n], out_px); + } + Some((tc, Arc::new(out_tile))) + }) + .collect(); + dst.put_tiles(edits); + return; + } + let b = top.content_bounds(); + if b.is_empty() { + return; + } + let t = top.read_region(b); + let mut d = dst.read_region(b); + for (dp, tp) in d.chunks_exact_mut(n).zip(t.chunks_exact(n)) { + let (ta, da) = (tp[a], dp[a]); + let oa = ta + da * (1.0 - ta); + if oa > 0.0 { + for c in 0..a { + dp[c] = (tp[c] * ta + dp[c] * da * (1.0 - ta)) / oa; + } + } + dp[a] = oa; + } + dst.write_region(b, &d); +} + +/// The relative form (`scaleX`, `scaleY` in percent, `rotate` in degrees clockwise, `dx`, `dy` +/// in pixels), as Photoshop records a Free Transform: scale and rotate about the frame's +/// centre, then move. `None` when none of them is given. +fn relative_matrix(p: &Value, rect: [f64; 4]) -> Result> { + let num = |k: &str| -> Result> { + match p.get(k) { + None | Some(Value::Null) => Ok(None), + Some(v) => v.as_f64().filter(|f| f.is_finite()).map(Some).ok_or_else(|| bad(format!("`{k}` must be a finite number"))), + } + }; + let (sx, sy, rot, dx, dy) = (num("scaleX")?, num("scaleY")?, num("rotate")?, num("dx")?, num("dy")?); + if sx.is_none() && sy.is_none() && rot.is_none() && dx.is_none() && dy.is_none() { + return Ok(None); + } + let (sx, sy) = (sx.unwrap_or(100.0) / 100.0, sy.unwrap_or(100.0) / 100.0); + if sx.abs() < 1e-6 || sy.abs() < 1e-6 { + return Err(bad("`scaleX` and `scaleY` must not be 0")); + } + let (cx, cy) = ((rect[0] + rect[2]) / 2.0, (rect[1] + rect[3]) / 2.0); + let (sin, cos) = rot.unwrap_or(0.0).to_radians().sin_cos(); + // (x, y) → translate(-c) → scale → rotate → translate(c + d). + let (a, b, c, d) = (sx * cos, sx * sin, -sy * sin, sy * cos); + let e = cx + dx.unwrap_or(0.0) - a * cx - c * cy; + let f = cy + dy.unwrap_or(0.0) - b * cx - d * cy; + Ok(Some(Homography([a, c, e, b, d, f, 0.0, 0.0, 1.0]))) +} + +fn quad_param(p: &Value) -> Option<[[f64; 2]; 4]> { + let a = p.get("quad")?.as_array()?; + if a.len() != 4 { + return None; + } + let mut q = [[0.0; 2]; 4]; + for (i, v) in a.iter().enumerate() { + let c = v.as_array()?; + q[i] = [c.first()?.as_f64()?, c.get(1)?.as_f64()?]; + } + Some(q) +} + +/// `p`, with the Channels panel's targeted alpha channel or Quick Mask as its `"target"` when it +/// names neither a target nor a layer (#2835). +fn with_panel_target(s: &Session, p: &Value) -> Value { + let mut p = if p.is_object() { p.clone() } else { json!({}) }; + if p.get("target").is_none() + && p.get("layer").is_none() + && let (Some(m), Some(Value::Object(t))) = (p.as_object_mut(), crate::channel_cmds::targeted_channel(s)) + { + m.extend(t); + } + p +} + +fn transform(s: &mut Session, p: &Value) -> Result { + let p = &with_panel_target(s, p); + let st = s.active().ok_or(EngineError::NoDocument)?; + let id = crate::commands::explicit_layer(s, p)?.or(st.active_layer); + let lone = lone_target(&st.doc, id, p)?; + let id = match (id, lone.is_some() && crate::channel_cmds::is_channel_target(p)) { + (_, true) => None, + (Some(id), false) => Some(id), + (None, false) => return Err(EngineError::Other("no active layer".into())), + }; + let rect = match p.get("rect").and_then(Value::as_array) { + Some(r) if r.len() == 4 => { + let v: Vec = r.iter().map(|x| x.as_f64().unwrap_or(0.0)).collect(); + [v[0], v[1], v[2], v[3]] + } + _ => { + let b = match (lone, id) { + (Some(surf), _) => target_bounds(&st.doc, surf), + (None, Some(id)) => transform_bounds(&st.doc, st.doc.layer(id).ok_or(EngineError::NoLayer(id))?), + (None, None) => Rect::EMPTY, + }; + if b.is_empty() { + return Err(EngineError::Other("nothing to transform".into())); + } + [b.x0 as f64, b.y0 as f64, b.x1 as f64, b.y1 as f64] + } + }; + let h = if let Some(q) = quad_param(p) { + Homography::rect_to_quad(rect, q).ok_or_else(|| bad("degenerate quad"))? + } else if let Some(m) = p.get("matrix").and_then(Value::as_array) { + let v: Vec = m.iter().filter_map(Value::as_f64).collect(); + if v.len() != 6 { + return Err(bad("matrix must be [a, b, c, d, e, f]")); + } + // Affine [a b c d e f] maps (x, y) → (a·x + c·y + e, b·x + d·y + f). + Homography([v[0], v[2], v[4], v[1], v[3], v[5], 0.0, 0.0, 1.0]) + } else if let Some(m) = relative_matrix(p, rect)? { + m + } else { + return Err(bad("pass `quad` (where the rect's corners go), `matrix`, or `scaleX`/`scaleY`/`rotate`/`dx`/`dy`")); + }; + if h.inverse().is_none() { + return Err(bad("the transform collapses the layer")); + } + let m = h.0; + let affine = + (m[6].abs() < 1e-12 && m[7].abs() < 1e-12).then(|| Affine { m: [m[0] / m[8], m[3] / m[8], m[1] / m[8], m[4] / m[8], m[2] / m[8], m[5] / m[8]] }); + let interp = Interp::parse(p.get("interpolation").and_then(Value::as_str).unwrap_or("bicubic")); + let lone = lone.is_some(); + let p = p.clone(); + // A background job when started with `Session::start` (#1015): the warp of a large layer runs + // on a worker with progress, and can be cancelled. + crate::jobs::edit_job( + s, + "Free Transform", + move |doc, _, ctx| ctx.stage(0.0, 1.0, "Transforming", |ctl| transform_doc(doc, id, &p, lone, &h, affine, interp, ctl)), + move |()| json!({"rect": rect}), + ) +} + +/// The edit of [`transform`]: the layer (or a lone mask or channel) and the selection outline. +#[allow(clippy::too_many_arguments)] +fn transform_doc( + doc: &mut Document, + id: Option, + p: &Value, + lone: bool, + h: &Homography, + affine: Option, + interp: Interp, + ctl: &Interrupt, +) -> Result<()> { + let sel = doc.selection.clone(); + // The selection outline moves too: price it before anything is built. + if let Some(sel) = sel.as_ref().filter(|_| !h.is_identity()) { + check_budget(sel.content_bounds(), h, "selection", sel.format())?; + } + if lone { + // A targeted unlinked mask, alpha channel or Quick Mask transforms by itself. + if !h.is_identity() { + let (surf, _) = crate::channel_cmds::target_surface(doc, id, p)?; + let src = sel.as_ref().map_or_else(|| surf.content_bounds(), Surface::content_bounds); + check_budget(src, h, "mask or channel", surf.format())?; + *surf = match &sel { + Some(sel) => warp_gray_selected(surf, sel, h, interp)?, + None => warp_gray(surf, h, interp)?, + }; + if let Some(sel) = &doc.selection { + doc.selection = Some(warp_gray(sel, h, Interp::Bilinear)?).filter(|s| !s.content_bounds().is_empty()); + } + } + return Ok(()); + } + let id = id.ok_or_else(|| EngineError::Other("no active layer".into()))?; + let is_group = doc.layer(id).is_some_and(Layer::is_group); + let group = group_locks(doc, id); + // Photoshop turns the Background into a normal layer before transforming it. + crate::extra_cmds::background_to_layer(doc, id); + let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; + let layer_sel = if is_group { None } else { sel.as_ref() }; + check_layer_budget(layer_sel, l, h)?; + let taken = if h.is_identity() { Vec::new() } else { crate::smart_cmds::take_caches(std::slice::from_mut(l)) }; + apply_transform(layer_sel, group, l, h, affine, interp, ctl)?; + if !h.is_identity() { + // Type layers re-render from their new transform. + let snapshot = doc.clone(); + if let Some(l) = doc.layer_mut(id) { + refresh_text(&snapshot, l); + } + crate::smart_cmds::restore_unrendered(doc, taken, |c| warp_surface(c, c.content_bounds(), h, interp))?; + // The selection outline moves with the pixels. + if let Some(sel) = &doc.selection { + doc.selection = Some(warp_gray(sel, h, Interp::Bilinear)?).filter(|s| !s.content_bounds().is_empty()); + } + } + Ok(()) +} + +pub fn specs() -> Vec { + vec![CommandSpec { + id: "edit.transform", + label: "Free Transform", + menu: &[], + shortcut: None, + params: r##"{"layer":id?,"rect":[x0,y0,x1,y1]? (source frame; default = layer content ∩ selection),"quad":[[x,y]×4]? (where the frame's corners go, clockwise from top-left),"matrix":[a,b,c,d,e,f]? (affine alternative),"scaleX":%?,"scaleY":%?,"rotate":deg?,"dx":px?,"dy":px? (relative alternative: scale and rotate about the frame's centre, then move, as a Photoshop action records a Free Transform),"interpolation":"bicubic|bilinear|nearest|bicubicSharper|bicubicSmoother|bicubicAutomatic"="bicubic" (Photoshop's bicubic variants render as Bicubic),"target":"pixels"|"mask"|"quickMask"|{"channel":i}=Channels panel target (an unlinked mask, an alpha channel or the Quick Mask transforms alone; a linked mask moves with its layer)}"##, + enabled: has_layer, + journal: true, + run: transform, + }] +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/transform_cmds/tests.rs b/crates/engine/src/cmd/transform_cmds/tests.rs new file mode 100644 index 0000000000..f8ff204257 --- /dev/null +++ b/crates/engine/src/cmd/transform_cmds/tests.rs @@ -0,0 +1,910 @@ +use super::*; + +fn session() -> Session { + session_depth(8) +} + +fn session_depth(depth: u32) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 100, "height": 100, "depth": depth})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.edit("paint", |doc, active| { + let l = doc.layer_mut(active.unwrap()).unwrap(); + l.surface_mut().unwrap().fill_rect(Rect::new(10, 10, 30, 20), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + s +} + +/// The content bounds of the active layer's pixels. +fn active_bounds(s: &Session) -> Rect { + let st = s.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds() +} + +// ---- Memory budget (#3773, #7807). Tests run with a 20 MB budget (2²⁰ px of 32-bit CMYK with +// alpha), so nothing here comes near the real one. ---- + +/// Memory Usage's default, in bytes. +const DEFAULT_BUDGET: u64 = (crate::prefs::DEFAULT_MEMORY_USAGE_MB as u64) << 20; + +/// Scales of 10⁷ and past are refused by the real budget too, whatever the axis or sign. +#[test] +fn huge_transform_scales_exceed_the_production_budget_before_clipping() { + let src = Rect::new(0, 0, 24, 16); + for scale in [1e7, 1e28, 1e306] { + for (sx, sy) in [(scale, 1.0), (1.0, scale), (-scale, 1.0)] { + let h = Homography([sx, 0.0, 0.0, 0.0, sy, 0.0, 0.0, 0.0, 1.0]); + assert!(check_budget_with_limit(src, &h, "layer", PixelFormat::RGBA8, DEFAULT_BUDGET).is_err(), "{sx} x {sy} must be refused"); + } + } +} + +/// A 240000 px wide stretch, placed far from the canvas but within the warp's reach, fits. +#[test] +fn an_ordinary_transform_remains_within_the_production_budget() { + let src = Rect::new(0, 0, 24, 16); + let h = Homography([10_000.0, 0.0, 800_000.0, 0.0, 1.0, -900_000.0, 0.0, 0.0, 1.0]); + assert!(check_budget_with_limit(src, &h, "layer", PixelFormat::RGBA8, DEFAULT_BUDGET).is_ok()); +} + +/// The warp places pixels only within ±2²⁰ px ([`WARP_REACH`]): a result that fits Memory +/// Usage but would reach past it, by its size or by where it lands, is refused, not clipped. +#[test] +fn a_result_past_the_warps_reach_is_refused_not_clipped() { + let src = Rect::new(0, 0, 24, 16); + let check = |h: [f64; 9]| check_budget_with_limit(src, &Homography(h), "layer", PixelFormat::RGBA8, DEFAULT_BUDGET); + // 2000016 x 18 px, 138 MB of 8-bit RGBA: from x = 0 it would be cut at 2²⁰; centred it fits. + let err = check([83_334.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]).unwrap_err().to_string(); + assert!(err.contains("would reach past ±1048576 px") && err.ends_with("the document was not changed"), "{err}"); + assert!(check([83_334.0, 0.0, -1_000_000.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]).is_ok()); + // A small layer moved past the reach, either way on either axis. + for (dx, dy) in [(1_100_000.0, 0.0), (-1_100_000.0, 0.0), (0.0, 1_100_000.0), (0.0, -1_100_000.0)] { + assert!(check([1.0, 0.0, dx, 0.0, 1.0, dy, 0.0, 0.0, 1.0]).is_err(), "{dx}, {dy}"); + } + // Through the command: nothing moves, nothing is lost. + let mut s = session(); + let st = s.active().unwrap(); + let (before, steps) = (st.doc.clone(), st.history.past_len()); + let err = s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 2_000_000, 0]})).unwrap_err().to_string(); + assert!(err.contains("the transformed layer \"Layer 1\" would reach past ±1048576 px"), "{err}"); + let st = s.active().unwrap(); + assert!(st.doc == before && st.history.past_len() == steps, "the document is untouched"); +} + +/// #7807: the stitched layer's 90 % and 15°, a 37708 x 35259 px result that the old 2³⁰ px limit +/// refused, fits the default Memory Usage at 8 bits (5072 MB); at 16 bits it needs Memory Usage +/// raised, and the message says so. +#[test] +fn a_gigapixel_layer_transforms_within_memory_usage() { + let src = Rect::new(0, 0, 35_020, 31_171); + let r = [0.0, 0.0, 35_020.0, 31_171.0]; + let h = relative_matrix(&json!({"scaleX": 90, "scaleY": 90, "rotate": 15}), r).unwrap().unwrap(); + assert_eq!(warp_output_size(src, &h), Some((37_708, 35_259)), "the report's result, past the old limit"); + assert!(check_budget_with_limit(src, &h, "layer \"Layer 1\"", PixelFormat::RGBA8, DEFAULT_BUDGET).is_ok()); + let err = check_budget_with_limit(src, &h, "layer \"Layer 1\"", PixelFormat::RGBA16, DEFAULT_BUDGET).unwrap_err().to_string(); + assert!(err.contains("(10144 MB), more than the 8192 MB Memory Usage allows (Preferences › Performance)"), "{err}"); + assert!(check_budget_with_limit(src, &h, "layer", PixelFormat::RGBA16, 2 * DEFAULT_BUDGET).is_ok()); + // A format without alpha is priced as the warp makes it, with alpha. + let rgb8 = PixelFormat::new(PixelFormat::RGBA8.mode, PixelFormat::RGBA8.sample, false); + assert!(check_budget_with_limit(src, &h, "layer", rgb8, 5071 << 20).is_err()); +} + +/// A 16 x 16 document whose active layer is a 1 x 8 column at x = 10. +fn column() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.edit("paint", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(10, 2, 11, 10), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + s +} + +/// Stretch x by `k` about x = 10 (the column's left edge). +fn stretch(k: f64) -> Value { + json!({"matrix": [k, 0, 0, 1, -10.0 * k, 0], "interpolation": "nearest"}) +} + +/// A stretch past the budget is refused with the limit named, and the document, its revision +/// and History stay as they were; within the budget the same stretch applies unclipped. +#[test] +fn a_scale_past_the_pixel_budget_is_refused_and_changes_nothing() { + let mut s = column(); + let st = s.active().unwrap(); + let (before, revision, steps) = (st.doc.clone(), st.revision, st.history.past_len()); + // 1000000 x 10 px of 8-bit RGBA output: about twice the test budget. + let err = s.execute("edit.transform", stretch(1e6)).unwrap_err().to_string(); + assert!(err.starts_with("too large to transform: the transformed layer \"Layer 1\""), "{err}"); + assert!( + err.contains("would be 1000002 x 10 px (39 MB), more than the 20 MB Memory Usage allows") && err.ends_with("the document was not changed"), + "{err}" + ); + // Nothing was allocated, so nothing ran short (#7807). + assert!(!err.contains("not enough memory"), "{err}"); + let st = s.active().unwrap(); + assert!(st.doc == before, "the document is untouched"); + assert_eq!((st.revision, st.history.past_len()), (revision, steps)); + // Within the budget the same stretch still works, nothing clipped. + s.execute("edit.transform", stretch(1e4)).unwrap(); + assert_eq!(active_bounds(&s), Rect::new(0, 2, 10_000, 10)); +} + +#[test] +fn a_group_with_one_layer_past_the_budget_is_not_half_transformed() { + let mut s = column(); + let wide = s.active().unwrap().active_layer.unwrap(); + // Over the column: a 1 px dot, which fits the budget stretched by the same amount. + s.execute("layer.new.layer", json!({})).unwrap(); + let dot = s.active().unwrap().active_layer.unwrap(); + s.edit("paint", |doc, _| { + doc.layer_mut(dot).unwrap().surface_mut().unwrap().fill_rect(Rect::new(10, 12, 11, 13), &[0.0, 1.0, 0.0, 1.0]); + // Widen the column to 8 px (x 2..10), so it alone needs 800002 x 10 px (31 MB). + doc.layer_mut(wide).unwrap().surface_mut().unwrap().fill_rect(Rect::new(2, 2, 10, 10), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + s.execute("layer.select", json!({"layer": wide.0})).unwrap(); + s.execute("layer.select", json!({"layer": dot.0, "mode": "add"})).unwrap(); + let group = LayerId(s.execute("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap()); + let st = s.active().unwrap(); + assert!(matches!(&st.doc.layer(group).unwrap().content, LayerContent::Group(g) if g.children.len() == 2)); + let (before, revision) = (st.doc.clone(), st.revision); + let k = 1e5; + assert!(s.execute("edit.transform", json!({"layer": group.0, "matrix": [k, 0, 0, 1, -10.0 * k, 0]})).is_err()); + let st = s.active().unwrap(); + assert!(st.doc == before && st.revision == revision, "nothing changed"); + // The layer-level check runs before any child is warped, so even the layer itself + // (not just the edit's copy of the document) is left as it was. + let mut l = st.doc.layer(group).unwrap().clone(); + let h = Homography([k, 0.0, -10.0 * k, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]); + assert!(transform_layer(None, Locks::default(), &mut l, &h, None, Interp::Nearest).is_err()); + assert!(&l == st.doc.layer(group).unwrap(), "no child was transformed"); +} + +/// Only the result's size is priced: a small layer moved 900000 px away (within the warp's +/// reach) and back keeps every pixel. +#[test] +fn moving_a_small_layer_far_off_the_canvas_is_within_budget() { + let mut s = session(); + s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 900_000, -900_000]})).unwrap(); + assert_eq!(active_bounds(&s), Rect::new(900_010, -899_990, 900_030, -899_980)); + s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, -900_000, 900_000]})).unwrap(); + assert_eq!(active_bounds(&s), Rect::new(10, 10, 30, 20), "and back, every pixel kept"); +} + +/// Each priced at its own format, as the warp makes it: an 8-bit outline, mask or channel with +/// alpha is 2 bytes a pixel, so a canvas-high column of it stretched 10⁶ times (34 MB) is over +/// the test budget. +#[test] +fn selections_masks_and_channels_have_the_same_budget() { + // The selection outline of a layer transform. + let mut s = column(); + s.execute("select.rect", json!({"x": 10, "y": 0, "width": 1, "height": 16})).unwrap(); + let before = s.active().unwrap().doc.clone(); + let err = s.execute("edit.transform", stretch(1e6)).unwrap_err().to_string(); + assert!(err.contains("transformed selection would be"), "{err}"); + // Transform Selection. + let err = s.execute("select.transformSelection", stretch(1e6)).unwrap_err().to_string(); + assert!(err.contains("transformed selection would be"), "{err}"); + assert!(s.active().unwrap().doc == before); + // A targeted alpha channel. + let mut s = column(); + s.execute("channel.new", json!({})).unwrap(); + s.edit("paint channel", |doc, _| { + doc.channels[0].surface.fill_rect(Rect::new(10, 0, 11, 16), &[1.0]); + Ok(()) + }) + .unwrap(); + let before = s.active().unwrap().doc.clone(); + let mut p = stretch(1e6); + p["target"] = json!({"channel": 0}); + let err = s.execute("edit.transform", p).unwrap_err().to_string(); + assert!(err.contains("transformed mask or channel would be"), "{err}"); + assert!(s.active().unwrap().doc == before); +} + +#[test] +fn scale_via_quad_and_undo() { + let mut s = session(); + s.execute("edit.transform", json!({"quad": [[10, 10], [50, 10], [50, 30], [10, 30]]})).unwrap(); + let b = active_bounds(&s); + assert!(b.width().abs_diff(40) <= 2 && b.height().abs_diff(20) <= 2, "{b:?}"); + s.undo(); + assert_eq!(active_bounds(&s), Rect::new(10, 10, 30, 20)); +} + +#[test] +fn affine_matrix_and_perspective() { + let mut s = session(); + // Translate by (40, 50). + s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 40, 50]})).unwrap(); + assert_eq!(active_bounds(&s), Rect::new(50, 60, 70, 70)); + // Perspective: top edge narrower than the bottom. + s.execute("edit.transform", json!({"quad": [[55, 60], [65, 60], [75, 70], [45, 70]]})).unwrap(); + let b = active_bounds(&s); + assert!(b.x0 <= 46 && b.x1 >= 74, "{b:?}"); + assert!(s.execute("edit.transform", json!({"quad": [[0, 0], [0, 0], [0, 0], [0, 0]]})).is_err()); +} + +#[test] +fn background_becomes_layer_0() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 40, "height": 40})).unwrap(); + s.execute("edit.transform", json!({"quad": [[0, 0], [20, 0], [20, 20], [0, 20]]})).unwrap(); + let st = s.active().unwrap(); + let l = &st.doc.layers[0]; + assert_eq!(l.name, "Layer 0"); + assert!(l.surface().unwrap().format().alpha); + assert_eq!(l.surface().unwrap().pixel(30, 30)[3], 0.0, "revealed area is transparent"); +} + +/// `locked_for_transform` (what Free Transform asks before its box opens, #2585) agrees with +/// what `edit.transform` refuses at commit: a position lock, its own or a group's; never the +/// Background's (it becomes Layer 0). +#[test] +fn locked_for_transform_matches_the_commit() { + let quad = json!({"quad": [[10, 10], [50, 10], [50, 30], [10, 30]]}); + let lock = |s: &mut Session, id: LayerId, on: bool| { + s.edit("lock", |doc, _| { + doc.layer_mut(id).unwrap().locks.position = on; + Ok(()) + }) + .unwrap(); + }; + let mut s = session(); + let layer = s.active().unwrap().active_layer.unwrap(); + lock(&mut s, layer, true); + assert!(locked_for_transform(&s.active().unwrap().doc, layer)); + assert!(s.execute("edit.transform", quad.clone()).is_err()); + lock(&mut s, layer, false); + let group = LayerId(s.execute("layer.groupLayers", json!({"layer": layer.0})).unwrap()["layer"].as_u64().unwrap()); + lock(&mut s, group, true); + s.execute("layer.select", json!({"layer": layer.0})).unwrap(); + assert!(locked_for_transform(&s.active().unwrap().doc, layer), "the group's lock reaches the layer"); + assert!(s.execute("edit.transform", quad.clone()).is_err()); + let bg = s.active().unwrap().doc.layers[0].id; + assert!(!locked_for_transform(&s.active().unwrap().doc, bg), "the Background transforms"); +} + +#[test] +fn with_selection_only_selected_pixels_move() { + let mut s = session(); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); + s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 0, 50]})).unwrap(); + let st = s.active().unwrap(); + let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); + assert_eq!(surf.pixel(15, 15)[3], 0.0, "lifted area is cleared"); + assert_eq!(surf.pixel(25, 15)[3], 1.0, "unselected part stays"); + assert_eq!(surf.pixel(15, 65)[3], 1.0, "moved pixels land"); + let sel = st.doc.selection.as_ref().unwrap().content_bounds(); + assert_eq!((sel.y0, sel.y1), (60, 70), "selection moves too"); +} + +#[test] +fn with_selection_bounds_drop_the_vacated_area() { + // #1097: moving every pixel through a selection left transparent but coloured pixels + // behind, so the layer bounds were the union of the old and new positions. + let mut s = session(); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 20, "height": 10})).unwrap(); + s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 50, 0]})).unwrap(); + assert_eq!(active_bounds(&s), Rect::new(60, 10, 80, 20)); +} + +#[test] +fn type_layers_transform_as_vectors() { + let mut s = session(); + let r = s.execute("type.create", json!({"x": 10, "y": 50, "text": "Hi", "size": 20})).unwrap(); + let id = r["layer"].as_u64().unwrap(); + let w0 = active_bounds(&s).width(); + s.execute("edit.transform", json!({"layer": id, "matrix": [2, 0, 0, 2, -10, -50]})).unwrap(); + let w1 = active_bounds(&s).width(); + assert!(w1 as f32 > w0 as f32 * 1.8, "{w0} → {w1}"); + let st = s.active().unwrap(); + let LayerContent::Text(t) = &st.doc.layer(LayerId(id)).unwrap().content else { panic!() }; + assert!((t.transform.m[0] - 2.0).abs() < 1e-9); + // Perspective on type is refused, like Photoshop. + assert!(s.execute("edit.transform", json!({"layer": id, "quad": [[0, 0], [10, 0], [12, 10], [-2, 10]]})).is_err()); +} + +#[test] +fn shapes_move_and_transform_as_vectors() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); + s.execute("shape.create", json!({"kind": "rect", "rect": [10, 10, 40, 20], "fill": "#ff0000"})).unwrap(); + s.execute("layer.translate", json!({"dx": 30, "dy": 5})).unwrap(); + assert_eq!(active_bounds(&s), Rect::new(40, 15, 80, 35)); + s.execute("edit.transform", json!({"matrix": [2, 0, 0, 2, -40, -15]})).unwrap(); + assert_eq!(active_bounds(&s), Rect::new(40, 15, 120, 55)); + // Distort maps the path and keeps a live shape (#3009): the rectangle's corners go to the quad. + let quad = [[40.0, 15.0], [120.0, 15.0], [130.0, 55.0], [30.0, 55.0]]; + s.execute("edit.transform", json!({ "quad": quad })).unwrap(); + let st = s.active().unwrap(); + let LayerContent::Shape(sh) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!("still a shape layer") }; + let mut anchors: Vec<[f64; 2]> = sh.path.subpaths[0].knots.iter().map(|k| [k.anchor.x, k.anchor.y]).collect(); + let mut want = quad.to_vec(); + anchors.sort_by(|a, b| a.partial_cmp(b).unwrap()); + want.sort_by(|a, b| a.partial_cmp(b).unwrap()); + assert!(anchors.iter().zip(&want).all(|(a, b)| (a[0] - b[0]).abs() < 1e-6 && (a[1] - b[1]).abs() < 1e-6), "{anchors:?}"); + assert!(sh.live.is_none(), "the live rectangle is now a path"); + assert_eq!(active_bounds(&s), Rect::new(30, 15, 130, 55)); + // Warp bends the path too: the arc adds anchors along the curved edges. + s.execute("edit.transform.warp", json!({"style": "arc", "bend": 50})).unwrap(); + let st = s.active().unwrap(); + let LayerContent::Shape(sh) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!("still a shape layer") }; + assert!(sh.path.subpaths[0].knots.len() > 4, "{}", sh.path.subpaths[0].knots.len()); + assert!(!active_bounds(&s).is_empty()); +} + +/// A gradient fill layer whose mask (a selection when it was made) frames the gradient over +/// 10..40, with the cached render a PSD import gives it: exactly the pixels the fill renders. +fn cached_gradient_fill() -> Session { + let mut s = session(); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap(); + s.execute("layer.newFillLayer.gradient", json!({"from": "#ff0000", "to": "#0000ff", "angle": 0})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s.edit("cache", |doc, active| { + let (fmt, canvas) = (doc.pixel_format(), doc.bounds()); + let l = doc.layer_mut(active.unwrap()).unwrap(); + let LayerContent::Fill(f) = &l.content else { panic!("a fill layer") }; + let buf = photocraft_compose::render_fill_content(l, f, canvas, &[]); + let mut surface = Surface::new(fmt); + let vals: Vec = buf.px.iter().flat_map(|p| photocraft_raster::from_rgba(&fmt, *p)).collect(); + surface.write_region(canvas, &vals); + l.fill_cache = Some(photocraft_doc::FillCache { fill: f.clone(), surface }); + Ok(()) + }) + .unwrap(); + s +} + +/// How far the composite is from the composite with the fill re-rendered from its model +/// (cache dropped): the largest channel difference. +fn off_from_fresh(s: &Session) -> f32 { + let st = s.active().unwrap(); + let mut fresh: Document = (*st.doc).clone(); + fresh.layer_mut(st.active_layer.unwrap()).unwrap().fill_cache = None; + let (a, b) = (photocraft_compose::render(&st.doc, st.doc.bounds()).px, photocraft_compose::render(&fresh, fresh.bounds()).px); + a.iter().zip(&b).flat_map(|(p, q)| p.iter().zip(q).map(|(x, y)| (x - y).abs())).fold(0.0, f32::max) +} + +#[test] +fn transforming_a_fill_layer_drops_its_stale_cached_render() { + let mut s = cached_gradient_fill(); + let off = off_from_fresh(&s); + assert!(off < 0.01, "the cache is the fill's own render: {off}"); + // The mask (and so the gradient's frame) moves 50 px right and doubles in height. + s.execute("edit.transform", json!({"matrix": [1, 0, 0, 2, 50, 0]})).unwrap(); + let off = off_from_fresh(&s); + assert!(off < 0.01, "the composite shows the fill laid out in its new frame, not the old render: {off}"); +} + +#[test] +fn warping_a_fill_layer_drops_its_stale_cached_render() { + let mut s = cached_gradient_fill(); + s.execute("edit.transform.warp", json!({"style": "arc", "bend": 50})).unwrap(); + let off = off_from_fresh(&s); + assert!(off < 0.01, "the composite shows the fill laid out in its new frame, not the old render: {off}"); +} + +#[test] +fn type_moves_with_the_move_command() { + let mut s = session(); + s.execute("type.create", json!({"x": 10, "y": 50, "text": "Hi", "size": 20})).unwrap(); + let b0 = active_bounds(&s); + s.execute("layer.translate", json!({"dx": 20, "dy": 10})).unwrap(); + let b1 = active_bounds(&s); + assert_eq!((b1.x0 - b0.x0, b1.y0 - b0.y0), (20, 10)); +} + +// ---- Layer masks and targets (#205) ---- + +/// `session()` plus a reveal-all mask with `hide` painted black (linked unless `linked` is false). +fn masked(hide: &[Rect], linked: bool) -> Session { + masked_depth(hide, linked, 8) +} + +fn masked_depth(hide: &[Rect], linked: bool, depth: u32) -> Session { + let mut s = session_depth(depth); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + s.edit("mask", |doc, active| { + let m = doc.layer_mut(active.unwrap()).unwrap().mask.as_mut().unwrap(); + for r in hide { + m.surface.fill_rect(*r, &[0.0]); + } + m.linked = linked; + Ok(()) + }) + .unwrap(); + s +} + +fn mask_at(s: &Session, x: i32, y: i32) -> f32 { + let st = s.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().mask.as_ref().unwrap().surface.sample_channel(x, y, 0) +} + +fn alpha_at(s: &Session, x: i32, y: i32) -> f32 { + let st = s.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().pixel(x, y)[3] +} + +#[test] +fn linked_raster_mask_moves_with_the_pixels() { + let mut s = masked(&[Rect::new(10, 10, 20, 20)], true); + s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 40, 50]})).unwrap(); + assert_eq!(active_bounds(&s), Rect::new(50, 60, 70, 70)); + assert!(mask_at(&s, 55, 65) < 0.01, "the hidden half moved with the pixels"); + assert!(mask_at(&s, 65, 65) > 0.99); + assert!(mask_at(&s, 15, 15) > 0.99, "nothing hidden left behind"); +} + +#[test] +fn linked_mask_with_a_selection_moves_only_the_selected_region() { + // The selection covers the left half of the red rect; the mask hides its left quarter + // (selected) and its right quarter (not selected). + let mut s = masked(&[Rect::new(10, 10, 15, 20), Rect::new(25, 10, 30, 20)], true); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); + s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 0, 50]})).unwrap(); + // Moved pixels and their mask line up. + assert_eq!(alpha_at(&s, 12, 65), 1.0); + assert!(mask_at(&s, 12, 65) < 0.01, "selected hidden quarter moved"); + assert!(mask_at(&s, 17, 65) > 0.99, "selected visible quarter moved"); + // The vacated area reads as revealed (default), with transparent pixels. + assert_eq!(alpha_at(&s, 12, 15), 0.0); + assert!(mask_at(&s, 12, 15) > 0.99); + // The unselected part of the mask stays, aligned with the unselected pixels. + assert_eq!(alpha_at(&s, 27, 15), 1.0); + assert!(mask_at(&s, 27, 15) < 0.01, "unselected mask stays put"); + assert!(mask_at(&s, 27, 65) > 0.99, "and isn't copied along"); + // Every pixel's mask value is where it was relative to the pixel. + for (x, y) in [(11, 61), (14, 69), (15, 61), (19, 69)] { + let want = if x < 15 { 0.0 } else { 1.0 }; + assert!((mask_at(&s, x, y) - want).abs() < 0.01, "({x},{y})"); + } +} + +#[test] +fn unlinked_mask_stays_put() { + let mut s = masked(&[Rect::new(10, 10, 20, 20)], false); + s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 40, 50]})).unwrap(); + assert_eq!(active_bounds(&s), Rect::new(50, 60, 70, 70)); + assert!(mask_at(&s, 15, 15) < 0.01); + assert!(mask_at(&s, 55, 65) > 0.99); + // With a selection too. + let mut s = masked(&[Rect::new(10, 10, 20, 20)], false); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); + s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 0, 50]})).unwrap(); + assert!(mask_at(&s, 15, 15) < 0.01 && mask_at(&s, 15, 65) > 0.99); +} + +#[test] +fn targeted_unlinked_mask_transforms_alone() { + let mut s = masked(&[Rect::new(10, 10, 20, 20)], false); + s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 40, 50], "target": "mask"})).unwrap(); + assert_eq!(active_bounds(&s), Rect::new(10, 10, 30, 20), "pixels untouched"); + assert!(mask_at(&s, 55, 65) < 0.01, "mask moved"); + assert!(mask_at(&s, 15, 15) > 0.99, "vacated area reads as the default"); + s.undo(); + assert!(mask_at(&s, 15, 15) < 0.01, "one undo step"); + // With a selection, only its part of the mask. + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 5, "height": 10})).unwrap(); + s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 0, 50], "target": "mask"})).unwrap(); + assert!(mask_at(&s, 12, 65) < 0.01 && mask_at(&s, 12, 15) > 0.99); + assert!(mask_at(&s, 17, 15) < 0.01, "unselected mask stays"); + assert_eq!(active_bounds(&s), Rect::new(10, 10, 30, 20), "pixels untouched"); +} + +#[test] +fn targeted_linked_mask_moves_with_its_layer() { + // Photoshop: a linked mask can't move without its layer. + let mut s = masked(&[Rect::new(10, 10, 20, 20)], true); + s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 40, 50], "target": "mask"})).unwrap(); + assert_eq!(active_bounds(&s), Rect::new(50, 60, 70, 70)); + assert!(mask_at(&s, 55, 65) < 0.01); +} + +#[test] +fn targeted_alpha_channel_transforms_alone() { + let mut s = session(); + s.execute("channel.new", json!({})).unwrap(); + s.edit("paint channel", |doc, _| { + doc.channels[0].surface.fill_rect(Rect::new(10, 10, 20, 20), &[1.0]); + Ok(()) + }) + .unwrap(); + s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 40, 50], "target": {"channel": 0}})).unwrap(); + let st = s.active().unwrap(); + let ch = &st.doc.channels[0].surface; + assert!(ch.sample_channel(55, 65, 0) > 0.99 && ch.sample_channel(15, 15, 0) < 0.01); + assert_eq!(active_bounds(&s), Rect::new(10, 10, 30, 20), "layer untouched"); +} + +/// The Channels panel targets an alpha channel: Edit › Transform › Flip Horizontal and a +/// 50% `edit.transform` (no `target` param) work on the channel, not the layer (BUG-207-4). +#[test] +fn transforms_follow_the_targeted_alpha_channel() { + let mut s = session(); + s.execute("channel.new", json!({})).unwrap(); + s.edit("paint channel", |doc, _| { + let ch = &mut doc.channels[0].surface; + ch.fill_rect(Rect::new(10, 10, 20, 20), &[1.0]); + ch.fill_rect(Rect::new(10, 10, 12, 20), &[0.5]); + Ok(()) + }) + .unwrap(); + s.execute("channel.target", json!({"channel": 0})).unwrap(); + let layer = |s: &Session| crate::active_layer_of(s).unwrap().surface().unwrap().read_region(Rect::new(0, 0, 100, 100)); + let (pixels, past) = (layer(&s), s.active().unwrap().history.past_len()); + s.execute("edit.transform.flipHorizontal", json!({})).unwrap(); + // 8-bit channel: 0.5 is stored as 128/255. + let ch = |s: &Session, x, y| (s.active().unwrap().doc.channels[0].surface.sample_channel(x, y, 0) * 10.0).round() / 10.0; + assert_eq!((ch(&s, 19, 15), ch(&s, 10, 15)), (0.5, 1.0), "the channel flips within its frame"); + assert!(layer(&s) == pixels, "the layer is untouched"); + assert_eq!(s.active().unwrap().history.past_len(), past + 1, "one undo step"); + s.execute("edit.transform", json!({"matrix": [0.5, 0, 0, 0.5, 0, 0], "interpolation": "nearest"})).unwrap(); + assert_eq!((ch(&s, 7, 7), ch(&s, 15, 15)), (1.0, 0.0), "the channel scales to 50%"); + assert!(layer(&s) == pixels, "the layer is untouched"); + s.undo(); + s.undo(); + assert_eq!((ch(&s, 10, 15), ch(&s, 19, 15)), (0.5, 1.0)); +} + +#[test] +fn transform_targets_fail_gracefully() { + let mut s = session(); + let m = json!([1, 0, 0, 1, 5, 5]); + assert!(s.execute("edit.transform", json!({"matrix": m, "target": "mask"})).is_err(), "no mask"); + assert!(s.execute("edit.transform", json!({"matrix": m, "target": {"channel": 9}})).is_err()); + assert!(s.execute("edit.transform", json!({"matrix": m, "target": "quickMask"})).is_err()); + // Unknown target shapes fall back to the pixels. + s.execute("edit.transform", json!({"matrix": m, "target": 7})).unwrap(); + s.execute("edit.transform", json!({"matrix": m, "target": {"channel": "x"}})).unwrap(); + // Selections that miss the mask entirely transform nothing, without panicking. + let mut s = masked(&[Rect::new(10, 10, 20, 20)], false); + s.execute("select.rect", json!({"x": 80, "y": 80, "width": 5, "height": 5})).unwrap(); + let _ = s.execute("edit.transform", json!({"matrix": [1e9, 0, 0, 1e9, 0, 0], "target": "mask"})); + let _ = s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 1e12, 0], "target": "mask"})); +} + +#[test] +fn split_gray_selected_rejects_non_gray() { + let s = Surface::new(PixelFormat::RGBA8); + let mut sel = Surface::new(PixelFormat::GRAY8); + sel.fill_rect(Rect::new(0, 0, 4, 4), &[1.0]); + assert!(matches!(split_gray_selected(&s, &sel), Ok(None))); +} + +/// #2630: type can't be partly transformed, so a selection doesn't narrow the frame: Free +/// Transform (and the frame-based presets) act on the whole type layer. +#[test] +fn a_selection_does_not_narrow_a_type_layers_frame() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 200, "height": 120})).unwrap(); + s.execute("type.create", json!({"x": 20, "y": 60, "text": "Hello", "size": 36})).unwrap(); + let whole = active_bounds(&s); + s.execute("select.rect", json!({"x": whole.x0, "y": whole.y0, "width": whole.width() / 2, "height": whole.height()})).unwrap(); + let st = s.active().unwrap(); + let l = st.doc.layer(st.active_layer.unwrap()).unwrap(); + assert_eq!(transform_bounds(&st.doc, l), whole, "the frame is the whole type layer"); + // Corners of the frame moved 10 px right: a pure translation of the whole text. + let q = [[whole.x0 + 10, whole.y0], [whole.x1 + 10, whole.y0], [whole.x1 + 10, whole.y1], [whole.x0 + 10, whole.y1]]; + s.execute("edit.transform", json!({"quad": q})).unwrap(); + let moved = active_bounds(&s); + assert!(moved.x0.abs_diff(whole.x0 + 10) <= 1 && moved.width().abs_diff(whole.width()) <= 1, "{whole:?} -> {moved:?}"); + // Rotate 180° turns it about its own centre, not the selection's. + s.execute("edit.transform.rotate180", json!({})).unwrap(); + let turned = active_bounds(&s); + assert!(turned.x0.abs_diff(moved.x0) <= 2 && turned.x1.abs_diff(moved.x1) <= 2, "{moved:?} -> {turned:?}"); + // A pixel layer still frames only the selected pixels. + let mut s = session(); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 5, "height": 10})).unwrap(); + let st = s.active().unwrap(); + assert_eq!(transform_bounds(&st.doc, st.doc.layer(st.active_layer.unwrap()).unwrap()), Rect::new(10, 10, 15, 20)); +} + +/// #5297: the box Free Transform opens with a selection is the selection's own rectangle, +/// not the part of it the layer fills; type still moves whole, and a selection that holds none +/// of the layer leaves nothing to transform. +#[test] +fn the_frame_is_the_selections_own_bounds() { + let mut s = session(); + let frame = |s: &Session| { + let st = s.active().unwrap(); + let l = st.doc.layer(st.active_layer.unwrap()).unwrap(); + (transform_frame(&st.doc, l), transform_bounds(&st.doc, l)) + }; + let content = Rect::new(10, 10, 30, 20); + assert_eq!(frame(&s), (content, content), "no selection: the content"); + s.execute("select.rect", json!({"x": 5, "y": 5, "width": 15, "height": 40})).unwrap(); + assert_eq!(frame(&s), (Rect::new(5, 5, 20, 45), Rect::new(10, 10, 20, 20))); + s.execute("select.rect", json!({"x": 60, "y": 60, "width": 10, "height": 10})).unwrap(); + assert!(frame(&s).0.is_empty(), "nothing of the layer is selected"); + + let mut s = Session::new(); + s.execute("file.new", json!({"width": 200, "height": 120})).unwrap(); + s.execute("type.create", json!({"x": 20, "y": 60, "text": "Hello", "size": 36})).unwrap(); + let whole = active_bounds(&s); + s.execute("select.rect", json!({"x": whole.x0, "y": whole.y0, "width": whole.width() / 2, "height": whole.height()})).unwrap(); + assert_eq!(frame(&s), (whole, whole), "type moves whole"); +} + +#[test] +fn group_transform_ignores_selections_inside_its_children() { + group_transform_with_selection(Rect::new(10, 10, 15, 15)); +} + +#[test] +fn group_transform_ignores_selections_outside_its_children() { + group_transform_with_selection(Rect::new(70, 70, 80, 80)); +} + +#[test] +fn group_transform_presets_rotate_about_the_whole_group() { + for depth in [8, 16, 32] { + for x in [10, 70] { + let mut s = masked_depth(&[Rect::new(10, 10, 15, 20)], true, depth); + let child = s.active().unwrap().active_layer.unwrap(); + s.execute("layer.groupLayers", json!({})).unwrap(); + s.execute("select.rect", json!({"x": x, "y": 10, "width": 5, "height": 5})).unwrap(); + s.execute("edit.transform.rotate180", json!({})).unwrap(); + let layer = s.active().unwrap().doc.layer(child).unwrap(); + assert_eq!(layer.surface().unwrap().content_bounds(), Rect::new(10, 10, 30, 20), "rotate about the group's centre, not the selection's"); + let mask = &layer.mask.as_ref().unwrap().surface; + assert_eq!(mask.sample_channel(27, 15, 0), 0.0); + assert_eq!(mask.sample_channel(12, 15, 0), 1.0); + } + } +} + +fn group_transform_with_selection(selection: Rect) { + for depth in [8, 16, 32] { + for nested in [false, true] { + let mut s = masked_depth(&[Rect::new(10, 10, 15, 20)], true, depth); + let child = s.active().unwrap().active_layer.unwrap(); + s.execute("layer.groupLayers", json!({})).unwrap(); + if nested { + s.execute("layer.groupLayers", json!({})).unwrap(); + } + s.execute("select.rect", json!({"x": selection.x0, "y": selection.y0, "width": selection.width(), "height": selection.height()})).unwrap(); + let steps = s.active().unwrap().history.entries().len(); + let result = s.execute("edit.transform", json!({"quad": [[10, 10], [50, 10], [50, 30], [10, 30]], "interpolation": "nearest"})).unwrap(); + assert_eq!(result["rect"], json!([10.0, 10.0, 30.0, 20.0]), "frame must include the whole group (nested={nested})"); + let st = s.active().unwrap(); + let layer = st.doc.layer(child).unwrap(); + assert_eq!(layer.surface().unwrap().content_bounds(), Rect::new(10, 10, 50, 30)); + let mask = &layer.mask.as_ref().unwrap().surface; + assert_eq!(mask.sample_channel(19, 20, 0), 0.0, "the linked mask scales with its complete layer"); + assert_eq!(mask.sample_channel(21, 20, 0), 1.0); + assert_eq!(st.history.entries().len(), steps + 1); + assert!(s.undo()); + let st = s.active().unwrap(); + let layer = st.doc.layer(child).unwrap(); + assert_eq!(layer.surface().unwrap().content_bounds(), Rect::new(10, 10, 30, 20)); + assert_eq!(layer.mask.as_ref().unwrap().surface.sample_channel(19, 15, 0), 1.0); + assert_eq!(st.doc.selection.as_ref().unwrap().content_bounds(), selection); + assert!(s.redo()); + assert_eq!(s.active().unwrap().doc.layer(child).unwrap().surface().unwrap().content_bounds(), Rect::new(10, 10, 50, 30)); + } + } +} + +#[test] +fn feathered_selection_identity_transform_preserves_pixels() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16, "background": "transparent"})).unwrap(); + s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + s.execute("select.rect", json!({"x": 4, "y": 4, "width": 8, "height": 8})).unwrap(); + s.execute("select.modify.feather", json!({"radius": 1})).unwrap(); + + let mut before_px = Vec::new(); + for y in 0..16 { + for x in 0..16 { + before_px.push(s.execute("document.pixel", json!({"x": x, "y": y})).unwrap()); + } + } + + s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 0, 0], "interpolation": "nearest"})).unwrap(); + + let mut after_px = Vec::new(); + for y in 0..16 { + for x in 0..16 { + after_px.push(s.execute("document.pixel", json!({"x": x, "y": y})).unwrap()); + } + } + + assert_eq!(before_px, after_px, "feathered selection identity transform must preserve all pixels"); + let p4_8 = s.execute("document.pixel", json!({"x": 4, "y": 8})).unwrap(); + assert_eq!(p4_8, json!([1.0, 0.0, 0.0, 1.0]), "(4,8) must remain opaque red"); + + // Undo restores original document. + s.execute("edit.undo", json!({})).unwrap(); + let undo_p4_8 = s.execute("document.pixel", json!({"x": 4, "y": 8})).unwrap(); + assert_eq!(undo_p4_8, json!([1.0, 0.0, 0.0, 1.0])); + + // Locked layer still refuses transform even if identity. + s.execute("layer.setProps", json!({"locks": {"position": true}})).unwrap(); + assert!(s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 0, 0]})).is_err(), "locked layer refuses identity transform"); +} + +/// A 1 x 8 px column on a 256 x 256 canvas (#3773). +fn column_session() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 256, "height": 256})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.edit("paint", |doc, active| { + let l = doc.layer_mut(active.unwrap()).unwrap(); + l.surface_mut().unwrap().fill_rect(Rect::new(100, 100, 101, 108), &[0.0, 1.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + s +} + +fn opaque_green(s: &Session, x: i32, y: i32) -> bool { + let st = s.active().unwrap(); + let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); + (surf.sample_channel(x, y, 1) - 1.0).abs() < 1e-3 && (surf.sample_channel(x, y, 3) - 1.0).abs() < 1e-3 +} + +/// The "pixel stretch" (#3773): scales far past 1000% are taken, and the stretched column stays +/// solid along its whole length. +#[test] +fn a_one_pixel_column_stretches_5000_percent() { + let mut s = column_session(); + s.execute("edit.transform", json!({"quad": [[100, 100], [150, 100], [150, 108], [100, 108]]})).unwrap(); + assert_eq!(active_bounds(&s), Rect::new(100, 100, 150, 108)); + for x in [100, 101, 125, 149] { + for y in 100..108 { + assert!(opaque_green(&s, x, y), "({x}, {y})"); + } + } +} + +/// The technique as done in Photoshop: select a 1 px column of an image and stretch it across. +#[test] +fn a_selected_column_stretches_solid_over_the_image() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 256, "height": 256})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.edit("paint", |doc, active| { + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + surf.fill_rect(Rect::new(0, 0, 256, 256), &[1.0, 0.0, 0.0, 1.0]); + surf.fill_rect(Rect::new(10, 0, 11, 256), &[0.0, 1.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + s.execute("select.rect", json!({"x": 10, "y": 0, "width": 1, "height": 256})).unwrap(); + s.execute("edit.transform", json!({"quad": [[10, 0], [250, 0], [250, 256], [10, 256]]})).unwrap(); + for x in [10, 11, 100, 200, 249] { + assert!(opaque_green(&s, x, 128), "x = {x}"); + } + let st = s.active().unwrap(); + let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); + assert!(surf.sample_channel(250, 128, 0) > 0.999 && surf.sample_channel(9, 128, 0) > 0.999, "the image either side is untouched"); +} + +/// Free Transform keeps pixels moved off the canvas, as Photoshop does: an 8 x 8 layer moved +/// three canvas widths right and back comes back whole. +#[test] +fn a_layer_moved_far_off_the_canvas_and_back_keeps_its_pixels() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.edit("paint", |doc, active| { + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + for y in 0..8 { + for x in 0..8 { + surf.fill_rect(Rect::new(20 + x, 20 + y, 21 + x, 21 + y), &[x as f32 / 8.0, y as f32 / 8.0, 0.5, 1.0]); + } + } + Ok(()) + }) + .unwrap(); + let pixels = |s: &Session| { + let st = s.active().unwrap(); + let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); + (0..8 * 8 * 4).map(|i| surf.sample_channel(20 + i / 4 % 8, 20 + i / 32, (i % 4) as usize)).collect::>() + }; + let before = pixels(&s); + s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 192, 0]})).unwrap(); + assert_eq!(active_bounds(&s), Rect::new(212, 20, 220, 28)); + s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, -192, 0]})).unwrap(); + assert_eq!(active_bounds(&s), Rect::new(20, 20, 28, 28)); + assert_eq!(pixels(&s), before); +} + +#[test] +fn relative_params_scale_and_rotate_about_the_frame_centre() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 100, "height": 100})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("select.rect", json!({"x": 20, "y": 30, "width": 40, "height": 20})).unwrap(); + s.execute("edit.fill", json!({"contents": "black"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + // 50% about the centre (40, 40), then 10 px right: the content ends at x 40..60, y 35..45. + let r = s.execute("edit.transform", json!({"scaleX": 50, "scaleY": 50, "dx": 10})).unwrap(); + let rect: Vec = serde_json::from_value(r["rect"].clone()).unwrap(); + assert_eq!(rect, [20.0, 30.0, 60.0, 50.0], "the reported frame is the source frame"); + let bounds = |s: &Session| { + let d = s.active().unwrap(); + let b = transform_bounds(&d.doc, d.doc.layer(d.active_layer.unwrap()).unwrap()); + (b.x0, b.y0, b.x1, b.y1) + }; + assert_eq!(bounds(&s), (40, 35, 60, 45)); + // A quarter turn about the centre (50, 40) swaps the frame's sides. + s.execute("edit.transform", json!({"rotate": 90})).unwrap(); + assert_eq!(bounds(&s), (45, 30, 55, 50)); + for bad in [json!({"scaleX": 0}), json!({"rotate": "x"}), json!({"dx": f64::NAN})] { + assert!(s.execute("edit.transform", bad.clone()).is_err(), "{bad}"); + } +} + +/// #5846: a shape's Density and Feather render past its path (over the whole canvas below +/// 100 %), but its transform frame follows the path, as in Photoshop: the same box as the hard +/// shape for Free Transform, the Move tool's controls and snapping, never the canvas. +#[test] +fn a_soft_shapes_frame_follows_its_path() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); + let id = s.execute("shape.create", json!({"kind": "rect", "rect": [20, 30, 60, 40], "fill": "#000000"})).unwrap()["layer"].as_u64().unwrap(); + let id = photocraft_doc::LayerId(id); + let boxes = |s: &Session| { + let st = s.active().unwrap(); + let l = st.doc.layer(id).unwrap(); + (transform_bounds(&st.doc, l), transform_frame(&st.doc, l), crate::snap::layer_rect(&st.doc, id)) + }; + let hard = boxes(&s); + assert_eq!(hard.0, Rect::new(20, 30, 80, 70), "the hard shape's frame"); + s.execute("layer.vectorMask.edit", json!({"density": 60, "feather": 20})).unwrap(); + { + let st = s.active().unwrap(); + let LayerContent::Shape(sh) = &st.doc.layer(id).unwrap().content else { panic!("a shape") }; + let painted = photocraft_compose::bounds::content_bounds(sh.cache.as_ref().unwrap()); + assert_eq!(painted, st.doc.bounds(), "the soft fill renders over the whole canvas"); + } + let soft = boxes(&s); + assert_eq!(soft, hard, "the frame ignores Density and Feather"); + assert_ne!(soft.1, s.active().unwrap().doc.bounds()); + // Feather alone (density 100 %) leaves the frame on the path too, not grown by the blur. + s.execute("layer.vectorMask.edit", json!({"density": 100, "feather": 20})).unwrap(); + assert_eq!(boxes(&s), hard); + // Free Transform scales about the path's centre, not the canvas's. + s.execute("edit.transform", json!({"layer": id.0, "scaleX": 200})).unwrap(); + let st = s.active().unwrap(); + let LayerContent::Shape(sh) = &st.doc.layer(id).unwrap().content else { panic!("a shape") }; + let (x0, y0, x1, y1) = sh.path.control_bounds().unwrap(); + assert_eq!((x0.round(), y0.round(), x1.round(), y1.round()), (-10.0, 30.0, 110.0, 70.0)); + assert_eq!((sh.density, sh.feather), (1.0, 20.0), "the transform keeps the soft settings"); +} + +/// A stroked soft shape's frame is the hard shape's rendered frame for every stroke alignment: +/// a centred stroke reaches half its width past the path, not its full width; both stop at +/// the canvas edge. +#[test] +fn a_stroked_soft_shapes_frame_matches_the_hard_shapes() { + for (align, reach, x) in [("center", 5, 50), ("inside", 0, 50), ("outside", 10, 50), ("center", 5, -20)] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); + let stroke = json!({"width": 10, "color": "#ff0000", "align": align, "join": "round"}); + let id = s.execute("shape.create", json!({"kind": "rect", "rect": [x, 50, 60, 40], "fill": "#000000", "stroke": stroke})).unwrap()["layer"] + .as_u64() + .unwrap(); + let id = photocraft_doc::LayerId(id); + let boxes = |s: &Session| { + let st = s.active().unwrap(); + let l = st.doc.layer(id).unwrap(); + (transform_bounds(&st.doc, l), transform_frame(&st.doc, l), crate::snap::layer_rect(&st.doc, id)) + }; + let hard = boxes(&s); + // Hand-computed: the path is x..x + 60 x 50..90, the stroke reaches `reach` px past it. + assert_eq!(hard.0, Rect::new((x - reach).max(0), 50 - reach, x + 60 + reach, 90 + reach), "{align} at {x}: the hard shape's frame"); + s.execute("layer.vectorMask.edit", json!({"density": 60, "feather": 8})).unwrap(); + assert_eq!(boxes(&s), hard, "{align} at {x}: Density and Feather leave the frame"); + s.execute("layer.vectorMask.edit", json!({"density": 100, "feather": 8})).unwrap(); + assert_eq!(boxes(&s), hard, "{align} at {x}: Feather alone leaves the frame"); + } +} diff --git a/crates/engine/src/trap_cmds.rs b/crates/engine/src/cmd/trap_cmds.rs similarity index 100% rename from crates/engine/src/trap_cmds.rs rename to crates/engine/src/cmd/trap_cmds.rs diff --git a/crates/engine/src/type_area_cmds.rs b/crates/engine/src/cmd/type_area_cmds.rs similarity index 100% rename from crates/engine/src/type_area_cmds.rs rename to crates/engine/src/cmd/type_area_cmds.rs diff --git a/crates/engine/src/type_area_cmds/tests.rs b/crates/engine/src/cmd/type_area_cmds/tests.rs similarity index 100% rename from crates/engine/src/type_area_cmds/tests.rs rename to crates/engine/src/cmd/type_area_cmds/tests.rs diff --git a/crates/engine/src/type_caret_cmds.rs b/crates/engine/src/cmd/type_caret_cmds.rs similarity index 100% rename from crates/engine/src/type_caret_cmds.rs rename to crates/engine/src/cmd/type_caret_cmds.rs diff --git a/crates/engine/src/type_cmds.rs b/crates/engine/src/cmd/type_cmds.rs similarity index 55% rename from crates/engine/src/type_cmds.rs rename to crates/engine/src/cmd/type_cmds.rs index 82ac7a7915..67fc34be60 100644 --- a/crates/engine/src/type_cmds.rs +++ b/crates/engine/src/cmd/type_cmds.rs @@ -1184,800 +1184,4 @@ fn step_size(s: &mut Session, p: &Value, up: bool, default_by: f32) -> Result Session { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 200, "height": 100, "background": "transparent"})).unwrap(); - s - } - - fn text_layer(s: &Session, id: u64) -> TextLayer { - match &s.active().unwrap().doc.layer(LayerId(id)).unwrap().content { - LayerContent::Text(t) => t.clone(), - other => panic!("{}", other.kind_name()), - } - } - - #[test] - fn named_face_metadata_replaces_old_postscript_identity() { - let mut style = CharStyle { font_family: "Inter".into(), postscript_name: Some("Inter-Regular".into()), ..Default::default() }; - apply_char_props(&mut style, &json!({"fontStyle": "SemiBold"})); - assert_eq!(style.weight, 600); - assert_eq!(style.postscript_name.as_deref(), Some("Inter-SemiBold")); - apply_char_props(&mut style, &json!({"weight": 400})); - // #3556: a style change re-resolves to the installed face instead of leaving it nameless. - assert_eq!(style.postscript_name.as_deref(), Some("Inter-Regular")); - assert!(style.font_style.is_empty()); - apply_char_props(&mut style, &json!({"fontStyle": "unknown-style"})); - assert_eq!(style.postscript_name.as_deref(), Some("Inter-Regular")); - apply_char_props(&mut style, &json!({"fontStyle": "Regular", "postscriptName": "ExplicitFace"})); - assert_eq!(style.postscript_name.as_deref(), Some("ExplicitFace")); - } - - /// #3556: a font named by family stores the installed face's PostScript name, so PSD export - /// names a real font instead of inventing "-Regular" that Photoshop calls missing. - #[test] - fn a_family_font_gets_the_installed_postscript_name() { - let mut style = CharStyle { font_family: "Inter".into(), ..Default::default() }; - apply_char_props(&mut style, &json!({"font": "Inter"})); - assert_eq!(style.font_family, "Inter"); - assert_eq!(style.postscript_name.as_deref(), Some("Inter-Regular"), "resolved from the font database"); - // A weight picks that face's name. - apply_char_props(&mut style, &json!({"font": "Inter", "weight": 600})); - assert_eq!(style.postscript_name.as_deref(), Some("Inter-SemiBold")); - // A weight no face has (a variable font's axis, or between two faces) names no face, so - // layout still matches the requested weight instead of a nearby face's. - apply_char_props(&mut style, &json!({"weight": 650})); - assert!(style.postscript_name.is_none(), "{:?}", style.postscript_name); - // A family PhotoCraft does not have keeps no name; the export falls back as before. - let mut absent = CharStyle { font_family: "No Such Family 123".into(), ..Default::default() }; - apply_char_props(&mut absent, &json!({"font": "No Such Family 123"})); - assert!(absent.postscript_name.is_none()); - } - - /// Picking a style or weight resets the weight axis to it; other axes keep their values (#2985). - #[test] - fn a_style_or_weight_resets_the_weight_axis() { - let mut style = CharStyle::default(); - apply_char_props(&mut style, &json!({"variations": {"wght": 650, "wdth": 80}})); - apply_char_props(&mut style, &json!({"fontStyle": "Bold"})); - let axes = |s: &CharStyle| s.variations.iter().map(|v| (v.axis.clone(), v.value)).collect::>(); - assert_eq!(axes(&style), [("wdth".to_string(), 80.0)]); - apply_char_props(&mut style, &json!({"variations": {"wght": 650}})); - apply_char_props(&mut style, &json!({"weight": 300})); - assert_eq!(axes(&style), [("wdth".to_string(), 80.0)]); - apply_char_props(&mut style, &json!({"fontStyle": "Light", "variations": {"wght": 350}})); - assert_eq!(axes(&style), [("wdth".to_string(), 80.0), ("wght".to_string(), 350.0)], "same-call values apply after the style"); - } - - #[test] - fn absurd_type_size_and_tracking_are_rejected_as_bad_params() { - let mut s = session(); - assert!(matches!( - s.execute("type.create", json!({"text": "abc", "size": 1e30})), - Err(EngineError::BadParams { cmd, .. }) if cmd == "type.create" - )); - - let id = s.execute("type.create", json!({"text": "abc", "size": 12})).unwrap()["layer"].as_u64().unwrap(); - let before = text_layer(&s, id); - for params in [json!({"layer": id, "tracking": 1e30}), json!({"layer": id, "runs": [{"start": 0, "end": 3, "tracking": 1e30}]})] { - assert!(matches!( - s.execute("type.edit", params), - Err(EngineError::BadParams { cmd, .. }) if cmd == "type.edit" - )); - assert_eq!(text_layer(&s, id).runs, before.runs); - } - assert!(matches!( - s.execute("type.setStyle", json!({"layer": id, "tracking": 1e30})), - Err(EngineError::BadParams { cmd, .. }) if cmd == "type.setStyle" - )); - assert_eq!(text_layer(&s, id).runs, before.runs); - } - - /// A font that arrives after the layer was drawn (served fonts on the web) re-renders it with - /// no history step, and a clean document stays clean. - #[test] - fn refreshing_type_layers_takes_no_history_step() { - let mut s = session(); - let id = LayerId(s.execute("type.create", json!({"text": "Hello", "size": 24})).unwrap()["layer"].as_u64().unwrap()); - let doc_id = s.active().unwrap().doc.id; - // Stale pixels, and a document saved in this state. - { - let st = s.active_mut().unwrap(); - let Some(Layer { content: LayerContent::Text(t), .. }) = Arc::make_mut(&mut st.doc).layer_mut(id) else { panic!("not a type layer") }; - t.cache = None; - st.saved_revision = st.revision; - } - let rev = s.active().unwrap().revision; - let unknown = [(doc_id, LayerId(u64::MAX)), (photocraft_doc::DocId(u64::MAX), id)]; - assert!(s.refresh_type_layers(&[&[(doc_id, id)][..], &unknown].concat()).is_empty()); - assert!(text_layer(&s, id.0).cache.is_some()); - let st = s.active().unwrap(); - assert!(st.revision > rev); - assert_eq!(st.saved_revision, st.revision, "still clean"); - // The only history step is still the creation. - assert!(s.undo()); - assert!(s.active().unwrap().doc.layer(id).is_none()); - } - - #[test] - fn create_renders_and_is_undoable() { - let mut s = session(); - let r = s.execute("type.create", json!({"x": 10, "y": 50, "text": "Hello", "size": 24, "color": "#ff0000"})).unwrap(); - let id = r["layer"].as_u64().unwrap(); - let b = r["bounds"].as_array().unwrap(); - assert!(b[0].as_i64().unwrap() >= 9 && b[3].as_i64().unwrap() <= 56, "{b:?}"); - let t = text_layer(&s, id); - assert_eq!(t.text, "Hello"); - assert_eq!(t.runs[0].style.size_pt, 24.0); - assert!(t.cache.is_some() && t.psd_raw.is_some()); - let l = s.active().unwrap().doc.layer(LayerId(id)).unwrap(); - assert_eq!(l.name, "Hello"); - // Red pixels exist. - let c = t.cache.as_ref().unwrap(); - let r = c.content_bounds(); - assert!(c.read_region(r).as_chunks::<4>().0.iter().any(|p| p[3] > 0.9 && p[0] > 0.9 && p[1] < 0.1)); - // The TySh we generated parses back to the same model. - let back = photocraft_text::psd::text_layer_from_tysh(t.psd_raw.as_ref().unwrap(), 72.0).unwrap(); - assert_eq!(back.text, "Hello"); - let strip = |mut r: Vec| { - for x in &mut r { - x.style.postscript_name = None; - } - r - }; - assert_eq!(strip(back.char_runs()), strip(t.char_runs())); - assert_eq!(back.char_runs()[0].style.postscript_name.as_deref(), Some("Inter-Regular")); - assert!(s.undo()); - assert!(s.active().unwrap().doc.layer(LayerId(id)).is_none()); - } - - fn layer_name_of(s: &Session, id: u64) -> String { - s.active().unwrap().doc.layer(LayerId(id)).unwrap().name.clone() - } - - #[test] - fn auto_name_follows_the_text() { - // The Type tool's flow (#483): a placeholder, selected, then replaced by typing. - let mut s = session(); - let id = s.execute("type.create", json!({"x": 0, "y": 40, "text": "Lorem Ipsum", "coalesce": "k"})).unwrap()["layer"].as_u64().unwrap(); - assert_eq!(layer_name_of(&s, id), "Lorem Ipsum"); - s.execute("type.edit", json!({"layer": id, "replace": {"start": 0, "end": 11, "text": "H"}, "coalesce": "k"})).unwrap(); - s.execute("type.edit", json!({"layer": id, "replace": {"start": 1, "end": 1, "text": "eading\nsecond line"}, "coalesce": "k"})).unwrap(); - assert_eq!(layer_name_of(&s, id), "Heading"); - // Emptied, the name is the default one and keeps following. - s.execute("type.edit", json!({"layer": id, "text": ""})).unwrap(); - assert_eq!(layer_name_of(&s, id), "Type Layer"); - s.execute("type.edit", json!({"layer": id, "text": "Title"})).unwrap(); - assert_eq!(layer_name_of(&s, id), "Title"); - assert!(s.undo()); - assert_eq!(layer_name_of(&s, id), "Type Layer"); - } - - #[test] - fn size_keys_step_each_run_and_respect_layer_scale() { - let mut s = session(); - let id = s.execute("type.create", json!({"x": 0, "y": 40, "text": "Hello world", "size": 12})).unwrap()["layer"].as_u64().unwrap(); - s.execute("type.setStyle", json!({"layer": id, "range": [6, 11], "size": 20})).unwrap(); - s.execute("type.increaseSize", json!({})).unwrap(); - let sizes = |s: &Session| text_layer(s, id).char_runs().iter().map(|r| r.style.size_pt).collect::>(); - assert_eq!(sizes(&s), vec![14.0, 22.0], "every run grows by 2 pt"); - s.execute("type.decreaseSizeMore", json!({"range": [0, 5]})).unwrap(); - assert_eq!(sizes(&s)[0], 4.0, "only the range, by 10 pt"); - for _ in 0..2 { - s.execute("type.decreaseSize", json!({"range": [0, 5]})).unwrap(); - } - assert_eq!(sizes(&s)[0], TYPE_SIZE_MIN_PT as f32, "never below the smallest size"); - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(sizes(&s)[0], 2.0, "one undo step per press"); - - let scaled = s.execute("type.create", json!({"x": 0, "y": 80, "text": "Big", "size": 12})).unwrap()["layer"].as_u64().unwrap(); - s.execute("type.edit", json!({"layer": scaled, "transform": [2.0, 0.0, 0.0, 2.0, 0.0, 80.0]})).unwrap(); - s.execute("type.increaseSize", json!({"layer": scaled})).unwrap(); - assert_eq!(text_layer(&s, scaled).char_runs()[0].style.size_pt, 13.0, "a 200% layer shows 24 pt and steps to 26 pt"); - } - - #[test] - fn size_keys_need_a_type_layer() { - let mut s = session(); - assert!(s.execute("type.increaseSize", json!({})).is_err()); - let id = s.execute("type.create", json!({"x": 0, "y": 40, "text": "Hi", "size": 12})).unwrap()["layer"].as_u64().unwrap(); - s.execute("type.increaseSize", json!({"by": "big"})).unwrap(); - s.execute("type.increaseSize", json!({"by": -3})).unwrap(); - s.execute("type.decreaseSize", json!({"by": 1e30, "range": [9, 0]})).unwrap(); - assert_eq!(text_layer(&s, id).char_runs()[0].style.size_pt, TYPE_SIZE_MIN_PT as f32, "bad steps fall back or clamp, never panic"); - assert_eq!(crate::commands::find("type.increaseSize").and_then(|c| c.shortcut), Some("Cmd+Shift+.")); - assert_eq!(crate::commands::find("type.decreaseSize").and_then(|c| c.shortcut), Some("Cmd+Shift+,")); - } - - #[test] - fn auto_name_skips_leading_blank_lines() { - let mut s = session(); - let id = s.execute("type.create", json!({"x": 0, "y": 40, "text": "\n \nHello\nworld"})).unwrap()["layer"].as_u64().unwrap(); - assert_eq!(layer_name_of(&s, id), "Hello"); - s.execute("type.edit", json!({"layer": id, "replace": {"start": 0, "end": 0, "text": "\n"}})).unwrap(); - s.execute("type.edit", json!({"layer": id, "text": "\n\nGoodbye"})).unwrap(); - assert_eq!(layer_name_of(&s, id), "Goodbye"); - } - - #[test] - fn custom_name_survives_text_edits() { - let mut s = session(); - let id = s.execute("type.create", json!({"x": 0, "y": 40, "text": "Hello", "name": "Logo"})).unwrap()["layer"].as_u64().unwrap(); - s.execute("type.edit", json!({"layer": id, "text": "Goodbye"})).unwrap(); - assert_eq!(layer_name_of(&s, id), "Logo"); - // Renamed after creation: kept too. - let id = s.execute("type.create", json!({"x": 0, "y": 80, "text": "Hello"})).unwrap()["layer"].as_u64().unwrap(); - s.execute("layer.renameLayer", json!({"layer": id, "name": "Caption"})).unwrap(); - s.execute("type.edit", json!({"layer": id, "text": "Goodbye"})).unwrap(); - assert_eq!(layer_name_of(&s, id), "Caption"); - // A name given with the edit wins over the text. - s.execute("type.edit", json!({"layer": id, "text": "Again", "name": "Footer"})).unwrap(); - assert_eq!(layer_name_of(&s, id), "Footer"); - } - - #[test] - fn edit_with_name_is_one_undo_step_for_text_name_and_bounds() { - let mut s = session(); - let id = s.execute("type.create", json!({"x": 10, "y": 50, "text": "Before", "size": 20, "name": "Original"})).unwrap()["layer"].as_u64().unwrap(); - let layer = s.active().unwrap().doc.layer(LayerId(id)).unwrap(); - let before_bounds = text_layer(&s, id).cache.unwrap().content_bounds(); - assert_eq!(layer.name, "Original"); - let steps = s.active().unwrap().history.entries().len(); - - s.execute("type.edit", json!({"layer": id, "text": "A much longer edited title that wraps", "box": [10, 10, 50, 60], "name": "Renamed"})).unwrap(); - - let edited = s.active().unwrap().doc.layer(LayerId(id)).unwrap(); - let edited_bounds = text_layer(&s, id).cache.unwrap().content_bounds(); - assert_eq!(edited.name, "Renamed"); - assert_eq!(text_layer(&s, id).text, "A much longer edited title that wraps"); - assert_ne!(edited_bounds, before_bounds); - assert_eq!(s.active().unwrap().history.entries().len(), steps + 1); - - assert!(s.undo()); - let restored = s.active().unwrap().doc.layer(LayerId(id)).unwrap(); - assert_eq!(restored.name, "Original"); - assert_eq!(text_layer(&s, id).text, "Before"); - assert_eq!(text_layer(&s, id).cache.unwrap().content_bounds(), before_bounds); - } - - #[test] - fn edit_replace_keeps_styles() { - let mut s = session(); - let id = s.execute("type.create", json!({"x": 0, "y": 40, "text": "Hello world"})).unwrap()["layer"].as_u64().unwrap(); - s.execute("type.setStyle", json!({"layer": id, "range": [6, 11], "fauxBold": true, "color": [0, 0, 1]})).unwrap(); - let t = text_layer(&s, id); - assert_eq!(t.runs.len(), 2); - assert_eq!(t.runs[0].len, 6); - assert!(t.runs[1].style.faux_bold); - // Insert inside the bold word: inherits bold. - s.execute("type.edit", json!({"layer": id, "replace": {"start": 8, "end": 8, "text": "XX"}})).unwrap(); - let t = text_layer(&s, id); - assert_eq!(t.text, "Hello woXXrld"); - assert_eq!(t.runs[1].len, 7); - // Delete across the style boundary. - s.execute("type.edit", json!({"layer": id, "replace": {"start": 3, "end": 8, "text": ""}})).unwrap(); - let t = text_layer(&s, id); - assert_eq!(t.text, "HelXXrld"); - assert_eq!(t.runs.iter().map(|r| r.len).collect::>(), vec![3, 5]); - // Whole-text replace with a multi-byte string. - let info = s.execute("type.edit", json!({"layer": id, "text": "Größe ✓\nzwei"})).unwrap(); - assert_eq!(info["lines"].as_array().unwrap().len(), 2); - let t = text_layer(&s, id); - assert_eq!(t.runs.iter().map(|r| r.len).sum::(), t.text.len()); - } - - #[test] - fn all_locked_type_edit_rejects_text_replacement_without_history() { - let mut s = session(); - let id = s.execute("type.create", json!({"x": 20, "y": 20, "text": "a", "size": 12})).unwrap()["layer"].as_u64().unwrap(); - s.execute("layer.setProps", json!({"layer": id, "locked": true})).unwrap(); - let history = s.active().unwrap().history.past_len(); - - let result = s.execute("type.edit", json!({"layer": id, "text": "b"})); - assert!(matches!(&result, Err(EngineError::Other(message)) if message.contains("locked")), "{result:?}"); - assert_eq!(text_layer(&s, id).text, "a"); - assert_eq!(s.active().unwrap().history.past_len(), history); - - s.execute("layer.setProps", json!({"layer": id, "locked": false})).unwrap(); - let history = s.active().unwrap().history.past_len(); - s.execute("type.edit", json!({"layer": id, "text": "b"})).unwrap(); - assert_eq!(text_layer(&s, id).text, "b"); - assert_eq!(s.active().unwrap().history.past_len(), history + 1); - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(text_layer(&s, id).text, "a"); - assert_eq!(s.active().unwrap().history.past_len(), history); - } - - #[test] - fn all_locked_type_layer_rejects_formatting_without_history() { - let mut s = session(); - let id = s.execute("type.create", json!({"x": 20, "y": 20, "text": "a", "size": 12})).unwrap()["layer"].as_u64().unwrap(); - let other = s.execute("type.create", json!({"x": 20, "y": 60, "text": "b", "size": 12})).unwrap()["layer"].as_u64().unwrap(); - s.execute("layer.setProps", json!({"layer": id, "locked": true})).unwrap(); - let before = text_layer(&s, id); - let history = s.active().unwrap().history.past_len(); - - for (cmd, p) in [ - ("type.setStyle", json!({"layer": id, "size": 40, "fauxBold": true})), - ("type.setStyle", json!({"layers": [other, id], "size": 40})), - ("type.warpText", json!({"layer": id, "style": "arc"})), - ("type.antiAlias.none", json!({"layer": id})), - ("type.orientation.vertical", json!({"layer": id})), - ("type.openType.swash", json!({"layer": id})), - ] { - let result = s.execute(cmd, p); - assert!(matches!(&result, Err(EngineError::Other(message)) if message.contains("locked")), "{cmd}: {result:?}"); - } - assert_eq!(text_layer(&s, id), before); - assert_eq!(text_layer(&s, other).size_pt, 12.0); - assert_eq!(s.active().unwrap().history.past_len(), history); - - s.execute("layer.setProps", json!({"layer": id, "locked": false})).unwrap(); - s.execute("type.setStyle", json!({"layer": id, "size": 40})).unwrap(); - assert_eq!(text_layer(&s, id).size_pt, 40.0); - } - - #[test] - fn trailing_empty_paragraph_styles_without_changing_previous_lines() { - let mut s = session(); - let id = s.execute("type.create", json!({"text":"a\nb\n","x":20,"y":20,"size":12,"font":"Inter","align":"left"})).unwrap()["layer"].as_u64().unwrap(); - let before = s.execute("type.info", json!({"layer":id})).unwrap(); - let previous_line = before["lines"][1].clone(); - - let styled = s.execute("type.setStyle", json!({"layer":id,"range":[4,4],"align":"right"})).unwrap(); - assert_eq!(styled["paragraphs"].as_array().unwrap().len(), 2); - assert_eq!(styled["paragraphs"][0]["start"], 0); - assert_eq!(styled["paragraphs"][0]["end"], 4); - assert_eq!(styled["paragraphs"][0]["style"]["align"], "Left"); - assert_eq!(styled["paragraphs"][1]["start"], 4); - assert_eq!(styled["paragraphs"][1]["end"], 4); - assert_eq!(styled["paragraphs"][1]["style"]["align"], "Right"); - assert_eq!(styled["lines"][1], previous_line, "the preceding paragraph must not move"); - let raw = text_layer(&s, id).psd_raw.clone().unwrap(); - let round_trip = photocraft_text::psd::text_layer_from_tysh(&raw, 72.0).unwrap(); - assert_eq!(round_trip.paragraph_runs().last().unwrap().style.align, TextAlign::Right); - - // Typing directly into the previously empty final paragraph retains its style. - let edited = s.execute("type.edit", json!({"layer":id,"replace":{"start":4,"end":4,"text":"c"}})).unwrap(); - assert_eq!(edited["text"], "a\nb\nc"); - assert_eq!(edited["paragraphs"][0]["end"], 4); - assert_eq!(edited["paragraphs"][0]["style"]["align"], "Left"); - assert_eq!(edited["paragraphs"][1]["start"], 4); - assert_eq!(edited["paragraphs"][1]["end"], 5); - assert_eq!(edited["paragraphs"][1]["style"]["align"], "Right"); - assert_eq!(edited["lines"][1], previous_line, "typing in the final paragraph does not move b"); - } - - #[test] - fn set_style_paragraph_and_box() { - let mut s = session(); - let id = s.execute("type.create", json!({"box": [10, 10, 80, 80], "text": "one two three four five six seven", "size": 12})).unwrap()["layer"] - .as_u64() - .unwrap(); - let info = s.execute("type.setStyle", json!({"layer": id, "align": "center", "leading": 20})).unwrap(); - let lines = info["lines"].as_array().unwrap(); - assert!(lines.len() >= 3); - let b0 = lines[0]["baseline"].as_f64().unwrap(); - let b1 = lines[1]["baseline"].as_f64().unwrap(); - assert!((b1 - b0 - 20.0).abs() < 1e-3, "explicit leading {b0} {b1}"); - assert_eq!(info["paragraphs"][0]["style"]["align"], "Center"); - let t = text_layer(&s, id); - assert!(matches!(t.shape, TextShape::Box { width, .. } if width == 80.0)); - // Pixels stay inside the box horizontally. - let r = t.cache.as_ref().unwrap().content_bounds(); - assert!(r.x0 >= 9 && r.x1 <= 91, "{r:?}"); - // Convert to point text and move. - s.execute("type.edit", json!({"layer": id, "point": [5, 30]})).unwrap(); - s.execute("type.edit", json!({"layer": id, "move": [10, 0]})).unwrap(); - let t = text_layer(&s, id); - assert_eq!(t.shape, TextShape::Point); - assert_eq!(t.transform.m[4], 15.0); - } - - #[test] - fn rasterize_and_fonts() { - let mut s = session(); - let id = s.execute("type.create", json!({"x": 5, "y": 30, "text": "Raster"})).unwrap()["layer"].as_u64().unwrap(); - s.execute("type.rasterize", json!({"layer": id})).unwrap(); - let l = s.active().unwrap().doc.layer(LayerId(id)).unwrap(); - assert!(matches!(l.content, LayerContent::Raster(_))); - assert!(l.surface().unwrap().content_bounds().width() > 10); - assert!(s.execute("type.edit", json!({"layer": id, "text": "x"})).is_err()); - let fonts = s.execute("type.fonts", json!({})).unwrap(); - assert!(fonts["families"].as_array().unwrap().iter().any(|f| f == "Inter")); - let faces = s.execute("type.fonts", json!({"family": "Inter"})).unwrap(); - assert!(!faces["faces"].as_array().unwrap().is_empty()); - } - - /// #124: a type edit damages only the layer's old and new pixels (the canvas recomposites - /// that, not the document), and a drag's coalesced steps are one history step. - #[test] - fn type_edits_damage_only_the_layer_and_coalesce() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 3000, "height": 2000})).unwrap(); - let id = s.execute("type.create", json!({"x": 100, "y": 100, "text": "Hi", "size": 20})).unwrap()["layer"].as_u64().unwrap(); - let steps = s.active().unwrap().history.entries().len(); - for k in 0..5 { - s.execute("type.setStyle", json!({"layer": id, "size": 30 + k * 10, "coalesce": "drag"})).unwrap(); - let d = s.active().unwrap().last_damage.expect("damage rect"); - let r = text_layer(&s, id).cache.unwrap().content_bounds(); - assert!(d.intersect(&r) == r && d.width() <= 512 && d.height() <= 512, "{d:?} {r:?}"); - } - assert_eq!(s.active().unwrap().history.entries().len(), steps + 1); - assert!(s.undo()); - assert_eq!(text_layer(&s, id).runs[0].style.size_pt, 20.0); - } - - #[test] - fn edit_rejects_a_reversed_runs_range() { - let mut s = session(); - let id = s.execute("type.create", json!({"x": 0, "y": 40, "text": "Hello world", "size": 20})).unwrap()["layer"].as_u64().unwrap(); - let before = text_layer(&s, id).char_runs(); - let steps = s.active().unwrap().history.entries().len(); - for runs in [ - json!([{"start": 5, "end": 2, "fauxBold": true}]), - json!([{"start": 0, "end": 3, "fauxBold": true}, {"start": 8, "end": 7}]), - json!([{"end": 0, "start": 1}]), - ] { - let e = s.execute("type.edit", json!({"layer": id, "runs": runs})).unwrap_err(); - assert!(matches!(e, EngineError::BadParams { .. }) && e.to_string().contains("is before `start`"), "{e}"); - } - // Nothing changed and nothing was recorded, not even the valid run before the bad one. - assert_eq!(text_layer(&s, id).char_runs(), before); - assert_eq!(s.active().unwrap().history.entries().len(), steps); - // The same range the right way round still styles it. - s.execute("type.edit", json!({"layer": id, "runs": [{"start": 2, "end": 5, "fauxBold": true}]})).unwrap(); - let runs = text_layer(&s, id).char_runs(); - assert_eq!(runs.iter().map(|r| (r.len, r.style.faux_bold)).collect::>(), [(2, false), (3, true), (6, false)]); - } - - #[test] - fn style_range_reversed_is_a_no_op() { - let mut t = TextLayer::default(); - replace_text(&mut t, 0, 0, "Hello world"); - let before = t.char_runs(); - style_range(&mut t, 5, 2, &|s| s.size_pt = 40.0); - assert_eq!(t.char_runs(), before); - assert_eq!(t.runs.iter().map(|r| r.len).sum::(), t.text.len()); - } - - #[test] - fn style_range_on_empty_text() { - let mut t = TextLayer::default(); - style_range(&mut t, 0, 0, &|s| s.size_pt = 40.0); - assert_eq!(t.runs[0].style.size_pt, 40.0); - replace_text(&mut t, 0, 0, "abc"); - assert_eq!(t.runs.len(), 1); - assert_eq!(t.runs[0].len, 3); - assert_eq!(t.runs[0].style.size_pt, 40.0); - } - - /// Replacing a selected smaller second line (by typing or pasting) keeps its size, not the - /// first line's, whose line break precedes the selection. - #[test] - fn replacing_a_selection_keeps_its_first_characters_style() { - let mut s = session(); - let id = s.execute("type.create", json!({"x": 5, "y": 50, "text": "BIG\nsmall", "size": 40})).unwrap()["layer"].as_u64().unwrap(); - s.execute("type.edit", json!({"layer": id, "runs": [{"start": 4, "end": 9, "size": 12}]})).unwrap(); - s.execute("type.edit", json!({"layer": id, "replace": {"start": 4, "end": 9, "text": "AIR"}})).unwrap(); - let sizes = |s: &Session| text_layer(s, id).char_runs().iter().map(|r| (r.len, r.style.size_pt)).collect::>(); - assert_eq!(text_layer(&s, id).text, "BIG\nAIR"); - assert_eq!(sizes(&s), [(4, 40.0), (3, 12.0)]); - // A mixed selection takes its first character's style. - s.execute("type.edit", json!({"layer": id, "replace": {"start": 2, "end": 6, "text": "xy"}})).unwrap(); - assert_eq!(sizes(&s), [(4, 40.0), (1, 12.0)]); - // Inserting at a caret still follows the character before it. - s.execute("type.edit", json!({"layer": id, "replace": {"start": 4, "end": 4, "text": "!"}})).unwrap(); - assert_eq!(sizes(&s), [(5, 40.0), (1, 12.0)]); - } - - /// A misspelt `baseline` is an error and keeps superscript, instead of resetting it to Normal. - #[test] - fn unknown_baseline_is_rejected_and_keeps_the_style() { - let mut s = session(); - let id = s.execute("type.create", json!({"x": 5, "y": 50, "text": "x2", "size": 30})).unwrap()["layer"].as_u64().unwrap(); - s.execute("type.setStyle", json!({"layer": id, "range": [1, 2], "baseline": "superscript"})).unwrap(); - let before = text_layer(&s, id).runs; - for b in [json!("superscipt"), json!("Superscript"), json!(1)] { - assert!(matches!(s.execute("type.setStyle", json!({"layer": id, "baseline": b})), Err(EngineError::BadParams { .. })), "{b}"); - assert!(s.execute("type.edit", json!({"layer": id, "baseline": b})).is_err(), "{b}"); - assert!(s.execute("type.create", json!({"x": 0, "y": 10, "text": "a", "baseline": b})).is_err(), "{b}"); - } - assert_eq!(text_layer(&s, id).runs, before); - s.execute("type.setStyle", json!({"layer": id, "baseline": "normal"})).unwrap(); - assert!(text_layer(&s, id).char_runs().iter().all(|r| r.style.baseline == FontBaseline::Normal)); - } - - fn kerning_of(s: &Session, id: u64) -> Vec<(Kerning, f32)> { - let t = text_layer(s, id); - let mut out = Vec::new(); - let mut at = 0; - for r in t.char_runs() { - out.extend(std::iter::repeat_n((r.style.kerning, r.style.kern), t.text[at..at + r.len].chars().count())); - at += r.len; - } - out - } - - /// #8489: `type.edit {"text"}` changes only what differs, so the rest keeps its styles: an - /// added character takes the style beside it, and a change inside one run stays in it. - #[test] - fn edit_text_keeps_the_styles_of_unchanged_text() { - // (characters, colour) per run. - fn runs(s: &Session, id: u64) -> Vec<(usize, [u8; 4])> { - let t = text_layer(s, id); - let mut at = 0; - t.char_runs() - .into_iter() - .map(|r| { - let n = t.text[at..at + r.len].chars().count(); - at += r.len; - (n, r.style.color.to_rgba8()) - }) - .collect() - } - let (dark, purple) = ([0x1b, 0x1f, 0x4b, 255], [0x5a, 0x3d, 0xf0, 255]); - let mut s = session(); - let id = s.execute("type.create", json!({"x": 20, "y": 50, "text": "Craft Suite in Workshop", "size": 40, "color": "#1b1f4b"})).unwrap()["layer"] - .as_u64() - .unwrap(); - s.execute("type.setStyle", json!({"layer": id, "range": [15, 23], "color": "#5a3df0"})).unwrap(); - assert_eq!(runs(&s, id), [(15, dark), (8, purple)]); - s.execute("type.edit", json!({"layer": id, "text": "Craft Suite in Workshop!"})).unwrap(); - assert_eq!(runs(&s, id), [(15, dark), (9, purple)], "the added character joins the last run"); - s.execute("type.edit", json!({"layer": id, "text": "Craft Suite in Worksh\u{f6}p!"})).unwrap(); - assert_eq!(runs(&s, id), [(15, dark), (9, purple)], "a change inside a run stays in it"); - s.execute("type.edit", json!({"layer": id, "text": "Kraft Suite in Worksh\u{f6}p!"})).unwrap(); - assert_eq!(runs(&s, id), [(15, dark), (9, purple)]); - // Replacing everything leaves one style, as before. - s.execute("type.edit", json!({"layer": id, "text": "Hello"})).unwrap(); - assert_eq!(text_layer(&s, id).text, "Hello"); - assert_eq!(runs(&s, id).iter().map(|r| r.0).sum::(), 5); - s.execute("type.edit", json!({"layer": id, "text": ""})).unwrap(); - assert_eq!(text_layer(&s, id).text, ""); - - // Text inserted at the start of a paragraph joins that paragraph, which keeps its style. - let id = s - .execute( - "type.create", - json!({"x": 20, "y": 50, "text": "a -b", "size": 20}), - ) - .unwrap()["layer"] - .as_u64() - .unwrap(); - s.execute("type.setStyle", json!({"layer": id, "range": [2, 3], "align": "right"})).unwrap(); - s.execute( - "type.edit", - json!({"layer": id, "text": "a -Xb"}), - ) - .unwrap(); - let paragraphs: Vec<(usize, photocraft_doc::text::TextAlign)> = - text_layer(&s, id).paragraph_runs().into_iter().map(|r| (r.len, r.style.align)).collect(); - assert_eq!(paragraphs.first().map(|p| p.0), Some(2), "{paragraphs:?}"); - assert_eq!(paragraphs.get(1).copied(), Some((2, photocraft_doc::text::TextAlign::Right)), "{paragraphs:?}"); - } - - /// #206: `type.edit {"kerning"}` over a range takes a number (manual, 1/1000 em) or a mode. - #[test] - fn edit_sets_kerning_over_a_range() { - let mut s = session(); - let id = s.execute("type.create", json!({"x": 5, "y": 50, "text": "AVAT", "size": 30})).unwrap()["layer"].as_u64().unwrap(); - s.execute("type.edit", json!({"layer": id, "range": [0, 1], "kerning": 100})).unwrap(); - s.execute("type.edit", json!({"layer": id, "range": [2, 4], "kerning": "optical"})).unwrap(); - assert_eq!(kerning_of(&s, id), vec![(Kerning::Off, 100.0), (Kerning::Metrics, 0.0), (Kerning::Optical, 0.0), (Kerning::Optical, 0.0)]); - s.execute("type.edit", json!({"layer": id, "kerning": "metrics"})).unwrap(); - assert!(kerning_of(&s, id).iter().all(|k| *k == (Kerning::Metrics, 0.0))); - // Runs and setStyle take the same values; type.info reports them. - s.execute("type.edit", json!({"layer": id, "runs": [{"start": 1, "end": 2, "kerning": -50}]})).unwrap(); - s.execute("type.setStyle", json!({"layer": id, "range": [3, 4], "kerning": "off"})).unwrap(); - assert_eq!(kerning_of(&s, id)[1], (Kerning::Off, -50.0)); - assert_eq!(kerning_of(&s, id)[3], (Kerning::Off, 0.0)); - let info = s.execute("type.info", json!({"layer": id})).unwrap(); - assert_eq!(info["runs"][1]["style"]["kern"], json!(-50.0)); - } - - /// Bad kerning params are errors, never panics, and leave the layer alone. - #[test] - fn kerning_params_fail_gracefully() { - let mut s = session(); - let id = s.execute("type.create", json!({"x": 5, "y": 50, "text": "AV\nT", "size": 30})).unwrap()["layer"].as_u64().unwrap(); - let before = text_layer(&s, id); - for p in [ - json!({"kerning": "tight"}), - json!({"kerning": 1e9}), - json!({"kerning": -5000}), - json!({"kerning": true}), - json!({"kerning": [1]}), - json!({"runs": [{"start": 0, "end": 1, "kerning": "x"}]}), - json!({"kernPair": 3}), - json!({"kernPair": {"by": 20}}), - json!({"kernPair": {"at": 1}}), - json!({"kernPair": {"at": 1, "by": "20"}}), - json!({"kernPair": {"at": 1, "by": 1e12}}), - json!({"kernPair": {"at": 0, "by": 20}}), - json!({"kernPair": {"at": 4, "by": 20}}), - json!({"kernPair": {"at": 99, "by": 20}}), - json!({"kernPair": {"at": 2, "by": 20}}), - json!({"kernPair": {"at": 3, "by": 20}}), - json!({"kernPair": {"at": -1, "by": 20}}), - ] { - let mut p = p; - p["layer"] = json!(id); - assert!(s.execute("type.edit", p.clone()).is_err(), "{p}"); - } - assert!(s.execute("type.setStyle", json!({"layer": id, "kerning": "tight"})).is_err()); - assert_eq!(text_layer(&s, id).runs, before.runs); - // type.create rejects the same values and creates no layer (#994). - let layers = s.active().unwrap().doc.layer_count(); - for k in [json!("tight"), json!(1e9), json!(-5000), json!(true), json!([1])] { - let p = json!({"x": 0, "y": 10, "text": "AV", "kerning": k}); - assert!(s.execute("type.create", p.clone()).is_err(), "{p}"); - } - assert_eq!(s.active().unwrap().doc.layer_count(), layers); - let id = s.execute("type.create", json!({"x": 0, "y": 10, "text": "AV", "kerning": "optical"})).unwrap()["layer"].as_u64().unwrap(); - assert!(kerning_of(&s, id).iter().all(|k| *k == (Kerning::Optical, 0.0))); - let id = s.execute("type.create", json!({"x": 0, "y": 10, "text": "AV", "kerning": -50})).unwrap()["layer"].as_u64().unwrap(); - assert!(kerning_of(&s, id).iter().all(|k| *k == (Kerning::Off, -50.0))); - } - - /// Cost of one Alt+←/→ press (`kernPair`: two measuring layouts + the edit's re-render) on - /// a headline and on a 2000-character paragraph. Release timings for the dev log: - /// `cargo test --release -p photocraft-engine kern_pair_cost -- --ignored --nocapture`. - #[test] - #[ignore] - fn kern_pair_cost() { - let para = "The quick brown fox jumps over the lazy dog. ".repeat(45); - for (name, text, size, bx, kerning) in [ - ("headline", "AVATAR Wave", 72, false, "metrics"), - ("paragraph", para.as_str(), 12, true, "metrics"), - ("optical paragraph", para.as_str(), 12, true, "optical"), - ] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 2000, "height": 1500})).unwrap(); - let mut p = json!({"x": 20, "y": 100, "text": text, "size": size, "font": "Inter", "kerning": kerning}); - if bx { - p["box"] = json!([20, 20, 900, 1400]); - } - let id = s.execute("type.create", p).unwrap()["layer"].as_u64().unwrap(); - let n = 20; - let t0 = std::time::Instant::now(); - for i in 0..n { - s.execute("type.edit", json!({"layer": id, "kernPair": {"at": 1 + i % 3, "by": 20}})).unwrap(); - } - let per = t0.elapsed().as_secs_f64() * 1000.0 / f64::from(n); - let t1 = std::time::Instant::now(); - for i in 0..n { - s.execute("type.setStyle", json!({"layer": id, "range": [1 + i % 3, 2 + i % 3], "tracking": i})).unwrap(); - } - let base = t1.elapsed().as_secs_f64() * 1000.0 / f64::from(n); - eprintln!("{name} ({} chars): kernPair {per:.2} ms/press; a plain style edit {base:.2} ms", text.chars().count()); - } - } - - /// Photoshop's Alt+←/→: the pair before the caret becomes manual, starting from the kerning - /// it shows (the font's pair kerning for "AV"), ±20 per press, one history step each. - #[test] - fn kern_pair_steps_from_the_shown_kerning() { - let mut s = session(); - let id = s.execute("type.create", json!({"x": 5, "y": 50, "text": "AVA", "size": 40, "font": "Inter"})).unwrap()["layer"].as_u64().unwrap(); - let metric = { - let t = text_layer(&s, id); - photocraft_text::shared().lock().unwrap().pair_kerning(&t, 72.0, 0).unwrap() - }; - assert!(metric < -10.0, "Inter kerns AV: {metric}"); - let steps = s.active().unwrap().history.entries().len(); - s.execute("type.edit", json!({"layer": id, "kernPair": {"at": 1, "by": 20}})).unwrap(); - let k0 = kerning_of(&s, id)[0]; - assert_eq!(k0, (Kerning::Off, metric.round() + 20.0)); - s.execute("type.edit", json!({"layer": id, "kernPair": {"at": 1, "by": 100}})).unwrap(); - assert_eq!(kerning_of(&s, id)[0].1, metric.round() + 120.0); - s.execute("type.edit", json!({"layer": id, "kernPair": {"at": 1, "by": -20}})).unwrap(); - assert_eq!(kerning_of(&s, id)[0].1, metric.round() + 100.0); - // Other characters are untouched; each press is its own undoable step. - assert_eq!(&kerning_of(&s, id)[1..], &[(Kerning::Metrics, 0.0), (Kerning::Metrics, 0.0)]); - assert_eq!(s.active().unwrap().history.entries().len(), steps + 3); - assert!(s.undo()); - assert_eq!(kerning_of(&s, id)[0].1, metric.round() + 120.0); - assert!(s.undo() && s.undo()); - assert_eq!(kerning_of(&s, id)[0], (Kerning::Metrics, 0.0)); - } - #[test] - fn create_vertical_type_is_atomic_and_invalid_orientation_is_rejected() { - for boxed in [false, true] { - let mut s = session(); - let before = s.active().unwrap().history.entries().len(); - for orientation in [json!("diagonal"), json!(null), json!(true)] { - assert!(s.execute("type.create", json!({"text": "test", "orientation": orientation})).is_err()); - assert_eq!(s.active().unwrap().history.entries().len(), before); - } - let mut p = json!({"text": "test", "orientation": "vertical", "x": 20, "y": 20}); - if boxed { - p["box"] = json!([20, 20, 80, 60]); - } - let id = s.execute("type.create", p).unwrap()["layer"].as_u64().unwrap(); - let t = text_layer(&s, id); - assert_eq!(t.orientation, Orientation::Vertical); - assert_eq!(matches!(t.shape, TextShape::Box { .. }), boxed); - s.execute("edit.undo", json!({})).unwrap(); - assert!(s.active().unwrap().doc.layer(LayerId(id)).is_none()); - } - } - - #[test] - fn missing_font_emits_warning_in_create_set_style_and_edit() { - let mut s = session(); - let r = s.execute("type.create", json!({"x": 10, "y": 20, "text": "Hello", "font": "NoSuchFamily123"})).unwrap(); - assert_eq!(r["warnings"], json!(["font 'NoSuchFamily123' is not installed; text may render using a fallback face"])); - let id = r["layer"].as_u64().unwrap(); - let styled = s.execute("type.setStyle", json!({"layer": id, "font": "StillNoSuchFamily456"})).unwrap(); - assert_eq!(styled["warnings"], json!(["font 'StillNoSuchFamily456' is not installed; text may render using a fallback face"])); - let edited = s.execute("type.edit", json!({"layer": id, "runs": [{"start": 0, "end": 2, "font": "AnotherMissingFont789"}]})).unwrap(); - assert_eq!( - edited["warnings"], - json!([ - "font 'AnotherMissingFont789' is not installed; text may render using a fallback face", - "font 'StillNoSuchFamily456' is not installed; text may render using a fallback face" - ]) - ); - } - - /// `leadingBy`, `baselineShiftBy` and `trackingBy` step every character from its own value - /// (auto leading from its laid-out value), clamp to Photoshop's ranges, and reject hostile - /// steps without changing anything. - #[test] - fn relative_steps_move_each_character_from_its_own_value() { - let mut s = session(); - let id = s.execute("type.create", json!({"x": 0, "y": 40, "text": "Hello\nworld", "size": 10})).unwrap()["layer"].as_u64().unwrap(); - s.execute("type.setStyle", json!({"layer": id, "range": [8, 11], "leading": 30, "tracking": 50})).unwrap(); - s.execute("type.setStyle", json!({"layer": id, "range": [6, 11], "autoLeading": 150})).unwrap(); - let steps = s.active().unwrap().history.entries().len(); - s.execute("type.setStyle", json!({"layer": id, "range": [0, 11], "leadingBy": 2, "baselineShiftBy": -2, "trackingBy": 20})).unwrap(); - assert_eq!(s.active().unwrap().history.entries().len(), steps + 1, "one history step"); - let t = text_layer(&s, id); - let at = |c: usize| { - let byte = byte_at(&t.text, c); - let mut off = 0; - t.char_runs() - .into_iter() - .find(|r| { - off += r.len; - off > byte - }) - .unwrap() - .style - }; - // Auto leading 120% × 10 pt (first paragraph), 150% × 10 pt (second), and a set 30 pt. - assert_eq!(at(0).leading_pt, Some(14.0)); - assert_eq!(at(6).leading_pt, Some(17.0)); - assert_eq!(at(9).leading_pt, Some(32.0)); - assert_eq!((at(0).baseline_shift_pt, at(9).baseline_shift_pt), (-2.0, -2.0)); - assert_eq!((at(0).tracking, at(9).tracking), (20.0, 70.0)); - // Clamped to the ranges. - s.execute("type.setStyle", json!({"layer": id, "leadingBy": -5000, "baselineShiftBy": 10000, "trackingBy": -11000})).unwrap(); - let t = text_layer(&s, id); - assert!(t.char_runs().iter().all(|r| r.style.leading_pt == Some(LEADING_MIN_PT) - && r.style.baseline_shift_pt == BASELINE_SHIFT_MAX_PT - && r.style.tracking == TRACKING_MIN as f32)); - // A collapsed range in non-empty text changes no character. - let before = text_layer(&s, id).char_runs(); - s.execute("type.setStyle", json!({"layer": id, "range": [3, 3], "trackingBy": 100})).unwrap(); - assert_eq!(text_layer(&s, id).char_runs(), before); - // Hostile steps are refused. - let steps = s.active().unwrap().history.entries().len(); - for bad_step in [json!({"leadingBy": "up"}), json!({"trackingBy": 1e30}), json!({"baselineShiftBy": null}), json!({"leadingBy": [1]})] { - let mut p = bad_step.clone(); - p["layer"] = json!(id); - assert!(matches!(s.execute("type.setStyle", p), Err(EngineError::BadParams { .. })), "{bad_step}"); - } - assert_eq!(s.active().unwrap().history.entries().len(), steps); - // Empty text: the step sets the style the next typed characters get. - let empty = s.execute("type.create", json!({"x": 0, "y": 80, "text": "", "size": 10})).unwrap()["layer"].as_u64().unwrap(); - s.execute("type.setStyle", json!({"layer": empty, "range": [0, 0], "leadingBy": -2})).unwrap(); - assert_eq!(text_layer(&s, empty).char_runs()[0].style.leading_pt, Some(10.0)); - } -} +mod tests; diff --git a/crates/engine/src/cmd/type_cmds/tests.rs b/crates/engine/src/cmd/type_cmds/tests.rs new file mode 100644 index 0000000000..b9851d27e1 --- /dev/null +++ b/crates/engine/src/cmd/type_cmds/tests.rs @@ -0,0 +1,795 @@ +use super::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 200, "height": 100, "background": "transparent"})).unwrap(); + s +} + +fn text_layer(s: &Session, id: u64) -> TextLayer { + match &s.active().unwrap().doc.layer(LayerId(id)).unwrap().content { + LayerContent::Text(t) => t.clone(), + other => panic!("{}", other.kind_name()), + } +} + +#[test] +fn named_face_metadata_replaces_old_postscript_identity() { + let mut style = CharStyle { font_family: "Inter".into(), postscript_name: Some("Inter-Regular".into()), ..Default::default() }; + apply_char_props(&mut style, &json!({"fontStyle": "SemiBold"})); + assert_eq!(style.weight, 600); + assert_eq!(style.postscript_name.as_deref(), Some("Inter-SemiBold")); + apply_char_props(&mut style, &json!({"weight": 400})); + // #3556: a style change re-resolves to the installed face instead of leaving it nameless. + assert_eq!(style.postscript_name.as_deref(), Some("Inter-Regular")); + assert!(style.font_style.is_empty()); + apply_char_props(&mut style, &json!({"fontStyle": "unknown-style"})); + assert_eq!(style.postscript_name.as_deref(), Some("Inter-Regular")); + apply_char_props(&mut style, &json!({"fontStyle": "Regular", "postscriptName": "ExplicitFace"})); + assert_eq!(style.postscript_name.as_deref(), Some("ExplicitFace")); +} + +/// #3556: a font named by family stores the installed face's PostScript name, so PSD export +/// names a real font instead of inventing "-Regular" that Photoshop calls missing. +#[test] +fn a_family_font_gets_the_installed_postscript_name() { + let mut style = CharStyle { font_family: "Inter".into(), ..Default::default() }; + apply_char_props(&mut style, &json!({"font": "Inter"})); + assert_eq!(style.font_family, "Inter"); + assert_eq!(style.postscript_name.as_deref(), Some("Inter-Regular"), "resolved from the font database"); + // A weight picks that face's name. + apply_char_props(&mut style, &json!({"font": "Inter", "weight": 600})); + assert_eq!(style.postscript_name.as_deref(), Some("Inter-SemiBold")); + // A weight no face has (a variable font's axis, or between two faces) names no face, so + // layout still matches the requested weight instead of a nearby face's. + apply_char_props(&mut style, &json!({"weight": 650})); + assert!(style.postscript_name.is_none(), "{:?}", style.postscript_name); + // A family PhotoCraft does not have keeps no name; the export falls back as before. + let mut absent = CharStyle { font_family: "No Such Family 123".into(), ..Default::default() }; + apply_char_props(&mut absent, &json!({"font": "No Such Family 123"})); + assert!(absent.postscript_name.is_none()); +} + +/// Picking a style or weight resets the weight axis to it; other axes keep their values (#2985). +#[test] +fn a_style_or_weight_resets_the_weight_axis() { + let mut style = CharStyle::default(); + apply_char_props(&mut style, &json!({"variations": {"wght": 650, "wdth": 80}})); + apply_char_props(&mut style, &json!({"fontStyle": "Bold"})); + let axes = |s: &CharStyle| s.variations.iter().map(|v| (v.axis.clone(), v.value)).collect::>(); + assert_eq!(axes(&style), [("wdth".to_string(), 80.0)]); + apply_char_props(&mut style, &json!({"variations": {"wght": 650}})); + apply_char_props(&mut style, &json!({"weight": 300})); + assert_eq!(axes(&style), [("wdth".to_string(), 80.0)]); + apply_char_props(&mut style, &json!({"fontStyle": "Light", "variations": {"wght": 350}})); + assert_eq!(axes(&style), [("wdth".to_string(), 80.0), ("wght".to_string(), 350.0)], "same-call values apply after the style"); +} + +#[test] +fn absurd_type_size_and_tracking_are_rejected_as_bad_params() { + let mut s = session(); + assert!(matches!( + s.execute("type.create", json!({"text": "abc", "size": 1e30})), + Err(EngineError::BadParams { cmd, .. }) if cmd == "type.create" + )); + + let id = s.execute("type.create", json!({"text": "abc", "size": 12})).unwrap()["layer"].as_u64().unwrap(); + let before = text_layer(&s, id); + for params in [json!({"layer": id, "tracking": 1e30}), json!({"layer": id, "runs": [{"start": 0, "end": 3, "tracking": 1e30}]})] { + assert!(matches!( + s.execute("type.edit", params), + Err(EngineError::BadParams { cmd, .. }) if cmd == "type.edit" + )); + assert_eq!(text_layer(&s, id).runs, before.runs); + } + assert!(matches!( + s.execute("type.setStyle", json!({"layer": id, "tracking": 1e30})), + Err(EngineError::BadParams { cmd, .. }) if cmd == "type.setStyle" + )); + assert_eq!(text_layer(&s, id).runs, before.runs); +} + +/// A font that arrives after the layer was drawn (served fonts on the web) re-renders it with +/// no history step, and a clean document stays clean. +#[test] +fn refreshing_type_layers_takes_no_history_step() { + let mut s = session(); + let id = LayerId(s.execute("type.create", json!({"text": "Hello", "size": 24})).unwrap()["layer"].as_u64().unwrap()); + let doc_id = s.active().unwrap().doc.id; + // Stale pixels, and a document saved in this state. + { + let st = s.active_mut().unwrap(); + let Some(Layer { content: LayerContent::Text(t), .. }) = Arc::make_mut(&mut st.doc).layer_mut(id) else { panic!("not a type layer") }; + t.cache = None; + st.saved_revision = st.revision; + } + let rev = s.active().unwrap().revision; + let unknown = [(doc_id, LayerId(u64::MAX)), (photocraft_doc::DocId(u64::MAX), id)]; + assert!(s.refresh_type_layers(&[&[(doc_id, id)][..], &unknown].concat()).is_empty()); + assert!(text_layer(&s, id.0).cache.is_some()); + let st = s.active().unwrap(); + assert!(st.revision > rev); + assert_eq!(st.saved_revision, st.revision, "still clean"); + // The only history step is still the creation. + assert!(s.undo()); + assert!(s.active().unwrap().doc.layer(id).is_none()); +} + +#[test] +fn create_renders_and_is_undoable() { + let mut s = session(); + let r = s.execute("type.create", json!({"x": 10, "y": 50, "text": "Hello", "size": 24, "color": "#ff0000"})).unwrap(); + let id = r["layer"].as_u64().unwrap(); + let b = r["bounds"].as_array().unwrap(); + assert!(b[0].as_i64().unwrap() >= 9 && b[3].as_i64().unwrap() <= 56, "{b:?}"); + let t = text_layer(&s, id); + assert_eq!(t.text, "Hello"); + assert_eq!(t.runs[0].style.size_pt, 24.0); + assert!(t.cache.is_some() && t.psd_raw.is_some()); + let l = s.active().unwrap().doc.layer(LayerId(id)).unwrap(); + assert_eq!(l.name, "Hello"); + // Red pixels exist. + let c = t.cache.as_ref().unwrap(); + let r = c.content_bounds(); + assert!(c.read_region(r).as_chunks::<4>().0.iter().any(|p| p[3] > 0.9 && p[0] > 0.9 && p[1] < 0.1)); + // The TySh we generated parses back to the same model. + let back = photocraft_text::psd::text_layer_from_tysh(t.psd_raw.as_ref().unwrap(), 72.0).unwrap(); + assert_eq!(back.text, "Hello"); + let strip = |mut r: Vec| { + for x in &mut r { + x.style.postscript_name = None; + } + r + }; + assert_eq!(strip(back.char_runs()), strip(t.char_runs())); + assert_eq!(back.char_runs()[0].style.postscript_name.as_deref(), Some("Inter-Regular")); + assert!(s.undo()); + assert!(s.active().unwrap().doc.layer(LayerId(id)).is_none()); +} + +fn layer_name_of(s: &Session, id: u64) -> String { + s.active().unwrap().doc.layer(LayerId(id)).unwrap().name.clone() +} + +#[test] +fn auto_name_follows_the_text() { + // The Type tool's flow (#483): a placeholder, selected, then replaced by typing. + let mut s = session(); + let id = s.execute("type.create", json!({"x": 0, "y": 40, "text": "Lorem Ipsum", "coalesce": "k"})).unwrap()["layer"].as_u64().unwrap(); + assert_eq!(layer_name_of(&s, id), "Lorem Ipsum"); + s.execute("type.edit", json!({"layer": id, "replace": {"start": 0, "end": 11, "text": "H"}, "coalesce": "k"})).unwrap(); + s.execute("type.edit", json!({"layer": id, "replace": {"start": 1, "end": 1, "text": "eading\nsecond line"}, "coalesce": "k"})).unwrap(); + assert_eq!(layer_name_of(&s, id), "Heading"); + // Emptied, the name is the default one and keeps following. + s.execute("type.edit", json!({"layer": id, "text": ""})).unwrap(); + assert_eq!(layer_name_of(&s, id), "Type Layer"); + s.execute("type.edit", json!({"layer": id, "text": "Title"})).unwrap(); + assert_eq!(layer_name_of(&s, id), "Title"); + assert!(s.undo()); + assert_eq!(layer_name_of(&s, id), "Type Layer"); +} + +#[test] +fn size_keys_step_each_run_and_respect_layer_scale() { + let mut s = session(); + let id = s.execute("type.create", json!({"x": 0, "y": 40, "text": "Hello world", "size": 12})).unwrap()["layer"].as_u64().unwrap(); + s.execute("type.setStyle", json!({"layer": id, "range": [6, 11], "size": 20})).unwrap(); + s.execute("type.increaseSize", json!({})).unwrap(); + let sizes = |s: &Session| text_layer(s, id).char_runs().iter().map(|r| r.style.size_pt).collect::>(); + assert_eq!(sizes(&s), vec![14.0, 22.0], "every run grows by 2 pt"); + s.execute("type.decreaseSizeMore", json!({"range": [0, 5]})).unwrap(); + assert_eq!(sizes(&s)[0], 4.0, "only the range, by 10 pt"); + for _ in 0..2 { + s.execute("type.decreaseSize", json!({"range": [0, 5]})).unwrap(); + } + assert_eq!(sizes(&s)[0], TYPE_SIZE_MIN_PT as f32, "never below the smallest size"); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(sizes(&s)[0], 2.0, "one undo step per press"); + + let scaled = s.execute("type.create", json!({"x": 0, "y": 80, "text": "Big", "size": 12})).unwrap()["layer"].as_u64().unwrap(); + s.execute("type.edit", json!({"layer": scaled, "transform": [2.0, 0.0, 0.0, 2.0, 0.0, 80.0]})).unwrap(); + s.execute("type.increaseSize", json!({"layer": scaled})).unwrap(); + assert_eq!(text_layer(&s, scaled).char_runs()[0].style.size_pt, 13.0, "a 200% layer shows 24 pt and steps to 26 pt"); +} + +#[test] +fn size_keys_need_a_type_layer() { + let mut s = session(); + assert!(s.execute("type.increaseSize", json!({})).is_err()); + let id = s.execute("type.create", json!({"x": 0, "y": 40, "text": "Hi", "size": 12})).unwrap()["layer"].as_u64().unwrap(); + s.execute("type.increaseSize", json!({"by": "big"})).unwrap(); + s.execute("type.increaseSize", json!({"by": -3})).unwrap(); + s.execute("type.decreaseSize", json!({"by": 1e30, "range": [9, 0]})).unwrap(); + assert_eq!(text_layer(&s, id).char_runs()[0].style.size_pt, TYPE_SIZE_MIN_PT as f32, "bad steps fall back or clamp, never panic"); + assert_eq!(crate::commands::find("type.increaseSize").and_then(|c| c.shortcut), Some("Cmd+Shift+.")); + assert_eq!(crate::commands::find("type.decreaseSize").and_then(|c| c.shortcut), Some("Cmd+Shift+,")); +} + +#[test] +fn auto_name_skips_leading_blank_lines() { + let mut s = session(); + let id = s.execute("type.create", json!({"x": 0, "y": 40, "text": "\n \nHello\nworld"})).unwrap()["layer"].as_u64().unwrap(); + assert_eq!(layer_name_of(&s, id), "Hello"); + s.execute("type.edit", json!({"layer": id, "replace": {"start": 0, "end": 0, "text": "\n"}})).unwrap(); + s.execute("type.edit", json!({"layer": id, "text": "\n\nGoodbye"})).unwrap(); + assert_eq!(layer_name_of(&s, id), "Goodbye"); +} + +#[test] +fn custom_name_survives_text_edits() { + let mut s = session(); + let id = s.execute("type.create", json!({"x": 0, "y": 40, "text": "Hello", "name": "Logo"})).unwrap()["layer"].as_u64().unwrap(); + s.execute("type.edit", json!({"layer": id, "text": "Goodbye"})).unwrap(); + assert_eq!(layer_name_of(&s, id), "Logo"); + // Renamed after creation: kept too. + let id = s.execute("type.create", json!({"x": 0, "y": 80, "text": "Hello"})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.renameLayer", json!({"layer": id, "name": "Caption"})).unwrap(); + s.execute("type.edit", json!({"layer": id, "text": "Goodbye"})).unwrap(); + assert_eq!(layer_name_of(&s, id), "Caption"); + // A name given with the edit wins over the text. + s.execute("type.edit", json!({"layer": id, "text": "Again", "name": "Footer"})).unwrap(); + assert_eq!(layer_name_of(&s, id), "Footer"); +} + +#[test] +fn edit_with_name_is_one_undo_step_for_text_name_and_bounds() { + let mut s = session(); + let id = s.execute("type.create", json!({"x": 10, "y": 50, "text": "Before", "size": 20, "name": "Original"})).unwrap()["layer"].as_u64().unwrap(); + let layer = s.active().unwrap().doc.layer(LayerId(id)).unwrap(); + let before_bounds = text_layer(&s, id).cache.unwrap().content_bounds(); + assert_eq!(layer.name, "Original"); + let steps = s.active().unwrap().history.entries().len(); + + s.execute("type.edit", json!({"layer": id, "text": "A much longer edited title that wraps", "box": [10, 10, 50, 60], "name": "Renamed"})).unwrap(); + + let edited = s.active().unwrap().doc.layer(LayerId(id)).unwrap(); + let edited_bounds = text_layer(&s, id).cache.unwrap().content_bounds(); + assert_eq!(edited.name, "Renamed"); + assert_eq!(text_layer(&s, id).text, "A much longer edited title that wraps"); + assert_ne!(edited_bounds, before_bounds); + assert_eq!(s.active().unwrap().history.entries().len(), steps + 1); + + assert!(s.undo()); + let restored = s.active().unwrap().doc.layer(LayerId(id)).unwrap(); + assert_eq!(restored.name, "Original"); + assert_eq!(text_layer(&s, id).text, "Before"); + assert_eq!(text_layer(&s, id).cache.unwrap().content_bounds(), before_bounds); +} + +#[test] +fn edit_replace_keeps_styles() { + let mut s = session(); + let id = s.execute("type.create", json!({"x": 0, "y": 40, "text": "Hello world"})).unwrap()["layer"].as_u64().unwrap(); + s.execute("type.setStyle", json!({"layer": id, "range": [6, 11], "fauxBold": true, "color": [0, 0, 1]})).unwrap(); + let t = text_layer(&s, id); + assert_eq!(t.runs.len(), 2); + assert_eq!(t.runs[0].len, 6); + assert!(t.runs[1].style.faux_bold); + // Insert inside the bold word: inherits bold. + s.execute("type.edit", json!({"layer": id, "replace": {"start": 8, "end": 8, "text": "XX"}})).unwrap(); + let t = text_layer(&s, id); + assert_eq!(t.text, "Hello woXXrld"); + assert_eq!(t.runs[1].len, 7); + // Delete across the style boundary. + s.execute("type.edit", json!({"layer": id, "replace": {"start": 3, "end": 8, "text": ""}})).unwrap(); + let t = text_layer(&s, id); + assert_eq!(t.text, "HelXXrld"); + assert_eq!(t.runs.iter().map(|r| r.len).collect::>(), vec![3, 5]); + // Whole-text replace with a multi-byte string. + let info = s.execute("type.edit", json!({"layer": id, "text": "Größe ✓\nzwei"})).unwrap(); + assert_eq!(info["lines"].as_array().unwrap().len(), 2); + let t = text_layer(&s, id); + assert_eq!(t.runs.iter().map(|r| r.len).sum::(), t.text.len()); +} + +#[test] +fn all_locked_type_edit_rejects_text_replacement_without_history() { + let mut s = session(); + let id = s.execute("type.create", json!({"x": 20, "y": 20, "text": "a", "size": 12})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.setProps", json!({"layer": id, "locked": true})).unwrap(); + let history = s.active().unwrap().history.past_len(); + + let result = s.execute("type.edit", json!({"layer": id, "text": "b"})); + assert!(matches!(&result, Err(EngineError::Other(message)) if message.contains("locked")), "{result:?}"); + assert_eq!(text_layer(&s, id).text, "a"); + assert_eq!(s.active().unwrap().history.past_len(), history); + + s.execute("layer.setProps", json!({"layer": id, "locked": false})).unwrap(); + let history = s.active().unwrap().history.past_len(); + s.execute("type.edit", json!({"layer": id, "text": "b"})).unwrap(); + assert_eq!(text_layer(&s, id).text, "b"); + assert_eq!(s.active().unwrap().history.past_len(), history + 1); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(text_layer(&s, id).text, "a"); + assert_eq!(s.active().unwrap().history.past_len(), history); +} + +#[test] +fn all_locked_type_layer_rejects_formatting_without_history() { + let mut s = session(); + let id = s.execute("type.create", json!({"x": 20, "y": 20, "text": "a", "size": 12})).unwrap()["layer"].as_u64().unwrap(); + let other = s.execute("type.create", json!({"x": 20, "y": 60, "text": "b", "size": 12})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.setProps", json!({"layer": id, "locked": true})).unwrap(); + let before = text_layer(&s, id); + let history = s.active().unwrap().history.past_len(); + + for (cmd, p) in [ + ("type.setStyle", json!({"layer": id, "size": 40, "fauxBold": true})), + ("type.setStyle", json!({"layers": [other, id], "size": 40})), + ("type.warpText", json!({"layer": id, "style": "arc"})), + ("type.antiAlias.none", json!({"layer": id})), + ("type.orientation.vertical", json!({"layer": id})), + ("type.openType.swash", json!({"layer": id})), + ] { + let result = s.execute(cmd, p); + assert!(matches!(&result, Err(EngineError::Other(message)) if message.contains("locked")), "{cmd}: {result:?}"); + } + assert_eq!(text_layer(&s, id), before); + assert_eq!(text_layer(&s, other).size_pt, 12.0); + assert_eq!(s.active().unwrap().history.past_len(), history); + + s.execute("layer.setProps", json!({"layer": id, "locked": false})).unwrap(); + s.execute("type.setStyle", json!({"layer": id, "size": 40})).unwrap(); + assert_eq!(text_layer(&s, id).size_pt, 40.0); +} + +#[test] +fn trailing_empty_paragraph_styles_without_changing_previous_lines() { + let mut s = session(); + let id = s.execute("type.create", json!({"text":"a\nb\n","x":20,"y":20,"size":12,"font":"Inter","align":"left"})).unwrap()["layer"].as_u64().unwrap(); + let before = s.execute("type.info", json!({"layer":id})).unwrap(); + let previous_line = before["lines"][1].clone(); + + let styled = s.execute("type.setStyle", json!({"layer":id,"range":[4,4],"align":"right"})).unwrap(); + assert_eq!(styled["paragraphs"].as_array().unwrap().len(), 2); + assert_eq!(styled["paragraphs"][0]["start"], 0); + assert_eq!(styled["paragraphs"][0]["end"], 4); + assert_eq!(styled["paragraphs"][0]["style"]["align"], "Left"); + assert_eq!(styled["paragraphs"][1]["start"], 4); + assert_eq!(styled["paragraphs"][1]["end"], 4); + assert_eq!(styled["paragraphs"][1]["style"]["align"], "Right"); + assert_eq!(styled["lines"][1], previous_line, "the preceding paragraph must not move"); + let raw = text_layer(&s, id).psd_raw.clone().unwrap(); + let round_trip = photocraft_text::psd::text_layer_from_tysh(&raw, 72.0).unwrap(); + assert_eq!(round_trip.paragraph_runs().last().unwrap().style.align, TextAlign::Right); + + // Typing directly into the previously empty final paragraph retains its style. + let edited = s.execute("type.edit", json!({"layer":id,"replace":{"start":4,"end":4,"text":"c"}})).unwrap(); + assert_eq!(edited["text"], "a\nb\nc"); + assert_eq!(edited["paragraphs"][0]["end"], 4); + assert_eq!(edited["paragraphs"][0]["style"]["align"], "Left"); + assert_eq!(edited["paragraphs"][1]["start"], 4); + assert_eq!(edited["paragraphs"][1]["end"], 5); + assert_eq!(edited["paragraphs"][1]["style"]["align"], "Right"); + assert_eq!(edited["lines"][1], previous_line, "typing in the final paragraph does not move b"); +} + +#[test] +fn set_style_paragraph_and_box() { + let mut s = session(); + let id = + s.execute("type.create", json!({"box": [10, 10, 80, 80], "text": "one two three four five six seven", "size": 12})).unwrap()["layer"].as_u64().unwrap(); + let info = s.execute("type.setStyle", json!({"layer": id, "align": "center", "leading": 20})).unwrap(); + let lines = info["lines"].as_array().unwrap(); + assert!(lines.len() >= 3); + let b0 = lines[0]["baseline"].as_f64().unwrap(); + let b1 = lines[1]["baseline"].as_f64().unwrap(); + assert!((b1 - b0 - 20.0).abs() < 1e-3, "explicit leading {b0} {b1}"); + assert_eq!(info["paragraphs"][0]["style"]["align"], "Center"); + let t = text_layer(&s, id); + assert!(matches!(t.shape, TextShape::Box { width, .. } if width == 80.0)); + // Pixels stay inside the box horizontally. + let r = t.cache.as_ref().unwrap().content_bounds(); + assert!(r.x0 >= 9 && r.x1 <= 91, "{r:?}"); + // Convert to point text and move. + s.execute("type.edit", json!({"layer": id, "point": [5, 30]})).unwrap(); + s.execute("type.edit", json!({"layer": id, "move": [10, 0]})).unwrap(); + let t = text_layer(&s, id); + assert_eq!(t.shape, TextShape::Point); + assert_eq!(t.transform.m[4], 15.0); +} + +#[test] +fn rasterize_and_fonts() { + let mut s = session(); + let id = s.execute("type.create", json!({"x": 5, "y": 30, "text": "Raster"})).unwrap()["layer"].as_u64().unwrap(); + s.execute("type.rasterize", json!({"layer": id})).unwrap(); + let l = s.active().unwrap().doc.layer(LayerId(id)).unwrap(); + assert!(matches!(l.content, LayerContent::Raster(_))); + assert!(l.surface().unwrap().content_bounds().width() > 10); + assert!(s.execute("type.edit", json!({"layer": id, "text": "x"})).is_err()); + let fonts = s.execute("type.fonts", json!({})).unwrap(); + assert!(fonts["families"].as_array().unwrap().iter().any(|f| f == "Inter")); + let faces = s.execute("type.fonts", json!({"family": "Inter"})).unwrap(); + assert!(!faces["faces"].as_array().unwrap().is_empty()); +} + +/// #124: a type edit damages only the layer's old and new pixels (the canvas recomposites +/// that, not the document), and a drag's coalesced steps are one history step. +#[test] +fn type_edits_damage_only_the_layer_and_coalesce() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 3000, "height": 2000})).unwrap(); + let id = s.execute("type.create", json!({"x": 100, "y": 100, "text": "Hi", "size": 20})).unwrap()["layer"].as_u64().unwrap(); + let steps = s.active().unwrap().history.entries().len(); + for k in 0..5 { + s.execute("type.setStyle", json!({"layer": id, "size": 30 + k * 10, "coalesce": "drag"})).unwrap(); + let d = s.active().unwrap().last_damage.expect("damage rect"); + let r = text_layer(&s, id).cache.unwrap().content_bounds(); + assert!(d.intersect(&r) == r && d.width() <= 512 && d.height() <= 512, "{d:?} {r:?}"); + } + assert_eq!(s.active().unwrap().history.entries().len(), steps + 1); + assert!(s.undo()); + assert_eq!(text_layer(&s, id).runs[0].style.size_pt, 20.0); +} + +#[test] +fn edit_rejects_a_reversed_runs_range() { + let mut s = session(); + let id = s.execute("type.create", json!({"x": 0, "y": 40, "text": "Hello world", "size": 20})).unwrap()["layer"].as_u64().unwrap(); + let before = text_layer(&s, id).char_runs(); + let steps = s.active().unwrap().history.entries().len(); + for runs in [ + json!([{"start": 5, "end": 2, "fauxBold": true}]), + json!([{"start": 0, "end": 3, "fauxBold": true}, {"start": 8, "end": 7}]), + json!([{"end": 0, "start": 1}]), + ] { + let e = s.execute("type.edit", json!({"layer": id, "runs": runs})).unwrap_err(); + assert!(matches!(e, EngineError::BadParams { .. }) && e.to_string().contains("is before `start`"), "{e}"); + } + // Nothing changed and nothing was recorded, not even the valid run before the bad one. + assert_eq!(text_layer(&s, id).char_runs(), before); + assert_eq!(s.active().unwrap().history.entries().len(), steps); + // The same range the right way round still styles it. + s.execute("type.edit", json!({"layer": id, "runs": [{"start": 2, "end": 5, "fauxBold": true}]})).unwrap(); + let runs = text_layer(&s, id).char_runs(); + assert_eq!(runs.iter().map(|r| (r.len, r.style.faux_bold)).collect::>(), [(2, false), (3, true), (6, false)]); +} + +#[test] +fn style_range_reversed_is_a_no_op() { + let mut t = TextLayer::default(); + replace_text(&mut t, 0, 0, "Hello world"); + let before = t.char_runs(); + style_range(&mut t, 5, 2, &|s| s.size_pt = 40.0); + assert_eq!(t.char_runs(), before); + assert_eq!(t.runs.iter().map(|r| r.len).sum::(), t.text.len()); +} + +#[test] +fn style_range_on_empty_text() { + let mut t = TextLayer::default(); + style_range(&mut t, 0, 0, &|s| s.size_pt = 40.0); + assert_eq!(t.runs[0].style.size_pt, 40.0); + replace_text(&mut t, 0, 0, "abc"); + assert_eq!(t.runs.len(), 1); + assert_eq!(t.runs[0].len, 3); + assert_eq!(t.runs[0].style.size_pt, 40.0); +} + +/// Replacing a selected smaller second line (by typing or pasting) keeps its size, not the +/// first line's, whose line break precedes the selection. +#[test] +fn replacing_a_selection_keeps_its_first_characters_style() { + let mut s = session(); + let id = s.execute("type.create", json!({"x": 5, "y": 50, "text": "BIG\nsmall", "size": 40})).unwrap()["layer"].as_u64().unwrap(); + s.execute("type.edit", json!({"layer": id, "runs": [{"start": 4, "end": 9, "size": 12}]})).unwrap(); + s.execute("type.edit", json!({"layer": id, "replace": {"start": 4, "end": 9, "text": "AIR"}})).unwrap(); + let sizes = |s: &Session| text_layer(s, id).char_runs().iter().map(|r| (r.len, r.style.size_pt)).collect::>(); + assert_eq!(text_layer(&s, id).text, "BIG\nAIR"); + assert_eq!(sizes(&s), [(4, 40.0), (3, 12.0)]); + // A mixed selection takes its first character's style. + s.execute("type.edit", json!({"layer": id, "replace": {"start": 2, "end": 6, "text": "xy"}})).unwrap(); + assert_eq!(sizes(&s), [(4, 40.0), (1, 12.0)]); + // Inserting at a caret still follows the character before it. + s.execute("type.edit", json!({"layer": id, "replace": {"start": 4, "end": 4, "text": "!"}})).unwrap(); + assert_eq!(sizes(&s), [(5, 40.0), (1, 12.0)]); +} + +/// A misspelt `baseline` is an error and keeps superscript, instead of resetting it to Normal. +#[test] +fn unknown_baseline_is_rejected_and_keeps_the_style() { + let mut s = session(); + let id = s.execute("type.create", json!({"x": 5, "y": 50, "text": "x2", "size": 30})).unwrap()["layer"].as_u64().unwrap(); + s.execute("type.setStyle", json!({"layer": id, "range": [1, 2], "baseline": "superscript"})).unwrap(); + let before = text_layer(&s, id).runs; + for b in [json!("superscipt"), json!("Superscript"), json!(1)] { + assert!(matches!(s.execute("type.setStyle", json!({"layer": id, "baseline": b})), Err(EngineError::BadParams { .. })), "{b}"); + assert!(s.execute("type.edit", json!({"layer": id, "baseline": b})).is_err(), "{b}"); + assert!(s.execute("type.create", json!({"x": 0, "y": 10, "text": "a", "baseline": b})).is_err(), "{b}"); + } + assert_eq!(text_layer(&s, id).runs, before); + s.execute("type.setStyle", json!({"layer": id, "baseline": "normal"})).unwrap(); + assert!(text_layer(&s, id).char_runs().iter().all(|r| r.style.baseline == FontBaseline::Normal)); +} + +fn kerning_of(s: &Session, id: u64) -> Vec<(Kerning, f32)> { + let t = text_layer(s, id); + let mut out = Vec::new(); + let mut at = 0; + for r in t.char_runs() { + out.extend(std::iter::repeat_n((r.style.kerning, r.style.kern), t.text[at..at + r.len].chars().count())); + at += r.len; + } + out +} + +/// #8489: `type.edit {"text"}` changes only what differs, so the rest keeps its styles: an +/// added character takes the style beside it, and a change inside one run stays in it. +#[test] +fn edit_text_keeps_the_styles_of_unchanged_text() { + // (characters, colour) per run. + fn runs(s: &Session, id: u64) -> Vec<(usize, [u8; 4])> { + let t = text_layer(s, id); + let mut at = 0; + t.char_runs() + .into_iter() + .map(|r| { + let n = t.text[at..at + r.len].chars().count(); + at += r.len; + (n, r.style.color.to_rgba8()) + }) + .collect() + } + let (dark, purple) = ([0x1b, 0x1f, 0x4b, 255], [0x5a, 0x3d, 0xf0, 255]); + let mut s = session(); + let id = s.execute("type.create", json!({"x": 20, "y": 50, "text": "Craft Suite in Workshop", "size": 40, "color": "#1b1f4b"})).unwrap()["layer"] + .as_u64() + .unwrap(); + s.execute("type.setStyle", json!({"layer": id, "range": [15, 23], "color": "#5a3df0"})).unwrap(); + assert_eq!(runs(&s, id), [(15, dark), (8, purple)]); + s.execute("type.edit", json!({"layer": id, "text": "Craft Suite in Workshop!"})).unwrap(); + assert_eq!(runs(&s, id), [(15, dark), (9, purple)], "the added character joins the last run"); + s.execute("type.edit", json!({"layer": id, "text": "Craft Suite in Worksh\u{f6}p!"})).unwrap(); + assert_eq!(runs(&s, id), [(15, dark), (9, purple)], "a change inside a run stays in it"); + s.execute("type.edit", json!({"layer": id, "text": "Kraft Suite in Worksh\u{f6}p!"})).unwrap(); + assert_eq!(runs(&s, id), [(15, dark), (9, purple)]); + // Replacing everything leaves one style, as before. + s.execute("type.edit", json!({"layer": id, "text": "Hello"})).unwrap(); + assert_eq!(text_layer(&s, id).text, "Hello"); + assert_eq!(runs(&s, id).iter().map(|r| r.0).sum::(), 5); + s.execute("type.edit", json!({"layer": id, "text": ""})).unwrap(); + assert_eq!(text_layer(&s, id).text, ""); + + // Text inserted at the start of a paragraph joins that paragraph, which keeps its style. + let id = s + .execute( + "type.create", + json!({"x": 20, "y": 50, "text": "a +b", "size": 20}), + ) + .unwrap()["layer"] + .as_u64() + .unwrap(); + s.execute("type.setStyle", json!({"layer": id, "range": [2, 3], "align": "right"})).unwrap(); + s.execute( + "type.edit", + json!({"layer": id, "text": "a +Xb"}), + ) + .unwrap(); + let paragraphs: Vec<(usize, photocraft_doc::text::TextAlign)> = text_layer(&s, id).paragraph_runs().into_iter().map(|r| (r.len, r.style.align)).collect(); + assert_eq!(paragraphs.first().map(|p| p.0), Some(2), "{paragraphs:?}"); + assert_eq!(paragraphs.get(1).copied(), Some((2, photocraft_doc::text::TextAlign::Right)), "{paragraphs:?}"); +} + +/// #206: `type.edit {"kerning"}` over a range takes a number (manual, 1/1000 em) or a mode. +#[test] +fn edit_sets_kerning_over_a_range() { + let mut s = session(); + let id = s.execute("type.create", json!({"x": 5, "y": 50, "text": "AVAT", "size": 30})).unwrap()["layer"].as_u64().unwrap(); + s.execute("type.edit", json!({"layer": id, "range": [0, 1], "kerning": 100})).unwrap(); + s.execute("type.edit", json!({"layer": id, "range": [2, 4], "kerning": "optical"})).unwrap(); + assert_eq!(kerning_of(&s, id), vec![(Kerning::Off, 100.0), (Kerning::Metrics, 0.0), (Kerning::Optical, 0.0), (Kerning::Optical, 0.0)]); + s.execute("type.edit", json!({"layer": id, "kerning": "metrics"})).unwrap(); + assert!(kerning_of(&s, id).iter().all(|k| *k == (Kerning::Metrics, 0.0))); + // Runs and setStyle take the same values; type.info reports them. + s.execute("type.edit", json!({"layer": id, "runs": [{"start": 1, "end": 2, "kerning": -50}]})).unwrap(); + s.execute("type.setStyle", json!({"layer": id, "range": [3, 4], "kerning": "off"})).unwrap(); + assert_eq!(kerning_of(&s, id)[1], (Kerning::Off, -50.0)); + assert_eq!(kerning_of(&s, id)[3], (Kerning::Off, 0.0)); + let info = s.execute("type.info", json!({"layer": id})).unwrap(); + assert_eq!(info["runs"][1]["style"]["kern"], json!(-50.0)); +} + +/// Bad kerning params are errors, never panics, and leave the layer alone. +#[test] +fn kerning_params_fail_gracefully() { + let mut s = session(); + let id = s.execute("type.create", json!({"x": 5, "y": 50, "text": "AV\nT", "size": 30})).unwrap()["layer"].as_u64().unwrap(); + let before = text_layer(&s, id); + for p in [ + json!({"kerning": "tight"}), + json!({"kerning": 1e9}), + json!({"kerning": -5000}), + json!({"kerning": true}), + json!({"kerning": [1]}), + json!({"runs": [{"start": 0, "end": 1, "kerning": "x"}]}), + json!({"kernPair": 3}), + json!({"kernPair": {"by": 20}}), + json!({"kernPair": {"at": 1}}), + json!({"kernPair": {"at": 1, "by": "20"}}), + json!({"kernPair": {"at": 1, "by": 1e12}}), + json!({"kernPair": {"at": 0, "by": 20}}), + json!({"kernPair": {"at": 4, "by": 20}}), + json!({"kernPair": {"at": 99, "by": 20}}), + json!({"kernPair": {"at": 2, "by": 20}}), + json!({"kernPair": {"at": 3, "by": 20}}), + json!({"kernPair": {"at": -1, "by": 20}}), + ] { + let mut p = p; + p["layer"] = json!(id); + assert!(s.execute("type.edit", p.clone()).is_err(), "{p}"); + } + assert!(s.execute("type.setStyle", json!({"layer": id, "kerning": "tight"})).is_err()); + assert_eq!(text_layer(&s, id).runs, before.runs); + // type.create rejects the same values and creates no layer (#994). + let layers = s.active().unwrap().doc.layer_count(); + for k in [json!("tight"), json!(1e9), json!(-5000), json!(true), json!([1])] { + let p = json!({"x": 0, "y": 10, "text": "AV", "kerning": k}); + assert!(s.execute("type.create", p.clone()).is_err(), "{p}"); + } + assert_eq!(s.active().unwrap().doc.layer_count(), layers); + let id = s.execute("type.create", json!({"x": 0, "y": 10, "text": "AV", "kerning": "optical"})).unwrap()["layer"].as_u64().unwrap(); + assert!(kerning_of(&s, id).iter().all(|k| *k == (Kerning::Optical, 0.0))); + let id = s.execute("type.create", json!({"x": 0, "y": 10, "text": "AV", "kerning": -50})).unwrap()["layer"].as_u64().unwrap(); + assert!(kerning_of(&s, id).iter().all(|k| *k == (Kerning::Off, -50.0))); +} + +/// Cost of one Alt+←/→ press (`kernPair`: two measuring layouts + the edit's re-render) on +/// a headline and on a 2000-character paragraph. Release timings for the dev log: +/// `cargo test --release -p photocraft-engine kern_pair_cost -- --ignored --nocapture`. +#[test] +#[ignore] +fn kern_pair_cost() { + let para = "The quick brown fox jumps over the lazy dog. ".repeat(45); + for (name, text, size, bx, kerning) in [ + ("headline", "AVATAR Wave", 72, false, "metrics"), + ("paragraph", para.as_str(), 12, true, "metrics"), + ("optical paragraph", para.as_str(), 12, true, "optical"), + ] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 2000, "height": 1500})).unwrap(); + let mut p = json!({"x": 20, "y": 100, "text": text, "size": size, "font": "Inter", "kerning": kerning}); + if bx { + p["box"] = json!([20, 20, 900, 1400]); + } + let id = s.execute("type.create", p).unwrap()["layer"].as_u64().unwrap(); + let n = 20; + let t0 = std::time::Instant::now(); + for i in 0..n { + s.execute("type.edit", json!({"layer": id, "kernPair": {"at": 1 + i % 3, "by": 20}})).unwrap(); + } + let per = t0.elapsed().as_secs_f64() * 1000.0 / f64::from(n); + let t1 = std::time::Instant::now(); + for i in 0..n { + s.execute("type.setStyle", json!({"layer": id, "range": [1 + i % 3, 2 + i % 3], "tracking": i})).unwrap(); + } + let base = t1.elapsed().as_secs_f64() * 1000.0 / f64::from(n); + eprintln!("{name} ({} chars): kernPair {per:.2} ms/press; a plain style edit {base:.2} ms", text.chars().count()); + } +} + +/// Photoshop's Alt+←/→: the pair before the caret becomes manual, starting from the kerning +/// it shows (the font's pair kerning for "AV"), ±20 per press, one history step each. +#[test] +fn kern_pair_steps_from_the_shown_kerning() { + let mut s = session(); + let id = s.execute("type.create", json!({"x": 5, "y": 50, "text": "AVA", "size": 40, "font": "Inter"})).unwrap()["layer"].as_u64().unwrap(); + let metric = { + let t = text_layer(&s, id); + photocraft_text::shared().lock().unwrap().pair_kerning(&t, 72.0, 0).unwrap() + }; + assert!(metric < -10.0, "Inter kerns AV: {metric}"); + let steps = s.active().unwrap().history.entries().len(); + s.execute("type.edit", json!({"layer": id, "kernPair": {"at": 1, "by": 20}})).unwrap(); + let k0 = kerning_of(&s, id)[0]; + assert_eq!(k0, (Kerning::Off, metric.round() + 20.0)); + s.execute("type.edit", json!({"layer": id, "kernPair": {"at": 1, "by": 100}})).unwrap(); + assert_eq!(kerning_of(&s, id)[0].1, metric.round() + 120.0); + s.execute("type.edit", json!({"layer": id, "kernPair": {"at": 1, "by": -20}})).unwrap(); + assert_eq!(kerning_of(&s, id)[0].1, metric.round() + 100.0); + // Other characters are untouched; each press is its own undoable step. + assert_eq!(&kerning_of(&s, id)[1..], &[(Kerning::Metrics, 0.0), (Kerning::Metrics, 0.0)]); + assert_eq!(s.active().unwrap().history.entries().len(), steps + 3); + assert!(s.undo()); + assert_eq!(kerning_of(&s, id)[0].1, metric.round() + 120.0); + assert!(s.undo() && s.undo()); + assert_eq!(kerning_of(&s, id)[0], (Kerning::Metrics, 0.0)); +} +#[test] +fn create_vertical_type_is_atomic_and_invalid_orientation_is_rejected() { + for boxed in [false, true] { + let mut s = session(); + let before = s.active().unwrap().history.entries().len(); + for orientation in [json!("diagonal"), json!(null), json!(true)] { + assert!(s.execute("type.create", json!({"text": "test", "orientation": orientation})).is_err()); + assert_eq!(s.active().unwrap().history.entries().len(), before); + } + let mut p = json!({"text": "test", "orientation": "vertical", "x": 20, "y": 20}); + if boxed { + p["box"] = json!([20, 20, 80, 60]); + } + let id = s.execute("type.create", p).unwrap()["layer"].as_u64().unwrap(); + let t = text_layer(&s, id); + assert_eq!(t.orientation, Orientation::Vertical); + assert_eq!(matches!(t.shape, TextShape::Box { .. }), boxed); + s.execute("edit.undo", json!({})).unwrap(); + assert!(s.active().unwrap().doc.layer(LayerId(id)).is_none()); + } +} + +#[test] +fn missing_font_emits_warning_in_create_set_style_and_edit() { + let mut s = session(); + let r = s.execute("type.create", json!({"x": 10, "y": 20, "text": "Hello", "font": "NoSuchFamily123"})).unwrap(); + assert_eq!(r["warnings"], json!(["font 'NoSuchFamily123' is not installed; text may render using a fallback face"])); + let id = r["layer"].as_u64().unwrap(); + let styled = s.execute("type.setStyle", json!({"layer": id, "font": "StillNoSuchFamily456"})).unwrap(); + assert_eq!(styled["warnings"], json!(["font 'StillNoSuchFamily456' is not installed; text may render using a fallback face"])); + let edited = s.execute("type.edit", json!({"layer": id, "runs": [{"start": 0, "end": 2, "font": "AnotherMissingFont789"}]})).unwrap(); + assert_eq!( + edited["warnings"], + json!([ + "font 'AnotherMissingFont789' is not installed; text may render using a fallback face", + "font 'StillNoSuchFamily456' is not installed; text may render using a fallback face" + ]) + ); +} + +/// `leadingBy`, `baselineShiftBy` and `trackingBy` step every character from its own value +/// (auto leading from its laid-out value), clamp to Photoshop's ranges, and reject hostile +/// steps without changing anything. +#[test] +fn relative_steps_move_each_character_from_its_own_value() { + let mut s = session(); + let id = s.execute("type.create", json!({"x": 0, "y": 40, "text": "Hello\nworld", "size": 10})).unwrap()["layer"].as_u64().unwrap(); + s.execute("type.setStyle", json!({"layer": id, "range": [8, 11], "leading": 30, "tracking": 50})).unwrap(); + s.execute("type.setStyle", json!({"layer": id, "range": [6, 11], "autoLeading": 150})).unwrap(); + let steps = s.active().unwrap().history.entries().len(); + s.execute("type.setStyle", json!({"layer": id, "range": [0, 11], "leadingBy": 2, "baselineShiftBy": -2, "trackingBy": 20})).unwrap(); + assert_eq!(s.active().unwrap().history.entries().len(), steps + 1, "one history step"); + let t = text_layer(&s, id); + let at = |c: usize| { + let byte = byte_at(&t.text, c); + let mut off = 0; + t.char_runs() + .into_iter() + .find(|r| { + off += r.len; + off > byte + }) + .unwrap() + .style + }; + // Auto leading 120% × 10 pt (first paragraph), 150% × 10 pt (second), and a set 30 pt. + assert_eq!(at(0).leading_pt, Some(14.0)); + assert_eq!(at(6).leading_pt, Some(17.0)); + assert_eq!(at(9).leading_pt, Some(32.0)); + assert_eq!((at(0).baseline_shift_pt, at(9).baseline_shift_pt), (-2.0, -2.0)); + assert_eq!((at(0).tracking, at(9).tracking), (20.0, 70.0)); + // Clamped to the ranges. + s.execute("type.setStyle", json!({"layer": id, "leadingBy": -5000, "baselineShiftBy": 10000, "trackingBy": -11000})).unwrap(); + let t = text_layer(&s, id); + assert!( + t.char_runs().iter().all(|r| r.style.leading_pt == Some(LEADING_MIN_PT) + && r.style.baseline_shift_pt == BASELINE_SHIFT_MAX_PT + && r.style.tracking == TRACKING_MIN as f32) + ); + // A collapsed range in non-empty text changes no character. + let before = text_layer(&s, id).char_runs(); + s.execute("type.setStyle", json!({"layer": id, "range": [3, 3], "trackingBy": 100})).unwrap(); + assert_eq!(text_layer(&s, id).char_runs(), before); + // Hostile steps are refused. + let steps = s.active().unwrap().history.entries().len(); + for bad_step in [json!({"leadingBy": "up"}), json!({"trackingBy": 1e30}), json!({"baselineShiftBy": null}), json!({"leadingBy": [1]})] { + let mut p = bad_step.clone(); + p["layer"] = json!(id); + assert!(matches!(s.execute("type.setStyle", p), Err(EngineError::BadParams { .. })), "{bad_step}"); + } + assert_eq!(s.active().unwrap().history.entries().len(), steps); + // Empty text: the step sets the style the next typed characters get. + let empty = s.execute("type.create", json!({"x": 0, "y": 80, "text": "", "size": 10})).unwrap()["layer"].as_u64().unwrap(); + s.execute("type.setStyle", json!({"layer": empty, "range": [0, 0], "leadingBy": -2})).unwrap(); + assert_eq!(text_layer(&s, empty).char_runs()[0].style.leading_pt, Some(10.0)); +} diff --git a/crates/engine/src/type_extra_cmds.rs b/crates/engine/src/cmd/type_extra_cmds.rs similarity index 100% rename from crates/engine/src/type_extra_cmds.rs rename to crates/engine/src/cmd/type_extra_cmds.rs diff --git a/crates/engine/src/type_extra_cmds/tests.rs b/crates/engine/src/cmd/type_extra_cmds/tests.rs similarity index 100% rename from crates/engine/src/type_extra_cmds/tests.rs rename to crates/engine/src/cmd/type_extra_cmds/tests.rs diff --git a/crates/engine/src/type_mask_cmds.rs b/crates/engine/src/cmd/type_mask_cmds.rs similarity index 100% rename from crates/engine/src/type_mask_cmds.rs rename to crates/engine/src/cmd/type_mask_cmds.rs diff --git a/crates/engine/src/type_spell_cmds.rs b/crates/engine/src/cmd/type_spell_cmds.rs similarity index 100% rename from crates/engine/src/type_spell_cmds.rs rename to crates/engine/src/cmd/type_spell_cmds.rs diff --git a/crates/engine/src/type_styles_cmds.rs b/crates/engine/src/cmd/type_styles_cmds.rs similarity index 100% rename from crates/engine/src/type_styles_cmds.rs rename to crates/engine/src/cmd/type_styles_cmds.rs diff --git a/crates/engine/src/type_styles_cmds/tests.rs b/crates/engine/src/cmd/type_styles_cmds/tests.rs similarity index 100% rename from crates/engine/src/type_styles_cmds/tests.rs rename to crates/engine/src/cmd/type_styles_cmds/tests.rs diff --git a/crates/engine/src/updates_cmds.rs b/crates/engine/src/cmd/updates_cmds.rs similarity index 100% rename from crates/engine/src/updates_cmds.rs rename to crates/engine/src/cmd/updates_cmds.rs diff --git a/crates/engine/src/variables_cmds.rs b/crates/engine/src/cmd/variables_cmds.rs similarity index 100% rename from crates/engine/src/variables_cmds.rs rename to crates/engine/src/cmd/variables_cmds.rs diff --git a/crates/engine/src/variables_cmds/tests.rs b/crates/engine/src/cmd/variables_cmds/tests.rs similarity index 100% rename from crates/engine/src/variables_cmds/tests.rs rename to crates/engine/src/cmd/variables_cmds/tests.rs diff --git a/crates/engine/src/cmd/vector_cmds.rs b/crates/engine/src/cmd/vector_cmds.rs new file mode 100644 index 0000000000..7f3753e24e --- /dev/null +++ b/crates/engine/src/cmd/vector_cmds.rs @@ -0,0 +1,332 @@ +//! Vector commands: shape layers (`shape.*`), document paths (`path.*`, Paths panel), selection ⇄ +//! path, and layer vector masks (`layer.vectorMask.*`). +//! +//! Coordinates are document pixels. Paths in parameters and results use a compact JSON form: +//! +//! ```json +//! {"subpaths":[{"closed":true,"op":"combine|subtract|intersect|exclude", +//! "knots":[[x,y], {"anchor":[x,y],"in":[x,y],"out":[x,y],"smooth":true}, …]}], +//! "fillRule":"nonzero|evenodd", "inverted":false} +//! ``` +//! +//! A knot given as `[x, y]` is a corner with retracted handles; `in`/`out` default to the +//! anchor. The serde form of `photocraft_doc::Path` is accepted too. Colours are `"#rrggbb"`, +//! `"#rrggbbaa"` or `[r,g,b,a]` (0..1); opacities are percentages (0..100). +//! +//! Every edit re-renders the shape layer's cache with `photocraft-vector` in one undoable step. +//! PSD blocks stay byte-identical while they still decode to the model (see `photocraft-io`). + +use photocraft_algo::selection::{self as sel, SelectionMode}; +use photocraft_color::{BlendMode, Color}; +use photocraft_doc::{ + ClippingPath, Document, Fill, FillRule, GradientStyle, Knot, Layer, LayerContent, LayerId, LineCap, LineJoin, LiveShape, NamedPath, Path, PathOp, + ShapeLayer, ShapeStroke, StrokeAlign, Subpath, VectorMask, +}; +use photocraft_geom::{Affine, Point, Rect}; +use photocraft_vector as vector; +use serde_json::{Value, json}; + +use crate::commands::{CommandSpec, blend_from_str}; +use crate::{EngineError, Result, Session}; + +/// Keys PSD uses for a shape layer's vector data; dropped when a shape is rasterized. +const SHAPE_BLOCKS: [&[u8; 4]; 8] = [b"vmsk", b"vsms", b"vogk", b"vstk", b"vscg", b"SoCo", b"GdFl", b"PtFl"]; + +pub(crate) fn bad(cmd: &str, msg: impl Into) -> EngineError { + EngineError::BadParams { cmd: cmd.into(), msg: msg.into() } +} + +pub(crate) fn has_doc(s: &Session) -> std::result::Result<(), String> { + s.active().map(|_| ()).ok_or_else(|| "no document open".into()) +} + +fn has_layer(s: &Session) -> std::result::Result<(), String> { + let d = s.active().ok_or("no document open")?; + d.active_layer.filter(|id| d.doc.layer(*id).is_some()).map(|_| ()).ok_or_else(|| "no active layer".into()) +} + +fn has_selection(s: &Session) -> std::result::Result<(), String> { + s.active().filter(|d| d.doc.selection.is_some()).map(|_| ()).ok_or_else(|| "no selection".into()) +} + +// --------------------------------------------------------------------------- +// Specs +// --------------------------------------------------------------------------- + +/// Params of the Layer › Combine Shapes operations. +const COMBINE_PARAMS: &str = r##"{"layer":id?,"subpath":index? (default all but the first)} (no layer/subpath and two or more shape layers selected: merges them into the top-most, whose components above the bottom layer's take the operation)"##; + +pub(crate) const PATH_FORM: &str = r##"path: {"subpaths":[{"closed":bool=true,"op":"combine|subtract|intersect|exclude","knots":[[x,y] | {"anchor":[x,y],"in":[x,y],"out":[x,y],"smooth":bool}]}],"fillRule":"nonzero|evenodd","inverted":bool}"##; + +macro_rules! spec { + ($id:literal, $label:literal, [$($m:literal),*], $params:expr, $en:expr, $run:expr) => { + CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: None, params: $params, enabled: $en, run: $run, journal: true } + }; +} + +mod params; +mod paths; +mod shape; +mod vector_mask; + +pub(crate) use params::{layer_id, nums, pt}; +pub use params::{parse_path, parse_stroke, path_json}; +pub use paths::STROKE_PATH_TOOLS; +use paths::{ + clipping_path_clear, clipping_path_set, path_delete, path_fill, path_rename, path_set, path_stroke, path_to_selection, path_transform, paths_list, + resolve_path, select_to_work_path, +}; +pub(crate) use paths::{is_work, path_mut}; +use shape::{ + can_paste_shape_fill, can_paste_shape_stroke, combine_shapes, copy_shape_fill, copy_shape_stroke, has_shape_fill, has_shape_stroke, merge_components, + paste_shape_fill, paste_shape_stroke, selection_to_shape, shape_create, shape_edit, shape_info, shape_rasterize, +}; +pub(crate) use shape::{map_path, map_shape, shift_shape, with_shape}; +pub use shape::{preview_shape_stroke, refresh_shape, shape_path, transform_shape, translate_vectors}; +use vector_mask::{toggle_vector_mask, vector_mask_add, vector_mask_delete, vector_mask_edit, vector_mask_info, vector_mask_rasterize, with}; + +pub(crate) fn leak(s: String) -> &'static str { + Box::leak(s.into_boxed_str()) +} + +pub fn specs() -> Vec { + let stroke = r##""stroke":{"width":px,"color":"#rrggbb"|fill,"opacity":0..100,"align":"inside|center|outside","cap":"butt|round|square","join":"miter|round|bevel","miterLimit":n,"dashes":[multiples of width],"dashOffset":n}|null"##; + let fill = r##""fill":"#rrggbb"|[r,g,b,a]|{"gradient":{"stops":[[t,"#hex"|[r,g,b,a]|stored Color]],"angle":deg,"scale":%,"style":"linear|radial|angle|reflected|diamond","reverse":bool,"opacityStops":[[t,0..1]]?,"midpoints":[0..1]?,"offset":[x,y]?,"dither":bool?,"align":bool?}}|{"pattern":name}|null (no fill)"##; + vec![ + spec!( + "shape.create", + "New Shape Layer", + ["Layer", "New"], + leak(format!( + r##"{{"kind":"rect|roundedRect|ellipse|polygon|star|line|path"="rect","rect":[x,y,w,h] (rect/roundedRect/ellipse/polygon/star),"radii":[tl,tr,br,bl]|r (roundedRect=10),"sides":3..100=5,"starRatio":0..1 (star=0.5),"cornerRadius":px=0 (polygon/star: rounds every vertex; the Triangle tool is a 3-sided polygon),"from":[x,y],"to":[x,y],"weight":px=1 (line),"path":{{…}} (kind path),{fill}=foreground,{stroke}=none,"name":str?,"addTo":layerId? + "op":"combine|subtract|intersect|exclude" (append to an existing shape layer)}} → shape.info. {PATH_FORM}"## + )), + has_doc, + shape_create + ), + spec!( + "shape.edit", + "Edit Shape", + [], + leak(format!( + r##"{{"layer":id?,"path":{{…}}? (replaces; drops live shape),"kind":str?,"rect":[x,y,w,h]?,"radii":[tl,tr,br,bl]|r?,"sides":n?,"starRatio":r?,"cornerRadius":px?,"from":[x,y]?,"to":[x,y]?,"weight":px? (live-shape params regenerate the path),"move":[dx,dy]?,"transform":[a,b,c,d,e,f]?,"op":"combine|…"? + "subpath":index? (default all but the first),"fillRule":"nonzero|evenodd"?,{fill}?,{stroke}? (merged into the current stroke),"name":str?}} → shape.info"## + )), + has_layer, + shape_edit + ), + CommandSpec { + id: "shape.info", + label: "Shape Layer Info", + menu: &[], + shortcut: None, + params: r##"{"layer":id?} → {layer,name,kind,path,fill,stroke,live,bounds:[x,y,w,h]}"##, + enabled: has_layer, + run: |s, p| { + let id = layer_id(s, p)?; + shape_info(s, id) + }, + journal: false, + }, + spec!("shape.rasterize", "Rasterize Shape", ["Layer", "Rasterize"], r##"{"layer":id?}"##, has_layer, shape_rasterize), + CommandSpec { + id: "path.list", + label: "List Paths", + menu: &[], + shortcut: None, + params: r##"{} → {paths:[{name,knots,subpaths}],workPath,clippingPath,layerPath (active layer's shape path / vector mask)}"##, + enabled: has_doc, + run: |s, _| paths_list(s), + journal: false, + }, + CommandSpec { + id: "path.info", + label: "Path Info", + menu: &[], + shortcut: None, + params: r##"{"name":str|"work"|"layer"="work"} → {name,path}"##, + enabled: has_doc, + run: |s, p| { + let name = p.get("name").and_then(Value::as_str); + let path = resolve_path(s, name)?; + Ok(json!({ "name": name.unwrap_or("work"), "path": path_json(&path) })) + }, + journal: false, + }, + spec!( + "path.set", + "Set Path", + [], + leak(format!( + r##"{{"name":str|"work"="work","path":{{…}},"op":"combine|subtract|intersect|exclude"? (append to the existing path with this op instead of replacing)}}. {PATH_FORM}"## + )), + has_doc, + path_set + ), + spec!("path.delete", "Delete Path", [], r##"{"name":str|"work"="work"}"##, has_doc, path_delete), + spec!( + "path.transform", + "Free Transform Path", + [], + r##"{"name":str|"work"|"layer"="work","layer":id? (with layer target),"matrix":[a,b,c,d,e,f] | "quad":[[x,y]×4] (Distort/Perspective: where the frame's corners go, clockwise from top-left) | "style"|"mesh"|"warp":… (Warp, as edit.transform.warp) | "translateX":px?,"translateY":px?,"scaleX":factor?,"scaleY":factor?,"angle":degrees?,"rect":[x0,y0,x1,y1]? (the quad's or warp's frame; default = path control bounds)} (numeric transforms pivot on path bounds center)"##, + has_doc, + path_transform + ), + spec!( + "path.clippingPath.set", + "Clipping Path", + [], + r##"{"name":savedPathName,"flatness":0..100=0} (PSD export clipping path)"##, + has_doc, + clipping_path_set + ), + spec!("path.clippingPath.clear", "Clear Clipping Path", [], r##"{}"##, has_doc, clipping_path_clear), + spec!("path.style.copyFill", "Copy Fill", [], r##"{} (copies active shape layer fill)"##, has_shape_fill, copy_shape_fill), + spec!("path.style.copyStroke", "Copy Complete Stroke", [], r##"{} (copies active shape layer stroke)"##, has_shape_stroke, copy_shape_stroke), + spec!( + "path.style.pasteFill", + "Paste Fill", + [], + r##"{"layer":id?} (pastes copied fill onto active shape layer)"##, + can_paste_shape_fill, + paste_shape_fill + ), + spec!( + "path.style.pasteStroke", + "Paste Complete Stroke", + [], + r##"{"layer":id?} (pastes copied stroke onto active shape layer)"##, + can_paste_shape_stroke, + paste_shape_stroke + ), + spec!("path.rename", "Rename Path", [], r##"{"name":str|"work"="work","to":str} (renaming the work path saves it)"##, has_doc, path_rename), + // ⌘↩ / Ctrl+Enter, as in Photoshop (the UI loads the path selected in the Paths panel, #306). + CommandSpec { + id: "path.toSelection", + label: "Make Selection from Path", + menu: &[], + shortcut: Some("Cmd+Enter"), + params: r##"{"name":str|"work"|"layer"="work","feather":px=0,"antiAlias":bool=true,"mode":"replace|add|subtract|intersect"="replace"}"##, + enabled: has_doc, + run: path_to_selection, + journal: true, + }, + spec!("select.toWorkPath", "Make Work Path", [], r##"{"tolerance":0.5..10 px=2} → {subpaths,knots}"##, has_selection, select_to_work_path), + spec!( + "path.fill", + "Fill Path", + [], + r##"{"name":str|"work"|"layer"="work","layer":id? (pixel layer, default active),"color":"#rrggbb"=foreground,"opacity":0..100=100,"mode":"normal|multiply|…"="normal","feather":px=0,"antiAlias":bool=true}"##, + has_layer, + path_fill + ), + spec!( + "path.stroke", + "Stroke Path", + [], + r##"{"name":str|"work"|"layer"="work","layer":id? (pixel layer),"tool":"brush|pencil|eraser|backgroundEraser|cloneStamp|patternStamp|healingBrush|spotHealingBrush|historyBrush|blur|sharpen|smudge|dodge|burn|sponge|colorReplacement|mixerBrush"="brush","simulatePressure":bool=false (taper both ends when the brush follows pen pressure),"size":0.5..5000 px?,"hardness":0..1?,"opacity":0..100?,"color":"#rrggbb"=foreground} (current brush settings otherwise; tools past the Eraser run their paint.* command along the path and take its params)"##, + has_layer, + path_stroke + ), + spec!( + "layer.vectorMask.add", + "Add Vector Mask", + ["Layer", "Vector Mask"], + r##"{"layer":id?,"path":{…}? | "name":str|"work"? (copy a document path),"hide":bool=false (Hide All = inverted)} → vector mask info. Without a path the mask reveals all."##, + has_layer, + |s, p| vector_mask_add(s, p, false) + ), + spec!( + "layer.vectorMask.fromPath", + "Vector Mask from Current Path", + ["Layer", "Vector Mask"], + r##"{"layer":id?,"name":str|"work"="work"}"##, + has_layer, + |s, p| vector_mask_add(s, p, true) + ), + spec!( + "layer.vectorMask.edit", + "Edit Vector Mask", + [], + leak(format!( + r##"{{"layer":id?,"path":{{…}}?,"enabled":bool?,"linked":bool?,"density":0..100?,"feather":0..1000? (pixels),"invert":true?}}. On a shape layer (whose path is its vector mask) only density and feather apply: they soften its fill, which shows beyond the path at 100 − density %. {PATH_FORM}"## + )), + has_layer, + vector_mask_edit + ), + spec!("layer.vectorMask.delete", "Delete Vector Mask", ["Layer", "Vector Mask"], r##"{"layer":id?}"##, has_layer, vector_mask_delete), + spec!( + "layer.rasterize.vectorMask", + "Rasterize Vector Mask", + [], + r##"{"layer":id?} (multiplied into the layer mask)"##, + has_layer, + vector_mask_rasterize + ), + // Menu ids of Photoshop's Layer › Vector Mask / Rasterize / Combine Shapes. + spec!("layer.vectorMask.revealAll", "Vector Mask: Reveal All", [], r##"{"layer":id?}"##, has_layer, |s, p| vector_mask_add( + s, + &with(p, "hide", json!(false)), + false + )), + spec!("layer.vectorMask.hideAll", "Vector Mask: Hide All", [], r##"{"layer":id?}"##, has_layer, |s, p| vector_mask_add( + s, + &with(p, "hide", json!(true)), + false + )), + spec!("layer.vectorMask.currentPath", "Vector Mask: Current Path", [], r##"{"layer":id?,"name":str|"work"="work"}"##, has_layer, |s, p| { + vector_mask_add(s, p, true) + }), + spec!("layer.vectorMask.enabled", "Enable Vector Mask", [], r##"{"layer":id?,"enabled":bool? (default: toggle)}"##, has_layer, |s, p| { + toggle_vector_mask(s, p, "enabled") + }), + spec!("layer.vectorMask.linked", "Link Vector Mask", [], r##"{"layer":id?,"linked":bool? (default: toggle)}"##, has_layer, |s, p| toggle_vector_mask( + s, p, "linked" + )), + // Without `layer`, every selected shape layer (the shared Rasterize logic calls back here with one). + spec!("layer.rasterize.shape", "Rasterize Shape", [], r##"{"layer":id?} (no layer: every selected shape layer)"##, has_layer, |s, p| { + if p.get("layer").is_some() { shape_rasterize(s, p) } else { crate::extra_cmds::rasterize(s, p, Some("shape")) } + }), + // With two or more shape layers selected (and no `layer`/`subpath`), these merge them into + // the top-most one, as in Photoshop; with one, they set the operation of its components. + spec!("layer.combineShapes.unite", "Unite Shapes", [], COMBINE_PARAMS, has_layer, |s, p| combine_shapes(s, p, "combine", "Unite Shapes")), + spec!("layer.combineShapes.subtractFrontShape", "Subtract Front Shape", [], COMBINE_PARAMS, has_layer, |s, p| combine_shapes( + s, + p, + "subtract", + "Subtract Front Shape" + )), + spec!("layer.combineShapes.intersectShapeAreas", "Intersect Shape Areas", [], COMBINE_PARAMS, has_layer, |s, p| combine_shapes( + s, + p, + "intersect", + "Intersect Shape Areas" + )), + spec!("layer.combineShapes.excludeOverlappingShapes", "Exclude Overlapping Shapes", [], COMBINE_PARAMS, has_layer, |s, p| { + combine_shapes(s, p, "exclude", "Exclude Overlapping Shapes") + }), + spec!( + "layer.combineShapes.mergeShapeComponents", + "Merge Shape Components", + [], + r##"{"layer":id?,"tolerance":px=0.1} (bakes the path operations into plain combined outlines, traced from the exact coverage; no layer and several shape layers selected: merges them into the top-most first)"##, + has_layer, + merge_components + ), + spec!("select.convertToShape", "Convert to Shape", [], r##"{"tolerance":0.5..10 px=2} → shape.info"##, has_selection, selection_to_shape), + CommandSpec { + id: "layer.vectorMask.info", + label: "Vector Mask Info", + menu: &[], + shortcut: None, + params: r##"{"layer":id?} → {layer,path,enabled,linked,density,feather}"##, + enabled: has_layer, + run: |s, p| { + let id = layer_id(s, p)?; + vector_mask_info(s, id) + }, + journal: false, + }, + ] +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/vector_cmds/params.rs b/crates/engine/src/cmd/vector_cmds/params.rs new file mode 100644 index 0000000000..9661877409 --- /dev/null +++ b/crates/engine/src/cmd/vector_cmds/params.rs @@ -0,0 +1,371 @@ +use super::*; + +pub(crate) fn layer_id(s: &Session, p: &Value) -> Result { + match p.get("layer").and_then(Value::as_u64) { + Some(id) => Ok(LayerId(id)), + None => s.active().and_then(|d| d.active_layer).ok_or(EngineError::Other("no active layer".into())), + } +} + +pub(super) fn f64p(p: &Value, k: &str) -> Option { + p.get(k).and_then(Value::as_f64) +} + +pub(crate) fn pt(v: &Value) -> Option { + match v { + Value::Array(a) if a.len() >= 2 => Some(Point::new(a[0].as_f64()?, a[1].as_f64()?)), + Value::Object(_) => Some(Point::new(v.get("x")?.as_f64()?, v.get("y")?.as_f64()?)), + _ => None, + } +} + +pub(crate) fn nums(p: &Value, k: &str) -> Option<[f64; N]> { + let a = p.get(k)?.as_array()?; + if a.len() < N { + return None; + } + let mut out = [0.0; N]; + for (o, v) in out.iter_mut().zip(a) { + *o = v.as_f64()?; + } + Some(out) +} + +/// `[tl, tr, br, bl]` from an array or a single number. +pub(super) fn radii(p: &Value) -> Option<[f64; 4]> { + match p.get("radii").or_else(|| p.get("radius"))? { + Value::Number(n) => n.as_f64().map(|r| [r; 4]), + _ => nums::<4>(p, "radii"), + } +} + +pub(crate) fn color(v: &Value) -> Option { + match v { + Value::Array(a) if a.len() >= 3 => { + let c: Vec = a.iter().map(|x| x.as_f64().unwrap_or(0.0) as f32).collect(); + Some(Color::rgba(c[0], c[1], c[2], c.get(3).copied().unwrap_or(1.0))) + } + Value::String(s) => { + let s = s.trim_start_matches('#'); + let h = |i: usize| s.get(i..i + 2).and_then(|x| u8::from_str_radix(x, 16).ok()).map(|v| f32::from(v) / 255.0); + match s.len() { + 6 => Some(Color::rgb(h(0)?, h(2)?, h(4)?)), + 8 => Some(Color::rgba(h(0)?, h(2)?, h(4)?, h(6)?)), + _ => None, + } + } + // A stored `Color` (mode + components), so a CMYK or Lab gradient stop survives a + // read-modify-write through the shape swatches. + Value::Object(_) => serde_json::from_value::(v.clone()) + .ok() + .filter(|c| c.c.iter().all(|x| x.is_finite()) && c.alpha.is_finite() && (0.0..=1.0).contains(&c.alpha)), + _ => None, + } +} + +fn hex(c: &Color) -> String { + let [r, g, b] = c.to_rgb(); + let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; + if c.alpha < 1.0 { format!("#{:02x}{:02x}{:02x}{:02x}", q(r), q(g), q(b), q(c.alpha)) } else { format!("#{:02x}{:02x}{:02x}", q(r), q(g), q(b)) } +} + +pub(super) fn op_from(s: &str) -> Option { + Some(match s.to_ascii_lowercase().as_str() { + "combine" | "add" | "union" => PathOp::Combine, + "subtract" | "minus" => PathOp::Subtract, + "intersect" => PathOp::Intersect, + "exclude" | "xor" => PathOp::Exclude, + "join" => PathOp::Join, + _ => return None, + }) +} + +fn op_name(op: PathOp) -> &'static str { + match op { + PathOp::Combine => "combine", + PathOp::Subtract => "subtract", + PathOp::Intersect => "intersect", + PathOp::Exclude => "exclude", + PathOp::Join => "join", + } +} + +/// Parses a path from the compact JSON form (or the serde form). +pub fn parse_path(v: &Value) -> std::result::Result { + let subs = v.get("subpaths").and_then(Value::as_array).ok_or("path needs `subpaths`")?; + let mut out = Vec::with_capacity(subs.len()); + for (i, s) in subs.iter().enumerate() { + let knots_v = s.get("knots").and_then(Value::as_array).ok_or(format!("subpath {i} needs `knots`"))?; + let mut knots = Vec::with_capacity(knots_v.len()); + for (j, k) in knots_v.iter().enumerate() { + let knot = if k.is_array() { + let a = pt(k).ok_or(format!("knot {i}.{j}: expected [x, y]"))?; + Knot::corner(a.x, a.y) + } else { + let a = k.get("anchor").and_then(pt).ok_or(format!("knot {i}.{j}: missing anchor"))?; + let get = |keys: &[&str]| keys.iter().find_map(|key| k.get(*key).and_then(pt)); + Knot { + anchor: a, + in_ctrl: get(&["in", "inCtrl", "in_ctrl"]).unwrap_or(a), + out_ctrl: get(&["out", "outCtrl", "out_ctrl"]).unwrap_or(a), + smooth: k.get("smooth").and_then(Value::as_bool).unwrap_or(false), + } + }; + knots.push(knot); + } + let op = match s.get("op").and_then(Value::as_str) { + Some(o) => op_from(o).ok_or(format!("subpath {i}: unknown op `{o}`"))?, + None => PathOp::Combine, + }; + out.push(Subpath { closed: s.get("closed").and_then(Value::as_bool).unwrap_or(true), knots, op }); + } + let fill_rule = match v.get("fillRule").or_else(|| v.get("fill_rule")).and_then(Value::as_str).map(str::to_ascii_lowercase).as_deref() { + Some("evenodd" | "even-odd" | "even_odd") => FillRule::EvenOdd, + _ => FillRule::NonZero, + }; + Ok(Path { subpaths: out, fill_rule, inverted: v.get("inverted").and_then(Value::as_bool).unwrap_or(false) }) +} + +/// The compact JSON form of a path. +pub fn path_json(p: &Path) -> Value { + let a = |q: Point| json!([q.x, q.y]); + json!({ + "subpaths": p.subpaths.iter().map(|s| json!({ + "closed": s.closed, + "op": op_name(s.op), + "knots": s.knots.iter().map(|k| json!({ "anchor": a(k.anchor), "in": a(k.in_ctrl), "out": a(k.out_ctrl), "smooth": k.smooth })).collect::>(), + })).collect::>(), + "fillRule": if p.fill_rule == FillRule::EvenOdd { "evenodd" } else { "nonzero" }, + "inverted": p.inverted, + }) +} + +pub(super) fn fill_json(f: &Fill) -> Value { + match f { + Fill::Solid(c) => json!(hex(c)), + Fill::Gradient { stops, angle, scale, style, reverse, opacity_stops, midpoints, offset, dither, align } => json!({ "gradient": { + "stops": stops.iter().map(|(t, c)| json!([t, hex(c)])).collect::>(), + "angle": angle, "scale": scale * 100.0, "style": format!("{style:?}").to_ascii_lowercase(), "reverse": reverse, + "opacityStops": opacity_stops, "midpoints": midpoints, "offset": [offset.0, offset.1], "dither": dither, "align": align } }), + Fill::Pattern { name, scale, .. } => json!({ "pattern": name, "scale": scale * 100.0 }), + } +} + +/// The most colour stops, opacity stops or midpoints a gradient fill takes, as the gradient stop +/// edits (`gradient.fill.stop`, `gradient.presets.stop`) cap them. +const MAX_GRADIENT_STOPS: usize = 1024; + +/// `"#rrggbb"` / `[r,g,b,a]` / `{"gradient":{"stops":[[t,"#hex"|[r,g,b,a]],…],"angle","scale","style","reverse", +/// "opacityStops":[[t,0..1],…],"midpoints":[0..1,…],"offset":[x,y],"dither","align"}}` / `{"pattern":name,"scale"}`. +/// `null` → `Ok(None)` (no fill). +pub(super) fn parse_fill(v: &Value) -> std::result::Result, String> { + if v.is_null() { + return Ok(None); + } + if let Some(c) = color(v) { + return Ok(Some(Fill::Solid(c))); + } + if let Some(g) = v.get("gradient") { + // Stop lists are capped as `gradient.fill.stop` caps them: more is an error, not a cut. + let list = |key: &str, what: &str| match g.get(key) { + None | Some(Value::Null) => Ok(None), + Some(Value::Array(a)) if a.len() > MAX_GRADIENT_STOPS => Err(format!("too many {what} (max {MAX_GRADIENT_STOPS})")), + Some(Value::Array(a)) => Ok(Some(a)), + Some(_) => Err(format!("gradient `{key}` must be an array")), + }; + let stops: Vec<(f32, Color)> = list("stops", "colour stops")? + .map(|a| a.iter().filter_map(|s| Some((s.get(0)?.as_f64()? as f32, color(s.get(1)?)?))).collect()) + .unwrap_or_else(|| vec![(0.0, Color::BLACK), (1.0, Color::WHITE)]); + let style = match g.get("style").and_then(Value::as_str).unwrap_or("linear") { + "radial" => GradientStyle::Radial, + "angle" => GradientStyle::Angle, + "reflected" => GradientStyle::Reflected, + "diamond" => GradientStyle::Diamond, + _ => GradientStyle::Linear, + }; + let mut fill = Fill::gradient( + stops, + f64p(g, "angle").unwrap_or(90.0) as f32, + f64p(g, "scale").unwrap_or(100.0) as f32 / 100.0, + style, + g.get("reverse").and_then(Value::as_bool).unwrap_or(false), + ); + // The rest of a gradient, so a read-modify-write (the shape swatches) loses nothing. + if let Fill::Gradient { opacity_stops, midpoints, offset, dither, align, .. } = &mut fill { + let unit = |v: &Value| v.as_f64().map(|n| n.clamp(0.0, 1.0) as f32); + if let Some(a) = list("opacityStops", "opacity stops")? { + *opacity_stops = a.iter().filter_map(|s| Some((unit(s.get(0)?)?, unit(s.get(1)?)?))).collect(); + opacity_stops.sort_by(|a, b| a.0.total_cmp(&b.0)); + } + if let Some(a) = list("midpoints", "midpoints")? { + *midpoints = a.iter().filter_map(unit).collect(); + } + if let Some(o) = g.get("offset") { + let at = |i: usize| o.get(i).and_then(Value::as_f64).map(|n| n.clamp(-1000.0, 1000.0) as f32); + *offset = (at(0).ok_or("gradient offset must be [x, y]")?, at(1).ok_or("gradient offset must be [x, y]")?); + } + if let Some(d) = g.get("dither").and_then(Value::as_bool) { + *dither = d; + } + if let Some(a) = g.get("align").and_then(Value::as_bool) { + *align = a; + } + } + return Ok(Some(fill)); + } + if let Some(name) = v.get("pattern").and_then(Value::as_str) { + return Ok(Some(Fill::Pattern { + name: name.into(), + scale: f64p(v, "scale").unwrap_or(100.0) as f32 / 100.0, + id: String::new(), + angle: 0.0, + link: true, + phase: (0.0, 0.0), + })); + } + Err(format!("unrecognised fill {v}")) +} + +pub(super) fn stroke_json(s: &ShapeStroke) -> Value { + json!({ + "width": s.width, "fill": fill_json(&s.paint), "opacity": s.opacity * 100.0, + "align": format!("{:?}", s.align).to_ascii_lowercase(), "cap": format!("{:?}", s.cap).to_ascii_lowercase(), + "join": format!("{:?}", s.join).to_ascii_lowercase(), "miterLimit": s.miter_limit, "dashes": s.dashes, "dashOffset": s.dash_offset, + }) +} + +/// Applies stroke keys onto `base` (`null` → no stroke). +pub fn parse_stroke(v: &Value, base: Option, fg: Color) -> std::result::Result, String> { + if v.is_null() || v.as_bool() == Some(false) { + return Ok(None); + } + if !v.is_object() { + return Err("stroke must be an object or null".into()); + } + for (key, lo, hi) in [("width", 0.0, 1_000_000.0), ("opacity", 0.0, 100.0), ("miterLimit", 1.0, 500.0), ("dashOffset", -1_000_000.0, 1_000_000.0)] { + if let Some(value) = v.get(key) + && !value.as_f64().is_some_and(|n| n.is_finite() && (lo..=hi).contains(&n)) + { + return Err(format!("`{key}` must be a finite number between {lo} and {hi}")); + } + } + for key in ["align", "cap", "join"] { + if v.get(key).is_some_and(|value| !value.is_string()) { + return Err(format!("`{key}` must be a string")); + } + } + let mut s = base.unwrap_or(ShapeStroke { paint: Fill::Solid(fg), ..Default::default() }); + if let Some(w) = f64p(v, "width") { + s.width = w as f32; + } + if let Some(c) = v.get("color").or_else(|| v.get("fill")) { + s.paint = parse_fill(c)?.ok_or("stroke colour cannot be null")?; + } + if let Some(o) = f64p(v, "opacity") { + s.opacity = (o / 100.0) as f32; + } + if let Some(a) = v.get("align").and_then(Value::as_str) { + s.align = match a { + "inside" => StrokeAlign::Inside, + "outside" => StrokeAlign::Outside, + "center" | "centre" => StrokeAlign::Center, + o => return Err(format!("unknown align `{o}`")), + }; + } + if let Some(c) = v.get("cap").and_then(Value::as_str) { + s.cap = match c { + "butt" => LineCap::Butt, + "round" => LineCap::Round, + "square" => LineCap::Square, + o => return Err(format!("unknown cap `{o}`")), + }; + } + if let Some(j) = v.get("join").and_then(Value::as_str) { + s.join = match j { + "miter" => LineJoin::Miter, + "round" => LineJoin::Round, + "bevel" => LineJoin::Bevel, + o => return Err(format!("unknown join `{o}`")), + }; + } + if let Some(m) = f64p(v, "miterLimit") { + s.miter_limit = m as f32; + } + if let Some(d) = v.get("dashes") { + s.dashes = match d { + Value::Null => Vec::new(), + Value::Array(a) if a.len() <= 32 => a + .iter() + .map(|x| { + x.as_f64() + .filter(|n| n.is_finite() && (0.0..=10000.0).contains(n)) + .map(|x| x as f32) + .ok_or_else(|| "dash lengths must be finite numbers between 0 and 10000 widths".to_string()) + }) + .collect::, _>>()?, + _ => return Err("`dashes` must be an array (multiples of the width)".into()), + }; + } + if let Some(o) = f64p(v, "dashOffset") { + s.dash_offset = o as f32; + } + s.validate()?; + Ok(Some(s)) +} + +pub(super) fn live_json(l: &LiveShape) -> Value { + serde_json::to_value(l).unwrap_or(Value::Null) +} + +/// Builds a live shape from `kind` + geometry params. +pub(super) fn live_from_params(cmd: &str, kind: &str, p: &Value, prev: Option<&LiveShape>) -> Result { + let prev_rect = match prev { + Some(LiveShape::Rect { rect, .. } | LiveShape::Ellipse { rect } | LiveShape::Polygon { rect, .. }) => Some(*rect), + _ => None, + }; + let rect = || nums::<4>(p, "rect").or(prev_rect).ok_or_else(|| bad(cmd, "`rect`: [x, y, w, h] is required")); + Ok(match kind { + "rect" | "rectangle" => { + let r = match prev { + Some(LiveShape::Rect { radii, .. }) => *radii, + _ => [0.0; 4], + }; + LiveShape::Rect { rect: rect()?, radii: radii(p).unwrap_or(r) } + } + "roundedRect" | "roundRect" => { + let r = match prev { + Some(LiveShape::Rect { radii, .. }) if radii.iter().any(|v| *v > 0.0) => *radii, + _ => [10.0; 4], + }; + LiveShape::Rect { rect: rect()?, radii: radii(p).unwrap_or(r) } + } + "ellipse" => LiveShape::Ellipse { rect: rect()? }, + "polygon" | "star" => { + let (ps, pr, pc) = match prev { + Some(LiveShape::Polygon { sides, star_ratio, corner_radius, .. }) => (*sides, *star_ratio, *corner_radius), + _ => (5, if kind == "star" { 0.5 } else { 1.0 }, 0.0), + }; + let corner_radius = f64p(p, "cornerRadius").map_or(pc, |v| if v.is_finite() { v.clamp(0.0, 1.0e6) } else { pc }); + let sides = f64p(p, "sides").map_or(ps, |v| v.round().clamp(3.0, 100.0) as u32); + let ratio = f64p(p, "starRatio").map_or(if kind == "star" && pr >= 1.0 { 0.5 } else { pr }, |v| v.clamp(0.01, 1.0)); + LiveShape::Polygon { + rect: rect()?, + sides, + star_ratio: if kind == "polygon" && f64p(p, "starRatio").is_none() { 1.0 } else { ratio }, + corner_radius, + } + } + "line" => { + let (pf, pto, pw) = match prev { + Some(LiveShape::Line { from, to, weight }) => (Some(*from), Some(*to), *weight), + _ => (None, None, 1.0), + }; + LiveShape::Line { + from: nums::<2>(p, "from").or(pf).ok_or_else(|| bad(cmd, "`from`: [x, y] is required"))?, + to: nums::<2>(p, "to").or(pto).ok_or_else(|| bad(cmd, "`to`: [x, y] is required"))?, + weight: f64p(p, "weight").unwrap_or(pw).max(0.0), + } + } + o => return Err(bad(cmd, format!("unknown kind `{o}`"))), + }) +} diff --git a/crates/engine/src/cmd/vector_cmds/paths.rs b/crates/engine/src/cmd/vector_cmds/paths.rs new file mode 100644 index 0000000000..c737ea8d69 --- /dev/null +++ b/crates/engine/src/cmd/vector_cmds/paths.rs @@ -0,0 +1,607 @@ +use super::params::{color, f64p, layer_id, op_from, parse_path, path_json}; +use super::shape::{map_path, map_shape, transform_shape, with_shape}; +use super::*; + +// --------------------------------------------------------------------------- +// Document paths +// --------------------------------------------------------------------------- + +pub(crate) fn is_work(name: Option<&str>) -> bool { + name.is_none_or(|n| n.is_empty() || n.eq_ignore_ascii_case("work") || n == "Work Path") +} + +/// The path a command targets: `"work"`/absent → the work path (falling back to the active +/// layer's shape path or vector mask when there is none), `"layer"` → the active layer's, +/// otherwise a saved path by name. +pub(super) fn resolve_path(s: &Session, name: Option<&str>) -> Result { + let d = s.active().ok_or(EngineError::NoDocument)?; + let layer_path = || -> Option { + let l = d.doc.layer(d.active_layer?)?; + match &l.content { + LayerContent::Shape(sh) => Some(sh.path.clone()), + _ => l.vector_mask.as_ref().map(|v| v.path.clone()), + } + }; + if name == Some("layer") { + return layer_path().ok_or_else(|| EngineError::Other("active layer has no shape path or vector mask".into())); + } + if is_work(name) { + return d.doc.work_path.clone().or_else(layer_path).ok_or_else(|| EngineError::Other("no work path".into())); + } + let n = name.unwrap_or_default(); + d.doc.paths.iter().find(|p| p.name == n).map(|p| p.path.clone()).ok_or_else(|| EngineError::Other(format!("no path named \"{n}\""))) +} + +/// The path an edit targets, except a shape layer's (edit those with [`with_shape`], which +/// re-renders them): `layer`'s vector mask when given, else the work path or a saved path. +pub(crate) fn path_mut<'a>(doc: &'a mut Document, name: &str, layer: Option) -> Result<&'a mut Path> { + if let Some(id) = layer { + let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; + return l.vector_mask.as_mut().map(|vm| &mut vm.path).ok_or_else(|| EngineError::Other("active layer has no shape path or vector mask".into())); + } + if is_work(Some(name)) { + return doc.work_path.as_mut().ok_or_else(|| EngineError::Other("no work path".into())); + } + doc.paths.iter_mut().find(|q| q.name == name).map(|q| &mut q.path).ok_or_else(|| EngineError::Other(format!("no path named \"{name}\""))) +} + +pub(super) fn paths_list(s: &Session) -> Result { + let d = s.active().ok_or(EngineError::NoDocument)?; + let doc = &d.doc; + let knots = |p: &Path| p.subpaths.iter().map(|s| s.knots.len()).sum::(); + let layer = d.active_layer.and_then(|id| doc.layer(id)).and_then(|l| match &l.content { + LayerContent::Shape(sh) => Some(json!({ "kind": "shape", "layer": l.id.0, "name": format!("{} Shape Path", l.name), "knots": knots(&sh.path) })), + _ => { + l.vector_mask.as_ref().map(|v| json!({ "kind": "vectorMask", "layer": l.id.0, "name": format!("{} Vector Mask", l.name), "knots": knots(&v.path) })) + } + }); + Ok(json!({ + "paths": doc.paths.iter().map(|p| json!({ "name": p.name, "knots": knots(&p.path), "subpaths": p.path.subpaths.len() })).collect::>(), + "workPath": doc.work_path.as_ref().map(|p| json!({ "knots": knots(p), "subpaths": p.subpaths.len() })), + "clippingPath": doc.clipping_path.as_ref().map(|c| json!({ "name": c.name, "flatness": c.flatness })), + "layerPath": layer, + })) +} + +pub(super) fn path_set(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "path.set"; + let path = parse_path(p.get("path").ok_or_else(|| bad(CMD, "missing `path`"))?).map_err(|e| bad(CMD, e))?; + let name = p.get("name").and_then(Value::as_str).map(str::to_string); + let append = p.get("op").and_then(Value::as_str).map(|o| op_from(o).ok_or_else(|| bad(CMD, format!("unknown op `{o}`")))).transpose()?; + s.edit(if is_work(name.as_deref()) { "Work Path" } else { "Save Path" }, |doc, _| { + let merge = |old: Option<&Path>, new: Path| match (old, append) { + (Some(o), Some(op)) => { + let mut o = o.clone(); + o.subpaths.extend(new.subpaths.into_iter().map(|mut sp| { + sp.op = op; + sp + })); + o + } + _ => new, + }; + if is_work(name.as_deref()) { + doc.work_path = Some(merge(doc.work_path.as_ref(), path)); + } else { + let n = name.clone().unwrap_or_default(); + match doc.paths.iter_mut().find(|q| q.name == n) { + Some(q) => { + q.path = merge(Some(&q.path), path); + } + None => doc.paths.push(NamedPath { name: n, path, psd_raw: None }), + } + } + Ok(()) + })?; + let path = resolve_path(s, name.as_deref())?; + Ok(json!({ "name": name.unwrap_or_else(|| "work".into()), "path": path_json(&path) })) +} + +pub(super) fn path_delete(s: &mut Session, p: &Value) -> Result { + let name = p.get("name").and_then(Value::as_str).map(str::to_string); + s.edit("Delete Path", |doc, _| { + if is_work(name.as_deref()) { + return doc.work_path.take().map(|_| ()).ok_or_else(|| EngineError::Other("no work path".into())); + } + let n = name.clone().unwrap_or_default(); + let before = doc.paths.len(); + doc.paths.retain(|q| q.name != n); + if doc.paths.len() == before { + return Err(EngineError::Other(format!("no path named \"{n}\""))); + } + if doc.clipping_path.as_ref().is_some_and(|c| c.name == n) { + doc.clipping_path = None; + } + Ok(()) + })?; + Ok(Value::Null) +} + +pub(super) fn clipping_path_set(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "path.clippingPath.set"; + let name = p.get("name").and_then(Value::as_str).filter(|name| !name.is_empty()).ok_or_else(|| bad(CMD, "missing saved path `name`"))?.to_owned(); + let flatness = match p.get("flatness") { + Some(value) => { + value.as_f64().filter(|value| value.is_finite() && (0.0..=100.0).contains(value)).ok_or_else(|| bad(CMD, "`flatness` must be between 0 and 100"))? + as f32 + } + None => 0.0, + }; + s.edit("Clipping Path", |doc, _| { + if !doc.paths.iter().any(|path| path.name == name) { + return Err(EngineError::Other(format!("no saved path named \"{name}\""))); + } + doc.clipping_path = Some(ClippingPath { name: name.clone(), flatness }); + Ok(()) + })?; + Ok(json!({ "name": name, "flatness": flatness })) +} + +pub(super) fn clipping_path_clear(s: &mut Session, _p: &Value) -> Result { + s.edit("Clear Clipping Path", |doc, _| { + doc.clipping_path.take().ok_or_else(|| EngineError::Other("no clipping path".into()))?; + Ok(()) + })?; + Ok(Value::Null) +} + +/// The path `path.transform` edits: `layer`'s shape path or vector mask, else the work path or a +/// saved path. +fn transform_target(s: &Session, name: &str, layer: Option) -> Result { + let Some(id) = layer else { return resolve_path(s, Some(name)) }; + let d = s.active().ok_or(EngineError::NoDocument)?; + let l = d.doc.layer(id).ok_or(EngineError::NoLayer(id))?; + match &l.content { + LayerContent::Shape(sh) => Ok(sh.path.clone()), + _ => l.vector_mask.as_ref().map(|v| v.path.clone()).ok_or_else(|| EngineError::Other("target layer has no shape path or vector mask".into())), + } +} + +/// `n` numbers at `key` (`[x0, y0, x1, y1]` or `[[x, y] × 4]`, flattened): finite, magnitude at +/// most 1000000. `None` when `key` is absent. +fn coords(p: &Value, key: &str, n: usize) -> Result>> { + const CMD: &str = "path.transform"; + let Some(v) = p.get(key) else { return Ok(None) }; + let flat: Vec<&Value> = match v.as_array() { + Some(a) if a.iter().all(Value::is_array) => a.iter().filter_map(Value::as_array).flatten().collect(), + Some(a) => a.iter().collect(), + None => Vec::new(), + }; + let nums: Vec = flat.iter().filter_map(|v| v.as_f64()).filter(|x| x.is_finite() && x.abs() <= 1_000_000.0).collect(); + if flat.len() != n || nums.len() != n { + return Err(bad(CMD, format!("`{key}` must hold {n} finite numbers with magnitude at most 1000000"))); + } + Ok(Some(nums)) +} + +/// How `path.transform` moves the path. +enum PathMap { + Affine(Affine), + /// Distort / Perspective: the box's corners go to a quad. + Projective(photocraft_algo::transform::Homography), + Warp(Box), +} + +pub(super) fn path_transform(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "path.transform"; + let name = p.get("name").and_then(Value::as_str).unwrap_or("work").to_owned(); + let layer_id = if name == "layer" { Some(layer_id(s, p)?) } else { None }; + // The box Distort, Perspective and Warp frame: `rect`, else the path's control bounds. + let frame = |s: &Session| -> Result<[f64; 4]> { + let r = match coords(p, "rect", 4)? { + Some(r) => [r[0], r[1], r[2], r[3]], + None => { + let (x0, y0, x1, y1) = transform_target(s, &name, layer_id)?.control_bounds().ok_or_else(|| bad(CMD, "path has no points to transform"))?; + [x0, y0, x1, y1] + } + }; + if r[2] - r[0] <= 0.0 || r[3] - r[1] <= 0.0 { + return Err(bad(CMD, "`rect` must have a positive width and height (a straight path needs a `rect`)")); + } + Ok(r) + }; + let map = if let Some(values) = p.get("matrix") { + let values = values.as_array().filter(|values| values.len() == 6).ok_or_else(|| bad(CMD, "`matrix` must contain six numbers"))?; + let mut m = [0.0; 6]; + for (slot, value) in m.iter_mut().zip(values) { + *slot = value + .as_f64() + .filter(|number| number.is_finite() && number.abs() <= 1_000_000.0) + .ok_or_else(|| bad(CMD, "matrix entries must be finite numbers with magnitude at most 1000000"))?; + } + PathMap::Affine(Affine { m }) + } else if let Some(q) = coords(p, "quad", 8)? { + // Distort and Perspective (#3027): where the frame's corners go, clockwise from top-left. + let quad = [[q[0], q[1]], [q[2], q[3]], [q[4], q[5]], [q[6], q[7]]]; + let h = photocraft_algo::transform::Homography::rect_to_quad(frame(s)?, quad) + .filter(|h| h.0.iter().all(|v| v.is_finite()) && h.inverse().is_some()) + .ok_or_else(|| bad(CMD, "degenerate quad"))?; + let [a, b, c, d, e, f, g, hh, i] = h.0; + if g.abs() < 1e-12 && hh.abs() < 1e-12 && i.abs() > 1e-12 { + // A parallelogram is affine: a live shape stays live. + PathMap::Affine(Affine { m: [a / i, d / i, b / i, e / i, c / i, f / i] }) + } else { + PathMap::Projective(h) + } + } else if ["warp", "style", "mesh"].iter().any(|key| p.get(*key).is_some()) { + let w = crate::warp_cmds::warp_from_params(CMD, p, frame(s)?)?; + if [w.bend, w.h_distort, w.v_distort].iter().chain(w.bounds.iter()).any(|v| !v.is_finite() || v.abs() > 1_000_000.0) { + return Err(bad(CMD, "warp values must be finite numbers with magnitude at most 1000000")); + } + PathMap::Warp(Box::new(w)) + } else { + let number = |key: &str, default: f64| -> Result { + match p.get(key) { + Some(value) => value + .as_f64() + .filter(|n| n.is_finite() && n.abs() <= 1_000_000.0) + .ok_or_else(|| bad(CMD, format!("`{key}` must be a finite number with magnitude at most 1000000"))), + None => Ok(default), + } + }; + if !["translateX", "translateY", "scaleX", "scaleY", "angle"].iter().any(|key| p.get(*key).is_some()) { + return Err(bad(CMD, "pass `matrix`, `quad`, a warp (`style`, `mesh` or `warp`) or translate/scale/angle parameters")); + } + let (tx, ty) = (number("translateX", 0.0)?, number("translateY", 0.0)?); + let (sx, sy) = (number("scaleX", 1.0)?, number("scaleY", 1.0)?); + let angle = number("angle", 0.0)?; + // An explicit `layer` parameter determines both the transformed path and its pivot (#3062). + let path = transform_target(s, &name, layer_id)?; + let (x0, y0, x1, y1) = path.control_bounds().ok_or_else(|| bad(CMD, "path has no points to transform"))?; + let (cx, cy) = ((x0 + x1) * 0.5, (y0 + y1) * 0.5); + PathMap::Affine( + Affine::translate(-cx, -cy) + .then(&Affine { m: [sx, 0.0, 0.0, sy, 0.0, 0.0] }) + .then(&Affine::rotate(angle.to_radians())) + .then(&Affine::translate(cx + tx, cy + ty)), + ) + }; + let out = match &map { + PathMap::Affine(a) => json!({ "name": name, "matrix": a.m }), + PathMap::Projective(h) => json!({ "name": name, "homography": h.0 }), + PathMap::Warp(_) => json!({ "name": name, "warp": true }), + }; + if let Some(id) = layer_id + && s.active().and_then(|d| d.doc.layer(id)).is_some_and(|layer| matches!(layer.content, LayerContent::Shape(_))) + { + with_shape(s, id, "Transform Path", |shape, _| { + match &map { + PathMap::Affine(a) => transform_shape(shape, a), + PathMap::Projective(h) => map_shape(shape, Some(h), None)?, + PathMap::Warp(w) => map_shape(shape, None, Some(w))?, + } + shape.psd_raw = None; + Ok(()) + })?; + return Ok(out); + } + s.edit("Transform Path", |doc, _| { + let path = path_mut(doc, &name, layer_id)?; + *path = match &map { + PathMap::Affine(a) => path.transform(a), + PathMap::Projective(h) => map_path(path, Some(h), None)?, + PathMap::Warp(w) => map_path(path, None, Some(w))?, + }; + Ok(()) + })?; + Ok(out) +} + +pub(super) fn path_rename(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "path.rename"; + let name = p.get("name").and_then(Value::as_str).map(str::to_string); + let to = p.get("to").and_then(Value::as_str).filter(|t| !t.is_empty()).ok_or_else(|| bad(CMD, "missing `to`"))?.to_string(); + if is_work(Some(&to)) { + return Err(bad(CMD, "`to` cannot name the work path")); + } + s.edit(if is_work(name.as_deref()) { "Save Path" } else { "Rename Path" }, |doc, _| { + if doc.paths.iter().any(|q| q.name == to) { + return Err(EngineError::Other(format!("a path named \"{to}\" already exists"))); + } + if is_work(name.as_deref()) { + // Photoshop: saving the work path turns it into a named path. + let path = doc.work_path.take().ok_or_else(|| EngineError::Other("no work path".into()))?; + doc.paths.push(NamedPath { name: to.clone(), path, psd_raw: None }); + return Ok(()); + } + let n = name.clone().unwrap_or_default(); + let q = doc.paths.iter_mut().find(|q| q.name == n).ok_or_else(|| EngineError::Other(format!("no path named \"{n}\"")))?; + q.name = to.clone(); + if let Some(c) = doc.clipping_path.as_mut() + && c.name == n + { + c.name = to.clone(); + } + Ok(()) + })?; + Ok(json!({ "name": to })) +} + +pub(super) fn path_to_selection(s: &mut Session, p: &Value) -> Result { + let path = resolve_path(s, p.get("name").and_then(Value::as_str))?; + // Validate before rasterizing or touching selection history. An unchecked feather value + // could silently become zero (negative/string), or expand into an excessive blur. + let feather = match p.get("feather") { + None => 0.0, + Some(v) => v + .as_f64() + .filter(|n| n.is_finite() && (0.0..=1000.0).contains(n)) + .ok_or_else(|| bad("path.toSelection", "`feather` must be a finite number within 0..1000"))? as f32, + }; + let aa = match p.get("antiAlias") { + None => true, + Some(Value::Bool(v)) => *v, + _ => return Err(bad("path.toSelection", "`antiAlias` must be a boolean")), + }; + let mode = match p.get("mode") { + None => SelectionMode::Replace, + Some(Value::String(v)) if matches!(v.as_str(), "replace" | "add" | "subtract" | "intersect") => SelectionMode::parse(v), + _ => return Err(bad("path.toSelection", "`mode` must be replace, add, subtract or intersect")), + }; + let area = s.active().ok_or(EngineError::NoDocument)?.doc.bounds(); + let mut mask = vector::fill_rasterizer(&path, vector::DEFAULT_TOLERANCE).render(area); + if !aa { + for v in &mut mask { + *v = if *v >= 0.5 { 1.0 } else { 0.0 }; + } + } + if feather > 0.0 { + mask = sel::feather(&mask, area.width() as usize, area.height() as usize, feather); + } + let selected = s.edit("Make Selection", |doc, _| { + doc.selection = sel::combine(doc.selection.as_ref(), &mask, area, mode); + Ok(doc.selection.is_some()) + })?; + Ok(json!({ "selected": selected })) +} + +pub(super) fn select_to_work_path(s: &mut Session, p: &Value) -> Result { + let tol = f64p(p, "tolerance").unwrap_or(2.0).clamp(0.5, 10.0); + let d = s.active().ok_or(EngineError::NoDocument)?; + let area = d.doc.bounds(); + let sel_surface = d.doc.selection.as_ref().ok_or_else(|| EngineError::Other("no selection".into()))?; + let mask = sel::mask_from_surface(Some(sel_surface), area); + let path = vector::trace::trace_mask(&mask, area, 0.0, tol); + let knots: usize = path.subpaths.iter().map(|s| s.knots.len()).sum(); + let subpaths = path.subpaths.len(); + s.edit("Make Work Path", |doc, _| { + doc.work_path = Some(path); + Ok(()) + })?; + Ok(json!({ "subpaths": subpaths, "knots": knots })) +} + +pub(super) fn path_fill(s: &mut Session, p: &Value) -> Result { + let path = resolve_path(s, p.get("name").and_then(Value::as_str))?; + let fg = s.tools.foreground; + let c = p.get("color").and_then(color).unwrap_or(Color::rgba(fg[0], fg[1], fg[2], fg[3])); + let rgb = c.to_rgb(); + let src = [rgb[0], rgb[1], rgb[2], c.alpha]; + let opacity = (f64p(p, "opacity").unwrap_or(100.0) / 100.0).clamp(0.0, 1.0) as f32; + let mode = p.get("mode").and_then(Value::as_str).and_then(blend_from_str).unwrap_or(BlendMode::Normal); + let feather = f64p(p, "feather").unwrap_or(0.0) as f32; + let aa = p.get("antiAlias").and_then(Value::as_bool).unwrap_or(true); + let id = layer_id(s, p)?; + s.edit("Fill Path", |doc, _| { + let area = doc.bounds(); + let r = vector::fill_rasterizer(&path, vector::DEFAULT_TOLERANCE); + // The feather reaches 3σ = 3 × radius (σ = radius, as in Photoshop), plus a pixel. + let feather_pad = (feather.ceil() as i32).saturating_mul(3).saturating_add(1); + let area = r.pixel_bounds().map_or(area, |b| b.inflate(feather_pad).intersect(&area)); + if area.is_empty() { + return Ok(()); + } + let mut cov = r.render(area); + if !aa { + cov.iter_mut().for_each(|v| *v = if *v >= 0.5 { 1.0 } else { 0.0 }); + } + if feather > 0.0 { + cov = sel::feather(&cov, area.width() as usize, area.height() as usize, feather); + } + // An active selection limits the fill, soft edges included, as every other fill does (#2387). + if let Some(selection) = doc.selection.as_ref() { + let mask = sel::mask_from_surface(Some(selection), area); + cov.iter_mut().zip(&mask).for_each(|(c, m)| *c *= m); + } + let locks = doc.effective_locks(id); + let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; + if locks.pixels || locks.all { + return Err(EngineError::Other(format!("Could not complete your request because the layer \"{}\" is locked", l.name))); + } + let lock = locks.transparency; + let surf = l.surface_mut().ok_or_else(|| EngineError::Other("Fill Path needs a pixel layer".into()))?; + paint_coverage(surf, area, &cov, src, opacity, mode, lock); + Ok(()) + })?; + Ok(Value::Null) +} + +/// Composites `src` × coverage onto a surface over `area` (any pixel format). +fn paint_coverage(surf: &mut photocraft_raster::Surface, area: Rect, cov: &[f32], src: [f32; 4], opacity: f32, mode: BlendMode, lock_alpha: bool) { + let fmt = surf.format(); + let ch = fmt.channels(); + let mut vals = surf.read_region(area); + for (px, c) in vals.chunks_exact_mut(ch).zip(cov) { + if *c <= 0.0 { + continue; + } + let dst = photocraft_raster::to_rgba(&fmt, px); + let mut out = photocraft_compose::psblend::composite(mode, dst, [src[0], src[1], src[2], src[3] * c], opacity); + if lock_alpha { + out[3] = dst[3]; + } + photocraft_raster::from_rgba_into(&fmt, out, px); + } + surf.write_region(area, &vals); + surf.prune(); +} + +/// Stroke Path's brush-based tools besides the Brush, Pencil and Eraser it renders itself: each +/// paints the path with its own `paint.*` command (Photoshop's Stroke Path dialog Tool list). +pub const STROKE_PATH_TOOLS: &[(&str, &str)] = &[ + ("backgroundEraser", "paint.backgroundEraser"), + ("cloneStamp", "paint.cloneStamp"), + ("patternStamp", "paint.patternStamp"), + ("healingBrush", "paint.healingBrush"), + ("spotHealingBrush", "paint.spotHealing"), + ("historyBrush", "paint.historyBrush"), + ("blur", "paint.blur"), + ("sharpen", "paint.sharpen"), + ("smudge", "paint.smudge"), + ("dodge", "paint.dodge"), + ("burn", "paint.burn"), + ("sponge", "paint.sponge"), + ("colorReplacement", "paint.colorReplacement"), + ("mixerBrush", "paint.mixerBrush"), +]; + +/// At most this many points per subpath when Simulate Pressure resamples it. +const MAX_PRESSURE_POINTS: f64 = 200_000.0; + +/// The stroke points along one flattened subpath. With `simulate` (Stroke Path's Simulate +/// Pressure) the subpath is resampled about every pixel and the pressure rises from 0 at its start +/// to full at the middle and falls back to 0 at its end, so a brush whose size or opacity follows +/// pen pressure tapers at both ends, as in Photoshop. Otherwise every point has full pressure. +fn stroke_points(pts: &[(f64, f64)], closed: bool, simulate: bool) -> Vec { + use photocraft_paint::StrokePoint; + let mut line = pts.to_vec(); + if closed && let Some(&first) = pts.first() { + line.push(first); + } + let full = |line: Vec<(f64, f64)>| line.into_iter().map(|(x, y)| StrokePoint::new(x, y, 1.0)).collect(); + if !simulate { + return full(line); + } + let seg = |a: &(f64, f64), b: &(f64, f64)| (b.0 - a.0).hypot(b.1 - a.1); + let total: f64 = line.iter().zip(line.iter().skip(1)).map(|(a, b)| seg(a, b)).sum(); + if !(total.is_finite() && total > 0.0) { + return full(line); + } + let step = (total / MAX_PRESSURE_POINTS).max(1.0); + let pressure = |d: f64| (d / total * std::f64::consts::PI).sin().clamp(0.0, 1.0) as f32; + let mut out = Vec::new(); + let mut walked = 0.0; + for (a, b) in line.iter().zip(line.iter().skip(1)) { + let len = seg(a, b); + let n = (len / step).ceil().clamp(1.0, MAX_PRESSURE_POINTS) as usize; + for i in 0..n { + let t = i as f64 / n as f64; + out.push(StrokePoint::new(a.0 + (b.0 - a.0) * t, a.1 + (b.1 - a.1) * t, pressure(walked + len * t))); + } + walked += len; + } + if let Some(&(x, y)) = line.last() { + out.push(StrokePoint::new(x, y, 0.0)); + } + out +} + +/// Stroke Path with a tool that has its own `paint.*` command: the command runs once per subpath, +/// with the caller's params (size, opacity, the tool's options) and the path's points, all in one +/// history step. Only `path.stroke` itself is journalled, so a recorded action replays it once. +fn stroke_with_command(s: &mut Session, p: &Value, cmd: &str, lines: &[vector::Polyline], simulate: bool) -> Result { + let mut params = p.as_object().cloned().unwrap_or_default(); + for k in ["name", "tool", "simulatePressure", "coalesce"] { + params.remove(k); + } + let journal = s.journal.len(); + let r = crate::analysis_cmds::compound(s, "Stroke Path", |s| { + // The union of what each subpath's command changed; None when one of them didn't say. + let mut dmg = Some(Rect::EMPTY); + for pl in lines { + let pts = stroke_points(&pl.pts, pl.closed, simulate); + if pts.is_empty() { + continue; + } + let mut call = params.clone(); + call.insert("points".into(), Value::Array(pts.iter().map(|q| json!([q.x, q.y, q.pressure])).collect())); + s.execute(cmd, Value::Object(call))?; + let r = s.active().and_then(|d| d.last_damage); + dmg = dmg.zip(r).map(|(a, b)| { + if a.is_empty() { + b + } else if b.is_empty() { + a + } else { + a.union(&b) + } + }); + } + Ok(dmg) + }); + s.journal.truncate(journal); + let dmg = r?; + if let Some(st) = s.active_mut() { + st.last_damage = dmg; + } + let dmg = dmg.unwrap_or_else(|| s.active().map_or(Rect::EMPTY, |d| d.doc.bounds())); + Ok(json!({ "damage": [dmg.x0, dmg.y0, dmg.width(), dmg.height()] })) +} + +pub(super) fn path_stroke(s: &mut Session, p: &Value) -> Result { + let path = resolve_path(s, p.get("name").and_then(Value::as_str))?; + let tool = p.get("tool").and_then(Value::as_str).unwrap_or("brush"); + let simulate = match p.get("simulatePressure") { + None | Some(Value::Null) => false, + Some(v) => v.as_bool().ok_or_else(|| bad("path.stroke", "`simulatePressure` must be true or false"))?, + }; + if let Some(&(_, cmd)) = STROKE_PATH_TOOLS.iter().find(|(t, _)| *t == tool) { + let lines = vector::flatten_path(&path, 0.1); + return stroke_with_command(s, p, cmd, &lines, simulate); + } + let base = s.tools.brush.clone(); + let fg = s.tools.foreground; + let mut brush = photocraft_paint::BrushSettings { + size: f64p(p, "size").map_or(base.size, |v| v as f32), + hardness: f64p(p, "hardness").map_or(base.hardness, |v| v as f32), + opacity: f64p(p, "opacity").map_or(base.opacity, |v| (v / 100.0) as f32), + color: p.get("color").and_then(color).map_or(fg, |c| { + let v = c.to_rgb(); + [v[0], v[1], v[2], c.alpha] + }), + erase: tool == "eraser", + ..base + }; + // The path is the exact geometry: stroke smoothing (a hand-drawing aid) would cut its corners. + brush.smoothing.amount = 0.0; + match tool { + "pencil" => brush.hardness = 1.0, + "brush" | "eraser" => {} + o => { + let tools: Vec<&str> = ["brush", "pencil", "eraser"].into_iter().chain(STROKE_PATH_TOOLS.iter().map(|(t, _)| *t)).collect(); + return Err(bad("path.stroke", format!("unknown tool `{o}` ({})", tools.join("|")))); + } + } + crate::brush_cmds::validate_brush(&brush, "path.stroke")?; + let lines = vector::flatten_path(&path, 0.1); + let id = layer_id(s, p)?; + let bg = s.tools.background; + let dmg = s.edit("Stroke Path", |doc, _| { + let sel = doc.selection.clone(); + let locks = doc.effective_locks(id); + let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; + // Pixel and full locks (the layer's own or a parent group's) refuse the stroke, as Fill Path does (#2388). + if locks.pixels || locks.all { + return Err(EngineError::Other(format!("Could not complete your request because the layer \"{}\" is locked", l.name))); + } + let lock = locks.transparency; + let surf = l.surface_mut().ok_or_else(|| EngineError::Other("Stroke Path needs a pixel layer".into()))?; + let mut brush = brush.clone(); + if brush.erase && lock { + // Locked transparency (e.g. the Background): the Eraser paints the background colour (#76). + brush.erase = false; + brush.color = bg; + } + let mut dmg = Rect::EMPTY; + for pl in &lines { + let pts = stroke_points(&pl.pts, pl.closed, simulate); + if pts.is_empty() { + continue; + } + let r = photocraft_paint::apply_stroke(surf, &photocraft_paint::Stroke { brush: brush.clone(), points: pts }, sel.as_ref(), lock); + dmg = if dmg.is_empty() { r } else { dmg.union(&r) }; + } + Ok(dmg) + })?; + Ok(json!({ "damage": [dmg.x0, dmg.y0, dmg.width(), dmg.height()] })) +} diff --git a/crates/engine/src/cmd/vector_cmds/shape.rs b/crates/engine/src/cmd/vector_cmds/shape.rs new file mode 100644 index 0000000000..70af631e91 --- /dev/null +++ b/crates/engine/src/cmd/vector_cmds/shape.rs @@ -0,0 +1,560 @@ +use super::params::{ + f64p, fill_json, layer_id, live_from_params, live_json, nums, op_from, parse_fill, parse_path, parse_stroke, path_json, radii, stroke_json, +}; +use super::vector_mask::with; +use super::*; + +fn active_shape(s: &Session) -> std::result::Result<&ShapeLayer, String> { + let d = s.active().ok_or("no document open")?; + let id = d.active_layer.ok_or("no active layer")?; + let layer = d.doc.layer(id).ok_or("no active layer")?; + match &layer.content { + LayerContent::Shape(shape) => Ok(shape), + _ => Err("active layer is not a shape layer".into()), + } +} + +pub(super) fn has_shape_fill(s: &Session) -> std::result::Result<(), String> { + active_shape(s)?.fill.as_ref().map(|_| ()).ok_or_else(|| "shape has no fill".into()) +} + +pub(super) fn has_shape_stroke(s: &Session) -> std::result::Result<(), String> { + active_shape(s)?.stroke.as_ref().map(|_| ()).ok_or_else(|| "shape has no stroke".into()) +} + +pub(super) fn can_paste_shape_fill(s: &Session) -> std::result::Result<(), String> { + active_shape(s)?; + s.path_fill_clipboard.as_ref().map(|_| ()).ok_or_else(|| "no shape fill copied".into()) +} + +pub(super) fn can_paste_shape_stroke(s: &Session) -> std::result::Result<(), String> { + active_shape(s)?; + s.path_stroke_clipboard.as_ref().map(|_| ()).ok_or_else(|| "no shape stroke copied".into()) +} + +pub(super) fn copy_shape_fill(s: &mut Session, _p: &Value) -> Result { + let fill = active_shape(s).map_err(EngineError::Other)?.fill.clone().ok_or_else(|| EngineError::Other("shape has no fill".into()))?; + s.path_fill_clipboard = Some(fill); + Ok(Value::Null) +} + +pub(super) fn copy_shape_stroke(s: &mut Session, _p: &Value) -> Result { + let stroke = active_shape(s).map_err(EngineError::Other)?.stroke.clone().ok_or_else(|| EngineError::Other("shape has no stroke".into()))?; + s.path_stroke_clipboard = Some(stroke); + Ok(Value::Null) +} + +pub(super) fn paste_shape_fill(s: &mut Session, p: &Value) -> Result { + let fill = s.path_fill_clipboard.clone().ok_or_else(|| EngineError::Other("no shape fill copied".into()))?; + let id = layer_id(s, p)?; + with_shape(s, id, "Paste Fill", |shape, _| { + shape.fill = Some(fill); + Ok(()) + })?; + shape_info(s, id) +} + +pub(super) fn paste_shape_stroke(s: &mut Session, p: &Value) -> Result { + let stroke = s.path_stroke_clipboard.clone().ok_or_else(|| EngineError::Other("no shape stroke copied".into()))?; + let id = layer_id(s, p)?; + with_shape(s, id, "Paste Complete Stroke", |shape, _| { + shape.stroke = Some(stroke); + Ok(()) + })?; + shape_info(s, id) +} + +/// The path `shape.create` draws for live-shape params `p` (the Shape tools preview it while dragging). +pub fn shape_path(p: &Value) -> Result { + let kind = p.get("kind").and_then(Value::as_str).unwrap_or("rect"); + Ok(vector::shapes::live_path(&live_from_params("shape.create", kind, p, None)?)) +} + +fn live_kind(l: &LiveShape) -> &'static str { + match l { + LiveShape::Rect { radii, .. } if radii.iter().any(|r| *r > 0.0) => "roundedRect", + LiveShape::Rect { .. } => "rect", + LiveShape::Ellipse { .. } => "ellipse", + LiveShape::Polygon { star_ratio, .. } if *star_ratio < 1.0 => "star", + LiveShape::Polygon { .. } => "polygon", + LiveShape::Line { .. } => "line", + } +} + +/// Re-renders a shape layer's cache for `doc` (canvas-clipped, document pixel format). +pub fn refresh_shape(doc: &Document, sh: &mut ShapeLayer) { + sh.cache = Some(vector::render_shape(sh, doc.pixel_format(), doc.bounds())); +} + +/// A staged stroke edit rendered with the same validation and cache refresh as `shape.edit`. +/// The caller owns this snapshot; the session and its history remain untouched. +pub fn preview_shape_stroke(doc: &Document, id: LayerId, params: &Value) -> Result { + let mut result = doc.clone(); + let layer = result.layer_mut(id).ok_or(EngineError::NoLayer(id))?; + let LayerContent::Shape(shape) = &mut layer.content else { + return Err(EngineError::Other("preview target is not a shape layer".into())); + }; + shape.stroke = parse_stroke(params, shape.stroke.clone(), Color::BLACK).map_err(|e| bad("shape.edit", e))?; + vector::flatten::validate_shape(&shape.path, shape.stroke.as_ref()).map_err(|e| bad("shape.edit", e))?; + refresh_shape(doc, shape); + Ok(result) +} + +/// Moves a layer's vector content by `(dx, dy)`: shape paths (re-rendered) and linked vector +/// masks, recursing into groups. For the Move tool / `layer.move`. +pub fn translate_vectors(doc: &Document, l: &mut Layer, dx: f64, dy: f64) { + let a = Affine::translate(dx, dy); + if let Some(vm) = l.vector_mask.as_mut() + && vm.linked + { + vm.path = vm.path.transform(&a); + } + match &mut l.content { + LayerContent::Shape(sh) => shift_shape(doc, sh, dx, dy), + LayerContent::Group(g) => { + for c in &mut g.children { + translate_vectors(doc, c, dx, dy); + } + } + _ => {} + } +} + +/// Moves a shape by `(dx, dy)`. A whole-pixel move shifts the rendered pixels as they are, so a +/// shape from a PSD keeps Photoshop's anti-aliasing (as moved type does). The render is cut at +/// the canvas, so a shape reaching past it renders again, as does a fractional move. +pub(crate) fn shift_shape(doc: &Document, sh: &mut ShapeLayer, dx: f64, dy: f64) { + transform_shape(sh, &Affine::translate(dx, dy)); + let whole = |v: f64| (v.fract() == 0.0 && v.abs() <= f64::from(i32::MAX)).then_some(v as i32); + let canvas = doc.bounds(); + let inside = sh.cache.as_ref().is_some_and(|c| { + let b = photocraft_compose::bounds::content_bounds(c); + // An empty cache can be an off-canvas shape moving back into view. + !b.is_empty() && b.x0 > canvas.x0 && b.y0 > canvas.y0 && b.x1 < canvas.x1 && b.y1 < canvas.y1 + }); + let stroke_pad = sh.stroke.as_ref().filter(|s| s.opacity > 0.0).map_or(0.0, |s| f64::from(s.width.ceil())); + let stays_inside = sh.path.control_bounds().is_some_and(|(x0, y0, x1, y1)| { + (x0 - stroke_pad) > canvas.x0 as f64 + && (y0 - stroke_pad) > canvas.y0 as f64 + && (x1 + stroke_pad) < canvas.x1 as f64 + && (y1 + stroke_pad) < canvas.y1 as f64 + }); + match (&mut sh.cache, whole(dx), whole(dy)) { + (Some(c), Some(dx), Some(dy)) if inside && stays_inside => *c = crate::layer_multi_cmds::shift_surface(c, dx, dy), + _ => refresh_shape(doc, sh), + } +} + +/// Applies an affine transform to a shape's path, keeping the live shape when the transform +/// is a translation plus axis-aligned scale (otherwise the shape stops being parametric). +pub fn transform_shape(sh: &mut ShapeLayer, a: &Affine) { + sh.path = sh.path.transform(a); + let [m0, m1, m2, m3, tx, ty] = a.m; + let axis_aligned = m1.abs() < 1e-12 && m2.abs() < 1e-12 && m0 > 0.0 && m3 > 0.0; + sh.live = match (sh.live.take(), axis_aligned) { + (Some(l), true) => { + let r = |r: [f64; 4]| [r[0] * m0 + tx, r[1] * m3 + ty, r[2] * m0, r[3] * m3]; + let pt = |p: [f64; 2]| [p[0] * m0 + tx, p[1] * m3 + ty]; + Some(match l { + LiveShape::Rect { rect, radii } => { + let k = m0.min(m3); + LiveShape::Rect { rect: r(rect), radii: radii.map(|v| v * k) } + } + LiveShape::Ellipse { rect } => LiveShape::Ellipse { rect: r(rect) }, + LiveShape::Polygon { rect, sides, star_ratio, corner_radius } => { + LiveShape::Polygon { rect: r(rect), sides, star_ratio, corner_radius: corner_radius * m0.min(m3) } + } + LiveShape::Line { from, to, weight } => { + // Live-shape edits regenerate the line's filled bar from its parameters. + // Keep the weight in sync with a positive scale of the path, or an + // unchanged endpoint edit unexpectedly restores the old thickness (#3063). + // A line's width scales perpendicular to its direction. + let (dx, dy) = (to[0] - from[0], to[1] - from[1]); + let old_length = dx.hypot(dy); + let new_length = (dx * m0).hypot(dy * m3); + let width_scale = if old_length > 0.0 && new_length > 0.0 { m0 * m3 * old_length / new_length } else { m0.min(m3) }; + LiveShape::Line { from: pt(from), to: pt(to), weight: weight * width_scale } + } + }) + } + // Flips and 90° turns keep rectangles, ellipses and lines live (Image Rotation): the new + // live box is the mapped box. Polygons/stars would change orientation, so they don't. + (Some(l), false) if (m1.abs() < 1e-12 && m2.abs() < 1e-12) || (m0.abs() < 1e-12 && m3.abs() < 1e-12) => { + let pt = |p: [f64; 2]| [m0 * p[0] + m2 * p[1] + tx, m1 * p[0] + m3 * p[1] + ty]; + let r = |r: [f64; 4]| { + let (p, q) = (pt([r[0], r[1]]), pt([r[0] + r[2], r[1] + r[3]])); + [p[0].min(q[0]), p[1].min(q[1]), (q[0] - p[0]).abs(), (q[1] - p[1]).abs()] + }; + let k = (m0.abs() + m1.abs()).min(m2.abs() + m3.abs()); + match l { + LiveShape::Rect { rect, radii } if radii.iter().all(|v| (v - radii[0]).abs() < 1e-9) => { + Some(LiveShape::Rect { rect: r(rect), radii: radii.map(|v| v * k) }) + } + LiveShape::Ellipse { rect } => Some(LiveShape::Ellipse { rect: r(rect) }), + LiveShape::Line { from, to, weight } => Some(LiveShape::Line { from: pt(from), to: pt(to), weight: weight * k }), + _ => None, + } + } + _ => None, + }; + sh.psd_raw = None; +} + +/// Is every anchor and control point of `path` a finite point? +fn finite_path(path: &Path) -> bool { + path.subpaths.iter().flat_map(|s| &s.knots).all(|k| [k.anchor, k.in_ctrl, k.out_ctrl].iter().all(|p| p.x.is_finite() && p.y.is_finite())) +} + +/// `path` through Distort / Perspective (`h`, a projective map of its points: exact for straight +/// segments, the end tangents of curves exact) or, with `warp`, Warp (split where the warp bends +/// it). Refused when the map sends a point to infinity (past a perspective's horizon). +pub(crate) fn map_path(path: &Path, h: Option<&photocraft_algo::transform::Homography>, warp: Option<&photocraft_geom::warp::Warp>) -> Result { + let out = match (h, warp) { + (_, Some(w)) => vector::map::map_path( + path, + |p| { + let (x, y) = w.map(p.x, p.y); + Point::new(x, y) + }, + 0.1, + ), + (Some(h), None) => vector::map::map_points(path, |p| { + let (x, y) = h.apply(p.x, p.y); + Point::new(x, y) + }), + (None, None) => path.clone(), + }; + if !finite_path(&out) { + return Err(EngineError::Other("the distortion sends part of the path out of bounds".into())); + } + Ok(out) +} + +/// Distort, Perspective or Warp of a shape layer (#3009): the shape stays a shape, its path +/// mapped ([`map_path`]), as in Photoshop. A live rectangle, ellipse, polygon or line becomes a +/// plain path, as its parameters can't describe the distorted outline. +pub(crate) fn map_shape(sh: &mut ShapeLayer, h: Option<&photocraft_algo::transform::Homography>, warp: Option<&photocraft_geom::warp::Warp>) -> Result<()> { + sh.path = map_path(&sh.path, h, warp)?; + sh.live = None; + sh.psd_raw = None; + Ok(()) +} + +pub(super) fn shape_info(s: &Session, id: LayerId) -> Result { + let d = s.active().ok_or(EngineError::NoDocument)?; + let l = d.doc.layer(id).ok_or(EngineError::NoLayer(id))?; + let LayerContent::Shape(sh) = &l.content else { + return Err(EngineError::Other(format!("layer {} is {} {} layer, not a shape layer", id.0, l.content.article(), l.content.kind_name()))); + }; + let bounds = sh.cache.as_ref().map(|c| c.content_bounds()).filter(|r| !r.is_empty()).map(|r| json!([r.x0, r.y0, r.width(), r.height()])); + Ok(json!({ + "layer": id.0, + "name": l.name, + "path": path_json(&sh.path), + "fill": sh.fill.as_ref().map(fill_json), + "stroke": sh.stroke.as_ref().map(stroke_json), + "live": sh.live.as_ref().map(live_json), + "kind": sh.live.as_ref().map_or("path", live_kind), + "bounds": bounds, + })) +} + +pub(crate) fn with_shape(s: &mut Session, id: LayerId, label: &str, f: impl FnOnce(&mut ShapeLayer, &mut Layer) -> Result) -> Result { + if let Some(st) = s.active() { + let locks = st.doc.effective_locks(id); + if locks.all || locks.pixels { + return Err(EngineError::Other("shape layer is locked".into())); + } + } + s.edit(label, |doc, _| { + let snapshot = doc.clone(); + let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; + if !matches!(l.content, LayerContent::Shape(_)) { + return Err(EngineError::Other(format!("layer {} is {} {} layer, not a shape layer", id.0, l.content.article(), l.content.kind_name()))); + } + let LayerContent::Shape(mut sh) = std::mem::replace(&mut l.content, LayerContent::Fill(Fill::Solid(Color::BLACK))) else { + return Err(EngineError::Other(format!("layer {} is not a shape layer", id.0))); + }; + let r = f(&mut sh, l); + if r.is_ok() { + refresh_shape(&snapshot, &mut sh); + } + l.content = LayerContent::Shape(sh); + r + }) +} + +fn default_name(kind: &str) -> &'static str { + match kind { + "rect" | "rectangle" => "Rectangle", + "roundedRect" | "roundRect" => "Rounded Rectangle", + "ellipse" => "Ellipse", + "polygon" => "Polygon", + "star" => "Star", + "line" => "Line", + _ => "Shape", + } +} + +pub(super) fn shape_create(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "shape.create"; + let kind = p.get("kind").and_then(Value::as_str).unwrap_or("rect"); + let (path, live) = if kind == "path" { + let v = p.get("path").ok_or_else(|| bad(CMD, "kind \"path\" needs `path`"))?; + (parse_path(v).map_err(|e| bad(CMD, e))?, None) + } else { + let l = live_from_params(CMD, kind, p, None)?; + (vector::shapes::live_path(&l), Some(l)) + }; + let fg = s.tools.foreground; + let fgc = Color::rgba(fg[0], fg[1], fg[2], fg[3]); + let fill = match p.get("fill") { + Some(v) => parse_fill(v).map_err(|e| bad(CMD, e))?, + None => Some(Fill::Solid(fgc)), + }; + let stroke = match p.get("stroke") { + Some(v) => parse_stroke(v, None, fgc).map_err(|e| bad(CMD, e))?, + None => None, + }; + vector::flatten::validate_shape(&path, stroke.as_ref()).map_err(|e| bad(CMD, e))?; + // Add to an existing shape layer with a path operation (Shape tool in combine/subtract… mode). + if let Some(target) = p.get("addTo").and_then(Value::as_u64) { + let op = p.get("op").and_then(Value::as_str).map_or(Some(PathOp::Combine), op_from).ok_or_else(|| bad(CMD, "unknown `op`"))?; + let id = LayerId(target); + with_shape(s, id, "Add Shape", |sh, _| { + for mut sp in path.subpaths { + sp.op = op; + sh.path.subpaths.push(sp); + } + sh.live = None; + sh.psd_raw = None; + vector::flatten::validate_shape(&sh.path, sh.stroke.as_ref()).map_err(|e| bad(CMD, e))?; + Ok(()) + })?; + return shape_info(s, id); + } + let name = p.get("name").and_then(Value::as_str).map(str::to_string); + let mut sh = ShapeLayer { path, fill, stroke, live, ..Default::default() }; + let id = s.edit("New Shape Layer", |doc, active| { + refresh_shape(doc, &mut sh); + let name = name.unwrap_or_else(|| doc.next_layer_name(default_name(kind))); + let id = doc.insert_above(*active, Layer::new(name, LayerContent::Shape(sh))); + *active = Some(id); + Ok(id) + })?; + shape_info(s, id) +} + +pub(super) fn shape_edit(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "shape.edit"; + let id = layer_id(s, p)?; + let fg = s.tools.foreground; + let fgc = Color::rgba(fg[0], fg[1], fg[2], fg[3]); + let name = p.get("name").and_then(Value::as_str).map(str::to_string); + with_shape(s, id, "Edit Shape", |sh, layer| { + if let Some(v) = p.get("path") { + sh.path = parse_path(v).map_err(|e| bad(CMD, e))?; + sh.live = None; + sh.psd_raw = None; + } + let geom_keys = ["kind", "rect", "radii", "radius", "sides", "starRatio", "cornerRadius", "from", "to", "weight"]; + if geom_keys.iter().any(|k| p.get(*k).is_some()) { + let kind = p.get("kind").and_then(Value::as_str).map(str::to_string).or_else(|| sh.live.as_ref().map(|l| live_kind(l).to_string())); + let kind = kind.ok_or_else(|| bad(CMD, "this shape has no live-shape parameters; pass `kind` or `path`"))?; + // Explicit radii on a plain rectangle keep it a (now rounded) rectangle. + let kind = if kind == "rect" && radii(p).is_some_and(|r| r.iter().any(|v| *v > 0.0)) { "roundedRect".to_string() } else { kind }; + let l = live_from_params(CMD, &kind, p, sh.live.as_ref())?; + // A transformed live shape's path may carry nonuniform corner scaling + // that its scalar radii cannot represent. Re-entering unchanged values + // must not regenerate the outline and silently discard that geometry. + if sh.live.as_ref() != Some(&l) { + sh.path = vector::shapes::live_path(&l); + sh.live = Some(l); + sh.psd_raw = None; + } + } + if let Some(m) = nums::<6>(p, "transform") { + transform_shape(sh, &Affine { m }); + } + if let Some([dx, dy]) = nums::<2>(p, "move") { + transform_shape(sh, &Affine::translate(dx, dy)); + } + if let Some(op) = p.get("op").and_then(Value::as_str) { + // Operation of the selected subpath(s) (`subpath`: index, default all but the first). + let op = op_from(op).ok_or_else(|| bad(CMD, format!("unknown op `{op}`")))?; + match p.get("subpath").and_then(Value::as_u64) { + Some(i) => sh.path.subpaths.get_mut(i as usize).ok_or_else(|| bad(CMD, "no such subpath"))?.op = op, + None => sh.path.subpaths.iter_mut().skip(1).for_each(|sp| sp.op = op), + } + sh.live = None; + } + if let Some(r) = p.get("fillRule").and_then(Value::as_str) { + sh.path.fill_rule = if r.eq_ignore_ascii_case("evenodd") { FillRule::EvenOdd } else { FillRule::NonZero }; + } + if let Some(v) = p.get("fill") { + sh.fill = parse_fill(v).map_err(|e| bad(CMD, e))?; + } + if let Some(v) = p.get("stroke") { + sh.stroke = parse_stroke(v, sh.stroke.clone(), fgc).map_err(|e| bad(CMD, e))?; + } + if let Some(n) = name { + layer.name = n; + } + vector::flatten::validate_shape(&sh.path, sh.stroke.as_ref()).map_err(|e| bad(CMD, e))?; + Ok(()) + })?; + shape_info(s, id) +} + +pub(super) fn shape_rasterize(s: &mut Session, p: &Value) -> Result { + let id = layer_id(s, p)?; + s.edit("Rasterize Shape", |doc, _| { + let snapshot = doc.clone(); + let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; + let LayerContent::Shape(sh) = &mut l.content else { + return Err(EngineError::Other(format!("layer {} is not a shape layer", id.0))); + }; + if sh.cache.is_none() { + refresh_shape(&snapshot, sh); + } + let fmt = snapshot.pixel_format(); + let surface = sh.cache.take().unwrap_or_else(|| photocraft_raster::Surface::new(fmt)); + let surface = if surface.format() == fmt { surface } else { surface.convert(fmt) }; + l.content = LayerContent::Raster(surface); + l.psd_blocks.retain(|(k, _)| !SHAPE_BLOCKS.contains(&k)); + Ok(()) + })?; + Ok(json!({ "layer": id.0 })) +} + +/// Traces the exact coverage of the shape's path back into plain outlines. +pub(super) fn merge_components(s: &mut Session, p: &Value) -> Result { + let tol = f64p(p, "tolerance").unwrap_or(0.1).clamp(0.05, 10.0); + if let Some(ids) = combine_targets(s, p, &["layer"])? { + return merge_shape_layers(s, &ids, None, "Merge Shape Components", Some(tol)); + } + let id = layer_id(s, p)?; + with_shape(s, id, "Merge Shape Components", |sh, _| bake_components(sh, tol))?; + shape_info(s, id) +} + +/// Bakes `sh`'s path operations into plain combined outlines, traced from the exact coverage. +fn bake_components(sh: &mut ShapeLayer, tol: f64) -> Result<()> { + // Trace at 4× resolution so the fitted outline follows the anti-aliased edge closely. + const K: f64 = 4.0; + let up = sh.path.transform(&Affine::scale(K)); + let r = vector::fill_rasterizer(&up, vector::DEFAULT_TOLERANCE); + let Some(b) = r.pixel_bounds() else { + sh.path.subpaths.clear(); + return Ok(()); + }; + let b = b.inflate(2); + if u64::from(b.width()) * u64::from(b.height()) > 400_000_000 { + return Err(EngineError::Other("shape too large to merge".into())); + } + let cov = r.render(b); + let traced = vector::trace::trace_mask(&cov, b, 0.0, tol * K); + sh.path = traced.transform(&Affine::scale(1.0 / K)); + sh.live = None; + sh.psd_raw = None; + Ok(()) +} + +/// The shape layers Layer › Combine Shapes merges into one: with none of the `narrow` params +/// given and two or more shape layers selected, those layers bottom-to-top (other selected layers +/// are left alone). `None` keeps the single-layer behaviour (acting on one layer's components). +fn combine_targets(s: &Session, p: &Value, narrow: &[&str]) -> Result>> { + if narrow.iter().any(|k| p.get(*k).is_some()) { + return Ok(None); + } + let d = s.active().ok_or(EngineError::NoDocument)?; + let sel = d.selected_layers(); + let ids = crate::layer_multi_cmds::top_level(&d.doc, &sel); + let ids: Vec = ids.into_iter().filter(|id| d.doc.layer(*id).is_some_and(|l| matches!(l.content, LayerContent::Shape(_)))).collect(); + Ok((ids.len() > 1).then_some(ids)) +} + +/// Layer › Combine Shapes with several shape layers selected: Photoshop merges them into the +/// top-most one. The bottom layer's components keep their operations; every component of the +/// layers above takes `op` (front shapes subtract, intersect… in stacking order), or, with no +/// `op` (Merge Shape Components), keeps its own with each layer's first component combined, and +/// the result is then baked with tolerance `bake`. The other layers are removed; one history step. +fn merge_shape_layers(s: &mut Session, ids: &[LayerId], op: Option, label: &str, bake: Option) -> Result { + let (&keep, _) = ids.split_last().ok_or_else(|| EngineError::Other("Combine Shapes needs two or more shape layers".into()))?; + if let Some(st) = s.active() { + for id in ids { + let locks = st.doc.effective_locks(*id); + if locks.all || locks.pixels { + return Err(EngineError::Other("a selected shape layer is locked".into())); + } + } + } + s.edit(label, |doc, active| { + let mut path: Option = None; + for id in ids { + let l = doc.layer(*id).ok_or(EngineError::NoLayer(*id))?; + let LayerContent::Shape(sh) = &l.content else { + return Err(EngineError::Other(format!("layer {} is not a shape layer", id.0))); + }; + let Some(acc) = path.as_mut() else { + path = Some(sh.path.clone()); + continue; + }; + for (j, sp) in sh.path.subpaths.iter().enumerate() { + let mut sp = sp.clone(); + sp.op = match op { + Some(op) => op, + None if j == 0 => PathOp::Combine, + None => sp.op, + }; + acc.subpaths.push(sp); + } + } + let path = path.ok_or_else(|| EngineError::Other("Combine Shapes needs two or more shape layers".into()))?; + let snapshot = doc.clone(); + let l = doc.layer_mut(keep).ok_or(EngineError::NoLayer(keep))?; + let LayerContent::Shape(sh) = &mut l.content else { + return Err(EngineError::Other(format!("layer {} is not a shape layer", keep.0))); + }; + let mut merged = ShapeLayer { path, live: None, psd_raw: None, cache: None, ..sh.clone() }; + if let Some(tol) = bake { + bake_components(&mut merged, tol)?; + } + vector::flatten::validate_shape(&merged.path, merged.stroke.as_ref()).map_err(|e| bad(label, e))?; + refresh_shape(&snapshot, &mut merged); + *sh = merged; + for id in ids.iter().filter(|id| **id != keep) { + doc.remove(*id); + } + *active = Some(keep); + Ok(()) + })?; + crate::layer_multi_cmds::reselect(s, vec![keep], Some(keep)); + shape_info(s, keep) +} + +/// Layer › Combine Shapes › Unite / Subtract Front Shape / Intersect / Exclude: merges the +/// selected shape layers with `op` ([`merge_shape_layers`]), or with one layer (or an explicit +/// `layer`/`subpath`) sets the operation of that layer's components (`shape.edit`'s `op`). +pub(super) fn combine_shapes(s: &mut Session, p: &Value, op: &str, label: &str) -> Result { + if let Some(ids) = combine_targets(s, p, &["layer", "subpath"])? { + let op = op_from(op).ok_or_else(|| EngineError::Other(format!("unknown op `{op}`")))?; + return merge_shape_layers(s, &ids, Some(op), label, None); + } + shape_edit(s, &with(p, "op", json!(op))) +} + +pub(super) fn selection_to_shape(s: &mut Session, p: &Value) -> Result { + let tol = f64p(p, "tolerance").or_else(|| f64p(p, "simplifyTolerance")).unwrap_or(2.0).clamp(0.5, 10.0); + let d = s.active().ok_or(EngineError::NoDocument)?; + let area = d.doc.bounds(); + let mask = sel::mask_from_surface(d.doc.selection.as_ref(), area); + let path = vector::trace::trace_mask(&mask, area, 0.0, tol); + let mut q = json!({ "kind": "path", "path": path_json(&path) }); + for k in ["fill", "name", "stroke"] { + if let Some(v) = p.get(k) { + q[k] = v.clone(); + } + } + shape_create(s, &q) +} diff --git a/crates/engine/src/vector_cmds/tests.rs b/crates/engine/src/cmd/vector_cmds/tests.rs similarity index 100% rename from crates/engine/src/vector_cmds/tests.rs rename to crates/engine/src/cmd/vector_cmds/tests.rs diff --git a/crates/engine/src/cmd/vector_cmds/vector_mask.rs b/crates/engine/src/cmd/vector_cmds/vector_mask.rs new file mode 100644 index 0000000000..c21b214d81 --- /dev/null +++ b/crates/engine/src/cmd/vector_cmds/vector_mask.rs @@ -0,0 +1,199 @@ +use super::params::{layer_id, parse_path, path_json}; +use super::paths::{is_work, resolve_path}; +use super::shape::with_shape; +use super::*; + +// --------------------------------------------------------------------------- +// Vector masks +// --------------------------------------------------------------------------- + +pub(super) fn vector_mask_info(s: &Session, id: LayerId) -> Result { + let d = s.active().ok_or(EngineError::NoDocument)?; + let l = d.doc.layer(id).ok_or(EngineError::NoLayer(id))?; + Ok(match (&l.vector_mask, &l.content) { + (Some(v), _) => { + json!({ "layer": id.0, "path": path_json(&v.path), "enabled": v.enabled, "linked": v.linked, "density": v.density * 100.0, "feather": v.feather }) + } + // A shape layer's path is its vector mask. + (None, LayerContent::Shape(sh)) => { + json!({ "layer": id.0, "path": path_json(&sh.path), "enabled": true, "linked": true, "shape": true, "density": sh.density * 100.0, "feather": sh.feather }) + } + (None, _) => json!({ "layer": id.0, "vectorMask": null }), + }) +} + +pub(super) fn vector_mask_add(s: &mut Session, p: &Value, from_path: bool) -> Result { + const CMD: &str = "layer.vectorMask.add"; + let id = layer_id(s, p)?; + let mut path = match p.get("path") { + Some(v) => parse_path(v).map_err(|e| bad(CMD, e))?, + None if from_path || p.get("name").is_some() => { + let name = p.get("name").and_then(Value::as_str); + // Never fall back to the layer's own path here. + if is_work(name) { + s.active().and_then(|d| d.doc.work_path.clone()).ok_or_else(|| EngineError::Other("no work path".into()))? + } else { + resolve_path(s, name)? + } + } + None => Path::default(), + }; + if p.get("hide").and_then(Value::as_bool).unwrap_or(false) { + path.inverted = !path.inverted; + } + s.edit("Add Vector Mask", |doc, _| { + let locked = doc.effective_locks(id).all; + let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; + if matches!(l.content, LayerContent::Shape(_)) { + return Err(EngineError::Other("a shape layer's path is already its vector mask".into())); + } + if locked { + return Err(EngineError::Other(format!("layer \"{}\" is locked", l.name))); + } + crate::extra_cmds::background_to_layer(doc, id); + doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?.vector_mask = Some(VectorMask::new(path)); + Ok(()) + })?; + vector_mask_info(s, id) +} + +pub(super) fn vector_mask_edit(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "layer.vectorMask.edit"; + let id = layer_id(s, p)?; + let path = p.get("path").map(parse_path).transpose().map_err(|e| bad(CMD, e))?; + // Same range as a pixel mask's feather (`layer.layerMask.edit`), checked before any edit (#4201). + let feather = p + .get("feather") + .map(|v| { + v.as_f64() + .filter(|n| n.is_finite() && (0.0..=1000.0).contains(n)) + .map(|n| n as f32) + .ok_or_else(|| bad(CMD, "`feather` must be a finite number within 0..1000")) + }) + .transpose()?; + let density = p + .get("density") + .map(|v| { + v.as_f64() + .filter(|n| n.is_finite() && (0.0..=100.0).contains(n)) + .map(|n| (n / 100.0) as f32) + .ok_or_else(|| bad(CMD, "`density` must be a finite number within 0..100 (%)")) + }) + .transpose()?; + // A shape layer's path is its vector mask (Photoshop's Properties › Masks): Density and + // Feather soften its fill; the path itself is edited with the shape and path commands. + if s.active().and_then(|d| d.doc.layer(id)).is_some_and(|l| matches!(l.content, LayerContent::Shape(_)) && l.vector_mask.is_none()) { + if let Some(k) = ["path", "enabled", "linked", "invert"].into_iter().find(|k| p.get(*k).is_some()) { + return Err(bad(CMD, format!("`{k}`: a shape layer's vector mask is its path; only `density` and `feather` apply"))); + } + if density.is_none() && feather.is_none() { + return vector_mask_info(s, id); + } + with_shape(s, id, "Edit Vector Mask", |sh, _| { + if let Some(d) = density { + sh.density = d; + } + if let Some(f) = feather { + sh.feather = f; + } + Ok(()) + })?; + return vector_mask_info(s, id); + } + s.edit("Edit Vector Mask", |doc, _| { + let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; + let vm = l.vector_mask.as_mut().ok_or_else(|| EngineError::Other("layer has no vector mask".into()))?; + if let Some(pth) = path { + vm.path = pth; + } + if let Some(b) = p.get("enabled").and_then(Value::as_bool) { + vm.enabled = b; + } + if let Some(b) = p.get("linked").and_then(Value::as_bool) { + vm.linked = b; + } + if let Some(d) = density { + vm.density = d; + } + if let Some(f) = feather { + vm.feather = f; + } + if let Some(b) = p.get("invert").and_then(Value::as_bool) + && b + { + vm.path.inverted = !vm.path.inverted; + } + Ok(()) + })?; + vector_mask_info(s, id) +} + +pub(super) fn vector_mask_delete(s: &mut Session, p: &Value) -> Result { + let id = layer_id(s, p)?; + s.edit("Delete Vector Mask", |doc, _| { + let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; + l.vector_mask.take().map(|_| ()).ok_or_else(|| EngineError::Other("layer has no vector mask".into())) + })?; + Ok(Value::Null) +} + +/// Layer › Rasterize › Vector Mask: multiplies the vector mask into the pixel mask. When a feather +/// (either mask's) or the pixel mask's density shapes the rendered edge, the pixel mask instead +/// becomes exactly what the compositor showed, with those settings baked in (#992). +pub(super) fn vector_mask_rasterize(s: &mut Session, p: &Value) -> Result { + use photocraft_compose::masks::{combined_mask, feather_sigma}; + let id = layer_id(s, p)?; + s.edit("Rasterize Vector Mask", |doc, _| { + let area = doc.bounds(); + let depth = doc.depth; + let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; + let soft = l.vector_mask.as_ref().is_some_and(|v| v.enabled) + && (l.vector_mask.as_ref().is_some_and(|v| feather_sigma(v.feather) > 0.0) + || l.mask.as_ref().is_some_and(|m| m.enabled && (feather_sigma(m.feather) > 0.0 || m.density < 1.0))); + let shown = if soft { combined_mask(l, area) } else { None }; + let vm = l.vector_mask.take().ok_or_else(|| EngineError::Other("layer has no vector mask".into()))?; + let mut mask = l.mask.take().unwrap_or_else(|| { + let mut m = photocraft_doc::LayerMask::reveal_all(); + m.surface = + photocraft_raster::Surface::with_default(photocraft_color::PixelFormat::new(photocraft_color::ColorMode::Grayscale, depth, false), &[1.0]); + m + }); + if let Some(shown) = shown { + // Past the canvas the pixel mask keeps its own (density-applied) default, as below. + let d = mask.surface.default_pixel().first().copied().unwrap_or(1.0); + let mut surface = photocraft_raster::Surface::with_default(mask.surface.format(), &[1.0 - mask.density * (1.0 - d)]); + surface.write_region(area, &shown.read_region(area)); + surface.prune(); + (mask.surface, mask.feather, mask.density) = (surface, 0.0, 1.0); + l.mask = Some(mask); + return Ok(()); + } + let vals = vector::vector_mask_values(&vm, area); + // Outside the canvas the vector mask is 0 unless it is empty/inverted; keep the old default there. + let old = mask.surface.read_region(area); + let merged: Vec = old.iter().zip(&vals).map(|(a, b)| a * b).collect(); + mask.surface.write_region(area, &merged); + mask.surface.prune(); + l.mask = Some(mask); + Ok(()) + })?; + Ok(json!({ "layer": id.0 })) +} + +/// `p` with `key` set (for alias commands). +pub(super) fn with(p: &Value, key: &str, v: Value) -> Value { + let mut o = if p.is_object() { p.clone() } else { json!({}) }; + o[key] = v; + o +} + +pub(super) fn toggle_vector_mask(s: &mut Session, p: &Value, key: &str) -> Result { + let id = layer_id(s, p)?; + let cur = { + let d = s.active().ok_or(EngineError::NoDocument)?; + let vm = d.doc.layer(id).ok_or(EngineError::NoLayer(id))?.vector_mask.as_ref().ok_or_else(|| EngineError::Other("layer has no vector mask".into()))?; + if key == "enabled" { vm.enabled } else { vm.linked } + }; + let v = p.get(key).and_then(Value::as_bool).unwrap_or(!cur); + vector_mask_edit(s, &json!({ "layer": id.0, key: v })) +} diff --git a/crates/engine/src/video_cmds.rs b/crates/engine/src/cmd/video_cmds.rs similarity index 100% rename from crates/engine/src/video_cmds.rs rename to crates/engine/src/cmd/video_cmds.rs diff --git a/crates/engine/src/video_cmds/tests.rs b/crates/engine/src/cmd/video_cmds/tests.rs similarity index 100% rename from crates/engine/src/video_cmds/tests.rs rename to crates/engine/src/cmd/video_cmds/tests.rs diff --git a/crates/engine/src/vp_cmds.rs b/crates/engine/src/cmd/vp_cmds.rs similarity index 100% rename from crates/engine/src/vp_cmds.rs rename to crates/engine/src/cmd/vp_cmds.rs diff --git a/crates/engine/src/warp_cmds.rs b/crates/engine/src/cmd/warp_cmds.rs similarity index 57% rename from crates/engine/src/warp_cmds.rs rename to crates/engine/src/cmd/warp_cmds.rs index 6a98b608fb..c5c04132d5 100644 --- a/crates/engine/src/warp_cmds.rs +++ b/crates/engine/src/cmd/warp_cmds.rs @@ -728,465 +728,4 @@ pub fn specs() -> Vec { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn a_warp_box_holding_the_whole_layer_gives_what_compositing_over_the_cleared_layer_did() { - for depth in [8, 16, 32] { - let s = session(depth); - let st = s.active().unwrap(); - let l = st.doc.layer(st.active_layer.unwrap()).unwrap().clone(); - let surf = l.surface().unwrap().clone(); - let rect = surf.content_bounds(); - let w = Warp::preset(WarpStyle::Flag, 35.0, rect_f(rect)); - // What the warp built before the shortcut: the warp composited over the cleared layer. - let map = |x: f64, y: f64| w.map(x, y); - let warped = warp_mesh_surface_with(&surf, rect, &map, Interp::Bicubic, &Interrupt::NONE).unwrap(); - let mut want = surf.clone(); - crate::pixels::try_clear_surface(&mut want, rect, None).unwrap(); - crate::transform_cmds::composite_over(&mut want, &warped); - want.prune(); - let mut got = l.clone(); - warp_layer(None, Locks::default(), &mut got, &w, rect, Interp::Bicubic, None, &Interrupt::NONE).unwrap(); - let got = got.surface().unwrap(); - let b = want.content_bounds(); - assert_eq!(got.content_bounds(), b, "depth {depth}"); - let (g, wv) = (got.read_region(b), want.read_region(b)); - // Exact at 8 and 16 bits. At 32 the composite's `t·a / a` rounds a few values by an - // ulp; the shortcut keeps the warp's own. - let tol = if depth == 32 { 1e-6 } else { 0.0 }; - let worst = g.iter().zip(&wv).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); - assert!(worst <= tol, "depth {depth}: off by {worst}"); - } - } - - fn session(depth: u64) -> Session { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 80, "height": 60, "depth": depth})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.edit("paint", |doc, active| { - let l = doc.layer_mut(active.unwrap()).unwrap(); - let surf = l.surface_mut().unwrap(); - for y in 10..40 { - for x in 10..60 { - let v = ((x * 3 + y * 5) % 11) as f32 / 10.0; - surf.write_pixel(x, y, &[v, 1.0 - v, 0.5, 1.0]); - } - } - Ok(()) - }) - .unwrap(); - s - } - - fn active_surface(s: &Session) -> Surface { - let st = s.active().unwrap(); - st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().clone() - } - - /// Warp on type sets its Warp Text (#3004): the layer stays type, one step; a custom mesh is - /// refused rather than rasterizing. - #[test] - fn warp_style_on_type_is_warp_text() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 200, "height": 100})).unwrap(); - s.execute("type.create", json!({"x": 10, "y": 60, "text": "Hi"})).unwrap(); - let n = s.active().unwrap().history.past_len(); - s.execute("edit.transform.warp", json!({"style": "arc", "bend": 30})).unwrap(); - let st = s.active().unwrap(); - let LayerContent::Text(t) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!("type") }; - assert_eq!(t.warp.as_ref().map(|w| (w.style.as_str(), w.value)), Some(("warpArc", 30.0))); - assert_eq!(st.history.past_len(), n + 1); - let mesh = BezierMesh::identity([0.0, 0.0, 10.0, 10.0], 1, 1).map_points(|p| [p[0] * 2.0, p[1]]); - assert!(s.execute("edit.transform.warp", json!({"warp": Warp::custom(mesh, [0.0, 0.0, 10.0, 10.0])})).is_err()); - } - - /// The seven values of a cylinder over the session's painted box (x 10..60, y 10..40). - const CYL: [f64; 7] = [10.0, 40.0, 60.0, 10.0, 0.3, 0.3, 0.5]; - - /// `style: "cylinder"` takes its seven values (#4112); anything that isn't a horizontal - /// cylinder is refused, never a silent no-op, and the layer is left alone. - #[test] - fn cylinder_style_needs_its_values() { - let mut s = session(8); - let before = active_surface(&s); - for p in [ - json!({"style": "cylinder"}), - json!({"style": "cylinder", "values": [10, 40, 60, 10, 0.3, 0.3]}), - json!({"style": "cylinder", "values": [60, 40, 10, 10, 0.3, 0.3, 0.5]}), - json!({"style": "cylinder", "values": [10, 40, 60, 10, 0.3, 0.3, "x"]}), - json!({"style": "cylinder", "values": "seven"}), - json!({"style": "cylinder", "values": CYL, "vertical": true}), - json!({"style": "cylinder", "values": CYL, "hDistort": 10}), - json!({"warp": {"style": "cylinder", "bounds": [10.0, 10.0, 60.0, 40.0]}}), - json!({"warp": {"style": "cylinder", "values": CYL, "bounds": [10.0, 10.0, 60.0, 40.0], "vertical": true}}), - json!({"warp": {"style": "cylinder", "values": CYL, "bounds": [10.0, 10.0, 60.0, 40.0], "hDistort": 10.0}}), - json!({"warp": {"style": "cylinder", "values": CYL, "bounds": [10.0, 10.0, 60.0, 40.0], "vDistort": -5.0}}), - ] { - let e = s.execute("edit.transform.warp", p.clone()).unwrap_err().to_string(); - assert!(e.contains("cylinder"), "{p}: {e}"); - } - assert_eq!(active_surface(&s), before); - // On type it is refused like a custom mesh: Warp Text has no cylinder. - s.execute("type.create", json!({"x": 10, "y": 50, "text": "Hi"})).unwrap(); - assert!(s.execute("edit.transform.warp", json!({"style": "cylinder", "values": CYL})).is_err()); - } - - #[test] - fn cylinder_warps_pixels_at_every_depth() { - for depth in [8u64, 16, 32] { - let mut s = session(depth); - let r = s.execute("edit.transform.warp", json!({"style": "cylinder", "values": CYL})).unwrap(); - assert_eq!(r["changed"], true, "{depth}"); - let after = active_surface(&s); - let b = after.content_bounds(); - // Between the silhouettes, the edges bowed down by the ellipses. - assert!(b.x0 >= 9 && b.x1 <= 61 && b.y0 >= 9 && b.y1 > 40, "{depth}: {b:?}"); - // The same cylinder as a full warp object (its mesh rebuilt from the values) agrees. - let mut t = session(depth); - let w = Warp::cylinder(&CYL, [10.0, 10.0, 60.0, 40.0]).unwrap(); - let mut garbled = w.clone(); - garbled.mesh = None; - t.execute("edit.transform.warp", json!({"warp": garbled})).unwrap(); - assert_eq!(active_surface(&t), after, "{depth}"); - } - } - - /// On a smart object the cylinder is stored in source space: still a cylinder (so it goes to - /// PSD as one) when the placement only scales and moves, its mesh when it rotates. - #[test] - fn smart_object_cylinder_is_stored_in_source_space() { - let stored = |s: &Session| { - let st = s.active().unwrap(); - let LayerContent::Smart(sm) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!("smart") }; - sm.warp.clone().unwrap() - }; - let mut s = session(8); - s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - s.execute("layer.smartObjects.warp", json!({"style": "cylinder", "values": CYL, "rect": [10, 10, 60, 40]})).unwrap(); - let w = stored(&s); - assert_eq!(w.style, WarpStyle::Cylinder); - let LayerContent::Smart(sm) = &s.active().unwrap().doc.layers[1].content else { panic!("smart") }; - let inv = crate::smart_cmds::placement(sm).inverse().unwrap(); - let src = |x: f64, y: f64| inv.apply(x, y); - let ((l, t), (r, bt)) = (src(10.0, 10.0), src(60.0, 40.0)); - for (a, b) in w.values.iter().zip([l, bt, r, t, 0.3, 0.3, 0.5]) { - assert!((a - b).abs() < 1e-9, "{:?}", w.values); - } - // Twice as wide: the silhouettes double, the ellipses' depth (in half axes) halves. - let mut s = session(8); - s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - s.execute("edit.transform", json!({"scaleX": 200, "scaleY": 100})).unwrap(); - let wide = [-15.0, 40.0, 85.0, 10.0, 0.3, 0.3, 0.5]; - s.execute("layer.smartObjects.warp", json!({"style": "cylinder", "values": wide, "rect": [-15, 10, 85, 40]})).unwrap(); - let w = stored(&s); - assert_eq!(w.style, WarpStyle::Cylinder); - assert!((w.values[4] - 0.6).abs() < 1e-9 && (w.values[5] - 0.6).abs() < 1e-9, "{:?}", w.values); - // The silhouettes land on the source's own edges (its contents span the scaled box). - let LayerContent::Smart(sm) = &s.active().unwrap().doc.layers[1].content else { panic!("smart") }; - let inv = crate::smart_cmds::placement(sm).inverse().unwrap(); - assert!((w.values[0] - inv.apply(-15.0, 10.0).0).abs() < 1e-9 && (w.values[2] - inv.apply(85.0, 10.0).0).abs() < 1e-9, "{:?}", w.values); - // Rotated: a custom mesh with the same shape. - let mut s = session(8); - s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - s.execute("edit.transform", json!({"rotate": 30})).unwrap(); - s.execute("layer.smartObjects.warp", json!({"style": "cylinder", "values": CYL, "rect": [10, 10, 60, 40]})).unwrap(); - let w = stored(&s); - assert_eq!(w.style, WarpStyle::Custom); - assert_eq!(w.mesh.as_ref().map(|m| (m.nx(), m.ny())), Some((13, 4))); - } - - /// Warp mode shows a stored cylinder as its mesh, and Enter commits that mesh untouched: the - /// smart object keeps its cylinder (else the next PSD save writes no warp), while a moved - /// point still makes it a custom warp. - #[test] - fn untouched_cylinder_committed_from_warp_mode_stays_a_cylinder() { - for scale in [100, 150] { - let mut s = session(8); - s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - s.execute("edit.transform", json!({"scaleX": scale, "scaleY": 100})).unwrap(); - let id = s.active().unwrap().active_layer.unwrap(); - let rect = warp_bounds(&s.active().unwrap().doc, s.active().unwrap().doc.layer(id).unwrap()); - let [x0, x1] = [f64::from(rect.x0), f64::from(rect.x1)]; - let values = [x0, 40.0, x1, 10.0, 0.3, 0.3, 0.5]; - s.execute("layer.smartObjects.warp", json!({"style": "cylinder", "values": values, "rect": [rect.x0, 10, rect.x1, 40]})).unwrap(); - let stored = |s: &Session| { - let st = s.active().unwrap(); - let LayerContent::Smart(sm) = &st.doc.layer(id).unwrap().content else { panic!("smart") }; - sm.warp.clone().unwrap() - }; - let cylinder = stored(&s); - assert_eq!(cylinder.style, WarpStyle::Cylinder, "{scale}"); - let shown = smart_warp_doc_space(s.active().unwrap().doc.layer(id).unwrap()).unwrap(); - assert_eq!(shown.style, WarpStyle::Custom); - s.execute("select.all", json!({})).unwrap(); - let (sel, steps) = (s.active().unwrap().doc.selection.clone(), s.active().unwrap().history.past_len()); - let r = s.execute("edit.transform.warp", json!({"layer": id.0, "rect": shown.bounds, "warp": shown, "interpolation": "bicubic"})).unwrap(); - assert_eq!(r["changed"], false, "{scale}"); - assert_eq!(stored(&s), cylinder, "{scale}: untouched"); - let st = s.active().unwrap(); - assert!(st.doc.selection == sel && st.history.past_len() == steps, "{scale}: no step, the selection stays"); - // The same mesh over another box is another warp. - let mut wider = shown.clone(); - wider.bounds[2] += 10.0; - s.execute("edit.transform.warp", json!({"layer": id.0, "rect": wider.bounds, "warp": wider})).unwrap(); - assert_eq!(stored(&s).style, WarpStyle::Custom, "{scale}: other box"); - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(stored(&s), cylinder); - let mut moved = shown.clone(); - if let Some(m) = moved.mesh.as_mut() { - m.points[20][1] += 5.0; - } - s.execute("edit.transform.warp", json!({"layer": id.0, "rect": moved.bounds, "warp": moved})).unwrap(); - assert_eq!(stored(&s).style, WarpStyle::Custom, "{scale}: edited"); - } - } - - #[test] - fn identity_and_bend_zero_are_no_ops_at_every_depth() { - for depth in [8u64, 16, 32] { - let mut s = session(depth); - let before = active_surface(&s); - let r = s.execute("edit.transform.warp", json!({"style": "custom"})).unwrap(); - assert_eq!(r["changed"], false); - s.execute("edit.transform.warp", json!({"style": "flag", "bend": 0})).unwrap(); - // A custom identity mesh passed explicitly (forces a resample) stays within 1/255. - let m = BezierMesh::identity([10.0, 10.0, 60.0, 40.0], 2, 2); - let mut w = Warp::custom(m, [10.0, 10.0, 60.0, 40.0]); - w.mesh.as_mut().unwrap().points[5][0] += 1e-12; // not exactly identity - s.execute("edit.transform.warp", json!({"warp": w})).unwrap(); - let after = active_surface(&s); - let r = Rect::new(10, 10, 60, 40); - assert_eq!(after.content_bounds(), r, "{depth}"); - let worst = before.read_region(r).iter().zip(after.read_region(r)).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); - assert!(worst <= 1.0 / 255.0, "{depth}: {worst}"); - } - } - - #[test] - fn arc_warps_pixels_and_undoes() { - let mut s = session(8); - let before = active_surface(&s); - s.execute("edit.transform.warp", json!({"style": "arc", "bend": 50})).unwrap(); - let after = active_surface(&s); - // As in Photoshop: the bottom edge keeps its corners, the top rises and spreads. - let c = after.content_bounds(); - assert!(c.y1 <= 41 && c.y0 < 8 && c.x0 < 8 && c.x1 > 62, "{c:?}"); - s.undo(); - assert_eq!(active_surface(&s), before); - assert!(s.execute("edit.transform.warp", json!({"style": "spiral"})).is_err()); - assert!(s.execute("edit.transform.warp", json!({})).is_err()); - assert!(s.execute("edit.transform.warp", json!({"mesh": {"us": [0, 1], "vs": [0, 1], "points": [[0, 0]]}})).is_err()); - } - - #[test] - fn custom_mesh_moves_a_control_point() { - let mut s = session(16); - let mut m = BezierMesh::identity([10.0, 10.0, 60.0, 40.0], 1, 1); - m.points[15] = [70.0, 50.0]; // bottom-right corner - s.execute("edit.transform.warp", json!({"mesh": m})).unwrap(); - let b = active_surface(&s).content_bounds(); - assert!(b.x1 >= 69 && b.y1 >= 49, "{b:?}"); - } - - #[test] - fn split_cuts_existing_sections_instead_of_replacing_the_grid() { - let b = [0.0, 0.0, 90.0, 60.0]; - let plain = Warp::custom(BezierMesh::identity(b, 1, 1), b); - let cut = split_warp(&plain, Some([b[0] + 0.25 * 90.0, 30.0]), Split::Vertical).unwrap(); - let m = cut.mesh.unwrap(); - for u in [0.0, 0.25, 1.0 / 3.0, 2.0 / 3.0, 1.0] { - assert!(m.us.iter().any(|k| (k - u).abs() < 1e-6), "default guides stay, cut at 0.25: {:?}", m.us); - } - assert_eq!(m.vs, vec![0.0, 1.0 / 3.0, 2.0 / 3.0, 1.0]); - let grid = BezierMesh::identity(b, 3, 3); - let cut = split_warp(&Warp::custom(grid.clone(), b), Some([45.0, 10.0]), Split::Vertical).unwrap(); - let m = cut.mesh.unwrap(); - assert_eq!(m.vs, grid.vs); - assert_eq!(m.us.len(), grid.us.len() + 1); - for u in [0.0, 1.0 / 3.0, 0.5, 2.0 / 3.0, 1.0] { - assert!(m.us.iter().any(|k| (k - u).abs() < 1e-6), "{:?}", m.us); - } - let (nx0, nx1) = (grid.nx(), m.nx()); - for j in 0..grid.ny() { - for i in 0..3 { - assert_eq!(m.points[j * nx1 + i], grid.points[j * nx0 + i]); - } - } - } - - #[test] - fn split_commands_edit_meshes_exactly() { - let mut s = session(8); - let w = Warp::preset(WarpStyle::Bulge, 30.0, [10.0, 10.0, 60.0, 40.0]); - let r = s.execute("edit.transform.splitWarpCrosswise", json!({"warp": w, "at": [30.0, 20.0]})).unwrap(); - let split: Warp = serde_json::from_value(r["warp"].clone()).unwrap(); - let m = split.mesh.as_ref().unwrap(); - assert_eq!((m.nx(), m.ny()), (7, 7)); - let r = s.execute("edit.transform.splitWarpVertically", json!({"warp": split})).unwrap(); - let v: Warp = serde_json::from_value(r["warp"].clone()).unwrap(); - assert_eq!(v.mesh.as_ref().unwrap().us.len(), 4); - let r = s.execute("edit.transform.removeWarpSplit", json!({"warp": v, "at": [30.0, 20.0]})).unwrap(); - let back: Warp = serde_json::from_value(r["warp"].clone()).unwrap(); - assert!(back.mesh.as_ref().unwrap().us.len() + back.mesh.as_ref().unwrap().vs.len() < 7); - // Splitting never changes the shape. - for (x, y) in [(15.0, 15.0), (40.0, 33.0)] { - let (a, b) = (w.map(x, y), split.map(x, y)); - assert!((a.0 - b.0).abs() < 0.6 && (a.1 - b.1).abs() < 0.6, "{a:?} {b:?}"); - } - } - - #[test] - fn smart_object_warp_is_lossless() { - for depth in [8u64, 16, 32] { - let mut s = session(depth); - s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - let original = active_surface(&s); - s.execute("layer.smartObjects.warp", json!({"style": "wave", "bend": 60})).unwrap(); - let warped = active_surface(&s); - assert_ne!(warped, original); - let st = s.active().unwrap(); - let LayerContent::Smart(sm) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!() }; - assert!(sm.warp.is_some()); - // Removing the warp re-renders the source exactly (no accumulated resampling). - s.execute("layer.smartObjects.warp", json!({"style": "none"})).unwrap(); - assert_eq!(active_surface(&s), original, "{depth}"); - // Warping twice equals warping once with the second warp. - s.execute("layer.smartObjects.warp", json!({"style": "arc", "bend": 20})).unwrap(); - s.execute("layer.smartObjects.warp", json!({"style": "wave", "bend": 60})).unwrap(); - assert_eq!(active_surface(&s), warped, "{depth}"); - // Split on the stored warp keeps the appearance (within resampling of the mesh fit). - s.execute("edit.transform.splitWarpCrosswise", json!({})).unwrap(); - let st = s.active().unwrap(); - let LayerContent::Smart(sm) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!() }; - assert_eq!(sm.warp.as_ref().unwrap().style, WarpStyle::Custom); - } - } - - #[test] - fn crosswise_split_of_an_identity_custom_warp_is_four_by_four() { - let mut s = session(8); - let r = s.execute("edit.transform.splitWarpCrosswise", json!({"style": "custom", "rect": [0.0, 0.0, 90.0, 60.0]})).unwrap(); - let out: Warp = serde_json::from_value(r["warp"].clone()).unwrap(); - let m = out.mesh.unwrap(); - assert_eq!((m.us.len(), m.vs.len()), (5, 5), "thirds, then the centre cut: {:?}", (m.us.clone(), m.vs.clone())); - for u in [0.0, 1.0 / 3.0, 0.5, 2.0 / 3.0, 1.0] { - assert!(m.us.iter().any(|k| (k - u).abs() < 1e-6), "{:?}", m.us); - assert!(m.vs.iter().any(|k| (k - u).abs() < 1e-6), "{:?}", m.vs); - } - } - - #[test] - fn extreme_rect_is_bad_params_not_a_giant_warp() { - let mut s = session(8); - for cmd in ["edit.transform.warp", "layer.smartObjects.warp"] { - if cmd == "layer.smartObjects.warp" { - s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - } - let e = s.execute(cmd, json!({"style": "arc", "bend": 50, "rect": [-1e30, -1e30, 1e30, 1e30]})).unwrap_err(); - assert!(matches!(&e, EngineError::BadParams { msg, .. } if msg.contains("rect too large")), "{cmd}: {e}"); - } - s.execute("layer.smartObjects.warp", json!({"style": "arc", "bend": 50, "rect": [10, 10, 60, 40]})).unwrap(); - } - - #[test] - fn warp_grid_fits_the_surface_and_rejects_bad_sizes() { - let mut s = session(8); - assert!(s.execute("edit.transform.warpGrid", json!({})).is_err()); - assert!(s.execute("edit.transform.warpGrid", json!({"size": 0})).is_err()); - assert!(s.execute("edit.transform.warpGrid", json!({"size": -3})).is_err()); - assert!(s.execute("edit.transform.warpGrid", json!({"size": 65})).is_err()); - assert!(s.execute("edit.transform.warpGrid", json!({"size": 1.5})).is_err()); - assert!(s.execute("edit.transform.warpGrid", json!({"size": "custom"})).is_err()); - assert!(s.execute("edit.transform.warpGrid", json!({"size": "nope"})).is_err()); - assert!(s.execute("edit.transform.warpGrid", json!({"grid": [3, 3]})).is_err()); - let b = [10.0, 10.0, 60.0, 40.0]; - let mut bent = BezierMesh::identity(b, 1, 1); - bent.points[0][0] += 12.0; - let r = s.execute("edit.transform.warpGrid", json!({"warp": Warp::custom(bent.clone(), b), "size": 4})).unwrap(); - let out: Warp = serde_json::from_value(r["warp"].clone()).unwrap(); - let m = out.mesh.unwrap(); - assert_eq!(out.style, WarpStyle::Custom); - assert_eq!(m.us, vec![0.0, 0.25, 0.5, 0.75, 1.0]); - assert_eq!(m.vs, m.us); - assert!((m.eval(0.0, 0.0)[0] - bent.eval(0.0, 0.0)[0]).abs() < 1e-3); - assert!((m.eval(1.0, 1.0)[0] - b[2]).abs() < 1e-3); - let r = s.execute("edit.transform.warpGrid", json!({"warp": Warp::custom(m, b), "size": "default"})).unwrap(); - let back: Warp = serde_json::from_value(r["warp"].clone()).unwrap(); - assert_eq!(back.mesh.unwrap().us.len(), 2); - } - - /// A selection limits the warp of a linked mask too, as it does the pixels (#4175; Free - /// Transform and Perspective Warp did this already, #3083): the moved part of the mask lines - /// up with the moved pixels and the unselected part stays put. - #[test] - fn linked_mask_with_a_selection_warps_only_the_selected_region() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 100, "height": 100})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.execute("layer.layerMask.revealAll", json!({})).unwrap(); - s.edit("paint", |doc, active| { - let l = doc.layer_mut(active.unwrap()).unwrap(); - l.surface_mut().unwrap().fill_rect(Rect::new(10, 10, 30, 20), &[1.0, 0.0, 0.0, 1.0]); - // Hide the left quarter (selected) and the right quarter (not selected). - let m = l.mask.as_mut().unwrap(); - m.surface.fill_rect(Rect::new(10, 10, 15, 20), &[0.0]); - m.surface.fill_rect(Rect::new(25, 10, 30, 20), &[0.0]); - m.linked = true; - Ok(()) - }) - .unwrap(); - let mask_at = |s: &Session, x, y| { - let st = s.active().unwrap(); - st.doc.layer(st.active_layer.unwrap()).unwrap().mask.as_ref().unwrap().surface.sample_channel(x, y, 0) - }; - let alpha_at = |s: &Session, x, y| { - let st = s.active().unwrap(); - st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().pixel(x, y)[3] - }; - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); - // A mesh that translates the selected box 50 px down. - let b = [10.0, 10.0, 20.0, 20.0]; - let mesh = BezierMesh::identity(b, 1, 1).map_points(|p| [p[0], p[1] + 50.0]); - s.execute("edit.transform.warp", json!({"rect": [10, 10, 20, 20], "mesh": mesh})).unwrap(); - // Moved pixels and their mask line up. - assert!(alpha_at(&s, 12, 65) > 0.99); - assert!(mask_at(&s, 12, 65) < 0.01, "selected hidden quarter moved"); - assert!(mask_at(&s, 17, 65) > 0.99, "selected visible quarter moved"); - // The vacated area reads as revealed, with transparent pixels. - assert!(alpha_at(&s, 12, 15) < 0.01); - assert!(mask_at(&s, 12, 15) > 0.99); - // The unselected part of the mask stays, aligned with the unselected pixels. - assert!(alpha_at(&s, 27, 15) > 0.99); - assert!(mask_at(&s, 27, 15) < 0.01, "unselected mask stays put"); - assert!(mask_at(&s, 27, 65) > 0.99, "and isn't copied along"); - for (x, y) in [(11, 61), (13, 68), (16, 61), (18, 68)] { - let want = if x < 15 { 0.0 } else { 1.0 }; - assert!((mask_at(&s, x, y) - want).abs() < 0.01, "({x},{y}): {}", mask_at(&s, x, y)); - } - } - - /// Esc stops the warp of a selected linked mask too, not only of the pixels. A fill layer has - /// no pixels to warp, so the mask is the only part that can see the cancel. - #[test] - fn a_cancelled_warp_stops_in_a_selected_linked_mask() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 100, "height": 100})).unwrap(); - s.execute("layer.newFillLayer.solidColor", json!({})).unwrap(); - s.execute("layer.layerMask.revealAll", json!({})).unwrap(); - s.edit("link", |doc, active| { - doc.layer_mut(active.unwrap()).unwrap().mask.as_mut().unwrap().linked = true; - Ok(()) - }) - .unwrap(); - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); - let st = s.active().unwrap(); - let (sel, mut l) = (st.doc.selection.clone().unwrap(), st.doc.layer(st.active_layer.unwrap()).unwrap().clone()); - let rect = Rect::new(10, 10, 20, 20); - let w = Warp::preset(WarpStyle::Flag, 35.0, rect_f(rect)); - let ctl = Interrupt::cancel_only(&|| true); - let r = warp_layer(Some(&sel), Locks::default(), &mut l, &w, rect, Interp::Bicubic, None, &ctl); - assert!(matches!(r, Err(EngineError::Cancelled)), "{r:?}"); - } -} +mod tests; diff --git a/crates/engine/src/cmd/warp_cmds/tests.rs b/crates/engine/src/cmd/warp_cmds/tests.rs new file mode 100644 index 0000000000..08130688c6 --- /dev/null +++ b/crates/engine/src/cmd/warp_cmds/tests.rs @@ -0,0 +1,460 @@ +use super::*; + +#[test] +fn a_warp_box_holding_the_whole_layer_gives_what_compositing_over_the_cleared_layer_did() { + for depth in [8, 16, 32] { + let s = session(depth); + let st = s.active().unwrap(); + let l = st.doc.layer(st.active_layer.unwrap()).unwrap().clone(); + let surf = l.surface().unwrap().clone(); + let rect = surf.content_bounds(); + let w = Warp::preset(WarpStyle::Flag, 35.0, rect_f(rect)); + // What the warp built before the shortcut: the warp composited over the cleared layer. + let map = |x: f64, y: f64| w.map(x, y); + let warped = warp_mesh_surface_with(&surf, rect, &map, Interp::Bicubic, &Interrupt::NONE).unwrap(); + let mut want = surf.clone(); + crate::pixels::try_clear_surface(&mut want, rect, None).unwrap(); + crate::transform_cmds::composite_over(&mut want, &warped); + want.prune(); + let mut got = l.clone(); + warp_layer(None, Locks::default(), &mut got, &w, rect, Interp::Bicubic, None, &Interrupt::NONE).unwrap(); + let got = got.surface().unwrap(); + let b = want.content_bounds(); + assert_eq!(got.content_bounds(), b, "depth {depth}"); + let (g, wv) = (got.read_region(b), want.read_region(b)); + // Exact at 8 and 16 bits. At 32 the composite's `t·a / a` rounds a few values by an + // ulp; the shortcut keeps the warp's own. + let tol = if depth == 32 { 1e-6 } else { 0.0 }; + let worst = g.iter().zip(&wv).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); + assert!(worst <= tol, "depth {depth}: off by {worst}"); + } +} + +fn session(depth: u64) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 80, "height": 60, "depth": depth})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.edit("paint", |doc, active| { + let l = doc.layer_mut(active.unwrap()).unwrap(); + let surf = l.surface_mut().unwrap(); + for y in 10..40 { + for x in 10..60 { + let v = ((x * 3 + y * 5) % 11) as f32 / 10.0; + surf.write_pixel(x, y, &[v, 1.0 - v, 0.5, 1.0]); + } + } + Ok(()) + }) + .unwrap(); + s +} + +fn active_surface(s: &Session) -> Surface { + let st = s.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().clone() +} + +/// Warp on type sets its Warp Text (#3004): the layer stays type, one step; a custom mesh is +/// refused rather than rasterizing. +#[test] +fn warp_style_on_type_is_warp_text() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 200, "height": 100})).unwrap(); + s.execute("type.create", json!({"x": 10, "y": 60, "text": "Hi"})).unwrap(); + let n = s.active().unwrap().history.past_len(); + s.execute("edit.transform.warp", json!({"style": "arc", "bend": 30})).unwrap(); + let st = s.active().unwrap(); + let LayerContent::Text(t) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!("type") }; + assert_eq!(t.warp.as_ref().map(|w| (w.style.as_str(), w.value)), Some(("warpArc", 30.0))); + assert_eq!(st.history.past_len(), n + 1); + let mesh = BezierMesh::identity([0.0, 0.0, 10.0, 10.0], 1, 1).map_points(|p| [p[0] * 2.0, p[1]]); + assert!(s.execute("edit.transform.warp", json!({"warp": Warp::custom(mesh, [0.0, 0.0, 10.0, 10.0])})).is_err()); +} + +/// The seven values of a cylinder over the session's painted box (x 10..60, y 10..40). +const CYL: [f64; 7] = [10.0, 40.0, 60.0, 10.0, 0.3, 0.3, 0.5]; + +/// `style: "cylinder"` takes its seven values (#4112); anything that isn't a horizontal +/// cylinder is refused, never a silent no-op, and the layer is left alone. +#[test] +fn cylinder_style_needs_its_values() { + let mut s = session(8); + let before = active_surface(&s); + for p in [ + json!({"style": "cylinder"}), + json!({"style": "cylinder", "values": [10, 40, 60, 10, 0.3, 0.3]}), + json!({"style": "cylinder", "values": [60, 40, 10, 10, 0.3, 0.3, 0.5]}), + json!({"style": "cylinder", "values": [10, 40, 60, 10, 0.3, 0.3, "x"]}), + json!({"style": "cylinder", "values": "seven"}), + json!({"style": "cylinder", "values": CYL, "vertical": true}), + json!({"style": "cylinder", "values": CYL, "hDistort": 10}), + json!({"warp": {"style": "cylinder", "bounds": [10.0, 10.0, 60.0, 40.0]}}), + json!({"warp": {"style": "cylinder", "values": CYL, "bounds": [10.0, 10.0, 60.0, 40.0], "vertical": true}}), + json!({"warp": {"style": "cylinder", "values": CYL, "bounds": [10.0, 10.0, 60.0, 40.0], "hDistort": 10.0}}), + json!({"warp": {"style": "cylinder", "values": CYL, "bounds": [10.0, 10.0, 60.0, 40.0], "vDistort": -5.0}}), + ] { + let e = s.execute("edit.transform.warp", p.clone()).unwrap_err().to_string(); + assert!(e.contains("cylinder"), "{p}: {e}"); + } + assert_eq!(active_surface(&s), before); + // On type it is refused like a custom mesh: Warp Text has no cylinder. + s.execute("type.create", json!({"x": 10, "y": 50, "text": "Hi"})).unwrap(); + assert!(s.execute("edit.transform.warp", json!({"style": "cylinder", "values": CYL})).is_err()); +} + +#[test] +fn cylinder_warps_pixels_at_every_depth() { + for depth in [8u64, 16, 32] { + let mut s = session(depth); + let r = s.execute("edit.transform.warp", json!({"style": "cylinder", "values": CYL})).unwrap(); + assert_eq!(r["changed"], true, "{depth}"); + let after = active_surface(&s); + let b = after.content_bounds(); + // Between the silhouettes, the edges bowed down by the ellipses. + assert!(b.x0 >= 9 && b.x1 <= 61 && b.y0 >= 9 && b.y1 > 40, "{depth}: {b:?}"); + // The same cylinder as a full warp object (its mesh rebuilt from the values) agrees. + let mut t = session(depth); + let w = Warp::cylinder(&CYL, [10.0, 10.0, 60.0, 40.0]).unwrap(); + let mut garbled = w.clone(); + garbled.mesh = None; + t.execute("edit.transform.warp", json!({"warp": garbled})).unwrap(); + assert_eq!(active_surface(&t), after, "{depth}"); + } +} + +/// On a smart object the cylinder is stored in source space: still a cylinder (so it goes to +/// PSD as one) when the placement only scales and moves, its mesh when it rotates. +#[test] +fn smart_object_cylinder_is_stored_in_source_space() { + let stored = |s: &Session| { + let st = s.active().unwrap(); + let LayerContent::Smart(sm) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!("smart") }; + sm.warp.clone().unwrap() + }; + let mut s = session(8); + s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + s.execute("layer.smartObjects.warp", json!({"style": "cylinder", "values": CYL, "rect": [10, 10, 60, 40]})).unwrap(); + let w = stored(&s); + assert_eq!(w.style, WarpStyle::Cylinder); + let LayerContent::Smart(sm) = &s.active().unwrap().doc.layers[1].content else { panic!("smart") }; + let inv = crate::smart_cmds::placement(sm).inverse().unwrap(); + let src = |x: f64, y: f64| inv.apply(x, y); + let ((l, t), (r, bt)) = (src(10.0, 10.0), src(60.0, 40.0)); + for (a, b) in w.values.iter().zip([l, bt, r, t, 0.3, 0.3, 0.5]) { + assert!((a - b).abs() < 1e-9, "{:?}", w.values); + } + // Twice as wide: the silhouettes double, the ellipses' depth (in half axes) halves. + let mut s = session(8); + s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + s.execute("edit.transform", json!({"scaleX": 200, "scaleY": 100})).unwrap(); + let wide = [-15.0, 40.0, 85.0, 10.0, 0.3, 0.3, 0.5]; + s.execute("layer.smartObjects.warp", json!({"style": "cylinder", "values": wide, "rect": [-15, 10, 85, 40]})).unwrap(); + let w = stored(&s); + assert_eq!(w.style, WarpStyle::Cylinder); + assert!((w.values[4] - 0.6).abs() < 1e-9 && (w.values[5] - 0.6).abs() < 1e-9, "{:?}", w.values); + // The silhouettes land on the source's own edges (its contents span the scaled box). + let LayerContent::Smart(sm) = &s.active().unwrap().doc.layers[1].content else { panic!("smart") }; + let inv = crate::smart_cmds::placement(sm).inverse().unwrap(); + assert!((w.values[0] - inv.apply(-15.0, 10.0).0).abs() < 1e-9 && (w.values[2] - inv.apply(85.0, 10.0).0).abs() < 1e-9, "{:?}", w.values); + // Rotated: a custom mesh with the same shape. + let mut s = session(8); + s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + s.execute("edit.transform", json!({"rotate": 30})).unwrap(); + s.execute("layer.smartObjects.warp", json!({"style": "cylinder", "values": CYL, "rect": [10, 10, 60, 40]})).unwrap(); + let w = stored(&s); + assert_eq!(w.style, WarpStyle::Custom); + assert_eq!(w.mesh.as_ref().map(|m| (m.nx(), m.ny())), Some((13, 4))); +} + +/// Warp mode shows a stored cylinder as its mesh, and Enter commits that mesh untouched: the +/// smart object keeps its cylinder (else the next PSD save writes no warp), while a moved +/// point still makes it a custom warp. +#[test] +fn untouched_cylinder_committed_from_warp_mode_stays_a_cylinder() { + for scale in [100, 150] { + let mut s = session(8); + s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + s.execute("edit.transform", json!({"scaleX": scale, "scaleY": 100})).unwrap(); + let id = s.active().unwrap().active_layer.unwrap(); + let rect = warp_bounds(&s.active().unwrap().doc, s.active().unwrap().doc.layer(id).unwrap()); + let [x0, x1] = [f64::from(rect.x0), f64::from(rect.x1)]; + let values = [x0, 40.0, x1, 10.0, 0.3, 0.3, 0.5]; + s.execute("layer.smartObjects.warp", json!({"style": "cylinder", "values": values, "rect": [rect.x0, 10, rect.x1, 40]})).unwrap(); + let stored = |s: &Session| { + let st = s.active().unwrap(); + let LayerContent::Smart(sm) = &st.doc.layer(id).unwrap().content else { panic!("smart") }; + sm.warp.clone().unwrap() + }; + let cylinder = stored(&s); + assert_eq!(cylinder.style, WarpStyle::Cylinder, "{scale}"); + let shown = smart_warp_doc_space(s.active().unwrap().doc.layer(id).unwrap()).unwrap(); + assert_eq!(shown.style, WarpStyle::Custom); + s.execute("select.all", json!({})).unwrap(); + let (sel, steps) = (s.active().unwrap().doc.selection.clone(), s.active().unwrap().history.past_len()); + let r = s.execute("edit.transform.warp", json!({"layer": id.0, "rect": shown.bounds, "warp": shown, "interpolation": "bicubic"})).unwrap(); + assert_eq!(r["changed"], false, "{scale}"); + assert_eq!(stored(&s), cylinder, "{scale}: untouched"); + let st = s.active().unwrap(); + assert!(st.doc.selection == sel && st.history.past_len() == steps, "{scale}: no step, the selection stays"); + // The same mesh over another box is another warp. + let mut wider = shown.clone(); + wider.bounds[2] += 10.0; + s.execute("edit.transform.warp", json!({"layer": id.0, "rect": wider.bounds, "warp": wider})).unwrap(); + assert_eq!(stored(&s).style, WarpStyle::Custom, "{scale}: other box"); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(stored(&s), cylinder); + let mut moved = shown.clone(); + if let Some(m) = moved.mesh.as_mut() { + m.points[20][1] += 5.0; + } + s.execute("edit.transform.warp", json!({"layer": id.0, "rect": moved.bounds, "warp": moved})).unwrap(); + assert_eq!(stored(&s).style, WarpStyle::Custom, "{scale}: edited"); + } +} + +#[test] +fn identity_and_bend_zero_are_no_ops_at_every_depth() { + for depth in [8u64, 16, 32] { + let mut s = session(depth); + let before = active_surface(&s); + let r = s.execute("edit.transform.warp", json!({"style": "custom"})).unwrap(); + assert_eq!(r["changed"], false); + s.execute("edit.transform.warp", json!({"style": "flag", "bend": 0})).unwrap(); + // A custom identity mesh passed explicitly (forces a resample) stays within 1/255. + let m = BezierMesh::identity([10.0, 10.0, 60.0, 40.0], 2, 2); + let mut w = Warp::custom(m, [10.0, 10.0, 60.0, 40.0]); + w.mesh.as_mut().unwrap().points[5][0] += 1e-12; // not exactly identity + s.execute("edit.transform.warp", json!({"warp": w})).unwrap(); + let after = active_surface(&s); + let r = Rect::new(10, 10, 60, 40); + assert_eq!(after.content_bounds(), r, "{depth}"); + let worst = before.read_region(r).iter().zip(after.read_region(r)).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); + assert!(worst <= 1.0 / 255.0, "{depth}: {worst}"); + } +} + +#[test] +fn arc_warps_pixels_and_undoes() { + let mut s = session(8); + let before = active_surface(&s); + s.execute("edit.transform.warp", json!({"style": "arc", "bend": 50})).unwrap(); + let after = active_surface(&s); + // As in Photoshop: the bottom edge keeps its corners, the top rises and spreads. + let c = after.content_bounds(); + assert!(c.y1 <= 41 && c.y0 < 8 && c.x0 < 8 && c.x1 > 62, "{c:?}"); + s.undo(); + assert_eq!(active_surface(&s), before); + assert!(s.execute("edit.transform.warp", json!({"style": "spiral"})).is_err()); + assert!(s.execute("edit.transform.warp", json!({})).is_err()); + assert!(s.execute("edit.transform.warp", json!({"mesh": {"us": [0, 1], "vs": [0, 1], "points": [[0, 0]]}})).is_err()); +} + +#[test] +fn custom_mesh_moves_a_control_point() { + let mut s = session(16); + let mut m = BezierMesh::identity([10.0, 10.0, 60.0, 40.0], 1, 1); + m.points[15] = [70.0, 50.0]; // bottom-right corner + s.execute("edit.transform.warp", json!({"mesh": m})).unwrap(); + let b = active_surface(&s).content_bounds(); + assert!(b.x1 >= 69 && b.y1 >= 49, "{b:?}"); +} + +#[test] +fn split_cuts_existing_sections_instead_of_replacing_the_grid() { + let b = [0.0, 0.0, 90.0, 60.0]; + let plain = Warp::custom(BezierMesh::identity(b, 1, 1), b); + let cut = split_warp(&plain, Some([b[0] + 0.25 * 90.0, 30.0]), Split::Vertical).unwrap(); + let m = cut.mesh.unwrap(); + for u in [0.0, 0.25, 1.0 / 3.0, 2.0 / 3.0, 1.0] { + assert!(m.us.iter().any(|k| (k - u).abs() < 1e-6), "default guides stay, cut at 0.25: {:?}", m.us); + } + assert_eq!(m.vs, vec![0.0, 1.0 / 3.0, 2.0 / 3.0, 1.0]); + let grid = BezierMesh::identity(b, 3, 3); + let cut = split_warp(&Warp::custom(grid.clone(), b), Some([45.0, 10.0]), Split::Vertical).unwrap(); + let m = cut.mesh.unwrap(); + assert_eq!(m.vs, grid.vs); + assert_eq!(m.us.len(), grid.us.len() + 1); + for u in [0.0, 1.0 / 3.0, 0.5, 2.0 / 3.0, 1.0] { + assert!(m.us.iter().any(|k| (k - u).abs() < 1e-6), "{:?}", m.us); + } + let (nx0, nx1) = (grid.nx(), m.nx()); + for j in 0..grid.ny() { + for i in 0..3 { + assert_eq!(m.points[j * nx1 + i], grid.points[j * nx0 + i]); + } + } +} + +#[test] +fn split_commands_edit_meshes_exactly() { + let mut s = session(8); + let w = Warp::preset(WarpStyle::Bulge, 30.0, [10.0, 10.0, 60.0, 40.0]); + let r = s.execute("edit.transform.splitWarpCrosswise", json!({"warp": w, "at": [30.0, 20.0]})).unwrap(); + let split: Warp = serde_json::from_value(r["warp"].clone()).unwrap(); + let m = split.mesh.as_ref().unwrap(); + assert_eq!((m.nx(), m.ny()), (7, 7)); + let r = s.execute("edit.transform.splitWarpVertically", json!({"warp": split})).unwrap(); + let v: Warp = serde_json::from_value(r["warp"].clone()).unwrap(); + assert_eq!(v.mesh.as_ref().unwrap().us.len(), 4); + let r = s.execute("edit.transform.removeWarpSplit", json!({"warp": v, "at": [30.0, 20.0]})).unwrap(); + let back: Warp = serde_json::from_value(r["warp"].clone()).unwrap(); + assert!(back.mesh.as_ref().unwrap().us.len() + back.mesh.as_ref().unwrap().vs.len() < 7); + // Splitting never changes the shape. + for (x, y) in [(15.0, 15.0), (40.0, 33.0)] { + let (a, b) = (w.map(x, y), split.map(x, y)); + assert!((a.0 - b.0).abs() < 0.6 && (a.1 - b.1).abs() < 0.6, "{a:?} {b:?}"); + } +} + +#[test] +fn smart_object_warp_is_lossless() { + for depth in [8u64, 16, 32] { + let mut s = session(depth); + s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + let original = active_surface(&s); + s.execute("layer.smartObjects.warp", json!({"style": "wave", "bend": 60})).unwrap(); + let warped = active_surface(&s); + assert_ne!(warped, original); + let st = s.active().unwrap(); + let LayerContent::Smart(sm) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!() }; + assert!(sm.warp.is_some()); + // Removing the warp re-renders the source exactly (no accumulated resampling). + s.execute("layer.smartObjects.warp", json!({"style": "none"})).unwrap(); + assert_eq!(active_surface(&s), original, "{depth}"); + // Warping twice equals warping once with the second warp. + s.execute("layer.smartObjects.warp", json!({"style": "arc", "bend": 20})).unwrap(); + s.execute("layer.smartObjects.warp", json!({"style": "wave", "bend": 60})).unwrap(); + assert_eq!(active_surface(&s), warped, "{depth}"); + // Split on the stored warp keeps the appearance (within resampling of the mesh fit). + s.execute("edit.transform.splitWarpCrosswise", json!({})).unwrap(); + let st = s.active().unwrap(); + let LayerContent::Smart(sm) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!() }; + assert_eq!(sm.warp.as_ref().unwrap().style, WarpStyle::Custom); + } +} + +#[test] +fn crosswise_split_of_an_identity_custom_warp_is_four_by_four() { + let mut s = session(8); + let r = s.execute("edit.transform.splitWarpCrosswise", json!({"style": "custom", "rect": [0.0, 0.0, 90.0, 60.0]})).unwrap(); + let out: Warp = serde_json::from_value(r["warp"].clone()).unwrap(); + let m = out.mesh.unwrap(); + assert_eq!((m.us.len(), m.vs.len()), (5, 5), "thirds, then the centre cut: {:?}", (m.us.clone(), m.vs.clone())); + for u in [0.0, 1.0 / 3.0, 0.5, 2.0 / 3.0, 1.0] { + assert!(m.us.iter().any(|k| (k - u).abs() < 1e-6), "{:?}", m.us); + assert!(m.vs.iter().any(|k| (k - u).abs() < 1e-6), "{:?}", m.vs); + } +} + +#[test] +fn extreme_rect_is_bad_params_not_a_giant_warp() { + let mut s = session(8); + for cmd in ["edit.transform.warp", "layer.smartObjects.warp"] { + if cmd == "layer.smartObjects.warp" { + s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + } + let e = s.execute(cmd, json!({"style": "arc", "bend": 50, "rect": [-1e30, -1e30, 1e30, 1e30]})).unwrap_err(); + assert!(matches!(&e, EngineError::BadParams { msg, .. } if msg.contains("rect too large")), "{cmd}: {e}"); + } + s.execute("layer.smartObjects.warp", json!({"style": "arc", "bend": 50, "rect": [10, 10, 60, 40]})).unwrap(); +} + +#[test] +fn warp_grid_fits_the_surface_and_rejects_bad_sizes() { + let mut s = session(8); + assert!(s.execute("edit.transform.warpGrid", json!({})).is_err()); + assert!(s.execute("edit.transform.warpGrid", json!({"size": 0})).is_err()); + assert!(s.execute("edit.transform.warpGrid", json!({"size": -3})).is_err()); + assert!(s.execute("edit.transform.warpGrid", json!({"size": 65})).is_err()); + assert!(s.execute("edit.transform.warpGrid", json!({"size": 1.5})).is_err()); + assert!(s.execute("edit.transform.warpGrid", json!({"size": "custom"})).is_err()); + assert!(s.execute("edit.transform.warpGrid", json!({"size": "nope"})).is_err()); + assert!(s.execute("edit.transform.warpGrid", json!({"grid": [3, 3]})).is_err()); + let b = [10.0, 10.0, 60.0, 40.0]; + let mut bent = BezierMesh::identity(b, 1, 1); + bent.points[0][0] += 12.0; + let r = s.execute("edit.transform.warpGrid", json!({"warp": Warp::custom(bent.clone(), b), "size": 4})).unwrap(); + let out: Warp = serde_json::from_value(r["warp"].clone()).unwrap(); + let m = out.mesh.unwrap(); + assert_eq!(out.style, WarpStyle::Custom); + assert_eq!(m.us, vec![0.0, 0.25, 0.5, 0.75, 1.0]); + assert_eq!(m.vs, m.us); + assert!((m.eval(0.0, 0.0)[0] - bent.eval(0.0, 0.0)[0]).abs() < 1e-3); + assert!((m.eval(1.0, 1.0)[0] - b[2]).abs() < 1e-3); + let r = s.execute("edit.transform.warpGrid", json!({"warp": Warp::custom(m, b), "size": "default"})).unwrap(); + let back: Warp = serde_json::from_value(r["warp"].clone()).unwrap(); + assert_eq!(back.mesh.unwrap().us.len(), 2); +} + +/// A selection limits the warp of a linked mask too, as it does the pixels (#4175; Free +/// Transform and Perspective Warp did this already, #3083): the moved part of the mask lines +/// up with the moved pixels and the unselected part stays put. +#[test] +fn linked_mask_with_a_selection_warps_only_the_selected_region() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 100, "height": 100})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + s.edit("paint", |doc, active| { + let l = doc.layer_mut(active.unwrap()).unwrap(); + l.surface_mut().unwrap().fill_rect(Rect::new(10, 10, 30, 20), &[1.0, 0.0, 0.0, 1.0]); + // Hide the left quarter (selected) and the right quarter (not selected). + let m = l.mask.as_mut().unwrap(); + m.surface.fill_rect(Rect::new(10, 10, 15, 20), &[0.0]); + m.surface.fill_rect(Rect::new(25, 10, 30, 20), &[0.0]); + m.linked = true; + Ok(()) + }) + .unwrap(); + let mask_at = |s: &Session, x, y| { + let st = s.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().mask.as_ref().unwrap().surface.sample_channel(x, y, 0) + }; + let alpha_at = |s: &Session, x, y| { + let st = s.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().pixel(x, y)[3] + }; + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); + // A mesh that translates the selected box 50 px down. + let b = [10.0, 10.0, 20.0, 20.0]; + let mesh = BezierMesh::identity(b, 1, 1).map_points(|p| [p[0], p[1] + 50.0]); + s.execute("edit.transform.warp", json!({"rect": [10, 10, 20, 20], "mesh": mesh})).unwrap(); + // Moved pixels and their mask line up. + assert!(alpha_at(&s, 12, 65) > 0.99); + assert!(mask_at(&s, 12, 65) < 0.01, "selected hidden quarter moved"); + assert!(mask_at(&s, 17, 65) > 0.99, "selected visible quarter moved"); + // The vacated area reads as revealed, with transparent pixels. + assert!(alpha_at(&s, 12, 15) < 0.01); + assert!(mask_at(&s, 12, 15) > 0.99); + // The unselected part of the mask stays, aligned with the unselected pixels. + assert!(alpha_at(&s, 27, 15) > 0.99); + assert!(mask_at(&s, 27, 15) < 0.01, "unselected mask stays put"); + assert!(mask_at(&s, 27, 65) > 0.99, "and isn't copied along"); + for (x, y) in [(11, 61), (13, 68), (16, 61), (18, 68)] { + let want = if x < 15 { 0.0 } else { 1.0 }; + assert!((mask_at(&s, x, y) - want).abs() < 0.01, "({x},{y}): {}", mask_at(&s, x, y)); + } +} + +/// Esc stops the warp of a selected linked mask too, not only of the pixels. A fill layer has +/// no pixels to warp, so the mask is the only part that can see the cancel. +#[test] +fn a_cancelled_warp_stops_in_a_selected_linked_mask() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 100, "height": 100})).unwrap(); + s.execute("layer.newFillLayer.solidColor", json!({})).unwrap(); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + s.edit("link", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().mask.as_mut().unwrap().linked = true; + Ok(()) + }) + .unwrap(); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); + let st = s.active().unwrap(); + let (sel, mut l) = (st.doc.selection.clone().unwrap(), st.doc.layer(st.active_layer.unwrap()).unwrap().clone()); + let rect = Rect::new(10, 10, 20, 20); + let w = Warp::preset(WarpStyle::Flag, 35.0, rect_f(rect)); + let ctl = Interrupt::cancel_only(&|| true); + let r = warp_layer(Some(&sel), Locks::default(), &mut l, &w, rect, Interp::Bicubic, None, &ctl); + assert!(matches!(r, Err(EngineError::Cancelled)), "{r:?}"); +} diff --git a/crates/engine/src/cmd/web_cmds.rs b/crates/engine/src/cmd/web_cmds.rs new file mode 100644 index 0000000000..b28e7a94fb --- /dev/null +++ b/crates/engine/src/cmd/web_cmds.rs @@ -0,0 +1,119 @@ +//! File › Export › Save for Web (Legacy), File › Export › Export Preferences, the Quick Export +//! pipeline that honours them, and File › Generate › Image Assets (Photoshop's Generator). +//! +//! Save for Web optimises the flattened (optionally resized, sRGB-converted) image as GIF, +//! PNG-8, PNG-24, JPEG or WBMP, per slice, into a folder with an optional HTML table; without an +//! output it only reports the optimised size (the dialog's 2-Up/4-Up annotations). Colour +//! reduction and dithering reuse `algo::quantize`; GIF/WBMP/progressive JPEG writers live in +//! `codecs::web`. +//! +//! Image Assets implements the naming grammar of Adobe's public Generator documentation: a +//! layer or group named `foo.png`, `200% foo@2x.png, 48x48 icons/foo.png8`, `photo.jpg80%`, +//! `?x100 thumb.gif` is exported into `-assets/` whenever the document is saved while +//! the feature is on; a `default` layer (`default 50% low/ + 200% @2x`) adds variants. + +use photocraft_algo::quantize::{self, Dither, Forced, PaletteKind}; +use photocraft_doc::slices::{self, ResolvedSlice, SliceKind}; +use photocraft_doc::{DocId, Document, LayerContent, LayerId}; +use photocraft_geom::Rect; +use serde_json::{Value, json}; + +use crate::commands::CommandSpec; +use crate::file_cmds::{is_windows_device_name, join, native_doc, portable_device_name, stem, write_file}; +use crate::{EngineError, Result, Session}; + +mod assets; +mod optimizer; +mod quick; +mod save_web; +mod settings; + +use assets::image_assets; +pub use assets::{AssetDefault, AssetSpec, assets_dir, generate_assets, parse_asset_name, parse_defaults}; +pub use optimizer::{Optimized, optimize, web_document, web_exif, web_xmp}; +use quick::{export_preferences, quick_export}; +pub use quick::{quick_export_target, quick_export_target_is_own_file}; +use save_web::save_for_web; +pub use save_web::save_for_web_with_writer; +pub use settings::{PRESETS, WebFormat, WebMetadata, WebSettings, preset_settings, rgb_hex}; + +fn bad(cmd: &str, msg: impl Into) -> EngineError { + EngineError::BadParams { cmd: cmd.into(), msg: msg.into() } +} +fn other(e: impl std::fmt::Display) -> EngineError { + EngineError::Other(e.to_string()) +} + +/// After a save: regenerate the document's image assets when Generate › Image Assets is on. +pub fn on_saved(s: &Session, index: usize) -> Option { + let d = s.documents().get(index)?; + if !s.file_menu.image_assets.contains(&d.doc.id) || !s.prefs().plug_ins.generator_enabled || cfg!(target_arch = "wasm32") { + return None; + } + let dir = assets_dir(d.path.as_deref()?); + let (files, errors) = generate_assets(&d.doc, &dir); + Some(json!({"dir": dir, "files": files, "errors": errors})) +} + +pub fn specs() -> Vec { + macro_rules! spec { + ($id:expr, $label:expr, $menu:expr, $sc:expr, $params:expr, $enabled:expr, $run:expr) => { + CommandSpec { id: $id, label: $label, menu: $menu, shortcut: $sc, params: $params, enabled: $enabled, journal: true, run: $run } + }; + } + fn has_doc(s: &Session) -> std::result::Result<(), String> { + s.active().map(|_| ()).ok_or_else(|| "no document open".into()) + } + + /// Generate ▸ Image Assets needs Preferences ▸ Plug-ins ▸ Generator enabled, as in + /// Photoshop (where "Enable Generator" is unchecked until turned on). + fn generator_enabled(s: &Session) -> std::result::Result<(), String> { + has_doc(s)?; + if !s.prefs().plug_ins.generator_enabled { + return Err("Enable Generator in Preferences ▸ Plug-ins".into()); + } + Ok(()) + } + vec![ + spec!( + "file.export.saveForWebLegacy", + "Save for Web (Legacy)…", + &["File", "Export"], + Some("Cmd+Alt+Shift+S"), + r##"{"preset":"GIF 128 Dithered|JPEG High|PNG-24|…"?,"format":"gif|png8|png24|jpeg|wbmp"="png24","palette":"perceptual|selective|adaptive|restrictive|exact|systemMac|systemWindows|uniform"="selective","colors":2..256=256,"colorTable":["#rrggbb",…]? (fixed opaque source palette, 1–256 entries; 255 with transparency),"colorTableEdits":{"0":"#rrggbb",…}? (replace entries after indexing; requires colorTable),"dither":"none|diffusion|pattern|noise"="diffusion","ditherAmount":0..100=88,"transparency":bool=true,"matte":"#rrggbb|none"="none" (a preset's own: white; formats without transparency go over white),"interlaced":bool=false,"webSnap":0..100=0,"quality":0..100=60,"progressive":bool=false,"optimized":bool=true,"embedIcc":bool=false,"metadata":"none|copyright|copyrightAndContact|allExceptCameraInfo|all"="copyright" (EXIF only with all),"convertToSrgb":bool=true,"width"|"height"|"percent"? (image size),"resample":"bicubic|bilinear|nearest"?,"path":file? (whole image),"dir":folder? (one file per slice in images/),"imagesFolder":relative-folder?="images","html":bool=false,"trustedSliceHtml":bool=false (only for trusted documents; emit raw no-image cell HTML),"slices":"all|user"="all","numbers":[n]?} → no path/dir: {bytes,width,height,colors,colorTable,transparentIndex} estimate; else {files, html, bytes, warnings}"##, + has_doc, + save_for_web + ), + spec!( + "file.export.exportPreferences", + "Export Preferences…", + &["File", "Export"], + None, + r##"{"quickExportFormat":"png|jpg|gif|webp|exr"?,"quickExportLocation":"ask|sameFolder"?,"jpegQuality":1..100?,"webpLossless":bool?,"webpQuality":1..100?,"metadata":"none|copyright|all"?,"convertToSrgb":bool?} → {values}"##, + |_| Ok(()), + export_preferences + ), + spec!( + "file.export.quickExport", + "Quick Export", + &[], + None, + r##"{"path":str? (required unless Export Preferences › Location is "sameFolder" and the document is saved)} → {path, format, bytes, warnings}"##, + native_doc, + quick_export + ), + spec!( + "file.generate.imageAssets", + "Image Assets", + &["File", "Generate"], + None, + r##"{"on":bool? (default: toggle),"dir":folder? (default -assets next to the file)} → {enabled, files, errors}; layers named like "foo.png", "200% foo@2x.png", "48x48 icons/a.png8", "photo.jpg80%" are exported, now and after each save"##, + generator_enabled, + image_assets + ), + ] +} + +#[cfg(test)] +#[path = "web_cmds/tests.rs"] +mod tests; diff --git a/crates/engine/src/cmd/web_cmds/assets.rs b/crates/engine/src/cmd/web_cmds/assets.rs new file mode 100644 index 0000000000..23f2da990c --- /dev/null +++ b/crates/engine/src/cmd/web_cmds/assets.rs @@ -0,0 +1,368 @@ +use super::optimizer::{optimize, web_document}; +use super::settings::{WebFormat, WebMetadata, WebSettings}; +use super::*; + +// ---------- Generate › Image Assets ---------- + +/// One asset requested by a layer name. +#[derive(Clone, Debug, PartialEq)] +pub struct AssetSpec { + /// Relative output path (folders allowed), extension included. + pub file: String, + /// png8 | png24 | png32 | jpg | gif | webp + pub format: String, + /// JPEG quality 1..=100. + pub quality: Option, + /// Uniform scale (1.0 = 100 %). + pub scale: Option, + /// Target width / height in px (`?` = keep aspect). + pub width: Option, + pub height: Option, +} + +/// A `default` layer variant: size plus a folder (`low/`) or name suffix (`@2x`). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct AssetDefault { + pub scale: Option, + pub width: Option, + pub height: Option, + pub folder: String, + pub suffix: String, +} + +fn unit_px(tok: &str, dpi: f64) -> Option> { + if tok == "?" { + return Some(None); + } + let (num, k) = if let Some(n) = tok.strip_suffix("px") { + (n, 1.0) + } else if let Some(n) = tok.strip_suffix("in") { + (n, dpi) + } else if let Some(n) = tok.strip_suffix("cm") { + (n, dpi / 2.54) + } else if let Some(n) = tok.strip_suffix("mm") { + (n, dpi / 25.4) + } else { + (tok, 1.0) + }; + num.trim().parse::().ok().filter(|v| *v > 0.0).map(|v| Some(v * k)) +} + +/// `200%` or `WxH` (units px/in/cm/mm, `?` wildcard) at the start of `item`; returns the size and +/// the rest. +fn parse_size(item: &str, dpi: f64) -> (Option, Option, Option, &str) { + let item = item.trim(); + let (first, rest) = item.split_once(char::is_whitespace).map_or((item, ""), |(a, b)| (a, b.trim())); + if let Some(pc) = first.strip_suffix('%').and_then(|n| n.parse::().ok()).filter(|v| *v > 0.0) { + return (Some(pc / 100.0), None, None, rest); + } + // "100x50", "2in x 1in", "?x100" + if let Some((w, h)) = first.split_once(['x', 'X']).filter(|(w, h)| !w.is_empty() && !h.is_empty()) + && let (Some(w), Some(h)) = (unit_px(w, dpi), unit_px(h, dpi)) + { + return (None, w, h, rest); + } + // Spaced form "2in x 1in name.png": three tokens. + let toks: Vec<&str> = item.split_whitespace().collect(); + if toks.len() >= 4 + && toks[1].eq_ignore_ascii_case("x") + && let (Some(w), Some(h)) = (unit_px(toks[0], dpi), unit_px(toks[2], dpi)) + { + // Skip exactly the three size tokens; searching for the name's first word could match inside the size. + let mut rest = item; + for _ in 0..3 { + rest = rest.trim_start().trim_start_matches(|c: char| !c.is_whitespace()); + } + return (None, w, h, rest.trim_start()); + } + (None, None, None, item) +} + +/// Parses a layer name into its asset specs (empty when it names no asset). +pub fn parse_asset_name(name: &str, dpi: f64) -> Vec { + let mut out = Vec::new(); + for item in name.split([',', '+']) { + let (scale, width, height, rest) = parse_size(item, dpi); + let file = rest.trim(); + let Some((stem_part, ext)) = file.rsplit_once('.') else { continue }; + if stem_part.is_empty() { + continue; + } + let ext_l = ext.to_ascii_lowercase(); + let (format, quality, out_ext) = if let Some(q) = ext_l.strip_prefix("jpeg").or_else(|| ext_l.strip_prefix("jpg")) { + let q = q.trim(); + let quality = if q.is_empty() { + None + } else if let Some(pc) = q.strip_suffix('%') { + pc.parse::().ok().map(|v| v.clamp(1, 100) as u8) + } else { + // 1–10 scale. + q.parse::().ok().map(|v| (v.clamp(1, 10) * 10) as u8) + }; + if !q.is_empty() && quality.is_none() { + continue; + } + ("jpg".to_string(), quality, if ext_l.starts_with("jpeg") { "jpeg" } else { "jpg" }) + } else { + match ext_l.as_str() { + "png" | "png32" => ("png32".to_string(), None, "png"), + "png24" => ("png24".to_string(), None, "png"), + "png8" => ("png8".to_string(), None, "png"), + "gif" => ("gif".to_string(), None, "gif"), + "webp" => ("webp".to_string(), None, "webp"), + _ => continue, + } + }; + out.push(AssetSpec { file: format!("{stem_part}.{out_ext}"), format, quality, scale, width, height }); + } + out +} + +/// Parses a `default …` layer name into its variants. +pub fn parse_defaults(name: &str, dpi: f64) -> Option> { + let rest = name.trim().strip_prefix("default")?; + if !rest.is_empty() && !rest.starts_with(char::is_whitespace) { + return None; + } + let mut v = Vec::new(); + for item in rest.split([',', '+']) { + let (scale, width, height, tail) = parse_size(item, dpi); + let tail = tail.trim(); + let (folder, suffix) = match tail.rfind('/') { + Some(i) => (tail[..=i].to_string(), tail[i + 1..].to_string()), + None => (String::new(), tail.to_string()), + }; + if scale.is_none() && width.is_none() && height.is_none() && folder.is_empty() && suffix.is_empty() { + continue; + } + v.push(AssetDefault { scale, width, height, folder, suffix }); + } + Some(v) +} + +fn asset_settings(spec: &AssetSpec) -> WebSettings { + let base = WebSettings { transparency: true, matte: None, metadata: WebMetadata::None, ..WebSettings::default() }; + match spec.format.as_str() { + "jpg" => WebSettings { format: WebFormat::Jpeg, quality: spec.quality.unwrap_or(90), matte: Some([1.0, 1.0, 1.0]), ..base }, + "png8" => WebSettings { format: WebFormat::Png8, dither: Dither::None, ..base }, + "png24" => WebSettings { format: WebFormat::Png24, transparency: false, matte: Some([1.0, 1.0, 1.0]), ..base }, + "gif" => WebSettings { format: WebFormat::Gif, dither: Dither::None, ..base }, + _ => WebSettings { format: WebFormat::Png24, ..base }, + } +} + +/// Layer names and `default` folders are document data, so reject unsafe output components. +pub(super) fn asset_path_components(relative: &str) -> Result> { + // Split both separator styles even on Unix, where a backslash would otherwise be a legal + // filename. This also catches Windows drive, rooted, and UNC paths on every platform. + let mut parts = Vec::new(); + for part in relative.split(['/', '\\']) { + if part.is_empty() + || part == "." + || part == ".." + || part.ends_with('.') + || part.ends_with(' ') + || part.contains(':') + || part.contains('\0') + || is_windows_device_name(part) + { + return Err(other(format!("asset path {relative:?} has an unsafe component {part:?}"))); + } + parts.push(part); + } + Ok(parts) +} + +/// Resolve a generated asset below the selected output directory. The atomic writer follows an +/// existing file symlink, so reject it and directory symlinks before writing. +pub(super) fn asset_output_path(dir: &str, relative: &str) -> Result<(String, String)> { + if dir.is_empty() { + return Err(other("image assets need an output directory")); + } + let mut parts = asset_path_components(relative)?; + // Keep the caller's spelling in the result (for example /var on macOS), while writes use + // the canonical directory so a symlink in the selected root cannot move the destination. + let mut reported = std::path::PathBuf::from(dir); + for part in &parts { + reported.push(part); + } + let file = parts.pop().ok_or_else(|| other(format!("asset path {relative:?} is empty")))?; + let chosen_root: std::path::PathBuf = std::path::Path::new(dir).components().collect(); + std::fs::create_dir_all(&chosen_root).map_err(|e| other(format!("asset output directory {dir:?}: {e}")))?; + // The caller chose this root, so a symlink to an existing directory is intentional. All + // document-derived components below it are checked against its canonical target. + let root = std::fs::canonicalize(&chosen_root).map_err(|e| other(format!("asset output directory {dir:?}: {e}")))?; + let mut parent = root.clone(); + for part in parts { + parent.push(part); + match std::fs::symlink_metadata(&parent) { + Ok(meta) if meta.file_type().is_symlink() => { + return Err(other(format!("asset path {relative:?} crosses a symlink at {}", parent.display()))); + } + Ok(meta) if !meta.is_dir() => { + return Err(other(format!("asset path {relative:?} has a non-directory at {}", parent.display()))); + } + Ok(_) => {} + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + std::fs::create_dir(&parent).map_err(|e| other(format!("asset folder {}: {e}", parent.display())))?; + } + Err(e) => return Err(other(format!("asset folder {}: {e}", parent.display()))), + } + let actual = std::fs::canonicalize(&parent).map_err(|e| other(format!("asset folder {}: {e}", parent.display())))?; + if !actual.starts_with(&root) { + return Err(other(format!("asset path {relative:?} escapes output directory {dir:?}"))); + } + parent = actual; + } + let parent = std::fs::canonicalize(&parent).map_err(|e| other(format!("asset folder {}: {e}", parent.display())))?; + if !parent.starts_with(&root) { + return Err(other(format!("asset path {relative:?} escapes output directory {dir:?}"))); + } + let output = parent.join(file); + match std::fs::symlink_metadata(&output) { + Ok(meta) if meta.file_type().is_symlink() => { + return Err(other(format!("asset path {relative:?} points to a symlink"))); + } + Ok(meta) if !meta.is_file() => { + return Err(other(format!("asset path {relative:?} is not a file"))); + } + Ok(_) => {} + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => return Err(other(format!("asset path {relative:?}: {e}"))), + } + Ok((output.to_string_lossy().into_owned(), reported.to_string_lossy().into_owned())) +} + +/// Exports every asset named by `doc`'s layers into `dir`. Returns (files, errors). +/// +/// Each file is written once per run (#6614): when two layers (or two default variants) name the +/// same file, the one higher in the Layers panel keeps it and the other is reported in `errors`. +/// Names are compared ignoring case, as `Logo.png` and `logo.png` are one file on Windows and +/// macOS. +/// +/// A layer is trimmed to its visible pixels; an artboard keeps its whole board, transparent edges +/// included, as File › Export › Artboards to Files writes it (Photoshop's Generator exports an +/// artboard asset at the board's bounds). +pub fn generate_assets(doc: &Document, dir: &str) -> (Vec, Vec) { + let dpi = f64::from(doc.resolution_dpi.max(1.0)); + let mut defaults: Option> = None; + let mut by_layer: Vec> = Vec::new(); + for (_, _, l) in doc.walk() { + if let Some(d) = parse_defaults(&l.name, dpi) { + defaults = Some(d); + continue; + } + if matches!(l.content, LayerContent::Adjustment(_)) { + continue; + } + by_layer.push(parse_asset_name(&l.name, dpi).into_iter().map(|spec| (l.id, spec)).collect()); + } + // Top layer first, as the Layers panel lists them (`walk` goes bottom to top). + let jobs: Vec<(LayerId, AssetSpec)> = by_layer.into_iter().rev().flatten().collect(); + let variants: Vec = match defaults { + Some(d) if !d.is_empty() => d, + _ => vec![AssetDefault::default()], + }; + let mut files = Vec::new(); + let mut errors = Vec::new(); + let mut written = std::collections::HashSet::new(); + for (id, spec) in &jobs { + for v in &variants { + let r = (|| -> Result { + let (name_stem, ext) = spec.file.rsplit_once('.').unwrap_or((spec.file.as_str(), "png")); + let rel = format!("{}{}{}.{ext}", v.folder, name_stem, v.suffix); + let key = asset_path_components(&rel)?.join("/").to_lowercase(); + if written.contains(&key) { + return Err(other(format!("{rel}: another layer already writes this file; rename one of the layers"))); + } + let mut one = match crate::artboard_cmds::artboard_document(doc, *id)? { + // Like Photoshop's Generator, a board with nothing on it is refused rather + // than written as a blank file. + Some(board) if !has_pixels(&board) => return Err(other("the layer is empty")), + Some(board) => board, + None => crate::layer_menu_cmds::layer_document(doc, *id)?, + }; + one.metadata = Default::default(); + let (w0, h0) = (f64::from(one.size.width), f64::from(one.size.height)); + // The layer's own size spec wins; default variants scale on top of it. + let mut k = spec.scale.unwrap_or(1.0); + let (mut tw, mut th) = (w0 * k, h0 * k); + match (spec.width, spec.height) { + (Some(w), Some(h)) => (tw, th) = (w, h), + (Some(w), None) => (tw, th) = (w, h0 * w / w0), + (None, Some(h)) => (tw, th) = (w0 * h / h0, h), + _ => {} + } + k = v.scale.unwrap_or(1.0); + tw *= k; + th *= k; + match (v.width, v.height) { + (Some(w), Some(h)) => (tw, th) = (w, h), + (Some(w), None) => (tw, th) = (w, th * w / tw), + (None, Some(h)) => (tw, th) = (tw * h / th, h), + _ => {} + } + let st = asset_settings(spec); + let p = json!({"width": tw.round().max(1.0), "height": th.round().max(1.0)}); + let (wdoc, _, _) = web_document(&one, &p, &WebSettings { convert_to_srgb: true, ..st.clone() })?; + if spec.format == "webp" { + let (out, reported) = asset_output_path(dir, &rel)?; + crate::file_cmds::save_doc(&wdoc, &out, None)?; + written.insert(key); + return Ok(reported); + } + let buf = photocraft_compose::flatten(&wdoc); + let o = optimize(&buf.px, wdoc.size.width as usize, wdoc.bounds(), &st, None, None, None, wdoc.resolution_dpi, false)?; + let (out, reported) = asset_output_path(dir, &rel)?; + write_file(&out, &o.bytes)?; + written.insert(key); + Ok(reported) + })(); + match r { + Ok(f) => files.push(f), + Err(e) => errors.push(json!({"asset": spec.file, "error": e.to_string()})), + } + } + } + (files, errors) +} + +/// Whether any pixel of `doc` is not fully transparent. +fn has_pixels(doc: &Document) -> bool { + photocraft_compose::render(doc, doc.bounds()).px.iter().any(|q| q[3] > 0.0) +} + +/// `/-assets`. +pub fn assets_dir(doc_path: &str) -> String { + let p = std::path::Path::new(doc_path); + let dir = p.parent().map(|d| d.to_string_lossy().into_owned()).unwrap_or_default(); + join(&dir, &format!("{}-assets", stem(doc_path))) +} + +/// File › Generate › Image Assets: toggles generation for the active document (or sets it with +/// `on`) and, when it is on and the output folder is known, writes the assets now. +pub(super) fn image_assets(s: &mut Session, p: &Value) -> Result { + let d = s.active().ok_or(EngineError::NoDocument)?; + let id: DocId = d.doc.id; + let was = s.file_menu.image_assets.contains(&id); + let on = p.get("on").and_then(Value::as_bool).unwrap_or(!was); + if on { + if !was { + s.file_menu.image_assets.push(id); + } + } else { + s.file_menu.image_assets.retain(|x| *x != id); + } + let d = s.active().ok_or(EngineError::NoDocument)?; + let dir = p.get("dir").and_then(Value::as_str).map(str::to_string).or_else(|| d.path.as_deref().map(assets_dir)); + if !on { + return Ok(json!({"enabled": false})); + } + match dir { + Some(dir) if !cfg!(target_arch = "wasm32") => { + let (files, errors) = generate_assets(&d.doc, &dir); + Ok(json!({"enabled": true, "dir": dir, "files": files, "errors": errors})) + } + _ => Ok(json!({"enabled": true, "dir": null, "files": [], "note": "assets are written when the document is saved"})), + } +} diff --git a/crates/engine/src/web_cmds/color_table_tests.rs b/crates/engine/src/cmd/web_cmds/color_table_tests.rs similarity index 100% rename from crates/engine/src/web_cmds/color_table_tests.rs rename to crates/engine/src/cmd/web_cmds/color_table_tests.rs diff --git a/crates/engine/src/cmd/web_cmds/optimizer.rs b/crates/engine/src/cmd/web_cmds/optimizer.rs new file mode 100644 index 0000000000..98116d7d37 --- /dev/null +++ b/crates/engine/src/cmd/web_cmds/optimizer.rs @@ -0,0 +1,394 @@ +use super::settings::{WebFormat, WebMetadata, WebSettings}; +use super::*; + +// ---------- the image ---------- + +/// The document as Save for Web sees it: RGB (converted to sRGB unless told otherwise), resized +/// by `"width"`/`"height"`/`"percent"`, flattened. Returns the document and the scale factors. +pub fn web_document(doc: &Document, p: &Value, st: &WebSettings) -> Result<(Document, f64, f64)> { + let mut tmp = Session::new(); + tmp.add_document(doc.clone(), None); + let mode = doc.mode; + if mode != photocraft_color::ColorMode::Rgb { + tmp.execute("image.mode.rgb", json!({}))?; + } + if st.convert_to_srgb && doc.icc_profile.is_some() { + // Documents without a profile are treated as sRGB already. + tmp.execute("edit.convertToProfile", json!({"profile": "srgb", "intent": "perceptual"}))?; + } + let (w0, h0) = (f64::from(doc.size.width), f64::from(doc.size.height)); + let pct = p.get("percent").and_then(Value::as_f64).filter(|v| *v > 0.0); + let w = p.get("width").and_then(Value::as_f64).filter(|v| *v > 0.0); + let h = p.get("height").and_then(Value::as_f64).filter(|v| *v > 0.0); + let (nw, nh) = match (pct, w, h) { + (Some(pc), _, _) => (w0 * pc / 100.0, h0 * pc / 100.0), + (_, Some(w), Some(h)) => (w, h), + (_, Some(w), None) => (w, h0 * w / w0), + (_, None, Some(h)) => (w0 * h / h0, h), + _ => (w0, h0), + }; + let (nw, nh) = (nw.round().max(1.0), nh.round().max(1.0)); + if (nw - w0).abs() >= 1.0 || (nh - h0).abs() >= 1.0 { + let resample = p.get("resample").and_then(Value::as_str).unwrap_or("bicubic"); + tmp.execute("image.imageSize", json!({"width": nw, "height": nh, "resample": resample}))?; + } + let out = (*tmp.active().ok_or(EngineError::NoDocument)?.doc).clone(); + Ok((out, nw / w0, nh / h0)) +} + +/// An optimised image. +#[derive(Clone, Debug)] +pub struct Optimized { + pub bytes: Vec, + pub ext: &'static str, + pub width: u32, + pub height: u32, + /// Colours in the palette (indexed formats). + pub colors: Option, + /// Opaque source palette before replacements (empty for non-indexed formats). + pub color_table: Vec<[u8; 3]>, + pub transparent_index: Option, + /// Indexed pixels for previews; empty for non-indexed formats or when preview is disabled. + pub indices: Vec, + /// What the optimised file looks like, straight RGBA8 (for the dialog's previews). + pub preview: Vec, +} + +pub(super) fn to8(v: f32) -> u8 { + (v.clamp(0.0, 1.0) * 255.0).round() as u8 +} + +/// XMP to embed for the metadata choice. +pub fn web_xmp(doc: &Document, m: WebMetadata) -> Option { + let xmp = doc.metadata.xmp.as_deref()?; + match m { + WebMetadata::None => None, + WebMetadata::All | WebMetadata::AllExceptCameraInfo => Some(xmp.to_string()), + WebMetadata::Copyright | WebMetadata::CopyrightAndContact => { + let info = crate::file_cmds::read_file_info(Some(xmp)); + let mut keep = serde_json::Map::new(); + let mut keys = vec!["copyright", "copyrightStatus", "copyrightUrl"]; + if m == WebMetadata::CopyrightAndContact { + keys.extend(["author", "authorTitle"]); + } + for k in keys { + if let Some(v) = info.get(k).filter(|v| v.as_str().is_some_and(|s| !s.is_empty()) || v.is_array()) { + keep.insert(k.into(), v.clone()); + } + } + (!keep.is_empty()).then(|| crate::file_cmds::write_file_info(None, &Value::Object(keep))) + } + } +} + +/// The photo's EXIF to embed for the metadata choice: only "All" carries it (#7436). +pub fn web_exif(doc: &Document, m: WebMetadata) -> Option<&[u8]> { + doc.metadata.exif.as_deref().map(Vec::as_slice).filter(|_| m == WebMetadata::All) +} + +/// The response's warnings: EXIF that a JPEG couldn't hold (one segment, about 64 KB). +pub(super) fn web_warnings(st: &WebSettings, exif: Option<&[u8]>, dpi: f32) -> Vec { + exif.filter(|x| st.format == WebFormat::Jpeg && !photocraft_codecs::web::jpeg_exif_fits(x, Some(dpi))) + .map(|x| photocraft_codecs::FidelityWarning::MetadataTooLarge { what: "EXIF", bytes: x.len() }.to_string()) + .into_iter() + .collect() +} + +/// Optimises `rect` of `px` (straight RGBA, `bw` wide) with `st`. `preview` also returns what +/// the file looks like (the dialog's panes); exports skip it. +#[allow(clippy::too_many_arguments)] +pub fn optimize( + px: &[[f32; 4]], + bw: usize, + rect: Rect, + st: &WebSettings, + icc: Option<&[u8]>, + exif: Option<&[u8]>, + xmp: Option<&str>, + dpi: f32, + preview: bool, +) -> Result { + if bw == 0 || rect.x0 < 0 || rect.y0 < 0 || rect.is_empty() || rect.x1 as usize > bw || (rect.y1 as usize).checked_mul(bw).is_none_or(|end| end > px.len()) + { + return Err(other("slice is outside the pixel buffer")); + } + let (w, h) = (rect.width() as usize, rect.height() as usize); + let row = |y: i32| { + let o = y as usize * bw; + px.get(o + rect.x0 as usize..o + rect.x1 as usize).unwrap_or(&[]) + }; + let region = || (rect.y0..rect.y1).flat_map(row); + let matte = st.matte.unwrap_or([1.0, 1.0, 1.0]); + let over = |p: &[f32; 4]| -> [f32; 4] { + [p[0] * p[3] + matte[0] * (1.0 - p[3]), p[1] * p[3] + matte[1] * (1.0 - p[3]), p[2] * p[3] + matte[2] * (1.0 - p[3]), 1.0] + }; + let (ww, hh) = (w as u32, h as u32); + let e = |e: photocraft_codecs::CodecError| other(e); + let mut look: Vec = Vec::new(); + let mut color_table = Vec::new(); + let mut transparent_index = None; + let mut indices = Vec::new(); + let (bytes, colors) = match st.format { + WebFormat::Png24 => { + let alpha = st.transparency && region().any(|p| p[3] < 1.0); + let k = if alpha { 4 } else { 3 }; + let mut data = Vec::with_capacity(w * h * k); + for p in region() { + let q = if alpha { *p } else { over(p) }; + data.extend_from_slice(&[to8(q[0]), to8(q[1]), to8(q[2]), to8(q[3])][..k]); + } + if preview { + look = if alpha { data.clone() } else { data.as_chunks::<3>().0.iter().flat_map(|c| [c[0], c[1], c[2], 255]).collect() }; + } + let layout = if alpha { photocraft_codecs::ChannelLayout::Rgba } else { photocraft_codecs::ChannelLayout::Rgb }; + let meta = photocraft_codecs::Metadata { dpi: Some((dpi, dpi)), xmp: xmp.map(str::to_string), ..Default::default() }; + let img = photocraft_codecs::Image::from_u8(ww, hh, layout, data).map_err(e)?.with_icc(icc.map(<[u8]>::to_vec)).with_meta(meta); + let opts = photocraft_codecs::EncodeOptions { + png_interlaced: st.interlaced, + embed_icc: icc.is_some(), + embed_metadata: xmp.is_some(), + ..Default::default() + }; + (photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &opts).map_err(e)?, None) + } + WebFormat::Jpeg => { + let mut rgb = Vec::with_capacity(w * h * 3); + for p in region() { + let q = over(p); + rgb.extend_from_slice(&[to8(q[0]), to8(q[1]), to8(q[2])]); + } + // Save for Web's 0–100 quality → encoder 1–100. + let q = st.quality.max(1); + let bytes = + photocraft_codecs::web::encode_jpeg_rgb8(ww, hh, &rgb, q, st.progressive, st.optimized, icc.filter(|_| st.embed_icc), Some(dpi), exif, xmp) + .map_err(e)?; + if preview { + // The preview shows the compression artefacts. + look = match photocraft_codecs::decode(&bytes) { + Ok(img) => img.convert(photocraft_codecs::ChannelLayout::Rgba, photocraft_codecs::SampleType::U8).data().to_vec(), + Err(_) => rgb.as_chunks::<3>().0.iter().flat_map(|c| [c[0], c[1], c[2], 255]).collect(), + }; + } + (bytes, None) + } + WebFormat::Wbmp => { + let mut gray: Vec = region() + .map(|p| { + let q = over(p); + 0.299 * q[0] + 0.587 * q[1] + 0.114 * q[2] + }) + .collect(); + let method = match st.dither { + Dither::None => quantize::BitmapMethod::Threshold, + Dither::Pattern => quantize::BitmapMethod::Pattern, + _ => quantize::BitmapMethod::Diffusion, + }; + quantize::to_bitmap(&mut gray, w, method); + let white: Vec = gray.iter().map(|v| *v > 0.5).collect(); + if preview { + look = white.iter().flat_map(|b| if *b { [255, 255, 255, 255] } else { [0, 0, 0, 255] }).collect(); + } + (photocraft_codecs::web::encode_wbmp(ww, hh, &white).map_err(e)?, Some(2)) + } + WebFormat::Gif | WebFormat::Png8 => { + let transparent = st.transparency && region().any(|p| p[3] < 0.5); + // Partially transparent edges blend with the matte; with transparency off everything does. + let mut work: Vec<[f32; 4]> = region() + .map(|p| { + if st.transparency && p[3] < 0.5 { + [0.0, 0.0, 0.0, 0.0] + } else if st.transparency && st.matte.is_none() { + [p[0], p[1], p[2], 1.0] + } else { + over(p) + } + }) + .collect(); + let room = if transparent { st.colors.saturating_sub(1).max(2) } else { st.colors }; + let mut pal = if let Some(table) = &st.color_table { + if table.is_empty() || table.len() > if transparent { 255 } else { 256 } { + return Err(other("colorTable has too many entries for this image's transparency")); + } + table.clone() + } else { + // Large images: build adaptive palettes from an even ~1 MP sample (Exact needs all). + let n_opaque = work.iter().filter(|p| p[3] >= 0.5).count(); + let step = if n_opaque > 1 << 20 && st.palette != PaletteKind::Exact { n_opaque / (1 << 20) + 1 } else { 1 }; + let mut src: Vec<[f32; 4]> = work.iter().filter(|p| p[3] >= 0.5).step_by(step).copied().collect(); + if src.is_empty() { + src = work.clone(); + } + quantize::build_palette(&src, st.palette, room, Forced::None).map_err(other)? + }; + if st.web_snap > 0.0 && st.color_table.is_none() { + let tol = (st.web_snap * 255.0) as u8; + for c in &mut pal { + let snap = c.map(|x| ((f32::from(x) / 51.0).round() * 51.0) as u8); + if c.iter().zip(snap).all(|(a, b)| a.abs_diff(b) <= tol) { + *c = snap; + } + } + } + if transparent { + pal.truncate(255); + } + let first = pal.first().copied().ok_or_else(|| other("empty colour table"))?; + color_table = pal.clone(); + let t = transparent.then(|| { + pal.push(first); + pal.len() - 1 + }); + transparent_index = t; + let idx = quantize_rows(&mut work, w, &pal, st.dither, st.dither_amount, t); + for (index, color) in &st.color_table_edits { + let slot = pal.get_mut(*index).filter(|_| Some(*index) != t).ok_or_else(|| other("colour edit is outside the opaque palette"))?; + *slot = *color; + } + if preview { + look = idx + .iter() + .flat_map(|k| { + let c = pal.get(*k as usize).copied().unwrap_or(first); + [c[0], c[1], c[2], if Some(*k as usize) == t { 0 } else { 255 }] + }) + .collect(); + } + let tt = t.map(|v| v as u8); + let bytes = if st.format == WebFormat::Gif { + photocraft_codecs::web::encode_gif_indexed(ww, hh, &idx, &pal, tt, st.interlaced).map_err(e)? + } else { + photocraft_codecs::encode_png_indexed(ww, hh, &idx, &pal, tt, None, None).map_err(e)? + }; + if preview { + indices = idx; + } + (bytes, Some(pal.len())) + } + }; + Ok(Optimized { bytes, ext: st.format.ext(), width: ww, height: hh, colors, color_table, transparent_index, indices, preview: look }) +} + +/// Nearest palette entry through a lazily filled 6-bit-per-channel inverse colour map: each +/// 4×4×4 cell is resolved once (by its centre), so large images cost a table lookup per pixel +/// instead of a palette scan. `t` (the transparent index) is never returned. +struct InverseMap<'a> { + pal: &'a [[u8; 3]], + t: Option, + lut: Vec, +} + +impl<'a> InverseMap<'a> { + fn new(pal: &'a [[u8; 3]], t: Option) -> Self { + InverseMap { pal, t, lut: vec![u16::MAX; 1 << 18] } + } + #[inline] + fn get(&mut self, c: [f32; 3]) -> usize { + let q = c.map(|v| ((v.clamp(0.0, 1.0) * 255.0).round() as usize) >> 2); + let key = q[0] << 12 | q[1] << 6 | q[2]; + let v = self.lut[key]; + if v != u16::MAX { + return usize::from(v); + } + let center = q.map(|v| (v * 4 + 2) as f32); + let mut best = (f32::MAX, 0usize); + for (i, e) in self.pal.iter().enumerate() { + if Some(i) == self.t { + continue; + } + let d: f32 = (0..3).map(|k| (center[k] - f32::from(e[k])).powi(2)).sum(); + if d < best.0 { + best = (d, i); + } + } + self.lut[key] = best.1 as u16; + best.1 + } +} + +fn hash01(x: usize, y: usize) -> f32 { + let mut h = (x as u32).wrapping_mul(0x8da6_b343) ^ (y as u32).wrapping_mul(0xd816_3841) ^ 0x2545_f491; + h ^= h >> 13; + h = h.wrapping_mul(0x5bd1_e995); + h ^= h >> 15; + (h & 0xffff) as f32 / 65535.0 +} + +/// Palette mapping with dithering (Floyd–Steinberg diffusion, 8×8 Bayer pattern, noise), like +/// `algo::quantize::quantize` but through [`InverseMap`]. `y0` keeps patterns continuous across +/// bands. Pixels with alpha < ½ take index `t`. +fn quantize_band(px: &mut [[f32; 4]], w: usize, y0: usize, pal: &[[u8; 3]], dither: Dither, amount: f32, t: Option) -> Vec { + let h = px.len() / w.max(1); + let mut map = InverseMap::new(pal, t); + let mut idx = vec![0u8; px.len()]; + let opaque_n = pal.len() - usize::from(t.is_some()); + let spread = (1.0 / (opaque_n as f32).cbrt().max(1.0)).min(0.5) * amount.clamp(0.0, 1.0); + let a = amount.clamp(0.0, 1.0); + let mut cur = vec![[0.0f32; 3]; if dither == Dither::Diffusion { w + 2 } else { 0 }]; + let mut next = cur.clone(); + for y in 0..h { + if dither == Dither::Diffusion { + std::mem::swap(&mut cur, &mut next); + next.iter_mut().for_each(|e| *e = [0.0; 3]); + } + for x in 0..w { + let i = y * w + x; + let p = px[i]; + if p[3] < 0.5 + && let Some(t) = t + { + idx[i] = t as u8; + continue; + } + let mut c = [p[0], p[1], p[2]]; + match dither { + Dither::None => {} + Dither::Diffusion => (0..3).for_each(|k| c[k] += cur[x + 1][k]), + Dither::Pattern => { + let d = quantize::bayer8(x, y0 + y) * spread; + c = c.map(|v| v + d); + } + Dither::Noise => { + let d = (hash01(x, y0 + y) - 0.5) * spread; + c = c.map(|v| v + d); + } + } + let c = c.map(|v| v.clamp(0.0, 1.0)); + let k = map.get(c); + idx[i] = k as u8; + if dither == Dither::Diffusion { + let e = pal[k].map(|v| f32::from(v) / 255.0); + let d: [f32; 3] = std::array::from_fn(|q| (c[q] - e[q]) * a); + for q in 0..3 { + cur[x + 2][q] += d[q] * 7.0 / 16.0; + next[x][q] += d[q] * 3.0 / 16.0; + next[x + 1][q] += d[q] * 5.0 / 16.0; + next[x + 2][q] += d[q] / 16.0; + } + } + } + } + idx +} + +/// [`quantize_band`] over the whole image, in parallel bands of 64 rows when the dither is +/// position-independent. Error diffusion carries error down the image, so it stays sequential. +fn quantize_rows(px: &mut [[f32; 4]], w: usize, pal: &[[u8; 3]], dither: Dither, amount: f32, t: Option) -> Vec { + let h = px.len() / w.max(1); + if dither == Dither::Diffusion || h < 128 || cfg!(target_arch = "wasm32") { + return quantize_band(px, w, 0, pal, dither, amount, t); + } + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + let band = w * 64; + let mut idx = vec![0u8; px.len()]; + px.par_chunks_mut(band) + .zip(idx.par_chunks_mut(band)) + .enumerate() + .for_each(|(i, (p, out))| out.copy_from_slice(&quantize_band(p, w, i * 64, pal, dither, amount, t))); + idx + } + // Single-threaded on wasm (the early return above always takes this path there). + #[cfg(target_arch = "wasm32")] + quantize_band(px, w, 0, pal, dither, amount, t) +} diff --git a/crates/engine/src/cmd/web_cmds/quick.rs b/crates/engine/src/cmd/web_cmds/quick.rs new file mode 100644 index 0000000000..c017eb3d2f --- /dev/null +++ b/crates/engine/src/cmd/web_cmds/quick.rs @@ -0,0 +1,147 @@ +use super::optimizer::{optimize, web_document, web_exif, web_warnings, web_xmp}; +use super::settings::WebSettings; +use super::*; + +// ---------- Export Preferences / Quick Export ---------- + +/// File › Export › Export Preferences…: sets the given `export.*` preferences through `prefs.set` +/// (validated like any other preference) and returns the whole section. +pub(super) fn export_preferences(s: &mut Session, p: &Value) -> Result { + let cmd = "file.export.exportPreferences"; + let mut values = serde_json::Map::new(); + for (k, key) in [ + ("quickExportFormat", "export.quickExportFormat"), + ("quickExportLocation", "export.quickExportLocation"), + ("jpegQuality", "export.jpegQuality"), + ("webpLossless", "export.webpLossless"), + ("webpQuality", "export.webpQuality"), + ("metadata", "export.metadata"), + ("convertToSrgb", "export.convertToSrgb"), + ] { + if let Some(v) = p.get(k) { + values.insert(key.into(), v.clone()); + } + } + if !values.is_empty() { + s.execute("prefs.set", json!({"values": values})).map_err(|e| bad(cmd, e.to_string()))?; + } + Ok(json!({"section": "export", "values": s.prefs().get("export").unwrap_or(Value::Null)})) +} + +/// The Quick Export format's extension (Export Preferences › Format). +fn quick_export_ext(s: &Session) -> String { + serde_json::to_value(s.prefs().export.quick_export_format).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_else(|| "png".into()) +} + +/// Where Quick Export writes the active document with no `path` given: `.` beside +/// its file, when Export Preferences › Location is Same Folder and the document has a file. +pub fn quick_export_target(s: &Session) -> Option { + let same = s.prefs().export.quick_export_location == crate::prefs::ExportLocation::SameFolder; + let dp = s.active()?.path.as_deref().filter(|_| same)?; + let dir = std::path::Path::new(dp).parent().map(|d| d.to_string_lossy().into_owned()).unwrap_or_default(); + Some(join(&dir, &format!("{}.{}", stem(dp), quick_export_ext(s)))) +} + +/// Whether [`quick_export_target`] is the active document's own file (a document opened from +/// `photo.png` and exported as PNG), which Quick Export must not replace without asking (#6599). +pub fn quick_export_target_is_own_file(s: &Session) -> bool { + let own = s.active().and_then(|d| d.path.as_deref()); + quick_export_target(s).zip(own).is_some_and(|(target, own)| crate::file_cmds::same_file(&target, own)) +} + +/// File › Export › Quick Export as : the format, quality, metadata, colour space and +/// location from Export Preferences. `path` overrides the location ("ask" needs one). +pub(super) fn quick_export(s: &mut Session, p: &Value) -> Result { + let cmd = "file.export.quickExport"; + let prefs = s.prefs().export.clone(); + let fmt = quick_export_ext(s); + let path = match p.get("path").and_then(Value::as_str).filter(|v| !v.is_empty()) { + Some(v) => v.to_string(), + None => { + let Some(target) = quick_export_target(s) else { + return Err(bad(cmd, "missing `path` (Export Preferences › Location is \"ask\", or the document was never saved)")); + }; + // The document's own file is never replaced by an export the user didn't name (#6599). + if quick_export_target_is_own_file(s) { + return Err(bad(cmd, format!("the export would replace the document's own file {target}; give a `path`"))); + } + target + } + }; + // The name typed in the save dialog wins over Export Preferences' format: Quick Export as PNG + // renamed to `photo.jpeg` must write a JPEG, not PNG bytes upload checks refuse (#8519). + let fmt = match crate::file_cmds::extension(&path).as_deref() { + None => fmt, + Some("jpg" | "jpeg") => "jpg".into(), + Some(e @ ("png" | "gif" | "webp" | "exr")) => e.into(), + Some(e) => return Err(bad(cmd, format!("Quick Export writes PNG, JPEG, GIF, WebP or EXR, not .{e}; use Export As"))), + }; + let d = s.active().ok_or(EngineError::NoDocument)?; + let doc = d.doc.clone(); + if fmt == "exr" { + // EXR keeps floating-point scene values. The ordinary exporter converts to linear + // light; the web/sRGB pipeline would instead clamp HDR and negative values. + let opts = photocraft_io::ExportOptions { xmp: photocraft_io::XmpEmbed::None, ..Default::default() }; + let out = photocraft_io::export(&doc, "exr", &opts).map_err(other)?; + write_file(&path, &out.bytes)?; + crate::automate_cmds::fire_event(s, "export"); + return Ok(json!({"path": path, "format": fmt, "bytes": out.bytes.len(), "warnings": out.warnings})); + } + let metadata = serde_json::to_value(prefs.metadata).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default(); + let mut o = serde_json::Map::new(); + o.insert( + "metadata".into(), + json!(if metadata == "all" { + "all" + } else if metadata == "none" { + "none" + } else { + "copyright" + }), + ); + o.insert("convertToSrgb".into(), json!(prefs.convert_to_srgb)); + o.insert("transparency".into(), json!(true)); + o.insert("matte".into(), json!("#ffffff")); + match fmt.as_str() { + "jpg" => { + o.insert("format".into(), json!("jpeg")); + o.insert("quality".into(), json!(prefs.jpeg_quality.min(100))); + } + "gif" => { + o.insert("format".into(), json!("gif")); + } + "webp" => { + // WebP uses the regular exporter. Its optional quality is in the Photoshop-style + // 0–12 save scale: invert that mapping so the codec receives the chosen 1–100. + // Keeping quality absent preserves the historical lossless Quick Export behavior. + let (wdoc, _, _) = web_document(&doc, &json!({}), &WebSettings { convert_to_srgb: prefs.convert_to_srgb, ..Default::default() })?; + let quality = if prefs.webp_lossless { None } else { Some((f64::from(prefs.webp_quality.clamp(1, 100)) - 1.0) * 12.0 / 99.0) }; + let warnings = crate::file_cmds::save_doc(&wdoc, &path, quality)?; + crate::automate_cmds::fire_event(s, "export"); + return Ok(json!({"path": path, "format": fmt, "warnings": warnings})); + } + _ => { + o.insert("format".into(), json!("png24")); + } + } + let q = Value::Object(o); + let st = WebSettings::from_params(&q, cmd)?; + let (wdoc, _, _) = web_document(&doc, &json!({}), &st)?; + let buf = photocraft_compose::flatten(&wdoc); + let xmp = web_xmp(&doc, st.metadata); + let exif = web_exif(&doc, st.metadata); + let opt = optimize( + &buf.px, + wdoc.size.width as usize, + wdoc.bounds(), + &st, + wdoc.icc_profile.as_deref().map(|v| v.as_slice()), + exif, + xmp.as_deref(), + wdoc.resolution_dpi, + false, + )?; + write_file(&path, &opt.bytes)?; + crate::automate_cmds::fire_event(s, "export"); + Ok(json!({"path": path, "format": fmt, "bytes": opt.bytes.len(), "warnings": web_warnings(&st, exif, wdoc.resolution_dpi)})) +} diff --git a/crates/engine/src/cmd/web_cmds/save_web.rs b/crates/engine/src/cmd/web_cmds/save_web.rs new file mode 100644 index 0000000000..eeca746754 --- /dev/null +++ b/crates/engine/src/cmd/web_cmds/save_web.rs @@ -0,0 +1,304 @@ +use super::assets::{asset_output_path, asset_path_components}; +use super::optimizer::{optimize, web_document, web_exif, web_warnings, web_xmp}; +use super::settings::{WebSettings, rgb_hex}; +use super::*; + +/// A file-name-safe slice name. +fn slice_file(name: &str) -> String { + let s: String = name.chars().map(|c| if c.is_alphanumeric() || matches!(c, '-' | '_') { c } else { '_' }).collect(); + let s = if s.is_empty() { "slice".into() } else { s }; + portable_generated_stem(s) +} + +/// Generated filenames should remain usable on Windows even when a document or slice is named +/// after a reserved device. Caller-supplied path components are still rejected below. +fn portable_generated_stem(stem: String) -> String { + portable_device_name(stem) +} + +fn html_escape(s: &str) -> String { + s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """) +} + +/// Imported slice URLs are document data. Only ordinary web/contact links and relative links +/// become anchors; an unsupported scheme leaves the image unlinked. +fn safe_slice_url(url: &str) -> bool { + if url.is_empty() || url.trim() != url || url.chars().any(|c| c.is_control() || c == '\\') { + return false; + } + let delimiter = url.find(['/', '?', '#']).unwrap_or(url.len()); + let Some(colon) = url.find(':').filter(|pos| *pos < delimiter) else { + return true; + }; + let scheme = url.get(..colon).unwrap_or_default().to_ascii_lowercase(); + let rest = url.get(colon + 1..).unwrap_or_default(); + match scheme.as_str() { + "http" | "https" | "ftp" | "ftps" => rest.strip_prefix("//").is_some_and(|host| !host.is_empty() && !host.starts_with('/')), + "mailto" | "tel" => !rest.is_empty(), + _ => false, + } +} + +/// Keep the image folder relative to the selected export directory on every platform. +fn web_images_folder(images: &str, cmd: &str) -> Result { + if images.is_empty() { + return Ok(String::new()); + } + let trimmed = images.trim_end_matches(['/', '\\']); + if trimmed.is_empty() { + return Err(bad(cmd, "imagesFolder must be a relative folder name")); + } + let parts = asset_path_components(trimmed).map_err(|e| bad(cmd, format!("imagesFolder: {e}")))?; + Ok(parts.join("/")) +} + +fn web_output_path(dir: &str, relative: &str) -> Result { + let root = if dir.is_empty() { "." } else { dir }; + asset_output_path(root, relative).map(|(actual, _)| actual) +} + +fn web_derived_path(dir: &str, relative: &str, native_paths: bool) -> Result { + if native_paths { + web_output_path(dir, relative) + } else { + // Browser downloads use logical names, without a host filesystem to inspect. + asset_path_components(relative)?; + Ok(join(dir, relative)) + } +} + +fn scale_rect(r: Rect, sx: f64, sy: f64) -> Rect { + Rect::new( + (f64::from(r.x0) * sx).round() as i32, + (f64::from(r.y0) * sy).round() as i32, + (f64::from(r.x1) * sx).round() as i32, + (f64::from(r.y1) * sy).round() as i32, + ) +} + +/// The HTML table for `cells` (rect, td body) over a `w`×`h` image: one column per distinct x +/// edge, one row per y edge, colspan/rowspan per slice, and a spacer row fixing column widths. +fn html_table(title: &str, w: u32, h: u32, cells: &[(Rect, String, String)], spacer: Option<&str>) -> String { + let mut xs: Vec = cells.iter().flat_map(|(r, _, _)| [r.x0, r.x1]).collect(); + let mut ys: Vec = cells.iter().flat_map(|(r, _, _)| [r.y0, r.y1]).collect(); + xs.sort_unstable(); + xs.dedup(); + ys.sort_unstable(); + ys.dedup(); + let col = |x: i32| xs.iter().position(|v| *v == x).unwrap_or(0); + let row = |y: i32| ys.iter().position(|v| *v == y).unwrap_or(0); + let (nc, nr) = (xs.len().saturating_sub(1), ys.len().saturating_sub(1)); + let mut taken = vec![false; nc * nr]; + let mut by_row: Vec> = vec![Vec::new(); nr]; + for (r, attrs, body) in cells { + let (c0, c1, r0, r1) = (col(r.x0), col(r.x1), row(r.y0), row(r.y1)); + if (r0..r1).any(|j| (c0..c1).any(|i| taken[j * nc + i])) { + continue; // overlapped (the caller cuts slices into visible pieces, so this can't happen) + } + for j in r0..r1 { + for i in c0..c1 { + taken[j * nc + i] = true; + } + } + let mut td = String::from("\t\t 1 { + td.push_str(&format!(" colspan=\"{}\"", c1 - c0)); + } + if r1 - r0 > 1 { + td.push_str(&format!(" rowspan=\"{}\"", r1 - r0)); + } + td.push_str(attrs); + td.push('>'); + td.push_str(body); + td.push_str("\n"); + by_row[r0].push((c0, td)); + } + let mut s = format!( + "\n\n{t}\n\n\n\n\n\n", + t = html_escape(title) + ); + for (j, mut tds) in by_row.into_iter().enumerate() { + tds.sort_by_key(|(c, _)| *c); + s.push_str("\t\n"); + for (_, td) in tds { + s.push_str(&td); + } + if let Some(sp) = spacer { + s.push_str(&format!("\t\t\n", html_escape(sp), ys[j + 1] - ys[j])); + } + s.push_str("\t\n"); + } + if let Some(sp) = spacer { + s.push_str("\t\n"); + for i in 0..nc { + s.push_str(&format!("\t\t\n", html_escape(sp), xs[i + 1] - xs[i])); + } + s.push_str("\t\t\n\t\n"); + } + s.push_str("
\n\t\t\t\"\"
\n\t\t\t\"\"
\n\n\n\n"); + s +} + +/// File › Export › Save for Web (Legacy). +pub(super) fn save_for_web(s: &mut Session, p: &Value) -> Result { + save_for_web_impl(s, p, &mut write_file, true) +} + +/// Save for Web through a platform writer (native files or browser downloads). +/// The writer receives every image, spacer and HTML file. A write error stops the export; +/// only a complete export remembers its settings and fires the export event. A custom writer +/// that targets the local filesystem must enforce its own path confinement. +pub fn save_for_web_with_writer(s: &mut Session, p: &Value, write: &mut dyn FnMut(&str, &[u8]) -> Result<()>) -> Result { + save_for_web_impl(s, p, write, false) +} + +/// Settings to seed the Save for Web dialog from on the next launch: `file_menu` is session +/// state, so a complete export also writes the preferences' remembered dialog settings (like +/// Fill, Liquify and the filter dialogs). The destination is per export, never remembered. +fn remember_web_settings(s: &mut Session, cmd: &str, settings: &Value) { + let mut m = settings.clone(); + if let Some(o) = m.as_object_mut() { + for k in ["path", "dir", "trustedSliceHtml"] { + o.remove(k); + } + } + s.prefs.edit(|p| { + p.dialogs.insert(cmd.to_string(), m); + }); +} + +fn save_for_web_impl(s: &mut Session, p: &Value, write: &mut dyn FnMut(&str, &[u8]) -> Result<()>, native_paths: bool) -> Result { + let cmd = "file.export.saveForWebLegacy"; + if let Some(authorize) = s.authorize { + authorize(cmd, p)?; + } + // Direct platform calls must export the moved selection as it appears on the canvas, + // just as Session::execute does before dispatching the native command. + crate::float_cmds::before_command(s, cmd)?; + let st = WebSettings::from_params(p, cmd)?; + let d = s.active().ok_or(EngineError::NoDocument)?; + let doc = d.doc.clone(); + let (wdoc, sx, sy) = web_document(&doc, p, &st)?; + let buf = photocraft_compose::flatten(&wdoc); + let bw = wdoc.size.width as usize; + let icc = wdoc.icc_profile.as_deref().map(|v| v.as_slice()); + let xmp = web_xmp(&doc, st.metadata); + let exif = web_exif(&doc, st.metadata); + let dpi = wdoc.resolution_dpi; + let warnings = web_warnings(&st, exif, dpi); + let all = slices::resolve(&doc); + let pick = p.get("slices").and_then(Value::as_str).unwrap_or("all"); + let numbers: Option> = p.get("numbers").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_u64).collect()); + let chosen: Vec<&ResolvedSlice> = all + .iter() + .filter(|r| match (&numbers, pick) { + (Some(n), _) => n.contains(&(r.number as u64)), + (None, "user") => r.origin != photocraft_doc::SliceOrigin::Auto, + _ => true, + }) + .collect(); + let single = p.get("path").and_then(Value::as_str).filter(|v| !v.is_empty()); + let dir = p.get("dir").and_then(Value::as_str).filter(|v| !v.is_empty()); + let mut last_web = p.clone(); + // A trusted-markup decision applies to this export only, never to another document opened + // with the dialog's remembered settings. + if let Some(last) = last_web.as_object_mut() { + last.remove("trustedSliceHtml"); + } + // Estimate only (the dialog's annotations): the whole image, or each chosen slice. + if single.is_none() && dir.is_none() { + let o = optimize(&buf.px, bw, wdoc.bounds(), &st, icc, exif, xmp.as_deref(), dpi, false)?; + return Ok( + json!({"format": o.ext, "bytes": o.bytes.len(), "width": o.width, "height": o.height, "colors": o.colors, "colorTable": o.color_table.iter().map(|c| rgb_hex(*c)).collect::>(), "transparentIndex": o.transparent_index}), + ); + } + if let Some(path) = single.filter(|_| dir.is_none() && (all.len() == 1 || p.get("slices").is_none())) { + let o = optimize(&buf.px, bw, wdoc.bounds(), &st, icc, exif, xmp.as_deref(), dpi, false)?; + write(path, &o.bytes)?; + remember_web_settings(s, cmd, &last_web); + s.file_menu.last_web = Some(last_web); + crate::automate_cmds::fire_event(s, "export"); + return Ok(json!({"files": [path], "bytes": o.bytes.len(), "width": o.width, "height": o.height, "colors": o.colors, "warnings": warnings})); + } + let dir = + dir.map(str::to_string).or_else(|| single.and_then(|f| std::path::Path::new(f).parent().map(|d| d.to_string_lossy().into_owned()))).unwrap_or_default(); + let html = p.get("html").and_then(Value::as_bool).unwrap_or(false); + let images = web_images_folder(p.get("imagesFolder").and_then(Value::as_str).unwrap_or("images"), cmd)?; + let trusted_slice_html = p.get("trustedSliceHtml").and_then(Value::as_bool).unwrap_or(false); + let base = portable_generated_stem(single.map(stem).unwrap_or_else(|| slices::base_name(&doc))); + let mut files = Vec::new(); + let mut cells: Vec<(Rect, String, String)> = Vec::new(); + let mut total = 0usize; + // Output names are unique (case-insensitively, for macOS and Windows file systems): two + // slices named alike, or names that sanitize alike, must not overwrite each other. The HTML + // page's spacer image is reserved. + let mut used: std::collections::HashSet = std::collections::HashSet::new(); + if html { + used.insert("spacer.gif".into()); + } + let mut unique = |stem: &str, ext: &str| { + let mut name = format!("{stem}.{ext}"); + let mut k = 2u32; + while !used.insert(name.to_lowercase()) { + name = format!("{stem}_{k}.{ext}"); + k = k.saturating_add(1); + } + name + }; + // Slices never overlap here: one covered by later slices comes as its visible pieces (see + // `slices::resolve`), each its own image and cell, as Photoshop's subslices. A no-image cell's + // text goes into its first piece only. + let mut texted = std::collections::HashSet::new(); + for r in &chosen { + let piece = scale_rect(r.rect, sx, sy).intersect(&wdoc.bounds()); + if piece.is_empty() { + continue; + } + let stored = r.id.and_then(|id| doc.slices.get(id)); + if r.kind == SliceKind::NoImage { + let text = stored + .filter(|s| texted.insert(s.id)) + .map(|s| if trusted_slice_html && s.cell_text_is_html { s.cell_text.clone() } else { html_escape(&s.cell_text) }) + .unwrap_or_default(); + let bg = stored.and_then(|s| s.background).map(|c| format!(" bgcolor=\"#{:02X}{:02X}{:02X}\"", c[1], c[2], c[3])).unwrap_or_default(); + cells.push((piece, bg, text)); + continue; + } + let o = optimize(&buf.px, bw, piece, &st, icc, exif, xmp.as_deref(), dpi, false)?; + let name = unique(&slice_file(&r.name), o.ext); + let rel = if images.is_empty() { name.clone() } else { format!("{images}/{name}") }; + let out = join(&dir, &rel); + write(&web_derived_path(&dir, &rel, native_paths)?, &o.bytes)?; + total += o.bytes.len(); + files.push(out); + let alt = stored.map_or(String::new(), |s| html_escape(&s.alt)); + let img = format!("\n\t\t\t\"{alt}\"", html_escape(&rel), piece.width(), piece.height()); + let body = match stored.filter(|s| safe_slice_url(&s.url)) { + Some(s) => { + let target = if s.target.is_empty() { String::new() } else { format!(" target=\"{}\"", html_escape(&s.target)) }; + format!("\n\t\t\t{img}", html_escape(&s.url)) + } + None => img, + }; + cells.push((piece, String::new(), body)); + } + let mut html_path = None; + if html { + let grid = cells.len() > 1; + let spacer = grid.then(|| if images.is_empty() { "spacer.gif".to_string() } else { format!("{images}/spacer.gif") }); + if let Some(sp) = &spacer { + let gif = photocraft_codecs::web::encode_gif_indexed(1, 1, &[0], &[[0, 0, 0]], Some(0), false).map_err(other)?; + write(&web_derived_path(&dir, sp, native_paths)?, &gif)?; + } + let page = html_table(&base, wdoc.size.width, wdoc.size.height, &cells, spacer.as_deref()); + let hp = join(&dir, &format!("{base}.html")); + write(&web_derived_path(&dir, &format!("{base}.html"), native_paths)?, page.as_bytes())?; + html_path = Some(hp); + } + remember_web_settings(s, cmd, &last_web); + s.file_menu.last_web = Some(last_web); + crate::automate_cmds::fire_event(s, "export"); + Ok( + json!({"files": files, "html": html_path, "bytes": total, "slices": chosen.len(), "width": wdoc.size.width, "height": wdoc.size.height, "warnings": warnings}), + ) +} diff --git a/crates/engine/src/cmd/web_cmds/settings.rs b/crates/engine/src/cmd/web_cmds/settings.rs new file mode 100644 index 0000000000..19314673c0 --- /dev/null +++ b/crates/engine/src/cmd/web_cmds/settings.rs @@ -0,0 +1,303 @@ +use super::optimizer::to8; +use super::*; + +// ---------- settings ---------- + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum WebFormat { + Gif, + Png8, + Png24, + Jpeg, + Wbmp, +} + +impl WebFormat { + pub fn from_id(s: &str) -> Option { + Some(match s.to_ascii_lowercase().as_str() { + "gif" => WebFormat::Gif, + "png8" | "png-8" => WebFormat::Png8, + "png24" | "png-24" | "png" | "png32" => WebFormat::Png24, + "jpeg" | "jpg" => WebFormat::Jpeg, + "wbmp" => WebFormat::Wbmp, + _ => return None, + }) + } + pub fn ext(self) -> &'static str { + match self { + WebFormat::Gif => "gif", + WebFormat::Png8 | WebFormat::Png24 => "png", + WebFormat::Jpeg => "jpg", + WebFormat::Wbmp => "wbmp", + } + } + pub fn indexed(self) -> bool { + matches!(self, WebFormat::Gif | WebFormat::Png8) + } +} + +/// Which metadata Save for Web embeds (JPEG only, like Photoshop's legacy exporter). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum WebMetadata { + None, + Copyright, + CopyrightAndContact, + /// All the XMP, none of the photo's EXIF (camera, date taken, GPS). + AllExceptCameraInfo, + /// All the XMP and the photo's EXIF. + All, +} + +/// One optimisation preset (the right-hand side of the Save for Web dialog). +#[derive(Clone, Debug, PartialEq)] +pub struct WebSettings { + pub format: WebFormat, + pub palette: PaletteKind, + pub colors: usize, + /// Fixed opaque source palette in index order. + pub color_table: Option>, + /// Replacements applied after quantization, preserving pixel indices. + pub color_table_edits: std::collections::BTreeMap, + pub dither: Dither, + /// 0..=1. + pub dither_amount: f32, + pub transparency: bool, + /// Edge / background colour (0..=1 RGB); None = no matte (hard alpha threshold). + pub matte: Option<[f32; 3]>, + pub interlaced: bool, + /// Web Snap: palette entries within this distance (0..=1 of the channel range) snap to the + /// web-safe cube. + pub web_snap: f32, + /// JPEG quality 0..=100. + pub quality: u8, + pub progressive: bool, + pub optimized: bool, + pub embed_icc: bool, + pub metadata: WebMetadata, + pub convert_to_srgb: bool, +} + +impl Default for WebSettings { + fn default() -> Self { + WebSettings { + format: WebFormat::Png24, + palette: PaletteKind::Selective, + colors: 256, + color_table: None, + color_table_edits: Default::default(), + dither: Dither::Diffusion, + dither_amount: 0.88, + transparency: true, + matte: Some([1.0, 1.0, 1.0]), + interlaced: false, + web_snap: 0.0, + quality: 60, + progressive: false, + optimized: true, + embed_icc: false, + metadata: WebMetadata::Copyright, + convert_to_srgb: true, + } + } +} + +fn hex3(s: &str) -> Option<[f32; 3]> { + let s = s.trim_start_matches('#'); + let b = |i: usize| u8::from_str_radix(s.get(i..i + 2)?, 16).ok().map(|v| f32::from(v) / 255.0); + (s.len() == 6).then_some(())?; + Some([b(0)?, b(2)?, b(4)?]) +} + +impl WebSettings { + /// Settings from command parameters (missing keys keep the defaults; Photoshop's preset + /// names such as "GIF 128 Dithered" or "JPEG High" are accepted as `"preset"`). + /// + /// Without a preset there is no matte, as in Photoshop's scripted Save for Web + /// (`ExportOptionsSaveForWeb` left at its defaults): a GIF or PNG-8 keeps the colour of its + /// partly transparent pixels instead of lightening them towards white (#4115). Formats + /// without transparency still go over white. + pub fn from_params(p: &Value, cmd: &str) -> Result { + let mut st = WebSettings { matte: None, ..WebSettings::default() }; + if let Some(preset) = p.get("preset").and_then(Value::as_str) { + st = preset_settings(preset).ok_or_else(|| bad(cmd, format!("unknown preset `{preset}`")))?; + } + let s = |k: &str| p.get(k).and_then(Value::as_str); + if let Some(f) = s("format") { + st.format = WebFormat::from_id(f).ok_or_else(|| bad(cmd, format!("unknown format `{f}` (gif|png8|png24|jpeg|wbmp)")))?; + } + if let Some(k) = s("palette") { + st.palette = match k { + "restrictive" | "web" => PaletteKind::Web, + k => PaletteKind::from_id(k).ok_or_else(|| { + bad(cmd, format!("unknown palette `{k}` (perceptual|selective|adaptive|restrictive|exact|systemMac|systemWindows|uniform)")) + })?, + }; + } + if let Some(n) = crate::commands::int(p, "colors").filter(|v| *v > 0).map(|v| v as u64) { + st.colors = (n as usize).clamp(2, 256); + } + if let Some(d) = s("dither") { + st.dither = match d { + "none" | "noDither" => Dither::None, + "diffusion" => Dither::Diffusion, + "pattern" => Dither::Pattern, + "noise" => Dither::Noise, + d => return Err(bad(cmd, format!("unknown dither `{d}` (none|diffusion|pattern|noise)"))), + }; + } + if let Some(a) = p.get("ditherAmount").and_then(Value::as_f64) { + st.dither_amount = (a as f32 / 100.0).clamp(0.0, 1.0); + } + if let Some(b) = p.get("transparency").and_then(Value::as_bool) { + st.transparency = b; + } + match s("matte") { + Some("none") => st.matte = None, + Some(c) => st.matte = Some(hex3(c).ok_or_else(|| bad(cmd, "matte is \"none\" or \"#rrggbb\""))?), + None => {} + } + for (k, slot) in [ + ("interlaced", &mut st.interlaced), + ("progressive", &mut st.progressive), + ("optimized", &mut st.optimized), + ("embedIcc", &mut st.embed_icc), + ("convertToSrgb", &mut st.convert_to_srgb), + ] { + if let Some(b) = p.get(k).and_then(Value::as_bool) { + *slot = b; + } + } + if let Some(w) = p.get("webSnap").and_then(Value::as_f64) { + st.web_snap = (w as f32 / 100.0).clamp(0.0, 1.0); + } + if let Some(q) = p.get("quality").and_then(Value::as_f64) { + st.quality = q.clamp(0.0, 100.0).round() as u8; + } + if let Some(m) = s("metadata") { + st.metadata = match m { + "none" => WebMetadata::None, + "copyright" => WebMetadata::Copyright, + "copyrightAndContact" | "contact" => WebMetadata::CopyrightAndContact, + "allExceptCameraInfo" => WebMetadata::AllExceptCameraInfo, + "all" => WebMetadata::All, + m => return Err(bad(cmd, format!("unknown metadata `{m}` (none|copyright|copyrightAndContact|allExceptCameraInfo|all)"))), + }; + } + if let Some(table) = p.get("colorTable") { + let table = table.as_array().filter(|a| (1..=256).contains(&a.len())).ok_or_else(|| bad(cmd, "colorTable must contain 1–256 #rrggbb colours"))?; + st.color_table = Some( + table + .iter() + .map(|v| v.as_str().and_then(hex3).map(|c| c.map(to8)).ok_or_else(|| bad(cmd, "colorTable entries must be #rrggbb colours"))) + .collect::>>()?, + ); + } + if let Some(edits) = p.get("colorTableEdits") { + let edits = edits + .as_object() + .filter(|m| m.len() <= 256) + .ok_or_else(|| bad(cmd, "colorTableEdits must be an object of palette indices to #rrggbb colours"))?; + let table = st.color_table.as_ref().ok_or_else(|| bad(cmd, "colorTableEdits requires colorTable"))?; + for (index, value) in edits { + let index = index.parse::().ok().filter(|i| *i < table.len()).ok_or_else(|| bad(cmd, "colorTableEdits index is outside colorTable"))?; + let color = value.as_str().and_then(hex3).map(|c| c.map(to8)).ok_or_else(|| bad(cmd, "colorTableEdits values must be #rrggbb colours"))?; + st.color_table_edits.insert(index, color); + } + } + Ok(st) + } +} + +impl WebSettings { + /// The settings as command parameters (the inverse of [`WebSettings::from_params`]). + pub fn to_params(&self) -> Value { + let format = match self.format { + WebFormat::Gif => "gif", + WebFormat::Png8 => "png8", + WebFormat::Png24 => "png24", + WebFormat::Jpeg => "jpeg", + WebFormat::Wbmp => "wbmp", + }; + let palette = match self.palette { + PaletteKind::Exact => "exact", + PaletteKind::SystemMac => "systemMac", + PaletteKind::SystemWindows => "systemWindows", + PaletteKind::Web => "restrictive", + PaletteKind::Uniform => "uniform", + PaletteKind::Perceptual => "perceptual", + PaletteKind::Selective => "selective", + PaletteKind::Adaptive => "adaptive", + }; + let dither = match self.dither { + Dither::None => "none", + Dither::Diffusion => "diffusion", + Dither::Pattern => "pattern", + Dither::Noise => "noise", + }; + let metadata = match self.metadata { + WebMetadata::None => "none", + WebMetadata::Copyright => "copyright", + WebMetadata::CopyrightAndContact => "copyrightAndContact", + WebMetadata::AllExceptCameraInfo => "allExceptCameraInfo", + WebMetadata::All => "all", + }; + let matte = self.matte.map_or("none".to_string(), |c| format!("#{:02x}{:02x}{:02x}", to8(c[0]), to8(c[1]), to8(c[2]))); + let mut p = json!({"format": format, "palette": palette, "colors": self.colors, "dither": dither, "ditherAmount": (self.dither_amount * 100.0).round(), "transparency": self.transparency, "matte": matte, "interlaced": self.interlaced, "webSnap": (self.web_snap * 100.0).round(), "quality": self.quality, "progressive": self.progressive, "optimized": self.optimized, "embedIcc": self.embed_icc, "metadata": metadata, "convertToSrgb": self.convert_to_srgb}); + if let Some(table) = &self.color_table { + p["colorTable"] = json!(table.iter().map(|c| rgb_hex(*c)).collect::>()); + } + if !self.color_table_edits.is_empty() { + p["colorTableEdits"] = + json!(self.color_table_edits.iter().map(|(i, c)| (i.to_string(), rgb_hex(*c))).collect::>()); + } + p + } +} + +/// A palette colour in command/control-channel notation. +pub fn rgb_hex(c: [u8; 3]) -> String { + format!("#{:02x}{:02x}{:02x}", c[0], c[1], c[2]) +} + +/// Save for Web's named presets. +pub const PRESETS: [&str; 12] = [ + "GIF 128 Dithered", + "GIF 128 No Dither", + "GIF 32 Dithered", + "GIF 32 No Dither", + "GIF 64 Dithered", + "GIF 64 No Dither", + "GIF Restrictive", + "JPEG High", + "JPEG Low", + "JPEG Medium", + "PNG-24", + "PNG-8 128 Dithered", +]; + +pub fn preset_settings(name: &str) -> Option { + let d = WebSettings::default(); + let gif = |colors: usize, dither: bool| WebSettings { + format: WebFormat::Gif, + colors, + dither: if dither { Dither::Diffusion } else { Dither::None }, + ..WebSettings::default() + }; + Some(match name { + "GIF 128 Dithered" => gif(128, true), + "GIF 128 No Dither" => gif(128, false), + "GIF 32 Dithered" => gif(32, true), + "GIF 32 No Dither" => gif(32, false), + "GIF 64 Dithered" => gif(64, true), + "GIF 64 No Dither" => gif(64, false), + "GIF Restrictive" => WebSettings { palette: PaletteKind::Web, ..gif(256, true) }, + "JPEG High" => WebSettings { format: WebFormat::Jpeg, quality: 60, ..d }, + "JPEG Low" => WebSettings { format: WebFormat::Jpeg, quality: 10, ..d }, + "JPEG Medium" => WebSettings { format: WebFormat::Jpeg, quality: 30, ..d }, + "JPEG Maximum" => WebSettings { format: WebFormat::Jpeg, quality: 100, ..d }, + "JPEG Very High" => WebSettings { format: WebFormat::Jpeg, quality: 80, ..d }, + "PNG-24" => WebSettings { format: WebFormat::Png24, ..d }, + "PNG-8 128 Dithered" => WebSettings { format: WebFormat::Png8, colors: 128, ..d }, + _ => return None, + }) +} diff --git a/crates/engine/src/web_cmds/tests.rs b/crates/engine/src/cmd/web_cmds/tests.rs similarity index 100% rename from crates/engine/src/web_cmds/tests.rs rename to crates/engine/src/cmd/web_cmds/tests.rs diff --git a/crates/engine/src/wia_cmds.rs b/crates/engine/src/cmd/wia_cmds.rs similarity index 100% rename from crates/engine/src/wia_cmds.rs rename to crates/engine/src/cmd/wia_cmds.rs diff --git a/crates/engine/src/display_color.rs b/crates/engine/src/display_color.rs index 49b36f9031..55a9c83ed9 100644 --- a/crates/engine/src/display_color.rs +++ b/crates/engine/src/display_color.rs @@ -464,5 +464,4 @@ impl ColorState { } #[cfg(test)] -#[path = "display_color_tests.rs"] mod tests; diff --git a/crates/engine/src/display_color_tests.rs b/crates/engine/src/display_color/tests.rs similarity index 100% rename from crates/engine/src/display_color_tests.rs rename to crates/engine/src/display_color/tests.rs diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs new file mode 100644 index 0000000000..ef7c9445e4 --- /dev/null +++ b/crates/engine/src/doc_state.rs @@ -0,0 +1,276 @@ +use super::*; + +/// Per-document editing state. +#[derive(Clone, Debug)] +pub struct DocState { + pub doc: Arc, + pub history: History, + /// The primary ("key") layer: what single-layer commands act on. Always a member of + /// `selected_layers` when set. + pub active_layer: Option, + /// Every selected layer in the Layers panel (⌘/⇧-click), in selection order. Like + /// `active_layer`, selecting is not a history step, but undo and redo restore the layers each + /// state targeted when the next step was taken; see [`DocState::selected_layers`]. + pub selected_layers: Vec, + /// Anchor of ⇧-click range selection (the last plainly or ⌘-clicked layer). + pub layer_anchor: Option, + pub path: Option, + /// An Affinity document (or its preview) must not acquire the native source as its Save path. + pub source_read_only: bool, + /// Increments on every change; UIs re-render when it moves. + pub revision: u64, + pub saved_revision: u64, + /// Native save cache shared with this document's workers, released with the editing state. + pub pcraft_cache: photocraft_io::PcraftExportCache, + /// How much of `revision` came from view-only changes (channel eyes, targeting): pixel caches can ignore those. + pub view_revision: u64, + /// Area changed by the latest revision (None = assume everything changed). + pub last_damage: Option, + /// Coalescing key of the latest history step (see [`Session::execute`]'s `coalesce` param). + pub coalesce: Option, + /// Channels panel: targeted channel and eye toggles (view state, not history). + pub channel_view: channel_cmds::ChannelView, + /// Select › Isolate Layers: the Layers panel lists only these layers (empty = off; view state). + pub isolated_layers: Vec, + /// Painting symmetry preset or sampled path (tool state, not document pixels). + pub symmetry: Option, + /// Layers panel: layers whose effects list is collapsed under their row (the fx triangle; + /// view state, not history). Effects lists start open. + pub fx_collapsed: Vec, + /// ⌥-click on a layer's eye (`layer.showOnly`): the layer shown alone and every layer's + /// visibility before, so the next ⌥-click restores it (view state, not history). + pub show_only: Option<(LayerId, Vec<(LayerId, bool)>)>, + /// A floating selection (`select.float`): the cut piece and where it floats, until dropped + /// (view state: the document is unchanged until `select.drop`). + pub floating: Option, + /// Color Sampler points (`view.colorSamplers.*`, #1046): numbered sample positions in document + /// pixel coordinates. Per-document view state: discarded when the document closes, never saved + /// to `.pcraft` or PSD, and not a history step. + pub color_samplers: Vec<[f64; 2]>, + /// History panel snapshots, oldest first (`history.newSnapshot`, #2966): the first (id 0) is + /// the document as opened. Kept for the session only, as in Photoshop: not history states, + /// and not saved with the document. + pub snapshots: Vec, + /// The id the next snapshot gets; ids are never reused, so deleting one keeps the others. + pub(crate) next_snapshot: u64, + /// The snapshot set as the History Brush's source (`history.setSource {snapshot}`); `None`: + /// the source is a state, kept by the history ([`photocraft_ops::History::brush_source`]). + pub(crate) source_snapshot: Option, +} + +impl DocState { + /// Trim the history to its budget, counting the tiles only History panel snapshots hold + /// against it too (#4530). Returns how many states were dropped. + pub fn trim_history(&mut self) -> usize { + let snaps: Vec<&Document> = self.snapshots.iter().map(|s| &*s.doc).collect(); + self.history.trim_with(&self.doc, &snaps) + } + + /// Pixel bytes of the document, the tiles only its history holds and the tiles only its + /// History panel snapshots hold. + pub fn memory_bytes(&self) -> usize { + let snaps: Vec<&Document> = self.snapshots.iter().map(|s| &*s.doc).collect(); + self.history.pixel_bytes(&self.doc).saturating_add(self.history.extra_bytes(&self.doc, &snaps)) + } + + pub fn new(doc: Document, path: Option) -> Self { + let active_layer = doc.top_layer(); + let mut history = History::default(); + let target = LayerTarget { active: active_layer, selected: active_layer.into_iter().collect() }; + history.set_current_layers(target.clone()); + let doc = Arc::new(doc); + // Photoshop's first snapshot: the document as opened, named after it, so the History + // panel's top row can always bring it back (#2966). + let first = history_cmds::Snapshot { id: 0, name: doc.name.clone(), doc: doc.clone(), layers: target }; + Self { + doc, + history, + active_layer, + selected_layers: active_layer.into_iter().collect(), + layer_anchor: active_layer, + path, + source_read_only: false, + revision: 1, + saved_revision: 1, + pcraft_cache: Default::default(), + view_revision: 0, + last_damage: None, + coalesce: None, + channel_view: Default::default(), + isolated_layers: Vec::new(), + symmetry: None, + fx_collapsed: Vec::new(), + show_only: None, + floating: None, + color_samplers: Vec::new(), + snapshots: vec![first], + next_snapshot: 1, + source_snapshot: None, + } + } + /// The selected layers in bottom-to-top document order, always including the active layer. + /// Robust against stale state: ids no longer in the document are skipped, and if the active + /// layer was changed without updating the set, the selection is just the active layer. + pub fn selected_layers(&self) -> Vec { + let Some(active) = self.active_layer else { return Vec::new() }; + let set: &[LayerId] = if self.selected_layers.contains(&active) { &self.selected_layers } else { std::slice::from_ref(&active) }; + self.doc.walk().into_iter().map(|(_, _, l)| l.id).filter(|id| set.contains(id)).collect() + } + pub fn is_layer_selected(&self, id: LayerId) -> bool { + self.active_layer == Some(id) || (self.active_layer.is_some_and(|a| self.selected_layers.contains(&a)) && self.selected_layers.contains(&id)) + } + pub fn is_dirty(&self) -> bool { + self.revision != self.saved_revision + } + /// Whether the step from `before` to the current document leaves a clean document clean: + /// it changed nothing but the selection (#6865). Making, changing or dropping a selection + /// (marquee, lasso, Magic Wand, Quick / Object Selection, Select › …) is a history step but + /// not an edit, so it neither marks the file modified nor makes closing ask to save. + pub(crate) fn keeps_clean(&self, before: &Document) -> bool { + self.saved_revision == self.revision && layer_multi_cmds::selection_only_change(before, &self.doc) + } + /// Move to the next revision; `keep_clean` (from [`Self::keeps_clean`]) moves the saved + /// revision with it. + pub(crate) fn bump_revision(&mut self, keep_clean: bool) { + self.revision += 1; + if keep_clean { + self.saved_revision = self.revision; + } + } + /// The targeted layers, as history stores them with each state. + pub(crate) fn layer_target(&self) -> LayerTarget { + LayerTarget { active: self.active_layer, selected: self.selected_layers.clone() } + } +} + +/// App-wide tool state that commands read (foreground colour, brush…). +#[derive(Clone, Debug)] +pub struct ToolState { + pub foreground: [f32; 4], + pub background: [f32; 4], + pub brush: photocraft_paint::BrushSettings, + /// Brush presets (built-ins plus user presets; see `brush.presets.*`). + pub presets: Vec, + /// Bumped whenever `presets` changes ([`Session::brush_presets_changed`]); the preset store + /// syncs when it moves. + pub presets_rev: u64, + /// Mixer Brush paint carried between strokes. + pub mixer: photocraft_paint::mixer::MixerState, + /// The coalescing key of the running `tools.setBrush` gesture and the brush before it, so the + /// gesture journals as one call ([`brush_cmds::coalesce_journal`]). + pub brush_gesture: Option<(String, photocraft_paint::BrushSettings)>, + /// Name of the preset the current brush was last picked from. Kept across later edits (the + /// preset stays "the current brush" so `brush.presets.update` can overwrite it); cleared when + /// the brush is reset or the preset is gone. + pub current_preset: Option, + /// Bumped whenever `brush` or `current_preset` changes ([`ToolState::brush_changed`]). The + /// last-brush persistence watches it instead of comparing the brush itself, so an unchanged + /// brush costs a counter compare per frame, not a clone and serialise. + pub brush_rev: u64, + /// The revision whose value is in `Preferences::last_brush` (a restored one counts as saved): + /// [`brush_rev`](Self::brush_rev) == `brush_saved_rev` means there is nothing new to write. + pub brush_saved_rev: u64, + /// A layer mask is the edit target ([`ToolState::target_mask`]). + pub mask_targeted: bool, + /// The foreground/background pair of the edit target that isn't current: the layer pixels' + /// colours while a mask is targeted, the mask's while the pixels are (#2166). + pub other_colors: [[f32; 4]; 2], + /// Colours picked as CMYK, newest last: the sRGB colour that stands for them and the ink + /// values chosen. The tool colours are stored as sRGB, and an sRGB round trip does not give + /// back what was typed (100/0/0/0 cyan is outside sRGB), so a CMYK document is filled with + /// the inks the person picked (#4196). Matched by colour, so it follows a swap, a reset or a + /// mask pair without bookkeeping. + pub cmyk_picks: Vec<([f32; 3], [f32; 4])>, +} + +impl ToolState { + /// How many CMYK picks are remembered. + const CMYK_PICKS: usize = 8; + + /// Remember that sRGB colour `rgb` was picked as the inks `cmyk` (each 0..1). + pub fn remember_cmyk(&mut self, rgb: [f32; 3], cmyk: [f32; 4]) { + self.cmyk_picks.retain(|(c, _)| *c != rgb); + self.cmyk_picks.push((rgb, cmyk)); + let extra = self.cmyk_picks.len().saturating_sub(Self::CMYK_PICKS); + self.cmyk_picks.drain(..extra); + } + + /// The inks `rgb` was picked as, if it was picked as CMYK. + pub fn picked_cmyk(&self, rgb: [f32; 3]) -> Option<[f32; 4]> { + self.cmyk_picks.iter().rev().find(|(c, _)| *c == rgb).map(|(_, k)| *k) + } + + /// Photoshop's colour pair for a layer mask that has none yet: white foreground, black + /// background (reveal-paint first). + pub const MASK_COLORS: [[f32; 4]; 2] = [[1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 1.0]]; + + /// Note that `brush` or `current_preset` changed. Every setter of either (commands and the + /// shell's tool-switch paths) calls this; the last-brush persistence only serialises when the + /// revision has moved since the stored value ([`Self::brush_saved_rev`]). + pub fn brush_changed(&mut self) { + self.brush_rev = self.brush_rev.wrapping_add(1); + } + + /// Switch the edit target between layer pixels and a layer mask. Like Photoshop, the mask and + /// the pixels keep separate app-wide foreground/background pairs: changing the target puts + /// the current pair aside and brings back the other one, so colours picked while a mask is + /// targeted are remembered for masks (#2166). The mask pair starts at [`Self::MASK_COLORS`]. + /// Returns whether the target changed. + pub fn target_mask(&mut self, mask: bool) -> bool { + if self.mask_targeted == mask { + return false; + } + self.mask_targeted = mask; + let [fg, bg] = std::mem::replace(&mut self.other_colors, [self.foreground, self.background]); + self.foreground = fg; + self.background = bg; + true + } +} + +impl Default for ToolState { + fn default() -> Self { + Self { + foreground: [0.0, 0.0, 0.0, 1.0], + background: [1.0, 1.0, 1.0, 1.0], + // Photoshop's Brush tool starts at 10 % Smoothing. + brush: photocraft_paint::BrushSettings { + smoothing: photocraft_paint::brush::Smoothing { amount: 0.1, ..Default::default() }, + ..Default::default() + }, + presets: photocraft_paint::presets::builtin(), + presets_rev: 0, + mixer: Default::default(), + brush_gesture: None, + current_preset: None, + brush_rev: 0, + brush_saved_rev: 0, + mask_targeted: false, + other_colors: Self::MASK_COLORS, + cmyk_picks: Vec::new(), + } + } +} + +/// Layer › Layer Style › Copy Layer Style: the effects and the Blending Options, as Photoshop +/// copies them (Paste Layer Style puts them all on each target). +#[derive(Clone, Debug)] +pub struct CopiedStyle { + pub effects: photocraft_doc::Effects, + pub blend: photocraft_color::BlendMode, + pub fill: f32, + pub advanced: photocraft_doc::AdvancedBlending, + pub blend_if: photocraft_doc::BlendIf, + pub excluded_channels: u32, + /// The colour mode it was copied in: Blend If's channel ranges and the channel restrictions + /// only carry over to a document in the same mode. + pub mode: photocraft_color::ColorMode, +} + +/// The commands whose [`Session::precheck`] is complete: it accepts what `execute` does (Free +/// Transform applies its box before these, and only when they will run), but for the group +/// nesting limit ([`photocraft_doc::MAX_GROUP_DEPTH`]): grouping layers already that deep is +/// refused only as the edit is made. Layer via Copy and +/// Cut aren't: whether they have anything to copy (a selection over transparent pixels, a group +/// or fill layer) is known only when they run. +pub const PRECHECKED: &[&str] = &["layer.new.layer", "layer.new.group", "layer.new.groupFromLayers", "layer.new.layerFromBackground"]; diff --git a/crates/engine/src/edit_cmds.rs b/crates/engine/src/edit_cmds.rs deleted file mode 100644 index 4631cbae75..0000000000 --- a/crates/engine/src/edit_cmds.rs +++ /dev/null @@ -1,2578 +0,0 @@ -//! Everyday Photoshop commands: clipboard (Cut/Copy/Copy Merged/Paste/Paste in Place), Layer via -//! Copy/Cut, Merge Visible, Auto Tone/Contrast/Color, Toggle Last State and Transform Again. - -use photocraft_color::{ColorMode, PixelFormat}; -use photocraft_doc::adjust::LevelsChannel; -use photocraft_doc::{Adjustment, DocId, Document, Layer, LayerContent, LayerId}; -use photocraft_geom::Rect; -use photocraft_raster::Surface; -use serde_json::{Value, json}; - -use crate::commands::CommandSpec; -use crate::{EngineError, Result, Session}; - -/// The paste commands' `"target"` param (for `concat!` into their params docs). -macro_rules! paste_target { - () => { - r#""target":"pixels"|"mask"|"quickMask"|{"channel":i}=Channels panel target (not pixels: the luminosity pasted into that mask or channel)"# - }; -} -pub(crate) use paste_target; - -/// Pixels on the session clipboard, with where they came from (for Paste in Place). -#[derive(Clone, Debug)] -pub struct Clip { - pub surface: Surface, - pub bounds: Rect, - /// The copied layer itself, when Copy took a whole layer that Paste should recreate rather - /// than rasterize (see [`whole_layer`]): a scratch document in the source's colour holding it. - /// `surface` still holds its pixels, for Paste Into, masks, channels and other apps. - pub layers: Option>, - /// The source document's resolution (ppi): File › New from the clipboard takes it, as - /// Photoshop's Clipboard preset does. None for an image from another app. - pub resolution: Option, - /// The document the pixels were copied from: Paste keeps them in place only there, and - /// centres them in any other (#8945). None for an image from another app. - pub source: Option, -} - -/// Photoshop's layer-based copy (CC 2018 on): with no selection, Copy takes the active layer -/// whole when it is a smart object (#2428), a type or shape layer, or a group (its whole subtree) -/// (#2670), so Paste recreates it instead of its pixels. Fill and adjustment layers have no -/// pixels of their own, so they are taken whole too rather than refused (#2344). Pixel layers -/// still copy their pixels; several selected layers are [`multi_copy_ids`]. -fn takes_whole(d: &crate::DocState, id: LayerId) -> bool { - d.doc.selection.is_none() - && d.selected_layers().len() <= 1 - && crate::layer_copy_cmds::layered(d.doc.mode) - && d.doc.layer(id).is_some_and(|l| !matches!(l.content, LayerContent::Raster(_))) -} - -/// A scratch document in the source's colour, to hold copied layers. -fn scratch_doc(doc: &Document) -> Document { - let mut copies = Document::new("", doc.size, doc.mode, doc.depth); - copies.icc_profile = doc.icc_profile.clone(); - copies.resolution_dpi = doc.resolution_dpi; - copies.patterns = doc.patterns.clone(); - copies -} - -/// Scope linked records to the copied layer tree: a PSD block can also hold files belonging -/// to unselected or hidden layers, which must not follow this copy into a native save. -fn copy_linked_sources(source: &Document, copies: &mut Document) -> Result<()> { - fn collect<'a>(layers: &'a [Layer], depth: usize, paths: &mut std::collections::HashSet<&'a str>) -> Result<()> { - if depth > photocraft_doc::MAX_GROUP_DEPTH { - return Err(EngineError::Other("can't copy linked smart objects from layers nested too deeply".into())); - } - for layer in layers { - if let LayerContent::Smart(sm) = &layer.content - && let photocraft_doc::SmartSource::Linked { path } = &sm.source - { - paths.try_reserve(1).map_err(|_| EngineError::Other("not enough memory to copy smart-object source IDs".into()))?; - paths.insert(path); - } - if let Some(children) = layer.children().filter(|children| !children.is_empty()) { - collect(children, depth + 1, paths)?; - } - } - Ok(()) - } - let mut paths = std::collections::HashSet::new(); - collect(&copies.layers, 0, &mut paths)?; - if paths.is_empty() { - return Ok(()); - } - for (signature, key, data) in &source.metadata.psd_global_blocks { - if !matches!(key, b"lnk2" | b"lnk3" | b"lnkD" | b"lnkE") { - continue; - } - let selected = photocraft_io::linked::select_items(data, &|uuid, _| paths.contains(uuid)) - .map_err(|e| EngineError::Other(format!("Could not copy smart-object contents: {e}; the clipboard was not changed")))?; - let selected = selected.map(std::sync::Arc::new).unwrap_or_else(|| data.clone()); - if !selected.is_empty() { - copies.metadata.psd_global_blocks.try_reserve(1).map_err(|_| EngineError::Other("not enough memory to copy smart-object source records".into()))?; - copies.metadata.psd_global_blocks.push((*signature, *key, selected)); - } - } - Ok(()) -} - -/// The layer Copy takes whole ([`takes_whole`]): a scratch document in the source's colour -/// holding it. -fn whole_layer(d: &crate::DocState, id: LayerId) -> Option> { - let l = d.doc.layer(id).filter(|_| takes_whole(d, id))?; - let mut copies = scratch_doc(&d.doc); - copies.layers.push(l.clone()); - Some(Box::new(copies)) -} - -/// The layers Copy takes when several are selected and nothing is selected in the pixels -/// (Photoshop, #2478): the selected layers that no selected group already carries, bottom-to-top. -/// Empty otherwise, and for a single layer ([`takes_whole`] decides that case). -fn multi_copy_ids(d: &crate::DocState) -> Vec { - if d.doc.selection.is_some() || !crate::layer_copy_cmds::layered(d.doc.mode) { - return Vec::new(); - } - let selected = d.selected_layers(); - if selected.len() < 2 { - return Vec::new(); - } - crate::layer_multi_cmds::top_level(&d.doc, &selected) -} - -/// Every selected layer, whole ([`multi_copy_ids`]), in a scratch document: Paste recreates them -/// all, each with its mask, styles and content. The Background becomes an ordinary layer, as in -/// Photoshop's Duplicate Layer. -fn whole_layers(d: &crate::DocState, ids: &[LayerId]) -> Option> { - let mut copies = scratch_doc(&d.doc); - for id in ids { - let mut l = d.doc.layer(*id)?.clone(); - if d.doc.is_background(*id) { - l.name = "Layer 0".into(); - l.locks = Default::default(); - } - copies.layers.push(l); - } - Some(Box::new(copies)) -} - -fn has_doc(s: &Session) -> std::result::Result<(), String> { - s.active().map(|_| ()).ok_or_else(|| "no document open".into()) -} - -/// Paste and New from Clipboard need only a clipboard: with no document open, they make one. -fn has_clip_only(s: &Session) -> std::result::Result<(), String> { - s.clipboard.as_ref().map(|_| ()).ok_or_else(|| "the clipboard is empty".into()) -} - -fn active_layer(s: &Session) -> std::result::Result<&Layer, String> { - let d = s.active().ok_or("no document open")?; - d.active_layer.and_then(|id| d.doc.layer(id)).ok_or_else(|| "no active layer".into()) -} - -/// Cut and Layer via Cut edit the pixels, so they need a pixel layer. -fn has_pixels(s: &Session) -> std::result::Result<(), String> { - match active_layer(s)?.content { - LayerContent::Raster(_) => Ok(()), - LayerContent::Smart(_) => Err("the smart object is not directly editable".into()), - _ => Err("the active layer has no pixels".into()), - } -} - -/// Copy only reads: any layer that shows pixels will do, so a smart object, type or shape layer -/// copies what it shows (Photoshop). -fn has_layer_pixels(s: &Session) -> std::result::Result<(), String> { - active_layer(s)?.surface().map(|_| ()).ok_or_else(|| "the active layer has no pixels".into()) -} - -/// Copy: a targeted alpha channel (#2307), a layer with pixels, or one taken whole (a group with -/// no selection, #2670). -fn can_copy(s: &Session) -> std::result::Result<(), String> { - if crate::channel_clip::copies_alpha_channel(s) || s.active().is_some_and(|d| !multi_copy_ids(d).is_empty()) { - return Ok(()); - } - has_layer_pixels(s).or_else(|e| s.active().and_then(|d| d.active_layer.filter(|id| takes_whole(d, *id))).map(|_| ()).ok_or(e)) -} - -fn has_clip(s: &Session) -> std::result::Result<(), String> { - has_doc(s)?; - s.clipboard.as_ref().map(|_| ()).ok_or_else(|| "the clipboard is empty".into()) -} - -fn active_id(s: &Session) -> Result { - s.active().and_then(|d| d.active_layer).ok_or(EngineError::Other("no active layer".into())) -} - -/// The pixels of `src` inside the selection (or all of them), as a straight-alpha surface. -/// -/// Built tile by tile (#4516). A source tile that the copy takes whole (inside the canvas, fully -/// selected or no selection, already in the clip's format) is shared copy-on-write, so a plain -/// Copy or Select All, Copy costs a pointer per tile; only the other tiles are read and written, -/// one at a time, instead of the whole area as one `f32` buffer. -fn lift(src: &Surface, sel: Option<&Surface>, canvas: Rect) -> Result { - let fmt = src.format(); - let with_alpha = PixelFormat::new(fmt.mode, fmt.sample, true); - let area = match sel { - Some(m) => m.content_bounds().intersect(&canvas), - None => src.content_bounds().intersect(&canvas), - }; - let mut out = Surface::new(with_alpha); - if area.is_empty() { - return Ok(Clip { surface: out, bounds: Rect::EMPTY, layers: None, resolution: None, source: None }); - } - // Only the selected area is read: converting the whole layer (a 24 MP Background gaining - // alpha) cost about a second per Layer via Copy (#668). - let mut shared = Vec::new(); - for tc in area.tiles() { - let tr = tc.rect().intersect(&area); - if fmt.alpha - && tr == tc.rect() - && let Some(tile) = src.tile(tc) - && sel.is_none_or(|m| crate::fill_cmds::Mask::of(m, tc).full(tr)) - { - // Reading and writing it back would give the same bytes. - shared.push((tc, tile.clone())); - continue; - } - let px = lift_region(src, sel, tr, with_alpha.channels())?; - out.try_write_region(tr, &px).map_err(|e| EngineError::Other(format!("not enough memory while copying pixels ({e}); the document was not changed")))?; - } - out.put_tiles(shared); - out.prune(); - let bounds = out.content_bounds(); - Ok(Clip { surface: out, bounds, layers: None, resolution: None, source: None }) -} - -/// [`lift`] over one rectangle: `src`'s pixels with alpha (`n` channels), the selection -/// multiplied into it. -fn lift_region(src: &Surface, sel: Option<&Surface>, r: Rect, n: usize) -> Result> { - let fmt = src.format(); - let mut px = if fmt.alpha { - crate::allocation::read_region(src, r, "copying pixels")? - } else { - let opaque = crate::allocation::read_region(src, r, "copying pixels")?; - let k = fmt.channels(); - let len = opaque - .len() - .checked_div(k.max(1)) - .and_then(|pixels| pixels.checked_mul(n)) - .ok_or_else(|| EngineError::Other("not enough memory for copying pixels (requested size overflowed); the document was not changed".into()))?; - let mut v = crate::allocation::filled(len, 0.0, "copying pixels")?; - let mut at = 0; - for p in opaque.chunks_exact(k.max(1)) { - let Some(dst) = v.get_mut(at..at + k.max(1)) else { break }; - dst.copy_from_slice(p); - at += k.max(1); - if let Some(alpha) = v.get_mut(at) { - *alpha = 1.0; - } - at += 1; - } - v - }; - if let Some(m) = sel { - let mask = crate::allocation::read_region(m, r, "applying the selection to copied pixels")?; - let mk = m.format().channels().max(1); - for (p, a) in px.chunks_exact_mut(n.max(1)).zip(mask.chunks_exact(mk)) { - if let Some(alpha) = p.last_mut() { - *alpha *= a[0]; - } - } - } - Ok(px) -} - -/// Merged composite of the visible document as a surface in the document's format. -fn merged_surface(doc: &Document) -> Surface { - let fmt = doc.pixel_format(); - photocraft_compose::flatten_to_surface(doc, PixelFormat::new(fmt.mode, fmt.sample, true), None) -} - -fn copy(s: &mut Session, merged: bool) -> Result { - let d = s.active().ok_or(EngineError::NoDocument)?; - let canvas = d.doc.bounds(); - let clip = if merged { - lift(&merged_surface(&d.doc), d.doc.selection.as_ref(), canvas)? - } else { - let id = d.active_layer.ok_or(EngineError::Other("no active layer".into()))?; - let several = multi_copy_ids(d); - let mut layers = if several.is_empty() { whole_layer(d, id) } else { whole_layers(d, &several) }; - if let Some(copies) = &mut layers { - copy_linked_sources(&d.doc, copies)?; - } - match (d.doc.layer(id).and_then(Layer::surface).filter(|_| several.is_empty()), &layers) { - (Some(surf), _) => Clip { layers, ..lift(surf, d.doc.selection.as_ref(), canvas)? }, - // A group or fill layer has no pixels of its own: the clipboard pixels are what it - // shows. Adjustment layers show nothing by themselves, so their clip spans the canvas - // they apply to: Paste places them as a full-canvas layer, and the UI still mirrors - // the clip to the OS clipboard (an empty clip would let a stale OS image replace it). - (None, Some(copies)) => { - let mut shown = (**copies).clone(); - for l in &mut shown.layers { - l.visible = true; - } - let clip = lift(&merged_surface(&shown), None, canvas)?; - let bounds = if clip.bounds.is_empty() { canvas } else { clip.bounds }; - Clip { layers, bounds, ..clip } - } - (None, None) => return Err(EngineError::Other("the active layer has no pixels".into())), - } - }; - if clip.bounds.is_empty() { - return Err(EngineError::Other("Could not copy: the selected area is empty".into())); - } - let b = clip.bounds; - let clip = Clip { resolution: Some(d.doc.resolution_dpi), source: Some(d.doc.id), ..clip }; - s.clipboard = Some(clip); - Ok(json!({"bounds": [b.x0, b.y0, b.width(), b.height()]})) -} - -/// Copy the targeted layer mask (`"target":"mask"`, #2928) or smart-filter mask -/// (`"target":"filterMask"`): the mask's values as a -/// grayscale clip, inside the selection or the whole canvas — an untouched mask copies at its -/// default value, so a plain Reveal All / Hide All mask transfers too. Paste then writes into -/// another layer's mask (targeted, #1035), in this or another document. -fn copy_mask(s: &mut Session, filter: bool) -> Result { - let d = s.active().ok_or(EngineError::NoDocument)?; - let canvas = d.doc.bounds(); - let id = d.active_layer.ok_or_else(|| EngineError::Other("no active layer".into()))?; - let layer = d.doc.layer(id).ok_or(EngineError::NoLayer(id))?; - let mask = crate::mask_view_cmds::viewed_mask(layer, filter) - .ok_or_else(|| EngineError::Other(if filter { "the active layer has no filter mask" } else { "the active layer has no layer mask" }.into()))?; - let sel = d.doc.selection.as_ref(); - let area = sel.map_or(canvas, |m| m.content_bounds().intersect(&canvas)); - if area.is_empty() { - return Err(EngineError::Other("Could not copy: the selected area is empty".into())); - } - let n = mask.surface.format().channels().max(1); - let values = crate::allocation::read_region(&mask.surface, area, "copying the mask")?; - let len = values - .len() - .checked_div(n) - .and_then(|pixels| pixels.checked_mul(2)) - .ok_or_else(|| EngineError::Other("not enough memory for copying the mask (requested size overflowed); the document was not changed".into()))?; - let cover = sel.map(|m| (m.read_region(area), m.format().channels().max(1))); - let mut px = crate::allocation::filled(len, 0.0, "copying the mask")?; - for (i, p) in values.chunks_exact(n).enumerate() { - px[i * 2] = p.first().copied().unwrap_or(0.0); - px[i * 2 + 1] = cover.as_ref().map_or(1.0, |(m, mk)| m.get(i * mk).copied().unwrap_or(0.0)); - } - let fmt = PixelFormat::new(ColorMode::Grayscale, mask.surface.format().sample, true); - let mut surface = Surface::new(fmt); - surface - .try_write_region(area, &px) - .map_err(|e| EngineError::Other(format!("not enough memory while copying the mask ({e}); the document was not changed")))?; - surface.prune(); - let bounds = surface.content_bounds(); - if bounds.is_empty() { - return Err(EngineError::Other("Could not copy: the selected area is empty".into())); - } - let b = bounds; - let (resolution, source) = (Some(d.doc.resolution_dpi), Some(d.doc.id)); - s.clipboard = Some(Clip { surface, bounds: b, layers: None, resolution, source }); - Ok(json!({"bounds": [b.x0, b.y0, b.width(), b.height()], "target": if filter { "filterMask" } else { "mask" }})) -} - -fn clear_selected(doc: &mut Document, id: LayerId, background: [f32; 4]) -> Result<()> { - let sel = doc.selection.clone(); - let canvas = doc.bounds(); - let area = sel.as_ref().map_or(canvas, |m| m.content_bounds().intersect(&canvas)); - clear_area(doc, id, area, sel.as_ref(), background) -} - -/// Cut / Clear on a layer: makes the selected pixels transparent. The Background can't hold -/// transparency, so there the area is filled with the background colour instead (Photoshop). -pub(crate) fn clear_area(doc: &mut Document, id: LayerId, area: Rect, sel: Option<&Surface>, background: [f32; 4]) -> Result<()> { - doc.layer(id).ok_or(EngineError::NoLayer(id))?; - let bg = doc.is_background(id); - let surf = crate::commands::paint_surface(doc, id, &Value::Null)?; - if bg { - crate::pixels::try_fill_surface(surf, area, background, sel, true)?; - } else { - crate::pixels::try_clear_surface(surf, area, sel)?; - } - surf.prune(); - Ok(()) -} - -/// Paste as a new layer (or into the targeted mask or channel: [`paste_to_target`]). `in_place` keeps the original position; otherwise the pixels are centred -/// on `center` (the view centre from the UI) or the canvas, unless they already overlap the canvas. -fn paste(s: &mut Session, p: &Value, in_place: bool) -> Result { - crate::allocation::checkpoint("pasting pixels")?; - let clip = s.clipboard.clone().ok_or(EngineError::Other("the clipboard is empty".into()))?; - let Some(d) = s.active() else { - // Nothing open to paste into: the clipboard becomes a document of its own (#368). - return new_from_clipboard(s); - }; - if crate::channel_cmds::target_of(p) != crate::channel_cmds::Target::Pixels { - return paste_to_target(s, p, in_place, None, "Paste"); - } - // A targeted colour channel takes the paste instead of a new layer (#2307). - if let Some(k) = crate::channel_clip::paste_color_target(s, p) { - return crate::channel_clip::paste(s, p, k, in_place, None, "Paste"); - } - let canvas = d.doc.bounds(); - let fmt = d.doc.pixel_format(); - let (dx, dy) = paste_offset(&clip, d.doc.id, canvas, p, in_place); - if let Some(layers) = clip.layers.as_deref().filter(|_| crate::layer_copy_cmds::layered(d.doc.mode)) { - return paste_layers(s, layers, dx, dy); - } - let moved = shifted(&clip.surface, dx, dy); - let target = PixelFormat::new(fmt.mode, fmt.sample, true); - let surf = if moved.format() == target { moved } else { moved.convert(target) }; - let id = s.edit("Paste", |doc, active| { - let mut l = Layer::raster(doc.next_layer_name("Layer"), target); - *crate::pixels_mut(&mut l)? = surf; - let id = doc.insert_above(*active, l); - *active = Some(id); - doc.selection = None; - Ok(id) - })?; - // `edit` reports only where the pasted pixels land as damage, not the whole document (#2901). - Ok(json!({"layer": id.0, "offset": [dx, dy]})) -} - -/// Paste of a whole copied layer ([`whole_layer`]): fresh copies (a group's children too), -/// converted to the document's colour, moved as the pixels would be, above the active layer. A pasted smart object gets its -/// own contents, independent of the copied one (as across documents). -fn paste_layers(s: &mut Session, layers: &Document, dx: i32, dy: i32) -> Result { - let d = s.active().ok_or(EngineError::NoDocument)?; - let mut copies = layers.clone(); - for l in &mut copies.layers { - *l = l.duplicate(); - } - crate::layer_copy_cmds::adapt_copies(s, &mut copies, &d.doc)?; - crate::layer_copy_cmds::translate_copies(&mut copies, &d.doc, dx, dy); - let patterns: Vec<_> = copies.patterns.iter().filter(|pat| !d.doc.patterns.iter().any(|q| q.id == pat.id)).cloned().collect(); - // A copied smart object may name a PSD-embedded linked file; land its `lnk` block too (#3584). - let mut linked = Vec::new(); - for (signature, key, data) in copies.metadata.psd_global_blocks.iter().filter(|(_, k, _)| matches!(k, b"lnk2" | b"lnk3" | b"lnkD" | b"lnkE")) { - if d.doc.metadata.psd_global_blocks.iter().any(|(_, dk, dd)| dk == key && std::sync::Arc::ptr_eq(dd, data)) { - continue; - } - // The clipboard may contain a subset of a destination block. Compare complete records, - // so copying one layer in the same document does not duplicate large embedded files. - let missing = photocraft_io::linked::select_items(data, &|_, raw| { - !d.doc.metadata.psd_global_blocks.iter().any(|(_, dk, dd)| dk == key && photocraft_io::linked::contains_item(dd, raw)) - }) - .map_err(|e| EngineError::Other(format!("Could not paste smart-object contents: {e}; the document was not changed")))?; - let missing = missing.map(std::sync::Arc::new).unwrap_or_else(|| data.clone()); - if !missing.is_empty() { - linked.try_reserve(1).map_err(|_| EngineError::Other("not enough memory to paste smart-object source records".into()))?; - linked.push((*signature, *key, missing)); - } - } - let id = s.edit("Paste", |doc, active| { - doc.patterns.extend(patterns); - doc.metadata.psd_global_blocks.extend(linked); - for l in copies.layers { - *active = Some(doc.insert_above(*active, l)); - } - doc.selection = None; - active.ok_or(EngineError::Other("nothing to paste".into())) - })?; - Ok(json!({"layer": id.0, "offset": [dx, dy]})) -} - -/// How far a paste moves the clipboard pixels: not at all in place (or when they lie on the -/// canvas and no `center` is given), else onto `center` (the view centre from the UI) or the -/// canvas centre, then kept on the canvas as Photoshop keeps it: pixels that fit stay wholly -/// inside, larger ones start at the canvas's top-left corner (#6759). `"clampToCanvas": false` -/// skips that, for Paste Into / Outside, which centre on the selection. -pub(crate) fn paste_offset(clip: &Clip, doc: DocId, canvas: Rect, p: &Value, in_place: bool) -> (i32, i32) { - let home = clip.source == Some(doc); - if in_place || (home && clip.bounds.intersect(&canvas) == clip.bounds && p.get("center").is_none()) { - return (0, 0); - } - let c = p.get("center").and_then(Value::as_array).filter(|a| a.len() >= 2).map(|a| (a[0].as_f64().unwrap_or(0.0), a[1].as_f64().unwrap_or(0.0))); - let (cx, cy) = c.unwrap_or((mid(canvas.x0, canvas.x1), mid(canvas.y0, canvas.y1))); - let b = clip.bounds; - let (dx, dy) = ((cx - mid(b.x0, b.x1)).round(), (cy - mid(b.y0, b.y1)).round()); - if p.get("clampToCanvas").and_then(Value::as_bool) == Some(false) || b.is_empty() { - return (dx as i32, dy as i32); - } - (clamp_shift(dx, b.x0, b.x1, canvas.x0, canvas.x1), clamp_shift(dy, b.y0, b.y1, canvas.y0, canvas.y1)) -} - -/// The midpoint of `a..b`, each edge converted before adding so extreme coordinates can't overflow. -fn mid(a: i32, b: i32) -> f64 { - (f64::from(a) + f64::from(b)) / 2.0 -} - -/// Shift `d` of the span `b0..b1` along one axis, changed as little as needed to keep the span -/// inside `c0..c1` when it fits; a span longer than the canvas starts at `c0`. -fn clamp_shift(d: f64, b0: i32, b1: i32, c0: i32, c1: i32) -> i32 { - let (b0, b1, c0, c1) = (i64::from(b0), i64::from(b1), i64::from(c0), i64::from(c1)); - // `as` saturates a NaN or out-of-range shift, then the clamp brings it into range. - let start = if b1 - b0 <= c1 - c0 { b0.saturating_add(d as i64).clamp(c0, c1 - (b1 - b0)) } else { c0 }; - i32::try_from(start - b0).unwrap_or(if start > b0 { i32::MAX } else { i32::MIN }) -} - -pub(crate) fn shifted(surface: &Surface, dx: i32, dy: i32) -> Surface { - if dx == 0 && dy == 0 { surface.clone() } else { photocraft_algo::resample::translate_surface(surface, dx, dy) } -} - -/// Paste into the targeted layer mask, alpha channel or Quick Mask (`"target"`) instead of as a -/// new layer (Photoshop, #1035): the pasted pixels' luminosity, placed as a paste places them, -/// over what was there. Their transparency, and `limit` (Paste Into / Outside), let it show -/// through. One history step. -pub(crate) fn paste_to_target(s: &mut Session, p: &Value, in_place: bool, limit: Option<&Surface>, label: &str) -> Result { - crate::allocation::checkpoint("pasting pixels")?; - let clip = s.clipboard.clone().ok_or(EngineError::Other("the clipboard is empty".into()))?; - let d = s.active().ok_or(EngineError::NoDocument)?; - let canvas = d.doc.bounds(); - let layer = d.active_layer; - let (dx, dy) = paste_offset(&clip, d.doc.id, canvas, p, in_place); - let src = shifted(&clip.surface, dx, dy); - let area = src.content_bounds().intersect(&canvas); - s.edit(label, |doc, _| { - let (surf, _) = crate::channel_cmds::target_surface(doc, layer, p)?; - crate::fill_cmds::composite_over(surf, &src, area, limit)?; - surf.prune(); - doc.selection = None; - Ok(()) - })?; - Ok(json!({"target": p.get("target"), "offset": [dx, dy]})) -} - -/// A new document the size of the clipboard image, holding it as its one layer, in the pixel -/// format it was copied in (#368). -fn new_from_clipboard(s: &mut Session) -> Result { - let clip = s.clipboard.clone().ok_or(EngineError::Other("the clipboard is empty".into()))?; - let b = clip.bounds; - let (w, h) = (b.width(), b.height()); - if w == 0 || h == 0 { - return Err(EngineError::Other("the clipboard image has no size".into())); - } - let (Some(dx), Some(dy)) = (b.x0.checked_neg(), b.y0.checked_neg()) else { - return Err(EngineError::Other("the clipboard origin is outside the coordinate range for a new document".into())); - }; - let fmt = clip.surface.format(); - let target = PixelFormat::new(fmt.mode, fmt.sample, true); - let moved = if dx == 0 && dy == 0 { clip.surface } else { photocraft_algo::resample::translate_surface(&clip.surface, dx, dy) }; - let mut doc = Document::new("Untitled", photocraft_geom::Size::new(w, h), fmt.mode, fmt.sample); - if let Some(r) = clip.resolution.filter(|r| r.is_finite() && *r > 0.0) { - doc.resolution_dpi = r; - } - let mut l = Layer::raster(doc.next_layer_name("Layer"), target); - *crate::pixels_mut(&mut l)? = if moved.format() == target { moved } else { moved.convert(target) }; - doc.layers.push(l); - let i = s.add_document(doc, None); - // Clipboard content has never been saved; closing this tab must ask before discarding it. - if let Some(st) = s.active_mut() { - st.saved_revision = 0; - } - Ok(json!({"document": i, "width": w, "height": h})) -} - -fn layer_via(s: &mut Session, cut: bool) -> Result { - let d = s.active().ok_or(EngineError::NoDocument)?; - let id = active_id(s)?; - let has_sel = d.doc.selection.is_some(); - if !has_sel && !cut && crate::layer_multi_cmds::multi(s, &Value::Null) { - // No selection, several layers selected: copy every one of them (Photoshop, #2777). - return crate::layer_multi_cmds::duplicate_selected(s, true, "Layer Via Copy"); - } - if !has_sel && !cut { - // No selection: Layer via Copy duplicates the whole layer (Photoshop). - let nid = s.edit("Layer Via Copy", |doc, active| { - let src = doc.layer(id).ok_or(EngineError::NoLayer(id))?; - let mut dup = src.duplicate(); - dup.name = doc.copy_name(&src.name); - dup.locks = Default::default(); - let nid = doc.insert_above(Some(id), dup); - *active = Some(nid); - Ok(nid) - })?; - return Ok(json!({"layer": nid.0})); - } - let surf = d.doc.layer(id).and_then(Layer::surface).ok_or(EngineError::Other("the active layer has no pixels".into()))?; - let clip = lift(surf, d.doc.selection.as_ref(), d.doc.bounds())?; - if clip.bounds.is_empty() { - return Err(EngineError::Other("Could not complete the command: the selected area is empty".into())); - } - let bg = s.tools.background; - let label = if cut { "Layer Via Cut" } else { "Layer Via Copy" }; - let nid = s.edit(label, |doc, active| { - if cut { - clear_selected(doc, id, bg)?; - } - let mut l = Layer::raster(doc.next_layer_name("Layer"), clip.surface.format()); - *crate::pixels_mut(&mut l)? = clip.surface; - let nid = doc.insert_above(Some(id), l); - *active = Some(nid); - // Photoshop deselects: a following Free Transform moves the whole new layer (#1096). - doc.selection = None; - Ok(nid) - })?; - Ok(json!({"layer": nid.0})) -} - -fn merge_visible(s: &mut Session) -> Result { - s.edit("Merge Visible", |doc, active| { - let visible: Vec = doc.layers.iter().enumerate().filter(|(_, l)| l.visible).map(|(i, _)| i).collect(); - if visible.len() < 2 && !visible.iter().any(|i| doc.layers[*i].is_group()) { - return Err(EngineError::Other("there are not enough visible layers to merge".into())); - } - let lowest = visible[0]; - let base = doc.layers[lowest].clone(); - let is_background = lowest == 0 && doc.is_background(base.id); - // Composite of visible layers only (hidden ones stay where they are). - let mut solo = doc.clone(); - solo.layers.retain(|l| l.visible); - let fmt = doc.pixel_format(); - let fmt = if is_background { fmt } else { PixelFormat::new(fmt.mode, fmt.sample, true) }; - let mut merged = Layer::raster(base.name.clone(), fmt); - merged.locks = base.locks; - *crate::pixels_mut(&mut merged)? = crate::pixels::composite_layers(&solo, fmt, is_background.then_some([1.0, 1.0, 1.0])); - let mid = merged.id; - let mut out = Vec::with_capacity(doc.layers.len()); - for (i, l) in doc.layers.drain(..).enumerate() { - if i == lowest { - out.push(merged.clone()); - } else if !l.visible { - out.push(l); - } - } - doc.layers = out; - *active = Some(mid); - Ok(()) - })?; - Ok(Value::Null) -} - -/// Histogram of a pixel layer (8-bit bins per channel: R, G, B) inside the selection. -fn histograms(surf: &Surface, area: Rect) -> [[u64; 256]; 3] { - let mut h = [[0u64; 256]; 3]; - let step = ((area.width() as u64 * area.height() as u64) / 4_000_000).max(1) as usize; // sample big images - let mut row = vec![[0u8; 4]; area.width() as usize]; - for y in (area.y0..area.y1).step_by(step.isqrt().max(1)) { - surf.read_rgba8_into(Rect::new(area.x0, y, area.x1, y + 1), &mut row); - for p in row.iter().step_by(step.isqrt().max(1)) { - if p[3] == 0 { - continue; - } - for c in 0..3 { - h[c][p[c] as usize] += 1; - } - } - } - h -} - -/// Black and white points with `clip` (fraction) clipped at each end. -fn clip_points(h: &[u64; 256], clip: f64) -> (f32, f32) { - let total: u64 = h.iter().sum(); - if total == 0 { - return (0.0, 1.0); - } - let lim = (total as f64 * clip) as u64; - let (mut acc, mut lo) = (0u64, 0usize); - while lo < 254 && acc + h[lo] <= lim { - acc += h[lo]; - lo += 1; - } - let (mut acc, mut hi) = (0u64, 255usize); - while hi > lo + 1 && acc + h[hi] <= lim { - acc += h[hi]; - hi -= 1; - } - (lo as f32 / 255.0, hi as f32 / 255.0) -} - -fn median(h: &[u64; 256]) -> f32 { - let total: u64 = h.iter().sum(); - let mut acc = 0; - for (i, v) in h.iter().enumerate() { - acc += v; - if acc * 2 >= total { - return i as f32 / 255.0; - } - } - 0.5 -} - -/// Image › Auto Tone / Auto Contrast / Auto Color (0.1% clipping, Photoshop's defaults). -fn auto_adjust(s: &mut Session, kind: &str) -> Result { - let id = active_id(s)?; - let d = s.active().ok_or(EngineError::NoDocument)?; - let surf = d.doc.layer(id).and_then(Layer::surface).ok_or(EngineError::Other("the active layer has no pixels".into()))?; - let area = d.doc.selection.as_ref().map_or(d.doc.bounds(), |m| m.content_bounds()).intersect(&d.doc.bounds()); - let h = histograms(surf, area); - let clip = 0.001; - let mut per = [LevelsChannel::default(), LevelsChannel::default(), LevelsChannel::default()]; - match kind { - "contrast" => { - // Same points for all channels (preserves colour), from the combined histogram. - let mut all = [0u64; 256]; - for c in &h { - for (a, v) in all.iter_mut().zip(c) { - *a += v; - } - } - let (lo, hi) = clip_points(&all, clip); - for p in &mut per { - (p.in_black, p.in_white) = (lo, hi); - } - } - _ => { - for (c, p) in per.iter_mut().enumerate() { - (p.in_black, p.in_white) = clip_points(&h[c], clip); - } - if kind == "color" { - // Neutralise midtones: move each channel's median onto the average median. - let meds: Vec = (0..3).map(|c| median(&h[c])).collect(); - let target = meds.iter().sum::() / 3.0; - for (c, p) in per.iter_mut().enumerate() { - let t = ((meds[c] - p.in_black) / (p.in_white - p.in_black).max(1e-3)).clamp(0.02, 0.98); - let want = ((target - p.in_black) / (p.in_white - p.in_black).max(1e-3)).clamp(0.02, 0.98); - // out = t^(1/g) = want → g = ln t / ln want - p.gamma = (t.ln() / want.ln()).clamp(0.1, 9.99); - } - } - } - } - let adj = Adjustment::Levels { master: LevelsChannel::default(), per_channel: per, space: Default::default(), black: LevelsChannel::default() }; - let label = match kind { - "contrast" => "Auto Contrast", - "color" => "Auto Color", - _ => "Auto Tone", - }; - s.edit(label, |doc, _| { - let sel = doc.selection.clone(); - let mode = doc.mode; - let surf = crate::commands::paint_surface(doc, id, &Value::Null)?; - crate::pixels::adjust_surface(surf, &adj, sel.as_ref(), mode).map_err(EngineError::Other)?; - Ok(()) - })?; - Ok(Value::Null) -} - -fn toggle_last_state(s: &mut Session) -> Result { - let st = s.active().ok_or(EngineError::NoDocument)?; - let redo = st.history.can_redo(); - Ok(json!(if redo { s.redo() } else { s.undo() })) -} - -/// Edit › Transform › Again: replay the last `edit.transform` on the active layer. -fn transform_again(s: &mut Session) -> Result { - let p = transform_again_params(s)?; - s.execute("edit.transform", p) -} - -/// Transform Again on a copy (⌥⇧⌘T, no menu item): duplicates the active layer and repeats the -/// last transform on the copy, as one history step, so pressing it again steps and repeats -/// (#352). The transform is worked out before anything changes, so a refusal leaves no copy. -fn transform_again_copy(s: &mut Session) -> Result { - let p = transform_again_params(s)?; - let id = active_id(s)?; - let journal = s.journal.len(); - // The steps are recorded (Again on a Copy is not replayable itself): with one layer selected, - // "duplicate the current layer" plays back on any document, a layer id only on this one. - let dup = if crate::layer_multi_cmds::multi(s, &Value::Null) { json!({"layer": id.0}) } else { json!({}) }; - s.execute("layer.duplicate", dup)?; - match s.execute("edit.transform", p) { - Ok(r) => { - let st = s.active_mut().ok_or(EngineError::NoDocument)?; - st.history.purge_last(); - st.history.set_current_label("Transform Again"); - Ok(r) - } - Err(e) => { - // The copy (e.g. of a layer whose position is locked) couldn't be transformed: take - // it back, leaving nothing to redo and no Duplicate step to record. - s.undo(); - s.journal.truncate(journal); - if let Some(st) = s.active_mut() { - st.history.clear_redo(); - } - Err(e) - } - } -} - -/// The `edit.transform` params that repeat the last transform on the active layer. -fn transform_again_params(s: &Session) -> Result { - let (_, last) = - s.journal.iter().rev().find(|(id, _)| id == "edit.transform").cloned().ok_or(EngineError::Other("there is no transform to repeat".into()))?; - let (rect, quad) = (last.get("rect").cloned(), last.get("quad").cloned()); - let mut p = json!({"interpolation": last.get("interpolation").cloned().unwrap_or(json!("bicubic"))}); - match (rect, quad, last.get("matrix").cloned()) { - (Some(r), Some(q), _) => { - let v = |x: &Value| -> Vec { x.as_array().map(|a| a.iter().filter_map(Value::as_f64).collect()).unwrap_or_default() }; - let r = v(&r); - let q: Vec> = q.as_array().map(|a| a.iter().map(v).collect()).unwrap_or_default(); - if r.len() != 4 || q.len() != 4 || q.iter().any(|row| row.len() < 2) { - return Err(EngineError::Other("the last transform can't be repeated".into())); - } - let h = photocraft_algo::transform::Homography::rect_to_quad( - [r[0], r[1], r[2], r[3]], - [[q[0][0], q[0][1]], [q[1][0], q[1][1]], [q[2][0], q[2][1]], [q[3][0], q[3][1]]], - ) - .ok_or(EngineError::Other("the last transform can't be repeated".into()))?; - let d = s.active().ok_or(EngineError::NoDocument)?; - let l = d.doc.layer(active_id(s)?).ok_or(EngineError::Other("no active layer".into()))?; - let b = crate::transform_cmds::transform_bounds(&d.doc, l); - if b.is_empty() { - return Err(EngineError::Other("nothing to transform".into())); - } - let nr = [b.x0 as f64, b.y0 as f64, b.x1 as f64, b.y1 as f64]; - let corners = [(nr[0], nr[1]), (nr[2], nr[1]), (nr[2], nr[3]), (nr[0], nr[3])].map(|(x, y)| { - let (a, b) = h.apply(x, y); - [a, b] - }); - p["rect"] = json!(nr); - p["quad"] = json!(corners); - } - (_, _, Some(m)) => p["matrix"] = m, - _ => return Err(EngineError::Other("the last transform can't be repeated".into())), - } - Ok(p) -} - -/// Guides further than this from the canvas origin are refused: far past any document (300000 px) -/// yet well within f32 precision. -const MAX_GUIDE_PX: f64 = 1_000_000.0; - -/// A guide `position` in document pixels: a number of pixels, or text with a unit as in Photoshop's -/// New Guide dialog ("50%", "2.5 cm", "12 pt"). Percent is of the document's width for a vertical -/// guide and its height for a horizontal one; points and picas follow Units & Rulers › Point Size. -/// `None` when there is no `position`. -fn guide_position(s: &Session, p: &Value, vertical: bool) -> Result> { - let Some(v) = p.get("position") else { return Ok(None) }; - let px = match (v.as_f64(), v.as_str()) { - (Some(n), _) => n, - (None, Some(text)) => { - let (n, unit) = crate::prefs::Unit::parse_length(text).ok_or_else(|| { - EngineError::Other(format!("`position` {text:?} is not a length: give a number of pixels, or a number with px, in, cm, mm, pt, pc or %")) - })?; - let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; - let extent = if vertical { doc.size.width } else { doc.size.height }; - unit.unwrap_or(crate::prefs::Unit::Pixels).to_px(n, doc.resolution_dpi as f64, extent as f64, s.prefs().units_and_rulers.point_size.per_inch()) - } - _ => return Err(EngineError::Other("`position` must be a number of pixels or text with a unit".into())), - }; - if !px.is_finite() || px.abs() > MAX_GUIDE_PX { - return Err(EngineError::Other(format!("`position` is out of range (at most {MAX_GUIDE_PX} px from the canvas origin)"))); - } - Ok(Some(px)) -} - -/// Photoshop's guide colours, in its order, by the names `view.newGuide` takes: New Guide's and -/// New Guide Layout's Color lists. Cyan (the default guide colour in Preferences, so a guide -/// dragged from a ruler reads as Cyan), Magenta and Yellow are the values New Guide Layout first -/// shipped with; the rest approximate Photoshop's on screen, rounded to web-safe steps. -pub const GUIDE_COLORS: [(&str, [u8; 3]); 9] = [ - ("lightBlue", [0x33, 0x66, 0xff]), - ("lightRed", [0xff, 0x33, 0x33]), - ("green", [0x33, 0xff, 0x33]), - ("mediumBlue", [0x33, 0x33, 0xff]), - ("yellow", [0xff, 0xcc, 0x00]), - ("magenta", [0xff, 0x00, 0xff]), - ("cyan", [0x4a, 0xff, 0xff]), - ("lightGray", [0xe7, 0xe7, 0xe7]), - ("black", [0x00, 0x00, 0x00]), -]; - -/// A guide `color`: one of [`GUIDE_COLORS`]' names or `"#rrggbb"`. `None` when there is no `color` -/// (the guide uses Preferences › Guides, Grid & Slices › Guide colour). -fn guide_color(p: &Value) -> Result> { - let Some(v) = p.get("color") else { return Ok(None) }; - let text = v.as_str().ok_or(EngineError::Other("`color` must be a colour name or \"#rrggbb\"".into()))?; - GUIDE_COLORS.iter().find(|(name, ..)| name.eq_ignore_ascii_case(text)).map(|(.., rgb)| *rgb).or_else(|| crate::prefs::parse_hex(text)).map(Some).ok_or_else( - || EngineError::Other(format!("`color` {text:?} is not a guide colour: use \"#rrggbb\" or one of {}", GUIDE_COLORS.map(|c| c.0).join(", "))), - ) -} - -/// Edit Selected Guides (the guide context menu): change one guide's orientation, position and -/// colour in one history step. A guide that keeps its orientation keeps its index; one that turns -/// goes to the end of the other list. Without `color` it keeps its own colour, or none. -fn edit_guide(s: &mut Session, p: &Value) -> Result { - let orientation = |key: &str| match p.get(key).map(|v| v.as_str()) { - None => Ok(None), - Some(Some("horizontal")) => Ok(Some(false)), - Some(Some("vertical")) => Ok(Some(true)), - Some(_) => Err(EngineError::Other(format!("`{key}` must be \"horizontal\" or \"vertical\""))), - }; - let from = orientation("orientation")?.unwrap_or(false); - let to = orientation("newOrientation")?.unwrap_or(from); - let index = p.get("index").and_then(Value::as_u64).ok_or(EngineError::Other("missing `index`".into()))?; - let pos = guide_position(s, p, to)?; - let color = guide_color(p)?; - s.edit("Edit Guide", |doc, _| { - let guides = &mut doc.guides; - let list = if from { &guides.vertical } else { &guides.horizontal }; - let i = usize::try_from(index).ok().filter(|i| *i < list.len()).ok_or(EngineError::Other("no such guide".into()))?; - let old = list[i]; - let at = pos.unwrap_or(old); - let rgb = color.or_else(|| guides.color(from, old)); - if from == to { - let list = if from { &mut guides.vertical } else { &mut guides.horizontal }; - list[i] = at; - } else { - (if from { &mut guides.vertical } else { &mut guides.horizontal }).remove(i); - (if to { &mut guides.vertical } else { &mut guides.horizontal }).push(at); - } - guides.prune_colors(); - if rgb.is_some() { - guides.set_color(to, at, rgb); - } - Ok(()) - })?; - Ok(Value::Null) -} - -/// View › New Guide / guide moves (undoable, like Photoshop's "New Guide"/"Move Guide" states). -fn guide_cmd(s: &mut Session, p: &Value, op: &str) -> Result { - let vertical = p.get("orientation").and_then(Value::as_str).unwrap_or("horizontal") == "vertical"; - let pos = guide_position(s, p, vertical)?; - let color = if op == "new" { guide_color(p)? } else { None }; - let index = p.get("index").and_then(Value::as_u64).map(|v| v as usize); - let label = match op { - "new" => "New Guide", - "move" => "Move Guide", - "delete" => "Delete Guide", - _ => "Clear Guides", - }; - s.edit(label, |doc, _| { - let guides = &mut doc.guides; - let g = if vertical { &mut guides.vertical } else { &mut guides.horizontal }; - match op { - "new" => { - let at = pos.ok_or(EngineError::Other("missing `position`".into()))?; - g.push(at); - if color.is_some() { - guides.set_color(vertical, at, color); - } - } - "move" => { - let i = index.filter(|i| *i < g.len()).ok_or(EngineError::Other("no such guide".into()))?; - let to = pos.ok_or(EngineError::Other("missing `position`".into()))?; - let from = std::mem::replace(&mut g[i], to); - // The guide takes its colour along; another guide left at the old position keeps it. - if let Some(rgb) = guides.color(vertical, from) { - guides.set_color(vertical, to, Some(rgb)); - } - guides.prune_colors(); - } - "delete" => { - let i = index.filter(|i| *i < g.len()).ok_or(EngineError::Other("no such guide".into()))?; - g.remove(i); - guides.prune_colors(); - } - _ => { - guides.horizontal.clear(); - guides.vertical.clear(); - guides.colors.clear(); - } - } - Ok(()) - })?; - Ok(Value::Null) -} - -/// Farthest the ruler zero point may sit from the image, in document pixels. -const MAX_RULER_ORIGIN: f64 = 1.0e7; - -/// Move the rulers' zero point (`view.setRulerOrigin`), or put it back at the image's top-left -/// (`view.resetRulerOrigin`, `p` = None). Undoable like the guides. -fn ruler_origin_cmd(s: &mut Session, p: Option<&Value>) -> Result { - let origin = match p { - None => [0.0, 0.0], - Some(p) => { - let axis = |k: &str| { - p.get(k) - .and_then(Value::as_f64) - .filter(|v| v.is_finite() && v.abs() <= MAX_RULER_ORIGIN) - .ok_or_else(|| EngineError::Other(format!("`{k}` must be a number of pixels within ±{MAX_RULER_ORIGIN}"))) - }; - [axis("x")?, axis("y")?] - } - }; - let label = if p.is_some() { "Set Ruler Origin" } else { "Reset Ruler Origin" }; - s.edit(label, |doc, _| { - doc.ruler_origin = origin; - Ok(()) - })?; - Ok(json!({"x": origin[0], "y": origin[1]})) -} - -pub fn specs() -> Vec { - macro_rules! spec { - ($id:expr, $label:expr, $menu:expr, $sc:expr, $params:expr, $enabled:expr, $run:expr) => { - CommandSpec { id: $id, label: $label, menu: $menu, shortcut: $sc, params: $params, enabled: $enabled, journal: true, run: $run } - }; - } - vec![ - spec!("edit.cut", "Cut", &["Edit"], Some("Cmd+X"), "{} (a targeted colour channel cuts that channel only)", has_pixels, |s, p| { - // Refuse a locked layer before copying, so a refused Cut leaves the clipboard alone. - let id = active_id(s)?; - crate::commands::check_pixels_unlocked(&s.active().ok_or(EngineError::NoDocument)?.doc, id)?; - // A targeted colour channel cuts that channel only (#2698). - if let Some(k) = crate::channel_clip::paste_color_target(s, p) { - return crate::channel_clip::cut(s, id, k); - } - let r = copy(s, false)?; - let bg = s.tools.background; - s.edit("Cut Pixels", |doc, _| clear_selected(doc, id, bg))?; - Ok(r) - }), - spec!( - "edit.copy", - "Copy", - &["Edit"], - Some("Cmd+C"), - r##"{"target":"mask|filterMask"? = the targeted mask, copied as grayscale (#2928)} (a targeted colour or alpha channel copies that channel, as grayscale)"##, - can_copy, - |s, p| { - if crate::commands::is_mask_target(p) { - return copy_mask(s, crate::channel_cmds::target_of(p) == crate::channel_cmds::Target::FilterMask); - } - match crate::channel_clip::copy(s)? { - Some(r) => Ok(r), - None => copy(s, false), - } - } - ), - spec!("edit.copyMerged", "Copy Merged", &["Edit"], Some("Cmd+Shift+C"), "{}", has_doc, |s, _| copy(s, true)), - spec!( - "edit.paste", - "Paste", - &["Edit"], - Some("Cmd+V"), - concat!( - r#"{"center":[x,y]? (view centre; default keeps the position when it overlaps the canvas),"clampToCanvas":bool=true (keep the paste on the canvas, or at its top-left when larger),"#, - paste_target!(), - "} (with no document open: a new document from the clipboard)" - ), - has_clip_only, - |s, p| paste(s, p, false) - ), - spec!( - "file.newFromClipboard", - "New from Clipboard", - &["File"], - None, - "{} (a new document the size of the clipboard image, holding it as one layer)", - has_clip_only, - |s, _| new_from_clipboard(s) - ), - spec!( - "edit.pasteSpecial.pasteInPlace", - "Paste in Place", - &["Edit", "Paste Special"], - Some("Cmd+Shift+V"), - concat!("{", paste_target!(), "}"), - has_clip, - |s, p| paste(s, p, true) - ), - spec!("layer.new.layerViaCopy", "Layer via Copy", &["Layer", "New"], Some("Cmd+J"), "{}", has_doc, |s, _| layer_via(s, false)), - spec!("layer.new.layerViaCut", "Layer via Cut", &["Layer", "New"], Some("Cmd+Shift+J"), "{}", has_pixels, |s, _| layer_via(s, true)), - spec!("layer.mergeVisible", "Merge Visible", &["Layer"], Some("Cmd+Shift+E"), "{}", has_doc, |s, _| merge_visible(s)), - spec!("image.autoTone", "Auto Tone", &["Image"], Some("Cmd+Shift+L"), "{}", has_pixels, |s, _| auto_adjust(s, "tone")), - spec!("image.autoContrast", "Auto Contrast", &["Image"], Some("Cmd+Alt+Shift+L"), "{}", has_pixels, |s, _| auto_adjust(s, "contrast")), - spec!("image.autoColor", "Auto Color", &["Image"], Some("Cmd+Shift+B"), "{}", has_pixels, |s, _| auto_adjust(s, "color")), - spec!("edit.toggleLastState", "Toggle Last State", &["Edit"], Some("Cmd+Alt+Z"), "{}", has_doc, |s, _| toggle_last_state(s)), - spec!("edit.transform.again", "Again", &["Edit", "Transform"], Some("Cmd+Shift+T"), "{}", has_doc, |s, _| transform_again(s)), - spec!( - "edit.transform.againCopy", - "Transform Again on a Copy", - &[], - Some("Cmd+Alt+Shift+T"), - "{} (duplicates the active layer and repeats the last transform on the copy: step and repeat)", - has_doc, - |s, _| transform_again_copy(s) - ), - spec!( - "view.newGuide", - "New Guide…", - &["View"], - None, - r##"{"orientation":"horizontal|vertical","position":px or "","color":"lightBlue|lightRed|green|mediumBlue|yellow|magenta|cyan|lightGray|black" or "#rrggbb"?} (units px, in, cm, mm, pt, pc or %; % is of the width for a vertical guide, the height for a horizontal one; without a color the guide uses the guide colour in Preferences)"##, - has_doc, - |s, p| guide_cmd(s, p, "new") - ), - spec!( - "view.moveGuide", - "Move Guide", - &[], - None, - r##"{"orientation":"horizontal|vertical","index":n,"position":px or ""} (units as for view.newGuide)"##, - has_doc, - |s, p| guide_cmd(s, p, "move") - ), - spec!( - "view.editGuide", - "Edit Guide", - &[], - None, - r##"{"orientation":"horizontal|vertical","index":n,"newOrientation":"horizontal|vertical"?,"position":px or ""?,"color":name or "#rrggbb"?} (Edit Selected Guides: units and colours as for view.newGuide; % is of the new orientation's extent; whatever is left out stays as it was)"##, - has_doc, - edit_guide - ), - spec!("view.deleteGuide", "Delete Guide", &[], None, r##"{"orientation":"horizontal|vertical","index":n}"##, has_doc, |s, p| guide_cmd(s, p, "delete")), - spec!("view.clearGuides", "Clear Guides", &["View"], None, "{}", has_doc, |s, p| guide_cmd(s, p, "clear")), - spec!( - "view.setRulerOrigin", - "Set Ruler Origin", - &[], - None, - r##"{"x":px,"y":px} (the rulers' zero point in document pixels; the rulers and Info panel measure from it)"##, - has_doc, - |s, p| ruler_origin_cmd(s, Some(p)) - ), - spec!("view.resetRulerOrigin", "Reset Ruler Origin", &[], None, "{} (zero point back at the image's top-left)", has_doc, |s, _| ruler_origin_cmd( - s, None - )), - ] -} - -#[cfg(test)] -mod tests { - use super::*; - - fn session() -> Session { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 100, "height": 100})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.edit("paint", |doc, a| { - doc.layer_mut(a.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(10, 10, 50, 30), &[1.0, 0.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - s - } - - #[test] - fn new_clipboard_document_rejects_an_unrepresentable_origin() { - let mut s = Session::new(); - let mut surface = Surface::new(PixelFormat::RGBA8); - surface.write_pixel(i32::MIN, 0, &[1.0, 0.0, 0.0, 1.0]); - s.clipboard = Some(Clip { surface, bounds: Rect::from_xywh(i32::MIN, 0, 1, 1), layers: None, resolution: None, source: None }); - let result = new_from_clipboard(&mut s); - assert!(result.unwrap_err().to_string().contains("clipboard origin")); - assert!(s.execute("file.newFromClipboard", json!({})).is_err()); - assert!(s.documents().is_empty()); - assert_eq!(s.clipboard.as_ref().unwrap().surface.rgba(i32::MIN, 0), [1.0, 0.0, 0.0, 1.0]); - } - - /// #8945: pixels copied in one document land in place when pasted back into it, and centred - /// in another, even where their old position would fit (Photoshop's Paste). - #[test] - fn paste_centres_pixels_from_another_document() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 40, "height": 30, "background": "white"})).unwrap(); - s.execute("select.all", json!({})).unwrap(); - s.execute("edit.copy", json!({})).unwrap(); - let r = s.execute("edit.paste", json!({})).unwrap(); - assert_eq!(r["offset"], json!([0, 0]), "back into its own document: in place"); - s.execute("file.new", json!({"width": 100, "height": 80, "background": "white"})).unwrap(); - let r = s.execute("edit.paste", json!({})).unwrap(); - assert_eq!(r["offset"], json!([30, 25]), "into another document: centred"); - // An image from another app has no source document: centred too. - s.clipboard = s.clipboard.take().map(|c| Clip { source: None, ..c }); - let r = s.execute("edit.paste", json!({})).unwrap(); - assert_eq!(r["offset"], json!([30, 25])); - // Paste in Place still keeps the position. - let r = s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap(); - assert_eq!(r["offset"], json!([0, 0])); - } - - #[test] - fn paste_centers_clipboard_bounds_near_coordinate_limits() { - for origin in [i32::MAX - 512, i32::MIN + 512] { - let clip = - Clip { surface: Surface::new(PixelFormat::RGBA8), bounds: Rect::from_xywh(origin, origin, 2, 2), layers: None, resolution: None, source: None }; - let (dx, dy) = paste_offset(&clip, DocId(1), Rect::new(0, 0, 20, 20), &json!({}), false); - assert_eq!(i64::from(origin) + i64::from(dx), 9); - assert_eq!(i64::from(origin) + i64::from(dy), 9); - let clip = Clip { bounds: Rect::new(0, 0, 2, 2), ..clip }; - let (dx, dy) = paste_offset(&clip, DocId(1), Rect::from_xywh(origin, origin, 20, 20), &json!({}), false); - assert_eq!(dx, origin + 9); - assert_eq!(dy, origin + 9); - } - } - - #[test] - fn injected_clear_buffer_failure_leaves_the_document_unchanged() { - let mut s = session(); - let st = s.active().unwrap(); - let id = st.active_layer.unwrap(); - let before = st.doc.layer(id).unwrap().surface().unwrap().clone(); - let revision = st.revision; - - crate::allocation::fail_next_for_test(); - let result = s.execute("edit.clear", json!({})); - - assert!(result.as_ref().is_err_and(|e| e.to_string().contains("not enough memory for erasing pixels"))); - let st = s.active().unwrap(); - assert_eq!(st.doc.layer(id).unwrap().surface(), Some(&before)); - assert_eq!(st.revision, revision); - } - - #[test] - fn injected_copy_buffer_failure_does_not_change_document_or_clipboard() { - let mut s = session(); - let st = s.active().unwrap(); - let id = st.active_layer.unwrap(); - let before = st.doc.layer(id).unwrap().surface().unwrap().clone(); - let revision = st.revision; - - crate::allocation::fail_next_for_test(); - let result = s.execute("edit.copy", json!({})); - - assert!(result.as_ref().is_err_and(|e| e.to_string().contains("not enough memory for copying pixels"))); - let st = s.active().unwrap(); - assert_eq!(st.doc.layer(id).unwrap().surface(), Some(&before)); - assert_eq!(st.revision, revision); - assert!(s.clipboard.is_none()); - } - - #[test] - fn injected_fill_result_reservation_failure_keeps_pixels_and_history() { - let mut s = session(); - let st = s.active().unwrap(); - let id = st.active_layer.unwrap(); - let before = st.doc.layer(id).unwrap().surface().unwrap().clone(); - let revision = st.revision; - let history_len = st.history.past_len(); - - crate::allocation::fail_next_for_test(); - let result = s.execute("edit.fill", json!({"color": "#00ff00"})); - - assert!(result.as_ref().is_err_and(|e| e.to_string().contains("not enough memory for blending pixels"))); - let st = s.active().unwrap(); - assert_eq!(st.doc.layer(id).unwrap().surface(), Some(&before)); - assert_eq!(st.revision, revision); - assert_eq!(st.history.past_len(), history_len); - } - - #[test] - fn injected_paste_failure_does_not_change_document_or_clipboard() { - let mut s = session(); - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 8, "height": 8})).unwrap(); - s.execute("edit.copy", json!({})).unwrap(); - let before_clip = s.clipboard.clone(); - let st = s.active().unwrap(); - let before_doc = (*st.doc).clone(); - let revision = st.revision; - let history_len = st.history.past_len(); - - crate::allocation::fail_next_for_test(); - let result = s.execute("edit.paste", json!({})); - - assert!(result.as_ref().is_err_and(|e| e.to_string().contains("not enough memory for pasting pixels"))); - let st = s.active().unwrap(); - assert_eq!(*st.doc, before_doc); - assert_eq!(st.revision, revision); - assert_eq!(st.history.past_len(), history_len); - let after_clip = s.clipboard.as_ref().expect("clipboard remains available"); - let before_clip = before_clip.as_ref().expect("clipboard was populated"); - assert_eq!(after_clip.bounds, before_clip.bounds); - assert_eq!(after_clip.surface, before_clip.surface); - } - - #[test] - fn injected_transform_failure_keeps_pixels_and_history() { - let mut s = session(); - let st = s.active().unwrap(); - let id = st.active_layer.unwrap(); - let before = st.doc.layer(id).unwrap().surface().unwrap().clone(); - let revision = st.revision; - let history_len = st.history.past_len(); - - crate::allocation::fail_next_for_test(); - let result = s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 20, 30]})); - - assert!(result.as_ref().is_err_and(|e| e.to_string().contains("not enough memory for transforming pixels"))); - let st = s.active().unwrap(); - assert_eq!(st.doc.layer(id).unwrap().surface(), Some(&before)); - assert_eq!(st.revision, revision); - assert_eq!(st.history.past_len(), history_len); - } - - fn active_bounds(s: &Session) -> Rect { - let st = s.active().unwrap(); - st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds() - } - - /// New from Clipboard takes the copied document's resolution (Photoshop's Clipboard preset), - /// so a later Image Size by resolution scales from the right size. - #[test] - fn new_from_clipboard_keeps_the_source_resolution() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 60, "height": 40, "resolution": 300})).unwrap(); - s.execute("select.all", json!({})).unwrap(); - s.execute("edit.copy", json!({})).unwrap(); - s.execute("file.newFromClipboard", json!({})).unwrap(); - assert_eq!(s.active().unwrap().doc.resolution_dpi, 300.0); - } - - /// #368: the clipboard as a document of its own, from New from Clipboard or a Paste with - /// nothing open, at every depth. - #[test] - fn new_from_clipboard_and_paste_with_no_document() { - for depth in [8, 16, 32] { - let mut s = Session::new(); - assert!(!s.is_enabled("file.newFromClipboard") && !s.is_enabled("edit.paste"), "nothing copied yet"); - assert!(s.execute("file.newFromClipboard", json!({})).is_err()); - s.execute("file.new", json!({"width": 100, "height": 100, "depth": depth})).unwrap(); - assert!(!s.active().unwrap().is_dirty(), "an untouched blank document is clean"); - s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); - s.execute("select.rect", json!({"x": 10, "y": 20, "width": 30, "height": 15})).unwrap(); - s.execute("edit.copy", json!({})).unwrap(); - // With a document open: a second document, sized to the copy, its pixels at the origin. - let r = s.execute("file.newFromClipboard", json!({})).unwrap(); - assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(30), Some(15)), "{r}"); - assert_eq!(s.documents().len(), 2); - assert!(s.active().unwrap().is_dirty(), "a document made from clipboard pixels needs saving (#4665)"); - let d = &s.active().unwrap().doc; - assert_eq!((d.size.width, d.size.height, d.layers.len()), (30, 15, 1)); - assert_eq!(d.pixel_format().sample, s.documents()[0].doc.pixel_format().sample, "{depth}-bit kept"); - assert_eq!(active_bounds(&s), Rect::new(0, 0, 30, 15)); - let px = d.layers[0].surface().unwrap().rgba(0, 0); - assert!(px[0] > 0.99 && px[1] < 0.01 && px[3] > 0.99, "{px:?}"); - // With nothing open, Paste makes the document too. - while s.active().is_some() { - s.execute("file.close", json!({})).unwrap(); - } - assert!(s.is_enabled("edit.paste") && !s.is_enabled("edit.pasteSpecial.pasteInPlace")); - s.execute("edit.paste", json!({})).unwrap(); - assert_eq!(s.documents().len(), 1); - assert!(s.active().unwrap().is_dirty(), "Paste with no tab also needs a save prompt"); - assert_eq!(active_bounds(&s), Rect::new(0, 0, 30, 15)); - assert!(s.execute("edit.pasteSpecial.pasteInPlace", json!({})).is_ok(), "into the new document"); - } - } - - #[test] - fn copy_paste_in_place_and_centred() { - let mut s = session(); - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); - s.execute("edit.copy", json!({})).unwrap(); - s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap(); - assert_eq!(active_bounds(&s), Rect::new(10, 10, 30, 30)); - assert!(s.active().unwrap().doc.selection.is_none()); - s.execute("edit.paste", json!({"center": [70, 70]})).unwrap(); - assert_eq!(active_bounds(&s), Rect::new(60, 60, 80, 80)); - assert_eq!(s.active().unwrap().doc.layers.len(), 4); - } - - /// A `w`×`h` document with an opaque `cw`×`ch` image from another app on the clipboard. - fn external_clip_session(w: i32, h: i32, cw: i32, ch: i32) -> Session { - let mut s = Session::new(); - s.execute("file.new", json!({"width": w, "height": h})).unwrap(); - let mut surface = Surface::new(PixelFormat::RGBA8); - surface.fill_rect(Rect::new(0, 0, cw, ch), &[1.0, 0.0, 0.0, 1.0]); - s.clipboard = Some(Clip { surface, bounds: Rect::new(0, 0, cw, ch), layers: None, resolution: None, source: None }); - s - } - - /// #6759: wherever the view is centred, a paste that fits the canvas stays wholly on it. - #[test] - fn paste_that_fits_stays_on_the_canvas() { - for (w, h, center, want) in [ - (60, 100, [40.0, 45.0], Rect::new(0, 0, 60, 100)), - (60, 100, [-500.0, 900.0], Rect::new(0, 0, 60, 100)), - (100, 100, [10.0, 80.0], Rect::new(0, 0, 60, 100)), - (100, 100, [95.0, 50.0], Rect::new(40, 0, 100, 100)), - (100, 120, [50.0, 60.0], Rect::new(20, 10, 80, 110)), - ] { - let mut s = external_clip_session(w, h, 60, 100); - s.execute("edit.paste", json!({ "center": center })).unwrap(); - assert_eq!(active_bounds(&s), want, "{w}x{h} canvas, view centre {center:?}"); - } - } - - /// #6759: a paste larger than the canvas starts at its top-left corner, wherever the view is. - #[test] - fn paste_larger_than_the_canvas_starts_at_its_top_left() { - for center in [[0.0, 0.0], [25.0, 20.0], [1000.0, 1000.0], [-1000.0, 30.0]] { - let mut s = external_clip_session(50, 40, 60, 100); - s.execute("edit.paste", json!({ "center": center })).unwrap(); - assert_eq!(active_bounds(&s), Rect::new(0, 0, 60, 100), "view centre {center:?}"); - } - // Wider but not taller: at the left edge, and wholly inside vertically. - for (center, want) in - [([500.0, 500.0], Rect::new(0, 100, 60, 200)), ([-500.0, -500.0], Rect::new(0, 0, 60, 100)), ([25.0, 120.0], Rect::new(0, 70, 60, 170))] - { - let mut s = external_clip_session(50, 200, 60, 100); - s.execute("edit.paste", json!({ "center": center })).unwrap(); - assert_eq!(active_bounds(&s), want, "view centre {center:?}"); - } - } - - /// Paste Into centres on the selection even where that runs off the canvas. - #[test] - fn paste_into_is_not_clamped_to_the_canvas() { - let mut s = session(); - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 40, "height": 20})).unwrap(); - s.execute("edit.copy", json!({})).unwrap(); - s.execute("select.rect", json!({"x": 90, "y": 90, "width": 10, "height": 10})).unwrap(); - s.execute("edit.pasteSpecial.pasteInto", json!({})).unwrap(); - assert_eq!(active_bounds(&s), Rect::new(75, 85, 115, 105)); - } - - /// The clamp never overflows or panics: NaN, infinite and `i32`-limit shifts saturate (Rule 9). - #[test] - fn paste_offset_clamp_survives_extreme_coordinates() { - assert_eq!(clamp_shift(f64::NAN, 0, 10, 0, 100), 0); - assert_eq!(clamp_shift(f64::INFINITY, 0, 10, 0, 100), 90); - assert_eq!(clamp_shift(f64::NEG_INFINITY, i32::MIN, i32::MAX, 0, 1), i32::MAX); - assert_eq!(clamp_shift(1e30, i32::MIN, i32::MIN + 1, i32::MAX - 1, i32::MAX), i32::MAX); - let clip = Clip { - surface: Surface::new(PixelFormat::RGBA8), - bounds: Rect::new(i32::MAX - 2, i32::MAX - 2, i32::MAX, i32::MAX), - layers: None, - resolution: None, - source: None, - }; - let (dx, dy) = paste_offset(&clip, DocId(1), Rect::new(i32::MIN, i32::MIN, i32::MIN + 4, i32::MIN + 4), &json!({}), false); - assert_eq!((dx, dy), (i32::MIN, i32::MIN), "an unrepresentable shift saturates instead of wrapping"); - } - - #[test] - fn paste_with_malformed_center_does_not_panic() { - // A short/empty `center` array must not panic (Rule 9) — it falls back to the canvas centre. - let mut s = session(); - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); - s.execute("edit.copy", json!({})).unwrap(); - for center in [json!([5]), json!([]), json!("nope"), json!([1, 2, 3])] { - // Fresh clipboard each time is unnecessary; copy persists. Must return Ok, never panic. - assert!(s.execute("edit.paste", json!({ "center": center })).is_ok(), "center={center}"); - } - } - - #[test] - fn copy_paste_between_documents() { - // Copy in one tab, paste into another: the clipboard is shared across documents. - let mut s = session(); // doc A (100x100): red rect at (10,10)-(50,30) - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 40, "height": 20})).unwrap(); - s.execute("edit.copy", json!({})).unwrap(); - // Open a second document (a new tab), which becomes active. - s.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); - assert_eq!(s.active_index().unwrap(), 1, "the new document is the active tab"); - let before = s.active().unwrap().doc.layers.len(); - s.execute("edit.paste", json!({})).unwrap(); - assert_eq!(s.active_index().unwrap(), 1, "paste stays in the second tab"); - let d = &s.active().unwrap().doc; - assert_eq!(d.layers.len(), before + 1, "pasted layer added to the second document"); - let pasted = d.layers.last().unwrap().surface().unwrap(); - let cb = pasted.content_bounds(); - let (cx, cy) = (cb.x0 + cb.width() as i32 / 2, cb.y0 + cb.height() as i32 / 2); - let mut px = [[0.0f32; 4]; 1]; - pasted.read_rgba_into(Rect::new(cx, cy, cx + 1, cy + 1), &mut px); - assert!(px[0][0] > 0.9 && px[0][1] < 0.1 && px[0][2] < 0.1, "pasted content is red: {:?}", px[0]); - } - - /// #2901 (P10/P11): Paste, Paste in Place and Paste Into recomposite only where the pasted - /// layer draws, not the whole document; nothing outside that changes, and undo brings back - /// exactly the old pixels. - #[test] - fn paste_damages_only_the_pasted_layer() { - let render = |s: &Session| photocraft_compose::render(&s.active().unwrap().doc, s.active().unwrap().doc.bounds()); - for depth in [8, 16, 32] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 60, "height": 50, "depth": depth, "background": "white"})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.execute("select.rect", json!({"x": 5, "y": 5, "width": 10, "height": 8})).unwrap(); - s.execute("edit.fill", json!({"color": "#3366cc"})).unwrap(); - s.execute("edit.copy", json!({})).unwrap(); - // Half transparent, so an opaque copy pasted in place over it shows. - s.execute("layer.setProps", json!({"opacity": 0.5})).unwrap(); - for (id, p) in [ - ("edit.paste", json!({"center": [40, 30]})), - ("edit.pasteSpecial.pasteInPlace", json!({})), - ("edit.pasteSpecial.pasteInto", json!({"center": [40, 30]})), - ] { - s.execute("select.rect", json!({"x": 36, "y": 27, "width": 6, "height": 4})).unwrap(); - let shown = render(&s); - s.execute(id, p).unwrap(); - let st = s.active().unwrap(); - let area = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds(); - let damage = st.last_damage.unwrap_or_else(|| panic!("{depth}-bit {id}: bounded damage")); - assert!(!damage.is_empty() && damage.intersect(&area) == damage, "{depth}-bit {id}: {damage:?} within {area:?}"); - let now = render(&s); - assert_ne!(now, shown, "{depth}-bit {id}: the paste shows"); - let w = shown.rect.width() as usize; - for (i, (a, b)) in shown.px.iter().zip(&now.px).enumerate() { - if !damage.contains((i % w) as i32, (i / w) as i32) { - assert_eq!(a, b, "{depth}-bit {id}: pixel {i} outside the damage changed"); - } - } - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(render(&s), shown, "{depth}-bit {id}: undo"); - } - } - } - - /// #1035: a `depth`-bit document with a blue-grey square copied from layer `src` (at - /// (5,5)-(15,15)) and an active layer `m` above it with a hide-all mask. - fn mask_target_session(depth: u32) -> (Session, LayerId, LayerId) { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 40, "height": 40, "depth": depth})).unwrap(); - let src = LayerId(s.execute("layer.new.layer", json!({"name": "src"})).unwrap()["layer"].as_u64().unwrap()); - s.execute("select.rect", json!({"x": 5, "y": 5, "width": 10, "height": 10})).unwrap(); - s.execute("edit.fill", json!({"color": "#3366cc"})).unwrap(); - s.execute("edit.copy", json!({})).unwrap(); - s.execute("select.deselect", json!({})).unwrap(); - let m = LayerId(s.execute("layer.new.layer", json!({"name": "m"})).unwrap()["layer"].as_u64().unwrap()); - s.execute("layer.layerMask.hideAll", json!({})).unwrap(); - (s, src, m) - } - - /// The luminosity of `src`'s pixel at (`x`, `y`): what a paste into a mask writes there. - fn luminosity(s: &Session, src: LayerId, x: i32, y: i32) -> f32 { - let p = s.active().unwrap().doc.layer(src).unwrap().surface().unwrap().rgba(x, y); - photocraft_color::convert::rgb_to_gray([p[0], p[1], p[2]]) - } - - fn mask_at(s: &Session, id: LayerId, x: i32, y: i32) -> f32 { - s.active().unwrap().doc.layer(id).unwrap().mask.as_ref().unwrap().value(x, y) - } - - #[test] - fn paste_into_a_targeted_mask_writes_the_luminosity_in_one_step() { - for depth in [8, 16, 32] { - let (mut s, src, m) = mask_target_session(depth); - let lum = luminosity(&s, src, 10, 10); - assert!(lum > 0.05 && lum < 0.95, "{depth}-bit: a mid grey ({lum})"); - let (layers, steps) = (s.active().unwrap().doc.layer_count(), s.active().unwrap().history.past_len()); - s.execute("edit.pasteSpecial.pasteInPlace", json!({"target": "mask"})).unwrap(); - let st = s.active().unwrap(); - assert_eq!(st.doc.layer_count(), layers, "{depth}-bit: no new layer"); - assert_eq!(st.history.past_len(), steps + 1, "{depth}-bit: one history step"); - assert_eq!(st.active_layer, Some(m)); - assert!((mask_at(&s, m, 10, 10) - lum).abs() < 2.0 / 255.0, "{depth}-bit: {} vs {lum}", mask_at(&s, m, 10, 10)); - assert_eq!(mask_at(&s, m, 20, 20), 0.0, "{depth}-bit: the mask outside the paste is unchanged"); - assert!(st.doc.layer(m).unwrap().surface().unwrap().content_bounds().is_empty(), "{depth}-bit: the pixels are untouched"); - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(mask_at(&s, m, 10, 10), 0.0, "{depth}-bit: undo restores the mask"); - } - } - - #[test] - fn copy_with_the_mask_targeted_takes_the_mask_as_grayscale() { - for depth in [8, 16, 32] { - let (mut s, _, m) = mask_target_session(depth); - s.edit("paint mask", |doc, _| { - doc.layer_mut(m).unwrap().mask.as_mut().unwrap().surface.fill_rect(Rect::new(6, 6, 16, 12), &[0.75]); - Ok(()) - }) - .unwrap(); - let steps = s.active().unwrap().history.past_len(); - let r = s.execute("edit.copy", json!({"target": "mask"})).unwrap(); - assert_eq!(r["bounds"], json!([0, 0, 40, 40]), "{depth}-bit: a mask copies whole, as in Photoshop"); - assert_eq!(s.active().unwrap().history.past_len(), steps, "{depth}-bit: copy adds no history step"); - let clip = s.clipboard.clone().unwrap(); - let px = clip.surface.rgba(10, 10); - assert!((px[0] - 0.75).abs() < 2.0 / 255.0, "{depth}-bit: {} vs 0.75", px[0]); - assert!(clip.surface.rgba(30, 30)[0] < 0.01, "{depth}-bit: the hidden area copies as black"); - assert!(px[3] > 0.99, "{depth}-bit: the copy is opaque"); - // Paste it into another layer's reveal-all mask: it replaces that mask (the request - // in #2928): the square, and the black around it, land. - let m2 = LayerId(s.execute("layer.new.layer", json!({"name": "m2"})).unwrap()["layer"].as_u64().unwrap()); - s.execute("layer.layerMask.revealAll", json!({})).unwrap(); - s.execute("edit.pasteSpecial.pasteInPlace", json!({"target": "mask"})).unwrap(); - assert!((mask_at(&s, m2, 10, 10) - 0.75).abs() < 2.0 / 255.0, "{depth}-bit: the copied mask lands"); - assert!(mask_at(&s, m2, 30, 30) < 0.01, "{depth}-bit: the copied black replaces the reveal-all"); - } - } - - #[test] - fn an_untouched_mask_copies_the_whole_canvas_at_its_default() { - let (mut s, _, _) = mask_target_session(8); - s.execute("layer.layerMask.revealAll", json!({})).unwrap(); - let r = s.execute("edit.copy", json!({"target": "mask"})).unwrap(); - assert_eq!(r["bounds"], json!([0, 0, 40, 40]), "a plain Reveal All mask still transfers"); - assert!(s.clipboard.clone().unwrap().surface.rgba(20, 20)[0] > 0.99); - } - - #[test] - fn mask_copy_takes_only_the_selection() { - let (mut s, _, m) = mask_target_session(8); - s.edit("paint mask", |doc, _| { - doc.layer_mut(m).unwrap().mask.as_mut().unwrap().surface.fill_rect(Rect::new(6, 6, 16, 12), &[0.75]); - Ok(()) - }) - .unwrap(); - s.execute("select.rect", json!({"x": 8, "y": 8, "width": 4, "height": 4})).unwrap(); - let r = s.execute("edit.copy", json!({"target": "mask"})).unwrap(); - assert_eq!(r["bounds"], json!([8, 8, 4, 4])); - let clip = s.clipboard.clone().unwrap(); - assert!((clip.surface.rgba(9, 9)[0] - 0.75).abs() < 2.0 / 255.0); - assert!(clip.surface.rgba(5, 5)[3] < 0.01, "nothing outside the selection"); - } - - #[test] - fn mask_copy_needs_a_mask_and_fails_gracefully() { - let mut s = Session::new(); - assert!(s.execute("edit.copy", json!({"target": "mask"})).is_err(), "no document"); - s.execute("file.new", json!({"width": 20, "height": 20})).unwrap(); - assert!(s.execute("edit.copy", json!({"target": "mask"})).is_err(), "the layer has no mask"); - assert!(s.clipboard.is_none(), "a refused copy leaves the clipboard alone"); - s.execute("layer.layerMask.revealAll", json!({})).unwrap(); - assert!(s.execute("edit.copy", json!({"target": "mask"})).is_ok()); - // An adjustment layer has no pixels of its own: Copy takes the layer whole (#2344), and - // its mask while that is targeted (#2928). - s.execute("file.new", json!({"width": 20, "height": 20})).unwrap(); - let a = s.execute("layer.newAdjustmentLayer.levels", json!({})).unwrap()["layer"].as_u64().unwrap(); - s.execute("layer.select", json!({"layer": a})).unwrap(); - assert!(s.is_enabled("edit.copy"), "the layer itself can be copied"); - s.execute("layer.layerMask.revealAll", json!({})).unwrap(); - assert!(s.is_enabled_with("edit.copy", &json!({"target": "mask"})), "the mask can be copied"); - } - - #[test] - fn a_copied_mask_travels_to_another_document() { - let (mut s, _, m) = mask_target_session(8); - s.edit("paint mask", |doc, _| { - doc.layer_mut(m).unwrap().mask.as_mut().unwrap().surface.fill_rect(Rect::new(6, 6, 16, 12), &[0.75]); - Ok(()) - }) - .unwrap(); - s.execute("edit.copy", json!({"target": "mask"})).unwrap(); - s.execute("file.new", json!({"width": 40, "height": 40})).unwrap(); - let n = LayerId(s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap()); - s.execute("layer.layerMask.revealAll", json!({})).unwrap(); - s.execute("edit.pasteSpecial.pasteInPlace", json!({"target": "mask"})).unwrap(); - assert!((mask_at(&s, n, 10, 10) - 0.75).abs() < 2.0 / 255.0, "the mask arrived in the second document"); - assert!(mask_at(&s, n, 30, 30) < 0.01, "it replaced the reveal-all mask there"); - } - - #[test] - fn paste_follows_the_mask_view_and_is_placed_like_a_paste() { - let (mut s, src, m) = mask_target_session(8); - let lum = luminosity(&s, src, 10, 10); - // ⌥-click the mask thumbnail: the canvas shows the mask, and pasting targets it. - s.execute(crate::mask_view_cmds::ID, json!({"layer": m.0, "mode": "gray"})).unwrap(); - let r = s.execute("edit.paste", json!({"center": [30, 30]})).unwrap(); - assert_eq!(r["offset"], json!([20, 20])); - assert!((mask_at(&s, m, 30, 30) - lum).abs() < 2.0 / 255.0); - assert_eq!(mask_at(&s, m, 10, 10), 0.0); - assert_eq!(s.active().unwrap().doc.layers.len(), 3, "Background, src, m"); - } - - #[test] - fn paste_into_and_outside_a_targeted_mask_keep_to_the_selection() { - let (mut s, src, m) = mask_target_session(16); - let lum = luminosity(&s, src, 10, 10); - // The paste is centred on the selection, so lands in place: only the selection takes it. - s.execute("select.rect", json!({"x": 8, "y": 8, "width": 4, "height": 4})).unwrap(); - s.execute("edit.pasteSpecial.pasteInto", json!({"target": "mask"})).unwrap(); - assert!((mask_at(&s, m, 9, 9) - lum).abs() < 2.0 / 255.0); - assert_eq!(mask_at(&s, m, 7, 7), 0.0, "pasted, but outside the selection"); - assert!(s.active().unwrap().doc.selection.is_none()); - assert_eq!(s.active().unwrap().doc.layers.len(), 3, "no new layer"); - s.execute("layer.layerMask.hideAll", json!({})).unwrap(); - s.execute("select.rect", json!({"x": 8, "y": 8, "width": 4, "height": 4})).unwrap(); - s.execute("edit.pasteSpecial.pasteOutside", json!({"target": "mask"})).unwrap(); - assert_eq!(mask_at(&s, m, 9, 9), 0.0, "Paste Outside leaves the selection alone"); - assert!((mask_at(&s, m, 7, 7) - lum).abs() < 2.0 / 255.0); - } - - #[test] - fn paste_follows_a_targeted_alpha_channel() { - let (mut s, src, _) = mask_target_session(8); - let lum = luminosity(&s, src, 10, 10); - s.execute("channel.new", json!({})).unwrap(); - s.execute("edit.pasteSpecial.pasteInPlace", json!({"target": {"channel": 0}})).unwrap(); - let c = &s.active().unwrap().doc.channels[0].surface; - assert!((c.sample_channel(10, 10, 0) - lum).abs() < 2.0 / 255.0); - assert_eq!(s.active().unwrap().doc.layers.len(), 3, "no new layer"); - } - - #[test] - fn paste_into_a_missing_mask_or_channel_is_an_error() { - let (mut s, _, m) = mask_target_session(8); - s.edit("drop mask", |doc, _| { - doc.layer_mut(m).unwrap().mask = None; - Ok(()) - }) - .unwrap(); - let layers = s.active().unwrap().doc.layer_count(); - for target in [json!("mask"), json!({"channel": 7}), json!("quickMask")] { - for id in ["edit.paste", "edit.pasteSpecial.pasteInPlace"] { - assert!(s.execute(id, json!({ "target": target })).is_err(), "{id} {target}"); - } - } - assert_eq!(s.active().unwrap().doc.layer_count(), layers, "nothing pasted as a layer"); - } - - #[test] - fn paste_between_different_color_modes() { - // Copy from an RGB document, paste into a Grayscale one: the clipboard converts to the - // target document's format (a realistic between-tabs case that must not panic). - let mut s = session(); // RGB, red rect - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 40, "height": 20})).unwrap(); - s.execute("edit.copy", json!({})).unwrap(); - s.execute("file.new", json!({"width": 120, "height": 120, "mode": "gray"})).unwrap(); - s.execute("edit.paste", json!({})).unwrap(); - let d = &s.active().unwrap().doc; - assert_eq!(d.mode, photocraft_doc::ColorMode::Grayscale); - let pasted = d.layers.last().unwrap().surface().unwrap(); - assert_eq!(pasted.format().mode, photocraft_color::ColorMode::Grayscale, "pasted layer is grayscale"); - assert!(!pasted.content_bounds().is_empty(), "pasted content exists"); - } - - #[test] - fn transform_scale_grows_content() { - let mut s = session(); // red rect (10,10)-(50,30): 40x20 - s.execute("edit.transform", json!({"matrix": [2, 0, 0, 2, 0, 0]})).unwrap(); - let d = &s.active().unwrap().doc; - let cb = d.layers.last().unwrap().surface().unwrap().content_bounds(); - // Scaled ~2x about the origin (≈ 80x40 at ≈ (20,20)); allow ~1px bilinear edge bleed. - assert!((cb.x0 - 20).abs() <= 2 && (cb.y0 - 20).abs() <= 2, "origin ~ (20,20): {cb:?}"); - assert!((cb.width() as i32 - 80).abs() <= 3 && (cb.height() as i32 - 40).abs() <= 3, "size ~ 80x40: {cb:?}"); - } - - #[test] - fn cut_and_clear_on_the_background_fill_with_the_background_colour() { - // The Background keeps its transparency lock: cutting fills with the background colour. - let fresh = || { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 40, "height": 30})).unwrap(); - s.tools.background = [1.0, 0.0, 0.0, 1.0]; - s.execute("select.rect", json!({"x": 5, "y": 5, "width": 10, "height": 10})).unwrap(); - s - }; - let px = |s: &Session, i: usize, x: i32, y: i32| s.active().unwrap().doc.layers[i].surface().unwrap().pixel(x, y); - for cmd in ["edit.cut", "edit.clear", "layer.new.layerViaCut"] { - let mut s = fresh(); - s.execute(cmd, json!({})).unwrap(); - let d = &s.active().unwrap().doc; - assert!(d.is_background(d.layers[0].id), "{cmd}: still the Background"); - assert_eq!(px(&s, 0, 8, 8), vec![1.0, 0.0, 0.0, 1.0], "{cmd}: cut area is the background colour"); - assert_eq!(px(&s, 0, 30, 20), vec![1.0, 1.0, 1.0, 1.0], "{cmd}: outside untouched"); - } - // Layer via Cut still lifts the original pixels onto the new layer. - let mut s = fresh(); - s.execute("layer.new.layerViaCut", json!({})).unwrap(); - assert_eq!(px(&s, 1, 8, 8), vec![1.0, 1.0, 1.0, 1.0]); - // Once it's a normal layer, cutting makes transparency again. - let mut s = fresh(); - s.execute("layer.new.layerFromBackground", json!({})).unwrap(); - s.execute("edit.clear", json!({})).unwrap(); - assert_eq!(px(&s, 0, 8, 8)[3], 0.0); - } - - #[test] - fn layer_via_copy_of_a_background_keeps_colour_and_partial_selection() { - // #668: lift reads only the selected area now; the result must be what converting the - // whole layer gave: the colour, with the selection's coverage as alpha. - for depth in [8, 16, 32] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 40, "height": 30, "depth": depth, "background": "#336699"})).unwrap(); - s.edit("partial selection", |doc, _| { - let mut m = photocraft_raster::Surface::new(PixelFormat::GRAY8); - m.fill_rect(Rect::new(5, 5, 15, 15), &[1.0]); - m.fill_rect(Rect::new(15, 5, 20, 15), &[0.5]); - doc.selection = Some(m); - Ok(()) - }) - .unwrap(); - let id = s.execute("layer.new.layerViaCopy", json!({})).unwrap()["layer"].as_u64().unwrap(); - let d = s.active().unwrap(); - let surf = d.doc.layer(LayerId(id)).unwrap().surface().unwrap(); - assert!(surf.format().alpha, "@{depth}"); - let full = surf.read_region(Rect::new(6, 6, 7, 7)); - let half = surf.read_region(Rect::new(16, 6, 17, 7)); - for (got, want) in full.iter().zip([0.2, 0.4, 0.6, 1.0]) { - assert!((got - want).abs() < 0.01, "@{depth}: {full:?}"); - } - assert!((half[3] - 0.5).abs() < 0.01 && (half[0] - 0.2).abs() < 0.01, "@{depth}: {half:?}"); - assert_eq!(surf.content_bounds(), Rect::new(5, 5, 20, 15), "@{depth}"); - } - } - - #[test] - fn cut_clears_and_layer_via_copy_cut() { - let mut s = session(); - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 20})).unwrap(); - s.execute("edit.cut", json!({})).unwrap(); - assert_eq!(active_bounds(&s), Rect::new(20, 10, 50, 30)); - let mut s = session(); - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 20})).unwrap(); - s.execute("layer.new.layerViaCut", json!({})).unwrap(); - assert_eq!(active_bounds(&s), Rect::new(10, 10, 20, 30)); - let d = &s.active().unwrap().doc; - assert_eq!(d.layers[1].surface().unwrap().content_bounds(), Rect::new(20, 10, 50, 30)); - // Without a selection ⌘J duplicates the layer. - let mut s = session(); - s.execute("layer.new.layerViaCopy", json!({})).unwrap(); - let d = &s.active().unwrap().doc; - assert_eq!(d.layers.len(), 3); - assert!(d.layers[2].name.ends_with("copy")); - } - - /// #1096: Layer via Copy and Cut deselect, as Photoshop does, so a following Free Transform - /// moves the whole new layer; one undo brings back both the selection and the old layers. - #[test] - fn layer_via_copy_and_cut_deselect_in_one_step() { - for cmd in ["layer.new.layerViaCopy", "layer.new.layerViaCut"] { - let mut s = session(); - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 20})).unwrap(); - let (layers, steps) = (s.active().unwrap().doc.layers.len(), s.active().unwrap().history.past_len()); - s.execute(cmd, json!({})).unwrap(); - let st = s.active().unwrap(); - assert!(st.doc.selection.is_none(), "{cmd}: deselected"); - assert_eq!((st.doc.layers.len(), st.history.past_len()), (layers + 1, steps + 1), "{cmd}"); - assert!(s.undo()); - let st = s.active().unwrap(); - assert_eq!(st.doc.layers.len(), layers, "{cmd}: undo removes the layer"); - assert!(st.doc.selection.is_some(), "{cmd}: and restores the selection"); - } - } - - /// #2777: with several layers selected and no pixel selection, Layer via Copy (Cmd+J) copies - /// every selected layer in one step, each copy above its original and the copies selected. - /// With a pixel selection it still copies the active layer's selected pixels only. - #[test] - fn layer_via_copy_duplicates_every_selected_layer() { - let mut s = session(); - let a = s.active().unwrap().active_layer.unwrap(); - let b = LayerId(s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap()); - s.execute("layer.select", json!({"layer": a.0})).unwrap(); - s.execute("layer.select", json!({"layer": b.0, "mode": "toggle"})).unwrap(); - let steps = s.active().unwrap().history.past_len(); - s.execute("layer.new.layerViaCopy", json!({})).unwrap(); - let st = s.active().unwrap(); - let ids: Vec = st.doc.layers.iter().map(|l| l.id).collect(); - assert_eq!(ids.len(), 5, "background, a, a copy, b, b copy"); - assert_eq!((ids[1], ids[3]), (a, b), "each copy sits above its original"); - let mut selected = st.selected_layers(); - selected.sort_by_key(|l| l.0); - assert_eq!(selected, vec![ids[2], ids[4]], "the copies become the selection"); - assert_eq!(st.history.past_len(), steps + 1, "one undo step"); - assert!(s.undo()); - s.execute("layer.select", json!({"layer": b.0})).unwrap(); - s.execute("layer.select", json!({"layer": a.0, "mode": "toggle"})).unwrap(); - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); - s.execute("layer.new.layerViaCopy", json!({})).unwrap(); - assert_eq!(s.active().unwrap().doc.layers.len(), 4, "a pixel selection copies one layer's pixels"); - } - - fn active_content(s: &Session) -> LayerContent { - let st = s.active().unwrap(); - st.doc.layer(st.active_layer.unwrap()).unwrap().content.clone() - } - - /// #541, #2428: with no selection, Copy takes a smart object whole and Paste makes a smart - /// object again, with contents of its own; with a selection, the selected pixels paste as - /// pixels. Cut edits pixels, so it's refused; Layer via Copy and Duplicate Layer copy the layer. - #[test] - fn copy_a_smart_object_layer() { - let mut s = session(); - s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - let LayerContent::Smart(original) = active_content(&s) else { panic!("smart object") }; - assert!(s.is_enabled("edit.copy")); - assert_eq!(s.execute("edit.copy", json!({})).unwrap()["bounds"], json!([10, 10, 40, 20]), "no selection: the whole layer"); - s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap(); - let LayerContent::Smart(pasted) = active_content(&s) else { panic!("the paste is a smart object (#2428)") }; - assert_eq!(pasted.source, original.source, "the same contents"); - assert_ne!(pasted.contents_id, original.contents_id, "but not linked to the copied one"); - assert_eq!(active_bounds(&s), Rect::new(10, 10, 50, 30)); - s.execute("edit.paste", json!({"center": [70, 70]})).unwrap(); - assert!(matches!(active_content(&s), LayerContent::Smart(_))); - assert_eq!(active_bounds(&s), Rect::new(50, 60, 90, 80), "placed as pasted pixels are"); - s.undo(); - s.undo(); - assert!(matches!(active_content(&s), LayerContent::Smart(_))); - s.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap(); - assert_eq!(s.execute("edit.copy", json!({})).unwrap()["bounds"], json!([10, 10, 10, 10]), "only the selected part"); - s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap(); - assert!(matches!(active_content(&s), LayerContent::Raster(_)), "a selection copies pixels"); - assert_eq!(active_bounds(&s), Rect::new(10, 10, 20, 20)); - s.undo(); - let cut = s.execute("edit.cut", json!({})).unwrap_err().to_string(); - assert!(cut.contains("not directly editable"), "{cut}"); - assert!(matches!(active_content(&s), LayerContent::Smart(_))); - s.execute("select.deselect", json!({})).unwrap(); - s.execute("layer.new.layerViaCopy", json!({})).unwrap(); - assert!(matches!(active_content(&s), LayerContent::Smart(_)), "⌘J without a selection duplicates the smart object"); - s.execute("layer.duplicate", json!({})).unwrap(); - assert!(matches!(active_content(&s), LayerContent::Smart(_))); - assert_eq!(s.active().unwrap().doc.layers.len(), 4); - } - - /// #2478: with several layers selected and no pixel selection, Copy takes every one of them - /// and Paste recreates them all, in order, as one undo step; with a pixel selection Copy still - /// takes the active layer's selected pixels only. - #[test] - fn copy_and_paste_several_selected_layers() { - let mut s = session(); - let a = s.active().unwrap().active_layer.unwrap(); - let b = LayerId(s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap()); - s.edit("paint", |doc, _| { - doc.layer_mut(b).unwrap().surface_mut().unwrap().fill_rect(Rect::new(60, 60, 80, 90), &[0.0, 0.0, 1.0, 1.0]); - Ok(()) - }) - .unwrap(); - s.execute("layer.select", json!({"layer": a.0})).unwrap(); - s.execute("layer.select", json!({"layer": b.0, "mode": "toggle"})).unwrap(); - assert!(s.is_enabled("edit.copy")); - assert_eq!(s.execute("edit.copy", json!({})).unwrap()["bounds"], json!([10, 10, 70, 80]), "both layers' pixels"); - let before = s.active().unwrap().doc.layers.len(); - let steps = s.active().unwrap().history.past_len(); - s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap(); - let st = s.active().unwrap(); - assert_eq!(st.doc.layers.len(), before + 2, "every selected layer is pasted"); - assert_eq!(st.history.past_len(), steps + 1, "one undo step"); - let n = st.doc.layers.len(); - let (pa, pb) = (st.doc.layers[n - 2].surface().unwrap(), st.doc.layers[n - 1].surface().unwrap()); - assert_eq!(pa.content_bounds(), Rect::new(10, 10, 50, 30), "the lower layer first"); - assert_eq!(pb.content_bounds(), Rect::new(60, 60, 80, 90)); - assert!(s.undo()); - assert_eq!(s.active().unwrap().doc.layers.len(), before); - - // A pixel selection takes the active layer's selected pixels, as a single layer. - s.execute("layer.select", json!({"layer": a.0})).unwrap(); - s.execute("select.rect", json!({"x": 0, "y": 0, "width": 30, "height": 30})).unwrap(); - s.execute("edit.copy", json!({})).unwrap(); - s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap(); - assert_eq!(s.active().unwrap().doc.layers.len(), before + 1); - } - - /// #2478, #3588: several layers copied in one document paste into another, in that document's - /// bit depth and with their own pixels, in order, as one undo step. - #[test] - fn paste_several_layers_into_another_document() { - for depth in [16, 32] { - let mut s = session(); - let a = s.active().unwrap().active_layer.unwrap(); - let b = LayerId(s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap()); - s.edit("paint", |doc, _| { - doc.layer_mut(b).unwrap().surface_mut().unwrap().fill_rect(Rect::new(60, 60, 80, 90), &[0.0, 0.0, 1.0, 1.0]); - Ok(()) - }) - .unwrap(); - s.execute("layer.select", json!({"layer": a.0})).unwrap(); - s.execute("layer.select", json!({"layer": b.0, "mode": "toggle"})).unwrap(); - s.execute("edit.copy", json!({})).unwrap(); - - s.execute("file.new", json!({"width": 120, "height": 120, "depth": depth})).unwrap(); - assert_eq!(s.active_index().unwrap(), 1, "the new document is the active tab"); - let (before, steps) = (s.active().unwrap().doc.layers.len(), s.active().unwrap().history.past_len()); - s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap(); - let st = s.active().unwrap(); - assert_eq!(st.doc.layers.len(), before + 2, "{depth}-bit: both layers arrive"); - assert_eq!(st.history.past_len(), steps + 1, "{depth}-bit: one undo step"); - let n = st.doc.layers.len(); - let (pa, pb) = (st.doc.layers[n - 2].surface().unwrap(), st.doc.layers[n - 1].surface().unwrap()); - assert_eq!(pa.format().sample, st.doc.depth, "{depth}-bit: converted to the target depth"); - assert_eq!(pb.format().sample, st.doc.depth, "{depth}-bit: converted to the target depth"); - assert_eq!(pa.content_bounds(), Rect::new(10, 10, 50, 30), "{depth}-bit: the lower layer first"); - assert_eq!(pb.content_bounds(), Rect::new(60, 60, 80, 90)); - let (mut red, mut blue) = ([[0.0f32; 4]; 1], [[0.0f32; 4]; 1]); - pa.read_rgba_into(Rect::new(20, 20, 21, 21), &mut red); - pb.read_rgba_into(Rect::new(70, 70, 71, 71), &mut blue); - assert!(red[0][0] > 0.9 && red[0][1] < 0.1 && red[0][2] < 0.1, "{depth}-bit: red kept: {:?}", red[0]); - assert!(blue[0][2] > 0.9 && blue[0][0] < 0.1 && blue[0][1] < 0.1, "{depth}-bit: blue kept: {:?}", blue[0]); - assert!(s.undo()); - assert_eq!(s.active().unwrap().doc.layers.len(), before, "{depth}-bit: undo removes both"); - assert_eq!(s.documents().len(), 2, "the source document is untouched"); - } - } - - /// #2478: the Background in a multi-layer copy pastes as an ordinary, unlocked layer. - #[test] - fn copying_the_background_with_another_layer_pastes_an_ordinary_layer() { - let mut s = session(); - let a = s.active().unwrap().active_layer.unwrap(); - let bg = s.active().unwrap().doc.layers[0].id; - s.execute("layer.select", json!({"layer": a.0})).unwrap(); - s.execute("layer.select", json!({"layer": bg.0, "mode": "toggle"})).unwrap(); - s.execute("edit.copy", json!({})).unwrap(); - s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap(); - let st = s.active().unwrap(); - assert_eq!(st.doc.layers.len(), 4); - let pasted = &st.doc.layers[st.doc.layers.len() - 2]; - assert!(!st.doc.is_background(pasted.id)); - assert_eq!(pasted.locks, Default::default()); - assert!(st.doc.is_background(st.doc.layers[0].id), "the real Background is untouched"); - } - - /// #2428: a smart object copied in one document pastes into another as a smart object, in - /// that document's bit depth. - #[test] - fn paste_a_smart_object_into_another_document() { - let mut s = session(); - s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - s.execute("edit.copy", json!({})).unwrap(); - s.execute("file.new", json!({"width": 60, "height": 40, "depth": 16})).unwrap(); - s.execute("edit.paste", json!({})).unwrap(); - let LayerContent::Smart(sm) = active_content(&s) else { panic!("the paste is a smart object") }; - assert_eq!(sm.cache.map(|c| c.format().sample), Some(s.active().unwrap().doc.depth), "converted to 16 bits"); - assert_eq!(active_bounds(&s), Rect::new(10, 10, 50, 30), "on the canvas: in place"); - } - - /// #3584: a PSD-embedded linked smart object (its bytes in the document's `lnk2` block, its - /// source a uuid) can still be opened after Copy + Paste into another document. - #[test] - fn paste_keeps_a_psd_embedded_smart_object_openable() { - use std::sync::Arc; - let mut s = session(); - s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - let outer = s.active().unwrap().active_layer.unwrap(); - s.edit("embedded linked source", |doc, _| { - let LayerContent::Smart(sm) = &mut doc.layer_mut(outer).ok_or(EngineError::NoDocument)?.content else { - return Err(EngineError::Other("not a smart object".into())); - }; - sm.source = photocraft_doc::SmartSource::Linked { path: "uuid-1".into() }; - let linked = photocraft_io::linked::LinkedFile { uuid: "uuid-1".into(), file_name: "in.png".into(), bytes: vec![1, 2, 3, 4] }; - doc.metadata.psd_global_blocks.push((*b"8BIM", *b"lnk2", Arc::new(photocraft_io::linked::encode_linked_file(&linked)))); - Ok(()) - }) - .unwrap(); - s.execute("edit.copy", json!({})).unwrap(); - s.execute("file.new", json!({"width": 40, "height": 30})).unwrap(); - s.execute("edit.paste", json!({})).unwrap(); - let LayerContent::Smart(sm) = active_content(&s) else { panic!("the paste is a smart object") }; - assert!( - crate::smart_cmds::source_bytes(&s.active().unwrap().doc.metadata, &sm.source).is_some(), - "the pasted PSD-embedded linked source must resolve (#3584)" - ); - } - - /// Type and shape layers copy their rendered pixels too; groups and adjustments have none. - #[test] - fn copy_reads_any_layer_that_shows_pixels() { - let mut s = session(); - s.execute("type.create", json!({"text": "Hi", "size": 30, "x": 20, "y": 60})).unwrap(); - assert!(!s.is_enabled("edit.cut")); - assert!(s.execute("edit.copy", json!({})).is_ok()); - s.execute("layer.groupLayers", json!({})).unwrap(); - assert!(s.is_enabled("edit.copy"), "no selection: the group is copied whole (#2670)"); - s.execute("select.all", json!({})).unwrap(); - assert!(!s.is_enabled("edit.copy")); - } - - /// #2670: with no selection, Copy takes a type layer, a shape layer or a group whole and - /// Paste recreates it, into another document too (with fresh ids, in its bit depth); with a - /// selection, Copy takes pixels. - #[test] - fn copy_paste_keeps_type_shape_and_group_layers() { - let mut s = session(); - s.execute("type.create", json!({"text": "Hi", "size": 30, "x": 20, "y": 60})).unwrap(); - s.execute("edit.copy", json!({})).unwrap(); - s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap(); - let LayerContent::Text(t) = active_content(&s) else { panic!("the paste is a type layer") }; - assert_eq!(t.text, "Hi"); - s.execute("select.rect", json!({"x": 0, "y": 0, "width": 100, "height": 100})).unwrap(); - s.execute("edit.copy", json!({})).unwrap(); - s.execute("edit.paste", json!({})).unwrap(); - assert!(matches!(active_content(&s), LayerContent::Raster(_)), "a selection copies pixels"); - s.execute("shape.create", json!({"kind": "rect", "rect": [10, 10, 40, 20], "fill": "#ff0000"})).unwrap(); - s.execute("layer.groupLayers", json!({})).unwrap(); - let LayerContent::Group(src) = active_content(&s) else { panic!("a group") }; - s.execute("edit.copy", json!({})).unwrap(); - s.execute("file.new", json!({"width": 60, "height": 40, "depth": 16})).unwrap(); - s.execute("edit.paste", json!({})).unwrap(); - let LayerContent::Group(g) = active_content(&s) else { panic!("the paste is a group") }; - let [shape] = g.children.as_slice() else { panic!("one child") }; - assert!(matches!(shape.content, LayerContent::Shape(_)), "the shape stays a shape"); - assert_ne!(shape.id, src.children[0].id, "fresh ids"); - assert_eq!(shape.surface().map(|c| c.format().sample), Some(s.active().unwrap().doc.depth), "converted to 16 bits"); - } - - #[test] - fn cross_document_group_paste_renders_shapes_on_destination_canvas() { - for (copy_to_document, depth) in [(false, 8), (true, 16)] { - let mut s = Session::new(); - s.execute("file.new", json!({"width":100,"height":100})).unwrap(); - let mut ids = Vec::new(); - for x in [10, 50] { - s.execute("shape.create", json!({"kind":"rect","rect":[x,20,20,30],"fill":"#ff0000"})).unwrap(); - s.execute("layer.layerStyle.dropShadow", json!({"size":4,"distance":3})).unwrap(); - ids.push(s.active().unwrap().active_layer.unwrap()); - } - s.active_mut().unwrap().selected_layers = ids; - s.execute("layer.groupLayers", json!({})).unwrap(); - s.execute("edit.copy", json!({})).unwrap(); - s.execute("file.new", json!({"width":800,"height":600,"depth":depth})).unwrap(); - if copy_to_document { - s.execute("layer.copyToDocument", json!({"source":0,"document":1,"center":true})).unwrap(); - } else { - s.execute("edit.paste", json!({"center":[400,300]})).unwrap(); - } - let st = s.active().unwrap(); - let group = st.doc.layer(st.active_layer.unwrap()).unwrap(); - assert!(!crate::transform_cmds::transform_bounds(&st.doc, group).is_empty()); - assert_eq!(group.children().unwrap().len(), 2); - for child in group.children().unwrap() { - let LayerContent::Shape(shape) = &child.content else { panic!("shape") }; - let cache = shape.cache.as_ref().unwrap(); - assert_eq!(cache.format().sample, st.doc.depth); - assert!(!cache.content_bounds().is_empty(), "destination cache must not be clipped to source canvas"); - assert!(cache.content_bounds().x0 > 100); - let fresh = photocraft_vector::render_shape(shape, st.doc.pixel_format(), st.doc.bounds()); - assert_eq!(cache, &fresh); - } - let before = st.doc.clone(); - s.execute("layer.translate", json!({"dx":10,"dy":10})).unwrap(); - assert_ne!(s.active().unwrap().doc, before); - assert!(s.undo()); - assert_eq!(s.active().unwrap().doc, before); - } - } - - #[test] - fn paste_repairs_uncached_shapes_before_transform_and_effect_rendering() { - let mut s = session(); - s.execute("shape.create", json!({"kind":"rect","rect":[10,10,40,20],"fill":"#ff0000"})).unwrap(); - s.execute("layer.layerStyle.dropShadow", json!({"size":4,"distance":3})).unwrap(); - s.execute("edit.copy", json!({})).unwrap(); - let layers = s.clipboard.as_mut().unwrap().layers.as_mut().unwrap(); - let LayerContent::Shape(sh) = &mut layers.layers[0].content else { panic!("shape") }; - sh.cache = None; - s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap(); - let st = s.active().unwrap(); - let layer = st.doc.layer(st.active_layer.unwrap()).unwrap(); - let LayerContent::Shape(sh) = &layer.content else { panic!("shape") }; - assert!(sh.cache.is_some()); - assert!(!crate::transform_cmds::transform_bounds(&st.doc, layer).is_empty()); - let expected = photocraft_vector::render_shape(sh, st.doc.pixel_format(), st.doc.bounds()); - assert_eq!(sh.cache.as_ref().unwrap(), &expected); - let rendered = photocraft_compose::render_layer_in(&st.doc, layer, st.doc.bounds()); - let mut fresh_doc = (*st.doc).clone(); - let snapshot = fresh_doc.clone(); - if let LayerContent::Shape(shape) = &mut fresh_doc.layer_mut(layer.id).unwrap().content { - crate::vector_cmds::refresh_shape(&snapshot, shape); - } - let fresh = photocraft_compose::render_layer_in(&fresh_doc, fresh_doc.layer(layer.id).unwrap(), fresh_doc.bounds()); - assert_eq!(rendered.px, fresh.px, "pasted effects match a freshly rebuilt shape"); - assert!(s.undo()); - assert!(s.redo()); - let st = s.active().unwrap(); - assert!(st.doc.layer(st.active_layer.unwrap()).unwrap().surface().is_some()); - } - - /// #2344: fill and adjustment layers have no pixels of their own, so with no selection Copy - /// takes them whole and Paste recreates them, in the same or another document, in one step. - #[test] - fn copy_paste_keeps_fill_and_adjustment_layers() { - for (depth, other) in [(8, 16), (16, 32), (32, 8)] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 60, "height": 40, "depth": depth})).unwrap(); - s.execute("layer.newFillLayer.gradient", json!({"from": "#000000", "to": "#ffffff", "angle": 0})).unwrap(); - let LayerContent::Fill(fill) = active_content(&s) else { panic!("a fill layer") }; - let src = s.active().unwrap().active_layer.unwrap(); - assert!(s.is_enabled("edit.copy"), "{depth}-bit: a fill layer can be copied"); - assert_eq!(s.execute("edit.copy", json!({})).unwrap()["bounds"], json!([0, 0, 60, 40]), "{depth}-bit: what it shows"); - let clip = s.clipboard.clone().unwrap(); - assert!(clip.surface.rgba(59, 20)[0] > clip.surface.rgba(0, 20)[0], "{depth}-bit: the clip holds the gradient's pixels"); - let steps = s.active().unwrap().history.past_len(); - s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap(); - assert_eq!(s.active().unwrap().history.past_len(), steps + 1, "{depth}-bit: one history step"); - assert_eq!(active_content(&s), LayerContent::Fill(fill.clone()), "{depth}-bit: the paste is the same fill layer"); - assert_ne!(s.active().unwrap().active_layer, Some(src), "{depth}-bit: a new layer"); - s.undo(); - assert_eq!(s.active().unwrap().active_layer, Some(src), "{depth}-bit: undo removes the paste"); - s.redo(); - assert!(matches!(active_content(&s), LayerContent::Fill(_)), "{depth}-bit: redo brings it back"); - - s.execute("layer.newAdjustmentLayer.levels", json!({})).unwrap(); - let LayerContent::Adjustment(levels) = active_content(&s) else { panic!("an adjustment layer") }; - assert_eq!(s.execute("edit.copy", json!({})).unwrap()["bounds"], json!([0, 0, 60, 40]), "{depth}-bit: it applies to the canvas"); - s.execute("file.new", json!({"width": 30, "height": 30, "depth": other})).unwrap(); - s.execute("edit.paste", json!({})).unwrap(); - assert_eq!(active_content(&s), LayerContent::Adjustment(levels), "{depth}-bit: the same Levels layer in the {other}-bit document"); - assert_eq!(s.active().unwrap().doc.layers.len(), 2, "{depth}-bit: pasted above the Background"); - } - } - - /// #2344: several adjustment layers, which show nothing alone, still copy and paste together. - #[test] - fn several_adjustment_layers_copy_together() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 40, "height": 40})).unwrap(); - let a = s.execute("layer.newAdjustmentLayer.levels", json!({})).unwrap()["layer"].as_u64().unwrap(); - let b = s.execute("layer.newAdjustmentLayer.levels", json!({})).unwrap()["layer"].as_u64().unwrap(); - s.execute("layer.select", json!({"layer": a})).unwrap(); - s.execute("layer.select", json!({"layer": b, "mode": "toggle"})).unwrap(); - assert_eq!(s.execute("edit.copy", json!({})).unwrap()["bounds"], json!([0, 0, 40, 40])); - s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap(); - let d = &s.active().unwrap().doc; - assert_eq!(d.layers.len(), 5, "both are pasted"); - assert!(d.layers[3..].iter().all(|l| matches!(l.content, LayerContent::Adjustment(_)))); - } - - #[test] - fn merge_visible_keeps_hidden_layers() { - let mut s = session(); - s.execute("layer.new.layer", json!({})).unwrap(); - let hidden = s.active().unwrap().active_layer.unwrap(); - s.execute("layer.setProps", json!({"layer": hidden.0, "visible": false})).unwrap(); - s.execute("layer.mergeVisible", json!({})).unwrap(); - let d = &s.active().unwrap().doc; - assert_eq!(d.layers.len(), 2); - assert_eq!(d.layers[0].name, "Background"); - assert_eq!(d.layers[1].id, hidden); - assert_eq!(d.layers[0].surface().unwrap().pixel(20, 20)[..3], [1.0, 0.0, 0.0]); - } - - #[test] - fn auto_tone_stretches_a_low_contrast_layer() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); - s.edit("grey ramp", |doc, _| { - let surf = doc.layers[0].surface_mut().unwrap(); - for x in 0..64 { - let v = 0.3 + 0.4 * x as f32 / 63.0; - surf.fill_rect(Rect::new(x, 0, x + 1, 64), &[v, v * 0.9, v * 0.8, 1.0]); - } - Ok(()) - }) - .unwrap(); - for cmd in ["image.autoTone", "image.autoContrast", "image.autoColor"] { - s.execute(cmd, json!({})).unwrap(); - let d = &s.active().unwrap().doc; - let (a, b) = (d.layers[0].surface().unwrap().pixel(0, 0), d.layers[0].surface().unwrap().pixel(63, 0)); - // Auto Contrast keeps colour (shared points): only the extreme channels reach 0 and 1. - let (lo, hi) = if cmd == "image.autoContrast" { (a[2], b[0]) } else { (a[0], b[0]) }; - assert!(lo < 0.05 && hi > 0.95, "{cmd}: {a:?} {b:?}"); - s.undo(); - } - } - - /// #352: ⌥⇧⌘T steps and repeats: each press adds a copy one transform further on, and each - /// is one undo step. - #[test] - fn transform_again_on_a_copy_steps_and_repeats() { - let mut s = session(); - assert!(s.execute("edit.transform.againCopy", json!({})).is_err(), "nothing to repeat yet"); - assert_eq!(s.active().unwrap().doc.layers.len(), 2, "a refusal leaves no copy"); - s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 10, 0]})).unwrap(); - let steps = s.active().unwrap().history.past_len(); - for (i, x) in [30, 40].into_iter().enumerate() { - s.execute("edit.transform.againCopy", json!({})).unwrap(); - let d = &s.active().unwrap().doc; - assert_eq!(d.layers.len(), 3 + i); - assert_eq!(active_bounds(&s), Rect::new(x, 10, x + 40, 30), "the copy moved one step further"); - assert_eq!(s.active().unwrap().history.past_len(), steps + 1 + i, "one history step per press"); - } - assert_eq!(s.active().unwrap().history.undo_label(), Some("Transform Again")); - // The original and the first copy stay where they were. - let d = &s.active().unwrap().doc; - let b = |i: usize| d.layers[i].surface().unwrap().content_bounds(); - assert_eq!((b(1), b(2)), (Rect::new(20, 10, 60, 30), Rect::new(30, 10, 70, 30))); - // Undo removes the copy and its move together. - s.undo(); - assert_eq!(s.active().unwrap().doc.layers.len(), 3); - assert_eq!(active_bounds(&s), Rect::new(30, 10, 70, 30)); - // A copy that can't move (position locked) is taken back. - let id = s.active().unwrap().active_layer.unwrap(); - s.execute("layer.setProps", json!({"layer": id.0, "locks": {"position": true}})).unwrap(); - let layers = s.active().unwrap().doc.layers.len(); - assert!(s.execute("edit.transform.againCopy", json!({})).unwrap_err().to_string().contains("locked")); - assert_eq!(s.active().unwrap().doc.layers.len(), layers); - assert!(!s.active().unwrap().history.can_redo(), "nothing to redo"); - } - - #[test] - fn toggle_last_state_and_transform_again() { - let mut s = session(); - s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 10, 0]})).unwrap(); - s.execute("edit.transform.again", json!({})).unwrap(); - assert_eq!(active_bounds(&s), Rect::new(30, 10, 70, 30)); - s.execute("edit.toggleLastState", json!({})).unwrap(); - assert_eq!(active_bounds(&s), Rect::new(20, 10, 60, 30)); - s.execute("edit.toggleLastState", json!({})).unwrap(); - assert_eq!(active_bounds(&s), Rect::new(30, 10, 70, 30)); - } - - #[test] - fn guides_are_undoable() { - let mut s = session(); - s.execute("view.newGuide", json!({"orientation": "vertical", "position": 40})).unwrap(); - s.execute("view.newGuide", json!({"orientation": "horizontal", "position": 12.5})).unwrap(); - s.execute("view.moveGuide", json!({"orientation": "vertical", "index": 0, "position": 60})).unwrap(); - let g = &s.active().unwrap().doc.guides; - assert_eq!((g.vertical.clone(), g.horizontal.clone()), (vec![60.0], vec![12.5])); - s.execute("view.deleteGuide", json!({"orientation": "horizontal", "index": 0})).unwrap(); - s.undo(); - assert_eq!(s.active().unwrap().doc.guides.horizontal, vec![12.5]); - s.execute("view.clearGuides", json!({})).unwrap(); - assert!(s.active().unwrap().doc.guides.vertical.is_empty()); - assert!(s.execute("view.moveGuide", json!({"orientation": "vertical", "index": 3, "position": 1})).is_err()); - } - - /// #2955: the rulers' zero point is set and reset by command, undoable, and bad params are - /// refused without touching the document. - #[test] - fn ruler_origin_is_set_reset_and_undoable() { - let mut s = session(); - assert_eq!(s.active().unwrap().doc.ruler_origin, [0.0, 0.0]); - assert_eq!(s.execute("view.setRulerOrigin", json!({"x": 40, "y": 12.5})).unwrap(), json!({"x": 40.0, "y": 12.5})); - assert_eq!(s.active().unwrap().doc.ruler_origin, [40.0, 12.5]); - s.execute("view.resetRulerOrigin", json!({})).unwrap(); - assert_eq!(s.active().unwrap().doc.ruler_origin, [0.0, 0.0]); - s.undo(); - assert_eq!(s.active().unwrap().doc.ruler_origin, [40.0, 12.5]); - for bad in [json!({}), json!({"x": 1}), json!({"x": "a", "y": 2}), json!({"x": 1e300, "y": 0}), json!({"x": -2e7, "y": 0}), json!(null), json!([1, 2])] - { - assert!(s.execute("view.setRulerOrigin", bad.clone()).is_err(), "{bad} is refused"); - } - assert_eq!(s.active().unwrap().doc.ruler_origin, [40.0, 12.5]); - let mut empty = Session::new(); - assert!(empty.execute("view.setRulerOrigin", json!({"x": 1, "y": 2})).is_err()); - assert!(empty.execute("view.resetRulerOrigin", json!({})).is_err()); - } - - /// The last guide added in `orientation` for `position`. - fn new_guide(s: &mut Session, orientation: &str, position: Value) -> f64 { - s.execute("view.newGuide", json!({"orientation": orientation, "position": position})).unwrap(); - let g = &s.active().unwrap().doc.guides; - *if orientation == "vertical" { &g.vertical } else { &g.horizontal }.last().unwrap() - } - - #[test] - fn guide_positions_take_photoshop_units() { - let mut s = Session::new(); - // 4 × 2 inches at 100 ppi. - s.execute("file.new", json!({"width": 400, "height": 200, "resolution": 100})).unwrap(); - // Percent follows the guide's own axis: the width for a vertical guide, the height for a horizontal one. - assert_eq!(new_guide(&mut s, "vertical", json!("50%")), 200.0); - assert_eq!(new_guide(&mut s, "horizontal", json!("50%")), 100.0); - for one_inch in ["1in", "1 in", "2.54cm", "25.4 mm", "72pt", "6pc", "100px", "100", "1,0 inch"] { - assert!((new_guide(&mut s, "vertical", json!(one_inch)) - 100.0).abs() < 1e-3, "{one_inch}"); - } - // Fractional and negative positions are kept; a plain number is pixels, as before. - assert_eq!(new_guide(&mut s, "horizontal", json!("12.5px")), 12.5); - assert_eq!(new_guide(&mut s, "vertical", json!("-10px")), -10.0); - assert_eq!(new_guide(&mut s, "vertical", json!(40)), 40.0); - // Points and picas follow Units & Rulers › Point Size. - s.execute("prefs.set", json!({"path": "unitsAndRulers.pointSize", "value": "traditional"})).unwrap(); - assert!((new_guide(&mut s, "vertical", json!("72.27pt")) - 100.0).abs() < 1e-3); - // A guide moved with a unit lands where a new one would. - s.execute("view.moveGuide", json!({"orientation": "horizontal", "index": 0, "position": "25%"})).unwrap(); - assert_eq!(s.active().unwrap().doc.guides.horizontal[0], 50.0); - } - - #[test] - fn new_guides_keep_their_own_colour_through_moves_deletes_and_undo() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 400, "height": 200})).unwrap(); - let color = |s: &Session, vertical: bool, p: f64| s.active().unwrap().doc.guides.color(vertical, p); - // Without a colour a guide uses the preference colour, as ruler-drag guides always did. - s.execute("view.newGuide", json!({"orientation": "vertical", "position": 10})).unwrap(); - assert_eq!(color(&s, true, 10.0), None); - assert!(s.active().unwrap().doc.guides.colors.is_empty()); - s.execute("view.newGuide", json!({"orientation": "vertical", "position": 20, "color": "magenta"})).unwrap(); - s.execute("view.newGuide", json!({"orientation": "horizontal", "position": 20, "color": "#123456"})).unwrap(); - s.execute("view.newGuide", json!({"orientation": "vertical", "position": 30, "color": "LightBlue"})).unwrap(); - assert_eq!(color(&s, true, 20.0), Some([0xff, 0x00, 0xff])); - assert_eq!(color(&s, false, 20.0), Some([0x12, 0x34, 0x56]), "the same position across is a different guide"); - assert_eq!(color(&s, true, 30.0), Some([0x33, 0x66, 0xff]), "names are case-insensitive"); - // Moving takes the colour along. - s.execute("view.moveGuide", json!({"orientation": "vertical", "index": 1, "position": 25})).unwrap(); - assert_eq!((color(&s, true, 20.0), color(&s, true, 25.0)), (None, Some([0xff, 0x00, 0xff]))); - // Undo restores it where it was. - s.undo(); - assert_eq!((color(&s, true, 20.0), color(&s, true, 25.0)), (Some([0xff, 0x00, 0xff]), None)); - // Deleting drops it; clearing drops them all. - s.execute("view.deleteGuide", json!({"orientation": "vertical", "index": 2})).unwrap(); - assert_eq!(color(&s, true, 30.0), None); - assert_eq!(s.active().unwrap().doc.guides.colors.len(), 2); - s.execute("view.clearGuides", json!({})).unwrap(); - assert!(s.active().unwrap().doc.guides.colors.is_empty()); - } - - #[test] - fn moving_one_of_two_coloured_guides_at_one_position_leaves_the_other_its_colour() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 400, "height": 200})).unwrap(); - for _ in 0..2 { - s.execute("view.newGuide", json!({"orientation": "vertical", "position": 50, "color": "green"})).unwrap(); - } - s.execute("view.moveGuide", json!({"orientation": "vertical", "index": 0, "position": 60})).unwrap(); - let g = &s.active().unwrap().doc.guides; - assert_eq!((g.color(true, 50.0), g.color(true, 60.0)), (Some([0x33, 0xff, 0x33]), Some([0x33, 0xff, 0x33]))); - } - - #[test] - fn cyan_is_the_default_guide_colour_so_ruler_guides_read_as_cyan() { - let default = crate::prefs::Preferences::default().guides_grid_and_slices.guide_color; - let cyan = GUIDE_COLORS.iter().find(|(name, ..)| *name == "cyan").map(|(.., rgb)| *rgb); - assert_eq!(cyan, crate::prefs::parse_hex(&default)); - } - - #[test] - fn bad_guide_colours_are_refused_without_a_guide() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 400, "height": 200})).unwrap(); - let undo_before = s.active().unwrap().history.can_undo(); - for bad in [json!("puce"), json!("#12345"), json!("#gggggg"), json!(""), json!(7), json!(null), json!(["cyan"])] { - assert!(s.execute("view.newGuide", json!({"orientation": "vertical", "position": 10, "color": bad.clone()})).is_err(), "{bad}"); - } - let g = &s.active().unwrap().doc.guides; - assert!(g.vertical.is_empty() && g.colors.is_empty()); - assert_eq!(s.active().unwrap().history.can_undo(), undo_before); - } - - #[test] - fn editing_a_guide_changes_what_is_given_in_one_undoable_step() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 400, "height": 200})).unwrap(); - s.execute("view.newGuide", json!({"orientation": "vertical", "position": 10})).unwrap(); - s.execute("view.newGuide", json!({"orientation": "vertical", "position": 20, "color": "magenta"})).unwrap(); - s.execute("view.newGuide", json!({"orientation": "vertical", "position": 30})).unwrap(); - let guides = |s: &Session| s.active().unwrap().doc.guides.clone(); - // Position only: the guide keeps its index and its own colour. - s.execute("view.editGuide", json!({"orientation": "vertical", "index": 1, "position": "50%"})).unwrap(); - let g = guides(&s); - assert_eq!(g.vertical, vec![10.0, 200.0, 30.0]); - assert_eq!((g.color(true, 20.0), g.color(true, 200.0)), (None, Some([0xff, 0x00, 0xff]))); - // Colour only: an uncoloured guide gets one; the position stays. - s.execute("view.editGuide", json!({"orientation": "vertical", "index": 0, "color": "#123456"})).unwrap(); - assert_eq!(guides(&s).color(true, 10.0), Some([0x12, 0x34, 0x56])); - // Turning it: % is of the new orientation's extent, and the colour goes along. - s.execute("view.editGuide", json!({"orientation": "vertical", "index": 1, "newOrientation": "horizontal", "position": "25%"})).unwrap(); - let g = guides(&s); - assert_eq!((g.vertical.clone(), g.horizontal.clone()), (vec![10.0, 30.0], vec![50.0])); - assert_eq!((g.color(true, 200.0), g.color(false, 50.0)), (None, Some([0xff, 0x00, 0xff]))); - // One step each: undo restores the vertical guide with its colour. - s.undo(); - let g = guides(&s); - assert_eq!((g.vertical.clone(), g.horizontal.is_empty()), (vec![10.0, 200.0, 30.0], true)); - assert_eq!(g.color(true, 200.0), Some([0xff, 0x00, 0xff])); - } - - #[test] - fn bad_guide_edits_are_refused_without_a_history_step() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 400, "height": 200})).unwrap(); - s.execute("view.newGuide", json!({"orientation": "vertical", "position": 10, "color": "green"})).unwrap(); - let before = s.active().unwrap().doc.guides.clone(); - for bad in [ - json!({}), - json!({"orientation": "vertical"}), - json!({"orientation": "vertical", "index": 1}), - json!({"orientation": "horizontal", "index": 0}), - json!({"orientation": "vertical", "index": -1}), - json!({"orientation": "vertical", "index": "0"}), - json!({"orientation": "vertical", "index": u64::MAX}), - json!({"orientation": "diagonal", "index": 0}), - json!({"orientation": "vertical", "index": 0, "newOrientation": 3}), - json!({"orientation": "vertical", "index": 0, "position": "far"}), - json!({"orientation": "vertical", "index": 0, "position": 1e12}), - json!({"orientation": "vertical", "index": 0, "color": "puce"}), - ] { - assert!(s.execute("view.editGuide", bad.clone()).is_err(), "{bad}"); - } - assert_eq!(s.active().unwrap().doc.guides, before); - assert_eq!(s.active().unwrap().history.undo_label(), Some("New Guide")); - } - - #[test] - fn bad_guide_positions_are_refused_without_a_guide() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 400, "height": 200, "resolution": 100})).unwrap(); - let undo_before = s.active().unwrap().history.can_undo(); - for bad in [ - json!("abc"), - json!("50 furlongs"), - json!(""), - json!("%"), - json!("NaN"), - json!("inf"), - json!("1e400"), - json!("2000000px"), - json!(1e300), - json!(true), - json!([1]), - ] { - assert!(s.execute("view.newGuide", json!({"orientation": "vertical", "position": bad.clone()})).is_err(), "{bad}"); - } - assert!(s.execute("view.newGuide", json!({"orientation": "vertical"})).is_err(), "no position"); - let g = &s.active().unwrap().doc.guides; - assert!(g.vertical.is_empty() && g.horizontal.is_empty()); - assert_eq!(s.active().unwrap().history.can_undo(), undo_before, "a refused guide records no history step"); - } - - /// Guides keep their exact place (#2918): 1 cm at 300 ppi through New Guide and .pcraft, and - /// a 1/32 px PSD position past 2^19 px, where f32 has no 1/32 steps left. - #[test] - fn guides_keep_sub_pixel_positions_through_pcraft_and_psd() { - let (cm, far) = (300.0 / 2.54, 600_000.031_25); - let mut s = session(); - s.execute("view.newGuide", json!({"orientation": "horizontal", "position": cm})).unwrap(); - s.execute("view.newGuide", json!({"orientation": "vertical", "position": far})).unwrap(); - fn wide(v: impl Into) -> f64 { - v.into() - } - let exact = |g: &photocraft_doc::Guides| (wide(g.horizontal[0]), wide(g.vertical[0])); - let doc = &s.active().unwrap().doc; - assert_eq!(exact(&doc.guides), (cm, far)); - let pcraft = photocraft_format::save_to_bytes(doc, &Default::default()).unwrap(); - assert_eq!(exact(&photocraft_format::load_from_bytes(&pcraft).unwrap().guides), (cm, far)); - let psd = photocraft_io::export(doc, "psd", &Default::default()).unwrap().bytes; - let back = photocraft_io::import("g.psd", &psd).unwrap().document.guides; - assert_eq!(wide(back.vertical[0]), far, "1032 stores 1/32 px"); - } - - /// `lift` as it was before #4516: the whole area through one `f32` buffer. The oracle for - /// the tiled version. - fn lift_reference(src: &Surface, sel: Option<&Surface>, canvas: Rect) -> Clip { - let fmt = src.format(); - let with_alpha = PixelFormat::new(fmt.mode, fmt.sample, true); - let area = match sel { - Some(m) => m.content_bounds().intersect(&canvas), - None => src.content_bounds().intersect(&canvas), - }; - let mut out = Surface::new(with_alpha); - if area.is_empty() { - return Clip { surface: out, bounds: Rect::EMPTY, layers: None, resolution: None, source: None }; - } - let px = lift_region(src, sel, area, with_alpha.channels()).unwrap(); - out.try_write_region(area, &px).unwrap(); - out.prune(); - let bounds = out.content_bounds(); - Clip { surface: out, bounds, layers: None, resolution: None, source: None } - } - - fn noise(fmt: PixelFormat, r: Rect, seed: u32) -> Surface { - let mut s = Surface::new(fmt); - let n = r.width() as usize * r.height() as usize * fmt.channels(); - let data: Vec = (0..n as u32) - .map(|i| { - let mut h = seed.wrapping_mul(0x9e37_79b9) ^ i.wrapping_mul(0x85eb_ca6b); - h ^= h >> 13; - h = h.wrapping_mul(0xc2b2_ae35); - (h >> 16) as f32 / 65535.0 - }) - .collect(); - s.write_region(r, &data); - s - } - - fn assert_same_clip(a: &Clip, b: &Clip, what: &str) { - assert_eq!(a.bounds, b.bounds, "{what}: bounds"); - assert_eq!(a.surface.format(), b.surface.format(), "{what}: format"); - let r = a.bounds.union(&b.bounds); - if !r.is_empty() { - let (pa, pb) = (a.surface.read_region(r), b.surface.read_region(r)); - assert!(pa.iter().zip(&pb).all(|(x, y)| x.to_bits() == y.to_bits()), "{what}: pixels differ"); - } - } - - /// The tiled `lift` gives exactly the old result (#4516): with and without alpha, at every - /// depth, with no selection, Select All, a partial feathered selection and a selection off - /// the tile grid, and for content reaching past the canvas. - #[test] - fn tiled_lift_matches_the_whole_area_lift() { - use photocraft_color::{ColorMode, SampleType}; - let canvas = Rect::new(0, 0, 700, 600); - for sample in [SampleType::U8, SampleType::U16, SampleType::F32] { - for alpha in [true, false] { - let fmt = PixelFormat::new(ColorMode::Rgb, sample, alpha); - let src = noise(fmt, Rect::new(-40, -30, 760, 640), 7); - let mut all = Surface::new(PixelFormat::GRAY8); - all.fill_rect(canvas, &[1.0]); - let mut partial = Surface::new(PixelFormat::GRAY8); - partial.fill_rect(Rect::new(100, 50, 600, 550), &[1.0]); - partial.write_region(Rect::new(90, 40, 610, 50), &vec![0.5; 520 * 10]); - let off_grid = noise(PixelFormat::GRAY8, Rect::new(13, 270, 333, 290), 9); - for (name, sel) in [("no selection", None), ("select all", Some(&all)), ("partial", Some(&partial)), ("off grid", Some(&off_grid))] { - let what = format!("{sample:?} alpha {alpha} {name}"); - let new = lift(&src, sel, canvas).unwrap(); - assert_same_clip(&new, &lift_reference(&src, sel, canvas), &what); - } - } - } - } - - /// Copy shares the layer's whole tiles instead of copying them. - #[test] - fn copy_shares_whole_tiles_with_the_layer() { - let src = noise(PixelFormat::RGBA8, Rect::new(0, 0, 1024, 768), 3); - let canvas = Rect::new(0, 0, 1024, 768); - let mut all = Surface::new(PixelFormat::GRAY8); - all.fill_rect(canvas, &[1.0]); - for sel in [None, Some(&all)] { - let clip = lift(&src, sel, canvas).unwrap(); - let shared = src.tiles().filter(|(c, t)| clip.surface.tile(**c).is_some_and(|o| std::sync::Arc::ptr_eq(o, t))).count(); - assert_eq!(shared, src.tile_count(), "every tile is shared"); - } - } -} diff --git a/crates/engine/src/edit_menu_cmds.rs b/crates/engine/src/edit_menu_cmds.rs deleted file mode 100644 index 0ef173d242..0000000000 --- a/crates/engine/src/edit_menu_cmds.rs +++ /dev/null @@ -1,1606 +0,0 @@ -//! The rest of Photoshop's Edit menu: Fade, Purge, Content-Aware Fill and Scale, Define Brush -//! Preset / Custom Shape, Find and Replace Text, the Preset Manager and preset export/import. -//! Auto-Align and Auto-Blend Layers live in [`crate::align_cmds`]. -//! -//! Check Spelling is not implemented: it needs a word list per language, and no permissively -//! licensed dictionary small enough to bundle (or a pure-Rust checker with one) was available. - -use photocraft_color::{BlendMode, PixelFormat}; -use photocraft_doc::vector::Path; -use photocraft_doc::{DocId, Document, Layer, LayerContent, LayerId}; -use photocraft_geom::Rect; -use photocraft_raster::{Surface, from_rgba_into, to_rgba}; -use serde::{Deserialize, Serialize}; -use serde_json::{Value, json}; - -use crate::channel_cmds::Target; -use crate::commands::{CommandSpec, blend_from_str, int, layer_param}; -use crate::{EngineError, Result, Session}; - -// ------------------------------------------------------------------ state - -/// What Edit › Fade would fade: the result of the last filter, adjustment or paint command. -#[derive(Clone, Debug, PartialEq)] -pub struct FadeSource { - pub doc: DocId, - /// Document revision right after the command; any later change disables Fade. - pub revision: u64, - pub target: FadeTarget, - pub label: String, -} - -/// What the faded command changed, and so what Fade blends back. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum FadeTarget { - /// A layer's pixels. - Pixels(LayerId), - /// A layer's layer mask. - Mask(LayerId), - /// An alpha or spot channel (index into [`Document::channels`]). - Channel(usize), - /// The Quick Mask. - QuickMask, -} - -/// A custom shape (Edit › Define Custom Shape), usable by the Custom Shape tool. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct CustomShape { - pub name: String, - pub path: Path, -} - -/// Edit-menu state kept by the session. -#[derive(Clone, Debug, Default)] -pub struct EditState { - pub fade: Option, - /// Custom shape library (the vector tools read it). - pub custom_shapes: Vec, - /// Find and Replace Text position: (layer, byte offset after the current match). - pub find_cursor: Option<(LayerId, usize, usize)>, -} - -/// Commands whose result Edit › Fade can blend back against the previous state. -fn fadeable(id: &str) -> bool { - id.starts_with("filter.") - || id.starts_with("image.adjustments.") - || id.starts_with("paint.") - || matches!(id, "edit.fill" | "edit.stroke" | "edit.contentAwareFill" | "image.autoTone" | "image.autoContrast" | "image.autoColor") -} - -/// Called after every successful command: remember a fadeable result. -pub(crate) fn after_command(s: &mut Session, id: &str, params: &Value) { - if !fadeable(id) { - return; - } - let Some(st) = s.active() else { return }; - let label = st.history.undo_label().unwrap_or(id).to_string(); - // An alpha channel or the Quick Mask took the edit instead of the layer when the command ran - // on it (#7382): its explicit `target`, or the one the Channels panel gave it. Only commands - // routed to channels edit them; the others edit the layer whatever `target` says. - let run = crate::channel_cmds::inject_target(s, id, params.clone()); - let channel = match crate::channel_cmds::target_of(&run) { - _ if !crate::channel_cmds::routed(id) => None, - Target::Alpha(i) if i < st.doc.channels.len() => Some(FadeTarget::Channel(i)), - Target::QuickMask if st.doc.quick_mask.is_some() => Some(FadeTarget::QuickMask), - _ => None, - }; - if let Some(target) = channel { - s.edit_state.fade = Some(FadeSource { doc: st.doc.id, revision: st.revision, target, label }); - return; - } - let Some(layer) = st.active_layer else { return }; - let mask = st.doc.layer(layer).is_some_and(|l| l.mask.is_some()) - && st.history.state(st.history.past_len().wrapping_sub(1)).is_some_and(|prev| { - // The mask changed and the pixels didn't: the command painted the mask. - let now = st.doc.layer(layer); - let was = prev.layer(layer); - let surf_eq = |a: Option<&Surface>, b: Option<&Surface>| match (a, b) { - (Some(a), Some(b)) => a.format() == b.format() && a.default_pixel() == b.default_pixel() && crate_fingerprint(a) == crate_fingerprint(b), - (None, None) => true, - _ => false, - }; - surf_eq(now.and_then(|l| l.surface()), was.and_then(|l| l.surface())) - && !surf_eq(now.and_then(|l| l.mask.as_ref().map(|m| &m.surface)), was.and_then(|l| l.mask.as_ref().map(|m| &m.surface))) - }); - let target = if mask { FadeTarget::Mask(layer) } else { FadeTarget::Pixels(layer) }; - s.edit_state.fade = Some(FadeSource { doc: st.doc.id, revision: st.revision, target, label }); -} - -/// Tile identity of a surface (pointer equality of its COW tiles). -fn crate_fingerprint(s: &Surface) -> u64 { - s.tiles().fold(s.tile_count() as u64, |h, (c, t)| { - (h ^ std::sync::Arc::as_ptr(t) as usize as u64 ^ ((c.tx as u64) << 32 | c.ty as u32 as u64)).wrapping_mul(0x100_0000_01b3) - }) -} - -// ------------------------------------------------------------------ helpers - -fn bad(cmd: &str, msg: impl Into) -> EngineError { - EngineError::BadParams { cmd: cmd.into(), msg: msg.into() } -} - -fn f32_or(p: &Value, k: &str, d: f32) -> f32 { - p.get(k).and_then(Value::as_f64).map_or(d, |v| v as f32) -} - -fn str_or<'a>(p: &'a Value, k: &str, d: &'a str) -> &'a str { - p.get(k).and_then(Value::as_str).unwrap_or(d) -} - -fn bool_or(p: &Value, k: &str, d: bool) -> bool { - p.get(k).and_then(Value::as_bool).unwrap_or(d) -} - -fn always(_: &Session) -> std::result::Result<(), String> { - Ok(()) -} - -fn pixel_layer(s: &Session) -> std::result::Result { - let d = s.active().ok_or("no document open")?; - let id = d.active_layer.ok_or("no active layer")?; - pixel_layer_id(s, id) -} - -/// `id` if it is an unlocked pixel layer of the active document. -fn pixel_layer_id(s: &Session, id: LayerId) -> std::result::Result { - let d = s.active().ok_or("no document open")?; - let l = d.doc.layer(id).ok_or("no active layer")?; - if !matches!(l.content, LayerContent::Raster(_)) { - return Err(format!("active layer is {} {} layer, not a pixel layer", l.content.article(), l.content.kind_name())); - } - let locks = d.doc.effective_locks(id); - if locks.all || locks.pixels { - return Err(format!("the layer \"{}\" is locked", l.name)); - } - Ok(id) -} - -fn writable_surface(doc: &mut Document, id: LayerId) -> Result<&mut Surface> { - let locks = doc.effective_locks(id); - let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; - if locks.all || locks.pixels { - return Err(EngineError::Other(format!("Could not complete your request because the layer \"{}\" is locked", l.name))); - } - l.surface_mut().ok_or_else(|| EngineError::Other("not a pixel layer".into())) -} - -// ------------------------------------------------------------------ Fade - -fn can_fade(s: &Session) -> std::result::Result<(), String> { - let st = s.active().ok_or("no document open")?; - let f = s.edit_state.fade.as_ref().ok_or("nothing to fade")?; - if f.doc != st.doc.id || f.revision != st.revision || !st.history.can_undo() { - return Err("Fade is only available right after a filter, adjustment or painting step".into()); - } - if surface_of(&st.doc, f.target).is_none() { - return Err(match f.target { - FadeTarget::Pixels(_) | FadeTarget::Mask(_) => "the faded layer no longer exists".into(), - FadeTarget::Channel(_) | FadeTarget::QuickMask => "the faded channel no longer exists".into(), - }); - } - Ok(()) -} - -fn surface_of(doc: &Document, target: FadeTarget) -> Option<&Surface> { - match target { - FadeTarget::Pixels(id) => doc.layer(id)?.surface(), - FadeTarget::Mask(id) => doc.layer(id)?.mask.as_ref().map(|m| &m.surface), - FadeTarget::Channel(i) => doc.channels.get(i).map(|c| &c.surface), - FadeTarget::QuickMask => doc.quick_mask.as_ref().map(|c| &c.surface), - } -} - -fn surface_of_mut(doc: &mut Document, target: FadeTarget) -> Option<&mut Surface> { - match target { - FadeTarget::Pixels(id) => doc.layer_mut(id)?.surface_mut(), - FadeTarget::Mask(id) => doc.layer_mut(id)?.mask.as_mut().map(|m| &mut m.surface), - FadeTarget::Channel(i) => doc.channels.get_mut(i).map(|c| &mut c.surface), - FadeTarget::QuickMask => doc.quick_mask.as_mut().map(|c| &mut c.surface), - } -} - -/// Blend `after` back towards `before` over `area`: `before + opacity × (B(before, after) − before)` -/// with blend mode `mode` (premultiplied, so alpha changes fade too). -pub fn fade_surface(before: &Surface, after: &mut Surface, area: Rect, mode: BlendMode, opacity: f32) -> Result<()> { - let fmt = after.format(); - let n = fmt.channels(); - if area.is_empty() || n == 0 { - return Ok(()); - } - let b = crate::allocation::read_region(before, area, "fading pixels")?; - let mut a = crate::allocation::read_region(after, area, "fading pixels")?; - let k = opacity.clamp(0.0, 1.0); - let lerp_premul = |pb: &[f32], pa: &[f32], out: &mut [f32], alpha: bool| { - let m = out.len(); - if !alpha { - for c in 0..m { - out[c] = pb[c] + (pa[c] - pb[c]) * k; - } - return; - } - let (ab, aa) = (pb[m - 1], pa[m - 1]); - let ao = ab + (aa - ab) * k; - for c in 0..m - 1 { - let pm = pb[c] * ab + (pa[c] * aa - pb[c] * ab) * k; - out[c] = if ao > 1e-9 { pm / ao } else { 0.0 }; - } - out[m - 1] = ao; - }; - let mut tmp = crate::allocation::filled(n, 0.0f32, "fading pixels")?; - for (pa, pb) in a.chunks_exact_mut(n).zip(b.chunks_exact(n)) { - if mode == BlendMode::Normal || n == 1 { - lerp_premul(pb, pa, &mut tmp, fmt.alpha); - pa.copy_from_slice(&tmp); - } else { - let rb = to_rgba(&fmt, pb); - let ra = to_rgba(&fmt, pa); - let blended = photocraft_color::blend::composite(mode, rb, ra, 1.0); - let mut o = [0.0f32; 4]; - lerp_premul(&rb, &blended, &mut o, true); - let mut enc = [0.0f32; 8]; - from_rgba_into(&fmt, o, &mut enc); - pa.copy_from_slice(&enc[..n]); - } - } - after.try_write_region(area, &a)?; - Ok(()) -} - -fn fade(s: &mut Session, p: &Value) -> Result { - let cmd = "edit.fade"; - let src = s.edit_state.fade.clone().ok_or_else(|| bad(cmd, "nothing to fade"))?; - let opacity = f32_or(p, "opacity", 100.0).clamp(0.0, 100.0) / 100.0; - let mode = blend_from_str(str_or(p, "mode", "normal")).ok_or_else(|| bad(cmd, "unknown blend mode"))?; - let st = s.active().ok_or(EngineError::NoDocument)?; - let prev = st.history.past_len().checked_sub(1).and_then(|i| st.history.state(i)).ok_or_else(|| bad(cmd, "no previous state"))?; - let before = surface_of(&prev, src.target).cloned().ok_or_else(|| EngineError::Other("the layer or channel did not exist before this step".into()))?; - let now = surface_of(&st.doc, src.target).ok_or_else(|| EngineError::Other("the faded layer or channel no longer exists".into()))?; - if now.format() != before.format() { - return Err(EngineError::Other("can't fade a step that changed the layer's pixel format".into())); - } - // A uniform mask can change every pixel without storing a single tile. In that case - // the content bounds are empty, but Fade must still blend across the canvas. - let area = if before.default_pixel() != now.default_pixel() { st.doc.bounds() } else { before.content_bounds().union(&now.content_bounds()) }; - let label = format!("Fade {}", src.label); - s.edit(&label, |doc, _| { - let surf = surface_of_mut(doc, src.target).ok_or_else(|| EngineError::Other("the faded layer or channel no longer exists".into()))?; - fade_surface(&before, surf, area, mode, opacity)?; - surf.prune(); - Ok(()) - })?; - Ok(json!({"faded": src.label, "opacity": opacity * 100.0, "mode": mode.label()})) -} - -// ------------------------------------------------------------------ Purge - -fn history_bytes(s: &Session, all: bool) -> usize { - let docs: Vec<&crate::DocState> = if all { s.documents().iter().collect() } else { s.active().into_iter().collect() }; - // Purge keeps the snapshots, so the tiles they share with the states aren't freed. - docs.iter() - .map(|d| { - let snaps: Vec<&photocraft_doc::Document> = d.snapshots.iter().map(|s| &*s.doc).collect(); - d.history.unique_bytes_besides(&d.doc, &snaps) - }) - .sum() -} - -fn clip_bytes(s: &Session) -> usize { - s.clipboard.as_ref().map_or(0, |c| c.surface.tiles().map(|(_, t)| t.bytes().len()).sum()) -} - -fn purge(s: &mut Session, what: &str) -> Result { - let mut freed = 0usize; - let mut items: Vec<&str> = Vec::new(); - if matches!(what, "undo" | "all") && s.active().is_some_and(|d| d.history.can_undo()) { - let before = history_bytes(s, false); - if let Some(st) = s.active_mut() { - st.history.purge_last(); - } - freed += before.saturating_sub(history_bytes(s, false)); - items.push("undo"); - } - if matches!(what, "clipboard" | "all") && (s.clipboard.is_some() || s.style_clipboard.is_some()) { - freed += clip_bytes(s); - s.clipboard = None; - s.style_clipboard = None; - items.push("clipboard"); - } - if matches!(what, "histories" | "all") { - let b = history_bytes(s, true); - if s.documents().iter().any(|d| d.history.can_undo() || d.history.can_redo()) { - for st in &mut s.docs { - st.history.clear(); - st.coalesce = None; - } - freed += b; - items.push("histories"); - } - } - if what == "all" { - let fx = photocraft_compose::purge_effect_cache(); - if fx > 0 { - freed += fx; - items.push("effect cache"); - } - let masks = photocraft_compose::masks::purge_cache(); - if masks > 0 { - freed = freed.saturating_add(masks); - items.push("mask cache"); - } - let stages = crate::smart_cmds::purge_stack_cache(); - if stages > 0 { - freed = freed.saturating_add(stages); - items.push("smart filter cache"); - } - let strokes = photocraft_compose::shape_split::purge_cache(); - if strokes > 0 { - freed = freed.saturating_add(strokes); - items.push("shape stroke cache"); - } - } - s.edit_state.fade = None; - let msg = if items.is_empty() { "nothing to purge".to_string() } else { format!("purged {}", items.join(", ")) }; - Ok(json!({"purged": items, "bytes": freed, "message": msg})) -} - -fn can_purge_undo(s: &Session) -> std::result::Result<(), String> { - s.active().filter(|d| d.history.can_undo()).map(|_| ()).ok_or_else(|| "nothing to purge".into()) -} -fn can_purge_clipboard(s: &Session) -> std::result::Result<(), String> { - if s.clipboard.is_some() || s.style_clipboard.is_some() { Ok(()) } else { Err("the clipboard is empty".into()) } -} -fn can_purge_histories(s: &Session) -> std::result::Result<(), String> { - if s.documents().iter().any(|d| d.history.can_undo() || d.history.can_redo()) { Ok(()) } else { Err("no history to purge".into()) } -} -fn can_purge_all(s: &Session) -> std::result::Result<(), String> { - can_purge_histories(s).or_else(|_| can_purge_clipboard(s)).or_else(|_| { - if photocraft_compose::effect_cache_bytes() > 0 || photocraft_compose::masks::cache_bytes() > 0 || crate::smart_cmds::stack_cache_bytes() > 0 { - Ok(()) - } else { - Err("nothing to purge".into()) - } - }) -} - -// ------------------------------------------------------------------ Content-Aware Fill - -fn can_caf(s: &Session) -> std::result::Result<(), String> { - pixel_layer(s)?; - let d = s.active().ok_or("no document open")?; - if d.doc.selection.as_ref().is_none_or(|m| m.content_bounds().is_empty()) { - return Err("make a selection around what to remove".into()); - } - Ok(()) -} - -/// Mask surface (gray) of an alpha channel by index or name. -pub(crate) fn channel_mask<'a>(doc: &'a Document, v: &Value) -> Option<&'a Surface> { - match v { - Value::Number(n) => doc.channels.get(n.as_u64()? as usize).map(|c| &c.surface), - Value::String(name) => doc.channels.iter().find(|c| c.name == *name).map(|c| &c.surface), - _ => None, - } -} - -/// `key` as an `[x, y, w, h]` rectangle. The saturating float→int casts bound each component; -/// the additions saturate too — `area: [1e30, 0, 1e30, 10]` is a whole-canvas window, not an -/// overflow (it panicked in debug builds before the `saturating_add`). -fn rect_param(p: &Value, key: &str, cmd: &str) -> Result { - let a = p.get(key).and_then(Value::as_array).ok_or_else(|| bad(cmd, format!("`{key}` must be [x, y, w, h]")))?; - let n = |i: usize| { - a.get(i) - .and_then(Value::as_f64) - .filter(|f| f.is_finite()) - .map(|v| v.round() as i32) - .ok_or_else(|| bad(cmd, format!("`{key}` must be four finite numbers"))) - }; - let (x, y, w, h) = (n(0)?, n(1)?, n(2)?, n(3)?); - Ok(Rect::new(x, y, x.saturating_add(w.max(0)), y.saturating_add(h.max(0)))) -} - -fn content_aware_fill(s: &mut Session, p: &Value) -> Result { - content_aware_fill_as(s, p, "edit.contentAwareFill", "Content-Aware Fill") -} - -/// Delete and Fill Selection (#1286): Photoshop's one-click removal from the selection-tool -/// context menu. Content-Aware Fill into the layer, no dialog, sampling as Edit › Fill does (the -/// whole window, measured on Photoshop 25.4) with the default colour adaptation. -fn delete_and_fill(s: &mut Session, _: &Value) -> Result { - content_aware_fill_as(s, &json!({"sampling": "rectangular"}), "edit.deleteAndFillSelection", "Delete and Fill Selection") -} - -/// Everything one Content-Aware Fill needs, worked out from the document and the command's -/// params. The Content-Aware Fill workspace runs exactly this for its preview, so what it shows -/// is what OK and Apply write. -pub struct CafPlan { - pub layer: LayerId, - /// The rectangle worked on: the sampling window, and any sampling-brush strokes or custom - /// area beyond it. - pub rect: Rect, - /// Photoshop's sampling window around the fill area (`content_aware::sampling_window`). - pub window: Rect, - pub fmt: PixelFormat, - /// What is sampled over `rect`: the target's pixels, or with Sample All Layers the visible - /// composite in the target's encoding. - pub img: Vec, - /// The target's own pixels over `rect` when they differ from `img` (Sample All Layers); see - /// [`CafPlan::layer_pixels`]. - pub layer_px: Option>, - /// The fill area (selection coverage, after the workspace's lasso edits) over `rect`. - pub cover: Vec, - pub hole: Vec, - /// What may be copied from: the sampling option's area before the brush strokes, and after. - pub base: Vec, - pub source: Vec, - pub opts: photocraft_algo::content_aware::FillOptions, - pub output: String, -} - -impl CafPlan { - /// The target layer's pixels over `rect`. - pub fn layer_pixels(&self) -> &[f32] { - self.layer_px.as_deref().unwrap_or(&self.img) - } -} - -/// The workspace's lasso edits of the fill area: `{"op": "new|add|subtract|intersect", "points": -/// [[x, y], ...]}` or `{"op": "expand|contract", "by": px}`, applied in order. -#[derive(Clone, Debug, PartialEq)] -pub enum FillEdit { - Lasso { op: SelOp, points: Vec<[f64; 2]> }, - Grow(i32), -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum SelOp { - New, - Add, - Subtract, - Intersect, -} - -/// Most `fillEdits` and `samplingStrokes` one fill takes, and most points in all of them -/// together: the strokes and lassos are painted pixel by pixel, segment by segment. -pub const MAX_CAF_EDITS: usize = 1_000; -pub const MAX_CAF_POINTS: usize = 200_000; - -fn points_param(v: &Value, cmd: &str, what: &str, budget: &mut usize) -> Result> { - let a = v.get("points").and_then(Value::as_array).ok_or_else(|| bad(cmd, format!("{what} needs `points` [[x, y], ...]")))?; - *budget = budget.checked_sub(a.len()).ok_or_else(|| bad(cmd, format!("at most {MAX_CAF_POINTS} points in all fill edits and sampling strokes")))?; - a.iter() - .map(|p| { - let x = p.get(0).and_then(Value::as_f64).filter(|v| v.is_finite() && v.abs() < 1e7); - let y = p.get(1).and_then(Value::as_f64).filter(|v| v.is_finite() && v.abs() < 1e7); - match (x, y) { - (Some(x), Some(y)) => Ok([x, y]), - _ => Err(bad(cmd, format!("{what} points must be pairs of finite numbers"))), - } - }) - .collect() -} - -/// `p[key]` as an array of at most [`MAX_CAF_EDITS`] entries (empty when absent). -fn edits_param<'a>(p: &'a Value, key: &str, cmd: &str) -> Result<&'a [Value]> { - let Some(a) = p.get(key) else { return Ok(&[]) }; - let a = a.as_array().ok_or_else(|| bad(cmd, format!("`{key}` must be an array")))?; - if a.len() > MAX_CAF_EDITS { - return Err(bad(cmd, format!("`{key}` takes at most {MAX_CAF_EDITS} entries"))); - } - Ok(a) -} - -fn fill_edits(p: &Value, cmd: &str, budget: &mut usize) -> Result> { - edits_param(p, "fillEdits", cmd)? - .iter() - .map(|e| { - let op = e.get("op").and_then(Value::as_str).unwrap_or(""); - Ok(match op { - "expand" | "contract" => { - let by = e - .get("by") - .and_then(Value::as_f64) - .filter(|v| v.is_finite() && (0.0..=1000.0).contains(v)) - .ok_or_else(|| bad(cmd, "`by` must be 0..1000 px"))?; - FillEdit::Grow(if op == "expand" { by.round() as i32 } else { -(by.round() as i32) }) - } - "new" | "add" | "subtract" | "intersect" => FillEdit::Lasso { - op: match op { - "new" => SelOp::New, - "add" => SelOp::Add, - "subtract" => SelOp::Subtract, - _ => SelOp::Intersect, - }, - points: points_param(e, cmd, "a lasso edit", budget)?, - }, - o => return Err(bad(cmd, format!("unknown fill edit `{o}` (new|add|subtract|intersect|expand|contract)"))), - }) - }) - .collect() -} - -fn sampling_strokes(p: &Value, cmd: &str, budget: &mut usize) -> Result> { - edits_param(p, "samplingStrokes", cmd)? - .iter() - .map(|e| { - let add = match e.get("mode").and_then(Value::as_str).unwrap_or("add") { - "add" => true, - "subtract" => false, - o => return Err(bad(cmd, format!("unknown stroke mode `{o}` (add|subtract)"))), - }; - let size = e - .get("size") - .and_then(Value::as_f64) - .filter(|v| v.is_finite() && (1.0..=5000.0).contains(v)) - .ok_or_else(|| bad(cmd, "a stroke's `size` must be 1..5000 px"))?; - Ok(photocraft_algo::content_aware::SamplingStroke { add, size, points: points_param(e, cmd, "a sampling stroke", budget)? }) - }) - .collect() -} - -/// A Content-Aware Fill's params, checked against the document before any pixel is read. -struct CafParams<'a> { - sel: &'a Surface, - /// The selection's bounds on the canvas. - sb: Rect, - edits: Vec, - strokes: Vec, - sampling: String, - custom_mask: Option<&'a Surface>, - custom_rect: Option, - opts: photocraft_algo::content_aware::FillOptions, - output: String, - surf: &'a Surface, -} - -fn caf_params<'a>(doc: &'a Document, id: LayerId, p: &Value, cmd: &str) -> Result> { - use photocraft_algo::content_aware::{FillOptions, color_level, rotation_level}; - let sel = doc.selection.as_ref().ok_or_else(|| bad(cmd, "no selection"))?; - let sb = sel.content_bounds().intersect(&doc.bounds()); - if sb.is_empty() { - return Err(bad(cmd, "the selection is outside the canvas")); - } - let mut budget = MAX_CAF_POINTS; - let edits = fill_edits(p, cmd, &mut budget)?; - let strokes = sampling_strokes(p, cmd, &mut budget)?; - let sampling = str_or(p, "sampling", "auto").to_string(); - let custom_mask: Option<&Surface> = p.get("channel").and_then(|v| channel_mask(doc, v)); - let custom_rect = if p.get("area").is_some() { Some(rect_param(p, "area", cmd)?) } else { None }; - match sampling.as_str() { - "auto" | "rectangular" => {} - // The workspace's Custom: only what the Sampling Brush adds. - "custom" if custom_rect.is_some() || custom_mask.is_some() || strokes.iter().any(|s| s.add) => {} - "custom" => return Err(bad(cmd, "custom sampling needs `area` [x,y,w,h], `channel` (alpha channel index or name) or `samplingStrokes`")), - other => return Err(bad(cmd, format!("unknown sampling `{other}` (auto|rectangular|custom)"))), - } - let opts = FillOptions { - color_adaptation: color_level(str_or(p, "colorAdaptation", "default")), - rotations: rotation_level(str_or(p, "rotationAdaptation", "none")), - scale: bool_or(p, "scale", false), - mirror: bool_or(p, "mirror", false), - seed: p.get("seed").and_then(Value::as_u64).unwrap_or(1), - }; - let output = str_or(p, "output", "current").to_string(); - if !matches!(output.as_str(), "current" | "new" | "duplicate") { - return Err(bad(cmd, "`output` must be current|new|duplicate")); - } - let surf = doc.layer(id).and_then(|l| l.surface()).ok_or(EngineError::NoLayer(id))?; - Ok(CafParams { sel, sb, edits, strokes, sampling, custom_mask, custom_rect, opts, output, surf }) -} - -/// Work out a Content-Aware Fill (see [`CafPlan`]) on layer `id` of `doc`. -pub fn content_aware_plan(doc: &Document, id: LayerId, p: &Value, cmd: &str) -> Result { - content_aware_plan_with(doc, id, p, cmd, &photocraft_raster::Interrupt::NONE) -} - -/// [`content_aware_plan`], asking `ctl` row by row whether to stop ([`EngineError::Cancelled`]). -pub fn content_aware_plan_with(doc: &Document, id: LayerId, p: &Value, cmd: &str, ctl: &photocraft_raster::Interrupt) -> Result { - use photocraft_algo::content_aware::{auto_sampling_with, grow_mask, paint_strokes, polygon_mask}; - use rayon::prelude::*; - - use crate::fill_cmds::{read_window, read_window_mask}; - let CafParams { sel, sb, edits, strokes, sampling, custom_mask, custom_rect, opts, output, surf } = caf_params(doc, id, p, cmd)?; - let canvas = doc.bounds(); - let cancel = || ctl.cancelled(); - let stop = || if ctl.cancelled() { Err(EngineError::Cancelled) } else { Ok(()) }; - // The fill area: the selection, then the lasso edits, over a rectangle that holds them all. - let grow: i32 = edits.iter().map(|e| if let FillEdit::Grow(b) = e { b.max(&0) } else { &0 }).sum(); - let reach = edits.iter().fold(sb, |r, e| match e { - FillEdit::Lasso { points, .. } => { - points.iter().fold(r, |r, q| r.union(&Rect::new(q[0].floor() as i32, q[1].floor() as i32, q[0].floor() as i32 + 1, q[1].floor() as i32 + 1))) - } - FillEdit::Grow(_) => r, - }); - let er = reach.inflate(grow.saturating_add(1)).intersect(&canvas); - let (ew, eh) = crate::fill_cmds::window_size(er)?; - let ecover = read_window_mask(sel, er, &cancel).ok_or(EngineError::Cancelled)?; - let mut ehole: Vec = ecover.par_iter().map(|c| *c > 0.0).collect(); - for e in &edits { - stop()?; - match e { - FillEdit::Lasso { op, points } => { - let m = polygon_mask(er, points); - for (h, v) in ehole.iter_mut().zip(&m) { - *h = match op { - SelOp::New => *v, - SelOp::Add => *h || *v, - SelOp::Subtract => *h && !*v, - SelOp::Intersect => *h && *v, - }; - } - } - FillEdit::Grow(by) => ehole = grow_mask(&ehole, ew, eh, *by), - } - } - let (bx0, by0, bx1, by1) = mask_bounds(ew, eh, &ehole); - if bx1 <= bx0 { - return Err(bad(cmd, "the fill area is empty")); - } - let hb = Rect::new(er.x0 + bx0 as i32, er.y0 + by0 as i32, er.x0 + bx1 as i32, er.y0 + by1 as i32); - // Photoshop's window (`content_aware::sampling_window`) for Auto and Rectangular; `margin` - // asks for a rectangle that far around the fill area instead. - let window = match sampling.as_str() { - "rectangular" => match int(p, "margin") { - Some(m) => hb.inflate(m.clamp(0, 100_000) as i32), - None => crate::fill_cmds::sampling_window(hb, canvas), - }, - "custom" => match (custom_rect, custom_mask) { - (Some(r), _) => r, - (None, Some(m)) => m.content_bounds(), - (None, None) => hb, - } - .union(&hb) - .inflate(4), - _ => crate::fill_cmds::sampling_window(hb, canvas), - } - .intersect(&canvas); - // Strokes that add to the sampling area may reach past the window. - let rect = strokes.iter().filter(|s| s.add).fold(window, |r, s| r.union(&s.bounds())).intersect(&canvas); - let fmt = surf.format(); - // Photoshop's Sample All Layers checkbox is off unless the caller asks. When the active - // layer has no pixels in the window there is nothing to sample, so that case uses the - // visible composite (#4026). An explicit false still reads only this layer. - let sample_all = match p.get("sampleAllLayers").and_then(Value::as_bool) { - Some(v) => v, - None => surf.content_bounds().intersect(&window).is_empty(), - }; - let n = fmt.channels(); - // Refuse a window too large to read before allocating for it, whatever the sampling (#963). - let (w, h) = crate::fill_cmds::window_size(rect)?; - let pixels = read_window(surf, rect, &cancel).ok_or(EngineError::Cancelled)?; - let (img, layer_px) = if sample_all { - stop()?; - (crate::retouch_cmds::composite_region(doc, Some(id), crate::retouch_cmds::SampleLayers::All, rect, fmt).data, Some(pixels)) - } else { - (pixels, None) - }; - stop()?; - let mut cover = vec![0.0f32; w * h]; - let mut hole = vec![false; w * h]; - cover.par_chunks_mut(w.max(1)).zip(hole.par_chunks_mut(w.max(1))).enumerate().try_for_each(|(y, (crow, hrow))| { - stop()?; - let dy = rect.y0 + y as i32; - if dy < er.y0 || dy >= er.y1 { - return Ok(()); - } - for (x, (c, hl)) in crow.iter_mut().zip(hrow.iter_mut()).enumerate() { - let dx = rect.x0 + x as i32; - if dx >= er.x0 && dx < er.x1 { - let j = (dy - er.y0) as usize * ew + (dx - er.x0) as usize; - let (eh, ec) = (ehole.get(j).copied().unwrap_or(false), ecover.get(j).copied().unwrap_or(0.0)); - *hl = eh; - // Pixels the lasso added are filled outright; selected ones by their coverage. - *c = if eh { if ec > 0.0 { ec } else { 1.0 } } else { 0.0 }; - } - } - Ok::<(), EngineError>(()) - })?; - drop((ecover, ehole)); - // The sampling option's area: Auto keeps what looks like the surroundings within the window, - // Rectangular the whole window, Custom the given area (or nothing, for the brush to add to). - let mut base = vec![false; w * h]; - match sampling.as_str() { - "auto" | "rectangular" => { - let (ww, wh) = (window.width() as usize, window.height() as usize); - let (ox, oy) = ((window.x0 - rect.x0) as usize, (window.y0 - rect.y0) as usize); - let area: Vec = match sampling.as_str() { - "auto" if window == rect => auto_sampling_with(w, h, n, &img, &hole, ctl).map_err(|_| EngineError::Cancelled)?, - "auto" => { - let mut wimg = vec![0.0f32; ww * wh * n]; - let mut whole = vec![false; ww * wh]; - for y in 0..wh { - let s = ((oy + y) * w + ox) * n; - wimg[y * ww * n..(y + 1) * ww * n].copy_from_slice(&img[s..s + ww * n]); - whole[y * ww..(y + 1) * ww].copy_from_slice(&hole[(oy + y) * w + ox..(oy + y) * w + ox + ww]); - } - auto_sampling_with(ww, wh, n, &wimg, &whole, ctl).map_err(|_| EngineError::Cancelled)? - } - _ => vec![true; ww * wh], - }; - for y in 0..wh { - base[(oy + y) * w + ox..(oy + y) * w + ox + ww].copy_from_slice(&area[y * ww..(y + 1) * ww]); - } - } - _ => match (custom_rect, custom_mask) { - (Some(r), _) => base.par_iter_mut().enumerate().for_each(|(i, b)| *b = r.contains(rect.x0 + (i % w) as i32, rect.y0 + (i / w) as i32)), - (None, Some(m)) => { - let v = read_window_mask(m, rect, &cancel).ok_or(EngineError::Cancelled)?; - base.par_iter_mut().zip(&v).for_each(|(b, v)| *b = *v > 0.5); - } - (None, None) => {} - }, - } - stop()?; - base.par_iter_mut().zip(&hole).for_each(|(b, h)| *b &= !*h); - let mut source = base.clone(); - paint_strokes(&mut source, rect, &strokes); - source.par_iter_mut().zip(&hole).for_each(|(s, h)| *s &= !*h); - Ok(CafPlan { layer: id, rect, window, fmt, img, layer_px, cover, hole, base, source, opts, output }) -} - -fn content_aware_fill_as(s: &mut Session, p: &Value, cmd: &'static str, label: &'static str) -> Result { - use photocraft_algo::content_aware::fill_owned; - // The workspace names the layer it opened on: after an Apply to a new layer that one is - // active, but the fill still samples the original. - let id = match p.get("layer").and_then(Value::as_u64) { - Some(l) => pixel_layer_id(s, LayerId(l)), - None => pixel_layer(s), - } - .map_err(EngineError::Other)?; - let st = s.active().ok_or(EngineError::NoDocument)?; - let doc = st.doc.clone(); - // Check the params before the job starts. - caf_params(&doc, id, p, cmd)?; - let p = p.clone(); - // A background job when started with `Session::start` (#210): working out the fill area and - // the sampling area, reading the pixels and the PatchMatch fill run on a worker against the - // document snapshot, cancellable per row band. - crate::jobs::run( - s, - label, - true, - move |ctx| { - use rayon::prelude::*; - ctx.progress(0.0, label); - let cancel = || ctx.cancelled(); - let plan = content_aware_plan_with(&doc, id, &p, cmd, &photocraft_raster::Interrupt::cancel_only(&cancel))?; - let CafPlan { layer, rect, fmt, img, layer_px, cover, hole, source, opts, output, .. } = plan; - // Patches come only from the sampling area outside the fill area. With none (a - // Rectangular `margin` of 0, a Custom area inside the selection or off the canvas) - // the fill would be black (#6532), so refuse instead. The workspace's preview builds - // the same plan and may show an empty area while the Sampling Brush adds to it. - if !source.iter().any(|s| *s) { - return Err(bad(cmd, "nothing to sample from: the sampling area has no pixels outside the fill area")); - } - let (w, h) = (rect.width() as usize, rect.height() as usize); - let n = fmt.channels(); - // The fill changes only the fill area: keep the layer's pixels and the coverage over - // its bounds for the apply step, and fill the sampled pixels themselves. - let (bx0, by0, bx1, by1) = mask_bounds(w, h, &hole); - let own = layer_px.as_deref().unwrap_or(&img); - let original: Vec = (by0..by1).flat_map(|y| own[(y * w + bx0) * n..(y * w + bx1) * n].iter().copied()).collect(); - let cover: Vec = (by0..by1).flat_map(|y| cover[y * w + bx0..y * w + bx1].iter().copied()).collect(); - let n_hole = cover.iter().filter(|c| **c > 0.0).count(); - ctx.check()?; - let mut filled = ctx.stage(0.05, 1.0, label, |ctl| fill_owned(w, h, n, img, &hole, &source, &opts, ctl)).map_err(|_| EngineError::Cancelled)?; - // Sampled from all layers: outside the fill area the window keeps the layer's pixels. - if let Some(own) = layer_px { - filled.par_chunks_mut(n.max(1)).zip(own.par_chunks(n.max(1))).zip(hole.par_iter()).for_each(|((f, o), h)| { - if !*h { - f.copy_from_slice(o); - } - }); - } - Ok((layer, rect, fmt, output, FilledWindow { filled, bounds: (bx0, by0, bx1, by1), original, cover, n_hole })) - }, - move |s, (layer, rect, fmt, output, done)| apply_content_aware_fill(s, label, layer, &output, fmt, rect, done), - ) -} - -/// A Content-Aware Fill's result for its apply step: the filled window (the same as the -/// original outside the selected pixels) and, over the bounds of the selected pixels (in window -/// coordinates), the original pixels and the selection's coverage. -struct FilledWindow { - filled: Vec, - bounds: (usize, usize, usize, usize), - original: Vec, - cover: Vec, - n_hole: usize, -} - -/// `f(window index, index over the bounds, coverage)` for each selected pixel of a -/// [`FilledWindow`] (`w` wide). -fn each_selected(w: usize, (bx0, by0, bx1, by1): (usize, usize, usize, usize), cover: &[f32], mut f: impl FnMut(usize, usize, f32)) { - let bw = bx1.saturating_sub(bx0); - for y in by0..by1 { - for x in bx0..bx1 { - let k = (y - by0) * bw + (x - bx0); - if let Some(&c) = cover.get(k) - && c > 0.0 - { - f(y * w + x, k, c); - } - } - } -} - -/// Bounds `(x0, y0, x1, y1)` of the set cells of a `w × h` mask (all zero when there are none). -fn mask_bounds(w: usize, h: usize, m: &[bool]) -> (usize, usize, usize, usize) { - use rayon::prelude::*; - if w == 0 { - return (0, 0, 0, 0); - } - let rows: Vec> = - m.par_chunks(w).take(h).map(|row| Some((row.iter().position(|v| *v)?, row.iter().rposition(|v| *v)? + 1))).collect(); - let mut b: Option<(usize, usize, usize, usize)> = None; - for (y, span) in rows.into_iter().enumerate() { - if let Some((x0, x1)) = span { - b = Some(b.map_or((x0, y, x1, y + 1), |(bx0, by0, bx1, _)| (bx0.min(x0), by0, bx1.max(x1), y + 1))); - } - } - b.unwrap_or((0, 0, 0, 0)) -} - -/// Write a Content-Aware Fill result (the job's apply step): into the layer, a new layer or a -/// duplicate, as one undo step. -fn apply_content_aware_fill(s: &mut Session, label: &str, id: LayerId, output: &str, fmt: PixelFormat, window: Rect, done: FilledWindow) -> Result { - let n = fmt.channels(); - let (w, h) = (window.width() as usize, window.height() as usize); - let FilledWindow { mut filled, bounds, original, cover, n_hole } = done; - let layer = s.edit(label, |doc, active| { - let target = match output { - "new" => { - let mut l = Layer::raster(doc.next_layer_name("Content-Aware Fill"), PixelFormat { alpha: true, ..fmt }); - let mut px = vec![0.0f32; w * h * n.max(1)]; - let lf = l.surface().map(|s| s.format()).unwrap_or(fmt); - let ln = lf.channels(); - px.resize(w * h * ln, 0.0); - each_selected(w, bounds, &cover, |i, _, c| { - let rgba = to_rgba(&fmt, &filled[i * n..(i + 1) * n]); - let mut enc = [0.0f32; 8]; - from_rgba_into(&lf, [rgba[0], rgba[1], rgba[2], rgba[3] * c], &mut enc); - px[i * ln..(i + 1) * ln].copy_from_slice(&enc[..ln]); - }); - if let Some(s) = l.surface_mut() { - s.write_region(window, &px); - s.prune(); - } - let nid = doc.insert_above(Some(id), l); - *active = Some(nid); - return Ok(nid); - } - "duplicate" => { - let mut dup = doc.layer(id).ok_or(EngineError::NoLayer(id))?.duplicate(); - dup.name = doc.copy_name(&dup.name); - let nid = doc.insert_above(Some(id), dup); - *active = Some(nid); - nid - } - _ => id, - }; - let surf = writable_surface(doc, target)?; - // The fill blended in by the coverage (elsewhere it is the original). - each_selected(w, bounds, &cover, |i, k, c| { - for ch in 0..n { - let (j, o) = (i * n + ch, k * n + ch); - filled[j] = original[o] + (filled[j] - original[o]) * c; - } - }); - surf.write_region(window, &filled); - Ok(target) - })?; - Ok(json!({"layer": layer.0, "filled": n_hole, "window": [window.x0, window.y0, window.width(), window.height()]})) -} - -// ------------------------------------------------------------------ Content-Aware Scale - -/// Reach of Content-Aware Scale's `x`/`y`: the largest document side. -const CAS_POSITION_LIMIT: f64 = 300_000.0; - -/// What Content-Aware Scale does, read from its params against the active document: the -/// command and the transform box's live preview ([`ContentAwareScalePreview`]) share it. -struct CasPlan { - doc: std::sync::Arc, - layer: LayerId, - /// The area scaled: the selection's bounds, else the layer's content. - region: Rect, - /// Where the result goes: `x`, `y` (default: the region's corner), `width`, `height`. - dst: Rect, - amount: f32, - protect: Option, - skin_tones: bool, -} - -fn cas_plan(s: &Session, p: &Value) -> Result { - let cmd = "edit.contentAwareScale"; - let id = pixel_layer(s).map_err(EngineError::Other)?; - let st = s.active().ok_or(EngineError::NoDocument)?; - let doc = st.doc.clone(); - let surf = doc.layer(id).and_then(|l| l.surface()).ok_or(EngineError::NoLayer(id))?; - let region = match &doc.selection { - Some(sel) => sel.content_bounds().intersect(&doc.bounds()), - None => surf.content_bounds(), - }; - if region.is_empty() { - return Err(EngineError::Other("nothing to scale: the layer is empty".into())); - } - let (w, h) = (region.width() as usize, region.height() as usize); - let dim = |k: &str, pct: &str, cur: usize| -> Result { - let v = match (p.get(k).and_then(Value::as_f64), p.get(pct).and_then(Value::as_f64)) { - (Some(px), _) => px, - (None, Some(pc)) => cur as f64 * pc / 100.0, - (None, None) => cur as f64, - }; - if !(1.0..=60_000.0).contains(&v) { - return Err(bad(cmd, format!("`{k}` must be 1..60000 px"))); - } - Ok(v.round() as u32) - }; - let (nw, nh) = (dim("width", "scaleX", w)?, dim("height", "scaleY", h)?); - let at = |k: &str, cur: i32| -> Result { - match p.get(k).filter(|v| !v.is_null()) { - None => Ok(cur), - Some(v) => match v.as_f64() { - Some(x) if (-CAS_POSITION_LIMIT..=CAS_POSITION_LIMIT).contains(&x) => Ok(x.round() as i32), - _ => Err(bad(cmd, format!("`{k}` must be a number of px within ±300000"))), - }, - } - }; - let dst = Rect::from_xywh(at("x", region.x0)?, at("y", region.y0)?, nw, nh); - let amount = f32_or(p, "amount", 100.0).clamp(0.0, 100.0) / 100.0; - // Protection: an alpha channel and/or skin tones. - let protect = match p.get("protect").filter(|v| !v.is_null() && v.as_str() != Some("none")) { - Some(v) => Some(channel_mask(&doc, v).cloned().ok_or_else(|| bad(cmd, "`protect` must name an alpha channel (index or name) or \"none\""))?), - None => None, - }; - let skin_tones = bool_or(p, "protectSkinTones", false); - Ok(CasPlan { doc, layer: id, region, dst, amount: if amount.is_finite() { amount } else { 1.0 }, protect, skin_tones }) -} - -/// The scaled pixels: `img` (`w`×`h`, `fmt`) seam-carved to `nw`×`nh` where the protection -/// (`protect`, one value per pixel, and the skin tones when asked) steers the seams, blended with -/// a plain resample by `amount` (0..1). Checks `ctx` for cancellation before every seam. -#[allow(clippy::too_many_arguments)] -fn cas_pixels( - ctx: &crate::jobs::JobCtx, - label: &str, - img: &[f32], - (w, h): (usize, usize), - fmt: PixelFormat, - mut protect: Option>, - skin_tones: bool, - (nw, nh): (usize, usize), - amount: f32, -) -> Result> { - use photocraft_algo::seam::{carve_with, resize_bilinear, skin_mask}; - let n = fmt.channels(); - if skin_tones { - let rgba: Vec = img.chunks_exact(n).flat_map(|px| to_rgba(&fmt, px)).collect(); - let skin = skin_mask(w, h, 4, &rgba); - protect = Some(match protect { - Some(pm) => pm.iter().zip(&skin).map(|(a, b)| a.max(*b)).collect(), - None => skin, - }); - } - ctx.check()?; - let carved = if amount > 0.0 { - ctx.stage(0.05, 0.95, label, |ctl| carve_with(w, h, n, img, protect.as_deref(), nw, nh, ctl)).map_err(|_| EngineError::Cancelled)? - } else { - Vec::new() - }; - let plain = if amount < 1.0 { resize_bilinear(w, h, n, img, nw, nh) } else { Vec::new() }; - Ok(match (carved.is_empty(), plain.is_empty()) { - (false, true) => carved, - (true, false) => plain, - _ => carved.iter().zip(&plain).map(|(c, l)| l + (c - l) * amount).collect::>(), - }) -} - -fn content_aware_scale(s: &mut Session, p: &Value) -> Result { - let CasPlan { doc, layer: id, region, dst, amount, protect: protect_mask, skin_tones } = cas_plan(s, p)?; - let (w, h) = (region.width() as usize, region.height() as usize); - let (nw, nh) = (dst.width() as usize, dst.height() as usize); - let label = "Content-Aware Scale"; - // A background job when started with `Session::start` (#210): seam carving runs on a worker - // against the document snapshot and checks for cancellation before every seam. - crate::jobs::run( - s, - label, - true, - move |ctx| { - ctx.progress(0.0, label); - let surf = doc.layer(id).and_then(|l| l.surface()).ok_or(EngineError::NoLayer(id))?; - let img = surf.read_region(region); - let protect: Option> = - protect_mask.map(|m| (0..w * h).map(|i| m.sample_channel(region.x0 + (i % w) as i32, region.y0 + (i / w) as i32, 0)).collect()); - cas_pixels(ctx, label, &img, (w, h), surf.format(), protect, skin_tones, (nw, nh), amount) - }, - move |s, out| { - s.edit(label, |doc, _| { - let surf = writable_surface(doc, id)?; - crate::pixels::try_clear_surface(surf, region, None)?; - surf.write_region(dst, &out); - surf.prune(); - Ok(()) - })?; - Ok(json!({"from": [w, h], "to": [nw, nh], "bounds": [dst.x0, dst.y0, nw, nh]})) - }, - ) -} - -/// Content-Aware Scale on a reduced copy, for the transform box's live preview (#3096): the -/// command's own carving, on the area scaled down so the longer of its sides before and after -/// is at most `max_side` px. Prepared from the session ([`ContentAwareScalePreview::new`]) and -/// [`run`](ContentAwareScalePreview::run) on any thread. -pub struct ContentAwareScalePreview { - plan: CasPlan, - max_side: u32, -} - -impl ContentAwareScalePreview { - /// `p` takes `edit.contentAwareScale`'s params; the same ones fail the same way. - pub fn new(s: &Session, p: &Value, max_side: u32) -> Result { - Ok(Self { plan: cas_plan(s, p)?, max_side: max_side.max(1) }) - } - - /// The area scaled, in document px. - pub fn region(&self) -> Rect { - self.plan.region - } - - /// The reduced sizes of the area before and after: `[w, h, new w, new h]`. - fn reduced(&self) -> [usize; 4] { - let (region, dst) = (self.plan.region, self.plan.dst); - let (w, h, nw, nh) = (region.width(), region.height(), dst.width(), dst.height()); - let k = (f64::from(w.max(h).max(nw).max(nh)) / f64::from(self.max_side)).max(1.0); - let side = |v: u32| ((f64::from(v) / k).round() as usize).max(1); - [side(w), side(h), side(nw), side(nh)] - } - - /// The size of [`run`](Self::run)'s result, px. - pub fn size(&self) -> [u32; 2] { - let [_, _, w, h] = self.reduced(); - [w as u32, h as u32] - } - - /// The scaled pixels at the reduced size ([`size`](Self::size)), in the layer's format, as a - /// surface with its corner at the origin. Checks `ctx` for cancellation before every seam. - pub fn run(&self, ctx: &crate::jobs::JobCtx) -> Result { - let CasPlan { doc, layer, region, dst: _, amount, protect, skin_tones } = &self.plan; - let surf = doc.layer(*layer).and_then(|l| l.surface()).ok_or(EngineError::NoLayer(*layer))?; - let fmt = surf.format(); - let n = fmt.channels(); - let (w, h) = (region.width(), region.height()); - let [pw, ph, pnw, pnh] = self.reduced(); - // Nearest samples of the area (and of the protecting channel) at the reduced size. - let src_x: Vec = (0..pw).map(|i| region.x0 + (((i as f64 + 0.5) * f64::from(w) / pw as f64) as i32).min(w as i32 - 1)).collect(); - let src_y = |j: usize| region.y0 + (((j as f64 + 0.5) * f64::from(h) / ph as f64) as i32).min(h as i32 - 1); - let mut img = Vec::with_capacity(pw * ph * n); - for j in 0..ph { - ctx.check()?; - let row = surf.read_region(Rect::from_xywh(region.x0, src_y(j), w, 1)); - for &x in &src_x { - let at = (x - region.x0) as usize * n; - img.extend_from_slice(row.get(at..at + n).ok_or_else(|| EngineError::Other("preview read out of bounds".into()))?); - } - } - let protect = protect.as_ref().map(|m| (0..pw * ph).map(|i| m.sample_channel(src_x[i % pw], src_y(i / pw), 0)).collect()); - let out = cas_pixels(ctx, "Content-Aware Scale", &img, (pw, ph), fmt, protect, *skin_tones, (pnw, pnh), *amount)?; - let mut s = Surface::new(fmt); - s.write_region(Rect::from_xywh(0, 0, pnw as u32, pnh as u32), &out); - Ok(s) - } -} - -// ------------------------------------------------------------------ Define Brush / Custom Shape - -fn define_brush_preset(s: &mut Session, p: &Value) -> Result { - let name = match p.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()) { - Some(n) => n.to_string(), - None => { - let n = s.tools.presets.iter().filter(|b| b.name.starts_with("Sampled Brush")).count() + 1; - format!("Sampled Brush {n}") - } - }; - s.execute("brush.defineFromSelection", json!({"name": name})) -} - -/// The path Define Custom Shape uses: `"work"`, a saved path name, else the work path, the -/// active shape layer, the active layer's vector mask, or the last saved path. -pub(crate) fn current_path(doc: &Document, active: Option, spec: Option<&str>) -> Option { - let ok = |p: &Path| !p.subpaths.is_empty(); - match spec { - Some("work") => return doc.work_path.clone().filter(ok), - Some(name) => return doc.paths.iter().find(|n| n.name == name).map(|n| n.path.clone()).filter(ok), - None => {} - } - if let Some(p) = doc.work_path.clone().filter(ok) { - return Some(p); - } - if let Some(l) = active.and_then(|id| doc.layer(id)) { - if let LayerContent::Shape(sh) = &l.content - && ok(&sh.path) - { - return Some(sh.path.clone()); - } - if let Some(vm) = l.vector_mask.as_ref().filter(|v| ok(&v.path)) { - return Some(vm.path.clone()); - } - } - doc.paths.last().map(|n| n.path.clone()).filter(ok) -} - -fn can_define_shape(s: &Session) -> std::result::Result<(), String> { - let d = s.active().ok_or("no document open")?; - current_path(&d.doc, d.active_layer, None).map(|_| ()).ok_or_else(|| "select a path or shape layer first".into()) -} - -fn define_custom_shape(s: &mut Session, p: &Value) -> Result { - let st = s.active().ok_or(EngineError::NoDocument)?; - let path = current_path(&st.doc, st.active_layer, p.get("path").and_then(Value::as_str)).ok_or_else(|| bad("edit.defineCustomShape", "no such path"))?; - let name = p - .get("name") - .and_then(Value::as_str) - .map(str::trim) - .filter(|n| !n.is_empty()) - .map(str::to_string) - .unwrap_or_else(|| format!("Shape {}", s.edit_state.custom_shapes.len() + 1)); - let shapes = &mut s.edit_state.custom_shapes; - match shapes.iter_mut().find(|c| c.name == name) { - Some(c) => c.path = path, - None => shapes.push(CustomShape { name: name.clone(), path }), - } - Ok(json!({"name": name, "count": shapes.len()})) -} - -// ------------------------------------------------------------------ Find and Replace Text - -/// Byte ranges of `find` in `text` (case-insensitive unless `case`; whole words only with `whole`). -pub fn find_matches(text: &str, find: &str, case: bool, whole: bool) -> Vec<(usize, usize)> { - if find.is_empty() { - return Vec::new(); - } - let norm = |c: char| -> String { if case { c.to_string() } else { c.to_lowercase().collect() } }; - let needle: String = find.chars().map(norm).collect(); - let mut out = Vec::new(); - let mut at = 0; - while at < text.len() { - // Compare char by char so case folding that changes byte lengths stays aligned. - let mut hay = String::new(); - let mut end = at; - for (i, c) in text[at..].char_indices() { - if hay.len() >= needle.len() { - break; - } - hay.push_str(&norm(c)); - end = at + i + c.len_utf8(); - } - if hay == needle { - let word = |c: Option| c.is_some_and(|c| c.is_alphanumeric() || c == '_'); - let before = text[..at].chars().next_back(); - let after = text[end..].chars().next(); - if !whole || (!word(before) && !word(after)) { - out.push((at, end)); - at = end; - continue; - } - } - at += text[at..].chars().next().map_or(1, char::len_utf8); - } - out -} - -fn type_layers(doc: &Document, forward: bool) -> Vec { - // Layers panel order: top first. - let mut ids: Vec = - doc.walk().into_iter().rev().filter(|(p, _, l)| matches!(l.content, LayerContent::Text(_)) && !doc.locks_at(p).all).map(|(_, _, l)| l.id).collect(); - if !forward { - ids.reverse(); - } - ids -} - -fn has_type_layer(s: &Session) -> std::result::Result<(), String> { - let d = s.active().ok_or("no document open")?; - if type_layers(&d.doc, true).is_empty() { Err("the document has no type layers".into()) } else { Ok(()) } -} - -fn find_replace(s: &mut Session, p: &Value) -> Result { - let cmd = "edit.findAndReplaceText"; - let find = p.get("find").and_then(Value::as_str).filter(|f| !f.is_empty()).ok_or_else(|| bad(cmd, "missing `find`"))?.to_string(); - let replace = str_or(p, "replace", "").to_string(); - let (case, whole, forward, all_layers) = - (bool_or(p, "caseSensitive", false), bool_or(p, "wholeWord", false), bool_or(p, "forward", true), bool_or(p, "allLayers", true)); - let action = str_or(p, "action", "changeAll").to_string(); - let st = s.active().ok_or(EngineError::NoDocument)?; - let mut layers = type_layers(&st.doc, forward); - if !all_layers { - let active = layer_param(s, p).ok(); - layers.retain(|id| Some(*id) == active); - } - let text_of = |doc: &Document, id: LayerId| -> Option { - match &doc.layer(id)?.content { - LayerContent::Text(t) => Some(t.text.clone()), - _ => None, - } - }; - match action.as_str() { - "changeAll" => { - let doc = st.doc.clone(); - let plan: Vec<(LayerId, Vec<(usize, usize)>)> = - layers.iter().filter_map(|id| Some((*id, find_matches(&text_of(&doc, *id)?, &find, case, whole)))).filter(|(_, m)| !m.is_empty()).collect(); - let count: usize = plan.iter().map(|(_, m)| m.len()).sum(); - if count == 0 { - return Ok(json!({"count": 0, "layers": 0})); - } - s.edit("Replace All Text", |doc, _| { - let (dpi, format) = (doc.resolution_dpi, doc.pixel_format()); - for (id, matches) in &plan { - if let Some(LayerContent::Text(t)) = doc.layer_mut(*id).map(|l| &mut l.content) { - for (a, b) in matches.iter().rev() { - crate::type_cmds::replace_text(t, *a, *b, &replace); - } - crate::type_cmds::refresh_at(dpi, format, t); - } - } - Ok(()) - })?; - s.edit_state.find_cursor = None; - Ok(json!({"count": count, "layers": plan.len()})) - } - "find" | "change" | "changeFind" => { - let doc = st.doc.clone(); - let cursor = s.edit_state.find_cursor; - let mut changed = None; - if action != "find" - && let Some((id, a, b)) = cursor - && text_of(&doc, id).is_some_and(|t| find_matches(&t, &find, case, whole).contains(&(a, b))) - { - crate::type_cmds::check_text_unlocked(&doc, id)?; - s.edit("Replace Text", |doc, _| { - let (dpi, format) = (doc.resolution_dpi, doc.pixel_format()); - if let Some(LayerContent::Text(t)) = doc.layer_mut(id).map(|l| &mut l.content) { - crate::type_cmds::replace_text(t, a, b, &replace); - crate::type_cmds::refresh_at(dpi, format, t); - } - Ok(()) - })?; - let end = a + replace.len(); - // Collapse the cursor on the side the search moves away from, so the next search - // skips the replaced text even when the replacement still matches. - let c = if forward { end } else { a }; - s.edit_state.find_cursor = Some((id, c, c)); - changed = Some((id, a, end)); - if action == "change" { - return Ok(json!({"changed": {"layer": id.0, "start": a, "end": end}})); - } - } - // Find the next match after the cursor (wrapping through the layers). - let doc = s.active().ok_or(EngineError::NoDocument)?.doc.clone(); - let cursor = s.edit_state.find_cursor; - let start = cursor.and_then(|(id, _, _)| layers.iter().position(|l| *l == id)).unwrap_or(0); - for k in 0..=layers.len() { - // `allLayers: false` with a non-type layer active leaves no layers to search (#703). - let Some(&id) = layers.get((start + k) % layers.len().max(1)) else { break }; - let Some(text) = text_of(&doc, id) else { continue }; - let ms = find_matches(&text, &find, case, whole); - let hit = match (k, cursor) { - (0, Some((cid, a, b))) if cid == id => { - if forward { - ms.into_iter().find(|m| m.0 >= b) - } else { - ms.into_iter().rev().find(|m| m.1 <= a) - } - } - _ => { - if forward { - ms.into_iter().next() - } else { - ms.into_iter().next_back() - } - } - }; - if let Some((a, b)) = hit { - s.edit_state.find_cursor = Some((id, a, b)); - let _ = s.select_layer(id); - return Ok( - json!({"found": {"layer": id.0, "start": a, "end": b, "text": &text[a..b]}, "changed": changed.map(|(l, a, b)| json!({"layer": l.0, "start": a, "end": b}))}), - ); - } - } - s.edit_state.find_cursor = None; - Ok(json!({"found": null, "changed": changed.map(|(l, a, b)| json!({"layer": l.0, "start": a, "end": b}))})) - } - other => Err(bad(cmd, format!("unknown action `{other}` (find|change|changeFind|changeAll)"))), - } -} - -// ------------------------------------------------------------------ presets - -/// Libraries the Preset Manager edits (patterns export as `.pat` with `pattern.export`). -const PRESET_KINDS: [&str; 3] = ["brushes", "customShapes", "patterns"]; - -fn preset_names(s: &Session, kind: &str) -> Option> { - Some(match kind { - "brushes" => s.tools.presets.iter().map(|b| b.name.clone()).collect(), - "customShapes" => s.edit_state.custom_shapes.iter().map(|c| c.name.clone()).collect(), - "patterns" => s.patterns.items.iter().map(|p| p.name.clone()).collect(), - _ => return None, - }) -} - -fn preset_index(s: &Session, kind: &str, p: &Value) -> Result { - let names = preset_names(s, kind).ok_or_else(|| bad("edit.presets.presetManager", format!("unknown preset kind `{kind}` ({})", PRESET_KINDS.join("|"))))?; - if let Some(i) = p.get("index").and_then(Value::as_u64) { - return if (i as usize) < names.len() { Ok(i as usize) } else { Err(bad("edit.presets.presetManager", format!("no preset {i}"))) }; - } - let name = p.get("name").and_then(Value::as_str).ok_or_else(|| bad("edit.presets.presetManager", "give `index` or `name`"))?; - names.iter().position(|n| n == name).ok_or_else(|| bad("edit.presets.presetManager", format!("no preset named `{name}`"))) -} - -fn preset_manager(s: &mut Session, p: &Value) -> Result { - let cmd = "edit.presets.presetManager"; - let action = str_or(p, "action", "list"); - if action == "list" { - let kinds: Vec<&str> = match p.get("kind").and_then(Value::as_str) { - Some(k) => vec![k], - None => PRESET_KINDS.to_vec(), - }; - let mut out = serde_json::Map::new(); - for k in kinds { - out.insert(k.to_string(), json!(preset_names(s, k).ok_or_else(|| bad(cmd, format!("unknown preset kind `{k}`")))?)); - } - return Ok(Value::Object(out)); - } - let kind = p.get("kind").and_then(Value::as_str).ok_or_else(|| bad(cmd, "missing `kind`"))?.to_string(); - let i = preset_index(s, &kind, p)?; - match action { - "rename" => { - let new = - p.get("newName").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad(cmd, "missing `newName`"))?.to_string(); - match kind.as_str() { - // Same rules as Brush Settings: no duplicate names (case-insensitive), the current - // preset follows, a renamed built-in is the user's preset now (and persists as one). - "brushes" => crate::brush_preset_cmds::rename_at(s, i, &new, cmd)?, - "patterns" => s.patterns.items[i].name = new, - _ => s.edit_state.custom_shapes[i].name = new, - } - } - "delete" => match kind.as_str() { - "brushes" => { - let gone = s.tools.presets.remove(i); - crate::brush_cmds::forget_deleted_preset(s, &gone.name); - } - "patterns" => drop(s.patterns.items.remove(i)), - _ => drop(s.edit_state.custom_shapes.remove(i)), - }, - "move" => { - let to = p.get("to").and_then(Value::as_u64).ok_or_else(|| bad(cmd, "missing `to`"))? as usize; - match kind.as_str() { - "brushes" => crate::move_item(&mut s.tools.presets, i, to), - "patterns" => crate::move_item(&mut s.patterns.items, i, to), - _ => crate::move_item(&mut s.edit_state.custom_shapes, i, to), - }; - } - other => return Err(bad(cmd, format!("unknown action `{other}` (list|rename|delete|move)"))), - } - if kind == "brushes" { - s.brush_presets_changed(); - } - Ok(json!({kind.clone(): preset_names(s, &kind)})) -} - -/// Exported preset file (`.pcpresets`, JSON). -#[derive(Clone, Debug, Default, Serialize, Deserialize)] -#[serde(default, rename_all = "camelCase")] -pub struct PresetFile { - pub format: String, - pub version: u32, - pub brushes: Vec, - pub custom_shapes: Vec, - pub tool_presets: Vec, -} - -pub const PRESET_FORMAT: &str = "photocraft-presets"; - -fn export_import(s: &mut Session, p: &Value) -> Result { - let cmd = "edit.presets.exportImportPresets"; - let kinds: Vec = p - .get("kinds") - .and_then(Value::as_array) - .map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect()) - .unwrap_or_else(|| ["brushes", "customShapes", "tools"].iter().map(ToString::to_string).collect()); - let want = |k: &str| kinds.iter().any(|x| x == k); - match str_or(p, "action", "export") { - "export" => { - let file = PresetFile { - format: PRESET_FORMAT.into(), - version: 1, - brushes: if want("brushes") { - let mut out: Vec = - s.tools.presets.iter().filter(|b| !b.builtin || bool_or(p, "includeBuiltins", false)).cloned().collect(); - // The file embeds every bitmap: load the tips the preset store keeps (#1843). - for b in &mut out { - s.load_brush_tips(&mut b.brush).map_err(|e| bad(cmd, format!("brush preset `{}`: {e}", b.name)))?; - } - out - } else { - Vec::new() - }, - custom_shapes: if want("customShapes") { s.edit_state.custom_shapes.clone() } else { Vec::new() }, - tool_presets: if want("tools") { - let builtins = crate::presets::tools::builtin(); - s.presets.tool_presets.iter().filter(|preset| bool_or(p, "includeBuiltins", false) || !builtins.contains(preset)).cloned().collect() - } else { - Vec::new() - }, - }; - Ok(json!({"data": file, "brushes": file.brushes.len(), "customShapes": file.custom_shapes.len(), "tools": file.tool_presets.len()})) - } - "import" => { - let data = p.get("data").cloned().ok_or_else(|| bad(cmd, "missing `data` (an exported preset file)"))?; - let data = match data { - Value::String(text) => serde_json::from_str(&text).map_err(|e| bad(cmd, format!("not a preset file: {e}")))?, - v => v, - }; - let file: PresetFile = serde_json::from_value(data).map_err(|e| bad(cmd, format!("not a preset file: {e}")))?; - if file.format != PRESET_FORMAT { - return Err(bad(cmd, format!("not a preset file (format `{}`)", file.format))); - } - // Validate the whole tool import before changing any preset library. - let mut tools = s.presets.tool_presets.clone(); - let nt = if want("tools") { file.tool_presets.len() } else { 0 }; - if nt > crate::presets::tools::MAX_PRESETS { - return Err(bad(cmd, "too many tool presets")); - } - if want("tools") { - for mut preset in file.tool_presets { - preset.name = crate::presets::tools::checked_name(&preset.name, cmd)?; - if preset.tool.trim().is_empty() || !preset.options.is_object() { - return Err(bad(cmd, "tool presets require a non-empty tool and an options object")); - } - if let Some(old) = tools.iter_mut().find(|old| old.name == preset.name && old.tool.eq_ignore_ascii_case(&preset.tool)) { - *old = preset; - } else if tools.iter().any(|old| old.name == preset.name) { - return Err(bad(cmd, "a preset of that name belongs to another tool; rename it before importing")); - } else if tools.len() < crate::presets::tools::MAX_PRESETS { - tools.push(preset); - } else { - return Err(bad(cmd, "too many tool presets")); - } - } - } - let (mut nb, mut ns) = (0, 0); - if want("brushes") { - for mut b in file.brushes { - // Nested folders as the commands bound them (a hand-edited file can't build an - // absurd tree). - b.folder.retain(|f| !f.trim().is_empty()); - b.folder.truncate(crate::brush_preset_cmds::MAX_FOLDER_DEPTH); - match s.tools.presets.iter_mut().find(|x| x.name == b.name) { - Some(x) => *x = b, - None => s.tools.presets.push(b), - } - nb += 1; - } - s.brush_presets_changed(); - } - if want("customShapes") { - for c in file.custom_shapes { - match s.edit_state.custom_shapes.iter_mut().find(|x| x.name == c.name) { - Some(x) => *x = c, - None => s.edit_state.custom_shapes.push(c), - } - ns += 1; - } - } - if want("tools") { - s.presets.tool_presets = tools; - s.presets_changed(); - } - Ok(json!({"brushes": nb, "customShapes": ns, "tools": nt})) - } - other => Err(bad(cmd, format!("unknown action `{other}` (export|import)"))), - } -} - -// ------------------------------------------------------------------ specs - -macro_rules! spec { - ($id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $en:expr, $run:expr) => { - CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run, journal: true } - }; -} - -pub fn specs() -> Vec { - vec![ - spec!( - "edit.fade", - "Fade…", - ["Edit"], - Some("Cmd+Shift+F"), - r##"{"opacity":0..100=100,"mode":"normal|multiply|screen|overlay|softLight|hardLight|darken|lighten|difference|color|luminosity"}"##, - can_fade, - fade - ), - spec!("edit.purge.undo", "Undo", ["Edit", "Purge"], None, "{}", can_purge_undo, |s, _| purge(s, "undo")), - spec!("edit.purge.clipboard", "Clipboard", ["Edit", "Purge"], None, "{}", can_purge_clipboard, |s, _| purge(s, "clipboard")), - spec!("edit.purge.histories", "Histories", ["Edit", "Purge"], None, "{}", can_purge_histories, |s, _| purge(s, "histories")), - spec!("edit.purge.videoCache", "Video Cache", ["Edit", "Purge"], None, "{}", always, |_, _| Ok( - json!({"purged": [], "bytes": 0, "message": "nothing to purge (no video layers)"}) - )), - spec!("edit.purge.all", "All", ["Edit", "Purge"], None, "{}", can_purge_all, |s, _| purge(s, "all")), - spec!( - "edit.contentAwareFill", - "Content-Aware Fill…", - ["Edit"], - None, - r##"{"sampling":"auto|rectangular|custom","margin":px?,"area":[x,y,w,h]?,"channel":index|name?,"samplingStrokes":[{"mode":"add|subtract","size":px,"points":[[x,y],…]}]? (the workspace's Sampling Brush, after the sampling option's area; added strokes may lie outside the window),"fillEdits":[{"op":"new|add|subtract|intersect","points":[[x,y],…]}|{"op":"expand|contract","by":px}]? (the workspace's lasso edits of the fill area, in order),"sampleAllLayers":bool=false,"colorAdaptation":"default|none|high|veryHigh","rotationAdaptation":"none|low|medium|high|full","scale":bool=false,"mirror":bool=false,"output":"current|new|duplicate","layer":id?=active (the layer filled and sampled),"seed":u64=1}"##, - can_caf, - content_aware_fill - ), - spec!("edit.deleteAndFillSelection", "Delete and Fill Selection", [], None, "{}", can_caf, delete_and_fill), - spec!( - "edit.contentAwareScale", - "Content-Aware Scale", - ["Edit"], - Some("Cmd+Alt+Shift+C"), - r##"{"width":px?,"height":px?,"scaleX":1..400=100,"scaleY":1..400=100,"x":px?,"y":px?,"amount":0..100=100,"protect":"none"|channel index|name,"protectSkinTones":bool=false}"##, - |s| pixel_layer(s).map(|_| ()), - content_aware_scale - ), - spec!( - "edit.defineBrushPreset", - "Define Brush Preset…", - ["Edit"], - None, - r##"{"name":text}"##, - |s| if s.is_enabled("brush.defineFromSelection") { Ok(()) } else { Err("select pixels to define a brush from".into()) }, - define_brush_preset - ), - spec!( - "edit.defineCustomShape", - "Define Custom Shape…", - ["Edit"], - None, - r##"{"name":text,"path":"work|"?}"##, - can_define_shape, - define_custom_shape - ), - spec!( - "edit.findAndReplaceText", - "Find and Replace Text…", - ["Edit"], - None, - r##"{"find":text,"replace":text,"action":"changeAll|find|change|changeFind","caseSensitive":bool=false,"wholeWord":bool=false,"forward":bool=true,"allLayers":bool=true}"##, - has_type_layer, - find_replace - ), - spec!( - "edit.presets.presetManager", - "Preset Manager…", - ["Edit", "Presets"], - None, - r##"{"action":"list|rename|delete|move","kind":"brushes|customShapes|patterns","index":n?,"name":str?,"newName":str?,"to":n?}"##, - always, - preset_manager - ), - spec!( - "edit.presets.exportImportPresets", - "Export/Import Presets…", - ["Edit", "Presets"], - None, - r##"{"action":"export|import","kinds":["brushes","customShapes","tools"]?,"data":json (import),"includeBuiltins":bool=false}"##, - always, - export_import - ), - ] -} - -/// The custom shape library (for the Custom Shape tool). -pub fn custom_shapes(s: &Session) -> &[CustomShape] { - &s.edit_state.custom_shapes -} - -#[cfg(test)] -#[path = "edit_menu_cmds/tests.rs"] -mod tests; diff --git a/crates/engine/src/error.rs b/crates/engine/src/error.rs new file mode 100644 index 0000000000..e033d8db93 --- /dev/null +++ b/crates/engine/src/error.rs @@ -0,0 +1,32 @@ +use super::*; + +#[derive(Debug, thiserror::Error)] +pub enum EngineError { + #[error("unknown command `{0}`")] + UnknownCommand(String), + #[error("command `{0}` is not available right now: {1}")] + Disabled(String, String), + #[error("invalid parameters for `{cmd}`: {msg}")] + BadParams { cmd: String, msg: String }, + #[error("no active document")] + NoDocument, + #[error("no such layer {0:?}")] + NoLayer(LayerId), + /// [`Self::NoLayer`] as a command reports it: with the layers the document does have, as + /// ids are not positions (#5058). + #[error("no such layer {}; {known}", id.0)] + UnknownLayer { id: LayerId, known: String }, + #[error("{0}")] + Other(String), + /// A background job was cancelled (see [`jobs`]); nothing changed. + #[error("cancelled")] + Cancelled, +} + +pub type Result = std::result::Result; + +impl From for EngineError { + fn from(error: photocraft_raster::AllocationError) -> Self { + Self::Other(format!("not enough memory for this operation ({error}); the document was not changed")) + } +} diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs deleted file mode 100644 index 261e3d8608..0000000000 --- a/crates/engine/src/file_cmds.rs +++ /dev/null @@ -1,2222 +0,0 @@ -//! File-menu commands beyond New/Close: Close All / Others, Revert, Save a Copy, Open As, Place -//! Embedded / Linked, File Info, the Automate and Scripts items (Fit Image, Conditional Mode -//! Change, Batch, Image Processor, Load Files into Stack, Flatten All Layer Effects / Masks), -//! Export › Layers to Files and Color Lookup Tables, plus the document-level guide layouts of the -//! View menu (New Guide Layout, New Guides From Shape, Clear Canvas Guides). -//! -//! Commands that touch the file system take explicit paths (the UI asks for them with its own -//! pickers) and are unavailable on the web, where there is no file system; their byte-level -//! cores ([`place_bytes`], [`open_bytes_as`]) work everywhere. - -use std::sync::Arc; - -use photocraft_algo::resample::{Resample, resize_surface, translate_surface}; -use photocraft_color::{ColorMode, PixelFormat}; -use photocraft_doc::{Affine, Document, Layer, LayerContent, LayerId, SmartObject, SmartSource}; -use photocraft_geom::Rect; -use photocraft_raster::{Surface, from_rgba_into}; -use serde_json::{Value, json}; - -use crate::commands::{CommandSpec, layer_param}; -use crate::{EngineError, Result, Session}; - -mod batch_naming; - -// ---------- predicates ---------- - -fn has_doc(s: &Session) -> std::result::Result<(), String> { - s.active().map(|_| ()).ok_or_else(|| "no document open".into()) -} - -/// The file system is reachable (not on the web). -pub(crate) fn native(_: &Session) -> std::result::Result<(), String> { - if cfg!(target_arch = "wasm32") { Err("not available on the web (no file system)".into()) } else { Ok(()) } -} - -pub(crate) fn native_doc(s: &Session) -> std::result::Result<(), String> { - native(s)?; - has_doc(s) -} - -fn can_revert(s: &Session) -> std::result::Result<(), String> { - native(s)?; - let d = s.active().ok_or("no document open")?; - let path = d.path.as_deref().ok_or("the document has never been saved")?; - if !is_file(path) { - return Err(format!("{path} is not a file on disk")); - } - Ok(()) -} - -fn has_adjustments(s: &Session) -> std::result::Result<(), String> { - let d = s.active().ok_or("no document open")?; - if d.doc.layers.iter().any(|l| l.visible && matches!(l.content, LayerContent::Adjustment(_))) { - Ok(()) - } else { - Err("the document has no visible adjustment layers to export".into()) - } -} - -fn has_shape(s: &Session) -> std::result::Result<(), String> { - let d = s.active().ok_or("no document open")?; - match d.active_layer.and_then(|id| d.doc.layer(id)).map(|l| &l.content) { - Some(LayerContent::Shape(_)) => Ok(()), - _ => Err("the active layer is not a shape layer".into()), - } -} - -// ---------- file system (native only) ---------- - -#[cfg(not(target_arch = "wasm32"))] -fn is_file(path: &str) -> bool { - std::path::Path::new(path).is_file() -} -#[cfg(target_arch = "wasm32")] -fn is_file(_path: &str) -> bool { - false -} - -#[cfg(not(target_arch = "wasm32"))] -/// Every file the engine opens is read here: in bounded reads, with a clear error when it does -/// not fit in memory (see [`photocraft_format::read`]). -pub(crate) fn read_file(path: &str) -> Result> { - photocraft_format::read_file(std::path::Path::new(path)).map_err(|e| EngineError::Other(format!("{path}: {e}"))) -} -#[cfg(target_arch = "wasm32")] -pub(crate) fn read_file(path: &str) -> Result> { - Err(EngineError::Other(format!("cannot read {path}: no file system on the web"))) -} - -#[cfg(not(target_arch = "wasm32"))] -/// Every file the engine writes goes through here: crash-safe (temp file + fsync + rename, see -/// [`photocraft_format::atomic`]), so a failed save never destroys the previous file. -pub(crate) fn write_file(path: &str, bytes: &[u8]) -> Result<()> { - photocraft_format::atomic_write(std::path::Path::new(path), bytes).map_err(|e| EngineError::Other(e.to_string())) -} -#[cfg(target_arch = "wasm32")] -pub(crate) fn write_file(path: &str, _bytes: &[u8]) -> Result<()> { - Err(EngineError::Other(format!("cannot write {path}: no file system on the web"))) -} - -/// Files of a folder that look like images we can open, sorted by name. -#[cfg(not(target_arch = "wasm32"))] -pub fn list_images(dir: &str) -> Result> { - let rd = std::fs::read_dir(dir).map_err(|e| EngineError::Other(format!("{dir}: {e}")))?; - let mut out: Vec = rd - .filter_map(|e| e.ok()) - .map(|e| e.path()) - .filter(|p| p.is_file() && openable_name(&p.to_string_lossy())) - .map(|p| p.to_string_lossy().into_owned()) - .collect(); - out.sort(); - Ok(out) -} -#[cfg(target_arch = "wasm32")] -pub fn list_images(dir: &str) -> Result> { - Err(EngineError::Other(format!("cannot list {dir}: no file system on the web"))) -} - -/// Whether a folder entry is one the batch commands open: an `OPENABLE` extension, or GIMP's -/// gzipped `.xcf.gz`, whose last extension alone says nothing. -#[cfg(not(target_arch = "wasm32"))] -fn openable_name(path: &str) -> bool { - let lower = file_name(path).to_ascii_lowercase(); - lower.ends_with(".xcf.gz") || lower.rsplit_once('.').is_some_and(|(_, ext)| OPENABLE.contains(&ext)) -} - -/// Extensions the batch commands pick up from a folder. -#[cfg(not(target_arch = "wasm32"))] -const OPENABLE: &[&str] = &[ - "pdn", "ora", "xcf", "xcfgz", "kra", "krz", "psd", "psb", "pcraft", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "exr", "hdr", "qoi", - "ico", "pnm", "ppm", "pgm", "fits", "fit", "fts", "dpx", "heic", "heif", "hif", "dng", "cr2", "nef", "nrw", "arw", "pef", "svg", "svgz", "af", "afdesign", - "afphoto", "afpub", -]; - -/// Whether saving `doc` as a TIFF writes Photoshop layer data (anything beyond a lone -/// Background layer). The UI asks before such a save when the "ask before saving layered TIFF" -/// preference is on; see `photocraft_io::tiff_layers`. -pub fn tiff_would_write_layers(doc: &Document) -> bool { - photocraft_io::tiff_layers::would_write_layers(doc) -} - -pub(crate) fn file_name(path: &str) -> String { - path.rsplit(['/', '\\']).next().unwrap_or(path).to_string() -} - -impl crate::DocState { - /// Complete a successful document save. File identity is not a history step; callers must - /// finish the write first and must not call this for a copy or export. - pub fn saved_to(&mut self, path: String) { - let name = file_name(&path); - if self.doc.name != name { - Arc::make_mut(&mut self.doc).name = name; - } - self.path = Some(path); - self.saved_revision = self.revision; - } -} - -/// The lower-case extension of the file name in `path` (none for `.hidden` or `name`). -pub fn extension(path: &str) -> Option { - file_name(path).rsplit_once('.').filter(|(base, ext)| !base.is_empty() && !ext.is_empty()).map(|(_, ext)| ext.to_ascii_lowercase()) -} - -/// Whether a save without a new path may write back to `path` as far as its format goes: only -/// layered files (PSD, PSB, OpenRaster, .pcraft). A flat file goes through Save As instead, so it -/// is never flattened over the original. Whether this document fits is [`holds_at`]. -pub fn saves_in_place(path: &str) -> bool { - extension(path).is_some_and(|ext| layered_extension(&ext)) -} - -/// Whether the lower-case extension `ext` names a layered document format (PSD, PSB, OpenRaster, -/// .pcraft). A save to one becomes the document's file; any other format is a copy for automation -/// saves, desktop and headless alike (#1547, #2579). -pub fn layered_extension(ext: &str) -> bool { - matches!(ext, "psd" | "psb" | "pcraft" | "ora") -} - -/// Whether a file in format `ext` (lower-case) holds the whole of `doc`, so it can be the -/// document's own file: PSD, PSB and .pcraft always; OpenRaster only when it drops nothing (no -/// adjustment layers, styles, masks…, [`photocraft_io::ora_losses`]). A save to a format that -/// doesn't hold the document is a copy, and File › Save goes through Save As, so an editable -/// original is never overwritten with less than it had (#3806). -pub fn holds(doc: &photocraft_doc::Document, ext: &str) -> bool { - match ext { - "psd" | "psb" | "pcraft" => true, - "ora" => photocraft_io::ora_losses(doc).is_empty(), - _ => false, - } -} - -/// [`holds`] for the file at `path`. -pub fn holds_at(doc: &photocraft_doc::Document, path: &str) -> bool { - extension(path).is_some_and(|ext| holds(doc, &ext)) -} - -/// What a save of `doc` to `path` would leave out when its format can't hold it: OpenRaster's -/// [`photocraft_io::ora_losses`]; empty for other formats. -pub fn losses_at(doc: &photocraft_doc::Document, path: &str) -> Vec { - match extension(path).as_deref() { - Some("ora") => photocraft_io::ora_losses(doc), - _ => Vec::new(), - } -} - -/// Whether `path` names a document template (.psdt). A template opens as a new untitled document -/// without its path, so a save never writes over the template. -pub fn is_template(path: &str) -> bool { - extension(path).as_deref() == Some("psdt") -} - -/// The first "`base`-N" that isn't `taken`. -pub fn untitled_name(base: &str, taken: impl Fn(&str) -> bool) -> String { - (1..).map(|i| format!("{base}-{i}")).find(|n| !taken(n)).unwrap_or_default() -} - -/// The name a document opened from `path` gets when `path` is a template: the first "Untitled-N" -/// no open document has. -pub fn template_name(s: &Session, path: &str) -> Option { - is_template(path).then(|| untitled_name("Untitled", |n| s.documents().iter().any(|d| d.doc.name == n))) -} - -pub(crate) fn stem(path: &str) -> String { - let n = file_name(path); - match n.rfind('.') { - Some(i) if i > 0 => n[..i].to_string(), - _ => n, - } -} - -/// Whether `a` and `b` name the same file: the same text, or, when both exist, the same file on -/// disk (a hard link, a different case on a case-insensitive volume, `./` or `..` in one of them). -pub fn same_file(a: impl AsRef, b: impl AsRef) -> bool { - let (a, b) = (a.as_ref(), b.as_ref()); - if a == b { - return true; - } - #[cfg(unix)] - { - use std::os::unix::fs::MetadataExt; - if let (Ok(x), Ok(y)) = (std::fs::metadata(a), std::fs::metadata(b)) { - return x.dev() == y.dev() && x.ino() == y.ino(); - } - } - #[cfg(windows)] - { - // The volume serial number and file index of each, as unix compares dev and inode, so a - // hard link (another name for the file) is the same file. - if let Ok(same) = same_file::is_same_file(a, b) { - return same; - } - // Should a file not open: NTFS and FAT compare names without case. - if let (Ok(x), Ok(y)) = (std::fs::canonicalize(a), std::fs::canonicalize(b)) { - return x.to_string_lossy().to_lowercase() == y.to_string_lossy().to_lowercase(); - } - } - false -} - -/// A path as command results report it: `/` between components, whatever the platform. -/// -/// `join` already builds with `/`, but a directory from the caller or from `std::path::absolute` -/// carries the native separator, which would leave a reported path mixed. The control channel -/// takes `/` and rejects alternate separators (`AuthorizedWorkspace` in `crates/automation`), so -/// a result spelt this way can be handed straight back to it. Verbatim and UNC prefixes keep -/// theirs: Win32 does not accept `/` after a leading `\\`. -pub(crate) fn forward_slashes(path: String) -> String { - if path.starts_with(r"\\") { path } else { path.replace('\\', "/") } -} - -pub(crate) fn join(dir: &str, name: &str) -> String { - if dir.is_empty() { - name.to_string() - } else if dir.ends_with('/') || dir.ends_with('\\') { - format!("{dir}{name}") - } else { - format!("{dir}/{name}") - } -} - -/// A file-name-safe version of a layer name. A Windows device name (`nul`, `con.v2`) gets a `_` -/// before its first dot, so the file or folder is usable on Windows, wherever it was written. -pub(crate) fn sanitize(name: &str) -> String { - let s: String = name.chars().map(|c| if c.is_alphanumeric() || matches!(c, '-' | '_' | ' ' | '.') { c } else { '_' }).collect(); - let s = s.trim().trim_matches('.').to_string(); - if s.is_empty() { "layer".into() } else { portable_device_name(s) } -} - -/// `name` with a `_` before its first dot when it is a Windows device name (`nul` → `nul_`, -/// `com1.v2` → `com1_.v2`); a `_` at the end would leave the device stem in place. -pub(crate) fn portable_device_name(name: String) -> String { - if !is_windows_device_name(&name) { - return name; - } - match name.split_once('.') { - Some((device, rest)) => format!("{device}_.{rest}"), - None => format!("{name}_"), - } -} - -/// Whether `component` names a Windows device (`CON`, `NUL`, `COM1`…, with any extension): -/// Windows opens the device instead of a file or folder of that name. `COM` and `LPT` take the -/// superscript digits ¹ ² ³ as well, as Windows does. -pub(crate) fn is_windows_device_name(component: &str) -> bool { - let stem = component.split('.').next().unwrap_or(component).trim_end_matches(' ').to_ascii_uppercase(); - let port = |n: &str| matches!(n, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "¹" | "²" | "³"); - matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL" | "CLOCK$" | "CONIN$" | "CONOUT$") - || stem.strip_prefix("COM").is_some_and(port) - || stem.strip_prefix("LPT").is_some_and(port) -} - -pub(crate) fn import(name: &str, bytes: &[u8]) -> Result { - import_result(name, bytes).map(|r| r.document) -} - -/// [`import`] for a file that becomes a document of its own (Revert, Load Files into Stack; -/// Batch's scratch sessions use [`import_at_raw_ppi`]): a developed raw gets Preferences › Raw -/// Defaults › Resolution, as it does through File › Open. -pub(crate) fn import_opened(s: &Session, name: &str, bytes: &[u8]) -> Result { - import_at_raw_ppi(s.prefs().raw_defaults.resolution, name, bytes) -} - -fn import_at_raw_ppi(raw_ppi: f64, name: &str, bytes: &[u8]) -> Result { - let r = import_result(name, bytes)?; - let mut doc = r.document; - raw_resolution(raw_ppi, &r.warnings, &mut doc); - Ok(doc) -} - -fn import_result(name: &str, bytes: &[u8]) -> Result { - crate::allocation::checkpoint("importing document")?; - let r = photocraft_io::import(name, bytes).map_err(|e| EngineError::Other(format!("{name}: {e}")))?; - // Auxiliary imports return only a document and cannot surface the preview's fidelity warning. - // Open has its own warning-preserving path; never silently place or process a thumbnail. - if r.preview_only { - return Err(EngineError::Other(format!( - "{name}: only this Affinity file's embedded preview could be read; open it with File › Open to see the warning, or export PSD or PNG from Affinity before using it here" - ))); - } - Ok(r) -} - -/// What a headless save writes beyond the format: JPEG quality and format, TIFF layers, Targa -/// bits, DPX bits, DDS compression and mipmaps, PSD previews and the PSD merged image. -#[derive(Debug, Clone, Copy)] -pub(crate) struct SaveOpts { - /// Photoshop's 0–12 JPEG scale. - pub quality: Option, - /// JPEG Options › Format Options (`"jpegFormat"`); unset, Baseline ("Standard"). - pub jpeg_format: Option, - /// TIFF: keep the layers. Off unless a command's params ask (`"tiffLayers": true`). - pub tiff_layers: bool, - /// Targa: 24 or 32 bits per pixel (`"tgaBits"`); unset, 32 with an alpha channel or - /// transparency, else 24. - pub tga_bits: Option, - /// DPX: 8, 10, 12 or 16 bits per sample (`"dpxBits"`); unset, 8 for an 8-bit document, else 16. - pub dpx_bits: Option, - /// TIFF: the image compression (`"tiffCompression": "none" | "lzw" | "zip"`); unset, none. - pub tiff_compression: Option, - /// DDS: the compression and whether to write the mip chain (`"ddsCompression"`, - /// `"ddsMipmaps"`); unset, uncompressed without mipmaps. - pub dds: photocraft_io::DdsOptions, - /// PSD/PSB: embed the thumbnail resource (Preferences › File Handling › Image Previews). - pub image_previews: bool, - /// PSD/PSB: write the real merged image (Preferences › File Handling › Maximize PSD and PSB - /// File Compatibility). - pub psd_maximize_compatibility: bool, -} - -impl Default for SaveOpts { - fn default() -> Self { - SaveOpts { - quality: None, - jpeg_format: None, - tiff_layers: false, - tga_bits: None, - dpx_bits: None, - tiff_compression: None, - dds: photocraft_io::DdsOptions::default(), - image_previews: true, - psd_maximize_compatibility: true, - } - } -} - -impl SaveOpts { - /// `quality`, `jpegFormat`, `tiffLayers` and `tgaBits` from command `cmd`'s params (a - /// `jpegFormat` it doesn't name or a `tgaBits` other than 24 or 32 is an error); the image - /// previews and the PSD merged image from the session's File Handling preferences (Ask When - /// Saving has no dialog here, so it saves them, as Photoshop's Save As checkbox and its - /// Maximize Compatibility checkbox both start on). - pub(crate) fn from_params(s: &Session, p: &Value, cmd: &str) -> Result { - let file_handling = &s.prefs().file_handling; - Ok(SaveOpts { - quality: f64_param(p, "quality"), - jpeg_format: jpeg_format_param(p, cmd)?, - tiff_layers: p.get("tiffLayers").and_then(Value::as_bool).unwrap_or(false), - tga_bits: tga_bits_param(p, cmd)?, - dpx_bits: dpx_bits_param(p, cmd)?, - tiff_compression: tiff_compression_param(p, cmd)?, - dds: dds_param(p, cmd)?.unwrap_or_default(), - image_previews: file_handling.image_previews != crate::prefs::Ask::Never, - psd_maximize_compatibility: file_handling.maximize_psd_compatibility != crate::prefs::Ask::Never, - }) - } - - pub(crate) fn or_quality(mut self, q: f64) -> Self { - self.quality = self.quality.or(Some(q)); - self - } -} - -impl From> for SaveOpts { - fn from(quality: Option) -> Self { - SaveOpts { quality, ..Default::default() } - } -} - -/// The Targa bits per pixel in `p` (`"tgaBits": 24 | 32`; absent or null: the automatic choice). -/// Anything else is a bad parameter of command `cmd`. Shared by every save that takes it (the -/// engine's commands, the app's Save As and control channel, the headless server). -pub fn tga_bits_param(p: &Value, cmd: &str) -> Result> { - match p.get("tgaBits") { - None | Some(Value::Null) => Ok(None), - Some(v) => v - .as_u64() - .and_then(photocraft_io::TgaBits::from_bits) - .map(Some) - .ok_or_else(|| EngineError::BadParams { cmd: cmd.into(), msg: format!("`tgaBits` must be 24 or 32, got {v}") }), - } -} - -/// The TIFF compression in `p` (`"tiffCompression": "none" | "lzw" | "zip"`, Photoshop's TIFF -/// Options; absent or null: none). Anything else is a bad parameter of command `cmd` (#5301). -pub fn tiff_compression_param(p: &Value, cmd: &str) -> Result> { - use photocraft_codecs::TiffCompression; - match p.get("tiffCompression") { - None | Some(Value::Null) => Ok(None), - Some(v) => match v.as_str() { - Some("none") => Ok(Some(TiffCompression::None)), - Some("lzw") => Ok(Some(TiffCompression::Lzw)), - Some("zip") => Ok(Some(TiffCompression::Deflate)), - _ => Err(EngineError::BadParams { cmd: cmd.into(), msg: format!("`tiffCompression` must be \"none\", \"lzw\" or \"zip\", got {v}") }), - }, - } -} - -/// The JPEG format in `p` (`"jpegFormat": "baseline" | "optimized" | "progressive"`; absent or -/// null: Baseline). Anything else is a bad parameter of command `cmd`. Shared like -/// [`tga_bits_param`]. -pub fn jpeg_format_param(p: &Value, cmd: &str) -> Result> { - match p.get("jpegFormat") { - None | Some(Value::Null) => Ok(None), - Some(v) => v.as_str().and_then(photocraft_codecs::JpegFormat::parse).map(Some).ok_or_else(|| EngineError::BadParams { - cmd: cmd.into(), - msg: format!("`jpegFormat` must be \"baseline\", \"optimized\" or \"progressive\", got {v}"), - }), - } -} - -/// Photoshop's 0–12 JPEG quality as the encoder's 1–100 (0 → 1, 12 → 100, linear between; out of -/// range is clamped, and NaN or infinite is 100). -pub fn jpeg_quality(q: f64) -> u8 { - if q.is_finite() { (q.clamp(0.0, 12.0) / 12.0 * 99.0 + 1.0).round() as u8 } else { 100 } -} - -/// The DPX bits per sample in `p` (`"dpxBits": 8 | 10 | 12 | 16`; absent or null: the document's -/// depth). Anything else is a bad parameter of command `cmd`. -pub fn dpx_bits_param(p: &Value, cmd: &str) -> Result> { - match p.get("dpxBits") { - None | Some(Value::Null) => Ok(None), - Some(v) => v - .as_u64() - .and_then(photocraft_io::DpxBits::from_bits) - .map(Some) - .ok_or_else(|| EngineError::BadParams { cmd: cmd.into(), msg: format!("`dpxBits` must be 8, 10, 12 or 16, got {v}") }), - } -} - -/// The DDS options in `p`: `"ddsCompression": "none" | "bc1" | "bc2" | "bc3"` (or the DXT names) -/// and `"ddsMipmaps": bool`. `None` when neither is given (Save As then asks); either alone -/// leaves the other at its default (uncompressed, no mipmaps). Anything else is a bad parameter -/// of command `cmd`. -pub fn dds_param(p: &Value, cmd: &str) -> Result> { - let bad = |msg: String| EngineError::BadParams { cmd: cmd.into(), msg }; - let compression = match p.get("ddsCompression") { - None | Some(Value::Null) => None, - Some(v) => Some( - v.as_str() - .and_then(photocraft_io::DdsCompression::from_name) - .ok_or_else(|| bad(format!("`ddsCompression` must be \"none\", \"bc1\", \"bc2\" or \"bc3\", got {v}")))?, - ), - }; - let mipmaps = match p.get("ddsMipmaps") { - None | Some(Value::Null) => None, - Some(v) => Some(v.as_bool().ok_or_else(|| bad(format!("`ddsMipmaps` must be true or false, got {v}")))?), - }; - if compression.is_none() && mipmaps.is_none() { - return Ok(None); - } - Ok(Some(photocraft_io::DdsOptions { compression: compression.unwrap_or_default(), mipmaps: mipmaps.unwrap_or(false) })) -} - -/// Encodes `doc` for `path`'s extension. -pub(crate) fn encode(doc: &Document, path: &str, save: impl Into) -> Result<(Vec, Vec)> { - crate::allocation::checkpoint("saving document")?; - let save = save.into(); - let mut opts = photocraft_io::ExportOptions { - tiff_layers: save.tiff_layers, - tga_bits: save.tga_bits, - image_previews: save.image_previews, - psd_maximize_compatibility: save.psd_maximize_compatibility, - // Linked files a PSD embeds are resolved against the document being worked on. - document_path: crate::doc_path::current(), - // An untrusted session's stored paths are document data: embed none of them. - read_linked_files: !crate::jobs::authorization_installed(), - ..Default::default() - }; - // No quality chosen: write the file the way it was opened (a JPEG at its own quality, a WebP - // lossy or lossless as it was), as Photoshop's Save does. - photocraft_io::apply_file_encoding(doc, &mut opts.encode); - opts.encode.dpx_bits = save.dpx_bits; - if let Some(c) = save.tiff_compression { - opts.encode.tiff_compression = c; - } - opts.encode.dds = save.dds; - if let Some(q) = save.quality { - let q = jpeg_quality(q); - opts.encode.jpeg_quality = q; - // A quality on a WebP save asks for the lossy encoder; the default WebP stays lossless. - opts.encode.webp_quality = q; - opts.encode.webp_lossless = false; - } - if let Some(f) = save.jpeg_format { - opts.encode.jpeg_format = f; - } - photocraft_io::export(doc, path, &opts).map(|r| (r.bytes, r.warnings)).map_err(|e| EngineError::Other(format!("{path}: {e}"))) -} - -pub(crate) fn save_doc(doc: &Document, path: &str, save: impl Into) -> Result> { - let (bytes, warnings) = encode(doc, path, save)?; - write_file(path, &bytes)?; - Ok(warnings) -} - -pub(crate) fn str_param<'a>(p: &'a Value, key: &str, cmd: &str) -> Result<&'a str> { - p.get(key).and_then(Value::as_str).filter(|v| !v.is_empty()).ok_or_else(|| EngineError::BadParams { cmd: cmd.into(), msg: format!("missing \"{key}\"") }) -} - -pub(crate) fn f64_param(p: &Value, key: &str) -> Option { - p.get(key).and_then(Value::as_f64).filter(|v| v.is_finite()) -} - -/// A size parameter; zero or negative means "not set" (dialogs send 0 for empty fields). -fn size_param(p: &Value, key: &str) -> Option { - f64_param(p, key).filter(|v| *v > 0.0) -} - -// ---------- pixels ---------- - -/// A composite buffer as a surface in `fmt` (straight RGBA → the format's model and depth). -pub(crate) fn buffer_surface(buf: &photocraft_compose::Buffer, fmt: PixelFormat) -> Surface { - let n = fmt.channels(); - let mut data = vec![0.0f32; buf.px.len() * n]; - for (p, out) in buf.px.iter().zip(data.chunks_exact_mut(n)) { - from_rgba_into(&fmt, *p, out); - } - let mut s = Surface::new(fmt); - if !buf.rect.is_empty() { - s.write_region(buf.rect, &data); - } - s.prune(); - s -} - -/// The flattened image of `doc` as a surface in `fmt`, placed at the origin. -pub(crate) fn flattened(doc: &Document, fmt: PixelFormat) -> Surface { - photocraft_compose::flatten_to_surface(doc, fmt, None) -} - -/// [`flattened`] for documents that came from a file (Save a Copy, Place, Load Files into Stack): -/// a sparse bundle declares its canvas, and one the size of the format allows would be rendered -/// in full, however little it holds. Refused past the compositor's own per-render limit. -pub(crate) fn flattened_checked(doc: &Document, fmt: PixelFormat, cmd: &str) -> Result { - let b = doc.bounds(); - if u64::from(b.width()) * u64::from(b.height()) > photocraft_compose::MAX_RENDER_PIXELS { - return Err(EngineError::BadParams { cmd: cmd.into(), msg: format!("the document's {}×{} canvas is too large to flatten", b.width(), b.height()) }); - } - Ok(flattened(doc, fmt)) -} - -// ---------- close / revert / save a copy / open as ---------- - -fn close_all(s: &mut Session) -> Result { - let n = s.documents().len(); - while !s.documents().is_empty() { - s.close(s.documents().len() - 1); - } - Ok(json!({"closed": n})) -} - -fn close_others(s: &mut Session, p: &Value) -> Result { - let keep = p.get("document").and_then(Value::as_u64).map(|v| v as usize).or(s.active_index()).ok_or(EngineError::NoDocument)?; - if keep >= s.documents().len() { - return Err(EngineError::BadParams { cmd: "file.closeOthers".into(), msg: format!("no document {keep}") }); - } - let n = s.documents().len() - 1; - for i in (0..s.documents().len()).rev() { - if i != keep { - s.close(i); - } - } - s.set_active(0); - Ok(json!({"closed": n})) -} - -/// File › Revert: reload the saved file as one history step (undoable, like Photoshop's -/// "Revert" history state); the document is clean afterwards. -fn revert(s: &mut Session) -> Result { - let path = s.active().and_then(|d| d.path.clone()).ok_or(EngineError::Other("the document has never been saved".into()))?; - let bytes = read_file(&path)?; - let fresh = import_opened(s, &file_name(&path), &bytes)?; - s.edit("Revert", |doc, active| { - let (id, name) = (doc.id, doc.name.clone()); - *doc = fresh; - // Keep the identity (colour state, views and caches are keyed by it) and the tab name. - doc.id = id; - doc.name = name; - *active = doc.top_layer(); - Ok(()) - })?; - let st = s.active_mut().ok_or(EngineError::NoDocument)?; - st.saved_revision = st.revision; - Ok(json!({"path": path, "layers": st.doc.layers.len()})) -} - -fn save_a_copy(s: &mut Session, p: &Value) -> Result { - let path = str_param(p, "path", "file.saveACopy")?.to_string(); - let d = s.active().ok_or(EngineError::NoDocument)?; - // A copy over the document's own file replaces it, and a flat or lossy format can't be - // undone, so it takes an explicit `overwrite` (#7437). The desktop dialog writes through the - // shell, after the OS has confirmed the replace. - if d.path.as_deref().is_some_and(|own| same_file(&path, own)) && p.get("overwrite").and_then(Value::as_bool) != Some(true) { - return Err(EngineError::BadParams { - cmd: "file.saveACopy".into(), - msg: "`path` is the document's own file, so the copy would replace it: choose another path, or pass \"overwrite\": true".into(), - }); - } - let mut doc = (*d.doc).clone(); - if p.get("layers").and_then(Value::as_bool) == Some(false) { - // "Layers" unchecked in Save a Copy: write the flattened image. - let fmt = doc.pixel_format(); - let px = flattened_checked(&doc, fmt, "file.saveACopy")?; - doc.layers = vec![Layer::new("Background", LayerContent::Raster(px))]; - } - let warnings = save_doc(&doc, &path, SaveOpts::from_params(s, p, "file.saveACopy")?)?; - Ok(json!({"path": path, "warnings": warnings})) -} - -/// Open a file's bytes, decoding them as the format `as_ext` (Open As) when given. -/// EXR/HDR rarely states its colour space, so io tags it with the linear-sRGB default. -/// With File Handling's ACEScg option on, such an EXR opens as ACEScg instead (AP1, -/// linear) — the working space ACES render pipelines write. Only the io default is -/// replaced; an embedded or EXIF-declared profile is kept untouched. -pub(crate) fn tag_exr_colorspace(s: &Session, name: &str, doc: &mut Document) { - if !name.to_ascii_lowercase().ends_with(".exr") || !s.prefs.get().file_handling.exr_aces_cg { - return; - } - let linear = photocraft_cms::Builtin::LinearSrgb.profile().to_bytes(); - if doc.icc_profile.as_ref().map(|v| v.as_slice()) == Some(linear.as_slice()) { - doc.icc_profile = Some(photocraft_cms::Builtin::AcesCg.profile().to_bytes()); - } -} - -/// Edit › Preferences › Raw Defaults › Resolution: the ppi a raw developed on open gets, as -/// Camera Raw's workflow options set it (the raw itself states none). `warnings` are the -/// import's notes, which say whether the raw was developed or only its preview opened. -pub fn raw_defaults(s: &Session, warnings: &[String], doc: &mut Document) { - raw_resolution(s.prefs().raw_defaults.resolution, warnings, doc); -} - -fn raw_resolution(ppi: f64, warnings: &[String], doc: &mut Document) { - if ppi.is_finite() && warnings.iter().any(|w| w.contains(photocraft_io::raw::DEVELOPED_NOTE)) { - doc.resolution_dpi = ppi.clamp(1.0, 10_000.0) as f32; - } -} - -pub fn open_bytes_as(s: &mut Session, name: &str, bytes: &[u8], as_ext: Option<&str>, path: Option) -> Result { - crate::allocation::checkpoint("importing document")?; - let decode_name = match as_ext { - Some(ext) => format!("{}.{}", stem(name), ext.trim_start_matches('.')), - None => name.to_string(), - }; - let r = photocraft_io::import(&decode_name, bytes).map_err(|e| EngineError::Other(format!("{decode_name}: {e}")))?; - let mut doc = r.document; - tag_exr_colorspace(s, &decode_name, &mut doc); - raw_defaults(s, &r.warnings, &mut doc); - let path = match template_name(s, name) { - Some(untitled) => { - doc.name = untitled; - None - } - None => { - doc.name = file_name(name); - path - } - }; - // Color Settings policies (preserve / convert / discard the embedded profile). - let (i, color) = s.open_document(doc, path.filter(|_| !r.source_read_only)); - if let Some(st) = s.active_mut() { - st.source_read_only = r.source_read_only; - } - // Import notes (e.g. how a camera raw was developed, or that only its preview opened). - Ok(json!({"document": i, "color": color, "warnings": r.warnings})) -} - -fn open_as(s: &mut Session, p: &Value) -> Result { - let path = str_param(p, "path", "file.openAs")?.to_string(); - let bytes = read_file(&path)?; - let as_ext = p.get("as").or_else(|| p.get("format")).and_then(Value::as_str); - open_bytes_as(s, &path, &bytes, as_ext, Some(path.clone())) -} - -// ---------- place ---------- - -/// History label of an embedded place. -pub const PLACE_EMBEDDED: &str = "Place Embedded"; - -/// Place a file's bytes as a smart object layer, centred, and (with Preferences ▸ General ▸ -/// Resize Image During Place, on by default) scaled down to fit when larger than the canvas. -/// `linked` makes it a linked smart object that refers to that path instead of embedding the bytes. -/// With Preferences ▸ General ▸ Always Create Smart Objects When Placing off, an embedded place -/// lands as a plain pixel layer instead (an explicit `"smartObject": false` asks for one). -pub fn place_bytes(s: &mut Session, name: &str, bytes: Vec, linked: Option, p: &Value) -> Result { - let d = s.active().ok_or(EngineError::NoDocument)?; - let (cw, ch) = (d.doc.size.width as f64, d.doc.size.height as f64); - let fmt = d.doc.pixel_format(); - let vector = photocraft_io::svg::is_svg(&bytes); - let opts = crate::jobs::import_options(s.prefs()); - let imported = photocraft_io::import_with_options(name, &bytes, &opts).map_err(|e| EngineError::Other(format!("{name}: {e}")))?; - if imported.preview_only { - return Err(EngineError::Other(format!( - "{name}: only this Affinity file's embedded preview could be read; open it with File › Open to see the warning, or export PSD or PNG from Affinity before using it here" - ))); - } - let src = imported.document; - let (w, h) = (src.size.width as f64, src.size.height as f64); - // The implicit `fit` is Preferences ▸ General ▸ Resize Image During Place (on by default). - let fit = p.get("fit").and_then(Value::as_bool).unwrap_or(s.prefs().general.resize_image_during_place); - let scale = match f64_param(p, "scale") { - Some(k) => (k / 100.0).max(1e-4), - None if fit && (w > cw || h > ch) => (cw / w).min(ch / h), - None => 1.0, - }; - let center = match p.get("center").and_then(Value::as_array) { - Some(c) if c.len() == 2 => (c[0].as_f64().unwrap_or(cw / 2.0), c[1].as_f64().unwrap_or(ch / 2.0)), - _ => (cw / 2.0, ch / 2.0), - }; - let (dx, dy) = ((center.0 - w * scale / 2.0).round(), (center.1 - h * scale / 2.0).round()); - let mut px = flattened_checked(&src, fmt, "file.place")?; - if (scale - 1.0).abs() > 1e-9 { - px = resize_surface(&px, scale, scale, Resample::Bicubic); - } - let px = translate_surface(&px, dx as i32, dy as i32); - // Preferences ▸ General ▸ Always Create Smart Objects When Placing (on by default): off, an - // embedded place lands as a plain pixel layer. A linked place is always a smart object. - let smart = linked.is_some() || p.get("smartObject").and_then(Value::as_bool).unwrap_or(s.prefs().general.always_create_smart_objects_when_placing); - let source = match linked { - Some(path) => SmartSource::Linked { path }, - None => SmartSource::Embedded { file_name: file_name(name), bytes: Arc::new(bytes) }, - }; - let layer_name = stem(name); - let label = if matches!(&source, SmartSource::Linked { .. }) { "Place Linked" } else { PLACE_EMBEDDED }; - let id = s.edit(label, |doc, active| { - let layer = if smart { - let mut so = SmartObject::new(source, Affine { m: [scale, 0.0, 0.0, scale, dx, dy] }, Some(px)); - // A vector source (SVG) renders at its placement scale instead of as a resampled raster. - if vector && let Some(sharp) = crate::smart_cmds::render(doc, &so)? { - so.cache = Some(sharp); - } - Layer::new(layer_name, LayerContent::Smart(so)) - } else { - Layer::new(layer_name, LayerContent::Raster(px)) - }; - let id = doc.insert_above(*active, layer); - *active = Some(id); - Ok(id) - })?; - Ok(json!({"layer": id.0, "scale": scale * 100.0, "bounds": [dx, dy, dx + w * scale, dy + h * scale], "smartObject": smart})) -} - -fn place(s: &mut Session, p: &Value, linked: bool) -> Result { - let cmd = if linked { "file.placeLinked" } else { "file.placeEmbedded" }; - let path = str_param(p, "path", cmd)?.to_string(); - let bytes = read_file(&path)?; - // The link is stored absolute: a relative one would later be taken from the document's - // folder (`doc_path`), not the working directory the path was given in. - let link = linked.then(|| { - if std::path::Path::new(&path).is_relative() { - std::path::absolute(&path).map_or_else(|_| path.clone(), |a| a.to_string_lossy().into_owned()) - } else { - path.clone() - } - }); - place_bytes(s, &path, bytes, link, p) -} - -// ---------- File Info (XMP) ---------- - -/// The File Info fields we edit, as (JSON key, XMP property, container kind). -const INFO_FIELDS: [(&str, &str, &str); 6] = [ - ("title", "dc:title", "Alt"), - ("author", "dc:creator", "Seq"), - ("description", "dc:description", "Alt"), - ("keywords", "dc:subject", "Bag"), - ("copyright", "dc:rights", "Alt"), - ("authorTitle", "photoshop:AuthorsPosition", ""), -]; - -fn xml_escape(s: &str) -> String { - s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """) -} - -fn xml_unescape(s: &str) -> String { - let mut out = String::with_capacity(s.len()); - let mut rest = s; - while let Some(i) = rest.find('&') { - out.push_str(&rest[..i]); - rest = &rest[i..]; - let decoded = rest.as_bytes().iter().take(13).position(|&b| b == b';').and_then(|e| { - let c = match &rest[1..e] { - "lt" => '<', - "gt" => '>', - "quot" => '"', - "apos" => '\'', - "amp" => '&', - n => { - let n = n.strip_prefix('#')?; - let code = match n.strip_prefix(['x', 'X']) { - Some(h) => u32::from_str_radix(h, 16).ok()?, - None => n.parse().ok()?, - }; - char::from_u32(code)? - } - }; - Some((c, e + 1)) - }); - match decoded { - Some((c, len)) => { - out.push(c); - rest = &rest[len..]; - } - None => { - out.push('&'); - rest = &rest[1..]; - } - } - } - out.push_str(rest); - out -} - -/// The element `…` (first occurrence) as (start, end, inner). -fn find_element<'a>(xmp: &'a str, tag: &str) -> Option<(usize, usize, &'a str)> { - let open = format!("<{tag}"); - let mut from = 0; - while let Some(i) = xmp[from..].find(&open).map(|i| i + from) { - let after = xmp[i + open.len()..].chars().next(); - if matches!(after, Some('>' | ' ' | '/' | '\n' | '\r' | '\t')) { - let gt = xmp[i..].find('>')? + i; - if xmp[..gt].ends_with('/') { - return Some((i, gt + 1, "")); - } - let close = format!(""); - let c = xmp[gt..].find(&close)? + gt; - return Some((i, c + close.len(), &xmp[gt + 1..c])); - } - from = i + open.len(); - } - None -} - -/// `rdf:li` values of a container (or the element text for simple properties). -fn li_values(inner: &str) -> Vec { - let mut out = Vec::new(); - let mut rest = inner; - while let Some((a, b, v)) = find_element(rest, "rdf:li") { - out.push(xml_unescape(v.trim())); - rest = &rest[b..]; - let _ = a; - } - if out.is_empty() && !inner.contains('<') && !inner.trim().is_empty() { - out.push(xml_unescape(inner.trim())); - } - out -} - -/// Attribute form `prop="value"` on an `rdf:Description`. -fn find_attr<'a>(xmp: &'a str, prop: &str) -> Option<(usize, usize, &'a str)> { - let key = format!(" {prop}=\""); - let i = xmp.find(&key)?; - let v0 = i + key.len(); - let v1 = xmp[v0..].find('"')? + v0; - Some((i, v1 + 1, &xmp[v0..v1])) -} - -/// File Info fields read from an XMP packet. -pub fn read_file_info(xmp: Option<&str>) -> Value { - let mut m = serde_json::Map::new(); - let x = xmp.unwrap_or(""); - for (key, prop, kind) in INFO_FIELDS { - let vals = match find_element(x, prop) { - Some((_, _, inner)) => li_values(inner), - None => find_attr(x, prop).map(|(_, _, v)| vec![xml_unescape(v)]).unwrap_or_default(), - }; - let v = if kind == "Bag" { - json!(vals) - } else if kind == "Seq" { - json!(vals.join("; ")) - } else { - json!(vals.into_iter().next().unwrap_or_default()) - }; - m.insert(key.into(), v); - } - let marked = - find_element(x, "xmpRights:Marked").map(|(_, _, v)| v.trim().to_string()).or_else(|| find_attr(x, "xmpRights:Marked").map(|(_, _, v)| v.to_string())); - m.insert( - "copyrightStatus".into(), - json!(match marked.as_deref() { - Some("True") => "copyrighted", - Some("False") => "publicDomain", - _ => "unknown", - }), - ); - let url = find_element(x, "xmpRights:WebStatement") - .map(|(_, _, v)| xml_unescape(v.trim())) - .or_else(|| find_attr(x, "xmpRights:WebStatement").map(|(_, _, v)| xml_unescape(v))); - m.insert("copyrightUrl".into(), json!(url.unwrap_or_default())); - Value::Object(m) -} - -/// File Info's read-only Camera Data, as (result key, English label) in display order. -pub const CAMERA_FIELDS: [(&str, &str); 9] = [ - ("make", "Make"), - ("model", "Model"), - ("dateTaken", "Date Taken"), - ("exposure", "Exposure"), - ("fNumber", "F-Stop"), - ("iso", "ISO Speed"), - ("focalLength", "Focal Length"), - ("focalLength35mm", "Focal Length (35 mm)"), - ("lens", "Lens"), -]; - -/// `v` with at most `decimals` decimals and no trailing zeros (33.10 → "33.1", 8.0 → "8"). -fn short_num(v: f64, decimals: usize) -> String { - let s = format!("{v:.decimals$}"); - if s.contains('.') { s.trim_end_matches('0').trim_end_matches('.').to_string() } else { s } -} - -/// `v` to three significant digits, with no trailing zeros (0.031714 → "0.0317", 0.4 → "0.4"). -/// Two decimals threw away most of a slow shutter speed: a stored 0.031714 s printed as "0.03 s", -/// which is 5 % off, and a stored 0.0215 s printed as "0.02 s", 7 % off (#6958). -fn sig3(v: f64) -> String { - let magnitude = v.abs().log10().floor(); - // Clamped at both ends: a value at the large end must not ask for a negative field width, and - // at the small end the field is widened rather than truncated, so a positive exposure never - // reads as "0 s". 320 is beyond f64's decimal range, so it always terminates. - let decimals = if magnitude.is_finite() { (2.0 - magnitude).clamp(0.0, 320.0) } else { 0.0 }; - short_num(v, decimals as usize) -} - -/// Exposure time as cameras print it: "1/250 s" for fractions of a second, "0.4 s" or "2 s" -/// when the reciprocal isn't a whole number or the exposure is a second or longer. -fn exposure_text(t: f64) -> Option { - if !(t.is_finite() && t > 0.0) { - return None; - } - let r = 1.0 / t; - let n = r.round(); - // Below 1/10 s the reciprocal is above 10, so its nearest whole number puts the shown time - // within 5 % of the stored one, and is the form a photographer expects ("1/32 s"). The test - // used to be relative to the reciprocal, so it shrank as the exposure slowed: under 1/50 s it - // fell below half a rounding step and nearly every fraction fell through to the decimal form - // (#6958). Above 1/10 s the fraction is only right when the reciprocal is very nearly whole - // (1/2 s, 1/4 s) — 0.4 s stays "0.4 s" rather than becoming "1/3 s". - let fraction = n.is_finite() && (1.0..=1e9).contains(&n) && (t < 0.1 || (t < 1.0 && n > 1.0 && (r - n).abs() <= r * 0.01)); - if fraction { - return Some(format!("1/{} s", n as u64)); - } - Some(format!("{} s", sig3(t))) -} - -/// EXIF (`2024:02:17 12:40:19`) or XMP (`2024-02-17T12:40:19.00+01:00`) dates as -/// `2024-02-17 12:40:19`; anything else is shown as stored. -fn date_text(s: &str) -> String { - let b = s.trim().as_bytes(); - let digits = |r: &[usize]| r.iter().all(|&i| b.get(i).is_some_and(u8::is_ascii_digit)); - let sep = |i: usize, set: &[u8]| b.get(i).is_some_and(|c| set.contains(c)); - let ch = |i: usize| b.get(i).map_or('0', |&c| c as char); - let part = |r: std::ops::Range| r.map(ch).collect::(); - if !(digits(&[0, 1, 2, 3, 5, 6, 8, 9]) && sep(4, b":-") && sep(7, b":-")) { - return s.trim().to_string(); - } - let date = format!("{}-{}-{}", part(0..4), part(5..7), part(8..10)); - if digits(&[11, 12, 14, 15, 17, 18]) && sep(10, b" T") && sep(13, b":") && sep(16, b":") { format!("{date} {}", part(11..19)) } else { date } -} - -/// A single XMP value: the first `rdf:li` of a container, element text or attribute. -fn xmp_value(x: &str, prop: &str) -> Option { - let v = match find_element(x, prop) { - Some((_, _, inner)) => li_values(inner).into_iter().next(), - None => find_attr(x, prop).map(|(_, _, v)| xml_unescape(v)), - }?; - let v = v.trim().to_string(); - (!v.is_empty()).then_some(v) -} - -/// An XMP number: a rational "331/10" or a decimal. -fn xmp_number(x: &str, prop: &str) -> Option { - let v = xmp_value(x, prop)?; - let n = match v.split_once('/') { - Some((a, b)) => { - let (a, b) = (a.trim().parse::().ok()?, b.trim().parse::().ok()?); - (b != 0.0).then(|| a / b)? - } - None => v.parse::().ok()?, - }; - n.is_finite().then_some(n) -} - -/// File Info's read-only Camera Data (keys of [`CAMERA_FIELDS`], present ones only), formatted -/// for display. Read from the EXIF block (JPEG APP1, PSD resource 1058, …); properties it lacks -/// fall back to the XMP `tiff:`/`exif:`/`aux:` copies (files without an EXIF block). -pub fn camera_data(exif: Option<&[u8]>, xmp: Option<&str>) -> Value { - let e = exif.map(photocraft_algo::exif::read).unwrap_or_default(); - let x = xmp.unwrap_or(""); - let text = |v: Option, props: &[&str]| v.or_else(|| props.iter().find_map(|p| xmp_value(x, p))); - let num = - |v: Option, props: &[&str]| v.filter(|v| v.is_finite() && *v > 0.0).or_else(|| props.iter().find_map(|p| xmp_number(x, p))).filter(|v| *v > 0.0); - let values = [ - text(e.make, &["tiff:Make"]), - text(e.model, &["tiff:Model"]), - text(e.date_taken, &["exif:DateTimeOriginal"]).map(|d| date_text(&d)), - num(e.exposure_time, &["exif:ExposureTime"]).and_then(exposure_text), - num(e.f_number, &["exif:FNumber"]).map(|n| format!("f/{}", short_num(n, 1))), - num(e.iso, &["exif:ISOSpeedRatings", "exifEX:PhotographicSensitivity"]).map(|n| format!("ISO {}", n.round())), - num(e.focal_length, &["exif:FocalLength"]).map(|f| format!("{} mm", short_num(f, 1))), - num(e.focal_length_35mm, &["exif:FocalLengthIn35mmFilm"]).map(|f| format!("{} mm", short_num(f, 1))), - text(e.lens, &["exifEX:LensModel", "aux:Lens"]), - ]; - let mut m = serde_json::Map::new(); - for ((key, _), v) in CAMERA_FIELDS.into_iter().zip(values) { - // Hostile files can carry megabytes of "lens name"; the dialog shows a line. - if let Some(v) = v.map(|v| v.chars().take(200).collect::()).filter(|v| !v.is_empty()) { - m.insert(key.into(), json!(v)); - } - } - Value::Object(m) -} - -/// Rewrites only changed File Info fields of an XMP packet (creating one when there is none), -/// keeping the other properties verbatim. Edited properties move into their own -/// `rdf:Description` (several descriptions per packet are valid XMP). -pub fn write_file_info(xmp: Option<&str>, info: &Value) -> String { - let cur = read_file_info(xmp); - // The dialog submits all fields, including unchanged language alternatives. - let changed = |key: &str| info.get(key).is_some_and(|v| cur.get(key) != Some(v)); - let mut x = xmp.filter(|s| s.contains("")).map(str::to_string).unwrap_or_else(|| { - "\n\n \n \n\n".to_string() - }); - for (key, prop, _) in INFO_FIELDS.into_iter().chain([("copyrightStatus", "xmpRights:Marked", ""), ("copyrightUrl", "xmpRights:WebStatement", "")]) { - if !changed(key) { - continue; - } - while let Some((a, b, _)) = find_element(&x, prop) { - x.replace_range(a..b, ""); - } - while let Some((a, b, _)) = find_attr(&x, prop) { - x.replace_range(a..b, ""); - } - } - let get = |k: &str| info.get(k).filter(|_| changed(k)).cloned().unwrap_or(Value::Null); - let mut body = String::new(); - for (key, prop, kind) in INFO_FIELDS { - let vals: Vec = match get(key) { - Value::Array(a) => a.iter().filter_map(|v| v.as_str()).map(str::to_string).filter(|v| !v.is_empty()).collect(), - Value::String(s) if kind == "Bag" || kind == "Seq" => s.split([';', ',']).map(|v| v.trim().to_string()).filter(|v| !v.is_empty()).collect(), - Value::String(s) if !s.is_empty() => vec![s], - _ => Vec::new(), - }; - if vals.is_empty() { - continue; - } - let items: String = vals - .iter() - .map(|v| { - if kind == "Alt" { format!("{}", xml_escape(v)) } else { format!("{}", xml_escape(v)) } - }) - .collect(); - if kind.is_empty() { - body.push_str(&format!(" <{prop}>{}\n", xml_escape(&vals[0]))); - } else { - body.push_str(&format!(" <{prop}>{items}\n")); - } - } - match get("copyrightStatus").as_str() { - Some("copyrighted") => body.push_str(" True\n"), - Some("publicDomain") => body.push_str(" False\n"), - _ => {} - } - if let Some(u) = get("copyrightUrl").as_str().filter(|u| !u.is_empty()) { - body.push_str(&format!(" {}\n", xml_escape(u))); - } - if !body.is_empty() { - let desc = format!( - " \n{body} \n " - ); - let at = x.rfind("").unwrap_or(x.len()); - x.insert_str(at, &desc); - } - x -} - -fn file_info(s: &mut Session, p: &Value) -> Result { - let keys = ["title", "author", "authorTitle", "description", "keywords", "copyright", "copyrightStatus", "copyrightUrl"]; - let edits = p.as_object().is_some_and(|m| m.keys().any(|k| keys.contains(&k.as_str()))); - if edits { - let xmp = s.active().ok_or(EngineError::NoDocument)?.doc.metadata.xmp.clone(); - let new = write_file_info(xmp.as_deref(), p); - s.edit("File Info", |doc, _| { - doc.metadata.xmp = Some(new.into()); - Ok(()) - })?; - } - let d = s.active().ok_or(EngineError::NoDocument)?; - let mut info = read_file_info(d.doc.metadata.xmp.as_deref()); - if let Value::Object(m) = &mut info { - m.insert("camera".into(), camera_data(d.doc.metadata.exif.as_deref().map(Vec::as_slice), d.doc.metadata.xmp.as_deref())); - } - Ok(info) -} - -// ---------- Automate ---------- - -fn fit_image(s: &mut Session, p: &Value) -> Result { - let d = s.active().ok_or(EngineError::NoDocument)?; - let (w, h) = (d.doc.size.width as f64, d.doc.size.height as f64); - let bw = size_param(p, "width").unwrap_or(w); - let bh = size_param(p, "height").unwrap_or(h); - let k = (bw / w).min(bh / h); - if (k > 1.0 && p.get("dontEnlarge").and_then(Value::as_bool).unwrap_or(false)) || ((w * k).round() == w && (h * k).round() == h) { - return Ok(json!({"width": w, "height": h, "changed": false})); - } - let (nw, nh) = ((w * k).round().max(1.0), (h * k).round().max(1.0)); - let resample = p.get("resample").and_then(Value::as_str).unwrap_or("bicubic"); - s.execute("image.imageSize", json!({"width": nw, "height": nh, "resample": resample}))?; - Ok(json!({"width": nw, "height": nh, "changed": true})) -} - -fn mode_name(m: ColorMode) -> &'static str { - match m { - ColorMode::Bitmap => "bitmap", - ColorMode::Grayscale => "grayscale", - ColorMode::Duotone => "duotone", - ColorMode::Indexed => "indexed", - ColorMode::Rgb => "rgb", - ColorMode::Cmyk => "cmyk", - ColorMode::Lab => "lab", - ColorMode::Multichannel => "multichannel", - } -} - -fn conditional_mode_change(s: &mut Session, p: &Value) -> Result { - let cmd = "file.automate.conditionalModeChange"; - let to = str_param(p, "to", cmd)?.to_ascii_lowercase(); - let to = match to.as_str() { - "gray" | "grayscale" => "grayscale", - "rgb" => "rgb", - "cmyk" => "cmyk", - "lab" => "lab", - other => return Err(EngineError::BadParams { cmd: cmd.into(), msg: format!("unsupported target mode \"{other}\" (rgb, grayscale, cmyk, lab)") }), - }; - let cur = mode_name(s.active().ok_or(EngineError::NoDocument)?.doc.mode); - // One spelling per source mode, for the array and the single-string forms alike (#7042). - let norm = |v: &str| { - let v = v.to_ascii_lowercase(); - if v == "gray" { "grayscale".to_string() } else { v } - }; - let from: Vec = match p.get("from") { - Some(Value::Array(a)) => a.iter().filter_map(Value::as_str).map(norm).collect(), - Some(Value::String(v)) => vec![norm(v)], - _ => vec!["any".into()], - }; - if cur == to || !(from.iter().any(|f| f == "any" || f == cur)) { - return Ok(json!({"changed": false, "mode": cur})); - } - s.execute(&format!("image.mode.{to}"), json!({}))?; - Ok(json!({"changed": true, "mode": to})) -} - -/// One `[id, params]` / `{command, params}` / `{id, params}` step of an action. -fn parse_steps(v: &Value) -> Result> { - let bad = |m: &str| EngineError::BadParams { cmd: "file.automate.batch".into(), msg: m.into() }; - let arr = v.as_array().ok_or_else(|| bad("\"steps\" must be an array"))?; - arr.iter() - .map(|st| match st { - Value::Array(a) if !a.is_empty() => { - Ok((a[0].as_str().ok_or_else(|| bad("step id must be a string"))?.to_string(), a.get(1).cloned().unwrap_or(json!({})))) - } - Value::Object(o) => { - let id = o.get("command").or_else(|| o.get("id")).and_then(Value::as_str).ok_or_else(|| bad("step needs \"command\""))?; - Ok((id.to_string(), o.get("params").cloned().unwrap_or(json!({})))) - } - Value::String(id) => Ok((id.clone(), json!({}))), - _ => Err(bad("each step is [id, params] or {\"command\", \"params\"}")), - }) - .collect() -} - -/// Inputs of a batch command: `"input"` is a folder or an array of files. -pub(crate) fn batch_inputs(p: &Value, cmd: &str) -> Result> { - match p.get("input").or_else(|| p.get("files")) { - Some(Value::Array(a)) => Ok(a.iter().filter_map(Value::as_str).map(str::to_string).collect()), - Some(Value::String(dir)) => list_images(dir), - _ => Err(EngineError::BadParams { cmd: cmd.into(), msg: "missing \"input\" (folder or array of files)".into() }), - } -} - -/// One input of a batch run: the file, and the folder it sits in relative to the input folder -/// (`""` at the top level, `"a/b"` two levels down), which its result keeps under `output`. -#[derive(Clone, Debug, PartialEq)] -pub(crate) struct BatchInput { - pub path: String, - pub rel_dir: String, -} - -/// Subfolders below a batch input folder are walked at most this deep ("Include All Subfolders"). -pub(crate) const MAX_SUBFOLDER_DEPTH: usize = 32; -/// A batch over subfolders lists at most this many files; a larger tree is an error, not a run -/// that silently stops partway. -pub(crate) const MAX_SUBFOLDER_FILES: usize = 100_000; - -/// [`batch_inputs`] for the commands whose Photoshop dialog has "Include All Subfolders" (Batch, -/// Image Processor): with `"includeSubfolders": true` a folder input also yields the images in its -/// subfolders, each tagged with its relative folder. `output` (when inside the input folder, as -/// the dialog's default `/batch` is) is not walked, so a rerun doesn't process its results. -pub(crate) fn batch_inputs_tree(p: &Value, cmd: &str, output: &str) -> Result> { - let recurse = match p.get("includeSubfolders") { - None | Some(Value::Null) => false, - Some(Value::Bool(b)) => *b, - Some(_) => return Err(EngineError::BadParams { cmd: cmd.into(), msg: "\"includeSubfolders\" must be true or false".into() }), - }; - match p.get("input").or_else(|| p.get("files")) { - Some(Value::String(dir)) if recurse => list_images_tree(dir, output, cmd), - _ => Ok(batch_inputs(p, cmd)?.into_iter().map(|path| BatchInput { path, rel_dir: String::new() }).collect()), - } -} - -/// The images under `dir` and its subfolders: each folder's files sorted by name, then its -/// subfolders in name order (depth first). Bounded by [`MAX_SUBFOLDER_DEPTH`] and -/// [`MAX_SUBFOLDER_FILES`]; a folder reached twice (a symlink loop) is walked once, and `skip` -/// (the output folder) is left out. -#[cfg(not(target_arch = "wasm32"))] -pub(crate) fn list_images_tree(dir: &str, skip: &str, cmd: &str) -> Result> { - use std::path::{Path, PathBuf}; - let canon = |p: &Path| std::fs::canonicalize(p).ok(); - let root = Path::new(dir); - let root_canon = canon(root).ok_or_else(|| EngineError::Other(format!("{dir}: cannot open the folder")))?; - let skip = if skip.is_empty() { None } else { canon(Path::new(skip)) }; - let mut seen = std::collections::HashSet::new(); - seen.insert(root_canon); - let mut out = Vec::new(); - // Depth first with an explicit stack (no recursion): (folder, relative folder, depth). - let mut stack: Vec<(PathBuf, String, usize)> = vec![(root.to_path_buf(), String::new(), 0)]; - while let Some((folder, rel, depth)) = stack.pop() { - let shown = folder.to_string_lossy().into_owned(); - // The top folder must be readable; a subfolder that isn't is skipped. - let files = match list_images(&shown) { - Ok(f) => f, - Err(e) if depth == 0 => return Err(e), - Err(_) => continue, - }; - if out.len().saturating_add(files.len()) > MAX_SUBFOLDER_FILES { - return Err(EngineError::BadParams { cmd: cmd.into(), msg: format!("{dir} holds more than {MAX_SUBFOLDER_FILES} images with its subfolders") }); - } - out.extend(files.into_iter().map(|path| BatchInput { path, rel_dir: rel.clone() })); - if depth >= MAX_SUBFOLDER_DEPTH { - continue; - } - let Ok(rd) = std::fs::read_dir(&folder) else { continue }; - let mut subs: Vec<(String, PathBuf)> = rd - .filter_map(|e| e.ok()) - .map(|e| e.path()) - .filter(|p| p.is_dir()) - .filter_map(|p| Some((p.file_name()?.to_string_lossy().into_owned(), p))) - .collect(); - subs.sort(); - // Pushed in reverse so the stack pops them in name order. - for (name, sub) in subs.into_iter().rev() { - let Some(c) = canon(&sub) else { continue }; - if skip.as_ref() == Some(&c) || !seen.insert(c) { - continue; - } - let rel = if rel.is_empty() { name } else { format!("{rel}/{name}") }; - stack.push((sub, rel, depth + 1)); - } - } - Ok(out) -} -#[cfg(target_arch = "wasm32")] -pub(crate) fn list_images_tree(dir: &str, _skip: &str, _cmd: &str) -> Result> { - Err(EngineError::Other(format!("cannot list {dir}: no file system on the web"))) -} - -/// Opens each input in a scratch session, runs `f` on it and saves it to `output` as `format` -/// (`"same"` keeps the input's extension). Errors per file are collected, not fatal. -pub(crate) fn process_files( - s: &Session, - inputs: &[String], - output: &str, - format: &str, - save: SaveOpts, - suffix: &str, - f: &dyn Fn(&mut Session) -> Result<()>, -) -> Value { - let inputs: Vec = inputs.iter().map(|path| BatchInput { path: path.clone(), rel_dir: String::new() }).collect(); - process_tree(s, &inputs, output, format, save, suffix, &|scratch, _| f(scratch).map(|()| false)) -} - -/// [`process_files`] for inputs from subfolders: each result goes to its input's relative folder -/// under `output` (created as needed), so `a/x.png` and `b/x.png` don't collide. `f` gets the -/// output path and returns `true` when it wrote the result there itself (Batch writes what a -/// recorded save marked); otherwise the active document is saved after it. -pub(crate) fn process_tree( - s: &Session, - inputs: &[BatchInput], - output: &str, - format: &str, - save: SaveOpts, - suffix: &str, - f: &dyn Fn(&mut Session, &str) -> Result, -) -> Value { - let outputs = inputs.iter().map(|BatchInput { path, rel_dir }| { - let ext = if format == "same" { same_format(path) } else { format.trim_start_matches('.').to_ascii_lowercase() }; - (path.as_str(), join(&join(output, rel_dir), &format!("{}{suffix}.{ext}", stem(path)))) - }); - process_outputs(s, outputs, save, f) -} - -/// The extension a batch output takes with Format "Same": the input's own, except for formats -/// PhotoCraft opens but can't write, camera raws above all (#5799: a folder of ARWs failed on -/// every file). Those are saved as PSD, the format Photoshop's Save As offers for a raw. An input -/// whose file name has no extension (a dot in a folder name doesn't count) is saved as PNG. -fn same_format(path: &str) -> String { - const IMPORT_ONLY: &[&str] = &["pdn", "kra", "krz", "af", "afdesign", "afphoto", "afpub", "heic", "heif", "hif", "svg", "svgz", "cin", "pcx", "xpm"]; - let ext = extension(path).unwrap_or_else(|| "png".into()); - if photocraft_io::raw::EXTENSIONS.contains(&ext.as_str()) || IMPORT_ONLY.contains(&ext.as_str()) { "psd".into() } else { ext } -} - -#[cfg(test)] -#[test] -fn same_format_takes_the_file_names_extension() { - assert_eq!(same_format("/in/a.PNG"), "png"); - assert_eq!(same_format("/in/IMG_0001.ARW"), "psd"); - assert_eq!(same_format("/in/a.kra"), "psd"); - assert_eq!(same_format("/in/IMG_0001.HEIC"), "psd"); - assert_eq!(same_format("/in/logo.svg"), "psd"); - assert_eq!(same_format("/in/scan.cin"), "psd"); - // No extension in the file name: PNG, not the path after a dot in a folder name. - assert_eq!(same_format("/in/v1.2/scan"), "png"); - assert_eq!(same_format("C:\\in.d\\scan"), "png"); - assert_eq!(same_format("/in/.hidden"), "png"); -} - -fn process_outputs<'a>( - s: &Session, - outputs: impl IntoIterator, - save: SaveOpts, - f: &dyn Fn(&mut Session, &str) -> Result, -) -> Value { - // The scratch sessions have default preferences; a raw opens at the user's Raw Defaults. - let raw_ppi = s.prefs().raw_defaults.resolution; - let mut files = Vec::new(); - let mut errors = Vec::new(); - let mut written = OutputClaims::default(); - for (path, out) in outputs { - let r = (|| -> Result<()> { - written.check(&out).map_err(EngineError::Other)?; - let bytes = read_file(path)?; - let mut scratch = Session::new(); - let doc = import_at_raw_ppi(raw_ppi, &file_name(path), &bytes)?; - scratch.add_document(doc, Some(path.to_string())); - if !f(&mut scratch, &out)? { - let d = scratch.active().ok_or(EngineError::NoDocument)?; - save_doc(&d.doc, &out, save)?; - } - Ok(()) - })(); - match r { - Ok(()) => { - written.record(&out, path); - files.push(out); - } - Err(e) => errors.push(json!({"file": path, "error": e.to_string()})), - } - } - json!({"files": files, "errors": errors}) -} - -/// The output paths a batch run has written, so a later input whose output name matches an -/// earlier one's (`a.png` and `a.jpg` saved as JPEG, or the same name in two input folders) is -/// reported instead of silently replacing that result (#420, #422). Names are compared ignoring -/// case, because macOS and Windows file systems do. -#[derive(Default)] -pub struct OutputClaims(std::collections::HashMap); - -impl OutputClaims { - /// `Err` (naming the earlier input) when `out` was already written in this run. - pub fn check(&self, out: &str) -> std::result::Result<(), String> { - match self.0.get(&out.to_lowercase()) { - Some(first) => Err(format!("not written: {out} already holds the result of {first} from this run (same output name)")), - None => Ok(()), - } - } - /// Remember that `input`'s result was written to `out`. - pub fn record(&mut self, out: &str, input: &str) { - self.0.insert(out.to_lowercase(), input.to_string()); - } -} - -/// A recorded Save, Save As or Save a Copy, which marks the result Batch writes to its destination -/// (Photoshop's "Override Action 'Save As' Commands"). -pub(crate) fn batch_save_point(id: &str) -> bool { - matches!(id, "file.save" | "file.saveAs" | "file.saveACopy") -} - -/// Whether Batch and droplets keep a recorded step: save points mark the result, while other -/// shell-only saves and view steps (zoom, fit) don't change the output (#2752). -pub(crate) fn batch_keeps_step(id: &str) -> bool { - (batch_save_point(id) || !crate::actions_cmds::shell_save_command(id)) && !crate::actions_cmds::shell_view_command(id) -} - -fn batch(s: &mut Session, p: &Value) -> Result { - let cmd = "file.automate.batch"; - let mut steps = - parse_steps(p.get("steps").or_else(|| p.get("action")).ok_or_else(|| EngineError::BadParams { cmd: cmd.into(), msg: "missing \"steps\"".into() })?)?; - // Each result goes to the destination folder, which overrides the action's recorded Save / - // Save As steps: they only mark the result. - steps.retain(|(id, _)| batch_keeps_step(id) && id != "file.export.quickExport"); - if let Some((id, _)) = steps.iter().find(|(id, _)| !batch_save_point(id) && crate::commands::find(id).is_none()) { - return Err(EngineError::BadParams { cmd: cmd.into(), msg: format!("unknown command `{id}` in the action") }); - } - let output = str_param(p, "output", cmd)?.to_string(); - let inputs = batch_inputs_tree(p, cmd, &output)?; - let format = p.get("format").and_then(Value::as_str).unwrap_or("same").to_string(); - // Steps that call another action play it from the caller's actions; the playback stack comes - // along so an action that batches itself is caught as a recursive call. - let list = match p.get("calledActions") { - None | Some(Value::Null) => s.actions.list.clone(), - // A droplet brings the actions it calls (#2794) and runs with those alone. - Some(v) => { - let list: Vec = - serde_json::from_value(v.clone()).map_err(|e| EngineError::BadParams { cmd: cmd.into(), msg: format!("\"calledActions\": {e}") })?; - if list.len() > 4096 { - return Err(EngineError::BadParams { cmd: cmd.into(), msg: "\"calledActions\" holds more than 4096 actions".into() }); - } - list - } - }; - // A batch inside a played action charges its inputs × steps (at least one each: an input is read, - // decoded and saved even with no steps) to the playback tree it is in and - // hands the count on, so a batch of batches can't multiply past the limit. A top-level batch - // is not limited by it. - let mut playback_steps = 0; - if s.actions.playing > 0 { - playback_steps = s.actions.playback_steps.saturating_add((steps.len().max(1) as u64).saturating_mul(inputs.len() as u64)); - if playback_steps > crate::actions_cmds::MAX_PLAYBACK_STEPS { - return Err(EngineError::BadParams { cmd: cmd.into(), msg: "this batch would exceed the playback step limit of the action that runs it".into() }); - } - s.actions.playback_steps = playback_steps; - } - let actions = crate::actions_cmds::ActionState { - list, - playing: s.actions.playing, - playback_stack: s.actions.playback_stack.clone(), - playback_steps, - ..Default::default() - }; - let names = batch_naming::plan(&inputs, &output, &format, p)?; - let save = SaveOpts::from_params(s, p, cmd)?; - let authorize = s.authorize; - // Each input runs in its own scratch session, so what the played steps spend is carried from - // one input to the next (failed or not) and back to this session, not restarted per input. - let carried = std::cell::Cell::new(playback_steps); - let carried = &carried; - let run = move |scratch: &mut Session, out: &str| { - scratch.authorize = authorize; - scratch.actions = actions.clone(); - scratch.actions.playback_steps = carried.get(); - let result = (|| { - // The document as the last recorded save found it, written once the action has run so a - // failing step still writes nothing. - let mut saved: Option> = None; - for (id, params) in &steps { - if batch_save_point(id) { - saved = Some(scratch.active().ok_or(EngineError::NoDocument)?.doc.clone()); - continue; - } - let r = scratch.execute(id, params.clone())?; - // A failed step inside a called action makes this file an error, not a saved result. - if let Some(error) = crate::actions_cmds::nested_failure(id, &r) { - return Err(EngineError::Other(error)); - } - } - // While the saved document is still open the steps after the save reach the result too - // (#3058), so it is saved after the action as usual. Closed after its save, or with another - // document left active, it is written as the save found it. - match saved { - Some(doc) if scratch.active().is_none_or(|d| d.doc.id != doc.id) => { - save_doc(&doc, out, save)?; - Ok(true) - } - _ => Ok(false), - } - })(); - carried.set(scratch.actions.playback_steps); - result - }; - let r = match names { - Some(names) => process_outputs(s, inputs.iter().map(|i| i.path.as_str()).zip(names), save, &run), - None => process_tree(s, &inputs, &output, &format, save, "", &run), - }; - if s.actions.playing > 0 { - s.actions.playback_steps = carried.get(); - } - Ok(r) -} - -fn image_processor(s: &mut Session, p: &Value) -> Result { - let cmd = "file.scripts.imageProcessor"; - let output = str_param(p, "output", cmd)?.to_string(); - let inputs = batch_inputs_tree(p, cmd, &output)?; - let format = p.get("format").and_then(Value::as_str).unwrap_or("jpg").to_string(); - let fit = match (size_param(p, "width"), size_param(p, "height")) { - (None, None) => None, - (w, h) => Some(json!({"width": w.unwrap_or(1e9), "height": h.unwrap_or(1e9), "dontEnlarge": true})), - }; - let to_srgb = p.get("convertToSrgb").and_then(Value::as_bool).unwrap_or(false); - let r = process_tree(s, &inputs, &output, &format, SaveOpts::from_params(s, p, cmd)?.or_quality(8.0), "", &|scratch, _| { - if to_srgb && scratch.active().is_some_and(|d| d.doc.mode != ColorMode::Rgb) { - scratch.execute("image.mode.rgb", json!({}))?; - } - if let Some(fp) = &fit { - fit_image(scratch, fp)?; - } - Ok(false) - }); - Ok(r) -} - -fn load_files_into_stack(s: &mut Session, p: &Value) -> Result { - let cmd = "file.scripts.loadFilesIntoStack"; - let paths: Vec = match p.get("paths").or_else(|| p.get("input")) { - Some(Value::Array(a)) => a.iter().filter_map(Value::as_str).map(str::to_string).collect(), - Some(Value::String(dir)) => list_images(dir)?, - _ => return Err(EngineError::BadParams { cmd: cmd.into(), msg: "missing \"paths\"".into() }), - }; - if paths.is_empty() { - return Err(EngineError::BadParams { cmd: cmd.into(), msg: "no files to load".into() }); - } - let mut docs = Vec::new(); - for path in &paths { - let bytes = read_file(path)?; - docs.push((file_name(path), import_opened(s, &file_name(path), &bytes)?)); - } - let first = &docs[0].1; - let w = docs.iter().map(|(_, d)| d.size.width).max().unwrap_or(1); - let h = docs.iter().map(|(_, d)| d.size.height).max().unwrap_or(1); - let mut stack = Document::new(stem(&paths[0]), photocraft_doc::Size::new(w, h), first.mode, first.depth); - stack.resolution_dpi = first.resolution_dpi; - stack.icc_profile = first.icc_profile.clone(); - let fmt = stack.pixel_format(); - // First file at the bottom, like Photoshop's script. - for (name, d) in &docs { - stack.layers.push(Layer::new(name.clone(), LayerContent::Raster(flattened_checked(d, fmt, cmd)?))); - } - let n = stack.layers.len(); - let smart = p.get("createSmartObject").and_then(Value::as_bool).unwrap_or(false); - // "Attempt to Automatically Align Source Images": Auto-Align Layers on the loaded layers, before - // they go into the smart object. - let align = p.get("align").and_then(Value::as_bool).unwrap_or(false) && n > 1; - if smart && !align { - // "Create Smart Object after Loading Layers": the layers go inside one smart object, ready - // for Layer › Smart Objects › Stack Mode. Like Photoshop, they sit at the top level of the - // contents, with no wrapper group. - let layers = std::mem::take(&mut stack.layers); - let smart = crate::smart_cmds::layers_to_smart(&stack, &stem(&paths[0]), layers)?; - stack.layers = vec![smart]; - } - let i = s.add_document(stack, None); - if align { - s.execute("select.allLayers", json!({}))?; - s.execute("edit.autoAlignLayers", json!({"projection": "auto"}))?; - if smart { - let name = s.active().map(|d| d.doc.name.clone()).unwrap_or_default(); - s.edit("Convert to Smart Object", |doc, active| { - let layers = std::mem::take(&mut doc.layers); - let smart = crate::smart_cmds::layers_to_smart(doc, &name, layers)?; - *active = Some(smart.id); - doc.layers = vec![smart]; - Ok(()) - })?; - if let Some(st) = s.active_mut() { - st.selected_layers = st.active_layer.into_iter().collect(); - } - } - } - Ok(json!({"document": i, "layers": n})) -} - -// ---------- Scripts: flatten effects / masks ---------- - -fn has_live_effects(l: &Layer) -> bool { - l.effects.enabled && l.effects.items.iter().any(|e| e.enabled()) -} - -/// The layer of `doc` rendered alone (keeping what `keep` says) with the document's Global Light, -/// patterns and canvas, as a surface in the document's format. With `apply_mask` off the layer's -/// pixel and vector masks are left out of the render, so a caller that keeps them live on the -/// baked raster does not mask the pixels twice. -fn bake(doc: &Document, l: &Layer, keep_effects: bool, apply_mask: bool) -> Surface { - let canvas = doc.bounds(); - let mut tmp = l.clone(); - tmp.opacity = 1.0; - tmp.blend = photocraft_color::BlendMode::Normal; - tmp.visible = true; - tmp.clipped = false; - if !keep_effects { - tmp.effects.items.clear(); - tmp.fill_opacity = 1.0; - } - if !apply_mask { - tmp.mask = None; - tmp.vector_mask = None; - } - // Render over the union of the canvas and the content so off-canvas pixels survive. - let area = l.surface().map_or(canvas, |s| s.content_bounds().union(&canvas)); - let area = if keep_effects { area.inflate(256) } else { area }; - buffer_surface(&photocraft_compose::render_layer_in(doc, &tmp, area), doc.pixel_format()) -} - -fn walk_ids(doc: &Document) -> Vec { - doc.walk().into_iter().map(|(_, _, l)| l.id).collect() -} - -fn flatten_all_effects(s: &mut Session) -> Result { - let mut n = 0; - s.edit("Flatten All Layer Effects", |doc, _| { - for id in walk_ids(doc) { - let Some(l) = doc.layer(id) else { continue }; - if !has_live_effects(l) || matches!(l.content, LayerContent::Group(_) | LayerContent::Adjustment(_)) { - continue; - } - // The pixel and vector masks stay on the layer (baking must not destroy them), so the - // pixels are baked without them and each mask then applies once to the baked raster. - let px = bake(doc, l, true, false); - let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; - l.content = LayerContent::Raster(px); - l.effects = Default::default(); - l.fill_opacity = 1.0; - l.fill_cache = None; - l.psd_blocks.retain(|(k, _)| !matches!(k, b"TySh" | b"SoLd" | b"PlLd" | b"SoLE" | b"vmsk" | b"vsms" | b"vogk" | b"vscg" | b"vstk")); - n += 1; - } - Ok(()) - })?; - Ok(json!({"flattened": n})) -} - -fn flatten_all_masks(s: &mut Session) -> Result { - let (mut n, mut skipped) = (0, 0); - s.edit("Flatten All Masks", |doc, _| { - for id in walk_ids(doc) { - let Some(l) = doc.layer(id) else { continue }; - let masked = l.mask.as_ref().is_some_and(|m| m.enabled) || l.vector_mask.is_some(); - if !masked { - continue; - } - if !matches!(l.content, LayerContent::Raster(_)) { - // Masks on groups, adjustment, type, shape and smart layers have no pixels to - // fold into; Photoshop's script leaves them too. - skipped += 1; - continue; - } - let px = bake(doc, l, false, true); - let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; - l.content = LayerContent::Raster(px); - l.mask = None; - l.vector_mask = None; - l.psd_blocks.retain(|(k, _)| !matches!(k, b"vmsk" | b"vsms")); - n += 1; - } - Ok(()) - })?; - Ok(json!({"flattened": n, "skipped": skipped})) -} - -// ---------- Export ---------- - -fn layers_to_files(s: &mut Session, p: &Value) -> Result { - let cmd = "file.export.layersToFiles"; - let dir = str_param(p, "dir", cmd).or_else(|_| str_param(p, "output", cmd))?.to_string(); - let report = export_layers_report_with(s, p, |name, bytes| write_file(&join(&dir, name), bytes))?; - let files: Vec = report.files.iter().map(|name| join(&dir, name)).collect(); - Ok(json!({"files": files, "skipped": report.skipped})) -} - -/// The bodies of `file.export.layersToFiles`, streamed to `write` as a single-component filename -/// plus its bytes: one file per exported layer (top to bottom, like Photoshop's numbering), -/// encoded but never touched as a path. Automation writes exactly these bytes beneath its write -/// root (#3216), so the two paths cannot drift. Returns the filenames written, in order. -pub fn export_layers_with(s: &Session, p: &Value, write: impl FnMut(&str, &[u8]) -> Result<()>) -> Result> { - export_layers_report_with(s, p, write).map(|report| report.files) -} - -/// A top-level layer omitted from a successful Layers to Files export. -#[derive(Debug, serde::Serialize)] -pub struct SkippedExportLayer { - /// Session layer id (names need not be unique). - pub layer: u64, - /// Original name, not the sanitized filename component. - pub name: String, - /// Why the layer produced no file. - pub reason: &'static str, -} - -/// Filenames written and layers skipped, each in top-to-bottom order. -#[derive(Debug, Default)] -pub struct LayerExportReport { - pub files: Vec, - pub skipped: Vec, -} - -/// The same export as [`export_layers_with`], with an explanation for every omitted top-level -/// layer. Groups export merged, so their children are not separate exports or skips. Encoding -/// and write failures remain errors, never successful skips. Existing numbering is preserved. -pub fn export_layers_report_with(s: &Session, p: &Value, mut write: impl FnMut(&str, &[u8]) -> Result<()>) -> Result { - let cmd = "file.export.layersToFiles"; - let format = p.get("format").and_then(Value::as_str).unwrap_or("png").trim_start_matches('.').to_ascii_lowercase(); - let visible_only = p.get("visibleOnly").and_then(Value::as_bool).unwrap_or(true); - // Callers outside `Session::execute` (headless workspace exports) carry the session's gate - // into `encode`, so a PSD embeds no file a linked smart object names. - let _authorization = crate::jobs::render_authorization_scope(s.authorize); - let save = SaveOpts::from_params(s, p, cmd)?; - let d = s.active().ok_or(EngineError::NoDocument)?; - let prefix = p.get("prefix").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| stem(&d.doc.name)); - let doc = d.doc.clone(); - let mut report = LayerExportReport::default(); - // Hidden layers never consumed a filename index; adjustments that pass the visibility - // filter did. Keep those filenames stable while reporting both kinds of omission. - let mut i = 0usize; - for l in doc.layers.iter().rev() { - if !l.visible && visible_only { - report.skipped.push(SkippedExportLayer { layer: l.id.0, name: l.name.clone(), reason: "hidden by visibleOnly" }); - continue; - } - let index = i; - i += 1; - if matches!(l.content, LayerContent::Adjustment(_)) { - report.skipped.push(SkippedExportLayer { layer: l.id.0, name: l.name.clone(), reason: "adjustment layer has no pixels of its own" }); - continue; - } - let mut one = (*doc).clone(); - let mut only = l.clone(); - only.visible = true; - only.clipped = false; - one.layers = vec![only]; - let name = format!("{}_{:04}_{}.{format}", sanitize(&prefix), index, sanitize(&l.name)); - let (bytes, _warnings) = encode(&one, &name, save)?; - write(&name, &bytes)?; - report.files.push(name); - } - Ok(report) -} - -/// Adjustment layers that can be represented as an RGB-only LUT, in document stack order. -/// A LUT has no spatial coordinates, so masks and clipping geometry are deliberately stripped -/// at bake time. Group adjustments need their enclosing group's compositing semantics and are -/// not silently flattened as independent layers. -fn lut_layers<'a>(doc: &'a Document, ids: Option<&[LayerId]>) -> Result> { - const CMD: &str = "file.export.colorLookupTables"; - let mut selected = Vec::new(); - if let Some(ids) = ids { - if ids.is_empty() { - return Err(EngineError::BadParams { cmd: CMD.into(), msg: "select at least one adjustment layer".into() }); - } - for id in ids { - if selected.contains(id) { - return Err(EngineError::BadParams { cmd: CMD.into(), msg: format!("duplicate layer id {}", id.0) }); - } - let Some(layer) = doc.layer(*id) else { return Err(EngineError::NoLayer(*id)) }; - if !matches!(layer.content, LayerContent::Adjustment(_)) { - return Err(EngineError::BadParams { cmd: CMD.into(), msg: format!("layer {} is not an adjustment layer", id.0) }); - } - if !layer.visible { - return Err(EngineError::BadParams { cmd: CMD.into(), msg: format!("layer {} is hidden", id.0) }); - } - if !doc.layers.iter().any(|root| root.id == *id) { - return Err(EngineError::BadParams { - cmd: CMD.into(), - msg: format!("layer {} is nested in a group; export top-level adjustment layers", id.0), - }); - } - selected.push(*id); - } - } - let mut layers = Vec::new(); - for l in &doc.layers { - if l.visible && matches!(l.content, LayerContent::Adjustment(_)) && (ids.is_none() || selected.contains(&l.id)) { - layers.push(l); - } - } - if layers.is_empty() { - return Err(EngineError::BadParams { cmd: CMD.into(), msg: "no visible adjustment layers to export".into() }); - } - Ok(layers) -} - -/// Bake the chosen adjustment stack against an identity RGB lattice. -/// Source order always follows the document stack, even if an explicit list is reversed. -fn bake_cube_layers(size: usize, title: &str, layers: &[&Layer]) -> String { - let n = size; - let (w, h) = ((n * n) as u32, n as u32); - let mut lattice = Document::new("lut", photocraft_doc::Size::new(w, h), ColorMode::Rgb, photocraft_color::SampleType::F32); - let fmt = lattice.pixel_format(); - let step = 1.0 / (n - 1) as f32; - let mut data = Vec::with_capacity((w * h) as usize * fmt.channels()); - for g in 0..n { - for b in 0..n { - for r in 0..n { - let mut px = [0.0f32; 8]; - let k = from_rgba_into(&fmt, [r as f32 * step, g as f32 * step, b as f32 * step, 1.0], &mut px); - data.extend_from_slice(&px[..k]); - } - } - } - let mut surf = Surface::new(fmt); - surf.write_region(Rect::new(0, 0, w as i32, h as i32), &data); - lattice.layers.push(Layer::new("Lattice", LayerContent::Raster(surf))); - for l in layers { - let mut a = (*l).clone(); - // Masks and clipping are spatial; a LUT is the adjustment stack's colour mapping. - a.mask = None; - a.vector_mask = None; - a.clipped = false; - lattice.layers.push(a); - } - let out = photocraft_compose::flatten(&lattice); - let mut s = format!("TITLE \"{}\"\n# Created by PhotoCraft\nLUT_3D_SIZE {n}\nDOMAIN_MIN 0.0 0.0 0.0\nDOMAIN_MAX 1.0 1.0 1.0\n", title.replace('"', "'")); - // .cube order: red changes fastest, then green, then blue. - for b in 0..n { - for g in 0..n { - for r in 0..n { - let (x, y) = (b * n + r, g); - let px = out.px[y * w as usize + x]; - s.push_str(&format!("{:.6} {:.6} {:.6}\n", px[0].clamp(0.0, 1.0), px[1].clamp(0.0, 1.0), px[2].clamp(0.0, 1.0))); - } - } - } - s -} - -/// Backwards-compatible helper for exporting all visible top-level adjustments. -pub fn bake_cube(doc: &Document, size: usize, title: &str) -> String { - let layers: Vec<&Layer> = doc.layers.iter().filter(|l| l.visible && matches!(l.content, LayerContent::Adjustment(_))).collect(); - bake_cube_layers(size.clamp(2, photocraft_cms::lutfile::MAX_SIZE), title, &layers) -} - -/// Export either the whole visible stack (backward-compatible default), the Layers panel's -/// current selection, or an explicit list supplied by scripts/CLI/automation. -fn color_lookup_tables(s: &mut Session, p: &Value) -> Result { - const CMD: &str = "file.export.colorLookupTables"; - let d = s.active().ok_or(EngineError::NoDocument)?; - let size = match p.get("size") { - None | Some(Value::Null) => 33, - Some(v) => v.as_u64().ok_or_else(|| EngineError::BadParams { cmd: CMD.into(), msg: "size must be an integer".into() })?, - }; - if !(2..=photocraft_cms::lutfile::MAX_SIZE as u64).contains(&size) { - return Err(EngineError::BadParams { cmd: CMD.into(), msg: format!("size must be 2..={}", photocraft_cms::lutfile::MAX_SIZE) }); - } - let scope = match p.get("scope") { - None | Some(Value::Null) => "all", - Some(Value::String(s)) => s.as_str(), - Some(_) => return Err(EngineError::BadParams { cmd: CMD.into(), msg: "scope must be all or selected".into() }), - }; - if !matches!(scope, "all" | "selected") { - return Err(EngineError::BadParams { cmd: CMD.into(), msg: "scope must be all or selected".into() }); - } - if p.get("layers").is_some() && scope == "selected" { - return Err(EngineError::BadParams { cmd: CMD.into(), msg: "use either layers or scope=selected, not both".into() }); - } - let explicit: Option> = if let Some(v) = p.get("layers") { - let Some(a) = v.as_array() else { return Err(EngineError::BadParams { cmd: CMD.into(), msg: "layers must be an array of layer IDs".into() }) }; - let mut out = Vec::with_capacity(a.len()); - for id in a { - let Some(id) = id.as_u64() else { return Err(EngineError::BadParams { cmd: CMD.into(), msg: "layer IDs must be unsigned integers".into() }) }; - out.push(LayerId(id)); - } - Some(out) - } else if scope == "selected" { - Some(d.selected_layers()) - } else { - None - }; - let layers = lut_layers(&d.doc, explicit.as_deref())?; - let count = layers.len(); - let title = p.get("title").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| stem(&d.doc.name)); - let cube = bake_cube_layers(size as usize, &title, &layers); - match p.get("path").and_then(Value::as_str) { - Some(path) => { - write_file(path, cube.as_bytes())?; - Ok(json!({"path": path, "size": size, "layerCount": count})) - } - None => Ok(json!({"cube": cube, "size": size, "layerCount": count})), - } -} - -// ---------- guides ---------- - -fn push_unique(v: &mut Vec, x: f64) { - if !v.iter().any(|g| (g - x).abs() < 0.01) { - v.push(x); - } -} - -fn new_guide_layout(s: &mut Session, p: &Value) -> Result { - crate::guide_layout::apply(s, p) -} - -fn guides_from_shape(s: &mut Session, p: &Value) -> Result { - let id = layer_param(s, p)?; - let d = s.active().ok_or(EngineError::NoDocument)?; - let l = d.doc.layer(id).ok_or(EngineError::NoLayer(id))?; - let LayerContent::Shape(sh) = &l.content else { return Err(EngineError::Other("the layer is not a shape layer".into())) }; - let (x0, y0, x1, y1) = sh.path.control_bounds().ok_or(EngineError::Other("the shape has no path".into()))?; - s.edit("New Guides From Shape", |doc, _| { - for x in [x0, (x0 + x1) / 2.0, x1] { - push_unique(&mut doc.guides.vertical, x); - } - for y in [y0, (y0 + y1) / 2.0, y1] { - push_unique(&mut doc.guides.horizontal, y); - } - Ok(()) - })?; - Ok(json!({"bounds": [x0, y0, x1, y1]})) -} - -fn clear_canvas_guides(s: &mut Session) -> Result { - let d = s.active().ok_or(EngineError::NoDocument)?; - // Guides inside an artboard belong to it (View › Clear Selected Artboard Guides); the rest - // are canvas guides. Without artboards every guide is a canvas guide. - let boards: Vec = d.doc.artboards().iter().map(|b| b.2.rect).collect(); - let in_x = move |x: f64| boards.iter().any(|r| x > f64::from(r.x0) && x < f64::from(r.x1)); - let boards_y: Vec = d.doc.artboards().iter().map(|b| b.2.rect).collect(); - let in_y = move |y: f64| boards_y.iter().any(|r| y > f64::from(r.y0) && y < f64::from(r.y1)); - let n = d.doc.guides.vertical.iter().filter(|x| !in_x(**x)).count() + d.doc.guides.horizontal.iter().filter(|y| !in_y(**y)).count(); - if n == 0 { - return Ok(json!({"cleared": 0})); - } - s.edit("Clear Canvas Guides", |doc, _| { - doc.guides.vertical.retain(|x| in_x(*x)); - doc.guides.horizontal.retain(|y| in_y(*y)); - doc.guides.prune_colors(); - Ok(()) - })?; - Ok(json!({"cleared": n})) -} - -// ---------- registry ---------- - -pub fn specs() -> Vec { - macro_rules! spec { - ($id:expr, $label:expr, $menu:expr, $sc:expr, $params:expr, $enabled:expr, $run:expr) => { - CommandSpec { id: $id, label: $label, menu: $menu, shortcut: $sc, params: $params, enabled: $enabled, journal: true, run: $run } - }; - } - vec![ - spec!("file.closeAll", "Close All", &["File"], Some("Cmd+Alt+W"), "{}", has_doc, |s, _| close_all(s)), - spec!( - "file.closeOthers", - "Close Others", - &["File"], - Some("Cmd+Alt+P"), - r##"{"document":index? (the one to keep; default active)}"##, - has_doc, - close_others - ), - // The document tab's menu (UI-217-6): the tab's own file in the platform file manager. - // Not a Photoshop menu-bar item; enabled when the target document has a saved path. - spec!("file.revealInFinder", "Reveal in Finder", &[], None, r##"{"document":index? (default active),"dryRun":bool=false}"##, native_doc, |s, p| { - let i = match p.get("document") { - Some(v) => v - .as_u64() - .and_then(|v| usize::try_from(v).ok()) - .ok_or_else(|| EngineError::BadParams { cmd: "file.revealInFinder".into(), msg: "`document` must be an index".into() })?, - None => s.active_index().ok_or(EngineError::NoDocument)?, - }; - let path = s - .documents() - .get(i) - .and_then(|d| d.path.clone()) - .ok_or_else(|| EngineError::BadParams { cmd: "file.revealInFinder".into(), msg: format!("document {i} has no saved file") })?; - crate::layer_menu_cmds::reveal(&path, p.get("dryRun").and_then(Value::as_bool).unwrap_or(false)) - }), - spec!("file.revert", "Revert", &["File"], Some("F12"), "{} (reloads the saved file as one undoable step)", can_revert, |s, _| revert(s)), - spec!( - "file.saveACopy", - "Save a Copy…", - &["File"], - Some("Cmd+Alt+S"), - r##"{"path":str (format from the extension),"quality":0..12? (JPEG),"jpegFormat":"baseline|optimized|progressive"? (JPEG; default baseline),"layers":bool=true,"overwrite":bool=false (replace the document's own file),"tiffLayers":bool=false (TIFF: keep the layers; flat by default),"tiffCompression":"none|lzw|zip"? (TIFF: image compression; unset, none),"tgaBits":24|32? (TGA: 32 writes the alpha channel, or else the transparency, as the alpha; unset, 32 with an alpha channel or transparency, else 24),"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain)}"##, - native_doc, - save_a_copy - ), - spec!( - "file.openAs", - "Open As…", - &["File"], - Some("Cmd+Alt+Shift+O"), - r##"{"path":str,"as":"psd|png|jpg|tiff|…"? (decode as this format)}"##, - native, - open_as - ), - spec!( - "file.placeEmbedded", - "Place Embedded…", - &["File"], - None, - r##"{"path":str,"scale":%? (default: fit when larger than the canvas),"fit":bool? (default: Preferences > General > Resize Image During Place),"smartObject":bool? (default: Preferences > General > Always Create Smart Objects When Placing),"center":[x,y]?}"##, - native_doc, - |s, p| place(s, p, false) - ), - spec!( - "file.placeLinked", - "Place Linked…", - &["File"], - None, - r##"{"path":str,"scale":%?,"fit":bool? (default: Preferences > General > Resize Image During Place),"center":[x,y]?}"##, - native_doc, - |s, p| place(s, p, true) - ), - spec!( - "file.fileInfo", - "File Info…", - &["File"], - Some("Cmd+Alt+Shift+I"), - r##"{"title":str?,"author":str?,"authorTitle":str?,"description":str?,"keywords":[str]|"a; b"?,"copyright":str?,"copyrightStatus":"unknown|copyrighted|publicDomain"?,"copyrightUrl":str?} (no keys: read; the result also has read-only "camera":{"make","model","dateTaken","exposure","fNumber","iso","focalLength","focalLength35mm","lens"}, present keys only)"##, - has_doc, - file_info - ), - spec!( - "file.automate.fitImage", - "Fit Image…", - &["File", "Automate"], - None, - r##"{"width":px,"height":px,"dontEnlarge":bool=false,"resample":"automatic|preserveDetails|bicubicSmoother|bicubicSharper|bicubicAutomatic|bicubic|nearest|bilinear|lanczos"="bicubic"}"##, - has_doc, - fit_image - ), - spec!( - "file.automate.conditionalModeChange", - "Conditional Mode Change…", - &["File", "Automate"], - None, - r##"{"from":["rgb","grayscale","cmyk","lab","indexed","bitmap",…]|"any"="any","to":"rgb|grayscale|cmyk|lab"}"##, - has_doc, - conditional_mode_change - ), - spec!( - "file.automate.batch", - "Batch…", - &["File", "Automate"], - None, - r##"{"steps":[[commandId,params]|{"command":id,"params":{}}…] (a recorded action; a Save, Save As or Save a Copy step marks the document written to output, in this command's format and options: as the save found it if it was closed or another document is active at the end, else as the action leaves it; with no such step, the active document at the end),"input":folder|[paths],"includeSubfolders":bool=false (a folder input also takes the images in its subfolders, up to 32 levels and 100000 files; each result keeps its subfolder under output),"output":folder,"format":"same|png|jpg|psd|tiff|…"="same","quality":0..12?,"jpegFormat":"baseline|optimized|progressive"?,"naming":string? (blank keeps source names; {name}, {serial} padded to 3 digits, {date} as YYYY-MM-DD UTC; extension added automatically),"startingSerial":1..4294967295=1 (input position, including failed inputs),"tiffLayers":bool=false,"tiffCompression":"none|lzw|zip"?,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"calledActions":[{"name","steps"}…]? (the actions Play Action steps call; default: the session's)} → {files, errors} (an input whose output name was already written in the run goes to errors)"##, - native, - batch - ), - spec!( - "file.scripts.imageProcessor", - "Image Processor…", - &["File", "Scripts"], - None, - r##"{"input":folder|[paths],"includeSubfolders":bool=false (a folder input also takes the images in its subfolders, up to 32 levels and 100000 files; each result keeps its subfolder under output),"output":folder,"format":"jpg|png|psd|tiff|…"="jpg","quality":0..12=8,"jpegFormat":"baseline|optimized|progressive"?,"tiffLayers":bool=false,"tiffCompression":"none|lzw|zip"?,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"width":px?,"height":px? (fit, never enlarge),"convertToSrgb":bool=false} → {files, errors} (an input whose output name was already written in the run goes to errors)"##, - native, - image_processor - ), - spec!( - "file.scripts.loadFilesIntoStack", - "Load Files into Stack…", - &["File", "Scripts"], - None, - r##"{"paths":[str]|folder,"align":bool=false (Auto-Align Layers on them first),"createSmartObject":bool=false} → new document with one layer per file (inside one smart object with createSmartObject)"##, - native, - load_files_into_stack - ), - spec!("file.scripts.flattenAllLayerEffects", "Flatten All Layer Effects", &["File", "Scripts"], None, "{}", has_doc, |s, _| flatten_all_effects(s)), - spec!( - "file.scripts.flattenAllMasks", - "Flatten All Masks", - &["File", "Scripts"], - None, - "{} (pixel layers; masks on other layer kinds are left)", - has_doc, - |s, _| flatten_all_masks(s) - ), - spec!( - "file.export.layersToFiles", - "Layers to Files…", - &["File", "Export"], - None, - r##"{"dir":folder,"format":"png|jpg|psd|tiff|…"="png","prefix":str=document name,"visibleOnly":bool=true,"quality":0..12?,"jpegFormat":"baseline|optimized|progressive"?,"tiffLayers":bool=false,"tiffCompression":"none|lzw|zip"?,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain)} → {files}"##, - native_doc, - layers_to_files - ), - spec!( - "file.export.colorLookupTables", - "Color Lookup Tables…", - &["File", "Export"], - None, - r##"{"path":str? (.cube; omit to return the text),"size":2..129=33,"title":str?,"scope":"all|selected"="all","layers":[id,…]?} (selected layer IDs use original document stacking; masks are spatial and omitted)"##, - has_adjustments, - color_lookup_tables - ), - spec!( - "view.newGuideLayout", - "New Guide Layout…", - &["View"], - None, - r##"{"columns":n=0,"width":len?,"gutter":len=0,"rows":n=0,"height":len?,"rowGutter":len=gutter,"margin":len|[top,left,bottom,right]=0,"centerColumns":bool=false,"clearExisting":bool=false,"target":"document|selectedArtboards"="document"} (len: pixels, or text with px, in, cm, mm, pt, pc or % as typed in Photoshop, e.g. "1 cm"; % is of the target's width for columns, gutters and left/right margins, its height for rows and top/bottom margins)"##, - has_doc, - new_guide_layout - ), - spec!("view.newGuidesFromShape", "New Guides From Shape", &["View"], None, r##"{"layer":id?}"##, has_shape, guides_from_shape), - spec!("view.clearCanvasGuides", "Clear Canvas Guides", &["View"], None, "{}", has_doc, |s, _| clear_canvas_guides(s)), - ] -} - -#[cfg(test)] -#[path = "file_cmds/tests.rs"] -mod tests; - -#[cfg(test)] -mod aces_exr_tests { - use super::*; - - /// File Handling › "Open color-less EXR as ACEScg": off, an EXR opens on io's linear-sRGB - /// default; on, it opens as ACEScg — the working space ACES render pipelines write. - #[test] - fn exr_aces_cg_preference_retags_the_opened_document() { - let image = photocraft_codecs::Image::from_f32( - 4, - 4, - photocraft_codecs::ChannelLayout::Rgb, - &[ - 0.25, 0.5, 0.75, 1.0, 0.25, 0.5, 0.75, 1.0, 0.25, 0.5, 0.75, 1.0, 0.25, 0.5, 0.75, 1.0, 0.25, 0.5, 0.75, 1.0, 0.25, 0.5, 0.75, 1.0, 0.25, 0.5, - 0.75, 1.0, 0.25, 0.5, 0.75, 1.0, 0.25, 0.5, 0.75, 1.0, 0.25, 0.5, 0.75, 1.0, 0.25, 0.5, 0.75, 1.0, 0.25, 0.5, 0.75, 1.0, - ], - ) - .unwrap(); - let bytes = photocraft_codecs::encode(&image, photocraft_codecs::Format::OpenExr, &photocraft_codecs::EncodeOptions::default()).unwrap(); - - let linear = photocraft_cms::Builtin::LinearSrgb.profile().to_bytes(); - let aces = photocraft_cms::Builtin::AcesCg.profile().to_bytes(); - - // Off (the default): io's linear-sRGB tagging stays. - let mut s = Session::new(); - open_bytes_as(&mut s, "shot.exr", &bytes, None, None).unwrap(); - let d = &s.active().unwrap().doc; - assert_eq!(d.icc_profile.as_deref().map(|v| v.as_slice()), Some(linear.as_slice())); - - // On: the same file opens as ACEScg. - let mut s = Session::new(); - s.prefs.edit(|p| p.file_handling.exr_aces_cg = true); - open_bytes_as(&mut s, "shot.exr", &bytes, None, None).unwrap(); - let d = &s.active().unwrap().doc; - assert_eq!(d.icc_profile.as_deref().map(|v| v.as_slice()), Some(aces.as_slice())); - } - - /// The desktop app opens files as background jobs (File > Open, drag-drop, Open Recent): - /// the ACEScg preference applies there too, not only to `file.openAs`. - #[test] - fn exr_aces_cg_preference_applies_to_background_opens() { - use crate::jobs::{OpenSource, Started}; - let image = photocraft_codecs::Image::from_f32(4, 4, photocraft_codecs::ChannelLayout::Rgb, &[0.5; 48]).unwrap(); - let bytes = - std::sync::Arc::new(photocraft_codecs::encode(&image, photocraft_codecs::Format::OpenExr, &photocraft_codecs::EncodeOptions::default()).unwrap()); - let linear = photocraft_cms::Builtin::LinearSrgb.profile().to_bytes(); - let aces = photocraft_cms::Builtin::AcesCg.profile().to_bytes(); - for (on, want) in [(false, &linear), (true, &aces)] { - let mut s = Session::new(); - s.prefs.edit(|p| p.file_handling.exr_aces_cg = on); - let v = match s.start_open("shot.exr", OpenSource::Bytes(std::sync::Arc::clone(&bytes))).unwrap() { - Started::Job(id) => s.wait_job(id).unwrap(), - Started::Done(v) => v, - }; - // ACEScg isn't the working space, so Ask When Opening holds it for the prompt, which - // names the ACEScg profile; linear sRGB (io's HDR default) opens without asking. - let profile = match v.get("held").and_then(Value::as_u64) { - Some(held) => { - assert!(on, "{v}"); - assert!(v["color"]["embedded"].as_str().unwrap().starts_with("ACEScg"), "{v}"); - s.take_held_open(held).unwrap().0.icc_profile - } - None => { - assert!(v.get("document").is_some(), "{v}"); - s.active().unwrap().doc.icc_profile.clone() - } - }; - assert_eq!(profile.as_deref().map(|v| v.as_slice()), Some(want.as_slice()), "exr_aces_cg = {on}"); - } - } -} diff --git a/crates/engine/src/filters.rs b/crates/engine/src/filters.rs index b115a9f5e0..4d8db05213 100644 --- a/crates/engine/src/filters.rs +++ b/crates/engine/src/filters.rs @@ -498,520 +498,4 @@ pub fn last_filter(s: &Session) -> Option<(String, Value)> { } #[cfg(test)] -mod tests { - use super::*; - - fn session() -> Session { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 48, "height": 32})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.execute("edit.fill", json!({"color": "#3366cc"})).ok(); - s - } - - fn active_pixels(s: &Session) -> Vec { - let d = s.active().unwrap(); - let l = d.doc.layer(d.active_layer.unwrap()).unwrap(); - l.surface().unwrap().read_region(photocraft_geom::Rect::new(0, 0, 48, 32)) - } - - fn mask_session(reveal_selection: bool) -> Session { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 16, "height": 16, "background": "#ff0000"})).unwrap(); - if reveal_selection { - s.execute("select.all", json!({})).unwrap(); - s.execute("layer.layerMask.revealSelection", json!({})).unwrap(); - } else { - s.execute("layer.layerMask.revealAll", json!({})).unwrap(); - } - s - } - - fn mask_pixels(s: &Session) -> Vec { - let d = s.active().unwrap(); - let mask = d.doc.layer(d.active_layer.unwrap()).unwrap().mask.as_ref().unwrap(); - mask.surface.read_region(d.doc.bounds()) - } - - fn canvas_pixels(s: &Session) -> Vec { - let d = s.active().unwrap(); - d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap().read_region(d.doc.bounds()) - } - - fn paint_pattern(s: &mut Session) { - s.edit("pattern", |doc, active| { - let l = doc.layer_mut(active.unwrap()).unwrap(); - let surf = l.surface_mut().unwrap(); - for y in 0..32 { - for x in 0..48 { - let v = ((x * 5 + y * 3) % 17) as f32 / 16.0; - surf.write_pixel(x, y, &[v, 1.0 - v, (x % 3) as f32 / 2.0, 1.0]); - } - } - Ok(()) - }) - .unwrap(); - } - - const ALL: [&str; 24] = [ - "filter.blur.gaussianBlur", - "filter.blur.boxBlur", - "filter.blur.motionBlur", - "filter.blur.radialBlur", - "filter.blur.surfaceBlur", - "filter.sharpen.unsharpMask", - "filter.sharpen.smartSharpen", - "filter.noise.addNoise", - "filter.noise.median", - "filter.noise.dustAndScratches", - "filter.pixelate.mosaic", - "filter.stylize.emboss", - "filter.stylize.findEdges", - "filter.stylize.solarize", - "filter.distort.twirl", - "filter.distort.pinch", - "filter.distort.spherize", - "filter.distort.wave", - "filter.distort.ripple", - "filter.distort.polarCoordinates", - "filter.other.highPass", - "filter.other.minimum", - "filter.other.maximum", - "filter.other.offset", - ]; - - #[test] - fn every_filter_command_runs_changes_pixels_and_undoes() { - for id in ALL { - let mut s = session(); - paint_pattern(&mut s); - let before = active_pixels(&s); - let params = match id { - "filter.other.offset" => json!({"horizontal": 5, "vertical": 2}), - "filter.noise.dustAndScratches" => json!({"radius": 2, "threshold": 0}), - "filter.noise.median" => json!({"radius": 2}), - _ => json!({}), - }; - let r = s.execute(id, params).unwrap_or_else(|e| panic!("{id}: {e}")); - assert!(r.get("filter").is_some(), "{id}"); - assert_ne!(active_pixels(&s), before, "{id} changed nothing"); - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(active_pixels(&s), before, "{id} undo"); - } - } - - #[test] - fn preset_filters_record_their_own_name() { - // #528: one-step presets run a generic algorithm but name the step after themselves; - // the generic commands keep the algorithm's name. - let specs = specs(); - for (id, name) in [ - ("filter.blur.blur", "Blur"), - ("filter.blur.blurMore", "Blur More"), - ("filter.sharpen.sharpen", "Sharpen"), - ("filter.sharpen.sharpenMore", "Sharpen More"), - ("filter.sharpen.sharpenEdges", "Sharpen Edges"), - ("filter.noise.despeckle", "Despeckle"), - ("filter.blur.gaussianBlur", "Gaussian Blur"), - ("filter.sharpen.unsharpMask", "Unsharp Mask"), - ("filter.blur.surfaceBlur", "Surface Blur"), - ] { - let mut s = session(); - let steps = s.active().unwrap().history.past_len(); - s.execute(id, json!({})).unwrap(); - let h = &s.active().unwrap().history; - assert_eq!((h.past_len(), h.undo_label()), (steps + 1, Some(name)), "{id}"); - let label = specs.iter().find(|c| c.id == id).unwrap().label; - assert_eq!(label.trim_end_matches('…'), name, "{id}: the step is named like the command"); - } - } - - #[test] - fn specs_are_complete_and_documented() { - let specs = specs(); - for id in ALL { - let spec = specs.iter().find(|c| c.id == id).unwrap_or_else(|| panic!("missing {id}")); - assert!(spec.params.starts_with('{'), "{id}"); - assert!(!spec.menu.is_empty(), "{id}"); - } - } - - #[test] - fn disabled_without_pixel_layer() { - let mut s = Session::new(); - assert!(!s.is_enabled("filter.blur.gaussianBlur")); - s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); - s.execute("layer.newAdjustmentLayer.invert", json!({})).unwrap(); - assert!(matches!(s.execute("filter.blur.gaussianBlur", json!({})), Err(EngineError::Disabled(..)))); - } - - #[test] - fn selection_limits_the_filter() { - let mut s = session(); - paint_pattern(&mut s); - s.execute("select.rect", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); - let has_sel = s.active().unwrap().doc.selection.is_some(); - assert!(has_sel); - let before = active_pixels(&s); - s.execute("filter.blur.gaussianBlur", json!({"radius": 3})).unwrap(); - let after = active_pixels(&s); - if has_sel { - // A pixel far from the selection is unchanged. - let i = (30 * 48 + 40) * 4; - assert_eq!(after[i..i + 4], before[i..i + 4]); - let j = (5 * 48 + 5) * 4; - assert_ne!(after[j..j + 4], before[j..j + 4]); - } - } - - #[test] - fn solarize_and_add_noise_process_untouched_reveal_all_masks() { - for (id, params) in [ - ("filter.stylize.solarize", json!({"target": "mask"})), - ("filter.noise.addNoise", json!({"amount": 100, "seed": 1, "monochromatic": true, "target": "mask"})), - ] { - let mut reveal_all = mask_session(false); - let mut reveal_selection = mask_session(true); - let all_mask = reveal_all.active().unwrap().doc.layer(reveal_all.active().unwrap().active_layer.unwrap()).unwrap().mask.as_ref().unwrap(); - assert!(all_mask.surface.content_bounds().is_empty(), "{id}: Reveal All stores its white canvas in the default pixel"); - let initial_all = mask_pixels(&reveal_all); - let initial_selection = mask_pixels(&reveal_selection); - assert_eq!(initial_all, initial_selection, "{id}: masks start with equal white values"); - assert_eq!(initial_all, vec![1.0; 16 * 16], "{id}: the full canvas starts revealed"); - let pixels_before = canvas_pixels(&reveal_all); - - reveal_all.execute(id, params.clone()).unwrap(); - reveal_selection.execute(id, params).unwrap(); - - let actual = mask_pixels(&reveal_all); - let expected = mask_pixels(&reveal_selection); - assert!( - actual == expected, - "{id}: Reveal All differs from Reveal Selection: first={:?}/{:?}, changed pixels={}/{}", - actual[0], - expected[0], - actual.iter().filter(|&&v| v != 1.0).count(), - expected.iter().filter(|&&v| v != 1.0).count() - ); - assert_eq!(canvas_pixels(&reveal_all), pixels_before, "{id}: the mask target must leave layer pixels unchanged"); - if id == "filter.stylize.solarize" { - assert!(actual.iter().all(|&v| v == 0.0), "Solarize maps the white mask to black"); - } else { - assert!(actual.iter().any(|&v| v != 1.0), "seeded Add Noise changes the Reveal All mask"); - } - } - } - - #[test] - fn minimum_signed_offset_matches_its_wrapped_distance() { - for depth in [8, 16, 32] { - let make_session = || { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 48, "height": 32, "depth": depth})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - paint_pattern(&mut s); - s - }; - let mut actual = make_session(); - let before = active_pixels(&actual); - actual.execute("filter.other.offset", json!({"horizontal": i32::MIN, "vertical": i32::MIN})).unwrap(); - let mut expected = make_session(); - expected.execute("filter.other.offset", json!({"horizontal": i32::MIN.rem_euclid(48), "vertical": i32::MIN.rem_euclid(32)})).unwrap(); - let after = active_pixels(&actual); - assert_eq!(after, active_pixels(&expected), "depth {depth}"); - assert_ne!(after, before); - actual.execute("edit.undo", json!({})).unwrap(); - assert_eq!(active_pixels(&actual), before); - actual.execute("edit.redo", json!({})).unwrap(); - assert_eq!(active_pixels(&actual), after); - } - } - #[test] - fn huge_offsets_clamp_instead_of_wrapping() { - // 3e9 wrapped to a negative offset through `as i32`; it saturates now, so it - // equals the maximal in-range offset instead of shifting the other way. - let mut a = session(); - a.execute("filter.other.offset", json!({"horizontal": 3_000_000_000_i64, "vertical": 0})).unwrap(); - let mut b = session(); - b.execute("filter.other.offset", json!({"horizontal": 2_147_483_647_i64, "vertical": 0})).unwrap(); - assert_eq!(active_pixels(&a), active_pixels(&b)); - } - - #[test] - fn last_filter_repeats_with_same_params() { - let mut s = session(); - paint_pattern(&mut s); - assert!(!s.is_enabled("filter.lastFilter")); - s.execute("filter.other.offset", json!({"horizontal": 3})).unwrap(); - let once = active_pixels(&s); - s.execute("filter.lastFilter", json!({})).unwrap(); - let twice = active_pixels(&s); - assert_ne!(once, twice); - // Offsetting 3 twice equals offsetting 6 once. - let mut s2 = session(); - paint_pattern(&mut s2); - s2.execute("filter.other.offset", json!({"horizontal": 6})).unwrap(); - assert_eq!(active_pixels(&s2), twice); - } - - #[test] - fn recorded_last_filter_replays_the_filter_it_repeated() { - // #3089: the action holds the filter with its settings, not a "repeat whatever ran - // last" step that fails in a new session. - let mut s = session(); - paint_pattern(&mut s); - s.execute("filter.other.offset", json!({"horizontal": 3})).unwrap(); - s.execute("actions.record", json!({"name": "Again"})).unwrap(); - s.execute("filter.lastFilter", json!({})).unwrap(); - s.execute("actions.stop", json!({})).unwrap(); - let steps = s.execute("actions.get", json!({"action": "Again"})).unwrap()["steps"].clone(); - assert_eq!(steps, json!([["filter.other.offset", {"horizontal": 3}]])); - let action = s.actions.list[0].clone(); - - let mut fresh = session(); - paint_pattern(&mut fresh); - fresh.actions.list.push(action); - let played = fresh.execute("actions.play", json!({"action": "Again"})).unwrap(); - assert!(played.get("failed").is_none(), "{played}"); - let mut direct = session(); - paint_pattern(&mut direct); - direct.execute("filter.other.offset", json!({"horizontal": 3})).unwrap(); - assert_eq!(active_pixels(&fresh), active_pixels(&direct)); - } - - #[test] - fn last_filter_applies_to_the_active_layer() { - let mut s = session(); - paint_pattern(&mut s); - let first = s.active().unwrap().active_layer.unwrap(); - // Dialogs (Filter Gallery, Camera Raw…) record the layer they ran on. - s.execute("filter.other.offset", json!({"horizontal": 3, "layer": first.0})).unwrap(); - let first_once = active_pixels(&s); - s.execute("layer.new.layer", json!({})).unwrap(); - paint_pattern(&mut s); - let before = active_pixels(&s); - s.execute("filter.lastFilter", json!({})).unwrap(); - assert_ne!(active_pixels(&s), before, "the active layer is filtered"); - let d = s.active().unwrap(); - let l = d.doc.layer(first).unwrap(); - assert_eq!(l.surface().unwrap().read_region(photocraft_geom::Rect::new(0, 0, 48, 32)), first_once, "the first layer is left alone"); - } - - #[test] - fn params_map_to_algorithm_units() { - assert_eq!(params_for("filter.blur.gaussianBlur", &json!({"radius": 4.5})), Some(FilterParams::GaussianBlur { radius: 4.5 })); - assert_eq!( - params_for("filter.blur.radialBlur", &json!({"quality": "best"})), - Some(FilterParams::RadialBlur { amount: 10.0, method: RadialMethod::Spin, quality: RadialQuality::Best, center_x: 0.5, center_y: 0.5 }) - ); - assert_eq!( - params_for("filter.noise.addNoise", &json!({"amount": 10, "distribution": "gaussian", "monochromatic": true})), - Some(FilterParams::AddNoise { amount: 10.0, distribution: Distribution::Gaussian, monochromatic: true, seed: 0 }) - ); - assert_eq!(params_for("filter.blur.gaussianBlur", &json!({"radius": -3})), Some(FilterParams::GaussianBlur { radius: 0.1 })); - assert!(params_for("filter.nope", &json!({})).is_none()); - } - - #[test] - fn minimum_maximum_preserve_roundness() { - for depth in [8, 16, 32] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 48, "height": 32, "depth": depth})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - // A white dot on black. - s.edit("dot", |doc, active| { - let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); - surf.fill_rect(photocraft_geom::Rect::new(0, 0, 48, 32), &[0.0, 0.0, 0.0, 1.0]); - surf.write_pixel(24, 16, &[1.0, 1.0, 1.0, 1.0]); - Ok(()) - }) - .unwrap(); - let before = active_pixels(&s); - let lit = |s: &Session, x: usize, y: usize| active_pixels(s)[(y * 48 + x) * 4] > 0.5; - s.execute("filter.other.maximum", json!({"radius": 4, "preserve": "roundness"})).unwrap(); - // Grown into a disc of radius 4: (4, 0) and (2, 3) are in, the square's corner isn't. - assert!(lit(&s, 28, 16) && lit(&s, 26, 19), "depth {depth}"); - assert!(!lit(&s, 28, 20) && !lit(&s, 27, 19), "depth {depth}"); - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(active_pixels(&s), before); - // The default is Squareness: the corner is taken. - s.execute("filter.other.maximum", json!({"radius": 4})).unwrap(); - assert!(lit(&s, 28, 20), "depth {depth}"); - // Minimum with roundness: only the centre of that 9×9 square holds a whole disc. - s.execute("filter.other.minimum", json!({"radius": 4, "preserve": "roundness"})).unwrap(); - assert!(!lit(&s, 20, 12) && lit(&s, 24, 16), "depth {depth}"); - } - assert_eq!( - params_for("filter.other.minimum", &json!({"radius": 2, "preserve": "roundness"})), - Some(FilterParams::Minimum { radius: 2.0, preserve: Preserve::Roundness }) - ); - assert_eq!(params_for("filter.other.maximum", &json!({})), Some(FilterParams::Maximum { radius: 1.0, preserve: Preserve::Squareness })); - } - - #[test] - fn smart_object_records_smart_filter() { - use photocraft_doc::{Layer, SmartObject, SmartSource}; - let mut s = session(); - s.edit("smart", |doc, active| { - let mut cache = photocraft_raster::Surface::new(doc.pixel_format()); - cache.fill_rect(photocraft_geom::Rect::new(0, 0, 10, 10), &[1.0, 0.0, 0.0, 1.0]); - let l = Layer::new( - "so", - LayerContent::Smart(SmartObject { - contents_id: photocraft_doc::SmartContentsId::fresh(), - source: SmartSource::Linked { path: String::new() }, - transform: photocraft_geom::Affine::IDENTITY, - smart_filters: vec![], - cache: Some(cache), - psd_raw: None, - filters_enabled: true, - filter_mask: None, - warp: None, - stack_mode: None, - perspective: None, - }), - ); - *active = Some(doc.insert_above(*active, l)); - Ok(()) - }) - .unwrap(); - s.execute("filter.blur.gaussianBlur", json!({"radius": 2})).unwrap(); - let d = s.active().unwrap(); - let LayerContent::Smart(sm) = &d.doc.layer(d.active_layer.unwrap()).unwrap().content else { panic!() }; - assert_eq!(sm.smart_filters.len(), 1); - assert_eq!(sm.smart_filters[0].command, "filter.blur.gaussianBlur"); - assert_eq!(sm.smart_filters[0].params["radius"], json!(2)); - assert!(sm.cache.as_ref().unwrap().pixel(10, 5)[3] > 0.0, "cache was blurred"); - } - - /// The serial `keep_alpha` before #6205, kept as the oracle for the parallel one. - fn keep_alpha_serial(old: &photocraft_raster::Surface, new: &mut photocraft_raster::Surface) { - if old.format() != new.format() || !new.format().alpha { - return; - } - let mut coords: Vec<_> = new.tiles().filter(|(c, t)| old.tile(**c).is_none_or(|o| !std::sync::Arc::ptr_eq(o, t))).map(|(c, _)| *c).collect(); - coords.extend(old.tiles().filter(|(c, _)| new.tile(**c).is_none()).map(|(c, _)| *c)); - let n = new.channels(); - for c in coords { - let r = c.rect(); - let o = old.read_region(r); - let mut v = new.read_region(r); - for (pn, po) in v.chunks_exact_mut(n).zip(o.chunks_exact(n)) { - if let (Some(a), Some(b)) = (pn.last_mut(), po.last()) { - *a = *b; - } - } - new.write_region(r, &v); - } - new.prune(); - } - - /// A layer before and after a filter: tiles the filter changed, one it left shared, one it - /// emptied (only in `old`) and one it added (only in `new`). - fn alpha_pair(sample: photocraft_color::SampleType) -> (photocraft_raster::Surface, photocraft_raster::Surface) { - use photocraft_geom::Rect; - use photocraft_raster::Surface; - let fmt = photocraft_color::PixelFormat { mode: photocraft_color::ColorMode::Rgb, sample, alpha: true }; - let pattern = |r: Rect, k: f32| -> Vec { - (0..r.width() as usize * r.height() as usize * 4).map(|i| ((i as f32 * 0.37 + k).sin() * 0.5 + 0.5).clamp(0.0, 1.0)).collect() - }; - let mut old = Surface::new(fmt); - let r = Rect::new(-40, -20, 700, 300); - old.write_region(r, &pattern(r, 0.0)); - let mut new = old.clone(); - let changed = Rect::new(-40, -20, 400, 300); - new.write_region(changed, &pattern(changed, 1.3)); - let emptied = photocraft_geom::TileCoord::containing(600, 100).rect(); - drop(new.take_tiles(emptied)); - let added = Rect::new(800, 0, 900, 50); - new.write_region(added, &pattern(added, 2.1)); - (old, new) - } - - #[test] - fn keep_alpha_matches_the_serial_pass_at_every_depth() { - use photocraft_color::SampleType; - for sample in [SampleType::U8, SampleType::U16, SampleType::F32] { - let (old, new) = alpha_pair(sample); - let mut want = new.clone(); - keep_alpha_serial(&old, &mut want); - let mut got = new.clone(); - keep_alpha(&old, &mut got, &|| false).unwrap(); - assert!(got == want, "{sample:?}: parallel keep_alpha differs from the serial pass"); - assert_ne!(got, new, "{sample:?}: alpha was put back"); - } - } - - #[test] - fn keep_alpha_stops_when_cancelled_and_keeps_the_tiles() { - let (old, new) = alpha_pair(photocraft_color::SampleType::U8); - let mut got = new.clone(); - let calls = std::sync::atomic::AtomicUsize::new(0); - let cancel = || calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst) >= 2; - assert!(matches!(keep_alpha(&old, &mut got, &cancel), Err(EngineError::Cancelled))); - // The cancel was seen inside the pass (after some tiles), and no tile went missing. - assert!(calls.load(std::sync::atomic::Ordering::SeqCst) > 2); - assert!(new.tiles().all(|(c, _)| got.tile(*c).is_some())); - } - - /// #7423: Displace on a Smart Object keeps its map (read from an open document) in the smart - /// filter, as Photoshop embeds it, so the filter displaces and keeps displacing when the - /// object re-renders. A map chosen again replaces it. - #[test] - fn displace_on_a_smart_object_embeds_its_map() { - let mut s = Session::new(); - // Documents 0 and 1: a white and a black displacement map. - s.execute("file.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap(); - s.execute("file.new", json!({"width": 8, "height": 8, "background": "black"})).unwrap(); - s.execute("file.new", json!({"width": 48, "height": 32, "background": "transparent"})).unwrap(); - s.edit("square", |doc, active| { - let fmt = doc.pixel_format(); - let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); - surf.fill_rect(photocraft_geom::Rect::new(10, 10, 20, 12), &photocraft_raster::from_rgba(&fmt, [1.0, 0.0, 0.0, 1.0])); - Ok(()) - }) - .unwrap(); - s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - let original = { - let d = s.active().unwrap(); - let LayerContent::Smart(sm) = &d.doc.layer(d.active_layer.unwrap()).unwrap().content else { panic!("not a smart object") }; - sm.cache.as_ref().unwrap().read_region(d.doc.bounds()) - }; - let smart = |s: &Session| { - let d = s.active().unwrap(); - let LayerContent::Smart(sm) = &d.doc.layer(d.active_layer.unwrap()).unwrap().content else { panic!("not a smart object") }; - (sm.smart_filters[0].params.clone(), sm.cache.as_ref().unwrap().read_region(d.doc.bounds())) - }; - let first_value = |params: &Value| photocraft_io::smart_map::displace_embedded_map(params).expect("an embedded map").data[0]; - - s.execute("filter.distort.displace", json!({"horizontal": 10, "vertical": 0, "mapDocument": 0})).unwrap(); - let (params, displaced) = smart(&s); - assert!(params.get("mapDocument").is_none(), "{params}"); - assert_eq!(first_value(¶ms), 1.0, "the white map"); - assert_ne!(displaced, original, "the smart object is displaced"); - // Re-rendered from its params alone (the filter hidden and shown again): still displaced. - s.execute("layer.smartFilter.setVisible", json!({"index": 0, "visible": false})).unwrap(); - assert_eq!(smart(&s).1, original); - s.execute("layer.smartFilter.setVisible", json!({"index": 0, "visible": true})).unwrap(); - assert_eq!(smart(&s).1, displaced); - - // Another map chosen for the filter replaces the embedded one. - s.execute("layer.smartFilter.setParams", json!({"index": 0, "params": {"mapDocument": 1}})).unwrap(); - let (params, again) = smart(&s); - assert!(params.get("mapDocument").is_none(), "{params}"); - assert_eq!(first_value(¶ms), 0.0, "the black map"); - assert_ne!(again, displaced, "displaced the other way"); - - // The stored params passed back whole (the old embedded map included) with another map - // named: the named map wins, for the filter's own edit and for a new Displace alike. - let mut back = params.as_object().unwrap().clone(); - back.insert("mapDocument".into(), json!(0)); - s.execute("layer.smartFilter.setParams", json!({"index": 0, "params": back.clone()})).unwrap(); - assert_eq!(first_value(&smart(&s).0), 1.0, "the white map, not the embedded black one"); - back.insert("mapDocument".into(), json!(1)); - s.execute("filter.distort.displace", Value::Object(back)).unwrap(); - let d = s.active().unwrap(); - let LayerContent::Smart(sm) = &d.doc.layer(d.active_layer.unwrap()).unwrap().content else { panic!("not a smart object") }; - assert_eq!(first_value(&sm.smart_filters[1].params), 0.0, "the black map, not the passed-back white one"); - } -} +mod tests; diff --git a/crates/engine/src/filters/tests.rs b/crates/engine/src/filters/tests.rs new file mode 100644 index 0000000000..5b3f3a3703 --- /dev/null +++ b/crates/engine/src/filters/tests.rs @@ -0,0 +1,515 @@ +use super::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 48, "height": 32})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("edit.fill", json!({"color": "#3366cc"})).ok(); + s +} + +fn active_pixels(s: &Session) -> Vec { + let d = s.active().unwrap(); + let l = d.doc.layer(d.active_layer.unwrap()).unwrap(); + l.surface().unwrap().read_region(photocraft_geom::Rect::new(0, 0, 48, 32)) +} + +fn mask_session(reveal_selection: bool) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16, "background": "#ff0000"})).unwrap(); + if reveal_selection { + s.execute("select.all", json!({})).unwrap(); + s.execute("layer.layerMask.revealSelection", json!({})).unwrap(); + } else { + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + } + s +} + +fn mask_pixels(s: &Session) -> Vec { + let d = s.active().unwrap(); + let mask = d.doc.layer(d.active_layer.unwrap()).unwrap().mask.as_ref().unwrap(); + mask.surface.read_region(d.doc.bounds()) +} + +fn canvas_pixels(s: &Session) -> Vec { + let d = s.active().unwrap(); + d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap().read_region(d.doc.bounds()) +} + +fn paint_pattern(s: &mut Session) { + s.edit("pattern", |doc, active| { + let l = doc.layer_mut(active.unwrap()).unwrap(); + let surf = l.surface_mut().unwrap(); + for y in 0..32 { + for x in 0..48 { + let v = ((x * 5 + y * 3) % 17) as f32 / 16.0; + surf.write_pixel(x, y, &[v, 1.0 - v, (x % 3) as f32 / 2.0, 1.0]); + } + } + Ok(()) + }) + .unwrap(); +} + +const ALL: [&str; 24] = [ + "filter.blur.gaussianBlur", + "filter.blur.boxBlur", + "filter.blur.motionBlur", + "filter.blur.radialBlur", + "filter.blur.surfaceBlur", + "filter.sharpen.unsharpMask", + "filter.sharpen.smartSharpen", + "filter.noise.addNoise", + "filter.noise.median", + "filter.noise.dustAndScratches", + "filter.pixelate.mosaic", + "filter.stylize.emboss", + "filter.stylize.findEdges", + "filter.stylize.solarize", + "filter.distort.twirl", + "filter.distort.pinch", + "filter.distort.spherize", + "filter.distort.wave", + "filter.distort.ripple", + "filter.distort.polarCoordinates", + "filter.other.highPass", + "filter.other.minimum", + "filter.other.maximum", + "filter.other.offset", +]; + +#[test] +fn every_filter_command_runs_changes_pixels_and_undoes() { + for id in ALL { + let mut s = session(); + paint_pattern(&mut s); + let before = active_pixels(&s); + let params = match id { + "filter.other.offset" => json!({"horizontal": 5, "vertical": 2}), + "filter.noise.dustAndScratches" => json!({"radius": 2, "threshold": 0}), + "filter.noise.median" => json!({"radius": 2}), + _ => json!({}), + }; + let r = s.execute(id, params).unwrap_or_else(|e| panic!("{id}: {e}")); + assert!(r.get("filter").is_some(), "{id}"); + assert_ne!(active_pixels(&s), before, "{id} changed nothing"); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(active_pixels(&s), before, "{id} undo"); + } +} + +#[test] +fn preset_filters_record_their_own_name() { + // #528: one-step presets run a generic algorithm but name the step after themselves; + // the generic commands keep the algorithm's name. + let specs = specs(); + for (id, name) in [ + ("filter.blur.blur", "Blur"), + ("filter.blur.blurMore", "Blur More"), + ("filter.sharpen.sharpen", "Sharpen"), + ("filter.sharpen.sharpenMore", "Sharpen More"), + ("filter.sharpen.sharpenEdges", "Sharpen Edges"), + ("filter.noise.despeckle", "Despeckle"), + ("filter.blur.gaussianBlur", "Gaussian Blur"), + ("filter.sharpen.unsharpMask", "Unsharp Mask"), + ("filter.blur.surfaceBlur", "Surface Blur"), + ] { + let mut s = session(); + let steps = s.active().unwrap().history.past_len(); + s.execute(id, json!({})).unwrap(); + let h = &s.active().unwrap().history; + assert_eq!((h.past_len(), h.undo_label()), (steps + 1, Some(name)), "{id}"); + let label = specs.iter().find(|c| c.id == id).unwrap().label; + assert_eq!(label.trim_end_matches('…'), name, "{id}: the step is named like the command"); + } +} + +#[test] +fn specs_are_complete_and_documented() { + let specs = specs(); + for id in ALL { + let spec = specs.iter().find(|c| c.id == id).unwrap_or_else(|| panic!("missing {id}")); + assert!(spec.params.starts_with('{'), "{id}"); + assert!(!spec.menu.is_empty(), "{id}"); + } +} + +#[test] +fn disabled_without_pixel_layer() { + let mut s = Session::new(); + assert!(!s.is_enabled("filter.blur.gaussianBlur")); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + s.execute("layer.newAdjustmentLayer.invert", json!({})).unwrap(); + assert!(matches!(s.execute("filter.blur.gaussianBlur", json!({})), Err(EngineError::Disabled(..)))); +} + +#[test] +fn selection_limits_the_filter() { + let mut s = session(); + paint_pattern(&mut s); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + let has_sel = s.active().unwrap().doc.selection.is_some(); + assert!(has_sel); + let before = active_pixels(&s); + s.execute("filter.blur.gaussianBlur", json!({"radius": 3})).unwrap(); + let after = active_pixels(&s); + if has_sel { + // A pixel far from the selection is unchanged. + let i = (30 * 48 + 40) * 4; + assert_eq!(after[i..i + 4], before[i..i + 4]); + let j = (5 * 48 + 5) * 4; + assert_ne!(after[j..j + 4], before[j..j + 4]); + } +} + +#[test] +fn solarize_and_add_noise_process_untouched_reveal_all_masks() { + for (id, params) in [ + ("filter.stylize.solarize", json!({"target": "mask"})), + ("filter.noise.addNoise", json!({"amount": 100, "seed": 1, "monochromatic": true, "target": "mask"})), + ] { + let mut reveal_all = mask_session(false); + let mut reveal_selection = mask_session(true); + let all_mask = reveal_all.active().unwrap().doc.layer(reveal_all.active().unwrap().active_layer.unwrap()).unwrap().mask.as_ref().unwrap(); + assert!(all_mask.surface.content_bounds().is_empty(), "{id}: Reveal All stores its white canvas in the default pixel"); + let initial_all = mask_pixels(&reveal_all); + let initial_selection = mask_pixels(&reveal_selection); + assert_eq!(initial_all, initial_selection, "{id}: masks start with equal white values"); + assert_eq!(initial_all, vec![1.0; 16 * 16], "{id}: the full canvas starts revealed"); + let pixels_before = canvas_pixels(&reveal_all); + + reveal_all.execute(id, params.clone()).unwrap(); + reveal_selection.execute(id, params).unwrap(); + + let actual = mask_pixels(&reveal_all); + let expected = mask_pixels(&reveal_selection); + assert!( + actual == expected, + "{id}: Reveal All differs from Reveal Selection: first={:?}/{:?}, changed pixels={}/{}", + actual[0], + expected[0], + actual.iter().filter(|&&v| v != 1.0).count(), + expected.iter().filter(|&&v| v != 1.0).count() + ); + assert_eq!(canvas_pixels(&reveal_all), pixels_before, "{id}: the mask target must leave layer pixels unchanged"); + if id == "filter.stylize.solarize" { + assert!(actual.iter().all(|&v| v == 0.0), "Solarize maps the white mask to black"); + } else { + assert!(actual.iter().any(|&v| v != 1.0), "seeded Add Noise changes the Reveal All mask"); + } + } +} + +#[test] +fn minimum_signed_offset_matches_its_wrapped_distance() { + for depth in [8, 16, 32] { + let make_session = || { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 48, "height": 32, "depth": depth})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + paint_pattern(&mut s); + s + }; + let mut actual = make_session(); + let before = active_pixels(&actual); + actual.execute("filter.other.offset", json!({"horizontal": i32::MIN, "vertical": i32::MIN})).unwrap(); + let mut expected = make_session(); + expected.execute("filter.other.offset", json!({"horizontal": i32::MIN.rem_euclid(48), "vertical": i32::MIN.rem_euclid(32)})).unwrap(); + let after = active_pixels(&actual); + assert_eq!(after, active_pixels(&expected), "depth {depth}"); + assert_ne!(after, before); + actual.execute("edit.undo", json!({})).unwrap(); + assert_eq!(active_pixels(&actual), before); + actual.execute("edit.redo", json!({})).unwrap(); + assert_eq!(active_pixels(&actual), after); + } +} +#[test] +fn huge_offsets_clamp_instead_of_wrapping() { + // 3e9 wrapped to a negative offset through `as i32`; it saturates now, so it + // equals the maximal in-range offset instead of shifting the other way. + let mut a = session(); + a.execute("filter.other.offset", json!({"horizontal": 3_000_000_000_i64, "vertical": 0})).unwrap(); + let mut b = session(); + b.execute("filter.other.offset", json!({"horizontal": 2_147_483_647_i64, "vertical": 0})).unwrap(); + assert_eq!(active_pixels(&a), active_pixels(&b)); +} + +#[test] +fn last_filter_repeats_with_same_params() { + let mut s = session(); + paint_pattern(&mut s); + assert!(!s.is_enabled("filter.lastFilter")); + s.execute("filter.other.offset", json!({"horizontal": 3})).unwrap(); + let once = active_pixels(&s); + s.execute("filter.lastFilter", json!({})).unwrap(); + let twice = active_pixels(&s); + assert_ne!(once, twice); + // Offsetting 3 twice equals offsetting 6 once. + let mut s2 = session(); + paint_pattern(&mut s2); + s2.execute("filter.other.offset", json!({"horizontal": 6})).unwrap(); + assert_eq!(active_pixels(&s2), twice); +} + +#[test] +fn recorded_last_filter_replays_the_filter_it_repeated() { + // #3089: the action holds the filter with its settings, not a "repeat whatever ran + // last" step that fails in a new session. + let mut s = session(); + paint_pattern(&mut s); + s.execute("filter.other.offset", json!({"horizontal": 3})).unwrap(); + s.execute("actions.record", json!({"name": "Again"})).unwrap(); + s.execute("filter.lastFilter", json!({})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + let steps = s.execute("actions.get", json!({"action": "Again"})).unwrap()["steps"].clone(); + assert_eq!(steps, json!([["filter.other.offset", {"horizontal": 3}]])); + let action = s.actions.list[0].clone(); + + let mut fresh = session(); + paint_pattern(&mut fresh); + fresh.actions.list.push(action); + let played = fresh.execute("actions.play", json!({"action": "Again"})).unwrap(); + assert!(played.get("failed").is_none(), "{played}"); + let mut direct = session(); + paint_pattern(&mut direct); + direct.execute("filter.other.offset", json!({"horizontal": 3})).unwrap(); + assert_eq!(active_pixels(&fresh), active_pixels(&direct)); +} + +#[test] +fn last_filter_applies_to_the_active_layer() { + let mut s = session(); + paint_pattern(&mut s); + let first = s.active().unwrap().active_layer.unwrap(); + // Dialogs (Filter Gallery, Camera Raw…) record the layer they ran on. + s.execute("filter.other.offset", json!({"horizontal": 3, "layer": first.0})).unwrap(); + let first_once = active_pixels(&s); + s.execute("layer.new.layer", json!({})).unwrap(); + paint_pattern(&mut s); + let before = active_pixels(&s); + s.execute("filter.lastFilter", json!({})).unwrap(); + assert_ne!(active_pixels(&s), before, "the active layer is filtered"); + let d = s.active().unwrap(); + let l = d.doc.layer(first).unwrap(); + assert_eq!(l.surface().unwrap().read_region(photocraft_geom::Rect::new(0, 0, 48, 32)), first_once, "the first layer is left alone"); +} + +#[test] +fn params_map_to_algorithm_units() { + assert_eq!(params_for("filter.blur.gaussianBlur", &json!({"radius": 4.5})), Some(FilterParams::GaussianBlur { radius: 4.5 })); + assert_eq!( + params_for("filter.blur.radialBlur", &json!({"quality": "best"})), + Some(FilterParams::RadialBlur { amount: 10.0, method: RadialMethod::Spin, quality: RadialQuality::Best, center_x: 0.5, center_y: 0.5 }) + ); + assert_eq!( + params_for("filter.noise.addNoise", &json!({"amount": 10, "distribution": "gaussian", "monochromatic": true})), + Some(FilterParams::AddNoise { amount: 10.0, distribution: Distribution::Gaussian, monochromatic: true, seed: 0 }) + ); + assert_eq!(params_for("filter.blur.gaussianBlur", &json!({"radius": -3})), Some(FilterParams::GaussianBlur { radius: 0.1 })); + assert!(params_for("filter.nope", &json!({})).is_none()); +} + +#[test] +fn minimum_maximum_preserve_roundness() { + for depth in [8, 16, 32] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 48, "height": 32, "depth": depth})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + // A white dot on black. + s.edit("dot", |doc, active| { + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + surf.fill_rect(photocraft_geom::Rect::new(0, 0, 48, 32), &[0.0, 0.0, 0.0, 1.0]); + surf.write_pixel(24, 16, &[1.0, 1.0, 1.0, 1.0]); + Ok(()) + }) + .unwrap(); + let before = active_pixels(&s); + let lit = |s: &Session, x: usize, y: usize| active_pixels(s)[(y * 48 + x) * 4] > 0.5; + s.execute("filter.other.maximum", json!({"radius": 4, "preserve": "roundness"})).unwrap(); + // Grown into a disc of radius 4: (4, 0) and (2, 3) are in, the square's corner isn't. + assert!(lit(&s, 28, 16) && lit(&s, 26, 19), "depth {depth}"); + assert!(!lit(&s, 28, 20) && !lit(&s, 27, 19), "depth {depth}"); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(active_pixels(&s), before); + // The default is Squareness: the corner is taken. + s.execute("filter.other.maximum", json!({"radius": 4})).unwrap(); + assert!(lit(&s, 28, 20), "depth {depth}"); + // Minimum with roundness: only the centre of that 9×9 square holds a whole disc. + s.execute("filter.other.minimum", json!({"radius": 4, "preserve": "roundness"})).unwrap(); + assert!(!lit(&s, 20, 12) && lit(&s, 24, 16), "depth {depth}"); + } + assert_eq!( + params_for("filter.other.minimum", &json!({"radius": 2, "preserve": "roundness"})), + Some(FilterParams::Minimum { radius: 2.0, preserve: Preserve::Roundness }) + ); + assert_eq!(params_for("filter.other.maximum", &json!({})), Some(FilterParams::Maximum { radius: 1.0, preserve: Preserve::Squareness })); +} + +#[test] +fn smart_object_records_smart_filter() { + use photocraft_doc::{Layer, SmartObject, SmartSource}; + let mut s = session(); + s.edit("smart", |doc, active| { + let mut cache = photocraft_raster::Surface::new(doc.pixel_format()); + cache.fill_rect(photocraft_geom::Rect::new(0, 0, 10, 10), &[1.0, 0.0, 0.0, 1.0]); + let l = Layer::new( + "so", + LayerContent::Smart(SmartObject { + contents_id: photocraft_doc::SmartContentsId::fresh(), + source: SmartSource::Linked { path: String::new() }, + transform: photocraft_geom::Affine::IDENTITY, + smart_filters: vec![], + cache: Some(cache), + psd_raw: None, + filters_enabled: true, + filter_mask: None, + warp: None, + stack_mode: None, + perspective: None, + }), + ); + *active = Some(doc.insert_above(*active, l)); + Ok(()) + }) + .unwrap(); + s.execute("filter.blur.gaussianBlur", json!({"radius": 2})).unwrap(); + let d = s.active().unwrap(); + let LayerContent::Smart(sm) = &d.doc.layer(d.active_layer.unwrap()).unwrap().content else { panic!() }; + assert_eq!(sm.smart_filters.len(), 1); + assert_eq!(sm.smart_filters[0].command, "filter.blur.gaussianBlur"); + assert_eq!(sm.smart_filters[0].params["radius"], json!(2)); + assert!(sm.cache.as_ref().unwrap().pixel(10, 5)[3] > 0.0, "cache was blurred"); +} + +/// The serial `keep_alpha` before #6205, kept as the oracle for the parallel one. +fn keep_alpha_serial(old: &photocraft_raster::Surface, new: &mut photocraft_raster::Surface) { + if old.format() != new.format() || !new.format().alpha { + return; + } + let mut coords: Vec<_> = new.tiles().filter(|(c, t)| old.tile(**c).is_none_or(|o| !std::sync::Arc::ptr_eq(o, t))).map(|(c, _)| *c).collect(); + coords.extend(old.tiles().filter(|(c, _)| new.tile(**c).is_none()).map(|(c, _)| *c)); + let n = new.channels(); + for c in coords { + let r = c.rect(); + let o = old.read_region(r); + let mut v = new.read_region(r); + for (pn, po) in v.chunks_exact_mut(n).zip(o.chunks_exact(n)) { + if let (Some(a), Some(b)) = (pn.last_mut(), po.last()) { + *a = *b; + } + } + new.write_region(r, &v); + } + new.prune(); +} + +/// A layer before and after a filter: tiles the filter changed, one it left shared, one it +/// emptied (only in `old`) and one it added (only in `new`). +fn alpha_pair(sample: photocraft_color::SampleType) -> (photocraft_raster::Surface, photocraft_raster::Surface) { + use photocraft_geom::Rect; + use photocraft_raster::Surface; + let fmt = photocraft_color::PixelFormat { mode: photocraft_color::ColorMode::Rgb, sample, alpha: true }; + let pattern = |r: Rect, k: f32| -> Vec { + (0..r.width() as usize * r.height() as usize * 4).map(|i| ((i as f32 * 0.37 + k).sin() * 0.5 + 0.5).clamp(0.0, 1.0)).collect() + }; + let mut old = Surface::new(fmt); + let r = Rect::new(-40, -20, 700, 300); + old.write_region(r, &pattern(r, 0.0)); + let mut new = old.clone(); + let changed = Rect::new(-40, -20, 400, 300); + new.write_region(changed, &pattern(changed, 1.3)); + let emptied = photocraft_geom::TileCoord::containing(600, 100).rect(); + drop(new.take_tiles(emptied)); + let added = Rect::new(800, 0, 900, 50); + new.write_region(added, &pattern(added, 2.1)); + (old, new) +} + +#[test] +fn keep_alpha_matches_the_serial_pass_at_every_depth() { + use photocraft_color::SampleType; + for sample in [SampleType::U8, SampleType::U16, SampleType::F32] { + let (old, new) = alpha_pair(sample); + let mut want = new.clone(); + keep_alpha_serial(&old, &mut want); + let mut got = new.clone(); + keep_alpha(&old, &mut got, &|| false).unwrap(); + assert!(got == want, "{sample:?}: parallel keep_alpha differs from the serial pass"); + assert_ne!(got, new, "{sample:?}: alpha was put back"); + } +} + +#[test] +fn keep_alpha_stops_when_cancelled_and_keeps_the_tiles() { + let (old, new) = alpha_pair(photocraft_color::SampleType::U8); + let mut got = new.clone(); + let calls = std::sync::atomic::AtomicUsize::new(0); + let cancel = || calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst) >= 2; + assert!(matches!(keep_alpha(&old, &mut got, &cancel), Err(EngineError::Cancelled))); + // The cancel was seen inside the pass (after some tiles), and no tile went missing. + assert!(calls.load(std::sync::atomic::Ordering::SeqCst) > 2); + assert!(new.tiles().all(|(c, _)| got.tile(*c).is_some())); +} + +/// #7423: Displace on a Smart Object keeps its map (read from an open document) in the smart +/// filter, as Photoshop embeds it, so the filter displaces and keeps displacing when the +/// object re-renders. A map chosen again replaces it. +#[test] +fn displace_on_a_smart_object_embeds_its_map() { + let mut s = Session::new(); + // Documents 0 and 1: a white and a black displacement map. + s.execute("file.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap(); + s.execute("file.new", json!({"width": 8, "height": 8, "background": "black"})).unwrap(); + s.execute("file.new", json!({"width": 48, "height": 32, "background": "transparent"})).unwrap(); + s.edit("square", |doc, active| { + let fmt = doc.pixel_format(); + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + surf.fill_rect(photocraft_geom::Rect::new(10, 10, 20, 12), &photocraft_raster::from_rgba(&fmt, [1.0, 0.0, 0.0, 1.0])); + Ok(()) + }) + .unwrap(); + s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + let original = { + let d = s.active().unwrap(); + let LayerContent::Smart(sm) = &d.doc.layer(d.active_layer.unwrap()).unwrap().content else { panic!("not a smart object") }; + sm.cache.as_ref().unwrap().read_region(d.doc.bounds()) + }; + let smart = |s: &Session| { + let d = s.active().unwrap(); + let LayerContent::Smart(sm) = &d.doc.layer(d.active_layer.unwrap()).unwrap().content else { panic!("not a smart object") }; + (sm.smart_filters[0].params.clone(), sm.cache.as_ref().unwrap().read_region(d.doc.bounds())) + }; + let first_value = |params: &Value| photocraft_io::smart_map::displace_embedded_map(params).expect("an embedded map").data[0]; + + s.execute("filter.distort.displace", json!({"horizontal": 10, "vertical": 0, "mapDocument": 0})).unwrap(); + let (params, displaced) = smart(&s); + assert!(params.get("mapDocument").is_none(), "{params}"); + assert_eq!(first_value(¶ms), 1.0, "the white map"); + assert_ne!(displaced, original, "the smart object is displaced"); + // Re-rendered from its params alone (the filter hidden and shown again): still displaced. + s.execute("layer.smartFilter.setVisible", json!({"index": 0, "visible": false})).unwrap(); + assert_eq!(smart(&s).1, original); + s.execute("layer.smartFilter.setVisible", json!({"index": 0, "visible": true})).unwrap(); + assert_eq!(smart(&s).1, displaced); + + // Another map chosen for the filter replaces the embedded one. + s.execute("layer.smartFilter.setParams", json!({"index": 0, "params": {"mapDocument": 1}})).unwrap(); + let (params, again) = smart(&s); + assert!(params.get("mapDocument").is_none(), "{params}"); + assert_eq!(first_value(¶ms), 0.0, "the black map"); + assert_ne!(again, displaced, "displaced the other way"); + + // The stored params passed back whole (the old embedded map included) with another map + // named: the named map wins, for the filter's own edit and for a new Displace alike. + let mut back = params.as_object().unwrap().clone(); + back.insert("mapDocument".into(), json!(0)); + s.execute("layer.smartFilter.setParams", json!({"index": 0, "params": back.clone()})).unwrap(); + assert_eq!(first_value(&smart(&s).0), 1.0, "the white map, not the embedded black one"); + back.insert("mapDocument".into(), json!(1)); + s.execute("filter.distort.displace", Value::Object(back)).unwrap(); + let d = s.active().unwrap(); + let LayerContent::Smart(sm) = &d.doc.layer(d.active_layer.unwrap()).unwrap().content else { panic!("not a smart object") }; + assert_eq!(first_value(&sm.smart_filters[1].params), 0.0, "the black map, not the passed-back white one"); +} diff --git a/crates/engine/src/filters/validation.rs b/crates/engine/src/filters/validation.rs index f9bc1a4eec..2744524a85 100644 --- a/crates/engine/src/filters/validation.rs +++ b/crates/engine/src/filters/validation.rs @@ -176,368 +176,4 @@ pub(crate) fn validate_params(id: &str, params: &Value) -> Result<()> { } #[cfg(test)] -mod tests { - use std::sync::Arc; - - use photocraft_geom::Rect; - use serde_json::json; - - use super::*; - use crate::Session; - - fn session(depth: u32) -> Session { - let mut s = Session::new(); - s.execute("file.new", json!({"width":16,"height":12,"depth":depth})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.edit("pattern", |doc, active| { - let surface = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); - surface.fill_rect(Rect::new(0, 0, 8, 12), &[0.2, 0.6, 0.8, 1.0]); - Ok(()) - }) - .unwrap(); - s - } - - fn rejected(s: &mut Session, id: &str, key: &str, value: Value) { - let doc = s.active().unwrap().doc.clone(); - let history = s.active().unwrap().history.entries(); - let journal = s.journal.clone(); - let active = s.active().unwrap().active_layer; - let error = s.execute(id, json!({key:value})).unwrap_err(); - assert!(matches!(error, EngineError::BadParams { .. }), "{id}: {error}"); - let error = error.to_string(); - assert!(error.contains(id) && error.contains(key), "{error}"); - assert!(Arc::ptr_eq(&s.active().unwrap().doc, &doc), "{id}: {key}"); - assert_eq!(s.active().unwrap().history.entries(), history); - assert_eq!(s.active().unwrap().active_layer, active); - assert_eq!(s.journal, journal); - assert!(s.jobs().is_empty()); - } - - #[test] - fn every_core_filter_rejects_unknown_keys_without_editing() { - for depth in [8, 16, 32] { - let mut s = session(depth); - for spec in crate::filters::specs().into_iter().filter(|s| s.id != "filter.lastFilter") { - rejected(&mut s, spec.id, "radus", json!(3)); - } - } - } - - #[test] - fn core_filter_numbers_reject_wrong_types_and_documented_range_violations() { - // Each numeric field in the core registry, independently of the validation table. - let cases = [ - ("blur.gaussianBlur", "radius", 0.1, 1000.0), - ("blur.boxBlur", "radius", 1.0, 2000.0), - ("blur.motionBlur", "angle", -360.0, 360.0), - ("blur.motionBlur", "distance", 1.0, 2000.0), - ("blur.radialBlur", "amount", 1.0, 100.0), - ("blur.radialBlur", "centerX", 0.0, 1.0), - ("blur.radialBlur", "centerY", 0.0, 1.0), - ("blur.surfaceBlur", "radius", 1.0, 100.0), - ("blur.surfaceBlur", "threshold", 2.0, 255.0), - ("sharpen.unsharpMask", "amount", 1.0, 500.0), - ("sharpen.unsharpMask", "radius", 0.1, 1000.0), - ("sharpen.unsharpMask", "threshold", 0.0, 255.0), - ("sharpen.smartSharpen", "amount", 1.0, 500.0), - ("sharpen.smartSharpen", "radius", 0.1, 64.0), - ("sharpen.smartSharpen", "reduceNoise", 0.0, 100.0), - ("noise.addNoise", "amount", 0.1, 400.0), - ("noise.median", "radius", 1.0, 500.0), - ("noise.dustAndScratches", "radius", 1.0, 500.0), - ("noise.dustAndScratches", "threshold", 0.0, 255.0), - ("pixelate.mosaic", "cellSize", 2.0, 200.0), - ("stylize.emboss", "angle", -180.0, 180.0), - ("stylize.emboss", "height", 1.0, 100.0), - ("stylize.emboss", "amount", 1.0, 500.0), - ("distort.twirl", "angle", -999.0, 999.0), - ("distort.pinch", "amount", -100.0, 100.0), - ("distort.spherize", "amount", -100.0, 100.0), - ("distort.wave", "generators", 1.0, 999.0), - ("distort.wave", "wavelengthMin", 1.0, 998.0), - ("distort.wave", "wavelengthMax", 2.0, 999.0), - ("distort.wave", "amplitudeMin", 1.0, 998.0), - ("distort.wave", "amplitudeMax", 1.0, 999.0), - ("distort.ripple", "amount", -999.0, 999.0), - ("other.highPass", "radius", 0.1, 1000.0), - ("other.minimum", "radius", 0.2, 500.0), - ("other.maximum", "radius", 0.2, 500.0), - ]; - for depth in [8, 16, 32] { - let mut s = session(depth); - for (suffix, key, min, max) in cases { - let id = format!("filter.{suffix}"); - for value in [json!("big"), json!(true), Value::Null, json!([]), json!({}), json!(min - 0.01), json!(max + 0.01)] { - rejected(&mut s, &id, key, value); - } - // Large limits are validated without allocating a large blur kernel. - for value in [min, max] { - validate_params(&id, &json!({key:value})).unwrap(); - } - } - for key in ["horizontal", "vertical"] { - rejected(&mut s, "filter.other.offset", key, json!("4")); - } - } - } - - #[test] - fn core_filter_choices_booleans_seeds_and_shared_fields_are_validated() { - let mut s = session(8); - for (suffix, key, choices) in [ - ("blur.radialBlur", "method", "spin|zoom"), - ("blur.radialBlur", "quality", "draft|good|best"), - ("noise.addNoise", "distribution", "uniform|gaussian"), - ("distort.spherize", "mode", "normal|horizontalOnly|verticalOnly"), - ("distort.wave", "type", "sine|triangle|square"), - ("distort.wave", "undefinedAreas", "wrap|repeat"), - ("distort.ripple", "size", "small|medium|large"), - ("distort.polarCoordinates", "mode", "rectangularToPolar|polarToRectangular"), - ("other.minimum", "preserve", "squareness|roundness"), - ("other.maximum", "preserve", "squareness|roundness"), - ("other.offset", "undefinedAreas", "wrap|repeat|transparent"), - ] { - let id = format!("filter.{suffix}"); - for value in [json!("typo"), json!(false), json!(1), Value::Null] { - rejected(&mut s, &id, key, value); - } - for value in choices.split('|') { - validate_params(&id, &json!({key:value})).unwrap(); - } - } - for value in [json!("true"), json!(0), Value::Null] { - rejected(&mut s, "filter.noise.addNoise", "monochromatic", value); - } - for id in ["filter.noise.addNoise", "filter.distort.wave"] { - for value in [json!(-1), json!(4_294_967_296_u64), json!(0.5), json!("12")] { - rejected(&mut s, id, "seed", value); - } - // A valid u32 seed must not be saturated through an i32 helper. - let result = s.execute(id, json!({"seed":u32::MAX})).unwrap(); - assert_eq!(result["filter"]["seed"], json!(u32::MAX)); - } - for (key, value) in [("layer", json!("2")), ("target", json!("typo")), ("target", json!({"channel":-1})), ("coalesce", json!(false))] { - rejected(&mut s, "filter.blur.gaussianBlur", key, value); - } - } - - #[test] - fn extended_filter_choices_match_their_specs_and_reject_unlisted_values() { - let mut s = session(8); - let specs = crate::filters_ext::specs(); - let ids = [ - "filter.pixelate.mezzotint", - "filter.stylize.diffuse", - "filter.stylize.extrude", - "filter.stylize.tiles", - "filter.stylize.traceContour", - "filter.stylize.wind", - "filter.distort.displace", - "filter.distort.shear", - "filter.distort.zigZag", - "filter.render.lensFlare", - "filter.render.lightingEffects", - "filter.blur.lensBlur", - "filter.other.hsbHsl", - "filter.video.deInterlace", - ]; - for id in ids { - let doc = specs.iter().find(|spec| spec.id == id).unwrap().params; - for &(key, allowed) in choices(id).unwrap() { - // The table repeats the registry's params doc, so the two cannot drift apart. - assert!(doc.contains(&format!("\"{key}\":\"{allowed}\"")), "{id}.{key}"); - for value in [json!("zzbogus"), json!(false), json!(1), Value::Null] { - rejected(&mut s, id, key, value); - } - for value in allowed.split('|') { - validate_params(id, &json!({key:value})).unwrap(); - } - } - } - // Keys `prepare` injects, and undocumented ones, stay accepted as before. - s.execute("filter.stylize.tiles", json!({"count":4,"foreground":[1,0,0,1]})).unwrap(); - s.execute("filter.stylize.wind", json!({"direction":"fromLeft"})).unwrap(); - } - - const STRICT_EXTENDED: [&str; 3] = ["filter.blur.smartBlur", "filter.blur.shapeBlur", "filter.noise.reduceNoise"]; - - #[test] - fn strict_extended_filters_reject_bad_fields_without_editing() { - let numbers = [ - ("filter.blur.smartBlur", "radius", 0.1, 100.0), - ("filter.blur.smartBlur", "threshold", 0.1, 100.0), - ("filter.blur.shapeBlur", "radius", 5.0, 1000.0), - ("filter.noise.reduceNoise", "strength", 0.0, 10.0), - ("filter.noise.reduceNoise", "preserveDetails", 0.0, 100.0), - ("filter.noise.reduceNoise", "reduceColorNoise", 0.0, 100.0), - ("filter.noise.reduceNoise", "sharpenDetails", 0.0, 100.0), - ]; - let specs = crate::filters_ext::specs(); - for depth in [8, 16, 32] { - let mut s = session(depth); - for (id, key, min, max) in numbers { - let doc = specs.iter().find(|spec| spec.id == id).unwrap().params; - assert!(doc.contains(&format!("\"{key}\":{min}..{max}=")), "{id}.{key}"); - for value in [json!("3"), json!(true), Value::Null, json!([]), json!({}), json!(min - 0.01), json!(max + 0.01), json!(1e300)] { - rejected(&mut s, id, key, value); - } - // Validate large endpoints without allocating large blur kernels. - for value in [min, max] { - validate_params(id, &json!({key:value})).unwrap(); - } - } - for id in STRICT_EXTENDED { - for (key, value) in [("radus", json!(3)), ("layer", json!("2")), ("target", json!("typo")), ("coalesce", json!(false))] { - rejected(&mut s, id, key, value); - } - for value in [json!([]), json!(false), json!(3), json!("params")] { - assert!(matches!(validate_params(id, &value), Err(EngineError::BadParams { .. }))); - } - } - for value in [json!("true"), json!(1), Value::Null, json!([]), json!({})] { - rejected(&mut s, "filter.noise.reduceNoise", "removeJpegArtifact", value); - } - } - for value in [false, true] { - validate_params("filter.noise.reduceNoise", &json!({"removeJpegArtifact":value})).unwrap(); - } - for (id, key, allowed) in [ - ("filter.blur.smartBlur", "quality", "high|medium|low"), - ("filter.blur.smartBlur", "mode", "normal|edgeOnly|overlayEdge"), - ("filter.blur.shapeBlur", "shape", "circle|ring|square|diamond|triangle|hexagon|star|heart|cross"), - ] { - let doc = specs.iter().find(|spec| spec.id == id).unwrap().params; - assert!(doc.contains(&format!("\"{key}\":\"{allowed}\"")), "{id}.{key}"); - let mut s = session(8); - for value in [json!("typo"), json!(false), json!(1), Value::Null] { - rejected(&mut s, id, key, value); - } - for value in allowed.split('|') { - validate_params(id, &json!({key:value})).unwrap(); - } - } - } - - #[test] - fn strict_extended_filters_validate_before_floating_selection_commit_and_jobs() { - let mut s = session(16); - s.execute("select.rect", json!({"x":0,"y":0,"width":4,"height":4})).unwrap(); - s.execute("select.float", json!({"dx":8})).unwrap(); - for id in STRICT_EXTENDED { - rejected(&mut s, id, "radus", json!(3)); - let doc = s.active().unwrap().doc.clone(); - let history = s.active().unwrap().history.entries(); - let journal = s.journal.clone(); - let params = json!({"radus":3}); - assert!(matches!(s.start(id, params.clone()), Err(EngineError::BadParams { .. }))); - let spec = crate::commands::find(id).unwrap(); - assert!(matches!((spec.run)(&mut s, ¶ms), Err(EngineError::BadParams { .. }))); - assert!(crate::float_cmds::floating(s.active().unwrap()).is_some()); - assert!(Arc::ptr_eq(&s.active().unwrap().doc, &doc)); - assert_eq!(s.active().unwrap().history.entries(), history); - assert_eq!(s.journal, journal); - assert!(s.jobs().is_empty()); - } - } - - #[test] - fn strict_extended_filters_keep_defaults_targets_history_and_last_filter() { - for depth in [8, 16, 32] { - for id in STRICT_EXTENDED { - let mut s = session(depth); - let layer = s.active().unwrap().active_layer.unwrap(); - for params in [Value::Null, json!({}), json!({"layer":layer.0,"target":"pixels","coalesce":"extended"})] { - let before = s.active().unwrap().doc.clone(); - let history = s.active().unwrap().history.past_len(); - s.execute(id, params).unwrap(); - assert_eq!(s.active().unwrap().history.past_len(), history + 1); - let after = s.active().unwrap().doc.clone(); - s.undo(); - assert_eq!(*s.active().unwrap().doc, *before); - s.redo(); - assert_eq!(*s.active().unwrap().doc, *after); - } - s.execute("filter.lastFilter", json!({})).unwrap(); - // The session injects this target when editing an alpha channel. - s.execute("channel.new", json!({"fill":"white"})).unwrap(); - s.execute(id, json!({})).unwrap(); - } - } - } - - #[test] - fn stored_extended_filter_records_still_decode_tolerantly() { - use photocraft_algo::{BlurQuality, BlurShape, FilterParams, SmartBlurMode}; - let smart = - crate::filters::params_for("filter.blur.smartBlur", &json!({"radius":-2,"threshold":900,"quality":"old","mode":false,"extra":true})).unwrap(); - assert!(matches!(smart, FilterParams::SmartBlur { radius: 0.1, threshold: 100.0, quality: BlurQuality::High, mode: SmartBlurMode::Normal })); - let shape = crate::filters::params_for("filter.blur.shapeBlur", &json!({"radius":2000,"shape":"old"})).unwrap(); - assert!(matches!(shape, FilterParams::ShapeBlur { radius: 1000.0, shape: BlurShape::Circle })); - let noise = crate::filters::params_for("filter.noise.reduceNoise", &json!({"strength":-1,"preserveDetails":101,"removeJpegArtifact":"yes"})).unwrap(); - assert!(matches!(noise, FilterParams::ReduceNoise { strength: 0.0, preserve_details: 100.0, remove_jpeg_artifact: false, .. })); - } - - #[test] - fn invalid_filters_leave_floating_selection_and_background_jobs_alone() { - let mut s = session(16); - s.execute("select.rect", json!({"x":0,"y":0,"width":4,"height":4})).unwrap(); - s.execute("select.float", json!({"dx":8})).unwrap(); - let doc = s.active().unwrap().doc.clone(); - let history = s.active().unwrap().history.entries(); - for params in [json!({"radius":"big"}), json!({"radus":3}), json!({"radius":5000}), json!({"radius":-4})] { - assert!(s.start("filter.blur.gaussianBlur", params.clone()).is_err()); - let spec = crate::commands::find("filter.blur.gaussianBlur").unwrap(); - assert!((spec.run)(&mut s, ¶ms).is_err()); - assert!(crate::float_cmds::floating(s.active().unwrap()).is_some()); - assert!(Arc::ptr_eq(&s.active().unwrap().doc, &doc)); - assert_eq!(s.active().unwrap().history.entries(), history); - assert!(s.jobs().is_empty()); - } - } - - #[test] - fn valid_filters_keep_defaults_explicit_targets_and_undo_redo() { - for depth in [8, 16, 32] { - let mut s = session(depth); - let layer = s.active().unwrap().active_layer.unwrap(); - let pixels = |s: &Session| s.active().unwrap().doc.layer(layer).unwrap().surface().unwrap().read_region(Rect::new(0, 0, 16, 12)); - let before = pixels(&s); - for params in [Value::Null, json!({})] { - let result = s.execute("filter.blur.gaussianBlur", params).unwrap(); - assert_eq!(result["filter"]["radius"], json!(1.0)); - assert_ne!(pixels(&s), before); - s.undo(); - assert_eq!(pixels(&s), before); - } - s.execute("layer.new.layer", json!({})).unwrap(); - let other = s.active().unwrap().active_layer.unwrap(); - let result = s.execute("filter.blur.gaussianBlur", json!({"radius":3,"layer":layer.0,"target":"pixels","coalesce":"blur"})).unwrap(); - assert_eq!(result["filter"]["radius"], json!(3.0)); - let after = pixels(&s); - assert_ne!(after, before); - assert_eq!(s.active().unwrap().doc.layer(other).unwrap().surface().unwrap().tile_count(), 0); - s.undo(); - assert_eq!(pixels(&s), before); - s.redo(); - assert_eq!(pixels(&s), after); - } - } - - #[test] - fn injected_channel_targets_and_extended_filter_colours_keep_working() { - let mut s = session(8); - s.execute("channel.new", json!({"fill":"white"})).unwrap(); - let pixels = s.active().unwrap().doc.layers.clone(); - s.execute("filter.noise.addNoise", json!({"amount":40,"seed":2})).unwrap(); - assert_eq!(s.active().unwrap().doc.layers, pixels); - assert!(s.active().unwrap().doc.channels[0].surface.read_region(Rect::new(0, 0, 16, 12)).iter().any(|&v| v < 0.99)); - s.execute("channel.target", json!({"channel":"composite"})).unwrap(); - s.tools.foreground = [0.0, 0.0, 1.0, 1.0]; - s.tools.background = [1.0, 0.0, 0.0, 1.0]; - let params = crate::filters_ext::prepare(&s, "filter.render.fibers", &json!({})); - assert_eq!(params["foreground"], json!(s.tools.foreground)); - assert_eq!(params["background"], json!(s.tools.background)); - s.execute("filter.render.fibers", params).unwrap(); - } -} +mod tests; diff --git a/crates/engine/src/filters/validation/tests.rs b/crates/engine/src/filters/validation/tests.rs new file mode 100644 index 0000000000..408a55b365 --- /dev/null +++ b/crates/engine/src/filters/validation/tests.rs @@ -0,0 +1,362 @@ +use std::sync::Arc; + +use photocraft_geom::Rect; +use serde_json::json; + +use super::*; +use crate::Session; + +fn session(depth: u32) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width":16,"height":12,"depth":depth})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.edit("pattern", |doc, active| { + let surface = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + surface.fill_rect(Rect::new(0, 0, 8, 12), &[0.2, 0.6, 0.8, 1.0]); + Ok(()) + }) + .unwrap(); + s +} + +fn rejected(s: &mut Session, id: &str, key: &str, value: Value) { + let doc = s.active().unwrap().doc.clone(); + let history = s.active().unwrap().history.entries(); + let journal = s.journal.clone(); + let active = s.active().unwrap().active_layer; + let error = s.execute(id, json!({key:value})).unwrap_err(); + assert!(matches!(error, EngineError::BadParams { .. }), "{id}: {error}"); + let error = error.to_string(); + assert!(error.contains(id) && error.contains(key), "{error}"); + assert!(Arc::ptr_eq(&s.active().unwrap().doc, &doc), "{id}: {key}"); + assert_eq!(s.active().unwrap().history.entries(), history); + assert_eq!(s.active().unwrap().active_layer, active); + assert_eq!(s.journal, journal); + assert!(s.jobs().is_empty()); +} + +#[test] +fn every_core_filter_rejects_unknown_keys_without_editing() { + for depth in [8, 16, 32] { + let mut s = session(depth); + for spec in crate::filters::specs().into_iter().filter(|s| s.id != "filter.lastFilter") { + rejected(&mut s, spec.id, "radus", json!(3)); + } + } +} + +#[test] +fn core_filter_numbers_reject_wrong_types_and_documented_range_violations() { + // Each numeric field in the core registry, independently of the validation table. + let cases = [ + ("blur.gaussianBlur", "radius", 0.1, 1000.0), + ("blur.boxBlur", "radius", 1.0, 2000.0), + ("blur.motionBlur", "angle", -360.0, 360.0), + ("blur.motionBlur", "distance", 1.0, 2000.0), + ("blur.radialBlur", "amount", 1.0, 100.0), + ("blur.radialBlur", "centerX", 0.0, 1.0), + ("blur.radialBlur", "centerY", 0.0, 1.0), + ("blur.surfaceBlur", "radius", 1.0, 100.0), + ("blur.surfaceBlur", "threshold", 2.0, 255.0), + ("sharpen.unsharpMask", "amount", 1.0, 500.0), + ("sharpen.unsharpMask", "radius", 0.1, 1000.0), + ("sharpen.unsharpMask", "threshold", 0.0, 255.0), + ("sharpen.smartSharpen", "amount", 1.0, 500.0), + ("sharpen.smartSharpen", "radius", 0.1, 64.0), + ("sharpen.smartSharpen", "reduceNoise", 0.0, 100.0), + ("noise.addNoise", "amount", 0.1, 400.0), + ("noise.median", "radius", 1.0, 500.0), + ("noise.dustAndScratches", "radius", 1.0, 500.0), + ("noise.dustAndScratches", "threshold", 0.0, 255.0), + ("pixelate.mosaic", "cellSize", 2.0, 200.0), + ("stylize.emboss", "angle", -180.0, 180.0), + ("stylize.emboss", "height", 1.0, 100.0), + ("stylize.emboss", "amount", 1.0, 500.0), + ("distort.twirl", "angle", -999.0, 999.0), + ("distort.pinch", "amount", -100.0, 100.0), + ("distort.spherize", "amount", -100.0, 100.0), + ("distort.wave", "generators", 1.0, 999.0), + ("distort.wave", "wavelengthMin", 1.0, 998.0), + ("distort.wave", "wavelengthMax", 2.0, 999.0), + ("distort.wave", "amplitudeMin", 1.0, 998.0), + ("distort.wave", "amplitudeMax", 1.0, 999.0), + ("distort.ripple", "amount", -999.0, 999.0), + ("other.highPass", "radius", 0.1, 1000.0), + ("other.minimum", "radius", 0.2, 500.0), + ("other.maximum", "radius", 0.2, 500.0), + ]; + for depth in [8, 16, 32] { + let mut s = session(depth); + for (suffix, key, min, max) in cases { + let id = format!("filter.{suffix}"); + for value in [json!("big"), json!(true), Value::Null, json!([]), json!({}), json!(min - 0.01), json!(max + 0.01)] { + rejected(&mut s, &id, key, value); + } + // Large limits are validated without allocating a large blur kernel. + for value in [min, max] { + validate_params(&id, &json!({key:value})).unwrap(); + } + } + for key in ["horizontal", "vertical"] { + rejected(&mut s, "filter.other.offset", key, json!("4")); + } + } +} + +#[test] +fn core_filter_choices_booleans_seeds_and_shared_fields_are_validated() { + let mut s = session(8); + for (suffix, key, choices) in [ + ("blur.radialBlur", "method", "spin|zoom"), + ("blur.radialBlur", "quality", "draft|good|best"), + ("noise.addNoise", "distribution", "uniform|gaussian"), + ("distort.spherize", "mode", "normal|horizontalOnly|verticalOnly"), + ("distort.wave", "type", "sine|triangle|square"), + ("distort.wave", "undefinedAreas", "wrap|repeat"), + ("distort.ripple", "size", "small|medium|large"), + ("distort.polarCoordinates", "mode", "rectangularToPolar|polarToRectangular"), + ("other.minimum", "preserve", "squareness|roundness"), + ("other.maximum", "preserve", "squareness|roundness"), + ("other.offset", "undefinedAreas", "wrap|repeat|transparent"), + ] { + let id = format!("filter.{suffix}"); + for value in [json!("typo"), json!(false), json!(1), Value::Null] { + rejected(&mut s, &id, key, value); + } + for value in choices.split('|') { + validate_params(&id, &json!({key:value})).unwrap(); + } + } + for value in [json!("true"), json!(0), Value::Null] { + rejected(&mut s, "filter.noise.addNoise", "monochromatic", value); + } + for id in ["filter.noise.addNoise", "filter.distort.wave"] { + for value in [json!(-1), json!(4_294_967_296_u64), json!(0.5), json!("12")] { + rejected(&mut s, id, "seed", value); + } + // A valid u32 seed must not be saturated through an i32 helper. + let result = s.execute(id, json!({"seed":u32::MAX})).unwrap(); + assert_eq!(result["filter"]["seed"], json!(u32::MAX)); + } + for (key, value) in [("layer", json!("2")), ("target", json!("typo")), ("target", json!({"channel":-1})), ("coalesce", json!(false))] { + rejected(&mut s, "filter.blur.gaussianBlur", key, value); + } +} + +#[test] +fn extended_filter_choices_match_their_specs_and_reject_unlisted_values() { + let mut s = session(8); + let specs = crate::filters_ext::specs(); + let ids = [ + "filter.pixelate.mezzotint", + "filter.stylize.diffuse", + "filter.stylize.extrude", + "filter.stylize.tiles", + "filter.stylize.traceContour", + "filter.stylize.wind", + "filter.distort.displace", + "filter.distort.shear", + "filter.distort.zigZag", + "filter.render.lensFlare", + "filter.render.lightingEffects", + "filter.blur.lensBlur", + "filter.other.hsbHsl", + "filter.video.deInterlace", + ]; + for id in ids { + let doc = specs.iter().find(|spec| spec.id == id).unwrap().params; + for &(key, allowed) in choices(id).unwrap() { + // The table repeats the registry's params doc, so the two cannot drift apart. + assert!(doc.contains(&format!("\"{key}\":\"{allowed}\"")), "{id}.{key}"); + for value in [json!("zzbogus"), json!(false), json!(1), Value::Null] { + rejected(&mut s, id, key, value); + } + for value in allowed.split('|') { + validate_params(id, &json!({key:value})).unwrap(); + } + } + } + // Keys `prepare` injects, and undocumented ones, stay accepted as before. + s.execute("filter.stylize.tiles", json!({"count":4,"foreground":[1,0,0,1]})).unwrap(); + s.execute("filter.stylize.wind", json!({"direction":"fromLeft"})).unwrap(); +} + +const STRICT_EXTENDED: [&str; 3] = ["filter.blur.smartBlur", "filter.blur.shapeBlur", "filter.noise.reduceNoise"]; + +#[test] +fn strict_extended_filters_reject_bad_fields_without_editing() { + let numbers = [ + ("filter.blur.smartBlur", "radius", 0.1, 100.0), + ("filter.blur.smartBlur", "threshold", 0.1, 100.0), + ("filter.blur.shapeBlur", "radius", 5.0, 1000.0), + ("filter.noise.reduceNoise", "strength", 0.0, 10.0), + ("filter.noise.reduceNoise", "preserveDetails", 0.0, 100.0), + ("filter.noise.reduceNoise", "reduceColorNoise", 0.0, 100.0), + ("filter.noise.reduceNoise", "sharpenDetails", 0.0, 100.0), + ]; + let specs = crate::filters_ext::specs(); + for depth in [8, 16, 32] { + let mut s = session(depth); + for (id, key, min, max) in numbers { + let doc = specs.iter().find(|spec| spec.id == id).unwrap().params; + assert!(doc.contains(&format!("\"{key}\":{min}..{max}=")), "{id}.{key}"); + for value in [json!("3"), json!(true), Value::Null, json!([]), json!({}), json!(min - 0.01), json!(max + 0.01), json!(1e300)] { + rejected(&mut s, id, key, value); + } + // Validate large endpoints without allocating large blur kernels. + for value in [min, max] { + validate_params(id, &json!({key:value})).unwrap(); + } + } + for id in STRICT_EXTENDED { + for (key, value) in [("radus", json!(3)), ("layer", json!("2")), ("target", json!("typo")), ("coalesce", json!(false))] { + rejected(&mut s, id, key, value); + } + for value in [json!([]), json!(false), json!(3), json!("params")] { + assert!(matches!(validate_params(id, &value), Err(EngineError::BadParams { .. }))); + } + } + for value in [json!("true"), json!(1), Value::Null, json!([]), json!({})] { + rejected(&mut s, "filter.noise.reduceNoise", "removeJpegArtifact", value); + } + } + for value in [false, true] { + validate_params("filter.noise.reduceNoise", &json!({"removeJpegArtifact":value})).unwrap(); + } + for (id, key, allowed) in [ + ("filter.blur.smartBlur", "quality", "high|medium|low"), + ("filter.blur.smartBlur", "mode", "normal|edgeOnly|overlayEdge"), + ("filter.blur.shapeBlur", "shape", "circle|ring|square|diamond|triangle|hexagon|star|heart|cross"), + ] { + let doc = specs.iter().find(|spec| spec.id == id).unwrap().params; + assert!(doc.contains(&format!("\"{key}\":\"{allowed}\"")), "{id}.{key}"); + let mut s = session(8); + for value in [json!("typo"), json!(false), json!(1), Value::Null] { + rejected(&mut s, id, key, value); + } + for value in allowed.split('|') { + validate_params(id, &json!({key:value})).unwrap(); + } + } +} + +#[test] +fn strict_extended_filters_validate_before_floating_selection_commit_and_jobs() { + let mut s = session(16); + s.execute("select.rect", json!({"x":0,"y":0,"width":4,"height":4})).unwrap(); + s.execute("select.float", json!({"dx":8})).unwrap(); + for id in STRICT_EXTENDED { + rejected(&mut s, id, "radus", json!(3)); + let doc = s.active().unwrap().doc.clone(); + let history = s.active().unwrap().history.entries(); + let journal = s.journal.clone(); + let params = json!({"radus":3}); + assert!(matches!(s.start(id, params.clone()), Err(EngineError::BadParams { .. }))); + let spec = crate::commands::find(id).unwrap(); + assert!(matches!((spec.run)(&mut s, ¶ms), Err(EngineError::BadParams { .. }))); + assert!(crate::float_cmds::floating(s.active().unwrap()).is_some()); + assert!(Arc::ptr_eq(&s.active().unwrap().doc, &doc)); + assert_eq!(s.active().unwrap().history.entries(), history); + assert_eq!(s.journal, journal); + assert!(s.jobs().is_empty()); + } +} + +#[test] +fn strict_extended_filters_keep_defaults_targets_history_and_last_filter() { + for depth in [8, 16, 32] { + for id in STRICT_EXTENDED { + let mut s = session(depth); + let layer = s.active().unwrap().active_layer.unwrap(); + for params in [Value::Null, json!({}), json!({"layer":layer.0,"target":"pixels","coalesce":"extended"})] { + let before = s.active().unwrap().doc.clone(); + let history = s.active().unwrap().history.past_len(); + s.execute(id, params).unwrap(); + assert_eq!(s.active().unwrap().history.past_len(), history + 1); + let after = s.active().unwrap().doc.clone(); + s.undo(); + assert_eq!(*s.active().unwrap().doc, *before); + s.redo(); + assert_eq!(*s.active().unwrap().doc, *after); + } + s.execute("filter.lastFilter", json!({})).unwrap(); + // The session injects this target when editing an alpha channel. + s.execute("channel.new", json!({"fill":"white"})).unwrap(); + s.execute(id, json!({})).unwrap(); + } + } +} + +#[test] +fn stored_extended_filter_records_still_decode_tolerantly() { + use photocraft_algo::{BlurQuality, BlurShape, FilterParams, SmartBlurMode}; + let smart = crate::filters::params_for("filter.blur.smartBlur", &json!({"radius":-2,"threshold":900,"quality":"old","mode":false,"extra":true})).unwrap(); + assert!(matches!(smart, FilterParams::SmartBlur { radius: 0.1, threshold: 100.0, quality: BlurQuality::High, mode: SmartBlurMode::Normal })); + let shape = crate::filters::params_for("filter.blur.shapeBlur", &json!({"radius":2000,"shape":"old"})).unwrap(); + assert!(matches!(shape, FilterParams::ShapeBlur { radius: 1000.0, shape: BlurShape::Circle })); + let noise = crate::filters::params_for("filter.noise.reduceNoise", &json!({"strength":-1,"preserveDetails":101,"removeJpegArtifact":"yes"})).unwrap(); + assert!(matches!(noise, FilterParams::ReduceNoise { strength: 0.0, preserve_details: 100.0, remove_jpeg_artifact: false, .. })); +} + +#[test] +fn invalid_filters_leave_floating_selection_and_background_jobs_alone() { + let mut s = session(16); + s.execute("select.rect", json!({"x":0,"y":0,"width":4,"height":4})).unwrap(); + s.execute("select.float", json!({"dx":8})).unwrap(); + let doc = s.active().unwrap().doc.clone(); + let history = s.active().unwrap().history.entries(); + for params in [json!({"radius":"big"}), json!({"radus":3}), json!({"radius":5000}), json!({"radius":-4})] { + assert!(s.start("filter.blur.gaussianBlur", params.clone()).is_err()); + let spec = crate::commands::find("filter.blur.gaussianBlur").unwrap(); + assert!((spec.run)(&mut s, ¶ms).is_err()); + assert!(crate::float_cmds::floating(s.active().unwrap()).is_some()); + assert!(Arc::ptr_eq(&s.active().unwrap().doc, &doc)); + assert_eq!(s.active().unwrap().history.entries(), history); + assert!(s.jobs().is_empty()); + } +} + +#[test] +fn valid_filters_keep_defaults_explicit_targets_and_undo_redo() { + for depth in [8, 16, 32] { + let mut s = session(depth); + let layer = s.active().unwrap().active_layer.unwrap(); + let pixels = |s: &Session| s.active().unwrap().doc.layer(layer).unwrap().surface().unwrap().read_region(Rect::new(0, 0, 16, 12)); + let before = pixels(&s); + for params in [Value::Null, json!({})] { + let result = s.execute("filter.blur.gaussianBlur", params).unwrap(); + assert_eq!(result["filter"]["radius"], json!(1.0)); + assert_ne!(pixels(&s), before); + s.undo(); + assert_eq!(pixels(&s), before); + } + s.execute("layer.new.layer", json!({})).unwrap(); + let other = s.active().unwrap().active_layer.unwrap(); + let result = s.execute("filter.blur.gaussianBlur", json!({"radius":3,"layer":layer.0,"target":"pixels","coalesce":"blur"})).unwrap(); + assert_eq!(result["filter"]["radius"], json!(3.0)); + let after = pixels(&s); + assert_ne!(after, before); + assert_eq!(s.active().unwrap().doc.layer(other).unwrap().surface().unwrap().tile_count(), 0); + s.undo(); + assert_eq!(pixels(&s), before); + s.redo(); + assert_eq!(pixels(&s), after); + } +} + +#[test] +fn injected_channel_targets_and_extended_filter_colours_keep_working() { + let mut s = session(8); + s.execute("channel.new", json!({"fill":"white"})).unwrap(); + let pixels = s.active().unwrap().doc.layers.clone(); + s.execute("filter.noise.addNoise", json!({"amount":40,"seed":2})).unwrap(); + assert_eq!(s.active().unwrap().doc.layers, pixels); + assert!(s.active().unwrap().doc.channels[0].surface.read_region(Rect::new(0, 0, 16, 12)).iter().any(|&v| v < 0.99)); + s.execute("channel.target", json!({"channel":"composite"})).unwrap(); + s.tools.foreground = [0.0, 0.0, 1.0, 1.0]; + s.tools.background = [1.0, 0.0, 0.0, 1.0]; + let params = crate::filters_ext::prepare(&s, "filter.render.fibers", &json!({})); + assert_eq!(params["foreground"], json!(s.tools.foreground)); + assert_eq!(params["background"], json!(s.tools.background)); + s.execute("filter.render.fibers", params).unwrap(); +} diff --git a/crates/engine/src/image_cmds.rs b/crates/engine/src/image_cmds.rs deleted file mode 100644 index 1efc9c0a0e..0000000000 --- a/crates/engine/src/image_cmds.rs +++ /dev/null @@ -1,2011 +0,0 @@ -//! Image menu: Image Size, Canvas Size, Crop, Trim, Mode (colour model and -//! bit depth) conversions, Duplicate. - -use std::convert::Infallible; - -use photocraft_algo::resample::{Resample, crop_surface, resize_surface_in_canvas, translate_surface}; -use photocraft_color::{ColorMode, SampleType}; -use photocraft_doc::{Document, Effect, Effects, FxPaint, Layer, LayerContent, LayerId, Size}; -use photocraft_geom::Rect; -use photocraft_raster::Surface; -use serde_json::{Value, json}; - -use crate::commands::CommandSpec; -use crate::{EngineError, Result, Session}; - -fn has_doc(s: &Session) -> std::result::Result<(), String> { - s.active().map(|_| ()).ok_or_else(|| "no document open".into()) -} - -/// Applies `f` to every pixel surface of a layer tree: content (raster or -/// cached text/shape/smart pixels), fill caches, stored video frames (current and original), -/// and (if `masks`) masks. -pub(crate) fn for_each_surface(layers: &mut [Layer], masks: bool, f: &mut dyn FnMut(&mut Surface, bool)) { - for l in layers { - if masks && let Some(m) = &mut l.mask { - f(&mut m.surface, true); - } - if let Some(fc) = &mut l.fill_cache { - f(&mut fc.surface, false); - } - // The displayed content is only a copy of the frame at the playhead; the other frames - // would keep the old geometry and depth and come back stale when scrubbing (#4956). - if let Some(v) = &mut l.video { - for frame in v.frames.iter_mut().chain(v.original_frames.iter_mut().flatten()) { - f(frame, false); - } - } - match &mut l.content { - LayerContent::Raster(s) => f(s, false), - LayerContent::Text(t) => { - if let Some(c) = &mut t.cache { - f(c, false) - } - } - LayerContent::Shape(sh) => { - if let Some(c) = &mut sh.cache { - f(c, false) - } - } - LayerContent::Smart(sm) => { - if let Some(c) = &mut sm.cache { - f(c, false) - } - // Selection-derived smart-filter masks live in document coordinates. Every - // canvas resize/translation must carry them with the smart object's cache; - // otherwise toggling a filter recomputes its coverage at stale positions (#3077). - if masks && let Some(mask) = &mut sm.filter_mask { - f(&mut mask.surface, true); - } - } - LayerContent::Group(g) => for_each_surface(&mut g.children, masks, f), - _ => {} - } - } -} - -/// Drops every fill cache of a layer tree. A fill layer covers the whole canvas, but its cache -/// (the pixels a PSD stored) only the old one: after the canvas grows the fill must re-render -/// from its model, or the added area stays transparent (#7362). -fn drop_fill_caches(layers: &mut [Layer]) { - for l in layers { - l.fill_cache = None; - if let LayerContent::Group(g) = &mut l.content { - drop_fill_caches(&mut g.children); - } - } -} - -/// Converts every pixel surface of a layer tree (masks included) to `depth`. -pub(crate) fn convert_layers_depth(layers: &mut [Layer], depth: SampleType) { - for_each_surface(layers, true, &mut |surf, _| { - let f = surf.format().with_sample(depth); - *surf = surf.convert(f); - }); -} - -pub(crate) fn for_each_layer(layers: &mut [Layer], f: &mut dyn FnMut(&mut Layer)) { - for l in layers { - f(l); - if let Some(ch) = l.children_mut() { - for_each_layer(ch, f); - } - } -} - -/// Assign new layer ids to a copied document and update every saved layer reference. -/// -/// A document copy needs fresh identities, but its comps and variable definitions must -/// still target the copied layers. Deliberately leave references to already-deleted -/// layers untouched so their missing-layer warnings remain meaningful. The same applies -/// to Last Document State. -pub(crate) fn reidentify_copied_layers(doc: &mut Document) { - let mut ids = std::collections::HashMap::new(); - for_each_layer(&mut doc.layers, &mut |layer| { - let previous = layer.id; - layer.id = LayerId::fresh(); - ids.insert(previous, layer.id); - }); - - let remap = |comp: &mut photocraft_doc::LayerComp| { - for state in &mut comp.states { - if let Some(&new_id) = ids.get(&state.layer) { - state.layer = new_id; - } - } - }; - for comp in &mut doc.layer_comps { - remap(comp); - } - if let Some(last) = &mut doc.last_document_state { - remap(last); - } - for def in &mut doc.variables.defs { - if let Some(&new_id) = ids.get(&def.layer) { - def.layer = new_id; - } - } - for slice in &mut doc.slices.list { - if let Some(&new_id) = slice.layer.and_then(|layer| ids.get(&layer)) { - slice.layer = Some(new_id); - } - } -} - -/// Scale every size and distance of a style by `k` (Image Size's Scale Styles, Layer Style › -/// Scale Effects, and previews that draw a style at a reduced resolution). -pub fn scale_effects(fx: &mut Effects, k: f32) { - for e in &mut fx.items { - match e { - Effect::DropShadow(s) | Effect::InnerShadow(s) => { - s.distance *= k; - s.size *= k; - } - Effect::OuterGlow(g) | Effect::InnerGlow(g) => g.size *= k, - Effect::Stroke(s) => s.size *= k, - Effect::Satin(s) => { - s.distance *= k; - s.size *= k; - } - Effect::BevelEmboss(b) => { - b.size *= k; - b.soften *= k; - } - Effect::PatternOverlay { scale, .. } => *scale *= k, - Effect::GradientOverlay { .. } | Effect::ColorOverlay { .. } => {} - } - if let Effect::Stroke(s) = e - && let FxPaint::Pattern { scale, .. } = &mut s.paint - { - *scale *= k; - } - } - // Effects changed: the preserved PSD block no longer applies. - if k != 1.0 { - fx.psd_raw = None; - } -} - -/// Image Size's resampling methods; `None` changes the resolution only. -#[derive(Clone, Copy)] -enum Method { - None, - Filter(Resample), - /// Photoshop's Automatic: Preserve Details where the image grows, Bicubic Sharper otherwise. - Automatic, -} - -fn parse_resample(s: &str) -> Method { - Method::Filter(match s { - "none" => return Method::None, - "automatic" => return Method::Automatic, - "nearest" | "nearestNeighbor" => Resample::Nearest, - "bilinear" => Resample::Bilinear, - "bicubicSmoother" => Resample::BicubicSmoother, - "bicubicSharper" => Resample::BicubicSharper, - "bicubicAutomatic" => Resample::BicubicAutomatic, - "lanczos" => Resample::Lanczos, - "preserveDetails" => Resample::PreserveDetails, - _ => Resample::Bicubic, - }) -} - -/// The largest raster Image Size resamples to: the decoders' default allocation budget. -const MAX_RESAMPLE_BYTES: u64 = if cfg!(target_pointer_width = "64") { 8 << 30 } else { 2 << 30 }; - -/// Image → Image Size. -fn image_size(s: &mut Session, p: &Value) -> Result { - let d = s.active().ok_or(EngineError::NoDocument)?; - let (ow, oh) = (d.doc.size.width, d.doc.size.height); - let resample = parse_resample(p.get("resample").and_then(Value::as_str).unwrap_or("bicubic")); - // An Indexed Color document holds only its colour table's colours, and a save quantises to - // them: interpolation showed blends that the saved file didn't have (#6019). - let resample = match resample { - Method::Filter(_) | Method::Automatic if d.doc.mode == ColorMode::Indexed => Method::Filter(Resample::Nearest), - m => m, - }; - let mut pw = p.get("width").and_then(Value::as_f64); - let mut ph = p.get("height").and_then(Value::as_f64); - // `percent` scales both sides (what a Photoshop action records as "200%"); an explicit side wins. - if let Some(pc) = p.get("percent") { - let pc = pc.as_f64().filter(|v| v.is_finite() && *v > 0.0).ok_or_else(|| bad("image.imageSize", "`percent` must be a positive number"))?; - pw = pw.or(Some(ow as f64 * pc / 100.0)); - ph = ph.or(Some(oh as f64 * pc / 100.0)); - } - // `keepPrintSize`: only the resolution given, the pixels follow it (Photoshop's Image Size - // with Resample on, as an action records it). - if p.get("keepPrintSize").and_then(Value::as_bool) == Some(true) - && pw.is_none() - && ph.is_none() - && let Some(r) = p.get("resolution").and_then(Value::as_f64) - { - let r = r.clamp(1.0, 10_000.0); - let old = f64::from(d.doc.resolution_dpi).max(1.0); - pw = Some(ow as f64 * r / old); - ph = Some(oh as f64 * r / old); - } - // Missing dimension keeps the aspect ratio. - let (nw, nh) = match (pw, ph) { - (Some(w), Some(h)) => (w, h), - (Some(w), None) => (w, w * oh as f64 / ow.max(1) as f64), - (None, Some(h)) => (h * ow as f64 / oh.max(1) as f64, h), - (None, None) => (ow as f64, oh as f64), - }; - let (nw, nh) = (nw.round().clamp(1.0, 300_000.0) as u32, nh.round().clamp(1.0, 300_000.0) as u32); - // Each side may reach 300000 px, but resampling writes real pixels: refuse a canvas whose - // raster alone would pass the budget, before allocating any of it (#1544). - if !matches!(resample, Method::None) && (nw, nh) != (ow, oh) { - check_resample_budget("image.imageSize", &d.doc, nw, nh, ", or turn Resample off to change only the resolution")?; - } - let dpi = p.get("resolution").and_then(Value::as_f64).map(|v| v as f32); - if !matches!(resample, Method::None) && (nw, nh) != (ow, oh) { - // Color Sampler points scale with the pixels (same map `transform_geometry` applies). - let (sx, sy) = (f64::from(nw) / f64::from(ow.max(1)), f64::from(nh) / f64::from(oh.max(1))); - s.set_sampler_map(photocraft_geom::Affine { m: [sx, 0.0, 0.0, sy, 0.0, 0.0] }); - } - s.edit("Image Size", |doc, _| { - if let Some(r) = dpi { - // Type keeps its pixel size; resampling below then scales it with the pixels. - crate::canvas_geom::set_resolution(doc, r.clamp(1.0, 10_000.0)); - } - let filter = match resample { - Method::None => return Ok(()), - Method::Filter(f) => f, - Method::Automatic if nw > ow || nh > oh => Resample::PreserveDetails, - Method::Automatic => Resample::BicubicSharper, - }; - resample_doc(doc, nw, nh, filter); - Ok(()) - })?; - // The size the document has now: without resampling `width`/`height` are ignored (#1815). - let size = s.active().ok_or(EngineError::NoDocument)?.doc.size; - Ok(json!({ "width": size.width, "height": size.height })) -} - -/// Refuses to resample `doc` to `nw` x `nh` px when the raster alone would pass the budget, before -/// allocating any of it (#1544). `hint` ends the message with what the caller can do instead. -pub(crate) fn check_resample_budget(cmd: &str, doc: &Document, nw: u32, nh: u32, hint: &str) -> Result<()> { - let bpp = doc.pixel_format().bytes_per_pixel().max(1) as u64; - let bytes = u64::from(nw).saturating_mul(u64::from(nh)).saturating_mul(bpp); - if bytes <= MAX_RESAMPLE_BYTES { - return Ok(()); - } - let mp = u64::from(nw).saturating_mul(u64::from(nh)) / 1_000_000; - let max_mp = MAX_RESAMPLE_BYTES / bpp / 1_000_000; - Err(bad(cmd, format!("{nw} x {nh} px is {mp} megapixels; resampling at this bit depth is limited to {max_mp} megapixels. Choose a smaller size{hint}"))) -} - -/// Like [`check_resample_budget`] for a command that, besides resampling the document to -/// `nw` x `nh` px, holds `work_bytes_per_px` more bytes per pixel of full-canvas working buffers -/// (a composite, a mask, an output layer) at once. -pub(crate) fn check_working_budget(cmd: &str, doc: &Document, nw: u32, nh: u32, work_bytes_per_px: u64, hint: &str) -> Result<()> { - let bpp = (doc.pixel_format().bytes_per_pixel().max(1) as u64).saturating_add(work_bytes_per_px); - let px = u64::from(nw).saturating_mul(u64::from(nh)); - if px.saturating_mul(bpp) <= MAX_RESAMPLE_BYTES { - return Ok(()); - } - let max_mp = MAX_RESAMPLE_BYTES / bpp / 1_000_000; - Err(bad(cmd, format!("{nw} x {nh} px is {} megapixels; this conversion is limited to {max_mp} megapixels. Choose a smaller size{hint}", px / 1_000_000))) -} - -/// Resamples the whole document (pixels, masks, channels, selection, effects, vectors, guides) to -/// `nw` x `nh` px with `filter`: the body of Image Size, shared by the Crop tool's W x H x Resolution -/// mode. Callers check [`check_resample_budget`] first. -pub(crate) fn resample_doc(doc: &mut Document, nw: u32, nh: u32, filter: Resample) { - let (ow, oh) = (doc.size.width, doc.size.height); - let (sx, sy) = (nw as f64 / ow.max(1) as f64, nh as f64 / oh.max(1) as f64); - if (sx - 1.0).abs() < 1e-12 && (sy - 1.0).abs() < 1e-12 { - return; - } - // Content that reaches the canvas edge keeps it: a Background stays opaque to the border. - let canvas = Rect::from_xywh(0, 0, ow, oh); - let taken = crate::smart_cmds::take_caches(&mut doc.layers); - for_each_surface(&mut doc.layers, true, &mut |surf, is_mask| { - *surf = resize_surface_in_canvas(surf, sx, sy, if is_mask { Resample::Bilinear } else { filter }, canvas); - }); - let k = ((sx + sy) / 2.0) as f32; - for_each_layer(&mut doc.layers, &mut |l| { - scale_effects(&mut l.effects, k); - // Canvas resampling scales the whole appearance, including shape strokes (#8341). - // Dash lengths and offsets are already expressed in multiples of this width. - if let LayerContent::Shape(sh) = &mut l.content - && let Some(stroke) = &mut sh.stroke - { - stroke.width *= k; - } - }); - for ch in doc.channels.iter_mut().chain(doc.quick_mask.as_mut()) { - ch.surface = resize_surface_in_canvas(&ch.surface, sx, sy, Resample::Bilinear, canvas); - } - if let Some(sel) = &doc.selection { - doc.selection = Some(resize_surface_in_canvas(sel, sx, sy, Resample::Bilinear, canvas)); - } - // Vector geometry, guides and marks scale with the pixels; vectors re-render sharp. - crate::canvas_geom::transform_geometry(doc, &photocraft_geom::Affine { m: [sx, 0.0, 0.0, sy, 0.0, 0.0] }); - doc.size = Size::new(nw, nh); - crate::canvas_geom::refresh(doc, crate::canvas_geom::Refresh::All); - let Ok(()) = crate::smart_cmds::restore_unrendered(doc, taken, |c| Ok::<_, Infallible>(resize_surface_in_canvas(c, sx, sy, filter, canvas))); -} - -fn bad(cmd: &str, msg: impl Into) -> EngineError { - EngineError::BadParams { cmd: cmd.into(), msg: msg.into() } -} - -/// The flattened document, or an error when the canvas is over the compositor's render cap -/// ([`photocraft_compose::MAX_RENDER_PIXELS`]; `flatten` returns an empty buffer then). -fn flatten_whole(doc: &Document, cmd: &str) -> Result { - let buf = photocraft_compose::flatten(doc); - let (w, h) = (doc.size.width, doc.size.height); - if buf.px.len() as u64 != u64::from(w) * u64::from(h) { - return Err(bad(cmd, format!("the document ({w} x {h} px) is too large to flatten (limit {} pixels)", photocraft_compose::MAX_RENDER_PIXELS))); - } - Ok(buf) -} - -/// Moves every surface, channel, selection and guide by `(dx, dy)`. -/// -/// Fails, before moving anything, when some pixels would land outside the i32 coordinate -/// range: the surface copy saturates its target rectangle there, which no longer matches -/// the pixel data and panics (#959). -pub(crate) fn translate_doc(doc: &mut Document, cmd: &str, dx: i32, dy: i32) -> Result<()> { - if dx == 0 && dy == 0 { - return Ok(()); - } - let fits = |r: Rect| { - r.is_empty() || (r.x0.checked_add(dx).is_some() && r.x1.checked_add(dx).is_some() && r.y0.checked_add(dy).is_some() && r.y1.checked_add(dy).is_some()) - }; - let mut ok = true; - for_each_surface(&mut doc.layers, true, &mut |surf, _| ok = ok && fits(surf.content_bounds())); - ok = ok - && doc.channels.iter().chain(doc.quick_mask.as_ref()).all(|ch| fits(ch.surface.content_bounds())) - && doc.selection.as_ref().is_none_or(|sel| fits(sel.content_bounds())); - if !ok { - return Err(bad(cmd, format!("moving the document by ({dx}, {dy}) would push its pixels outside the 32-bit coordinate range"))); - } - for_each_surface(&mut doc.layers, true, &mut |surf, _| *surf = translate_surface(surf, dx, dy)); - for ch in doc.channels.iter_mut().chain(doc.quick_mask.as_mut()) { - ch.surface = translate_surface(&ch.surface, dx, dy); - } - if let Some(sel) = &doc.selection { - doc.selection = Some(translate_surface(sel, dx, dy)); - } - // Type, shapes, smart objects, vector masks, paths, guides, slices, notes… (caches above - // are already translated exactly, so nothing needs re-rendering for the move itself). - crate::canvas_geom::transform_geometry(doc, &photocraft_geom::Affine::translate(f64::from(dx), f64::from(dy))); - Ok(()) -} - -/// Delete Cropped Pixels on a layer tree: crops pixel-layer data only to `r`. Type and smart -/// objects move by shifting their rendered pixels, so cutting those would clip them at the old -/// edge. A video layer's stored frames are its pixels too: the displayed content is only the frame -/// at the playhead, so the others would bring the cropped pixels back when scrubbing (#4956). -fn delete_cropped_pixels(layers: &mut [Layer], r: Rect) { - for_each_layer(layers, &mut |l| { - if let Some(fc) = &mut l.fill_cache { - fc.surface = crop_surface(&fc.surface, r); - } - if let Some(v) = &mut l.video { - for frame in v.frames.iter_mut().chain(v.original_frames.iter_mut().flatten()) { - *frame = crop_surface(frame, r); - } - } - if let LayerContent::Raster(s) = &mut l.content { - *s = crop_surface(s, r); - } - }); -} - -/// Crops the document to `r` (in current document coordinates). -/// A frame that extends past the canvas fills the Background's new area with `extension` (the -/// background colour, as Photoshop's Crop tool does); other layers get transparent pixels there. -fn crop_doc(doc: &mut Document, cmd: &str, r: Rect, delete_pixels: bool, extension: [f32; 4]) -> Result<()> { - // The origin moves to (0, 0); `-i32::MIN` has no i32 value (#959). - let (Some(dx), Some(dy)) = (r.x0.checked_neg(), r.y0.checked_neg()) else { - return Err(bad(cmd, format!("the crop origin ({}, {}) can't be moved to (0, 0) within the 32-bit coordinate range", r.x0, r.y0))); - }; - let old_canvas = doc.bounds(); - let extends = r.x0 < old_canvas.x0 || r.y0 < old_canvas.y0 || r.x1 > old_canvas.x1 || r.y1 > old_canvas.y1; - if delete_pixels { - delete_cropped_pixels(&mut doc.layers, r); - } - translate_doc(doc, cmd, dx, dy)?; - doc.size = Size::new(r.width(), r.height()); - // A Background cannot hold transparent pixels: like an opaque Canvas Size extension, the area - // an extending Crop adds is filled with the extension (background) colour. - if extends - && let Some(bg) = doc.background_mut() - && let LayerContent::Raster(surf) = &mut bg.content - { - let old = old_canvas.translate(dx, dy); - let px = photocraft_raster::from_rgba(&surf.format(), [extension[0], extension[1], extension[2], 1.0]); - fill_background_extension(surf, Rect::from_xywh(0, 0, r.width(), r.height()), old, &px); - } - if extends { - drop_fill_caches(&mut doc.layers); - } - crate::canvas_geom::refresh(doc, crate::canvas_geom::Refresh::Shapes); - Ok(()) -} - -/// Fills the area an extension adds to the Background's `canvas` (all of it outside the `old` -/// canvas, and any gap there) with `px`, under the pixels the Background already holds there: -/// those a crop with Delete Cropped Pixels off hid show again instead of being painted over (#7086). -/// Only the added strips are touched, so the cost follows the added area, not the canvas. -fn fill_background_extension(surf: &mut Surface, canvas: Rect, old: Rect, px: &[f32]) { - let keep = surf.content_bounds().intersect(&old).intersect(&canvas); - let strips = if keep.is_empty() { - vec![canvas] - } else { - vec![ - Rect::new(canvas.x0, canvas.y0, canvas.x1, keep.y0), - Rect::new(canvas.x0, keep.y1, canvas.x1, canvas.y1), - Rect::new(canvas.x0, keep.y0, keep.x0, keep.y1), - Rect::new(keep.x1, keep.y0, canvas.x1, keep.y1), - ] - }; - let n = surf.channels(); - let a = n.saturating_sub(1); - let pa = px.get(a).copied().unwrap_or(1.0); - // Without an alpha channel hidden pixels can't be told from empty ones: fill the strips. - let has_alpha = surf.format().alpha; - for strip in strips.into_iter().filter(|r| !r.is_empty()) { - if !has_alpha || !surf.has_tiles_in(strip) { - surf.fill_rect(strip, px); - continue; - } - // The Background's own pixels over `px` (source-over). - let mut d = surf.read_region(strip); - for p in d.chunks_exact_mut(n) { - let ta = p.get(a).copied().unwrap_or(0.0); - let oa = ta + pa * (1.0 - ta); - for (c, &f) in p.iter_mut().zip(px).take(a) { - *c = if oa > 0.0 { (*c * ta + f * pa * (1.0 - ta)) / oa } else { 0.0 }; - } - if let Some(alpha) = p.get_mut(a) { - *alpha = oa; - } - } - surf.write_region(strip, &d); - } -} - -/// The nine documented canvas-size anchors, in the order the command lists them, each mapped to -/// its (x, y) factor (0.0 = top/left edge, 0.5 = centre, 1.0 = bottom/right edge). -const ANCHORS: [(&str, (f64, f64)); 9] = [ - ("topLeft", (0.0, 0.0)), - ("top", (0.5, 0.0)), - ("topRight", (1.0, 0.0)), - ("left", (0.0, 0.5)), - ("center", (0.5, 0.5)), - ("right", (1.0, 0.5)), - ("bottomLeft", (0.0, 1.0)), - ("bottom", (0.5, 1.0)), - ("bottomRight", (1.0, 1.0)), -]; - -/// Resolves an anchor name to its (x, y) factors, matching the nine documented values exactly. -/// Anything else is an error naming `anchor` and listing them, rather than resolving the two axes -/// independently (which let a misspelling like `"topleft"` land between two valid anchors, #2946). -fn anchor_factors(cmd: &str, a: &str) -> Result<(f64, f64)> { - ANCHORS.iter().find(|(name, _)| *name == a).map(|&(_, f)| f).ok_or_else(|| { - let names = ANCHORS.iter().map(|&(n, _)| n).collect::>().join("|"); - bad(cmd, format!("`anchor` must be one of {names}")) - }) -} - -fn extension_color(s: &Session, p: &Value) -> [f32; 4] { - match p.get("extensionColor").and_then(Value::as_str).unwrap_or("background") { - "foreground" => s.tools.foreground, - "white" => [1.0; 4], - "black" => [0.0, 0.0, 0.0, 1.0], - "transparent" => [0.0; 4], - hex if hex.starts_with('#') => { - let h = hex.trim_start_matches('#'); - let c = |i: usize| h.get(i..i + 2).and_then(|x| u8::from_str_radix(x, 16).ok()).map_or(0.0, |v| f32::from(v) / 255.0); - [c(0), c(2), c(4), 1.0] - } - _ => s.tools.background, - } -} - -/// Image → Canvas Size. -fn canvas_size(s: &mut Session, p: &Value) -> Result { - let d = s.active().ok_or(EngineError::NoDocument)?; - let (ow, oh) = (d.doc.size.width as f64, d.doc.size.height as f64); - let relative = p.get("relative").and_then(Value::as_bool).unwrap_or(false); - let w = p.get("width").and_then(Value::as_f64).unwrap_or(if relative { 0.0 } else { ow }); - let h = p.get("height").and_then(Value::as_f64).unwrap_or(if relative { 0.0 } else { oh }); - let (nw, nh) = if relative { (ow + w, oh + h) } else { (w, h) }; - let (nw, nh) = (nw.round().clamp(1.0, 300_000.0) as u32, nh.round().clamp(1.0, 300_000.0) as u32); - let (ax, ay) = anchor_factors("image.canvasSize", p.get("anchor").and_then(Value::as_str).unwrap_or("center"))?; - let dx = ((nw as f64 - ow) * ax).round() as i32; - let dy = ((nh as f64 - oh) * ay).round() as i32; - let ext = extension_color(s, p); - s.set_sampler_map(photocraft_geom::Affine::translate(f64::from(dx), f64::from(dy))); - s.edit("Canvas Size", |doc, _| { - translate_doc(doc, "image.canvasSize", dx, dy)?; - doc.size = Size::new(nw, nh); - if nw > ow as u32 || nh > oh as u32 { - drop_fill_caches(&mut doc.layers); - } - crate::canvas_geom::refresh(doc, crate::canvas_geom::Refresh::Shapes); - let canvas = doc.bounds(); - let old = Rect::from_xywh(dx, dy, ow as u32, oh as u32); - // A Background cannot contain transparent pixels. When a transparent - // extension adds canvas area, make it a normal paintable layer first. - // A shrink or no-op resize must not silently convert the Background. - if ext[3] == 0.0 - && (nw > ow as u32 || nh > oh as u32) - && let Some(bg) = doc.background_mut() - { - crate::extra_cmds::unlock_background(bg); - } - // The locked Background layer is extended with the extension colour. - if ext[3] > 0.0 - && let Some(bg) = doc.background_mut() - && let LayerContent::Raster(surf) = &mut bg.content - { - let px = photocraft_raster::from_rgba(&surf.format(), ext); - fill_background_extension(surf, canvas, old, &px); - } - Ok(()) - })?; - Ok(json!({ "width": nw, "height": nh, "offset": [dx, dy] })) -} - -/// The largest side an explicit crop may give the canvas (the `file.new` and Canvas Size limit). -const MAX_CROP_SIDE: i32 = 300_000; - -/// Image → Crop (to the selection bounds). -fn crop(s: &mut Session, p: &Value) -> Result { - let delete = p.get("deleteCroppedPixels").and_then(Value::as_bool).unwrap_or(true); - // The Crop tool's Fill: Content-Aware Fill of what the crop uncovers (#3823). - let content_aware = match p.get("contentAware") { - None | Some(Value::Null) => false, - Some(Value::Bool(b)) => *b, - Some(v) => return Err(bad("image.crop", format!("`contentAware` must be true or false, not {v}"))), - }; - // Values beyond i32 would wrap through the narrowing casts into a rectangle unrelated to - // the numbers passed; reject them (see `commands::int_i32`). - let explicit = match ( - crate::commands::int_i32("image.crop", p, "x")?, - crate::commands::int_i32("image.crop", p, "y")?, - crate::commands::int_i32("image.crop", p, "width")?, - crate::commands::int_i32("image.crop", p, "height")?, - ) { - (Some(x), Some(y), Some(w), Some(h)) if w > 0 && h > 0 => { - // The new canvas size: refuse what File › New, Image Size and Canvas Size won't make, - // before anything changes. Unbounded, a following full-canvas flatten (Trim, Duplicate - // Merged) aborted on allocation (#960). - if w > MAX_CROP_SIDE || h > MAX_CROP_SIDE { - return Err(bad("image.crop", format!("{w} x {h} exceeds the {MAX_CROP_SIDE} px limit per side"))); - } - // A far edge past i32::MAX used to saturate, silently cropping less than asked (#959). - let end = |o: i32, len: i32, ko: &str, kl: &str| { - o.checked_add(len) - .ok_or_else(|| bad("image.crop", format!("`{ko}` + `{kl}` = {} is outside the 32-bit coordinate range", i64::from(o) + i64::from(len)))) - }; - Some(Rect::new(x, y, end(x, w, "x", "width")?, end(y, h, "y", "height")?)) - } - _ => None, - }; - let target = crop_target(p)?; - if let Some((tw, th)) = target.size { - let d = s.active().ok_or(EngineError::NoDocument)?; - check_resample_budget("image.crop", &d.doc, tw, th, "")?; - } - if let Some(a) = crop_angle(p)? { - let rect = explicit.ok_or_else(|| bad("image.crop", "an `angle` needs an explicit `x`, `y`, `width` and `height`"))?; - return rotated_crop(s, rect, a, delete, content_aware, &target); - } - // An explicit rectangle (the Crop tool) may extend past the canvas; a selection crop is clamped. - let r = explicit - .or_else(|| s.active().and_then(|d| d.doc.selection.as_ref().map(|sel| sel.content_bounds().intersect(&d.doc.bounds())))) - .unwrap_or(Rect::EMPTY); - if r.is_empty() { - return Err(EngineError::Other("nothing to crop: pass x/y/width/height or make a selection".into())); - } - s.set_sampler_map(target.sampler_map(r)); - let extension = s.tools.background; - s.edit("Crop", |doc, active| { - let original = doc.size; - crop_doc(doc, "image.crop", r, delete, extension)?; - // A straight crop fills all of the area past the old canvas, pixels an earlier Delete Cropped - // Pixels off crop hid there included, as Photoshop does; only a turned frame keeps them (#8060). - if content_aware { - crate::crop_fill::fill_uncovered(doc, *active, &crate::crop_fill::Coverage::crop(r, original.width, original.height))?; - } - doc.selection = None; - target.apply(doc); - Ok(()) - })?; - Ok(crop_result(s, json!({ "x": r.x0, "y": r.y0, "width": r.width(), "height": r.height() }))) -} - -/// The Crop tool's W x H x Resolution: the size (px) the cropped area is resampled to and the -/// resolution the document gets, both optional. -struct CropTarget { - size: Option<(u32, u32)>, - resolution: Option, - filter: Resample, -} - -impl CropTarget { - /// Applies the target to a document that has just been cropped (inside the crop's history step). - fn apply(&self, doc: &mut Document) { - if let Some((w, h)) = self.size { - // As for Image Size: an Indexed Color document holds only its colour table's colours (#6019). - let filter = if doc.mode == ColorMode::Indexed { Resample::Nearest } else { self.filter }; - resample_doc(doc, w, h, filter); - } - if let Some(r) = self.resolution { - doc.resolution_dpi = r; - } - } - - /// Where Color Sampler points go: shifted by the crop's origin, then scaled with the pixels - /// when [`Self::apply`] resamples the cropped area `r` (as Image Size scales them). - fn sampler_map(&self, r: Rect) -> photocraft_geom::Affine { - let shift = photocraft_geom::Affine::translate(-f64::from(r.x0), -f64::from(r.y0)); - match self.size { - Some((w, h)) if r.width() > 0 && r.height() > 0 => { - let (sx, sy) = (f64::from(w) / f64::from(r.width()), f64::from(h) / f64::from(r.height())); - shift.then(&photocraft_geom::Affine { m: [sx, 0.0, 0.0, sy, 0.0, 0.0] }) - } - _ => shift, - } - } -} - -/// The highest resolution (ppi) a crop may set, as for Image Size. -const MAX_CROP_RESOLUTION: f64 = 10_000.0; - -/// `image.crop`'s optional `targetWidth`/`targetHeight` (whole px, both or neither), `resolution` -/// (ppi) and `resample` (as for `image.imageSize`; "none" is refused with a target size). -fn crop_target(p: &Value) -> Result { - const CMD: &str = "image.crop"; - let side = |key: &str| -> Result> { - match p.get(key) { - None | Some(Value::Null) => Ok(None), - // Whole-number floats (`100.0`) count too, as for the crop rectangle. - Some(v) => v - .as_u64() - .or_else(|| v.as_f64().filter(|f| f.fract() == 0.0 && (0.0..=f64::from(MAX_CROP_SIDE)).contains(f)).map(|f| f as u64)) - .and_then(|n| u32::try_from(n).ok()) - .filter(|n| (1..=MAX_CROP_SIDE as u32).contains(n)) - .map(Some) - .ok_or_else(|| bad(CMD, format!("`{key}` = {v} must be a whole number of pixels from 1 to {MAX_CROP_SIDE}"))), - } - }; - let size = match (side("targetWidth")?, side("targetHeight")?) { - (Some(w), Some(h)) => Some((w, h)), - (None, None) => None, - _ => return Err(bad(CMD, "`targetWidth` and `targetHeight` go together")), - }; - let resolution = match p.get("resolution") { - None | Some(Value::Null) => None, - Some(v) => { - let r = v.as_f64().filter(|r| r.is_finite() && (1.0..=MAX_CROP_RESOLUTION).contains(r)); - Some(r.ok_or_else(|| bad(CMD, format!("`resolution` = {v} must be a number of pixels per inch from 1 to {MAX_CROP_RESOLUTION}")))? as f32) - } - }; - let filter = match p.get("resample") { - None | Some(Value::Null) => Some(Resample::Bicubic), - Some(v) => match parse_resample(v.as_str().ok_or_else(|| bad(CMD, "`resample` must be a string"))?) { - Method::None => None, - Method::Filter(f) => Some(f), - // The direction is known only once the frame is: bicubic's own automatic choice. - Method::Automatic => Some(Resample::BicubicAutomatic), - }, - }; - let filter = match (filter, size) { - (Some(f), _) => f, - (None, None) => Resample::Bicubic, - (None, Some(_)) => return Err(bad(CMD, "a `targetWidth` x `targetHeight` crop needs resampling: `resample` can't be \"none\"")), - }; - Ok(CropTarget { size, resolution, filter }) -} - -/// A crop's result: the frame it cropped to, plus the document's size and resolution afterwards. -fn crop_result(s: &Session, mut frame: Value) -> Value { - if let (Some(d), Some(o)) = (s.active(), frame.as_object_mut()) { - o.insert("documentWidth".into(), json!(d.doc.size.width)); - o.insert("documentHeight".into(), json!(d.doc.size.height)); - o.insert("resolution".into(), json!(d.doc.resolution_dpi)); - } - frame -} - -/// The largest crop angle accepted (degrees), as for Image Rotation › Arbitrary. -const MAX_CROP_ANGLE: f64 = 3600.0; - -/// `image.crop`'s optional `angle` in degrees, normalised to (-180, 180]; `None` when it is absent, -/// null or (after normalising) zero, so an unrotated crop takes the plain, resampling-free path. -fn crop_angle(p: &Value) -> Result> { - let a = match p.get("angle") { - None | Some(Value::Null) => return Ok(None), - Some(v) => v.as_f64().ok_or_else(|| bad("image.crop", "`angle` must be a number of degrees"))?, - }; - if !a.is_finite() || a.abs() > MAX_CROP_ANGLE { - return Err(bad("image.crop", format!("`angle` must be a finite number of degrees within ±{MAX_CROP_ANGLE}"))); - } - let a = a.rem_euclid(360.0); - let a = if a > 180.0 { a - 360.0 } else { a }; - Ok((a.abs() >= 1e-9).then_some(a)) -} - -/// The Crop tool's rotated frame: `r` (document px) turned clockwise on screen by `angle` degrees -/// about its centre. The document is rotated counter-clockwise by `angle` (Image Rotation › -/// Arbitrary: the canvas grows to fit, the Background fills what the rotation uncovers with the -/// background colour, other layers keep transparency there and every pixel of theirs), which makes -/// the frame upright, then cropped to it (`deleteCroppedPixels` as for an unrotated crop), all in -/// one undo step. With `content_aware`, the corners the rotation uncovers (and any area past the -/// rotated image) are then filled from their surroundings, in the same step (#3823). -fn rotated_crop(s: &mut Session, r: Rect, angle: f64, delete: bool, content_aware: bool, crop_target: &CropTarget) -> Result { - const CMD: &str = "image.crop"; - let size = s.active().ok_or(EngineError::NoDocument)?.doc.size; - let (w, h) = (f64::from(r.width()), f64::from(r.height())); - let (cx, cy) = (f64::from(r.x0) + w / 2.0, f64::from(r.y0) + h / 2.0); - // Where the frame's centre lands: the rotation `image.rotation.arbitrary` applies, clockwise - // by `-angle` (x' = c·x − s·y, y' = s·x + c·y) about the old and new canvas centres. - let new = crate::mode_cmds::rotated_size(size, -angle); - let (sn, cs) = (-angle).to_radians().sin_cos(); - let (dx, dy) = (cx - f64::from(size.width) / 2.0, cy - f64::from(size.height) / 2.0); - let (ncx, ncy) = (f64::from(new.width) / 2.0 + cs * dx - sn * dy, f64::from(new.height) / 2.0 + sn * dx + cs * dy); - let (x, y) = ((ncx - w / 2.0).round(), (ncy - h / 2.0).round()); - let far = || bad(CMD, "the rotated frame is outside the 32-bit coordinate range"); - let limit = f64::from(i32::MAX / 2); - if !(x.is_finite() && y.is_finite()) || x.abs() > limit || y.abs() > limit { - return Err(far()); - } - let (x, y) = (x as i32, y as i32); - let end = |o: i32, len: u32| i32::try_from(len).ok().and_then(|l| o.checked_add(l)); - let (Some(x1), Some(y1)) = (end(x, r.width()), end(y, r.height())) else { return Err(far()) }; - let target = Rect::new(x, y, x1, y1); - // The cropped canvas back to the original document: undo the crop's offset, then the rotation - // (x = c·(x' − nx) + s·(y' − ny) + cx, y = −s·(x' − nx) + c·(y' − ny) + cy). - let (ox, oy) = (f64::from(target.x0) - f64::from(new.width) / 2.0, f64::from(target.y0) - f64::from(new.height) / 2.0); - let (ocx, ocy) = (f64::from(size.width) / 2.0, f64::from(size.height) / 2.0); - let coverage = crate::crop_fill::Coverage { - map: [cs, sn, -sn, cs, cs * ox + sn * oy + ocx, -sn * ox + cs * oy + ocy], - width: f64::from(size.width), - height: f64::from(size.height), - rotated: true, - held: None, - }; - // The pixels before the turn: under a turned frame a Delete Cropped Pixels off crop's hidden ones - // count as image, as in Photoshop (a straight crop fills over them) (#8060). - let coverage = if content_aware { - let d = s.active().ok_or(EngineError::NoDocument)?; - coverage.holding(&d.doc, d.active_layer) - } else { - coverage - }; - crate::analysis_cmds::compound(s, "Crop", |s| { - // Pixels the crop deletes needn't be turned first: keeping only what lands in the frame - // makes the rotation cost the frame's size, not the canvas's (a small turned crop of a - // 10 MP photo took over half a second). - if delete { - let keep = turned_crop_source(size, new, angle, target); - s.edit("Crop", |doc, _| { - // Type and smart objects stay whole, as in the crop itself: the rotation re-renders - // them, but a smart object whose source is unavailable keeps its cache. - delete_cropped_pixels(&mut doc.layers, keep); - for_each_layer(&mut doc.layers, &mut |l| { - if let Some(m) = &mut l.mask { - m.surface = crop_surface(&m.surface, keep); - } - }); - for ch in doc.channels.iter_mut().chain(doc.quick_mask.as_mut()) { - ch.surface = crop_surface(&ch.surface, keep); - } - // The crop drops the selection anyway. - doc.selection = None; - Ok(()) - })?; - } - crate::mode_cmds::rotate_arbitrary(s, &json!({"angle": angle, "direction": "ccw"}))?; - // Color Sampler points follow the crop's origin shift too (the rotation moved them above). - s.set_sampler_map(crop_target.sampler_map(target)); - let extension = s.tools.background; - s.edit("Crop", |doc, active| { - crop_doc(doc, CMD, target, delete, extension)?; - if content_aware { - crate::crop_fill::fill_uncovered(doc, *active, &coverage)?; - } - doc.selection = None; - crop_target.apply(doc); - Ok(()) - }) - })?; - Ok(crop_result(s, json!({ "x": r.x0, "y": r.y0, "width": r.width(), "height": r.height(), "angle": angle }))) -} - -/// The pixels a turned crop reads, in document coordinates before the turn: the source of the -/// `target` frame (on the `new` canvas the rotation by `-angle` makes of `old`), grown by the widest -/// interpolation kernel's reach so every sample the frame's pixels take is kept. -fn turned_crop_source(old: Size, new: Size, angle: f64, target: Rect) -> Rect { - const KERNEL_REACH: f64 = 4.0; - // The inverse of `rotate_arbitrary`'s map: x = c·u + s·v + cx, y = −s·u + c·v + cy, where - // (u, v) is the point relative to the new canvas's centre. - let (sn, cs) = (-angle).to_radians().sin_cos(); - let (cx, cy) = (f64::from(old.width) / 2.0, f64::from(old.height) / 2.0); - let (nx, ny) = (f64::from(new.width) / 2.0, f64::from(new.height) / 2.0); - let (mut x0, mut y0, mut x1, mut y1) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY); - for (px, py) in [(target.x0, target.y0), (target.x1, target.y0), (target.x0, target.y1), (target.x1, target.y1)] { - let (u, v) = (f64::from(px) - nx, f64::from(py) - ny); - let (x, y) = (cs * u + sn * v + cx, -sn * u + cs * v + cy); - (x0, y0, x1, y1) = (x0.min(x), y0.min(y), x1.max(x), y1.max(y)); - } - // `as` saturates: a frame near the coordinate limits keeps more, never less. - Rect::new((x0 - KERNEL_REACH).floor() as i32, (y0 - KERNEL_REACH).floor() as i32, (x1 + KERNEL_REACH).ceil() as i32, (y1 + KERNEL_REACH).ceil() as i32) -} - -/// Image → Trim. -fn trim(s: &mut Session, p: &Value) -> Result { - let d = s.active().ok_or(EngineError::NoDocument)?; - let canvas = d.doc.bounds(); - let buf = flatten_whole(&d.doc, "image.trim")?; - let based = p.get("basedOn").and_then(Value::as_str).unwrap_or("transparent"); - let w = canvas.width() as usize; - let reference = match based { - "topLeft" => buf.px.first().copied(), - "bottomRight" => buf.px.last().copied(), - _ => None, - }; - let differs = |q: [f32; 4]| match reference { - None => q[3] > 0.0, - Some(r) => (0..4).any(|c| (q[c] * q[3] - r[c] * r[3]).abs() > 0.5 / 255.0 || (c == 3 && (q[3] - r[3]).abs() > 0.5 / 255.0)), - }; - let mut b = Rect::EMPTY; - for (i, q) in buf.px.iter().enumerate() { - if differs(*q) { - let (x, y) = ((i % w) as i32, (i / w) as i32); - b = if b.is_empty() { Rect::new(x, y, x + 1, y + 1) } else { b.union(&Rect::new(x, y, x + 1, y + 1)) }; - } - } - if b.is_empty() { - return Err(EngineError::Other("nothing to trim to".into())); - } - let side = |k: &str| p.get(k).and_then(Value::as_bool).unwrap_or(true); - let r = Rect::new( - if side("left") { b.x0 } else { canvas.x0 }, - if side("top") { b.y0 } else { canvas.y0 }, - if side("right") { b.x1 } else { canvas.x1 }, - if side("bottom") { b.y1 } else { canvas.y1 }, - ); - s.set_sampler_map(photocraft_geom::Affine::translate(-f64::from(r.x0), -f64::from(r.y0))); - let extension = s.tools.background; - s.edit("Trim", |doc, _| crop_doc(doc, "image.trim", r, true, extension))?; - Ok(json!({ "x": r.x0, "y": r.y0, "width": r.width(), "height": r.height() })) -} - -/// Image → Mode → colour model, through the CMS (see [`crate::color_cmds::convert_mode`]). -fn convert_mode(s: &mut Session, mode: ColorMode, p: &Value) -> Result { - crate::color_cmds::convert_mode(s, mode, p) -} - -/// Image → Mode → 8/16/32 Bits/Channel. -fn convert_depth(s: &mut Session, depth: SampleType) -> Result { - let current = s.active().ok_or(EngineError::NoDocument)?.doc.depth; - if current == depth { - // History::record clears redo even when an edit closure leaves the document unchanged. - return Ok(Value::Null); - } - s.edit("Bit Depth", |doc, _| { - change_depth(doc, depth); - Ok(()) - })?; - Ok(Value::Null) -} - -pub(crate) fn change_depth(doc: &mut Document, depth: SampleType) { - let current = doc.depth; - // 32-bit documents hold linear light (as Photoshop's do: grey 128 becomes 0.2159, measured - // in Photoshop 27.11), so the colour samples cross the document's tone curve when the - // depth crosses 32 bits: decoded after widening, encoded before narrowing (so no linear - // value is quantised to 8 or 16 bits). Masks, alpha and channels are not colour. - let crosses = (current == SampleType::F32) != (depth == SampleType::F32) && matches!(doc.mode, ColorMode::Rgb | ColorMode::Grayscale); - let to_linear = depth == SampleType::F32; - let transfer = photocraft_compose::adjust::Transfer::for_document(doc.mode, if to_linear { current } else { depth }); - if crosses && !to_linear { - for_each_surface(&mut doc.layers, false, &mut |surf, _| surf.map_color(|v| transfer.encode(v).clamp(0.0, 1.0))); - } - convert_layers_depth(&mut doc.layers, depth); - if crosses && to_linear { - for_each_surface(&mut doc.layers, false, &mut |surf, _| surf.map_color(|v| transfer.decode(v))); - } - for ch in doc.channels.iter_mut().chain(doc.quick_mask.as_mut()) { - let f = ch.surface.format().with_sample(depth); - ch.surface = ch.surface.convert(f); - } - doc.depth = depth; -} - -/// Image → Duplicate. -fn duplicate(s: &mut Session, p: &Value) -> Result { - let d = s.active().ok_or(EngineError::NoDocument)?; - let mut doc = (*d.doc).clone(); - doc.id = photocraft_doc::DocId::fresh(); - doc.name = p.get("name").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| format!("{} copy", d.doc.name)); - if p.get("mergedOnly").and_then(Value::as_bool).unwrap_or(false) { - let buf = flatten_whole(&doc, "image.duplicate")?; - let fmt = doc.pixel_format(); - let mut surf = Surface::new(fmt); - let vals: Vec = buf.px.iter().flat_map(|q| photocraft_raster::from_rgba(&fmt, *q)).collect(); - surf.write_region(doc.bounds(), &vals); - surf.prune(); - // As Photoshop: a source with a Background gives one (opaque, locked); otherwise a plain - // "Layer 1" that keeps the composite's transparency. - let has_background = doc.background().is_some(); - let mut merged = Layer::new(if has_background { "Background" } else { "Layer 1" }, LayerContent::Raster(surf)); - merged.locks.transparency = has_background; - merged.locks.position = has_background; - doc.layers = vec![merged]; - // A merged-only copy has no original layers for saved comps to restore. - // Don't carry dangling comp state into a single-layer flattened document. - doc.layer_comps.clear(); - doc.last_applied_comp = None; - doc.last_document_state = None; - // Likewise, variables drove template layers that no longer exist: drop the whole - // binding set (defs, data sets and the active index) on the flattened copy. - doc.variables = photocraft_doc::Variables::default(); - } - reidentify_copied_layers(&mut doc); - let name = doc.name.clone(); - let index = s.add_document(doc, None); - Ok(json!({ "document": index, "name": name })) -} - -macro_rules! spec { - ($id:literal, $label:literal, [$($m:literal),*], $params:literal, $en:expr, $run:expr) => { - CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: None, params: $params, enabled: $en, run: $run, journal: true } - }; -} - -/// Image menu command specs. -pub fn specs() -> Vec { - vec![ - spec!( - "image.imageSize", - "Image Size…", - ["Image"], - r##"{"width":px,"height":px,"percent":%? (both sides; an explicit side wins),"resolution":ppi,"keepPrintSize":bool=false (with only a resolution: resample the pixels to keep the print size),"resample":"automatic|preserveDetails|bicubicSmoother|bicubicSharper|bicubicAutomatic|bicubic|nearest|bilinear|lanczos|none"="bicubic"} → {width,height} (the document's size after the command; "none" changes the resolution only)"##, - has_doc, - image_size - ), - spec!( - "image.canvasSize", - "Canvas Size…", - ["Image"], - r##"{"width":px,"height":px,"relative":bool=false,"anchor":"topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight"="center","extensionColor":"background|foreground|white|black|transparent|#rrggbb"="background"}"##, - has_doc, - canvas_size - ), - spec!( - "image.crop", - "Crop", - ["Image"], - r##"{"x":px,"y":px,"width":px,"height":px,"angle":-3600..3600=0,"deleteCroppedPixels":bool=true,"contentAware":bool=false,"targetWidth":px,"targetHeight":px,"resolution":ppi,"resample":"bicubic|bilinear|nearest|lanczos|preserveDetails"="bicubic"} → {x,y,width,height,documentWidth,documentHeight,resolution} (targetWidth/targetHeight, both or neither: the cropped area is resampled to exactly that size, as Image Size, in the same undo step; resolution: the document's new ppi; contentAware: the Crop tool's Fill › Content-Aware Fill, the area a rotated or extending crop uncovers filled from its surroundings on the Background, else the active pixel layer)"##, - has_doc, - crop - ), - spec!( - "image.trim", - "Trim…", - ["Image"], - r##"{"basedOn":"transparent|topLeft|bottomRight"="transparent","top":bool=true,"bottom":bool=true,"left":bool=true,"right":bool=true}"##, - has_doc, - trim - ), - spec!( - "image.mode.rgb", - "RGB Color", - ["Image", "Mode"], - r##"{"profile":"|working|/path/to/profile.icc"=working,"intent":"perceptual|relative|saturation|absolute"="relative","bpc":bool=true}"##, - has_doc, - |s, p| convert_mode(s, ColorMode::Rgb, p) - ), - spec!( - "image.mode.grayscale", - "Grayscale", - ["Image", "Mode"], - r##"{"profile":"|working|/path/to/profile.icc"=working,"intent":"perceptual|relative|saturation|absolute"="relative","bpc":bool=true}"##, - has_doc, - |s, p| convert_mode(s, ColorMode::Grayscale, p) - ), - spec!( - "image.mode.cmyk", - "CMYK Color", - ["Image", "Mode"], - r##"{"profile":"|working|/path/to/profile.icc"=working,"intent":"perceptual|relative|saturation|absolute"="relative","bpc":bool=true}"##, - has_doc, - |s, p| convert_mode(s, ColorMode::Cmyk, p) - ), - spec!( - "image.mode.lab", - "Lab Color", - ["Image", "Mode"], - r##"{"profile":"|working|/path/to/profile.icc"=working,"intent":"perceptual|relative|saturation|absolute"="relative","bpc":bool=true}"##, - has_doc, - |s, p| convert_mode(s, ColorMode::Lab, p) - ), - spec!("image.mode.bits8", "8 Bits/Channel", ["Image", "Mode"], "{}", has_doc, |s, _| convert_depth(s, SampleType::U8)), - spec!("image.mode.bits16", "16 Bits/Channel", ["Image", "Mode"], "{}", has_doc, |s, _| convert_depth(s, SampleType::U16)), - spec!("image.mode.bits32", "32 Bits/Channel", ["Image", "Mode"], "{}", has_doc, |s, _| convert_depth(s, SampleType::F32)), - spec!("image.duplicate", "Duplicate…", ["Image"], r##"{"name":str,"mergedOnly":bool=false}"##, has_doc, duplicate), - ] -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn crop_rejects_rectangles_that_would_wrap() { - let mut s = session(); - // 2^32 + 100 wrapped to `x = 100` through the narrowing casts: a crop rectangle - // somewhere unrelated to the numbers passed. - let err = s.execute("image.crop", json!({"x": 4_294_967_396_i64, "y": 0, "width": 10, "height": 10})).unwrap_err(); - assert!(err.to_string().contains("32-bit"), "{err}"); - // In-range rectangles past the canvas still work (clamped by the crop itself). - s.execute("image.crop", json!({"x": -10, "y": -10, "width": 1000, "height": 1000})).unwrap(); - } - - /// A crop whose translation to the origin can't be represented in i32 is rejected before - /// anything changes (#959): `-i32::MIN` overflowed the negation in `crop_doc`, `x + width` - /// past i32::MAX silently shortened the crop, and an origin one past i32::MIN moved the - /// layer pixels beyond i32::MAX (a length-mismatch panic while translating surfaces). - #[test] - fn crop_rejects_origins_that_cannot_move_to_zero() { - const MIN: i64 = i32::MIN as i64; - const MAX: i64 = i32::MAX as i64; - let cases = [ - json!({"x": MIN, "y": 0, "width": 1, "height": 1}), - json!({"x": 0, "y": MIN, "width": 1, "height": 1}), - json!({"x": MIN, "y": MIN, "width": 1, "height": 1}), - json!({"x": MIN, "y": 0, "width": 1, "height": 1, "deleteCroppedPixels": false}), - json!({"x": MAX - 5, "y": 0, "width": 10, "height": 1}), - json!({"x": 0, "y": MAX - 5, "width": 1, "height": 10}), - json!({"x": MIN + 1, "y": 0, "width": 1, "height": 1, "deleteCroppedPixels": false}), - json!({"x": 0, "y": MIN + 1, "width": 1, "height": 1, "deleteCroppedPixels": false}), - ]; - for p in cases { - let mut s = session(); - let before = s.active().unwrap().doc.clone(); - let (rev, steps) = (s.active().unwrap().revision, s.active().unwrap().history.entries().len()); - let err = s.execute("image.crop", p.clone()).unwrap_err(); - assert!(matches!(err, EngineError::BadParams { .. }), "{p}: {err}"); - assert!(err.to_string().contains("32-bit"), "{p}: {err}"); - let st = s.active().unwrap(); - assert!(std::sync::Arc::ptr_eq(&st.doc, &before), "{p}: document changed"); - assert_eq!(st.doc.size, Size::new(40, 20), "{p}"); - assert_eq!(st.doc.layers[1].surface().unwrap().content_bounds(), Rect::new(10, 5, 20, 15), "{p}"); - assert_eq!((st.revision, st.history.entries().len()), (rev, steps), "{p}: history step recorded"); - } - // Control: a legal negative origin past the canvas still crops (and extends) the canvas. - let mut s = session(); - s.execute("image.crop", json!({"x": -10, "y": -5, "width": 60, "height": 30})).unwrap(); - assert_eq!(doc(&s).size, Size::new(60, 30)); - assert_eq!(doc(&s).layers[1].surface().unwrap().pixel(20, 10), vec![1.0, 0.0, 0.0, 1.0]); - // A far-off crop that deletes the (non-overlapping) pixels has nothing left to move. - let mut s = session(); - s.execute("image.crop", json!({"x": MIN + 1, "y": 0, "width": 1, "height": 1})).unwrap(); - assert_eq!(doc(&s).size, Size::new(1, 1)); - } - - fn session() -> Session { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 40, "height": 20})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.edit("paint", |doc, active| { - let l = doc.layer_mut(active.unwrap()).unwrap(); - l.surface_mut().unwrap().fill_rect(Rect::new(10, 5, 20, 15), &[1.0, 0.0, 0.0, 1.0]); - l.mask = Some(photocraft_doc::LayerMask::reveal_all()); - l.effects.items.push(Effect::default_drop_shadow()); - Ok(()) - }) - .unwrap(); - s - } - - fn doc(s: &Session) -> &Document { - &s.active().unwrap().doc - } - - /// Document-wide conversions must move every stored video frame, not just the displayed one (#4956). - #[test] - fn crop_moves_stored_video_frames() { - let mut s = session(); - s.edit("video", |doc, active| { - let l = doc.layer_mut(active.unwrap()).unwrap(); - let frame = l.surface().unwrap().clone(); - let mut v = photocraft_doc::VideoData::new(vec![frame.clone(), frame.clone()], 24.0); - v.original_frames = Some(vec![frame.clone(), frame]); - l.video = Some(v); - Ok(()) - }) - .unwrap(); - s.execute("image.crop", json!({"x": -10, "y": -5, "width": 60, "height": 30})).unwrap(); - let v = doc(&s).layers[1].video.as_ref().unwrap(); - let red = vec![1.0, 0.0, 0.0, 1.0]; - for frame in v.frames.iter().chain(v.original_frames.iter().flatten()) { - assert_eq!(frame.pixel(20, 10), red); - assert_eq!(frame.pixel(5, 5)[3], 0.0); - } - } - - /// Delete Cropped Pixels on a shrinking crop deletes the cropped area from every stored video - /// frame (and the original footage), not just the displayed one (#4956). - #[test] - fn delete_cropped_pixels_crops_stored_video_frames() { - let mut s = session(); - s.edit("video", |doc, active| { - let l = doc.layer_mut(active.unwrap()).unwrap(); - let red = l.surface().unwrap().clone(); - let mut blue = red.clone(); - blue.fill_rect(Rect::new(0, 0, 40, 20), &[0.0, 0.0, 1.0, 1.0]); - let mut v = photocraft_doc::VideoData::new(vec![red.clone(), blue.clone()], 24.0); - v.original_frames = Some(vec![red, blue]); - l.video = Some(v); - Ok(()) - }) - .unwrap(); - s.execute("image.crop", json!({"x": 15, "y": 0, "width": 25, "height": 20, "deleteCroppedPixels": true})).unwrap(); - assert_eq!(doc(&s).size, Size::new(25, 20)); - let v = doc(&s).layers[1].video.as_ref().unwrap(); - let originals = v.original_frames.as_ref().unwrap(); - assert_eq!((v.frames.len(), originals.len()), (2, 2)); - for frames in [&v.frames, originals] { - // The red square (10..20, 5..15) keeps only its right half; the full blue frame - // keeps exactly the 25×20 crop. - assert_eq!(frames[0].content_bounds(), Rect::new(0, 5, 5, 15)); - assert_eq!(frames[0].pixel(2, 10), vec![1.0, 0.0, 0.0, 1.0]); - assert_eq!(frames[1].content_bounds(), Rect::new(0, 0, 25, 20)); - assert_eq!(frames[1].pixel(24, 19), vec![0.0, 0.0, 1.0, 1.0]); - } - } - - /// Resample on with only a new resolution keeps the print size, as Photoshop's Image Size - /// does (an action's `imageSize` with `Rslt` alone); without `keepPrintSize` only the - /// resolution changes. - #[test] - fn image_size_keep_print_size_resamples_to_the_resolution() { - let mut s = session(); - s.execute("image.imageSize", json!({"resolution": 144, "resample": "bicubic"})).unwrap(); - assert_eq!((doc(&s).size, doc(&s).resolution_dpi), (Size::new(40, 20), 144.0)); - s.execute("image.imageSize", json!({"resolution": 288, "resample": "bicubic", "keepPrintSize": true})).unwrap(); - assert_eq!((doc(&s).size, doc(&s).resolution_dpi), (Size::new(80, 40), 288.0)); - // An explicit side still wins. - s.execute("image.imageSize", json!({"width": 20, "resolution": 72, "resample": "bicubic", "keepPrintSize": true})).unwrap(); - assert_eq!(doc(&s).size, Size::new(20, 10)); - } - - #[test] - fn image_size_scales_everything() { - for resample in ["bicubic", "bicubicSmoother", "bicubicSharper", "bicubicAutomatic", "automatic", "bilinear", "nearest", "lanczos", "preserveDetails"] { - let mut s = session(); - s.execute("image.imageSize", json!({"width": 80, "resample": resample})).unwrap(); - let d = doc(&s); - assert_eq!(d.size, Size::new(80, 40), "{resample}"); - let l = &d.layers[1]; - let b = l.surface().unwrap().content_bounds(); - assert!((b.x0 - 20).abs() <= 1 && (b.x1 - 40).abs() <= 1, "{resample} {b:?}"); - let Effect::DropShadow(sh) = &l.effects.items[0] else { panic!() }; - assert_eq!(sh.distance, 10.0); - assert_eq!(l.mask.as_ref().unwrap().surface.default_pixel(), vec![1.0]); - } - } - - /// #6019: Image Size on an Indexed Color document makes no colours the colour table doesn't have. - #[test] - fn image_size_resamples_indexed_color_with_nearest_neighbor() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 2, "height": 1})).unwrap(); - s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); - s.execute("select.rect", json!({"x": 1, "y": 0, "width": 1, "height": 1})).unwrap(); - s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap(); - s.execute("select.deselect", json!({})).unwrap(); - s.execute("image.mode.indexedColor", json!({})).unwrap(); - for resample in ["bicubic", "automatic", "bilinear", "lanczos", "preserveDetails"] { - s.execute("image.imageSize", json!({"width": 8, "resample": resample})).unwrap(); - let st = s.active().unwrap(); - let surf = st.doc.layers[0].surface().unwrap(); - for x in 0..8 { - let px = surf.pixel(x, 0); - assert!(px[..3] == [1.0, 0.0, 0.0] || px[..3] == [0.0, 0.0, 1.0], "{resample}: no blended colour at x {x}: {px:?}"); - } - s.execute("history.undo", json!({})).unwrap(); - } - } - - /// The canvas border stays opaque after Image Size (it used to fade into transparency, so a - /// Background or a 200 % export got a translucent frame), and a full selection stays full. - /// #1544: 64 x 48 to 300000 x 300000 (90 billion pixels) started allocating resampled bands - /// without a budget. It is refused before any allocation and the document is untouched; a - /// change of resolution only, and an ordinary resize, still work. - #[test] - fn image_size_refuses_a_raster_past_the_budget() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 64, "height": 48})).unwrap(); - let before = (doc(&s).size, s.active().unwrap().history.past_len()); - let err = s.execute("image.imageSize", json!({"width": 300_000, "height": 300_000})).unwrap_err().to_string(); - assert!(err.contains("megapixels"), "{err}"); - assert_eq!((doc(&s).size, s.active().unwrap().history.past_len()), before); - s.execute("image.imageSize", json!({"width": 300_000, "height": 300_000, "resample": "none", "resolution": 300})).unwrap(); - s.execute("image.imageSize", json!({"width": 128, "height": 96})).unwrap(); - assert_eq!(doc(&s).size, Size::new(128, 96)); - } - - #[test] - fn image_size_keeps_canvas_edges_opaque() { - for depth in [8, 16, 32] { - for (w, resample) in [ - (60, "bicubic"), - (41, "lanczos"), - (15, "bilinear"), - (77, "preserveDetails"), - (21, "bicubicSharper"), - (47, "automatic"), - (9, "bicubicAutomatic"), - ] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 30, "height": 20, "depth": depth, "background": "#336699"})).unwrap(); - s.execute("select.all", json!({})).unwrap(); - s.execute("image.imageSize", json!({"width": w, "resample": resample})).unwrap(); - let d = doc(&s); - let flat = photocraft_compose::flatten(d); - let (w, h) = (flat.rect.width() as usize, flat.rect.height() as usize); - let mid = flat.px[(h / 2) * w + w / 2]; - assert!((mid[3] - 1.0).abs() < 1e-3, "{depth} {resample}: {mid:?}"); - for p in &flat.px { - let off = p.iter().zip(mid).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); - assert!(off < 0.01, "{depth} {resample} {w}: {p:?} vs {mid:?}"); - } - let sel = d.selection.as_ref().unwrap(); - let (x1, y1) = (d.size.width as i32 - 1, d.size.height as i32 - 1); - for (x, y) in [(0, 0), (x1, 0), (0, y1), (x1, y1)] { - assert!(sel.pixel(x, y)[0] > 0.99, "{depth} {resample}: selection at ({x},{y})"); - } - } - } - } - - #[test] - fn resolution_only_change() { - let mut s = session(); - let r = s.execute("image.imageSize", json!({"resolution": 300, "resample": "none", "width": 999})).unwrap(); - assert_eq!(doc(&s).size, Size::new(40, 20)); - assert_eq!(doc(&s).resolution_dpi, 300.0); - // #1815: the result is the size the document has, not the ignored request. - assert_eq!(r, json!({"width": 40, "height": 20})); - } - - /// Type keeps its pixel size across a resolution change: resampled 2x at twice the ppi it is - /// twice as tall (not 4x), with Resample off it stays, and a later re-render doesn't jump. - #[test] - fn image_size_with_a_new_resolution_scales_type_with_the_pixels_only() { - for (params, k) in [(json!({"width": 200, "height": 200, "resolution": 144}), 2), (json!({"resolution": 144, "resample": "none"}), 1)] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 100, "height": 100})).unwrap(); - s.execute("type.create", json!({"x": 10, "y": 50, "text": "Hi", "size": 12})).unwrap(); - let height = |s: &Session| doc(s).layers.last().unwrap().surface().unwrap().content_bounds().height(); - let h0 = height(&s); - assert!(h0 > 4, "{h0}"); - s.execute("image.imageSize", params.clone()).unwrap(); - assert!(height(&s).abs_diff(h0 * k) <= 2, "{params}: {h0} -> {}", height(&s)); - let d = doc(&s); - let LayerContent::Text(t) = &d.layers.last().unwrap().content else { panic!("type layer") }; - let mut t = t.clone(); - crate::type_cmds::refresh(d, &mut t); - let after = t.cache.unwrap().content_bounds().height(); - assert!(after.abs_diff(h0 * k) <= 2, "{params}: re-rendered {h0} -> {after}"); - } - } - - #[test] - fn image_size_reports_the_size_it_applied() { - // #1815: every path reports the document's size afterwards, at every depth. - for depth in [8, 16, 32] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 64, "height": 48, "depth": depth})).unwrap(); - let size = |s: &Session| json!({"width": doc(s).size.width, "height": doc(s).size.height}); - for p in [ - json!({"width": 999, "height": 777, "resample": "none", "resolution": 150}), - json!({"width": 32}), - json!({"height": 96, "resample": "nearest"}), - json!({"width": 96, "height": 72, "resample": "none"}), - json!({}), - ] { - let r = s.execute("image.imageSize", p.clone()).unwrap(); - assert_eq!(r, size(&s), "{depth}-bit {p}"); - } - // 64×48 → (none) → 32×24 → 128×96 (aspect kept) → (none) → unchanged. - assert_eq!(doc(&s).size, Size::new(128, 96), "{depth}-bit"); - } - } - - /// #1114: nearest neighbor reduction keeps source values without averaging. - #[test] - fn nearest_neighbor_reduction_keeps_source_values() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); - s.execute("tools.setColors", json!({"foreground": "#000000", "background": "#ffffff"})).unwrap(); - for y in 0..8 { - for x in 0..8 { - if (x + y) % 2 == 0 { - s.execute("select.rect", json!({"x": x, "y": y, "width": 1, "height": 1})).unwrap(); - s.execute("edit.fill", json!({"contents": "foreground"})).unwrap(); - } - } - } - s.execute("select.deselect", json!({})).unwrap(); - let st = s.active().unwrap(); - let before = st.doc.layers[0].surface().unwrap().rgba(0, 0); - assert!(before[0] < 0.01, "setup: (0,0) should be black, got {before:?}"); - s.execute("image.imageSize", json!({"width": 4, "height": 4, "resample": "nearest"})).unwrap(); - let st = s.active().unwrap(); - let surf = st.doc.layers[0].surface().unwrap(); - for (x, y) in [(0, 0), (1, 1), (2, 3)] { - let v = surf.rgba(x, y)[0]; - assert!(v.is_finite() && !(0.01..=0.99).contains(&v), "nearest produced an averaged value {v} at ({x},{y})"); - } - } - - #[test] - fn canvas_size_anchors_and_extends_background() { - let mut s = session(); - s.execute("image.canvasSize", json!({"width": 60, "height": 30, "anchor": "topLeft", "extensionColor": "#00ff00"})).unwrap(); - let d = doc(&s); - assert_eq!(d.size, Size::new(60, 30)); - assert_eq!(d.layers[1].surface().unwrap().content_bounds(), Rect::new(10, 5, 20, 15)); - let bg = d.layers[0].surface().unwrap(); - assert_eq!(bg.pixel(50, 25), vec![0.0, 1.0, 0.0, 1.0]); - assert_eq!(bg.pixel(5, 5), vec![1.0, 1.0, 1.0, 1.0]); - let mut s = session(); - s.execute("image.canvasSize", json!({"width": 20, "height": 10, "relative": true, "anchor": "center"})).unwrap(); - assert_eq!(doc(&s).layers[1].surface().unwrap().content_bounds(), Rect::new(20, 10, 30, 20)); - } - - #[test] - fn canvas_size_anchor_offsets_and_rejects_unlisted() { - // 64x48 -> 100x80: dx spans 36 and dy spans 32, so each anchor factor lands on a known - // offset. All nine documented values must anchor exactly where they do today (#2946). - let expected = [ - ("topLeft", [0, 0]), - ("top", [18, 0]), - ("topRight", [36, 0]), - ("left", [0, 16]), - ("center", [18, 16]), - ("right", [36, 16]), - ("bottomLeft", [0, 32]), - ("bottom", [18, 32]), - ("bottomRight", [36, 32]), - ]; - for (anchor, off) in expected { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 64, "height": 48, "background": "white"})).unwrap(); - let r = s.execute("image.canvasSize", json!({"width": 100, "height": 80, "anchor": anchor})).unwrap(); - assert_eq!(r["offset"], json!(off), "anchor {anchor}"); - } - // An omitted anchor still defaults to center. - let mut s = Session::new(); - s.execute("file.new", json!({"width": 64, "height": 48, "background": "white"})).unwrap(); - assert_eq!(s.execute("image.canvasSize", json!({"width": 100, "height": 80})).unwrap()["offset"], json!([18, 16])); - // A misspelling or unknown value is a BadParams error naming `anchor`, never an anchor - // between two of the nine (the old independent-axis matching produced top-centre etc.). - for anchor in ["topleft", "TopLeft", "TOPLEFT", "bottomleft", "bottomright", "middle", "", "NOPE"] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 64, "height": 48, "background": "white"})).unwrap(); - let err = s.execute("image.canvasSize", json!({"width": 100, "height": 80, "anchor": anchor})).unwrap_err(); - assert!(matches!(err, EngineError::BadParams { .. }), "anchor {anchor:?} must be rejected, got {err:?}"); - assert!(err.to_string().contains("anchor"), "the error for {anchor:?} must name `anchor`: {err}"); - } - } - - #[test] - fn crop_to_selection_and_trim() { - let mut s = session(); - assert!(s.execute("image.crop", json!({})).is_err(), "no selection, no rect"); - s.execute("select.rect", json!({"x": 5, "y": 2, "width": 20, "height": 10})).unwrap(); - s.execute("image.crop", json!({})).unwrap(); - let d = doc(&s); - assert_eq!(d.size, Size::new(20, 10)); - assert!(d.selection.is_none()); - assert_eq!(d.layers[1].surface().unwrap().content_bounds(), Rect::new(5, 3, 15, 10)); - // Trim transparent: hide the background, trim to the red square. - let mut s = session(); - s.execute("layer.setProps", json!({"layer": doc(&s).layers[0].id.0, "visible": false})).unwrap(); - s.execute("image.trim", json!({"basedOn": "transparent"})).unwrap(); - // The red square (10×10) plus its drop shadow (distance 5, size 5). - let size = doc(&s).size; - assert!(size.width > 10 && size.width < 30 && size.height > 10 && size.height < 25, "{size:?}"); - } - - #[test] - fn crop_to_explicit_rect_can_extend_canvas() { - let mut s = session(); - s.execute("image.crop", json!({"x": 10, "y": 5, "width": 10, "height": 10})).unwrap(); - assert_eq!(doc(&s).size, Size::new(10, 10)); - assert_eq!(doc(&s).layers[1].surface().unwrap().pixel(0, 0), vec![1.0, 0.0, 0.0, 1.0]); - let mut s = session(); - s.execute("image.crop", json!({"x": -10, "y": 0, "width": 60, "height": 20})).unwrap(); - assert_eq!(doc(&s).size, Size::new(60, 20)); - assert_eq!(doc(&s).layers[1].surface().unwrap().pixel(20, 5), vec![1.0, 0.0, 0.0, 1.0]); - } - - #[test] - fn crop_extension_fills_the_background_with_the_background_colour() { - let mut shrink = Session::new(); - shrink.execute("file.new", json!({"width": 16, "height": 16, "background": "#ff0000"})).unwrap(); - shrink.execute("image.crop", json!({"x": 2, "y": 0, "width": 12, "height": 16})).unwrap(); - let layer = &doc(&shrink).layers[0]; - assert_eq!(layer.name, "Background", "a shrink-only crop keeps the Background"); - assert!(layer.locks.transparency && layer.locks.position); - - let mut s = Session::new(); - s.execute("file.new", json!({"width": 16, "height": 16, "background": "#ff0000"})).unwrap(); - s.tools.background = [0.0, 1.0, 0.0, 1.0]; - s.execute("image.crop", json!({"x": -4, "y": 0, "width": 20, "height": 16})).unwrap(); - let layer = &doc(&s).layers[0]; - assert_eq!(layer.name, "Background", "an extending crop keeps the Background (#3081)"); - assert!(layer.locks.transparency && layer.locks.position); - assert_eq!(layer.surface().unwrap().rgba(1, 8), [0.0, 1.0, 0.0, 1.0], "the added border takes the background colour"); - assert_eq!(layer.surface().unwrap().rgba(8, 8), [1.0, 0.0, 0.0, 1.0], "the original pixels stay"); - - s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap(); - let layer = &doc(&s).layers[0]; - assert_eq!(layer.surface().unwrap().rgba(1, 8), [0.0, 0.0, 1.0, 1.0], "Fill paints the extended border"); - assert_eq!(layer.surface().unwrap().rgba(8, 8), [0.0, 0.0, 1.0, 1.0]); - - s.execute("edit.undo", json!({})).unwrap(); - s.execute("edit.undo", json!({})).unwrap(); - let layer = &doc(&s).layers[0]; - assert_eq!(doc(&s).size, Size::new(16, 16)); - assert_eq!(layer.surface().unwrap().rgba(8, 8), [1.0, 0.0, 0.0, 1.0]); - assert_eq!(layer.surface().unwrap().content_bounds(), Rect::new(0, 0, 16, 16), "undo removes the filled border"); - - // A normal layer gets transparent pixels in the added area. - let mut s = Session::new(); - s.execute("file.new", json!({"width": 16, "height": 16, "background": "#ff0000"})).unwrap(); - s.execute("layer.new.layerFromBackground", json!({})).unwrap(); - s.execute("image.crop", json!({"x": -4, "y": 0, "width": 20, "height": 16})).unwrap(); - assert_eq!(doc(&s).layers[0].surface().unwrap().rgba(1, 8), [0.0; 4]); - } - - /// Delete Cropped Pixels deletes pixel-layer data only: type and smart objects keep what lies - /// outside the frame, so moving them later doesn't show them cut at the old edge. - #[test] - fn delete_cropped_pixels_keeps_type_and_smart_objects_whole() { - let mut s = session(); - s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - s.execute("type.create", json!({"x": 10, "y": 15, "text": "Hi", "size": 12})).unwrap(); - let bounds = |s: &Session| -> Vec { doc(s).layers[1..].iter().map(|l| l.surface().unwrap().content_bounds()).collect() }; - let before = bounds(&s); - assert!(before.iter().all(|b| b.x0 < 15 && b.x1 > 15), "both cross the crop edge: {before:?}"); - s.execute("image.crop", json!({"x": 15, "y": 0, "width": 25, "height": 20})).unwrap(); - assert!(matches!(doc(&s).layers[1].content, LayerContent::Smart(_)) && matches!(doc(&s).layers[2].content, LayerContent::Text(_))); - assert_eq!(bounds(&s), before.iter().map(|b| b.translate(-15, 0)).collect::>()); - } - - /// A turned crop deleting pixels keeps type and smart objects whole too, also a smart object - /// whose source is unavailable (the rotation can't re-render it, so it keeps its cache): each - /// ends up exactly as the same turned crop with Delete Cropped Pixels off leaves it. - #[test] - fn turned_crop_deleting_pixels_keeps_type_and_smart_objects_whole() { - let [deleted, kept] = [true, false].map(|delete| { - let mut s = session(); - s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - s.edit("unlink", |doc, active| { - if let LayerContent::Smart(sm) = &mut doc.layer_mut(active.unwrap()).unwrap().content { - sm.source = photocraft_doc::SmartSource::Linked { path: "missing-photocraft-test-source.psd".into() }; - } - Ok(()) - }) - .unwrap(); - s.execute("type.create", json!({"x": 10, "y": 15, "text": "Hi", "size": 12})).unwrap(); - s.execute("image.crop", json!({"x": 20, "y": 0, "width": 20, "height": 20, "angle": 2.0, "deleteCroppedPixels": delete})).unwrap(); - s - }); - let (a, b) = (doc(&deleted), doc(&kept)); - assert!(matches!(a.layers[1].content, LayerContent::Smart(_)) && matches!(a.layers[2].content, LayerContent::Text(_))); - for i in [1, 2] { - let (sa, sb) = (a.layers[i].surface().unwrap(), b.layers[i].surface().unwrap()); - let r = sb.content_bounds(); - assert!(r.x0 < 0, "layer {i} reaches past the crop's left edge: {r:?}"); - assert_eq!(sa.content_bounds(), r, "layer {i}"); - assert_eq!(sa.read_region(r), sb.read_region(r), "layer {i}"); - } - } - - /// The Background keeps the pixels a crop with Delete Cropped Pixels off hid: extending the - /// canvas over them again (Reveal All, Canvas Size) shows them rather than painting them over - /// with the background colour (#7086). - #[test] - fn extending_the_canvas_keeps_the_backgrounds_hidden_pixels() { - for depth in [8, 16, 32] { - let hidden = |s: &mut Session| { - s.execute("file.new", json!({"width": 100, "height": 100, "depth": depth, "background": "white"})).unwrap(); - s.edit("paint", |doc, _| { - let bg = doc.background_mut().unwrap(); - bg.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 50, 100), &[1.0, 0.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - s.execute("image.crop", json!({"x": 50, "y": 0, "width": 50, "height": 100, "deleteCroppedPixels": false})).unwrap(); - s.tools.background = [0.0, 0.0, 0.0, 1.0]; - }; - let mut s = Session::new(); - hidden(&mut s); - s.execute("image.revealAll", json!({})).unwrap(); - let surf = doc(&s).background().unwrap().surface().unwrap(); - assert_eq!(doc(&s).size, Size::new(100, 100), "{depth}-bit"); - assert_eq!(surf.rgba(10, 50), [1.0, 0.0, 0.0, 1.0], "{depth}-bit: Reveal All shows the hidden red half"); - assert_eq!(surf.rgba(80, 50), [1.0, 1.0, 1.0, 1.0], "{depth}-bit"); - - // Canvas Size wider than the hidden pixels: they show, the rest takes the colour. - let mut s = Session::new(); - hidden(&mut s); - s.execute("image.canvasSize", json!({"width": 120, "height": 100, "anchor": "right"})).unwrap(); - let surf = doc(&s).background().unwrap().surface().unwrap(); - assert_eq!(surf.rgba(5, 50), [0.0, 0.0, 0.0, 1.0], "{depth}-bit: past the hidden pixels the background colour"); - assert_eq!(surf.rgba(30, 50), [1.0, 0.0, 0.0, 1.0], "{depth}-bit: Canvas Size shows the hidden red half"); - assert_eq!(surf.rgba(100, 50), [1.0, 1.0, 1.0, 1.0], "{depth}-bit"); - } - } - - /// A Background without an alpha channel (a Grayscale PSD import) has no hidden pixels to tell - /// from empty ones: the added area takes the colour, the kept area stays (#7086). - #[test] - fn an_alpha_less_background_extension_takes_the_colour() { - let mut surf = Surface::new(photocraft_color::PixelFormat::GRAY8); - surf.fill_rect(Rect::new(-50, 0, 100, 100), &[0.6]); - let kept = surf.pixel(50, 50); - fill_background_extension(&mut surf, Rect::new(-60, 0, 100, 100), Rect::new(0, 0, 100, 100), &[0.0]); - assert_eq!(surf.pixel(-55, 50), vec![0.0], "past the old pixels the colour"); - assert_eq!(surf.pixel(-30, 50), vec![0.0], "no alpha: the added area takes the colour"); - assert_eq!(surf.pixel(50, 50), kept, "the kept area is unchanged"); - } - - /// A document (`mode`, `depth`) with a white Background and a layer holding a red pixel at - /// (12, 8) and a blue one at (30, 3). - fn marked(mode: &str, depth: u32) -> Session { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 40, "height": 20, "mode": mode, "depth": depth, "background": "white"})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - for (x, y, c) in [(12, 8, "#ff0000"), (30, 3, "#0000ff")] { - s.execute("select.rect", json!({"x": x, "y": y, "width": 1, "height": 1})).unwrap(); - s.execute("edit.fill", json!({"color": c})).unwrap(); - } - s.execute("select.deselect", json!({})).unwrap(); - s - } - - fn layer_rgba(s: &Session, layer: usize, x: i32, y: i32) -> [f32; 4] { - doc(s).layers[layer].surface().unwrap().rgba(x, y) - } - - /// #1792: a frame turned 90° clockwise crops what Image Rotation › Arbitrary 90° CCW and a - /// plain crop give, in one undo step that restores the document, at 8, 16 and 32 bits. - #[test] - fn crop_at_90_degrees_is_rotate_then_crop_in_one_step() { - for depth in [8, 16, 32] { - let mut s = marked("rgb", depth); - let before = doc(&s).clone(); - let past = s.active().unwrap().history.past_len(); - // The 10 × 20 frame at (10, 0), turned 90° about (15, 10), covers x 5..25, y 5..15. - let r = s.execute("image.crop", json!({"x": 10, "y": 0, "width": 10, "height": 20, "angle": 90})).unwrap(); - assert_eq!(r["angle"], json!(90.0), "{depth}"); - assert_eq!(doc(&s).size, Size::new(10, 20), "{depth}"); - assert_eq!(s.active().unwrap().history.past_len(), past + 1, "{depth}: one undo step"); - // (12, 8) is 2.5 left of and 1.5 above the centre: in the upright frame, 1.5 left of - // and 2.5 below its centre (5, 10). - let red = layer_rgba(&s, 1, 3, 12); - assert!(red[0] > 0.9 && red[1] < 0.1 && red[3] > 0.9, "{depth}: {red:?}"); - let mut reference = marked("rgb", depth); - reference.execute("image.rotation.arbitrary", json!({"angle": 90, "direction": "ccw"})).unwrap(); - reference.execute("image.crop", json!({"x": 5, "y": 15, "width": 10, "height": 20})).unwrap(); - for l in 0..2 { - for y in 0..20 { - for x in 0..10 { - let (a, b) = (layer_rgba(&s, l, x, y), layer_rgba(&reference, l, x, y)); - // A fully transparent pixel's colour is invisible, and the turned crop - // doesn't turn the pixels it deletes, which the warp spreads colour from. - let n = if b[3] > 1e-3 { 4 } else { 1 }; - assert!(a.iter().rev().zip(b.iter().rev()).take(n).all(|(p, q)| (p - q).abs() < 1e-3), "{depth} layer {l} ({x}, {y}): {a:?} vs {b:?}"); - } - } - } - s.execute("edit.undo", json!({})).unwrap(); - let d = doc(&s); - assert_eq!(d.size, before.size, "{depth}"); - assert_eq!(d.depth, before.depth); - for y in 0..20 { - for x in 0..40 { - assert_eq!(layer_rgba(&s, 1, x, y), before.layers[1].surface().unwrap().rgba(x, y), "{depth} undo at ({x}, {y})"); - } - } - } - } - - /// A slightly turned frame keeps its own size, the pixel under its centre and the Background's - /// colour; the turn's sign matters (a counter-clockwise frame is a negative angle). - #[test] - fn crop_at_a_small_angle_keeps_the_frame_size_in_every_mode() { - for (mode, depth) in [("rgb", 8), ("rgb", 16), ("rgb", 32), ("grayscale", 16), ("cmyk", 8), ("lab", 16)] { - for angle in [5.0, -7.5, 365.0] { - let mut s = marked(mode, depth); - s.execute("image.crop", json!({"x": 2, "y": 1, "width": 21, "height": 15, "angle": angle})).unwrap(); - let d = doc(&s); - assert_eq!(d.size, Size::new(21, 15), "{mode} {depth} {angle}"); - assert_eq!(d.depth.bytes() * 8, depth as usize, "{mode} {depth}"); - assert_eq!(format!("{:?}", d.mode).to_lowercase(), mode, "{mode} {depth}"); - assert_eq!(d.layers.len(), 2); - // The frame's centre (12.5, 8.5) is the red pixel (the layer's only paint nearby); - // it stays at the centre, its colour kept. - let want = layer_rgba(&marked(mode, depth), 1, 12, 8); - let red = layer_rgba(&s, 1, 10, 7); - assert!(red[3] > 0.5 && (0..3).all(|c| (red[c] - want[c]).abs() < 0.2), "{mode} {depth} {angle}: {red:?} vs {want:?}"); - // The Background stays opaque white inside the canvas it came from. - let bg = layer_rgba(&s, 0, 10, 7); - assert!(bg.iter().all(|v| (v - 1.0).abs() < 0.02), "{mode} {depth} {angle}: {bg:?}"); - } - } - } - - /// A turned crop that deletes the cropped pixels turns only what lands in the frame; inside the - /// new canvas every layer, mask and channel is exactly what turning everything gives (the - /// frame spans several tiles, at several depths and angles). - #[test] - fn turned_crop_deleting_pixels_matches_turning_the_whole_canvas() { - use photocraft_color::PixelFormat; - let pixels = || (0..500).flat_map(|y| (0..700).map(move |x| (x, y))); - for depth in [8, 16, 32] { - for angle in [3.0, -7.5, 33.0, 181.0] { - let mut sessions = [true, false].map(|delete| { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 700, "height": 500, "depth": depth, "background": "white"})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.edit("paint", |doc, active| { - let wave = |x: i32, y: i32, k: i32| ((x * 7 + y * 13 + k * 31) % 97) as f32 / 96.0; - let all = Rect::new(0, 0, 700, 500); - let rgba: Vec = pixels().flat_map(|(x, y)| [wave(x, y, 0), wave(x, y, 1), wave(x, y, 2), wave(y, x, 3)]).collect(); - let gray: Vec = pixels().map(|(x, y)| wave(y, x, 4)).collect(); - let l = doc.layer_mut(active.unwrap()).unwrap(); - l.surface_mut().unwrap().write_region(all, &rgba); - let mut mask = photocraft_doc::LayerMask::reveal_all(); - mask.surface.write_region(all, &gray); - l.mask = Some(mask); - let bg = doc.background_mut().unwrap().surface_mut().unwrap(); - bg.write_region(all, &pixels().flat_map(|(x, y)| [wave(x, y, 5), wave(x, y, 6), wave(x, y, 7), 1.0]).collect::>()); - let fmt = PixelFormat::new(ColorMode::Grayscale, doc.pixel_format().sample, false); - let mut ch = Surface::new(fmt); - ch.write_region(all, &gray); - doc.channels.push(photocraft_doc::AlphaChannel::new("Alpha 1", ch)); - Ok(()) - }) - .unwrap(); - let p = json!({"x": 150, "y": 120, "width": 330, "height": 290, "angle": angle, "deleteCroppedPixels": delete}); - s.execute("image.crop", p).unwrap(); - s - }); - let [deleted, kept] = &mut sessions; - let (a, b) = (doc(deleted), doc(kept)); - assert_eq!(a.size, b.size, "{depth} {angle}"); - let canvas = a.bounds(); - for (la, lb) in a.layers.iter().zip(&b.layers) { - let (sa, sb) = (la.surface().unwrap(), lb.surface().unwrap()); - assert!(sa.to_interleaved(canvas) == sb.to_interleaved(canvas), "{depth} {angle}: layer {}", la.name); - if let (Some(ma), Some(mb)) = (&la.mask, &lb.mask) { - assert!(ma.surface.to_interleaved(canvas) == mb.surface.to_interleaved(canvas), "{depth} {angle}: mask of {}", la.name); - } - } - assert!(a.channels[0].surface.to_interleaved(canvas) == b.channels[0].surface.to_interleaved(canvas), "{depth} {angle}: alpha channel"); - // Deleting keeps nothing past the canvas. - let layer = a.layers[1].surface().unwrap(); - assert!(canvas.contains_rect(&layer.content_bounds()), "{depth} {angle}: {:?}", layer.content_bounds()); - } - } - } - - /// Angle 0 (or a whole turn) is the plain crop: no resampling, the same document. - #[test] - fn crop_at_angle_zero_is_the_plain_crop() { - let mut plain = marked("rgb", 16); - plain.execute("image.crop", json!({"x": 3, "y": 2, "width": 30, "height": 10})).unwrap(); - for angle in [json!(0), json!(0.0), json!(360), json!(-720), json!(null)] { - let mut s = marked("rgb", 16); - let r = s.execute("image.crop", json!({"x": 3, "y": 2, "width": 30, "height": 10, "angle": angle})).unwrap(); - assert!(r.get("angle").is_none(), "{angle}: {r}"); - assert_eq!(doc(&s).size, Size::new(30, 10)); - for l in 0..2 { - for y in 0..10 { - for x in 0..30 { - assert_eq!(layer_rgba(&s, l, x, y), layer_rgba(&plain, l, x, y), "{angle} layer {l} ({x}, {y})"); - } - } - } - } - } - - /// Bad angles fail cleanly, before anything changes. - #[test] - fn crop_angle_rejects_bad_values_without_changing_the_document() { - let bad = [ - json!({"x": 0, "y": 0, "width": 10, "height": 10, "angle": "NaN"}), - json!({"x": 0, "y": 0, "width": 10, "height": 10, "angle": "12"}), - json!({"x": 0, "y": 0, "width": 10, "height": 10, "angle": [1]}), - json!({"x": 0, "y": 0, "width": 10, "height": 10, "angle": true}), - json!({"x": 0, "y": 0, "width": 10, "height": 10, "angle": 1e308}), - json!({"x": 0, "y": 0, "width": 10, "height": 10, "angle": -3601}), - json!({"x": 0, "y": 0, "width": 10, "height": 10, "angle": f64::MAX}), - // An angle needs the frame: a selection crop has none. - json!({"angle": 10}), - json!({"x": 0, "y": 0, "width": 0, "height": 10, "angle": 10}), - json!({"x": 0, "y": 0, "width": 300_001, "height": 10, "angle": 10}), - json!({"x": i32::MAX - 5, "y": 0, "width": 10, "height": 10, "angle": 10}), - ]; - for p in bad { - let mut s = marked("rgb", 8); - s.execute("select.all", json!({})).unwrap(); - let before = doc(&s).clone(); - let past = s.active().unwrap().history.past_len(); - assert!(s.execute("image.crop", p.clone()).is_err(), "{p}"); - assert_eq!(doc(&s).size, before.size, "{p}"); - assert_eq!(s.active().unwrap().history.past_len(), past, "{p}"); - } - // Far-off but representable frames turn and crop without panicking. - for (x, y) in [(-1_000_000, 0), (0, 1_000_000), (i32::MIN / 4, i32::MAX / 4)] { - let mut s = marked("rgb", 8); - s.execute("image.crop", json!({"x": x, "y": y, "width": 4, "height": 3, "angle": 33.3})).unwrap(); - assert_eq!(doc(&s).size, Size::new(4, 3)); - } - } - - #[test] - fn crop_refuses_a_canvas_side_past_the_new_document_limit() { - // #960: an unbounded explicit crop left a canvas that a later Trim or Duplicate Merged - // could only abort on allocating. - for (w, h) in [(100_000_000, 100_000_000), (300_001, 10), (10, 300_001)] { - let mut s = session(); - let (size, past) = (doc(&s).size, s.active().unwrap().history.past_len()); - let err = s.execute("image.crop", json!({"x": 0, "y": 0, "width": w, "height": h})).unwrap_err(); - assert!(err.to_string().contains("300000 px limit"), "{w} x {h}: {err}"); - assert_eq!((doc(&s).size, s.active().unwrap().history.past_len()), (size, past), "{w} x {h}: nothing changed"); - } - // At the limit it still extends the canvas (the tiles stay lazy). - let mut s = session(); - s.execute("image.crop", json!({"x": 0, "y": 0, "width": 300_000, "height": 2})).unwrap(); - assert_eq!(doc(&s).size, Size::new(300_000, 2)); - } - - /// #2443: the Crop tool's W x H x Resolution crops, resamples the cropped area to exactly the - /// target size and sets the resolution, in one undo step, at 8 and 16 bits. - #[test] - fn crop_to_a_target_size_and_resolution_is_one_step() { - for depth in [8, 16] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 400, "height": 300, "resolution": 72, "depth": depth})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.edit("paint", |doc, active| { - doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(100, 100, 200, 225), &[1.0, 0.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - let past = s.active().unwrap().history.past_len(); - // 4 x 5 in at 300 ppi from a 100 x 125 px frame. - let r = s - .execute("image.crop", json!({"x": 100, "y": 100, "width": 100, "height": 125, "targetWidth": 1200, "targetHeight": 1500, "resolution": 300})) - .unwrap(); - assert_eq!((r["documentWidth"].as_u64(), r["documentHeight"].as_u64()), (Some(1200), Some(1500)), "{depth}: {r}"); - assert_eq!(r["resolution"].as_f64(), Some(300.0), "{depth}"); - let d = doc(&s); - assert_eq!(d.size, Size::new(1200, 1500), "{depth}"); - assert_eq!(d.resolution_dpi, 300.0, "{depth}"); - assert_eq!(d.layers[0].surface().unwrap().format().sample, if depth == 8 { SampleType::U8 } else { SampleType::U16 }); - // The red frame filled the crop; it fills the result. - let red = d.layers[1].surface().unwrap(); - for (x, y) in [(0, 0), (600, 750), (1199, 1499)] { - assert_eq!(red.pixel(x, y), vec![1.0, 0.0, 0.0, 1.0], "{depth}: ({x}, {y})"); - } - assert_eq!(s.active().unwrap().history.past_len(), past + 1, "{depth}: one history step"); - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!((doc(&s).size, doc(&s).resolution_dpi), (Size::new(400, 300), 72.0), "{depth}: undo restores the original"); - } - } - - #[test] - fn crop_target_resamples_after_a_turned_crop_and_resolution_alone_keeps_the_pixels() { - let mut s = session(); - let past = s.active().unwrap().history.past_len(); - s.execute("image.crop", json!({"x": 10, "y": 0, "width": 10, "height": 20, "angle": 90, "targetWidth": 30, "targetHeight": 60, "resample": "nearest"})) - .unwrap(); - assert_eq!(doc(&s).size, Size::new(30, 60)); - assert_eq!(s.active().unwrap().history.past_len(), past + 1, "rotate, crop and resample: one step"); - let mut s = session(); - s.execute("image.crop", json!({"x": 2, "y": 3, "width": 30, "height": 10, "resolution": 150})).unwrap(); - assert_eq!((doc(&s).size, doc(&s).resolution_dpi), (Size::new(30, 10), 150.0)); - } - - /// #7722: a W x H crop of an Indexed Color document resamples like Image Size (#6019), with - /// Nearest Neighbor, so no pixel gets a blend that isn't in the colour table. - #[test] - fn crop_target_resamples_indexed_color_with_nearest_neighbor() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 2, "height": 1})).unwrap(); - s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); - s.execute("select.rect", json!({"x": 1, "y": 0, "width": 1, "height": 1})).unwrap(); - s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap(); - s.execute("select.deselect", json!({})).unwrap(); - s.execute("image.mode.indexedColor", json!({})).unwrap(); - for resample in [None, Some("bicubic"), Some("automatic"), Some("bilinear"), Some("lanczos")] { - let mut p = json!({"x": 0, "y": 0, "width": 2, "height": 1, "targetWidth": 8, "targetHeight": 1}); - if let Some(r) = resample { - p["resample"] = json!(r); - } - s.execute("image.crop", p).unwrap(); - let surf = doc(&s).layers[0].surface().unwrap(); - for x in 0..8 { - let px = surf.pixel(x, 0); - assert!(px[..3] == [1.0, 0.0, 0.0] || px[..3] == [0.0, 0.0, 1.0], "{resample:?}: no blended colour at x {x}: {px:?}"); - } - s.execute("history.undo", json!({})).unwrap(); - } - } - - #[test] - fn crop_target_accepts_whole_number_floats() { - // `json.dumps(100.0)` and many other JSON writers send whole numbers as floats. - let mut s = session(); - s.execute("image.crop", json!({"x": 0, "y": 0, "width": 20, "height": 10, "targetWidth": 40.0, "targetHeight": 20.0})).unwrap(); - assert_eq!(doc(&s).size, Size::new(40, 20)); - } - - #[test] - fn crop_target_rejects_bad_params_without_changing_the_document() { - let rect = json!({"x": 0, "y": 0, "width": 10, "height": 10}); - let bad_params = [ - json!({"targetWidth": 100}), - json!({"targetHeight": 100}), - json!({"targetWidth": 0, "targetHeight": 10}), - json!({"targetWidth": -5, "targetHeight": 10}), - json!({"targetWidth": 10.5, "targetHeight": 10}), - json!({"targetWidth": -1.0, "targetHeight": 10}), - json!({"targetWidth": 0.0, "targetHeight": 10}), - json!({"targetWidth": 1e39, "targetHeight": 10}), - json!({"targetWidth": 300_001.0, "targetHeight": 10}), - json!({"targetWidth": "10", "targetHeight": 10}), - json!({"targetWidth": 300_001, "targetHeight": 10}), - json!({"targetWidth": 4_294_967_306_u64, "targetHeight": 10}), - json!({"targetWidth": 300_000, "targetHeight": 300_000}), - json!({"targetWidth": 10, "targetHeight": 10, "resample": "none"}), - json!({"targetWidth": 10, "targetHeight": 10, "resample": 3}), - json!({"resolution": 0}), - json!({"resolution": -72}), - json!({"resolution": 1e9}), - json!({"resolution": "300"}), - ]; - for extra in bad_params { - let mut s = session(); - let (size, dpi, past) = (doc(&s).size, doc(&s).resolution_dpi, s.active().unwrap().history.past_len()); - let mut p = rect.clone(); - if let (Some(o), Some(e)) = (p.as_object_mut(), extra.as_object()) { - o.extend(e.clone()); - } - assert!(s.execute("image.crop", p.clone()).is_err(), "{p}"); - assert_eq!((doc(&s).size, doc(&s).resolution_dpi, s.active().unwrap().history.past_len()), (size, dpi, past), "{p}: nothing changed"); - } - } - - #[test] - fn trim_based_on_top_left_colour() { - let mut s = session(); - s.edit("no fx", |doc, _| { - doc.layers[1].effects.items.clear(); - Ok(()) - }) - .unwrap(); - s.execute("image.trim", json!({"basedOn": "topLeft"})).unwrap(); - assert_eq!(doc(&s).size, Size::new(10, 10)); - } - - #[test] - fn thirty_two_bit_holds_linear_light() { - // Photoshop 27.11: an 8-bit sRGB grey 128 becomes 0.2159 in 32 bits (and 32 → 0.0144), - // and comes back unchanged; alpha keeps its value. - let mut s = Session::new(); - s.execute("file.new", json!({"width": 4, "height": 1, "background": "white"})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.edit("paint", |doc, active| { - let l = doc.layer_mut(active.unwrap()).unwrap(); - l.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 2, 1), &[128.0 / 255.0, 32.0 / 255.0, 1.0, 0.5]); - Ok(()) - }) - .unwrap(); - s.execute("image.mode.bits32", json!({})).unwrap(); - let px = doc(&s).layers[1].surface().unwrap().pixel(0, 0); - for (got, want) in px.iter().zip([0.2159, 0.0144, 1.0, 128.0 / 255.0]) { - assert!((got - want).abs() < 2e-4, "{px:?}"); - } - s.execute("image.mode.bits8", json!({})).unwrap(); - let px = doc(&s).layers[1].surface().unwrap().pixel(0, 0); - for (got, want) in px.iter().zip([128.0 / 255.0, 32.0 / 255.0, 1.0, 128.0 / 255.0]) { - assert!((got - want).abs() < 0.6 / 255.0, "{px:?}"); - } - } - - #[test] - fn grayscale_conversion_matches_photoshop() { - // Photoshop 27.11, default Color Settings (working gray Dot Gain 20 %): Image > Mode > - // Grayscale turns sRGB 64 / 128 / 192 grey and pure red into 46 / 105 / 177 / 107. - let mut s = Session::new(); - s.execute("file.new", json!({"width": 4, "height": 1, "background": "white"})).unwrap(); - s.edit("paint", |doc, _| { - let l = doc.layers.first_mut().unwrap(); - let surf = l.surface_mut().unwrap(); - for (x, c) in [[64.0, 64.0, 64.0], [128.0, 128.0, 128.0], [192.0, 192.0, 192.0], [255.0, 0.0, 0.0]].iter().enumerate() { - surf.fill_rect(Rect::new(x as i32, 0, x as i32 + 1, 1), &[c[0] / 255.0, c[1] / 255.0, c[2] / 255.0, 1.0]); - } - Ok(()) - }) - .unwrap(); - s.execute("image.mode.grayscale", json!({})).unwrap(); - let surf = doc(&s).layers[0].surface().unwrap(); - for (x, want) in [46.0, 105.0, 177.0, 107.0].iter().enumerate() { - let got = surf.pixel(x as i32, 0)[0] * 255.0; - assert!((got - want).abs() <= 1.5, "pixel {x}: {got} vs {want}"); - } - } - - #[test] - fn mode_and_depth_conversions() { - let mut s = session(); - s.execute("image.mode.grayscale", json!({})).unwrap(); - assert_eq!(doc(&s).mode, ColorMode::Grayscale); - assert_eq!(doc(&s).layers[1].surface().unwrap().format().mode, ColorMode::Grayscale); - s.execute("image.mode.bits16", json!({})).unwrap(); - assert_eq!(doc(&s).depth, SampleType::U16); - assert_eq!(doc(&s).layers[1].surface().unwrap().format().sample, SampleType::U16); - assert_eq!(doc(&s).layers[1].mask.as_ref().unwrap().surface.format().sample, SampleType::U16); - s.execute("image.mode.cmyk", json!({})).unwrap(); - s.execute("image.mode.bits32", json!({})).unwrap(); - s.execute("image.mode.lab", json!({})).unwrap(); - s.execute("image.mode.rgb", json!({})).unwrap(); - s.execute("image.mode.bits8", json!({})).unwrap(); - let d = doc(&s); - assert_eq!((d.mode, d.depth), (ColorMode::Rgb, SampleType::U8)); - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(doc(&s).depth, SampleType::F32); - let revision = s.active().unwrap().revision; - s.execute("image.mode.bits32", json!({})).unwrap(); - assert_eq!(s.active().unwrap().revision, revision, "an unchanged bit depth must preserve the history branch"); - assert!(s.redo(), "selecting the current depth must not discard the undone conversion"); - assert_eq!(doc(&s).depth, SampleType::U8); - } - - /// Duplicate › Merged Layers Only gives one locked Background when the source has one and a - /// plain "Layer 1" (keeping transparency) when it doesn't, as Photoshop does. - #[test] - fn merged_duplicate_is_a_background_only_when_the_source_has_one() { - let mut s = session(); - s.execute("image.duplicate", json!({"mergedOnly": true})).unwrap(); - let d = doc(&s); - assert!(d.is_background(d.layers[0].id), "source has a Background: the merged copy is one"); - let mut s = Session::new(); - s.execute("file.new", json!({"width": 8, "height": 8, "background": "transparent"})).unwrap(); - s.execute("image.duplicate", json!({"mergedOnly": true})).unwrap(); - let d = doc(&s); - assert!(d.background().is_none(), "transparent source: no Background in the copy"); - assert_eq!(d.layers[0].name, "Layer 1"); - } - - #[test] - fn duplicate_document() { - let mut s = session(); - let r = s.execute("image.duplicate", json!({"mergedOnly": true})).unwrap(); - assert_eq!(r["document"], json!(1)); - assert_eq!(s.documents().len(), 2); - assert_eq!(doc(&s).layers.len(), 1); - assert!(doc(&s).name.ends_with("copy")); - } -} diff --git a/crates/engine/src/jobs.rs b/crates/engine/src/jobs.rs index ffa4db96cb..6799640bad 100644 --- a/crates/engine/src/jobs.rs +++ b/crates/engine/src/jobs.rs @@ -1109,7 +1109,6 @@ pub fn specs() -> Vec { } #[cfg(test)] -#[path = "jobs_tests.rs"] mod tests; #[cfg(test)] diff --git a/crates/engine/src/jobs_tests.rs b/crates/engine/src/jobs/tests.rs similarity index 100% rename from crates/engine/src/jobs_tests.rs rename to crates/engine/src/jobs/tests.rs diff --git a/crates/engine/src/layer_multi_cmds.rs b/crates/engine/src/layer_multi_cmds.rs deleted file mode 100644 index 47114f7e5d..0000000000 --- a/crates/engine/src/layer_multi_cmds.rs +++ /dev/null @@ -1,3511 +0,0 @@ -//! Multi-layer selection and the commands that act on it: ⌘/⇧-click selection, Select › All / -//! Deselect / Find Layers, Layer › Align and Distribute, Link Layers, Merge Layers, Group from -//! Layers, Arrange › Reverse, Lock Layers and Rename Layer. -//! -//! The selection itself lives in [`DocState::selected_layers`] (UI state, like the active layer): -//! changing it never adds a history step. Every structural change below is one history step. - -use photocraft_color::PixelFormat; -use photocraft_doc::{Document, Layer, LayerContent, LayerId, VideoData}; -use photocraft_geom::Rect; -use serde_json::{Value, json}; - -use crate::commands::{CommandSpec, int_i32}; -use crate::{DocState, EngineError, Result, Session}; - -// ---------- selection state ---------- - -fn doc_state(s: &Session) -> std::result::Result<&DocState, String> { - s.active().ok_or_else(|| "no document open".into()) -} - -/// Selected layers of the active document, bottom-to-top. -pub fn selected(s: &Session) -> Vec { - s.active().map(DocState::selected_layers).unwrap_or_default() -} - -/// The layers a layer command acts on: the `layer` param when given, else every selected layer -/// (bottom-to-top), else the active layer. A single layer behaves exactly as before. -pub(crate) fn targets(s: &Session, p: &serde_json::Value) -> Result> { - if p.get("layer").is_some() { - return Ok(vec![crate::commands::layer_param(s, p)?]); - } - match selected(s) { - sel if sel.is_empty() => Ok(vec![crate::commands::layer_param(s, p)?]), - sel => Ok(sel), - } -} - -/// [`targets`] for a command that adds a layer mask: with several layers selected, those that can -/// take one (no layer mask yet, not the Background); one layer is taken as given. -pub(crate) fn mask_targets(s: &Session, p: &serde_json::Value) -> Result> { - let ids = targets(s, p)?; - if ids.len() < 2 { - return Ok(ids); - } - let d = s.active().ok_or(EngineError::NoDocument)?; - let ids: Vec = ids.into_iter().filter(|id| d.doc.layer(*id).is_some_and(|l| l.mask.is_none() && !d.doc.is_background(l.id))).collect(); - if ids.is_empty() { - return Err(EngineError::Other("none of the selected layers can take a layer mask".into())); - } - Ok(ids) -} - -/// Ids in `ids` that have no ancestor also in `ids` (a selected group already carries its -/// selected children), bottom-to-top. -pub(crate) fn top_level(doc: &Document, ids: &[LayerId]) -> Vec { - let walk = doc.walk(); - let paths: Vec<_> = walk.iter().filter(|(_, _, l)| ids.contains(&l.id)).map(|(p, _, l)| (p.clone(), l.id)).collect(); - paths.iter().filter(|(p, _)| !paths.iter().any(|(q, _)| q.len() < p.len() && p.starts_with(q))).map(|(_, id)| *id).collect() -} - -/// Replace the layer selection without a history step (like [`Session::select_layer`]). -pub fn set_selection(s: &mut Session, ids: Vec, active: Option, anchor: Option) -> Result<()> { - let st = s.active_mut().ok_or(EngineError::NoDocument)?; - if let Some(bad) = ids.iter().chain(active.iter()).find(|id| st.doc.layer(**id).is_none()) { - return Err(EngineError::NoLayer(*bad)); - } - let active = active.or_else(|| ids.last().copied()); - st.selected_layers = ids; - if let Some(a) = active - && !st.selected_layers.contains(&a) - { - st.selected_layers.push(a); - } - st.active_layer = active; - st.layer_anchor = anchor.or(active); - crate::fix_selection(st); - // Selecting layers is not an edit: keep a clean document clean. - let clean = st.saved_revision == st.revision; - st.revision += 1; - if clean { - st.saved_revision = st.revision; - } - st.last_damage = Some(Rect::EMPTY); - Ok(()) -} - -/// After a structural edit, make `ids` the selection (dropping any that no longer exist), which -/// is also what the edit's history state targets. -pub(crate) fn reselect(s: &mut Session, ids: Vec, active: Option) { - if let Some(st) = s.active_mut() { - st.selected_layers = ids; - if let Some(a) = active { - st.active_layer = Some(a); - st.layer_anchor = Some(a); - } - crate::fix_selection(st); - let layers = st.layer_target(); - st.history.set_current_layers(layers); - } -} - -/// Capture a selection target while its name is still known. Later renames/deletions must not -/// change an earlier recorded selection. Direct, non-recording calls retain their numeric IDs. -pub(crate) fn recorded_selection(s: &Session, mut p: Value) -> Value { - let Some(id) = p.get("layer").and_then(Value::as_u64).map(LayerId) else { return p }; - let Some(st) = s.active() else { return p }; - let Some(layer) = st.doc.layer(id) else { return p }; - let matches: Vec<_> = st.doc.walk().into_iter().filter(|(_, _, l)| l.name == layer.name).map(|(_, _, l)| l.id).collect(); - let Some(occurrence) = matches.iter().position(|candidate| *candidate == id) else { return p }; - if let Some(fields) = p.as_object_mut() { - fields.remove("layer"); - fields.insert("name".into(), json!(layer.name)); - if matches.len() > 1 { - fields.insert("occurrence".into(), json!(occurrence)); - } - } - p -} - -/// The layers named `name`, in document order, other than the ones being moved and (groups) their -/// contents. Moving layers never changes the others' order, so an occurrence counted among these -/// means the same layer before the move (when an action replays it) and after it (when the step -/// is recorded). -fn same_named_targets(doc: &photocraft_doc::Document, name: &str, moved: &[LayerId]) -> Vec { - fn subtree(l: &Layer, out: &mut Vec, depth: usize) { - out.push(l.id); - if depth < 256 - && let Some(children) = l.children() - { - children.iter().for_each(|c| subtree(c, out, depth + 1)); - } - } - let mut skip = Vec::new(); - for l in moved.iter().filter_map(|id| doc.layer(*id)) { - subtree(l, &mut skip, 0); - } - doc.walk().into_iter().filter(|(_, _, l)| l.name == name && !skip.contains(&l.id)).map(|(_, _, l)| l.id).collect() -} - -/// A Layers-panel drag of the selected layer records its drop target by name (and which of -/// several same-named layers it is), as [`recorded_selection`] does: the id means nothing in the -/// document the action plays in later, so playback failed with "no such layer" (#7845). Drags of -/// several layers, or of a layer that isn't the selected one, keep their ids. -fn recorded_move(s: &Session, mut p: Value, pre_selected: Option<&[LayerId]>) -> Value { - if p.get("layers").is_some() { - return p; - } - let Some(st) = s.active() else { return p }; - let moved = match p.get("layer") { - None => st.active_layer, - Some(v) => match v.as_u64().map(LayerId) { - Some(id) if pre_selected.map_or_else(|| st.selected_layers().as_slice() == [id], |sel| sel == [id]) => Some(id), - _ => return p, - }, - }; - if let Some(fields) = p.as_object_mut() { - fields.remove("layer"); - } - let Some(id) = p.get("target").and_then(Value::as_u64).map(LayerId) else { return p }; - let Some(layer) = st.doc.layer(id) else { return p }; - // A copy leaves its source where it is (it may even land beside it), so the source stays a - // candidate; the new copy (the active layer once the step has run, which is when it is - // recorded) is left out instead, as it doesn't exist yet when the step replays. - let copy = p.get("copy").and_then(Value::as_bool).unwrap_or(false); - let skip = if copy { st.active_layer.filter(|a| Some(*a) != moved) } else { moved }; - let matches = same_named_targets(&st.doc, &layer.name, skip.as_slice()); - let Some(occurrence) = matches.iter().position(|candidate| *candidate == id) else { return p }; - if let Some(fields) = p.as_object_mut() { - fields.insert("target".into(), json!(layer.name)); - if matches.len() > 1 { - fields.insert("targetOccurrence".into(), json!(occurrence)); - } - } - p -} - -/// `layer.moveTo`'s drop target: an id, or a name with `targetOccurrence` choosing among layers -/// that share it (in document order, the `moved` layers aside; required when several do). -fn move_target(s: &Session, p: &Value, moved: &[LayerId]) -> Result { - const CMD: &str = "layer.moveTo"; - match p.get("target") { - Some(Value::String(name)) => { - let occurrence = p - .get("targetOccurrence") - .map(|v| v.as_u64().and_then(|n| usize::try_from(n).ok()).ok_or_else(|| bad(CMD, "`targetOccurrence` must be a non-negative integer"))) - .transpose()?; - let st = s.active().ok_or(EngineError::NoDocument)?; - let matches = same_named_targets(&st.doc, name, moved); - if matches.len() > 1 && occurrence.is_none() { - return Err(bad(CMD, format!("multiple layers named `{name}`; specify `targetOccurrence`"))); - } - let index = occurrence.unwrap_or(0); - matches.get(index).copied().ok_or_else(|| bad(CMD, format!("no layer named `{name}` at occurrence {index}"))) - } - Some(v) => v.as_u64().map(LayerId).ok_or_else(|| bad(CMD, "`target` must be a layer id or name")), - None => Err(bad(CMD, "missing `target`")), - } -} - -/// Normalise parameters when recording an action step. -/// -/// For `layer.select`, captures the layer by name. For other commands, if a numeric `layer` -/// parameter references the document's sole selected layer, normalises it to the target form -/// (omitting `layer`) so that the recorded step applies to whatever layer is targeted when -/// replayed or exported to `.atn` (#7248). -pub(crate) fn recorded_step(s: &Session, id: &str, p: Value, pre_selected: Option<&[LayerId]>) -> Value { - if id == "layer.select" { - return recorded_selection(s, p); - } - if id == "layer.moveTo" { - return recorded_move(s, p, pre_selected); - } - let Some(layer_id) = p.get("layer").and_then(Value::as_u64).map(LayerId) else { return p }; - let is_sole_selected = match pre_selected { - Some(sel) => sel == [layer_id], - None => s.active().is_some_and(|st| st.selected_layers().as_slice() == [layer_id]), - }; - if is_sole_selected { - let mut p = p; - if let Some(fields) = p.as_object_mut() { - fields.remove("layer"); - } - return p; - } - p -} - -fn selection_target(s: &Session, p: &Value) -> Result { - let Some(name) = p.get("name") else { - if p.get("occurrence").is_some() { - return Err(bad("layer.select", "`occurrence` requires `name`")); - } - return crate::commands::explicit_layer(s, p)?.ok_or_else(|| bad("layer.select", "needs `layer` or `name`")); - }; - if p.get("layer").is_some() { - return Err(bad("layer.select", "use either `layer` or `name`, not both")); - } - let name = name.as_str().ok_or_else(|| bad("layer.select", "`name` must be a string"))?; - let occurrence = p - .get("occurrence") - .map(|v| v.as_u64().and_then(|n| usize::try_from(n).ok()).ok_or_else(|| bad("layer.select", "`occurrence` must be a non-negative integer"))) - .transpose()?; - let st = s.active().ok_or(EngineError::NoDocument)?; - let matches: Vec<_> = st.doc.walk().into_iter().filter(|(_, _, l)| l.name == name).map(|(_, _, l)| l.id).collect(); - if matches.len() > 1 && occurrence.is_none() { - return Err(bad("layer.select", format!("multiple layers named `{name}`; specify `occurrence`"))); - } - let index = occurrence.unwrap_or(0); - matches.get(index).copied().ok_or_else(|| bad("layer.select", format!("no layer named `{name}` at occurrence {index}"))) -} - -/// Layer rows follow the Layers panel's visual order, not Document::walk's storage order. -/// Closed groups hide their children unless both endpoints were selected programmatically. -fn range_order(layers: &[Layer], include_collapsed: bool, out: &mut Vec) { - for layer in layers.iter().rev() { - out.push(layer.id); - if let LayerContent::Group(group) = &layer.content - && (group.expanded || include_collapsed) - { - range_order(&group.children, include_collapsed, out); - } - } -} - -/// `layer.select`: `{"layer": id, "mode": "replace|toggle|range|add|remove"}`. -pub fn select(s: &mut Session, p: &Value) -> Result { - let id = selection_target(s, p)?; - let mode = p.get("mode").and_then(Value::as_str).unwrap_or("replace"); - let st = s.active().ok_or(EngineError::NoDocument)?; - if st.doc.layer(id).is_none() { - return Err(EngineError::NoLayer(id)); - } - let mut sel = st.selected_layers(); - match mode { - "replace" => s.select_layer(id)?, - "add" => { - if !sel.contains(&id) { - sel.push(id); - } - set_selection(s, sel, Some(id), Some(id))?; - } - "toggle" => { - if sel.contains(&id) { - if sel.len() == 1 { - // Photoshop keeps at least the clicked layer targeted. - return Ok(json!({"selected": [id.0]})); - } - sel.retain(|x| *x != id); - let active = if st.active_layer == Some(id) { sel.last().copied() } else { st.active_layer }; - set_selection(s, sel, active, active)?; - } else { - sel.push(id); - set_selection(s, sel, Some(id), Some(id))?; - } - } - // Toggle's removing half: a layer that isn't selected stays unselected (Photoshop's - // `removeFromSelection`, recorded by actions). - "remove" => { - if sel.contains(&id) && sel.len() > 1 { - sel.retain(|x| *x != id); - let active = if st.active_layer == Some(id) { sel.last().copied() } else { st.active_layer }; - set_selection(s, sel, active, active)?; - } - } - "range" => { - let anchor = st.layer_anchor.filter(|a| st.doc.layer(*a).is_some()).or(st.active_layer).unwrap_or(id); - let mut order = Vec::new(); - range_order(&st.doc.layers, false, &mut order); - // Engine clients may target a child of a collapsed group that the panel cannot - // click. Retain that capability by using expanded visual order for such calls. - if !order.contains(&anchor) || !order.contains(&id) { - order.clear(); - range_order(&st.doc.layers, true, &mut order); - } - let (a, b) = (order.iter().position(|x| *x == anchor).unwrap_or(0), order.iter().position(|x| *x == id).unwrap_or(0)); - let range = order[a.min(b)..=a.max(b)].to_vec(); - set_selection(s, range, Some(id), Some(anchor))?; - } - other => return Err(bad("layer.select", format!("unknown mode `{other}`"))), - } - Ok(json!({"selected": selected(s).iter().map(|l| l.0).collect::>()})) -} - -fn select_all_layers(s: &mut Session) -> Result { - let d = s.active().ok_or(EngineError::NoDocument)?; - let ids: Vec = d.doc.walk().into_iter().filter(|(_, _, l)| !d.doc.is_background(l.id)).map(|(_, _, l)| l.id).collect(); - if ids.is_empty() { - return Err(EngineError::Other("there are no layers to select".into())); - } - let active = d.active_layer.filter(|a| ids.contains(a)).or(ids.last().copied()); - let n = ids.len(); - set_selection(s, ids, active, None)?; - Ok(json!({"selected": n})) -} - -fn find_layers(s: &mut Session, p: &Value) -> Result { - let needle = p.get("name").and_then(Value::as_str).ok_or_else(|| bad("select.findLayers", "missing `name`"))?.to_lowercase(); - let d = s.active().ok_or(EngineError::NoDocument)?; - let ids: Vec = d.doc.walk().into_iter().filter(|(_, _, l)| l.name.to_lowercase().contains(&needle)).map(|(_, _, l)| l.id).collect(); - if ids.is_empty() { - return Err(EngineError::Other(format!("no layer name contains \"{needle}\""))); - } - let out = ids.iter().map(|l| l.0).collect::>(); - set_selection(s, ids, None, None)?; - Ok(json!({"selected": out})) -} - -fn select_linked(s: &mut Session) -> Result { - let d = s.active().ok_or(EngineError::NoDocument)?; - let groups = link_groups(&d.doc, &d.selected_layers()); - let ids: Vec = d.doc.walk().into_iter().filter(|(_, _, l)| l.link_group.is_some_and(|g| groups.contains(&g))).map(|(_, _, l)| l.id).collect(); - let active = d.active_layer.filter(|a| ids.contains(a)).or(ids.last().copied()); - let n = ids.len(); - set_selection(s, ids, active, active)?; - Ok(json!({"selected": n})) -} - -// ---------- enabled predicates ---------- - -fn has_layer(s: &Session) -> std::result::Result<(), String> { - if selected(s).is_empty() { Err("no layer selected".into()) } else { Ok(()) } -} -fn has_doc(s: &Session) -> std::result::Result<(), String> { - doc_state(s).map(|_| ()) -} -fn two_plus(s: &Session) -> std::result::Result<(), String> { - if selected(s).len() >= 2 { Ok(()) } else { Err("select two or more layers".into()) } -} -fn can_align(s: &Session) -> std::result::Result<(), String> { - let d = doc_state(s)?; - match d.selected_layers().len() { - 0 => Err("no layer selected".into()), - // Photoshop aligns to an active selection however many layers are selected; without one, - // a single layer aligns to the canvas and 2+ align to each other. - _ => Ok(()), - } -} -fn can_distribute(s: &Session) -> std::result::Result<(), String> { - if selected(s).len() >= 3 { Ok(()) } else { Err("select three or more layers to distribute".into()) } -} -fn can_link(s: &Session) -> std::result::Result<(), String> { - let d = doc_state(s)?; - let sel = d.selected_layers(); - match sel.len() { - 0 => Err("no layer selected".into()), - 1 if d.doc.layer(sel[0]).is_none_or(|l| l.link_group.is_none()) => Err("select two or more layers to link".into()), - _ => Ok(()), - } -} -fn has_linked(s: &Session) -> std::result::Result<(), String> { - let d = doc_state(s)?; - if link_groups(&d.doc, &d.selected_layers()).is_empty() { Err("the selected layers are not linked".into()) } else { Ok(()) } -} - -fn bad(cmd: &str, msg: impl Into) -> EngineError { - EngineError::BadParams { cmd: cmd.into(), msg: msg.into() } -} - -// ---------- moving layers ---------- - -fn link_groups(doc: &Document, ids: &[LayerId]) -> Vec { - let mut g: Vec = ids.iter().filter_map(|id| doc.layer(*id)?.link_group).collect(); - g.sort_unstable(); - g.dedup(); - g -} - -/// `ids` plus every layer linked to one of them. -pub(crate) fn with_links(doc: &Document, ids: &[LayerId]) -> Vec { - let groups = link_groups(doc, ids); - let mut out = ids.to_vec(); - if !groups.is_empty() { - for (_, _, l) in doc.walk() { - if l.link_group.is_some_and(|g| groups.contains(&g)) && !out.contains(&l.id) { - out.push(l.id); - } - } - } - out -} - -/// Move layers by whole pixels the way the Move tool does: pixels, linked masks, type and -/// vector content (shapes, linked vector masks) all move together. `before` is `doc` as it was -/// before any of the moves (the edit's starting document), read when type and shapes re-render. -pub(crate) fn move_layers(doc: &mut Document, before: &Document, moves: &[(LayerId, i32, i32)]) -> Result<()> { - for &(id, dx, dy) in moves { - if dx == 0 && dy == 0 { - continue; - } - let locks = doc.effective_locks(id); - let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; - if locks.position || locks.all { - return Err(EngineError::Other(format!("layer \"{}\" is position-locked", l.name))); - } - crate::commands::translate_layer(before, l, dx, dy); - crate::vector_cmds::translate_vectors(before, l, dx as f64, dy as f64); - } - Ok(()) -} - -/// Does a move aimed at the layer mask (`"target":"mask"`) move `l`'s mask alone? Only an -/// unlinked mask does (the chain off); a linked one moves with its layer, as in Photoshop. -pub fn moves_mask_alone(l: &Layer) -> bool { - l.mask.as_ref().is_some_and(|m| !m.linked) -} - -/// `layer.translate`: the explicit layer, or every selected layer, plus their linked layers. -/// With `"target":"mask"` a layer whose mask is unlinked moves that mask alone. -pub fn translate(s: &mut Session, p: &Value) -> Result { - let (dx, dy) = match p.get("units").and_then(Value::as_str) { - None | Some("px") => (int_i32("layer.translate", p, "dx")?.unwrap_or(0), int_i32("layer.translate", p, "dy")?.unwrap_or(0)), - // Points (1/72 in), as a Photoshop action records a nudge: whole pixels at this - // document's resolution. - Some("pt") => { - let dpi = s.active().map_or(72.0, |d| f64::from(d.doc.resolution_dpi)); - let to_px = |key: &str| -> Result { - let pt = match p.get(key) { - None => 0.0, - Some(v) => v.as_f64().filter(|f| f.is_finite()).ok_or_else(|| bad("layer.translate", format!("`{key}` must be a number")))?, - }; - let px = (pt * dpi / 72.0).round(); - if px.abs() > f64::from(i32::MAX) { - return Err(bad("layer.translate", format!("`{key}` = {pt} pt is outside the 32-bit coordinate range"))); - } - Ok(px as i32) - }; - (to_px("dx")?, to_px("dy")?) - } - Some(other) => return Err(bad("layer.translate", format!("unknown units `{other}` (px|pt)"))), - }; - let carry = match p.get("selection") { - None | Some(Value::Null) => false, - Some(v) => v.as_bool().ok_or_else(|| bad("layer.translate", "`selection` must be a boolean"))?, - }; - if dx == 0 && dy == 0 { - return Ok(Value::Null); - } - let roots = match crate::commands::explicit_layer(s, p)? { - Some(id) => vec![id], - None => selected(s), - }; - if roots.is_empty() { - return Err(EngineError::Other("no active layer".into())); - } - let mask_target = p.get("target").and_then(Value::as_str) == Some("mask"); - let before = s.active().ok_or(EngineError::NoDocument)?.doc.clone(); - let ids = s.edit("Move", |doc, _| { - let (alone, rest): (Vec, Vec) = roots.iter().partition(|id| mask_target && doc.layer(**id).is_some_and(moves_mask_alone)); - let mut ids = move_targets(doc, &rest); - if ids.is_empty() && alone.is_empty() { - return Err(EngineError::NoLayer(roots[0])); - } - let moves: Vec<_> = ids.iter().map(|&id| (id, dx, dy)).collect(); - move_layers(doc, &before, &moves)?; - for id in alone { - let locks = doc.effective_locks(id); - let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; - if locks.position || locks.all { - return Err(EngineError::Other(format!("layer \"{}\" is position-locked", l.name))); - } - if let Some(m) = &mut l.mask { - m.surface = shift_surface(&m.surface, dx, dy); - } - ids.push(id); - } - // A board moved past any canvas edge grows the canvas, as a new one does (#1531, #3070). - if ids.iter().any(|id| doc.layer(*id).is_some_and(|l| l.artboard().is_some())) { - crate::artboard_cmds::fit_canvas(doc); - } - // The Move tool carries the selection along when it moves several layers whole, as - // Photoshop does (#7538): one step, so Undo takes both back. - if carry { - doc.selection = doc.selection.as_ref().map(|sel| shift_surface(sel, dx, dy)); - } - Ok(ids) - })?; - note_damage(s, &before, &ids); - Ok(Value::Null) -} - -/// The layers a move of `roots` takes along: their linked layers, without layers whose group -/// is also moving (the group carries them). -pub fn move_targets(doc: &Document, roots: &[LayerId]) -> Vec { - top_level(doc, &with_links(doc, roots)) -} - -/// `doc` with the layers `ids` ([`move_targets`]) moved by whole pixels, as `layer.translate` -/// leaves them: the Move tool's live preview while it drags. Type, shape and smart-object pixels -/// shift as they are instead of re-rendering (the commit re-renders them), so a drag frame costs -/// copying the moving pixels only. -pub fn moved(doc: &Document, ids: &[LayerId], dx: i32, dy: i32) -> Result { - moved_target(doc, ids, dx, dy, false) -} - -/// [`moved`] for a drag aimed at the layer mask (`mask_target`): unlinked masks move alone. -pub fn moved_target(doc: &Document, ids: &[LayerId], dx: i32, dy: i32, mask_target: bool) -> Result { - let mut out = doc.clone(); - for &id in ids { - let locks = doc.effective_locks(id); - let l = out.layer_mut(id).ok_or(EngineError::NoLayer(id))?; - if locks.position || locks.all { - return Err(EngineError::Other(format!("layer \"{}\" is position-locked", l.name))); - } - if mask_target && moves_mask_alone(l) { - if let Some(m) = &mut l.mask { - m.surface = shift_surface(&m.surface, dx, dy); - } - continue; - } - shift_shown(doc, l, dx, dy); - } - Ok(out) -} - -/// `photocraft_algo::resample::translate_surface` with the content scan cached per tile (a Move -/// drag shifts the same layers every frame; scanning them each time cost more than the copy). -pub(crate) fn shift_surface(s: &photocraft_raster::Surface, dx: i32, dy: i32) -> photocraft_raster::Surface { - s.translated(dx, dy, photocraft_compose::bounds::content_bounds(s)) -} - -/// [`crate::commands::translate_layer`] plus the vector side, without re-rendering anything. -fn shift_shown(doc: &Document, l: &mut Layer, dx: i32, dy: i32) { - use self::shift_surface as translate_surface; - let a = photocraft_geom::Affine::translate(f64::from(dx), f64::from(dy)); - if let Some(r) = &mut l.effects.reference { - *r = (r.0 + f64::from(dx), r.1 + f64::from(dy)); - } - if let Some(m) = l.mask.as_mut().filter(|m| m.linked) { - m.surface = translate_surface(&m.surface, dx, dy); - } - if let Some(vm) = l.vector_mask.as_mut().filter(|v| v.linked) { - vm.path = vm.path.transform(&a); - } - match &mut l.content { - LayerContent::Raster(s) => *s = translate_surface(s, dx, dy), - LayerContent::Text(t) => { - t.transform = a.mul(&t.transform); - if let Some(c) = &mut t.cache { - *c = translate_surface(c, dx, dy); - } - } - LayerContent::Shape(sh) => crate::vector_cmds::shift_shape(doc, sh, f64::from(dx), f64::from(dy)), - LayerContent::Smart(sm) => crate::smart_cmds::shift_smart(sm, dx, dy), - LayerContent::Group(g) => { - if let Some(ab) = &mut g.artboard { - ab.rect = ab.rect.translate(dx, dy); - } - g.children.iter_mut().for_each(|c| shift_shown(doc, c, dx, dy)); - } - LayerContent::Adjustment(_) | LayerContent::Fill(_) => {} - } -} - -/// The document pixels an edit of the layers `ids` (moved, shown, hidden or restyled; contents -/// otherwise as they were) can have changed from `before` to `after`, or `None` for anywhere. -pub fn layers_damage(before: &Document, after: &Document, ids: &[LayerId]) -> Option { - let mut out = Rect::EMPTY; - for d in [before, after] { - let canvas = d.bounds(); - for id in ids { - // A layer gone from one side (never for a move) changes who knows what. - let (siblings, k, outer) = siblings_of(d, *id)?; - let b = photocraft_compose::change_bounds_in(siblings, k, outer, canvas)?; - if !b.is_empty() { - out = if out.is_empty() { b } else { out.union(&b) }; - } - } - } - Some(out) -} - -/// The sibling list holding layer `id` in `doc` (bottom→top), its index there, and the list -/// holding its parent group with the group's index (`None` at the top level). -type Siblings<'d> = (&'d [Layer], usize, Option<(&'d [Layer], usize)>); -fn siblings_of(doc: &Document, id: LayerId) -> Option> { - let path = doc.path_of(id)?; - let (&k, parent) = path.split_last()?; - let Some((&g, grand)) = parent.split_last() else { return Some((doc.layers.as_slice(), k, None)) }; - let outer = if grand.is_empty() { doc.layers.as_slice() } else { doc.layer_at(grand)?.children()? }; - Some((outer.get(g)?.children()?, k, Some((outer, g)))) -} - -/// Report [`layers_damage`] as the active document's last change, so the canvas recomposites -/// only that (grown by the effect reach around it) instead of everything. -pub(crate) fn note_damage(s: &mut Session, before: &Document, ids: &[LayerId]) { - let Some(st) = s.active_mut() else { return }; - if before.size != st.doc.size { - return; - } - st.last_damage = layers_damage(before, &st.doc, ids); -} - -/// Whether two surfaces hold identical pixels: same format and default pixel, and the same -/// copy-on-write tile pointers at the same coordinates. Both documents stay alive during the -/// comparison, so tile addresses cannot be reused under it. -fn surfaces_equal(a: &photocraft_raster::Surface, b: &photocraft_raster::Surface) -> bool { - a.format() == b.format() - && a.default_pixel() == b.default_pixel() - && a.tile_count() == b.tile_count() - && a.tiles().zip(b.tiles()).all(|((ca, ta), (cb, tb))| ca == cb && std::sync::Arc::ptr_eq(ta, tb)) -} - -/// Byte blobs kept in `Arc`s (PSD raw blocks, embedded smart-object sources): pointer-identical -/// or content-equal (they are small compared to pixels, and undo steps rarely re-parse them). -fn blob_equal(x: &std::sync::Arc>, y: &std::sync::Arc>) -> bool { - std::sync::Arc::ptr_eq(x, y) || (x.len() == y.len() && x.as_slice() == y.as_slice()) -} - -fn blobs_equal(a: &Option>>, b: &Option>>) -> bool { - match (a, b) { - (None, None) => true, - (Some(x), Some(y)) => blob_equal(x, y), - _ => false, - } -} - -/// Layer masks (also the smart-filter mask): scalars plus tile-pointer surface identity. -fn masks_equal(a: &Option, b: &Option) -> bool { - match (a, b) { - (None, None) => true, - (Some(x), Some(y)) => { - x.enabled == y.enabled && x.linked == y.linked && x.density == y.density && x.feather == y.feather && surfaces_equal(&x.surface, &y.surface) - } - _ => false, - } -} - -fn texts_equal(a: &photocraft_doc::TextLayer, b: &photocraft_doc::TextLayer) -> bool { - a.text == b.text - && a.font_family == b.font_family - && a.size_pt == b.size_pt - && a.color == b.color - && a.transform == b.transform - && a.runs == b.runs - && a.paragraphs == b.paragraphs - && a.shape == b.shape - && a.orientation == b.orientation - && a.antialias == b.antialias - && a.warp == b.warp - && match (&a.cache, &b.cache) { - (None, None) => true, - (Some(x), Some(y)) => surfaces_equal(x, y), - _ => false, - } - && blobs_equal(&a.psd_raw, &b.psd_raw) -} - -fn smarts_equal(a: &photocraft_doc::SmartObject, b: &photocraft_doc::SmartObject) -> bool { - a.filters_enabled == b.filters_enabled - && a.transform == b.transform - && a.smart_filters == b.smart_filters - && a.stack_mode == b.stack_mode - && a.perspective == b.perspective - && a.warp == b.warp - && match (&a.source, &b.source) { - (photocraft_doc::SmartSource::Embedded { file_name: x, bytes: xb }, photocraft_doc::SmartSource::Embedded { file_name: y, bytes: yb }) => { - x == y && blob_equal(xb, yb) - } - (photocraft_doc::SmartSource::Linked { path: x }, photocraft_doc::SmartSource::Linked { path: y }) => x == y, - _ => false, - } - && match (&a.cache, &b.cache) { - (None, None) => true, - (Some(x), Some(y)) => surfaces_equal(x, y), - _ => false, - } - && blobs_equal(&a.psd_raw, &b.psd_raw) - && masks_equal(&a.filter_mask, &b.filter_mask) -} - -/// Extra alpha/spot channels (the image itself in Multichannel mode). -fn alpha_channels_equal(a: &photocraft_doc::AlphaChannel, b: &photocraft_doc::AlphaChannel) -> bool { - a.name == b.name && a.spot == b.spot && a.color == b.color && a.opacity == b.opacity && a.indicates == b.indicates && surfaces_equal(&a.surface, &b.surface) -} - -/// Whether two layers render to identical pixels in place. Everything the compositor reads is -/// compared structurally — no hashing, a hash collision would under-report damage; pixels are -/// identified by their copy-on-write tile pointers. Group children are deliberately *not* -/// compared here: the caller walks into them, so an edit inside a group damages only the -/// edited child's extent, not the whole group's. The destructure is exhaustive, so a new -/// `Layer` field fails to compile until it is classified: compared, or explicitly ignored -/// (name, locks, label, `psd_blocks`, `psd_id`, link group, XMP — none of them composite; video -/// bails out earlier in the walk). -fn layer_pixels_equal(a: &Layer, b: &Layer) -> bool { - let Layer { - id, - name: _, - visible, - locks: _, - blend, - opacity, - fill_opacity, - clipped, - mask, - vector_mask, - effects, - label: _, - content, - psd_blocks: _, - psd_id: _, - fill_cache, - link_group: _, - excluded_channels, - blend_if, - advanced, - video: _, - xmp: _, - } = a; - *id == b.id - && *visible == b.visible - && *blend == b.blend - && *opacity == b.opacity - && *fill_opacity == b.fill_opacity - && *clipped == b.clipped - && masks_equal(mask, &b.mask) - && *vector_mask == b.vector_mask - && *effects == b.effects - && *excluded_channels == b.excluded_channels - && *blend_if == b.blend_if - && *advanced == b.advanced - && match (content, &b.content) { - (LayerContent::Raster(x), LayerContent::Raster(y)) => surfaces_equal(x, y), - // Children are walked separately; only the group's own clipping frame counts. - (LayerContent::Group(x), LayerContent::Group(y)) => x.artboard == y.artboard, - (LayerContent::Fill(x), LayerContent::Fill(y)) => x == y, - (LayerContent::Adjustment(x), LayerContent::Adjustment(y)) => x == y, - (LayerContent::Text(x), LayerContent::Text(y)) => texts_equal(x, y), - (LayerContent::Shape(x), LayerContent::Shape(y)) => x == y, - (LayerContent::Smart(x), LayerContent::Smart(y)) => smarts_equal(x, y), - _ => false, - } - && match (fill_cache, &b.fill_cache) { - (None, None) => true, - (Some(x), Some(y)) => x.fill == y.fill && surfaces_equal(&x.surface, &y.surface), - _ => false, - } -} - -/// Document-level fields the compositor reads: all must match for a bounded damage claim. The -/// destructure is exhaustive, so a new `Document` field fails to compile until it is classified -/// here — compared when it composites, or explicitly ignored (the pixel-irrelevant allowlist: -/// identity, name, selection, guides, paths, layer comps, annotations, automation state). -fn doc_pixels_equal(a: &Document, b: &Document) -> bool { - let Document { - id: _, - name: _, - size, - resolution_dpi, - mode, - depth, - icc_profile, - layers: _, - channels, - guides: _, - ruler_origin: _, - selection: _, - metadata: _, - global_light, - paths: _, - work_path: _, - clipping_path: _, - quick_mask, - quick_mask_unselected: _, - patterns, - color_table, - duotone, - layer_comps: _, - last_applied_comp: _, - last_document_state: _, - measurement: _, - notes: _, - text_styles: _, - slices: _, - variables: _, - timeline: _, - file_encoding: _, - } = a; - *size == b.size - && resolution_dpi.to_bits() == b.resolution_dpi.to_bits() - && *mode == b.mode - && *depth == b.depth - && icc_profile.as_deref() == b.icc_profile.as_deref() - && channels.len() == b.channels.len() - && channels.iter().zip(&b.channels).all(|(x, y)| alpha_channels_equal(x, y)) - && *global_light == b.global_light - && match (quick_mask, &b.quick_mask) { - (None, None) => true, - (Some(x), Some(y)) => alpha_channels_equal(x, y), - _ => false, - } - && *patterns == b.patterns - && *color_table == b.color_table - && *duotone == b.duotone -} - -/// Whether `a` and `b` composite to the same pixels: they differ at most in fields the -/// compositor never reads (selection, guides, paths, names, …), by the same classification as -/// [`step_damage`] but without computing any bounds. Cheap: pixels compare by tile pointer. -/// Conservative (`false`) past a nesting depth no real document reaches. -pub fn same_pixels(a: &Document, b: &Document) -> bool { - pixels_equal_with(a, b, |_, _| false) -} - -/// [`same_pixels`], with video layers equal when `video_equal` says their frame stacks are. -fn pixels_equal_with(a: &Document, b: &Document, video_equal: fn(&VideoData, &VideoData) -> bool) -> bool { - fn walk(xs: &[Layer], ys: &[Layer], depth: usize, video_equal: fn(&VideoData, &VideoData) -> bool) -> bool { - depth < 256 - && xs.len() == ys.len() - && xs.iter().zip(ys).all(|(x, y)| { - layer_pixels_equal(x, y) - && match (&x.video, &y.video) { - (None, None) => true, - (Some(vx), Some(vy)) => video_equal(vx, vy), - _ => false, - } - && match (x.children(), y.children()) { - (Some(xc), Some(yc)) => walk(xc, yc, depth + 1, video_equal), - (None, None) => true, - _ => false, - } - }) - } - doc_pixels_equal(a, b) && walk(&a.layers, &b.layers, 0, video_equal) -} - -/// Whether two video layers hold the same frames: the same settings and stack shape -/// (`VideoData`'s own, shallow equality) and the same tile pointers in every frame, painted and -/// original. Pointer compares only, like [`surfaces_equal`]. -fn video_frames_equal(a: &VideoData, b: &VideoData) -> bool { - let frames = |x: &[photocraft_raster::Surface], y: &[photocraft_raster::Surface]| x.len() == y.len() && x.iter().zip(y).all(|(f, g)| surfaces_equal(f, g)); - *a == *b - && frames(&a.frames, &b.frames) - && match (&a.original_frames, &b.original_frames) { - (Some(x), Some(y)) => frames(x, y), - (None, None) => true, - _ => false, - } -} - -/// Whether `a` and `b` differ at most in their selection (#6865): a selection step, which must -/// not mark a clean document modified. Pixels compare by tile pointer (as in [`same_pixels`], -/// plus every frame of a video layer, whose own equality is shallow); every other field compares -/// structurally, where copy-on-write `Arc`s of `Eq` data short-circuit on pointer identity. The -/// destructure is exhaustive, so a new `Document` field fails to compile until it is classified. -pub fn selection_only_change(a: &Document, b: &Document) -> bool { - let Document { - id, - name, - size: _, - resolution_dpi: _, - mode: _, - depth: _, - icc_profile: _, - layers, - channels: _, - guides, - ruler_origin, - selection: _, - metadata, - global_light: _, - paths, - work_path, - clipping_path, - quick_mask: _, - quick_mask_unselected, - patterns: _, - color_table: _, - duotone: _, - layer_comps, - last_applied_comp, - last_document_state, - measurement, - notes, - text_styles, - slices, - variables, - timeline, - file_encoding, - } = a; - // The ignored fields above are the pixel ones `pixels_equal_with` already compares. - pixels_equal_with(a, b, video_frames_equal) - && *id == b.id - && *name == b.name - && *layers == b.layers - && *guides == b.guides - && *ruler_origin == b.ruler_origin - && *metadata == b.metadata - && *paths == b.paths - && *work_path == b.work_path - && *clipping_path == b.clipping_path - && *quick_mask_unselected == b.quick_mask_unselected - && *layer_comps == b.layer_comps - && *last_applied_comp == b.last_applied_comp - && *last_document_state == b.last_document_state - && *measurement == b.measurement - && *notes == b.notes - && *text_styles == b.text_styles - && *slices == b.slices - && *variables == b.variables - && *timeline == b.timeline - && *file_encoding == b.file_encoding -} - -/// Pixels a single history step can have changed between `a` and `b` (the documents on either -/// side of an edit, its undo or its redo): the union of the change bounds of every layer whose -/// pixels differ, so a local edit recomposites only that area instead of the whole canvas. A -/// layer only one side has (a duplicate, a paste, a deleted layer) counts where it draws (see -/// [`one_sided_bounds`]); one that draws nothing ([`inert_at`]) changes nothing. `None` -/// (composite everything) when the step touched anything the layer walk cannot bound: -/// document-level fields the compositor reads (canvas size, mode, depth, profile, global light, -/// patterns, channels, palettes), layer order and kind changes, layers added or removed that -/// reach outside their own bounds, layer properties that do (clipping, excluded channels — -/// what `layer.setProps` already reports as unbounded), and video layers. Inserting a copy of a -/// 12 MP layer used to recomposite every layer of the document (#2883, P8/P9 in -/// `perf/budgets.toml`). -pub fn step_damage(a: &Document, b: &Document) -> Option { - if !doc_pixels_equal(a, b) { - return None; - } - /// The list holding a sibling list's parent group, and the group's index there. - type Outer<'d> = Option<(&'d [Layer], usize)>; - fn walk(xs: &[Layer], ys: &[Layer], (ox, oy): (Outer, Outer), a: &Document, b: &Document, out: &mut Rect) -> bool { - // Pair the layers by id, stepping over layers only one side has: one that draws nothing - // changes no pixels (a new empty layer or group, #1771), any other only where it draws. - let one_sided = |layers: &[Layer], k: usize, outer: Outer, canvas: Rect, out: &mut Rect| { - let Some(r) = one_sided_bounds(layers, k, outer, canvas) else { return false }; - if !r.is_empty() { - *out = if out.is_empty() { r } else { out.union(&r) }; - } - true - }; - let (mut i, mut j) = (0, 0); - loop { - let (x, y) = match (xs.get(i), ys.get(j)) { - (None, None) => return true, - (Some(x), Some(y)) if x.id == y.id => (x, y), - _ if inert_at(ys, j) => { - j += 1; - continue; - } - _ if inert_at(xs, i) => { - i += 1; - continue; - } - (_, Some(y)) if xs.iter().all(|x| x.id != y.id) => { - if !one_sided(ys, j, oy, b.bounds(), out) { - return false; - } - j += 1; - continue; - } - (Some(x), _) if ys.iter().all(|y| y.id != x.id) => { - if !one_sided(xs, i, ox, a.bounds(), out) { - return false; - } - i += 1; - continue; - } - // Both sides have the layer, in another order. - _ => return false, - }; - let (xk, yk) = (i, j); - i += 1; - j += 1; - if x.video.is_some() || y.video.is_some() { - return false; - } - // Clipping and channel exclusion change how *other* layers render, outside this - // layer's own bounds; they have no bounded damage. - if x.clipped != y.clipped || x.excluded_channels != y.excluded_channels { - return false; - } - if !layer_pixels_equal(x, y) { - // Both sides' extents: a move changes pixels where it left and where it landed. - // A clipped adjustment reaches as far as its base (#6535). - let (Some(bx), Some(by)) = - (photocraft_compose::change_bounds_in(xs, xk, ox, a.bounds()), photocraft_compose::change_bounds_in(ys, yk, oy, b.bounds())) - else { - return false; - }; - *out = if out.is_empty() { bx.union(&by) } else { out.union(&bx).union(&by) }; - } - match (x.children(), y.children()) { - (Some(xc), Some(yc)) => { - if !walk(xc, yc, (Some((xs, xk)), Some((ys, yk))), a, b, out) { - return false; - } - } - (None, None) => {} - _ => return false, - } - } - } - let mut out = Rect::EMPTY; - if walk(&a.layers, &b.layers, (None, None), a, b, &mut out) { Some(out) } else { None } -} - -/// The pixels adding or removing `layers[k]` can change, when that is bounded: its change bounds -/// (`photocraft_compose::change_bounds_in`: not for an unclipped adjustment, or a pass-through -/// group holding one; a clipped adjustment's are its base's), provided it isn't the clipping base -/// of clipped layers above it (they would change base), and neither it nor anything inside it is -/// a video layer or excludes channels (both reach outside the layer's bounds, see -/// [`step_damage`]). -fn one_sided_bounds(layers: &[Layer], k: usize, outer: Option<(&[Layer], usize)>, canvas: Rect) -> Option { - fn contained(l: &Layer, depth: usize) -> bool { - depth < 256 && l.video.is_none() && l.excluded_channels == 0 && l.children().is_none_or(|c| c.iter().all(|c| contained(c, depth + 1))) - } - let l = layers.get(k)?; - let new_base = !l.clipped && layers.get(k + 1).is_some_and(|above| above.clipped); - if new_base || !contained(l, 0) { - return None; - } - photocraft_compose::change_bounds_in(layers, k, outer, canvas) -} - -/// Whether `layers[k]` draws nothing wherever it sits, so adding or removing it leaves the -/// composite as it was: an empty pixel layer (no tiles, transparent default) or an empty group, -/// in a Normal or Pass Through blend with no mask, vector mask, effects or Advanced Blending. -/// A clipping base that would gain or lose the clipped layers above it is not inert. -fn inert_at(layers: &[Layer], k: usize) -> bool { - let Some(l) = layers.get(k) else { return false }; - let empty = match &l.content { - LayerContent::Raster(s) => s.tile_count() == 0 && s.format().alpha && s.default_bytes().iter().all(|b| *b == 0), - LayerContent::Group(g) => g.children.is_empty() && g.artboard.is_none(), - _ => false, - }; - empty - && matches!(l.blend, photocraft_doc::BlendMode::Normal | photocraft_doc::BlendMode::PassThrough) - && l.mask.is_none() - && l.vector_mask.is_none() - && !photocraft_compose::effects::has_effects(l) - && l.fill_cache.is_none() - && l.video.is_none() - && l.advanced == photocraft_doc::AdvancedBlending::default() - && (l.clipped || layers.get(k + 1).is_none_or(|above| !above.clipped)) -} - -/// Report that adding layer `id` to the active document changed no pixels when it draws -/// nothing ([`inert_at`]), so the canvas doesn't recomposite every layer for it (#1771). Looks -/// only at the new layer and its neighbour, never at other layers' tiles. -pub(crate) fn note_inert_insert(s: &mut Session, id: LayerId) { - let Some(st) = s.active_mut() else { return }; - let Some(path) = st.doc.path_of(id) else { return }; - let Some((&k, parent)) = path.split_last() else { return }; - let siblings = if parent.is_empty() { Some(st.doc.layers.as_slice()) } else { st.doc.layer_at(parent).and_then(Layer::children) }; - if siblings.is_some_and(|sib| inert_at(sib, k)) { - st.last_damage = Some(Rect::EMPTY); - } -} - -/// Report the pixels a command made of more than one edit changed since `before` ([`step_damage`]), -/// so the canvas recomposites only where its new layers draw instead of the whole document. -/// A single [`Session::edit`] already reports its own damage: don't call this after one (#5695). -pub(crate) fn note_insert(s: &mut Session, before: &Document) { - let Some(st) = s.active_mut() else { return }; - st.last_damage = step_damage(before, &st.doc); -} - -/// Content bounds used by Align/Distribute: the layer's pixels (type and shape layers use their -/// rendered pixels), or the union of a group's children. Fill and adjustment layers have none. -pub fn layer_bounds(l: &Layer) -> Option { - let r = match &l.content { - LayerContent::Group(g) => g.children.iter().filter_map(layer_bounds).fold(Rect::EMPTY, |a, b| a.union(&b)), - _ => l.surface().map(|s| s.content_bounds()).unwrap_or(Rect::EMPTY), - }; - (!r.is_empty()).then_some(r) -} - -#[derive(Clone, Copy, PartialEq, Eq, Debug)] -enum Edge { - Top, - VCenter, - Bottom, - Left, - HCenter, - Right, -} - -impl Edge { - fn parse(k: &str) -> Option { - Some(match k { - "topEdges" => Edge::Top, - "verticalCenters" => Edge::VCenter, - "bottomEdges" => Edge::Bottom, - "leftEdges" => Edge::Left, - "horizontalCenters" => Edge::HCenter, - "rightEdges" => Edge::Right, - _ => return None, - }) - } - fn vertical(self) -> bool { - matches!(self, Edge::Top | Edge::VCenter | Edge::Bottom) - } - /// The edge's coordinate, doubled so centres stay integral. - fn value2(self, r: &Rect) -> i64 { - let (a, b) = if self.vertical() { (r.y0, r.y1) } else { (r.x0, r.x1) }; - match self { - Edge::Top | Edge::Left => 2 * a as i64, - Edge::Bottom | Edge::Right => 2 * b as i64, - Edge::VCenter | Edge::HCenter => a as i64 + b as i64, - } - } - fn delta(self, d: i32) -> (i32, i32) { - if self.vertical() { (0, d) } else { (d, 0) } - } -} - -/// Selected top-level layers that have content bounds, bottom-to-top. -fn bounded_selection(doc: &Document, sel: &[LayerId]) -> Vec<(LayerId, Rect)> { - top_level(doc, sel).into_iter().filter_map(|id| Some((id, layer_bounds(doc.layer(id)?)?))).collect() -} - -fn align(s: &mut Session, p: &Value, kind: &str) -> Result { - let cmd = format!("layer.align.{kind}"); - let edge = Edge::parse(kind).ok_or_else(|| bad(&cmd, "unknown edge"))?; - let sel = selected(s); - let to = p.get("to").and_then(Value::as_str).unwrap_or("auto").to_string(); - let before = s.active().ok_or(EngineError::NoDocument)?.doc.clone(); - let moved = s.edit("Align", |doc, _| { - let items = bounded_selection(doc, &sel); - if items.is_empty() { - return Err(EngineError::Other("the selected layers have no content to align".into())); - } - let target = match to.as_str() { - "canvas" => doc.bounds(), - "selection" => doc.selection.as_ref().map(|m| m.content_bounds()).ok_or_else(|| EngineError::Other("there is no selection to align to".into()))?, - "auto" | "layers" => match (&doc.selection, sel.len()) { - // Photoshop: with an active selection, the layers align to its bounds (Layer › Align - // Layers to Selection), however many are selected. - (Some(m), _) if to == "auto" && !m.content_bounds().is_empty() => m.content_bounds(), - // One layer with no selection aligns to the canvas (otherwise it would align to - // itself), or to the artboard it sits in, as in Photoshop (#7945). - (None, 1) if to == "auto" => items.first().map_or_else(|| doc.bounds(), |(id, _)| board_or_canvas(doc, *id)), - _ => items.iter().fold(Rect::EMPTY, |a, (_, b)| a.union(b)), - }, - other => return Err(bad(&cmd, format!("`to` must be auto|layers|selection|canvas, not `{other}`"))), - }; - if target.is_empty() { - return Err(EngineError::Other("nothing to align to".into())); - } - let t2 = edge.value2(&target); - let moves: Vec<(LayerId, i32, i32)> = items - .iter() - .flat_map(|(id, r)| { - let d = (t2 - edge.value2(r)).div_euclid(2) as i32; - let (dx, dy) = edge.delta(d); - // Linked layers travel with the layer they are linked to. - with_links(doc, &[*id]).into_iter().map(move |l| (l, dx, dy)) - }) - .collect(); - let moves = dedup_moves(doc, moves); - move_layers(doc, &before, &moves)?; - Ok(moves.iter().filter(|m| m.1 != 0 || m.2 != 0).count()) - })?; - Ok(json!({"moved": moved})) -} - -/// The bounds a lone layer aligns to: the artboard holding it, else the canvas. An artboard -/// itself aligns to the canvas. -fn board_or_canvas(doc: &Document, id: LayerId) -> Rect { - doc.artboard_of(id).filter(|board| *board != id).and_then(|board| doc.layer(board)?.artboard().map(|a| a.rect)).unwrap_or_else(|| doc.bounds()) -} - -/// One move per layer (first wins), skipping layers nested in another moved layer. -fn dedup_moves(doc: &Document, moves: Vec<(LayerId, i32, i32)>) -> Vec<(LayerId, i32, i32)> { - let mut out: Vec<(LayerId, i32, i32)> = Vec::new(); - for m in moves { - if !out.iter().any(|o| o.0 == m.0) { - out.push(m); - } - } - let ids: Vec = out.iter().map(|m| m.0).collect(); - let keep = top_level(doc, &ids); - out.retain(|m| keep.contains(&m.0)); - out -} - -fn distribute(s: &mut Session, kind: &str) -> Result { - let sel = selected(s); - let kind = kind.to_string(); - let before = s.active().ok_or(EngineError::NoDocument)?.doc.clone(); - let moved = s.edit("Distribute", |doc, _| { - let mut items = bounded_selection(doc, &sel); - if items.len() < 3 { - return Err(EngineError::Other("distributing needs three or more layers with content".into())); - } - let n = items.len(); - let mut moves = Vec::new(); - match kind.as_str() { - "horizontally" | "vertically" => { - // Equal gaps between neighbours; the outermost layers stay put. - let v = kind == "vertically"; - let lo = |r: &Rect| if v { r.y0 } else { r.x0 } as i64; - let hi = |r: &Rect| if v { r.y1 } else { r.x1 } as i64; - items.sort_by_key(|(_, r)| (lo(r) + hi(r), lo(r))); - let span = hi(&items[n - 1].1) - lo(&items[0].1); - let total: i64 = items.iter().map(|(_, r)| hi(r) - lo(r)).sum(); - let gap = (span - total) as f64 / (n - 1) as f64; - let mut cursor = lo(&items[0].1) as f64; - for (id, r) in &items { - let want = cursor.round() as i64; - let d = (want - lo(r)) as i32; - moves.push(if v { (*id, 0, d) } else { (*id, d, 0) }); - cursor += (hi(r) - lo(r)) as f64 + gap; - } - } - k => { - let edge = Edge::parse(k).ok_or_else(|| bad("layer.distribute", format!("unknown kind `{k}`")))?; - items.sort_by_key(|(_, r)| edge.value2(r)); - let (first, last) = (edge.value2(&items[0].1) as f64, edge.value2(&items[n - 1].1) as f64); - for (i, (id, r)) in items.iter().enumerate() { - let want2 = first + (last - first) * i as f64 / (n - 1) as f64; - let d = ((want2 - edge.value2(r) as f64) / 2.0).round() as i32; - let (dx, dy) = edge.delta(d); - moves.push((*id, dx, dy)); - } - } - } - let moves: Vec<_> = moves.into_iter().flat_map(|(id, dx, dy)| with_links(doc, &[id]).into_iter().map(move |l| (l, dx, dy))).collect(); - let moves = dedup_moves(doc, moves); - move_layers(doc, &before, &moves)?; - Ok(moves.iter().filter(|m| m.1 != 0 || m.2 != 0).count()) - })?; - Ok(json!({"moved": moved})) -} - -/// Reorder one or multiple layers to a single destination in one undoable edit. -/// -/// Explicit `layers` are ordered according to the source document, not caller ordering. -/// A transient snapshot for the Layers panel's "Preview on canvas when reordering layers". -/// Uses the same source ordering and insertion semantics as `move_to`, but never edits history. -/// Invalid/self-referential hover targets return None (the committed image stays visible). -pub fn preview_move(doc: &Document, p: &Value, add_copy: bool) -> Option { - let target = LayerId(p.get("target")?.as_u64()?); - let position = p.get("position")?.as_str()?; - if !matches!(position, "above" | "below" | "into") { - return None; - } - let copy = p.get("copy").and_then(Value::as_bool).unwrap_or(false); - let ids = if let Some(ids) = p.get("layers") { - ids.as_array()?.iter().map(|v| v.as_u64().map(LayerId)).collect::>>()? - } else { - vec![LayerId(p.get("layer")?.as_u64()?)] - }; - if ids.is_empty() || doc.layer(target).is_none() { - return None; - } - let moved_ids = top_level(doc, &ids); - if moved_ids.is_empty() || moved_ids.iter().any(|id| doc.layer(*id).is_none()) { - return None; - } - if moved_ids.len() == 1 && moved_ids[0] == target && !copy { - return None; - } - let target_path = doc.path_of(target)?; - for id in &moved_ids { - let path = doc.path_of(*id)?; - if target_path.starts_with(&path) && !(copy && *id == target && position != "into") { - return None; - } - } - if position == "into" && !doc.layer(target)?.is_group() { - return None; - } - // The very structural move the drop commits, so the preview shows the same clip groups, - // Background handling and group-depth refusals; a drop `move_to` would refuse has no preview. - let mut preview = doc.clone(); - apply_move(&mut preview, &moved_ids, target, position, copy, add_copy).ok()?; - Some(preview) -} - -/// The document-only part of `move_to`, shared with [`preview_move`] so the Layers panel's hover -/// preview cannot drift from what the drop commits. Moves (or, with `copy`, duplicates) the -/// top-level `moved_ids` to `pos` (`above`, `below` or `into`) `target`, then applies the -/// group-depth cap, the Background-stays-at-the-bottom rule and the clip-group rules -/// (`clip_group::settle`). Returns the ids of the new copies (empty for a move). On `Err` `doc` is -/// half edited: run it inside `Session::edit` or on a scratch copy. -fn apply_move(doc: &mut Document, moved_ids: &[LayerId], target: LayerId, pos: &str, copy: bool, add_copy: bool) -> Result> { - const CMD: &str = "layer.moveTo"; - let background = crate::background_cmds::background_id(doc); - let before = if copy { Default::default() } else { crate::clip_group::Before::read(doc, moved_ids) }; - let mut moved = Vec::with_capacity(moved_ids.len()); - for &id in moved_ids { - moved.push(if copy { crate::commands::layer_copy(doc, id, add_copy)? } else { doc.remove(id).ok_or(EngineError::NoLayer(id))? }); - } - let copies: Vec = if copy { moved.iter().map(|l| l.id).collect() } else { Vec::new() }; - // Look up the destination AFTER removing every source: its indices may have shifted. - let path = doc.path_of(target).ok_or(EngineError::NoLayer(target))?; - if pos == "into" { - let children = doc.layer_at_mut(&path).and_then(Layer::children_mut).ok_or_else(|| bad(CMD, "target is not a group"))?; - children.extend(moved); - } else { - let (&idx, parent) = path.split_last().ok_or(EngineError::NoLayer(target))?; - let siblings = if parent.is_empty() { - &mut doc.layers - } else { - doc.layer_at_mut(parent).and_then(Layer::children_mut).ok_or_else(|| bad(CMD, "target's parent is not a group"))? - }; - let at = if pos == "below" { idx } else { idx + 1 }; - siblings.splice(at..at, moved); - } - check_group_depth(doc, "Reorder Layer")?; - crate::background_cmds::keep_background_at_bottom(background, doc)?; - crate::clip_group::settle(doc, if copy { &copies } else { moved_ids }, &before, false); - Ok(copies) -} - -/// Selected descendants of a moved group remain inside their parent; only top-level -/// selected nodes are detached, and every reference is validated before editing. -pub fn move_to(s: &mut Session, p: &Value) -> Result { - const CMD: &str = "layer.moveTo"; - let pos = p.get("position").and_then(Value::as_str).unwrap_or("above"); - if !matches!(pos, "above" | "below" | "into") { - return Err(bad(CMD, "position must be above, below, or into")); - } - // ⌥-drag in the Layers panel: duplicates land at the target and the layers stay put. - let copy = p.get("copy").and_then(Value::as_bool).unwrap_or(false); - - let batch = p.get("layers"); - if batch.is_some() && p.get("layer").is_some() { - return Err(bad(CMD, "give either `layer` or `layers`, not both")); - } - let requested = if let Some(raw) = batch { - let arr = raw.as_array().filter(|a| !a.is_empty()).ok_or_else(|| bad(CMD, "`layers` must be a nonempty array of ids"))?; - let mut ids = Vec::with_capacity(arr.len()); - for item in arr { - let id = LayerId(item.as_u64().ok_or_else(|| bad(CMD, "every layer id must be an unsigned integer"))?); - if ids.contains(&id) { - return Err(bad(CMD, "duplicate layer id")); - } - ids.push(id); - } - ids - } else { - vec![crate::commands::layer_param(s, p)?] - }; - // A copy moves nothing, so its source stays a candidate (⌥-dragging a layer beside itself). - let target = move_target(s, p, if copy { &[] } else { &requested })?; - let st = s.active().ok_or(EngineError::NoDocument)?; - let doc = &st.doc; - let target_path = doc.path_of(target).ok_or(EngineError::NoLayer(target))?; - for &id in &requested { - if doc.layer(id).is_none() { - return Err(EngineError::NoLayer(id)); - } - } - let moved_ids = top_level(doc, &requested); - if moved_ids.len() == 1 && moved_ids[0] == target && batch.is_none() && !copy { - // Preserve single-layer drag-to-self semantics. - return Ok(Value::Null); - } - // Also rejects dragging a selected group onto any of its descendants. - for id in &moved_ids { - let path = doc.path_of(*id).ok_or(EngineError::NoLayer(*id))?; - // A copy may land beside its own source (not inside it). - let beside_itself = copy && *id == target && pos != "into"; - if target_path.starts_with(&path) && !beside_itself { - return Err(bad(CMD, "target cannot be one of the moved layers or its descendant")); - } - } - if pos == "into" && doc.layer(target).is_none_or(|l| !l.is_group()) { - return Err(bad(CMD, "target is not a group")); - } - - let original_active = st.active_layer; - let add_copy = crate::commands::layer_panel_option(s, "addCopyToCopiedLayersAndGroups", true); - let (count, copies) = s.edit(if copy { "Duplicate Layer" } else { "Reorder Layers" }, |doc, active| { - let copies = apply_move(doc, &moved_ids, target, pos, copy, add_copy)?; - *active = if copy { - copies.last().copied() - } else if batch.is_some() { - original_active.filter(|id| requested.contains(id)).or_else(|| requested.last().copied()) - } else { - moved_ids.first().copied() - }; - Ok((moved_ids.len(), copies)) - })?; - if copy { - let ids: Vec = copies.iter().map(|id| id.0).collect(); - if batch.is_some() { - let active = copies.last().copied(); - reselect(s, copies, active); - return Ok(json!({"moved": count, "layers": ids})); - } - return Ok(json!({"layer": ids.first()})); - } - if batch.is_some() { - let active = original_active.filter(|id| requested.contains(id)).or_else(|| requested.last().copied()); - reselect(s, requested, active); - Ok(json!({"moved": count})) - } else { - Ok(Value::Null) - } -} - -// ---------- structural commands ---------- - -fn link_layers(s: &mut Session) -> Result { - let sel = selected(s); - let linked = s.edit("Link Layers", |doc, _| { - let groups: Vec> = sel.iter().map(|id| doc.layer(*id).and_then(|l| l.link_group)).collect(); - // Already one link group (or a single linked layer): unlink, like Photoshop's toggle. - let first = groups.first().copied().flatten(); - let unlink = first.is_some() && groups.iter().all(|g| *g == first); - // A loaded file can store any id up to u64::MAX, so the new id must not be a bare - // max + 1 (#961). Unlinking needs no new id at all. - let next = if unlink { None } else { Some(doc.unused_link_group().ok_or_else(|| bad("layer.linkLayers", "no free link group id is left"))?) }; - for id in &sel { - let l = doc.layer_mut(*id).ok_or(EngineError::NoLayer(*id))?; - l.link_group = next; - } - // A group left with a single member is no longer a link. - let mut counts = std::collections::HashMap::::new(); - for (_, _, l) in doc.walk() { - if let Some(g) = l.link_group { - *counts.entry(g).or_default() += 1; - } - } - let lonely: Vec = - doc.walk().iter().filter(|(_, _, l)| l.link_group.is_some_and(|g| counts.get(&g).is_some_and(|&c| c < 2))).map(|(_, _, l)| l.id).collect(); - for id in lonely { - if let Some(l) = doc.layer_mut(id) { - l.link_group = None; - } - } - Ok(!unlink) - })?; - Ok(json!({"linked": linked})) -} - -fn lock_layers(s: &mut Session, p: &Value) -> Result { - let sel = selected(s); - let keys = ["transparency", "pixels", "position", "artboard", "all"]; - let given: Vec<(&str, bool)> = keys.iter().filter_map(|k| Some((*k, p.get(*k)?.as_bool()?))).collect(); - s.edit("Lock Layers", |doc, _| { - // No explicit locks: toggle "lock all" (on unless every selected layer is already locked). - let all_locked = sel.iter().all(|id| doc.layer(*id).is_some_and(|l| l.locks.all)); - let given: Vec<(&str, bool)> = if given.is_empty() { vec![("all", !all_locked)] } else { given.clone() }; - for id in &sel { - let l = doc.layer_mut(*id).ok_or(EngineError::NoLayer(*id))?; - for (k, v) in &given { - l.locks.set(k, *v); - } - } - Ok(()) - })?; - Ok(json!({"layers": sel.len()})) -} - -fn rename_layer(s: &mut Session, p: &Value) -> Result { - let name = p.get("name").and_then(Value::as_str).filter(|n| !n.trim().is_empty()).ok_or_else(|| bad("layer.renameLayer", "missing `name`"))?.to_string(); - let id = crate::commands::layer_param(s, p)?; - s.edit("Rename Layer", |doc, _| { - doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?.name = name; - Ok(()) - })?; - Ok(Value::Null) -} - -fn reverse(s: &mut Session) -> Result { - let sel = selected(s); - s.edit("Reverse", |doc, _| { - let background = crate::background_cmds::background_id(doc); - let ids = top_level(doc, &sel); - if ids.len() < 2 { - return Err(EngineError::Other("select two or more layers to reverse".into())); - } - let paths: Vec> = ids.iter().map(|id| doc.path_of(*id).ok_or(EngineError::NoLayer(*id))).collect::>()?; - let layers: Vec = ids.iter().map(|id| doc.layer(*id).cloned().ok_or(EngineError::NoLayer(*id))).collect::>()?; - // Slots are disjoint (no layer is nested in another), so writing whole layers back to the - // same paths never shifts another slot. - for (path, l) in paths.iter().zip(layers.into_iter().rev()) { - *doc.layer_at_mut(path).ok_or_else(|| EngineError::Other("layer tree changed".into()))? = l; - } - crate::background_cmds::keep_background_at_bottom(background, doc) - })?; - Ok(Value::Null) -} - -/// Refuses an edit that left `doc` nested deeper than [`photocraft_doc::MAX_GROUP_DEPTH`] -/// groups. Called at the end of a `Session::edit` closure, so an `Err` leaves the document and -/// history untouched. -pub(crate) fn check_group_depth(doc: &Document, what: &str) -> Result<()> { - if doc.max_group_depth() > photocraft_doc::MAX_GROUP_DEPTH { - return Err(EngineError::Other(format!("{what} would nest layers deeper than {} groups", photocraft_doc::MAX_GROUP_DEPTH))); - } - Ok(()) -} - -/// Group Layers (⌘G) / Group from Layers: the explicit layer, or every selected layer, moves -/// into a new, collapsed group placed where the top-most of them was. Bottom-to-top order is -/// preserved. -pub fn group_layers(s: &mut Session, p: &Value) -> Result { - let ids = match crate::commands::explicit_layer(s, p)? { - Some(id) => vec![id], - None => selected(s), - }; - if ids.is_empty() { - return Err(EngineError::Other("no layer selected".into())); - } - let name = p.get("name").and_then(Value::as_str).map(str::to_string); - let gid = s.edit("Group Layers", |doc, active| { - let ids = top_level(doc, &ids); - let top = *ids.last().ok_or(EngineError::NoLayer(LayerId(0)))?; - let name = name.unwrap_or_else(|| doc.next_layer_name("Group")); - // Photoshop creates the group collapsed, so the panel shows one row in place of the layers. - let mut group = Layer::group(name, vec![]); - if let LayerContent::Group(g) = &mut group.content { - g.expanded = false; - } - let gid = doc.insert_above(Some(top), group); - let mut children = Vec::with_capacity(ids.len()); - for id in &ids { - children.push(doc.remove(*id).ok_or(EngineError::NoLayer(*id))?); - } - *doc.layer_mut(gid).and_then(Layer::children_mut).ok_or(EngineError::NoLayer(gid))? = children; - check_group_depth(doc, "Group Layers")?; - *active = Some(gid); - Ok(gid) - })?; - reselect(s, vec![gid], Some(gid)); - Ok(json!({ "layer": gid.0 })) -} - -fn merge_layers(s: &mut Session) -> Result { - let sel = selected(s); - if sel.len() < 2 { - // ⌘E on a lone group is Photoshop's Merge Group (#3832); on a layer, Merge Down. - if let Some(&id) = sel.first() - && s.active().and_then(|d| d.doc.layer(id)).is_some_and(|l| matches!(l.content, LayerContent::Group(_))) - { - return s.execute("layer.mergeGroup", json!({ "layer": id.0 })); - } - return s.execute("layer.mergeDown", json!({})); - } - let mid = s.edit("Merge Layers", |doc, active| { - let ids = top_level(doc, &sel); - let lowest_id = *ids.first().ok_or_else(|| EngineError::Other("Merge Layers needs two or more layers".into()))?; - let is_background = doc.is_background(lowest_id); - - let mut solo = doc.clone(); - solo.layers = ids.iter().filter_map(|id| doc.layer(*id)).filter(|l| l.visible).cloned().collect(); - if solo.layers.is_empty() { - return Err(EngineError::Other("the selected layers are all hidden".into())); - } - - if is_background { - let base = doc.layer(lowest_id).ok_or(EngineError::NoLayer(lowest_id))?.clone(); - let fmt = doc.pixel_format(); - let mut merged = Layer::raster(base.name.clone(), fmt); - merged.locks = base.locks; - merged.label = base.label; - merged.id = lowest_id; - merged.blend = base.blend; - merged.opacity = 1.0; - *crate::pixels_mut(&mut merged)? = crate::pixels::composite_layers(&solo, fmt, None); - for id in &ids[1..] { - doc.remove(*id); - } - *doc.layer_mut(lowest_id).ok_or(EngineError::NoLayer(lowest_id))? = merged; - *active = Some(lowest_id); - Ok(lowest_id) - } else { - let top_id = *ids.last().ok_or_else(|| EngineError::Other("Merge Layers needs two or more layers".into()))?; - let top = doc.layer(top_id).ok_or(EngineError::NoLayer(top_id))?.clone(); - let fmt = doc.pixel_format(); - let fmt = PixelFormat::new(fmt.mode, fmt.sample, true); - let mut merged = Layer::raster(top.name.clone(), fmt); - merged.locks = top.locks; - merged.label = top.label; - // Clipped layers of one chain merge into a layer still clipped to their base. Clipped - // layers of different chains don't: the result, at the top one's slot, would clip the - // lower chain's pixels to the upper chain's base. - let base = crate::clip_group::base_of(doc, top_id); - merged.clipped = base.is_some() && solo.layers.iter().all(|l| l.clipped && crate::clip_group::base_of(doc, l.id) == base); - *crate::pixels_mut(&mut merged)? = crate::pixels::composite_layers_uncropped(&solo, fmt); - let mid = merged.id; - // Hidden selected layers are discarded, as in Photoshop. - for id in &ids[..ids.len() - 1] { - doc.remove(*id); - } - *doc.layer_mut(top_id).ok_or(EngineError::NoLayer(top_id))? = merged; - *active = Some(mid); - Ok(mid) - } - })?; - reselect(s, vec![mid], Some(mid)); - Ok(json!({ "layer": mid.0 })) -} - -/// Next visible layer row below the deleted target, then rows above in reverse order. -/// Group headers precede their children in the UI, unlike Document::walk's storage order. -pub(crate) fn deletion_neighbours(doc: &Document, target: LayerId) -> Vec { - let rows = |expand_all: bool| { - let mut stack: Vec<&Layer> = doc.layers.iter().collect(); - let mut order = Vec::new(); - while let Some(layer) = stack.pop() { - order.push(layer.id); - if let LayerContent::Group(group) = &layer.content - && (expand_all || group.expanded) - { - stack.extend(group.children.iter()); - } - } - order - }; - let mut order = rows(false); - if !order.contains(&target) { - order = rows(true); - } - let Some(index) = order.iter().position(|id| *id == target) else { - return Vec::new(); - }; - order.iter().skip(index + 1).chain(order.iter().take(index).rev()).copied().collect() -} - -/// Delete Layer with several layers selected. -pub fn delete_selected(s: &mut Session) -> Result { - let sel = selected(s); - s.edit("Delete Layers", |doc, active| { - let ids = top_level(doc, &sel); - let neighbours = active.map(|id| deletion_neighbours(doc, id)).unwrap_or_default(); - let before = crate::clip_group::Before::read(doc, &ids); - for id in &ids { - doc.remove(*id).ok_or(EngineError::NoLayer(*id))?; - } - crate::clip_group::settle(doc, &[], &before, false); - if doc.layers.is_empty() { - return Err(EngineError::Other("a document must keep at least one layer".into())); - } - *active = neighbours.into_iter().find(|candidate| doc.layer(*candidate).is_some()); - Ok(()) - })?; - Ok(json!({"deleted": sel.len()})) -} - -/// Duplicate Layer with several layers selected: each copy goes above its original and the -/// copies become the selection. Artboard copies go beside their boards unless `in_place` -/// ([`crate::artboard_cmds::place_copy`]). `label` names the history step (Layer via Copy reuses -/// this path, #2777). -pub fn duplicate_selected(s: &mut Session, in_place: bool, label: &str) -> Result { - let sel = selected(s); - let old_active = s.active().and_then(|d| d.active_layer); - let add_copy = crate::commands::layer_panel_option(s, "addCopyToCopiedLayersAndGroups", true); - let (copies, active) = s.edit(label, |doc, active| { - let mut copies = Vec::new(); - let mut new_active = None; - for id in top_level(doc, &sel) { - // Match the single-layer duplicate path: Background copies become - // ordinary layers, while normal copies retain their original locks. - let dup = crate::commands::layer_copy(doc, id, add_copy)?; - let nid = doc.insert_above(Some(id), dup); - if !in_place { - crate::artboard_cmds::place_copy(doc, nid)?; - } - if Some(id) == old_active { - new_active = Some(nid); - } - copies.push(nid); - } - let a = new_active.or(copies.last().copied()); - *active = a; - Ok((copies, a)) - })?; - let out = copies.iter().map(|l| l.0).collect::>(); - reselect(s, copies, active); - Ok(json!({"layers": out, "layer": active.map(|l| l.0)})) -} - -/// Show/hide every selected layer in one step. -pub fn set_visible_selected(s: &mut Session, visible: bool) -> Result { - let sel = selected(s); - s.edit(if visible { "Show Layers" } else { "Hide Layers" }, |doc, _| { - for id in &sel { - doc.layer_mut(*id).ok_or(EngineError::NoLayer(*id))?.visible = visible; - } - Ok(()) - })?; - Ok(Value::Null) -} - -/// Is more than one layer selected (so single-layer commands should act on the whole set)? -pub fn multi(s: &Session, p: &Value) -> bool { - p.get("layer").is_none() && selected(s).len() > 1 -} - -// ---------- registry ---------- - -pub fn specs() -> Vec { - macro_rules! spec { - ($id:expr, $label:expr, $menu:expr, $sc:expr, $params:expr, $enabled:expr, $run:expr) => { - CommandSpec { id: $id, label: $label, menu: $menu, shortcut: $sc, params: $params, enabled: $enabled, journal: true, run: $run } - }; - } - const ALIGN: &str = r##"{"to":"auto|layers|selection|canvas"="auto"} (auto: the active selection's bounds when there is one, however many layers are selected; else one layer aligns to the canvas and several to their combined bounds)"##; - vec![ - spec!("select.allLayers", "All Layers", &["Select"], Some("Cmd+Alt+A"), "{}", has_doc, |s, _| select_all_layers(s)), - spec!("select.deselectLayers", "Deselect Layers", &["Select"], None, "{}", has_doc, |s, _| { - set_selection(s, Vec::new(), None, None)?; - if let Some(st) = s.active_mut() { - st.active_layer = None; - st.selected_layers.clear(); - } - Ok(Value::Null) - }), - spec!("select.findLayers", "Find Layers", &["Select"], Some("Cmd+Alt+Shift+F"), r##"{"name":str (case-insensitive substring)}"##, has_doc, find_layers), - spec!("layer.selectLinkedLayers", "Select Linked Layers", &["Layer"], None, "{}", has_linked, |s, _| select_linked(s)), - spec!("layer.align.topEdges", "Top Edges", &["Layer", "Align"], None, ALIGN, can_align, |s, p| align(s, p, "topEdges")), - spec!("layer.align.verticalCenters", "Vertical Centers", &["Layer", "Align"], None, ALIGN, can_align, |s, p| align(s, p, "verticalCenters")), - spec!("layer.align.bottomEdges", "Bottom Edges", &["Layer", "Align"], None, ALIGN, can_align, |s, p| align(s, p, "bottomEdges")), - spec!("layer.align.leftEdges", "Left Edges", &["Layer", "Align"], None, ALIGN, can_align, |s, p| align(s, p, "leftEdges")), - spec!("layer.align.horizontalCenters", "Horizontal Centers", &["Layer", "Align"], None, ALIGN, can_align, |s, p| align(s, p, "horizontalCenters")), - spec!("layer.align.rightEdges", "Right Edges", &["Layer", "Align"], None, ALIGN, can_align, |s, p| align(s, p, "rightEdges")), - spec!("layer.distribute.topEdges", "Top Edges", &["Layer", "Distribute"], None, "{}", can_distribute, |s, _| distribute(s, "topEdges")), - spec!("layer.distribute.verticalCenters", "Vertical Centers", &["Layer", "Distribute"], None, "{}", can_distribute, |s, _| distribute( - s, - "verticalCenters" - )), - spec!("layer.distribute.bottomEdges", "Bottom Edges", &["Layer", "Distribute"], None, "{}", can_distribute, |s, _| distribute(s, "bottomEdges")), - spec!("layer.distribute.leftEdges", "Left Edges", &["Layer", "Distribute"], None, "{}", can_distribute, |s, _| distribute(s, "leftEdges")), - spec!("layer.distribute.horizontalCenters", "Horizontal Centers", &["Layer", "Distribute"], None, "{}", can_distribute, |s, _| distribute( - s, - "horizontalCenters" - )), - spec!("layer.distribute.rightEdges", "Right Edges", &["Layer", "Distribute"], None, "{}", can_distribute, |s, _| distribute(s, "rightEdges")), - spec!( - "layer.distribute.horizontally", - "Horizontally", - &["Layer", "Distribute"], - None, - "{} (equal horizontal gaps)", - can_distribute, - |s, _| distribute(s, "horizontally") - ), - spec!("layer.distribute.vertically", "Vertically", &["Layer", "Distribute"], None, "{} (equal vertical gaps)", can_distribute, |s, _| distribute( - s, - "vertically" - )), - spec!("layer.linkLayers", "Link Layers", &["Layer"], None, "{} (toggles: unlinks when the selection is already one link group)", can_link, |s, _| { - link_layers(s) - }), - spec!("layer.mergeLayers", "Merge Layers", &["Layer"], Some("Cmd+E"), "{} (one layer selected: Merge Down)", has_layer, |s, _| merge_layers(s)), - spec!( - "layer.new.groupFromLayers", - "Group from Layers…", - &["Layer", "New"], - None, - r##"{"layer":id?,"name":str?} (no layer: every selected layer)"##, - has_layer, - group_layers - ), - spec!("layer.arrange.reverse", "Reverse", &["Layer", "Arrange"], None, "{}", two_plus, |s, _| reverse(s)), - spec!( - "layer.lockLayers", - "Lock Layers…", - &["Layer"], - None, - r##"{"transparency":bool?,"pixels":bool?,"position":bool?,"artboard":bool?,"all":bool?} (none given: toggle lock all)"##, - has_layer, - lock_layers - ), - spec!("layer.renameLayer", "Rename Layer", &["Layer"], None, r##"{"layer":id?,"name":str}"##, has_layer, rename_layer), - ] -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn merge_with_background_preserves_background() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 20, "height": 20})).unwrap(); - let bg_id = s.active().unwrap().doc.layers[0].id; - assert!(s.active().unwrap().doc.is_background(bg_id)); - let l1 = LayerId(s.execute("layer.new.layer", json!({"name": "Generative Fill"})).unwrap()["layer"].as_u64().unwrap()); - set_selection(&mut s, vec![bg_id, l1], Some(l1), Some(bg_id)).unwrap(); - let res = s.execute("layer.mergeLayers", json!({})).unwrap(); - let mid = LayerId(res["layer"].as_u64().unwrap()); - assert_eq!(mid, bg_id); - let doc = &s.active().unwrap().doc; - assert_eq!(doc.layers.len(), 1); - assert!(doc.is_background(mid)); - assert_eq!(doc.layers[0].name, "Background"); - } - - #[test] - fn duplicates_are_numbered_not_stacked() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 20, "height": 20})).unwrap(); - s.execute("layer.new.layer", json!({"name": "Layer 1"})).unwrap(); - let name = |s: &Session| { - let st = s.active().unwrap(); - st.doc.layer(st.active_layer.unwrap()).unwrap().name.clone() - }; - s.execute("layer.duplicate", json!({})).unwrap(); - assert_eq!(name(&s), "Layer 1 copy"); - // Duplicating the copy (the active layer) numbers it rather than adding "copy" again. - s.execute("layer.duplicate", json!({})).unwrap(); - assert_eq!(name(&s), "Layer 1 copy 2"); - s.execute("layer.duplicate", json!({})).unwrap(); - assert_eq!(name(&s), "Layer 1 copy 3"); - let doc = &s.active().unwrap().doc; - assert_eq!(doc.copy_name("Layer 1"), "Layer 1 copy 4"); - // Names that merely contain "copy" keep it. - assert_eq!(doc.copy_name("Copywriting"), "Copywriting copy"); - assert_eq!(doc.copy_name("A copyedit"), "A copyedit copy"); - } - - fn session(depth: u32) -> Session { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 100, "height": 80, "depth": depth})).unwrap(); - s - } - - fn doc(s: &Session) -> &Document { - &s.active().unwrap().doc - } - - /// New pixel layer with an opaque red rectangle. - fn rect_layer(s: &mut Session, r: Rect) -> LayerId { - let id = LayerId(s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap()); - s.edit("paint", |doc, _| { - doc.layer_mut(id).unwrap().surface_mut().unwrap().fill_rect(r, &[1.0, 0.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - id - } - - fn bounds(s: &Session, id: LayerId) -> Rect { - layer_bounds(doc(s).layer(id).unwrap()).unwrap() - } - - fn sel(s: &Session) -> Vec { - selected(s) - } - - fn damage(s: &Session) -> Option { - s.active().unwrap().last_damage - } - - /// A Photoshop action's nudge in points moves whole pixels at the document's resolution: - /// 0.36 pt is 1 px at 200 ppi and 1.5 → 2 px at 300 ppi. - #[test] - fn translate_in_points_follows_the_resolution() { - for (res, moved) in [(200, 1), (300, 2), (72, 0)] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 100, "height": 80, "resolution": res})).unwrap(); - let a = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); - s.execute("layer.translate", json!({"dx": 0.36, "dy": -0.36, "units": "pt"})).unwrap(); - assert_eq!(bounds(&s, a), Rect::new(10 + moved, 10 - moved, 20 + moved, 20 - moved), "{res} ppi"); - } - let mut s = session(8); - rect_layer(&mut s, Rect::new(10, 10, 20, 20)); - for bad in [json!({"dx": 1, "units": "in"}), json!({"dx": "x", "units": "pt"}), json!({"dx": 1e300, "units": "pt"})] { - assert!(s.execute("layer.translate", bad.clone()).is_err(), "{bad}"); - } - } - - /// `remove` deselects a selected layer, leaves an unselected one alone and never empties the - /// selection. - #[test] - fn select_remove_takes_a_layer_out_of_the_selection() { - let mut s = session(8); - let a = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); - let b = rect_layer(&mut s, Rect::new(30, 10, 40, 20)); - let c = rect_layer(&mut s, Rect::new(50, 10, 60, 20)); - s.execute("layer.select", json!({"layer": a.0})).unwrap(); - s.execute("layer.select", json!({"layer": b.0, "mode": "add"})).unwrap(); - s.execute("layer.select", json!({"layer": c.0, "mode": "remove"})).unwrap(); - assert_eq!(sel(&s).len(), 2, "an unselected layer stays out"); - s.execute("layer.select", json!({"layer": b.0, "mode": "remove"})).unwrap(); - assert_eq!(sel(&s), vec![a]); - s.execute("layer.select", json!({"layer": a.0, "mode": "remove"})).unwrap(); - assert_eq!(sel(&s), vec![a], "the last selected layer stays"); - } - - /// A mask with its chain off stays put while the layer moves; a linked one moves along. - #[test] - fn translate_leaves_an_unlinked_mask_in_place() { - for depth in [8, 16] { - let mut s = session(depth); - let a = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); - s.execute("layer.select", json!({"layer": a.0})).unwrap(); - s.execute("layer.layerMask.hideAll", json!({})).unwrap(); - s.edit("mask", |doc, _| { - doc.layer_mut(a).unwrap().mask.as_mut().unwrap().surface.fill_rect(Rect::new(12, 12, 18, 18), &[1.0]); - Ok(()) - }) - .unwrap(); - let mval = |s: &Session, x, y| doc(s).layer(a).unwrap().mask.as_ref().unwrap().surface.sample_channel(x, y, 0); - s.execute("layer.layerMask.linked", json!({"linked": false})).unwrap(); - s.execute("layer.translate", json!({"dx": 30, "dy": 0})).unwrap(); - assert!(mval(&s, 14, 14) > 0.9, "{depth}-bit: unlinked mask stays"); - assert!(mval(&s, 44, 14) < 0.1); - s.execute("edit.undo", json!({})).unwrap(); - s.execute("layer.layerMask.linked", json!({"linked": true})).unwrap(); - s.execute("layer.translate", json!({"dx": 30, "dy": 0})).unwrap(); - assert!(mval(&s, 44, 14) > 0.9, "{depth}-bit: linked mask moves"); - } - } - - /// Aimed at the mask, a move shifts an unlinked mask alone and leaves a linked one with its layer. - #[test] - fn translate_with_the_mask_targeted_moves_an_unlinked_mask_alone() { - for depth in [8, 16] { - let mut s = session(depth); - let a = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); - s.execute("layer.select", json!({"layer": a.0})).unwrap(); - s.execute("layer.layerMask.hideAll", json!({})).unwrap(); - s.edit("mask", |doc, _| { - doc.layer_mut(a).unwrap().mask.as_mut().unwrap().surface.fill_rect(Rect::new(12, 12, 18, 18), &[1.0]); - Ok(()) - }) - .unwrap(); - let mval = |s: &Session, x, y| doc(s).layer(a).unwrap().mask.as_ref().unwrap().surface.sample_channel(x, y, 0); - // Linked: the layer and its mask move together. - s.execute("layer.translate", json!({"dx": 30, "dy": 0, "target": "mask"})).unwrap(); - assert_eq!(bounds(&s, a), Rect::new(40, 10, 50, 20), "{depth}-bit"); - assert!(mval(&s, 44, 14) > 0.9); - s.execute("layer.layerMask.linked", json!({"linked": false})).unwrap(); - s.execute("layer.translate", json!({"dx": -30, "dy": 0, "target": "mask"})).unwrap(); - assert_eq!(bounds(&s, a), Rect::new(40, 10, 50, 20), "{depth}-bit: the layer stays"); - assert!(mval(&s, 14, 14) > 0.9, "the mask moved"); - assert!(mval(&s, 44, 14) < 0.1); - s.execute("edit.undo", json!({})).unwrap(); - assert!(mval(&s, 44, 14) > 0.9, "undo puts the mask back"); - } - } - - #[test] - fn moves_and_layer_props_report_only_their_area() { - let mut s = session(8); - let a = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); - s.execute("layer.select", json!({"layer": a.0})).unwrap(); - s.execute("layer.translate", json!({"dx": 5, "dy": -3})).unwrap(); - assert_eq!(damage(&s), Some(Rect::new(10, 7, 25, 20)), "where the layer was and is"); - s.execute("layer.setProps", json!({"layer": a.0, "visible": false})).unwrap(); - assert_eq!(damage(&s), Some(Rect::new(15, 7, 25, 17))); - s.execute("layer.setProps", json!({"layer": a.0, "opacity": 0.5, "blend": "Multiply"})).unwrap(); - assert_eq!(damage(&s), Some(Rect::new(15, 7, 25, 17))); - // Clipping changes reach the layers around: everything. - s.execute("layer.setProps", json!({"layer": a.0, "clipped": true})).unwrap(); - assert_eq!(damage(&s), None); - // An adjustment layer changes everything beneath it. - let adj = s.execute("layer.newAdjustmentLayer.invert", json!({})).unwrap()["layer"].as_u64().unwrap(); - s.execute("layer.setProps", json!({"layer": adj, "visible": false})).unwrap(); - assert_eq!(damage(&s), None); - // The Background (opaque everywhere): everything. - let bg = doc(&s).layers[0].id; - s.execute("layer.setProps", json!({"layer": bg.0, "opacity": 0.5})).unwrap(); - let all = doc(&s).bounds(); - assert!(damage(&s).is_none_or(|r| r.contains_rect(&all)), "{:?}", damage(&s)); - // Bad params still fail cleanly. - assert!(s.execute("layer.setProps", json!({"layer": u64::MAX, "visible": true})).is_err()); - assert!(s.execute("layer.translate", json!({"layer": u64::MAX, "dx": 1})).is_err()); - } - - /// #1771: a new empty layer or group changes no pixels, so it (and undoing or redoing it) - /// must not make the canvas recomposite every layer of the document. - #[test] - fn new_empty_layers_and_groups_damage_nothing() { - for depth in [8, 16, 32] { - let mut s = session(depth); - let a = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); - let composite = |s: &Session| photocraft_compose::render(doc(s), doc(s).bounds()); - let shown = composite(&s); - s.execute("layer.new.layer", json!({})).unwrap(); - assert_eq!(damage(&s), Some(Rect::EMPTY), "{depth}-bit new layer"); - assert_eq!(composite(&s), shown, "an empty layer changes no pixels"); - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(damage(&s), Some(Rect::EMPTY), "{depth}-bit undo New Layer"); - s.execute("edit.redo", json!({})).unwrap(); - assert_eq!(damage(&s), Some(Rect::EMPTY), "{depth}-bit redo New Layer"); - s.execute("layer.new.group", json!({})).unwrap(); - assert_eq!(damage(&s), Some(Rect::EMPTY), "{depth}-bit new group"); - // Inside a group too. - let child = s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap(); - let g = s.execute("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap(); - s.execute("layer.select", json!({"layer": child})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - assert_eq!(damage(&s), Some(Rect::EMPTY), "{depth}-bit new layer in a group"); - assert!(doc(&s).layer(LayerId(g)).and_then(Layer::children).is_some_and(|c| c.len() == 2)); - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(damage(&s), Some(Rect::EMPTY)); - // Undoing a step that painted still reports that area, not nothing. - s.execute("layer.select", json!({"layer": a.0})).unwrap(); - s.execute("layer.translate", json!({"dx": 5, "dy": 0})).unwrap(); - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(damage(&s), Some(Rect::new(10, 10, 25, 20))); - } - } - - #[test] - fn new_layers_that_change_clipping_recomposite_everything() { - let mut s = session(8); - let base = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); - let clipped = rect_layer(&mut s, Rect::new(0, 0, 100, 80)); - s.edit("green", |doc, _| { - doc.layer_mut(clipped).unwrap().surface_mut().unwrap().fill_rect(Rect::new(0, 0, 100, 80), &[0.0, 1.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - s.execute("layer.setProps", json!({"layer": clipped.0, "clipped": true})).unwrap(); - // New Layer between a clipping base and its clipped layer joins their clip group (#2203), - // so it draws nothing; an empty layer there that stayed unclipped would become their base. - s.execute("layer.select", json!({"layer": base.0})).unwrap(); - let shown = photocraft_compose::render(doc(&s), doc(&s).bounds()); - let before = doc(&s).clone(); - s.execute("layer.new.layer", json!({})).unwrap(); - assert_eq!(damage(&s), Some(Rect::EMPTY)); - assert_eq!(photocraft_compose::render(doc(&s), doc(&s).bounds()), shown); - let mut split = before.clone(); - split.insert_above(Some(base), Layer::raster("split", split.pixel_format())); - assert_ne!(photocraft_compose::render(&split, split.bounds()), shown); - assert_eq!(step_damage(&before, &split), None); - assert_eq!(step_damage(&split, &before), None); - s.execute("edit.undo", json!({})).unwrap(); - // A step that adds a layer with pixels (Layer via Copy, paste…) changes where it draws. - let before = doc(&s).clone(); - let mut after = before.clone(); - let mut l = Layer::raster("painted", after.pixel_format()); - l.surface_mut().unwrap().fill_rect(Rect::new(1, 1, 2, 2), &[0.0, 1.0, 0.0, 1.0]); - after.insert_above(None, l); - assert_eq!(step_damage(&before, &after), Some(Rect::new(1, 1, 2, 2))); - assert_eq!(step_damage(&after, &before), Some(Rect::new(1, 1, 2, 2))); - // Unless it becomes the base of clipped layers above it. - let mut based = before.clone(); - let mut l = Layer::raster("base", based.pixel_format()); - l.surface_mut().unwrap().fill_rect(Rect::new(1, 1, 2, 2), &[0.0, 1.0, 0.0, 1.0]); - let under = based.layers.iter().position(|l| l.id == clipped).unwrap(); - based.layers.insert(under, l); - assert_eq!(step_damage(&before, &based), None); - assert_eq!(step_damage(&based, &before), None); - // An adjustment reaches every pixel below it. - let mut adjusted = before.clone(); - adjusted.insert_above(None, Layer::new("inv", LayerContent::Adjustment(photocraft_doc::Adjustment::Invert))); - assert_eq!(step_damage(&before, &adjusted), None); - assert_eq!(step_damage(&adjusted, &before), None); - // Empty layers draw nothing, in any blend mode. - let mut styled = before.clone(); - let mut l = Layer::raster("styled", styled.pixel_format()); - l.blend = photocraft_doc::BlendMode::Multiply; - styled.insert_above(None, l); - assert_eq!(step_damage(&before, &styled), Some(Rect::EMPTY)); - let mut plain = before.clone(); - plain.insert_above(None, Layer::raster("plain", plain.pixel_format())); - assert_eq!(step_damage(&before, &plain), Some(Rect::EMPTY)); - assert_eq!(step_damage(&plain, &before), Some(Rect::EMPTY)); - } - - /// #6535: hiding or showing an adjustment clipped to a layer recomposites only that base's - /// area, also on undo and redo and inside a group, and recompositing just that area gives - /// the same canvas as a full recomposite. - #[test] - fn toggling_a_clipped_adjustment_damages_only_its_base() { - let all = |s: &Session| photocraft_compose::render(doc(s), doc(s).bounds()); - // Recomposite only the reported damage over the previous canvas, as the view does. - let patched = |s: &Session, prev: &photocraft_compose::Buffer| { - let r = damage(s).expect("bounded damage"); - let mut out = prev.clone(); - if r.is_empty() { - return out; - } - let part = photocraft_compose::render(doc(s), r); - let w = out.rect.width() as usize; - for y in r.y0..r.y1 { - for x in r.x0..r.x1 { - let i = (y - out.rect.y0) as usize * w + (x - out.rect.x0) as usize; - let k = (y - r.y0) as usize * r.width() as usize + (x - r.x0) as usize; - out.px[i] = part.px[k]; - } - } - out - }; - for grouped in [false, true] { - let mut s = session(16); - let base_rect = Rect::new(10, 10, 30, 25); - let base = rect_layer(&mut s, base_rect); - let adj = LayerId(s.execute("layer.newAdjustmentLayer.invert", json!({})).unwrap()["layer"].as_u64().unwrap()); - s.execute("layer.createClippingMask", json!({"layer": adj.0})).unwrap(); - assert!(doc(&s).layer(adj).unwrap().clipped); - if grouped { - s.execute("layer.select", json!({"layer": base.0})).unwrap(); - s.execute("layer.select", json!({"layer": adj.0, "mode": "toggle"})).unwrap(); - s.execute("layer.groupLayers", json!({})).unwrap(); - assert!(doc(&s).path_of(adj).unwrap().len() == 2, "the pair sits in a group"); - } - let shown = all(&s); - s.execute("layer.hideLayers", json!({"layer": adj.0})).unwrap(); - assert!(!doc(&s).layer(adj).unwrap().visible); - assert_eq!(damage(&s), Some(base_rect), "grouped: {grouped}"); - let hidden = all(&s); - assert_ne!(hidden, shown); - assert_eq!(patched(&s, &shown), hidden); - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(damage(&s), Some(base_rect)); - assert_eq!(patched(&s, &hidden), shown); - s.execute("edit.redo", json!({})).unwrap(); - assert_eq!(damage(&s), Some(base_rect)); - assert_eq!(patched(&s, &shown), hidden); - s.execute("layer.showLayers", json!({"layer": adj.0})).unwrap(); - assert_eq!(damage(&s), Some(base_rect)); - assert_eq!(patched(&s, &hidden), shown); - // layer.setProps reports its own damage. - s.execute("layer.setProps", json!({"layer": adj.0, "visible": false})).unwrap(); - assert_eq!(damage(&s), Some(base_rect)); - assert_eq!(patched(&s, &shown), hidden); - // Unclipped, the adjustment still reaches the whole canvas. - s.execute("layer.setProps", json!({"layer": adj.0, "visible": true})).unwrap(); - s.execute("layer.releaseClippingMask", json!({"layer": adj.0})).unwrap(); - s.execute("layer.hideLayers", json!({"layer": adj.0})).unwrap(); - assert_eq!(damage(&s), None); - } - } - - /// #6535: hiding a clipped adjustment inside a pass-through group that is itself a clip base - /// can switch the group between isolated and pass-through rendering, so the step damages the - /// whole group, on undo, redo and when the adjustment is deleted too. - #[test] - fn clipped_adjustment_in_pass_through_clip_base_damages_its_group() { - use photocraft_doc::{Adjustment, BlendMode}; - let solid = |name: &str, r: Rect, blend: BlendMode| { - let mut l = Layer::raster(name, PixelFormat::RGBA8); - l.surface_mut().unwrap().fill_rect(r, &[0.5, 0.5, 0.5, 1.0]); - l.blend = blend; - l - }; - let mut before = Document::with_background( - "t", - photocraft_geom::Size::new(10, 8), - photocraft_doc::ColorMode::Rgb, - photocraft_doc::SampleType::U8, - photocraft_color::Color::WHITE, - ); - before.layers.push(solid("bg", before.bounds(), BlendMode::Normal)); - let mut a = Layer::new("A", LayerContent::Adjustment(Adjustment::Invert)); - a.clipped = true; - let mut g = Layer::group("G", vec![solid("P", Rect::new(2, 1, 4, 3), BlendMode::Normal), a, solid("Q", Rect::new(6, 4, 8, 6), BlendMode::Multiply)]); - g.blend = BlendMode::PassThrough; - before.layers.push(g); - let mut x = solid("X", Rect::new(2, 1, 3, 2), BlendMode::Normal); - x.clipped = true; - before.layers.push(x); - let mut after = before.clone(); - let LayerContent::Group(g) = &mut after.layers[2].content else { panic!("group") }; - g.children[1].visible = false; - let group = Some(Rect::new(2, 1, 8, 6)); - assert_eq!(step_damage(&before, &after), group); - assert_eq!(step_damage(&after, &before), group); - let mut deleted = before.clone(); - let LayerContent::Group(g) = &mut deleted.layers[2].content else { panic!("group") }; - g.children.remove(1); - assert_eq!(step_damage(&before, &deleted), group); - let LayerContent::Group(g) = &before.layers[2].content else { panic!("group") }; - let ids = [g.children[1].id]; - assert_eq!(layers_damage(&before, &after, &ids), group); - // Without the layer clipped to the group it stays pass-through: just A's base. - before.layers.truncate(3); - after.layers.truncate(3); - assert_eq!(step_damage(&before, &after), Some(Rect::new(2, 1, 4, 3))); - } - - /// #2883 (P8/P9): a duplicate shares the source's tiles (no pixel copy) and recomposites only - /// where it draws; undo brings back exactly the old pixels. A copy that becomes the clipping - /// base of the layers above still recomposites everything. - #[test] - fn duplicate_shares_tiles_and_damages_only_the_copy() { - let render = |s: &Session| photocraft_compose::render(doc(s), doc(s).bounds()); - let tiles = - |s: &Session, id: LayerId| doc(s).layer(id).unwrap().surface().unwrap().tiles().map(|(c, t)| (*c, std::sync::Arc::as_ptr(t))).collect::>(); - for depth in [8, 16, 32] { - let mut s = session(depth); - let a = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); - s.execute("layer.setProps", json!({"layer": a.0, "opacity": 0.5})).unwrap(); - let shown = render(&s); - let copy = LayerId(s.execute("layer.duplicate", json!({"layer": a.0})).unwrap()["layer"].as_u64().unwrap()); - assert_eq!(damage(&s), Some(Rect::new(10, 10, 20, 20)), "{depth}-bit: only where the copy draws"); - assert!(!tiles(&s, a).is_empty()); - assert_eq!(tiles(&s, copy), tiles(&s, a), "{depth}-bit: the copy shares the source's tiles"); - let now = render(&s); - assert_ne!(now, shown, "the half-transparent copy darkens its area"); - let w = shown.rect.width() as usize; - for (i, (p, q)) in shown.px.iter().zip(&now.px).enumerate() { - if !Rect::new(10, 10, 20, 20).contains((i % w) as i32, (i / w) as i32) { - assert_eq!(p, q, "{depth}-bit: pixel {i} outside the damage changed"); - } - } - s.execute("edit.undo", json!({})).unwrap(); - assert!(doc(&s).layer(copy).is_none()); - assert_eq!(render(&s), shown); - // A clipping base's copy goes between it and its clipped layer and becomes their base. - let clipped = rect_layer(&mut s, Rect::new(0, 0, 50, 50)); - s.execute("layer.setProps", json!({"layer": clipped.0, "clipped": true})).unwrap(); - s.execute("layer.duplicate", json!({"layer": a.0})).unwrap(); - assert_eq!(damage(&s), None, "{depth}-bit: a new clipping base"); - } - } - - /// The composite of `after` equals `before`'s outside `damage`. - fn unchanged_outside(before: &Document, after: &Document, damage: Rect) -> bool { - let (x, y) = (photocraft_compose::render(before, before.bounds()), photocraft_compose::render(after, after.bounds())); - let w = before.bounds().width() as i32; - x.px.iter().zip(&y.px).enumerate().all(|(i, (p, q))| p == q || damage.contains(i as i32 % w, i as i32 / w)) - } - - /// Duplicate (one layer or several), paste and delete, and their undo and redo, recomposite - /// only where the layers draw; undoing a duplicate used to recomposite the whole document. - #[test] - fn duplicate_paste_and_delete_report_where_the_layer_draws() { - let mut s = session(8); - let a = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); - let full = doc(&s).bounds(); - let step = |s: &mut Session, id: &str, p: serde_json::Value| { - let before = doc(s).clone(); - s.execute(id, p).unwrap(); - let d = damage(s).unwrap_or_else(|| panic!("{id}: unbounded damage")); - assert!(d.width() < full.width(), "{id}: {d:?}"); - assert!(unchanged_outside(&before, doc(s), d), "{id}: pixels changed outside {d:?}"); - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(damage(s), Some(d), "undo {id}"); - s.execute("edit.redo", json!({})).unwrap(); - assert_eq!(damage(s), Some(d), "redo {id}"); - }; - step(&mut s, "layer.duplicate", json!({"layer": a.0})); - s.execute("layer.select", json!({"layer": a.0})).unwrap(); - s.execute("select.rect", json!({"x": 12, "y": 12, "width": 4, "height": 4})).unwrap(); - s.execute("edit.copy", json!({})).unwrap(); - s.execute("select.deselect", json!({})).unwrap(); - step(&mut s, "edit.paste", json!({})); - // Duplicating several selected layers reports where the copies draw, too. - let b = rect_layer(&mut s, Rect::new(30, 30, 40, 40)); - s.execute("layer.select", json!({"layer": a.0})).unwrap(); - s.execute("layer.select", json!({"layer": b.0, "mode": "add"})).unwrap(); - step(&mut s, "layer.duplicate", json!({})); - assert_eq!(damage(&s), Some(Rect::new(10, 10, 40, 40)), "both copies, nothing else"); - step(&mut s, "layer.delete", json!({"layer": a.0})); - } - - #[test] - fn the_move_preview_matches_the_move() { - let mut s = session(8); - let a = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); - let before = s.active().unwrap().doc.clone(); - let ids = move_targets(&before, &[a]); - let shown = moved(&before, &ids, 7, 4).unwrap(); - s.execute("layer.translate", json!({"layer": a.0, "dx": 7, "dy": 4})).unwrap(); - assert_eq!(layer_bounds(shown.layer(a).unwrap()), Some(bounds(&s, a))); - // Locked layers don't move in the preview either. - let mut locked = (*before).clone(); - locked.layer_mut(a).unwrap().locks.position = true; - assert!(moved(&locked, &ids, 1, 1).is_err()); - assert!(moved(&before, &[LayerId(u64::MAX)], 1, 1).is_err()); - } - - #[test] - fn move_stroked_shape_across_canvas_edge_matches_fresh_render() { - let mut s = session(8); - let id = LayerId( - s.execute("shape.create", json!({"kind": "rect", "rect": [10, 10, 30, 30], "stroke": {"width": 4, "color": "#ff0000"}})).unwrap()["layer"] - .as_u64() - .unwrap(), - ); - let before = doc(&s).clone(); - let ids = move_targets(&before, &[id]); - - // Drag the stroked shape across the left canvas boundary: - let moved_doc = moved(&before, &ids, -25, 0).unwrap(); - let moved_layer = moved_doc.layer(id).unwrap(); - let LayerContent::Shape(sh) = &moved_layer.content else { panic!("not a shape") }; - let cached = sh.cache.as_ref().expect("cached render"); - - let mut fresh_sh = sh.clone(); - crate::vector_cmds::refresh_shape(&moved_doc, &mut fresh_sh); - let fresh = fresh_sh.cache.as_ref().expect("fresh render"); - - assert_eq!(cached, fresh, "dragged shape cached render must match fresh render across canvas edge"); - - // Drag it back inside the canvas: - let moved_back = moved(&moved_doc, &ids, 30, 0).unwrap(); - let back_layer = moved_back.layer(id).unwrap(); - let LayerContent::Shape(back_sh) = &back_layer.content else { panic!("not a shape") }; - let back_cached = back_sh.cache.as_ref().expect("cached render"); - - let mut fresh_back = back_sh.clone(); - crate::vector_cmds::refresh_shape(&moved_back, &mut fresh_back); - let fresh_back_render = fresh_back.cache.as_ref().expect("fresh render"); - - assert_eq!(back_cached, fresh_back_render, "cached render must match fresh render when dragged back"); - } - - fn select_all(s: &mut Session, ids: &[LayerId]) { - s.execute("layer.select", json!({"layer": ids[0].0})).unwrap(); - for id in &ids[1..] { - s.execute("layer.select", json!({"layer": id.0, "mode": "toggle"})).unwrap(); - } - } - - #[test] - fn toggle_and_range_selection() { - let mut s = session(8); - let a = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); - let b = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); - let c = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); - let d = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); - assert_eq!(sel(&s), vec![d]); - s.execute("layer.select", json!({"layer": b.0, "mode": "toggle"})).unwrap(); - assert_eq!(sel(&s), vec![b, d]); - assert_eq!(s.active().unwrap().active_layer, Some(b)); - // Toggling the active layer off hands "active" to a remaining member. - s.execute("layer.select", json!({"layer": b.0, "mode": "toggle"})).unwrap(); - assert_eq!(sel(&s), vec![d]); - assert_eq!(s.active().unwrap().active_layer, Some(d)); - // The last selected layer can't be toggled off. - s.execute("layer.select", json!({"layer": d.0, "mode": "toggle"})).unwrap(); - assert_eq!(sel(&s), vec![d]); - // Range from the anchor (a) to c. - s.execute("layer.select", json!({"layer": a.0})).unwrap(); - s.execute("layer.select", json!({"layer": c.0, "mode": "range"})).unwrap(); - assert_eq!(sel(&s), vec![a, b, c]); - // A second ⇧-click re-ranges from the same anchor. - s.execute("layer.select", json!({"layer": b.0, "mode": "range"})).unwrap(); - assert_eq!(sel(&s), vec![a, b]); - assert!(s.execute("layer.select", json!({"layer": b.0, "mode": "bogus"})).is_err()); - // Selection changes are not edits. - let history = s.active().unwrap().history.entries().len(); - s.execute("select.allLayers", json!({})).unwrap(); - assert_eq!(sel(&s), vec![a, b, c, d], "Select All Layers skips the locked Background"); - s.execute("select.deselectLayers", json!({})).unwrap(); - assert!(sel(&s).is_empty()); - assert_eq!(s.active().unwrap().history.entries().len(), history); - // Nothing selected: a no-op, not an error (#2457). - s.execute("select.deselectLayers", json!({})).unwrap(); - assert_eq!(s.active().unwrap().history.entries().len(), history); - // An explicit layer needs no active layer. - s.execute("layer.hideLayers", json!({"layer": a.0})).unwrap(); - assert!(!s.active().unwrap().doc.layer(a).unwrap().visible); - s.execute("layer.renameLayer", json!({"layer": a.0, "name": "x"})).unwrap(); - assert_eq!(s.active().unwrap().doc.layer(a).unwrap().name, "x"); - s.execute("layer.showLayers", json!({"layer": a.0})).unwrap(); - assert!(s.active().unwrap().doc.layer(a).unwrap().visible); - assert!(s.execute("layer.hideLayers", json!({"layer": u64::MAX})).is_err()); - assert!(s.execute("layer.hideLayers", json!({})).is_err()); - assert!(!s.is_enabled("layer.align.topEdges")); - } - - #[test] - fn find_layers_by_name() { - let mut s = session(8); - let a = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); - let b = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); - s.execute("layer.renameLayer", json!({"layer": a.0, "name": "Sky photo"})).unwrap(); - s.execute("layer.renameLayer", json!({"layer": b.0, "name": "Photo of sea"})).unwrap(); - assert_eq!(doc(&s).layer(a).unwrap().name, "Sky photo"); - let r = s.execute("select.findLayers", json!({"name": "PHOTO"})).unwrap(); - assert_eq!(r["selected"], json!([a.0, b.0])); - assert!(s.execute("select.findLayers", json!({"name": "nothing"})).is_err()); - assert!(s.execute("layer.renameLayer", json!({})).is_err()); - } - - #[test] - fn rename_layer_keeps_surrounding_spaces() { - let mut s = session(8); - let a = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); - s.execute("layer.renameLayer", json!({"layer": a.0, "name": " black skin bw "})).unwrap(); - assert_eq!(doc(&s).layer(a).unwrap().name, " black skin bw "); - assert!(s.execute("layer.renameLayer", json!({"layer": a.0, "name": " "})).is_err()); - assert_eq!(doc(&s).layer(a).unwrap().name, " black skin bw "); - } - - #[test] - fn align_each_edge() { - for depth in [8, 16, 32] { - let cases: [(&str, [Rect; 2]); 6] = [ - ("topEdges", [Rect::new(10, 5, 20, 15), Rect::new(40, 5, 50, 25)]), - ("bottomEdges", [Rect::new(10, 20, 20, 30), Rect::new(40, 10, 50, 30)]), - // Union 5..30: centre 17.5; half-pixel offsets round towards the top. - ("verticalCenters", [Rect::new(10, 12, 20, 22), Rect::new(40, 7, 50, 27)]), - ("leftEdges", [Rect::new(10, 5, 20, 15), Rect::new(10, 10, 50, 30)]), - ("rightEdges", [Rect::new(40, 5, 50, 15), Rect::new(10, 10, 50, 30)]), - ("horizontalCenters", [Rect::new(25, 5, 35, 15), Rect::new(10, 10, 50, 30)]), - ]; - for (kind, want) in cases { - let mut s = session(depth); - let a = rect_layer(&mut s, Rect::new(10, 5, 20, 15)); - let b = rect_layer(&mut s, Rect::new(40, 10, 50, 30)); - // For the horizontal cases make b wide so it defines the target bounds. - if !matches!(kind, "topEdges" | "bottomEdges" | "verticalCenters") { - s.edit("wide", |doc, _| { - doc.layer_mut(b).unwrap().surface_mut().unwrap().fill_rect(Rect::new(10, 10, 50, 30), &[0.0, 1.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - } - select_all(&mut s, &[a, b]); - s.execute(&format!("layer.align.{kind}"), json!({})).unwrap(); - assert_eq!([bounds(&s, a), bounds(&s, b)], want, "{kind} at {depth}-bit"); - // Pixels moved, not just bounds. - let r = want[0]; - assert_eq!(doc(&s).layer(a).unwrap().surface().unwrap().pixel(r.x0, r.y0)[..4], [1.0, 0.0, 0.0, 1.0]); - // One undo restores the original positions. - s.undo(); - assert_eq!(bounds(&s, a), Rect::new(10, 5, 20, 15)); - } - } - } - - #[test] - fn align_single_layer_to_selection() { - for depth in [8, 16, 32] { - let mut s = session(depth); - let a = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); - assert!(s.is_enabled("layer.align.leftEdges"), "one layer aligns to the canvas"); - s.execute("select.rect", json!({"x": 50, "y": 40, "width": 30, "height": 30})).unwrap(); - assert!(s.is_enabled("layer.align.leftEdges")); - s.execute("layer.align.rightEdges", json!({})).unwrap(); - assert_eq!(bounds(&s, a), Rect::new(70, 10, 80, 20)); - s.execute("layer.align.verticalCenters", json!({})).unwrap(); - assert_eq!(bounds(&s, a), Rect::new(70, 50, 80, 60)); - s.execute("layer.align.topEdges", json!({"to": "canvas"})).unwrap(); - assert_eq!(bounds(&s, a), Rect::new(70, 0, 80, 10)); - } - } - - #[test] - fn align_single_layer_to_canvas() { - // Photoshop: a single selected layer with no active selection aligns to the canvas. - let mut s = session(8); // 100 x 80 - let a = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); // 10 x 10 - assert!(s.is_enabled("layer.align.horizontalCenters")); - s.execute("layer.align.horizontalCenters", json!({})).unwrap(); - assert_eq!(bounds(&s, a), Rect::new(45, 10, 55, 20), "centred on the 100px-wide canvas"); - s.execute("layer.align.verticalCenters", json!({})).unwrap(); - assert_eq!(bounds(&s, a), Rect::new(45, 35, 55, 45), "centred on the 80px-tall canvas"); - s.execute("layer.align.leftEdges", json!({})).unwrap(); - assert_eq!(bounds(&s, a), Rect::new(0, 35, 10, 45), "left edge to the canvas"); - } - - #[test] - fn distribute_uneven_layers() { - for depth in [8, 16, 32] { - let mut s = session(depth); - let a = rect_layer(&mut s, Rect::new(0, 0, 10, 10)); - let b = rect_layer(&mut s, Rect::new(12, 0, 32, 10)); // 20 wide - let c = rect_layer(&mut s, Rect::new(70, 0, 100, 10)); // 30 wide - select_all(&mut s, &[a, b, c]); - // Undo targets the layers its state had when it was created (#495): reselect. - assert!(s.is_enabled("layer.distribute.leftEdges")); - s.execute("layer.distribute.leftEdges", json!({})).unwrap(); - assert_eq!(bounds(&s, b), Rect::new(35, 0, 55, 10), "left edges 0, 35, 70"); - s.undo(); - select_all(&mut s, &[a, b, c]); - s.execute("layer.distribute.horizontalCenters", json!({})).unwrap(); - // centres 5 and 85 → middle centre 45 - assert_eq!(bounds(&s, b), Rect::new(35, 0, 55, 10)); - s.undo(); - select_all(&mut s, &[a, b, c]); - s.execute("layer.distribute.rightEdges", json!({})).unwrap(); - // right edges 10 and 100 → 55 - assert_eq!(bounds(&s, b), Rect::new(35, 0, 55, 10)); - s.undo(); - select_all(&mut s, &[a, b, c]); - s.execute("layer.distribute.horizontally", json!({})).unwrap(); - // span 100, widths 60 → gaps of 20: b at 30..50 - assert_eq!(bounds(&s, b), Rect::new(30, 0, 50, 10)); - assert_eq!(bounds(&s, a), Rect::new(0, 0, 10, 10)); - assert_eq!(bounds(&s, c), Rect::new(70, 0, 100, 10)); - s.undo(); - assert_eq!(bounds(&s, b), Rect::new(12, 0, 32, 10)); - } - // Vertical: tall layers with uneven heights. - let mut s = session(8); - let a = rect_layer(&mut s, Rect::new(0, 0, 10, 10)); - let b = rect_layer(&mut s, Rect::new(0, 50, 10, 54)); - let c = rect_layer(&mut s, Rect::new(0, 60, 10, 80)); - select_all(&mut s, &[a, b, c]); - s.execute("layer.distribute.vertically", json!({})).unwrap(); - // span 80, heights 34 → gaps 23: b at 33..37 - assert_eq!(bounds(&s, b), Rect::new(0, 33, 10, 37)); - s.undo(); - select_all(&mut s, &[a, b, c]); - s.execute("layer.distribute.topEdges", json!({})).unwrap(); - assert_eq!(bounds(&s, b), Rect::new(0, 30, 10, 34)); - s.undo(); - select_all(&mut s, &[a, b, c]); - s.execute("layer.distribute.bottomEdges", json!({})).unwrap(); - assert_eq!(bounds(&s, b), Rect::new(0, 41, 10, 45)); - s.undo(); - select_all(&mut s, &[a, b, c]); - s.execute("layer.distribute.verticalCenters", json!({})).unwrap(); - // centres 5 and 70 → 37.5, b is 4 tall → top 35.5 → rounds to 36 (35 for ties down) - let y0 = bounds(&s, b).y0; - assert!((35..=36).contains(&y0), "{y0}"); - // Two layers can't be distributed. - select_all(&mut s, &[a, b]); - assert!(!s.is_enabled("layer.distribute.leftEdges")); - } - - #[test] - fn merge_keeps_pixels_outside_the_canvas() { - // #5067: the merged layer was cropped to the 100x80 canvas. - let mut s = session(8); - let a = rect_layer(&mut s, Rect::new(-30, -20, 10, 10)); - let b = rect_layer(&mut s, Rect::new(90, 70, 140, 120)); - select_all(&mut s, &[a, b]); - let m = LayerId(s.execute("layer.mergeLayers", json!({})).unwrap()["layer"].as_u64().unwrap()); - let ml = doc(&s).layer(m).unwrap(); - assert_eq!(layer_bounds(ml).unwrap(), Rect::new(-30, -20, 140, 120)); - assert_eq!(ml.surface().unwrap().pixel(-10, -5)[3], 1.0); - assert_eq!(ml.surface().unwrap().pixel(130, 110)[3], 1.0); - } - - #[test] - fn merge_down_and_merge_group_keep_pixels_outside_the_canvas() { - let mut s = session(8); - let a = rect_layer(&mut s, Rect::new(-30, -20, 10, 10)); - let b = rect_layer(&mut s, Rect::new(90, 70, 140, 120)); - s.execute("layer.mergeDown", json!({"layer": b.0})).unwrap(); - assert_eq!(layer_bounds(doc(&s).layer(a).unwrap()).unwrap(), Rect::new(-30, -20, 140, 120)); - - let mut s = session(8); - let a = rect_layer(&mut s, Rect::new(-30, -20, 10, 10)); - let b = rect_layer(&mut s, Rect::new(90, 70, 140, 120)); - select_all(&mut s, &[a, b]); - let g = LayerId(s.execute("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap()); - s.execute("layer.mergeGroup", json!({"layer": g.0})).unwrap(); - assert_eq!(layer_bounds(doc(&s).layer(g).unwrap()).unwrap(), Rect::new(-30, -20, 140, 120)); - } - - #[test] - fn merge_selected_into_top_most() { - for depth in [8, 16, 32] { - let mut s = session(depth); - let a = rect_layer(&mut s, Rect::new(0, 0, 10, 10)); - let b = rect_layer(&mut s, Rect::new(20, 0, 30, 10)); - let c = rect_layer(&mut s, Rect::new(40, 0, 50, 10)); - s.execute("layer.renameLayer", json!({"layer": c.0, "name": "Top"})).unwrap(); - select_all(&mut s, &[a, c]); - let before = doc(&s).layer_count(); - let m = LayerId(s.execute("layer.mergeLayers", json!({})).unwrap()["layer"].as_u64().unwrap()); - let d = doc(&s); - assert_eq!(d.layer_count(), before - 1); - let ml = d.layer(m).unwrap(); - assert_eq!(ml.name, "Top"); - assert_eq!(layer_bounds(ml).unwrap(), Rect::new(0, 0, 50, 10)); - assert_eq!(ml.surface().unwrap().pixel(5, 5)[..4], [1.0, 0.0, 0.0, 1.0]); - assert_eq!(ml.surface().unwrap().pixel(25, 5)[3], 0.0, "b was not merged"); - assert!(d.layer(b).is_some() && d.layer(a).is_none()); - assert_eq!(d.layers.last().unwrap().id, m, "merged layer sits where the top-most was"); - assert_eq!(sel(&s), vec![m]); - s.undo(); - assert_eq!(doc(&s).layer_count(), before); - assert_eq!(sel(&s), vec![a, c], "undo selects the layers that were merged"); - // One layer selected: Merge Down. - s.execute("layer.select", json!({"layer": c.0})).unwrap(); - s.execute("layer.mergeLayers", json!({})).unwrap(); - assert_eq!(doc(&s).layer_count(), before - 1); - } - } - - #[test] - fn merging_group_children_preserves_their_composite() { - for depth in [8, 16, 32] { - let mut s = session(depth); - let lower = rect_layer(&mut s, Rect::new(10, 12, 40, 42)); - let upper = rect_layer(&mut s, Rect::new(25, 20, 55, 50)); - select_all(&mut s, &[lower, upper]); - let group = LayerId(s.execute("layer.groupLayers", json!({"name": "Merge test group"})).unwrap()["layer"].as_u64().unwrap()); - let doc_before = doc(&s); - let expected = photocraft_compose::render(doc_before, doc_before.bounds()); - let children = doc_before.layer(group).unwrap().children().unwrap().iter().map(|layer| layer.id).collect::>(); - - select_all(&mut s, &children); - s.execute("layer.mergeLayers", json!({})).unwrap(); - let doc_after = doc(&s); - let actual = photocraft_compose::render(doc_after, doc_after.bounds()); - assert_eq!(actual, expected, "depth {depth}: group merge changed rendered pixels"); - assert_eq!(doc_after.layer(group).unwrap().children().unwrap().len(), 1); - } - } - - #[test] - fn merging_keeps_layer_effects_outside_the_pixels() { - // A drop shadow reaches past the layer's pixels; the merge must render that far. - for depth in [8, 16, 32] { - let mut s = session(depth); - let lower = rect_layer(&mut s, Rect::new(10, 10, 30, 30)); - let upper = rect_layer(&mut s, Rect::new(40, 20, 60, 40)); - s.execute("layer.layerStyle.dropShadow", json!({"layer": upper.0, "blend": "normal", "distance": 12, "size": 4})).unwrap(); - let before = photocraft_compose::render(doc(&s), doc(&s).bounds()); - select_all(&mut s, &[lower, upper]); - s.execute("layer.mergeLayers", json!({})).unwrap(); - let after = photocraft_compose::render(doc(&s), doc(&s).bounds()); - let worst = before.px.iter().zip(&after.px).map(|(a, b)| a.iter().zip(b).map(|(x, y)| (x - y).abs()).fold(0.0f32, f32::max)).fold(0.0f32, f32::max); - assert!(worst <= 1.5 / 255.0, "depth {depth}: merge layers dropped the shadow (off by {worst})"); - } - } - - #[test] - fn merging_a_group_down_preserves_the_composite() { - for depth in [8, 16, 32] { - let mut s = session(depth); - let lower = rect_layer(&mut s, Rect::new(10, 12, 50, 52)); - let child_a = rect_layer(&mut s, Rect::new(24, 20, 64, 60)); - let child_b = rect_layer(&mut s, Rect::new(35, 28, 75, 68)); - select_all(&mut s, &[child_a, child_b]); - let group = LayerId(s.execute("layer.groupLayers", json!({"name": "Merge down group"})).unwrap()["layer"].as_u64().unwrap()); - let doc_before = doc(&s); - let expected = photocraft_compose::render(doc_before, doc_before.bounds()); - - s.execute("layer.mergeDown", json!({"layer": group.0})).unwrap(); - let doc_after = doc(&s); - let actual = photocraft_compose::render(doc_after, doc_after.bounds()); - assert_eq!(actual, expected, "depth {depth}: group merge down changed rendered pixels"); - assert!(doc_after.layer(lower).is_some()); - assert!(doc_after.layer(group).is_none()); - } - } - - #[test] - fn a_locked_group_locks_its_contents() { - let mut s = session(8); - let a = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); - let g = s.execute("layer.new.groupFromLayers", json!({})).unwrap()["layer"].as_u64().unwrap(); - s.execute("layer.setProps", json!({"layer": g, "locked": true})).unwrap(); - s.execute("layer.select", json!({"layer": a.0})).unwrap(); - for (cmd, p) in [ - ("layer.translate", json!({"dx": 1})), - ("paint.stroke", json!({"points": [[2, 2], [4, 4]]})), - ("edit.fill", json!({"color": "#00ff00"})), - ("edit.transform.flipHorizontal", json!({})), - ] { - assert!(s.execute(cmd, p).is_err(), "{cmd} edited a layer in a locked group"); - } - // Unlocking the group releases its contents. - s.execute("layer.setProps", json!({"layer": g, "locked": false})).unwrap(); - s.execute("layer.translate", json!({"dx": 1})).unwrap(); - assert_eq!(bounds(&s, a), Rect::new(1, 0, 6, 5)); - } - - #[test] - fn a_locked_group_keeps_a_grouped_background_locked() { - let mut s = session(8); - let bg = doc(&s).layers[0].id; - s.execute("layer.select", json!({"layer": bg.0})).unwrap(); - let g = s.execute("layer.new.groupFromLayers", json!({})).unwrap()["layer"].as_u64().unwrap(); - s.execute("layer.setProps", json!({"layer": g, "locked": true})).unwrap(); - s.execute("layer.select", json!({"layer": bg.0})).unwrap(); - for (cmd, p) in [ - ("edit.transform.flipHorizontal", json!({})), - ("edit.transform.warp", json!({"style": "flag", "bend": 50})), - ("edit.puppetWarp", json!({"pins": [{"src": [30, 25], "dst": [36, 29]}]})), - ] { - let e = s.execute(cmd, p).unwrap_err().to_string(); - assert!(e.contains("locked"), "{cmd}: {e}"); - assert_eq!(doc(&s).layer(bg).unwrap().name, "Background", "{cmd}"); - } - } - - #[test] - fn group_from_layers_preserves_order() { - let mut s = session(8); - let a = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); - let b = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); - let c = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); - let d = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); - select_all(&mut s, &[c, a]); - let g = LayerId(s.execute("layer.new.groupFromLayers", json!({"name": "Pair"})).unwrap()["layer"].as_u64().unwrap()); - let docu = doc(&s); - let gl = docu.layer(g).unwrap(); - assert_eq!(gl.name, "Pair"); - assert!(matches!(&gl.content, LayerContent::Group(gr) if !gr.expanded), "created collapsed"); - assert_eq!(gl.children().unwrap().iter().map(|l| l.id).collect::>(), vec![a, c]); - // Root (bottom-to-top): Background, b, Pair (where c was), d. - assert_eq!(docu.layers.iter().map(|l| l.id).skip(1).collect::>(), vec![b, g, d]); - assert_eq!(sel(&s), vec![g]); - s.undo(); - assert_eq!(doc(&s).layers.len(), 5); - // ⌘G with several selected groups them too. - select_all(&mut s, &[b, d]); - let g = LayerId(s.execute("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap()); - assert_eq!(doc(&s).layers.len(), 4); - // Both create the group collapsed, as Photoshop does (#5571). - assert!(matches!(&doc(&s).layer(g).unwrap().content, LayerContent::Group(gr) if !gr.expanded)); - } - - #[test] - fn grouping_is_capped_at_the_document_nesting_limit() { - let mut s = session(8); - let a = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); - select_all(&mut s, &[a]); - for _ in 0..photocraft_doc::MAX_GROUP_DEPTH { - s.execute("layer.groupLayers", json!({})).unwrap(); - } - assert_eq!(doc(&s).max_group_depth(), photocraft_doc::MAX_GROUP_DEPTH); - // One more wrapping group would pass the cap: rejected, document untouched. - let err = s.execute("layer.groupLayers", json!({})).unwrap_err(); - assert!(err.to_string().contains("deeper than 100"), "{err}"); - assert_eq!(doc(&s).max_group_depth(), photocraft_doc::MAX_GROUP_DEPTH); - // The rejected call recorded no history step: undo still lands one grouping earlier. - s.undo(); - assert_eq!(doc(&s).max_group_depth(), photocraft_doc::MAX_GROUP_DEPTH - 1); - } - - #[test] - fn select_linked_layers_excludes_an_unlinked_active_layer() { - for depth in [8, 16, 32] { - let mut s = session(depth); - let a = rect_layer(&mut s, Rect::new(0, 0, 10, 10)); - let b = rect_layer(&mut s, Rect::new(20, 20, 30, 30)); - let other = rect_layer(&mut s, Rect::new(50, 50, 60, 60)); - select_all(&mut s, &[a, b]); - s.execute("layer.linkLayers", json!({})).unwrap(); - s.execute("layer.select", json!({"layer": a.0})).unwrap(); - s.execute("layer.select", json!({"layer": other.0, "mode": "toggle"})).unwrap(); - assert_eq!(sel(&s), vec![a, other]); - assert_eq!(s.active().unwrap().active_layer, Some(other)); - let past = s.active().unwrap().history.past_len(); - let dirty = s.active().unwrap().is_dirty(); - - let result = s.execute("layer.selectLinkedLayers", json!({})).unwrap(); - assert_eq!(sel(&s), vec![a, b]); - assert_eq!(result["selected"], sel(&s).len()); - assert_eq!(s.active().unwrap().active_layer, Some(b)); - assert_eq!(s.active().unwrap().layer_anchor, Some(b)); - assert_eq!(s.active().unwrap().history.past_len(), past); - assert_eq!(s.active().unwrap().is_dirty(), dirty); - - // A following multi-layer delete must leave the unrelated layer intact. - s.execute("layer.delete", json!({})).unwrap(); - assert!(doc(&s).layer(a).is_none() && doc(&s).layer(b).is_none()); - assert!(doc(&s).layer(other).is_some()); - s.undo(); - assert!(doc(&s).layer(a).is_some() && doc(&s).layer(b).is_some()); - assert!(doc(&s).layer(other).is_some()); - } - } - - #[test] - fn select_linked_layers_preserves_a_linked_active_layer() { - for depth in [8, 16, 32] { - let mut s = session(depth); - let a = rect_layer(&mut s, Rect::new(0, 0, 10, 10)); - let b = rect_layer(&mut s, Rect::new(20, 20, 30, 30)); - select_all(&mut s, &[a, b]); - s.execute("layer.linkLayers", json!({})).unwrap(); - for active in [a, b] { - s.execute("layer.select", json!({"layer": active.0})).unwrap(); - let st = s.active_mut().unwrap(); - st.saved_revision = st.revision; - let past = st.history.past_len(); - for _ in 0..2 { - let result = s.execute("layer.selectLinkedLayers", json!({})).unwrap(); - assert_eq!(sel(&s), vec![a, b]); - assert_eq!(result["selected"], sel(&s).len()); - assert_eq!(s.active().unwrap().active_layer, Some(active)); - assert_eq!(s.active().unwrap().layer_anchor, Some(active)); - assert_eq!(s.active().unwrap().history.past_len(), past); - assert!(!s.active().unwrap().is_dirty()); - } - } - } - } - - #[test] - fn select_linked_layers_requires_a_linked_selection() { - let mut s = Session::new(); - assert!(!s.is_enabled("layer.selectLinkedLayers")); - assert!(s.execute("layer.selectLinkedLayers", json!({})).is_err()); - let mut s = session(8); - let before = sel(&s); - assert!(!s.is_enabled("layer.selectLinkedLayers")); - assert!(s.execute("layer.selectLinkedLayers", json!({})).is_err()); - assert_eq!(sel(&s), before); - } - - #[test] - fn translate_rejects_offsets_that_would_wrap() { - let mut s = session(8); - let a = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); - select_all(&mut s, &[a]); - // 2^32 + 50 wrapped to `dx = 50` and 3e9 to a negative offset through `as i32`. - for dx in [4_294_967_346_i64, 3_000_000_000_i64] { - let err = s.execute("layer.translate", json!({"dx": dx, "dy": 0})).unwrap_err(); - assert!(err.to_string().contains("32-bit"), "{err}"); - } - assert_eq!(bounds(&s, a), Rect::new(0, 0, 5, 5), "the layer never moved"); - // Large in-range offsets still work. - s.execute("layer.translate", json!({"dx": -200_000, "dy": 200_000})).unwrap(); - } - - #[test] - fn link_layers_never_reuses_a_group_when_the_largest_id_is_u64_max() { - let mut s = session(8); - let a = rect_layer(&mut s, Rect::new(0, 0, 10, 10)); - let b = rect_layer(&mut s, Rect::new(20, 20, 30, 30)); - let c = rect_layer(&mut s, Rect::new(50, 50, 60, 60)); - let d = rect_layer(&mut s, Rect::new(70, 70, 80, 80)); - // A stored document can carry any id; `max + 1` once overflowed here. - let st = s.active_mut().unwrap(); - for id in [c, d] { - std::sync::Arc::make_mut(&mut st.doc).layer_mut(id).unwrap().link_group = Some(u64::MAX); - } - select_all(&mut s, &[a, b]); - assert_eq!(s.execute("layer.linkLayers", json!({})).unwrap()["linked"], true); - let g = doc(&s).layer(a).unwrap().link_group; - assert_eq!(g, Some(1)); - assert_eq!(doc(&s).layer(b).unwrap().link_group, g); - for id in [c, d] { - assert_eq!(doc(&s).layer(id).unwrap().link_group, Some(u64::MAX), "the existing group is untouched"); - } - } - - #[test] - fn undo_and_redo_report_only_the_edited_area() { - let mut s = session(8); - let a = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); - select_all(&mut s, &[a]); - // A pixel edit on one layer is bounded by that layer's extent on both sides. - s.edit("paint", |doc, _| { - doc.layer_mut(a).unwrap().surface_mut().unwrap().fill_rect(Rect::new(12, 12, 14, 14), &[0.0, 0.0, 1.0, 1.0]); - Ok(()) - }) - .unwrap(); - s.undo(); - assert_eq!(damage(&s), Some(Rect::new(10, 10, 20, 20))); - s.redo(); - assert_eq!(damage(&s), Some(Rect::new(10, 10, 20, 20))); - // A move reports where the layer was and where it landed. - s.execute("layer.translate", json!({"dx": 5, "dy": 0})).unwrap(); - s.undo(); - assert_eq!(damage(&s), Some(Rect::new(10, 10, 25, 20)), "union of where the layer was and is"); - s.redo(); - assert_eq!(damage(&s), Some(Rect::new(10, 10, 25, 20))); - } - - #[test] - fn undo_of_document_wide_steps_still_composites_everything() { - let mut s = session(8); - let _ = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); - // A canvas change has no bounded damage. - s.execute("image.crop", json!({"x": 0, "y": 0, "width": 30, "height": 25})).unwrap(); - assert_ne!(doc(&s).size, photocraft_doc::Size::new(100, 80)); - s.undo(); - assert_eq!(damage(&s), None, "a size change recomposites the whole canvas"); - // A layer removed and restored changes only where it draws. - let b = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); - select_all(&mut s, &[b]); - s.execute("layer.delete", json!({})).unwrap(); - s.undo(); - assert_eq!(damage(&s), Some(Rect::new(0, 0, 5, 5))); - } - - #[test] - fn undo_of_compositor_read_document_fields_composites_everything() { - let mut s = session(8); - let _ = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); - // Global Light changes every effect's angle across the document. - s.execute("layer.layerStyle.globalLight", json!({"angle": 90.0})).unwrap(); - s.undo(); - assert_eq!(damage(&s), None, "a global-light change recomposites everything"); - // A mode change that keeps the pixel format (RGB → Indexed maps to RGB) neither. - s.execute("image.mode.indexedColor", json!({})).unwrap(); - s.undo(); - assert_eq!(damage(&s), None, "a mode change recomposites everything"); - } - - #[test] - fn undo_of_clipping_or_channel_exclusion_composites_everything() { - let mut s = session(8); - let _ = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); - let b = rect_layer(&mut s, Rect::new(12, 12, 30, 30)); - select_all(&mut s, &[b]); - // Clipping reaches the layers clipped above, outside this layer's bounds. - s.execute("layer.setProps", json!({"clipped": true})).unwrap(); - s.undo(); - assert_eq!(damage(&s), None, "a clipping change recomposites everything"); - s.execute("layer.setProps", json!({"channels": [true, false, true]})).unwrap(); - s.undo(); - assert_eq!(damage(&s), None, "an excluded-channel change recomposites everything"); - } - - #[test] - fn linked_layers_move_together_and_undo() { - for depth in [8, 16, 32] { - let mut s = session(depth); - let a = rect_layer(&mut s, Rect::new(0, 0, 10, 10)); - let b = rect_layer(&mut s, Rect::new(20, 20, 30, 30)); - let c = rect_layer(&mut s, Rect::new(50, 50, 60, 60)); - assert!(!s.is_enabled("layer.linkLayers")); - select_all(&mut s, &[a, b]); - assert_eq!(s.execute("layer.linkLayers", json!({})).unwrap()["linked"], true); - let g = doc(&s).layer(a).unwrap().link_group; - assert!(g.is_some() && doc(&s).layer(b).unwrap().link_group == g); - // Move only a: b follows, c stays. - s.execute("layer.select", json!({"layer": a.0})).unwrap(); - s.execute("layer.translate", json!({"dx": 5, "dy": 3})).unwrap(); - assert_eq!(bounds(&s, a), Rect::new(5, 3, 15, 13)); - assert_eq!(bounds(&s, b), Rect::new(25, 23, 35, 33)); - assert_eq!(bounds(&s, c), Rect::new(50, 50, 60, 60)); - s.undo(); - assert_eq!(bounds(&s, a), Rect::new(0, 0, 10, 10)); - assert_eq!(bounds(&s, b), Rect::new(20, 20, 30, 30)); - // Select Linked Layers from just a. - s.execute("layer.selectLinkedLayers", json!({})).unwrap(); - assert_eq!(sel(&s), vec![a, b]); - // Multi-selection translate moves all selected (c added, unlinked). - s.execute("layer.select", json!({"layer": c.0, "mode": "toggle"})).unwrap(); - s.execute("layer.translate", json!({"dx": -1, "dy": 0})).unwrap(); - assert_eq!(bounds(&s, c), Rect::new(49, 50, 59, 60)); - assert_eq!(bounds(&s, a), Rect::new(-1, 0, 9, 10)); - // Toggle: linking the same group again unlinks. - select_all(&mut s, &[a, b]); - assert_eq!(s.execute("layer.linkLayers", json!({})).unwrap()["linked"], false); - assert!(doc(&s).layer(a).unwrap().link_group.is_none()); - } - } - - /// Plain layers carrying stored link groups, as a loaded `.pcraft` or PSD can hold (#961). - fn stored_groups(s: &mut Session, groups: &[Option]) -> Vec { - let ids: Vec = groups.iter().map(|_| rect_layer(s, Rect::new(0, 0, 4, 4))).collect(); - s.edit("load groups", |doc, _| { - for (id, g) in ids.iter().zip(groups) { - doc.layer_mut(*id).unwrap().link_group = *g; - } - Ok(()) - }) - .unwrap(); - ids - } - - fn group(s: &Session, id: LayerId) -> Option { - doc(s).layer(id).unwrap().link_group - } - - /// Links `ids`, then checks they share one group no other layer uses (#961). - fn link_fresh(s: &mut Session, ids: &[LayerId]) -> u64 { - select_all(s, ids); - let past = s.active().unwrap().history.past_len(); - assert_eq!(s.execute("layer.linkLayers", json!({})).unwrap()["linked"], true); - assert_eq!(s.active().unwrap().history.past_len(), past + 1); - let g = group(s, ids[0]).expect("linked"); - assert!(ids.iter().all(|id| group(s, *id) == Some(g))); - let members = doc(s).walk().iter().filter(|(_, _, l)| l.link_group == Some(g)).count(); - assert_eq!(members, ids.len(), "group {g} is shared with unselected layers"); - g - } - - #[test] - fn link_layers_beside_a_maximal_stored_group() { - // The issue's repro: one layer stored at u64::MAX, link it with an unlinked one. - let mut s = session(8); - let ids = stored_groups(&mut s, &[Some(u64::MAX), None]); - assert_ne!(link_fresh(&mut s, &ids), u64::MAX); - // Unlink and relink the pair: with no groups left, numbering starts over at 1. - assert_eq!(s.execute("layer.linkLayers", json!({})).unwrap()["linked"], false); - assert!(ids.iter().all(|id| group(&s, *id).is_none())); - assert_eq!(link_fresh(&mut s, &ids), 1); - - // Two other layers linked beside an untouched maximal pair. - let mut s = session(8); - let ids = stored_groups(&mut s, &[Some(u64::MAX), Some(u64::MAX), None, None]); - let g = link_fresh(&mut s, &ids[2..]); - assert_ne!(g, u64::MAX); - assert_eq!((group(&s, ids[0]), group(&s, ids[1])), (Some(u64::MAX), Some(u64::MAX))); - } - - #[test] - fn unlink_a_maximal_stored_group() { - let mut s = session(8); - let ids = stored_groups(&mut s, &[Some(u64::MAX), Some(u64::MAX), None]); - select_all(&mut s, &ids[..2]); - assert_eq!(s.execute("layer.linkLayers", json!({})).unwrap()["linked"], false); - assert!(ids.iter().all(|id| group(&s, *id).is_none())); - s.undo(); - assert_eq!((group(&s, ids[0]), group(&s, ids[1])), (Some(u64::MAX), Some(u64::MAX))); - // Relinking all three gets a working group. - link_fresh(&mut s, &ids); - } - - #[test] - fn link_layers_when_every_group_is_huge() { - // Unselected groups at the top of the range, including the 0 a wrapped id would join. - let top = [u64::MAX, u64::MAX - 1, u64::MAX - 2, 0, 1, 2]; - let stored: Vec> = top.iter().flat_map(|g| [Some(*g), Some(*g)]).chain([None, None, None, None]).collect(); - let mut s = session(8); - let ids = stored_groups(&mut s, &stored); - let n = top.len() * 2; - let g = link_fresh(&mut s, &ids[n..n + 2]); - assert!(!top.contains(&g), "{g} collides with a stored group"); - // A second link gets yet another group, and existing groups never change. - let h = link_fresh(&mut s, &ids[n + 2..]); - assert!(!top.contains(&h) && h != g); - for (i, t) in top.iter().enumerate() { - assert_eq!((group(&s, ids[2 * i]), group(&s, ids[2 * i + 1])), (Some(*t), Some(*t))); - } - // Moving a newly linked layer leaves the group-0 pair alone. - assert_eq!(with_links(doc(&s), &[ids[n]]), vec![ids[n], ids[n + 1]]); - } - - #[test] - fn link_layers_near_the_maximum() { - // max + 1 still fits: the new group is u64::MAX itself. - let mut s = session(8); - let ids = stored_groups(&mut s, &[Some(u64::MAX - 1), Some(u64::MAX - 1), None, None, None, None]); - assert_eq!(link_fresh(&mut s, &ids[2..4]), u64::MAX); - // The next link no longer fits above the maximum and takes a free id instead. - let g = link_fresh(&mut s, &ids[4..]); - assert!(g != u64::MAX && g != u64::MAX - 1); - } - - #[test] - fn link_layers_assigns_working_groups() { - // Control: ordinary documents keep getting max + 1, starting at 1. - let mut s = session(8); - let ids = stored_groups(&mut s, &[None, None, None, None]); - assert_eq!(link_fresh(&mut s, &ids[..2]), 1); - assert_eq!(link_fresh(&mut s, &ids[2..]), 2); - assert_eq!(s.execute("layer.linkLayers", json!({})).unwrap()["linked"], false); - assert_eq!((group(&s, ids[2]), group(&s, ids[3])), (None, None)); - assert_eq!((group(&s, ids[0]), group(&s, ids[1])), (Some(1), Some(1))); - } - - #[test] - fn selection_pruned_after_delete_and_undo() { - let mut s = session(8); - let a = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); - let b = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); - let c = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); - select_all(&mut s, &[a, c]); - // Deleting one layer explicitly prunes it from the set. - s.execute("layer.delete", json!({"layer": a.0})).unwrap(); - assert_eq!(sel(&s), vec![c]); - s.undo(); - assert!(sel(&s).iter().all(|id| doc(&s).layer(*id).is_some())); - // Deleting with several selected removes them all, then selects the layer below. - select_all(&mut s, &[a, c]); - s.execute("layer.delete", json!({})).unwrap(); - assert!(doc(&s).layer(a).is_none() && doc(&s).layer(c).is_none()); - assert_eq!(doc(&s).layer_count(), 2); - assert_eq!(sel(&s).len(), 1); - assert!(s.active().unwrap().selected_layers.iter().all(|id| doc(&s).layer(*id).is_some())); - s.undo(); - assert_eq!(doc(&s).layer_count(), 4); - let _ = b; - // Redo then undo again keeps the set valid. - s.redo(); - assert!(sel(&s).iter().all(|id| doc(&s).layer(*id).is_some())); - } - - #[test] - fn duplicate_hide_lock_and_reverse_selected() { - let mut s = session(8); - let a = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); - let b = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); - let c = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); - select_all(&mut s, &[a, c]); - let r = s.execute("layer.duplicate", json!({})).unwrap(); - assert_eq!(r["layers"].as_array().unwrap().len(), 2); - assert_eq!(doc(&s).layer_count(), 6); - assert_eq!(sel(&s).len(), 2); - assert!(sel(&s).iter().all(|id| *id != a && *id != c)); - s.undo(); - select_all(&mut s, &[a, b]); - s.execute("layer.hideLayers", json!({})).unwrap(); - assert!(!doc(&s).layer(a).unwrap().visible && !doc(&s).layer(b).unwrap().visible && doc(&s).layer(c).unwrap().visible); - s.execute("layer.showLayers", json!({})).unwrap(); - assert!(doc(&s).layer(a).unwrap().visible); - s.execute("layer.lockLayers", json!({})).unwrap(); - assert!(doc(&s).layer(a).unwrap().locks.all && doc(&s).layer(b).unwrap().locks.all); - assert!(s.execute("layer.translate", json!({"dx": 1})).is_err(), "locked layers don't move"); - s.execute("layer.lockLayers", json!({})).unwrap(); - assert!(!doc(&s).layer(a).unwrap().locks.all); - s.execute("layer.lockLayers", json!({"position": true})).unwrap(); - assert!(doc(&s).layer(b).unwrap().locks.position && !doc(&s).layer(c).unwrap().locks.position); - // Reverse a, b, c. - select_all(&mut s, &[a, b, c]); - s.execute("layer.arrange.reverse", json!({})).unwrap(); - assert_eq!(doc(&s).layers.iter().skip(1).map(|l| l.id).collect::>(), vec![c, b, a]); - assert_eq!(s.active().unwrap().history.entries().last().map(|e| e.as_str()), Some("Reverse")); - } - - /// #4892: Lock Image Pixels includes Lock Transparent Pixels, so the two are never both on: - /// locking the pixels clears the transparency lock, which stays off while they are locked, - /// through both `layer.setProps` and `layer.lockLayers`. - #[test] - fn locking_pixels_clears_and_holds_off_the_transparency_lock() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); - let id = LayerId(s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap()); - let locks = |s: &Session| doc(s).layer(id).unwrap().locks; - s.execute("layer.setProps", json!({"locks": {"transparency": true}})).unwrap(); - assert!(locks(&s).transparency); - s.execute("layer.setProps", json!({"locks": {"pixels": true}})).unwrap(); - assert!(locks(&s).pixels && !locks(&s).transparency, "locking the pixels clears the transparency lock"); - s.execute("layer.setProps", json!({"locks": {"transparency": true}})).unwrap(); - assert!(!locks(&s).transparency, "and it stays off while the pixels are locked"); - s.execute("layer.setProps", json!({"locks": {"transparency": true, "pixels": true}})).unwrap(); - assert!(locks(&s).pixels && !locks(&s).transparency, "both at once: the pixel lock wins"); - s.execute("layer.lockLayers", json!({"pixels": false})).unwrap(); - s.execute("layer.lockLayers", json!({"transparency": true})).unwrap(); - assert!(locks(&s).transparency && !locks(&s).pixels, "with the pixels unlocked it can be set again"); - s.execute("layer.lockLayers", json!({"pixels": true})).unwrap(); - assert!(locks(&s).pixels && !locks(&s).transparency); - assert!(s.execute("layer.setProps", json!({"locks": {"nope": true}})).is_err()); - } - - /// `document.inspect` lists the selected layers and marks them in the layer list. - #[test] - fn inspect_reports_selection() { - let mut s = session(8); - let a = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); - let b = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); - select_all(&mut s, &[a, b]); - let v = s.execute("document.inspect", json!({})).unwrap(); - assert_eq!(v["selectedLayers"], json!([a.0, b.0])); - assert_eq!(v["layers"][0]["selected"], true); - } - - /// #7538: `selection: true` moves the selection with the layers in the same step, as the Move - /// tool does with several layers selected; without it the selection stays. - #[test] - fn translate_can_carry_the_selection_in_the_same_step() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 100, "height": 100, "background": "transparent"})).unwrap(); - let a = s.active().unwrap().active_layer.unwrap(); - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); - s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); - let b = LayerId(s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap()); - s.execute("select.rect", json!({"x": 50, "y": 10, "width": 20, "height": 20})).unwrap(); - s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap(); - s.execute("layer.select", json!({"layer": a.0, "mode": "add"})).unwrap(); - s.execute("select.rect", json!({"x": 5, "y": 5, "width": 70, "height": 30})).unwrap(); - let sel = |s: &Session| s.active().unwrap().doc.selection.as_ref().map(|m| m.content_bounds()); - let bounds = |s: &Session, id: LayerId| s.active().unwrap().doc.layer(id).unwrap().surface().unwrap().content_bounds(); - let steps = s.active().unwrap().history.past_len(); - s.execute("layer.translate", json!({"dx": 7, "dy": 20, "selection": true})).unwrap(); - assert_eq!((bounds(&s, a), bounds(&s, b)), (Rect::new(17, 30, 37, 50), Rect::new(57, 30, 77, 50))); - assert_eq!(sel(&s), Some(Rect::new(12, 25, 82, 55)), "the selection came along"); - assert_eq!(s.active().unwrap().history.past_len(), steps + 1, "one step"); - s.undo(); - assert_eq!((sel(&s), bounds(&s, a)), (Some(Rect::new(5, 5, 75, 35)), Rect::new(10, 10, 30, 30)), "undone together"); - s.execute("layer.translate", json!({"dx": 7, "dy": 20})).unwrap(); - assert_eq!(sel(&s), Some(Rect::new(5, 5, 75, 35)), "without it the selection stays"); - let state = |s: &Session| (bounds(s, a), bounds(s, b), sel(s), s.active().unwrap().history.past_len()); - let before = state(&s); - for dx in [1, 0] { - assert!(s.execute("layer.translate", json!({"dx": dx, "selection": "yes"})).is_err(), "dx {dx}: a bad `selection` is an error"); - assert_eq!(state(&s), before, "dx {dx}: and changes nothing"); - } - } -} - -#[cfg(test)] -mod layers_panel_parity_tests { - use super::*; - - /// A 24×16 document with three layers, "Test 0" to "Test 2", above the Background; the last one is active. - fn new_session() -> (Session, Vec) { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 24, "height": 16})).unwrap(); - let ids = (0..3).map(|n| LayerId(s.execute("layer.new.layer", json!({"name": format!("Test {n}")})).unwrap()["layer"].as_u64().unwrap())).collect(); - (s, ids) - } - - /// Set one Layers panel option in the preferences, as the Panel Options dialog does. - fn option(s: &mut Session, key: &str, enabled: bool) { - s.prefs.edit(|p| { - let val = p.dialogs.entry("ui.layersPanelOptions".into()).or_insert_with(|| json!({})); - if let Some(o) = val.as_object_mut() { - o.insert(key.to_owned(), json!(enabled)); - } - }); - } - - /// The drag preview equals the committed `layer.moveTo` result and never touches the document or its history. - #[test] - fn preview_matches_real_move_and_never_edits_document_or_history() { - let (mut s, ids) = new_session(); - let params = json!({"layer": ids[0].0, "target": ids[2].0, "position": "above"}); - let before = s.active().unwrap().doc.clone(); - let undo_before = s.active().unwrap().history.entries().len(); - let candidate = preview_move(&before, ¶ms, true).unwrap(); - assert_eq!(*before, *s.active().unwrap().doc); - assert_eq!(s.active().unwrap().history.entries().len(), undo_before); - s.execute("layer.moveTo", params).unwrap(); - assert_eq!(candidate, *s.active().unwrap().doc, "visual preview must match committed layer order"); - } - - /// A previewed ⌥-drag copy names its layers like the committed copy, with and without the "copy" suffix option. - #[test] - fn preview_copy_and_no_copy_suffix_option_match_committed_layers() { - let (mut s, ids) = new_session(); - option(&mut s, "addCopyToCopiedLayersAndGroups", false); - let params = json!({"layer": ids[0].0, "target": ids[2].0, "position": "below", "copy": true}); - let before = s.active().unwrap().doc.clone(); - let candidate = preview_move(&before, ¶ms, false).unwrap(); - s.execute("layer.moveTo", params).unwrap(); - let actual = &s.active().unwrap().doc; - assert_eq!(candidate.layers.iter().map(|l| l.name.as_str()).collect::>(), actual.layers.iter().map(|l| l.name.as_str()).collect::>()); - assert_eq!(actual.layer_count(), before.layer_count() + 1); - assert_eq!(actual.layers.iter().filter(|l| l.name == "Test 0").count(), 2); - let d = s.execute("layer.duplicate", json!({"layer": ids[1].0})).unwrap(); - let duplicate = LayerId(d["layer"].as_u64().unwrap()); - assert_eq!(s.active().unwrap().doc.layer(duplicate).unwrap().name, "Test 1"); - option(&mut s, "addCopyToCopiedLayersAndGroups", true); - let d = s.execute("layer.duplicate", json!({"layer": ids[1].0})).unwrap(); - assert!(s.active().unwrap().doc.layer(LayerId(d["layer"].as_u64().unwrap())).unwrap().name.contains("copy")); - } - - /// Drops the command refuses (or ignores) give no preview and leave the document alone; a multi-layer preview follows the committed stack order. - #[test] - fn preview_rejects_invalid_drop_unchanged() { - let (mut s, ids) = new_session(); - let before = s.active().unwrap().doc.clone(); - // Dropping a layer on itself is a no-op for the command, the others are errors. - for (p, command_rejects) in [ - (json!({"layer": ids[1].0, "target": ids[1].0, "position": "above"}), false), - (json!({"layer": ids[1].0, "target": 999999, "position": "below"}), true), - (json!({"layer": ids[1].0, "target": ids[2].0, "position": "into"}), true), - (json!({"layer": ids[1].0, "target": ids[2].0, "position": "invalid"}), true), - ] { - assert!(preview_move(&before, &p, true).is_none(), "{p}"); - let result = s.execute("layer.moveTo", p.clone()); - if command_rejects { - assert!(result.is_err(), "{p}"); - } else { - assert_eq!(result.unwrap(), Value::Null, "{p}"); - } - assert_eq!(*before, *s.active().unwrap().doc, "{p}"); - } - // Multi-layer preview and commit follow the same stack order regardless of params order. - let p = json!({"layers": [ids[2].0, ids[0].0], "target": ids[1].0, "position": "below"}); - let candidate = preview_move(&before, &p, true).unwrap(); - s.execute("layer.moveTo", p).unwrap(); - assert_eq!(candidate, *s.active().unwrap().doc); - } - - /// A 16×16 document holding `spec` (bottom to top, `*` = clipped) above its Background. Every - /// layer is a translucent, differently placed rectangle, so the stack order and the clip - /// groups both show in the composite. - fn clip_stack(spec: &str) -> Session { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 16, "height": 16})).unwrap(); - for (n, name) in spec.split_whitespace().enumerate() { - let id = LayerId(s.execute("layer.new.layer", json!({"name": name.trim_end_matches('*')})).unwrap()["layer"].as_u64().unwrap()); - let n = n as i32; - let colour = [(n % 3) as f32 * 0.5, ((n + 1) % 3) as f32 * 0.5, ((n + 2) % 3) as f32 * 0.5, 0.6]; - s.edit("paint", |doc, _| { - let layer = doc.layer_mut(id).unwrap(); - layer.clipped = name.ends_with('*'); - layer.surface_mut().unwrap().fill_rect(Rect::new(n * 2, 0, n * 2 + 10, 16), &colour); - Ok(()) - }) - .unwrap(); - } - s - } - - /// Every layer of `doc` from the bottom, `*` marking the clipped ones. - fn stack_text(doc: &Document) -> String { - doc.layers.iter().map(|l| format!("{}{}", l.name, if l.clipped { "*" } else { "" })).collect::>().join(" ") - } - - /// The id of the layer called `name`, searching the whole layer tree. - fn id_of(s: &Session, name: &str) -> u64 { - s.active().unwrap().doc.walk().into_iter().find(|(_, _, l)| l.name == name).unwrap().2.id.0 - } - - /// The preview of `params` and the committed `layer.moveTo` show the same stack (names, clip - /// flags) and the same composite, and both are `want`. - fn assert_preview_is_commit(mut s: Session, params: Value, want: &str) { - let before = s.active().unwrap().doc.clone(); - let preview = preview_move(&before, ¶ms, true).expect("the drop has a preview"); - s.execute("layer.moveTo", params.clone()).unwrap(); - let committed = &s.active().unwrap().doc; - assert_eq!(stack_text(&preview), want, "preview of {params}"); - assert_eq!(stack_text(committed), want, "commit of {params}"); - assert_eq!(photocraft_compose::flatten(&preview).px, photocraft_compose::flatten(committed).px, "composite of {params}"); - } - - /// Previewed moves join and release clipping groups exactly as the committed reorder does, copies included. - #[test] - fn preview_follows_clip_groups_like_the_committed_reorder() { - // The fixtures of `clip_group::reorder_joins_and_leaves_groups`. - for (spec, layers, target, pos, want) in [ - // A layer dropped into a clip group joins it. - ("B C1* C2* U", vec!["U"], "C1", "above", "Background B C1* U* C2*"), - ("B C1* C2* U V", vec!["U", "V"], "C1", "above", "Background B C1* U* V* C2*"), - // A clipped layer dropped off its group is released. - ("B C1* C2* U", vec!["C1"], "U", "above", "Background B C2* U C1"), - // A base moved away releases the layers clipped to it. - ("B C1* C2* U", vec!["B"], "U", "above", "Background C1 C2 U B"), - // A base moved up into its own group joins it, and the layers it left are released. - ("B C1* C2*", vec!["B"], "C1", "above", "Background C1 B* C2"), - ("X B C1* C2* U", vec!["B", "C1"], "U", "above", "Background X C2 U B C1*"), - ] { - let s = clip_stack(spec); - let ids: Vec = layers.iter().map(|n| id_of(&s, n)).collect(); - let t = id_of(&s, target); - assert_preview_is_commit(s, json!({"layers": ids, "target": t, "position": pos}), want); - } - // An option-drag copy joins the clip group it lands in too. - let s = clip_stack("B C1* C2* U"); - let (u, c1) = (id_of(&s, "U"), id_of(&s, "C1")); - assert_preview_is_commit(s, json!({"layer": u, "target": c1, "position": "above", "copy": true}), "Background B C1* U copy* C2* U"); - } - - /// Copying the locked Background in a preview gives the same unlocked copy, joining the clip group it lands in, as the command. - #[test] - fn preview_copies_the_background_like_the_committed_copy() { - let mut s = clip_stack("A B*"); - let (bg, a) = (s.active().unwrap().doc.background().unwrap().id, id_of(&s, "A")); - let before = s.active().unwrap().doc.clone(); - assert_ne!(before.layer(bg).unwrap().locks, Default::default(), "the Background is locked"); - let p = json!({"layer": bg.0, "target": a, "position": "above", "copy": true}); - let preview = preview_move(&before, &p, true).unwrap(); - s.execute("layer.moveTo", p).unwrap(); - let committed = &s.active().unwrap().doc; - // The copy is an ordinary, unlocked layer that joins the clip group it lands in. - assert_eq!(stack_text(committed), "Background A Background copy* B*"); - assert_eq!(stack_text(&preview), stack_text(committed)); - for doc in [&preview, committed] { - assert_eq!(doc.layers.get(2).unwrap().locks, Default::default()); - assert!(doc.layers.first().unwrap().locks != Default::default()); - } - assert_eq!(photocraft_compose::flatten(&preview).px, photocraft_compose::flatten(committed).px); - } - - /// A drop that would move the Background off the bottom has no preview, as the command refuses it. - #[test] - fn preview_refuses_what_would_leave_the_background_off_the_bottom() { - let mut s = clip_stack("A B"); - let (bg, a) = (s.active().unwrap().doc.background().unwrap().id, id_of(&s, "A")); - let before = s.active().unwrap().doc.clone(); - for p in [ - json!({"layer": a, "target": bg.0, "position": "below"}), - json!({"layer": bg.0, "target": bg.0, "position": "below", "copy": true}), - json!({"layer": a, "target": bg.0, "position": "below", "copy": true}), - ] { - assert!(preview_move(&before, &p, true).is_none(), "{p}"); - assert!(s.execute("layer.moveTo", p.clone()).is_err(), "{p}"); - assert_eq!(*before, *s.active().unwrap().doc, "{p}"); - } - } - - /// The UI runs commands through `start`; Expand New Effects applies there as well as to `execute`. - #[test] - fn expand_new_effects_applies_to_ui_start_dispatch_too() { - let (mut s, ids) = new_session(); - option(&mut s, "expandNewEffects", false); - let target = ids[0]; - let started = s.start("layer.layerStyle.dropShadow", json!({"layer": target.0})).unwrap(); - assert!(matches!(started, crate::jobs::Started::Done(_))); - assert!(s.active().unwrap().fx_collapsed.contains(&target)); - } - - /// New Solid Color and Gradient fill layers get the default mask only while Use Default Masks on Fill Layers is on. - #[test] - fn fill_layers_respect_use_default_masks_option() { - let (mut s, _) = new_session(); - option(&mut s, "useDefaultMasksOnFillLayers", false); - let new = s.execute("layer.newFillLayer.solidColor", json!({"color": "#112233"})).unwrap(); - let id = LayerId(new["layer"].as_u64().unwrap()); - assert!(s.active().unwrap().doc.layer(id).unwrap().mask.is_none()); - option(&mut s, "useDefaultMasksOnFillLayers", true); - let new = s.execute("layer.newFillLayer.gradient", json!({})).unwrap(); - let id = LayerId(new["layer"].as_u64().unwrap()); - assert!(s.active().unwrap().doc.layer(id).unwrap().mask.is_some()); - } - - /// With the option off only the default reveal-all mask goes away: an active selection still - /// becomes the layer mask and an explicit path still becomes the vector mask (path first). - #[test] - fn fill_layers_without_default_masks_keep_selection_and_explicit_path_masks() { - const KINDS: [(&str, &str); 3] = [ - ("layer.newFillLayer.solidColor", r##"{"color": "#112233"}"##), - ("layer.newFillLayer.gradient", "{}"), - ("layer.newFillLayer.pattern", r#"{"pattern": "Checkerboard"}"#), - ]; - let path = json!({"subpaths": [{"closed": true, "knots": [[2, 2], [10, 2], [10, 10], [2, 10]]}]}); - let (mut s, _) = new_session(); - option(&mut s, "useDefaultMasksOnFillLayers", false); - // Creates the fill layer; returns its raster mask and whether it has a vector mask. - let create = |s: &mut Session, cmd: &str, params: &str, path: Option<&Value>| { - let mut p: Value = serde_json::from_str(params).unwrap(); - if let Some(path) = path { - p["path"] = path.clone(); - } - let id = LayerId(s.execute(cmd, p).unwrap()["layer"].as_u64().unwrap()); - let l = s.active().unwrap().doc.layer(id).unwrap(); - (l.mask.clone(), l.vector_mask.is_some()) - }; - - for (cmd, params) in KINDS { - let (mask, vector) = create(&mut s, cmd, params, None); - assert!(mask.is_none() && !vector, "{cmd}: no selection, no path: no mask at all"); - } - - s.execute("select.rect", json!({"x": 4, "y": 4, "width": 8, "height": 6})).unwrap(); - for (cmd, params) in KINDS { - let (mask, vector) = create(&mut s, cmd, params, None); - let mask = mask.unwrap_or_else(|| panic!("{cmd}: the selection still becomes the layer mask")); - assert!(!vector, "{cmd}"); - assert!(mask.surface.pixel(6, 6)[0] > 0.99, "{cmd}: inside the selection reveals"); - assert!(mask.surface.pixel(20, 12)[0] < 0.01, "{cmd}: outside the selection hides"); - } - - // An explicit path wins over the selection, as with the option on. - for selected in [true, false] { - if !selected { - s.execute("select.deselect", json!({})).unwrap(); - } - for (cmd, params) in KINDS { - let (mask, vector) = create(&mut s, cmd, params, Some(&path)); - assert!(vector, "{cmd}: the explicit path becomes the vector mask (selection: {selected})"); - assert!(mask.is_none(), "{cmd}: no raster mask next to the vector mask (selection: {selected})"); - } - } - } - - /// Whether new effects start expanded is view state: it adds no history step, and editing an existing effect keeps its disclosure. - #[test] - fn expand_new_effects_is_view_state_and_keeps_edit_history_clean() { - let (mut s, ids) = new_session(); - option(&mut s, "expandNewEffects", false); - let target = ids[0]; - let history = s.active().unwrap().history.entries().len(); - s.execute("layer.layerStyle.dropShadow", json!({"layer": target.0, "size": 2})).unwrap(); - assert_eq!(s.active().unwrap().history.entries().len(), history + 1); - assert!(s.active().unwrap().fx_collapsed.contains(&target)); - option(&mut s, "expandNewEffects", true); - let other = ids[1]; - s.execute("layer.layerStyle.stroke", json!({"layer": other.0, "size": 2})).unwrap(); - assert!(!s.active().unwrap().fx_collapsed.contains(&other)); - // Editing the existing effect must not unexpectedly change its disclosure. - s.execute("layer.layerStyle.dropShadow", json!({"layer": target.0, "size": 5})).unwrap(); - assert!(s.active().unwrap().fx_collapsed.contains(&target)); - } - - /// The disclosure follows the layer the command changes, however the command names it: a - /// layer given by name is not the active one. - #[test] - fn expand_new_effects_follows_a_layer_named_by_its_name() { - let (mut s, ids) = new_session(); - option(&mut s, "expandNewEffects", false); - let (named, active) = (ids[0], ids[2]); - assert_eq!(s.active().unwrap().active_layer, Some(active)); - s.execute("layer.layerStyle.dropShadow", json!({"layer": "Test 0", "size": 2})).unwrap(); - assert!(s.active().unwrap().doc.layer(named).is_some_and(|l| !l.effects.items.is_empty())); - assert!(s.active().unwrap().fx_collapsed.contains(&named), "the named layer's new effects start collapsed"); - assert!(!s.active().unwrap().fx_collapsed.contains(&active), "the active layer is not the one changed"); - } - - /// Transfer Effects changes the layer it moves the effects to, so that is the layer whose - /// disclosure follows the option, not the active layer or the one the effects came from. - #[test] - fn expand_new_effects_follows_the_transfer_destination() { - let (mut s, ids) = new_session(); - let (from, to, active) = (ids[0], ids[1], ids[2]); - s.execute("layer.layerStyle.dropShadow", json!({"layer": from.0, "size": 2})).unwrap(); - option(&mut s, "expandNewEffects", false); - assert_eq!(s.active().unwrap().active_layer, Some(active)); - s.execute("layer.layerStyle.transferEffects", json!({"from": from.0, "to": to.0, "copy": true})).unwrap(); - assert!(s.active().unwrap().doc.layer(to).is_some_and(|l| !l.effects.items.is_empty())); - assert!(s.active().unwrap().fx_collapsed.contains(&to), "the destination's new effects start collapsed"); - assert!(!s.active().unwrap().fx_collapsed.contains(&active), "the active layer is not the one changed"); - } -} diff --git a/crates/engine/src/layer_style.rs b/crates/engine/src/layer_style.rs index 2527f402f3..7d0e337d34 100644 --- a/crates/engine/src/layer_style.rs +++ b/crates/engine/src/layer_style.rs @@ -1154,585 +1154,4 @@ fn delete_effect(s: &mut Session, p: &Value, effect: &Value) -> Result { } #[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - - fn session() -> Session { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 32, "height": 32})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s - } - - fn effects(s: &Session) -> Vec { - let d = s.active().unwrap(); - d.doc.layer(d.active_layer.unwrap()).unwrap().effects.items.clone() - } - - #[test] - fn bevel_command_sets_technique_contour_and_texture() { - let mut s = session(); - s.execute("layer.layerStyle.bevelEmboss", json!({"style": "pillow", "technique": "chiselHard", "contour": true, "contourRange": 70, "texture": "Bubbles", "textureDepth": -200, "textureInvert": true})).unwrap(); - let fx = effects(&s); - let Effect::BevelEmboss(b) = &fx[0] else { panic!("{fx:?}") }; - assert_eq!((b.style, b.technique), (photocraft_doc::BevelStyle::PillowEmboss, BevelTechnique::ChiselHard)); - assert!((b.contour.as_ref().unwrap().range - 0.7).abs() < 1e-6); - let t = b.texture.as_ref().unwrap(); - assert_eq!((t.name.as_str(), t.depth, t.invert), ("Bubbles", -2.0, true)); - } - - /// #6698 review: a glow's Range runs 1..100 %, as its slider and Photoshop's do. A 0 is - /// held at the 1 % floor, and 100 is kept. - #[test] - fn glow_range_is_held_to_one_through_one_hundred() { - for kind in ["outerGlow", "innerGlow"] { - for (sent, kept) in [(0.0, 0.01), (-5.0, 0.01), (1.0, 0.01), (50.0, 0.5), (100.0, 1.0), (250.0, 1.0)] { - let mut s = session(); - s.execute(&format!("layer.layerStyle.{kind}"), json!({"range": sent})).unwrap(); - let range = match &effects(&s)[0] { - Effect::OuterGlow(g) | Effect::InnerGlow(g) => g.range, - other => panic!("{other:?}"), - }; - assert!((range - kept).abs() < 1e-6, "{kind} range {sent} kept as {range}, not {kept}"); - } - } - let doc = |id: &str| specs().into_iter().find(|c| c.id == id).map(|c| c.params).unwrap_or_default(); - assert!(doc("layer.layerStyle.outerGlow").contains(r#""range":1..100=50"#)); - assert!(doc("layer.layerStyle.innerGlow").contains(r#""range":1..100=50"#)); - } - - #[test] - fn bevel_gloss_anti_alias_is_a_param() { - let mut s = session(); - s.execute("layer.layerStyle.bevelEmboss", json!({"glossContour": "Ring - Double", "glossAntiAlias": true})).unwrap(); - let Effect::BevelEmboss(b) = &effects(&s)[0] else { panic!() }; - assert!(b.gloss_anti_alias); - s.execute("layer.layerStyle.bevelEmboss", json!({"glossAntiAlias": false})).unwrap(); - let Effect::BevelEmboss(b) = &effects(&s)[0] else { panic!() }; - assert!(!b.gloss_anti_alias); - } - - #[test] - fn stroke_overprint_is_a_param() { - let mut s = session(); - s.execute("layer.layerStyle.stroke", json!({"size": 4, "overprint": true})).unwrap(); - let Effect::Stroke(st) = &effects(&s)[0] else { panic!() }; - assert!(st.overprint); - s.execute("layer.layerStyle.stroke", json!({"overprint": false})).unwrap(); - let Effect::Stroke(st) = &effects(&s)[0] else { panic!() }; - assert!(!st.overprint); - } - - #[test] - fn bevel_shading_fields_are_independent_and_preserved_on_partial_edits() { - let mut s = session(); - s.execute( - "layer.layerStyle.bevelEmboss", - json!({ - "highlightBlend": "Normal", "highlightColor": "#ff0000", "highlightOpacity": 35, - "shadowBlend": "Color Burn", "shadowColor": "#0000ff", "shadowOpacity": 60 - }), - ) - .unwrap(); - let fx = effects(&s); - let Effect::BevelEmboss(bevel) = &fx[0] else { panic!("{fx:?}") }; - assert_eq!(bevel.highlight.blend, BlendMode::Normal); - assert_eq!(bevel.highlight_color, Color::rgb(1.0, 0.0, 0.0)); - assert!((bevel.highlight.opacity - 0.35).abs() < 0.001); - assert_eq!(bevel.shadow.blend, BlendMode::ColorBurn); - assert_eq!(bevel.shadow_color, Color::rgb(0.0, 0.0, 1.0)); - assert!((bevel.shadow.opacity - 0.60).abs() < 0.001); - - let mut changed = fx[0].clone(); - overlay_effect(&mut changed, &json!({"size": 12})); - let Effect::BevelEmboss(partial) = &changed else { panic!("expected bevel") }; - assert_eq!(partial.highlight, bevel.highlight); - assert_eq!(partial.highlight_color, bevel.highlight_color); - assert_eq!(partial.shadow, bevel.shadow); - assert_eq!(partial.shadow_color, bevel.shadow_color); - - overlay_effect(&mut changed, &json!({"highlightOpacity": 120, "shadowOpacity": -30})); - let Effect::BevelEmboss(limits) = &changed else { panic!("expected bevel") }; - assert_eq!((limits.highlight.opacity, limits.shadow.opacity), (1.0, 0.0)); - } - - #[test] - fn every_style_command_adds_its_effect() { - for kind in ["dropShadow", "innerShadow", "outerGlow", "innerGlow", "stroke", "colorOverlay", "gradientOverlay", "bevelEmboss", "satin"] { - let mut s = session(); - s.execute(&format!("layer.layerStyle.{kind}"), json!({})).unwrap(); - let fx = effects(&s); - assert_eq!(fx.len(), 1, "{kind}"); - assert!(fx[0].enabled()); - } - } - - /// #1543: a Satin or Bevel & Emboss size or softness far past Photoshop's range rendered a - /// blur kernel of 2^62 taps ("capacity overflow"), or ran for minutes at 1e6. The blur width - /// is capped at the effect reach, so the document still renders, quickly. - #[test] - fn oversized_satin_and_bevel_sizes_stay_saveable_and_render() { - for (cmd, p, accepted) in [ - ("satin", json!({"size": 1e308}), false), - ("satin", json!({"size": 1e30}), true), - ("satin", json!({"size": 1_000_000}), true), - ("bevelEmboss", json!({"size": 1e308}), false), - ("bevelEmboss", json!({"soften": 1e308}), false), - ("bevelEmboss", json!({"size": 1e30, "soften": 1e30}), true), - ("bevelEmboss", json!({"size": 1_000_000, "soften": 1_000_000}), true), - ] { - let mut s = session(); - s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); - let result = s.execute(&format!("layer.layerStyle.{cmd}"), p.clone()); - if accepted { - result.unwrap(); - } else { - assert!(matches!(result, Err(EngineError::BadParams { .. }))); - } - photocraft_format::save_to_bytes(&s.active().unwrap().doc, &Default::default()).unwrap(); - let start = std::time::Instant::now(); - s.execute("document.pixel", json!({"x": 0, "y": 0})).unwrap_or_else(|e| panic!("{cmd} {p}: {e}")); - assert!(start.elapsed().as_secs() < 20, "{cmd} {p}: {:?}", start.elapsed()); - } - } - - #[test] - fn params_are_applied_and_replace_or_add() { - let mut s = session(); - s.execute("layer.layerStyle.stroke", json!({"size": 7, "position": "inside", "color": "#00ff00", "opacity": 50})).unwrap(); - match &effects(&s)[0] { - Effect::Stroke(st) => { - assert_eq!(st.size, 7.0); - assert_eq!(st.position, StrokePosition::Inside); - assert_eq!(st.common.opacity, 0.5); - assert_eq!(st.paint, FxPaint::Color(Color::rgb(0.0, 1.0, 0.0))); - } - other => panic!("{other:?}"), - } - s.execute("layer.layerStyle.stroke", json!({"size": 2})).unwrap(); - assert_eq!(effects(&s).len(), 1, "replaces"); - s.execute("layer.layerStyle.stroke", json!({"size": 4, "add": true})).unwrap(); - assert_eq!(effects(&s).len(), 2, "adds a second instance"); - s.execute("layer.layerStyle.dropShadow", json!({"blend": "normal", "distance": 12})).unwrap(); - assert!(matches!(&effects(&s)[2], Effect::DropShadow(sh) if sh.common.blend == BlendMode::Normal && sh.distance == 12.0)); - } - - /// The gradient overlay and the gradient stroke keep their scale in Photoshop's 10-150 %. - #[test] - fn gradient_overlay_and_stroke_scale_stay_in_range() { - let scale = |s: &Session| match &effects(s)[0] { - Effect::GradientOverlay { gradient, .. } => gradient.scale, - Effect::Stroke(st) => match &st.paint { - FxPaint::Gradient(g) => g.scale, - other => panic!("{other:?}"), - }, - other => panic!("{other:?}"), - }; - for (cmd, p, want) in [ - ("gradientOverlay", json!({"scale": 1000}), 1.5), - ("gradientOverlay", json!({"scale": 1}), 0.1), - ("gradientOverlay", json!({"scale": 80}), 0.8), - ("stroke", json!({"from": "#000000", "to": "#ffffff", "scale": -50}), 0.1), - ("stroke", json!({"from": "#000000", "to": "#ffffff", "scale": 0}), 0.1), - ("stroke", json!({"from": "#000000", "to": "#ffffff", "scale": 400}), 1.5), - ] { - let mut s = session(); - s.execute(&format!("layer.layerStyle.{cmd}"), p.clone()).unwrap(); - assert!((scale(&s) - want).abs() < 1e-6, "{cmd} {p}: {}", scale(&s)); - } - // Beyond f32 range is refused before any edit (commands.rs), not clamped. - let err = session().execute("layer.layerStyle.gradientOverlay", json!({"scale": 1e39})).unwrap_err(); - assert!(format!("{err:?}").contains("finite 32-bit"), "{err:?}"); - } - - #[test] - fn clear_and_undo() { - let mut s = session(); - s.execute("layer.layerStyle.colorOverlay", json!({"color": "#ff0000"})).unwrap(); - s.execute("layer.layerStyle.clear", json!({})).unwrap(); - assert!(effects(&s).is_empty()); - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(effects(&s).len(), 1); - } - - fn pixel(s: &mut Session) -> Vec { - serde_json::from_value(s.execute("document.pixel", json!({"x": 3, "y": 3})).unwrap()).unwrap() - } - - fn list_enabled(s: &Session) -> bool { - let d = s.active().unwrap(); - d.doc.layer(d.active_layer.unwrap()).unwrap().effects.enabled - } - - /// #3648: the Layers panel's "Effects" eye (`layer.setEffectsVisible`) must survive a Layer - /// Style dialog OK: the dialog's whole-list replace re-creates the items but leaves the - /// list's master switch alone. - #[test] - fn replacing_the_list_keeps_a_disabled_effect_list_disabled() { - let mut s = session(); - s.execute("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap(); - s.execute("layer.layerStyle.colorOverlay", json!({"color": "#0000ff"})).unwrap(); - let shown = pixel(&mut s); - s.execute("layer.setEffectsVisible", json!({"visible": false})).unwrap(); - let hidden = pixel(&mut s); - assert_ne!(hidden, shown, "the eye really hides the style"); - let r = s.execute("layer.layerStyle.replace", json!({"effects": [{"kind": "colorOverlay", "params": {"color": "#00ff00"}}]})).unwrap(); - assert_eq!(r["effects"], 1, "the list itself is updated"); - assert!(!list_enabled(&s), "the whole-list switch survives the edit"); - assert!(effects(&s)[0].enabled(), "the effect's own state is updated"); - assert_eq!(pixel(&mut s), hidden, "a disabled list still draws nothing"); - s.execute("layer.setEffectsVisible", json!({"visible": true})).unwrap(); - assert_ne!(pixel(&mut s), hidden, "re-showing the list draws the edited effect"); - } - - /// #3648: adding or replacing one effect (`layer.layerStyle.`) also leaves the master - /// switch as the user left it. - #[test] - fn set_effect_keeps_a_disabled_effect_list_disabled() { - let mut s = session(); - s.execute("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap(); - s.execute("layer.layerStyle.colorOverlay", json!({"color": "#0000ff"})).unwrap(); - s.execute("layer.setEffectsVisible", json!({"visible": false})).unwrap(); - let hidden = pixel(&mut s); - s.execute("layer.layerStyle.colorOverlay", json!({"color": "#00ff00"})).unwrap(); - assert!(!list_enabled(&s), "the whole-list switch survives the edit"); - assert!(effects(&s)[0].enabled(), "the effect's own state is updated"); - assert_eq!(pixel(&mut s), hidden, "a disabled list still draws nothing"); - } - - /// A layer that never had effects keeps the default: its first effect shows. - #[test] - fn a_first_effect_shows_on_a_layer_that_never_had_effects() { - let mut s = session(); - s.execute("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap(); - let plain = pixel(&mut s); - s.execute("layer.layerStyle.colorOverlay", json!({"color": "#00ff00"})).unwrap(); - assert!(list_enabled(&s), "a fresh effects list defaults to enabled"); - assert_ne!(pixel(&mut s), plain, "the first effect renders"); - } - - /// #3102: an effect row dropped on the Delete button deletes only that effect, in one step. - #[test] - fn clear_one_effect_by_index() { - let mut s = session(); - s.execute("layer.layerStyle.dropShadow", json!({})).unwrap(); - s.execute("layer.layerStyle.colorOverlay", json!({"color": "#ff0000"})).unwrap(); - let layer = s.active().unwrap().active_layer.unwrap().0; - s.execute("layer.layerStyle.clear", json!({"layer": layer, "effect": 0})).unwrap(); - assert!(matches!(effects(&s)[..], [Effect::ColorOverlay { .. }])); - for bad in [json!({"effect": 5}), json!({"effect": -1}), json!({"effect": "x"}), json!({"effect": 0, "layer": u64::MAX})] { - assert!(s.execute("layer.layerStyle.clear", bad).is_err()); - } - assert_eq!(effects(&s).len(), 1, "bad params change nothing"); - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(effects(&s).len(), 2); - } - - #[test] - fn color_overlay_renders() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); - s.execute("layer.layerStyle.colorOverlay", json!({"color": "#ff0000"})).unwrap(); - let px: Vec = serde_json::from_value(s.execute("document.pixel", json!({"x": 3, "y": 3})).unwrap()).unwrap(); - assert!(px[0] > 0.99 && px[1] < 0.01, "{px:?}"); - } - - #[test] - fn gradient_styles_parse() { - assert_eq!(gradient_style("Radial"), GradientStyle::Radial); - assert_eq!(gradient_style("diamond"), GradientStyle::Diamond); - assert_eq!(gradient_style("?"), GradientStyle::Linear); - } - - fn snapshot(fx: &Effect) -> Value { - serde_json::to_value(fx).unwrap() - } - - #[test] - fn every_kind_has_factory_defaults() { - for kind in - ["dropShadow", "innerShadow", "outerGlow", "innerGlow", "stroke", "colorOverlay", "gradientOverlay", "patternOverlay", "satin", "bevelEmboss"] - { - assert!(effect_defaults(kind).as_object().is_some_and(|o| !o.is_empty()), "{kind}"); - assert!(effect_from_params(kind, &json!({})).is_some(), "{kind}"); - } - assert!(effect_from_params("nope", &json!({})).is_none()); - } - - #[test] - fn replace_builds_edits_and_preserves_instances() { - let mut s = session(); - // Two strokes: the first edits a snapshot (params overlay), the second is fresh. - let first = Effect::Stroke(StrokeFx { - common: photocraft_doc::FxCommon::new(BlendMode::Normal, 1.0), - size: 7.0, - position: StrokePosition::Outside, - paint: FxPaint::Gradient(Gradient { stops: vec![(0.0, Color::rgb(0.0, 0.0, 1.0)), (1.0, Color::WHITE)], ..Gradient::default() }), - overprint: false, - }); - let r = s - .execute( - "layer.layerStyle.replace", - json!({"effects": [ - {"kind": "stroke", "fx": snapshot(&first), "params": {"opacity": 50}}, - {"kind": "stroke", "params": {"size": 2, "color": "#ffffff"}}, - ]}), - ) - .unwrap(); - assert_eq!(r["effects"], 2); - let fx = effects(&s); - assert_eq!(fx.len(), 2, "order preserved"); - match (&fx[0], &fx[1]) { - (Effect::Stroke(a), Effect::Stroke(b)) => { - assert_eq!(a.common.opacity, 0.5); - // The overlay must not clobber the gradient paint it doesn't model. - assert!(matches!(&a.paint, FxPaint::Gradient(g) if g.stops.len() == 2 && g.stops[0].1 == Color::rgb(0.0, 0.0, 1.0))); - assert_eq!(b.size, 2.0); - assert_eq!(b.paint, FxPaint::Color(Color::rgb(1.0, 1.0, 1.0))); - } - other => panic!("{other:?}"), - } - // Replacing with an empty list clears the layer. - s.execute("layer.layerStyle.replace", json!({"effects": []})).unwrap(); - assert!(effects(&s).is_empty()); - } - - #[test] - fn replace_rejects_bad_entries_gracefully() { - let mut s = session(); - let stroke = Effect::Stroke(StrokeFx { - common: photocraft_doc::FxCommon::new(BlendMode::Normal, 1.0), - size: 3.0, - position: StrokePosition::Outside, - paint: FxPaint::Color(Color::BLACK), - overprint: false, - }); - for p in [ - json!({}), - json!({"effects": "nope"}), - json!({"effects": [{"params": {}}]}), - json!({"effects": [{"kind": "nope"}]}), - json!({"effects": [{"kind": "stroke", "fx": {"Bogus": {}}}]}), - json!({"effects": [{"kind": "stroke", "fx": 3}]}), - json!({"effects": [{"kind": "dropShadow", "fx": snapshot(&stroke)}]}), - json!({"effects": [{"kind": "stroke", "fx": snapshot(&stroke), "params": "nope"}]}), - ] { - assert!(s.execute("layer.layerStyle.replace", p).is_err()); - } - // A long list is refused, not run. - let many: Vec<_> = (0..257).map(|_| json!({"kind": "stroke"})).collect(); - assert!(s.execute("layer.layerStyle.replace", json!({"effects": many})).is_err()); - assert!(effects(&s).is_empty(), "nothing was applied"); - } - - #[test] - fn contour_and_noise_params_edit_existing_effects() { - let mut s = session(); - s.execute("layer.layerStyle.dropShadow", json!({})).unwrap(); - let before = effects(&s); - let Effect::DropShadow(_) = &before[0] else { panic!("{before:?}") }; - let fx0 = snapshot(&before[0]); - // Unknown contour names are carried, not clobbered to Linear. - s.execute("layer.layerStyle.replace", json!({"effects": [{"kind": "dropShadow", "fx": fx0, "params": {"contour": "Cone", "noise": 30}}]})).unwrap(); - let fx = effects(&s); - let Effect::DropShadow(sh) = &fx[0] else { panic!("{fx:?}") }; - assert_eq!(sh.contour, builtin_contour("Cone").unwrap(), "known preset applies"); - assert!((sh.noise - 0.3).abs() < 1e-6, "noise in percent"); - // An imported contour with an unknown name survives the same round trip. - let imported = Contour::Custom { - name: "Photoshop contour".into(), - points: vec![photocraft_doc::adjust::CurvePoint { input: 0.0, output: 1.0 }, photocraft_doc::adjust::CurvePoint { input: 1.0, output: 0.0 }], - corners: vec![], - }; - let mut carried = before[0].clone(); - if let Effect::DropShadow(c) = &mut carried { - c.contour = imported.clone(); - } - overlay_effect(&mut carried, &json!({"contour": "Photoshop contour"})); - let Effect::DropShadow(after) = &carried else { panic!() }; - assert_eq!(after.contour, imported); - // Linear applies by name. - let mut back = carried; - overlay_effect(&mut back, &json!({"contour": "Linear"})); - let Effect::DropShadow(lin) = &back else { panic!() }; - assert_eq!(lin.contour, Contour::Linear); - } - - #[test] - fn contour_presets_match_photoshop() { - // Photoshop 27.11, measured through Satin: Cone and Cone − Inverted Satins are identical, - // and Gaussian reads 0.36 at 0.5 through Satin but 0.64 as the preset curve (glows, gloss). - let lut = |name: &str| { - let Some(Contour::Custom { points, corners, .. }) = builtin_contour(name) else { panic!("{name}") }; - photocraft_compose::adjust::contour_curve_lut(&points, &corners) - }; - let satin = |name: &str| photocraft_compose::effects::satin_lut(&builtin_contour(name).unwrap()).unwrap(); - let at = |l: &[f32], x: f32| l[(x * (l.len() - 1) as f32).round() as usize]; - let (cone, inverted) = (satin("Cone"), satin("Cone - Inverted")); - for x in [0.1, 0.25, 0.5, 0.8] { - assert!((at(&cone, x) - at(&inverted, x)).abs() < 0.03, "{x}: {} vs {}", at(&cone, x), at(&inverted, x)); - } - assert!((at(&satin("Gaussian"), 0.5) - 0.36).abs() < 0.04, "{}", at(&satin("Gaussian"), 0.5)); - assert!((at(&lut("Gaussian"), 0.5) - 0.64).abs() < 0.03, "{}", at(&lut("Gaussian"), 0.5)); - assert!((at(&lut("Cove - Deep"), 0.0) - 0.26).abs() < 0.02, "Cove - Deep starts above zero"); - } - - #[test] - fn gradient_overlay_method_matches_photoshop() { - // Photoshop 27.11, Classic Gradient Overlay #000000 → #ffffff (Smoothness 100 %): 0.037 at - // t = 1/16 and 0.5 in the middle; straight stops would give 0.0625. - let mut s = session(); - s.execute("layer.layerStyle.gradientOverlay", json!({"from": "#000000", "to": "#ffffff", "method": "classic"})).unwrap(); - let Effect::GradientOverlay { gradient, .. } = &effects(&s)[0] else { panic!() }; - let at = |t: f32| { - let w = gradient.stops.windows(2).find(|w| t >= w[0].0 && t <= w[1].0).unwrap(); - let u = (t - w[0].0) / (w[1].0 - w[0].0).max(1e-6); - w[0].1.to_rgb()[0] + (w[1].1.to_rgb()[0] - w[0].1.to_rgb()[0]) * u - }; - assert!((at(1.0 / 16.0) - 0.037).abs() < 0.004, "{}", at(1.0 / 16.0)); - assert!((at(0.5) - 0.5).abs() < 0.004, "{}", at(0.5)); - // Without a method the two stops stay as they are. - s.execute("layer.layerStyle.gradientOverlay", json!({"from": "#000000", "to": "#ffffff", "add": true})).unwrap(); - let plain = effects(&s).iter().filter(|e| matches!(e, Effect::GradientOverlay { gradient, .. } if gradient.stops.len() == 2)).count(); - assert_eq!(plain, 1, "the added overlay keeps its two stops"); - } - - #[test] - fn contour_presets_and_custom_curves_apply_in_one_undo_step() { - let mut s = session(); - // Picking Cone: the preset's own curve, its points corners, in one undo step. - s.execute("layer.layerStyle.dropShadow", json!({"contour": "Cone", "antiAlias": true})).unwrap(); - let Effect::DropShadow(sh) = &effects(&s)[0] else { panic!() }; - assert_eq!(sh.contour, builtin_contour("Cone").unwrap()); - assert!(sh.contour.is_corner(1) && sh.anti_alias); - let Contour::Custom { points, corners, .. } = &sh.contour else { panic!() }; - let lut = photocraft_compose::adjust::contour_curve_lut(points, corners); - let at = |x: f32| lut[(x * (lut.len() - 1) as f32).round() as usize]; - // Photoshop's measured Cone: 0 at both ends, a 0.99 peak at 0.5, symmetric. - assert!(at(0.0).abs() < 1e-3 && at(1.0).abs() < 1e-3 && at(0.5) > 0.98, "a Λ: {} {} {}", at(0.0), at(0.5), at(1.0)); - assert!((at(0.25) - at(0.75)).abs() < 0.03, "symmetric: {} vs {}", at(0.25), at(0.75)); - assert_eq!(contour_param(&sh.contour), json!("Cone")); - s.execute("edit.undo", json!({})).unwrap(); - assert!(effects(&s).is_empty(), "one undo removes it"); - - // An edited curve (the Contour Editor's param) round trips exactly, in every effect. - let curve = json!({"name": "Mine", "points": [[0.0, 0.2], [0.4, 0.9], [1.0, 0.1]], "corners": [false, true, false]}); - for kind in ["dropShadow", "innerShadow", "outerGlow", "innerGlow", "satin"] { - let mut fx = fresh_effect(kind).unwrap(); - overlay_effect(&mut fx, &json!({"contour": curve})); - let v = values(&fx, "contour"); - assert_eq!(v, curve, "{kind}"); - } - let mut bevel = fresh_effect("bevelEmboss").unwrap(); - overlay_effect(&mut bevel, &json!({"contour": true, "contourName": curve, "glossContour": "Ring"})); - let Effect::BevelEmboss(b) = &bevel else { panic!() }; - assert_eq!(contour_param(&b.contour.as_ref().unwrap().contour), curve); - assert_eq!(b.gloss_contour, builtin_contour("Ring").unwrap()); - // Malformed curves leave the contour alone. - for bad in [json!({"points": [[0.5, 0.5]]}), json!({"points": [[0.0, "x"], [1.0, 1.0]]}), json!({"points": "no"}), json!(7)] { - let mut fx = fresh_effect("dropShadow").unwrap(); - overlay_effect(&mut fx, &json!({"contour": bad})); - assert_eq!(values(&fx, "contour"), json!("Linear")); - } - - // `.shc` round trip of a curve with a corner. - let mine = contour_from_param(&curve).unwrap(); - let back = contours_from_shc(&contour_to_shc(&mine).unwrap()).unwrap(); - let back = contour_from_param(&back[0]).unwrap(); - let Contour::Custom { points, corners, .. } = &back else { panic!() }; - assert_eq!(corners, &vec![false, true, false]); - assert!((points[1].input - 0.4).abs() < 0.003 && (points[1].output - 0.9).abs() < 0.003, "{points:?}"); - } - - fn values(fx: &Effect, key: &str) -> Value { - let c = match fx { - Effect::DropShadow(s) | Effect::InnerShadow(s) => &s.contour, - Effect::OuterGlow(g) | Effect::InnerGlow(g) => &g.contour, - Effect::Satin(s) => &s.contour, - _ => panic!("{key}: no contour"), - }; - contour_param(c) - } - - #[test] - fn make_default_then_reset_restores_it() { - let mut s = session(); - // Factory default first: Reset without a saved default gives the factory set. - let r = s.execute("layer.layerStyle.defaultFor", json!({"kind": "stroke"})).unwrap(); - assert_eq!(r["user"], json!(false)); - assert_eq!(r["params"]["size"], json!(1)); - s.execute( - "layer.layerStyle.makeDefault", - json!({"kind": "stroke", "params": {"size": 9, "position": "inside", "blend": "Normal", "opacity": 100, "color": "#000000"}}), - ) - .unwrap(); - let r = s.execute("layer.layerStyle.defaultFor", json!({"kind": "stroke"})).unwrap(); - assert_eq!(r["user"], json!(true)); - assert_eq!(r["params"]["size"], json!(9)); - // Bad kinds and params are graceful errors. - assert!(s.execute("layer.layerStyle.makeDefault", json!({"kind": "nope", "params": {}})).is_err()); - assert!(s.execute("layer.layerStyle.makeDefault", json!({"kind": "stroke", "params": "x"})).is_err()); - assert!(s.execute("layer.layerStyle.defaultFor", json!({"kind": "nope"})).is_err()); - } - - /// #7765: a stroke built without params was red, while the dialog's factory default was - /// black. Both now give Photoshop's Reset to Default: 1 px, inside, Normal, 100 %, black. - #[test] - fn fresh_effects_match_the_dialog_factory_defaults() { - for kind in - ["dropShadow", "innerShadow", "outerGlow", "innerGlow", "stroke", "colorOverlay", "gradientOverlay", "patternOverlay", "satin", "bevelEmboss"] - { - let bare = effect_from_params(kind, &json!({})).unwrap(); - let dialog = effect_from_params(kind, &effect_defaults(kind)).unwrap(); - assert_eq!(bare, dialog, "{kind}"); - } - let Some(Effect::Stroke(st)) = effect_from_params("stroke", &json!({})) else { panic!("no stroke") }; - assert_eq!((st.size, st.position, st.common.blend, st.common.opacity), (1.0, StrokePosition::Inside, BlendMode::Normal, 1.0)); - assert_eq!(st.paint, FxPaint::Color(Color::BLACK)); - } - - #[test] - fn layer_style_defaults_persist_with_presets() { - let mut s = session(); - s.execute("layer.layerStyle.makeDefault", json!({"kind": "stroke", "params": {"size": 9}})).unwrap(); - let blob = s.presets.to_json(&s); - let mut t = Session::new(); - t.load_presets_json(blob); - let r = t.execute("layer.layerStyle.defaultFor", json!({"kind": "stroke"})).unwrap(); - assert_eq!(r["user"], json!(true)); - assert_eq!(r["params"]["size"], json!(9)); - } - - #[test] - fn double_stroke_bands_render_and_survive_an_edit() { - // The manga/typesetting case (#157): a 7 px white stroke under a 3 px black one. - let mut s = Session::new(); - s.execute("file.new", json!({"width": 48, "height": 48})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.execute("select.rect", json!({"x": 16, "y": 16, "width": 16, "height": 16})).unwrap(); - s.execute("edit.fill", json!({"color": "#000000"})).unwrap(); - s.execute("select.deselect", json!({})).unwrap(); - s.execute("layer.layerStyle.stroke", json!({"size": 3, "color": "#000000", "position": "outside"})).unwrap(); - s.execute("layer.layerStyle.stroke", json!({"size": 7, "color": "#ffffff", "position": "outside", "add": true})).unwrap(); - let px = |s: &mut Session, x: i32, y: i32| -> [f32; 4] { - let mut v: Vec = serde_json::from_value(s.execute("document.pixel", json!({"x": x, "y": y})).unwrap()).unwrap(); - v.resize(4, 1.0); - [v[0], v[1], v[2], v[3]] - }; - // Bands from the square edge outward: 0..3 px black (the first stroke renders on top), - // 3..7 px white, then the white background. - assert!(px(&mut s, 24, 24)[0] < 0.1, "the square is black"); - assert!(px(&mut s, 24, 14)[0] < 0.1, "the first stroke covers the wider one"); - assert!(px(&mut s, 24, 11)[0] > 0.9, "the second stroke shows outside it"); - assert!(px(&mut s, 24, 5)[0] > 0.9, "background beyond both"); - // A dialog round trip (replace with the same snapshots) keeps both bands. - let before = px(&mut s, 24, 14); - let st = s.active().unwrap(); - let id = st.active_layer.unwrap(); - let items = st.doc.layer(id).unwrap().effects.items.clone(); - let entries: Vec = items.iter().map(|fx| json!({"kind": "stroke", "fx": serde_json::to_value(fx).unwrap(), "params": {}})).collect(); - s.execute("layer.layerStyle.replace", json!({"layer": id.0, "effects": entries})).unwrap(); - assert_eq!(px(&mut s, 24, 14), before, "both strokes render identically after the round trip"); - } -} +mod tests; diff --git a/crates/engine/src/layer_style/tests.rs b/crates/engine/src/layer_style/tests.rs new file mode 100644 index 0000000000..87e80ef898 --- /dev/null +++ b/crates/engine/src/layer_style/tests.rs @@ -0,0 +1,576 @@ +use super::*; +use serde_json::json; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 32, "height": 32})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s +} + +fn effects(s: &Session) -> Vec { + let d = s.active().unwrap(); + d.doc.layer(d.active_layer.unwrap()).unwrap().effects.items.clone() +} + +#[test] +fn bevel_command_sets_technique_contour_and_texture() { + let mut s = session(); + s.execute("layer.layerStyle.bevelEmboss", json!({"style": "pillow", "technique": "chiselHard", "contour": true, "contourRange": 70, "texture": "Bubbles", "textureDepth": -200, "textureInvert": true})).unwrap(); + let fx = effects(&s); + let Effect::BevelEmboss(b) = &fx[0] else { panic!("{fx:?}") }; + assert_eq!((b.style, b.technique), (photocraft_doc::BevelStyle::PillowEmboss, BevelTechnique::ChiselHard)); + assert!((b.contour.as_ref().unwrap().range - 0.7).abs() < 1e-6); + let t = b.texture.as_ref().unwrap(); + assert_eq!((t.name.as_str(), t.depth, t.invert), ("Bubbles", -2.0, true)); +} + +/// #6698 review: a glow's Range runs 1..100 %, as its slider and Photoshop's do. A 0 is +/// held at the 1 % floor, and 100 is kept. +#[test] +fn glow_range_is_held_to_one_through_one_hundred() { + for kind in ["outerGlow", "innerGlow"] { + for (sent, kept) in [(0.0, 0.01), (-5.0, 0.01), (1.0, 0.01), (50.0, 0.5), (100.0, 1.0), (250.0, 1.0)] { + let mut s = session(); + s.execute(&format!("layer.layerStyle.{kind}"), json!({"range": sent})).unwrap(); + let range = match &effects(&s)[0] { + Effect::OuterGlow(g) | Effect::InnerGlow(g) => g.range, + other => panic!("{other:?}"), + }; + assert!((range - kept).abs() < 1e-6, "{kind} range {sent} kept as {range}, not {kept}"); + } + } + let doc = |id: &str| specs().into_iter().find(|c| c.id == id).map(|c| c.params).unwrap_or_default(); + assert!(doc("layer.layerStyle.outerGlow").contains(r#""range":1..100=50"#)); + assert!(doc("layer.layerStyle.innerGlow").contains(r#""range":1..100=50"#)); +} + +#[test] +fn bevel_gloss_anti_alias_is_a_param() { + let mut s = session(); + s.execute("layer.layerStyle.bevelEmboss", json!({"glossContour": "Ring - Double", "glossAntiAlias": true})).unwrap(); + let Effect::BevelEmboss(b) = &effects(&s)[0] else { panic!() }; + assert!(b.gloss_anti_alias); + s.execute("layer.layerStyle.bevelEmboss", json!({"glossAntiAlias": false})).unwrap(); + let Effect::BevelEmboss(b) = &effects(&s)[0] else { panic!() }; + assert!(!b.gloss_anti_alias); +} + +#[test] +fn stroke_overprint_is_a_param() { + let mut s = session(); + s.execute("layer.layerStyle.stroke", json!({"size": 4, "overprint": true})).unwrap(); + let Effect::Stroke(st) = &effects(&s)[0] else { panic!() }; + assert!(st.overprint); + s.execute("layer.layerStyle.stroke", json!({"overprint": false})).unwrap(); + let Effect::Stroke(st) = &effects(&s)[0] else { panic!() }; + assert!(!st.overprint); +} + +#[test] +fn bevel_shading_fields_are_independent_and_preserved_on_partial_edits() { + let mut s = session(); + s.execute( + "layer.layerStyle.bevelEmboss", + json!({ + "highlightBlend": "Normal", "highlightColor": "#ff0000", "highlightOpacity": 35, + "shadowBlend": "Color Burn", "shadowColor": "#0000ff", "shadowOpacity": 60 + }), + ) + .unwrap(); + let fx = effects(&s); + let Effect::BevelEmboss(bevel) = &fx[0] else { panic!("{fx:?}") }; + assert_eq!(bevel.highlight.blend, BlendMode::Normal); + assert_eq!(bevel.highlight_color, Color::rgb(1.0, 0.0, 0.0)); + assert!((bevel.highlight.opacity - 0.35).abs() < 0.001); + assert_eq!(bevel.shadow.blend, BlendMode::ColorBurn); + assert_eq!(bevel.shadow_color, Color::rgb(0.0, 0.0, 1.0)); + assert!((bevel.shadow.opacity - 0.60).abs() < 0.001); + + let mut changed = fx[0].clone(); + overlay_effect(&mut changed, &json!({"size": 12})); + let Effect::BevelEmboss(partial) = &changed else { panic!("expected bevel") }; + assert_eq!(partial.highlight, bevel.highlight); + assert_eq!(partial.highlight_color, bevel.highlight_color); + assert_eq!(partial.shadow, bevel.shadow); + assert_eq!(partial.shadow_color, bevel.shadow_color); + + overlay_effect(&mut changed, &json!({"highlightOpacity": 120, "shadowOpacity": -30})); + let Effect::BevelEmboss(limits) = &changed else { panic!("expected bevel") }; + assert_eq!((limits.highlight.opacity, limits.shadow.opacity), (1.0, 0.0)); +} + +#[test] +fn every_style_command_adds_its_effect() { + for kind in ["dropShadow", "innerShadow", "outerGlow", "innerGlow", "stroke", "colorOverlay", "gradientOverlay", "bevelEmboss", "satin"] { + let mut s = session(); + s.execute(&format!("layer.layerStyle.{kind}"), json!({})).unwrap(); + let fx = effects(&s); + assert_eq!(fx.len(), 1, "{kind}"); + assert!(fx[0].enabled()); + } +} + +/// #1543: a Satin or Bevel & Emboss size or softness far past Photoshop's range rendered a +/// blur kernel of 2^62 taps ("capacity overflow"), or ran for minutes at 1e6. The blur width +/// is capped at the effect reach, so the document still renders, quickly. +#[test] +fn oversized_satin_and_bevel_sizes_stay_saveable_and_render() { + for (cmd, p, accepted) in [ + ("satin", json!({"size": 1e308}), false), + ("satin", json!({"size": 1e30}), true), + ("satin", json!({"size": 1_000_000}), true), + ("bevelEmboss", json!({"size": 1e308}), false), + ("bevelEmboss", json!({"soften": 1e308}), false), + ("bevelEmboss", json!({"size": 1e30, "soften": 1e30}), true), + ("bevelEmboss", json!({"size": 1_000_000, "soften": 1_000_000}), true), + ] { + let mut s = session(); + s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + let result = s.execute(&format!("layer.layerStyle.{cmd}"), p.clone()); + if accepted { + result.unwrap(); + } else { + assert!(matches!(result, Err(EngineError::BadParams { .. }))); + } + photocraft_format::save_to_bytes(&s.active().unwrap().doc, &Default::default()).unwrap(); + let start = std::time::Instant::now(); + s.execute("document.pixel", json!({"x": 0, "y": 0})).unwrap_or_else(|e| panic!("{cmd} {p}: {e}")); + assert!(start.elapsed().as_secs() < 20, "{cmd} {p}: {:?}", start.elapsed()); + } +} + +#[test] +fn params_are_applied_and_replace_or_add() { + let mut s = session(); + s.execute("layer.layerStyle.stroke", json!({"size": 7, "position": "inside", "color": "#00ff00", "opacity": 50})).unwrap(); + match &effects(&s)[0] { + Effect::Stroke(st) => { + assert_eq!(st.size, 7.0); + assert_eq!(st.position, StrokePosition::Inside); + assert_eq!(st.common.opacity, 0.5); + assert_eq!(st.paint, FxPaint::Color(Color::rgb(0.0, 1.0, 0.0))); + } + other => panic!("{other:?}"), + } + s.execute("layer.layerStyle.stroke", json!({"size": 2})).unwrap(); + assert_eq!(effects(&s).len(), 1, "replaces"); + s.execute("layer.layerStyle.stroke", json!({"size": 4, "add": true})).unwrap(); + assert_eq!(effects(&s).len(), 2, "adds a second instance"); + s.execute("layer.layerStyle.dropShadow", json!({"blend": "normal", "distance": 12})).unwrap(); + assert!(matches!(&effects(&s)[2], Effect::DropShadow(sh) if sh.common.blend == BlendMode::Normal && sh.distance == 12.0)); +} + +/// The gradient overlay and the gradient stroke keep their scale in Photoshop's 10-150 %. +#[test] +fn gradient_overlay_and_stroke_scale_stay_in_range() { + let scale = |s: &Session| match &effects(s)[0] { + Effect::GradientOverlay { gradient, .. } => gradient.scale, + Effect::Stroke(st) => match &st.paint { + FxPaint::Gradient(g) => g.scale, + other => panic!("{other:?}"), + }, + other => panic!("{other:?}"), + }; + for (cmd, p, want) in [ + ("gradientOverlay", json!({"scale": 1000}), 1.5), + ("gradientOverlay", json!({"scale": 1}), 0.1), + ("gradientOverlay", json!({"scale": 80}), 0.8), + ("stroke", json!({"from": "#000000", "to": "#ffffff", "scale": -50}), 0.1), + ("stroke", json!({"from": "#000000", "to": "#ffffff", "scale": 0}), 0.1), + ("stroke", json!({"from": "#000000", "to": "#ffffff", "scale": 400}), 1.5), + ] { + let mut s = session(); + s.execute(&format!("layer.layerStyle.{cmd}"), p.clone()).unwrap(); + assert!((scale(&s) - want).abs() < 1e-6, "{cmd} {p}: {}", scale(&s)); + } + // Beyond f32 range is refused before any edit (commands.rs), not clamped. + let err = session().execute("layer.layerStyle.gradientOverlay", json!({"scale": 1e39})).unwrap_err(); + assert!(format!("{err:?}").contains("finite 32-bit"), "{err:?}"); +} + +#[test] +fn clear_and_undo() { + let mut s = session(); + s.execute("layer.layerStyle.colorOverlay", json!({"color": "#ff0000"})).unwrap(); + s.execute("layer.layerStyle.clear", json!({})).unwrap(); + assert!(effects(&s).is_empty()); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(effects(&s).len(), 1); +} + +fn pixel(s: &mut Session) -> Vec { + serde_json::from_value(s.execute("document.pixel", json!({"x": 3, "y": 3})).unwrap()).unwrap() +} + +fn list_enabled(s: &Session) -> bool { + let d = s.active().unwrap(); + d.doc.layer(d.active_layer.unwrap()).unwrap().effects.enabled +} + +/// #3648: the Layers panel's "Effects" eye (`layer.setEffectsVisible`) must survive a Layer +/// Style dialog OK: the dialog's whole-list replace re-creates the items but leaves the +/// list's master switch alone. +#[test] +fn replacing_the_list_keeps_a_disabled_effect_list_disabled() { + let mut s = session(); + s.execute("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap(); + s.execute("layer.layerStyle.colorOverlay", json!({"color": "#0000ff"})).unwrap(); + let shown = pixel(&mut s); + s.execute("layer.setEffectsVisible", json!({"visible": false})).unwrap(); + let hidden = pixel(&mut s); + assert_ne!(hidden, shown, "the eye really hides the style"); + let r = s.execute("layer.layerStyle.replace", json!({"effects": [{"kind": "colorOverlay", "params": {"color": "#00ff00"}}]})).unwrap(); + assert_eq!(r["effects"], 1, "the list itself is updated"); + assert!(!list_enabled(&s), "the whole-list switch survives the edit"); + assert!(effects(&s)[0].enabled(), "the effect's own state is updated"); + assert_eq!(pixel(&mut s), hidden, "a disabled list still draws nothing"); + s.execute("layer.setEffectsVisible", json!({"visible": true})).unwrap(); + assert_ne!(pixel(&mut s), hidden, "re-showing the list draws the edited effect"); +} + +/// #3648: adding or replacing one effect (`layer.layerStyle.`) also leaves the master +/// switch as the user left it. +#[test] +fn set_effect_keeps_a_disabled_effect_list_disabled() { + let mut s = session(); + s.execute("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap(); + s.execute("layer.layerStyle.colorOverlay", json!({"color": "#0000ff"})).unwrap(); + s.execute("layer.setEffectsVisible", json!({"visible": false})).unwrap(); + let hidden = pixel(&mut s); + s.execute("layer.layerStyle.colorOverlay", json!({"color": "#00ff00"})).unwrap(); + assert!(!list_enabled(&s), "the whole-list switch survives the edit"); + assert!(effects(&s)[0].enabled(), "the effect's own state is updated"); + assert_eq!(pixel(&mut s), hidden, "a disabled list still draws nothing"); +} + +/// A layer that never had effects keeps the default: its first effect shows. +#[test] +fn a_first_effect_shows_on_a_layer_that_never_had_effects() { + let mut s = session(); + s.execute("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap(); + let plain = pixel(&mut s); + s.execute("layer.layerStyle.colorOverlay", json!({"color": "#00ff00"})).unwrap(); + assert!(list_enabled(&s), "a fresh effects list defaults to enabled"); + assert_ne!(pixel(&mut s), plain, "the first effect renders"); +} + +/// #3102: an effect row dropped on the Delete button deletes only that effect, in one step. +#[test] +fn clear_one_effect_by_index() { + let mut s = session(); + s.execute("layer.layerStyle.dropShadow", json!({})).unwrap(); + s.execute("layer.layerStyle.colorOverlay", json!({"color": "#ff0000"})).unwrap(); + let layer = s.active().unwrap().active_layer.unwrap().0; + s.execute("layer.layerStyle.clear", json!({"layer": layer, "effect": 0})).unwrap(); + assert!(matches!(effects(&s)[..], [Effect::ColorOverlay { .. }])); + for bad in [json!({"effect": 5}), json!({"effect": -1}), json!({"effect": "x"}), json!({"effect": 0, "layer": u64::MAX})] { + assert!(s.execute("layer.layerStyle.clear", bad).is_err()); + } + assert_eq!(effects(&s).len(), 1, "bad params change nothing"); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(effects(&s).len(), 2); +} + +#[test] +fn color_overlay_renders() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + s.execute("layer.layerStyle.colorOverlay", json!({"color": "#ff0000"})).unwrap(); + let px: Vec = serde_json::from_value(s.execute("document.pixel", json!({"x": 3, "y": 3})).unwrap()).unwrap(); + assert!(px[0] > 0.99 && px[1] < 0.01, "{px:?}"); +} + +#[test] +fn gradient_styles_parse() { + assert_eq!(gradient_style("Radial"), GradientStyle::Radial); + assert_eq!(gradient_style("diamond"), GradientStyle::Diamond); + assert_eq!(gradient_style("?"), GradientStyle::Linear); +} + +fn snapshot(fx: &Effect) -> Value { + serde_json::to_value(fx).unwrap() +} + +#[test] +fn every_kind_has_factory_defaults() { + for kind in ["dropShadow", "innerShadow", "outerGlow", "innerGlow", "stroke", "colorOverlay", "gradientOverlay", "patternOverlay", "satin", "bevelEmboss"] { + assert!(effect_defaults(kind).as_object().is_some_and(|o| !o.is_empty()), "{kind}"); + assert!(effect_from_params(kind, &json!({})).is_some(), "{kind}"); + } + assert!(effect_from_params("nope", &json!({})).is_none()); +} + +#[test] +fn replace_builds_edits_and_preserves_instances() { + let mut s = session(); + // Two strokes: the first edits a snapshot (params overlay), the second is fresh. + let first = Effect::Stroke(StrokeFx { + common: photocraft_doc::FxCommon::new(BlendMode::Normal, 1.0), + size: 7.0, + position: StrokePosition::Outside, + paint: FxPaint::Gradient(Gradient { stops: vec![(0.0, Color::rgb(0.0, 0.0, 1.0)), (1.0, Color::WHITE)], ..Gradient::default() }), + overprint: false, + }); + let r = s + .execute( + "layer.layerStyle.replace", + json!({"effects": [ + {"kind": "stroke", "fx": snapshot(&first), "params": {"opacity": 50}}, + {"kind": "stroke", "params": {"size": 2, "color": "#ffffff"}}, + ]}), + ) + .unwrap(); + assert_eq!(r["effects"], 2); + let fx = effects(&s); + assert_eq!(fx.len(), 2, "order preserved"); + match (&fx[0], &fx[1]) { + (Effect::Stroke(a), Effect::Stroke(b)) => { + assert_eq!(a.common.opacity, 0.5); + // The overlay must not clobber the gradient paint it doesn't model. + assert!(matches!(&a.paint, FxPaint::Gradient(g) if g.stops.len() == 2 && g.stops[0].1 == Color::rgb(0.0, 0.0, 1.0))); + assert_eq!(b.size, 2.0); + assert_eq!(b.paint, FxPaint::Color(Color::rgb(1.0, 1.0, 1.0))); + } + other => panic!("{other:?}"), + } + // Replacing with an empty list clears the layer. + s.execute("layer.layerStyle.replace", json!({"effects": []})).unwrap(); + assert!(effects(&s).is_empty()); +} + +#[test] +fn replace_rejects_bad_entries_gracefully() { + let mut s = session(); + let stroke = Effect::Stroke(StrokeFx { + common: photocraft_doc::FxCommon::new(BlendMode::Normal, 1.0), + size: 3.0, + position: StrokePosition::Outside, + paint: FxPaint::Color(Color::BLACK), + overprint: false, + }); + for p in [ + json!({}), + json!({"effects": "nope"}), + json!({"effects": [{"params": {}}]}), + json!({"effects": [{"kind": "nope"}]}), + json!({"effects": [{"kind": "stroke", "fx": {"Bogus": {}}}]}), + json!({"effects": [{"kind": "stroke", "fx": 3}]}), + json!({"effects": [{"kind": "dropShadow", "fx": snapshot(&stroke)}]}), + json!({"effects": [{"kind": "stroke", "fx": snapshot(&stroke), "params": "nope"}]}), + ] { + assert!(s.execute("layer.layerStyle.replace", p).is_err()); + } + // A long list is refused, not run. + let many: Vec<_> = (0..257).map(|_| json!({"kind": "stroke"})).collect(); + assert!(s.execute("layer.layerStyle.replace", json!({"effects": many})).is_err()); + assert!(effects(&s).is_empty(), "nothing was applied"); +} + +#[test] +fn contour_and_noise_params_edit_existing_effects() { + let mut s = session(); + s.execute("layer.layerStyle.dropShadow", json!({})).unwrap(); + let before = effects(&s); + let Effect::DropShadow(_) = &before[0] else { panic!("{before:?}") }; + let fx0 = snapshot(&before[0]); + // Unknown contour names are carried, not clobbered to Linear. + s.execute("layer.layerStyle.replace", json!({"effects": [{"kind": "dropShadow", "fx": fx0, "params": {"contour": "Cone", "noise": 30}}]})).unwrap(); + let fx = effects(&s); + let Effect::DropShadow(sh) = &fx[0] else { panic!("{fx:?}") }; + assert_eq!(sh.contour, builtin_contour("Cone").unwrap(), "known preset applies"); + assert!((sh.noise - 0.3).abs() < 1e-6, "noise in percent"); + // An imported contour with an unknown name survives the same round trip. + let imported = Contour::Custom { + name: "Photoshop contour".into(), + points: vec![photocraft_doc::adjust::CurvePoint { input: 0.0, output: 1.0 }, photocraft_doc::adjust::CurvePoint { input: 1.0, output: 0.0 }], + corners: vec![], + }; + let mut carried = before[0].clone(); + if let Effect::DropShadow(c) = &mut carried { + c.contour = imported.clone(); + } + overlay_effect(&mut carried, &json!({"contour": "Photoshop contour"})); + let Effect::DropShadow(after) = &carried else { panic!() }; + assert_eq!(after.contour, imported); + // Linear applies by name. + let mut back = carried; + overlay_effect(&mut back, &json!({"contour": "Linear"})); + let Effect::DropShadow(lin) = &back else { panic!() }; + assert_eq!(lin.contour, Contour::Linear); +} + +#[test] +fn contour_presets_match_photoshop() { + // Photoshop 27.11, measured through Satin: Cone and Cone − Inverted Satins are identical, + // and Gaussian reads 0.36 at 0.5 through Satin but 0.64 as the preset curve (glows, gloss). + let lut = |name: &str| { + let Some(Contour::Custom { points, corners, .. }) = builtin_contour(name) else { panic!("{name}") }; + photocraft_compose::adjust::contour_curve_lut(&points, &corners) + }; + let satin = |name: &str| photocraft_compose::effects::satin_lut(&builtin_contour(name).unwrap()).unwrap(); + let at = |l: &[f32], x: f32| l[(x * (l.len() - 1) as f32).round() as usize]; + let (cone, inverted) = (satin("Cone"), satin("Cone - Inverted")); + for x in [0.1, 0.25, 0.5, 0.8] { + assert!((at(&cone, x) - at(&inverted, x)).abs() < 0.03, "{x}: {} vs {}", at(&cone, x), at(&inverted, x)); + } + assert!((at(&satin("Gaussian"), 0.5) - 0.36).abs() < 0.04, "{}", at(&satin("Gaussian"), 0.5)); + assert!((at(&lut("Gaussian"), 0.5) - 0.64).abs() < 0.03, "{}", at(&lut("Gaussian"), 0.5)); + assert!((at(&lut("Cove - Deep"), 0.0) - 0.26).abs() < 0.02, "Cove - Deep starts above zero"); +} + +#[test] +fn gradient_overlay_method_matches_photoshop() { + // Photoshop 27.11, Classic Gradient Overlay #000000 → #ffffff (Smoothness 100 %): 0.037 at + // t = 1/16 and 0.5 in the middle; straight stops would give 0.0625. + let mut s = session(); + s.execute("layer.layerStyle.gradientOverlay", json!({"from": "#000000", "to": "#ffffff", "method": "classic"})).unwrap(); + let Effect::GradientOverlay { gradient, .. } = &effects(&s)[0] else { panic!() }; + let at = |t: f32| { + let w = gradient.stops.windows(2).find(|w| t >= w[0].0 && t <= w[1].0).unwrap(); + let u = (t - w[0].0) / (w[1].0 - w[0].0).max(1e-6); + w[0].1.to_rgb()[0] + (w[1].1.to_rgb()[0] - w[0].1.to_rgb()[0]) * u + }; + assert!((at(1.0 / 16.0) - 0.037).abs() < 0.004, "{}", at(1.0 / 16.0)); + assert!((at(0.5) - 0.5).abs() < 0.004, "{}", at(0.5)); + // Without a method the two stops stay as they are. + s.execute("layer.layerStyle.gradientOverlay", json!({"from": "#000000", "to": "#ffffff", "add": true})).unwrap(); + let plain = effects(&s).iter().filter(|e| matches!(e, Effect::GradientOverlay { gradient, .. } if gradient.stops.len() == 2)).count(); + assert_eq!(plain, 1, "the added overlay keeps its two stops"); +} + +#[test] +fn contour_presets_and_custom_curves_apply_in_one_undo_step() { + let mut s = session(); + // Picking Cone: the preset's own curve, its points corners, in one undo step. + s.execute("layer.layerStyle.dropShadow", json!({"contour": "Cone", "antiAlias": true})).unwrap(); + let Effect::DropShadow(sh) = &effects(&s)[0] else { panic!() }; + assert_eq!(sh.contour, builtin_contour("Cone").unwrap()); + assert!(sh.contour.is_corner(1) && sh.anti_alias); + let Contour::Custom { points, corners, .. } = &sh.contour else { panic!() }; + let lut = photocraft_compose::adjust::contour_curve_lut(points, corners); + let at = |x: f32| lut[(x * (lut.len() - 1) as f32).round() as usize]; + // Photoshop's measured Cone: 0 at both ends, a 0.99 peak at 0.5, symmetric. + assert!(at(0.0).abs() < 1e-3 && at(1.0).abs() < 1e-3 && at(0.5) > 0.98, "a Λ: {} {} {}", at(0.0), at(0.5), at(1.0)); + assert!((at(0.25) - at(0.75)).abs() < 0.03, "symmetric: {} vs {}", at(0.25), at(0.75)); + assert_eq!(contour_param(&sh.contour), json!("Cone")); + s.execute("edit.undo", json!({})).unwrap(); + assert!(effects(&s).is_empty(), "one undo removes it"); + + // An edited curve (the Contour Editor's param) round trips exactly, in every effect. + let curve = json!({"name": "Mine", "points": [[0.0, 0.2], [0.4, 0.9], [1.0, 0.1]], "corners": [false, true, false]}); + for kind in ["dropShadow", "innerShadow", "outerGlow", "innerGlow", "satin"] { + let mut fx = fresh_effect(kind).unwrap(); + overlay_effect(&mut fx, &json!({"contour": curve})); + let v = values(&fx, "contour"); + assert_eq!(v, curve, "{kind}"); + } + let mut bevel = fresh_effect("bevelEmboss").unwrap(); + overlay_effect(&mut bevel, &json!({"contour": true, "contourName": curve, "glossContour": "Ring"})); + let Effect::BevelEmboss(b) = &bevel else { panic!() }; + assert_eq!(contour_param(&b.contour.as_ref().unwrap().contour), curve); + assert_eq!(b.gloss_contour, builtin_contour("Ring").unwrap()); + // Malformed curves leave the contour alone. + for bad in [json!({"points": [[0.5, 0.5]]}), json!({"points": [[0.0, "x"], [1.0, 1.0]]}), json!({"points": "no"}), json!(7)] { + let mut fx = fresh_effect("dropShadow").unwrap(); + overlay_effect(&mut fx, &json!({"contour": bad})); + assert_eq!(values(&fx, "contour"), json!("Linear")); + } + + // `.shc` round trip of a curve with a corner. + let mine = contour_from_param(&curve).unwrap(); + let back = contours_from_shc(&contour_to_shc(&mine).unwrap()).unwrap(); + let back = contour_from_param(&back[0]).unwrap(); + let Contour::Custom { points, corners, .. } = &back else { panic!() }; + assert_eq!(corners, &vec![false, true, false]); + assert!((points[1].input - 0.4).abs() < 0.003 && (points[1].output - 0.9).abs() < 0.003, "{points:?}"); +} + +fn values(fx: &Effect, key: &str) -> Value { + let c = match fx { + Effect::DropShadow(s) | Effect::InnerShadow(s) => &s.contour, + Effect::OuterGlow(g) | Effect::InnerGlow(g) => &g.contour, + Effect::Satin(s) => &s.contour, + _ => panic!("{key}: no contour"), + }; + contour_param(c) +} + +#[test] +fn make_default_then_reset_restores_it() { + let mut s = session(); + // Factory default first: Reset without a saved default gives the factory set. + let r = s.execute("layer.layerStyle.defaultFor", json!({"kind": "stroke"})).unwrap(); + assert_eq!(r["user"], json!(false)); + assert_eq!(r["params"]["size"], json!(1)); + s.execute( + "layer.layerStyle.makeDefault", + json!({"kind": "stroke", "params": {"size": 9, "position": "inside", "blend": "Normal", "opacity": 100, "color": "#000000"}}), + ) + .unwrap(); + let r = s.execute("layer.layerStyle.defaultFor", json!({"kind": "stroke"})).unwrap(); + assert_eq!(r["user"], json!(true)); + assert_eq!(r["params"]["size"], json!(9)); + // Bad kinds and params are graceful errors. + assert!(s.execute("layer.layerStyle.makeDefault", json!({"kind": "nope", "params": {}})).is_err()); + assert!(s.execute("layer.layerStyle.makeDefault", json!({"kind": "stroke", "params": "x"})).is_err()); + assert!(s.execute("layer.layerStyle.defaultFor", json!({"kind": "nope"})).is_err()); +} + +/// #7765: a stroke built without params was red, while the dialog's factory default was +/// black. Both now give Photoshop's Reset to Default: 1 px, inside, Normal, 100 %, black. +#[test] +fn fresh_effects_match_the_dialog_factory_defaults() { + for kind in ["dropShadow", "innerShadow", "outerGlow", "innerGlow", "stroke", "colorOverlay", "gradientOverlay", "patternOverlay", "satin", "bevelEmboss"] { + let bare = effect_from_params(kind, &json!({})).unwrap(); + let dialog = effect_from_params(kind, &effect_defaults(kind)).unwrap(); + assert_eq!(bare, dialog, "{kind}"); + } + let Some(Effect::Stroke(st)) = effect_from_params("stroke", &json!({})) else { panic!("no stroke") }; + assert_eq!((st.size, st.position, st.common.blend, st.common.opacity), (1.0, StrokePosition::Inside, BlendMode::Normal, 1.0)); + assert_eq!(st.paint, FxPaint::Color(Color::BLACK)); +} + +#[test] +fn layer_style_defaults_persist_with_presets() { + let mut s = session(); + s.execute("layer.layerStyle.makeDefault", json!({"kind": "stroke", "params": {"size": 9}})).unwrap(); + let blob = s.presets.to_json(&s); + let mut t = Session::new(); + t.load_presets_json(blob); + let r = t.execute("layer.layerStyle.defaultFor", json!({"kind": "stroke"})).unwrap(); + assert_eq!(r["user"], json!(true)); + assert_eq!(r["params"]["size"], json!(9)); +} + +#[test] +fn double_stroke_bands_render_and_survive_an_edit() { + // The manga/typesetting case (#157): a 7 px white stroke under a 3 px black one. + let mut s = Session::new(); + s.execute("file.new", json!({"width": 48, "height": 48})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("select.rect", json!({"x": 16, "y": 16, "width": 16, "height": 16})).unwrap(); + s.execute("edit.fill", json!({"color": "#000000"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s.execute("layer.layerStyle.stroke", json!({"size": 3, "color": "#000000", "position": "outside"})).unwrap(); + s.execute("layer.layerStyle.stroke", json!({"size": 7, "color": "#ffffff", "position": "outside", "add": true})).unwrap(); + let px = |s: &mut Session, x: i32, y: i32| -> [f32; 4] { + let mut v: Vec = serde_json::from_value(s.execute("document.pixel", json!({"x": x, "y": y})).unwrap()).unwrap(); + v.resize(4, 1.0); + [v[0], v[1], v[2], v[3]] + }; + // Bands from the square edge outward: 0..3 px black (the first stroke renders on top), + // 3..7 px white, then the white background. + assert!(px(&mut s, 24, 24)[0] < 0.1, "the square is black"); + assert!(px(&mut s, 24, 14)[0] < 0.1, "the first stroke covers the wider one"); + assert!(px(&mut s, 24, 11)[0] > 0.9, "the second stroke shows outside it"); + assert!(px(&mut s, 24, 5)[0] > 0.9, "background beyond both"); + // A dialog round trip (replace with the same snapshots) keeps both bands. + let before = px(&mut s, 24, 14); + let st = s.active().unwrap(); + let id = st.active_layer.unwrap(); + let items = st.doc.layer(id).unwrap().effects.items.clone(); + let entries: Vec = items.iter().map(|fx| json!({"kind": "stroke", "fx": serde_json::to_value(fx).unwrap(), "params": {}})).collect(); + s.execute("layer.layerStyle.replace", json!({"layer": id.0, "effects": entries})).unwrap(); + assert_eq!(px(&mut s, 24, 14), before, "both strokes render identically after the round trip"); +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index c49e555071..93e91922b6 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -7,140 +7,38 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] -pub mod actions_cmds; -pub mod actions_edit_cmds; -pub mod adjust_cmds; pub mod adjust_params; -pub mod align_cmds; mod allocation; -pub mod analysis_cmds; -pub mod artboard_cmds; -pub mod atn_cmds; -pub mod automate_cmds; -pub mod background_cmds; -pub mod brush_cmds; -pub mod brush_key_cmds; -pub mod brush_preset_cmds; pub mod build_info; mod canvas_geom; mod channel_clip; -pub mod channel_cmds; mod clip_group; -pub mod color_cmds; -pub mod color_to_alpha_cmds; -pub mod commands; -pub mod comps_cmds; -pub mod contour_lib_cmds; mod crop_fill; -pub mod cutout_cmds; pub mod display_color; -pub mod distort_cmds; pub mod doc_path; -pub mod document_preset_cmds; -pub mod edit_cmds; -pub mod edit_menu_cmds; -pub mod eraser_cmds; -pub mod export_preset_cmds; -pub mod exr_cmds; -pub mod extra_cmds; -pub mod face_cmds; -pub mod file_cmds; -pub mod fill_cmds; -pub mod fill_key_cmds; pub mod filters; pub mod filters_ext; -pub mod float_cmds; -mod frame_cmds; -pub mod fx_view_cmds; -pub mod fx_visibility_cmds; -pub mod gallery_cmds; -pub mod gradient_fill_cmds; -pub mod group_view_cmds; pub mod guide_layout; pub mod hidden_target; -pub mod history_cmds; -pub mod history_menu_cmds; -pub mod history_select_cmds; -pub mod history_source_cmds; -pub mod image_cmds; pub mod inspect; pub mod installed_profiles; pub mod jobs; pub mod kys; -pub mod layer_copy_cmds; -pub mod layer_label_cmds; -pub mod layer_list_cmds; -pub mod layer_mask_props_cmds; -pub mod layer_menu_cmds; -pub mod layer_multi_cmds; -pub mod layer_nav_cmds; pub mod layer_style; -pub mod layer_xmp_cmds; -pub mod lens_cmds; pub mod link_watch; -pub mod magnetic_cmds; -pub mod mask_view_cmds; -mod migrate_cmds; -pub mod mode_cmds; -pub mod multichannel_cmds; pub mod new_layer; -pub mod notes_cmds; -pub mod paint_cmds; mod param_check; -mod path_edit_cmds; -pub mod pattern_cmds; -pub mod pattern_fill_cmds; -pub mod perspective_crop_cmds; -pub mod photo_cmds; -pub mod pick_cmds; mod pixels; -pub mod plugin_cmds; pub mod prefs; -pub mod preset_import_cmds; pub mod preset_store; pub mod presets; -pub mod print_cmds; pub mod proof_sim; -pub mod rasterize_style_cmds; -pub mod redeye_cmds; -pub mod render_cmds; -pub mod retouch_cmds; -pub mod sample_cmds; -pub mod sampler_cmds; -pub mod select_extra_cmds; pub mod select_mask_edits; -pub mod selection_cmds; pub mod shell_commands; pub mod shortcut_sets; -pub mod slice_cmds; -pub mod smart_cmds; -pub mod smartselect_cmds; pub mod snap; -pub mod solid_fill_cmds; -pub mod stamp_cmds; -pub mod style_asl_cmds; -pub mod swatch_cmds; -pub mod symmetry_cmds; -mod timeline_cmds; -pub mod transform_cmds; -mod trap_cmds; -pub mod type_area_cmds; -pub mod type_caret_cmds; -pub mod type_cmds; -pub mod type_extra_cmds; -pub mod type_mask_cmds; -pub mod type_spell_cmds; -pub mod type_styles_cmds; -pub mod updates_cmds; -mod variables_cmds; pub use variables_cmds::{export_data_sets_with, import_data_sets_text}; -pub mod vector_cmds; -mod video_cmds; pub use video_cmds::render_video_with; -pub mod vp_cmds; -pub mod warp_cmds; -pub mod web_cmds; -mod wia_cmds; use std::sync::Arc; @@ -153,36 +51,118 @@ pub use photocraft_doc as doc; pub use photocraft_paint as paint; pub use photocraft_paint::BrushSettings; -#[derive(Debug, thiserror::Error)] -pub enum EngineError { - #[error("unknown command `{0}`")] - UnknownCommand(String), - #[error("command `{0}` is not available right now: {1}")] - Disabled(String, String), - #[error("invalid parameters for `{cmd}`: {msg}")] - BadParams { cmd: String, msg: String }, - #[error("no active document")] - NoDocument, - #[error("no such layer {0:?}")] - NoLayer(LayerId), - /// [`Self::NoLayer`] as a command reports it: with the layers the document does have, as - /// ids are not positions (#5058). - #[error("no such layer {}; {known}", id.0)] - UnknownLayer { id: LayerId, known: String }, - #[error("{0}")] - Other(String), - /// A background job was cancelled (see [`jobs`]); nothing changed. - #[error("cancelled")] - Cancelled, -} +pub mod cmd; +mod doc_state; +mod error; +mod session; -pub type Result = std::result::Result; - -impl From for EngineError { - fn from(error: photocraft_raster::AllocationError) -> Self { - Self::Other(format!("not enough memory for this operation ({error}); the document was not changed")) - } -} +pub use cmd as commands; +pub use cmd::actions_cmds; +pub use cmd::actions_edit_cmds; +pub use cmd::adjust_cmds; +pub use cmd::align_cmds; +pub use cmd::analysis_cmds; +pub use cmd::artboard_cmds; +pub use cmd::atn_cmds; +pub use cmd::automate_cmds; +pub use cmd::background_cmds; +pub use cmd::brush_cmds; +pub use cmd::brush_key_cmds; +pub use cmd::brush_preset_cmds; +pub use cmd::channel_cmds; +pub use cmd::color_cmds; +pub use cmd::color_to_alpha_cmds; +pub use cmd::comps_cmds; +pub use cmd::contour_lib_cmds; +pub use cmd::cutout_cmds; +pub use cmd::distort_cmds; +pub use cmd::document_preset_cmds; +pub use cmd::edit_cmds; +pub use cmd::edit_menu_cmds; +pub use cmd::eraser_cmds; +pub use cmd::export_preset_cmds; +pub use cmd::exr_cmds; +pub use cmd::extra_cmds; +pub use cmd::face_cmds; +pub use cmd::file_cmds; +pub use cmd::fill_cmds; +pub use cmd::fill_key_cmds; +pub use cmd::float_cmds; +use cmd::frame_cmds; +pub use cmd::fx_view_cmds; +pub use cmd::fx_visibility_cmds; +pub use cmd::gallery_cmds; +pub use cmd::gradient_fill_cmds; +pub use cmd::group_view_cmds; +pub use cmd::history_cmds; +pub use cmd::history_menu_cmds; +pub use cmd::history_select_cmds; +pub use cmd::history_source_cmds; +pub use cmd::image_cmds; +pub use cmd::layer_copy_cmds; +pub use cmd::layer_label_cmds; +pub use cmd::layer_list_cmds; +pub use cmd::layer_mask_props_cmds; +pub use cmd::layer_menu_cmds; +pub use cmd::layer_multi_cmds; +pub use cmd::layer_nav_cmds; +pub use cmd::layer_xmp_cmds; +pub use cmd::lens_cmds; +pub use cmd::magnetic_cmds; +pub use cmd::mask_view_cmds; +use cmd::migrate_cmds; +pub use cmd::mode_cmds; +pub use cmd::multichannel_cmds; +pub use cmd::notes_cmds; +pub use cmd::paint_cmds; +use cmd::path_edit_cmds; +pub use cmd::pattern_cmds; +pub use cmd::pattern_fill_cmds; +pub use cmd::perspective_crop_cmds; +pub use cmd::photo_cmds; +pub use cmd::pick_cmds; +pub use cmd::plugin_cmds; +pub use cmd::preset_import_cmds; +pub use cmd::print_cmds; +pub use cmd::rasterize_style_cmds; +pub use cmd::redeye_cmds; +pub use cmd::render_cmds; +pub use cmd::retouch_cmds; +pub use cmd::sample_cmds; +pub use cmd::sampler_cmds; +pub use cmd::select_extra_cmds; +pub use cmd::selection_cmds; +pub use cmd::slice_cmds; +pub use cmd::smart_cmds; +pub use cmd::smartselect_cmds; +pub use cmd::solid_fill_cmds; +pub use cmd::stamp_cmds; +pub use cmd::style_asl_cmds; +pub use cmd::swatch_cmds; +pub use cmd::symmetry_cmds; +use cmd::timeline_cmds; +pub use cmd::transform_cmds; +use cmd::trap_cmds; +pub use cmd::type_area_cmds; +pub use cmd::type_caret_cmds; +pub use cmd::type_cmds; +pub use cmd::type_extra_cmds; +pub use cmd::type_mask_cmds; +pub use cmd::type_spell_cmds; +pub use cmd::type_styles_cmds; +pub use cmd::updates_cmds; +use cmd::variables_cmds; +pub use cmd::vector_cmds; +use cmd::video_cmds; +pub use cmd::vp_cmds; +pub use cmd::warp_cmds; +pub use cmd::web_cmds; +use cmd::wia_cmds; +pub use doc_state::{CopiedStyle, DocState, PRECHECKED, ToolState}; +pub use error::{EngineError, Result}; +pub(crate) use session::fix_selection; +pub use session::move_item; +use session::restore_target; /// The pixels of a raster layer (typically one a command just created), as an error instead /// of a panic if the layer has none. @@ -197,281 +177,6 @@ pub(crate) fn active_layer_of(s: &Session) -> std::result::Result<&photocraft_do d.active_layer.and_then(|id| d.doc.layer(id)).ok_or_else(|| "no active layer".into()) } -/// Per-document editing state. -#[derive(Clone, Debug)] -pub struct DocState { - pub doc: Arc, - pub history: History, - /// The primary ("key") layer: what single-layer commands act on. Always a member of - /// `selected_layers` when set. - pub active_layer: Option, - /// Every selected layer in the Layers panel (⌘/⇧-click), in selection order. Like - /// `active_layer`, selecting is not a history step, but undo and redo restore the layers each - /// state targeted when the next step was taken; see [`DocState::selected_layers`]. - pub selected_layers: Vec, - /// Anchor of ⇧-click range selection (the last plainly or ⌘-clicked layer). - pub layer_anchor: Option, - pub path: Option, - /// An Affinity document (or its preview) must not acquire the native source as its Save path. - pub source_read_only: bool, - /// Increments on every change; UIs re-render when it moves. - pub revision: u64, - pub saved_revision: u64, - /// Native save cache shared with this document's workers, released with the editing state. - pub pcraft_cache: photocraft_io::PcraftExportCache, - /// How much of `revision` came from view-only changes (channel eyes, targeting): pixel caches can ignore those. - pub view_revision: u64, - /// Area changed by the latest revision (None = assume everything changed). - pub last_damage: Option, - /// Coalescing key of the latest history step (see [`Session::execute`]'s `coalesce` param). - pub coalesce: Option, - /// Channels panel: targeted channel and eye toggles (view state, not history). - pub channel_view: channel_cmds::ChannelView, - /// Select › Isolate Layers: the Layers panel lists only these layers (empty = off; view state). - pub isolated_layers: Vec, - /// Painting symmetry preset or sampled path (tool state, not document pixels). - pub symmetry: Option, - /// Layers panel: layers whose effects list is collapsed under their row (the fx triangle; - /// view state, not history). Effects lists start open. - pub fx_collapsed: Vec, - /// ⌥-click on a layer's eye (`layer.showOnly`): the layer shown alone and every layer's - /// visibility before, so the next ⌥-click restores it (view state, not history). - pub show_only: Option<(LayerId, Vec<(LayerId, bool)>)>, - /// A floating selection (`select.float`): the cut piece and where it floats, until dropped - /// (view state: the document is unchanged until `select.drop`). - pub floating: Option, - /// Color Sampler points (`view.colorSamplers.*`, #1046): numbered sample positions in document - /// pixel coordinates. Per-document view state: discarded when the document closes, never saved - /// to `.pcraft` or PSD, and not a history step. - pub color_samplers: Vec<[f64; 2]>, - /// History panel snapshots, oldest first (`history.newSnapshot`, #2966): the first (id 0) is - /// the document as opened. Kept for the session only, as in Photoshop: not history states, - /// and not saved with the document. - pub snapshots: Vec, - /// The id the next snapshot gets; ids are never reused, so deleting one keeps the others. - next_snapshot: u64, - /// The snapshot set as the History Brush's source (`history.setSource {snapshot}`); `None`: - /// the source is a state, kept by the history ([`photocraft_ops::History::brush_source`]). - pub(crate) source_snapshot: Option, -} - -impl DocState { - /// Trim the history to its budget, counting the tiles only History panel snapshots hold - /// against it too (#4530). Returns how many states were dropped. - pub fn trim_history(&mut self) -> usize { - let snaps: Vec<&Document> = self.snapshots.iter().map(|s| &*s.doc).collect(); - self.history.trim_with(&self.doc, &snaps) - } - - /// Pixel bytes of the document, the tiles only its history holds and the tiles only its - /// History panel snapshots hold. - pub fn memory_bytes(&self) -> usize { - let snaps: Vec<&Document> = self.snapshots.iter().map(|s| &*s.doc).collect(); - self.history.pixel_bytes(&self.doc).saturating_add(self.history.extra_bytes(&self.doc, &snaps)) - } - - pub fn new(doc: Document, path: Option) -> Self { - let active_layer = doc.top_layer(); - let mut history = History::default(); - let target = LayerTarget { active: active_layer, selected: active_layer.into_iter().collect() }; - history.set_current_layers(target.clone()); - let doc = Arc::new(doc); - // Photoshop's first snapshot: the document as opened, named after it, so the History - // panel's top row can always bring it back (#2966). - let first = history_cmds::Snapshot { id: 0, name: doc.name.clone(), doc: doc.clone(), layers: target }; - Self { - doc, - history, - active_layer, - selected_layers: active_layer.into_iter().collect(), - layer_anchor: active_layer, - path, - source_read_only: false, - revision: 1, - saved_revision: 1, - pcraft_cache: Default::default(), - view_revision: 0, - last_damage: None, - coalesce: None, - channel_view: Default::default(), - isolated_layers: Vec::new(), - symmetry: None, - fx_collapsed: Vec::new(), - show_only: None, - floating: None, - color_samplers: Vec::new(), - snapshots: vec![first], - next_snapshot: 1, - source_snapshot: None, - } - } - /// The selected layers in bottom-to-top document order, always including the active layer. - /// Robust against stale state: ids no longer in the document are skipped, and if the active - /// layer was changed without updating the set, the selection is just the active layer. - pub fn selected_layers(&self) -> Vec { - let Some(active) = self.active_layer else { return Vec::new() }; - let set: &[LayerId] = if self.selected_layers.contains(&active) { &self.selected_layers } else { std::slice::from_ref(&active) }; - self.doc.walk().into_iter().map(|(_, _, l)| l.id).filter(|id| set.contains(id)).collect() - } - pub fn is_layer_selected(&self, id: LayerId) -> bool { - self.active_layer == Some(id) || (self.active_layer.is_some_and(|a| self.selected_layers.contains(&a)) && self.selected_layers.contains(&id)) - } - pub fn is_dirty(&self) -> bool { - self.revision != self.saved_revision - } - /// Whether the step from `before` to the current document leaves a clean document clean: - /// it changed nothing but the selection (#6865). Making, changing or dropping a selection - /// (marquee, lasso, Magic Wand, Quick / Object Selection, Select › …) is a history step but - /// not an edit, so it neither marks the file modified nor makes closing ask to save. - pub(crate) fn keeps_clean(&self, before: &Document) -> bool { - self.saved_revision == self.revision && layer_multi_cmds::selection_only_change(before, &self.doc) - } - /// Move to the next revision; `keep_clean` (from [`Self::keeps_clean`]) moves the saved - /// revision with it. - pub(crate) fn bump_revision(&mut self, keep_clean: bool) { - self.revision += 1; - if keep_clean { - self.saved_revision = self.revision; - } - } - /// The targeted layers, as history stores them with each state. - fn layer_target(&self) -> LayerTarget { - LayerTarget { active: self.active_layer, selected: self.selected_layers.clone() } - } -} - -/// App-wide tool state that commands read (foreground colour, brush…). -#[derive(Clone, Debug)] -pub struct ToolState { - pub foreground: [f32; 4], - pub background: [f32; 4], - pub brush: photocraft_paint::BrushSettings, - /// Brush presets (built-ins plus user presets; see `brush.presets.*`). - pub presets: Vec, - /// Bumped whenever `presets` changes ([`Session::brush_presets_changed`]); the preset store - /// syncs when it moves. - pub presets_rev: u64, - /// Mixer Brush paint carried between strokes. - pub mixer: photocraft_paint::mixer::MixerState, - /// The coalescing key of the running `tools.setBrush` gesture and the brush before it, so the - /// gesture journals as one call ([`brush_cmds::coalesce_journal`]). - pub brush_gesture: Option<(String, photocraft_paint::BrushSettings)>, - /// Name of the preset the current brush was last picked from. Kept across later edits (the - /// preset stays "the current brush" so `brush.presets.update` can overwrite it); cleared when - /// the brush is reset or the preset is gone. - pub current_preset: Option, - /// Bumped whenever `brush` or `current_preset` changes ([`ToolState::brush_changed`]). The - /// last-brush persistence watches it instead of comparing the brush itself, so an unchanged - /// brush costs a counter compare per frame, not a clone and serialise. - pub brush_rev: u64, - /// The revision whose value is in `Preferences::last_brush` (a restored one counts as saved): - /// [`brush_rev`](Self::brush_rev) == `brush_saved_rev` means there is nothing new to write. - pub brush_saved_rev: u64, - /// A layer mask is the edit target ([`ToolState::target_mask`]). - pub mask_targeted: bool, - /// The foreground/background pair of the edit target that isn't current: the layer pixels' - /// colours while a mask is targeted, the mask's while the pixels are (#2166). - pub other_colors: [[f32; 4]; 2], - /// Colours picked as CMYK, newest last: the sRGB colour that stands for them and the ink - /// values chosen. The tool colours are stored as sRGB, and an sRGB round trip does not give - /// back what was typed (100/0/0/0 cyan is outside sRGB), so a CMYK document is filled with - /// the inks the person picked (#4196). Matched by colour, so it follows a swap, a reset or a - /// mask pair without bookkeeping. - pub cmyk_picks: Vec<([f32; 3], [f32; 4])>, -} - -impl ToolState { - /// How many CMYK picks are remembered. - const CMYK_PICKS: usize = 8; - - /// Remember that sRGB colour `rgb` was picked as the inks `cmyk` (each 0..1). - pub fn remember_cmyk(&mut self, rgb: [f32; 3], cmyk: [f32; 4]) { - self.cmyk_picks.retain(|(c, _)| *c != rgb); - self.cmyk_picks.push((rgb, cmyk)); - let extra = self.cmyk_picks.len().saturating_sub(Self::CMYK_PICKS); - self.cmyk_picks.drain(..extra); - } - - /// The inks `rgb` was picked as, if it was picked as CMYK. - pub fn picked_cmyk(&self, rgb: [f32; 3]) -> Option<[f32; 4]> { - self.cmyk_picks.iter().rev().find(|(c, _)| *c == rgb).map(|(_, k)| *k) - } - - /// Photoshop's colour pair for a layer mask that has none yet: white foreground, black - /// background (reveal-paint first). - pub const MASK_COLORS: [[f32; 4]; 2] = [[1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 1.0]]; - - /// Note that `brush` or `current_preset` changed. Every setter of either (commands and the - /// shell's tool-switch paths) calls this; the last-brush persistence only serialises when the - /// revision has moved since the stored value ([`Self::brush_saved_rev`]). - pub fn brush_changed(&mut self) { - self.brush_rev = self.brush_rev.wrapping_add(1); - } - - /// Switch the edit target between layer pixels and a layer mask. Like Photoshop, the mask and - /// the pixels keep separate app-wide foreground/background pairs: changing the target puts - /// the current pair aside and brings back the other one, so colours picked while a mask is - /// targeted are remembered for masks (#2166). The mask pair starts at [`Self::MASK_COLORS`]. - /// Returns whether the target changed. - pub fn target_mask(&mut self, mask: bool) -> bool { - if self.mask_targeted == mask { - return false; - } - self.mask_targeted = mask; - let [fg, bg] = std::mem::replace(&mut self.other_colors, [self.foreground, self.background]); - self.foreground = fg; - self.background = bg; - true - } -} - -impl Default for ToolState { - fn default() -> Self { - Self { - foreground: [0.0, 0.0, 0.0, 1.0], - background: [1.0, 1.0, 1.0, 1.0], - // Photoshop's Brush tool starts at 10 % Smoothing. - brush: photocraft_paint::BrushSettings { - smoothing: photocraft_paint::brush::Smoothing { amount: 0.1, ..Default::default() }, - ..Default::default() - }, - presets: photocraft_paint::presets::builtin(), - presets_rev: 0, - mixer: Default::default(), - brush_gesture: None, - current_preset: None, - brush_rev: 0, - brush_saved_rev: 0, - mask_targeted: false, - other_colors: Self::MASK_COLORS, - cmyk_picks: Vec::new(), - } - } -} - -/// Layer › Layer Style › Copy Layer Style: the effects and the Blending Options, as Photoshop -/// copies them (Paste Layer Style puts them all on each target). -#[derive(Clone, Debug)] -pub struct CopiedStyle { - pub effects: photocraft_doc::Effects, - pub blend: photocraft_color::BlendMode, - pub fill: f32, - pub advanced: photocraft_doc::AdvancedBlending, - pub blend_if: photocraft_doc::BlendIf, - pub excluded_channels: u32, - /// The colour mode it was copied in: Blend If's channel ranges and the channel restrictions - /// only carry over to a document in the same mode. - pub mode: photocraft_color::ColorMode, -} - -/// The commands whose [`Session::precheck`] is complete: it accepts what `execute` does (Free -/// Transform applies its box before these, and only when they will run), but for the group -/// nesting limit ([`photocraft_doc::MAX_GROUP_DEPTH`]): grouping layers already that deep is -/// refused only as the edit is made. Layer via Copy and -/// Cut aren't: whether they have anything to copy (a selection over transparent pixels, a group -/// or fill layer) is known only when they run. -pub const PRECHECKED: &[&str] = &["layer.new.layer", "layer.new.group", "layer.new.groupFromLayers", "layer.new.layerFromBackground"]; - #[derive(Default)] pub struct Session { docs: Vec, @@ -567,590 +272,6 @@ pub struct Session { next_held_open: u64, } -/// Move item `i` of `v` to position `to`, clamped to the end. Returns where it went; `None` when -/// `i` is out of range. -pub fn move_item(v: &mut Vec, i: usize, to: usize) -> Option { - if i >= v.len() { - return None; - } - let x = v.remove(i); - let to = to.min(v.len()); - v.insert(to, x); - Some(to) -} - -impl Session { - pub fn new() -> Self { - Self::default() - } - - pub fn documents(&self) -> &[DocState] { - &self.docs - } - pub fn active_index(&self) -> Option { - self.active - } - pub fn active(&self) -> Option<&DocState> { - self.active.and_then(|i| self.docs.get(i)) - } - pub fn active_mut(&mut self) -> Option<&mut DocState> { - self.active.and_then(|i| self.docs.get_mut(i)) - } - /// Monotonic active-document generation. It changes when a different document becomes - /// active, including a switch away and back between two observations; equal values therefore - /// mean the document was not switched in between. - pub fn active_generation(&self) -> u64 { - self.active_generation - } - /// Bump [`Self::active_generation`] when the active document id changed. Call after every - /// assignment to `self.active`. - pub(crate) fn note_active_change(&mut self) { - let id = self.active().map(|st| st.doc.id); - if id != self.active_doc_for_generation { - self.active_doc_for_generation = id; - self.active_generation = self.active_generation.wrapping_add(1); - } - } - pub fn set_active(&mut self, index: usize) -> bool { - if index < self.docs.len() { - self.active = Some(index); - self.note_active_change(); - self.sync_tools_mask_target(); - true - } else { - false - } - } - - /// Color Sampler points dropped by the last canvas-size change (crop, Canvas Size, Image Size, - /// rotation) since this was last called, for the status message. See [`edit`](Self::edit). - pub fn take_samplers_removed(&mut self) -> usize { - std::mem::take(&mut self.samplers_removed) - } - - /// Move the Color Sampler points through `a` in the next [`Session::edit`] (crop, Canvas Size, - /// Image Size, rotation), dropping the ones that land outside the new canvas. View state: the - /// points stay pinned to their pixels, no history step. Cleared by the edit it is set for. - /// The painting symmetry moves through `a` too. - pub(crate) fn set_sampler_map(&mut self, a: photocraft_geom::Affine) { - self.set_canvas_map(a, a); - } - - /// [`set_sampler_map`](Self::set_sampler_map) for an edit whose sampler map differs from its - /// geometry map (a flip or rotation maps pixel centres): `geometry` moves the painting symmetry. - pub(crate) fn set_canvas_map(&mut self, geometry: photocraft_geom::Affine, samplers: photocraft_geom::Affine) { - self.sampler_map = Some(samplers); - self.symmetry_map = Some(geometry); - } - - pub fn sync_tools_mask_target(&mut self) { - let mask = self.active().is_some_and(|st| st.channel_view.target == crate::channel_cmds::ChannelTarget::LayerMask); - self.tools.target_mask(mask); - } - - /// Move the document at `from` to tab position `to` (clamped to the last), keeping the active - /// document active. Returns its new index; `None` when `from` is out of range. - pub fn move_document(&mut self, from: usize, to: usize) -> Option { - let active = self.active().map(|d| d.doc.id); - let to = move_item(&mut self.docs, from, to)?; - self.active = active.and_then(|id| self.docs.iter().position(|d| d.doc.id == id)); - self.note_active_change(); - Some(to) - } - - /// Add a document (from File → New, an import, etc.) and make it active. - /// Preserve its identity unless another open document already owns it. - /// Identity-dependent callers must read the admitted document at the returned index. - pub fn add_document(&mut self, mut doc: Document, path: Option) -> usize { - // Persisted IDs can overlap the allocator, so check every replacement too. - while self.docs.iter().any(|st| st.doc.id == doc.id) { - doc.id = photocraft_doc::DocId::fresh(); - } - let mut st = DocState::new(doc, path); - st.history.max_states = self.prefs.get().performance.history_states.max(1) as usize; - st.history.max_bytes = self.prefs.get().performance.history_budget_bytes(); - self.docs.push(st); - let i = self.docs.len() - 1; - self.active = Some(i); - self.note_active_change(); - i - } - - /// Holds a decoded document back from opening (see `held_opens`); returns its id. - pub(crate) fn hold_open(&mut self, doc: Document, source_read_only: bool) -> u64 { - self.next_held_open = self.next_held_open.wrapping_add(1); - self.held_opens.push((self.next_held_open, doc, source_read_only)); - self.next_held_open - } - - /// Takes a document a background open held back for the profile prompt: the document and - /// whether its source is read-only. `None` when there is no such document (already taken). - pub fn take_held_open(&mut self, id: u64) -> Option<(Document, bool)> { - let i = self.held_opens.iter().position(|(h, _, _)| *h == id)?; - let (_, doc, read_only) = self.held_opens.remove(i); - Some((doc, read_only)) - } - - pub fn close(&mut self, index: usize) -> Option { - if index >= self.docs.len() { - return None; - } - smart_cmds::on_close(self, index); - if let Some(id) = self.docs.get(index).map(|d| d.doc.id) { - self.cancel_jobs_on(id); - self.subject_cache.forget_doc(id); - self.object_finder.forget_doc(id); - } - let d = self.docs.remove(index); - self.active = if self.docs.is_empty() { - None - } else { - Some(match self.active { - Some(active) if active > index => active - 1, - Some(active) if active < index => active, - _ => index.min(self.docs.len() - 1), - }) - }; - self.note_active_change(); - Some(d) - } - - /// Run a command by id with JSON params. Returns a JSON result. - /// - /// Any command accepts an optional `"coalesce": ""` param: consecutive edits with the same - /// key (and no other edit, undo or redo in between) share one history step, like Photoshop's - /// single "Edit Type Layer" step for a whole typing session or one step per slider drag. - /// - /// Runs synchronously, including job-capable commands (see [`jobs`]; [`Session::start`] runs - /// those in the background). - pub fn execute(&mut self, id: &str, params: Value) -> Result { - match self.dispatch(id, params, false)? { - jobs::Started::Done(v) => Ok(v), - // Not reached: inline dispatch never starts a job. Waiting is still correct. - jobs::Started::Job(j) => self.wait_job(j), - } - } - - /// Offer a finished live stroke to the next command: a `paint.stroke` / `paint.pencil` whose - /// params match it exactly takes its pixels instead of rendering the stroke again (its result - /// then says `"fromLive": true`); any other command drops the offer. The command still runs - /// through the normal dispatch, so authorization, the journal and history are unchanged. - pub fn offer_live_stroke(&mut self, live: brush_cmds::LiveStroke) -> Result<()> { - self.live_commit = Some(live.into_commit()?); - Ok(()) - } - - /// [`Self::offer_live_stroke`] for a live Clone Stamp or History Brush stroke, taken by the - /// `paint.cloneStamp` / `paint.historyBrush` it was drawn for. Refused for the Healing Brush - /// (it blends on release) and when the brush, layer or clone source changed during the stroke. - pub fn offer_live_retouch(&mut self, live: retouch_cmds::LiveRetouch) -> Result<()> { - let commit = live.into_commit(self)?; - self.live_commit = Some(commit); - Ok(()) - } - - /// [`Self::offer_live_stroke`] for a live Dodge, Burn, Sponge, Blur, Sharpen or Smudge stroke, - /// taken by the command it was drawn for: the stroke's finishing dabs are run first. Refused - /// when the brush, tool options or layer changed during the stroke. - pub fn offer_live_dab(&mut self, live: retouch_cmds::LiveDab) -> Result<()> { - // A refused offer withdraws the previous one too. - self.live_commit = None; - let commit = live.into_commit(self)?; - self.live_commit = Some(commit); - Ok(()) - } - - /// Withdraw an offer the command didn't take. - pub fn clear_live_stroke(&mut self) { - self.live_commit = None; - } - - /// Check a call without running it: the command exists, its params have the shape - /// [`Self::execute`] requires (New Layer's fully), and it can run now. For a caller that does - /// something first only when the command will go through: Free Transform applies its box - /// before a new layer is made. - /// - /// Complete for the commands in [`PRECHECKED`]: there it accepts what `execute` accepts, but - /// for the group nesting limit (a test holds the two together). For others it checks only what they share. - pub fn precheck(&mut self, id: &str, params: &Value) -> Result<()> { - let spec = crate::commands::find(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?; - if !(params.is_object() || params.is_null()) { - return Err(EngineError::BadParams { cmd: id.to_string(), msg: "params must be a JSON object".into() }); - } - crate::param_check::check(spec, params)?; - crate::filters::validate_params(id, params)?; - if id == "layer.new.layer" { - crate::new_layer::parse(params)?; - } - // A command that takes `"layer"` (an id or a name, as it resolves it) fails on one the - // document doesn't have. - if spec.params.contains("\"layer\":id") - && let Some(l) = commands::explicit_layer(self, params)? - && self.active().is_none_or(|st| st.doc.layer(l).is_none()) - { - return Err(EngineError::BadParams { cmd: id.to_string(), msg: format!("no layer {}", l.0) }); - } - self.admit(id, spec, params).map(|_| ()) - } - - /// What `dispatch` checks once the params are valid and a floating selection has dropped: - /// the precondition (on a named layer for commands that take one), a job running on the - /// document, a hidden target. The run params (the Channels panel's target filled in) when it - /// may run. - pub(crate) fn admit(&mut self, id: &str, spec: &commands::CommandSpec, params: &Value) -> Result { - let run_params = channel_cmds::inject_target(self, id, commands::inject_kind(id, params.clone())); - if let Err(why) = self.explicit_layer_enabled(spec, params).unwrap_or_else(|| self.precondition(spec, &run_params)) { - return Err(EngineError::Disabled(id.to_string(), why)); - } - if let Some(why) = self.job_conflict(id, spec.journal) { - return Err(EngineError::Disabled(id.to_string(), why)); - } - // Painting on or moving a hidden layer is refused, as in Photoshop (#571). - if let Some(why) = hidden_target::refusal(self, id, params) { - return Err(EngineError::Other(why.into())); - } - Ok(run_params) - } - - /// Is the command currently runnable? (drives menu enablement) - pub fn is_enabled(&self, id: &str) -> bool { - self.is_enabled_with(id, &Value::Null) - } - - /// [`Self::is_enabled`] for a call with `params`: their `"target"` can enable a command, as a - /// targeted layer mask enables Image › Adjustments › Invert on an adjustment layer (#780). - pub fn is_enabled_with(&self, id: &str, params: &Value) -> bool { - self.disabled_reason_with(id, params).is_none() - } - - /// Why the command can't run now (None = it can): its own precondition, or a background job - /// running on the active document. - pub fn disabled_reason(&self, id: &str) -> Option { - self.disabled_reason_with(id, &Value::Null) - } - - /// [`Self::disabled_reason`] for a call with `params`. - pub fn disabled_reason_with(&self, id: &str, params: &Value) -> Option { - let Some(s) = commands::find(id) else { return Some(format!("unknown command `{id}`")) }; - self.precondition(s, &channel_cmds::inject_target(self, id, params.clone())).err().or_else(|| self.job_conflict(id, s.journal)) - } - - /// The command's own precondition for a call with `params` (their target filled in). - fn precondition(&self, spec: &commands::CommandSpec, params: &Value) -> std::result::Result<(), String> { - if self.names_existing_layer(spec.id, params) { - return Ok(()); - } - // `ifPresent`: with no Background there is nothing to do, which isn't an error. - if spec.id == "layer.new.layerFromBackground" && params.get("ifPresent").and_then(Value::as_bool) == Some(true) { - return self.active().map(|_| ()).ok_or_else(|| "no document open".into()); - } - channel_cmds::mask_target_enabled(self, spec.id, params).unwrap_or_else(|| (spec.enabled)(self)) - } - - /// Whether `id` is a layer command whose `"layer"` param names an existing layer, so it needs no - /// active layer (#2457). Matches how `layer_param` resolves the layer when the command runs. - fn names_existing_layer(&self, id: &str, params: &Value) -> bool { - matches!(id, "layer.hideLayers" | "layer.showLayers" | "layer.renameLayer") - && params.get("layer").and_then(Value::as_u64).is_some_and(|l| self.active().is_some_and(|st| st.doc.layer(LayerId(l)).is_some())) - } - - /// The precondition of a command whose params document `"layer":id` (it acts on that layer), - /// when `params` name an existing layer of the active document: checked on that layer rather - /// than on the active one, which stays active (#466). A script, action or agent can then - /// Replace Contents, Rasterize or Merge Down a layer without selecting it first. `None` for - /// other commands, or without such a layer. - pub(crate) fn explicit_layer_enabled(&mut self, spec: &commands::CommandSpec, params: &Value) -> Option> { - if !spec.params.contains("\"layer\":id") { - return None; - } - let target = LayerId(params.get("layer")?.as_u64()?); - let d = self.active_mut()?; - d.doc.layer(target)?; - let active = d.active_layer.replace(target); - let r = self.precondition(spec, params); - if let Some(d) = self.active_mut() { - d.active_layer = active; - } - Some(r) - } - - /// Apply an undoable edit to the active document. - pub fn edit(&mut self, label: &str, f: impl FnOnce(&mut Document, &mut Option) -> Result) -> Result { - // Every mutation path (linked-file refresh, transform, place) re-renders smart objects - // through this entry; the requesting session's authority must reach those renders. - let _authorization = crate::jobs::render_authorization_scope(self.authorize); - let _document = crate::doc_path::scope(self.active().and_then(|d| d.path.as_deref()).map(std::path::Path::new)); - let restrict = self.color_restrict; - let filter_mask_layer = self.filter_mask_layer; - let sampler_map = self.sampler_map.take(); - let symmetry_map = self.symmetry_map.take(); - let st = self.active_mut().ok_or(EngineError::NoDocument)?; - let before = st.doc.clone(); - // Selecting layers is not a step, so the state this edit leaves behind targets what was - // selected just before it (#1356): undoing a stroke keeps the painted layer active. - let prior = st.layer_target(); - let mut doc = (*before).clone(); - let mut active = st.active_layer; - let r = f(&mut doc, &mut active)?; - if let (Some(k), Some(id)) = (restrict, active) { - channel_cmds::restrict_to_color(&before, &mut doc, id, k); - } - if let Some(id) = filter_mask_layer { - smart_cmds::refresh_after_filter_mask_edit(&mut doc, id)?; - } - st.doc = Arc::new(doc); - st.active_layer = active; - fix_selection(st); - channel_cmds::fix_view(st); - // A canvas-size change (crop, Canvas Size, Image Size, rotation) moves the Color Sampler - // points with their pixels and drops the ones that land outside the new canvas. View - // state: not a history step. A mapped edit (the four above) gives the exact map; any other - // size change falls back to dropping whatever is now outside. - let mut samplers_removed = 0; - if let Some(a) = sampler_map { - let bounds = st.doc.bounds(); - let n = st.color_samplers.len(); - st.color_samplers.retain_mut(|p| { - let q = a.apply(photocraft_geom::Point::new(p[0], p[1])); - *p = [q.x, q.y]; - bounds.contains(q.x.floor() as i32, q.y.floor() as i32) - }); - samplers_removed = n - st.color_samplers.len(); - } else if st.doc.size != before.size { - let bounds = st.doc.bounds(); - let n = st.color_samplers.len(); - st.color_samplers.retain(|p| bounds.contains(p[0].floor() as i32, p[1].floor() as i32)); - samplers_removed = n - st.color_samplers.len(); - } - // The painting symmetry stays on its pixels too (Photoshop keeps it as a path). - if let Some(a) = symmetry_map { - st.symmetry = st.symmetry.take().and_then(|sym| sym.transform(&a)); - } - // The pixels the edit can have changed, as its undo would report them: nothing for a - // selection, guides or a layer's name (a new lasso selection used to recomposite a large - // document, seconds on the CPU path, #1773), a new or deleted layer's bounds (a - // duplicate or a paste), and everything when that can't be bounded. A command may still - // report its own, tighter damage after this. - let damage = layer_multi_cmds::step_damage(&before, &st.doc); - let keep_clean = st.keeps_clean(&before); - let key = self.coalesce_request.clone(); - let st = self.active_mut().ok_or(EngineError::NoDocument)?; - let layers = st.layer_target(); - if key.is_none() || st.coalesce != key || !st.history.can_undo() { - st.history.set_current_layers(prior); - st.history.record(label, before, layers); - st.trim_history(); - } else { - st.history.set_current_layers(layers); - } - st.coalesce = key; - st.bump_revision(keep_clean); - st.last_damage = damage; - self.samplers_removed += samplers_removed; - if damage.is_none_or(|d| !d.is_empty()) { - // Free the mask early; a stale entry would only miss (it is keyed by pixels). - self.subject_cache = Default::default(); - self.object_finder = Default::default(); - } - Ok(r) - } - - /// Replace the active document's active layer without creating a history step. - pub fn select_layer(&mut self, id: LayerId) -> Result<()> { - let st = self.active_mut().ok_or(EngineError::NoDocument)?; - if st.doc.layer(id).is_none() { - return Err(EngineError::NoLayer(id)); - } - st.active_layer = Some(id); - st.selected_layers = vec![id]; - st.layer_anchor = Some(id); - channel_cmds::fix_view(st); - // Selecting a layer is not an edit: keep a clean document clean. - let clean = st.saved_revision == st.revision; - st.revision += 1; - if clean { - st.saved_revision = st.revision; - } - st.last_damage = Some(photocraft_geom::Rect::EMPTY); - Ok(()) - } - - /// Put back a layer selection (active layer, selected layers, anchor) that a step moved, such - /// as the undo ending an empty Type Mask, which restores the selection from before it. `None` - /// is no layer selected. Selected layers that are gone are dropped; an active layer that is - /// gone is an error and changes nothing. Like [`Self::select_layer`], not an edit. - pub fn restore_layer_selection(&mut self, active: Option, selected: &[LayerId], anchor: Option) -> Result<()> { - let st = self.active_mut().ok_or(EngineError::NoDocument)?; - if let Some(id) = active - && st.doc.layer(id).is_none() - { - return Err(EngineError::NoLayer(id)); - } - st.active_layer = active; - st.selected_layers = selected.to_vec(); - st.layer_anchor = anchor.filter(|_| active.is_some()); - fix_selection(st); - channel_cmds::fix_view(st); - let clean = st.saved_revision == st.revision; - st.revision += 1; - if clean { - st.saved_revision = st.revision; - } - st.last_damage = Some(photocraft_geom::Rect::EMPTY); - Ok(()) - } - - /// Re-renders the pixels of type layers whose font arrived after they were drawn (the web - /// build fetches served fonts on demand, `photocraft_text::served`). The layers' model is - /// unchanged, so this is no history step and leaves a clean document clean. Unknown documents - /// and layers are skipped. A document a background job is computing from must not move under - /// it: its layers are returned, to try again later. - pub fn refresh_type_layers(&mut self, layers: &[(photocraft_doc::DocId, LayerId)]) -> Vec<(photocraft_doc::DocId, LayerId)> { - let mut busy = Vec::new(); - let mut docs: Vec = Vec::new(); - for (d, _) in layers { - if !docs.contains(d) { - docs.push(*d); - } - } - for doc_id in docs { - let mine = layers.iter().filter(|(d, _)| *d == doc_id); - if self.job_on(doc_id).is_some() { - busy.extend(mine); - continue; - } - let Some(st) = self.docs.iter_mut().find(|st| st.doc.id == doc_id) else { continue }; - let snapshot = st.doc.clone(); - let mut doc = (*snapshot).clone(); - let mut changed = false; - for (_, id) in mine { - if let Some(photocraft_doc::Layer { content: photocraft_doc::LayerContent::Text(t), .. }) = doc.layer_mut(*id) { - type_cmds::refresh(&snapshot, t); - changed = true; - } - } - if changed { - let clean = st.saved_revision == st.revision; - st.doc = Arc::new(doc); - st.revision += 1; - if clean { - st.saved_revision = st.revision; - } - st.last_damage = None; - } - } - busy - } - - pub fn undo(&mut self) -> bool { - // A background job is computing from the current state: it must not move under it. - if self.active_job().is_some() { - return false; - } - let Some(st) = self.active_mut() else { return false }; - st.coalesce = None; - match st.history.undo(st.doc.clone()) { - // Undo Clear History: the list comes back, the document is the same one. Not an - // edit: keep a clean document clean (the revision still moves for the panels). - Some((d, layers)) if Arc::ptr_eq(&d, &st.doc) => { - restore_target(st, layers); - let clean = !st.is_dirty(); - st.revision += 1; - if clean { - st.saved_revision = st.revision; - } - st.last_damage = Some(photocraft_geom::Rect::EMPTY); - true - } - Some((mut d, layers)) => { - // Save As changes file identity outside history, just like the saved path. - if d.name != st.doc.name { - Arc::make_mut(&mut d).name.clone_from(&st.doc.name); - } - // Pixels this step can have touched, so the canvas recomposites only that - // (it recomposited everything before). - let damage = layer_multi_cmds::step_damage(&d, &st.doc); - let before = std::mem::replace(&mut st.doc, d); - let keep_clean = st.keeps_clean(&before); - restore_target(st, layers); - st.bump_revision(keep_clean); - st.last_damage = damage; - true - } - None => false, - } - } - - pub fn redo(&mut self) -> bool { - if self.active_job().is_some() { - return false; - } - let Some(st) = self.active_mut() else { return false }; - st.coalesce = None; - match st.history.redo(st.doc.clone()) { - Some((mut d, layers)) => { - if d.name != st.doc.name { - Arc::make_mut(&mut d).name.clone_from(&st.doc.name); - } - let damage = layer_multi_cmds::step_damage(&st.doc, &d); - let before = std::mem::replace(&mut st.doc, d); - let keep_clean = st.keeps_clean(&before); - restore_target(st, layers); - st.bump_revision(keep_clean); - st.last_damage = damage; - true - } - None => false, - } - } -} - -/// Undo / redo: target the layers the restored state targeted, as far as they still exist. -fn restore_target(st: &mut DocState, layers: LayerTarget) { - // Deselect Layers is a valid history target, not a missing layer to replace with the top - // layer. An edit after deselection must undo back to no active or selected layers (#3042). - if layers.active.is_none() && layers.selected.is_empty() { - st.active_layer = None; - st.selected_layers.clear(); - st.layer_anchor = None; - channel_cmds::fix_view(st); - return; - } - if layers.active.is_some_and(|id| st.doc.layer(id).is_some()) { - st.active_layer = layers.active; - st.selected_layers = layers.selected; - } - fix_active(st); -} - -fn fix_active(st: &mut DocState) { - if st.active_layer.is_none_or(|id| st.doc.layer(id).is_none()) { - st.active_layer = st.doc.top_layer(); - } - fix_selection(st); - channel_cmds::fix_view(st); -} - -/// Keep the layer selection valid after the document or the active layer changed: drop deleted -/// layers, and collapse to the active layer when a command made a non-member active. -pub(crate) fn fix_selection(st: &mut DocState) { - let Some(active) = st.active_layer else { - st.selected_layers.clear(); - return; - }; - if !st.selected_layers.contains(&active) { - st.selected_layers = vec![active]; - } else { - let live: std::collections::HashSet = st.doc.walk().into_iter().map(|(_, _, l)| l.id).collect(); - st.selected_layers.retain(|id| live.contains(id)); - let mut seen = std::collections::HashSet::new(); - st.selected_layers.retain(|id| seen.insert(*id)); - } - if st.layer_anchor.is_some_and(|a| !st.selected_layers.contains(&a)) { - st.layer_anchor = Some(active); - } -} - #[cfg(test)] mod fill_layer_mode_tests; #[cfg(test)] diff --git a/crates/engine/src/paint_cmds.rs b/crates/engine/src/paint_cmds.rs deleted file mode 100644 index 91c0a87356..0000000000 --- a/crates/engine/src/paint_cmds.rs +++ /dev/null @@ -1,531 +0,0 @@ -//! Paint helpers: Paint Bucket and Gradient tool. - -use photocraft_algo::paint::{FillMode, GradientShape, bucket_fill_inks, bucket_fill_region_inks, paint_gradient}; -use serde_json::{Value, json}; - -use crate::commands::{CommandSpec, blend_from_str}; -use crate::presets::gradients; -use crate::{EngineError, Result, Session}; - -fn f(p: &Value, k: &str, d: f32) -> f32 { - p.get(k).and_then(Value::as_f64).map_or(d, |v| v as f32) -} -fn b(p: &Value, k: &str, d: bool) -> bool { - p.get(k).and_then(Value::as_bool).unwrap_or(d) -} -fn color(v: Option<&Value>, d: [f32; 4]) -> [f32; 4] { - match v { - Some(Value::Array(a)) if a.len() >= 3 => { - let c: Vec = a.iter().map(|x| x.as_f64().unwrap_or(0.0) as f32).collect(); - [c[0], c[1], c[2], c.get(3).copied().unwrap_or(1.0)] - } - Some(Value::String(h)) => { - let h = h.trim_start_matches('#'); - let c = |i: usize| h.get(i..i + 2).and_then(|x| u8::from_str_radix(x, 16).ok()).map(|v| f32::from(v) / 255.0); - match (c(0), c(2), c(4)) { - (Some(r), Some(g), Some(b)) => [r, g, b, c(6).unwrap_or(1.0)], - _ => d, - } - } - _ => d, - } -} -fn point(p: &Value, k: &str) -> Option<(f32, f32)> { - let a = p.get(k)?.as_array()?; - Some((a.first()?.as_f64()? as f32, a.get(1)?.as_f64()? as f32)) -} - -/// `opacity` (1..100 %) as a coverage in 0.01..=1, clamped like the Magic Eraser's: a value -/// above 1 would overshoot the blend (#4167). -fn opacity(p: &Value, cmd: &str) -> Result { - Ok(crate::eraser_cmds::number(p, cmd, "opacity", 100.0, 1.0..=100.0)? as f32 / 100.0) -} - -/// The Paint Bucket's `mode`: a blend mode (not Pass Through, a group's) or `clear`. -fn fill_mode(p: &Value) -> Result { - let bad = |msg: String| EngineError::BadParams { cmd: "paint.bucket".into(), msg }; - match p.get("mode") { - None | Some(Value::Null) => Ok(FillMode::Blend(photocraft_color::BlendMode::Normal)), - Some(Value::String(m)) if m.eq_ignore_ascii_case("clear") => Ok(FillMode::Clear), - Some(Value::String(m)) => blend_from_str(m) - .filter(|m| *m != photocraft_color::BlendMode::PassThrough) - .map(FillMode::Blend) - .ok_or_else(|| bad(format!("unknown blend mode `{m}`"))), - Some(v) => Err(bad(format!("`mode` must be a blend mode name or `clear`, not {v}"))), - } -} - -fn bucket(s: &mut Session, p: &Value) -> Result { - let fg = s.tools.foreground; - let c = color(p.get("color"), fg); - let (x, y) = (f(p, "x", 0.0).floor() as i32, f(p, "y", 0.0).floor() as i32); - let (tol, contiguous, aa) = (f(p, "tolerance", 32.0), b(p, "contiguous", true), b(p, "antiAlias", true)); - let opacity = opacity(p, "paint.bucket")?; - let mode = fill_mode(p)?; - let all = b(p, "sampleAllLayers", false) && crate::channel_cmds::target_of(p) == crate::channel_cmds::Target::Pixels; - // Other visible layers can define the region, but the fill still writes only to the target. - let region = if all { - let (area, img) = crate::selection_cmds::sample_rgba8(s, true)?; - let region = photocraft_algo::selection::wand_region(&img, area, (x, y), tol, contiguous, aa); - drop(img); - region - } else { - None - }; - // Fill source: foreground colour (default) or a pattern (the Paint Bucket "Fill" dropdown). - let source = p.get("contents").or_else(|| p.get("source")).and_then(Value::as_str).unwrap_or("foreground"); - let pattern = if source == "pattern" { - let pat = crate::pattern_cmds::resolve_param(s, "paint.bucket", p)?; - let tile = photocraft_compose::pattern::Tile::new(&pat) - .ok_or_else(|| EngineError::BadParams { cmd: "paint.bucket".into(), msg: "the pattern is empty or too large to paint".into() })?; - let (scale, angle, _, phase) = crate::pattern_cmds::placement("paint.bucket", p)?; - Some((tile, scale, angle, phase)) - } else { - None - }; - // A foreground picked as CMYK fills a CMYK document with the picked inks (#4196). - let inks = s.tools.picked_cmyk([c[0], c[1], c[2]]).filter(|_| c[3] >= 1.0 && pattern.is_none()); - let filled = s.edit("Paint Bucket", |doc, active| { - let area = doc.bounds(); - let sel = doc.selection.clone(); - let (surf, lock) = crate::channel_cmds::target_surface(doc, *active, p)?; - let ok = if all && region.is_none() { - false - } else if let Some((tile, scale, angle, phase)) = &pattern { - // Render the pattern over the canvas once, then sample it at each filled pixel. - let place = photocraft_compose::pattern::Placement::new(photocraft_geom::Rect::EMPTY, false, *phase, *scale, *angle); - let rendered = photocraft_compose::pattern::render(tile, &place, area); - let w = area.width() as usize; - let src = |px: i32, py: i32| rendered[(py - area.y0) as usize * w + (px - area.x0) as usize]; - if let Some(region) = ®ion { - bucket_fill_region_inks(surf, region, opacity, sel.as_ref(), lock, src, None, mode); - true - } else { - bucket_fill_inks(surf, area, (x, y), tol, contiguous, aa, opacity, sel.as_ref(), lock, src, None, mode) - } - } else if let Some(region) = ®ion { - bucket_fill_region_inks(surf, region, opacity, sel.as_ref(), lock, |_, _| c, inks, mode); - true - } else { - bucket_fill_inks(surf, area, (x, y), tol, contiguous, aa, opacity, sel.as_ref(), lock, |_, _| c, inks, mode) - }; - surf.prune(); - Ok(ok) - })?; - Ok(json!({ "filled": filled })) -} - -fn gradient(s: &mut Session, p: &Value) -> Result { - let from = point(p, "from").ok_or_else(|| EngineError::BadParams { cmd: "paint.gradient".into(), msg: "missing from".into() })?; - let to = point(p, "to").ok_or_else(|| EngineError::BadParams { cmd: "paint.gradient".into(), msg: "missing to".into() })?; - let shape = match p.get("style").and_then(Value::as_str).unwrap_or("linear") { - "radial" => GradientShape::Radial, - "angle" => GradientShape::Angle, - "reflected" => GradientShape::Reflected, - "diamond" => GradientShape::Diamond, - _ => GradientShape::Linear, - }; - let (fg, bg) = (s.tools.foreground, s.tools.background); - // A preset (`gradient`), explicit `stops`, or the current gradient (Gradients panel); the - // legacy `colors` list spaces its colours evenly. Explicit `transparency` applies to all. - let stops: Vec<(f32, [f32; 4])> = match gradients::tool_stops(s, p)? { - Some(st) => st, - None => { - let colors: Vec<[f32; 4]> = - p.get("colors").and_then(Value::as_array).map(|a| a.iter().map(|v| color(Some(v), fg)).collect()).unwrap_or_else(|| vec![fg, bg]); - let n = colors.len(); - let cs = colors.into_iter().enumerate().map(|(i, c)| (if n > 1 { i as f32 / (n - 1) as f32 } else { 0.0 }, c)).collect(); - gradients::apply_opacity(cs, &gradients::transparency_param(p, "paint.gradient")?.unwrap_or_default()) - } - }; - // Photoshop's interpolation (`method`, with `smoothness` 0..=100, default 100) baked into dense - // stops, as for Gradient Overlay: Photoshop 27.11's Classic black → white is 0.037 at t = 1/16 - // where straight stops give 0.0625. - let stops = match p.get("method").and_then(Value::as_str).and_then(photocraft_io::GradientMethod::from_name) { - Some(m) if stops.len() >= 2 => { - let colors = stops.iter().map(|(t, c)| (*t, photocraft_color::Color::rgba(c[0], c[1], c[2], c[3]))).collect(); - let mids = vec![0.5; stops.len() - 1]; - photocraft_io::bake_gradient(colors, &mids, (f(p, "smoothness", 100.0) / 100.0).clamp(0.0, 1.0), m) - .into_iter() - .map(|(t, c)| { - let rgb = c.to_rgb(); - (t, [rgb[0], rgb[1], rgb[2], c.alpha]) - }) - .collect() - } - _ => stops, - }; - let reverse = b(p, "reverse", false); - let opacity = opacity(p, "paint.gradient")?; - let blend = p.get("mode").and_then(Value::as_str).and_then(blend_from_str).unwrap_or(photocraft_color::BlendMode::Normal); - let dither = b(p, "dither", true); // Photoshop dithers gradients by default (reduces banding). - s.edit("Gradient", |doc, active| { - let sel = doc.selection.clone(); - let area = sel.as_ref().map(|m| m.content_bounds()).filter(|r| !r.is_empty()).unwrap_or_else(|| doc.bounds()).intersect(&doc.bounds()); - let (surf, lock) = crate::channel_cmds::target_surface(doc, *active, p)?; - paint_gradient(surf, area, from, to, shape, &stops, reverse, opacity, blend, dither, sel.as_ref(), lock); - Ok(()) - })?; - Ok(Value::Null) -} - -/// Paint helper command specs. -pub fn specs() -> Vec { - vec![ - CommandSpec { - id: "paint.bucket", - label: "Paint Bucket", - menu: &[], - shortcut: None, - params: r##"{"x":px,"y":px,"tolerance":0..255=32,"contiguous":bool=true,"antiAlias":bool=true,"sampleAllLayers":bool=false,"contents":"foreground|pattern"="foreground","color":"#rrggbb"=foreground,"pattern":id|name (contents=pattern),"scale":%=100,"angle":deg,"opacity":1..100=100,"mode":"normal|multiply|…|clear (erases the filled area)"="normal","target":"pixels"|"mask"|"filterMask"|"quickMask"|{"channel":i}=Channels panel target}"##, - enabled: crate::commands::has_paintable, - run: bucket, - journal: true, - }, - CommandSpec { - id: "paint.gradient", - label: "Gradient", - menu: &[], - shortcut: None, - params: r##"{"from":[x,y],"to":[x,y],"style":"linear|radial|angle|reflected|diamond"="linear","colors":["#rrggbb",…]? (evenly spaced),"gradient":preset name?,"stops":[[t,"#rrggbb"|"foreground"|"background"],…]?,"transparency":[[t,0..100],…]? (default: the current gradient, see gradient.presets.select),"method":"classic|perceptual|linear|smooth"? (Photoshop's interpolation; omitted: straight stops),"smoothness":0..100=100,"reverse":bool=false,"dither":bool=true,"opacity":1..100=100,"mode":"normal|multiply|…"="normal","target":"pixels"|"mask"|"filterMask"|"quickMask"|{"channel":i}=Channels panel target}"##, - enabled: crate::commands::has_paintable, - run: gradient, - journal: true, - }, - ] -} - -#[cfg(test)] -mod tests { - use super::*; - use photocraft_geom::Rect; - - fn session() -> Session { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 20, "height": 10})).unwrap(); - s - } - - fn px(s: &Session, x: i32, y: i32) -> Vec { - let d = s.active().unwrap(); - d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap().pixel(x, y) - } - - /// A visible wall on the Background with an empty, active layer above it. - fn bucket_layers(depth: u32) -> (Session, photocraft_doc::LayerId) { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 20, "height": 10, "depth": depth, "background": "white"})).unwrap(); - let bottom = s.active().unwrap().active_layer.unwrap(); - s.edit("wall", |doc, _| { - doc.layer_mut(bottom).unwrap().surface_mut().unwrap().fill_rect(Rect::new(10, 0, 11, 10), &[0.0, 0.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - (s, bottom) - } - - /// The options bar's Mode reaches the fill: Multiply over grey, Clear erases, a bad name or - /// Pass Through is an error and changes nothing. - #[test] - fn bucket_mode_multiplies_clears_and_rejects_bad_names() { - for depth in [8, 16, 32] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 8, "height": 8, "depth": depth})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - let base = json!({"x": 1, "y": 1, "antiAlias": false, "tolerance": 0}); - let with = |extra: Value| { - let mut p = base.clone(); - p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); - p - }; - s.execute("paint.bucket", with(json!({"color": "#808080"}))).unwrap(); - s.execute("paint.bucket", with(json!({"color": "#ff0000", "mode": "multiply"}))).unwrap(); - let p = px(&s, 3, 3); - assert!((p[0] - 0.5).abs() < 0.01 && p[1] < 0.01 && p[3] > 0.99, "depth {depth}: {p:?}"); - for bad in [json!("passThrough"), json!("sparkle"), json!(3)] { - assert!(s.execute("paint.bucket", with(json!({"mode": bad}))).is_err(), "{bad}"); - } - assert_eq!(px(&s, 3, 3), p, "a refused mode paints nothing"); - s.execute("paint.bucket", with(json!({"mode": "Clear", "opacity": 50}))).unwrap(); - assert!((px(&s, 3, 3)[3] - 0.5).abs() < 0.01, "depth {depth}: half cleared"); - } - } - - #[test] - fn bucket_sample_all_layers_uses_visible_boundaries_at_all_depths() { - for depth in [8, 16, 32] { - for all in [None, Some(false), Some(true)] { - let (mut s, bottom) = bucket_layers(depth); - let before = s.active().unwrap().doc.layer(bottom).unwrap().clone(); - let mut p = json!({"x": 2, "y": 2, "color": "#ff0000", "antiAlias": false, "tolerance": 0}); - if let Some(all) = all { - p["sampleAllLayers"] = json!(all); - } - assert_eq!(s.execute("paint.bucket", p.clone()).unwrap()["filled"], true); - assert_eq!(px(&s, 5, 5), vec![1.0, 0.0, 0.0, 1.0], "depth {depth}, all {all:?}"); - let beyond = if all == Some(true) { vec![0.0; 4] } else { vec![1.0, 0.0, 0.0, 1.0] }; - assert_eq!(px(&s, 15, 5), beyond, "depth {depth}, all {all:?}: sample flag controls the boundary"); - assert_eq!(s.active().unwrap().doc.layer(bottom).unwrap(), &before, "only the active layer is written"); - if all == Some(true) { - assert_eq!(px(&s, 10, 5), vec![0.0; 4], "wall itself is untouched"); - assert!(s.undo()); - p["contiguous"] = json!(false); - s.execute("paint.bucket", p).unwrap(); - assert_eq!(px(&s, 15, 5), vec![1.0, 0.0, 0.0, 1.0], "noncontiguous finds both white regions"); - assert_eq!(px(&s, 10, 5), vec![0.0; 4]); - assert!(s.undo()); - assert_eq!(s.execute("paint.bucket", json!({"x": -1, "y": 2, "sampleAllLayers": true})).unwrap()["filled"], false); - assert_eq!(px(&s, 5, 5), vec![0.0; 4], "an off-canvas sample does not fill the layer"); - } - } - } - } - - #[test] - fn bucket_sample_all_layers_ignores_hidden_layers() { - let (mut s, _) = bucket_layers(8); - s.edit("hidden wall", |doc, active| { - let l = doc.layer_mut(active.unwrap()).unwrap(); - l.surface_mut().unwrap().fill_rect(Rect::new(4, 0, 5, 10), &[0.0, 0.0, 0.0, 1.0]); - l.visible = false; - Ok(()) - }) - .unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.execute("paint.bucket", json!({"x": 2, "y": 2, "color": "#ff0000", "antiAlias": false, "tolerance": 0, "sampleAllLayers": true})).unwrap(); - assert_eq!(px(&s, 4, 5), vec![1.0, 0.0, 0.0, 1.0], "hidden wall does not bound the fill"); - assert_eq!(px(&s, 8, 5), vec![1.0, 0.0, 0.0, 1.0]); - assert_eq!(px(&s, 15, 5), vec![0.0; 4], "visible wall still bounds the fill"); - } - - #[test] - fn bucket_sample_all_layers_keeps_selection_opacity_and_history() { - for depth in [8, 16, 32] { - let (mut s, _) = bucket_layers(depth); - s.execute("select.rect", json!({"x": 0, "y": 2, "width": 20, "height": 6})).unwrap(); - s.edit("feather", |doc, _| { - doc.selection.as_mut().unwrap().fill_rect(Rect::new(0, 2, 4, 8), &[0.5]); - Ok(()) - }) - .unwrap(); - let selection = s.active().unwrap().doc.selection.clone(); - s.execute("paint.bucket", json!({"x": 2, "y": 5, "color": "#ff0000", "antiAlias": false, "tolerance": 0, "opacity": 50, "sampleAllLayers": true})) - .unwrap(); - let (feathered, full) = (px(&s, 2, 5), px(&s, 6, 5)); - assert!((feathered[3] - 0.25).abs() < 0.005 && (full[3] - 0.5).abs() < 0.005, "depth {depth}: selection coverage multiplies opacity"); - assert_eq!(full[..3], [1.0, 0.0, 0.0]); - assert_eq!(px(&s, 6, 1), vec![0.0; 4], "outside selection"); - assert_eq!(px(&s, 15, 5), vec![0.0; 4], "outside sampled region"); - assert_eq!(s.active().unwrap().history.undo_label(), Some("Paint Bucket")); - assert!(s.undo()); - assert_eq!(px(&s, 2, 5), vec![0.0; 4]); - assert_eq!(s.active().unwrap().doc.selection, selection); - assert!(s.redo()); - assert_eq!(px(&s, 2, 5), feathered); - assert_eq!(px(&s, 6, 5), full); - assert_eq!(s.active().unwrap().doc.selection, selection); - } - } - - #[test] - fn bucket_sample_all_layers_pattern_uses_the_same_region() { - let (mut s, _) = bucket_layers(8); - s.execute( - "paint.bucket", - json!({"x": 2, "y": 2, "contents": "pattern", "pattern": "Diagonal Lines", "antiAlias": false, "tolerance": 0, "sampleAllLayers": true}), - ) - .unwrap(); - let left: Vec = (0..10).map(|x| px(&s, x, 0)[0]).collect(); - assert!(left.iter().any(|&r| r < 0.3) && left.iter().any(|&r| r > 0.9), "pattern varies inside the region: {left:?}"); - assert_eq!(px(&s, 10, 5), vec![0.0; 4], "wall untouched"); - assert_eq!(px(&s, 15, 5), vec![0.0; 4], "region past the wall untouched"); - } - - #[test] - fn bucket_sample_all_layers_mask_and_channel_targets_keep_their_own_boundaries() { - for target in [json!("mask"), json!({"channel": 0}), json!("quickMask")] { - for all in [false, true] { - let (mut s, _) = bucket_layers(8); - match crate::channel_cmds::target_of(&json!({"target": target})) { - crate::channel_cmds::Target::Mask => { - s.execute("layer.layerMask.revealAll", json!({})).unwrap(); - } - crate::channel_cmds::Target::Alpha(_) => { - s.execute("channel.new", json!({"fill": "white"})).unwrap(); - } - crate::channel_cmds::Target::QuickMask => { - s.execute("select.editInQuickMaskMode", json!({"on": true})).unwrap(); - } - _ => panic!("expected a grayscale target"), - } - let p = json!({"x": 2, "y": 2, "color": "#000000", "antiAlias": false, "tolerance": 0, "target": target, "sampleAllLayers": all}); - s.edit("target wall", |doc, active| { - let area = doc.bounds(); - let (surf, _) = crate::channel_cmds::target_surface(doc, *active, &p).unwrap(); - surf.fill_rect(area, &[1.0]); - surf.fill_rect(Rect::new(5, 0, 6, 10), &[0.0]); - Ok(()) - }) - .unwrap(); - s.execute("paint.bucket", p.clone()).unwrap(); - let d = &s.active().unwrap().doc; - let surf = match crate::channel_cmds::target_of(&p) { - crate::channel_cmds::Target::Mask => &d.layer(s.active().unwrap().active_layer.unwrap()).unwrap().mask.as_ref().unwrap().surface, - crate::channel_cmds::Target::Alpha(i) => &d.channels[i].surface, - crate::channel_cmds::Target::QuickMask => &d.quick_mask.as_ref().unwrap().surface, - _ => panic!("expected a grayscale target"), - }; - assert_eq!(surf.sample_channel(2, 5, 0), 0.0, "{target}, all {all}: filled target"); - assert_eq!(surf.sample_channel(7, 5, 0), 1.0, "{target}, all {all}: stopped at target wall"); - assert_eq!(px(&s, 2, 5), vec![0.0; 4], "layer pixels remain untouched"); - } - } - } - - #[test] - fn bucket_fill_contiguous() { - let mut s = session(); - s.edit("wall", |doc, _| { - doc.layers[0].surface_mut().unwrap().fill_rect(Rect::new(10, 0, 11, 10), &[0.0, 0.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - s.execute("paint.bucket", json!({"x": 2, "y": 2, "color": "#ff0000", "antiAlias": false})).unwrap(); - assert_eq!(px(&s, 5, 5), vec![1.0, 0.0, 0.0, 1.0]); - assert_eq!(px(&s, 15, 5), vec![1.0, 1.0, 1.0, 1.0]); - s.execute("paint.bucket", json!({"x": 2, "y": 2, "color": "#0000ff", "contiguous": false, "antiAlias": false, "tolerance": 0})).unwrap(); - assert_eq!(px(&s, 5, 5), vec![0.0, 0.0, 1.0, 1.0]); - } - - /// #4196: the Paint Bucket and Edit > Stroke write a CMYK pick as its inks into a CMYK document, - /// not as its sRGB stand-in converted back (100/0/0/0 cyan would come out as about 100/28/0/17). - #[test] - fn bucket_and_stroke_write_a_cmyk_pick_as_its_inks() { - let cyan = [1.0f32, 0.0, 0.0, 0.0]; - let mut s = session(); - s.execute("image.mode.cmyk", json!({})).unwrap(); - let rgb = photocraft_color::convert::cmyk_to_rgb(cyan).map(|c| c.clamp(0.0, 1.0)); - s.execute("tools.setColors", json!({"foreground": rgb, "foregroundCmyk": cyan})).unwrap(); - let inks_at = |s: &Session, x: i32, y: i32| -> Vec { - let st = s.active().unwrap(); - let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); - surf.read_region(Rect::new(x, y, x + 1, y + 1)).into_iter().take(4).collect() - }; - let is_cyan = |got: &[f32]| got.iter().zip(cyan).all(|(a, b)| (a - b).abs() < 0.02); - s.execute("paint.bucket", json!({"x": 2, "y": 2, "antiAlias": false})).unwrap(); - let got = inks_at(&s, 5, 5); - assert!(is_cyan(&got), "bucket: {got:?}"); - s.execute("select.all", json!({})).unwrap(); - s.execute("edit.stroke", json!({"width": 2, "location": "inside", "color": rgb})).unwrap(); - let got = inks_at(&s, 0, 5); - assert!(is_cyan(&got), "stroke: {got:?}"); - } - - #[test] - fn bucket_fills_with_a_pattern() { - // Paint Bucket with contents="pattern" flood-fills the region with a pattern, not a colour. - let mut s = session(); - s.edit("wall", |doc, _| { - doc.layers[0].surface_mut().unwrap().fill_rect(Rect::new(10, 0, 11, 10), &[0.0, 0.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - s.execute("paint.bucket", json!({"x": 2, "y": 2, "contents": "pattern", "pattern": "Diagonal Lines", "antiAlias": false, "tolerance": 0})).unwrap(); - // The filled region (left of the wall) now carries the pattern's light/dark variation, - // while the wall and the region past it are untouched. - let left: Vec<[f32; 4]> = (0..10) - .map(|x| { - let p = px(&s, x, 0); - [p[0], p[1], p[2], p[3]] - }) - .collect(); - assert!(left.iter().any(|p| p[0] < 0.3) && left.iter().any(|p| p[0] > 0.9), "pattern varies in the fill: {left:?}"); - assert_eq!(px(&s, 15, 5), vec![1.0, 1.0, 1.0, 1.0], "region past the wall untouched"); - } - - #[test] - fn gradient_tool_with_selection_and_reverse() { - let mut s = session(); - s.execute("paint.gradient", json!({"from": [0, 0], "to": [20, 0], "colors": ["#000000", "#ffffff"]})).unwrap(); - assert!(px(&s, 0, 5)[0] < 0.05 && px(&s, 19, 5)[0] > 0.95); - s.execute("paint.gradient", json!({"from": [0, 0], "to": [20, 0], "colors": ["#000000", "#ffffff"], "reverse": true})).unwrap(); - assert!(px(&s, 0, 5)[0] > 0.95); - s.execute("select.rect", json!({"x": 0, "y": 0, "width": 5, "height": 10})).unwrap(); - s.execute("paint.gradient", json!({"from": [0, 0], "to": [0, 10], "colors": ["#ff0000"]})).unwrap(); - assert_eq!(px(&s, 2, 5)[..3], [1.0, 0.0, 0.0]); - assert!(px(&s, 10, 5)[1] > 0.4, "outside the selection untouched"); - assert!(s.execute("paint.gradient", json!({"from": [0, 0]})).is_err()); - } - - #[test] - fn gradient_dither_breaks_banding() { - // A flat gradient (same colour both ends) is perfectly smooth with dither off, and gains - // per-pixel noise with dither on (which breaks 8-bit banding). - let run = |dither: bool| { - let mut s = session(); - s.execute("paint.gradient", json!({"from": [0, 0], "to": [19, 0], "colors": [[0.5, 0.5, 0.5, 1.0], [0.5, 0.5, 0.5, 1.0]], "dither": dither})) - .unwrap(); - (0..19).map(|x| px(&s, x, 5)[0]).collect::>() - }; - let smooth = run(false); - assert!(smooth.iter().all(|&v| v == smooth[0]), "no dither: perfectly flat"); - let noisy = run(true); - assert!(noisy.windows(2).any(|w| w[0] != w[1]), "dither: per-pixel variation"); - } - - /// The two commands under test, each painting #808080 over a white document. - fn grey_fill(cmd: &str, opacity: Value) -> Value { - match cmd { - "paint.bucket" => json!({"x": 2, "y": 2, "color": "#808080", "opacity": opacity}), - _ => json!({"from": [0, 0], "to": [19, 0], "colors": ["#808080", "#808080"], "dither": false, "opacity": opacity}), - } - } - - fn white(depth: u32) -> Session { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 20, "height": 10, "depth": depth, "background": "white"})).unwrap(); - s - } - - /// Issue #4167: an opacity above 100 overshot the blend (200 painted near-black on white). - #[test] - fn bucket_and_gradient_clamp_opacity_like_the_magic_eraser() { - for cmd in ["paint.bucket", "paint.gradient"] { - for depth in [8, 16, 32] { - let mut full = white(depth); - full.execute(cmd, grey_fill(cmd, json!(100))).unwrap(); - let expected = px(&full, 5, 5); - assert!((expected[0] - 128.0 / 255.0).abs() < 0.01, "{cmd} depth {depth}: 100% paints #808080, got {expected:?}"); - for over in [200.0, 1e9] { - let mut s = white(depth); - s.execute(cmd, grey_fill(cmd, json!(over))).unwrap(); - assert_eq!(px(&s, 5, 5), expected, "{cmd} depth {depth}: opacity {over} clamps to 100"); - } - let (mut low, mut one) = (white(depth), white(depth)); - low.execute(cmd, grey_fill(cmd, json!(-50))).unwrap(); - one.execute(cmd, grey_fill(cmd, json!(1))).unwrap(); - assert_eq!(px(&low, 5, 5), px(&one, 5, 5), "{cmd} depth {depth}: opacity below 1 clamps to 1"); - assert!(px(&low, 5, 5).iter().all(|v| (0.0..=1.0).contains(v)), "{cmd} depth {depth}: no overshoot"); - } - } - } - - #[test] - fn bucket_and_gradient_reject_non_numeric_opacity_without_editing() { - for cmd in ["paint.bucket", "paint.gradient"] { - for bad in [json!("50"), json!(true), json!([50]), json!({"v": 50})] { - let mut s = white(8); - let (before, steps) = (px(&s, 5, 5), s.active().unwrap().history.past_len()); - let err = s.execute(cmd, grey_fill(cmd, bad.clone())).unwrap_err(); - assert!(matches!(err, EngineError::BadParams { .. }), "{cmd} {bad}: {err:?}"); - assert_eq!(px(&s, 5, 5), before, "{cmd} {bad}: pixels unchanged"); - assert_eq!(s.active().unwrap().history.past_len(), steps, "{cmd} {bad}: no history step"); - } - // An explicit null keeps the default (100%), like the Magic Eraser. - let mut s = white(8); - s.execute(cmd, grey_fill(cmd, Value::Null)).unwrap(); - assert!((px(&s, 5, 5)[0] - 128.0 / 255.0).abs() < 0.01, "{cmd}: null opacity is 100%"); - } - } -} diff --git a/crates/engine/src/pixels.rs b/crates/engine/src/pixels.rs index 01339e859d..3f6b074153 100644 --- a/crates/engine/src/pixels.rs +++ b/crates/engine/src/pixels.rs @@ -123,10 +123,8 @@ pub fn adjust_surface(s: &mut Surface, adj: &Adjustment, selection: Option<&Surf } #[cfg(test)] -#[path = "flatten_cmyk_tests.rs"] mod flatten_cmyk_tests; #[cfg(test)] -#[path = "pixels_tests.rs"] mod tests; /// Applies `adj` to a layer mask through the selection. Untouched mask pixels count (they read as diff --git a/crates/engine/src/flatten_cmyk_tests.rs b/crates/engine/src/pixels/flatten_cmyk_tests.rs similarity index 100% rename from crates/engine/src/flatten_cmyk_tests.rs rename to crates/engine/src/pixels/flatten_cmyk_tests.rs diff --git a/crates/engine/src/pixels_tests.rs b/crates/engine/src/pixels/tests.rs similarity index 100% rename from crates/engine/src/pixels_tests.rs rename to crates/engine/src/pixels/tests.rs diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 1525741a5e..24cba73d4d 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -433,6 +433,25 @@ impl Default for Tools { /// since a whole-section update or a hand-edited preferences file can store anything. pub use photocraft_paint::ResponseCurve as PressureCurve; +mod cmds; +mod customize; +mod files; +mod shortcuts; +mod store; +mod validate; + +pub use cmds::specs; +#[cfg(test)] +pub(crate) use files::write_files_atomically; +pub use shortcuts::{ + ALTERNATE_SHORTCUTS, BindKind, MAX_ALTERNATES, TEMPORARY_TOOLS, alternate_keys, bindable_items, conflicts, default_alternates, normalize_shortcut, + reserved_shortcut, +}; +use store::read_lenient; +pub use store::{InvalidPref, PREFS_VERSION, PrefsStore}; +pub use validate::{HIDDEN_UNTIL_IMPLEMENTED, LINUX_ONLY, SECTIONS, choices, gpu_adapter_matches, is_color, is_hidden, parse_hex, range}; +use validate::{check_value, get_path, keyed, set_path}; + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] pub struct HistoryLog { @@ -1122,276 +1141,6 @@ pub struct Preferences { pub layer_mask_overlay: LayerMaskOverlay, } -/// Preferences dialog sections in Photoshop's order: (id, title). -pub const SECTIONS: [(&str, &str); 18] = [ - ("general", "General"), - ("interface", "Interface"), - ("workspace", "Workspace"), - ("tools", "Tools"), - ("historyLog", "History Log"), - ("fileHandling", "File Handling"), - ("export", "Export"), - ("performance", "Performance"), - ("scratchDisks", "Scratch Disks"), - ("cursors", "Cursors"), - ("transparencyAndGamut", "Transparency & Gamut"), - ("unitsAndRulers", "Units & Rulers"), - ("guidesGridAndSlices", "Guides, Grid & Slices"), - ("plugIns", "Plug-ins"), - ("type", "Type"), - ("enhancedControls", "Enhanced Controls"), - ("rawDefaults", "Camera Raw Defaults"), - ("integrations", "Integrations"), -]; - -/// Preferences that nothing reads yet, so Edit › Preferences doesn't show them: a control that -/// does nothing is worse than a missing one (https://github.com/storytold/photocraft/issues/204). -/// They still load, save and round-trip through `prefs.get` / `prefs.set` unchanged. -/// -/// When you implement one, remove it here; the `prefs_usage` test fails while a listed -/// preference is read anywhere outside `prefs.rs`, and while an unlisted one is read nowhere. -pub const HIDDEN_UNTIL_IMPLEMENTED: &[&str] = &[ - "general.colorPicker", - "workspace.autoShowHiddenPanels", - "workspace.enableFloatingDocumentWindowDocking", - "performance.effectCacheMb", - "performance.legacyCompositing", - "scratchDisks.disks", - "unitsAndRulers.columnWidth", - "unitsAndRulers.gutter", - "plugIns.showExtensionPanels", - "plugIns.allowScriptsToConnect", - "type.textEngine", - "enhancedControls.scrubbySliderAcceleration", -]; - -/// Is the preference at `path` (`"section.key"`) hidden from the Preferences dialog? -pub fn is_hidden(path: &str) -> bool { - HIDDEN_UNTIL_IMPLEMENTED.contains(&path) || (!cfg!(target_os = "linux") && LINUX_ONLY.contains(&path)) -} - -/// Preferences that only do something on Linux; the dialog doesn't show them elsewhere. They -/// still load, save and round-trip on every platform. -pub const LINUX_ONLY: &[&str] = &["performance.linuxDisplayServer", "performance.gpuAdapter"]; - -/// Whether a graphics adapter called `name` is the one `performance.gpuAdapter` (`wanted`) asks -/// for: every whitespace-separated word of `wanted` appears in the name, ignoring case ("nvidia", -/// "arc a370m"). An empty `wanted` matches nothing. Startup and Preferences share this. -pub fn gpu_adapter_matches(name: &str, wanted: &str) -> bool { - let name = name.to_lowercase(); - let mut words = wanted.split_whitespace().peekable(); - words.peek().is_some() && words.all(|w| name.contains(&w.to_lowercase())) -} - -/// Choices of an enumerated preference (dotted path, e.g. `"cursors.painting"`). -pub fn choices(path: &str) -> Option<&'static [&'static str]> { - Some(match path { - "general.colorPicker" => ColorPicker::NAMES, - "general.imageInterpolation" => Interpolation::NAMES, - "interface.theme" => Theme::NAMES, - "interface.appearanceMode" => AppearanceMode::NAMES, - "interface.darkTheme" => DarkTheme::NAMES, - "interface.lightTheme" => LightTheme::NAMES, - "interface.canvasColor" => CanvasColor::NAMES, - "interface.canvasBorder" => CanvasBorder::NAMES, - "interface.uiScale" => UiScale::NAMES, - "interface.uiFontSize" => UiFontSize::NAMES, - "historyLog.destination" => LogDestination::NAMES, - "historyLog.detail" => LogDetail::NAMES, - "fileHandling.imagePreviews" | "fileHandling.maximizePsdCompatibility" => Ask::NAMES, - "export.quickExportFormat" => QuickExportFormat::NAMES, - "export.quickExportLocation" => ExportLocation::NAMES, - "export.metadata" => ExportMetadata::NAMES, - "cursors.painting" => PaintingCursor::NAMES, - "cursors.other" => OtherCursor::NAMES, - "tools.rightClickWithPaintingTools" => RightClickPaint::NAMES, - "transparencyAndGamut.gridSize" => CheckerSize::NAMES, - "transparencyAndGamut.gridColors" => CheckerColors::NAMES, - "unitsAndRulers.rulers" | "guidesGridAndSlices.gridUnit" => Unit::NAMES, - "unitsAndRulers.typeUnits" => TypeUnit::NAMES, - "unitsAndRulers.pointSize" => PointSize::NAMES, - "guidesGridAndSlices.guideStyle" | "guidesGridAndSlices.gridStyle" => LineStyle::NAMES, - "type.textEngine" => TextEngine::NAMES, - "type.fontPreview" => FontPreview::NAMES, - "rawDefaults.colorSpace" => RawColorSpace::NAMES, - "rawDefaults.bitDepth" => RawDepth::NAMES, - "rawDefaults.sharpenFor" => RawSharpen::NAMES, - "rawDefaults.demosaic" => RawDemosaic::NAMES, - "performance.gpuBackend" => GpuBackend::NAMES, - "performance.linuxDisplayServer" => LinuxDisplayServer::NAMES, - "performance.renderingMode" => RenderingMode::NAMES, - _ => return None, - }) -} - -/// Valid range of a numeric preference. -pub fn range(path: &str) -> Option<(f64, f64)> { - Some(match path { - "fileHandling.autosaveMinutes" => (1.0, 240.0), - "fileHandling.recentFileCount" => (0.0, 100.0), - "tools.nudgeBundlePauseMs" => (100.0, 10_000.0), - "fileHandling.rasterizeSvgGroupsDeeperThan" => (0.0, photocraft_doc::MAX_GROUP_DEPTH as f64), - "interface.notificationDurationSeconds" => (1.0, 120.0), - "export.jpegQuality" | "export.webpQuality" => (1.0, 100.0), - "performance.memoryUsageMb" => (256.0, 1_048_576.0), - "performance.gpuMemoryMb" => (0.0, 1_048_576.0), - "performance.historyStates" => (1.0, 1000.0), - "performance.cacheLevels" => (1.0, 8.0), - "performance.cacheTileSize" => (256.0, 16384.0), - "performance.effectCacheMb" => (16.0, 65536.0), - "transparencyAndGamut.gamutWarningOpacity" => (1.0, 100.0), - "unitsAndRulers.columnWidth" | "unitsAndRulers.gutter" => (0.0, 10_000.0), - "unitsAndRulers.printResolution" | "unitsAndRulers.screenResolution" | "rawDefaults.resolution" => (1.0, 10_000.0), - "guidesGridAndSlices.gridlineEvery" => (0.001, 10_000.0), - "guidesGridAndSlices.subdivisions" => (1.0, 100.0), - "layerMaskOverlay.opacity" => (0.0, 100.0), - "type.recentFonts" => (0.0, 50.0), - "integrations.controlPort" => (0.0, 65535.0), - _ => return None, - }) -} - -/// Is this preference a `#rrggbb` colour? -pub fn is_color(path: &str) -> bool { - if choices(path).is_some() || path.starts_with("shortcuts.") || path.starts_with("alternateShortcuts.") || path.starts_with("menus.") { - return false; - } - if path == "layerMaskOverlay.color" { - return true; - } - let leaf = path.rsplit('.').next().unwrap_or(path); - matches!( - leaf, - "guideColor" - | "smartGuideColor" - | "gridColor" - | "sliceColor" - | "canvasCustomColor" - | "brushPreviewColor" - | "gamutWarningColor" - | "customLight" - | "customDark" - ) -} - -pub fn parse_hex(s: &str) -> Option<[u8; 3]> { - let s = s.trim().trim_start_matches('#'); - if s.len() != 6 { - return None; - } - let b = |i: usize| s.get(i..i + 2).and_then(|s| u8::from_str_radix(s, 16).ok()); - Some([b(0)?, b(2)?, b(4)?]) -} - -// ------------------------------------------------------------------ JSON paths - -/// Map keys that are command ids (which contain dots): `shortcuts.`, -/// `alternateShortcuts.`, `menus.colors.`. -fn keyed(path: &str) -> Option<(&str, &str)> { - for prefix in ["shortcuts.", "alternateShortcuts.", "menus.colors."] { - if let Some(id) = path.strip_prefix(prefix) { - return Some((&prefix[..prefix.len() - 1], id)); - } - } - None -} - -fn get_path<'a>(root: &'a Value, path: &str) -> Option<&'a Value> { - if path.is_empty() { - return Some(root); - } - if let Some((map, id)) = keyed(path) { - return get_path(root, map)?.get(id); - } - path.split('.').try_fold(root, |v, k| v.get(k)) -} - -/// Set `value` at `path` (creating keys only inside free-form maps such as `shortcuts`). -fn set_path(root: &mut Value, path: &str, value: Value) -> std::result::Result<(), String> { - if let Some((map, id)) = keyed(path) { - let mut cur = &mut *root; - for k in map.split('.') { - cur = cur.get_mut(k).ok_or_else(|| format!("unknown preference `{path}`"))?; - } - cur.as_object_mut().ok_or_else(|| format!("`{map}` is not a map"))?.insert(id.to_string(), value); - return Ok(()); - } - let keys: Vec<&str> = path.split('.').filter(|k| !k.is_empty()).collect(); - let Some((last, parents)) = keys.split_last() else { return Err("empty path".into()) }; - let mut cur = root; - for k in parents { - cur = cur.get_mut(*k).ok_or_else(|| format!("unknown preference `{path}`"))?; - } - let free_map = matches!(parents.first(), Some(&"shortcuts")) || (parents.len() == 2 && parents[0] == "menus" && parents[1] == "colors"); - let obj = cur.as_object_mut().ok_or_else(|| format!("`{path}` is not inside a section"))?; - if !obj.contains_key(*last) && !free_map { - return Err(format!("unknown preference `{path}`")); - } - obj.insert(last.to_string(), value); - Ok(()) -} - -/// Validate one value for `path` before it is stored (choices, ranges, colours). -fn check_value(path: &str, v: &Value) -> std::result::Result<(), String> { - if path == "interface.favoriteThemes" { - let items = v.as_array().ok_or("`interface.favoriteThemes` must be a list of theme ids")?; - if items.len() > Theme::NAMES.len() { - return Err("`interface.favoriteThemes` contains too many themes".into()); - } - let mut seen = Vec::with_capacity(items.len()); - for item in items { - let theme = item.as_str().and_then(Theme::parse).ok_or_else(|| format!("unknown favorite theme `{item}`"))?; - if seen.contains(&theme) { - return Err(format!("duplicate favorite theme `{}`", theme.name())); - } - seen.push(theme); - } - } - if path == "performance.renderingMode" && v.is_null() { - return Ok(()); // Legacy policy, resolved from useGpu and gpuBackend. - } - if let Some(c) = choices(path) { - let s = v.as_str().ok_or_else(|| format!("`{path}` must be one of {}", c.join("|")))?; - if !c.contains(&s) { - return Err(format!("`{path}` must be one of {} (got `{s}`)", c.join("|"))); - } - } - if path == "interface.language" { - let ok = v.as_str().is_some_and(|s| !s.is_empty() && s.len() <= 16 && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')); - if !ok { - return Err("`interface.language` must be `auto` or a language code such as `en` or `ja`".into()); - } - } - if let Some((lo, hi)) = range(path) { - let x = v.as_f64().ok_or_else(|| format!("`{path}` must be a number"))?; - if !(lo..=hi).contains(&x) { - return Err(format!("`{path}` must be within {lo}..{hi} (got {x})")); - } - } - if is_color(path) && v.as_str().and_then(parse_hex).is_none() { - return Err(format!("`{path}` must be a #rrggbb colour")); - } - if path == "tools.pressureCurve" { - let pts = v.as_array().ok_or("`tools.pressureCurve` must be a list of [input, output] points")?; - if !(2..=PressureCurve::MAX_POINTS).contains(&pts.len()) { - return Err(format!("`tools.pressureCurve` needs 2..={} points (got {})", PressureCurve::MAX_POINTS, pts.len())); - } - for p in pts { - let ok = p.as_array().is_some_and(|a| a.len() == 2 && a.iter().all(|x| x.as_f64().is_some_and(|x| (0.0..=1.0).contains(&x)))); - if !ok { - return Err(format!("`tools.pressureCurve` points are [input, output] pairs within 0..1 (got {p})")); - } - } - } - if let Some(sc) = path.strip_prefix("shortcuts.") { - let s = v.as_str().ok_or_else(|| format!("shortcut for `{sc}` must be a string"))?; - if !s.is_empty() && normalize_shortcut(s).is_none() { - return Err(format!("`{s}` is not a valid shortcut (e.g. Cmd+Shift+N, F7)")); - } - } - Ok(()) -} - impl Preferences { /// The preferences as JSON (camelCase keys). pub fn to_json(&self) -> Value { @@ -1506,340 +1255,6 @@ impl Preferences { } } -/// Most further keys one command may hold; Photoshop's own defaults use one. -pub const MAX_ALTERNATES: usize = 8; - -/// Validate and normalise a command's alternate keys: a list of shortcut strings (a single -/// string is a one-key list, `""` none). -pub fn alternate_keys(v: &Value) -> std::result::Result, String> { - let items: Vec<&Value> = match v { - Value::String(s) if s.is_empty() => Vec::new(), - Value::String(_) => vec![v], - Value::Array(a) => a.iter().collect(), - _ => return Err("alternate shortcuts are a list of shortcuts (e.g. [\"F3\"])".into()), - }; - if items.len() > MAX_ALTERNATES { - return Err(format!("at most {MAX_ALTERNATES} alternate shortcuts (got {})", items.len())); - } - let mut out: Vec = Vec::with_capacity(items.len()); - for item in items { - let s = item.as_str().ok_or_else(|| format!("alternate shortcut `{item}` must be a string"))?; - let n = normalize_shortcut(s).ok_or_else(|| format!("`{s}` is not a valid shortcut (e.g. Cmd+Shift+N, F7)"))?; - if !out.contains(&n) { - out.push(n); - } - } - Ok(out) -} - -// ------------------------------------------------------------------ shortcuts - -/// Canonical spelling of a shortcut: modifiers in `Cmd+Ctrl+Alt+Shift` order, key last -/// (single characters upper-cased). `None` if it has no key or an unknown modifier. -pub fn normalize_shortcut(s: &str) -> Option { - let s = s.trim(); - if s.is_empty() { - return None; - } - let (mut cmd, mut ctrl, mut alt, mut shift) = (false, false, false, false); - let mut key: Option = None; - // A trailing "+" key is spelled "Cmd++". - let (body, plus_key) = if s.ends_with("++") || s == "+" { (s.trim_end_matches('+'), true) } else { (s, false) }; - for part in body.split('+').filter(|p| !p.is_empty()) { - match part.to_ascii_lowercase().as_str() { - "cmd" | "command" | "⌘" | "meta" | "super" => cmd = true, - "ctrl" | "control" | "⌃" => ctrl = true, - "alt" | "option" | "opt" | "⌥" => alt = true, - "shift" | "⇧" => shift = true, - _ => { - if key.is_some() { - return None; - } - let k = if part.chars().count() == 1 { part.to_uppercase() } else { capitalize(part) }; - key = Some(k); - } - } - } - if plus_key { - if key.is_some() { - return None; - } - key = Some("+".into()); - } - let key = key?; - let mut out = Vec::new(); - if cmd { - out.push("Cmd"); - } - if ctrl { - out.push("Ctrl"); - } - if alt { - out.push("Alt"); - } - if shift { - out.push("Shift"); - } - let mut s = out.join("+"); - if !s.is_empty() { - s.push('+'); - } - s.push_str(&key); - Some(s) -} - -/// Key names spelled with more than one capital (egui's `Key::name`): Title case would turn -/// `PageUp` into `Pageup`, which no key matches, so a binding saved that way never fired (#6827). -const MULTI_WORD_KEYS: [&str; 8] = - ["PageUp", "PageDown", "OpenBracket", "CloseBracket", "OpenCurlyBracket", "CloseCurlyBracket", "BrowserBack", "IntlBackslash"]; - -fn capitalize(s: &str) -> String { - if let Some(k) = MULTI_WORD_KEYS.iter().find(|k| k.eq_ignore_ascii_case(s)) { - return (*k).to_string(); - } - let mut c = s.chars(); - match c.next() { - Some(f) if f.is_ascii_alphabetic() => { - let rest: String = c.collect(); - // Function keys stay upper-case (F1…F24); named keys are Title case. - if f.eq_ignore_ascii_case(&'f') && rest.chars().all(|c| c.is_ascii_digit()) && !rest.is_empty() { - format!("F{rest}") - } else { - format!("{}{}", f.to_ascii_uppercase(), rest.to_ascii_lowercase()) - } - } - _ => s.to_string(), - } -} - -/// Hold-and-release gestures (#249): temporary tools that last while their key is held and give -/// the previous tool back on release. They are bound like shortcuts (Edit › Keyboard Shortcuts › -/// Tools › Temporary, `edit.keyboardShortcuts`) but held rather than pressed, so they are not -/// commands; the UI reads their keys through [`Preferences::shortcut`]. While a selection or -/// shape is being dragged, the Hand key repositions it instead of panning (Photoshop's Space). -/// The erase key keeps the Brush or Pencil and makes its strokes erase (Photoshop's `~`). -pub const TEMPORARY_TOOLS: &[(&str, &str, &str)] = &[ - ("tools.temporary.hand", "Hand Tool (hold)", "Space"), - ("tools.temporary.zoomIn", "Zoom In (hold, drag to scrub)", "Cmd+Space"), - ("tools.temporary.zoomOut", "Zoom Out (hold)", "Alt+Space"), - ("tools.temporary.erase", "Erase with Brush or Pencil (hold)", "`"), -]; - -/// Photoshop's second default keys (#3665): (command, key). Each command keeps its main key -/// (the one its menu shows) and answers these as well, as in Photoshop's default set: the -/// legacy function keys F2 Cut, F3 Copy, F4 Paste and Shift+F7 Inverse; Shift+Backspace -/// (Shift+Delete on a Mac) for Fill; ⌘+ beside ⌘= for Zoom In; and off the Mac, Ctrl+F4 beside -/// Ctrl+W for Close (Windows' close-document key; macOS keeps Ctrl+F4 for window focus). -pub const ALTERNATE_SHORTCUTS: &[(&str, &str)] = &[ - ("edit.cut", "F2"), - ("edit.copy", "F3"), - ("edit.paste", "F4"), - ("edit.fill", "Shift+Backspace"), - ("select.inverse", "Shift+F7"), - ("view.zoomIn", "Cmd++"), - #[cfg(not(target_os = "macos"))] - ("file.close", "Cmd+F4"), -]; - -/// A command's default alternate keys ([`ALTERNATE_SHORTCUTS`]). -pub fn default_alternates(id: &str) -> impl Iterator + '_ { - ALTERNATE_SHORTCUTS.iter().filter(move |(c, _)| *c == id).map(|(_, sc)| *sc) -} - -/// Keys the system takes before the app sees them (switching apps, closing the window, force -/// quit): `edit.keyboardShortcuts` won't bind them, as Photoshop won't. `sc` is in our notation, -/// where `Cmd` is Ctrl off the Mac. -pub fn reserved_shortcut(sc: &str) -> bool { - let Some(n) = normalize_shortcut(sc) else { return false }; - let reserved: &[&str] = if cfg!(target_os = "macos") { - &["Cmd+Tab", "Cmd+Shift+Tab", "Cmd+Alt+Escape", "Cmd+`"] - } else if cfg!(target_os = "windows") { - &["Alt+Tab", "Alt+Shift+Tab", "Alt+F4", "Cmd+Alt+Delete", "Cmd+Escape", "Cmd+Shift+Escape"] - } else { - // Linux and the BSDs: window switching and closing, and the virtual consoles. - &[ - "Alt+Tab", - "Alt+Shift+Tab", - "Alt+F4", - "Cmd+Alt+Delete", - "Cmd+Alt+F1", - "Cmd+Alt+F2", - "Cmd+Alt+F3", - "Cmd+Alt+F4", - "Cmd+Alt+F5", - "Cmd+Alt+F6", - "Cmd+Alt+F7", - "Cmd+Alt+F8", - "Cmd+Alt+F9", - "Cmd+Alt+F10", - "Cmd+Alt+F11", - "Cmd+Alt+F12", - ] - }; - reserved.iter().filter_map(|r| normalize_shortcut(r)).any(|r| r == n) -} - -/// What a bindable id is: a command (the engine's or the shell's), a tool, or a held tool. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum BindKind { - Command, - Tool, - Hold, -} - -/// Every bindable id: (id, label, menu path, default key, kind). The engine's commands, the -/// shell's ([`crate::shell_commands::SHELL_COMMANDS`]), the tools and the held temporary tools, -/// so Edit › Keyboard Shortcuts works the same with or without the app's UI. -pub fn bindable_items() -> impl Iterator, BindKind)> { - let engine = crate::command_specs().iter().map(|c| (c.id, c.label, c.menu, c.shortcut, BindKind::Command)); - let shell = crate::shell_commands::SHELL_COMMANDS.iter().map(|c| (c.0, c.1, c.2, c.3, BindKind::Command)); - let tools = crate::shell_commands::TOOLS.iter().map(|t| (t.0, t.1, &["Tools"][..], t.2, BindKind::Tool)); - let hold = TEMPORARY_TOOLS.iter().map(|t| (t.0, t.1, &["Tools", "Temporary"][..], Some(t.2), BindKind::Hold)); - engine.chain(shell).chain(tools).chain(hold) -} - -/// Every bindable id with its default. -fn bindable() -> impl Iterator)> { - bindable_items().map(|i| (i.0, i.3)) -} - -fn is_tool(id: &str) -> bool { - crate::shell_commands::tool_default(id).is_some() -} - -/// Shortcuts bound to more than one command: (shortcut, ids). `bindings` are (id, shortcut). -pub fn conflicts<'a>(bindings: impl IntoIterator) -> Vec<(String, Vec)> { - let mut by: BTreeMap> = BTreeMap::new(); - for (id, sc) in bindings { - if let Some(n) = normalize_shortcut(sc) { - by.entry(n).or_default().push(id.to_string()); - } - } - by.into_iter().filter(|(_, ids)| ids.len() > 1).collect() -} - -// ------------------------------------------------------------------ store - -/// The session's preferences plus a revision counter that moves on every change (frontends -/// persist when it moves). -#[derive(Clone, Debug, Default)] -pub struct PrefsStore { - values: Preferences, - rev: u64, -} - -impl PrefsStore { - pub fn get(&self) -> &Preferences { - &self.values - } - /// Change preferences; bumps the revision. - pub fn edit(&mut self, f: impl FnOnce(&mut Preferences) -> R) -> R { - self.rev += 1; - f(&mut self.values) - } - pub fn rev(&self) -> u64 { - self.rev - } -} - -/// The preferences file format written by [`Session::prefs_value`]. 2: Use Shift Key for Tool -/// Switch stored as chosen (before, a stored `false` was the old default; see `load_prefs_json`). -pub const PREFS_VERSION: u64 = 2; - -/// A saved preference [`Session::load_prefs_json`] couldn't read (a wrong type, an unknown -/// choice) and left at its default. -#[derive(Clone, Debug, PartialEq)] -pub struct InvalidPref { - /// JSON keys from the top of the preferences file (`["fileHandling", "recentFileCount"]`), - /// kept apart because keys such as command ids contain dots. - pub keys: Vec, - /// The value the file held there. - pub value: Value, -} - -impl InvalidPref { - /// The dotted path, as `prefs.get` and `prefs.set` take it. - pub fn path(&self) -> String { - self.keys.join(".") - } -} - -/// How deep [`read_lenient`] looks for the readable parts of an unreadable value. -const LENIENT_DEPTH: usize = 32; - -/// Read `v` as a `T`. When that fails, start from `T::default()` and lay the file's values over -/// it one at a time, keeping each one the whole still reads with and descending into objects -/// that don't, so one bad value resets only itself. The values left out are added to -/// `invalid`, their keys after `prefix`. -fn read_lenient(v: Value, prefix: &[&str], invalid: &mut Vec) -> T -where - T: Default + Serialize + for<'de> Deserialize<'de>, -{ - if let Ok(t) = T::deserialize(&v) { - return t; - } - let prefix: Vec = prefix.iter().map(|k| (*k).to_string()).collect(); - let mut acc = serde_json::to_value(T::default()).unwrap_or(Value::Null); - let fits = |root: &Value| T::deserialize(root).is_ok(); - match v { - Value::Object(file) if acc.is_object() && fits(&acc) => { - lay_over(&mut acc, &mut Vec::new(), file, &fits, &prefix, invalid); - T::deserialize(&acc).unwrap_or_default() - } - value => { - invalid.push(InvalidPref { keys: prefix, value }); - T::default() - } - } -} - -/// [`read_lenient`]'s walk: lay `file` over the object at `at` inside `root`, key by key, so that -/// `root` always reads (`fits`). -fn lay_over( - root: &mut Value, - at: &mut Vec, - file: Map, - fits: &dyn Fn(&Value) -> bool, - prefix: &[String], - invalid: &mut Vec, -) { - for (k, fv) in file { - let Some(obj) = object_at(root, at) else { return }; - let old = obj.insert(k.clone(), fv.clone()); - if fits(root) { - continue; - } - // Back to the default. An object keeps its parts that read, and so does a new map entry - // (a shortcut set, a workspace) when it reads from an empty object. - let Some(obj) = object_at(root, at) else { return }; - let mut descend = fv.is_object() && at.len() < LENIENT_DEPTH && matches!(old, None | Some(Value::Object(_))); - match old { - Some(o) => obj.insert(k.clone(), o), - None if descend => obj.insert(k.clone(), Value::Object(Map::new())), - None => obj.remove(&k), - }; - at.push(k); - if descend && !fits(root) { - descend = false; - if let Some((key, parent)) = at.split_last() - && let Some(obj) = object_at(root, parent) - { - obj.remove(key); - } - } - match fv { - Value::Object(m) if descend => lay_over(root, at, m, fits, prefix, invalid), - value => invalid.push(InvalidPref { keys: prefix.iter().chain(at.iter()).cloned().collect(), value }), - } - at.pop(); - } -} - -/// The JSON object at `path` inside `root`. -fn object_at<'a>(root: &'a mut Value, path: &[String]) -> Option<&'a mut Map> { - path.iter().try_fold(root, |cur, k| cur.get_mut(k.as_str()))?.as_object_mut() -} - impl Session { /// The current preferences. pub fn prefs(&self) -> &Preferences { @@ -2068,699 +1483,6 @@ impl Session { } } -// ------------------------------------------------------------------ commands - -fn always(_: &Session) -> std::result::Result<(), String> { - Ok(()) -} - -fn bad(cmd: &str, msg: impl Into) -> EngineError { - EngineError::BadParams { cmd: cmd.into(), msg: msg.into() } -} - -fn prefs_get(s: &mut Session, p: &Value) -> Result { - let path = p.get("path").and_then(Value::as_str).unwrap_or(""); - let v = s.prefs_view(); - get_path(&v, path).cloned().ok_or_else(|| bad("prefs.get", format!("unknown preference `{path}`"))) -} - -fn prefs_set(s: &mut Session, p: &Value) -> Result { - let cmd = "prefs.set"; - let mut changes: Vec<(String, Value)> = Vec::new(); - if let Some(path) = p.get("path").and_then(Value::as_str) { - changes.push((path.to_string(), p.get("value").cloned().ok_or_else(|| bad(cmd, "missing `value`"))?)); - } - if let Some(m) = p.get("values").and_then(Value::as_object) { - changes.extend(m.iter().map(|(k, v)| (k.clone(), v.clone()))); - } - if changes.is_empty() { - return Err(bad(cmd, "give `path` and `value`, or `values: {path: value, …}`")); - } - // All or nothing: validate against a scratch copy first. - let (saved_prefs, saved_color) = (s.prefs().clone(), s.color.settings.clone()); - let mut color_changed = false; - for (path, v) in &changes { - match s.set_pref(path, v.clone(), false) { - Ok(touched) => color_changed |= touched, - Err(e) => { - s.prefs.edit(|p| *p = saved_prefs); - s.color.settings = saved_color; - return Err(bad(cmd, e)); - } - } - } - if color_changed && let Err(e) = crate::color_cmds::validate_settings(&s.color.settings) { - s.prefs.edit(|p| *p = saved_prefs); - s.color.settings = saved_color; - return Err(bad(cmd, e)); - } - // `colorSettings.blendTextGamma` lives in the compositor too, as `edit.colorSettings` sets it. - photocraft_compose::psblend::set_text_gamma(s.color.settings.blend_text_gamma); - s.apply_prefs(); - let view = s.prefs_view(); - let out: Map = changes.iter().map(|(k, _)| (k.clone(), get_path(&view, k).cloned().unwrap_or(Value::Null))).collect(); - Ok(Value::Object(out)) -} - -fn prefs_reset(s: &mut Session, p: &Value) -> Result { - let path = p.get("path").or_else(|| p.get("section")).and_then(Value::as_str); - match path { - Some("colorSettings") => s.color.settings = Default::default(), - // One colour setting: `Preferences` has no `colorSettings`, so take the default - // from `ColorSettings` and route it like `prefs.set` does. - Some(path) if path.starts_with("colorSettings.") => { - let defaults = serde_json::to_value(crate::color_cmds::ColorSettings::default()).map_err(|e| bad("prefs.reset", e.to_string()))?; - let key = path.strip_prefix("colorSettings.").unwrap_or(path); - let def = get_path(&defaults, key).cloned().ok_or_else(|| bad("prefs.reset", format!("unknown preference `{path}`")))?; - s.set_pref(path, def, true).map_err(|e| bad("prefs.reset", e))?; - } - None => { - s.color.settings = Default::default(); - s.edit_prefs(|p| p.reset(None)).map_err(|e| bad("prefs.reset", e))?; - } - Some(path) => { - let mut next = s.prefs().clone(); - next.reset(Some(path)).map_err(|e| bad("prefs.reset", e))?; - s.edit_prefs(|p| *p = next); - } - } - s.prefs.edit(|_| ()); - photocraft_compose::psblend::set_text_gamma(s.color.settings.blend_text_gamma); - s.apply_prefs(); - if path.is_some_and(|path| keyed(path).is_some()) { - // The removed override is absent, so reading its old path would report an error. - Ok(Value::Null) - } else { - prefs_get(s, &json!({"path": path.unwrap_or("")})) - } -} - -/// `edit.preferences.
`: the section's values (the GUI opens the dialog on it instead). -fn preferences_section(s: &mut Session, p: &Value) -> Result { - let section = p.get("__section").and_then(Value::as_str).unwrap_or("general").to_string(); - let title = SECTIONS.iter().find(|(id, _)| *id == section).map_or("General", |(_, t)| *t); - let values = s.prefs().get(§ion).unwrap_or(Value::Null); - Ok(json!({"section": section, "title": title, "values": values})) -} - -/// Edit › Keyboard Shortcuts (engine part): list, change and reset application shortcuts. -fn keyboard_shortcuts(s: &mut Session, p: &Value) -> Result { - let cmd = "edit.keyboardShortcuts"; - // Every change lands at once, after all of it validated: a bad key leaves the set as it was. - let mut next = s.prefs().clone(); - // A set loads first, so the call's other changes apply on top of it. - let mut changed = crate::shortcut_sets::load(&mut next, p).map_err(|e| bad(cmd, e))?; - if let Some(r) = p.get("reset") { - match r { - Value::Bool(true) => { - next.shortcuts.clear(); - next.alternate_shortcuts.clear(); - changed = true; - } - Value::Array(ids) => { - for id in ids.iter().filter_map(Value::as_str) { - next.shortcuts.remove(id); - next.alternate_shortcuts.remove(id); - } - changed = true; - } - _ => {} - } - } - // A Photoshop `.kys` set (`importKys`, its XML text) becomes `set` and `alternates` entries, - // matched by label (`crate::kys`); a key equal to the command's default restores the - // default, and keys given in `set` / `alternates` as well win over the file's. - let imported; - let mut import = None; - let p = match p.get("importKys") { - Some(v) => { - // The file's text, or {"path": …} to read it. - let read; - let xml = match v { - Value::String(s) => s.as_str(), - Value::Object(o) => { - let path = - o.get("path").and_then(Value::as_str).filter(|s| !s.trim().is_empty()).ok_or_else(|| bad(cmd, "`importKys.path` is a .kys file"))?; - read = read_text_file(path, crate::kys::MAX_BYTES).map_err(|e| bad(cmd, format!("{path}: {e}")))?; - read.as_str() - } - _ => return Err(bad(cmd, "`importKys` is the text of a .kys file, or {\"path\": …}")), - }; - let set = crate::kys::parse(xml).map_err(|e| bad(cmd, e))?; - let plan = crate::kys::plan(crate::kys::command_candidates(), &set); - let mut merged = serde_json::Map::new(); - // A key the system reserves is left out (reported as `reserved`), not a failed import. - let mut skipped: Vec = Vec::new(); - for (id, sc) in plan.set.iter().filter(|(id, sc)| { - let bad = reserved_shortcut(sc); - if bad { - skipped.push(format!("{id}: {sc}")); - } - !bad - }) { - let default = crate::command_specs().iter().find(|c| c.id == id).and_then(|c| c.shortcut).and_then(normalize_shortcut); - merged.insert(id.clone(), if default.as_deref() == Some(sc.as_str()) { Value::Null } else { json!(sc) }); - } - // Tool keys: a tool's own letter restores it (and its Shift cycling). - let tools = crate::shell_commands::TOOLS.iter().map(|t| (t.0, t.1)); - let (tool_keys, unknown_tools) = crate::kys::plan_tools(tools, &set); - for (id, key) in &tool_keys { - let own = crate::shell_commands::tool_default(id).flatten().is_some_and(|d| d.eq_ignore_ascii_case(key)); - merged.insert(id.clone(), if own { Value::Null } else { json!(key) }); - } - merged.extend(p.get("set").and_then(Value::as_object).cloned().unwrap_or_default()); - let mut alternates = serde_json::Map::new(); - for (id, keys) in &plan.alternate_keys { - let keys: &Vec = &keys.iter().filter(|k| !reserved_shortcut(k)).cloned().collect(); - let main = plan.set.get(id).map(String::as_str); - let default = Preferences::default().alternates(id, main); - alternates.insert(id.clone(), if *keys == default { Value::Null } else { json!(keys) }); - } - alternates.extend(p.get("alternates").and_then(Value::as_object).cloned().unwrap_or_default()); - import = Some(json!({ - "name": set.name, - "imported": plan.set.len(), - "set": plan.set, - "unknown": plan.unknown, - "unreadable": plan.unreadable, - "alternates": plan.alternates, - "alternateKeys": plan.alternate_keys, - "toolKeys": set.tool_keys, - "tools": tool_keys, - "unknownTools": unknown_tools, - "reserved": skipped, - "windows": set.windows, - })); - let mut with_import = p.clone(); - with_import["set"] = Value::Object(merged); - with_import["alternates"] = Value::Object(alternates); - imported = with_import; - &imported - } - None => p, - }; - let empty = serde_json::Map::new(); - let set = match p.get("set") { - Some(Value::Object(m)) => m, - _ => &empty, - }; - let alts = match p.get("alternates") { - None | Some(Value::Null) => &empty, - Some(v) => v.as_object().ok_or_else(|| bad(cmd, "`alternates` maps command ids to lists of shortcuts"))?, - }; - if !set.is_empty() || !alts.is_empty() { - let allow_unknown = p.get("allowUnknown").and_then(Value::as_bool).unwrap_or(false); - changed = true; - // Reserved system keys can't be bound, by hand or from a file. - let reserved = |v: &Value| -> Option { - let keys = match v { - Value::String(s) => vec![s.clone()], - other => alternate_keys(other).unwrap_or_default(), - }; - keys.into_iter().find(|k| reserved_shortcut(k)) - }; - if let Some((id, k)) = set.iter().chain(alts.iter()).find_map(|(id, v)| reserved(v).map(|k| (id, k))) { - return Err(bad(cmd, format!("`{k}` (for `{id}`) is reserved by the system and can't be assigned"))); - } - for (id, v) in set { - if !bindable().any(|(b, _)| b == id) && !allow_unknown { - return Err(bad(cmd, format!("unknown command `{id}`"))); - } - next.set(&format!("shortcuts.{id}"), v.clone()).map_err(|e| bad(cmd, e))?; - } - for (id, v) in alts { - if !bindable().any(|(b, _)| b == id) && default_alternates(id).next().is_none() && !allow_unknown { - return Err(bad(cmd, format!("unknown command `{id}`"))); - } - next.set(&format!("alternateShortcuts.{id}"), v.clone()).map_err(|e| bad(cmd, e))?; - } - // Like Photoshop, a shortcut moved to a new command is taken away from the old one, - // whether the old one held it as its main key or as an alternate (#3665). - if p.get("removeConflicts").and_then(Value::as_bool).unwrap_or(true) { - let assigned: Vec<(&str, String)> = set - .iter() - .filter_map(|(id, v)| Some((id.as_str(), v.as_str().and_then(normalize_shortcut)?))) - .chain(alts.iter().flat_map(|(id, v)| alternate_keys(v).unwrap_or_default().into_iter().map(move |k| (id.as_str(), k)))) - .collect(); - for (id, sc) in assigned { - for (c, def) in bindable() { - // Tools may share a key: they cycle with Shift, as Photoshop's groups do. - if is_tool(id) && is_tool(c) { - continue; - } - // Never strip a command that this same call is assigning: - // two entries for one key are a clash inside the call, which - // the returned conflicts list reports (#719). Stripping - // each other here unbound both silently. - if c == id || set.contains_key(c) || alts.contains_key(c) { - continue; - } - let main = next.shortcut(c, def).map(str::to_string); - if main.as_deref().and_then(normalize_shortcut).as_deref() == Some(sc.as_str()) { - next.shortcuts.insert(c.to_string(), String::new()); - } - let held = next.alternates(c, main.as_deref()); - if held.contains(&sc) { - next.alternate_shortcuts.insert(c.to_string(), held.into_iter().filter(|k| *k != sc).collect()); - } - } - } - } - } - // Then the sets are saved, deleted or switched, from the bindings as they now stand. - changed |= crate::shortcut_sets::store(&mut next, p).map_err(|e| bad(cmd, e))?; - // The reply and the exports read the bindings as they will be; they are committed only once - // the exports are written, so a bad export target changes nothing. - let prefs = &next; - let filter = p.get("filter").and_then(Value::as_str).map(str::to_ascii_lowercase); - let list: Vec = bindable_items() - .filter(|c| filter.as_ref().is_none_or(|f| c.0.to_ascii_lowercase().contains(f) || c.1.to_ascii_lowercase().contains(f))) - .filter(|c| { - p.get("list").and_then(Value::as_bool).unwrap_or(false) - || filter.is_some() - || prefs.shortcuts.contains_key(c.0) - || prefs.alternate_shortcuts.contains_key(c.0) - }) - .map(|(id, label, menu, def, kind)| { - let main = prefs.shortcut(id, def); - let defaults: Vec<&str> = default_alternates(id).collect(); - let mut v = json!({"id": id, "label": label, "menu": menu, "default": def, "shortcut": main, "alternates": prefs.alternates(id, main)}); - if !defaults.is_empty() { - v["defaultAlternates"] = json!(defaults); - } - match kind { - BindKind::Hold => v["hold"] = json!(true), - BindKind::Tool => v["tool"] = json!(true), - BindKind::Command => {} - } - v - }) - .collect(); - let mut bindings: Vec<(&str, String)> = Vec::new(); - for (id, def) in bindable() { - let main = prefs.shortcut(id, def); - bindings.extend(main.map(|m| (id, m.to_string()))); - bindings.extend(prefs.alternates(id, main).into_iter().map(|k| (id, k))); - } - // Tools sharing a key are a cycling group, not a conflict. - let conflicts: Vec = conflicts(bindings.iter().map(|(id, k)| (*id, k.as_str()))) - .into_iter() - .filter(|(_, ids)| !ids.iter().all(|id| is_tool(id))) - .map(|(sc, ids)| json!({"shortcut": sc, "commands": ids})) - .collect(); - let mut out = json!({"overrides": prefs.shortcuts, "alternateOverrides": prefs.alternate_shortcuts, "commands": list, "conflicts": conflicts}); - if let (Some(o), Value::Object(sets)) = (out.as_object_mut(), crate::shortcut_sets::describe(prefs)) { - o.extend(sets); - } - // The bindings as a `.kys` file, or Photoshop's Summarize page: every bindable item (the - // engine's commands, the shell's commands and the tools). - let set_name = if prefs.shortcut_set.is_empty() { crate::shortcut_sets::DEFAULTS_NAME } else { prefs.shortcut_set.as_str() }; - // Both targets are resolved and their texts made before anything is written, and a path that - // can't be written is refused before either file is: a bad export changes nothing. - let kys_target = file_target(cmd, p.get("exportKys"))?; - let html_target = file_target(cmd, p.get("summarize"))?; - let mut files: Vec<(&str, String, String)> = Vec::new(); - if let Some(target) = kys_target { - let entries: Vec = - crate::shortcut_sets::bound(prefs).into_iter().map(|b| crate::kys::Entry { id: b.id, label: b.label, tool: b.tool, keys: b.keys }).collect(); - let text = crate::kys::write(set_name, &entries); - match target { - Some(path) => files.push(("kysPath", path, text)), - None => out["kys"] = json!(text), - } - } - if let Some(target) = html_target { - let v = p.get("summarize").cloned().unwrap_or(Value::Null); - let mac = v.get("mac").and_then(Value::as_bool).unwrap_or(cfg!(target_os = "macos")); - let mut sections: Vec = Vec::new(); - for crate::shortcut_sets::Bound { label, menu, keys, .. } in crate::shortcut_sets::bound(prefs) { - match sections.iter_mut().find(|(m, _)| *m == menu) { - Some((_, rows)) => rows.push((label, keys)), - None => sections.push((menu, vec![(label, keys)])), - } - } - let html = crate::shortcut_sets::summarize(set_name, §ions, mac); - match target { - Some(path) => files.push(("htmlPath", path, html)), - None => out["html"] = json!(html), - } - } - for (_, path, _) in &files { - writable(path).map_err(|e| bad(cmd, format!("{path}: {e}")))?; - } - let list: Vec<(&str, &str)> = files.iter().map(|(_, path, text)| (path.as_str(), text.as_str())).collect(); - write_files_atomically(&list, &rename_path).map_err(|e| bad(cmd, e))?; - for (key, path, _) in &files { - out[*key] = json!(path); - } - if changed { - s.edit_prefs(|p| *p = next); - } - if let Some(import) = import { - out["import"] = import; - } - Ok(out) -} - -/// An output parameter (`exportKys`, `summarize`): absent or false → `None`; true (or an object -/// without `path`) → `Some(None)`, the text comes back in the reply; `{"path": …}` → -/// `Some(Some(path))`, written there. -fn file_target(cmd: &str, v: Option<&Value>) -> Result>> { - match v { - None | Some(Value::Null) | Some(Value::Bool(false)) => Ok(None), - Some(Value::Bool(true)) => Ok(Some(None)), - Some(Value::Object(o)) => match o.get("path") { - None | Some(Value::Null) => Ok(Some(None)), - Some(Value::String(s)) if !s.trim().is_empty() => Ok(Some(Some(s.clone()))), - Some(_) => Err(bad(cmd, "`path` must be a non-empty string")), - }, - Some(_) => Err(bad(cmd, "expected true or {\"path\": …}")), - } -} - -#[cfg(not(target_arch = "wasm32"))] -fn read_text_file(path: &str, max: usize) -> std::result::Result { - let meta = std::fs::metadata(path).map_err(|e| e.to_string())?; - if !meta.is_file() || meta.len() > max as u64 { - return Err(format!("not a file of at most {} KiB", max / 1024)); - } - std::fs::read_to_string(path).map_err(|e| e.to_string()) -} - -#[cfg(target_arch = "wasm32")] -fn read_text_file(_: &str, _: usize) -> std::result::Result { - Err("paths can't be read on the web; pass the file's text instead".into()) -} - -/// Whether `path` can be written: not a folder, in a folder that exists. -#[cfg(not(target_arch = "wasm32"))] -fn writable(path: &str) -> std::result::Result<(), String> { - let p = std::path::Path::new(path); - if p.is_dir() { - return Err("is a folder".into()); - } - if std::fs::metadata(p).is_ok_and(|m| m.permissions().readonly()) { - return Err("is read-only".into()); - } - match p.parent().filter(|d| !d.as_os_str().is_empty()) { - Some(d) if !d.is_dir() => Err("its folder doesn't exist".into()), - _ => Ok(()), - } -} - -#[cfg(target_arch = "wasm32")] -fn writable(_: &str) -> std::result::Result<(), String> { - Err("paths can't be written on the web; omit `path` to get the text back".into()) -} - -#[cfg(not(target_arch = "wasm32"))] -fn rename_path(from: &std::path::Path, to: &std::path::Path) -> std::io::Result<()> { - std::fs::rename(from, to) -} - -#[cfg(target_arch = "wasm32")] -fn rename_path(_: &std::path::Path, _: &std::path::Path) -> std::io::Result<()> { - Err(std::io::Error::other("paths can't be written on the web")) -} - -/// Where `path` points, for telling whether two targets are one file: its folder resolved, its -/// name compared without case where the file system ignores it. -#[cfg(not(target_arch = "wasm32"))] -fn path_key(path: &str) -> String { - let p = std::path::Path::new(path); - let dir = p.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(std::path::Path::new(".")); - let dir = dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf()); - let key = dir.join(p.file_name().unwrap_or_default()).to_string_lossy().into_owned(); - if cfg!(any(target_os = "windows", target_os = "macos")) { key.to_lowercase() } else { key } -} - -/// A new, empty file beside `path` with a name nothing else uses (`create_new`), for staging -/// (`kind` "tmp") or a backup ("bak"). -#[cfg(not(target_arch = "wasm32"))] -fn sibling(path: &str, kind: &str) -> std::io::Result<(std::path::PathBuf, std::fs::File)> { - for n in 0..1000u32 { - let p = std::path::PathBuf::from(format!("{path}.{}-{n}.photocraft-{kind}", std::process::id())); - match std::fs::OpenOptions::new().write(true).create_new(true).open(&p) { - Ok(f) => return Ok((p, f)), - Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue, - Err(e) => return Err(e), - } - } - Err(std::io::Error::other("no free name beside it")) -} - -/// Write `files` ((path, text)) all or nothing. Each text is staged in a new file beside its -/// target; once every one is written, each existing target is moved aside to a backup and the -/// staged file moved in. Any failure moves the backups back and removes what was staged, so the -/// user's files end as they began; on success the backups go. Two targets naming one file are -/// refused. `rename` is `std::fs::rename` (a test fails it on purpose). -#[cfg(not(target_arch = "wasm32"))] -pub(crate) fn write_files_atomically( - files: &[(&str, &str)], - rename: &dyn Fn(&std::path::Path, &std::path::Path) -> std::io::Result<()>, -) -> std::result::Result<(), String> { - use std::io::Write; - use std::path::{Path, PathBuf}; - for (i, (a, _)) in files.iter().enumerate() { - if files.iter().skip(i + 1).any(|(b, _)| path_key(a) == path_key(b)) { - return Err(format!("{a}: two exports to the same file")); - } - } - let mut staged: Vec = Vec::new(); - let drop_all = |paths: &[PathBuf]| { - for p in paths { - let _ = std::fs::remove_file(p); - } - }; - for (path, text) in files { - let (tmp, mut f) = match sibling(path, "tmp") { - Ok(v) => v, - Err(e) => { - drop_all(&staged); - return Err(format!("{path}: {e}")); - } - }; - staged.push(tmp); - if let Err(e) = f.write_all(text.as_bytes()).and_then(|()| f.sync_all()) { - drop_all(&staged); - return Err(format!("{path}: {e}")); - } - } - // (target, its backup) of each file moved in so far. - let mut moved: Vec<(&Path, Option)> = Vec::new(); - // Put each backup back over its target (a target that had none is removed). What couldn't be - // put back is named, so the user can find their previous file. - let undo = |moved: &[(&Path, Option)]| -> String { - let mut stranded = Vec::new(); - for (target, backup) in moved.iter().rev() { - match backup { - Some(b) => { - if rename(b, target).is_err() { - stranded.push(format!("the previous {} is at {}", target.display(), b.display())); - } - } - None => { - let _ = std::fs::remove_file(target); - } - } - } - if stranded.is_empty() { String::new() } else { format!(" ({})", stranded.join("; ")) } - }; - for ((path, _), tmp) in files.iter().zip(&staged) { - let target = Path::new(*path); - let backup = if target.exists() { - let moved_aside = sibling(path, "bak").and_then(|(b, f)| { - drop(f); - match rename(target, &b) { - Ok(()) => Ok(b), - Err(e) => { - // The placeholder the backup name reserved goes too. - let _ = std::fs::remove_file(&b); - Err(e) - } - } - }); - match moved_aside { - Ok(b) => Some(b), - Err(e) => { - let stranded = undo(&moved); - drop_all(&staged); - return Err(format!("{path}: {e}{stranded}")); - } - } - } else { - None - }; - if let Err(e) = rename(tmp, target) { - let mut stranded = undo(&moved); - if let Some(b) = &backup - && rename(b, target).is_err() - { - stranded = format!("{stranded} (the previous {path} is at {})", b.display()); - } - drop_all(&staged); - return Err(format!("{path}: {e}{stranded}")); - } - moved.push((target, backup)); - } - for (_, backup) in moved { - if let Some(b) = backup { - let _ = std::fs::remove_file(b); - } - } - Ok(()) -} - -#[cfg(target_arch = "wasm32")] -pub(crate) fn write_files_atomically( - files: &[(&str, &str)], - _: &dyn Fn(&std::path::Path, &std::path::Path) -> std::io::Result<()>, -) -> std::result::Result<(), String> { - if files.is_empty() { Ok(()) } else { Err("paths can't be written on the web; omit `path` to get the text back".into()) } -} - -/// Edit › Menus: hide/show items and give them colours. -fn menus(s: &mut Session, p: &Value) -> Result { - let ids = |k: &str| -> Vec { - p.get(k).and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect()).unwrap_or_default() - }; - const COLORS: [&str; 8] = ["none", "red", "orange", "yellow", "green", "blue", "violet", "gray"]; - if let Some(m) = p.get("color").and_then(Value::as_object) { - for v in m.values() { - if let Some(c) = v.as_str().filter(|c| !COLORS.contains(c)) { - return Err(bad("edit.menus", format!("unknown colour `{c}` ({})", COLORS.join("|")))); - } - } - } - let (hide, show) = (ids("hide"), ids("show")); - if let Some(id) = hide.iter().find(|id| !MenuCustomization::hideable(id)) { - return Err(bad("edit.menus", format!("`{id}` can't be hidden"))); - } - s.edit_prefs(|pr| { - if p.get("reset").and_then(Value::as_bool) == Some(true) { - pr.menus = MenuCustomization::default(); - } - for id in hide { - if !pr.menus.hidden.contains(&id) { - pr.menus.hidden.push(id); - } - } - pr.menus.hidden.retain(|h| !show.contains(h)); - if let Some(m) = p.get("color").and_then(Value::as_object) { - for (id, v) in m { - match v.as_str() { - Some(c) if c != "none" => { - pr.menus.colors.insert(id.clone(), c.to_string()); - } - _ => { - pr.menus.colors.remove(id); - } - } - } - } - }); - Ok(serde_json::to_value(&s.prefs().menus).unwrap_or_default()) -} - -/// Edit › Toolbar: hide tools and reorder the toolbar. -fn toolbar(s: &mut Session, p: &Value) -> Result { - let ids = |k: &str| -> Option> { p.get(k).and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect()) }; - s.edit_prefs(|pr| { - if p.get("reset").and_then(Value::as_bool) == Some(true) { - pr.toolbar = ToolbarCustomization::default(); - } - if let Some(h) = ids("hidden") { - pr.toolbar.hidden = h; - } - if let Some(o) = ids("order") { - pr.toolbar.order = o; - } - }); - Ok(serde_json::to_value(&s.prefs().toolbar).unwrap_or_default()) -} - -macro_rules! spec { - ($id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $run:expr, $journal:expr) => { - CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: always, run: $run, journal: $journal } - }; -} - -macro_rules! section { - ($id:literal, $label:literal) => { - section!($id, $label, None) - }; - ($id:literal, $label:literal, $shortcut:expr) => { - CommandSpec { id: $id, label: $label, menu: &["Edit", "Preferences"], shortcut: $shortcut, params: r##"{}"##, enabled: always, run: |s, _| preferences_section(s, &json!({"__section": section_of($id)})), journal: false } - }; -} - -fn section_of(id: &str) -> &str { - id.rsplit('.').next().unwrap_or("general") -} - -/// Preference command specs. -pub fn specs() -> Vec { - vec![ - spec!( - "prefs.get", - "Get Preferences", - [], - None, - r##"{"path":"section.key"?=everything (e.g. "performance.historyStates", "colorSettings.workingRgb")}"##, - prefs_get, - false - ), - spec!( - "prefs.set", - "Set Preferences", - [], - None, - r##"{"path":"section.key","value":json} or {"values":{"section.key":json,…}} (validated; all or nothing)"##, - prefs_set, - false - ), - spec!("prefs.reset", "Reset Preferences", [], None, r##"{"path":"section|section.key"?=everything}"##, prefs_reset, false), - // Photoshop: ⌘K opens Preferences › General (⌘, is Layer › Hide Layers). - section!("edit.preferences.general", "General…", Some("Cmd+K")), - section!("edit.preferences.interface", "Interface…"), - section!("edit.preferences.workspace", "Workspace…"), - section!("edit.preferences.tools", "Tools…"), - section!("edit.preferences.historyLog", "History Log…"), - section!("edit.preferences.fileHandling", "File Handling…"), - section!("edit.preferences.export", "Export…"), - section!("edit.preferences.performance", "Performance…"), - section!("edit.preferences.scratchDisks", "Scratch Disks…"), - section!("edit.preferences.cursors", "Cursors…"), - section!("edit.preferences.transparencyAndGamut", "Transparency & Gamut…"), - section!("edit.preferences.unitsAndRulers", "Units & Rulers…"), - section!("edit.preferences.guidesGridAndSlices", "Guides, Grid & Slices…"), - section!("edit.preferences.plugIns", "Plug-ins…"), - section!("edit.preferences.type", "Type…"), - section!("edit.preferences.enhancedControls", "Enhanced Controls…"), - section!("edit.preferences.rawDefaults", "Camera Raw…"), - section!("edit.preferences.integrations", "Integrations…"), - spec!( - "edit.keyboardShortcuts", - "Keyboard Shortcuts…", - ["Edit"], - Some("Cmd+Alt+Shift+K"), - r##"{"set":{"|tools.temporary.hand|zoomIn|zoomOut":"Cmd+Shift+X"|""(remove)|null(default)}?,"alternates":{"":["F3",…]|[](none)|null(default)}?,"reset":true|["",…]?,"removeConflicts":bool=true,"filter":str?,"list":bool=false,"importKys":"<.kys XML>"|{"path":".kys"}?,"useSet":""|""(defaults)?,"saveSet":""?,"deleteSet":""?,"sets":{"":{"shortcuts":{…},"alternateShortcuts":{…}}}?,"activeSet":""|""?,"exportKys":true|{"path":".kys"}?,"summarize":true|{"mac":bool,"path":".html"}?} (with a path the file is written and the reply has kysPath/htmlPath instead of kys/html)"##, - keyboard_shortcuts, - true - ), - spec!( - "edit.menus", - "Menus…", - ["Edit"], - Some("Cmd+Alt+Shift+M"), - r##"{"hide":["",…]?,"show":["",…]?,"color":{"":"red|orange|yellow|green|blue|violet|gray|none"}?,"reset":bool=false}"##, - menus, - true - ), - spec!("edit.toolbar", "Toolbar…", ["Edit"], None, r##"{"hidden":["",…]?,"order":["",…]?,"reset":bool=false}"##, toolbar, true), - ] -} - #[cfg(test)] #[path = "prefs/tests.rs"] mod tests; diff --git a/crates/engine/src/prefs/cmds.rs b/crates/engine/src/prefs/cmds.rs new file mode 100644 index 0000000000..b8f92356da --- /dev/null +++ b/crates/engine/src/prefs/cmds.rs @@ -0,0 +1,197 @@ +use super::customize::{keyboard_shortcuts, menus}; +use super::validate::{SECTIONS, get_path, keyed}; +use super::*; + +// ------------------------------------------------------------------ commands + +fn always(_: &Session) -> std::result::Result<(), String> { + Ok(()) +} + +pub(super) fn bad(cmd: &str, msg: impl Into) -> EngineError { + EngineError::BadParams { cmd: cmd.into(), msg: msg.into() } +} + +fn prefs_get(s: &mut Session, p: &Value) -> Result { + let path = p.get("path").and_then(Value::as_str).unwrap_or(""); + let v = s.prefs_view(); + get_path(&v, path).cloned().ok_or_else(|| bad("prefs.get", format!("unknown preference `{path}`"))) +} + +fn prefs_set(s: &mut Session, p: &Value) -> Result { + let cmd = "prefs.set"; + let mut changes: Vec<(String, Value)> = Vec::new(); + if let Some(path) = p.get("path").and_then(Value::as_str) { + changes.push((path.to_string(), p.get("value").cloned().ok_or_else(|| bad(cmd, "missing `value`"))?)); + } + if let Some(m) = p.get("values").and_then(Value::as_object) { + changes.extend(m.iter().map(|(k, v)| (k.clone(), v.clone()))); + } + if changes.is_empty() { + return Err(bad(cmd, "give `path` and `value`, or `values: {path: value, …}`")); + } + // All or nothing: validate against a scratch copy first. + let (saved_prefs, saved_color) = (s.prefs().clone(), s.color.settings.clone()); + let mut color_changed = false; + for (path, v) in &changes { + match s.set_pref(path, v.clone(), false) { + Ok(touched) => color_changed |= touched, + Err(e) => { + s.prefs.edit(|p| *p = saved_prefs); + s.color.settings = saved_color; + return Err(bad(cmd, e)); + } + } + } + if color_changed && let Err(e) = crate::color_cmds::validate_settings(&s.color.settings) { + s.prefs.edit(|p| *p = saved_prefs); + s.color.settings = saved_color; + return Err(bad(cmd, e)); + } + // `colorSettings.blendTextGamma` lives in the compositor too, as `edit.colorSettings` sets it. + photocraft_compose::psblend::set_text_gamma(s.color.settings.blend_text_gamma); + s.apply_prefs(); + let view = s.prefs_view(); + let out: Map = changes.iter().map(|(k, _)| (k.clone(), get_path(&view, k).cloned().unwrap_or(Value::Null))).collect(); + Ok(Value::Object(out)) +} + +fn prefs_reset(s: &mut Session, p: &Value) -> Result { + let path = p.get("path").or_else(|| p.get("section")).and_then(Value::as_str); + match path { + Some("colorSettings") => s.color.settings = Default::default(), + // One colour setting: `Preferences` has no `colorSettings`, so take the default + // from `ColorSettings` and route it like `prefs.set` does. + Some(path) if path.starts_with("colorSettings.") => { + let defaults = serde_json::to_value(crate::color_cmds::ColorSettings::default()).map_err(|e| bad("prefs.reset", e.to_string()))?; + let key = path.strip_prefix("colorSettings.").unwrap_or(path); + let def = get_path(&defaults, key).cloned().ok_or_else(|| bad("prefs.reset", format!("unknown preference `{path}`")))?; + s.set_pref(path, def, true).map_err(|e| bad("prefs.reset", e))?; + } + None => { + s.color.settings = Default::default(); + s.edit_prefs(|p| p.reset(None)).map_err(|e| bad("prefs.reset", e))?; + } + Some(path) => { + let mut next = s.prefs().clone(); + next.reset(Some(path)).map_err(|e| bad("prefs.reset", e))?; + s.edit_prefs(|p| *p = next); + } + } + s.prefs.edit(|_| ()); + photocraft_compose::psblend::set_text_gamma(s.color.settings.blend_text_gamma); + s.apply_prefs(); + if path.is_some_and(|path| keyed(path).is_some()) { + // The removed override is absent, so reading its old path would report an error. + Ok(Value::Null) + } else { + prefs_get(s, &json!({"path": path.unwrap_or("")})) + } +} + +/// `edit.preferences.
`: the section's values (the GUI opens the dialog on it instead). +fn preferences_section(s: &mut Session, p: &Value) -> Result { + let section = p.get("__section").and_then(Value::as_str).unwrap_or("general").to_string(); + let title = SECTIONS.iter().find(|(id, _)| *id == section).map_or("General", |(_, t)| *t); + let values = s.prefs().get(§ion).unwrap_or(Value::Null); + Ok(json!({"section": section, "title": title, "values": values})) +} + +/// Edit › Toolbar: hide tools and reorder the toolbar. +fn toolbar(s: &mut Session, p: &Value) -> Result { + let ids = |k: &str| -> Option> { p.get(k).and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect()) }; + s.edit_prefs(|pr| { + if p.get("reset").and_then(Value::as_bool) == Some(true) { + pr.toolbar = ToolbarCustomization::default(); + } + if let Some(h) = ids("hidden") { + pr.toolbar.hidden = h; + } + if let Some(o) = ids("order") { + pr.toolbar.order = o; + } + }); + Ok(serde_json::to_value(&s.prefs().toolbar).unwrap_or_default()) +} + +macro_rules! spec { + ($id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $run:expr, $journal:expr) => { + CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: always, run: $run, journal: $journal } + }; +} + +macro_rules! section { + ($id:literal, $label:literal) => { + section!($id, $label, None) + }; + ($id:literal, $label:literal, $shortcut:expr) => { + CommandSpec { id: $id, label: $label, menu: &["Edit", "Preferences"], shortcut: $shortcut, params: r##"{}"##, enabled: always, run: |s, _| preferences_section(s, &json!({"__section": section_of($id)})), journal: false } + }; +} + +fn section_of(id: &str) -> &str { + id.rsplit('.').next().unwrap_or("general") +} + +/// Preference command specs. +pub fn specs() -> Vec { + vec![ + spec!( + "prefs.get", + "Get Preferences", + [], + None, + r##"{"path":"section.key"?=everything (e.g. "performance.historyStates", "colorSettings.workingRgb")}"##, + prefs_get, + false + ), + spec!( + "prefs.set", + "Set Preferences", + [], + None, + r##"{"path":"section.key","value":json} or {"values":{"section.key":json,…}} (validated; all or nothing)"##, + prefs_set, + false + ), + spec!("prefs.reset", "Reset Preferences", [], None, r##"{"path":"section|section.key"?=everything}"##, prefs_reset, false), + // Photoshop: ⌘K opens Preferences › General (⌘, is Layer › Hide Layers). + section!("edit.preferences.general", "General…", Some("Cmd+K")), + section!("edit.preferences.interface", "Interface…"), + section!("edit.preferences.workspace", "Workspace…"), + section!("edit.preferences.tools", "Tools…"), + section!("edit.preferences.historyLog", "History Log…"), + section!("edit.preferences.fileHandling", "File Handling…"), + section!("edit.preferences.export", "Export…"), + section!("edit.preferences.performance", "Performance…"), + section!("edit.preferences.scratchDisks", "Scratch Disks…"), + section!("edit.preferences.cursors", "Cursors…"), + section!("edit.preferences.transparencyAndGamut", "Transparency & Gamut…"), + section!("edit.preferences.unitsAndRulers", "Units & Rulers…"), + section!("edit.preferences.guidesGridAndSlices", "Guides, Grid & Slices…"), + section!("edit.preferences.plugIns", "Plug-ins…"), + section!("edit.preferences.type", "Type…"), + section!("edit.preferences.enhancedControls", "Enhanced Controls…"), + section!("edit.preferences.rawDefaults", "Camera Raw…"), + section!("edit.preferences.integrations", "Integrations…"), + spec!( + "edit.keyboardShortcuts", + "Keyboard Shortcuts…", + ["Edit"], + Some("Cmd+Alt+Shift+K"), + r##"{"set":{"|tools.temporary.hand|zoomIn|zoomOut":"Cmd+Shift+X"|""(remove)|null(default)}?,"alternates":{"":["F3",…]|[](none)|null(default)}?,"reset":true|["",…]?,"removeConflicts":bool=true,"filter":str?,"list":bool=false,"importKys":"<.kys XML>"|{"path":".kys"}?,"useSet":""|""(defaults)?,"saveSet":""?,"deleteSet":""?,"sets":{"":{"shortcuts":{…},"alternateShortcuts":{…}}}?,"activeSet":""|""?,"exportKys":true|{"path":".kys"}?,"summarize":true|{"mac":bool,"path":".html"}?} (with a path the file is written and the reply has kysPath/htmlPath instead of kys/html)"##, + keyboard_shortcuts, + true + ), + spec!( + "edit.menus", + "Menus…", + ["Edit"], + Some("Cmd+Alt+Shift+M"), + r##"{"hide":["",…]?,"show":["",…]?,"color":{"":"red|orange|yellow|green|blue|violet|gray|none"}?,"reset":bool=false}"##, + menus, + true + ), + spec!("edit.toolbar", "Toolbar…", ["Edit"], None, r##"{"hidden":["",…]?,"order":["",…]?,"reset":bool=false}"##, toolbar, true), + ] +} diff --git a/crates/engine/src/prefs/customize.rs b/crates/engine/src/prefs/customize.rs new file mode 100644 index 0000000000..e6d76723c8 --- /dev/null +++ b/crates/engine/src/prefs/customize.rs @@ -0,0 +1,306 @@ +use super::cmds::bad; +use super::files::{file_target, read_text_file, rename_path, writable, write_files_atomically}; +use super::shortcuts::{BindKind, alternate_keys, bindable, bindable_items, conflicts, default_alternates, is_tool, normalize_shortcut, reserved_shortcut}; +use super::*; + +/// Edit › Keyboard Shortcuts (engine part): list, change and reset application shortcuts. +pub(super) fn keyboard_shortcuts(s: &mut Session, p: &Value) -> Result { + let cmd = "edit.keyboardShortcuts"; + // Every change lands at once, after all of it validated: a bad key leaves the set as it was. + let mut next = s.prefs().clone(); + // A set loads first, so the call's other changes apply on top of it. + let mut changed = crate::shortcut_sets::load(&mut next, p).map_err(|e| bad(cmd, e))?; + if let Some(r) = p.get("reset") { + match r { + Value::Bool(true) => { + next.shortcuts.clear(); + next.alternate_shortcuts.clear(); + changed = true; + } + Value::Array(ids) => { + for id in ids.iter().filter_map(Value::as_str) { + next.shortcuts.remove(id); + next.alternate_shortcuts.remove(id); + } + changed = true; + } + _ => {} + } + } + // A Photoshop `.kys` set (`importKys`, its XML text) becomes `set` and `alternates` entries, + // matched by label (`crate::kys`); a key equal to the command's default restores the + // default, and keys given in `set` / `alternates` as well win over the file's. + let imported; + let mut import = None; + let p = match p.get("importKys") { + Some(v) => { + // The file's text, or {"path": …} to read it. + let read; + let xml = match v { + Value::String(s) => s.as_str(), + Value::Object(o) => { + let path = + o.get("path").and_then(Value::as_str).filter(|s| !s.trim().is_empty()).ok_or_else(|| bad(cmd, "`importKys.path` is a .kys file"))?; + read = read_text_file(path, crate::kys::MAX_BYTES).map_err(|e| bad(cmd, format!("{path}: {e}")))?; + read.as_str() + } + _ => return Err(bad(cmd, "`importKys` is the text of a .kys file, or {\"path\": …}")), + }; + let set = crate::kys::parse(xml).map_err(|e| bad(cmd, e))?; + let plan = crate::kys::plan(crate::kys::command_candidates(), &set); + let mut merged = serde_json::Map::new(); + // A key the system reserves is left out (reported as `reserved`), not a failed import. + let mut skipped: Vec = Vec::new(); + for (id, sc) in plan.set.iter().filter(|(id, sc)| { + let bad = reserved_shortcut(sc); + if bad { + skipped.push(format!("{id}: {sc}")); + } + !bad + }) { + let default = crate::command_specs().iter().find(|c| c.id == id).and_then(|c| c.shortcut).and_then(normalize_shortcut); + merged.insert(id.clone(), if default.as_deref() == Some(sc.as_str()) { Value::Null } else { json!(sc) }); + } + // Tool keys: a tool's own letter restores it (and its Shift cycling). + let tools = crate::shell_commands::TOOLS.iter().map(|t| (t.0, t.1)); + let (tool_keys, unknown_tools) = crate::kys::plan_tools(tools, &set); + for (id, key) in &tool_keys { + let own = crate::shell_commands::tool_default(id).flatten().is_some_and(|d| d.eq_ignore_ascii_case(key)); + merged.insert(id.clone(), if own { Value::Null } else { json!(key) }); + } + merged.extend(p.get("set").and_then(Value::as_object).cloned().unwrap_or_default()); + let mut alternates = serde_json::Map::new(); + for (id, keys) in &plan.alternate_keys { + let keys: &Vec = &keys.iter().filter(|k| !reserved_shortcut(k)).cloned().collect(); + let main = plan.set.get(id).map(String::as_str); + let default = Preferences::default().alternates(id, main); + alternates.insert(id.clone(), if *keys == default { Value::Null } else { json!(keys) }); + } + alternates.extend(p.get("alternates").and_then(Value::as_object).cloned().unwrap_or_default()); + import = Some(json!({ + "name": set.name, + "imported": plan.set.len(), + "set": plan.set, + "unknown": plan.unknown, + "unreadable": plan.unreadable, + "alternates": plan.alternates, + "alternateKeys": plan.alternate_keys, + "toolKeys": set.tool_keys, + "tools": tool_keys, + "unknownTools": unknown_tools, + "reserved": skipped, + "windows": set.windows, + })); + let mut with_import = p.clone(); + with_import["set"] = Value::Object(merged); + with_import["alternates"] = Value::Object(alternates); + imported = with_import; + &imported + } + None => p, + }; + let empty = serde_json::Map::new(); + let set = match p.get("set") { + Some(Value::Object(m)) => m, + _ => &empty, + }; + let alts = match p.get("alternates") { + None | Some(Value::Null) => &empty, + Some(v) => v.as_object().ok_or_else(|| bad(cmd, "`alternates` maps command ids to lists of shortcuts"))?, + }; + if !set.is_empty() || !alts.is_empty() { + let allow_unknown = p.get("allowUnknown").and_then(Value::as_bool).unwrap_or(false); + changed = true; + // Reserved system keys can't be bound, by hand or from a file. + let reserved = |v: &Value| -> Option { + let keys = match v { + Value::String(s) => vec![s.clone()], + other => alternate_keys(other).unwrap_or_default(), + }; + keys.into_iter().find(|k| reserved_shortcut(k)) + }; + if let Some((id, k)) = set.iter().chain(alts.iter()).find_map(|(id, v)| reserved(v).map(|k| (id, k))) { + return Err(bad(cmd, format!("`{k}` (for `{id}`) is reserved by the system and can't be assigned"))); + } + for (id, v) in set { + if !bindable().any(|(b, _)| b == id) && !allow_unknown { + return Err(bad(cmd, format!("unknown command `{id}`"))); + } + next.set(&format!("shortcuts.{id}"), v.clone()).map_err(|e| bad(cmd, e))?; + } + for (id, v) in alts { + if !bindable().any(|(b, _)| b == id) && default_alternates(id).next().is_none() && !allow_unknown { + return Err(bad(cmd, format!("unknown command `{id}`"))); + } + next.set(&format!("alternateShortcuts.{id}"), v.clone()).map_err(|e| bad(cmd, e))?; + } + // Like Photoshop, a shortcut moved to a new command is taken away from the old one, + // whether the old one held it as its main key or as an alternate (#3665). + if p.get("removeConflicts").and_then(Value::as_bool).unwrap_or(true) { + let assigned: Vec<(&str, String)> = set + .iter() + .filter_map(|(id, v)| Some((id.as_str(), v.as_str().and_then(normalize_shortcut)?))) + .chain(alts.iter().flat_map(|(id, v)| alternate_keys(v).unwrap_or_default().into_iter().map(move |k| (id.as_str(), k)))) + .collect(); + for (id, sc) in assigned { + for (c, def) in bindable() { + // Tools may share a key: they cycle with Shift, as Photoshop's groups do. + if is_tool(id) && is_tool(c) { + continue; + } + // Never strip a command that this same call is assigning: + // two entries for one key are a clash inside the call, which + // the returned conflicts list reports (#719). Stripping + // each other here unbound both silently. + if c == id || set.contains_key(c) || alts.contains_key(c) { + continue; + } + let main = next.shortcut(c, def).map(str::to_string); + if main.as_deref().and_then(normalize_shortcut).as_deref() == Some(sc.as_str()) { + next.shortcuts.insert(c.to_string(), String::new()); + } + let held = next.alternates(c, main.as_deref()); + if held.contains(&sc) { + next.alternate_shortcuts.insert(c.to_string(), held.into_iter().filter(|k| *k != sc).collect()); + } + } + } + } + } + // Then the sets are saved, deleted or switched, from the bindings as they now stand. + changed |= crate::shortcut_sets::store(&mut next, p).map_err(|e| bad(cmd, e))?; + // The reply and the exports read the bindings as they will be; they are committed only once + // the exports are written, so a bad export target changes nothing. + let prefs = &next; + let filter = p.get("filter").and_then(Value::as_str).map(str::to_ascii_lowercase); + let list: Vec = bindable_items() + .filter(|c| filter.as_ref().is_none_or(|f| c.0.to_ascii_lowercase().contains(f) || c.1.to_ascii_lowercase().contains(f))) + .filter(|c| { + p.get("list").and_then(Value::as_bool).unwrap_or(false) + || filter.is_some() + || prefs.shortcuts.contains_key(c.0) + || prefs.alternate_shortcuts.contains_key(c.0) + }) + .map(|(id, label, menu, def, kind)| { + let main = prefs.shortcut(id, def); + let defaults: Vec<&str> = default_alternates(id).collect(); + let mut v = json!({"id": id, "label": label, "menu": menu, "default": def, "shortcut": main, "alternates": prefs.alternates(id, main)}); + if !defaults.is_empty() { + v["defaultAlternates"] = json!(defaults); + } + match kind { + BindKind::Hold => v["hold"] = json!(true), + BindKind::Tool => v["tool"] = json!(true), + BindKind::Command => {} + } + v + }) + .collect(); + let mut bindings: Vec<(&str, String)> = Vec::new(); + for (id, def) in bindable() { + let main = prefs.shortcut(id, def); + bindings.extend(main.map(|m| (id, m.to_string()))); + bindings.extend(prefs.alternates(id, main).into_iter().map(|k| (id, k))); + } + // Tools sharing a key are a cycling group, not a conflict. + let conflicts: Vec = conflicts(bindings.iter().map(|(id, k)| (*id, k.as_str()))) + .into_iter() + .filter(|(_, ids)| !ids.iter().all(|id| is_tool(id))) + .map(|(sc, ids)| json!({"shortcut": sc, "commands": ids})) + .collect(); + let mut out = json!({"overrides": prefs.shortcuts, "alternateOverrides": prefs.alternate_shortcuts, "commands": list, "conflicts": conflicts}); + if let (Some(o), Value::Object(sets)) = (out.as_object_mut(), crate::shortcut_sets::describe(prefs)) { + o.extend(sets); + } + // The bindings as a `.kys` file, or Photoshop's Summarize page: every bindable item (the + // engine's commands, the shell's commands and the tools). + let set_name = if prefs.shortcut_set.is_empty() { crate::shortcut_sets::DEFAULTS_NAME } else { prefs.shortcut_set.as_str() }; + // Both targets are resolved and their texts made before anything is written, and a path that + // can't be written is refused before either file is: a bad export changes nothing. + let kys_target = file_target(cmd, p.get("exportKys"))?; + let html_target = file_target(cmd, p.get("summarize"))?; + let mut files: Vec<(&str, String, String)> = Vec::new(); + if let Some(target) = kys_target { + let entries: Vec = + crate::shortcut_sets::bound(prefs).into_iter().map(|b| crate::kys::Entry { id: b.id, label: b.label, tool: b.tool, keys: b.keys }).collect(); + let text = crate::kys::write(set_name, &entries); + match target { + Some(path) => files.push(("kysPath", path, text)), + None => out["kys"] = json!(text), + } + } + if let Some(target) = html_target { + let v = p.get("summarize").cloned().unwrap_or(Value::Null); + let mac = v.get("mac").and_then(Value::as_bool).unwrap_or(cfg!(target_os = "macos")); + let mut sections: Vec = Vec::new(); + for crate::shortcut_sets::Bound { label, menu, keys, .. } in crate::shortcut_sets::bound(prefs) { + match sections.iter_mut().find(|(m, _)| *m == menu) { + Some((_, rows)) => rows.push((label, keys)), + None => sections.push((menu, vec![(label, keys)])), + } + } + let html = crate::shortcut_sets::summarize(set_name, §ions, mac); + match target { + Some(path) => files.push(("htmlPath", path, html)), + None => out["html"] = json!(html), + } + } + for (_, path, _) in &files { + writable(path).map_err(|e| bad(cmd, format!("{path}: {e}")))?; + } + let list: Vec<(&str, &str)> = files.iter().map(|(_, path, text)| (path.as_str(), text.as_str())).collect(); + write_files_atomically(&list, &rename_path).map_err(|e| bad(cmd, e))?; + for (key, path, _) in &files { + out[*key] = json!(path); + } + if changed { + s.edit_prefs(|p| *p = next); + } + if let Some(import) = import { + out["import"] = import; + } + Ok(out) +} + +/// Edit › Menus: hide/show items and give them colours. +pub(super) fn menus(s: &mut Session, p: &Value) -> Result { + let ids = |k: &str| -> Vec { + p.get(k).and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect()).unwrap_or_default() + }; + const COLORS: [&str; 8] = ["none", "red", "orange", "yellow", "green", "blue", "violet", "gray"]; + if let Some(m) = p.get("color").and_then(Value::as_object) { + for v in m.values() { + if let Some(c) = v.as_str().filter(|c| !COLORS.contains(c)) { + return Err(bad("edit.menus", format!("unknown colour `{c}` ({})", COLORS.join("|")))); + } + } + } + let (hide, show) = (ids("hide"), ids("show")); + if let Some(id) = hide.iter().find(|id| !MenuCustomization::hideable(id)) { + return Err(bad("edit.menus", format!("`{id}` can't be hidden"))); + } + s.edit_prefs(|pr| { + if p.get("reset").and_then(Value::as_bool) == Some(true) { + pr.menus = MenuCustomization::default(); + } + for id in hide { + if !pr.menus.hidden.contains(&id) { + pr.menus.hidden.push(id); + } + } + pr.menus.hidden.retain(|h| !show.contains(h)); + if let Some(m) = p.get("color").and_then(Value::as_object) { + for (id, v) in m { + match v.as_str() { + Some(c) if c != "none" => { + pr.menus.colors.insert(id.clone(), c.to_string()); + } + _ => { + pr.menus.colors.remove(id); + } + } + } + } + }); + Ok(serde_json::to_value(&s.prefs().menus).unwrap_or_default()) +} diff --git a/crates/engine/src/prefs/files.rs b/crates/engine/src/prefs/files.rs new file mode 100644 index 0000000000..d24205228a --- /dev/null +++ b/crates/engine/src/prefs/files.rs @@ -0,0 +1,199 @@ +use super::cmds::bad; +use super::*; + +/// An output parameter (`exportKys`, `summarize`): absent or false → `None`; true (or an object +/// without `path`) → `Some(None)`, the text comes back in the reply; `{"path": …}` → +/// `Some(Some(path))`, written there. +pub(super) fn file_target(cmd: &str, v: Option<&Value>) -> Result>> { + match v { + None | Some(Value::Null) | Some(Value::Bool(false)) => Ok(None), + Some(Value::Bool(true)) => Ok(Some(None)), + Some(Value::Object(o)) => match o.get("path") { + None | Some(Value::Null) => Ok(Some(None)), + Some(Value::String(s)) if !s.trim().is_empty() => Ok(Some(Some(s.clone()))), + Some(_) => Err(bad(cmd, "`path` must be a non-empty string")), + }, + Some(_) => Err(bad(cmd, "expected true or {\"path\": …}")), + } +} + +#[cfg(not(target_arch = "wasm32"))] +pub(super) fn read_text_file(path: &str, max: usize) -> std::result::Result { + let meta = std::fs::metadata(path).map_err(|e| e.to_string())?; + if !meta.is_file() || meta.len() > max as u64 { + return Err(format!("not a file of at most {} KiB", max / 1024)); + } + std::fs::read_to_string(path).map_err(|e| e.to_string()) +} + +#[cfg(target_arch = "wasm32")] +pub(super) fn read_text_file(_: &str, _: usize) -> std::result::Result { + Err("paths can't be read on the web; pass the file's text instead".into()) +} + +/// Whether `path` can be written: not a folder, in a folder that exists. +#[cfg(not(target_arch = "wasm32"))] +pub(super) fn writable(path: &str) -> std::result::Result<(), String> { + let p = std::path::Path::new(path); + if p.is_dir() { + return Err("is a folder".into()); + } + if std::fs::metadata(p).is_ok_and(|m| m.permissions().readonly()) { + return Err("is read-only".into()); + } + match p.parent().filter(|d| !d.as_os_str().is_empty()) { + Some(d) if !d.is_dir() => Err("its folder doesn't exist".into()), + _ => Ok(()), + } +} + +#[cfg(target_arch = "wasm32")] +pub(super) fn writable(_: &str) -> std::result::Result<(), String> { + Err("paths can't be written on the web; omit `path` to get the text back".into()) +} + +#[cfg(not(target_arch = "wasm32"))] +pub(super) fn rename_path(from: &std::path::Path, to: &std::path::Path) -> std::io::Result<()> { + std::fs::rename(from, to) +} + +#[cfg(target_arch = "wasm32")] +pub(super) fn rename_path(_: &std::path::Path, _: &std::path::Path) -> std::io::Result<()> { + Err(std::io::Error::other("paths can't be written on the web")) +} + +/// Where `path` points, for telling whether two targets are one file: its folder resolved, its +/// name compared without case where the file system ignores it. +#[cfg(not(target_arch = "wasm32"))] +fn path_key(path: &str) -> String { + let p = std::path::Path::new(path); + let dir = p.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(std::path::Path::new(".")); + let dir = dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf()); + let key = dir.join(p.file_name().unwrap_or_default()).to_string_lossy().into_owned(); + if cfg!(any(target_os = "windows", target_os = "macos")) { key.to_lowercase() } else { key } +} + +/// A new, empty file beside `path` with a name nothing else uses (`create_new`), for staging +/// (`kind` "tmp") or a backup ("bak"). +#[cfg(not(target_arch = "wasm32"))] +fn sibling(path: &str, kind: &str) -> std::io::Result<(std::path::PathBuf, std::fs::File)> { + for n in 0..1000u32 { + let p = std::path::PathBuf::from(format!("{path}.{}-{n}.photocraft-{kind}", std::process::id())); + match std::fs::OpenOptions::new().write(true).create_new(true).open(&p) { + Ok(f) => return Ok((p, f)), + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(e) => return Err(e), + } + } + Err(std::io::Error::other("no free name beside it")) +} + +/// Write `files` ((path, text)) all or nothing. Each text is staged in a new file beside its +/// target; once every one is written, each existing target is moved aside to a backup and the +/// staged file moved in. Any failure moves the backups back and removes what was staged, so the +/// user's files end as they began; on success the backups go. Two targets naming one file are +/// refused. `rename` is `std::fs::rename` (a test fails it on purpose). +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn write_files_atomically( + files: &[(&str, &str)], + rename: &dyn Fn(&std::path::Path, &std::path::Path) -> std::io::Result<()>, +) -> std::result::Result<(), String> { + use std::io::Write; + use std::path::{Path, PathBuf}; + for (i, (a, _)) in files.iter().enumerate() { + if files.iter().skip(i + 1).any(|(b, _)| path_key(a) == path_key(b)) { + return Err(format!("{a}: two exports to the same file")); + } + } + let mut staged: Vec = Vec::new(); + let drop_all = |paths: &[PathBuf]| { + for p in paths { + let _ = std::fs::remove_file(p); + } + }; + for (path, text) in files { + let (tmp, mut f) = match sibling(path, "tmp") { + Ok(v) => v, + Err(e) => { + drop_all(&staged); + return Err(format!("{path}: {e}")); + } + }; + staged.push(tmp); + if let Err(e) = f.write_all(text.as_bytes()).and_then(|()| f.sync_all()) { + drop_all(&staged); + return Err(format!("{path}: {e}")); + } + } + // (target, its backup) of each file moved in so far. + let mut moved: Vec<(&Path, Option)> = Vec::new(); + // Put each backup back over its target (a target that had none is removed). What couldn't be + // put back is named, so the user can find their previous file. + let undo = |moved: &[(&Path, Option)]| -> String { + let mut stranded = Vec::new(); + for (target, backup) in moved.iter().rev() { + match backup { + Some(b) => { + if rename(b, target).is_err() { + stranded.push(format!("the previous {} is at {}", target.display(), b.display())); + } + } + None => { + let _ = std::fs::remove_file(target); + } + } + } + if stranded.is_empty() { String::new() } else { format!(" ({})", stranded.join("; ")) } + }; + for ((path, _), tmp) in files.iter().zip(&staged) { + let target = Path::new(*path); + let backup = if target.exists() { + let moved_aside = sibling(path, "bak").and_then(|(b, f)| { + drop(f); + match rename(target, &b) { + Ok(()) => Ok(b), + Err(e) => { + // The placeholder the backup name reserved goes too. + let _ = std::fs::remove_file(&b); + Err(e) + } + } + }); + match moved_aside { + Ok(b) => Some(b), + Err(e) => { + let stranded = undo(&moved); + drop_all(&staged); + return Err(format!("{path}: {e}{stranded}")); + } + } + } else { + None + }; + if let Err(e) = rename(tmp, target) { + let mut stranded = undo(&moved); + if let Some(b) = &backup + && rename(b, target).is_err() + { + stranded = format!("{stranded} (the previous {path} is at {})", b.display()); + } + drop_all(&staged); + return Err(format!("{path}: {e}{stranded}")); + } + moved.push((target, backup)); + } + for (_, backup) in moved { + if let Some(b) = backup { + let _ = std::fs::remove_file(b); + } + } + Ok(()) +} + +#[cfg(target_arch = "wasm32")] +pub(crate) fn write_files_atomically( + files: &[(&str, &str)], + _: &dyn Fn(&std::path::Path, &std::path::Path) -> std::io::Result<()>, +) -> std::result::Result<(), String> { + if files.is_empty() { Ok(()) } else { Err("paths can't be written on the web; omit `path` to get the text back".into()) } +} diff --git a/crates/engine/src/prefs/shortcuts.rs b/crates/engine/src/prefs/shortcuts.rs new file mode 100644 index 0000000000..47ba5a5f83 --- /dev/null +++ b/crates/engine/src/prefs/shortcuts.rs @@ -0,0 +1,213 @@ +use super::*; + +/// Most further keys one command may hold; Photoshop's own defaults use one. +pub const MAX_ALTERNATES: usize = 8; + +/// Validate and normalise a command's alternate keys: a list of shortcut strings (a single +/// string is a one-key list, `""` none). +pub fn alternate_keys(v: &Value) -> std::result::Result, String> { + let items: Vec<&Value> = match v { + Value::String(s) if s.is_empty() => Vec::new(), + Value::String(_) => vec![v], + Value::Array(a) => a.iter().collect(), + _ => return Err("alternate shortcuts are a list of shortcuts (e.g. [\"F3\"])".into()), + }; + if items.len() > MAX_ALTERNATES { + return Err(format!("at most {MAX_ALTERNATES} alternate shortcuts (got {})", items.len())); + } + let mut out: Vec = Vec::with_capacity(items.len()); + for item in items { + let s = item.as_str().ok_or_else(|| format!("alternate shortcut `{item}` must be a string"))?; + let n = normalize_shortcut(s).ok_or_else(|| format!("`{s}` is not a valid shortcut (e.g. Cmd+Shift+N, F7)"))?; + if !out.contains(&n) { + out.push(n); + } + } + Ok(out) +} + +// ------------------------------------------------------------------ shortcuts + +/// Canonical spelling of a shortcut: modifiers in `Cmd+Ctrl+Alt+Shift` order, key last +/// (single characters upper-cased). `None` if it has no key or an unknown modifier. +pub fn normalize_shortcut(s: &str) -> Option { + let s = s.trim(); + if s.is_empty() { + return None; + } + let (mut cmd, mut ctrl, mut alt, mut shift) = (false, false, false, false); + let mut key: Option = None; + // A trailing "+" key is spelled "Cmd++". + let (body, plus_key) = if s.ends_with("++") || s == "+" { (s.trim_end_matches('+'), true) } else { (s, false) }; + for part in body.split('+').filter(|p| !p.is_empty()) { + match part.to_ascii_lowercase().as_str() { + "cmd" | "command" | "⌘" | "meta" | "super" => cmd = true, + "ctrl" | "control" | "⌃" => ctrl = true, + "alt" | "option" | "opt" | "⌥" => alt = true, + "shift" | "⇧" => shift = true, + _ => { + if key.is_some() { + return None; + } + let k = if part.chars().count() == 1 { part.to_uppercase() } else { capitalize(part) }; + key = Some(k); + } + } + } + if plus_key { + if key.is_some() { + return None; + } + key = Some("+".into()); + } + let key = key?; + let mut out = Vec::new(); + if cmd { + out.push("Cmd"); + } + if ctrl { + out.push("Ctrl"); + } + if alt { + out.push("Alt"); + } + if shift { + out.push("Shift"); + } + let mut s = out.join("+"); + if !s.is_empty() { + s.push('+'); + } + s.push_str(&key); + Some(s) +} + +/// Key names spelled with more than one capital (egui's `Key::name`): Title case would turn +/// `PageUp` into `Pageup`, which no key matches, so a binding saved that way never fired (#6827). +const MULTI_WORD_KEYS: [&str; 8] = + ["PageUp", "PageDown", "OpenBracket", "CloseBracket", "OpenCurlyBracket", "CloseCurlyBracket", "BrowserBack", "IntlBackslash"]; + +fn capitalize(s: &str) -> String { + if let Some(k) = MULTI_WORD_KEYS.iter().find(|k| k.eq_ignore_ascii_case(s)) { + return (*k).to_string(); + } + let mut c = s.chars(); + match c.next() { + Some(f) if f.is_ascii_alphabetic() => { + let rest: String = c.collect(); + // Function keys stay upper-case (F1…F24); named keys are Title case. + if f.eq_ignore_ascii_case(&'f') && rest.chars().all(|c| c.is_ascii_digit()) && !rest.is_empty() { + format!("F{rest}") + } else { + format!("{}{}", f.to_ascii_uppercase(), rest.to_ascii_lowercase()) + } + } + _ => s.to_string(), + } +} + +/// Hold-and-release gestures (#249): temporary tools that last while their key is held and give +/// the previous tool back on release. They are bound like shortcuts (Edit › Keyboard Shortcuts › +/// Tools › Temporary, `edit.keyboardShortcuts`) but held rather than pressed, so they are not +/// commands; the UI reads their keys through [`Preferences::shortcut`]. While a selection or +/// shape is being dragged, the Hand key repositions it instead of panning (Photoshop's Space). +/// The erase key keeps the Brush or Pencil and makes its strokes erase (Photoshop's `~`). +pub const TEMPORARY_TOOLS: &[(&str, &str, &str)] = &[ + ("tools.temporary.hand", "Hand Tool (hold)", "Space"), + ("tools.temporary.zoomIn", "Zoom In (hold, drag to scrub)", "Cmd+Space"), + ("tools.temporary.zoomOut", "Zoom Out (hold)", "Alt+Space"), + ("tools.temporary.erase", "Erase with Brush or Pencil (hold)", "`"), +]; + +/// Photoshop's second default keys (#3665): (command, key). Each command keeps its main key +/// (the one its menu shows) and answers these as well, as in Photoshop's default set: the +/// legacy function keys F2 Cut, F3 Copy, F4 Paste and Shift+F7 Inverse; Shift+Backspace +/// (Shift+Delete on a Mac) for Fill; ⌘+ beside ⌘= for Zoom In; and off the Mac, Ctrl+F4 beside +/// Ctrl+W for Close (Windows' close-document key; macOS keeps Ctrl+F4 for window focus). +pub const ALTERNATE_SHORTCUTS: &[(&str, &str)] = &[ + ("edit.cut", "F2"), + ("edit.copy", "F3"), + ("edit.paste", "F4"), + ("edit.fill", "Shift+Backspace"), + ("select.inverse", "Shift+F7"), + ("view.zoomIn", "Cmd++"), + #[cfg(not(target_os = "macos"))] + ("file.close", "Cmd+F4"), +]; + +/// A command's default alternate keys ([`ALTERNATE_SHORTCUTS`]). +pub fn default_alternates(id: &str) -> impl Iterator + '_ { + ALTERNATE_SHORTCUTS.iter().filter(move |(c, _)| *c == id).map(|(_, sc)| *sc) +} + +/// Keys the system takes before the app sees them (switching apps, closing the window, force +/// quit): `edit.keyboardShortcuts` won't bind them, as Photoshop won't. `sc` is in our notation, +/// where `Cmd` is Ctrl off the Mac. +pub fn reserved_shortcut(sc: &str) -> bool { + let Some(n) = normalize_shortcut(sc) else { return false }; + let reserved: &[&str] = if cfg!(target_os = "macos") { + &["Cmd+Tab", "Cmd+Shift+Tab", "Cmd+Alt+Escape", "Cmd+`"] + } else if cfg!(target_os = "windows") { + &["Alt+Tab", "Alt+Shift+Tab", "Alt+F4", "Cmd+Alt+Delete", "Cmd+Escape", "Cmd+Shift+Escape"] + } else { + // Linux and the BSDs: window switching and closing, and the virtual consoles. + &[ + "Alt+Tab", + "Alt+Shift+Tab", + "Alt+F4", + "Cmd+Alt+Delete", + "Cmd+Alt+F1", + "Cmd+Alt+F2", + "Cmd+Alt+F3", + "Cmd+Alt+F4", + "Cmd+Alt+F5", + "Cmd+Alt+F6", + "Cmd+Alt+F7", + "Cmd+Alt+F8", + "Cmd+Alt+F9", + "Cmd+Alt+F10", + "Cmd+Alt+F11", + "Cmd+Alt+F12", + ] + }; + reserved.iter().filter_map(|r| normalize_shortcut(r)).any(|r| r == n) +} + +/// What a bindable id is: a command (the engine's or the shell's), a tool, or a held tool. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BindKind { + Command, + Tool, + Hold, +} + +/// Every bindable id: (id, label, menu path, default key, kind). The engine's commands, the +/// shell's ([`crate::shell_commands::SHELL_COMMANDS`]), the tools and the held temporary tools, +/// so Edit › Keyboard Shortcuts works the same with or without the app's UI. +pub fn bindable_items() -> impl Iterator, BindKind)> { + let engine = crate::command_specs().iter().map(|c| (c.id, c.label, c.menu, c.shortcut, BindKind::Command)); + let shell = crate::shell_commands::SHELL_COMMANDS.iter().map(|c| (c.0, c.1, c.2, c.3, BindKind::Command)); + let tools = crate::shell_commands::TOOLS.iter().map(|t| (t.0, t.1, &["Tools"][..], t.2, BindKind::Tool)); + let hold = TEMPORARY_TOOLS.iter().map(|t| (t.0, t.1, &["Tools", "Temporary"][..], Some(t.2), BindKind::Hold)); + engine.chain(shell).chain(tools).chain(hold) +} + +/// Every bindable id with its default. +pub(super) fn bindable() -> impl Iterator)> { + bindable_items().map(|i| (i.0, i.3)) +} + +pub(super) fn is_tool(id: &str) -> bool { + crate::shell_commands::tool_default(id).is_some() +} + +/// Shortcuts bound to more than one command: (shortcut, ids). `bindings` are (id, shortcut). +pub fn conflicts<'a>(bindings: impl IntoIterator) -> Vec<(String, Vec)> { + let mut by: BTreeMap> = BTreeMap::new(); + for (id, sc) in bindings { + if let Some(n) = normalize_shortcut(sc) { + by.entry(n).or_default().push(id.to_string()); + } + } + by.into_iter().filter(|(_, ids)| ids.len() > 1).collect() +} diff --git a/crates/engine/src/prefs/store.rs b/crates/engine/src/prefs/store.rs new file mode 100644 index 0000000000..2e0c3e7576 --- /dev/null +++ b/crates/engine/src/prefs/store.rs @@ -0,0 +1,123 @@ +use super::*; + +// ------------------------------------------------------------------ store + +/// The session's preferences plus a revision counter that moves on every change (frontends +/// persist when it moves). +#[derive(Clone, Debug, Default)] +pub struct PrefsStore { + values: Preferences, + rev: u64, +} + +impl PrefsStore { + pub fn get(&self) -> &Preferences { + &self.values + } + /// Change preferences; bumps the revision. + pub fn edit(&mut self, f: impl FnOnce(&mut Preferences) -> R) -> R { + self.rev += 1; + f(&mut self.values) + } + pub fn rev(&self) -> u64 { + self.rev + } +} + +/// The preferences file format written by [`Session::prefs_value`]. 2: Use Shift Key for Tool +/// Switch stored as chosen (before, a stored `false` was the old default; see `load_prefs_json`). +pub const PREFS_VERSION: u64 = 2; + +/// A saved preference [`Session::load_prefs_json`] couldn't read (a wrong type, an unknown +/// choice) and left at its default. +#[derive(Clone, Debug, PartialEq)] +pub struct InvalidPref { + /// JSON keys from the top of the preferences file (`["fileHandling", "recentFileCount"]`), + /// kept apart because keys such as command ids contain dots. + pub keys: Vec, + /// The value the file held there. + pub value: Value, +} + +impl InvalidPref { + /// The dotted path, as `prefs.get` and `prefs.set` take it. + pub fn path(&self) -> String { + self.keys.join(".") + } +} + +/// How deep [`read_lenient`] looks for the readable parts of an unreadable value. +const LENIENT_DEPTH: usize = 32; + +/// Read `v` as a `T`. When that fails, start from `T::default()` and lay the file's values over +/// it one at a time, keeping each one the whole still reads with and descending into objects +/// that don't, so one bad value resets only itself. The values left out are added to +/// `invalid`, their keys after `prefix`. +pub(super) fn read_lenient(v: Value, prefix: &[&str], invalid: &mut Vec) -> T +where + T: Default + Serialize + for<'de> Deserialize<'de>, +{ + if let Ok(t) = T::deserialize(&v) { + return t; + } + let prefix: Vec = prefix.iter().map(|k| (*k).to_string()).collect(); + let mut acc = serde_json::to_value(T::default()).unwrap_or(Value::Null); + let fits = |root: &Value| T::deserialize(root).is_ok(); + match v { + Value::Object(file) if acc.is_object() && fits(&acc) => { + lay_over(&mut acc, &mut Vec::new(), file, &fits, &prefix, invalid); + T::deserialize(&acc).unwrap_or_default() + } + value => { + invalid.push(InvalidPref { keys: prefix, value }); + T::default() + } + } +} + +/// [`read_lenient`]'s walk: lay `file` over the object at `at` inside `root`, key by key, so that +/// `root` always reads (`fits`). +fn lay_over( + root: &mut Value, + at: &mut Vec, + file: Map, + fits: &dyn Fn(&Value) -> bool, + prefix: &[String], + invalid: &mut Vec, +) { + for (k, fv) in file { + let Some(obj) = object_at(root, at) else { return }; + let old = obj.insert(k.clone(), fv.clone()); + if fits(root) { + continue; + } + // Back to the default. An object keeps its parts that read, and so does a new map entry + // (a shortcut set, a workspace) when it reads from an empty object. + let Some(obj) = object_at(root, at) else { return }; + let mut descend = fv.is_object() && at.len() < LENIENT_DEPTH && matches!(old, None | Some(Value::Object(_))); + match old { + Some(o) => obj.insert(k.clone(), o), + None if descend => obj.insert(k.clone(), Value::Object(Map::new())), + None => obj.remove(&k), + }; + at.push(k); + if descend && !fits(root) { + descend = false; + if let Some((key, parent)) = at.split_last() + && let Some(obj) = object_at(root, parent) + { + obj.remove(key); + } + } + match fv { + Value::Object(m) if descend => lay_over(root, at, m, fits, prefix, invalid), + value => invalid.push(InvalidPref { keys: prefix.iter().chain(at.iter()).cloned().collect(), value }), + } + at.pop(); + } +} + +/// The JSON object at `path` inside `root`. +fn object_at<'a>(root: &'a mut Value, path: &[String]) -> Option<&'a mut Map> { + path.iter().try_fold(root, |cur, k| cur.get_mut(k.as_str()))?.as_object_mut() +} diff --git a/crates/engine/src/prefs/validate.rs b/crates/engine/src/prefs/validate.rs new file mode 100644 index 0000000000..af637f90d9 --- /dev/null +++ b/crates/engine/src/prefs/validate.rs @@ -0,0 +1,272 @@ +use super::shortcuts::normalize_shortcut; +use super::*; + +/// Preferences dialog sections in Photoshop's order: (id, title). +pub const SECTIONS: [(&str, &str); 18] = [ + ("general", "General"), + ("interface", "Interface"), + ("workspace", "Workspace"), + ("tools", "Tools"), + ("historyLog", "History Log"), + ("fileHandling", "File Handling"), + ("export", "Export"), + ("performance", "Performance"), + ("scratchDisks", "Scratch Disks"), + ("cursors", "Cursors"), + ("transparencyAndGamut", "Transparency & Gamut"), + ("unitsAndRulers", "Units & Rulers"), + ("guidesGridAndSlices", "Guides, Grid & Slices"), + ("plugIns", "Plug-ins"), + ("type", "Type"), + ("enhancedControls", "Enhanced Controls"), + ("rawDefaults", "Camera Raw Defaults"), + ("integrations", "Integrations"), +]; + +/// Preferences that nothing reads yet, so Edit › Preferences doesn't show them: a control that +/// does nothing is worse than a missing one (https://github.com/storytold/photocraft/issues/204). +/// They still load, save and round-trip through `prefs.get` / `prefs.set` unchanged. +/// +/// When you implement one, remove it here; the `prefs_usage` test fails while a listed +/// preference is read anywhere outside `prefs.rs`, and while an unlisted one is read nowhere. +pub const HIDDEN_UNTIL_IMPLEMENTED: &[&str] = &[ + "general.colorPicker", + "workspace.autoShowHiddenPanels", + "workspace.enableFloatingDocumentWindowDocking", + "performance.effectCacheMb", + "performance.legacyCompositing", + "scratchDisks.disks", + "unitsAndRulers.columnWidth", + "unitsAndRulers.gutter", + "plugIns.showExtensionPanels", + "plugIns.allowScriptsToConnect", + "type.textEngine", + "enhancedControls.scrubbySliderAcceleration", +]; + +/// Is the preference at `path` (`"section.key"`) hidden from the Preferences dialog? +pub fn is_hidden(path: &str) -> bool { + HIDDEN_UNTIL_IMPLEMENTED.contains(&path) || (!cfg!(target_os = "linux") && LINUX_ONLY.contains(&path)) +} + +/// Preferences that only do something on Linux; the dialog doesn't show them elsewhere. They +/// still load, save and round-trip on every platform. +pub const LINUX_ONLY: &[&str] = &["performance.linuxDisplayServer", "performance.gpuAdapter"]; + +/// Whether a graphics adapter called `name` is the one `performance.gpuAdapter` (`wanted`) asks +/// for: every whitespace-separated word of `wanted` appears in the name, ignoring case ("nvidia", +/// "arc a370m"). An empty `wanted` matches nothing. Startup and Preferences share this. +pub fn gpu_adapter_matches(name: &str, wanted: &str) -> bool { + let name = name.to_lowercase(); + let mut words = wanted.split_whitespace().peekable(); + words.peek().is_some() && words.all(|w| name.contains(&w.to_lowercase())) +} + +/// Choices of an enumerated preference (dotted path, e.g. `"cursors.painting"`). +pub fn choices(path: &str) -> Option<&'static [&'static str]> { + Some(match path { + "general.colorPicker" => ColorPicker::NAMES, + "general.imageInterpolation" => Interpolation::NAMES, + "interface.theme" => Theme::NAMES, + "interface.appearanceMode" => AppearanceMode::NAMES, + "interface.darkTheme" => DarkTheme::NAMES, + "interface.lightTheme" => LightTheme::NAMES, + "interface.canvasColor" => CanvasColor::NAMES, + "interface.canvasBorder" => CanvasBorder::NAMES, + "interface.uiScale" => UiScale::NAMES, + "interface.uiFontSize" => UiFontSize::NAMES, + "historyLog.destination" => LogDestination::NAMES, + "historyLog.detail" => LogDetail::NAMES, + "fileHandling.imagePreviews" | "fileHandling.maximizePsdCompatibility" => Ask::NAMES, + "export.quickExportFormat" => QuickExportFormat::NAMES, + "export.quickExportLocation" => ExportLocation::NAMES, + "export.metadata" => ExportMetadata::NAMES, + "cursors.painting" => PaintingCursor::NAMES, + "cursors.other" => OtherCursor::NAMES, + "tools.rightClickWithPaintingTools" => RightClickPaint::NAMES, + "transparencyAndGamut.gridSize" => CheckerSize::NAMES, + "transparencyAndGamut.gridColors" => CheckerColors::NAMES, + "unitsAndRulers.rulers" | "guidesGridAndSlices.gridUnit" => Unit::NAMES, + "unitsAndRulers.typeUnits" => TypeUnit::NAMES, + "unitsAndRulers.pointSize" => PointSize::NAMES, + "guidesGridAndSlices.guideStyle" | "guidesGridAndSlices.gridStyle" => LineStyle::NAMES, + "type.textEngine" => TextEngine::NAMES, + "type.fontPreview" => FontPreview::NAMES, + "rawDefaults.colorSpace" => RawColorSpace::NAMES, + "rawDefaults.bitDepth" => RawDepth::NAMES, + "rawDefaults.sharpenFor" => RawSharpen::NAMES, + "rawDefaults.demosaic" => RawDemosaic::NAMES, + "performance.gpuBackend" => GpuBackend::NAMES, + "performance.linuxDisplayServer" => LinuxDisplayServer::NAMES, + "performance.renderingMode" => RenderingMode::NAMES, + _ => return None, + }) +} + +/// Valid range of a numeric preference. +pub fn range(path: &str) -> Option<(f64, f64)> { + Some(match path { + "fileHandling.autosaveMinutes" => (1.0, 240.0), + "fileHandling.recentFileCount" => (0.0, 100.0), + "tools.nudgeBundlePauseMs" => (100.0, 10_000.0), + "fileHandling.rasterizeSvgGroupsDeeperThan" => (0.0, photocraft_doc::MAX_GROUP_DEPTH as f64), + "interface.notificationDurationSeconds" => (1.0, 120.0), + "export.jpegQuality" | "export.webpQuality" => (1.0, 100.0), + "performance.memoryUsageMb" => (256.0, 1_048_576.0), + "performance.gpuMemoryMb" => (0.0, 1_048_576.0), + "performance.historyStates" => (1.0, 1000.0), + "performance.cacheLevels" => (1.0, 8.0), + "performance.cacheTileSize" => (256.0, 16384.0), + "performance.effectCacheMb" => (16.0, 65536.0), + "transparencyAndGamut.gamutWarningOpacity" => (1.0, 100.0), + "unitsAndRulers.columnWidth" | "unitsAndRulers.gutter" => (0.0, 10_000.0), + "unitsAndRulers.printResolution" | "unitsAndRulers.screenResolution" | "rawDefaults.resolution" => (1.0, 10_000.0), + "guidesGridAndSlices.gridlineEvery" => (0.001, 10_000.0), + "guidesGridAndSlices.subdivisions" => (1.0, 100.0), + "layerMaskOverlay.opacity" => (0.0, 100.0), + "type.recentFonts" => (0.0, 50.0), + "integrations.controlPort" => (0.0, 65535.0), + _ => return None, + }) +} + +/// Is this preference a `#rrggbb` colour? +pub fn is_color(path: &str) -> bool { + if choices(path).is_some() || path.starts_with("shortcuts.") || path.starts_with("alternateShortcuts.") || path.starts_with("menus.") { + return false; + } + if path == "layerMaskOverlay.color" { + return true; + } + let leaf = path.rsplit('.').next().unwrap_or(path); + matches!( + leaf, + "guideColor" + | "smartGuideColor" + | "gridColor" + | "sliceColor" + | "canvasCustomColor" + | "brushPreviewColor" + | "gamutWarningColor" + | "customLight" + | "customDark" + ) +} + +pub fn parse_hex(s: &str) -> Option<[u8; 3]> { + let s = s.trim().trim_start_matches('#'); + if s.len() != 6 { + return None; + } + let b = |i: usize| s.get(i..i + 2).and_then(|s| u8::from_str_radix(s, 16).ok()); + Some([b(0)?, b(2)?, b(4)?]) +} + +// ------------------------------------------------------------------ JSON paths + +/// Map keys that are command ids (which contain dots): `shortcuts.`, +/// `alternateShortcuts.`, `menus.colors.`. +pub(super) fn keyed(path: &str) -> Option<(&str, &str)> { + for prefix in ["shortcuts.", "alternateShortcuts.", "menus.colors."] { + if let Some(id) = path.strip_prefix(prefix) { + return Some((&prefix[..prefix.len() - 1], id)); + } + } + None +} + +pub(super) fn get_path<'a>(root: &'a Value, path: &str) -> Option<&'a Value> { + if path.is_empty() { + return Some(root); + } + if let Some((map, id)) = keyed(path) { + return get_path(root, map)?.get(id); + } + path.split('.').try_fold(root, |v, k| v.get(k)) +} + +/// Set `value` at `path` (creating keys only inside free-form maps such as `shortcuts`). +pub(super) fn set_path(root: &mut Value, path: &str, value: Value) -> std::result::Result<(), String> { + if let Some((map, id)) = keyed(path) { + let mut cur = &mut *root; + for k in map.split('.') { + cur = cur.get_mut(k).ok_or_else(|| format!("unknown preference `{path}`"))?; + } + cur.as_object_mut().ok_or_else(|| format!("`{map}` is not a map"))?.insert(id.to_string(), value); + return Ok(()); + } + let keys: Vec<&str> = path.split('.').filter(|k| !k.is_empty()).collect(); + let Some((last, parents)) = keys.split_last() else { return Err("empty path".into()) }; + let mut cur = root; + for k in parents { + cur = cur.get_mut(*k).ok_or_else(|| format!("unknown preference `{path}`"))?; + } + let free_map = matches!(parents.first(), Some(&"shortcuts")) || (parents.len() == 2 && parents[0] == "menus" && parents[1] == "colors"); + let obj = cur.as_object_mut().ok_or_else(|| format!("`{path}` is not inside a section"))?; + if !obj.contains_key(*last) && !free_map { + return Err(format!("unknown preference `{path}`")); + } + obj.insert(last.to_string(), value); + Ok(()) +} + +/// Validate one value for `path` before it is stored (choices, ranges, colours). +pub(super) fn check_value(path: &str, v: &Value) -> std::result::Result<(), String> { + if path == "interface.favoriteThemes" { + let items = v.as_array().ok_or("`interface.favoriteThemes` must be a list of theme ids")?; + if items.len() > Theme::NAMES.len() { + return Err("`interface.favoriteThemes` contains too many themes".into()); + } + let mut seen = Vec::with_capacity(items.len()); + for item in items { + let theme = item.as_str().and_then(Theme::parse).ok_or_else(|| format!("unknown favorite theme `{item}`"))?; + if seen.contains(&theme) { + return Err(format!("duplicate favorite theme `{}`", theme.name())); + } + seen.push(theme); + } + } + if path == "performance.renderingMode" && v.is_null() { + return Ok(()); // Legacy policy, resolved from useGpu and gpuBackend. + } + if let Some(c) = choices(path) { + let s = v.as_str().ok_or_else(|| format!("`{path}` must be one of {}", c.join("|")))?; + if !c.contains(&s) { + return Err(format!("`{path}` must be one of {} (got `{s}`)", c.join("|"))); + } + } + if path == "interface.language" { + let ok = v.as_str().is_some_and(|s| !s.is_empty() && s.len() <= 16 && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')); + if !ok { + return Err("`interface.language` must be `auto` or a language code such as `en` or `ja`".into()); + } + } + if let Some((lo, hi)) = range(path) { + let x = v.as_f64().ok_or_else(|| format!("`{path}` must be a number"))?; + if !(lo..=hi).contains(&x) { + return Err(format!("`{path}` must be within {lo}..{hi} (got {x})")); + } + } + if is_color(path) && v.as_str().and_then(parse_hex).is_none() { + return Err(format!("`{path}` must be a #rrggbb colour")); + } + if path == "tools.pressureCurve" { + let pts = v.as_array().ok_or("`tools.pressureCurve` must be a list of [input, output] points")?; + if !(2..=PressureCurve::MAX_POINTS).contains(&pts.len()) { + return Err(format!("`tools.pressureCurve` needs 2..={} points (got {})", PressureCurve::MAX_POINTS, pts.len())); + } + for p in pts { + let ok = p.as_array().is_some_and(|a| a.len() == 2 && a.iter().all(|x| x.as_f64().is_some_and(|x| (0.0..=1.0).contains(&x)))); + if !ok { + return Err(format!("`tools.pressureCurve` points are [input, output] pairs within 0..1 (got {p})")); + } + } + } + if let Some(sc) = path.strip_prefix("shortcuts.") { + let s = v.as_str().ok_or_else(|| format!("shortcut for `{sc}` must be a string"))?; + if !s.is_empty() && normalize_shortcut(s).is_none() { + return Err(format!("`{s}` is not a valid shortcut (e.g. Cmd+Shift+N, F7)")); + } + } + Ok(()) +} diff --git a/crates/engine/src/presets/mod.rs b/crates/engine/src/presets.rs similarity index 100% rename from crates/engine/src/presets/mod.rs rename to crates/engine/src/presets.rs diff --git a/crates/engine/src/retouch_cmds.rs b/crates/engine/src/retouch_cmds.rs deleted file mode 100644 index 063eca3363..0000000000 --- a/crates/engine/src/retouch_cmds.rs +++ /dev/null @@ -1,1709 +0,0 @@ -//! Retouching tools as commands: Clone Stamp, Pattern Stamp, Healing Brush, Spot Healing Brush, -//! Patch, Content-Aware Move, Remove, Dodge, Burn, Sponge, Blur, Sharpen, Smudge, History Brush and -//! Art History Brush. -//! -//! Every command takes a Photoshop-style brush (`points`, `size`, `hardness`, `opacity`, `flow`, -//! `spacing`, `layer`), respects the active selection as a mask and the layer's transparency lock, and -//! works at any depth (8/16/32f) and colour model. Like the Brush, each paints the targeted surface: -//! the layer's pixels, its mask (`"target":"mask"`), an alpha channel or the Quick Mask (`"target"`, -//! filled in from the Channels panel when absent). The pixel algorithms live in `photocraft-algo` -//! (`poisson`, `inpaint`, `retouch`) and the dab machinery in `photocraft-paint::retouch`; this module -//! only parses parameters and wires them together. - -use photocraft_algo::inpaint::{self, CompleteParams}; -use photocraft_algo::poisson; -use photocraft_algo::retouch::{ToneRange, dodge_burn, local_blur, local_sharpen, sponge}; -use photocraft_color::{BlendMode, PixelFormat, SampleType}; -use photocraft_doc::{Document, LayerContent, LayerId}; -use photocraft_geom::Rect; -use photocraft_paint::retouch::{Footprint, Region, Smudge, alpha_index, apply_coverage, apply_dab_stroke}; -use photocraft_paint::{BrushSettings, Stroke, StrokePoint}; -use photocraft_raster::{Surface, from_rgba_into, to_rgba}; -use rayon::prelude::*; -use serde_json::{Value, json}; - -use crate::commands::{CommandSpec, blend_from_str}; -use crate::{EngineError, Result, Session}; - -mod art_history; -mod content_aware_move; -mod patch; -mod pattern_stamp; -pub use pattern_stamp::live_impressionist as live_pattern_impressionist; -mod periodic; -mod remove; -pub use content_aware_move::{ContentAwarePreview, preview as content_aware_move_preview}; -pub use patch::preview as patch_preview; - -fn bad(cmd: &str, msg: impl Into) -> EngineError { - EngineError::BadParams { cmd: cmd.into(), msg: msg.into() } -} - -/// A single stroke's accumulated coverage must stay at or under this many pixels (8192², so a -/// stroke corner to corner across a 24–36 MP canvas fits). Larger footprints return an error -/// instead of allocating. -const MAX_STROKE_PIXELS: u64 = 67_108_864; - -/// Refuse a stroke whose footprint would not fit the coverage budget, from the points and brush -/// size alone, before the renderer allocates anything for it. -fn reject_huge_stroke(cmd: &str, stroke: &Stroke) -> Result<()> { - // Dynamics place dabs beyond the input points, so half the tip is not the whole reach: - // Scattering offsets a centre by up to its amount times the tip size, and a Dual Brush dab - // reaches its own radius further. Pad by what those can add so this estimate does not fall - // short of what the renderer will cover. It is only the cheap early-out; the rendered extent - // is admitted for real in `coverage` below. - let b = &stroke.brush; - let size = f64::from(b.size.max(1.0)); - let scatter = if b.scattering.enabled { size * f64::from(b.scattering.scatter.jitter.max(0.0)) } else { 0.0 }; - let dual = if b.dual_brush.enabled { f64::from(b.dual_brush.size.max(0.0)) * 0.5 } else { 0.0 }; - let pad = size.mul_add(0.5, 4.0) + scatter + dual; - let mut min_x = f64::INFINITY; - let mut min_y = f64::INFINITY; - let mut max_x = f64::NEG_INFINITY; - let mut max_y = f64::NEG_INFINITY; - for q in &stroke.points { - min_x = min_x.min(q.x); - min_y = min_y.min(q.y); - max_x = max_x.max(q.x); - max_y = max_y.max(q.y); - } - if !min_x.is_finite() || !min_y.is_finite() || !max_x.is_finite() || !max_y.is_finite() { - return Err(bad(cmd, "point coordinates must be finite")); - } - let w = (max_x - min_x + pad * 2.0).ceil().max(1.0); - let h = (max_y - min_y + pad * 2.0).ceil().max(1.0); - if !w.is_finite() || !h.is_finite() || w > 1.0e9 || h > 1.0e9 { - return Err(bad(cmd, format!("stroke too large (at most {MAX_STROKE_PIXELS} px)"))); - } - let area = (w as u64).saturating_mul(h as u64); - if area > MAX_STROKE_PIXELS { - return Err(bad(cmd, format!("stroke too large ({w:.0}×{h:.0} px, at most {MAX_STROKE_PIXELS})"))); - } - Ok(()) -} - -/// The stroke's coverage, with the **rendered** extent admitted before the dense buffer exists. -/// -/// `reject_huge_stroke` estimates from the input points; this is the real bound. Rendering is -/// tiled, so it holds only the tiles the dabs touch; the extent is read from those tiles once -/// every dab is placed (tips, dynamics and scattering included) and checked against `max`, and -/// only a stroke that fits is made dense. `max` is a parameter so tests can inject a small budget. -fn coverage_within(cmd: &str, stroke: &Stroke, max: u64) -> Result<(Rect, Vec)> { - photocraft_paint::retouch::stroke_coverage_within(stroke, max).ok_or_else(|| bad(cmd, format!("stroke too large (at most {max} px)"))) -} - -/// [`coverage_within`] at the shared allowance. -fn coverage(cmd: &str, stroke: &Stroke) -> Result<(Rect, Vec)> { - coverage_within(cmd, stroke, MAX_STROKE_PIXELS) -} - -/// A pixel layer, a layer with a mask, or a targeted alpha channel / Quick Mask (as the Brush). -fn has_pixel_layer(s: &Session) -> std::result::Result<(), String> { - if crate::channel_cmds::edits_channel(s) { - return Ok(()); - } - let d = s.active().ok_or("no document open")?; - let l = d.active_layer.and_then(|id| d.doc.layer(id)).ok_or("no active layer")?; - if matches!(l.content, LayerContent::Raster(_)) || l.mask.is_some() { - Ok(()) - } else { - Err(format!("active layer is {} {} layer, not a pixel layer", l.content.article(), l.content.kind_name())) - } -} - -/// The stroke paints layer pixels (not a mask or channel), so other layers can be sampled. -fn targets_pixels(p: &Value) -> bool { - crate::channel_cmds::target_of(p) == crate::channel_cmds::Target::Pixels -} - -fn num(p: &Value, k: &str, d: f32) -> f32 { - p.get(k).and_then(Value::as_f64).map_or(d, |v| v as f32) -} -fn flag(p: &Value, k: &str, d: bool) -> bool { - p.get(k).and_then(Value::as_bool).unwrap_or(d) -} -fn string<'a>(p: &'a Value, k: &str, d: &'a str) -> &'a str { - p.get(k).and_then(Value::as_str).unwrap_or(d) -} -fn point(p: &Value, k: &str) -> Option<(f64, f64)> { - let a = p.get(k)?.as_array()?; - Some((a.first()?.as_f64()?, a.get(1)?.as_f64()?)) -} - -/// The brush a retouching stroke paints with: the tool's brush (`base`, its tip, hardness and -/// shape dynamics) with the shared params of `p` applied. UI previews of a stroke (the Spot Healing -/// Brush's trail) render their coverage with it, so they match what the command changes. -pub fn stroke_brush(base: &BrushSettings, p: &Value) -> BrushSettings { - let pct = |k: &str, d: f32, lo: f32, hi: f32| num(p, k, d).clamp(lo, hi) / 100.0; - BrushSettings { - size: num(p, "size", base.size).max(1.0), - hardness: pct("hardness", base.hardness * 100.0, 0.0, 100.0), - opacity: pct("opacity", 100.0, 1.0, 100.0), - flow: pct("flow", 100.0, 1.0, 100.0), - // Brush Settings › Brush Tip Shape › Spacing, as the Brush uses it (#2140). - spacing: pct("spacing", base.spacing * 100.0, 1.0, 1000.0), - erase: false, - ..base.clone() - } -} - -/// Parse the shared brush params into a stroke on a layer (`None` when an alpha channel or the -/// Quick Mask is targeted). -fn parse_brush(s: &Session, p: &Value, cmd: &str) -> Result<(Stroke, Option)> { - let pts: Vec = p - .get("points") - .and_then(Value::as_array) - .ok_or_else(|| bad(cmd, "missing `points`"))? - .iter() - .filter_map(|v| { - let a = v.as_array()?; - Some(StrokePoint::new(a.first()?.as_f64()?, a.get(1)?.as_f64()?, a.get(2).and_then(Value::as_f64).unwrap_or(1.0) as f32)) - }) - .collect(); - if pts.is_empty() { - return Err(bad(cmd, "`points` is empty")); - } - crate::brush_cmds::check_coords(&pts, cmd)?; - let brush = stroke_brush(&s.tools.brush, p); - crate::brush_cmds::validate_brush(&brush, cmd)?; - if crate::channel_cmds::is_channel_target(p) { - return Ok((Stroke { brush, points: pts }, None)); - } - let id = match p.get("layer").and_then(Value::as_u64) { - Some(id) => LayerId(id), - None => s.active().and_then(|d| d.active_layer).ok_or(EngineError::Other("no active layer".into()))?, - }; - Ok((Stroke { brush, points: pts }, Some(id))) -} - -/// Run `f` on the targeted surface (layer pixels, layer mask, alpha channel or Quick Mask: the -/// Brush's paint target) inside one undoable step. `f` gets the pre-stroke document (a cheap -/// copy-on-write snapshot), the surface, the selection and the transparency lock. -fn run_stroke( - s: &mut Session, - label: &str, - id: Option, - p: &Value, - f: impl FnOnce(&Document, &mut Surface, Option<&Surface>, bool) -> Result, -) -> Result { - let dmg = s.edit(label, |doc, _| { - let pre = doc.clone(); - let (surf, lock) = crate::channel_cmds::target_surface(doc, id, p)?; - // No prune: retouching only rewrites pixels inside the stroke, and scanning every tile of a - // large layer would dominate the cost of a dab. - f(&pre, surf, pre.selection.as_ref(), lock) - })?; - if let Some(st) = s.active_mut() { - st.last_damage = Some(dmg); - } - Ok(dmg) -} - -fn damage_json(r: Rect) -> Value { - json!([r.x0, r.y0, r.width(), r.height()]) -} - -// --------------------------------------------------------------------------------------------- -// Sampling sources -// --------------------------------------------------------------------------------------------- - -/// Which pixels Clone Stamp / Healing Brush sample. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum SampleLayers { - Current, - CurrentAndBelow, - All, -} - -fn sample_layers(p: &Value, cmd: &str) -> Result { - match string(p, "sampleLayer", "current") { - "current" => Ok(SampleLayers::Current), - "currentAndBelow" => Ok(SampleLayers::CurrentAndBelow), - "all" => Ok(SampleLayers::All), - o => Err(bad(cmd, format!("unknown sampleLayer `{o}` (current|currentAndBelow|all)"))), - } -} - -/// Composite pixels of `rect` in `fmt` (native channels): the whole document, or the target layer -/// and everything below it. -pub(crate) fn composite_region(pre: &Document, id: Option, which: SampleLayers, rect: Rect, fmt: PixelFormat) -> Region { - let mut doc = pre.clone(); - if which == SampleLayers::CurrentAndBelow - && let Some(id) = id - { - // Hide everything composited after (above) the target in the bottom-to-top walk. - let walk: Vec<(Vec, LayerId)> = pre.walk().into_iter().map(|(p, _, l)| (p, l.id)).collect(); - if let Some(pos) = walk.iter().position(|(_, l)| *l == id) { - for (path, _) in &walk[pos + 1..] { - if let Some(l) = doc.layer_at_mut(path) { - l.visible = false; - } - } - } - } - let buf = photocraft_compose::render(&doc, rect); - let n = fmt.channels(); - let mut out = Region::new(rect, n); - let mut enc = [0.0f32; 8]; - for (i, px) in buf.px.iter().enumerate() { - from_rgba_into(&fmt, *px, &mut enc); - out.data[i * n..(i + 1) * n].copy_from_slice(&enc[..n]); - } - out -} - -/// Pixels to sample at `rect` (document coordinates, already offset to the source position). -fn sample(pre: &Document, id: Option, surf: &Surface, which: SampleLayers, rect: Rect) -> Region { - match which { - SampleLayers::Current => Region::read(surf, rect), - _ => composite_region(pre, id, which, rect, surf.format()), - } -} - -/// Where a clone stroke samples: `offset` / `source` params, else the active Clone Source slot, -/// with the slot's (or the call's) scale, rotation and flips (see `presets::clone_source`). -fn clone_mapping(s: &mut Session, p: &Value, stroke: &Stroke, cmd: &str) -> Result { - let f = stroke.points[0]; - crate::presets::clone_source::mapping(s, p, (f.x, f.y), cmd) -} - -/// Source pixels for destination `rect`: a translated read, or a bilinear resample when the -/// clone source is scaled, rotated or flipped. -#[allow(clippy::too_many_arguments)] -fn clone_sample( - pre: &Document, - id: Option, - surf: &Surface, - which: SampleLayers, - rect: Rect, - map: &crate::presets::clone_source::Mapping, - wrap: bool, - cmd: &str, -) -> Result { - let read = |rect| { - if wrap { periodic::sample(pre, id, surf, which, rect, cmd) } else { Ok(sample(pre, id, surf, which, rect)) } - }; - if map.is_translation() { - let off = map.offset(); - let src = rect.translate(off.0, off.1); - // `translate` saturates at the i32 edges, so a far source (issue #1111) yields a window - // smaller than `rect`; relabelling that as `rect` would index past the sampled pixels. - if src.width() != rect.width() || src.height() != rect.height() { - return Err(bad(cmd, format!("source offset [{}, {}] is too far: the sample window leaves the coordinate range", off.0, off.1))); - } - let mut r = read(src)?; - r.rect = rect; - return Ok(r); - } - let src = read(map.source_rect(rect))?; - Ok(crate::presets::clone_source::resample(&src, rect, map, alpha_index(&surf.format()))) -} - -/// Read-only clone overlay. Shares the stroke sampler without anchoring a source or editing history. -/// Both destination and transformed source allocations are bounded for interactive use. -pub fn clone_preview(s: &Session, rect: Rect, map: &crate::presets::clone_source::Mapping, sample_layer: &str) -> Result { - clone_preview_periodic(s, rect, map, sample_layer, false) -} - -/// Clone-source overlay with optional source repetition for View > Pattern Preview. -pub fn clone_preview_periodic( - s: &Session, - rect: Rect, - map: &crate::presets::clone_source::Mapping, - sample_layer: &str, - wrap: bool, -) -> Result { - if ![map.source.0, map.source.1, map.anchor.0, map.anchor.1].into_iter().chain(map.m).all(|v| v.is_finite() && v.abs() < 1_000_000.0) { - return Err(bad("clone.preview", "invalid preview mapping")); - } - if ![rect.x0, rect.y0, rect.x1, rect.y1].into_iter().all(|v| v.abs_diff(0) < 1_000_000) - || ![(rect.x0, rect.y0), (rect.x1, rect.y1), (rect.x0, rect.y1), (rect.x1, rect.y0)].into_iter().all(|(x, y)| { - let (x, y) = map.map(f64::from(x), f64::from(y)); - x.is_finite() && y.is_finite() && x.abs() < 1_000_000.0 && y.abs() < 1_000_000.0 - }) - { - return Err(bad("clone.preview", "preview coordinates exceed their budget")); - } - let bounded = |r: Rect| r.width() > 0 && r.height() > 0 && r.width() <= 1024 && r.height() <= 1024; - if !bounded(rect) || !bounded(map.source_rect(rect)) { - return Err(bad("clone.preview", "preview region exceeds its budget")); - } - let d = s.active().ok_or(EngineError::NoDocument)?; - let id = d.active_layer.ok_or_else(|| bad("clone.preview", "no active layer"))?; - let surf = d.doc.layer(id).and_then(|l| l.surface()).ok_or_else(|| bad("clone.preview", "no pixel surface"))?; - let which = sample_layers(&json!({"sampleLayer": sample_layer}), "clone.preview")?; - let region = clone_sample(&d.doc, Some(id), surf, which, rect, map, wrap, "clone.preview")?; - let px = region.data.chunks_exact(surf.format().channels()).map(|p| to_rgba(&surf.format(), p)).collect(); - Ok(photocraft_compose::Buffer { rect, px }) -} - -/// Result JSON shared by Clone Stamp and Healing Brush: the offset used and where the next stroke -/// should sample from if the UI keeps Photoshop's "Aligned" semantics. -fn clone_result(dmg: Rect, off: (i32, i32), aligned: bool, p: &Value, stroke: &Stroke) -> Value { - let f = stroke.points[0]; - let source = point(p, "source").unwrap_or((f.x + off.0 as f64, f.y + off.1 as f64)); - // Aligned: the offset persists (next stroke samples at its own first point + offset). - // Non-aligned: every stroke restarts at the original source point. - json!({ "damage": damage_json(dmg), "offset": [off.0, off.1], "aligned": aligned, "nextSource": if aligned { Value::Null } else { json!([source.0, source.1]) } }) -} - -fn blend_param(p: &Value, cmd: &str) -> Result { - match p.get("mode").and_then(Value::as_str) { - None => Ok(BlendMode::Normal), - Some(m) => blend_from_str(m).ok_or_else(|| bad(cmd, format!("unknown blend mode `{m}`"))), - } -} - -/// Clamp results into the storable range: integer depths to 0..1, float depths only below at 0; -/// alpha always 0..1. -fn clamp_samples(fmt: &PixelFormat, data: &mut [f32]) { - let n = fmt.channels(); - let a = alpha_index(fmt); - let float = fmt.sample == SampleType::F32; - for px in data.chunks_exact_mut(n) { - for (c, v) in px.iter_mut().enumerate() { - *v = if Some(c) == a || !float { v.clamp(0.0, 1.0) } else { v.max(0.0) }; - } - } -} - -// --------------------------------------------------------------------------------------------- -// Clone Stamp / Healing Brush / History Brush -// --------------------------------------------------------------------------------------------- - -fn clone_stamp(s: &mut Session, p: &Value) -> Result { - const CMD: &str = "paint.cloneStamp"; - let (stroke, id) = parse_brush(s, p, CMD)?; - reject_huge_stroke(CMD, &stroke)?; - let which = sample_layers(p, CMD)?; - let mode = blend_param(p, CMD)?; - let aligned = flag(p, "aligned", true); - // The live stroke the canvas already drew for exactly this commit: take its pixels instead of - // rendering the stroke again (the hitch on release). - let live = s.live_commit.take().filter(|l| l.matches(s, CMD, p, &stroke.points)); - let from_live = live.is_some(); - let map = clone_mapping(s, p, &stroke, CMD)?; - let off = map.offset(); - let dmg = - run_stroke(s, "Clone Stamp", id, p, |pre, surf, sel, lock| { - if let Some(l) = live { - *surf = l.surface; - return Ok(l.bounds); - } - if flag(p, "wrap", false) { - let mut renderer = photocraft_paint::StrokeRenderer::new(&stroke.brush, None, 1.0); - renderer.push(&stroke.points); - renderer.finish(); - let before = surf.clone(); - let bounds = renderer.bounds(); - return periodic::Composite { target: surf, before: &before, tile: pre.bounds(), opacity: stroke.brush.opacity, selection: sel, lock, mode } - .draw(bounds, &stroke.brush, &stroke.points, |r| clone_sample(pre, id, &before, which, r, &map, true, CMD)); - } - let (bounds, cov) = coverage(CMD, &stroke)?; - // Samples come from the pre-stroke state, so pixels painted earlier in the stroke are never re-cloned. - let paint = clone_sample(pre, id, surf, which, bounds, &map, flag(p, "wrap", false), CMD)?; - Ok(apply_coverage(surf, bounds, &cov, stroke.brush.opacity, sel, lock, &paint, mode)) - })?; - let mut r = clone_result(dmg, off, aligned, p, &stroke); - if from_live { - r["fromLive"] = json!(true); - } - Ok(r) -} - -/// What a live retouching stroke paints through its coverage. -enum LivePaint { - /// The clone source (Clone Stamp; the Healing Brush shows its texture while drawing and - /// blends it on release). - Clone { which: SampleLayers, map: crate::presets::clone_source::Mapping, cmd: &'static str }, - /// The History Brush's history state. - History(Surface), - /// The Pattern Stamp's pattern, tiled from its aligned placement (Impressionist strokes are - /// laid dab by dab: `pattern_stamp::live_impressionist`). - Pattern { tile: std::sync::Arc, place: photocraft_compose::pattern::Placement }, -} - -/// A retouching stroke shown while it is drawn: the dabs so far composited onto a copy of the -/// active document as the command with the same params commits them (the same coverage, -/// sampling and blend): Clone Stamp, History Brush, and the Healing Brush's texture. -pub struct LiveRetouch { - /// The active document with the stroke so far. - pub doc: std::sync::Arc, - cmd: String, - renderer: photocraft_paint::StrokeRenderer, - pre: std::sync::Arc, - pre_surf: Surface, - id: Option, - params: Value, - paint: LivePaint, - mode: BlendMode, - opacity: f32, - sel: Option, - lock: bool, - /// Where the doc shows what finishing the stroke now would add (a lone first dab, the - /// smoothing catch-up), redrawn on every step as the Brush's live stroke does. - tail: Rect, - /// The document and revision the stroke started on. - base: (photocraft_doc::DocId, u64), - brush: Box, - /// Every point rendered so far, in order. - points: Vec, -} - -impl LiveRetouch { - /// Start a live stroke of `cmd` (`paint.cloneStamp`, `paint.healingBrush`, - /// `paint.historyBrush` or an aligned, non-Impressionist `paint.patternStamp`) from its - /// params; their `points` are rendered. - pub fn begin(s: &Session, cmd: &str, p: &Value) -> Result { - has_pixel_layer(s).map_err(EngineError::Other)?; - if cmd == "paint.patternStamp" { - let st = pattern_stamp::Setup::parse(s, p)?; - if st.impressionist { - return Err(bad(cmd, "Impressionist strokes are laid dab by dab (pattern_stamp::live_impressionist)")); - } - let paint = LivePaint::Pattern { place: st.placement(), tile: st.tile }; - return Self::with_paint(s, cmd, p, st.stroke, st.id, paint, st.mode); - } - let (stroke, id) = parse_brush(s, p, cmd)?; - let mode = blend_param(p, cmd)?; - let paint = match cmd { - "paint.cloneStamp" | "paint.healingBrush" => { - let f = *stroke.points.first().ok_or_else(|| bad(cmd, "`points` is empty"))?; - LivePaint::Clone { - which: sample_layers(p, cmd)?, - map: crate::presets::clone_source::resolve(s, p, (f.x, f.y), cmd)?.0, - cmd: if cmd == "paint.healingBrush" { "paint.healingBrush" } else { "paint.cloneStamp" }, - } - } - "paint.historyBrush" => LivePaint::History(history_source(s, id, p, cmd)?), - other => return Err(bad(other, "live retouching strokes are the Clone Stamp, Healing Brush, History Brush and Pattern Stamp")), - }; - Self::with_paint(s, cmd, p, stroke, id, paint, mode) - } - - /// Start a live stroke of `cmd` painting `paint` through `stroke`'s coverage. - fn with_paint(s: &Session, cmd: &str, p: &Value, stroke: Stroke, id: Option, paint: LivePaint, mode: BlendMode) -> Result { - let st = s.active().ok_or(EngineError::NoDocument)?; - let (pre, base) = (st.doc.clone(), (st.doc.id, st.revision)); - let mut doc = (*pre).clone(); - let sel = doc.selection.clone(); - let (surf, lock) = crate::channel_cmds::target_surface(&mut doc, id, p)?; - let pre_surf = surf.clone(); - // As `stroke_coverage`, which the commit uses. - let renderer = photocraft_paint::StrokeRenderer::new(&stroke.brush, None, 1.0); - let opacity = stroke.brush.opacity; - let brush = Box::new(stroke.brush.clone()); - let paint = match paint { - LivePaint::History(src) if src.format() != pre_surf.format() => LivePaint::History(src.convert(pre_surf.format())), - other => other, - }; - let mut live = Self { - doc: std::sync::Arc::new(doc), - cmd: cmd.into(), - renderer, - pre, - pre_surf, - id, - params: p.clone(), - paint, - mode, - opacity, - sel, - lock, - tail: Rect::EMPTY, - base, - brush, - points: Vec::new(), - }; - live.push(&stroke.points)?; - Ok(live) - } - - /// Everything the stroke has touched so far. - pub fn bounds(&self) -> Rect { - let bounds = self.renderer.bounds().union(&self.tail); - if self.cmd == "paint.cloneStamp" && flag(&self.params, "wrap", false) { - periodic::project(bounds, self.pre.bounds()).into_iter().fold(Rect::EMPTY, |a, b| a.union(&b)) - } else { - bounds - } - } - - /// Every point rendered so far, in order. - pub fn points(&self) -> &[StrokePoint] { - &self.points - } - - /// The finished stroke as its commit would take it over ([`Session::offer_live_retouch`]). - /// Only the Clone Stamp and History Brush draw what they commit (the Healing Brush blends on - /// release), and only while the brush, layer and clone source are still the ones the stroke - /// started with: the document revision doesn't cover those. - pub(crate) fn into_commit(mut self, s: &Session) -> Result { - let (stroke, id) = parse_brush(s, &self.params, &self.cmd)?; - let source_unchanged = match &self.paint { - LivePaint::Clone { map, .. } if self.cmd == "paint.cloneStamp" => { - let f = stroke.points.first().ok_or_else(|| bad(&self.cmd, "`points` is empty"))?; - crate::presets::clone_source::resolve(s, &self.params, (f.x, f.y), &self.cmd)?.0 == *map - } - LivePaint::History(_) if self.cmd == "paint.historyBrush" => true, - _ => return Err(bad(&self.cmd, "only Clone Stamp and History Brush strokes commit their live pixels")), - }; - if !source_unchanged || *self.brush != stroke.brush || id != self.id { - return Err(bad(&self.cmd, "the brush, layer or clone source changed during the stroke")); - } - let bounds = self.bounds(); - let (surf, _) = crate::channel_cmds::target_surface(std::sync::Arc::make_mut(&mut self.doc), self.id, &self.params)?; - let surface = surf.clone(); - Ok(crate::brush_cmds::LiveCommit { mixer: None, cmd: self.cmd, base: self.base, params: self.params, seed: None, points: self.points, surface, bounds }) - } - - /// Render more points; returns the rectangle that changed. Each changed area is redrawn from - /// the pre-stroke pixels with the stroke's coverage so far, so overlapping dabs build up as in - /// the commit, and pixels painted earlier in the stroke are never re-cloned. What finishing - /// the stroke now would add is drawn too (a lone first dab shows on the press), and redrawn on - /// every step. - /// Invalid coordinates reject the whole batch without changing the preview. - /// Only the position and pressure of `pts` are used: the commands take no tilt or times. - pub fn push(&mut self, pts: &[StrokePoint]) -> Result { - crate::brush_cmds::check_coords(pts, &self.cmd)?; - let pts: Vec<_> = pts.iter().map(|q| StrokePoint::new(q.x, q.y, q.pressure)).collect(); - self.points.extend_from_slice(&pts); - self.renderer.push(&pts); - if self.cmd == "paint.cloneStamp" && flag(&self.params, "wrap", false) { - return self.push_periodic(); - } - let old = std::mem::replace(&mut self.tail, Rect::EMPTY); - let mut dmg = Rect::EMPTY; - if !old.is_empty() { - // Back to the stroke without the previous tail. - let (surf, _) = crate::channel_cmds::target_surface(std::sync::Arc::make_mut(&mut self.doc), self.id, &self.params)?; - surf.write_region(old, &self.pre_surf.read_region(old)); - self.renderer.mark_dirty(old); - dmg = old; - } - let r = self.renderer.take_dirty_rect(); - let cov = self.renderer.coverage_in(r); - dmg = dmg.union(&self.composite(r, &cov)?); - if let Some(mut tail) = self.renderer.tail_preview() { - let r = tail.take_dirty_rect(); - let cov = tail.coverage_in(r); - self.tail = self.composite(r, &cov)?; - dmg = dmg.union(&self.tail); - } - Ok(dmg) - } - - fn push_periodic(&mut self) -> Result { - let mut dirty = self.renderer.take_dirty_rect().union(&self.tail); - let mut tail = self.renderer.tail_preview(); - self.tail = tail.as_mut().map_or(Rect::EMPTY, |t| t.take_dirty_rect()); - dirty = dirty.union(&self.tail); - let LivePaint::Clone { which, map, cmd } = &self.paint else { - return Err(bad(&self.cmd, "periodic painting requires a clone source")); - }; - let (surf, _) = crate::channel_cmds::target_surface(std::sync::Arc::make_mut(&mut self.doc), self.id, &self.params)?; - periodic::Composite { - target: surf, - before: &self.pre_surf, - tile: self.pre.bounds(), - opacity: self.opacity, - selection: self.sel.as_ref(), - lock: self.lock, - mode: self.mode, - } - .draw(dirty, &self.brush, &self.points, |r| clone_sample(&self.pre, self.id, &self.pre_surf, *which, r, map, true, cmd)) - } - - /// Redraw `r` from the pre-stroke pixels with the clone source through coverage `cov`. - fn composite(&mut self, r: Rect, cov: &[f32]) -> Result { - if r.is_empty() { - return Ok(r); - } - let paint = match &self.paint { - LivePaint::Clone { which, map, cmd } => { - clone_sample(&self.pre, self.id, &self.pre_surf, *which, r, map, *cmd == "paint.cloneStamp" && flag(&self.params, "wrap", false), cmd)? - } - LivePaint::History(src) => Region::read(src, r), - LivePaint::Pattern { tile, place } => pattern_stamp::paint_region(tile, place, &self.pre_surf.format(), r), - }; - let (surf, _) = crate::channel_cmds::target_surface(std::sync::Arc::make_mut(&mut self.doc), self.id, &self.params)?; - surf.write_region(r, &self.pre_surf.read_region(r)); - Ok(apply_coverage(surf, r, cov, self.opacity, self.sel.as_ref(), self.lock, &paint, self.mode).union(&r)) - } -} - -/// Grow a stroke's coverage map by `m` pixels of zero coverage (a Dirichlet boundary for the solve). -fn pad_coverage(bounds: Rect, cov: &[f32], m: i32) -> (Rect, Vec) { - let g = bounds.inflate(m); - let (w, gw) = (bounds.width() as usize, g.width() as usize); - let mut out = vec![0.0f32; gw * g.height() as usize]; - for (i, c) in cov.iter().enumerate() { - let (x, y) = (i % w + m as usize, i / w + m as usize); - out[y * gw + x] = *c; - } - (g, out) -} - -/// Seamless-clone `src` into `dst` over the mask (both regions cover the same rect). The solve runs -/// only on the mask's bounding box plus a one-pixel Dirichlet ring; the rest is `dst`. -fn heal_region(fmt: &PixelFormat, src: &Region, dst: &Region, mask: &[bool]) -> Region { - let w = dst.width(); - let bbox = mask.iter().enumerate().filter(|(_, m)| **m).fold(Rect::EMPTY, |r, (i, _)| { - let (x, y) = (dst.rect.x0 + (i % w) as i32, dst.rect.y0 + (i / w) as i32); - r.union(&Rect::new(x, y, x + 1, y + 1)) - }); - let mut out = dst.clone(); - if bbox.is_empty() { - return out; - } - let r = bbox.inflate(1).intersect(&dst.rect); - let (s, d) = (src.crop(r), dst.crop(r)); - let m: Vec = (r.y0..r.y1).flat_map(|y| (r.x0..r.x1).map(move |x| (x, y))).map(|(x, y)| mask[dst.index(x, y)]).collect(); - let mut data = poisson::seamless_clone(d.width(), d.height(), d.ch, &s.data, &d.data, &m); - clamp_samples(fmt, &mut data); - let (n, rw) = (dst.ch, r.width() as usize); - for y in r.y0..r.y1 { - let o = out.index(r.x0, y) * n; - let i = (y - r.y0) as usize * rw * n; - out.data[o..o + rw * n].copy_from_slice(&data[i..i + rw * n]); - } - out -} - -fn healing_brush(s: &mut Session, p: &Value) -> Result { - const CMD: &str = "paint.healingBrush"; - let (stroke, id) = parse_brush(s, p, CMD)?; - reject_huge_stroke(CMD, &stroke)?; - let which = sample_layers(p, CMD)?; - let mode = blend_param(p, CMD)?; - let aligned = flag(p, "aligned", true); - let map = clone_mapping(s, p, &stroke, CMD)?; - let off = map.offset(); - let dmg = run_stroke(s, "Healing Brush", id, p, |pre, surf, sel, lock| { - let (bounds, cov) = coverage(CMD, &stroke)?; - let (g, cov) = pad_coverage(bounds, &cov, 2); - let fmt = surf.format(); - let src = clone_sample(pre, id, surf, which, g, &map, false, CMD)?; - // The destination the texture is fitted to: the layer itself, or what the user sees when - // sampling several layers (so healing onto an empty layer matches the composite). - let dst = if which == SampleLayers::Current { Region::read(surf, g) } else { composite_region(pre, id, which, g, fmt) }; - let mask: Vec = cov.iter().map(|c| *c > 0.0).collect(); - let healed = heal_region(&fmt, &src, &dst, &mask); - Ok(apply_coverage(surf, g, &cov, stroke.brush.opacity, sel, lock, &healed, mode)) - })?; - Ok(clone_result(dmg, off, aligned, p, &stroke)) -} - -/// The History Brush's source: the targeted surface (pixels, mask, channel) as it was in History -/// panel row `state` or snapshot `snapshot` (default: the source set in the History panel, -/// `history.setSource`, else the oldest state still held, the "Open" state unless trimmed). -fn history_source(s: &Session, id: Option, p: &Value, cmd: &str) -> Result { - let st = s.active().ok_or(EngineError::NoDocument)?; - let source_doc = crate::history_source_cmds::paint_source(st, p, cmd)?; - crate::channel_cmds::read_target_surface(source_doc.as_ref(), id, p) - .cloned() - .map_err(|_| EngineError::Other("the target did not exist (as pixels, a mask or a channel) in that history state".into())) -} - -fn history_brush(s: &mut Session, p: &Value) -> Result { - const CMD: &str = "paint.historyBrush"; - let (stroke, id) = parse_brush(s, p, CMD)?; - let mode = blend_param(p, CMD)?; - // The coverage and the source region below are both dense over the stroke's bounds, so a - // thin stroke across a large canvas would still ask for the whole box. Refuse it from the - // points and brush size, before the source surface is cloned or anything is rendered (#4961). - reject_huge_stroke(CMD, &stroke)?; - let live = s.live_commit.take().filter(|l| l.matches(s, CMD, p, &stroke.points)); - let from_live = live.is_some(); - let src_surface = history_source(s, id, p, CMD)?; - let dmg = run_stroke(s, "History Brush", id, p, |_, surf, sel, lock| { - if let Some(l) = live { - *surf = l.surface; - return Ok(l.bounds); - } - let fmt = surf.format(); - let src = if src_surface.format() == fmt { src_surface } else { src_surface.convert(fmt) }; - let (bounds, cov) = coverage(CMD, &stroke)?; - let paint = Region::read(&src, bounds); - Ok(apply_coverage(surf, bounds, &cov, stroke.brush.opacity, sel, lock, &paint, mode)) - })?; - let mut r = json!({ "damage": damage_json(dmg) }); - if from_live { - r["fromLive"] = json!(true); - } - Ok(r) -} - -// --------------------------------------------------------------------------------------------- -// Spot Healing -// --------------------------------------------------------------------------------------------- - -/// Dilate a mask by `r` pixels (square structuring element). -fn dilate(w: usize, h: usize, m: &[bool], r: usize) -> Vec { - let mut tmp = vec![false; w * h]; - for y in 0..h { - for x in 0..w { - if m[y * w + x] { - for xx in x.saturating_sub(r)..(x + r + 1).min(w) { - tmp[y * w + xx] = true; - } - } - } - } - let mut out = vec![false; w * h]; - for y in 0..h { - for x in 0..w { - if tmp[y * w + x] { - for yy in y.saturating_sub(r)..(y + r + 1).min(h) { - out[yy * w + x] = true; - } - } - } - } - out -} - -/// Copy a translated Proximity Match patch from the *pre-healing* pixels. Reading -/// `out` here would make overlapping offsets repeatedly copy the pixels just written, -/// leaving streaks instead of the selected source texture. -fn proximity_source_patch(img: &[f32], w: usize, h: usize, ch: usize, mask: &[bool], dx: i32, dy: i32) -> Option> { - if w == 0 || h == 0 || ch == 0 || mask.len() != w.checked_mul(h)? || img.len() != mask.len().checked_mul(ch)? { - return None; - } - let mut out = img.to_vec(); - for (p, masked) in mask.iter().enumerate() { - if !masked { - continue; - } - let x = i32::try_from(p % w).ok()?.checked_add(dx)?; - let y = i32::try_from(p / w).ok()?.checked_add(dy)?; - if x < 0 || y < 0 || x >= i32::try_from(w).ok()? || y >= i32::try_from(h).ok()? { - return None; - } - let src = (usize::try_from(y).ok()?.checked_mul(w)? + usize::try_from(x).ok()?).checked_mul(ch)?; - let dst = p.checked_mul(ch)?; - out.get_mut(dst..dst + ch)?.copy_from_slice(img.get(src..src + ch)?); - } - Some(out) -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum SpotType { - ContentAware, - CreateTexture, - ProximityMatch, -} - -/// Fill the stroke area with no source, then gradient-domain blend it into its surroundings. With -/// `all` (Sample All Layers) it heals what is visible, so it works on an empty layer above the image. -/// -/// Photoshop 25.4 (measured): a dab changes exactly the brush's footprint, and Content-Aware takes -/// its texture from around it, as Edit › Fill does from its window -/// ([`crate::fill_cmds::sampling_window`] of the stroke's bounds), which is what this samples. -fn spot_heal_surface(surf: &mut Surface, pre: &Document, stroke: &Stroke, kind: SpotType, all: bool, sel: Option<&Surface>, lock: bool) -> Result { - let (bounds, cov) = coverage("paint.spotHealing", stroke)?; - let size = stroke.brush.size; - let region_rect = crate::fill_cmds::sampling_window(bounds, pre.bounds()); - if region_rect.is_empty() { - return Ok(Rect::EMPTY); - } - // Proximity Match looks for its source anywhere in that window. - let margin = (region_rect.width().max(region_rect.height()) / 2) as i32; - let fmt = surf.format(); - let img = if all { composite_region(pre, None, SampleLayers::All, region_rect, fmt) } else { Region::read(surf, region_rect) }; - let (w, h, ch) = (img.width(), img.height(), img.ch); - let bw = bounds.width() as usize; - let mut stroke_cov = vec![0.0f32; w * h]; - for (i, c) in cov.iter().enumerate() { - let (x, y) = (bounds.x0 + (i % bw) as i32, bounds.y0 + (i / bw) as i32); - if region_rect.contains(x, y) { - stroke_cov[img.index(x, y)] = *c; - } - } - let hole: Vec = stroke_cov.iter().map(|c| *c > 0.0).collect(); - if !hole.iter().any(|h| *h) { - return Ok(Rect::EMPTY); - } - // Synthesise over a slightly larger domain than the Poisson region, so the solve's boundary pixels - // carry synthesised values that differ from the untouched surroundings: that mismatch is what the - // membrane corrects (otherwise the Dirichlet data would be all zero and the blend a no-op). - let domain = dilate(w, h, &hole, 2); - let heal_mask = dilate(w, h, &hole, 1); - let content_aware = - |img: &[f32]| inpaint::complete(w, h, ch, img, &domain, &CompleteParams::default()).unwrap_or_else(|| poisson::membrane_fill(w, h, ch, img, &domain)); - let filled = match kind { - SpotType::ContentAware => content_aware(&img.data), - SpotType::CreateTexture => inpaint::synthesize(w, h, ch, &img.data, &domain, (size / 4.0).clamp(6.0, 32.0) as usize, 0x5eed), - SpotType::ProximityMatch => { - let ring = (size / 8.0).clamp(3.0, 16.0) as usize; - match inpaint::best_offset(w, h, ch, &img.data, &domain, ring, margin) { - Some((dx, dy)) => proximity_source_patch(&img.data, w, h, ch, &domain, dx, dy).unwrap_or_else(|| content_aware(&img.data)), - None => content_aware(&img.data), - } - } - }; - let src = Region { rect: region_rect, ch, data: filled }; - let healed = heal_region(&fmt, &src, &img, &heal_mask); - let dmg = bounds.intersect(®ion_rect); - let dmg_cov: Vec = (dmg.y0..dmg.y1).flat_map(|y| (dmg.x0..dmg.x1).map(move |x| (x, y))).map(|(x, y)| stroke_cov[img.index(x, y)]).collect(); - Ok(apply_coverage(surf, dmg, &dmg_cov, stroke.brush.opacity, sel, lock, &healed, BlendMode::Normal)) -} - -fn spot_healing(s: &mut Session, p: &Value) -> Result { - const CMD: &str = "paint.spotHealing"; - let (stroke, id) = parse_brush(s, p, CMD)?; - reject_huge_stroke(CMD, &stroke)?; - let kind = match string(p, "type", "contentAware") { - "contentAware" => SpotType::ContentAware, - "createTexture" => SpotType::CreateTexture, - "proximityMatch" => SpotType::ProximityMatch, - o => return Err(bad(CMD, format!("unknown type `{o}` (contentAware|createTexture|proximityMatch)"))), - }; - let all = sample_all_layers(p); - let dmg = run_stroke(s, "Spot Healing Brush", id, p, |pre, surf, sel, lock| spot_heal_surface(surf, pre, &stroke, kind, all, sel, lock))?; - Ok(json!({ "damage": damage_json(dmg) })) -} - -// --------------------------------------------------------------------------------------------- -// Toning (Dodge / Burn / Sponge) and focus (Blur / Sharpen), Smudge -// --------------------------------------------------------------------------------------------- - -/// Per-dab strength such that one pass over a point totals roughly `e`, whatever the spacing -/// (about `1/spacing` dabs overlap each point on the stroke's centre line). -#[inline] -fn per_dab(e: f32, spacing: f32) -> f32 { - 1.0 - (1.0 - e.clamp(0.0, 1.0)).powf(spacing.clamp(0.01, 1.0)) -} - -/// Apply an RGB colour transform `f(rgb, strength)` to each covered pixel of a dab (through straight -/// RGBA, so it works for Gray/CMYK/Lab too; untouched pixels are never round-tripped). -fn color_dab(fmt: &PixelFormat, work: &mut Region, fp: &Footprint, strength: f32, spacing: f32, f: impl Fn([f32; 3], f32) -> [f32; 3]) { - let r = fp.rect.intersect(&work.rect); - let n = fmt.channels(); - let mut enc = [0.0f32; 8]; - for y in r.y0..r.y1 { - for x in r.x0..r.x1 { - let k = per_dab(fp.at(x, y) * strength, spacing); - if k <= 0.0 { - continue; - } - let px = work.px_mut(x, y); - let rgba = to_rgba(fmt, px); - let o = f([rgba[0], rgba[1], rgba[2]], k); - from_rgba_into(fmt, [o[0], o[1], o[2], rgba[3]], &mut enc); - let a = alpha_index(fmt); - for c in 0..n { - if Some(c) != a { - px[c] = enc[c]; - } - } - } - } -} - -/// Dodge and Burn: a stroke tones each pixel once, from its original colour, mixed in by the -/// stroke's coverage there (`toned` is the full-exposure colour). Dabs build up coverage as in a -/// brush stroke, capped at full coverage, so Exposure caps a stroke the way Opacity caps a paint -/// stroke: overlapping dabs and passes within one stroke don't compound the tone curve, and a -/// new stroke builds on the last. -fn tone_stroke(fmt: PixelFormat, toned: impl Fn([f32; 3]) -> [f32; 3] + 'static) -> DabEffect { - /// Side of the cells that remember, per touched pixel, the coverage applied so far and the - /// original pixel (copied from the working pixels the first time a dab reaches it). Dense - /// cells rather than a map per pixel: a map lookup per covered pixel made long strokes with - /// large brushes over ten times slower. - const CELL: i32 = 64; - struct Cell { - cov: Vec, - orig: Vec, - } - let mut cells: std::collections::HashMap<(i32, i32), Cell> = std::collections::HashMap::new(); - let a = alpha_index(&fmt); - let n = fmt.channels(); - Box::new(move |work, fp| { - let r = fp.rect.intersect(&work.rect); - if r.is_empty() { - return; - } - let mut enc = [0.0f32; 8]; - for cy in r.y0.div_euclid(CELL)..=(r.y1 - 1).div_euclid(CELL) { - for cx in r.x0.div_euclid(CELL)..=(r.x1 - 1).div_euclid(CELL) { - let cr = Rect::new(cx * CELL, cy * CELL, cx * CELL + CELL, cy * CELL + CELL); - let part = r.intersect(&cr); - if part.is_empty() { - continue; - } - let len = (CELL * CELL) as usize; - // Coverage -1: not touched yet, so `orig` isn't filled in for that pixel. - let cell = cells.entry((cx, cy)).or_insert_with(|| Cell { cov: vec![-1.0; len], orig: vec![0.0; len * n] }); - for y in part.y0..part.y1 { - for x in part.x0..part.x1 { - let k = fp.at(x, y).clamp(0.0, 1.0); - if k <= 0.0 { - continue; - } - let i = ((y - cr.y0) * CELL + (x - cr.x0)) as usize; - let (Some(prev), Some(src)) = (cell.cov.get_mut(i), cell.orig.get_mut(i * n..i * n + n)) else { continue }; - if *prev < 0.0 { - // First touch: the working pixel is still the original. - src.copy_from_slice(work.px(x, y)); - *prev = 0.0; - } - // Dabs build up the stroke's coverage as a brush stroke's do (flow), up - // to full coverage; the tone is applied once, from the original. - let k = *prev + k * (1.0 - *prev); - if k <= *prev { - continue; - } - *prev = k; - let o = to_rgba(&fmt, src); - let t = toned([o[0], o[1], o[2]]); - let m = [o[0] + (t[0] - o[0]) * k, o[1] + (t[1] - o[1]) * k, o[2] + (t[2] - o[2]) * k]; - from_rgba_into(&fmt, [m[0], m[1], m[2], o[3]], &mut enc); - let px = work.px_mut(x, y); - for c in 0..n { - if Some(c) != a { - px[c] = enc[c]; - } - } - } - } - } - } - }) -} - -fn tone_range(p: &Value, cmd: &str) -> Result { - match string(p, "range", "midtones") { - "shadows" => Ok(ToneRange::Shadows), - "midtones" => Ok(ToneRange::Midtones), - "highlights" => Ok(ToneRange::Highlights), - o => Err(bad(cmd, format!("unknown range `{o}` (shadows|midtones|highlights)"))), - } -} - -/// A sequential-dab tool's settings (Dodge, Burn, Sponge, Blur, Sharpen, Smudge), parsed once and -/// turned into its per-dab effect, for the commit and the live preview alike. -#[derive(Clone, Debug, PartialEq)] -enum DabTool { - Tone { burn: bool, range: ToneRange, exposure: f32, protect: bool }, - Sponge { saturate: bool, vibrance: bool }, - Focus { sharpen: bool, strength: f32, protect: bool, sigma: f32 }, - Smudge { strength: f32, finger: Option<[f32; 4]>, max_size: f32 }, -} - -/// One dab's edit of the working copy. -pub(crate) type DabEffect = Box; - -/// Pixels an effect reads beyond the dab it writes. Smudge's pickup is a fixed-size square, -/// independent of pressure, roundness and the dab's current angle. -#[derive(Clone, Copy)] -enum DabNeighborhood { - Halo(i32), - Smudge(i32), -} - -impl DabNeighborhood { - fn halo(self) -> i32 { - match self { - Self::Halo(radius) | Self::Smudge(radius) => radius, - } - } - - fn read_rect(self, rect: Rect, dab: &photocraft_paint::Dab) -> Rect { - match self { - Self::Halo(radius) => rect.inflate(radius), - Self::Smudge(radius) => { - let (x, y) = (dab.center.x.floor() as i32, dab.center.y.floor() as i32); - rect.union(&Rect::new( - x.saturating_sub(radius), - y.saturating_sub(radius), - x.saturating_add(radius).saturating_add(1), - y.saturating_add(radius).saturating_add(1), - )) - } - } - } -} - -impl DabTool { - /// The tool for `cmd` and its history label. - fn parse(s: &Session, cmd: &str, p: &Value, stroke: &Stroke) -> Result<(Self, &'static str)> { - Ok(match cmd { - "paint.dodge" | "paint.burn" => { - let burn = cmd == "paint.burn"; - let tool = Self::Tone { - burn, - range: tone_range(p, cmd)?, - exposure: num(p, "exposure", 50.0).clamp(1.0, 100.0) / 100.0, - protect: flag(p, "protectTones", true), - }; - (tool, if burn { "Burn Tool" } else { "Dodge Tool" }) - } - "paint.sponge" => { - let saturate = match string(p, "mode", "desaturate") { - "desaturate" => false, - "saturate" => true, - o => return Err(bad(cmd, format!("unknown mode `{o}` (desaturate|saturate)"))), - }; - (Self::Sponge { saturate, vibrance: flag(p, "vibrance", true) }, "Sponge Tool") - } - "paint.blur" | "paint.sharpen" => { - let sharpen = cmd == "paint.sharpen"; - let tool = Self::Focus { - sharpen, - strength: num(p, "strength", 50.0).clamp(1.0, 100.0) / 100.0, - protect: flag(p, "protectDetail", true), - sigma: (stroke.brush.size * 0.03).clamp(1.0, 4.0), - }; - (tool, if sharpen { "Sharpen Tool" } else { "Blur Tool" }) - } - "paint.smudge" => { - let finger = flag(p, "fingerPainting", false).then_some(s.tools.foreground); - (Self::Smudge { strength: num(p, "strength", 50.0).clamp(1.0, 100.0) / 100.0, finger, max_size: stroke.brush.size }, "Smudge Tool") - } - o => return Err(bad(o, "not a sequential-dab tool")), - }) - } - - /// How far around each dab the effect reads (Blur and Sharpen read a neighbourhood). - fn neighborhood(&self) -> DabNeighborhood { - match self { - Self::Focus { sigma, .. } => DabNeighborhood::Halo((sigma * 3.0).ceil() as i32 + 1), - Self::Smudge { max_size, .. } => DabNeighborhood::Smudge(Smudge::sampling_radius(*max_size)), - _ => DabNeighborhood::Halo(0), - } - } - - /// The per-dab effect on a working copy in `fmt`, for a brush of `spacing`. - fn effect(&self, fmt: PixelFormat, spacing: f32) -> DabEffect { - let sp = spacing; - match self.clone() { - Self::Tone { burn, range, exposure, protect } => tone_stroke(fmt, move |c| dodge_burn(c, exposure, range, burn, protect)), - // Flow is already in each dab's coverage; a full-flow pass moves colours half-way. - Self::Sponge { saturate, vibrance } => Box::new(move |work, fp| color_dab(&fmt, work, fp, 0.5, sp, |c, k| sponge(c, k, saturate, vibrance))), - Self::Focus { sharpen, strength, protect, sigma } => { - let a = alpha_index(&fmt); - Box::new(move |work, fp| { - let r = fp.rect.intersect(&work.rect); - if r.is_empty() { - return; - } - let (w, h, n) = (work.width(), work.height(), work.ch); - let win = ((r.x0 - work.rect.x0) as usize, (r.y0 - work.rect.y0) as usize, (r.x1 - work.rect.x0) as usize, (r.y1 - work.rect.y0) as usize); - let out = if sharpen { local_sharpen(&work.data, w, h, n, a, win, 1.0, protect) } else { local_blur(&work.data, w, h, n, a, win, sigma) }; - let rw = r.width() as usize; - // Row-parallel, like the blur itself (#5426). - let (wx0, wy0) = (work.rect.x0, work.rect.y0); - work.data.par_chunks_mut(w * n).enumerate().for_each(|(row, line)| { - let y = wy0 + row as i32; - if y < r.y0 || y >= r.y1 { - return; - } - for x in r.x0..r.x1 { - let k = per_dab(fp.at(x, y) * strength, sp); - if k <= 0.0 { - continue; - } - let o = ((y - r.y0) as usize * rw + (x - r.x0) as usize) * n; - let i = (x - wx0) as usize * n; - let px = &mut line[i..i + n]; - for c in 0..n { - px[c] += (out[o + c] - px[c]) * k; - } - } - }); - }) - } - Self::Smudge { strength, finger, max_size } => { - let finger_px = finger.map(|fg| photocraft_raster::from_rgba(&fmt, fg)); - // Premultiplied mixing: transparent pixels carry no colour, so no dark fringes. - let mut sm = Smudge::new(strength, finger_px, max_size).with_alpha(alpha_index(&fmt)); - Box::new(move |work, fp| sm.dab(work, fp)) - } - } - } -} - -/// Dodge, Burn, Sponge, Blur, Sharpen and Smudge: each dab edits a working copy in order -/// (`apply_dab_stroke`). Blur, Sharpen and Smudge can sample all layers. -fn dab_cmd(s: &mut Session, p: &Value, cmd: &str) -> Result { - let (stroke, id) = parse_brush(s, p, cmd)?; - let (tool, label) = DabTool::parse(s, cmd, p, &stroke)?; - let all = matches!(tool, DabTool::Focus { .. } | DabTool::Smudge { .. }) && sample_all_layers(p); - // The live stroke the canvas already drew for exactly this commit (`LiveDab::into_commit`): - // take its pixels instead of running every dab again (the hitch on release). - let live = s.live_commit.take().filter(|l| l.matches(s, cmd, p, &stroke.points)); - let from_live = live.is_some(); - let dmg = run_stroke(s, label, id, p, |pre, surf, sel, lock| { - if let Some(l) = live { - *surf = l.surface; - return Ok(l.bounds); - } - let fmt = surf.format(); - let mut effect = tool.effect(fmt, stroke.brush.spacing); - let mut sampler = all.then(|| AllLayers::new(pre, fmt)); - Ok(apply_dab_stroke(surf, &stroke, sel, lock, tool.neighborhood().halo(), |work, fp| match &mut sampler { - Some(all) => all.dab(work, fp, |w, f| effect(w, f)), - None => effect(work, fp), - })) - })?; - let mut r = json!({ "damage": damage_json(dmg) }); - if from_live { - r["fromLive"] = json!(true); - } - Ok(r) -} - -/// Side of the tiles a live sequential-dab stroke keeps its working pixels in ([`WorkTiles`]). -const WORK_TILE: i32 = 128; - -/// The working copy of a live sequential-dab stroke: the target's native channels as `f32`, in -/// tiles copied from the pre-stroke surface the first time a dab writes to them. Unlike a -/// `Surface`, it isn't rounded to the document's depth between dabs, so each dab sees what the -/// commit's working copy (`apply_dab_stroke`) holds and the preview is the commit's pixels. -struct WorkTiles { - ch: usize, - tiles: std::collections::HashMap<(i32, i32), Vec>, -} - -impl WorkTiles { - fn new(ch: usize) -> Self { - Self { ch, tiles: std::collections::HashMap::new() } - } - - fn tile_rect((tx, ty): (i32, i32)) -> Rect { - Rect::new(tx * WORK_TILE, ty * WORK_TILE, tx * WORK_TILE + WORK_TILE, ty * WORK_TILE + WORK_TILE) - } - - /// The tiles `r` overlaps. - fn coords(r: Rect) -> impl Iterator { - let (x0, x1) = (r.x0.div_euclid(WORK_TILE), (r.x1 - 1).div_euclid(WORK_TILE)); - let (y0, y1) = (r.y0.div_euclid(WORK_TILE), (r.y1 - 1).div_euclid(WORK_TILE)); - let empty = r.is_empty(); - (y0..=y1).filter(move |_| !empty).flat_map(move |ty| (x0..=x1).map(move |tx| (tx, ty))) - } - - /// The working pixels of `r`: the pre-stroke pixels `pre` where no dab has written yet. - fn read(&self, pre: &Surface, r: Rect) -> Region { - let mut out = Region::new(r, self.ch); - let n = self.ch; - let mut buf = Vec::new(); - for c in Self::coords(r) { - let tr = Self::tile_rect(c); - let part = r.intersect(&tr); - let w = part.width() as usize * n; - let tile = self.tiles.get(&c); - if tile.is_none() { - pre.read_region_into(part, &mut buf); - } - for y in part.y0..part.y1 { - let src = match tile { - Some(t) => t.get(((y - tr.y0) * WORK_TILE + (part.x0 - tr.x0)) as usize * n..).and_then(|s| s.get(..w)), - None => buf.get((y - part.y0) as usize * w..).and_then(|s| s.get(..w)), - }; - let dst = out.index(part.x0, y) * n; - if let (Some(s), Some(d)) = (src, out.data.get_mut(dst..dst + w)) { - d.copy_from_slice(s); - } - } - } - out - } - - /// Store `region` as the working pixels of its rectangle. - fn write(&mut self, pre: &Surface, region: &Region) { - let (r, n) = (region.rect, self.ch); - for c in Self::coords(r) { - let tr = Self::tile_rect(c); - let tile = self.tiles.entry(c).or_insert_with(|| pre.read_region(tr)); - let part = r.intersect(&tr); - let w = part.width() as usize * n; - for y in part.y0..part.y1 { - let dst = ((y - tr.y0) * WORK_TILE + (part.x0 - tr.x0)) as usize * n; - let src = region.index(part.x0, y) * n; - if let (Some(s), Some(d)) = (region.data.get(src..src + w), tile.get_mut(dst..dst + w)) { - d.copy_from_slice(s); - } - } - } - } -} - -/// A Dodge, Burn, Sponge, Blur, Sharpen or Smudge stroke shown while it is drawn: each new dab -/// runs the tool's effect on a working copy of the target, in order, and the changed area is -/// mixed back over the original at the brush opacity, as `apply_dab_stroke` does on release. -/// The working copy keeps full precision ([`WorkTiles`]), so the pixels are the commit's, and the -/// commit takes them over ([`Session::offer_live_dab`]) instead of running every dab again. -/// Sample All Layers isn't previewed (its composite spans the whole stroke). -pub struct LiveDab { - /// The active document with the stroke so far. - pub doc: std::sync::Arc, - cmd: String, - renderer: photocraft_paint::StrokeRenderer, - done: usize, - effect: DabEffect, - neighborhood: DabNeighborhood, - pre_surf: Surface, - work: WorkTiles, - id: Option, - params: Value, - opacity: f32, - sel: Option, - lock: bool, - bounds: Rect, - /// Show the dabs finishing the stroke would add, so the preview at the last point is the - /// commit. Only for effects that a repeated dab doesn't change (Color Replacement): the - /// tail runs on a scratch copy at every push, so an effect that carries paint from dab to - /// dab (Smudge) would drift. - preview_tail: bool, - /// Where the shown tail is. - tail: Rect, - /// The tool and brush the stroke started with, which its commit must still have: the - /// document revision doesn't cover the session's brush or foreground colour. `None` for - /// strokes whose commit renders itself (Color Replacement). - tool: Option<(DabTool, Box)>, - /// The document and revision the stroke started on, for strokes started from the session's - /// active document ([`Self::with_effect`]); `None` for strokes on a prepared copy. - base: Option<(photocraft_doc::DocId, u64)>, - /// Every point rendered so far, in order. - points: Vec, -} - -impl LiveDab { - /// Start a live stroke of `cmd` from its params; their `points` are rendered. - pub fn begin(s: &Session, cmd: &str, p: &Value) -> Result { - has_pixel_layer(s).map_err(EngineError::Other)?; - if sample_all_layers(p) { - return Err(bad(cmd, "Sample All Layers strokes aren't previewed live")); - } - let (stroke, id) = parse_brush(s, p, cmd)?; - let (tool, _) = DabTool::parse(s, cmd, p, &stroke)?; - let (neighborhood, spacing, brush) = (tool.neighborhood(), stroke.brush.spacing, Box::new(stroke.brush.clone())); - let effect = tool.clone(); - let mut live = Self::with_neighborhood(s, cmd, p, stroke, id, neighborhood, |pre| effect.effect(pre.format(), spacing))?; - live.tool = Some((tool, brush)); - Ok(live) - } - - /// Start a live stroke of `cmd` that runs `effect` (made from the target before the stroke) - /// at each dab of `stroke`, reading `halo` pixels around it. `p` gives the target. - pub(crate) fn with_effect( - s: &Session, - cmd: &str, - p: &Value, - stroke: Stroke, - id: Option, - halo: i32, - effect: impl FnOnce(&Surface) -> DabEffect, - ) -> Result { - Self::with_neighborhood(s, cmd, p, stroke, id, DabNeighborhood::Halo(halo), effect) - } - - fn with_neighborhood( - s: &Session, - cmd: &str, - p: &Value, - stroke: Stroke, - id: Option, - neighborhood: DabNeighborhood, - effect: impl FnOnce(&Surface) -> DabEffect, - ) -> Result { - let st = s.active().ok_or(EngineError::NoDocument)?; - let base = (st.doc.id, st.revision); - let doc = (*st.doc).clone(); - let mut live = Self::with_neighborhood_on(doc, cmd, p, stroke, id, neighborhood, effect)?; - live.base = Some(base); - Ok(live) - } - - /// [`Self::with_effect`] on `doc`, a copy of the active document with what the commit's own - /// edit does first (the Background Eraser's Background turned into a normal layer, say). - pub(crate) fn with_effect_on( - doc: Document, - cmd: &str, - p: &Value, - stroke: Stroke, - id: Option, - halo: i32, - effect: impl FnOnce(&Surface) -> DabEffect, - ) -> Result { - Self::with_neighborhood_on(doc, cmd, p, stroke, id, DabNeighborhood::Halo(halo), effect) - } - - fn with_neighborhood_on( - mut doc: Document, - cmd: &str, - p: &Value, - stroke: Stroke, - id: Option, - neighborhood: DabNeighborhood, - effect: impl FnOnce(&Surface) -> DabEffect, - ) -> Result { - let sel = doc.selection.clone(); - let (surf, lock) = crate::channel_cmds::target_surface(&mut doc, id, p)?; - let pre_surf = surf.clone(); - let effect = effect(&pre_surf); - // `apply_dab_stroke` generates the same dabs (`dabs`: zoom 1, no smoothing scale). - let renderer = photocraft_paint::StrokeRenderer::new(&stroke.brush, None, 1.0).record_dabs(); - let mut live = Self { - doc: std::sync::Arc::new(doc), - cmd: cmd.into(), - renderer, - done: 0, - effect, - neighborhood, - work: WorkTiles::new(pre_surf.channels()), - pre_surf, - id, - params: p.clone(), - opacity: stroke.brush.opacity, - sel, - lock, - bounds: Rect::EMPTY, - preview_tail: false, - tail: Rect::EMPTY, - tool: None, - base: None, - points: Vec::new(), - }; - live.push(&stroke.points)?; - Ok(live) - } - - /// Also show the stroke's finishing dabs (see `preview_tail`). - pub(crate) fn with_tail_preview(mut self) -> Result { - self.preview_tail = true; - self.push(&[])?; - Ok(self) - } - - /// Everything the stroke has touched so far. - pub fn bounds(&self) -> Rect { - self.bounds - } - - /// Run the dabs the renderer has generated since the last call on the working copy; returns - /// the rectangle they changed. - fn run_new_dabs(&mut self) -> Rect { - let ctx = self.renderer.ctx.clone(); - let new: Vec<_> = self.renderer.dabs().get(self.done..).unwrap_or_default().to_vec(); - let mut dmg = Rect::EMPTY; - for (k, d) in new.iter().enumerate() { - let r = ctx.dab_rect(d, false); - if r.is_empty() { - continue; - } - let mut region = self.work.read(&self.pre_surf, self.neighborhood.read_rect(r, d)); - (self.effect)(&mut region, &ctx.footprint(d, self.done + k)); - self.work.write(&self.pre_surf, ®ion.crop(r)); - dmg = dmg.union(&r); - } - self.done += new.len(); - dmg - } - - /// Mix the working pixels of `r` back over the original into the shown document. - fn show(&mut self, r: Rect, work: &Region) -> Result<()> { - let (surf, _) = crate::channel_cmds::target_surface(std::sync::Arc::make_mut(&mut self.doc), self.id, &self.params)?; - photocraft_paint::retouch::mix_back(surf, &Region::read(&self.pre_surf, r), work, r, self.opacity, self.sel.as_ref(), self.lock); - Ok(()) - } - - /// Render more points; returns the rectangle that changed. - /// Invalid coordinates reject the whole batch without changing the preview. - /// Only the position and pressure of `pts` are used: the commands take no tilt or times. - pub fn push(&mut self, pts: &[StrokePoint]) -> Result { - crate::brush_cmds::check_coords(pts, &self.cmd)?; - let pts: Vec<_> = pts.iter().map(|q| StrokePoint::new(q.x, q.y, q.pressure)).collect(); - self.points.extend_from_slice(&pts); - self.renderer.push(&pts); - let dmg = self.run_new_dabs(); - let ctx = self.renderer.ctx.clone(); - // The finishing dabs, run on a scratch copy of the working pixels. - let mut tail = None; - if self.preview_tail { - let ds = self.renderer.tail_dabs(); - let r = ds.iter().fold(Rect::EMPTY, |a, d| a.union(&ctx.dab_rect(d, false))); - if !r.is_empty() { - let mut region = self.work.read(&self.pre_surf, r.inflate(self.neighborhood.halo())); - for (k, d) in ds.iter().enumerate() { - (self.effect)(&mut region, &ctx.footprint(d, self.done + k)); - } - tail = Some((r, region.crop(r))); - } - } - // Back to the stroke without the previous tail. - let old = std::mem::replace(&mut self.tail, Rect::EMPTY); - let shown = dmg.union(&old); - let tail_rect = tail.as_ref().map_or(Rect::EMPTY, |(r, _)| *r); - if shown.is_empty() && tail_rect.is_empty() { - return Ok(Rect::EMPTY); - } - self.bounds = self.bounds.union(&dmg).union(&tail_rect); - if !shown.is_empty() { - let work = self.work.read(&self.pre_surf, shown); - self.show(shown, &work)?; - } - if let Some((r, work)) = tail { - self.show(r, &work)?; - self.tail = r; - } - Ok(shown.union(&tail_rect)) - } - - /// The finished stroke as its commit would take it over ([`Session::offer_live_dab`]): the - /// finishing dabs are run, and the pixels are the ones the command with the same params and - /// points paints. Only while the brush, tool settings and layer are still the ones the stroke - /// started with: the document revision doesn't cover those. - pub(crate) fn into_commit(mut self, s: &Session) -> Result { - let (Some((tool, brush)), Some(base)) = (self.tool.take(), self.base) else { - return Err(bad(&self.cmd, "this stroke's commit renders itself")); - }; - let (stroke, id) = parse_brush(s, &self.params, &self.cmd)?; - let (now, _) = DabTool::parse(s, &self.cmd, &self.params, &stroke)?; - if now != tool || stroke.brush != *brush || id != self.id { - return Err(bad(&self.cmd, "the brush, tool options or layer changed during the stroke")); - } - self.renderer.finish(); - let dmg = self.run_new_dabs(); - let shown = dmg.union(&self.tail); - if !shown.is_empty() { - let work = self.work.read(&self.pre_surf, shown); - self.show(shown, &work)?; - } - self.bounds = self.bounds.union(&dmg); - let (surf, _) = crate::channel_cmds::target_surface(std::sync::Arc::make_mut(&mut self.doc), self.id, &self.params)?; - let surface = surf.clone(); - Ok(crate::brush_cmds::LiveCommit { - mixer: None, - cmd: self.cmd, - base, - params: self.params, - seed: None, - points: self.points, - surface, - bounds: self.bounds, - }) - } -} - -/// "Sample All Layers" for Spot Healing, Blur, Sharpen and Smudge (layer pixels only: a mask or -/// channel has nothing to sample from other layers). -fn sample_all_layers(p: &Value) -> bool { - flag(p, "sampleAllLayers", false) && targets_pixels(p) -} - -/// Sample All Layers for the sequential-dab tools: each dab's effect runs on a copy of the visible -/// composite (kept across dabs, so a dab sees the earlier ones), and the result is laid onto the -/// layer under the dab. An empty layer above the image so picks up the blurred or smudged picture, -/// and pixels the effect didn't change look as before (they are what was already visible). -struct AllLayers<'a> { - pre: &'a Document, - fmt: PixelFormat, - visible: Option, -} - -impl<'a> AllLayers<'a> { - fn new(pre: &'a Document, fmt: PixelFormat) -> Self { - Self { pre, fmt, visible: None } - } - - fn dab(&mut self, work: &mut Region, fp: &Footprint, effect: impl FnOnce(&mut Region, &Footprint)) { - let (pre, fmt) = (self.pre, self.fmt); - let visible = self.visible.get_or_insert_with(|| composite_region(pre, None, SampleLayers::All, work.rect, fmt)); - if visible.rect != work.rect || visible.ch != work.ch { - return effect(work, fp); - } - effect(visible, fp); - let r = fp.rect.intersect(&work.rect); - for y in r.y0..r.y1 { - for x in r.x0..r.x1 { - if fp.at(x, y) > 0.0 { - work.px_mut(x, y).copy_from_slice(visible.px(x, y)); - } - } - } - } -} - -// --------------------------------------------------------------------------------------------- -// Registry -// --------------------------------------------------------------------------------------------- - -/// The brush every retouching command shares, plus the tool's own params. -macro_rules! brush_params { - ($extra:literal) => { - concat!("{", r#""points":[[x,y,pressure?],…],"size":1..5000 px=tool size,"hardness":0..100=tool hardness,"opacity":1..100=100,"flow":1..100=100,"spacing":1..1000 (% of size)=Brush Settings spacing,"layer":id?=active,"target":"pixels"|"mask"|"filterMask"|"quickMask"|{"channel":i}=Channels panel target"#, $extra, "}") - }; -} - -/// Retouching command specs. -pub fn specs() -> Vec { - vec![ - CommandSpec { - id: "paint.cloneStamp", - label: "Clone Stamp", - menu: &[], - shortcut: None, - params: brush_params!( - r#","source":[sx,sy] (sampled under the first point) | "offset":[dx,dy],"aligned":bool=true,"sampleLayer":"current|currentAndBelow|all"="current","mode":"normal|multiply|…"="normal","wrap":bool=false (repeat source and stroke at document edges for Pattern Preview) → {"damage","offset","aligned","nextSource"}"# - ), - enabled: has_pixel_layer, - run: clone_stamp, - journal: true, - }, - CommandSpec { - id: "paint.patternStamp", - label: "Pattern Stamp", - menu: &[], - shortcut: None, - params: brush_params!( - r#","pattern":id|name?=Patterns panel current,"scale":1..1000 %=100,"angle":deg=0,"aligned":bool=true,"impressionist":bool=false,"mode":"normal|multiply|…"="normal","phase":[px,py]? → {"damage","phase","aligned","pattern"}"# - ), - enabled: pattern_stamp::enabled, - run: pattern_stamp::run, - journal: true, - }, - CommandSpec { - id: "paint.healingBrush", - label: "Healing Brush", - menu: &[], - shortcut: None, - params: brush_params!( - r#","source":[sx,sy] | "offset":[dx,dy],"aligned":bool=true,"sampleLayer":"current|currentAndBelow|all"="current","mode":"normal|…"="normal" → {"damage","offset","aligned","nextSource"}"# - ), - enabled: has_pixel_layer, - run: healing_brush, - journal: true, - }, - CommandSpec { - id: "paint.spotHealing", - label: "Spot Healing Brush", - menu: &[], - shortcut: None, - params: brush_params!(r#","type":"contentAware|createTexture|proximityMatch"="contentAware","sampleAllLayers":bool=false"#), - enabled: has_pixel_layer, - run: spot_healing, - journal: true, - }, - CommandSpec { - id: "paint.patch", - label: "Patch", - menu: &[], - shortcut: None, - params: r#"{"offset":[dx,dy] (how far the selection was dragged),"mode":"source|destination"="source","contentAware":bool=false (fill the selection content-aware from the dragged-to place; a background job),"structure":1..7=4 (content-aware: 3..7 copy the middle exactly, 1..2 re-synthesise more of it),"color":0..10=0 (content-aware: how far the copy's level adapts to the selection's surroundings),"sampleAllLayers":bool=false (content-aware),"layer":id?=active,"target":"pixels"|"mask"|"filterMask"|"quickMask"|{"channel":i}=Channels panel target} → {"damage","offset"}"#, - enabled: patch::enabled, - run: patch::patch, - journal: true, - }, - CommandSpec { - id: "paint.contentAwareMove", - label: "Content-Aware Move", - menu: &[], - shortcut: None, - params: r#"{"offset":[dx,dy] (how far the selection was dragged),"mode":"move|extend"="move","structure":1..7=4 (3..7 copy the content exactly but for a band about a patch wide along its edge; 2 widens the band, 1 re-synthesises the content too),"color":0..10=0 (0 keeps the content's level; higher values bring it towards its new place, by up to about 0.04 × color),"sampleAllLayers":bool=false,"scaleX":%=100,"scaleY":%=100 (Transform On Drop: 1..10000, negative flips),"rotate":deg=0 (Transform On Drop, clockwise; scale and rotation are about the selection's centre, before the offset; a transformed patch may reach past the canvas edge),"layer":id?=active,"target":"pixels"|"mask"|"filterMask"|"quickMask"|{"channel":i}=Channels panel target} → {"damage","offset","mode","transformed"?} (a background job; the selection moves, and is transformed, with the content)"#, - enabled: content_aware_move::enabled, - run: content_aware_move::content_aware_move, - journal: true, - }, - CommandSpec { - id: "paint.remove", - label: "Remove", - menu: &[], - shortcut: None, - params: brush_params!( - r#","strokes":[[[x,y,pressure?],…],…]? (several strokes removed together, as one job and one undo step; else "points"),"closeLoops":bool=true (a stroke around an object removes what it encloses),"sampleAllLayers":bool=false,"newLayer":bool=false (the fill goes to a new layer above the target, which stays as it was) → {"damage","layer"?} (a background job)"# - ), - enabled: has_pixel_layer, - run: remove::remove, - journal: true, - }, - CommandSpec { - id: "paint.dodge", - label: "Dodge", - menu: &[], - shortcut: None, - params: brush_params!(r#","range":"shadows|midtones|highlights"="midtones","exposure":1..100=50,"protectTones":bool=true"#), - enabled: has_pixel_layer, - run: |s, p| dab_cmd(s, p, "paint.dodge"), - journal: true, - }, - CommandSpec { - id: "paint.burn", - label: "Burn", - menu: &[], - shortcut: None, - params: brush_params!(r#","range":"shadows|midtones|highlights"="midtones","exposure":1..100=50,"protectTones":bool=true"#), - enabled: has_pixel_layer, - run: |s, p| dab_cmd(s, p, "paint.burn"), - journal: true, - }, - CommandSpec { - id: "paint.sponge", - label: "Sponge", - menu: &[], - shortcut: None, - params: brush_params!(r#","mode":"desaturate|saturate"="desaturate","vibrance":bool=true (flow = sponge strength)"#), - enabled: has_pixel_layer, - run: |s, p| dab_cmd(s, p, "paint.sponge"), - journal: true, - }, - CommandSpec { - id: "paint.blur", - label: "Blur", - menu: &[], - shortcut: None, - params: brush_params!(r#","strength":1..100=50,"sampleAllLayers":bool=false"#), - enabled: has_pixel_layer, - run: |s, p| dab_cmd(s, p, "paint.blur"), - journal: true, - }, - CommandSpec { - id: "paint.sharpen", - label: "Sharpen", - menu: &[], - shortcut: None, - params: brush_params!(r#","strength":1..100=50,"protectDetail":bool=true,"sampleAllLayers":bool=false"#), - enabled: has_pixel_layer, - run: |s, p| dab_cmd(s, p, "paint.sharpen"), - journal: true, - }, - CommandSpec { - id: "paint.smudge", - label: "Smudge", - menu: &[], - shortcut: None, - params: brush_params!(r#","strength":1..100=50,"fingerPainting":bool=false (starts with the foreground colour),"sampleAllLayers":bool=false"#), - enabled: has_pixel_layer, - run: |s, p| dab_cmd(s, p, "paint.smudge"), - journal: true, - }, - CommandSpec { - id: "paint.historyBrush", - label: "History Brush", - menu: &[], - shortcut: None, - params: brush_params!( - r#","state":row (a History panel row, as history.setSource: 0 = oldest state, then the current one, then the greyed redo states),"snapshot":id (a history.newSnapshot id; default: the History panel's source, else the oldest held state; a source of another canvas size is an error)"# - ), - enabled: has_pixel_layer, - run: history_brush, - journal: true, - }, - CommandSpec { - id: "paint.artHistoryBrush", - label: "Art History Brush", - menu: &[], - shortcut: None, - params: brush_params!( - r#","state":row (a History panel row, as history.setSource),"snapshot":id (a history.newSnapshot id; default: the History panel's source, as paint.historyBrush; a source of another canvas size is an error),"style":"tightShort|tightMedium|tightLong|looseMedium|looseLong|dab|tightCurl|looseCurl"="tightMedium","area":0..100=50,"tolerance":0..100=0"# - ), - enabled: has_pixel_layer, - run: art_history::run, - journal: true, - }, - ] -} - -#[cfg(test)] -mod tests; diff --git a/crates/engine/src/sampler_cmds.rs b/crates/engine/src/sampler_cmds.rs deleted file mode 100644 index a67b023a6f..0000000000 --- a/crates/engine/src/sampler_cmds.rs +++ /dev/null @@ -1,558 +0,0 @@ -//! Color Sampler points (#1046): numbered colour readings pinned to canvas pixels and listed in -//! the Info panel, so a fixed position can be compared instead of chasing the live pointer. -//! -//! Points are per-document view state ([`crate::DocState::color_samplers`]): they belong to their -//! document, are discarded when it closes, and are not saved to `.pcraft` or PSD. Placing, moving -//! and removing them changes no pixels and adds no History step, so they are not journaled. Each -//! point reads one composite pixel (no averaging); its values match the Info panel's pointer -//! readout (RGB 0–255 and colour-managed CMYK percentages, as in the Color Picker). - -use photocraft_doc::Document; -use serde_json::{Value, json}; - -use crate::commands::CommandSpec; -use crate::{DocState, EngineError, Result, Session}; - -/// Photoshop's Color Sampler limit: at most 10 points per document. -pub const MAX_SAMPLERS: usize = 10; - -fn bad(cmd: &str, msg: impl Into) -> EngineError { - EngineError::BadParams { cmd: cmd.into(), msg: msg.into() } -} - -fn has_doc(s: &Session) -> std::result::Result<(), String> { - s.active().map(|_| ()).ok_or_else(|| "no document open".into()) -} - -/// Colour-managed CMYK, in percent, as the Info panel shows it: the same conversion the Color -/// Picker uses (`photocraft_color::convert::rgb_to_cmyk`: the CMYK profile active on this thread, -/// else the built-in coated CMYK), so both panels agree (#8101). 32-bit samples can lie outside -/// 0..1, so each channel is clamped first (NaN reads as 0), like the RGB readout. -pub fn device_cmyk(r: f32, g: f32, b: f32) -> [i32; 4] { - let unit = |v: f32| if v.is_nan() { 0.0 } else { v.clamp(0.0, 1.0) }; - photocraft_color::convert::rgb_to_cmyk([unit(r), unit(g), unit(b)]).map(|v| (unit(v) * 100.0).round() as i32) -} - -/// The Info-panel values for a sample point at document pixel `pos`: composite RGB 0–255 and -/// colour-managed CMYK percentages (the document's CMYK profile when it has one). One composite -/// pixel, no averaging. -pub fn readout(doc: &Document, pos: [f64; 2]) -> ([i32; 3], [i32; 4]) { - let rgba = crate::sample_cmds::sample_color(doc, None, pos[0], pos[1], 1, crate::sample_cmds::SampleLayers::All); - let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as i32; - let cmyk = photocraft_color::convert::with_cmyk_space(photocraft_compose::cmyk_space(doc).as_ref(), || device_cmyk(rgba[0], rgba[1], rgba[2])); - ([q(rgba[0]), q(rgba[1]), q(rgba[2])], cmyk) -} - -/// One point as the list command reports it. -pub fn point_json(doc: &Document, index: usize, pos: [f64; 2]) -> Value { - let (rgb, cmyk) = readout(doc, pos); - json!({"index": index, "number": index + 1, "position": [pos[0], pos[1]], "rgb": rgb, "cmyk": cmyk}) -} - -fn list_json(doc: &Document, points: &[[f64; 2]]) -> Value { - json!({ - "max": MAX_SAMPLERS, - "samplers": points.iter().enumerate().map(|(i, p)| point_json(doc, i, *p)).collect::>(), - }) -} - -fn coord(cmd: &str, p: &Value, key: &str) -> Result { - p.get(key).and_then(Value::as_f64).filter(|v| v.is_finite()).ok_or_else(|| bad(cmd, format!("`{key}` must be a finite number (document pixels)"))) -} - -/// The pixel a point at document coordinate `(x, y)` sits on, if it is inside the canvas. Whole -/// pixels only: the click's fractional position floors to the pixel it lands on. -fn pixel(doc: &Document, x: f64, y: f64) -> Option<[f64; 2]> { - let (px, py) = (x.floor(), y.floor()); - if px < f64::from(i32::MIN) || px > f64::from(i32::MAX) || py < f64::from(i32::MIN) || py > f64::from(i32::MAX) { - return None; - } - doc.bounds().contains(px as i32, py as i32).then_some([px, py]) -} - -fn index_param(cmd: &str, p: &Value) -> Result { - p.get("index").and_then(Value::as_u64).and_then(|n| usize::try_from(n).ok()).ok_or_else(|| bad(cmd, "pass `index` (0-based)")) -} - -/// Apply a Color Sampler change to the active document: view state, so no history step and no -/// pixels. Bumps the revision (keeping a clean document clean) so UIs refresh. -fn change(s: &mut Session, f: impl FnOnce(&mut DocState) -> Result) -> Result { - let st = s.active_mut().ok_or(EngineError::NoDocument)?; - let r = f(st)?; - let clean = st.saved_revision == st.revision; - st.revision += 1; - if clean { - st.saved_revision = st.revision; - } - st.last_damage = Some(photocraft_geom::Rect::EMPTY); - Ok(r) -} - -fn add(s: &mut Session, p: &Value) -> Result { - const CMD: &str = "view.colorSamplers.add"; - let x = coord(CMD, p, "x")?; - let y = coord(CMD, p, "y")?; - change(s, |st| { - let pos = pixel(&st.doc, x, y).ok_or_else(|| EngineError::Other("the sample point is outside the canvas".into()))?; - if st.color_samplers.len() >= MAX_SAMPLERS { - return Err(EngineError::Other(format!("Color Sampler limit reached: at most {MAX_SAMPLERS} points per document"))); - } - st.color_samplers.push(pos); - let i = st.color_samplers.len() - 1; - Ok(json!({"index": i, "count": st.color_samplers.len(), "point": point_json(&st.doc, i, pos)})) - }) -} - -fn move_point(s: &mut Session, p: &Value) -> Result { - const CMD: &str = "view.colorSamplers.move"; - let i = index_param(CMD, p)?; - let x = coord(CMD, p, "x")?; - let y = coord(CMD, p, "y")?; - change(s, |st| { - let n = st.color_samplers.len(); - if i >= n { - return Err(bad(CMD, format!("no sample point {i} (the document has {n})"))); - } - let pos = pixel(&st.doc, x, y).ok_or_else(|| EngineError::Other("the sample point is outside the canvas".into()))?; - st.color_samplers[i] = pos; - Ok(json!({"index": i, "point": point_json(&st.doc, i, pos)})) - }) -} - -fn delete(s: &mut Session, p: &Value) -> Result { - const CMD: &str = "view.colorSamplers.delete"; - let i = index_param(CMD, p)?; - change(s, |st| { - let n = st.color_samplers.len(); - if i >= n { - return Err(bad(CMD, format!("no sample point {i} (the document has {n})"))); - } - st.color_samplers.remove(i); - Ok(json!({"deleted": 1, "remaining": st.color_samplers.len()})) - }) -} - -fn clear(s: &mut Session, _p: &Value) -> Result { - change(s, |st| { - let n = st.color_samplers.len(); - st.color_samplers.clear(); - Ok(json!({"deleted": n, "remaining": 0})) - }) -} - -fn list(s: &mut Session, _p: &Value) -> Result { - let st = s.active().ok_or(EngineError::NoDocument)?; - Ok(list_json(&st.doc, &st.color_samplers)) -} - -pub fn specs() -> Vec { - vec![ - CommandSpec { - id: "view.colorSamplers.add", - label: "Add Color Sampler", - menu: &[], - shortcut: None, - params: r##"{"x":f64,"y":f64} → the new point {index, number, position, rgb, cmyk}; errors at the 10-point limit or off the canvas"##, - enabled: has_doc, - run: add, - journal: false, - }, - CommandSpec { - id: "view.colorSamplers.move", - label: "Move Color Sampler", - menu: &[], - shortcut: None, - params: r##"{"index":n,"x":f64,"y":f64}"##, - enabled: has_doc, - run: move_point, - journal: false, - }, - CommandSpec { - id: "view.colorSamplers.delete", - label: "Delete Color Sampler", - menu: &[], - shortcut: None, - params: r##"{"index":n}"##, - enabled: has_doc, - run: delete, - journal: false, - }, - CommandSpec { - id: "view.colorSamplers.clear", - label: "Clear Color Samplers", - menu: &[], - shortcut: None, - params: "{}", - enabled: has_doc, - run: clear, - journal: false, - }, - CommandSpec { - id: "view.colorSamplers.list", - label: "Color Samplers", - menu: &[], - shortcut: None, - params: r##"{} → {max, samplers:[{index, number, position, rgb, cmyk}]}"##, - enabled: has_doc, - run: list, - journal: false, - }, - ] -} - -#[cfg(test)] -mod tests { - use super::*; - use photocraft_color::{ColorMode, SampleType}; - use photocraft_doc::{Layer, Size}; - use photocraft_geom::Rect; - - /// A 100×80 white document. - fn session() -> Session { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 100, "height": 80, "background": "white"})).unwrap(); - s - } - - fn list(s: &mut Session) -> Value { - s.execute("view.colorSamplers.list", json!({})).unwrap() - } - - fn points(s: &mut Session) -> Vec { - list(s)["samplers"].as_array().cloned().unwrap_or_default() - } - - #[test] - fn add_reads_the_composite_pixel_and_lists_it() { - let mut s = session(); - let r = s.execute("view.colorSamplers.add", json!({"x": 5, "y": 6})).unwrap(); - assert_eq!(r["index"], 0); - assert_eq!(r["count"], 1); - assert_eq!(r["point"]["number"], 1); - assert_eq!(r["point"]["position"], json!([5.0, 6.0])); - assert_eq!(r["point"]["rgb"], json!([255, 255, 255])); - assert_eq!(r["point"]["cmyk"], json!([0, 0, 0, 0])); - let l = list(&mut s); - assert_eq!(l["max"], 10); - assert_eq!(l["samplers"].as_array().unwrap().len(), 1); - assert_eq!(l["samplers"][0]["position"], json!([5.0, 6.0])); - } - - #[test] - fn fractional_clicks_floor_to_the_pixel() { - let mut s = session(); - let r = s.execute("view.colorSamplers.add", json!({"x": 5.9, "y": 6.1})).unwrap(); - assert_eq!(r["point"]["position"], json!([5.0, 6.0])); - } - - #[test] - fn add_reads_an_actual_painted_pixel() { - // A black pixel at (3, 3) of an otherwise white document. - let mut s = session(); - s.edit("paint", |doc, _| { - let surf = doc.layers[0].surface_mut().unwrap(); - let black = photocraft_raster::from_rgba(&surf.format(), [0.0, 0.0, 0.0, 1.0]); - surf.fill_rect(Rect::new(3, 3, 4, 4), &black); - Ok(()) - }) - .unwrap(); - let r = s.execute("view.colorSamplers.add", json!({"x": 3, "y": 3})).unwrap(); - assert_eq!(r["point"]["rgb"], json!([0, 0, 0])); - assert_eq!(r["point"]["cmyk"], json!(device_cmyk(0.0, 0.0, 0.0)), "the profile's black, not the naive 0/0/0/100"); - // Painting over the point changes its readout (the list is computed live). - s.edit("paint", |doc, _| { - let surf = doc.layers[0].surface_mut().unwrap(); - let red = photocraft_raster::from_rgba(&surf.format(), [1.0, 0.0, 0.0, 1.0]); - surf.fill_rect(Rect::new(3, 3, 4, 4), &red); - Ok(()) - }) - .unwrap(); - assert_eq!(points(&mut s)[0]["rgb"], json!([255, 0, 0])); - } - - #[test] - fn ten_points_then_the_limit() { - let mut s = session(); - for i in 0..10 { - s.execute("view.colorSamplers.add", json!({"x": i, "y": 0})).unwrap(); - } - assert_eq!(points(&mut s).len(), 10); - let err = s.execute("view.colorSamplers.add", json!({"x": 20, "y": 0})).unwrap_err().to_string(); - assert!(err.contains("limit"), "{err}"); - assert_eq!(points(&mut s).len(), 10); - } - - #[test] - fn move_delete_and_clear() { - let mut s = session(); - s.execute("view.colorSamplers.add", json!({"x": 5, "y": 5})).unwrap(); - s.execute("view.colorSamplers.add", json!({"x": 50, "y": 50})).unwrap(); - let r = s.execute("view.colorSamplers.move", json!({"index": 0, "x": 10, "y": 20})).unwrap(); - assert_eq!(r["point"]["position"], json!([10.0, 20.0])); - assert_eq!(points(&mut s)[0]["position"], json!([10.0, 20.0])); - s.execute("view.colorSamplers.delete", json!({"index": 1})).unwrap(); - assert_eq!(points(&mut s).len(), 1); - // The remaining point is the moved #1. - assert_eq!(points(&mut s)[0]["position"], json!([10.0, 20.0])); - let r = s.execute("view.colorSamplers.clear", json!({})).unwrap(); - assert_eq!(r["deleted"], 1); - assert!(points(&mut s).is_empty()); - } - - #[test] - fn placing_and_moving_add_no_history_and_change_no_pixels() { - let mut s = session(); - let before = s.active().unwrap().doc.layers[0].surface().unwrap().pixel(5, 5); - let past = s.active().unwrap().history.past_len(); - s.execute("view.colorSamplers.add", json!({"x": 5, "y": 5})).unwrap(); - s.execute("view.colorSamplers.move", json!({"index": 0, "x": 9, "y": 9})).unwrap(); - s.execute("view.colorSamplers.delete", json!({"index": 0})).unwrap(); - assert_eq!(s.active().unwrap().history.past_len(), past, "no history steps"); - assert_eq!(s.active().unwrap().doc.layers[0].surface().unwrap().pixel(5, 5), before, "no pixels changed"); - assert!(!s.active().unwrap().is_dirty(), "a clean document stays clean"); - } - - #[test] - fn points_belong_to_their_document() { - let mut s = session(); - s.execute("view.colorSamplers.add", json!({"x": 5, "y": 5})).unwrap(); - s.execute("file.new", json!({"width": 40, "height": 40, "background": "white"})).unwrap(); - assert!(points(&mut s).is_empty(), "the new document has no points"); - s.execute("document.activate", json!({"document": 0})).unwrap(); - assert_eq!(points(&mut s).len(), 1, "the first document kept its point"); - // Closing the second document leaves the first's points alone. - s.execute("file.close", json!({"document": 1})).unwrap(); - assert_eq!(points(&mut s).len(), 1); - // Closing the first discards its points with it. - s.execute("file.close", json!({"document": 0})).unwrap(); - assert!(s.execute("view.colorSamplers.list", json!({})).is_err(), "no document open"); - } - - #[test] - fn a_crop_drops_points_outside_the_new_canvas() { - let mut s = session(); - s.execute("view.colorSamplers.add", json!({"x": 5, "y": 5})).unwrap(); - s.execute("view.colorSamplers.add", json!({"x": 50, "y": 50})).unwrap(); - s.execute("image.crop", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); - let p = points(&mut s); - assert_eq!(p.len(), 1, "the outside point was removed"); - assert_eq!(p[0]["position"], json!([5.0, 5.0])); - assert_eq!(s.take_samplers_removed(), 1, "one removed point reported"); - assert_eq!(s.take_samplers_removed(), 0, "reported once"); - } - - #[test] - fn a_crop_moves_points_with_their_pixels() { - // A crop from a non-zero origin moves the canvas: the point follows its pixel. - let mut s = session(); - s.execute("view.colorSamplers.add", json!({"x": 50, "y": 40})).unwrap(); - s.execute("image.crop", json!({"x": 40, "y": 30, "width": 20, "height": 20})).unwrap(); - let p = points(&mut s); - assert_eq!(p.len(), 1); - assert_eq!(p[0]["position"], json!([10.0, 10.0]), "moved by (-40, -30)"); - assert_eq!(s.take_samplers_removed(), 0, "nothing removed"); - } - - #[test] - fn a_canvas_size_shift_moves_points() { - // Canvas Size anchored bottom-right shifts the canvas origin by (+20, +20). - let mut s = session(); - s.execute("view.colorSamplers.add", json!({"x": 30, "y": 30})).unwrap(); - s.execute("image.canvasSize", json!({"width": 120, "height": 100, "anchor": "bottomRight"})).unwrap(); - let p = points(&mut s); - assert_eq!(p.len(), 1); - assert_eq!(p[0]["position"], json!([50.0, 50.0]), "moved by the canvas shift"); - } - - #[test] - fn a_right_angle_rotation_moves_points() { - // 90° clockwise about the centre: pixel (x, y) of the 100×80 canvas goes to (79 - y, x). - let mut s = session(); - s.execute("view.colorSamplers.add", json!({"x": 50, "y": 40})).unwrap(); - s.execute("image.rotation.arbitrary", json!({"angle": 90, "direction": "cw"})).unwrap(); - let p = points(&mut s); - assert_eq!(p.len(), 1); - let pos = p[0]["position"].as_array().unwrap(); - let (x, y) = (pos[0].as_f64().unwrap(), pos[1].as_f64().unwrap()); - assert!((x - 39.0).abs() < 1e-6 && (y - 50.0).abs() < 1e-6, "{pos:?}"); - } - - #[test] - fn flips_and_right_angle_turns_keep_points_on_their_pixel() { - use crate::canvas_geom::Turn; - for (id, turn) in [ - ("image.imageRotation.flipCanvasHorizontal", Turn::FlipHorizontal), - ("image.imageRotation.flipCanvasVertical", Turn::FlipVertical), - ("image.imageRotation.180", Turn::Rotate180), - ("image.imageRotation.90cw", Turn::Cw90), - ("image.imageRotation.90ccw", Turn::Ccw90), - ] { - // A black pixel at (3, 3) of a white 100×80 document, with a point on it. - let mut s = session(); - s.edit("paint", |doc, _| { - let surf = doc.layers[0].surface_mut().unwrap(); - let black = photocraft_raster::from_rgba(&surf.format(), [0.0, 0.0, 0.0, 1.0]); - surf.fill_rect(Rect::new(3, 3, 4, 4), &black); - Ok(()) - }) - .unwrap(); - s.execute("view.colorSamplers.add", json!({"x": 3, "y": 3})).unwrap(); - s.execute(id, json!({})).unwrap(); - let (x, y) = turn.pixel_map(100, 80)(3, 3); - let p = points(&mut s); - assert_eq!(p.len(), 1, "{id}"); - assert_eq!(p[0]["position"], json!([f64::from(x), f64::from(y)]), "{id}"); - assert_eq!(p[0]["rgb"], json!([0, 0, 0]), "{id}"); - } - } - - #[test] - fn an_arbitrary_rotation_keeps_points_on_their_pixel() { - // The pixel at (3, 3) of the 100×80 document, and where each turn moves it. - for (angle, direction, at) in [(90, "cw", [76.0, 3.0]), (90, "ccw", [3.0, 96.0]), (180, "cw", [96.0, 76.0])] { - let mut s = session(); - s.edit("paint", |doc, _| { - let surf = doc.layers[0].surface_mut().unwrap(); - let black = photocraft_raster::from_rgba(&surf.format(), [0.0, 0.0, 0.0, 1.0]); - surf.fill_rect(Rect::new(3, 3, 4, 4), &black); - Ok(()) - }) - .unwrap(); - s.execute("view.colorSamplers.add", json!({"x": 3, "y": 3})).unwrap(); - s.execute("view.colorSamplers.add", json!({"x": 0, "y": 0})).unwrap(); - s.execute("image.rotation.arbitrary", json!({"angle": angle, "direction": direction})).unwrap(); - assert_eq!(s.take_samplers_removed(), 0, "{angle} {direction}: the corner point stays on the canvas"); - let p = points(&mut s); - assert_eq!(p.len(), 2, "{angle} {direction}: the corner point stays on the canvas"); - assert_eq!(p[0]["position"], json!(at), "{angle} {direction}"); - assert_eq!(p[0]["rgb"], json!([0, 0, 0]), "{angle} {direction}"); - } - } - - #[test] - fn a_rotated_crop_moves_points() { - // The crop frame is centred on the point's pixel; turned 90° that pixel lands at (10, 9). - let mut s = session(); - s.edit("paint", |doc, _| { - let surf = doc.layers[0].surface_mut().unwrap(); - let black = photocraft_raster::from_rgba(&surf.format(), [0.0, 0.0, 0.0, 1.0]); - surf.fill_rect(Rect::new(50, 40, 51, 41), &black); - Ok(()) - }) - .unwrap(); - s.execute("view.colorSamplers.add", json!({"x": 50, "y": 40})).unwrap(); - s.execute("image.crop", json!({"x": 40, "y": 30, "width": 20, "height": 20, "angle": 90})).unwrap(); - let p = points(&mut s); - assert_eq!(p.len(), 1); - assert_eq!(p[0]["position"], json!([10.0, 9.0])); - assert_eq!(p[0]["rgb"], json!([0, 0, 0])); - } - - #[test] - fn a_crop_to_a_target_size_scales_points() { - // The crop resamples the 20 x 20 area to 40 x 40: the point (10, 10 after the shift; 10, 9 - // turned 90°, as in `a_rotated_crop_moves_points`) doubles. - for (angle, at) in [(None, [20.0, 20.0]), (Some(90), [20.0, 18.0])] { - let mut s = session(); - s.execute("view.colorSamplers.add", json!({"x": 50, "y": 40})).unwrap(); - let mut p = json!({"x": 40, "y": 30, "width": 20, "height": 20, "targetWidth": 40, "targetHeight": 40}); - if let Some(a) = angle { - p["angle"] = json!(a); - } - s.execute("image.crop", p).unwrap(); - let p = points(&mut s); - assert_eq!(p.len(), 1, "angle {angle:?}"); - assert_eq!(p[0]["position"], json!(at), "angle {angle:?}"); - assert_eq!(s.take_samplers_removed(), 0, "angle {angle:?}"); - } - } - - #[test] - fn bad_params_and_no_document_are_errors_not_panics() { - let mut s = Session::new(); - for id in ["view.colorSamplers.add", "view.colorSamplers.move", "view.colorSamplers.delete", "view.colorSamplers.clear", "view.colorSamplers.list"] { - assert!(s.execute(id, json!({})).is_err(), "{id} without a document"); - } - let mut s = session(); - for (id, p) in [ - ("view.colorSamplers.add", json!({})), - ("view.colorSamplers.add", json!({"x": "a", "y": 1})), - ("view.colorSamplers.add", json!({"x": 1e300, "y": 1})), - ("view.colorSamplers.add", json!({"x": 5, "y": f64::NAN})), - ("view.colorSamplers.add", json!({"x": -1, "y": 5})), - ("view.colorSamplers.add", json!({"x": 5, "y": 1000})), - ("view.colorSamplers.move", json!({"index": 0, "x": 1, "y": 1})), - ("view.colorSamplers.delete", json!({"index": 0})), - ("view.colorSamplers.delete", json!({})), - ("view.colorSamplers.move", json!({"index": 4_294_967_296u64, "x": 1, "y": 1})), - ] { - assert!(matches!(s.execute(id, p.clone()), Err(EngineError::BadParams { .. }) | Err(EngineError::Other(_))), "{id} {p}"); - } - // An off-canvas point is refused and places nothing. - assert!(points(&mut s).is_empty()); - } - - /// The Info panel and the Color Picker read CMYK through one conversion (#8101): the - /// colour-managed `rgb_to_cmyk`, not a naive formula that disagrees with it by tens of percent. - #[test] - fn device_cmyk_agrees_with_the_color_picker_conversion() { - for rgb in [[1.0, 1.0, 1.0], [0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.5, 0.5, 0.5], [0.2, 0.6, 0.9], [1.0, 0.93, 0.0]] { - let picker = photocraft_color::convert::rgb_to_cmyk(rgb).map(|v| (v * 100.0).round() as i32); - assert_eq!(device_cmyk(rgb[0], rgb[1], rgb[2]), picker, "{rgb:?}"); - } - assert_eq!(device_cmyk(1.0, 1.0, 1.0), [0, 0, 0, 0]); - assert_ne!(device_cmyk(1.0, 0.0, 0.0), [0, 100, 100, 0], "pure red is not the naive 0/100/100/0"); - } - - /// 32-bit samples can lie outside 0..1 (or be NaN); the CMYK readout clamps them like the RGB - /// readout does instead of reporting K:-50% or C:120% (#4191). - #[test] - fn device_cmyk_clamps_out_of_range_and_nan_samples() { - assert_eq!(device_cmyk(1.5, 1.5, 1.5), [0, 0, 0, 0]); - assert_eq!(device_cmyk(2.0, 0.0, 0.0), device_cmyk(1.0, 0.0, 0.0)); - let in_range = |c: [i32; 4]| c.iter().all(|v| (0..=100).contains(v)); - for (r, g, b) in [(-0.2, 0.5, 0.5), (-1.0, -1.0, -1.0), (f32::NAN, 0.5, 0.5), (f32::NAN, f32::NAN, f32::NAN), (f32::INFINITY, f32::NEG_INFINITY, 0.5)] { - let c = device_cmyk(r, g, b); - assert!(in_range(c), "{r} {g} {b} -> {c:?}"); - } - assert_eq!(device_cmyk(f32::NAN, f32::NAN, f32::NAN), device_cmyk(0.0, 0.0, 0.0)); - } - - #[test] - fn hdr_pixel_on_a_32_bit_document_reads_in_range() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 8, "height": 8, "depth": 32, "background": "white"})).unwrap(); - s.edit("paint", |doc, _| { - let surf = doc.layers[0].surface_mut().unwrap(); - let hdr = photocraft_raster::from_rgba(&surf.format(), [2.0, 2.0, 2.0, 1.0]); - surf.fill_rect(Rect::new(3, 3, 4, 4), &hdr); - Ok(()) - }) - .unwrap(); - let r = s.execute("view.colorSamplers.add", json!({"x": 3, "y": 3})).unwrap(); - assert_eq!(r["point"]["rgb"], json!([255, 255, 255])); - assert_eq!(r["point"]["cmyk"], json!([0, 0, 0, 0])); - } - - #[test] - fn points_work_at_every_depth_and_mode() { - for (mode, depth) in [("rgb", 8), ("rgb", 16), ("rgb", 32), ("grayscale", 8), ("cmyk", 8), ("lab", 8)] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 20, "height": 20, "mode": mode, "depth": depth, "background": "white"})).unwrap(); - let r = s.execute("view.colorSamplers.add", json!({"x": 10, "y": 10})).unwrap(); - let rgb = r["point"]["rgb"].as_array().unwrap(); - assert_eq!(rgb.len(), 3); - assert!(rgb.iter().all(|v| v.as_i64().is_some_and(|n| (0..=255).contains(&n))), "{mode} {depth}: {rgb:?}"); - } - } - - /// The mode and depth only affect the composite the readout samples, not the point model. - #[test] - fn document_helpers_are_not_disturbed() { - let mut d = Document::new("t", Size::new(4, 4), ColorMode::Rgb, SampleType::U8); - d.layers.push(Layer::raster("Background", d.pixel_format())); - assert_eq!(pixel(&d, 0.0, 0.0), Some([0.0, 0.0])); - assert_eq!(pixel(&d, 3.9, 3.9), Some([3.0, 3.0])); - assert_eq!(pixel(&d, 4.0, 0.0), None); - } -} diff --git a/crates/engine/src/selection_cmds.rs b/crates/engine/src/selection_cmds.rs deleted file mode 100644 index d6fc50aeea..0000000000 --- a/crates/engine/src/selection_cmds.rs +++ /dev/null @@ -1,1441 +0,0 @@ -//! Select menu and selection tools: Magic Wand, Color Range, Modify -//! (expand/contract/border/smooth/feather), Grow, Similar, Lasso. -//! Selections are grayscale coverage surfaces clipped to the canvas. - -use photocraft_algo::selection::{self as sel, SelectionMode}; -use photocraft_doc::Document; -use photocraft_geom::Rect; -use photocraft_raster::Surface; -use serde_json::{Value, json}; - -use crate::commands::CommandSpec; -use crate::{EngineError, Result, Session}; - -fn has_doc(s: &Session) -> std::result::Result<(), String> { - s.active().map(|_| ()).ok_or_else(|| "no document open".into()) -} -fn has_selection(s: &Session) -> std::result::Result<(), String> { - s.active().filter(|d| d.doc.selection.is_some()).map(|_| ()).ok_or_else(|| "no selection".into()) -} - -fn f(p: &Value, k: &str, d: f32) -> f32 { - p.get(k).and_then(Value::as_f64).map_or(d, |v| v as f32) -} -fn b(p: &Value, k: &str, d: bool) -> bool { - p.get(k).and_then(Value::as_bool).unwrap_or(d) -} -fn mode(p: &Value) -> SelectionMode { - SelectionMode::parse(p.get("mode").and_then(Value::as_str).unwrap_or("replace")) -} - -/// A Color Range replacement is scoped to the selection that was active when it opened. -/// Explicit add/subtract/intersect operations retain their normal selection-combine semantics. -fn scope_color_range(mask: &mut [f32], doc: &Document, area: Rect, m: SelectionMode) { - if m != SelectionMode::Replace { - return; - } - if let Some(selection) = doc.selection.as_ref() { - let previous = sel::mask_from_surface(Some(selection), area); - for (value, bound) in mask.iter_mut().zip(previous) { - *value = value.min(bound); - } - } -} - -/// RGBA pixels the tools sample: the composite, or the active layer. -fn sample_pixels(s: &Session, all_layers: bool) -> Result<(Rect, Vec<[f32; 4]>)> { - let d = s.active().ok_or(EngineError::NoDocument)?; - let area = d.doc.bounds(); - // Match the decoders' raster budget before either the layer or composite path allocates. - let len = area.size().area(); - let max_bytes: u64 = if cfg!(target_pointer_width = "64") { 8 << 30 } else { 2 << 30 }; - if len > max_bytes / std::mem::size_of::<[f32; 4]>() as u64 { - return Err(EngineError::Other("the canvas is too large to sample for a selection".into())); - } - let layer = d.active_layer.and_then(|id| d.doc.layer(id)).and_then(|l| l.surface()); - match (all_layers, layer) { - (false, Some(surf)) => { - let len = usize::try_from(len).map_err(|_| EngineError::Other("the canvas is too large to sample for a selection".into()))?; - let mut px = crate::allocation::filled(len, [0.0f32; 4], "sampling pixels for a selection")?; - surf.read_rgba_into(area, &mut px); - Ok((area, px)) - } - _ => Ok((area, photocraft_compose::render(&d.doc, area).px)), - } -} - -fn set_selection(s: &mut Session, label: &str, area: Rect, mask: Vec, m: SelectionMode) -> Result { - let selected = s.edit(label, |doc, _| { - doc.selection = sel::combine(doc.selection.as_ref(), &mask, area, m); - Ok(doc.selection.is_some()) - })?; - Ok(json!({ "selected": selected })) -} - -fn current_mask(doc: &Document) -> (Rect, Vec) { - let area = doc.bounds(); - (area, sel::mask_from_surface(doc.selection.as_ref(), area)) -} - -/// Grayscale the canvas is actually showing, as opaque RGBA, when that is not the colour -/// composite: a gray layer-mask view, or — with every colour channel hidden — the first -/// visible alpha, Quick Mask, or the active layer's mask. The Magic Wand selects from this -/// so a white alpha stays one region instead of breaking up along the RGB underneath. -fn shown_gray(s: &Session) -> Option<(Rect, Vec<[u8; 4]>)> { - let st = s.active()?; - let doc = &st.doc; - let area = doc.bounds(); - let v = &st.channel_view; - let colors_off = v.visible_colors(crate::channel_cmds::color_count(doc)) == 0; - let surf = if let Some((mask, crate::mask_view_cmds::MaskViewMode::Gray)) = v.shown_layer_mask(doc) { - &mask.surface - } else if colors_off { - if let Some(i) = (0..doc.channels.len()).find(|i| v.alpha_shown(*i)) { - &doc.channels[i].surface - } else if let Some(q) = doc.quick_mask.as_ref().filter(|_| !v.quick_mask_hidden) { - &q.surface - } else if let Some((mask, _)) = v.shown_layer_mask(doc) { - &mask.surface - } else { - &st.active_layer.and_then(|id| doc.layer(id))?.mask.as_ref()?.surface - } - } else { - return None; - }; - Some((area, sel::rgba8_image(surf, area))) -} - -/// 8-bit RGBA of the active layer (or the composite with `all_layers`) over the canvas. -pub(crate) fn sample_rgba8(s: &Session, all_layers: bool) -> Result<(Rect, Vec<[u8; 4]>)> { - let d = s.active().ok_or(EngineError::NoDocument)?; - let area = d.doc.bounds(); - let layer = d.active_layer.and_then(|id| d.doc.layer(id)).and_then(|l| l.surface()); - match (all_layers, layer) { - (false, Some(surf)) => Ok((area, sel::rgba8_image(surf, area))), - _ => { - let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; - Ok((area, photocraft_compose::render(&d.doc, area).px.iter().map(|p| p.map(q)).collect())) - } - } -} - -fn magic_wand(s: &mut Session, p: &Value) -> Result { - let (x, y) = (f(p, "x", 0.0).floor() as i32, f(p, "y", 0.0).floor() as i32); - let (area, img) = match shown_gray(s) { - Some(plane) => plane, - None => sample_rgba8(s, b(p, "sampleAllLayers", false))?, - }; - let region = sel::wand_region(&img, area, (x, y), f(p, "tolerance", 32.0), b(p, "contiguous", true), b(p, "antiAlias", true)); - drop(img); - let m = mode(p); - let selected = s.edit("Magic Wand", |doc, _| { - doc.selection = sel::combine_region(doc.selection.as_ref(), region.as_ref(), m); - Ok(doc.selection.is_some()) - })?; - Ok(json!({ "selected": selected })) -} - -fn parse_color(p: &Value) -> [f32; 3] { - match p.get("color") { - Some(Value::Array(a)) if a.len() >= 3 => [0, 1, 2].map(|i| a[i].as_f64().unwrap_or(0.0) as f32), - Some(Value::String(h)) => { - let h = h.trim_start_matches('#'); - let c = |i: usize| h.get(i..i + 2).and_then(|x| u8::from_str_radix(x, 16).ok()).map_or(0.0, |v| f32::from(v) / 255.0); - [c(0), c(2), c(4)] - } - _ => [0.0; 3], - } -} - -/// Eyedropper samples from `key` (`[[x, y], …]` in document pixels): the colour under each point -/// and where it was picked (area-local, for Localized Color Clusters). -fn eyedropper_samples(p: &Value, key: &str, area: Rect, px: &[[f32; 4]], bad: &impl Fn(String) -> EngineError) -> Result> { - let Some(pts) = p.get(key) else { return Ok(Vec::new()) }; - let pts = pts.as_array().ok_or_else(|| bad(format!("`{key}` must be [[x, y], …]")))?; - let w = area.width() as usize; - let mut out = Vec::with_capacity(pts.len().min(4096)); - for pt in pts { - let xy = pt.as_array().and_then(|a| match a.as_slice() { - [x, y] => Some((x.as_f64()?, y.as_f64()?)), - _ => None, - }); - let Some((x, y)) = xy.filter(|(x, y)| x.is_finite() && y.is_finite()) else { - return Err(bad(format!("bad point {pt} in `{key}` (want [x, y])"))); - }; - let (xi, yi) = (x.floor() as i32, y.floor() as i32); - let q = if area.contains(xi, yi) { px.get((yi - area.y0) as usize * w + (xi - area.x0) as usize) } else { None }; - let Some(&[r, g, b, _]) = q else { - return Err(bad(format!("point [{x}, {y}] in `{key}` is outside the canvas"))); - }; - out.push(sel::RangeSample { color: [r, g, b], at: Some(((xi - area.x0) as f32, (yi - area.y0) as f32)) }); - } - Ok(out) -} - -/// Composite RGB (the compositor's output profile for the document) → CIE Lab D50. -fn lab_transform(s: &Session) -> Result> { - let d = s.active().ok_or(EngineError::NoDocument)?; - let src = crate::color_cmds::composite_profile(&d.doc); - photocraft_cms::cached(&src, photocraft_cms::Builtin::LabD50.profile(), photocraft_cms::TransformOptions::default()) - .map_err(|e| EngineError::Other(format!("colour management: {e}"))) -} - -/// The Lab profile's normalised encoding (ICC v4) → L 0–100, a and b −128–127. -fn decode_lab(v: [f32; 3]) -> [f32; 3] { - [v[0] * 100.0, v[1] * 255.0 - 128.0, v[2] * 255.0 - 128.0] -} - -fn colour_to_lab(t: &photocraft_cms::Transform, rgb: [f32; 3]) -> [f32; 3] { - let mut out = [0.0f32; 3]; - t.eval(&rgb.map(|v| v.clamp(0.0, 1.0)), &mut out); - decode_lab(out) -} - -/// RGBA pixels → Lab + alpha (L, a, b, alpha). -fn pixels_to_lab(t: &photocraft_cms::Transform, px: &[[f32; 4]]) -> Vec<[f32; 4]> { - let src: Vec<[f32; 4]> = px.iter().map(|p| [p[0].clamp(0.0, 1.0), p[1].clamp(0.0, 1.0), p[2].clamp(0.0, 1.0), p[3]]).collect(); - let mut out = vec![[0.0f32; 4]; px.len()]; - t.convert_f32(src.as_flattened(), 4, out.as_flattened_mut(), 4, true); - for p in &mut out { - let [l, a, b] = decode_lab([p[0], p[1], p[2]]); - *p = [l, a, b, p[3]]; - } - out -} - -/// Prepared Sampled Colors query shared by the command and its interactive preview. -/// Samples always come from the original document; reducing an image must not change them. -pub struct ColorRangeSamples { - to_lab: std::sync::Arc, - range: sel::LabRange, - grid: bool, - fuzziness: f32, - localized: Option, - plus_at: Vec<(f32, f32)>, -} - -impl ColorRangeSamples { - /// Prepare the query without allocating a full-resolution composite. Point samples use - /// exactly the same compositor/profile as the final selection. - pub fn new(s: &Session, p: &Value) -> Result { - let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; - let area = doc.bounds(); - let bad = |msg: String| EngineError::BadParams { cmd: "select.colorRange".into(), msg }; - let sample = |key: &str| -> Result> { - let Some(pts) = p.get(key) else { return Ok(Vec::new()) }; - let pts = pts.as_array().ok_or_else(|| bad(format!("`{key}` must be [[x, y], …]")))?; - let mut samples = Vec::new(); - for point in pts { - let q = point.as_array().and_then(|v| match v.as_slice() { - [x, y] => Some((x.as_f64()?, y.as_f64()?)), - _ => None, - }); - let Some((x, y)) = q.filter(|(x, y)| x.is_finite() && y.is_finite()) else { - return Err(bad(format!("bad point {point} in `{key}` (want [x, y])"))); - }; - let (x, y) = (x.floor() as i32, y.floor() as i32); - if !area.contains(x, y) { - return Err(bad(format!("point [{x}, {y}] in `{key}` is outside the canvas"))); - } - let r = Rect::from_xywh(x, y, 1, 1); - let pixel = if !b(p, "sampleAllLayers", true) { - s.active().and_then(|d| d.active_layer.and_then(|id| d.doc.layer(id))).and_then(|l| l.surface()).map(|surf| { - let mut px = [[0.0; 4]]; - surf.read_rgba_into(r, &mut px); - px[0] - }) - } else { - None - }; - let px = match pixel { - Some(px) => px, - None => photocraft_compose::render(doc, r).px.first().copied().unwrap_or([0.0; 4]), - }; - samples.push(sel::RangeSample { color: [px[0], px[1], px[2]], at: Some(((x - area.x0) as f32, (y - area.y0) as f32)) }); - } - Ok(samples) - }; - Self::with_samples(s, p, area, &sample("points")?, &sample("subtractPoints")?) - } - - fn with_samples(s: &Session, p: &Value, area: Rect, plus: &[sel::RangeSample], minus: &[sel::RangeSample]) -> Result { - let bad = |msg: String| EngineError::BadParams { cmd: "select.colorRange".into(), msg }; - let fuzz = |d: f32| f(p, "fuzziness", d).max(0.0); - // The order the eyedropper clicks came in ("+" a point, "-" a subtracted point): - // Photoshop applies them one after another. Without it, all additions come first. - let order: Vec = match p.get("order") { - None => std::iter::repeat_n(true, plus.len()).chain(std::iter::repeat_n(false, minus.len())).collect(), - Some(o) => { - let o = o.as_array().ok_or_else(|| bad("`order` must be a list of \"+\" and \"-\"".into()))?; - let order = o - .iter() - .map(|v| match v.as_str() { - Some("+") => Ok(true), - Some("-") => Ok(false), - _ => Err(bad(format!("bad entry {v} in `order` (want \"+\" or \"-\")"))), - }) - .collect::>>()?; - if order.iter().filter(|x| **x).count() != plus.len() || order.iter().filter(|x| !**x).count() != minus.len() { - return Err(bad("`order` must list each of `points` (\"+\") and `subtractPoints` (\"-\") once".into())); - } - order - } - }; - let mut fixed: Vec<[f32; 3]> = Vec::new(); - if let Some(cs) = p.get("colors") { - let cs = cs.as_array().ok_or_else(|| bad("`colors` must be a list of colours".into()))?; - fixed.extend(cs.iter().map(|c| parse_color(&json!({ "color": c })))); - } - if p.get("color").is_some() { - fixed.push(parse_color(p)); - } - // Localized Color Clusters: Range is a percentage of the canvas's longer side. - let plus_at: Vec<(f32, f32)> = plus.iter().filter_map(|x| x.at).collect(); - let localized = if b(p, "localized", false) { - if plus_at.is_empty() { - return Err(bad("localized clusters need eyedropper `points`".into())); - } - Some(f(p, "range", 100.0).clamp(0.0, 100.0) / 100.0 * area.width().max(area.height()) as f32) - } else { - None - }; - // Photoshop compares colours in Lab, through the document's profile - // (sel::lab_range_coverage). The samples span one Lab box; "Add to Sample" grows it, - // "Subtract from Sample" reshapes it (sel::LabRange::subtract). - let to_lab = lab_transform(s)?; - // 8-bit documents are compared on the 8-bit Lab grid, samples and pixels alike. - let grid = s.active().is_some_and(|d| d.doc.depth == photocraft_doc::SampleType::U8); - let q = |c: [f32; 3]| if grid { sel::quantize_lab8(c) } else { c }; - let colour_to_lab = |t: &photocraft_cms::Transform, c: [f32; 3]| q(colour_to_lab(t, c)); - let foreground = || { - let [r, g, b, _] = s.tools.foreground; - sel::LabRange::point(colour_to_lab(&to_lab, [r, g, b])) - }; - let fixed_lab: Vec<[f32; 3]> = fixed.iter().map(|c| colour_to_lab(&to_lab, *c)).collect(); - let mut range = sel::LabRange::spanning(&fixed_lab); - let (mut pi, mut mi) = (plus.iter(), minus.iter()); - for add in order { - if add { - if let Some(x) = pi.next() { - let c = colour_to_lab(&to_lab, x.color); - range = Some(range.map_or(sel::LabRange::point(c), |r| r.grow(&c))); - } - } else if let Some(x) = mi.next() { - range = Some(range.unwrap_or_else(foreground).subtract(&colour_to_lab(&to_lab, x.color), fuzz(40.0))); - } - } - let range = range.unwrap_or_else(foreground); - Ok(Self { to_lab, range, grid, fuzziness: fuzz(40.0), localized, plus_at }) - } - - /// Coverage of a composite rectangle. `scale` is the original document pixels represented - /// by one input pixel; `origin` is in original document pixels (for a visible canvas crop). - pub fn coverage(&self, px: &[[f32; 4]], width: usize, scale: f32, origin: [f32; 2]) -> Vec { - let mut lab = pixels_to_lab(&self.to_lab, px); - if self.grid { - for p in &mut lab { - let [l, a, b] = sel::quantize_lab8([p[0], p[1], p[2]]); - *p = [l, a, b, p[3]]; - } - } - let scale = if scale.is_finite() && scale > 0.0 { scale } else { 1.0 }; - let points: Vec<_> = self.plus_at.iter().map(|(x, y)| ((x - origin[0]) / scale, (y - origin[1]) / scale)).collect(); - sel::color_range_lab(&lab, width, &self.range, self.fuzziness, self.grid, self.localized.map(|r| (r / scale, points.as_slice()))) - } -} - -fn color_range(s: &mut Session, p: &Value) -> Result { - const CMD: &str = "select.colorRange"; - let bad = |msg: String| EngineError::BadParams { cmd: CMD.into(), msg }; - let preset = p.get("select").map_or(Some("sampledColors"), Value::as_str).ok_or_else(|| bad("`select` must be a string".into()))?; - let invert = b(p, "invert", false); - let selection_mode = mode(p); - let fuzz = |d: f32| f(p, "fuzziness", d).max(0.0); - // Photoshop's Detect Faces needs a face detector, which there is none of yet (#4455). - if b(p, "detectFaces", false) { - return Err(bad("detectFaces: face detection isn't available yet; select without it".into())); - } - let (area, mut mask) = match preset { - "sampledColors" => { - let (area, px) = sample_pixels(s, b(p, "sampleAllLayers", true))?; - let w = area.width() as usize; - // The dialog's eyedroppers: colours picked on the image, at their positions. - // Like Photoshop's, they may sample anywhere on the canvas: an active selection only - // limits the result (scope_color_range), not where colours are picked (#5244). - let plus = eyedropper_samples(p, "points", area, &px, &bad)?; - let minus = eyedropper_samples(p, "subtractPoints", area, &px, &bad)?; - let query = ColorRangeSamples::with_samples(s, p, area, &plus, &minus)?; - let mask = query.coverage(&px, w, 1.0, [0.0, 0.0]); - (area, mask) - } - "reds" | "yellows" | "greens" | "cyans" | "blues" | "magentas" => { - let center = match preset { - "reds" => 0.0, - "yellows" => 60.0, - "greens" => 120.0, - "cyans" => 180.0, - "blues" => 240.0, - _ => 300.0, - }; - let (area, px) = sample_pixels(s, b(p, "sampleAllLayers", true))?; - (area, sel::hue_range(&px, center)) - } - "skinTones" => { - let (area, px) = sample_pixels(s, b(p, "sampleAllLayers", true))?; - (area, sel::skin_tones(&px, fuzz(40.0).min(200.0))) - } - "highlights" | "midtones" | "shadows" => { - // Range in levels (Highlights / Shadows: one value, Midtones: [low, high]); Fuzziness - // is a percentage of the tonal scale. - let level = |v: &Value| v.as_f64().filter(|x| (0.0..=255.0).contains(x)).map(|x| x as f32); - let r = p.get("tonalRange"); - let (lo, hi) = match (preset, r) { - ("shadows", None) => (0.0, 65.0), - ("highlights", None) => (190.0, 255.0), - (_, None) => (105.0, 150.0), - ("shadows", Some(v)) => (0.0, level(v).ok_or_else(|| bad(format!("tonalRange: want a level 0..255 (got {v})")))?), - ("highlights", Some(v)) => (level(v).ok_or_else(|| bad(format!("tonalRange: want a level 0..255 (got {v})")))?, 255.0), - (_, Some(v)) => v - .as_array() - .and_then(|a| match a.as_slice() { - [l, h] => Some((level(l)?, level(h)?)), - _ => None, - }) - .filter(|(l, h)| l <= h) - .ok_or_else(|| bad(format!("tonalRange: want [low, high] levels 0..255 (got {v})")))?, - }; - let (area, px) = sample_pixels(s, b(p, "sampleAllLayers", true))?; - (area, sel::tone_range(&px, lo, hi, fuzz(20.0).min(100.0) / 100.0 * 255.0)) - } - "outOfGamut" => { - // Pixels the current proof setup (View › Proof Setup) can't reproduce, as the gamut - // warning shows them: judged on the composite. - let d = s.active().ok_or(EngineError::NoDocument)?; - let pv = s.color.proof(d.doc.id); - let (m, _) = crate::color_cmds::gamut_mask(&d.doc, &pv.setup, pv.gamut_threshold)?; - (d.doc.bounds(), m.iter().map(|v| f32::from(*v) / 255.0).collect()) - } - other => { - return Err(bad(format!( - "unknown select `{other}` (sampledColors, reds, yellows, greens, cyans, blues, magentas, highlights, midtones, shadows, skinTones, outOfGamut)" - ))); - } - }; - if invert { - for v in &mut mask { - *v = 1.0 - *v; - } - } - // Invert the colour result first, then constrain it to the original selection. - // Add mode must still be able to extend an existing selection intentionally. - scope_color_range(&mut mask, &s.active().ok_or(EngineError::NoDocument)?.doc, area, selection_mode); - set_selection(s, "Color Range", area, mask, selection_mode) -} - -fn modify(s: &mut Session, p: &Value, op: &str) -> Result { - // The dialogs' ranges (Photoshop's limits); anything else is refused, never clamped silently. - let (min, max): (f32, f32) = match op { - "border" => (1.0, 200.0), - "feather" => (0.1, 1000.0), - _ => (1.0, 500.0), - }; - let r = f(p, "radius", 1.0); - // Below the dialog's minimum (a negative or zero radius, #993) or above its maximum is - // refused: a clamp to 0 left the selection alone (Expand, Contract) or cleared it (Border) - // while reporting success. - if !(min..=max).contains(&r) { - return Err(EngineError::BadParams { cmd: format!("select.modify.{op}"), msg: format!("radius must be a number in {min}..{max}") }); - } - // Photoshop's "Apply effect at canvas bounds": when on, the canvas edge is a selection edge - // (Select All then Contract shrinks from the edges); when off, the selection is taken to - // continue past the canvas. Border has no such option: its band always follows the canvas edge, - // or a Select All would border to nothing. - let at_bounds = op == "border" || b(p, "applyAtCanvasBounds", false); - let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; - let area = doc.bounds(); - if area.size().area() > MAX_MODIFY_PIXELS as u64 { - return Err(EngineError::BadParams { cmd: format!("select.modify.{op}"), msg: "the selection is too large to modify".into() }); - } - let (_, m) = current_mask(doc); - let (w, h) = (area.width() as usize, area.height() as usize); - // Feather reaches 3σ = 3 r (σ = r, as in Photoshop); the others reach r. A margin past that - // keeps the canvas edge out of reach. A selection clear of the canvas edge needs none: both - // readings agree there. - let reach = if op == "feather" { r * 3.0 } else { r }; - let pad = if touches_edge(&m, w, h) { reach.ceil() as usize + 2 } else { 0 }; - let grown = |n: usize| pad.checked_mul(2).and_then(|p| n.checked_add(p)); - let (Some(pw), Some(ph)) = (grown(w), grown(h)) else { - return Err(EngineError::BadParams { cmd: format!("select.modify.{op}"), msg: "the selection is too large to modify".into() }); - }; - if pw.checked_mul(ph).is_none_or(|n| n > MAX_MODIFY_PIXELS) { - return Err(EngineError::BadParams { cmd: format!("select.modify.{op}"), msg: "the selection is too large to modify".into() }); - } - // Unpadded (the usual case) the mask is used as it is: two serial full-canvas copies were - // most of a 24 MP Feather or Smooth (#211). - let padded = if pad == 0 { m } else { pad_mask(&m, w, h, pad, at_bounds) }; - let out = match op { - "expand" => sel::expand(&padded, pw, ph, r), - "contract" => sel::contract(&padded, pw, ph, r), - "border" => sel::border(&padded, pw, ph, r), - "smooth" => sel::smooth(&padded, pw, ph, r), - _ => sel::feather(&padded, pw, ph, r), - }; - let out = if pad == 0 { out } else { crop_mask(&out, pw, pad, w, h) }; - let label = match op { - "expand" => "Expand Selection", - "contract" => "Contract Selection", - "border" => "Border Selection", - "smooth" => "Smooth Selection", - _ => "Feather Selection", - }; - set_selection(s, label, area, out, SelectionMode::Replace) -} - -/// The largest padded mask Modify works on (a 300000 × 300000 canvas is 9e10 pixels; this caps a -/// padded copy at ~4 GB of f32, beyond which the edit is refused rather than aborting on allocation). -const MAX_MODIFY_PIXELS: usize = 1 << 30; - -/// Whether any pixel on the outermost rows or columns of `m` (`w`×`h`) is selected. -fn touches_edge(m: &[f32], w: usize, h: usize) -> bool { - let sel = |x: usize, y: usize| m.get(y * w + x).is_some_and(|v| *v > 0.0); - (0..w).any(|x| sel(x, 0) || sel(x, h.saturating_sub(1))) || (0..h).any(|y| sel(0, y) || sel(w.saturating_sub(1), y)) -} - -/// `m` (`w`×`h`) with a `pad`-pixel margin: unselected when `outside_empty`, else the nearest -/// edge pixel repeated (the selection continues past the canvas). -fn pad_mask(m: &[f32], w: usize, h: usize, pad: usize, outside_empty: bool) -> Vec { - let pw = w + 2 * pad; - let mut out = vec![0.0f32; pw * (h + 2 * pad)]; - if w == 0 || h == 0 { - return out; - } - // Row by row (a copy and two fills), not sample by sample (#211). - for (py, row) in out.chunks_exact_mut(pw).enumerate() { - if outside_empty && !(pad..pad + h).contains(&py) { - continue; - } - let y = py.saturating_sub(pad).min(h - 1); - let (Some(src), Some((left, rest))) = (m.get(y * w..(y + 1) * w), row.split_at_mut_checked(pad)) else { continue }; - let Some((mid, right)) = rest.split_at_mut_checked(w) else { continue }; - mid.copy_from_slice(src); - if !outside_empty { - left.fill(src.first().copied().unwrap_or(0.0)); - right.fill(src.last().copied().unwrap_or(0.0)); - } - } - out -} - -/// The `w`×`h` centre of a mask padded by `pad_mask`. -fn crop_mask(m: &[f32], pw: usize, pad: usize, w: usize, h: usize) -> Vec { - let mut out = Vec::with_capacity(w.saturating_mul(h)); - for row in m.chunks_exact(pw.max(1)).skip(pad).take(h) { - out.extend_from_slice(row.get(pad..pad + w).unwrap_or_default()); - } - out -} - -/// Grow (contiguous) / Similar (anywhere): pixels whose colour lies within -/// the selected pixels' colour range widened by the tolerance. -fn grow_similar(s: &mut Session, p: &Value, contiguous: bool) -> Result { - let tol = f(p, "tolerance", 32.0) / 255.0; - let (area, px) = sample_pixels(s, b(p, "sampleAllLayers", false))?; - let (_, m) = current_mask(&s.active().ok_or(EngineError::NoDocument)?.doc); - let (mut lo, mut hi) = ([f32::MAX; 4], [f32::MIN; 4]); - for (q, v) in px.iter().zip(&m) { - if *v >= 0.5 { - for c in 0..4 { - lo[c] = lo[c].min(q[c]); - hi[c] = hi[c].max(q[c]); - } - } - } - if lo[0] > hi[0] { - return Err(EngineError::Other("selection is empty".into())); - } - let inside = |q: &[f32; 4]| (0..4).all(|c| q[c] >= lo[c] - tol - 1e-6 && q[c] <= hi[c] + tol + 1e-6); - let (w, h) = (area.width() as usize, area.height() as usize); - let mut out: Vec = m.iter().map(|v| if *v >= 0.5 { 1.0 } else { 0.0 }).collect(); - if contiguous { - let mut stack: Vec = (0..out.len()).filter(|i| out[*i] > 0.0).collect(); - while let Some(i) = stack.pop() { - let (x, y) = (i % w, i / w); - let n = [(x > 0).then(|| i - 1), (x + 1 < w).then(|| i + 1), (y > 0).then(|| i - w), (y + 1 < h).then(|| i + w)]; - for j in n.into_iter().flatten() { - if out[j] == 0.0 && inside(&px[j]) { - out[j] = 1.0; - stack.push(j); - } - } - } - } else { - for (o, q) in out.iter_mut().zip(&px) { - if inside(q) { - *o = 1.0; - } - } - } - set_selection(s, if contiguous { "Grow" } else { "Similar" }, area, out, SelectionMode::Replace) -} - -fn lasso(s: &mut Session, p: &Value) -> Result { - let pts: Vec<(f32, f32)> = p - .get("points") - .and_then(Value::as_array) - .map(|a| a.iter().filter_map(|q| Some((q.get(0)?.as_f64()? as f32, q.get(1)?.as_f64()? as f32))).collect()) - .unwrap_or_default(); - if pts.len() < 3 { - return Err(EngineError::BadParams { cmd: "select.lasso".into(), msg: "needs at least 3 points".into() }); - } - polygon_selection(s, "select.lasso", "Lasso", &pts, p) -} - -/// Selects the polygon `pts` with the lasso tools' `mode`, `antiAlias` and `feather` params, as -/// one history step called `label`. -pub(crate) fn polygon_selection(s: &mut Session, cmd: &str, label: &str, pts: &[(f32, f32)], p: &Value) -> Result { - let feather = f(p, "feather", 0.0); - // Select › Modify › Feather's range. - if !(0.0..=1000.0).contains(&feather) { - return Err(EngineError::BadParams { cmd: cmd.into(), msg: "feather must be a number in 0..1000".into() }); - } - let area = s.active().ok_or(EngineError::NoDocument)?.doc.bounds(); - if feather > 0.0 { - // The blur spreads past the polygon and isn't bit-identical over a smaller window. - let mut mask = sel::polygon(pts, area, b(p, "antiAlias", true)); - mask = sel::feather(&mask, area.width() as usize, area.height() as usize, feather); - return set_selection(s, label, area, mask, mode(p)); - } - // Only the rows the polygon spans (#4532): rows outside it are empty, and full-width rows - // keep `polygon`'s coverage bit-identical (its x arithmetic is relative to the area's left - // edge; its y samples are whole rows plus the same sub-row fractions). - let band = polygon_rows(pts, area); - let mask = sel::polygon(pts, band, b(p, "antiAlias", true)); - let m = mode(p); - let selected = s.edit(label, |doc, _| { - doc.selection = combine_band(doc.selection.as_ref(), &mask, band, m); - Ok(doc.selection.is_some()) - })?; - Ok(json!({ "selected": selected })) -} - -/// The full-width rows of `area` that points `pts` span (empty when none are finite). -fn polygon_rows(pts: &[(f32, f32)], area: Rect) -> Rect { - let ys = pts.iter().map(|p| p.1).filter(|y| y.is_finite()); - let (lo, hi) = ys.fold((f32::INFINITY, f32::NEG_INFINITY), |(lo, hi), y| (lo.min(y), hi.max(y))); - if lo > hi { - return Rect::EMPTY; - } - let clamp = |v: f32| v.clamp(area.y0 as f32, area.y1 as f32) as i32; - let (y0, y1) = (clamp(lo.floor()), clamp(hi.ceil() + 1.0)); - if y0 >= y1 { Rect::EMPTY } else { Rect::new(area.x0, y0, area.x1, y1) } -} - -/// [`sel::combine`] of a mask covering only `band` (zero elsewhere), giving exactly what the -/// whole-canvas combine gives: Replace and Intersect are empty outside the band, and Add and -/// Subtract keep the old selection there. -fn combine_band(old: Option<&Surface>, mask: &[f32], band: Rect, m: SelectionMode) -> Option { - let inside = sel::combine(old, mask, band, m); - let Some(old) = old.filter(|_| matches!(m, SelectionMode::Add | SelectionMode::Subtract)) else { return inside }; - if band.is_empty() { - return Some(old.clone()); - } - let values = inside.map_or_else(|| vec![0.0; band.width() as usize * band.height() as usize], |w| w.read_region(band)); - let mut s = old.clone(); - s.write_region(band, &values); - s.prune(); - (s.tile_count() > 0).then_some(s) -} - -macro_rules! spec { - ($id:literal, $label:literal, [$($m:literal),*], $params:literal, $en:expr, $run:expr) => { - CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: None, params: $params, enabled: $en, run: $run, journal: true } - }; -} - -/// Selection command specs. -pub fn specs() -> Vec { - vec![ - spec!( - "select.magicWand", - "Magic Wand", - [], - r##"{"x":px,"y":px,"tolerance":0..255=32,"contiguous":bool=true,"antiAlias":bool=true,"sampleAllLayers":bool=false,"mode":"replace|add|subtract|intersect"="replace"} (samples the visible alpha, Quick Mask, or layer mask when that is the picture)"##, - has_doc, - magic_wand - ), - spec!( - "select.colorRange", - "Color Range…", - ["Select"], - r##"{"select":"sampledColors|reds|yellows|greens|cyans|blues|magentas|highlights|midtones|shadows|skinTones|outOfGamut"="sampledColors","color":"#rrggbb"=foreground,"colors":["#rrggbb",…]?,"points":[[x,y],…]? (eyedropper samples),"subtractPoints":[[x,y],…]? (minus eyedropper),"order":["+"|"-",…]? (click order of points and subtractPoints; default all points first),"fuzziness":0..200=40 (tones: 0..100 %=20),"detectFaces":bool=false (not available yet: refused),"localized":bool=false,"range":0..100=100 (% of the longer side),"tonalRange":level|[lo,hi] (shadows 65, highlights 190, midtones [105,150]),"invert":bool=false,"sampleAllLayers":bool=true,"mode":"replace|add|subtract|intersect"="replace"}"##, - has_doc, - color_range - ), - spec!("select.modify.border", "Border…", ["Select", "Modify"], r##"{"radius":1..200=1}"##, has_selection, |s, p| modify(s, p, "border")), - spec!("select.modify.smooth", "Smooth…", ["Select", "Modify"], r##"{"radius":1..500=1,"applyAtCanvasBounds":bool=false}"##, has_selection, |s, p| { - modify(s, p, "smooth") - }), - spec!("select.modify.expand", "Expand…", ["Select", "Modify"], r##"{"radius":1..500=1,"applyAtCanvasBounds":bool=false}"##, has_selection, |s, p| { - modify(s, p, "expand") - }), - spec!( - "select.modify.contract", - "Contract…", - ["Select", "Modify"], - r##"{"radius":1..500=1,"applyAtCanvasBounds":bool=false}"##, - has_selection, - |s, p| modify(s, p, "contract") - ), - spec!( - "select.modify.feather", - "Feather…", - ["Select", "Modify"], - r##"{"radius":0.1..1000=1,"applyAtCanvasBounds":bool=false}"##, - has_selection, - |s, p| modify(s, p, "feather") - ), - spec!("select.grow", "Grow", ["Select"], r##"{"tolerance":0..255=32,"sampleAllLayers":bool=false}"##, has_selection, |s, p| grow_similar(s, p, true)), - spec!("select.similar", "Similar", ["Select"], r##"{"tolerance":0..255=32,"sampleAllLayers":bool=false}"##, has_selection, |s, p| grow_similar( - s, p, false - )), - spec!( - "select.lasso", - "Lasso", - [], - r##"{"points":[[x,y],…],"mode":"replace|add|subtract|intersect"="replace","antiAlias":bool=true,"feather":px=0}"##, - has_doc, - lasso - ), - ] -} - -#[cfg(test)] -mod tests { - use super::*; - - fn session() -> Session { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 40, "height": 30})).unwrap(); - s.edit("paint", |doc, _| { - let bg = doc.layers[0].surface_mut().unwrap(); - bg.fill_rect(Rect::new(5, 5, 15, 15), &[1.0, 0.0, 0.0, 1.0]); - bg.fill_rect(Rect::new(25, 5, 35, 15), &[1.0, 0.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - s - } - - fn coverage(s: &Session, x: i32, y: i32) -> f32 { - s.active().unwrap().doc.selection.as_ref().map_or(0.0, |m| m.sample_channel(x, y, 0)) - } - - fn clear_selection(s: &mut Session) { - if s.active().unwrap().doc.selection.is_some() { - s.execute("select.deselect", json!({})).unwrap(); - } - } - - #[test] - fn color_range_skin_tones_selects_skin_not_cream_and_refuses_detect_faces() { - let mut s = session(); - let rgb = |c: [u8; 3]| [f32::from(c[0]) / 255.0, f32::from(c[1]) / 255.0, f32::from(c[2]) / 255.0, 1.0]; - s.edit("paint", |doc, _| { - let bg = doc.layers[0].surface_mut().unwrap(); - bg.fill_rect(Rect::new(0, 0, 40, 30), &rgb([252, 253, 247])); - bg.fill_rect(Rect::new(5, 5, 15, 15), &rgb([183, 119, 81])); - bg.fill_rect(Rect::new(25, 5, 35, 15), &rgb([231, 225, 202])); - Ok(()) - }) - .unwrap(); - s.execute("select.colorRange", json!({"select": "skinTones"})).unwrap(); - assert!(coverage(&s, 10, 10) > 0.95, "skin"); - assert!(coverage(&s, 30, 10) < 0.05, "cream"); - assert!(coverage(&s, 2, 2) < 0.05, "near-white background"); - // Subtracting skin from a selection of both squares keeps only the cream one. - s.execute("select.rect", json!({"x": 5, "y": 5, "width": 30, "height": 10})).unwrap(); - s.execute("select.colorRange", json!({"select": "skinTones", "mode": "subtract"})).unwrap(); - assert!(coverage(&s, 10, 10) < 0.05 && coverage(&s, 30, 10) > 0.95, "{} {}", coverage(&s, 10, 10), coverage(&s, 30, 10)); - let err = s.execute("select.colorRange", json!({"select": "skinTones", "detectFaces": true})).unwrap_err(); - assert!(err.to_string().contains("detectFaces"), "{err}"); - } - - #[test] - fn selection_sampling_refuses_oversized_canvases_before_reading_pixels() { - let mut s = Session::new(); - s.add_document( - photocraft_doc::Document::new( - "large", - photocraft_geom::Size::new(300_000, 300_000), - photocraft_color::ColorMode::Rgb, - photocraft_color::SampleType::U8, - ), - None, - ); - for all_layers in [false, true] { - assert!(sample_pixels(&s, all_layers).unwrap_err().to_string().contains("too large to sample")); - } - assert!(!s.active().unwrap().history.can_undo()); - } - - #[test] - fn selection_sampling_allocation_failure_keeps_the_selection() { - let mut s = session(); - s.execute("select.rect", json!({"x": 5, "y": 5, "width": 4, "height": 4})).unwrap(); - let before = s.active().unwrap().doc.clone(); - let history = s.active().unwrap().history.entries(); - crate::allocation::fail_next_for_test(); - let result = s.execute("select.similar", json!({"sampleAllLayers": false})); - let _ = crate::allocation::capacity::(0, "reset failpoint"); - assert!(result.is_err()); - assert_eq!(*s.active().unwrap().doc, *before); - assert_eq!(s.active().unwrap().history.entries(), history); - } - - #[test] - fn modify_rejects_oversized_canvases_before_reading_the_mask() { - let mut s = Session::new(); - let mut doc = photocraft_doc::Document::new( - "large", - photocraft_geom::Size::new(300_000, 300_000), - photocraft_color::ColorMode::Rgb, - photocraft_color::SampleType::U8, - ); - let mut selection = photocraft_raster::Surface::new(photocraft_color::PixelFormat::GRAY8); - selection.write_pixel(0, 0, &[1.0]); - doc.selection = Some(selection); - s.add_document(doc, None); - let before = s.active().unwrap().doc.clone(); - for op in ["expand", "contract", "border", "smooth", "feather"] { - let error = s.execute(&format!("select.modify.{op}"), json!({"radius": 1})).unwrap_err(); - assert!(error.to_string().contains("too large to modify")); - assert_eq!(*s.active().unwrap().doc, *before); - assert!(!s.active().unwrap().history.can_undo()); - } - } - - #[test] - fn color_range_replace_is_bounded_by_existing_selection() { - for params in [json!({"color": "#ff0000", "fuzziness": 0}), json!({"select": "reds"})] { - let mut s = session(); - // Both red squares match, but only the left is inside the original selection. - s.execute("select.rect", json!({"x": 5, "y": 5, "width": 10, "height": 10})).unwrap(); - s.execute("select.colorRange", params).unwrap(); - assert_eq!(coverage(&s, 10, 10), 1.0); - assert_eq!(coverage(&s, 30, 10), 0.0); - assert_eq!(coverage(&s, 2, 2), 0.0); - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(coverage(&s, 10, 10), 1.0); - assert_eq!(coverage(&s, 30, 10), 0.0); - } - } - - #[test] - fn color_range_invert_and_partial_masks_stay_within_prior_selection() { - let mut s = session(); - s.execute("select.rect", json!({"x": 5, "y": 5, "width": 10, "height": 10})).unwrap(); - s.execute("select.colorRange", json!({"select": "highlights", "invert": true})).unwrap(); - assert_eq!(coverage(&s, 10, 10), 1.0, "inverted white excludes the white background"); - assert_eq!(coverage(&s, 20, 20), 0.0, "invert must not select outside the old boundary"); - - let mut s = session(); - s.edit("soft selection", |doc, _| { - let mut mask = vec![0.0; 40 * 30]; - mask[10 * 40 + 10] = 128.0 / 255.0; - doc.selection = Some(sel::mask_to_surface(&mask, doc.bounds())); - Ok(()) - }) - .unwrap(); - s.execute("select.colorRange", json!({"select": "reds"})).unwrap(); - assert!((coverage(&s, 10, 10) - 128.0 / 255.0).abs() < 0.001); - assert_eq!(coverage(&s, 30, 10), 0.0); - } - - #[test] - fn color_range_eyedropper_samples_anywhere_but_the_result_stays_in_the_selection() { - // #5244: as in Photoshop, a colour picked outside the active selection is accepted; only - // the result is limited to the selection. - let mut s = session(); - s.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 30})).unwrap(); - let outside = json!({"points": [[30, 10]], "fuzziness": 0}); - assert!(ColorRangeSamples::new(&s, &outside).is_ok()); - s.execute("select.colorRange", outside).unwrap(); - assert_eq!(coverage(&s, 10, 10), 1.0, "the red inside the selection is selected"); - assert_eq!(coverage(&s, 30, 10), 0.0, "the sampled red outside it stays out"); - assert_eq!(coverage(&s, 2, 2), 0.0, "white is not the sampled colour"); - } - - #[test] - fn color_range_eyedropper_respects_selection_but_add_can_extend_it() { - let mut s = session(); - s.execute("select.rect", json!({"x": 5, "y": 5, "width": 10, "height": 10})).unwrap(); - s.execute("select.colorRange", json!({"points": [[10, 10]], "fuzziness": 0})).unwrap(); - assert_eq!(coverage(&s, 10, 10), 1.0); - assert_eq!(coverage(&s, 30, 10), 0.0); - - // Explicitly adding a matching colour is still allowed to grow the selection. - s.execute("select.colorRange", json!({"points": [[30, 10]], "fuzziness": 0, "mode": "add"})).unwrap(); - assert_eq!(coverage(&s, 10, 10), 1.0); - assert_eq!(coverage(&s, 30, 10), 1.0); - - clear_selection(&mut s); - s.execute("select.colorRange", json!({"color": "#ff0000", "fuzziness": 0})).unwrap(); - assert_eq!(coverage(&s, 30, 10), 1.0, "an unbounded color range still searches the canvas"); - } - - #[test] - fn magic_wand_selects_the_visible_alpha_or_mask_not_the_rgb() { - let mut s = session(); - // Alpha covers the first red square and the pixels beside it. RGB would stop at the red. - s.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap(); - s.execute("channel.new", json!({"fill": "selection", "name": "Alpha"})).unwrap(); - s.execute("select.magicWand", json!({"x": 7, "y": 7, "tolerance": 0, "antiAlias": false})).unwrap(); - assert_eq!(coverage(&s, 7, 7), 1.0); - assert_eq!(coverage(&s, 2, 2), 1.0, "the white alpha includes pixels that are not the red square"); - assert_eq!(coverage(&s, 30, 10), 0.0, "outside the alpha stays unselected"); - // Colour channels back on: the wand reads RGB again. - s.execute("channel.setVisible", json!({"channel": "composite", "visible": true})).unwrap(); - s.execute("channel.setVisible", json!({"channel": 0, "visible": false})).unwrap(); - s.execute("select.magicWand", json!({"x": 7, "y": 7, "tolerance": 0, "antiAlias": false})).unwrap(); - assert_eq!(coverage(&s, 7, 7), 1.0); - assert_eq!(coverage(&s, 2, 2), 0.0, "RGB sampling stops at the red square"); - // Eyes off again, Alpha still the picture. - s.execute("channel.setVisible", json!({"channel": 0, "visible": true})).unwrap(); - s.execute("channel.setVisible", json!({"channel": "composite", "visible": false})).unwrap(); - s.execute("select.magicWand", json!({"x": 7, "y": 7, "tolerance": 0, "antiAlias": false})).unwrap(); - assert_eq!(coverage(&s, 2, 2), 1.0); - - let mut s = session(); - s.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap(); - s.execute("layer.layerMask.revealSelection", json!({})).unwrap(); - s.execute("view.layerMask", json!({"mode": "gray"})).unwrap(); - s.execute("select.magicWand", json!({"x": 7, "y": 7, "tolerance": 0, "antiAlias": false})).unwrap(); - assert_eq!(coverage(&s, 2, 2), 1.0, "gray mask view selects the mask"); - assert_eq!(coverage(&s, 30, 10), 0.0); - s.execute("view.layerMask", json!({"mode": "off"})).unwrap(); - for name in ["red", "green", "blue"] { - s.execute("channel.setVisible", json!({"channel": name, "visible": false})).unwrap(); - } - s.execute("select.magicWand", json!({"x": 7, "y": 7, "tolerance": 0, "antiAlias": false})).unwrap(); - assert_eq!(coverage(&s, 2, 2), 1.0, "a layer mask shown alone is what the wand reads"); - assert_eq!(coverage(&s, 30, 10), 0.0); - } - - #[test] - fn magic_wand_contiguous_and_modes() { - let mut s = session(); - s.execute("select.magicWand", json!({"x": 7, "y": 7, "antiAlias": false})).unwrap(); - assert_eq!(coverage(&s, 10, 10), 1.0); - assert_eq!(coverage(&s, 30, 10), 0.0); - s.execute("select.magicWand", json!({"x": 30, "y": 7, "mode": "add", "antiAlias": false})).unwrap(); - assert_eq!(coverage(&s, 30, 10), 1.0); - s.execute("select.magicWand", json!({"x": 7, "y": 7, "mode": "subtract", "antiAlias": false})).unwrap(); - assert_eq!(coverage(&s, 10, 10), 0.0); - s.execute("select.magicWand", json!({"x": 7, "y": 7, "contiguous": false, "antiAlias": false})).unwrap(); - assert_eq!(coverage(&s, 30, 10), 1.0); - } - - #[test] - fn color_range_prepared_query_matches_the_command_at_all_depths() { - use photocraft_doc::{Color, ColorMode, SampleType, Size}; - for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { - for profile in [None, Some(photocraft_cms::Builtin::DisplayP3.profile().to_bytes())] { - let mut doc = Document::with_background("samples", Size::new(24, 12), ColorMode::Rgb, depth, Color::WHITE); - doc.icc_profile = profile; - let layer = doc.layers[0].surface_mut().unwrap(); - layer.fill_rect(Rect::new(0, 0, 8, 12), &[0.65, 0.3, 0.2, 1.0]); - layer.fill_rect(Rect::new(8, 0, 16, 12), &[0.2, 0.3, 0.65, 1.0]); - let mut s = Session::new(); - s.add_document(doc, None); - for p in [ - json!({"points": [[2, 3]], "fuzziness": 0}), - json!({"points": [[2, 3], [10, 3]], "subtractPoints": [[10, 3]], "order": ["+", "+", "-"], "fuzziness": 40}), - json!({"points": [[2, 3]], "localized": true, "range": 50, "fuzziness": 80}), - ] { - clear_selection(&mut s); - let q = ColorRangeSamples::new(&s, &p).unwrap(); - let doc = s.active().unwrap().doc.clone(); - let pixels = photocraft_compose::render(&doc, doc.bounds()); - let preview = q.coverage(&pixels.px, 24, 1.0, [0.0, 0.0]); - s.execute("select.colorRange", p).unwrap(); - let actual = current_mask(&s.active().unwrap().doc).1; - for (shown, selected) in preview.iter().zip(actual) { - let rounded = (shown.clamp(0.0, 1.0) * 255.0 + 0.5).floor() / 255.0; - assert_eq!(rounded, selected, "{depth:?}: original-pixel preview and OK differ"); - } - } - } - } - } - - #[test] - fn color_range_prepared_query_samples_visible_layers_not_the_active_layer() { - use photocraft_doc::{Layer, LayerContent}; - let mut s = session_colours(); - let doc = s.active().unwrap().doc.clone(); - let mut top = Layer::new("blue foreground", LayerContent::Raster(doc.layers[0].surface().unwrap().clone())); - top.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 40, 30), &[0.0, 0.0, 1.0, 1.0]); - let mut hidden = Layer::new("hidden green", LayerContent::Raster(top.surface().unwrap().clone())); - hidden.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 40, 30), &[0.0, 1.0, 0.0, 1.0]); - hidden.visible = false; - s.edit("layers", |doc, _| { - doc.layers.push(top); - doc.layers.push(hidden); - Ok(()) - }) - .unwrap(); - for all_layers in [false, true] { - clear_selection(&mut s); - let p = json!({"points": [[7, 7]], "sampleAllLayers": all_layers, "fuzziness": 0}); - let query = ColorRangeSamples::new(&s, &p).unwrap(); - let (area, px) = sample_pixels(&s, all_layers).unwrap(); - let shown = query.coverage(&px, area.width() as usize, 1.0, [0.0, 0.0]); - s.execute("select.colorRange", p).unwrap(); - assert_eq!(shown[7 * 40 + 7], coverage(&s, 7, 7)); - assert_eq!(shown[24 * 40 + 10], coverage(&s, 10, 24)); - } - for p in [json!({"points": [[-1, 0]]}), json!({"points": [[40, 1]]}), json!({"points": "wrong"}), json!({"points": [[null, 0]]})] { - assert!(ColorRangeSamples::new(&s, &p).is_err(), "{p}"); - } - } - - #[test] - fn color_range_selects_by_colour() { - let mut s = session(); - s.execute("select.colorRange", json!({"color": "#ff0000", "fuzziness": 40})).unwrap(); - // The sampled colour itself is fully selected (as with Photoshop's eyedropper). - assert_eq!(coverage(&s, 10, 10), 1.0); - assert_eq!(coverage(&s, 20, 20), 0.0); - s.execute("select.colorRange", json!({"color": "#ff0000", "fuzziness": 100})).unwrap(); - assert_eq!(coverage(&s, 10, 10), 1.0); - assert_eq!(coverage(&s, 20, 20), 0.0); - } - - #[test] - fn color_range_compares_in_lab_like_photoshop() { - // Photoshop weighs hue (Lab a/b) three times as much as lightness; a per-channel RGB - // distance can't tell a lighter shade from a redder one. - let mut s = Session::new(); - s.execute("file.new", json!({"width": 30, "height": 10})).unwrap(); - s.edit("paint", |doc, _| { - let bg = doc.layers[0].surface_mut().unwrap(); - let v = |c: u8| f32::from(c) / 255.0; - bg.fill_rect(Rect::new(0, 0, 10, 10), &[v(200), v(140), v(120), 1.0]); // skin - bg.fill_rect(Rect::new(10, 0, 20, 10), &[v(220), v(160), v(140), 1.0]); // lighter skin - bg.fill_rect(Rect::new(20, 0, 30, 10), &[v(220), v(140), v(120), 1.0]); // redder skin - Ok(()) - }) - .unwrap(); - s.execute("select.colorRange", json!({"points": [[5, 5]], "fuzziness": 40})).unwrap(); - assert!(coverage(&s, 5, 5) > 0.98); - // Both differ from the sample by 20 levels in one RGB channel, yet the lighter one is - // kept clearly more (about 0.55 vs 0.31). - let (lighter, redder) = (coverage(&s, 15, 5), coverage(&s, 25, 5)); - assert!(lighter > redder + 0.15 && redder > 0.0, "lighter {lighter}, redder {redder}"); - } - - #[test] - fn color_range_fuzziness_zero_selects_exact_match_only() { - // Sampled Colors at Fuzziness 0 selects only the exact match (TOOL-214-3, #214). - let mut s = Session::new(); - s.execute("file.new", json!({"width": 50, "height": 10})).unwrap(); - s.edit("paint", |doc, _| { - let bg = doc.layers[0].surface_mut().unwrap(); - let v = |c: u8| f32::from(c) / 255.0; - // Exact target color [200, 140, 120] - bg.fill_rect(Rect::new(0, 0, 10, 10), &[v(200), v(140), v(120), 1.0]); - // Off by 1 level in red [201, 140, 120] - bg.fill_rect(Rect::new(10, 0, 20, 10), &[v(201), v(140), v(120), 1.0]); - // Off by 1 level in green [200, 141, 120] - bg.fill_rect(Rect::new(20, 0, 30, 10), &[v(200), v(141), v(120), 1.0]); - // Off by 2 levels in blue [200, 140, 122] (crosses 8-bit Lab grid threshold) - bg.fill_rect(Rect::new(30, 0, 40, 10), &[v(200), v(140), v(122), 1.0]); - // Exact target color again at a different position - bg.fill_rect(Rect::new(40, 0, 50, 10), &[v(200), v(140), v(120), 1.0]); - Ok(()) - }) - .unwrap(); - - // Sampled via eyedropper point at [5, 5] with Fuzziness 0 - s.execute("select.colorRange", json!({"points": [[5, 5]], "fuzziness": 0})).unwrap(); - assert_eq!(coverage(&s, 5, 5), 1.0, "sampled pixel itself is fully selected"); - assert_eq!(coverage(&s, 45, 5), 1.0, "identical color elsewhere on canvas is fully selected"); - assert_eq!(coverage(&s, 15, 5), 0.0, "1 level off in red is unselected at fuzziness 0"); - assert_eq!(coverage(&s, 25, 5), 0.0, "1 level off in green is unselected at fuzziness 0"); - assert_eq!(coverage(&s, 35, 5), 0.0, "1 level off in blue is unselected at fuzziness 0"); - - // Sampled via hex color with Fuzziness 0 - s.execute("select.colorRange", json!({"color": "#c88c78", "fuzziness": 0})).unwrap(); - assert_eq!(coverage(&s, 5, 5), 1.0, "exact color match from hex is fully selected"); - assert_eq!(coverage(&s, 45, 5), 1.0, "identical color elsewhere on canvas is fully selected"); - assert_eq!(coverage(&s, 15, 5), 0.0, "1 level off in red is unselected for hex at fuzziness 0"); - assert_eq!(coverage(&s, 25, 5), 0.0, "1 level off in green is unselected for hex at fuzziness 0"); - assert_eq!(coverage(&s, 35, 5), 0.0, "1 level off in blue is unselected for hex at fuzziness 0"); - } - - /// Red squares (from `session`), a blue square, a black and a mid-grey strip on white. - fn session_colours() -> Session { - let mut s = session(); - s.edit("paint", |doc, _| { - let bg = doc.layers[0].surface_mut().unwrap(); - bg.fill_rect(Rect::new(5, 20, 15, 28), &[0.0, 0.0, 1.0, 1.0]); - bg.fill_rect(Rect::new(20, 20, 25, 28), &[0.0, 0.0, 0.0, 1.0]); - bg.fill_rect(Rect::new(30, 20, 35, 28), &[0.5, 0.5, 0.5, 1.0]); - Ok(()) - }) - .unwrap(); - s - } - - #[test] - fn color_range_several_samples_points_and_invert() { - let mut s = session_colours(); - // Several samples span one Lab box (Photoshop's Minimum/Maximum): red and blue take - // both squares, black, grey and white stay out. - s.execute("select.colorRange", json!({"colors": ["#ff0000", "#0000ff"], "fuzziness": 100})).unwrap(); - assert_eq!((coverage(&s, 10, 10), coverage(&s, 30, 10), coverage(&s, 10, 24)), (1.0, 1.0, 1.0)); - assert_eq!((coverage(&s, 2, 2), coverage(&s, 22, 24), coverage(&s, 32, 24)), (0.0, 0.0, 0.0)); - // Eyedropper point on the blue square; `invert` flips the result. - clear_selection(&mut s); - s.execute("select.colorRange", json!({"points": [[7, 22]], "fuzziness": 100, "invert": true})).unwrap(); - assert_eq!((coverage(&s, 10, 24), coverage(&s, 10, 10), coverage(&s, 2, 2)), (0.0, 1.0, 1.0)); - // Localized clusters: picked on the left red square, a 25% range (10 px) leaves the right one. - clear_selection(&mut s); - s.execute("select.colorRange", json!({"points": [[10, 10]], "fuzziness": 100, "localized": true, "range": 25})).unwrap(); - assert_eq!(coverage(&s, 10, 10), 1.0); - assert!(coverage(&s, 13, 10) > 0.5); - assert_eq!(coverage(&s, 30, 10), 0.0); - // Undo restores the empty selection that preceded the most recent Color Range. - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(coverage(&s, 2, 2), 0.0); - } - - #[test] - fn color_range_subtract_follows_photoshop_and_the_click_order() { - // Grey strips from dark to light; samples at both ends span the whole run. - let mut s = Session::new(); - s.execute("file.new", json!({"width": 50, "height": 10})).unwrap(); - s.edit("paint", |doc, _| { - let bg = doc.layers[0].surface_mut().unwrap(); - for (i, v) in [0.30f32, 0.40, 0.50, 0.60, 0.70].iter().enumerate() { - bg.fill_rect(Rect::new(i as i32 * 10, 0, i as i32 * 10 + 10, 10), &[*v, *v, *v, 1.0]); - } - Ok(()) - }) - .unwrap(); - let run = |s: &mut Session, extra: Value| { - clear_selection(s); - let mut p = json!({"points": [[5, 5], [45, 5]], "fuzziness": 10}); - p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); - s.execute("select.colorRange", p).unwrap(); - (0..5).map(|i| coverage(s, i * 10 + 5, 5)).collect::>() - }; - assert!(run(&mut s, json!({})).iter().all(|v| *v > 0.99), "both samples span every strip"); - // Subtracting a colour inside the range moves the nearer edge onto it: the strips beyond - // it drop out, the subtracted grey itself stays selected (Photoshop does the same). - let cut = run(&mut s, json!({"subtractPoints": [[15, 5]]})); - assert!(cut[0] < 0.5 && cut[1] > 0.99 && cut[4] > 0.99, "{cut:?}"); - // Order matters: adding the dark strip back after the subtraction restores it. - let readd = run(&mut s, json!({"points": [[5, 5], [45, 5], [5, 5]], "subtractPoints": [[15, 5]], "order": ["+", "+", "-", "+"]})); - assert!(readd[0] > 0.99, "{readd:?}"); - let sub_last = run(&mut s, json!({"points": [[5, 5], [45, 5], [5, 5]], "subtractPoints": [[15, 5]], "order": ["+", "+", "+", "-"]})); - assert!(sub_last[0] < 0.5, "{sub_last:?}"); - // A malformed or inconsistent order is an error, never a panic. - clear_selection(&mut s); - for bad in [json!(["+"]), json!(["+", "+", "x"]), json!("+-"), json!(["-", "-", "+"])] { - assert!(s.execute("select.colorRange", json!({"points": [[5, 5], [45, 5]], "subtractPoints": [[15, 5]], "order": bad})).is_err(), "{bad}"); - } - } - - #[test] - fn color_range_presets() { - let mut s = session_colours(); - s.execute("select.colorRange", json!({"select": "reds"})).unwrap(); - assert_eq!((coverage(&s, 10, 10), coverage(&s, 30, 10)), (1.0, 1.0)); - assert_eq!((coverage(&s, 10, 24), coverage(&s, 2, 2), coverage(&s, 32, 24)), (0.0, 0.0, 0.0)); - clear_selection(&mut s); - s.execute("select.colorRange", json!({"select": "blues"})).unwrap(); - assert_eq!((coverage(&s, 10, 24), coverage(&s, 10, 10)), (1.0, 0.0)); - clear_selection(&mut s); - s.execute("select.colorRange", json!({"select": "greens"})).unwrap(); - assert!(s.active().unwrap().doc.selection.is_none() || coverage(&s, 10, 10) == 0.0); - // Tones: black is a shadow, white a highlight, 50% grey (128) a midtone. - clear_selection(&mut s); - s.execute("select.colorRange", json!({"select": "shadows"})).unwrap(); - assert_eq!((coverage(&s, 22, 24), coverage(&s, 2, 2), coverage(&s, 32, 24)), (1.0, 0.0, 0.0)); - clear_selection(&mut s); - s.execute("select.colorRange", json!({"select": "highlights"})).unwrap(); - assert_eq!((coverage(&s, 22, 24), coverage(&s, 2, 2)), (0.0, 1.0)); - clear_selection(&mut s); - s.execute("select.colorRange", json!({"select": "midtones", "fuzziness": 0})).unwrap(); - assert_eq!((coverage(&s, 32, 24), coverage(&s, 2, 2), coverage(&s, 22, 24)), (1.0, 0.0, 0.0)); - // A wider shadow range takes the grey too. - clear_selection(&mut s); - s.execute("select.colorRange", json!({"select": "shadows", "tonalRange": 140, "fuzziness": 0})).unwrap(); - assert_eq!(coverage(&s, 32, 24), 1.0); - // Modes combine as for the other selection commands. - s.execute("select.colorRange", json!({"select": "reds", "mode": "add"})).unwrap(); - assert_eq!((coverage(&s, 32, 24), coverage(&s, 10, 10)), (1.0, 1.0)); - } - - #[test] - fn color_range_out_of_gamut_matches_the_gamut_warning() { - let mut s = session(); - s.edit("paint", |doc, _| { - // Saturated sRGB blue is outside the default CMYK proof; mid grey is inside. - let bg = doc.layers[0].surface_mut().unwrap(); - bg.fill_rect(Rect::new(0, 20, 20, 30), &[0.0, 0.0, 1.0, 1.0]); - bg.fill_rect(Rect::new(20, 20, 40, 30), &[0.5, 0.5, 0.5, 1.0]); - Ok(()) - }) - .unwrap(); - s.execute("select.colorRange", json!({"select": "outOfGamut"})).unwrap(); - assert_eq!((coverage(&s, 5, 25), coverage(&s, 30, 25)), (1.0, 0.0)); - let warn = s.execute("view.gamutWarning", json!({"on": true})).unwrap(); - let sel = s.active().unwrap().doc.selection.clone().unwrap(); - let mut n = 0; - for y in 0..30 { - for x in 0..40 { - n += usize::from(sel.sample_channel(x, y, 0) > 0.5); - } - } - assert_eq!(warn["outOfGamut"].as_u64(), Some(n as u64)); - } - - #[test] - fn color_range_rejects_bad_params() { - let mut s = session_colours(); - for p in [ - json!({"select": "skin"}), - json!({"select": 3}), - json!({"points": [[100, 2]]}), - json!({"points": [[1]]}), - json!({"points": "here"}), - json!({"colors": "#ff0000"}), - json!({"localized": true}), - json!({"select": "midtones", "tonalRange": [200, 100]}), - json!({"select": "shadows", "tonalRange": 300}), - ] { - assert!(s.execute("select.colorRange", p.clone()).is_err(), "{p}"); - } - assert!(s.active().unwrap().doc.selection.is_none()); - } - - #[test] - fn modify_commands() { - let mut s = session(); - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); - s.execute("select.modify.expand", json!({"radius": 2})).unwrap(); - assert_eq!(coverage(&s, 8, 15), 1.0); - s.execute("select.modify.contract", json!({"radius": 4})).unwrap(); - assert_eq!(coverage(&s, 11, 15), 0.0); - assert_eq!(coverage(&s, 15, 15), 1.0); - s.execute("select.modify.border", json!({"radius": 2})).unwrap(); - assert_eq!(coverage(&s, 15, 15), 0.0); - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); - s.execute("select.modify.feather", json!({"radius": 4})).unwrap(); - let e = coverage(&s, 10, 15); - assert!(e > 0.2 && e < 0.8, "{e}"); - s.execute("select.modify.smooth", json!({"radius": 2})).unwrap(); - assert!(s.active().unwrap().doc.selection.is_some()); - assert!(!s.is_enabled("select.nothing")); - // Out-of-range or non-finite radii are refused and leave the selection alone. - for op in ["feather", "smooth", "expand", "contract", "border"] { - for r in [json!(1e300), json!(5000), json!(f64::MAX), json!(-5), json!(-0.5), json!(f64::MIN)] { - assert!(s.execute(&format!("select.modify.{op}"), json!({"radius": r})).is_err(), "{op} {r}"); - } - } - assert!(s.active().unwrap().doc.selection.is_some()); - } - - #[test] - fn modify_select_all_honours_canvas_bounds() { - let all = || { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 40, "height": 30})).unwrap(); - s.execute("select.all", json!({})).unwrap(); - s - }; - // Off (Photoshop's default): the selection continues past the canvas, so the edges stay. - for op in ["contract", "smooth", "expand", "feather"] { - let mut s = all(); - s.execute(&format!("select.modify.{op}"), json!({"radius": 4})).unwrap(); - assert_eq!(coverage(&s, 0, 15), 1.0, "{op}"); - assert_eq!(coverage(&s, 20, 0), 1.0, "{op}"); - } - // On: the canvas edge is a selection edge (#1277). - let mut s = all(); - s.execute("select.modify.contract", json!({"radius": 4, "applyAtCanvasBounds": true})).unwrap(); - assert_eq!(coverage(&s, 2, 15), 0.0); - assert_eq!(coverage(&s, 20, 28), 0.0); - assert_eq!(coverage(&s, 20, 15), 1.0); - let mut s = all(); - s.execute("select.modify.feather", json!({"radius": 4, "applyAtCanvasBounds": true})).unwrap(); - let e = coverage(&s, 0, 15); - assert!(e > 0.2 && e < 0.8, "{e}"); - assert_eq!(coverage(&s, 20, 15), 1.0); - let mut s = all(); - s.execute("select.modify.smooth", json!({"radius": 4, "applyAtCanvasBounds": true})).unwrap(); - assert!(coverage(&s, 0, 0) < 1.0); - // Border always follows the canvas edge: a band inside it, not an empty selection. - let mut s = all(); - s.execute("select.modify.border", json!({"radius": 4})).unwrap(); - assert!(coverage(&s, 0, 15) > 0.0); - assert_eq!(coverage(&s, 20, 15), 0.0); - } - - #[test] - fn modify_away_from_the_canvas_edge_ignores_canvas_bounds() { - for at in [false, true] { - let mut s = session(); - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); - s.execute("select.modify.contract", json!({"radius": 4, "applyAtCanvasBounds": at})).unwrap(); - assert_eq!(coverage(&s, 11, 15), 0.0); - assert_eq!(coverage(&s, 15, 15), 1.0); - } - } - - #[test] - fn modify_refuses_radii_below_the_minimum() { - let mut s = session(); - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); - // Below each dialog's minimum (1 px, Feather 0.1 px) is refused, not clamped to 0: a - // negative Border radius used to clear the selection and report success (#993). - let below = [ - ("border", -5.0), - ("border", 0.5), - ("smooth", -5.0), - ("smooth", 0.0), - ("expand", -5.0), - ("expand", 0.0), - ("contract", -5.0), - ("contract", 0.9), - ("feather", -5.0), - ("feather", 0.0), - ("feather", 0.05), - ]; - let before = current_mask(&s.active().unwrap().doc).1; - for (op, r) in below { - let err = s.execute(&format!("select.modify.{op}"), json!({"radius": r})).unwrap_err(); - assert!(matches!(err, EngineError::BadParams { .. }), "{op} {r}: {err}"); - assert!(current_mask(&s.active().unwrap().doc).1 == before, "{op} {r}: the selection changed"); - } - // The minimum itself is still accepted. - s.execute("select.modify.feather", json!({"radius": 0.1})).unwrap(); - s.execute("select.modify.expand", json!({"radius": 1})).unwrap(); - assert_eq!(coverage(&s, 9, 15), 1.0); - } - - #[test] - fn geometry_params_that_would_wrap_are_rejected() { - let mut s = session(); - // 2^32 + 50 wrapped to `x = 50` and 3e9 to a negative coordinate through `as i32`; - // both are bad-params errors now, whatever the front door (UI, CLI, control, MCP). - for x in [4_294_967_346_i64, 3_000_000_000_i64] { - let err = s.execute("select.rect", json!({"x": x, "y": 0, "width": 10, "height": 10})).unwrap_err(); - assert!(err.to_string().contains("32-bit"), "{err}"); - } - let err = s.execute("document.pixel", json!({"x": 4_294_967_346_i64, "y": 0})).unwrap_err(); - assert!(err.to_string().contains("32 bits"), "{err}"); - // In-range coordinates, including negative and past-canvas ones, are unaffected. - s.execute("select.rect", json!({"x": -100, "y": -100, "width": 500, "height": 500})).unwrap(); - s.execute("document.pixel", json!({"x": 0, "y": 0})).unwrap(); - } - - #[test] - fn grow_and_similar() { - let mut s = session(); - s.execute("select.rect", json!({"x": 6, "y": 6, "width": 2, "height": 2})).unwrap(); - s.execute("select.grow", json!({"tolerance": 5})).unwrap(); - assert_eq!(coverage(&s, 14, 14), 1.0); - assert_eq!(coverage(&s, 30, 10), 0.0); - s.execute("select.similar", json!({"tolerance": 5})).unwrap(); - assert_eq!(coverage(&s, 30, 10), 1.0); - assert_eq!(coverage(&s, 20, 20), 0.0); - } - - #[test] - fn lasso_polygon() { - let mut s = session(); - s.execute("select.lasso", json!({"points": [[0, 0], [20, 0], [0, 20]]})).unwrap(); - assert_eq!(coverage(&s, 2, 2), 1.0); - assert_eq!(coverage(&s, 18, 18), 0.0); - assert!(s.execute("select.lasso", json!({"points": [[0, 0], [1, 1]]})).is_err()); - s.execute("select.lasso", json!({"points": [[0, 0], [20, 0], [0, 20]], "mode": "subtract"})).unwrap(); - assert!(s.active().unwrap().doc.selection.is_none()); - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(coverage(&s, 2, 2), 1.0); - } - - /// The previous per-sample padding and cropping, kept as the oracle for the row-wise ones. - fn old_pad_mask(m: &[f32], w: usize, h: usize, pad: usize, outside_empty: bool) -> Vec { - let pw = w + 2 * pad; - let mut out = vec![0.0f32; pw * (h + 2 * pad)]; - for (py, row) in out.chunks_exact_mut(pw).enumerate() { - let inside_y = (pad..pad + h).contains(&py); - if outside_empty && !inside_y { - continue; - } - let y = py.saturating_sub(pad).min(h - 1); - for (px, v) in row.iter_mut().enumerate() { - if outside_empty && !(pad..pad + w).contains(&px) { - continue; - } - *v = m.get(y * w + px.saturating_sub(pad).min(w - 1)).copied().unwrap_or(0.0); - } - } - out - } - - #[test] - fn row_wise_pad_and_crop_match_per_sample_ones() { - let mut seed = 0x2545_f491_4f6c_dd1du64; - let (w, h) = (37, 23); - let m: Vec = (0..w * h) - .map(|_| { - seed ^= seed << 13; - seed ^= seed >> 7; - seed ^= seed << 17; - (seed % 1000) as f32 / 999.0 - }) - .collect(); - for pad in [0, 1, 5, 40] { - for outside_empty in [false, true] { - let padded = pad_mask(&m, w, h, pad, outside_empty); - assert_eq!(padded, old_pad_mask(&m, w, h, pad, outside_empty), "pad {pad} {outside_empty}"); - assert_eq!(crop_mask(&padded, w + 2 * pad, pad, w, h), m, "pad {pad}"); - } - } - } - - /// The lasso over the polygon's rows gives exactly the whole-canvas result (#4532): random - /// polygons, partly off the canvas, with and without anti-aliasing, in every mode over an - /// existing selection. - #[test] - fn lasso_over_its_rows_matches_the_whole_canvas() { - let mut seed = 0x2545_f491_u32; - let mut rnd = |lo: f32, hi: f32| { - seed ^= seed << 13; - seed ^= seed >> 17; - seed ^= seed << 5; - lo + (seed % 10_000) as f32 / 10_000.0 * (hi - lo) - }; - for case in 0..24 { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 300, "height": 520})).unwrap(); - s.execute("select.rect", json!({"x": 40, "y": 60, "width": 200, "height": 300})).unwrap(); - let n = 3 + case % 7; - let pts: Vec<(f32, f32)> = (0..n).map(|_| (rnd(-30.0, 330.0), rnd(100.0, 420.0))).collect(); - let aa = case % 2 == 0; - let m = ["replace", "add", "subtract", "intersect"][case % 4]; - let doc = s.active().unwrap().doc.clone(); - let area = doc.bounds(); - let want = sel::combine(doc.selection.as_ref(), &sel::polygon(&pts, area, aa), area, SelectionMode::parse(m)); - let points: Vec<[f32; 2]> = pts.iter().map(|p| [p.0, p.1]).collect(); - s.execute("select.lasso", json!({"points": points, "antiAlias": aa, "mode": m})).unwrap(); - let got = s.active().unwrap().doc.selection.clone(); - let read = |x: &Option| x.as_ref().map(|s| s.read_region(area)); - assert_eq!(read(&got), read(&want), "case {case}: {m}, anti-alias {aa}, {pts:?}"); - } - } -} diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs new file mode 100644 index 0000000000..18eb3dc80a --- /dev/null +++ b/crates/engine/src/session.rs @@ -0,0 +1,11 @@ +use super::doc_state::DocState; +use super::error::{EngineError, Result}; +use super::*; + +mod documents; +mod execute; +mod history; +mod layers; + +pub use documents::move_item; +pub(crate) use history::{fix_selection, restore_target}; diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs new file mode 100644 index 0000000000..ea20944fbc --- /dev/null +++ b/crates/engine/src/session/documents.rs @@ -0,0 +1,165 @@ +use super::history::fix_selection; +use super::*; + +/// Move item `i` of `v` to position `to`, clamped to the end. Returns where it went; `None` when +/// `i` is out of range. +pub fn move_item(v: &mut Vec, i: usize, to: usize) -> Option { + if i >= v.len() { + return None; + } + let x = v.remove(i); + let to = to.min(v.len()); + v.insert(to, x); + Some(to) +} + +impl Session { + pub fn new() -> Self { + Self::default() + } + + pub fn documents(&self) -> &[DocState] { + &self.docs + } + + pub fn active_index(&self) -> Option { + self.active + } + + pub fn active(&self) -> Option<&DocState> { + self.active.and_then(|i| self.docs.get(i)) + } + + pub fn active_mut(&mut self) -> Option<&mut DocState> { + self.active.and_then(|i| self.docs.get_mut(i)) + } + + /// Monotonic active-document generation. It changes when a different document becomes + /// active, including a switch away and back between two observations; equal values therefore + /// mean the document was not switched in between. + pub fn active_generation(&self) -> u64 { + self.active_generation + } + + /// Bump [`Self::active_generation`] when the active document id changed. Call after every + /// assignment to `self.active`. + pub(crate) fn note_active_change(&mut self) { + let id = self.active().map(|st| st.doc.id); + if id != self.active_doc_for_generation { + self.active_doc_for_generation = id; + self.active_generation = self.active_generation.wrapping_add(1); + } + } + + pub fn set_active(&mut self, index: usize) -> bool { + if index < self.docs.len() { + self.active = Some(index); + self.note_active_change(); + self.sync_tools_mask_target(); + true + } else { + false + } + } + + /// Color Sampler points dropped by the last canvas-size change (crop, Canvas Size, Image Size, + /// rotation) since this was last called, for the status message. See [`edit`](Self::edit). + pub fn take_samplers_removed(&mut self) -> usize { + std::mem::take(&mut self.samplers_removed) + } + + /// Move the Color Sampler points through `a` in the next [`Session::edit`] (crop, Canvas Size, + /// Image Size, rotation), dropping the ones that land outside the new canvas. View state: the + /// points stay pinned to their pixels, no history step. Cleared by the edit it is set for. + /// The painting symmetry moves through `a` too. + pub(crate) fn set_sampler_map(&mut self, a: photocraft_geom::Affine) { + self.set_canvas_map(a, a); + } + + /// [`set_sampler_map`](Self::set_sampler_map) for an edit whose sampler map differs from its + /// geometry map (a flip or rotation maps pixel centres): `geometry` moves the painting symmetry. + pub(crate) fn set_canvas_map(&mut self, geometry: photocraft_geom::Affine, samplers: photocraft_geom::Affine) { + self.sampler_map = Some(samplers); + self.symmetry_map = Some(geometry); + } + + pub fn sync_tools_mask_target(&mut self) { + let mask = self.active().is_some_and(|st| st.channel_view.target == crate::channel_cmds::ChannelTarget::LayerMask); + self.tools.target_mask(mask); + } + + /// Move the document at `from` to tab position `to` (clamped to the last), keeping the active + /// document active. Returns its new index; `None` when `from` is out of range. + pub fn move_document(&mut self, from: usize, to: usize) -> Option { + let active = self.active().map(|d| d.doc.id); + let to = move_item(&mut self.docs, from, to)?; + self.active = active.and_then(|id| self.docs.iter().position(|d| d.doc.id == id)); + self.note_active_change(); + Some(to) + } + + /// Add a document (from File → New, an import, etc.) and make it active. + /// Preserve its identity unless another open document already owns it. + /// Identity-dependent callers must read the admitted document at the returned index. + pub fn add_document(&mut self, mut doc: Document, path: Option) -> usize { + // Persisted IDs can overlap the allocator, so check every replacement too. + while self.docs.iter().any(|st| st.doc.id == doc.id) { + doc.id = photocraft_doc::DocId::fresh(); + } + let mut st = DocState::new(doc, path); + st.history.max_states = self.prefs.get().performance.history_states.max(1) as usize; + st.history.max_bytes = self.prefs.get().performance.history_budget_bytes(); + self.docs.push(st); + let i = self.docs.len() - 1; + self.active = Some(i); + self.note_active_change(); + i + } + + /// Holds a decoded document back from opening (see `held_opens`); returns its id. + pub(crate) fn hold_open(&mut self, doc: Document, source_read_only: bool) -> u64 { + self.next_held_open = self.next_held_open.wrapping_add(1); + self.held_opens.push((self.next_held_open, doc, source_read_only)); + self.next_held_open + } + + /// Takes a document a background open held back for the profile prompt: the document and + /// whether its source is read-only. `None` when there is no such document (already taken). + pub fn take_held_open(&mut self, id: u64) -> Option<(Document, bool)> { + let i = self.held_opens.iter().position(|(h, _, _)| *h == id)?; + let (_, doc, read_only) = self.held_opens.remove(i); + Some((doc, read_only)) + } + + pub fn close(&mut self, index: usize) -> Option { + if index >= self.docs.len() { + return None; + } + smart_cmds::on_close(self, index); + if let Some(id) = self.docs.get(index).map(|d| d.doc.id) { + self.cancel_jobs_on(id); + self.subject_cache.forget_doc(id); + self.object_finder.forget_doc(id); + } + let d = self.docs.remove(index); + self.active = if self.docs.is_empty() { + None + } else { + Some(match self.active { + Some(active) if active > index => active - 1, + Some(active) if active < index => active, + _ => index.min(self.docs.len() - 1), + }) + }; + self.note_active_change(); + Some(d) + } +} + +pub(super) fn fix_active(st: &mut DocState) { + if st.active_layer.is_none_or(|id| st.doc.layer(id).is_none()) { + st.active_layer = st.doc.top_layer(); + } + fix_selection(st); + channel_cmds::fix_view(st); +} diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs new file mode 100644 index 0000000000..c3822673bb --- /dev/null +++ b/crates/engine/src/session/execute.rs @@ -0,0 +1,244 @@ +use super::history::fix_selection; +use super::*; + +impl Session { + /// Run a command by id with JSON params. Returns a JSON result. + /// + /// Any command accepts an optional `"coalesce": ""` param: consecutive edits with the same + /// key (and no other edit, undo or redo in between) share one history step, like Photoshop's + /// single "Edit Type Layer" step for a whole typing session or one step per slider drag. + /// + /// Runs synchronously, including job-capable commands (see [`jobs`]; [`Session::start`] runs + /// those in the background). + pub fn execute(&mut self, id: &str, params: Value) -> Result { + match self.dispatch(id, params, false)? { + jobs::Started::Done(v) => Ok(v), + // Not reached: inline dispatch never starts a job. Waiting is still correct. + jobs::Started::Job(j) => self.wait_job(j), + } + } + + /// Offer a finished live stroke to the next command: a `paint.stroke` / `paint.pencil` whose + /// params match it exactly takes its pixels instead of rendering the stroke again (its result + /// then says `"fromLive": true`); any other command drops the offer. The command still runs + /// through the normal dispatch, so authorization, the journal and history are unchanged. + pub fn offer_live_stroke(&mut self, live: brush_cmds::LiveStroke) -> Result<()> { + self.live_commit = Some(live.into_commit()?); + Ok(()) + } + + /// [`Self::offer_live_stroke`] for a live Clone Stamp or History Brush stroke, taken by the + /// `paint.cloneStamp` / `paint.historyBrush` it was drawn for. Refused for the Healing Brush + /// (it blends on release) and when the brush, layer or clone source changed during the stroke. + pub fn offer_live_retouch(&mut self, live: retouch_cmds::LiveRetouch) -> Result<()> { + let commit = live.into_commit(self)?; + self.live_commit = Some(commit); + Ok(()) + } + + /// [`Self::offer_live_stroke`] for a live Dodge, Burn, Sponge, Blur, Sharpen or Smudge stroke, + /// taken by the command it was drawn for: the stroke's finishing dabs are run first. Refused + /// when the brush, tool options or layer changed during the stroke. + pub fn offer_live_dab(&mut self, live: retouch_cmds::LiveDab) -> Result<()> { + // A refused offer withdraws the previous one too. + self.live_commit = None; + let commit = live.into_commit(self)?; + self.live_commit = Some(commit); + Ok(()) + } + + /// Withdraw an offer the command didn't take. + pub fn clear_live_stroke(&mut self) { + self.live_commit = None; + } + + /// Check a call without running it: the command exists, its params have the shape + /// [`Self::execute`] requires (New Layer's fully), and it can run now. For a caller that does + /// something first only when the command will go through: Free Transform applies its box + /// before a new layer is made. + /// + /// Complete for the commands in [`PRECHECKED`]: there it accepts what `execute` accepts, but + /// for the group nesting limit (a test holds the two together). For others it checks only what they share. + pub fn precheck(&mut self, id: &str, params: &Value) -> Result<()> { + let spec = crate::commands::find(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?; + if !(params.is_object() || params.is_null()) { + return Err(EngineError::BadParams { cmd: id.to_string(), msg: "params must be a JSON object".into() }); + } + crate::param_check::check(spec, params)?; + crate::filters::validate_params(id, params)?; + if id == "layer.new.layer" { + crate::new_layer::parse(params)?; + } + // A command that takes `"layer"` (an id or a name, as it resolves it) fails on one the + // document doesn't have. + if spec.params.contains("\"layer\":id") + && let Some(l) = commands::explicit_layer(self, params)? + && self.active().is_none_or(|st| st.doc.layer(l).is_none()) + { + return Err(EngineError::BadParams { cmd: id.to_string(), msg: format!("no layer {}", l.0) }); + } + self.admit(id, spec, params).map(|_| ()) + } + + /// What `dispatch` checks once the params are valid and a floating selection has dropped: + /// the precondition (on a named layer for commands that take one), a job running on the + /// document, a hidden target. The run params (the Channels panel's target filled in) when it + /// may run. + pub(crate) fn admit(&mut self, id: &str, spec: &commands::CommandSpec, params: &Value) -> Result { + let run_params = channel_cmds::inject_target(self, id, commands::inject_kind(id, params.clone())); + if let Err(why) = self.explicit_layer_enabled(spec, params).unwrap_or_else(|| self.precondition(spec, &run_params)) { + return Err(EngineError::Disabled(id.to_string(), why)); + } + if let Some(why) = self.job_conflict(id, spec.journal) { + return Err(EngineError::Disabled(id.to_string(), why)); + } + // Painting on or moving a hidden layer is refused, as in Photoshop (#571). + if let Some(why) = hidden_target::refusal(self, id, params) { + return Err(EngineError::Other(why.into())); + } + Ok(run_params) + } + + /// Is the command currently runnable? (drives menu enablement) + pub fn is_enabled(&self, id: &str) -> bool { + self.is_enabled_with(id, &Value::Null) + } + + /// [`Self::is_enabled`] for a call with `params`: their `"target"` can enable a command, as a + /// targeted layer mask enables Image › Adjustments › Invert on an adjustment layer (#780). + pub fn is_enabled_with(&self, id: &str, params: &Value) -> bool { + self.disabled_reason_with(id, params).is_none() + } + + /// Why the command can't run now (None = it can): its own precondition, or a background job + /// running on the active document. + pub fn disabled_reason(&self, id: &str) -> Option { + self.disabled_reason_with(id, &Value::Null) + } + + /// [`Self::disabled_reason`] for a call with `params`. + pub fn disabled_reason_with(&self, id: &str, params: &Value) -> Option { + let Some(s) = commands::find(id) else { return Some(format!("unknown command `{id}`")) }; + self.precondition(s, &channel_cmds::inject_target(self, id, params.clone())).err().or_else(|| self.job_conflict(id, s.journal)) + } + + /// The command's own precondition for a call with `params` (their target filled in). + fn precondition(&self, spec: &commands::CommandSpec, params: &Value) -> std::result::Result<(), String> { + if self.names_existing_layer(spec.id, params) { + return Ok(()); + } + // `ifPresent`: with no Background there is nothing to do, which isn't an error. + if spec.id == "layer.new.layerFromBackground" && params.get("ifPresent").and_then(Value::as_bool) == Some(true) { + return self.active().map(|_| ()).ok_or_else(|| "no document open".into()); + } + channel_cmds::mask_target_enabled(self, spec.id, params).unwrap_or_else(|| (spec.enabled)(self)) + } + + /// Whether `id` is a layer command whose `"layer"` param names an existing layer, so it needs no + /// active layer (#2457). Matches how `layer_param` resolves the layer when the command runs. + fn names_existing_layer(&self, id: &str, params: &Value) -> bool { + matches!(id, "layer.hideLayers" | "layer.showLayers" | "layer.renameLayer") + && params.get("layer").and_then(Value::as_u64).is_some_and(|l| self.active().is_some_and(|st| st.doc.layer(LayerId(l)).is_some())) + } + + /// The precondition of a command whose params document `"layer":id` (it acts on that layer), + /// when `params` name an existing layer of the active document: checked on that layer rather + /// than on the active one, which stays active (#466). A script, action or agent can then + /// Replace Contents, Rasterize or Merge Down a layer without selecting it first. `None` for + /// other commands, or without such a layer. + pub(crate) fn explicit_layer_enabled(&mut self, spec: &commands::CommandSpec, params: &Value) -> Option> { + if !spec.params.contains("\"layer\":id") { + return None; + } + let target = LayerId(params.get("layer")?.as_u64()?); + let d = self.active_mut()?; + d.doc.layer(target)?; + let active = d.active_layer.replace(target); + let r = self.precondition(spec, params); + if let Some(d) = self.active_mut() { + d.active_layer = active; + } + Some(r) + } + + /// Apply an undoable edit to the active document. + pub fn edit(&mut self, label: &str, f: impl FnOnce(&mut Document, &mut Option) -> Result) -> Result { + // Every mutation path (linked-file refresh, transform, place) re-renders smart objects + // through this entry; the requesting session's authority must reach those renders. + let _authorization = crate::jobs::render_authorization_scope(self.authorize); + let _document = crate::doc_path::scope(self.active().and_then(|d| d.path.as_deref()).map(std::path::Path::new)); + let restrict = self.color_restrict; + let filter_mask_layer = self.filter_mask_layer; + let sampler_map = self.sampler_map.take(); + let symmetry_map = self.symmetry_map.take(); + let st = self.active_mut().ok_or(EngineError::NoDocument)?; + let before = st.doc.clone(); + // Selecting layers is not a step, so the state this edit leaves behind targets what was + // selected just before it (#1356): undoing a stroke keeps the painted layer active. + let prior = st.layer_target(); + let mut doc = (*before).clone(); + let mut active = st.active_layer; + let r = f(&mut doc, &mut active)?; + if let (Some(k), Some(id)) = (restrict, active) { + channel_cmds::restrict_to_color(&before, &mut doc, id, k); + } + if let Some(id) = filter_mask_layer { + smart_cmds::refresh_after_filter_mask_edit(&mut doc, id)?; + } + st.doc = Arc::new(doc); + st.active_layer = active; + fix_selection(st); + channel_cmds::fix_view(st); + // A canvas-size change (crop, Canvas Size, Image Size, rotation) moves the Color Sampler + // points with their pixels and drops the ones that land outside the new canvas. View + // state: not a history step. A mapped edit (the four above) gives the exact map; any other + // size change falls back to dropping whatever is now outside. + let mut samplers_removed = 0; + if let Some(a) = sampler_map { + let bounds = st.doc.bounds(); + let n = st.color_samplers.len(); + st.color_samplers.retain_mut(|p| { + let q = a.apply(photocraft_geom::Point::new(p[0], p[1])); + *p = [q.x, q.y]; + bounds.contains(q.x.floor() as i32, q.y.floor() as i32) + }); + samplers_removed = n - st.color_samplers.len(); + } else if st.doc.size != before.size { + let bounds = st.doc.bounds(); + let n = st.color_samplers.len(); + st.color_samplers.retain(|p| bounds.contains(p[0].floor() as i32, p[1].floor() as i32)); + samplers_removed = n - st.color_samplers.len(); + } + // The painting symmetry stays on its pixels too (Photoshop keeps it as a path). + if let Some(a) = symmetry_map { + st.symmetry = st.symmetry.take().and_then(|sym| sym.transform(&a)); + } + // The pixels the edit can have changed, as its undo would report them: nothing for a + // selection, guides or a layer's name (a new lasso selection used to recomposite a large + // document, seconds on the CPU path, #1773), a new or deleted layer's bounds (a + // duplicate or a paste), and everything when that can't be bounded. A command may still + // report its own, tighter damage after this. + let damage = layer_multi_cmds::step_damage(&before, &st.doc); + let keep_clean = st.keeps_clean(&before); + let key = self.coalesce_request.clone(); + let st = self.active_mut().ok_or(EngineError::NoDocument)?; + let layers = st.layer_target(); + if key.is_none() || st.coalesce != key || !st.history.can_undo() { + st.history.set_current_layers(prior); + st.history.record(label, before, layers); + st.trim_history(); + } else { + st.history.set_current_layers(layers); + } + st.coalesce = key; + st.bump_revision(keep_clean); + st.last_damage = damage; + self.samplers_removed += samplers_removed; + if damage.is_none_or(|d| !d.is_empty()) { + // Free the mask early; a stale entry would only miss (it is keyed by pixels). + self.subject_cache = Default::default(); + self.object_finder = Default::default(); + } + Ok(r) + } +} diff --git a/crates/engine/src/session/history.rs b/crates/engine/src/session/history.rs new file mode 100644 index 0000000000..0d619f47e9 --- /dev/null +++ b/crates/engine/src/session/history.rs @@ -0,0 +1,104 @@ +use super::documents::fix_active; +use super::*; + +impl Session { + pub fn undo(&mut self) -> bool { + // A background job is computing from the current state: it must not move under it. + if self.active_job().is_some() { + return false; + } + let Some(st) = self.active_mut() else { return false }; + st.coalesce = None; + match st.history.undo(st.doc.clone()) { + // Undo Clear History: the list comes back, the document is the same one. Not an + // edit: keep a clean document clean (the revision still moves for the panels). + Some((d, layers)) if Arc::ptr_eq(&d, &st.doc) => { + restore_target(st, layers); + let clean = !st.is_dirty(); + st.revision += 1; + if clean { + st.saved_revision = st.revision; + } + st.last_damage = Some(photocraft_geom::Rect::EMPTY); + true + } + Some((mut d, layers)) => { + // Save As changes file identity outside history, just like the saved path. + if d.name != st.doc.name { + Arc::make_mut(&mut d).name.clone_from(&st.doc.name); + } + // Pixels this step can have touched, so the canvas recomposites only that + // (it recomposited everything before). + let damage = layer_multi_cmds::step_damage(&d, &st.doc); + let before = std::mem::replace(&mut st.doc, d); + let keep_clean = st.keeps_clean(&before); + restore_target(st, layers); + st.bump_revision(keep_clean); + st.last_damage = damage; + true + } + None => false, + } + } + + pub fn redo(&mut self) -> bool { + if self.active_job().is_some() { + return false; + } + let Some(st) = self.active_mut() else { return false }; + st.coalesce = None; + match st.history.redo(st.doc.clone()) { + Some((mut d, layers)) => { + if d.name != st.doc.name { + Arc::make_mut(&mut d).name.clone_from(&st.doc.name); + } + let damage = layer_multi_cmds::step_damage(&st.doc, &d); + let before = std::mem::replace(&mut st.doc, d); + let keep_clean = st.keeps_clean(&before); + restore_target(st, layers); + st.bump_revision(keep_clean); + st.last_damage = damage; + true + } + None => false, + } + } +} + +/// Undo / redo: target the layers the restored state targeted, as far as they still exist. +pub(crate) fn restore_target(st: &mut DocState, layers: LayerTarget) { + // Deselect Layers is a valid history target, not a missing layer to replace with the top + // layer. An edit after deselection must undo back to no active or selected layers (#3042). + if layers.active.is_none() && layers.selected.is_empty() { + st.active_layer = None; + st.selected_layers.clear(); + st.layer_anchor = None; + channel_cmds::fix_view(st); + return; + } + if layers.active.is_some_and(|id| st.doc.layer(id).is_some()) { + st.active_layer = layers.active; + st.selected_layers = layers.selected; + } + fix_active(st); +} + +/// Keep the layer selection valid after the document or the active layer changed: drop deleted +/// layers, and collapse to the active layer when a command made a non-member active. +pub(crate) fn fix_selection(st: &mut DocState) { + let Some(active) = st.active_layer else { + st.selected_layers.clear(); + return; + }; + if !st.selected_layers.contains(&active) { + st.selected_layers = vec![active]; + } else { + let live: std::collections::HashSet = st.doc.walk().into_iter().map(|(_, _, l)| l.id).collect(); + st.selected_layers.retain(|id| live.contains(id)); + let mut seen = std::collections::HashSet::new(); + st.selected_layers.retain(|id| seen.insert(*id)); + } + if st.layer_anchor.is_some_and(|a| !st.selected_layers.contains(&a)) { + st.layer_anchor = Some(active); + } +} diff --git a/crates/engine/src/session/layers.rs b/crates/engine/src/session/layers.rs new file mode 100644 index 0000000000..b6e5d1c688 --- /dev/null +++ b/crates/engine/src/session/layers.rs @@ -0,0 +1,91 @@ +use super::history::fix_selection; +use super::*; + +impl Session { + /// Replace the active document's active layer without creating a history step. + pub fn select_layer(&mut self, id: LayerId) -> Result<()> { + let st = self.active_mut().ok_or(EngineError::NoDocument)?; + if st.doc.layer(id).is_none() { + return Err(EngineError::NoLayer(id)); + } + st.active_layer = Some(id); + st.selected_layers = vec![id]; + st.layer_anchor = Some(id); + channel_cmds::fix_view(st); + // Selecting a layer is not an edit: keep a clean document clean. + let clean = st.saved_revision == st.revision; + st.revision += 1; + if clean { + st.saved_revision = st.revision; + } + st.last_damage = Some(photocraft_geom::Rect::EMPTY); + Ok(()) + } + + /// Put back a layer selection (active layer, selected layers, anchor) that a step moved, such + /// as the undo ending an empty Type Mask, which restores the selection from before it. `None` + /// is no layer selected. Selected layers that are gone are dropped; an active layer that is + /// gone is an error and changes nothing. Like [`Self::select_layer`], not an edit. + pub fn restore_layer_selection(&mut self, active: Option, selected: &[LayerId], anchor: Option) -> Result<()> { + let st = self.active_mut().ok_or(EngineError::NoDocument)?; + if let Some(id) = active + && st.doc.layer(id).is_none() + { + return Err(EngineError::NoLayer(id)); + } + st.active_layer = active; + st.selected_layers = selected.to_vec(); + st.layer_anchor = anchor.filter(|_| active.is_some()); + fix_selection(st); + channel_cmds::fix_view(st); + let clean = st.saved_revision == st.revision; + st.revision += 1; + if clean { + st.saved_revision = st.revision; + } + st.last_damage = Some(photocraft_geom::Rect::EMPTY); + Ok(()) + } + + /// Re-renders the pixels of type layers whose font arrived after they were drawn (the web + /// build fetches served fonts on demand, `photocraft_text::served`). The layers' model is + /// unchanged, so this is no history step and leaves a clean document clean. Unknown documents + /// and layers are skipped. A document a background job is computing from must not move under + /// it: its layers are returned, to try again later. + pub fn refresh_type_layers(&mut self, layers: &[(photocraft_doc::DocId, LayerId)]) -> Vec<(photocraft_doc::DocId, LayerId)> { + let mut busy = Vec::new(); + let mut docs: Vec = Vec::new(); + for (d, _) in layers { + if !docs.contains(d) { + docs.push(*d); + } + } + for doc_id in docs { + let mine = layers.iter().filter(|(d, _)| *d == doc_id); + if self.job_on(doc_id).is_some() { + busy.extend(mine); + continue; + } + let Some(st) = self.docs.iter_mut().find(|st| st.doc.id == doc_id) else { continue }; + let snapshot = st.doc.clone(); + let mut doc = (*snapshot).clone(); + let mut changed = false; + for (_, id) in mine { + if let Some(photocraft_doc::Layer { content: photocraft_doc::LayerContent::Text(t), .. }) = doc.layer_mut(*id) { + type_cmds::refresh(&snapshot, t); + changed = true; + } + } + if changed { + let clean = st.saved_revision == st.revision; + st.doc = Arc::new(doc); + st.revision += 1; + if clean { + st.saved_revision = st.revision; + } + st.last_damage = None; + } + } + busy + } +} diff --git a/crates/engine/src/smart_cmds.rs b/crates/engine/src/smart_cmds.rs deleted file mode 100644 index 1205c82e4c..0000000000 --- a/crates/engine/src/smart_cmds.rs +++ /dev/null @@ -1,1618 +0,0 @@ -//! Smart Objects and Smart Filters: Layer › Smart Objects, Layer › Smart Filter and -//! Filter › Convert for Smart Filters. -//! -//! A smart object keeps its **source** (embedded file bytes, or a linked path) plus a -//! `transform` and a stack of smart filters; its `cache` is the rendered appearance the -//! compositors draw. The engine owns re-rendering (compose stays a pure function of the -//! document): -//! -//! ```text -//! source bytes ──decode + composite (cached by content hash)──► source image (source pixels) -//! ──transform (exact shift, or bicubic warp)──────► placed (document pixels) -//! ──each visible smart filter, blended (blend/opacity)──► filtered -//! ──filter mask mix (unfiltered ↔ filtered)───────► cache -//! ``` -//! -//! The placed stage and the result after each filter are cached too (`stack_cache`), so a -//! re-render starts from the deepest stage it shares with an earlier one. -//! -//! Converting a layer embeds it as an in-memory `.pcraft` bundle of a nested document (exactly -//! lossless, layered, any depth/model). PSD placed layers keep their source in the preserved -//! global `lnk2` block (found by uuid), and keep Photoshop's rendering until something changes, -//! so an unedited PSD still round-trips byte for byte. PSD export (`photocraft_io::smart_map`) -//! writes every smart object back as one: its source embedded in `lnk2` (a `.pcraft` source as a -//! PSB), its smart filters in `filterFX` and its filter mask in `FEid`. - -use std::sync::{Arc, Mutex}; - -use photocraft_algo::resample::translate_surface; -use photocraft_algo::transform::Homography; -use photocraft_color::{BlendMode, ColorMode, PixelFormat, SampleType}; -use photocraft_doc::{DocId, Document, Layer, LayerContent, LayerId, LayerMask, Metadata, SmartContentsId, SmartFilter, SmartObject, SmartSource}; -use photocraft_geom::{Affine, Rect, Size}; -use photocraft_raster::Surface; -use serde_json::{Value, json}; -use stack_cache::{Stage, StageKey}; - -use crate::commands::{CommandSpec, blend_from_str, layer_param}; -use crate::jobs::JobCtx; -use crate::{EngineError, Result, Session}; - -/// An open Edit Contents document and the shared contents it updates when saved or closed. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct SmartLink { - pub child: DocId, - pub parent: DocId, - pub layer: LayerId, - pub contents_id: SmartContentsId, -} - -/// PSD placed-layer keys that describe the smart object's source; stale once we change it. -const PLACED_KEYS: [&[u8; 4]; 3] = [b"SoLd", b"PlLd", b"SoLE"]; - -/// Command id of a Photoshop smart filter PhotoCraft does not implement (kept verbatim from PSD). -pub use photocraft_io::smart_map::UNSUPPORTED_FILTER; - -fn other(msg: impl Into) -> EngineError { - EngineError::Other(msg.into()) -} - -fn bad(cmd: &str, msg: impl Into) -> EngineError { - EngineError::BadParams { cmd: cmd.into(), msg: msg.into() } -} - -// ---------- source encoding / decoding ---------- - -/// Encodes a document as embedded smart-object contents: an in-memory `.pcraft` bundle. -pub fn encode_source(doc: &Document) -> Result> { - photocraft_format::save_to_bytes(doc, &Default::default()).map_err(|e| other(format!("can't encode smart object contents: {e}"))) -} - -/// Decodes smart-object contents (a `.pcraft` bundle, PSD/PSB, or any flat image format). -pub fn decode_source(file_name: &str, bytes: &[u8]) -> Result { - crate::file_cmds::import(file_name, bytes).map_err(|e| other(format!("can't read smart object contents \"{file_name}\": {e}"))) -} - -fn base_name(path: &str) -> String { - path.rsplit(['/', '\\']).next().unwrap_or(path).to_string() -} - -/// A linked file's bytes; `None` when it is missing or its path is not followed -/// ([`crate::doc_path::resolve`]). -/// -/// The path is document data, not a request parameter, so every read rechecks it with the gate -/// of the session the work is done for: a filter, transform or refresh re-renders from here, -/// not only the contents commands that judge it up front. A refused path is handled like a -/// missing file: the layer keeps its last rendering. -fn read_file(path: &str) -> Option> { - if path.is_empty() { - return None; - } - crate::jobs::authorize_render_command("layer.smartObjects.updateModifiedContent", &json!({"path": path})).ok()?; - photocraft_format::read_file(&crate::doc_path::resolve(path).ok()?).ok() -} - -/// The source file of a smart object: embedded bytes, the PSD's embedded linked-layer data (PSD -/// import keeps the placed layer's uuid as the path), or a linked file on disk. -pub fn source_bytes(meta: &Metadata, src: &SmartSource) -> Option<(String, Arc>)> { - embedded_source_bytes(meta, src).or_else(|| match src { - SmartSource::Linked { path } => read_file(path).map(|b| (base_name(path), Arc::new(b))), - SmartSource::Embedded { .. } => None, - }) -} - -/// Memory-only resolution also covers Photoshop's embedded files addressed by a `Linked` UUID. -fn embedded_source_bytes(meta: &Metadata, src: &SmartSource) -> Option<(String, Arc>)> { - match src { - SmartSource::Embedded { file_name, bytes } => Some((file_name.clone(), bytes.clone())), - SmartSource::Linked { path } => photocraft_io::linked::find_linked_file(meta, path).map(|f| (f.file_name, Arc::new(f.bytes))), - } -} - -/// The actual path is stored in the document, not in the command's params. Recheck it before -/// reading, reusing embedded PSD bytes rather than parsing their global blocks a second time. -fn authorized_source_bytes(s: &Session, cmd: &str, meta: &Metadata, src: &SmartSource) -> Result>)>> { - if let Some(source) = embedded_source_bytes(meta, src) { - return Ok(Some(source)); - } - let SmartSource::Linked { path } = src else { return Ok(None) }; - if let Some(gate) = s.authorize { - gate(cmd, &json!({"path": path}))?; - } - Ok(read_file(path).map(|b| (base_name(path), Arc::new(b)))) -} - -/// Recheck a source's actual path before an untrusted command reads it: the path lives in the -/// document, not in the command's params. Embedded PSD UUIDs never reach the filesystem. -fn authorize_source(s: &Session, cmd: &str, doc: &Document, src: &SmartSource) -> Result<()> { - if let (Some(gate), SmartSource::Linked { path }) = (s.authorize, src) - && embedded_source_bytes(&doc.metadata, src).is_none() - { - gate(cmd, &json!({"path": path}))?; - } - Ok(()) -} - -/// A decoded, composited source in its own pixel space (`bounds` starts at the origin). -#[derive(Clone, Debug)] -pub struct SourceImage { - pub surface: Arc, - pub bounds: Rect, -} - -type CacheKey = ([u8; 32], PixelFormat); - -struct CacheEntry { - key: CacheKey, - image: SourceImage, - decodes: u32, -} - -/// Decoded source composites by content hash, most recent last. Re-filtering or re-transforming -/// a smart object never decodes its contents again. -static SOURCE_CACHE: Mutex> = Mutex::new(Vec::new()); -const CACHE_ENTRIES: usize = 32; -const CACHE_BYTES: usize = 1 << 30; - -fn cache_key(bytes: &[u8], fmt: PixelFormat) -> CacheKey { - (*blake3::hash(bytes).as_bytes(), fmt) -} - -fn cache_get(key: &CacheKey) -> Option { - let mut c = SOURCE_CACHE.lock().ok()?; - let i = c.iter().position(|e| e.key == *key)?; - let e = c.remove(i); - let img = e.image.clone(); - c.push(e); - Some(img) -} - -fn cache_put(key: CacheKey, image: SourceImage) { - let Ok(mut c) = SOURCE_CACHE.lock() else { return }; - let decodes = match c.iter().position(|e| e.key == key) { - Some(i) => c.remove(i).decodes + 1, - None => 1, - }; - c.push(CacheEntry { key, image, decodes }); - let size = |e: &CacheEntry| e.image.bounds.width() as usize * e.image.bounds.height() as usize * e.key.1.channels() * 4; - while c.len() > CACHE_ENTRIES || (c.len() > 1 && c.iter().map(size).sum::() > CACHE_BYTES) { - c.remove(0); - } -} - -/// How many times these contents were decoded at this pixel format (0 = never / evicted). -pub fn source_decode_count(bytes: &[u8], fmt: PixelFormat) -> u32 { - let key = cache_key(bytes, fmt); - SOURCE_CACHE.lock().ok().and_then(|c| c.iter().find(|e| e.key == key).map(|e| e.decodes)).unwrap_or(0) -} - -pub(crate) fn take_caches(layers: &mut [Layer]) -> Vec<(LayerId, Surface)> { - let mut out = Vec::new(); - for l in layers { - match &mut l.content { - LayerContent::Smart(sm) => out.extend(sm.cache.take().map(|c| (l.id, c))), - LayerContent::Group(g) => out.extend(take_caches(&mut g.children)), - _ => {} - } - } - out -} - -pub(crate) fn restore_unrendered( - doc: &mut Document, - taken: Vec<(LayerId, Surface)>, - mut fallback: impl FnMut(&Surface) -> std::result::Result, -) -> std::result::Result<(), E> { - for (id, cache) in taken { - if let Some(LayerContent::Smart(sm)) = doc.layer_mut(id).map(|l| &mut l.content) - && sm.cache.is_none() - { - sm.cache = Some(fallback(&cache)?); - } - } - Ok(()) -} - -fn buffer_to_surface(buf: &photocraft_compose::Buffer, fmt: PixelFormat) -> Surface { - let n = fmt.channels(); - let mut data = vec![0.0f32; buf.px.len() * n]; - for (p, out) in buf.px.iter().zip(data.chunks_exact_mut(n)) { - photocraft_raster::from_rgba_into(&fmt, *p, out); - } - let mut s = Surface::new(fmt); - if !buf.rect.is_empty() { - s.write_region(buf.rect, &data); - } - s.prune(); - s -} - -fn source_surface(src: &Document, buf: &photocraft_compose::Buffer, fmt: PixelFormat) -> Result { - let gray = fmt.mode == ColorMode::Grayscale && src.pixel_format().mode != ColorMode::Grayscale; - let linear = fmt.sample == SampleType::F32 && src.depth != SampleType::F32; - if !gray && !linear { - return Ok(buffer_to_surface(buf, fmt)); - } - let mut doc = Document::new(src.name.clone(), src.size, src.mode, src.depth); - doc.icc_profile = src.icc_profile.clone(); - doc.layers = vec![Layer::new("source", LayerContent::Raster(buffer_to_surface(buf, src.pixel_format())))]; - if gray { - let gray_profile = crate::color_cmds::working_profile(ColorMode::Grayscale); - crate::color_cmds::convert_document(&mut doc, &gray_profile, photocraft_cms::Intent::RelativeColorimetric, true)?; - } - if linear { - crate::image_cmds::change_depth(&mut doc, SampleType::F32); - } - let surface = doc.layers.pop().and_then(|l| match l.content { - LayerContent::Raster(s) => Some(s), - _ => None, - }); - let surface = surface.ok_or_else(|| other("the smart object's source could not be converted"))?; - Ok(if surface.format() == fmt { surface } else { surface.convert(fmt) }) -} - -/// An SVG source rendered at `scale` times its own size (cached per scale), so a vector smart -/// object stays sharp however it is placed. -pub fn svg_source_image(bytes: &[u8], fmt: PixelFormat, scale: f64) -> Result { - let mut h = blake3::Hasher::new(); - h.update(bytes); - h.update(&scale.to_bits().to_le_bytes()); - let key = (*h.finalize().as_bytes(), fmt); - if let Some(img) = cache_get(&key) { - return Ok(img); - } - let buf = photocraft_io::svg::rasterize(bytes, scale as f32).map_err(|e| other(format!("can't render the SVG smart object: {e}")))?; - let img = SourceImage { surface: Arc::new(buffer_to_surface(&buf, fmt)), bounds: buf.rect }; - cache_put(key, img.clone()); - Ok(img) -} - -/// The scale a vector source is rasterised at for its placement: the larger axis scale of the -/// transform in 1/16 steps (so nudges reuse the cache), between 1/16 and 64. -fn vector_scale(sm: &SmartObject) -> f64 { - let [a, b, c, d, ..] = sm.transform.m; - let k = (a * a + b * b).sqrt().max((c * c + d * d).sqrt()); - if !k.is_finite() { - return 1.0; - } - ((k * 16.0).ceil() / 16.0).clamp(1.0 / 16.0, 64.0) -} - -/// The composited source image of `bytes` in pixel format `fmt` (decoded once, then cached). -pub fn source_image(file_name: &str, bytes: &[u8], fmt: PixelFormat) -> Result { - let key = cache_key(bytes, fmt); - if let Some(img) = cache_get(&key) { - return Ok(img); - } - let doc = decode_source(file_name, bytes)?; - let buf = photocraft_compose::flatten(&doc); - let img = SourceImage { surface: Arc::new(source_surface(&doc, &buf, fmt)?), bounds: doc.bounds() }; - cache_put(key, img.clone()); - Ok(img) -} - -/// Layer › Smart Objects › Stack Mode: the source's layers (or, when it holds a single group, the -/// group's layers) combined per pixel with `mode`. Cached like [`source_image`], keyed by mode. -pub fn stack_image(file_name: &str, bytes: &[u8], fmt: PixelFormat, mode: photocraft_doc::StackMode) -> Result { - use photocraft_algo::stack::Stat; - let mut key = cache_key(bytes, fmt); - key.0 = *blake3::hash(&[&key.0[..], b"stack:", mode.id().as_bytes()].concat()).as_bytes(); - if let Some(img) = cache_get(&key) { - return Ok(img); - } - let doc = decode_source(file_name, bytes)?; - let layers: &[Layer] = match doc.layers.as_slice() { - [only] if only.is_group() => only.children().unwrap_or_default(), - all => all, - }; - let bounds = doc.bounds(); - let frames: Vec> = layers - .iter() - .filter(|l| l.visible) - .map(|l| { - let mut one = l.clone(); - one.blend = BlendMode::Normal; - one.clipped = false; - photocraft_compose::render_layer(&one, bounds).px - }) - .collect(); - if frames.is_empty() { - return Err(EngineError::Other("the smart object's contents have no visible layers".into())); - } - let stat = match mode { - photocraft_doc::StackMode::Entropy => Stat::Entropy, - photocraft_doc::StackMode::Kurtosis => Stat::Kurtosis, - photocraft_doc::StackMode::Maximum => Stat::Maximum, - photocraft_doc::StackMode::Mean => Stat::Mean, - photocraft_doc::StackMode::Median => Stat::Median, - photocraft_doc::StackMode::Minimum => Stat::Minimum, - photocraft_doc::StackMode::Range => Stat::Range, - photocraft_doc::StackMode::Skewness => Stat::Skewness, - photocraft_doc::StackMode::StandardDeviation => Stat::StandardDeviation, - photocraft_doc::StackMode::Summation => Stat::Summation, - photocraft_doc::StackMode::Variance => Stat::Variance, - }; - let buf = photocraft_compose::Buffer { rect: bounds, px: photocraft_algo::stack::combine(&frames, stat) }; - let img = SourceImage { surface: Arc::new(source_surface(&doc, &buf, fmt)?), bounds }; - cache_put(key, img.clone()); - Ok(img) -} - -// ---------- rendering ---------- - -/// Mix a filter's result with its input, without stacking the same pixel coverage twice. -fn blend_surfaces(base: &Surface, top: &Surface, mode: BlendMode, opacity: f32) -> Surface { - if opacity <= 0.0 { - return base.clone(); - } - let fmt = base.format(); - let area = base.content_bounds().union(&top.content_bounds()); - let mut out = base.clone(); - if area.is_empty() { - return out; - } - let n = fmt.channels(); - let (b, t) = (base.read_region(area), top.read_region(area)); - // Alpha-preserving filters edit the same coverage. A non-Normal filter that - // changes coverage (e.g. blur) must also retain input-only pixels and admit - // filtered-only pixels, as Photoshop's Smart Filter blend oracles require. - // Classify the whole result so unchanged pixels do not switch blend rules - // independently at the edge of a blur. - let composite_coverage = mode != BlendMode::Normal && fmt.alpha && b.chunks_exact(n).zip(t.chunks_exact(n)).any(|(bp, tp)| bp.last() != tp.last()); - let mut o = vec![0.0f32; b.len()]; - for ((bp, tp), op) in b.chunks_exact(n).zip(t.chunks_exact(n)).zip(o.chunks_exact_mut(n)) { - let b = photocraft_raster::to_rgba(&fmt, bp); - let t = photocraft_raster::to_rgba(&fmt, tp); - if composite_coverage { - let rgba = photocraft_color::blend::composite(mode, b, t, opacity); - photocraft_raster::from_rgba_into(&fmt, rgba, op); - continue; - } - let cb = [b[0], b[1], b[2]]; - let ct = [t[0], t[1], t[2]]; - let color = if fmt.sample == photocraft_color::SampleType::F32 { - photocraft_color::blend::blend_rgb_hdr(mode, cb, ct) - } else { - photocraft_color::blend::blend_rgb(mode, cb, ct) - }; - // A filter edits this surface, rather than adding a second source-over layer. Mix - // premultiplied results so alpha-preserving filters keep coverage at every opacity, - // while Normal-mode filters that change coverage interpolate it too. - let a = b[3] + (t[3] - b[3]) * opacity; - let mut rgba = [0.0, 0.0, 0.0, a]; - if a > 0.0 { - for c in 0..3 { - rgba[c] = (cb[c] * b[3] * (1.0 - opacity) + color[c] * t[3] * opacity) / a; - } - } - photocraft_raster::from_rgba_into(&fmt, rgba, op); - } - out.write_region(area, &o); - out.prune(); - out -} - -/// Runs the smart filter stack on the placed (unfiltered) content. A filter the session's -/// authority denies surfaces its error (the trusted compositor path has no gate installed, so -/// this reads ambiently only when the caller established one and it refuses). -pub fn apply_smart_filters(placed: &Surface, sm: &SmartObject, canvas: Rect) -> Result { - if !sm.filters_enabled || !sm.smart_filters.iter().any(|f| f.visible) { - return Ok(placed.clone()); - } - let mut cur = placed.clone(); - // Edge pixels repeat at the canvas ∪ placed-content edge, as for layer filters. - let extent = canvas.union(&placed.content_bounds()); - for f in sm.smart_filters.iter().filter(|f| f.visible) { - cur = apply_smart_filter(f, &cur, filter_bounds(f, placed, canvas), extent)?; - } - Ok(match sm.filter_mask.as_ref().filter(|m| m.enabled) { - Some(m) => photocraft_compose::filter_mask::mix(placed, &cur, m), - None => cur, - }) -} - -/// The reference bounds of smart filter `f`. Render filters work within the smart object, as -/// Photoshop's do: Lens Flare's centre is a fraction of the object, and Clouds and Fibers fill it -/// and size their pattern by it. The object is its placed content's bounds (which leaves out -/// fully transparent edges of the source); the other filters use the canvas, as on a layer. -fn filter_bounds(f: &SmartFilter, placed: &Surface, canvas: Rect) -> Rect { - match placed.content_bounds() { - b if renders_in_object(f) && !b.is_empty() => b, - _ => canvas, - } -} - -fn renders_in_object(f: &SmartFilter) -> bool { - matches!(f.command.as_str(), "filter.render.clouds" | "filter.render.differenceClouds" | "filter.render.fibers" | "filter.render.lensFlare") -} - -/// One visible smart filter over `cur`, blended with its blend mode and opacity. `Err` when the -/// requesting session's authority denies the filter's params: callers surface the error instead of -/// rendering (and caching) unfiltered pixels. -fn apply_smart_filter(f: &SmartFilter, cur: &Surface, canvas: Rect, extent: Rect) -> Result { - let out = match crate::filters::apply_filter_to_surface(&f.command, &f.params, cur, canvas, None, extent)? { - // Unknown ids (e.g. Photoshop filters we don't implement) leave the pixels alone. - Some(out) => out, - None => cur.clone(), - }; - if f.blend == BlendMode::Normal && f.opacity >= 1.0 { Ok(out) } else { Ok(blend_surfaces(cur, &out, f.blend, f.opacity.clamp(0.0, 1.0))) } -} - -/// The source placed in document pixels, before any smart filter. -fn place(name: &str, bytes: &[u8], fmt: PixelFormat, sm: &SmartObject) -> Result { - // A vector source is rendered at the placement's scale, and the placement is divided by - // that scale so the rendered pixels land where the source units would. - if sm.stack_mode.is_none() && sm.warp.is_none() && photocraft_io::svg::is_svg(bytes) { - let k = vector_scale(sm); - let img = svg_source_image(bytes, fmt, k)?; - return Ok(match &sm.perspective { - Some(p) => { - let [h0, h1, h2, h3, h4, h5, h6, h7, h8] = *p; - let h = Homography([h0 / k, h1 / k, h2, h3 / k, h4 / k, h5, h6 / k, h7 / k, h8]); - photocraft_algo::warp::place_source_projective(&img.surface, img.bounds, &h, None)? - } - None => { - let [a, b, c, d, e, f] = sm.transform.m; - let t = Affine { m: [a / k, b / k, c / k, d / k, e, f] }; - photocraft_algo::warp::place_source(&img.surface, img.bounds, &t, None)? - } - }); - } - let img = match sm.stack_mode { - Some(mode) => stack_image(name, bytes, fmt, mode)?, - None => source_image(name, bytes, fmt)?, - }; - // Through the warp (source space) and the transform in one pass; whole-pixel moves are exact. - Ok(match &sm.perspective { - Some(p) => photocraft_algo::warp::place_source_projective(&img.surface, img.bounds, &Homography(*p), sm.warp.as_ref())?, - None => photocraft_algo::warp::place_source(&img.surface, img.bounds, &sm.transform, sm.warp.as_ref())?, - }) -} - -/// The box of a smart object's source in source pixels (what its warp's `us`/`vs` span), or `None` -/// when the source can't be read. -pub(crate) fn source_box(doc: &Document, sm: &SmartObject) -> Option<[f64; 4]> { - let (name, bytes) = source_bytes(&doc.metadata, &sm.source)?; - let fmt = doc.pixel_format(); - let img = match sm.stack_mode { - Some(mode) => stack_image(&name, &bytes, fmt, mode), - None => source_image(&name, &bytes, fmt), - } - .ok()?; - let r = img.bounds; - Some([f64::from(r.x0), f64::from(r.y0), f64::from(r.x1), f64::from(r.y1)]) -} - -/// Renders a smart object from its source. `Ok(None)` when the source is unavailable (a missing -/// linked file, or a PSD placed layer without embedded data): callers keep the existing cache. -pub fn render(doc: &Document, sm: &SmartObject) -> Result> { - render_in(doc, sm, &JobCtx::new()) -} - -/// [`render`], reporting progress per smart filter to `ctx` and stopping between filters once it -/// is cancelled. Gives the same pixels as [`apply_smart_filters`] on the placed source, but -/// starts from the deepest stage of the stack already rendered (see [`stack_cache`]). -fn render_in(doc: &Document, sm: &SmartObject, ctx: &JobCtx) -> Result> { - // Stored filters can come from a file or another layer. Check before looking up cached - // stages too: a trusted UI render may have populated this process-wide cache earlier. - for filter in sm.smart_filters.iter().filter(|f| sm.filters_enabled && f.visible) { - crate::jobs::authorize_render_command(&filter.command, &filter.params)?; - } - let Some((name, bytes)) = source_bytes(&doc.metadata, &sm.source) else { return Ok(None) }; - let (fmt, canvas) = (doc.pixel_format(), doc.bounds()); - let placed_key = stack_cache::placed_key(&bytes, fmt, sm, canvas); - let placed = || -> Result { - if let Some(stage) = stack_cache::get(&placed_key) { - return Ok(stage); - } - let surface = place(&name, &bytes, fmt, sm)?; - // Edge pixels repeat at the canvas ∪ placed-content edge, as for layer filters. - let stage = Stage { extent: canvas.union(&surface.content_bounds()), surface }; - stack_cache::put(placed_key, &stage); - Ok(stage) - }; - let filters: Vec<&SmartFilter> = sm.smart_filters.iter().filter(|f| sm.filters_enabled && f.visible).collect(); - if filters.is_empty() { - return Ok(Some(placed()?.surface)); - } - let keys: Vec = filters - .iter() - .scan(placed_key, |key, f| { - *key = stack_cache::filter_key(key, f); - Some(*key) - }) - .collect(); - let deepest = keys.iter().enumerate().rev().find_map(|(i, key)| stack_cache::get(key).map(|stage| (i + 1, stage))); - let (done, mut cur) = match deepest { - Some(hit) => hit, - None => (0, placed()?), - }; - let n = filters.len() as f32; - // The object's bounds, found once: the placed stage may have been evicted from the cache, and - // placing it again for every render filter would decode the source each time. - let mut object_bounds: Option = None; - for (i, (f, key)) in filters.iter().zip(&keys).enumerate().skip(done) { - ctx.check()?; - ctx.progress(i as f32 / n, ""); - let bounds = match object_bounds { - _ if !renders_in_object(f) => canvas, - Some(b) => b, - None => *object_bounds.insert(filter_bounds(f, &placed()?.surface, canvas)), - }; - cur = Stage { surface: apply_smart_filter(f, &cur.surface, bounds, cur.extent)?, extent: cur.extent }; - stack_cache::put(*key, &cur); - } - ctx.progress(1.0, ""); - Ok(Some(match sm.filter_mask.as_ref().filter(|m| m.enabled) { - Some(m) => photocraft_compose::filter_mask::mix(&placed()?.surface, &cur.surface, m), - None => cur.surface, - })) -} - -/// Bytes held by rendered smart filter stages. -pub fn stack_cache_bytes() -> usize { - stack_cache::bytes() -} - -/// Drop every rendered smart filter stage (Edit › Purge › All). Returns the bytes released. -pub fn purge_stack_cache() -> usize { - stack_cache::purge() -} - -/// The smart object's pixels below smart filter `index` (the input that filter edits): the placed -/// source and the filters under it, without the filter mask. `Ok(None)` when the source is -/// unavailable. -pub fn render_below_filter(doc: &Document, sm: &SmartObject, index: usize) -> Result> { - let mut below = sm.clone(); - below.smart_filters.truncate(index); - below.filter_mask = None; - render(doc, &below) -} - -/// Re-renders smart layer `l` (which lives in `doc`) in place. Returns false if its source is -/// unavailable or a visible filter can't be applied (the cache is then left alone). -pub fn refresh_layer(doc: &Document, l: &mut Layer) -> Result { - if matches!(&l.content, LayerContent::Smart(sm) if !unapplied_filters(sm).is_empty()) { - return Ok(false); - } - refresh_layer_in(doc, l, &JobCtx::new()) -} - -fn unapplied_filters(sm: &SmartObject) -> Vec { - sm.smart_filters - .iter() - .filter(|f| sm.filters_enabled && f.visible && crate::commands::find(&f.command).is_none()) - .map(|f| f.params.get("name").and_then(Value::as_str).unwrap_or(&f.command).to_string()) - .collect() -} - -fn refresh_layer_in(doc: &Document, l: &mut Layer, ctx: &JobCtx) -> Result { - let LayerContent::Smart(sm) = &mut l.content else { return Ok(false) }; - match render_in(doc, sm, ctx)? { - Some(px) => { - sm.cache = Some(px); - Ok(true) - } - None => Ok(false), - } -} - -/// Re-renders the smart object `id` of `doc`. -pub fn refresh(doc: &mut Document, id: LayerId) -> Result { - refresh_in(doc, id, &JobCtx::new()) -} - -fn refresh_in(doc: &mut Document, id: LayerId, ctx: &JobCtx) -> Result { - let mut l = doc.layer(id).cloned().ok_or(EngineError::NoLayer(id))?; - if !matches!(l.content, LayerContent::Smart(_)) { - return Err(other("the layer is not a smart object")); - } - let ok = refresh_layer_in(doc, &mut l, ctx)?; - if ok && let Some(dst) = doc.layer_mut(id) { - dst.content = l.content; - } - Ok(ok) -} - -fn refresh_or_fail(doc: &mut Document, id: LayerId) -> Result<()> { - refresh_or_fail_in(doc, id, &JobCtx::new()) -} - -fn refresh_or_fail_in(doc: &mut Document, id: LayerId, ctx: &JobCtx) -> Result<()> { - if refresh_in(doc, id, ctx)? { - return Ok(()); - } - if let SmartSource::Linked { path } = &smart(doc, id)?.source - && let Err(why @ crate::doc_path::NotFollowed::Refused(_)) = crate::doc_path::resolve(path) - { - return Err(crate::doc_path::refusal("the linked file", path, why)); - } - Err(other("the smart object's contents are unavailable (missing linked file?), so it can't be re-rendered")) -} - -fn smart(doc: &Document, id: LayerId) -> Result<&SmartObject> { - match &doc.layer(id).ok_or(EngineError::NoLayer(id))?.content { - LayerContent::Smart(sm) => Ok(sm), - _ => Err(other("the layer is not a smart object")), - } -} - -fn smart_mut(doc: &mut Document, id: LayerId) -> Result<&mut SmartObject> { - match &mut doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?.content { - LayerContent::Smart(sm) => Ok(sm), - _ => Err(other("the layer is not a smart object")), - } -} - -/// Whether `l`'s filter mask can be painted (`"target":"filterMask"`): a smart object with smart -/// filters. Its filter mask need not exist yet: painting starts it white (Reveal All), the mask -/// Photoshop adds with the first smart filter. -pub(crate) fn filter_mask_paintable(l: &Layer) -> std::result::Result<(), String> { - match &l.content { - LayerContent::Smart(sm) if !sm.smart_filters.is_empty() => Ok(()), - LayerContent::Smart(_) => Err(format!("smart object \"{}\" has no smart filters, so no filter mask", l.name)), - other => Err(format!("the active layer is {} {} layer, not a smart object", other.article(), other.kind_name())), - } -} - -/// The filter mask surface of smart object `id` for painting into, made white (Reveal All) first -/// when the object has smart filters but no filter mask yet. The caller re-renders the object -/// afterwards ([`refresh_after_filter_mask_edit`]). -pub(crate) fn filter_mask_surface(doc: &mut Document, id: LayerId) -> Result<&mut Surface> { - let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; - filter_mask_paintable(l).map_err(EngineError::Other)?; - let sm = smart_mut_of(l)?; - Ok(&mut sm.filter_mask.get_or_insert_with(LayerMask::reveal_all).surface) -} - -/// Re-renders smart object `id` after its filter mask was painted, filled or filtered, so the -/// stroke shows (where the mask is black the smart filters don't). Part of the same history step. -pub(crate) fn refresh_after_filter_mask_edit(doc: &mut Document, id: LayerId) -> Result<()> { - if matches!(doc.layer(id).map(|l| &l.content), Some(LayerContent::Smart(_))) { refresh_or_fail(doc, id) } else { Ok(()) } -} - -fn smart_mut_of(l: &mut Layer) -> Result<&mut SmartObject> { - match &mut l.content { - LayerContent::Smart(sm) => Ok(sm), - _ => Err(other("the layer is not a smart object")), - } -} - -fn mask_from_selection(sel: &Surface) -> LayerMask { - LayerMask { surface: sel.clone(), enabled: true, linked: true, density: 1.0, feather: 0.0 } -} - -/// Appends a smart filter (from a `filter.*` command) and re-renders. A selection becomes the -/// filter mask, as in Photoshop. Without a renderable source the filter is applied to the cached -/// pixels (and still recorded). -pub(crate) fn add_smart_filter(doc: &mut Document, id: LayerId, sf: photocraft_doc::SmartFilter, selection: Option<&Surface>) -> Result<()> { - let canvas = doc.bounds(); - let renderable = source_bytes(&doc.metadata, &smart(doc, id)?.source).is_some(); - let sm = smart_mut(doc, id)?; - if renderable { - if let Some(sel) = selection - && sm.filter_mask.is_none() - { - sm.filter_mask = Some(mask_from_selection(sel)); - } - sm.smart_filters.push(sf); - return refresh_or_fail(doc, id); - } - let bounds = selection.map(Surface::content_bounds).filter(|b| !b.is_empty()).unwrap_or(canvas); - let cache = sm.cache.as_ref().ok_or_else(|| other("smart object has no pixels"))?; - let out = crate::filters::apply_filter_to_surface(&sf.command, &sf.params, cache, bounds, selection, canvas)? - .ok_or_else(|| other(format!("unknown filter {}", sf.command)))?; - sm.cache = Some(out); - sm.smart_filters.push(sf); - Ok(()) -} - -/// Rounds float noise off a composed transform (scale 0.1 then 10 should be exactly 1), so -/// repeated transforms land back on exact, lossless placements. -pub(crate) fn snap_affine(a: Affine) -> Affine { - Affine { m: a.m.map(|v| if (v - v.round()).abs() < 1e-9 { v.round() } else { v }) } -} - -/// Where the smart object's source pixels land in the document: its projective map (Distort, -/// Perspective) or its affine transform. -pub fn placement(sm: &SmartObject) -> Homography { - sm.perspective.map(Homography).unwrap_or_else(|| affine_homography(&sm.transform)) -} - -pub(crate) fn affine_homography(a: &Affine) -> Homography { - let [a, b, c, d, e, f] = a.m; - Homography([a, c, e, b, d, f, 0.0, 0.0, 1.0]) -} - -/// Sets where the source lands. An affine map is stored exactly in `transform` (no -/// `perspective`); a projective one in `perspective`, with `transform` its affine approximation at -/// the source origin (for code that only needs scale and position). -pub(crate) fn set_placement(sm: &mut SmartObject, h: Homography) { - let m = h.0; - let n = if m[8].abs() > 1e-12 { m.map(|v| v / m[8]) } else { m }; - if n[6].abs() < 1e-12 && n[7].abs() < 1e-12 { - sm.transform = snap_affine(Affine { m: [n[0], n[3], n[1], n[4], n[2], n[5]] }); - sm.perspective = None; - return; - } - let h = Homography(n); - let (o, x, y) = (h.apply(0.0, 0.0), h.apply(1.0, 0.0), h.apply(0.0, 1.0)); - sm.transform = Affine { m: [x.0 - o.0, x.1 - o.1, y.0 - o.0, y.1 - o.1, o.0, o.1] }; - sm.perspective = Some(n); -} - -/// Composes `a` (document → document) onto the smart object's placement. -pub(crate) fn transform_placement(sm: &mut SmartObject, a: &Affine) { - match sm.perspective { - None => sm.transform = snap_affine(a.mul(&sm.transform)), - Some(_) => set_placement(sm, affine_homography(a).mul(&placement(sm))), - } -} - -/// Moves a smart object by whole pixels without re-rendering. -pub(crate) fn shift_smart(sm: &mut SmartObject, dx: i32, dy: i32) { - transform_placement(sm, &Affine::translate(dx as f64, dy as f64)); - if let Some(c) = &mut sm.cache { - *c = crate::layer_multi_cmds::shift_surface(c, dx, dy); - } - if let Some(m) = &mut sm.filter_mask { - m.surface = crate::layer_multi_cmds::shift_surface(&m.surface, dx, dy); - } -} - -/// Forget PSD placed-layer data that no longer describes the smart object (its source changed): -/// PSD export then writes fresh placed-layer blocks and embeds the new source. -fn detach_psd(l: &mut Layer) { - if let LayerContent::Smart(sm) = &mut l.content { - sm.psd_raw = None; - } - l.psd_blocks.retain(|(k, _)| !PLACED_KEYS.contains(&k)); -} - -// ---------- conversion ---------- - -/// Moves a layer (any kind) by whole pixels without re-rendering anything. -fn shift_layer(l: &mut Layer, dx: i32, dy: i32) { - if dx == 0 && dy == 0 { - return; - } - let a = Affine::translate(dx as f64, dy as f64); - let mv = |s: &Surface| translate_surface(s, dx, dy); - if let Some(m) = &mut l.mask { - m.surface = mv(&m.surface); - } - if let Some(vm) = &mut l.vector_mask { - vm.path = vm.path.transform(&a); - } - if let Some(fc) = &mut l.fill_cache { - fc.surface = mv(&fc.surface); - } - match &mut l.content { - LayerContent::Raster(s) => *s = mv(s), - LayerContent::Text(t) => { - t.transform = a.mul(&t.transform); - if let Some(c) = &mut t.cache { - *c = mv(c); - } - } - LayerContent::Shape(sh) => { - crate::vector_cmds::transform_shape(sh, &a); - if let Some(c) = &mut sh.cache { - *c = mv(c); - } - } - LayerContent::Smart(sm) => shift_smart(sm, dx, dy), - LayerContent::Group(g) => g.children.iter_mut().for_each(|c| shift_layer(c, dx, dy)), - LayerContent::Adjustment(_) | LayerContent::Fill(_) => {} - } -} - -fn subtree_bounds(l: &Layer, canvas: Rect) -> Rect { - match &l.content { - LayerContent::Group(g) => g.children.iter().map(|c| subtree_bounds(c, canvas)).fold(Rect::EMPTY, |a, b| a.union(&b)), - LayerContent::Adjustment(_) | LayerContent::Fill(_) => canvas, - _ => l.surface().map_or(Rect::EMPTY, Surface::content_bounds), - } -} - -fn any_layer(l: &Layer, f: &dyn Fn(&Layer) -> bool) -> bool { - f(l) || l.children().is_some_and(|c| c.iter().any(|c| any_layer(c, f))) -} - -/// Builds the smart-object layer replacing `l` in `doc`: the layer (with its mask, effects and -/// fill opacity) becomes a nested document cropped to its rendered bounds; visibility, opacity, -/// blend mode, clipping and label stay on the smart layer. The cache is the exact composite, so -/// the document looks the same before and after. -pub fn layer_to_smart(doc: &Document, l: &Layer) -> Result { - let background = doc.is_background(l.id); - let mut inner = l.clone(); - inner.visible = true; - inner.opacity = 1.0; - inner.clipped = false; - inner.locks = Default::default(); - if !(inner.is_group() && inner.blend == BlendMode::PassThrough) { - inner.blend = BlendMode::Normal; - } - if background { - inner.name = "Layer 0".into(); - } - let mut out = layers_to_smart(doc, &l.name, vec![inner])?; - if background { - out.name = "Layer 0".into(); - } - out.visible = l.visible; - out.opacity = l.opacity; - out.blend = if l.blend == BlendMode::PassThrough { BlendMode::Normal } else { l.blend }; - out.clipped = l.clipped; - out.label = l.label; - if !background { - out.locks = l.locks; - } - Ok(out) -} - -/// Builds a smart-object layer named `name` whose nested document holds `layers` (bottom to top) -/// at its top level, as Photoshop does when several layers are converted: no wrapper group. The -/// nested document is cropped to the rendered bounds and the cache is the exact composite (the -/// same as the layers inside a pass-through group). The smart layer is visible, opaque and Normal. -pub fn layers_to_smart(doc: &Document, name: &str, layers: Vec) -> Result { - let canvas = doc.bounds(); - let mut sub = Document::new(format!("{name}.pcraft"), doc.size, doc.mode, doc.depth); - sub.resolution_dpi = doc.resolution_dpi; - sub.icc_profile = doc.icc_profile.clone(); - sub.global_light = doc.global_light; - // Pattern fills and pattern layer effects reference document-level patterns by ID. - // Preserve those resources in the embedded document before rendering or saving it. - sub.patterns = doc.patterns.clone(); - if layers.iter().any(|l| any_layer(l, &|x| matches!(x.content, LayerContent::Smart(_)))) { - // Nested PSD placed layers find their embedded files here. - sub.metadata.psd_global_blocks = doc.metadata.psd_global_blocks.clone(); - } - let has_fx = layers.iter().any(|l| any_layer(l, &|x| x.effects.enabled && !x.effects.items.is_empty())); - let region = layers.iter().map(|l| subtree_bounds(l, canvas)).fold(canvas, |a, b| a.union(&b)).inflate(if has_fx { 256 } else { 0 }); - sub.layers = layers; - - let buf = photocraft_compose::render(&sub, region); - let w = region.width() as usize; - let mut b = Rect::EMPTY; - for (i, p) in buf.px.iter().enumerate() { - if p[3] > 0.0 { - let (x, y) = (region.x0 + (i % w) as i32, region.y0 + (i / w) as i32); - b = b.union(&Rect::new(x, y, x + 1, y + 1)); - } - } - if b.is_empty() { - return Err(other("the layer is empty, so there is nothing to convert")); - } - let fmt = doc.pixel_format(); - let mut cache = buffer_to_surface(&buf, fmt); - cache = photocraft_algo::resample::crop_surface(&cache, b); - cache.prune(); - - sub.layers.iter_mut().for_each(|l| shift_layer(l, -b.x0, -b.y0)); - sub.size = Size::new(b.width(), b.height()); - let bytes = encode_source(&sub)?; - // Seed the decode cache with the composite we already have. - cache_put(cache_key(&bytes, fmt), SourceImage { surface: Arc::new(translate_surface(&cache, -b.x0, -b.y0)), bounds: sub.bounds() }); - - let source = SmartSource::Embedded { file_name: sub.name.clone(), bytes: Arc::new(bytes) }; - Ok(Layer::new(name, LayerContent::Smart(SmartObject::new(source, Affine::translate(b.x0 as f64, b.y0 as f64), Some(cache))))) -} - -fn convert(s: &mut Session, p: &Value) -> Result { - let ids = match p.get("layer").and_then(Value::as_u64) { - Some(id) => vec![LayerId(id)], - None => crate::layer_multi_cmds::selected(s), - }; - let new_id = s.edit("Convert to Smart Object", |doc, active| { - let ids = crate::layer_multi_cmds::top_level(doc, &ids); - let top = *ids.last().ok_or_else(|| other("no layer selected"))?; - let l = doc.layer(top).ok_or(EngineError::NoLayer(top))?; - let so = if ids.len() == 1 { - layer_to_smart(doc, l)? - } else { - let children = ids.iter().map(|id| doc.layer(*id).cloned().ok_or(EngineError::NoLayer(*id))).collect::>>()?; - layers_to_smart(doc, &l.name, children)? - }; - let new_id = so.id; - // As with Group Layers, place the result in the top selected root's parent. Insert - // before removal so paths shifting in other parents cannot discard unselected content. - doc.insert_above(Some(top), so); - for id in &ids { - doc.remove(*id).ok_or(EngineError::NoLayer(*id))?; - } - if let [only] = ids[..] { - retarget_layer_refs(doc, only, new_id); - } - *active = Some(new_id); - Ok(new_id) - })?; - crate::layer_multi_cmds::reselect(s, vec![new_id], Some(new_id)); - Ok(json!({"layer": new_id.0})) -} - -fn retarget_layer_refs(doc: &mut Document, from: LayerId, to: LayerId) { - let Some((fill_opacity, effects)) = doc.layer(to).map(|l| (l.fill_opacity, l.effects.clone())) else { return }; - for comp in doc.layer_comps.iter_mut().chain(doc.last_document_state.as_mut()) { - for state in comp.states.iter_mut().filter(|state| state.layer == from) { - state.layer = to; - if let Some(appearance) = &mut state.appearance { - appearance.fill_opacity = fill_opacity; - appearance.effects = effects.clone(); - } - } - } - for def in doc.variables.defs.iter_mut().filter(|def| def.layer == from) { - def.layer = to; - } - for slice in doc.slices.list.iter_mut().filter(|slice| slice.layer == Some(from)) { - slice.layer = Some(to); - } -} - -// ---------- contents ---------- - -fn via_copy(s: &mut Session, p: &Value) -> Result { - let id = layer_param(s, p)?; - s.edit("New Smart Object via Copy", |doc, active| { - let src = doc.layer(id).ok_or(EngineError::NoLayer(id))?; - let mut copy = src.duplicate(); - copy.name = doc.copy_name(&src.name); - if let LayerContent::Smart(sm) = &mut copy.content { - // Independent contents: resolve to embedded bytes and drop the shared PSD uuid. - sm.contents_id = SmartContentsId::fresh(); - if let Some((file_name, bytes)) = source_bytes(&doc.metadata, &sm.source) { - sm.source = SmartSource::Embedded { file_name, bytes }; - } - } else { - return Err(other("the layer is not a smart object")); - } - detach_psd(&mut copy); - let new_id = doc.insert_above(Some(id), copy); - *active = Some(new_id); - Ok(json!({"layer": new_id.0})) - }) -} - -fn path_param<'a>(cmd: &str, p: &'a Value) -> Result<&'a str> { - p.get("path").and_then(Value::as_str).filter(|s| !s.is_empty()).ok_or_else(|| bad(cmd, "pass `path`")) -} - -/// Instances sharing contents in this document, including those inside groups. -fn instances(doc: &Document, contents_id: SmartContentsId) -> Vec { - doc.walk().into_iter().filter_map(|(_, _, l)| matches!(&l.content, LayerContent::Smart(sm) if sm.contents_id == contents_id).then_some(l.id)).collect() -} - -/// Swaps shared contents, keeping each instance's transform and filters, and re-renders. -fn set_source(s: &mut Session, p: &Value, label: &str, keep_psd: bool, make: impl FnOnce(&Metadata, &SmartSource) -> Result) -> Result { - let id = layer_param(s, p)?; - let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; - let new = make(&doc.metadata, &smart(doc, id)?.source)?; - set_shared_source(s, id, label, keep_psd, new) -} - -// Keep the shared-instance transaction out of the per-command source-builder instantiations. -fn set_shared_source(s: &mut Session, id: LayerId, label: &str, keep_psd: bool, new: SmartSource) -> Result { - let (parent, contents_id, changed, warnings) = s.edit(label, |doc, _| { - let contents_id = smart(doc, id)?.contents_id; - let changed = instances(doc, contents_id); - let mut warnings = std::collections::BTreeSet::new(); - for &instance in &changed { - smart_mut(doc, instance)?.source = new.clone(); - if !keep_psd { - detach_psd(doc.layer_mut(instance).ok_or(EngineError::NoLayer(instance))?); - } - warnings - .extend(unapplied_filters(smart(doc, instance)?).into_iter().map(|n| format!("the {n} smart filter is not supported, so it was not applied"))); - refresh_or_fail(doc, instance)?; - } - Ok((doc.id, contents_id, changed, warnings)) - })?; - // An old editor must not overwrite newly replaced/relinked contents on close. Keep its - // document open, but the next Edit Contents opens the replacement source. - s.smart_links.retain(|l| l.parent != parent || l.contents_id != contents_id); - // Every instance changed, not only `layer`: list them, so a caller doesn't repeat the - // command once per copy (#4075). - Ok(json!({"layer": id.0, "instances": changed.iter().map(|l| l.0).collect::>(), "warnings": warnings})) -} - -fn replace_contents(s: &mut Session, p: &Value) -> Result { - let path = path_param("layer.smartObjects.replaceContents", p)?.to_string(); - let bytes = photocraft_format::read_file(std::path::Path::new(&path)).map_err(|e| other(format!("can't read {path}: {e}")))?; - let id = layer_param(s, p)?; - replace_contents_bytes(s, id, &base_name(&path), bytes) -} - -/// Replace Contents with a file the caller already read, for the smart object `p` names (`layer`, -/// else the active layer): the body of the command minus its ambient path read (#8061). -pub fn replace_contents_from_bytes(s: &mut Session, p: &Value, file_name: &str, bytes: Vec) -> Result { - let id = layer_param(s, p)?; - replace_contents_bytes(s, id, file_name, bytes) -} - -/// Replace Contents from a file's name and bytes: what the desktop and web file pickers hand over. -pub fn replace_contents_bytes(s: &mut Session, id: LayerId, file_name: &str, bytes: Vec) -> Result { - decode_source(file_name, &bytes)?; // fail before touching the document - set_shared_source(s, id, "Replace Contents", false, SmartSource::Embedded { file_name: file_name.to_string(), bytes: Arc::new(bytes) }) -} - -/// The file name and bytes of smart object `id`'s contents. -pub fn contents_of(doc: &Document, id: LayerId) -> Result<(String, Arc>)> { - source_bytes(&doc.metadata, &smart(doc, id)?.source).ok_or_else(|| other("the smart object's contents are unavailable")) -} - -/// Writes the smart object's file as it is. To a path with another extension (a `.png` for -/// `.psb` or `.pcraft` contents) the contents are opened and exported in that format instead. -fn export_contents(s: &mut Session, p: &Value) -> Result { - let path = path_param("layer.smartObjects.exportContents", p)?; - let id = layer_param(s, p)?; - let (name, bytes) = contents_of(&s.active().ok_or(EngineError::NoDocument)?.doc, id)?; - let ext = |f: &str| { - let e = std::path::Path::new(f).extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase); - e.map(|e| match e.as_str() { - "jpeg" => "jpg".to_string(), - "tiff" => "tif".to_string(), - _ => e, - }) - }; - if ext(path).is_none() || ext(path) == ext(&name) { - crate::file_cmds::write_file(path, &bytes)?; - return Ok(json!({"path": path, "fileName": name, "bytes": bytes.len(), "converted": false})); - } - let contents = decode_source(&name, &bytes)?; - let r = photocraft_io::export(&contents, path, &Default::default()).map_err(|e| other(format!("can't export the contents as {}: {e}", base_name(path))))?; - crate::file_cmds::write_file(path, &r.bytes)?; - Ok(json!({"path": path, "fileName": name, "bytes": r.bytes.len(), "converted": true, "warnings": r.warnings})) -} - -fn edit_contents(s: &mut Session, p: &Value) -> Result { - let id = layer_param(s, p)?; - let st = s.active().ok_or(EngineError::NoDocument)?; - let parent = st.doc.id; - let contents_id = smart(&st.doc, id)?.contents_id; - // Already open for editing: switch to that document rather than opening another copy. - if let Some(index) = - s.smart_links.iter().find(|l| l.parent == parent && l.contents_id == contents_id).and_then(|l| s.documents().iter().position(|d| d.doc.id == l.child)) - { - s.set_active(index); - return Ok(json!({"document": index, "parentLayer": id.0})); - } - let source = &smart(&st.doc, id)?.source; - let (name, bytes) = authorized_source_bytes(s, "layer.smartObjects.editContents", &st.doc.metadata, source)? - .ok_or_else(|| other("the smart object's contents are unavailable"))?; - let mut child = decode_source(&name, &bytes)?; - // Bundles keep their document id; each open copy needs its own. - child.id = DocId::fresh(); - child.name = name; - let index = s.add_document(child, None); - // Admission may replace an ID already owned by another open document. - let child_id = s.documents().get(index).ok_or(EngineError::NoDocument)?.doc.id; - s.smart_links.retain(|l| l.child != child_id); - s.smart_links.push(SmartLink { child: child_id, parent, layer: id, contents_id }); - Ok(json!({"document": index, "parentLayer": id.0})) -} - -/// Writes an Edit Contents document back into all its parent instances (one undoable step in the -/// parent) and marks it saved. Returns false if `index` isn't an Edit Contents document. -pub fn commit_child(s: &mut Session, index: usize) -> Result { - let Some(st) = s.docs.get(index) else { return Ok(false) }; - let child = st.doc.clone(); - let Some(link) = s.smart_links.iter().find(|l| l.child == child.id).copied() else { return Ok(false) }; - let parent = s.docs.iter().position(|d| d.doc.id == link.parent).ok_or_else(|| other("the smart object's document was closed"))?; - let bytes = Arc::new(encode_source(&child)?); - let prev = s.active; - s.active = Some(parent); - s.note_active_change(); - let r = s.edit("Edit Contents", |doc, _| { - let ids = instances(doc, link.contents_id); - if ids.is_empty() { - return Err(other("the smart object's instances were removed")); - } - for id in ids { - let sm = smart_mut(doc, id)?; - let name = match &sm.source { - SmartSource::Embedded { file_name, .. } => file_name.as_str(), - SmartSource::Linked { .. } => child.name.as_str(), - }; - let stem = name.rsplit_once('.').map_or(name, |(stem, _)| stem); - sm.source = SmartSource::Embedded { file_name: format!("{stem}.pcraft"), bytes: bytes.clone() }; - detach_psd(doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?); - refresh_or_fail(doc, id)?; - } - Ok(()) - }); - s.active = prev; - s.note_active_change(); - r?; - if let Some(st) = s.docs.get_mut(index) { - st.saved_revision = st.revision; - } - Ok(true) -} - -/// Called before a document closes: an edited Edit Contents document updates its parent. -pub(crate) fn on_close(s: &mut Session, index: usize) { - let Some(st) = s.docs.get(index) else { return }; - let id = st.doc.id; - if st.is_dirty() && s.smart_links.iter().any(|l| l.child == id) { - let _ = commit_child(s, index); - } - s.smart_links.retain(|l| l.child != id && l.parent != id); -} - -fn is_smart_child(s: &Session) -> std::result::Result<(), String> { - let d = s.active().ok_or("no document open")?; - if s.smart_links.iter().any(|l| l.child == d.doc.id) { Ok(()) } else { Err("this document isn't smart object contents".into()) } -} - -fn update_all(s: &mut Session) -> Result { - let ids: Vec = s - .active() - .ok_or(EngineError::NoDocument)? - .doc - .walk() - .into_iter() - .filter(|(_, _, l)| matches!(&l.content, LayerContent::Smart(sm) if matches!(sm.source, SmartSource::Linked { .. }))) - .map(|(_, _, l)| l.id) - .collect(); - let mut updated = Vec::new(); - s.edit("Update All Modified Content", |doc, _| { - for id in &ids { - if refresh(doc, *id)? { - updated.push(id.0); - } - } - Ok(()) - })?; - Ok(json!({"updated": updated})) -} - -// ---------- smart filter editing ---------- - -/// Edits the smart filters of a smart object and re-renders it. The edit itself is instant, so its -/// errors (a bad index, say) are reported at once; the re-render runs as a background job when -/// started with `Session::start`, so the window keeps drawing (with progress, cancellable) while -/// a long filter stack recomputes. -fn edit_filters(s: &mut Session, p: &Value, label: &str, f: impl FnOnce(&mut SmartObject) -> Result<()>) -> Result { - let id = layer_param(s, p)?; - let mut edited = smart(&s.active().ok_or(EngineError::NoDocument)?.doc, id)?.clone(); - f(&mut edited)?; - crate::jobs::edit_job( - s, - label, - move |doc, _, ctx| { - *smart_mut(doc, id)? = edited; - refresh_or_fail_in(doc, id, ctx) - }, - move |()| json!({"layer": id.0}), - ) -} - -fn filter_index(cmd: &str, p: &Value, sm: &SmartObject) -> Result { - let n = sm.smart_filters.len(); - if n == 0 { - return Err(other("the smart object has no smart filters")); - } - match p.get("index") { - None => Ok(n - 1), - Some(v) => v.as_u64().map(|i| i as usize).filter(|i| *i < n).ok_or_else(|| bad(cmd, format!("`index` must be 0..{n} (0 = bottom filter)"))), - } -} - -fn set_filter_visible(s: &mut Session, p: &Value) -> Result { - const CMD: &str = "layer.smartFilter.setVisible"; - edit_filters(s, p, "Smart Filter Visibility", |sm| { - let i = filter_index(CMD, p, sm)?; - let f = &mut sm.smart_filters[i]; - f.visible = p.get("visible").and_then(Value::as_bool).unwrap_or(!f.visible); - Ok(()) - }) -} - -/// The Displace filter, whose map a smart filter keeps embedded in its params. -const DISPLACE: &str = "filter.distort.displace"; - -fn set_filter_params(s: &mut Session, p: &Value) -> Result { - const CMD: &str = "layer.smartFilter.setParams"; - let new = p.get("params").cloned().ok_or_else(|| bad(CMD, "pass `params` (merged into the filter's parameters)"))?; - let authorize = s.authorize; - // A Displace given another open document as its map embeds that one in place of the old - // (#7423). It is read here, before the edit, from the session; the request is authorized - // first, as the merged params are below. A new `mapPath` stays a path (read next to the - // document on each re-render) and only drops the old embedded map; an empty one, or a - // negative `mapDocument` (the dialog's "None"), names no map. - let new_map_asked = crate::filters_ext::map_document(&new).is_some(); - let new_path = crate::filters_ext::map_path(&new).is_some(); - let displace = { - let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; - let sm = smart(doc, layer_param(s, p)?)?; - sm.smart_filters.get(filter_index(CMD, p, sm)?).is_some_and(|f| f.command == DISPLACE) - }; - let new_map = if displace && new_map_asked { - // The old embedded map, if the edit passed it back, gives way to the one named. - let request = crate::filters_ext::displace_request(&new); - if let Some(gate) = authorize { - gate(DISPLACE, &request)?; - } - let mut fp = crate::filters::params_for(DISPLACE, &request).ok_or_else(|| bad(CMD, "unreadable Displace settings"))?; - crate::filters_ext::resolve(s, &mut fp, &request)?; - match fp { - photocraft_algo::FilterParams::Displace { map, .. } => map, - _ => None, - } - } else { - None - }; - edit_filters(s, p, "Edit Smart Filter", |sm| { - let i = filter_index(CMD, p, sm)?; - let f = &mut sm.smart_filters[i]; - if f.command == photocraft_io::smart_map::UNSUPPORTED_FILTER { - return Err(bad(CMD, "this smart filter isn't implemented in PhotoCraft: it is kept as is (it can be hidden, moved or deleted)")); - } - match (&mut f.params, new) { - (Value::Object(old), Value::Object(n)) => old.extend(n), - (slot, n) => *slot = n, - } - if f.command == DISPLACE { - if let Some(map) = &new_map { - f.params = photocraft_io::smart_map::displace_embed_map(&f.params, map) - .ok_or_else(|| bad(CMD, "the displacement map is too large to keep in a Smart Object's filter"))?; - } else if new_path { - f.params = photocraft_io::smart_map::displace_without_map(&f.params); - } - } - // Authorize the underlying command with the complete merged params, including paths - // already stored in the document, before committing the edit or starting a worker. - if let Some(gate) = authorize { - gate(&f.command, &f.params)?; - } - Ok(()) - }) -} - -fn blending_options(s: &mut Session, p: &Value) -> Result { - const CMD: &str = "layer.smartFilter.blendingOptions"; - let blend = match p.get("blend").and_then(Value::as_str) { - Some(b) => Some(blend_from_str(b).filter(|m| *m != BlendMode::PassThrough).ok_or_else(|| bad(CMD, format!("unknown blend mode `{b}`")))?), - None => None, - }; - let opacity = p.get("opacity").and_then(Value::as_f64).map(|o| if o > 1.0 { o / 100.0 } else { o } as f32); - edit_filters(s, p, "Smart Filter Blending Options", |sm| { - let i = filter_index(CMD, p, sm)?; - let f = &mut sm.smart_filters[i]; - if let Some(b) = blend { - f.blend = b; - } - if let Some(o) = opacity { - f.opacity = o.clamp(0.0, 1.0); - } - Ok(()) - }) -} - -fn delete_filter(s: &mut Session, p: &Value) -> Result { - edit_filters(s, p, "Delete Smart Filter", |sm| { - let i = filter_index("layer.smartFilter.delete", p, sm)?; - sm.smart_filters.remove(i); - if sm.smart_filters.is_empty() { - sm.filter_mask = None; - } - Ok(()) - }) -} - -fn move_filter(s: &mut Session, p: &Value) -> Result { - const CMD: &str = "layer.smartFilter.move"; - edit_filters(s, p, "Move Smart Filter", |sm| { - let i = filter_index(CMD, p, sm)?; - let n = sm.smart_filters.len(); - let to = p.get("to").and_then(Value::as_u64).map(|t| t as usize).filter(|t| *t < n).ok_or_else(|| bad(CMD, format!("`to` must be 0..{n}")))?; - let f = sm.smart_filters.remove(i); - sm.smart_filters.insert(to, f); - Ok(()) - }) -} - -/// Dragging smart filters onto another smart object in the Layers panel (#4271): they move there, -/// or are copied with `copy` (⌥-drag in Photoshop). One filter (`filter`) lands on top of the -/// target's filters; all of them (the Smart Filters row) are added on top too, with the filter -/// mask when the target has none. Both smart objects are re-rendered in one undo step. -fn transfer_filters(s: &mut Session, p: &Value) -> Result { - const CMD: &str = "layer.smartFilter.transfer"; - let id_of = |key: &str| p.get(key).and_then(Value::as_u64).map(LayerId).ok_or_else(|| bad(CMD, format!("`{key}` must be a layer id"))); - let (from, to) = (id_of("from")?, id_of("to")?); - if from == to { - return Err(bad(CMD, "the smart filters are already on that layer")); - } - // The other `layer.smartFilter.*` commands name a filter `index`; here a guessed `index` - // would otherwise be dropped and every filter moved. - if p.get("index").is_some() { - return Err(bad(CMD, "name the filter with `filter` (no `filter`: all of them)")); - } - let copy = p.get("copy").and_then(Value::as_bool).unwrap_or(false); - let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; - let src = smart(doc, from)?; - smart(doc, to).map_err(|_| bad(CMD, "smart filters can only be dropped on a smart object"))?; - let n = src.smart_filters.len(); - if n == 0 { - return Err(other("the smart object has no smart filters")); - } - let index = match p.get("filter") { - None | Some(Value::Null) => None, - Some(v) => Some(v.as_u64().map(|i| i as usize).filter(|i| *i < n).ok_or_else(|| bad(CMD, format!("`filter` must be 0..{n} (0 = bottom filter)")))?), - }; - let (filters, mask) = match index { - Some(i) => (vec![src.smart_filters[i].clone()], None), - None => (src.smart_filters.clone(), src.filter_mask.clone()), - }; - let label = match (copy, index.is_some()) { - (true, true) => "Copy Smart Filter", - (true, false) => "Copy Smart Filters", - (false, true) => "Move Smart Filter", - (false, false) => "Move Smart Filters", - }; - crate::jobs::edit_job( - s, - label, - move |doc, _, ctx| { - let dst = smart_mut(doc, to)?; - dst.smart_filters.extend(filters); - if dst.filter_mask.is_none() { - dst.filter_mask = mask; - } - refresh_or_fail_in(doc, to, ctx)?; - if !copy { - let src = smart_mut(doc, from)?; - match index { - Some(i) => { - src.smart_filters.remove(i); - if src.smart_filters.is_empty() { - src.filter_mask = None; - } - } - None => { - src.smart_filters.clear(); - src.filter_mask = None; - } - } - refresh_or_fail_in(doc, from, ctx)?; - } - Ok(()) - }, - move |()| json!({"from": from.0, "to": to.0}), - ) -} - -// ---------- enablement ---------- - -fn active_smart(s: &Session) -> std::result::Result<&SmartObject, String> { - let d = s.active().ok_or("no document open")?; - let id = d.active_layer.ok_or("no active layer")?; - match &d.doc.layer(id).ok_or("no active layer")?.content { - LayerContent::Smart(sm) => Ok(sm), - other => Err(format!("the active layer is {} {} layer, not a smart object", other.article(), other.kind_name())), - } -} -fn has_smart(s: &Session) -> std::result::Result<(), String> { - active_smart(s).map(|_| ()) -} -fn has_linked(s: &Session) -> std::result::Result<(), String> { - match active_smart(s)?.source { - SmartSource::Linked { .. } => Ok(()), - _ => Err("the smart object is embedded".into()), - } -} -fn has_doc(s: &Session) -> std::result::Result<(), String> { - s.active().map(|_| ()).ok_or_else(|| "no document open".into()) -} -fn has_smart_filters(s: &Session) -> std::result::Result<(), String> { - if active_smart(s)?.smart_filters.is_empty() { Err("the smart object has no smart filters".into()) } else { Ok(()) } -} -fn has_filter_mask(s: &Session) -> std::result::Result<(), String> { - active_smart(s)?.filter_mask.as_ref().map(|_| ()).ok_or_else(|| "the smart object has no filter mask".into()) -} -fn convertible(s: &Session) -> std::result::Result<(), String> { - let d = s.active().ok_or("no document open")?; - let id = d.active_layer.ok_or("no active layer")?; - d.doc.layer(id).map(|_| ()).ok_or_else(|| "no active layer".into()) -} -fn not_smart(s: &Session) -> std::result::Result<(), String> { - convertible(s)?; - if active_smart(s).is_ok() { Err("the layer is already a smart object".into()) } else { Ok(()) } -} - -/// Convert to Smart Object: refused only when the single targeted layer is already a smart -/// object. A multi-layer selection can still be combined (nesting any smart object in it). -fn convertible_to_smart(s: &Session) -> std::result::Result<(), String> { - convertible(s)?; - if crate::layer_multi_cmds::selected(s).len() <= 1 { not_smart(s) } else { Ok(()) } -} - -macro_rules! spec { - ($id:literal, $label:literal, $menu:expr, $params:literal, $en:expr, $run:expr) => { - CommandSpec { id: $id, label: $label, menu: $menu, shortcut: None, params: $params, enabled: $en, run: $run, journal: true } - }; -} - -const SO: &[&str] = &["Layer", "Smart Objects"]; -const SF: &[&str] = &["Layer", "Smart Filter"]; - -pub fn specs() -> Vec { - vec![ - spec!( - "layer.smartObjects.convertToSmartObject", - "Convert to Smart Object", - SO, - r##"{"layer":id?} (default: combine selected layers)"##, - convertible_to_smart, - convert - ), - spec!( - "filter.convertForSmartFilters", - "Convert for Smart Filters", - &["Filter"], - r##"{"layer":id?} (default: combine selected layers)"##, - not_smart, - convert - ), - spec!("layer.smartObjects.newSmartObjectViaCopy", "New Smart Object via Copy", SO, r##"{"layer":id?}"##, has_smart, via_copy), - spec!("layer.smartObjects.rasterize", "Rasterize", SO, r##"{"layer":id?}"##, has_smart, |s, p| s.execute("layer.rasterize.smartObject", p.clone())), - spec!( - "layer.smartObjects.editContents", - "Edit Contents", - SO, - r##"{"layer":id?} → opens the contents as a new document; saving (layer.smartObjects.saveContents) or closing it updates the smart object"##, - has_smart, - edit_contents - ), - spec!("layer.smartObjects.saveContents", "Save Contents", &[], "{} (in an Edit Contents document)", is_smart_child, |s, _| { - let i = s.active_index().ok_or(EngineError::NoDocument)?; - Ok(json!({"updated": commit_child(s, i)?})) - }), - spec!("layer.smartObjects.replaceContents", "Replace Contents…", SO, r##"{"layer":id?,"path":str}"##, has_smart, replace_contents), - spec!( - "layer.smartObjects.exportContents", - "Export Contents…", - SO, - r##"{"layer":id?,"path":str (another extension than the contents' own exports them in that format)}"##, - has_smart, - export_contents - ), - spec!("layer.smartObjects.relinkToFile", "Relink to File…", SO, r##"{"layer":id?,"path":str}"##, has_smart, |s, p| { - let path = path_param("layer.smartObjects.relinkToFile", p)?.to_string(); - set_source(s, p, "Relink to File", false, |_, _| Ok(SmartSource::Linked { path })) - }), - spec!("layer.smartObjects.updateModifiedContent", "Update Modified Content", SO, r##"{"layer":id?}"##, has_linked, |s, p| { - let id = layer_param(s, p)?; - s.edit("Update Modified Content", |doc, _| refresh_or_fail(doc, id))?; - Ok(json!({"layer": id.0})) - }), - spec!( - "layer.smartObjects.updateChanged", - "Update Changed Linked Content", - &[], - "{} — re-render the active document's linked smart objects whose files changed on disk since they were last seen (size or modification time); the desktop app does this by itself every two seconds, as Photoshop does while a document is open. Files seen for the first time are only remembered. One Update Modified Content undo step per file → {updated: [layer ids]}", - |s| s.active().map(|_| ()).ok_or_else(|| "no document open".into()), - crate::link_watch::update_changed - ), - spec!( - "layer.smartObjects.updateAllModifiedContent", - "Update All Modified Content", - SO, - "{}", - |s| s.active().map(|_| ()).ok_or_else(|| "no document open".into()), - |s, _| update_all(s) - ), - spec!( - "layer.smartObjects.convertToLayers", - "Convert to Layers", - SO, - r##"{"layer":id?} (contents unpacked at the placement: one layer, or a group named after the smart object; smart filters are discarded)"##, - has_smart, - unpack::convert_to_layers - ), - spec!("layer.smartObjects.convertToEmbedded", "Convert to Embedded", SO, r##"{"layer":id?}"##, has_linked, |s, p| { - set_source(s, p, "Convert to Embedded", true, |meta, src| { - let (file_name, bytes) = source_bytes(meta, src).ok_or_else(|| other("the linked file can't be read"))?; - Ok(SmartSource::Embedded { file_name, bytes }) - }) - }), - spec!( - "layer.smartObjects.convertToLinked", - "Convert to Linked…", - SO, - r##"{"layer":id?,"path":str} (writes the contents there)"##, - has_smart, - |s, p| { - let path = path_param("layer.smartObjects.convertToLinked", p)?.to_string(); - set_source(s, p, "Convert to Linked", false, |meta, src| { - let (_, bytes) = source_bytes(meta, src).ok_or_else(|| other("the smart object's contents are unavailable"))?; - crate::file_cmds::write_file(&path, &bytes)?; - Ok(SmartSource::Linked { path }) - }) - } - ), - // Smart filters - spec!( - "layer.smartFilter.disableSmartFilters", - "Disable Smart Filters", - SF, - r##"{"layer":id?,"enabled":bool? (default: toggle)}"##, - has_smart_filters, - |s, p| { - edit_filters(s, p, "Disable Smart Filters", |sm| { - sm.filters_enabled = p.get("enabled").and_then(Value::as_bool).unwrap_or(!sm.filters_enabled); - Ok(()) - }) - } - ), - spec!("layer.smartFilter.deleteFilterMask", "Delete Filter Mask", SF, r##"{"layer":id?}"##, has_filter_mask, |s, p| { - edit_filters(s, p, "Delete Filter Mask", |sm| { - sm.filter_mask = None; - Ok(()) - }) - }), - spec!( - "layer.smartFilter.disableFilterMask", - "Disable Filter Mask", - SF, - r##"{"layer":id?,"enabled":bool? (default: toggle)}"##, - has_filter_mask, - |s, p| { - edit_filters(s, p, "Disable Filter Mask", |sm| { - if let Some(m) = &mut sm.filter_mask { - m.enabled = p.get("enabled").and_then(Value::as_bool).unwrap_or(!m.enabled); - } - Ok(()) - }) - } - ), - spec!( - "layer.smartFilter.blendingOptions", - "Blending Options…", - SF, - r##"{"layer":id?,"index":u32? (0 = bottom; default top),"blend":str?,"opacity":0..1?}"##, - has_smart_filters, - blending_options - ), - spec!("layer.smartFilter.clearSmartFilters", "Clear Smart Filters", SF, r##"{"layer":id?}"##, has_smart_filters, |s, p| { - edit_filters(s, p, "Clear Smart Filters", |sm| { - sm.smart_filters.clear(); - sm.filter_mask = None; - Ok(()) - }) - }), - spec!( - "layer.smartFilter.setVisible", - "Show/Hide Smart Filter", - &[], - r##"{"layer":id?,"index":u32?,"visible":bool? (default: toggle)}"##, - has_smart_filters, - set_filter_visible - ), - spec!( - "layer.smartFilter.setParams", - "Edit Smart Filter", - &[], - r##"{"layer":id?,"index":u32?,"params":{…} (merged)}"##, - has_smart_filters, - set_filter_params - ), - spec!("layer.smartFilter.delete", "Delete Smart Filter", &[], r##"{"layer":id?,"index":u32?}"##, has_smart_filters, delete_filter), - spec!("layer.smartFilter.move", "Move Smart Filter", &[], r##"{"layer":id?,"index":u32?,"to":u32}"##, has_smart_filters, move_filter), - spec!( - "layer.smartFilter.transfer", - "Move or Copy Smart Filters", - &[], - r##"{"from":id,"to":id,"filter":u32? (default: all, with the filter mask),"copy":bool=false}"##, - has_doc, - transfer_filters - ), - ] -} - -mod stack_cache; -mod unpack; - -#[cfg(test)] -mod tests; diff --git a/crates/engine/src/smartselect_cmds.rs b/crates/engine/src/smartselect_cmds.rs deleted file mode 100644 index cfd1b333e0..0000000000 --- a/crates/engine/src/smartselect_cmds.rs +++ /dev/null @@ -1,1257 +0,0 @@ -//! Smart selection commands: Quick Selection, Object Selection, Select Subject, Select and Mask -//! (Refine Edge) and Focus Area. The algorithms live in `photocraft_algo::segment` and -//! `photocraft_algo::matting`; these commands pick the pixels to analyse (active layer or -//! composite), run them, and store the result as the selection (or a mask / new layer). - -use photocraft_algo::matting::{self, RefineParams}; -use photocraft_algo::segment::{Sampler, SurfaceSampler, focus, grabcut, quick, subject}; -use photocraft_algo::selection::{Region, SelectionMode, combine_region}; -use photocraft_doc::{Document, Layer, LayerContent, LayerId, LayerMask}; -use photocraft_geom::Rect; -use serde_json::{Value, json}; - -use crate::commands::CommandSpec; -use crate::select_mask_edits; -use crate::{EngineError, Result, Session}; - -fn has_doc(s: &Session) -> std::result::Result<(), String> { - s.active().map(|_| ()).ok_or_else(|| "no document open".into()) -} -fn has_selection_or_mask(s: &Session) -> std::result::Result<(), String> { - let d = s.active().ok_or_else(|| "no document open".to_string())?; - if d.doc.selection.is_some() { - return Ok(()); - } - if let Some(l) = d.active_layer.and_then(|id| d.doc.layer(id)) - && l.mask.is_some() - { - return Ok(()); - } - Err("no selection or layer mask".into()) -} - -fn f(p: &Value, k: &str, d: f32) -> f32 { - p.get(k).and_then(Value::as_f64).map_or(d, |v| v as f32) -} -fn b(p: &Value, k: &str, d: bool) -> bool { - p.get(k).and_then(Value::as_bool).unwrap_or(d) -} -fn mode(p: &Value, default: &str) -> SelectionMode { - let m = p.get("mode").and_then(Value::as_str).unwrap_or(default); - SelectionMode::parse(if m == "new" { "replace" } else { m }) -} -fn bad(cmd: &str, msg: &str) -> EngineError { - EngineError::BadParams { cmd: cmd.into(), msg: msg.into() } -} - -/// Composite of all visible layers. -struct CompositeSampler<'a>(&'a Document); - -impl Sampler for CompositeSampler<'_> { - fn rgba(&self, r: Rect) -> Vec<[f32; 4]> { - photocraft_compose::render(self.0, r).px - } -} - -/// Runs `f` with a sampler over the active layer (or the composite with `all_layers`, or when the -/// active layer has no pixels). -fn with_sampler(s: &Session, all_layers: bool, f: impl FnOnce(&dyn Sampler, &Document) -> R) -> Result { - let d = s.active().ok_or(EngineError::NoDocument)?; - Ok(with_doc_sampler(&d.doc, d.active_layer, all_layers, f)) -} - -/// Runs `f` with a sampler over `layer`'s pixels in `doc` (or the composite with `all_layers`, or -/// when the layer has no pixels). -pub(crate) fn with_doc_sampler(doc: &Document, layer: Option, all_layers: bool, f: impl FnOnce(&dyn Sampler, &Document) -> R) -> R { - match (all_layers, layer.and_then(|id| doc.layer(id)).and_then(Layer::surface)) { - (false, Some(surf)) => f(&SurfaceSampler(surf), doc), - _ => f(&CompositeSampler(doc), doc), - } -} - -/// Stores `region` combined with the current selection by `m` as one history step. -/// Finding nothing never destroys work: the selection (and history) is left alone and the -/// caller gets `changed: false`, whatever the mode. (Select Subject and Object Selection run -/// heuristics that often find nothing on busy photos; clearing the selection then looks like -/// a dead button.) -fn apply(s: &mut Session, label: &str, region: Option<&Region>, m: SelectionMode) -> Result { - if region.is_none() { - // Nothing found: leave the selection (and history) alone. - let selected = s.active().ok_or(EngineError::NoDocument)?.doc.selection.is_some(); - return Ok(json!({ "selected": selected, "changed": false })); - } - let bbox = region.map(|r| r.bbox); - let selected = s.edit(label, |doc, _| { - doc.selection = combine_region(doc.selection.as_ref(), region, m); - Ok(doc.selection.is_some()) - })?; - Ok(json!({ "selected": selected, "changed": true, "bounds": bbox.map(|r| [r.x0, r.y0, r.width() as i32, r.height() as i32]) })) -} - -fn points(p: &Value) -> Vec<(f32, f32)> { - p.get("points") - .and_then(Value::as_array) - .map(|a| a.iter().filter_map(|q| Some((q.get(0)?.as_f64()? as f32, q.get(1)?.as_f64()? as f32))).collect()) - .unwrap_or_default() -} - -/// Auto-Enhance for Quick Selection: a light edge refinement that flows the edge towards image -/// edges and removes blockiness. -const ENHANCE: RefineParams = RefineParams { radius: 4.0, smart_radius: true, smooth: 15.0, feather: 0.0, contrast: 25.0, shift_edge: 0.0 }; - -fn quick_selection(s: &mut Session, p: &Value) -> Result { - let pts = points(p); - if pts.is_empty() { - return Err(bad("select.quick", "needs at least one point")); - } - let size = f(p, "size", 30.0).clamp(1.0, 5000.0); - let m = match p.get("mode").and_then(Value::as_str).unwrap_or("add") { - "subtract" => SelectionMode::Subtract, - "replace" | "new" => SelectionMode::Replace, - _ => SelectionMode::Add, - }; - let enhance = b(p, "enhanceEdge", false); - let region = with_sampler(s, b(p, "sampleAllLayers", false), |smp, doc| { - let canvas = doc.bounds(); - let r = quick::quick_select(smp, canvas, &pts, size)?; - if enhance { matting::refine_mask(smp, &matting::region_reader(&r), r.bbox, canvas, &ENHANCE) } else { Some(r) } - })?; - apply(s, "Quick Selection", region.as_ref(), m) -} - -fn rect_param(p: &Value) -> Option { - let a = p.get("rect")?.as_array()?; - let v: Vec = a.iter().filter_map(Value::as_f64).collect(); - if v.len() < 4 { - return None; - } - // Negative sizes (dragging up/left) are normalised. - let (x0, x1) = (v[0].min(v[0] + v[2]), v[0].max(v[0] + v[2])); - let (y0, y1) = (v[1].min(v[1] + v[3]), v[1].max(v[1] + v[3])); - Some(Rect::new(x0.floor() as i32, y0.floor() as i32, x1.ceil() as i32, y1.ceil() as i32)) -} - -fn point_param(p: &Value) -> Option<(f32, f32)> { - let a = p.get("point")?.as_array()?; - let (x, y) = (a.first()?.as_f64()? as f32, a.get(1)?.as_f64()? as f32); - (x.is_finite() && y.is_finite()).then_some((x, y)) -} - -/// The layer [`with_doc_sampler`] samples for `layer` / `all_layers`: `None` = the composite. -pub fn sampled_target(doc: &Document, layer: Option, all_layers: bool) -> Option { - layer.filter(|id| !all_layers && doc.layer(*id).and_then(Layer::surface).is_some()) -} - -/// Object Finder (#4087): the object Object Selection would select at document point `(x, y)`, -/// sampling `layer` (or the composite). Pure, so the UI can run it on a worker thread while the -/// pointer hovers; `select.object` with `"point"` commits the same result. -pub fn find_object(doc: &Document, layer: Option, all_layers: bool, x: f32, y: f32) -> Option { - with_doc_sampler(doc, layer, all_layers, |smp, doc| grabcut::object_at(smp, doc.bounds(), x, y, grabcut::OBJECT_AT_WORK_PX)) -} - -/// Most objects remembered by [`ObjectFinderCache`]. -pub const OBJECT_FINDER_ENTRIES: usize = 12; - -/// Object Finder results for one document's pixels (#4087): hovering over an object already -/// found, or clicking it, answers at once. Keyed like [`SubjectCache`] (valid while the pixels -/// are the same, the document held weakly) plus the sampled layer; a lookup hits any cached -/// object that covers the point, so one computation serves the whole object. -#[derive(Debug, Default)] -pub struct ObjectFinderCache { - doc: std::sync::Weak, - doc_id: Option, - target: Option, - regions: Vec>, -} - -impl ObjectFinderCache { - fn valid(&self, doc: &Document, target: Option) -> bool { - self.doc_id == Some(doc.id) && self.target == target && self.doc.upgrade().is_some_and(|old| crate::layer_multi_cmds::same_pixels(&old, doc)) - } - - /// A cached object of `doc` (sampling `target`) covering `(x, y)`. - pub fn lookup(&self, doc: &Document, target: Option, x: f32, y: f32) -> Option> { - if !x.is_finite() || !y.is_finite() || !self.valid(doc, target) { - return None; - } - let (px, py) = (x.floor() as i32, y.floor() as i32); - self.regions.iter().find(|r| r.at(px, py) >= 0.5).cloned() - } - - /// Remembers `region`, found in `doc` sampling `target`. A different document or pixels - /// start over; the oldest object is dropped beyond [`OBJECT_FINDER_ENTRIES`]. - pub fn insert(&mut self, doc: &std::sync::Arc, target: Option, region: std::sync::Arc) { - if !self.valid(doc, target) { - self.regions.clear(); - } - self.doc = std::sync::Arc::downgrade(doc); - self.doc_id = Some(doc.id); - self.target = target; - if self.regions.len() >= OBJECT_FINDER_ENTRIES { - self.regions.remove(0); - } - self.regions.push(region); - } - - /// Number of remembered objects. - pub fn len(&self) -> usize { - self.regions.len() - } - - /// Whether nothing is remembered. - pub fn is_empty(&self) -> bool { - self.regions.is_empty() - } - - /// Forget the results if they were computed from the document `id` (it is closing). - pub(crate) fn forget_doc(&mut self, id: photocraft_doc::DocId) { - if self.doc_id == Some(id) { - *self = Self::default(); - } - } - - /// Follows `doc` past a selection-only edit (same pixels), so the next lookup still hits. - fn follow(&mut self, doc: &std::sync::Arc) { - if self.doc_id == Some(doc.id) && self.doc.upgrade().is_some_and(|old| crate::layer_multi_cmds::same_pixels(&old, doc)) { - self.doc = std::sync::Arc::downgrade(doc); - } - } -} - -/// Object Selection samples only the active layer by default: when that layer has no pixels in -/// `area`, say so instead of quietly finding nothing (#5246; scripts often add an empty layer -/// above the photo first). -fn check_sampled_pixels(doc: &Document, layer: Option, all_layers: bool, area: Rect) -> Result<()> { - match empty_sampled_area(doc, layer, all_layers, area) { - Some(msg) => Err(bad("select.object", &format!("{msg}; set \"sampleAllLayers\": true or select a layer with pixels"))), - None => Ok(()), - } -} - -/// Why sampling `layer` (unless `all_layers`) can find nothing in `area`: the layer is empty, or has no pixels there. -/// `None` = there is something to sample. The click path reports it as an error, the Object Finder hover as a hint. -pub fn empty_sampled_area(doc: &Document, layer: Option, all_layers: bool, area: Rect) -> Option<&'static str> { - let surf = sampled_target(doc, layer, all_layers).and_then(|id| doc.layer(id)).and_then(Layer::surface)?; - if !surf.content_bounds().intersect(&area).is_empty() { - return None; - } - Some(if surf.content_bounds().is_empty() { "the active layer is empty" } else { "the active layer has no pixels in that area" }) -} - -/// `select.object` with `"point"`: the Object Finder's object under the point (cached). -fn object_at_point(s: &mut Session, p: &Value, (x, y): (f32, f32)) -> Result { - let all_layers = b(p, "sampleAllLayers", false); - let d = s.active().ok_or(EngineError::NoDocument)?; - check_sampled_pixels(&d.doc, d.active_layer, all_layers, Rect::from_xywh(x.floor() as i32, y.floor() as i32, 1, 1))?; - let target = sampled_target(&d.doc, d.active_layer, all_layers); - let region = match s.object_finder.lookup(&d.doc, target, x, y) { - Some(r) => Some(r), - None => { - let doc = std::sync::Arc::clone(&d.doc); - let found = find_object(&doc, d.active_layer, all_layers, x, y).map(std::sync::Arc::new); - if let Some(r) = &found { - s.object_finder.insert(&doc, target, std::sync::Arc::clone(r)); - } - found - } - }; - let out = apply(s, "Object Selection", region.as_deref(), mode(p, "replace"))?; - if let Some(d) = s.active() { - let doc = std::sync::Arc::clone(&d.doc); - s.object_finder.follow(&doc); - } - Ok(out) -} - -fn object_selection(s: &mut Session, p: &Value) -> Result { - if p.get("rect").is_none() - && let Some(pt) = point_param(p) - { - return object_at_point(s, p, pt); - } - let rect = rect_param(p).ok_or_else(|| bad("select.object", "needs \"rect\": [x, y, w, h] or \"point\": [x, y]"))?; - let all_layers = b(p, "sampleAllLayers", false); - let d = s.active().ok_or(EngineError::NoDocument)?; - check_sampled_pixels(&d.doc, d.active_layer, all_layers, rect)?; - let region = with_sampler(s, all_layers, |smp, doc| grabcut::object_select(smp, doc.bounds(), rect, 160_000))?; - apply(s, "Object Selection", region.as_ref(), mode(p, "replace")) -} - -/// Select Subject's last result (#2865), so running it again on unchanged pixels answers at -/// once instead of recomputing superpixels, saliency and GrabCut (P29). Keyed by the pixels it -/// was computed from: valid while [`same_pixels`](crate::layer_multi_cmds::same_pixels) (a -/// tile-pointer comparison) holds against that document, so selection-only edits such as -/// Deselect keep it. One entry per session; the document is held weakly, so the cache never -/// keeps a closed or edited document's tiles alive (the session also drops it on pixel edits -/// and when its document closes). Its memory is the mask: one byte per pixel of its bounds. -#[derive(Debug, Default)] -pub struct SubjectCache { - doc: std::sync::Weak, - doc_id: Option, - /// The sampled layer; `None` = the composite. - target: Option, - region: Option>, -} - -impl SubjectCache { - /// Forget the result if it was computed from the document `id` (it is closing). - pub(crate) fn forget_doc(&mut self, id: photocraft_doc::DocId) { - if self.doc_id == Some(id) { - *self = Self::default(); - } - } -} - -fn select_subject(s: &mut Session, p: &Value) -> Result { - let all_layers = b(p, "sampleAllLayers", true); - let d = s.active().ok_or(EngineError::NoDocument)?; - // What `with_doc_sampler` samples: the active layer's pixels, else the composite. - let target = d.active_layer.filter(|id| !all_layers && d.doc.layer(*id).and_then(Layer::surface).is_some()); - let c = &s.subject_cache; - let hit = c.target == target && c.doc.upgrade().is_some_and(|old| crate::layer_multi_cmds::same_pixels(&old, &d.doc)); - let region = if hit { - c.region.clone() - } else { - let doc = std::sync::Arc::clone(&d.doc); - let region = with_doc_sampler(&doc, d.active_layer, all_layers, |smp, doc| subject::select_subject(smp, doc.bounds())).map(std::sync::Arc::new); - s.subject_cache = SubjectCache { doc: std::sync::Arc::downgrade(&doc), doc_id: Some(doc.id), target, region: region.clone() }; - region - }; - let out = apply(s, "Select Subject", region.as_deref(), mode(p, "replace"))?; - // Follow the document past the selection edit just made (same pixels), so a short history - // dropping the older state doesn't turn the next repeat into a miss. - if let Some(d) = s.active() - && s.subject_cache.doc_id == Some(d.doc.id) - && s.subject_cache.doc.upgrade().is_some_and(|old| crate::layer_multi_cmds::same_pixels(&old, &d.doc)) - { - s.subject_cache.doc = std::sync::Arc::downgrade(&d.doc); - } - Ok(out) -} - -fn focus_area(s: &mut Session, p: &Value) -> Result { - let (range, noise) = (f(p, "range", 0.5).clamp(0.0, 1.0), f(p, "noise", 0.0).clamp(0.0, 1.0)); - let region = with_sampler(s, b(p, "sampleAllLayers", true), |smp, doc| focus::focus_area(smp, doc.bounds(), range, noise))?; - apply(s, "Focus Area", region.as_ref(), mode(p, "replace")) -} - -fn refine_params(p: &Value) -> RefineParams { - RefineParams { - radius: f(p, "radius", 0.0).clamp(0.0, 250.0), - smart_radius: b(p, "smartRadius", false), - smooth: f(p, "smooth", 0.0).clamp(0.0, 100.0), - feather: f(p, "feather", 0.0).clamp(0.0, 1000.0), - contrast: f(p, "contrast", 0.0).clamp(0.0, 100.0), - shift_edge: f(p, "shiftEdge", 0.0).clamp(-100.0, 100.0), - } -} - -/// Most Refine Edge Brush strokes, and points across them, one Select and Mask takes. -pub const MAX_STROKES: usize = 4096; -pub const MAX_STROKE_POINTS: usize = 100_000; - -/// The Refine Edge Brush strokes of `refineStrokes`: -/// `[{"points":[[x,y],…],"size":px,"mode":"add|subtract"}]`, in painting order. -fn refine_strokes(p: &Value) -> Result> { - const CMD: &str = "select.refineEdge"; - let Some(v) = p.get("refineStrokes").filter(|v| !v.is_null()) else { return Ok(Vec::new()) }; - let list = v.as_array().ok_or_else(|| bad(CMD, "refineStrokes must be an array of strokes"))?; - if list.len() > MAX_STROKES { - return Err(bad(CMD, &format!("refineStrokes holds more than {MAX_STROKES} strokes"))); - } - let mut total = 0usize; - let mut strokes = Vec::with_capacity(list.len()); - for stroke in list { - let o = stroke.as_object().ok_or_else(|| bad(CMD, "each refineStrokes entry must be {\"points\":[[x,y],…],\"size\":px,\"mode\":\"add|subtract\"}"))?; - let pts = o.get("points").and_then(Value::as_array).filter(|a| !a.is_empty()).ok_or_else(|| bad(CMD, "each stroke needs a non-empty points array"))?; - total = total.saturating_add(pts.len()); - if total > MAX_STROKE_POINTS { - return Err(bad(CMD, &format!("refineStrokes holds more than {MAX_STROKE_POINTS} points"))); - } - let points = pts - .iter() - .map(|pt| { - let xy = pt.as_array().filter(|a| a.len() == 2)?; - let (x, y) = (xy.first()?.as_f64()?, xy.get(1)?.as_f64()?); - let ok = |v: f64| v.is_finite() && v.abs() <= 1e7; - (ok(x) && ok(y)).then_some((x as f32, y as f32)) - }) - .collect::>>() - .ok_or_else(|| bad(CMD, "stroke points must be [x,y] pairs of finite numbers"))?; - let range = matting::BRUSH_SIZE_RANGE; - let size = match o.get("size") { - None => 30.0, - Some(v) => v - .as_f64() - .filter(|s| s.is_finite() && (f64::from(*range.start())..=f64::from(*range.end())).contains(s)) - .ok_or_else(|| bad(CMD, &format!("stroke size must be {}..{} px", range.start(), range.end())))? as f32, - }; - let add = match o.get("mode").map(|m| m.as_str()) { - None | Some(Some("add")) => true, - Some(Some("subtract")) => false, - Some(_) => return Err(bad(CMD, "stroke mode must be add|subtract")), - }; - strokes.push(matting::EdgeStroke { points, size, add }); - } - if matting::swept_area(&strokes) > matting::MAX_SWEPT_AREA { - return Err(bad(CMD, "refineStrokes paint too large an area")); - } - Ok(strokes) -} - -/// Select and Mask: applies the workspace's tool `edits` to the selection (or layer mask), refines -/// its edge, then outputs to the selection, a layer mask on the active layer, a new layer or a new -/// document (each with or without a mask). -/// Decontaminating colours needs new pixels, so it upgrades `selection` / `layerMask` output to -/// `newLayerWithMask` (as Photoshop does). New-layer outputs hide the source layer; new-document -/// outputs leave the source document untouched. -fn refine_edge(s: &mut Session, p: &Value) -> Result { - let params = refine_params(p); - let strokes = refine_strokes(p)?; - let decontaminate = b(p, "decontaminate", false); - let amount = f(p, "amount", 100.0).clamp(0.0, 100.0); - let d = s.active().ok_or(EngineError::NoDocument)?; - let active = d.active_layer.filter(|id| d.doc.layer(*id).is_some()); - let default_output = - if d.doc.selection.is_none() && active.and_then(|id| d.doc.layer(id)).and_then(|l| l.mask.as_ref()).is_some() { "layerMask" } else { "selection" }; - let mut output = p.get("output").and_then(Value::as_str).unwrap_or(default_output).to_string(); - if !matches!(output.as_str(), "selection" | "layerMask" | "newLayer" | "newLayerWithMask" | "newDocument" | "newDocumentWithMask") { - return Err(bad("select.refineEdge", "output must be selection|layerMask|newLayer|newLayerWithMask|newDocument|newDocumentWithMask")); - } - if decontaminate && matches!(output.as_str(), "selection" | "layerMask") { - output = "newLayerWithMask".into(); - } - let edits = select_mask_edits::parse(p)?; - // Before anything is painted: a thin stroke across a huge canvas paints few pixels but many tiles. - select_mask_edits::check_size(&edits, d.doc.bounds())?; - select_mask_edits::check_strokes(&strokes, d.doc.bounds())?; - let region = with_sampler(s, b(p, "sampleAllLayers", false), |smp, doc| { - let mask_surf = active.and_then(|id| doc.layer(id)).and_then(|l| l.mask.as_ref()).map(|m| &m.surface); - let target_mask = p.get("target").and_then(Value::as_str) == Some("mask"); - let start = if target_mask { mask_surf.or(doc.selection.as_ref()) } else { doc.selection.as_ref().or(mask_surf) }; - // The workspace's tool edits change the selection before its edge is refined. - let edited = if edits.is_empty() { None } else { select_mask_edits::apply(doc, active, start.cloned(), &edits) }; - let Some(sel) = (if edits.is_empty() { start } else { edited.as_ref() }) else { return Ok(None) }; - let brush = matting::EdgeBrush::new(&strokes, doc.bounds()); - // The refined result is dense over the selection's bounds: refuse what would not fit - // rather than allocate it (a thin edit across a huge canvas; the #8783 review). - let content = sel.content_bounds(); - let area = matting::refine_area(content, doc.bounds(), ¶ms, brush.as_ref()); - if u64::from(area.width()) * u64::from(area.height()) > matting::MAX_REFINE_AREA { - return Err(bad( - "select.refineEdge", - &format!("the selection is too large to refine ({} × {} px; at most {} px in all)", area.width(), area.height(), matting::MAX_REFINE_AREA), - )); - } - Ok(matting::refine_mask_brushed(smp, &matting::surface_reader(sel), content, doc.bounds(), ¶ms, brush.as_ref())) - })??; - let d = s.active().ok_or(EngineError::NoDocument)?; - let active = d.active_layer.filter(|id| d.doc.layer(*id).is_some()); - match output.as_str() { - "selection" => { - let selected = s.edit("Select and Mask", |doc, _| { - doc.selection = region.as_ref().map(matting::region_surface); - Ok(doc.selection.is_some()) - })?; - Ok(json!({ "output": output, "selected": selected })) - } - "layerMask" => { - let id = active.ok_or_else(|| EngineError::Other("no active layer".into()))?; - s.edit("Select and Mask", |doc, _| { - let surface = - region.as_ref().map(matting::region_surface).unwrap_or_else(|| photocraft_raster::Surface::new(photocraft_color::PixelFormat::GRAY8)); - crate::extra_cmds::background_to_layer_for_mask(doc, id); - let existing = doc.layer(id).and_then(|l| l.mask.as_ref()).cloned().unwrap_or_else(LayerMask::reveal_all); - doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?.mask = Some(LayerMask { surface, ..existing }); - doc.selection = None; - Ok(()) - })?; - Ok(json!({ "output": output, "layer": id.0, "selected": false })) - } - _ => { - let id = active.ok_or_else(|| EngineError::Other("no active layer".into()))?; - let src_layer = d.doc.layer(id).ok_or(EngineError::NoLayer(id))?; - let src = src_layer.surface().ok_or_else(|| { - EngineError::Other(format!("the active layer is {} {} layer without pixels", src_layer.content.article(), src_layer.content.kind_name())) - })?; - let name = d.doc.copy_name(&src_layer.name); - let empty = Region { bbox: Rect::EMPTY, mask: Vec::new() }; - let reg = region.as_ref().unwrap_or(&empty); - let pixels = if decontaminate { matting::decontaminate(src, reg, params.radius, amount) } else { src.clone() }; - let with_mask = matches!(output.as_str(), "newLayerWithMask" | "newDocumentWithMask"); - let (content, mask) = if with_mask { - (pixels, Some(LayerMask { surface: matting::region_surface(reg), ..LayerMask::reveal_all() })) - } else { - (matting::masked_copy(&pixels, reg), None) - }; - if output.starts_with("newDocument") { - // Same canvas, colour mode, depth and profile, so the pixels need no conversion. - let mut doc = Document::new("Untitled", d.doc.size, d.doc.mode, d.doc.depth); - doc.resolution_dpi = d.doc.resolution_dpi; - doc.icc_profile = d.doc.icc_profile.clone(); - doc.color_table = d.doc.color_table.clone(); - doc.duotone = d.doc.duotone.clone(); - let mut layer = Layer::new(src_layer.name.clone(), LayerContent::Raster(content)); - layer.mask = mask; - let layer_id = layer.id; - doc.layers.push(layer); - let i = s.add_document(doc, None); - return Ok(json!({ "output": output, "document": i, "layer": layer_id.0, "selected": false })); - } - let new_id = s.edit("Select and Mask", |doc, act| { - let mut layer = Layer::new(name, LayerContent::Raster(content)); - layer.mask = mask; - let nid = doc.insert_above(Some(id), layer); - if let Some(l) = doc.layer_mut(id) { - l.visible = false; - } - doc.selection = None; - *act = Some(nid); - Ok(nid) - })?; - Ok(json!({ "output": output, "layer": new_id.0, "selected": false })) - } - } -} - -macro_rules! spec { - ($id:literal, $label:literal, [$($m:literal),*], $params:literal, $en:expr, $run:expr) => { - CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: None, params: $params, enabled: $en, run: $run, journal: true } - }; -} - -/// Smart selection command specs. -pub fn specs() -> Vec { - vec![ - spec!( - "select.quick", - "Quick Selection", - [], - r##"{"points":[[x,y],…],"size":px=30,"mode":"add|subtract|replace"="add","sampleAllLayers":bool=false,"enhanceEdge":bool=false}"##, - has_doc, - quick_selection - ), - spec!( - "select.object", - "Object Selection", - [], - r##"{"rect":[x,y,w,h] | "point":[x,y],"mode":"replace|add|subtract|intersect"="replace","sampleAllLayers":bool=false} (point: the Object Finder's object under the point, as hovering previews it)"##, - has_doc, - object_selection - ), - spec!( - "select.subject", - "Subject", - ["Select"], - r##"{"sampleAllLayers":bool=true,"mode":"replace|add|subtract|intersect"="replace"}"##, - has_doc, - select_subject - ), - spec!( - "select.refineEdge", - "Refine Edge", - [], - r##"{"radius":px=0,"smartRadius":bool=false,"smooth":0..100=0,"feather":px=0,"contrast":0..100=0,"shiftEdge":-100..100=0,"decontaminate":bool=false,"amount":0..100=100,"output":"selection|layerMask|newLayer|newLayerWithMask|newDocument|newDocumentWithMask"="selection","sampleAllLayers":bool=false,"refineStrokes":[{"points":[[x,y],…],"size":px=30,"mode":"add|subtract"="add"},…]=[],"edits":[{"tool":"quick","points":[[x,y],…],"size":px=30,"mode":"add|subtract"="add","sampleAllLayers":bool=false} | {"tool":"brush","points":[[x,y],…],"size":px=30,"hardness":0..100=100,"mode":"add|subtract"="add"} | {"tool":"lasso","points":[[x,y],…≥3],"mode":"add|subtract"="add"} | {"tool":"object","rect":[x,y,w,h] | "point":[x,y],"mode":"add|subtract"="add","sampleAllLayers":bool=false} | {"tool":"subject","mode":"replace|add|subtract"="replace","sampleAllLayers":bool=true} | {"tool":"clear"} | {"tool":"invert"},…]=[]} (refineStrokes: the Refine Edge Brush, in painting order: add refines the painted area from the image, subtract keeps the original edge there; edits: the workspace's Quick Selection, Brush, Lasso, Object Selection, Select Subject, Clear Selection and Invert, applied in order to the selection before its edge is refined)"##, - has_selection_or_mask, - refine_edge - ), - spec!( - "select.focusArea", - "Focus Area…", - ["Select"], - r##"{"range":0..1=0.5,"noise":0..1=0,"sampleAllLayers":bool=true,"mode":"replace|add|subtract|intersect"="replace"}"##, - has_doc, - focus_area - ), - ] -} - -#[cfg(test)] -mod tests { - use super::*; - use photocraft_algo::segment::Rng; - - /// A document whose background shows `px(x, y)` (RGB, 0–1), at the given depth. - fn session_with(w: u32, h: u32, depth: u32, px: impl Fn(u32, u32) -> [f32; 3]) -> Session { - let mut s = Session::new(); - s.execute("file.new", json!({"width": w, "height": h, "depth": depth})).unwrap(); - s.edit("paint", |doc, _| { - let bg = doc.layers[0].surface_mut().unwrap(); - let n = bg.channels(); - let mut data = Vec::with_capacity((w * h) as usize * n); - for y in 0..h { - for x in 0..w { - let c = px(x, y); - data.extend_from_slice(&c[..n.min(3)]); - if n == 4 { - data.push(1.0); - } - } - } - bg.write_region(Rect::new(0, 0, w as i32, h as i32), &data); - Ok(()) - }) - .unwrap(); - s - } - - fn noise_field(w: u32, h: u32, seed: u64) -> Vec { - let mut rng = Rng::new(seed); - (0..w * h).map(|_| rng.normal()).collect() - } - - /// Warm textured left part (x < 60), cool right part. - fn two_regions(depth: u32) -> Session { - let nz = noise_field(140, 100, 1); - session_with(140, 100, depth, move |x, y| { - let n = 0.04 * nz[(y * 140 + x) as usize]; - if x < 60 { [0.8 + n, 0.5 + n, 0.3] } else { [0.2, 0.35 + n, 0.6 + n] }.map(|v| v.clamp(0.0, 1.0)) - }) - } - - /// Textured disc (centre (100, 80), radius 45) on a noisy background. - fn disc(depth: u32) -> (Session, impl Fn(i32, i32) -> bool) { - let nz = noise_field(200, 160, 2); - let inside = |x: i32, y: i32| { - let (dx, dy) = (x as f32 + 0.5 - 100.0, y as f32 + 0.5 - 80.0); - dx * dx + dy * dy <= 45.0 * 45.0 - }; - let s = session_with(200, 160, depth, move |x, y| { - let n = 0.05 * nz[(y * 200 + x) as usize]; - if inside(x as i32, y as i32) { - let t = ((x + y) as f32 * 0.35).sin() * 0.5 + 0.5; - [0.85 + 0.05 * t + n, 0.2 + 0.3 * t + n, 0.15 + n] - } else { - [0.25 + n, 0.45 + n, 0.7 + n] - } - .map(|v| v.clamp(0.0, 1.0)) - }); - (s, inside) - } - - fn cov(s: &Session, x: i32, y: i32) -> f32 { - s.active().unwrap().doc.selection.as_ref().map_or(0.0, |m| m.sample_channel(x, y, 0)) - } - - fn sel_iou(s: &Session, w: i32, h: i32, truth: impl Fn(i32, i32) -> bool) -> f32 { - let (mut i, mut u) = (0, 0); - for y in 0..h { - for x in 0..w { - let (a, b) = (cov(s, x, y) >= 0.5, truth(x, y)); - i += (a && b) as i32; - u += (a || b) as i32; - } - } - i as f32 / u.max(1) as f32 - } - - #[test] - fn quick_selection_add_subtract_undo() { - for depth in [8, 16] { - let mut s = two_regions(depth); - let r = s.execute("select.quick", json!({"points": [[20, 50], [35, 50]], "size": 8})).unwrap(); - assert_eq!(r["selected"], true); - for y in (0..100).step_by(7) { - for x in (0..140).step_by(3) { - let c = cov(&s, x, y); - if x < 57 { - assert!(c >= 0.5, "depth {depth}: ({x},{y}) not selected"); - } else if x > 62 { - assert!(c < 0.5, "depth {depth}: leaked to ({x},{y})"); - } - } - } - // A second stroke on the right adds it. - s.execute("select.quick", json!({"points": [[100, 50]], "size": 8})).unwrap(); - assert!(cov(&s, 130, 90) >= 0.5 && cov(&s, 10, 10) >= 0.5); - // Subtract the left region again. - s.execute("select.quick", json!({"points": [[20, 50]], "size": 8, "mode": "subtract"})).unwrap(); - assert!(cov(&s, 10, 10) < 0.5 && cov(&s, 130, 90) >= 0.5); - s.execute("edit.undo", json!({})).unwrap(); - assert!(cov(&s, 10, 10) >= 0.5); - assert!(s.execute("select.quick", json!({"points": []})).is_err()); - } - } - - #[test] - fn quick_selection_subtract_from_select_all_and_enhance() { - let mut s = two_regions(8); - s.execute("select.all", json!({})).unwrap(); - s.execute("select.quick", json!({"points": [[100, 30], [110, 70]], "size": 10, "mode": "subtract"})).unwrap(); - assert!(cov(&s, 10, 50) >= 0.99); - assert!(cov(&s, 120, 20) < 0.01 && cov(&s, 70, 90) < 0.01); - s.execute("select.deselect", json!({})).unwrap(); - s.execute("select.quick", json!({"points": [[20, 50]], "size": 8, "enhanceEdge": true})).unwrap(); - assert!(cov(&s, 10, 10) >= 0.5 && cov(&s, 100, 50) < 0.5); - } - - #[test] - fn empty_result_keeps_the_selection_in_every_mode() { - // Finding nothing must never wipe the selection, whatever the mode: Select Subject - // and Object Selection run heuristics that often miss on busy photos, and a missed - // Quick Selection dab must not destroy the work either. - for m in ["add", "subtract", "replace"] { - let mut s = two_regions(8); - s.execute("select.all", json!({})).unwrap(); - let r = s.execute("select.quick", json!({"points": [[-5000, -5000]], "size": 8, "mode": m})).unwrap(); - assert_eq!(r["changed"], false, "mode {m}"); - assert_eq!(r["selected"], true, "mode {m}"); - assert!(cov(&s, 10, 50) >= 0.99, "mode {m}: Select All survived an empty result"); - } - // Select Subject on a flat field finds nothing and keeps the selection too. - let mut s = session_with(140, 100, 8, |_, _| [0.5, 0.5, 0.5]); - s.execute("select.all", json!({})).unwrap(); - let r = s.execute("select.subject", json!({})).unwrap(); - assert_eq!(r["changed"], false); - assert!(cov(&s, 10, 10) >= 0.99); - } - - #[test] - fn object_selection_point_selects_the_object_under_it() { - for depth in [8, 16, 32] { - let (mut s, inside) = disc(depth); - let r = s.execute("select.object", json!({"point": [100, 80]})).unwrap(); - assert_eq!(r["changed"], true, "depth {depth}"); - let v = sel_iou(&s, 200, 160, &inside); - assert!(v > 0.9, "depth {depth}: IoU {v}"); - } - // The background is no object: nothing changes. - let (mut s, _) = disc(8); - let r = s.execute("select.object", json!({"point": [3, 3]})).unwrap(); - assert_eq!(r["changed"], false); - assert!(s.active().unwrap().doc.selection.is_none()); - assert!(s.execute("select.object", json!({"point": ["a", 1]})).is_err()); - } - - #[test] - fn object_selection_finds_a_large_foreground_at_each_depth_and_undoes() { - for depth in [8, 16, 32] { - let inside = |x: i32, y: i32| (10..190).contains(&x) && (8..152).contains(&y); - let mut s = session_with(200, 160, depth, |x, y| if inside(x as i32, y as i32) { [0.8, 0.2, 0.1] } else { [0.1, 0.2, 0.8] }); - let r = s.execute("select.object", json!({"point": [100, 80]})).unwrap(); - assert_eq!(r["changed"], true, "depth {depth}"); - assert!(sel_iou(&s, 200, 160, inside) > 0.95, "depth {depth}"); - s.execute("edit.undo", json!({})).unwrap(); - assert!(s.active().unwrap().doc.selection.is_none()); - let r = s.execute("select.object", json!({"point": [1, 1]})).unwrap(); - assert_eq!(r["changed"], false, "background at depth {depth}"); - assert!(s.active().unwrap().doc.selection.is_none()); - } - } - - #[test] - fn object_selection_point_honours_the_modes() { - let (mut s, _) = disc(8); - s.execute("select.all", json!({})).unwrap(); - s.execute("select.object", json!({"point": [100, 80], "mode": "subtract"})).unwrap(); - assert!(cov(&s, 100, 80) < 0.5 && cov(&s, 3, 3) >= 0.5); - s.execute("select.object", json!({"point": [100, 80], "mode": "add"})).unwrap(); - assert!(cov(&s, 100, 80) >= 0.5 && cov(&s, 3, 3) >= 0.5); - s.execute("select.object", json!({"point": [100, 80], "mode": "intersect"})).unwrap(); - assert!(cov(&s, 100, 80) >= 0.5 && cov(&s, 3, 3) < 0.5); - } - - #[test] - fn object_finder_cache_serves_the_whole_object_until_pixels_change() { - let (mut s, _) = disc(8); - let d = s.active().unwrap(); - let doc = std::sync::Arc::clone(&d.doc); - let target = sampled_target(&doc, d.active_layer, false); - assert!(s.object_finder.lookup(&doc, target, 100.0, 80.0).is_none()); - let r = std::sync::Arc::new(find_object(&doc, d.active_layer, false, 100.0, 80.0).unwrap()); - s.object_finder.insert(&doc, target, std::sync::Arc::clone(&r)); - // Any point on the object hits; the background and another target miss. - assert!(std::sync::Arc::ptr_eq(&s.object_finder.lookup(&doc, target, 120.0, 90.0).unwrap(), &r)); - assert!(s.object_finder.lookup(&doc, target, 3.0, 3.0).is_none()); - assert!(s.object_finder.lookup(&doc, Some(LayerId(u64::MAX)), 100.0, 80.0).is_none()); - // The click reuses it, and a selection-only edit keeps it. - s.execute("select.object", json!({"point": [110, 70]})).unwrap(); - assert_eq!(s.object_finder.len(), 1); - s.execute("select.deselect", json!({})).unwrap(); - let d = s.active().unwrap(); - assert!(s.object_finder.lookup(&std::sync::Arc::clone(&d.doc), target, 100.0, 80.0).is_some()); - // A pixel edit drops it. - s.execute("paint.pencil", json!({"points": [[5, 5], [30, 5]], "size": 4, "color": "#000000"})).unwrap(); - assert!(s.object_finder.is_empty()); - } - - #[test] - fn object_selection_disc() { - for depth in [8, 16, 32] { - let (mut s, inside) = disc(depth); - s.execute("select.object", json!({"rect": [40, 20, 120, 120]})).unwrap(); - let v = sel_iou(&s, 200, 160, &inside); - assert!(v > 0.95, "depth {depth}: IoU {v}"); - } - let (mut s, _) = disc(8); - assert!(s.execute("select.object", json!({"rect": [1, 2]})).is_err()); - // Negative width/height (drag up-left) work too. - s.execute("select.object", json!({"rect": [160, 140, -120, -120]})).unwrap(); - assert!(cov(&s, 100, 80) >= 0.5); - } - - #[test] - fn object_selection_on_an_empty_active_layer_says_so() { - // #5246: an empty layer above the photo used to find nothing without a word. - let (mut s, inside) = disc(8); - s.execute("layer.new.layer", json!({})).unwrap(); - for p in [json!({"rect": [40, 20, 120, 120]}), json!({"point": [100, 80]})] { - let e = s.execute("select.object", p.clone()).unwrap_err().to_string(); - assert!(e.contains("active layer is empty") && e.contains("sampleAllLayers"), "{p}: {e}"); - assert!(s.active().unwrap().doc.selection.is_none()); - } - // Sampling all layers finds the disc below. - s.execute("select.object", json!({"rect": [40, 20, 120, 120], "sampleAllLayers": true})).unwrap(); - assert!(sel_iou(&s, 200, 160, &inside) > 0.95); - // A layer with pixels elsewhere: the rectangle holds none of them. - s.execute("select.deselect", json!({})).unwrap(); - s.execute("paint.pencil", json!({"points": [[5, 5], [10, 5]], "size": 2, "color": "#000000"})).unwrap(); - let e = s.execute("select.object", json!({"rect": [60, 60, 100, 80]})).unwrap_err().to_string(); - assert!(e.contains("no pixels in that area"), "{e}"); - } - - #[test] - fn select_subject_centred_object() { - let (mut s, inside) = disc(8); - assert!(s.is_enabled("select.subject")); - s.execute("select.subject", json!({})).unwrap(); - let v = sel_iou(&s, 200, 160, inside); - assert!(v > 0.9, "IoU {v}"); - s.execute("edit.undo", json!({})).unwrap(); - assert!(s.active().unwrap().doc.selection.is_none()); - } - - /// #2865: a repeat on unchanged pixels reuses the last mask (an identical selection, even - /// after Deselect); sampling something else or a pixel edit computes it again. - #[test] - fn select_subject_repeat_reuses_the_mask_until_pixels_change() { - let (mut s, _) = disc(8); - let sel = |s: &Session| { - let mut v = Vec::new(); - s.active().unwrap().doc.selection.as_ref().unwrap().read_region_into(Rect::new(0, 0, 200, 160), &mut v); - v - }; - let cached = |s: &Session| s.subject_cache.region.clone().unwrap(); - s.execute("select.subject", json!({})).unwrap(); - let (first, mask) = (sel(&s), cached(&s)); - s.execute("select.deselect", json!({})).unwrap(); - s.execute("select.subject", json!({})).unwrap(); - assert!(std::sync::Arc::ptr_eq(&mask, &cached(&s)), "the repeat recomputed the mask"); - assert_eq!(sel(&s), first); - // Another sampled target (the layer rather than the composite) is a miss. - s.execute("select.subject", json!({"sampleAllLayers": false})).unwrap(); - assert!(!std::sync::Arc::ptr_eq(&mask, &cached(&s))); - // A pixel edit drops the entry; the next run recomputes it. - s.edit("paint", |doc, _| { - let bg = doc.layers[0].surface_mut().unwrap(); - let n = bg.channels(); - bg.write_region(Rect::new(0, 0, 1, 1), &vec![1.0; n]); - Ok(()) - }) - .unwrap(); - assert!(s.subject_cache.region.is_none()); - s.execute("select.subject", json!({})).unwrap(); - assert_eq!(sel(&s), first); - } - - /// A vertical Gaussian-blurred edge at x = 40 (warm left, cool right) with the left half selected. - fn blurred_edge_selected() -> Session { - blurred_edge_selected_at(8) - } - - fn blurred_edge_selected_at(depth: u32) -> Session { - let mut s = session_with(80, 40, depth, |x, _| { - let t = 1.0 / (1.0 + ((x as f32 + 0.5 - 40.0) / 1.8).exp()); - [0.9 * t + 0.1 * (1.0 - t), 0.8 * t + 0.2 * (1.0 - t), 0.2 * t + 0.6 * (1.0 - t)] - }); - s.execute("select.rect", json!({"x": 0, "y": 0, "width": 40, "height": 40})).unwrap(); - s - } - - fn soft_count(s: &photocraft_raster::Surface, y: i32) -> usize { - (0..80) - .filter(|x| { - let v = s.sample_channel(*x, y, 0); - v > 0.05 && v < 0.95 - }) - .count() - } - - #[test] - fn refine_edge_outputs_and_undo() { - // Selection output: the hard edge becomes a soft matte following the blur. - let mut s = blurred_edge_selected(); - assert!(s.is_enabled("select.refineEdge")); - s.execute("select.refineEdge", json!({"radius": 8})).unwrap(); - let sel = s.active().unwrap().doc.selection.clone().unwrap(); - assert!(soft_count(&sel, 20) >= 4, "selection edge not soft"); - assert!(sel.sample_channel(5, 20, 0) > 0.99 && sel.sample_channel(75, 20, 0) < 0.01); - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(soft_count(s.active().unwrap().doc.selection.as_ref().unwrap(), 20), 0); - - // Layer mask output. - let layers_before = s.active().unwrap().doc.layer_count(); - let r = s.execute("select.refineEdge", json!({"radius": 8, "output": "layerMask"})).unwrap(); - let d = s.active().unwrap(); - let l = d.doc.layer(photocraft_doc::LayerId(r["layer"].as_u64().unwrap())).unwrap(); - let m = l.mask.as_ref().unwrap(); - assert!(soft_count(&m.surface, 20) >= 4); - assert!(m.value(5, 20) > 0.99 && m.value(75, 20) < 0.01); - assert!(d.doc.selection.is_none()); - assert_eq!(d.doc.layer_count(), layers_before); - s.execute("edit.undo", json!({})).unwrap(); - assert!(s.active().unwrap().doc.layers[0].mask.is_none()); - assert!(s.active().unwrap().doc.selection.is_some()); - - // Existing mask settings (density, feather, linked) are preserved - s.edit("set mask", |doc, _| { - doc.layers[0].mask = Some(photocraft_doc::LayerMask { - surface: photocraft_raster::Surface::new(photocraft_color::PixelFormat::GRAY8), - density: 0.75, - feather: 3.5, - linked: false, - enabled: true, - }); - Ok(()) - }) - .unwrap(); - let r = s.execute("select.refineEdge", json!({"radius": 8, "output": "layerMask"})).unwrap(); - let l = s.active().unwrap().doc.layer(photocraft_doc::LayerId(r["layer"].as_u64().unwrap())).unwrap(); - let m = l.mask.as_ref().unwrap(); - assert_eq!(m.density, 0.75); - assert_eq!(m.feather, 3.5); - assert!(!m.linked); - s.execute("edit.undo", json!({})).unwrap(); - s.edit("clear mask", |doc, _| { - doc.layers[0].mask = None; - Ok(()) - }) - .unwrap(); - - // New layer: pixels with the refined alpha; the source is hidden. - let r = s.execute("select.refineEdge", json!({"radius": 8, "feather": 1, "output": "newLayer"})).unwrap(); - let d = s.active().unwrap(); - let nid = photocraft_doc::LayerId(r["layer"].as_u64().unwrap()); - assert_eq!(d.active_layer, Some(nid)); - assert_eq!(d.doc.layer_count(), layers_before + 1); - let nl = d.doc.layer(nid).unwrap(); - let surf = nl.surface().unwrap(); - assert!(surf.format().alpha); - let a = |x: i32| surf.pixel(x, 20)[3]; - assert!(a(5) > 0.99 && a(75) == 0.0 && a(40) > 0.05 && a(40) < 0.95); - assert!(!d.doc.layers[0].visible); - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(s.active().unwrap().doc.layer_count(), layers_before); - assert!(s.active().unwrap().doc.layers[0].visible); - - // New layer with mask + decontamination (selection output upgrades to it). - let r = s.execute("select.refineEdge", json!({"radius": 8, "decontaminate": true, "amount": 100})).unwrap(); - assert_eq!(r["output"], "newLayerWithMask"); - let d = s.active().unwrap(); - let nl = d.doc.layer(photocraft_doc::LayerId(r["layer"].as_u64().unwrap())).unwrap(); - assert!(nl.mask.is_some()); - let px = nl.surface().unwrap().pixel(41, 20); - let orig = d.doc.layers[0].surface().unwrap().pixel(41, 20); - // The fringe colour moved towards the warm foreground (more red, less blue). - assert!(px[0] > orig[0] + 0.05 && px[2] < orig[2] - 0.05, "{px:?} vs {orig:?}"); - s.execute("edit.undo", json!({})).unwrap(); - assert!(s.execute("select.refineEdge", json!({"output": "bogus"})).is_err()); - s.execute("select.deselect", json!({})).unwrap(); - assert!(!s.is_enabled("select.refineEdge")); - } - - /// Output To New Document (with or without a layer mask) opens a document like the source, - /// at every depth, and leaves the source document as it was. - #[test] - fn refine_edge_outputs_to_a_new_document() { - for depth in [8, 16, 32] { - let mut s = blurred_edge_selected_at(depth); - s.edit("profile", |doc, _| { - doc.resolution_dpi = 300.0; - Ok(()) - }) - .unwrap(); - let before = s.active().unwrap().doc.clone(); - let r = s.execute("select.refineEdge", json!({"radius": 8, "output": "newDocument"})).unwrap(); - assert_eq!((r["output"].as_str(), r["document"].as_u64()), (Some("newDocument"), Some(1)), "depth {depth}"); - assert_eq!(s.active_index(), Some(1)); - let nd = &s.active().unwrap().doc; - assert_eq!((nd.size, nd.mode, nd.depth, nd.resolution_dpi), (before.size, before.mode, before.depth, 300.0)); - assert_eq!(nd.layers.len(), 1); - assert!(nd.selection.is_none() && nd.layers[0].mask.is_none()); - let surf = nd.layers[0].surface().unwrap(); - let a = |x: i32| surf.pixel(x, 20)[3]; - assert!(a(5) > 0.99 && a(75) == 0.0 && a(40) > 0.05 && a(40) < 0.95, "depth {depth}: {} {} {}", a(5), a(40), a(75)); - // The source is untouched: same layers, still visible, selection kept, no history step. - let src = &s.documents()[0]; - assert_eq!(src.doc.layers, before.layers); - assert_eq!(src.doc.selection, before.selection); - assert_eq!(src.history.undo_label(), Some("profile")); - - // With a layer mask: full pixels, the refined matte as the mask. - s.execute("file.close", json!({"document": 1})).unwrap(); - let r = s.execute("select.refineEdge", json!({"radius": 8, "output": "newDocumentWithMask"})).unwrap(); - assert_eq!(r["output"], "newDocumentWithMask"); - let nd = &s.active().unwrap().doc; - let l = &nd.layers[0]; - assert_eq!(l.surface().unwrap().pixel(75, 20), before.layers[0].surface().unwrap().pixel(75, 20), "depth {depth}"); - let m = l.mask.as_ref().unwrap(); - assert!(soft_count(&m.surface, 20) >= 4, "depth {depth}"); - assert!(m.value(5, 20) > 0.99 && m.value(75, 20) < 0.01, "depth {depth}"); - } - } - - #[test] - fn refine_edge_shift_and_contrast() { - let mut s = blurred_edge_selected(); - s.execute("select.refineEdge", json!({"shiftEdge": 100})).unwrap(); - assert!(cov(&s, 42, 20) > 0.99); - s.execute("edit.undo", json!({})).unwrap(); - s.execute("select.refineEdge", json!({"feather": 8, "contrast": 100})).unwrap(); - assert!(cov(&s, 38, 20) == 1.0 && cov(&s, 42, 20) == 0.0); - } - - /// The Refine Edge Brush adds strands beyond the radius band, at every depth, and rejects - /// malformed strokes. - #[test] - fn refine_edge_brush_strokes() { - for depth in [8, 16, 32] { - // Warm subject (x < 40) with warm strands every 4th column from x = 60, on blue. - let strand = |x: u32| x < 40 || ((60..84).contains(&x) && x.is_multiple_of(4)); - let mut s = session_with(120, 40, depth, |x, _| if strand(x) { [0.9, 0.7, 0.2] } else { [0.1, 0.3, 0.8] }); - s.execute("select.rect", json!({"x": 0, "y": 0, "width": 40, "height": 40})).unwrap(); - let stroke = json!([{"points": [[70, 5], [70, 35]], "size": 30}]); - s.execute("select.refineEdge", json!({"radius": 4, "refineStrokes": stroke})).unwrap(); - assert!(cov(&s, 64, 20) > 0.9 && cov(&s, 72, 20) > 0.9, "depth {depth}: strands {}", cov(&s, 64, 20)); - assert!(cov(&s, 66, 20) < 0.1 && cov(&s, 100, 20) < 0.01, "depth {depth}: background"); - s.execute("edit.undo", json!({})).unwrap(); - // Subtract over the same place paints the refinement out again. - let both = json!([{"points": [[70, 5], [70, 35]], "size": 30}, {"points": [[70, 5], [70, 35]], "size": 40, "mode": "subtract"}]); - s.execute("select.refineEdge", json!({"radius": 4, "refineStrokes": both})).unwrap(); - assert!(cov(&s, 64, 20) < 0.01, "depth {depth}"); - s.execute("edit.undo", json!({})).unwrap(); - for bad in [ - json!(7), - json!([5]), - json!([{"points": []}]), - json!([{"points": [[1, "x"]]}]), - json!([{"points": [[1, 2, 3]]}]), - json!([{"points": [[1, 2]], "size": 0}]), - json!([{"points": [[1, 2]], "size": 1e9}]), - json!([{"points": [[1, 2]], "mode": "xor"}]), - json!([{"points": [[0, 0], [1e6, 1e6], [0, 0], [1e6, 1e6]], "size": 5000}]), - ] { - assert!(s.execute("select.refineEdge", json!({"refineStrokes": bad})).is_err(), "{bad}"); - } - } - } - - #[test] - fn refine_edge_works_on_layer_mask_without_selection() { - let mut s = blurred_edge_selected(); - s.execute("layer.layerMask.revealSelection", json!({})).unwrap(); - assert!(s.active().unwrap().doc.selection.is_none()); - assert!(s.active().unwrap().doc.layers[0].mask.is_some()); - assert!(s.is_enabled("select.refineEdge")); - - let r = s.execute("select.refineEdge", json!({"radius": 8})).unwrap(); - assert_eq!(r["output"], "layerMask"); - let d = s.active().unwrap(); - let m = d.doc.layers[0].mask.as_ref().unwrap(); - assert!(soft_count(&m.surface, 20) >= 4); - } - - #[test] - fn focus_area_command() { - let nz = noise_field(160, 100, 3); - let mut blurred = vec![0.0f32; nz.len()]; - for y in 0..100i32 { - for x in 0..160i32 { - let mut a = 0.0; - for dy in -4..=4 { - for dx in -4..=4 { - a += nz[((y + dy).clamp(0, 99) * 160 + (x + dx).clamp(0, 159)) as usize]; - } - } - blurred[(y * 160 + x) as usize] = a / 81.0; - } - } - let mut s = session_with(160, 100, 8, move |x, y| { - let i = (y * 160 + x) as usize; - let v = 0.5 + 0.15 * if x < 80 { nz[i] } else { blurred[i] * 3.0 }; - [v, v, v].map(|c| c.clamp(0.0, 1.0)) - }); - s.execute("select.focusArea", json!({})).unwrap(); - assert!(cov(&s, 30, 50) >= 0.5 && cov(&s, 130, 50) < 0.5); - } - /// The selection as 8-bit coverage over `w × h`, to compare two selections exactly. - fn sel_bytes(s: &Session, w: i32, h: i32) -> Vec { - (0..h).flat_map(|y| (0..w).map(move |x| (cov(s, x, y) * 255.0).round() as u8)).collect() - } - - /// The #8783 review: a refine whose result would be dense over more than - /// [`matting::MAX_REFINE_AREA`] pixels is refused, not allocated: a thin Brush edit across a - /// huge canvas (its edited selection spans the canvas) and a selection of the whole canvas. - /// The selection stays as it was. - #[test] - fn refine_edge_refuses_a_selection_too_large_to_refine() { - let mut s = Session::new(); - s.add_document( - Document::new("huge", photocraft_doc::Size::new(100_000, 100_000), photocraft_doc::ColorMode::Rgb, photocraft_color::SampleType::U8), - None, - ); - s.execute("select.rect", json!({"x": 10, "y": 60, "width": 10, "height": 10})).unwrap(); - let small = s.active().and_then(|d| d.doc.selection.clone()).expect("selected"); - let diagonal = json!({"edits": [{"tool": "brush", "points": [[0, 0], [99_999, 99_999]], "size": 1}]}); - let t = std::time::Instant::now(); - let e = s.execute("select.refineEdge", diagonal).expect_err("too large to refine"); - assert!(e.to_string().contains("too large to refine"), "{e}"); - assert!(s.active().and_then(|d| d.doc.selection.as_ref()) == Some(&small), "the selection is unchanged"); - // The small selection itself still refines. - s.execute("select.refineEdge", json!({"radius": 4})).unwrap(); - s.execute("edit.undo", json!({})).unwrap(); - s.execute("select.all", json!({})).unwrap(); - let all = s.active().and_then(|d| d.doc.selection.clone()).expect("selected"); - assert!(s.execute("select.refineEdge", json!({"radius": 4})).is_err()); - assert!(s.active().and_then(|d| d.doc.selection.as_ref()) == Some(&all)); - assert!(t.elapsed() < std::time::Duration::from_secs(20), "{:?}", t.elapsed()); - } - - /// The #8783 review: Brush and Lasso edits and Refine Edge Brush strokes that would paint - /// too many tiles of a huge canvas are refused before anything is painted, and the selection - /// stays as it was. - #[test] - fn refine_edge_refuses_edits_that_cross_too_many_tiles() { - let mut s = Session::new(); - s.add_document( - Document::new("huge", photocraft_doc::Size::new(100_000, 100_000), photocraft_doc::ColorMode::Rgb, photocraft_color::SampleType::U8), - None, - ); - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); - let before = s.active().and_then(|d| d.doc.selection.clone()).expect("selected"); - let zigzag: Vec<[f32; 2]> = (0..20).map(|i| [if i % 2 == 0 { 0.0 } else { 99_999.0 }, i as f32 * 5000.0]).collect(); - for p in [ - json!({"edits": [{"tool": "brush", "points": zigzag, "size": 1}]}), - json!({"edits": [{"tool": "lasso", "points": zigzag}]}), - json!({"refineStrokes": [{"points": zigzag, "size": 1}]}), - ] { - let e = s.execute("select.refineEdge", p.clone()).expect_err("refused"); - assert!(e.to_string().contains("too many tiles"), "{p}: {e}"); - assert!(s.active().and_then(|d| d.doc.selection.as_ref()) == Some(&before), "{p}: the selection is unchanged"); - } - } - - /// Select and Mask's own tools (#7069, #8148): each edit changes the selection before the - /// edge is refined, at every depth, and the whole run is one history step. - #[test] - fn refine_edge_edits_apply_each_tool_at_every_depth() { - for depth in [8, 16, 32] { - let mut s = two_regions(depth); - s.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap(); - let start = sel_bytes(&s, 140, 100); - let run = |s: &mut Session, edits: Value| { - s.execute("select.refineEdge", json!({"edits": edits})).unwrap(); - let after = sel_bytes(s, 140, 100); - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(sel_bytes(s, 140, 100), start, "depth {depth}: one undo restores the selection"); - after - }; - let at = |b: &[u8], x: usize, y: usize| b[y * 140 + x]; - // Quick Selection grows across the cool region; subtracting it again leaves the start. - let quick = run(&mut s, json!([{"tool": "quick", "points": [[100, 50], [110, 50]], "size": 8}])); - assert!(at(&quick, 120, 80) >= 128 && at(&quick, 5, 5) >= 128 && at(&quick, 40, 60) < 128, "depth {depth}: quick"); - let back = run( - &mut s, - json!([{"tool": "quick", "points": [[100, 50]], "size": 8}, {"tool": "quick", "points": [[100, 50]], "size": 8, "mode": "subtract"}]), - ); - assert!(at(&back, 120, 80) < 128 && at(&back, 5, 5) >= 128, "depth {depth}: quick subtract"); - // The Brush paints exactly where it goes. - let brush = run(&mut s, json!([{"tool": "brush", "points": [[30, 80], [60, 80]], "size": 10}])); - assert!(at(&brush, 45, 80) == 255 && at(&brush, 45, 90) == 0, "depth {depth}: brush"); - let erased = run(&mut s, json!([{"tool": "brush", "points": [[10, 10]], "size": 6, "mode": "subtract"}])); - assert!(at(&erased, 10, 10) == 0 && at(&erased, 2, 2) == 255, "depth {depth}: brush subtract"); - // Lasso adds and subtracts polygons. - let lasso = run(&mut s, json!([{"tool": "lasso", "points": [[50, 50], [90, 50], [90, 90], [50, 90]]}])); - assert!(at(&lasso, 70, 70) == 255 && at(&lasso, 95, 70) == 0 && at(&lasso, 5, 5) == 255, "depth {depth}: lasso"); - let cut = run(&mut s, json!([{"tool": "lasso", "points": [[0, 0], [10, 0], [10, 10], [0, 10]], "mode": "subtract"}])); - assert!(at(&cut, 5, 5) == 0 && at(&cut, 15, 15) == 255, "depth {depth}: lasso subtract"); - // Clear Selection, then Invert of nothing: everything. - let all = run(&mut s, json!([{"tool": "clear"}, {"tool": "invert"}])); - assert!(all.iter().all(|v| *v == 255), "depth {depth}: clear + invert"); - let inverted = run(&mut s, json!([{"tool": "invert"}])); - assert!(at(&inverted, 5, 5) == 0 && at(&inverted, 100, 50) == 255, "depth {depth}: invert"); - } - } - - /// Object Selection and Select Subject inside the workspace find what the standalone tools find. - #[test] - fn refine_edge_edits_object_and_subject() { - for depth in [8, 16, 32] { - let (mut s, inside) = disc(depth); - s.execute("select.rect", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); - s.execute("select.refineEdge", json!({"edits": [{"tool": "object", "rect": [40, 20, 120, 120]}, {"tool": "lasso", "points": [[0, 0], [10, 0], [10, 10], [0, 10]], "mode": "subtract"}]})).unwrap(); - let v = sel_iou(&s, 200, 160, &inside); - assert!(v > 0.95, "depth {depth}: object rect IoU {v}"); - s.execute("select.refineEdge", json!({"edits": [{"tool": "clear"}, {"tool": "object", "point": [3, 3]}, {"tool": "object", "point": [100, 80]}]})) - .unwrap(); - let v = sel_iou(&s, 200, 160, &inside); - assert!(v > 0.9, "depth {depth}: object point IoU {v} (the background point finds nothing)"); - } - let (mut s, inside) = disc(8); - s.execute("select.rect", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); - s.execute("select.refineEdge", json!({"edits": [{"tool": "subject"}]})).unwrap(); - let v = sel_iou(&s, 200, 160, &inside); - assert!(v > 0.9, "subject replaces the selection: IoU {v}"); - s.execute("select.rect", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); - s.execute("select.refineEdge", json!({"edits": [{"tool": "subject", "mode": "add"}]})).unwrap(); - assert!(cov(&s, 5, 5) >= 0.5 && cov(&s, 100, 80) >= 0.5, "subject added to the selection"); - } - - /// An edit gives what the standalone tool gives, then the edge is refined as usual, and the - /// result reaches every output. - #[test] - fn refine_edge_edits_match_the_tools_and_reach_the_outputs() { - let mut tool = two_regions(8); - tool.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap(); - tool.execute("select.quick", json!({"points": [[100, 50], [110, 50]], "size": 8})).unwrap(); - let mut ws = two_regions(8); - ws.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap(); - ws.execute("select.refineEdge", json!({"edits": [{"tool": "quick", "points": [[100, 50], [110, 50]], "size": 8}]})).unwrap(); - assert_eq!(sel_bytes(&ws, 140, 100), sel_bytes(&tool, 140, 100)); - // Refinement runs on the edited selection: Shift Edge contracts the brushed bar too. - let mut s = two_regions(8); - s.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap(); - s.execute("select.refineEdge", json!({"shiftEdge": -100, "edits": [{"tool": "brush", "points": [[30, 80], [100, 80]], "size": 20}]})).unwrap(); - assert!(cov(&s, 60, 80) >= 0.5 && cov(&s, 60, 88) < 0.5 && cov(&s, 60, 72) < 0.5, "the 20 px bar shrank"); - // Layer mask and new-layer outputs take the edited selection. - let mut s = blurred_edge_selected(); - let r = s.execute("select.refineEdge", json!({"output": "layerMask", "edits": [{"tool": "invert"}]})).unwrap(); - assert_eq!(r["output"], "layerMask"); - let m = s.active().unwrap().doc.layers[0].mask.as_ref().unwrap(); - assert!(m.surface.sample_channel(10, 20, 0) < 0.01 && m.surface.sample_channel(70, 20, 0) > 0.99); - let mut s = blurred_edge_selected(); - let r = s.execute("select.refineEdge", json!({"output": "newLayerWithMask", "edits": [{"tool": "invert"}]})).unwrap(); - assert_eq!(r["output"], "newLayerWithMask"); - let d = s.active().unwrap(); - let m = d.doc.layers.iter().find_map(|l| l.mask.as_ref()).unwrap(); - assert!(m.surface.sample_channel(10, 20, 0) < 0.01 && m.surface.sample_channel(70, 20, 0) > 0.99); - // Clearing everything deselects. - let mut s = blurred_edge_selected(); - let r = s.execute("select.refineEdge", json!({"edits": [{"tool": "clear"}]})).unwrap(); - assert_eq!(r["selected"], false); - assert!(s.active().unwrap().doc.selection.is_none()); - } - - /// Bad edits are refused before anything changes. - #[test] - fn refine_edge_rejects_bad_edits_and_keeps_the_selection() { - let mut s = blurred_edge_selected(); - let before = sel_bytes(&s, 80, 40); - for bad in - [json!(7), json!([{"tool": "nope"}]), json!([{"tool": "lasso", "points": [[0, 0]]}]), json!([{"tool": "brush", "points": [[0, 0]], "size": -1}])] - { - assert!(s.execute("select.refineEdge", json!({"edits": bad})).is_err(), "{bad}"); - assert_eq!(sel_bytes(&s, 80, 40), before, "{bad}"); - } - } -} diff --git a/crates/engine/src/transform_cmds.rs b/crates/engine/src/transform_cmds.rs deleted file mode 100644 index c634441394..0000000000 --- a/crates/engine/src/transform_cmds.rs +++ /dev/null @@ -1,1787 +0,0 @@ -//! Edit › Free Transform / Transform: projective transforms of layers (and the selection). - -use photocraft_algo::transform::{Homography, Interp, WARP_REACH, warp_output_clipped, warp_output_size, warp_surface, warp_surface_with}; -use photocraft_color::PixelFormat; -#[cfg(test)] -use photocraft_color::{ColorMode, SampleType}; -use photocraft_doc::{Document, Layer, LayerContent, LayerId, Locks}; -use photocraft_geom::{Affine, Rect}; -use photocraft_raster::{Interrupt, Surface}; -use serde_json::{Value, json}; -use std::sync::atomic::{AtomicU64, Ordering}; - -use crate::commands::CommandSpec; -use crate::{EngineError, Result, Session}; - -fn has_layer(s: &Session) -> std::result::Result<(), String> { - s.active().and_then(|d| d.active_layer).map(|_| ()).ok_or_else(|| "no active layer".into()) -} - -fn bad(msg: impl Into) -> EngineError { - EngineError::BadParams { cmd: "edit.transform".into(), msg: msg.into() } -} - -/// Layers a transform moves as a whole, even with a selection: groups, and the kinds that keep the -/// transform instead of pixels (type, shapes, smart objects). Only pixel layers move just the -/// selected pixels. -pub fn moves_whole(layer: &Layer) -> bool { - matches!(layer.content, LayerContent::Group(_) | LayerContent::Text(_) | LayerContent::Shape(_) | LayerContent::Smart(_)) -} - -/// Document-space bounds a transform of `layer` starts from (what Free Transform frames): the -/// content within the selection, or all of it for a layer that [`moves_whole`] (#2630). -/// Content scans are cached per tile: snapping asks for every layer's bounds per Move drag. -pub fn transform_bounds(doc: &Document, layer: &Layer) -> Rect { - let content = whole_layer_bounds(doc, layer); - match &doc.selection { - Some(sel) if !moves_whole(layer) => content.intersect(&sel.content_bounds()), - _ => content, - } -} - -/// The box Free Transform opens on `layer`, and the Move tool's transform controls show (#5297). -/// With a selection that limits the transform it is the selection's own bounds, as in Photoshop: -/// the box and the marching ants are one rectangle, however little of the selection the layer -/// fills. Empty, like [`transform_bounds`], when the selection holds none of the layer. -pub fn transform_frame(doc: &Document, layer: &Layer) -> Rect { - let b = transform_bounds(doc, layer); - if moves_whole(layer) { b } else { framed_by_selection(doc, b) } -} - -/// `bounds` (what a selection left of a transform's content), or the selection's own bounds. -fn framed_by_selection(doc: &Document, bounds: Rect) -> Rect { - match &doc.selection { - Some(sel) if !bounds.is_empty() => sel.content_bounds(), - _ => bounds, - } -} - -/// A group moves all its descendants, so its frame must not clip raster children to the selection. -pub(crate) fn whole_layer_bounds(doc: &Document, layer: &Layer) -> Rect { - let content = match &layer.content { - LayerContent::Group(g) => g.children.iter().map(|c| whole_layer_bounds(doc, c)).fold(Rect::EMPTY, |a, b| a.union(&b)), - // A soft shape (Density below 100 % or a Feather) renders past its path, over the whole - // canvas below 100 %: its frame follows the path and stroke, as in Photoshop (#5846). - LayerContent::Shape(sh) if sh.has_soft_mask() => photocraft_compose::soft_shape_frame(sh, doc.pixel_format(), doc.bounds()).unwrap_or(Rect::EMPTY), - _ => layer.surface().map_or(Rect::EMPTY, photocraft_compose::bounds::content_bounds), - }; - if content.is_empty() { layer.mask.as_ref().map_or(Rect::EMPTY, |m| photocraft_compose::bounds::content_bounds(&m.surface)) } else { content } -} - -/// Warp a surface whose pixels outside the content read as `default` (masks, selections): -/// warp the content with alpha, then flatten back onto the default value. -pub(crate) fn warp_gray(s: &Surface, h: &Homography, interp: Interp) -> Result { - let default = s.default_pixel().first().copied().unwrap_or(0.0); - let fmt = s.format(); - let src = s.content_bounds(); - let mut out = Surface::with_default(fmt, &[default]); - if src.is_empty() { - return Ok(out); - } - // Content-only copy (default 0 + alpha) so the "outside" is transparent during the warp. - let with_alpha = PixelFormat::new(fmt.mode, fmt.sample, true); - let mut tmp = Surface::new(with_alpha); - let v = crate::allocation::read_region(s, src, "transforming a mask or channel")?; - let mut lifted = - crate::allocation::filled(v.len().checked_mul(2).ok_or_else(|| bad("the mask is too large to transform"))?, 0.0, "transforming a mask or channel")?; - let (lifted_pairs, _) = lifted.as_chunks_mut::<2>(); - for (g, px) in v.iter().zip(lifted_pairs) { - px.copy_from_slice(&[*g, 1.0]); - } - tmp.try_write_region(src, &lifted)?; - let w = warp_surface(&tmp, src, h, interp)?; - // Clear the old content region, then composite the warped content over it. These are written as - // two sparse regions rather than one dense `src ∪ warped` block: a transform that moves the - // content far away (e.g. a huge translation) would otherwise allocate a buffer spanning both and - // hang/OOM. `Surface` is tile-sparse, so distant regions cost only their own tiles. - let old_len = (src.width() as usize).checked_mul(src.height() as usize).ok_or_else(|| bad("the mask is too large to transform"))?; - let old = crate::allocation::filled(old_len, default, "transforming a mask or channel")?; - out.try_write_region(src, &old)?; - let b = w.content_bounds(); - if !b.is_empty() { - let px = crate::allocation::read_region(&w, b, "flattening a transformed mask or channel")?; - let mut flat = crate::allocation::filled(px.len() / 2, 0.0, "flattening a transformed mask or channel")?; - for (p, f) in px.as_chunks::<2>().0.iter().zip(&mut flat) { - *f = p[0] * p[1] + default * (1.0 - p[1]); - } - out.try_write_region(b, &flat)?; - } - out.prune(); - Ok(out) -} - -/// Split a single-channel surface whose outside reads as its default (a mask, a channel) by a -/// selection: (the selected values as grey + alpha = selection, the surface with the selected -/// values replaced by the default). `None` for surfaces that aren't a single grey channel. -pub fn split_gray_selected(s: &Surface, sel: &Surface) -> Result> { - let fmt = s.format(); - if fmt.alpha || fmt.channels() != 1 { - return Ok(None); - } - let default = s.default_pixel().first().copied().unwrap_or(0.0); - let mut rest = s.clone(); - let mut lifted = Surface::new(PixelFormat::new(fmt.mode, fmt.sample, true)); - // Everything selected moves, including default-valued parts outside the painted content, so - // the moved region stays aligned with the moved pixels. - let area = sel.content_bounds(); - if area.is_empty() { - return Ok(Some((lifted, rest))); - } - let v = crate::allocation::read_region(s, area, "transforming a selected mask or channel")?; - let w = area.width() as usize; - let mut lp = crate::allocation::capacity( - v.len().checked_mul(2).ok_or_else(|| bad("the selected mask is too large to transform"))?, - "transforming a selected mask or channel", - )?; - let mut rp = crate::allocation::capacity(v.len(), "transforming a selected mask or channel")?; - for (i, g) in v.iter().enumerate() { - let (x, y) = (area.x0 + (i % w) as i32, area.y0 + (i / w) as i32); - let k = sel.sample_channel(x, y, 0); - lp.extend([*g, k]); - rp.push(g * (1.0 - k) + default * k); - } - lifted.try_write_region(area, &lp)?; - lifted.prune(); - rest.try_write_region(area, &rp)?; - rest.prune(); - Ok(Some((lifted, rest))) -} - -/// [`warp_gray`] limited to a selection: only the selected values move (the vacated area reads as -/// the default), as the selected pixels of the layer do. -pub(crate) fn warp_gray_selected(s: &Surface, sel: &Surface, h: &Homography, interp: Interp) -> Result { - move_gray_selected(s, sel, &|lifted, src| Ok(warp_surface(lifted, src, h, interp)?), &|s| warp_gray(s, h, interp)) -} - -/// [`warp_gray_selected`] with any geometric warp: `warp` moves the lifted grey + alpha values -/// (given their bounds), `whole` moves `s` when it isn't a single grey channel. -pub(crate) fn move_gray_selected( - s: &Surface, - sel: &Surface, - warp: &dyn Fn(&Surface, Rect) -> Result, - whole: &dyn Fn(&Surface) -> Result, -) -> Result { - let Some((lifted, mut out)) = split_gray_selected(s, sel)? else { return whole(s) }; - let src = lifted.content_bounds(); - if src.is_empty() { - return Ok(out); - } - let w = warp(&lifted, src)?; - let b = w.content_bounds(); - if !b.is_empty() { - let moved = crate::allocation::read_region(&w, b, "compositing transformed mask pixels")?; - let under = crate::allocation::read_region(&out, b, "compositing transformed mask pixels")?; - let mut flat = crate::allocation::filled(under.len(), 0.0, "compositing transformed mask pixels")?; - for (i, (p, u)) in moved.as_chunks::<2>().0.iter().zip(&under).enumerate() { - flat[i] = p[0] * p[1] + u * (1.0 - p[1]); - } - out.try_write_region(b, &flat)?; - } - out.prune(); - Ok(out) -} - -/// The surface Free Transform moves by itself when the params target one (`"target"`): an -/// unlinked layer mask, an alpha channel or the Quick Mask. `None` means the layer, with its -/// linked masks (a targeted *linked* mask moves together with its layer, as in Photoshop). -pub fn lone_target<'a>(doc: &'a Document, layer: Option, p: &Value) -> Result> { - use crate::channel_cmds::Target; - match crate::channel_cmds::target_of(p) { - Target::Pixels => Ok(None), - Target::Mask => { - let id = layer.ok_or_else(|| EngineError::Other("no active layer".into()))?; - let l = doc.layer(id).ok_or(EngineError::NoLayer(id))?; - let m = l.mask.as_ref().ok_or_else(|| EngineError::Other("layer has no mask".into()))?; - Ok((!m.linked).then_some(&m.surface)) - } - // A filter mask is not transformed on its own: the smart object transforms, as in Photoshop. - Target::FilterMask => Ok(None), - Target::Alpha(i) => doc - .channels - .get(i) - .map(|c| Some(&c.surface)) - .ok_or_else(|| EngineError::Other(format!("no alpha channel {i} (document has {})", doc.channels.len()))), - Target::QuickMask => doc.quick_mask.as_ref().map(|c| Some(&c.surface)).ok_or_else(|| EngineError::Other("not in Quick Mask mode".into())), - } -} - -/// [`lone_target`], mutably. -pub fn lone_target_mut<'a>(doc: &'a mut Document, layer: Option, p: &Value) -> Result> { - if lone_target(doc, layer, p)?.is_none() { - return Ok(None); - } - crate::channel_cmds::target_surface(doc, layer, p).map(|(s, _)| Some(s)) -} - -/// The frame Free Transform starts from on a lone target: its painted content (the whole canvas -/// when nothing is painted), within the selection. -pub fn target_bounds(doc: &Document, surf: &Surface) -> Rect { - let content = surf.content_bounds(); - let content = if content.is_empty() { doc.bounds() } else { content }; - match &doc.selection { - Some(sel) => content.intersect(&sel.content_bounds()), - None => content, - } -} - -/// The box Free Transform opens on a lone target: like [`transform_frame`], the selection's own -/// bounds when there is one (#5297). -pub fn target_frame(doc: &Document, surf: &Surface) -> Rect { - framed_by_selection(doc, target_bounds(doc, surf)) -} - -/// The locks `id` inherits from the groups around it. -pub(crate) fn group_locks(doc: &Document, id: LayerId) -> Locks { - doc.path_of(id).and_then(|p| Some(doc.locks_at(p.split_last()?.1))).unwrap_or_default() -} - -/// The locks a transform of `l` meets: its own and `group`'s (those it inherits). The Background's -/// position lock doesn't count: Photoshop turns it into a normal layer first. -fn transform_locks(l: &Layer, group: Locks, background: bool) -> Locks { - let mut own = l.locks; - if background { - own.position = false; - own.transparency = false; - } - own.union(group) -} - -/// Would a transform of the layer `id` be refused because it, a group around it, or (for a group) -/// a layer inside it is locked in place? The same rule [`transform_layer`] applies at commit, so -/// Free Transform can refuse before its box opens, as Photoshop does. -pub fn locked_for_transform(doc: &Document, id: LayerId) -> bool { - let Some(l) = doc.layer(id) else { return false }; - // An explicit stack rather than recursion: documents can nest deeply. - let mut stack = vec![(l, group_locks(doc, id), doc.is_background(id))]; - while let Some((l, group, background)) = stack.pop() { - let locks = transform_locks(l, group, background); - if locks.position || locks.all { - return true; - } - if let LayerContent::Group(g) = &l.content { - stack.extend(g.children.iter().map(|c| (c, locks, false))); - } - } - false -} - -/// The memory (bytes) a single Free Transform warp's result may take: Preferences › Performance › -/// Memory Usage, which [`Session::apply_prefs`] sets, rather than a fixed 2³⁰ px, so a stitched -/// layer of a few gigapixels transforms on a machine that has the memory for it (#7807). Only the -/// size of the result counts, not where it lands, so moving a layer far off the canvas stays -/// allowed as far as the warp reaches ([`WARP_REACH`]). A scale past it is refused rather than -/// clipped (#3773): the warp would otherwise fill every tile of a result up to 2²¹ px on a side -/// before anything could fail. -static BUDGET: AtomicU64 = AtomicU64::new((crate::prefs::DEFAULT_MEMORY_USAGE_MB as u64) << 20); - -/// Set the memory (bytes) one transform's result may take (see [`budget`]). -pub fn set_budget(bytes: u64) { - BUDGET.store(bytes, Ordering::Relaxed); -} - -/// The memory (bytes) one transform's result may take: Memory Usage. -pub fn budget() -> u64 { - BUDGET.load(Ordering::Relaxed) -} - -/// What [`check_budget`] holds a result to: [`budget`]. -#[cfg(not(test))] -fn active_budget() -> u64 { - budget() -} - -/// Tests use a far lower budget, so proving a refusal never comes near allocating the real one: -/// 2²⁰ px of the widest format (32-bit CMYK with alpha, 20 MB), so a result within the old 2²⁰ px -/// test limit still fits at any depth. -#[cfg(test)] -fn active_budget() -> u64 { - (1 << 20) * PixelFormat::new(ColorMode::Cmyk, SampleType::F32, true).bytes_per_pixel() as u64 -} - -/// Refuse a warp of the content inside `src` (pixels of `format`) by `h` whose result would take -/// more memory than the budget, or reach past where the warp places pixels (it would be clipped), -/// before anything is built. `what` names the surface in the message, which names the setting or -/// the reach rather than a shortage: nothing has been allocated yet. -pub(crate) fn check_budget(src: Rect, h: &Homography, what: &str, format: PixelFormat) -> Result<()> { - check_budget_with_limit(src, h, what, format, active_budget()) -} - -/// [`check_budget`] against `budget` bytes (the tests price the production budget with it). -fn check_budget_with_limit(src: Rect, h: &Homography, what: &str, format: PixelFormat, budget: u64) -> Result<()> { - let Some((w, ht)) = warp_output_size(src, h) else { return Ok(()) }; - // The warp writes each tile into the result as it goes, so the result is what it holds; it - // adds alpha to a format without it. - let bpp = PixelFormat::new(format.mode, format.sample, true).bytes_per_pixel() as u64; - let bytes = w.saturating_mul(ht).saturating_mul(bpp); - if bytes > budget { - let mb = |b: u64| b.div_ceil(1 << 20); - return Err(EngineError::Other(format!( - "too large to transform: the transformed {what} would be {w} x {ht} px ({} MB), more than the {} MB Memory Usage allows (Preferences › Performance); the document was not changed", - mb(bytes), - budget >> 20 - ))); - } - if warp_output_clipped(src, h) { - return Err(EngineError::Other(format!( - "too large to transform: the transformed {what} would reach past ±{WARP_REACH} px, the farthest a transform places pixels; the document was not changed" - ))); - } - Ok(()) -} - -/// [`check_budget`] for every warp [`transform_layer`] would make of `l` (for a group, of every -/// layer inside it), so a transform that doesn't fit is refused before any layer is built and a -/// group that partly fits isn't half-transformed. -fn check_layer_budget(doc_sel: Option<&Surface>, l: &Layer, h: &Homography) -> Result<()> { - if h.is_identity() { - return Ok(()); - } - // An explicit stack rather than recursion: documents can nest deeply. - let mut stack = vec![(l, doc_sel)]; - while let Some((l, sel)) = stack.pop() { - match &l.content { - LayerContent::Group(g) => stack.extend(g.children.iter().map(|c| (c, None))), - LayerContent::Text(_) | LayerContent::Shape(_) => {} - LayerContent::Smart(sm) => { - if let Some(c) = &sm.cache { - check_budget(c.content_bounds(), h, "smart object", c.format())?; - } - if let Some(m) = &sm.filter_mask { - check_budget(m.surface.content_bounds(), h, "smart filter mask", m.surface.format())?; - } - } - _ => { - if let Some(surf) = l.surface() { - // With a selection only the lifted pixels are warped (`split_selected`). - let src = match sel { - Some(sel) => surf.content_bounds().intersect(&sel.content_bounds()), - None => surf.content_bounds(), - }; - check_budget(src, h, &format!("layer \"{}\"", l.name), surf.format())?; - } - } - } - if let Some(m) = &l.mask - && m.linked - { - // With a selection only its region of the mask moves (`warp_gray_selected`). - let src = match sel.filter(|_| !moves_whole(l)) { - Some(sel) => sel.content_bounds(), - None => m.surface.content_bounds(), - }; - check_budget(src, h, "layer mask", m.surface.format())?; - } - } - Ok(()) -} - -/// `group` holds the locks `l` inherits from the groups around it ([`group_locks`]). A Background -/// is turned into a normal layer by the caller first ([`crate::extra_cmds::background_to_layer`]). -/// Refused, with `l` untouched, when a result would take more than [`budget`]. -pub(crate) fn transform_layer(doc_sel: Option<&Surface>, group: Locks, l: &mut Layer, h: &Homography, affine: Option, interp: Interp) -> Result<()> { - transform_layer_with(doc_sel, group, l, h, affine, interp, &Interrupt::NONE) -} - -/// [`transform_layer`] with progress and cancellation for the pixel warp (the slow part on a -/// large layer, #1015). -fn transform_layer_with( - doc_sel: Option<&Surface>, - group: Locks, - l: &mut Layer, - h: &Homography, - affine: Option, - interp: Interp, - ctl: &Interrupt, -) -> Result<()> { - check_layer_budget(doc_sel, l, h)?; - apply_transform(doc_sel, group, l, h, affine, interp, ctl) -} - -fn apply_transform( - doc_sel: Option<&Surface>, - group: Locks, - l: &mut Layer, - h: &Homography, - affine: Option, - interp: Interp, - ctl: &Interrupt, -) -> Result<()> { - crate::allocation::checkpoint("transforming pixels")?; - let locks = transform_locks(l, group, false); - if locks.position || locks.all { - return Err(EngineError::Other(format!("layer \"{}\" is locked", l.name))); - } - if h.is_identity() { - if let LayerContent::Group(g) = &mut l.content { - for c in g.children.iter_mut() { - apply_transform(None, locks, c, h, affine, interp, ctl)?; - } - } - return Ok(()); - } - // With a selection only the selected pixels move, and so only the same region of a linked - // mask (#205). Groups, type, shapes and smart objects move whole. - let mask_sel = doc_sel.filter(|_| !moves_whole(l)); - // The masks (and so a fill's frame) move, but a fill layer's cached render isn't warped: - // drop it, the fill re-renders from its model (as `transform_layer_geometry` does). - l.fill_cache = None; - match &mut l.content { - LayerContent::Group(g) => { - for c in g.children.iter_mut() { - apply_transform(None, locks, c, h, affine, interp, ctl)?; - } - } - LayerContent::Text(t) => { - let Some(a) = affine else { - return Err(EngineError::Other("Distort and Perspective need rasterized type (Type › Rasterize Type Layer)".into())); - }; - t.transform = a.mul(&t.transform); - } - LayerContent::Shape(sh) => match affine { - Some(a) => crate::vector_cmds::transform_shape(sh, &a), - // Distort and Perspective map the path and keep the shape (#3009). - None => crate::vector_cmds::map_shape(sh, Some(h), None)?, - }, - LayerContent::Smart(sm) => { - // Smart objects keep the transform and re-render from their source afterwards - // (`refresh_text`), so repeated transforms don't degrade the pixels. Distort and - // Perspective keep the full projective map, so the fourth corner survives re-renders. - match affine { - Some(a) => crate::smart_cmds::transform_placement(sm, &a), - None => crate::smart_cmds::set_placement(sm, h.mul(&crate::smart_cmds::placement(sm))), - } - // Fallback appearance for sources that can't be re-rendered. - if let Some(c) = &mut sm.cache { - let src = c.content_bounds(); - *c = warp_surface(c, src, h, interp)?; - } - if let Some(m) = &mut sm.filter_mask { - m.surface = warp_gray(&m.surface, h, interp)?; - } - } - _ => { - if let Some(surf) = l.surface_mut() { - *surf = match doc_sel { - // Only the selected pixels move: lift them, clear them, warp and paste back. The - // lifted pixels' own bounds are the edge a stretch repeats (#3773). - Some(sel) => { - let (lifted, mut rest) = split_selected(surf, sel)?; - let moved = warp_surface_with(&lifted, lifted.content_bounds(), h, interp, ctl)?.ok_or(EngineError::Cancelled)?; - composite_over(&mut rest, &moved); - rest.prune(); - rest - } - None => { - let src = surf.content_bounds(); - warp_surface_with(surf, src, h, interp, ctl)?.ok_or(EngineError::Cancelled)? - } - }; - } - } - } - if let Some(m) = l.mask.as_mut() - && m.linked - { - m.surface = match mask_sel { - Some(sel) => warp_gray_selected(&m.surface, sel, h, interp)?, - None => warp_gray(&m.surface, h, interp)?, - }; - } - if let Some(vm) = l.vector_mask.as_mut() - && vm.linked - { - vm.path = match affine { - Some(a) => vm.path.transform(&a), - None => crate::vector_cmds::map_path(&vm.path, Some(h), None)?, - }; - } - Ok(()) -} - -/// Split a layer surface by a selection: (selected pixels, everything else), both with alpha. -pub fn split_selected(surf: &Surface, sel: &Surface) -> Result<(Surface, Surface)> { - let fmt = surf.format(); - let with_alpha = PixelFormat::new(fmt.mode, fmt.sample, true); - let mut lifted = Surface::new(with_alpha); - let mut rest = surf.try_convert(with_alpha)?; - let src = surf.content_bounds(); - if src.is_empty() { - return Ok((lifted, rest)); - } - let n = with_alpha.channels(); - let px = crate::allocation::read_region(&rest, src, "transforming selected pixels")?; - let mut lp = crate::allocation::filled(px.len(), 0.0, "transforming selected pixels")?; - lp.copy_from_slice(&px); - let mut rp = px; - let w = src.width() as usize; - // A pixel the selection fully lifts out is reset to the surface's (transparent) default; - // keeping its colour would make `content_bounds` still count it, so the layer's bounds would - // include the area the pixels were moved from. - let mut rest_clear = rest.default_pixel(); - if rest_clear.last().is_some_and(|a| *a > 0.0) { - rest_clear.fill(0.0); - } - for (i, (l, r)) in lp.chunks_exact_mut(n).zip(rp.chunks_exact_mut(n)).enumerate() { - let (x, y) = (src.x0 + (i % w) as i32, src.y0 + (i / w) as i32); - let k = sel.sample_channel(x, y, 0); - l[n - 1] *= k; - r[n - 1] *= 1.0 - k; - // Likewise an unselected pixel leaves nothing in the lifted surface, so its bounds are the - // selected pixels' (what a stretch repeats at the edge, #3773). - if l[n - 1] <= 0.0 { - l.fill(0.0); - } - if r[n - 1] <= 0.0 { - r.iter_mut().zip(&rest_clear).for_each(|(d, c)| *d = *c); - } - } - lifted.try_write_region(src, &lp)?; - lifted.prune(); - rest.try_write_region(src, &rp)?; - Ok((lifted, rest)) -} - -pub(crate) fn refresh_text(doc: &Document, l: &mut Layer) { - match &mut l.content { - LayerContent::Text(t) => crate::type_cmds::refresh(doc, t), - LayerContent::Shape(sh) => crate::vector_cmds::refresh_shape(doc, sh), - LayerContent::Smart(_) => { - // Unavailable sources keep the warped cache. - let _ = crate::smart_cmds::refresh_layer(doc, l); - } - LayerContent::Group(g) => g.children.iter_mut().for_each(|c| refresh_text(doc, c)), - _ => {} - } -} - -/// Normal-blend `top` over `dst` (both straight alpha, same format). -/// Works tile by tile in parallel on `top`'s allocated tiles: fully opaque tiles share their -/// `Arc` directly with `dst`, and opaque/transparent pixels on border tiles copy encoded -/// bytes without a whole-region `f32` round trip. -pub(crate) fn composite_over(dst: &mut Surface, top: &Surface) { - use photocraft_color::{SampleType, read_sample}; - use photocraft_geom::TileCoord; - use photocraft_raster::Tile; - use rayon::prelude::*; - use std::sync::Arc; - - let fmt = dst.format(); - let n = fmt.channels(); - if n == 0 || !fmt.alpha || top.format() != fmt { - return; - } - let a = n - 1; - if top.default_pixel().get(a).is_none_or(|&ta| ta <= 0.0) { - let top_tiles: Vec<(TileCoord, Arc)> = top.tiles().map(|(&tc, t)| (tc, t.clone())).collect(); - if top_tiles.is_empty() { - return; - } - let bpp = fmt.bytes_per_pixel(); - let sb = fmt.sample.bytes(); - let alpha_off = bpp - sb; - let dst_empty_default = dst.default_bytes().iter().all(|&b| b == 0); - let dst_ref = &*dst; - let edits: Vec<(TileCoord, Arc)> = top_tiles - .into_par_iter() - .filter_map(|(tc, top_tile)| { - let tb = top_tile.bytes(); - let all_opaque = match fmt.sample { - SampleType::U8 => tb.chunks_exact(bpp).all(|px| px.get(alpha_off) == Some(&u8::MAX)), - SampleType::U16 => tb.chunks_exact(bpp).all(|px| px.get(alpha_off..bpp) == Some(&[u8::MAX, u8::MAX])), - SampleType::F32 => tb.chunks_exact(bpp).all(|px| read_sample(px, SampleType::F32, a) == 1.0), - }; - if all_opaque { - return Some((tc, top_tile)); - } - let all_transparent = match fmt.sample { - SampleType::U8 => tb.chunks_exact(bpp).all(|px| px.get(alpha_off) == Some(&0)), - SampleType::U16 => tb.chunks_exact(bpp).all(|px| px.get(alpha_off..bpp) == Some(&[0, 0])), - SampleType::F32 => tb.chunks_exact(bpp).all(|px| read_sample(px, SampleType::F32, a) <= 0.0), - }; - if all_transparent { - return None; - } - if dst_ref.tile(tc).is_none() && dst_empty_default { - let clean_zero = match fmt.sample { - SampleType::U8 => tb.chunks_exact(bpp).all(|px| px.get(alpha_off) != Some(&0) || px.iter().all(|&b| b == 0)), - SampleType::U16 => tb.chunks_exact(bpp).all(|px| px.get(alpha_off..bpp) != Some(&[0, 0]) || px.iter().all(|&b| b == 0)), - SampleType::F32 => tb.chunks_exact(bpp).all(|px| read_sample(px, SampleType::F32, a) > 0.0 || px.iter().all(|&b| b == 0)), - }; - if clean_zero { - return Some((tc, top_tile)); - } - } - let mut out_tile = match dst_ref.tile(tc) { - Some(dt) => (**dt).clone(), - None => dst_ref.try_default_tile().ok()?, - }; - let mut tp = [0.0f32; 8]; - let mut dp = [0.0f32; 8]; - for (out_px, top_px) in out_tile.bytes_mut().chunks_exact_mut(bpp).zip(tb.chunks_exact(bpp)) { - match fmt.sample { - SampleType::U8 => { - let ta_b = top_px[alpha_off]; - if ta_b == 0 { - continue; - } - if ta_b == u8::MAX { - out_px.copy_from_slice(top_px); - continue; - } - } - SampleType::U16 => { - if top_px[alpha_off..bpp] == [0, 0] { - continue; - } - if top_px[alpha_off..bpp] == [u8::MAX, u8::MAX] { - out_px.copy_from_slice(top_px); - continue; - } - } - SampleType::F32 => { - let ta = read_sample(top_px, SampleType::F32, a); - if ta <= 0.0 { - continue; - } - if ta == 1.0 { - out_px.copy_from_slice(top_px); - continue; - } - } - } - for c in 0..n { - tp[c] = read_sample(top_px, fmt.sample, c); - dp[c] = read_sample(out_px, fmt.sample, c); - } - let (ta, da) = (tp[a], dp[a]); - let oa = ta + da * (1.0 - ta); - if oa > 0.0 { - for c in 0..a { - dp[c] = (tp[c] * ta + dp[c] * da * (1.0 - ta)) / oa; - } - } - dp[a] = oa; - photocraft_raster::encode_pixel(&fmt, &dp[..n], out_px); - } - Some((tc, Arc::new(out_tile))) - }) - .collect(); - dst.put_tiles(edits); - return; - } - let b = top.content_bounds(); - if b.is_empty() { - return; - } - let t = top.read_region(b); - let mut d = dst.read_region(b); - for (dp, tp) in d.chunks_exact_mut(n).zip(t.chunks_exact(n)) { - let (ta, da) = (tp[a], dp[a]); - let oa = ta + da * (1.0 - ta); - if oa > 0.0 { - for c in 0..a { - dp[c] = (tp[c] * ta + dp[c] * da * (1.0 - ta)) / oa; - } - } - dp[a] = oa; - } - dst.write_region(b, &d); -} - -/// The relative form (`scaleX`, `scaleY` in percent, `rotate` in degrees clockwise, `dx`, `dy` -/// in pixels), as Photoshop records a Free Transform: scale and rotate about the frame's -/// centre, then move. `None` when none of them is given. -fn relative_matrix(p: &Value, rect: [f64; 4]) -> Result> { - let num = |k: &str| -> Result> { - match p.get(k) { - None | Some(Value::Null) => Ok(None), - Some(v) => v.as_f64().filter(|f| f.is_finite()).map(Some).ok_or_else(|| bad(format!("`{k}` must be a finite number"))), - } - }; - let (sx, sy, rot, dx, dy) = (num("scaleX")?, num("scaleY")?, num("rotate")?, num("dx")?, num("dy")?); - if sx.is_none() && sy.is_none() && rot.is_none() && dx.is_none() && dy.is_none() { - return Ok(None); - } - let (sx, sy) = (sx.unwrap_or(100.0) / 100.0, sy.unwrap_or(100.0) / 100.0); - if sx.abs() < 1e-6 || sy.abs() < 1e-6 { - return Err(bad("`scaleX` and `scaleY` must not be 0")); - } - let (cx, cy) = ((rect[0] + rect[2]) / 2.0, (rect[1] + rect[3]) / 2.0); - let (sin, cos) = rot.unwrap_or(0.0).to_radians().sin_cos(); - // (x, y) → translate(-c) → scale → rotate → translate(c + d). - let (a, b, c, d) = (sx * cos, sx * sin, -sy * sin, sy * cos); - let e = cx + dx.unwrap_or(0.0) - a * cx - c * cy; - let f = cy + dy.unwrap_or(0.0) - b * cx - d * cy; - Ok(Some(Homography([a, c, e, b, d, f, 0.0, 0.0, 1.0]))) -} - -fn quad_param(p: &Value) -> Option<[[f64; 2]; 4]> { - let a = p.get("quad")?.as_array()?; - if a.len() != 4 { - return None; - } - let mut q = [[0.0; 2]; 4]; - for (i, v) in a.iter().enumerate() { - let c = v.as_array()?; - q[i] = [c.first()?.as_f64()?, c.get(1)?.as_f64()?]; - } - Some(q) -} - -/// `p`, with the Channels panel's targeted alpha channel or Quick Mask as its `"target"` when it -/// names neither a target nor a layer (#2835). -fn with_panel_target(s: &Session, p: &Value) -> Value { - let mut p = if p.is_object() { p.clone() } else { json!({}) }; - if p.get("target").is_none() - && p.get("layer").is_none() - && let (Some(m), Some(Value::Object(t))) = (p.as_object_mut(), crate::channel_cmds::targeted_channel(s)) - { - m.extend(t); - } - p -} - -fn transform(s: &mut Session, p: &Value) -> Result { - let p = &with_panel_target(s, p); - let st = s.active().ok_or(EngineError::NoDocument)?; - let id = crate::commands::explicit_layer(s, p)?.or(st.active_layer); - let lone = lone_target(&st.doc, id, p)?; - let id = match (id, lone.is_some() && crate::channel_cmds::is_channel_target(p)) { - (_, true) => None, - (Some(id), false) => Some(id), - (None, false) => return Err(EngineError::Other("no active layer".into())), - }; - let rect = match p.get("rect").and_then(Value::as_array) { - Some(r) if r.len() == 4 => { - let v: Vec = r.iter().map(|x| x.as_f64().unwrap_or(0.0)).collect(); - [v[0], v[1], v[2], v[3]] - } - _ => { - let b = match (lone, id) { - (Some(surf), _) => target_bounds(&st.doc, surf), - (None, Some(id)) => transform_bounds(&st.doc, st.doc.layer(id).ok_or(EngineError::NoLayer(id))?), - (None, None) => Rect::EMPTY, - }; - if b.is_empty() { - return Err(EngineError::Other("nothing to transform".into())); - } - [b.x0 as f64, b.y0 as f64, b.x1 as f64, b.y1 as f64] - } - }; - let h = if let Some(q) = quad_param(p) { - Homography::rect_to_quad(rect, q).ok_or_else(|| bad("degenerate quad"))? - } else if let Some(m) = p.get("matrix").and_then(Value::as_array) { - let v: Vec = m.iter().filter_map(Value::as_f64).collect(); - if v.len() != 6 { - return Err(bad("matrix must be [a, b, c, d, e, f]")); - } - // Affine [a b c d e f] maps (x, y) → (a·x + c·y + e, b·x + d·y + f). - Homography([v[0], v[2], v[4], v[1], v[3], v[5], 0.0, 0.0, 1.0]) - } else if let Some(m) = relative_matrix(p, rect)? { - m - } else { - return Err(bad("pass `quad` (where the rect's corners go), `matrix`, or `scaleX`/`scaleY`/`rotate`/`dx`/`dy`")); - }; - if h.inverse().is_none() { - return Err(bad("the transform collapses the layer")); - } - let m = h.0; - let affine = - (m[6].abs() < 1e-12 && m[7].abs() < 1e-12).then(|| Affine { m: [m[0] / m[8], m[3] / m[8], m[1] / m[8], m[4] / m[8], m[2] / m[8], m[5] / m[8]] }); - let interp = Interp::parse(p.get("interpolation").and_then(Value::as_str).unwrap_or("bicubic")); - let lone = lone.is_some(); - let p = p.clone(); - // A background job when started with `Session::start` (#1015): the warp of a large layer runs - // on a worker with progress, and can be cancelled. - crate::jobs::edit_job( - s, - "Free Transform", - move |doc, _, ctx| ctx.stage(0.0, 1.0, "Transforming", |ctl| transform_doc(doc, id, &p, lone, &h, affine, interp, ctl)), - move |()| json!({"rect": rect}), - ) -} - -/// The edit of [`transform`]: the layer (or a lone mask or channel) and the selection outline. -#[allow(clippy::too_many_arguments)] -fn transform_doc( - doc: &mut Document, - id: Option, - p: &Value, - lone: bool, - h: &Homography, - affine: Option, - interp: Interp, - ctl: &Interrupt, -) -> Result<()> { - let sel = doc.selection.clone(); - // The selection outline moves too: price it before anything is built. - if let Some(sel) = sel.as_ref().filter(|_| !h.is_identity()) { - check_budget(sel.content_bounds(), h, "selection", sel.format())?; - } - if lone { - // A targeted unlinked mask, alpha channel or Quick Mask transforms by itself. - if !h.is_identity() { - let (surf, _) = crate::channel_cmds::target_surface(doc, id, p)?; - let src = sel.as_ref().map_or_else(|| surf.content_bounds(), Surface::content_bounds); - check_budget(src, h, "mask or channel", surf.format())?; - *surf = match &sel { - Some(sel) => warp_gray_selected(surf, sel, h, interp)?, - None => warp_gray(surf, h, interp)?, - }; - if let Some(sel) = &doc.selection { - doc.selection = Some(warp_gray(sel, h, Interp::Bilinear)?).filter(|s| !s.content_bounds().is_empty()); - } - } - return Ok(()); - } - let id = id.ok_or_else(|| EngineError::Other("no active layer".into()))?; - let is_group = doc.layer(id).is_some_and(Layer::is_group); - let group = group_locks(doc, id); - // Photoshop turns the Background into a normal layer before transforming it. - crate::extra_cmds::background_to_layer(doc, id); - let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; - let layer_sel = if is_group { None } else { sel.as_ref() }; - check_layer_budget(layer_sel, l, h)?; - let taken = if h.is_identity() { Vec::new() } else { crate::smart_cmds::take_caches(std::slice::from_mut(l)) }; - apply_transform(layer_sel, group, l, h, affine, interp, ctl)?; - if !h.is_identity() { - // Type layers re-render from their new transform. - let snapshot = doc.clone(); - if let Some(l) = doc.layer_mut(id) { - refresh_text(&snapshot, l); - } - crate::smart_cmds::restore_unrendered(doc, taken, |c| warp_surface(c, c.content_bounds(), h, interp))?; - // The selection outline moves with the pixels. - if let Some(sel) = &doc.selection { - doc.selection = Some(warp_gray(sel, h, Interp::Bilinear)?).filter(|s| !s.content_bounds().is_empty()); - } - } - Ok(()) -} - -pub fn specs() -> Vec { - vec![CommandSpec { - id: "edit.transform", - label: "Free Transform", - menu: &[], - shortcut: None, - params: r##"{"layer":id?,"rect":[x0,y0,x1,y1]? (source frame; default = layer content ∩ selection),"quad":[[x,y]×4]? (where the frame's corners go, clockwise from top-left),"matrix":[a,b,c,d,e,f]? (affine alternative),"scaleX":%?,"scaleY":%?,"rotate":deg?,"dx":px?,"dy":px? (relative alternative: scale and rotate about the frame's centre, then move, as a Photoshop action records a Free Transform),"interpolation":"bicubic|bilinear|nearest|bicubicSharper|bicubicSmoother|bicubicAutomatic"="bicubic" (Photoshop's bicubic variants render as Bicubic),"target":"pixels"|"mask"|"quickMask"|{"channel":i}=Channels panel target (an unlinked mask, an alpha channel or the Quick Mask transforms alone; a linked mask moves with its layer)}"##, - enabled: has_layer, - journal: true, - run: transform, - }] -} - -#[cfg(test)] -mod tests { - use super::*; - - fn session() -> Session { - session_depth(8) - } - - fn session_depth(depth: u32) -> Session { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 100, "height": 100, "depth": depth})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.edit("paint", |doc, active| { - let l = doc.layer_mut(active.unwrap()).unwrap(); - l.surface_mut().unwrap().fill_rect(Rect::new(10, 10, 30, 20), &[1.0, 0.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - s - } - - /// The content bounds of the active layer's pixels. - fn active_bounds(s: &Session) -> Rect { - let st = s.active().unwrap(); - st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds() - } - - // ---- Memory budget (#3773, #7807). Tests run with a 20 MB budget (2²⁰ px of 32-bit CMYK with - // alpha), so nothing here comes near the real one. ---- - - /// Memory Usage's default, in bytes. - const DEFAULT_BUDGET: u64 = (crate::prefs::DEFAULT_MEMORY_USAGE_MB as u64) << 20; - - /// Scales of 10⁷ and past are refused by the real budget too, whatever the axis or sign. - #[test] - fn huge_transform_scales_exceed_the_production_budget_before_clipping() { - let src = Rect::new(0, 0, 24, 16); - for scale in [1e7, 1e28, 1e306] { - for (sx, sy) in [(scale, 1.0), (1.0, scale), (-scale, 1.0)] { - let h = Homography([sx, 0.0, 0.0, 0.0, sy, 0.0, 0.0, 0.0, 1.0]); - assert!(check_budget_with_limit(src, &h, "layer", PixelFormat::RGBA8, DEFAULT_BUDGET).is_err(), "{sx} x {sy} must be refused"); - } - } - } - - /// A 240000 px wide stretch, placed far from the canvas but within the warp's reach, fits. - #[test] - fn an_ordinary_transform_remains_within_the_production_budget() { - let src = Rect::new(0, 0, 24, 16); - let h = Homography([10_000.0, 0.0, 800_000.0, 0.0, 1.0, -900_000.0, 0.0, 0.0, 1.0]); - assert!(check_budget_with_limit(src, &h, "layer", PixelFormat::RGBA8, DEFAULT_BUDGET).is_ok()); - } - - /// The warp places pixels only within ±2²⁰ px ([`WARP_REACH`]): a result that fits Memory - /// Usage but would reach past it, by its size or by where it lands, is refused, not clipped. - #[test] - fn a_result_past_the_warps_reach_is_refused_not_clipped() { - let src = Rect::new(0, 0, 24, 16); - let check = |h: [f64; 9]| check_budget_with_limit(src, &Homography(h), "layer", PixelFormat::RGBA8, DEFAULT_BUDGET); - // 2000016 x 18 px, 138 MB of 8-bit RGBA: from x = 0 it would be cut at 2²⁰; centred it fits. - let err = check([83_334.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]).unwrap_err().to_string(); - assert!(err.contains("would reach past ±1048576 px") && err.ends_with("the document was not changed"), "{err}"); - assert!(check([83_334.0, 0.0, -1_000_000.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]).is_ok()); - // A small layer moved past the reach, either way on either axis. - for (dx, dy) in [(1_100_000.0, 0.0), (-1_100_000.0, 0.0), (0.0, 1_100_000.0), (0.0, -1_100_000.0)] { - assert!(check([1.0, 0.0, dx, 0.0, 1.0, dy, 0.0, 0.0, 1.0]).is_err(), "{dx}, {dy}"); - } - // Through the command: nothing moves, nothing is lost. - let mut s = session(); - let st = s.active().unwrap(); - let (before, steps) = (st.doc.clone(), st.history.past_len()); - let err = s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 2_000_000, 0]})).unwrap_err().to_string(); - assert!(err.contains("the transformed layer \"Layer 1\" would reach past ±1048576 px"), "{err}"); - let st = s.active().unwrap(); - assert!(st.doc == before && st.history.past_len() == steps, "the document is untouched"); - } - - /// #7807: the stitched layer's 90 % and 15°, a 37708 x 35259 px result that the old 2³⁰ px limit - /// refused, fits the default Memory Usage at 8 bits (5072 MB); at 16 bits it needs Memory Usage - /// raised, and the message says so. - #[test] - fn a_gigapixel_layer_transforms_within_memory_usage() { - let src = Rect::new(0, 0, 35_020, 31_171); - let r = [0.0, 0.0, 35_020.0, 31_171.0]; - let h = relative_matrix(&json!({"scaleX": 90, "scaleY": 90, "rotate": 15}), r).unwrap().unwrap(); - assert_eq!(warp_output_size(src, &h), Some((37_708, 35_259)), "the report's result, past the old limit"); - assert!(check_budget_with_limit(src, &h, "layer \"Layer 1\"", PixelFormat::RGBA8, DEFAULT_BUDGET).is_ok()); - let err = check_budget_with_limit(src, &h, "layer \"Layer 1\"", PixelFormat::RGBA16, DEFAULT_BUDGET).unwrap_err().to_string(); - assert!(err.contains("(10144 MB), more than the 8192 MB Memory Usage allows (Preferences › Performance)"), "{err}"); - assert!(check_budget_with_limit(src, &h, "layer", PixelFormat::RGBA16, 2 * DEFAULT_BUDGET).is_ok()); - // A format without alpha is priced as the warp makes it, with alpha. - let rgb8 = PixelFormat::new(PixelFormat::RGBA8.mode, PixelFormat::RGBA8.sample, false); - assert!(check_budget_with_limit(src, &h, "layer", rgb8, 5071 << 20).is_err()); - } - - /// A 16 x 16 document whose active layer is a 1 x 8 column at x = 10. - fn column() -> Session { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 16, "height": 16})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.edit("paint", |doc, active| { - doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(10, 2, 11, 10), &[1.0, 0.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - s - } - - /// Stretch x by `k` about x = 10 (the column's left edge). - fn stretch(k: f64) -> Value { - json!({"matrix": [k, 0, 0, 1, -10.0 * k, 0], "interpolation": "nearest"}) - } - - /// A stretch past the budget is refused with the limit named, and the document, its revision - /// and History stay as they were; within the budget the same stretch applies unclipped. - #[test] - fn a_scale_past_the_pixel_budget_is_refused_and_changes_nothing() { - let mut s = column(); - let st = s.active().unwrap(); - let (before, revision, steps) = (st.doc.clone(), st.revision, st.history.past_len()); - // 1000000 x 10 px of 8-bit RGBA output: about twice the test budget. - let err = s.execute("edit.transform", stretch(1e6)).unwrap_err().to_string(); - assert!(err.starts_with("too large to transform: the transformed layer \"Layer 1\""), "{err}"); - assert!( - err.contains("would be 1000002 x 10 px (39 MB), more than the 20 MB Memory Usage allows") && err.ends_with("the document was not changed"), - "{err}" - ); - // Nothing was allocated, so nothing ran short (#7807). - assert!(!err.contains("not enough memory"), "{err}"); - let st = s.active().unwrap(); - assert!(st.doc == before, "the document is untouched"); - assert_eq!((st.revision, st.history.past_len()), (revision, steps)); - // Within the budget the same stretch still works, nothing clipped. - s.execute("edit.transform", stretch(1e4)).unwrap(); - assert_eq!(active_bounds(&s), Rect::new(0, 2, 10_000, 10)); - } - - #[test] - fn a_group_with_one_layer_past_the_budget_is_not_half_transformed() { - let mut s = column(); - let wide = s.active().unwrap().active_layer.unwrap(); - // Over the column: a 1 px dot, which fits the budget stretched by the same amount. - s.execute("layer.new.layer", json!({})).unwrap(); - let dot = s.active().unwrap().active_layer.unwrap(); - s.edit("paint", |doc, _| { - doc.layer_mut(dot).unwrap().surface_mut().unwrap().fill_rect(Rect::new(10, 12, 11, 13), &[0.0, 1.0, 0.0, 1.0]); - // Widen the column to 8 px (x 2..10), so it alone needs 800002 x 10 px (31 MB). - doc.layer_mut(wide).unwrap().surface_mut().unwrap().fill_rect(Rect::new(2, 2, 10, 10), &[1.0, 0.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - s.execute("layer.select", json!({"layer": wide.0})).unwrap(); - s.execute("layer.select", json!({"layer": dot.0, "mode": "add"})).unwrap(); - let group = LayerId(s.execute("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap()); - let st = s.active().unwrap(); - assert!(matches!(&st.doc.layer(group).unwrap().content, LayerContent::Group(g) if g.children.len() == 2)); - let (before, revision) = (st.doc.clone(), st.revision); - let k = 1e5; - assert!(s.execute("edit.transform", json!({"layer": group.0, "matrix": [k, 0, 0, 1, -10.0 * k, 0]})).is_err()); - let st = s.active().unwrap(); - assert!(st.doc == before && st.revision == revision, "nothing changed"); - // The layer-level check runs before any child is warped, so even the layer itself - // (not just the edit's copy of the document) is left as it was. - let mut l = st.doc.layer(group).unwrap().clone(); - let h = Homography([k, 0.0, -10.0 * k, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]); - assert!(transform_layer(None, Locks::default(), &mut l, &h, None, Interp::Nearest).is_err()); - assert!(&l == st.doc.layer(group).unwrap(), "no child was transformed"); - } - - /// Only the result's size is priced: a small layer moved 900000 px away (within the warp's - /// reach) and back keeps every pixel. - #[test] - fn moving_a_small_layer_far_off_the_canvas_is_within_budget() { - let mut s = session(); - s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 900_000, -900_000]})).unwrap(); - assert_eq!(active_bounds(&s), Rect::new(900_010, -899_990, 900_030, -899_980)); - s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, -900_000, 900_000]})).unwrap(); - assert_eq!(active_bounds(&s), Rect::new(10, 10, 30, 20), "and back, every pixel kept"); - } - - /// Each priced at its own format, as the warp makes it: an 8-bit outline, mask or channel with - /// alpha is 2 bytes a pixel, so a canvas-high column of it stretched 10⁶ times (34 MB) is over - /// the test budget. - #[test] - fn selections_masks_and_channels_have_the_same_budget() { - // The selection outline of a layer transform. - let mut s = column(); - s.execute("select.rect", json!({"x": 10, "y": 0, "width": 1, "height": 16})).unwrap(); - let before = s.active().unwrap().doc.clone(); - let err = s.execute("edit.transform", stretch(1e6)).unwrap_err().to_string(); - assert!(err.contains("transformed selection would be"), "{err}"); - // Transform Selection. - let err = s.execute("select.transformSelection", stretch(1e6)).unwrap_err().to_string(); - assert!(err.contains("transformed selection would be"), "{err}"); - assert!(s.active().unwrap().doc == before); - // A targeted alpha channel. - let mut s = column(); - s.execute("channel.new", json!({})).unwrap(); - s.edit("paint channel", |doc, _| { - doc.channels[0].surface.fill_rect(Rect::new(10, 0, 11, 16), &[1.0]); - Ok(()) - }) - .unwrap(); - let before = s.active().unwrap().doc.clone(); - let mut p = stretch(1e6); - p["target"] = json!({"channel": 0}); - let err = s.execute("edit.transform", p).unwrap_err().to_string(); - assert!(err.contains("transformed mask or channel would be"), "{err}"); - assert!(s.active().unwrap().doc == before); - } - - #[test] - fn scale_via_quad_and_undo() { - let mut s = session(); - s.execute("edit.transform", json!({"quad": [[10, 10], [50, 10], [50, 30], [10, 30]]})).unwrap(); - let b = active_bounds(&s); - assert!(b.width().abs_diff(40) <= 2 && b.height().abs_diff(20) <= 2, "{b:?}"); - s.undo(); - assert_eq!(active_bounds(&s), Rect::new(10, 10, 30, 20)); - } - - #[test] - fn affine_matrix_and_perspective() { - let mut s = session(); - // Translate by (40, 50). - s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 40, 50]})).unwrap(); - assert_eq!(active_bounds(&s), Rect::new(50, 60, 70, 70)); - // Perspective: top edge narrower than the bottom. - s.execute("edit.transform", json!({"quad": [[55, 60], [65, 60], [75, 70], [45, 70]]})).unwrap(); - let b = active_bounds(&s); - assert!(b.x0 <= 46 && b.x1 >= 74, "{b:?}"); - assert!(s.execute("edit.transform", json!({"quad": [[0, 0], [0, 0], [0, 0], [0, 0]]})).is_err()); - } - - #[test] - fn background_becomes_layer_0() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 40, "height": 40})).unwrap(); - s.execute("edit.transform", json!({"quad": [[0, 0], [20, 0], [20, 20], [0, 20]]})).unwrap(); - let st = s.active().unwrap(); - let l = &st.doc.layers[0]; - assert_eq!(l.name, "Layer 0"); - assert!(l.surface().unwrap().format().alpha); - assert_eq!(l.surface().unwrap().pixel(30, 30)[3], 0.0, "revealed area is transparent"); - } - - /// `locked_for_transform` (what Free Transform asks before its box opens, #2585) agrees with - /// what `edit.transform` refuses at commit: a position lock, its own or a group's; never the - /// Background's (it becomes Layer 0). - #[test] - fn locked_for_transform_matches_the_commit() { - let quad = json!({"quad": [[10, 10], [50, 10], [50, 30], [10, 30]]}); - let lock = |s: &mut Session, id: LayerId, on: bool| { - s.edit("lock", |doc, _| { - doc.layer_mut(id).unwrap().locks.position = on; - Ok(()) - }) - .unwrap(); - }; - let mut s = session(); - let layer = s.active().unwrap().active_layer.unwrap(); - lock(&mut s, layer, true); - assert!(locked_for_transform(&s.active().unwrap().doc, layer)); - assert!(s.execute("edit.transform", quad.clone()).is_err()); - lock(&mut s, layer, false); - let group = LayerId(s.execute("layer.groupLayers", json!({"layer": layer.0})).unwrap()["layer"].as_u64().unwrap()); - lock(&mut s, group, true); - s.execute("layer.select", json!({"layer": layer.0})).unwrap(); - assert!(locked_for_transform(&s.active().unwrap().doc, layer), "the group's lock reaches the layer"); - assert!(s.execute("edit.transform", quad.clone()).is_err()); - let bg = s.active().unwrap().doc.layers[0].id; - assert!(!locked_for_transform(&s.active().unwrap().doc, bg), "the Background transforms"); - } - - #[test] - fn with_selection_only_selected_pixels_move() { - let mut s = session(); - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); - s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 0, 50]})).unwrap(); - let st = s.active().unwrap(); - let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); - assert_eq!(surf.pixel(15, 15)[3], 0.0, "lifted area is cleared"); - assert_eq!(surf.pixel(25, 15)[3], 1.0, "unselected part stays"); - assert_eq!(surf.pixel(15, 65)[3], 1.0, "moved pixels land"); - let sel = st.doc.selection.as_ref().unwrap().content_bounds(); - assert_eq!((sel.y0, sel.y1), (60, 70), "selection moves too"); - } - - #[test] - fn with_selection_bounds_drop_the_vacated_area() { - // #1097: moving every pixel through a selection left transparent but coloured pixels - // behind, so the layer bounds were the union of the old and new positions. - let mut s = session(); - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 20, "height": 10})).unwrap(); - s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 50, 0]})).unwrap(); - assert_eq!(active_bounds(&s), Rect::new(60, 10, 80, 20)); - } - - #[test] - fn type_layers_transform_as_vectors() { - let mut s = session(); - let r = s.execute("type.create", json!({"x": 10, "y": 50, "text": "Hi", "size": 20})).unwrap(); - let id = r["layer"].as_u64().unwrap(); - let w0 = active_bounds(&s).width(); - s.execute("edit.transform", json!({"layer": id, "matrix": [2, 0, 0, 2, -10, -50]})).unwrap(); - let w1 = active_bounds(&s).width(); - assert!(w1 as f32 > w0 as f32 * 1.8, "{w0} → {w1}"); - let st = s.active().unwrap(); - let LayerContent::Text(t) = &st.doc.layer(LayerId(id)).unwrap().content else { panic!() }; - assert!((t.transform.m[0] - 2.0).abs() < 1e-9); - // Perspective on type is refused, like Photoshop. - assert!(s.execute("edit.transform", json!({"layer": id, "quad": [[0, 0], [10, 0], [12, 10], [-2, 10]]})).is_err()); - } - - #[test] - fn shapes_move_and_transform_as_vectors() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); - s.execute("shape.create", json!({"kind": "rect", "rect": [10, 10, 40, 20], "fill": "#ff0000"})).unwrap(); - s.execute("layer.translate", json!({"dx": 30, "dy": 5})).unwrap(); - assert_eq!(active_bounds(&s), Rect::new(40, 15, 80, 35)); - s.execute("edit.transform", json!({"matrix": [2, 0, 0, 2, -40, -15]})).unwrap(); - assert_eq!(active_bounds(&s), Rect::new(40, 15, 120, 55)); - // Distort maps the path and keeps a live shape (#3009): the rectangle's corners go to the quad. - let quad = [[40.0, 15.0], [120.0, 15.0], [130.0, 55.0], [30.0, 55.0]]; - s.execute("edit.transform", json!({ "quad": quad })).unwrap(); - let st = s.active().unwrap(); - let LayerContent::Shape(sh) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!("still a shape layer") }; - let mut anchors: Vec<[f64; 2]> = sh.path.subpaths[0].knots.iter().map(|k| [k.anchor.x, k.anchor.y]).collect(); - let mut want = quad.to_vec(); - anchors.sort_by(|a, b| a.partial_cmp(b).unwrap()); - want.sort_by(|a, b| a.partial_cmp(b).unwrap()); - assert!(anchors.iter().zip(&want).all(|(a, b)| (a[0] - b[0]).abs() < 1e-6 && (a[1] - b[1]).abs() < 1e-6), "{anchors:?}"); - assert!(sh.live.is_none(), "the live rectangle is now a path"); - assert_eq!(active_bounds(&s), Rect::new(30, 15, 130, 55)); - // Warp bends the path too: the arc adds anchors along the curved edges. - s.execute("edit.transform.warp", json!({"style": "arc", "bend": 50})).unwrap(); - let st = s.active().unwrap(); - let LayerContent::Shape(sh) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!("still a shape layer") }; - assert!(sh.path.subpaths[0].knots.len() > 4, "{}", sh.path.subpaths[0].knots.len()); - assert!(!active_bounds(&s).is_empty()); - } - - /// A gradient fill layer whose mask (a selection when it was made) frames the gradient over - /// 10..40, with the cached render a PSD import gives it: exactly the pixels the fill renders. - fn cached_gradient_fill() -> Session { - let mut s = session(); - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap(); - s.execute("layer.newFillLayer.gradient", json!({"from": "#ff0000", "to": "#0000ff", "angle": 0})).unwrap(); - s.execute("select.deselect", json!({})).unwrap(); - s.edit("cache", |doc, active| { - let (fmt, canvas) = (doc.pixel_format(), doc.bounds()); - let l = doc.layer_mut(active.unwrap()).unwrap(); - let LayerContent::Fill(f) = &l.content else { panic!("a fill layer") }; - let buf = photocraft_compose::render_fill_content(l, f, canvas, &[]); - let mut surface = Surface::new(fmt); - let vals: Vec = buf.px.iter().flat_map(|p| photocraft_raster::from_rgba(&fmt, *p)).collect(); - surface.write_region(canvas, &vals); - l.fill_cache = Some(photocraft_doc::FillCache { fill: f.clone(), surface }); - Ok(()) - }) - .unwrap(); - s - } - - /// How far the composite is from the composite with the fill re-rendered from its model - /// (cache dropped): the largest channel difference. - fn off_from_fresh(s: &Session) -> f32 { - let st = s.active().unwrap(); - let mut fresh: Document = (*st.doc).clone(); - fresh.layer_mut(st.active_layer.unwrap()).unwrap().fill_cache = None; - let (a, b) = (photocraft_compose::render(&st.doc, st.doc.bounds()).px, photocraft_compose::render(&fresh, fresh.bounds()).px); - a.iter().zip(&b).flat_map(|(p, q)| p.iter().zip(q).map(|(x, y)| (x - y).abs())).fold(0.0, f32::max) - } - - #[test] - fn transforming_a_fill_layer_drops_its_stale_cached_render() { - let mut s = cached_gradient_fill(); - let off = off_from_fresh(&s); - assert!(off < 0.01, "the cache is the fill's own render: {off}"); - // The mask (and so the gradient's frame) moves 50 px right and doubles in height. - s.execute("edit.transform", json!({"matrix": [1, 0, 0, 2, 50, 0]})).unwrap(); - let off = off_from_fresh(&s); - assert!(off < 0.01, "the composite shows the fill laid out in its new frame, not the old render: {off}"); - } - - #[test] - fn warping_a_fill_layer_drops_its_stale_cached_render() { - let mut s = cached_gradient_fill(); - s.execute("edit.transform.warp", json!({"style": "arc", "bend": 50})).unwrap(); - let off = off_from_fresh(&s); - assert!(off < 0.01, "the composite shows the fill laid out in its new frame, not the old render: {off}"); - } - - #[test] - fn type_moves_with_the_move_command() { - let mut s = session(); - s.execute("type.create", json!({"x": 10, "y": 50, "text": "Hi", "size": 20})).unwrap(); - let b0 = active_bounds(&s); - s.execute("layer.translate", json!({"dx": 20, "dy": 10})).unwrap(); - let b1 = active_bounds(&s); - assert_eq!((b1.x0 - b0.x0, b1.y0 - b0.y0), (20, 10)); - } - - // ---- Layer masks and targets (#205) ---- - - /// `session()` plus a reveal-all mask with `hide` painted black (linked unless `linked` is false). - fn masked(hide: &[Rect], linked: bool) -> Session { - masked_depth(hide, linked, 8) - } - - fn masked_depth(hide: &[Rect], linked: bool, depth: u32) -> Session { - let mut s = session_depth(depth); - s.execute("layer.layerMask.revealAll", json!({})).unwrap(); - s.edit("mask", |doc, active| { - let m = doc.layer_mut(active.unwrap()).unwrap().mask.as_mut().unwrap(); - for r in hide { - m.surface.fill_rect(*r, &[0.0]); - } - m.linked = linked; - Ok(()) - }) - .unwrap(); - s - } - - fn mask_at(s: &Session, x: i32, y: i32) -> f32 { - let st = s.active().unwrap(); - st.doc.layer(st.active_layer.unwrap()).unwrap().mask.as_ref().unwrap().surface.sample_channel(x, y, 0) - } - - fn alpha_at(s: &Session, x: i32, y: i32) -> f32 { - let st = s.active().unwrap(); - st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().pixel(x, y)[3] - } - - #[test] - fn linked_raster_mask_moves_with_the_pixels() { - let mut s = masked(&[Rect::new(10, 10, 20, 20)], true); - s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 40, 50]})).unwrap(); - assert_eq!(active_bounds(&s), Rect::new(50, 60, 70, 70)); - assert!(mask_at(&s, 55, 65) < 0.01, "the hidden half moved with the pixels"); - assert!(mask_at(&s, 65, 65) > 0.99); - assert!(mask_at(&s, 15, 15) > 0.99, "nothing hidden left behind"); - } - - #[test] - fn linked_mask_with_a_selection_moves_only_the_selected_region() { - // The selection covers the left half of the red rect; the mask hides its left quarter - // (selected) and its right quarter (not selected). - let mut s = masked(&[Rect::new(10, 10, 15, 20), Rect::new(25, 10, 30, 20)], true); - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); - s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 0, 50]})).unwrap(); - // Moved pixels and their mask line up. - assert_eq!(alpha_at(&s, 12, 65), 1.0); - assert!(mask_at(&s, 12, 65) < 0.01, "selected hidden quarter moved"); - assert!(mask_at(&s, 17, 65) > 0.99, "selected visible quarter moved"); - // The vacated area reads as revealed (default), with transparent pixels. - assert_eq!(alpha_at(&s, 12, 15), 0.0); - assert!(mask_at(&s, 12, 15) > 0.99); - // The unselected part of the mask stays, aligned with the unselected pixels. - assert_eq!(alpha_at(&s, 27, 15), 1.0); - assert!(mask_at(&s, 27, 15) < 0.01, "unselected mask stays put"); - assert!(mask_at(&s, 27, 65) > 0.99, "and isn't copied along"); - // Every pixel's mask value is where it was relative to the pixel. - for (x, y) in [(11, 61), (14, 69), (15, 61), (19, 69)] { - let want = if x < 15 { 0.0 } else { 1.0 }; - assert!((mask_at(&s, x, y) - want).abs() < 0.01, "({x},{y})"); - } - } - - #[test] - fn unlinked_mask_stays_put() { - let mut s = masked(&[Rect::new(10, 10, 20, 20)], false); - s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 40, 50]})).unwrap(); - assert_eq!(active_bounds(&s), Rect::new(50, 60, 70, 70)); - assert!(mask_at(&s, 15, 15) < 0.01); - assert!(mask_at(&s, 55, 65) > 0.99); - // With a selection too. - let mut s = masked(&[Rect::new(10, 10, 20, 20)], false); - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); - s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 0, 50]})).unwrap(); - assert!(mask_at(&s, 15, 15) < 0.01 && mask_at(&s, 15, 65) > 0.99); - } - - #[test] - fn targeted_unlinked_mask_transforms_alone() { - let mut s = masked(&[Rect::new(10, 10, 20, 20)], false); - s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 40, 50], "target": "mask"})).unwrap(); - assert_eq!(active_bounds(&s), Rect::new(10, 10, 30, 20), "pixels untouched"); - assert!(mask_at(&s, 55, 65) < 0.01, "mask moved"); - assert!(mask_at(&s, 15, 15) > 0.99, "vacated area reads as the default"); - s.undo(); - assert!(mask_at(&s, 15, 15) < 0.01, "one undo step"); - // With a selection, only its part of the mask. - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 5, "height": 10})).unwrap(); - s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 0, 50], "target": "mask"})).unwrap(); - assert!(mask_at(&s, 12, 65) < 0.01 && mask_at(&s, 12, 15) > 0.99); - assert!(mask_at(&s, 17, 15) < 0.01, "unselected mask stays"); - assert_eq!(active_bounds(&s), Rect::new(10, 10, 30, 20), "pixels untouched"); - } - - #[test] - fn targeted_linked_mask_moves_with_its_layer() { - // Photoshop: a linked mask can't move without its layer. - let mut s = masked(&[Rect::new(10, 10, 20, 20)], true); - s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 40, 50], "target": "mask"})).unwrap(); - assert_eq!(active_bounds(&s), Rect::new(50, 60, 70, 70)); - assert!(mask_at(&s, 55, 65) < 0.01); - } - - #[test] - fn targeted_alpha_channel_transforms_alone() { - let mut s = session(); - s.execute("channel.new", json!({})).unwrap(); - s.edit("paint channel", |doc, _| { - doc.channels[0].surface.fill_rect(Rect::new(10, 10, 20, 20), &[1.0]); - Ok(()) - }) - .unwrap(); - s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 40, 50], "target": {"channel": 0}})).unwrap(); - let st = s.active().unwrap(); - let ch = &st.doc.channels[0].surface; - assert!(ch.sample_channel(55, 65, 0) > 0.99 && ch.sample_channel(15, 15, 0) < 0.01); - assert_eq!(active_bounds(&s), Rect::new(10, 10, 30, 20), "layer untouched"); - } - - /// The Channels panel targets an alpha channel: Edit › Transform › Flip Horizontal and a - /// 50% `edit.transform` (no `target` param) work on the channel, not the layer (BUG-207-4). - #[test] - fn transforms_follow_the_targeted_alpha_channel() { - let mut s = session(); - s.execute("channel.new", json!({})).unwrap(); - s.edit("paint channel", |doc, _| { - let ch = &mut doc.channels[0].surface; - ch.fill_rect(Rect::new(10, 10, 20, 20), &[1.0]); - ch.fill_rect(Rect::new(10, 10, 12, 20), &[0.5]); - Ok(()) - }) - .unwrap(); - s.execute("channel.target", json!({"channel": 0})).unwrap(); - let layer = |s: &Session| crate::active_layer_of(s).unwrap().surface().unwrap().read_region(Rect::new(0, 0, 100, 100)); - let (pixels, past) = (layer(&s), s.active().unwrap().history.past_len()); - s.execute("edit.transform.flipHorizontal", json!({})).unwrap(); - // 8-bit channel: 0.5 is stored as 128/255. - let ch = |s: &Session, x, y| (s.active().unwrap().doc.channels[0].surface.sample_channel(x, y, 0) * 10.0).round() / 10.0; - assert_eq!((ch(&s, 19, 15), ch(&s, 10, 15)), (0.5, 1.0), "the channel flips within its frame"); - assert!(layer(&s) == pixels, "the layer is untouched"); - assert_eq!(s.active().unwrap().history.past_len(), past + 1, "one undo step"); - s.execute("edit.transform", json!({"matrix": [0.5, 0, 0, 0.5, 0, 0], "interpolation": "nearest"})).unwrap(); - assert_eq!((ch(&s, 7, 7), ch(&s, 15, 15)), (1.0, 0.0), "the channel scales to 50%"); - assert!(layer(&s) == pixels, "the layer is untouched"); - s.undo(); - s.undo(); - assert_eq!((ch(&s, 10, 15), ch(&s, 19, 15)), (0.5, 1.0)); - } - - #[test] - fn transform_targets_fail_gracefully() { - let mut s = session(); - let m = json!([1, 0, 0, 1, 5, 5]); - assert!(s.execute("edit.transform", json!({"matrix": m, "target": "mask"})).is_err(), "no mask"); - assert!(s.execute("edit.transform", json!({"matrix": m, "target": {"channel": 9}})).is_err()); - assert!(s.execute("edit.transform", json!({"matrix": m, "target": "quickMask"})).is_err()); - // Unknown target shapes fall back to the pixels. - s.execute("edit.transform", json!({"matrix": m, "target": 7})).unwrap(); - s.execute("edit.transform", json!({"matrix": m, "target": {"channel": "x"}})).unwrap(); - // Selections that miss the mask entirely transform nothing, without panicking. - let mut s = masked(&[Rect::new(10, 10, 20, 20)], false); - s.execute("select.rect", json!({"x": 80, "y": 80, "width": 5, "height": 5})).unwrap(); - let _ = s.execute("edit.transform", json!({"matrix": [1e9, 0, 0, 1e9, 0, 0], "target": "mask"})); - let _ = s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 1e12, 0], "target": "mask"})); - } - - #[test] - fn split_gray_selected_rejects_non_gray() { - let s = Surface::new(PixelFormat::RGBA8); - let mut sel = Surface::new(PixelFormat::GRAY8); - sel.fill_rect(Rect::new(0, 0, 4, 4), &[1.0]); - assert!(matches!(split_gray_selected(&s, &sel), Ok(None))); - } - - /// #2630: type can't be partly transformed, so a selection doesn't narrow the frame: Free - /// Transform (and the frame-based presets) act on the whole type layer. - #[test] - fn a_selection_does_not_narrow_a_type_layers_frame() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 200, "height": 120})).unwrap(); - s.execute("type.create", json!({"x": 20, "y": 60, "text": "Hello", "size": 36})).unwrap(); - let whole = active_bounds(&s); - s.execute("select.rect", json!({"x": whole.x0, "y": whole.y0, "width": whole.width() / 2, "height": whole.height()})).unwrap(); - let st = s.active().unwrap(); - let l = st.doc.layer(st.active_layer.unwrap()).unwrap(); - assert_eq!(transform_bounds(&st.doc, l), whole, "the frame is the whole type layer"); - // Corners of the frame moved 10 px right: a pure translation of the whole text. - let q = [[whole.x0 + 10, whole.y0], [whole.x1 + 10, whole.y0], [whole.x1 + 10, whole.y1], [whole.x0 + 10, whole.y1]]; - s.execute("edit.transform", json!({"quad": q})).unwrap(); - let moved = active_bounds(&s); - assert!(moved.x0.abs_diff(whole.x0 + 10) <= 1 && moved.width().abs_diff(whole.width()) <= 1, "{whole:?} -> {moved:?}"); - // Rotate 180° turns it about its own centre, not the selection's. - s.execute("edit.transform.rotate180", json!({})).unwrap(); - let turned = active_bounds(&s); - assert!(turned.x0.abs_diff(moved.x0) <= 2 && turned.x1.abs_diff(moved.x1) <= 2, "{moved:?} -> {turned:?}"); - // A pixel layer still frames only the selected pixels. - let mut s = session(); - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 5, "height": 10})).unwrap(); - let st = s.active().unwrap(); - assert_eq!(transform_bounds(&st.doc, st.doc.layer(st.active_layer.unwrap()).unwrap()), Rect::new(10, 10, 15, 20)); - } - - /// #5297: the box Free Transform opens with a selection is the selection's own rectangle, - /// not the part of it the layer fills; type still moves whole, and a selection that holds none - /// of the layer leaves nothing to transform. - #[test] - fn the_frame_is_the_selections_own_bounds() { - let mut s = session(); - let frame = |s: &Session| { - let st = s.active().unwrap(); - let l = st.doc.layer(st.active_layer.unwrap()).unwrap(); - (transform_frame(&st.doc, l), transform_bounds(&st.doc, l)) - }; - let content = Rect::new(10, 10, 30, 20); - assert_eq!(frame(&s), (content, content), "no selection: the content"); - s.execute("select.rect", json!({"x": 5, "y": 5, "width": 15, "height": 40})).unwrap(); - assert_eq!(frame(&s), (Rect::new(5, 5, 20, 45), Rect::new(10, 10, 20, 20))); - s.execute("select.rect", json!({"x": 60, "y": 60, "width": 10, "height": 10})).unwrap(); - assert!(frame(&s).0.is_empty(), "nothing of the layer is selected"); - - let mut s = Session::new(); - s.execute("file.new", json!({"width": 200, "height": 120})).unwrap(); - s.execute("type.create", json!({"x": 20, "y": 60, "text": "Hello", "size": 36})).unwrap(); - let whole = active_bounds(&s); - s.execute("select.rect", json!({"x": whole.x0, "y": whole.y0, "width": whole.width() / 2, "height": whole.height()})).unwrap(); - assert_eq!(frame(&s), (whole, whole), "type moves whole"); - } - - #[test] - fn group_transform_ignores_selections_inside_its_children() { - group_transform_with_selection(Rect::new(10, 10, 15, 15)); - } - - #[test] - fn group_transform_ignores_selections_outside_its_children() { - group_transform_with_selection(Rect::new(70, 70, 80, 80)); - } - - #[test] - fn group_transform_presets_rotate_about_the_whole_group() { - for depth in [8, 16, 32] { - for x in [10, 70] { - let mut s = masked_depth(&[Rect::new(10, 10, 15, 20)], true, depth); - let child = s.active().unwrap().active_layer.unwrap(); - s.execute("layer.groupLayers", json!({})).unwrap(); - s.execute("select.rect", json!({"x": x, "y": 10, "width": 5, "height": 5})).unwrap(); - s.execute("edit.transform.rotate180", json!({})).unwrap(); - let layer = s.active().unwrap().doc.layer(child).unwrap(); - assert_eq!(layer.surface().unwrap().content_bounds(), Rect::new(10, 10, 30, 20), "rotate about the group's centre, not the selection's"); - let mask = &layer.mask.as_ref().unwrap().surface; - assert_eq!(mask.sample_channel(27, 15, 0), 0.0); - assert_eq!(mask.sample_channel(12, 15, 0), 1.0); - } - } - } - - fn group_transform_with_selection(selection: Rect) { - for depth in [8, 16, 32] { - for nested in [false, true] { - let mut s = masked_depth(&[Rect::new(10, 10, 15, 20)], true, depth); - let child = s.active().unwrap().active_layer.unwrap(); - s.execute("layer.groupLayers", json!({})).unwrap(); - if nested { - s.execute("layer.groupLayers", json!({})).unwrap(); - } - s.execute("select.rect", json!({"x": selection.x0, "y": selection.y0, "width": selection.width(), "height": selection.height()})).unwrap(); - let steps = s.active().unwrap().history.entries().len(); - let result = s.execute("edit.transform", json!({"quad": [[10, 10], [50, 10], [50, 30], [10, 30]], "interpolation": "nearest"})).unwrap(); - assert_eq!(result["rect"], json!([10.0, 10.0, 30.0, 20.0]), "frame must include the whole group (nested={nested})"); - let st = s.active().unwrap(); - let layer = st.doc.layer(child).unwrap(); - assert_eq!(layer.surface().unwrap().content_bounds(), Rect::new(10, 10, 50, 30)); - let mask = &layer.mask.as_ref().unwrap().surface; - assert_eq!(mask.sample_channel(19, 20, 0), 0.0, "the linked mask scales with its complete layer"); - assert_eq!(mask.sample_channel(21, 20, 0), 1.0); - assert_eq!(st.history.entries().len(), steps + 1); - assert!(s.undo()); - let st = s.active().unwrap(); - let layer = st.doc.layer(child).unwrap(); - assert_eq!(layer.surface().unwrap().content_bounds(), Rect::new(10, 10, 30, 20)); - assert_eq!(layer.mask.as_ref().unwrap().surface.sample_channel(19, 15, 0), 1.0); - assert_eq!(st.doc.selection.as_ref().unwrap().content_bounds(), selection); - assert!(s.redo()); - assert_eq!(s.active().unwrap().doc.layer(child).unwrap().surface().unwrap().content_bounds(), Rect::new(10, 10, 50, 30)); - } - } - } - - #[test] - fn feathered_selection_identity_transform_preserves_pixels() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 16, "height": 16, "background": "transparent"})).unwrap(); - s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); - s.execute("select.rect", json!({"x": 4, "y": 4, "width": 8, "height": 8})).unwrap(); - s.execute("select.modify.feather", json!({"radius": 1})).unwrap(); - - let mut before_px = Vec::new(); - for y in 0..16 { - for x in 0..16 { - before_px.push(s.execute("document.pixel", json!({"x": x, "y": y})).unwrap()); - } - } - - s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 0, 0], "interpolation": "nearest"})).unwrap(); - - let mut after_px = Vec::new(); - for y in 0..16 { - for x in 0..16 { - after_px.push(s.execute("document.pixel", json!({"x": x, "y": y})).unwrap()); - } - } - - assert_eq!(before_px, after_px, "feathered selection identity transform must preserve all pixels"); - let p4_8 = s.execute("document.pixel", json!({"x": 4, "y": 8})).unwrap(); - assert_eq!(p4_8, json!([1.0, 0.0, 0.0, 1.0]), "(4,8) must remain opaque red"); - - // Undo restores original document. - s.execute("edit.undo", json!({})).unwrap(); - let undo_p4_8 = s.execute("document.pixel", json!({"x": 4, "y": 8})).unwrap(); - assert_eq!(undo_p4_8, json!([1.0, 0.0, 0.0, 1.0])); - - // Locked layer still refuses transform even if identity. - s.execute("layer.setProps", json!({"locks": {"position": true}})).unwrap(); - assert!(s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 0, 0]})).is_err(), "locked layer refuses identity transform"); - } - - /// A 1 x 8 px column on a 256 x 256 canvas (#3773). - fn column_session() -> Session { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 256, "height": 256})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.edit("paint", |doc, active| { - let l = doc.layer_mut(active.unwrap()).unwrap(); - l.surface_mut().unwrap().fill_rect(Rect::new(100, 100, 101, 108), &[0.0, 1.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - s - } - - fn opaque_green(s: &Session, x: i32, y: i32) -> bool { - let st = s.active().unwrap(); - let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); - (surf.sample_channel(x, y, 1) - 1.0).abs() < 1e-3 && (surf.sample_channel(x, y, 3) - 1.0).abs() < 1e-3 - } - - /// The "pixel stretch" (#3773): scales far past 1000% are taken, and the stretched column stays - /// solid along its whole length. - #[test] - fn a_one_pixel_column_stretches_5000_percent() { - let mut s = column_session(); - s.execute("edit.transform", json!({"quad": [[100, 100], [150, 100], [150, 108], [100, 108]]})).unwrap(); - assert_eq!(active_bounds(&s), Rect::new(100, 100, 150, 108)); - for x in [100, 101, 125, 149] { - for y in 100..108 { - assert!(opaque_green(&s, x, y), "({x}, {y})"); - } - } - } - - /// The technique as done in Photoshop: select a 1 px column of an image and stretch it across. - #[test] - fn a_selected_column_stretches_solid_over_the_image() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 256, "height": 256})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.edit("paint", |doc, active| { - let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); - surf.fill_rect(Rect::new(0, 0, 256, 256), &[1.0, 0.0, 0.0, 1.0]); - surf.fill_rect(Rect::new(10, 0, 11, 256), &[0.0, 1.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - s.execute("select.rect", json!({"x": 10, "y": 0, "width": 1, "height": 256})).unwrap(); - s.execute("edit.transform", json!({"quad": [[10, 0], [250, 0], [250, 256], [10, 256]]})).unwrap(); - for x in [10, 11, 100, 200, 249] { - assert!(opaque_green(&s, x, 128), "x = {x}"); - } - let st = s.active().unwrap(); - let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); - assert!(surf.sample_channel(250, 128, 0) > 0.999 && surf.sample_channel(9, 128, 0) > 0.999, "the image either side is untouched"); - } - - /// Free Transform keeps pixels moved off the canvas, as Photoshop does: an 8 x 8 layer moved - /// three canvas widths right and back comes back whole. - #[test] - fn a_layer_moved_far_off_the_canvas_and_back_keeps_its_pixels() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.edit("paint", |doc, active| { - let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); - for y in 0..8 { - for x in 0..8 { - surf.fill_rect(Rect::new(20 + x, 20 + y, 21 + x, 21 + y), &[x as f32 / 8.0, y as f32 / 8.0, 0.5, 1.0]); - } - } - Ok(()) - }) - .unwrap(); - let pixels = |s: &Session| { - let st = s.active().unwrap(); - let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); - (0..8 * 8 * 4).map(|i| surf.sample_channel(20 + i / 4 % 8, 20 + i / 32, (i % 4) as usize)).collect::>() - }; - let before = pixels(&s); - s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 192, 0]})).unwrap(); - assert_eq!(active_bounds(&s), Rect::new(212, 20, 220, 28)); - s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, -192, 0]})).unwrap(); - assert_eq!(active_bounds(&s), Rect::new(20, 20, 28, 28)); - assert_eq!(pixels(&s), before); - } - - #[test] - fn relative_params_scale_and_rotate_about_the_frame_centre() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 100, "height": 100})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.execute("select.rect", json!({"x": 20, "y": 30, "width": 40, "height": 20})).unwrap(); - s.execute("edit.fill", json!({"contents": "black"})).unwrap(); - s.execute("select.deselect", json!({})).unwrap(); - // 50% about the centre (40, 40), then 10 px right: the content ends at x 40..60, y 35..45. - let r = s.execute("edit.transform", json!({"scaleX": 50, "scaleY": 50, "dx": 10})).unwrap(); - let rect: Vec = serde_json::from_value(r["rect"].clone()).unwrap(); - assert_eq!(rect, [20.0, 30.0, 60.0, 50.0], "the reported frame is the source frame"); - let bounds = |s: &Session| { - let d = s.active().unwrap(); - let b = transform_bounds(&d.doc, d.doc.layer(d.active_layer.unwrap()).unwrap()); - (b.x0, b.y0, b.x1, b.y1) - }; - assert_eq!(bounds(&s), (40, 35, 60, 45)); - // A quarter turn about the centre (50, 40) swaps the frame's sides. - s.execute("edit.transform", json!({"rotate": 90})).unwrap(); - assert_eq!(bounds(&s), (45, 30, 55, 50)); - for bad in [json!({"scaleX": 0}), json!({"rotate": "x"}), json!({"dx": f64::NAN})] { - assert!(s.execute("edit.transform", bad.clone()).is_err(), "{bad}"); - } - } - - /// #5846: a shape's Density and Feather render past its path (over the whole canvas below - /// 100 %), but its transform frame follows the path, as in Photoshop: the same box as the hard - /// shape for Free Transform, the Move tool's controls and snapping, never the canvas. - #[test] - fn a_soft_shapes_frame_follows_its_path() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); - let id = s.execute("shape.create", json!({"kind": "rect", "rect": [20, 30, 60, 40], "fill": "#000000"})).unwrap()["layer"].as_u64().unwrap(); - let id = photocraft_doc::LayerId(id); - let boxes = |s: &Session| { - let st = s.active().unwrap(); - let l = st.doc.layer(id).unwrap(); - (transform_bounds(&st.doc, l), transform_frame(&st.doc, l), crate::snap::layer_rect(&st.doc, id)) - }; - let hard = boxes(&s); - assert_eq!(hard.0, Rect::new(20, 30, 80, 70), "the hard shape's frame"); - s.execute("layer.vectorMask.edit", json!({"density": 60, "feather": 20})).unwrap(); - { - let st = s.active().unwrap(); - let LayerContent::Shape(sh) = &st.doc.layer(id).unwrap().content else { panic!("a shape") }; - let painted = photocraft_compose::bounds::content_bounds(sh.cache.as_ref().unwrap()); - assert_eq!(painted, st.doc.bounds(), "the soft fill renders over the whole canvas"); - } - let soft = boxes(&s); - assert_eq!(soft, hard, "the frame ignores Density and Feather"); - assert_ne!(soft.1, s.active().unwrap().doc.bounds()); - // Feather alone (density 100 %) leaves the frame on the path too, not grown by the blur. - s.execute("layer.vectorMask.edit", json!({"density": 100, "feather": 20})).unwrap(); - assert_eq!(boxes(&s), hard); - // Free Transform scales about the path's centre, not the canvas's. - s.execute("edit.transform", json!({"layer": id.0, "scaleX": 200})).unwrap(); - let st = s.active().unwrap(); - let LayerContent::Shape(sh) = &st.doc.layer(id).unwrap().content else { panic!("a shape") }; - let (x0, y0, x1, y1) = sh.path.control_bounds().unwrap(); - assert_eq!((x0.round(), y0.round(), x1.round(), y1.round()), (-10.0, 30.0, 110.0, 70.0)); - assert_eq!((sh.density, sh.feather), (1.0, 20.0), "the transform keeps the soft settings"); - } - - /// A stroked soft shape's frame is the hard shape's rendered frame for every stroke alignment: - /// a centred stroke reaches half its width past the path, not its full width; both stop at - /// the canvas edge. - #[test] - fn a_stroked_soft_shapes_frame_matches_the_hard_shapes() { - for (align, reach, x) in [("center", 5, 50), ("inside", 0, 50), ("outside", 10, 50), ("center", 5, -20)] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); - let stroke = json!({"width": 10, "color": "#ff0000", "align": align, "join": "round"}); - let id = s.execute("shape.create", json!({"kind": "rect", "rect": [x, 50, 60, 40], "fill": "#000000", "stroke": stroke})).unwrap()["layer"] - .as_u64() - .unwrap(); - let id = photocraft_doc::LayerId(id); - let boxes = |s: &Session| { - let st = s.active().unwrap(); - let l = st.doc.layer(id).unwrap(); - (transform_bounds(&st.doc, l), transform_frame(&st.doc, l), crate::snap::layer_rect(&st.doc, id)) - }; - let hard = boxes(&s); - // Hand-computed: the path is x..x + 60 x 50..90, the stroke reaches `reach` px past it. - assert_eq!(hard.0, Rect::new((x - reach).max(0), 50 - reach, x + 60 + reach, 90 + reach), "{align} at {x}: the hard shape's frame"); - s.execute("layer.vectorMask.edit", json!({"density": 60, "feather": 8})).unwrap(); - assert_eq!(boxes(&s), hard, "{align} at {x}: Density and Feather leave the frame"); - s.execute("layer.vectorMask.edit", json!({"density": 100, "feather": 8})).unwrap(); - assert_eq!(boxes(&s), hard, "{align} at {x}: Feather alone leaves the frame"); - } - } -} diff --git a/crates/engine/src/vector_cmds.rs b/crates/engine/src/vector_cmds.rs deleted file mode 100644 index 989f312db8..0000000000 --- a/crates/engine/src/vector_cmds.rs +++ /dev/null @@ -1,2035 +0,0 @@ -//! Vector commands: shape layers (`shape.*`), document paths (`path.*`, Paths panel), selection ⇄ -//! path, and layer vector masks (`layer.vectorMask.*`). -//! -//! Coordinates are document pixels. Paths in parameters and results use a compact JSON form: -//! -//! ```json -//! {"subpaths":[{"closed":true,"op":"combine|subtract|intersect|exclude", -//! "knots":[[x,y], {"anchor":[x,y],"in":[x,y],"out":[x,y],"smooth":true}, …]}], -//! "fillRule":"nonzero|evenodd", "inverted":false} -//! ``` -//! -//! A knot given as `[x, y]` is a corner with retracted handles; `in`/`out` default to the -//! anchor. The serde form of `photocraft_doc::Path` is accepted too. Colours are `"#rrggbb"`, -//! `"#rrggbbaa"` or `[r,g,b,a]` (0..1); opacities are percentages (0..100). -//! -//! Every edit re-renders the shape layer's cache with `photocraft-vector` in one undoable step. -//! PSD blocks stay byte-identical while they still decode to the model (see `photocraft-io`). - -use photocraft_algo::selection::{self as sel, SelectionMode}; -use photocraft_color::{BlendMode, Color}; -use photocraft_doc::{ - ClippingPath, Document, Fill, FillRule, GradientStyle, Knot, Layer, LayerContent, LayerId, LineCap, LineJoin, LiveShape, NamedPath, Path, PathOp, - ShapeLayer, ShapeStroke, StrokeAlign, Subpath, VectorMask, -}; -use photocraft_geom::{Affine, Point, Rect}; -use photocraft_vector as vector; -use serde_json::{Value, json}; - -use crate::commands::{CommandSpec, blend_from_str}; -use crate::{EngineError, Result, Session}; - -/// Keys PSD uses for a shape layer's vector data; dropped when a shape is rasterized. -const SHAPE_BLOCKS: [&[u8; 4]; 8] = [b"vmsk", b"vsms", b"vogk", b"vstk", b"vscg", b"SoCo", b"GdFl", b"PtFl"]; - -pub(crate) fn bad(cmd: &str, msg: impl Into) -> EngineError { - EngineError::BadParams { cmd: cmd.into(), msg: msg.into() } -} - -pub(crate) fn has_doc(s: &Session) -> std::result::Result<(), String> { - s.active().map(|_| ()).ok_or_else(|| "no document open".into()) -} - -fn has_layer(s: &Session) -> std::result::Result<(), String> { - let d = s.active().ok_or("no document open")?; - d.active_layer.filter(|id| d.doc.layer(*id).is_some()).map(|_| ()).ok_or_else(|| "no active layer".into()) -} - -fn has_selection(s: &Session) -> std::result::Result<(), String> { - s.active().filter(|d| d.doc.selection.is_some()).map(|_| ()).ok_or_else(|| "no selection".into()) -} - -fn active_shape(s: &Session) -> std::result::Result<&ShapeLayer, String> { - let d = s.active().ok_or("no document open")?; - let id = d.active_layer.ok_or("no active layer")?; - let layer = d.doc.layer(id).ok_or("no active layer")?; - match &layer.content { - LayerContent::Shape(shape) => Ok(shape), - _ => Err("active layer is not a shape layer".into()), - } -} - -fn has_shape_fill(s: &Session) -> std::result::Result<(), String> { - active_shape(s)?.fill.as_ref().map(|_| ()).ok_or_else(|| "shape has no fill".into()) -} - -fn has_shape_stroke(s: &Session) -> std::result::Result<(), String> { - active_shape(s)?.stroke.as_ref().map(|_| ()).ok_or_else(|| "shape has no stroke".into()) -} - -fn can_paste_shape_fill(s: &Session) -> std::result::Result<(), String> { - active_shape(s)?; - s.path_fill_clipboard.as_ref().map(|_| ()).ok_or_else(|| "no shape fill copied".into()) -} - -fn can_paste_shape_stroke(s: &Session) -> std::result::Result<(), String> { - active_shape(s)?; - s.path_stroke_clipboard.as_ref().map(|_| ()).ok_or_else(|| "no shape stroke copied".into()) -} - -fn copy_shape_fill(s: &mut Session, _p: &Value) -> Result { - let fill = active_shape(s).map_err(EngineError::Other)?.fill.clone().ok_or_else(|| EngineError::Other("shape has no fill".into()))?; - s.path_fill_clipboard = Some(fill); - Ok(Value::Null) -} - -fn copy_shape_stroke(s: &mut Session, _p: &Value) -> Result { - let stroke = active_shape(s).map_err(EngineError::Other)?.stroke.clone().ok_or_else(|| EngineError::Other("shape has no stroke".into()))?; - s.path_stroke_clipboard = Some(stroke); - Ok(Value::Null) -} - -fn paste_shape_fill(s: &mut Session, p: &Value) -> Result { - let fill = s.path_fill_clipboard.clone().ok_or_else(|| EngineError::Other("no shape fill copied".into()))?; - let id = layer_id(s, p)?; - with_shape(s, id, "Paste Fill", |shape, _| { - shape.fill = Some(fill); - Ok(()) - })?; - shape_info(s, id) -} - -fn paste_shape_stroke(s: &mut Session, p: &Value) -> Result { - let stroke = s.path_stroke_clipboard.clone().ok_or_else(|| EngineError::Other("no shape stroke copied".into()))?; - let id = layer_id(s, p)?; - with_shape(s, id, "Paste Complete Stroke", |shape, _| { - shape.stroke = Some(stroke); - Ok(()) - })?; - shape_info(s, id) -} - -pub(crate) fn layer_id(s: &Session, p: &Value) -> Result { - match p.get("layer").and_then(Value::as_u64) { - Some(id) => Ok(LayerId(id)), - None => s.active().and_then(|d| d.active_layer).ok_or(EngineError::Other("no active layer".into())), - } -} - -fn f64p(p: &Value, k: &str) -> Option { - p.get(k).and_then(Value::as_f64) -} - -pub(crate) fn pt(v: &Value) -> Option { - match v { - Value::Array(a) if a.len() >= 2 => Some(Point::new(a[0].as_f64()?, a[1].as_f64()?)), - Value::Object(_) => Some(Point::new(v.get("x")?.as_f64()?, v.get("y")?.as_f64()?)), - _ => None, - } -} - -pub(crate) fn nums(p: &Value, k: &str) -> Option<[f64; N]> { - let a = p.get(k)?.as_array()?; - if a.len() < N { - return None; - } - let mut out = [0.0; N]; - for (o, v) in out.iter_mut().zip(a) { - *o = v.as_f64()?; - } - Some(out) -} - -/// `[tl, tr, br, bl]` from an array or a single number. -fn radii(p: &Value) -> Option<[f64; 4]> { - match p.get("radii").or_else(|| p.get("radius"))? { - Value::Number(n) => n.as_f64().map(|r| [r; 4]), - _ => nums::<4>(p, "radii"), - } -} - -pub(crate) fn color(v: &Value) -> Option { - match v { - Value::Array(a) if a.len() >= 3 => { - let c: Vec = a.iter().map(|x| x.as_f64().unwrap_or(0.0) as f32).collect(); - Some(Color::rgba(c[0], c[1], c[2], c.get(3).copied().unwrap_or(1.0))) - } - Value::String(s) => { - let s = s.trim_start_matches('#'); - let h = |i: usize| s.get(i..i + 2).and_then(|x| u8::from_str_radix(x, 16).ok()).map(|v| f32::from(v) / 255.0); - match s.len() { - 6 => Some(Color::rgb(h(0)?, h(2)?, h(4)?)), - 8 => Some(Color::rgba(h(0)?, h(2)?, h(4)?, h(6)?)), - _ => None, - } - } - // A stored `Color` (mode + components), so a CMYK or Lab gradient stop survives a - // read-modify-write through the shape swatches. - Value::Object(_) => serde_json::from_value::(v.clone()) - .ok() - .filter(|c| c.c.iter().all(|x| x.is_finite()) && c.alpha.is_finite() && (0.0..=1.0).contains(&c.alpha)), - _ => None, - } -} - -fn hex(c: &Color) -> String { - let [r, g, b] = c.to_rgb(); - let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; - if c.alpha < 1.0 { format!("#{:02x}{:02x}{:02x}{:02x}", q(r), q(g), q(b), q(c.alpha)) } else { format!("#{:02x}{:02x}{:02x}", q(r), q(g), q(b)) } -} - -fn op_from(s: &str) -> Option { - Some(match s.to_ascii_lowercase().as_str() { - "combine" | "add" | "union" => PathOp::Combine, - "subtract" | "minus" => PathOp::Subtract, - "intersect" => PathOp::Intersect, - "exclude" | "xor" => PathOp::Exclude, - "join" => PathOp::Join, - _ => return None, - }) -} - -fn op_name(op: PathOp) -> &'static str { - match op { - PathOp::Combine => "combine", - PathOp::Subtract => "subtract", - PathOp::Intersect => "intersect", - PathOp::Exclude => "exclude", - PathOp::Join => "join", - } -} - -/// Parses a path from the compact JSON form (or the serde form). -pub fn parse_path(v: &Value) -> std::result::Result { - let subs = v.get("subpaths").and_then(Value::as_array).ok_or("path needs `subpaths`")?; - let mut out = Vec::with_capacity(subs.len()); - for (i, s) in subs.iter().enumerate() { - let knots_v = s.get("knots").and_then(Value::as_array).ok_or(format!("subpath {i} needs `knots`"))?; - let mut knots = Vec::with_capacity(knots_v.len()); - for (j, k) in knots_v.iter().enumerate() { - let knot = if k.is_array() { - let a = pt(k).ok_or(format!("knot {i}.{j}: expected [x, y]"))?; - Knot::corner(a.x, a.y) - } else { - let a = k.get("anchor").and_then(pt).ok_or(format!("knot {i}.{j}: missing anchor"))?; - let get = |keys: &[&str]| keys.iter().find_map(|key| k.get(*key).and_then(pt)); - Knot { - anchor: a, - in_ctrl: get(&["in", "inCtrl", "in_ctrl"]).unwrap_or(a), - out_ctrl: get(&["out", "outCtrl", "out_ctrl"]).unwrap_or(a), - smooth: k.get("smooth").and_then(Value::as_bool).unwrap_or(false), - } - }; - knots.push(knot); - } - let op = match s.get("op").and_then(Value::as_str) { - Some(o) => op_from(o).ok_or(format!("subpath {i}: unknown op `{o}`"))?, - None => PathOp::Combine, - }; - out.push(Subpath { closed: s.get("closed").and_then(Value::as_bool).unwrap_or(true), knots, op }); - } - let fill_rule = match v.get("fillRule").or_else(|| v.get("fill_rule")).and_then(Value::as_str).map(str::to_ascii_lowercase).as_deref() { - Some("evenodd" | "even-odd" | "even_odd") => FillRule::EvenOdd, - _ => FillRule::NonZero, - }; - Ok(Path { subpaths: out, fill_rule, inverted: v.get("inverted").and_then(Value::as_bool).unwrap_or(false) }) -} - -/// The compact JSON form of a path. -pub fn path_json(p: &Path) -> Value { - let a = |q: Point| json!([q.x, q.y]); - json!({ - "subpaths": p.subpaths.iter().map(|s| json!({ - "closed": s.closed, - "op": op_name(s.op), - "knots": s.knots.iter().map(|k| json!({ "anchor": a(k.anchor), "in": a(k.in_ctrl), "out": a(k.out_ctrl), "smooth": k.smooth })).collect::>(), - })).collect::>(), - "fillRule": if p.fill_rule == FillRule::EvenOdd { "evenodd" } else { "nonzero" }, - "inverted": p.inverted, - }) -} - -fn fill_json(f: &Fill) -> Value { - match f { - Fill::Solid(c) => json!(hex(c)), - Fill::Gradient { stops, angle, scale, style, reverse, opacity_stops, midpoints, offset, dither, align } => json!({ "gradient": { - "stops": stops.iter().map(|(t, c)| json!([t, hex(c)])).collect::>(), - "angle": angle, "scale": scale * 100.0, "style": format!("{style:?}").to_ascii_lowercase(), "reverse": reverse, - "opacityStops": opacity_stops, "midpoints": midpoints, "offset": [offset.0, offset.1], "dither": dither, "align": align } }), - Fill::Pattern { name, scale, .. } => json!({ "pattern": name, "scale": scale * 100.0 }), - } -} - -/// The most colour stops, opacity stops or midpoints a gradient fill takes, as the gradient stop -/// edits (`gradient.fill.stop`, `gradient.presets.stop`) cap them. -const MAX_GRADIENT_STOPS: usize = 1024; - -/// `"#rrggbb"` / `[r,g,b,a]` / `{"gradient":{"stops":[[t,"#hex"|[r,g,b,a]],…],"angle","scale","style","reverse", -/// "opacityStops":[[t,0..1],…],"midpoints":[0..1,…],"offset":[x,y],"dither","align"}}` / `{"pattern":name,"scale"}`. -/// `null` → `Ok(None)` (no fill). -fn parse_fill(v: &Value) -> std::result::Result, String> { - if v.is_null() { - return Ok(None); - } - if let Some(c) = color(v) { - return Ok(Some(Fill::Solid(c))); - } - if let Some(g) = v.get("gradient") { - // Stop lists are capped as `gradient.fill.stop` caps them: more is an error, not a cut. - let list = |key: &str, what: &str| match g.get(key) { - None | Some(Value::Null) => Ok(None), - Some(Value::Array(a)) if a.len() > MAX_GRADIENT_STOPS => Err(format!("too many {what} (max {MAX_GRADIENT_STOPS})")), - Some(Value::Array(a)) => Ok(Some(a)), - Some(_) => Err(format!("gradient `{key}` must be an array")), - }; - let stops: Vec<(f32, Color)> = list("stops", "colour stops")? - .map(|a| a.iter().filter_map(|s| Some((s.get(0)?.as_f64()? as f32, color(s.get(1)?)?))).collect()) - .unwrap_or_else(|| vec![(0.0, Color::BLACK), (1.0, Color::WHITE)]); - let style = match g.get("style").and_then(Value::as_str).unwrap_or("linear") { - "radial" => GradientStyle::Radial, - "angle" => GradientStyle::Angle, - "reflected" => GradientStyle::Reflected, - "diamond" => GradientStyle::Diamond, - _ => GradientStyle::Linear, - }; - let mut fill = Fill::gradient( - stops, - f64p(g, "angle").unwrap_or(90.0) as f32, - f64p(g, "scale").unwrap_or(100.0) as f32 / 100.0, - style, - g.get("reverse").and_then(Value::as_bool).unwrap_or(false), - ); - // The rest of a gradient, so a read-modify-write (the shape swatches) loses nothing. - if let Fill::Gradient { opacity_stops, midpoints, offset, dither, align, .. } = &mut fill { - let unit = |v: &Value| v.as_f64().map(|n| n.clamp(0.0, 1.0) as f32); - if let Some(a) = list("opacityStops", "opacity stops")? { - *opacity_stops = a.iter().filter_map(|s| Some((unit(s.get(0)?)?, unit(s.get(1)?)?))).collect(); - opacity_stops.sort_by(|a, b| a.0.total_cmp(&b.0)); - } - if let Some(a) = list("midpoints", "midpoints")? { - *midpoints = a.iter().filter_map(unit).collect(); - } - if let Some(o) = g.get("offset") { - let at = |i: usize| o.get(i).and_then(Value::as_f64).map(|n| n.clamp(-1000.0, 1000.0) as f32); - *offset = (at(0).ok_or("gradient offset must be [x, y]")?, at(1).ok_or("gradient offset must be [x, y]")?); - } - if let Some(d) = g.get("dither").and_then(Value::as_bool) { - *dither = d; - } - if let Some(a) = g.get("align").and_then(Value::as_bool) { - *align = a; - } - } - return Ok(Some(fill)); - } - if let Some(name) = v.get("pattern").and_then(Value::as_str) { - return Ok(Some(Fill::Pattern { - name: name.into(), - scale: f64p(v, "scale").unwrap_or(100.0) as f32 / 100.0, - id: String::new(), - angle: 0.0, - link: true, - phase: (0.0, 0.0), - })); - } - Err(format!("unrecognised fill {v}")) -} - -fn stroke_json(s: &ShapeStroke) -> Value { - json!({ - "width": s.width, "fill": fill_json(&s.paint), "opacity": s.opacity * 100.0, - "align": format!("{:?}", s.align).to_ascii_lowercase(), "cap": format!("{:?}", s.cap).to_ascii_lowercase(), - "join": format!("{:?}", s.join).to_ascii_lowercase(), "miterLimit": s.miter_limit, "dashes": s.dashes, "dashOffset": s.dash_offset, - }) -} - -/// Applies stroke keys onto `base` (`null` → no stroke). -pub fn parse_stroke(v: &Value, base: Option, fg: Color) -> std::result::Result, String> { - if v.is_null() || v.as_bool() == Some(false) { - return Ok(None); - } - if !v.is_object() { - return Err("stroke must be an object or null".into()); - } - for (key, lo, hi) in [("width", 0.0, 1_000_000.0), ("opacity", 0.0, 100.0), ("miterLimit", 1.0, 500.0), ("dashOffset", -1_000_000.0, 1_000_000.0)] { - if let Some(value) = v.get(key) - && !value.as_f64().is_some_and(|n| n.is_finite() && (lo..=hi).contains(&n)) - { - return Err(format!("`{key}` must be a finite number between {lo} and {hi}")); - } - } - for key in ["align", "cap", "join"] { - if v.get(key).is_some_and(|value| !value.is_string()) { - return Err(format!("`{key}` must be a string")); - } - } - let mut s = base.unwrap_or(ShapeStroke { paint: Fill::Solid(fg), ..Default::default() }); - if let Some(w) = f64p(v, "width") { - s.width = w as f32; - } - if let Some(c) = v.get("color").or_else(|| v.get("fill")) { - s.paint = parse_fill(c)?.ok_or("stroke colour cannot be null")?; - } - if let Some(o) = f64p(v, "opacity") { - s.opacity = (o / 100.0) as f32; - } - if let Some(a) = v.get("align").and_then(Value::as_str) { - s.align = match a { - "inside" => StrokeAlign::Inside, - "outside" => StrokeAlign::Outside, - "center" | "centre" => StrokeAlign::Center, - o => return Err(format!("unknown align `{o}`")), - }; - } - if let Some(c) = v.get("cap").and_then(Value::as_str) { - s.cap = match c { - "butt" => LineCap::Butt, - "round" => LineCap::Round, - "square" => LineCap::Square, - o => return Err(format!("unknown cap `{o}`")), - }; - } - if let Some(j) = v.get("join").and_then(Value::as_str) { - s.join = match j { - "miter" => LineJoin::Miter, - "round" => LineJoin::Round, - "bevel" => LineJoin::Bevel, - o => return Err(format!("unknown join `{o}`")), - }; - } - if let Some(m) = f64p(v, "miterLimit") { - s.miter_limit = m as f32; - } - if let Some(d) = v.get("dashes") { - s.dashes = match d { - Value::Null => Vec::new(), - Value::Array(a) if a.len() <= 32 => a - .iter() - .map(|x| { - x.as_f64() - .filter(|n| n.is_finite() && (0.0..=10000.0).contains(n)) - .map(|x| x as f32) - .ok_or_else(|| "dash lengths must be finite numbers between 0 and 10000 widths".to_string()) - }) - .collect::, _>>()?, - _ => return Err("`dashes` must be an array (multiples of the width)".into()), - }; - } - if let Some(o) = f64p(v, "dashOffset") { - s.dash_offset = o as f32; - } - s.validate()?; - Ok(Some(s)) -} - -fn live_json(l: &LiveShape) -> Value { - serde_json::to_value(l).unwrap_or(Value::Null) -} - -/// Builds a live shape from `kind` + geometry params. -fn live_from_params(cmd: &str, kind: &str, p: &Value, prev: Option<&LiveShape>) -> Result { - let prev_rect = match prev { - Some(LiveShape::Rect { rect, .. } | LiveShape::Ellipse { rect } | LiveShape::Polygon { rect, .. }) => Some(*rect), - _ => None, - }; - let rect = || nums::<4>(p, "rect").or(prev_rect).ok_or_else(|| bad(cmd, "`rect`: [x, y, w, h] is required")); - Ok(match kind { - "rect" | "rectangle" => { - let r = match prev { - Some(LiveShape::Rect { radii, .. }) => *radii, - _ => [0.0; 4], - }; - LiveShape::Rect { rect: rect()?, radii: radii(p).unwrap_or(r) } - } - "roundedRect" | "roundRect" => { - let r = match prev { - Some(LiveShape::Rect { radii, .. }) if radii.iter().any(|v| *v > 0.0) => *radii, - _ => [10.0; 4], - }; - LiveShape::Rect { rect: rect()?, radii: radii(p).unwrap_or(r) } - } - "ellipse" => LiveShape::Ellipse { rect: rect()? }, - "polygon" | "star" => { - let (ps, pr, pc) = match prev { - Some(LiveShape::Polygon { sides, star_ratio, corner_radius, .. }) => (*sides, *star_ratio, *corner_radius), - _ => (5, if kind == "star" { 0.5 } else { 1.0 }, 0.0), - }; - let corner_radius = f64p(p, "cornerRadius").map_or(pc, |v| if v.is_finite() { v.clamp(0.0, 1.0e6) } else { pc }); - let sides = f64p(p, "sides").map_or(ps, |v| v.round().clamp(3.0, 100.0) as u32); - let ratio = f64p(p, "starRatio").map_or(if kind == "star" && pr >= 1.0 { 0.5 } else { pr }, |v| v.clamp(0.01, 1.0)); - LiveShape::Polygon { - rect: rect()?, - sides, - star_ratio: if kind == "polygon" && f64p(p, "starRatio").is_none() { 1.0 } else { ratio }, - corner_radius, - } - } - "line" => { - let (pf, pto, pw) = match prev { - Some(LiveShape::Line { from, to, weight }) => (Some(*from), Some(*to), *weight), - _ => (None, None, 1.0), - }; - LiveShape::Line { - from: nums::<2>(p, "from").or(pf).ok_or_else(|| bad(cmd, "`from`: [x, y] is required"))?, - to: nums::<2>(p, "to").or(pto).ok_or_else(|| bad(cmd, "`to`: [x, y] is required"))?, - weight: f64p(p, "weight").unwrap_or(pw).max(0.0), - } - } - o => return Err(bad(cmd, format!("unknown kind `{o}`"))), - }) -} - -/// The path `shape.create` draws for live-shape params `p` (the Shape tools preview it while dragging). -pub fn shape_path(p: &Value) -> Result { - let kind = p.get("kind").and_then(Value::as_str).unwrap_or("rect"); - Ok(vector::shapes::live_path(&live_from_params("shape.create", kind, p, None)?)) -} - -fn live_kind(l: &LiveShape) -> &'static str { - match l { - LiveShape::Rect { radii, .. } if radii.iter().any(|r| *r > 0.0) => "roundedRect", - LiveShape::Rect { .. } => "rect", - LiveShape::Ellipse { .. } => "ellipse", - LiveShape::Polygon { star_ratio, .. } if *star_ratio < 1.0 => "star", - LiveShape::Polygon { .. } => "polygon", - LiveShape::Line { .. } => "line", - } -} - -/// Re-renders a shape layer's cache for `doc` (canvas-clipped, document pixel format). -pub fn refresh_shape(doc: &Document, sh: &mut ShapeLayer) { - sh.cache = Some(vector::render_shape(sh, doc.pixel_format(), doc.bounds())); -} - -/// A staged stroke edit rendered with the same validation and cache refresh as `shape.edit`. -/// The caller owns this snapshot; the session and its history remain untouched. -pub fn preview_shape_stroke(doc: &Document, id: LayerId, params: &Value) -> Result { - let mut result = doc.clone(); - let layer = result.layer_mut(id).ok_or(EngineError::NoLayer(id))?; - let LayerContent::Shape(shape) = &mut layer.content else { - return Err(EngineError::Other("preview target is not a shape layer".into())); - }; - shape.stroke = parse_stroke(params, shape.stroke.clone(), Color::BLACK).map_err(|e| bad("shape.edit", e))?; - vector::flatten::validate_shape(&shape.path, shape.stroke.as_ref()).map_err(|e| bad("shape.edit", e))?; - refresh_shape(doc, shape); - Ok(result) -} - -/// Moves a layer's vector content by `(dx, dy)`: shape paths (re-rendered) and linked vector -/// masks, recursing into groups. For the Move tool / `layer.move`. -pub fn translate_vectors(doc: &Document, l: &mut Layer, dx: f64, dy: f64) { - let a = Affine::translate(dx, dy); - if let Some(vm) = l.vector_mask.as_mut() - && vm.linked - { - vm.path = vm.path.transform(&a); - } - match &mut l.content { - LayerContent::Shape(sh) => shift_shape(doc, sh, dx, dy), - LayerContent::Group(g) => { - for c in &mut g.children { - translate_vectors(doc, c, dx, dy); - } - } - _ => {} - } -} - -/// Moves a shape by `(dx, dy)`. A whole-pixel move shifts the rendered pixels as they are, so a -/// shape from a PSD keeps Photoshop's anti-aliasing (as moved type does). The render is cut at -/// the canvas, so a shape reaching past it renders again, as does a fractional move. -pub(crate) fn shift_shape(doc: &Document, sh: &mut ShapeLayer, dx: f64, dy: f64) { - transform_shape(sh, &Affine::translate(dx, dy)); - let whole = |v: f64| (v.fract() == 0.0 && v.abs() <= f64::from(i32::MAX)).then_some(v as i32); - let canvas = doc.bounds(); - let inside = sh.cache.as_ref().is_some_and(|c| { - let b = photocraft_compose::bounds::content_bounds(c); - // An empty cache can be an off-canvas shape moving back into view. - !b.is_empty() && b.x0 > canvas.x0 && b.y0 > canvas.y0 && b.x1 < canvas.x1 && b.y1 < canvas.y1 - }); - let stroke_pad = sh.stroke.as_ref().filter(|s| s.opacity > 0.0).map_or(0.0, |s| f64::from(s.width.ceil())); - let stays_inside = sh.path.control_bounds().is_some_and(|(x0, y0, x1, y1)| { - (x0 - stroke_pad) > canvas.x0 as f64 - && (y0 - stroke_pad) > canvas.y0 as f64 - && (x1 + stroke_pad) < canvas.x1 as f64 - && (y1 + stroke_pad) < canvas.y1 as f64 - }); - match (&mut sh.cache, whole(dx), whole(dy)) { - (Some(c), Some(dx), Some(dy)) if inside && stays_inside => *c = crate::layer_multi_cmds::shift_surface(c, dx, dy), - _ => refresh_shape(doc, sh), - } -} - -/// Applies an affine transform to a shape's path, keeping the live shape when the transform -/// is a translation plus axis-aligned scale (otherwise the shape stops being parametric). -pub fn transform_shape(sh: &mut ShapeLayer, a: &Affine) { - sh.path = sh.path.transform(a); - let [m0, m1, m2, m3, tx, ty] = a.m; - let axis_aligned = m1.abs() < 1e-12 && m2.abs() < 1e-12 && m0 > 0.0 && m3 > 0.0; - sh.live = match (sh.live.take(), axis_aligned) { - (Some(l), true) => { - let r = |r: [f64; 4]| [r[0] * m0 + tx, r[1] * m3 + ty, r[2] * m0, r[3] * m3]; - let pt = |p: [f64; 2]| [p[0] * m0 + tx, p[1] * m3 + ty]; - Some(match l { - LiveShape::Rect { rect, radii } => { - let k = m0.min(m3); - LiveShape::Rect { rect: r(rect), radii: radii.map(|v| v * k) } - } - LiveShape::Ellipse { rect } => LiveShape::Ellipse { rect: r(rect) }, - LiveShape::Polygon { rect, sides, star_ratio, corner_radius } => { - LiveShape::Polygon { rect: r(rect), sides, star_ratio, corner_radius: corner_radius * m0.min(m3) } - } - LiveShape::Line { from, to, weight } => { - // Live-shape edits regenerate the line's filled bar from its parameters. - // Keep the weight in sync with a positive scale of the path, or an - // unchanged endpoint edit unexpectedly restores the old thickness (#3063). - // A line's width scales perpendicular to its direction. - let (dx, dy) = (to[0] - from[0], to[1] - from[1]); - let old_length = dx.hypot(dy); - let new_length = (dx * m0).hypot(dy * m3); - let width_scale = if old_length > 0.0 && new_length > 0.0 { m0 * m3 * old_length / new_length } else { m0.min(m3) }; - LiveShape::Line { from: pt(from), to: pt(to), weight: weight * width_scale } - } - }) - } - // Flips and 90° turns keep rectangles, ellipses and lines live (Image Rotation): the new - // live box is the mapped box. Polygons/stars would change orientation, so they don't. - (Some(l), false) if (m1.abs() < 1e-12 && m2.abs() < 1e-12) || (m0.abs() < 1e-12 && m3.abs() < 1e-12) => { - let pt = |p: [f64; 2]| [m0 * p[0] + m2 * p[1] + tx, m1 * p[0] + m3 * p[1] + ty]; - let r = |r: [f64; 4]| { - let (p, q) = (pt([r[0], r[1]]), pt([r[0] + r[2], r[1] + r[3]])); - [p[0].min(q[0]), p[1].min(q[1]), (q[0] - p[0]).abs(), (q[1] - p[1]).abs()] - }; - let k = (m0.abs() + m1.abs()).min(m2.abs() + m3.abs()); - match l { - LiveShape::Rect { rect, radii } if radii.iter().all(|v| (v - radii[0]).abs() < 1e-9) => { - Some(LiveShape::Rect { rect: r(rect), radii: radii.map(|v| v * k) }) - } - LiveShape::Ellipse { rect } => Some(LiveShape::Ellipse { rect: r(rect) }), - LiveShape::Line { from, to, weight } => Some(LiveShape::Line { from: pt(from), to: pt(to), weight: weight * k }), - _ => None, - } - } - _ => None, - }; - sh.psd_raw = None; -} - -/// Is every anchor and control point of `path` a finite point? -fn finite_path(path: &Path) -> bool { - path.subpaths.iter().flat_map(|s| &s.knots).all(|k| [k.anchor, k.in_ctrl, k.out_ctrl].iter().all(|p| p.x.is_finite() && p.y.is_finite())) -} - -/// `path` through Distort / Perspective (`h`, a projective map of its points: exact for straight -/// segments, the end tangents of curves exact) or, with `warp`, Warp (split where the warp bends -/// it). Refused when the map sends a point to infinity (past a perspective's horizon). -pub(crate) fn map_path(path: &Path, h: Option<&photocraft_algo::transform::Homography>, warp: Option<&photocraft_geom::warp::Warp>) -> Result { - let out = match (h, warp) { - (_, Some(w)) => vector::map::map_path( - path, - |p| { - let (x, y) = w.map(p.x, p.y); - Point::new(x, y) - }, - 0.1, - ), - (Some(h), None) => vector::map::map_points(path, |p| { - let (x, y) = h.apply(p.x, p.y); - Point::new(x, y) - }), - (None, None) => path.clone(), - }; - if !finite_path(&out) { - return Err(EngineError::Other("the distortion sends part of the path out of bounds".into())); - } - Ok(out) -} - -/// Distort, Perspective or Warp of a shape layer (#3009): the shape stays a shape, its path -/// mapped ([`map_path`]), as in Photoshop. A live rectangle, ellipse, polygon or line becomes a -/// plain path, as its parameters can't describe the distorted outline. -pub(crate) fn map_shape(sh: &mut ShapeLayer, h: Option<&photocraft_algo::transform::Homography>, warp: Option<&photocraft_geom::warp::Warp>) -> Result<()> { - sh.path = map_path(&sh.path, h, warp)?; - sh.live = None; - sh.psd_raw = None; - Ok(()) -} - -fn shape_info(s: &Session, id: LayerId) -> Result { - let d = s.active().ok_or(EngineError::NoDocument)?; - let l = d.doc.layer(id).ok_or(EngineError::NoLayer(id))?; - let LayerContent::Shape(sh) = &l.content else { - return Err(EngineError::Other(format!("layer {} is {} {} layer, not a shape layer", id.0, l.content.article(), l.content.kind_name()))); - }; - let bounds = sh.cache.as_ref().map(|c| c.content_bounds()).filter(|r| !r.is_empty()).map(|r| json!([r.x0, r.y0, r.width(), r.height()])); - Ok(json!({ - "layer": id.0, - "name": l.name, - "path": path_json(&sh.path), - "fill": sh.fill.as_ref().map(fill_json), - "stroke": sh.stroke.as_ref().map(stroke_json), - "live": sh.live.as_ref().map(live_json), - "kind": sh.live.as_ref().map_or("path", live_kind), - "bounds": bounds, - })) -} - -pub(crate) fn with_shape(s: &mut Session, id: LayerId, label: &str, f: impl FnOnce(&mut ShapeLayer, &mut Layer) -> Result) -> Result { - if let Some(st) = s.active() { - let locks = st.doc.effective_locks(id); - if locks.all || locks.pixels { - return Err(EngineError::Other("shape layer is locked".into())); - } - } - s.edit(label, |doc, _| { - let snapshot = doc.clone(); - let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; - if !matches!(l.content, LayerContent::Shape(_)) { - return Err(EngineError::Other(format!("layer {} is {} {} layer, not a shape layer", id.0, l.content.article(), l.content.kind_name()))); - } - let LayerContent::Shape(mut sh) = std::mem::replace(&mut l.content, LayerContent::Fill(Fill::Solid(Color::BLACK))) else { - return Err(EngineError::Other(format!("layer {} is not a shape layer", id.0))); - }; - let r = f(&mut sh, l); - if r.is_ok() { - refresh_shape(&snapshot, &mut sh); - } - l.content = LayerContent::Shape(sh); - r - }) -} - -fn default_name(kind: &str) -> &'static str { - match kind { - "rect" | "rectangle" => "Rectangle", - "roundedRect" | "roundRect" => "Rounded Rectangle", - "ellipse" => "Ellipse", - "polygon" => "Polygon", - "star" => "Star", - "line" => "Line", - _ => "Shape", - } -} - -fn shape_create(s: &mut Session, p: &Value) -> Result { - const CMD: &str = "shape.create"; - let kind = p.get("kind").and_then(Value::as_str).unwrap_or("rect"); - let (path, live) = if kind == "path" { - let v = p.get("path").ok_or_else(|| bad(CMD, "kind \"path\" needs `path`"))?; - (parse_path(v).map_err(|e| bad(CMD, e))?, None) - } else { - let l = live_from_params(CMD, kind, p, None)?; - (vector::shapes::live_path(&l), Some(l)) - }; - let fg = s.tools.foreground; - let fgc = Color::rgba(fg[0], fg[1], fg[2], fg[3]); - let fill = match p.get("fill") { - Some(v) => parse_fill(v).map_err(|e| bad(CMD, e))?, - None => Some(Fill::Solid(fgc)), - }; - let stroke = match p.get("stroke") { - Some(v) => parse_stroke(v, None, fgc).map_err(|e| bad(CMD, e))?, - None => None, - }; - vector::flatten::validate_shape(&path, stroke.as_ref()).map_err(|e| bad(CMD, e))?; - // Add to an existing shape layer with a path operation (Shape tool in combine/subtract… mode). - if let Some(target) = p.get("addTo").and_then(Value::as_u64) { - let op = p.get("op").and_then(Value::as_str).map_or(Some(PathOp::Combine), op_from).ok_or_else(|| bad(CMD, "unknown `op`"))?; - let id = LayerId(target); - with_shape(s, id, "Add Shape", |sh, _| { - for mut sp in path.subpaths { - sp.op = op; - sh.path.subpaths.push(sp); - } - sh.live = None; - sh.psd_raw = None; - vector::flatten::validate_shape(&sh.path, sh.stroke.as_ref()).map_err(|e| bad(CMD, e))?; - Ok(()) - })?; - return shape_info(s, id); - } - let name = p.get("name").and_then(Value::as_str).map(str::to_string); - let mut sh = ShapeLayer { path, fill, stroke, live, ..Default::default() }; - let id = s.edit("New Shape Layer", |doc, active| { - refresh_shape(doc, &mut sh); - let name = name.unwrap_or_else(|| doc.next_layer_name(default_name(kind))); - let id = doc.insert_above(*active, Layer::new(name, LayerContent::Shape(sh))); - *active = Some(id); - Ok(id) - })?; - shape_info(s, id) -} - -fn shape_edit(s: &mut Session, p: &Value) -> Result { - const CMD: &str = "shape.edit"; - let id = layer_id(s, p)?; - let fg = s.tools.foreground; - let fgc = Color::rgba(fg[0], fg[1], fg[2], fg[3]); - let name = p.get("name").and_then(Value::as_str).map(str::to_string); - with_shape(s, id, "Edit Shape", |sh, layer| { - if let Some(v) = p.get("path") { - sh.path = parse_path(v).map_err(|e| bad(CMD, e))?; - sh.live = None; - sh.psd_raw = None; - } - let geom_keys = ["kind", "rect", "radii", "radius", "sides", "starRatio", "cornerRadius", "from", "to", "weight"]; - if geom_keys.iter().any(|k| p.get(*k).is_some()) { - let kind = p.get("kind").and_then(Value::as_str).map(str::to_string).or_else(|| sh.live.as_ref().map(|l| live_kind(l).to_string())); - let kind = kind.ok_or_else(|| bad(CMD, "this shape has no live-shape parameters; pass `kind` or `path`"))?; - // Explicit radii on a plain rectangle keep it a (now rounded) rectangle. - let kind = if kind == "rect" && radii(p).is_some_and(|r| r.iter().any(|v| *v > 0.0)) { "roundedRect".to_string() } else { kind }; - let l = live_from_params(CMD, &kind, p, sh.live.as_ref())?; - // A transformed live shape's path may carry nonuniform corner scaling - // that its scalar radii cannot represent. Re-entering unchanged values - // must not regenerate the outline and silently discard that geometry. - if sh.live.as_ref() != Some(&l) { - sh.path = vector::shapes::live_path(&l); - sh.live = Some(l); - sh.psd_raw = None; - } - } - if let Some(m) = nums::<6>(p, "transform") { - transform_shape(sh, &Affine { m }); - } - if let Some([dx, dy]) = nums::<2>(p, "move") { - transform_shape(sh, &Affine::translate(dx, dy)); - } - if let Some(op) = p.get("op").and_then(Value::as_str) { - // Operation of the selected subpath(s) (`subpath`: index, default all but the first). - let op = op_from(op).ok_or_else(|| bad(CMD, format!("unknown op `{op}`")))?; - match p.get("subpath").and_then(Value::as_u64) { - Some(i) => sh.path.subpaths.get_mut(i as usize).ok_or_else(|| bad(CMD, "no such subpath"))?.op = op, - None => sh.path.subpaths.iter_mut().skip(1).for_each(|sp| sp.op = op), - } - sh.live = None; - } - if let Some(r) = p.get("fillRule").and_then(Value::as_str) { - sh.path.fill_rule = if r.eq_ignore_ascii_case("evenodd") { FillRule::EvenOdd } else { FillRule::NonZero }; - } - if let Some(v) = p.get("fill") { - sh.fill = parse_fill(v).map_err(|e| bad(CMD, e))?; - } - if let Some(v) = p.get("stroke") { - sh.stroke = parse_stroke(v, sh.stroke.clone(), fgc).map_err(|e| bad(CMD, e))?; - } - if let Some(n) = name { - layer.name = n; - } - vector::flatten::validate_shape(&sh.path, sh.stroke.as_ref()).map_err(|e| bad(CMD, e))?; - Ok(()) - })?; - shape_info(s, id) -} - -fn shape_rasterize(s: &mut Session, p: &Value) -> Result { - let id = layer_id(s, p)?; - s.edit("Rasterize Shape", |doc, _| { - let snapshot = doc.clone(); - let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; - let LayerContent::Shape(sh) = &mut l.content else { - return Err(EngineError::Other(format!("layer {} is not a shape layer", id.0))); - }; - if sh.cache.is_none() { - refresh_shape(&snapshot, sh); - } - let fmt = snapshot.pixel_format(); - let surface = sh.cache.take().unwrap_or_else(|| photocraft_raster::Surface::new(fmt)); - let surface = if surface.format() == fmt { surface } else { surface.convert(fmt) }; - l.content = LayerContent::Raster(surface); - l.psd_blocks.retain(|(k, _)| !SHAPE_BLOCKS.contains(&k)); - Ok(()) - })?; - Ok(json!({ "layer": id.0 })) -} - -// --------------------------------------------------------------------------- -// Document paths -// --------------------------------------------------------------------------- - -pub(crate) fn is_work(name: Option<&str>) -> bool { - name.is_none_or(|n| n.is_empty() || n.eq_ignore_ascii_case("work") || n == "Work Path") -} - -/// The path a command targets: `"work"`/absent → the work path (falling back to the active -/// layer's shape path or vector mask when there is none), `"layer"` → the active layer's, -/// otherwise a saved path by name. -fn resolve_path(s: &Session, name: Option<&str>) -> Result { - let d = s.active().ok_or(EngineError::NoDocument)?; - let layer_path = || -> Option { - let l = d.doc.layer(d.active_layer?)?; - match &l.content { - LayerContent::Shape(sh) => Some(sh.path.clone()), - _ => l.vector_mask.as_ref().map(|v| v.path.clone()), - } - }; - if name == Some("layer") { - return layer_path().ok_or_else(|| EngineError::Other("active layer has no shape path or vector mask".into())); - } - if is_work(name) { - return d.doc.work_path.clone().or_else(layer_path).ok_or_else(|| EngineError::Other("no work path".into())); - } - let n = name.unwrap_or_default(); - d.doc.paths.iter().find(|p| p.name == n).map(|p| p.path.clone()).ok_or_else(|| EngineError::Other(format!("no path named \"{n}\""))) -} - -/// The path an edit targets, except a shape layer's (edit those with [`with_shape`], which -/// re-renders them): `layer`'s vector mask when given, else the work path or a saved path. -pub(crate) fn path_mut<'a>(doc: &'a mut Document, name: &str, layer: Option) -> Result<&'a mut Path> { - if let Some(id) = layer { - let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; - return l.vector_mask.as_mut().map(|vm| &mut vm.path).ok_or_else(|| EngineError::Other("active layer has no shape path or vector mask".into())); - } - if is_work(Some(name)) { - return doc.work_path.as_mut().ok_or_else(|| EngineError::Other("no work path".into())); - } - doc.paths.iter_mut().find(|q| q.name == name).map(|q| &mut q.path).ok_or_else(|| EngineError::Other(format!("no path named \"{name}\""))) -} - -fn paths_list(s: &Session) -> Result { - let d = s.active().ok_or(EngineError::NoDocument)?; - let doc = &d.doc; - let knots = |p: &Path| p.subpaths.iter().map(|s| s.knots.len()).sum::(); - let layer = d.active_layer.and_then(|id| doc.layer(id)).and_then(|l| match &l.content { - LayerContent::Shape(sh) => Some(json!({ "kind": "shape", "layer": l.id.0, "name": format!("{} Shape Path", l.name), "knots": knots(&sh.path) })), - _ => { - l.vector_mask.as_ref().map(|v| json!({ "kind": "vectorMask", "layer": l.id.0, "name": format!("{} Vector Mask", l.name), "knots": knots(&v.path) })) - } - }); - Ok(json!({ - "paths": doc.paths.iter().map(|p| json!({ "name": p.name, "knots": knots(&p.path), "subpaths": p.path.subpaths.len() })).collect::>(), - "workPath": doc.work_path.as_ref().map(|p| json!({ "knots": knots(p), "subpaths": p.subpaths.len() })), - "clippingPath": doc.clipping_path.as_ref().map(|c| json!({ "name": c.name, "flatness": c.flatness })), - "layerPath": layer, - })) -} - -fn path_set(s: &mut Session, p: &Value) -> Result { - const CMD: &str = "path.set"; - let path = parse_path(p.get("path").ok_or_else(|| bad(CMD, "missing `path`"))?).map_err(|e| bad(CMD, e))?; - let name = p.get("name").and_then(Value::as_str).map(str::to_string); - let append = p.get("op").and_then(Value::as_str).map(|o| op_from(o).ok_or_else(|| bad(CMD, format!("unknown op `{o}`")))).transpose()?; - s.edit(if is_work(name.as_deref()) { "Work Path" } else { "Save Path" }, |doc, _| { - let merge = |old: Option<&Path>, new: Path| match (old, append) { - (Some(o), Some(op)) => { - let mut o = o.clone(); - o.subpaths.extend(new.subpaths.into_iter().map(|mut sp| { - sp.op = op; - sp - })); - o - } - _ => new, - }; - if is_work(name.as_deref()) { - doc.work_path = Some(merge(doc.work_path.as_ref(), path)); - } else { - let n = name.clone().unwrap_or_default(); - match doc.paths.iter_mut().find(|q| q.name == n) { - Some(q) => { - q.path = merge(Some(&q.path), path); - } - None => doc.paths.push(NamedPath { name: n, path, psd_raw: None }), - } - } - Ok(()) - })?; - let path = resolve_path(s, name.as_deref())?; - Ok(json!({ "name": name.unwrap_or_else(|| "work".into()), "path": path_json(&path) })) -} - -fn path_delete(s: &mut Session, p: &Value) -> Result { - let name = p.get("name").and_then(Value::as_str).map(str::to_string); - s.edit("Delete Path", |doc, _| { - if is_work(name.as_deref()) { - return doc.work_path.take().map(|_| ()).ok_or_else(|| EngineError::Other("no work path".into())); - } - let n = name.clone().unwrap_or_default(); - let before = doc.paths.len(); - doc.paths.retain(|q| q.name != n); - if doc.paths.len() == before { - return Err(EngineError::Other(format!("no path named \"{n}\""))); - } - if doc.clipping_path.as_ref().is_some_and(|c| c.name == n) { - doc.clipping_path = None; - } - Ok(()) - })?; - Ok(Value::Null) -} - -fn clipping_path_set(s: &mut Session, p: &Value) -> Result { - const CMD: &str = "path.clippingPath.set"; - let name = p.get("name").and_then(Value::as_str).filter(|name| !name.is_empty()).ok_or_else(|| bad(CMD, "missing saved path `name`"))?.to_owned(); - let flatness = match p.get("flatness") { - Some(value) => { - value.as_f64().filter(|value| value.is_finite() && (0.0..=100.0).contains(value)).ok_or_else(|| bad(CMD, "`flatness` must be between 0 and 100"))? - as f32 - } - None => 0.0, - }; - s.edit("Clipping Path", |doc, _| { - if !doc.paths.iter().any(|path| path.name == name) { - return Err(EngineError::Other(format!("no saved path named \"{name}\""))); - } - doc.clipping_path = Some(ClippingPath { name: name.clone(), flatness }); - Ok(()) - })?; - Ok(json!({ "name": name, "flatness": flatness })) -} - -fn clipping_path_clear(s: &mut Session, _p: &Value) -> Result { - s.edit("Clear Clipping Path", |doc, _| { - doc.clipping_path.take().ok_or_else(|| EngineError::Other("no clipping path".into()))?; - Ok(()) - })?; - Ok(Value::Null) -} - -/// The path `path.transform` edits: `layer`'s shape path or vector mask, else the work path or a -/// saved path. -fn transform_target(s: &Session, name: &str, layer: Option) -> Result { - let Some(id) = layer else { return resolve_path(s, Some(name)) }; - let d = s.active().ok_or(EngineError::NoDocument)?; - let l = d.doc.layer(id).ok_or(EngineError::NoLayer(id))?; - match &l.content { - LayerContent::Shape(sh) => Ok(sh.path.clone()), - _ => l.vector_mask.as_ref().map(|v| v.path.clone()).ok_or_else(|| EngineError::Other("target layer has no shape path or vector mask".into())), - } -} - -/// `n` numbers at `key` (`[x0, y0, x1, y1]` or `[[x, y] × 4]`, flattened): finite, magnitude at -/// most 1000000. `None` when `key` is absent. -fn coords(p: &Value, key: &str, n: usize) -> Result>> { - const CMD: &str = "path.transform"; - let Some(v) = p.get(key) else { return Ok(None) }; - let flat: Vec<&Value> = match v.as_array() { - Some(a) if a.iter().all(Value::is_array) => a.iter().filter_map(Value::as_array).flatten().collect(), - Some(a) => a.iter().collect(), - None => Vec::new(), - }; - let nums: Vec = flat.iter().filter_map(|v| v.as_f64()).filter(|x| x.is_finite() && x.abs() <= 1_000_000.0).collect(); - if flat.len() != n || nums.len() != n { - return Err(bad(CMD, format!("`{key}` must hold {n} finite numbers with magnitude at most 1000000"))); - } - Ok(Some(nums)) -} - -/// How `path.transform` moves the path. -enum PathMap { - Affine(Affine), - /// Distort / Perspective: the box's corners go to a quad. - Projective(photocraft_algo::transform::Homography), - Warp(Box), -} - -fn path_transform(s: &mut Session, p: &Value) -> Result { - const CMD: &str = "path.transform"; - let name = p.get("name").and_then(Value::as_str).unwrap_or("work").to_owned(); - let layer_id = if name == "layer" { Some(layer_id(s, p)?) } else { None }; - // The box Distort, Perspective and Warp frame: `rect`, else the path's control bounds. - let frame = |s: &Session| -> Result<[f64; 4]> { - let r = match coords(p, "rect", 4)? { - Some(r) => [r[0], r[1], r[2], r[3]], - None => { - let (x0, y0, x1, y1) = transform_target(s, &name, layer_id)?.control_bounds().ok_or_else(|| bad(CMD, "path has no points to transform"))?; - [x0, y0, x1, y1] - } - }; - if r[2] - r[0] <= 0.0 || r[3] - r[1] <= 0.0 { - return Err(bad(CMD, "`rect` must have a positive width and height (a straight path needs a `rect`)")); - } - Ok(r) - }; - let map = if let Some(values) = p.get("matrix") { - let values = values.as_array().filter(|values| values.len() == 6).ok_or_else(|| bad(CMD, "`matrix` must contain six numbers"))?; - let mut m = [0.0; 6]; - for (slot, value) in m.iter_mut().zip(values) { - *slot = value - .as_f64() - .filter(|number| number.is_finite() && number.abs() <= 1_000_000.0) - .ok_or_else(|| bad(CMD, "matrix entries must be finite numbers with magnitude at most 1000000"))?; - } - PathMap::Affine(Affine { m }) - } else if let Some(q) = coords(p, "quad", 8)? { - // Distort and Perspective (#3027): where the frame's corners go, clockwise from top-left. - let quad = [[q[0], q[1]], [q[2], q[3]], [q[4], q[5]], [q[6], q[7]]]; - let h = photocraft_algo::transform::Homography::rect_to_quad(frame(s)?, quad) - .filter(|h| h.0.iter().all(|v| v.is_finite()) && h.inverse().is_some()) - .ok_or_else(|| bad(CMD, "degenerate quad"))?; - let [a, b, c, d, e, f, g, hh, i] = h.0; - if g.abs() < 1e-12 && hh.abs() < 1e-12 && i.abs() > 1e-12 { - // A parallelogram is affine: a live shape stays live. - PathMap::Affine(Affine { m: [a / i, d / i, b / i, e / i, c / i, f / i] }) - } else { - PathMap::Projective(h) - } - } else if ["warp", "style", "mesh"].iter().any(|key| p.get(*key).is_some()) { - let w = crate::warp_cmds::warp_from_params(CMD, p, frame(s)?)?; - if [w.bend, w.h_distort, w.v_distort].iter().chain(w.bounds.iter()).any(|v| !v.is_finite() || v.abs() > 1_000_000.0) { - return Err(bad(CMD, "warp values must be finite numbers with magnitude at most 1000000")); - } - PathMap::Warp(Box::new(w)) - } else { - let number = |key: &str, default: f64| -> Result { - match p.get(key) { - Some(value) => value - .as_f64() - .filter(|n| n.is_finite() && n.abs() <= 1_000_000.0) - .ok_or_else(|| bad(CMD, format!("`{key}` must be a finite number with magnitude at most 1000000"))), - None => Ok(default), - } - }; - if !["translateX", "translateY", "scaleX", "scaleY", "angle"].iter().any(|key| p.get(*key).is_some()) { - return Err(bad(CMD, "pass `matrix`, `quad`, a warp (`style`, `mesh` or `warp`) or translate/scale/angle parameters")); - } - let (tx, ty) = (number("translateX", 0.0)?, number("translateY", 0.0)?); - let (sx, sy) = (number("scaleX", 1.0)?, number("scaleY", 1.0)?); - let angle = number("angle", 0.0)?; - // An explicit `layer` parameter determines both the transformed path and its pivot (#3062). - let path = transform_target(s, &name, layer_id)?; - let (x0, y0, x1, y1) = path.control_bounds().ok_or_else(|| bad(CMD, "path has no points to transform"))?; - let (cx, cy) = ((x0 + x1) * 0.5, (y0 + y1) * 0.5); - PathMap::Affine( - Affine::translate(-cx, -cy) - .then(&Affine { m: [sx, 0.0, 0.0, sy, 0.0, 0.0] }) - .then(&Affine::rotate(angle.to_radians())) - .then(&Affine::translate(cx + tx, cy + ty)), - ) - }; - let out = match &map { - PathMap::Affine(a) => json!({ "name": name, "matrix": a.m }), - PathMap::Projective(h) => json!({ "name": name, "homography": h.0 }), - PathMap::Warp(_) => json!({ "name": name, "warp": true }), - }; - if let Some(id) = layer_id - && s.active().and_then(|d| d.doc.layer(id)).is_some_and(|layer| matches!(layer.content, LayerContent::Shape(_))) - { - with_shape(s, id, "Transform Path", |shape, _| { - match &map { - PathMap::Affine(a) => transform_shape(shape, a), - PathMap::Projective(h) => map_shape(shape, Some(h), None)?, - PathMap::Warp(w) => map_shape(shape, None, Some(w))?, - } - shape.psd_raw = None; - Ok(()) - })?; - return Ok(out); - } - s.edit("Transform Path", |doc, _| { - let path = path_mut(doc, &name, layer_id)?; - *path = match &map { - PathMap::Affine(a) => path.transform(a), - PathMap::Projective(h) => map_path(path, Some(h), None)?, - PathMap::Warp(w) => map_path(path, None, Some(w))?, - }; - Ok(()) - })?; - Ok(out) -} - -fn path_rename(s: &mut Session, p: &Value) -> Result { - const CMD: &str = "path.rename"; - let name = p.get("name").and_then(Value::as_str).map(str::to_string); - let to = p.get("to").and_then(Value::as_str).filter(|t| !t.is_empty()).ok_or_else(|| bad(CMD, "missing `to`"))?.to_string(); - if is_work(Some(&to)) { - return Err(bad(CMD, "`to` cannot name the work path")); - } - s.edit(if is_work(name.as_deref()) { "Save Path" } else { "Rename Path" }, |doc, _| { - if doc.paths.iter().any(|q| q.name == to) { - return Err(EngineError::Other(format!("a path named \"{to}\" already exists"))); - } - if is_work(name.as_deref()) { - // Photoshop: saving the work path turns it into a named path. - let path = doc.work_path.take().ok_or_else(|| EngineError::Other("no work path".into()))?; - doc.paths.push(NamedPath { name: to.clone(), path, psd_raw: None }); - return Ok(()); - } - let n = name.clone().unwrap_or_default(); - let q = doc.paths.iter_mut().find(|q| q.name == n).ok_or_else(|| EngineError::Other(format!("no path named \"{n}\"")))?; - q.name = to.clone(); - if let Some(c) = doc.clipping_path.as_mut() - && c.name == n - { - c.name = to.clone(); - } - Ok(()) - })?; - Ok(json!({ "name": to })) -} - -fn path_to_selection(s: &mut Session, p: &Value) -> Result { - let path = resolve_path(s, p.get("name").and_then(Value::as_str))?; - // Validate before rasterizing or touching selection history. An unchecked feather value - // could silently become zero (negative/string), or expand into an excessive blur. - let feather = match p.get("feather") { - None => 0.0, - Some(v) => v - .as_f64() - .filter(|n| n.is_finite() && (0.0..=1000.0).contains(n)) - .ok_or_else(|| bad("path.toSelection", "`feather` must be a finite number within 0..1000"))? as f32, - }; - let aa = match p.get("antiAlias") { - None => true, - Some(Value::Bool(v)) => *v, - _ => return Err(bad("path.toSelection", "`antiAlias` must be a boolean")), - }; - let mode = match p.get("mode") { - None => SelectionMode::Replace, - Some(Value::String(v)) if matches!(v.as_str(), "replace" | "add" | "subtract" | "intersect") => SelectionMode::parse(v), - _ => return Err(bad("path.toSelection", "`mode` must be replace, add, subtract or intersect")), - }; - let area = s.active().ok_or(EngineError::NoDocument)?.doc.bounds(); - let mut mask = vector::fill_rasterizer(&path, vector::DEFAULT_TOLERANCE).render(area); - if !aa { - for v in &mut mask { - *v = if *v >= 0.5 { 1.0 } else { 0.0 }; - } - } - if feather > 0.0 { - mask = sel::feather(&mask, area.width() as usize, area.height() as usize, feather); - } - let selected = s.edit("Make Selection", |doc, _| { - doc.selection = sel::combine(doc.selection.as_ref(), &mask, area, mode); - Ok(doc.selection.is_some()) - })?; - Ok(json!({ "selected": selected })) -} - -fn select_to_work_path(s: &mut Session, p: &Value) -> Result { - let tol = f64p(p, "tolerance").unwrap_or(2.0).clamp(0.5, 10.0); - let d = s.active().ok_or(EngineError::NoDocument)?; - let area = d.doc.bounds(); - let sel_surface = d.doc.selection.as_ref().ok_or_else(|| EngineError::Other("no selection".into()))?; - let mask = sel::mask_from_surface(Some(sel_surface), area); - let path = vector::trace::trace_mask(&mask, area, 0.0, tol); - let knots: usize = path.subpaths.iter().map(|s| s.knots.len()).sum(); - let subpaths = path.subpaths.len(); - s.edit("Make Work Path", |doc, _| { - doc.work_path = Some(path); - Ok(()) - })?; - Ok(json!({ "subpaths": subpaths, "knots": knots })) -} - -fn path_fill(s: &mut Session, p: &Value) -> Result { - let path = resolve_path(s, p.get("name").and_then(Value::as_str))?; - let fg = s.tools.foreground; - let c = p.get("color").and_then(color).unwrap_or(Color::rgba(fg[0], fg[1], fg[2], fg[3])); - let rgb = c.to_rgb(); - let src = [rgb[0], rgb[1], rgb[2], c.alpha]; - let opacity = (f64p(p, "opacity").unwrap_or(100.0) / 100.0).clamp(0.0, 1.0) as f32; - let mode = p.get("mode").and_then(Value::as_str).and_then(blend_from_str).unwrap_or(BlendMode::Normal); - let feather = f64p(p, "feather").unwrap_or(0.0) as f32; - let aa = p.get("antiAlias").and_then(Value::as_bool).unwrap_or(true); - let id = layer_id(s, p)?; - s.edit("Fill Path", |doc, _| { - let area = doc.bounds(); - let r = vector::fill_rasterizer(&path, vector::DEFAULT_TOLERANCE); - // The feather reaches 3σ = 3 × radius (σ = radius, as in Photoshop), plus a pixel. - let feather_pad = (feather.ceil() as i32).saturating_mul(3).saturating_add(1); - let area = r.pixel_bounds().map_or(area, |b| b.inflate(feather_pad).intersect(&area)); - if area.is_empty() { - return Ok(()); - } - let mut cov = r.render(area); - if !aa { - cov.iter_mut().for_each(|v| *v = if *v >= 0.5 { 1.0 } else { 0.0 }); - } - if feather > 0.0 { - cov = sel::feather(&cov, area.width() as usize, area.height() as usize, feather); - } - // An active selection limits the fill, soft edges included, as every other fill does (#2387). - if let Some(selection) = doc.selection.as_ref() { - let mask = sel::mask_from_surface(Some(selection), area); - cov.iter_mut().zip(&mask).for_each(|(c, m)| *c *= m); - } - let locks = doc.effective_locks(id); - let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; - if locks.pixels || locks.all { - return Err(EngineError::Other(format!("Could not complete your request because the layer \"{}\" is locked", l.name))); - } - let lock = locks.transparency; - let surf = l.surface_mut().ok_or_else(|| EngineError::Other("Fill Path needs a pixel layer".into()))?; - paint_coverage(surf, area, &cov, src, opacity, mode, lock); - Ok(()) - })?; - Ok(Value::Null) -} - -/// Composites `src` × coverage onto a surface over `area` (any pixel format). -fn paint_coverage(surf: &mut photocraft_raster::Surface, area: Rect, cov: &[f32], src: [f32; 4], opacity: f32, mode: BlendMode, lock_alpha: bool) { - let fmt = surf.format(); - let ch = fmt.channels(); - let mut vals = surf.read_region(area); - for (px, c) in vals.chunks_exact_mut(ch).zip(cov) { - if *c <= 0.0 { - continue; - } - let dst = photocraft_raster::to_rgba(&fmt, px); - let mut out = photocraft_compose::psblend::composite(mode, dst, [src[0], src[1], src[2], src[3] * c], opacity); - if lock_alpha { - out[3] = dst[3]; - } - photocraft_raster::from_rgba_into(&fmt, out, px); - } - surf.write_region(area, &vals); - surf.prune(); -} - -/// Stroke Path's brush-based tools besides the Brush, Pencil and Eraser it renders itself: each -/// paints the path with its own `paint.*` command (Photoshop's Stroke Path dialog Tool list). -pub const STROKE_PATH_TOOLS: &[(&str, &str)] = &[ - ("backgroundEraser", "paint.backgroundEraser"), - ("cloneStamp", "paint.cloneStamp"), - ("patternStamp", "paint.patternStamp"), - ("healingBrush", "paint.healingBrush"), - ("spotHealingBrush", "paint.spotHealing"), - ("historyBrush", "paint.historyBrush"), - ("blur", "paint.blur"), - ("sharpen", "paint.sharpen"), - ("smudge", "paint.smudge"), - ("dodge", "paint.dodge"), - ("burn", "paint.burn"), - ("sponge", "paint.sponge"), - ("colorReplacement", "paint.colorReplacement"), - ("mixerBrush", "paint.mixerBrush"), -]; - -/// At most this many points per subpath when Simulate Pressure resamples it. -const MAX_PRESSURE_POINTS: f64 = 200_000.0; - -/// The stroke points along one flattened subpath. With `simulate` (Stroke Path's Simulate -/// Pressure) the subpath is resampled about every pixel and the pressure rises from 0 at its start -/// to full at the middle and falls back to 0 at its end, so a brush whose size or opacity follows -/// pen pressure tapers at both ends, as in Photoshop. Otherwise every point has full pressure. -fn stroke_points(pts: &[(f64, f64)], closed: bool, simulate: bool) -> Vec { - use photocraft_paint::StrokePoint; - let mut line = pts.to_vec(); - if closed && let Some(&first) = pts.first() { - line.push(first); - } - let full = |line: Vec<(f64, f64)>| line.into_iter().map(|(x, y)| StrokePoint::new(x, y, 1.0)).collect(); - if !simulate { - return full(line); - } - let seg = |a: &(f64, f64), b: &(f64, f64)| (b.0 - a.0).hypot(b.1 - a.1); - let total: f64 = line.iter().zip(line.iter().skip(1)).map(|(a, b)| seg(a, b)).sum(); - if !(total.is_finite() && total > 0.0) { - return full(line); - } - let step = (total / MAX_PRESSURE_POINTS).max(1.0); - let pressure = |d: f64| (d / total * std::f64::consts::PI).sin().clamp(0.0, 1.0) as f32; - let mut out = Vec::new(); - let mut walked = 0.0; - for (a, b) in line.iter().zip(line.iter().skip(1)) { - let len = seg(a, b); - let n = (len / step).ceil().clamp(1.0, MAX_PRESSURE_POINTS) as usize; - for i in 0..n { - let t = i as f64 / n as f64; - out.push(StrokePoint::new(a.0 + (b.0 - a.0) * t, a.1 + (b.1 - a.1) * t, pressure(walked + len * t))); - } - walked += len; - } - if let Some(&(x, y)) = line.last() { - out.push(StrokePoint::new(x, y, 0.0)); - } - out -} - -/// Stroke Path with a tool that has its own `paint.*` command: the command runs once per subpath, -/// with the caller's params (size, opacity, the tool's options) and the path's points, all in one -/// history step. Only `path.stroke` itself is journalled, so a recorded action replays it once. -fn stroke_with_command(s: &mut Session, p: &Value, cmd: &str, lines: &[vector::Polyline], simulate: bool) -> Result { - let mut params = p.as_object().cloned().unwrap_or_default(); - for k in ["name", "tool", "simulatePressure", "coalesce"] { - params.remove(k); - } - let journal = s.journal.len(); - let r = crate::analysis_cmds::compound(s, "Stroke Path", |s| { - // The union of what each subpath's command changed; None when one of them didn't say. - let mut dmg = Some(Rect::EMPTY); - for pl in lines { - let pts = stroke_points(&pl.pts, pl.closed, simulate); - if pts.is_empty() { - continue; - } - let mut call = params.clone(); - call.insert("points".into(), Value::Array(pts.iter().map(|q| json!([q.x, q.y, q.pressure])).collect())); - s.execute(cmd, Value::Object(call))?; - let r = s.active().and_then(|d| d.last_damage); - dmg = dmg.zip(r).map(|(a, b)| { - if a.is_empty() { - b - } else if b.is_empty() { - a - } else { - a.union(&b) - } - }); - } - Ok(dmg) - }); - s.journal.truncate(journal); - let dmg = r?; - if let Some(st) = s.active_mut() { - st.last_damage = dmg; - } - let dmg = dmg.unwrap_or_else(|| s.active().map_or(Rect::EMPTY, |d| d.doc.bounds())); - Ok(json!({ "damage": [dmg.x0, dmg.y0, dmg.width(), dmg.height()] })) -} - -fn path_stroke(s: &mut Session, p: &Value) -> Result { - let path = resolve_path(s, p.get("name").and_then(Value::as_str))?; - let tool = p.get("tool").and_then(Value::as_str).unwrap_or("brush"); - let simulate = match p.get("simulatePressure") { - None | Some(Value::Null) => false, - Some(v) => v.as_bool().ok_or_else(|| bad("path.stroke", "`simulatePressure` must be true or false"))?, - }; - if let Some(&(_, cmd)) = STROKE_PATH_TOOLS.iter().find(|(t, _)| *t == tool) { - let lines = vector::flatten_path(&path, 0.1); - return stroke_with_command(s, p, cmd, &lines, simulate); - } - let base = s.tools.brush.clone(); - let fg = s.tools.foreground; - let mut brush = photocraft_paint::BrushSettings { - size: f64p(p, "size").map_or(base.size, |v| v as f32), - hardness: f64p(p, "hardness").map_or(base.hardness, |v| v as f32), - opacity: f64p(p, "opacity").map_or(base.opacity, |v| (v / 100.0) as f32), - color: p.get("color").and_then(color).map_or(fg, |c| { - let v = c.to_rgb(); - [v[0], v[1], v[2], c.alpha] - }), - erase: tool == "eraser", - ..base - }; - // The path is the exact geometry: stroke smoothing (a hand-drawing aid) would cut its corners. - brush.smoothing.amount = 0.0; - match tool { - "pencil" => brush.hardness = 1.0, - "brush" | "eraser" => {} - o => { - let tools: Vec<&str> = ["brush", "pencil", "eraser"].into_iter().chain(STROKE_PATH_TOOLS.iter().map(|(t, _)| *t)).collect(); - return Err(bad("path.stroke", format!("unknown tool `{o}` ({})", tools.join("|")))); - } - } - crate::brush_cmds::validate_brush(&brush, "path.stroke")?; - let lines = vector::flatten_path(&path, 0.1); - let id = layer_id(s, p)?; - let bg = s.tools.background; - let dmg = s.edit("Stroke Path", |doc, _| { - let sel = doc.selection.clone(); - let locks = doc.effective_locks(id); - let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; - // Pixel and full locks (the layer's own or a parent group's) refuse the stroke, as Fill Path does (#2388). - if locks.pixels || locks.all { - return Err(EngineError::Other(format!("Could not complete your request because the layer \"{}\" is locked", l.name))); - } - let lock = locks.transparency; - let surf = l.surface_mut().ok_or_else(|| EngineError::Other("Stroke Path needs a pixel layer".into()))?; - let mut brush = brush.clone(); - if brush.erase && lock { - // Locked transparency (e.g. the Background): the Eraser paints the background colour (#76). - brush.erase = false; - brush.color = bg; - } - let mut dmg = Rect::EMPTY; - for pl in &lines { - let pts = stroke_points(&pl.pts, pl.closed, simulate); - if pts.is_empty() { - continue; - } - let r = photocraft_paint::apply_stroke(surf, &photocraft_paint::Stroke { brush: brush.clone(), points: pts }, sel.as_ref(), lock); - dmg = if dmg.is_empty() { r } else { dmg.union(&r) }; - } - Ok(dmg) - })?; - Ok(json!({ "damage": [dmg.x0, dmg.y0, dmg.width(), dmg.height()] })) -} - -// --------------------------------------------------------------------------- -// Vector masks -// --------------------------------------------------------------------------- - -fn vector_mask_info(s: &Session, id: LayerId) -> Result { - let d = s.active().ok_or(EngineError::NoDocument)?; - let l = d.doc.layer(id).ok_or(EngineError::NoLayer(id))?; - Ok(match (&l.vector_mask, &l.content) { - (Some(v), _) => { - json!({ "layer": id.0, "path": path_json(&v.path), "enabled": v.enabled, "linked": v.linked, "density": v.density * 100.0, "feather": v.feather }) - } - // A shape layer's path is its vector mask. - (None, LayerContent::Shape(sh)) => { - json!({ "layer": id.0, "path": path_json(&sh.path), "enabled": true, "linked": true, "shape": true, "density": sh.density * 100.0, "feather": sh.feather }) - } - (None, _) => json!({ "layer": id.0, "vectorMask": null }), - }) -} - -fn vector_mask_add(s: &mut Session, p: &Value, from_path: bool) -> Result { - const CMD: &str = "layer.vectorMask.add"; - let id = layer_id(s, p)?; - let mut path = match p.get("path") { - Some(v) => parse_path(v).map_err(|e| bad(CMD, e))?, - None if from_path || p.get("name").is_some() => { - let name = p.get("name").and_then(Value::as_str); - // Never fall back to the layer's own path here. - if is_work(name) { - s.active().and_then(|d| d.doc.work_path.clone()).ok_or_else(|| EngineError::Other("no work path".into()))? - } else { - resolve_path(s, name)? - } - } - None => Path::default(), - }; - if p.get("hide").and_then(Value::as_bool).unwrap_or(false) { - path.inverted = !path.inverted; - } - s.edit("Add Vector Mask", |doc, _| { - let locked = doc.effective_locks(id).all; - let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; - if matches!(l.content, LayerContent::Shape(_)) { - return Err(EngineError::Other("a shape layer's path is already its vector mask".into())); - } - if locked { - return Err(EngineError::Other(format!("layer \"{}\" is locked", l.name))); - } - crate::extra_cmds::background_to_layer(doc, id); - doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?.vector_mask = Some(VectorMask::new(path)); - Ok(()) - })?; - vector_mask_info(s, id) -} - -fn vector_mask_edit(s: &mut Session, p: &Value) -> Result { - const CMD: &str = "layer.vectorMask.edit"; - let id = layer_id(s, p)?; - let path = p.get("path").map(parse_path).transpose().map_err(|e| bad(CMD, e))?; - // Same range as a pixel mask's feather (`layer.layerMask.edit`), checked before any edit (#4201). - let feather = p - .get("feather") - .map(|v| { - v.as_f64() - .filter(|n| n.is_finite() && (0.0..=1000.0).contains(n)) - .map(|n| n as f32) - .ok_or_else(|| bad(CMD, "`feather` must be a finite number within 0..1000")) - }) - .transpose()?; - let density = p - .get("density") - .map(|v| { - v.as_f64() - .filter(|n| n.is_finite() && (0.0..=100.0).contains(n)) - .map(|n| (n / 100.0) as f32) - .ok_or_else(|| bad(CMD, "`density` must be a finite number within 0..100 (%)")) - }) - .transpose()?; - // A shape layer's path is its vector mask (Photoshop's Properties › Masks): Density and - // Feather soften its fill; the path itself is edited with the shape and path commands. - if s.active().and_then(|d| d.doc.layer(id)).is_some_and(|l| matches!(l.content, LayerContent::Shape(_)) && l.vector_mask.is_none()) { - if let Some(k) = ["path", "enabled", "linked", "invert"].into_iter().find(|k| p.get(*k).is_some()) { - return Err(bad(CMD, format!("`{k}`: a shape layer's vector mask is its path; only `density` and `feather` apply"))); - } - if density.is_none() && feather.is_none() { - return vector_mask_info(s, id); - } - with_shape(s, id, "Edit Vector Mask", |sh, _| { - if let Some(d) = density { - sh.density = d; - } - if let Some(f) = feather { - sh.feather = f; - } - Ok(()) - })?; - return vector_mask_info(s, id); - } - s.edit("Edit Vector Mask", |doc, _| { - let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; - let vm = l.vector_mask.as_mut().ok_or_else(|| EngineError::Other("layer has no vector mask".into()))?; - if let Some(pth) = path { - vm.path = pth; - } - if let Some(b) = p.get("enabled").and_then(Value::as_bool) { - vm.enabled = b; - } - if let Some(b) = p.get("linked").and_then(Value::as_bool) { - vm.linked = b; - } - if let Some(d) = density { - vm.density = d; - } - if let Some(f) = feather { - vm.feather = f; - } - if let Some(b) = p.get("invert").and_then(Value::as_bool) - && b - { - vm.path.inverted = !vm.path.inverted; - } - Ok(()) - })?; - vector_mask_info(s, id) -} - -fn vector_mask_delete(s: &mut Session, p: &Value) -> Result { - let id = layer_id(s, p)?; - s.edit("Delete Vector Mask", |doc, _| { - let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; - l.vector_mask.take().map(|_| ()).ok_or_else(|| EngineError::Other("layer has no vector mask".into())) - })?; - Ok(Value::Null) -} - -/// Layer › Rasterize › Vector Mask: multiplies the vector mask into the pixel mask. When a feather -/// (either mask's) or the pixel mask's density shapes the rendered edge, the pixel mask instead -/// becomes exactly what the compositor showed, with those settings baked in (#992). -fn vector_mask_rasterize(s: &mut Session, p: &Value) -> Result { - use photocraft_compose::masks::{combined_mask, feather_sigma}; - let id = layer_id(s, p)?; - s.edit("Rasterize Vector Mask", |doc, _| { - let area = doc.bounds(); - let depth = doc.depth; - let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; - let soft = l.vector_mask.as_ref().is_some_and(|v| v.enabled) - && (l.vector_mask.as_ref().is_some_and(|v| feather_sigma(v.feather) > 0.0) - || l.mask.as_ref().is_some_and(|m| m.enabled && (feather_sigma(m.feather) > 0.0 || m.density < 1.0))); - let shown = if soft { combined_mask(l, area) } else { None }; - let vm = l.vector_mask.take().ok_or_else(|| EngineError::Other("layer has no vector mask".into()))?; - let mut mask = l.mask.take().unwrap_or_else(|| { - let mut m = photocraft_doc::LayerMask::reveal_all(); - m.surface = - photocraft_raster::Surface::with_default(photocraft_color::PixelFormat::new(photocraft_color::ColorMode::Grayscale, depth, false), &[1.0]); - m - }); - if let Some(shown) = shown { - // Past the canvas the pixel mask keeps its own (density-applied) default, as below. - let d = mask.surface.default_pixel().first().copied().unwrap_or(1.0); - let mut surface = photocraft_raster::Surface::with_default(mask.surface.format(), &[1.0 - mask.density * (1.0 - d)]); - surface.write_region(area, &shown.read_region(area)); - surface.prune(); - (mask.surface, mask.feather, mask.density) = (surface, 0.0, 1.0); - l.mask = Some(mask); - return Ok(()); - } - let vals = vector::vector_mask_values(&vm, area); - // Outside the canvas the vector mask is 0 unless it is empty/inverted; keep the old default there. - let old = mask.surface.read_region(area); - let merged: Vec = old.iter().zip(&vals).map(|(a, b)| a * b).collect(); - mask.surface.write_region(area, &merged); - mask.surface.prune(); - l.mask = Some(mask); - Ok(()) - })?; - Ok(json!({ "layer": id.0 })) -} - -/// `p` with `key` set (for alias commands). -fn with(p: &Value, key: &str, v: Value) -> Value { - let mut o = if p.is_object() { p.clone() } else { json!({}) }; - o[key] = v; - o -} - -fn toggle_vector_mask(s: &mut Session, p: &Value, key: &str) -> Result { - let id = layer_id(s, p)?; - let cur = { - let d = s.active().ok_or(EngineError::NoDocument)?; - let vm = d.doc.layer(id).ok_or(EngineError::NoLayer(id))?.vector_mask.as_ref().ok_or_else(|| EngineError::Other("layer has no vector mask".into()))?; - if key == "enabled" { vm.enabled } else { vm.linked } - }; - let v = p.get(key).and_then(Value::as_bool).unwrap_or(!cur); - vector_mask_edit(s, &json!({ "layer": id.0, key: v })) -} - -/// Traces the exact coverage of the shape's path back into plain outlines. -fn merge_components(s: &mut Session, p: &Value) -> Result { - let tol = f64p(p, "tolerance").unwrap_or(0.1).clamp(0.05, 10.0); - if let Some(ids) = combine_targets(s, p, &["layer"])? { - return merge_shape_layers(s, &ids, None, "Merge Shape Components", Some(tol)); - } - let id = layer_id(s, p)?; - with_shape(s, id, "Merge Shape Components", |sh, _| bake_components(sh, tol))?; - shape_info(s, id) -} - -/// Bakes `sh`'s path operations into plain combined outlines, traced from the exact coverage. -fn bake_components(sh: &mut ShapeLayer, tol: f64) -> Result<()> { - // Trace at 4× resolution so the fitted outline follows the anti-aliased edge closely. - const K: f64 = 4.0; - let up = sh.path.transform(&Affine::scale(K)); - let r = vector::fill_rasterizer(&up, vector::DEFAULT_TOLERANCE); - let Some(b) = r.pixel_bounds() else { - sh.path.subpaths.clear(); - return Ok(()); - }; - let b = b.inflate(2); - if u64::from(b.width()) * u64::from(b.height()) > 400_000_000 { - return Err(EngineError::Other("shape too large to merge".into())); - } - let cov = r.render(b); - let traced = vector::trace::trace_mask(&cov, b, 0.0, tol * K); - sh.path = traced.transform(&Affine::scale(1.0 / K)); - sh.live = None; - sh.psd_raw = None; - Ok(()) -} - -/// The shape layers Layer › Combine Shapes merges into one: with none of the `narrow` params -/// given and two or more shape layers selected, those layers bottom-to-top (other selected layers -/// are left alone). `None` keeps the single-layer behaviour (acting on one layer's components). -fn combine_targets(s: &Session, p: &Value, narrow: &[&str]) -> Result>> { - if narrow.iter().any(|k| p.get(*k).is_some()) { - return Ok(None); - } - let d = s.active().ok_or(EngineError::NoDocument)?; - let sel = d.selected_layers(); - let ids = crate::layer_multi_cmds::top_level(&d.doc, &sel); - let ids: Vec = ids.into_iter().filter(|id| d.doc.layer(*id).is_some_and(|l| matches!(l.content, LayerContent::Shape(_)))).collect(); - Ok((ids.len() > 1).then_some(ids)) -} - -/// Layer › Combine Shapes with several shape layers selected: Photoshop merges them into the -/// top-most one. The bottom layer's components keep their operations; every component of the -/// layers above takes `op` (front shapes subtract, intersect… in stacking order), or, with no -/// `op` (Merge Shape Components), keeps its own with each layer's first component combined, and -/// the result is then baked with tolerance `bake`. The other layers are removed; one history step. -fn merge_shape_layers(s: &mut Session, ids: &[LayerId], op: Option, label: &str, bake: Option) -> Result { - let (&keep, _) = ids.split_last().ok_or_else(|| EngineError::Other("Combine Shapes needs two or more shape layers".into()))?; - if let Some(st) = s.active() { - for id in ids { - let locks = st.doc.effective_locks(*id); - if locks.all || locks.pixels { - return Err(EngineError::Other("a selected shape layer is locked".into())); - } - } - } - s.edit(label, |doc, active| { - let mut path: Option = None; - for id in ids { - let l = doc.layer(*id).ok_or(EngineError::NoLayer(*id))?; - let LayerContent::Shape(sh) = &l.content else { - return Err(EngineError::Other(format!("layer {} is not a shape layer", id.0))); - }; - let Some(acc) = path.as_mut() else { - path = Some(sh.path.clone()); - continue; - }; - for (j, sp) in sh.path.subpaths.iter().enumerate() { - let mut sp = sp.clone(); - sp.op = match op { - Some(op) => op, - None if j == 0 => PathOp::Combine, - None => sp.op, - }; - acc.subpaths.push(sp); - } - } - let path = path.ok_or_else(|| EngineError::Other("Combine Shapes needs two or more shape layers".into()))?; - let snapshot = doc.clone(); - let l = doc.layer_mut(keep).ok_or(EngineError::NoLayer(keep))?; - let LayerContent::Shape(sh) = &mut l.content else { - return Err(EngineError::Other(format!("layer {} is not a shape layer", keep.0))); - }; - let mut merged = ShapeLayer { path, live: None, psd_raw: None, cache: None, ..sh.clone() }; - if let Some(tol) = bake { - bake_components(&mut merged, tol)?; - } - vector::flatten::validate_shape(&merged.path, merged.stroke.as_ref()).map_err(|e| bad(label, e))?; - refresh_shape(&snapshot, &mut merged); - *sh = merged; - for id in ids.iter().filter(|id| **id != keep) { - doc.remove(*id); - } - *active = Some(keep); - Ok(()) - })?; - crate::layer_multi_cmds::reselect(s, vec![keep], Some(keep)); - shape_info(s, keep) -} - -/// Layer › Combine Shapes › Unite / Subtract Front Shape / Intersect / Exclude: merges the -/// selected shape layers with `op` ([`merge_shape_layers`]), or with one layer (or an explicit -/// `layer`/`subpath`) sets the operation of that layer's components (`shape.edit`'s `op`). -fn combine_shapes(s: &mut Session, p: &Value, op: &str, label: &str) -> Result { - if let Some(ids) = combine_targets(s, p, &["layer", "subpath"])? { - let op = op_from(op).ok_or_else(|| EngineError::Other(format!("unknown op `{op}`")))?; - return merge_shape_layers(s, &ids, Some(op), label, None); - } - shape_edit(s, &with(p, "op", json!(op))) -} - -fn selection_to_shape(s: &mut Session, p: &Value) -> Result { - let tol = f64p(p, "tolerance").or_else(|| f64p(p, "simplifyTolerance")).unwrap_or(2.0).clamp(0.5, 10.0); - let d = s.active().ok_or(EngineError::NoDocument)?; - let area = d.doc.bounds(); - let mask = sel::mask_from_surface(d.doc.selection.as_ref(), area); - let path = vector::trace::trace_mask(&mask, area, 0.0, tol); - let mut q = json!({ "kind": "path", "path": path_json(&path) }); - for k in ["fill", "name", "stroke"] { - if let Some(v) = p.get(k) { - q[k] = v.clone(); - } - } - shape_create(s, &q) -} - -// --------------------------------------------------------------------------- -// Specs -// --------------------------------------------------------------------------- - -/// Params of the Layer › Combine Shapes operations. -const COMBINE_PARAMS: &str = r##"{"layer":id?,"subpath":index? (default all but the first)} (no layer/subpath and two or more shape layers selected: merges them into the top-most, whose components above the bottom layer's take the operation)"##; - -pub(crate) const PATH_FORM: &str = r##"path: {"subpaths":[{"closed":bool=true,"op":"combine|subtract|intersect|exclude","knots":[[x,y] | {"anchor":[x,y],"in":[x,y],"out":[x,y],"smooth":bool}]}],"fillRule":"nonzero|evenodd","inverted":bool}"##; - -macro_rules! spec { - ($id:literal, $label:literal, [$($m:literal),*], $params:expr, $en:expr, $run:expr) => { - CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: None, params: $params, enabled: $en, run: $run, journal: true } - }; -} - -pub(crate) fn leak(s: String) -> &'static str { - Box::leak(s.into_boxed_str()) -} - -pub fn specs() -> Vec { - let stroke = r##""stroke":{"width":px,"color":"#rrggbb"|fill,"opacity":0..100,"align":"inside|center|outside","cap":"butt|round|square","join":"miter|round|bevel","miterLimit":n,"dashes":[multiples of width],"dashOffset":n}|null"##; - let fill = r##""fill":"#rrggbb"|[r,g,b,a]|{"gradient":{"stops":[[t,"#hex"|[r,g,b,a]|stored Color]],"angle":deg,"scale":%,"style":"linear|radial|angle|reflected|diamond","reverse":bool,"opacityStops":[[t,0..1]]?,"midpoints":[0..1]?,"offset":[x,y]?,"dither":bool?,"align":bool?}}|{"pattern":name}|null (no fill)"##; - vec![ - spec!( - "shape.create", - "New Shape Layer", - ["Layer", "New"], - leak(format!( - r##"{{"kind":"rect|roundedRect|ellipse|polygon|star|line|path"="rect","rect":[x,y,w,h] (rect/roundedRect/ellipse/polygon/star),"radii":[tl,tr,br,bl]|r (roundedRect=10),"sides":3..100=5,"starRatio":0..1 (star=0.5),"cornerRadius":px=0 (polygon/star: rounds every vertex; the Triangle tool is a 3-sided polygon),"from":[x,y],"to":[x,y],"weight":px=1 (line),"path":{{…}} (kind path),{fill}=foreground,{stroke}=none,"name":str?,"addTo":layerId? + "op":"combine|subtract|intersect|exclude" (append to an existing shape layer)}} → shape.info. {PATH_FORM}"## - )), - has_doc, - shape_create - ), - spec!( - "shape.edit", - "Edit Shape", - [], - leak(format!( - r##"{{"layer":id?,"path":{{…}}? (replaces; drops live shape),"kind":str?,"rect":[x,y,w,h]?,"radii":[tl,tr,br,bl]|r?,"sides":n?,"starRatio":r?,"cornerRadius":px?,"from":[x,y]?,"to":[x,y]?,"weight":px? (live-shape params regenerate the path),"move":[dx,dy]?,"transform":[a,b,c,d,e,f]?,"op":"combine|…"? + "subpath":index? (default all but the first),"fillRule":"nonzero|evenodd"?,{fill}?,{stroke}? (merged into the current stroke),"name":str?}} → shape.info"## - )), - has_layer, - shape_edit - ), - CommandSpec { - id: "shape.info", - label: "Shape Layer Info", - menu: &[], - shortcut: None, - params: r##"{"layer":id?} → {layer,name,kind,path,fill,stroke,live,bounds:[x,y,w,h]}"##, - enabled: has_layer, - run: |s, p| { - let id = layer_id(s, p)?; - shape_info(s, id) - }, - journal: false, - }, - spec!("shape.rasterize", "Rasterize Shape", ["Layer", "Rasterize"], r##"{"layer":id?}"##, has_layer, shape_rasterize), - CommandSpec { - id: "path.list", - label: "List Paths", - menu: &[], - shortcut: None, - params: r##"{} → {paths:[{name,knots,subpaths}],workPath,clippingPath,layerPath (active layer's shape path / vector mask)}"##, - enabled: has_doc, - run: |s, _| paths_list(s), - journal: false, - }, - CommandSpec { - id: "path.info", - label: "Path Info", - menu: &[], - shortcut: None, - params: r##"{"name":str|"work"|"layer"="work"} → {name,path}"##, - enabled: has_doc, - run: |s, p| { - let name = p.get("name").and_then(Value::as_str); - let path = resolve_path(s, name)?; - Ok(json!({ "name": name.unwrap_or("work"), "path": path_json(&path) })) - }, - journal: false, - }, - spec!( - "path.set", - "Set Path", - [], - leak(format!( - r##"{{"name":str|"work"="work","path":{{…}},"op":"combine|subtract|intersect|exclude"? (append to the existing path with this op instead of replacing)}}. {PATH_FORM}"## - )), - has_doc, - path_set - ), - spec!("path.delete", "Delete Path", [], r##"{"name":str|"work"="work"}"##, has_doc, path_delete), - spec!( - "path.transform", - "Free Transform Path", - [], - r##"{"name":str|"work"|"layer"="work","layer":id? (with layer target),"matrix":[a,b,c,d,e,f] | "quad":[[x,y]×4] (Distort/Perspective: where the frame's corners go, clockwise from top-left) | "style"|"mesh"|"warp":… (Warp, as edit.transform.warp) | "translateX":px?,"translateY":px?,"scaleX":factor?,"scaleY":factor?,"angle":degrees?,"rect":[x0,y0,x1,y1]? (the quad's or warp's frame; default = path control bounds)} (numeric transforms pivot on path bounds center)"##, - has_doc, - path_transform - ), - spec!( - "path.clippingPath.set", - "Clipping Path", - [], - r##"{"name":savedPathName,"flatness":0..100=0} (PSD export clipping path)"##, - has_doc, - clipping_path_set - ), - spec!("path.clippingPath.clear", "Clear Clipping Path", [], r##"{}"##, has_doc, clipping_path_clear), - spec!("path.style.copyFill", "Copy Fill", [], r##"{} (copies active shape layer fill)"##, has_shape_fill, copy_shape_fill), - spec!("path.style.copyStroke", "Copy Complete Stroke", [], r##"{} (copies active shape layer stroke)"##, has_shape_stroke, copy_shape_stroke), - spec!( - "path.style.pasteFill", - "Paste Fill", - [], - r##"{"layer":id?} (pastes copied fill onto active shape layer)"##, - can_paste_shape_fill, - paste_shape_fill - ), - spec!( - "path.style.pasteStroke", - "Paste Complete Stroke", - [], - r##"{"layer":id?} (pastes copied stroke onto active shape layer)"##, - can_paste_shape_stroke, - paste_shape_stroke - ), - spec!("path.rename", "Rename Path", [], r##"{"name":str|"work"="work","to":str} (renaming the work path saves it)"##, has_doc, path_rename), - // ⌘↩ / Ctrl+Enter, as in Photoshop (the UI loads the path selected in the Paths panel, #306). - CommandSpec { - id: "path.toSelection", - label: "Make Selection from Path", - menu: &[], - shortcut: Some("Cmd+Enter"), - params: r##"{"name":str|"work"|"layer"="work","feather":px=0,"antiAlias":bool=true,"mode":"replace|add|subtract|intersect"="replace"}"##, - enabled: has_doc, - run: path_to_selection, - journal: true, - }, - spec!("select.toWorkPath", "Make Work Path", [], r##"{"tolerance":0.5..10 px=2} → {subpaths,knots}"##, has_selection, select_to_work_path), - spec!( - "path.fill", - "Fill Path", - [], - r##"{"name":str|"work"|"layer"="work","layer":id? (pixel layer, default active),"color":"#rrggbb"=foreground,"opacity":0..100=100,"mode":"normal|multiply|…"="normal","feather":px=0,"antiAlias":bool=true}"##, - has_layer, - path_fill - ), - spec!( - "path.stroke", - "Stroke Path", - [], - r##"{"name":str|"work"|"layer"="work","layer":id? (pixel layer),"tool":"brush|pencil|eraser|backgroundEraser|cloneStamp|patternStamp|healingBrush|spotHealingBrush|historyBrush|blur|sharpen|smudge|dodge|burn|sponge|colorReplacement|mixerBrush"="brush","simulatePressure":bool=false (taper both ends when the brush follows pen pressure),"size":0.5..5000 px?,"hardness":0..1?,"opacity":0..100?,"color":"#rrggbb"=foreground} (current brush settings otherwise; tools past the Eraser run their paint.* command along the path and take its params)"##, - has_layer, - path_stroke - ), - spec!( - "layer.vectorMask.add", - "Add Vector Mask", - ["Layer", "Vector Mask"], - r##"{"layer":id?,"path":{…}? | "name":str|"work"? (copy a document path),"hide":bool=false (Hide All = inverted)} → vector mask info. Without a path the mask reveals all."##, - has_layer, - |s, p| vector_mask_add(s, p, false) - ), - spec!( - "layer.vectorMask.fromPath", - "Vector Mask from Current Path", - ["Layer", "Vector Mask"], - r##"{"layer":id?,"name":str|"work"="work"}"##, - has_layer, - |s, p| vector_mask_add(s, p, true) - ), - spec!( - "layer.vectorMask.edit", - "Edit Vector Mask", - [], - leak(format!( - r##"{{"layer":id?,"path":{{…}}?,"enabled":bool?,"linked":bool?,"density":0..100?,"feather":0..1000? (pixels),"invert":true?}}. On a shape layer (whose path is its vector mask) only density and feather apply: they soften its fill, which shows beyond the path at 100 − density %. {PATH_FORM}"## - )), - has_layer, - vector_mask_edit - ), - spec!("layer.vectorMask.delete", "Delete Vector Mask", ["Layer", "Vector Mask"], r##"{"layer":id?}"##, has_layer, vector_mask_delete), - spec!( - "layer.rasterize.vectorMask", - "Rasterize Vector Mask", - [], - r##"{"layer":id?} (multiplied into the layer mask)"##, - has_layer, - vector_mask_rasterize - ), - // Menu ids of Photoshop's Layer › Vector Mask / Rasterize / Combine Shapes. - spec!("layer.vectorMask.revealAll", "Vector Mask: Reveal All", [], r##"{"layer":id?}"##, has_layer, |s, p| vector_mask_add( - s, - &with(p, "hide", json!(false)), - false - )), - spec!("layer.vectorMask.hideAll", "Vector Mask: Hide All", [], r##"{"layer":id?}"##, has_layer, |s, p| vector_mask_add( - s, - &with(p, "hide", json!(true)), - false - )), - spec!("layer.vectorMask.currentPath", "Vector Mask: Current Path", [], r##"{"layer":id?,"name":str|"work"="work"}"##, has_layer, |s, p| { - vector_mask_add(s, p, true) - }), - spec!("layer.vectorMask.enabled", "Enable Vector Mask", [], r##"{"layer":id?,"enabled":bool? (default: toggle)}"##, has_layer, |s, p| { - toggle_vector_mask(s, p, "enabled") - }), - spec!("layer.vectorMask.linked", "Link Vector Mask", [], r##"{"layer":id?,"linked":bool? (default: toggle)}"##, has_layer, |s, p| toggle_vector_mask( - s, p, "linked" - )), - // Without `layer`, every selected shape layer (the shared Rasterize logic calls back here with one). - spec!("layer.rasterize.shape", "Rasterize Shape", [], r##"{"layer":id?} (no layer: every selected shape layer)"##, has_layer, |s, p| { - if p.get("layer").is_some() { shape_rasterize(s, p) } else { crate::extra_cmds::rasterize(s, p, Some("shape")) } - }), - // With two or more shape layers selected (and no `layer`/`subpath`), these merge them into - // the top-most one, as in Photoshop; with one, they set the operation of its components. - spec!("layer.combineShapes.unite", "Unite Shapes", [], COMBINE_PARAMS, has_layer, |s, p| combine_shapes(s, p, "combine", "Unite Shapes")), - spec!("layer.combineShapes.subtractFrontShape", "Subtract Front Shape", [], COMBINE_PARAMS, has_layer, |s, p| combine_shapes( - s, - p, - "subtract", - "Subtract Front Shape" - )), - spec!("layer.combineShapes.intersectShapeAreas", "Intersect Shape Areas", [], COMBINE_PARAMS, has_layer, |s, p| combine_shapes( - s, - p, - "intersect", - "Intersect Shape Areas" - )), - spec!("layer.combineShapes.excludeOverlappingShapes", "Exclude Overlapping Shapes", [], COMBINE_PARAMS, has_layer, |s, p| { - combine_shapes(s, p, "exclude", "Exclude Overlapping Shapes") - }), - spec!( - "layer.combineShapes.mergeShapeComponents", - "Merge Shape Components", - [], - r##"{"layer":id?,"tolerance":px=0.1} (bakes the path operations into plain combined outlines, traced from the exact coverage; no layer and several shape layers selected: merges them into the top-most first)"##, - has_layer, - merge_components - ), - spec!("select.convertToShape", "Convert to Shape", [], r##"{"tolerance":0.5..10 px=2} → shape.info"##, has_selection, selection_to_shape), - CommandSpec { - id: "layer.vectorMask.info", - label: "Vector Mask Info", - menu: &[], - shortcut: None, - params: r##"{"layer":id?} → {layer,path,enabled,linked,density,feather}"##, - enabled: has_layer, - run: |s, p| { - let id = layer_id(s, p)?; - vector_mask_info(s, id) - }, - journal: false, - }, - ] -} - -#[cfg(test)] -mod tests; diff --git a/crates/engine/src/web_cmds.rs b/crates/engine/src/web_cmds.rs deleted file mode 100644 index 121cfe36b8..0000000000 --- a/crates/engine/src/web_cmds.rs +++ /dev/null @@ -1,1606 +0,0 @@ -//! File › Export › Save for Web (Legacy), File › Export › Export Preferences, the Quick Export -//! pipeline that honours them, and File › Generate › Image Assets (Photoshop's Generator). -//! -//! Save for Web optimises the flattened (optionally resized, sRGB-converted) image as GIF, -//! PNG-8, PNG-24, JPEG or WBMP, per slice, into a folder with an optional HTML table; without an -//! output it only reports the optimised size (the dialog's 2-Up/4-Up annotations). Colour -//! reduction and dithering reuse `algo::quantize`; GIF/WBMP/progressive JPEG writers live in -//! `codecs::web`. -//! -//! Image Assets implements the naming grammar of Adobe's public Generator documentation: a -//! layer or group named `foo.png`, `200% foo@2x.png, 48x48 icons/foo.png8`, `photo.jpg80%`, -//! `?x100 thumb.gif` is exported into `-assets/` whenever the document is saved while -//! the feature is on; a `default` layer (`default 50% low/ + 200% @2x`) adds variants. - -use photocraft_algo::quantize::{self, Dither, Forced, PaletteKind}; -use photocraft_doc::slices::{self, ResolvedSlice, SliceKind}; -use photocraft_doc::{DocId, Document, LayerContent, LayerId}; -use photocraft_geom::Rect; -use serde_json::{Value, json}; - -use crate::commands::CommandSpec; -use crate::file_cmds::{is_windows_device_name, join, native_doc, portable_device_name, stem, write_file}; -use crate::{EngineError, Result, Session}; - -fn bad(cmd: &str, msg: impl Into) -> EngineError { - EngineError::BadParams { cmd: cmd.into(), msg: msg.into() } -} -fn other(e: impl std::fmt::Display) -> EngineError { - EngineError::Other(e.to_string()) -} - -// ---------- settings ---------- - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum WebFormat { - Gif, - Png8, - Png24, - Jpeg, - Wbmp, -} - -impl WebFormat { - pub fn from_id(s: &str) -> Option { - Some(match s.to_ascii_lowercase().as_str() { - "gif" => WebFormat::Gif, - "png8" | "png-8" => WebFormat::Png8, - "png24" | "png-24" | "png" | "png32" => WebFormat::Png24, - "jpeg" | "jpg" => WebFormat::Jpeg, - "wbmp" => WebFormat::Wbmp, - _ => return None, - }) - } - pub fn ext(self) -> &'static str { - match self { - WebFormat::Gif => "gif", - WebFormat::Png8 | WebFormat::Png24 => "png", - WebFormat::Jpeg => "jpg", - WebFormat::Wbmp => "wbmp", - } - } - pub fn indexed(self) -> bool { - matches!(self, WebFormat::Gif | WebFormat::Png8) - } -} - -/// Which metadata Save for Web embeds (JPEG only, like Photoshop's legacy exporter). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum WebMetadata { - None, - Copyright, - CopyrightAndContact, - /// All the XMP, none of the photo's EXIF (camera, date taken, GPS). - AllExceptCameraInfo, - /// All the XMP and the photo's EXIF. - All, -} - -/// One optimisation preset (the right-hand side of the Save for Web dialog). -#[derive(Clone, Debug, PartialEq)] -pub struct WebSettings { - pub format: WebFormat, - pub palette: PaletteKind, - pub colors: usize, - /// Fixed opaque source palette in index order. - pub color_table: Option>, - /// Replacements applied after quantization, preserving pixel indices. - pub color_table_edits: std::collections::BTreeMap, - pub dither: Dither, - /// 0..=1. - pub dither_amount: f32, - pub transparency: bool, - /// Edge / background colour (0..=1 RGB); None = no matte (hard alpha threshold). - pub matte: Option<[f32; 3]>, - pub interlaced: bool, - /// Web Snap: palette entries within this distance (0..=1 of the channel range) snap to the - /// web-safe cube. - pub web_snap: f32, - /// JPEG quality 0..=100. - pub quality: u8, - pub progressive: bool, - pub optimized: bool, - pub embed_icc: bool, - pub metadata: WebMetadata, - pub convert_to_srgb: bool, -} - -impl Default for WebSettings { - fn default() -> Self { - WebSettings { - format: WebFormat::Png24, - palette: PaletteKind::Selective, - colors: 256, - color_table: None, - color_table_edits: Default::default(), - dither: Dither::Diffusion, - dither_amount: 0.88, - transparency: true, - matte: Some([1.0, 1.0, 1.0]), - interlaced: false, - web_snap: 0.0, - quality: 60, - progressive: false, - optimized: true, - embed_icc: false, - metadata: WebMetadata::Copyright, - convert_to_srgb: true, - } - } -} - -fn hex3(s: &str) -> Option<[f32; 3]> { - let s = s.trim_start_matches('#'); - let b = |i: usize| u8::from_str_radix(s.get(i..i + 2)?, 16).ok().map(|v| f32::from(v) / 255.0); - (s.len() == 6).then_some(())?; - Some([b(0)?, b(2)?, b(4)?]) -} - -impl WebSettings { - /// Settings from command parameters (missing keys keep the defaults; Photoshop's preset - /// names such as "GIF 128 Dithered" or "JPEG High" are accepted as `"preset"`). - /// - /// Without a preset there is no matte, as in Photoshop's scripted Save for Web - /// (`ExportOptionsSaveForWeb` left at its defaults): a GIF or PNG-8 keeps the colour of its - /// partly transparent pixels instead of lightening them towards white (#4115). Formats - /// without transparency still go over white. - pub fn from_params(p: &Value, cmd: &str) -> Result { - let mut st = WebSettings { matte: None, ..WebSettings::default() }; - if let Some(preset) = p.get("preset").and_then(Value::as_str) { - st = preset_settings(preset).ok_or_else(|| bad(cmd, format!("unknown preset `{preset}`")))?; - } - let s = |k: &str| p.get(k).and_then(Value::as_str); - if let Some(f) = s("format") { - st.format = WebFormat::from_id(f).ok_or_else(|| bad(cmd, format!("unknown format `{f}` (gif|png8|png24|jpeg|wbmp)")))?; - } - if let Some(k) = s("palette") { - st.palette = match k { - "restrictive" | "web" => PaletteKind::Web, - k => PaletteKind::from_id(k).ok_or_else(|| { - bad(cmd, format!("unknown palette `{k}` (perceptual|selective|adaptive|restrictive|exact|systemMac|systemWindows|uniform)")) - })?, - }; - } - if let Some(n) = crate::commands::int(p, "colors").filter(|v| *v > 0).map(|v| v as u64) { - st.colors = (n as usize).clamp(2, 256); - } - if let Some(d) = s("dither") { - st.dither = match d { - "none" | "noDither" => Dither::None, - "diffusion" => Dither::Diffusion, - "pattern" => Dither::Pattern, - "noise" => Dither::Noise, - d => return Err(bad(cmd, format!("unknown dither `{d}` (none|diffusion|pattern|noise)"))), - }; - } - if let Some(a) = p.get("ditherAmount").and_then(Value::as_f64) { - st.dither_amount = (a as f32 / 100.0).clamp(0.0, 1.0); - } - if let Some(b) = p.get("transparency").and_then(Value::as_bool) { - st.transparency = b; - } - match s("matte") { - Some("none") => st.matte = None, - Some(c) => st.matte = Some(hex3(c).ok_or_else(|| bad(cmd, "matte is \"none\" or \"#rrggbb\""))?), - None => {} - } - for (k, slot) in [ - ("interlaced", &mut st.interlaced), - ("progressive", &mut st.progressive), - ("optimized", &mut st.optimized), - ("embedIcc", &mut st.embed_icc), - ("convertToSrgb", &mut st.convert_to_srgb), - ] { - if let Some(b) = p.get(k).and_then(Value::as_bool) { - *slot = b; - } - } - if let Some(w) = p.get("webSnap").and_then(Value::as_f64) { - st.web_snap = (w as f32 / 100.0).clamp(0.0, 1.0); - } - if let Some(q) = p.get("quality").and_then(Value::as_f64) { - st.quality = q.clamp(0.0, 100.0).round() as u8; - } - if let Some(m) = s("metadata") { - st.metadata = match m { - "none" => WebMetadata::None, - "copyright" => WebMetadata::Copyright, - "copyrightAndContact" | "contact" => WebMetadata::CopyrightAndContact, - "allExceptCameraInfo" => WebMetadata::AllExceptCameraInfo, - "all" => WebMetadata::All, - m => return Err(bad(cmd, format!("unknown metadata `{m}` (none|copyright|copyrightAndContact|allExceptCameraInfo|all)"))), - }; - } - if let Some(table) = p.get("colorTable") { - let table = table.as_array().filter(|a| (1..=256).contains(&a.len())).ok_or_else(|| bad(cmd, "colorTable must contain 1–256 #rrggbb colours"))?; - st.color_table = Some( - table - .iter() - .map(|v| v.as_str().and_then(hex3).map(|c| c.map(to8)).ok_or_else(|| bad(cmd, "colorTable entries must be #rrggbb colours"))) - .collect::>>()?, - ); - } - if let Some(edits) = p.get("colorTableEdits") { - let edits = edits - .as_object() - .filter(|m| m.len() <= 256) - .ok_or_else(|| bad(cmd, "colorTableEdits must be an object of palette indices to #rrggbb colours"))?; - let table = st.color_table.as_ref().ok_or_else(|| bad(cmd, "colorTableEdits requires colorTable"))?; - for (index, value) in edits { - let index = index.parse::().ok().filter(|i| *i < table.len()).ok_or_else(|| bad(cmd, "colorTableEdits index is outside colorTable"))?; - let color = value.as_str().and_then(hex3).map(|c| c.map(to8)).ok_or_else(|| bad(cmd, "colorTableEdits values must be #rrggbb colours"))?; - st.color_table_edits.insert(index, color); - } - } - Ok(st) - } -} - -impl WebSettings { - /// The settings as command parameters (the inverse of [`WebSettings::from_params`]). - pub fn to_params(&self) -> Value { - let format = match self.format { - WebFormat::Gif => "gif", - WebFormat::Png8 => "png8", - WebFormat::Png24 => "png24", - WebFormat::Jpeg => "jpeg", - WebFormat::Wbmp => "wbmp", - }; - let palette = match self.palette { - PaletteKind::Exact => "exact", - PaletteKind::SystemMac => "systemMac", - PaletteKind::SystemWindows => "systemWindows", - PaletteKind::Web => "restrictive", - PaletteKind::Uniform => "uniform", - PaletteKind::Perceptual => "perceptual", - PaletteKind::Selective => "selective", - PaletteKind::Adaptive => "adaptive", - }; - let dither = match self.dither { - Dither::None => "none", - Dither::Diffusion => "diffusion", - Dither::Pattern => "pattern", - Dither::Noise => "noise", - }; - let metadata = match self.metadata { - WebMetadata::None => "none", - WebMetadata::Copyright => "copyright", - WebMetadata::CopyrightAndContact => "copyrightAndContact", - WebMetadata::AllExceptCameraInfo => "allExceptCameraInfo", - WebMetadata::All => "all", - }; - let matte = self.matte.map_or("none".to_string(), |c| format!("#{:02x}{:02x}{:02x}", to8(c[0]), to8(c[1]), to8(c[2]))); - let mut p = json!({"format": format, "palette": palette, "colors": self.colors, "dither": dither, "ditherAmount": (self.dither_amount * 100.0).round(), "transparency": self.transparency, "matte": matte, "interlaced": self.interlaced, "webSnap": (self.web_snap * 100.0).round(), "quality": self.quality, "progressive": self.progressive, "optimized": self.optimized, "embedIcc": self.embed_icc, "metadata": metadata, "convertToSrgb": self.convert_to_srgb}); - if let Some(table) = &self.color_table { - p["colorTable"] = json!(table.iter().map(|c| rgb_hex(*c)).collect::>()); - } - if !self.color_table_edits.is_empty() { - p["colorTableEdits"] = - json!(self.color_table_edits.iter().map(|(i, c)| (i.to_string(), rgb_hex(*c))).collect::>()); - } - p - } -} - -/// A palette colour in command/control-channel notation. -pub fn rgb_hex(c: [u8; 3]) -> String { - format!("#{:02x}{:02x}{:02x}", c[0], c[1], c[2]) -} - -/// Save for Web's named presets. -pub const PRESETS: [&str; 12] = [ - "GIF 128 Dithered", - "GIF 128 No Dither", - "GIF 32 Dithered", - "GIF 32 No Dither", - "GIF 64 Dithered", - "GIF 64 No Dither", - "GIF Restrictive", - "JPEG High", - "JPEG Low", - "JPEG Medium", - "PNG-24", - "PNG-8 128 Dithered", -]; - -pub fn preset_settings(name: &str) -> Option { - let d = WebSettings::default(); - let gif = |colors: usize, dither: bool| WebSettings { - format: WebFormat::Gif, - colors, - dither: if dither { Dither::Diffusion } else { Dither::None }, - ..WebSettings::default() - }; - Some(match name { - "GIF 128 Dithered" => gif(128, true), - "GIF 128 No Dither" => gif(128, false), - "GIF 32 Dithered" => gif(32, true), - "GIF 32 No Dither" => gif(32, false), - "GIF 64 Dithered" => gif(64, true), - "GIF 64 No Dither" => gif(64, false), - "GIF Restrictive" => WebSettings { palette: PaletteKind::Web, ..gif(256, true) }, - "JPEG High" => WebSettings { format: WebFormat::Jpeg, quality: 60, ..d }, - "JPEG Low" => WebSettings { format: WebFormat::Jpeg, quality: 10, ..d }, - "JPEG Medium" => WebSettings { format: WebFormat::Jpeg, quality: 30, ..d }, - "JPEG Maximum" => WebSettings { format: WebFormat::Jpeg, quality: 100, ..d }, - "JPEG Very High" => WebSettings { format: WebFormat::Jpeg, quality: 80, ..d }, - "PNG-24" => WebSettings { format: WebFormat::Png24, ..d }, - "PNG-8 128 Dithered" => WebSettings { format: WebFormat::Png8, colors: 128, ..d }, - _ => return None, - }) -} - -// ---------- the image ---------- - -/// The document as Save for Web sees it: RGB (converted to sRGB unless told otherwise), resized -/// by `"width"`/`"height"`/`"percent"`, flattened. Returns the document and the scale factors. -pub fn web_document(doc: &Document, p: &Value, st: &WebSettings) -> Result<(Document, f64, f64)> { - let mut tmp = Session::new(); - tmp.add_document(doc.clone(), None); - let mode = doc.mode; - if mode != photocraft_color::ColorMode::Rgb { - tmp.execute("image.mode.rgb", json!({}))?; - } - if st.convert_to_srgb && doc.icc_profile.is_some() { - // Documents without a profile are treated as sRGB already. - tmp.execute("edit.convertToProfile", json!({"profile": "srgb", "intent": "perceptual"}))?; - } - let (w0, h0) = (f64::from(doc.size.width), f64::from(doc.size.height)); - let pct = p.get("percent").and_then(Value::as_f64).filter(|v| *v > 0.0); - let w = p.get("width").and_then(Value::as_f64).filter(|v| *v > 0.0); - let h = p.get("height").and_then(Value::as_f64).filter(|v| *v > 0.0); - let (nw, nh) = match (pct, w, h) { - (Some(pc), _, _) => (w0 * pc / 100.0, h0 * pc / 100.0), - (_, Some(w), Some(h)) => (w, h), - (_, Some(w), None) => (w, h0 * w / w0), - (_, None, Some(h)) => (w0 * h / h0, h), - _ => (w0, h0), - }; - let (nw, nh) = (nw.round().max(1.0), nh.round().max(1.0)); - if (nw - w0).abs() >= 1.0 || (nh - h0).abs() >= 1.0 { - let resample = p.get("resample").and_then(Value::as_str).unwrap_or("bicubic"); - tmp.execute("image.imageSize", json!({"width": nw, "height": nh, "resample": resample}))?; - } - let out = (*tmp.active().ok_or(EngineError::NoDocument)?.doc).clone(); - Ok((out, nw / w0, nh / h0)) -} - -/// An optimised image. -#[derive(Clone, Debug)] -pub struct Optimized { - pub bytes: Vec, - pub ext: &'static str, - pub width: u32, - pub height: u32, - /// Colours in the palette (indexed formats). - pub colors: Option, - /// Opaque source palette before replacements (empty for non-indexed formats). - pub color_table: Vec<[u8; 3]>, - pub transparent_index: Option, - /// Indexed pixels for previews; empty for non-indexed formats or when preview is disabled. - pub indices: Vec, - /// What the optimised file looks like, straight RGBA8 (for the dialog's previews). - pub preview: Vec, -} - -fn to8(v: f32) -> u8 { - (v.clamp(0.0, 1.0) * 255.0).round() as u8 -} - -/// XMP to embed for the metadata choice. -pub fn web_xmp(doc: &Document, m: WebMetadata) -> Option { - let xmp = doc.metadata.xmp.as_deref()?; - match m { - WebMetadata::None => None, - WebMetadata::All | WebMetadata::AllExceptCameraInfo => Some(xmp.to_string()), - WebMetadata::Copyright | WebMetadata::CopyrightAndContact => { - let info = crate::file_cmds::read_file_info(Some(xmp)); - let mut keep = serde_json::Map::new(); - let mut keys = vec!["copyright", "copyrightStatus", "copyrightUrl"]; - if m == WebMetadata::CopyrightAndContact { - keys.extend(["author", "authorTitle"]); - } - for k in keys { - if let Some(v) = info.get(k).filter(|v| v.as_str().is_some_and(|s| !s.is_empty()) || v.is_array()) { - keep.insert(k.into(), v.clone()); - } - } - (!keep.is_empty()).then(|| crate::file_cmds::write_file_info(None, &Value::Object(keep))) - } - } -} - -/// The photo's EXIF to embed for the metadata choice: only "All" carries it (#7436). -pub fn web_exif(doc: &Document, m: WebMetadata) -> Option<&[u8]> { - doc.metadata.exif.as_deref().map(Vec::as_slice).filter(|_| m == WebMetadata::All) -} - -/// The response's warnings: EXIF that a JPEG couldn't hold (one segment, about 64 KB). -fn web_warnings(st: &WebSettings, exif: Option<&[u8]>, dpi: f32) -> Vec { - exif.filter(|x| st.format == WebFormat::Jpeg && !photocraft_codecs::web::jpeg_exif_fits(x, Some(dpi))) - .map(|x| photocraft_codecs::FidelityWarning::MetadataTooLarge { what: "EXIF", bytes: x.len() }.to_string()) - .into_iter() - .collect() -} - -/// Optimises `rect` of `px` (straight RGBA, `bw` wide) with `st`. `preview` also returns what -/// the file looks like (the dialog's panes); exports skip it. -#[allow(clippy::too_many_arguments)] -pub fn optimize( - px: &[[f32; 4]], - bw: usize, - rect: Rect, - st: &WebSettings, - icc: Option<&[u8]>, - exif: Option<&[u8]>, - xmp: Option<&str>, - dpi: f32, - preview: bool, -) -> Result { - if bw == 0 || rect.x0 < 0 || rect.y0 < 0 || rect.is_empty() || rect.x1 as usize > bw || (rect.y1 as usize).checked_mul(bw).is_none_or(|end| end > px.len()) - { - return Err(other("slice is outside the pixel buffer")); - } - let (w, h) = (rect.width() as usize, rect.height() as usize); - let row = |y: i32| { - let o = y as usize * bw; - px.get(o + rect.x0 as usize..o + rect.x1 as usize).unwrap_or(&[]) - }; - let region = || (rect.y0..rect.y1).flat_map(row); - let matte = st.matte.unwrap_or([1.0, 1.0, 1.0]); - let over = |p: &[f32; 4]| -> [f32; 4] { - [p[0] * p[3] + matte[0] * (1.0 - p[3]), p[1] * p[3] + matte[1] * (1.0 - p[3]), p[2] * p[3] + matte[2] * (1.0 - p[3]), 1.0] - }; - let (ww, hh) = (w as u32, h as u32); - let e = |e: photocraft_codecs::CodecError| other(e); - let mut look: Vec = Vec::new(); - let mut color_table = Vec::new(); - let mut transparent_index = None; - let mut indices = Vec::new(); - let (bytes, colors) = match st.format { - WebFormat::Png24 => { - let alpha = st.transparency && region().any(|p| p[3] < 1.0); - let k = if alpha { 4 } else { 3 }; - let mut data = Vec::with_capacity(w * h * k); - for p in region() { - let q = if alpha { *p } else { over(p) }; - data.extend_from_slice(&[to8(q[0]), to8(q[1]), to8(q[2]), to8(q[3])][..k]); - } - if preview { - look = if alpha { data.clone() } else { data.as_chunks::<3>().0.iter().flat_map(|c| [c[0], c[1], c[2], 255]).collect() }; - } - let layout = if alpha { photocraft_codecs::ChannelLayout::Rgba } else { photocraft_codecs::ChannelLayout::Rgb }; - let meta = photocraft_codecs::Metadata { dpi: Some((dpi, dpi)), xmp: xmp.map(str::to_string), ..Default::default() }; - let img = photocraft_codecs::Image::from_u8(ww, hh, layout, data).map_err(e)?.with_icc(icc.map(<[u8]>::to_vec)).with_meta(meta); - let opts = photocraft_codecs::EncodeOptions { - png_interlaced: st.interlaced, - embed_icc: icc.is_some(), - embed_metadata: xmp.is_some(), - ..Default::default() - }; - (photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &opts).map_err(e)?, None) - } - WebFormat::Jpeg => { - let mut rgb = Vec::with_capacity(w * h * 3); - for p in region() { - let q = over(p); - rgb.extend_from_slice(&[to8(q[0]), to8(q[1]), to8(q[2])]); - } - // Save for Web's 0–100 quality → encoder 1–100. - let q = st.quality.max(1); - let bytes = - photocraft_codecs::web::encode_jpeg_rgb8(ww, hh, &rgb, q, st.progressive, st.optimized, icc.filter(|_| st.embed_icc), Some(dpi), exif, xmp) - .map_err(e)?; - if preview { - // The preview shows the compression artefacts. - look = match photocraft_codecs::decode(&bytes) { - Ok(img) => img.convert(photocraft_codecs::ChannelLayout::Rgba, photocraft_codecs::SampleType::U8).data().to_vec(), - Err(_) => rgb.as_chunks::<3>().0.iter().flat_map(|c| [c[0], c[1], c[2], 255]).collect(), - }; - } - (bytes, None) - } - WebFormat::Wbmp => { - let mut gray: Vec = region() - .map(|p| { - let q = over(p); - 0.299 * q[0] + 0.587 * q[1] + 0.114 * q[2] - }) - .collect(); - let method = match st.dither { - Dither::None => quantize::BitmapMethod::Threshold, - Dither::Pattern => quantize::BitmapMethod::Pattern, - _ => quantize::BitmapMethod::Diffusion, - }; - quantize::to_bitmap(&mut gray, w, method); - let white: Vec = gray.iter().map(|v| *v > 0.5).collect(); - if preview { - look = white.iter().flat_map(|b| if *b { [255, 255, 255, 255] } else { [0, 0, 0, 255] }).collect(); - } - (photocraft_codecs::web::encode_wbmp(ww, hh, &white).map_err(e)?, Some(2)) - } - WebFormat::Gif | WebFormat::Png8 => { - let transparent = st.transparency && region().any(|p| p[3] < 0.5); - // Partially transparent edges blend with the matte; with transparency off everything does. - let mut work: Vec<[f32; 4]> = region() - .map(|p| { - if st.transparency && p[3] < 0.5 { - [0.0, 0.0, 0.0, 0.0] - } else if st.transparency && st.matte.is_none() { - [p[0], p[1], p[2], 1.0] - } else { - over(p) - } - }) - .collect(); - let room = if transparent { st.colors.saturating_sub(1).max(2) } else { st.colors }; - let mut pal = if let Some(table) = &st.color_table { - if table.is_empty() || table.len() > if transparent { 255 } else { 256 } { - return Err(other("colorTable has too many entries for this image's transparency")); - } - table.clone() - } else { - // Large images: build adaptive palettes from an even ~1 MP sample (Exact needs all). - let n_opaque = work.iter().filter(|p| p[3] >= 0.5).count(); - let step = if n_opaque > 1 << 20 && st.palette != PaletteKind::Exact { n_opaque / (1 << 20) + 1 } else { 1 }; - let mut src: Vec<[f32; 4]> = work.iter().filter(|p| p[3] >= 0.5).step_by(step).copied().collect(); - if src.is_empty() { - src = work.clone(); - } - quantize::build_palette(&src, st.palette, room, Forced::None).map_err(other)? - }; - if st.web_snap > 0.0 && st.color_table.is_none() { - let tol = (st.web_snap * 255.0) as u8; - for c in &mut pal { - let snap = c.map(|x| ((f32::from(x) / 51.0).round() * 51.0) as u8); - if c.iter().zip(snap).all(|(a, b)| a.abs_diff(b) <= tol) { - *c = snap; - } - } - } - if transparent { - pal.truncate(255); - } - let first = pal.first().copied().ok_or_else(|| other("empty colour table"))?; - color_table = pal.clone(); - let t = transparent.then(|| { - pal.push(first); - pal.len() - 1 - }); - transparent_index = t; - let idx = quantize_rows(&mut work, w, &pal, st.dither, st.dither_amount, t); - for (index, color) in &st.color_table_edits { - let slot = pal.get_mut(*index).filter(|_| Some(*index) != t).ok_or_else(|| other("colour edit is outside the opaque palette"))?; - *slot = *color; - } - if preview { - look = idx - .iter() - .flat_map(|k| { - let c = pal.get(*k as usize).copied().unwrap_or(first); - [c[0], c[1], c[2], if Some(*k as usize) == t { 0 } else { 255 }] - }) - .collect(); - } - let tt = t.map(|v| v as u8); - let bytes = if st.format == WebFormat::Gif { - photocraft_codecs::web::encode_gif_indexed(ww, hh, &idx, &pal, tt, st.interlaced).map_err(e)? - } else { - photocraft_codecs::encode_png_indexed(ww, hh, &idx, &pal, tt, None, None).map_err(e)? - }; - if preview { - indices = idx; - } - (bytes, Some(pal.len())) - } - }; - Ok(Optimized { bytes, ext: st.format.ext(), width: ww, height: hh, colors, color_table, transparent_index, indices, preview: look }) -} - -/// Nearest palette entry through a lazily filled 6-bit-per-channel inverse colour map: each -/// 4×4×4 cell is resolved once (by its centre), so large images cost a table lookup per pixel -/// instead of a palette scan. `t` (the transparent index) is never returned. -struct InverseMap<'a> { - pal: &'a [[u8; 3]], - t: Option, - lut: Vec, -} - -impl<'a> InverseMap<'a> { - fn new(pal: &'a [[u8; 3]], t: Option) -> Self { - InverseMap { pal, t, lut: vec![u16::MAX; 1 << 18] } - } - #[inline] - fn get(&mut self, c: [f32; 3]) -> usize { - let q = c.map(|v| ((v.clamp(0.0, 1.0) * 255.0).round() as usize) >> 2); - let key = q[0] << 12 | q[1] << 6 | q[2]; - let v = self.lut[key]; - if v != u16::MAX { - return usize::from(v); - } - let center = q.map(|v| (v * 4 + 2) as f32); - let mut best = (f32::MAX, 0usize); - for (i, e) in self.pal.iter().enumerate() { - if Some(i) == self.t { - continue; - } - let d: f32 = (0..3).map(|k| (center[k] - f32::from(e[k])).powi(2)).sum(); - if d < best.0 { - best = (d, i); - } - } - self.lut[key] = best.1 as u16; - best.1 - } -} - -fn hash01(x: usize, y: usize) -> f32 { - let mut h = (x as u32).wrapping_mul(0x8da6_b343) ^ (y as u32).wrapping_mul(0xd816_3841) ^ 0x2545_f491; - h ^= h >> 13; - h = h.wrapping_mul(0x5bd1_e995); - h ^= h >> 15; - (h & 0xffff) as f32 / 65535.0 -} - -/// Palette mapping with dithering (Floyd–Steinberg diffusion, 8×8 Bayer pattern, noise), like -/// `algo::quantize::quantize` but through [`InverseMap`]. `y0` keeps patterns continuous across -/// bands. Pixels with alpha < ½ take index `t`. -fn quantize_band(px: &mut [[f32; 4]], w: usize, y0: usize, pal: &[[u8; 3]], dither: Dither, amount: f32, t: Option) -> Vec { - let h = px.len() / w.max(1); - let mut map = InverseMap::new(pal, t); - let mut idx = vec![0u8; px.len()]; - let opaque_n = pal.len() - usize::from(t.is_some()); - let spread = (1.0 / (opaque_n as f32).cbrt().max(1.0)).min(0.5) * amount.clamp(0.0, 1.0); - let a = amount.clamp(0.0, 1.0); - let mut cur = vec![[0.0f32; 3]; if dither == Dither::Diffusion { w + 2 } else { 0 }]; - let mut next = cur.clone(); - for y in 0..h { - if dither == Dither::Diffusion { - std::mem::swap(&mut cur, &mut next); - next.iter_mut().for_each(|e| *e = [0.0; 3]); - } - for x in 0..w { - let i = y * w + x; - let p = px[i]; - if p[3] < 0.5 - && let Some(t) = t - { - idx[i] = t as u8; - continue; - } - let mut c = [p[0], p[1], p[2]]; - match dither { - Dither::None => {} - Dither::Diffusion => (0..3).for_each(|k| c[k] += cur[x + 1][k]), - Dither::Pattern => { - let d = quantize::bayer8(x, y0 + y) * spread; - c = c.map(|v| v + d); - } - Dither::Noise => { - let d = (hash01(x, y0 + y) - 0.5) * spread; - c = c.map(|v| v + d); - } - } - let c = c.map(|v| v.clamp(0.0, 1.0)); - let k = map.get(c); - idx[i] = k as u8; - if dither == Dither::Diffusion { - let e = pal[k].map(|v| f32::from(v) / 255.0); - let d: [f32; 3] = std::array::from_fn(|q| (c[q] - e[q]) * a); - for q in 0..3 { - cur[x + 2][q] += d[q] * 7.0 / 16.0; - next[x][q] += d[q] * 3.0 / 16.0; - next[x + 1][q] += d[q] * 5.0 / 16.0; - next[x + 2][q] += d[q] / 16.0; - } - } - } - } - idx -} - -/// [`quantize_band`] over the whole image, in parallel bands of 64 rows when the dither is -/// position-independent. Error diffusion carries error down the image, so it stays sequential. -fn quantize_rows(px: &mut [[f32; 4]], w: usize, pal: &[[u8; 3]], dither: Dither, amount: f32, t: Option) -> Vec { - let h = px.len() / w.max(1); - if dither == Dither::Diffusion || h < 128 || cfg!(target_arch = "wasm32") { - return quantize_band(px, w, 0, pal, dither, amount, t); - } - #[cfg(not(target_arch = "wasm32"))] - { - use rayon::prelude::*; - let band = w * 64; - let mut idx = vec![0u8; px.len()]; - px.par_chunks_mut(band) - .zip(idx.par_chunks_mut(band)) - .enumerate() - .for_each(|(i, (p, out))| out.copy_from_slice(&quantize_band(p, w, i * 64, pal, dither, amount, t))); - idx - } - // Single-threaded on wasm (the early return above always takes this path there). - #[cfg(target_arch = "wasm32")] - quantize_band(px, w, 0, pal, dither, amount, t) -} - -/// A file-name-safe slice name. -fn slice_file(name: &str) -> String { - let s: String = name.chars().map(|c| if c.is_alphanumeric() || matches!(c, '-' | '_') { c } else { '_' }).collect(); - let s = if s.is_empty() { "slice".into() } else { s }; - portable_generated_stem(s) -} - -/// Generated filenames should remain usable on Windows even when a document or slice is named -/// after a reserved device. Caller-supplied path components are still rejected below. -fn portable_generated_stem(stem: String) -> String { - portable_device_name(stem) -} - -fn html_escape(s: &str) -> String { - s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """) -} - -/// Imported slice URLs are document data. Only ordinary web/contact links and relative links -/// become anchors; an unsupported scheme leaves the image unlinked. -fn safe_slice_url(url: &str) -> bool { - if url.is_empty() || url.trim() != url || url.chars().any(|c| c.is_control() || c == '\\') { - return false; - } - let delimiter = url.find(['/', '?', '#']).unwrap_or(url.len()); - let Some(colon) = url.find(':').filter(|pos| *pos < delimiter) else { - return true; - }; - let scheme = url.get(..colon).unwrap_or_default().to_ascii_lowercase(); - let rest = url.get(colon + 1..).unwrap_or_default(); - match scheme.as_str() { - "http" | "https" | "ftp" | "ftps" => rest.strip_prefix("//").is_some_and(|host| !host.is_empty() && !host.starts_with('/')), - "mailto" | "tel" => !rest.is_empty(), - _ => false, - } -} - -/// Keep the image folder relative to the selected export directory on every platform. -fn web_images_folder(images: &str, cmd: &str) -> Result { - if images.is_empty() { - return Ok(String::new()); - } - let trimmed = images.trim_end_matches(['/', '\\']); - if trimmed.is_empty() { - return Err(bad(cmd, "imagesFolder must be a relative folder name")); - } - let parts = asset_path_components(trimmed).map_err(|e| bad(cmd, format!("imagesFolder: {e}")))?; - Ok(parts.join("/")) -} - -fn web_output_path(dir: &str, relative: &str) -> Result { - let root = if dir.is_empty() { "." } else { dir }; - asset_output_path(root, relative).map(|(actual, _)| actual) -} - -fn web_derived_path(dir: &str, relative: &str, native_paths: bool) -> Result { - if native_paths { - web_output_path(dir, relative) - } else { - // Browser downloads use logical names, without a host filesystem to inspect. - asset_path_components(relative)?; - Ok(join(dir, relative)) - } -} - -fn scale_rect(r: Rect, sx: f64, sy: f64) -> Rect { - Rect::new( - (f64::from(r.x0) * sx).round() as i32, - (f64::from(r.y0) * sy).round() as i32, - (f64::from(r.x1) * sx).round() as i32, - (f64::from(r.y1) * sy).round() as i32, - ) -} - -/// The HTML table for `cells` (rect, td body) over a `w`×`h` image: one column per distinct x -/// edge, one row per y edge, colspan/rowspan per slice, and a spacer row fixing column widths. -fn html_table(title: &str, w: u32, h: u32, cells: &[(Rect, String, String)], spacer: Option<&str>) -> String { - let mut xs: Vec = cells.iter().flat_map(|(r, _, _)| [r.x0, r.x1]).collect(); - let mut ys: Vec = cells.iter().flat_map(|(r, _, _)| [r.y0, r.y1]).collect(); - xs.sort_unstable(); - xs.dedup(); - ys.sort_unstable(); - ys.dedup(); - let col = |x: i32| xs.iter().position(|v| *v == x).unwrap_or(0); - let row = |y: i32| ys.iter().position(|v| *v == y).unwrap_or(0); - let (nc, nr) = (xs.len().saturating_sub(1), ys.len().saturating_sub(1)); - let mut taken = vec![false; nc * nr]; - let mut by_row: Vec> = vec![Vec::new(); nr]; - for (r, attrs, body) in cells { - let (c0, c1, r0, r1) = (col(r.x0), col(r.x1), row(r.y0), row(r.y1)); - if (r0..r1).any(|j| (c0..c1).any(|i| taken[j * nc + i])) { - continue; // overlapped (the caller cuts slices into visible pieces, so this can't happen) - } - for j in r0..r1 { - for i in c0..c1 { - taken[j * nc + i] = true; - } - } - let mut td = String::from("\t\t 1 { - td.push_str(&format!(" colspan=\"{}\"", c1 - c0)); - } - if r1 - r0 > 1 { - td.push_str(&format!(" rowspan=\"{}\"", r1 - r0)); - } - td.push_str(attrs); - td.push('>'); - td.push_str(body); - td.push_str("\n"); - by_row[r0].push((c0, td)); - } - let mut s = format!( - "\n\n{t}\n\n\n\n\n\n", - t = html_escape(title) - ); - for (j, mut tds) in by_row.into_iter().enumerate() { - tds.sort_by_key(|(c, _)| *c); - s.push_str("\t\n"); - for (_, td) in tds { - s.push_str(&td); - } - if let Some(sp) = spacer { - s.push_str(&format!("\t\t\n", html_escape(sp), ys[j + 1] - ys[j])); - } - s.push_str("\t\n"); - } - if let Some(sp) = spacer { - s.push_str("\t\n"); - for i in 0..nc { - s.push_str(&format!("\t\t\n", html_escape(sp), xs[i + 1] - xs[i])); - } - s.push_str("\t\t\n\t\n"); - } - s.push_str("
\n\t\t\t\"\"
\n\t\t\t\"\"
\n\n\n\n"); - s -} - -/// File › Export › Save for Web (Legacy). -fn save_for_web(s: &mut Session, p: &Value) -> Result { - save_for_web_impl(s, p, &mut write_file, true) -} - -/// Save for Web through a platform writer (native files or browser downloads). -/// The writer receives every image, spacer and HTML file. A write error stops the export; -/// only a complete export remembers its settings and fires the export event. A custom writer -/// that targets the local filesystem must enforce its own path confinement. -pub fn save_for_web_with_writer(s: &mut Session, p: &Value, write: &mut dyn FnMut(&str, &[u8]) -> Result<()>) -> Result { - save_for_web_impl(s, p, write, false) -} - -/// Settings to seed the Save for Web dialog from on the next launch: `file_menu` is session -/// state, so a complete export also writes the preferences' remembered dialog settings (like -/// Fill, Liquify and the filter dialogs). The destination is per export, never remembered. -fn remember_web_settings(s: &mut Session, cmd: &str, settings: &Value) { - let mut m = settings.clone(); - if let Some(o) = m.as_object_mut() { - for k in ["path", "dir", "trustedSliceHtml"] { - o.remove(k); - } - } - s.prefs.edit(|p| { - p.dialogs.insert(cmd.to_string(), m); - }); -} - -fn save_for_web_impl(s: &mut Session, p: &Value, write: &mut dyn FnMut(&str, &[u8]) -> Result<()>, native_paths: bool) -> Result { - let cmd = "file.export.saveForWebLegacy"; - if let Some(authorize) = s.authorize { - authorize(cmd, p)?; - } - // Direct platform calls must export the moved selection as it appears on the canvas, - // just as Session::execute does before dispatching the native command. - crate::float_cmds::before_command(s, cmd)?; - let st = WebSettings::from_params(p, cmd)?; - let d = s.active().ok_or(EngineError::NoDocument)?; - let doc = d.doc.clone(); - let (wdoc, sx, sy) = web_document(&doc, p, &st)?; - let buf = photocraft_compose::flatten(&wdoc); - let bw = wdoc.size.width as usize; - let icc = wdoc.icc_profile.as_deref().map(|v| v.as_slice()); - let xmp = web_xmp(&doc, st.metadata); - let exif = web_exif(&doc, st.metadata); - let dpi = wdoc.resolution_dpi; - let warnings = web_warnings(&st, exif, dpi); - let all = slices::resolve(&doc); - let pick = p.get("slices").and_then(Value::as_str).unwrap_or("all"); - let numbers: Option> = p.get("numbers").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_u64).collect()); - let chosen: Vec<&ResolvedSlice> = all - .iter() - .filter(|r| match (&numbers, pick) { - (Some(n), _) => n.contains(&(r.number as u64)), - (None, "user") => r.origin != photocraft_doc::SliceOrigin::Auto, - _ => true, - }) - .collect(); - let single = p.get("path").and_then(Value::as_str).filter(|v| !v.is_empty()); - let dir = p.get("dir").and_then(Value::as_str).filter(|v| !v.is_empty()); - let mut last_web = p.clone(); - // A trusted-markup decision applies to this export only, never to another document opened - // with the dialog's remembered settings. - if let Some(last) = last_web.as_object_mut() { - last.remove("trustedSliceHtml"); - } - // Estimate only (the dialog's annotations): the whole image, or each chosen slice. - if single.is_none() && dir.is_none() { - let o = optimize(&buf.px, bw, wdoc.bounds(), &st, icc, exif, xmp.as_deref(), dpi, false)?; - return Ok( - json!({"format": o.ext, "bytes": o.bytes.len(), "width": o.width, "height": o.height, "colors": o.colors, "colorTable": o.color_table.iter().map(|c| rgb_hex(*c)).collect::>(), "transparentIndex": o.transparent_index}), - ); - } - if let Some(path) = single.filter(|_| dir.is_none() && (all.len() == 1 || p.get("slices").is_none())) { - let o = optimize(&buf.px, bw, wdoc.bounds(), &st, icc, exif, xmp.as_deref(), dpi, false)?; - write(path, &o.bytes)?; - remember_web_settings(s, cmd, &last_web); - s.file_menu.last_web = Some(last_web); - crate::automate_cmds::fire_event(s, "export"); - return Ok(json!({"files": [path], "bytes": o.bytes.len(), "width": o.width, "height": o.height, "colors": o.colors, "warnings": warnings})); - } - let dir = - dir.map(str::to_string).or_else(|| single.and_then(|f| std::path::Path::new(f).parent().map(|d| d.to_string_lossy().into_owned()))).unwrap_or_default(); - let html = p.get("html").and_then(Value::as_bool).unwrap_or(false); - let images = web_images_folder(p.get("imagesFolder").and_then(Value::as_str).unwrap_or("images"), cmd)?; - let trusted_slice_html = p.get("trustedSliceHtml").and_then(Value::as_bool).unwrap_or(false); - let base = portable_generated_stem(single.map(stem).unwrap_or_else(|| slices::base_name(&doc))); - let mut files = Vec::new(); - let mut cells: Vec<(Rect, String, String)> = Vec::new(); - let mut total = 0usize; - // Output names are unique (case-insensitively, for macOS and Windows file systems): two - // slices named alike, or names that sanitize alike, must not overwrite each other. The HTML - // page's spacer image is reserved. - let mut used: std::collections::HashSet = std::collections::HashSet::new(); - if html { - used.insert("spacer.gif".into()); - } - let mut unique = |stem: &str, ext: &str| { - let mut name = format!("{stem}.{ext}"); - let mut k = 2u32; - while !used.insert(name.to_lowercase()) { - name = format!("{stem}_{k}.{ext}"); - k = k.saturating_add(1); - } - name - }; - // Slices never overlap here: one covered by later slices comes as its visible pieces (see - // `slices::resolve`), each its own image and cell, as Photoshop's subslices. A no-image cell's - // text goes into its first piece only. - let mut texted = std::collections::HashSet::new(); - for r in &chosen { - let piece = scale_rect(r.rect, sx, sy).intersect(&wdoc.bounds()); - if piece.is_empty() { - continue; - } - let stored = r.id.and_then(|id| doc.slices.get(id)); - if r.kind == SliceKind::NoImage { - let text = stored - .filter(|s| texted.insert(s.id)) - .map(|s| if trusted_slice_html && s.cell_text_is_html { s.cell_text.clone() } else { html_escape(&s.cell_text) }) - .unwrap_or_default(); - let bg = stored.and_then(|s| s.background).map(|c| format!(" bgcolor=\"#{:02X}{:02X}{:02X}\"", c[1], c[2], c[3])).unwrap_or_default(); - cells.push((piece, bg, text)); - continue; - } - let o = optimize(&buf.px, bw, piece, &st, icc, exif, xmp.as_deref(), dpi, false)?; - let name = unique(&slice_file(&r.name), o.ext); - let rel = if images.is_empty() { name.clone() } else { format!("{images}/{name}") }; - let out = join(&dir, &rel); - write(&web_derived_path(&dir, &rel, native_paths)?, &o.bytes)?; - total += o.bytes.len(); - files.push(out); - let alt = stored.map_or(String::new(), |s| html_escape(&s.alt)); - let img = format!("\n\t\t\t\"{alt}\"", html_escape(&rel), piece.width(), piece.height()); - let body = match stored.filter(|s| safe_slice_url(&s.url)) { - Some(s) => { - let target = if s.target.is_empty() { String::new() } else { format!(" target=\"{}\"", html_escape(&s.target)) }; - format!("\n\t\t\t{img}", html_escape(&s.url)) - } - None => img, - }; - cells.push((piece, String::new(), body)); - } - let mut html_path = None; - if html { - let grid = cells.len() > 1; - let spacer = grid.then(|| if images.is_empty() { "spacer.gif".to_string() } else { format!("{images}/spacer.gif") }); - if let Some(sp) = &spacer { - let gif = photocraft_codecs::web::encode_gif_indexed(1, 1, &[0], &[[0, 0, 0]], Some(0), false).map_err(other)?; - write(&web_derived_path(&dir, sp, native_paths)?, &gif)?; - } - let page = html_table(&base, wdoc.size.width, wdoc.size.height, &cells, spacer.as_deref()); - let hp = join(&dir, &format!("{base}.html")); - write(&web_derived_path(&dir, &format!("{base}.html"), native_paths)?, page.as_bytes())?; - html_path = Some(hp); - } - remember_web_settings(s, cmd, &last_web); - s.file_menu.last_web = Some(last_web); - crate::automate_cmds::fire_event(s, "export"); - Ok( - json!({"files": files, "html": html_path, "bytes": total, "slices": chosen.len(), "width": wdoc.size.width, "height": wdoc.size.height, "warnings": warnings}), - ) -} - -// ---------- Export Preferences / Quick Export ---------- - -/// File › Export › Export Preferences…: sets the given `export.*` preferences through `prefs.set` -/// (validated like any other preference) and returns the whole section. -fn export_preferences(s: &mut Session, p: &Value) -> Result { - let cmd = "file.export.exportPreferences"; - let mut values = serde_json::Map::new(); - for (k, key) in [ - ("quickExportFormat", "export.quickExportFormat"), - ("quickExportLocation", "export.quickExportLocation"), - ("jpegQuality", "export.jpegQuality"), - ("webpLossless", "export.webpLossless"), - ("webpQuality", "export.webpQuality"), - ("metadata", "export.metadata"), - ("convertToSrgb", "export.convertToSrgb"), - ] { - if let Some(v) = p.get(k) { - values.insert(key.into(), v.clone()); - } - } - if !values.is_empty() { - s.execute("prefs.set", json!({"values": values})).map_err(|e| bad(cmd, e.to_string()))?; - } - Ok(json!({"section": "export", "values": s.prefs().get("export").unwrap_or(Value::Null)})) -} - -/// The Quick Export format's extension (Export Preferences › Format). -fn quick_export_ext(s: &Session) -> String { - serde_json::to_value(s.prefs().export.quick_export_format).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_else(|| "png".into()) -} - -/// Where Quick Export writes the active document with no `path` given: `.` beside -/// its file, when Export Preferences › Location is Same Folder and the document has a file. -pub fn quick_export_target(s: &Session) -> Option { - let same = s.prefs().export.quick_export_location == crate::prefs::ExportLocation::SameFolder; - let dp = s.active()?.path.as_deref().filter(|_| same)?; - let dir = std::path::Path::new(dp).parent().map(|d| d.to_string_lossy().into_owned()).unwrap_or_default(); - Some(join(&dir, &format!("{}.{}", stem(dp), quick_export_ext(s)))) -} - -/// Whether [`quick_export_target`] is the active document's own file (a document opened from -/// `photo.png` and exported as PNG), which Quick Export must not replace without asking (#6599). -pub fn quick_export_target_is_own_file(s: &Session) -> bool { - let own = s.active().and_then(|d| d.path.as_deref()); - quick_export_target(s).zip(own).is_some_and(|(target, own)| crate::file_cmds::same_file(&target, own)) -} - -/// File › Export › Quick Export as : the format, quality, metadata, colour space and -/// location from Export Preferences. `path` overrides the location ("ask" needs one). -fn quick_export(s: &mut Session, p: &Value) -> Result { - let cmd = "file.export.quickExport"; - let prefs = s.prefs().export.clone(); - let fmt = quick_export_ext(s); - let path = match p.get("path").and_then(Value::as_str).filter(|v| !v.is_empty()) { - Some(v) => v.to_string(), - None => { - let Some(target) = quick_export_target(s) else { - return Err(bad(cmd, "missing `path` (Export Preferences › Location is \"ask\", or the document was never saved)")); - }; - // The document's own file is never replaced by an export the user didn't name (#6599). - if quick_export_target_is_own_file(s) { - return Err(bad(cmd, format!("the export would replace the document's own file {target}; give a `path`"))); - } - target - } - }; - // The name typed in the save dialog wins over Export Preferences' format: Quick Export as PNG - // renamed to `photo.jpeg` must write a JPEG, not PNG bytes upload checks refuse (#8519). - let fmt = match crate::file_cmds::extension(&path).as_deref() { - None => fmt, - Some("jpg" | "jpeg") => "jpg".into(), - Some(e @ ("png" | "gif" | "webp" | "exr")) => e.into(), - Some(e) => return Err(bad(cmd, format!("Quick Export writes PNG, JPEG, GIF, WebP or EXR, not .{e}; use Export As"))), - }; - let d = s.active().ok_or(EngineError::NoDocument)?; - let doc = d.doc.clone(); - if fmt == "exr" { - // EXR keeps floating-point scene values. The ordinary exporter converts to linear - // light; the web/sRGB pipeline would instead clamp HDR and negative values. - let opts = photocraft_io::ExportOptions { xmp: photocraft_io::XmpEmbed::None, ..Default::default() }; - let out = photocraft_io::export(&doc, "exr", &opts).map_err(other)?; - write_file(&path, &out.bytes)?; - crate::automate_cmds::fire_event(s, "export"); - return Ok(json!({"path": path, "format": fmt, "bytes": out.bytes.len(), "warnings": out.warnings})); - } - let metadata = serde_json::to_value(prefs.metadata).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default(); - let mut o = serde_json::Map::new(); - o.insert( - "metadata".into(), - json!(if metadata == "all" { - "all" - } else if metadata == "none" { - "none" - } else { - "copyright" - }), - ); - o.insert("convertToSrgb".into(), json!(prefs.convert_to_srgb)); - o.insert("transparency".into(), json!(true)); - o.insert("matte".into(), json!("#ffffff")); - match fmt.as_str() { - "jpg" => { - o.insert("format".into(), json!("jpeg")); - o.insert("quality".into(), json!(prefs.jpeg_quality.min(100))); - } - "gif" => { - o.insert("format".into(), json!("gif")); - } - "webp" => { - // WebP uses the regular exporter. Its optional quality is in the Photoshop-style - // 0–12 save scale: invert that mapping so the codec receives the chosen 1–100. - // Keeping quality absent preserves the historical lossless Quick Export behavior. - let (wdoc, _, _) = web_document(&doc, &json!({}), &WebSettings { convert_to_srgb: prefs.convert_to_srgb, ..Default::default() })?; - let quality = if prefs.webp_lossless { None } else { Some((f64::from(prefs.webp_quality.clamp(1, 100)) - 1.0) * 12.0 / 99.0) }; - let warnings = crate::file_cmds::save_doc(&wdoc, &path, quality)?; - crate::automate_cmds::fire_event(s, "export"); - return Ok(json!({"path": path, "format": fmt, "warnings": warnings})); - } - _ => { - o.insert("format".into(), json!("png24")); - } - } - let q = Value::Object(o); - let st = WebSettings::from_params(&q, cmd)?; - let (wdoc, _, _) = web_document(&doc, &json!({}), &st)?; - let buf = photocraft_compose::flatten(&wdoc); - let xmp = web_xmp(&doc, st.metadata); - let exif = web_exif(&doc, st.metadata); - let opt = optimize( - &buf.px, - wdoc.size.width as usize, - wdoc.bounds(), - &st, - wdoc.icc_profile.as_deref().map(|v| v.as_slice()), - exif, - xmp.as_deref(), - wdoc.resolution_dpi, - false, - )?; - write_file(&path, &opt.bytes)?; - crate::automate_cmds::fire_event(s, "export"); - Ok(json!({"path": path, "format": fmt, "bytes": opt.bytes.len(), "warnings": web_warnings(&st, exif, wdoc.resolution_dpi)})) -} - -// ---------- Generate › Image Assets ---------- - -/// One asset requested by a layer name. -#[derive(Clone, Debug, PartialEq)] -pub struct AssetSpec { - /// Relative output path (folders allowed), extension included. - pub file: String, - /// png8 | png24 | png32 | jpg | gif | webp - pub format: String, - /// JPEG quality 1..=100. - pub quality: Option, - /// Uniform scale (1.0 = 100 %). - pub scale: Option, - /// Target width / height in px (`?` = keep aspect). - pub width: Option, - pub height: Option, -} - -/// A `default` layer variant: size plus a folder (`low/`) or name suffix (`@2x`). -#[derive(Clone, Debug, Default, PartialEq)] -pub struct AssetDefault { - pub scale: Option, - pub width: Option, - pub height: Option, - pub folder: String, - pub suffix: String, -} - -fn unit_px(tok: &str, dpi: f64) -> Option> { - if tok == "?" { - return Some(None); - } - let (num, k) = if let Some(n) = tok.strip_suffix("px") { - (n, 1.0) - } else if let Some(n) = tok.strip_suffix("in") { - (n, dpi) - } else if let Some(n) = tok.strip_suffix("cm") { - (n, dpi / 2.54) - } else if let Some(n) = tok.strip_suffix("mm") { - (n, dpi / 25.4) - } else { - (tok, 1.0) - }; - num.trim().parse::().ok().filter(|v| *v > 0.0).map(|v| Some(v * k)) -} - -/// `200%` or `WxH` (units px/in/cm/mm, `?` wildcard) at the start of `item`; returns the size and -/// the rest. -fn parse_size(item: &str, dpi: f64) -> (Option, Option, Option, &str) { - let item = item.trim(); - let (first, rest) = item.split_once(char::is_whitespace).map_or((item, ""), |(a, b)| (a, b.trim())); - if let Some(pc) = first.strip_suffix('%').and_then(|n| n.parse::().ok()).filter(|v| *v > 0.0) { - return (Some(pc / 100.0), None, None, rest); - } - // "100x50", "2in x 1in", "?x100" - if let Some((w, h)) = first.split_once(['x', 'X']).filter(|(w, h)| !w.is_empty() && !h.is_empty()) - && let (Some(w), Some(h)) = (unit_px(w, dpi), unit_px(h, dpi)) - { - return (None, w, h, rest); - } - // Spaced form "2in x 1in name.png": three tokens. - let toks: Vec<&str> = item.split_whitespace().collect(); - if toks.len() >= 4 - && toks[1].eq_ignore_ascii_case("x") - && let (Some(w), Some(h)) = (unit_px(toks[0], dpi), unit_px(toks[2], dpi)) - { - // Skip exactly the three size tokens; searching for the name's first word could match inside the size. - let mut rest = item; - for _ in 0..3 { - rest = rest.trim_start().trim_start_matches(|c: char| !c.is_whitespace()); - } - return (None, w, h, rest.trim_start()); - } - (None, None, None, item) -} - -/// Parses a layer name into its asset specs (empty when it names no asset). -pub fn parse_asset_name(name: &str, dpi: f64) -> Vec { - let mut out = Vec::new(); - for item in name.split([',', '+']) { - let (scale, width, height, rest) = parse_size(item, dpi); - let file = rest.trim(); - let Some((stem_part, ext)) = file.rsplit_once('.') else { continue }; - if stem_part.is_empty() { - continue; - } - let ext_l = ext.to_ascii_lowercase(); - let (format, quality, out_ext) = if let Some(q) = ext_l.strip_prefix("jpeg").or_else(|| ext_l.strip_prefix("jpg")) { - let q = q.trim(); - let quality = if q.is_empty() { - None - } else if let Some(pc) = q.strip_suffix('%') { - pc.parse::().ok().map(|v| v.clamp(1, 100) as u8) - } else { - // 1–10 scale. - q.parse::().ok().map(|v| (v.clamp(1, 10) * 10) as u8) - }; - if !q.is_empty() && quality.is_none() { - continue; - } - ("jpg".to_string(), quality, if ext_l.starts_with("jpeg") { "jpeg" } else { "jpg" }) - } else { - match ext_l.as_str() { - "png" | "png32" => ("png32".to_string(), None, "png"), - "png24" => ("png24".to_string(), None, "png"), - "png8" => ("png8".to_string(), None, "png"), - "gif" => ("gif".to_string(), None, "gif"), - "webp" => ("webp".to_string(), None, "webp"), - _ => continue, - } - }; - out.push(AssetSpec { file: format!("{stem_part}.{out_ext}"), format, quality, scale, width, height }); - } - out -} - -/// Parses a `default …` layer name into its variants. -pub fn parse_defaults(name: &str, dpi: f64) -> Option> { - let rest = name.trim().strip_prefix("default")?; - if !rest.is_empty() && !rest.starts_with(char::is_whitespace) { - return None; - } - let mut v = Vec::new(); - for item in rest.split([',', '+']) { - let (scale, width, height, tail) = parse_size(item, dpi); - let tail = tail.trim(); - let (folder, suffix) = match tail.rfind('/') { - Some(i) => (tail[..=i].to_string(), tail[i + 1..].to_string()), - None => (String::new(), tail.to_string()), - }; - if scale.is_none() && width.is_none() && height.is_none() && folder.is_empty() && suffix.is_empty() { - continue; - } - v.push(AssetDefault { scale, width, height, folder, suffix }); - } - Some(v) -} - -fn asset_settings(spec: &AssetSpec) -> WebSettings { - let base = WebSettings { transparency: true, matte: None, metadata: WebMetadata::None, ..WebSettings::default() }; - match spec.format.as_str() { - "jpg" => WebSettings { format: WebFormat::Jpeg, quality: spec.quality.unwrap_or(90), matte: Some([1.0, 1.0, 1.0]), ..base }, - "png8" => WebSettings { format: WebFormat::Png8, dither: Dither::None, ..base }, - "png24" => WebSettings { format: WebFormat::Png24, transparency: false, matte: Some([1.0, 1.0, 1.0]), ..base }, - "gif" => WebSettings { format: WebFormat::Gif, dither: Dither::None, ..base }, - _ => WebSettings { format: WebFormat::Png24, ..base }, - } -} - -/// Layer names and `default` folders are document data, so reject unsafe output components. -fn asset_path_components(relative: &str) -> Result> { - // Split both separator styles even on Unix, where a backslash would otherwise be a legal - // filename. This also catches Windows drive, rooted, and UNC paths on every platform. - let mut parts = Vec::new(); - for part in relative.split(['/', '\\']) { - if part.is_empty() - || part == "." - || part == ".." - || part.ends_with('.') - || part.ends_with(' ') - || part.contains(':') - || part.contains('\0') - || is_windows_device_name(part) - { - return Err(other(format!("asset path {relative:?} has an unsafe component {part:?}"))); - } - parts.push(part); - } - Ok(parts) -} - -/// Resolve a generated asset below the selected output directory. The atomic writer follows an -/// existing file symlink, so reject it and directory symlinks before writing. -fn asset_output_path(dir: &str, relative: &str) -> Result<(String, String)> { - if dir.is_empty() { - return Err(other("image assets need an output directory")); - } - let mut parts = asset_path_components(relative)?; - // Keep the caller's spelling in the result (for example /var on macOS), while writes use - // the canonical directory so a symlink in the selected root cannot move the destination. - let mut reported = std::path::PathBuf::from(dir); - for part in &parts { - reported.push(part); - } - let file = parts.pop().ok_or_else(|| other(format!("asset path {relative:?} is empty")))?; - let chosen_root: std::path::PathBuf = std::path::Path::new(dir).components().collect(); - std::fs::create_dir_all(&chosen_root).map_err(|e| other(format!("asset output directory {dir:?}: {e}")))?; - // The caller chose this root, so a symlink to an existing directory is intentional. All - // document-derived components below it are checked against its canonical target. - let root = std::fs::canonicalize(&chosen_root).map_err(|e| other(format!("asset output directory {dir:?}: {e}")))?; - let mut parent = root.clone(); - for part in parts { - parent.push(part); - match std::fs::symlink_metadata(&parent) { - Ok(meta) if meta.file_type().is_symlink() => { - return Err(other(format!("asset path {relative:?} crosses a symlink at {}", parent.display()))); - } - Ok(meta) if !meta.is_dir() => { - return Err(other(format!("asset path {relative:?} has a non-directory at {}", parent.display()))); - } - Ok(_) => {} - Err(e) if e.kind() == std::io::ErrorKind::NotFound => { - std::fs::create_dir(&parent).map_err(|e| other(format!("asset folder {}: {e}", parent.display())))?; - } - Err(e) => return Err(other(format!("asset folder {}: {e}", parent.display()))), - } - let actual = std::fs::canonicalize(&parent).map_err(|e| other(format!("asset folder {}: {e}", parent.display())))?; - if !actual.starts_with(&root) { - return Err(other(format!("asset path {relative:?} escapes output directory {dir:?}"))); - } - parent = actual; - } - let parent = std::fs::canonicalize(&parent).map_err(|e| other(format!("asset folder {}: {e}", parent.display())))?; - if !parent.starts_with(&root) { - return Err(other(format!("asset path {relative:?} escapes output directory {dir:?}"))); - } - let output = parent.join(file); - match std::fs::symlink_metadata(&output) { - Ok(meta) if meta.file_type().is_symlink() => { - return Err(other(format!("asset path {relative:?} points to a symlink"))); - } - Ok(meta) if !meta.is_file() => { - return Err(other(format!("asset path {relative:?} is not a file"))); - } - Ok(_) => {} - Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} - Err(e) => return Err(other(format!("asset path {relative:?}: {e}"))), - } - Ok((output.to_string_lossy().into_owned(), reported.to_string_lossy().into_owned())) -} - -/// Exports every asset named by `doc`'s layers into `dir`. Returns (files, errors). -/// -/// Each file is written once per run (#6614): when two layers (or two default variants) name the -/// same file, the one higher in the Layers panel keeps it and the other is reported in `errors`. -/// Names are compared ignoring case, as `Logo.png` and `logo.png` are one file on Windows and -/// macOS. -/// -/// A layer is trimmed to its visible pixels; an artboard keeps its whole board, transparent edges -/// included, as File › Export › Artboards to Files writes it (Photoshop's Generator exports an -/// artboard asset at the board's bounds). -pub fn generate_assets(doc: &Document, dir: &str) -> (Vec, Vec) { - let dpi = f64::from(doc.resolution_dpi.max(1.0)); - let mut defaults: Option> = None; - let mut by_layer: Vec> = Vec::new(); - for (_, _, l) in doc.walk() { - if let Some(d) = parse_defaults(&l.name, dpi) { - defaults = Some(d); - continue; - } - if matches!(l.content, LayerContent::Adjustment(_)) { - continue; - } - by_layer.push(parse_asset_name(&l.name, dpi).into_iter().map(|spec| (l.id, spec)).collect()); - } - // Top layer first, as the Layers panel lists them (`walk` goes bottom to top). - let jobs: Vec<(LayerId, AssetSpec)> = by_layer.into_iter().rev().flatten().collect(); - let variants: Vec = match defaults { - Some(d) if !d.is_empty() => d, - _ => vec![AssetDefault::default()], - }; - let mut files = Vec::new(); - let mut errors = Vec::new(); - let mut written = std::collections::HashSet::new(); - for (id, spec) in &jobs { - for v in &variants { - let r = (|| -> Result { - let (name_stem, ext) = spec.file.rsplit_once('.').unwrap_or((spec.file.as_str(), "png")); - let rel = format!("{}{}{}.{ext}", v.folder, name_stem, v.suffix); - let key = asset_path_components(&rel)?.join("/").to_lowercase(); - if written.contains(&key) { - return Err(other(format!("{rel}: another layer already writes this file; rename one of the layers"))); - } - let mut one = match crate::artboard_cmds::artboard_document(doc, *id)? { - // Like Photoshop's Generator, a board with nothing on it is refused rather - // than written as a blank file. - Some(board) if !has_pixels(&board) => return Err(other("the layer is empty")), - Some(board) => board, - None => crate::layer_menu_cmds::layer_document(doc, *id)?, - }; - one.metadata = Default::default(); - let (w0, h0) = (f64::from(one.size.width), f64::from(one.size.height)); - // The layer's own size spec wins; default variants scale on top of it. - let mut k = spec.scale.unwrap_or(1.0); - let (mut tw, mut th) = (w0 * k, h0 * k); - match (spec.width, spec.height) { - (Some(w), Some(h)) => (tw, th) = (w, h), - (Some(w), None) => (tw, th) = (w, h0 * w / w0), - (None, Some(h)) => (tw, th) = (w0 * h / h0, h), - _ => {} - } - k = v.scale.unwrap_or(1.0); - tw *= k; - th *= k; - match (v.width, v.height) { - (Some(w), Some(h)) => (tw, th) = (w, h), - (Some(w), None) => (tw, th) = (w, th * w / tw), - (None, Some(h)) => (tw, th) = (tw * h / th, h), - _ => {} - } - let st = asset_settings(spec); - let p = json!({"width": tw.round().max(1.0), "height": th.round().max(1.0)}); - let (wdoc, _, _) = web_document(&one, &p, &WebSettings { convert_to_srgb: true, ..st.clone() })?; - if spec.format == "webp" { - let (out, reported) = asset_output_path(dir, &rel)?; - crate::file_cmds::save_doc(&wdoc, &out, None)?; - written.insert(key); - return Ok(reported); - } - let buf = photocraft_compose::flatten(&wdoc); - let o = optimize(&buf.px, wdoc.size.width as usize, wdoc.bounds(), &st, None, None, None, wdoc.resolution_dpi, false)?; - let (out, reported) = asset_output_path(dir, &rel)?; - write_file(&out, &o.bytes)?; - written.insert(key); - Ok(reported) - })(); - match r { - Ok(f) => files.push(f), - Err(e) => errors.push(json!({"asset": spec.file, "error": e.to_string()})), - } - } - } - (files, errors) -} - -/// Whether any pixel of `doc` is not fully transparent. -fn has_pixels(doc: &Document) -> bool { - photocraft_compose::render(doc, doc.bounds()).px.iter().any(|q| q[3] > 0.0) -} - -/// `/-assets`. -pub fn assets_dir(doc_path: &str) -> String { - let p = std::path::Path::new(doc_path); - let dir = p.parent().map(|d| d.to_string_lossy().into_owned()).unwrap_or_default(); - join(&dir, &format!("{}-assets", stem(doc_path))) -} - -/// File › Generate › Image Assets: toggles generation for the active document (or sets it with -/// `on`) and, when it is on and the output folder is known, writes the assets now. -fn image_assets(s: &mut Session, p: &Value) -> Result { - let d = s.active().ok_or(EngineError::NoDocument)?; - let id: DocId = d.doc.id; - let was = s.file_menu.image_assets.contains(&id); - let on = p.get("on").and_then(Value::as_bool).unwrap_or(!was); - if on { - if !was { - s.file_menu.image_assets.push(id); - } - } else { - s.file_menu.image_assets.retain(|x| *x != id); - } - let d = s.active().ok_or(EngineError::NoDocument)?; - let dir = p.get("dir").and_then(Value::as_str).map(str::to_string).or_else(|| d.path.as_deref().map(assets_dir)); - if !on { - return Ok(json!({"enabled": false})); - } - match dir { - Some(dir) if !cfg!(target_arch = "wasm32") => { - let (files, errors) = generate_assets(&d.doc, &dir); - Ok(json!({"enabled": true, "dir": dir, "files": files, "errors": errors})) - } - _ => Ok(json!({"enabled": true, "dir": null, "files": [], "note": "assets are written when the document is saved"})), - } -} - -/// After a save: regenerate the document's image assets when Generate › Image Assets is on. -pub fn on_saved(s: &Session, index: usize) -> Option { - let d = s.documents().get(index)?; - if !s.file_menu.image_assets.contains(&d.doc.id) || !s.prefs().plug_ins.generator_enabled || cfg!(target_arch = "wasm32") { - return None; - } - let dir = assets_dir(d.path.as_deref()?); - let (files, errors) = generate_assets(&d.doc, &dir); - Some(json!({"dir": dir, "files": files, "errors": errors})) -} - -pub fn specs() -> Vec { - macro_rules! spec { - ($id:expr, $label:expr, $menu:expr, $sc:expr, $params:expr, $enabled:expr, $run:expr) => { - CommandSpec { id: $id, label: $label, menu: $menu, shortcut: $sc, params: $params, enabled: $enabled, journal: true, run: $run } - }; - } - fn has_doc(s: &Session) -> std::result::Result<(), String> { - s.active().map(|_| ()).ok_or_else(|| "no document open".into()) - } - - /// Generate ▸ Image Assets needs Preferences ▸ Plug-ins ▸ Generator enabled, as in - /// Photoshop (where "Enable Generator" is unchecked until turned on). - fn generator_enabled(s: &Session) -> std::result::Result<(), String> { - has_doc(s)?; - if !s.prefs().plug_ins.generator_enabled { - return Err("Enable Generator in Preferences ▸ Plug-ins".into()); - } - Ok(()) - } - vec![ - spec!( - "file.export.saveForWebLegacy", - "Save for Web (Legacy)…", - &["File", "Export"], - Some("Cmd+Alt+Shift+S"), - r##"{"preset":"GIF 128 Dithered|JPEG High|PNG-24|…"?,"format":"gif|png8|png24|jpeg|wbmp"="png24","palette":"perceptual|selective|adaptive|restrictive|exact|systemMac|systemWindows|uniform"="selective","colors":2..256=256,"colorTable":["#rrggbb",…]? (fixed opaque source palette, 1–256 entries; 255 with transparency),"colorTableEdits":{"0":"#rrggbb",…}? (replace entries after indexing; requires colorTable),"dither":"none|diffusion|pattern|noise"="diffusion","ditherAmount":0..100=88,"transparency":bool=true,"matte":"#rrggbb|none"="none" (a preset's own: white; formats without transparency go over white),"interlaced":bool=false,"webSnap":0..100=0,"quality":0..100=60,"progressive":bool=false,"optimized":bool=true,"embedIcc":bool=false,"metadata":"none|copyright|copyrightAndContact|allExceptCameraInfo|all"="copyright" (EXIF only with all),"convertToSrgb":bool=true,"width"|"height"|"percent"? (image size),"resample":"bicubic|bilinear|nearest"?,"path":file? (whole image),"dir":folder? (one file per slice in images/),"imagesFolder":relative-folder?="images","html":bool=false,"trustedSliceHtml":bool=false (only for trusted documents; emit raw no-image cell HTML),"slices":"all|user"="all","numbers":[n]?} → no path/dir: {bytes,width,height,colors,colorTable,transparentIndex} estimate; else {files, html, bytes, warnings}"##, - has_doc, - save_for_web - ), - spec!( - "file.export.exportPreferences", - "Export Preferences…", - &["File", "Export"], - None, - r##"{"quickExportFormat":"png|jpg|gif|webp|exr"?,"quickExportLocation":"ask|sameFolder"?,"jpegQuality":1..100?,"webpLossless":bool?,"webpQuality":1..100?,"metadata":"none|copyright|all"?,"convertToSrgb":bool?} → {values}"##, - |_| Ok(()), - export_preferences - ), - spec!( - "file.export.quickExport", - "Quick Export", - &[], - None, - r##"{"path":str? (required unless Export Preferences › Location is "sameFolder" and the document is saved)} → {path, format, bytes, warnings}"##, - native_doc, - quick_export - ), - spec!( - "file.generate.imageAssets", - "Image Assets", - &["File", "Generate"], - None, - r##"{"on":bool? (default: toggle),"dir":folder? (default -assets next to the file)} → {enabled, files, errors}; layers named like "foo.png", "200% foo@2x.png", "48x48 icons/a.png8", "photo.jpg80%" are exported, now and after each save"##, - generator_enabled, - image_assets - ), - ] -} - -#[cfg(test)] -#[path = "web_cmds/tests.rs"] -mod tests; diff --git a/crates/engine/tests/it/prefs_usage.rs b/crates/engine/tests/it/prefs_usage.rs index 7b9adebdd1..eabad21ed8 100644 --- a/crates/engine/tests/it/prefs_usage.rs +++ b/crates/engine/tests/it/prefs_usage.rs @@ -44,15 +44,36 @@ fn has_ident(text: &str, prefix: &str, ident: &str) -> bool { }) } -/// Production source of a file: everything before its unit-test module. -fn production(text: &str) -> &str { +/// Production source of a file: the file without its inline unit-test modules +/// (`#[cfg(test)] mod tests { … }` at the top level, closed by `}` at column 0). A declaration +/// (`#[cfg(test)] mod tests;`) can come before the rest of the code, so it doesn't end the scan. +fn production(text: &str) -> String { // Windows checkouts may use CRLF; test-only reads must stay excluded. - let cut = ["#[cfg(test)]\nmod ", "#[cfg(test)]\r\nmod ", "#[cfg(test)]\npub mod ", "#[cfg(test)]\r\npub mod "] - .into_iter() - .filter_map(|marker| text.find(marker)) - .min() - .unwrap_or(text.len()); - &text[..cut] + let marker = "#[cfg(test)]"; + let mut out = String::with_capacity(text.len()); + let mut rest = text; + while let Some(at) = rest.match_indices(marker).map(|(i, _)| i).find(|&i| i == 0 || rest[..i].ends_with('\n')) { + let after = &rest[at + marker.len()..]; + let item = after.trim_start(); + let item = item.strip_prefix("pub ").unwrap_or(item); + let body = item.strip_prefix("mod ").and_then(|m| { + let name_end = m.find(|c: char| !c.is_alphanumeric() && c != '_')?; + m[name_end..].trim_start().strip_prefix('{') + }); + let Some(body) = body else { + out.push_str(&rest[..at + marker.len()]); + rest = after; + continue; + }; + out.push_str(&rest[..at]); + let Some(end) = body.match_indices("\n}").map(|(i, _)| i + 2).find(|&e| matches!(body[e..].chars().next(), None | Some('\r' | '\n'))) else { + return out; + }; + let tail = &body[end..]; + rest = tail.strip_prefix("\r\n").or_else(|| tail.strip_prefix('\n')).unwrap_or(tail); + } + out.push_str(rest); + out } fn rust_sources(dir: &Path, out: &mut Vec) { @@ -96,12 +117,22 @@ fn every_preference_is_read_or_hidden() { let mut files = Vec::new(); rust_sources(&root.join("crates"), &mut files); rust_sources(&root.join("apps"), &mut files); - let sources: Vec = files - .iter() - .filter(|p| !p.ends_with("engine/src/prefs.rs")) - .filter_map(|p| std::fs::read_to_string(p).ok()) - .map(|t| production(&t).to_string()) + let prefs_dir = root.join("crates/engine/src/prefs"); + let files: Vec<(PathBuf, String)> = files + .into_iter() + .filter(|p| !p.ends_with("engine/src/prefs.rs") && !p.starts_with(&prefs_dir)) + .filter_map(|p| std::fs::read_to_string(&p).ok().map(|t| (p, production(&t)))) .collect(); + let mut sources: Vec = files.iter().map(|(_, t)| t.clone()).collect(); + // A module split into child files (`foo.rs` + `foo/*.rs`) counts as one file too, so a section + // named in the parent and a field read in a child still count as a read. + for (path, text) in &files { + let dir = path.with_extension(""); + let children: Vec<&str> = files.iter().filter(|(p, _)| p.starts_with(&dir)).map(|(_, t)| t.as_str()).collect(); + if !children.is_empty() { + sources.push([text.as_str()].into_iter().chain(children).collect::>().join("\n")); + } + } assert!(sources.len() > 100, "found only {} source files under {}", sources.len(), root.display()); // Section key → struct name, from `pub : ,` in `struct Preferences`. diff --git a/crates/geom/src/warp.rs b/crates/geom/src/warp.rs index 0ca3c36b98..90c70cc30f 100644 --- a/crates/geom/src/warp.rs +++ b/crates/geom/src/warp.rs @@ -1215,472 +1215,4 @@ impl Warp { } #[cfg(test)] -mod tests { - use super::*; - - const B: [f64; 4] = [10.0, 20.0, 110.0, 70.0]; - - /// The largest mismatch between the tangents on the two sides of any interior grid line. - fn tangent_defect(m: &BezierMesh) -> f64 { - let nx = m.nx(); - let mut worst: f64 = 0.0; - for a in 1..m.us.len() - 1 { - let (hl, hr) = (m.us[a] - m.us[a - 1], m.us[a + 1] - m.us[a]); - for j in 0..m.ny() { - let (l, c, r) = (m.points[j * nx + 3 * a - 1], m.points[j * nx + 3 * a], m.points[j * nx + 3 * a + 1]); - for k in 0..2 { - worst = worst.max(((c[k] - l[k]) / hl - (r[k] - c[k]) / hr).abs()); - } - } - } - for b in 1..m.vs.len() - 1 { - let (hl, hr) = (m.vs[b] - m.vs[b - 1], m.vs[b + 1] - m.vs[b]); - for i in 0..nx { - let (l, c, r) = (m.points[(3 * b - 1) * nx + i], m.points[3 * b * nx + i], m.points[(3 * b + 1) * nx + i]); - for k in 0..2 { - worst = worst.max(((c[k] - l[k]) / hl - (r[k] - c[k]) / hr).abs()); - } - } - } - worst - } - - #[test] - fn dragging_an_anchor_or_handle_keeps_the_surface_smooth_across_the_lines() { - let mut base = BezierMesh::identity([0.0, 0.0, 300.0, 300.0], 1, 1); - for s in [0.3, 0.55, 0.9] { - assert!(base.split_u(s)); - assert!(base.split_v(s)); - } - let nx = base.nx(); - // Every kind of point on a grid line, interior and border: anchors, handles each way. - for (i, j) in [(6, 6), (7, 6), (5, 6), (6, 7), (6, 5), (3, 9), (9, 3), (0, 6), (6, 0), (4, 3), (3, 4), (12, 12)] { - let mut m = base.clone(); - m.drag_point(&base.points, j * nx + i, [23.0, -31.0]); - assert_eq!(m.points[j * nx + i], [base.points[j * nx + i][0] + 23.0, base.points[j * nx + i][1] - 31.0], "({i}, {j}) lands on the pointer"); - assert!(tangent_defect(&m) < 1e-6, "({i}, {j}): {}", tangent_defect(&m)); - } - } - - /// Fraction of the surface where the map folds over itself (its Jacobian is not positive). - fn fold_fraction(m: &BezierMesh) -> f64 { - let (n, h) = (80, 1e-4); - let mut bad = 0; - for j in 0..n { - for i in 0..n { - let (s, t) = ((i as f64 + 0.5) / n as f64, (j as f64 + 0.5) / n as f64); - let q = m.eval(s, t); - let (qs, qt) = (m.eval(s + h, t), m.eval(s, t + h)); - if (qs[0] - q[0]) * (qt[1] - q[1]) - (qt[0] - q[0]) * (qs[1] - q[1]) <= 0.0 { - bad += 1; - } - } - } - bad as f64 / (n * n) as f64 - } - - #[test] - fn a_pull_within_a_quarter_cell_never_folds_the_surface() { - // 75 px cells: dragging a quarter of a cell, any direction, anywhere in the grid must not tear the picture. - let base = BezierMesh::identity([0.0, 0.0, 300.0, 300.0], 4, 4); - for (s, t) in [(0.42, 0.42), (0.75, 0.2), (0.2, 0.2), (0.5, 0.5), (0.85, 0.7), (0.3, 0.7)] { - for (dx, dy) in [(-1.0, 0.0), (1.0, 0.0), (0.0, -1.0), (0.0, 1.0), (0.7, 0.7), (-0.7, 0.7)] { - let mut m = base.clone(); - m.pull(&base.points, s, t, [dx * 19.0, dy * 19.0]); - assert_eq!(fold_fraction(&m), 0.0, "({s}, {t}) by ({dx}, {dy}) quarter cells"); - } - } - } - - #[test] - fn a_pull_in_the_middle_leaves_the_border_where_it_is() { - let mut base = BezierMesh::identity([0.0, 0.0, 600.0, 800.0], 1, 1); - for s in [0.33, 0.66] { - assert!(base.split_u(s)); - } - assert!(base.split_v(0.5)); - let (nx, ny) = (base.nx(), base.ny()); - let on_border = |i: usize, j: usize| i == 0 || j == 0 || i == nx - 1 || j == ny - 1; - let mut m = base.clone(); - m.pull(&base.points, 0.5, 0.5, [-180.0, 40.0]); - for j in 0..ny { - for i in 0..nx { - if on_border(i, j) { - let (a, b) = (m.points[j * nx + i], base.points[j * nx + i]); - assert!((a[0] - b[0]).abs() < 1e-6 && (a[1] - b[1]).abs() < 1e-6, "border point ({i}, {j}) moved"); - } - } - } - // The pull itself still lands exactly. - let (before, after) = (base.eval(0.5, 0.5), m.eval(0.5, 0.5)); - assert!((after[0] - before[0] + 180.0).abs() < 1e-4 && (after[1] - before[1] - 40.0).abs() < 1e-4); - } - - #[test] - fn a_pull_anywhere_away_from_the_border_never_moves_the_border() { - // The default one-patch grid and a cut one; grabs all over, none within 12% of an edge. - let one = BezierMesh::identity([0.0, 0.0, 600.0, 800.0], 1, 1); - let mut cut = one.clone(); - assert!(cut.split_u(0.4) && cut.split_u(0.7) && cut.split_v(0.35) && cut.split_v(0.8)); - for base in [one, cut] { - let (nx, ny) = (base.nx(), base.ny()); - for (s, t) in [(0.5, 0.5), (0.2, 0.5), (0.8, 0.3), (0.3, 0.85), (0.14, 0.14), (0.86, 0.5)] { - for d in [[-400.0, 0.0], [250.0, -90.0], [0.0, 300.0]] { - let mut m = base.clone(); - m.pull(&base.points, s, t, d); - for j in 0..ny { - for i in 0..nx { - if i == 0 || j == 0 || i == nx - 1 || j == ny - 1 { - let (a, b) = (m.points[j * nx + i], base.points[j * nx + i]); - assert!((a[0] - b[0]).abs() < 1e-6 && (a[1] - b[1]).abs() < 1e-6, "({s}, {t}) by {d:?} moved border point ({i}, {j})"); - } - } - } - let (before, after) = (base.eval(s, t), m.eval(s, t)); - assert!((after[0] - before[0] - d[0]).abs() < 1e-3 && (after[1] - before[1] - d[1]).abs() < 1e-3, "({s}, {t}) by {d:?}: {after:?}"); - } - } - } - } - - #[test] - fn pulling_on_the_border_bows_it_and_leaves_the_corners_put() { - // A one-patch grid, grabbed on the middle of its right edge and pulled 170 px out. - let base = BezierMesh::identity([0.0, 0.0, 800.0, 1200.0], 1, 1); - let mut m = base.clone(); - m.pull(&base.points, 1.0, 0.5, [170.0, 0.0]); - let at = m.eval(1.0, 0.5); - assert!((at[0] - 970.0).abs() < 1e-3 && (at[1] - 600.0).abs() < 1e-3, "{at:?}"); - for (s, t) in [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0), (1.0, 1.0)] { - let (a, b) = (m.eval(s, t), base.eval(s, t)); - assert!((a[0] - b[0]).abs() < 1e-6 && (a[1] - b[1]).abs() < 1e-6, "corner ({s}, {t}) moved"); - } - // The other three edges did not move. - for k in 0..=10 { - let u = k as f64 / 10.0; - for (s, t) in [(0.0, u), (u, 0.0), (u, 1.0)] { - let (a, b) = (m.eval(s, t), base.eval(s, t)); - assert!((a[0] - b[0]).abs() < 1e-6 && (a[1] - b[1]).abs() < 1e-6, "edge point ({s}, {t}) moved"); - } - } - // Only the right edge's two handles carry the pull. - let nx = base.nx(); - let moved: Vec = (0..m.points.len()).filter(|k| m.points[*k] != base.points[*k]).collect(); - assert_eq!(moved, vec![nx + 3, 2 * nx + 3], "{moved:?}"); - assert_eq!(fold_fraction(&m), 0.0); - } - - #[test] - fn pull_keeps_the_surface_smooth_across_the_grid_lines() { - // A grid cut unevenly both ways, then pulled hard inside one cell and then another. - let mut base = BezierMesh::identity([0.0, 0.0, 300.0, 300.0], 1, 1); - for s in [0.3, 0.55, 0.9] { - assert!(base.split_u(s)); - assert!(base.split_v(s)); - } - assert!(tangent_defect(&base) < 1e-9, "cuts are exact"); - for (s, t, d) in [(0.42, 0.42, [60.0, -35.0]), (0.75, 0.2, [-40.0, 50.0]), (0.1, 0.95, [30.0, 30.0])] { - let mut m = base.clone(); - m.pull(&base.points, s, t, d); - assert!(tangent_defect(&m) < 1e-6, "({s}, {t}): {}", tangent_defect(&m)); - let before = base.eval(s, t); - let after = m.eval(s, t); - assert!((after[0] - before[0] - d[0]).abs() < 1e-4 && (after[1] - before[1] - d[1]).abs() < 1e-4, "{after:?}"); - } - } - - #[test] - fn pull_moves_the_grabbed_surface_point_exactly_and_stays_local() { - let base = BezierMesh::identity(B, 3, 2); - for (s, t) in [(0.5, 0.5), (0.1, 0.9), (0.4, 0.25), (0.0, 0.5), (1.0, 0.3)] { - let mut m = base.clone(); - let before = base.eval(s, t); - m.pull(&base.points, s, t, [7.0, -4.5]); - let after = m.eval(s, t); - assert!((after[0] - before[0] - 7.0).abs() < 1e-4 && (after[1] - before[1] + 4.5).abs() < 1e-4, "({s}, {t}): {after:?}"); - } - // The pull stays near the grabbed patch: the far end of the grid does not move. - let mut m = base.clone(); - m.pull(&base.points, 0.1, 0.25, [5.0, 5.0]); - let nx = base.nx(); - let moved = |k: usize| (m.points[k][0] - base.points[k][0]).abs() > 1e-6 || (m.points[k][1] - base.points[k][1]).abs() > 1e-6; - assert!((0..base.ny()).all(|j| !moved(j * nx + nx - 1)), "last column stays put"); - assert!((0..nx).any(moved), "something moved"); - // Pulling again from the same base replaces the pull (a drag is not cumulative). - m.pull(&base.points, 0.5, 0.25, [0.0, 0.0]); - assert!(m.points.iter().zip(&base.points).all(|(a, b)| (a[0] - b[0]).abs() < 1e-9 && (a[1] - b[1]).abs() < 1e-9)); - } - - fn close(a: (f64, f64), b: (f64, f64), eps: f64) -> bool { - (a.0 - b.0).abs() < eps && (a.1 - b.1).abs() < eps - } - - #[test] - fn styles_parse_and_round_trip_names() { - for s in WarpStyle::all() { - assert_eq!(WarpStyle::parse(s.id()), Some(s)); - assert_eq!(WarpStyle::parse(s.psd_name()), Some(s)); - assert_eq!(WarpStyle::parse(s.label()), Some(s), "{s:?}"); - } - assert_eq!(WarpStyle::parse("spiral"), None); - } - - #[test] - fn presets_at_bend_zero_are_identity() { - for s in WarpStyle::PRESETS { - let w = Warp::preset(s, 0.0, B); - assert!(w.is_identity()); - assert_eq!(w.map(33.0, 44.0), (33.0, 44.0)); - } - } - - #[test] - fn identity_mesh_is_exact_and_fit_reproduces_affine() { - let m = BezierMesh::identity(B, 1, 1); - assert_eq!((m.nx(), m.ny()), (4, 4)); - let w = Warp::custom(m, B); - assert!(w.is_identity()); - assert!(close(w.map(37.5, 61.25), (37.5, 61.25), 1e-9)); - // Affine maps fit exactly. - let f = |s: f64, t: f64| [3.0 + 2.0 * s - t, 1.0 + 0.5 * s + 4.0 * t]; - let m = BezierMesh::fit(&f, vec![0.0, 1.0], vec![0.0, 0.4, 1.0]); - for (s, t) in [(0.1, 0.9), (0.5, 0.2), (0.77, 0.41)] { - let p = m.eval(s, t); - let e = f(s, t); - assert!((p[0] - e[0]).abs() < 1e-9 && (p[1] - e[1]).abs() < 1e-9); - } - } - - #[test] - fn remove_split_u_rejects_out_of_range_indices() { - let original = BezierMesh::identity(B, 2, 3); - for k in [0, original.us.len() - 1, original.us.len(), usize::MAX - 1, usize::MAX] { - let mut mesh = original.clone(); - assert!(!mesh.remove_split_u(k), "index {k}"); - assert_eq!(mesh, original, "index {k} must leave the mesh unchanged"); - } - } - - #[test] - fn remove_split_v_rejects_out_of_range_indices() { - let original = BezierMesh::identity(B, 2, 3); - for k in [0, original.vs.len() - 1, original.vs.len(), usize::MAX - 1, usize::MAX] { - let mut mesh = original.clone(); - assert!(!mesh.remove_split_v(k), "index {k}"); - assert_eq!(mesh, original, "index {k} must leave the mesh unchanged"); - } - } - - #[test] - fn splits_are_exact_and_removable() { - let mut m = BezierMesh::identity(B, 1, 1); - // Bend it: move an inner control point. - m.points[5] = [50.0, 10.0]; - let before: Vec<[f64; 2]> = (0..=10).flat_map(|j| (0..=10).map(move |i| (i, j))).map(|(i, j)| m.eval(i as f64 / 10.0, j as f64 / 10.0)).collect(); - let orig = m.clone(); - assert!(m.split_u(0.3)); - assert!(m.split_v(0.6)); - assert!(!m.split_u(0.3), "existing boundary"); - assert_eq!((m.nx(), m.ny()), (7, 7)); - assert!(m.is_valid()); - let after: Vec<[f64; 2]> = (0..=10).flat_map(|j| (0..=10).map(move |i| (i, j))).map(|(i, j)| m.eval(i as f64 / 10.0, j as f64 / 10.0)).collect(); - for (a, b) in before.iter().zip(&after) { - assert!((a[0] - b[0]).abs() < 1e-9 && (a[1] - b[1]).abs() < 1e-9); - } - let (ls, lt) = m.param_at(m.eval(0.42, 0.77)); - assert!((ls - 0.42).abs() < 1e-6 && (lt - 0.77).abs() < 1e-6, "{ls},{lt}"); - assert!(m.remove_split_u(1)); - assert!(m.remove_split_v(1)); - assert_eq!(m.us, orig.us); - for (a, b) in m.points.iter().zip(&orig.points) { - assert!((a[0] - b[0]).abs() < 1e-9 && (a[1] - b[1]).abs() < 1e-9); - } - } - - const SQUARE: [f64; 4] = [128.0, 128.0, 384.0, 384.0]; - const WIDE: [f64; 4] = [128.0, 208.0, 384.0, 304.0]; - const TALL: [f64; 4] = [208.0, 128.0, 304.0, 384.0]; - - /// Photoshop 27.11, measured: a 256 px grid image whose colours encode each pixel's own - /// position, warped in a 512 px document over the box (128, 128)–(384, 384). Each pair is a - /// source point and where Photoshop put it. - #[test] - fn presets_match_photoshop() { - type Case = (WarpStyle, f64, f64, f64, bool, [([f64; 2], [f64; 2]); 3]); - let cases: [Case; 9] = [ - (WarpStyle::Arc, 50.0, 0.0, 0.0, false, [([272.5, 155.5], [296.5, 104.5]), ([331.5, 182.5], [424.5, 168.5]), ([259.5, 157.5], [264.5, 104.5])]), - (WarpStyle::Arc, -100.0, 0.0, 0.0, false, [([277.5, 354.5], [344.5, 472.5]), ([140.5, 218.5], [40.5, 168.5]), ([172.5, 237.5], [56.5, 264.5])]), - (WarpStyle::Flag, 50.0, 0.0, 0.0, false, [([136.5, 143.5], [136.5, 120.5]), ([136.5, 159.5], [136.5, 136.5]), ([136.5, 175.5], [136.5, 152.5])]), - (WarpStyle::Twist, -50.0, 0.0, 0.0, false, [([148.5, 205.5], [152.5, 216.5]), ([197.5, 212.5], [200.5, 232.5]), ([134.5, 212.5], [136.5, 216.5])]), - ( - WarpStyle::ShellLower, - 50.0, - 0.0, - 0.0, - false, - [([248.5, 136.5], [248.5, 136.5]), ([264.5, 136.5], [264.5, 136.5]), ([232.5, 136.5], [232.5, 136.5])], - ), - (WarpStyle::Fish, -100.0, 0.0, 0.0, false, [([296.5, 355.5], [296.5, 440.5]), ([344.5, 298.5], [344.5, 344.5]), ([328.5, 356.5], [328.5, 472.5])]), - (WarpStyle::Bulge, 50.0, 50.0, 0.0, false, [([293.5, 147.5], [296.5, 88.5]), ([293.5, 375.5], [296.5, 440.5]), ([340.5, 281.5], [344.5, 296.5])]), - (WarpStyle::Arc, 50.0, 0.0, -50.0, false, [([181.5, 350.5], [184.5, 328.5]), ([291.5, 372.5], [280.5, 344.5]), ([232.5, 349.5], [232.5, 312.5])]), - (WarpStyle::Arc, 50.0, 0.0, 0.0, true, [([155.5, 272.5], [104.5, 296.5]), ([182.5, 331.5], [168.5, 424.5]), ([157.5, 259.5], [104.5, 264.5])]), - ]; - // Wide (256 × 96 at 128, 208) and tall (96 × 256 at 208, 128) boxes, and a vertical warp - // with distortion. - type Boxed = (WarpStyle, f64, f64, f64, bool, [f64; 4], [([f64; 2], [f64; 2]); 2]); - let boxed: [Boxed; 6] = [ - (WarpStyle::Arc, 50.0, 0.0, 0.0, false, WIDE, [([144.5, 269.6], [120.5, 264.5]), ([271.5, 220.42], [280.5, 168.5])]), - (WarpStyle::Bulge, 50.0, 0.0, 0.0, false, TALL, [([249.11, 374.5], [248.5, 392.5]), ([249.11, 360.5], [248.5, 376.5])]), - (WarpStyle::Flag, 50.0, 0.0, 0.0, true, WIDE, [([137.5, 296.42], [184.5, 296.5]), ([153.5, 296.42], [200.5, 296.5])]), - (WarpStyle::Rise, 50.0, 0.0, 0.0, true, TALL, [([250.97, 152.5], [344.5, 152.5]), ([301.26, 264.5], [344.5, 264.5])]), - (WarpStyle::Bulge, 60.0, 20.0, -10.0, false, WIDE, [([208.5, 224.15], [200.5, 184.5]), ([219.5, 277.42], [216.5, 296.5])]), - (WarpStyle::Arc, 50.0, 30.0, 0.0, true, SQUARE, [([331.5, 327.5], [296.5, 360.5]), ([318.5, 240.5], [264.5, 232.5])]), - ]; - let all = - cases.iter().map(|c| (c.0, c.1, c.2, c.3, c.4, SQUARE, c.5.to_vec())).chain(boxed.iter().map(|c| (c.0, c.1, c.2, c.3, c.4, c.5, c.6.to_vec()))); - for (style, bend, hd, vd, vertical, bounds, pairs) in all { - let w = Warp { h_distort: hd, v_distort: vd, vertical, ..Warp::preset(style, bend, bounds) }; - for (src, want) in pairs { - let got = w.map(src[0], src[1]); - let d = (got.0 - want[0]).hypot(got.1 - want[1]); - assert!(d < 1.5, "{style:?} {bend} h{hd} v{vd} vertical {vertical} {bounds:?}: {src:?} -> {got:?}, Photoshop {want:?}"); - } - } - } - - #[test] - fn preset_fits_closely_as_mesh_and_affine_composes() { - let w = Warp::preset(WarpStyle::Bulge, 40.0, B); - let m = Warp::custom(w.to_mesh(4, 4), B); - for (x, y) in [(20.0, 30.0), (60.0, 45.0), (100.0, 65.0)] { - assert!(close(w.map(x, y), m.map(x, y), 0.5), "{:?} vs {:?}", w.map(x, y), m.map(x, y)); - } - let t = Warp::custom(BezierMesh::identity(B, 1, 1), B).then_affine([1.0, 0.0, 0.0, 1.0, 5.0, -2.0]); - assert!(close(t.map(50.0, 50.0), (55.0, 48.0), 1e-9)); - let ob = Warp::none(B).output_bounds(); - assert!((ob[0] - 10.0).abs() < 1e-9 && (ob[3] - 70.0).abs() < 1e-9); - } - - /// A cylinder over a 1000 × 1000 source like #4112's: silhouettes at x 100 and 900, edges at - /// y 200 (top) and 800 (bottom), ellipses 0.3 deep, half wrapped round. - const CYL: [f64; 7] = [100.0, 800.0, 900.0, 200.0, 0.3, 0.3, 0.5]; - - #[test] - fn cylinder_style_is_read_and_named_but_not_a_bend_preset() { - for s in ["cylinder", "warpCylinder", "Cylinder"] { - assert_eq!(WarpStyle::parse(s), Some(WarpStyle::Cylinder), "{s}"); - } - assert_eq!(WarpStyle::Cylinder.psd_name(), "warpCylinder"); - assert_eq!(WarpStyle::Cylinder.id(), "cylinder"); - assert!(!WarpStyle::Cylinder.is_preset()); - assert!(StyleWarp::new(WarpStyle::Cylinder, 50.0, 0.0, 0.0, false, B).is_none()); - // The Warp menus list what they can edit. - assert!(WarpStyle::all().all(|s| s != WarpStyle::Cylinder)); - assert_eq!(WarpStyle::all().filter(|s| s.is_preset()).count(), 15); - } - - #[test] - fn cylinder_values_that_describe_no_cylinder_are_refused() { - assert!(cylinder_mesh(&CYL[..6]).is_none(), "six values"); - assert!(cylinder_mesh(&[CYL.as_slice(), &[0.0]].concat()).is_none(), "eight values"); - for i in 0..7 { - for bad in [f64::NAN, f64::INFINITY] { - let mut v = CYL; - v[i] = bad; - assert!(cylinder_mesh(&v).is_none(), "value {i} = {bad}"); - } - } - let mut v = CYL; - v[2] = v[0]; - assert!(Warp::cylinder(&v, [0.0, 0.0, 1000.0, 1000.0]).is_none(), "no width"); - v[2] = 50.0; - assert!(Warp::cylinder(&v, [0.0, 0.0, 1000.0, 1000.0]).is_none(), "right silhouette left of the left one"); - } - - #[test] - fn cylinder_wraps_the_contents_between_its_silhouettes() { - let w = Warp::cylinder(&CYL, [0.0, 0.0, 1000.0, 1000.0]).unwrap(); - assert_eq!(w.style, WarpStyle::Cylinder); - assert_eq!(w.values, CYL); - assert!(!w.is_identity()); - let m = w.mesh.as_ref().unwrap(); - assert_eq!((m.nx(), m.ny()), (13, 4)); - let [ul, ..] = cylinder_shape(0.5); - assert!((m.us[1] - ul).abs() < 1e-12 && (m.us[3] - (1.0 - ul)).abs() < 1e-12); - // The middle of the contents is at the front: centred, on the ellipses' near side. - assert!(close(w.map(500.0, 0.0), (500.0, 200.0 + 0.3 * 400.0), 1e-9)); - assert!(close(w.map(500.0, 1000.0), (500.0, 800.0 + 0.3 * 400.0), 1e-9)); - // What wraps round the back lies on the silhouettes, at the edges' ends. - for x in [0.0, ul * 500.0, ul * 1000.0] { - assert!(close(w.map(x, 0.0), (100.0, 200.0), 1e-9), "{x}"); - assert!(close(w.map(1000.0 - x, 1000.0), (900.0, 800.0), 1e-9), "{x}"); - } - // Across the front x only grows, and the two halves mirror each other. - let mut last = f64::MIN; - for i in 0..=200 { - let x = 1000.0 * (ul + (1.0 - 2.0 * ul) * f64::from(i) / 200.0); - let (px, py) = w.map(x, 400.0); - assert!(px >= last - 1e-9, "x {x}"); - last = px; - let (qx, qy) = w.map(1000.0 - x, 400.0); - assert!(close((px - 500.0, py), (500.0 - qx, qy), 1e-9), "x {x}"); - } - // Every point stays inside the control-point box the placement frames. - let cb = m.control_bounds(); - let ob = w.output_bounds(); - assert!(ob[0] >= cb[0] - 1e-9 && ob[1] >= cb[1] - 1e-9 && ob[2] <= cb[2] + 1e-9 && ob[3] <= cb[3] + 1e-9); - assert!((cb[0] - 100.0).abs() < 1e-9 && (cb[2] - 900.0).abs() < 1e-9); - // The box's bottom is the lower ellipse's deepest control point (`my` > 1). - assert!((cb[3] - (800.0 + 0.3 * 400.0 * cylinder_shape(0.5)[3])).abs() < 1e-9); - assert_eq!(w.to_mesh(4, 4), *m, "a cylinder is its own mesh"); - } - - #[test] - fn cylinder_shape_follows_the_measured_rows() { - assert_eq!(cylinder_shape(0.0), CYLINDER_SHAPE[0]); - assert_eq!(cylinder_shape(1.0), CYLINDER_SHAPE[40]); - assert_eq!(cylinder_shape(-3.0), CYLINDER_SHAPE[0]); - assert_eq!(cylinder_shape(7.0), CYLINDER_SHAPE[40]); - assert_eq!(cylinder_shape(f64::NAN), CYLINDER_SHAPE[0]); - let mid = cylinder_shape(0.0125); - for k in 0..4 { - assert!((mid[k] - (CYLINDER_SHAPE[0][k] + CYLINDER_SHAPE[1][k]) / 2.0).abs() < 1e-12); - } - // The more it wraps, the less of the contents is on the back. - assert!(CYLINDER_SHAPE.windows(2).all(|r| r[1][0] < r[0][0])); - } - - #[test] - fn is_identity_rejects_malformed_custom_mesh_without_allocating() { - let us: Vec = (0..=1000).map(|i| i as f64 / 1000.0).collect(); - let vs: Vec = (0..=1000).map(|i| i as f64 / 1000.0).collect(); - let malformed = BezierMesh { us, vs, points: Vec::new() }; - assert!(!malformed.is_valid()); - let w = Warp::custom(malformed.clone(), B); - assert!(!w.is_identity()); - assert_eq!(malformed.eval(0.5, 0.5), [0.0, 0.0]); - } - - #[test] - fn locate_binary_search_matches_linear_scan() { - let knots = [0.0, 0.1, 0.25, 0.5, 0.85, 1.0]; - let linear = |s: f64| { - let n = knots.len() - 1; - let s = if s.is_finite() { s.clamp(0.0, 1.0) } else { 0.0 }; - let mut i = 0; - while i + 1 < n && s > knots[i + 1] { - i += 1; - } - let w = knots[i + 1] - knots[i]; - (i, if w > 0.0 { (s - knots[i]) / w } else { 0.0 }) - }; - for k in -10..=110 { - let s = k as f64 / 100.0; - assert_eq!(BezierMesh::locate(&knots, s), linear(s), "s={s}"); - } - for &s in &knots { - assert_eq!(BezierMesh::locate(&knots, s), linear(s), "knot={s}"); - } - assert_eq!(BezierMesh::locate(&knots, f64::NAN), linear(f64::NAN)); - } -} +mod tests; diff --git a/crates/geom/src/warp/tests.rs b/crates/geom/src/warp/tests.rs new file mode 100644 index 0000000000..1fc9612316 --- /dev/null +++ b/crates/geom/src/warp/tests.rs @@ -0,0 +1,459 @@ +use super::*; + +const B: [f64; 4] = [10.0, 20.0, 110.0, 70.0]; + +/// The largest mismatch between the tangents on the two sides of any interior grid line. +fn tangent_defect(m: &BezierMesh) -> f64 { + let nx = m.nx(); + let mut worst: f64 = 0.0; + for a in 1..m.us.len() - 1 { + let (hl, hr) = (m.us[a] - m.us[a - 1], m.us[a + 1] - m.us[a]); + for j in 0..m.ny() { + let (l, c, r) = (m.points[j * nx + 3 * a - 1], m.points[j * nx + 3 * a], m.points[j * nx + 3 * a + 1]); + for k in 0..2 { + worst = worst.max(((c[k] - l[k]) / hl - (r[k] - c[k]) / hr).abs()); + } + } + } + for b in 1..m.vs.len() - 1 { + let (hl, hr) = (m.vs[b] - m.vs[b - 1], m.vs[b + 1] - m.vs[b]); + for i in 0..nx { + let (l, c, r) = (m.points[(3 * b - 1) * nx + i], m.points[3 * b * nx + i], m.points[(3 * b + 1) * nx + i]); + for k in 0..2 { + worst = worst.max(((c[k] - l[k]) / hl - (r[k] - c[k]) / hr).abs()); + } + } + } + worst +} + +#[test] +fn dragging_an_anchor_or_handle_keeps_the_surface_smooth_across_the_lines() { + let mut base = BezierMesh::identity([0.0, 0.0, 300.0, 300.0], 1, 1); + for s in [0.3, 0.55, 0.9] { + assert!(base.split_u(s)); + assert!(base.split_v(s)); + } + let nx = base.nx(); + // Every kind of point on a grid line, interior and border: anchors, handles each way. + for (i, j) in [(6, 6), (7, 6), (5, 6), (6, 7), (6, 5), (3, 9), (9, 3), (0, 6), (6, 0), (4, 3), (3, 4), (12, 12)] { + let mut m = base.clone(); + m.drag_point(&base.points, j * nx + i, [23.0, -31.0]); + assert_eq!(m.points[j * nx + i], [base.points[j * nx + i][0] + 23.0, base.points[j * nx + i][1] - 31.0], "({i}, {j}) lands on the pointer"); + assert!(tangent_defect(&m) < 1e-6, "({i}, {j}): {}", tangent_defect(&m)); + } +} + +/// Fraction of the surface where the map folds over itself (its Jacobian is not positive). +fn fold_fraction(m: &BezierMesh) -> f64 { + let (n, h) = (80, 1e-4); + let mut bad = 0; + for j in 0..n { + for i in 0..n { + let (s, t) = ((i as f64 + 0.5) / n as f64, (j as f64 + 0.5) / n as f64); + let q = m.eval(s, t); + let (qs, qt) = (m.eval(s + h, t), m.eval(s, t + h)); + if (qs[0] - q[0]) * (qt[1] - q[1]) - (qt[0] - q[0]) * (qs[1] - q[1]) <= 0.0 { + bad += 1; + } + } + } + bad as f64 / (n * n) as f64 +} + +#[test] +fn a_pull_within_a_quarter_cell_never_folds_the_surface() { + // 75 px cells: dragging a quarter of a cell, any direction, anywhere in the grid must not tear the picture. + let base = BezierMesh::identity([0.0, 0.0, 300.0, 300.0], 4, 4); + for (s, t) in [(0.42, 0.42), (0.75, 0.2), (0.2, 0.2), (0.5, 0.5), (0.85, 0.7), (0.3, 0.7)] { + for (dx, dy) in [(-1.0, 0.0), (1.0, 0.0), (0.0, -1.0), (0.0, 1.0), (0.7, 0.7), (-0.7, 0.7)] { + let mut m = base.clone(); + m.pull(&base.points, s, t, [dx * 19.0, dy * 19.0]); + assert_eq!(fold_fraction(&m), 0.0, "({s}, {t}) by ({dx}, {dy}) quarter cells"); + } + } +} + +#[test] +fn a_pull_in_the_middle_leaves_the_border_where_it_is() { + let mut base = BezierMesh::identity([0.0, 0.0, 600.0, 800.0], 1, 1); + for s in [0.33, 0.66] { + assert!(base.split_u(s)); + } + assert!(base.split_v(0.5)); + let (nx, ny) = (base.nx(), base.ny()); + let on_border = |i: usize, j: usize| i == 0 || j == 0 || i == nx - 1 || j == ny - 1; + let mut m = base.clone(); + m.pull(&base.points, 0.5, 0.5, [-180.0, 40.0]); + for j in 0..ny { + for i in 0..nx { + if on_border(i, j) { + let (a, b) = (m.points[j * nx + i], base.points[j * nx + i]); + assert!((a[0] - b[0]).abs() < 1e-6 && (a[1] - b[1]).abs() < 1e-6, "border point ({i}, {j}) moved"); + } + } + } + // The pull itself still lands exactly. + let (before, after) = (base.eval(0.5, 0.5), m.eval(0.5, 0.5)); + assert!((after[0] - before[0] + 180.0).abs() < 1e-4 && (after[1] - before[1] - 40.0).abs() < 1e-4); +} + +#[test] +fn a_pull_anywhere_away_from_the_border_never_moves_the_border() { + // The default one-patch grid and a cut one; grabs all over, none within 12% of an edge. + let one = BezierMesh::identity([0.0, 0.0, 600.0, 800.0], 1, 1); + let mut cut = one.clone(); + assert!(cut.split_u(0.4) && cut.split_u(0.7) && cut.split_v(0.35) && cut.split_v(0.8)); + for base in [one, cut] { + let (nx, ny) = (base.nx(), base.ny()); + for (s, t) in [(0.5, 0.5), (0.2, 0.5), (0.8, 0.3), (0.3, 0.85), (0.14, 0.14), (0.86, 0.5)] { + for d in [[-400.0, 0.0], [250.0, -90.0], [0.0, 300.0]] { + let mut m = base.clone(); + m.pull(&base.points, s, t, d); + for j in 0..ny { + for i in 0..nx { + if i == 0 || j == 0 || i == nx - 1 || j == ny - 1 { + let (a, b) = (m.points[j * nx + i], base.points[j * nx + i]); + assert!((a[0] - b[0]).abs() < 1e-6 && (a[1] - b[1]).abs() < 1e-6, "({s}, {t}) by {d:?} moved border point ({i}, {j})"); + } + } + } + let (before, after) = (base.eval(s, t), m.eval(s, t)); + assert!((after[0] - before[0] - d[0]).abs() < 1e-3 && (after[1] - before[1] - d[1]).abs() < 1e-3, "({s}, {t}) by {d:?}: {after:?}"); + } + } + } +} + +#[test] +fn pulling_on_the_border_bows_it_and_leaves_the_corners_put() { + // A one-patch grid, grabbed on the middle of its right edge and pulled 170 px out. + let base = BezierMesh::identity([0.0, 0.0, 800.0, 1200.0], 1, 1); + let mut m = base.clone(); + m.pull(&base.points, 1.0, 0.5, [170.0, 0.0]); + let at = m.eval(1.0, 0.5); + assert!((at[0] - 970.0).abs() < 1e-3 && (at[1] - 600.0).abs() < 1e-3, "{at:?}"); + for (s, t) in [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0), (1.0, 1.0)] { + let (a, b) = (m.eval(s, t), base.eval(s, t)); + assert!((a[0] - b[0]).abs() < 1e-6 && (a[1] - b[1]).abs() < 1e-6, "corner ({s}, {t}) moved"); + } + // The other three edges did not move. + for k in 0..=10 { + let u = k as f64 / 10.0; + for (s, t) in [(0.0, u), (u, 0.0), (u, 1.0)] { + let (a, b) = (m.eval(s, t), base.eval(s, t)); + assert!((a[0] - b[0]).abs() < 1e-6 && (a[1] - b[1]).abs() < 1e-6, "edge point ({s}, {t}) moved"); + } + } + // Only the right edge's two handles carry the pull. + let nx = base.nx(); + let moved: Vec = (0..m.points.len()).filter(|k| m.points[*k] != base.points[*k]).collect(); + assert_eq!(moved, vec![nx + 3, 2 * nx + 3], "{moved:?}"); + assert_eq!(fold_fraction(&m), 0.0); +} + +#[test] +fn pull_keeps_the_surface_smooth_across_the_grid_lines() { + // A grid cut unevenly both ways, then pulled hard inside one cell and then another. + let mut base = BezierMesh::identity([0.0, 0.0, 300.0, 300.0], 1, 1); + for s in [0.3, 0.55, 0.9] { + assert!(base.split_u(s)); + assert!(base.split_v(s)); + } + assert!(tangent_defect(&base) < 1e-9, "cuts are exact"); + for (s, t, d) in [(0.42, 0.42, [60.0, -35.0]), (0.75, 0.2, [-40.0, 50.0]), (0.1, 0.95, [30.0, 30.0])] { + let mut m = base.clone(); + m.pull(&base.points, s, t, d); + assert!(tangent_defect(&m) < 1e-6, "({s}, {t}): {}", tangent_defect(&m)); + let before = base.eval(s, t); + let after = m.eval(s, t); + assert!((after[0] - before[0] - d[0]).abs() < 1e-4 && (after[1] - before[1] - d[1]).abs() < 1e-4, "{after:?}"); + } +} + +#[test] +fn pull_moves_the_grabbed_surface_point_exactly_and_stays_local() { + let base = BezierMesh::identity(B, 3, 2); + for (s, t) in [(0.5, 0.5), (0.1, 0.9), (0.4, 0.25), (0.0, 0.5), (1.0, 0.3)] { + let mut m = base.clone(); + let before = base.eval(s, t); + m.pull(&base.points, s, t, [7.0, -4.5]); + let after = m.eval(s, t); + assert!((after[0] - before[0] - 7.0).abs() < 1e-4 && (after[1] - before[1] + 4.5).abs() < 1e-4, "({s}, {t}): {after:?}"); + } + // The pull stays near the grabbed patch: the far end of the grid does not move. + let mut m = base.clone(); + m.pull(&base.points, 0.1, 0.25, [5.0, 5.0]); + let nx = base.nx(); + let moved = |k: usize| (m.points[k][0] - base.points[k][0]).abs() > 1e-6 || (m.points[k][1] - base.points[k][1]).abs() > 1e-6; + assert!((0..base.ny()).all(|j| !moved(j * nx + nx - 1)), "last column stays put"); + assert!((0..nx).any(moved), "something moved"); + // Pulling again from the same base replaces the pull (a drag is not cumulative). + m.pull(&base.points, 0.5, 0.25, [0.0, 0.0]); + assert!(m.points.iter().zip(&base.points).all(|(a, b)| (a[0] - b[0]).abs() < 1e-9 && (a[1] - b[1]).abs() < 1e-9)); +} + +fn close(a: (f64, f64), b: (f64, f64), eps: f64) -> bool { + (a.0 - b.0).abs() < eps && (a.1 - b.1).abs() < eps +} + +#[test] +fn styles_parse_and_round_trip_names() { + for s in WarpStyle::all() { + assert_eq!(WarpStyle::parse(s.id()), Some(s)); + assert_eq!(WarpStyle::parse(s.psd_name()), Some(s)); + assert_eq!(WarpStyle::parse(s.label()), Some(s), "{s:?}"); + } + assert_eq!(WarpStyle::parse("spiral"), None); +} + +#[test] +fn presets_at_bend_zero_are_identity() { + for s in WarpStyle::PRESETS { + let w = Warp::preset(s, 0.0, B); + assert!(w.is_identity()); + assert_eq!(w.map(33.0, 44.0), (33.0, 44.0)); + } +} + +#[test] +fn identity_mesh_is_exact_and_fit_reproduces_affine() { + let m = BezierMesh::identity(B, 1, 1); + assert_eq!((m.nx(), m.ny()), (4, 4)); + let w = Warp::custom(m, B); + assert!(w.is_identity()); + assert!(close(w.map(37.5, 61.25), (37.5, 61.25), 1e-9)); + // Affine maps fit exactly. + let f = |s: f64, t: f64| [3.0 + 2.0 * s - t, 1.0 + 0.5 * s + 4.0 * t]; + let m = BezierMesh::fit(&f, vec![0.0, 1.0], vec![0.0, 0.4, 1.0]); + for (s, t) in [(0.1, 0.9), (0.5, 0.2), (0.77, 0.41)] { + let p = m.eval(s, t); + let e = f(s, t); + assert!((p[0] - e[0]).abs() < 1e-9 && (p[1] - e[1]).abs() < 1e-9); + } +} + +#[test] +fn remove_split_u_rejects_out_of_range_indices() { + let original = BezierMesh::identity(B, 2, 3); + for k in [0, original.us.len() - 1, original.us.len(), usize::MAX - 1, usize::MAX] { + let mut mesh = original.clone(); + assert!(!mesh.remove_split_u(k), "index {k}"); + assert_eq!(mesh, original, "index {k} must leave the mesh unchanged"); + } +} + +#[test] +fn remove_split_v_rejects_out_of_range_indices() { + let original = BezierMesh::identity(B, 2, 3); + for k in [0, original.vs.len() - 1, original.vs.len(), usize::MAX - 1, usize::MAX] { + let mut mesh = original.clone(); + assert!(!mesh.remove_split_v(k), "index {k}"); + assert_eq!(mesh, original, "index {k} must leave the mesh unchanged"); + } +} + +#[test] +fn splits_are_exact_and_removable() { + let mut m = BezierMesh::identity(B, 1, 1); + // Bend it: move an inner control point. + m.points[5] = [50.0, 10.0]; + let before: Vec<[f64; 2]> = (0..=10).flat_map(|j| (0..=10).map(move |i| (i, j))).map(|(i, j)| m.eval(i as f64 / 10.0, j as f64 / 10.0)).collect(); + let orig = m.clone(); + assert!(m.split_u(0.3)); + assert!(m.split_v(0.6)); + assert!(!m.split_u(0.3), "existing boundary"); + assert_eq!((m.nx(), m.ny()), (7, 7)); + assert!(m.is_valid()); + let after: Vec<[f64; 2]> = (0..=10).flat_map(|j| (0..=10).map(move |i| (i, j))).map(|(i, j)| m.eval(i as f64 / 10.0, j as f64 / 10.0)).collect(); + for (a, b) in before.iter().zip(&after) { + assert!((a[0] - b[0]).abs() < 1e-9 && (a[1] - b[1]).abs() < 1e-9); + } + let (ls, lt) = m.param_at(m.eval(0.42, 0.77)); + assert!((ls - 0.42).abs() < 1e-6 && (lt - 0.77).abs() < 1e-6, "{ls},{lt}"); + assert!(m.remove_split_u(1)); + assert!(m.remove_split_v(1)); + assert_eq!(m.us, orig.us); + for (a, b) in m.points.iter().zip(&orig.points) { + assert!((a[0] - b[0]).abs() < 1e-9 && (a[1] - b[1]).abs() < 1e-9); + } +} + +const SQUARE: [f64; 4] = [128.0, 128.0, 384.0, 384.0]; +const WIDE: [f64; 4] = [128.0, 208.0, 384.0, 304.0]; +const TALL: [f64; 4] = [208.0, 128.0, 304.0, 384.0]; + +/// Photoshop 27.11, measured: a 256 px grid image whose colours encode each pixel's own +/// position, warped in a 512 px document over the box (128, 128)–(384, 384). Each pair is a +/// source point and where Photoshop put it. +#[test] +fn presets_match_photoshop() { + type Case = (WarpStyle, f64, f64, f64, bool, [([f64; 2], [f64; 2]); 3]); + let cases: [Case; 9] = [ + (WarpStyle::Arc, 50.0, 0.0, 0.0, false, [([272.5, 155.5], [296.5, 104.5]), ([331.5, 182.5], [424.5, 168.5]), ([259.5, 157.5], [264.5, 104.5])]), + (WarpStyle::Arc, -100.0, 0.0, 0.0, false, [([277.5, 354.5], [344.5, 472.5]), ([140.5, 218.5], [40.5, 168.5]), ([172.5, 237.5], [56.5, 264.5])]), + (WarpStyle::Flag, 50.0, 0.0, 0.0, false, [([136.5, 143.5], [136.5, 120.5]), ([136.5, 159.5], [136.5, 136.5]), ([136.5, 175.5], [136.5, 152.5])]), + (WarpStyle::Twist, -50.0, 0.0, 0.0, false, [([148.5, 205.5], [152.5, 216.5]), ([197.5, 212.5], [200.5, 232.5]), ([134.5, 212.5], [136.5, 216.5])]), + (WarpStyle::ShellLower, 50.0, 0.0, 0.0, false, [([248.5, 136.5], [248.5, 136.5]), ([264.5, 136.5], [264.5, 136.5]), ([232.5, 136.5], [232.5, 136.5])]), + (WarpStyle::Fish, -100.0, 0.0, 0.0, false, [([296.5, 355.5], [296.5, 440.5]), ([344.5, 298.5], [344.5, 344.5]), ([328.5, 356.5], [328.5, 472.5])]), + (WarpStyle::Bulge, 50.0, 50.0, 0.0, false, [([293.5, 147.5], [296.5, 88.5]), ([293.5, 375.5], [296.5, 440.5]), ([340.5, 281.5], [344.5, 296.5])]), + (WarpStyle::Arc, 50.0, 0.0, -50.0, false, [([181.5, 350.5], [184.5, 328.5]), ([291.5, 372.5], [280.5, 344.5]), ([232.5, 349.5], [232.5, 312.5])]), + (WarpStyle::Arc, 50.0, 0.0, 0.0, true, [([155.5, 272.5], [104.5, 296.5]), ([182.5, 331.5], [168.5, 424.5]), ([157.5, 259.5], [104.5, 264.5])]), + ]; + // Wide (256 × 96 at 128, 208) and tall (96 × 256 at 208, 128) boxes, and a vertical warp + // with distortion. + type Boxed = (WarpStyle, f64, f64, f64, bool, [f64; 4], [([f64; 2], [f64; 2]); 2]); + let boxed: [Boxed; 6] = [ + (WarpStyle::Arc, 50.0, 0.0, 0.0, false, WIDE, [([144.5, 269.6], [120.5, 264.5]), ([271.5, 220.42], [280.5, 168.5])]), + (WarpStyle::Bulge, 50.0, 0.0, 0.0, false, TALL, [([249.11, 374.5], [248.5, 392.5]), ([249.11, 360.5], [248.5, 376.5])]), + (WarpStyle::Flag, 50.0, 0.0, 0.0, true, WIDE, [([137.5, 296.42], [184.5, 296.5]), ([153.5, 296.42], [200.5, 296.5])]), + (WarpStyle::Rise, 50.0, 0.0, 0.0, true, TALL, [([250.97, 152.5], [344.5, 152.5]), ([301.26, 264.5], [344.5, 264.5])]), + (WarpStyle::Bulge, 60.0, 20.0, -10.0, false, WIDE, [([208.5, 224.15], [200.5, 184.5]), ([219.5, 277.42], [216.5, 296.5])]), + (WarpStyle::Arc, 50.0, 30.0, 0.0, true, SQUARE, [([331.5, 327.5], [296.5, 360.5]), ([318.5, 240.5], [264.5, 232.5])]), + ]; + let all = cases.iter().map(|c| (c.0, c.1, c.2, c.3, c.4, SQUARE, c.5.to_vec())).chain(boxed.iter().map(|c| (c.0, c.1, c.2, c.3, c.4, c.5, c.6.to_vec()))); + for (style, bend, hd, vd, vertical, bounds, pairs) in all { + let w = Warp { h_distort: hd, v_distort: vd, vertical, ..Warp::preset(style, bend, bounds) }; + for (src, want) in pairs { + let got = w.map(src[0], src[1]); + let d = (got.0 - want[0]).hypot(got.1 - want[1]); + assert!(d < 1.5, "{style:?} {bend} h{hd} v{vd} vertical {vertical} {bounds:?}: {src:?} -> {got:?}, Photoshop {want:?}"); + } + } +} + +#[test] +fn preset_fits_closely_as_mesh_and_affine_composes() { + let w = Warp::preset(WarpStyle::Bulge, 40.0, B); + let m = Warp::custom(w.to_mesh(4, 4), B); + for (x, y) in [(20.0, 30.0), (60.0, 45.0), (100.0, 65.0)] { + assert!(close(w.map(x, y), m.map(x, y), 0.5), "{:?} vs {:?}", w.map(x, y), m.map(x, y)); + } + let t = Warp::custom(BezierMesh::identity(B, 1, 1), B).then_affine([1.0, 0.0, 0.0, 1.0, 5.0, -2.0]); + assert!(close(t.map(50.0, 50.0), (55.0, 48.0), 1e-9)); + let ob = Warp::none(B).output_bounds(); + assert!((ob[0] - 10.0).abs() < 1e-9 && (ob[3] - 70.0).abs() < 1e-9); +} + +/// A cylinder over a 1000 × 1000 source like #4112's: silhouettes at x 100 and 900, edges at +/// y 200 (top) and 800 (bottom), ellipses 0.3 deep, half wrapped round. +const CYL: [f64; 7] = [100.0, 800.0, 900.0, 200.0, 0.3, 0.3, 0.5]; + +#[test] +fn cylinder_style_is_read_and_named_but_not_a_bend_preset() { + for s in ["cylinder", "warpCylinder", "Cylinder"] { + assert_eq!(WarpStyle::parse(s), Some(WarpStyle::Cylinder), "{s}"); + } + assert_eq!(WarpStyle::Cylinder.psd_name(), "warpCylinder"); + assert_eq!(WarpStyle::Cylinder.id(), "cylinder"); + assert!(!WarpStyle::Cylinder.is_preset()); + assert!(StyleWarp::new(WarpStyle::Cylinder, 50.0, 0.0, 0.0, false, B).is_none()); + // The Warp menus list what they can edit. + assert!(WarpStyle::all().all(|s| s != WarpStyle::Cylinder)); + assert_eq!(WarpStyle::all().filter(|s| s.is_preset()).count(), 15); +} + +#[test] +fn cylinder_values_that_describe_no_cylinder_are_refused() { + assert!(cylinder_mesh(&CYL[..6]).is_none(), "six values"); + assert!(cylinder_mesh(&[CYL.as_slice(), &[0.0]].concat()).is_none(), "eight values"); + for i in 0..7 { + for bad in [f64::NAN, f64::INFINITY] { + let mut v = CYL; + v[i] = bad; + assert!(cylinder_mesh(&v).is_none(), "value {i} = {bad}"); + } + } + let mut v = CYL; + v[2] = v[0]; + assert!(Warp::cylinder(&v, [0.0, 0.0, 1000.0, 1000.0]).is_none(), "no width"); + v[2] = 50.0; + assert!(Warp::cylinder(&v, [0.0, 0.0, 1000.0, 1000.0]).is_none(), "right silhouette left of the left one"); +} + +#[test] +fn cylinder_wraps_the_contents_between_its_silhouettes() { + let w = Warp::cylinder(&CYL, [0.0, 0.0, 1000.0, 1000.0]).unwrap(); + assert_eq!(w.style, WarpStyle::Cylinder); + assert_eq!(w.values, CYL); + assert!(!w.is_identity()); + let m = w.mesh.as_ref().unwrap(); + assert_eq!((m.nx(), m.ny()), (13, 4)); + let [ul, ..] = cylinder_shape(0.5); + assert!((m.us[1] - ul).abs() < 1e-12 && (m.us[3] - (1.0 - ul)).abs() < 1e-12); + // The middle of the contents is at the front: centred, on the ellipses' near side. + assert!(close(w.map(500.0, 0.0), (500.0, 200.0 + 0.3 * 400.0), 1e-9)); + assert!(close(w.map(500.0, 1000.0), (500.0, 800.0 + 0.3 * 400.0), 1e-9)); + // What wraps round the back lies on the silhouettes, at the edges' ends. + for x in [0.0, ul * 500.0, ul * 1000.0] { + assert!(close(w.map(x, 0.0), (100.0, 200.0), 1e-9), "{x}"); + assert!(close(w.map(1000.0 - x, 1000.0), (900.0, 800.0), 1e-9), "{x}"); + } + // Across the front x only grows, and the two halves mirror each other. + let mut last = f64::MIN; + for i in 0..=200 { + let x = 1000.0 * (ul + (1.0 - 2.0 * ul) * f64::from(i) / 200.0); + let (px, py) = w.map(x, 400.0); + assert!(px >= last - 1e-9, "x {x}"); + last = px; + let (qx, qy) = w.map(1000.0 - x, 400.0); + assert!(close((px - 500.0, py), (500.0 - qx, qy), 1e-9), "x {x}"); + } + // Every point stays inside the control-point box the placement frames. + let cb = m.control_bounds(); + let ob = w.output_bounds(); + assert!(ob[0] >= cb[0] - 1e-9 && ob[1] >= cb[1] - 1e-9 && ob[2] <= cb[2] + 1e-9 && ob[3] <= cb[3] + 1e-9); + assert!((cb[0] - 100.0).abs() < 1e-9 && (cb[2] - 900.0).abs() < 1e-9); + // The box's bottom is the lower ellipse's deepest control point (`my` > 1). + assert!((cb[3] - (800.0 + 0.3 * 400.0 * cylinder_shape(0.5)[3])).abs() < 1e-9); + assert_eq!(w.to_mesh(4, 4), *m, "a cylinder is its own mesh"); +} + +#[test] +fn cylinder_shape_follows_the_measured_rows() { + assert_eq!(cylinder_shape(0.0), CYLINDER_SHAPE[0]); + assert_eq!(cylinder_shape(1.0), CYLINDER_SHAPE[40]); + assert_eq!(cylinder_shape(-3.0), CYLINDER_SHAPE[0]); + assert_eq!(cylinder_shape(7.0), CYLINDER_SHAPE[40]); + assert_eq!(cylinder_shape(f64::NAN), CYLINDER_SHAPE[0]); + let mid = cylinder_shape(0.0125); + for k in 0..4 { + assert!((mid[k] - (CYLINDER_SHAPE[0][k] + CYLINDER_SHAPE[1][k]) / 2.0).abs() < 1e-12); + } + // The more it wraps, the less of the contents is on the back. + assert!(CYLINDER_SHAPE.windows(2).all(|r| r[1][0] < r[0][0])); +} + +#[test] +fn is_identity_rejects_malformed_custom_mesh_without_allocating() { + let us: Vec = (0..=1000).map(|i| i as f64 / 1000.0).collect(); + let vs: Vec = (0..=1000).map(|i| i as f64 / 1000.0).collect(); + let malformed = BezierMesh { us, vs, points: Vec::new() }; + assert!(!malformed.is_valid()); + let w = Warp::custom(malformed.clone(), B); + assert!(!w.is_identity()); + assert_eq!(malformed.eval(0.5, 0.5), [0.0, 0.0]); +} + +#[test] +fn locate_binary_search_matches_linear_scan() { + let knots = [0.0, 0.1, 0.25, 0.5, 0.85, 1.0]; + let linear = |s: f64| { + let n = knots.len() - 1; + let s = if s.is_finite() { s.clamp(0.0, 1.0) } else { 0.0 }; + let mut i = 0; + while i + 1 < n && s > knots[i + 1] { + i += 1; + } + let w = knots[i + 1] - knots[i]; + (i, if w > 0.0 { (s - knots[i]) / w } else { 0.0 }) + }; + for k in -10..=110 { + let s = k as f64 / 100.0; + assert_eq!(BezierMesh::locate(&knots, s), linear(s), "s={s}"); + } + for &s in &knots { + assert_eq!(BezierMesh::locate(&knots, s), linear(s), "knot={s}"); + } + assert_eq!(BezierMesh::locate(&knots, f64::NAN), linear(f64::NAN)); +} diff --git a/crates/gpu/src/batch.rs b/crates/gpu/src/batch.rs new file mode 100644 index 0000000000..988a580cc4 --- /dev/null +++ b/crates/gpu/src/batch.rs @@ -0,0 +1,215 @@ +use super::convert::{W, words}; +use super::textures::Resident; +use super::*; + +/// The uniform record of a pass. +pub(crate) fn op_words(p: &plan::Pass<'_>, tex: Option<[i32; 4]>, mask: Option<[i32; 4]>, map: Option) -> Vec { + words(&op_values(p, tex, mask, map)) +} + +/// The uniform record of the `fs_layerbatch` pass that draws `p` (whose texture and mask cover +/// `tex` and `mask`) and then `extras`, each an unmasked plain layer's `LayerBlend` pass with the +/// area its texture covers. Layout: see `batch_layer` in compose.wgsl. +pub(crate) fn batch_op_words(p: &plan::Pass<'_>, tex: Option<[i32; 4]>, mask: Option<[i32; 4]>, extras: &[(&plan::Pass<'_>, Option<[i32; 4]>)]) -> Vec { + let mut v = op_values(p, tex, mask, None); + // Word offsets of the record's vec4s holding the extra layers, three each: p0, p1, p2 | p3, + // q0, q1 | q2, q3, q4. + const AT: [usize; 9] = [20, 24, 28, 32, 44, 48, 52, 56, 60]; + if let Some(kind) = v.get_mut(1) { + *kind = I(extras.len().min(AT.len() / 3) as i32); + } + for (e, (x, area)) in extras.iter().take(AT.len() / 3).enumerate() { + let r = area.unwrap_or([0; 4]); + let geo = [r[0] as f32, r[1] as f32, r[2] as f32, r[3] as f32]; + let prm = [x.opacity, x.fill, plan::mode_index(x.mode) as f32, if area.is_some() { 1.0 } else { 0.0 }]; + for (k, vals) in [geo, x.color, prm].into_iter().enumerate() { + let at = AT[e * 3 + k]; + for (c, f) in vals.into_iter().enumerate() { + if let Some(w) = v.get_mut(at + c) { + *w = F(f); + } + } + } + } + words(&v) +} + +/// The words of a pass's uniform record (`Op` in compose.wgsl). +fn op_values(p: &plan::Pass<'_>, tex: Option<[i32; 4]>, mask: Option<[i32; 4]>, map: Option) -> Vec { + let mut flags = p.flags; + let (mut to, mut ts, mut mo, mut ms) = ([0; 2], [0; 2], [0; 2], [0; 2]); + if let Some(r) = tex { + flags |= 4; + to = [r[0], r[1]]; + ts = [r[2], r[3]]; + } + let (mut density, mut mdefault) = (0.0, 1.0); + if let Some(m) = &p.mask { + flags |= 1; + density = m.density; + mdefault = m.default; + if let Some(r) = mask { + flags |= 2; + mo = [r[0], r[1]]; + ms = [r[2], r[3]]; + } + } + if p.gradient { + flags |= 8; + } + let (mpo, mps) = map.map_or(([0, 0], [0, 0]), |r| ([r.x0, r.y0], [r.width() as i32, r.height() as i32])); + let mut v = vec![ + I(plan::mode_index(p.mode)), + I(p.adjust_kind), + U(flags), + U(0), + F(p.opacity), + F(density), + F(mdefault), + F(p.fill), + I(to[0]), + I(to[1]), + I(ts[0]), + I(ts[1]), + I(mo[0]), + I(mo[1]), + I(ms[0]), + I(ms[1]), + ]; + v.extend(p.color.iter().map(|f| F(*f))); + for row in &p.params { + v.extend(row.iter().map(|f| F(*f))); + } + v.extend([I(mpo[0]), I(mpo[1]), I(mps[0]), I(mps[1])]); + v.extend(p.extra.iter().map(|f| F(*f))); + // q0..q4: only `fs_layerbatch` reads them (`batch_op_words`). + v.extend((0..20).map(|_| F(0.0))); + v +} + +/// Most layers one `fs_layerbatch` pass blends: its own and the three more its record holds. +pub(crate) const BATCH: usize = 4; + +/// For each pass, how many passes from it on the executor draws as one `fs_layerbatch` pass +/// (1: the pass alone). A run starts at a `LayerBlend` pass over the whole chunk (no clip) that +/// isn't a gradient (whose parameters use the words the extra layers go in), and continues while +/// the next pass is a `LayerBlend` of an unmasked plain layer (no text gamma, no Dissolve) onto +/// exactly what the previous pass wrote, a slot nothing else reads before it is written again. +/// A run never ends in the slot it reads from. +/// +/// The runs depend on the plan alone, never on the prefix cache: a compiler may give a layer +/// other bits batched than drawn alone (FXC on D3D12 does), and reusing a prefix must stay exact +/// (#5286). The cache captures and resumes only at `run_starts` instead. +pub(crate) fn batch_runs(plan: &Plan<'_>) -> Vec { + let passes = &plan.passes; + let n = passes.len(); + let reads = |p: &plan::Pass<'_>, s: plan::Slot| [p.a, p.b, p.c, p.d].contains(&Some(s)); + // feeds_next[i]: what pass i writes is read by pass i + 1 alone. + let feeds_next: Vec = (0..n) + .map(|i| { + let (Some(this), Some(next)) = (passes.get(i), passes.get(i + 1)) else { return false }; + let dst = this.dst; + if next.a != Some(dst) || [next.b, next.c, next.d].contains(&Some(dst)) { + return false; + } + for later in passes.iter().skip(i + 2) { + // A copy into a slot keeps what lies outside its rect: that is a read too. + if reads(later, dst) || (later.dst == dst && later.kernel == Kernel::CopyRect) { + return false; + } + if later.dst == dst { + return true; + } + } + dst != plan.root + }) + .collect(); + let lead = |p: &plan::Pass<'_>| p.kernel == Kernel::LayerBlend && p.clip.is_none() && !p.gradient; + let extra = |p: &plan::Pass<'_>| lead(p) && p.mask.is_none() && p.flags & plan::F_TEXT_GAMMA == 0 && p.mode != photocraft_color::BlendMode::Dissolve; + (0..n) + .map(|i| { + let Some(first) = passes.get(i).filter(|p| lead(p)) else { return 1 }; + let (mut k, mut best) = (1, 1); + while k < BATCH && feeds_next.get(i + k - 1).copied().unwrap_or(false) && passes.get(i + k).is_some_and(extra) { + k += 1; + if passes.get(i + k - 1).is_some_and(|p| Some(p.dst) != first.a) { + best = k; + } + } + best + }) + .collect() +} + +/// For each pass and the end of the plan, whether the executor draws `runs` (`batch_runs`) so +/// that a pass starts there rather than inside a run. +pub(crate) fn run_starts(runs: &[usize]) -> Vec { + let mut starts = vec![false; runs.len() + 1]; + let mut i = 0; + while let Some(s) = starts.get_mut(i) { + *s = true; + i += runs.get(i).copied().unwrap_or(1).max(1); + } + starts +} + +/// The pipeline that draws `run` (passes `batch_runs` joined): `fs_layerbatch_normal` when every +/// layer blends Normal without text gamma outside Lab documents, else `fs_layerbatch`. +pub(crate) fn batch_kernel(run: &[plan::Pass<'_>]) -> Kernel { + let normal = |p: &plan::Pass<'_>| p.mode == photocraft_color::BlendMode::Normal && p.flags & (plan::F_TEXT_GAMMA | plan::F_LAB) == 0; + if run.iter().all(normal) { Kernel::LayerBatchNormal } else { Kernel::LayerBatch } +} + +/// Canvas rounded out to whole tiles. +pub(crate) fn tile_grid(canvas: Rect) -> Rect { + let t = TILE_SIZE; + Rect::new(canvas.x0.div_euclid(t) * t, canvas.y0.div_euclid(t) * t, (canvas.x1 + t - 1).div_euclid(t) * t, (canvas.y1 + t - 1).div_euclid(t) * t) +} + +pub(crate) fn write_tile(queue: &wgpu::Queue, r: &Resident, c: TileCoord, bytes: &[u8]) { + let tr = c.rect(); + let bpp = r.kind.bytes_per_pixel() as u32; + queue.write_texture( + wgpu::TexelCopyTextureInfo { + texture: &r.texture, + mip_level: 0, + origin: wgpu::Origin3d { x: (tr.x0 - r.region.x0) as u32, y: (tr.y0 - r.region.y0) as u32, z: 0 }, + aspect: wgpu::TextureAspect::All, + }, + bytes, + wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(TILE_SIZE as u32 * bpp), rows_per_image: Some(TILE_SIZE as u32) }, + wgpu::Extent3d { width: TILE_SIZE as u32, height: TILE_SIZE as u32, depth_or_array_layers: 1 }, + ); +} + +/// Submit what `encoder` recorded and continue in a fresh one, then wait for the previous +/// intermediate submit (`last`), so at most two batches of uploads and evicted pages are in +/// flight. The web has no blocking wait and relies on the browser's own scheduling. +pub(crate) fn submit_batch( + device: &wgpu::Device, + queue: &wgpu::Queue, + encoder: &mut wgpu::CommandEncoder, + health: Option<&DeviceHealth>, + timer: Option<&mut timing::GpuTimer>, + last: &mut Option, +) { + let mut done = std::mem::replace(encoder, device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("pc_compose") })); + if let Some(t) = timer { + // One refresh, several command buffers: the measurement spans all of them. + t.split(&mut done, encoder); + } + let prev = last.replace(queue.submit([done.finish()])); + #[cfg(not(target_arch = "wasm32"))] + if let Some(prev) = prev { + match health { + Some(h) => { + h.wait(device, Some(prev)); + } + None => { + let _ = device.poll(wgpu::PollType::Wait { submission_index: Some(prev), timeout: None }); + } + } + } + #[cfg(target_arch = "wasm32")] + let _ = (prev, health); +} diff --git a/crates/gpu/src/cells.rs b/crates/gpu/src/cells.rs new file mode 100644 index 0000000000..8d8a44ec97 --- /dev/null +++ b/crates/gpu/src/cells.rs @@ -0,0 +1,523 @@ +use super::batch::{batch_kernel, batch_op_words, op_words, submit_batch}; +use super::consts::{FLUSH_OPS, MAP32, STRIDE}; +use super::convert::{convert_tile, convert_tiles, keep_overlap, put_tiles, words}; +use super::kit::{Bound, FrameRes, texture_group, uniform_group}; +use super::paging::cell_rect; +use super::textures::{CachedPattern, Cell, ChunkOut, ResKey, Resident, ResidentRef, Stats, Tex, TexKind}; +use super::*; + +impl Compositor { + /// Bring the pages of `cell` that `plan` samples up to date and resolve its effect maps. + #[allow(clippy::too_many_arguments)] + fn bind_cell( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + encoder: &mut wgpu::CommandEncoder, + doc: DocId, + plan: &Plan<'_>, + paged: &[bool], + cell: Cell, + fr: &FrameRes, + first_pass: usize, + stats: &mut Stats, + ) -> Bound { + let cr = cell_rect(cell, self.page); + let mut views: Vec<(Option, Option)> = Vec::with_capacity(plan.passes.len()); + let mut keys: Vec = Vec::new(); + let mut maps = Vec::with_capacity(plan.passes.len()); + for (i, p) in plan.passes.iter().enumerate() { + if i < first_pass { + views.push((None, None)); + maps.push(None); + continue; + } + let (ta, ma) = fr.areas.get(i).copied().unwrap_or((Rect::EMPTY, Rect::EMPTY)); + let tex = + p.tex.as_ref().and_then(|t| self.sync(device, queue, encoder, doc, (t.layer, t.role, cell), t.surface.get(), ta.intersect(&cr), stats)).map( + |(k, r)| { + keys.push(k); + (keys.len() - 1, r) + }, + ); + let mask = p + .mask + .as_ref() + .and_then(|m| self.sync(device, queue, encoder, doc, (m.layer, Role::Mask, cell), m.surface.get(), ma.intersect(&cr), stats)) + .map(|(k, r)| { + keys.push(k); + (keys.len() - 1, r) + }); + views.push((tex, mask)); + maps.push(p.map.and_then(|m| { + let f = plan.fx.get(m.fx)?; + let key = (f.layer.id, paged.get(m.fx).copied().unwrap_or(false).then_some(cell)); + let e = self.fx.get(&key)?; + if m.item == plan::SHAPE_MAP { + return Some((e.shape.view.clone(), e.region)); + } + let t = e.progs.get(m.item)?.maps.get(m.map)?.as_ref()?; + Some((t.view.clone(), e.region)) + })); + } + Bound { views, keys, maps } + } + + /// Run `plan` (drawn as `runs`, its `batch_runs`) over the `chunks` of one page cell + /// (document rects, at most a chunk square), handing each finished chunk to `sink`. + #[allow(clippy::too_many_arguments)] + pub(crate) fn run_cell( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + encoder: &mut wgpu::CommandEncoder, + doc: DocId, + plan: &Plan<'_>, + runs: &[usize], + paged: &[bool], + cell: Cell, + fr: &FrameRes, + chunks: &[Rect], + checkpoint: Option, + stats: &mut Stats, + sink: &mut dyn FnMut(&mut wgpu::CommandEncoder, ChunkOut<'_>), + // The previous intermediate submit, when this refresh may submit in between. + batch: &mut Option<&mut Option>, + ) { + if chunks.is_empty() { + return; + } + // Chunks may hold different checkpoints: bind from the lowest one any of them resumes at. + let first_pass = checkpoint + .and_then(|_| chunks.iter().map(|c| self.prefix.restore_point(*c).map(|r| r.pass_end)).try_fold(usize::MAX, |m, p| Some(m.min(p?)))) + .unwrap_or(0); + let bound = self.bind_cell(device, queue, encoder, doc, plan, paged, cell, fr, first_pass, stats); + // A page couldn't be created: draw nothing with the pages missing (the caller ends the refresh). + if self.layer_alloc.is_some() { + return; + } + + // Chunk pool. + while self.pool.len() < plan.slots as usize { + let t = device.create_texture(&wgpu::TextureDescriptor { + label: Some("pc_compose_chunk"), + size: wgpu::Extent3d { width: self.chunk, height: self.chunk, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: self.acc_format, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT + | wgpu::TextureUsages::TEXTURE_BINDING + | wgpu::TextureUsages::COPY_SRC + | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }); + let v = t.create_view(&Default::default()); + self.pool.push((t, v)); + } + + // Uniforms: chunk records, then one record per pass. encode_scoped preflight checked + // the length, device capacity and dynamic offsets before any GPU work for this frame. + let op_base = chunks.len() as u64 * STRIDE; + let mut data = vec![0u8; (op_base + plan.passes.len() as u64 * STRIDE) as usize]; + for (i, c) in chunks.iter().enumerate() { + let w = words(&[I(c.x0), I(c.y0), I(c.width() as i32), I(c.height() as i32)]); + data[i * STRIDE as usize..][..w.len()].copy_from_slice(&w); + } + for (i, p) in plan.passes.iter().enumerate() { + if i < first_pass { + continue; + } + let (tex, mask) = bound.views[i]; + let map = bound.maps[i].as_ref().map(|(_, r)| *r); + let run = runs.get(i).copied().unwrap_or(1); + let w = if run > 1 { + let extras: Vec<_> = (i + 1..i + run).filter_map(|j| Some((plan.passes.get(j)?, bound.views.get(j).and_then(|v| v.0).map(|t| t.1)))).collect(); + batch_op_words(p, tex.map(|t| t.1), mask.map(|m| m.1), &extras) + } else { + op_words(p, tex.map(|t| t.1), mask.map(|m| m.1), map) + }; + let off = (op_base + i as u64 * STRIDE) as usize; + data[off..][..w.len()].copy_from_slice(&w); + } + let ubuf = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("pc_compose_uniforms"), + size: data.len() as u64, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + queue.write_buffer(&ubuf, 0, &data); + let bg0 = uniform_group(device, &self.kit.bgl0, &ubuf); + + // Per-pass texture bind groups (chunk-independent: pool slots are reused per chunk). + let dummy = &self.kit.dummy; + let resident_views: Vec<&wgpu::TextureView> = bound.keys.iter().map(|k| self.residents.get(k).map_or(dummy, |r| &r.view)).collect(); + let mut bg1 = Vec::with_capacity(plan.passes.len()); + for (i, p) in plan.passes.iter().enumerate() { + if i < first_pass || p.kernel.entry().is_none() { + bg1.push(None); + continue; + } + let slot = |s: Option| s.map_or(dummy, |s| &self.pool[s as usize].1); + let (tex, mask) = &bound.views[i]; + let tv = tex.map_or(slot(p.d), |(k, _)| resident_views[k]); + let mv = mask.map_or(dummy, |(k, _)| resident_views[k]); + let lv = fr.luts.get(i).and_then(Option::as_ref).map_or(dummy, |(_, v)| v); + let map = bound.maps[i].as_ref().map_or(dummy, |(v, _)| v); + let pat = fr.patterns.get(i).and_then(Option::as_ref).unwrap_or(dummy); + let run = runs.get(i).copied().unwrap_or(1); + if run > 1 { + // The extra layers' pixels in tex_b, tex_c and map_tex (`batch_layer`). + let extra = |e: usize| bound.views.get(i + e).and_then(|v| v.0).map_or(dummy, |(k, _)| resident_views[k]); + bg1.push(Some(texture_group(device, &self.kit.bgl1, &[slot(p.a), extra(1), tv, mv, lv, extra(2), extra(3), pat]))); + continue; + } + bg1.push(Some(texture_group(device, &self.kit.bgl1, &[slot(p.a), slot(p.b), tv, mv, lv, slot(p.c), map, pat]))); + } + + for (ci, c) in chunks.iter().enumerate() { + let mut resume = 0; + if let Some(cp) = checkpoint.and_then(|_| self.prefix.restore_point(*c)) + && let Some((dst, _)) = self.pool.get(cp.slot as usize) + && self.prefix.copy_out(encoder, *c, dst) + { + resume = cp.pass_end; + stats.prefix_hits = stats.prefix_hits.saturating_add(1); + stats.prefix_passes_skipped = stats.prefix_passes_skipped.saturating_add(resume); + } + // Passes drawn inside the previous `fs_layerbatch` pass. + let mut batched_to = 0; + for (i, p) in plan.passes.iter().enumerate() { + if i < resume || i < batched_to { + continue; + } + // Chunk textures, uniforms and bind groups outlive the submit, and the queue + // keeps the order, so a chunk may continue in the next command buffer. + if self.recorded >= FLUSH_OPS + && let Some(last) = batch.as_deref_mut() + { + submit_batch(device, queue, encoder, self.health.as_ref(), self.timer.as_mut(), last); + self.staged = 0; + self.recorded = 0; + stats.flushes += 1; + if self.fault().is_some() { + return; + } + } + // Also after resuming from a lower checkpoint: the chunk moves up to this one. + if resume < i + && let Some(cp) = checkpoint.filter(|cp| cp.pass_end == i) + && let Some((src, _)) = self.pool.get(cp.slot as usize) + { + self.prefix.capture(device, encoder, *c, src, cp); + } + let scissor = match p.clip { + Some(clip) => { + let r = clip.intersect(c); + if r.is_empty() { + continue; + } + Rect::new(r.x0 - c.x0, r.y0 - c.y0, r.x1 - c.x0, r.y1 - c.y0) + } + None => Rect::new(0, 0, c.width() as i32, c.height() as i32), + }; + match p.kernel { + Kernel::CopyRect | Kernel::CopyFull => { + // The planner always gives copies a source. + let Some(a) = p.a else { continue }; + let src = &self.pool[a as usize].0; + let dst = &self.pool[p.dst as usize].0; + encoder.copy_texture_to_texture( + wgpu::TexelCopyTextureInfo { + texture: src, + mip_level: 0, + origin: wgpu::Origin3d { x: scissor.x0 as u32, y: scissor.y0 as u32, z: 0 }, + aspect: wgpu::TextureAspect::All, + }, + wgpu::TexelCopyTextureInfo { + texture: dst, + mip_level: 0, + origin: wgpu::Origin3d { x: scissor.x0 as u32, y: scissor.y0 as u32, z: 0 }, + aspect: wgpu::TextureAspect::All, + }, + wgpu::Extent3d { width: scissor.width(), height: scissor.height(), depth_or_array_layers: 1 }, + ); + self.recorded += 1; + continue; + } + _ => {} + } + self.recorded += 1; + // A run draws as one pass into the slot its last layer writes. + let run = runs.get(i).copied().unwrap_or(1); + let (kernel, dst) = match plan.passes.get(i + run - 1) { + Some(last) if run > 1 => { + batched_to = i + run; + stats.layers_batched = stats.layers_batched.saturating_add(run - 1); + let kernel = plan.passes.get(i..i + run).map_or(Kernel::LayerBatch, batch_kernel); + if kernel == Kernel::LayerBatchNormal { + stats.normal_batches = stats.normal_batches.saturating_add(1); + } + (kernel, last.dst) + } + _ => (p.kernel, p.dst), + }; + let target = &self.pool[dst as usize].1; + let clear = p.kernel == Kernel::Clear; + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("pc_compose_pass"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: target, + resolve_target: None, + depth_slice: None, + ops: wgpu::Operations { + load: if clear { wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT) } else { wgpu::LoadOp::Load }, + store: wgpu::StoreOp::Store, + }, + })], + depth_stencil_attachment: None, + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); + if clear { + continue; + } + pass.set_pipeline(&self.kit.pipelines[&(kernel, self.acc_format)]); + pass.set_scissor_rect(scissor.x0 as u32, scissor.y0 as u32, scissor.width(), scissor.height()); + pass.set_bind_group(0, &bg0, &[(ci as u64 * STRIDE) as u32, (op_base + i as u64 * STRIDE) as u32]); + pass.set_bind_group(1, bg1[i].as_ref(), &[]); + pass.draw(0..3, 0..1); + } + if resume < plan.passes.len() + && let Some(cp) = checkpoint.filter(|cp| cp.pass_end == plan.passes.len()) + && let Some((src, _)) = self.pool.get(cp.slot as usize) + { + self.prefix.capture(device, encoder, *c, src, cp); + } + let (t, v) = &self.pool[plan.root as usize]; + sink(encoder, ChunkOut { rect: *c, texture: t, view: v }); + } + } + + /// Upload changed tiles of `surface` within `region` (its tile area inside one page cell); + /// returns the resident key and its region (x, y, w, h). + #[allow(clippy::too_many_arguments)] + fn sync( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + encoder: &mut wgpu::CommandEncoder, + doc: DocId, + key: ResKey, + surface: &Surface, + region: Rect, + stats: &mut Stats, + ) -> Option<(ResKey, [i32; 4])> { + // An earlier page of this cell didn't fit: the refresh ends after the cell anyway. + if region.is_empty() || self.layer_alloc.is_some() { + return None; + } + let format = surface.format(); + let kind = TexKind::for_surface(key.1, format); + let cmyk = if format.mode == photocraft_color::ColorMode::Cmyk { self.cmyk } else { 0 }; + let default_pixel = surface.default_pixel(); + let default_bits: Vec = default_pixel.iter().map(|v| v.to_bits()).collect(); + let stale = self + .residents + .get(&key) + .is_none_or(|r| r.region != region || r.kind != kind || r.format != format || r.cmyk != cmyk || r.default_bits != default_bits); + if stale { + let desc = wgpu::TextureDescriptor { + label: Some("pc_compose_layer"), + size: wgpu::Extent3d { width: region.width(), height: region.height(), depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: kind.format(), + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::COPY_SRC, + view_formats: &[], + }; + let bytes = region.width() as u64 * region.height() as u64 * kind.bytes_per_pixel() as u64; + let texture = self.create_layer_texture(device, &desc, key, bytes, stats)?; + let view = texture.create_view(&Default::default()); + let default_nonzero = default_pixel.iter().any(|v| *v != 0.0); + let mut r = Resident { + texture, + view, + region, + kind, + format, + tiles: HashMap::new(), + default_nonzero, + default_bits: default_bits.clone(), + doc, + last_used: 0, + stamp: 0, + cmyk, + ordered: false, + }; + // Only the region moved (painting past a layer's tiles grows it): keep the texels the + // old texture already holds instead of converting and uploading every tile again. + let kept = self.residents.remove(&key).map_or(Rect::EMPTY, |old| keep_overlap(device, queue, &old, &mut r)); + // A new layer whose tiles another resident already holds (a duplicate shares its + // source's tiles) starts as a GPU copy of that texture. Duplicating a 20 MP photo + // converted and uploaded every tile again. + let shares = + |o: &Resident| region.tiles().filter(|c| surface.tile(*c).is_some_and(|t| o.tiles.get(c).is_some_and(|ot| Arc::ptr_eq(ot, t)))).count(); + let donor = self + .residents + .iter() + .filter(|(k, o)| k.1 == key.1 && o.region == region && o.kind == kind && o.format == format && o.cmyk == cmyk && o.default_bits == default_bits) + .map(|(k, o)| (shares(o), *k)) + .filter(|(n, _)| *n > 0) + .max_by_key(|(n, _)| *n); + if kept.is_empty() + && let Some((n, o)) = donor.and_then(|(n, k)| Some((n, self.residents.get_mut(&k)?))) + { + // Recorded in the frame's encoder, after the writes and copies that brought the + // donor up to date ([`keep_overlap`]'s own submission would run before those). + o.ordered = true; + encoder.copy_texture_to_texture( + o.texture.as_image_copy(), + r.texture.as_image_copy(), + wgpu::Extent3d { width: region.width(), height: region.height(), depth_or_array_layers: 1 }, + ); + r.tiles = o.tiles.clone(); + r.ordered = true; + stats.tiles_shared += n; + } else { + // A new texture starts zeroed: write the tiles that are present, and the default + // pixel where they are missing if it isn't zero. Coordinates sharing a tile (a + // solid fill, the default) take one upload and GPU copies (#1774). Kept tiles are + // brought up to date below, like those of a resident that didn't move. + let mut present = Vec::new(); + let mut missing = Vec::new(); + for c in region.tiles().filter(|c| !kept.contains_rect(&c.rect())) { + match surface.tile(c) { + Some(t) => present.push((c, t.clone())), + None if default_nonzero => missing.push(c), + None => {} + } + } + if !missing.is_empty() { + let bytes = convert_tile(surface, None, kind, TileCoord::new(0, 0)); + self.staged += put_tiles(device, queue, encoder, &r, &missing, &bytes); + } + let staged = &mut self.staged; + convert_tiles(surface, present, kind, |t, cs, bytes| { + *staged += put_tiles(device, queue, encoder, &r, cs, bytes); + for &c in cs { + stats.tiles_uploaded += 1; + stats.bytes_uploaded += bytes.len(); + r.tiles.insert(c, t.clone()); + } + }); + } + // Tiles the donor held that this surface doesn't, or holds differently, are fixed up + // by the pass over the region below. + self.residents.insert(key, r); + } + // Present: inserted above when it was missing or stale. + let r = self.residents.get_mut(&key)?; + r.last_used = self.frame; + r.stamp = self.stamp; + r.doc = doc; + let mut changed = Vec::new(); + let mut gone = Vec::new(); + for c in region.tiles() { + match surface.tile(c) { + Some(t) => { + if !r.tiles.get(&c).is_some_and(|old| Arc::ptr_eq(old, t)) { + changed.push((c, t.clone())); + } + } + None => { + if r.tiles.remove(&c).is_some() { + gone.push(c); + } + } + } + } + if !gone.is_empty() { + // A tile that went away reads as the default pixel again. + let bytes = if r.default_nonzero { + convert_tile(surface, None, kind, TileCoord::new(0, 0)) + } else { + vec![0u8; (TILE_SIZE * TILE_SIZE) as usize * kind.bytes_per_pixel()] + }; + self.staged += put_tiles(device, queue, encoder, r, &gone, &bytes); + } + let staged = &mut self.staged; + convert_tiles(surface, changed, kind, |t, cs, bytes| { + *staged += put_tiles(device, queue, encoder, r, cs, bytes); + for &c in cs { + stats.tiles_uploaded += 1; + stats.bytes_uploaded += bytes.len(); + r.tiles.insert(c, t.clone()); + } + }); + Some((key, [region.x0, region.y0, region.width() as i32, region.height() as i32])) + } + + /// Premultiplied RGBA32F texture of a pattern as it paints in the document's mode (cached by + /// pixel identity and mode). + pub(crate) fn pattern_view(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, pat: &Pattern) -> wgpu::TextureView { + let fp = pat.surface.tiles().fold((pat.width as u64) << 32 | pat.height as u64, |acc, (c, t)| { + acc.wrapping_mul(0x9e37_79b9_7f4a_7c15) ^ (Arc::as_ptr(t) as usize as u64) ^ ((c.tx as u64) << 20) ^ c.ty as u64 + }); + let mode = self.pattern_mode; + let key = format!("{}\u{0}{}\u{0}{mode:?}", pat.id, pat.name); + let format = pat.surface.format(); + // Unstored tiles read the default pixel, interpreted in the source format. + let default_bits: Vec = pat.surface.default_pixel().iter().map(|v| v.to_bits()).collect(); + let (doc, last_used) = (self.pattern_doc, self.frame); + if let Some(cached) = self.patterns.get_mut(&key) + && cached.fingerprint == fp + && cached.format == format + && cached.default_bits == default_bits + { + cached.doc = doc; + cached.last_used = last_used; + return cached.texture.view.clone(); + } + let (w, h) = (pat.width, pat.height); + let px = photocraft_compose::pattern::pattern_rgba(pat, mode); + let bytes: Vec = px.iter().flat_map(|q| [q[0] * q[3], q[1] * q[3], q[2] * q[3], q[3]]).flat_map(f32::to_le_bytes).collect(); + let t = Tex::new(device, "pc_pattern", w, h, wgpu::TextureFormat::Rgba32Float, wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST); + queue.write_texture( + wgpu::TexelCopyTextureInfo { texture: &t.texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, + &bytes, + wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(w * 16), rows_per_image: Some(h) }, + wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }, + ); + let v = t.view.clone(); + let bytes = u64::from(w.max(1)) * u64::from(h.max(1)) * 16; + self.patterns.insert(key, CachedPattern { fingerprint: fp, format, default_bits, texture: t, doc, last_used, bytes }); + v + } + + /// An R32F temporary at least `region`-sized (the smallest that fits) not in `taken`. + /// Stages only read what they wrote, inside the region, so a larger one is as good; page + /// windows of different sizes share them. + pub(crate) fn temp(&mut self, device: &wgpu::Device, region: Rect, taken: &[wgpu::TextureView]) -> wgpu::TextureView { + let (w, h) = (region.width(), region.height()); + let frame = self.frame; + let fit = self + .temps + .iter_mut() + .filter(|(t, _)| { + let s = t.texture.size(); + s.width >= w && s.height >= h && !taken.contains(&t.view) + }) + .min_by_key(|(t, _)| t.texture.size().width as u64 * t.texture.size().height as u64); + if let Some((t, used)) = fit { + *used = frame; + return t.view.clone(); + } + let t = Tex::map(device, "pc_fx_temp", region, MAP32); + let v = t.view.clone(); + self.temps.push((t, frame)); + v + } +} diff --git a/crates/gpu/src/consts.rs b/crates/gpu/src/consts.rs new file mode 100644 index 0000000000..40081a55c8 --- /dev/null +++ b/crates/gpu/src/consts.rs @@ -0,0 +1,54 @@ +/// Accumulator format for intermediate buffers. Full float: discontinuous operations +/// (Posterize, Threshold, Hard Mix, Dissolve) must land on the same side of their thresholds as +/// the CPU reference, and Color Burn/Dodge amplify input error. +pub const ACC_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba32Float; + +// default accumulation format; `preferred_acc_format` downgrades to Rgba16Float where 32-bit float isn't renderable +/// Effect intermediates (distances, blurs) and layer shapes. +pub(crate) const MAP32: wgpu::TextureFormat = wgpu::TextureFormat::R32Float; + +/// Final effect coverage maps (0..1; half precision is ~1/4000). +pub(crate) const MAP16: wgpu::TextureFormat = wgpu::TextureFormat::R16Float; + +/// Side of the square chunks the canvas is processed in. +pub const CHUNK: u32 = 1024; + +pub(crate) const STRIDE: u64 = 256; + +pub(crate) const CHUNK_UNIFORM: u64 = 16; + +pub(crate) const OP_UNIFORM: u64 = 256; + +/// GPU memory the effect-map cache may hold before evicting layers not drawn this frame. +pub const FX_BUDGET: usize = 1536 << 20; + +/// Largest side of the square pages layer surfaces are stored in on the GPU (smaller when the +/// device's texture limit is). A chunk only binds the pages of the cell it lies in, so layers of +/// any size composite on the GPU. +pub const PAGE: u32 = 2048; + +/// GPU memory resident layer pages may hold before the least recently used are evicted. +pub const RESIDENT_BUDGET: u64 = 4 << 30; + +/// GPU memory pattern textures may hold before the least recently painted are dropped (those the +/// current frame paints with always stay). +pub const PATTERN_BUDGET: u64 = 256 << 20; + +/// A pattern texture no frame has painted with for this many frames is dropped. +pub const PATTERN_IDLE_FRAMES: u64 = 240; + +/// Uploads (bytes) [`Compositor::render`] stages before submitting the work recorded so far, so +/// a refresh of a huge document never holds all its uploads in staging memory at once. +pub(crate) const FLUSH_BYTES: u64 = 512 << 20; + +/// Pass pixels (chunk pixels × passes) [`Compositor::render`] records before submitting: one +/// command buffer holding a whole huge refresh can run for seconds, long enough for the OS to +/// reset the GPU. +pub(crate) const FLUSH_WORK: u64 = 1 << 30; + +/// Copies and render passes [`Compositor::render`] records before submitting. wgpu opens up to +/// two backend command buffers for each (a render pass and its barrier pre-pass), and Metal +/// treats more than 4096 outstanding ones as a lost device: a refresh of a document with a few +/// hundred layers reached that inside a single page cell (P12, "pc_compose_uniforms is +/// invalid"), where the work and byte limits above never trigger. +pub(crate) const FLUSH_OPS: u32 = 1000; diff --git a/crates/gpu/src/convert.rs b/crates/gpu/src/convert.rs new file mode 100644 index 0000000000..6b0a7e6f98 --- /dev/null +++ b/crates/gpu/src/convert.rs @@ -0,0 +1,371 @@ +use super::batch::write_tile; +use super::textures::{Resident, TexKind}; +use super::*; + +/// Distinct tiles converted per parallel batch: bounds the converted bytes held at once (64 tiles +/// of a 16-bit page are 32 MiB). +pub(crate) const CONVERT_BATCH: usize = 64; + +/// Write the same tile `bytes` at every coordinate in `cs` of resident `r`; returns the bytes +/// staged. Several coordinates (a solid fill or a cleared area shares one tile) get one upload to +/// a scratch tile and GPU copies from it: writing each one from the CPU sent 387 MB per refresh +/// of a filled 50 MP 16-bit page (#1774). +pub(crate) fn put_tiles(device: &wgpu::Device, queue: &wgpu::Queue, encoder: &mut wgpu::CommandEncoder, r: &Resident, cs: &[TileCoord], bytes: &[u8]) -> u64 { + if let [c] = cs + && !r.ordered + { + write_tile(queue, r, *c, bytes); + return bytes.len() as u64; + } + if cs.is_empty() { + return 0; + } + let extent = wgpu::Extent3d { width: TILE_SIZE as u32, height: TILE_SIZE as u32, depth_or_array_layers: 1 }; + // Its own texture per call: queued writes land before the encoder runs, so a shared scratch + // would hold only the last tile by then. + let scratch = device.create_texture(&wgpu::TextureDescriptor { + label: Some("pc_tile_scratch"), + size: extent, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: r.kind.format(), + usage: wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }); + queue.write_texture( + wgpu::TexelCopyTextureInfo { texture: &scratch, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, + bytes, + wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(TILE_SIZE as u32 * r.kind.bytes_per_pixel() as u32), + rows_per_image: Some(TILE_SIZE as u32), + }, + extent, + ); + for c in cs { + let tr = c.rect(); + encoder.copy_texture_to_texture( + wgpu::TexelCopyTextureInfo { texture: &scratch, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, + wgpu::TexelCopyTextureInfo { + texture: &r.texture, + mip_level: 0, + origin: wgpu::Origin3d { x: (tr.x0 - r.region.x0) as u32, y: (tr.y0 - r.region.y0) as u32, z: 0 }, + aspect: wgpu::TextureAspect::All, + }, + extent, + ); + } + bytes.len() as u64 +} + +/// Copy the texels `old` holds inside the region of its replacement `new` (same texel kind, +/// format and default pixel; only the region moved) and carry over the tiles they show, so only +/// tiles outside the overlap or changed since need uploading. Returns the kept (tile-aligned) +/// rect; empty when nothing can be kept. +pub(crate) fn keep_overlap(device: &wgpu::Device, queue: &wgpu::Queue, old: &Resident, new: &mut Resident) -> Rect { + let same = old.kind == new.kind && old.format == new.format && old.cmyk == new.cmyk && old.default_bits == new.default_bits; + let k = old.region.intersect(&new.region); + if !same || k.is_empty() { + return Rect::EMPTY; + } + // Its own submission: tile writes go through the queue and land at the start of the next + // submit, before anything in the frame's encoder, so a copy recorded there would overwrite + // the tiles written after it with the old texels. + let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("pc_compose_keep") }); + encoder.copy_texture_to_texture( + wgpu::TexelCopyTextureInfo { + texture: &old.texture, + mip_level: 0, + origin: wgpu::Origin3d { x: (k.x0 - old.region.x0) as u32, y: (k.y0 - old.region.y0) as u32, z: 0 }, + aspect: wgpu::TextureAspect::All, + }, + wgpu::TexelCopyTextureInfo { + texture: &new.texture, + mip_level: 0, + origin: wgpu::Origin3d { x: (k.x0 - new.region.x0) as u32, y: (k.y0 - new.region.y0) as u32, z: 0 }, + aspect: wgpu::TextureAspect::All, + }, + wgpu::Extent3d { width: k.width(), height: k.height(), depth_or_array_layers: 1 }, + ); + queue.submit([encoder.finish()]); + new.tiles = old.tiles.iter().filter(|(c, _)| k.contains_rect(&c.rect())).map(|(c, t)| (*c, t.clone())).collect(); + k +} + +/// Convert `tiles` of `surface` to `kind` texels and hand each distinct tile, the coordinates +/// sharing it and its bytes to `put`. Each distinct tile is converted once (a solid fill shares +/// one `Arc` across every coordinate it covers), in parallel batches. Converting every tile one +/// after another on the UI thread froze a 50 MP 16-bit document for about 1.4 s after a +/// full-canvas fill (#1774). Returns how many tiles were converted. +pub(crate) fn convert_tiles( + surface: &Surface, + tiles: Vec<(TileCoord, Arc)>, + kind: TexKind, + mut put: impl FnMut(&Arc, &[TileCoord], &[u8]), +) -> usize { + let mut groups: Vec<(Arc, Vec)> = Vec::new(); + let mut index: HashMap<*const Tile, usize> = HashMap::new(); + for (c, t) in tiles { + match index.get(&Arc::as_ptr(&t)).and_then(|&i| groups.get_mut(i)) { + Some(g) => g.1.push(c), + None => { + index.insert(Arc::as_ptr(&t), groups.len()); + groups.push((t, vec![c])); + } + } + } + // CMYK and Lab tiles convert pixel by pixel through a colour transform (a CMYK tile took + // ~5 ms on one thread, the whole of a brush dab's refresh on an A4 CMYK page, #5108): those + // go in bands of rows, so even the one tile a dab touches spreads over the threads. Workers + // don't inherit this thread's CMYK profile scope, so each band enters it. + let bands = if colour_managed(&surface.format(), kind) { TILE_SIZE / MANAGED_BAND_ROWS } else { 1 }; + let space = photocraft_color::convert::active_cmyk_space(); + for batch in groups.chunks(CONVERT_BATCH) { + // A tile's content is the same at every coordinate sharing it: convert it at the first. + let jobs: Vec<_> = batch.iter().filter_map(|(t, cs)| cs.first().map(|c| (t, *c))).flat_map(|(t, c)| (0..bands).map(move |b| (t, c, b))).collect(); + let parts = fx::par_map(jobs, |(t, c, b)| { + photocraft_color::convert::with_cmyk_space(space.as_ref(), || { + if bands == 1 { + return convert_tile(surface, Some(t), kind, c); + } + let r = c.rect(); + let y0 = r.y0 + b * MANAGED_BAND_ROWS; + convert_rows(surface, Some(t), kind, Rect::new(r.x0, y0, r.x1, y0 + MANAGED_BAND_ROWS)) + }) + }); + for ((t, cs), bytes) in batch.iter().zip(parts.chunks(bands as usize)) { + // One part (every format but CMYK and Lab) goes through as is: no copy per tile. + match bytes { + [one] => put(t, cs, one), + _ => put(t, cs, &bytes.concat()), + } + } + } + groups.len() +} + +/// Rows per parallel band of a colour-managed (CMYK, Lab) tile conversion. +const MANAGED_BAND_ROWS: i32 = 16; + +/// Whether `fmt` pixels reach `kind` texels through a per-pixel colour transform (CMYK, Lab). +pub(crate) fn colour_managed(fmt: &PixelFormat, kind: TexKind) -> bool { + use photocraft_color::ColorMode; + matches!(kind, TexKind::Rgba8 | TexKind::Rgba16F) && matches!(fmt.mode, ColorMode::Cmyk | ColorMode::Lab) +} + +/// Tile pixels in the texture's format. `tile = None` gives the default pixel everywhere. +pub(crate) fn convert_tile(surface: &Surface, tile: Option<&Arc>, kind: TexKind, c: TileCoord) -> Vec { + if let (Some(t), TexKind::Rgba8Direct | TexKind::R8Direct) = (tile, kind) { + return t.bytes().to_vec(); + } + let fmt = surface.format(); + if let (Some(t), TexKind::Rgba16F) = (tile, kind) + && let Some(out) = rgb_gray16_to_f16(&fmt, t.bytes()).or_else(|| rgb_gray32_to_f16(&fmt, t.bytes())) + { + return out; + } + convert_rows(surface, tile, kind, c.rect()) +} + +/// [`convert_tile`]'s general path for `rect` (rows of one tile): each pixel through +/// `photocraft_raster::to_rgba`. A run of identical pixels (the transparent or flat areas around a +/// brush dab) is converted once: the same samples give the same texels. +fn convert_rows(surface: &Surface, tile: Option<&Arc>, kind: TexKind, rect: Rect) -> Vec { + let n = rect.width() as usize * rect.height() as usize; + let fmt = surface.format(); + let ch = fmt.channels(); + let raw: Vec = match tile { + Some(_) => surface.read_region(rect), + None => surface.default_pixel().repeat(n), + }; + let mut out = Vec::with_capacity(n * kind.bytes_per_pixel()); + // The previous pixel and its colour. + let mut last: Option<(usize, [f32; 4])> = None; + for (i, px) in raw.chunks_exact(ch).enumerate() { + let mut rgba = || -> [f32; 4] { + if let Some((j, v)) = last + && raw.get(j * ch..j * ch + ch).is_some_and(|p| p.iter().zip(px).all(|(a, b)| a.to_bits() == b.to_bits())) + { + return v; + } + let v = photocraft_raster::to_rgba(&fmt, px); + last = Some((i, v)); + v + }; + match kind { + TexKind::Rgba8Direct | TexKind::Rgba8 => { + let v = rgba(); + out.extend(v.map(|x| (x.clamp(0.0, 1.0) * 255.0 + 0.5) as u8)); + } + TexKind::Rgba16F => { + let v = rgba(); + for x in v { + out.extend(f32_to_f16(x).to_le_bytes()); + } + } + TexKind::R8Direct => out.push((px[0].clamp(0.0, 1.0) * 255.0 + 0.5) as u8), + TexKind::R16F => out.extend(f32_to_f16(px[0]).to_le_bytes()), + TexKind::R32F => out.extend(px[0].to_le_bytes()), + } + } + out +} + +/// RGBA16F texels of a 16-bit RGB or grayscale tile, through a table of every 16-bit sample's +/// half: the same bytes as the general path at a fraction of its cost (a 50 MP 16-bit refresh +/// converts dozens of tiles). `None` for other formats. +pub(crate) fn rgb_gray16_to_f16(fmt: &PixelFormat, bytes: &[u8]) -> Option> { + use photocraft_color::ColorMode; + static HALF: std::sync::OnceLock> = std::sync::OnceLock::new(); + if fmt.sample != SampleType::U16 { + return None; + } + let gray = match fmt.mode { + ColorMode::Rgb => false, + ColorMode::Grayscale | ColorMode::Bitmap | ColorMode::Duotone => true, + _ => return None, + }; + let half = HALF.get_or_init(|| (0..=u16::MAX).map(|v| f32_to_f16(v as f32 / 65535.0)).collect()); + let one = f32_to_f16(1.0).to_le_bytes(); + let ch = fmt.channels(); + let mut out = Vec::with_capacity((TILE_SIZE * TILE_SIZE) as usize * 8); + for px in bytes.chunks_exact(ch * 2) { + let h = |i: usize| -> [u8; 2] { + let v = px.get(i * 2..i * 2 + 2).map_or(0, |b| u16::from_ne_bytes([b[0], b[1]])); + half.get(v as usize).copied().unwrap_or(0).to_le_bytes() + }; + let (r, g, b) = if gray { (h(0), h(0), h(0)) } else { (h(0), h(1), h(2)) }; + let a = if fmt.alpha { h(ch - 1) } else { one }; + out.extend_from_slice(&r); + out.extend_from_slice(&g); + out.extend_from_slice(&b); + out.extend_from_slice(&a); + } + Some(out) +} + +/// RGBA16F texels of a 32-bit float RGB or grayscale tile, straight from its samples: the same +/// bytes as the general path without decoding the tile into a float buffer and converting it +/// pixel by pixel (a brush dab on a 32-bit layer re-uploads the tiles it touched). `None` for +/// other formats. +pub(crate) fn rgb_gray32_to_f16(fmt: &PixelFormat, bytes: &[u8]) -> Option> { + use photocraft_color::ColorMode; + if fmt.sample != SampleType::F32 { + return None; + } + let gray = match fmt.mode { + ColorMode::Rgb => false, + ColorMode::Grayscale | ColorMode::Bitmap | ColorMode::Duotone => true, + _ => return None, + }; + let one = f32_to_f16(1.0).to_le_bytes(); + let ch = fmt.channels(); + let mut out = Vec::with_capacity((TILE_SIZE * TILE_SIZE) as usize * 8); + for px in bytes.chunks_exact(ch * 4) { + let h = |i: usize| -> [u8; 2] { + let v = px.get(i * 4..i * 4 + 4).map_or(0.0, |b| f32::from_ne_bytes([b[0], b[1], b[2], b[3]])); + f32_to_f16(v).to_le_bytes() + }; + let (r, g, b) = if gray { + let v = h(0); + (v, v, v) + } else { + (h(0), h(1), h(2)) + }; + let a = if fmt.alpha { h(ch - 1) } else { one }; + out.extend_from_slice(&r); + out.extend_from_slice(&g); + out.extend_from_slice(&b); + out.extend_from_slice(&a); + } + Some(out) +} + +pub(crate) fn lut_texture(device: &wgpu::Device, queue: &wgpu::Queue, rows: &[[f32; 4096]]) -> (wgpu::Texture, wgpu::TextureView) { + let t = device.create_texture(&wgpu::TextureDescriptor { + label: Some("pc_compose_lut"), + size: wgpu::Extent3d { width: 4096, height: rows.len() as u32, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::R32Float, + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }); + let bytes: Vec = rows.iter().flat_map(|r| r.iter().flat_map(|v| v.to_le_bytes())).collect(); + queue.write_texture( + wgpu::TexelCopyTextureInfo { texture: &t, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, + &bytes, + wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(4096 * 4), rows_per_image: Some(rows.len() as u32) }, + wgpu::Extent3d { width: 4096, height: rows.len() as u32, depth_or_array_layers: 1 }, + ); + let v = t.create_view(&Default::default()); + (t, v) +} + +#[derive(Clone, Copy)] +pub(crate) enum W { + I(i32), + U(u32), + F(f32), +} + +pub(crate) fn words(v: &[W]) -> Vec { + v.iter() + .flat_map(|w| match w { + I(i) => i.to_le_bytes(), + U(u) => u.to_le_bytes(), + F(f) => f.to_le_bytes(), + }) + .collect() +} + +/// IEEE half from f32 (round to nearest even; overflow → inf). +pub fn f32_to_f16(x: f32) -> u16 { + let b = x.to_bits(); + let sign = ((b >> 16) & 0x8000) as u16; + let exp = ((b >> 23) & 0xff) as i32; + let man = b & 0x7f_ffff; + if exp == 0xff { + return sign | 0x7c00 | if man != 0 { 0x200 } else { 0 }; + } + let e = exp - 127 + 15; + if e >= 0x1f { + return sign | 0x7c00; + } + if e <= 0 { + if e < -10 { + return sign; + } + let m = man | 0x80_0000; + let shift = (14 - e) as u32; + let half = 1u32 << (shift - 1); + let rounded = (m + half - 1 + ((m >> shift) & 1)) >> shift; + return sign | rounded as u16; + } + let mut h = ((e as u32) << 10) | (man >> 13); + let rest = man & 0x1fff; + if rest > 0x1000 || (rest == 0x1000 && (h & 1) == 1) { + h += 1; + } + sign | h as u16 +} + +/// f32 from IEEE half. +pub fn f16_to_f32(h: u16) -> f32 { + let sign = if h & 0x8000 != 0 { -1.0 } else { 1.0 }; + let exp = ((h >> 10) & 0x1f) as i32; + let man = (h & 0x3ff) as f32; + match exp { + 0 => sign * man * 2f32.powi(-24), + 0x1f => { + if man == 0.0 { + sign * f32::INFINITY + } else { + f32::NAN + } + } + e => sign * (1.0 + man / 1024.0) * 2f32.powi(e - 15), + } +} diff --git a/crates/gpu/src/encode.rs b/crates/gpu/src/encode.rs new file mode 100644 index 0000000000..037a4cc80d --- /dev/null +++ b/crates/gpu/src/encode.rs @@ -0,0 +1,423 @@ +use super::batch::{batch_runs, run_starts, submit_batch, tile_grid}; +use super::consts::{FLUSH_BYTES, FLUSH_OPS, FLUSH_WORK, PATTERN_IDLE_FRAMES}; +use super::convert::lut_texture; +use super::kit::FrameRes; +use super::paging::{OVER_BUDGET, cell_rect, first_error, grid_rect_count, grid_rects, lru_victims, scoped_work, uniform_buffer_len}; +use super::textures::{ChunkOut, FxKey, ResKey, Resident, Stats}; +use super::*; + +impl Compositor { + /// Composite `region` of `doc`. Each finished chunk is passed to `sink` while its encoder is + /// still open; the chunk texture is reused afterwards, so the sink must record any copies + /// or passes that read it into the given encoder. Submits the work before returning; a + /// refresh of a huge document also submits in between (the sink may be handed a new + /// encoder), so its uploads and evicted pages never pile up in memory. + pub fn render( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + doc: &Document, + region: Rect, + mut sink: impl FnMut(&mut wgpu::CommandEncoder, ChunkOut<'_>), + ) -> Result { + let result = scoped_work(device, self.health.clone(), || { + let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("pc_compose") }); + if self.timer.as_ref().is_some_and(timing::GpuTimer::busy) { + // The readback map completes on a poll. The app polls every frame, but a + // non-blocking poll here keeps the measurements coming whatever the caller does. + match &self.health { + Some(h) => h.poll(device), + None => { + let _ = device.poll(wgpu::PollType::Poll); + } + } + } + // Whatever came back since the last render travels out with this one's stats, so + // nothing has to reach back into the compositor for it afterwards. + let landed = self.timer.as_mut().and_then(timing::GpuTimer::take); + if let Some(t) = &mut self.timer { + let r = region.intersect(&doc.bounds()); + t.start(&mut encoder, r.width() as u64 * r.height() as u64); + } + let mut stats = self.encode_inner(device, queue, &mut encoder, doc, region, &mut sink, true); + if let Ok(s) = &mut stats { + s.gpu_time = landed; + } + if let Some(t) = &mut self.timer { + // A refresh that failed part way measures nothing: its spans describe work the + // caller is about to redo on the CPU. + match stats { + Ok(_) => t.finish(&mut encoder), + Err(_) => { + t.cancel(); + // The refresh is lost, but a measurement that came back with it is not: + // hand it to the next render rather than drop it on the fallback path. + if let Some(landed) = landed { + t.restore(landed); + } + } + } + } + let stats = stats?; + queue.submit([encoder.finish()]); + if let Some(t) = &mut self.timer { + t.submitted(); + } + Ok(stats) + }); + if result.is_err() { + self.discard_failed_work(); + } + result + } + + /// Like [`Self::render`] but records into `encoder` without submitting. + pub fn encode( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + encoder: &mut wgpu::CommandEncoder, + doc: &Document, + region: Rect, + sink: &mut dyn FnMut(&mut wgpu::CommandEncoder, ChunkOut<'_>), + ) -> Result { + let result = scoped_work(device, self.health.clone(), || self.encode_inner(device, queue, encoder, doc, region, sink, false)); + if result.is_err() { + self.discard_failed_work(); + } + result + } + + fn discard_failed_work(&mut self) { + // Cache metadata advances while recording. A failed encoder may never execute its + // texture uploads or effect maps, so none of those cached pixels can be trusted. + self.prefix.clear(); + self.residents.clear(); + self.fx.clear(); + self.patterns.clear(); + self.temps.clear(); + self.pool.clear(); + } + + #[allow(clippy::too_many_arguments)] + fn encode_inner( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + encoder: &mut wgpu::CommandEncoder, + doc: &Document, + region: Rect, + sink: &mut dyn FnMut(&mut wgpu::CommandEncoder, ChunkOut<'_>), + flush: bool, + ) -> Result { + if let Some(f) = self.fault() { + return Err(Unsupported(f.to_string())); + } + // CMYK layers convert through the document's own CMYK profile (uploads and plan colours). + let space = photocraft_compose::cmyk_space(doc); + self.cmyk = space.as_ref().map_or(0, |s| s.id); + photocraft_color::convert::with_cmyk_space(space.as_ref(), || self.encode_scoped(device, queue, encoder, doc, region, sink, flush)) + } + + #[allow(clippy::too_many_arguments)] + fn encode_scoped( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + encoder: &mut wgpu::CommandEncoder, + doc: &Document, + region: Rect, + sink: &mut dyn FnMut(&mut wgpu::CommandEncoder, ChunkOut<'_>), + flush: bool, + ) -> Result { + let canvas = doc.bounds(); + let region = region.intersect(&canvas); + let plan = plan(doc)?; + self.check_fx(doc, &plan)?; + self.pattern_mode = doc.pixel_format().mode; + self.pattern_doc = doc.id; + let mut stats = Stats { passes: plan.passes.len(), slots: plan.slots, ..Default::default() }; + if region.is_empty() { + return Ok(stats); + } + let page = self.page; + let mut cells = grid_rects(region, page); + // Check every actual page cell before uploads, submissions or sink output. A later + // cell can need more chunk records than the first; a failure must leave the device healthy. + let buffer_limit = device.limits().max_buffer_size; + for part in &cells { + uniform_buffer_len(grid_rect_count(*part, self.chunk)?, plan.passes.len(), buffer_limit)?; + } + if self.frame == 0 { + // The first submission after device creation is dropped on some drivers (RADV), + // which would render the first frame black; land it on an empty buffer instead. + queue.submit(std::iter::empty::()); + } + self.frame += 1; + self.stamp += 1; + self.staged = 0; + self.recorded = 0; + self.layer_alloc = None; + self.admit_freed = 0; + + // Only render owns submission. A caller may discard encode's command buffer, so it + // cannot establish (or consume) a checkpoint whose GPU copy might never execute. + // Runs of plain layers drawn as one pass each (`fs_layerbatch`). The grouping is the same + // for every render of this plan, so a layer's bits don't depend on the cache: renders + // capture and resume only where a run starts. + let runs = batch_runs(&plan); + let checkpoint = if flush { + let starts = run_starts(&runs); + let resumable: Vec<_> = plan.checkpoints.iter().filter(|c| starts.get(c.pass_end).copied().unwrap_or(false)).copied().collect(); + self.prefix.prepare(doc, &resumable) + } else { + None + }; + + // Effect maps of whole regions first (they may render group shapes through sub-plans); + // regions larger than the limit are built per cell below. + let paged: Vec = plan.fx.iter().map(|f| self.fx_paged(f.region)).collect(); + let aprons: Vec = plan.fx.iter().zip(&paged).map(|(f, &pg)| if pg { Self::fx_apron(doc, f) } else { 0 }).collect(); + for (f, &pg) in plan.fx.iter().zip(&paged) { + if !pg { + self.sync_fx(device, queue, encoder, doc, f, (f.layer.id, None), f.region, &mut stats)?; + } + } + let fr = self.frame_res(device, queue, canvas, &plan); + + // Page cells; every other frame in reverse, so a repeated full refresh of a document + // larger than the budget starts with the pages still resident. + if self.frame.is_multiple_of(2) { + cells.reverse(); + } + if let Some(f) = self.focus { + let p = page as i32; + let focused = |r: &Rect| !cell_rect((r.x0.div_euclid(p), r.y0.div_euclid(p)), page).intersect(&f).is_empty(); + cells.sort_by_key(focused); + } + let flush_bytes = FLUSH_BYTES.min(self.memory_budget() / 8).max(16 << 20); + stats.cells = cells.len(); + // The previous intermediate submit (see `submit_batch`). + let mut last_submit: Option = None; + // Work recorded and bytes evicted since the last submit. + let (mut work, mut freed) = (0u64, 0u64); + for part in cells { + self.stamp += 1; + let cell = (part.x0.div_euclid(page as i32), part.y0.div_euclid(page as i32)); + let cr = cell_rect(cell, page); + for (i, f) in plan.fx.iter().enumerate() { + let pf = cr.intersect(&f.region); + if !paged.get(i).copied().unwrap_or(false) || pf.is_empty() { + continue; + } + let window = pf.inflate(aprons.get(i).copied().unwrap_or(0)).intersect(&f.region); + self.sync_fx(device, queue, encoder, doc, f, (f.layer.id, Some(cell)), window, &mut stats)?; + } + let chunks = grid_rects(part, self.chunk); + stats.chunks += chunks.len(); + work += part.width() as u64 * part.height() as u64 * plan.passes.len() as u64; + let mut batch = flush.then_some(&mut last_submit); + self.run_cell(device, queue, encoder, doc.id, &plan, &runs, &paged, cell, &fr, &chunks, checkpoint, &mut stats, sink, &mut batch); + // The device was lost in a submit inside the cell: issue no more work. + if let Some(f) = self.fault() { + return Err(Unsupported(f.to_string())); + } + // Out of memory although every page this cell doesn't use was dropped: the work recorded + // since the last submit can still hold those pages. Submit it, wait until the GPU is done + // with it so their memory is released, and run the cell once more. `encode` can't + // submit, so there the refresh goes to the CPU straight away. + if flush && self.layer_alloc.as_deref() == Some(OVER_BUDGET) { + self.layer_alloc = None; + submit_batch(device, queue, encoder, self.health.as_ref(), self.timer.as_mut(), &mut last_submit); + #[cfg(not(target_arch = "wasm32"))] + { + let idle = match self.health.as_ref() { + Some(h) => h.wait_idle(device, last_submit.clone()), + None => device.poll(wgpu::PollType::Wait { submission_index: last_submit.clone(), timeout: None }).is_ok(), + }; + // The GPU has run every timestamp submitted so far, so a retry that fails too + // can drop this measurement without switching timing off for good. + if idle && let Some(t) = self.timer.as_mut() { + t.drained(); + } + } + self.staged = 0; + self.recorded = 0; + work = 0; + freed = 0; + self.admit_freed = 0; + stats.flushes += 1; + if let Some(f) = self.fault() { + return Err(Unsupported(f.to_string())); + } + let mut batch = Some(&mut last_submit); + self.run_cell(device, queue, encoder, doc.id, &plan, &runs, &paged, cell, &fr, &chunks, checkpoint, &mut stats, sink, &mut batch); + if let Some(f) = self.fault() { + return Err(Unsupported(f.to_string())); + } + } + // A page didn't fit even after evicting: this refresh goes to the CPU, the next one + // tries the GPU again (#6563). + if let Some(e) = self.layer_alloc.take() { + return Err(Unsupported(e)); + } + let (evicted, bytes) = self.evict(); + stats.evicted += evicted; + freed = freed.saturating_add(bytes.saturating_add(std::mem::take(&mut self.admit_freed))); + if flush && (self.staged >= flush_bytes || work >= FLUSH_WORK || freed >= flush_bytes || self.recorded >= FLUSH_OPS) { + submit_batch(device, queue, encoder, self.health.as_ref(), self.timer.as_mut(), &mut last_submit); + self.staged = 0; + self.recorded = 0; + work = 0; + freed = 0; + stats.flushes += 1; + // The device was lost mid-refresh: issue no more work. + if let Some(f) = self.fault() { + return Err(Unsupported(f.to_string())); + } + } + } + + // Evict this document's textures whose layers are gone (hidden layers stay resident so + // toggling visibility costs no upload). + let frame = self.frame; + let live: std::collections::HashSet = doc.walk().into_iter().map(|(_, _, l)| l.id).collect(); + self.residents.retain(|(id, _, _), r| r.doc != doc.id || r.last_used == frame || live.contains(id)); + self.fx.retain(|(id, _), e| e.doc != doc.id || e.last_used == frame || live.contains(id)); + stats.evicted += self.evict().0; + self.temps.retain(|(_, used)| frame.saturating_sub(*used) < 240); + self.evict_patterns(); + Ok(stats) + } + + /// Drop the pattern textures no frame has painted with for [`PATTERN_IDLE_FRAMES`] frames, + /// then the least recently painted ones over the pattern budget. Never one this frame painted + /// with: it would only be uploaded again on the next frame. + fn evict_patterns(&mut self) { + let frame = self.frame; + self.patterns.retain(|_, p| frame.saturating_sub(p.last_used) < PATTERN_IDLE_FRAMES); + let mut total = self.pattern_cache_bytes(); + if total > self.pattern_budget { + let mut lru: Vec<(u64, String, u64)> = + self.patterns.iter().filter(|(_, p)| p.last_used != frame).map(|(k, p)| (p.last_used, k.clone(), p.bytes)).collect(); + lru.sort_unstable(); + for (_, key, bytes) in lru { + if total <= self.pattern_budget { + break; + } + self.patterns.remove(&key); + total = total.saturating_sub(bytes); + } + } + } + + /// Keep resident pages within the resident budget and the effect cache within + /// its budget, least recently used first. Never drops what the current cell uses, nor + /// whole-region effect maps drawn this frame. Returns how many textures were dropped and + /// their bytes. + fn evict(&mut self) -> (usize, u64) { + let (mut n, mut freed) = self.evict_residents(self.resident_budget, 0, None); + let mut total = self.fx_cache_bytes(); + let fx_budget = usize::try_from(self.fx_budget).unwrap_or(usize::MAX); + if total > fx_budget { + let (frame, stamp) = (self.frame, self.stamp); + let mut lru: Vec<((u64, u64), FxKey)> = self + .fx + .iter() + .filter(|(k, e)| e.last_used != frame || (k.1.is_some() && e.stamp != stamp)) + .map(|(k, e)| ((e.last_used, e.stamp), *k)) + .collect(); + lru.sort_unstable_by_key(|c| c.0); + for (_, k) in lru { + if total <= fx_budget { + break; + } + if let Some(e) = self.fx.remove(&k) { + total = total.saturating_sub(e.bytes()); + n += 1; + freed += e.bytes() as u64; + } + } + } + (n, freed) + } + + /// Drop least recently used resident pages until `incoming` more bytes fit in `budget`. + /// Never drops what the current cell uses, nor `keep`. Returns how many pages were dropped + /// and their bytes. + fn evict_residents(&mut self, budget: u64, incoming: u64, keep: Option) -> (usize, u64) { + let stamp = self.stamp; + let pages: Vec<(u64, ResKey, u64)> = + self.residents.iter().filter(|(k, r)| r.stamp != stamp && Some(**k) != keep).map(|(k, r)| (r.stamp, *k, r.bytes())).collect(); + let (mut n, mut freed) = (0, 0u64); + for k in lru_victims(pages, self.resident_bytes(), incoming, budget) { + if let Some(r) = self.residents.remove(&k) { + n += 1; + freed += r.bytes(); + } + } + (n, freed) + } + + /// Create the page texture for `key`, `bytes` large. Least recently used pages make room in + /// the budget first; when the device is still out of memory, every page the current cell + /// doesn't use is dropped and creation is tried once more (#6563). `None` (with + /// `layer_alloc` set) when it still fails: `render` submits the recorded work, which can still + /// hold the dropped pages, and runs the cell once more; after that the CPU draws the refresh. + pub(crate) fn create_layer_texture( + &mut self, + device: &wgpu::Device, + desc: &wgpu::TextureDescriptor<'_>, + key: ResKey, + bytes: u64, + stats: &mut Stats, + ) -> Option { + let replaced = self.residents.get(&key).map_or(0, Resident::bytes); + let (n, dropped) = self.evict_residents(self.resident_budget, bytes.saturating_sub(replaced), Some(key)); + stats.evicted += n; + self.admit_freed = self.admit_freed.saturating_add(dropped); + // WebGPU reports errors asynchronously: its failures reach the health callbacks. + if cfg!(target_arch = "wasm32") { + return Some(device.create_texture(desc)); + } + for retry in [false, true] { + let (texture, mut error) = first_error(device, || device.create_texture(desc)); + if error.is_none() && self.fail_allocs > 0 { + self.fail_allocs -= 1; + error = Some(wgpu::Error::OutOfMemory { source: "out of memory (test hook)".into() }); + } + match error { + None => return Some(texture), + Some(wgpu::Error::OutOfMemory { .. }) if !retry => { + let (n, dropped) = self.evict_residents(0, 0, Some(key)); + stats.evicted += n; + self.admit_freed = self.admit_freed.saturating_add(dropped); + } + Some(wgpu::Error::OutOfMemory { .. }) => { + self.layer_alloc = Some(OVER_BUDGET.into()); + return None; + } + Some(e) => { + self.layer_alloc = Some(format!("GPU layer texture failed: {e}")); + return None; + } + } + } + self.layer_alloc = Some(OVER_BUDGET.into()); + None + } + + /// Per-frame resources of `plan`: the tile area of each pass's surfaces, its LUT and pattern. + fn frame_res(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, canvas: Rect, plan: &Plan<'_>) -> FrameRes { + let grid = tile_grid(canvas); + let area = |s: &Surface| s.tile_bounds().intersect(&grid); + let areas = plan + .passes + .iter() + .map(|p| (p.tex.as_ref().map_or(Rect::EMPTY, |t| area(t.surface.get())), p.mask.as_ref().map_or(Rect::EMPTY, |m| area(m.surface.get())))) + .collect(); + let luts = plan.passes.iter().map(|p| p.lut.as_ref().map(|rows| lut_texture(device, queue, rows))).collect(); + let patterns = plan.passes.iter().map(|p| p.pattern.map(|pat| self.pattern_view(device, queue, pat))).collect(); + FrameRes { areas, luts, patterns } + } +} diff --git a/crates/gpu/src/fx.rs b/crates/gpu/src/fx.rs index 898eb2b87a..34982cd2be 100644 --- a/crates/gpu/src/fx.rs +++ b/crates/gpu/src/fx.rs @@ -757,316 +757,4 @@ pub(crate) fn group_key(layer: &Layer, light: &GlobalLight, pin: &mut dyn FnMut( #[cfg(test)] #[allow(clippy::unreachable)] // clippy.toml exempts unwrap/expect/panic in tests, not unreachable! -mod tests { - use super::*; - use photocraft_color::BlendMode; - use photocraft_doc::FxCommon; - - /// Filled-shape identity survives integer moves, including fractional anchors and handles. - #[test] - fn filled_shape_key_preserves_translation_but_detects_deformation() { - use photocraft_doc::{Fill, Path, ShapeLayer, Subpath}; - let mut layer = Layer::new( - "shape", - LayerContent::Shape(ShapeLayer { - path: Path::new(vec![Subpath::polygon(&[(20.0, 20.0), (70.0, 20.0), (70.0, 60.0), (20.0, 60.0)])]), - fill: Some(Fill::Solid(photocraft_color::Color::WHITE)), - ..Default::default() - }), - ); - let canvas = Rect::new(0, 0, 200, 200); - let before = shape_key(&layer, canvas); - let LayerContent::Shape(shape) = &mut layer.content else { unreachable!() }; - shape.path = shape.path.transform(&photocraft_geom::Affine::translate(13.0, 7.0)); - assert_eq!(before, shape_key(&layer, canvas)); - let LayerContent::Shape(shape) = &mut layer.content else { unreachable!() }; - shape.path.subpaths[0].knots[1].anchor.x += 3.0; - assert_ne!(before, shape_key(&layer, canvas)); - - let LayerContent::Shape(shape) = &mut layer.content else { unreachable!() }; - shape.path = Path::new(vec![Subpath::polygon(&[(0.1, 0.2), (0.3, 0.2), (0.3, 1.7), (0.1, 1.7)])]); - shape.path.subpaths[0].knots[1].out_ctrl = photocraft_geom::Point::new(0.45, 0.65); - let original = shape.path.clone(); - let before = shape_key(&layer, canvas); - for (dx, dy) in [(1.0, 1.0), (-13.0, 7.0), (100_000.0, -100_000.0)] { - let LayerContent::Shape(shape) = &mut layer.content else { unreachable!() }; - shape.path = original.transform(&photocraft_geom::Affine::translate(dx, dy)); - assert_eq!(before, shape_key(&layer, canvas), "fractional path translated by {dx}, {dy}"); - } - let LayerContent::Shape(shape) = &mut layer.content else { unreachable!() }; - shape.path.subpaths[0].knots[1].out_ctrl.x += 0.01; - assert_ne!(before, shape_key(&layer, canvas), "a handle deformation invalidates the key"); - } - - #[test] - fn programs_key_on_geometry_not_colour() { - let light = GlobalLight::default(); - let Effect::DropShadow(mut s) = Effect::default_drop_shadow() else { unreachable!() }; - let a = program(&Effect::DropShadow(s.clone()), &light, false); - s.color = photocraft_color::Color::rgb(1.0, 0.0, 0.0); - s.common = FxCommon::new(BlendMode::Screen, 0.3); - let b = program(&Effect::DropShadow(s.clone()), &light, false); - assert_eq!(a.key, b.key); - s.size += 1.0; - assert_ne!(a.key, program(&Effect::DropShadow(s), &light, false).key); - } - - /// A styled group's effect shape follows its own vector mask and its children's Blend If and - /// Advanced Blending, so the cached shape must be rebuilt when any of them changes. - #[test] - fn group_key_follows_vector_mask_blend_if_and_advanced() { - use photocraft_doc::{BlendRange, Knockout, Path, PixelFormat, Subpath, VectorMask}; - let light = GlobalLight::default(); - let group = Layer::group("g", vec![Layer::raster("child", PixelFormat::RGBA8)]); - let base = group_key(&group, &light, &mut |_| {}); - - let mask = |x: f64| VectorMask::new(Path::new(vec![Subpath::polygon(&[(x, 0.0), (x + 10.0, 0.0), (x + 10.0, 10.0)])])); - let mut masked = group.clone(); - masked.vector_mask = Some(mask(0.0)); - let with_mask = group_key(&masked, &light, &mut |_| {}); - assert_ne!(base, with_mask, "adding the group's vector mask"); - masked.vector_mask = Some(mask(5.0)); - assert_ne!(with_mask, group_key(&masked, &light, &mut |_| {}), "moving the group's vector mask"); - - fn child_mut(g: &mut Layer) -> &mut Layer { - let LayerContent::Group(gr) = &mut g.content else { unreachable!() }; - &mut gr.children[0] - } - let mut blend_if = group.clone(); - child_mut(&mut blend_if).blend_if.ranges = vec![[BlendRange { black: [128, 128], white: [255, 255] }, BlendRange::FULL]]; - assert_ne!(base, group_key(&blend_if, &light, &mut |_| {}), "a child's Blend If"); - - let mut advanced = group.clone(); - child_mut(&mut advanced).advanced.knockout = Knockout::Deep; - assert_ne!(base, group_key(&advanced, &light, &mut |_| {}), "a child's Advanced Blending"); - } - - #[test] - fn windows_grow_by_reach_and_temps_are_reused() { - let light = GlobalLight::default(); - let Effect::DropShadow(mut s) = Effect::default_drop_shadow() else { unreachable!() }; - s.spread = 0.5; - let p = program(&Effect::DropShadow(s), &light, false); - let region = Rect::new(-100, -100, 1000, 1000); - let d = Rect::new(0, 0, 10, 10); - let fr = |_| 5; - let w = p.windows(d, region, &fr); - let last = *w.last().unwrap(); - assert!(last.contains_rect(&d.inflate(7)), "{last:?}"); - // Earlier stages need at least as much as later ones read. - assert!(w[0].width() >= last.width()); - let (t, n) = p.temps(); - assert!(n <= 3, "{n} temporaries for {} stages", p.stages.len()); - assert!(t.last().unwrap().is_none()); - } - - /// A distance field computed in bands from grown windows equals the whole-region field - /// wherever it is within its reach (the property incremental updates rely on). - #[test] - fn banded_fields_match_whole_region_within_reach() { - let region = Rect::new(-20, -10, 300, 290); - let (w, h) = (region.width() as usize, region.height() as usize); - let mut shape = vec![0.0f32; w * h]; - for y in 0..h { - for x in 0..w { - let (fx, fy) = (x as f32 - 150.0, y as f32 - 140.0); - let r = (fx * fx + fy * fy).sqrt() + 8.0 * (fy * 0.07).sin() * (fx * 0.05).cos(); - shape[y * w + x] = (90.0 - r).clamp(0.0, 1.0) * if (x / 13 + y / 17) % 5 == 0 { 0.6 } else { 1.0 }; - } - } - for kind in [ - FieldKind::Outside, - FieldKind::Inside, - FieldKind::BevelOutside, - FieldKind::BevelInside, - FieldKind::ChokeInside, - FieldKind::StrokeOutside, - FieldKind::StrokeInside, - FieldKind::StrokeOutsideExact, - FieldKind::StrokeOutsideVector, - FieldKind::StrokeOutsideVectorChamfer, - ] { - let reach = 9; - let whole = photocraft_compose::effects::distance_field(kind, shape.clone(), w, h, reach as f32); - let banded = field(kind, reach, &shape, region, region); - let part = Rect::new(40, 30, 170, 120); - let partial = field(kind, reach, &shape, region, part); - for (i, (a, b)) in whole.iter().zip(&banded).enumerate() { - if a.min(*b) < reach as f32 { - assert!((a - b).abs() < 1e-5, "{kind:?} at {i}: {a} vs {b}"); - } - } - for (i, b) in partial.iter().enumerate() { - let (x, y) = (part.x0 + (i % part.width() as usize) as i32, part.y0 + (i / part.width() as usize) as i32); - let a = whole[(y - region.y0) as usize * w + (x - region.x0) as usize]; - if a.min(*b) < reach as f32 { - assert!((a - b).abs() < 1e-5, "{kind:?} at ({x},{y}): {a} vs {b}"); - } - } - } - } - #[test] - fn windowed_bevel_fields_match_whole_region_on_anti_aliased_edges() { - // The bevel fields read the edge pixels around the foot of the perpendicular and take the - // direction of each from its neighbours, so the halo of a part of the region has to cover all of - // that. A wide bar with clean anti-aliased edges (almost along the 128 row bands the other - // fields use, across them and at an angle) puts sharp edge pixels where bands would meet and - // inside the partial window. The whole region is one window, so it is exactly the CPU's field. - let region = Rect::new(-20, -10, 300, 290); - let (w, h) = (region.width() as usize, region.height() as usize); - let part = Rect::new(40, 30, 170, 120); - let mut too_small_noticed = false; - for deg in [1.5f32, 5.0, 30.0, 88.5] { - let (sn, cs) = deg.to_radians().sin_cos(); - let inside = |x: f32, y: f32| { - let (u, v) = ((x - 150.0) * cs + (y - 128.3) * sn, -(x - 150.0) * sn + (y - 128.3) * cs); - u.abs() <= 140.0 && v.abs() <= 60.0 - }; - let mut shape = vec![0.0f32; w * h]; - for y in 0..h { - for x in 0..w { - let hits = (0..64).filter(|k| inside(x as f32 + ((k % 8) as f32 + 0.5) / 8.0, y as f32 + ((k / 8) as f32 + 0.5) / 8.0)).count(); - shape[y * w + x] = hits as f32 / 64.0; - } - } - for reach in [9, 24] { - for kind in [FieldKind::BevelInside, FieldKind::BevelOutside] { - let whole = photocraft_compose::effects::distance_field(kind, shape.clone(), w, h, reach as f32); - let differs = |part_field: &[f32], out: Rect| { - let ow = out.width() as usize; - part_field - .iter() - .enumerate() - .filter(|&(i, b)| { - let (x, y) = (out.x0 + (i % ow) as i32, out.y0 + (i / ow) as i32); - let a = whole[(y - region.y0) as usize * w + (x - region.x0) as usize]; - a.min(*b) < reach as f32 && (a - b).abs() > 1e-5 - }) - .count() - }; - let all = field(kind, reach, &shape, region, region); - assert!( - all.iter().zip(&whole).all(|(a, b)| a.to_bits() == b.to_bits()), - "{kind:?}, {deg} deg, reach {reach}: the whole region is not the CPU's field" - ); - assert_eq!( - differs(&field(kind, reach, &shape, region, part), part), - 0, - "{kind:?}, {deg} deg, reach {reach}: partial window differs from whole" - ); - // The test can see a halo that is too small: two rows past the part is not enough. - too_small_noticed |= differs(&field_banded(kind, reach, &shape, region, part, 2), part) > 0; - } - } - } - assert!(too_small_noticed, "a 2 row halo went unnoticed, so this test guards nothing"); - } - - /// Both bevel fields from one window (sharp edges found once) are bit for bit the fields - /// computed one at a time, over the whole region and over a part of it. - #[test] - fn paired_bevel_fields_equal_the_fields_one_at_a_time() { - let region = Rect::new(-20, -10, 300, 290); - let (w, h) = (region.width() as usize, region.height() as usize); - let mut shape = vec![0.0f32; w * h]; - for y in 0..h { - for x in 0..w { - let (fx, fy) = (x as f32 - 150.0, y as f32 - 140.0); - let r = (fx * fx + fy * fy).sqrt() + 8.0 * (fy * 0.07).sin() * (fx * 0.05).cos(); - shape[y * w + x] = (90.0 - r).clamp(0.0, 1.0) * if (x / 13 + y / 17) % 5 == 0 { 0.6 } else { 1.0 }; - } - } - let bits = |v: &[f32]| v.iter().map(|x| x.to_bits()).collect::>(); - for reach in [3, 9, 40] { - for out in [region, Rect::new(40, 30, 170, 120), Rect::new(-20, 200, 300, 290)] { - let [inside, outside] = bevel_fields(reach, &shape, region, out); - assert_eq!(bits(&inside), bits(&field(FieldKind::BevelInside, reach, &shape, region, out)), "inside, reach {reach}, {out:?}"); - assert_eq!(bits(&outside), bits(&field(FieldKind::BevelOutside, reach, &shape, region, out)), "outside, reach {reach}, {out:?}"); - // The banded path (wasm) pairs them per band the same way. - let halo = field_radius(FieldKind::BevelInside, reach) + 1; - let banded = - fields_in_windows(false, &shape, region, out, halo, |s, w, h| photocraft_compose::effects::bevel_distance_fields(s, w, h, reach as f32)); - for (k, kind) in [FieldKind::BevelInside, FieldKind::BevelOutside].into_iter().enumerate() { - let [one] = fields_in_windows(false, &shape, region, out, halo, |s, w, h| { - [photocraft_compose::effects::distance_field(kind, s, w, h, reach as f32)] - }); - assert_eq!(bits(&banded[k]), bits(&one), "banded {kind:?}, reach {reach}, {out:?}"); - } - } - } - } - - /// #3646: a stroke's outer edge is the fitted 5 × 5 chamfer while it is narrow and the exact - /// Euclidean transform once it is wide — the chamfer's octagon facets a wide stroke. The GPU - /// builds it from the field its width picks (`stroke_outside_exact`), while the spread of drop - /// shadows and softer outer glows keeps the chamfer field (fitted to Photoshop, #224) — so - /// routing a wide stroke through the chamfer, or a shadow through the exact field, fails here. - #[test] - fn a_stroke_uses_the_chamfer_narrow_and_the_exact_field_wide() { - use photocraft_color::{BlendMode, Color}; - use photocraft_doc::{FxCommon, FxPaint, StrokeFx, StrokePosition}; - let light = GlobalLight::default(); - let stroke = |size, position| { - Effect::Stroke(StrokeFx { common: FxCommon::new(BlendMode::Normal, 1.0), size, position, paint: FxPaint::Color(Color::BLACK), overprint: false }) - }; - // Narrow (< STROKE_CHAMFER_MAX): the chamfer, exactly as before #3646. - let narrow = program(&stroke(6.0, StrokePosition::Outside), &light, false); - assert!(narrow.fields.iter().any(|(k, _)| *k == FieldKind::StrokeOutside), "a narrow raster outside stroke keeps the chamfer: {:?}", narrow.fields); - assert!(!narrow.fields.iter().any(|(k, _)| *k == FieldKind::StrokeOutsideExact), "…not the exact field: {:?}", narrow.fields); - // Wide: the exact transform. - let wide = program(&stroke(40.0, StrokePosition::Outside), &light, false); - assert!( - wide.fields.iter().any(|(k, _)| *k == FieldKind::StrokeOutsideExact), - "a wide raster outside stroke needs the exact outer field: {:?}", - wide.fields - ); - assert!(!wide.fields.iter().any(|(k, _)| *k == FieldKind::StrokeOutside), "…not the chamfer field: {:?}", wide.fields); - // A shape layer's outline stroke follows the same width rule; the inside edge keeps the chamfer. - let vector_narrow = program(&stroke(6.0, StrokePosition::Outside), &light, true); - assert!(vector_narrow.fields.iter().any(|(k, _)| *k == FieldKind::StrokeOutsideVectorChamfer), "{:?}", vector_narrow.fields); - let vector_wide = program(&stroke(40.0, StrokePosition::Outside), &light, true); - assert!(vector_wide.fields.iter().any(|(k, _)| *k == FieldKind::StrokeOutsideVector), "{:?}", vector_wide.fields); - let inner = program(&stroke(40.0, StrokePosition::Inside), &light, false); - assert!(inner.fields.iter().any(|(k, _)| *k == FieldKind::StrokeInside), "{:?}", inner.fields); - // The shadow / softer-glow spread is unchanged: still the chamfer. - let Effect::DropShadow(mut s) = Effect::default_drop_shadow() else { unreachable!() }; - s.spread = 0.5; - let shadow = program(&Effect::DropShadow(s), &light, false); - assert!(shadow.fields.iter().any(|(k, _)| *k == FieldKind::StrokeOutside), "the shadow spread keeps the chamfer: {:?}", shadow.fields); - } - - /// Cached shapes and group keys reserve tile addresses without keeping pixels (#4530): - /// damage still tells a replaced tile from an unchanged one, and a dropped tile's pixels - /// are freed although the entry remembers it. - #[test] - fn shape_tiles_and_group_pins_hold_addresses_not_pixels() { - use photocraft_color::{ColorMode, PixelFormat, SampleType}; - let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::U8, true); - let mut s = Surface::new(fmt); - // A ramp, so no two tiles share their pixels. - for x in 0..600 { - let v = x as f32 / 600.0; - s.fill_rect(Rect::new(x, 0, x + 1, 300), &[v, 0.2, 0.9, 1.0]); - } - let first = s.tiles().find(|(c, _)| c.tx == 0 && c.ty == 0).map(|(_, t)| t.clone()).unwrap(); - assert_eq!(Arc::strong_count(&first), 2); - let old = snapshot(&s); - assert_eq!(Arc::strong_count(&first), 2, "the snapshot adds no strong reference"); - assert!(damage(&old, &s).is_empty()); - s.fill_rect(Rect::new(0, 0, 4, 4), &[0.0, 0.0, 0.0, 1.0]); - let origin = s.tiles().map(|(c, _)| *c).find(|c| c.tx == 0 && c.ty == 0).unwrap(); - assert_eq!(damage(&old, &s), origin.rect(), "only the edited tile"); - drop(first); - assert!(old.values().any(|w| w.strong_count() == 0), "the replaced tile's pixels are freed"); - - let child = Layer::new("c", LayerContent::Raster(s)); - let n = child.surface().map_or(0, |s| s.tile_count()); - let group = Layer::group("g", vec![child]); - let mut pins = Vec::new(); - let key = group_key(&group, &GlobalLight::default(), &mut |t| pins.push(Arc::downgrade(t))); - assert_eq!(key, group_key(&group, &GlobalLight::default(), &mut |_| {}), "pinning doesn't change the key"); - assert_eq!(pins.len(), n); - drop(group); - assert!(pins.iter().all(|w| w.strong_count() == 0), "a group's pins keep none of its pixels"); - } -} +mod tests; diff --git a/crates/gpu/src/fx/tests.rs b/crates/gpu/src/fx/tests.rs new file mode 100644 index 0000000000..1622da28e2 --- /dev/null +++ b/crates/gpu/src/fx/tests.rs @@ -0,0 +1,310 @@ +use super::*; +use photocraft_color::BlendMode; +use photocraft_doc::FxCommon; + +/// Filled-shape identity survives integer moves, including fractional anchors and handles. +#[test] +fn filled_shape_key_preserves_translation_but_detects_deformation() { + use photocraft_doc::{Fill, Path, ShapeLayer, Subpath}; + let mut layer = Layer::new( + "shape", + LayerContent::Shape(ShapeLayer { + path: Path::new(vec![Subpath::polygon(&[(20.0, 20.0), (70.0, 20.0), (70.0, 60.0), (20.0, 60.0)])]), + fill: Some(Fill::Solid(photocraft_color::Color::WHITE)), + ..Default::default() + }), + ); + let canvas = Rect::new(0, 0, 200, 200); + let before = shape_key(&layer, canvas); + let LayerContent::Shape(shape) = &mut layer.content else { unreachable!() }; + shape.path = shape.path.transform(&photocraft_geom::Affine::translate(13.0, 7.0)); + assert_eq!(before, shape_key(&layer, canvas)); + let LayerContent::Shape(shape) = &mut layer.content else { unreachable!() }; + shape.path.subpaths[0].knots[1].anchor.x += 3.0; + assert_ne!(before, shape_key(&layer, canvas)); + + let LayerContent::Shape(shape) = &mut layer.content else { unreachable!() }; + shape.path = Path::new(vec![Subpath::polygon(&[(0.1, 0.2), (0.3, 0.2), (0.3, 1.7), (0.1, 1.7)])]); + shape.path.subpaths[0].knots[1].out_ctrl = photocraft_geom::Point::new(0.45, 0.65); + let original = shape.path.clone(); + let before = shape_key(&layer, canvas); + for (dx, dy) in [(1.0, 1.0), (-13.0, 7.0), (100_000.0, -100_000.0)] { + let LayerContent::Shape(shape) = &mut layer.content else { unreachable!() }; + shape.path = original.transform(&photocraft_geom::Affine::translate(dx, dy)); + assert_eq!(before, shape_key(&layer, canvas), "fractional path translated by {dx}, {dy}"); + } + let LayerContent::Shape(shape) = &mut layer.content else { unreachable!() }; + shape.path.subpaths[0].knots[1].out_ctrl.x += 0.01; + assert_ne!(before, shape_key(&layer, canvas), "a handle deformation invalidates the key"); +} + +#[test] +fn programs_key_on_geometry_not_colour() { + let light = GlobalLight::default(); + let Effect::DropShadow(mut s) = Effect::default_drop_shadow() else { unreachable!() }; + let a = program(&Effect::DropShadow(s.clone()), &light, false); + s.color = photocraft_color::Color::rgb(1.0, 0.0, 0.0); + s.common = FxCommon::new(BlendMode::Screen, 0.3); + let b = program(&Effect::DropShadow(s.clone()), &light, false); + assert_eq!(a.key, b.key); + s.size += 1.0; + assert_ne!(a.key, program(&Effect::DropShadow(s), &light, false).key); +} + +/// A styled group's effect shape follows its own vector mask and its children's Blend If and +/// Advanced Blending, so the cached shape must be rebuilt when any of them changes. +#[test] +fn group_key_follows_vector_mask_blend_if_and_advanced() { + use photocraft_doc::{BlendRange, Knockout, Path, PixelFormat, Subpath, VectorMask}; + let light = GlobalLight::default(); + let group = Layer::group("g", vec![Layer::raster("child", PixelFormat::RGBA8)]); + let base = group_key(&group, &light, &mut |_| {}); + + let mask = |x: f64| VectorMask::new(Path::new(vec![Subpath::polygon(&[(x, 0.0), (x + 10.0, 0.0), (x + 10.0, 10.0)])])); + let mut masked = group.clone(); + masked.vector_mask = Some(mask(0.0)); + let with_mask = group_key(&masked, &light, &mut |_| {}); + assert_ne!(base, with_mask, "adding the group's vector mask"); + masked.vector_mask = Some(mask(5.0)); + assert_ne!(with_mask, group_key(&masked, &light, &mut |_| {}), "moving the group's vector mask"); + + fn child_mut(g: &mut Layer) -> &mut Layer { + let LayerContent::Group(gr) = &mut g.content else { unreachable!() }; + &mut gr.children[0] + } + let mut blend_if = group.clone(); + child_mut(&mut blend_if).blend_if.ranges = vec![[BlendRange { black: [128, 128], white: [255, 255] }, BlendRange::FULL]]; + assert_ne!(base, group_key(&blend_if, &light, &mut |_| {}), "a child's Blend If"); + + let mut advanced = group.clone(); + child_mut(&mut advanced).advanced.knockout = Knockout::Deep; + assert_ne!(base, group_key(&advanced, &light, &mut |_| {}), "a child's Advanced Blending"); +} + +#[test] +fn windows_grow_by_reach_and_temps_are_reused() { + let light = GlobalLight::default(); + let Effect::DropShadow(mut s) = Effect::default_drop_shadow() else { unreachable!() }; + s.spread = 0.5; + let p = program(&Effect::DropShadow(s), &light, false); + let region = Rect::new(-100, -100, 1000, 1000); + let d = Rect::new(0, 0, 10, 10); + let fr = |_| 5; + let w = p.windows(d, region, &fr); + let last = *w.last().unwrap(); + assert!(last.contains_rect(&d.inflate(7)), "{last:?}"); + // Earlier stages need at least as much as later ones read. + assert!(w[0].width() >= last.width()); + let (t, n) = p.temps(); + assert!(n <= 3, "{n} temporaries for {} stages", p.stages.len()); + assert!(t.last().unwrap().is_none()); +} + +/// A distance field computed in bands from grown windows equals the whole-region field +/// wherever it is within its reach (the property incremental updates rely on). +#[test] +fn banded_fields_match_whole_region_within_reach() { + let region = Rect::new(-20, -10, 300, 290); + let (w, h) = (region.width() as usize, region.height() as usize); + let mut shape = vec![0.0f32; w * h]; + for y in 0..h { + for x in 0..w { + let (fx, fy) = (x as f32 - 150.0, y as f32 - 140.0); + let r = (fx * fx + fy * fy).sqrt() + 8.0 * (fy * 0.07).sin() * (fx * 0.05).cos(); + shape[y * w + x] = (90.0 - r).clamp(0.0, 1.0) * if (x / 13 + y / 17) % 5 == 0 { 0.6 } else { 1.0 }; + } + } + for kind in [ + FieldKind::Outside, + FieldKind::Inside, + FieldKind::BevelOutside, + FieldKind::BevelInside, + FieldKind::ChokeInside, + FieldKind::StrokeOutside, + FieldKind::StrokeInside, + FieldKind::StrokeOutsideExact, + FieldKind::StrokeOutsideVector, + FieldKind::StrokeOutsideVectorChamfer, + ] { + let reach = 9; + let whole = photocraft_compose::effects::distance_field(kind, shape.clone(), w, h, reach as f32); + let banded = field(kind, reach, &shape, region, region); + let part = Rect::new(40, 30, 170, 120); + let partial = field(kind, reach, &shape, region, part); + for (i, (a, b)) in whole.iter().zip(&banded).enumerate() { + if a.min(*b) < reach as f32 { + assert!((a - b).abs() < 1e-5, "{kind:?} at {i}: {a} vs {b}"); + } + } + for (i, b) in partial.iter().enumerate() { + let (x, y) = (part.x0 + (i % part.width() as usize) as i32, part.y0 + (i / part.width() as usize) as i32); + let a = whole[(y - region.y0) as usize * w + (x - region.x0) as usize]; + if a.min(*b) < reach as f32 { + assert!((a - b).abs() < 1e-5, "{kind:?} at ({x},{y}): {a} vs {b}"); + } + } + } +} +#[test] +fn windowed_bevel_fields_match_whole_region_on_anti_aliased_edges() { + // The bevel fields read the edge pixels around the foot of the perpendicular and take the + // direction of each from its neighbours, so the halo of a part of the region has to cover all of + // that. A wide bar with clean anti-aliased edges (almost along the 128 row bands the other + // fields use, across them and at an angle) puts sharp edge pixels where bands would meet and + // inside the partial window. The whole region is one window, so it is exactly the CPU's field. + let region = Rect::new(-20, -10, 300, 290); + let (w, h) = (region.width() as usize, region.height() as usize); + let part = Rect::new(40, 30, 170, 120); + let mut too_small_noticed = false; + for deg in [1.5f32, 5.0, 30.0, 88.5] { + let (sn, cs) = deg.to_radians().sin_cos(); + let inside = |x: f32, y: f32| { + let (u, v) = ((x - 150.0) * cs + (y - 128.3) * sn, -(x - 150.0) * sn + (y - 128.3) * cs); + u.abs() <= 140.0 && v.abs() <= 60.0 + }; + let mut shape = vec![0.0f32; w * h]; + for y in 0..h { + for x in 0..w { + let hits = (0..64).filter(|k| inside(x as f32 + ((k % 8) as f32 + 0.5) / 8.0, y as f32 + ((k / 8) as f32 + 0.5) / 8.0)).count(); + shape[y * w + x] = hits as f32 / 64.0; + } + } + for reach in [9, 24] { + for kind in [FieldKind::BevelInside, FieldKind::BevelOutside] { + let whole = photocraft_compose::effects::distance_field(kind, shape.clone(), w, h, reach as f32); + let differs = |part_field: &[f32], out: Rect| { + let ow = out.width() as usize; + part_field + .iter() + .enumerate() + .filter(|&(i, b)| { + let (x, y) = (out.x0 + (i % ow) as i32, out.y0 + (i / ow) as i32); + let a = whole[(y - region.y0) as usize * w + (x - region.x0) as usize]; + a.min(*b) < reach as f32 && (a - b).abs() > 1e-5 + }) + .count() + }; + let all = field(kind, reach, &shape, region, region); + assert!( + all.iter().zip(&whole).all(|(a, b)| a.to_bits() == b.to_bits()), + "{kind:?}, {deg} deg, reach {reach}: the whole region is not the CPU's field" + ); + assert_eq!( + differs(&field(kind, reach, &shape, region, part), part), + 0, + "{kind:?}, {deg} deg, reach {reach}: partial window differs from whole" + ); + // The test can see a halo that is too small: two rows past the part is not enough. + too_small_noticed |= differs(&field_banded(kind, reach, &shape, region, part, 2), part) > 0; + } + } + } + assert!(too_small_noticed, "a 2 row halo went unnoticed, so this test guards nothing"); +} + +/// Both bevel fields from one window (sharp edges found once) are bit for bit the fields +/// computed one at a time, over the whole region and over a part of it. +#[test] +fn paired_bevel_fields_equal_the_fields_one_at_a_time() { + let region = Rect::new(-20, -10, 300, 290); + let (w, h) = (region.width() as usize, region.height() as usize); + let mut shape = vec![0.0f32; w * h]; + for y in 0..h { + for x in 0..w { + let (fx, fy) = (x as f32 - 150.0, y as f32 - 140.0); + let r = (fx * fx + fy * fy).sqrt() + 8.0 * (fy * 0.07).sin() * (fx * 0.05).cos(); + shape[y * w + x] = (90.0 - r).clamp(0.0, 1.0) * if (x / 13 + y / 17) % 5 == 0 { 0.6 } else { 1.0 }; + } + } + let bits = |v: &[f32]| v.iter().map(|x| x.to_bits()).collect::>(); + for reach in [3, 9, 40] { + for out in [region, Rect::new(40, 30, 170, 120), Rect::new(-20, 200, 300, 290)] { + let [inside, outside] = bevel_fields(reach, &shape, region, out); + assert_eq!(bits(&inside), bits(&field(FieldKind::BevelInside, reach, &shape, region, out)), "inside, reach {reach}, {out:?}"); + assert_eq!(bits(&outside), bits(&field(FieldKind::BevelOutside, reach, &shape, region, out)), "outside, reach {reach}, {out:?}"); + // The banded path (wasm) pairs them per band the same way. + let halo = field_radius(FieldKind::BevelInside, reach) + 1; + let banded = + fields_in_windows(false, &shape, region, out, halo, |s, w, h| photocraft_compose::effects::bevel_distance_fields(s, w, h, reach as f32)); + for (k, kind) in [FieldKind::BevelInside, FieldKind::BevelOutside].into_iter().enumerate() { + let [one] = + fields_in_windows(false, &shape, region, out, halo, |s, w, h| [photocraft_compose::effects::distance_field(kind, s, w, h, reach as f32)]); + assert_eq!(bits(&banded[k]), bits(&one), "banded {kind:?}, reach {reach}, {out:?}"); + } + } + } +} + +/// #3646: a stroke's outer edge is the fitted 5 × 5 chamfer while it is narrow and the exact +/// Euclidean transform once it is wide — the chamfer's octagon facets a wide stroke. The GPU +/// builds it from the field its width picks (`stroke_outside_exact`), while the spread of drop +/// shadows and softer outer glows keeps the chamfer field (fitted to Photoshop, #224) — so +/// routing a wide stroke through the chamfer, or a shadow through the exact field, fails here. +#[test] +fn a_stroke_uses_the_chamfer_narrow_and_the_exact_field_wide() { + use photocraft_color::{BlendMode, Color}; + use photocraft_doc::{FxCommon, FxPaint, StrokeFx, StrokePosition}; + let light = GlobalLight::default(); + let stroke = |size, position| { + Effect::Stroke(StrokeFx { common: FxCommon::new(BlendMode::Normal, 1.0), size, position, paint: FxPaint::Color(Color::BLACK), overprint: false }) + }; + // Narrow (< STROKE_CHAMFER_MAX): the chamfer, exactly as before #3646. + let narrow = program(&stroke(6.0, StrokePosition::Outside), &light, false); + assert!(narrow.fields.iter().any(|(k, _)| *k == FieldKind::StrokeOutside), "a narrow raster outside stroke keeps the chamfer: {:?}", narrow.fields); + assert!(!narrow.fields.iter().any(|(k, _)| *k == FieldKind::StrokeOutsideExact), "…not the exact field: {:?}", narrow.fields); + // Wide: the exact transform. + let wide = program(&stroke(40.0, StrokePosition::Outside), &light, false); + assert!( + wide.fields.iter().any(|(k, _)| *k == FieldKind::StrokeOutsideExact), + "a wide raster outside stroke needs the exact outer field: {:?}", + wide.fields + ); + assert!(!wide.fields.iter().any(|(k, _)| *k == FieldKind::StrokeOutside), "…not the chamfer field: {:?}", wide.fields); + // A shape layer's outline stroke follows the same width rule; the inside edge keeps the chamfer. + let vector_narrow = program(&stroke(6.0, StrokePosition::Outside), &light, true); + assert!(vector_narrow.fields.iter().any(|(k, _)| *k == FieldKind::StrokeOutsideVectorChamfer), "{:?}", vector_narrow.fields); + let vector_wide = program(&stroke(40.0, StrokePosition::Outside), &light, true); + assert!(vector_wide.fields.iter().any(|(k, _)| *k == FieldKind::StrokeOutsideVector), "{:?}", vector_wide.fields); + let inner = program(&stroke(40.0, StrokePosition::Inside), &light, false); + assert!(inner.fields.iter().any(|(k, _)| *k == FieldKind::StrokeInside), "{:?}", inner.fields); + // The shadow / softer-glow spread is unchanged: still the chamfer. + let Effect::DropShadow(mut s) = Effect::default_drop_shadow() else { unreachable!() }; + s.spread = 0.5; + let shadow = program(&Effect::DropShadow(s), &light, false); + assert!(shadow.fields.iter().any(|(k, _)| *k == FieldKind::StrokeOutside), "the shadow spread keeps the chamfer: {:?}", shadow.fields); +} + +/// Cached shapes and group keys reserve tile addresses without keeping pixels (#4530): +/// damage still tells a replaced tile from an unchanged one, and a dropped tile's pixels +/// are freed although the entry remembers it. +#[test] +fn shape_tiles_and_group_pins_hold_addresses_not_pixels() { + use photocraft_color::{ColorMode, PixelFormat, SampleType}; + let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::U8, true); + let mut s = Surface::new(fmt); + // A ramp, so no two tiles share their pixels. + for x in 0..600 { + let v = x as f32 / 600.0; + s.fill_rect(Rect::new(x, 0, x + 1, 300), &[v, 0.2, 0.9, 1.0]); + } + let first = s.tiles().find(|(c, _)| c.tx == 0 && c.ty == 0).map(|(_, t)| t.clone()).unwrap(); + assert_eq!(Arc::strong_count(&first), 2); + let old = snapshot(&s); + assert_eq!(Arc::strong_count(&first), 2, "the snapshot adds no strong reference"); + assert!(damage(&old, &s).is_empty()); + s.fill_rect(Rect::new(0, 0, 4, 4), &[0.0, 0.0, 0.0, 1.0]); + let origin = s.tiles().map(|(c, _)| *c).find(|c| c.tx == 0 && c.ty == 0).unwrap(); + assert_eq!(damage(&old, &s), origin.rect(), "only the edited tile"); + drop(first); + assert!(old.values().any(|w| w.strong_count() == 0), "the replaced tile's pixels are freed"); + + let child = Layer::new("c", LayerContent::Raster(s)); + let n = child.surface().map_or(0, |s| s.tile_count()); + let group = Layer::group("g", vec![child]); + let mut pins = Vec::new(); + let key = group_key(&group, &GlobalLight::default(), &mut |t| pins.push(Arc::downgrade(t))); + assert_eq!(key, group_key(&group, &GlobalLight::default(), &mut |_| {}), "pinning doesn't change the key"); + assert_eq!(pins.len(), n); + drop(group); + assert!(pins.iter().all(|w| w.strong_count() == 0), "a group's pins keep none of its pixels"); +} diff --git a/crates/gpu/src/fx_passes.rs b/crates/gpu/src/fx_passes.rs new file mode 100644 index 0000000000..a549979f63 --- /dev/null +++ b/crates/gpu/src/fx_passes.rs @@ -0,0 +1,268 @@ +use super::batch::op_words; +use super::consts::{MAP16, MAP32}; +use super::kit::MapDraw; +use super::paging::field_reaches; +use super::textures::{FxEntry, FxKey, ProgState, Stats, Tex}; +use super::*; + +impl Compositor { + /// Build or update the effect maps of one layer over `region`: its whole effect region, or + /// the window of one page cell (`key.1`) grown by the effects' reach. + #[allow(clippy::too_many_arguments)] + pub(crate) fn sync_fx( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + encoder: &mut wgpu::CommandEncoder, + doc: &Document, + f: &plan::FxLayer<'_>, + key: FxKey, + region: Rect, + stats: &mut Stats, + ) -> Result<(), Unsupported> { + let layer = f.layer; + let canvas = doc.bounds(); + let is_group = matches!(layer.content, LayerContent::Group(_)); + let shape_key = if is_group { fx::group_key(layer, &doc.global_light, &mut |_| {}) } else { fx::shape_key(layer, canvas) }; + let (content_src, mask_src) = if is_group { (None, None) } else { fx::shape_sources(layer) }; + let frame = self.frame; + let (rw, rh) = (region.width(), region.height()); + + // What changed: everything (new settings / size), the position only, some tiles, or + // nothing. + let mut damage = Rect::EMPTY; + let prev = self.fx.get(&key).filter(|e| e.shape_key == shape_key).map(|e| e.region); + let mut rebuild = true; + if prev == Some(region) + && let Some(e) = self.fx.get(&key) + { + rebuild = false; + for (old, cur) in e.tiles.iter().zip([content_src, mask_src]) { + let d = match (old, cur) { + (Some(o), Some(s)) => fx::damage(o, s), + (None, None) => Rect::EMPTY, + // A source appeared or vanished (the key changes with it too). + _ => region, + }; + damage = if damage.is_empty() { d } else { damage.union(&d) }; + } + damage = damage.intersect(®ion); + } else if let Some(old) = prev + && (old.width(), old.height()) == (rw, rh) + && !region.is_empty() + { + // Moved by whole pixels: maps are computed relative to the region, so if the shape + // moved unchanged with it, every map is still exact. + let v = fx::shape(doc, layer, region); + if let Some(e) = self.fx.get_mut(&key) + && v == e.shape_cpu + { + e.region = region; + rebuild = false; + } + } + if rebuild { + let shape = Tex::map(device, "pc_fx_shape", region, MAP32); + let n = rw as usize * rh as usize; + self.fx.insert( + key, + FxEntry { + doc: doc.id, + region, + shape_key, + tiles: [None, None], + _pin: if is_group { + let mut pin = Vec::new(); + fx::group_key(layer, &doc.global_light, &mut |t| pin.push(Arc::downgrade(t))); + pin + } else { + Vec::new() + }, + shape_cpu: vec![0.0; n], + shape, + fields: HashMap::new(), + progs: Vec::new(), + last_used: frame, + stamp: 0, + }, + ); + damage = region; + } + // Present: kept or (re)inserted above. + let stamp = self.stamp; + let Some(e) = self.fx.get_mut(&key) else { return Ok(()) }; + e.last_used = frame; + e.stamp = stamp; + e.doc = doc.id; + e.tiles = [content_src.map(fx::snapshot), mask_src.map(fx::snapshot)]; + if region.is_empty() { + return Ok(()); + } + + let t_trace = web_time_now(); + let mut staged = 0u64; + // Shape over the damage (compose's own alpha). + if !damage.is_empty() { + stats.fx_shapes += 1; + let v = fx::shape(doc, layer, damage); + fx::paste(&mut e.shape_cpu, region, damage, &v); + e.shape.write_r32(queue, region, damage, &v); + staged += v.len() as u64 * 4; + } + + // Programs, and the distance fields they read (max reach per field). + // Filled shapes stroke their outline (the effect shape); others estimate it. + let vector_shape = matches!(layer.content, LayerContent::Shape(_)) && photocraft_compose::effect_outline(layer).is_none(); + let anchor = layer.effects.reference.unwrap_or((f64::from(f.bounds.x0), f64::from(f.bounds.y0))); + let progs: Vec = + layer.effects.items.iter().filter(|e| e.enabled()).map(|e| fx::program_with(e, &doc.global_light, vector_shape, &doc.patterns, anchor)).collect(); + let want = field_reaches(&progs); + e.fields.retain(|k, _| want.contains_key(k)); + // Each field to recompute: over which rectangle, exact up to which reach. + let jobs: Vec<(FieldKind, Rect, i32)> = want + .iter() + .filter_map(|(&kind, &reach)| match e.fields.get(&kind).map(|(r, _)| *r) { + Some(r) if r >= reach => (!damage.is_empty()).then(|| (kind, damage.inflate(fx::field_radius(kind, r)).intersect(®ion), r)), + _ => Some((kind, region, reach)), + }) + .collect(); + // A chiselled bevel's two fields are asked for and kept together (`fx::bevel_fields`), so they + // are recomputed together, over one rectangle at one reach. + let job = |k: FieldKind| jobs.iter().find(|j| j.0 == k).map(|j| (j.1, j.2)); + let (bevel_in, bevel_out) = (job(FieldKind::BevelInside), job(FieldKind::BevelOutside)); + if bevel_in != bevel_out { + return Err(Unsupported(format!("bevel fields of `{}` out of step: inside {bevel_in:?}, outside {bevel_out:?}", layer.name))); + } + for (kind, out, reach) in jobs { + let fields = match kind { + FieldKind::BevelInside => { + let [inside, outside] = fx::bevel_fields(reach, &e.shape_cpu, region, out); + vec![(FieldKind::BevelInside, inside), (FieldKind::BevelOutside, outside)] + } + // Computed with BevelInside, over the same rectangle at the same reach (checked above). + FieldKind::BevelOutside => continue, + _ => vec![(kind, fx::field(kind, reach, &e.shape_cpu, region, out))], + }; + for (kind, v) in fields { + if e.fields.get(&kind).is_none_or(|(r, _)| *r < reach) { + e.fields.insert(kind, (reach, Tex::map(device, "pc_fx_field", region, MAP32))); + } + if let Some((_, t)) = e.fields.get(&kind) { + t.write_r32(queue, region, out, &v); + } + staged += v.len() as u64 * 4; + stats.fx_pixels += out.width() as u64 * out.height() as u64; + } + } + + if let Some(t) = t_trace.filter(|_| !damage.is_empty()) { + eprintln!("effect maps of `{}`: shape + distance fields over {damage:?} in {:.2} ms (CPU)", layer.name, t.elapsed().as_secs_f64() * 1000.0); + } + e.progs.truncate(progs.len()); + while e.progs.len() < progs.len() { + e.progs.push(ProgState { key: 0, maps: Vec::new() }); + } + self.staged += staged; + for (i, prog) in progs.iter().enumerate() { + if prog.maps == 0 { + continue; + } + let Some(e) = self.fx.get_mut(&key) else { return Ok(()) }; + let same = e.progs[i].key == prog.key && e.progs[i].maps.len() == prog.maps; + let d = if same { damage } else { region }; + if d.is_empty() { + continue; + } + if !same { + e.progs[i] = ProgState { + key: prog.key, + maps: (0..prog.maps).map(|k| prog.stages.iter().any(|s| s.out == Some(k)).then(|| Tex::map(device, "pc_fx_map", region, MAP16))).collect(), + }; + } + stats.fx_programs += 1; + self.run_program(device, queue, encoder, key, i, prog, d, stats); + } + Ok(()) + } + + /// Record the passes of `prog` (maps of item `item` of `layer`) recomputing damage `d`. + #[allow(clippy::too_many_arguments)] + fn run_program( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + encoder: &mut wgpu::CommandEncoder, + key: FxKey, + item: usize, + prog: &fx::MapProgram, + d: Rect, + stats: &mut Stats, + ) { + let pattern_views: Vec> = + prog.stages.iter().map(|s| s.pattern.as_ref().map(|p| self.pattern_view(device, queue, p))).collect(); + let Some(e) = self.fx.get(&key) else { return }; + let region = e.region; + let shape = e.shape.view.clone(); + let finals: Vec> = e.progs[item].maps.iter().map(|m| m.as_ref().map(|t| t.view.clone())).collect(); + let fields: HashMap = e.fields.iter().map(|(k, (r, t))| (*k, (*r, t.view.clone()))).collect(); + let windows = prog.windows(d, region, &|k| fields.get(&k).map_or(0, |f| f.0)); + let (assign, count) = prog.temps(); + let mut temps: Vec = Vec::with_capacity(count); + for _ in 0..count { + let v = self.temp(device, region, &temps); + temps.push(v); + } + // `None` only if a program's map or temporary wasn't allocated, which `sync_fx` and + // `MapProgram::temps` rule out. + let target_of = |i: usize| -> Option<(wgpu::TextureView, wgpu::TextureFormat)> { + match prog.stages[i].out { + Some(k) => Some((finals.get(k)?.clone()?, MAP16)), + None => Some((temps.get((*assign.get(i)?)?)?.clone(), MAP32)), + } + }; + let view_of = |inp: Option| -> Option { + match inp? { + fx::In::Shape => Some(shape.clone()), + fx::In::Field(k) => fields.get(&k).map(|f| f.1.clone()), + fx::In::Val(k) => target_of(k).map(|t| t.0), + } + }; + let mut draws = Vec::with_capacity(prog.stages.len()); + for (i, s) in prog.stages.iter().enumerate() { + let w = windows[i]; + if w.is_empty() { + continue; + } + stats.fx_pixels += w.width() as u64 * w.height() as u64; + let Some((target, format)) = target_of(i) else { continue }; + let mut p = plan::Pass::new(s.kernel, 0); + p.params[0] = s.p0; + p.params[1] = s.p1; + p.params[3] = s.p3; + p.extra = s.p4; + draws.push(MapDraw { + kernel: s.kernel, + format, + target, + scissor: [(w.x0 - region.x0) as u32, (w.y0 - region.y0) as u32, w.width(), w.height()], + space: [region.x0, region.y0, region.width() as i32, region.height() as i32], + op: op_words(&p, None, None, None), + views: [view_of(s.a), view_of(s.b), view_of(s.s), None, None, None, None, pattern_views[i].clone()], + lut: s.lut.clone(), + }); + } + self.kit.run(device, queue, encoder, &draws); + } +} + +/// A start time when `PHOTOCRAFT_FX_TRACE=1` (it prints the CPU time of effect shapes and +/// distance fields); never on wasm. +fn web_time_now() -> Option { + #[cfg(not(target_arch = "wasm32"))] + { + static T: std::sync::OnceLock = std::sync::OnceLock::new(); + T.get_or_init(|| std::env::var_os("PHOTOCRAFT_FX_TRACE").is_some()).then(std::time::Instant::now) + } + #[cfg(target_arch = "wasm32")] + None +} diff --git a/crates/gpu/src/kit.rs b/crates/gpu/src/kit.rs new file mode 100644 index 0000000000..2de048a2e2 --- /dev/null +++ b/crates/gpu/src/kit.rs @@ -0,0 +1,144 @@ +use super::consts::{CHUNK_UNIFORM, OP_UNIFORM, STRIDE}; +use super::convert::{lut_texture, words}; +use super::textures::{ResKey, ResidentRef}; +use super::*; + +/// Pipelines and layouts, shared by cheap clones (wgpu handles are reference counted). +#[derive(Clone)] +pub(crate) struct Kit { + pub(crate) pipelines: HashMap<(Kernel, wgpu::TextureFormat), wgpu::RenderPipeline>, + pub(crate) bgl0: wgpu::BindGroupLayout, + pub(crate) bgl1: wgpu::BindGroupLayout, + pub(crate) dummy: wgpu::TextureView, +} + +/// One draw of an effect-map kernel (outside the chunk loop). +pub(crate) struct MapDraw { + pub(crate) kernel: Kernel, + pub(crate) format: wgpu::TextureFormat, + pub(crate) target: wgpu::TextureView, + /// Target-local scissor (x, y, w, h). + pub(crate) scissor: [u32; 4], + /// Chunk record: origin and size of the target's space. + pub(crate) space: [i32; 4], + pub(crate) op: Vec, + pub(crate) views: [Option; 8], + pub(crate) lut: Option>>, +} + +impl Kit { + /// Record `draws` (each its own render pass) into `encoder`. + pub(crate) fn run(&self, device: &wgpu::Device, queue: &wgpu::Queue, encoder: &mut wgpu::CommandEncoder, draws: &[MapDraw]) { + if draws.is_empty() { + return; + } + let mut data = vec![0u8; draws.len() * 2 * STRIDE as usize]; + for (i, d) in draws.iter().enumerate() { + let w = words(&[I(d.space[0]), I(d.space[1]), I(d.space[2]), I(d.space[3])]); + data[2 * i * STRIDE as usize..][..w.len()].copy_from_slice(&w); + data[(2 * i + 1) * STRIDE as usize..][..d.op.len()].copy_from_slice(&d.op); + } + let ubuf = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("pc_fx_uniforms"), + size: data.len() as u64, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + queue.write_buffer(&ubuf, 0, &data); + let bg0 = uniform_group(device, &self.bgl0, &ubuf); + for (i, d) in draws.iter().enumerate() { + let lut = d.lut.as_ref().map(|l| { + let mut row = [0.0f32; 4096]; + row[..l.len().min(4096)].copy_from_slice(&l[..l.len().min(4096)]); + lut_texture(device, queue, &[row]) + }); + let mut views: Vec<&wgpu::TextureView> = d.views.iter().map(|v| v.as_ref().unwrap_or(&self.dummy)).collect(); + if let Some((_, lv)) = &lut { + views[4] = lv; + } + let bg1 = texture_group(device, &self.bgl1, &views); + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("pc_fx_map"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &d.target, + resolve_target: None, + depth_slice: None, + ops: wgpu::Operations { load: wgpu::LoadOp::Load, store: wgpu::StoreOp::Store }, + })], + depth_stencil_attachment: None, + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); + pass.set_pipeline(&self.pipelines[&(d.kernel, d.format)]); + pass.set_scissor_rect(d.scissor[0], d.scissor[1], d.scissor[2], d.scissor[3]); + pass.set_bind_group(0, &bg0, &[(2 * i as u64 * STRIDE) as u32, ((2 * i + 1) as u64 * STRIDE) as u32]); + pass.set_bind_group(1, &bg1, &[]); + pass.draw(0..3, 0..1); + } + } +} + +pub(crate) fn uniform_group(device: &wgpu::Device, layout: &wgpu::BindGroupLayout, ubuf: &wgpu::Buffer) -> wgpu::BindGroup { + device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("pc_compose_uniforms"), + layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { buffer: ubuf, offset: 0, size: NonZeroU64::new(CHUNK_UNIFORM) }), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { buffer: ubuf, offset: 0, size: NonZeroU64::new(OP_UNIFORM) }), + }, + ], + }) +} + +pub(crate) fn texture_group(device: &wgpu::Device, layout: &wgpu::BindGroupLayout, views: &[&wgpu::TextureView]) -> wgpu::BindGroup { + let e: Vec = + views.iter().enumerate().map(|(b, v)| wgpu::BindGroupEntry { binding: b as u32, resource: wgpu::BindingResource::TextureView(v) }).collect(); + device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("pc_compose_pass"), layout, entries: &e }) +} + +pub(crate) fn tex_entry(binding: u32) -> wgpu::BindGroupLayoutEntry { + wgpu::BindGroupLayoutEntry { + binding, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + multisampled: false, + sample_type: wgpu::TextureSampleType::Float { filterable: false }, + view_dimension: wgpu::TextureViewDimension::D2, + }, + count: None, + } +} + +pub(crate) fn uniform_entry(binding: u32, size: u64) -> wgpu::BindGroupLayoutEntry { + wgpu::BindGroupLayoutEntry { + binding, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: true, min_binding_size: NonZeroU64::new(size) }, + count: None, + } +} + +/// The compositor's WGSL source (exposed for validation in tests). +pub const SHADER: &str = include_str!("compose.wgsl"); + +/// Pass-level resources resolved for one page cell: resident pages (texture, mask) and effect +/// maps (view and region) per pass. +pub(crate) struct Bound { + pub(crate) views: Vec<(Option, Option)>, + pub(crate) keys: Vec, + pub(crate) maps: Vec>, +} + +/// Pass-level resources shared by every cell of a frame. +pub(crate) struct FrameRes { + /// Tile area of each pass's (texture, mask) surface within the canvas tile grid. + pub(crate) areas: Vec<(Rect, Rect)>, + pub(crate) luts: Vec>, + pub(crate) patterns: Vec>, +} diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs index 7770662b15..6fd8c13439 100644 --- a/crates/gpu/src/lib.rs +++ b/crates/gpu/src/lib.rs @@ -63,388 +63,6 @@ pub use health::{DeviceHealth, Fault}; pub use plan::{Kernel, Plan, Role, Unsupported, plan}; pub use timing::{GpuTimer, GpuTiming}; -/// Accumulator format for intermediate buffers. Full float: discontinuous operations -/// (Posterize, Threshold, Hard Mix, Dissolve) must land on the same side of their thresholds as -/// the CPU reference, and Color Burn/Dodge amplify input error. -pub const ACC_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba32Float; // default accumulation format; `preferred_acc_format` downgrades to Rgba16Float where 32-bit float isn't renderable -/// Effect intermediates (distances, blurs) and layer shapes. -const MAP32: wgpu::TextureFormat = wgpu::TextureFormat::R32Float; -/// Final effect coverage maps (0..1; half precision is ~1/4000). -const MAP16: wgpu::TextureFormat = wgpu::TextureFormat::R16Float; -/// Side of the square chunks the canvas is processed in. -pub const CHUNK: u32 = 1024; -const STRIDE: u64 = 256; -const CHUNK_UNIFORM: u64 = 16; -const OP_UNIFORM: u64 = 256; -/// GPU memory the effect-map cache may hold before evicting layers not drawn this frame. -pub const FX_BUDGET: usize = 1536 << 20; -/// Largest side of the square pages layer surfaces are stored in on the GPU (smaller when the -/// device's texture limit is). A chunk only binds the pages of the cell it lies in, so layers of -/// any size composite on the GPU. -pub const PAGE: u32 = 2048; -/// GPU memory resident layer pages may hold before the least recently used are evicted. -pub const RESIDENT_BUDGET: u64 = 4 << 30; -/// GPU memory pattern textures may hold before the least recently painted are dropped (those the -/// current frame paints with always stay). -pub const PATTERN_BUDGET: u64 = 256 << 20; -/// A pattern texture no frame has painted with for this many frames is dropped. -pub const PATTERN_IDLE_FRAMES: u64 = 240; -/// Uploads (bytes) [`Compositor::render`] stages before submitting the work recorded so far, so -/// a refresh of a huge document never holds all its uploads in staging memory at once. -const FLUSH_BYTES: u64 = 512 << 20; -/// Pass pixels (chunk pixels × passes) [`Compositor::render`] records before submitting: one -/// command buffer holding a whole huge refresh can run for seconds, long enough for the OS to -/// reset the GPU. -const FLUSH_WORK: u64 = 1 << 30; -/// Copies and render passes [`Compositor::render`] records before submitting. wgpu opens up to -/// two backend command buffers for each (a render pass and its barrier pre-pass), and Metal -/// treats more than 4096 outstanding ones as a lost device: a refresh of a document with a few -/// hundred layers reached that inside a single page cell (P12, "pc_compose_uniforms is -/// invalid"), where the work and byte limits above never trigger. -const FLUSH_OPS: u32 = 1000; - -/// A finished chunk: straight-alpha RGBA32F pixels of `rect` (document coordinates) at the -/// texture's origin. -pub struct ChunkOut<'a> { - pub rect: Rect, - pub texture: &'a wgpu::Texture, - pub view: &'a wgpu::TextureView, -} - -/// What a render did (for profiling and tests). -#[derive(Clone, Copy, Debug, Default)] -pub struct Stats { - /// How long the GPU spent executing a composite, once its timestamps came back. Because the - /// readback is asynchronous this belongs to an *earlier* render than the one returning it - /// (it carries that render's own pixel count, so the two are never confused), and it is - /// `None` unless [`Compositor::measure_gpu_time`] is on and a measurement has landed. - /// Always `None` from [`Compositor::encode`], which submits nothing of its own. - pub gpu_time: Option, - pub passes: usize, - pub chunks: usize, - pub slots: u32, - pub tiles_uploaded: usize, - pub bytes_uploaded: usize, - /// Tiles a new layer texture took from another layer's texture by a GPU copy (a duplicate - /// shares its source's tiles) instead of uploading them. - pub tiles_shared: usize, - /// Effect layers whose shape was (re)rendered, fully or partially. - pub fx_shapes: usize, - /// Effect map programs run (one per effect whose maps were rebuilt). - pub fx_programs: usize, - /// Effect-map pixels written (all stages). - pub fx_pixels: u64, - /// Page cells the region spans (each binds only the layer pages it overlaps). - pub cells: usize, - /// Layer pages and paged effect maps evicted to stay within the memory budgets. - pub evicted: usize, - /// Intermediate submits of a huge refresh (to bound staging and evicted memory). - pub flushes: usize, - /// Chunks restored from an unchanged lower-stack composite. - pub prefix_hits: usize, - /// Planned prefix passes skipped, summed over the reused chunks. - pub prefix_passes_skipped: usize, - /// Plain layers blended inside another layer's pass (`fs_layerbatch`), summed over chunks. - pub layers_batched: usize, - /// Batched passes drawn with Normal's code alone (`fs_layerbatch_normal`), summed over chunks. - pub normal_batches: usize, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum TexKind { - /// RGBA8 tiles copied verbatim. - Rgba8Direct, - /// Other 8-bit formats converted to RGBA8. - Rgba8, - /// 16/32-bit formats converted to RGBA16F. - Rgba16F, - /// GRAY8 masks copied verbatim. - R8Direct, - /// 16-bit masks as R16F (the precision 16-bit pixels get as RGBA16F). - R16F, - /// 32-bit masks as R32F. - R32F, -} - -impl TexKind { - fn for_surface(role: Role, f: PixelFormat) -> Self { - match role { - Role::Content | Role::Stroke if f == PixelFormat::RGBA8 => TexKind::Rgba8Direct, - Role::Content | Role::Stroke if f.sample == SampleType::U8 => TexKind::Rgba8, - Role::Content | Role::Stroke => TexKind::Rgba16F, - Role::Mask if f == PixelFormat::GRAY8 => TexKind::R8Direct, - Role::Mask if f.sample == SampleType::F32 => TexKind::R32F, - Role::Mask => TexKind::R16F, - } - } - fn format(self) -> wgpu::TextureFormat { - match self { - TexKind::Rgba8Direct | TexKind::Rgba8 => wgpu::TextureFormat::Rgba8Unorm, - TexKind::Rgba16F => wgpu::TextureFormat::Rgba16Float, - TexKind::R8Direct => wgpu::TextureFormat::R8Unorm, - TexKind::R16F => wgpu::TextureFormat::R16Float, - TexKind::R32F => wgpu::TextureFormat::R32Float, - } - } - fn bytes_per_pixel(self) -> usize { - match self { - TexKind::Rgba8Direct | TexKind::Rgba8 => 4, - TexKind::Rgba16F => 8, - TexKind::R8Direct => 1, - TexKind::R16F => 2, - TexKind::R32F => 4, - } - } -} - -/// Index into the render's resident key list, and the texture's region (x, y, w, h). -type ResidentRef = (usize, [i32; 4]); -/// A page cell: the square `[x·page, (x+1)·page) × [y·page, (y+1)·page)` of document pixels. -type Cell = (i32, i32); -/// A resident layer page. -type ResKey = (LayerId, Role, Cell); -/// Effect maps of a layer: over its whole effect region (`None`), or one page cell of a region -/// larger than the texture limit. -type FxKey = (LayerId, Option); - -struct CachedPattern { - fingerprint: u64, - format: PixelFormat, - default_bits: Vec, - texture: Tex, - /// The document that last painted with it: closing that document frees the texture (#4971). - doc: DocId, - /// [`Compositor::frame`] when it last painted. - last_used: u64, - /// GPU bytes of the texture (RGBA32F). - bytes: u64, -} - -struct Resident { - texture: wgpu::Texture, - view: wgpu::TextureView, - /// Document-pixel rect covered (tile aligned, inside one page cell). - region: Rect, - kind: TexKind, - format: PixelFormat, - tiles: HashMap>, - default_nonzero: bool, - /// Bit pattern of the surface's default pixel when the texture was filled. Tiles the surface - /// doesn't store hold it, so a changed default (Invert, Fill) makes the texture stale. - default_bits: Vec, - doc: DocId, - last_used: u64, - /// Cell visit that last used it (least recently used pages are evicted first). - stamp: u64, - /// CMYK profile the texels were converted with (`CmykSpace::id`, 0 = built-in / not CMYK). - cmyk: u64, - /// Its texels were copied to or from another layer texture by the encoder, so every write - /// to it goes through the encoder too: a queued write lands before the encoder runs, and - /// would be overwritten by the copy, or leak into it. - ordered: bool, -} - -impl Resident { - fn bytes(&self) -> u64 { - self.region.width() as u64 * self.region.height() as u64 * self.kind.bytes_per_pixel() as u64 - } -} - -/// A texture and its default view. -#[derive(Clone)] -struct Tex { - texture: wgpu::Texture, - view: wgpu::TextureView, -} - -impl Tex { - fn new(device: &wgpu::Device, label: &str, w: u32, h: u32, format: wgpu::TextureFormat, usage: wgpu::TextureUsages) -> Self { - let texture = device.create_texture(&wgpu::TextureDescriptor { - label: Some(label), - size: wgpu::Extent3d { width: w.max(1), height: h.max(1), depth_or_array_layers: 1 }, - mip_level_count: 1, - sample_count: 1, - dimension: wgpu::TextureDimension::D2, - format, - usage, - view_formats: &[], - }); - let view = texture.create_view(&Default::default()); - Tex { texture, view } - } - fn map(device: &wgpu::Device, label: &str, r: Rect, format: wgpu::TextureFormat) -> Self { - Tex::new( - device, - label, - r.width(), - r.height(), - format, - wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, - ) - } - /// Upload R32F values (row-major over `r`) into this region-space texture at `r`. - fn write_r32(&self, queue: &wgpu::Queue, region: Rect, r: Rect, v: &[f32]) { - if r.is_empty() { - return; - } - let bytes: Vec = v.iter().flat_map(|x| x.to_le_bytes()).collect(); - queue.write_texture( - wgpu::TexelCopyTextureInfo { - texture: &self.texture, - mip_level: 0, - origin: wgpu::Origin3d { x: (r.x0 - region.x0) as u32, y: (r.y0 - region.y0) as u32, z: 0 }, - aspect: wgpu::TextureAspect::All, - }, - &bytes, - wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(r.width() * 4), rows_per_image: Some(r.height()) }, - wgpu::Extent3d { width: r.width(), height: r.height(), depth_or_array_layers: 1 }, - ); - } - fn bytes(&self) -> usize { - let s = self.texture.size(); - let bpp = match self.texture.format() { - wgpu::TextureFormat::R16Float => 2, - wgpu::TextureFormat::Rgba32Float => 16, - wgpu::TextureFormat::Rgba16Float => 8, - _ => 4, - }; - s.width as usize * s.height as usize * bpp - } -} - -/// Cached maps of one effect (one enabled item of a layer). -struct ProgState { - key: u64, - maps: Vec>, -} - -/// Cached effect state of one layer. -struct FxEntry { - doc: DocId, - region: Rect, - shape_key: u64, - /// Tiles the shape was rendered from (content, mask): damage is their difference. - tiles: [Option; 2], - /// Groups: the tiles `shape_key` hashes, by address only (see [`fx::Tiles`]). - _pin: Vec>, - /// The shape on the CPU (distance fields are computed from it) and on the GPU. - shape_cpu: Vec, - shape: Tex, - /// Distance fields: the reach each is exact to, and its texture. - fields: HashMap, - progs: Vec, - last_used: u64, - stamp: u64, -} - -impl FxEntry { - fn bytes(&self) -> usize { - self.shape.bytes() - + self.shape_cpu.len() * 4 - + self.fields.values().map(|(_, t)| t.bytes()).sum::() - + self.progs.iter().flat_map(|p| p.maps.iter().flatten()).map(Tex::bytes).sum::() - } -} - -/// Pipelines and layouts, shared by cheap clones (wgpu handles are reference counted). -#[derive(Clone)] -struct Kit { - pipelines: HashMap<(Kernel, wgpu::TextureFormat), wgpu::RenderPipeline>, - bgl0: wgpu::BindGroupLayout, - bgl1: wgpu::BindGroupLayout, - dummy: wgpu::TextureView, -} - -/// One draw of an effect-map kernel (outside the chunk loop). -struct MapDraw { - kernel: Kernel, - format: wgpu::TextureFormat, - target: wgpu::TextureView, - /// Target-local scissor (x, y, w, h). - scissor: [u32; 4], - /// Chunk record: origin and size of the target's space. - space: [i32; 4], - op: Vec, - views: [Option; 8], - lut: Option>>, -} - -impl Kit { - /// Record `draws` (each its own render pass) into `encoder`. - fn run(&self, device: &wgpu::Device, queue: &wgpu::Queue, encoder: &mut wgpu::CommandEncoder, draws: &[MapDraw]) { - if draws.is_empty() { - return; - } - let mut data = vec![0u8; draws.len() * 2 * STRIDE as usize]; - for (i, d) in draws.iter().enumerate() { - let w = words(&[I(d.space[0]), I(d.space[1]), I(d.space[2]), I(d.space[3])]); - data[2 * i * STRIDE as usize..][..w.len()].copy_from_slice(&w); - data[(2 * i + 1) * STRIDE as usize..][..d.op.len()].copy_from_slice(&d.op); - } - let ubuf = device.create_buffer(&wgpu::BufferDescriptor { - label: Some("pc_fx_uniforms"), - size: data.len() as u64, - usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, - mapped_at_creation: false, - }); - queue.write_buffer(&ubuf, 0, &data); - let bg0 = uniform_group(device, &self.bgl0, &ubuf); - for (i, d) in draws.iter().enumerate() { - let lut = d.lut.as_ref().map(|l| { - let mut row = [0.0f32; 4096]; - row[..l.len().min(4096)].copy_from_slice(&l[..l.len().min(4096)]); - lut_texture(device, queue, &[row]) - }); - let mut views: Vec<&wgpu::TextureView> = d.views.iter().map(|v| v.as_ref().unwrap_or(&self.dummy)).collect(); - if let Some((_, lv)) = &lut { - views[4] = lv; - } - let bg1 = texture_group(device, &self.bgl1, &views); - let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { - label: Some("pc_fx_map"), - color_attachments: &[Some(wgpu::RenderPassColorAttachment { - view: &d.target, - resolve_target: None, - depth_slice: None, - ops: wgpu::Operations { load: wgpu::LoadOp::Load, store: wgpu::StoreOp::Store }, - })], - depth_stencil_attachment: None, - timestamp_writes: None, - occlusion_query_set: None, - multiview_mask: None, - }); - pass.set_pipeline(&self.pipelines[&(d.kernel, d.format)]); - pass.set_scissor_rect(d.scissor[0], d.scissor[1], d.scissor[2], d.scissor[3]); - pass.set_bind_group(0, &bg0, &[(2 * i as u64 * STRIDE) as u32, ((2 * i + 1) as u64 * STRIDE) as u32]); - pass.set_bind_group(1, &bg1, &[]); - pass.draw(0..3, 0..1); - } - } -} - -fn uniform_group(device: &wgpu::Device, layout: &wgpu::BindGroupLayout, ubuf: &wgpu::Buffer) -> wgpu::BindGroup { - device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("pc_compose_uniforms"), - layout, - entries: &[ - wgpu::BindGroupEntry { - binding: 0, - resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { buffer: ubuf, offset: 0, size: NonZeroU64::new(CHUNK_UNIFORM) }), - }, - wgpu::BindGroupEntry { - binding: 1, - resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { buffer: ubuf, offset: 0, size: NonZeroU64::new(OP_UNIFORM) }), - }, - ], - }) -} - -fn texture_group(device: &wgpu::Device, layout: &wgpu::BindGroupLayout, views: &[&wgpu::TextureView]) -> wgpu::BindGroup { - let e: Vec = - views.iter().enumerate().map(|(b, v)| wgpu::BindGroupEntry { binding: b as u32, resource: wgpu::BindingResource::TextureView(v) }).collect(); - device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("pc_compose_pass"), layout, entries: &e }) -} - /// GPU compositor. Create once per device; call [`Compositor::render`] per refresh. pub struct Compositor { kit: Kit, @@ -508,2872 +126,42 @@ pub struct Compositor { /// [`Compositor::measure_gpu_time`]); `None` = not measured. timer: Option, } - -fn tex_entry(binding: u32) -> wgpu::BindGroupLayoutEntry { - wgpu::BindGroupLayoutEntry { - binding, - visibility: wgpu::ShaderStages::FRAGMENT, - ty: wgpu::BindingType::Texture { - multisampled: false, - sample_type: wgpu::TextureSampleType::Float { filterable: false }, - view_dimension: wgpu::TextureViewDimension::D2, - }, - count: None, - } -} - -fn uniform_entry(binding: u32, size: u64) -> wgpu::BindGroupLayoutEntry { - wgpu::BindGroupLayoutEntry { - binding, - visibility: wgpu::ShaderStages::FRAGMENT, - ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: true, min_binding_size: NonZeroU64::new(size) }, - count: None, - } -} - -/// The compositor's WGSL source (exposed for validation in tests). -pub const SHADER: &str = include_str!("compose.wgsl"); - -/// Pass-level resources resolved for one page cell: resident pages (texture, mask) and effect -/// maps (view and region) per pass. -struct Bound { - views: Vec<(Option, Option)>, - keys: Vec, - maps: Vec>, -} - -/// Pass-level resources shared by every cell of a frame. -struct FrameRes { - /// Tile area of each pass's (texture, mask) surface within the canvas tile grid. - areas: Vec<(Rect, Rect)>, - luts: Vec>, - patterns: Vec>, -} - -/// Document pixels of page cell `c`. -fn cell_rect(c: Cell, page: u32) -> Rect { - let p = page as i32; - Rect::new(c.0.saturating_mul(p), c.1.saturating_mul(p), c.0.saturating_add(1).saturating_mul(p), c.1.saturating_add(1).saturating_mul(p)) -} - -/// `r` cut along the grid of `step`-sized squares (row-major). -fn grid_rects(r: Rect, step: u32) -> Vec { - let s = step.max(1) as i32; - let mut out = Vec::new(); - let mut y = r.y0.div_euclid(s) * s; - while y < r.y1 { - let mut x = r.x0.div_euclid(s) * s; - while x < r.x1 { - out.push(Rect::new(x, y, x.saturating_add(s), y.saturating_add(s)).intersect(&r)); - x = x.saturating_add(s); - } - y = y.saturating_add(s); - } - out -} - -/// Number of rectangles `grid_rects` would produce, without allocating them during preflight. -fn grid_rect_count(r: Rect, step: u32) -> Result { - if r.is_empty() { - return Ok(0); - } - let s = i64::from(step.max(1)); - let axis = |lo: i32, hi: i32| usize::try_from((i64::from(hi) - 1).div_euclid(s) - i64::from(lo).div_euclid(s) + 1).ok(); - axis(r.x0, r.x1).and_then(|x| axis(r.y0, r.y1).and_then(|y| x.checked_mul(y))).ok_or_else(|| Unsupported("GPU compositor chunk count is too large".into())) -} - -/// Host length and GPU capacity for the chunk/pass uniform records, including their u32 -/// dynamic binding offsets. Decline unsupported stacks before an invalid buffer faults the device. -fn uniform_buffer_len(chunks: usize, passes: usize, limit: u64) -> Result { - let too_large = || Unsupported("GPU compositor uniform buffer is too large".into()); - let records = chunks.checked_add(passes).and_then(|n| u64::try_from(n).ok()).ok_or_else(too_large)?; - let bytes = records.checked_mul(STRIDE).ok_or_else(too_large)?; - if bytes > limit { - return Err(Unsupported(format!("GPU compositor uniform buffer requires {bytes} bytes; device limit is {limit}"))); - } - if bytes.saturating_sub(STRIDE) > u64::from(u32::MAX) { - return Err(Unsupported("GPU compositor uniform offsets exceed u32".into())); - } - usize::try_from(bytes).map_err(|_| too_large()) -} - -/// The reach up to which each distance field must be exact (the largest any program asks for). -fn field_reaches(progs: &[fx::MapProgram]) -> HashMap { - let mut want: HashMap = HashMap::new(); - for (k, r) in progs.iter().flat_map(|p| p.fields.iter()) { - let w = want.entry(*k).or_insert(0); - *w = (*w).max(*r); - } - want -} - -/// Why a refresh whose layer pages don't fit GPU memory is drawn on the CPU. -pub const OVER_BUDGET: &str = "layers exceed the GPU memory budget; full refresh on the CPU"; - -/// Which of `pages` (LRU clock, key, bytes) to drop, least recently used first, so `incoming` -/// more bytes fit `budget` on top of the `total` held now. Callers leave out pages that must stay. -fn lru_victims(mut pages: Vec<(u64, K, u64)>, total: u64, incoming: u64, budget: u64) -> Vec { - pages.sort_unstable_by_key(|p| p.0); - let mut total = total; - let mut out = Vec::new(); - for (_, k, bytes) in pages { - if total.saturating_add(incoming) <= budget { - break; - } - total = total.saturating_sub(bytes); - out.push(k); - } - out -} - -/// Runs `f` inside GPU error scopes and returns the first error raised. -/// Native wgpu reports validation/internal/OOM errors synchronously; where they only arrive -/// asynchronously (WebGPU) none is reported. -fn first_error(device: &wgpu::Device, f: impl FnOnce() -> T) -> (T, Option) { - let validation = device.push_error_scope(wgpu::ErrorFilter::Validation); - let internal = device.push_error_scope(wgpu::ErrorFilter::Internal); - let memory = device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); - let out = f(); - let mut cx = std::task::Context::from_waker(std::task::Waker::noop()); - let mut error = None; - // Scopes pop in reverse order. - for pop in [memory.pop(), internal.pop(), validation.pop()] { - if let std::task::Poll::Ready(Some(e)) = std::pin::pin!(pop).poll(&mut cx) { - error.get_or_insert(e); - } - } - (out, error) -} - -/// Runs `f` inside the error scopes of [`first_error`], turning a reported error into -/// [`Unsupported`] instead of letting it escape to wgpu's panic handler. -/// -/// Every native caller needs this, watched or not: a validation error (writing into a destroyed -/// or too-small buffer, say) is raised synchronously and never reaches the health callbacks, so a -/// watched compositor still panicked on it. WebGPU reports its errors asynchronously, long after -/// the scope has popped, so wasm relies on the health callbacks alone. -/// -/// A scope also swallows the error that [`DeviceHealth`]'s uncaptured-error handler would have -/// recorded, so a reported error is handed back to `health`: a watched device must stop being -/// used and let the caller fall back to the CPU compositor. -fn scoped_work(device: &wgpu::Device, health: Option, f: impl FnOnce() -> Result) -> Result { - // WebGPU errors arrive asynchronously; its callers still use the health callbacks. - if cfg!(target_arch = "wasm32") { - return f(); - } - let (result, error) = first_error(device, f); - match error { - Some(error) => { - if let Some(health) = health.as_ref() { - health.caught(device, &error); - } - Err(Unsupported(format!("GPU work failed: {error}"))) - } - None => result, - } -} - -impl Compositor { - /// Create a compositor with the default accumulation format ([`ACC_FORMAT`]). - pub fn new(device: &wgpu::Device) -> Self { - Self::new_with_format(device, ACC_FORMAT) - } - - /// The accumulation format to use on `adapter`: `Rgba32Float` when it can be a render target, - /// else `Rgba16Float`. Some drivers (e.g. Intel Vulkan) don't support rendering to `Rgba32Float` - /// and would otherwise panic at render-pipeline creation. - pub fn preferred_acc_format(adapter: &wgpu::Adapter) -> wgpu::TextureFormat { - let feats = adapter.get_texture_format_features(wgpu::TextureFormat::Rgba32Float); - if feats.allowed_usages.contains(wgpu::TextureUsages::RENDER_ATTACHMENT) { wgpu::TextureFormat::Rgba32Float } else { wgpu::TextureFormat::Rgba16Float } - } - - /// [`Compositor::new_with_format`], but a shader or pipeline the driver can't build (e.g. a - /// D3D12 shader-compiler failure) is an `Err` instead of a panic, so the caller can fall back - /// to the CPU compositor. Where errors only arrive asynchronously (WebGPU), creation is assumed - /// to have worked. - pub fn try_new_with_format(device: &wgpu::Device, acc_format: wgpu::TextureFormat) -> Result { - match first_error(device, || Self::build(device, acc_format)) { - ((comp, None), None) => Ok(comp), - ((_, Some(e)), _) | (_, Some(e)) => Err(Unsupported(format!("couldn't build the compositor's pipelines: {e}"))), - } - } - - /// Create a compositor whose accumulation/render-target format is `acc_format`. Pass - /// `Rgba16Float` on adapters that can't render to `Rgba32Float` (e.g. some Intel Vulkan drivers), - /// which otherwise panics at render-pipeline creation. See `Compositor::preferred_acc_format`. - pub fn new_with_format(device: &wgpu::Device, acc_format: wgpu::TextureFormat) -> Self { - let (comp, error) = Self::build(device, acc_format); - if let Some(e) = error { - log::error!("GPU compositor: couldn't build its pipelines: {e}"); - } - comp - } - - /// The compositor and the first error raised building its (non-map) pipelines. They are - /// built in parallel, each inside its own error scope on the thread that builds it (wgpu's - /// scopes are per thread): on DX12, FXC compiles one shader at a time and the ~30 pipelines - /// took about 8 s on one core (#6419). - fn build(device: &wgpu::Device, acc_format: wgpu::TextureFormat) -> (Self, Option) { - let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("pc_compose"), source: wgpu::ShaderSource::Wgsl(SHADER.into()) }); - let bgl0 = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { - label: Some("pc_compose_uniforms"), - entries: &[uniform_entry(0, CHUNK_UNIFORM), uniform_entry(1, OP_UNIFORM)], - }); - let bgl1 = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { - label: Some("pc_compose_textures"), - entries: &(0..8).map(tex_entry).collect::>(), - }); - let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { - label: Some("pc_compose"), - bind_group_layouts: &[Some(&bgl0), Some(&bgl1)], - immediate_size: 0, - }); - // `None` only for kernels without a fragment entry point, which are never drawn. - let pipeline = |k: Kernel, format: wgpu::TextureFormat| { - let entry = k.entry()?; - Some(device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { - label: Some(entry), - layout: Some(&layout), - vertex: wgpu::VertexState { module: &module, entry_point: Some("vs"), buffers: &[], compilation_options: Default::default() }, - primitive: wgpu::PrimitiveState::default(), - depth_stencil: None, - multisample: wgpu::MultisampleState::default(), - fragment: Some(wgpu::FragmentState { - module: &module, - entry_point: Some(entry), - targets: &[Some(wgpu::ColorTargetState { format, blend: None, write_mask: wgpu::ColorWrites::ALL })], - compilation_options: Default::default(), - }), - multiview_mask: None, - cache: None, - })) - }; - // Effect maps render to R32Float / R16Float, which some adapters (e.g. GL without float - // render targets) can't: then layer effects use the CPU compositor and the rest stays here. - let keys = Kernel::DRAWN.iter().filter(|k| !k.is_map()).map(|&k| (k, acc_format)); - let keys: Vec<_> = keys.chain(Kernel::DRAWN.iter().filter(|k| k.is_map()).flat_map(|&k| [(k, MAP32), (k, MAP16)])).collect(); - let built = fx::par_map(keys, |key| { - let (built, error) = first_error(device, || pipeline(key.0, key.1)); - (key, built, error) - }); - let (mut pipelines, mut maps) = (HashMap::new(), Vec::new()); - let (mut error, mut map_error) = (None, None); - for (key, built, e) in built { - let map = key.0.is_map(); - // A failed map pipeline turns all effect maps off below. A failed non-map pipeline - // keeps its (invalid) handle: draws look pipelines up by key, so dropping it would - // turn a validation error into a missing-key panic on the first draw. - if let Some(e) = e { - if map { - map_error.get_or_insert(e); - continue; - } - error.get_or_insert(e); - } - let Some(p) = built else { continue }; - if map { - maps.push((key, p)); - } else { - pipelines.insert(key, p); - } - } - if let Some(e) = &map_error { - log::info!("GPU compositor: no effect-map pipelines ({e}); layer effects use the CPU"); - } else { - pipelines.extend(maps); - } - let dummy = Tex::new(device, "pc_compose_dummy", 1, 1, wgpu::TextureFormat::Rgba8Unorm, wgpu::TextureUsages::TEXTURE_BINDING).view; - let comp = Self { - kit: Kit { pipelines, bgl0, bgl1, dummy }, - pool: Vec::new(), - residents: HashMap::new(), - fx: HashMap::new(), - prefix: prefix::Prefix::default(), - temps: Vec::new(), - patterns: HashMap::new(), - pattern_mode: photocraft_color::ColorMode::Rgb, - pattern_doc: DocId(0), - pattern_budget: PATTERN_BUDGET, - max_dim: 0, - device_max: device.limits().max_texture_dimension_2d, - page: PAGE, - chunk: CHUNK, - resident_budget: RESIDENT_BUDGET, - fx_budget: (FX_BUDGET as u64).saturating_sub(prefix::MAX_BYTES), - layer_need: 0, - lent: 0, - exact_resident: false, - focus: None, - frame: 0, - stamp: 0, - staged: 0, - recorded: 0, - layer_alloc: None, - admit_freed: 0, - fail_allocs: 0, - acc_format, - effect_maps: map_error.is_none(), - cmyk: 0, - health: None, - timer: None, - } - .with_texture_limit(device.limits().max_texture_dimension_2d); - (comp, error) - } - - fn with_texture_limit(mut self, max: u32) -> Self { - self.set_texture_limit(max); - self - } - - /// Plan paging for a texture side limit of `max` (clamped to the device's own limit and at - /// least one tile). Tests use a small limit to exercise documents larger than it on any - /// adapter. Drops every cached texture. - pub fn set_texture_limit(&mut self, max: u32) { - let tile = TILE_SIZE as u32; - self.max_dim = max.min(self.device_max).max(tile); - let mut page = tile; - while page * 2 <= self.max_dim.min(PAGE) { - page *= 2; - } - self.page = page; - self.chunk = CHUNK.min(page); - self.prefix.set_step(self.chunk); - self.pool.clear(); - self.residents.clear(); - self.fx.clear(); - self.temps.clear(); - self.prefix.clear(); - } - - /// The page side layer surfaces are stored in. - pub fn page_size(&self) -> u32 { - self.page - } - - /// Test hook: the next `n` layer page textures fail as if the device were out of memory - /// (a real one can't be forced), so the fallback paths of #6563 can be tested. - #[doc(hidden)] - pub fn fail_layer_allocs(&mut self, n: u32) { - self.fail_allocs = n; - } - - /// Set the GPU memory resident layer pages may hold (default [`RESIDENT_BUDGET`]), exactly: - /// nothing is lent to it ([`Self::fit_layers`]) until the next [`Self::set_memory_budget`]. - pub fn set_resident_budget(&mut self, bytes: u64) { - // The loan goes back to the effect maps, so the total budget stays what it was. - self.fx_budget = self.fx_budget.saturating_add(self.lent); - self.lent = 0; - self.resident_budget = bytes; - self.exact_resident = true; - } - - /// Set the GPU memory the compositor may hold for layer pages and caches together - /// (a quarter of it, at most [`FX_BUDGET`], for effect maps and lower-stack chunks). Uploads and evicted pages in - /// flight during a refresh stay within about a quarter more. - pub fn set_memory_budget(&mut self, bytes: u64) { - let caches = (FX_BUDGET as u64).min(bytes / 4); - self.prefix.set_budget((caches / 2).min(prefix::MAX_BYTES)); - self.fx_budget = caches.saturating_sub(self.prefix.budget()); - self.resident_budget = bytes.saturating_sub(caches); - self.lent = 0; - self.exact_resident = false; - self.lend(); - } - - /// Record that a render needs `needed` bytes of layer pages and return the resident budget - /// they now have. A render of the `whole` document sets the need; a part of it only raises - /// it, so a large partial refresh never shrinks what the next full one keeps resident. - /// - /// Pages that miss their share by less than the effect-map share borrow from it: an evicted - /// effect map is rebuilt by the next refresh that draws it, but one page too many sends the - /// whole refresh to the CPU compositor, 10× slower (#5973, P60: 150 layers of 6 MP on an - /// integrated GPU missed by 5 % and took 680 ms instead of 62). - /// The lower-stack share is never lent: it is what keeps a mid-stack edit at half the work. - /// The loan holds across [`Self::set_memory_budget`] until a later call needs less or more. - pub fn fit_layers(&mut self, needed: u64, whole: bool) -> u64 { - self.layer_need = if whole { needed } else { self.layer_need.max(needed) }; - self.lend(); - self.resident_budget - } - - /// Return the loan to the effect maps, then lend what [`Self::layer_need`] still lacks, if - /// the effect-map share covers it (lending part of it would fit nothing and only evict maps). - fn lend(&mut self) { - self.fx_budget = self.fx_budget.saturating_add(self.lent); - self.resident_budget = self.resident_budget.saturating_sub(self.lent); - let short = self.layer_need.saturating_sub(self.resident_budget); - self.lent = if short <= self.fx_budget && !self.exact_resident { short } else { 0 }; - self.fx_budget = self.fx_budget.saturating_sub(self.lent); - self.resident_budget = self.resident_budget.saturating_add(self.lent); - } - - /// The budget of layer pages, effect maps and lower-stack chunks (bytes). - pub fn memory_budget(&self) -> u64 { - self.resident_budget.saturating_add(self.fx_budget).saturating_add(self.prefix.budget()) - } - - /// Bytes held by reusable lower-stack chunks, within the overall cache allowance. - pub fn composite_cache_bytes(&self) -> u64 { - self.prefix.bytes() - } - - /// Cap lower-stack reuse (default at most 512 MiB); zero disables it. The released allowance - /// goes back to effect maps, preserving the total budget and layer-page allowance. - pub fn set_composite_cache_budget(&mut self, bytes: u64) { - let caches = self.fx_budget.saturating_add(self.prefix.budget()); - self.prefix.set_budget(bytes.min(caches)); - self.fx_budget = caches.saturating_sub(self.prefix.budget()); - } - - /// Bytes of the layer pages a render of `region` needs resident (each layer and mask - /// surface's tiles within the region's page cells, in their texture format). - pub fn working_set(&self, doc: &Document, region: Rect) -> u64 { - let Ok(plan) = plan(doc) else { return 0 }; - let grid = tile_grid(doc.bounds()); - let cells = grid_rects(region.intersect(&doc.bounds()), self.page) - .into_iter() - .map(|r| cell_rect((r.x0.div_euclid(self.page as i32), r.y0.div_euclid(self.page as i32)), self.page)) - .fold(Rect::EMPTY, |a, c| if a.is_empty() { c } else { a.union(&c) }); - let mut seen = std::collections::HashSet::new(); - let mut total = 0u64; - for p in &plan.passes { - let sources = [p.tex.as_ref().map(|t| (t.layer, t.role, t.surface.get())), p.mask.as_ref().map(|m| (m.layer, Role::Mask, m.surface.get()))]; - for (layer, role, s) in sources.into_iter().flatten() { - if seen.insert((layer, role)) { - let a = s.tile_bounds().intersect(&grid).intersect(&cells); - total += a.width() as u64 * a.height() as u64 * TexKind::for_surface(role, s.format()).bytes_per_pixel() as u64; - } - } - } - total - } - - /// The GPU memory resident layer pages may hold (bytes; see [`Compositor::set_memory_budget`]). - pub fn resident_budget(&self) -> u64 { - self.resident_budget - } - - /// Whether a render of `region` keeps every layer page it needs within the budget; when it - /// doesn't, each render re-uploads what was evicted. - pub fn fits_budget(&self, doc: &Document, region: Rect) -> bool { - self.working_set(doc, region) <= self.resident_budget - } - - /// The document area the view shows (`None`: unknown). Full refreshes draw its cells last. - pub fn set_focus(&mut self, focus: Option) { - self.focus = focus; - } - - /// GPU memory held by resident layer pages (bytes). - pub fn resident_bytes(&self) -> u64 { - self.residents.values().map(Resident::bytes).sum() - } - - /// GPU memory held by cached pattern textures (bytes). - pub fn pattern_cache_bytes(&self) -> u64 { - self.patterns.values().map(|p| p.bytes).sum() - } - - /// Set the GPU memory pattern textures may hold (default [`PATTERN_BUDGET`]). It takes effect - /// at the end of the next refresh. - pub fn set_pattern_budget(&mut self, bytes: u64) { - self.pattern_budget = bytes; - } - - /// Whether `doc` can be composited on the GPU. Documents and layers larger than the texture - /// limit are fine: surfaces are stored in page-sized textures and effect maps of regions - /// larger than the limit are built per page cell. - pub fn supports(&self, doc: &Document) -> Result<(), Unsupported> { - let p = plan(doc)?; - self.check_fx(doc, &p) - } - - /// Whether the maps of an effect region are built per page cell (it exceeds the limit). - fn fx_paged(&self, region: Rect) -> bool { - region.width() > self.max_dim || region.height() > self.max_dim - } - - /// How far beyond a page cell the effect maps of `f` must be computed to be exact in it. - fn fx_apron(doc: &Document, f: &plan::FxLayer<'_>) -> i32 { - let vector_shape = matches!(f.layer.content, LayerContent::Shape(_)) && photocraft_compose::effect_outline(f.layer).is_none(); - let progs: Vec = f - .layer - .effects - .items - .iter() - .filter(|e| e.enabled()) - .map(|e| fx::program_with(e, &doc.global_light, vector_shape, &doc.patterns, (0.0, 0.0))) - .collect(); - let want = field_reaches(&progs); - // Distance fields are exact one pixel inside the window they are computed from. - progs.iter().map(|p| p.reach(&|k| want.get(&k).copied().unwrap_or(0))).max().unwrap_or(0).saturating_add(2) - } - - /// Effect maps must fit in textures (per page cell when the region exceeds the limit), and - /// patterns in one texture. - fn check_fx(&self, doc: &Document, p: &Plan<'_>) -> Result<(), Unsupported> { - if !self.effect_maps && !p.fx.is_empty() { - return Err(Unsupported("layer effects need float effect-map render targets, which this GPU lacks".into())); - } - for f in &p.fx { - if self.fx_paged(f.region) { - let side = i64::from(self.page) + 2 * i64::from(Self::fx_apron(doc, f)); - if side > i64::from(self.device_max) { - return Err(Unsupported(format!("effects of `{}` reach too far to build per page", f.layer.name))); - } - } - for e in f.layer.effects.items.iter().filter(|e| e.enabled()) { - // Effect noise is speckled in the CPU maps; keep CPU and GPU identical by - // rendering noise-carrying effects on the CPU path. - let noisy = match e { - photocraft_doc::Effect::DropShadow(s) | photocraft_doc::Effect::InnerShadow(s) => s.noise > 0.0, - photocraft_doc::Effect::OuterGlow(g) | photocraft_doc::Effect::InnerGlow(g) => g.noise > 0.0, - _ => false, - }; - if noisy { - return Err(Unsupported(format!("effect noise on `{}` uses the CPU path", f.layer.name))); - } - for s in fx::program_with(e, &doc.global_light, false, &doc.patterns, (0.0, 0.0)).stages { - if s.lut.as_ref().is_some_and(|l| l.len() > 4096) { - return Err(Unsupported(format!("effect blur on `{}` too wide for the GPU path", f.layer.name))); - } - } - } - } - for pass in &p.passes { - if let Some(pat) = pass.pattern - && (pat.width > self.device_max || pat.height > self.device_max) - { - return Err(Unsupported(format!("pattern `{}` larger than the GPU texture limit", pat.name))); - } - } - Ok(()) - } - - /// Drop GPU textures of a closed document. - pub fn forget_doc(&mut self, doc: DocId) { - self.residents.retain(|_, r| r.doc != doc); - self.fx.retain(|_, e| e.doc != doc); - self.patterns.retain(|_, p| p.doc != doc); - self.prefix.forget(doc); - } - - /// [`Self::forget_doc`] for every document `keep` rejects: what the compositor holds for - /// documents that were closed, however their canvas entry went (#4529). - pub fn retain_docs(&mut self, keep: impl Fn(DocId) -> bool) { - let mut gone: Vec = self - .residents - .values() - .map(|r| r.doc) - .chain(self.fx.values().map(|e| e.doc)) - .chain(self.patterns.values().map(|p| p.doc)) - .chain(self.prefix.doc()) - .filter(|d| !keep(*d)) - .collect(); - gone.sort_by_key(|d| d.0); - gone.dedup(); - for d in gone { - self.forget_doc(d); - } - } - - /// Documents the compositor holds pages, effect maps, pattern textures or a lower-stack - /// composite for. - pub fn held_docs(&self) -> Vec { - let mut docs: Vec = self - .residents - .values() - .map(|r| r.doc) - .chain(self.fx.values().map(|e| e.doc)) - .chain(self.patterns.values().map(|p| p.doc)) - .chain(self.prefix.doc()) - .collect(); - docs.sort_by_key(|d| d.0); - docs.dedup(); - docs - } - - /// GPU memory held by cached effect maps (bytes). - pub fn fx_cache_bytes(&self) -> usize { - self.fx.values().map(FxEntry::bytes).sum() - } - - /// Watch `health` (see [`DeviceHealth::watch`]): once the device is lost or reported an - /// error, every render returns [`Unsupported`] without touching the GPU, so callers use the - /// CPU compositor instead. - pub fn set_health(&mut self, health: DeviceHealth) { - self.health = Some(health); - } - - /// Why the device can't be used (`None` while healthy or unwatched). - pub fn fault(&self) -> Option { - self.health.as_ref().and_then(DeviceHealth::fault) - } - - /// Measure how long the GPU spends executing each [`Compositor::render`], with timestamp - /// queries read back asynchronously (nothing waits for the GPU). Returns whether the device - /// supports it: without [`timing::FEATURES`] there is no measurement at all, and callers - /// report no GPU time rather than the encode-and-submit cost `composite_ms` already is. - /// - /// A measurement arrives a frame or two after the refresh it belongs to, so it carries that - /// refresh's own pixel count; take it with [`Compositor::take_gpu_timing`]. - pub fn measure_gpu_time(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) -> bool { - // `PHOTOCRAFT_NO_GPU_TIMING` turns it off: a kill switch for a driver whose timestamp - // queries misbehave, and the control arm for measuring what the queries themselves - // cost — the device is identical either way, so only the instrumentation varies. - if std::env::var_os("PHOTOCRAFT_NO_GPU_TIMING").is_some() { - return false; - } - if self.timer.is_none() { - self.timer = timing::GpuTimer::new(device, queue); - } - self.timer.is_some() - } - - /// Whether [`Compositor::measure_gpu_time`] is on for this compositor. - pub fn measures_gpu_time(&self) -> bool { - self.timer.is_some() - } - - /// The most recent finished GPU measurement, leaving none behind (a stale number is never - /// reported twice as new). `None` while unmeasured, unsupported, or still in flight. - /// - /// [`Compositor::render`] already drains this into [`Stats::gpu_time`], so the app never - /// calls it; it is how a bench or a test collects a measurement without issuing another - /// render to carry it. - pub fn take_gpu_timing(&mut self) -> Option { - self.timer.as_mut().and_then(timing::GpuTimer::take) - } - - /// Composite `region` of `doc`. Each finished chunk is passed to `sink` while its encoder is - /// still open; the chunk texture is reused afterwards, so the sink must record any copies - /// or passes that read it into the given encoder. Submits the work before returning; a - /// refresh of a huge document also submits in between (the sink may be handed a new - /// encoder), so its uploads and evicted pages never pile up in memory. - pub fn render( - &mut self, - device: &wgpu::Device, - queue: &wgpu::Queue, - doc: &Document, - region: Rect, - mut sink: impl FnMut(&mut wgpu::CommandEncoder, ChunkOut<'_>), - ) -> Result { - let result = scoped_work(device, self.health.clone(), || { - let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("pc_compose") }); - if self.timer.as_ref().is_some_and(timing::GpuTimer::busy) { - // The readback map completes on a poll. The app polls every frame, but a - // non-blocking poll here keeps the measurements coming whatever the caller does. - match &self.health { - Some(h) => h.poll(device), - None => { - let _ = device.poll(wgpu::PollType::Poll); - } - } - } - // Whatever came back since the last render travels out with this one's stats, so - // nothing has to reach back into the compositor for it afterwards. - let landed = self.timer.as_mut().and_then(timing::GpuTimer::take); - if let Some(t) = &mut self.timer { - let r = region.intersect(&doc.bounds()); - t.start(&mut encoder, r.width() as u64 * r.height() as u64); - } - let mut stats = self.encode_inner(device, queue, &mut encoder, doc, region, &mut sink, true); - if let Ok(s) = &mut stats { - s.gpu_time = landed; - } - if let Some(t) = &mut self.timer { - // A refresh that failed part way measures nothing: its spans describe work the - // caller is about to redo on the CPU. - match stats { - Ok(_) => t.finish(&mut encoder), - Err(_) => { - t.cancel(); - // The refresh is lost, but a measurement that came back with it is not: - // hand it to the next render rather than drop it on the fallback path. - if let Some(landed) = landed { - t.restore(landed); - } - } - } - } - let stats = stats?; - queue.submit([encoder.finish()]); - if let Some(t) = &mut self.timer { - t.submitted(); - } - Ok(stats) - }); - if result.is_err() { - self.discard_failed_work(); - } - result - } - - /// Like [`Self::render`] but records into `encoder` without submitting. - pub fn encode( - &mut self, - device: &wgpu::Device, - queue: &wgpu::Queue, - encoder: &mut wgpu::CommandEncoder, - doc: &Document, - region: Rect, - sink: &mut dyn FnMut(&mut wgpu::CommandEncoder, ChunkOut<'_>), - ) -> Result { - let result = scoped_work(device, self.health.clone(), || self.encode_inner(device, queue, encoder, doc, region, sink, false)); - if result.is_err() { - self.discard_failed_work(); - } - result - } - - fn discard_failed_work(&mut self) { - // Cache metadata advances while recording. A failed encoder may never execute its - // texture uploads or effect maps, so none of those cached pixels can be trusted. - self.prefix.clear(); - self.residents.clear(); - self.fx.clear(); - self.patterns.clear(); - self.temps.clear(); - self.pool.clear(); - } - - #[allow(clippy::too_many_arguments)] - fn encode_inner( - &mut self, - device: &wgpu::Device, - queue: &wgpu::Queue, - encoder: &mut wgpu::CommandEncoder, - doc: &Document, - region: Rect, - sink: &mut dyn FnMut(&mut wgpu::CommandEncoder, ChunkOut<'_>), - flush: bool, - ) -> Result { - if let Some(f) = self.fault() { - return Err(Unsupported(f.to_string())); - } - // CMYK layers convert through the document's own CMYK profile (uploads and plan colours). - let space = photocraft_compose::cmyk_space(doc); - self.cmyk = space.as_ref().map_or(0, |s| s.id); - photocraft_color::convert::with_cmyk_space(space.as_ref(), || self.encode_scoped(device, queue, encoder, doc, region, sink, flush)) - } - - #[allow(clippy::too_many_arguments)] - fn encode_scoped( - &mut self, - device: &wgpu::Device, - queue: &wgpu::Queue, - encoder: &mut wgpu::CommandEncoder, - doc: &Document, - region: Rect, - sink: &mut dyn FnMut(&mut wgpu::CommandEncoder, ChunkOut<'_>), - flush: bool, - ) -> Result { - let canvas = doc.bounds(); - let region = region.intersect(&canvas); - let plan = plan(doc)?; - self.check_fx(doc, &plan)?; - self.pattern_mode = doc.pixel_format().mode; - self.pattern_doc = doc.id; - let mut stats = Stats { passes: plan.passes.len(), slots: plan.slots, ..Default::default() }; - if region.is_empty() { - return Ok(stats); - } - let page = self.page; - let mut cells = grid_rects(region, page); - // Check every actual page cell before uploads, submissions or sink output. A later - // cell can need more chunk records than the first; a failure must leave the device healthy. - let buffer_limit = device.limits().max_buffer_size; - for part in &cells { - uniform_buffer_len(grid_rect_count(*part, self.chunk)?, plan.passes.len(), buffer_limit)?; - } - if self.frame == 0 { - // The first submission after device creation is dropped on some drivers (RADV), - // which would render the first frame black; land it on an empty buffer instead. - queue.submit(std::iter::empty::()); - } - self.frame += 1; - self.stamp += 1; - self.staged = 0; - self.recorded = 0; - self.layer_alloc = None; - self.admit_freed = 0; - - // Only render owns submission. A caller may discard encode's command buffer, so it - // cannot establish (or consume) a checkpoint whose GPU copy might never execute. - // Runs of plain layers drawn as one pass each (`fs_layerbatch`). The grouping is the same - // for every render of this plan, so a layer's bits don't depend on the cache: renders - // capture and resume only where a run starts. - let runs = batch_runs(&plan); - let checkpoint = if flush { - let starts = run_starts(&runs); - let resumable: Vec<_> = plan.checkpoints.iter().filter(|c| starts.get(c.pass_end).copied().unwrap_or(false)).copied().collect(); - self.prefix.prepare(doc, &resumable) - } else { - None - }; - - // Effect maps of whole regions first (they may render group shapes through sub-plans); - // regions larger than the limit are built per cell below. - let paged: Vec = plan.fx.iter().map(|f| self.fx_paged(f.region)).collect(); - let aprons: Vec = plan.fx.iter().zip(&paged).map(|(f, &pg)| if pg { Self::fx_apron(doc, f) } else { 0 }).collect(); - for (f, &pg) in plan.fx.iter().zip(&paged) { - if !pg { - self.sync_fx(device, queue, encoder, doc, f, (f.layer.id, None), f.region, &mut stats)?; - } - } - let fr = self.frame_res(device, queue, canvas, &plan); - - // Page cells; every other frame in reverse, so a repeated full refresh of a document - // larger than the budget starts with the pages still resident. - if self.frame.is_multiple_of(2) { - cells.reverse(); - } - if let Some(f) = self.focus { - let p = page as i32; - let focused = |r: &Rect| !cell_rect((r.x0.div_euclid(p), r.y0.div_euclid(p)), page).intersect(&f).is_empty(); - cells.sort_by_key(focused); - } - let flush_bytes = FLUSH_BYTES.min(self.memory_budget() / 8).max(16 << 20); - stats.cells = cells.len(); - // The previous intermediate submit (see `submit_batch`). - let mut last_submit: Option = None; - // Work recorded and bytes evicted since the last submit. - let (mut work, mut freed) = (0u64, 0u64); - for part in cells { - self.stamp += 1; - let cell = (part.x0.div_euclid(page as i32), part.y0.div_euclid(page as i32)); - let cr = cell_rect(cell, page); - for (i, f) in plan.fx.iter().enumerate() { - let pf = cr.intersect(&f.region); - if !paged.get(i).copied().unwrap_or(false) || pf.is_empty() { - continue; - } - let window = pf.inflate(aprons.get(i).copied().unwrap_or(0)).intersect(&f.region); - self.sync_fx(device, queue, encoder, doc, f, (f.layer.id, Some(cell)), window, &mut stats)?; - } - let chunks = grid_rects(part, self.chunk); - stats.chunks += chunks.len(); - work += part.width() as u64 * part.height() as u64 * plan.passes.len() as u64; - let mut batch = flush.then_some(&mut last_submit); - self.run_cell(device, queue, encoder, doc.id, &plan, &runs, &paged, cell, &fr, &chunks, checkpoint, &mut stats, sink, &mut batch); - // The device was lost in a submit inside the cell: issue no more work. - if let Some(f) = self.fault() { - return Err(Unsupported(f.to_string())); - } - // Out of memory although every page this cell doesn't use was dropped: the work recorded - // since the last submit can still hold those pages. Submit it, wait until the GPU is done - // with it so their memory is released, and run the cell once more. `encode` can't - // submit, so there the refresh goes to the CPU straight away. - if flush && self.layer_alloc.as_deref() == Some(OVER_BUDGET) { - self.layer_alloc = None; - submit_batch(device, queue, encoder, self.health.as_ref(), self.timer.as_mut(), &mut last_submit); - #[cfg(not(target_arch = "wasm32"))] - { - let idle = match self.health.as_ref() { - Some(h) => h.wait_idle(device, last_submit.clone()), - None => device.poll(wgpu::PollType::Wait { submission_index: last_submit.clone(), timeout: None }).is_ok(), - }; - // The GPU has run every timestamp submitted so far, so a retry that fails too - // can drop this measurement without switching timing off for good. - if idle && let Some(t) = self.timer.as_mut() { - t.drained(); - } - } - self.staged = 0; - self.recorded = 0; - work = 0; - freed = 0; - self.admit_freed = 0; - stats.flushes += 1; - if let Some(f) = self.fault() { - return Err(Unsupported(f.to_string())); - } - let mut batch = Some(&mut last_submit); - self.run_cell(device, queue, encoder, doc.id, &plan, &runs, &paged, cell, &fr, &chunks, checkpoint, &mut stats, sink, &mut batch); - if let Some(f) = self.fault() { - return Err(Unsupported(f.to_string())); - } - } - // A page didn't fit even after evicting: this refresh goes to the CPU, the next one - // tries the GPU again (#6563). - if let Some(e) = self.layer_alloc.take() { - return Err(Unsupported(e)); - } - let (evicted, bytes) = self.evict(); - stats.evicted += evicted; - freed = freed.saturating_add(bytes.saturating_add(std::mem::take(&mut self.admit_freed))); - if flush && (self.staged >= flush_bytes || work >= FLUSH_WORK || freed >= flush_bytes || self.recorded >= FLUSH_OPS) { - submit_batch(device, queue, encoder, self.health.as_ref(), self.timer.as_mut(), &mut last_submit); - self.staged = 0; - self.recorded = 0; - work = 0; - freed = 0; - stats.flushes += 1; - // The device was lost mid-refresh: issue no more work. - if let Some(f) = self.fault() { - return Err(Unsupported(f.to_string())); - } - } - } - - // Evict this document's textures whose layers are gone (hidden layers stay resident so - // toggling visibility costs no upload). - let frame = self.frame; - let live: std::collections::HashSet = doc.walk().into_iter().map(|(_, _, l)| l.id).collect(); - self.residents.retain(|(id, _, _), r| r.doc != doc.id || r.last_used == frame || live.contains(id)); - self.fx.retain(|(id, _), e| e.doc != doc.id || e.last_used == frame || live.contains(id)); - stats.evicted += self.evict().0; - self.temps.retain(|(_, used)| frame.saturating_sub(*used) < 240); - self.evict_patterns(); - Ok(stats) - } - - /// Drop the pattern textures no frame has painted with for [`PATTERN_IDLE_FRAMES`] frames, - /// then the least recently painted ones over the pattern budget. Never one this frame painted - /// with: it would only be uploaded again on the next frame. - fn evict_patterns(&mut self) { - let frame = self.frame; - self.patterns.retain(|_, p| frame.saturating_sub(p.last_used) < PATTERN_IDLE_FRAMES); - let mut total = self.pattern_cache_bytes(); - if total > self.pattern_budget { - let mut lru: Vec<(u64, String, u64)> = - self.patterns.iter().filter(|(_, p)| p.last_used != frame).map(|(k, p)| (p.last_used, k.clone(), p.bytes)).collect(); - lru.sort_unstable(); - for (_, key, bytes) in lru { - if total <= self.pattern_budget { - break; - } - self.patterns.remove(&key); - total = total.saturating_sub(bytes); - } - } - } - - /// Keep resident pages within the resident budget and the effect cache within - /// its budget, least recently used first. Never drops what the current cell uses, nor - /// whole-region effect maps drawn this frame. Returns how many textures were dropped and - /// their bytes. - fn evict(&mut self) -> (usize, u64) { - let (mut n, mut freed) = self.evict_residents(self.resident_budget, 0, None); - let mut total = self.fx_cache_bytes(); - let fx_budget = usize::try_from(self.fx_budget).unwrap_or(usize::MAX); - if total > fx_budget { - let (frame, stamp) = (self.frame, self.stamp); - let mut lru: Vec<((u64, u64), FxKey)> = self - .fx - .iter() - .filter(|(k, e)| e.last_used != frame || (k.1.is_some() && e.stamp != stamp)) - .map(|(k, e)| ((e.last_used, e.stamp), *k)) - .collect(); - lru.sort_unstable_by_key(|c| c.0); - for (_, k) in lru { - if total <= fx_budget { - break; - } - if let Some(e) = self.fx.remove(&k) { - total = total.saturating_sub(e.bytes()); - n += 1; - freed += e.bytes() as u64; - } - } - } - (n, freed) - } - - /// Drop least recently used resident pages until `incoming` more bytes fit in `budget`. - /// Never drops what the current cell uses, nor `keep`. Returns how many pages were dropped - /// and their bytes. - fn evict_residents(&mut self, budget: u64, incoming: u64, keep: Option) -> (usize, u64) { - let stamp = self.stamp; - let pages: Vec<(u64, ResKey, u64)> = - self.residents.iter().filter(|(k, r)| r.stamp != stamp && Some(**k) != keep).map(|(k, r)| (r.stamp, *k, r.bytes())).collect(); - let (mut n, mut freed) = (0, 0u64); - for k in lru_victims(pages, self.resident_bytes(), incoming, budget) { - if let Some(r) = self.residents.remove(&k) { - n += 1; - freed += r.bytes(); - } - } - (n, freed) - } - - /// Create the page texture for `key`, `bytes` large. Least recently used pages make room in - /// the budget first; when the device is still out of memory, every page the current cell - /// doesn't use is dropped and creation is tried once more (#6563). `None` (with - /// `layer_alloc` set) when it still fails: `render` submits the recorded work, which can still - /// hold the dropped pages, and runs the cell once more; after that the CPU draws the refresh. - fn create_layer_texture( - &mut self, - device: &wgpu::Device, - desc: &wgpu::TextureDescriptor<'_>, - key: ResKey, - bytes: u64, - stats: &mut Stats, - ) -> Option { - let replaced = self.residents.get(&key).map_or(0, Resident::bytes); - let (n, dropped) = self.evict_residents(self.resident_budget, bytes.saturating_sub(replaced), Some(key)); - stats.evicted += n; - self.admit_freed = self.admit_freed.saturating_add(dropped); - // WebGPU reports errors asynchronously: its failures reach the health callbacks. - if cfg!(target_arch = "wasm32") { - return Some(device.create_texture(desc)); - } - for retry in [false, true] { - let (texture, mut error) = first_error(device, || device.create_texture(desc)); - if error.is_none() && self.fail_allocs > 0 { - self.fail_allocs -= 1; - error = Some(wgpu::Error::OutOfMemory { source: "out of memory (test hook)".into() }); - } - match error { - None => return Some(texture), - Some(wgpu::Error::OutOfMemory { .. }) if !retry => { - let (n, dropped) = self.evict_residents(0, 0, Some(key)); - stats.evicted += n; - self.admit_freed = self.admit_freed.saturating_add(dropped); - } - Some(wgpu::Error::OutOfMemory { .. }) => { - self.layer_alloc = Some(OVER_BUDGET.into()); - return None; - } - Some(e) => { - self.layer_alloc = Some(format!("GPU layer texture failed: {e}")); - return None; - } - } - } - self.layer_alloc = Some(OVER_BUDGET.into()); - None - } - - /// Per-frame resources of `plan`: the tile area of each pass's surfaces, its LUT and pattern. - fn frame_res(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, canvas: Rect, plan: &Plan<'_>) -> FrameRes { - let grid = tile_grid(canvas); - let area = |s: &Surface| s.tile_bounds().intersect(&grid); - let areas = plan - .passes - .iter() - .map(|p| (p.tex.as_ref().map_or(Rect::EMPTY, |t| area(t.surface.get())), p.mask.as_ref().map_or(Rect::EMPTY, |m| area(m.surface.get())))) - .collect(); - let luts = plan.passes.iter().map(|p| p.lut.as_ref().map(|rows| lut_texture(device, queue, rows))).collect(); - let patterns = plan.passes.iter().map(|p| p.pattern.map(|pat| self.pattern_view(device, queue, pat))).collect(); - FrameRes { areas, luts, patterns } - } - - /// Bring the pages of `cell` that `plan` samples up to date and resolve its effect maps. - #[allow(clippy::too_many_arguments)] - fn bind_cell( - &mut self, - device: &wgpu::Device, - queue: &wgpu::Queue, - encoder: &mut wgpu::CommandEncoder, - doc: DocId, - plan: &Plan<'_>, - paged: &[bool], - cell: Cell, - fr: &FrameRes, - first_pass: usize, - stats: &mut Stats, - ) -> Bound { - let cr = cell_rect(cell, self.page); - let mut views: Vec<(Option, Option)> = Vec::with_capacity(plan.passes.len()); - let mut keys: Vec = Vec::new(); - let mut maps = Vec::with_capacity(plan.passes.len()); - for (i, p) in plan.passes.iter().enumerate() { - if i < first_pass { - views.push((None, None)); - maps.push(None); - continue; - } - let (ta, ma) = fr.areas.get(i).copied().unwrap_or((Rect::EMPTY, Rect::EMPTY)); - let tex = - p.tex.as_ref().and_then(|t| self.sync(device, queue, encoder, doc, (t.layer, t.role, cell), t.surface.get(), ta.intersect(&cr), stats)).map( - |(k, r)| { - keys.push(k); - (keys.len() - 1, r) - }, - ); - let mask = p - .mask - .as_ref() - .and_then(|m| self.sync(device, queue, encoder, doc, (m.layer, Role::Mask, cell), m.surface.get(), ma.intersect(&cr), stats)) - .map(|(k, r)| { - keys.push(k); - (keys.len() - 1, r) - }); - views.push((tex, mask)); - maps.push(p.map.and_then(|m| { - let f = plan.fx.get(m.fx)?; - let key = (f.layer.id, paged.get(m.fx).copied().unwrap_or(false).then_some(cell)); - let e = self.fx.get(&key)?; - if m.item == plan::SHAPE_MAP { - return Some((e.shape.view.clone(), e.region)); - } - let t = e.progs.get(m.item)?.maps.get(m.map)?.as_ref()?; - Some((t.view.clone(), e.region)) - })); - } - Bound { views, keys, maps } - } - - /// Run `plan` (drawn as `runs`, its `batch_runs`) over the `chunks` of one page cell - /// (document rects, at most a chunk square), handing each finished chunk to `sink`. - #[allow(clippy::too_many_arguments)] - fn run_cell( - &mut self, - device: &wgpu::Device, - queue: &wgpu::Queue, - encoder: &mut wgpu::CommandEncoder, - doc: DocId, - plan: &Plan<'_>, - runs: &[usize], - paged: &[bool], - cell: Cell, - fr: &FrameRes, - chunks: &[Rect], - checkpoint: Option, - stats: &mut Stats, - sink: &mut dyn FnMut(&mut wgpu::CommandEncoder, ChunkOut<'_>), - // The previous intermediate submit, when this refresh may submit in between. - batch: &mut Option<&mut Option>, - ) { - if chunks.is_empty() { - return; - } - // Chunks may hold different checkpoints: bind from the lowest one any of them resumes at. - let first_pass = checkpoint - .and_then(|_| chunks.iter().map(|c| self.prefix.restore_point(*c).map(|r| r.pass_end)).try_fold(usize::MAX, |m, p| Some(m.min(p?)))) - .unwrap_or(0); - let bound = self.bind_cell(device, queue, encoder, doc, plan, paged, cell, fr, first_pass, stats); - // A page couldn't be created: draw nothing with the pages missing (the caller ends the refresh). - if self.layer_alloc.is_some() { - return; - } - - // Chunk pool. - while self.pool.len() < plan.slots as usize { - let t = device.create_texture(&wgpu::TextureDescriptor { - label: Some("pc_compose_chunk"), - size: wgpu::Extent3d { width: self.chunk, height: self.chunk, depth_or_array_layers: 1 }, - mip_level_count: 1, - sample_count: 1, - dimension: wgpu::TextureDimension::D2, - format: self.acc_format, - usage: wgpu::TextureUsages::RENDER_ATTACHMENT - | wgpu::TextureUsages::TEXTURE_BINDING - | wgpu::TextureUsages::COPY_SRC - | wgpu::TextureUsages::COPY_DST, - view_formats: &[], - }); - let v = t.create_view(&Default::default()); - self.pool.push((t, v)); - } - - // Uniforms: chunk records, then one record per pass. encode_scoped preflight checked - // the length, device capacity and dynamic offsets before any GPU work for this frame. - let op_base = chunks.len() as u64 * STRIDE; - let mut data = vec![0u8; (op_base + plan.passes.len() as u64 * STRIDE) as usize]; - for (i, c) in chunks.iter().enumerate() { - let w = words(&[I(c.x0), I(c.y0), I(c.width() as i32), I(c.height() as i32)]); - data[i * STRIDE as usize..][..w.len()].copy_from_slice(&w); - } - for (i, p) in plan.passes.iter().enumerate() { - if i < first_pass { - continue; - } - let (tex, mask) = bound.views[i]; - let map = bound.maps[i].as_ref().map(|(_, r)| *r); - let run = runs.get(i).copied().unwrap_or(1); - let w = if run > 1 { - let extras: Vec<_> = (i + 1..i + run).filter_map(|j| Some((plan.passes.get(j)?, bound.views.get(j).and_then(|v| v.0).map(|t| t.1)))).collect(); - batch_op_words(p, tex.map(|t| t.1), mask.map(|m| m.1), &extras) - } else { - op_words(p, tex.map(|t| t.1), mask.map(|m| m.1), map) - }; - let off = (op_base + i as u64 * STRIDE) as usize; - data[off..][..w.len()].copy_from_slice(&w); - } - let ubuf = device.create_buffer(&wgpu::BufferDescriptor { - label: Some("pc_compose_uniforms"), - size: data.len() as u64, - usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, - mapped_at_creation: false, - }); - queue.write_buffer(&ubuf, 0, &data); - let bg0 = uniform_group(device, &self.kit.bgl0, &ubuf); - - // Per-pass texture bind groups (chunk-independent: pool slots are reused per chunk). - let dummy = &self.kit.dummy; - let resident_views: Vec<&wgpu::TextureView> = bound.keys.iter().map(|k| self.residents.get(k).map_or(dummy, |r| &r.view)).collect(); - let mut bg1 = Vec::with_capacity(plan.passes.len()); - for (i, p) in plan.passes.iter().enumerate() { - if i < first_pass || p.kernel.entry().is_none() { - bg1.push(None); - continue; - } - let slot = |s: Option| s.map_or(dummy, |s| &self.pool[s as usize].1); - let (tex, mask) = &bound.views[i]; - let tv = tex.map_or(slot(p.d), |(k, _)| resident_views[k]); - let mv = mask.map_or(dummy, |(k, _)| resident_views[k]); - let lv = fr.luts.get(i).and_then(Option::as_ref).map_or(dummy, |(_, v)| v); - let map = bound.maps[i].as_ref().map_or(dummy, |(v, _)| v); - let pat = fr.patterns.get(i).and_then(Option::as_ref).unwrap_or(dummy); - let run = runs.get(i).copied().unwrap_or(1); - if run > 1 { - // The extra layers' pixels in tex_b, tex_c and map_tex (`batch_layer`). - let extra = |e: usize| bound.views.get(i + e).and_then(|v| v.0).map_or(dummy, |(k, _)| resident_views[k]); - bg1.push(Some(texture_group(device, &self.kit.bgl1, &[slot(p.a), extra(1), tv, mv, lv, extra(2), extra(3), pat]))); - continue; - } - bg1.push(Some(texture_group(device, &self.kit.bgl1, &[slot(p.a), slot(p.b), tv, mv, lv, slot(p.c), map, pat]))); - } - - for (ci, c) in chunks.iter().enumerate() { - let mut resume = 0; - if let Some(cp) = checkpoint.and_then(|_| self.prefix.restore_point(*c)) - && let Some((dst, _)) = self.pool.get(cp.slot as usize) - && self.prefix.copy_out(encoder, *c, dst) - { - resume = cp.pass_end; - stats.prefix_hits = stats.prefix_hits.saturating_add(1); - stats.prefix_passes_skipped = stats.prefix_passes_skipped.saturating_add(resume); - } - // Passes drawn inside the previous `fs_layerbatch` pass. - let mut batched_to = 0; - for (i, p) in plan.passes.iter().enumerate() { - if i < resume || i < batched_to { - continue; - } - // Chunk textures, uniforms and bind groups outlive the submit, and the queue - // keeps the order, so a chunk may continue in the next command buffer. - if self.recorded >= FLUSH_OPS - && let Some(last) = batch.as_deref_mut() - { - submit_batch(device, queue, encoder, self.health.as_ref(), self.timer.as_mut(), last); - self.staged = 0; - self.recorded = 0; - stats.flushes += 1; - if self.fault().is_some() { - return; - } - } - // Also after resuming from a lower checkpoint: the chunk moves up to this one. - if resume < i - && let Some(cp) = checkpoint.filter(|cp| cp.pass_end == i) - && let Some((src, _)) = self.pool.get(cp.slot as usize) - { - self.prefix.capture(device, encoder, *c, src, cp); - } - let scissor = match p.clip { - Some(clip) => { - let r = clip.intersect(c); - if r.is_empty() { - continue; - } - Rect::new(r.x0 - c.x0, r.y0 - c.y0, r.x1 - c.x0, r.y1 - c.y0) - } - None => Rect::new(0, 0, c.width() as i32, c.height() as i32), - }; - match p.kernel { - Kernel::CopyRect | Kernel::CopyFull => { - // The planner always gives copies a source. - let Some(a) = p.a else { continue }; - let src = &self.pool[a as usize].0; - let dst = &self.pool[p.dst as usize].0; - encoder.copy_texture_to_texture( - wgpu::TexelCopyTextureInfo { - texture: src, - mip_level: 0, - origin: wgpu::Origin3d { x: scissor.x0 as u32, y: scissor.y0 as u32, z: 0 }, - aspect: wgpu::TextureAspect::All, - }, - wgpu::TexelCopyTextureInfo { - texture: dst, - mip_level: 0, - origin: wgpu::Origin3d { x: scissor.x0 as u32, y: scissor.y0 as u32, z: 0 }, - aspect: wgpu::TextureAspect::All, - }, - wgpu::Extent3d { width: scissor.width(), height: scissor.height(), depth_or_array_layers: 1 }, - ); - self.recorded += 1; - continue; - } - _ => {} - } - self.recorded += 1; - // A run draws as one pass into the slot its last layer writes. - let run = runs.get(i).copied().unwrap_or(1); - let (kernel, dst) = match plan.passes.get(i + run - 1) { - Some(last) if run > 1 => { - batched_to = i + run; - stats.layers_batched = stats.layers_batched.saturating_add(run - 1); - let kernel = plan.passes.get(i..i + run).map_or(Kernel::LayerBatch, batch_kernel); - if kernel == Kernel::LayerBatchNormal { - stats.normal_batches = stats.normal_batches.saturating_add(1); - } - (kernel, last.dst) - } - _ => (p.kernel, p.dst), - }; - let target = &self.pool[dst as usize].1; - let clear = p.kernel == Kernel::Clear; - let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { - label: Some("pc_compose_pass"), - color_attachments: &[Some(wgpu::RenderPassColorAttachment { - view: target, - resolve_target: None, - depth_slice: None, - ops: wgpu::Operations { - load: if clear { wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT) } else { wgpu::LoadOp::Load }, - store: wgpu::StoreOp::Store, - }, - })], - depth_stencil_attachment: None, - timestamp_writes: None, - occlusion_query_set: None, - multiview_mask: None, - }); - if clear { - continue; - } - pass.set_pipeline(&self.kit.pipelines[&(kernel, self.acc_format)]); - pass.set_scissor_rect(scissor.x0 as u32, scissor.y0 as u32, scissor.width(), scissor.height()); - pass.set_bind_group(0, &bg0, &[(ci as u64 * STRIDE) as u32, (op_base + i as u64 * STRIDE) as u32]); - pass.set_bind_group(1, bg1[i].as_ref(), &[]); - pass.draw(0..3, 0..1); - } - if resume < plan.passes.len() - && let Some(cp) = checkpoint.filter(|cp| cp.pass_end == plan.passes.len()) - && let Some((src, _)) = self.pool.get(cp.slot as usize) - { - self.prefix.capture(device, encoder, *c, src, cp); - } - let (t, v) = &self.pool[plan.root as usize]; - sink(encoder, ChunkOut { rect: *c, texture: t, view: v }); - } - } - - /// Upload changed tiles of `surface` within `region` (its tile area inside one page cell); - /// returns the resident key and its region (x, y, w, h). - #[allow(clippy::too_many_arguments)] - fn sync( - &mut self, - device: &wgpu::Device, - queue: &wgpu::Queue, - encoder: &mut wgpu::CommandEncoder, - doc: DocId, - key: ResKey, - surface: &Surface, - region: Rect, - stats: &mut Stats, - ) -> Option<(ResKey, [i32; 4])> { - // An earlier page of this cell didn't fit: the refresh ends after the cell anyway. - if region.is_empty() || self.layer_alloc.is_some() { - return None; - } - let format = surface.format(); - let kind = TexKind::for_surface(key.1, format); - let cmyk = if format.mode == photocraft_color::ColorMode::Cmyk { self.cmyk } else { 0 }; - let default_pixel = surface.default_pixel(); - let default_bits: Vec = default_pixel.iter().map(|v| v.to_bits()).collect(); - let stale = self - .residents - .get(&key) - .is_none_or(|r| r.region != region || r.kind != kind || r.format != format || r.cmyk != cmyk || r.default_bits != default_bits); - if stale { - let desc = wgpu::TextureDescriptor { - label: Some("pc_compose_layer"), - size: wgpu::Extent3d { width: region.width(), height: region.height(), depth_or_array_layers: 1 }, - mip_level_count: 1, - sample_count: 1, - dimension: wgpu::TextureDimension::D2, - format: kind.format(), - usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::COPY_SRC, - view_formats: &[], - }; - let bytes = region.width() as u64 * region.height() as u64 * kind.bytes_per_pixel() as u64; - let texture = self.create_layer_texture(device, &desc, key, bytes, stats)?; - let view = texture.create_view(&Default::default()); - let default_nonzero = default_pixel.iter().any(|v| *v != 0.0); - let mut r = Resident { - texture, - view, - region, - kind, - format, - tiles: HashMap::new(), - default_nonzero, - default_bits: default_bits.clone(), - doc, - last_used: 0, - stamp: 0, - cmyk, - ordered: false, - }; - // Only the region moved (painting past a layer's tiles grows it): keep the texels the - // old texture already holds instead of converting and uploading every tile again. - let kept = self.residents.remove(&key).map_or(Rect::EMPTY, |old| keep_overlap(device, queue, &old, &mut r)); - // A new layer whose tiles another resident already holds (a duplicate shares its - // source's tiles) starts as a GPU copy of that texture. Duplicating a 20 MP photo - // converted and uploaded every tile again. - let shares = - |o: &Resident| region.tiles().filter(|c| surface.tile(*c).is_some_and(|t| o.tiles.get(c).is_some_and(|ot| Arc::ptr_eq(ot, t)))).count(); - let donor = self - .residents - .iter() - .filter(|(k, o)| k.1 == key.1 && o.region == region && o.kind == kind && o.format == format && o.cmyk == cmyk && o.default_bits == default_bits) - .map(|(k, o)| (shares(o), *k)) - .filter(|(n, _)| *n > 0) - .max_by_key(|(n, _)| *n); - if kept.is_empty() - && let Some((n, o)) = donor.and_then(|(n, k)| Some((n, self.residents.get_mut(&k)?))) - { - // Recorded in the frame's encoder, after the writes and copies that brought the - // donor up to date ([`keep_overlap`]'s own submission would run before those). - o.ordered = true; - encoder.copy_texture_to_texture( - o.texture.as_image_copy(), - r.texture.as_image_copy(), - wgpu::Extent3d { width: region.width(), height: region.height(), depth_or_array_layers: 1 }, - ); - r.tiles = o.tiles.clone(); - r.ordered = true; - stats.tiles_shared += n; - } else { - // A new texture starts zeroed: write the tiles that are present, and the default - // pixel where they are missing if it isn't zero. Coordinates sharing a tile (a - // solid fill, the default) take one upload and GPU copies (#1774). Kept tiles are - // brought up to date below, like those of a resident that didn't move. - let mut present = Vec::new(); - let mut missing = Vec::new(); - for c in region.tiles().filter(|c| !kept.contains_rect(&c.rect())) { - match surface.tile(c) { - Some(t) => present.push((c, t.clone())), - None if default_nonzero => missing.push(c), - None => {} - } - } - if !missing.is_empty() { - let bytes = convert_tile(surface, None, kind, TileCoord::new(0, 0)); - self.staged += put_tiles(device, queue, encoder, &r, &missing, &bytes); - } - let staged = &mut self.staged; - convert_tiles(surface, present, kind, |t, cs, bytes| { - *staged += put_tiles(device, queue, encoder, &r, cs, bytes); - for &c in cs { - stats.tiles_uploaded += 1; - stats.bytes_uploaded += bytes.len(); - r.tiles.insert(c, t.clone()); - } - }); - } - // Tiles the donor held that this surface doesn't, or holds differently, are fixed up - // by the pass over the region below. - self.residents.insert(key, r); - } - // Present: inserted above when it was missing or stale. - let r = self.residents.get_mut(&key)?; - r.last_used = self.frame; - r.stamp = self.stamp; - r.doc = doc; - let mut changed = Vec::new(); - let mut gone = Vec::new(); - for c in region.tiles() { - match surface.tile(c) { - Some(t) => { - if !r.tiles.get(&c).is_some_and(|old| Arc::ptr_eq(old, t)) { - changed.push((c, t.clone())); - } - } - None => { - if r.tiles.remove(&c).is_some() { - gone.push(c); - } - } - } - } - if !gone.is_empty() { - // A tile that went away reads as the default pixel again. - let bytes = if r.default_nonzero { - convert_tile(surface, None, kind, TileCoord::new(0, 0)) - } else { - vec![0u8; (TILE_SIZE * TILE_SIZE) as usize * kind.bytes_per_pixel()] - }; - self.staged += put_tiles(device, queue, encoder, r, &gone, &bytes); - } - let staged = &mut self.staged; - convert_tiles(surface, changed, kind, |t, cs, bytes| { - *staged += put_tiles(device, queue, encoder, r, cs, bytes); - for &c in cs { - stats.tiles_uploaded += 1; - stats.bytes_uploaded += bytes.len(); - r.tiles.insert(c, t.clone()); - } - }); - Some((key, [region.x0, region.y0, region.width() as i32, region.height() as i32])) - } - - /// Premultiplied RGBA32F texture of a pattern as it paints in the document's mode (cached by - /// pixel identity and mode). - fn pattern_view(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, pat: &Pattern) -> wgpu::TextureView { - let fp = pat.surface.tiles().fold((pat.width as u64) << 32 | pat.height as u64, |acc, (c, t)| { - acc.wrapping_mul(0x9e37_79b9_7f4a_7c15) ^ (Arc::as_ptr(t) as usize as u64) ^ ((c.tx as u64) << 20) ^ c.ty as u64 - }); - let mode = self.pattern_mode; - let key = format!("{}\u{0}{}\u{0}{mode:?}", pat.id, pat.name); - let format = pat.surface.format(); - // Unstored tiles read the default pixel, interpreted in the source format. - let default_bits: Vec = pat.surface.default_pixel().iter().map(|v| v.to_bits()).collect(); - let (doc, last_used) = (self.pattern_doc, self.frame); - if let Some(cached) = self.patterns.get_mut(&key) - && cached.fingerprint == fp - && cached.format == format - && cached.default_bits == default_bits - { - cached.doc = doc; - cached.last_used = last_used; - return cached.texture.view.clone(); - } - let (w, h) = (pat.width, pat.height); - let px = photocraft_compose::pattern::pattern_rgba(pat, mode); - let bytes: Vec = px.iter().flat_map(|q| [q[0] * q[3], q[1] * q[3], q[2] * q[3], q[3]]).flat_map(f32::to_le_bytes).collect(); - let t = Tex::new(device, "pc_pattern", w, h, wgpu::TextureFormat::Rgba32Float, wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST); - queue.write_texture( - wgpu::TexelCopyTextureInfo { texture: &t.texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, - &bytes, - wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(w * 16), rows_per_image: Some(h) }, - wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }, - ); - let v = t.view.clone(); - let bytes = u64::from(w.max(1)) * u64::from(h.max(1)) * 16; - self.patterns.insert(key, CachedPattern { fingerprint: fp, format, default_bits, texture: t, doc, last_used, bytes }); - v - } - - /// An R32F temporary at least `region`-sized (the smallest that fits) not in `taken`. - /// Stages only read what they wrote, inside the region, so a larger one is as good; page - /// windows of different sizes share them. - fn temp(&mut self, device: &wgpu::Device, region: Rect, taken: &[wgpu::TextureView]) -> wgpu::TextureView { - let (w, h) = (region.width(), region.height()); - let frame = self.frame; - let fit = self - .temps - .iter_mut() - .filter(|(t, _)| { - let s = t.texture.size(); - s.width >= w && s.height >= h && !taken.contains(&t.view) - }) - .min_by_key(|(t, _)| t.texture.size().width as u64 * t.texture.size().height as u64); - if let Some((t, used)) = fit { - *used = frame; - return t.view.clone(); - } - let t = Tex::map(device, "pc_fx_temp", region, MAP32); - let v = t.view.clone(); - self.temps.push((t, frame)); - v - } - - /// Build or update the effect maps of one layer over `region`: its whole effect region, or - /// the window of one page cell (`key.1`) grown by the effects' reach. - #[allow(clippy::too_many_arguments)] - fn sync_fx( - &mut self, - device: &wgpu::Device, - queue: &wgpu::Queue, - encoder: &mut wgpu::CommandEncoder, - doc: &Document, - f: &plan::FxLayer<'_>, - key: FxKey, - region: Rect, - stats: &mut Stats, - ) -> Result<(), Unsupported> { - let layer = f.layer; - let canvas = doc.bounds(); - let is_group = matches!(layer.content, LayerContent::Group(_)); - let shape_key = if is_group { fx::group_key(layer, &doc.global_light, &mut |_| {}) } else { fx::shape_key(layer, canvas) }; - let (content_src, mask_src) = if is_group { (None, None) } else { fx::shape_sources(layer) }; - let frame = self.frame; - let (rw, rh) = (region.width(), region.height()); - - // What changed: everything (new settings / size), the position only, some tiles, or - // nothing. - let mut damage = Rect::EMPTY; - let prev = self.fx.get(&key).filter(|e| e.shape_key == shape_key).map(|e| e.region); - let mut rebuild = true; - if prev == Some(region) - && let Some(e) = self.fx.get(&key) - { - rebuild = false; - for (old, cur) in e.tiles.iter().zip([content_src, mask_src]) { - let d = match (old, cur) { - (Some(o), Some(s)) => fx::damage(o, s), - (None, None) => Rect::EMPTY, - // A source appeared or vanished (the key changes with it too). - _ => region, - }; - damage = if damage.is_empty() { d } else { damage.union(&d) }; - } - damage = damage.intersect(®ion); - } else if let Some(old) = prev - && (old.width(), old.height()) == (rw, rh) - && !region.is_empty() - { - // Moved by whole pixels: maps are computed relative to the region, so if the shape - // moved unchanged with it, every map is still exact. - let v = fx::shape(doc, layer, region); - if let Some(e) = self.fx.get_mut(&key) - && v == e.shape_cpu - { - e.region = region; - rebuild = false; - } - } - if rebuild { - let shape = Tex::map(device, "pc_fx_shape", region, MAP32); - let n = rw as usize * rh as usize; - self.fx.insert( - key, - FxEntry { - doc: doc.id, - region, - shape_key, - tiles: [None, None], - _pin: if is_group { - let mut pin = Vec::new(); - fx::group_key(layer, &doc.global_light, &mut |t| pin.push(Arc::downgrade(t))); - pin - } else { - Vec::new() - }, - shape_cpu: vec![0.0; n], - shape, - fields: HashMap::new(), - progs: Vec::new(), - last_used: frame, - stamp: 0, - }, - ); - damage = region; - } - // Present: kept or (re)inserted above. - let stamp = self.stamp; - let Some(e) = self.fx.get_mut(&key) else { return Ok(()) }; - e.last_used = frame; - e.stamp = stamp; - e.doc = doc.id; - e.tiles = [content_src.map(fx::snapshot), mask_src.map(fx::snapshot)]; - if region.is_empty() { - return Ok(()); - } - - let t_trace = web_time_now(); - let mut staged = 0u64; - // Shape over the damage (compose's own alpha). - if !damage.is_empty() { - stats.fx_shapes += 1; - let v = fx::shape(doc, layer, damage); - fx::paste(&mut e.shape_cpu, region, damage, &v); - e.shape.write_r32(queue, region, damage, &v); - staged += v.len() as u64 * 4; - } - - // Programs, and the distance fields they read (max reach per field). - // Filled shapes stroke their outline (the effect shape); others estimate it. - let vector_shape = matches!(layer.content, LayerContent::Shape(_)) && photocraft_compose::effect_outline(layer).is_none(); - let anchor = layer.effects.reference.unwrap_or((f64::from(f.bounds.x0), f64::from(f.bounds.y0))); - let progs: Vec = - layer.effects.items.iter().filter(|e| e.enabled()).map(|e| fx::program_with(e, &doc.global_light, vector_shape, &doc.patterns, anchor)).collect(); - let want = field_reaches(&progs); - e.fields.retain(|k, _| want.contains_key(k)); - // Each field to recompute: over which rectangle, exact up to which reach. - let jobs: Vec<(FieldKind, Rect, i32)> = want - .iter() - .filter_map(|(&kind, &reach)| match e.fields.get(&kind).map(|(r, _)| *r) { - Some(r) if r >= reach => (!damage.is_empty()).then(|| (kind, damage.inflate(fx::field_radius(kind, r)).intersect(®ion), r)), - _ => Some((kind, region, reach)), - }) - .collect(); - // A chiselled bevel's two fields are asked for and kept together (`fx::bevel_fields`), so they - // are recomputed together, over one rectangle at one reach. - let job = |k: FieldKind| jobs.iter().find(|j| j.0 == k).map(|j| (j.1, j.2)); - let (bevel_in, bevel_out) = (job(FieldKind::BevelInside), job(FieldKind::BevelOutside)); - if bevel_in != bevel_out { - return Err(Unsupported(format!("bevel fields of `{}` out of step: inside {bevel_in:?}, outside {bevel_out:?}", layer.name))); - } - for (kind, out, reach) in jobs { - let fields = match kind { - FieldKind::BevelInside => { - let [inside, outside] = fx::bevel_fields(reach, &e.shape_cpu, region, out); - vec![(FieldKind::BevelInside, inside), (FieldKind::BevelOutside, outside)] - } - // Computed with BevelInside, over the same rectangle at the same reach (checked above). - FieldKind::BevelOutside => continue, - _ => vec![(kind, fx::field(kind, reach, &e.shape_cpu, region, out))], - }; - for (kind, v) in fields { - if e.fields.get(&kind).is_none_or(|(r, _)| *r < reach) { - e.fields.insert(kind, (reach, Tex::map(device, "pc_fx_field", region, MAP32))); - } - if let Some((_, t)) = e.fields.get(&kind) { - t.write_r32(queue, region, out, &v); - } - staged += v.len() as u64 * 4; - stats.fx_pixels += out.width() as u64 * out.height() as u64; - } - } - - if let Some(t) = t_trace.filter(|_| !damage.is_empty()) { - eprintln!("effect maps of `{}`: shape + distance fields over {damage:?} in {:.2} ms (CPU)", layer.name, t.elapsed().as_secs_f64() * 1000.0); - } - e.progs.truncate(progs.len()); - while e.progs.len() < progs.len() { - e.progs.push(ProgState { key: 0, maps: Vec::new() }); - } - self.staged += staged; - for (i, prog) in progs.iter().enumerate() { - if prog.maps == 0 { - continue; - } - let Some(e) = self.fx.get_mut(&key) else { return Ok(()) }; - let same = e.progs[i].key == prog.key && e.progs[i].maps.len() == prog.maps; - let d = if same { damage } else { region }; - if d.is_empty() { - continue; - } - if !same { - e.progs[i] = ProgState { - key: prog.key, - maps: (0..prog.maps).map(|k| prog.stages.iter().any(|s| s.out == Some(k)).then(|| Tex::map(device, "pc_fx_map", region, MAP16))).collect(), - }; - } - stats.fx_programs += 1; - self.run_program(device, queue, encoder, key, i, prog, d, stats); - } - Ok(()) - } - - /// Record the passes of `prog` (maps of item `item` of `layer`) recomputing damage `d`. - #[allow(clippy::too_many_arguments)] - fn run_program( - &mut self, - device: &wgpu::Device, - queue: &wgpu::Queue, - encoder: &mut wgpu::CommandEncoder, - key: FxKey, - item: usize, - prog: &fx::MapProgram, - d: Rect, - stats: &mut Stats, - ) { - let pattern_views: Vec> = - prog.stages.iter().map(|s| s.pattern.as_ref().map(|p| self.pattern_view(device, queue, p))).collect(); - let Some(e) = self.fx.get(&key) else { return }; - let region = e.region; - let shape = e.shape.view.clone(); - let finals: Vec> = e.progs[item].maps.iter().map(|m| m.as_ref().map(|t| t.view.clone())).collect(); - let fields: HashMap = e.fields.iter().map(|(k, (r, t))| (*k, (*r, t.view.clone()))).collect(); - let windows = prog.windows(d, region, &|k| fields.get(&k).map_or(0, |f| f.0)); - let (assign, count) = prog.temps(); - let mut temps: Vec = Vec::with_capacity(count); - for _ in 0..count { - let v = self.temp(device, region, &temps); - temps.push(v); - } - // `None` only if a program's map or temporary wasn't allocated, which `sync_fx` and - // `MapProgram::temps` rule out. - let target_of = |i: usize| -> Option<(wgpu::TextureView, wgpu::TextureFormat)> { - match prog.stages[i].out { - Some(k) => Some((finals.get(k)?.clone()?, MAP16)), - None => Some((temps.get((*assign.get(i)?)?)?.clone(), MAP32)), - } - }; - let view_of = |inp: Option| -> Option { - match inp? { - fx::In::Shape => Some(shape.clone()), - fx::In::Field(k) => fields.get(&k).map(|f| f.1.clone()), - fx::In::Val(k) => target_of(k).map(|t| t.0), - } - }; - let mut draws = Vec::with_capacity(prog.stages.len()); - for (i, s) in prog.stages.iter().enumerate() { - let w = windows[i]; - if w.is_empty() { - continue; - } - stats.fx_pixels += w.width() as u64 * w.height() as u64; - let Some((target, format)) = target_of(i) else { continue }; - let mut p = plan::Pass::new(s.kernel, 0); - p.params[0] = s.p0; - p.params[1] = s.p1; - p.params[3] = s.p3; - p.extra = s.p4; - draws.push(MapDraw { - kernel: s.kernel, - format, - target, - scissor: [(w.x0 - region.x0) as u32, (w.y0 - region.y0) as u32, w.width(), w.height()], - space: [region.x0, region.y0, region.width() as i32, region.height() as i32], - op: op_words(&p, None, None, None), - views: [view_of(s.a), view_of(s.b), view_of(s.s), None, None, None, None, pattern_views[i].clone()], - lut: s.lut.clone(), - }); - } - self.kit.run(device, queue, encoder, &draws); - } -} - -/// A start time when `PHOTOCRAFT_FX_TRACE=1` (it prints the CPU time of effect shapes and -/// distance fields); never on wasm. -fn web_time_now() -> Option { - #[cfg(not(target_arch = "wasm32"))] - { - static T: std::sync::OnceLock = std::sync::OnceLock::new(); - T.get_or_init(|| std::env::var_os("PHOTOCRAFT_FX_TRACE").is_some()).then(std::time::Instant::now) - } - #[cfg(target_arch = "wasm32")] - None -} - -/// The uniform record of a pass. -fn op_words(p: &plan::Pass<'_>, tex: Option<[i32; 4]>, mask: Option<[i32; 4]>, map: Option) -> Vec { - words(&op_values(p, tex, mask, map)) -} - -/// The uniform record of the `fs_layerbatch` pass that draws `p` (whose texture and mask cover -/// `tex` and `mask`) and then `extras`, each an unmasked plain layer's `LayerBlend` pass with the -/// area its texture covers. Layout: see `batch_layer` in compose.wgsl. -fn batch_op_words(p: &plan::Pass<'_>, tex: Option<[i32; 4]>, mask: Option<[i32; 4]>, extras: &[(&plan::Pass<'_>, Option<[i32; 4]>)]) -> Vec { - let mut v = op_values(p, tex, mask, None); - // Word offsets of the record's vec4s holding the extra layers, three each: p0, p1, p2 | p3, - // q0, q1 | q2, q3, q4. - const AT: [usize; 9] = [20, 24, 28, 32, 44, 48, 52, 56, 60]; - if let Some(kind) = v.get_mut(1) { - *kind = I(extras.len().min(AT.len() / 3) as i32); - } - for (e, (x, area)) in extras.iter().take(AT.len() / 3).enumerate() { - let r = area.unwrap_or([0; 4]); - let geo = [r[0] as f32, r[1] as f32, r[2] as f32, r[3] as f32]; - let prm = [x.opacity, x.fill, plan::mode_index(x.mode) as f32, if area.is_some() { 1.0 } else { 0.0 }]; - for (k, vals) in [geo, x.color, prm].into_iter().enumerate() { - let at = AT[e * 3 + k]; - for (c, f) in vals.into_iter().enumerate() { - if let Some(w) = v.get_mut(at + c) { - *w = F(f); - } - } - } - } - words(&v) -} - -/// The words of a pass's uniform record (`Op` in compose.wgsl). -fn op_values(p: &plan::Pass<'_>, tex: Option<[i32; 4]>, mask: Option<[i32; 4]>, map: Option) -> Vec { - let mut flags = p.flags; - let (mut to, mut ts, mut mo, mut ms) = ([0; 2], [0; 2], [0; 2], [0; 2]); - if let Some(r) = tex { - flags |= 4; - to = [r[0], r[1]]; - ts = [r[2], r[3]]; - } - let (mut density, mut mdefault) = (0.0, 1.0); - if let Some(m) = &p.mask { - flags |= 1; - density = m.density; - mdefault = m.default; - if let Some(r) = mask { - flags |= 2; - mo = [r[0], r[1]]; - ms = [r[2], r[3]]; - } - } - if p.gradient { - flags |= 8; - } - let (mpo, mps) = map.map_or(([0, 0], [0, 0]), |r| ([r.x0, r.y0], [r.width() as i32, r.height() as i32])); - let mut v = vec![ - I(plan::mode_index(p.mode)), - I(p.adjust_kind), - U(flags), - U(0), - F(p.opacity), - F(density), - F(mdefault), - F(p.fill), - I(to[0]), - I(to[1]), - I(ts[0]), - I(ts[1]), - I(mo[0]), - I(mo[1]), - I(ms[0]), - I(ms[1]), - ]; - v.extend(p.color.iter().map(|f| F(*f))); - for row in &p.params { - v.extend(row.iter().map(|f| F(*f))); - } - v.extend([I(mpo[0]), I(mpo[1]), I(mps[0]), I(mps[1])]); - v.extend(p.extra.iter().map(|f| F(*f))); - // q0..q4: only `fs_layerbatch` reads them (`batch_op_words`). - v.extend((0..20).map(|_| F(0.0))); - v -} - -/// Most layers one `fs_layerbatch` pass blends: its own and the three more its record holds. -const BATCH: usize = 4; - -/// For each pass, how many passes from it on the executor draws as one `fs_layerbatch` pass -/// (1: the pass alone). A run starts at a `LayerBlend` pass over the whole chunk (no clip) that -/// isn't a gradient (whose parameters use the words the extra layers go in), and continues while -/// the next pass is a `LayerBlend` of an unmasked plain layer (no text gamma, no Dissolve) onto -/// exactly what the previous pass wrote, a slot nothing else reads before it is written again. -/// A run never ends in the slot it reads from. -/// -/// The runs depend on the plan alone, never on the prefix cache: a compiler may give a layer -/// other bits batched than drawn alone (FXC on D3D12 does), and reusing a prefix must stay exact -/// (#5286). The cache captures and resumes only at `run_starts` instead. -fn batch_runs(plan: &Plan<'_>) -> Vec { - let passes = &plan.passes; - let n = passes.len(); - let reads = |p: &plan::Pass<'_>, s: plan::Slot| [p.a, p.b, p.c, p.d].contains(&Some(s)); - // feeds_next[i]: what pass i writes is read by pass i + 1 alone. - let feeds_next: Vec = (0..n) - .map(|i| { - let (Some(this), Some(next)) = (passes.get(i), passes.get(i + 1)) else { return false }; - let dst = this.dst; - if next.a != Some(dst) || [next.b, next.c, next.d].contains(&Some(dst)) { - return false; - } - for later in passes.iter().skip(i + 2) { - // A copy into a slot keeps what lies outside its rect: that is a read too. - if reads(later, dst) || (later.dst == dst && later.kernel == Kernel::CopyRect) { - return false; - } - if later.dst == dst { - return true; - } - } - dst != plan.root - }) - .collect(); - let lead = |p: &plan::Pass<'_>| p.kernel == Kernel::LayerBlend && p.clip.is_none() && !p.gradient; - let extra = |p: &plan::Pass<'_>| lead(p) && p.mask.is_none() && p.flags & plan::F_TEXT_GAMMA == 0 && p.mode != photocraft_color::BlendMode::Dissolve; - (0..n) - .map(|i| { - let Some(first) = passes.get(i).filter(|p| lead(p)) else { return 1 }; - let (mut k, mut best) = (1, 1); - while k < BATCH && feeds_next.get(i + k - 1).copied().unwrap_or(false) && passes.get(i + k).is_some_and(extra) { - k += 1; - if passes.get(i + k - 1).is_some_and(|p| Some(p.dst) != first.a) { - best = k; - } - } - best - }) - .collect() -} - -/// For each pass and the end of the plan, whether the executor draws `runs` (`batch_runs`) so -/// that a pass starts there rather than inside a run. -fn run_starts(runs: &[usize]) -> Vec { - let mut starts = vec![false; runs.len() + 1]; - let mut i = 0; - while let Some(s) = starts.get_mut(i) { - *s = true; - i += runs.get(i).copied().unwrap_or(1).max(1); - } - starts -} - -/// The pipeline that draws `run` (passes `batch_runs` joined): `fs_layerbatch_normal` when every -/// layer blends Normal without text gamma outside Lab documents, else `fs_layerbatch`. -fn batch_kernel(run: &[plan::Pass<'_>]) -> Kernel { - let normal = |p: &plan::Pass<'_>| p.mode == photocraft_color::BlendMode::Normal && p.flags & (plan::F_TEXT_GAMMA | plan::F_LAB) == 0; - if run.iter().all(normal) { Kernel::LayerBatchNormal } else { Kernel::LayerBatch } -} - -/// Canvas rounded out to whole tiles. -fn tile_grid(canvas: Rect) -> Rect { - let t = TILE_SIZE; - Rect::new(canvas.x0.div_euclid(t) * t, canvas.y0.div_euclid(t) * t, (canvas.x1 + t - 1).div_euclid(t) * t, (canvas.y1 + t - 1).div_euclid(t) * t) -} - -fn write_tile(queue: &wgpu::Queue, r: &Resident, c: TileCoord, bytes: &[u8]) { - let tr = c.rect(); - let bpp = r.kind.bytes_per_pixel() as u32; - queue.write_texture( - wgpu::TexelCopyTextureInfo { - texture: &r.texture, - mip_level: 0, - origin: wgpu::Origin3d { x: (tr.x0 - r.region.x0) as u32, y: (tr.y0 - r.region.y0) as u32, z: 0 }, - aspect: wgpu::TextureAspect::All, - }, - bytes, - wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(TILE_SIZE as u32 * bpp), rows_per_image: Some(TILE_SIZE as u32) }, - wgpu::Extent3d { width: TILE_SIZE as u32, height: TILE_SIZE as u32, depth_or_array_layers: 1 }, - ); -} - -/// Submit what `encoder` recorded and continue in a fresh one, then wait for the previous -/// intermediate submit (`last`), so at most two batches of uploads and evicted pages are in -/// flight. The web has no blocking wait and relies on the browser's own scheduling. -fn submit_batch( - device: &wgpu::Device, - queue: &wgpu::Queue, - encoder: &mut wgpu::CommandEncoder, - health: Option<&DeviceHealth>, - timer: Option<&mut timing::GpuTimer>, - last: &mut Option, -) { - let mut done = std::mem::replace(encoder, device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("pc_compose") })); - if let Some(t) = timer { - // One refresh, several command buffers: the measurement spans all of them. - t.split(&mut done, encoder); - } - let prev = last.replace(queue.submit([done.finish()])); - #[cfg(not(target_arch = "wasm32"))] - if let Some(prev) = prev { - match health { - Some(h) => { - h.wait(device, Some(prev)); - } - None => { - let _ = device.poll(wgpu::PollType::Wait { submission_index: Some(prev), timeout: None }); - } - } - } - #[cfg(target_arch = "wasm32")] - let _ = (prev, health); -} - -/// Distinct tiles converted per parallel batch: bounds the converted bytes held at once (64 tiles -/// of a 16-bit page are 32 MiB). -const CONVERT_BATCH: usize = 64; - -/// Write the same tile `bytes` at every coordinate in `cs` of resident `r`; returns the bytes -/// staged. Several coordinates (a solid fill or a cleared area shares one tile) get one upload to -/// a scratch tile and GPU copies from it: writing each one from the CPU sent 387 MB per refresh -/// of a filled 50 MP 16-bit page (#1774). -fn put_tiles(device: &wgpu::Device, queue: &wgpu::Queue, encoder: &mut wgpu::CommandEncoder, r: &Resident, cs: &[TileCoord], bytes: &[u8]) -> u64 { - if let [c] = cs - && !r.ordered - { - write_tile(queue, r, *c, bytes); - return bytes.len() as u64; - } - if cs.is_empty() { - return 0; - } - let extent = wgpu::Extent3d { width: TILE_SIZE as u32, height: TILE_SIZE as u32, depth_or_array_layers: 1 }; - // Its own texture per call: queued writes land before the encoder runs, so a shared scratch - // would hold only the last tile by then. - let scratch = device.create_texture(&wgpu::TextureDescriptor { - label: Some("pc_tile_scratch"), - size: extent, - mip_level_count: 1, - sample_count: 1, - dimension: wgpu::TextureDimension::D2, - format: r.kind.format(), - usage: wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::COPY_DST, - view_formats: &[], - }); - queue.write_texture( - wgpu::TexelCopyTextureInfo { texture: &scratch, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, - bytes, - wgpu::TexelCopyBufferLayout { - offset: 0, - bytes_per_row: Some(TILE_SIZE as u32 * r.kind.bytes_per_pixel() as u32), - rows_per_image: Some(TILE_SIZE as u32), - }, - extent, - ); - for c in cs { - let tr = c.rect(); - encoder.copy_texture_to_texture( - wgpu::TexelCopyTextureInfo { texture: &scratch, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, - wgpu::TexelCopyTextureInfo { - texture: &r.texture, - mip_level: 0, - origin: wgpu::Origin3d { x: (tr.x0 - r.region.x0) as u32, y: (tr.y0 - r.region.y0) as u32, z: 0 }, - aspect: wgpu::TextureAspect::All, - }, - extent, - ); - } - bytes.len() as u64 -} - -/// Copy the texels `old` holds inside the region of its replacement `new` (same texel kind, -/// format and default pixel; only the region moved) and carry over the tiles they show, so only -/// tiles outside the overlap or changed since need uploading. Returns the kept (tile-aligned) -/// rect; empty when nothing can be kept. -fn keep_overlap(device: &wgpu::Device, queue: &wgpu::Queue, old: &Resident, new: &mut Resident) -> Rect { - let same = old.kind == new.kind && old.format == new.format && old.cmyk == new.cmyk && old.default_bits == new.default_bits; - let k = old.region.intersect(&new.region); - if !same || k.is_empty() { - return Rect::EMPTY; - } - // Its own submission: tile writes go through the queue and land at the start of the next - // submit, before anything in the frame's encoder, so a copy recorded there would overwrite - // the tiles written after it with the old texels. - let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("pc_compose_keep") }); - encoder.copy_texture_to_texture( - wgpu::TexelCopyTextureInfo { - texture: &old.texture, - mip_level: 0, - origin: wgpu::Origin3d { x: (k.x0 - old.region.x0) as u32, y: (k.y0 - old.region.y0) as u32, z: 0 }, - aspect: wgpu::TextureAspect::All, - }, - wgpu::TexelCopyTextureInfo { - texture: &new.texture, - mip_level: 0, - origin: wgpu::Origin3d { x: (k.x0 - new.region.x0) as u32, y: (k.y0 - new.region.y0) as u32, z: 0 }, - aspect: wgpu::TextureAspect::All, - }, - wgpu::Extent3d { width: k.width(), height: k.height(), depth_or_array_layers: 1 }, - ); - queue.submit([encoder.finish()]); - new.tiles = old.tiles.iter().filter(|(c, _)| k.contains_rect(&c.rect())).map(|(c, t)| (*c, t.clone())).collect(); - k -} - -/// Convert `tiles` of `surface` to `kind` texels and hand each distinct tile, the coordinates -/// sharing it and its bytes to `put`. Each distinct tile is converted once (a solid fill shares -/// one `Arc` across every coordinate it covers), in parallel batches. Converting every tile one -/// after another on the UI thread froze a 50 MP 16-bit document for about 1.4 s after a -/// full-canvas fill (#1774). Returns how many tiles were converted. -fn convert_tiles(surface: &Surface, tiles: Vec<(TileCoord, Arc)>, kind: TexKind, mut put: impl FnMut(&Arc, &[TileCoord], &[u8])) -> usize { - let mut groups: Vec<(Arc, Vec)> = Vec::new(); - let mut index: HashMap<*const Tile, usize> = HashMap::new(); - for (c, t) in tiles { - match index.get(&Arc::as_ptr(&t)).and_then(|&i| groups.get_mut(i)) { - Some(g) => g.1.push(c), - None => { - index.insert(Arc::as_ptr(&t), groups.len()); - groups.push((t, vec![c])); - } - } - } - // CMYK and Lab tiles convert pixel by pixel through a colour transform (a CMYK tile took - // ~5 ms on one thread, the whole of a brush dab's refresh on an A4 CMYK page, #5108): those - // go in bands of rows, so even the one tile a dab touches spreads over the threads. Workers - // don't inherit this thread's CMYK profile scope, so each band enters it. - let bands = if colour_managed(&surface.format(), kind) { TILE_SIZE / MANAGED_BAND_ROWS } else { 1 }; - let space = photocraft_color::convert::active_cmyk_space(); - for batch in groups.chunks(CONVERT_BATCH) { - // A tile's content is the same at every coordinate sharing it: convert it at the first. - let jobs: Vec<_> = batch.iter().filter_map(|(t, cs)| cs.first().map(|c| (t, *c))).flat_map(|(t, c)| (0..bands).map(move |b| (t, c, b))).collect(); - let parts = fx::par_map(jobs, |(t, c, b)| { - photocraft_color::convert::with_cmyk_space(space.as_ref(), || { - if bands == 1 { - return convert_tile(surface, Some(t), kind, c); - } - let r = c.rect(); - let y0 = r.y0 + b * MANAGED_BAND_ROWS; - convert_rows(surface, Some(t), kind, Rect::new(r.x0, y0, r.x1, y0 + MANAGED_BAND_ROWS)) - }) - }); - for ((t, cs), bytes) in batch.iter().zip(parts.chunks(bands as usize)) { - // One part (every format but CMYK and Lab) goes through as is: no copy per tile. - match bytes { - [one] => put(t, cs, one), - _ => put(t, cs, &bytes.concat()), - } - } - } - groups.len() -} - -/// Rows per parallel band of a colour-managed (CMYK, Lab) tile conversion. -const MANAGED_BAND_ROWS: i32 = 16; - -/// Whether `fmt` pixels reach `kind` texels through a per-pixel colour transform (CMYK, Lab). -fn colour_managed(fmt: &PixelFormat, kind: TexKind) -> bool { - use photocraft_color::ColorMode; - matches!(kind, TexKind::Rgba8 | TexKind::Rgba16F) && matches!(fmt.mode, ColorMode::Cmyk | ColorMode::Lab) -} - -/// Tile pixels in the texture's format. `tile = None` gives the default pixel everywhere. -fn convert_tile(surface: &Surface, tile: Option<&Arc>, kind: TexKind, c: TileCoord) -> Vec { - if let (Some(t), TexKind::Rgba8Direct | TexKind::R8Direct) = (tile, kind) { - return t.bytes().to_vec(); - } - let fmt = surface.format(); - if let (Some(t), TexKind::Rgba16F) = (tile, kind) - && let Some(out) = rgb_gray16_to_f16(&fmt, t.bytes()).or_else(|| rgb_gray32_to_f16(&fmt, t.bytes())) - { - return out; - } - convert_rows(surface, tile, kind, c.rect()) -} - -/// [`convert_tile`]'s general path for `rect` (rows of one tile): each pixel through -/// `photocraft_raster::to_rgba`. A run of identical pixels (the transparent or flat areas around a -/// brush dab) is converted once: the same samples give the same texels. -fn convert_rows(surface: &Surface, tile: Option<&Arc>, kind: TexKind, rect: Rect) -> Vec { - let n = rect.width() as usize * rect.height() as usize; - let fmt = surface.format(); - let ch = fmt.channels(); - let raw: Vec = match tile { - Some(_) => surface.read_region(rect), - None => surface.default_pixel().repeat(n), - }; - let mut out = Vec::with_capacity(n * kind.bytes_per_pixel()); - // The previous pixel and its colour. - let mut last: Option<(usize, [f32; 4])> = None; - for (i, px) in raw.chunks_exact(ch).enumerate() { - let mut rgba = || -> [f32; 4] { - if let Some((j, v)) = last - && raw.get(j * ch..j * ch + ch).is_some_and(|p| p.iter().zip(px).all(|(a, b)| a.to_bits() == b.to_bits())) - { - return v; - } - let v = photocraft_raster::to_rgba(&fmt, px); - last = Some((i, v)); - v - }; - match kind { - TexKind::Rgba8Direct | TexKind::Rgba8 => { - let v = rgba(); - out.extend(v.map(|x| (x.clamp(0.0, 1.0) * 255.0 + 0.5) as u8)); - } - TexKind::Rgba16F => { - let v = rgba(); - for x in v { - out.extend(f32_to_f16(x).to_le_bytes()); - } - } - TexKind::R8Direct => out.push((px[0].clamp(0.0, 1.0) * 255.0 + 0.5) as u8), - TexKind::R16F => out.extend(f32_to_f16(px[0]).to_le_bytes()), - TexKind::R32F => out.extend(px[0].to_le_bytes()), - } - } - out -} - -/// RGBA16F texels of a 16-bit RGB or grayscale tile, through a table of every 16-bit sample's -/// half: the same bytes as the general path at a fraction of its cost (a 50 MP 16-bit refresh -/// converts dozens of tiles). `None` for other formats. -fn rgb_gray16_to_f16(fmt: &PixelFormat, bytes: &[u8]) -> Option> { - use photocraft_color::ColorMode; - static HALF: std::sync::OnceLock> = std::sync::OnceLock::new(); - if fmt.sample != SampleType::U16 { - return None; - } - let gray = match fmt.mode { - ColorMode::Rgb => false, - ColorMode::Grayscale | ColorMode::Bitmap | ColorMode::Duotone => true, - _ => return None, - }; - let half = HALF.get_or_init(|| (0..=u16::MAX).map(|v| f32_to_f16(v as f32 / 65535.0)).collect()); - let one = f32_to_f16(1.0).to_le_bytes(); - let ch = fmt.channels(); - let mut out = Vec::with_capacity((TILE_SIZE * TILE_SIZE) as usize * 8); - for px in bytes.chunks_exact(ch * 2) { - let h = |i: usize| -> [u8; 2] { - let v = px.get(i * 2..i * 2 + 2).map_or(0, |b| u16::from_ne_bytes([b[0], b[1]])); - half.get(v as usize).copied().unwrap_or(0).to_le_bytes() - }; - let (r, g, b) = if gray { (h(0), h(0), h(0)) } else { (h(0), h(1), h(2)) }; - let a = if fmt.alpha { h(ch - 1) } else { one }; - out.extend_from_slice(&r); - out.extend_from_slice(&g); - out.extend_from_slice(&b); - out.extend_from_slice(&a); - } - Some(out) -} - -/// RGBA16F texels of a 32-bit float RGB or grayscale tile, straight from its samples: the same -/// bytes as the general path without decoding the tile into a float buffer and converting it -/// pixel by pixel (a brush dab on a 32-bit layer re-uploads the tiles it touched). `None` for -/// other formats. -fn rgb_gray32_to_f16(fmt: &PixelFormat, bytes: &[u8]) -> Option> { - use photocraft_color::ColorMode; - if fmt.sample != SampleType::F32 { - return None; - } - let gray = match fmt.mode { - ColorMode::Rgb => false, - ColorMode::Grayscale | ColorMode::Bitmap | ColorMode::Duotone => true, - _ => return None, - }; - let one = f32_to_f16(1.0).to_le_bytes(); - let ch = fmt.channels(); - let mut out = Vec::with_capacity((TILE_SIZE * TILE_SIZE) as usize * 8); - for px in bytes.chunks_exact(ch * 4) { - let h = |i: usize| -> [u8; 2] { - let v = px.get(i * 4..i * 4 + 4).map_or(0.0, |b| f32::from_ne_bytes([b[0], b[1], b[2], b[3]])); - f32_to_f16(v).to_le_bytes() - }; - let (r, g, b) = if gray { - let v = h(0); - (v, v, v) - } else { - (h(0), h(1), h(2)) - }; - let a = if fmt.alpha { h(ch - 1) } else { one }; - out.extend_from_slice(&r); - out.extend_from_slice(&g); - out.extend_from_slice(&b); - out.extend_from_slice(&a); - } - Some(out) -} - -fn lut_texture(device: &wgpu::Device, queue: &wgpu::Queue, rows: &[[f32; 4096]]) -> (wgpu::Texture, wgpu::TextureView) { - let t = device.create_texture(&wgpu::TextureDescriptor { - label: Some("pc_compose_lut"), - size: wgpu::Extent3d { width: 4096, height: rows.len() as u32, depth_or_array_layers: 1 }, - mip_level_count: 1, - sample_count: 1, - dimension: wgpu::TextureDimension::D2, - format: wgpu::TextureFormat::R32Float, - usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, - view_formats: &[], - }); - let bytes: Vec = rows.iter().flat_map(|r| r.iter().flat_map(|v| v.to_le_bytes())).collect(); - queue.write_texture( - wgpu::TexelCopyTextureInfo { texture: &t, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, - &bytes, - wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(4096 * 4), rows_per_image: Some(rows.len() as u32) }, - wgpu::Extent3d { width: 4096, height: rows.len() as u32, depth_or_array_layers: 1 }, - ); - let v = t.create_view(&Default::default()); - (t, v) -} - -#[derive(Clone, Copy)] -enum W { - I(i32), - U(u32), - F(f32), -} use W::{F, I, U}; -fn words(v: &[W]) -> Vec { - v.iter() - .flat_map(|w| match w { - I(i) => i.to_le_bytes(), - U(u) => u.to_le_bytes(), - F(f) => f.to_le_bytes(), - }) - .collect() -} - -/// IEEE half from f32 (round to nearest even; overflow → inf). -pub fn f32_to_f16(x: f32) -> u16 { - let b = x.to_bits(); - let sign = ((b >> 16) & 0x8000) as u16; - let exp = ((b >> 23) & 0xff) as i32; - let man = b & 0x7f_ffff; - if exp == 0xff { - return sign | 0x7c00 | if man != 0 { 0x200 } else { 0 }; - } - let e = exp - 127 + 15; - if e >= 0x1f { - return sign | 0x7c00; - } - if e <= 0 { - if e < -10 { - return sign; - } - let m = man | 0x80_0000; - let shift = (14 - e) as u32; - let half = 1u32 << (shift - 1); - let rounded = (m + half - 1 + ((m >> shift) & 1)) >> shift; - return sign | rounded as u16; - } - let mut h = ((e as u32) << 10) | (man >> 13); - let rest = man & 0x1fff; - if rest > 0x1000 || (rest == 0x1000 && (h & 1) == 1) { - h += 1; - } - sign | h as u16 -} - -/// f32 from IEEE half. -pub fn f16_to_f32(h: u16) -> f32 { - let sign = if h & 0x8000 != 0 { -1.0 } else { 1.0 }; - let exp = ((h >> 10) & 0x1f) as i32; - let man = (h & 0x3ff) as f32; - match exp { - 0 => sign * man * 2f32.powi(-24), - 0x1f => { - if man == 0.0 { - sign * f32::INFINITY - } else { - f32::NAN - } - } - e => sign * (1.0 + man / 1024.0) * 2f32.powi(e - 15), - } -} - -/// Blocking readback of a composite (native tests and tools). +mod batch; +mod cells; +mod consts; +mod convert; +mod encode; +mod fx_passes; +mod kit; +mod paging; #[cfg(not(target_arch = "wasm32"))] -pub fn render_to_vec(comp: &mut Compositor, device: &wgpu::Device, queue: &wgpu::Queue, doc: &Document, rect: Rect) -> Result, Unsupported> { - render_to_vec_stats(comp, device, queue, doc, rect).map(|(v, _)| v) -} - -/// [`render_to_vec`] plus the render's [`Stats`]. -#[cfg(not(target_arch = "wasm32"))] -pub fn render_to_vec_stats( - comp: &mut Compositor, - device: &wgpu::Device, - queue: &wgpu::Queue, - doc: &Document, - rect: Rect, -) -> Result<(Vec<[f32; 4]>, Stats), Unsupported> { - let rect = rect.intersect(&doc.bounds()); - let mut staging: Vec<(Rect, wgpu::Buffer, u32)> = Vec::new(); - let mut bpp = 16u32; - let stats = comp.render(device, queue, doc, rect, |enc, out| { - // Bytes per pixel of the accumulation format (Rgba32Float = 16, Rgba16Float = 8). - bpp = if out.texture.format() == wgpu::TextureFormat::Rgba32Float { 16 } else { 8 }; - let row = (out.rect.width() * bpp).div_ceil(256) * 256; - let buf = device.create_buffer(&wgpu::BufferDescriptor { - label: Some("pc_readback"), - size: (row * out.rect.height()) as u64, - usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, - mapped_at_creation: false, - }); - enc.copy_texture_to_buffer( - wgpu::TexelCopyTextureInfo { texture: out.texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, - wgpu::TexelCopyBufferInfo { - buffer: &buf, - layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(row), rows_per_image: Some(out.rect.height()) }, - }, - wgpu::Extent3d { width: out.rect.width(), height: out.rect.height(), depth_or_array_layers: 1 }, - ); - staging.push((out.rect, buf, row)); - })?; - for (_, b, _) in &staging { - b.slice(..).map_async(wgpu::MapMode::Read, |_| {}); - } - match &comp.health { - Some(h) if !h.wait(device, None) => return Err(Unsupported(h.fault().map_or_else(|| "GPU device lost".into(), |f| f.to_string()))), - Some(_) => {} - None => { - let _ = device.poll(wgpu::PollType::Wait { submission_index: None, timeout: None }); - } - } - let w = rect.width() as usize; - let mut out = vec![[0.0f32; 4]; w * rect.height() as usize]; - for (r, b, row) in &staging { - let data = b.slice(..).get_mapped_range().map_err(|e| Unsupported(format!("GPU readback failed: {e:?}")))?; - for y in 0..r.height() as usize { - for x in 0..r.width() as usize { - let o = y * *row as usize + x * bpp as usize; - let px: [f32; 4] = if bpp == 16 { - std::array::from_fn(|i| f32::from_le_bytes([data[o + i * 4], data[o + i * 4 + 1], data[o + i * 4 + 2], data[o + i * 4 + 3]])) - } else { - std::array::from_fn(|i| half::f16::from_le_bytes([data[o + i * 2], data[o + i * 2 + 1]]).to_f32()) - }; - let (dx, dy) = ((r.x0 - rect.x0) as usize + x, (r.y0 - rect.y0) as usize + y); - out[dy * w + dx] = px; - } - } - } - Ok((out, stats)) -} +mod readback; +mod setup; +mod textures; #[cfg(test)] -mod tests { - use super::*; +use batch::{BATCH, batch_kernel, batch_op_words, batch_runs, op_words, run_starts, tile_grid}; +#[cfg(test)] +use consts::OP_UNIFORM; +pub use consts::{ACC_FORMAT, CHUNK, FX_BUDGET, PAGE, PATTERN_BUDGET, PATTERN_IDLE_FRAMES, RESIDENT_BUDGET}; +use convert::W; +#[cfg(test)] +use convert::{CONVERT_BATCH, colour_managed, convert_tile, convert_tiles, rgb_gray16_to_f16, rgb_gray32_to_f16}; +pub use convert::{f16_to_f32, f32_to_f16}; +pub use kit::SHADER; +use kit::{Kit, tex_entry}; +pub use paging::OVER_BUDGET; +use paging::first_error; +#[cfg(test)] +use paging::{lru_victims, uniform_buffer_len}; +#[cfg(not(target_arch = "wasm32"))] +pub use readback::{render_to_vec, render_to_vec_stats}; +#[cfg(test)] +use textures::TexKind; +use textures::{CachedPattern, FxEntry, FxKey, ResKey, Resident, Tex}; +pub use textures::{ChunkOut, Stats}; - /// A run joins `LayerBlend` passes that only feed each other, at most `BATCH` of them, and - /// never ends in the slot it reads from. - fn check_runs(p: &Plan<'_>) -> Vec { - let runs = batch_runs(p); - assert_eq!(runs.len(), p.passes.len()); - for (i, &k) in runs.iter().enumerate() { - assert!((1..=BATCH).contains(&k), "pass {i}: run {k}"); - if k > 1 { - assert_ne!(Some(p.passes[i + k - 1].dst), p.passes[i].a, "run at {i} renders into its input"); - for j in i + 1..i + k { - assert_eq!(p.passes[j].kernel, Kernel::LayerBlend); - assert_eq!(p.passes[j].a, Some(p.passes[j - 1].dst), "run at {i}: pass {j} doesn't read the one before"); - assert!(p.passes[j].mask.is_none() && p.passes[j].mode != photocraft_color::BlendMode::Dissolve, "run at {i}: pass {j}"); - } - } - } - runs - } - - #[test] - fn plain_layers_batch_and_runs_stop_where_a_pass_must_stand_alone() { - use photocraft_color::{BlendMode, Color, ColorMode, SampleType}; - use photocraft_doc::{Document, Layer, LayerMask}; - let mut d = Document::with_background("t", photocraft_geom::Size::new(8, 8), ColorMode::Rgb, SampleType::U8, Color::WHITE); - for i in 0..12 { - let mut l = Layer::raster(format!("l{i}"), d.pixel_format()); - l.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 8, 8), &[0.2, 0.4, 0.6, 0.5]); - d.layers.push(l); - } - let p = plan::plan(&d).unwrap(); - let runs = check_runs(&p); - assert!(runs.iter().any(|k| *k >= 3), "{runs:?}"); - // The cache resumes only where a run starts, so a cached render draws the passes above - // its checkpoint in the same runs as an uncached one; checkpoints inside a run are - // skipped, but a stack of plain layers keeps some to resume at. - let starts = run_starts(&runs); - assert_eq!(starts.len(), runs.len() + 1); - assert!(starts[0] && starts[runs.len()]); - let (mut at, mut i) = (Vec::new(), 0); - while i < runs.len() { - at.push(i); - i += runs[i]; - } - assert_eq!(starts.iter().enumerate().filter(|(_, s)| **s).map(|(i, _)| i).collect::>(), [at, vec![runs.len()]].concat()); - let resumable = p.checkpoints.iter().filter(|c| c.pass_end > 1 && starts[c.pass_end]).count(); - assert!(resumable >= 2 && resumable < p.checkpoints.len(), "{resumable} of {:?}", p.checkpoints); - // A masked or Dissolve layer, or a clipped one, never joins a run as an extra layer. - d.layers[3].mask = Some(LayerMask::hide_all()); - d.layers[6].blend = BlendMode::Dissolve; - d.layers[9].clipped = true; - check_runs(&plan::plan(&d).unwrap()); - // Nothing to batch: a lone layer. - d.layers.truncate(1); - assert_eq!(check_runs(&plan::plan(&d).unwrap()), vec![1; plan::plan(&d).unwrap().passes.len()]); - } - - #[test] - fn batch_records_hold_three_extra_layers_in_the_spare_words() { - let lead = plan::Pass::new(Kernel::LayerBlend, 0); - let mut x = plan::Pass::new(Kernel::LayerBlend, 1); - x.opacity = 0.25; - x.fill = 0.5; - x.color = [0.1, 0.2, 0.3, 0.4]; - let w = batch_op_words(&lead, None, None, &[(&x, Some([1, 2, 3, 4])), (&x, None), (&x, None), (&x, None)]); - assert_eq!(w.len() as u64, OP_UNIFORM); - let word = |i: usize| <[u8; 4]>::try_from(&w[i * 4..i * 4 + 4]).unwrap(); - let f = |i: usize| f32::from_le_bytes(word(i)); - // At most three extras; the first's geometry, colour and parameters in p0, p1, p2. - assert_eq!(i32::from_le_bytes(word(1)), 3); - assert_eq!([f(20), f(21), f(22), f(23)], [1.0, 2.0, 3.0, 4.0]); - assert_eq!([f(24), f(25), f(26), f(27)], [0.1, 0.2, 0.3, 0.4]); - assert_eq!([f(28), f(29), f(31)], [0.25, 0.5, 1.0]); - // The third's parameters in q4; one without pixels says so. - assert_eq!([f(60), f(61), f(63)], [0.25, 0.5, 0.0]); - // Other passes leave the batch words zero. - let plain = op_words(&x, None, None, None); - assert!(plain[44 * 4..].iter().all(|b| *b == 0)); - } - - #[test] - fn runs_of_normal_layers_draw_with_normal_code_alone() { - use photocraft_color::BlendMode; - let pass = |mode: BlendMode, flags: u32| { - let mut p = plan::Pass::new(Kernel::LayerBlend, 0); - p.mode = mode; - p.flags = flags; - p - }; - let normal = pass(BlendMode::Normal, plan::F_HDR); - assert_eq!(batch_kernel(&[normal.clone(), pass(BlendMode::Normal, 0)]), Kernel::LayerBatchNormal); - // Any other mode, text gamma or a Lab document anywhere in the run takes the full shader. - for other in - [pass(BlendMode::Multiply, 0), pass(BlendMode::Dissolve, 0), pass(BlendMode::Normal, plan::F_TEXT_GAMMA), pass(BlendMode::Normal, plan::F_LAB)] - { - assert_eq!(batch_kernel(&[normal.clone(), other.clone()]), Kernel::LayerBatch); - assert_eq!(batch_kernel(&[other, normal.clone()]), Kernel::LayerBatch); - } - } - - #[test] - fn layer_pages_are_admitted_by_evicting_least_recently_used_first() { - let pages = || vec![(5, 'c', 40), (1, 'a', 30), (3, 'b', 20)]; - // Fits already: nothing dropped. - assert!(lru_victims(pages(), 90, 10, 100).is_empty()); - // 90 held + 40 incoming over 100: the oldest page goes first, then the next. - assert_eq!(lru_victims(pages(), 90, 40, 100), vec!['a']); - assert_eq!(lru_victims(pages(), 90, 60, 100), vec!['a', 'b']); - // Out of memory: a zero budget drops every candidate, and an impossible request stops - // when none are left instead of looping or overflowing. - assert_eq!(lru_victims(pages(), 90, 0, 0), vec!['a', 'b', 'c']); - assert_eq!(lru_victims(pages(), u64::MAX, u64::MAX, 1), vec!['a', 'b', 'c']); - assert!(lru_victims(Vec::<(u64, char, u64)>::new(), 90, 40, 100).is_empty()); - } - - #[test] - fn uniform_buffer_sizes_are_checked_before_allocation() { - assert_eq!(uniform_buffer_len(1, 255, 65_536).unwrap(), 65_536); - assert!(uniform_buffer_len(1, 255, 65_535).is_err()); - assert!(uniform_buffer_len(usize::MAX, 1, u64::MAX).is_err()); - assert!(uniform_buffer_len(usize::MAX, 0, u64::MAX).is_err()); - assert!(uniform_buffer_len(1, 16_777_216, u64::MAX).is_err(), "the last record offset cannot be represented by u32"); - #[cfg(target_pointer_width = "64")] - assert_eq!(uniform_buffer_len(1, 16_777_215, u64::MAX).unwrap(), 4_294_967_296, "the last valid u32 dynamic offset is accepted"); - } - - #[test] - fn half_roundtrip() { - for v in [0.0f32, 1.0, 0.5, 0.25, 1.0 / 255.0, 0.333, 65504.0, -2.5, 1e-6] { - let r = f16_to_f32(f32_to_f16(v)); - assert!((r - v).abs() <= v.abs() / 1024.0 + 1e-7, "{v} -> {r}"); - } - } - - #[test] - fn shader_validates() { - let module = wgpu::naga::front::wgsl::parse_str(SHADER).unwrap_or_else(|e| panic!("{}", e.emit_to_string(SHADER))); - wgpu::naga::valid::Validator::new(wgpu::naga::valid::ValidationFlags::all(), wgpu::naga::valid::Capabilities::empty()) - .validate(&module) - .unwrap_or_else(|e| panic!("{e:?}")); - for k in Kernel::DRAWN { - let e = k.entry().unwrap(); - assert!(module.entry_points.iter().any(|ep| ep.name == e), "missing entry point {e}"); - } - } - - /// The decimal float literals in `src` (comments skipped; hex literals are exact, so skipped), - /// with their line numbers. - fn decimal_float_literals(src: &str) -> Vec<(usize, String)> { - let mut out = Vec::new(); - for (n, line) in src.lines().enumerate() { - let code = line.split("//").next().unwrap_or("").as_bytes(); - let mut i = 0; - while i < code.len() { - let digit_or_dot = code[i].is_ascii_digit() || (code[i] == b'.' && code.get(i + 1).is_some_and(u8::is_ascii_digit)); - let word_before = i > 0 && (code[i - 1].is_ascii_alphanumeric() || code[i - 1] == b'_' || code[i - 1] == b'.'); - if !digit_or_dot || word_before { - i += 1; - continue; - } - if code[i] == b'0' && matches!(code.get(i + 1), Some(b'x' | b'X')) { - i += 2; - while i < code.len() && (code[i].is_ascii_hexdigit() || matches!(code[i], b'.' | b'p' | b'P' | b'+' | b'-')) { - i += 1; - } - continue; - } - let start = i; - while i < code.len() && (code[i].is_ascii_digit() || code[i] == b'.') { - i += 1; - } - if i < code.len() && matches!(code[i], b'e' | b'E') { - let mut j = i + 1; - if j < code.len() && matches!(code[j], b'+' | b'-') { - j += 1; - } - if j < code.len() && code[j].is_ascii_digit() { - i = j; - while i < code.len() && code[i].is_ascii_digit() { - i += 1; - } - } - } - out.push((n + 1, String::from_utf8_lossy(&code[start..i]).into_owned())); - } - } - out - } - - /// Browsers' WebGPU shader compiler (Tint) rejects a float literal beyond f32's finite range - /// even when it would round to `f32::MAX` (naga, used natively, rounds it), and then no - /// compositor pipeline builds and the web app falls back to the CPU renderer. `3.40282347e38` - /// was such a literal. - #[test] - fn shader_float_literals_fit_f32() { - let lits = decimal_float_literals(SHADER); - assert!(lits.iter().any(|(_, l)| l == "1.0"), "the scanner finds literals: {lits:?}"); - let bad: Vec<_> = lits.iter().filter(|(_, l)| l.parse::().map_or(true, |v| !v.is_finite() || v.abs() > f64::from(f32::MAX))).collect(); - assert!(bad.is_empty(), "float literals outside f32's finite range (line, literal): {bad:?}"); - } - - #[test] - fn op_record_fits_the_uniform() { - let p = plan::Pass::new(Kernel::FxPaint, 0); - assert_eq!(op_words(&p, None, None, None).len() as u64, OP_UNIFORM); - } - - /// #6534: a 16-bit mask (16-bit documents, feathered or vector combined masks) costs two - /// bytes per pixel on the GPU, twice an 8-bit mask, not four; 32-bit masks stay R32Float. - #[test] - fn sixteen_bit_masks_upload_at_two_bytes_per_pixel() { - let gray = |sample| PixelFormat { sample, ..PixelFormat::GRAY8 }; - assert_eq!(TexKind::for_surface(Role::Mask, PixelFormat::GRAY8).bytes_per_pixel(), 1); - let k16 = TexKind::for_surface(Role::Mask, gray(SampleType::U16)); - assert_eq!(k16.bytes_per_pixel(), 2, "{k16:?}"); - assert_eq!(k16.format().block_copy_size(None), Some(2), "{k16:?}"); - let k32 = TexKind::for_surface(Role::Mask, gray(SampleType::F32)); - assert_eq!(k32.format(), wgpu::TextureFormat::R32Float); - // The texels hold the mask values (a half each), the default pixel included. - let mut s = Surface::with_default(gray(SampleType::U16), &[1.0]); - s.fill_rect(Rect::new(0, 0, 4, 1), &[0.25]); - let c = TileCoord::new(0, 0); - let bytes = convert_tile(&s, s.tile(c), k16, c); - assert_eq!(bytes.len(), (TILE_SIZE * TILE_SIZE) as usize * 2); - assert_eq!(bytes.get(..2), Some(f32_to_f16(0.25).to_le_bytes().as_slice())); - assert_eq!(bytes.get(8..10), Some(f32_to_f16(1.0).to_le_bytes().as_slice())); - assert_eq!(convert_tile(&s, None, k16, c).get(..2), Some(f32_to_f16(1.0).to_le_bytes().as_slice())); - } - - /// #1774: a solid fill shares one tile across every coordinate; it is converted once, and - /// every coordinate (shared or not) still gets exactly the bytes `convert_tile` gives it, at - /// every depth and texture kind. - #[test] - fn convert_tiles_converts_each_distinct_tile_once() { - let area = Rect::new(0, 0, TILE_SIZE * 9, TILE_SIZE * 9); - for (fmt, kind) in [ - (PixelFormat::RGBA8, TexKind::Rgba8Direct), - (PixelFormat { alpha: false, ..PixelFormat::RGBA8 }, TexKind::Rgba8), - (PixelFormat::RGBA16, TexKind::Rgba16F), - (PixelFormat::RGBA32F, TexKind::Rgba16F), - (PixelFormat::GRAY8, TexKind::R8Direct), - (PixelFormat { sample: SampleType::U16, ..PixelFormat::GRAY8 }, TexKind::R16F), - (PixelFormat { sample: SampleType::F32, ..PixelFormat::GRAY8 }, TexKind::R32F), - ] { - let mut s = Surface::new(fmt); - let px = [0.2, 0.4, 0.6, 1.0]; - let n = fmt.channels(); - // Fully covered tiles share one `Arc`; then two tiles get their own pixels. - s.fill_rect(area, &px[..n]); - s.fill_rect(Rect::new(3, 5, 40, 60), &[0.9, 0.1, 0.3, 0.5][..n]); - s.fill_rect(Rect::new(TILE_SIZE * 4 + 7, TILE_SIZE * 2, TILE_SIZE * 4 + 9, TILE_SIZE * 2 + 3), &[0.0; 4][..n]); - let tiles: Vec<_> = area.tiles().filter_map(|c| s.tile(c).map(|t| (c, t.clone()))).collect(); - assert_eq!(tiles.len(), 81, "{fmt:?}"); - let mut seen = Vec::new(); - let converted = convert_tiles(&s, tiles, kind, |t, cs, bytes| { - for &c in cs { - assert!(s.tile(c).is_some_and(|own| Arc::ptr_eq(own, t)), "{fmt:?} {c:?}"); - assert_eq!(bytes, convert_tile(&s, Some(t), kind, c).as_slice(), "{fmt:?} {c:?}"); - seen.push(c); - } - }); - assert_eq!(converted, 3, "{fmt:?}: the shared tile once, plus the two edited ones"); - seen.sort_by_key(|c| (c.ty, c.tx)); - let mut want: Vec<_> = area.tiles().collect(); - want.sort_by_key(|c| (c.ty, c.tx)); - assert_eq!(seen, want, "{fmt:?}: every coordinate once"); - } - // More distinct tiles than one batch: all converted, each coordinate once. - let mut s = Surface::new(PixelFormat::RGBA16); - let wide = Rect::new(0, 0, TILE_SIZE * (CONVERT_BATCH as i32 + 5), TILE_SIZE); - for c in wide.tiles() { - s.fill_rect(Rect::new(c.rect().x0, 0, c.rect().x0 + 1, 1), &[c.tx as f32 / 100.0, 0.0, 0.0, 1.0]); - } - let tiles: Vec<_> = wide.tiles().filter_map(|c| s.tile(c).map(|t| (c, t.clone()))).collect(); - let mut n = 0; - let converted = convert_tiles(&s, tiles, TexKind::Rgba16F, |t, cs, bytes| { - for &c in cs { - assert_eq!(bytes, convert_tile(&s, Some(t), TexKind::Rgba16F, c).as_slice()); - n += 1; - } - }); - assert_eq!((converted, n), (CONVERT_BATCH + 5, CONVERT_BATCH + 5)); - } - - /// The 16-bit and 32-bit float RGB/gray fast paths give exactly the general path's half - /// floats (32-bit samples above 1 and below 0 included). - #[test] - fn sixteen_and_thirty_two_bit_fast_paths_match_the_general_one() { - for fmt in [ - PixelFormat::RGBA16, - PixelFormat { alpha: false, ..PixelFormat::RGBA16 }, - PixelFormat { sample: SampleType::U16, ..PixelFormat::GRAY8 }, - PixelFormat { sample: SampleType::U16, alpha: true, ..PixelFormat::GRAY8 }, - PixelFormat::RGBA32F, - PixelFormat { alpha: false, ..PixelFormat::RGBA32F }, - PixelFormat { sample: SampleType::F32, ..PixelFormat::GRAY8 }, - PixelFormat { sample: SampleType::F32, alpha: true, ..PixelFormat::GRAY8 }, - ] { - let mut s = Surface::new(fmt); - let r = Rect::new(0, 0, TILE_SIZE, TILE_SIZE); - let n = (TILE_SIZE * TILE_SIZE) as usize * fmt.channels(); - let hdr = if fmt.sample == SampleType::F32 { 4.0 } else { 1.0 }; - let data: Vec = (0..n).map(|i| (i as u32).wrapping_mul(2_654_435_761) as f32 / u32::MAX as f32 * hdr - (hdr - 1.0) / 4.0).collect(); - s.write_region(r, &data); - let t = s.tile(TileCoord::new(0, 0)).expect("written").clone(); - let fast = rgb_gray16_to_f16(&fmt, t.bytes()).or_else(|| rgb_gray32_to_f16(&fmt, t.bytes())).expect("fast path"); - let raw = s.read_region(r); - let general: Vec = - raw.chunks_exact(fmt.channels()).flat_map(|px| photocraft_raster::to_rgba(&fmt, px).map(|x| f32_to_f16(x).to_le_bytes())).flatten().collect(); - assert_eq!(fast, general, "{fmt:?}"); - assert_eq!(convert_tile(&s, Some(&t), TexKind::Rgba16F, TileCoord::new(0, 0)), general, "{fmt:?}"); - } - assert!(rgb_gray16_to_f16(&PixelFormat::RGBA8, &[]).is_none()); - assert!(rgb_gray16_to_f16(&PixelFormat { sample: SampleType::U16, ..PixelFormat::CMYKA8 }, &[]).is_none()); - assert!(rgb_gray32_to_f16(&PixelFormat::RGBA16, &[]).is_none()); - assert!(rgb_gray32_to_f16(&PixelFormat { sample: SampleType::F32, ..PixelFormat::CMYKA8 }, &[]).is_none()); - } - - /// CMYK and Lab tiles convert in parallel bands of rows, each run of equal pixels once - /// (#5108): the texels are still exactly the per-pixel conversion's, at 8 and 16 bits, with - /// the built-in CMYK profile and with a document's own (which the worker threads enter). - #[test] - fn colour_managed_tiles_match_the_per_pixel_conversion() { - use photocraft_cms::synth::{CmykParams, cmyk_profile}; - use photocraft_color::ColorMode; - use photocraft_color::convert::{CmykSpace, with_cmyk_space}; - let icc = Arc::new( - cmyk_profile(&CmykParams { description: "GPU test CMYK".into(), tvi: [0.26, 0.26, 0.26, 0.3], grid_a2b: 5, grid_b2a: 9, ..Default::default() }) - .to_bytes(), - ); - let own = CmykSpace::for_profile(Some(&icc)); - assert!(own.is_some(), "the synthetic profile is not the built-in one"); - let area = Rect::new(0, 0, TILE_SIZE * 3, TILE_SIZE); - for (mode, sample, space) in [ - (ColorMode::Cmyk, SampleType::U8, None), - (ColorMode::Cmyk, SampleType::U16, None), - (ColorMode::Cmyk, SampleType::U8, own.clone()), - (ColorMode::Cmyk, SampleType::U16, own.clone()), - (ColorMode::Lab, SampleType::U8, None), - (ColorMode::Lab, SampleType::U16, None), - ] { - let fmt = PixelFormat { mode, sample, alpha: true }; - let kind = TexKind::for_surface(Role::Content, fmt); - assert!(colour_managed(&fmt, kind), "{fmt:?}"); - let ch = fmt.channels(); - let mut s = Surface::new(fmt); - // Tile 0: noise. Tile 1: transparent with a soft dab (runs of equal pixels). Tile 2: - // a flat colour with a few lines of noise. - let n = (TILE_SIZE * TILE_SIZE) as usize * ch; - let noise: Vec = (0..n).map(|i| (i as u32).wrapping_mul(2_654_435_761) as f32 / u32::MAX as f32).collect(); - s.write_region(Rect::new(0, 0, TILE_SIZE, TILE_SIZE), &noise); - let mut dab = [0.8, 0.6, 0.1, 0.05, 0.0]; - for r in (1..30).rev() { - dab[ch - 1] = 1.0 - r as f32 / 30.0; - s.fill_rect(Rect::new(TILE_SIZE + 100 - r, 90 - r, TILE_SIZE + 100 + r, 90 + r), &dab[..ch]); - } - s.fill_rect(Rect::new(TILE_SIZE * 2, 0, TILE_SIZE * 3, TILE_SIZE), &[0.3, 0.2, 0.7, 0.1, 1.0][..ch]); - s.write_region(Rect::new(TILE_SIZE * 2, 40, TILE_SIZE * 3, 43), &noise[..TILE_SIZE as usize * 3 * ch]); - let tiles: Vec<_> = area.tiles().filter_map(|c| s.tile(c).map(|t| (c, t.clone()))).collect(); - assert_eq!(tiles.len(), 3, "{fmt:?}"); - let mut seen = 0; - with_cmyk_space(space.as_ref(), || { - convert_tiles(&s, tiles, kind, |_, cs, bytes| { - for &c in cs { - // The old path: every pixel through `to_rgba` on this thread, in this scope. - let want: Vec = s - .read_region(c.rect()) - .chunks_exact(ch) - .flat_map(|px| { - let v = photocraft_raster::to_rgba(&fmt, px); - match kind { - TexKind::Rgba16F => v.iter().flat_map(|x| f32_to_f16(*x).to_le_bytes()).collect::>(), - _ => v.map(|x| (x.clamp(0.0, 1.0) * 255.0 + 0.5) as u8).to_vec(), - } - }) - .collect(); - assert!( - bytes == want.as_slice(), - "{fmt:?} {c:?} with {}", - if space.is_some() { "the document's profile" } else { "the built-in profile" } - ); - assert_eq!(convert_tile(&s, s.tile(c), kind, c), want, "{fmt:?} {c:?}"); - seen += 1; - } - }); - }); - assert_eq!(seen, 3, "{fmt:?}"); - } - } - - #[test] - fn grid_rounds_out() { - assert_eq!(tile_grid(Rect::new(0, 0, 300, 256)), Rect::new(0, 0, 512, 256)); - } -} +#[cfg(test)] +mod tests; diff --git a/crates/gpu/src/paging.rs b/crates/gpu/src/paging.rs new file mode 100644 index 0000000000..c6d4b61563 --- /dev/null +++ b/crates/gpu/src/paging.rs @@ -0,0 +1,126 @@ +use super::consts::STRIDE; +use super::textures::Cell; +use super::*; + +/// Document pixels of page cell `c`. +pub(crate) fn cell_rect(c: Cell, page: u32) -> Rect { + let p = page as i32; + Rect::new(c.0.saturating_mul(p), c.1.saturating_mul(p), c.0.saturating_add(1).saturating_mul(p), c.1.saturating_add(1).saturating_mul(p)) +} + +/// `r` cut along the grid of `step`-sized squares (row-major). +pub(crate) fn grid_rects(r: Rect, step: u32) -> Vec { + let s = step.max(1) as i32; + let mut out = Vec::new(); + let mut y = r.y0.div_euclid(s) * s; + while y < r.y1 { + let mut x = r.x0.div_euclid(s) * s; + while x < r.x1 { + out.push(Rect::new(x, y, x.saturating_add(s), y.saturating_add(s)).intersect(&r)); + x = x.saturating_add(s); + } + y = y.saturating_add(s); + } + out +} + +/// Number of rectangles `grid_rects` would produce, without allocating them during preflight. +pub(crate) fn grid_rect_count(r: Rect, step: u32) -> Result { + if r.is_empty() { + return Ok(0); + } + let s = i64::from(step.max(1)); + let axis = |lo: i32, hi: i32| usize::try_from((i64::from(hi) - 1).div_euclid(s) - i64::from(lo).div_euclid(s) + 1).ok(); + axis(r.x0, r.x1).and_then(|x| axis(r.y0, r.y1).and_then(|y| x.checked_mul(y))).ok_or_else(|| Unsupported("GPU compositor chunk count is too large".into())) +} + +/// Host length and GPU capacity for the chunk/pass uniform records, including their u32 +/// dynamic binding offsets. Decline unsupported stacks before an invalid buffer faults the device. +pub(crate) fn uniform_buffer_len(chunks: usize, passes: usize, limit: u64) -> Result { + let too_large = || Unsupported("GPU compositor uniform buffer is too large".into()); + let records = chunks.checked_add(passes).and_then(|n| u64::try_from(n).ok()).ok_or_else(too_large)?; + let bytes = records.checked_mul(STRIDE).ok_or_else(too_large)?; + if bytes > limit { + return Err(Unsupported(format!("GPU compositor uniform buffer requires {bytes} bytes; device limit is {limit}"))); + } + if bytes.saturating_sub(STRIDE) > u64::from(u32::MAX) { + return Err(Unsupported("GPU compositor uniform offsets exceed u32".into())); + } + usize::try_from(bytes).map_err(|_| too_large()) +} + +/// The reach up to which each distance field must be exact (the largest any program asks for). +pub(crate) fn field_reaches(progs: &[fx::MapProgram]) -> HashMap { + let mut want: HashMap = HashMap::new(); + for (k, r) in progs.iter().flat_map(|p| p.fields.iter()) { + let w = want.entry(*k).or_insert(0); + *w = (*w).max(*r); + } + want +} + +/// Why a refresh whose layer pages don't fit GPU memory is drawn on the CPU. +pub const OVER_BUDGET: &str = "layers exceed the GPU memory budget; full refresh on the CPU"; + +/// Which of `pages` (LRU clock, key, bytes) to drop, least recently used first, so `incoming` +/// more bytes fit `budget` on top of the `total` held now. Callers leave out pages that must stay. +pub(crate) fn lru_victims(mut pages: Vec<(u64, K, u64)>, total: u64, incoming: u64, budget: u64) -> Vec { + pages.sort_unstable_by_key(|p| p.0); + let mut total = total; + let mut out = Vec::new(); + for (_, k, bytes) in pages { + if total.saturating_add(incoming) <= budget { + break; + } + total = total.saturating_sub(bytes); + out.push(k); + } + out +} + +/// Runs `f` inside GPU error scopes and returns the first error raised. +/// Native wgpu reports validation/internal/OOM errors synchronously; where they only arrive +/// asynchronously (WebGPU) none is reported. +pub(crate) fn first_error(device: &wgpu::Device, f: impl FnOnce() -> T) -> (T, Option) { + let validation = device.push_error_scope(wgpu::ErrorFilter::Validation); + let internal = device.push_error_scope(wgpu::ErrorFilter::Internal); + let memory = device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); + let out = f(); + let mut cx = std::task::Context::from_waker(std::task::Waker::noop()); + let mut error = None; + // Scopes pop in reverse order. + for pop in [memory.pop(), internal.pop(), validation.pop()] { + if let std::task::Poll::Ready(Some(e)) = std::pin::pin!(pop).poll(&mut cx) { + error.get_or_insert(e); + } + } + (out, error) +} + +/// Runs `f` inside the error scopes of [`first_error`], turning a reported error into +/// [`Unsupported`] instead of letting it escape to wgpu's panic handler. +/// +/// Every native caller needs this, watched or not: a validation error (writing into a destroyed +/// or too-small buffer, say) is raised synchronously and never reaches the health callbacks, so a +/// watched compositor still panicked on it. WebGPU reports its errors asynchronously, long after +/// the scope has popped, so wasm relies on the health callbacks alone. +/// +/// A scope also swallows the error that [`DeviceHealth`]'s uncaptured-error handler would have +/// recorded, so a reported error is handed back to `health`: a watched device must stop being +/// used and let the caller fall back to the CPU compositor. +pub(crate) fn scoped_work(device: &wgpu::Device, health: Option, f: impl FnOnce() -> Result) -> Result { + // WebGPU errors arrive asynchronously; its callers still use the health callbacks. + if cfg!(target_arch = "wasm32") { + return f(); + } + let (result, error) = first_error(device, f); + match error { + Some(error) => { + if let Some(health) = health.as_ref() { + health.caught(device, &error); + } + Err(Unsupported(format!("GPU work failed: {error}"))) + } + None => result, + } +} diff --git a/crates/gpu/src/plan.rs b/crates/gpu/src/plan.rs index 38cc879b09..166e977800 100644 --- a/crates/gpu/src/plan.rs +++ b/crates/gpu/src/plan.rs @@ -23,272 +23,25 @@ use photocraft_raster::Surface; use crate::bounds; +mod lower; +mod planner; +mod types; + +#[cfg(test)] +use lower::check_gradient_stops; +pub use lower::{adjustment_on_gpu, adjustment_program, mode_index, stroke_widths}; +use planner::Planner; +#[cfg(test)] +use planner::blend_if_params; +pub use planner::{ + F_ADD_DIFF, F_ATOP, F_BLEND_IF, F_CHANNELS, F_FIRST, F_GATE, F_HDR, F_KNOCKOUT, F_LAB, F_LAYER_SHAPE, F_NO_LAYER, F_OUTLINE, F_QUANT, F_REL, F_STROKE_OUT, + F_TEXT_GAMMA, F_VECTOR, INIT_ALPHA, INIT_COVER, INIT_INSIDE, INIT_OPAQUE, INIT_OUTLINE, INIT_RELATIVE, INIT_SCALE, INIT_VSTROKE, SHAPE_MAP, +}; +pub use types::{Checkpoint, DocCtx, FxLayer, Kernel, MapRef, MaskUse, Pass, Role, SurfaceRef, TexUse, Unsupported}; + /// Index of a chunk-sized accumulator texture. pub type Slot = u32; -/// Pipeline (fragment entry point) of a pass. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub enum Kernel { - /// Transparent fill (no draw). - Clear, - Content, - Mask, - Blend, - /// `Content` then `Blend` in one pass: a plain layer's pixels blended straight onto A. - LayerBlend, - /// A run of consecutive `LayerBlend` passes drawn as one (never planned: the executor draws - /// it in their place, see `batch_runs`). - LayerBatch, - /// `LayerBatch` of a run whose layers all blend Normal without text gamma, outside Lab - /// documents (never planned: the executor picks it, see `batch_kernel`). - LayerBatchNormal, - Atop, - Adjust, - AdjMix, - Lerp, - /// Effect chain start: the layer at fill opacity, or an opaque copy of a clipping base. - FxInit, - /// Paint an effect through a coverage map (or the layer's alpha) into A. - FxPaint, - /// Layer + interior effects over the exterior result, then layer opacity against the backdrop. - FxMerge, - /// Outside strokes: accumulate one stroke's share (`kind` 0, premultiplied colour) or its - /// coverage (`kind` 1). - FxStroke, - /// Outside strokes: resolve the accumulated strokes over the exterior result. - FxStrokeEnd, - /// Copy slot A into `dst` (an existing slot) over the pass clip (no draw). - CopyRect, - /// Copy all of slot A into the fresh slot `dst` (no draw). - CopyFull, - // Effect-map kernels (single-channel targets over an effect region, see `fx`). - MShift, - MDilate, - MBlur, - MGlow, - MFinish, - MBevelH, - MBevelShade, - MStroke, - MBevelTex, -} - -impl Kernel { - /// Fragment entry point in `compose.wgsl` (`None` for copies and clears). - pub fn entry(self) -> Option<&'static str> { - Some(match self { - Kernel::Clear | Kernel::CopyRect | Kernel::CopyFull => return None, - Kernel::Content => "fs_content", - Kernel::Mask => "fs_mask", - Kernel::Blend => "fs_blend", - Kernel::LayerBlend => "fs_layerblend", - Kernel::LayerBatch => "fs_layerbatch", - Kernel::LayerBatchNormal => "fs_layerbatch_normal", - Kernel::Atop => "fs_atop", - Kernel::Adjust => "fs_adjust", - Kernel::AdjMix => "fs_adjmix", - Kernel::Lerp => "fs_lerp", - Kernel::FxInit => "fs_fxinit", - Kernel::FxPaint => "fs_fxpaint", - Kernel::FxMerge => "fs_fxmerge", - Kernel::FxStroke => "fs_fxstroke", - Kernel::FxStrokeEnd => "fs_fxstrokeend", - Kernel::MShift => "fs_mshift", - Kernel::MDilate => "fs_mdilate", - Kernel::MBlur => "fs_mblur", - Kernel::MGlow => "fs_mglow", - Kernel::MFinish => "fs_mfinish", - Kernel::MBevelH => "fs_mbevelh", - Kernel::MBevelShade => "fs_mbevelshade", - Kernel::MStroke => "fs_mstroke", - Kernel::MBevelTex => "fs_mbeveltex", - }) - } - - /// Kernels that write effect maps (R32F / R16F targets) rather than RGBA accumulators. - pub fn is_map(self) -> bool { - matches!( - self, - Kernel::MShift - | Kernel::MDilate - | Kernel::MBlur - | Kernel::MGlow - | Kernel::MFinish - | Kernel::MBevelH - | Kernel::MBevelShade - | Kernel::MStroke - | Kernel::MBevelTex - ) - } - - /// Every kernel with a pipeline. - pub const DRAWN: [Kernel; 24] = [ - Kernel::Content, - Kernel::Mask, - Kernel::Blend, - Kernel::LayerBlend, - Kernel::LayerBatch, - Kernel::LayerBatchNormal, - Kernel::Atop, - Kernel::Adjust, - Kernel::AdjMix, - Kernel::Lerp, - Kernel::FxInit, - Kernel::FxPaint, - Kernel::FxMerge, - Kernel::FxStroke, - Kernel::FxStrokeEnd, - Kernel::MShift, - Kernel::MDilate, - Kernel::MBlur, - Kernel::MGlow, - Kernel::MFinish, - Kernel::MBevelH, - Kernel::MBevelShade, - Kernel::MStroke, - Kernel::MBevelTex, - ]; -} - -/// Which resident texture a pass samples. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub enum Role { - Content, - Mask, - /// A stroked shape's stroke alone (its fill uses `Content`). - Stroke, -} - -/// A surface the pass needs on the GPU. -#[derive(Clone, Debug)] -pub struct TexUse<'a> { - pub layer: LayerId, - pub role: Role, - pub surface: SurfaceRef<'a>, -} - -/// An effect map sampled by a pass: map `map` of enabled effect `item` of `plan.fx[fx]`. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct MapRef { - pub fx: usize, - pub item: usize, - pub map: usize, -} - -#[derive(Clone, Debug)] -pub struct Pass<'a> { - pub kernel: Kernel, - pub dst: Slot, - pub a: Option, - pub b: Option, - pub c: Option, - /// A fourth slot, bound in place of `tex` (passes without layer pixels). - pub d: Option, - pub mode: BlendMode, - pub opacity: f32, - /// The layer's Fill where it isn't folded into `opacity`: the final blend of a plain layer - /// (`Kernel::Blend`), so the special eight can apply it inside the blend. 1 elsewhere. - pub fill: f32, - /// Layer pixels (raster / text / shape / smart cache / fill cache). - pub tex: Option>, - /// Colour outside `tex` (the surface's default pixel), the solid fill colour, or the effect - /// colour. - pub color: [f32; 4], - pub mask: Option>, - /// Adjustment kind (see `adjust` in compose.wgsl) and parameters; the coverage kind of an - /// effect paint. - pub adjust_kind: i32, - pub params: [[f32; 4]; 4], - pub extra: [f32; 4], - /// Extra shader flags (`F_KNOCKOUT`, …). - pub flags: u32, - /// 4096-entry LUT rows (Levels / Curves / Gradient map / gradient stops). - pub lut: Option>, - pub gradient: bool, - /// Effect map sampled by `FxPaint`. - pub map: Option, - /// Pattern painted by `FxPaint`. - pub pattern: Option<&'a Pattern>, - /// Only pixels inside this rect (document coordinates) are computed; the pass is skipped for - /// chunks it misses. Consumers of the slot must be clipped alike. - pub clip: Option, -} - -/// Pixels a pass samples: a surface of the document, or one derived from it on the CPU (a -/// combined pixel × vector mask, a shape's fill or stroke alone). -#[derive(Clone, Debug)] -pub enum SurfaceRef<'a> { - Doc(&'a Surface), - Derived(std::sync::Arc), -} - -impl SurfaceRef<'_> { - pub fn get(&self) -> &Surface { - match self { - SurfaceRef::Doc(s) => s, - SurfaceRef::Derived(s) => s, - } - } -} - -#[derive(Clone, Debug)] -pub struct MaskUse<'a> { - pub layer: LayerId, - pub surface: SurfaceRef<'a>, - pub density: f32, - pub default: f32, -} - -impl<'a> Pass<'a> { - pub(crate) fn new(kernel: Kernel, dst: Slot) -> Self { - Pass { - kernel, - dst, - a: None, - b: None, - c: None, - d: None, - mode: BlendMode::Normal, - opacity: 1.0, - fill: 1.0, - tex: None, - color: [0.0; 4], - mask: None, - adjust_kind: 0, - params: [[0.0; 4]; 4], - extra: [0.0; 4], - flags: 0, - lut: None, - gradient: false, - map: None, - pattern: None, - clip: None, - } - } -} - -/// Why a document can't be composited on the GPU (the caller falls back to the CPU compositor). -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct Unsupported(pub String); - -impl std::fmt::Display for Unsupported { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "GPU compositor: {}", self.0) - } -} - -impl std::error::Error for Unsupported {} - -/// A layer whose effects the plan renders: its maps are built (or reused) before the chunks run. -#[derive(Clone, Copy, Debug)] -pub struct FxLayer<'a> { - pub layer: &'a Layer, - /// Region the maps cover (`compose::effect_maps`). - pub region: Rect, - /// Layer bounds (gradients and linked patterns are laid out in them). - pub bounds: Rect, -} - #[derive(Debug)] pub struct Plan<'a> { pub passes: Vec>, @@ -300,46 +53,6 @@ pub struct Plan<'a> { pub checkpoints: Vec, } -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct Checkpoint { - /// First root layer included after occlusion pruning. - pub layer_start: usize, - /// Root layers below this boundary (including the complete clipping unit). - pub layer_end: usize, - /// Resume at this pass with `slot` restored. - pub pass_end: usize, - pub slot: Slot, -} - -/// Document-level inputs of a plan. -#[derive(Clone, Copy)] -pub struct DocCtx<'a> { - pub canvas: Rect, - pub transfer: Transfer, - pub light: GlobalLight, - pub patterns: &'a [Pattern], - /// Colour mode (channel restrictions name its channels). - pub mode: photocraft_color::ColorMode, - /// Sample depth (adjustment results are rounded to it). - pub depth: photocraft_color::SampleType, - /// The document (effect geometry the CPU computes, e.g. gradient stroke frames). - pub doc: &'a Document, -} - -impl<'a> DocCtx<'a> { - pub fn of(doc: &'a Document) -> Self { - DocCtx { - canvas: doc.bounds(), - transfer: Transfer::for_document(doc.mode, doc.depth), - light: doc.global_light, - patterns: &doc.patterns, - mode: doc.mode, - depth: doc.depth, - doc, - } - } -} - /// Build the pass list for `doc`. pub fn plan(doc: &Document) -> Result, Unsupported> { if doc.mode == photocraft_color::ColorMode::Multichannel { @@ -354,1876 +67,5 @@ pub fn plan(doc: &Document) -> Result, Unsupported> { Ok(p.finish(root)) } -struct Planner<'a> { - passes: Vec>, - free: Vec, - refs: Vec, - cx: DocCtx<'a>, - fx: Vec>, - checkpoints: Vec, - /// Layers planned so far, counting a layer each time it is planned (a clipped pass-through - /// group is planned twice). - visits: usize, -} - -/// Most layer plannings one document may take: a pass-through group with clipped layers is -/// planned twice, so groups nested in one another double the work at every level. -const MAX_PLAN_VISITS: usize = 100_000; - -/// Coverage source of an effect paint (`kind` in `fs_fxpaint`); flags refine it. -#[derive(Clone, Copy)] -enum Cov { - /// An effect map; `outside` beyond its region. - Map(MapRef, f32), - /// Full coverage. - One, -} - -/// Shader flags for effect passes (keep in sync with compose.wgsl). Coverage `m` of a paint, with -/// `a` the layer's alpha and `inside` = `a > 0.5/255`: -/// knockout `m × (1 − a × k)` (k in `p4.w`); gate `inside ? m : 0`; rel `inside ? min(m / a, 1) : 0`; -/// stroke-out `inside ? (vector ? 0 : (1 − a) / (1 − layer alpha), 1 at an opaque layer) : m`. -pub const F_KNOCKOUT: u32 = 16; -/// Effect merge: A already holds the layer; only mix with the backdrop by the layer's opacity. -pub const F_NO_LAYER: u32 = 32; -/// Outside strokes along a filled shape's outline (`effects::outline_share`; the coverage slot -/// carries the layer's alpha in `.g`). -pub const F_OUTLINE: u32 = 131072; -/// Shape layer (outside strokes never show inside it). -pub const F_VECTOR: u32 = 64; -/// Merge onto an opaque clipping base, keeping its alpha. -pub const F_ATOP: u32 = 128; -pub const F_GATE: u32 = 256; -pub const F_REL: u32 = 512; -pub const F_STROKE_OUT: u32 = 1024; -/// First outside stroke (no accumulated share yet). -pub const F_FIRST: u32 = 2048; -/// `Lerp` per channel: weights in `p0` (channel restrictions), no opacity or mask. -pub const F_CHANNELS: u32 = 4096; -/// Lab document: Normal blending mixes in CIELAB (`psblend::LAB_MIX`). -pub const F_LAB: u32 = 65536; -/// 32-bit float document: Add, Divide and Exposure retain values above 1; the non-separable -/// blend modes clip only below 0 (`psblend::HDR`). -pub const F_HDR: u32 = 262144; -/// `Lerp`: A rounded to `p0.x` steps per unit (adjustment results on integer documents). -pub const F_QUANT: u32 = 32768; -/// `Lerp` as A + (B − C) premultiplied (layers clipped to pass-through groups). -pub const F_ADD_DIFF: u32 = 16384; -/// `Lerp`: B mixed back towards A (the backdrop) by the layer's Blend If weight -/// (`compose::apply_blend_if`), from C ("This Layer", or B itself for an adjustment layer, `p4.y`) -/// and A ("Underlying Layer"). The ranges are packed in `p0..p3` (`blend_if_params`); `p4.x` marks -/// a one-channel document. -pub const F_BLEND_IF: u32 = 524288; -/// Blend / Atop / FxMerge of a type layer: coverage mixed at `psblend::TEXT_GAMMA`. -pub const F_TEXT_GAMMA: u32 = 8192; -/// `FxMerge`: B is the layer's shape (its content); the layer is its colour at fill opacity -/// (`p0.x`) inside the shape, times the shape's alpha: `FxInit` `INIT_INSIDE` then -/// `INIT_ALPHA` in the merge, for a layer with no interior effects between them. -pub const F_LAYER_SHAPE: u32 = 1_048_576; - -/// A layer's Blend If ranges for `F_BLEND_IF`: Gray, then the colour channels, each as -/// [this layer, underlying layer]; every range as two floats, `black low × 256 + black high` and -/// `white low × 256 + white high` (exact in f32), so entry `e`, side `s` starts at float -/// `(e × 2 + s) × 2`. Entries past the fourth never apply (RGB has four, one-channel modes two). -fn blend_if_params(bi: &photocraft_doc::BlendIf) -> [[f32; 4]; 4] { - let mut f = [0.0f32; 16]; - for e in 0..4 { - for (s, r) in bi.get(e).iter().enumerate() { - let i = (e * 2 + s) * 2; - f[i] = f32::from(r.black[0]) * 256.0 + f32::from(r.black[1]); - f[i + 1] = f32::from(r.white[0]) * 256.0 + f32::from(r.white[1]); - } - } - [[f[0], f[1], f[2], f[3]], [f[4], f[5], f[6], f[7]], [f[8], f[9], f[10], f[11]], [f[12], f[13], f[14], f[15]]] -} - -/// `F_TEXT_GAMMA` for type layers while text gamma blending is on; the gamma goes in `p4.w`. -fn gamma_flag(layer: &Layer) -> u32 { - if photocraft_compose::text_gamma(layer) != 1.0 { F_TEXT_GAMMA } else { 0 } -} - -/// `FxInit` kinds: A at `opacity` × alpha; an opaque copy of A; A's colour with alpha `opacity` -/// inside B's shape; A with alpha × B's alpha. -pub const INIT_SCALE: i32 = 0; -pub const INIT_OPAQUE: i32 = 1; -pub const INIT_INSIDE: i32 = 2; -pub const INIT_ALPHA: i32 = 3; -/// The vector stroke C over A relative to the shape B, at `opacity`. -pub const INIT_VSTROKE: i32 = 4; -/// A's colour with alpha `opacity` × A's alpha relative to B's. -pub const INIT_RELATIVE: i32 = 5; -/// Outside-stroke coverage seed: (0, A's alpha). -pub const INIT_COVER: i32 = 6; -/// A with its alpha joined with the effect shape (the map). -pub const INIT_OUTLINE: i32 = 7; - -/// `MapRef::item` of the layer's effect shape (`compose::layer_shape`) instead of an effect map. -pub const SHAPE_MAP: usize = usize::MAX; - -impl<'a> Planner<'a> { - fn new(cx: DocCtx<'a>) -> Self { - Planner { passes: Vec::new(), free: Vec::new(), refs: Vec::new(), cx, fx: Vec::new(), checkpoints: Vec::new(), visits: 0 } - } - - fn finish(self, root: Slot) -> Plan<'a> { - Plan { passes: self.passes, slots: self.refs.len() as u32, root, fx: self.fx, checkpoints: self.checkpoints } - } - - fn alloc(&mut self) -> Slot { - if let Some(s) = self.free.pop() { - self.refs[s as usize] = 1; - return s; - } - self.refs.push(1); - (self.refs.len() - 1) as Slot - } - fn retain(&mut self, s: Slot) -> Slot { - self.refs[s as usize] += 1; - s - } - fn release(&mut self, s: Slot) { - let r = &mut self.refs[s as usize]; - *r -= 1; - if *r == 0 { - self.free.push(s); - } - } - /// Emit `pass` into a fresh slot, releasing its inputs. - fn emit(&mut self, mut pass: Pass<'a>) -> Slot { - let dst = self.alloc(); - pass.dst = dst; - if self.cx.mode == photocraft_color::ColorMode::Lab { - pass.flags |= F_LAB; - } - if self.cx.depth == photocraft_color::SampleType::F32 { - pass.flags |= F_HDR; - } - let (a, b, c, d) = (pass.a, pass.b, pass.c, pass.d); - self.passes.push(pass); - for s in [a, b, c, d].into_iter().flatten() { - self.release(s); - } - dst - } - fn clear(&mut self) -> Slot { - self.emit(Pass::new(Kernel::Clear, 0)) - } - - /// composite_stack: returns the new backdrop (consumes `backdrop`). - fn stack(&mut self, layers: &'a [Layer], backdrop: Slot) -> Result { - self.stack_inner(layers, backdrop, None) - } - - fn stack_inner(&mut self, layers: &'a [Layer], mut backdrop: Slot, root_start: Option) -> Result { - let mut i = 0; - while i < layers.len() { - let base = &layers[i]; - let mut j = i + 1; - while j < layers.len() && layers[j].clipped && !base.clipped { - j += 1; - } - let clipped = &layers[i + 1..j]; - if base.visible { - backdrop = self.layer(base, clipped, backdrop)?; - if let (LayerContent::Adjustment(_), Some(q)) = (&base.content, photocraft_compose::adjustment_quantum(self.cx.depth)) { - // compose: adjustment results are rounded to the document's depth. - let mut p = Pass::new(Kernel::Lerp, 0); - p.a = Some(backdrop); - p.flags = F_QUANT; - p.params[0] = [q, 0.0, 0.0, 0.0]; - backdrop = self.emit(p); - } - } - i = j.max(i + 1); - if let Some(start) = root_start - && self.refs.iter().enumerate().all(|(slot, &refs)| refs == u32::from(slot == backdrop as usize)) - { - self.checkpoints.push(Checkpoint { layer_start: start, layer_end: start.saturating_add(i), pass_end: self.passes.len(), slot: backdrop }); - } - } - Ok(backdrop) - } - - fn mask_use(&self, layer: &'a Layer) -> Option> { - if let Some(c) = photocraft_compose::masks::combined_mask(layer, self.cx.canvas) { - let default = c.default_pixel().first().copied().unwrap_or(1.0); - return Some(MaskUse { layer: layer.id, surface: SurfaceRef::Derived(std::sync::Arc::new(c)), density: 1.0, default }); - } - let m = layer.mask.as_ref()?; - if !m.enabled { - return None; - } - Some(MaskUse { - layer: layer.id, - surface: SurfaceRef::Doc(&m.surface), - density: m.density, - default: m.surface.default_pixel().first().copied().unwrap_or(1.0), - }) - } - - /// `compose::apply_blend_if`: `after` (the backdrop with `layer` drawn) mixed back towards - /// `before` (the backdrop without it) where the layer's Blend If ranges hide it. "This Layer" - /// is the layer's own content with its masks; an adjustment layer is judged by its result. - /// Consumes both slots. - fn blend_if(&mut self, layer: &'a Layer, before: Slot, after: Slot) -> Result { - let own = match layer.content { - LayerContent::Adjustment(_) => None, - _ => Some(self.content(layer)?), - }; - let mut p = Pass::new(Kernel::Lerp, 0); - p.a = Some(before); - p.b = Some(after); - p.c = own; - p.flags = F_BLEND_IF; - p.params = blend_if_params(&layer.blend_if); - let one_channel = self.cx.mode != photocraft_color::ColorMode::Rgb; - p.extra = [f32::from(u8::from(one_channel)), f32::from(u8::from(own.is_none())), 0.0, 0.0]; - Ok(self.emit(p)) - } - - /// Channel restrictions and Blend If around `draw`, which composites `layer` onto `backdrop` - /// (`compose::composite_layer` / `composite_atop`: both are relative to the same backdrop). - fn restricted(&mut self, layer: &'a Layer, backdrop: Slot, draw: impl FnOnce(&mut Self, Slot) -> Result) -> Result { - let w = photocraft_compose::channel_weights(layer, self.cx.mode); - let blend_if = photocraft_compose::blend_if_active(layer, self.cx.mode); - if w.is_none() && !blend_if { - return draw(self, backdrop); - } - let before = self.retain(backdrop); - let mut after = draw(self, backdrop)?; - if let Some(w) = w { - let b = if blend_if { self.retain(before) } else { before }; - after = self.restore_channels(b, after, w); - } - if blend_if { - after = self.blend_if(layer, before, after)?; - } - Ok(after) - } - - /// Blending Options › Advanced Blending (knockout, clipped layers blended individually, blend - /// interior effects as group, transparency shapes off, masks hiding effects) has no GPU pass: - /// documents using it are composited on the CPU (`photocraft_compose::advanced`). Layers at - /// Photoshop's defaults pass this check for free. - fn check_advanced(&self, layer: &Layer, clipped: &[Layer]) -> Result<(), Unsupported> { - if photocraft_compose::advanced_active(layer, clipped) { - return Err(Unsupported(format!("Advanced Blending on `{}` (composited on the CPU)", layer.name))); - } - Ok(()) - } - - /// composite_layer, honouring the layer's channel restrictions. - fn layer(&mut self, layer: &'a Layer, clipped: &'a [Layer], backdrop: Slot) -> Result { - self.visits += 1; - if self.visits > MAX_PLAN_VISITS { - return Err(Unsupported("too many nested layers to plan for the GPU (composited on the CPU)".into())); - } - self.check_advanced(layer, clipped)?; - self.restricted(layer, backdrop, |s, b| s.layer_any(layer, clipped, b)) - } - - /// `compose::restore_channels`: `after` with the channels a layer leaves out taken from - /// `before` (consumes both). - fn restore_channels(&mut self, before: Slot, after: Slot, w: [f32; 3]) -> Slot { - let mut p = Pass::new(Kernel::Lerp, 0); - p.a = Some(before); - p.b = Some(after); - p.flags = F_CHANNELS; - p.params[0] = [w[0], w[1], w[2], 1.0]; - self.emit(p) - } - - fn layer_any(&mut self, layer: &'a Layer, clipped: &'a [Layer], backdrop: Slot) -> Result { - match layer.artboard() { - Some(ab) => self.artboard(layer, ab, clipped, backdrop), - None => self.layer_plain(layer, clipped, backdrop), - } - } - - /// compose::composite_artboard: the board's background and the group composited over the - /// backdrop, kept only inside the board (contents and effects outside it are clipped away). - fn artboard(&mut self, layer: &'a Layer, ab: &photocraft_doc::Artboard, clipped: &'a [Layer], backdrop: Slot) -> Result { - let board = ab.rect.intersect(&self.cx.canvas); - if board.is_empty() { - return Ok(backdrop); - } - let before = self.retain(backdrop); - let mut sub = backdrop; - if let Some(bg) = ab.background.rgba() { - let mut c = Pass::new(Kernel::Content, 0); - c.color = bg; - let c = self.emit(c); - let mut p = Pass::new(Kernel::Blend, 0); - p.a = Some(sub); - p.b = Some(c); - sub = self.emit(p); - } - let sub = self.layer_plain(layer, clipped, sub)?; - let dst = if self.refs[before as usize] == 1 { - before - } else { - let n = self.alloc(); - let mut p = Pass::new(Kernel::CopyFull, n); - p.a = Some(before); - self.passes.push(p); - self.release(before); - n - }; - let mut p = Pass::new(Kernel::CopyRect, dst); - p.a = Some(sub); - p.clip = Some(board); - self.passes.push(p); - self.release(sub); - Ok(dst) - } - - fn layer_plain(&mut self, layer: &'a Layer, clipped: &'a [Layer], backdrop: Slot) -> Result { - let opacity = layer.opacity * layer.fill_opacity; - let visible_clipped: Vec<&'a Layer> = clipped.iter().filter(|c| c.visible).collect(); - - // Below 100% fill a pass-through group renders isolated (as the CPU compositor does), and - // so does one that is the base of a clipping group and holds an adjustment layer. - let clip_base_adjusts = !visible_clipped.is_empty() - && matches!(&layer.content, LayerContent::Group(g) if g.children.iter().any(|c| c.visible && matches!(c.content, LayerContent::Adjustment(_)))); - if let LayerContent::Group(g) = &layer.content - && layer.blend == BlendMode::PassThrough - && layer.fill_opacity >= 1.0 - && !has_effects(layer) - && !clip_base_adjusts - { - let before = self.retain(backdrop); - let mut after = self.stack(&g.children, backdrop)?; - if opacity < 1.0 || layer.mask.is_some() || layer.vector_mask.is_some() { - let mut p = Pass::new(Kernel::Lerp, 0); - p.a = Some(self.retain(before)); - p.b = Some(after); - p.opacity = opacity; - p.mask = self.mask_use(layer); - after = self.emit(p); - } - if visible_clipped.is_empty() { - self.release(before); - return Ok(after); - } - // Layers clipped to a pass-through group (compose: their effect on the group's - // isolated rendering, each placed over the original backdrop, is added to the - // pass-through result, premultiplied). - let iso = self.content(layer)?; - let iso_keep = self.retain(iso); - let mut clipped_iso = iso; - for c in visible_clipped { - clipped_iso = self.atop(c, clipped_iso)?; - } - let over = |s: &mut Self, src: Slot, before: Slot| { - let mut p = Pass::new(Kernel::Blend, 0); - p.a = Some(before); - p.b = Some(src); - p.opacity = opacity; - s.emit(p) - }; - let b2 = self.retain(before); - let without = over(self, iso_keep, b2); - let with = over(self, clipped_iso, before); - let mut p = Pass::new(Kernel::Lerp, 0); - p.a = Some(after); - p.b = Some(with); - p.c = Some(without); - p.flags = F_ADD_DIFF; - return Ok(self.emit(p)); - } - - if let LayerContent::Adjustment(adj) = &layer.content { - let before = self.retain(backdrop); - let mut adjusted = self.adjust(adj, backdrop)?; - for c in visible_clipped { - adjusted = self.atop(c, adjusted)?; - } - let mut p = Pass::new(Kernel::AdjMix, 0); - p.a = Some(before); - p.b = Some(adjusted); - p.mode = layer.blend; - p.opacity = opacity; - p.mask = self.mask_use(layer); - return Ok(self.emit(p)); - } - - if has_effects(layer) { - return self.effects(layer, &visible_clipped, backdrop, false); - } - - if let LayerContent::Shape(sh) = &layer.content - && !visible_clipped.is_empty() - && let Some((fill, stroke)) = photocraft_compose::shape_split::split(sh, self.cx.canvas, self.cx.depth) - { - // The vector stroke goes above the clipped layers: the fill is the clipping base, - // the stroke is laid over the clipped result, then the masks apply to both - // (compose::shape_parts). - let mut content = self.shape_part(layer, Role::Content, fill); - for c in visible_clipped { - content = self.atop(c, content)?; - } - let stroke = self.shape_part(layer, Role::Stroke, stroke); - let mut p = Pass::new(Kernel::Blend, 0); - p.a = Some(content); - p.b = Some(stroke); - let mut content = self.emit(p); - if let Some(m) = self.mask_use(layer) { - let mut p = Pass::new(Kernel::Mask, 0); - p.a = Some(content); - p.mask = Some(m); - content = self.emit(p); - } - let mut p = Pass::new(Kernel::Blend, 0); - p.a = Some(backdrop); - p.b = Some(content); - p.mode = layer.blend; - p.opacity = layer.opacity; - p.fill = layer.fill_opacity; - return Ok(self.emit(p)); - } - - // A layer that covers little of the canvas composites only over its bounds and is - // copied back into the backdrop (#125): a layout with hundreds of small text and shape - // layers otherwise shades every layer over every chunk. - let clip = self.local_clip(layer); - if clip.is_some_and(|c| c.is_empty()) { - // Nothing to draw (an empty layer, or a group of them). - for c in &visible_clipped { - self.check_advanced(c, &[])?; - } - return Ok(backdrop); - } - // A layer with nothing clipped to it whose content is one Content pass is blended - // straight from its pixels (`Kernel::LayerBlend`): one pass instead of two, and no - // scratch chunk written and read back. - let mut p = if visible_clipped.is_empty() && single_content_pass(layer) { - let mut p = self.content_pass(layer)?; - p.kernel = Kernel::LayerBlend; - p - } else { - let start = self.passes.len(); - let mut content = self.content(layer)?; - for c in visible_clipped { - content = self.atop(c, content)?; - } - if let Some(clip) = clip { - // Everything that built the layer's content only matters inside its bounds. - for p in &mut self.passes[start..] { - if p.clip.is_none() && !matches!(p.kernel, Kernel::Clear | Kernel::CopyFull) { - p.clip = Some(clip); - } - } - } - let mut p = Pass::new(Kernel::Blend, 0); - p.b = Some(content); - p - }; - p.a = Some(if clip.is_some() { self.retain(backdrop) } else { backdrop }); - p.mode = layer.blend; - p.opacity = layer.opacity; - p.fill = layer.fill_opacity; - p.flags |= gamma_flag(layer); - p.extra[3] = photocraft_compose::text_gamma(layer); - p.clip = clip; - let merged = self.emit(p); - match clip { - Some(clip) => Ok(self.write_back(backdrop, merged, clip)), - None => Ok(merged), - } - } - - /// The rect a plain layer composites over: its composite bounds when they cover at most half - /// the canvas (beyond that, compositing everywhere costs less than the copy back). - fn local_clip(&self, layer: &Layer) -> Option { - let canvas = self.cx.canvas; - let b = bounds::composite_bounds(layer, canvas)?; - (b.width() as u64 * b.height() as u64 * 2 <= canvas.width() as u64 * canvas.height() as u64).then_some(b) - } - - /// Copy `merged` into `backdrop` over `clip` (in place when nothing else holds the backdrop); - /// returns the new backdrop. Consumes both. - fn write_back(&mut self, backdrop: Slot, merged: Slot, clip: Rect) -> Slot { - // A clip over the whole canvas left no pixel of `merged` uncomputed: it is the backdrop. - if clip.contains_rect(&self.cx.canvas) { - self.release(backdrop); - return merged; - } - let dst = if self.refs[backdrop as usize] == 1 { - backdrop - } else { - let n = self.alloc(); - let mut p = Pass::new(Kernel::CopyFull, n); - p.a = Some(backdrop); - self.passes.push(p); - self.release(backdrop); - n - }; - let mut p = Pass::new(Kernel::CopyRect, dst); - p.a = Some(merged); - p.clip = Some(clip); - self.passes.push(p); - self.release(merged); - dst - } - - /// A stroked shape's fill or vector stroke alone (`compose::shape_split`), unmasked. - fn shape_part(&mut self, layer: &'a Layer, role: Role, surface: Surface) -> Slot { - let mut p = Pass::new(Kernel::Content, 0); - p.color = photocraft_raster::to_rgba(&surface.format(), &surface.default_pixel()); - if surface.tile_count() > 0 { - p.tex = Some(TexUse { layer: layer.id, role, surface: SurfaceRef::Derived(std::sync::Arc::new(surface)) }); - } - self.emit(p) - } - - /// render_content for non-adjustment layers. - fn content(&mut self, layer: &'a Layer) -> Result { - match &layer.content { - LayerContent::Group(g) => { - let empty = self.clear(); - let s = self.stack(&g.children, empty)?; - if layer.mask.is_some() || layer.vector_mask.is_some() { - let mut p = Pass::new(Kernel::Mask, 0); - p.a = Some(s); - p.mask = self.mask_use(layer); - return Ok(self.emit(p)); - } - Ok(s) - } - // Adjustments are handled by the caller and never get here. - LayerContent::Adjustment(_) => Err(Unsupported("adjustment layer reached the content planner".into())), - LayerContent::Fill(f @ Fill::Pattern { name, scale, id, angle, link, phase }) if layer.fill_cache.as_ref().is_none_or(|c| c.fill != *f) => { - // compose::render_fill: the pattern tiled from the layer's frame (transparent - // when missing), then the layer's masks. - let empty = self.clear(); - let Some(pat) = photocraft_doc::pattern::find(self.cx.patterns, id, name).filter(|p| p.is_paintable()) else { return Ok(empty) }; - let frame = photocraft_compose::fill_frame(layer, self.cx.canvas); - let anchor = if frame.is_empty() { (0.0, 0.0) } else { (f64::from(frame.x0), f64::from(frame.y0)) }; - let paint = Paint::Pattern(pat, placement(anchor, *link, *phase, *scale, *angle)); - let canvas = self.cx.canvas; - let s = self.paint(empty, empty, Cov::One, &paint, BlendMode::Normal, 1.0, 0, canvas, canvas); - if layer.mask.is_some() || layer.vector_mask.is_some() { - let mut p = Pass::new(Kernel::Mask, 0); - p.a = Some(s); - p.mask = self.mask_use(layer); - return Ok(self.emit(p)); - } - Ok(s) - } - _ => { - let p = self.content_pass(layer)?; - Ok(self.emit(p)) - } - } - } - - /// The Content pass of a raster / text / shape / smart / fill layer. - fn content_pass(&self, layer: &'a Layer) -> Result, Unsupported> { - let mut p = Pass::new(Kernel::Content, 0); - p.mask = self.mask_use(layer); - match &layer.content { - LayerContent::Fill(f) => match &layer.fill_cache { - Some(c) if c.fill == *f => self.surface_tex(&mut p, layer.id, &c.surface), - _ => self.fill(&mut p, f, photocraft_compose::fill_frame(layer, self.cx.canvas))?, - }, - _ => { - if let Some(s) = layer.surface() { - self.surface_tex(&mut p, layer.id, s); - } - } - } - Ok(p) - } - - fn surface_tex(&self, p: &mut Pass<'a>, id: LayerId, s: &'a Surface) { - let dp = s.default_pixel(); - p.color = photocraft_raster::to_rgba(&s.format(), &dp); - if s.tile_count() > 0 { - p.tex = Some(TexUse { layer: id, role: Role::Content, surface: SurfaceRef::Doc(s) }); - } - } - - fn fill(&self, p: &mut Pass<'a>, f: &Fill, frame: photocraft_geom::Rect) -> Result<(), Unsupported> { - // The RGB shader cannot interpolate or dither native ink channels. - if self.cx.mode == photocraft_color::ColorMode::Cmyk && !matches!(f, Fill::Pattern { .. }) { - return Err(Unsupported("native CMYK fill (composited on the CPU)".into())); - } - match f { - Fill::Solid(c) => { - let rgb = c.to_rgb(); - p.color = [rgb[0], rgb[1], rgb[2], c.alpha]; - } - Fill::Gradient { stops, opacity_stops, angle, scale, style, reverse, offset, dither, .. } => { - check_gradient_stops(stops)?; - check_gradient_stops(opacity_stops)?; - p.gradient = true; - // compose::render_fill: whole-pixel end points (fill_layout). - let (angle, scale, offset) = photocraft_compose::fill_layout::gradient_layout(*style, *angle, *scale, *offset, frame); - p.params[0] = [angle, scale, if *reverse { 1.0 } else { 0.0 }, style_index(*style)]; - let c = frame; - p.params[1] = [c.x0 as f32, c.y0 as f32, c.width() as f32, c.height() as f32]; - // p2.xy: centre offset; p2.z: the depth's levels a dithered pixel is rounded to - // (0: float, compose::gradient_fill::render_quantized); p2.w: dither (the shared - // position hash, see the shader). - let quantum = photocraft_compose::adjustment_quantum(self.cx.depth).unwrap_or(0.0); - p.params[2] = [offset.0, offset.1, quantum, if *dither { 1.0 } else { 0.0 }]; - let ramp = photocraft_compose::gradient_fill::Ramp::new(f); - let mut rows = vec![[0.0f32; 4096]; 4]; - for k in 0..4096 { - let v = ramp.as_ref().map_or([0.0; 4], |r| r.sample(k as f32 / 4095.0)); - for (ch, row) in rows.iter_mut().enumerate() { - row[k] = v[ch]; - } - } - p.lut = Some(rows); - } - // Pattern fills fall back to the CPU compositor (see `check`). - Fill::Pattern { .. } => {} - } - Ok(()) - } - - /// composite_atop: `layer` onto `base`, restricted to the base's alpha, honouring the - /// layer's channel restrictions. - fn atop(&mut self, layer: &'a Layer, base: Slot) -> Result { - self.check_advanced(layer, &[])?; - self.restricted(layer, base, |s, b| s.atop_any(layer, b)) - } - - fn atop_any(&mut self, layer: &'a Layer, base: Slot) -> Result { - let opacity = layer.opacity * layer.fill_opacity; - if let LayerContent::Adjustment(adj) = &layer.content { - let before = self.retain(base); - let adjusted = self.adjust(adj, base)?; - let mut p = Pass::new(Kernel::AdjMix, 0); - p.a = Some(before); - p.b = Some(adjusted); - p.mode = layer.blend; - p.opacity = opacity; - p.mask = self.mask_use(layer); - return Ok(self.emit(p)); - } - if has_effects(layer) { - return self.effects(layer, &[], base, true); - } - let content = self.content(layer)?; - let mut p = Pass::new(Kernel::Atop, 0); - p.a = Some(base); - p.b = Some(content); - p.mode = layer.blend; - p.opacity = opacity; - p.flags = gamma_flag(layer); - p.extra[3] = photocraft_compose::text_gamma(layer); - Ok(self.emit(p)) - } - - /// adjust::apply_with on a slot (consumes it). - fn adjust(&mut self, adj: &Adjustment, src: Slot) -> Result { - if !adjustment_on_gpu(adj, self.cx.mode) { - return Err(Unsupported(format!("{} on CMYK/Lab channels (evaluated on the CPU)", adj.label()))); - } - if let Adjustment::GradientMap { stops, .. } = adj { - check_gradient_stops(stops)?; - } - let mut p = Pass::new(Kernel::Adjust, 0); - p.a = Some(src); - let (kind, params, lut) = adjustment_program(adj, self.cx.transfer, self.cx.depth, self.cx.mode); - p.adjust_kind = kind; - p.params = params; - p.lut = lut; - Ok(self.emit(p)) - } - - /// `composite_with_effects` (atop = false) or the clipped-layer variant of `composite_atop` - /// (atop = true: effects over the base treated as opaque, keeping the base's alpha). - /// Consumes `backdrop`. - fn effects(&mut self, layer: &'a Layer, clipped: &[&'a Layer], backdrop: Slot, atop: bool) -> Result { - let canvas = self.cx.canvas; - let region = bounds::effect_region(layer, canvas); - let sb = photocraft_compose::paint_bounds(layer).unwrap_or_else(|| bounds::layer_bounds(layer, canvas)); - let clip = if bounds::transparent_outside(layer) { region } else { canvas }; - // A stroked shape's vector stroke goes above its clipped layers and interior effects - // (compose::split_parts): the fill and the stroke unmasked, the masks applied after. - let split = match &layer.content { - LayerContent::Shape(sh) if sh.stroke.is_some() => photocraft_compose::shape_split::split(sh, canvas, self.cx.depth), - _ => None, - }; - let (mut content, vstroke) = match split { - Some((fill, stroke)) => { - let f = self.shape_part(layer, Role::Content, fill); - let s = self.shape_part(layer, Role::Stroke, stroke); - (f, Some(s)) - } - None => (self.content(layer)?, None), - }; - for p in self.passes.iter_mut().rev().take(if vstroke.is_some() { 2 } else { 1 }) { - if !matches!(layer.content, LayerContent::Group(_)) { - p.clip = Some(clip); - } - } - for c in clipped { - content = self.atop(c, content)?; - } - let fx = self.fx.len(); - self.fx.push(FxLayer { layer, region, bounds: sb }); - let outline = photocraft_compose::effect_outline(layer).is_some(); - let relative = outline || vstroke.is_some(); - // `content` becomes the effect shape (B of every effect pass); `lay_src` the layer's colour. - let (lay_src, vstroke) = match vstroke { - Some(s) => { - let mut p = Pass::new(Kernel::Blend, 0); - p.a = Some(self.retain(content)); - p.b = Some(self.retain(s)); - p.clip = Some(clip); - let union = self.emit(p); - let m = self.mask_use(layer); - let masked = |me: &mut Self, slot: Slot| match &m { - Some(m) => { - let mut p = Pass::new(Kernel::Mask, 0); - p.a = Some(slot); - p.mask = Some(m.clone()); - p.clip = Some(clip); - me.emit(p) - } - None => slot, - }; - let fill = masked(self, content); - content = masked(self, union); - (fill, Some(masked(self, s))) - } - None => (self.retain(content), None), - }; - if outline { - let mut p = Pass::new(Kernel::FxInit, 0); - p.a = Some(content); - p.adjust_kind = INIT_OUTLINE; - p.map = Some(MapRef { fx, item: SHAPE_MAP, map: 0 }); - p.clip = Some(clip); - content = self.emit(p); - } - - let items: Vec<&'a Effect> = layer.effects.items.iter().filter(|e| e.enabled()).collect(); - for e in &items { - let gradient = match e { - Effect::GradientOverlay { gradient, .. } => Some(gradient), - Effect::Stroke(s) => match &s.paint { - FxPaint::Gradient(g) => Some(g), - _ => None, - }, - Effect::OuterGlow(g) | Effect::InnerGlow(g) => match &g.paint { - FxPaint::Gradient(g) => Some(g), - _ => None, - }, - _ => None, - }; - if let Some(g) = gradient { - check_gradient_stops(&g.stops)?; - check_gradient_stops(&g.opacity_stops)?; - } - } - // Linked patterns tile from the effects reference point (else the layer's top-left). - let anchor = layer.effects.reference.unwrap_or((f64::from(sb.x0), f64::from(sb.y0))); - let vector_shape = matches!(layer.content, LayerContent::Shape(_)) && !outline; - let map = |item: usize, map: usize| MapRef { fx, item, map }; - let rev: Vec<(usize, &'a Effect)> = items.iter().copied().enumerate().rev().collect(); - let init = |s: &mut Self, src: Slot, b: Option, kind: i32, opacity: f32| { - let mut p = Pass::new(Kernel::FxInit, 0); - p.a = Some(src); - p.b = b; - p.adjust_kind = kind; - p.opacity = opacity; - p.clip = Some(clip); - s.emit(p) - }; - - // Exterior effects over the backdrop (an opaque copy of it for clipped layers). - let mut w = if atop { - let b = self.retain(backdrop); - init(self, b, None, INIT_OPAQUE, 1.0) - } else { - self.retain(backdrop) - }; - for &(i, e) in &rev { - if let Effect::DropShadow(s) = e { - // The layer hides the shadow beneath it where its fill is see-through, and wholly - // in a mode that blends with it (as the CPU renderer: `shadow_see_through`). - let flags = if s.knocks_out { F_KNOCKOUT } else { 0 }; - let see_through = photocraft_compose::effects::shadow_see_through(layer); - w = self.paint_k( - w, - content, - Cov::Map(map(i, 0), 0.0), - &Paint::Color(s.color.to_rgb()), - s.common.blend, - s.common.opacity, - flags, - clip, - sb, - see_through, - ); - } - } - for &(i, e) in &rev { - if let Effect::OuterGlow(g) = e { - let paint = self.glow_paint(g, anchor); - // Match CPU exterior knockout: a see-through fill must not reveal the - // glow through its own shape. The shader applies m × (1 − alpha × k). - let see_through = 1.0 - layer.fill_opacity.clamp(0.0, 1.0); - w = self.paint_k(w, content, Cov::Map(map(i, 0), 0.0), &paint, g.common.blend, g.common.opacity, F_KNOCKOUT, clip, sb, see_through); - } - } - - // Only exterior effects (drop shadows, outer glows): nothing is painted between the - // layer's colour inside its shape and the shape's alpha, so the merge derives both from - // the shape (`F_LAYER_SHAPE`) instead of two passes building the layer. - let premerge = photocraft_compose::effects::premerges_layer(layer); - if !relative && !premerge && items.iter().all(|e| matches!(e, Effect::DropShadow(_) | Effect::OuterGlow(_))) { - let mut p = Pass::new(Kernel::FxMerge, 0); - p.a = Some(w); - p.b = Some(lay_src); - p.c = Some(self.retain(backdrop)); - p.mode = if layer.blend == BlendMode::PassThrough { BlendMode::Normal } else { layer.blend }; - p.opacity = layer.opacity; - p.flags = if atop { F_ATOP } else { 0 } | gamma_flag(layer) | F_LAYER_SHAPE; - p.params[0][0] = layer.fill_opacity; - p.extra[3] = photocraft_compose::text_gamma(layer); - p.clip = Some(clip); - let merged = self.emit(p); - self.release(content); - return Ok(self.write_back(backdrop, merged, clip)); - } - // The layer: its colour at fill opacity inside its shape; interior effects are painted - // relative to the shape (coverage within it), then the shape's alpha applies. - let mut l = if relative { - let c = self.retain(content); - init(self, lay_src, Some(c), INIT_RELATIVE, layer.fill_opacity) - } else { - init(self, lay_src, None, INIT_INSIDE, layer.fill_opacity) - }; - // Blend Interior Effects as Group off: the layer merges in its mode first and the - // interior effects paint over the result (`effects::premerges_layer`). - if premerge { - let mut p = Pass::new(Kernel::Blend, 0); - p.a = Some(self.retain(w)); - p.b = Some(l); - p.mode = layer.blend; - p.flags = gamma_flag(layer); - p.extra[3] = photocraft_compose::text_gamma(layer); - p.clip = Some(clip); - l = self.emit(p); - } - for &(_, e) in &rev { - if let Effect::PatternOverlay { common, name, id, scale, angle, link, phase } = e - && let Some(pat) = photocraft_doc::pattern::find(self.cx.patterns, id, name).filter(|p| p.is_paintable()) - { - let paint = Paint::Pattern(pat, placement(anchor, *link, *phase, *scale, *angle)); - l = self.paint(l, content, Cov::One, &paint, common.blend, common.opacity, F_GATE, clip, sb); - } - } - for &(_, e) in &rev { - if let Effect::GradientOverlay { common, gradient, .. } = e { - l = self.paint(l, content, Cov::One, &Paint::Gradient(gradient), common.blend, common.opacity, F_GATE, clip, sb); - } - } - for &(_, e) in &rev { - if let Effect::ColorOverlay { common, color } = e { - l = self.paint(l, content, Cov::One, &Paint::Color(color.to_rgb()), common.blend, common.opacity, F_GATE, clip, sb); - } - } - for &(i, e) in &rev { - if let Effect::Satin(s) = e { - l = self.paint(l, content, Cov::Map(map(i, 0), 0.0), &Paint::Color(s.color.to_rgb()), s.common.blend, s.common.opacity, F_REL, clip, sb); - } - } - for &(i, e) in &rev { - if let Effect::InnerGlow(g) = e { - let paint = self.glow_paint(g, anchor); - l = self.paint(l, content, Cov::Map(map(i, 0), 0.0), &paint, g.common.blend, g.common.opacity, F_REL, clip, sb); - } - } - for &(i, e) in &rev { - if let Effect::InnerShadow(s) = e { - l = self.paint(l, content, Cov::Map(map(i, 0), 0.0), &Paint::Color(s.color.to_rgb()), s.common.blend, s.common.opacity, F_REL, clip, sb); - } - } - if let Some(s) = vstroke { - let mut p = Pass::new(Kernel::FxInit, 0); - p.a = Some(l); - p.b = Some(self.retain(content)); - p.c = Some(s); - p.adjust_kind = INIT_VSTROKE; - p.opacity = layer.fill_opacity; - p.clip = Some(clip); - l = self.emit(p); - } - // Inside stroke parts are painted over the layer (bottom instance first). - for &(i, e) in &rev { - if let Effect::Stroke(st) = e { - let (in_w, _) = stroke_widths(st); - if in_w > 0.0 { - let paint = self.fx_paint(&st.paint, anchor); - l = self.paint( - l, - content, - Cov::Map(map(i, 1), (in_w + 0.5).clamp(0.0, 1.0)), - &paint, - st.common.blend, - st.common.opacity, - F_GATE, - clip, - photocraft_compose::stroke_frame(self.cx.doc, layer, st).unwrap_or(sb), - ); - } - } - } - let bevel_paint = |b: &photocraft_doc::Bevel| photocraft_compose::effects::bevel_geom(b).paint; - for &(i, e) in &rev { - if let Effect::BevelEmboss(b) = e - && bevel_paint(b) == photocraft_compose::effects::BevelPaint::Inner - { - l = self.paint( - l, - content, - Cov::Map(map(i, 0), 0.0), - &Paint::Color(b.highlight_color.to_rgb()), - b.highlight.blend, - b.highlight.opacity, - F_REL, - clip, - sb, - ); - l = self.paint(l, content, Cov::Map(map(i, 1), 0.0), &Paint::Color(b.shadow_color.to_rgb()), b.shadow.blend, b.shadow.opacity, F_REL, clip, sb); - } - } - // The shape's own alpha. - let c = self.retain(content); - l = init(self, l, Some(c), INIT_ALPHA, 1.0); - // Outside stroke parts lie beneath the layer and blend onto the exterior result with their - // own mode; a higher stroke covers the ones below it (each takes its coverage × opacity - // not yet taken above it, blended over the result as it was before the strokes). - let outs: Vec<(usize, &photocraft_doc::StrokeFx)> = items - .iter() - .copied() - .enumerate() - .filter_map(|(i, e)| if let Effect::Stroke(st) = e { Some((i, st)) } else { None }) - .filter(|(_, st)| stroke_widths(st).1 > 0.0) - .collect(); - if !outs.is_empty() { - let (mut acc, mut cover): (Option, Option) = (None, None); - if outline || !vector_shape { - // The layer's alpha rides along the coverage: `effects::outline_share`, and for - // pixel layers the stroke's share beneath a partly covering layer (fill < 100 %). - let ll = self.retain(l); - cover = Some(init(self, ll, None, INIT_COVER, 1.0)); - } - for (n, &(i, st)) in outs.iter().enumerate() { - let paint = self.fx_paint(&st.paint, anchor); - let flags = F_STROKE_OUT | if vector_shape { F_VECTOR } else { 0 } | if outline { F_OUTLINE } else { 0 } | if n == 0 { F_FIRST } else { 0 }; - // Share × blended colour, then coverage (both read the coverage so far). - let mut p = self.fx_pass_kernel( - Kernel::FxStroke, - w, - content, - &paint, - st.common.blend, - st.common.opacity, - flags, - clip, - photocraft_compose::stroke_frame(self.cx.doc, layer, st).unwrap_or(sb), - ); - if matches!(paint, Paint::None) { - // A missing pattern paints nothing: the stroke's share keeps the result as is. - p.params[2][2] = 3.0; - } - p.adjust_kind = 0; - p.map = Some(map(i, 0)); - p.c = cover.map(|c| self.retain(c)); - p.d = acc; - let a = self.emit(p); - // The stroke's mode rides along only for Dissolve, whose coverage is all or - // nothing in this pass as in the colour pass (#6995). - let mut p = self.fx_pass_kernel(Kernel::FxStroke, w, content, &Paint::Color([0.0; 3]), st.common.blend, st.common.opacity, flags, clip, sb); - p.adjust_kind = 1; - p.map = Some(map(i, 0)); - p.c = cover; - cover = Some(self.emit(p)); - acc = Some(a); - } - let mut p = Pass::new(Kernel::FxStrokeEnd, 0); - p.a = Some(w); - p.b = acc; - p.c = cover; - p.clip = Some(clip); - w = self.emit(p); - } - for &(i, e) in &rev { - if let Effect::BevelEmboss(b) = e - && bevel_paint(b) == photocraft_compose::effects::BevelPaint::Outer - { - let k = 0; - w = self.paint( - w, - content, - Cov::Map(map(i, k), 0.0), - &Paint::Color(b.highlight_color.to_rgb()), - b.highlight.blend, - b.highlight.opacity, - 0, - clip, - sb, - ); - w = self.paint(w, content, Cov::Map(map(i, k + 1), 0.0), &Paint::Color(b.shadow_color.to_rgb()), b.shadow.blend, b.shadow.opacity, 0, clip, sb); - } - } - - let mode = if premerge || layer.blend == BlendMode::PassThrough { BlendMode::Normal } else { layer.blend }; - let late: Vec<(usize, &'a photocraft_doc::Bevel)> = rev - .iter() - .filter_map(|&(i, e)| if let Effect::BevelEmboss(b) = e { Some((i, b)) } else { None }) - .filter(|(_, b)| bevel_paint(b) == photocraft_compose::effects::BevelPaint::Both) - .collect(); - let merged = if late.is_empty() { - let mut p = Pass::new(Kernel::FxMerge, 0); - p.a = Some(w); - p.b = Some(l); - p.c = Some(self.retain(backdrop)); - p.mode = mode; - p.opacity = layer.opacity; - p.flags = if atop { F_ATOP } else { 0 } | gamma_flag(layer); - p.extra[3] = photocraft_compose::text_gamma(layer); - p.clip = Some(clip); - self.emit(p) - } else { - // Emboss styles shade the composited layer (`composite_with_effects`): merge at full - // opacity, paint their maps (inside and outside halves), then mix. - let mut p = Pass::new(Kernel::FxMerge, 0); - p.a = Some(w); - p.b = Some(l); - p.c = Some(self.retain(w)); - p.mode = mode; - p.opacity = 1.0; - p.flags = gamma_flag(layer); - p.extra[3] = photocraft_compose::text_gamma(layer); - p.clip = Some(clip); - let mut m = self.emit(p); - for (i, b) in late { - for (k, color, fxc) in [(0, &b.highlight_color, &b.highlight), (1, &b.shadow_color, &b.shadow)] { - m = self.paint(m, content, Cov::Map(map(i, k), 0.0), &Paint::Color(color.to_rgb()), fxc.blend, fxc.opacity, 0, clip, sb); - } - } - let mut p = Pass::new(Kernel::FxMerge, 0); - p.b = Some(self.retain(m)); - p.a = Some(m); - p.c = Some(self.retain(backdrop)); - p.mode = mode; - p.opacity = layer.opacity; - p.flags = if atop { F_ATOP } else { 0 } | F_NO_LAYER; - p.clip = Some(clip); - self.emit(p) - }; - self.release(content); - - // Write the clipped result back into the backdrop (in place when nothing else holds it). - Ok(self.write_back(backdrop, merged, clip)) - } - - fn fx_paint(&self, p: &'a FxPaint, anchor: (f64, f64)) -> Paint<'a> { - match p { - FxPaint::Color(c) => Paint::Color(c.to_rgb()), - FxPaint::Gradient(g) => Paint::Gradient(g), - FxPaint::Pattern { name, id, scale } => match photocraft_doc::pattern::find(self.cx.patterns, id, name).filter(|p| p.is_paintable()) { - Some(pat) => Paint::Pattern(pat, placement(anchor, true, (0.0, 0.0), *scale, 0.0)), - None => Paint::None, - }, - } - } - - fn glow_paint(&self, g: &'a Glow, anchor: (f64, f64)) -> Paint<'a> { - match &g.paint { - FxPaint::Gradient(gradient) => Paint::GlowGradient(gradient, photocraft_compose::effects::glow_gradient_gain(g.range)), - p => self.fx_paint(p, anchor), - } - } - - /// An effect pass reading `dst` (A, retained) and the layer `content` (B, retained) with its - /// paint set up. - #[allow(clippy::too_many_arguments)] - fn fx_pass(&mut self, dst: Slot, content: Slot, paint: &Paint<'a>, blend: BlendMode, opacity: f32, flags: u32, clip: Rect, sb: Rect) -> Pass<'a> { - self.fx_pass_kernel(Kernel::FxPaint, dst, content, paint, blend, opacity, flags, clip, sb) - } - - #[allow(clippy::too_many_arguments)] - fn fx_pass_kernel( - &mut self, - kernel: Kernel, - dst: Slot, - content: Slot, - paint: &Paint<'a>, - blend: BlendMode, - opacity: f32, - flags: u32, - clip: Rect, - sb: Rect, - ) -> Pass<'a> { - let mut p = Pass::new(kernel, 0); - p.a = Some(self.retain(dst)); - p.b = Some(self.retain(content)); - p.mode = blend; - p.opacity = opacity; - p.flags = flags; - p.clip = Some(clip); - match paint { - Paint::None => {} - Paint::Color(c) => p.color = [c[0], c[1], c[2], 1.0], - Paint::Gradient(g) => { - // effects::paint_fx: whole-pixel end points (fill_layout::gradient_layout). - let (angle, scale, offset) = photocraft_compose::fill_layout::gradient_layout(g.style, g.angle, g.scale, g.offset, sb); - p.params[0] = [angle, scale, if g.reverse { 1.0 } else { 0.0 }, style_index(g.style)]; - p.params[1] = [sb.x0 as f32, sb.y0 as f32, sb.width() as f32, sb.height() as f32]; - p.params[2][0] = offset.0; - p.params[2][1] = offset.1; - p.params[2][2] = 1.0; - p.lut = Some(gradient_rows(g)); - } - Paint::GlowGradient(g, gain) => { - // effects::paint_glow: the gradient at 1 - strength, opaque from 1 / gain. - p.params[0][0] = *gain; - p.params[2][2] = 4.0; - p.lut = Some(gradient_rows(g)); - } - Paint::Pattern(pat, pl) => { - p.params[2][2] = 2.0; - p.params[3] = [pl.origin.0 as f32, pl.origin.1 as f32, pl.cs.0 as f32, pl.cs.1 as f32]; - p.extra = [pl.inv_scale as f32, pat.width as f32, pat.height as f32, 0.0]; - p.pattern = Some(pat); - } - } - p - } - - /// One effect paint into `dst` (consumed); reads the layer's alpha from `content` (kept). - #[allow(clippy::too_many_arguments)] - fn paint(&mut self, dst: Slot, content: Slot, cov: Cov, paint: &Paint<'a>, blend: BlendMode, opacity: f32, flags: u32, clip: Rect, sb: Rect) -> Slot { - self.paint_k(dst, content, cov, paint, blend, opacity, flags, clip, sb, 1.0) - } - - /// [`Self::paint`] with the knockout strength (`F_KNOCKOUT`: coverage × (1 − alpha × k)). - #[allow(clippy::too_many_arguments)] - fn paint_k( - &mut self, - dst: Slot, - content: Slot, - cov: Cov, - paint: &Paint<'a>, - blend: BlendMode, - opacity: f32, - flags: u32, - clip: Rect, - sb: Rect, - knockout: f32, - ) -> Slot { - if matches!(paint, Paint::None) { - // Missing pattern: compose paints nothing. - return dst; - } - let mut p = self.fx_pass(dst, content, paint, blend, opacity, flags, clip, sb); - self.release(dst); - match cov { - Cov::Map(m, outside) => { - p.adjust_kind = 0; - p.map = Some(m); - p.params[2][3] = outside; - } - Cov::One => p.adjust_kind = 1, - } - p.extra[3] = knockout; - self.emit(p) - } -} - -/// Paint source of an effect. -enum Paint<'a> { - None, - Color([f32; 3]), - Gradient(&'a Gradient), - /// A glow's gradient with its opacity gain (`effects::paint_glow`). - GlowGradient(&'a Gradient, f32), - Pattern(&'a Pattern, Placement), -} - -/// `compose::pattern::Placement` (origin, inverse rotation, inverse scale). -#[derive(Clone, Copy, Debug)] -struct Placement { - origin: (f64, f64), - cs: (f64, f64), - inv_scale: f64, -} - -/// `Placement::anchored`: linked patterns tile from `anchor` (the effects reference point). -fn placement(anchor: (f64, f64), link: bool, phase: (f32, f32), scale: f32, angle: f32) -> Placement { - let base = if link { anchor } else { (0.0, 0.0) }; - let origin = (base.0 + f64::from(phase.0), base.1 + f64::from(phase.1)); - let s = f64::from(scale); - let inv_scale = if s.is_finite() && s > 1e-3 { 1.0 / s } else { 1.0 }; - let a = f64::from(angle).to_radians(); - Placement { origin, cs: (a.cos(), a.sin()), inv_scale } -} - -/// (inside width, outside width) of a stroke. -pub fn stroke_widths(st: &photocraft_doc::StrokeFx) -> (f32, f32) { - match st.position { - StrokePosition::Outside => (0.0, st.size), - StrokePosition::Inside => (st.size, 0.0), - StrokePosition::Center => (st.size / 2.0, st.size / 2.0), - } -} - -fn style_index(s: photocraft_doc::GradientStyle) -> f32 { - match s { - photocraft_doc::GradientStyle::Linear => 0.0, - photocraft_doc::GradientStyle::Radial => 1.0, - photocraft_doc::GradientStyle::Angle => 2.0, - photocraft_doc::GradientStyle::Reflected => 3.0, - photocraft_doc::GradientStyle::Diamond => 4.0, - } -} - -fn sample_stops4(stops: &[(f32, [f32; 4])], t: f32) -> [f32; 4] { - match stops { - [] => [0.0; 4], - [only] => only.1, - _ => { - if t <= stops[0].0 { - return stops[0].1; - } - for w in stops.windows(2) { - let (a, b) = (&w[0], &w[1]); - if t <= b.0 { - let k = if b.0 > a.0 { (t - a.0) / (b.0 - a.0) } else { 0.0 }; - return std::array::from_fn(|i| a.1[i] + (b.1[i] - a.1[i]) * k); - } - } - stops[stops.len() - 1].1 - } - } -} - -fn lut_rows(f: impl Fn(usize, f32) -> f32, rows: usize) -> Vec<[f32; 4096]> { - (0..rows) - .map(|r| { - let mut row = [0.0f32; 4096]; - for (k, v) in row.iter_mut().enumerate() { - *v = f(r, k as f32 / 4095.0); - } - row - }) - .collect() -} - -type Program = (i32, [[f32; 4]; 4], Option>); - -/// A CPU LUT (4096 entries) as one texture row. -fn to_row(t: &[f32]) -> [f32; 4096] { - let mut row = [0.0f32; 4096]; - for (o, v) in row.iter_mut().zip(t) { - *o = *v; - } - row -} - -/// Whether the adjustment kernel can evaluate `adj` in a document of colour `mode`: Levels and -/// Curves on CMYK ink or Lab channels convert through ICC profiles per pixel, and so do the -/// adjustments a Lab document evaluates on L, a and b (`photocraft_compose::adjust::lab_channel_adjustment`) -/// and a CMYK document on its inks (`cmyk_channel_adjustment`), which only the CPU does. -pub fn adjustment_on_gpu(adj: &Adjustment, mode: photocraft_color::ColorMode) -> bool { - use photocraft_compose::adjust::{cmyk_channel_adjustment, lab_channel_adjustment}; - let tone_in_space = - matches!(adj, Adjustment::Levels { space: ToneSpace::Cmyk | ToneSpace::Lab, .. } | Adjustment::Curves { space: ToneSpace::Cmyk | ToneSpace::Lab, .. }); - let own_channels = match mode { - photocraft_color::ColorMode::Lab => lab_channel_adjustment(adj), - photocraft_color::ColorMode::Cmyk => cmyk_channel_adjustment(adj), - _ => false, - }; - !tone_in_space && !own_channels -} - -/// A tone transfer as the shader's `t_decode`/`t_encode` exponent (0: the sRGB curve). -fn transfer_exponent(t: Transfer) -> f32 { - match t { - Transfer::Srgb => 0.0, - Transfer::Gamma(g) => g, - } -} - -/// Adjustment → (kernel kind, parameters, LUT rows). Kinds are the `switch` in `adjust()`. -pub fn adjustment_program(adj: &Adjustment, transfer: Transfer, depth: photocraft_color::SampleType, mode: photocraft_color::ColorMode) -> Program { - let mut p = [[0.0f32; 4]; 4]; - match adj { - Adjustment::Invert => (1, p, None), - Adjustment::Threshold { level } => { - // The level, the depth's split (compose::adjust::threshold_white) and the level in 16 bits. - let t = (level * 255.0).round(); - p[0] = match depth { - photocraft_color::SampleType::U8 => [t, 1.0, 0.0, 0.0], - photocraft_color::SampleType::U16 => [t, 2.0, (t * 32768.0 / 255.0).round(), 0.0], - photocraft_color::SampleType::F32 => [t, 0.0, 0.0, 0.0], - }; - (2, p, None) - } - Adjustment::Posterize { levels } => { - // The levels, and the 16-bit rule (compose::adjust::posterize_in). - p[0][0] = (*levels).clamp(2, 255) as f32; - p[0][1] = if depth == photocraft_color::SampleType::U16 { 1.0 } else { 0.0 }; - (3, p, None) - } - Adjustment::BrightnessContrast { brightness, contrast, legacy: true } => { - let c = contrast.clamp(-100.0, 99.0); - let k = if c >= 0.0 { 1.0 / (1.0 - c / 100.0) } else { 1.0 + c / 100.0 }; - // Brightness before contrast when it is raised, after it when lowered (compose::adjust). - let (pre, post) = if c >= 0.0 { (brightness / 255.0, 0.0) } else { (0.0, brightness / 255.0) }; - // 32-bit documents pivot at 127 of 255 and don't clip (the shader checks F_HDR). - let pivot = if depth == photocraft_color::SampleType::F32 { 127.0 / 255.0 } else { photocraft_compose::adjust::LEGACY_PIVOT }; - p[0] = [pre, k, pivot, post]; - (4, p, None) - } - Adjustment::BrightnessContrast { brightness, contrast, .. } => { - // Modern B/C: the CPU's lookup table (compose::adjust::modern_lut) on every channel, - // through the Levels / Curves kernel. - let row = to_row(&adjust::modern_lut(*brightness, *contrast)); - (7, p, Some(vec![row; 3])) - } - Adjustment::Exposure { exposure, offset, gamma } => { - p[0] = [2f32.powf(*exposure), *offset, gamma.max(0.01), transfer_exponent(transfer.for_exposure())]; - (6, p, None) - } - Adjustment::Levels { master, per_channel, space: ToneSpace::Rgb, .. } if depth == photocraft_color::SampleType::F32 => { - // Twenty coefficients exceed the sixteen uniform parameters. Store four records - // in LUT row 0, read texel-exact by the analytic float Levels kernel. - let mut row = [0.0f32; 4096]; - for (i, ch) in std::iter::once(master).chain(per_channel).enumerate() { - let coefficients = [ch.in_black, ch.in_white, ch.gamma.max(0.01), ch.out_black, ch.out_white]; - row[i * 5..i * 5 + 5].copy_from_slice(&coefficients); - } - (17, p, Some(vec![row])) - } - // RGB space only (see `adjustment_on_gpu`); the rows are the CPU's channel∘master LUTs. - Adjustment::Levels { .. } | Adjustment::Curves { .. } => { - for (v, identity) in p[0].iter_mut().zip(adjust::float_tone_identity(adj, Some(depth))) { - *v = if identity { 1.0 } else { 0.0 }; - } - // p0.w: continue the curve past 0..1 (32-bit RGB Curves, #7157). - p[0][3] = if adjust::float_tone_extrapolates(adj, Some(depth), mode) { 1.0 } else { 0.0 }; - (7, p, Some(adjust::tone_luts_depth(adj, Some(depth)).iter().take(3).map(|t| to_row(t)).collect())) - } - Adjustment::HueSaturation { hue, saturation, lightness, colorize, ranges } => { - let sat = adjust::colorize_saturation(saturation / 100.0, lightness / 100.0, *colorize, Some(depth)); - p[0] = [*hue, sat, lightness / 100.0, if *colorize { 1.0 } else { 0.0 }]; - if !*colorize && ranges.iter().any(|r| !r.is_neutral()) { - // Range edits: hue-indexed rows (shift, saturation, lightness), as on the CPU. - p[1][0] = 1.0; - (8, p, Some(adjust::hue_range_tables(ranges).iter().map(|t| to_row(t)).collect())) - } else { - (8, p, None) - } - } - Adjustment::Vibrance { vibrance, saturation } => { - // compose::adjust::vibrance_px; 32-bit samples aren't clipped at 1. - let hi = if depth == photocraft_color::SampleType::F32 { f32::MAX } else { 1.0 }; - p[0] = [vibrance / 100.0, saturation / 100.0, transfer_exponent(transfer), hi]; - let b = adjust::VIBRANCE_BOOST; - p[1] = [b[0], b[1], b[2], b[3]]; - p[2] = [b[4], b[5], b[6], 0.0]; - (9, p, None) - } - Adjustment::ChannelMixer { matrix, monochrome } => { - // compose::adjust: 32-bit documents cut each percentage to 1/1024, count 255/512 of - // the constant and don't clip (the shader checks F_HDR). - let hdr = depth == photocraft_color::SampleType::F32; - let cut = |v: f32| if hdr { (v * 1024.0).trunc() / 1024.0 } else { v }; - let rows = matrix.map(|r| [cut(r[0]), cut(r[1]), cut(r[2]), if hdr { r[3] * 255.0 / 512.0 } else { r[3] }]); - p[0] = rows[0]; - p[1] = rows[1]; - p[2] = rows[2]; - p[3][0] = if *monochrome { 1.0 } else { 0.0 }; - (10, p, None) - } - Adjustment::PhotoFilter { color, density, preserve_luminosity } => { - // compose::adjust: the linear-light matrix, then SetLum on the encoded values (8/16-bit). - let linear_doc = depth == photocraft_color::SampleType::F32; - let m = adjust::photo_filter_matrix(*color, *density, *preserve_luminosity && linear_doc); - for (row, m) in p.iter_mut().zip(m) { - *row = [m[0], m[1], m[2], 0.0]; - } - p[3] = [if *preserve_luminosity && !linear_doc { 1.0 } else { 0.0 }, transfer_exponent(transfer), 0.0, 0.0]; - (11, p, None) - } - Adjustment::BlackWhite { weights, tint } => { - p[0] = [weights[0], weights[1], weights[2], weights[3]]; - p[1] = [weights[4], weights[5], if tint.is_some() { 1.0 } else { 0.0 }, 0.0]; - if let Some(t) = tint { - p[2] = [t[0], t[1], t[2], 0.0]; - } - (12, p, None) - } - Adjustment::GradientMap { stops, reverse, dither } => { - p[0][0] = if *reverse { 1.0 } else { 0.0 }; - p[0][1] = if *dither { 1.0 } else { 0.0 }; - let s4: Vec<(f32, [f32; 4])> = stops.iter().map(|(t, c)| (*t, [c[0], c[1], c[2], 1.0])).collect(); - let rows = lut_rows(|r, t| if s4.is_empty() { t } else { sample_stops4(&s4, t)[r] }, 3); - (13, p, Some(rows)) - } - Adjustment::ColorBalance { shadows, midtones, highlights, preserve_luminosity } => { - // Per-channel curves (compose::adjust::BalanceCurve), through the Levels kernel. - let curves = adjust::BalanceCurve::rgb([*shadows, *midtones, *highlights], *preserve_luminosity); - (7, p, Some(lut_rows(|ch, v| curves[ch].eval(v), 3))) - } - Adjustment::SelectiveColor { relative, adjustments } => { - // 9 ranges × CMYK don't fit the 16 params: they go in LUT row 0 (read texel-exact). - p[0][0] = if *relative { 1.0 } else { 0.0 }; - let mut row = [0.0f32; 4096]; - for (i, v) in adjustments.iter().flatten().enumerate() { - row[i] = *v; - } - (15, p, Some(vec![row])) - } - Adjustment::ColorLookup { lut: Some(table), size, tetrahedral, dither, .. } if lut3d_len(*size).is_some_and(|len| table.len() >= len) => { - // The flattened table (n³ RGB triplets) spans as many 4096-wide rows as it needs. - let n = *size as usize; - let rows = lut3d_len(*size) - .and_then(|len| table.get(..len)) - .unwrap_or_default() - .chunks(4096) - .map(|c| { - let mut row = [0.0f32; 4096]; - row[..c.len()].copy_from_slice(c); - row - }) - .collect(); - p[0] = [n as f32, if *tetrahedral { 1.0 } else { 0.0 }, if *dither { 1.0 } else { 0.0 }, 0.0]; - (16, p, Some(rows)) - } - // Identity on the CPU too (not evaluated there). - Adjustment::ColorLookup { .. } | Adjustment::Unsupported { .. } => (0, p, None), - } -} - -/// A gradient's colour and alpha as four 4096-entry LUT rows (`lut_tex`). -fn gradient_rows(g: &Gradient) -> Vec<[f32; 4096]> { - let mut rows = vec![[0.0f32; 4096]; 4]; - for k in 0..4096 { - let v = photocraft_compose::effects::sample_gradient(g, k as f32 / 4095.0); - for (ch, row) in rows.iter_mut().enumerate() { - row[k] = v[ch]; - } - } - rows -} - -/// Linear interpolation between LUT entries cannot preserve a discontinuity. Let the canvas -/// use the CPU oracle for coincident stops, including opacity stops and unsorted fill ramps -/// (which `gradient_fill::Ramp` sorts). Check only ramps we will sample: cached fills and -/// disabled effects can still use the GPU. -fn check_gradient_stops(stops: &[(f32, T)]) -> Result<(), Unsupported> { - let mut positions: Vec = stops.iter().map(|s| s.0).collect(); - positions.sort_by(f32::total_cmp); - // A 4096-entry LUT cannot keep two stops that fall in the same entry apart (#3053). - if positions.windows(2).any(|w| (w[1] - w[0]).abs() < 1.0 / 4095.0) { - return Err(Unsupported("coincident gradient stops (composited on the CPU)".into())); - } - Ok(()) -} - -/// Mode index used by the shader (declaration order of [`BlendMode`]). -pub fn mode_index(m: BlendMode) -> i32 { - match m { - BlendMode::PassThrough => 0, - BlendMode::Normal => 1, - BlendMode::Dissolve => 2, - BlendMode::Darken => 3, - BlendMode::Multiply => 4, - BlendMode::ColorBurn => 5, - BlendMode::LinearBurn => 6, - BlendMode::DarkerColor => 7, - BlendMode::Lighten => 8, - BlendMode::Screen => 9, - BlendMode::ColorDodge => 10, - BlendMode::LinearDodge => 11, - BlendMode::LighterColor => 12, - BlendMode::Overlay => 13, - BlendMode::SoftLight => 14, - BlendMode::HardLight => 15, - BlendMode::VividLight => 16, - BlendMode::LinearLight => 17, - BlendMode::PinLight => 18, - BlendMode::HardMix => 19, - BlendMode::Difference => 20, - BlendMode::Exclusion => 21, - BlendMode::Subtract => 22, - BlendMode::Divide => 23, - BlendMode::Hue => 24, - BlendMode::Saturation => 25, - BlendMode::Color => 26, - BlendMode::Luminosity => 27, - BlendMode::Reflect => 28, - BlendMode::Glow => 29, - BlendMode::Negation => 30, - BlendMode::Xor => 31, - BlendMode::PaintNetColorBurn => 32, - BlendMode::PaintNetColorDodge => 33, - } -} - -/// Whether `Planner::content` draws `layer` as one `Planner::content_pass`: not a group's stack, -/// an adjustment, or a pattern fill painted in passes. -fn single_content_pass(layer: &Layer) -> bool { - match &layer.content { - LayerContent::Group(_) | LayerContent::Adjustment(_) => false, - LayerContent::Fill(f @ Fill::Pattern { .. }) => layer.fill_cache.as_ref().is_some_and(|c| c.fill == *f), - _ => true, - } -} - #[cfg(test)] -mod tests { - use super::*; - use photocraft_color::{Color, ColorMode, SampleType}; - use photocraft_geom::Size; - - #[test] - fn nested_pass_through_groups_with_clipped_layers_are_not_planned_exponentially() { - let mut layers = vec![Layer::raster("leaf", photocraft_color::PixelFormat::RGBA8)]; - for _ in 0..30 { - let group = Layer::group("g", layers); - let mut clipped = Layer::raster("c", photocraft_color::PixelFormat::RGBA8); - clipped.clipped = true; - layers = vec![group, clipped]; - } - let mut doc = Document::new("nest", Size::new(8, 8), ColorMode::Rgb, SampleType::U8); - doc.layers = layers; - let started = std::time::Instant::now(); - let Err(error) = plan(&doc) else { panic!("2^30 plannings must be refused") }; - assert!(error.0.contains("too many nested layers"), "{}", error.0); - assert!(started.elapsed().as_secs() < 10, "{:?}", started.elapsed()); - } - - #[test] - fn stops_closer_than_one_lut_step_stay_on_the_cpu() { - assert!(check_gradient_stops(&[(0.4999_f32, ()), (0.5, ())]).is_err()); - assert!(check_gradient_stops(&[(0.0_f32, ()), (1.0, ())]).is_ok()); - } - - #[test] - fn lab_channel_adjustments_defer_to_the_cpu_in_lab_documents() { - let lab_rules = [ - Adjustment::Invert, - Adjustment::Posterize { levels: 4 }, - Adjustment::Threshold { level: 0.5 }, - Adjustment::BrightnessContrast { brightness: 10.0, contrast: 5.0, legacy: false }, - Adjustment::GradientMap { stops: vec![(0.0, [0.0; 3]), (1.0, [1.0; 3])], reverse: false, dither: false }, - ]; - for adj in &lab_rules { - assert!(!adjustment_on_gpu(adj, ColorMode::Lab), "{adj:?}"); - for mode in [ColorMode::Rgb, ColorMode::Grayscale] { - assert!(adjustment_on_gpu(adj, mode), "{adj:?} in {mode:?}"); - } - // CMYK documents invert, posterize, threshold and brighten their inks, on the CPU. - let inks = !matches!(adj, Adjustment::GradientMap { .. }); - assert_eq!(adjustment_on_gpu(adj, ColorMode::Cmyk), !inks, "{adj:?} in CMYK"); - } - // CMYK Hue/Saturation works on the inks (on the CPU); Colorize stays on the screen colour. - let ranges = photocraft_doc::adjust::HueRange::defaults(); - let hue = |colorize| Adjustment::HueSaturation { hue: 30.0, saturation: 10.0, lightness: 0.0, colorize, ranges: ranges.clone() }; - assert!(!adjustment_on_gpu(&hue(false), ColorMode::Cmyk) && adjustment_on_gpu(&hue(true), ColorMode::Cmyk)); - assert!(adjustment_on_gpu(&hue(false), ColorMode::Rgb)); - // Screen-colour adjustments stay on the GPU in Lab documents. - assert!(adjustment_on_gpu(&Adjustment::Exposure { exposure: 1.0, offset: 0.0, gamma: 1.0 }, ColorMode::Lab)); - } - - #[test] - fn native_cmyk_fills_fall_back_only_without_a_valid_cache() { - use photocraft_doc::{FillCache, GradientStyle}; - for depth in photocraft_color::SampleType::ALL { - for fill in [Fill::Solid(Color::WHITE), Fill::gradient(vec![(0.0, Color::BLACK), (1.0, Color::WHITE)], 0.0, 1.0, GradientStyle::Linear, false)] { - let mut doc = Document::new("CMYK", photocraft_geom::Size::new(3, 2), photocraft_color::ColorMode::Cmyk, depth); - doc.layers.push(Layer::new("Fill", LayerContent::Fill(fill.clone()))); - assert!(plan(&doc).unwrap_err().0.contains("native CMYK fill")); - doc.layers[0].visible = false; - assert!(plan(&doc).is_ok()); - doc.layers[0].visible = true; - doc.layers[0].fill_cache = Some(FillCache { fill, surface: photocraft_raster::Surface::new(doc.pixel_format()) }); - assert!(plan(&doc).is_ok()); - doc.layers[0].fill_cache.as_mut().unwrap().fill = Fill::Solid(Color::TRANSPARENT); - assert!(plan(&doc).is_err()); - doc.mode = photocraft_color::ColorMode::Rgb; - assert!(plan(&doc).is_ok()); - } - } - } - #[test] - fn outer_glow_plan_knocks_out_see_through_fill() { - use photocraft_doc::{Contour, FxCommon, GlowSource, GlowTechnique}; - - for fill in [0.0, 0.4, 1.0] { - let mut d = Document::with_background("glow", Size::new(64, 64), ColorMode::Rgb, SampleType::U8, Color::WHITE); - let mut layer = Layer::raster("frame", d.pixel_format()); - layer.surface_mut().unwrap().fill_rect(Rect::new(16, 16, 48, 48), &[1.0, 0.0, 0.0, 1.0]); - layer.fill_opacity = fill; - layer.effects.items.push(Effect::OuterGlow(Glow { - common: FxCommon::new(BlendMode::Normal, 1.0), - paint: FxPaint::Color(Color::rgb(1.0, 1.0, 0.0)), - technique: GlowTechnique::Softer, - spread: 0.3, - size: 8.0, - contour: Contour::Linear, - anti_alias: false, - range: 0.5, - jitter: 0.0, - noise: 0.0, - source: GlowSource::Edge, - })); - d.layers.push(layer); - let planned = plan(&d).unwrap(); - let glow = planned - .passes - .iter() - .find(|pass| { - pass.kernel == Kernel::FxPaint && pass.flags & F_KNOCKOUT != 0 && pass.color[0] > 0.9 && pass.color[1] > 0.9 && pass.color[2] < 0.1 - }) - .expect("outer glow paint pass"); - assert!((glow.extra[3] - (1.0 - fill)).abs() < 1e-6, "fill {fill}"); - } - } - - #[test] - fn color_lookup_with_an_overflowing_stored_size_uploads_no_table() { - for size in [1 << 22, u32::MAX] { - let a = Adjustment::ColorLookup { name: "x".into(), lut: Some(std::sync::Arc::new(vec![0.5; 24])), size, tetrahedral: false, dither: false }; - let (kind, _, rows) = adjustment_program(&a, Transfer::Srgb, SampleType::U8, photocraft_color::ColorMode::Rgb); - assert_eq!((kind, rows.is_none()), (0, true), "size {size}"); - } - } - - #[test] - fn root_checkpoints_have_only_one_live_input_and_keep_clips_whole() { - for mode in [BlendMode::Normal, BlendMode::PassThrough] { - let mut d = Document::with_background("t", Size::new(32, 24), ColorMode::Rgb, SampleType::U8, Color::WHITE); - let mut clip = Layer::new("clip", LayerContent::Fill(Fill::Solid(Color::rgba(0.2, 0.3, 0.7, 0.4)))); - clip.clipped = true; - let mut group = Layer::group( - "group", - vec![ - Layer::new("fill", LayerContent::Fill(Fill::Solid(Color::rgba(0.9, 0.1, 0.3, 0.6)))), - Layer::new("invert", LayerContent::Adjustment(Adjustment::Invert)), - ], - ); - group.blend = mode; - d.layers.extend([group, clip, Layer::new("top", LayerContent::Adjustment(Adjustment::Invert))]); - let plan = plan(&d).unwrap(); - assert_eq!(plan.checkpoints.iter().map(|c| c.layer_end).collect::>(), vec![1, 3, 4]); - for checkpoint in &plan.checkpoints { - let mut written = std::collections::HashSet::from([checkpoint.slot]); - for pass in &plan.passes[checkpoint.pass_end..] { - for input in [pass.a, pass.b, pass.c, pass.d].into_iter().flatten() { - assert!(written.contains(&input), "a suffix must not need another saved slot: {checkpoint:?}"); - } - written.insert(pass.dst); - } - assert!(written.contains(&plan.root)); - } - } - } - - #[test] - fn slots_are_recycled() { - let mut d = Document::with_background("t", Size::new(8, 8), ColorMode::Rgb, SampleType::U8, Color::WHITE); - for i in 0..10 { - d.layers.push(Layer::raster(format!("l{i}"), d.pixel_format())); - } - let p = plan(&d).unwrap(); - // Empty layers draw nothing: the clear and the background's one fused pass. - assert_eq!(p.passes.len(), 1 + 1); - for (i, l) in d.layers.iter_mut().skip(1).enumerate() { - l.surface_mut().unwrap().fill_rect(Rect::new(i as i32 % 4, 0, 4, 8), &[0.0, 0.0, 1.0, 1.0]); - } - let p = plan(&d).unwrap(); - assert!(p.slots <= 3, "{} slots", p.slots); - // The background, then each small layer blended over its bounds and copied back. - assert_eq!(p.passes.len(), 1 + 1 + 10 * 2); - } - - #[test] - fn small_layers_composite_only_over_their_bounds() { - let mut d = Document::with_background("t", Size::new(64, 64), ColorMode::Rgb, SampleType::U8, Color::WHITE); - let mut l = Layer::raster("small", d.pixel_format()); - l.surface_mut().unwrap().fill_rect(Rect::new(10, 12, 20, 30), &[1.0, 0.0, 0.0, 1.0]); - let mut group = Layer::group("g", vec![l]); - group.blend = BlendMode::Normal; - d.layers.push(group); - let p = plan(&d).unwrap(); - let r = Rect::new(10, 12, 20, 30); - // The group's content, its blend and the copy back are all limited to the layer. - assert!(p.passes.iter().filter(|p| matches!(p.kernel, Kernel::Content | Kernel::Blend)).skip(2).all(|p| p.clip == Some(r)), "{:?}", p.passes); - let last = p.passes.last().unwrap(); - assert_eq!((last.kernel, last.dst, last.clip), (Kernel::CopyRect, p.root, Some(r))); - // A layer that covers most of the canvas composites everywhere. - d.layers[1].children_mut().unwrap()[0].surface_mut().unwrap().fill_rect(Rect::new(0, 0, 60, 60), &[1.0, 0.0, 0.0, 1.0]); - let p = plan(&d).unwrap(); - assert!(p.passes.iter().all(|p| p.clip.is_none())); - } - - #[test] - fn effects_are_planned_in_place() { - let mut d = Document::with_background("t", Size::new(8, 8), ColorMode::Rgb, SampleType::U8, Color::WHITE); - let mut l = Layer::raster("fx", d.pixel_format()); - l.surface_mut().unwrap().fill_rect(Rect::new(2, 2, 5, 5), &[1.0, 0.0, 0.0, 1.0]); - l.effects.items.push(photocraft_doc::Effect::ColorOverlay { common: photocraft_doc::FxCommon::new(BlendMode::Normal, 1.0), color: Color::WHITE }); - l.effects.items.push(photocraft_doc::Effect::default_drop_shadow()); - d.layers.push(l); - let p = plan(&d).unwrap(); - assert_eq!(p.fx.len(), 1); - let m = photocraft_compose::effects::margin(&d.layers[1]); - assert_eq!(p.fx[0].region, Rect::new(2, 2, 5, 5).inflate(m).intersect(&d.bounds().inflate(m))); - // The effect region covers the whole canvas: the merged result is the backdrop, no copy. - assert!(p.fx[0].region.contains_rect(&d.bounds())); - let last = p.passes.last().unwrap(); - assert_eq!(last.kernel, Kernel::FxMerge); - assert_eq!(last.dst, p.root); - assert!(p.slots <= 6, "{} slots", p.slots); - // On a larger canvas the result lands back in the backdrop slot over the region only. - let mut big = Document::with_background("t", Size::new(64, 64), ColorMode::Rgb, SampleType::U8, Color::WHITE); - big.layers.push(d.layers[1].clone()); - let p = plan(&big).unwrap(); - assert!(!p.fx[0].region.contains_rect(&big.bounds())); - let last = p.passes.last().unwrap(); - assert_eq!((last.kernel, last.dst, last.clip), (Kernel::CopyRect, p.root, Some(p.fx[0].region))); - } - - #[test] - fn exterior_effects_merge_from_the_shape() { - // A drop shadow alone: the layer's pixels, the shadow, the merge. With an interior effect - // the layer is built in passes of its own (colour inside the shape, the overlay, alpha). - let mut d = Document::with_background("t", Size::new(8, 8), ColorMode::Rgb, SampleType::U8, Color::WHITE); - let mut l = Layer::raster("fx", d.pixel_format()); - l.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 8, 8), &[1.0, 0.0, 0.0, 0.5]); - l.fill_opacity = 0.7; - l.effects.items.push(photocraft_doc::Effect::default_drop_shadow()); - d.layers.push(l); - let p = plan(&d).unwrap(); - let fx: Vec = p.passes.iter().skip(2).map(|p| p.kernel).collect(); - assert_eq!(fx, [Kernel::Content, Kernel::FxPaint, Kernel::FxMerge], "{:?}", p.passes); - let merge = p.passes.last().unwrap(); - assert!(merge.flags & F_LAYER_SHAPE != 0); - assert_eq!(merge.params[0][0], 0.7); - d.layers[1] - .effects - .items - .push(photocraft_doc::Effect::ColorOverlay { common: photocraft_doc::FxCommon::new(BlendMode::Normal, 1.0), color: Color::WHITE }); - let p = plan(&d).unwrap(); - assert!(p.passes.iter().all(|p| p.flags & F_LAYER_SHAPE == 0)); - assert!(p.passes.iter().any(|p| p.kernel == Kernel::FxInit)); - } - - #[test] - fn opaque_fill_layers_skip_what_they_cover() { - let opaque = || Fill::gradient(vec![(0.0, Color::BLACK), (1.0, Color::WHITE)], 30.0, 1.0, photocraft_doc::GradientStyle::Linear, false); - let mut d = Document::with_background("t", Size::new(8, 8), ColorMode::Rgb, SampleType::U8, Color::WHITE); - for i in 0..4 { - // Small painted layers (empty ones plan no passes at all). - let mut l = Layer::raster(format!("l{i}"), d.pixel_format()); - l.surface_mut().unwrap().fill_rect(Rect::new(i, i, i + 2, i + 2), &[0.0, 0.0, 1.0, 1.0]); - d.layers.push(l); - } - d.layers.push(Layer::new("g", LayerContent::Fill(opaque()))); - let mut top = Layer::raster("top", d.pixel_format()); - top.clipped = true; - d.layers.push(top); - // Clear, then the fill and its clipped layer: the background and four rasters are skipped. - let skipped = plan(&d).unwrap().passes.len(); - let mut alone = d.clone(); - alone.layers.drain(..5); - assert_eq!(skipped, plan(&alone).unwrap().passes.len()); - // Anything that lets the layers below show through keeps them. - let see_through: [fn(&mut Layer); 6] = [ - |l| l.opacity = 0.99, - |l| l.fill_opacity = 0.5, - |l| l.blend = BlendMode::Multiply, - |l| l.visible = false, - |l| l.excluded_channels = 1, - |l| { - if let LayerContent::Fill(Fill::Gradient { opacity_stops, .. }) = &mut l.content { - opacity_stops.push((1.0, 0.5)); - } - }, - ]; - for (k, f) in see_through.iter().enumerate() { - let mut d2 = d.clone(); - f(&mut d2.layers[5]); - assert!(plan(&d2).unwrap().passes.len() > skipped, "case {k}: the layers below are planned"); - assert!(!photocraft_compose::occludes_below(&d2.layers[5], ColorMode::Rgb), "case {k}"); - } - let mut translucent = d.clone(); - translucent.layers[5].content = LayerContent::Fill(Fill::Solid(Color::rgba(1.0, 0.0, 0.0, 0.5))); - assert!(!photocraft_compose::occludes_below(&translucent.layers[5], ColorMode::Rgb)); - assert!(photocraft_compose::occludes_below(&d.layers[5], ColorMode::Rgb)); - } - - #[test] - fn blend_if_plans_on_the_gpu() { - let mut d = Document::with_background("t", Size::new(8, 8), ColorMode::Rgb, SampleType::U8, Color::WHITE); - let mut l = Layer::raster("bi", d.pixel_format()); - l.surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(0, 0, 4, 4), &[1.0, 0.0, 0.0, 1.0]); - l.blend_if.set(0, [photocraft_doc::BlendRange { black: [40, 40], white: [255, 255] }, photocraft_doc::BlendRange::FULL]); - d.layers.push(l.clone()); - let blend_if = |d: &Document| plan(d).unwrap().passes.iter().filter(|p| p.flags & F_BLEND_IF != 0).count(); - assert_eq!(blend_if(&d), 1); - // Clipped layers too. - l.clipped = true; - d.layers[1].blend_if = Default::default(); - d.layers.push(l); - assert_eq!(blend_if(&d), 1); - // Outside RGB, Grayscale and Duotone the setting round-trips without applying. - d.mode = ColorMode::Lab; - assert_eq!(blend_if(&d), 0); - } - - #[test] - fn blend_if_params_pack_every_range_exactly() { - let mut bi = photocraft_doc::BlendIf::default(); - bi.set(3, [photocraft_doc::BlendRange { black: [255, 255], white: [0, 1] }, photocraft_doc::BlendRange { black: [12, 200], white: [201, 254] }]); - let f: Vec = blend_if_params(&bi).iter().flatten().copied().collect(); - // Entry 3 (B), this layer then underlying; unset entries are full ranges. - assert_eq!(&f[12..16], &[255.0 * 256.0 + 255.0, 1.0, 12.0 * 256.0 + 200.0, 201.0 * 256.0 + 254.0]); - assert_eq!(&f[0..2], &[0.0, 255.0 * 256.0 + 255.0]); - } - - #[test] - fn advanced_blending_falls_back_to_the_cpu() { - use photocraft_doc::Knockout; - let mut d = Document::with_background("t", Size::new(8, 8), ColorMode::Rgb, SampleType::U8, Color::WHITE); - let mut l = Layer::raster("ko", d.pixel_format()); - l.surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(0, 0, 4, 4), &[1.0, 0.0, 0.0, 1.0]); - d.layers.push(l.clone()); - assert!(plan(&d).is_ok(), "defaults stay on the GPU"); - // Switches with nothing to act on (no effects, no clipped layers) stay on the GPU too. - d.layers[1].advanced.blend_interior = true; - d.layers[1].advanced.blend_clipped = false; - assert!(plan(&d).is_ok()); - d.layers[1].advanced.knockout = Knockout::Deep; - assert!(plan(&d).unwrap_err().0.contains("Advanced Blending")); - // Inside groups and clipping groups. - d.layers[1].advanced.knockout = Knockout::None; - let mut c = l.clone(); - c.clipped = true; - d.layers.push(c.clone()); - assert!(plan(&d).is_err(), "clipped layers blended individually"); - d.layers[1].advanced.blend_clipped = true; - assert!(plan(&d).is_ok()); - d.layers[2].advanced.knockout = Knockout::Shallow; - assert!(plan(&d).is_err(), "clipped knockout"); - d.layers.truncate(1); - let mut inner = l; - inner.advanced.knockout = Knockout::Shallow; - d.layers.push(Layer::group("g", vec![inner])); - assert!(plan(&d).is_err(), "knockout inside a group"); - } -} +mod tests; diff --git a/crates/gpu/src/plan/lower.rs b/crates/gpu/src/plan/lower.rs new file mode 100644 index 0000000000..42dd17e099 --- /dev/null +++ b/crates/gpu/src/plan/lower.rs @@ -0,0 +1,344 @@ +use super::types::Unsupported; +use super::*; + +/// Paint source of an effect. +pub(super) enum Paint<'a> { + None, + Color([f32; 3]), + Gradient(&'a Gradient), + /// A glow's gradient with its opacity gain (`effects::paint_glow`). + GlowGradient(&'a Gradient, f32), + Pattern(&'a Pattern, Placement), +} + +/// `compose::pattern::Placement` (origin, inverse rotation, inverse scale). +#[derive(Clone, Copy, Debug)] +pub(super) struct Placement { + pub(super) origin: (f64, f64), + pub(super) cs: (f64, f64), + pub(super) inv_scale: f64, +} + +/// `Placement::anchored`: linked patterns tile from `anchor` (the effects reference point). +pub(super) fn placement(anchor: (f64, f64), link: bool, phase: (f32, f32), scale: f32, angle: f32) -> Placement { + let base = if link { anchor } else { (0.0, 0.0) }; + let origin = (base.0 + f64::from(phase.0), base.1 + f64::from(phase.1)); + let s = f64::from(scale); + let inv_scale = if s.is_finite() && s > 1e-3 { 1.0 / s } else { 1.0 }; + let a = f64::from(angle).to_radians(); + Placement { origin, cs: (a.cos(), a.sin()), inv_scale } +} + +/// (inside width, outside width) of a stroke. +pub fn stroke_widths(st: &photocraft_doc::StrokeFx) -> (f32, f32) { + match st.position { + StrokePosition::Outside => (0.0, st.size), + StrokePosition::Inside => (st.size, 0.0), + StrokePosition::Center => (st.size / 2.0, st.size / 2.0), + } +} + +pub(super) fn style_index(s: photocraft_doc::GradientStyle) -> f32 { + match s { + photocraft_doc::GradientStyle::Linear => 0.0, + photocraft_doc::GradientStyle::Radial => 1.0, + photocraft_doc::GradientStyle::Angle => 2.0, + photocraft_doc::GradientStyle::Reflected => 3.0, + photocraft_doc::GradientStyle::Diamond => 4.0, + } +} + +fn sample_stops4(stops: &[(f32, [f32; 4])], t: f32) -> [f32; 4] { + match stops { + [] => [0.0; 4], + [only] => only.1, + _ => { + if t <= stops[0].0 { + return stops[0].1; + } + for w in stops.windows(2) { + let (a, b) = (&w[0], &w[1]); + if t <= b.0 { + let k = if b.0 > a.0 { (t - a.0) / (b.0 - a.0) } else { 0.0 }; + return std::array::from_fn(|i| a.1[i] + (b.1[i] - a.1[i]) * k); + } + } + stops[stops.len() - 1].1 + } + } +} + +fn lut_rows(f: impl Fn(usize, f32) -> f32, rows: usize) -> Vec<[f32; 4096]> { + (0..rows) + .map(|r| { + let mut row = [0.0f32; 4096]; + for (k, v) in row.iter_mut().enumerate() { + *v = f(r, k as f32 / 4095.0); + } + row + }) + .collect() +} + +type Program = (i32, [[f32; 4]; 4], Option>); + +/// A CPU LUT (4096 entries) as one texture row. +fn to_row(t: &[f32]) -> [f32; 4096] { + let mut row = [0.0f32; 4096]; + for (o, v) in row.iter_mut().zip(t) { + *o = *v; + } + row +} + +/// Whether the adjustment kernel can evaluate `adj` in a document of colour `mode`: Levels and +/// Curves on CMYK ink or Lab channels convert through ICC profiles per pixel, and so do the +/// adjustments a Lab document evaluates on L, a and b (`photocraft_compose::adjust::lab_channel_adjustment`) +/// and a CMYK document on its inks (`cmyk_channel_adjustment`), which only the CPU does. +pub fn adjustment_on_gpu(adj: &Adjustment, mode: photocraft_color::ColorMode) -> bool { + use photocraft_compose::adjust::{cmyk_channel_adjustment, lab_channel_adjustment}; + let tone_in_space = + matches!(adj, Adjustment::Levels { space: ToneSpace::Cmyk | ToneSpace::Lab, .. } | Adjustment::Curves { space: ToneSpace::Cmyk | ToneSpace::Lab, .. }); + let own_channels = match mode { + photocraft_color::ColorMode::Lab => lab_channel_adjustment(adj), + photocraft_color::ColorMode::Cmyk => cmyk_channel_adjustment(adj), + _ => false, + }; + !tone_in_space && !own_channels +} + +/// A tone transfer as the shader's `t_decode`/`t_encode` exponent (0: the sRGB curve). +fn transfer_exponent(t: Transfer) -> f32 { + match t { + Transfer::Srgb => 0.0, + Transfer::Gamma(g) => g, + } +} + +/// Adjustment → (kernel kind, parameters, LUT rows). Kinds are the `switch` in `adjust()`. +pub fn adjustment_program(adj: &Adjustment, transfer: Transfer, depth: photocraft_color::SampleType, mode: photocraft_color::ColorMode) -> Program { + let mut p = [[0.0f32; 4]; 4]; + match adj { + Adjustment::Invert => (1, p, None), + Adjustment::Threshold { level } => { + // The level, the depth's split (compose::adjust::threshold_white) and the level in 16 bits. + let t = (level * 255.0).round(); + p[0] = match depth { + photocraft_color::SampleType::U8 => [t, 1.0, 0.0, 0.0], + photocraft_color::SampleType::U16 => [t, 2.0, (t * 32768.0 / 255.0).round(), 0.0], + photocraft_color::SampleType::F32 => [t, 0.0, 0.0, 0.0], + }; + (2, p, None) + } + Adjustment::Posterize { levels } => { + // The levels, and the 16-bit rule (compose::adjust::posterize_in). + p[0][0] = (*levels).clamp(2, 255) as f32; + p[0][1] = if depth == photocraft_color::SampleType::U16 { 1.0 } else { 0.0 }; + (3, p, None) + } + Adjustment::BrightnessContrast { brightness, contrast, legacy: true } => { + let c = contrast.clamp(-100.0, 99.0); + let k = if c >= 0.0 { 1.0 / (1.0 - c / 100.0) } else { 1.0 + c / 100.0 }; + // Brightness before contrast when it is raised, after it when lowered (compose::adjust). + let (pre, post) = if c >= 0.0 { (brightness / 255.0, 0.0) } else { (0.0, brightness / 255.0) }; + // 32-bit documents pivot at 127 of 255 and don't clip (the shader checks F_HDR). + let pivot = if depth == photocraft_color::SampleType::F32 { 127.0 / 255.0 } else { photocraft_compose::adjust::LEGACY_PIVOT }; + p[0] = [pre, k, pivot, post]; + (4, p, None) + } + Adjustment::BrightnessContrast { brightness, contrast, .. } => { + // Modern B/C: the CPU's lookup table (compose::adjust::modern_lut) on every channel, + // through the Levels / Curves kernel. + let row = to_row(&adjust::modern_lut(*brightness, *contrast)); + (7, p, Some(vec![row; 3])) + } + Adjustment::Exposure { exposure, offset, gamma } => { + p[0] = [2f32.powf(*exposure), *offset, gamma.max(0.01), transfer_exponent(transfer.for_exposure())]; + (6, p, None) + } + Adjustment::Levels { master, per_channel, space: ToneSpace::Rgb, .. } if depth == photocraft_color::SampleType::F32 => { + // Twenty coefficients exceed the sixteen uniform parameters. Store four records + // in LUT row 0, read texel-exact by the analytic float Levels kernel. + let mut row = [0.0f32; 4096]; + for (i, ch) in std::iter::once(master).chain(per_channel).enumerate() { + let coefficients = [ch.in_black, ch.in_white, ch.gamma.max(0.01), ch.out_black, ch.out_white]; + row[i * 5..i * 5 + 5].copy_from_slice(&coefficients); + } + (17, p, Some(vec![row])) + } + // RGB space only (see `adjustment_on_gpu`); the rows are the CPU's channel∘master LUTs. + Adjustment::Levels { .. } | Adjustment::Curves { .. } => { + for (v, identity) in p[0].iter_mut().zip(adjust::float_tone_identity(adj, Some(depth))) { + *v = if identity { 1.0 } else { 0.0 }; + } + // p0.w: continue the curve past 0..1 (32-bit RGB Curves, #7157). + p[0][3] = if adjust::float_tone_extrapolates(adj, Some(depth), mode) { 1.0 } else { 0.0 }; + (7, p, Some(adjust::tone_luts_depth(adj, Some(depth)).iter().take(3).map(|t| to_row(t)).collect())) + } + Adjustment::HueSaturation { hue, saturation, lightness, colorize, ranges } => { + let sat = adjust::colorize_saturation(saturation / 100.0, lightness / 100.0, *colorize, Some(depth)); + p[0] = [*hue, sat, lightness / 100.0, if *colorize { 1.0 } else { 0.0 }]; + if !*colorize && ranges.iter().any(|r| !r.is_neutral()) { + // Range edits: hue-indexed rows (shift, saturation, lightness), as on the CPU. + p[1][0] = 1.0; + (8, p, Some(adjust::hue_range_tables(ranges).iter().map(|t| to_row(t)).collect())) + } else { + (8, p, None) + } + } + Adjustment::Vibrance { vibrance, saturation } => { + // compose::adjust::vibrance_px; 32-bit samples aren't clipped at 1. + let hi = if depth == photocraft_color::SampleType::F32 { f32::MAX } else { 1.0 }; + p[0] = [vibrance / 100.0, saturation / 100.0, transfer_exponent(transfer), hi]; + let b = adjust::VIBRANCE_BOOST; + p[1] = [b[0], b[1], b[2], b[3]]; + p[2] = [b[4], b[5], b[6], 0.0]; + (9, p, None) + } + Adjustment::ChannelMixer { matrix, monochrome } => { + // compose::adjust: 32-bit documents cut each percentage to 1/1024, count 255/512 of + // the constant and don't clip (the shader checks F_HDR). + let hdr = depth == photocraft_color::SampleType::F32; + let cut = |v: f32| if hdr { (v * 1024.0).trunc() / 1024.0 } else { v }; + let rows = matrix.map(|r| [cut(r[0]), cut(r[1]), cut(r[2]), if hdr { r[3] * 255.0 / 512.0 } else { r[3] }]); + p[0] = rows[0]; + p[1] = rows[1]; + p[2] = rows[2]; + p[3][0] = if *monochrome { 1.0 } else { 0.0 }; + (10, p, None) + } + Adjustment::PhotoFilter { color, density, preserve_luminosity } => { + // compose::adjust: the linear-light matrix, then SetLum on the encoded values (8/16-bit). + let linear_doc = depth == photocraft_color::SampleType::F32; + let m = adjust::photo_filter_matrix(*color, *density, *preserve_luminosity && linear_doc); + for (row, m) in p.iter_mut().zip(m) { + *row = [m[0], m[1], m[2], 0.0]; + } + p[3] = [if *preserve_luminosity && !linear_doc { 1.0 } else { 0.0 }, transfer_exponent(transfer), 0.0, 0.0]; + (11, p, None) + } + Adjustment::BlackWhite { weights, tint } => { + p[0] = [weights[0], weights[1], weights[2], weights[3]]; + p[1] = [weights[4], weights[5], if tint.is_some() { 1.0 } else { 0.0 }, 0.0]; + if let Some(t) = tint { + p[2] = [t[0], t[1], t[2], 0.0]; + } + (12, p, None) + } + Adjustment::GradientMap { stops, reverse, dither } => { + p[0][0] = if *reverse { 1.0 } else { 0.0 }; + p[0][1] = if *dither { 1.0 } else { 0.0 }; + let s4: Vec<(f32, [f32; 4])> = stops.iter().map(|(t, c)| (*t, [c[0], c[1], c[2], 1.0])).collect(); + let rows = lut_rows(|r, t| if s4.is_empty() { t } else { sample_stops4(&s4, t)[r] }, 3); + (13, p, Some(rows)) + } + Adjustment::ColorBalance { shadows, midtones, highlights, preserve_luminosity } => { + // Per-channel curves (compose::adjust::BalanceCurve), through the Levels kernel. + let curves = adjust::BalanceCurve::rgb([*shadows, *midtones, *highlights], *preserve_luminosity); + (7, p, Some(lut_rows(|ch, v| curves[ch].eval(v), 3))) + } + Adjustment::SelectiveColor { relative, adjustments } => { + // 9 ranges × CMYK don't fit the 16 params: they go in LUT row 0 (read texel-exact). + p[0][0] = if *relative { 1.0 } else { 0.0 }; + let mut row = [0.0f32; 4096]; + for (i, v) in adjustments.iter().flatten().enumerate() { + row[i] = *v; + } + (15, p, Some(vec![row])) + } + Adjustment::ColorLookup { lut: Some(table), size, tetrahedral, dither, .. } if lut3d_len(*size).is_some_and(|len| table.len() >= len) => { + // The flattened table (n³ RGB triplets) spans as many 4096-wide rows as it needs. + let n = *size as usize; + let rows = lut3d_len(*size) + .and_then(|len| table.get(..len)) + .unwrap_or_default() + .chunks(4096) + .map(|c| { + let mut row = [0.0f32; 4096]; + row[..c.len()].copy_from_slice(c); + row + }) + .collect(); + p[0] = [n as f32, if *tetrahedral { 1.0 } else { 0.0 }, if *dither { 1.0 } else { 0.0 }, 0.0]; + (16, p, Some(rows)) + } + // Identity on the CPU too (not evaluated there). + Adjustment::ColorLookup { .. } | Adjustment::Unsupported { .. } => (0, p, None), + } +} + +/// A gradient's colour and alpha as four 4096-entry LUT rows (`lut_tex`). +pub(super) fn gradient_rows(g: &Gradient) -> Vec<[f32; 4096]> { + let mut rows = vec![[0.0f32; 4096]; 4]; + for k in 0..4096 { + let v = photocraft_compose::effects::sample_gradient(g, k as f32 / 4095.0); + for (ch, row) in rows.iter_mut().enumerate() { + row[k] = v[ch]; + } + } + rows +} + +/// Linear interpolation between LUT entries cannot preserve a discontinuity. Let the canvas +/// use the CPU oracle for coincident stops, including opacity stops and unsorted fill ramps +/// (which `gradient_fill::Ramp` sorts). Check only ramps we will sample: cached fills and +/// disabled effects can still use the GPU. +pub(super) fn check_gradient_stops(stops: &[(f32, T)]) -> Result<(), Unsupported> { + let mut positions: Vec = stops.iter().map(|s| s.0).collect(); + positions.sort_by(f32::total_cmp); + // A 4096-entry LUT cannot keep two stops that fall in the same entry apart (#3053). + if positions.windows(2).any(|w| (w[1] - w[0]).abs() < 1.0 / 4095.0) { + return Err(Unsupported("coincident gradient stops (composited on the CPU)".into())); + } + Ok(()) +} + +/// Mode index used by the shader (declaration order of [`BlendMode`]). +pub fn mode_index(m: BlendMode) -> i32 { + match m { + BlendMode::PassThrough => 0, + BlendMode::Normal => 1, + BlendMode::Dissolve => 2, + BlendMode::Darken => 3, + BlendMode::Multiply => 4, + BlendMode::ColorBurn => 5, + BlendMode::LinearBurn => 6, + BlendMode::DarkerColor => 7, + BlendMode::Lighten => 8, + BlendMode::Screen => 9, + BlendMode::ColorDodge => 10, + BlendMode::LinearDodge => 11, + BlendMode::LighterColor => 12, + BlendMode::Overlay => 13, + BlendMode::SoftLight => 14, + BlendMode::HardLight => 15, + BlendMode::VividLight => 16, + BlendMode::LinearLight => 17, + BlendMode::PinLight => 18, + BlendMode::HardMix => 19, + BlendMode::Difference => 20, + BlendMode::Exclusion => 21, + BlendMode::Subtract => 22, + BlendMode::Divide => 23, + BlendMode::Hue => 24, + BlendMode::Saturation => 25, + BlendMode::Color => 26, + BlendMode::Luminosity => 27, + BlendMode::Reflect => 28, + BlendMode::Glow => 29, + BlendMode::Negation => 30, + BlendMode::Xor => 31, + BlendMode::PaintNetColorBurn => 32, + BlendMode::PaintNetColorDodge => 33, + } +} + +/// Whether `Planner::content` draws `layer` as one `Planner::content_pass`: not a group's stack, +/// an adjustment, or a pattern fill painted in passes. +pub(super) fn single_content_pass(layer: &Layer) -> bool { + match &layer.content { + LayerContent::Group(_) | LayerContent::Adjustment(_) => false, + LayerContent::Fill(f @ Fill::Pattern { .. }) => layer.fill_cache.as_ref().is_some_and(|c| c.fill == *f), + _ => true, + } +} diff --git a/crates/gpu/src/plan/planner.rs b/crates/gpu/src/plan/planner.rs new file mode 100644 index 0000000000..577237e975 --- /dev/null +++ b/crates/gpu/src/plan/planner.rs @@ -0,0 +1,1215 @@ +use super::lower::{ + Paint, adjustment_on_gpu, adjustment_program, check_gradient_stops, gradient_rows, placement, single_content_pass, stroke_widths, style_index, +}; +use super::types::{Checkpoint, DocCtx, FxLayer, Kernel, MapRef, MaskUse, Pass, Role, SurfaceRef, TexUse, Unsupported}; +use super::*; + +pub(super) struct Planner<'a> { + passes: Vec>, + free: Vec, + refs: Vec, + cx: DocCtx<'a>, + fx: Vec>, + checkpoints: Vec, + /// Layers planned so far, counting a layer each time it is planned (a clipped pass-through + /// group is planned twice). + visits: usize, +} + +/// Most layer plannings one document may take: a pass-through group with clipped layers is +/// planned twice, so groups nested in one another double the work at every level. +const MAX_PLAN_VISITS: usize = 100_000; + +/// Coverage source of an effect paint (`kind` in `fs_fxpaint`); flags refine it. +#[derive(Clone, Copy)] +enum Cov { + /// An effect map; `outside` beyond its region. + Map(MapRef, f32), + /// Full coverage. + One, +} + +/// Shader flags for effect passes (keep in sync with compose.wgsl). Coverage `m` of a paint, with +/// `a` the layer's alpha and `inside` = `a > 0.5/255`: +/// knockout `m × (1 − a × k)` (k in `p4.w`); gate `inside ? m : 0`; rel `inside ? min(m / a, 1) : 0`; +/// stroke-out `inside ? (vector ? 0 : (1 − a) / (1 − layer alpha), 1 at an opaque layer) : m`. +pub const F_KNOCKOUT: u32 = 16; + +/// Effect merge: A already holds the layer; only mix with the backdrop by the layer's opacity. +pub const F_NO_LAYER: u32 = 32; + +/// Outside strokes along a filled shape's outline (`effects::outline_share`; the coverage slot +/// carries the layer's alpha in `.g`). +pub const F_OUTLINE: u32 = 131072; + +/// Shape layer (outside strokes never show inside it). +pub const F_VECTOR: u32 = 64; + +/// Merge onto an opaque clipping base, keeping its alpha. +pub const F_ATOP: u32 = 128; + +pub const F_GATE: u32 = 256; + +pub const F_REL: u32 = 512; + +pub const F_STROKE_OUT: u32 = 1024; + +/// First outside stroke (no accumulated share yet). +pub const F_FIRST: u32 = 2048; + +/// `Lerp` per channel: weights in `p0` (channel restrictions), no opacity or mask. +pub const F_CHANNELS: u32 = 4096; + +/// Lab document: Normal blending mixes in CIELAB (`psblend::LAB_MIX`). +pub const F_LAB: u32 = 65536; + +/// 32-bit float document: Add, Divide and Exposure retain values above 1; the non-separable +/// blend modes clip only below 0 (`psblend::HDR`). +pub const F_HDR: u32 = 262144; + +/// `Lerp`: A rounded to `p0.x` steps per unit (adjustment results on integer documents). +pub const F_QUANT: u32 = 32768; + +/// `Lerp` as A + (B − C) premultiplied (layers clipped to pass-through groups). +pub const F_ADD_DIFF: u32 = 16384; + +/// `Lerp`: B mixed back towards A (the backdrop) by the layer's Blend If weight +/// (`compose::apply_blend_if`), from C ("This Layer", or B itself for an adjustment layer, `p4.y`) +/// and A ("Underlying Layer"). The ranges are packed in `p0..p3` (`blend_if_params`); `p4.x` marks +/// a one-channel document. +pub const F_BLEND_IF: u32 = 524288; + +/// Blend / Atop / FxMerge of a type layer: coverage mixed at `psblend::TEXT_GAMMA`. +pub const F_TEXT_GAMMA: u32 = 8192; + +/// `FxMerge`: B is the layer's shape (its content); the layer is its colour at fill opacity +/// (`p0.x`) inside the shape, times the shape's alpha: `FxInit` `INIT_INSIDE` then +/// `INIT_ALPHA` in the merge, for a layer with no interior effects between them. +pub const F_LAYER_SHAPE: u32 = 1_048_576; + +/// A layer's Blend If ranges for `F_BLEND_IF`: Gray, then the colour channels, each as +/// [this layer, underlying layer]; every range as two floats, `black low × 256 + black high` and +/// `white low × 256 + white high` (exact in f32), so entry `e`, side `s` starts at float +/// `(e × 2 + s) × 2`. Entries past the fourth never apply (RGB has four, one-channel modes two). +pub(super) fn blend_if_params(bi: &photocraft_doc::BlendIf) -> [[f32; 4]; 4] { + let mut f = [0.0f32; 16]; + for e in 0..4 { + for (s, r) in bi.get(e).iter().enumerate() { + let i = (e * 2 + s) * 2; + f[i] = f32::from(r.black[0]) * 256.0 + f32::from(r.black[1]); + f[i + 1] = f32::from(r.white[0]) * 256.0 + f32::from(r.white[1]); + } + } + [[f[0], f[1], f[2], f[3]], [f[4], f[5], f[6], f[7]], [f[8], f[9], f[10], f[11]], [f[12], f[13], f[14], f[15]]] +} + +/// `F_TEXT_GAMMA` for type layers while text gamma blending is on; the gamma goes in `p4.w`. +fn gamma_flag(layer: &Layer) -> u32 { + if photocraft_compose::text_gamma(layer) != 1.0 { F_TEXT_GAMMA } else { 0 } +} + +/// `FxInit` kinds: A at `opacity` × alpha; an opaque copy of A; A's colour with alpha `opacity` +/// inside B's shape; A with alpha × B's alpha. +pub const INIT_SCALE: i32 = 0; + +pub const INIT_OPAQUE: i32 = 1; + +pub const INIT_INSIDE: i32 = 2; + +pub const INIT_ALPHA: i32 = 3; + +/// The vector stroke C over A relative to the shape B, at `opacity`. +pub const INIT_VSTROKE: i32 = 4; + +/// A's colour with alpha `opacity` × A's alpha relative to B's. +pub const INIT_RELATIVE: i32 = 5; + +/// Outside-stroke coverage seed: (0, A's alpha). +pub const INIT_COVER: i32 = 6; + +/// A with its alpha joined with the effect shape (the map). +pub const INIT_OUTLINE: i32 = 7; + +/// `MapRef::item` of the layer's effect shape (`compose::layer_shape`) instead of an effect map. +pub const SHAPE_MAP: usize = usize::MAX; + +impl<'a> Planner<'a> { + pub(super) fn new(cx: DocCtx<'a>) -> Self { + Planner { passes: Vec::new(), free: Vec::new(), refs: Vec::new(), cx, fx: Vec::new(), checkpoints: Vec::new(), visits: 0 } + } + + pub(super) fn finish(self, root: Slot) -> Plan<'a> { + Plan { passes: self.passes, slots: self.refs.len() as u32, root, fx: self.fx, checkpoints: self.checkpoints } + } + + fn alloc(&mut self) -> Slot { + if let Some(s) = self.free.pop() { + self.refs[s as usize] = 1; + return s; + } + self.refs.push(1); + (self.refs.len() - 1) as Slot + } + fn retain(&mut self, s: Slot) -> Slot { + self.refs[s as usize] += 1; + s + } + fn release(&mut self, s: Slot) { + let r = &mut self.refs[s as usize]; + *r -= 1; + if *r == 0 { + self.free.push(s); + } + } + /// Emit `pass` into a fresh slot, releasing its inputs. + fn emit(&mut self, mut pass: Pass<'a>) -> Slot { + let dst = self.alloc(); + pass.dst = dst; + if self.cx.mode == photocraft_color::ColorMode::Lab { + pass.flags |= F_LAB; + } + if self.cx.depth == photocraft_color::SampleType::F32 { + pass.flags |= F_HDR; + } + let (a, b, c, d) = (pass.a, pass.b, pass.c, pass.d); + self.passes.push(pass); + for s in [a, b, c, d].into_iter().flatten() { + self.release(s); + } + dst + } + pub(super) fn clear(&mut self) -> Slot { + self.emit(Pass::new(Kernel::Clear, 0)) + } + + /// composite_stack: returns the new backdrop (consumes `backdrop`). + fn stack(&mut self, layers: &'a [Layer], backdrop: Slot) -> Result { + self.stack_inner(layers, backdrop, None) + } + + pub(super) fn stack_inner(&mut self, layers: &'a [Layer], mut backdrop: Slot, root_start: Option) -> Result { + let mut i = 0; + while i < layers.len() { + let base = &layers[i]; + let mut j = i + 1; + while j < layers.len() && layers[j].clipped && !base.clipped { + j += 1; + } + let clipped = &layers[i + 1..j]; + if base.visible { + backdrop = self.layer(base, clipped, backdrop)?; + if let (LayerContent::Adjustment(_), Some(q)) = (&base.content, photocraft_compose::adjustment_quantum(self.cx.depth)) { + // compose: adjustment results are rounded to the document's depth. + let mut p = Pass::new(Kernel::Lerp, 0); + p.a = Some(backdrop); + p.flags = F_QUANT; + p.params[0] = [q, 0.0, 0.0, 0.0]; + backdrop = self.emit(p); + } + } + i = j.max(i + 1); + if let Some(start) = root_start + && self.refs.iter().enumerate().all(|(slot, &refs)| refs == u32::from(slot == backdrop as usize)) + { + self.checkpoints.push(Checkpoint { layer_start: start, layer_end: start.saturating_add(i), pass_end: self.passes.len(), slot: backdrop }); + } + } + Ok(backdrop) + } + + fn mask_use(&self, layer: &'a Layer) -> Option> { + if let Some(c) = photocraft_compose::masks::combined_mask(layer, self.cx.canvas) { + let default = c.default_pixel().first().copied().unwrap_or(1.0); + return Some(MaskUse { layer: layer.id, surface: SurfaceRef::Derived(std::sync::Arc::new(c)), density: 1.0, default }); + } + let m = layer.mask.as_ref()?; + if !m.enabled { + return None; + } + Some(MaskUse { + layer: layer.id, + surface: SurfaceRef::Doc(&m.surface), + density: m.density, + default: m.surface.default_pixel().first().copied().unwrap_or(1.0), + }) + } + + /// `compose::apply_blend_if`: `after` (the backdrop with `layer` drawn) mixed back towards + /// `before` (the backdrop without it) where the layer's Blend If ranges hide it. "This Layer" + /// is the layer's own content with its masks; an adjustment layer is judged by its result. + /// Consumes both slots. + fn blend_if(&mut self, layer: &'a Layer, before: Slot, after: Slot) -> Result { + let own = match layer.content { + LayerContent::Adjustment(_) => None, + _ => Some(self.content(layer)?), + }; + let mut p = Pass::new(Kernel::Lerp, 0); + p.a = Some(before); + p.b = Some(after); + p.c = own; + p.flags = F_BLEND_IF; + p.params = blend_if_params(&layer.blend_if); + let one_channel = self.cx.mode != photocraft_color::ColorMode::Rgb; + p.extra = [f32::from(u8::from(one_channel)), f32::from(u8::from(own.is_none())), 0.0, 0.0]; + Ok(self.emit(p)) + } + + /// Channel restrictions and Blend If around `draw`, which composites `layer` onto `backdrop` + /// (`compose::composite_layer` / `composite_atop`: both are relative to the same backdrop). + fn restricted(&mut self, layer: &'a Layer, backdrop: Slot, draw: impl FnOnce(&mut Self, Slot) -> Result) -> Result { + let w = photocraft_compose::channel_weights(layer, self.cx.mode); + let blend_if = photocraft_compose::blend_if_active(layer, self.cx.mode); + if w.is_none() && !blend_if { + return draw(self, backdrop); + } + let before = self.retain(backdrop); + let mut after = draw(self, backdrop)?; + if let Some(w) = w { + let b = if blend_if { self.retain(before) } else { before }; + after = self.restore_channels(b, after, w); + } + if blend_if { + after = self.blend_if(layer, before, after)?; + } + Ok(after) + } + + /// Blending Options › Advanced Blending (knockout, clipped layers blended individually, blend + /// interior effects as group, transparency shapes off, masks hiding effects) has no GPU pass: + /// documents using it are composited on the CPU (`photocraft_compose::advanced`). Layers at + /// Photoshop's defaults pass this check for free. + fn check_advanced(&self, layer: &Layer, clipped: &[Layer]) -> Result<(), Unsupported> { + if photocraft_compose::advanced_active(layer, clipped) { + return Err(Unsupported(format!("Advanced Blending on `{}` (composited on the CPU)", layer.name))); + } + Ok(()) + } + + /// composite_layer, honouring the layer's channel restrictions. + fn layer(&mut self, layer: &'a Layer, clipped: &'a [Layer], backdrop: Slot) -> Result { + self.visits += 1; + if self.visits > MAX_PLAN_VISITS { + return Err(Unsupported("too many nested layers to plan for the GPU (composited on the CPU)".into())); + } + self.check_advanced(layer, clipped)?; + self.restricted(layer, backdrop, |s, b| s.layer_any(layer, clipped, b)) + } + + /// `compose::restore_channels`: `after` with the channels a layer leaves out taken from + /// `before` (consumes both). + fn restore_channels(&mut self, before: Slot, after: Slot, w: [f32; 3]) -> Slot { + let mut p = Pass::new(Kernel::Lerp, 0); + p.a = Some(before); + p.b = Some(after); + p.flags = F_CHANNELS; + p.params[0] = [w[0], w[1], w[2], 1.0]; + self.emit(p) + } + + fn layer_any(&mut self, layer: &'a Layer, clipped: &'a [Layer], backdrop: Slot) -> Result { + match layer.artboard() { + Some(ab) => self.artboard(layer, ab, clipped, backdrop), + None => self.layer_plain(layer, clipped, backdrop), + } + } + + /// compose::composite_artboard: the board's background and the group composited over the + /// backdrop, kept only inside the board (contents and effects outside it are clipped away). + fn artboard(&mut self, layer: &'a Layer, ab: &photocraft_doc::Artboard, clipped: &'a [Layer], backdrop: Slot) -> Result { + let board = ab.rect.intersect(&self.cx.canvas); + if board.is_empty() { + return Ok(backdrop); + } + let before = self.retain(backdrop); + let mut sub = backdrop; + if let Some(bg) = ab.background.rgba() { + let mut c = Pass::new(Kernel::Content, 0); + c.color = bg; + let c = self.emit(c); + let mut p = Pass::new(Kernel::Blend, 0); + p.a = Some(sub); + p.b = Some(c); + sub = self.emit(p); + } + let sub = self.layer_plain(layer, clipped, sub)?; + let dst = if self.refs[before as usize] == 1 { + before + } else { + let n = self.alloc(); + let mut p = Pass::new(Kernel::CopyFull, n); + p.a = Some(before); + self.passes.push(p); + self.release(before); + n + }; + let mut p = Pass::new(Kernel::CopyRect, dst); + p.a = Some(sub); + p.clip = Some(board); + self.passes.push(p); + self.release(sub); + Ok(dst) + } + + fn layer_plain(&mut self, layer: &'a Layer, clipped: &'a [Layer], backdrop: Slot) -> Result { + let opacity = layer.opacity * layer.fill_opacity; + let visible_clipped: Vec<&'a Layer> = clipped.iter().filter(|c| c.visible).collect(); + + // Below 100% fill a pass-through group renders isolated (as the CPU compositor does), and + // so does one that is the base of a clipping group and holds an adjustment layer. + let clip_base_adjusts = !visible_clipped.is_empty() + && matches!(&layer.content, LayerContent::Group(g) if g.children.iter().any(|c| c.visible && matches!(c.content, LayerContent::Adjustment(_)))); + if let LayerContent::Group(g) = &layer.content + && layer.blend == BlendMode::PassThrough + && layer.fill_opacity >= 1.0 + && !has_effects(layer) + && !clip_base_adjusts + { + let before = self.retain(backdrop); + let mut after = self.stack(&g.children, backdrop)?; + if opacity < 1.0 || layer.mask.is_some() || layer.vector_mask.is_some() { + let mut p = Pass::new(Kernel::Lerp, 0); + p.a = Some(self.retain(before)); + p.b = Some(after); + p.opacity = opacity; + p.mask = self.mask_use(layer); + after = self.emit(p); + } + if visible_clipped.is_empty() { + self.release(before); + return Ok(after); + } + // Layers clipped to a pass-through group (compose: their effect on the group's + // isolated rendering, each placed over the original backdrop, is added to the + // pass-through result, premultiplied). + let iso = self.content(layer)?; + let iso_keep = self.retain(iso); + let mut clipped_iso = iso; + for c in visible_clipped { + clipped_iso = self.atop(c, clipped_iso)?; + } + let over = |s: &mut Self, src: Slot, before: Slot| { + let mut p = Pass::new(Kernel::Blend, 0); + p.a = Some(before); + p.b = Some(src); + p.opacity = opacity; + s.emit(p) + }; + let b2 = self.retain(before); + let without = over(self, iso_keep, b2); + let with = over(self, clipped_iso, before); + let mut p = Pass::new(Kernel::Lerp, 0); + p.a = Some(after); + p.b = Some(with); + p.c = Some(without); + p.flags = F_ADD_DIFF; + return Ok(self.emit(p)); + } + + if let LayerContent::Adjustment(adj) = &layer.content { + let before = self.retain(backdrop); + let mut adjusted = self.adjust(adj, backdrop)?; + for c in visible_clipped { + adjusted = self.atop(c, adjusted)?; + } + let mut p = Pass::new(Kernel::AdjMix, 0); + p.a = Some(before); + p.b = Some(adjusted); + p.mode = layer.blend; + p.opacity = opacity; + p.mask = self.mask_use(layer); + return Ok(self.emit(p)); + } + + if has_effects(layer) { + return self.effects(layer, &visible_clipped, backdrop, false); + } + + if let LayerContent::Shape(sh) = &layer.content + && !visible_clipped.is_empty() + && let Some((fill, stroke)) = photocraft_compose::shape_split::split(sh, self.cx.canvas, self.cx.depth) + { + // The vector stroke goes above the clipped layers: the fill is the clipping base, + // the stroke is laid over the clipped result, then the masks apply to both + // (compose::shape_parts). + let mut content = self.shape_part(layer, Role::Content, fill); + for c in visible_clipped { + content = self.atop(c, content)?; + } + let stroke = self.shape_part(layer, Role::Stroke, stroke); + let mut p = Pass::new(Kernel::Blend, 0); + p.a = Some(content); + p.b = Some(stroke); + let mut content = self.emit(p); + if let Some(m) = self.mask_use(layer) { + let mut p = Pass::new(Kernel::Mask, 0); + p.a = Some(content); + p.mask = Some(m); + content = self.emit(p); + } + let mut p = Pass::new(Kernel::Blend, 0); + p.a = Some(backdrop); + p.b = Some(content); + p.mode = layer.blend; + p.opacity = layer.opacity; + p.fill = layer.fill_opacity; + return Ok(self.emit(p)); + } + + // A layer that covers little of the canvas composites only over its bounds and is + // copied back into the backdrop (#125): a layout with hundreds of small text and shape + // layers otherwise shades every layer over every chunk. + let clip = self.local_clip(layer); + if clip.is_some_and(|c| c.is_empty()) { + // Nothing to draw (an empty layer, or a group of them). + for c in &visible_clipped { + self.check_advanced(c, &[])?; + } + return Ok(backdrop); + } + // A layer with nothing clipped to it whose content is one Content pass is blended + // straight from its pixels (`Kernel::LayerBlend`): one pass instead of two, and no + // scratch chunk written and read back. + let mut p = if visible_clipped.is_empty() && single_content_pass(layer) { + let mut p = self.content_pass(layer)?; + p.kernel = Kernel::LayerBlend; + p + } else { + let start = self.passes.len(); + let mut content = self.content(layer)?; + for c in visible_clipped { + content = self.atop(c, content)?; + } + if let Some(clip) = clip { + // Everything that built the layer's content only matters inside its bounds. + for p in &mut self.passes[start..] { + if p.clip.is_none() && !matches!(p.kernel, Kernel::Clear | Kernel::CopyFull) { + p.clip = Some(clip); + } + } + } + let mut p = Pass::new(Kernel::Blend, 0); + p.b = Some(content); + p + }; + p.a = Some(if clip.is_some() { self.retain(backdrop) } else { backdrop }); + p.mode = layer.blend; + p.opacity = layer.opacity; + p.fill = layer.fill_opacity; + p.flags |= gamma_flag(layer); + p.extra[3] = photocraft_compose::text_gamma(layer); + p.clip = clip; + let merged = self.emit(p); + match clip { + Some(clip) => Ok(self.write_back(backdrop, merged, clip)), + None => Ok(merged), + } + } + + /// The rect a plain layer composites over: its composite bounds when they cover at most half + /// the canvas (beyond that, compositing everywhere costs less than the copy back). + fn local_clip(&self, layer: &Layer) -> Option { + let canvas = self.cx.canvas; + let b = bounds::composite_bounds(layer, canvas)?; + (b.width() as u64 * b.height() as u64 * 2 <= canvas.width() as u64 * canvas.height() as u64).then_some(b) + } + + /// Copy `merged` into `backdrop` over `clip` (in place when nothing else holds the backdrop); + /// returns the new backdrop. Consumes both. + fn write_back(&mut self, backdrop: Slot, merged: Slot, clip: Rect) -> Slot { + // A clip over the whole canvas left no pixel of `merged` uncomputed: it is the backdrop. + if clip.contains_rect(&self.cx.canvas) { + self.release(backdrop); + return merged; + } + let dst = if self.refs[backdrop as usize] == 1 { + backdrop + } else { + let n = self.alloc(); + let mut p = Pass::new(Kernel::CopyFull, n); + p.a = Some(backdrop); + self.passes.push(p); + self.release(backdrop); + n + }; + let mut p = Pass::new(Kernel::CopyRect, dst); + p.a = Some(merged); + p.clip = Some(clip); + self.passes.push(p); + self.release(merged); + dst + } + + /// A stroked shape's fill or vector stroke alone (`compose::shape_split`), unmasked. + fn shape_part(&mut self, layer: &'a Layer, role: Role, surface: Surface) -> Slot { + let mut p = Pass::new(Kernel::Content, 0); + p.color = photocraft_raster::to_rgba(&surface.format(), &surface.default_pixel()); + if surface.tile_count() > 0 { + p.tex = Some(TexUse { layer: layer.id, role, surface: SurfaceRef::Derived(std::sync::Arc::new(surface)) }); + } + self.emit(p) + } + + /// render_content for non-adjustment layers. + fn content(&mut self, layer: &'a Layer) -> Result { + match &layer.content { + LayerContent::Group(g) => { + let empty = self.clear(); + let s = self.stack(&g.children, empty)?; + if layer.mask.is_some() || layer.vector_mask.is_some() { + let mut p = Pass::new(Kernel::Mask, 0); + p.a = Some(s); + p.mask = self.mask_use(layer); + return Ok(self.emit(p)); + } + Ok(s) + } + // Adjustments are handled by the caller and never get here. + LayerContent::Adjustment(_) => Err(Unsupported("adjustment layer reached the content planner".into())), + LayerContent::Fill(f @ Fill::Pattern { name, scale, id, angle, link, phase }) if layer.fill_cache.as_ref().is_none_or(|c| c.fill != *f) => { + // compose::render_fill: the pattern tiled from the layer's frame (transparent + // when missing), then the layer's masks. + let empty = self.clear(); + let Some(pat) = photocraft_doc::pattern::find(self.cx.patterns, id, name).filter(|p| p.is_paintable()) else { return Ok(empty) }; + let frame = photocraft_compose::fill_frame(layer, self.cx.canvas); + let anchor = if frame.is_empty() { (0.0, 0.0) } else { (f64::from(frame.x0), f64::from(frame.y0)) }; + let paint = Paint::Pattern(pat, placement(anchor, *link, *phase, *scale, *angle)); + let canvas = self.cx.canvas; + let s = self.paint(empty, empty, Cov::One, &paint, BlendMode::Normal, 1.0, 0, canvas, canvas); + if layer.mask.is_some() || layer.vector_mask.is_some() { + let mut p = Pass::new(Kernel::Mask, 0); + p.a = Some(s); + p.mask = self.mask_use(layer); + return Ok(self.emit(p)); + } + Ok(s) + } + _ => { + let p = self.content_pass(layer)?; + Ok(self.emit(p)) + } + } + } + + /// The Content pass of a raster / text / shape / smart / fill layer. + fn content_pass(&self, layer: &'a Layer) -> Result, Unsupported> { + let mut p = Pass::new(Kernel::Content, 0); + p.mask = self.mask_use(layer); + match &layer.content { + LayerContent::Fill(f) => match &layer.fill_cache { + Some(c) if c.fill == *f => self.surface_tex(&mut p, layer.id, &c.surface), + _ => self.fill(&mut p, f, photocraft_compose::fill_frame(layer, self.cx.canvas))?, + }, + _ => { + if let Some(s) = layer.surface() { + self.surface_tex(&mut p, layer.id, s); + } + } + } + Ok(p) + } + + fn surface_tex(&self, p: &mut Pass<'a>, id: LayerId, s: &'a Surface) { + let dp = s.default_pixel(); + p.color = photocraft_raster::to_rgba(&s.format(), &dp); + if s.tile_count() > 0 { + p.tex = Some(TexUse { layer: id, role: Role::Content, surface: SurfaceRef::Doc(s) }); + } + } + + fn fill(&self, p: &mut Pass<'a>, f: &Fill, frame: photocraft_geom::Rect) -> Result<(), Unsupported> { + // The RGB shader cannot interpolate or dither native ink channels. + if self.cx.mode == photocraft_color::ColorMode::Cmyk && !matches!(f, Fill::Pattern { .. }) { + return Err(Unsupported("native CMYK fill (composited on the CPU)".into())); + } + match f { + Fill::Solid(c) => { + let rgb = c.to_rgb(); + p.color = [rgb[0], rgb[1], rgb[2], c.alpha]; + } + Fill::Gradient { stops, opacity_stops, angle, scale, style, reverse, offset, dither, .. } => { + check_gradient_stops(stops)?; + check_gradient_stops(opacity_stops)?; + p.gradient = true; + // compose::render_fill: whole-pixel end points (fill_layout). + let (angle, scale, offset) = photocraft_compose::fill_layout::gradient_layout(*style, *angle, *scale, *offset, frame); + p.params[0] = [angle, scale, if *reverse { 1.0 } else { 0.0 }, style_index(*style)]; + let c = frame; + p.params[1] = [c.x0 as f32, c.y0 as f32, c.width() as f32, c.height() as f32]; + // p2.xy: centre offset; p2.z: the depth's levels a dithered pixel is rounded to + // (0: float, compose::gradient_fill::render_quantized); p2.w: dither (the shared + // position hash, see the shader). + let quantum = photocraft_compose::adjustment_quantum(self.cx.depth).unwrap_or(0.0); + p.params[2] = [offset.0, offset.1, quantum, if *dither { 1.0 } else { 0.0 }]; + let ramp = photocraft_compose::gradient_fill::Ramp::new(f); + let mut rows = vec![[0.0f32; 4096]; 4]; + for k in 0..4096 { + let v = ramp.as_ref().map_or([0.0; 4], |r| r.sample(k as f32 / 4095.0)); + for (ch, row) in rows.iter_mut().enumerate() { + row[k] = v[ch]; + } + } + p.lut = Some(rows); + } + // Pattern fills fall back to the CPU compositor (see `check`). + Fill::Pattern { .. } => {} + } + Ok(()) + } + + /// composite_atop: `layer` onto `base`, restricted to the base's alpha, honouring the + /// layer's channel restrictions. + fn atop(&mut self, layer: &'a Layer, base: Slot) -> Result { + self.check_advanced(layer, &[])?; + self.restricted(layer, base, |s, b| s.atop_any(layer, b)) + } + + fn atop_any(&mut self, layer: &'a Layer, base: Slot) -> Result { + let opacity = layer.opacity * layer.fill_opacity; + if let LayerContent::Adjustment(adj) = &layer.content { + let before = self.retain(base); + let adjusted = self.adjust(adj, base)?; + let mut p = Pass::new(Kernel::AdjMix, 0); + p.a = Some(before); + p.b = Some(adjusted); + p.mode = layer.blend; + p.opacity = opacity; + p.mask = self.mask_use(layer); + return Ok(self.emit(p)); + } + if has_effects(layer) { + return self.effects(layer, &[], base, true); + } + let content = self.content(layer)?; + let mut p = Pass::new(Kernel::Atop, 0); + p.a = Some(base); + p.b = Some(content); + p.mode = layer.blend; + p.opacity = opacity; + p.flags = gamma_flag(layer); + p.extra[3] = photocraft_compose::text_gamma(layer); + Ok(self.emit(p)) + } + + /// adjust::apply_with on a slot (consumes it). + fn adjust(&mut self, adj: &Adjustment, src: Slot) -> Result { + if !adjustment_on_gpu(adj, self.cx.mode) { + return Err(Unsupported(format!("{} on CMYK/Lab channels (evaluated on the CPU)", adj.label()))); + } + if let Adjustment::GradientMap { stops, .. } = adj { + check_gradient_stops(stops)?; + } + let mut p = Pass::new(Kernel::Adjust, 0); + p.a = Some(src); + let (kind, params, lut) = adjustment_program(adj, self.cx.transfer, self.cx.depth, self.cx.mode); + p.adjust_kind = kind; + p.params = params; + p.lut = lut; + Ok(self.emit(p)) + } + + /// `composite_with_effects` (atop = false) or the clipped-layer variant of `composite_atop` + /// (atop = true: effects over the base treated as opaque, keeping the base's alpha). + /// Consumes `backdrop`. + fn effects(&mut self, layer: &'a Layer, clipped: &[&'a Layer], backdrop: Slot, atop: bool) -> Result { + let canvas = self.cx.canvas; + let region = bounds::effect_region(layer, canvas); + let sb = photocraft_compose::paint_bounds(layer).unwrap_or_else(|| bounds::layer_bounds(layer, canvas)); + let clip = if bounds::transparent_outside(layer) { region } else { canvas }; + // A stroked shape's vector stroke goes above its clipped layers and interior effects + // (compose::split_parts): the fill and the stroke unmasked, the masks applied after. + let split = match &layer.content { + LayerContent::Shape(sh) if sh.stroke.is_some() => photocraft_compose::shape_split::split(sh, canvas, self.cx.depth), + _ => None, + }; + let (mut content, vstroke) = match split { + Some((fill, stroke)) => { + let f = self.shape_part(layer, Role::Content, fill); + let s = self.shape_part(layer, Role::Stroke, stroke); + (f, Some(s)) + } + None => (self.content(layer)?, None), + }; + for p in self.passes.iter_mut().rev().take(if vstroke.is_some() { 2 } else { 1 }) { + if !matches!(layer.content, LayerContent::Group(_)) { + p.clip = Some(clip); + } + } + for c in clipped { + content = self.atop(c, content)?; + } + let fx = self.fx.len(); + self.fx.push(FxLayer { layer, region, bounds: sb }); + let outline = photocraft_compose::effect_outline(layer).is_some(); + let relative = outline || vstroke.is_some(); + // `content` becomes the effect shape (B of every effect pass); `lay_src` the layer's colour. + let (lay_src, vstroke) = match vstroke { + Some(s) => { + let mut p = Pass::new(Kernel::Blend, 0); + p.a = Some(self.retain(content)); + p.b = Some(self.retain(s)); + p.clip = Some(clip); + let union = self.emit(p); + let m = self.mask_use(layer); + let masked = |me: &mut Self, slot: Slot| match &m { + Some(m) => { + let mut p = Pass::new(Kernel::Mask, 0); + p.a = Some(slot); + p.mask = Some(m.clone()); + p.clip = Some(clip); + me.emit(p) + } + None => slot, + }; + let fill = masked(self, content); + content = masked(self, union); + (fill, Some(masked(self, s))) + } + None => (self.retain(content), None), + }; + if outline { + let mut p = Pass::new(Kernel::FxInit, 0); + p.a = Some(content); + p.adjust_kind = INIT_OUTLINE; + p.map = Some(MapRef { fx, item: SHAPE_MAP, map: 0 }); + p.clip = Some(clip); + content = self.emit(p); + } + + let items: Vec<&'a Effect> = layer.effects.items.iter().filter(|e| e.enabled()).collect(); + for e in &items { + let gradient = match e { + Effect::GradientOverlay { gradient, .. } => Some(gradient), + Effect::Stroke(s) => match &s.paint { + FxPaint::Gradient(g) => Some(g), + _ => None, + }, + Effect::OuterGlow(g) | Effect::InnerGlow(g) => match &g.paint { + FxPaint::Gradient(g) => Some(g), + _ => None, + }, + _ => None, + }; + if let Some(g) = gradient { + check_gradient_stops(&g.stops)?; + check_gradient_stops(&g.opacity_stops)?; + } + } + // Linked patterns tile from the effects reference point (else the layer's top-left). + let anchor = layer.effects.reference.unwrap_or((f64::from(sb.x0), f64::from(sb.y0))); + let vector_shape = matches!(layer.content, LayerContent::Shape(_)) && !outline; + let map = |item: usize, map: usize| MapRef { fx, item, map }; + let rev: Vec<(usize, &'a Effect)> = items.iter().copied().enumerate().rev().collect(); + let init = |s: &mut Self, src: Slot, b: Option, kind: i32, opacity: f32| { + let mut p = Pass::new(Kernel::FxInit, 0); + p.a = Some(src); + p.b = b; + p.adjust_kind = kind; + p.opacity = opacity; + p.clip = Some(clip); + s.emit(p) + }; + + // Exterior effects over the backdrop (an opaque copy of it for clipped layers). + let mut w = if atop { + let b = self.retain(backdrop); + init(self, b, None, INIT_OPAQUE, 1.0) + } else { + self.retain(backdrop) + }; + for &(i, e) in &rev { + if let Effect::DropShadow(s) = e { + // The layer hides the shadow beneath it where its fill is see-through, and wholly + // in a mode that blends with it (as the CPU renderer: `shadow_see_through`). + let flags = if s.knocks_out { F_KNOCKOUT } else { 0 }; + let see_through = photocraft_compose::effects::shadow_see_through(layer); + w = self.paint_k( + w, + content, + Cov::Map(map(i, 0), 0.0), + &Paint::Color(s.color.to_rgb()), + s.common.blend, + s.common.opacity, + flags, + clip, + sb, + see_through, + ); + } + } + for &(i, e) in &rev { + if let Effect::OuterGlow(g) = e { + let paint = self.glow_paint(g, anchor); + // Match CPU exterior knockout: a see-through fill must not reveal the + // glow through its own shape. The shader applies m × (1 − alpha × k). + let see_through = 1.0 - layer.fill_opacity.clamp(0.0, 1.0); + w = self.paint_k(w, content, Cov::Map(map(i, 0), 0.0), &paint, g.common.blend, g.common.opacity, F_KNOCKOUT, clip, sb, see_through); + } + } + + // Only exterior effects (drop shadows, outer glows): nothing is painted between the + // layer's colour inside its shape and the shape's alpha, so the merge derives both from + // the shape (`F_LAYER_SHAPE`) instead of two passes building the layer. + let premerge = photocraft_compose::effects::premerges_layer(layer); + if !relative && !premerge && items.iter().all(|e| matches!(e, Effect::DropShadow(_) | Effect::OuterGlow(_))) { + let mut p = Pass::new(Kernel::FxMerge, 0); + p.a = Some(w); + p.b = Some(lay_src); + p.c = Some(self.retain(backdrop)); + p.mode = if layer.blend == BlendMode::PassThrough { BlendMode::Normal } else { layer.blend }; + p.opacity = layer.opacity; + p.flags = if atop { F_ATOP } else { 0 } | gamma_flag(layer) | F_LAYER_SHAPE; + p.params[0][0] = layer.fill_opacity; + p.extra[3] = photocraft_compose::text_gamma(layer); + p.clip = Some(clip); + let merged = self.emit(p); + self.release(content); + return Ok(self.write_back(backdrop, merged, clip)); + } + // The layer: its colour at fill opacity inside its shape; interior effects are painted + // relative to the shape (coverage within it), then the shape's alpha applies. + let mut l = if relative { + let c = self.retain(content); + init(self, lay_src, Some(c), INIT_RELATIVE, layer.fill_opacity) + } else { + init(self, lay_src, None, INIT_INSIDE, layer.fill_opacity) + }; + // Blend Interior Effects as Group off: the layer merges in its mode first and the + // interior effects paint over the result (`effects::premerges_layer`). + if premerge { + let mut p = Pass::new(Kernel::Blend, 0); + p.a = Some(self.retain(w)); + p.b = Some(l); + p.mode = layer.blend; + p.flags = gamma_flag(layer); + p.extra[3] = photocraft_compose::text_gamma(layer); + p.clip = Some(clip); + l = self.emit(p); + } + for &(_, e) in &rev { + if let Effect::PatternOverlay { common, name, id, scale, angle, link, phase } = e + && let Some(pat) = photocraft_doc::pattern::find(self.cx.patterns, id, name).filter(|p| p.is_paintable()) + { + let paint = Paint::Pattern(pat, placement(anchor, *link, *phase, *scale, *angle)); + l = self.paint(l, content, Cov::One, &paint, common.blend, common.opacity, F_GATE, clip, sb); + } + } + for &(_, e) in &rev { + if let Effect::GradientOverlay { common, gradient, .. } = e { + l = self.paint(l, content, Cov::One, &Paint::Gradient(gradient), common.blend, common.opacity, F_GATE, clip, sb); + } + } + for &(_, e) in &rev { + if let Effect::ColorOverlay { common, color } = e { + l = self.paint(l, content, Cov::One, &Paint::Color(color.to_rgb()), common.blend, common.opacity, F_GATE, clip, sb); + } + } + for &(i, e) in &rev { + if let Effect::Satin(s) = e { + l = self.paint(l, content, Cov::Map(map(i, 0), 0.0), &Paint::Color(s.color.to_rgb()), s.common.blend, s.common.opacity, F_REL, clip, sb); + } + } + for &(i, e) in &rev { + if let Effect::InnerGlow(g) = e { + let paint = self.glow_paint(g, anchor); + l = self.paint(l, content, Cov::Map(map(i, 0), 0.0), &paint, g.common.blend, g.common.opacity, F_REL, clip, sb); + } + } + for &(i, e) in &rev { + if let Effect::InnerShadow(s) = e { + l = self.paint(l, content, Cov::Map(map(i, 0), 0.0), &Paint::Color(s.color.to_rgb()), s.common.blend, s.common.opacity, F_REL, clip, sb); + } + } + if let Some(s) = vstroke { + let mut p = Pass::new(Kernel::FxInit, 0); + p.a = Some(l); + p.b = Some(self.retain(content)); + p.c = Some(s); + p.adjust_kind = INIT_VSTROKE; + p.opacity = layer.fill_opacity; + p.clip = Some(clip); + l = self.emit(p); + } + // Inside stroke parts are painted over the layer (bottom instance first). + for &(i, e) in &rev { + if let Effect::Stroke(st) = e { + let (in_w, _) = stroke_widths(st); + if in_w > 0.0 { + let paint = self.fx_paint(&st.paint, anchor); + l = self.paint( + l, + content, + Cov::Map(map(i, 1), (in_w + 0.5).clamp(0.0, 1.0)), + &paint, + st.common.blend, + st.common.opacity, + F_GATE, + clip, + photocraft_compose::stroke_frame(self.cx.doc, layer, st).unwrap_or(sb), + ); + } + } + } + let bevel_paint = |b: &photocraft_doc::Bevel| photocraft_compose::effects::bevel_geom(b).paint; + for &(i, e) in &rev { + if let Effect::BevelEmboss(b) = e + && bevel_paint(b) == photocraft_compose::effects::BevelPaint::Inner + { + l = self.paint( + l, + content, + Cov::Map(map(i, 0), 0.0), + &Paint::Color(b.highlight_color.to_rgb()), + b.highlight.blend, + b.highlight.opacity, + F_REL, + clip, + sb, + ); + l = self.paint(l, content, Cov::Map(map(i, 1), 0.0), &Paint::Color(b.shadow_color.to_rgb()), b.shadow.blend, b.shadow.opacity, F_REL, clip, sb); + } + } + // The shape's own alpha. + let c = self.retain(content); + l = init(self, l, Some(c), INIT_ALPHA, 1.0); + // Outside stroke parts lie beneath the layer and blend onto the exterior result with their + // own mode; a higher stroke covers the ones below it (each takes its coverage × opacity + // not yet taken above it, blended over the result as it was before the strokes). + let outs: Vec<(usize, &photocraft_doc::StrokeFx)> = items + .iter() + .copied() + .enumerate() + .filter_map(|(i, e)| if let Effect::Stroke(st) = e { Some((i, st)) } else { None }) + .filter(|(_, st)| stroke_widths(st).1 > 0.0) + .collect(); + if !outs.is_empty() { + let (mut acc, mut cover): (Option, Option) = (None, None); + if outline || !vector_shape { + // The layer's alpha rides along the coverage: `effects::outline_share`, and for + // pixel layers the stroke's share beneath a partly covering layer (fill < 100 %). + let ll = self.retain(l); + cover = Some(init(self, ll, None, INIT_COVER, 1.0)); + } + for (n, &(i, st)) in outs.iter().enumerate() { + let paint = self.fx_paint(&st.paint, anchor); + let flags = F_STROKE_OUT | if vector_shape { F_VECTOR } else { 0 } | if outline { F_OUTLINE } else { 0 } | if n == 0 { F_FIRST } else { 0 }; + // Share × blended colour, then coverage (both read the coverage so far). + let mut p = self.fx_pass_kernel( + Kernel::FxStroke, + w, + content, + &paint, + st.common.blend, + st.common.opacity, + flags, + clip, + photocraft_compose::stroke_frame(self.cx.doc, layer, st).unwrap_or(sb), + ); + if matches!(paint, Paint::None) { + // A missing pattern paints nothing: the stroke's share keeps the result as is. + p.params[2][2] = 3.0; + } + p.adjust_kind = 0; + p.map = Some(map(i, 0)); + p.c = cover.map(|c| self.retain(c)); + p.d = acc; + let a = self.emit(p); + // The stroke's mode rides along only for Dissolve, whose coverage is all or + // nothing in this pass as in the colour pass (#6995). + let mut p = self.fx_pass_kernel(Kernel::FxStroke, w, content, &Paint::Color([0.0; 3]), st.common.blend, st.common.opacity, flags, clip, sb); + p.adjust_kind = 1; + p.map = Some(map(i, 0)); + p.c = cover; + cover = Some(self.emit(p)); + acc = Some(a); + } + let mut p = Pass::new(Kernel::FxStrokeEnd, 0); + p.a = Some(w); + p.b = acc; + p.c = cover; + p.clip = Some(clip); + w = self.emit(p); + } + for &(i, e) in &rev { + if let Effect::BevelEmboss(b) = e + && bevel_paint(b) == photocraft_compose::effects::BevelPaint::Outer + { + let k = 0; + w = self.paint( + w, + content, + Cov::Map(map(i, k), 0.0), + &Paint::Color(b.highlight_color.to_rgb()), + b.highlight.blend, + b.highlight.opacity, + 0, + clip, + sb, + ); + w = self.paint(w, content, Cov::Map(map(i, k + 1), 0.0), &Paint::Color(b.shadow_color.to_rgb()), b.shadow.blend, b.shadow.opacity, 0, clip, sb); + } + } + + let mode = if premerge || layer.blend == BlendMode::PassThrough { BlendMode::Normal } else { layer.blend }; + let late: Vec<(usize, &'a photocraft_doc::Bevel)> = rev + .iter() + .filter_map(|&(i, e)| if let Effect::BevelEmboss(b) = e { Some((i, b)) } else { None }) + .filter(|(_, b)| bevel_paint(b) == photocraft_compose::effects::BevelPaint::Both) + .collect(); + let merged = if late.is_empty() { + let mut p = Pass::new(Kernel::FxMerge, 0); + p.a = Some(w); + p.b = Some(l); + p.c = Some(self.retain(backdrop)); + p.mode = mode; + p.opacity = layer.opacity; + p.flags = if atop { F_ATOP } else { 0 } | gamma_flag(layer); + p.extra[3] = photocraft_compose::text_gamma(layer); + p.clip = Some(clip); + self.emit(p) + } else { + // Emboss styles shade the composited layer (`composite_with_effects`): merge at full + // opacity, paint their maps (inside and outside halves), then mix. + let mut p = Pass::new(Kernel::FxMerge, 0); + p.a = Some(w); + p.b = Some(l); + p.c = Some(self.retain(w)); + p.mode = mode; + p.opacity = 1.0; + p.flags = gamma_flag(layer); + p.extra[3] = photocraft_compose::text_gamma(layer); + p.clip = Some(clip); + let mut m = self.emit(p); + for (i, b) in late { + for (k, color, fxc) in [(0, &b.highlight_color, &b.highlight), (1, &b.shadow_color, &b.shadow)] { + m = self.paint(m, content, Cov::Map(map(i, k), 0.0), &Paint::Color(color.to_rgb()), fxc.blend, fxc.opacity, 0, clip, sb); + } + } + let mut p = Pass::new(Kernel::FxMerge, 0); + p.b = Some(self.retain(m)); + p.a = Some(m); + p.c = Some(self.retain(backdrop)); + p.mode = mode; + p.opacity = layer.opacity; + p.flags = if atop { F_ATOP } else { 0 } | F_NO_LAYER; + p.clip = Some(clip); + self.emit(p) + }; + self.release(content); + + // Write the clipped result back into the backdrop (in place when nothing else holds it). + Ok(self.write_back(backdrop, merged, clip)) + } + + fn fx_paint(&self, p: &'a FxPaint, anchor: (f64, f64)) -> Paint<'a> { + match p { + FxPaint::Color(c) => Paint::Color(c.to_rgb()), + FxPaint::Gradient(g) => Paint::Gradient(g), + FxPaint::Pattern { name, id, scale } => match photocraft_doc::pattern::find(self.cx.patterns, id, name).filter(|p| p.is_paintable()) { + Some(pat) => Paint::Pattern(pat, placement(anchor, true, (0.0, 0.0), *scale, 0.0)), + None => Paint::None, + }, + } + } + + fn glow_paint(&self, g: &'a Glow, anchor: (f64, f64)) -> Paint<'a> { + match &g.paint { + FxPaint::Gradient(gradient) => Paint::GlowGradient(gradient, photocraft_compose::effects::glow_gradient_gain(g.range)), + p => self.fx_paint(p, anchor), + } + } + + /// An effect pass reading `dst` (A, retained) and the layer `content` (B, retained) with its + /// paint set up. + #[allow(clippy::too_many_arguments)] + fn fx_pass(&mut self, dst: Slot, content: Slot, paint: &Paint<'a>, blend: BlendMode, opacity: f32, flags: u32, clip: Rect, sb: Rect) -> Pass<'a> { + self.fx_pass_kernel(Kernel::FxPaint, dst, content, paint, blend, opacity, flags, clip, sb) + } + + #[allow(clippy::too_many_arguments)] + fn fx_pass_kernel( + &mut self, + kernel: Kernel, + dst: Slot, + content: Slot, + paint: &Paint<'a>, + blend: BlendMode, + opacity: f32, + flags: u32, + clip: Rect, + sb: Rect, + ) -> Pass<'a> { + let mut p = Pass::new(kernel, 0); + p.a = Some(self.retain(dst)); + p.b = Some(self.retain(content)); + p.mode = blend; + p.opacity = opacity; + p.flags = flags; + p.clip = Some(clip); + match paint { + Paint::None => {} + Paint::Color(c) => p.color = [c[0], c[1], c[2], 1.0], + Paint::Gradient(g) => { + // effects::paint_fx: whole-pixel end points (fill_layout::gradient_layout). + let (angle, scale, offset) = photocraft_compose::fill_layout::gradient_layout(g.style, g.angle, g.scale, g.offset, sb); + p.params[0] = [angle, scale, if g.reverse { 1.0 } else { 0.0 }, style_index(g.style)]; + p.params[1] = [sb.x0 as f32, sb.y0 as f32, sb.width() as f32, sb.height() as f32]; + p.params[2][0] = offset.0; + p.params[2][1] = offset.1; + p.params[2][2] = 1.0; + p.lut = Some(gradient_rows(g)); + } + Paint::GlowGradient(g, gain) => { + // effects::paint_glow: the gradient at 1 - strength, opaque from 1 / gain. + p.params[0][0] = *gain; + p.params[2][2] = 4.0; + p.lut = Some(gradient_rows(g)); + } + Paint::Pattern(pat, pl) => { + p.params[2][2] = 2.0; + p.params[3] = [pl.origin.0 as f32, pl.origin.1 as f32, pl.cs.0 as f32, pl.cs.1 as f32]; + p.extra = [pl.inv_scale as f32, pat.width as f32, pat.height as f32, 0.0]; + p.pattern = Some(pat); + } + } + p + } + + /// One effect paint into `dst` (consumed); reads the layer's alpha from `content` (kept). + #[allow(clippy::too_many_arguments)] + fn paint(&mut self, dst: Slot, content: Slot, cov: Cov, paint: &Paint<'a>, blend: BlendMode, opacity: f32, flags: u32, clip: Rect, sb: Rect) -> Slot { + self.paint_k(dst, content, cov, paint, blend, opacity, flags, clip, sb, 1.0) + } + + /// [`Self::paint`] with the knockout strength (`F_KNOCKOUT`: coverage × (1 − alpha × k)). + #[allow(clippy::too_many_arguments)] + fn paint_k( + &mut self, + dst: Slot, + content: Slot, + cov: Cov, + paint: &Paint<'a>, + blend: BlendMode, + opacity: f32, + flags: u32, + clip: Rect, + sb: Rect, + knockout: f32, + ) -> Slot { + if matches!(paint, Paint::None) { + // Missing pattern: compose paints nothing. + return dst; + } + let mut p = self.fx_pass(dst, content, paint, blend, opacity, flags, clip, sb); + self.release(dst); + match cov { + Cov::Map(m, outside) => { + p.adjust_kind = 0; + p.map = Some(m); + p.params[2][3] = outside; + } + Cov::One => p.adjust_kind = 1, + } + p.extra[3] = knockout; + self.emit(p) + } +} diff --git a/crates/gpu/src/plan/tests.rs b/crates/gpu/src/plan/tests.rs new file mode 100644 index 0000000000..283fe034de --- /dev/null +++ b/crates/gpu/src/plan/tests.rs @@ -0,0 +1,336 @@ +use super::*; +use photocraft_color::{Color, ColorMode, SampleType}; +use photocraft_geom::Size; + +#[test] +fn nested_pass_through_groups_with_clipped_layers_are_not_planned_exponentially() { + let mut layers = vec![Layer::raster("leaf", photocraft_color::PixelFormat::RGBA8)]; + for _ in 0..30 { + let group = Layer::group("g", layers); + let mut clipped = Layer::raster("c", photocraft_color::PixelFormat::RGBA8); + clipped.clipped = true; + layers = vec![group, clipped]; + } + let mut doc = Document::new("nest", Size::new(8, 8), ColorMode::Rgb, SampleType::U8); + doc.layers = layers; + let started = std::time::Instant::now(); + let Err(error) = plan(&doc) else { panic!("2^30 plannings must be refused") }; + assert!(error.0.contains("too many nested layers"), "{}", error.0); + assert!(started.elapsed().as_secs() < 10, "{:?}", started.elapsed()); +} + +#[test] +fn stops_closer_than_one_lut_step_stay_on_the_cpu() { + assert!(check_gradient_stops(&[(0.4999_f32, ()), (0.5, ())]).is_err()); + assert!(check_gradient_stops(&[(0.0_f32, ()), (1.0, ())]).is_ok()); +} + +#[test] +fn lab_channel_adjustments_defer_to_the_cpu_in_lab_documents() { + let lab_rules = [ + Adjustment::Invert, + Adjustment::Posterize { levels: 4 }, + Adjustment::Threshold { level: 0.5 }, + Adjustment::BrightnessContrast { brightness: 10.0, contrast: 5.0, legacy: false }, + Adjustment::GradientMap { stops: vec![(0.0, [0.0; 3]), (1.0, [1.0; 3])], reverse: false, dither: false }, + ]; + for adj in &lab_rules { + assert!(!adjustment_on_gpu(adj, ColorMode::Lab), "{adj:?}"); + for mode in [ColorMode::Rgb, ColorMode::Grayscale] { + assert!(adjustment_on_gpu(adj, mode), "{adj:?} in {mode:?}"); + } + // CMYK documents invert, posterize, threshold and brighten their inks, on the CPU. + let inks = !matches!(adj, Adjustment::GradientMap { .. }); + assert_eq!(adjustment_on_gpu(adj, ColorMode::Cmyk), !inks, "{adj:?} in CMYK"); + } + // CMYK Hue/Saturation works on the inks (on the CPU); Colorize stays on the screen colour. + let ranges = photocraft_doc::adjust::HueRange::defaults(); + let hue = |colorize| Adjustment::HueSaturation { hue: 30.0, saturation: 10.0, lightness: 0.0, colorize, ranges: ranges.clone() }; + assert!(!adjustment_on_gpu(&hue(false), ColorMode::Cmyk) && adjustment_on_gpu(&hue(true), ColorMode::Cmyk)); + assert!(adjustment_on_gpu(&hue(false), ColorMode::Rgb)); + // Screen-colour adjustments stay on the GPU in Lab documents. + assert!(adjustment_on_gpu(&Adjustment::Exposure { exposure: 1.0, offset: 0.0, gamma: 1.0 }, ColorMode::Lab)); +} + +#[test] +fn native_cmyk_fills_fall_back_only_without_a_valid_cache() { + use photocraft_doc::{FillCache, GradientStyle}; + for depth in photocraft_color::SampleType::ALL { + for fill in [Fill::Solid(Color::WHITE), Fill::gradient(vec![(0.0, Color::BLACK), (1.0, Color::WHITE)], 0.0, 1.0, GradientStyle::Linear, false)] { + let mut doc = Document::new("CMYK", photocraft_geom::Size::new(3, 2), photocraft_color::ColorMode::Cmyk, depth); + doc.layers.push(Layer::new("Fill", LayerContent::Fill(fill.clone()))); + assert!(plan(&doc).unwrap_err().0.contains("native CMYK fill")); + doc.layers[0].visible = false; + assert!(plan(&doc).is_ok()); + doc.layers[0].visible = true; + doc.layers[0].fill_cache = Some(FillCache { fill, surface: photocraft_raster::Surface::new(doc.pixel_format()) }); + assert!(plan(&doc).is_ok()); + doc.layers[0].fill_cache.as_mut().unwrap().fill = Fill::Solid(Color::TRANSPARENT); + assert!(plan(&doc).is_err()); + doc.mode = photocraft_color::ColorMode::Rgb; + assert!(plan(&doc).is_ok()); + } + } +} +#[test] +fn outer_glow_plan_knocks_out_see_through_fill() { + use photocraft_doc::{Contour, FxCommon, GlowSource, GlowTechnique}; + + for fill in [0.0, 0.4, 1.0] { + let mut d = Document::with_background("glow", Size::new(64, 64), ColorMode::Rgb, SampleType::U8, Color::WHITE); + let mut layer = Layer::raster("frame", d.pixel_format()); + layer.surface_mut().unwrap().fill_rect(Rect::new(16, 16, 48, 48), &[1.0, 0.0, 0.0, 1.0]); + layer.fill_opacity = fill; + layer.effects.items.push(Effect::OuterGlow(Glow { + common: FxCommon::new(BlendMode::Normal, 1.0), + paint: FxPaint::Color(Color::rgb(1.0, 1.0, 0.0)), + technique: GlowTechnique::Softer, + spread: 0.3, + size: 8.0, + contour: Contour::Linear, + anti_alias: false, + range: 0.5, + jitter: 0.0, + noise: 0.0, + source: GlowSource::Edge, + })); + d.layers.push(layer); + let planned = plan(&d).unwrap(); + let glow = planned + .passes + .iter() + .find(|pass| pass.kernel == Kernel::FxPaint && pass.flags & F_KNOCKOUT != 0 && pass.color[0] > 0.9 && pass.color[1] > 0.9 && pass.color[2] < 0.1) + .expect("outer glow paint pass"); + assert!((glow.extra[3] - (1.0 - fill)).abs() < 1e-6, "fill {fill}"); + } +} + +#[test] +fn color_lookup_with_an_overflowing_stored_size_uploads_no_table() { + for size in [1 << 22, u32::MAX] { + let a = Adjustment::ColorLookup { name: "x".into(), lut: Some(std::sync::Arc::new(vec![0.5; 24])), size, tetrahedral: false, dither: false }; + let (kind, _, rows) = adjustment_program(&a, Transfer::Srgb, SampleType::U8, photocraft_color::ColorMode::Rgb); + assert_eq!((kind, rows.is_none()), (0, true), "size {size}"); + } +} + +#[test] +fn root_checkpoints_have_only_one_live_input_and_keep_clips_whole() { + for mode in [BlendMode::Normal, BlendMode::PassThrough] { + let mut d = Document::with_background("t", Size::new(32, 24), ColorMode::Rgb, SampleType::U8, Color::WHITE); + let mut clip = Layer::new("clip", LayerContent::Fill(Fill::Solid(Color::rgba(0.2, 0.3, 0.7, 0.4)))); + clip.clipped = true; + let mut group = Layer::group( + "group", + vec![ + Layer::new("fill", LayerContent::Fill(Fill::Solid(Color::rgba(0.9, 0.1, 0.3, 0.6)))), + Layer::new("invert", LayerContent::Adjustment(Adjustment::Invert)), + ], + ); + group.blend = mode; + d.layers.extend([group, clip, Layer::new("top", LayerContent::Adjustment(Adjustment::Invert))]); + let plan = plan(&d).unwrap(); + assert_eq!(plan.checkpoints.iter().map(|c| c.layer_end).collect::>(), vec![1, 3, 4]); + for checkpoint in &plan.checkpoints { + let mut written = std::collections::HashSet::from([checkpoint.slot]); + for pass in &plan.passes[checkpoint.pass_end..] { + for input in [pass.a, pass.b, pass.c, pass.d].into_iter().flatten() { + assert!(written.contains(&input), "a suffix must not need another saved slot: {checkpoint:?}"); + } + written.insert(pass.dst); + } + assert!(written.contains(&plan.root)); + } + } +} + +#[test] +fn slots_are_recycled() { + let mut d = Document::with_background("t", Size::new(8, 8), ColorMode::Rgb, SampleType::U8, Color::WHITE); + for i in 0..10 { + d.layers.push(Layer::raster(format!("l{i}"), d.pixel_format())); + } + let p = plan(&d).unwrap(); + // Empty layers draw nothing: the clear and the background's one fused pass. + assert_eq!(p.passes.len(), 1 + 1); + for (i, l) in d.layers.iter_mut().skip(1).enumerate() { + l.surface_mut().unwrap().fill_rect(Rect::new(i as i32 % 4, 0, 4, 8), &[0.0, 0.0, 1.0, 1.0]); + } + let p = plan(&d).unwrap(); + assert!(p.slots <= 3, "{} slots", p.slots); + // The background, then each small layer blended over its bounds and copied back. + assert_eq!(p.passes.len(), 1 + 1 + 10 * 2); +} + +#[test] +fn small_layers_composite_only_over_their_bounds() { + let mut d = Document::with_background("t", Size::new(64, 64), ColorMode::Rgb, SampleType::U8, Color::WHITE); + let mut l = Layer::raster("small", d.pixel_format()); + l.surface_mut().unwrap().fill_rect(Rect::new(10, 12, 20, 30), &[1.0, 0.0, 0.0, 1.0]); + let mut group = Layer::group("g", vec![l]); + group.blend = BlendMode::Normal; + d.layers.push(group); + let p = plan(&d).unwrap(); + let r = Rect::new(10, 12, 20, 30); + // The group's content, its blend and the copy back are all limited to the layer. + assert!(p.passes.iter().filter(|p| matches!(p.kernel, Kernel::Content | Kernel::Blend)).skip(2).all(|p| p.clip == Some(r)), "{:?}", p.passes); + let last = p.passes.last().unwrap(); + assert_eq!((last.kernel, last.dst, last.clip), (Kernel::CopyRect, p.root, Some(r))); + // A layer that covers most of the canvas composites everywhere. + d.layers[1].children_mut().unwrap()[0].surface_mut().unwrap().fill_rect(Rect::new(0, 0, 60, 60), &[1.0, 0.0, 0.0, 1.0]); + let p = plan(&d).unwrap(); + assert!(p.passes.iter().all(|p| p.clip.is_none())); +} + +#[test] +fn effects_are_planned_in_place() { + let mut d = Document::with_background("t", Size::new(8, 8), ColorMode::Rgb, SampleType::U8, Color::WHITE); + let mut l = Layer::raster("fx", d.pixel_format()); + l.surface_mut().unwrap().fill_rect(Rect::new(2, 2, 5, 5), &[1.0, 0.0, 0.0, 1.0]); + l.effects.items.push(photocraft_doc::Effect::ColorOverlay { common: photocraft_doc::FxCommon::new(BlendMode::Normal, 1.0), color: Color::WHITE }); + l.effects.items.push(photocraft_doc::Effect::default_drop_shadow()); + d.layers.push(l); + let p = plan(&d).unwrap(); + assert_eq!(p.fx.len(), 1); + let m = photocraft_compose::effects::margin(&d.layers[1]); + assert_eq!(p.fx[0].region, Rect::new(2, 2, 5, 5).inflate(m).intersect(&d.bounds().inflate(m))); + // The effect region covers the whole canvas: the merged result is the backdrop, no copy. + assert!(p.fx[0].region.contains_rect(&d.bounds())); + let last = p.passes.last().unwrap(); + assert_eq!(last.kernel, Kernel::FxMerge); + assert_eq!(last.dst, p.root); + assert!(p.slots <= 6, "{} slots", p.slots); + // On a larger canvas the result lands back in the backdrop slot over the region only. + let mut big = Document::with_background("t", Size::new(64, 64), ColorMode::Rgb, SampleType::U8, Color::WHITE); + big.layers.push(d.layers[1].clone()); + let p = plan(&big).unwrap(); + assert!(!p.fx[0].region.contains_rect(&big.bounds())); + let last = p.passes.last().unwrap(); + assert_eq!((last.kernel, last.dst, last.clip), (Kernel::CopyRect, p.root, Some(p.fx[0].region))); +} + +#[test] +fn exterior_effects_merge_from_the_shape() { + // A drop shadow alone: the layer's pixels, the shadow, the merge. With an interior effect + // the layer is built in passes of its own (colour inside the shape, the overlay, alpha). + let mut d = Document::with_background("t", Size::new(8, 8), ColorMode::Rgb, SampleType::U8, Color::WHITE); + let mut l = Layer::raster("fx", d.pixel_format()); + l.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 8, 8), &[1.0, 0.0, 0.0, 0.5]); + l.fill_opacity = 0.7; + l.effects.items.push(photocraft_doc::Effect::default_drop_shadow()); + d.layers.push(l); + let p = plan(&d).unwrap(); + let fx: Vec = p.passes.iter().skip(2).map(|p| p.kernel).collect(); + assert_eq!(fx, [Kernel::Content, Kernel::FxPaint, Kernel::FxMerge], "{:?}", p.passes); + let merge = p.passes.last().unwrap(); + assert!(merge.flags & F_LAYER_SHAPE != 0); + assert_eq!(merge.params[0][0], 0.7); + d.layers[1].effects.items.push(photocraft_doc::Effect::ColorOverlay { common: photocraft_doc::FxCommon::new(BlendMode::Normal, 1.0), color: Color::WHITE }); + let p = plan(&d).unwrap(); + assert!(p.passes.iter().all(|p| p.flags & F_LAYER_SHAPE == 0)); + assert!(p.passes.iter().any(|p| p.kernel == Kernel::FxInit)); +} + +#[test] +fn opaque_fill_layers_skip_what_they_cover() { + let opaque = || Fill::gradient(vec![(0.0, Color::BLACK), (1.0, Color::WHITE)], 30.0, 1.0, photocraft_doc::GradientStyle::Linear, false); + let mut d = Document::with_background("t", Size::new(8, 8), ColorMode::Rgb, SampleType::U8, Color::WHITE); + for i in 0..4 { + // Small painted layers (empty ones plan no passes at all). + let mut l = Layer::raster(format!("l{i}"), d.pixel_format()); + l.surface_mut().unwrap().fill_rect(Rect::new(i, i, i + 2, i + 2), &[0.0, 0.0, 1.0, 1.0]); + d.layers.push(l); + } + d.layers.push(Layer::new("g", LayerContent::Fill(opaque()))); + let mut top = Layer::raster("top", d.pixel_format()); + top.clipped = true; + d.layers.push(top); + // Clear, then the fill and its clipped layer: the background and four rasters are skipped. + let skipped = plan(&d).unwrap().passes.len(); + let mut alone = d.clone(); + alone.layers.drain(..5); + assert_eq!(skipped, plan(&alone).unwrap().passes.len()); + // Anything that lets the layers below show through keeps them. + let see_through: [fn(&mut Layer); 6] = [ + |l| l.opacity = 0.99, + |l| l.fill_opacity = 0.5, + |l| l.blend = BlendMode::Multiply, + |l| l.visible = false, + |l| l.excluded_channels = 1, + |l| { + if let LayerContent::Fill(Fill::Gradient { opacity_stops, .. }) = &mut l.content { + opacity_stops.push((1.0, 0.5)); + } + }, + ]; + for (k, f) in see_through.iter().enumerate() { + let mut d2 = d.clone(); + f(&mut d2.layers[5]); + assert!(plan(&d2).unwrap().passes.len() > skipped, "case {k}: the layers below are planned"); + assert!(!photocraft_compose::occludes_below(&d2.layers[5], ColorMode::Rgb), "case {k}"); + } + let mut translucent = d.clone(); + translucent.layers[5].content = LayerContent::Fill(Fill::Solid(Color::rgba(1.0, 0.0, 0.0, 0.5))); + assert!(!photocraft_compose::occludes_below(&translucent.layers[5], ColorMode::Rgb)); + assert!(photocraft_compose::occludes_below(&d.layers[5], ColorMode::Rgb)); +} + +#[test] +fn blend_if_plans_on_the_gpu() { + let mut d = Document::with_background("t", Size::new(8, 8), ColorMode::Rgb, SampleType::U8, Color::WHITE); + let mut l = Layer::raster("bi", d.pixel_format()); + l.surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(0, 0, 4, 4), &[1.0, 0.0, 0.0, 1.0]); + l.blend_if.set(0, [photocraft_doc::BlendRange { black: [40, 40], white: [255, 255] }, photocraft_doc::BlendRange::FULL]); + d.layers.push(l.clone()); + let blend_if = |d: &Document| plan(d).unwrap().passes.iter().filter(|p| p.flags & F_BLEND_IF != 0).count(); + assert_eq!(blend_if(&d), 1); + // Clipped layers too. + l.clipped = true; + d.layers[1].blend_if = Default::default(); + d.layers.push(l); + assert_eq!(blend_if(&d), 1); + // Outside RGB, Grayscale and Duotone the setting round-trips without applying. + d.mode = ColorMode::Lab; + assert_eq!(blend_if(&d), 0); +} + +#[test] +fn blend_if_params_pack_every_range_exactly() { + let mut bi = photocraft_doc::BlendIf::default(); + bi.set(3, [photocraft_doc::BlendRange { black: [255, 255], white: [0, 1] }, photocraft_doc::BlendRange { black: [12, 200], white: [201, 254] }]); + let f: Vec = blend_if_params(&bi).iter().flatten().copied().collect(); + // Entry 3 (B), this layer then underlying; unset entries are full ranges. + assert_eq!(&f[12..16], &[255.0 * 256.0 + 255.0, 1.0, 12.0 * 256.0 + 200.0, 201.0 * 256.0 + 254.0]); + assert_eq!(&f[0..2], &[0.0, 255.0 * 256.0 + 255.0]); +} + +#[test] +fn advanced_blending_falls_back_to_the_cpu() { + use photocraft_doc::Knockout; + let mut d = Document::with_background("t", Size::new(8, 8), ColorMode::Rgb, SampleType::U8, Color::WHITE); + let mut l = Layer::raster("ko", d.pixel_format()); + l.surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(0, 0, 4, 4), &[1.0, 0.0, 0.0, 1.0]); + d.layers.push(l.clone()); + assert!(plan(&d).is_ok(), "defaults stay on the GPU"); + // Switches with nothing to act on (no effects, no clipped layers) stay on the GPU too. + d.layers[1].advanced.blend_interior = true; + d.layers[1].advanced.blend_clipped = false; + assert!(plan(&d).is_ok()); + d.layers[1].advanced.knockout = Knockout::Deep; + assert!(plan(&d).unwrap_err().0.contains("Advanced Blending")); + // Inside groups and clipping groups. + d.layers[1].advanced.knockout = Knockout::None; + let mut c = l.clone(); + c.clipped = true; + d.layers.push(c.clone()); + assert!(plan(&d).is_err(), "clipped layers blended individually"); + d.layers[1].advanced.blend_clipped = true; + assert!(plan(&d).is_ok()); + d.layers[2].advanced.knockout = Knockout::Shallow; + assert!(plan(&d).is_err(), "clipped knockout"); + d.layers.truncate(1); + let mut inner = l; + inner.advanced.knockout = Knockout::Shallow; + d.layers.push(Layer::group("g", vec![inner])); + assert!(plan(&d).is_err(), "knockout inside a group"); +} diff --git a/crates/gpu/src/plan/types.rs b/crates/gpu/src/plan/types.rs new file mode 100644 index 0000000000..e83fac8c8c --- /dev/null +++ b/crates/gpu/src/plan/types.rs @@ -0,0 +1,304 @@ +use super::*; + +/// Pipeline (fragment entry point) of a pass. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Kernel { + /// Transparent fill (no draw). + Clear, + Content, + Mask, + Blend, + /// `Content` then `Blend` in one pass: a plain layer's pixels blended straight onto A. + LayerBlend, + /// A run of consecutive `LayerBlend` passes drawn as one (never planned: the executor draws + /// it in their place, see `batch_runs`). + LayerBatch, + /// `LayerBatch` of a run whose layers all blend Normal without text gamma, outside Lab + /// documents (never planned: the executor picks it, see `batch_kernel`). + LayerBatchNormal, + Atop, + Adjust, + AdjMix, + Lerp, + /// Effect chain start: the layer at fill opacity, or an opaque copy of a clipping base. + FxInit, + /// Paint an effect through a coverage map (or the layer's alpha) into A. + FxPaint, + /// Layer + interior effects over the exterior result, then layer opacity against the backdrop. + FxMerge, + /// Outside strokes: accumulate one stroke's share (`kind` 0, premultiplied colour) or its + /// coverage (`kind` 1). + FxStroke, + /// Outside strokes: resolve the accumulated strokes over the exterior result. + FxStrokeEnd, + /// Copy slot A into `dst` (an existing slot) over the pass clip (no draw). + CopyRect, + /// Copy all of slot A into the fresh slot `dst` (no draw). + CopyFull, + // Effect-map kernels (single-channel targets over an effect region, see `fx`). + MShift, + MDilate, + MBlur, + MGlow, + MFinish, + MBevelH, + MBevelShade, + MStroke, + MBevelTex, +} + +impl Kernel { + /// Fragment entry point in `compose.wgsl` (`None` for copies and clears). + pub fn entry(self) -> Option<&'static str> { + Some(match self { + Kernel::Clear | Kernel::CopyRect | Kernel::CopyFull => return None, + Kernel::Content => "fs_content", + Kernel::Mask => "fs_mask", + Kernel::Blend => "fs_blend", + Kernel::LayerBlend => "fs_layerblend", + Kernel::LayerBatch => "fs_layerbatch", + Kernel::LayerBatchNormal => "fs_layerbatch_normal", + Kernel::Atop => "fs_atop", + Kernel::Adjust => "fs_adjust", + Kernel::AdjMix => "fs_adjmix", + Kernel::Lerp => "fs_lerp", + Kernel::FxInit => "fs_fxinit", + Kernel::FxPaint => "fs_fxpaint", + Kernel::FxMerge => "fs_fxmerge", + Kernel::FxStroke => "fs_fxstroke", + Kernel::FxStrokeEnd => "fs_fxstrokeend", + Kernel::MShift => "fs_mshift", + Kernel::MDilate => "fs_mdilate", + Kernel::MBlur => "fs_mblur", + Kernel::MGlow => "fs_mglow", + Kernel::MFinish => "fs_mfinish", + Kernel::MBevelH => "fs_mbevelh", + Kernel::MBevelShade => "fs_mbevelshade", + Kernel::MStroke => "fs_mstroke", + Kernel::MBevelTex => "fs_mbeveltex", + }) + } + + /// Kernels that write effect maps (R32F / R16F targets) rather than RGBA accumulators. + pub fn is_map(self) -> bool { + matches!( + self, + Kernel::MShift + | Kernel::MDilate + | Kernel::MBlur + | Kernel::MGlow + | Kernel::MFinish + | Kernel::MBevelH + | Kernel::MBevelShade + | Kernel::MStroke + | Kernel::MBevelTex + ) + } + + /// Every kernel with a pipeline. + pub const DRAWN: [Kernel; 24] = [ + Kernel::Content, + Kernel::Mask, + Kernel::Blend, + Kernel::LayerBlend, + Kernel::LayerBatch, + Kernel::LayerBatchNormal, + Kernel::Atop, + Kernel::Adjust, + Kernel::AdjMix, + Kernel::Lerp, + Kernel::FxInit, + Kernel::FxPaint, + Kernel::FxMerge, + Kernel::FxStroke, + Kernel::FxStrokeEnd, + Kernel::MShift, + Kernel::MDilate, + Kernel::MBlur, + Kernel::MGlow, + Kernel::MFinish, + Kernel::MBevelH, + Kernel::MBevelShade, + Kernel::MStroke, + Kernel::MBevelTex, + ]; +} + +/// Which resident texture a pass samples. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Role { + Content, + Mask, + /// A stroked shape's stroke alone (its fill uses `Content`). + Stroke, +} + +/// A surface the pass needs on the GPU. +#[derive(Clone, Debug)] +pub struct TexUse<'a> { + pub layer: LayerId, + pub role: Role, + pub surface: SurfaceRef<'a>, +} + +/// An effect map sampled by a pass: map `map` of enabled effect `item` of `plan.fx[fx]`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct MapRef { + pub fx: usize, + pub item: usize, + pub map: usize, +} + +#[derive(Clone, Debug)] +pub struct Pass<'a> { + pub kernel: Kernel, + pub dst: Slot, + pub a: Option, + pub b: Option, + pub c: Option, + /// A fourth slot, bound in place of `tex` (passes without layer pixels). + pub d: Option, + pub mode: BlendMode, + pub opacity: f32, + /// The layer's Fill where it isn't folded into `opacity`: the final blend of a plain layer + /// (`Kernel::Blend`), so the special eight can apply it inside the blend. 1 elsewhere. + pub fill: f32, + /// Layer pixels (raster / text / shape / smart cache / fill cache). + pub tex: Option>, + /// Colour outside `tex` (the surface's default pixel), the solid fill colour, or the effect + /// colour. + pub color: [f32; 4], + pub mask: Option>, + /// Adjustment kind (see `adjust` in compose.wgsl) and parameters; the coverage kind of an + /// effect paint. + pub adjust_kind: i32, + pub params: [[f32; 4]; 4], + pub extra: [f32; 4], + /// Extra shader flags (`F_KNOCKOUT`, …). + pub flags: u32, + /// 4096-entry LUT rows (Levels / Curves / Gradient map / gradient stops). + pub lut: Option>, + pub gradient: bool, + /// Effect map sampled by `FxPaint`. + pub map: Option, + /// Pattern painted by `FxPaint`. + pub pattern: Option<&'a Pattern>, + /// Only pixels inside this rect (document coordinates) are computed; the pass is skipped for + /// chunks it misses. Consumers of the slot must be clipped alike. + pub clip: Option, +} + +/// Pixels a pass samples: a surface of the document, or one derived from it on the CPU (a +/// combined pixel × vector mask, a shape's fill or stroke alone). +#[derive(Clone, Debug)] +pub enum SurfaceRef<'a> { + Doc(&'a Surface), + Derived(std::sync::Arc), +} + +impl SurfaceRef<'_> { + pub fn get(&self) -> &Surface { + match self { + SurfaceRef::Doc(s) => s, + SurfaceRef::Derived(s) => s, + } + } +} + +#[derive(Clone, Debug)] +pub struct MaskUse<'a> { + pub layer: LayerId, + pub surface: SurfaceRef<'a>, + pub density: f32, + pub default: f32, +} + +impl<'a> Pass<'a> { + pub(crate) fn new(kernel: Kernel, dst: Slot) -> Self { + Pass { + kernel, + dst, + a: None, + b: None, + c: None, + d: None, + mode: BlendMode::Normal, + opacity: 1.0, + fill: 1.0, + tex: None, + color: [0.0; 4], + mask: None, + adjust_kind: 0, + params: [[0.0; 4]; 4], + extra: [0.0; 4], + flags: 0, + lut: None, + gradient: false, + map: None, + pattern: None, + clip: None, + } + } +} + +/// Why a document can't be composited on the GPU (the caller falls back to the CPU compositor). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Unsupported(pub String); + +impl std::fmt::Display for Unsupported { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "GPU compositor: {}", self.0) + } +} + +impl std::error::Error for Unsupported {} + +/// A layer whose effects the plan renders: its maps are built (or reused) before the chunks run. +#[derive(Clone, Copy, Debug)] +pub struct FxLayer<'a> { + pub layer: &'a Layer, + /// Region the maps cover (`compose::effect_maps`). + pub region: Rect, + /// Layer bounds (gradients and linked patterns are laid out in them). + pub bounds: Rect, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Checkpoint { + /// First root layer included after occlusion pruning. + pub layer_start: usize, + /// Root layers below this boundary (including the complete clipping unit). + pub layer_end: usize, + /// Resume at this pass with `slot` restored. + pub pass_end: usize, + pub slot: Slot, +} + +/// Document-level inputs of a plan. +#[derive(Clone, Copy)] +pub struct DocCtx<'a> { + pub canvas: Rect, + pub transfer: Transfer, + pub light: GlobalLight, + pub patterns: &'a [Pattern], + /// Colour mode (channel restrictions name its channels). + pub mode: photocraft_color::ColorMode, + /// Sample depth (adjustment results are rounded to it). + pub depth: photocraft_color::SampleType, + /// The document (effect geometry the CPU computes, e.g. gradient stroke frames). + pub doc: &'a Document, +} + +impl<'a> DocCtx<'a> { + pub fn of(doc: &'a Document) -> Self { + DocCtx { + canvas: doc.bounds(), + transfer: Transfer::for_document(doc.mode, doc.depth), + light: doc.global_light, + patterns: &doc.patterns, + mode: doc.mode, + depth: doc.depth, + doc, + } + } +} diff --git a/crates/gpu/src/readback.rs b/crates/gpu/src/readback.rs new file mode 100644 index 0000000000..14dd73a831 --- /dev/null +++ b/crates/gpu/src/readback.rs @@ -0,0 +1,70 @@ +use super::textures::Stats; +use super::*; + +/// Blocking readback of a composite (native tests and tools). +#[cfg(not(target_arch = "wasm32"))] +pub fn render_to_vec(comp: &mut Compositor, device: &wgpu::Device, queue: &wgpu::Queue, doc: &Document, rect: Rect) -> Result, Unsupported> { + render_to_vec_stats(comp, device, queue, doc, rect).map(|(v, _)| v) +} + +/// [`render_to_vec`] plus the render's [`Stats`]. +#[cfg(not(target_arch = "wasm32"))] +pub fn render_to_vec_stats( + comp: &mut Compositor, + device: &wgpu::Device, + queue: &wgpu::Queue, + doc: &Document, + rect: Rect, +) -> Result<(Vec<[f32; 4]>, Stats), Unsupported> { + let rect = rect.intersect(&doc.bounds()); + let mut staging: Vec<(Rect, wgpu::Buffer, u32)> = Vec::new(); + let mut bpp = 16u32; + let stats = comp.render(device, queue, doc, rect, |enc, out| { + // Bytes per pixel of the accumulation format (Rgba32Float = 16, Rgba16Float = 8). + bpp = if out.texture.format() == wgpu::TextureFormat::Rgba32Float { 16 } else { 8 }; + let row = (out.rect.width() * bpp).div_ceil(256) * 256; + let buf = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("pc_readback"), + size: (row * out.rect.height()) as u64, + usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, + mapped_at_creation: false, + }); + enc.copy_texture_to_buffer( + wgpu::TexelCopyTextureInfo { texture: out.texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, + wgpu::TexelCopyBufferInfo { + buffer: &buf, + layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(row), rows_per_image: Some(out.rect.height()) }, + }, + wgpu::Extent3d { width: out.rect.width(), height: out.rect.height(), depth_or_array_layers: 1 }, + ); + staging.push((out.rect, buf, row)); + })?; + for (_, b, _) in &staging { + b.slice(..).map_async(wgpu::MapMode::Read, |_| {}); + } + match &comp.health { + Some(h) if !h.wait(device, None) => return Err(Unsupported(h.fault().map_or_else(|| "GPU device lost".into(), |f| f.to_string()))), + Some(_) => {} + None => { + let _ = device.poll(wgpu::PollType::Wait { submission_index: None, timeout: None }); + } + } + let w = rect.width() as usize; + let mut out = vec![[0.0f32; 4]; w * rect.height() as usize]; + for (r, b, row) in &staging { + let data = b.slice(..).get_mapped_range().map_err(|e| Unsupported(format!("GPU readback failed: {e:?}")))?; + for y in 0..r.height() as usize { + for x in 0..r.width() as usize { + let o = y * *row as usize + x * bpp as usize; + let px: [f32; 4] = if bpp == 16 { + std::array::from_fn(|i| f32::from_le_bytes([data[o + i * 4], data[o + i * 4 + 1], data[o + i * 4 + 2], data[o + i * 4 + 3]])) + } else { + std::array::from_fn(|i| half::f16::from_le_bytes([data[o + i * 2], data[o + i * 2 + 1]]).to_f32()) + }; + let (dx, dy) = ((r.x0 - rect.x0) as usize + x, (r.y0 - rect.y0) as usize + y); + out[dy * w + dx] = px; + } + } + } + Ok((out, stats)) +} diff --git a/crates/gpu/src/setup.rs b/crates/gpu/src/setup.rs new file mode 100644 index 0000000000..30d04d872e --- /dev/null +++ b/crates/gpu/src/setup.rs @@ -0,0 +1,480 @@ +use super::batch::tile_grid; +use super::consts::{ACC_FORMAT, CHUNK, CHUNK_UNIFORM, FX_BUDGET, MAP16, MAP32, OP_UNIFORM, PAGE, PATTERN_BUDGET, RESIDENT_BUDGET}; +use super::kit::{Kit, SHADER, tex_entry, uniform_entry}; +use super::paging::{cell_rect, field_reaches, first_error, grid_rects}; +use super::textures::{FxEntry, Resident, Tex, TexKind}; +use super::*; + +impl Compositor { + /// Create a compositor with the default accumulation format ([`ACC_FORMAT`]). + pub fn new(device: &wgpu::Device) -> Self { + Self::new_with_format(device, ACC_FORMAT) + } + + /// The accumulation format to use on `adapter`: `Rgba32Float` when it can be a render target, + /// else `Rgba16Float`. Some drivers (e.g. Intel Vulkan) don't support rendering to `Rgba32Float` + /// and would otherwise panic at render-pipeline creation. + pub fn preferred_acc_format(adapter: &wgpu::Adapter) -> wgpu::TextureFormat { + let feats = adapter.get_texture_format_features(wgpu::TextureFormat::Rgba32Float); + if feats.allowed_usages.contains(wgpu::TextureUsages::RENDER_ATTACHMENT) { wgpu::TextureFormat::Rgba32Float } else { wgpu::TextureFormat::Rgba16Float } + } + + /// [`Compositor::new_with_format`], but a shader or pipeline the driver can't build (e.g. a + /// D3D12 shader-compiler failure) is an `Err` instead of a panic, so the caller can fall back + /// to the CPU compositor. Where errors only arrive asynchronously (WebGPU), creation is assumed + /// to have worked. + pub fn try_new_with_format(device: &wgpu::Device, acc_format: wgpu::TextureFormat) -> Result { + match first_error(device, || Self::build(device, acc_format)) { + ((comp, None), None) => Ok(comp), + ((_, Some(e)), _) | (_, Some(e)) => Err(Unsupported(format!("couldn't build the compositor's pipelines: {e}"))), + } + } + + /// Create a compositor whose accumulation/render-target format is `acc_format`. Pass + /// `Rgba16Float` on adapters that can't render to `Rgba32Float` (e.g. some Intel Vulkan drivers), + /// which otherwise panics at render-pipeline creation. See `Compositor::preferred_acc_format`. + pub fn new_with_format(device: &wgpu::Device, acc_format: wgpu::TextureFormat) -> Self { + let (comp, error) = Self::build(device, acc_format); + if let Some(e) = error { + log::error!("GPU compositor: couldn't build its pipelines: {e}"); + } + comp + } + + /// The compositor and the first error raised building its (non-map) pipelines. They are + /// built in parallel, each inside its own error scope on the thread that builds it (wgpu's + /// scopes are per thread): on DX12, FXC compiles one shader at a time and the ~30 pipelines + /// took about 8 s on one core (#6419). + fn build(device: &wgpu::Device, acc_format: wgpu::TextureFormat) -> (Self, Option) { + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("pc_compose"), source: wgpu::ShaderSource::Wgsl(SHADER.into()) }); + let bgl0 = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("pc_compose_uniforms"), + entries: &[uniform_entry(0, CHUNK_UNIFORM), uniform_entry(1, OP_UNIFORM)], + }); + let bgl1 = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("pc_compose_textures"), + entries: &(0..8).map(tex_entry).collect::>(), + }); + let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("pc_compose"), + bind_group_layouts: &[Some(&bgl0), Some(&bgl1)], + immediate_size: 0, + }); + // `None` only for kernels without a fragment entry point, which are never drawn. + let pipeline = |k: Kernel, format: wgpu::TextureFormat| { + let entry = k.entry()?; + Some(device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some(entry), + layout: Some(&layout), + vertex: wgpu::VertexState { module: &module, entry_point: Some("vs"), buffers: &[], compilation_options: Default::default() }, + primitive: wgpu::PrimitiveState::default(), + depth_stencil: None, + multisample: wgpu::MultisampleState::default(), + fragment: Some(wgpu::FragmentState { + module: &module, + entry_point: Some(entry), + targets: &[Some(wgpu::ColorTargetState { format, blend: None, write_mask: wgpu::ColorWrites::ALL })], + compilation_options: Default::default(), + }), + multiview_mask: None, + cache: None, + })) + }; + // Effect maps render to R32Float / R16Float, which some adapters (e.g. GL without float + // render targets) can't: then layer effects use the CPU compositor and the rest stays here. + let keys = Kernel::DRAWN.iter().filter(|k| !k.is_map()).map(|&k| (k, acc_format)); + let keys: Vec<_> = keys.chain(Kernel::DRAWN.iter().filter(|k| k.is_map()).flat_map(|&k| [(k, MAP32), (k, MAP16)])).collect(); + let built = fx::par_map(keys, |key| { + let (built, error) = first_error(device, || pipeline(key.0, key.1)); + (key, built, error) + }); + let (mut pipelines, mut maps) = (HashMap::new(), Vec::new()); + let (mut error, mut map_error) = (None, None); + for (key, built, e) in built { + let map = key.0.is_map(); + // A failed map pipeline turns all effect maps off below. A failed non-map pipeline + // keeps its (invalid) handle: draws look pipelines up by key, so dropping it would + // turn a validation error into a missing-key panic on the first draw. + if let Some(e) = e { + if map { + map_error.get_or_insert(e); + continue; + } + error.get_or_insert(e); + } + let Some(p) = built else { continue }; + if map { + maps.push((key, p)); + } else { + pipelines.insert(key, p); + } + } + if let Some(e) = &map_error { + log::info!("GPU compositor: no effect-map pipelines ({e}); layer effects use the CPU"); + } else { + pipelines.extend(maps); + } + let dummy = Tex::new(device, "pc_compose_dummy", 1, 1, wgpu::TextureFormat::Rgba8Unorm, wgpu::TextureUsages::TEXTURE_BINDING).view; + let comp = Self { + kit: Kit { pipelines, bgl0, bgl1, dummy }, + pool: Vec::new(), + residents: HashMap::new(), + fx: HashMap::new(), + prefix: prefix::Prefix::default(), + temps: Vec::new(), + patterns: HashMap::new(), + pattern_mode: photocraft_color::ColorMode::Rgb, + pattern_doc: DocId(0), + pattern_budget: PATTERN_BUDGET, + max_dim: 0, + device_max: device.limits().max_texture_dimension_2d, + page: PAGE, + chunk: CHUNK, + resident_budget: RESIDENT_BUDGET, + fx_budget: (FX_BUDGET as u64).saturating_sub(prefix::MAX_BYTES), + layer_need: 0, + lent: 0, + exact_resident: false, + focus: None, + frame: 0, + stamp: 0, + staged: 0, + recorded: 0, + layer_alloc: None, + admit_freed: 0, + fail_allocs: 0, + acc_format, + effect_maps: map_error.is_none(), + cmyk: 0, + health: None, + timer: None, + } + .with_texture_limit(device.limits().max_texture_dimension_2d); + (comp, error) + } + + fn with_texture_limit(mut self, max: u32) -> Self { + self.set_texture_limit(max); + self + } + + /// Plan paging for a texture side limit of `max` (clamped to the device's own limit and at + /// least one tile). Tests use a small limit to exercise documents larger than it on any + /// adapter. Drops every cached texture. + pub fn set_texture_limit(&mut self, max: u32) { + let tile = TILE_SIZE as u32; + self.max_dim = max.min(self.device_max).max(tile); + let mut page = tile; + while page * 2 <= self.max_dim.min(PAGE) { + page *= 2; + } + self.page = page; + self.chunk = CHUNK.min(page); + self.prefix.set_step(self.chunk); + self.pool.clear(); + self.residents.clear(); + self.fx.clear(); + self.temps.clear(); + self.prefix.clear(); + } + + /// The page side layer surfaces are stored in. + pub fn page_size(&self) -> u32 { + self.page + } + + /// Test hook: the next `n` layer page textures fail as if the device were out of memory + /// (a real one can't be forced), so the fallback paths of #6563 can be tested. + #[doc(hidden)] + pub fn fail_layer_allocs(&mut self, n: u32) { + self.fail_allocs = n; + } + + /// Set the GPU memory resident layer pages may hold (default [`RESIDENT_BUDGET`]), exactly: + /// nothing is lent to it ([`Self::fit_layers`]) until the next [`Self::set_memory_budget`]. + pub fn set_resident_budget(&mut self, bytes: u64) { + // The loan goes back to the effect maps, so the total budget stays what it was. + self.fx_budget = self.fx_budget.saturating_add(self.lent); + self.lent = 0; + self.resident_budget = bytes; + self.exact_resident = true; + } + + /// Set the GPU memory the compositor may hold for layer pages and caches together + /// (a quarter of it, at most [`FX_BUDGET`], for effect maps and lower-stack chunks). Uploads and evicted pages in + /// flight during a refresh stay within about a quarter more. + pub fn set_memory_budget(&mut self, bytes: u64) { + let caches = (FX_BUDGET as u64).min(bytes / 4); + self.prefix.set_budget((caches / 2).min(prefix::MAX_BYTES)); + self.fx_budget = caches.saturating_sub(self.prefix.budget()); + self.resident_budget = bytes.saturating_sub(caches); + self.lent = 0; + self.exact_resident = false; + self.lend(); + } + + /// Record that a render needs `needed` bytes of layer pages and return the resident budget + /// they now have. A render of the `whole` document sets the need; a part of it only raises + /// it, so a large partial refresh never shrinks what the next full one keeps resident. + /// + /// Pages that miss their share by less than the effect-map share borrow from it: an evicted + /// effect map is rebuilt by the next refresh that draws it, but one page too many sends the + /// whole refresh to the CPU compositor, 10× slower (#5973, P60: 150 layers of 6 MP on an + /// integrated GPU missed by 5 % and took 680 ms instead of 62). + /// The lower-stack share is never lent: it is what keeps a mid-stack edit at half the work. + /// The loan holds across [`Self::set_memory_budget`] until a later call needs less or more. + pub fn fit_layers(&mut self, needed: u64, whole: bool) -> u64 { + self.layer_need = if whole { needed } else { self.layer_need.max(needed) }; + self.lend(); + self.resident_budget + } + + /// Return the loan to the effect maps, then lend what [`Self::layer_need`] still lacks, if + /// the effect-map share covers it (lending part of it would fit nothing and only evict maps). + fn lend(&mut self) { + self.fx_budget = self.fx_budget.saturating_add(self.lent); + self.resident_budget = self.resident_budget.saturating_sub(self.lent); + let short = self.layer_need.saturating_sub(self.resident_budget); + self.lent = if short <= self.fx_budget && !self.exact_resident { short } else { 0 }; + self.fx_budget = self.fx_budget.saturating_sub(self.lent); + self.resident_budget = self.resident_budget.saturating_add(self.lent); + } + + /// The budget of layer pages, effect maps and lower-stack chunks (bytes). + pub fn memory_budget(&self) -> u64 { + self.resident_budget.saturating_add(self.fx_budget).saturating_add(self.prefix.budget()) + } + + /// Bytes held by reusable lower-stack chunks, within the overall cache allowance. + pub fn composite_cache_bytes(&self) -> u64 { + self.prefix.bytes() + } + + /// Cap lower-stack reuse (default at most 512 MiB); zero disables it. The released allowance + /// goes back to effect maps, preserving the total budget and layer-page allowance. + pub fn set_composite_cache_budget(&mut self, bytes: u64) { + let caches = self.fx_budget.saturating_add(self.prefix.budget()); + self.prefix.set_budget(bytes.min(caches)); + self.fx_budget = caches.saturating_sub(self.prefix.budget()); + } + + /// Bytes of the layer pages a render of `region` needs resident (each layer and mask + /// surface's tiles within the region's page cells, in their texture format). + pub fn working_set(&self, doc: &Document, region: Rect) -> u64 { + let Ok(plan) = plan(doc) else { return 0 }; + let grid = tile_grid(doc.bounds()); + let cells = grid_rects(region.intersect(&doc.bounds()), self.page) + .into_iter() + .map(|r| cell_rect((r.x0.div_euclid(self.page as i32), r.y0.div_euclid(self.page as i32)), self.page)) + .fold(Rect::EMPTY, |a, c| if a.is_empty() { c } else { a.union(&c) }); + let mut seen = std::collections::HashSet::new(); + let mut total = 0u64; + for p in &plan.passes { + let sources = [p.tex.as_ref().map(|t| (t.layer, t.role, t.surface.get())), p.mask.as_ref().map(|m| (m.layer, Role::Mask, m.surface.get()))]; + for (layer, role, s) in sources.into_iter().flatten() { + if seen.insert((layer, role)) { + let a = s.tile_bounds().intersect(&grid).intersect(&cells); + total += a.width() as u64 * a.height() as u64 * TexKind::for_surface(role, s.format()).bytes_per_pixel() as u64; + } + } + } + total + } + + /// The GPU memory resident layer pages may hold (bytes; see [`Compositor::set_memory_budget`]). + pub fn resident_budget(&self) -> u64 { + self.resident_budget + } + + /// Whether a render of `region` keeps every layer page it needs within the budget; when it + /// doesn't, each render re-uploads what was evicted. + pub fn fits_budget(&self, doc: &Document, region: Rect) -> bool { + self.working_set(doc, region) <= self.resident_budget + } + + /// The document area the view shows (`None`: unknown). Full refreshes draw its cells last. + pub fn set_focus(&mut self, focus: Option) { + self.focus = focus; + } + + /// GPU memory held by resident layer pages (bytes). + pub fn resident_bytes(&self) -> u64 { + self.residents.values().map(Resident::bytes).sum() + } + + /// GPU memory held by cached pattern textures (bytes). + pub fn pattern_cache_bytes(&self) -> u64 { + self.patterns.values().map(|p| p.bytes).sum() + } + + /// Set the GPU memory pattern textures may hold (default [`PATTERN_BUDGET`]). It takes effect + /// at the end of the next refresh. + pub fn set_pattern_budget(&mut self, bytes: u64) { + self.pattern_budget = bytes; + } + + /// Whether `doc` can be composited on the GPU. Documents and layers larger than the texture + /// limit are fine: surfaces are stored in page-sized textures and effect maps of regions + /// larger than the limit are built per page cell. + pub fn supports(&self, doc: &Document) -> Result<(), Unsupported> { + let p = plan(doc)?; + self.check_fx(doc, &p) + } + + /// Whether the maps of an effect region are built per page cell (it exceeds the limit). + pub(crate) fn fx_paged(&self, region: Rect) -> bool { + region.width() > self.max_dim || region.height() > self.max_dim + } + + /// How far beyond a page cell the effect maps of `f` must be computed to be exact in it. + pub(crate) fn fx_apron(doc: &Document, f: &plan::FxLayer<'_>) -> i32 { + let vector_shape = matches!(f.layer.content, LayerContent::Shape(_)) && photocraft_compose::effect_outline(f.layer).is_none(); + let progs: Vec = f + .layer + .effects + .items + .iter() + .filter(|e| e.enabled()) + .map(|e| fx::program_with(e, &doc.global_light, vector_shape, &doc.patterns, (0.0, 0.0))) + .collect(); + let want = field_reaches(&progs); + // Distance fields are exact one pixel inside the window they are computed from. + progs.iter().map(|p| p.reach(&|k| want.get(&k).copied().unwrap_or(0))).max().unwrap_or(0).saturating_add(2) + } + + /// Effect maps must fit in textures (per page cell when the region exceeds the limit), and + /// patterns in one texture. + pub(crate) fn check_fx(&self, doc: &Document, p: &Plan<'_>) -> Result<(), Unsupported> { + if !self.effect_maps && !p.fx.is_empty() { + return Err(Unsupported("layer effects need float effect-map render targets, which this GPU lacks".into())); + } + for f in &p.fx { + if self.fx_paged(f.region) { + let side = i64::from(self.page) + 2 * i64::from(Self::fx_apron(doc, f)); + if side > i64::from(self.device_max) { + return Err(Unsupported(format!("effects of `{}` reach too far to build per page", f.layer.name))); + } + } + for e in f.layer.effects.items.iter().filter(|e| e.enabled()) { + // Effect noise is speckled in the CPU maps; keep CPU and GPU identical by + // rendering noise-carrying effects on the CPU path. + let noisy = match e { + photocraft_doc::Effect::DropShadow(s) | photocraft_doc::Effect::InnerShadow(s) => s.noise > 0.0, + photocraft_doc::Effect::OuterGlow(g) | photocraft_doc::Effect::InnerGlow(g) => g.noise > 0.0, + _ => false, + }; + if noisy { + return Err(Unsupported(format!("effect noise on `{}` uses the CPU path", f.layer.name))); + } + for s in fx::program_with(e, &doc.global_light, false, &doc.patterns, (0.0, 0.0)).stages { + if s.lut.as_ref().is_some_and(|l| l.len() > 4096) { + return Err(Unsupported(format!("effect blur on `{}` too wide for the GPU path", f.layer.name))); + } + } + } + } + for pass in &p.passes { + if let Some(pat) = pass.pattern + && (pat.width > self.device_max || pat.height > self.device_max) + { + return Err(Unsupported(format!("pattern `{}` larger than the GPU texture limit", pat.name))); + } + } + Ok(()) + } + + /// Drop GPU textures of a closed document. + pub fn forget_doc(&mut self, doc: DocId) { + self.residents.retain(|_, r| r.doc != doc); + self.fx.retain(|_, e| e.doc != doc); + self.patterns.retain(|_, p| p.doc != doc); + self.prefix.forget(doc); + } + + /// [`Self::forget_doc`] for every document `keep` rejects: what the compositor holds for + /// documents that were closed, however their canvas entry went (#4529). + pub fn retain_docs(&mut self, keep: impl Fn(DocId) -> bool) { + let mut gone: Vec = self + .residents + .values() + .map(|r| r.doc) + .chain(self.fx.values().map(|e| e.doc)) + .chain(self.patterns.values().map(|p| p.doc)) + .chain(self.prefix.doc()) + .filter(|d| !keep(*d)) + .collect(); + gone.sort_by_key(|d| d.0); + gone.dedup(); + for d in gone { + self.forget_doc(d); + } + } + + /// Documents the compositor holds pages, effect maps, pattern textures or a lower-stack + /// composite for. + pub fn held_docs(&self) -> Vec { + let mut docs: Vec = self + .residents + .values() + .map(|r| r.doc) + .chain(self.fx.values().map(|e| e.doc)) + .chain(self.patterns.values().map(|p| p.doc)) + .chain(self.prefix.doc()) + .collect(); + docs.sort_by_key(|d| d.0); + docs.dedup(); + docs + } + + /// GPU memory held by cached effect maps (bytes). + pub fn fx_cache_bytes(&self) -> usize { + self.fx.values().map(FxEntry::bytes).sum() + } + + /// Watch `health` (see [`DeviceHealth::watch`]): once the device is lost or reported an + /// error, every render returns [`Unsupported`] without touching the GPU, so callers use the + /// CPU compositor instead. + pub fn set_health(&mut self, health: DeviceHealth) { + self.health = Some(health); + } + + /// Why the device can't be used (`None` while healthy or unwatched). + pub fn fault(&self) -> Option { + self.health.as_ref().and_then(DeviceHealth::fault) + } + + /// Measure how long the GPU spends executing each [`Compositor::render`], with timestamp + /// queries read back asynchronously (nothing waits for the GPU). Returns whether the device + /// supports it: without [`timing::FEATURES`] there is no measurement at all, and callers + /// report no GPU time rather than the encode-and-submit cost `composite_ms` already is. + /// + /// A measurement arrives a frame or two after the refresh it belongs to, so it carries that + /// refresh's own pixel count; take it with [`Compositor::take_gpu_timing`]. + pub fn measure_gpu_time(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) -> bool { + // `PHOTOCRAFT_NO_GPU_TIMING` turns it off: a kill switch for a driver whose timestamp + // queries misbehave, and the control arm for measuring what the queries themselves + // cost — the device is identical either way, so only the instrumentation varies. + if std::env::var_os("PHOTOCRAFT_NO_GPU_TIMING").is_some() { + return false; + } + if self.timer.is_none() { + self.timer = timing::GpuTimer::new(device, queue); + } + self.timer.is_some() + } + + /// Whether [`Compositor::measure_gpu_time`] is on for this compositor. + pub fn measures_gpu_time(&self) -> bool { + self.timer.is_some() + } + + /// The most recent finished GPU measurement, leaving none behind (a stale number is never + /// reported twice as new). `None` while unmeasured, unsupported, or still in flight. + /// + /// [`Compositor::render`] already drains this into [`Stats::gpu_time`], so the app never + /// calls it; it is how a bench or a test collects a measurement without issuing another + /// render to carry it. + pub fn take_gpu_timing(&mut self) -> Option { + self.timer.as_mut().and_then(timing::GpuTimer::take) + } +} diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs new file mode 100644 index 0000000000..281c67421e --- /dev/null +++ b/crates/gpu/src/tests.rs @@ -0,0 +1,390 @@ +use super::*; + +/// A run joins `LayerBlend` passes that only feed each other, at most `BATCH` of them, and +/// never ends in the slot it reads from. +fn check_runs(p: &Plan<'_>) -> Vec { + let runs = batch_runs(p); + assert_eq!(runs.len(), p.passes.len()); + for (i, &k) in runs.iter().enumerate() { + assert!((1..=BATCH).contains(&k), "pass {i}: run {k}"); + if k > 1 { + assert_ne!(Some(p.passes[i + k - 1].dst), p.passes[i].a, "run at {i} renders into its input"); + for j in i + 1..i + k { + assert_eq!(p.passes[j].kernel, Kernel::LayerBlend); + assert_eq!(p.passes[j].a, Some(p.passes[j - 1].dst), "run at {i}: pass {j} doesn't read the one before"); + assert!(p.passes[j].mask.is_none() && p.passes[j].mode != photocraft_color::BlendMode::Dissolve, "run at {i}: pass {j}"); + } + } + } + runs +} + +#[test] +fn plain_layers_batch_and_runs_stop_where_a_pass_must_stand_alone() { + use photocraft_color::{BlendMode, Color, ColorMode, SampleType}; + use photocraft_doc::{Document, Layer, LayerMask}; + let mut d = Document::with_background("t", photocraft_geom::Size::new(8, 8), ColorMode::Rgb, SampleType::U8, Color::WHITE); + for i in 0..12 { + let mut l = Layer::raster(format!("l{i}"), d.pixel_format()); + l.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 8, 8), &[0.2, 0.4, 0.6, 0.5]); + d.layers.push(l); + } + let p = plan::plan(&d).unwrap(); + let runs = check_runs(&p); + assert!(runs.iter().any(|k| *k >= 3), "{runs:?}"); + // The cache resumes only where a run starts, so a cached render draws the passes above + // its checkpoint in the same runs as an uncached one; checkpoints inside a run are + // skipped, but a stack of plain layers keeps some to resume at. + let starts = run_starts(&runs); + assert_eq!(starts.len(), runs.len() + 1); + assert!(starts[0] && starts[runs.len()]); + let (mut at, mut i) = (Vec::new(), 0); + while i < runs.len() { + at.push(i); + i += runs[i]; + } + assert_eq!(starts.iter().enumerate().filter(|(_, s)| **s).map(|(i, _)| i).collect::>(), [at, vec![runs.len()]].concat()); + let resumable = p.checkpoints.iter().filter(|c| c.pass_end > 1 && starts[c.pass_end]).count(); + assert!(resumable >= 2 && resumable < p.checkpoints.len(), "{resumable} of {:?}", p.checkpoints); + // A masked or Dissolve layer, or a clipped one, never joins a run as an extra layer. + d.layers[3].mask = Some(LayerMask::hide_all()); + d.layers[6].blend = BlendMode::Dissolve; + d.layers[9].clipped = true; + check_runs(&plan::plan(&d).unwrap()); + // Nothing to batch: a lone layer. + d.layers.truncate(1); + assert_eq!(check_runs(&plan::plan(&d).unwrap()), vec![1; plan::plan(&d).unwrap().passes.len()]); +} + +#[test] +fn batch_records_hold_three_extra_layers_in_the_spare_words() { + let lead = plan::Pass::new(Kernel::LayerBlend, 0); + let mut x = plan::Pass::new(Kernel::LayerBlend, 1); + x.opacity = 0.25; + x.fill = 0.5; + x.color = [0.1, 0.2, 0.3, 0.4]; + let w = batch_op_words(&lead, None, None, &[(&x, Some([1, 2, 3, 4])), (&x, None), (&x, None), (&x, None)]); + assert_eq!(w.len() as u64, OP_UNIFORM); + let word = |i: usize| <[u8; 4]>::try_from(&w[i * 4..i * 4 + 4]).unwrap(); + let f = |i: usize| f32::from_le_bytes(word(i)); + // At most three extras; the first's geometry, colour and parameters in p0, p1, p2. + assert_eq!(i32::from_le_bytes(word(1)), 3); + assert_eq!([f(20), f(21), f(22), f(23)], [1.0, 2.0, 3.0, 4.0]); + assert_eq!([f(24), f(25), f(26), f(27)], [0.1, 0.2, 0.3, 0.4]); + assert_eq!([f(28), f(29), f(31)], [0.25, 0.5, 1.0]); + // The third's parameters in q4; one without pixels says so. + assert_eq!([f(60), f(61), f(63)], [0.25, 0.5, 0.0]); + // Other passes leave the batch words zero. + let plain = op_words(&x, None, None, None); + assert!(plain[44 * 4..].iter().all(|b| *b == 0)); +} + +#[test] +fn runs_of_normal_layers_draw_with_normal_code_alone() { + use photocraft_color::BlendMode; + let pass = |mode: BlendMode, flags: u32| { + let mut p = plan::Pass::new(Kernel::LayerBlend, 0); + p.mode = mode; + p.flags = flags; + p + }; + let normal = pass(BlendMode::Normal, plan::F_HDR); + assert_eq!(batch_kernel(&[normal.clone(), pass(BlendMode::Normal, 0)]), Kernel::LayerBatchNormal); + // Any other mode, text gamma or a Lab document anywhere in the run takes the full shader. + for other in [pass(BlendMode::Multiply, 0), pass(BlendMode::Dissolve, 0), pass(BlendMode::Normal, plan::F_TEXT_GAMMA), pass(BlendMode::Normal, plan::F_LAB)] + { + assert_eq!(batch_kernel(&[normal.clone(), other.clone()]), Kernel::LayerBatch); + assert_eq!(batch_kernel(&[other, normal.clone()]), Kernel::LayerBatch); + } +} + +#[test] +fn layer_pages_are_admitted_by_evicting_least_recently_used_first() { + let pages = || vec![(5, 'c', 40), (1, 'a', 30), (3, 'b', 20)]; + // Fits already: nothing dropped. + assert!(lru_victims(pages(), 90, 10, 100).is_empty()); + // 90 held + 40 incoming over 100: the oldest page goes first, then the next. + assert_eq!(lru_victims(pages(), 90, 40, 100), vec!['a']); + assert_eq!(lru_victims(pages(), 90, 60, 100), vec!['a', 'b']); + // Out of memory: a zero budget drops every candidate, and an impossible request stops + // when none are left instead of looping or overflowing. + assert_eq!(lru_victims(pages(), 90, 0, 0), vec!['a', 'b', 'c']); + assert_eq!(lru_victims(pages(), u64::MAX, u64::MAX, 1), vec!['a', 'b', 'c']); + assert!(lru_victims(Vec::<(u64, char, u64)>::new(), 90, 40, 100).is_empty()); +} + +#[test] +fn uniform_buffer_sizes_are_checked_before_allocation() { + assert_eq!(uniform_buffer_len(1, 255, 65_536).unwrap(), 65_536); + assert!(uniform_buffer_len(1, 255, 65_535).is_err()); + assert!(uniform_buffer_len(usize::MAX, 1, u64::MAX).is_err()); + assert!(uniform_buffer_len(usize::MAX, 0, u64::MAX).is_err()); + assert!(uniform_buffer_len(1, 16_777_216, u64::MAX).is_err(), "the last record offset cannot be represented by u32"); + #[cfg(target_pointer_width = "64")] + assert_eq!(uniform_buffer_len(1, 16_777_215, u64::MAX).unwrap(), 4_294_967_296, "the last valid u32 dynamic offset is accepted"); +} + +#[test] +fn half_roundtrip() { + for v in [0.0f32, 1.0, 0.5, 0.25, 1.0 / 255.0, 0.333, 65504.0, -2.5, 1e-6] { + let r = f16_to_f32(f32_to_f16(v)); + assert!((r - v).abs() <= v.abs() / 1024.0 + 1e-7, "{v} -> {r}"); + } +} + +#[test] +fn shader_validates() { + let module = wgpu::naga::front::wgsl::parse_str(SHADER).unwrap_or_else(|e| panic!("{}", e.emit_to_string(SHADER))); + wgpu::naga::valid::Validator::new(wgpu::naga::valid::ValidationFlags::all(), wgpu::naga::valid::Capabilities::empty()) + .validate(&module) + .unwrap_or_else(|e| panic!("{e:?}")); + for k in Kernel::DRAWN { + let e = k.entry().unwrap(); + assert!(module.entry_points.iter().any(|ep| ep.name == e), "missing entry point {e}"); + } +} + +/// The decimal float literals in `src` (comments skipped; hex literals are exact, so skipped), +/// with their line numbers. +fn decimal_float_literals(src: &str) -> Vec<(usize, String)> { + let mut out = Vec::new(); + for (n, line) in src.lines().enumerate() { + let code = line.split("//").next().unwrap_or("").as_bytes(); + let mut i = 0; + while i < code.len() { + let digit_or_dot = code[i].is_ascii_digit() || (code[i] == b'.' && code.get(i + 1).is_some_and(u8::is_ascii_digit)); + let word_before = i > 0 && (code[i - 1].is_ascii_alphanumeric() || code[i - 1] == b'_' || code[i - 1] == b'.'); + if !digit_or_dot || word_before { + i += 1; + continue; + } + if code[i] == b'0' && matches!(code.get(i + 1), Some(b'x' | b'X')) { + i += 2; + while i < code.len() && (code[i].is_ascii_hexdigit() || matches!(code[i], b'.' | b'p' | b'P' | b'+' | b'-')) { + i += 1; + } + continue; + } + let start = i; + while i < code.len() && (code[i].is_ascii_digit() || code[i] == b'.') { + i += 1; + } + if i < code.len() && matches!(code[i], b'e' | b'E') { + let mut j = i + 1; + if j < code.len() && matches!(code[j], b'+' | b'-') { + j += 1; + } + if j < code.len() && code[j].is_ascii_digit() { + i = j; + while i < code.len() && code[i].is_ascii_digit() { + i += 1; + } + } + } + out.push((n + 1, String::from_utf8_lossy(&code[start..i]).into_owned())); + } + } + out +} + +/// Browsers' WebGPU shader compiler (Tint) rejects a float literal beyond f32's finite range +/// even when it would round to `f32::MAX` (naga, used natively, rounds it), and then no +/// compositor pipeline builds and the web app falls back to the CPU renderer. `3.40282347e38` +/// was such a literal. +#[test] +fn shader_float_literals_fit_f32() { + let lits = decimal_float_literals(SHADER); + assert!(lits.iter().any(|(_, l)| l == "1.0"), "the scanner finds literals: {lits:?}"); + let bad: Vec<_> = lits.iter().filter(|(_, l)| l.parse::().map_or(true, |v| !v.is_finite() || v.abs() > f64::from(f32::MAX))).collect(); + assert!(bad.is_empty(), "float literals outside f32's finite range (line, literal): {bad:?}"); +} + +#[test] +fn op_record_fits_the_uniform() { + let p = plan::Pass::new(Kernel::FxPaint, 0); + assert_eq!(op_words(&p, None, None, None).len() as u64, OP_UNIFORM); +} + +/// #6534: a 16-bit mask (16-bit documents, feathered or vector combined masks) costs two +/// bytes per pixel on the GPU, twice an 8-bit mask, not four; 32-bit masks stay R32Float. +#[test] +fn sixteen_bit_masks_upload_at_two_bytes_per_pixel() { + let gray = |sample| PixelFormat { sample, ..PixelFormat::GRAY8 }; + assert_eq!(TexKind::for_surface(Role::Mask, PixelFormat::GRAY8).bytes_per_pixel(), 1); + let k16 = TexKind::for_surface(Role::Mask, gray(SampleType::U16)); + assert_eq!(k16.bytes_per_pixel(), 2, "{k16:?}"); + assert_eq!(k16.format().block_copy_size(None), Some(2), "{k16:?}"); + let k32 = TexKind::for_surface(Role::Mask, gray(SampleType::F32)); + assert_eq!(k32.format(), wgpu::TextureFormat::R32Float); + // The texels hold the mask values (a half each), the default pixel included. + let mut s = Surface::with_default(gray(SampleType::U16), &[1.0]); + s.fill_rect(Rect::new(0, 0, 4, 1), &[0.25]); + let c = TileCoord::new(0, 0); + let bytes = convert_tile(&s, s.tile(c), k16, c); + assert_eq!(bytes.len(), (TILE_SIZE * TILE_SIZE) as usize * 2); + assert_eq!(bytes.get(..2), Some(f32_to_f16(0.25).to_le_bytes().as_slice())); + assert_eq!(bytes.get(8..10), Some(f32_to_f16(1.0).to_le_bytes().as_slice())); + assert_eq!(convert_tile(&s, None, k16, c).get(..2), Some(f32_to_f16(1.0).to_le_bytes().as_slice())); +} + +/// #1774: a solid fill shares one tile across every coordinate; it is converted once, and +/// every coordinate (shared or not) still gets exactly the bytes `convert_tile` gives it, at +/// every depth and texture kind. +#[test] +fn convert_tiles_converts_each_distinct_tile_once() { + let area = Rect::new(0, 0, TILE_SIZE * 9, TILE_SIZE * 9); + for (fmt, kind) in [ + (PixelFormat::RGBA8, TexKind::Rgba8Direct), + (PixelFormat { alpha: false, ..PixelFormat::RGBA8 }, TexKind::Rgba8), + (PixelFormat::RGBA16, TexKind::Rgba16F), + (PixelFormat::RGBA32F, TexKind::Rgba16F), + (PixelFormat::GRAY8, TexKind::R8Direct), + (PixelFormat { sample: SampleType::U16, ..PixelFormat::GRAY8 }, TexKind::R16F), + (PixelFormat { sample: SampleType::F32, ..PixelFormat::GRAY8 }, TexKind::R32F), + ] { + let mut s = Surface::new(fmt); + let px = [0.2, 0.4, 0.6, 1.0]; + let n = fmt.channels(); + // Fully covered tiles share one `Arc`; then two tiles get their own pixels. + s.fill_rect(area, &px[..n]); + s.fill_rect(Rect::new(3, 5, 40, 60), &[0.9, 0.1, 0.3, 0.5][..n]); + s.fill_rect(Rect::new(TILE_SIZE * 4 + 7, TILE_SIZE * 2, TILE_SIZE * 4 + 9, TILE_SIZE * 2 + 3), &[0.0; 4][..n]); + let tiles: Vec<_> = area.tiles().filter_map(|c| s.tile(c).map(|t| (c, t.clone()))).collect(); + assert_eq!(tiles.len(), 81, "{fmt:?}"); + let mut seen = Vec::new(); + let converted = convert_tiles(&s, tiles, kind, |t, cs, bytes| { + for &c in cs { + assert!(s.tile(c).is_some_and(|own| Arc::ptr_eq(own, t)), "{fmt:?} {c:?}"); + assert_eq!(bytes, convert_tile(&s, Some(t), kind, c).as_slice(), "{fmt:?} {c:?}"); + seen.push(c); + } + }); + assert_eq!(converted, 3, "{fmt:?}: the shared tile once, plus the two edited ones"); + seen.sort_by_key(|c| (c.ty, c.tx)); + let mut want: Vec<_> = area.tiles().collect(); + want.sort_by_key(|c| (c.ty, c.tx)); + assert_eq!(seen, want, "{fmt:?}: every coordinate once"); + } + // More distinct tiles than one batch: all converted, each coordinate once. + let mut s = Surface::new(PixelFormat::RGBA16); + let wide = Rect::new(0, 0, TILE_SIZE * (CONVERT_BATCH as i32 + 5), TILE_SIZE); + for c in wide.tiles() { + s.fill_rect(Rect::new(c.rect().x0, 0, c.rect().x0 + 1, 1), &[c.tx as f32 / 100.0, 0.0, 0.0, 1.0]); + } + let tiles: Vec<_> = wide.tiles().filter_map(|c| s.tile(c).map(|t| (c, t.clone()))).collect(); + let mut n = 0; + let converted = convert_tiles(&s, tiles, TexKind::Rgba16F, |t, cs, bytes| { + for &c in cs { + assert_eq!(bytes, convert_tile(&s, Some(t), TexKind::Rgba16F, c).as_slice()); + n += 1; + } + }); + assert_eq!((converted, n), (CONVERT_BATCH + 5, CONVERT_BATCH + 5)); +} + +/// The 16-bit and 32-bit float RGB/gray fast paths give exactly the general path's half +/// floats (32-bit samples above 1 and below 0 included). +#[test] +fn sixteen_and_thirty_two_bit_fast_paths_match_the_general_one() { + for fmt in [ + PixelFormat::RGBA16, + PixelFormat { alpha: false, ..PixelFormat::RGBA16 }, + PixelFormat { sample: SampleType::U16, ..PixelFormat::GRAY8 }, + PixelFormat { sample: SampleType::U16, alpha: true, ..PixelFormat::GRAY8 }, + PixelFormat::RGBA32F, + PixelFormat { alpha: false, ..PixelFormat::RGBA32F }, + PixelFormat { sample: SampleType::F32, ..PixelFormat::GRAY8 }, + PixelFormat { sample: SampleType::F32, alpha: true, ..PixelFormat::GRAY8 }, + ] { + let mut s = Surface::new(fmt); + let r = Rect::new(0, 0, TILE_SIZE, TILE_SIZE); + let n = (TILE_SIZE * TILE_SIZE) as usize * fmt.channels(); + let hdr = if fmt.sample == SampleType::F32 { 4.0 } else { 1.0 }; + let data: Vec = (0..n).map(|i| (i as u32).wrapping_mul(2_654_435_761) as f32 / u32::MAX as f32 * hdr - (hdr - 1.0) / 4.0).collect(); + s.write_region(r, &data); + let t = s.tile(TileCoord::new(0, 0)).expect("written").clone(); + let fast = rgb_gray16_to_f16(&fmt, t.bytes()).or_else(|| rgb_gray32_to_f16(&fmt, t.bytes())).expect("fast path"); + let raw = s.read_region(r); + let general: Vec = + raw.chunks_exact(fmt.channels()).flat_map(|px| photocraft_raster::to_rgba(&fmt, px).map(|x| f32_to_f16(x).to_le_bytes())).flatten().collect(); + assert_eq!(fast, general, "{fmt:?}"); + assert_eq!(convert_tile(&s, Some(&t), TexKind::Rgba16F, TileCoord::new(0, 0)), general, "{fmt:?}"); + } + assert!(rgb_gray16_to_f16(&PixelFormat::RGBA8, &[]).is_none()); + assert!(rgb_gray16_to_f16(&PixelFormat { sample: SampleType::U16, ..PixelFormat::CMYKA8 }, &[]).is_none()); + assert!(rgb_gray32_to_f16(&PixelFormat::RGBA16, &[]).is_none()); + assert!(rgb_gray32_to_f16(&PixelFormat { sample: SampleType::F32, ..PixelFormat::CMYKA8 }, &[]).is_none()); +} + +/// CMYK and Lab tiles convert in parallel bands of rows, each run of equal pixels once +/// (#5108): the texels are still exactly the per-pixel conversion's, at 8 and 16 bits, with +/// the built-in CMYK profile and with a document's own (which the worker threads enter). +#[test] +fn colour_managed_tiles_match_the_per_pixel_conversion() { + use photocraft_cms::synth::{CmykParams, cmyk_profile}; + use photocraft_color::ColorMode; + use photocraft_color::convert::{CmykSpace, with_cmyk_space}; + let icc = Arc::new( + cmyk_profile(&CmykParams { description: "GPU test CMYK".into(), tvi: [0.26, 0.26, 0.26, 0.3], grid_a2b: 5, grid_b2a: 9, ..Default::default() }) + .to_bytes(), + ); + let own = CmykSpace::for_profile(Some(&icc)); + assert!(own.is_some(), "the synthetic profile is not the built-in one"); + let area = Rect::new(0, 0, TILE_SIZE * 3, TILE_SIZE); + for (mode, sample, space) in [ + (ColorMode::Cmyk, SampleType::U8, None), + (ColorMode::Cmyk, SampleType::U16, None), + (ColorMode::Cmyk, SampleType::U8, own.clone()), + (ColorMode::Cmyk, SampleType::U16, own.clone()), + (ColorMode::Lab, SampleType::U8, None), + (ColorMode::Lab, SampleType::U16, None), + ] { + let fmt = PixelFormat { mode, sample, alpha: true }; + let kind = TexKind::for_surface(Role::Content, fmt); + assert!(colour_managed(&fmt, kind), "{fmt:?}"); + let ch = fmt.channels(); + let mut s = Surface::new(fmt); + // Tile 0: noise. Tile 1: transparent with a soft dab (runs of equal pixels). Tile 2: + // a flat colour with a few lines of noise. + let n = (TILE_SIZE * TILE_SIZE) as usize * ch; + let noise: Vec = (0..n).map(|i| (i as u32).wrapping_mul(2_654_435_761) as f32 / u32::MAX as f32).collect(); + s.write_region(Rect::new(0, 0, TILE_SIZE, TILE_SIZE), &noise); + let mut dab = [0.8, 0.6, 0.1, 0.05, 0.0]; + for r in (1..30).rev() { + dab[ch - 1] = 1.0 - r as f32 / 30.0; + s.fill_rect(Rect::new(TILE_SIZE + 100 - r, 90 - r, TILE_SIZE + 100 + r, 90 + r), &dab[..ch]); + } + s.fill_rect(Rect::new(TILE_SIZE * 2, 0, TILE_SIZE * 3, TILE_SIZE), &[0.3, 0.2, 0.7, 0.1, 1.0][..ch]); + s.write_region(Rect::new(TILE_SIZE * 2, 40, TILE_SIZE * 3, 43), &noise[..TILE_SIZE as usize * 3 * ch]); + let tiles: Vec<_> = area.tiles().filter_map(|c| s.tile(c).map(|t| (c, t.clone()))).collect(); + assert_eq!(tiles.len(), 3, "{fmt:?}"); + let mut seen = 0; + with_cmyk_space(space.as_ref(), || { + convert_tiles(&s, tiles, kind, |_, cs, bytes| { + for &c in cs { + // The old path: every pixel through `to_rgba` on this thread, in this scope. + let want: Vec = s + .read_region(c.rect()) + .chunks_exact(ch) + .flat_map(|px| { + let v = photocraft_raster::to_rgba(&fmt, px); + match kind { + TexKind::Rgba16F => v.iter().flat_map(|x| f32_to_f16(*x).to_le_bytes()).collect::>(), + _ => v.map(|x| (x.clamp(0.0, 1.0) * 255.0 + 0.5) as u8).to_vec(), + } + }) + .collect(); + assert!(bytes == want.as_slice(), "{fmt:?} {c:?} with {}", if space.is_some() { "the document's profile" } else { "the built-in profile" }); + assert_eq!(convert_tile(&s, s.tile(c), kind, c), want, "{fmt:?} {c:?}"); + seen += 1; + } + }); + }); + assert_eq!(seen, 3, "{fmt:?}"); + } +} + +#[test] +fn grid_rounds_out() { + assert_eq!(tile_grid(Rect::new(0, 0, 300, 256)), Rect::new(0, 0, 512, 256)); +} diff --git a/crates/gpu/src/textures.rs b/crates/gpu/src/textures.rs new file mode 100644 index 0000000000..1b28f61150 --- /dev/null +++ b/crates/gpu/src/textures.rs @@ -0,0 +1,247 @@ +use super::*; + +/// A finished chunk: straight-alpha RGBA32F pixels of `rect` (document coordinates) at the +/// texture's origin. +pub struct ChunkOut<'a> { + pub rect: Rect, + pub texture: &'a wgpu::Texture, + pub view: &'a wgpu::TextureView, +} + +/// What a render did (for profiling and tests). +#[derive(Clone, Copy, Debug, Default)] +pub struct Stats { + /// How long the GPU spent executing a composite, once its timestamps came back. Because the + /// readback is asynchronous this belongs to an *earlier* render than the one returning it + /// (it carries that render's own pixel count, so the two are never confused), and it is + /// `None` unless [`Compositor::measure_gpu_time`] is on and a measurement has landed. + /// Always `None` from [`Compositor::encode`], which submits nothing of its own. + pub gpu_time: Option, + pub passes: usize, + pub chunks: usize, + pub slots: u32, + pub tiles_uploaded: usize, + pub bytes_uploaded: usize, + /// Tiles a new layer texture took from another layer's texture by a GPU copy (a duplicate + /// shares its source's tiles) instead of uploading them. + pub tiles_shared: usize, + /// Effect layers whose shape was (re)rendered, fully or partially. + pub fx_shapes: usize, + /// Effect map programs run (one per effect whose maps were rebuilt). + pub fx_programs: usize, + /// Effect-map pixels written (all stages). + pub fx_pixels: u64, + /// Page cells the region spans (each binds only the layer pages it overlaps). + pub cells: usize, + /// Layer pages and paged effect maps evicted to stay within the memory budgets. + pub evicted: usize, + /// Intermediate submits of a huge refresh (to bound staging and evicted memory). + pub flushes: usize, + /// Chunks restored from an unchanged lower-stack composite. + pub prefix_hits: usize, + /// Planned prefix passes skipped, summed over the reused chunks. + pub prefix_passes_skipped: usize, + /// Plain layers blended inside another layer's pass (`fs_layerbatch`), summed over chunks. + pub layers_batched: usize, + /// Batched passes drawn with Normal's code alone (`fs_layerbatch_normal`), summed over chunks. + pub normal_batches: usize, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum TexKind { + /// RGBA8 tiles copied verbatim. + Rgba8Direct, + /// Other 8-bit formats converted to RGBA8. + Rgba8, + /// 16/32-bit formats converted to RGBA16F. + Rgba16F, + /// GRAY8 masks copied verbatim. + R8Direct, + /// 16-bit masks as R16F (the precision 16-bit pixels get as RGBA16F). + R16F, + /// 32-bit masks as R32F. + R32F, +} + +impl TexKind { + pub(crate) fn for_surface(role: Role, f: PixelFormat) -> Self { + match role { + Role::Content | Role::Stroke if f == PixelFormat::RGBA8 => TexKind::Rgba8Direct, + Role::Content | Role::Stroke if f.sample == SampleType::U8 => TexKind::Rgba8, + Role::Content | Role::Stroke => TexKind::Rgba16F, + Role::Mask if f == PixelFormat::GRAY8 => TexKind::R8Direct, + Role::Mask if f.sample == SampleType::F32 => TexKind::R32F, + Role::Mask => TexKind::R16F, + } + } + pub(crate) fn format(self) -> wgpu::TextureFormat { + match self { + TexKind::Rgba8Direct | TexKind::Rgba8 => wgpu::TextureFormat::Rgba8Unorm, + TexKind::Rgba16F => wgpu::TextureFormat::Rgba16Float, + TexKind::R8Direct => wgpu::TextureFormat::R8Unorm, + TexKind::R16F => wgpu::TextureFormat::R16Float, + TexKind::R32F => wgpu::TextureFormat::R32Float, + } + } + pub(crate) fn bytes_per_pixel(self) -> usize { + match self { + TexKind::Rgba8Direct | TexKind::Rgba8 => 4, + TexKind::Rgba16F => 8, + TexKind::R8Direct => 1, + TexKind::R16F => 2, + TexKind::R32F => 4, + } + } +} + +/// Index into the render's resident key list, and the texture's region (x, y, w, h). +pub(crate) type ResidentRef = (usize, [i32; 4]); + +/// A page cell: the square `[x·page, (x+1)·page) × [y·page, (y+1)·page)` of document pixels. +pub(crate) type Cell = (i32, i32); + +/// A resident layer page. +pub(crate) type ResKey = (LayerId, Role, Cell); + +/// Effect maps of a layer: over its whole effect region (`None`), or one page cell of a region +/// larger than the texture limit. +pub(crate) type FxKey = (LayerId, Option); + +pub(crate) struct CachedPattern { + pub(crate) fingerprint: u64, + pub(crate) format: PixelFormat, + pub(crate) default_bits: Vec, + pub(crate) texture: Tex, + /// The document that last painted with it: closing that document frees the texture (#4971). + pub(crate) doc: DocId, + /// [`Compositor::frame`] when it last painted. + pub(crate) last_used: u64, + /// GPU bytes of the texture (RGBA32F). + pub(crate) bytes: u64, +} + +pub(crate) struct Resident { + pub(crate) texture: wgpu::Texture, + pub(crate) view: wgpu::TextureView, + /// Document-pixel rect covered (tile aligned, inside one page cell). + pub(crate) region: Rect, + pub(crate) kind: TexKind, + pub(crate) format: PixelFormat, + pub(crate) tiles: HashMap>, + pub(crate) default_nonzero: bool, + /// Bit pattern of the surface's default pixel when the texture was filled. Tiles the surface + /// doesn't store hold it, so a changed default (Invert, Fill) makes the texture stale. + pub(crate) default_bits: Vec, + pub(crate) doc: DocId, + pub(crate) last_used: u64, + /// Cell visit that last used it (least recently used pages are evicted first). + pub(crate) stamp: u64, + /// CMYK profile the texels were converted with (`CmykSpace::id`, 0 = built-in / not CMYK). + pub(crate) cmyk: u64, + /// Its texels were copied to or from another layer texture by the encoder, so every write + /// to it goes through the encoder too: a queued write lands before the encoder runs, and + /// would be overwritten by the copy, or leak into it. + pub(crate) ordered: bool, +} + +impl Resident { + pub(crate) fn bytes(&self) -> u64 { + self.region.width() as u64 * self.region.height() as u64 * self.kind.bytes_per_pixel() as u64 + } +} + +/// A texture and its default view. +#[derive(Clone)] +pub(crate) struct Tex { + pub(crate) texture: wgpu::Texture, + pub(crate) view: wgpu::TextureView, +} + +impl Tex { + pub(crate) fn new(device: &wgpu::Device, label: &str, w: u32, h: u32, format: wgpu::TextureFormat, usage: wgpu::TextureUsages) -> Self { + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: Some(label), + size: wgpu::Extent3d { width: w.max(1), height: h.max(1), depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format, + usage, + view_formats: &[], + }); + let view = texture.create_view(&Default::default()); + Tex { texture, view } + } + pub(crate) fn map(device: &wgpu::Device, label: &str, r: Rect, format: wgpu::TextureFormat) -> Self { + Tex::new( + device, + label, + r.width(), + r.height(), + format, + wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, + ) + } + /// Upload R32F values (row-major over `r`) into this region-space texture at `r`. + pub(crate) fn write_r32(&self, queue: &wgpu::Queue, region: Rect, r: Rect, v: &[f32]) { + if r.is_empty() { + return; + } + let bytes: Vec = v.iter().flat_map(|x| x.to_le_bytes()).collect(); + queue.write_texture( + wgpu::TexelCopyTextureInfo { + texture: &self.texture, + mip_level: 0, + origin: wgpu::Origin3d { x: (r.x0 - region.x0) as u32, y: (r.y0 - region.y0) as u32, z: 0 }, + aspect: wgpu::TextureAspect::All, + }, + &bytes, + wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(r.width() * 4), rows_per_image: Some(r.height()) }, + wgpu::Extent3d { width: r.width(), height: r.height(), depth_or_array_layers: 1 }, + ); + } + fn bytes(&self) -> usize { + let s = self.texture.size(); + let bpp = match self.texture.format() { + wgpu::TextureFormat::R16Float => 2, + wgpu::TextureFormat::Rgba32Float => 16, + wgpu::TextureFormat::Rgba16Float => 8, + _ => 4, + }; + s.width as usize * s.height as usize * bpp + } +} + +/// Cached maps of one effect (one enabled item of a layer). +pub(crate) struct ProgState { + pub(crate) key: u64, + pub(crate) maps: Vec>, +} + +/// Cached effect state of one layer. +pub(crate) struct FxEntry { + pub(crate) doc: DocId, + pub(crate) region: Rect, + pub(crate) shape_key: u64, + /// Tiles the shape was rendered from (content, mask): damage is their difference. + pub(crate) tiles: [Option; 2], + /// Groups: the tiles `shape_key` hashes, by address only (see [`fx::Tiles`]). + pub(crate) _pin: Vec>, + /// The shape on the CPU (distance fields are computed from it) and on the GPU. + pub(crate) shape_cpu: Vec, + pub(crate) shape: Tex, + /// Distance fields: the reach each is exact to, and its texture. + pub(crate) fields: HashMap, + pub(crate) progs: Vec, + pub(crate) last_used: u64, + pub(crate) stamp: u64, +} + +impl FxEntry { + pub(crate) fn bytes(&self) -> usize { + self.shape.bytes() + + self.shape_cpu.len() * 4 + + self.fields.values().map(|(_, t)| t.bytes()).sum::() + + self.progs.iter().flat_map(|p| p.maps.iter().flatten()).map(Tex::bytes).sum::() + } +} diff --git a/crates/io/src/adjust_map.rs b/crates/io/src/adjust_map.rs index 3a9d18f94e..2cac91c4a0 100644 --- a/crates/io/src/adjust_map.rs +++ b/crates/io/src/adjust_map.rs @@ -843,608 +843,4 @@ pub fn write(adj: &Adjustment) -> Vec<([u8; 4], Vec)> { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn gradient_map_v3_methods_and_smoothness() { - let classic = vec![(0.0, [0.0, 0.0, 1.0]), (1.0, [1.0, 1.0, 0.0])]; - let v1 = write_gradient_map(&classic, false, false); - // Version 3 inserts the interpolation method after reverse/dither. - let v3 = |m: &[u8; 4]| { - let mut v = v1.clone(); - v[1] = 3; - v.splice(4..4, m.iter().copied()); - v - }; - let at_t = |data: &[u8], t: f32| match parse(b"grdm", data, None, Channels::Rgb) { - Adjustment::GradientMap { stops, .. } => { - let i = stops.windows(2).position(|w| w[0].0 <= t && t <= w[1].0).unwrap(); - let (x, y) = (stops[i], stops[i + 1]); - let u = (t - x.0) / (y.0 - x.0).max(1e-6); - std::array::from_fn::(|k| x.1[k] + (y.1[k] - x.1[k]) * u) - } - other => panic!("{other:?}"), - }; - let mid = |data: &[u8]| at_t(data, 0.5); - let c = mid(&v3(b"Gcls")); - assert!((c[0] - 0.5).abs() < 1e-3 && (c[2] - 0.5).abs() < 1e-3, "classic = sRGB lerp {c:?}"); - let p = mid(&v3(b"Perc")); - assert!((p[0] - c[0]).abs() > 0.02, "perceptual differs from classic {p:?}"); - // Smoothness 100 % (4096) bends a three-stop ramp. - let three = vec![(0.0, [0.0; 3]), (0.25, [1.0, 0.0, 0.0]), (0.75, [0.0, 0.0, 1.0]), (1.0, [1.0; 3])]; - let mut smooth = write_gradient_map(&three, false, false); - // v1 header/name/count + colour stops + transparency stops + expansion count. - let at = 48 + three.len() * 20; - smooth[at..at + 2].copy_from_slice(&4096u16.to_be_bytes()); - let (a, b) = (at_t(&write_gradient_map(&three, false, false), 0.4), at_t(&smooth, 0.4)); - assert!((0..3).any(|k| (a[k] - b[k]).abs() > 1e-3), "{a:?} {b:?}"); - // Noise gradients (no colour stops) stay unsupported. - assert!(matches!(parse(b"grdm", &[0, 1, 0, 0, 0, 0, 0, 0, 0, 0], None, Channels::Rgb), Adjustment::Unsupported { .. })); - } - - #[test] - fn pencil_curves_read_and_write_the_map_form() { - // Photoshop's pencil-drawn curves: map flag 1, then 256 output bytes per channel. - let mut block = vec![1, 0, 1, 0, 0, 0, 0b1111]; - let maps: [Vec; 4] = [ - (0..=255u8).rev().collect(), - (0..=255u8).map(|k| if k < 128 { 0 } else { 255 }).collect(), - (0..=255u8).collect(), - (0..=255u8).map(|k| k / 2).collect(), - ]; - for m in &maps { - block.extend_from_slice(m); - } - let a = parse(b"curv", &block, None, Channels::Rgb); - let Adjustment::Curves { master, per_channel, pencil, .. } = &a else { panic!("{a:?}") }; - assert!(*pencil); - assert_eq!(master.len(), CURVE_MAP_LEN); - assert_eq!((master[0].output, master[255].output), (1.0, 0.0)); - assert_eq!((per_channel[0][127].output, per_channel[0][128].output), (0.0, 1.0)); - assert_eq!(write(&a)[0].1, block); - } - - /// A two-stop `grdm` (version 1) whose stops are the colour structures `a` and `b`. - fn grdm_with(a: (u16, [u16; 4]), b: (u16, [u16; 4])) -> Vec { - let mut v = write_gradient_map(&[(0.0, [0.0; 3]), (1.0, [1.0; 3])], false, false); - // Header 4 + name length 4 + "Custom\0" 14 + stop count 2; 20 bytes per stop. - for (i, (space, c)) in [a, b].into_iter().enumerate() { - let at = 24 + 20 * i + 8; - v[at..at + 2].copy_from_slice(&space.to_be_bytes()); - for (k, x) in c.iter().enumerate() { - v[at + 2 + 2 * k..at + 4 + 2 * k].copy_from_slice(&x.to_be_bytes()); - } - } - v - } - - fn ends(a: &Adjustment) -> ([f32; 3], [f32; 3]) { - match a { - Adjustment::GradientMap { stops, .. } => (stops[0].1, stops[stops.len() - 1].1), - other => panic!("{other:?}"), - } - } - - #[test] - fn gradient_map_stops_in_every_colour_space() { - use photocraft_color::{Color, ColorMode}; - let white_rgb = (0, [65535, 65535, 65535, 0]); - // CMYK, stored inverted: 65535 = no ink. Full K only. - let k_only = grdm_with((2, [65535, 65535, 65535, 0]), white_rgb); - let expected = Color { mode: ColorMode::Cmyk, c: [0.0, 0.0, 0.0, 1.0], alpha: 1.0 }.to_rgb(); - for channels in [Channels::Cmyk, Channels::Rgb, Channels::Lab] { - let a = parse(b"grdm", &k_only, None, channels); - let (first, last) = ends(&a); - assert!(first.iter().zip(expected).all(|(x, y)| (x - y).abs() < 1e-5), "{first:?} vs {expected:?}"); - assert!(first[0] < 0.4 && (first[0] - first[2]).abs() < 0.05, "K-only black is a dark neutral: {first:?}"); - assert_eq!(last, [1.0; 3]); - } - // Lab: L 50, a 0, b 0 is a neutral mid grey; L 100 white. - let lab = parse(b"grdm", &grdm_with((7, [5000, 0, 0, 0]), (7, [10000, 0, 0, 0])), None, Channels::Lab); - let (first, last) = ends(&lab); - assert!(first.iter().all(|v| (v - 0.466).abs() < 0.01), "{first:?}"); - assert!(last.iter().all(|v| *v > 0.99), "{last:?}"); - // Lab with chroma: a = +60 is reddish (a and b are signed hundredths). - let red = parse(b"grdm", &grdm_with((7, [5000, 6000, 0, 0]), white_rgb), None, Channels::Lab); - let (first, _) = ends(&red); - assert!(first[0] > first[1] + 0.2, "{first:?}"); - // Grayscale: 0..10000 is ink coverage (10000 = black). - let gray = parse(b"grdm", &grdm_with((8, [10000, 0, 0, 0]), (8, [0, 0, 0, 0])), None, Channels::Gray); - assert_eq!(ends(&gray), ([0.0; 3], [1.0; 3])); - // HSB: hue 240 degrees (2/3 of 65535), full saturation and brightness = blue. - let hsb = parse(b"grdm", &grdm_with((1, [43690, 65535, 65535, 0]), white_rgb), None, Channels::Rgb); - let (first, _) = ends(&hsb); - assert!(first[0] < 1e-3 && first[1] < 1e-3 && (first[2] - 1.0).abs() < 1e-3, "{first:?}"); - // Book colours and unknown ids are not guessed: the block stays raw. - for space in [3u16, 9, 0xFFFF] { - let d = grdm_with((space, [1, 2, 3, 4]), white_rgb); - assert!(matches!(parse(b"grdm", &d, None, Channels::Rgb), Adjustment::Unsupported { .. }), "space {space}"); - } - // Truncated stops never panic. - for n in 0..k_only.len() { - let _ = parse(b"grdm", &k_only[..n], None, Channels::Cmyk); - } - } - - #[test] - fn gradient_map_reverse_and_dither_keep_the_stops_block() { - let original = grdm_with((2, [65535, 65535, 65535, 0]), (7, [10000, 0, 0, 0])); - let Adjustment::GradientMap { stops, .. } = parse(b"grdm", &original, None, Channels::Cmyk) else { panic!() }; - let mut data = original.clone(); - let target = Adjustment::GradientMap { stops: stops.clone(), reverse: true, dither: true }; - assert!(retarget_gradient_map(&mut data, &target, Channels::Cmyk)); - assert_eq!(&data[2..4], &[1, 1]); - assert_eq!(data[4..], original[4..], "the stops keep their colour spaces"); - assert_eq!(parse(b"grdm", &data, None, Channels::Cmyk), target); - // Edited stops are not patched in. - let mut edited = stops; - edited[0].1 = [0.5; 3]; - let mut data2 = original.clone(); - let target = Adjustment::GradientMap { stops: edited, reverse: false, dither: false }; - assert!(!retarget_gradient_map(&mut data2, &target, Channels::Cmyk)); - assert_eq!(data2, original); - assert!(!retarget_gradient_map(&mut [], &target, Channels::Cmyk)); - assert!(!retarget_gradient_map(&mut data2, &Adjustment::Invert, Channels::Cmyk)); - } - - fn rt(a: Adjustment) { - let blocks = write(&a); - assert!(!blocks.is_empty(), "{a:?}"); - let cged = blocks.iter().find(|b| &b.0 == b"CgEd").map(|b| &b.1[..]); - let back = parse(&blocks[0].0, &blocks[0].1, cged, Channels::Rgb); - assert_eq!(back, a); - } - - /// Photoshop keeps the colorize triplet at byte 4 and the master triplet at byte 10, and fills - /// the inactive one with its defaults: colorize (30, 25, 0), master (0, 0, 0). The colorize hue - /// is stored signed (200 -> -160). - #[test] - fn hue2_writes_each_triplet_in_its_own_slot() { - let triplets = |a: &Adjustment| -> Vec { - let blocks = write(a); - (0..6).map(|i| bei16(&blocks[0].1, 4 + 2 * i).unwrap_or(i16::MIN)).collect() - }; - let on = Adjustment::HueSaturation { hue: 200.0, saturation: 40.0, lightness: 10.0, colorize: true, ranges: HueRange::defaults() }; - assert_eq!(triplets(&on), [-160, 40, 10, 0, 0, 0]); - let off = Adjustment::HueSaturation { hue: -30.0, saturation: 20.0, lightness: 5.0, colorize: false, ranges: HueRange::defaults() }; - assert_eq!(triplets(&off), [30, 25, 0, -30, 20, 5]); - } - - #[test] - fn roundtrips() { - rt(Adjustment::Invert); - rt(Adjustment::Threshold { level: 128.0 / 255.0 }); - rt(Adjustment::Posterize { levels: 4 }); - rt(Adjustment::BrightnessContrast { brightness: 20.0, contrast: -10.0, legacy: false }); - rt(Adjustment::BrightnessContrast { brightness: -150.0, contrast: 100.0, legacy: true }); - rt(Adjustment::HueSaturation { hue: 30.0, saturation: -20.0, lightness: 5.0, colorize: false, ranges: HueRange::defaults() }); - rt(Adjustment::HueSaturation { hue: 200.0, saturation: 50.0, lightness: 0.0, colorize: true, ranges: HueRange::defaults() }); - let mut ranges = HueRange::defaults(); - ranges[0] = HueRange { hue: 15.0, saturation: -40.0, lightness: 10.0, bounds: [-60.0, -20.0, 10.0, 30.0] }; - ranges[4].saturation = 25.0; - rt(Adjustment::HueSaturation { hue: -10.0, saturation: 0.0, lightness: 0.0, colorize: false, ranges }); - rt(Adjustment::Exposure { exposure: 1.5, offset: -0.01, gamma: 0.9 }); - let lc = |a: u16, b: u16| LevelsChannel { in_black: f32::from(a) / 255.0, in_white: f32::from(b) / 255.0, gamma: 1.2, out_black: 0.0, out_white: 1.0 }; - rt(Adjustment::Levels { - master: lc(10, 240), - per_channel: [lc(0, 255), lc(5, 250), lc(20, 200)], - space: ToneSpace::Rgb, - black: LevelsChannel::default(), - }); - let pts = |v: &[(u8, u8)]| v.iter().map(|&(i, o)| CurvePoint { input: f32::from(i) / 255.0, output: f32::from(o) / 255.0 }).collect::>(); - rt(Adjustment::Curves { - master: pts(&[(0, 0), (128, 150), (255, 255)]), - per_channel: [pts(&[(0, 10), (255, 255)]), pts(&[(0, 0), (255, 245)]), pts(&[(0, 0), (64, 32), (255, 255)])], - space: ToneSpace::Rgb, - black: Vec::new(), - pencil: false, - }); - // CMYK ink curves and levels keep their black record. - let ink = Adjustment::Curves { - master: pts(&[(0, 0), (255, 255)]), - per_channel: [pts(&[(0, 0), (255, 255)]), pts(&[(0, 30), (255, 255)]), pts(&[(0, 0), (255, 255)])], - space: ToneSpace::Cmyk, - black: pts(&[(0, 0), (128, 100), (255, 255)]), - pencil: false, - }; - let b = write(&ink); - assert_eq!(parse(&b[0].0, &b[0].1, None, Channels::Cmyk), ink); - let inkl = Adjustment::Levels { master: lc(0, 255), per_channel: [lc(0, 255), lc(5, 250), lc(0, 255)], space: ToneSpace::Cmyk, black: lc(30, 255) }; - let b = write(&inkl); - assert_eq!(parse(&b[0].0, &b[0].1, None, Channels::Cmyk), inkl); - rt(Adjustment::Unsupported { psd_key: "selc".into(), raw: vec![1, 2, 3].into() }); - rt(Adjustment::GradientMap { stops: vec![(0.0, [0.0, 0.0, 0.0]), (0.5, [1.0, 0.0, 0.0]), (1.0, [1.0, 1.0, 1.0])], reverse: true, dither: false }); - rt(Adjustment::GradientMap { stops: vec![(0.0, [0.0, 0.0, 0.0]), (1.0, [1.0, 1.0, 1.0])], reverse: false, dither: true }); - rt(Adjustment::SelectiveColor { relative: true, adjustments: std::array::from_fn(|r| [r as f32 * 10.0 - 40.0, 5.0, -100.0, 100.0]) }); - rt(Adjustment::SelectiveColor { relative: false, adjustments: [[0.0; 4]; 9] }); - rt(Adjustment::Vibrance { vibrance: 35.0, saturation: -12.0 }); - rt(Adjustment::Vibrance { vibrance: 0.0, saturation: 0.0 }); - rt(Adjustment::ColorBalance { shadows: [20.0, -10.0, 5.0], midtones: [-15.0, 10.0, 30.0], highlights: [0.0, 5.0, -100.0], preserve_luminosity: true }); - rt(Adjustment::ColorBalance { shadows: [0.0; 3], midtones: [100.0, 0.0, 0.0], highlights: [0.0; 3], preserve_luminosity: false }); - rt(Adjustment::BlackWhite { weights: [40.0, 60.0, 40.0, 60.0, 20.0, 80.0], tint: None }); - rt(Adjustment::BlackWhite { weights: [-200.0, 300.0, 0.0, 10.0, 90.0, 30.0], tint: Some([0.9, 0.7, 0.5]) }); - let q = |v: u16| f32::from(v) / 65535.0; - rt(Adjustment::PhotoFilter { color: [q(60000), q(30000), q(0)], density: 0.25, preserve_luminosity: true }); - rt(Adjustment::PhotoFilter { color: [q(0), q(40000), q(65535)], density: 1.0, preserve_luminosity: false }); - rt(Adjustment::ChannelMixer { matrix: [[0.5, 0.3, 0.2, 0.0], [0.1, 0.8, 0.1, 0.05], [0.0, 0.2, 0.9, -0.05]], monochrome: false }); - rt(Adjustment::ChannelMixer { matrix: [[0.4, 0.4, 0.2, 0.1], [0.0, 1.0, 0.0, 0.0], [-2.0, 0.0, 2.0, 0.0]], monochrome: true }); - let id = photocraft_cms::lutfile::LutFile::identity(5); - rt(Adjustment::ColorLookup { name: "Look.cube".into(), lut: Some(std::sync::Arc::new(id.data)), size: 5, tetrahedral: false, dither: true }); - } - - #[test] - fn selective_color_synthetic_block() { - // Absolute; reds = (+10, -20, +30, -40), blacks = (0, 0, 0, 25). - let mut d = vec![0, 1, 0, 1]; - d.extend([0u8; 8]); - for r in 0..9 { - let rec: [i16; 4] = match r { - 0 => [10, -20, 30, -40], - 8 => [0, 0, 0, 25], - _ => [0; 4], - }; - for x in rec { - d.extend(x.to_be_bytes()); - } - } - let a = parse(b"selc", &d, None, Channels::Rgb); - let Adjustment::SelectiveColor { relative, adjustments } = &a else { panic!("{a:?}") }; - assert!(!relative); - assert_eq!(adjustments[0], [10.0, -20.0, 30.0, -40.0]); - assert_eq!(adjustments[8], [0.0, 0.0, 0.0, 25.0]); - // Written back byte-exact. - assert_eq!(write(&a)[0].1, d); - } - - #[test] - fn color_lookup_synthetic_block() { - let cube = b"TITLE \"t\"\nLUT_3D_SIZE 2\n0 0 0\n1 0 0\n0 1 0\n1 1 0\n0 0 1\n1 0 1\n0 1 1\n1 1 1\n"; - let en = |t: &str, val: &str| Value::Enumerated { type_id: photocraft_psd::descriptor::Id::new(t), value: photocraft_psd::descriptor::Id::new(val) }; - let desc = Descriptor::new("null") - .with("lookupType", en("colorLookupType", "3DLUT")) - .with("NM ", Value::Text(photocraft_psd::descriptor::UnicodeString::new_nul("Id"))) - .with("Dthr", Value::Boolean(true)) - .with("LUTFormat", en("LUTFormatType", "LUTFormatCUBE")) - .with("LUT3DFileData", Value::RawData(cube.to_vec())); - let mut d = vec![0, 1]; - d.extend(VersionedDescriptor::new(desc).to_bytes()); - let a = parse(b"clrL", &d, None, Channels::Rgb); - let Adjustment::ColorLookup { name, lut: Some(t), size: 2, dither: true, .. } = &a else { panic!("{a:?}") }; - assert_eq!(name, "Id"); - assert_eq!(&t[..6], &[0.0, 0.0, 0.0, 1.0, 0.0, 0.0]); - // A profile-based lookup (no table) is preserved raw. - let mut p = vec![0, 1]; - p.extend(VersionedDescriptor::new(Descriptor::new("null").with("lookupType", en("colorLookupType", "abstractProfile"))).to_bytes()); - assert!(matches!(parse(b"clrL", &p, None, Channels::Rgb), Adjustment::Unsupported { .. })); - // Each way a lookup can't be read has a reason for the import warning (#1763). - assert_eq!(unreadable_reason(b"clrL", &d), None); - assert!(unreadable_reason(b"clrL", &p).unwrap().contains("colour profile")); - assert!(unreadable_reason(b"clrL", &[0]).unwrap().contains("truncated")); - assert!(unreadable_reason(b"clrL", &[0, 2, 0, 0]).unwrap().contains("version 2")); - assert!(unreadable_reason(b"clrL", &[0, 1, 9]).unwrap().contains("unreadable settings")); - let bad = Descriptor::new("null").with("LUTFormat", en("LUTFormatType", "LUTFormat3DL")).with("LUT3DFileData", Value::RawData(b"not a lut".to_vec())); - let mut b = vec![0, 1]; - b.extend(VersionedDescriptor::new(bad).to_bytes()); - assert!(matches!(parse(b"clrL", &b, None, Channels::Rgb), Adjustment::Unsupported { .. })); - assert!(unreadable_reason(b"clrL", &b).unwrap().contains("3DL LUT can't be read"), "{:?}", unreadable_reason(b"clrL", &b)); - assert_eq!(label(b"clrL"), "Color Lookup"); - assert!(matches!(parse(b"clrL", &[0, 1, 9], None, Channels::Rgb), Adjustment::Unsupported { .. })); - assert!(matches!(parse(b"selc", &[0, 1, 0, 0], None, Channels::Rgb), Adjustment::Unsupported { .. })); - } - - fn cube_lookup_block(cube: &[u8]) -> Vec { - let en = |t: &str, val: &str| Value::Enumerated { type_id: photocraft_psd::descriptor::Id::new(t), value: photocraft_psd::descriptor::Id::new(val) }; - let desc = Descriptor::new("null") - .with("LUTFormat", en("LUTFormatType", "LUTFormatCUBE")) - .with("LUT3DFileName", Value::Text(photocraft_psd::descriptor::UnicodeString::new_nul("domain.cube"))) - .with("LUT3DFileData", Value::RawData(cube.to_vec())); - let mut block = vec![0, 1]; - block.extend(VersionedDescriptor::new(desc).to_bytes()); - block - } - - fn identity_cube(domain: &str) -> Vec { - format!("{domain}LUT_3D_SIZE 2\n0 0 0\n1 0 0\n0 1 0\n1 1 0\n0 0 1\n1 0 1\n0 1 1\n1 1 1\n").into_bytes() - } - - #[test] - fn color_lookup_custom_domains_are_kept_unsupported() { - let domains = ["DOMAIN_MIN 0 0 0\nDOMAIN_MAX 0.5 0.5 0.5\n", "DOMAIN_MIN 0 0.25 0\nDOMAIN_MAX 1 0.75 1\n", "LUT_3D_INPUT_RANGE 0 0.5\n"]; - for domain in domains { - let raw = cube_lookup_block(&identity_cube(domain)); - let Adjustment::Unsupported { psd_key, raw: kept } = parse(b"clrL", &raw, None, Channels::Rgb) else { - panic!("custom LUT domain was applied instead of kept unsupported: {domain}") - }; - assert_eq!(psd_key, "clrL"); - assert_eq!(*kept, *raw); - let reason = unreadable_reason(b"clrL", &raw).expect("custom domain has an explanation"); - assert!(reason.contains("DOMAIN_MIN") && reason.contains("DOMAIN_MAX"), "{reason}"); - assert!(reason.to_ascii_lowercase().contains("not supported"), "{reason}"); - } - } - - #[test] - fn color_lookup_default_domains_stay_supported() { - for domain in ["", "DOMAIN_MIN 0 0 0\nDOMAIN_MAX 1 1 1\n"] { - let raw = cube_lookup_block(&identity_cube(domain)); - assert!(matches!(parse(b"clrL", &raw, None, Channels::Rgb), Adjustment::ColorLookup { size: 2, .. })); - assert_eq!(unreadable_reason(b"clrL", &raw), None); - } - } - - #[test] - fn malformed_falls_back_to_unsupported() { - assert!(matches!(parse(b"levl", &[0, 2, 1], None, Channels::Rgb), Adjustment::Unsupported { .. })); - assert!(matches!(parse(b"curv", &[0, 0, 9], None, Channels::Rgb), Adjustment::Unsupported { .. })); - assert!(matches!(parse(b"thrs", &[], None, Channels::Rgb), Adjustment::Unsupported { .. })); - assert!(matches!(parse(b"blnc", &[0; 18], None, Channels::Rgb), Adjustment::Unsupported { .. })); - assert!(matches!(parse(b"vibA", &[0, 0, 0, 15, 0], None, Channels::Rgb), Adjustment::Unsupported { .. })); - assert!(matches!(parse(b"blwh", &[], None, Channels::Rgb), Adjustment::Unsupported { .. })); - assert!(matches!(parse(b"mixr", &[0, 2, 0, 0], None, Channels::Rgb), Adjustment::Unsupported { .. })); - // A CMYK mixer (black source used) stays raw in CMYK documents; our own RGB layout maps. - let mut cmyk = i16s(&[1, 0]); - for r in 0..4 { - cmyk.extend(i16s(&std::array::from_fn::(|k| if k == r { 100 } else { 0 }))); - } - assert!(matches!(parse(b"mixr", &cmyk, None, Channels::Cmyk), Adjustment::Unsupported { .. })); - assert!(matches!(parse(b"mixr", &cmyk, None, Channels::Other), Adjustment::Unsupported { .. })); - let ours = write(&Adjustment::ChannelMixer { matrix: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]], monochrome: false }); - assert!(matches!(parse(b"mixr", &ours[0].1, None, Channels::Cmyk), Adjustment::ChannelMixer { .. })); - assert!(matches!(parse(b"mixr", &ours[0].1, None, Channels::Other), Adjustment::ChannelMixer { .. })); - assert!(matches!(parse(b"mixr", &[0, 1, 0, 0, 0, 100], None, Channels::Rgb), Adjustment::Unsupported { .. })); - // Photo Filter: unknown version, HSB colour space, out-of-range version-3 XYZ, truncated. - assert!(matches!(parse(b"phfl", &[0, 4, 0, 0], None, Channels::Rgb), Adjustment::Unsupported { .. })); - assert!(matches!(parse(b"phfl", &[0, 2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 25, 1], None, Channels::Rgb), Adjustment::Unsupported { .. })); - for bad in [[200_000u32, 0, 0], [0, u32::MAX, 0]] { - let mut xyz = vec![0, 3]; - for x in bad { - xyz.extend(x.to_be_bytes()); - } - xyz.extend([0, 0, 0, 25, 1]); - assert!(matches!(parse(b"phfl", &xyz, None, Channels::Rgb), Adjustment::Unsupported { .. })); - } - assert!(matches!(parse(b"phfl", &[0, 2, 0, 0, 0, 0], None, Channels::Rgb), Adjustment::Unsupported { .. })); - // Arbitrary bytes never panic, whatever the key. - for key in ADJUSTMENT_KEYS { - for len in 0..64usize { - let d: Vec = (0..len).map(|i| (i * 37 + len) as u8).collect(); - let _ = parse(key, &d, Some(&d), Channels::Rgb); - let _ = parse(key, &d, None, Channels::Other); - } - } - } - - fn i16s(v: &[i16]) -> Vec { - v.iter().flat_map(|x| x.to_be_bytes()).collect() - } - - /// Hand-built blocks laid out per the Adobe spec (no file written by Photoshop involved). - #[test] - fn color_balance_golden_block() { - let mut d = i16s(&[-30, 20, 0, 10, -5, 100, 0, 0, -100]); - d.extend([1, 0]); - let a = parse(b"blnc", &d, None, Channels::Rgb); - assert_eq!( - a, - Adjustment::ColorBalance { shadows: [-30.0, 20.0, 0.0], midtones: [10.0, -5.0, 100.0], highlights: [0.0, 0.0, -100.0], preserve_luminosity: true } - ); - assert_eq!(write(&a), vec![(*b"blnc", d.clone())]); - // The 19-byte form (no trailing pad) parses the same. - assert_eq!(parse(b"blnc", &d[..19], None, Channels::Rgb), a); - } - - #[test] - fn photo_filter_golden_blocks() { - // Version 2, RGB colour structure (65535, 32768, 0), density 40 %, preserve luminosity. - let mut v2 = i16s(&[2, 0]); - v2.extend([0xff, 0xff, 0x80, 0x00, 0, 0, 0, 0]); - v2.extend(40u32.to_be_bytes()); - v2.extend([1, 0, 0, 0]); - assert_eq!(v2.len(), 20, "Photo Filter must occupy 20 bytes"); - assert_eq!(&v2[17..], &[0, 0, 0], "padding is included inside the block length"); - let a = parse(b"phfl", &v2, None, Channels::Rgb); - let Adjustment::PhotoFilter { color, density, preserve_luminosity: true } = a else { panic!("{a:?}") }; - assert_eq!(color, [1.0, 32768.0 / 65535.0, 0.0]); - assert_eq!(density, 0.4); - assert_eq!(write(&a)[0].1, v2, "version 2 RGB is written back byte-exact"); - // Older PhotoCraft files used only one padding byte (18 bytes); keep importing them, - // but never produce that Photoshop-incompatible length again. - assert_eq!(parse(b"phfl", &v2[..18], None, Channels::Rgb), a); - for preserve_luminosity in [false, true] { - for density in [0.0, 0.14, 1.0] { - let adjustment = Adjustment::PhotoFilter { color: [0.8, 0.4, 0.2], density, preserve_luminosity }; - let blocks = write(&adjustment); - assert_eq!(blocks.len(), 1); - assert_eq!(blocks[0].0, *b"phfl"); - assert_eq!(blocks[0].1.len(), 20); - assert_eq!(&blocks[0].1[17..], &[0, 0, 0]); - let Adjustment::PhotoFilter { color, density: read_density, preserve_luminosity: read_preserve } = - parse(b"phfl", &blocks[0].1, None, Channels::Rgb) - else { - panic!("written phfl must parse") - }; - assert!(color.iter().zip([0.8, 0.4, 0.2]).all(|(got, expected)| (got - expected).abs() <= 1.0 / 65535.0)); - assert!((read_density - density).abs() < 0.00001); - assert_eq!(read_preserve, preserve_luminosity); - } - } - // Version 2, Lab colour structure: L 50, a 0, b 0 is mid gray. - let mut lab = i16s(&[2, 7, 5000, 0, 0, 0]); - lab.extend(25u32.to_be_bytes()); - lab.push(0); - let Adjustment::PhotoFilter { color, density, preserve_luminosity: false } = parse(b"phfl", &lab, None, Channels::Rgb) else { panic!() }; - assert!(color.iter().all(|c| (c - 0.466).abs() < 0.01), "{color:?}"); - assert_eq!(density, 0.25); - // Version 3: XYZ relative to the D50 white, 1.0 = 32768. White is (32768, 32768, 32768). - let v3 = phfl_v3([32768, 32768, 32768], 100, true); - let Adjustment::PhotoFilter { color, density, preserve_luminosity: true } = parse(b"phfl", &v3, None, Channels::Rgb) else { panic!() }; - assert!(color.iter().all(|c| (c - 1.0).abs() < 0.005), "{color:?}"); - assert_eq!(density, 1.0); - // Photoshop's Warming Filter (85) preset, sRGB #EC8A00: the CS2 file of #4940 stores it - // relative to the D50 white as (15548, 12029, 0). - let Adjustment::PhotoFilter { color, density, preserve_luminosity: false } = - parse(b"phfl", &phfl_v3([15548, 12029, 0], 25, false), None, Channels::Rgb) - else { - panic!() - }; - let expected = [0xecu8, 0x8a, 0x00].map(|v| f32::from(v) / 255.0); - assert!(color.iter().zip(expected).all(|(got, want)| (got - want).abs() < 1.5 / 255.0), "{color:?}"); - assert_eq!(density, 0.25); - // The block from #3777 (Photoshop CS2): the Yellow filter preset, #F9E31C, density 63 %. - let issue = [0, 3, 0, 0, 0x5e, 0x7f, 0, 0, 0x61, 0xaa, 0, 0, 0x0e, 0xf3, 0, 0, 0, 0x3f, 1, 0]; - let Adjustment::PhotoFilter { color, density, preserve_luminosity: true } = parse(b"phfl", &issue, None, Channels::Rgb) else { panic!() }; - let expected = [0xf9u8, 0xe3, 0x1c].map(|v| f32::from(v) / 255.0); - assert!(color.iter().zip(expected).all(|(got, want)| (got - want).abs() < 1.5 / 255.0), "{color:?}"); - assert_eq!(density, 0.63); - // Cooling Filter (82) from #4940: a deep blue outside sRGB; its Z stays under the 2.0 - // garbage guard and the colour clamps to (0, 181, 255). - let Adjustment::PhotoFilter { color: cooling, density, preserve_luminosity: true } = - parse(b"phfl", &phfl_v3([5327, 9584, 65357], 72, true), None, Channels::Rgb) - else { - panic!("Cooling Filter (82) must parse") - }; - let expected = [0u8, 181, 255].map(|v| f32::from(v) / 255.0); - assert!(cooling.iter().zip(expected).all(|(got, want)| (got - want).abs() < 1.5 / 255.0), "{cooling:?}"); - assert_eq!(density, 0.72); - // The 19-byte form (no trailing pad) parses the same. - assert_eq!(parse(b"phfl", &issue[..19], None, Channels::Rgb), parse(b"phfl", &issue, None, Channels::Rgb)); - // Version 3 is read, never written: an edited filter is saved as version 2 and keeps its colour. - let a = parse(b"phfl", &issue, None, Channels::Rgb); - let w = write(&a); - assert_eq!(&w[0].1[..2], &[0, 2]); - let Adjustment::PhotoFilter { color: back, .. } = parse(b"phfl", &w[0].1, None, Channels::Rgb) else { panic!() }; - assert!(back.iter().zip(color).all(|(b, c)| (b - c).abs() <= 1.0 / 65535.0)); - } - - /// A version 3 Photo Filter block: version, three u32 XYZ components, density, flag, pad. - fn phfl_v3(xyz: [u32; 3], density: u32, preserve_luminosity: bool) -> Vec { - let mut d = vec![0, 3]; - for x in xyz { - d.extend(x.to_be_bytes()); - } - d.extend(density.to_be_bytes()); - d.extend([u8::from(preserve_luminosity), 0]); - d - } - - #[test] - fn channel_mixer_golden_blocks() { - // RGB: red = 100 % R + 20 % const; green = 50 % R + 50 % G; blue = -50 % G + 150 % B - 10 % const. - let mut d = i16s(&[1, 0]); - d.extend(i16s(&[100, 0, 0, 0, 20, 50, 50, 0, 0, 0, 0, -50, 150, 0, -10])); - let a = parse(b"mixr", &d, None, Channels::Rgb); - assert_eq!(a, Adjustment::ChannelMixer { matrix: [[1.0, 0.0, 0.0, 0.2], [0.5, 0.5, 0.0, 0.0], [0.0, -0.5, 1.5, -0.1]], monochrome: false }); - // Written with the trailing gray record (a copy of the first row). - let w = write(&a); - assert_eq!(w[0].1[..d.len()], d[..]); - assert_eq!(w[0].1[d.len()..], i16s(&[100, 0, 0, 0, 20])[..]); - // Monochrome with only the gray record: 30/59/11. - let mut m = i16s(&[1, 1]); - m.extend(i16s(&[30, 59, 11, 0, 0])); - let Adjustment::ChannelMixer { matrix, monochrome: true } = parse(b"mixr", &m, None, Channels::Rgb) else { panic!() }; - assert_eq!(matrix[0], [0.3, 0.59, 0.11, 0.0]); - } - - fn vdesc(d: Descriptor) -> Vec { - VersionedDescriptor::new(d).to_bytes() - } - - #[test] - fn vibrance_golden_block() { - let d = vdesc(Descriptor::new("null").with("vibrance", Value::Integer(-40)).with("Strt", Value::Integer(25))); - assert_eq!(&d[..4], &[0, 0, 0, 16], "descriptor version 16"); - assert_eq!(parse(b"vibA", &d, None, Channels::Rgb), Adjustment::Vibrance { vibrance: -40.0, saturation: 25.0 }); - // Photoshop omits zero values. - let only = vdesc(Descriptor::new("null").with("Strt", Value::Integer(10))); - assert_eq!(parse(b"vibA", &only, None, Channels::Rgb), Adjustment::Vibrance { vibrance: 0.0, saturation: 10.0 }); - // Other descriptor versions are rejected (kept raw). - let mut v = d.clone(); - v[3] = 17; - assert!(matches!(parse(b"vibA", &v, None, Channels::Rgb), Adjustment::Unsupported { .. })); - } - - #[test] - fn black_white_golden_block() { - let tint = Descriptor::new("RGBC").with("Rd ", Value::Double(255.0)).with("Grn ", Value::Double(127.5)).with("Bl ", Value::Double(0.0)); - let mut desc = Descriptor::new("null"); - for (k, w) in BW_KEYS.iter().zip([10, 20, 30, 40, 50, 60]) { - desc = desc.with(k, Value::Integer(w)); - } - let d = vdesc( - desc.clone().with("useTint", Value::Boolean(true)).with("tintColor", Value::Descriptor(tint.clone())).with("bwPresetKind", Value::Integer(1)), - ); - let a = parse(b"blwh", &d, None, Channels::Rgb); - assert_eq!(a, Adjustment::BlackWhite { weights: [10.0, 20.0, 30.0, 40.0, 50.0, 60.0], tint: Some([1.0, 0.5, 0.0]) }); - // useTint off: no tint, even with a stored colour. - let off = vdesc(desc.with("useTint", Value::Boolean(false)).with("tintColor", Value::Descriptor(tint))); - assert!(matches!(parse(b"blwh", &off, None, Channels::Rgb), Adjustment::BlackWhite { tint: None, .. })); - // Missing weights take Photoshop's defaults. - let empty = vdesc(Descriptor::new("null")); - assert_eq!(parse(b"blwh", &empty, None, Channels::Rgb), Adjustment::BlackWhite { weights: BW_DEFAULT, tint: None }); - } - - #[test] - fn degenerate_adjustments_still_get_an_encoding() { - // Gradient maps with fewer than two stops render as gray (none) or one colour. - for (stops, want) in - [(vec![], vec![(0.0, [0.0; 3]), (1.0, [1.0; 3])]), (vec![(0.3, [0.2, 0.4, 0.6])], vec![(0.0, [0.2, 0.4, 0.6]), (1.0, [0.2, 0.4, 0.6])])] - { - let b = write(&Adjustment::GradientMap { stops, reverse: true, dither: false }); - let back = parse(&b[0].0, &b[0].1, None, Channels::Rgb); - let Adjustment::GradientMap { stops, reverse: true, .. } = back else { panic!("{back:?}") }; - assert_eq!(stops.len(), want.len()); - for (s, w) in stops.iter().zip(&want) { - assert!((s.0 - w.0).abs() < 1e-6 && (0..3).all(|k| (s.1[k] - w.1[k]).abs() < 1e-4), "{s:?} vs {w:?}"); - } - } - // A colour lookup without a (usable) table becomes an identity cube, without dither. - for lut in [None, Some(std::sync::Arc::new(vec![0.5; 7]))] { - let b = write(&Adjustment::ColorLookup { name: "L".into(), lut, size: 3, tetrahedral: false, dither: true }); - let back = parse(&b[0].0, &b[0].1, None, Channels::Rgb); - let Adjustment::ColorLookup { lut: Some(t), size: 2, dither: false, name, .. } = back else { panic!("{back:?}") }; - assert_eq!(name, "L"); - assert_eq!(*t, photocraft_cms::lutfile::LutFile::identity(2).data); - } - // Every kind except a malformed Unsupported key has an encoding. - assert!(write(&Adjustment::Unsupported { psd_key: "abc".into(), raw: Vec::new().into() }).is_empty()); - } - - #[test] - fn non_rgb_ignores_channel_records() { - let lc = LevelsChannel { in_black: 0.1, ..Default::default() }; - let a = Adjustment::Levels { - master: LevelsChannel::default(), - per_channel: [lc.clone(), lc.clone(), lc], - space: ToneSpace::Rgb, - black: LevelsChannel::default(), - }; - let b = write(&a); - match parse(&b[0].0, &b[0].1, None, Channels::Other) { - Adjustment::Levels { per_channel, .. } => assert_eq!(per_channel, <[LevelsChannel; 3]>::default()), - other => panic!("{other:?}"), - } - } - - #[test] - fn gray_uses_first_channel_record_for_all() { - let lc = LevelsChannel { in_black: 44.0 / 255.0, ..Default::default() }; - let a = Adjustment::Levels { - master: LevelsChannel::default(), - per_channel: [lc.clone(), Default::default(), Default::default()], - space: ToneSpace::Rgb, - black: LevelsChannel::default(), - }; - let b = write(&a); - match parse(&b[0].0, &b[0].1, None, Channels::Gray) { - Adjustment::Levels { per_channel, .. } => assert_eq!(per_channel, [lc.clone(), lc.clone(), lc]), - other => panic!("{other:?}"), - } - } - - #[test] - fn legacy_brit_without_cged() { - let a = parse(b"brit", &[0, 10, 0xff, 0xf6, 0, 127, 0], None, Channels::Rgb); - assert_eq!(a, Adjustment::BrightnessContrast { brightness: 10.0, contrast: -10.0, legacy: true }); - } -} +mod tests; diff --git a/crates/io/src/adjust_map/tests.rs b/crates/io/src/adjust_map/tests.rs new file mode 100644 index 0000000000..70727fba4f --- /dev/null +++ b/crates/io/src/adjust_map/tests.rs @@ -0,0 +1,596 @@ +use super::*; + +#[test] +fn gradient_map_v3_methods_and_smoothness() { + let classic = vec![(0.0, [0.0, 0.0, 1.0]), (1.0, [1.0, 1.0, 0.0])]; + let v1 = write_gradient_map(&classic, false, false); + // Version 3 inserts the interpolation method after reverse/dither. + let v3 = |m: &[u8; 4]| { + let mut v = v1.clone(); + v[1] = 3; + v.splice(4..4, m.iter().copied()); + v + }; + let at_t = |data: &[u8], t: f32| match parse(b"grdm", data, None, Channels::Rgb) { + Adjustment::GradientMap { stops, .. } => { + let i = stops.windows(2).position(|w| w[0].0 <= t && t <= w[1].0).unwrap(); + let (x, y) = (stops[i], stops[i + 1]); + let u = (t - x.0) / (y.0 - x.0).max(1e-6); + std::array::from_fn::(|k| x.1[k] + (y.1[k] - x.1[k]) * u) + } + other => panic!("{other:?}"), + }; + let mid = |data: &[u8]| at_t(data, 0.5); + let c = mid(&v3(b"Gcls")); + assert!((c[0] - 0.5).abs() < 1e-3 && (c[2] - 0.5).abs() < 1e-3, "classic = sRGB lerp {c:?}"); + let p = mid(&v3(b"Perc")); + assert!((p[0] - c[0]).abs() > 0.02, "perceptual differs from classic {p:?}"); + // Smoothness 100 % (4096) bends a three-stop ramp. + let three = vec![(0.0, [0.0; 3]), (0.25, [1.0, 0.0, 0.0]), (0.75, [0.0, 0.0, 1.0]), (1.0, [1.0; 3])]; + let mut smooth = write_gradient_map(&three, false, false); + // v1 header/name/count + colour stops + transparency stops + expansion count. + let at = 48 + three.len() * 20; + smooth[at..at + 2].copy_from_slice(&4096u16.to_be_bytes()); + let (a, b) = (at_t(&write_gradient_map(&three, false, false), 0.4), at_t(&smooth, 0.4)); + assert!((0..3).any(|k| (a[k] - b[k]).abs() > 1e-3), "{a:?} {b:?}"); + // Noise gradients (no colour stops) stay unsupported. + assert!(matches!(parse(b"grdm", &[0, 1, 0, 0, 0, 0, 0, 0, 0, 0], None, Channels::Rgb), Adjustment::Unsupported { .. })); +} + +#[test] +fn pencil_curves_read_and_write_the_map_form() { + // Photoshop's pencil-drawn curves: map flag 1, then 256 output bytes per channel. + let mut block = vec![1, 0, 1, 0, 0, 0, 0b1111]; + let maps: [Vec; 4] = [ + (0..=255u8).rev().collect(), + (0..=255u8).map(|k| if k < 128 { 0 } else { 255 }).collect(), + (0..=255u8).collect(), + (0..=255u8).map(|k| k / 2).collect(), + ]; + for m in &maps { + block.extend_from_slice(m); + } + let a = parse(b"curv", &block, None, Channels::Rgb); + let Adjustment::Curves { master, per_channel, pencil, .. } = &a else { panic!("{a:?}") }; + assert!(*pencil); + assert_eq!(master.len(), CURVE_MAP_LEN); + assert_eq!((master[0].output, master[255].output), (1.0, 0.0)); + assert_eq!((per_channel[0][127].output, per_channel[0][128].output), (0.0, 1.0)); + assert_eq!(write(&a)[0].1, block); +} + +/// A two-stop `grdm` (version 1) whose stops are the colour structures `a` and `b`. +fn grdm_with(a: (u16, [u16; 4]), b: (u16, [u16; 4])) -> Vec { + let mut v = write_gradient_map(&[(0.0, [0.0; 3]), (1.0, [1.0; 3])], false, false); + // Header 4 + name length 4 + "Custom\0" 14 + stop count 2; 20 bytes per stop. + for (i, (space, c)) in [a, b].into_iter().enumerate() { + let at = 24 + 20 * i + 8; + v[at..at + 2].copy_from_slice(&space.to_be_bytes()); + for (k, x) in c.iter().enumerate() { + v[at + 2 + 2 * k..at + 4 + 2 * k].copy_from_slice(&x.to_be_bytes()); + } + } + v +} + +fn ends(a: &Adjustment) -> ([f32; 3], [f32; 3]) { + match a { + Adjustment::GradientMap { stops, .. } => (stops[0].1, stops[stops.len() - 1].1), + other => panic!("{other:?}"), + } +} + +#[test] +fn gradient_map_stops_in_every_colour_space() { + use photocraft_color::{Color, ColorMode}; + let white_rgb = (0, [65535, 65535, 65535, 0]); + // CMYK, stored inverted: 65535 = no ink. Full K only. + let k_only = grdm_with((2, [65535, 65535, 65535, 0]), white_rgb); + let expected = Color { mode: ColorMode::Cmyk, c: [0.0, 0.0, 0.0, 1.0], alpha: 1.0 }.to_rgb(); + for channels in [Channels::Cmyk, Channels::Rgb, Channels::Lab] { + let a = parse(b"grdm", &k_only, None, channels); + let (first, last) = ends(&a); + assert!(first.iter().zip(expected).all(|(x, y)| (x - y).abs() < 1e-5), "{first:?} vs {expected:?}"); + assert!(first[0] < 0.4 && (first[0] - first[2]).abs() < 0.05, "K-only black is a dark neutral: {first:?}"); + assert_eq!(last, [1.0; 3]); + } + // Lab: L 50, a 0, b 0 is a neutral mid grey; L 100 white. + let lab = parse(b"grdm", &grdm_with((7, [5000, 0, 0, 0]), (7, [10000, 0, 0, 0])), None, Channels::Lab); + let (first, last) = ends(&lab); + assert!(first.iter().all(|v| (v - 0.466).abs() < 0.01), "{first:?}"); + assert!(last.iter().all(|v| *v > 0.99), "{last:?}"); + // Lab with chroma: a = +60 is reddish (a and b are signed hundredths). + let red = parse(b"grdm", &grdm_with((7, [5000, 6000, 0, 0]), white_rgb), None, Channels::Lab); + let (first, _) = ends(&red); + assert!(first[0] > first[1] + 0.2, "{first:?}"); + // Grayscale: 0..10000 is ink coverage (10000 = black). + let gray = parse(b"grdm", &grdm_with((8, [10000, 0, 0, 0]), (8, [0, 0, 0, 0])), None, Channels::Gray); + assert_eq!(ends(&gray), ([0.0; 3], [1.0; 3])); + // HSB: hue 240 degrees (2/3 of 65535), full saturation and brightness = blue. + let hsb = parse(b"grdm", &grdm_with((1, [43690, 65535, 65535, 0]), white_rgb), None, Channels::Rgb); + let (first, _) = ends(&hsb); + assert!(first[0] < 1e-3 && first[1] < 1e-3 && (first[2] - 1.0).abs() < 1e-3, "{first:?}"); + // Book colours and unknown ids are not guessed: the block stays raw. + for space in [3u16, 9, 0xFFFF] { + let d = grdm_with((space, [1, 2, 3, 4]), white_rgb); + assert!(matches!(parse(b"grdm", &d, None, Channels::Rgb), Adjustment::Unsupported { .. }), "space {space}"); + } + // Truncated stops never panic. + for n in 0..k_only.len() { + let _ = parse(b"grdm", &k_only[..n], None, Channels::Cmyk); + } +} + +#[test] +fn gradient_map_reverse_and_dither_keep_the_stops_block() { + let original = grdm_with((2, [65535, 65535, 65535, 0]), (7, [10000, 0, 0, 0])); + let Adjustment::GradientMap { stops, .. } = parse(b"grdm", &original, None, Channels::Cmyk) else { panic!() }; + let mut data = original.clone(); + let target = Adjustment::GradientMap { stops: stops.clone(), reverse: true, dither: true }; + assert!(retarget_gradient_map(&mut data, &target, Channels::Cmyk)); + assert_eq!(&data[2..4], &[1, 1]); + assert_eq!(data[4..], original[4..], "the stops keep their colour spaces"); + assert_eq!(parse(b"grdm", &data, None, Channels::Cmyk), target); + // Edited stops are not patched in. + let mut edited = stops; + edited[0].1 = [0.5; 3]; + let mut data2 = original.clone(); + let target = Adjustment::GradientMap { stops: edited, reverse: false, dither: false }; + assert!(!retarget_gradient_map(&mut data2, &target, Channels::Cmyk)); + assert_eq!(data2, original); + assert!(!retarget_gradient_map(&mut [], &target, Channels::Cmyk)); + assert!(!retarget_gradient_map(&mut data2, &Adjustment::Invert, Channels::Cmyk)); +} + +fn rt(a: Adjustment) { + let blocks = write(&a); + assert!(!blocks.is_empty(), "{a:?}"); + let cged = blocks.iter().find(|b| &b.0 == b"CgEd").map(|b| &b.1[..]); + let back = parse(&blocks[0].0, &blocks[0].1, cged, Channels::Rgb); + assert_eq!(back, a); +} + +/// Photoshop keeps the colorize triplet at byte 4 and the master triplet at byte 10, and fills +/// the inactive one with its defaults: colorize (30, 25, 0), master (0, 0, 0). The colorize hue +/// is stored signed (200 -> -160). +#[test] +fn hue2_writes_each_triplet_in_its_own_slot() { + let triplets = |a: &Adjustment| -> Vec { + let blocks = write(a); + (0..6).map(|i| bei16(&blocks[0].1, 4 + 2 * i).unwrap_or(i16::MIN)).collect() + }; + let on = Adjustment::HueSaturation { hue: 200.0, saturation: 40.0, lightness: 10.0, colorize: true, ranges: HueRange::defaults() }; + assert_eq!(triplets(&on), [-160, 40, 10, 0, 0, 0]); + let off = Adjustment::HueSaturation { hue: -30.0, saturation: 20.0, lightness: 5.0, colorize: false, ranges: HueRange::defaults() }; + assert_eq!(triplets(&off), [30, 25, 0, -30, 20, 5]); +} + +#[test] +fn roundtrips() { + rt(Adjustment::Invert); + rt(Adjustment::Threshold { level: 128.0 / 255.0 }); + rt(Adjustment::Posterize { levels: 4 }); + rt(Adjustment::BrightnessContrast { brightness: 20.0, contrast: -10.0, legacy: false }); + rt(Adjustment::BrightnessContrast { brightness: -150.0, contrast: 100.0, legacy: true }); + rt(Adjustment::HueSaturation { hue: 30.0, saturation: -20.0, lightness: 5.0, colorize: false, ranges: HueRange::defaults() }); + rt(Adjustment::HueSaturation { hue: 200.0, saturation: 50.0, lightness: 0.0, colorize: true, ranges: HueRange::defaults() }); + let mut ranges = HueRange::defaults(); + ranges[0] = HueRange { hue: 15.0, saturation: -40.0, lightness: 10.0, bounds: [-60.0, -20.0, 10.0, 30.0] }; + ranges[4].saturation = 25.0; + rt(Adjustment::HueSaturation { hue: -10.0, saturation: 0.0, lightness: 0.0, colorize: false, ranges }); + rt(Adjustment::Exposure { exposure: 1.5, offset: -0.01, gamma: 0.9 }); + let lc = |a: u16, b: u16| LevelsChannel { in_black: f32::from(a) / 255.0, in_white: f32::from(b) / 255.0, gamma: 1.2, out_black: 0.0, out_white: 1.0 }; + rt(Adjustment::Levels { master: lc(10, 240), per_channel: [lc(0, 255), lc(5, 250), lc(20, 200)], space: ToneSpace::Rgb, black: LevelsChannel::default() }); + let pts = |v: &[(u8, u8)]| v.iter().map(|&(i, o)| CurvePoint { input: f32::from(i) / 255.0, output: f32::from(o) / 255.0 }).collect::>(); + rt(Adjustment::Curves { + master: pts(&[(0, 0), (128, 150), (255, 255)]), + per_channel: [pts(&[(0, 10), (255, 255)]), pts(&[(0, 0), (255, 245)]), pts(&[(0, 0), (64, 32), (255, 255)])], + space: ToneSpace::Rgb, + black: Vec::new(), + pencil: false, + }); + // CMYK ink curves and levels keep their black record. + let ink = Adjustment::Curves { + master: pts(&[(0, 0), (255, 255)]), + per_channel: [pts(&[(0, 0), (255, 255)]), pts(&[(0, 30), (255, 255)]), pts(&[(0, 0), (255, 255)])], + space: ToneSpace::Cmyk, + black: pts(&[(0, 0), (128, 100), (255, 255)]), + pencil: false, + }; + let b = write(&ink); + assert_eq!(parse(&b[0].0, &b[0].1, None, Channels::Cmyk), ink); + let inkl = Adjustment::Levels { master: lc(0, 255), per_channel: [lc(0, 255), lc(5, 250), lc(0, 255)], space: ToneSpace::Cmyk, black: lc(30, 255) }; + let b = write(&inkl); + assert_eq!(parse(&b[0].0, &b[0].1, None, Channels::Cmyk), inkl); + rt(Adjustment::Unsupported { psd_key: "selc".into(), raw: vec![1, 2, 3].into() }); + rt(Adjustment::GradientMap { stops: vec![(0.0, [0.0, 0.0, 0.0]), (0.5, [1.0, 0.0, 0.0]), (1.0, [1.0, 1.0, 1.0])], reverse: true, dither: false }); + rt(Adjustment::GradientMap { stops: vec![(0.0, [0.0, 0.0, 0.0]), (1.0, [1.0, 1.0, 1.0])], reverse: false, dither: true }); + rt(Adjustment::SelectiveColor { relative: true, adjustments: std::array::from_fn(|r| [r as f32 * 10.0 - 40.0, 5.0, -100.0, 100.0]) }); + rt(Adjustment::SelectiveColor { relative: false, adjustments: [[0.0; 4]; 9] }); + rt(Adjustment::Vibrance { vibrance: 35.0, saturation: -12.0 }); + rt(Adjustment::Vibrance { vibrance: 0.0, saturation: 0.0 }); + rt(Adjustment::ColorBalance { shadows: [20.0, -10.0, 5.0], midtones: [-15.0, 10.0, 30.0], highlights: [0.0, 5.0, -100.0], preserve_luminosity: true }); + rt(Adjustment::ColorBalance { shadows: [0.0; 3], midtones: [100.0, 0.0, 0.0], highlights: [0.0; 3], preserve_luminosity: false }); + rt(Adjustment::BlackWhite { weights: [40.0, 60.0, 40.0, 60.0, 20.0, 80.0], tint: None }); + rt(Adjustment::BlackWhite { weights: [-200.0, 300.0, 0.0, 10.0, 90.0, 30.0], tint: Some([0.9, 0.7, 0.5]) }); + let q = |v: u16| f32::from(v) / 65535.0; + rt(Adjustment::PhotoFilter { color: [q(60000), q(30000), q(0)], density: 0.25, preserve_luminosity: true }); + rt(Adjustment::PhotoFilter { color: [q(0), q(40000), q(65535)], density: 1.0, preserve_luminosity: false }); + rt(Adjustment::ChannelMixer { matrix: [[0.5, 0.3, 0.2, 0.0], [0.1, 0.8, 0.1, 0.05], [0.0, 0.2, 0.9, -0.05]], monochrome: false }); + rt(Adjustment::ChannelMixer { matrix: [[0.4, 0.4, 0.2, 0.1], [0.0, 1.0, 0.0, 0.0], [-2.0, 0.0, 2.0, 0.0]], monochrome: true }); + let id = photocraft_cms::lutfile::LutFile::identity(5); + rt(Adjustment::ColorLookup { name: "Look.cube".into(), lut: Some(std::sync::Arc::new(id.data)), size: 5, tetrahedral: false, dither: true }); +} + +#[test] +fn selective_color_synthetic_block() { + // Absolute; reds = (+10, -20, +30, -40), blacks = (0, 0, 0, 25). + let mut d = vec![0, 1, 0, 1]; + d.extend([0u8; 8]); + for r in 0..9 { + let rec: [i16; 4] = match r { + 0 => [10, -20, 30, -40], + 8 => [0, 0, 0, 25], + _ => [0; 4], + }; + for x in rec { + d.extend(x.to_be_bytes()); + } + } + let a = parse(b"selc", &d, None, Channels::Rgb); + let Adjustment::SelectiveColor { relative, adjustments } = &a else { panic!("{a:?}") }; + assert!(!relative); + assert_eq!(adjustments[0], [10.0, -20.0, 30.0, -40.0]); + assert_eq!(adjustments[8], [0.0, 0.0, 0.0, 25.0]); + // Written back byte-exact. + assert_eq!(write(&a)[0].1, d); +} + +#[test] +fn color_lookup_synthetic_block() { + let cube = b"TITLE \"t\"\nLUT_3D_SIZE 2\n0 0 0\n1 0 0\n0 1 0\n1 1 0\n0 0 1\n1 0 1\n0 1 1\n1 1 1\n"; + let en = |t: &str, val: &str| Value::Enumerated { type_id: photocraft_psd::descriptor::Id::new(t), value: photocraft_psd::descriptor::Id::new(val) }; + let desc = Descriptor::new("null") + .with("lookupType", en("colorLookupType", "3DLUT")) + .with("NM ", Value::Text(photocraft_psd::descriptor::UnicodeString::new_nul("Id"))) + .with("Dthr", Value::Boolean(true)) + .with("LUTFormat", en("LUTFormatType", "LUTFormatCUBE")) + .with("LUT3DFileData", Value::RawData(cube.to_vec())); + let mut d = vec![0, 1]; + d.extend(VersionedDescriptor::new(desc).to_bytes()); + let a = parse(b"clrL", &d, None, Channels::Rgb); + let Adjustment::ColorLookup { name, lut: Some(t), size: 2, dither: true, .. } = &a else { panic!("{a:?}") }; + assert_eq!(name, "Id"); + assert_eq!(&t[..6], &[0.0, 0.0, 0.0, 1.0, 0.0, 0.0]); + // A profile-based lookup (no table) is preserved raw. + let mut p = vec![0, 1]; + p.extend(VersionedDescriptor::new(Descriptor::new("null").with("lookupType", en("colorLookupType", "abstractProfile"))).to_bytes()); + assert!(matches!(parse(b"clrL", &p, None, Channels::Rgb), Adjustment::Unsupported { .. })); + // Each way a lookup can't be read has a reason for the import warning (#1763). + assert_eq!(unreadable_reason(b"clrL", &d), None); + assert!(unreadable_reason(b"clrL", &p).unwrap().contains("colour profile")); + assert!(unreadable_reason(b"clrL", &[0]).unwrap().contains("truncated")); + assert!(unreadable_reason(b"clrL", &[0, 2, 0, 0]).unwrap().contains("version 2")); + assert!(unreadable_reason(b"clrL", &[0, 1, 9]).unwrap().contains("unreadable settings")); + let bad = Descriptor::new("null").with("LUTFormat", en("LUTFormatType", "LUTFormat3DL")).with("LUT3DFileData", Value::RawData(b"not a lut".to_vec())); + let mut b = vec![0, 1]; + b.extend(VersionedDescriptor::new(bad).to_bytes()); + assert!(matches!(parse(b"clrL", &b, None, Channels::Rgb), Adjustment::Unsupported { .. })); + assert!(unreadable_reason(b"clrL", &b).unwrap().contains("3DL LUT can't be read"), "{:?}", unreadable_reason(b"clrL", &b)); + assert_eq!(label(b"clrL"), "Color Lookup"); + assert!(matches!(parse(b"clrL", &[0, 1, 9], None, Channels::Rgb), Adjustment::Unsupported { .. })); + assert!(matches!(parse(b"selc", &[0, 1, 0, 0], None, Channels::Rgb), Adjustment::Unsupported { .. })); +} + +fn cube_lookup_block(cube: &[u8]) -> Vec { + let en = |t: &str, val: &str| Value::Enumerated { type_id: photocraft_psd::descriptor::Id::new(t), value: photocraft_psd::descriptor::Id::new(val) }; + let desc = Descriptor::new("null") + .with("LUTFormat", en("LUTFormatType", "LUTFormatCUBE")) + .with("LUT3DFileName", Value::Text(photocraft_psd::descriptor::UnicodeString::new_nul("domain.cube"))) + .with("LUT3DFileData", Value::RawData(cube.to_vec())); + let mut block = vec![0, 1]; + block.extend(VersionedDescriptor::new(desc).to_bytes()); + block +} + +fn identity_cube(domain: &str) -> Vec { + format!("{domain}LUT_3D_SIZE 2\n0 0 0\n1 0 0\n0 1 0\n1 1 0\n0 0 1\n1 0 1\n0 1 1\n1 1 1\n").into_bytes() +} + +#[test] +fn color_lookup_custom_domains_are_kept_unsupported() { + let domains = ["DOMAIN_MIN 0 0 0\nDOMAIN_MAX 0.5 0.5 0.5\n", "DOMAIN_MIN 0 0.25 0\nDOMAIN_MAX 1 0.75 1\n", "LUT_3D_INPUT_RANGE 0 0.5\n"]; + for domain in domains { + let raw = cube_lookup_block(&identity_cube(domain)); + let Adjustment::Unsupported { psd_key, raw: kept } = parse(b"clrL", &raw, None, Channels::Rgb) else { + panic!("custom LUT domain was applied instead of kept unsupported: {domain}") + }; + assert_eq!(psd_key, "clrL"); + assert_eq!(*kept, *raw); + let reason = unreadable_reason(b"clrL", &raw).expect("custom domain has an explanation"); + assert!(reason.contains("DOMAIN_MIN") && reason.contains("DOMAIN_MAX"), "{reason}"); + assert!(reason.to_ascii_lowercase().contains("not supported"), "{reason}"); + } +} + +#[test] +fn color_lookup_default_domains_stay_supported() { + for domain in ["", "DOMAIN_MIN 0 0 0\nDOMAIN_MAX 1 1 1\n"] { + let raw = cube_lookup_block(&identity_cube(domain)); + assert!(matches!(parse(b"clrL", &raw, None, Channels::Rgb), Adjustment::ColorLookup { size: 2, .. })); + assert_eq!(unreadable_reason(b"clrL", &raw), None); + } +} + +#[test] +fn malformed_falls_back_to_unsupported() { + assert!(matches!(parse(b"levl", &[0, 2, 1], None, Channels::Rgb), Adjustment::Unsupported { .. })); + assert!(matches!(parse(b"curv", &[0, 0, 9], None, Channels::Rgb), Adjustment::Unsupported { .. })); + assert!(matches!(parse(b"thrs", &[], None, Channels::Rgb), Adjustment::Unsupported { .. })); + assert!(matches!(parse(b"blnc", &[0; 18], None, Channels::Rgb), Adjustment::Unsupported { .. })); + assert!(matches!(parse(b"vibA", &[0, 0, 0, 15, 0], None, Channels::Rgb), Adjustment::Unsupported { .. })); + assert!(matches!(parse(b"blwh", &[], None, Channels::Rgb), Adjustment::Unsupported { .. })); + assert!(matches!(parse(b"mixr", &[0, 2, 0, 0], None, Channels::Rgb), Adjustment::Unsupported { .. })); + // A CMYK mixer (black source used) stays raw in CMYK documents; our own RGB layout maps. + let mut cmyk = i16s(&[1, 0]); + for r in 0..4 { + cmyk.extend(i16s(&std::array::from_fn::(|k| if k == r { 100 } else { 0 }))); + } + assert!(matches!(parse(b"mixr", &cmyk, None, Channels::Cmyk), Adjustment::Unsupported { .. })); + assert!(matches!(parse(b"mixr", &cmyk, None, Channels::Other), Adjustment::Unsupported { .. })); + let ours = write(&Adjustment::ChannelMixer { matrix: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]], monochrome: false }); + assert!(matches!(parse(b"mixr", &ours[0].1, None, Channels::Cmyk), Adjustment::ChannelMixer { .. })); + assert!(matches!(parse(b"mixr", &ours[0].1, None, Channels::Other), Adjustment::ChannelMixer { .. })); + assert!(matches!(parse(b"mixr", &[0, 1, 0, 0, 0, 100], None, Channels::Rgb), Adjustment::Unsupported { .. })); + // Photo Filter: unknown version, HSB colour space, out-of-range version-3 XYZ, truncated. + assert!(matches!(parse(b"phfl", &[0, 4, 0, 0], None, Channels::Rgb), Adjustment::Unsupported { .. })); + assert!(matches!(parse(b"phfl", &[0, 2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 25, 1], None, Channels::Rgb), Adjustment::Unsupported { .. })); + for bad in [[200_000u32, 0, 0], [0, u32::MAX, 0]] { + let mut xyz = vec![0, 3]; + for x in bad { + xyz.extend(x.to_be_bytes()); + } + xyz.extend([0, 0, 0, 25, 1]); + assert!(matches!(parse(b"phfl", &xyz, None, Channels::Rgb), Adjustment::Unsupported { .. })); + } + assert!(matches!(parse(b"phfl", &[0, 2, 0, 0, 0, 0], None, Channels::Rgb), Adjustment::Unsupported { .. })); + // Arbitrary bytes never panic, whatever the key. + for key in ADJUSTMENT_KEYS { + for len in 0..64usize { + let d: Vec = (0..len).map(|i| (i * 37 + len) as u8).collect(); + let _ = parse(key, &d, Some(&d), Channels::Rgb); + let _ = parse(key, &d, None, Channels::Other); + } + } +} + +fn i16s(v: &[i16]) -> Vec { + v.iter().flat_map(|x| x.to_be_bytes()).collect() +} + +/// Hand-built blocks laid out per the Adobe spec (no file written by Photoshop involved). +#[test] +fn color_balance_golden_block() { + let mut d = i16s(&[-30, 20, 0, 10, -5, 100, 0, 0, -100]); + d.extend([1, 0]); + let a = parse(b"blnc", &d, None, Channels::Rgb); + assert_eq!( + a, + Adjustment::ColorBalance { shadows: [-30.0, 20.0, 0.0], midtones: [10.0, -5.0, 100.0], highlights: [0.0, 0.0, -100.0], preserve_luminosity: true } + ); + assert_eq!(write(&a), vec![(*b"blnc", d.clone())]); + // The 19-byte form (no trailing pad) parses the same. + assert_eq!(parse(b"blnc", &d[..19], None, Channels::Rgb), a); +} + +#[test] +fn photo_filter_golden_blocks() { + // Version 2, RGB colour structure (65535, 32768, 0), density 40 %, preserve luminosity. + let mut v2 = i16s(&[2, 0]); + v2.extend([0xff, 0xff, 0x80, 0x00, 0, 0, 0, 0]); + v2.extend(40u32.to_be_bytes()); + v2.extend([1, 0, 0, 0]); + assert_eq!(v2.len(), 20, "Photo Filter must occupy 20 bytes"); + assert_eq!(&v2[17..], &[0, 0, 0], "padding is included inside the block length"); + let a = parse(b"phfl", &v2, None, Channels::Rgb); + let Adjustment::PhotoFilter { color, density, preserve_luminosity: true } = a else { panic!("{a:?}") }; + assert_eq!(color, [1.0, 32768.0 / 65535.0, 0.0]); + assert_eq!(density, 0.4); + assert_eq!(write(&a)[0].1, v2, "version 2 RGB is written back byte-exact"); + // Older PhotoCraft files used only one padding byte (18 bytes); keep importing them, + // but never produce that Photoshop-incompatible length again. + assert_eq!(parse(b"phfl", &v2[..18], None, Channels::Rgb), a); + for preserve_luminosity in [false, true] { + for density in [0.0, 0.14, 1.0] { + let adjustment = Adjustment::PhotoFilter { color: [0.8, 0.4, 0.2], density, preserve_luminosity }; + let blocks = write(&adjustment); + assert_eq!(blocks.len(), 1); + assert_eq!(blocks[0].0, *b"phfl"); + assert_eq!(blocks[0].1.len(), 20); + assert_eq!(&blocks[0].1[17..], &[0, 0, 0]); + let Adjustment::PhotoFilter { color, density: read_density, preserve_luminosity: read_preserve } = + parse(b"phfl", &blocks[0].1, None, Channels::Rgb) + else { + panic!("written phfl must parse") + }; + assert!(color.iter().zip([0.8, 0.4, 0.2]).all(|(got, expected)| (got - expected).abs() <= 1.0 / 65535.0)); + assert!((read_density - density).abs() < 0.00001); + assert_eq!(read_preserve, preserve_luminosity); + } + } + // Version 2, Lab colour structure: L 50, a 0, b 0 is mid gray. + let mut lab = i16s(&[2, 7, 5000, 0, 0, 0]); + lab.extend(25u32.to_be_bytes()); + lab.push(0); + let Adjustment::PhotoFilter { color, density, preserve_luminosity: false } = parse(b"phfl", &lab, None, Channels::Rgb) else { panic!() }; + assert!(color.iter().all(|c| (c - 0.466).abs() < 0.01), "{color:?}"); + assert_eq!(density, 0.25); + // Version 3: XYZ relative to the D50 white, 1.0 = 32768. White is (32768, 32768, 32768). + let v3 = phfl_v3([32768, 32768, 32768], 100, true); + let Adjustment::PhotoFilter { color, density, preserve_luminosity: true } = parse(b"phfl", &v3, None, Channels::Rgb) else { panic!() }; + assert!(color.iter().all(|c| (c - 1.0).abs() < 0.005), "{color:?}"); + assert_eq!(density, 1.0); + // Photoshop's Warming Filter (85) preset, sRGB #EC8A00: the CS2 file of #4940 stores it + // relative to the D50 white as (15548, 12029, 0). + let Adjustment::PhotoFilter { color, density, preserve_luminosity: false } = parse(b"phfl", &phfl_v3([15548, 12029, 0], 25, false), None, Channels::Rgb) + else { + panic!() + }; + let expected = [0xecu8, 0x8a, 0x00].map(|v| f32::from(v) / 255.0); + assert!(color.iter().zip(expected).all(|(got, want)| (got - want).abs() < 1.5 / 255.0), "{color:?}"); + assert_eq!(density, 0.25); + // The block from #3777 (Photoshop CS2): the Yellow filter preset, #F9E31C, density 63 %. + let issue = [0, 3, 0, 0, 0x5e, 0x7f, 0, 0, 0x61, 0xaa, 0, 0, 0x0e, 0xf3, 0, 0, 0, 0x3f, 1, 0]; + let Adjustment::PhotoFilter { color, density, preserve_luminosity: true } = parse(b"phfl", &issue, None, Channels::Rgb) else { panic!() }; + let expected = [0xf9u8, 0xe3, 0x1c].map(|v| f32::from(v) / 255.0); + assert!(color.iter().zip(expected).all(|(got, want)| (got - want).abs() < 1.5 / 255.0), "{color:?}"); + assert_eq!(density, 0.63); + // Cooling Filter (82) from #4940: a deep blue outside sRGB; its Z stays under the 2.0 + // garbage guard and the colour clamps to (0, 181, 255). + let Adjustment::PhotoFilter { color: cooling, density, preserve_luminosity: true } = + parse(b"phfl", &phfl_v3([5327, 9584, 65357], 72, true), None, Channels::Rgb) + else { + panic!("Cooling Filter (82) must parse") + }; + let expected = [0u8, 181, 255].map(|v| f32::from(v) / 255.0); + assert!(cooling.iter().zip(expected).all(|(got, want)| (got - want).abs() < 1.5 / 255.0), "{cooling:?}"); + assert_eq!(density, 0.72); + // The 19-byte form (no trailing pad) parses the same. + assert_eq!(parse(b"phfl", &issue[..19], None, Channels::Rgb), parse(b"phfl", &issue, None, Channels::Rgb)); + // Version 3 is read, never written: an edited filter is saved as version 2 and keeps its colour. + let a = parse(b"phfl", &issue, None, Channels::Rgb); + let w = write(&a); + assert_eq!(&w[0].1[..2], &[0, 2]); + let Adjustment::PhotoFilter { color: back, .. } = parse(b"phfl", &w[0].1, None, Channels::Rgb) else { panic!() }; + assert!(back.iter().zip(color).all(|(b, c)| (b - c).abs() <= 1.0 / 65535.0)); +} + +/// A version 3 Photo Filter block: version, three u32 XYZ components, density, flag, pad. +fn phfl_v3(xyz: [u32; 3], density: u32, preserve_luminosity: bool) -> Vec { + let mut d = vec![0, 3]; + for x in xyz { + d.extend(x.to_be_bytes()); + } + d.extend(density.to_be_bytes()); + d.extend([u8::from(preserve_luminosity), 0]); + d +} + +#[test] +fn channel_mixer_golden_blocks() { + // RGB: red = 100 % R + 20 % const; green = 50 % R + 50 % G; blue = -50 % G + 150 % B - 10 % const. + let mut d = i16s(&[1, 0]); + d.extend(i16s(&[100, 0, 0, 0, 20, 50, 50, 0, 0, 0, 0, -50, 150, 0, -10])); + let a = parse(b"mixr", &d, None, Channels::Rgb); + assert_eq!(a, Adjustment::ChannelMixer { matrix: [[1.0, 0.0, 0.0, 0.2], [0.5, 0.5, 0.0, 0.0], [0.0, -0.5, 1.5, -0.1]], monochrome: false }); + // Written with the trailing gray record (a copy of the first row). + let w = write(&a); + assert_eq!(w[0].1[..d.len()], d[..]); + assert_eq!(w[0].1[d.len()..], i16s(&[100, 0, 0, 0, 20])[..]); + // Monochrome with only the gray record: 30/59/11. + let mut m = i16s(&[1, 1]); + m.extend(i16s(&[30, 59, 11, 0, 0])); + let Adjustment::ChannelMixer { matrix, monochrome: true } = parse(b"mixr", &m, None, Channels::Rgb) else { panic!() }; + assert_eq!(matrix[0], [0.3, 0.59, 0.11, 0.0]); +} + +fn vdesc(d: Descriptor) -> Vec { + VersionedDescriptor::new(d).to_bytes() +} + +#[test] +fn vibrance_golden_block() { + let d = vdesc(Descriptor::new("null").with("vibrance", Value::Integer(-40)).with("Strt", Value::Integer(25))); + assert_eq!(&d[..4], &[0, 0, 0, 16], "descriptor version 16"); + assert_eq!(parse(b"vibA", &d, None, Channels::Rgb), Adjustment::Vibrance { vibrance: -40.0, saturation: 25.0 }); + // Photoshop omits zero values. + let only = vdesc(Descriptor::new("null").with("Strt", Value::Integer(10))); + assert_eq!(parse(b"vibA", &only, None, Channels::Rgb), Adjustment::Vibrance { vibrance: 0.0, saturation: 10.0 }); + // Other descriptor versions are rejected (kept raw). + let mut v = d.clone(); + v[3] = 17; + assert!(matches!(parse(b"vibA", &v, None, Channels::Rgb), Adjustment::Unsupported { .. })); +} + +#[test] +fn black_white_golden_block() { + let tint = Descriptor::new("RGBC").with("Rd ", Value::Double(255.0)).with("Grn ", Value::Double(127.5)).with("Bl ", Value::Double(0.0)); + let mut desc = Descriptor::new("null"); + for (k, w) in BW_KEYS.iter().zip([10, 20, 30, 40, 50, 60]) { + desc = desc.with(k, Value::Integer(w)); + } + let d = + vdesc(desc.clone().with("useTint", Value::Boolean(true)).with("tintColor", Value::Descriptor(tint.clone())).with("bwPresetKind", Value::Integer(1))); + let a = parse(b"blwh", &d, None, Channels::Rgb); + assert_eq!(a, Adjustment::BlackWhite { weights: [10.0, 20.0, 30.0, 40.0, 50.0, 60.0], tint: Some([1.0, 0.5, 0.0]) }); + // useTint off: no tint, even with a stored colour. + let off = vdesc(desc.with("useTint", Value::Boolean(false)).with("tintColor", Value::Descriptor(tint))); + assert!(matches!(parse(b"blwh", &off, None, Channels::Rgb), Adjustment::BlackWhite { tint: None, .. })); + // Missing weights take Photoshop's defaults. + let empty = vdesc(Descriptor::new("null")); + assert_eq!(parse(b"blwh", &empty, None, Channels::Rgb), Adjustment::BlackWhite { weights: BW_DEFAULT, tint: None }); +} + +#[test] +fn degenerate_adjustments_still_get_an_encoding() { + // Gradient maps with fewer than two stops render as gray (none) or one colour. + for (stops, want) in + [(vec![], vec![(0.0, [0.0; 3]), (1.0, [1.0; 3])]), (vec![(0.3, [0.2, 0.4, 0.6])], vec![(0.0, [0.2, 0.4, 0.6]), (1.0, [0.2, 0.4, 0.6])])] + { + let b = write(&Adjustment::GradientMap { stops, reverse: true, dither: false }); + let back = parse(&b[0].0, &b[0].1, None, Channels::Rgb); + let Adjustment::GradientMap { stops, reverse: true, .. } = back else { panic!("{back:?}") }; + assert_eq!(stops.len(), want.len()); + for (s, w) in stops.iter().zip(&want) { + assert!((s.0 - w.0).abs() < 1e-6 && (0..3).all(|k| (s.1[k] - w.1[k]).abs() < 1e-4), "{s:?} vs {w:?}"); + } + } + // A colour lookup without a (usable) table becomes an identity cube, without dither. + for lut in [None, Some(std::sync::Arc::new(vec![0.5; 7]))] { + let b = write(&Adjustment::ColorLookup { name: "L".into(), lut, size: 3, tetrahedral: false, dither: true }); + let back = parse(&b[0].0, &b[0].1, None, Channels::Rgb); + let Adjustment::ColorLookup { lut: Some(t), size: 2, dither: false, name, .. } = back else { panic!("{back:?}") }; + assert_eq!(name, "L"); + assert_eq!(*t, photocraft_cms::lutfile::LutFile::identity(2).data); + } + // Every kind except a malformed Unsupported key has an encoding. + assert!(write(&Adjustment::Unsupported { psd_key: "abc".into(), raw: Vec::new().into() }).is_empty()); +} + +#[test] +fn non_rgb_ignores_channel_records() { + let lc = LevelsChannel { in_black: 0.1, ..Default::default() }; + let a = Adjustment::Levels { + master: LevelsChannel::default(), + per_channel: [lc.clone(), lc.clone(), lc], + space: ToneSpace::Rgb, + black: LevelsChannel::default(), + }; + let b = write(&a); + match parse(&b[0].0, &b[0].1, None, Channels::Other) { + Adjustment::Levels { per_channel, .. } => assert_eq!(per_channel, <[LevelsChannel; 3]>::default()), + other => panic!("{other:?}"), + } +} + +#[test] +fn gray_uses_first_channel_record_for_all() { + let lc = LevelsChannel { in_black: 44.0 / 255.0, ..Default::default() }; + let a = Adjustment::Levels { + master: LevelsChannel::default(), + per_channel: [lc.clone(), Default::default(), Default::default()], + space: ToneSpace::Rgb, + black: LevelsChannel::default(), + }; + let b = write(&a); + match parse(&b[0].0, &b[0].1, None, Channels::Gray) { + Adjustment::Levels { per_channel, .. } => assert_eq!(per_channel, [lc.clone(), lc.clone(), lc]), + other => panic!("{other:?}"), + } +} + +#[test] +fn legacy_brit_without_cged() { + let a = parse(b"brit", &[0, 10, 0xff, 0xf6, 0, 127, 0], None, Channels::Rgb); + assert_eq!(a, Adjustment::BrightnessContrast { brightness: 10.0, contrast: -10.0, legacy: true }); +} diff --git a/crates/io/src/blocks.rs b/crates/io/src/blocks.rs index 0cfe0b5e8e..c280747611 100644 --- a/crates/io/src/blocks.rs +++ b/crates/io/src/blocks.rs @@ -916,855 +916,7 @@ pub fn effects_enabled(lfx2: &[u8]) -> bool { } #[cfg(test)] -mod tests { - use super::*; - - fn noise_gradient_fill(min: [i32; 4], max: [i32; 4], add_transparency: bool) -> Descriptor { - let values = |v: [i32; 4]| Value::List(v.into_iter().map(Value::Integer).collect()); - let gradient = Descriptor::new("Grdn") - .with("GrdF", Value::Enumerated { type_id: Id::new("GrdF"), value: Id::new("ClNs") }) - .with("ClrS", Value::Enumerated { type_id: Id::new("ClrS"), value: Id::new("RGBC") }) - .with("ShTr", Value::Boolean(add_transparency)) - .with("VctC", Value::Boolean(true)) - .with("RndS", Value::Integer(9052369)) - .with("Smth", Value::Integer(2048)) - .with("Mnm ", values(min)) - .with("Mxm ", values(max)); - Descriptor::new("null").with("Grad", Value::Descriptor(gradient)) - } - - #[test] - fn constant_rgb_noise_fill_uses_its_exact_colour() { - use photocraft_doc::Fill; - let fill = fill_from_desc(b"GdFl", &noise_gradient_fill([50, 25, 0, 0], [50, 25, 0, 100], false)); - let Some(Fill::Gradient { stops, .. }) = fill else { panic!("constant noise gradient") }; - assert_eq!(stops, vec![(0.0, Color::rgb(0.5, 0.25, 0.0)), (1.0, Color::rgb(0.5, 0.25, 0.0))]); - } - - #[test] - fn variable_or_transparent_noise_stays_a_fill_with_the_placeholder_ramp() { - use photocraft_doc::Fill; - // Photoshop's default Noise gradient (min 0, max 100) and a transparent variant: no - // exact colour is provable, but the fill must parse — the layer keeps its type, its - // stored pixels (`fill_cache`) and its raw `GdFl` block. Only the uncached preview - // shows the placeholder ramp. - for descriptor in [noise_gradient_fill([0, 0, 0, 0], [100, 100, 100, 100], false), noise_gradient_fill([50, 25, 0, 0], [50, 25, 0, 100], true)] { - let Some(Fill::Gradient { stops, .. }) = fill_from_desc(b"GdFl", &descriptor) else { panic!("variable noise gradient must stay a fill layer") }; - assert_eq!(stops, vec![(0.0, Color::BLACK), (1.0, Color::WHITE)]); - } - } - - /// psd-tools layers-minimal/gradient-fill.psd ("Color to Transparent", no stored pixels): a - /// gradient fill's opacity stops reach the model (as its opacity stops; written from stop - /// alpha) and survive a write; the ramp's alpha follows them. - #[test] - fn gradient_fill_opacity_stops_become_alpha() { - use photocraft_color::Color; - use photocraft_doc::{Fill, GradientStyle}; - let red = Color::rgba(1.0, 0.0, 0.0, 1.0); - let f = Fill::gradient(vec![(0.0, red), (1.0, Color { alpha: 0.0, ..red })], 90.0, 1.0, GradientStyle::Linear, false); - let (k, data) = super::write_fill(&f); - let back = super::parse_fill(&k, &data).unwrap(); - let Fill::Gradient { stops, opacity_stops, .. } = &back else { panic!("gradient") }; - assert_eq!(opacity_stops, &vec![(0.0, 1.0), (1.0, 0.0)]); - assert!(stops.iter().all(|s| s.1.c[0] == 1.0 && s.1.c[1] == 0.0)); - let ramp = photocraft_compose::gradient_fill::Ramp::new(&back).unwrap(); - assert_eq!(ramp.sample(0.0)[3], 1.0); - assert!(ramp.sample(1.0)[3] < 0.01); - // Opaque gradients come back without opacity stops. - let (k, data) = super::write_fill(&Fill::gradient(vec![(0.0, red), (1.0, Color::WHITE)], 0.0, 1.0, GradientStyle::Linear, false)); - let Some(Fill::Gradient { opacity_stops, .. }) = super::parse_fill(&k, &data) else { panic!("gradient") }; - assert!(opacity_stops.is_empty()); - } - - /// Photoshop 27.11 stores a gradient's method as the enum `gradientsInterpolationMethod` - /// (seen in gradient fill layers saved by scripted Photoshop): a black→white Linear gradient - /// is at 188 of 255 halfway (measured), where Classic gives 128. The key used to be read as - /// `gs99`, which Photoshop doesn't write, so every gradient opened as Classic. - #[test] - fn gradient_fill_reads_the_interpolation_method() { - use photocraft_color::Color; - use photocraft_doc::{Fill, GradientStyle}; - use photocraft_psd::descriptor::{Id, Value}; - let f = Fill::gradient(vec![(0.0, Color::BLACK), (1.0, Color::WHITE)], 0.0, 1.0, GradientStyle::Linear, false); - let (k, data) = super::write_fill(&f); - let d = super::parse_prefix_versioned(&data).unwrap(); - let mid = |code: &str| { - let d = - d.clone().with("gradientsInterpolationMethod", Value::Enumerated { type_id: Id::new("gradientInterpolationMethodType"), value: Id::new(code) }); - let back = super::fill_from_desc(&k, &d).unwrap(); - let ramp = photocraft_compose::gradient_fill::Ramp::new(&back).unwrap(); - (ramp.sample(0.5)[0] * 255.0).round() - }; - assert_eq!(mid("Gcls"), 128.0); - assert!((mid("Lnr ") - 188.0).abs() <= 1.0, "Linear: {}", mid("Lnr ")); - assert!((mid("Perc") - 99.0).abs() <= 2.0, "Perceptual: {}", mid("Perc")); - assert!((mid("Smoo") - 99.0).abs() <= 2.0, "Smooth: {}", mid("Smoo")); - } - - #[test] - fn lab_descriptor_colours_round_trip() { - use photocraft_color::ColorMode; - use photocraft_psd::descriptor::{Descriptor, Value}; - let d = Descriptor::new("LbCl").with("Lmnc", Value::Double(19.07)).with("A ", Value::Double(52.29)).with("B ", Value::Double(-85.08)); - let c = super::color_from_desc(&d).unwrap(); - assert_eq!(c.mode, ColorMode::Lab); - assert!((c.c[0] - 0.1907).abs() < 1e-5 && (c.c[1] * 255.0 - 128.0 - 52.29).abs() < 1e-3 && (c.c[2] * 255.0 - 128.0 + 85.08).abs() < 1e-3); - let back = super::color_from_desc(&super::color_to_desc(&c)).unwrap(); - assert_eq!(back.mode, ColorMode::Lab); - for i in 0..3 { - assert!((back.c[i] - c.c[i]).abs() < 1e-6); - } - // Missing components are rejected, not defaulted. - assert!(super::color_from_desc(&Descriptor::new("LbCl").with("Lmnc", Value::Double(50.0))).is_none()); - } - - /// Colours stored as HSB (`HSBC`: `H ` an angle in degrees, `Strt`/`Brgh` 0..100), as in - /// psd-tools `stroke-color-descriptors-hsb-with-rgb-mode.psd`, used to be dropped (#6774). - #[test] - fn hsb_descriptor_colours_parse() { - use photocraft_doc::Fill; - use photocraft_psd::descriptor::{Descriptor, Value}; - let hsb = |h: f64, s: f64, b: f64| { - Descriptor::new("HSBC").with("H ", Value::UnitFloat { unit: *b"#Ang", value: h }).with("Strt", Value::Double(s)).with("Brgh", Value::Double(b)) - }; - let close = |c: [f32; 3], e: [f32; 3]| c.iter().zip(e).all(|(a, b)| (a - b).abs() < 1e-5); - let green = super::color_from_desc(&hsb(120.0, 100.0, 100.0)).unwrap().to_rgb(); - assert!(close(green, [0.0, 1.0, 0.0]), "{green:?}"); - let white = super::color_from_desc(&hsb(0.0, 0.0, 100.0)).unwrap().to_rgb(); - assert!(close(white, [1.0, 1.0, 1.0]), "{white:?}"); - let half = super::color_from_desc(&hsb(240.0, 50.0, 50.0)).unwrap().to_rgb(); - assert!(close(half, [0.25, 0.25, 0.5]), "{half:?}"); - // A solid fill (`SoCo`) with an HSB colour is read, not lost. - let soco = Descriptor::new("null").with("Clr ", Value::Descriptor(hsb(0.0, 100.0, 100.0))); - let Some(Fill::Solid(c)) = super::fill_from_desc(b"SoCo", &soco) else { panic!("solid fill") }; - assert!(close(c.to_rgb(), [1.0, 0.0, 0.0]), "{:?}", c.to_rgb()); - // Missing components are rejected, not defaulted. - assert!(super::color_from_desc(&Descriptor::new("HSBC").with("Strt", Value::Double(50.0))).is_none()); - } - - #[test] - fn color_descriptor_keeps_photocraft_alpha() { - use photocraft_color::Color; - use photocraft_doc::Fill; - let c = Color::rgba(0.2, 0.4, 0.6, 0.25); - let (k, d) = super::fill_to_desc(&Fill::Solid(c)); - let Fill::Solid(back) = super::fill_from_desc(&k, &d).unwrap() else { panic!("solid") }; - assert!((back.alpha - 0.25).abs() < 1e-5); - assert!((back.to_rgb()[0] - 0.2).abs() < 1e-3); - let (k, d) = super::fill_to_desc(&Fill::Solid(Color::rgb(1.0, 0.0, 0.0))); - let Fill::Solid(opaque) = super::fill_from_desc(&k, &d).unwrap() else { panic!("solid") }; - assert!((opaque.alpha - 1.0).abs() < 1e-6); - assert!(super::color_to_desc(&c).get("pcAl").is_none(), "generic colour descriptors have no pcAl"); - } - - #[test] - fn non_finite_photocraft_alpha_is_ignored() { - use photocraft_color::Color; - for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { - let d = super::color_to_desc(&Color::rgb(0.2, 0.4, 0.6)).with("pcAl", Value::Double(bad)); - let c = super::color_from_desc(&d).unwrap(); - assert_eq!(c.alpha, 1.0, "pcAl {bad}"); - } - let d = super::color_to_desc(&Color::rgb(0.2, 0.4, 0.6)).with("pcAl", Value::Double(0.5)); - assert!((super::color_from_desc(&d).unwrap().alpha - 0.5).abs() < 1e-6); - } - - #[test] - fn gradient_stop_alpha_round_trips_once() { - use photocraft_color::Color; - use photocraft_doc::Fill; - let fill = Fill::Gradient { - stops: vec![(0.0, Color::rgba(1.0, 0.0, 0.0, 0.5)), (1.0, Color::WHITE)], - angle: 90.0, - scale: 1.0, - style: photocraft_doc::GradientStyle::Linear, - reverse: false, - opacity_stops: vec![], - midpoints: vec![], - offset: (0.0, 0.0), - dither: false, - align: true, - }; - let (k, d) = super::fill_to_desc(&fill); - let Fill::Gradient { stops, opacity_stops, .. } = super::fill_from_desc(&k, &d).unwrap() else { panic!("grad") }; - assert!((stops[0].1.alpha - 1.0).abs() < 1e-4, "colour alpha lives in Trns, not the stop colour"); - assert!(opacity_stops.iter().any(|(_, a)| (*a - 0.5).abs() < 1e-3), "{opacity_stops:?}"); - } - - #[test] - fn blending_ranges_map_to_blend_if() { - use photocraft_doc::{BlendIf, BlendRange}; - use photocraft_psd::layer::BlendingRanges; - // Full ranges (what every layer without Blend If carries) → the default setting. - assert_eq!(super::blend_if_from_ranges(&BlendingRanges::full(3)), BlendIf::default()); - assert_eq!(super::blend_if_from_ranges(&BlendingRanges::default()), BlendIf::default()); - // Gray: This Layer black split 10/40; Blue (entry 3): Underlying white at 200. - let mut data = BlendingRanges::full(3).data; - data[..4].copy_from_slice(&[10, 40, 255, 255]); - data[3 * 8 + 4..3 * 8 + 8].copy_from_slice(&[0, 0, 200, 200]); - let b = super::blend_if_from_ranges(&BlendingRanges { data: data.clone() }); - assert_eq!(b.get(0), [BlendRange { black: [10, 40], white: [255, 255] }, BlendRange::FULL]); - assert_eq!(b.get(3), [BlendRange::FULL, BlendRange { black: [0, 0], white: [200, 200] }]); - assert_eq!(b.ranges.len(), 4); - assert_eq!(super::ranges_from_blend_if(&b, 3).data, data); - // The default writes full ranges for gray + each channel. - assert_eq!(super::ranges_from_blend_if(&BlendIf::default(), 4), BlendingRanges::full(4)); - // A trimmed setting is padded to the document's channel count. - let mut short = BlendIf::default(); - short.set(0, [BlendRange { black: [5, 5], white: [255, 255] }, BlendRange::FULL]); - let r = super::ranges_from_blend_if(&short, 3); - assert_eq!(r.data.len(), 4 * 8); - assert_eq!(&r.data[..8], &[5, 5, 255, 255, 0, 0, 255, 255]); - assert_eq!(&r.data[8..], &BlendingRanges::full(2).data[..]); - } - - #[test] - fn advanced_blending_blocks_round_trip() { - use photocraft_doc::{AdvancedBlending, Knockout}; - let a = AdvancedBlending { - knockout: Knockout::Deep, - blend_interior: true, - blend_clipped: false, - transparency_shapes: false, - layer_mask_hides_effects: true, - vector_mask_hides_effects: true, - }; - let mut raw = Vec::new(); - super::put_advanced(&a, &mut raw); - assert_eq!(raw.len(), 6); - assert!(raw.contains(&(*b"knko", vec![2, 0, 0, 0]))); - assert!(raw.contains(&(*b"clbl", vec![0, 0, 0, 0]))); - let get = |k: &[u8; 4]| raw.iter().find(|(bk, _)| bk == k).map(|(_, d)| d.as_slice()); - assert_eq!(super::advanced_from_blocks(get), a); - // Defaults: nothing added to a plain layer; existing blocks rewritten in place, in order. - let mut plain = Vec::new(); - super::put_advanced(&AdvancedBlending::default(), &mut plain); - assert!(plain.is_empty()); - let mut kept = vec![(*b"luni", vec![0; 4]), (*b"knko", vec![1, 0, 0, 0]), (*b"clbl", vec![1])]; - super::put_advanced(&AdvancedBlending::default(), &mut kept); - assert_eq!(kept, vec![(*b"luni", vec![0; 4]), (*b"knko", vec![0, 0, 0, 0]), (*b"clbl", vec![1, 0, 0, 0])]); - // Missing and empty blocks read as Photoshop's defaults. - assert!(super::advanced_from_blocks(|_| None).is_default()); - assert!(super::advanced_from_blocks(|_| Some(&[][..])).is_default()); - assert_eq!(super::advanced_from_blocks(|k| (k == b"knko").then_some(&[1u8][..])).knockout, Knockout::Shallow); - } - - #[test] - fn brst_round_trip() { - assert_eq!(super::parse_brst(&[0, 0, 0, 2]), 0b100); - assert_eq!(super::parse_brst(&[0, 0, 0, 0, 0, 0, 0, 1]), 0b11); - assert_eq!(super::brst_data(0b101).unwrap(), vec![0, 0, 0, 0, 0, 0, 0, 2]); - assert_eq!(super::brst_data(0), None); - } - - #[test] - fn placed_layer_warp_is_read() { - use photocraft_geom::warp::WarpStyle; - use photocraft_psd::descriptor::ObjectArray; - let e = |t: &str, v: &str| Value::Enumerated { type_id: Id::new(t), value: Id::new(v) }; - let bounds = Descriptor::new("Rctn") - .with("Top ", Value::UnitFloat { unit: *b"#Pxl", value: 0.0 }) - .with("Left", Value::UnitFloat { unit: *b"#Pxl", value: 0.0 }) - .with("Btom", Value::UnitFloat { unit: *b"#Pxl", value: 30.0 }) - .with("Rght", Value::UnitFloat { unit: *b"#Pxl", value: 60.0 }); - let sold = |warp: Descriptor| { - let mut v = b"soLD".to_vec(); - v.extend_from_slice(&4u32.to_be_bytes()); - v.extend(VersionedDescriptor::new(Descriptor::new("null").with("warp", Value::Descriptor(warp))).to_bytes()); - v - }; - let arc = Descriptor::new("warp") - .with("warpStyle", e("warpStyle", "warpArc")) - .with("warpValue", Value::Double(40.0)) - .with("warpPerspective", Value::Double(0.0)) - .with("warpPerspectiveOther", Value::Double(0.0)) - .with("warpRotate", e("Ornt", "Hrzn")) - .with("bounds", Value::Descriptor(bounds.clone())); - let w = parse_placed_warp(b"SoLd", &sold(arc)).unwrap(); - assert_eq!((w.style, w.bend, w.bounds), (WarpStyle::Arc, 40.0, [0.0, 0.0, 60.0, 30.0])); - let (mut xs, mut ys) = (Vec::new(), Vec::new()); - for j in 0..4 { - for i in 0..4 { - xs.push(f64::from(i) * 20.0 + if i == 3 && j == 3 { 7.0 } else { 0.0 }); - ys.push(f64::from(j) * 10.0); - } - } - let mesh = Descriptor::new("null") - .with("Hrzn", Value::UnitFloats { unit: *b"#Pxl", values: xs }) - .with("Vrtc", Value::UnitFloats { unit: *b"#Pxl", values: ys }); - let custom = Descriptor::new("warp").with("warpStyle", e("warpStyle", "warpCustom")).with("bounds", Value::Descriptor(bounds)).with( - "customEnvelopeWarp", - Value::Descriptor(Descriptor::new("customEnvelopeWarp").with("meshPoints", Value::ObjectArray(ObjectArray { prefix: 16, body: mesh }))), - ); - let w = parse_placed_warp(b"SoLd", &sold(custom)).unwrap(); - assert_eq!(w.style, WarpStyle::Custom); - assert_eq!(w.mesh.as_ref().unwrap().points[15], [67.0, 30.0]); - assert!(parse_placed_warp(b"PlLd", &[0; 20]).is_none()); - } - - #[test] - fn locks_and_labels() { - // Reference values round-trip byte for byte; Background layers carry 0x0D - // (transparency + position + the bit-3 lock reference files write). - for bits in [0u32, 1, 2, 4, 8, 0x0D, 0x8000_0000, 0x8000_000F] { - assert_eq!(lspf_from_locks(&locks_from_lspf(bits)), bits); - } - // Older PhotoCraft files wrote the artboard lock at 0x10; it reads back as artboard - // and is rewritten at the reference value 0x08. - assert!(locks_from_lspf(0x10).artboard); - assert_eq!(lspf_from_locks(&locks_from_lspf(0x10)), 0x08); - for i in 0..8 { - assert_eq!(label_index(label_from_index(i)), i); - } - } - - #[test] - fn fills_roundtrip() { - for f in [ - Fill::Solid(Color::rgb(1.0, 0.5, 0.0)), - Fill::Solid(Color { mode: ColorMode::Cmyk, c: [0.1, 0.2, 0.3, 0.4], alpha: 1.0 }), - Fill::Solid(Color::gray(0.25)), - Fill::gradient(vec![(0.0, Color::rgb(1.0, 0.0, 0.0)), (1.0, Color::rgb(0.0, 0.0, 1.0))], 45.0, 1.0, GradientStyle::Reflected, true), - // A live gradient (Gradient tool): canvas-aligned, offset, midpoints, opacity, dither. - Fill::Gradient { - stops: vec![(0.0, Color::rgb(1.0, 0.0, 0.0)), (0.5, Color::rgb(0.0, 1.0, 0.0)), (1.0, Color::rgb(0.0, 0.0, 1.0))], - angle: -33.5, - scale: 2.25, - style: GradientStyle::Radial, - reverse: false, - opacity_stops: vec![(0.0, 1.0), (0.25, 0.5), (1.0, 0.0)], - midpoints: vec![0.25, 0.75], - offset: (0.125, -0.375), - dither: true, - align: false, - }, - Fill::Pattern { name: "Bubbles".into(), scale: 0.5, id: "abc".into(), angle: 30.0, link: false, phase: (3.0, -2.0) }, - ] { - let (k, d) = write_fill(&f); - let back = parse_fill(&k, &d).unwrap(); - match (&f, &back) { - (Fill::Solid(a), Fill::Solid(b)) => { - assert_eq!(a.mode, b.mode); - for i in 0..4 { - assert!((a.c[i] - b.c[i]).abs() < 1e-5); - } - } - _ => assert_eq!(back, f), - } - } - } -} +mod tests; #[cfg(test)] -mod more_tests { - use super::*; - - #[test] - fn float_rgb_colors_parse() { - let d = Descriptor::new("RGBC").with("redFloat", Value::Double(1.0)).with("greenFloat", Value::Double(0.5)).with("blueFloat", Value::Double(0.25)); - let c = color_from_desc(&d).unwrap(); - assert_eq!(c.to_rgb(), [1.0, 0.5, 0.25]); - } - - #[test] - fn smart_transform_from_sold() { - let pts = [10.0, 20.0, 110.0, 20.0, 110.0, 70.0, 10.0, 70.0].map(Value::Double).to_vec(); - let d = Descriptor::new("null") - .with("Idnt", Value::Text(UnicodeString::new_nul("uuid-1"))) - .with("Trnf", Value::List(pts)) - .with("Sz ", Value::Descriptor(Descriptor::new("Pnt ").with("Wdth", Value::Double(50.0)).with("Hght", Value::Double(25.0)))); - let mut data = b"soLD".to_vec(); - data.extend_from_slice(&4u32.to_be_bytes()); - data.extend(VersionedDescriptor::new(d).to_bytes()); - data.extend_from_slice(&[0, 0]); - let (id, a) = parse_smart(b"SoLd", &data); - assert_eq!(id, "uuid-1"); - assert_eq!(a.m, [2.0, 0.0, 0.0, 2.0, 10.0, 20.0]); - assert_eq!(parse_smart(b"PlLd", &data).0, ""); - assert_eq!(parse_plld(&data), None, "soLD data is not a plcL record"); - } - - /// A `PlLd` record (as Photoshop CS2 writes it, with no `SoLd`, #2465) gives its source id and - /// placed corners; with the source size those are the same transform `SoLd` gives. - #[test] - fn plld_id_and_corners() { - use crate::smart_map::{PlacedSpec, plld_bytes}; - let t = Affine { m: [1.5, 0.25, -0.5, 2.0, 10.0, 20.0] }; - let spec = PlacedSpec { idnt: "uuid-cs2", placed: "", transform: t, perspective: None, size: (40.0, 30.0), dpi: 72.0, warp: None, filter_fx: None }; - let data = plld_bytes(&spec, &mut Vec::new()); - let (id, p) = parse_plld(&data).expect("a plcL record"); - assert_eq!(id, "uuid-cs2"); - assert_eq!(p, [10.0, 20.0, 70.0, 30.0, 55.0, 90.0, -5.0, 80.0]); - let back = corners_affine(&p, [0.0, 0.0, 40.0, 30.0]).unwrap(); - for (a, b) in back.m.iter().zip(t.m) { - assert!((a - b).abs() < 1e-12, "{back:?} vs {t:?}"); - } - assert_eq!(corners_perspective([[p[0], p[1]], [p[2], p[3]], [p[4], p[5]], [p[6], p[7]]], (40.0, 30.0)), None, "affine corners"); - assert_eq!(corners_affine(&p, [0.0, 0.0, 0.0, 30.0]), None); - assert_eq!(corners_affine(&p, [0.0, 0.0, f64::NAN, 30.0]), None); - assert_eq!(corners_affine(&p, [5.0, 0.0, 5.0, 30.0]), None, "an empty frame"); - let mut nan = p; - nan[3] = f64::INFINITY; - assert_eq!(corners_affine(&nan, [0.0, 0.0, 40.0, 30.0]), None); - // The placed-layer record is the one block that can be the principal one: PlLd-only - // layers have no smart transform from `parse_smart`. - assert_eq!(parse_smart(b"PlLd", &data), (String::new(), Affine::IDENTITY)); - } - - /// A `PlLd` record's corners frame the same box as `SoLd`'s `Trnf` (#3677): with a custom - /// warp whose control points spill past the source, the control-point box, not the source - /// rect. The CS2 record then places the layer exactly as the equivalent `SoLd` does, with or - /// without the source size (the box needs none). - #[test] - fn plld_corners_frame_a_spilled_custom_warp_like_sold() { - use crate::smart_map::{PlacedSpec, parse_sold, plld_bytes, sold_bytes}; - use photocraft_geom::warp::{BezierMesh, Warp}; - let bounds = [0.0, 0.0, 50.0, 25.0]; - let mut mesh = BezierMesh::identity(bounds, 1, 1); - mesh.points[0] = [-10.0, -5.0]; - mesh.points[15] = [60.0, 25.0]; - let warp = Warp::custom(mesh, bounds); - let t = Affine { m: [2.0, 0.5, -0.25, 2.0, 120.0, 210.0] }; - let spec = PlacedSpec { idnt: "cs2", placed: "p", transform: t, perspective: None, size: (50.0, 25.0), dpi: 72.0, warp: Some(&warp), filter_fx: None }; - let plld = plld_bytes(&spec, &mut Vec::new()); - let sold = sold_bytes(None, &spec, &mut Vec::new()); - let (_, p) = parse_plld(&plld).expect("a plcL record"); - assert_eq!(parse_plld_warp(&plld), PlldWarp::Warp(warp.clone())); - let from_sold = parse_smart(b"SoLd", &sold).1; - assert_eq!(parse_sold(&sold).map(|s| s.transform), Some(from_sold)); - let close = |a: Affine, b: Affine| a.m.iter().zip(b.m).all(|(x, y)| (x - y).abs() < 1e-9); - assert!(close(from_sold, t), "{from_sold:?} vs {t:?}"); - for size in [Some((50.0, 25.0)), None] { - let (got, perspective) = plld_transform(&p, size, Some(&warp)); - assert!(close(got, from_sold), "size {size:?}: {got:?} vs SoLd {from_sold:?}"); - assert_eq!(perspective, None); - } - // Framing the source rect instead would stretch it (the bug #3677 fixed for SoLd). - let rect = corners_affine(&p, [0.0, 0.0, 50.0, 25.0]).unwrap(); - assert!(!close(rect, t), "the test needs a mesh that spills: {rect:?}"); - // With no warp, or a preset one, the frame is the source rect, as before. - let plain = PlacedSpec { warp: None, ..spec }; - let (_, q) = parse_plld(&plld_bytes(&plain, &mut Vec::new())).unwrap(); - assert!(close(plld_transform(&q, Some((50.0, 25.0)), None).0, t)); - } - - /// Malformed `PlLd` data (wrong magic, truncated anywhere, a Pascal length past the end, - /// non-finite corners) reads as `None`, never a panic. - #[test] - fn plld_malformed_is_none() { - use crate::smart_map::{PlacedSpec, plld_bytes}; - let spec = - PlacedSpec { idnt: "id", placed: "", transform: Affine::IDENTITY, perspective: None, size: (4.0, 4.0), dpi: 72.0, warp: None, filter_fx: None }; - let data = plld_bytes(&spec, &mut Vec::new()); - // Magic + version + Pascal "id" + 4 × u32 + 8 × f64: everything after is the warp. - let end = 4 + 4 + 1 + 2 + 16 + 64; - assert!(parse_plld(&data[..end]).is_some()); - for n in 0..end { - assert_eq!(parse_plld(&data[..n]), None, "truncated to {n} bytes"); - } - let mut bad = data.clone(); - bad[..4].copy_from_slice(b"soLD"); - assert_eq!(parse_plld(&bad), None); - let mut long = data.clone(); - long[8] = 255; // a Pascal id longer than the record - assert_eq!(parse_plld(&long[..200.min(long.len())]), None); - let mut nan = data.clone(); - nan[end - 8..end].copy_from_slice(&f64::NAN.to_be_bytes()); - assert_eq!(parse_plld(&nan), None); - assert_eq!(parse_plld(&[]), None); - } - - /// Photoshop CS2 can warp a smart object; `PlLd` keeps that warp after the corners (a u32 - /// warp version, then the versioned `warp` descriptor). It reads back as written, and - /// `warpNone`, an identity warp or a record that stops at its corners mean no warp. - #[test] - fn plld_warps_round_trip() { - use crate::smart_map::{PlacedSpec, plld_bytes}; - use photocraft_geom::warp::{BezierMesh, Warp, WarpStyle}; - let bounds = [0.0, 0.0, 60.0, 30.0]; - let mut arc = Warp::preset(WarpStyle::Arc, 40.0, bounds); - arc.vertical = true; - arc.h_distort = 10.0; - let mut mesh = BezierMesh::identity(bounds, 1, 1); - mesh.points[15] = [67.0, 30.0]; - let custom = Warp::custom(mesh, bounds); - let flat = Warp::preset(WarpStyle::Flag, 0.0, bounds); - for (w, back) in - [(Some(&arc), PlldWarp::Warp(arc.clone())), (Some(&custom), PlldWarp::Warp(custom.clone())), (Some(&flat), PlldWarp::None), (None, PlldWarp::None)] - { - let t = Affine { m: [0.5, 0.0, 0.0, 0.5, 3.0, 4.0] }; - let spec = PlacedSpec { idnt: "w", placed: "", transform: t, perspective: None, size: (60.0, 30.0), dpi: 72.0, warp: w, filter_fx: None }; - let data = plld_bytes(&spec, &mut Vec::new()); - assert_eq!(parse_plld_warp(&data), back, "{w:?}"); - // The corners are unchanged by the warp that follows them. - assert_eq!(parse_plld(&data).map(|(_, p)| p[..2].to_vec()), Some(vec![3.0, 4.0])); - } - let spec = - PlacedSpec { idnt: "id", placed: "", transform: Affine::IDENTITY, perspective: None, size: (4.0, 4.0), dpi: 72.0, warp: None, filter_fx: None }; - let end = 4 + 4 + 1 + 2 + 16 + 64; - let data = plld_bytes(&spec, &mut Vec::new()); - assert_eq!(parse_plld_warp(&data[..end]), PlldWarp::None, "no warp stored"); - assert_eq!(parse_plld_warp(&[data[..end].to_vec(), vec![0; 3]].concat()), PlldWarp::None, "padding"); - } - - /// A `PlLd` warp that is stored but can't be read (truncated, an unknown style, a missing - /// bounds rectangle or mesh) is `Unreadable`, so the import keeps the warped pixels. - #[test] - fn plld_unreadable_warps() { - use crate::smart_map::{PlacedSpec, plld_bytes}; - use photocraft_geom::warp::{Warp, WarpStyle}; - let arc = Warp::preset(WarpStyle::Arc, 40.0, [0.0, 0.0, 4.0, 4.0]); - let spec = PlacedSpec { - idnt: "id", - placed: "", - transform: Affine::IDENTITY, - perspective: None, - size: (4.0, 4.0), - dpi: 72.0, - warp: Some(&arc), - filter_fx: None, - }; - let data = plld_bytes(&spec, &mut Vec::new()); - let end = 4 + 4 + 1 + 2 + 16 + 64; - assert!(matches!(parse_plld_warp(&data), PlldWarp::Warp(_))); - for n in end + 1..data.len() - 4 { - if data[end..n].iter().any(|b| *b != 0) { - assert_eq!(parse_plld_warp(&data[..n]), PlldWarp::Unreadable, "truncated to {n} bytes"); - } - } - let with = |d: Descriptor| [data[..end].to_vec(), vec![0; 4], VersionedDescriptor::new(d).to_bytes()].concat(); - let style = |s: &str| Value::Enumerated { type_id: Id::new("warpStyle"), value: Id::new(s) }; - assert_eq!(parse_plld_warp(&with(Descriptor::new("warp").with("warpStyle", style("warpSomethingNew")))), PlldWarp::Unreadable); - assert_eq!(parse_plld_warp(&with(Descriptor::new("warp").with("warpStyle", style("warpArc")))), PlldWarp::Unreadable, "no bounds"); - assert_eq!(parse_plld_warp(&with(Descriptor::new("warp").with("warpStyle", style("warpNone")))), PlldWarp::None); - let bounds = Descriptor::new("classFloatRect") - .with("Top ", Value::Double(0.0)) - .with("Left", Value::Double(0.0)) - .with("Btom", Value::Double(4.0)) - .with("Rght", Value::Double(4.0)); - let custom = Descriptor::new("warp").with("warpStyle", style("warpCustom")).with("bounds", Value::Descriptor(bounds)); - assert_eq!(parse_plld_warp(&with(custom)), PlldWarp::Unreadable, "custom with no mesh"); - assert_eq!(parse_plld_warp(&[data[..end].to_vec(), vec![0, 0, 0, 0, 0, 0, 0, 16, 1, 2]].concat()), PlldWarp::Unreadable); - assert_eq!(parse_plld_warp(&data[..end - 1]), PlldWarp::Unreadable, "the record itself"); - assert_eq!(parse_plld_warp(&[]), PlldWarp::Unreadable); - } - - /// `SoLd` data with a 50 × 25 source, the quad `trnf` and, when given, a custom warp whose - /// 16 control points are `pts`. - fn sold_with_warp(trnf: [f64; 8], pts: Option<&[[f64; 2]]>) -> Vec { - use photocraft_psd::descriptor::ObjectArray; - let e = |t: &str, v: &str| Value::Enumerated { type_id: Id::new(t), value: Id::new(v) }; - let mut d = Descriptor::new("null") - .with("Idnt", Value::Text(UnicodeString::new_nul("uuid-1"))) - .with("Trnf", Value::List(trnf.map(Value::Double).to_vec())) - .with("Sz ", Value::Descriptor(Descriptor::new("Pnt ").with("Wdth", Value::Double(50.0)).with("Hght", Value::Double(25.0)))); - if let Some(pts) = pts { - let bounds = Descriptor::new("Rctn") - .with("Top ", Value::Double(0.0)) - .with("Left", Value::Double(0.0)) - .with("Btom", Value::Double(25.0)) - .with("Rght", Value::Double(50.0)); - let mesh = Descriptor::new("null") - .with("Hrzn", Value::UnitFloats { unit: *b"#Pxl", values: pts.iter().map(|p| p[0]).collect() }) - .with("Vrtc", Value::UnitFloats { unit: *b"#Pxl", values: pts.iter().map(|p| p[1]).collect() }); - let warp = Descriptor::new("warp").with("warpStyle", e("warpStyle", "warpCustom")).with("bounds", Value::Descriptor(bounds)).with( - "customEnvelopeWarp", - Value::Descriptor(Descriptor::new("customEnvelopeWarp").with("meshPoints", Value::ObjectArray(ObjectArray { prefix: 16, body: mesh }))), - ); - d = d.with("warp", Value::Descriptor(warp)); - } - let mut data = b"soLD".to_vec(); - data.extend_from_slice(&4u32.to_be_bytes()); - data.extend(VersionedDescriptor::new(d).to_bytes()); - data - } - - /// `SoLd` data with a split (quilt) custom warp, as Photoshop writes it: a `quiltWarp` - /// descriptor with `deformNumCols` × `deformNumRows` control points and the patch boundaries - /// in `quiltSliceX` / `quiltSliceY`. With `plain_warp`, a `warpNone` `warp` key sits next to it. - fn sold_with_quilt(trnf: [f64; 8], cols: f64, rows: f64, sx: &[f64], sy: &[f64], pts: &[[f64; 2]], plain_warp: bool) -> Vec { - use photocraft_psd::descriptor::ObjectArray; - let e = |t: &str, v: &str| Value::Enumerated { type_id: Id::new(t), value: Id::new(v) }; - let bounds = || { - Descriptor::new("Rctn") - .with("Top ", Value::Double(0.0)) - .with("Left", Value::Double(0.0)) - .with("Btom", Value::Double(25.0)) - .with("Rght", Value::Double(50.0)) - }; - let slices = |k: &str, v: &[f64]| { - let body = Descriptor::new("null").with(k, Value::UnitFloats { unit: *b"#Pxl", values: v.to_vec() }); - Value::ObjectArray(ObjectArray { prefix: v.len() as u32, body }) - }; - let mesh = Descriptor::new("null") - .with("Hrzn", Value::UnitFloats { unit: *b"#Pxl", values: pts.iter().map(|p| p[0]).collect() }) - .with("Vrtc", Value::UnitFloats { unit: *b"#Pxl", values: pts.iter().map(|p| p[1]).collect() }); - let envelope = Descriptor::new("customEnvelopeWarp") - .with("quiltSliceX", slices("quiltSliceX", sx)) - .with("quiltSliceY", slices("quiltSliceY", sy)) - .with("meshPoints", Value::ObjectArray(ObjectArray { prefix: 16, body: mesh })); - let quilt = Descriptor::new("quiltWarp") - .with("warpStyle", e("warpStyle", "warpCustom")) - .with("bounds", Value::Descriptor(bounds())) - .with("deformNumRows", Value::Integer(rows as i32)) - .with("deformNumCols", Value::Double(cols)) - .with("customEnvelopeWarp", Value::Descriptor(envelope)); - let mut d = Descriptor::new("null") - .with("Idnt", Value::Text(UnicodeString::new_nul("uuid-1"))) - .with("Trnf", Value::List(trnf.map(Value::Double).to_vec())) - .with("Sz ", Value::Descriptor(Descriptor::new("Pnt ").with("Wdth", Value::Double(50.0)).with("Hght", Value::Double(25.0)))); - if plain_warp { - d = d.with( - "warp", - Value::Descriptor(Descriptor::new("warp").with("warpStyle", e("warpStyle", "warpNone")).with("bounds", Value::Descriptor(bounds()))), - ); - } - d = d.with("quiltWarp", Value::Descriptor(quilt)); - let mut data = b"soLD".to_vec(); - data.extend_from_slice(&4u32.to_be_bytes()); - data.extend(VersionedDescriptor::new(d).to_bytes()); - data - } - - /// A 3 × 2 patch identity grid over the 50 × 25 source with one interior control point pulled. - fn quilt_points() -> Vec<[f64; 2]> { - let mut pts = photocraft_geom::warp::BezierMesh::identity([0.0, 0.0, 50.0, 25.0], 3, 2).points; - if let Some(p) = pts.get_mut(10 * 3 + 4) { - p[1] += 3.0; - } - pts - } - - /// Photoshop's split warp (`quiltWarp`, mockups' usual warp) reads as a multi-patch mesh: the - /// patch boundaries become the knots, the control points stay in order, and the quilt wins over - /// the `warpNone` `warp` key written next to it. Before, any mesh but 4 × 4 was dropped and the - /// layer re-rendered flat. - #[test] - fn quilt_warp_is_read_as_a_multi_patch_mesh() { - let quad = [100.0, 200.0, 240.0, 200.0, 240.0, 260.0, 100.0, 260.0]; - let pts = quilt_points(); - // Photoshop pads the outer boundaries a little past the grid's edges. - let data = sold_with_quilt(quad, 10.0, 7.0, &[-0.5, 12.5, 37.5, 50.5], &[-0.5, 12.5, 25.5], &pts, true); - let warp = parse_placed_warp(b"SoLd", &data).expect("a quilt warp"); - let mesh = warp.mesh.as_ref().expect("its mesh"); - assert_eq!(mesh.points, pts); - assert_eq!(mesh.us.len(), 4); - assert_eq!(mesh.vs.len(), 3); - assert_eq!((mesh.us[0], mesh.us[3], mesh.vs[0], mesh.vs[2]), (0.0, 1.0, 0.0, 1.0)); - assert!((mesh.us[1] - 13.0 / 51.0).abs() < 1e-12 && (mesh.vs[1] - 13.0 / 26.0).abs() < 1e-12); - assert!(mesh.is_valid()); - } - - /// A quilt's control points frame the placed quad as a single patch's do (#3677): a grid - /// spilling to x = -10, y = -5 and x = 60 frames a 70 × 30 box. - #[test] - fn quilt_warp_control_box_frames_the_quad() { - let mut pts = quilt_points(); - pts[0] = [-10.0, -5.0]; - if let Some(last) = pts.last_mut() { - *last = [60.0, 25.0]; - } - let quad = [100.0, 200.0, 240.0, 200.0, 240.0, 260.0, 100.0, 260.0]; - let data = sold_with_quilt(quad, 10.0, 7.0, &[0.0, 12.5, 37.5, 50.0], &[0.0, 12.5, 25.0], &pts, false); - assert_eq!(parse_smart(b"SoLd", &data).1.m, [2.0, 0.0, 0.0, 2.0, 120.0, 210.0]); - } - - /// An inconsistent quilt reads as no warp rather than a wrong one, and never panics. - #[test] - fn inconsistent_quilt_warps_are_not_read() { - let quad = [100.0, 200.0, 240.0, 200.0, 240.0, 260.0, 100.0, 260.0]; - let pts = quilt_points(); - let (sx, sy) = ([0.0, 12.5, 37.5, 50.0], [0.0, 12.5, 25.0]); - let read = - |cols: f64, rows: f64, sx: &[f64], sy: &[f64], pts: &[[f64; 2]]| parse_placed_warp(b"SoLd", &sold_with_quilt(quad, cols, rows, sx, sy, pts, false)); - assert!(read(10.0, 7.0, &sx, &sy, &pts).is_some()); - assert!(read(9.0, 7.0, &sx, &sy, &pts).is_none(), "not three points per patch side plus one"); - assert!(read(13.0, 7.0, &sx, &sy, &pts).is_none(), "more points claimed than stored"); - assert!(read(10.0, 7.0, &[0.0, 12.5, 50.0], &sy, &pts).is_none(), "one slice per patch boundary"); - assert!(read(10.0, 7.0, &[0.0, 37.5, 12.5, 50.0], &sy, &pts).is_none(), "slices must increase"); - assert!(read(10.0, 7.0, &[0.0, f64::NAN, 37.5, 50.0], &sy, &pts).is_none()); - assert!(read(1e9, 7.0, &sx, &sy, &pts).is_none(), "an absurd grid is refused before any arithmetic"); - assert!(read(10.0, 7.0, &sx, &sy, &pts[..pts.len() - 1]).is_none()); - let mut nan = pts.clone(); - nan[3] = [f64::NAN, 0.0]; - assert!(read(10.0, 7.0, &sx, &sy, &nan).is_none()); - } - - /// Photoshop's `Trnf` is the image of the custom warp's control-point bounding box, not of the - /// source rect: a mesh spilling to x = -10, y = -5 and x = 60 frames a 70 × 30 box. - #[test] - fn smart_transform_maps_the_warp_control_box_onto_the_quad() { - let mut pts = photocraft_geom::warp::BezierMesh::identity([0.0, 0.0, 50.0, 25.0], 1, 1).points; - pts[0] = [-10.0, -5.0]; - pts[15] = [60.0, 25.0]; - let quad = [100.0, 200.0, 240.0, 200.0, 240.0, 260.0, 100.0, 260.0]; - let (_, a) = parse_smart(b"SoLd", &sold_with_warp(quad, Some(&pts))); - assert_eq!(a.m, [2.0, 0.0, 0.0, 2.0, 120.0, 210.0]); - // Without a warp the source rect is the frame, as before. - assert_eq!(parse_smart(b"SoLd", &sold_with_warp(quad, None)).1.m, [2.8, 0.0, 0.0, 2.4, 100.0, 200.0]); - } - - /// A custom mesh with no area (every control point on one spot) can't frame the quad: the - /// source rect does, with no division by zero. - #[test] - fn smart_transform_with_a_degenerate_warp_box_uses_the_source_rect() { - let quad = [100.0, 200.0, 240.0, 200.0, 240.0, 260.0, 100.0, 260.0]; - let (_, a) = parse_smart(b"SoLd", &sold_with_warp(quad, Some(&[[7.0, 7.0]; 16]))); - assert_eq!(a.m, [2.8, 0.0, 0.0, 2.4, 100.0, 200.0]); - let mut warp = photocraft_geom::warp::Warp::preset(photocraft_geom::warp::WarpStyle::Custom, 0.0, [0.0, 0.0, 50.0, 25.0]); - warp.mesh = Some(photocraft_geom::warp::BezierMesh { us: vec![0.0, 1.0], vs: vec![0.0, 1.0], points: vec![[f64::NAN, 1.0]; 16] }); - assert_eq!(placed_frame(Some(&warp), 50.0, 25.0), [0.0, 0.0, 50.0, 25.0]); - assert_eq!(placed_frame(None, 50.0, 25.0), [0.0, 0.0, 50.0, 25.0]); - } - - /// A `SoLd` placed on `quad` (`Trnf` and `nonAffineTransform`) for a 1000 × 1000 source, - /// warped by `warp`. - fn sold_placed(quad: [f64; 8], warp: Descriptor) -> Vec { - let list = Value::List(quad.iter().map(|v| Value::Double(*v)).collect()); - let d = Descriptor::new("null") - .with("Trnf", list.clone()) - .with("nonAffineTransform", list) - .with("Sz ", Value::Descriptor(Descriptor::new("Pnt ").with("Wdth", Value::Double(1000.0)).with("Hght", Value::Double(1000.0)))) - .with("warp", Value::Descriptor(warp)); - let mut data = b"soLD".to_vec(); - data.extend_from_slice(&4u32.to_be_bytes()); - data.extend(VersionedDescriptor::new(d).to_bytes()); - data - } - - /// A `warpCylinder` descriptor as #4112 describes it: horizontal, no perspective, seven - /// `warpValues` in the space of `bounds`. - fn cylinder_desc(values: Value) -> Descriptor { - let e = |t: &str, v: &str| Value::Enumerated { type_id: Id::new(t), value: Id::new(v) }; - let bounds = Descriptor::new("classFloatRect") - .with("Top ", Value::Double(0.0)) - .with("Left", Value::Double(0.0)) - .with("Btom", Value::Double(1000.0)) - .with("Rght", Value::Double(1000.0)); - Descriptor::new("warp") - .with("warpStyle", e("warpStyle", "warpCylinder")) - .with("warpValue", Value::Double(0.0)) - .with("warpValues", values) - .with("warpPerspective", Value::Double(0.0)) - .with("warpPerspectiveOther", Value::Double(0.0)) - .with("warpRotate", e("Ornt", "Hrzn")) - .with("bounds", Value::Descriptor(bounds)) - } - - const CYL: [f64; 7] = [100.0, 800.0, 900.0, 200.0, 0.3, 0.3, 0.5]; - - fn doubles(v: &[f64]) -> Value { - Value::List(v.iter().map(|x| Value::Double(*x)).collect()) - } - - /// A projective placement is framed by the warp `parse_placed_warp` imports: an unreadable - /// `quiltWarp` next to a cylinder under `warp` imports no warp, so the source rect is framed. - #[test] - fn perspective_frame_follows_the_warp_parse_placed_warp_reads() { - let quad = [10.0, 20.0, 410.0, 60.0, 400.0, 480.0, 30.0, 520.0]; - let list = Value::List(quad.iter().map(|v| Value::Double(*v)).collect()); - let unreadable = - Descriptor::new("quiltWarp").with("warpStyle", Value::Enumerated { type_id: Id::new("warpStyle"), value: Id::new("warpSomethingNew") }); - let d = Descriptor::new("null") - .with("Trnf", list.clone()) - .with("nonAffineTransform", list) - .with("Sz ", Value::Descriptor(Descriptor::new("Pnt ").with("Wdth", Value::Double(1000.0)).with("Hght", Value::Double(1000.0)))) - .with("quiltWarp", Value::Descriptor(unreadable)) - .with("warp", Value::Descriptor(cylinder_desc(doubles(&CYL)))); - let mut data = b"soLD".to_vec(); - data.extend_from_slice(&4u32.to_be_bytes()); - data.extend(VersionedDescriptor::new(d).to_bytes()); - assert_eq!(parse_placed_warp(b"SoLd", &data), None); - let h = photocraft_algo::transform::Homography(parse_smart_perspective(b"SoLd", &data).expect("projective")); - let (px, py) = h.apply(1000.0, 1000.0); - assert!((px - 400.0).abs() < 1e-6 && (py - 480.0).abs() < 1e-6, "{px},{py}"); - } - /// #4112: a `warpCylinder` placed layer comes in as the cylinder its seven values describe, - /// instead of no warp (which re-rendered the contents flat). - #[test] - fn placed_cylinder_warp_is_read() { - use photocraft_geom::warp::{Warp, WarpStyle}; - let quad = [0.0, 0.0, 800.0, 0.0, 800.0, 800.0, 0.0, 800.0]; - let want = Warp::cylinder(&CYL, [0.0, 0.0, 1000.0, 1000.0]).unwrap(); - let w = parse_placed_warp(b"SoLd", &sold_placed(quad, cylinder_desc(doubles(&CYL)))).expect("a cylinder"); - assert_eq!(w, want); - assert_eq!(w.style, WarpStyle::Cylinder); - // Values written as one unit-float list read the same. - let floats = Value::UnitFloats { unit: *b"#Pxl", values: CYL.to_vec() }; - assert_eq!(parse_placed_warp(b"SoLE", &sold_placed(quad, cylinder_desc(floats))), Some(want)); - } - - /// Cylinders nobody has measured (vertical, with perspective) and broken values stay - /// unreadable, as every cylinder was before: the layer keeps the pixels Photoshop stored. - #[test] - fn placed_cylinder_warps_that_cant_be_read() { - let quad = [0.0, 0.0, 800.0, 0.0, 800.0, 800.0, 0.0, 800.0]; - let read = |d: Descriptor| parse_placed_warp(b"SoLd", &sold_placed(quad, d)); - let e = |t: &str, v: &str| Value::Enumerated { type_id: Id::new(t), value: Id::new(v) }; - let with = |key: &str, v: Value| { - let mut d = cylinder_desc(doubles(&CYL)); - d.items.iter_mut().filter(|(k, _)| k.is(key)).for_each(|(_, old)| *old = v.clone()); - d - }; - assert!(read(with("warpRotate", e("Ornt", "Vrtc"))).is_none(), "vertical"); - assert!(read(with("warpPerspective", Value::Double(20.0))).is_none(), "perspective"); - assert!(read(with("warpPerspectiveOther", Value::Double(-5.0))).is_none(), "the other perspective"); - assert!(read(cylinder_desc(doubles(&CYL[..6]))).is_none(), "six values"); - assert!(read(cylinder_desc(Value::List(vec![Value::Text(UnicodeString::new_nul("x")); 7]))).is_none(), "not numbers"); - assert!(read(cylinder_desc(Value::Double(1.0))).is_none(), "one number"); - let mut flipped = CYL; - flipped.swap(0, 2); - assert!(read(cylinder_desc(doubles(&flipped))).is_none(), "silhouettes swapped"); - let mut no_values = cylinder_desc(doubles(&CYL)); - no_values.items.retain(|(k, _)| !k.is("warpValues")); - assert!(read(no_values).is_none(), "no warpValues"); - } - - /// Like a custom warp's (#3677), a cylinder's control-point box is what the placement quad - /// frames, for affine corners and for projective ones (`nonAffineTransform`). - #[test] - fn placed_cylinder_quad_frames_its_control_box() { - use photocraft_geom::warp::Warp; - let cb = Warp::cylinder(&CYL, [0.0, 0.0, 1000.0, 1000.0]).unwrap().mesh.unwrap().control_bounds(); - // Affine: the box lands on the quad. - let quad = [10.0, 20.0, 410.0, 20.0, 410.0, 520.0, 10.0, 520.0]; - let (_, a) = parse_smart(b"SoLd", &sold_placed(quad, cylinder_desc(doubles(&CYL)))); - let [m0, m1, m2, m3, m4, m5] = a.m; - let map = |x: f64, y: f64| (m0 * x + m2 * y + m4, m1 * x + m3 * y + m5); - for ((x, y), (qx, qy)) in - [(cb[0], cb[1]), (cb[2], cb[1]), (cb[2], cb[3]), (cb[0], cb[3])].into_iter().zip(quad.as_chunks::<2>().0.iter().map(|p| (p[0], p[1]))) - { - let (px, py) = map(x, y); - assert!((px - qx).abs() < 1e-9 && (py - qy).abs() < 1e-9, "{x},{y} → {px},{py}, not {qx},{qy}"); - } - assert!(parse_smart_perspective(b"SoLd", &sold_placed(quad, cylinder_desc(doubles(&CYL)))).is_none(), "affine"); - // Projective: the same box lands on the four corners. - let quad = [10.0, 20.0, 410.0, 60.0, 400.0, 480.0, 30.0, 520.0]; - let h = photocraft_algo::transform::Homography(parse_smart_perspective(b"SoLd", &sold_placed(quad, cylinder_desc(doubles(&CYL)))).expect("projective")); - for ((x, y), (qx, qy)) in - [(cb[0], cb[1]), (cb[2], cb[1]), (cb[2], cb[3]), (cb[0], cb[3])].into_iter().zip(quad.as_chunks::<2>().0.iter().map(|p| (p[0], p[1]))) - { - let (px, py) = h.apply(x, y); - assert!((px - qx).abs() < 1e-6 && (py - qy).abs() < 1e-6, "{x},{y} → {px},{py}, not {qx},{qy}"); - } - // Without a warp a projective quad still frames the source rect. - let none = Descriptor::new("warp").with("warpStyle", Value::Enumerated { type_id: Id::new("warpStyle"), value: Id::new("warpNone") }); - let h = photocraft_algo::transform::Homography(parse_smart_perspective(b"SoLd", &sold_placed(quad, none)).expect("projective")); - let (px, py) = h.apply(1000.0, 1000.0); - assert!((px - 400.0).abs() < 1e-6 && (py - 480.0).abs() < 1e-6); - } - - #[test] - fn effects_switch() { - let mut lfx = vec![0, 0, 0, 0]; - lfx.extend(VersionedDescriptor::new(Descriptor::new("null").with("masterFXSwitch", Value::Boolean(false))).to_bytes()); - assert!(!effects_enabled(&lfx)); - assert!(effects_enabled(&[0, 0, 0, 0])); - } - - #[test] - fn tysh_garbage_is_none() { - assert!(parse_tysh(&[0; 10]).is_none()); - } -} +mod more_tests; diff --git a/crates/io/src/blocks/more_tests.rs b/crates/io/src/blocks/more_tests.rs new file mode 100644 index 0000000000..3c41296134 --- /dev/null +++ b/crates/io/src/blocks/more_tests.rs @@ -0,0 +1,496 @@ +use super::*; + +#[test] +fn float_rgb_colors_parse() { + let d = Descriptor::new("RGBC").with("redFloat", Value::Double(1.0)).with("greenFloat", Value::Double(0.5)).with("blueFloat", Value::Double(0.25)); + let c = color_from_desc(&d).unwrap(); + assert_eq!(c.to_rgb(), [1.0, 0.5, 0.25]); +} + +#[test] +fn smart_transform_from_sold() { + let pts = [10.0, 20.0, 110.0, 20.0, 110.0, 70.0, 10.0, 70.0].map(Value::Double).to_vec(); + let d = Descriptor::new("null") + .with("Idnt", Value::Text(UnicodeString::new_nul("uuid-1"))) + .with("Trnf", Value::List(pts)) + .with("Sz ", Value::Descriptor(Descriptor::new("Pnt ").with("Wdth", Value::Double(50.0)).with("Hght", Value::Double(25.0)))); + let mut data = b"soLD".to_vec(); + data.extend_from_slice(&4u32.to_be_bytes()); + data.extend(VersionedDescriptor::new(d).to_bytes()); + data.extend_from_slice(&[0, 0]); + let (id, a) = parse_smart(b"SoLd", &data); + assert_eq!(id, "uuid-1"); + assert_eq!(a.m, [2.0, 0.0, 0.0, 2.0, 10.0, 20.0]); + assert_eq!(parse_smart(b"PlLd", &data).0, ""); + assert_eq!(parse_plld(&data), None, "soLD data is not a plcL record"); +} + +/// A `PlLd` record (as Photoshop CS2 writes it, with no `SoLd`, #2465) gives its source id and +/// placed corners; with the source size those are the same transform `SoLd` gives. +#[test] +fn plld_id_and_corners() { + use crate::smart_map::{PlacedSpec, plld_bytes}; + let t = Affine { m: [1.5, 0.25, -0.5, 2.0, 10.0, 20.0] }; + let spec = PlacedSpec { idnt: "uuid-cs2", placed: "", transform: t, perspective: None, size: (40.0, 30.0), dpi: 72.0, warp: None, filter_fx: None }; + let data = plld_bytes(&spec, &mut Vec::new()); + let (id, p) = parse_plld(&data).expect("a plcL record"); + assert_eq!(id, "uuid-cs2"); + assert_eq!(p, [10.0, 20.0, 70.0, 30.0, 55.0, 90.0, -5.0, 80.0]); + let back = corners_affine(&p, [0.0, 0.0, 40.0, 30.0]).unwrap(); + for (a, b) in back.m.iter().zip(t.m) { + assert!((a - b).abs() < 1e-12, "{back:?} vs {t:?}"); + } + assert_eq!(corners_perspective([[p[0], p[1]], [p[2], p[3]], [p[4], p[5]], [p[6], p[7]]], (40.0, 30.0)), None, "affine corners"); + assert_eq!(corners_affine(&p, [0.0, 0.0, 0.0, 30.0]), None); + assert_eq!(corners_affine(&p, [0.0, 0.0, f64::NAN, 30.0]), None); + assert_eq!(corners_affine(&p, [5.0, 0.0, 5.0, 30.0]), None, "an empty frame"); + let mut nan = p; + nan[3] = f64::INFINITY; + assert_eq!(corners_affine(&nan, [0.0, 0.0, 40.0, 30.0]), None); + // The placed-layer record is the one block that can be the principal one: PlLd-only + // layers have no smart transform from `parse_smart`. + assert_eq!(parse_smart(b"PlLd", &data), (String::new(), Affine::IDENTITY)); +} + +/// A `PlLd` record's corners frame the same box as `SoLd`'s `Trnf` (#3677): with a custom +/// warp whose control points spill past the source, the control-point box, not the source +/// rect. The CS2 record then places the layer exactly as the equivalent `SoLd` does, with or +/// without the source size (the box needs none). +#[test] +fn plld_corners_frame_a_spilled_custom_warp_like_sold() { + use crate::smart_map::{PlacedSpec, parse_sold, plld_bytes, sold_bytes}; + use photocraft_geom::warp::{BezierMesh, Warp}; + let bounds = [0.0, 0.0, 50.0, 25.0]; + let mut mesh = BezierMesh::identity(bounds, 1, 1); + mesh.points[0] = [-10.0, -5.0]; + mesh.points[15] = [60.0, 25.0]; + let warp = Warp::custom(mesh, bounds); + let t = Affine { m: [2.0, 0.5, -0.25, 2.0, 120.0, 210.0] }; + let spec = PlacedSpec { idnt: "cs2", placed: "p", transform: t, perspective: None, size: (50.0, 25.0), dpi: 72.0, warp: Some(&warp), filter_fx: None }; + let plld = plld_bytes(&spec, &mut Vec::new()); + let sold = sold_bytes(None, &spec, &mut Vec::new()); + let (_, p) = parse_plld(&plld).expect("a plcL record"); + assert_eq!(parse_plld_warp(&plld), PlldWarp::Warp(warp.clone())); + let from_sold = parse_smart(b"SoLd", &sold).1; + assert_eq!(parse_sold(&sold).map(|s| s.transform), Some(from_sold)); + let close = |a: Affine, b: Affine| a.m.iter().zip(b.m).all(|(x, y)| (x - y).abs() < 1e-9); + assert!(close(from_sold, t), "{from_sold:?} vs {t:?}"); + for size in [Some((50.0, 25.0)), None] { + let (got, perspective) = plld_transform(&p, size, Some(&warp)); + assert!(close(got, from_sold), "size {size:?}: {got:?} vs SoLd {from_sold:?}"); + assert_eq!(perspective, None); + } + // Framing the source rect instead would stretch it (the bug #3677 fixed for SoLd). + let rect = corners_affine(&p, [0.0, 0.0, 50.0, 25.0]).unwrap(); + assert!(!close(rect, t), "the test needs a mesh that spills: {rect:?}"); + // With no warp, or a preset one, the frame is the source rect, as before. + let plain = PlacedSpec { warp: None, ..spec }; + let (_, q) = parse_plld(&plld_bytes(&plain, &mut Vec::new())).unwrap(); + assert!(close(plld_transform(&q, Some((50.0, 25.0)), None).0, t)); +} + +/// Malformed `PlLd` data (wrong magic, truncated anywhere, a Pascal length past the end, +/// non-finite corners) reads as `None`, never a panic. +#[test] +fn plld_malformed_is_none() { + use crate::smart_map::{PlacedSpec, plld_bytes}; + let spec = PlacedSpec { idnt: "id", placed: "", transform: Affine::IDENTITY, perspective: None, size: (4.0, 4.0), dpi: 72.0, warp: None, filter_fx: None }; + let data = plld_bytes(&spec, &mut Vec::new()); + // Magic + version + Pascal "id" + 4 × u32 + 8 × f64: everything after is the warp. + let end = 4 + 4 + 1 + 2 + 16 + 64; + assert!(parse_plld(&data[..end]).is_some()); + for n in 0..end { + assert_eq!(parse_plld(&data[..n]), None, "truncated to {n} bytes"); + } + let mut bad = data.clone(); + bad[..4].copy_from_slice(b"soLD"); + assert_eq!(parse_plld(&bad), None); + let mut long = data.clone(); + long[8] = 255; // a Pascal id longer than the record + assert_eq!(parse_plld(&long[..200.min(long.len())]), None); + let mut nan = data.clone(); + nan[end - 8..end].copy_from_slice(&f64::NAN.to_be_bytes()); + assert_eq!(parse_plld(&nan), None); + assert_eq!(parse_plld(&[]), None); +} + +/// Photoshop CS2 can warp a smart object; `PlLd` keeps that warp after the corners (a u32 +/// warp version, then the versioned `warp` descriptor). It reads back as written, and +/// `warpNone`, an identity warp or a record that stops at its corners mean no warp. +#[test] +fn plld_warps_round_trip() { + use crate::smart_map::{PlacedSpec, plld_bytes}; + use photocraft_geom::warp::{BezierMesh, Warp, WarpStyle}; + let bounds = [0.0, 0.0, 60.0, 30.0]; + let mut arc = Warp::preset(WarpStyle::Arc, 40.0, bounds); + arc.vertical = true; + arc.h_distort = 10.0; + let mut mesh = BezierMesh::identity(bounds, 1, 1); + mesh.points[15] = [67.0, 30.0]; + let custom = Warp::custom(mesh, bounds); + let flat = Warp::preset(WarpStyle::Flag, 0.0, bounds); + for (w, back) in + [(Some(&arc), PlldWarp::Warp(arc.clone())), (Some(&custom), PlldWarp::Warp(custom.clone())), (Some(&flat), PlldWarp::None), (None, PlldWarp::None)] + { + let t = Affine { m: [0.5, 0.0, 0.0, 0.5, 3.0, 4.0] }; + let spec = PlacedSpec { idnt: "w", placed: "", transform: t, perspective: None, size: (60.0, 30.0), dpi: 72.0, warp: w, filter_fx: None }; + let data = plld_bytes(&spec, &mut Vec::new()); + assert_eq!(parse_plld_warp(&data), back, "{w:?}"); + // The corners are unchanged by the warp that follows them. + assert_eq!(parse_plld(&data).map(|(_, p)| p[..2].to_vec()), Some(vec![3.0, 4.0])); + } + let spec = PlacedSpec { idnt: "id", placed: "", transform: Affine::IDENTITY, perspective: None, size: (4.0, 4.0), dpi: 72.0, warp: None, filter_fx: None }; + let end = 4 + 4 + 1 + 2 + 16 + 64; + let data = plld_bytes(&spec, &mut Vec::new()); + assert_eq!(parse_plld_warp(&data[..end]), PlldWarp::None, "no warp stored"); + assert_eq!(parse_plld_warp(&[data[..end].to_vec(), vec![0; 3]].concat()), PlldWarp::None, "padding"); +} + +/// A `PlLd` warp that is stored but can't be read (truncated, an unknown style, a missing +/// bounds rectangle or mesh) is `Unreadable`, so the import keeps the warped pixels. +#[test] +fn plld_unreadable_warps() { + use crate::smart_map::{PlacedSpec, plld_bytes}; + use photocraft_geom::warp::{Warp, WarpStyle}; + let arc = Warp::preset(WarpStyle::Arc, 40.0, [0.0, 0.0, 4.0, 4.0]); + let spec = + PlacedSpec { idnt: "id", placed: "", transform: Affine::IDENTITY, perspective: None, size: (4.0, 4.0), dpi: 72.0, warp: Some(&arc), filter_fx: None }; + let data = plld_bytes(&spec, &mut Vec::new()); + let end = 4 + 4 + 1 + 2 + 16 + 64; + assert!(matches!(parse_plld_warp(&data), PlldWarp::Warp(_))); + for n in end + 1..data.len() - 4 { + if data[end..n].iter().any(|b| *b != 0) { + assert_eq!(parse_plld_warp(&data[..n]), PlldWarp::Unreadable, "truncated to {n} bytes"); + } + } + let with = |d: Descriptor| [data[..end].to_vec(), vec![0; 4], VersionedDescriptor::new(d).to_bytes()].concat(); + let style = |s: &str| Value::Enumerated { type_id: Id::new("warpStyle"), value: Id::new(s) }; + assert_eq!(parse_plld_warp(&with(Descriptor::new("warp").with("warpStyle", style("warpSomethingNew")))), PlldWarp::Unreadable); + assert_eq!(parse_plld_warp(&with(Descriptor::new("warp").with("warpStyle", style("warpArc")))), PlldWarp::Unreadable, "no bounds"); + assert_eq!(parse_plld_warp(&with(Descriptor::new("warp").with("warpStyle", style("warpNone")))), PlldWarp::None); + let bounds = Descriptor::new("classFloatRect") + .with("Top ", Value::Double(0.0)) + .with("Left", Value::Double(0.0)) + .with("Btom", Value::Double(4.0)) + .with("Rght", Value::Double(4.0)); + let custom = Descriptor::new("warp").with("warpStyle", style("warpCustom")).with("bounds", Value::Descriptor(bounds)); + assert_eq!(parse_plld_warp(&with(custom)), PlldWarp::Unreadable, "custom with no mesh"); + assert_eq!(parse_plld_warp(&[data[..end].to_vec(), vec![0, 0, 0, 0, 0, 0, 0, 16, 1, 2]].concat()), PlldWarp::Unreadable); + assert_eq!(parse_plld_warp(&data[..end - 1]), PlldWarp::Unreadable, "the record itself"); + assert_eq!(parse_plld_warp(&[]), PlldWarp::Unreadable); +} + +/// `SoLd` data with a 50 × 25 source, the quad `trnf` and, when given, a custom warp whose +/// 16 control points are `pts`. +fn sold_with_warp(trnf: [f64; 8], pts: Option<&[[f64; 2]]>) -> Vec { + use photocraft_psd::descriptor::ObjectArray; + let e = |t: &str, v: &str| Value::Enumerated { type_id: Id::new(t), value: Id::new(v) }; + let mut d = Descriptor::new("null") + .with("Idnt", Value::Text(UnicodeString::new_nul("uuid-1"))) + .with("Trnf", Value::List(trnf.map(Value::Double).to_vec())) + .with("Sz ", Value::Descriptor(Descriptor::new("Pnt ").with("Wdth", Value::Double(50.0)).with("Hght", Value::Double(25.0)))); + if let Some(pts) = pts { + let bounds = Descriptor::new("Rctn") + .with("Top ", Value::Double(0.0)) + .with("Left", Value::Double(0.0)) + .with("Btom", Value::Double(25.0)) + .with("Rght", Value::Double(50.0)); + let mesh = Descriptor::new("null") + .with("Hrzn", Value::UnitFloats { unit: *b"#Pxl", values: pts.iter().map(|p| p[0]).collect() }) + .with("Vrtc", Value::UnitFloats { unit: *b"#Pxl", values: pts.iter().map(|p| p[1]).collect() }); + let warp = Descriptor::new("warp").with("warpStyle", e("warpStyle", "warpCustom")).with("bounds", Value::Descriptor(bounds)).with( + "customEnvelopeWarp", + Value::Descriptor(Descriptor::new("customEnvelopeWarp").with("meshPoints", Value::ObjectArray(ObjectArray { prefix: 16, body: mesh }))), + ); + d = d.with("warp", Value::Descriptor(warp)); + } + let mut data = b"soLD".to_vec(); + data.extend_from_slice(&4u32.to_be_bytes()); + data.extend(VersionedDescriptor::new(d).to_bytes()); + data +} + +/// `SoLd` data with a split (quilt) custom warp, as Photoshop writes it: a `quiltWarp` +/// descriptor with `deformNumCols` × `deformNumRows` control points and the patch boundaries +/// in `quiltSliceX` / `quiltSliceY`. With `plain_warp`, a `warpNone` `warp` key sits next to it. +fn sold_with_quilt(trnf: [f64; 8], cols: f64, rows: f64, sx: &[f64], sy: &[f64], pts: &[[f64; 2]], plain_warp: bool) -> Vec { + use photocraft_psd::descriptor::ObjectArray; + let e = |t: &str, v: &str| Value::Enumerated { type_id: Id::new(t), value: Id::new(v) }; + let bounds = || { + Descriptor::new("Rctn") + .with("Top ", Value::Double(0.0)) + .with("Left", Value::Double(0.0)) + .with("Btom", Value::Double(25.0)) + .with("Rght", Value::Double(50.0)) + }; + let slices = |k: &str, v: &[f64]| { + let body = Descriptor::new("null").with(k, Value::UnitFloats { unit: *b"#Pxl", values: v.to_vec() }); + Value::ObjectArray(ObjectArray { prefix: v.len() as u32, body }) + }; + let mesh = Descriptor::new("null") + .with("Hrzn", Value::UnitFloats { unit: *b"#Pxl", values: pts.iter().map(|p| p[0]).collect() }) + .with("Vrtc", Value::UnitFloats { unit: *b"#Pxl", values: pts.iter().map(|p| p[1]).collect() }); + let envelope = Descriptor::new("customEnvelopeWarp") + .with("quiltSliceX", slices("quiltSliceX", sx)) + .with("quiltSliceY", slices("quiltSliceY", sy)) + .with("meshPoints", Value::ObjectArray(ObjectArray { prefix: 16, body: mesh })); + let quilt = Descriptor::new("quiltWarp") + .with("warpStyle", e("warpStyle", "warpCustom")) + .with("bounds", Value::Descriptor(bounds())) + .with("deformNumRows", Value::Integer(rows as i32)) + .with("deformNumCols", Value::Double(cols)) + .with("customEnvelopeWarp", Value::Descriptor(envelope)); + let mut d = Descriptor::new("null") + .with("Idnt", Value::Text(UnicodeString::new_nul("uuid-1"))) + .with("Trnf", Value::List(trnf.map(Value::Double).to_vec())) + .with("Sz ", Value::Descriptor(Descriptor::new("Pnt ").with("Wdth", Value::Double(50.0)).with("Hght", Value::Double(25.0)))); + if plain_warp { + d = d + .with("warp", Value::Descriptor(Descriptor::new("warp").with("warpStyle", e("warpStyle", "warpNone")).with("bounds", Value::Descriptor(bounds())))); + } + d = d.with("quiltWarp", Value::Descriptor(quilt)); + let mut data = b"soLD".to_vec(); + data.extend_from_slice(&4u32.to_be_bytes()); + data.extend(VersionedDescriptor::new(d).to_bytes()); + data +} + +/// A 3 × 2 patch identity grid over the 50 × 25 source with one interior control point pulled. +fn quilt_points() -> Vec<[f64; 2]> { + let mut pts = photocraft_geom::warp::BezierMesh::identity([0.0, 0.0, 50.0, 25.0], 3, 2).points; + if let Some(p) = pts.get_mut(10 * 3 + 4) { + p[1] += 3.0; + } + pts +} + +/// Photoshop's split warp (`quiltWarp`, mockups' usual warp) reads as a multi-patch mesh: the +/// patch boundaries become the knots, the control points stay in order, and the quilt wins over +/// the `warpNone` `warp` key written next to it. Before, any mesh but 4 × 4 was dropped and the +/// layer re-rendered flat. +#[test] +fn quilt_warp_is_read_as_a_multi_patch_mesh() { + let quad = [100.0, 200.0, 240.0, 200.0, 240.0, 260.0, 100.0, 260.0]; + let pts = quilt_points(); + // Photoshop pads the outer boundaries a little past the grid's edges. + let data = sold_with_quilt(quad, 10.0, 7.0, &[-0.5, 12.5, 37.5, 50.5], &[-0.5, 12.5, 25.5], &pts, true); + let warp = parse_placed_warp(b"SoLd", &data).expect("a quilt warp"); + let mesh = warp.mesh.as_ref().expect("its mesh"); + assert_eq!(mesh.points, pts); + assert_eq!(mesh.us.len(), 4); + assert_eq!(mesh.vs.len(), 3); + assert_eq!((mesh.us[0], mesh.us[3], mesh.vs[0], mesh.vs[2]), (0.0, 1.0, 0.0, 1.0)); + assert!((mesh.us[1] - 13.0 / 51.0).abs() < 1e-12 && (mesh.vs[1] - 13.0 / 26.0).abs() < 1e-12); + assert!(mesh.is_valid()); +} + +/// A quilt's control points frame the placed quad as a single patch's do (#3677): a grid +/// spilling to x = -10, y = -5 and x = 60 frames a 70 × 30 box. +#[test] +fn quilt_warp_control_box_frames_the_quad() { + let mut pts = quilt_points(); + pts[0] = [-10.0, -5.0]; + if let Some(last) = pts.last_mut() { + *last = [60.0, 25.0]; + } + let quad = [100.0, 200.0, 240.0, 200.0, 240.0, 260.0, 100.0, 260.0]; + let data = sold_with_quilt(quad, 10.0, 7.0, &[0.0, 12.5, 37.5, 50.0], &[0.0, 12.5, 25.0], &pts, false); + assert_eq!(parse_smart(b"SoLd", &data).1.m, [2.0, 0.0, 0.0, 2.0, 120.0, 210.0]); +} + +/// An inconsistent quilt reads as no warp rather than a wrong one, and never panics. +#[test] +fn inconsistent_quilt_warps_are_not_read() { + let quad = [100.0, 200.0, 240.0, 200.0, 240.0, 260.0, 100.0, 260.0]; + let pts = quilt_points(); + let (sx, sy) = ([0.0, 12.5, 37.5, 50.0], [0.0, 12.5, 25.0]); + let read = + |cols: f64, rows: f64, sx: &[f64], sy: &[f64], pts: &[[f64; 2]]| parse_placed_warp(b"SoLd", &sold_with_quilt(quad, cols, rows, sx, sy, pts, false)); + assert!(read(10.0, 7.0, &sx, &sy, &pts).is_some()); + assert!(read(9.0, 7.0, &sx, &sy, &pts).is_none(), "not three points per patch side plus one"); + assert!(read(13.0, 7.0, &sx, &sy, &pts).is_none(), "more points claimed than stored"); + assert!(read(10.0, 7.0, &[0.0, 12.5, 50.0], &sy, &pts).is_none(), "one slice per patch boundary"); + assert!(read(10.0, 7.0, &[0.0, 37.5, 12.5, 50.0], &sy, &pts).is_none(), "slices must increase"); + assert!(read(10.0, 7.0, &[0.0, f64::NAN, 37.5, 50.0], &sy, &pts).is_none()); + assert!(read(1e9, 7.0, &sx, &sy, &pts).is_none(), "an absurd grid is refused before any arithmetic"); + assert!(read(10.0, 7.0, &sx, &sy, &pts[..pts.len() - 1]).is_none()); + let mut nan = pts.clone(); + nan[3] = [f64::NAN, 0.0]; + assert!(read(10.0, 7.0, &sx, &sy, &nan).is_none()); +} + +/// Photoshop's `Trnf` is the image of the custom warp's control-point bounding box, not of the +/// source rect: a mesh spilling to x = -10, y = -5 and x = 60 frames a 70 × 30 box. +#[test] +fn smart_transform_maps_the_warp_control_box_onto_the_quad() { + let mut pts = photocraft_geom::warp::BezierMesh::identity([0.0, 0.0, 50.0, 25.0], 1, 1).points; + pts[0] = [-10.0, -5.0]; + pts[15] = [60.0, 25.0]; + let quad = [100.0, 200.0, 240.0, 200.0, 240.0, 260.0, 100.0, 260.0]; + let (_, a) = parse_smart(b"SoLd", &sold_with_warp(quad, Some(&pts))); + assert_eq!(a.m, [2.0, 0.0, 0.0, 2.0, 120.0, 210.0]); + // Without a warp the source rect is the frame, as before. + assert_eq!(parse_smart(b"SoLd", &sold_with_warp(quad, None)).1.m, [2.8, 0.0, 0.0, 2.4, 100.0, 200.0]); +} + +/// A custom mesh with no area (every control point on one spot) can't frame the quad: the +/// source rect does, with no division by zero. +#[test] +fn smart_transform_with_a_degenerate_warp_box_uses_the_source_rect() { + let quad = [100.0, 200.0, 240.0, 200.0, 240.0, 260.0, 100.0, 260.0]; + let (_, a) = parse_smart(b"SoLd", &sold_with_warp(quad, Some(&[[7.0, 7.0]; 16]))); + assert_eq!(a.m, [2.8, 0.0, 0.0, 2.4, 100.0, 200.0]); + let mut warp = photocraft_geom::warp::Warp::preset(photocraft_geom::warp::WarpStyle::Custom, 0.0, [0.0, 0.0, 50.0, 25.0]); + warp.mesh = Some(photocraft_geom::warp::BezierMesh { us: vec![0.0, 1.0], vs: vec![0.0, 1.0], points: vec![[f64::NAN, 1.0]; 16] }); + assert_eq!(placed_frame(Some(&warp), 50.0, 25.0), [0.0, 0.0, 50.0, 25.0]); + assert_eq!(placed_frame(None, 50.0, 25.0), [0.0, 0.0, 50.0, 25.0]); +} + +/// A `SoLd` placed on `quad` (`Trnf` and `nonAffineTransform`) for a 1000 × 1000 source, +/// warped by `warp`. +fn sold_placed(quad: [f64; 8], warp: Descriptor) -> Vec { + let list = Value::List(quad.iter().map(|v| Value::Double(*v)).collect()); + let d = Descriptor::new("null") + .with("Trnf", list.clone()) + .with("nonAffineTransform", list) + .with("Sz ", Value::Descriptor(Descriptor::new("Pnt ").with("Wdth", Value::Double(1000.0)).with("Hght", Value::Double(1000.0)))) + .with("warp", Value::Descriptor(warp)); + let mut data = b"soLD".to_vec(); + data.extend_from_slice(&4u32.to_be_bytes()); + data.extend(VersionedDescriptor::new(d).to_bytes()); + data +} + +/// A `warpCylinder` descriptor as #4112 describes it: horizontal, no perspective, seven +/// `warpValues` in the space of `bounds`. +fn cylinder_desc(values: Value) -> Descriptor { + let e = |t: &str, v: &str| Value::Enumerated { type_id: Id::new(t), value: Id::new(v) }; + let bounds = Descriptor::new("classFloatRect") + .with("Top ", Value::Double(0.0)) + .with("Left", Value::Double(0.0)) + .with("Btom", Value::Double(1000.0)) + .with("Rght", Value::Double(1000.0)); + Descriptor::new("warp") + .with("warpStyle", e("warpStyle", "warpCylinder")) + .with("warpValue", Value::Double(0.0)) + .with("warpValues", values) + .with("warpPerspective", Value::Double(0.0)) + .with("warpPerspectiveOther", Value::Double(0.0)) + .with("warpRotate", e("Ornt", "Hrzn")) + .with("bounds", Value::Descriptor(bounds)) +} + +const CYL: [f64; 7] = [100.0, 800.0, 900.0, 200.0, 0.3, 0.3, 0.5]; + +fn doubles(v: &[f64]) -> Value { + Value::List(v.iter().map(|x| Value::Double(*x)).collect()) +} + +/// A projective placement is framed by the warp `parse_placed_warp` imports: an unreadable +/// `quiltWarp` next to a cylinder under `warp` imports no warp, so the source rect is framed. +#[test] +fn perspective_frame_follows_the_warp_parse_placed_warp_reads() { + let quad = [10.0, 20.0, 410.0, 60.0, 400.0, 480.0, 30.0, 520.0]; + let list = Value::List(quad.iter().map(|v| Value::Double(*v)).collect()); + let unreadable = Descriptor::new("quiltWarp").with("warpStyle", Value::Enumerated { type_id: Id::new("warpStyle"), value: Id::new("warpSomethingNew") }); + let d = Descriptor::new("null") + .with("Trnf", list.clone()) + .with("nonAffineTransform", list) + .with("Sz ", Value::Descriptor(Descriptor::new("Pnt ").with("Wdth", Value::Double(1000.0)).with("Hght", Value::Double(1000.0)))) + .with("quiltWarp", Value::Descriptor(unreadable)) + .with("warp", Value::Descriptor(cylinder_desc(doubles(&CYL)))); + let mut data = b"soLD".to_vec(); + data.extend_from_slice(&4u32.to_be_bytes()); + data.extend(VersionedDescriptor::new(d).to_bytes()); + assert_eq!(parse_placed_warp(b"SoLd", &data), None); + let h = photocraft_algo::transform::Homography(parse_smart_perspective(b"SoLd", &data).expect("projective")); + let (px, py) = h.apply(1000.0, 1000.0); + assert!((px - 400.0).abs() < 1e-6 && (py - 480.0).abs() < 1e-6, "{px},{py}"); +} +/// #4112: a `warpCylinder` placed layer comes in as the cylinder its seven values describe, +/// instead of no warp (which re-rendered the contents flat). +#[test] +fn placed_cylinder_warp_is_read() { + use photocraft_geom::warp::{Warp, WarpStyle}; + let quad = [0.0, 0.0, 800.0, 0.0, 800.0, 800.0, 0.0, 800.0]; + let want = Warp::cylinder(&CYL, [0.0, 0.0, 1000.0, 1000.0]).unwrap(); + let w = parse_placed_warp(b"SoLd", &sold_placed(quad, cylinder_desc(doubles(&CYL)))).expect("a cylinder"); + assert_eq!(w, want); + assert_eq!(w.style, WarpStyle::Cylinder); + // Values written as one unit-float list read the same. + let floats = Value::UnitFloats { unit: *b"#Pxl", values: CYL.to_vec() }; + assert_eq!(parse_placed_warp(b"SoLE", &sold_placed(quad, cylinder_desc(floats))), Some(want)); +} + +/// Cylinders nobody has measured (vertical, with perspective) and broken values stay +/// unreadable, as every cylinder was before: the layer keeps the pixels Photoshop stored. +#[test] +fn placed_cylinder_warps_that_cant_be_read() { + let quad = [0.0, 0.0, 800.0, 0.0, 800.0, 800.0, 0.0, 800.0]; + let read = |d: Descriptor| parse_placed_warp(b"SoLd", &sold_placed(quad, d)); + let e = |t: &str, v: &str| Value::Enumerated { type_id: Id::new(t), value: Id::new(v) }; + let with = |key: &str, v: Value| { + let mut d = cylinder_desc(doubles(&CYL)); + d.items.iter_mut().filter(|(k, _)| k.is(key)).for_each(|(_, old)| *old = v.clone()); + d + }; + assert!(read(with("warpRotate", e("Ornt", "Vrtc"))).is_none(), "vertical"); + assert!(read(with("warpPerspective", Value::Double(20.0))).is_none(), "perspective"); + assert!(read(with("warpPerspectiveOther", Value::Double(-5.0))).is_none(), "the other perspective"); + assert!(read(cylinder_desc(doubles(&CYL[..6]))).is_none(), "six values"); + assert!(read(cylinder_desc(Value::List(vec![Value::Text(UnicodeString::new_nul("x")); 7]))).is_none(), "not numbers"); + assert!(read(cylinder_desc(Value::Double(1.0))).is_none(), "one number"); + let mut flipped = CYL; + flipped.swap(0, 2); + assert!(read(cylinder_desc(doubles(&flipped))).is_none(), "silhouettes swapped"); + let mut no_values = cylinder_desc(doubles(&CYL)); + no_values.items.retain(|(k, _)| !k.is("warpValues")); + assert!(read(no_values).is_none(), "no warpValues"); +} + +/// Like a custom warp's (#3677), a cylinder's control-point box is what the placement quad +/// frames, for affine corners and for projective ones (`nonAffineTransform`). +#[test] +fn placed_cylinder_quad_frames_its_control_box() { + use photocraft_geom::warp::Warp; + let cb = Warp::cylinder(&CYL, [0.0, 0.0, 1000.0, 1000.0]).unwrap().mesh.unwrap().control_bounds(); + // Affine: the box lands on the quad. + let quad = [10.0, 20.0, 410.0, 20.0, 410.0, 520.0, 10.0, 520.0]; + let (_, a) = parse_smart(b"SoLd", &sold_placed(quad, cylinder_desc(doubles(&CYL)))); + let [m0, m1, m2, m3, m4, m5] = a.m; + let map = |x: f64, y: f64| (m0 * x + m2 * y + m4, m1 * x + m3 * y + m5); + for ((x, y), (qx, qy)) in + [(cb[0], cb[1]), (cb[2], cb[1]), (cb[2], cb[3]), (cb[0], cb[3])].into_iter().zip(quad.as_chunks::<2>().0.iter().map(|p| (p[0], p[1]))) + { + let (px, py) = map(x, y); + assert!((px - qx).abs() < 1e-9 && (py - qy).abs() < 1e-9, "{x},{y} → {px},{py}, not {qx},{qy}"); + } + assert!(parse_smart_perspective(b"SoLd", &sold_placed(quad, cylinder_desc(doubles(&CYL)))).is_none(), "affine"); + // Projective: the same box lands on the four corners. + let quad = [10.0, 20.0, 410.0, 60.0, 400.0, 480.0, 30.0, 520.0]; + let h = photocraft_algo::transform::Homography(parse_smart_perspective(b"SoLd", &sold_placed(quad, cylinder_desc(doubles(&CYL)))).expect("projective")); + for ((x, y), (qx, qy)) in + [(cb[0], cb[1]), (cb[2], cb[1]), (cb[2], cb[3]), (cb[0], cb[3])].into_iter().zip(quad.as_chunks::<2>().0.iter().map(|p| (p[0], p[1]))) + { + let (px, py) = h.apply(x, y); + assert!((px - qx).abs() < 1e-6 && (py - qy).abs() < 1e-6, "{x},{y} → {px},{py}, not {qx},{qy}"); + } + // Without a warp a projective quad still frames the source rect. + let none = Descriptor::new("warp").with("warpStyle", Value::Enumerated { type_id: Id::new("warpStyle"), value: Id::new("warpNone") }); + let h = photocraft_algo::transform::Homography(parse_smart_perspective(b"SoLd", &sold_placed(quad, none)).expect("projective")); + let (px, py) = h.apply(1000.0, 1000.0); + assert!((px - 400.0).abs() < 1e-6 && (py - 480.0).abs() < 1e-6); +} + +#[test] +fn effects_switch() { + let mut lfx = vec![0, 0, 0, 0]; + lfx.extend(VersionedDescriptor::new(Descriptor::new("null").with("masterFXSwitch", Value::Boolean(false))).to_bytes()); + assert!(!effects_enabled(&lfx)); + assert!(effects_enabled(&[0, 0, 0, 0])); +} + +#[test] +fn tysh_garbage_is_none() { + assert!(parse_tysh(&[0; 10]).is_none()); +} diff --git a/crates/io/src/blocks/tests.rs b/crates/io/src/blocks/tests.rs new file mode 100644 index 0000000000..59193a9344 --- /dev/null +++ b/crates/io/src/blocks/tests.rs @@ -0,0 +1,335 @@ +use super::*; + +fn noise_gradient_fill(min: [i32; 4], max: [i32; 4], add_transparency: bool) -> Descriptor { + let values = |v: [i32; 4]| Value::List(v.into_iter().map(Value::Integer).collect()); + let gradient = Descriptor::new("Grdn") + .with("GrdF", Value::Enumerated { type_id: Id::new("GrdF"), value: Id::new("ClNs") }) + .with("ClrS", Value::Enumerated { type_id: Id::new("ClrS"), value: Id::new("RGBC") }) + .with("ShTr", Value::Boolean(add_transparency)) + .with("VctC", Value::Boolean(true)) + .with("RndS", Value::Integer(9052369)) + .with("Smth", Value::Integer(2048)) + .with("Mnm ", values(min)) + .with("Mxm ", values(max)); + Descriptor::new("null").with("Grad", Value::Descriptor(gradient)) +} + +#[test] +fn constant_rgb_noise_fill_uses_its_exact_colour() { + use photocraft_doc::Fill; + let fill = fill_from_desc(b"GdFl", &noise_gradient_fill([50, 25, 0, 0], [50, 25, 0, 100], false)); + let Some(Fill::Gradient { stops, .. }) = fill else { panic!("constant noise gradient") }; + assert_eq!(stops, vec![(0.0, Color::rgb(0.5, 0.25, 0.0)), (1.0, Color::rgb(0.5, 0.25, 0.0))]); +} + +#[test] +fn variable_or_transparent_noise_stays_a_fill_with_the_placeholder_ramp() { + use photocraft_doc::Fill; + // Photoshop's default Noise gradient (min 0, max 100) and a transparent variant: no + // exact colour is provable, but the fill must parse — the layer keeps its type, its + // stored pixels (`fill_cache`) and its raw `GdFl` block. Only the uncached preview + // shows the placeholder ramp. + for descriptor in [noise_gradient_fill([0, 0, 0, 0], [100, 100, 100, 100], false), noise_gradient_fill([50, 25, 0, 0], [50, 25, 0, 100], true)] { + let Some(Fill::Gradient { stops, .. }) = fill_from_desc(b"GdFl", &descriptor) else { panic!("variable noise gradient must stay a fill layer") }; + assert_eq!(stops, vec![(0.0, Color::BLACK), (1.0, Color::WHITE)]); + } +} + +/// psd-tools layers-minimal/gradient-fill.psd ("Color to Transparent", no stored pixels): a +/// gradient fill's opacity stops reach the model (as its opacity stops; written from stop +/// alpha) and survive a write; the ramp's alpha follows them. +#[test] +fn gradient_fill_opacity_stops_become_alpha() { + use photocraft_color::Color; + use photocraft_doc::{Fill, GradientStyle}; + let red = Color::rgba(1.0, 0.0, 0.0, 1.0); + let f = Fill::gradient(vec![(0.0, red), (1.0, Color { alpha: 0.0, ..red })], 90.0, 1.0, GradientStyle::Linear, false); + let (k, data) = super::write_fill(&f); + let back = super::parse_fill(&k, &data).unwrap(); + let Fill::Gradient { stops, opacity_stops, .. } = &back else { panic!("gradient") }; + assert_eq!(opacity_stops, &vec![(0.0, 1.0), (1.0, 0.0)]); + assert!(stops.iter().all(|s| s.1.c[0] == 1.0 && s.1.c[1] == 0.0)); + let ramp = photocraft_compose::gradient_fill::Ramp::new(&back).unwrap(); + assert_eq!(ramp.sample(0.0)[3], 1.0); + assert!(ramp.sample(1.0)[3] < 0.01); + // Opaque gradients come back without opacity stops. + let (k, data) = super::write_fill(&Fill::gradient(vec![(0.0, red), (1.0, Color::WHITE)], 0.0, 1.0, GradientStyle::Linear, false)); + let Some(Fill::Gradient { opacity_stops, .. }) = super::parse_fill(&k, &data) else { panic!("gradient") }; + assert!(opacity_stops.is_empty()); +} + +/// Photoshop 27.11 stores a gradient's method as the enum `gradientsInterpolationMethod` +/// (seen in gradient fill layers saved by scripted Photoshop): a black→white Linear gradient +/// is at 188 of 255 halfway (measured), where Classic gives 128. The key used to be read as +/// `gs99`, which Photoshop doesn't write, so every gradient opened as Classic. +#[test] +fn gradient_fill_reads_the_interpolation_method() { + use photocraft_color::Color; + use photocraft_doc::{Fill, GradientStyle}; + use photocraft_psd::descriptor::{Id, Value}; + let f = Fill::gradient(vec![(0.0, Color::BLACK), (1.0, Color::WHITE)], 0.0, 1.0, GradientStyle::Linear, false); + let (k, data) = super::write_fill(&f); + let d = super::parse_prefix_versioned(&data).unwrap(); + let mid = |code: &str| { + let d = d.clone().with("gradientsInterpolationMethod", Value::Enumerated { type_id: Id::new("gradientInterpolationMethodType"), value: Id::new(code) }); + let back = super::fill_from_desc(&k, &d).unwrap(); + let ramp = photocraft_compose::gradient_fill::Ramp::new(&back).unwrap(); + (ramp.sample(0.5)[0] * 255.0).round() + }; + assert_eq!(mid("Gcls"), 128.0); + assert!((mid("Lnr ") - 188.0).abs() <= 1.0, "Linear: {}", mid("Lnr ")); + assert!((mid("Perc") - 99.0).abs() <= 2.0, "Perceptual: {}", mid("Perc")); + assert!((mid("Smoo") - 99.0).abs() <= 2.0, "Smooth: {}", mid("Smoo")); +} + +#[test] +fn lab_descriptor_colours_round_trip() { + use photocraft_color::ColorMode; + use photocraft_psd::descriptor::{Descriptor, Value}; + let d = Descriptor::new("LbCl").with("Lmnc", Value::Double(19.07)).with("A ", Value::Double(52.29)).with("B ", Value::Double(-85.08)); + let c = super::color_from_desc(&d).unwrap(); + assert_eq!(c.mode, ColorMode::Lab); + assert!((c.c[0] - 0.1907).abs() < 1e-5 && (c.c[1] * 255.0 - 128.0 - 52.29).abs() < 1e-3 && (c.c[2] * 255.0 - 128.0 + 85.08).abs() < 1e-3); + let back = super::color_from_desc(&super::color_to_desc(&c)).unwrap(); + assert_eq!(back.mode, ColorMode::Lab); + for i in 0..3 { + assert!((back.c[i] - c.c[i]).abs() < 1e-6); + } + // Missing components are rejected, not defaulted. + assert!(super::color_from_desc(&Descriptor::new("LbCl").with("Lmnc", Value::Double(50.0))).is_none()); +} + +/// Colours stored as HSB (`HSBC`: `H ` an angle in degrees, `Strt`/`Brgh` 0..100), as in +/// psd-tools `stroke-color-descriptors-hsb-with-rgb-mode.psd`, used to be dropped (#6774). +#[test] +fn hsb_descriptor_colours_parse() { + use photocraft_doc::Fill; + use photocraft_psd::descriptor::{Descriptor, Value}; + let hsb = |h: f64, s: f64, b: f64| { + Descriptor::new("HSBC").with("H ", Value::UnitFloat { unit: *b"#Ang", value: h }).with("Strt", Value::Double(s)).with("Brgh", Value::Double(b)) + }; + let close = |c: [f32; 3], e: [f32; 3]| c.iter().zip(e).all(|(a, b)| (a - b).abs() < 1e-5); + let green = super::color_from_desc(&hsb(120.0, 100.0, 100.0)).unwrap().to_rgb(); + assert!(close(green, [0.0, 1.0, 0.0]), "{green:?}"); + let white = super::color_from_desc(&hsb(0.0, 0.0, 100.0)).unwrap().to_rgb(); + assert!(close(white, [1.0, 1.0, 1.0]), "{white:?}"); + let half = super::color_from_desc(&hsb(240.0, 50.0, 50.0)).unwrap().to_rgb(); + assert!(close(half, [0.25, 0.25, 0.5]), "{half:?}"); + // A solid fill (`SoCo`) with an HSB colour is read, not lost. + let soco = Descriptor::new("null").with("Clr ", Value::Descriptor(hsb(0.0, 100.0, 100.0))); + let Some(Fill::Solid(c)) = super::fill_from_desc(b"SoCo", &soco) else { panic!("solid fill") }; + assert!(close(c.to_rgb(), [1.0, 0.0, 0.0]), "{:?}", c.to_rgb()); + // Missing components are rejected, not defaulted. + assert!(super::color_from_desc(&Descriptor::new("HSBC").with("Strt", Value::Double(50.0))).is_none()); +} + +#[test] +fn color_descriptor_keeps_photocraft_alpha() { + use photocraft_color::Color; + use photocraft_doc::Fill; + let c = Color::rgba(0.2, 0.4, 0.6, 0.25); + let (k, d) = super::fill_to_desc(&Fill::Solid(c)); + let Fill::Solid(back) = super::fill_from_desc(&k, &d).unwrap() else { panic!("solid") }; + assert!((back.alpha - 0.25).abs() < 1e-5); + assert!((back.to_rgb()[0] - 0.2).abs() < 1e-3); + let (k, d) = super::fill_to_desc(&Fill::Solid(Color::rgb(1.0, 0.0, 0.0))); + let Fill::Solid(opaque) = super::fill_from_desc(&k, &d).unwrap() else { panic!("solid") }; + assert!((opaque.alpha - 1.0).abs() < 1e-6); + assert!(super::color_to_desc(&c).get("pcAl").is_none(), "generic colour descriptors have no pcAl"); +} + +#[test] +fn non_finite_photocraft_alpha_is_ignored() { + use photocraft_color::Color; + for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + let d = super::color_to_desc(&Color::rgb(0.2, 0.4, 0.6)).with("pcAl", Value::Double(bad)); + let c = super::color_from_desc(&d).unwrap(); + assert_eq!(c.alpha, 1.0, "pcAl {bad}"); + } + let d = super::color_to_desc(&Color::rgb(0.2, 0.4, 0.6)).with("pcAl", Value::Double(0.5)); + assert!((super::color_from_desc(&d).unwrap().alpha - 0.5).abs() < 1e-6); +} + +#[test] +fn gradient_stop_alpha_round_trips_once() { + use photocraft_color::Color; + use photocraft_doc::Fill; + let fill = Fill::Gradient { + stops: vec![(0.0, Color::rgba(1.0, 0.0, 0.0, 0.5)), (1.0, Color::WHITE)], + angle: 90.0, + scale: 1.0, + style: photocraft_doc::GradientStyle::Linear, + reverse: false, + opacity_stops: vec![], + midpoints: vec![], + offset: (0.0, 0.0), + dither: false, + align: true, + }; + let (k, d) = super::fill_to_desc(&fill); + let Fill::Gradient { stops, opacity_stops, .. } = super::fill_from_desc(&k, &d).unwrap() else { panic!("grad") }; + assert!((stops[0].1.alpha - 1.0).abs() < 1e-4, "colour alpha lives in Trns, not the stop colour"); + assert!(opacity_stops.iter().any(|(_, a)| (*a - 0.5).abs() < 1e-3), "{opacity_stops:?}"); +} + +#[test] +fn blending_ranges_map_to_blend_if() { + use photocraft_doc::{BlendIf, BlendRange}; + use photocraft_psd::layer::BlendingRanges; + // Full ranges (what every layer without Blend If carries) → the default setting. + assert_eq!(super::blend_if_from_ranges(&BlendingRanges::full(3)), BlendIf::default()); + assert_eq!(super::blend_if_from_ranges(&BlendingRanges::default()), BlendIf::default()); + // Gray: This Layer black split 10/40; Blue (entry 3): Underlying white at 200. + let mut data = BlendingRanges::full(3).data; + data[..4].copy_from_slice(&[10, 40, 255, 255]); + data[3 * 8 + 4..3 * 8 + 8].copy_from_slice(&[0, 0, 200, 200]); + let b = super::blend_if_from_ranges(&BlendingRanges { data: data.clone() }); + assert_eq!(b.get(0), [BlendRange { black: [10, 40], white: [255, 255] }, BlendRange::FULL]); + assert_eq!(b.get(3), [BlendRange::FULL, BlendRange { black: [0, 0], white: [200, 200] }]); + assert_eq!(b.ranges.len(), 4); + assert_eq!(super::ranges_from_blend_if(&b, 3).data, data); + // The default writes full ranges for gray + each channel. + assert_eq!(super::ranges_from_blend_if(&BlendIf::default(), 4), BlendingRanges::full(4)); + // A trimmed setting is padded to the document's channel count. + let mut short = BlendIf::default(); + short.set(0, [BlendRange { black: [5, 5], white: [255, 255] }, BlendRange::FULL]); + let r = super::ranges_from_blend_if(&short, 3); + assert_eq!(r.data.len(), 4 * 8); + assert_eq!(&r.data[..8], &[5, 5, 255, 255, 0, 0, 255, 255]); + assert_eq!(&r.data[8..], &BlendingRanges::full(2).data[..]); +} + +#[test] +fn advanced_blending_blocks_round_trip() { + use photocraft_doc::{AdvancedBlending, Knockout}; + let a = AdvancedBlending { + knockout: Knockout::Deep, + blend_interior: true, + blend_clipped: false, + transparency_shapes: false, + layer_mask_hides_effects: true, + vector_mask_hides_effects: true, + }; + let mut raw = Vec::new(); + super::put_advanced(&a, &mut raw); + assert_eq!(raw.len(), 6); + assert!(raw.contains(&(*b"knko", vec![2, 0, 0, 0]))); + assert!(raw.contains(&(*b"clbl", vec![0, 0, 0, 0]))); + let get = |k: &[u8; 4]| raw.iter().find(|(bk, _)| bk == k).map(|(_, d)| d.as_slice()); + assert_eq!(super::advanced_from_blocks(get), a); + // Defaults: nothing added to a plain layer; existing blocks rewritten in place, in order. + let mut plain = Vec::new(); + super::put_advanced(&AdvancedBlending::default(), &mut plain); + assert!(plain.is_empty()); + let mut kept = vec![(*b"luni", vec![0; 4]), (*b"knko", vec![1, 0, 0, 0]), (*b"clbl", vec![1])]; + super::put_advanced(&AdvancedBlending::default(), &mut kept); + assert_eq!(kept, vec![(*b"luni", vec![0; 4]), (*b"knko", vec![0, 0, 0, 0]), (*b"clbl", vec![1, 0, 0, 0])]); + // Missing and empty blocks read as Photoshop's defaults. + assert!(super::advanced_from_blocks(|_| None).is_default()); + assert!(super::advanced_from_blocks(|_| Some(&[][..])).is_default()); + assert_eq!(super::advanced_from_blocks(|k| (k == b"knko").then_some(&[1u8][..])).knockout, Knockout::Shallow); +} + +#[test] +fn brst_round_trip() { + assert_eq!(super::parse_brst(&[0, 0, 0, 2]), 0b100); + assert_eq!(super::parse_brst(&[0, 0, 0, 0, 0, 0, 0, 1]), 0b11); + assert_eq!(super::brst_data(0b101).unwrap(), vec![0, 0, 0, 0, 0, 0, 0, 2]); + assert_eq!(super::brst_data(0), None); +} + +#[test] +fn placed_layer_warp_is_read() { + use photocraft_geom::warp::WarpStyle; + use photocraft_psd::descriptor::ObjectArray; + let e = |t: &str, v: &str| Value::Enumerated { type_id: Id::new(t), value: Id::new(v) }; + let bounds = Descriptor::new("Rctn") + .with("Top ", Value::UnitFloat { unit: *b"#Pxl", value: 0.0 }) + .with("Left", Value::UnitFloat { unit: *b"#Pxl", value: 0.0 }) + .with("Btom", Value::UnitFloat { unit: *b"#Pxl", value: 30.0 }) + .with("Rght", Value::UnitFloat { unit: *b"#Pxl", value: 60.0 }); + let sold = |warp: Descriptor| { + let mut v = b"soLD".to_vec(); + v.extend_from_slice(&4u32.to_be_bytes()); + v.extend(VersionedDescriptor::new(Descriptor::new("null").with("warp", Value::Descriptor(warp))).to_bytes()); + v + }; + let arc = Descriptor::new("warp") + .with("warpStyle", e("warpStyle", "warpArc")) + .with("warpValue", Value::Double(40.0)) + .with("warpPerspective", Value::Double(0.0)) + .with("warpPerspectiveOther", Value::Double(0.0)) + .with("warpRotate", e("Ornt", "Hrzn")) + .with("bounds", Value::Descriptor(bounds.clone())); + let w = parse_placed_warp(b"SoLd", &sold(arc)).unwrap(); + assert_eq!((w.style, w.bend, w.bounds), (WarpStyle::Arc, 40.0, [0.0, 0.0, 60.0, 30.0])); + let (mut xs, mut ys) = (Vec::new(), Vec::new()); + for j in 0..4 { + for i in 0..4 { + xs.push(f64::from(i) * 20.0 + if i == 3 && j == 3 { 7.0 } else { 0.0 }); + ys.push(f64::from(j) * 10.0); + } + } + let mesh = + Descriptor::new("null").with("Hrzn", Value::UnitFloats { unit: *b"#Pxl", values: xs }).with("Vrtc", Value::UnitFloats { unit: *b"#Pxl", values: ys }); + let custom = Descriptor::new("warp").with("warpStyle", e("warpStyle", "warpCustom")).with("bounds", Value::Descriptor(bounds)).with( + "customEnvelopeWarp", + Value::Descriptor(Descriptor::new("customEnvelopeWarp").with("meshPoints", Value::ObjectArray(ObjectArray { prefix: 16, body: mesh }))), + ); + let w = parse_placed_warp(b"SoLd", &sold(custom)).unwrap(); + assert_eq!(w.style, WarpStyle::Custom); + assert_eq!(w.mesh.as_ref().unwrap().points[15], [67.0, 30.0]); + assert!(parse_placed_warp(b"PlLd", &[0; 20]).is_none()); +} + +#[test] +fn locks_and_labels() { + // Reference values round-trip byte for byte; Background layers carry 0x0D + // (transparency + position + the bit-3 lock reference files write). + for bits in [0u32, 1, 2, 4, 8, 0x0D, 0x8000_0000, 0x8000_000F] { + assert_eq!(lspf_from_locks(&locks_from_lspf(bits)), bits); + } + // Older PhotoCraft files wrote the artboard lock at 0x10; it reads back as artboard + // and is rewritten at the reference value 0x08. + assert!(locks_from_lspf(0x10).artboard); + assert_eq!(lspf_from_locks(&locks_from_lspf(0x10)), 0x08); + for i in 0..8 { + assert_eq!(label_index(label_from_index(i)), i); + } +} + +#[test] +fn fills_roundtrip() { + for f in [ + Fill::Solid(Color::rgb(1.0, 0.5, 0.0)), + Fill::Solid(Color { mode: ColorMode::Cmyk, c: [0.1, 0.2, 0.3, 0.4], alpha: 1.0 }), + Fill::Solid(Color::gray(0.25)), + Fill::gradient(vec![(0.0, Color::rgb(1.0, 0.0, 0.0)), (1.0, Color::rgb(0.0, 0.0, 1.0))], 45.0, 1.0, GradientStyle::Reflected, true), + // A live gradient (Gradient tool): canvas-aligned, offset, midpoints, opacity, dither. + Fill::Gradient { + stops: vec![(0.0, Color::rgb(1.0, 0.0, 0.0)), (0.5, Color::rgb(0.0, 1.0, 0.0)), (1.0, Color::rgb(0.0, 0.0, 1.0))], + angle: -33.5, + scale: 2.25, + style: GradientStyle::Radial, + reverse: false, + opacity_stops: vec![(0.0, 1.0), (0.25, 0.5), (1.0, 0.0)], + midpoints: vec![0.25, 0.75], + offset: (0.125, -0.375), + dither: true, + align: false, + }, + Fill::Pattern { name: "Bubbles".into(), scale: 0.5, id: "abc".into(), angle: 30.0, link: false, phase: (3.0, -2.0) }, + ] { + let (k, d) = write_fill(&f); + let back = parse_fill(&k, &d).unwrap(); + match (&f, &back) { + (Fill::Solid(a), Fill::Solid(b)) => { + assert_eq!(a.mode, b.mode); + for i in 0..4 { + assert!((a.c[i] - b.c[i]).abs() < 1e-5); + } + } + _ => assert_eq!(back, f), + } + } +} diff --git a/crates/io/src/camera_raw_map.rs b/crates/io/src/camera_raw_map.rs index cfe3ad6be2..a53d6d40c6 100644 --- a/crates/io/src/camera_raw_map.rs +++ b/crates/io/src/camera_raw_map.rs @@ -343,329 +343,5 @@ pub(super) fn export_item(params: &J) -> Result { } #[cfg(test)] -mod tests { - use super::*; - use crate::smart_map::{UNSUPPORTED_FILTER, filter_from_item, item_for_filter}; - use photocraft_color::BlendMode; - - // Parameter values observed in the supplied 18.4 PSD. No source pixels or private - // document metadata are included in this synthetic regression fixture. - fn source_item() -> Descriptor { - let mut d = Descriptor::new(CLASS) - .with("CrVe", Value::Text(UnicodeString::new_nul("18.4"))) - .with("PrVN", Value::Integer(6)) - .with("PrVe", Value::Integer(251920384)) - .with("Ex12", Value::Double(1.15)); - for (key, value) in [ - ("Cr12", -38), - ("Hi12", 35), - ("Sh12", -50), - ("Wh12", 49), - ("Bk12", -34), - ("PC_S", 0), - ("PC_D", -21), - ("PC_L", 38), - ("PC_H", 0), - ("PC_1", 25), - ("PC_2", 50), - ("PC_3", 75), - ] { - d = d.with(key, Value::Integer(value)); - } - for (_, keys) in ARRAYS.iter().skip(1) { - for key in *keys { - let value = match *key { - "HA_R" => -50, - "HA_Y" => 29, - "HA_G" => 1, - _ => 0, - }; - d = d.with(key, Value::Integer(value)); - } - } - let f = SmartFilter { command: COMMAND.into(), params: J::Null, blend: BlendMode::Normal, opacity: 1.0, visible: true }; - Descriptor::new("filterFX") - .with("Nm ", Value::Text(UnicodeString::new_nul("Camera Raw Filter"))) - .with("blendOptions", blend_options(&f)) - .with("enab", Value::Boolean(true)) - .with("hasoptions", Value::Boolean(true)) - .with("FrgC", rgbc(0.0)) - .with("BckC", rgbc(255.0)) - .with("Fltr", Value::Descriptor(d)) - .with("filterID", Value::Integer(FILTER_ID)) - } - - fn all_controls_item() -> Descriptor { - let mut item = source_item(); - let mut d = get_desc(&item, "Fltr").unwrap().clone(); - set(&mut d, "WBal", Value::Enumerated { type_id: photocraft_psd::descriptor::Id::new("WBal"), value: photocraft_psd::descriptor::Id::new("Cst ") }); - set(&mut d, "ShpR", Value::Double(1.2)); - for (key, value) in [ - ("Temp", -26), - ("Tint", -25), - ("CrTx", -31), - ("Cl12", 30), - ("Dhze", -34), - ("Vibr", 33), - ("Strt", 33), - ("Shrp", 43), - ("ShpD", 36), - ("ShpM", 30), - ("LNR ", 47), - ("LNRD", 50), - ("CNR ", 25), - ("CNRD", 50), - ("STSH", 117), - ("STSS", 52), - ("STHH", 316), - ("STHS", 70), - ("STB ", 35), - ("CgMH", 51), - ("CgMS", 51), - ("CgSL", -24), - ("CgML", 41), - ("CgHL", 28), - ("CgBl", 36), - ("CgGH", 20), - ("CgGS", 61), - ("CgGL", 45), - ("GRNA", 45), - ("GRNS", 25), - ("GRNF", 50), - ("PCVA", 31), - ("PCVM", 50), - ("PCVF", 50), - ("PCVR", 0), - ] { - set(&mut d, key, Value::Integer(value)); - } - for (key, neutral) in NEUTRAL_ONLY { - set(&mut d, key, Value::Integer(*neutral)); - } - for (key, x, y) in [("Crv ", 146, 102), ("CrvR", 90, 174), ("CrvG", 162, 122), ("CrvB", 129, 202)] { - set(&mut d, key, Value::List([0, 0, x, y, 255, 255].into_iter().map(Value::Integer).collect())); - } - set(&mut item, "Fltr", Value::Descriptor(d)); - item - } - - #[test] - fn all_observed_develop_controls_roundtrip_and_patch_only_the_edited_field() { - let source = all_controls_item(); - let f = filter_from_item(&source); - assert_eq!(f.command, COMMAND); - assert_eq!(f.params["temperature"], -26.0); - assert_eq!(f.params["texture"], -31.0); - assert!((f.params["sharpenRadius"].as_f64().unwrap() - 1.2).abs() < 1e-6); - assert_eq!(f.params["gradeHighlights"], json!({"hue": 316.0, "sat": 70.0, "lum": 28.0})); - assert_eq!(f.params["pointCurveBlue"], json!([[0.0, 0.0], [129.0, 202.0], [255.0, 255.0]])); - assert_eq!(item_for_filter(&f).unwrap(), source); - let defaults = default_params().unwrap(); - for (param, key) in SCALARS { - let mut edited = f.clone(); - let mut number = get_param(&defaults, param).unwrap().as_f64().unwrap(); - if get_param(&f.params, param).unwrap().as_f64() == Some(number) { - number += 1.0; - } - *get_param_mut(&mut edited.params, param).unwrap() = json!(number); - let mut expected = get_desc(&source, "Fltr").unwrap().clone(); - set(&mut expected, key, if matches!(*key, "Ex12" | "ShpR") { Value::Double(number) } else { Value::Integer(number as i32) }); - assert_eq!(get_desc(&item_for_filter(&edited).unwrap(), "Fltr"), Some(&expected), "{param}"); - } - for (param, key) in CURVES { - let mut edited = f.clone(); - edited.params[*param] = json!([]); - let item = item_for_filter(&edited).unwrap(); - let mut expected = get_desc(&source, "Fltr").unwrap().clone(); - set(&mut expected, key, Value::List([0, 0, 255, 255].into_iter().map(Value::Integer).collect())); - assert_eq!(get_desc(&item, "Fltr"), Some(&expected), "{param}"); - assert_eq!(filter_from_item(&item).params[*param], json!([]), "{param}"); - } - } - - #[test] - fn active_unimplemented_controls_and_malformed_curves_stay_opaque() { - for (key, neutral) in NEUTRAL_ONLY { - let mut item = all_controls_item(); - let mut d = get_desc(&item, "Fltr").unwrap().clone(); - set(&mut d, key, Value::Integer(neutral + 1)); - set(&mut item, "Fltr", Value::Descriptor(d)); - let f = filter_from_item(&item); - assert_eq!(f.command, UNSUPPORTED_FILTER, "{key}"); - assert_eq!(item_for_filter(&f).unwrap(), item, "{key}"); - } - for value in [ - Value::List(vec![Value::Integer(0)]), - Value::List([0, 0, 0, 255].into_iter().map(Value::Integer).collect()), - Value::List([0, 0, 255, 256].into_iter().map(Value::Integer).collect()), - Value::List(vec![Value::Double(0.0); 4]), - Value::List(vec![Value::Integer(0); 34]), - ] { - let mut item = all_controls_item(); - let mut d = get_desc(&item, "Fltr").unwrap().clone(); - set(&mut d, "Crv ", value); - set(&mut item, "Fltr", Value::Descriptor(d)); - let f = filter_from_item(&item); - assert_eq!(f.command, UNSUPPORTED_FILTER); - assert_eq!(item_for_filter(&f).unwrap(), item); - } - } - - #[test] - #[ignore = "requires a user-supplied Camera Raw PSD"] - fn all_sliders_fixture() { - let path = std::env::var("PHOTOCRAFT_CAMERA_RAW_PSD").expect("set PHOTOCRAFT_CAMERA_RAW_PSD"); - let doc = crate::import("fixture.psd", &std::fs::read(path).unwrap()).unwrap().document; - let original = doc - .walk() - .into_iter() - .find_map(|(_, _, layer)| { - let photocraft_doc::LayerContent::Smart(sm) = &layer.content else { return None }; - sm.smart_filters.iter().find_map(|f| { - let item = item_for_filter(f).ok()?; - get_desc(&item, "Fltr").is_some_and(|d| d.class_id.is(CLASS)).then_some(item) - }) - }) - .expect("a Camera Raw descriptor"); - assert_eq!(item_for_filter(&filter_from_item(&original)).unwrap(), original); - let mut projected = original.clone(); - let mut d = get_desc(&original, "Fltr").unwrap().clone(); - // This is a codec projection, not an editable replacement for the source filter: - // active Optics settings have no rendering counterpart, and PCVS is unverified. - d.items.retain(|(key, _)| !["MDis", "VigA", "PCVS"].iter().any(|k| key.is(k))); - set(&mut projected, "Fltr", Value::Descriptor(d)); - let mut f = filter_from_item(&projected); - assert_eq!(f.command, COMMAND); - assert_eq!(f.params["temperature"], -26.0); - assert_eq!(f.params["sharpenAmount"], 43.0); - assert_eq!(f.params["gradeGlobal"], json!({"hue": 20.0, "sat": 61.0, "lum": 45.0})); - assert_eq!(f.params["pointCurveRed"], json!([[0.0, 0.0], [90.0, 174.0], [255.0, 255.0]])); - assert_eq!(item_for_filter(&f).unwrap(), projected); - f.params["exposure"] = json!(0.5); - let mut expected = get_desc(&projected, "Fltr").unwrap().clone(); - set(&mut expected, "Ex12", Value::Double(0.5)); - assert_eq!(get_desc(&item_for_filter(&f).unwrap(), "Fltr"), Some(&expected)); - } - - #[test] - fn light_curve_and_hsl_are_editable_without_rewriting_unchanged_settings() { - let source = source_item().with("futureOuterData", Value::RawData(vec![1, 2, 3, 4])); - let mut f = filter_from_item(&source); - assert_eq!(f.command, COMMAND); - assert!((f.params["exposure"].as_f64().unwrap() - 1.15).abs() < 1e-6); - assert_eq!(f.params["contrast"], -38.0); - assert_eq!(f.params["curveDarks"], -21.0); - assert_eq!(f.params["curveLights"], 38.0); - assert_eq!(f.params["curveSplits"], json!([25.0, 50.0, 75.0])); - assert_eq!(f.params["hslHue"], json!([-50.0, 0.0, 29.0, 1.0, 0.0, 0.0, 0.0, 0.0])); - assert_eq!(item_for_filter(&f).unwrap(), source); - f.params["exposure"] = json!(0.0); - f.params["hslHue"][2] = json!(-20.0); - f.visible = false; - f.opacity = 0.4; - f.blend = BlendMode::Multiply; - let edited = item_for_filter(&f).unwrap(); - let mut expected = get_desc(&source, "Fltr").unwrap().clone(); - set(&mut expected, "Ex12", Value::Double(0.0)); - set(&mut expected, "HA_Y", Value::Integer(-20)); - assert_eq!(get_desc(&edited, "Fltr"), Some(&expected)); - assert_eq!(edited.get("futureOuterData"), source.get("futureOuterData")); - let back = filter_from_item(&edited); - assert_eq!((back.visible, back.blend, back.opacity), (false, BlendMode::Multiply, 0.4)); - assert_eq!(back.params["exposure"], 0.0); - assert_eq!(back.params["hslHue"][2], -20.0); - } - - #[test] - fn new_filters_write_every_verified_control_and_accept_explicit_defaults() { - let mut params = default_params().unwrap(); - params["seed"] = json!(0); - for (param, key) in SCALARS { - let number = match *key { - "Ex12" => 0.75, - "ShpR" => 1.2, - _ => 12.0, - }; - *get_param_mut(&mut params, param).unwrap() = json!(number); - } - for (param, keys) in ARRAYS { - params[*param] = if *param == "curveSplits" { json!([20, 45, 80]) } else { json!((0..keys.len()).map(|i| i as f64 + 1.0).collect::>()) }; - } - let f = SmartFilter { command: COMMAND.into(), params: params.clone(), blend: BlendMode::Screen, opacity: 0.5, visible: false }; - let item = item_for_filter(&f).unwrap(); - let back = filter_from_item(&Descriptor::from_bytes(&item.to_bytes()).unwrap()); - assert_eq!((&back.command, back.visible, back.blend, back.opacity), (&f.command, false, BlendMode::Screen, 0.5)); - // Compare slider numbers after both sides have been normalized through CameraRaw. - let typed: CameraRaw = serde_json::from_value(params).unwrap(); - let expected = serde_json::to_value(typed).unwrap(); - for param in SCALARS.iter().map(|(p, _)| *p).chain(ARRAYS.iter().map(|(p, _)| *p)) { - assert_eq!(get_param(&back.params, param), get_param(&expected, param)); - } - } - - #[test] - fn unsupported_processing_settings_remain_opaque_and_lossless() { - for (key, value) in [ - ("LCs ", Value::Text(UnicodeString::new("unknown masks"))), - ("PrVN", Value::Integer(7)), - ("PrVe", Value::Integer(123)), - ("Ex12", Value::Double(f64::INFINITY)), - ("Cr12", Value::Text(UnicodeString::new("bad type"))), - ] { - let mut item = source_item(); - let mut d = get_desc(&item, "Fltr").unwrap().clone(); - set(&mut d, key, value); - set(&mut item, "Fltr", Value::Descriptor(d)); - let f = filter_from_item(&item); - assert_eq!(f.command, UNSUPPORTED_FILTER, "{key}"); - assert_eq!(item_for_filter(&f).unwrap(), item, "{key}"); - } - } - - #[test] - fn fractional_slider_levels_round_instead_of_dropping_the_filter() { - let mut f = filter_from_item(&source_item()); - f.params["contrast"] = json!(-12.4); - f.params["hslHue"][0] = json!(10.5); - f.params["gradeShadows"]["hue"] = json!(359.7); - f.params["pointCurve"] = json!([[0, 0], [100.2, 120.6], [200.6, 180.4], [255, 255]]); - let item = item_for_filter(&f).unwrap(); - let d = get_desc(&item, "Fltr").unwrap(); - assert_eq!(d.get("Cr12"), Some(&Value::Integer(-12))); - assert_eq!(d.get("HA_R"), Some(&Value::Integer(11))); - assert_eq!(d.get("STSH"), Some(&Value::Integer(0))); - assert_eq!(d.get("Crv "), Some(&Value::List([0, 0, 100, 121, 201, 180, 255, 255].into_iter().map(Value::Integer).collect()))); - let back = filter_from_item(&item); - assert_eq!(back.command, COMMAND); - assert_eq!(back.params["contrast"], -12.0); - } - - #[test] - fn unsupported_or_malformed_exports_report_errors() { - for params in [ - J::Null, - json!({"exposure": "bright"}), - json!({"exposure": 1e40}), - json!({"exposure": 6}), - json!({"contrast": 101}), - json!({"hslHue": [1, 2]}), - json!({"curveSplits": [80, 50, 20]}), - json!({"curveSplits": [25, 25, 75]}), - json!({"pointCurve": [[0, 0], [0, 255]]}), - json!({"sharpenRadius": 4}), - json!({"gradeShadows": {"hue": 361}}), - json!({"gradeShadows": {"unknown": 1}}), - json!({"seed": 1}), - json!({"vignetteHighlights": 10}), - json!({"futureSetting": 1}), - json!({TEMPLATE_KEY: "zz"}), - json!({TEMPLATE_KEY: "00"}), - json!({TEMPLATE_KEY: 12}), - json!({TEMPLATE_KEY: "0".repeat(MAX_TEMPLATE_BYTES * 2 + 1)}), - ] { - assert!(export_item(¶ms).is_err()); - } - let wrong = Descriptor::new("filterFX").with("filterID", Value::Integer(1)); - assert!(export_item(&json!({TEMPLATE_KEY: to_hex(&wrong.to_bytes())})).is_err()); - } -} +#[path = "camera_raw_map/tests.rs"] +mod tests; diff --git a/crates/io/src/camera_raw_map/tests.rs b/crates/io/src/camera_raw_map/tests.rs new file mode 100644 index 0000000000..ad40acb25d --- /dev/null +++ b/crates/io/src/camera_raw_map/tests.rs @@ -0,0 +1,324 @@ +use super::*; +use crate::smart_map::{UNSUPPORTED_FILTER, filter_from_item, item_for_filter}; +use photocraft_color::BlendMode; + +// Parameter values observed in the supplied 18.4 PSD. No source pixels or private +// document metadata are included in this synthetic regression fixture. +fn source_item() -> Descriptor { + let mut d = Descriptor::new(CLASS) + .with("CrVe", Value::Text(UnicodeString::new_nul("18.4"))) + .with("PrVN", Value::Integer(6)) + .with("PrVe", Value::Integer(251920384)) + .with("Ex12", Value::Double(1.15)); + for (key, value) in [ + ("Cr12", -38), + ("Hi12", 35), + ("Sh12", -50), + ("Wh12", 49), + ("Bk12", -34), + ("PC_S", 0), + ("PC_D", -21), + ("PC_L", 38), + ("PC_H", 0), + ("PC_1", 25), + ("PC_2", 50), + ("PC_3", 75), + ] { + d = d.with(key, Value::Integer(value)); + } + for (_, keys) in ARRAYS.iter().skip(1) { + for key in *keys { + let value = match *key { + "HA_R" => -50, + "HA_Y" => 29, + "HA_G" => 1, + _ => 0, + }; + d = d.with(key, Value::Integer(value)); + } + } + let f = SmartFilter { command: COMMAND.into(), params: J::Null, blend: BlendMode::Normal, opacity: 1.0, visible: true }; + Descriptor::new("filterFX") + .with("Nm ", Value::Text(UnicodeString::new_nul("Camera Raw Filter"))) + .with("blendOptions", blend_options(&f)) + .with("enab", Value::Boolean(true)) + .with("hasoptions", Value::Boolean(true)) + .with("FrgC", rgbc(0.0)) + .with("BckC", rgbc(255.0)) + .with("Fltr", Value::Descriptor(d)) + .with("filterID", Value::Integer(FILTER_ID)) +} + +fn all_controls_item() -> Descriptor { + let mut item = source_item(); + let mut d = get_desc(&item, "Fltr").unwrap().clone(); + set(&mut d, "WBal", Value::Enumerated { type_id: photocraft_psd::descriptor::Id::new("WBal"), value: photocraft_psd::descriptor::Id::new("Cst ") }); + set(&mut d, "ShpR", Value::Double(1.2)); + for (key, value) in [ + ("Temp", -26), + ("Tint", -25), + ("CrTx", -31), + ("Cl12", 30), + ("Dhze", -34), + ("Vibr", 33), + ("Strt", 33), + ("Shrp", 43), + ("ShpD", 36), + ("ShpM", 30), + ("LNR ", 47), + ("LNRD", 50), + ("CNR ", 25), + ("CNRD", 50), + ("STSH", 117), + ("STSS", 52), + ("STHH", 316), + ("STHS", 70), + ("STB ", 35), + ("CgMH", 51), + ("CgMS", 51), + ("CgSL", -24), + ("CgML", 41), + ("CgHL", 28), + ("CgBl", 36), + ("CgGH", 20), + ("CgGS", 61), + ("CgGL", 45), + ("GRNA", 45), + ("GRNS", 25), + ("GRNF", 50), + ("PCVA", 31), + ("PCVM", 50), + ("PCVF", 50), + ("PCVR", 0), + ] { + set(&mut d, key, Value::Integer(value)); + } + for (key, neutral) in NEUTRAL_ONLY { + set(&mut d, key, Value::Integer(*neutral)); + } + for (key, x, y) in [("Crv ", 146, 102), ("CrvR", 90, 174), ("CrvG", 162, 122), ("CrvB", 129, 202)] { + set(&mut d, key, Value::List([0, 0, x, y, 255, 255].into_iter().map(Value::Integer).collect())); + } + set(&mut item, "Fltr", Value::Descriptor(d)); + item +} + +#[test] +fn all_observed_develop_controls_roundtrip_and_patch_only_the_edited_field() { + let source = all_controls_item(); + let f = filter_from_item(&source); + assert_eq!(f.command, COMMAND); + assert_eq!(f.params["temperature"], -26.0); + assert_eq!(f.params["texture"], -31.0); + assert!((f.params["sharpenRadius"].as_f64().unwrap() - 1.2).abs() < 1e-6); + assert_eq!(f.params["gradeHighlights"], json!({"hue": 316.0, "sat": 70.0, "lum": 28.0})); + assert_eq!(f.params["pointCurveBlue"], json!([[0.0, 0.0], [129.0, 202.0], [255.0, 255.0]])); + assert_eq!(item_for_filter(&f).unwrap(), source); + let defaults = default_params().unwrap(); + for (param, key) in SCALARS { + let mut edited = f.clone(); + let mut number = get_param(&defaults, param).unwrap().as_f64().unwrap(); + if get_param(&f.params, param).unwrap().as_f64() == Some(number) { + number += 1.0; + } + *get_param_mut(&mut edited.params, param).unwrap() = json!(number); + let mut expected = get_desc(&source, "Fltr").unwrap().clone(); + set(&mut expected, key, if matches!(*key, "Ex12" | "ShpR") { Value::Double(number) } else { Value::Integer(number as i32) }); + assert_eq!(get_desc(&item_for_filter(&edited).unwrap(), "Fltr"), Some(&expected), "{param}"); + } + for (param, key) in CURVES { + let mut edited = f.clone(); + edited.params[*param] = json!([]); + let item = item_for_filter(&edited).unwrap(); + let mut expected = get_desc(&source, "Fltr").unwrap().clone(); + set(&mut expected, key, Value::List([0, 0, 255, 255].into_iter().map(Value::Integer).collect())); + assert_eq!(get_desc(&item, "Fltr"), Some(&expected), "{param}"); + assert_eq!(filter_from_item(&item).params[*param], json!([]), "{param}"); + } +} + +#[test] +fn active_unimplemented_controls_and_malformed_curves_stay_opaque() { + for (key, neutral) in NEUTRAL_ONLY { + let mut item = all_controls_item(); + let mut d = get_desc(&item, "Fltr").unwrap().clone(); + set(&mut d, key, Value::Integer(neutral + 1)); + set(&mut item, "Fltr", Value::Descriptor(d)); + let f = filter_from_item(&item); + assert_eq!(f.command, UNSUPPORTED_FILTER, "{key}"); + assert_eq!(item_for_filter(&f).unwrap(), item, "{key}"); + } + for value in [ + Value::List(vec![Value::Integer(0)]), + Value::List([0, 0, 0, 255].into_iter().map(Value::Integer).collect()), + Value::List([0, 0, 255, 256].into_iter().map(Value::Integer).collect()), + Value::List(vec![Value::Double(0.0); 4]), + Value::List(vec![Value::Integer(0); 34]), + ] { + let mut item = all_controls_item(); + let mut d = get_desc(&item, "Fltr").unwrap().clone(); + set(&mut d, "Crv ", value); + set(&mut item, "Fltr", Value::Descriptor(d)); + let f = filter_from_item(&item); + assert_eq!(f.command, UNSUPPORTED_FILTER); + assert_eq!(item_for_filter(&f).unwrap(), item); + } +} + +#[test] +#[ignore = "requires a user-supplied Camera Raw PSD"] +fn all_sliders_fixture() { + let path = std::env::var("PHOTOCRAFT_CAMERA_RAW_PSD").expect("set PHOTOCRAFT_CAMERA_RAW_PSD"); + let doc = crate::import("fixture.psd", &std::fs::read(path).unwrap()).unwrap().document; + let original = doc + .walk() + .into_iter() + .find_map(|(_, _, layer)| { + let photocraft_doc::LayerContent::Smart(sm) = &layer.content else { return None }; + sm.smart_filters.iter().find_map(|f| { + let item = item_for_filter(f).ok()?; + get_desc(&item, "Fltr").is_some_and(|d| d.class_id.is(CLASS)).then_some(item) + }) + }) + .expect("a Camera Raw descriptor"); + assert_eq!(item_for_filter(&filter_from_item(&original)).unwrap(), original); + let mut projected = original.clone(); + let mut d = get_desc(&original, "Fltr").unwrap().clone(); + // This is a codec projection, not an editable replacement for the source filter: + // active Optics settings have no rendering counterpart, and PCVS is unverified. + d.items.retain(|(key, _)| !["MDis", "VigA", "PCVS"].iter().any(|k| key.is(k))); + set(&mut projected, "Fltr", Value::Descriptor(d)); + let mut f = filter_from_item(&projected); + assert_eq!(f.command, COMMAND); + assert_eq!(f.params["temperature"], -26.0); + assert_eq!(f.params["sharpenAmount"], 43.0); + assert_eq!(f.params["gradeGlobal"], json!({"hue": 20.0, "sat": 61.0, "lum": 45.0})); + assert_eq!(f.params["pointCurveRed"], json!([[0.0, 0.0], [90.0, 174.0], [255.0, 255.0]])); + assert_eq!(item_for_filter(&f).unwrap(), projected); + f.params["exposure"] = json!(0.5); + let mut expected = get_desc(&projected, "Fltr").unwrap().clone(); + set(&mut expected, "Ex12", Value::Double(0.5)); + assert_eq!(get_desc(&item_for_filter(&f).unwrap(), "Fltr"), Some(&expected)); +} + +#[test] +fn light_curve_and_hsl_are_editable_without_rewriting_unchanged_settings() { + let source = source_item().with("futureOuterData", Value::RawData(vec![1, 2, 3, 4])); + let mut f = filter_from_item(&source); + assert_eq!(f.command, COMMAND); + assert!((f.params["exposure"].as_f64().unwrap() - 1.15).abs() < 1e-6); + assert_eq!(f.params["contrast"], -38.0); + assert_eq!(f.params["curveDarks"], -21.0); + assert_eq!(f.params["curveLights"], 38.0); + assert_eq!(f.params["curveSplits"], json!([25.0, 50.0, 75.0])); + assert_eq!(f.params["hslHue"], json!([-50.0, 0.0, 29.0, 1.0, 0.0, 0.0, 0.0, 0.0])); + assert_eq!(item_for_filter(&f).unwrap(), source); + f.params["exposure"] = json!(0.0); + f.params["hslHue"][2] = json!(-20.0); + f.visible = false; + f.opacity = 0.4; + f.blend = BlendMode::Multiply; + let edited = item_for_filter(&f).unwrap(); + let mut expected = get_desc(&source, "Fltr").unwrap().clone(); + set(&mut expected, "Ex12", Value::Double(0.0)); + set(&mut expected, "HA_Y", Value::Integer(-20)); + assert_eq!(get_desc(&edited, "Fltr"), Some(&expected)); + assert_eq!(edited.get("futureOuterData"), source.get("futureOuterData")); + let back = filter_from_item(&edited); + assert_eq!((back.visible, back.blend, back.opacity), (false, BlendMode::Multiply, 0.4)); + assert_eq!(back.params["exposure"], 0.0); + assert_eq!(back.params["hslHue"][2], -20.0); +} + +#[test] +fn new_filters_write_every_verified_control_and_accept_explicit_defaults() { + let mut params = default_params().unwrap(); + params["seed"] = json!(0); + for (param, key) in SCALARS { + let number = match *key { + "Ex12" => 0.75, + "ShpR" => 1.2, + _ => 12.0, + }; + *get_param_mut(&mut params, param).unwrap() = json!(number); + } + for (param, keys) in ARRAYS { + params[*param] = if *param == "curveSplits" { json!([20, 45, 80]) } else { json!((0..keys.len()).map(|i| i as f64 + 1.0).collect::>()) }; + } + let f = SmartFilter { command: COMMAND.into(), params: params.clone(), blend: BlendMode::Screen, opacity: 0.5, visible: false }; + let item = item_for_filter(&f).unwrap(); + let back = filter_from_item(&Descriptor::from_bytes(&item.to_bytes()).unwrap()); + assert_eq!((&back.command, back.visible, back.blend, back.opacity), (&f.command, false, BlendMode::Screen, 0.5)); + // Compare slider numbers after both sides have been normalized through CameraRaw. + let typed: CameraRaw = serde_json::from_value(params).unwrap(); + let expected = serde_json::to_value(typed).unwrap(); + for param in SCALARS.iter().map(|(p, _)| *p).chain(ARRAYS.iter().map(|(p, _)| *p)) { + assert_eq!(get_param(&back.params, param), get_param(&expected, param)); + } +} + +#[test] +fn unsupported_processing_settings_remain_opaque_and_lossless() { + for (key, value) in [ + ("LCs ", Value::Text(UnicodeString::new("unknown masks"))), + ("PrVN", Value::Integer(7)), + ("PrVe", Value::Integer(123)), + ("Ex12", Value::Double(f64::INFINITY)), + ("Cr12", Value::Text(UnicodeString::new("bad type"))), + ] { + let mut item = source_item(); + let mut d = get_desc(&item, "Fltr").unwrap().clone(); + set(&mut d, key, value); + set(&mut item, "Fltr", Value::Descriptor(d)); + let f = filter_from_item(&item); + assert_eq!(f.command, UNSUPPORTED_FILTER, "{key}"); + assert_eq!(item_for_filter(&f).unwrap(), item, "{key}"); + } +} + +#[test] +fn fractional_slider_levels_round_instead_of_dropping_the_filter() { + let mut f = filter_from_item(&source_item()); + f.params["contrast"] = json!(-12.4); + f.params["hslHue"][0] = json!(10.5); + f.params["gradeShadows"]["hue"] = json!(359.7); + f.params["pointCurve"] = json!([[0, 0], [100.2, 120.6], [200.6, 180.4], [255, 255]]); + let item = item_for_filter(&f).unwrap(); + let d = get_desc(&item, "Fltr").unwrap(); + assert_eq!(d.get("Cr12"), Some(&Value::Integer(-12))); + assert_eq!(d.get("HA_R"), Some(&Value::Integer(11))); + assert_eq!(d.get("STSH"), Some(&Value::Integer(0))); + assert_eq!(d.get("Crv "), Some(&Value::List([0, 0, 100, 121, 201, 180, 255, 255].into_iter().map(Value::Integer).collect()))); + let back = filter_from_item(&item); + assert_eq!(back.command, COMMAND); + assert_eq!(back.params["contrast"], -12.0); +} + +#[test] +fn unsupported_or_malformed_exports_report_errors() { + for params in [ + J::Null, + json!({"exposure": "bright"}), + json!({"exposure": 1e40}), + json!({"exposure": 6}), + json!({"contrast": 101}), + json!({"hslHue": [1, 2]}), + json!({"curveSplits": [80, 50, 20]}), + json!({"curveSplits": [25, 25, 75]}), + json!({"pointCurve": [[0, 0], [0, 255]]}), + json!({"sharpenRadius": 4}), + json!({"gradeShadows": {"hue": 361}}), + json!({"gradeShadows": {"unknown": 1}}), + json!({"seed": 1}), + json!({"vignetteHighlights": 10}), + json!({"futureSetting": 1}), + json!({TEMPLATE_KEY: "zz"}), + json!({TEMPLATE_KEY: "00"}), + json!({TEMPLATE_KEY: 12}), + json!({TEMPLATE_KEY: "0".repeat(MAX_TEMPLATE_BYTES * 2 + 1)}), + ] { + assert!(export_item(¶ms).is_err()); + } + let wrong = Descriptor::new("filterFX").with("filterID", Value::Integer(1)); + assert!(export_item(&json!({TEMPLATE_KEY: to_hex(&wrong.to_bytes())})).is_err()); +} diff --git a/crates/io/src/effects_map.rs b/crates/io/src/effects_map.rs index 416aa56b56..36aff72a3a 100644 --- a/crates/io/src/effects_map.rs +++ b/crates/io/src/effects_map.rs @@ -641,346 +641,4 @@ pub fn parse_lrfx(data: &[u8]) -> Option<(bool, Vec)> { #[cfg(test)] #[allow(clippy::unreachable)] // clippy.toml exempts unwrap/expect/panic in tests, not unreachable! -mod tests { - use super::*; - - fn sample_effects() -> Vec { - let g = Gradient { - stops: vec![(0.0, Color::rgb(1.0, 0.0, 0.0)), (1.0, Color::rgb(0.0, 0.0, 1.0))], - opacity_stops: vec![(0.0, 1.0), (1.0, 0.5)], - ..Gradient::default() - }; - vec![ - Effect::default_drop_shadow(), - Effect::DropShadow(Shadow { - distance: 9.0, - spread: 0.25, - contour: Contour::Custom { - name: "Cone".into(), - points: vec![CurvePoint { input: 0.0, output: 0.0 }, CurvePoint { input: 0.5, output: 1.0 }, CurvePoint { input: 1.0, output: 0.0 }], - corners: vec![false, true, false], - }, - ..match Effect::default_drop_shadow() { - Effect::DropShadow(s) => s, - _ => unreachable!(), - } - }), - Effect::InnerShadow(Shadow { - knocks_out: false, - ..match Effect::default_drop_shadow() { - Effect::DropShadow(s) => s, - _ => unreachable!(), - } - }), - Effect::OuterGlow(Glow { - common: FxCommon::new(BlendMode::Screen, 0.5), - paint: FxPaint::Color(Color::rgb(1.0, 1.0, 0.0)), - technique: GlowTechnique::Precise, - spread: 0.1, - size: 8.0, - contour: Contour::Linear, - anti_alias: true, - range: 0.5, - jitter: 0.0, - noise: 0.0, - source: GlowSource::Edge, - }), - Effect::InnerGlow(Glow { - common: FxCommon::new(BlendMode::Screen, 0.75), - paint: FxPaint::Gradient(g.clone()), - technique: GlowTechnique::Softer, - spread: 0.0, - size: 5.0, - contour: Contour::Linear, - anti_alias: false, - range: 0.5, - jitter: 0.0, - noise: 0.0, - source: GlowSource::Center, - }), - Effect::Stroke(StrokeFx { - common: FxCommon::new(BlendMode::Normal, 1.0), - size: 3.0, - position: StrokePosition::Inside, - paint: FxPaint::Color(Color::rgb(0.0, 1.0, 0.0)), - overprint: false, - }), - Effect::Stroke(StrokeFx { - common: FxCommon::new(BlendMode::Multiply, 0.5), - size: 6.0, - position: StrokePosition::Center, - paint: FxPaint::Gradient(g.clone()), - overprint: true, - }), - Effect::ColorOverlay { common: FxCommon::new(BlendMode::Overlay, 0.5), color: Color::rgb(0.0, 0.0, 1.0) }, - Effect::GradientOverlay { common: FxCommon::new(BlendMode::Normal, 1.0), gradient: g, dither: true, interpolation: None }, - Effect::PatternOverlay { - common: FxCommon::new(BlendMode::Normal, 1.0), - name: "Bubbles".into(), - id: "abc".into(), - scale: 1.0, - angle: 15.0, - link: false, - phase: (4.0, 2.0), - }, - Effect::Satin(Satin { - common: FxCommon::new(BlendMode::Multiply, 0.5), - color: Color::BLACK, - angle: 19.0, - distance: 11.0, - size: 14.0, - contour: Contour::Linear, - anti_alias: true, - invert: true, - }), - Effect::BevelEmboss(Bevel { - enabled: true, - style: BevelStyle::Emboss, - technique: BevelTechnique::ChiselSoft, - depth: 1.5, - up: false, - size: 7.0, - soften: 2.0, - angle: 45.0, - altitude: 40.0, - use_global_light: false, - gloss_contour: Contour::Linear, - gloss_anti_alias: true, - highlight: FxCommon::new(BlendMode::Screen, 0.75), - highlight_color: Color::WHITE, - shadow: FxCommon::new(BlendMode::Multiply, 0.6), - shadow_color: Color::BLACK, - contour: Some(BevelContour { contour: Contour::Linear, range: 0.7, anti_alias: true }), - texture: Some(BevelTexture { name: "Bubbles".into(), id: "abc".into(), scale: 0.5, depth: -2.0, invert: true, link: false, phase: (3.0, 1.0) }), - }), - ] - } - - fn approx(a: &[Effect], b: &[Effect]) { - // Colours go through 0..255 doubles; compare via re-serialization. - assert_eq!(a.len(), b.len()); - assert_eq!(write_lfx2(true, a), write_lfx2(true, b)); - } - - /// `approx` compares re-serialized bytes, so a field the writer drops looks equal on both - /// sides: read the Gloss Contour's Anti-aliased back directly. - #[test] - fn bevel_gloss_anti_alias_is_written() { - let fx: Vec = sample_effects().into_iter().filter(|e| matches!(e, Effect::BevelEmboss(_))).collect(); - assert!(matches!(fx.as_slice(), [Effect::BevelEmboss(b)] if b.gloss_anti_alias)); - let (_, back) = parse_lfx2(&write_lfx2(false, &fx)).unwrap(); - assert!(matches!(back.as_slice(), [Effect::BevelEmboss(b)] if b.gloss_anti_alias), "{back:?}"); - } - - #[test] - fn lfx2_roundtrip_all_kinds() { - let fx = sample_effects(); - let data = write_lfx2(false, &fx); - let (master, back) = parse_lfx2(&data).unwrap(); - assert!(!master); - approx(&fx, &back); - // Kind order is canonical: shadows first ... strokes last. - assert!(matches!(back[0], Effect::DropShadow(_))); - assert!(matches!(back.last().unwrap(), Effect::Stroke(_))); - } - - #[test] - fn stroke_overprint_is_read_and_written() { - for overprint in [false, true] { - let fx = [Effect::Stroke(StrokeFx { - common: FxCommon::new(BlendMode::Normal, 1.0), - size: 3.0, - position: StrokePosition::Outside, - paint: FxPaint::Color(Color::BLACK), - overprint, - })]; - let (_, back) = parse_lfx2(&write_lfx2(false, &fx)).unwrap(); - let [Effect::Stroke(s)] = back.as_slice() else { panic!("{back:?}") }; - assert_eq!(s.overprint, overprint); - } - // A stroke without the key (other writers) has Overprint off. - let d = Descriptor::new("null").with("FrFX", Value::Descriptor(Descriptor::new("FrFX").with("enab", Value::Boolean(true)))); - let mut data = 0u32.to_be_bytes().to_vec(); - data.extend(VersionedDescriptor::new(d).to_bytes()); - let (_, back) = parse_lfx2(&data).unwrap(); - let [Effect::Stroke(s)] = back.as_slice() else { panic!("{back:?}") }; - assert!(!s.overprint); - } - - #[test] - fn lfx2_ignores_absent_effects_but_keeps_disabled_configured_effects() { - let d = Descriptor::new("null") - .with("DrSh", Value::Descriptor(Descriptor::new("DrSh").with("present", Value::Boolean(false)).with("enab", Value::Boolean(false)))) - .with("FrFX", Value::Descriptor(Descriptor::new("FrFX").with("present", Value::Boolean(true)).with("enab", Value::Boolean(false)))) - .with("SoFi", Value::Descriptor(Descriptor::new("SoFi").with("enab", Value::Boolean(false)))); - let mut data = 0u32.to_be_bytes().to_vec(); - data.extend(VersionedDescriptor::new(d).to_bytes()); - - let (_, effects) = parse_lfx2(&data).unwrap(); - - assert_eq!(effects.len(), 2); - assert!(effects.iter().all(|effect| !effect.enabled())); - assert!(effects.iter().any(|effect| effect.label() == "Stroke")); - assert!(effects.iter().any(|effect| effect.label() == "Color Overlay")); - } - - #[test] - fn multi_instances_use_multi_keys() { - let fx = sample_effects(); - let data = write_lfx2(true, &fx); - let (vd, _) = VersionedDescriptor::parse_prefix(&data[4..]).unwrap(); - assert!(vd.descriptor.get("dropShadowMulti").is_some()); - assert!(vd.descriptor.get("frameFXMulti").is_some()); - assert!(vd.descriptor.get("SoFi").is_some()); - } - - #[test] - fn blend_names_are_unique() { - let mut s = std::collections::HashSet::new(); - for (_, n) in BLEND_NAMES { - assert!(s.insert(n)); - } - } - - #[test] - fn long_string_blend_ids_parse() { - // Some writers store effect modes as long string IDs (`BlnM` `multiply`, `colorDodge`) - // instead of the four-character codes (psd-tools effects/blend-modes.psd). - let long = |v: &str| Value::Enumerated { type_id: Id::new("BlnM"), value: Id::new(v) }; - let d = Descriptor::new("null") - .with("masterFXSwitch", Value::Boolean(true)) - .with("DrSh", Value::Descriptor(Descriptor::new("DrSh").with("enab", Value::Boolean(true)).with("Md ", long("linearBurn")))) - .with("ebbl", Value::Descriptor(Descriptor::new("ebbl").with("hglM", long("colorDodge")).with("sdwM", long("colorBurn")))) - .with("SoFi", Value::Descriptor(Descriptor::new("SoFi").with("Md ", long("hue")))); - let mut data = 0u32.to_be_bytes().to_vec(); - data.extend(VersionedDescriptor { version: 16, descriptor: d }.to_bytes()); - let (_, fx) = parse_lfx2(&data).unwrap(); - let modes: Vec = fx - .iter() - .flat_map(|e| match e { - Effect::DropShadow(s) => vec![s.common.blend], - Effect::BevelEmboss(b) => vec![b.highlight.blend, b.shadow.blend], - Effect::ColorOverlay { common, .. } => vec![common.blend], - _ => vec![], - }) - .collect(); - assert_eq!(modes, vec![BlendMode::LinearBurn, BlendMode::ColorDodge, BlendMode::ColorBurn, BlendMode::Hue]); - for (m, n) in BLEND_LONG_NAMES { - assert_eq!(blend_from_id(n.as_bytes()), Some(m)); - } - } - - /// A Gradient Overlay `lfx2` laid out as Photoshop writes it: one black colour, opacity - /// 100 → 0 % with the opacity midpoint `mid` (%), Smoothness `intr` (0..4096) and the method - /// enum `gs99` (Photoshop's key in layer effects; codes `Gcls`, `Lnr `, `Perc`). - fn overlay_lfx2(mid: i32, intr: f64, method: &str) -> Vec { - let black = || Descriptor::new("RGBC").with("Rd ", Value::Double(0.0)).with("Grn ", Value::Double(0.0)).with("Bl ", Value::Double(0.0)); - let clr = |loc: i32| { - Value::Descriptor( - Descriptor::new("Clrt") - .with("Clr ", Value::Descriptor(black())) - .with("Type", Value::Enumerated { type_id: Id::new("Clry"), value: Id::new("UsrS") }) - .with("Lctn", Value::Integer(loc)) - .with("Mdpn", Value::Integer(50)), - ) - }; - let trn = |loc: i32, op: f32, mid: i32| { - Value::Descriptor(Descriptor::new("TrnS").with("Opct", unit(b"#Prc", op)).with("Lctn", Value::Integer(loc)).with("Mdpn", Value::Integer(mid))) - }; - let grad = Descriptor::new("Grdn") - .with("GrdF", Value::Enumerated { type_id: Id::new("GrdF"), value: Id::new("CstS") }) - .with("Intr", Value::Double(intr)) - .with("Clrs", Value::List(vec![clr(0), clr(4096)])) - .with("Trns", Value::List(vec![trn(0, 100.0, 50), trn(4096, 0.0, mid)])); - let fx = Descriptor::new("GrFl") - .with("enab", Value::Boolean(true)) - .with("Grad", Value::Descriptor(grad)) - .with("Angl", unit(b"#Ang", 0.0)) - .with("gs99", Value::Enumerated { type_id: Id::new("gradientInterpolationMethodType"), value: Id::new(method) }); - let d = Descriptor::new("null").with("masterFXSwitch", Value::Boolean(true)).with("GrFl", Value::Descriptor(fx)); - let mut data = 0u32.to_be_bytes().to_vec(); - data.extend(VersionedDescriptor { version: 16, descriptor: d }.to_bytes()); - data - } - - fn overlay_opacity(data: &[u8]) -> Vec<(f32, f32)> { - let (_, fx) = parse_lfx2(data).unwrap(); - let Some(Effect::GradientOverlay { gradient, .. }) = fx.first() else { panic!("overlay: {fx:?}") }; - gradient.opacity_stops.clone() - } - - fn opacity_at(o: &[(f32, f32)], t: f32) -> f32 { - let i = o.windows(2).position(|w| t >= w[0].0 && t <= w[1].0).unwrap(); - o[i].1 + (o[i + 1].1 - o[i].1) * (t - o[i].0) / (o[i + 1].0 - o[i].0) - } - - /// #1954: the overlay's transparency follows Smoothness, the opacity midpoints and the method - /// like a gradient fill layer's (Photoshop renders both identically; the values are its - /// composites at t = 0.25 and 0.5). - #[test] - fn gradient_overlay_opacity_follows_smoothness_midpoint_and_method() { - let at = |mid, intr, method: &str, t| opacity_at(&overlay_opacity(&overlay_lfx2(mid, intr, method)), t); - // Plain Classic stays the linear fade it is stored as. - assert_eq!(overlay_opacity(&overlay_lfx2(50, 0.0, "Gcls")), vec![(0.0, 1.0), (1.0, 0.0)]); - // Midpoint 25 %: half transparent a quarter of the way. - assert!((at(25, 0.0, "Gcls", 0.25) - 0.5).abs() < 0.01); - // Smoothness 100 % eases the ends (Photoshop: 0.796 at a quarter). - assert!((at(50, 4096.0, "Gcls", 0.25) - 0.796).abs() < 0.015); - // The method bends the transparency ramp too, not only the colours (Photoshop at the - // middle: 0.631 Linear, 0.255 Perceptual). - assert!((at(50, 0.0, "Lnr ", 0.5) - 0.631).abs() < 0.015); - assert!((at(50, 0.0, "Perc", 0.5) - 0.255).abs() < 0.015); - assert!((at(25, 4096.0, "Perc", 0.25) - 0.255).abs() < 0.015); - } - - /// A regenerated `lfx2` carries the baked ramp as plain (Classic, Smoothness 0) stops, so it - /// reads back unchanged. - #[test] - fn baked_overlay_opacity_round_trips() { - let data = overlay_lfx2(25, 4096.0, "Perc"); - let (master, fx) = parse_lfx2(&data).unwrap(); - let a = overlay_opacity(&data); - let b = overlay_opacity(&write_lfx2(master, &fx)); - assert!(a.len() > 2); - assert_eq!(a.len(), b.len()); - for (x, y) in a.iter().zip(&b) { - assert!((x.0 - y.0).abs() < 1e-3 && (x.1 - y.1).abs() < 1e-4, "{x:?} vs {y:?}"); - } - } - - #[test] - fn garbage_is_none() { - assert!(parse_lfx2(&[0, 0]).is_none()); - assert!(parse_lrfx(&[0, 0, 0, 1, b'X']).is_none()); - } - - #[test] - fn lrfx_drop_shadow() { - // version 0, count 1, 'dsdw' v2 record. - let mut d = vec![0, 0, 0, 1]; - d.extend_from_slice(b"8BIMdsdw"); - let mut rec = Vec::new(); - rec.extend_from_slice(&2u32.to_be_bytes()); // version - rec.extend_from_slice(&(7u32 << 16).to_be_bytes()); // blur (16.16) - rec.extend_from_slice(&0u32.to_be_bytes()); // intensity - rec.extend_from_slice(&(90u32 << 16).to_be_bytes()); // angle - rec.extend_from_slice(&(4u32 << 16).to_be_bytes()); // distance - rec.extend_from_slice(&[0, 0, 0xff, 0xff, 0, 0, 0, 0, 0, 0]); // color: red - rec.extend_from_slice(b"8BIMmul "); - rec.extend_from_slice(&[1, 1, 128]); - rec.extend_from_slice(&[0; 10]); - d.extend_from_slice(&(rec.len() as u32).to_be_bytes()); - d.extend(rec); - let (_, fx) = parse_lrfx(&d).unwrap(); - match &fx[0] { - Effect::DropShadow(s) => { - assert_eq!(s.size, 7.0); - assert_eq!(s.distance, 4.0); - assert_eq!(s.common.blend, BlendMode::Multiply); - assert!((s.common.opacity - 128.0 / 255.0).abs() < 1e-6); - assert_eq!(s.color.c[0], 1.0); - } - other => panic!("{other:?}"), - } - } -} +mod tests; diff --git a/crates/io/src/effects_map/tests.rs b/crates/io/src/effects_map/tests.rs new file mode 100644 index 0000000000..3944739fb8 --- /dev/null +++ b/crates/io/src/effects_map/tests.rs @@ -0,0 +1,341 @@ +use super::*; + +fn sample_effects() -> Vec { + let g = Gradient { + stops: vec![(0.0, Color::rgb(1.0, 0.0, 0.0)), (1.0, Color::rgb(0.0, 0.0, 1.0))], + opacity_stops: vec![(0.0, 1.0), (1.0, 0.5)], + ..Gradient::default() + }; + vec![ + Effect::default_drop_shadow(), + Effect::DropShadow(Shadow { + distance: 9.0, + spread: 0.25, + contour: Contour::Custom { + name: "Cone".into(), + points: vec![CurvePoint { input: 0.0, output: 0.0 }, CurvePoint { input: 0.5, output: 1.0 }, CurvePoint { input: 1.0, output: 0.0 }], + corners: vec![false, true, false], + }, + ..match Effect::default_drop_shadow() { + Effect::DropShadow(s) => s, + _ => unreachable!(), + } + }), + Effect::InnerShadow(Shadow { + knocks_out: false, + ..match Effect::default_drop_shadow() { + Effect::DropShadow(s) => s, + _ => unreachable!(), + } + }), + Effect::OuterGlow(Glow { + common: FxCommon::new(BlendMode::Screen, 0.5), + paint: FxPaint::Color(Color::rgb(1.0, 1.0, 0.0)), + technique: GlowTechnique::Precise, + spread: 0.1, + size: 8.0, + contour: Contour::Linear, + anti_alias: true, + range: 0.5, + jitter: 0.0, + noise: 0.0, + source: GlowSource::Edge, + }), + Effect::InnerGlow(Glow { + common: FxCommon::new(BlendMode::Screen, 0.75), + paint: FxPaint::Gradient(g.clone()), + technique: GlowTechnique::Softer, + spread: 0.0, + size: 5.0, + contour: Contour::Linear, + anti_alias: false, + range: 0.5, + jitter: 0.0, + noise: 0.0, + source: GlowSource::Center, + }), + Effect::Stroke(StrokeFx { + common: FxCommon::new(BlendMode::Normal, 1.0), + size: 3.0, + position: StrokePosition::Inside, + paint: FxPaint::Color(Color::rgb(0.0, 1.0, 0.0)), + overprint: false, + }), + Effect::Stroke(StrokeFx { + common: FxCommon::new(BlendMode::Multiply, 0.5), + size: 6.0, + position: StrokePosition::Center, + paint: FxPaint::Gradient(g.clone()), + overprint: true, + }), + Effect::ColorOverlay { common: FxCommon::new(BlendMode::Overlay, 0.5), color: Color::rgb(0.0, 0.0, 1.0) }, + Effect::GradientOverlay { common: FxCommon::new(BlendMode::Normal, 1.0), gradient: g, dither: true, interpolation: None }, + Effect::PatternOverlay { + common: FxCommon::new(BlendMode::Normal, 1.0), + name: "Bubbles".into(), + id: "abc".into(), + scale: 1.0, + angle: 15.0, + link: false, + phase: (4.0, 2.0), + }, + Effect::Satin(Satin { + common: FxCommon::new(BlendMode::Multiply, 0.5), + color: Color::BLACK, + angle: 19.0, + distance: 11.0, + size: 14.0, + contour: Contour::Linear, + anti_alias: true, + invert: true, + }), + Effect::BevelEmboss(Bevel { + enabled: true, + style: BevelStyle::Emboss, + technique: BevelTechnique::ChiselSoft, + depth: 1.5, + up: false, + size: 7.0, + soften: 2.0, + angle: 45.0, + altitude: 40.0, + use_global_light: false, + gloss_contour: Contour::Linear, + gloss_anti_alias: true, + highlight: FxCommon::new(BlendMode::Screen, 0.75), + highlight_color: Color::WHITE, + shadow: FxCommon::new(BlendMode::Multiply, 0.6), + shadow_color: Color::BLACK, + contour: Some(BevelContour { contour: Contour::Linear, range: 0.7, anti_alias: true }), + texture: Some(BevelTexture { name: "Bubbles".into(), id: "abc".into(), scale: 0.5, depth: -2.0, invert: true, link: false, phase: (3.0, 1.0) }), + }), + ] +} + +fn approx(a: &[Effect], b: &[Effect]) { + // Colours go through 0..255 doubles; compare via re-serialization. + assert_eq!(a.len(), b.len()); + assert_eq!(write_lfx2(true, a), write_lfx2(true, b)); +} + +/// `approx` compares re-serialized bytes, so a field the writer drops looks equal on both +/// sides: read the Gloss Contour's Anti-aliased back directly. +#[test] +fn bevel_gloss_anti_alias_is_written() { + let fx: Vec = sample_effects().into_iter().filter(|e| matches!(e, Effect::BevelEmboss(_))).collect(); + assert!(matches!(fx.as_slice(), [Effect::BevelEmboss(b)] if b.gloss_anti_alias)); + let (_, back) = parse_lfx2(&write_lfx2(false, &fx)).unwrap(); + assert!(matches!(back.as_slice(), [Effect::BevelEmboss(b)] if b.gloss_anti_alias), "{back:?}"); +} + +#[test] +fn lfx2_roundtrip_all_kinds() { + let fx = sample_effects(); + let data = write_lfx2(false, &fx); + let (master, back) = parse_lfx2(&data).unwrap(); + assert!(!master); + approx(&fx, &back); + // Kind order is canonical: shadows first ... strokes last. + assert!(matches!(back[0], Effect::DropShadow(_))); + assert!(matches!(back.last().unwrap(), Effect::Stroke(_))); +} + +#[test] +fn stroke_overprint_is_read_and_written() { + for overprint in [false, true] { + let fx = [Effect::Stroke(StrokeFx { + common: FxCommon::new(BlendMode::Normal, 1.0), + size: 3.0, + position: StrokePosition::Outside, + paint: FxPaint::Color(Color::BLACK), + overprint, + })]; + let (_, back) = parse_lfx2(&write_lfx2(false, &fx)).unwrap(); + let [Effect::Stroke(s)] = back.as_slice() else { panic!("{back:?}") }; + assert_eq!(s.overprint, overprint); + } + // A stroke without the key (other writers) has Overprint off. + let d = Descriptor::new("null").with("FrFX", Value::Descriptor(Descriptor::new("FrFX").with("enab", Value::Boolean(true)))); + let mut data = 0u32.to_be_bytes().to_vec(); + data.extend(VersionedDescriptor::new(d).to_bytes()); + let (_, back) = parse_lfx2(&data).unwrap(); + let [Effect::Stroke(s)] = back.as_slice() else { panic!("{back:?}") }; + assert!(!s.overprint); +} + +#[test] +fn lfx2_ignores_absent_effects_but_keeps_disabled_configured_effects() { + let d = Descriptor::new("null") + .with("DrSh", Value::Descriptor(Descriptor::new("DrSh").with("present", Value::Boolean(false)).with("enab", Value::Boolean(false)))) + .with("FrFX", Value::Descriptor(Descriptor::new("FrFX").with("present", Value::Boolean(true)).with("enab", Value::Boolean(false)))) + .with("SoFi", Value::Descriptor(Descriptor::new("SoFi").with("enab", Value::Boolean(false)))); + let mut data = 0u32.to_be_bytes().to_vec(); + data.extend(VersionedDescriptor::new(d).to_bytes()); + + let (_, effects) = parse_lfx2(&data).unwrap(); + + assert_eq!(effects.len(), 2); + assert!(effects.iter().all(|effect| !effect.enabled())); + assert!(effects.iter().any(|effect| effect.label() == "Stroke")); + assert!(effects.iter().any(|effect| effect.label() == "Color Overlay")); +} + +#[test] +fn multi_instances_use_multi_keys() { + let fx = sample_effects(); + let data = write_lfx2(true, &fx); + let (vd, _) = VersionedDescriptor::parse_prefix(&data[4..]).unwrap(); + assert!(vd.descriptor.get("dropShadowMulti").is_some()); + assert!(vd.descriptor.get("frameFXMulti").is_some()); + assert!(vd.descriptor.get("SoFi").is_some()); +} + +#[test] +fn blend_names_are_unique() { + let mut s = std::collections::HashSet::new(); + for (_, n) in BLEND_NAMES { + assert!(s.insert(n)); + } +} + +#[test] +fn long_string_blend_ids_parse() { + // Some writers store effect modes as long string IDs (`BlnM` `multiply`, `colorDodge`) + // instead of the four-character codes (psd-tools effects/blend-modes.psd). + let long = |v: &str| Value::Enumerated { type_id: Id::new("BlnM"), value: Id::new(v) }; + let d = Descriptor::new("null") + .with("masterFXSwitch", Value::Boolean(true)) + .with("DrSh", Value::Descriptor(Descriptor::new("DrSh").with("enab", Value::Boolean(true)).with("Md ", long("linearBurn")))) + .with("ebbl", Value::Descriptor(Descriptor::new("ebbl").with("hglM", long("colorDodge")).with("sdwM", long("colorBurn")))) + .with("SoFi", Value::Descriptor(Descriptor::new("SoFi").with("Md ", long("hue")))); + let mut data = 0u32.to_be_bytes().to_vec(); + data.extend(VersionedDescriptor { version: 16, descriptor: d }.to_bytes()); + let (_, fx) = parse_lfx2(&data).unwrap(); + let modes: Vec = fx + .iter() + .flat_map(|e| match e { + Effect::DropShadow(s) => vec![s.common.blend], + Effect::BevelEmboss(b) => vec![b.highlight.blend, b.shadow.blend], + Effect::ColorOverlay { common, .. } => vec![common.blend], + _ => vec![], + }) + .collect(); + assert_eq!(modes, vec![BlendMode::LinearBurn, BlendMode::ColorDodge, BlendMode::ColorBurn, BlendMode::Hue]); + for (m, n) in BLEND_LONG_NAMES { + assert_eq!(blend_from_id(n.as_bytes()), Some(m)); + } +} + +/// A Gradient Overlay `lfx2` laid out as Photoshop writes it: one black colour, opacity +/// 100 → 0 % with the opacity midpoint `mid` (%), Smoothness `intr` (0..4096) and the method +/// enum `gs99` (Photoshop's key in layer effects; codes `Gcls`, `Lnr `, `Perc`). +fn overlay_lfx2(mid: i32, intr: f64, method: &str) -> Vec { + let black = || Descriptor::new("RGBC").with("Rd ", Value::Double(0.0)).with("Grn ", Value::Double(0.0)).with("Bl ", Value::Double(0.0)); + let clr = |loc: i32| { + Value::Descriptor( + Descriptor::new("Clrt") + .with("Clr ", Value::Descriptor(black())) + .with("Type", Value::Enumerated { type_id: Id::new("Clry"), value: Id::new("UsrS") }) + .with("Lctn", Value::Integer(loc)) + .with("Mdpn", Value::Integer(50)), + ) + }; + let trn = |loc: i32, op: f32, mid: i32| { + Value::Descriptor(Descriptor::new("TrnS").with("Opct", unit(b"#Prc", op)).with("Lctn", Value::Integer(loc)).with("Mdpn", Value::Integer(mid))) + }; + let grad = Descriptor::new("Grdn") + .with("GrdF", Value::Enumerated { type_id: Id::new("GrdF"), value: Id::new("CstS") }) + .with("Intr", Value::Double(intr)) + .with("Clrs", Value::List(vec![clr(0), clr(4096)])) + .with("Trns", Value::List(vec![trn(0, 100.0, 50), trn(4096, 0.0, mid)])); + let fx = Descriptor::new("GrFl") + .with("enab", Value::Boolean(true)) + .with("Grad", Value::Descriptor(grad)) + .with("Angl", unit(b"#Ang", 0.0)) + .with("gs99", Value::Enumerated { type_id: Id::new("gradientInterpolationMethodType"), value: Id::new(method) }); + let d = Descriptor::new("null").with("masterFXSwitch", Value::Boolean(true)).with("GrFl", Value::Descriptor(fx)); + let mut data = 0u32.to_be_bytes().to_vec(); + data.extend(VersionedDescriptor { version: 16, descriptor: d }.to_bytes()); + data +} + +fn overlay_opacity(data: &[u8]) -> Vec<(f32, f32)> { + let (_, fx) = parse_lfx2(data).unwrap(); + let Some(Effect::GradientOverlay { gradient, .. }) = fx.first() else { panic!("overlay: {fx:?}") }; + gradient.opacity_stops.clone() +} + +fn opacity_at(o: &[(f32, f32)], t: f32) -> f32 { + let i = o.windows(2).position(|w| t >= w[0].0 && t <= w[1].0).unwrap(); + o[i].1 + (o[i + 1].1 - o[i].1) * (t - o[i].0) / (o[i + 1].0 - o[i].0) +} + +/// #1954: the overlay's transparency follows Smoothness, the opacity midpoints and the method +/// like a gradient fill layer's (Photoshop renders both identically; the values are its +/// composites at t = 0.25 and 0.5). +#[test] +fn gradient_overlay_opacity_follows_smoothness_midpoint_and_method() { + let at = |mid, intr, method: &str, t| opacity_at(&overlay_opacity(&overlay_lfx2(mid, intr, method)), t); + // Plain Classic stays the linear fade it is stored as. + assert_eq!(overlay_opacity(&overlay_lfx2(50, 0.0, "Gcls")), vec![(0.0, 1.0), (1.0, 0.0)]); + // Midpoint 25 %: half transparent a quarter of the way. + assert!((at(25, 0.0, "Gcls", 0.25) - 0.5).abs() < 0.01); + // Smoothness 100 % eases the ends (Photoshop: 0.796 at a quarter). + assert!((at(50, 4096.0, "Gcls", 0.25) - 0.796).abs() < 0.015); + // The method bends the transparency ramp too, not only the colours (Photoshop at the + // middle: 0.631 Linear, 0.255 Perceptual). + assert!((at(50, 0.0, "Lnr ", 0.5) - 0.631).abs() < 0.015); + assert!((at(50, 0.0, "Perc", 0.5) - 0.255).abs() < 0.015); + assert!((at(25, 4096.0, "Perc", 0.25) - 0.255).abs() < 0.015); +} + +/// A regenerated `lfx2` carries the baked ramp as plain (Classic, Smoothness 0) stops, so it +/// reads back unchanged. +#[test] +fn baked_overlay_opacity_round_trips() { + let data = overlay_lfx2(25, 4096.0, "Perc"); + let (master, fx) = parse_lfx2(&data).unwrap(); + let a = overlay_opacity(&data); + let b = overlay_opacity(&write_lfx2(master, &fx)); + assert!(a.len() > 2); + assert_eq!(a.len(), b.len()); + for (x, y) in a.iter().zip(&b) { + assert!((x.0 - y.0).abs() < 1e-3 && (x.1 - y.1).abs() < 1e-4, "{x:?} vs {y:?}"); + } +} + +#[test] +fn garbage_is_none() { + assert!(parse_lfx2(&[0, 0]).is_none()); + assert!(parse_lrfx(&[0, 0, 0, 1, b'X']).is_none()); +} + +#[test] +fn lrfx_drop_shadow() { + // version 0, count 1, 'dsdw' v2 record. + let mut d = vec![0, 0, 0, 1]; + d.extend_from_slice(b"8BIMdsdw"); + let mut rec = Vec::new(); + rec.extend_from_slice(&2u32.to_be_bytes()); // version + rec.extend_from_slice(&(7u32 << 16).to_be_bytes()); // blur (16.16) + rec.extend_from_slice(&0u32.to_be_bytes()); // intensity + rec.extend_from_slice(&(90u32 << 16).to_be_bytes()); // angle + rec.extend_from_slice(&(4u32 << 16).to_be_bytes()); // distance + rec.extend_from_slice(&[0, 0, 0xff, 0xff, 0, 0, 0, 0, 0, 0]); // color: red + rec.extend_from_slice(b"8BIMmul "); + rec.extend_from_slice(&[1, 1, 128]); + rec.extend_from_slice(&[0; 10]); + d.extend_from_slice(&(rec.len() as u32).to_be_bytes()); + d.extend(rec); + let (_, fx) = parse_lrfx(&d).unwrap(); + match &fx[0] { + Effect::DropShadow(s) => { + assert_eq!(s.size, 7.0); + assert_eq!(s.distance, 4.0); + assert_eq!(s.common.blend, BlendMode::Multiply); + assert!((s.common.opacity - 128.0 / 255.0).abs() < 1e-6); + assert_eq!(s.color.c[0], 1.0); + } + other => panic!("{other:?}"), + } +} diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rs index 7a92cc40d1..0c809273a9 100644 --- a/crates/io/src/psd_export.rs +++ b/crates/io/src/psd_export.rs @@ -15,6 +15,23 @@ use crate::blocks; use crate::pixels::{deinterleave, encode_be, psd_depth}; use crate::psd_import::REGENERATED; +mod document; +mod estimate; +mod merged; +mod resources; +mod smart; + +pub(crate) use document::document_to_psd_interruptible; +pub use document::{document_to_psd, document_to_psd_with}; +use document::{document_to_psd_nested, mask_parameters}; +#[cfg(test)] +pub(crate) use estimate::estimate_psd_size; +pub(crate) use estimate::{block_signature, psd_size_exceeds_limit, psd_version}; +#[cfg(test)] +use estimate::{estimate_encoded_size, exceeds_psd_size_limit}; +pub(crate) use resources::{global_block, guides_resource, keep_imported_resource, legacy_name, pascal_names_resource, path_resources, unicode_names_resource}; +use smart::{LINK_KEYS, SmartOut, Source, contents_uuid, effects_unchanged, masked, size_from_layer, smart_keys, upsert}; + /// Blocks that define a layer's content as something other than pixels: fill (`SoCo`, `GdFl`, /// `PtFl`), placed / smart object (`SoLd`, `PlLd`, `SoLE`), type (`TySh`) and shape fill (`vscg`). /// A raster layer never writes them, nor adjustment blocks. @@ -138,202 +155,6 @@ fn psd_background(doc: &Document) -> Option { /// as pixels instead. const MAX_NESTING: u32 = 8; -/// An embedded smart-object source as written to `lnk2`. -#[derive(Clone, Debug)] -struct Source { - uuid: String, - /// Pixel size of the source document. - size: (f64, f64), - dpi: f64, -} - -fn contents_uuid(contents_id: SmartContentsId, bytes: &[u8]) -> String { - let mut identity = blake3::Hasher::new(); - identity.update(&contents_id.0.to_le_bytes()); - identity.update(bytes); - crate::smart_map::uuid_from(identity.finalize().as_bytes()) -} - -/// Smart-object state collected while emitting layers, written into the global blocks at the end. -#[derive(Default)] -struct SmartOut { - /// Nesting depth of this export (embedded documents are exported recursively). - depth: u32, - /// The document's preserved global blocks (embedded files and filter caches from PSD import). - globals: Vec, - /// uuids of the files in the preserved linked-layer blocks. - known: std::collections::HashSet, - /// uuids the layers reference. - used: std::collections::HashSet, - /// Unreferenced preserved files may be dropped (every smart layer's file id is known). - prune_ok: bool, - /// Files to embed. - add: Vec, - /// Sources converted so far, by contents identity, bytes and whether they were read from a - /// link (`Err` = can't be embedded). - converted: std::collections::HashMap<(SmartContentsId, [u8; 32], bool), Result>, - /// Each placed layer has its own id, even when it duplicates an imported layer. - placed_used: std::collections::HashSet, - /// Original instances reserve their imported placement regardless of layer order. - placed_owners: std::collections::HashMap, - /// Legacy records without a placed id stay unchanged for the original instance. - unplaced_owners: std::collections::HashMap, - /// The imported identity that keeps each original linked UUID. - linked_contents: std::collections::HashMap, - /// Independent copies of preserved linked items, including unavailable external sources. - linked_copies: std::collections::BTreeMap<(String, SmartContentsId), photocraft_doc::PsdGlobalBlock>, - /// Embedded documents decoded while converting them, by uuid (for the filter caches). - docs: std::collections::HashMap, - /// Source composites (document pixel format, source space) by uuid; `None` = unreadable. - composites: std::collections::HashMap, photocraft_geom::Rect)>>, - /// Preserved `FEid` items (by placed id). - old_fx: Vec, - /// Placed ids whose preserved `FEid` item stays. - keep_fx: std::collections::HashSet, - /// Regenerated `FEid` items. - new_fx: Vec, - /// The unfiltered pixels of each smart object whose filter mask shows: its layer record holds - /// the filtered pixels without the mask, as Photoshop's do (`compose::filter_mask`). - unfiltered: std::collections::HashMap, -} - -/// Whether a smart object's filter mask shows: enabled over at least one visible, enabled filter. -fn masked(sm: &photocraft_doc::SmartObject) -> bool { - sm.filter_mask.as_ref().is_some_and(|m| m.enabled) && sm.filters_enabled && sm.smart_filters.iter().any(|f| f.visible) -} - -/// `FEid` data padded to 4 bytes inside the block length: Photoshop counts the padding in the -/// length and can't open a file whose `FEid` is padded outside it. -fn padded_fx(fx: &photocraft_psd::filter_effects::FilterEffects) -> Vec { - let mut d = fx.to_bytes(); - d.resize(d.len().next_multiple_of(4), 0); - d -} - -const LINK_KEYS: [&[u8; 4]; 4] = [b"lnk2", b"lnk3", b"lnkD", b"lnkE"]; -const FX_KEYS: [&[u8; 4]; 2] = [b"FEid", b"FXid"]; - -impl SmartOut { - fn new(doc: &Document, depth: u32) -> Self { - let globals = doc.metadata.psd_global_blocks.clone(); - let known = globals.iter().filter(|(_, k, _)| LINK_KEYS.contains(&k)).flat_map(|(_, _, d)| crate::linked::block_uuids(d)).collect(); - let old_fx = globals - .iter() - .filter(|(_, k, _)| FX_KEYS.contains(&k)) - .filter_map(|(_, _, d)| photocraft_psd::filter_effects::FilterEffects::parse(d).ok()) - .flat_map(|fx| fx.items) - .collect(); - let mut linked_contents = std::collections::HashMap::new(); - let mut placed_owners = std::collections::HashMap::new(); - let mut unplaced_owners = std::collections::HashMap::new(); - let mut layers = doc.walk(); - // Duplicating a layer clears psd_id and gives it a newer runtime id. - layers.sort_by_key(|(_, _, layer)| (layer.psd_id.is_none(), layer.id)); - for (_, _, layer) in layers { - if let LayerContent::Smart(sm) = &layer.content - && let photocraft_doc::SmartSource::Linked { path } = &sm.source - && let Some(placed) = sm.psd_raw.as_ref().and_then(|d| crate::smart_map::parse_sold(d)) - && placed.idnt == *path - { - linked_contents.entry(path.clone()).or_insert(sm.contents_id); - if placed.placed.is_empty() { - unplaced_owners.entry(sm.contents_id).or_insert(layer.id); - } else { - placed_owners.entry(placed.placed).or_insert(layer.id); - } - } - } - SmartOut { depth, globals, known, prune_ok: true, old_fx, linked_contents, placed_owners, unplaced_owners, ..Default::default() } - } - - /// The document's global blocks with the linked-layer files and filter caches brought up to - /// date: unreferenced files dropped (when every reference is known), new files appended, - /// filter caches kept or regenerated per smart object. Unchanged blocks stay byte-identical. - fn finish(&self, blocks: Vec) -> Vec { - use std::sync::Arc; - let keep = |u: &str| !self.prune_ok || self.used.contains(u); - let mut out = Vec::with_capacity(blocks.len() + 2); - let mut added = false; - let mut fx_placed = false; - for (sig, key, data) in blocks { - if LINK_KEYS.contains(&&key) { - let add: &[crate::linked::LinkedFile] = if !added && &key == b"lnk2" { &self.add } else { &[] }; - added |= &key == b"lnk2"; - match crate::linked::rebuild_block(&data, &keep, add) { - None => out.push((sig, key, data)), - Some(d) if d.is_empty() => {} - Some(d) => out.push((sig, key, Arc::new(d))), - } - } else if FX_KEYS.contains(&&key) { - let Ok(mut fx) = photocraft_psd::filter_effects::FilterEffects::parse(&data) else { - out.push((sig, key, data)); - continue; - }; - let before = fx.items.len(); - fx.items.retain(|i| self.keep_fx.contains(&i.id)); - let fresh = !fx_placed && !self.new_fx.is_empty(); - if fresh { - fx.items.extend(self.new_fx.iter().cloned()); - fx_placed = true; - } - if fx.items.len() == before && !fresh { - out.push((sig, key, data)); - } else if !fx.items.is_empty() { - out.push((sig, key, Arc::new(padded_fx(&fx)))); - } - } else { - out.push((sig, key, data)); - } - } - if !added && !self.add.is_empty() { - let data: Vec = self.add.iter().flat_map(crate::linked::encode_linked_file).collect(); - out.push((*b"8BIM", *b"lnk2", Arc::new(data))); - } - for (sig, key, data) in self.linked_copies.values() { - if let Some((_, _, block)) = out.iter_mut().find(|(s, k, _)| s == sig && k == key) { - Arc::make_mut(block).extend_from_slice(data); - } else { - out.push((*sig, *key, data.clone())); - } - } - if !fx_placed && !self.new_fx.is_empty() { - let fx = photocraft_psd::filter_effects::FilterEffects { version: 3, items: self.new_fx.clone() }; - out.push((*b"8BIM", *b"FEid", Arc::new(padded_fx(&fx)))); - if !out.iter().any(|(_, k, _)| k == b"FMsk") { - // Filter mask overlay: RGB red at 50 %, Photoshop's default. - out.push((*b"8BIM", *b"FMsk", Arc::new(vec![0, 0, 255, 255, 0, 0, 0, 0, 0, 0, 0, 50]))); - } - } - out - } -} - -/// The source size of a smart object whose file we can't decode: its rendered bounds taken back -/// through the inverse transform (the source's top-left is the origin). -fn size_from_layer(sm: &photocraft_doc::SmartObject) -> (f64, f64) { - let r = sm.cache.as_ref().map(Surface::content_bounds).filter(|r| !r.is_empty()); - let (Some(r), Some(inv)) = (r, sm.transform.inverse()) else { return (1.0, 1.0) }; - let [a, b, c, d, e, f] = inv.m; - let (mut w, mut h) = (1.0f64, 1.0f64); - for (x, y) in [(r.x0, r.y0), (r.x1, r.y0), (r.x1, r.y1), (r.x0, r.y1)] { - let (x, y) = (f64::from(x), f64::from(y)); - w = w.max((a * x + c * y + e).round()); - h = h.max((b * x + d * y + f).round()); - } - (w, h) -} - -fn upsert(raw: &mut Vec<([u8; 4], Vec)>, key: &[u8; 4], data: Vec, before: Option<&[u8; 4]>) { - if let Some(e) = raw.iter_mut().find(|(k, _)| k == key) { - e.1 = data; - return; - } - match before.and_then(|b| raw.iter().position(|(k, _)| k == b)) { - Some(i) => raw.insert(i, (*key, data)), - None => raw.push((*key, data)), - } -} - fn h_of(r: photocraft_geom::Rect) -> usize { r.height() as usize } @@ -1195,1283 +1016,5 @@ impl Ex { } } -/// Resource 1026 (Layer › Link Layers): one u16 group id per layer record, in the order -/// [`Ex::emit`] writes records (a group's bounding divider, its children, then the group). -/// Imported ids that fit in a u16 are kept, so unchanged files write the same bytes; otherwise -/// groups are renumbered by first appearance. `None` when no layer is linked. -fn link_group_resource(layers: &[Layer]) -> Option> { - fn walk(layers: &[Layer], out: &mut Vec>) { - for l in layers { - if let LayerContent::Group(g) = &l.content { - out.push(None); - walk(&g.children, out); - } - out.push(l.link_group); - } - } - let mut per = Vec::new(); - walk(layers, &mut per); - if per.iter().all(Option::is_none) { - return None; - } - let fits = per.iter().flatten().all(|&g| (1..=u64::from(u16::MAX)).contains(&g)); - let mut seen: Vec = Vec::new(); - let ids = per.iter().map(|g| match *g { - None => 0u16, - Some(g) if fits => g as u16, - Some(g) => { - let i = seen.iter().position(|&s| s == g).unwrap_or_else(|| { - seen.push(g); - seen.len() - 1 - }); - u16::try_from(i + 1).unwrap_or(u16::MAX) - } - }); - Some(ids.flat_map(u16::to_be_bytes).collect()) -} - -/// Whether the layer's effects still equal what its preserved `lmfx`/`lfx2` -/// decodes to. `None` when there is nothing preserved or it can't be decoded. -/// Block keys a smart object's `psd_raw` may be written under, in priority order. The data says -/// which it is: `PlLd` holds a `plcL` structure, `SoLd`/`SoLE` a `soLD` one (Adobe PSD spec, -/// "Placed Layer" and "Placed Layer Data"). Writing one under the other's key makes the block -/// unreadable. -fn smart_keys(data: Option<&[u8]>) -> &'static [&'static [u8; 4]] { - match data.and_then(|d| d.get(..4)) { - Some(b"plcL") => &[b"PlLd"], - Some(b"soLD") => &[b"SoLd", b"SoLE"], - _ => &[b"SoLd", b"PlLd", b"SoLE"], - } -} - -fn effects_unchanged(l: &Layer) -> Option { - let src = l.psd_blocks.iter().find(|(k, _)| k == b"lmfx").map(|(_, d)| d.clone()).or_else(|| l.effects.psd_raw.clone())?; - let (m, items) = crate::effects_map::parse_lfx2(&src)?; - Some(m == l.effects.enabled && items == l.effects.items) -} - -pub(crate) fn legacy_name(s: &str) -> Vec { - s.chars().map(|c| if c.is_ascii() && !c.is_ascii_control() { c as u8 } else { b'?' }).take(255).collect() -} - -pub(crate) fn unicode_names_resource(names: &[&str]) -> Vec { - let mut v = Vec::new(); - for n in names { - let units: Vec = n.encode_utf16().chain(std::iter::once(0)).collect(); - v.extend_from_slice(&(units.len() as u32).to_be_bytes()); - for u in units { - v.extend_from_slice(&u.to_be_bytes()); - } - } - v -} - -pub(crate) fn pascal_names_resource(names: &[&str]) -> Vec { - let mut v = Vec::new(); - for n in names { - let b = legacy_name(n); - let n = b.len().min(255); - v.push(n as u8); - v.extend_from_slice(&b[..n]); - } - // No per-string pad: Photoshop's resource 1006 for "Spot Color 1" is 13 bytes - // (length byte + 12 characters). The 8BIM container pads an odd resource separately. - v -} - -pub(crate) fn guides_resource(doc: &Document) -> Vec { - let mut v = Vec::new(); - v.extend_from_slice(&1u32.to_be_bytes()); - v.extend_from_slice(&576u32.to_be_bytes()); - v.extend_from_slice(&576u32.to_be_bytes()); - let n = doc.guides.horizontal.len() + doc.guides.vertical.len(); - v.extend_from_slice(&(n as u32).to_be_bytes()); - for (list, dir) in [(&doc.guides.vertical, 0u8), (&doc.guides.horizontal, 1u8)] { - for p in list { - v.extend_from_slice(&((p * 32.0).round() as i32).to_be_bytes()); - v.push(dir); - } - } - v -} - -/// Path resources: saved paths (2000+), the work path (1025) and the clipping path name (2999), -/// the last only when the imported one doesn't already name the document's clipping path. -pub(crate) fn path_resources(doc: &Document, warnings: &mut Vec) -> Vec { - use crate::vector_map::{CLIPPING_PATH, WORK_PATH, path_from_resource, path_to_records}; - let mut out = Vec::new(); - let (w, h) = (doc.size.width, doc.size.height); - let max = (*crate::vector_map::SAVED_PATHS.end() - *crate::vector_map::SAVED_PATHS.start() + 1) as usize; - if doc.paths.len() > max { - warnings.push(format!("only {max} saved paths fit in PSD; the rest were dropped")); - } - for (i, p) in doc.paths.iter().take(max).enumerate() { - let data = match &p.psd_raw { - Some(r) if path_from_resource(r, w, h).as_ref() == Some(&p.path) => r.to_vec(), - _ => path_to_records(&p.path, w, h).to_bytes(), - }; - let mut r = ImageResource::new(crate::vector_map::SAVED_PATHS.start() + i as u16, data); - r.name = legacy_name(&p.name); - out.push(r); - } - if let Some(wp) = &doc.work_path { - out.push(ImageResource::new(WORK_PATH, path_to_records(wp, w, h).to_bytes())); - } - let raw_clip = doc.metadata.psd_resources.iter().find(|(id, _, _)| *id == CLIPPING_PATH); - let raw_name = raw_clip.map(|(_, _, d)| { - let n = usize::from(d.first().copied().unwrap_or(0)); - d.get(1..1 + n).map(|b| String::from_utf8_lossy(b).into_owned()).unwrap_or_default() - }); - if let Some(c) = &doc.clipping_path - && raw_name.as_deref() != Some(c.name.as_str()) - { - // Pascal name, then flatness as 16.16 fixed (best effort; see vector_map docs). - let mut data = vec![0u8]; - let name = legacy_name(&c.name); - data[0] = name.len() as u8; - data.extend_from_slice(&name); - data.extend_from_slice(&((c.flatness.max(0.0) * 65536.0) as u32).to_be_bytes()); - out.push(ImageResource::new(CLIPPING_PATH, data)); - } - out -} - -/// Whether an imported (unmodelled) resource still describes the document and is written back. -pub(crate) fn keep_imported_resource(doc: &Document, id: u16, data: &[u8]) -> bool { - // Measurement scale / count resources: only while they still describe the document. - if !crate::annotations_map::keep_resource(doc, id) { - return false; - } - // Guides v2 and guide GUIDs: only while they still describe the document's guides. - if !crate::guides_map::keep_resource(doc, id, data) { - return false; - } - // A preserved clipping-path resource is only valid while it names the current one. - if id == crate::vector_map::CLIPPING_PATH { - let n = usize::from(data.first().copied().unwrap_or(0)); - let raw_name = data.get(1..1 + n).map(|b| String::from_utf8_lossy(b).into_owned()).unwrap_or_default(); - return doc.clipping_path.as_ref().is_some_and(|c| c.name == raw_name); - } - true -} - -/// A document-level (global) tagged block. Photoshop pads these to a multiple of 4, and readers -/// such as psd-tools step to the next block that way: an even pad after `CAI ` (77 bytes) -/// misaligned every block after it (#200). -pub(crate) fn global_block(signature: [u8; 4], key: [u8; 4], data: &[u8]) -> TaggedBlock { - let mut tb = TaggedBlock::new(key, data.to_vec()); - tb.signature = signature; - tb.padding = Some(vec![0; (4 - data.len() % 4) % 4]); - tb -} - -fn cmyk_of(fmt: &PixelFormat) -> bool { - fmt.mode == ColorMode::Cmyk -} - -/// The merged image's planes (colour channels, then alpha), big-endian, matted against white -/// when `matte`; with whether any pixel needs the alpha channel and whether any is below 1. -/// `ctl` gets the fraction of rows done after each band; once it is cancelled the rest of the -/// image is left blank (the caller discards it). -fn merged_planes(doc: &Document, fmt: &PixelFormat, cmyk: bool, matte: bool, ctl: &Interrupt) -> (Vec, bool, bool) { - if cmyk && let Some(planes) = merged_ink_planes(doc, fmt.sample, matte, ctl) { - return planes; - } - let sample = fmt.sample; - let cc = fmt.mode.color_channels(); - let bps = sample.bytes(); - let n = doc.size.area() as usize; - let plane = n * bps; - let mut planes = vec![0u8; plane * (cc + 1)]; - let (mut has_alpha, mut translucent) = (false, false); - let white = photocraft_raster::from_rgba(fmt, [1.0, 1.0, 1.0, 1.0]); - let canvas = doc.bounds(); - let w = canvas.width() as usize; - let space = photocraft_compose::cmyk_space(doc); - let lab16 = fmt.mode == ColorMode::Lab && sample == SampleType::U16; - let rows = canvas.height().max(1) as f32; - let _ = photocraft_compose::render_bands(doc, canvas, 0, |band| -> Result<(), ()> { - if ctl.cancelled() { - return Err(()); - } - // Retain alpha whenever it differs from opaque at the stored precision. - has_alpha |= band.px.iter().any(|p| match sample { - SampleType::U8 => q255(p[3]) < 255, - SampleType::U16 => (p[3].clamp(0.0, 1.0) * 65535.0 + 0.5) as u16 != u16::MAX, - SampleType::F32 => p[3] != 1.0, - }); - translucent |= band.px.iter().any(|p| p[3] < 1.0); - let start = (band.rect.y0 - canvas.y0) as usize * w; - // Converted and encoded on all cores, then copied into each plane. - let parts = crate::pixels::par_map(crate::pixels::bands(band.px.len()), |range| { - // The composite came through the document's CMYK profile: convert back through it too. - photocraft_color::convert::with_cmyk_space(space.as_ref(), || { - let mut out: Vec> = vec![Vec::with_capacity(range.len() * bps); cc + 1]; - let mut v = [0.0f32; 5]; - for p in &band.px[range.clone()] { - photocraft_raster::from_rgba_into(fmt, *p, &mut v); - for c in 0..=cc { - // Matte against white like Photoshop (see `pixels::matte`). - let m = if c < cc && matte { crate::pixels::matte(v[c], v[cc], white[c]) } else { v[c] }; - let x = if cmyk && c < cc { 1.0 - m } else { m }; - // 16-bit Lab a*/b* use Photoshop's 0..65280 scale (`pixels::lab16_chroma`). - let x = if lab16 && (c == 1 || c == 2) { x * (crate::pixels::LAB16_CHROMA_MAX / 65535.0) } else { x }; - encode_be(x, sample, &mut out[c]); - } - } - (range.start, out) - }) - }); - for (at, part) in parts { - for (c, src) in part.iter().enumerate() { - let o = c * plane + (start + at) * bps; - planes[o..o + src.len()].copy_from_slice(src); - } - } - ctl.progress((band.rect.y1 - canvas.y0) as f32 / rows); - Ok(()) - }); - (planes, has_alpha, translucent) -} - -/// [`merged_planes`] of a CMYK document whose layers are mixed on their ink values -/// (`photocraft_compose::cmyk`), so opaque pixels keep their exact inks; `None` for documents -/// that composite in RGB. Reports progress and stops on cancel like [`merged_planes`]. -fn merged_ink_planes(doc: &Document, sample: SampleType, matte: bool, ctl: &Interrupt) -> Option<(Vec, bool, bool)> { - let bps = sample.bytes(); - let n = doc.size.area() as usize; - let plane = n * bps; - let mut planes = vec![0u8; plane * 5]; - let (mut has_alpha, mut translucent) = (false, false); - let canvas = doc.bounds(); - let w = canvas.width() as usize; - let rows = canvas.height().max(1) as f32; - // A cancelled export leaves the rest blank (the caller discards it), so the result stands either way. - let _ = photocraft_compose::cmyk::render_cmyk_bands(doc, canvas, 0, |band| -> Result<(), ()> { - if ctl.cancelled() { - return Err(()); - } - // Retain alpha whenever it differs from opaque at the stored precision. - has_alpha |= band.px.iter().any(|p| match sample { - SampleType::U8 => q255(p[4]) < 255, - SampleType::U16 => (p[4].clamp(0.0, 1.0) * 65535.0 + 0.5) as u16 != u16::MAX, - SampleType::F32 => p[4] != 1.0, - }); - translucent |= band.px.iter().any(|p| p[4] < 1.0); - let start = (band.rect.y0 - canvas.y0) as usize * w; - let parts = crate::pixels::par_map(crate::pixels::bands(band.px.len()), |range| { - let mut out: Vec> = (0..5).map(|_| Vec::with_capacity(range.len() * bps)).collect(); - for p in band.px.get(range.clone()).unwrap_or(&[]) { - for (c, o) in out.iter_mut().enumerate() { - // Inks matted against white paper (no ink) like Photoshop (see - // `pixels::matte`), and stored inverted as PSD's CMYK is. - let v = if c < 4 { 1.0 - if matte { crate::pixels::matte(p[c], p[4], 0.0) } else { p[c] } } else { p[4] }; - encode_be(v, sample, o); - } - } - (range.start, out) - }); - for (at, part) in parts { - for (c, src) in part.iter().enumerate() { - let o = c * plane + (start + at) * bps; - if let Some(dst) = planes.get_mut(o..o + src.len()) { - dst.copy_from_slice(src); - } - } - } - ctl.progress((band.rect.y1 - canvas.y0) as f32 / rows); - Ok(()) - })?; - Some((planes, has_alpha, translucent)) -} - -/// The merged image of a file saved without Maximize Compatibility: Photoshop's white placeholder -/// in the document's colour channels, with no alpha. Encoded like [`merged_planes`], so CMYK white -/// is no ink and Lab white is L 100 with neutral a*/b*. -fn placeholder_planes(doc: &Document, fmt: &PixelFormat) -> Vec { - let cc = fmt.mode.color_channels(); - let cmyk = cmyk_of(fmt); - let lab16 = fmt.mode == ColorMode::Lab && fmt.sample == SampleType::U16; - let space = photocraft_compose::cmyk_space(doc); - let white = photocraft_color::convert::with_cmyk_space(space.as_ref(), || photocraft_raster::from_rgba(fmt, [1.0, 1.0, 1.0, 1.0])); - let n = doc.size.area() as usize; - let mut planes = Vec::with_capacity(n * fmt.sample.bytes() * cc); - for c in 0..cc { - let v = white.get(c).copied().unwrap_or(1.0); - let x = if cmyk { 1.0 - v } else { v }; - let x = if lab16 && (c == 1 || c == 2) { x * (crate::pixels::LAB16_CHROMA_MAX / 65535.0) } else { x }; - let mut sample = Vec::with_capacity(4); - encode_be(x, fmt.sample, &mut sample); - planes.extend(sample.iter().copied().cycle().take(n * sample.len())); - } - planes -} - -/// Converts a document to a PSD file model (see [`document_to_psd_with`]). -pub fn document_to_psd(doc: &Document) -> PsdFile { - document_to_psd_with(doc, &PsdExportOptions::default()).0 -} - -/// Converts a document to a PSD/PSB file model, returning warnings about -/// anything that could not be represented. The merged composite is rendered -/// with `photocraft_compose::flatten`. -pub fn document_to_psd_with(doc: &Document, opts: &PsdExportOptions) -> (PsdFile, Vec) { - document_to_psd_nested(doc, opts, 0, &Interrupt::NONE) -} - -/// [`document_to_psd_with`] for a background save (#3389): reports progress through `ctl` after -/// each layer record and each band of the merged composite. Once `ctl` is cancelled it stops -/// early and returns an **incomplete** model: callers check `ctl` and discard it. -pub(crate) fn document_to_psd_interruptible(doc: &Document, opts: &PsdExportOptions, ctl: &Interrupt) -> (PsdFile, Vec) { - document_to_psd_nested(doc, opts, 0, ctl) -} - -/// How much of a PSD conversion the merged composite weighs, in layer records: rendering it -/// (all layers composited) and encoding its planes cost about two full-canvas layers. -const MERGED_WEIGHT: f32 = 2.0; -/// The part of the merged composite's share filled once its bands are rendered and converted; the -/// rest is compressing its planes. -const MERGED_RENDERED: f32 = 0.8; - -/// Adds headroom for compressed channel streams and their per-row length tables. -fn estimate_encoded_size(raw_bytes: u64, rows: u64, structural_bytes: u64) -> Option { - raw_bytes.checked_add(raw_bytes.checked_add(63)?.checked_div(64)?)?.checked_add(rows.checked_mul(8)?)?.checked_add(structural_bytes) -} - -fn add_plane_estimate(raw_bytes: &mut u64, rows: &mut u64, width: u64, height: u64, channels: u64, bytes_per_sample: u64) -> Option<()> { - let plane_bytes = width.checked_mul(height)?.checked_mul(channels)?.checked_mul(bytes_per_sample)?; - let plane_rows = height.checked_mul(channels)?; - *raw_bytes = raw_bytes.checked_add(plane_bytes)?; - *rows = rows.checked_add(plane_rows)?; - Some(()) -} - -fn exceeds_psd_size_limit(estimated_size: Option) -> bool { - estimated_size.is_none_or(|size| size > PSD_MAX_FILE_SIZE) -} - -fn surface_dimensions(surface: &Surface) -> Option<(u64, u64)> { - let bounds = surface.content_bounds(); - Some((u64::from(bounds.width()), u64::from(bounds.height()))) -} - -pub(crate) fn estimate_psd_size(doc: &Document) -> Option { - let mut raw_bytes = 0; - let mut rows = 0; - let mut structural_bytes = PSD_ESTIMATE_FIXED_OVERHEAD; - - let width = u64::from(doc.size.width); - let height = u64::from(doc.size.height); - - if doc.mode == ColorMode::Multichannel { - let channels = u64::try_from(doc.channels.len().clamp(1, 56)).ok()?; - let sample_bytes = u64::try_from(if doc.depth == SampleType::F32 { SampleType::U16.bytes() } else { doc.depth.bytes() }).ok()?; - add_plane_estimate(&mut raw_bytes, &mut rows, width, height, channels, sample_bytes)?; - } else { - let format = doc.pixel_format(); - let color_channels = u64::try_from(format.mode.color_channels()).ok()?; - let bytes_per_sample = u64::try_from(format.sample.bytes()).ok()?; - let layer_channels = color_channels.checked_add(1)?; - - for (_, _, layer) in doc.walk() { - structural_bytes = structural_bytes.checked_add(PSD_ESTIMATE_LAYER_OVERHEAD)?.checked_add(u64::try_from(layer.name.len()).ok()?)?; - for (_, data) in &layer.psd_blocks { - structural_bytes = structural_bytes.checked_add(u64::try_from(data.len()).ok()?)?; - } - - let surface = match &layer.content { - LayerContent::Fill(fill) => { - let mut fill_width = width; - let mut fill_height = height; - if let Some(cache) = &layer.fill_cache - && cache.fill == *fill - { - let (cache_width, cache_height) = surface_dimensions(&cache.surface)?; - fill_width = fill_width.max(cache_width); - fill_height = fill_height.max(cache_height); - } - add_plane_estimate(&mut raw_bytes, &mut rows, fill_width, fill_height, layer_channels, bytes_per_sample)?; - None - } - _ => layer.surface(), - }; - if let Some(surface) = surface { - let (surface_width, surface_height) = surface_dimensions(surface)?; - add_plane_estimate(&mut raw_bytes, &mut rows, surface_width, surface_height, layer_channels, bytes_per_sample)?; - } - if let Some(mask) = &layer.mask { - let (mask_width, mask_height) = surface_dimensions(&mask.surface)?; - add_plane_estimate(&mut raw_bytes, &mut rows, mask_width, mask_height, 1, bytes_per_sample)?; - } - if let LayerContent::Smart(smart) = &layer.content - && let photocraft_doc::SmartSource::Embedded { bytes, .. } = &smart.source - { - structural_bytes = structural_bytes.checked_add(u64::try_from(bytes.len()).ok()?)?; - } - } - - let max_extra_channels = 56usize.saturating_sub(format.mode.color_channels() + 1); - let mut extra_channels = doc.channels.len().min(max_extra_channels); - if doc.quick_mask.is_some() && extra_channels < max_extra_channels { - extra_channels += 1; - } - let merged_channels = color_channels.checked_add(1)?.checked_add(u64::try_from(extra_channels).ok()?)?; - add_plane_estimate(&mut raw_bytes, &mut rows, width, height, merged_channels, bytes_per_sample)?; - for channel in doc.channels.iter().take(extra_channels) { - structural_bytes = structural_bytes.checked_add(u64::try_from(channel.name.len()).ok()?)?; - } - } - - structural_bytes = structural_bytes - .checked_add(u64::try_from(doc.icc_profile.as_ref().map_or(0, |profile| profile.len())).ok()?)? - .checked_add(u64::try_from(doc.metadata.xmp.as_deref().map_or(0, str::len)).ok()?)? - .checked_add(u64::try_from(doc.metadata.exif.as_ref().map_or(0, |data| data.len())).ok()?)?; - for (_, name, data) in &doc.metadata.psd_resources { - structural_bytes = structural_bytes.checked_add(u64::try_from(name.len()).ok()?)?.checked_add(u64::try_from(data.len()).ok()?)?; - } - for (_, _, data) in &doc.metadata.psd_global_blocks { - structural_bytes = structural_bytes.checked_add(u64::try_from(data.len()).ok()?)?; - } - - estimate_encoded_size(raw_bytes, rows, structural_bytes) -} - -/// The signature a kept tagged block is written with. `8B64` exists only in PSB files: a PSD -/// with an `8B64` block (kept from a PSB source, e.g. its global `FMsk` or `cinf`) is refused by -/// Photoshop as "not compatible with this version" (measured in Photoshop 27.11). The other way -/// round, a PSB block with an 8-byte length is `8B64`, as Photoshop writes it: an `8BIM` `lnk2`, -/// `pths` or `cinf` (kept from a PSD source, whose lengths the PSB widens) makes Photoshop read -/// the length as 4 bytes and refuse the whole file (#7937). -pub(crate) fn block_signature(sig: [u8; 4], key: [u8; 4], version: Version) -> [u8; 4] { - match version { - Version::Psd if sig == *b"8B64" => *b"8BIM", - Version::Psb if sig == *b"8BIM" && photocraft_psd::tagged::uses_long_length(version, &key) => *b"8B64", - _ => sig, - } -} - -pub(crate) fn psd_version(doc: &Document, force_psb: bool, size_exceeds_limit: bool) -> Version { - let exceeds_dimensions = doc.size.width > 30_000 || doc.size.height > 30_000; - if force_psb || exceeds_dimensions || size_exceeds_limit { Version::Psb } else { Version::Psd } -} - -pub(crate) fn psd_size_exceeds_limit(doc: &Document) -> bool { - exceeds_psd_size_limit(estimate_psd_size(doc)) -} - -/// [`document_to_psd_with`] for a document embedded `depth` smart objects deep. -fn document_to_psd_nested(doc: &Document, opts: &PsdExportOptions, depth: u32, ctl: &Interrupt) -> (PsdFile, Vec) { - if doc.mode == ColorMode::Multichannel { - return crate::multichannel_map::document_to_psd(doc, opts.force_psb); - } - if let Some(file) = crate::palette_map::document_to_psd(doc, opts.force_psb) { - return file; - } - let fmt = doc.pixel_format(); - // A Duotone is written over its grey plate with its inks: the block it was imported with, - // verbatim, while the inks are unedited, else one made from them (`duotone_map`). Photoshop - // has only 8-bit Duotone: it refuses to open a 16-bit one. - let duotone_inks: Option> = doc - .duotone - .as_ref() - .filter(|d| !d.inks.is_empty() && doc.mode == ColorMode::Duotone && fmt.mode == ColorMode::Grayscale && fmt.sample == SampleType::U8) - .map(|d| d.psd_raw.as_deref().map_or_else(|| crate::duotone_map::write(d), <[u8]>::to_vec)); - let sample = fmt.sample; - let cc = fmt.mode.color_channels(); - let big = doc.size.width > 30_000 || doc.size.height > 30_000; - let size_exceeds_limit = opts.size_limit_psb && !opts.force_psb && !big && psd_size_exceeds_limit(doc); - let version = psd_version(doc, opts.force_psb, size_exceeds_limit); - let mut ex = Ex { - fmt, - dpi: doc.resolution_dpi, - document: opts.document_path.clone(), - read_linked_files: opts.read_linked_files, - text_styles: doc.text_styles.clone(), - text_index: Default::default(), - mask_fmt: PixelFormat::new(ColorMode::Grayscale, sample, false), - cc, - cmyk: fmt.mode == ColorMode::Cmyk, - version, - next_id: 0, - used_ids: Default::default(), - layer_ids: Default::default(), - canvas: doc.bounds(), - records: Vec::new(), - warnings: Vec::new(), - guides: doc.guides.clone(), - comps: (!crate::comps_map::comps_unchanged(doc)).then(|| (doc.layer_comps.clone(), doc.last_document_state.clone())), - smart: SmartOut::new(doc, depth), - patterns: doc.patterns.clone(), - background: psd_background(doc), - }; - if big && !opts.force_psb { - ex.warnings.push("document exceeds 30000 px; written as PSB".into()); - } else if size_exceeds_limit && !opts.force_psb { - ex.warnings.push("estimated encoded size exceeds 2 GB; written as PSB".into()); - } - if fmt.mode != doc.mode && duotone_inks.is_none() { - ex.warnings.push(format!("{:?} document written as {:?}", doc.mode, fmt.mode)); - } - // Assign layer ids up front (stable across round trips): keep unique - // `psd_id`s, number the rest after them; dividers come after all. - { - let walk = doc.walk(); - let mut used = std::collections::HashSet::new(); - for (_, _, l) in &walk { - if let Some(id) = l.psd_id - && used.insert(id) - { - ex.layer_ids.insert(l.id, id); - } - } - let mut next = 1u32; - for (_, _, l) in &walk { - if let std::collections::hash_map::Entry::Vacant(e) = ex.layer_ids.entry(l.id) { - while used.contains(&next) { - next += 1; - } - used.insert(next); - e.insert(next); - } - } - ex.next_id = used.iter().copied().max().unwrap_or(0); - ex.used_ids = used; - // Text objects' number in the generated `Txt2` (#1348): a preserved `TySh` keeps the - // number it already names — its `Txt2` object must sit at that slot for `apply_txt2` — - // and new layers get numbers past every kept one and every object in the file's `Txt2`. - // Kept numbers are claimed first: a layer added below others must not take a number a - // layer above it keeps, or each of those would be renumbered onto its neighbour's object - // and take its style (#7773); nor may it land on a deleted layer's object. - let mut used_txt = std::collections::HashSet::new(); - ex.text_index = Default::default(); - let mut fresh = Vec::new(); - for (_, _, l) in &walk { - let LayerContent::Text(t) = &l.content else { - continue; - }; - match t.psd_raw.as_deref().and_then(|d| photocraft_text::psd::text_index(d)) { - Some(i) if used_txt.insert(i) => { - ex.text_index.insert(l.id, i); - } - _ => fresh.push(l.id), - } - } - let objects = - doc.metadata.psd_global_blocks.iter().find(|(_, key, _)| key == b"Txt2").map_or(0, |(_, _, d)| photocraft_text::psd::txt2_object_count(d)); - let mut next_txt = used_txt.iter().max().map_or(0, |m| m + 1).max(i32::try_from(objects).unwrap_or(i32::MAX)); - if next_txt.saturating_add(fresh.len() as i32) > photocraft_text::psd::MAX_TEXT_INDEX + 1 { - next_txt = 0; - } - for id in fresh { - while used_txt.contains(&next_txt) { - next_txt += 1; - } - used_txt.insert(next_txt); - ex.text_index.insert(id, next_txt); - } - } - // Progress: one unit per layer record, then the merged composite (#3389). - let records = doc.walk().len() as f32; - let units = records + MERGED_WEIGHT; - let layers_share = records / units; - let mut done = 0.0f32; - let mut tick = || { - done += 1.0; - ctl.progress(done / units); - !ctl.cancelled() - }; - let space = photocraft_compose::cmyk_space(doc); - photocraft_color::convert::with_cmyk_space(space.as_ref(), || ex.emit(&doc.layers, &mut tick)); - - // Without Maximize Compatibility the merged image is a white placeholder and the composite - // isn't rendered at all. A document without layer records keeps the real image: its pixels - // live nowhere else. So does a Duotone: it opens flattened from that image (its layer records - // are not read back). - let real_merged = opts.maximize_compatibility || ex.records.is_empty() || duotone_inks.is_some(); - let (mut planes, has_alpha) = if real_merged { - // Merged composite, rendered and encoded in bands (no full-size float composite). Matting - // against white only changes pixels with alpha < 1; if some are slightly translucent but - // all round to opaque (so no alpha channel is written), encode once more without the matte. - let merged_end = layers_share + (1.0 - layers_share) * MERGED_RENDERED; - let (mut planes, has_alpha, translucent) = - crate::with_span(ctl, layers_share, merged_end, |ctl| merged_planes(doc, &fmt, cmyk_of(&fmt), opts.merged_matte, ctl)); - if !has_alpha && translucent && opts.merged_matte { - planes = merged_planes(doc, &fmt, cmyk_of(&fmt), false, &Interrupt::cancel_only(&|| ctl.cancelled())).0; - } - (planes, has_alpha) - } else { - (placeholder_planes(doc, &fmt), false) - }; - let n = doc.size.area() as usize; - if !has_alpha { - planes.truncate(cc * n * sample.bytes()); - } - let canvas = doc.bounds(); - let max_extra = 56 - cc - usize::from(has_alpha); - if doc.channels.len() > max_extra { - ex.warnings.push(format!("only {max_extra} alpha channels fit in PSD; the rest were dropped")); - } - let mut extra: Vec<_> = doc.channels.iter().take(max_extra).collect(); - // Saved in Quick Mask mode: the mask is written as the last extra channel and flagged by - // resource 1022 (quick mask info: channel id, initially-empty flag), as Photoshop does. - let quick_mask_id = match &doc.quick_mask { - Some(q) if extra.len() < max_extra => { - extra.push(q); - Some((cc + usize::from(has_alpha) + extra.len() - 1) as u16) - } - Some(_) => { - ex.warnings.push("Quick Mask was dropped because the PSD channel limit was reached".into()); - None - } - None => None, - }; - for a in &extra { - let s = if a.surface.format() != ex.mask_fmt { a.surface.convert(ex.mask_fmt) } else { a.surface.clone() }; - let mut bytes = s.to_interleaved(canvas); - // Spot ink as Photoshop stores it (0 = solid); an alpha channel stays straight. - if a.spot.is_some() { - crate::channel_map::photoshop_spot_plane(&mut bytes, sample); - } - planes.extend(deinterleave(&bytes, 1, sample, &[false]).remove(0)); - } - let channels = (cc + usize::from(has_alpha) + extra.len()) as u16; - let mode = if duotone_inks.is_some() { PsdMode::Duotone } else { psd_mode(fmt.mode) }; - let header = Header::new(version, doc.size.width, doc.size.height, channels, psd_depth(sample), mode); - let mcomp = if sample == SampleType::F32 { Compression::Raw } else { opts.merged_compression }; - let image_data = ImageData::encode(mcomp, &planes, &header) - .or_else(|_| ImageData::encode(Compression::Raw, &planes, &header)) - .unwrap_or(ImageData { compression: Compression::Raw, data: planes }); - ctl.progress(1.0); - - // Resources. - let mut resources = vec![ - // hRes/vRes are always pixels per inch. The display unit written here is inches. - ImageResource::new(ids::RESOLUTION_INFO, ResolutionInfo::from_dpi(f64::from(doc.resolution_dpi)).to_bytes()), - ImageResource::new(ids::GLOBAL_ANGLE, (doc.global_light.angle.round() as i32).to_be_bytes().to_vec()), - ImageResource::new(ids::GLOBAL_ALTITUDE, (doc.global_light.altitude.round() as i32).to_be_bytes().to_vec()), - ]; - if let Some(icc) = &doc.icc_profile { - resources.push(ImageResource::new(ids::ICC_PROFILE, icc.to_vec())); - } - if !doc.guides.horizontal.is_empty() || !doc.guides.vertical.is_empty() { - resources.push(ImageResource::new(1032, guides_resource(doc))); - } - if !extra.is_empty() { - // One entry per extra channel, the merged transparency included (as in every file - // Photoshop opens; one short, Photoshop refuses the file with "unexpected end-of-file"). - let names: Vec<&str> = has_alpha.then_some("Transparency").into_iter().chain(extra.iter().map(|a| a.name.as_str())).collect(); - resources.push(ImageResource::new(1006, pascal_names_resource(&names))); - resources.push(ImageResource::new(1045, unicode_names_resource(&names))); - resources.push(ImageResource::new(crate::channel_map::DISPLAY_INFO, crate::channel_map::display_info(&extra, has_alpha))); - // Photoshop writes 1053 in every file with an extra channel. Its absence is how a file from - // an earlier PhotoCraft is told apart (`psd_import::earlier_photocraft_spot_planes`). - resources.push(ImageResource::new(crate::channel_map::ALPHA_IDENTIFIERS, crate::channel_map::alpha_identifiers(has_alpha, extra.len()))); - } - if let Some(id) = quick_mask_id { - let mut data = id.to_be_bytes().to_vec(); - data.push(0); - resources.push(ImageResource::new(crate::channel_map::QUICK_MASK_INFO, data)); - } - resources.extend(path_resources(doc, &mut ex.warnings)); - if let Some(groups) = link_group_resource(&doc.layers) { - resources.push(ImageResource::new(ids::LAYER_GROUP_INFO, groups)); - } - // The pixels are saved as they are shown: never let a reader rotate them again. The XMP and - // EXIF resolution follow the ResolutionInfo resource, so no copy contradicts it (#1691). - let ppi = Some((doc.resolution_dpi, doc.resolution_dpi)).filter(|d| d.0 > 0.0); - if let Some(x) = &doc.metadata.xmp { - resources.push(ImageResource::new(ids::XMP, photocraft_codecs::export_xmp(x, ppi).as_bytes().to_vec())); - } - if let Some(e) = &doc.metadata.exif { - resources.push(ImageResource::new(ids::EXIF, photocraft_codecs::export_exif(e, ppi).into_owned())); - } - let mut global_blocks = Vec::new(); - let preserved = ex.smart.finish(crate::annotations_map::export_blocks(doc, crate::pattern_map::export_global_blocks(doc))); - // The type layers' `Txt2` is regenerated (the auto-kern modes live there, and a preserved - // block goes stale as text is edited): one object per `TextIndex`, at the slot each layer's - // `TySh` names (unused slots stay empty; see `photocraft_text::psd::build_txt2`). The block - // it replaces is handed over so a kept object keeps everything the file held beyond its text - // and style runs (Photoshop's `/21 /1` glyph pen positions, …). - let text_layers: Vec<(i32, &photocraft_doc::TextLayer)> = doc - .walk() - .into_iter() - .filter_map(|(_, _, l)| match &l.content { - LayerContent::Text(t) => Some((ex.text_index.get(&l.id).copied().unwrap_or(0), t)), - _ => None, - }) - .collect(); - let previous = (!text_layers.is_empty()).then(|| preserved.iter().find(|(_, key, _)| key == b"Txt2").map(|(_, _, data)| data.to_vec())).flatten(); - // A fresh document of ordinary (Metrics) text has nothing to put in `Txt2`, and Photoshop never - // writes its empty `<< /0 << >> >>` stub — readers such as Photopea reject it (#3514). Keep the - // block when the file had one (round-trip its pen positions/extras) or a layer is Optical (the - // one mode EngineData can't carry; #1348). - let txt2 = (previous.is_some() || photocraft_text::psd::needs_txt2(&text_layers)) - .then(|| photocraft_text::psd::build_txt2_at(&text_layers, previous.as_deref(), ex.dpi)); - for (sig, key, data) in preserved { - if txt2.is_some() && key == *b"Txt2" { - continue; - } - // A kept layer block (one the import could not read, #2700) describes layers the - // document doesn't have. The document's own layers are written below, and a file holds - // one layer list: a second `Lr16`/`Lr32` would contradict it. - if !ex.records.is_empty() && matches!(&key, b"Lr16" | b"Lr32" | b"Layr") { - continue; - } - let block = global_block(block_signature(sig, key, version), key, &data); - // A kept merged-transparency marker describes the opened file's composite. Over an opaque - // one it would make the first alpha channel read back as the transparency, and vanish. - if !has_alpha && block.is_merged_transparency_marker() { - continue; - } - global_blocks.push(block); - } - if let Some(txt2) = txt2 { - let mut tb = TaggedBlock::new(*b"Txt2", txt2.clone()); - tb.signature = *b"8BIM"; - tb.padding = Some(vec![0; (4 - txt2.len() % 4) % 4]); - global_blocks.push(tb); - } - let comps_resource = ex.comps.is_some().then(|| crate::comps_map::write_comps_resource(doc)); - let (slices_resource, slices_warning) = crate::slices_map::export_resource(doc, &ex.layer_ids); - if let Some(warning) = slices_warning { - ex.warnings.push(warning); - } - for (id, name, data) in &doc.metadata.psd_resources { - // Layer comps: the preserved list while unchanged, else regenerated (or dropped) below. - if *id == crate::comps_map::LAYER_COMPS && comps_resource.is_some() { - continue; - } - // Slices: the preserved resource while unchanged, else regenerated (or dropped) below. - if *id == crate::slices_map::SLICES && slices_resource.is_some() { - continue; - } - if !keep_imported_resource(doc, *id, data) { - continue; - } - // 1053 is written afresh with the extra channels. A kept copy (from a Multichannel file, or - // a document saved by an earlier version) would be a second one, or list channels that - // are gone. - if *id == crate::channel_map::ALPHA_IDENTIFIERS { - continue; - } - let mut r = ImageResource::new(*id, data.to_vec()); - r.name = legacy_name(name); - resources.push(r); - } - if let Some(data) = crate::annotations_map::fresh_scale_resource(doc) { - resources.push(ImageResource::new(crate::annotations_map::MEASUREMENT_SCALE, data)); - } - if let Some(Some(data)) = comps_resource { - resources.push(ImageResource::new(crate::comps_map::LAYER_COMPS, data)); - } - if let Some(Some(data)) = slices_resource { - resources.push(ImageResource::new(crate::slices_map::SLICES, data)); - } - resources.push(version_info_resource(real_merged)); - - let has_layers = !ex.records.is_empty(); - // Photoshop writes a merged-transparency marker (`Mtrn`, `Mt16`, `Mt32`; `MTrn` in a TIFF) - // before the layer block, and won't open a file whose `Lr32` comes first (#5068): the layer - // block goes right after the last kept marker, else first. - let index = global_blocks.iter().rposition(TaggedBlock::is_merged_transparency_marker).map_or(0, |i| i + 1); - let placement = match (has_layers, sample) { - (true, SampleType::U16) => LayerInfoPlacement::GlobalBlock { index, signature: *b"8BIM", key: *b"Lr16", padding: None }, - (true, SampleType::F32) => LayerInfoPlacement::GlobalBlock { index, signature: *b"8BIM", key: *b"Lr32", padding: None }, - _ => LayerInfoPlacement::Section, - }; - let records = std::mem::take(&mut ex.records); - let mut layer_info = has_layers.then_some(LayerInfo { merged_alpha: has_alpha, layers: records, padding: None }); - if let Some(info) = &mut layer_info { - // Photoshop pads the layer info to 4 bytes (an even pad misaligns readers after a global - // `Lr16`/`Lr32` block, #200). A length that cannot be computed keeps the even default. - // A global block's length is the exact data length and its padding to 4 follows the block: - // readers that check that length exactly (Unity's PSD Importer) reject it otherwise (#4654). - if matches!(placement, LayerInfoPlacement::GlobalBlock { .. }) { - info.padding = Some(Vec::new()); - } else if info.pad_to(version, 4).is_err() { - info.padding = None; - } - } - // 32-bit files carry Photoshop's HDR toning records as Color Mode Data; Photoshop will not - // open a 32-bit file without them (#291). - let color_mode_data = match duotone_inks { - Some(raw) => raw, - None => photocraft_psd::hdr::color_mode_data_for_depth(header.depth), - }; - let file = PsdFile { - header, - color_mode_data, - resources, - layer_info, - layer_info_placement: placement, - global_layer_mask: (has_layers || !global_blocks.is_empty()).then(GlobalLayerMask::default), - global_blocks, - layer_mask_trailing: Vec::new(), - image_data, - }; - (file, ex.warnings) -} - -/// PSD mask parameters for a user mask's and a vector mask's (density, feather); `None` when -/// every value is the default (density 1, feather 0). -fn mask_parameters(user: Option<(f32, f32)>, vector: Option<(f32, f32)>) -> Option { - let density = |v: Option<(f32, f32)>| v.and_then(|(d, _)| (d < 1.0).then(|| q255(d))); - let feather = |v: Option<(f32, f32)>| v.and_then(|(_, f)| (f.is_finite() && f > 0.0).then_some(f64::from(f))); - let p = - MaskParameters { flags: 0, user_density: density(user), user_feather: feather(user), vector_density: density(vector), vector_feather: feather(vector) }; - let flags = u8::from(p.user_density.is_some()) - | u8::from(p.user_feather.is_some()) << 1 - | u8::from(p.vector_density.is_some()) << 2 - | u8::from(p.vector_feather.is_some()) << 3; - (flags != 0).then_some(MaskParameters { flags, ..p }) -} - #[cfg(test)] -mod tests { - use super::*; - - fn document(width: u32, height: u32) -> Document { - Document::new("size estimate", photocraft_geom::Size::new(width, height), ColorMode::Rgb, SampleType::U8) - } - - /// Photoshop opens a PSD's bottom layer as its Background only when that layer has no - /// transparency channel (measured on Photoshop 27.11: with the channel written, re-exported - /// files reopened with the Background as an ordinary layer). - #[test] - fn a_background_is_written_without_a_transparency_channel() { - use photocraft_color::Color; - let size = photocraft_geom::Size::new(8, 6); - let mut doc = Document::with_background("bg", size, ColorMode::Rgb, SampleType::U8, Color::rgb(0.2, 0.4, 0.6)); - doc.layers.push(Layer::raster("Layer 1", doc.pixel_format())); - let file = document_to_psd(&doc); - let layers = &file.layer_info.as_ref().unwrap().layers; - let ids = |i: usize| layers[i].channels.iter().map(|c| c.id).collect::>(); - assert_eq!(ids(0), vec![0, 1, 2], "the Background has no -1 channel"); - assert_eq!(layers[0].flags.0, LayerFlags::BIT4_USEFUL | LayerFlags::TRANSPARENCY_PROTECTED, "as Photoshop writes it"); - assert!(ids(1).contains(&-1), "other layers keep their transparency"); - // It comes back as the same locked, opaque Background. - let back = crate::import("bg.psd", &file.to_bytes().unwrap()).unwrap().document; - let bg = &back.layers[0]; - assert!(bg.locks.transparency && bg.locks.position, "{:?}", bg.locks); - assert_eq!(bg.surface().unwrap().read_region(back.bounds()), doc.layers[0].surface().unwrap().read_region(doc.bounds())); - // A bottom layer with transparency (or unlocked) is not a Background. - let mut holey = doc.clone(); - holey.layers[0].surface_mut().unwrap().write_pixel(2, 2, &[0.0, 0.0, 0.0, 0.0]); - assert!(document_to_psd(&holey).layer_info.unwrap().layers[0].channels.iter().any(|c| c.id == -1)); - let mut unlocked = doc.clone(); - unlocked.layers[0].locks.position = false; - assert!(document_to_psd(&unlocked).layer_info.unwrap().layers[0].channels.iter().any(|c| c.id == -1)); - } - - /// A flat 1-bit Bitmap file (no layers) opens in Photoshop as its Background; so does it in - /// PhotoCraft, and it is written back as one (no transparency channel). - #[test] - fn a_flat_bitmap_file_opens_and_saves_as_a_background() { - let file = photocraft_psd::testgen::merged_only(Version::Psd, PsdMode::Bitmap, 1, Compression::Raw, 8, 4); - let doc = crate::import("flat.psd", &file.to_bytes().unwrap()).unwrap().document; - let bg = &doc.layers[0]; - assert!(bg.name == "Background" && bg.locks.transparency && bg.locks.position, "{:?}", bg.locks); - // Bitmap has no layers in Photoshop (#4814): the file is saved flat in Bitmap mode, without - // a layer section, and opens as a Background again. - let out = document_to_psd(&doc); - assert_eq!(out.header.color_mode, PsdMode::Bitmap); - assert!(out.layer_info.as_ref().is_none_or(|li| li.layers.is_empty())); - let back = crate::import("flat.psd", &out.to_bytes().unwrap()).unwrap().document; - let bg = &back.layers[0]; - assert!(back.layers.len() == 1 && bg.name == "Background" && bg.locks.transparency && bg.locks.position, "{:?}", bg.locks); - } - - /// A layered document with a spot and an alpha channel. Each channel holds 100 %, 25 %, 75 % - /// and 0 % in four columns, the layout of the Photoshop spot oracles. - fn spot_and_alpha_document() -> Document { - let mut doc = document(4, 1); - doc.layers.push(Layer::group("Group", vec![Layer::raster("Layer 1", doc.pixel_format())])); - let channel = |name: &str| { - let mut s = Surface::new(PixelFormat::GRAY8); - s.write_interleaved(doc.bounds(), &[255, 64, 191, 0]); - photocraft_doc::AlphaChannel::new(name, s) - }; - let mut spot = channel("Spot Color 1"); - spot.spot = Some((photocraft_doc::Color::rgb(0.0, 0.6, 1.0), 0.0)); - let alpha = channel("Alpha 1"); - doc.channels.extend([spot, alpha]); - doc - } - - /// The extra planes after the colour channels (and the merged transparency) of `file`. - fn extra_planes(file: &PsdFile, count: usize) -> Vec { - let planes = file.decode_merged().unwrap(); - let plane = (file.header.width * file.header.height) as usize * usize::from(file.header.depth / 8); - planes[planes.len() - count * plane..].to_vec() - } - - /// Resource 1053's identifiers. - fn alpha_ids(file: &PsdFile) -> Option> { - file.resource(crate::channel_map::ALPHA_IDENTIFIERS).map(|r| r.data.as_chunks::<4>().0.iter().map(|c| u32::from_be_bytes(*c)).collect()) - } - - /// A PSD stores spot ink as Photoshop's own PSDs do (0 = solid ink: the 100, 25, 75 and 0 % - /// columns are 0, 191, 64, 255) and an alpha channel straight (255 = selected). The global - /// layer mask stays empty and flag bit 3 stays on the layers only, not on the group's closing - /// divider: Photoshop opens those as they are, and 509 of the corpus's 721 Photoshop PSDs have - /// an empty mask too. Opening the file gives the same ink back. - #[test] - fn psd_stores_spot_ink_as_photoshop_does() { - let doc = spot_and_alpha_document(); - let file = PsdFile::from_bytes(&document_to_psd(&doc).to_bytes().unwrap()).unwrap(); - assert_eq!(extra_planes(&file, 2), [0, 191, 64, 255, 255, 64, 191, 0], "spot, then alpha"); - assert_eq!(file.global_layer_mask.as_ref().map(|m| m.data.len()), Some(0)); - let flags: Vec = file.layers().iter().map(|l| l.flags.0 & LayerFlags::BIT4_USEFUL).collect(); - assert_eq!(flags, [0, LayerFlags::BIT4_USEFUL, LayerFlags::BIT4_USEFUL], "closing divider, layer, group"); - let back = crate::import("spot.psd", &file.to_bytes().unwrap()).unwrap().document; - assert!(back.channels[0].spot.is_some() && back.channels[1].spot.is_none()); - for c in &back.channels { - assert_eq!(c.surface.to_interleaved(back.bounds()), [255, 64, 191, 0], "{}", c.name); - } - } - - /// Resource 1053 numbers the extra channels as Photoshop 27.11 does in a new document: 3, 4, 5 - /// in every colour mode, after 0 for the merged transparency when there is one (its - /// transparent PSD lists `0, 3, 4, 5`). A Quick Mask is an extra channel too. Without extra - /// channels there is none. - #[test] - fn psd_alpha_identifiers_number_the_channels_as_photoshop_does() { - use photocraft_color::Color; - let size = photocraft_geom::Size::new(4, 1); - for mode in [ColorMode::Rgb, ColorMode::Cmyk, ColorMode::Grayscale, ColorMode::Lab] { - let mut doc = Document::with_background("bg", size, mode, SampleType::U8, Color::rgb(1.0, 1.0, 1.0)); - assert_eq!(alpha_ids(&document_to_psd(&doc)), None, "{mode:?} without channels"); - doc.channels = spot_and_alpha_document().channels; - let file = document_to_psd(&doc); - assert!(!file.merged_has_alpha(), "{mode:?}"); - assert_eq!(alpha_ids(&file), Some(vec![3, 4]), "{mode:?}"); - doc.quick_mask = Some(photocraft_doc::AlphaChannel::new("Quick Mask", Surface::new(PixelFormat::GRAY8))); - assert_eq!(alpha_ids(&document_to_psd(&doc)), Some(vec![3, 4, 5]), "{mode:?} with a Quick Mask"); - } - // The empty layer leaves the composite transparent. - let file = document_to_psd(&spot_and_alpha_document()); - assert!(file.merged_has_alpha()); - assert_eq!(alpha_ids(&file), Some(vec![0, 3, 4])); - } - - /// A save writes one fresh 1053 for the channels the document has. A Photoshop file's own is - /// not kept on open (it would be new metadata after every round trip), and one a document - /// carries anyway (kept by an earlier version) is never written: next to the fresh one it - /// would be a second, and without channels it would list channels that are gone. The - /// identifiers here, 3 and 2, are those of psd-tools' `cmyk-alpha-spot.psd` (Photoshop 24.7). - #[test] - fn a_kept_alpha_identifiers_resource_is_not_written() { - let kept = || (crate::channel_map::ALPHA_IDENTIFIERS, String::new(), std::sync::Arc::new([0, 0, 0, 3, 0, 0, 0, 2].to_vec())); - let mut file = document_to_psd(&spot_and_alpha_document()); - file.resources.retain(|r| r.id != crate::channel_map::ALPHA_IDENTIFIERS); - file.resources.push(ImageResource::new(kept().0, kept().2.to_vec())); - let mut opened = crate::import("ps.psd", &file.to_bytes().unwrap()).unwrap().document; - assert!(!opened.metadata.psd_resources.iter().any(|(id, ..)| *id == crate::channel_map::ALPHA_IDENTIFIERS)); - opened.metadata.psd_resources.push(kept()); - let again = PsdFile::from_bytes(&crate::export(&opened, "x.psd", &crate::ExportOptions::default()).unwrap().bytes).unwrap(); - assert_eq!(again.resources.iter().filter(|r| r.id == crate::channel_map::ALPHA_IDENTIFIERS).count(), 1); - assert_eq!(alpha_ids(&again), Some(vec![0, 3, 4])); - opened.channels.clear(); - assert_eq!(alpha_ids(&document_to_psd(&opened)), None, "no channels left"); - } - - #[test] - fn group_divider_id_wraps_without_colliding_with_imported_layer_ids() { - let mut doc = document(8, 8); - let mut group = Layer::group("Imported group", vec![Layer::raster("Child", doc.pixel_format())]); - group.psd_id = Some(u32::MAX); - doc.layers.push(group); - - let file = document_to_psd(&doc); - let ids: Vec = file.layers().iter().filter_map(|layer| layer.layer_id()).collect(); - let unique: std::collections::HashSet = ids.iter().copied().collect(); - assert_eq!(ids.len(), 3, "group, child and closing divider"); - assert_eq!(unique.len(), ids.len(), "no generated ID may collide"); - assert!(unique.contains(&u32::MAX), "preserve the imported group ID"); - assert!(unique.contains(&1), "reuse the first unused positive ID on wrap"); - - let encoded = file.to_bytes().unwrap(); - let parsed = PsdFile::from_bytes(&encoded).unwrap(); - let reloaded_ids: std::collections::HashSet = parsed.layers().iter().filter_map(|layer| layer.layer_id()).collect(); - assert_eq!(unique, reloaded_ids); - } - - /// #5068: Photoshop won't open a file whose `Lr32` comes before the `Mt32` marker it keeps for - /// a 32-bit document's merged transparency (verified in Photoshop 2026 on psd-tools' - /// `transparentbg.psd` re-saved both ways). The layer block follows a kept marker. - #[test] - fn layer_block_follows_a_kept_merged_transparency_marker() { - for (depth, key, marker) in [ - (SampleType::F32, *b"Lr32", *b"Mt32"), - (SampleType::U16, *b"Lr16", *b"Mt16"), - (SampleType::F32, *b"Lr32", *b"Mtrn"), - (SampleType::F32, *b"Lr32", *b"MTrn"), - ] { - let mut doc = Document::new("t", photocraft_geom::Size::new(8, 6), ColorMode::Rgb, depth); - let mut s = Surface::new(doc.pixel_format()); - s.fill_rect(photocraft_geom::Rect::new(1, 1, 5, 4), &[0.5, 0.2, 0.9, 1.0]); - doc.layers.push(Layer::new("Layer 1", LayerContent::Raster(s))); - doc.metadata.psd_global_blocks = vec![(*b"8BIM", *b"Patt", std::sync::Arc::new(Vec::new())), (*b"8BIM", marker, std::sync::Arc::new(Vec::new()))]; - let saved = PsdFile::from_bytes(&document_to_psd(&doc).to_bytes().unwrap()).unwrap(); - let LayerInfoPlacement::GlobalBlock { index, key: written, .. } = saved.layer_info_placement else { panic!("{depth:?}: a global layer block") }; - assert_eq!(written, key); - let at = saved.global_blocks.iter().position(|b| b.key == marker).expect("the marker is kept"); - assert!(at < index, "{depth:?}: {marker:?} at {at}, the layer block at {index}"); - } - // Without a marker the layer block stays first. - let mut doc = Document::new("t", photocraft_geom::Size::new(8, 6), ColorMode::Rgb, SampleType::F32); - doc.layers.push(Layer::new("Layer 1", LayerContent::Raster(Surface::new(doc.pixel_format())))); - doc.metadata.psd_global_blocks = vec![(*b"8BIM", *b"Patt", std::sync::Arc::new(Vec::new()))]; - let saved = PsdFile::from_bytes(&document_to_psd(&doc).to_bytes().unwrap()).unwrap(); - assert!(matches!(saved.layer_info_placement, LayerInfoPlacement::GlobalBlock { index: 0, .. })); - } - - /// A merged-transparency marker kept from the opened file describes that file's composite. - /// Saved with an opaque composite, it would make the first alpha channel read back as the - /// merged transparency, and the channel would be gone: the save drops it. - #[test] - fn an_opaque_save_drops_a_kept_merged_transparency_marker() { - for (depth, marker) in [(SampleType::U8, *b"MTrn"), (SampleType::U8, *b"Mtrn"), (SampleType::U16, *b"Mt16"), (SampleType::F32, *b"Mt32")] { - let case = format!("{depth:?} {}", String::from_utf8_lossy(&marker)); - let mut doc = Document::new("t", photocraft_geom::Size::new(8, 6), ColorMode::Rgb, depth); - let mut s = Surface::new(doc.pixel_format()); - s.fill_rect(photocraft_geom::Rect::new(0, 0, 8, 6), &[0.5, 0.2, 0.9, 1.0]); - doc.layers.push(Layer::new("Layer 1", LayerContent::Raster(s))); - doc.channels.push(photocraft_doc::AlphaChannel::new("Alpha 1", Surface::new(PixelFormat::GRAY8))); - doc.metadata.psd_global_blocks = vec![(*b"8BIM", marker, std::sync::Arc::new(Vec::new()))]; - let file = document_to_psd(&doc); - assert!(!file.global_blocks.iter().any(TaggedBlock::is_merged_transparency_marker), "{case}"); - assert!(!file.merged_has_alpha(), "{case}"); - let back = crate::import("a.psd", &file.to_bytes().unwrap()).unwrap().document; - let names: Vec<&str> = back.channels.iter().map(|c| c.name.as_str()).collect(); - assert_eq!(names, ["Alpha 1"], "{case}"); - } - } - - #[test] - fn unreadable_lr16_warns_on_import_and_is_not_saved_twice() { - // #2700: a 16-bit file whose Lr16 block claims five layers but holds none. - let mut file = photocraft_psd::testgen::merged_only(Version::Psd, PsdMode::Rgb, 16, Compression::Raw, 8, 6); - file.global_layer_mask = Some(GlobalLayerMask::default()); - file.global_blocks.push(TaggedBlock::new(*b"Lr16", vec![0, 5, 0, 0])); - let imported = crate::import("broken.psd", &file.to_bytes().unwrap()).unwrap(); - assert!(imported.warnings.iter().any(|w| w.contains("Lr16") && w.contains("could not be read")), "{:?}", imported.warnings); - - let saved = PsdFile::from_bytes(&document_to_psd(&imported.document).to_bytes().unwrap()).unwrap(); - let ours = matches!(saved.layer_info_placement, LayerInfoPlacement::GlobalBlock { key, .. } if key == *b"Lr16"); - let kept = saved.global_blocks.iter().filter(|b| b.key == *b"Lr16").count(); - assert_eq!((ours, kept), (true, 0), "exactly one Lr16 block: the document's own layers"); - assert_eq!(saved.layers().len(), 1); - } - - #[test] - fn photo_filter_psd_is_four_byte_aligned_and_round_trips() { - let color = [60000u16, 30000, 0].map(|x| x as f32 / 65535.0); - let adjustment = photocraft_doc::Adjustment::PhotoFilter { color, density: 0.14, preserve_luminosity: true }; - let mut doc = - Document::with_background("Photo Filter PSD", photocraft_geom::Size::new(32, 24), ColorMode::Rgb, SampleType::U8, photocraft_doc::Color::WHITE); - let mut layer = Layer::new("Warming Filter", LayerContent::Adjustment(adjustment.clone())); - doc.layers.push(layer.clone()); - - let assert_phfl = |file: &PsdFile| { - let records = &file.layer_info.as_ref().unwrap().layers; - let data = - records.iter().flat_map(|r| r.blocks.iter()).find(|b| b.key == *b"phfl").map(|b| b.data.as_slice()).expect("Photo Filter adjustment data"); - assert_eq!(data.len(), 20, "PSD layer block length includes four-byte padding"); - assert_eq!(&data[0..2], &[0, 2], "version 2 RGB Photo Filter"); - assert_eq!(&data[17..], &[0, 0, 0], "three padding bytes after the 17-byte payload"); - }; - - let exported = document_to_psd(&doc); - assert_phfl(&exported); - let encoded = exported.to_bytes().unwrap(); - let parsed = PsdFile::from_bytes(&encoded).unwrap(); - assert_phfl(&parsed); - let (restored, _) = crate::psd_import::psd_to_document(&parsed); - assert!(restored.layers.iter().any(|l| l.content == LayerContent::Adjustment(adjustment.clone()))); - - // Importing a legacy 18-byte block must still work; saving it again should repair it - // even when the adjustment values have not changed (normally raw blocks are reused). - let mut legacy = crate::adjust_map::write(&adjustment)[0].1.clone(); - legacy.truncate(18); - layer.psd_blocks = vec![(*b"phfl", std::sync::Arc::new(legacy))]; - doc.layers.pop(); - doc.layers.push(layer); - let repaired = document_to_psd(&doc); - assert_phfl(&repaired); - let repaired_bytes = repaired.to_bytes().unwrap(); - assert_phfl(&PsdFile::from_bytes(&repaired_bytes).unwrap()); - } - - #[test] - fn photo_filter_version_3_is_kept_until_edited() { - // The #3777 block (Photoshop CS2, XYZ colour): saved back byte-exact while unchanged. - let v3 = vec![0, 3, 0, 0, 0x5e, 0x7f, 0, 0, 0x61, 0xaa, 0, 0, 0x0e, 0xf3, 0, 0, 0, 0x3f, 1, 0]; - let adjustment = crate::adjust_map::parse(b"phfl", &v3, None, crate::adjust_map::Channels::Rgb); - let photocraft_doc::Adjustment::PhotoFilter { color, .. } = adjustment else { panic!("{adjustment:?}") }; - let mut doc = - Document::with_background("Photo Filter v3", photocraft_geom::Size::new(8, 8), ColorMode::Rgb, SampleType::U8, photocraft_doc::Color::WHITE); - let mut layer = Layer::new("Photo Filter 1", LayerContent::Adjustment(adjustment.clone())); - layer.psd_blocks = vec![(*b"phfl", std::sync::Arc::new(v3.clone()))]; - doc.layers.push(layer); - let phfl = |doc: &Document| { - let file = PsdFile::from_bytes(&document_to_psd(doc).to_bytes().unwrap()).unwrap(); - let records = &file.layer_info.as_ref().unwrap().layers; - records.iter().flat_map(|r| r.blocks.iter()).find(|b| b.key == *b"phfl").map(|b| b.data.clone()).expect("Photo Filter adjustment data") - }; - assert_eq!(phfl(&doc), v3); - // Once edited it is written as version 2 (RGB), and the colour survives. - let edited = photocraft_doc::Adjustment::PhotoFilter { color, density: 0.5, preserve_luminosity: true }; - if let Some(l) = doc.layers.last_mut() { - l.content = LayerContent::Adjustment(edited.clone()); - } - let saved = phfl(&doc); - assert_eq!(&saved[..2], &[0, 2]); - let reread = crate::adjust_map::parse(b"phfl", &saved, None, crate::adjust_map::Channels::Rgb); - let photocraft_doc::Adjustment::PhotoFilter { color: back, density, .. } = reread else { panic!("{reread:?}") }; - assert!(back.iter().zip(color).all(|(b, c)| (b - c).abs() <= 1.0 / 65535.0), "{back:?} vs {color:?}"); - assert_eq!(density, 0.5); - } - - #[test] - fn light_adjustment_is_kept_verbatim_and_warned() { - // #6542: Photoshop 2026's Light layer is a `brit` block whose `CgEd` descriptor carries - // more than Brightness/Contrast. Synthetic block: the extra key names are placeholders. - use photocraft_psd::descriptor::{Descriptor, Value, VersionedDescriptor}; - let brit = vec![0, 0, 0xff, 0xfe, 0, 127, 0, 0]; - let d = Descriptor::new("null") - .with("Vrsn", Value::Integer(1)) - .with("Brgh", Value::Integer(0)) - .with("Cntr", Value::Integer(-2)) - .with("Exps", Value::Double(-2.3)) - .with("Hghl", Value::Integer(-64)) - .with("useLegacy", Value::Boolean(false)); - let cged = VersionedDescriptor::new(d).to_bytes(); - let adjustment = crate::adjust_map::parse(b"brit", &brit, Some(&cged), crate::adjust_map::Channels::Rgb); - assert_eq!(adjustment, photocraft_doc::Adjustment::Unsupported { psd_key: "brit".into(), raw: brit.clone().into() }); - let mut doc = Document::with_background("Light", photocraft_geom::Size::new(8, 8), ColorMode::Rgb, SampleType::U8, photocraft_doc::Color::WHITE); - let mut layer = Layer::new("Light 1", LayerContent::Adjustment(adjustment)); - layer.psd_blocks = vec![(*b"brit", std::sync::Arc::new(brit.clone())), (*b"CgEd", std::sync::Arc::new(cged.clone()))]; - doc.layers.push(layer); - let block = |file: &PsdFile, key: &[u8; 4]| { - let records = &file.layer_info.as_ref().unwrap().layers; - records.iter().flat_map(|r| r.blocks.iter()).find(|b| b.key == *key).map(|b| b.data.clone()) - }; - let file = PsdFile::from_bytes(&document_to_psd(&doc).to_bytes().unwrap()).unwrap(); - let (restored, warnings) = crate::psd_import::psd_to_document(&file); - assert!(warnings.iter().any(|w| w.contains("\"Light 1\"") && w.contains("Light settings")), "{warnings:?}"); - // Saved again unchanged, both blocks are written back byte for byte. - let again = PsdFile::from_bytes(&document_to_psd(&restored).to_bytes().unwrap()).unwrap(); - assert_eq!(block(&again, b"brit").as_deref(), Some(&brit[..])); - assert_eq!(block(&again, b"CgEd").as_deref(), Some(&cged[..])); - // A plain Brightness/Contrast descriptor still reads as Brightness/Contrast. - let plain = crate::adjust_map::write(&photocraft_doc::Adjustment::BrightnessContrast { brightness: 5.0, contrast: -2.0, legacy: false }); - assert!(!crate::adjust_map::is_extended_brit(Some(&plain[1].1))); - } - - #[test] - fn size_limit_boundary_keeps_limit_and_switches_above_it() { - assert!(!exceeds_psd_size_limit(Some(PSD_MAX_FILE_SIZE))); - assert!(exceeds_psd_size_limit(Some(PSD_MAX_FILE_SIZE + 1))); - assert!(exceeds_psd_size_limit(None)); - } - - #[test] - fn encoded_size_estimator_rejects_arithmetic_overflow() { - assert_eq!(estimate_encoded_size(u64::MAX, 0, 0), None); - assert_eq!(estimate_encoded_size(0, u64::MAX, 0), None); - assert_eq!(estimate_encoded_size(0, 0, u64::MAX), Some(u64::MAX)); - assert!(exceeds_psd_size_limit(estimate_psd_size(&document(u32::MAX, u32::MAX)))); - } - - #[test] - fn large_encoded_size_selects_psb_without_changing_explicit_choice() { - let large = document(30_000, 30_000); - assert!(estimate_psd_size(&large).is_some_and(|size| size > PSD_MAX_FILE_SIZE)); - let large_size_exceeds_limit = psd_size_exceeds_limit(&large); - assert_eq!(psd_version(&large, false, large_size_exceeds_limit), Version::Psb); - - let small = document(1, 1); - let small_size_exceeds_limit = psd_size_exceeds_limit(&small); - assert_eq!(psd_version(&small, false, small_size_exceeds_limit), Version::Psd); - assert_eq!(psd_version(&small, true, small_size_exceeds_limit), Version::Psb); - } - #[test] - fn kept_psb_blocks_are_written_as_8bim_in_a_psd() { - // Photoshop 27.11 refuses a PSD holding `8B64` blocks ("not compatible with this - // version"); they came from re-saving a PSB as PSD with its global FMsk and cinf kept. - let mut doc = document(4, 4); - doc.metadata.psd_global_blocks = vec![ - (*b"8B64", *b"FMsk", std::sync::Arc::new(vec![0xff, 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, 50])), - (*b"8BIM", *b"Patt", std::sync::Arc::new(Vec::new())), - ]; - let signatures = |force_psb| { - let opts = PsdExportOptions { force_psb, ..PsdExportOptions::default() }; - let bytes = document_to_psd_with(&doc, &opts).0.to_bytes().unwrap(); - let file = PsdFile::from_bytes(&bytes).unwrap(); - file.global_blocks.iter().map(|b| (b.signature, b.key)).collect::>() - }; - assert_eq!(signatures(false), vec![(*b"8BIM", *b"FMsk"), (*b"8BIM", *b"Patt")]); - assert_eq!(signatures(true), vec![(*b"8B64", *b"FMsk"), (*b"8BIM", *b"Patt")], "a PSB keeps 8B64"); - } - - /// A PSB writes every global block with an 8-byte length as `8B64`, the way Photoshop does: - /// kept from a PSD source, `lnk2`, `pths` and `cinf` arrive as `8BIM`, and with that signature - /// and the PSB's 8-byte length Photoshop 27.11 refused the whole file (#7937). Blocks with a - /// 4-byte length keep `8BIM`, and a PSD keeps `8BIM` throughout. - #[test] - fn psb_writes_long_length_blocks_as_8b64() { - let mut doc = document(4, 4); - doc.metadata.psd_global_blocks = vec![ - (*b"8BIM", *b"cinf", std::sync::Arc::new(vec![0, 0, 0, 16, 0, 0, 0, 0])), - (*b"8BIM", *b"pths", std::sync::Arc::new(vec![0, 0, 0, 16, 0, 0, 0, 0])), - (*b"8BIM", *b"Patt", std::sync::Arc::new(Vec::new())), - ]; - let written = |force_psb| { - let opts = PsdExportOptions { force_psb, ..PsdExportOptions::default() }; - let bytes = document_to_psd_with(&doc, &opts).0.to_bytes().unwrap(); - let file = PsdFile::from_bytes(&bytes).unwrap(); - let blocks = file.global_blocks.iter().map(|b| (b.signature, b.key, b.data.len())).collect::>(); - (bytes, blocks) - }; - let (bytes, blocks) = written(true); - assert_eq!(blocks, vec![(*b"8B64", *b"cinf", 8), (*b"8B64", *b"pths", 8), (*b"8BIM", *b"Patt", 0)]); - // On disk: the signature, the key, then the 8-byte length. - let at = bytes.windows(8).position(|w| w == b"8B64cinf").expect("8B64cinf in the file"); - assert_eq!(bytes.get(at + 8..at + 16), Some(&[0u8, 0, 0, 0, 0, 0, 0, 8][..])); - assert!(!bytes.windows(8).any(|w| w == b"8BIMcinf" || w == b"8BIMpths")); - let (_, blocks) = written(false); - assert_eq!(blocks, vec![(*b"8BIM", *b"cinf", 8), (*b"8BIM", *b"pths", 8), (*b"8BIM", *b"Patt", 0)], "a PSD keeps 8BIM"); - } - - /// A layered document with transparency in the merged image and an alpha channel: the name - /// and DisplayInfo resources hold one entry per extra channel, the merged transparency first, - /// as in every file Photoshop opens (one short, Photoshop 27.11 refused the file with "Could - /// not import the clipboard because an unexpected end-of-file was encountered"). The alpha - /// channel keeps its own name and options on the way back. - #[test] - fn alpha_names_count_the_merged_transparency() { - let mut doc = document(8, 6); - let mut layer = Layer::raster("Layer 1", doc.pixel_format()); - layer.surface_mut().unwrap().write_pixel(1, 1, &[1.0, 0.0, 0.0, 1.0]); - doc.layers.push(layer); - let mut a = photocraft_doc::AlphaChannel::new("Alpha 1", photocraft_raster::Surface::new(PixelFormat::GRAY8)); - a.opacity = 0.5; - doc.channels.push(a); - let file = document_to_psd(&doc); - let header_extra = usize::from(file.header.channels) - 3; - let names = |id| file.resources.iter().find(|r| r.id == id).map(|r| r.data.clone()).unwrap(); - let pascal = names(1006); - let (mut count, mut i) = (0, 0); - while i < pascal.len() { - count += 1; - i += 1 + usize::from(pascal[i]); - } - assert_eq!((header_extra, count), (2, 2), "transparency + Alpha 1"); - assert_eq!(names(crate::channel_map::DISPLAY_INFO).len(), 4 + 2 * 13); - let back = crate::import("a.psd", &file.to_bytes().unwrap()).unwrap().document; - assert_eq!(back.channels.len(), 1); - assert_eq!(back.channels[0].name, "Alpha 1"); - assert!((back.channels[0].opacity - 0.5).abs() < 1e-6); - } -} +mod tests; diff --git a/crates/io/src/psd_export/document.rs b/crates/io/src/psd_export/document.rs new file mode 100644 index 0000000000..0ad7188a58 --- /dev/null +++ b/crates/io/src/psd_export/document.rs @@ -0,0 +1,391 @@ +use super::estimate::{MERGED_RENDERED, MERGED_WEIGHT, block_signature, psd_size_exceeds_limit, psd_version}; +use super::merged::{cmyk_of, merged_planes, placeholder_planes}; +use super::resources::{global_block, guides_resource, keep_imported_resource, legacy_name, pascal_names_resource, path_resources, unicode_names_resource}; +use super::smart::{SmartOut, link_group_resource}; +use super::*; + +/// Converts a document to a PSD file model (see [`document_to_psd_with`]). +pub fn document_to_psd(doc: &Document) -> PsdFile { + document_to_psd_with(doc, &PsdExportOptions::default()).0 +} + +/// Converts a document to a PSD/PSB file model, returning warnings about +/// anything that could not be represented. The merged composite is rendered +/// with `photocraft_compose::flatten`. +pub fn document_to_psd_with(doc: &Document, opts: &PsdExportOptions) -> (PsdFile, Vec) { + document_to_psd_nested(doc, opts, 0, &Interrupt::NONE) +} + +/// [`document_to_psd_with`] for a background save (#3389): reports progress through `ctl` after +/// each layer record and each band of the merged composite. Once `ctl` is cancelled it stops +/// early and returns an **incomplete** model: callers check `ctl` and discard it. +pub(crate) fn document_to_psd_interruptible(doc: &Document, opts: &PsdExportOptions, ctl: &Interrupt) -> (PsdFile, Vec) { + document_to_psd_nested(doc, opts, 0, ctl) +} + +/// [`document_to_psd_with`] for a document embedded `depth` smart objects deep. +pub(super) fn document_to_psd_nested(doc: &Document, opts: &PsdExportOptions, depth: u32, ctl: &Interrupt) -> (PsdFile, Vec) { + if doc.mode == ColorMode::Multichannel { + return crate::multichannel_map::document_to_psd(doc, opts.force_psb); + } + if let Some(file) = crate::palette_map::document_to_psd(doc, opts.force_psb) { + return file; + } + let fmt = doc.pixel_format(); + // A Duotone is written over its grey plate with its inks: the block it was imported with, + // verbatim, while the inks are unedited, else one made from them (`duotone_map`). Photoshop + // has only 8-bit Duotone: it refuses to open a 16-bit one. + let duotone_inks: Option> = doc + .duotone + .as_ref() + .filter(|d| !d.inks.is_empty() && doc.mode == ColorMode::Duotone && fmt.mode == ColorMode::Grayscale && fmt.sample == SampleType::U8) + .map(|d| d.psd_raw.as_deref().map_or_else(|| crate::duotone_map::write(d), <[u8]>::to_vec)); + let sample = fmt.sample; + let cc = fmt.mode.color_channels(); + let big = doc.size.width > 30_000 || doc.size.height > 30_000; + let size_exceeds_limit = opts.size_limit_psb && !opts.force_psb && !big && psd_size_exceeds_limit(doc); + let version = psd_version(doc, opts.force_psb, size_exceeds_limit); + let mut ex = Ex { + fmt, + dpi: doc.resolution_dpi, + document: opts.document_path.clone(), + read_linked_files: opts.read_linked_files, + text_styles: doc.text_styles.clone(), + text_index: Default::default(), + mask_fmt: PixelFormat::new(ColorMode::Grayscale, sample, false), + cc, + cmyk: fmt.mode == ColorMode::Cmyk, + version, + next_id: 0, + used_ids: Default::default(), + layer_ids: Default::default(), + canvas: doc.bounds(), + records: Vec::new(), + warnings: Vec::new(), + guides: doc.guides.clone(), + comps: (!crate::comps_map::comps_unchanged(doc)).then(|| (doc.layer_comps.clone(), doc.last_document_state.clone())), + smart: SmartOut::new(doc, depth), + patterns: doc.patterns.clone(), + background: psd_background(doc), + }; + if big && !opts.force_psb { + ex.warnings.push("document exceeds 30000 px; written as PSB".into()); + } else if size_exceeds_limit && !opts.force_psb { + ex.warnings.push("estimated encoded size exceeds 2 GB; written as PSB".into()); + } + if fmt.mode != doc.mode && duotone_inks.is_none() { + ex.warnings.push(format!("{:?} document written as {:?}", doc.mode, fmt.mode)); + } + // Assign layer ids up front (stable across round trips): keep unique + // `psd_id`s, number the rest after them; dividers come after all. + { + let walk = doc.walk(); + let mut used = std::collections::HashSet::new(); + for (_, _, l) in &walk { + if let Some(id) = l.psd_id + && used.insert(id) + { + ex.layer_ids.insert(l.id, id); + } + } + let mut next = 1u32; + for (_, _, l) in &walk { + if let std::collections::hash_map::Entry::Vacant(e) = ex.layer_ids.entry(l.id) { + while used.contains(&next) { + next += 1; + } + used.insert(next); + e.insert(next); + } + } + ex.next_id = used.iter().copied().max().unwrap_or(0); + ex.used_ids = used; + // Text objects' number in the generated `Txt2` (#1348): a preserved `TySh` keeps the + // number it already names — its `Txt2` object must sit at that slot for `apply_txt2` — + // and new layers get numbers past every kept one and every object in the file's `Txt2`. + // Kept numbers are claimed first: a layer added below others must not take a number a + // layer above it keeps, or each of those would be renumbered onto its neighbour's object + // and take its style (#7773); nor may it land on a deleted layer's object. + let mut used_txt = std::collections::HashSet::new(); + ex.text_index = Default::default(); + let mut fresh = Vec::new(); + for (_, _, l) in &walk { + let LayerContent::Text(t) = &l.content else { + continue; + }; + match t.psd_raw.as_deref().and_then(|d| photocraft_text::psd::text_index(d)) { + Some(i) if used_txt.insert(i) => { + ex.text_index.insert(l.id, i); + } + _ => fresh.push(l.id), + } + } + let objects = + doc.metadata.psd_global_blocks.iter().find(|(_, key, _)| key == b"Txt2").map_or(0, |(_, _, d)| photocraft_text::psd::txt2_object_count(d)); + let mut next_txt = used_txt.iter().max().map_or(0, |m| m + 1).max(i32::try_from(objects).unwrap_or(i32::MAX)); + if next_txt.saturating_add(fresh.len() as i32) > photocraft_text::psd::MAX_TEXT_INDEX + 1 { + next_txt = 0; + } + for id in fresh { + while used_txt.contains(&next_txt) { + next_txt += 1; + } + used_txt.insert(next_txt); + ex.text_index.insert(id, next_txt); + } + } + // Progress: one unit per layer record, then the merged composite (#3389). + let records = doc.walk().len() as f32; + let units = records + MERGED_WEIGHT; + let layers_share = records / units; + let mut done = 0.0f32; + let mut tick = || { + done += 1.0; + ctl.progress(done / units); + !ctl.cancelled() + }; + let space = photocraft_compose::cmyk_space(doc); + photocraft_color::convert::with_cmyk_space(space.as_ref(), || ex.emit(&doc.layers, &mut tick)); + + // Without Maximize Compatibility the merged image is a white placeholder and the composite + // isn't rendered at all. A document without layer records keeps the real image: its pixels + // live nowhere else. So does a Duotone: it opens flattened from that image (its layer records + // are not read back). + let real_merged = opts.maximize_compatibility || ex.records.is_empty() || duotone_inks.is_some(); + let (mut planes, has_alpha) = if real_merged { + // Merged composite, rendered and encoded in bands (no full-size float composite). Matting + // against white only changes pixels with alpha < 1; if some are slightly translucent but + // all round to opaque (so no alpha channel is written), encode once more without the matte. + let merged_end = layers_share + (1.0 - layers_share) * MERGED_RENDERED; + let (mut planes, has_alpha, translucent) = + crate::with_span(ctl, layers_share, merged_end, |ctl| merged_planes(doc, &fmt, cmyk_of(&fmt), opts.merged_matte, ctl)); + if !has_alpha && translucent && opts.merged_matte { + planes = merged_planes(doc, &fmt, cmyk_of(&fmt), false, &Interrupt::cancel_only(&|| ctl.cancelled())).0; + } + (planes, has_alpha) + } else { + (placeholder_planes(doc, &fmt), false) + }; + let n = doc.size.area() as usize; + if !has_alpha { + planes.truncate(cc * n * sample.bytes()); + } + let canvas = doc.bounds(); + let max_extra = 56 - cc - usize::from(has_alpha); + if doc.channels.len() > max_extra { + ex.warnings.push(format!("only {max_extra} alpha channels fit in PSD; the rest were dropped")); + } + let mut extra: Vec<_> = doc.channels.iter().take(max_extra).collect(); + // Saved in Quick Mask mode: the mask is written as the last extra channel and flagged by + // resource 1022 (quick mask info: channel id, initially-empty flag), as Photoshop does. + let quick_mask_id = match &doc.quick_mask { + Some(q) if extra.len() < max_extra => { + extra.push(q); + Some((cc + usize::from(has_alpha) + extra.len() - 1) as u16) + } + Some(_) => { + ex.warnings.push("Quick Mask was dropped because the PSD channel limit was reached".into()); + None + } + None => None, + }; + for a in &extra { + let s = if a.surface.format() != ex.mask_fmt { a.surface.convert(ex.mask_fmt) } else { a.surface.clone() }; + let mut bytes = s.to_interleaved(canvas); + // Spot ink as Photoshop stores it (0 = solid); an alpha channel stays straight. + if a.spot.is_some() { + crate::channel_map::photoshop_spot_plane(&mut bytes, sample); + } + planes.extend(deinterleave(&bytes, 1, sample, &[false]).remove(0)); + } + let channels = (cc + usize::from(has_alpha) + extra.len()) as u16; + let mode = if duotone_inks.is_some() { PsdMode::Duotone } else { psd_mode(fmt.mode) }; + let header = Header::new(version, doc.size.width, doc.size.height, channels, psd_depth(sample), mode); + let mcomp = if sample == SampleType::F32 { Compression::Raw } else { opts.merged_compression }; + let image_data = ImageData::encode(mcomp, &planes, &header) + .or_else(|_| ImageData::encode(Compression::Raw, &planes, &header)) + .unwrap_or(ImageData { compression: Compression::Raw, data: planes }); + ctl.progress(1.0); + + // Resources. + let mut resources = vec![ + // hRes/vRes are always pixels per inch. The display unit written here is inches. + ImageResource::new(ids::RESOLUTION_INFO, ResolutionInfo::from_dpi(f64::from(doc.resolution_dpi)).to_bytes()), + ImageResource::new(ids::GLOBAL_ANGLE, (doc.global_light.angle.round() as i32).to_be_bytes().to_vec()), + ImageResource::new(ids::GLOBAL_ALTITUDE, (doc.global_light.altitude.round() as i32).to_be_bytes().to_vec()), + ]; + if let Some(icc) = &doc.icc_profile { + resources.push(ImageResource::new(ids::ICC_PROFILE, icc.to_vec())); + } + if !doc.guides.horizontal.is_empty() || !doc.guides.vertical.is_empty() { + resources.push(ImageResource::new(1032, guides_resource(doc))); + } + if !extra.is_empty() { + // One entry per extra channel, the merged transparency included (as in every file + // Photoshop opens; one short, Photoshop refuses the file with "unexpected end-of-file"). + let names: Vec<&str> = has_alpha.then_some("Transparency").into_iter().chain(extra.iter().map(|a| a.name.as_str())).collect(); + resources.push(ImageResource::new(1006, pascal_names_resource(&names))); + resources.push(ImageResource::new(1045, unicode_names_resource(&names))); + resources.push(ImageResource::new(crate::channel_map::DISPLAY_INFO, crate::channel_map::display_info(&extra, has_alpha))); + // Photoshop writes 1053 in every file with an extra channel. Its absence is how a file from + // an earlier PhotoCraft is told apart (`psd_import::earlier_photocraft_spot_planes`). + resources.push(ImageResource::new(crate::channel_map::ALPHA_IDENTIFIERS, crate::channel_map::alpha_identifiers(has_alpha, extra.len()))); + } + if let Some(id) = quick_mask_id { + let mut data = id.to_be_bytes().to_vec(); + data.push(0); + resources.push(ImageResource::new(crate::channel_map::QUICK_MASK_INFO, data)); + } + resources.extend(path_resources(doc, &mut ex.warnings)); + if let Some(groups) = link_group_resource(&doc.layers) { + resources.push(ImageResource::new(ids::LAYER_GROUP_INFO, groups)); + } + // The pixels are saved as they are shown: never let a reader rotate them again. The XMP and + // EXIF resolution follow the ResolutionInfo resource, so no copy contradicts it (#1691). + let ppi = Some((doc.resolution_dpi, doc.resolution_dpi)).filter(|d| d.0 > 0.0); + if let Some(x) = &doc.metadata.xmp { + resources.push(ImageResource::new(ids::XMP, photocraft_codecs::export_xmp(x, ppi).as_bytes().to_vec())); + } + if let Some(e) = &doc.metadata.exif { + resources.push(ImageResource::new(ids::EXIF, photocraft_codecs::export_exif(e, ppi).into_owned())); + } + let mut global_blocks = Vec::new(); + let preserved = ex.smart.finish(crate::annotations_map::export_blocks(doc, crate::pattern_map::export_global_blocks(doc))); + // The type layers' `Txt2` is regenerated (the auto-kern modes live there, and a preserved + // block goes stale as text is edited): one object per `TextIndex`, at the slot each layer's + // `TySh` names (unused slots stay empty; see `photocraft_text::psd::build_txt2`). The block + // it replaces is handed over so a kept object keeps everything the file held beyond its text + // and style runs (Photoshop's `/21 /1` glyph pen positions, …). + let text_layers: Vec<(i32, &photocraft_doc::TextLayer)> = doc + .walk() + .into_iter() + .filter_map(|(_, _, l)| match &l.content { + LayerContent::Text(t) => Some((ex.text_index.get(&l.id).copied().unwrap_or(0), t)), + _ => None, + }) + .collect(); + let previous = (!text_layers.is_empty()).then(|| preserved.iter().find(|(_, key, _)| key == b"Txt2").map(|(_, _, data)| data.to_vec())).flatten(); + // A fresh document of ordinary (Metrics) text has nothing to put in `Txt2`, and Photoshop never + // writes its empty `<< /0 << >> >>` stub — readers such as Photopea reject it (#3514). Keep the + // block when the file had one (round-trip its pen positions/extras) or a layer is Optical (the + // one mode EngineData can't carry; #1348). + let txt2 = (previous.is_some() || photocraft_text::psd::needs_txt2(&text_layers)) + .then(|| photocraft_text::psd::build_txt2_at(&text_layers, previous.as_deref(), ex.dpi)); + for (sig, key, data) in preserved { + if txt2.is_some() && key == *b"Txt2" { + continue; + } + // A kept layer block (one the import could not read, #2700) describes layers the + // document doesn't have. The document's own layers are written below, and a file holds + // one layer list: a second `Lr16`/`Lr32` would contradict it. + if !ex.records.is_empty() && matches!(&key, b"Lr16" | b"Lr32" | b"Layr") { + continue; + } + let block = global_block(block_signature(sig, key, version), key, &data); + // A kept merged-transparency marker describes the opened file's composite. Over an opaque + // one it would make the first alpha channel read back as the transparency, and vanish. + if !has_alpha && block.is_merged_transparency_marker() { + continue; + } + global_blocks.push(block); + } + if let Some(txt2) = txt2 { + let mut tb = TaggedBlock::new(*b"Txt2", txt2.clone()); + tb.signature = *b"8BIM"; + tb.padding = Some(vec![0; (4 - txt2.len() % 4) % 4]); + global_blocks.push(tb); + } + let comps_resource = ex.comps.is_some().then(|| crate::comps_map::write_comps_resource(doc)); + let (slices_resource, slices_warning) = crate::slices_map::export_resource(doc, &ex.layer_ids); + if let Some(warning) = slices_warning { + ex.warnings.push(warning); + } + for (id, name, data) in &doc.metadata.psd_resources { + // Layer comps: the preserved list while unchanged, else regenerated (or dropped) below. + if *id == crate::comps_map::LAYER_COMPS && comps_resource.is_some() { + continue; + } + // Slices: the preserved resource while unchanged, else regenerated (or dropped) below. + if *id == crate::slices_map::SLICES && slices_resource.is_some() { + continue; + } + if !keep_imported_resource(doc, *id, data) { + continue; + } + // 1053 is written afresh with the extra channels. A kept copy (from a Multichannel file, or + // a document saved by an earlier version) would be a second one, or list channels that + // are gone. + if *id == crate::channel_map::ALPHA_IDENTIFIERS { + continue; + } + let mut r = ImageResource::new(*id, data.to_vec()); + r.name = legacy_name(name); + resources.push(r); + } + if let Some(data) = crate::annotations_map::fresh_scale_resource(doc) { + resources.push(ImageResource::new(crate::annotations_map::MEASUREMENT_SCALE, data)); + } + if let Some(Some(data)) = comps_resource { + resources.push(ImageResource::new(crate::comps_map::LAYER_COMPS, data)); + } + if let Some(Some(data)) = slices_resource { + resources.push(ImageResource::new(crate::slices_map::SLICES, data)); + } + resources.push(version_info_resource(real_merged)); + + let has_layers = !ex.records.is_empty(); + // Photoshop writes a merged-transparency marker (`Mtrn`, `Mt16`, `Mt32`; `MTrn` in a TIFF) + // before the layer block, and won't open a file whose `Lr32` comes first (#5068): the layer + // block goes right after the last kept marker, else first. + let index = global_blocks.iter().rposition(TaggedBlock::is_merged_transparency_marker).map_or(0, |i| i + 1); + let placement = match (has_layers, sample) { + (true, SampleType::U16) => LayerInfoPlacement::GlobalBlock { index, signature: *b"8BIM", key: *b"Lr16", padding: None }, + (true, SampleType::F32) => LayerInfoPlacement::GlobalBlock { index, signature: *b"8BIM", key: *b"Lr32", padding: None }, + _ => LayerInfoPlacement::Section, + }; + let records = std::mem::take(&mut ex.records); + let mut layer_info = has_layers.then_some(LayerInfo { merged_alpha: has_alpha, layers: records, padding: None }); + if let Some(info) = &mut layer_info { + // Photoshop pads the layer info to 4 bytes (an even pad misaligns readers after a global + // `Lr16`/`Lr32` block, #200). A length that cannot be computed keeps the even default. + // A global block's length is the exact data length and its padding to 4 follows the block: + // readers that check that length exactly (Unity's PSD Importer) reject it otherwise (#4654). + if matches!(placement, LayerInfoPlacement::GlobalBlock { .. }) { + info.padding = Some(Vec::new()); + } else if info.pad_to(version, 4).is_err() { + info.padding = None; + } + } + // 32-bit files carry Photoshop's HDR toning records as Color Mode Data; Photoshop will not + // open a 32-bit file without them (#291). + let color_mode_data = match duotone_inks { + Some(raw) => raw, + None => photocraft_psd::hdr::color_mode_data_for_depth(header.depth), + }; + let file = PsdFile { + header, + color_mode_data, + resources, + layer_info, + layer_info_placement: placement, + global_layer_mask: (has_layers || !global_blocks.is_empty()).then(GlobalLayerMask::default), + global_blocks, + layer_mask_trailing: Vec::new(), + image_data, + }; + (file, ex.warnings) +} + +/// PSD mask parameters for a user mask's and a vector mask's (density, feather); `None` when +/// every value is the default (density 1, feather 0). +pub(super) fn mask_parameters(user: Option<(f32, f32)>, vector: Option<(f32, f32)>) -> Option { + let density = |v: Option<(f32, f32)>| v.and_then(|(d, _)| (d < 1.0).then(|| q255(d))); + let feather = |v: Option<(f32, f32)>| v.and_then(|(_, f)| (f.is_finite() && f > 0.0).then_some(f64::from(f))); + let p = + MaskParameters { flags: 0, user_density: density(user), user_feather: feather(user), vector_density: density(vector), vector_feather: feather(vector) }; + let flags = u8::from(p.user_density.is_some()) + | u8::from(p.user_feather.is_some()) << 1 + | u8::from(p.vector_density.is_some()) << 2 + | u8::from(p.vector_feather.is_some()) << 3; + (flags != 0).then_some(MaskParameters { flags, ..p }) +} diff --git a/crates/io/src/psd_export/estimate.rs b/crates/io/src/psd_export/estimate.rs new file mode 100644 index 0000000000..83c2388a1e --- /dev/null +++ b/crates/io/src/psd_export/estimate.rs @@ -0,0 +1,135 @@ +use super::*; + +/// How much of a PSD conversion the merged composite weighs, in layer records: rendering it +/// (all layers composited) and encoding its planes cost about two full-canvas layers. +pub(super) const MERGED_WEIGHT: f32 = 2.0; + +/// The part of the merged composite's share filled once its bands are rendered and converted; the +/// rest is compressing its planes. +pub(super) const MERGED_RENDERED: f32 = 0.8; + +/// Adds headroom for compressed channel streams and their per-row length tables. +pub(super) fn estimate_encoded_size(raw_bytes: u64, rows: u64, structural_bytes: u64) -> Option { + raw_bytes.checked_add(raw_bytes.checked_add(63)?.checked_div(64)?)?.checked_add(rows.checked_mul(8)?)?.checked_add(structural_bytes) +} + +fn add_plane_estimate(raw_bytes: &mut u64, rows: &mut u64, width: u64, height: u64, channels: u64, bytes_per_sample: u64) -> Option<()> { + let plane_bytes = width.checked_mul(height)?.checked_mul(channels)?.checked_mul(bytes_per_sample)?; + let plane_rows = height.checked_mul(channels)?; + *raw_bytes = raw_bytes.checked_add(plane_bytes)?; + *rows = rows.checked_add(plane_rows)?; + Some(()) +} + +pub(super) fn exceeds_psd_size_limit(estimated_size: Option) -> bool { + estimated_size.is_none_or(|size| size > PSD_MAX_FILE_SIZE) +} + +fn surface_dimensions(surface: &Surface) -> Option<(u64, u64)> { + let bounds = surface.content_bounds(); + Some((u64::from(bounds.width()), u64::from(bounds.height()))) +} + +pub(crate) fn estimate_psd_size(doc: &Document) -> Option { + let mut raw_bytes = 0; + let mut rows = 0; + let mut structural_bytes = PSD_ESTIMATE_FIXED_OVERHEAD; + + let width = u64::from(doc.size.width); + let height = u64::from(doc.size.height); + + if doc.mode == ColorMode::Multichannel { + let channels = u64::try_from(doc.channels.len().clamp(1, 56)).ok()?; + let sample_bytes = u64::try_from(if doc.depth == SampleType::F32 { SampleType::U16.bytes() } else { doc.depth.bytes() }).ok()?; + add_plane_estimate(&mut raw_bytes, &mut rows, width, height, channels, sample_bytes)?; + } else { + let format = doc.pixel_format(); + let color_channels = u64::try_from(format.mode.color_channels()).ok()?; + let bytes_per_sample = u64::try_from(format.sample.bytes()).ok()?; + let layer_channels = color_channels.checked_add(1)?; + + for (_, _, layer) in doc.walk() { + structural_bytes = structural_bytes.checked_add(PSD_ESTIMATE_LAYER_OVERHEAD)?.checked_add(u64::try_from(layer.name.len()).ok()?)?; + for (_, data) in &layer.psd_blocks { + structural_bytes = structural_bytes.checked_add(u64::try_from(data.len()).ok()?)?; + } + + let surface = match &layer.content { + LayerContent::Fill(fill) => { + let mut fill_width = width; + let mut fill_height = height; + if let Some(cache) = &layer.fill_cache + && cache.fill == *fill + { + let (cache_width, cache_height) = surface_dimensions(&cache.surface)?; + fill_width = fill_width.max(cache_width); + fill_height = fill_height.max(cache_height); + } + add_plane_estimate(&mut raw_bytes, &mut rows, fill_width, fill_height, layer_channels, bytes_per_sample)?; + None + } + _ => layer.surface(), + }; + if let Some(surface) = surface { + let (surface_width, surface_height) = surface_dimensions(surface)?; + add_plane_estimate(&mut raw_bytes, &mut rows, surface_width, surface_height, layer_channels, bytes_per_sample)?; + } + if let Some(mask) = &layer.mask { + let (mask_width, mask_height) = surface_dimensions(&mask.surface)?; + add_plane_estimate(&mut raw_bytes, &mut rows, mask_width, mask_height, 1, bytes_per_sample)?; + } + if let LayerContent::Smart(smart) = &layer.content + && let photocraft_doc::SmartSource::Embedded { bytes, .. } = &smart.source + { + structural_bytes = structural_bytes.checked_add(u64::try_from(bytes.len()).ok()?)?; + } + } + + let max_extra_channels = 56usize.saturating_sub(format.mode.color_channels() + 1); + let mut extra_channels = doc.channels.len().min(max_extra_channels); + if doc.quick_mask.is_some() && extra_channels < max_extra_channels { + extra_channels += 1; + } + let merged_channels = color_channels.checked_add(1)?.checked_add(u64::try_from(extra_channels).ok()?)?; + add_plane_estimate(&mut raw_bytes, &mut rows, width, height, merged_channels, bytes_per_sample)?; + for channel in doc.channels.iter().take(extra_channels) { + structural_bytes = structural_bytes.checked_add(u64::try_from(channel.name.len()).ok()?)?; + } + } + + structural_bytes = structural_bytes + .checked_add(u64::try_from(doc.icc_profile.as_ref().map_or(0, |profile| profile.len())).ok()?)? + .checked_add(u64::try_from(doc.metadata.xmp.as_deref().map_or(0, str::len)).ok()?)? + .checked_add(u64::try_from(doc.metadata.exif.as_ref().map_or(0, |data| data.len())).ok()?)?; + for (_, name, data) in &doc.metadata.psd_resources { + structural_bytes = structural_bytes.checked_add(u64::try_from(name.len()).ok()?)?.checked_add(u64::try_from(data.len()).ok()?)?; + } + for (_, _, data) in &doc.metadata.psd_global_blocks { + structural_bytes = structural_bytes.checked_add(u64::try_from(data.len()).ok()?)?; + } + + estimate_encoded_size(raw_bytes, rows, structural_bytes) +} + +/// The signature a kept tagged block is written with. `8B64` exists only in PSB files: a PSD +/// with an `8B64` block (kept from a PSB source, e.g. its global `FMsk` or `cinf`) is refused by +/// Photoshop as "not compatible with this version" (measured in Photoshop 27.11). The other way +/// round, a PSB block with an 8-byte length is `8B64`, as Photoshop writes it: an `8BIM` `lnk2`, +/// `pths` or `cinf` (kept from a PSD source, whose lengths the PSB widens) makes Photoshop read +/// the length as 4 bytes and refuse the whole file (#7937). +pub(crate) fn block_signature(sig: [u8; 4], key: [u8; 4], version: Version) -> [u8; 4] { + match version { + Version::Psd if sig == *b"8B64" => *b"8BIM", + Version::Psb if sig == *b"8BIM" && photocraft_psd::tagged::uses_long_length(version, &key) => *b"8B64", + _ => sig, + } +} + +pub(crate) fn psd_version(doc: &Document, force_psb: bool, size_exceeds_limit: bool) -> Version { + let exceeds_dimensions = doc.size.width > 30_000 || doc.size.height > 30_000; + if force_psb || exceeds_dimensions || size_exceeds_limit { Version::Psb } else { Version::Psd } +} + +pub(crate) fn psd_size_exceeds_limit(doc: &Document) -> bool { + exceeds_psd_size_limit(estimate_psd_size(doc)) +} diff --git a/crates/io/src/psd_export/merged.rs b/crates/io/src/psd_export/merged.rs new file mode 100644 index 0000000000..da3afe0597 --- /dev/null +++ b/crates/io/src/psd_export/merged.rs @@ -0,0 +1,143 @@ +use super::*; + +pub(super) fn cmyk_of(fmt: &PixelFormat) -> bool { + fmt.mode == ColorMode::Cmyk +} + +/// The merged image's planes (colour channels, then alpha), big-endian, matted against white +/// when `matte`; with whether any pixel needs the alpha channel and whether any is below 1. +/// `ctl` gets the fraction of rows done after each band; once it is cancelled the rest of the +/// image is left blank (the caller discards it). +pub(super) fn merged_planes(doc: &Document, fmt: &PixelFormat, cmyk: bool, matte: bool, ctl: &Interrupt) -> (Vec, bool, bool) { + if cmyk && let Some(planes) = merged_ink_planes(doc, fmt.sample, matte, ctl) { + return planes; + } + let sample = fmt.sample; + let cc = fmt.mode.color_channels(); + let bps = sample.bytes(); + let n = doc.size.area() as usize; + let plane = n * bps; + let mut planes = vec![0u8; plane * (cc + 1)]; + let (mut has_alpha, mut translucent) = (false, false); + let white = photocraft_raster::from_rgba(fmt, [1.0, 1.0, 1.0, 1.0]); + let canvas = doc.bounds(); + let w = canvas.width() as usize; + let space = photocraft_compose::cmyk_space(doc); + let lab16 = fmt.mode == ColorMode::Lab && sample == SampleType::U16; + let rows = canvas.height().max(1) as f32; + let _ = photocraft_compose::render_bands(doc, canvas, 0, |band| -> Result<(), ()> { + if ctl.cancelled() { + return Err(()); + } + // Retain alpha whenever it differs from opaque at the stored precision. + has_alpha |= band.px.iter().any(|p| match sample { + SampleType::U8 => q255(p[3]) < 255, + SampleType::U16 => (p[3].clamp(0.0, 1.0) * 65535.0 + 0.5) as u16 != u16::MAX, + SampleType::F32 => p[3] != 1.0, + }); + translucent |= band.px.iter().any(|p| p[3] < 1.0); + let start = (band.rect.y0 - canvas.y0) as usize * w; + // Converted and encoded on all cores, then copied into each plane. + let parts = crate::pixels::par_map(crate::pixels::bands(band.px.len()), |range| { + // The composite came through the document's CMYK profile: convert back through it too. + photocraft_color::convert::with_cmyk_space(space.as_ref(), || { + let mut out: Vec> = vec![Vec::with_capacity(range.len() * bps); cc + 1]; + let mut v = [0.0f32; 5]; + for p in &band.px[range.clone()] { + photocraft_raster::from_rgba_into(fmt, *p, &mut v); + for c in 0..=cc { + // Matte against white like Photoshop (see `pixels::matte`). + let m = if c < cc && matte { crate::pixels::matte(v[c], v[cc], white[c]) } else { v[c] }; + let x = if cmyk && c < cc { 1.0 - m } else { m }; + // 16-bit Lab a*/b* use Photoshop's 0..65280 scale (`pixels::lab16_chroma`). + let x = if lab16 && (c == 1 || c == 2) { x * (crate::pixels::LAB16_CHROMA_MAX / 65535.0) } else { x }; + encode_be(x, sample, &mut out[c]); + } + } + (range.start, out) + }) + }); + for (at, part) in parts { + for (c, src) in part.iter().enumerate() { + let o = c * plane + (start + at) * bps; + planes[o..o + src.len()].copy_from_slice(src); + } + } + ctl.progress((band.rect.y1 - canvas.y0) as f32 / rows); + Ok(()) + }); + (planes, has_alpha, translucent) +} + +/// [`merged_planes`] of a CMYK document whose layers are mixed on their ink values +/// (`photocraft_compose::cmyk`), so opaque pixels keep their exact inks; `None` for documents +/// that composite in RGB. Reports progress and stops on cancel like [`merged_planes`]. +fn merged_ink_planes(doc: &Document, sample: SampleType, matte: bool, ctl: &Interrupt) -> Option<(Vec, bool, bool)> { + let bps = sample.bytes(); + let n = doc.size.area() as usize; + let plane = n * bps; + let mut planes = vec![0u8; plane * 5]; + let (mut has_alpha, mut translucent) = (false, false); + let canvas = doc.bounds(); + let w = canvas.width() as usize; + let rows = canvas.height().max(1) as f32; + // A cancelled export leaves the rest blank (the caller discards it), so the result stands either way. + let _ = photocraft_compose::cmyk::render_cmyk_bands(doc, canvas, 0, |band| -> Result<(), ()> { + if ctl.cancelled() { + return Err(()); + } + // Retain alpha whenever it differs from opaque at the stored precision. + has_alpha |= band.px.iter().any(|p| match sample { + SampleType::U8 => q255(p[4]) < 255, + SampleType::U16 => (p[4].clamp(0.0, 1.0) * 65535.0 + 0.5) as u16 != u16::MAX, + SampleType::F32 => p[4] != 1.0, + }); + translucent |= band.px.iter().any(|p| p[4] < 1.0); + let start = (band.rect.y0 - canvas.y0) as usize * w; + let parts = crate::pixels::par_map(crate::pixels::bands(band.px.len()), |range| { + let mut out: Vec> = (0..5).map(|_| Vec::with_capacity(range.len() * bps)).collect(); + for p in band.px.get(range.clone()).unwrap_or(&[]) { + for (c, o) in out.iter_mut().enumerate() { + // Inks matted against white paper (no ink) like Photoshop (see + // `pixels::matte`), and stored inverted as PSD's CMYK is. + let v = if c < 4 { 1.0 - if matte { crate::pixels::matte(p[c], p[4], 0.0) } else { p[c] } } else { p[4] }; + encode_be(v, sample, o); + } + } + (range.start, out) + }); + for (at, part) in parts { + for (c, src) in part.iter().enumerate() { + let o = c * plane + (start + at) * bps; + if let Some(dst) = planes.get_mut(o..o + src.len()) { + dst.copy_from_slice(src); + } + } + } + ctl.progress((band.rect.y1 - canvas.y0) as f32 / rows); + Ok(()) + })?; + Some((planes, has_alpha, translucent)) +} + +/// The merged image of a file saved without Maximize Compatibility: Photoshop's white placeholder +/// in the document's colour channels, with no alpha. Encoded like [`merged_planes`], so CMYK white +/// is no ink and Lab white is L 100 with neutral a*/b*. +pub(super) fn placeholder_planes(doc: &Document, fmt: &PixelFormat) -> Vec { + let cc = fmt.mode.color_channels(); + let cmyk = cmyk_of(fmt); + let lab16 = fmt.mode == ColorMode::Lab && fmt.sample == SampleType::U16; + let space = photocraft_compose::cmyk_space(doc); + let white = photocraft_color::convert::with_cmyk_space(space.as_ref(), || photocraft_raster::from_rgba(fmt, [1.0, 1.0, 1.0, 1.0])); + let n = doc.size.area() as usize; + let mut planes = Vec::with_capacity(n * fmt.sample.bytes() * cc); + for c in 0..cc { + let v = white.get(c).copied().unwrap_or(1.0); + let x = if cmyk { 1.0 - v } else { v }; + let x = if lab16 && (c == 1 || c == 2) { x * (crate::pixels::LAB16_CHROMA_MAX / 65535.0) } else { x }; + let mut sample = Vec::with_capacity(4); + encode_be(x, fmt.sample, &mut sample); + planes.extend(sample.iter().copied().cycle().take(n * sample.len())); + } + planes +} diff --git a/crates/io/src/psd_export/resources.rs b/crates/io/src/psd_export/resources.rs new file mode 100644 index 0000000000..4ab5210e94 --- /dev/null +++ b/crates/io/src/psd_export/resources.rs @@ -0,0 +1,116 @@ +use super::*; + +pub(crate) fn legacy_name(s: &str) -> Vec { + s.chars().map(|c| if c.is_ascii() && !c.is_ascii_control() { c as u8 } else { b'?' }).take(255).collect() +} + +pub(crate) fn unicode_names_resource(names: &[&str]) -> Vec { + let mut v = Vec::new(); + for n in names { + let units: Vec = n.encode_utf16().chain(std::iter::once(0)).collect(); + v.extend_from_slice(&(units.len() as u32).to_be_bytes()); + for u in units { + v.extend_from_slice(&u.to_be_bytes()); + } + } + v +} + +pub(crate) fn pascal_names_resource(names: &[&str]) -> Vec { + let mut v = Vec::new(); + for n in names { + let b = legacy_name(n); + let n = b.len().min(255); + v.push(n as u8); + v.extend_from_slice(&b[..n]); + } + // No per-string pad: Photoshop's resource 1006 for "Spot Color 1" is 13 bytes + // (length byte + 12 characters). The 8BIM container pads an odd resource separately. + v +} + +pub(crate) fn guides_resource(doc: &Document) -> Vec { + let mut v = Vec::new(); + v.extend_from_slice(&1u32.to_be_bytes()); + v.extend_from_slice(&576u32.to_be_bytes()); + v.extend_from_slice(&576u32.to_be_bytes()); + let n = doc.guides.horizontal.len() + doc.guides.vertical.len(); + v.extend_from_slice(&(n as u32).to_be_bytes()); + for (list, dir) in [(&doc.guides.vertical, 0u8), (&doc.guides.horizontal, 1u8)] { + for p in list { + v.extend_from_slice(&((p * 32.0).round() as i32).to_be_bytes()); + v.push(dir); + } + } + v +} + +/// Path resources: saved paths (2000+), the work path (1025) and the clipping path name (2999), +/// the last only when the imported one doesn't already name the document's clipping path. +pub(crate) fn path_resources(doc: &Document, warnings: &mut Vec) -> Vec { + use crate::vector_map::{CLIPPING_PATH, WORK_PATH, path_from_resource, path_to_records}; + let mut out = Vec::new(); + let (w, h) = (doc.size.width, doc.size.height); + let max = (*crate::vector_map::SAVED_PATHS.end() - *crate::vector_map::SAVED_PATHS.start() + 1) as usize; + if doc.paths.len() > max { + warnings.push(format!("only {max} saved paths fit in PSD; the rest were dropped")); + } + for (i, p) in doc.paths.iter().take(max).enumerate() { + let data = match &p.psd_raw { + Some(r) if path_from_resource(r, w, h).as_ref() == Some(&p.path) => r.to_vec(), + _ => path_to_records(&p.path, w, h).to_bytes(), + }; + let mut r = ImageResource::new(crate::vector_map::SAVED_PATHS.start() + i as u16, data); + r.name = legacy_name(&p.name); + out.push(r); + } + if let Some(wp) = &doc.work_path { + out.push(ImageResource::new(WORK_PATH, path_to_records(wp, w, h).to_bytes())); + } + let raw_clip = doc.metadata.psd_resources.iter().find(|(id, _, _)| *id == CLIPPING_PATH); + let raw_name = raw_clip.map(|(_, _, d)| { + let n = usize::from(d.first().copied().unwrap_or(0)); + d.get(1..1 + n).map(|b| String::from_utf8_lossy(b).into_owned()).unwrap_or_default() + }); + if let Some(c) = &doc.clipping_path + && raw_name.as_deref() != Some(c.name.as_str()) + { + // Pascal name, then flatness as 16.16 fixed (best effort; see vector_map docs). + let mut data = vec![0u8]; + let name = legacy_name(&c.name); + data[0] = name.len() as u8; + data.extend_from_slice(&name); + data.extend_from_slice(&((c.flatness.max(0.0) * 65536.0) as u32).to_be_bytes()); + out.push(ImageResource::new(CLIPPING_PATH, data)); + } + out +} + +/// Whether an imported (unmodelled) resource still describes the document and is written back. +pub(crate) fn keep_imported_resource(doc: &Document, id: u16, data: &[u8]) -> bool { + // Measurement scale / count resources: only while they still describe the document. + if !crate::annotations_map::keep_resource(doc, id) { + return false; + } + // Guides v2 and guide GUIDs: only while they still describe the document's guides. + if !crate::guides_map::keep_resource(doc, id, data) { + return false; + } + // A preserved clipping-path resource is only valid while it names the current one. + if id == crate::vector_map::CLIPPING_PATH { + let n = usize::from(data.first().copied().unwrap_or(0)); + let raw_name = data.get(1..1 + n).map(|b| String::from_utf8_lossy(b).into_owned()).unwrap_or_default(); + return doc.clipping_path.as_ref().is_some_and(|c| c.name == raw_name); + } + true +} + +/// A document-level (global) tagged block. Photoshop pads these to a multiple of 4, and readers +/// such as psd-tools step to the next block that way: an even pad after `CAI ` (77 bytes) +/// misaligned every block after it (#200). +pub(crate) fn global_block(signature: [u8; 4], key: [u8; 4], data: &[u8]) -> TaggedBlock { + let mut tb = TaggedBlock::new(key, data.to_vec()); + tb.signature = signature; + tb.padding = Some(vec![0; (4 - data.len() % 4) % 4]); + tb +} diff --git a/crates/io/src/psd_export/smart.rs b/crates/io/src/psd_export/smart.rs new file mode 100644 index 0000000000..264a2ab8ab --- /dev/null +++ b/crates/io/src/psd_export/smart.rs @@ -0,0 +1,253 @@ +use super::*; + +/// An embedded smart-object source as written to `lnk2`. +#[derive(Clone, Debug)] +pub(super) struct Source { + pub(super) uuid: String, + /// Pixel size of the source document. + pub(super) size: (f64, f64), + pub(super) dpi: f64, +} + +pub(super) fn contents_uuid(contents_id: SmartContentsId, bytes: &[u8]) -> String { + let mut identity = blake3::Hasher::new(); + identity.update(&contents_id.0.to_le_bytes()); + identity.update(bytes); + crate::smart_map::uuid_from(identity.finalize().as_bytes()) +} + +/// Smart-object state collected while emitting layers, written into the global blocks at the end. +#[derive(Default)] +pub(super) struct SmartOut { + /// Nesting depth of this export (embedded documents are exported recursively). + pub(super) depth: u32, + /// The document's preserved global blocks (embedded files and filter caches from PSD import). + pub(super) globals: Vec, + /// uuids of the files in the preserved linked-layer blocks. + pub(super) known: std::collections::HashSet, + /// uuids the layers reference. + pub(super) used: std::collections::HashSet, + /// Unreferenced preserved files may be dropped (every smart layer's file id is known). + pub(super) prune_ok: bool, + /// Files to embed. + pub(super) add: Vec, + /// Sources converted so far, by contents identity, bytes and whether they were read from a + /// link (`Err` = can't be embedded). + pub(super) converted: std::collections::HashMap<(SmartContentsId, [u8; 32], bool), Result>, + /// Each placed layer has its own id, even when it duplicates an imported layer. + pub(super) placed_used: std::collections::HashSet, + /// Original instances reserve their imported placement regardless of layer order. + pub(super) placed_owners: std::collections::HashMap, + /// Legacy records without a placed id stay unchanged for the original instance. + pub(super) unplaced_owners: std::collections::HashMap, + /// The imported identity that keeps each original linked UUID. + pub(super) linked_contents: std::collections::HashMap, + /// Independent copies of preserved linked items, including unavailable external sources. + pub(super) linked_copies: std::collections::BTreeMap<(String, SmartContentsId), photocraft_doc::PsdGlobalBlock>, + /// Embedded documents decoded while converting them, by uuid (for the filter caches). + pub(super) docs: std::collections::HashMap, + /// Source composites (document pixel format, source space) by uuid; `None` = unreadable. + pub(super) composites: std::collections::HashMap, photocraft_geom::Rect)>>, + /// Preserved `FEid` items (by placed id). + pub(super) old_fx: Vec, + /// Placed ids whose preserved `FEid` item stays. + pub(super) keep_fx: std::collections::HashSet, + /// Regenerated `FEid` items. + pub(super) new_fx: Vec, + /// The unfiltered pixels of each smart object whose filter mask shows: its layer record holds + /// the filtered pixels without the mask, as Photoshop's do (`compose::filter_mask`). + pub(super) unfiltered: std::collections::HashMap, +} + +/// Whether a smart object's filter mask shows: enabled over at least one visible, enabled filter. +pub(super) fn masked(sm: &photocraft_doc::SmartObject) -> bool { + sm.filter_mask.as_ref().is_some_and(|m| m.enabled) && sm.filters_enabled && sm.smart_filters.iter().any(|f| f.visible) +} + +/// `FEid` data padded to 4 bytes inside the block length: Photoshop counts the padding in the +/// length and can't open a file whose `FEid` is padded outside it. +fn padded_fx(fx: &photocraft_psd::filter_effects::FilterEffects) -> Vec { + let mut d = fx.to_bytes(); + d.resize(d.len().next_multiple_of(4), 0); + d +} + +pub(super) const LINK_KEYS: [&[u8; 4]; 4] = [b"lnk2", b"lnk3", b"lnkD", b"lnkE"]; + +const FX_KEYS: [&[u8; 4]; 2] = [b"FEid", b"FXid"]; + +impl SmartOut { + pub(super) fn new(doc: &Document, depth: u32) -> Self { + let globals = doc.metadata.psd_global_blocks.clone(); + let known = globals.iter().filter(|(_, k, _)| LINK_KEYS.contains(&k)).flat_map(|(_, _, d)| crate::linked::block_uuids(d)).collect(); + let old_fx = globals + .iter() + .filter(|(_, k, _)| FX_KEYS.contains(&k)) + .filter_map(|(_, _, d)| photocraft_psd::filter_effects::FilterEffects::parse(d).ok()) + .flat_map(|fx| fx.items) + .collect(); + let mut linked_contents = std::collections::HashMap::new(); + let mut placed_owners = std::collections::HashMap::new(); + let mut unplaced_owners = std::collections::HashMap::new(); + let mut layers = doc.walk(); + // Duplicating a layer clears psd_id and gives it a newer runtime id. + layers.sort_by_key(|(_, _, layer)| (layer.psd_id.is_none(), layer.id)); + for (_, _, layer) in layers { + if let LayerContent::Smart(sm) = &layer.content + && let photocraft_doc::SmartSource::Linked { path } = &sm.source + && let Some(placed) = sm.psd_raw.as_ref().and_then(|d| crate::smart_map::parse_sold(d)) + && placed.idnt == *path + { + linked_contents.entry(path.clone()).or_insert(sm.contents_id); + if placed.placed.is_empty() { + unplaced_owners.entry(sm.contents_id).or_insert(layer.id); + } else { + placed_owners.entry(placed.placed).or_insert(layer.id); + } + } + } + SmartOut { depth, globals, known, prune_ok: true, old_fx, linked_contents, placed_owners, unplaced_owners, ..Default::default() } + } + + /// The document's global blocks with the linked-layer files and filter caches brought up to + /// date: unreferenced files dropped (when every reference is known), new files appended, + /// filter caches kept or regenerated per smart object. Unchanged blocks stay byte-identical. + pub(super) fn finish(&self, blocks: Vec) -> Vec { + use std::sync::Arc; + let keep = |u: &str| !self.prune_ok || self.used.contains(u); + let mut out = Vec::with_capacity(blocks.len() + 2); + let mut added = false; + let mut fx_placed = false; + for (sig, key, data) in blocks { + if LINK_KEYS.contains(&&key) { + let add: &[crate::linked::LinkedFile] = if !added && &key == b"lnk2" { &self.add } else { &[] }; + added |= &key == b"lnk2"; + match crate::linked::rebuild_block(&data, &keep, add) { + None => out.push((sig, key, data)), + Some(d) if d.is_empty() => {} + Some(d) => out.push((sig, key, Arc::new(d))), + } + } else if FX_KEYS.contains(&&key) { + let Ok(mut fx) = photocraft_psd::filter_effects::FilterEffects::parse(&data) else { + out.push((sig, key, data)); + continue; + }; + let before = fx.items.len(); + fx.items.retain(|i| self.keep_fx.contains(&i.id)); + let fresh = !fx_placed && !self.new_fx.is_empty(); + if fresh { + fx.items.extend(self.new_fx.iter().cloned()); + fx_placed = true; + } + if fx.items.len() == before && !fresh { + out.push((sig, key, data)); + } else if !fx.items.is_empty() { + out.push((sig, key, Arc::new(padded_fx(&fx)))); + } + } else { + out.push((sig, key, data)); + } + } + if !added && !self.add.is_empty() { + let data: Vec = self.add.iter().flat_map(crate::linked::encode_linked_file).collect(); + out.push((*b"8BIM", *b"lnk2", Arc::new(data))); + } + for (sig, key, data) in self.linked_copies.values() { + if let Some((_, _, block)) = out.iter_mut().find(|(s, k, _)| s == sig && k == key) { + Arc::make_mut(block).extend_from_slice(data); + } else { + out.push((*sig, *key, data.clone())); + } + } + if !fx_placed && !self.new_fx.is_empty() { + let fx = photocraft_psd::filter_effects::FilterEffects { version: 3, items: self.new_fx.clone() }; + out.push((*b"8BIM", *b"FEid", Arc::new(padded_fx(&fx)))); + if !out.iter().any(|(_, k, _)| k == b"FMsk") { + // Filter mask overlay: RGB red at 50 %, Photoshop's default. + out.push((*b"8BIM", *b"FMsk", Arc::new(vec![0, 0, 255, 255, 0, 0, 0, 0, 0, 0, 0, 50]))); + } + } + out + } +} + +/// The source size of a smart object whose file we can't decode: its rendered bounds taken back +/// through the inverse transform (the source's top-left is the origin). +pub(super) fn size_from_layer(sm: &photocraft_doc::SmartObject) -> (f64, f64) { + let r = sm.cache.as_ref().map(Surface::content_bounds).filter(|r| !r.is_empty()); + let (Some(r), Some(inv)) = (r, sm.transform.inverse()) else { return (1.0, 1.0) }; + let [a, b, c, d, e, f] = inv.m; + let (mut w, mut h) = (1.0f64, 1.0f64); + for (x, y) in [(r.x0, r.y0), (r.x1, r.y0), (r.x1, r.y1), (r.x0, r.y1)] { + let (x, y) = (f64::from(x), f64::from(y)); + w = w.max((a * x + c * y + e).round()); + h = h.max((b * x + d * y + f).round()); + } + (w, h) +} + +pub(super) fn upsert(raw: &mut Vec<([u8; 4], Vec)>, key: &[u8; 4], data: Vec, before: Option<&[u8; 4]>) { + if let Some(e) = raw.iter_mut().find(|(k, _)| k == key) { + e.1 = data; + return; + } + match before.and_then(|b| raw.iter().position(|(k, _)| k == b)) { + Some(i) => raw.insert(i, (*key, data)), + None => raw.push((*key, data)), + } +} + +/// Resource 1026 (Layer › Link Layers): one u16 group id per layer record, in the order +/// [`Ex::emit`] writes records (a group's bounding divider, its children, then the group). +/// Imported ids that fit in a u16 are kept, so unchanged files write the same bytes; otherwise +/// groups are renumbered by first appearance. `None` when no layer is linked. +pub(super) fn link_group_resource(layers: &[Layer]) -> Option> { + fn walk(layers: &[Layer], out: &mut Vec>) { + for l in layers { + if let LayerContent::Group(g) = &l.content { + out.push(None); + walk(&g.children, out); + } + out.push(l.link_group); + } + } + let mut per = Vec::new(); + walk(layers, &mut per); + if per.iter().all(Option::is_none) { + return None; + } + let fits = per.iter().flatten().all(|&g| (1..=u64::from(u16::MAX)).contains(&g)); + let mut seen: Vec = Vec::new(); + let ids = per.iter().map(|g| match *g { + None => 0u16, + Some(g) if fits => g as u16, + Some(g) => { + let i = seen.iter().position(|&s| s == g).unwrap_or_else(|| { + seen.push(g); + seen.len() - 1 + }); + u16::try_from(i + 1).unwrap_or(u16::MAX) + } + }); + Some(ids.flat_map(u16::to_be_bytes).collect()) +} + +/// Whether the layer's effects still equal what its preserved `lmfx`/`lfx2` +/// decodes to. `None` when there is nothing preserved or it can't be decoded. +/// Block keys a smart object's `psd_raw` may be written under, in priority order. The data says +/// which it is: `PlLd` holds a `plcL` structure, `SoLd`/`SoLE` a `soLD` one (Adobe PSD spec, +/// "Placed Layer" and "Placed Layer Data"). Writing one under the other's key makes the block +/// unreadable. +pub(super) fn smart_keys(data: Option<&[u8]>) -> &'static [&'static [u8; 4]] { + match data.and_then(|d| d.get(..4)) { + Some(b"plcL") => &[b"PlLd"], + Some(b"soLD") => &[b"SoLd", b"SoLE"], + _ => &[b"SoLd", b"PlLd", b"SoLE"], + } +} + +pub(super) fn effects_unchanged(l: &Layer) -> Option { + let src = l.psd_blocks.iter().find(|(k, _)| k == b"lmfx").map(|(_, d)| d.clone()).or_else(|| l.effects.psd_raw.clone())?; + let (m, items) = crate::effects_map::parse_lfx2(&src)?; + Some(m == l.effects.enabled && items == l.effects.items) +} diff --git a/crates/io/src/psd_export/tests.rs b/crates/io/src/psd_export/tests.rs new file mode 100644 index 0000000000..9688dfeac2 --- /dev/null +++ b/crates/io/src/psd_export/tests.rs @@ -0,0 +1,442 @@ +use super::*; + +fn document(width: u32, height: u32) -> Document { + Document::new("size estimate", photocraft_geom::Size::new(width, height), ColorMode::Rgb, SampleType::U8) +} + +/// Photoshop opens a PSD's bottom layer as its Background only when that layer has no +/// transparency channel (measured on Photoshop 27.11: with the channel written, re-exported +/// files reopened with the Background as an ordinary layer). +#[test] +fn a_background_is_written_without_a_transparency_channel() { + use photocraft_color::Color; + let size = photocraft_geom::Size::new(8, 6); + let mut doc = Document::with_background("bg", size, ColorMode::Rgb, SampleType::U8, Color::rgb(0.2, 0.4, 0.6)); + doc.layers.push(Layer::raster("Layer 1", doc.pixel_format())); + let file = document_to_psd(&doc); + let layers = &file.layer_info.as_ref().unwrap().layers; + let ids = |i: usize| layers[i].channels.iter().map(|c| c.id).collect::>(); + assert_eq!(ids(0), vec![0, 1, 2], "the Background has no -1 channel"); + assert_eq!(layers[0].flags.0, LayerFlags::BIT4_USEFUL | LayerFlags::TRANSPARENCY_PROTECTED, "as Photoshop writes it"); + assert!(ids(1).contains(&-1), "other layers keep their transparency"); + // It comes back as the same locked, opaque Background. + let back = crate::import("bg.psd", &file.to_bytes().unwrap()).unwrap().document; + let bg = &back.layers[0]; + assert!(bg.locks.transparency && bg.locks.position, "{:?}", bg.locks); + assert_eq!(bg.surface().unwrap().read_region(back.bounds()), doc.layers[0].surface().unwrap().read_region(doc.bounds())); + // A bottom layer with transparency (or unlocked) is not a Background. + let mut holey = doc.clone(); + holey.layers[0].surface_mut().unwrap().write_pixel(2, 2, &[0.0, 0.0, 0.0, 0.0]); + assert!(document_to_psd(&holey).layer_info.unwrap().layers[0].channels.iter().any(|c| c.id == -1)); + let mut unlocked = doc.clone(); + unlocked.layers[0].locks.position = false; + assert!(document_to_psd(&unlocked).layer_info.unwrap().layers[0].channels.iter().any(|c| c.id == -1)); +} + +/// A flat 1-bit Bitmap file (no layers) opens in Photoshop as its Background; so does it in +/// PhotoCraft, and it is written back as one (no transparency channel). +#[test] +fn a_flat_bitmap_file_opens_and_saves_as_a_background() { + let file = photocraft_psd::testgen::merged_only(Version::Psd, PsdMode::Bitmap, 1, Compression::Raw, 8, 4); + let doc = crate::import("flat.psd", &file.to_bytes().unwrap()).unwrap().document; + let bg = &doc.layers[0]; + assert!(bg.name == "Background" && bg.locks.transparency && bg.locks.position, "{:?}", bg.locks); + // Bitmap has no layers in Photoshop (#4814): the file is saved flat in Bitmap mode, without + // a layer section, and opens as a Background again. + let out = document_to_psd(&doc); + assert_eq!(out.header.color_mode, PsdMode::Bitmap); + assert!(out.layer_info.as_ref().is_none_or(|li| li.layers.is_empty())); + let back = crate::import("flat.psd", &out.to_bytes().unwrap()).unwrap().document; + let bg = &back.layers[0]; + assert!(back.layers.len() == 1 && bg.name == "Background" && bg.locks.transparency && bg.locks.position, "{:?}", bg.locks); +} + +/// A layered document with a spot and an alpha channel. Each channel holds 100 %, 25 %, 75 % +/// and 0 % in four columns, the layout of the Photoshop spot oracles. +fn spot_and_alpha_document() -> Document { + let mut doc = document(4, 1); + doc.layers.push(Layer::group("Group", vec![Layer::raster("Layer 1", doc.pixel_format())])); + let channel = |name: &str| { + let mut s = Surface::new(PixelFormat::GRAY8); + s.write_interleaved(doc.bounds(), &[255, 64, 191, 0]); + photocraft_doc::AlphaChannel::new(name, s) + }; + let mut spot = channel("Spot Color 1"); + spot.spot = Some((photocraft_doc::Color::rgb(0.0, 0.6, 1.0), 0.0)); + let alpha = channel("Alpha 1"); + doc.channels.extend([spot, alpha]); + doc +} + +/// The extra planes after the colour channels (and the merged transparency) of `file`. +fn extra_planes(file: &PsdFile, count: usize) -> Vec { + let planes = file.decode_merged().unwrap(); + let plane = (file.header.width * file.header.height) as usize * usize::from(file.header.depth / 8); + planes[planes.len() - count * plane..].to_vec() +} + +/// Resource 1053's identifiers. +fn alpha_ids(file: &PsdFile) -> Option> { + file.resource(crate::channel_map::ALPHA_IDENTIFIERS).map(|r| r.data.as_chunks::<4>().0.iter().map(|c| u32::from_be_bytes(*c)).collect()) +} + +/// A PSD stores spot ink as Photoshop's own PSDs do (0 = solid ink: the 100, 25, 75 and 0 % +/// columns are 0, 191, 64, 255) and an alpha channel straight (255 = selected). The global +/// layer mask stays empty and flag bit 3 stays on the layers only, not on the group's closing +/// divider: Photoshop opens those as they are, and 509 of the corpus's 721 Photoshop PSDs have +/// an empty mask too. Opening the file gives the same ink back. +#[test] +fn psd_stores_spot_ink_as_photoshop_does() { + let doc = spot_and_alpha_document(); + let file = PsdFile::from_bytes(&document_to_psd(&doc).to_bytes().unwrap()).unwrap(); + assert_eq!(extra_planes(&file, 2), [0, 191, 64, 255, 255, 64, 191, 0], "spot, then alpha"); + assert_eq!(file.global_layer_mask.as_ref().map(|m| m.data.len()), Some(0)); + let flags: Vec = file.layers().iter().map(|l| l.flags.0 & LayerFlags::BIT4_USEFUL).collect(); + assert_eq!(flags, [0, LayerFlags::BIT4_USEFUL, LayerFlags::BIT4_USEFUL], "closing divider, layer, group"); + let back = crate::import("spot.psd", &file.to_bytes().unwrap()).unwrap().document; + assert!(back.channels[0].spot.is_some() && back.channels[1].spot.is_none()); + for c in &back.channels { + assert_eq!(c.surface.to_interleaved(back.bounds()), [255, 64, 191, 0], "{}", c.name); + } +} + +/// Resource 1053 numbers the extra channels as Photoshop 27.11 does in a new document: 3, 4, 5 +/// in every colour mode, after 0 for the merged transparency when there is one (its +/// transparent PSD lists `0, 3, 4, 5`). A Quick Mask is an extra channel too. Without extra +/// channels there is none. +#[test] +fn psd_alpha_identifiers_number_the_channels_as_photoshop_does() { + use photocraft_color::Color; + let size = photocraft_geom::Size::new(4, 1); + for mode in [ColorMode::Rgb, ColorMode::Cmyk, ColorMode::Grayscale, ColorMode::Lab] { + let mut doc = Document::with_background("bg", size, mode, SampleType::U8, Color::rgb(1.0, 1.0, 1.0)); + assert_eq!(alpha_ids(&document_to_psd(&doc)), None, "{mode:?} without channels"); + doc.channels = spot_and_alpha_document().channels; + let file = document_to_psd(&doc); + assert!(!file.merged_has_alpha(), "{mode:?}"); + assert_eq!(alpha_ids(&file), Some(vec![3, 4]), "{mode:?}"); + doc.quick_mask = Some(photocraft_doc::AlphaChannel::new("Quick Mask", Surface::new(PixelFormat::GRAY8))); + assert_eq!(alpha_ids(&document_to_psd(&doc)), Some(vec![3, 4, 5]), "{mode:?} with a Quick Mask"); + } + // The empty layer leaves the composite transparent. + let file = document_to_psd(&spot_and_alpha_document()); + assert!(file.merged_has_alpha()); + assert_eq!(alpha_ids(&file), Some(vec![0, 3, 4])); +} + +/// A save writes one fresh 1053 for the channels the document has. A Photoshop file's own is +/// not kept on open (it would be new metadata after every round trip), and one a document +/// carries anyway (kept by an earlier version) is never written: next to the fresh one it +/// would be a second, and without channels it would list channels that are gone. The +/// identifiers here, 3 and 2, are those of psd-tools' `cmyk-alpha-spot.psd` (Photoshop 24.7). +#[test] +fn a_kept_alpha_identifiers_resource_is_not_written() { + let kept = || (crate::channel_map::ALPHA_IDENTIFIERS, String::new(), std::sync::Arc::new([0, 0, 0, 3, 0, 0, 0, 2].to_vec())); + let mut file = document_to_psd(&spot_and_alpha_document()); + file.resources.retain(|r| r.id != crate::channel_map::ALPHA_IDENTIFIERS); + file.resources.push(ImageResource::new(kept().0, kept().2.to_vec())); + let mut opened = crate::import("ps.psd", &file.to_bytes().unwrap()).unwrap().document; + assert!(!opened.metadata.psd_resources.iter().any(|(id, ..)| *id == crate::channel_map::ALPHA_IDENTIFIERS)); + opened.metadata.psd_resources.push(kept()); + let again = PsdFile::from_bytes(&crate::export(&opened, "x.psd", &crate::ExportOptions::default()).unwrap().bytes).unwrap(); + assert_eq!(again.resources.iter().filter(|r| r.id == crate::channel_map::ALPHA_IDENTIFIERS).count(), 1); + assert_eq!(alpha_ids(&again), Some(vec![0, 3, 4])); + opened.channels.clear(); + assert_eq!(alpha_ids(&document_to_psd(&opened)), None, "no channels left"); +} + +#[test] +fn group_divider_id_wraps_without_colliding_with_imported_layer_ids() { + let mut doc = document(8, 8); + let mut group = Layer::group("Imported group", vec![Layer::raster("Child", doc.pixel_format())]); + group.psd_id = Some(u32::MAX); + doc.layers.push(group); + + let file = document_to_psd(&doc); + let ids: Vec = file.layers().iter().filter_map(|layer| layer.layer_id()).collect(); + let unique: std::collections::HashSet = ids.iter().copied().collect(); + assert_eq!(ids.len(), 3, "group, child and closing divider"); + assert_eq!(unique.len(), ids.len(), "no generated ID may collide"); + assert!(unique.contains(&u32::MAX), "preserve the imported group ID"); + assert!(unique.contains(&1), "reuse the first unused positive ID on wrap"); + + let encoded = file.to_bytes().unwrap(); + let parsed = PsdFile::from_bytes(&encoded).unwrap(); + let reloaded_ids: std::collections::HashSet = parsed.layers().iter().filter_map(|layer| layer.layer_id()).collect(); + assert_eq!(unique, reloaded_ids); +} + +/// #5068: Photoshop won't open a file whose `Lr32` comes before the `Mt32` marker it keeps for +/// a 32-bit document's merged transparency (verified in Photoshop 2026 on psd-tools' +/// `transparentbg.psd` re-saved both ways). The layer block follows a kept marker. +#[test] +fn layer_block_follows_a_kept_merged_transparency_marker() { + for (depth, key, marker) in [ + (SampleType::F32, *b"Lr32", *b"Mt32"), + (SampleType::U16, *b"Lr16", *b"Mt16"), + (SampleType::F32, *b"Lr32", *b"Mtrn"), + (SampleType::F32, *b"Lr32", *b"MTrn"), + ] { + let mut doc = Document::new("t", photocraft_geom::Size::new(8, 6), ColorMode::Rgb, depth); + let mut s = Surface::new(doc.pixel_format()); + s.fill_rect(photocraft_geom::Rect::new(1, 1, 5, 4), &[0.5, 0.2, 0.9, 1.0]); + doc.layers.push(Layer::new("Layer 1", LayerContent::Raster(s))); + doc.metadata.psd_global_blocks = vec![(*b"8BIM", *b"Patt", std::sync::Arc::new(Vec::new())), (*b"8BIM", marker, std::sync::Arc::new(Vec::new()))]; + let saved = PsdFile::from_bytes(&document_to_psd(&doc).to_bytes().unwrap()).unwrap(); + let LayerInfoPlacement::GlobalBlock { index, key: written, .. } = saved.layer_info_placement else { panic!("{depth:?}: a global layer block") }; + assert_eq!(written, key); + let at = saved.global_blocks.iter().position(|b| b.key == marker).expect("the marker is kept"); + assert!(at < index, "{depth:?}: {marker:?} at {at}, the layer block at {index}"); + } + // Without a marker the layer block stays first. + let mut doc = Document::new("t", photocraft_geom::Size::new(8, 6), ColorMode::Rgb, SampleType::F32); + doc.layers.push(Layer::new("Layer 1", LayerContent::Raster(Surface::new(doc.pixel_format())))); + doc.metadata.psd_global_blocks = vec![(*b"8BIM", *b"Patt", std::sync::Arc::new(Vec::new()))]; + let saved = PsdFile::from_bytes(&document_to_psd(&doc).to_bytes().unwrap()).unwrap(); + assert!(matches!(saved.layer_info_placement, LayerInfoPlacement::GlobalBlock { index: 0, .. })); +} + +/// A merged-transparency marker kept from the opened file describes that file's composite. +/// Saved with an opaque composite, it would make the first alpha channel read back as the +/// merged transparency, and the channel would be gone: the save drops it. +#[test] +fn an_opaque_save_drops_a_kept_merged_transparency_marker() { + for (depth, marker) in [(SampleType::U8, *b"MTrn"), (SampleType::U8, *b"Mtrn"), (SampleType::U16, *b"Mt16"), (SampleType::F32, *b"Mt32")] { + let case = format!("{depth:?} {}", String::from_utf8_lossy(&marker)); + let mut doc = Document::new("t", photocraft_geom::Size::new(8, 6), ColorMode::Rgb, depth); + let mut s = Surface::new(doc.pixel_format()); + s.fill_rect(photocraft_geom::Rect::new(0, 0, 8, 6), &[0.5, 0.2, 0.9, 1.0]); + doc.layers.push(Layer::new("Layer 1", LayerContent::Raster(s))); + doc.channels.push(photocraft_doc::AlphaChannel::new("Alpha 1", Surface::new(PixelFormat::GRAY8))); + doc.metadata.psd_global_blocks = vec![(*b"8BIM", marker, std::sync::Arc::new(Vec::new()))]; + let file = document_to_psd(&doc); + assert!(!file.global_blocks.iter().any(TaggedBlock::is_merged_transparency_marker), "{case}"); + assert!(!file.merged_has_alpha(), "{case}"); + let back = crate::import("a.psd", &file.to_bytes().unwrap()).unwrap().document; + let names: Vec<&str> = back.channels.iter().map(|c| c.name.as_str()).collect(); + assert_eq!(names, ["Alpha 1"], "{case}"); + } +} + +#[test] +fn unreadable_lr16_warns_on_import_and_is_not_saved_twice() { + // #2700: a 16-bit file whose Lr16 block claims five layers but holds none. + let mut file = photocraft_psd::testgen::merged_only(Version::Psd, PsdMode::Rgb, 16, Compression::Raw, 8, 6); + file.global_layer_mask = Some(GlobalLayerMask::default()); + file.global_blocks.push(TaggedBlock::new(*b"Lr16", vec![0, 5, 0, 0])); + let imported = crate::import("broken.psd", &file.to_bytes().unwrap()).unwrap(); + assert!(imported.warnings.iter().any(|w| w.contains("Lr16") && w.contains("could not be read")), "{:?}", imported.warnings); + + let saved = PsdFile::from_bytes(&document_to_psd(&imported.document).to_bytes().unwrap()).unwrap(); + let ours = matches!(saved.layer_info_placement, LayerInfoPlacement::GlobalBlock { key, .. } if key == *b"Lr16"); + let kept = saved.global_blocks.iter().filter(|b| b.key == *b"Lr16").count(); + assert_eq!((ours, kept), (true, 0), "exactly one Lr16 block: the document's own layers"); + assert_eq!(saved.layers().len(), 1); +} + +#[test] +fn photo_filter_psd_is_four_byte_aligned_and_round_trips() { + let color = [60000u16, 30000, 0].map(|x| x as f32 / 65535.0); + let adjustment = photocraft_doc::Adjustment::PhotoFilter { color, density: 0.14, preserve_luminosity: true }; + let mut doc = + Document::with_background("Photo Filter PSD", photocraft_geom::Size::new(32, 24), ColorMode::Rgb, SampleType::U8, photocraft_doc::Color::WHITE); + let mut layer = Layer::new("Warming Filter", LayerContent::Adjustment(adjustment.clone())); + doc.layers.push(layer.clone()); + + let assert_phfl = |file: &PsdFile| { + let records = &file.layer_info.as_ref().unwrap().layers; + let data = records.iter().flat_map(|r| r.blocks.iter()).find(|b| b.key == *b"phfl").map(|b| b.data.as_slice()).expect("Photo Filter adjustment data"); + assert_eq!(data.len(), 20, "PSD layer block length includes four-byte padding"); + assert_eq!(&data[0..2], &[0, 2], "version 2 RGB Photo Filter"); + assert_eq!(&data[17..], &[0, 0, 0], "three padding bytes after the 17-byte payload"); + }; + + let exported = document_to_psd(&doc); + assert_phfl(&exported); + let encoded = exported.to_bytes().unwrap(); + let parsed = PsdFile::from_bytes(&encoded).unwrap(); + assert_phfl(&parsed); + let (restored, _) = crate::psd_import::psd_to_document(&parsed); + assert!(restored.layers.iter().any(|l| l.content == LayerContent::Adjustment(adjustment.clone()))); + + // Importing a legacy 18-byte block must still work; saving it again should repair it + // even when the adjustment values have not changed (normally raw blocks are reused). + let mut legacy = crate::adjust_map::write(&adjustment)[0].1.clone(); + legacy.truncate(18); + layer.psd_blocks = vec![(*b"phfl", std::sync::Arc::new(legacy))]; + doc.layers.pop(); + doc.layers.push(layer); + let repaired = document_to_psd(&doc); + assert_phfl(&repaired); + let repaired_bytes = repaired.to_bytes().unwrap(); + assert_phfl(&PsdFile::from_bytes(&repaired_bytes).unwrap()); +} + +#[test] +fn photo_filter_version_3_is_kept_until_edited() { + // The #3777 block (Photoshop CS2, XYZ colour): saved back byte-exact while unchanged. + let v3 = vec![0, 3, 0, 0, 0x5e, 0x7f, 0, 0, 0x61, 0xaa, 0, 0, 0x0e, 0xf3, 0, 0, 0, 0x3f, 1, 0]; + let adjustment = crate::adjust_map::parse(b"phfl", &v3, None, crate::adjust_map::Channels::Rgb); + let photocraft_doc::Adjustment::PhotoFilter { color, .. } = adjustment else { panic!("{adjustment:?}") }; + let mut doc = Document::with_background("Photo Filter v3", photocraft_geom::Size::new(8, 8), ColorMode::Rgb, SampleType::U8, photocraft_doc::Color::WHITE); + let mut layer = Layer::new("Photo Filter 1", LayerContent::Adjustment(adjustment.clone())); + layer.psd_blocks = vec![(*b"phfl", std::sync::Arc::new(v3.clone()))]; + doc.layers.push(layer); + let phfl = |doc: &Document| { + let file = PsdFile::from_bytes(&document_to_psd(doc).to_bytes().unwrap()).unwrap(); + let records = &file.layer_info.as_ref().unwrap().layers; + records.iter().flat_map(|r| r.blocks.iter()).find(|b| b.key == *b"phfl").map(|b| b.data.clone()).expect("Photo Filter adjustment data") + }; + assert_eq!(phfl(&doc), v3); + // Once edited it is written as version 2 (RGB), and the colour survives. + let edited = photocraft_doc::Adjustment::PhotoFilter { color, density: 0.5, preserve_luminosity: true }; + if let Some(l) = doc.layers.last_mut() { + l.content = LayerContent::Adjustment(edited.clone()); + } + let saved = phfl(&doc); + assert_eq!(&saved[..2], &[0, 2]); + let reread = crate::adjust_map::parse(b"phfl", &saved, None, crate::adjust_map::Channels::Rgb); + let photocraft_doc::Adjustment::PhotoFilter { color: back, density, .. } = reread else { panic!("{reread:?}") }; + assert!(back.iter().zip(color).all(|(b, c)| (b - c).abs() <= 1.0 / 65535.0), "{back:?} vs {color:?}"); + assert_eq!(density, 0.5); +} + +#[test] +fn light_adjustment_is_kept_verbatim_and_warned() { + // #6542: Photoshop 2026's Light layer is a `brit` block whose `CgEd` descriptor carries + // more than Brightness/Contrast. Synthetic block: the extra key names are placeholders. + use photocraft_psd::descriptor::{Descriptor, Value, VersionedDescriptor}; + let brit = vec![0, 0, 0xff, 0xfe, 0, 127, 0, 0]; + let d = Descriptor::new("null") + .with("Vrsn", Value::Integer(1)) + .with("Brgh", Value::Integer(0)) + .with("Cntr", Value::Integer(-2)) + .with("Exps", Value::Double(-2.3)) + .with("Hghl", Value::Integer(-64)) + .with("useLegacy", Value::Boolean(false)); + let cged = VersionedDescriptor::new(d).to_bytes(); + let adjustment = crate::adjust_map::parse(b"brit", &brit, Some(&cged), crate::adjust_map::Channels::Rgb); + assert_eq!(adjustment, photocraft_doc::Adjustment::Unsupported { psd_key: "brit".into(), raw: brit.clone().into() }); + let mut doc = Document::with_background("Light", photocraft_geom::Size::new(8, 8), ColorMode::Rgb, SampleType::U8, photocraft_doc::Color::WHITE); + let mut layer = Layer::new("Light 1", LayerContent::Adjustment(adjustment)); + layer.psd_blocks = vec![(*b"brit", std::sync::Arc::new(brit.clone())), (*b"CgEd", std::sync::Arc::new(cged.clone()))]; + doc.layers.push(layer); + let block = |file: &PsdFile, key: &[u8; 4]| { + let records = &file.layer_info.as_ref().unwrap().layers; + records.iter().flat_map(|r| r.blocks.iter()).find(|b| b.key == *key).map(|b| b.data.clone()) + }; + let file = PsdFile::from_bytes(&document_to_psd(&doc).to_bytes().unwrap()).unwrap(); + let (restored, warnings) = crate::psd_import::psd_to_document(&file); + assert!(warnings.iter().any(|w| w.contains("\"Light 1\"") && w.contains("Light settings")), "{warnings:?}"); + // Saved again unchanged, both blocks are written back byte for byte. + let again = PsdFile::from_bytes(&document_to_psd(&restored).to_bytes().unwrap()).unwrap(); + assert_eq!(block(&again, b"brit").as_deref(), Some(&brit[..])); + assert_eq!(block(&again, b"CgEd").as_deref(), Some(&cged[..])); + // A plain Brightness/Contrast descriptor still reads as Brightness/Contrast. + let plain = crate::adjust_map::write(&photocraft_doc::Adjustment::BrightnessContrast { brightness: 5.0, contrast: -2.0, legacy: false }); + assert!(!crate::adjust_map::is_extended_brit(Some(&plain[1].1))); +} + +#[test] +fn size_limit_boundary_keeps_limit_and_switches_above_it() { + assert!(!exceeds_psd_size_limit(Some(PSD_MAX_FILE_SIZE))); + assert!(exceeds_psd_size_limit(Some(PSD_MAX_FILE_SIZE + 1))); + assert!(exceeds_psd_size_limit(None)); +} + +#[test] +fn encoded_size_estimator_rejects_arithmetic_overflow() { + assert_eq!(estimate_encoded_size(u64::MAX, 0, 0), None); + assert_eq!(estimate_encoded_size(0, u64::MAX, 0), None); + assert_eq!(estimate_encoded_size(0, 0, u64::MAX), Some(u64::MAX)); + assert!(exceeds_psd_size_limit(estimate_psd_size(&document(u32::MAX, u32::MAX)))); +} + +#[test] +fn large_encoded_size_selects_psb_without_changing_explicit_choice() { + let large = document(30_000, 30_000); + assert!(estimate_psd_size(&large).is_some_and(|size| size > PSD_MAX_FILE_SIZE)); + let large_size_exceeds_limit = psd_size_exceeds_limit(&large); + assert_eq!(psd_version(&large, false, large_size_exceeds_limit), Version::Psb); + + let small = document(1, 1); + let small_size_exceeds_limit = psd_size_exceeds_limit(&small); + assert_eq!(psd_version(&small, false, small_size_exceeds_limit), Version::Psd); + assert_eq!(psd_version(&small, true, small_size_exceeds_limit), Version::Psb); +} +#[test] +fn kept_psb_blocks_are_written_as_8bim_in_a_psd() { + // Photoshop 27.11 refuses a PSD holding `8B64` blocks ("not compatible with this + // version"); they came from re-saving a PSB as PSD with its global FMsk and cinf kept. + let mut doc = document(4, 4); + doc.metadata.psd_global_blocks = + vec![(*b"8B64", *b"FMsk", std::sync::Arc::new(vec![0xff, 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, 50])), (*b"8BIM", *b"Patt", std::sync::Arc::new(Vec::new()))]; + let signatures = |force_psb| { + let opts = PsdExportOptions { force_psb, ..PsdExportOptions::default() }; + let bytes = document_to_psd_with(&doc, &opts).0.to_bytes().unwrap(); + let file = PsdFile::from_bytes(&bytes).unwrap(); + file.global_blocks.iter().map(|b| (b.signature, b.key)).collect::>() + }; + assert_eq!(signatures(false), vec![(*b"8BIM", *b"FMsk"), (*b"8BIM", *b"Patt")]); + assert_eq!(signatures(true), vec![(*b"8B64", *b"FMsk"), (*b"8BIM", *b"Patt")], "a PSB keeps 8B64"); +} + +/// A PSB writes every global block with an 8-byte length as `8B64`, the way Photoshop does: +/// kept from a PSD source, `lnk2`, `pths` and `cinf` arrive as `8BIM`, and with that signature +/// and the PSB's 8-byte length Photoshop 27.11 refused the whole file (#7937). Blocks with a +/// 4-byte length keep `8BIM`, and a PSD keeps `8BIM` throughout. +#[test] +fn psb_writes_long_length_blocks_as_8b64() { + let mut doc = document(4, 4); + doc.metadata.psd_global_blocks = vec![ + (*b"8BIM", *b"cinf", std::sync::Arc::new(vec![0, 0, 0, 16, 0, 0, 0, 0])), + (*b"8BIM", *b"pths", std::sync::Arc::new(vec![0, 0, 0, 16, 0, 0, 0, 0])), + (*b"8BIM", *b"Patt", std::sync::Arc::new(Vec::new())), + ]; + let written = |force_psb| { + let opts = PsdExportOptions { force_psb, ..PsdExportOptions::default() }; + let bytes = document_to_psd_with(&doc, &opts).0.to_bytes().unwrap(); + let file = PsdFile::from_bytes(&bytes).unwrap(); + let blocks = file.global_blocks.iter().map(|b| (b.signature, b.key, b.data.len())).collect::>(); + (bytes, blocks) + }; + let (bytes, blocks) = written(true); + assert_eq!(blocks, vec![(*b"8B64", *b"cinf", 8), (*b"8B64", *b"pths", 8), (*b"8BIM", *b"Patt", 0)]); + // On disk: the signature, the key, then the 8-byte length. + let at = bytes.windows(8).position(|w| w == b"8B64cinf").expect("8B64cinf in the file"); + assert_eq!(bytes.get(at + 8..at + 16), Some(&[0u8, 0, 0, 0, 0, 0, 0, 8][..])); + assert!(!bytes.windows(8).any(|w| w == b"8BIMcinf" || w == b"8BIMpths")); + let (_, blocks) = written(false); + assert_eq!(blocks, vec![(*b"8BIM", *b"cinf", 8), (*b"8BIM", *b"pths", 8), (*b"8BIM", *b"Patt", 0)], "a PSD keeps 8BIM"); +} + +/// A layered document with transparency in the merged image and an alpha channel: the name +/// and DisplayInfo resources hold one entry per extra channel, the merged transparency first, +/// as in every file Photoshop opens (one short, Photoshop 27.11 refused the file with "Could +/// not import the clipboard because an unexpected end-of-file was encountered"). The alpha +/// channel keeps its own name and options on the way back. +#[test] +fn alpha_names_count_the_merged_transparency() { + let mut doc = document(8, 6); + let mut layer = Layer::raster("Layer 1", doc.pixel_format()); + layer.surface_mut().unwrap().write_pixel(1, 1, &[1.0, 0.0, 0.0, 1.0]); + doc.layers.push(layer); + let mut a = photocraft_doc::AlphaChannel::new("Alpha 1", photocraft_raster::Surface::new(PixelFormat::GRAY8)); + a.opacity = 0.5; + doc.channels.push(a); + let file = document_to_psd(&doc); + let header_extra = usize::from(file.header.channels) - 3; + let names = |id| file.resources.iter().find(|r| r.id == id).map(|r| r.data.clone()).unwrap(); + let pascal = names(1006); + let (mut count, mut i) = (0, 0); + while i < pascal.len() { + count += 1; + i += 1 + usize::from(pascal[i]); + } + assert_eq!((header_extra, count), (2, 2), "transparency + Alpha 1"); + assert_eq!(names(crate::channel_map::DISPLAY_INFO).len(), 4 + 2 * 13); + let back = crate::import("a.psd", &file.to_bytes().unwrap()).unwrap().document; + assert_eq!(back.channels.len(), 1); + assert_eq!(back.channels[0].name, "Alpha 1"); + assert!((back.channels[0].opacity - 0.5).abs() < 1e-6); +} diff --git a/crates/io/src/psd_import.rs b/crates/io/src/psd_import.rs index 07542bf2c6..2a0f982514 100644 --- a/crates/io/src/psd_import.rs +++ b/crates/io/src/psd_import.rs @@ -1333,374 +1333,4 @@ pub(crate) fn psd_to_document_decoded_integrity( } #[cfg(test)] -mod tests { - use super::*; - use photocraft_psd::descriptor::UnicodeString; - use photocraft_psd::resources::VersionInfo; - use photocraft_psd::{Compression, ImageData, ImageResource, PsdError, Version, testgen}; - - /// #5200: the Multichannel fallback checks its RGBA output against the budget before - /// allocating it (here a 2x2 image, 16 bytes, against caps of 15 and 16 bytes). - #[test] - fn flat_fallback_refuses_an_output_over_the_cap() { - let file = testgen::merged_only(Version::Psd, PsdMode::Multichannel, 8, Compression::Raw, 2, 2); - assert!(file.composite_rgba8().is_err(), "Multichannel goes through the fallback"); - let merged = file.decode_merged(); - assert!(matches!(flat_composite(&file, Some(&merged), 15), Err(PsdError::LimitExceeded(_)))); - let img = flat_composite(&file, Some(&merged), 16).unwrap(); - assert_eq!(img.data.len(), 16); - } - - /// #5200: a composite over the budget is not retried by the fallback (which allocated the - /// refused buffer: 14.4 GB for this 60000x60000 Bitmap header). - #[test] - fn flat_fallback_does_not_retry_an_over_budget_composite() { - let mut file = testgen::small(Version::Psb, Compression::Raw); - file.header.color_mode = PsdMode::Bitmap; - file.header.depth = 1; - file.header.channels = 1; - file.header.width = 60_000; - file.header.height = 60_000; - let merged = Ok(vec![0u8; 16]); - let cap = photocraft_psd::compression::MAX_DECODED_BYTES; - assert!(matches!(flat_composite(&file, Some(&merged), cap), Err(PsdError::LimitExceeded(_)))); - } - - /// #5202: a hostile name length ends the list instead of overflowing. - #[test] - fn unicode_names_stop_at_a_hostile_length() { - let mut data = 1u32.to_be_bytes().to_vec(); - data.extend([0, b'A']); - data.extend(u32::MAX.to_be_bytes()); - data.extend([0, b'B']); - assert_eq!(unicode_names(&data), ["A"]); - } - - /// Verifies an unreadable layer channel sets the structured damage indicator. - #[test] - fn unreadable_layer_channel_marks_conversion_damaged() { - let mut file = testgen::small(Version::Psd, Compression::Raw); - let channel = file.layers_mut()[0].channels.iter_mut().find(|c| c.id == 0).unwrap(); - channel.data.clear(); - assert!(file.layers()[0].decode_channel(0, file.header.depth, file.header.version).is_err()); - - let (_, warnings, damaged) = psd_to_document_decoded_integrity(&file, &photocraft_raster::Interrupt::NONE, None).unwrap(); - assert!(damaged); - assert!(warnings.iter().any(|w| w.contains("could not be decoded"))); - } - - /// Verifies an unreadable user-mask channel sets the structured damage indicator. - #[test] - fn unreadable_mask_channel_marks_conversion_damaged() { - let mut file = testgen::small(Version::Psd, Compression::Raw); - let channel = file.layers_mut()[0].channels.iter_mut().find(|c| c.id == CHANNEL_USER_MASK).unwrap(); - channel.data.clear(); - - let (_, warnings, damaged) = psd_to_document_decoded_integrity(&file, &photocraft_raster::Interrupt::NONE, None).unwrap(); - assert!(damaged); - assert!(warnings.iter().any(|w| w.contains("could not be decoded"))); - } - - /// A layer whose bounds hold pixels but whose colour and transparency channels are missing - /// lost its pixel data: the open asks before continuing. - #[test] - fn layer_bounds_without_channel_data_mark_conversion_damaged() { - let mut file = testgen::small(Version::Psd, Compression::Raw); - file.layers_mut()[0].channels.retain(|c| c.id == CHANNEL_USER_MASK); - - let (_, warnings, damaged) = psd_to_document_decoded_integrity(&file, &photocraft_raster::Interrupt::NONE, None).unwrap(); - assert!(damaged); - assert!(warnings.iter().any(|w| w.contains("no channel data"))); - } - - /// A layer without pixels (an empty layer, or a text or shape layer written without a - /// pixel cache) has empty bounds: nothing is missing, so the file is not damaged even when - /// it lists no colour or transparency channel. - #[test] - fn empty_layer_without_channel_data_is_not_damaged() { - let mut file = testgen::small(Version::Psd, Compression::Raw); - file.layers_mut()[0].channels.retain(|c| c.id == CHANNEL_USER_MASK); - file.layers_mut()[0].rect = Default::default(); - - let (_, warnings, damaged) = psd_to_document_decoded_integrity(&file, &photocraft_raster::Interrupt::NONE, None).unwrap(); - assert!(!damaged, "an empty layer marked the PSD damaged: {warnings:?}"); - } - - /// Verifies healthy layer channels do not mark the PSD as damaged. - #[test] - fn valid_layer_channels_keep_conversion_editable() { - let file = testgen::small(Version::Psd, Compression::Raw); - let (_, warnings, damaged) = psd_to_document_decoded_integrity(&file, &photocraft_raster::Interrupt::NONE, None).unwrap(); - assert!(!damaged, "unexpectedly marked good PSD damaged: {warnings:?}"); - } - - #[test] - fn merged_plane_checks_offsets() { - let all = [1u8, 2, 3, 4]; - assert_eq!(merged_plane(&all, 1, 2), Some(&[3u8, 4][..])); - assert_eq!(merged_plane(&all, 2, 2), None); - assert_eq!(merged_plane(&all, usize::MAX, 2), None); - } - - /// Resource 1057's data. - fn version_info(writer: UnicodeString, reader: UnicodeString, has_real_merged_data: bool) -> Vec { - VersionInfo { version: 1, has_real_merged_data, writer, reader, file_version: 1 }.to_bytes() - } - - /// The 1057 PhotoCraft 0.1.0 to 0.7.0 wrote: Photoshop CS6's names, NUL-terminated. - fn version_info_cs6(has_real_merged_data: bool) -> Vec { - version_info(UnicodeString::new_nul("Adobe Photoshop"), UnicodeString::new_nul("Adobe Photoshop CS6"), has_real_merged_data) - } - - /// The 1057 PhotoCraft writes since 0.8.2: Photoshop 2026's bytes, no NUL. - fn version_info_2026(has_real_merged_data: bool) -> Vec { - photocraft_psd::resources::version_info_resource(has_real_merged_data).data - } - - /// An opaque 4 × 1 RGB document with the Photoshop spot oracles' channels in their order: - /// "Spot A", "Alpha 1" and "Spot B", each holding 100, 25, 75 and 0 % in four columns. - fn channels_document(depth: SampleType) -> Document { - let mut doc = Document::with_background("old", Size::new(4, 1), ColorMode::Rgb, depth, photocraft_color::Color::rgb(1.0, 1.0, 1.0)); - let gray = PixelFormat::new(ColorMode::Grayscale, depth, false); - let canvas = doc.bounds(); - let channel = |name: &str, spot: Option<(photocraft_color::Color, f32)>| { - let mut s = Surface::new(gray); - s.write_region(canvas, &[1.0, 0.25, 0.75, 0.0]); - AlphaChannel { spot, ..AlphaChannel::new(name, s) } - }; - doc.channels.push(channel("Spot A", Some((photocraft_color::Color::rgb(0.0, 0.627, 1.0), 0.0)))); - doc.channels.push(channel("Alpha 1", None)); - doc.channels.push(channel("Spot B", Some((photocraft_color::Color::rgb(1.0, 0.0, 0.627), 0.5)))); - doc - } - - /// Each channel's values on an 8-bit scale. - fn ink(doc: &Document) -> Vec> { - doc.channels.iter().map(|c| c.surface.read_region(doc.bounds()).iter().map(|v| (v * 255.0).round() as u8).collect()).collect() - } - - fn spots(doc: &Document) -> Vec { - doc.channels.iter().map(|c| c.spot.is_some()).collect() - } - - /// `doc` (opaque, 8 or 16-bit) saved the way PhotoCraft 0.1.0 to 0.16.0 saved it: spot planes - /// straight (the maximum = solid ink), no 1053, and `version_info` as resource 1057. `padded` - /// lays DisplayInfo out in the 14-byte records of 0.1.0 to 0.7.0. - fn as_earlier_photocraft_saved(doc: &Document, version_info: Vec, padded: bool) -> Vec { - let mut file = crate::psd_export::document_to_psd(doc); - assert!(!file.merged_has_alpha()); - file.resources.retain(|r| r.id != crate::channel_map::ALPHA_IDENTIFIERS); - for r in &mut file.resources { - match r.id { - ids::VERSION_INFO => r.data = version_info.clone(), - crate::channel_map::DISPLAY_INFO if padded => { - let (version, records) = r.data.split_at(4); - r.data = version.iter().copied().chain(records.chunks(13).flat_map(|rec| rec.iter().copied().chain([0]))).collect(); - } - _ => {} - } - } - let mut planes = file.decode_merged().unwrap(); - let plane = planes.len() / usize::from(file.header.channels); - for (k, c) in doc.channels.iter().enumerate() { - if c.spot.is_some() { - // At 8 and 16 bits the complement of a sample is that of each of its bytes. - planes[(3 + k) * plane..(4 + k) * plane].iter_mut().for_each(|b| *b = !*b); - } - } - file.image_data = ImageData::encode(Compression::Raw, &planes, &file.header).unwrap(); - file.to_bytes().unwrap() - } - - /// PSDs that PhotoCraft 0.1.0 to 0.16.0 saved with spot channels store them straight. They - /// open with the ink they had in those versions (which read every plane straight), whichever - /// 1057 they carry. Saved again, they get Photoshop's polarity and a 1053, and reopen with the - /// same ink. (A 0.1.0 to 0.7.0 file's padded records misread every channel's options after - /// the first, here Spot B's kind, as those versions' successors always have; its ink is kept.) - #[test] - fn spot_planes_from_earlier_photocraft_keep_their_ink() { - for depth in [SampleType::U8, SampleType::U16] { - let doc = channels_document(depth); - let cases = [ - ("0.1.0 to 0.7.0", version_info_cs6(true), true), - ("0.8.2 on", version_info_2026(true), false), - ("0.8.2 on, Maximize Compatibility off", version_info_2026(false), false), - ("0.1.0 to 0.7.0, 13-byte records", version_info_cs6(true), false), - ]; - for (what, version_info, padded) in cases { - let bytes = as_earlier_photocraft_saved(&doc, version_info, padded); - assert!(earlier_photocraft_spot_planes(&PsdFile::from_bytes(&bytes).unwrap()), "{what}"); - let opened = crate::import("old.psd", &bytes).unwrap().document; - assert_eq!(ink(&opened), ink(&doc), "{depth:?} {what}: the ink earlier versions opened"); - assert!(spots(&opened)[0], "{depth:?} {what}"); - if !padded { - assert_eq!(spots(&opened), spots(&doc), "{depth:?} {what}"); - } - let saved = crate::export(&opened, "old.psd", &crate::ExportOptions::default()).unwrap(); - let file = PsdFile::from_bytes(&saved.bytes).unwrap(); - assert!(file.resource(crate::channel_map::ALPHA_IDENTIFIERS).is_some() && !earlier_photocraft_spot_planes(&file), "{what}"); - let again = crate::import("again.psd", &saved.bytes).unwrap().document; - assert_eq!(ink(&again), ink(&doc), "{depth:?} {what}: saved again"); - assert_eq!(spots(&again), spots(&opened), "{depth:?} {what}: saved again"); - } - } - } - - /// A 0.1.0 to 0.7.0 file whose first extra channel is an alpha channel, spots after it. In its - /// 14-byte DisplayInfo records the spots' kind bytes sit where a 13-byte reader (main's, and - /// this one's) doesn't look, so only the padded reading finds a spot for the rule. Every plane - /// is then read straight, as those versions read it, and keeps its ink. The 13-byte reader - /// opens each channel's options from shifted bytes, as on main: here every channel opens as - /// an alpha channel. A spot of 2 % solidity puts a 2 where that reader looks for the kind, so - /// that channel opens as a spot: without the rule its plane would be inverted. Saved again and - /// reopened, every channel keeps its ink and kind. - #[test] - fn an_early_file_with_an_alpha_channel_first_keeps_its_ink() { - for solidity in [0.0, 0.02] { - let mut doc = channels_document(SampleType::U8); - doc.channels.swap(0, 1); - doc.channels[1].spot = Some((photocraft_color::Color::rgb(0.0, 0.627, 1.0), solidity)); - let names: Vec<&str> = doc.channels.iter().map(|c| c.name.as_str()).collect(); - assert_eq!(names, ["Alpha 1", "Spot A", "Spot B"]); - let bytes = as_earlier_photocraft_saved(&doc, version_info_cs6(true), true); - let file = PsdFile::from_bytes(&bytes).unwrap(); - let info = &file.resource(crate::channel_map::DISPLAY_INFO).unwrap().data; - let misread = solidity > 0.0; - assert_eq!(crate::channel_map::spot_flags(info, true, 0), [false, misread, false], "{solidity}: 13-byte records"); - assert!(earlier_photocraft_spot_planes(&file), "{solidity}: found in the 14-byte records"); - let opened = crate::import("old.psd", &bytes).unwrap().document; - assert_eq!(ink(&opened), ink(&doc), "{solidity}: the ink 0.7.0 opened"); - assert_eq!(spots(&opened), [false, misread, false], "{solidity}: kinds as main reads them"); - let saved = crate::export(&opened, "old.psd", &crate::ExportOptions::default()).unwrap(); - let again = crate::import("again.psd", &saved.bytes).unwrap().document; - assert_eq!(ink(&again), ink(&doc), "{solidity}: saved again"); - assert_eq!(spots(&again), spots(&opened), "{solidity}: saved again"); - } - } - - /// A file with spots and no 1053 that no earlier PhotoCraft wrote is read in Photoshop's - /// polarity (0 = solid ink). psd-tools' `cmyk-spot.psd` is one: its 1057 names psd-tools as - /// writer and reader. So is a file with no 1057, with Photoshop CS6's names without the NUL, - /// or with bytes after PhotoCraft's. - #[test] - fn other_files_without_alpha_identifiers_use_photoshop_polarity() { - let doc = channels_document(SampleType::U8); - let mut trailing = version_info_2026(true); - trailing.extend([0, 0]); - let cases = [ - ("psd-tools", Some(version_info(UnicodeString::new("psd-tools 1.10.0"), UnicodeString::new("psd-tools 1.10.0"), true))), - ("no 1057", None), - ("CS6 without a NUL", Some(version_info(UnicodeString::new("Adobe Photoshop"), UnicodeString::new("Adobe Photoshop CS6"), true))), - ("bytes after PhotoCraft's 1057", Some(trailing)), - ]; - for (what, info) in cases { - // Photoshop's polarity, as this version writes it, without 1053. - let mut file = crate::psd_export::document_to_psd(&doc); - file.resources.retain(|r| r.id != crate::channel_map::ALPHA_IDENTIFIERS && r.id != ids::VERSION_INFO); - file.resources.extend(info.map(|d| ImageResource::new(ids::VERSION_INFO, d))); - let bytes = file.to_bytes().unwrap(); - assert!(!earlier_photocraft_spot_planes(&PsdFile::from_bytes(&bytes).unwrap()), "{what}"); - let opened = crate::import("x.psd", &bytes).unwrap().document; - assert_eq!(ink(&opened), ink(&doc), "{what}"); - assert_eq!(spots(&opened), spots(&doc), "{what}"); - } - } - - /// The rule needs a spot in DisplayInfo and no 1053, besides PhotoCraft's 1057. - #[test] - fn the_earlier_photocraft_rule_needs_a_spot_and_no_alpha_identifiers() { - let mut doc = channels_document(SampleType::U8); - let old = PsdFile::from_bytes(&as_earlier_photocraft_saved(&doc, version_info_2026(true), false)).unwrap(); - assert!(earlier_photocraft_spot_planes(&old)); - let mut with_ids = old.clone(); - with_ids.resources.push(ImageResource::new(crate::channel_map::ALPHA_IDENTIFIERS, crate::channel_map::alpha_identifiers(false, 3))); - assert!(!earlier_photocraft_spot_planes(&with_ids), "a 1053"); - let mut no_info = old.clone(); - no_info.resources.retain(|r| r.id != crate::channel_map::DISPLAY_INFO); - assert!(!earlier_photocraft_spot_planes(&no_info), "no DisplayInfo"); - doc.channels.retain(|c| c.spot.is_none()); - let alpha_only = PsdFile::from_bytes(&as_earlier_photocraft_saved(&doc, version_info_2026(true), false)).unwrap(); - assert!(!earlier_photocraft_spot_planes(&alpha_only), "alpha channels only"); - } - - /// `doc` as an earlier PhotoCraft saved a Photoshop file it had opened with the first `kept` - /// of `doc`'s channels: it wrote back the Photoshop file's 1053, `stale_ids`, unchanged and - /// those channels' planes as Photoshop stored them (it had read and written them straight), - /// and stored the channels added after them straight. - fn as_earlier_photocraft_resaved(doc: &Document, stale_ids: &[u32], kept: usize) -> Vec { - let mut file = crate::psd_export::document_to_psd(doc); - file.resources.retain(|r| r.id != crate::channel_map::ALPHA_IDENTIFIERS && r.id != ids::VERSION_INFO); - file.resources.push(ImageResource::new(crate::channel_map::ALPHA_IDENTIFIERS, stale_ids.iter().flat_map(|id| id.to_be_bytes()).collect())); - file.resources.push(ImageResource::new(ids::VERSION_INFO, version_info_2026(true))); - let mut planes = file.decode_merged().unwrap(); - let plane = planes.len() / usize::from(file.header.channels); - let first = usize::from(file.header.channels) - doc.channels.len(); - for (k, c) in doc.channels.iter().enumerate().skip(kept) { - if c.spot.is_some() { - planes[(first + k) * plane..(first + k + 1) * plane].iter_mut().for_each(|b| *b = !*b); - } - } - file.image_data = ImageData::encode(Compression::Raw, &planes, &file.header).unwrap(); - file.to_bytes().unwrap() - } - - /// An earlier PhotoCraft kept the 1053 of a Photoshop file it opened and wrote it back - /// unchanged, so a spot channel added there sits behind a 1053 that doesn't list it: a - /// transparent Photoshop document's `[0]` (the white plate of a DTF print, added before - /// saving), the `[0, 3]` of one with a spot channel already, or a `[0]` kept through a - /// flatten that removed the transparency. The added spot is stored straight and keeps its - /// ink; the Photoshop file's own spot keeps Photoshop's polarity. Saved again, both reopen - /// the same. - #[test] - fn a_spot_added_behind_a_kept_alpha_identifiers_resource_keeps_its_ink() { - let transparent = |names: &[&str]| { - let mut doc = channels_document(SampleType::U8); - doc.layers = vec![Layer::raster("Layer 1", doc.pixel_format())]; - doc.channels.retain(|c| names.contains(&c.name.as_str())); - doc - }; - let mut flattened = channels_document(SampleType::U8); - flattened.channels.retain(|c| c.name == "Spot A"); - let cases = [ - ("transparent, one spot added", transparent(&["Spot A"]), vec![0], 0), - ("transparent, a Photoshop spot and one added", transparent(&["Spot A", "Spot B"]), vec![0, 3], 1), - ("flattened, one spot added", flattened, vec![0], 0), - ]; - for (what, doc, stale_ids, kept) in cases { - let bytes = as_earlier_photocraft_resaved(&doc, &stale_ids, kept); - let file = PsdFile::from_bytes(&bytes).unwrap(); - assert_eq!(file.merged_has_alpha(), what.starts_with("transparent"), "{what}"); - assert!(earlier_photocraft_spot_planes(&file), "{what}"); - let opened = crate::import("old.psd", &bytes).unwrap().document; - assert_eq!(ink(&opened), ink(&doc), "{what}: the ink earlier versions opened"); - assert_eq!(spots(&opened), spots(&doc), "{what}"); - let saved = crate::export(&opened, "old.psd", &crate::ExportOptions::default()).unwrap(); - let again = crate::import("again.psd", &saved.bytes).unwrap().document; - assert_eq!(ink(&again), ink(&doc), "{what}: saved again"); - } - } - - /// A 1053 that lists every extra channel, as Photoshop and this version write it, keeps the - /// file in Photoshop's polarity, with PhotoCraft's (Photoshop 2026's) 1057 too: a transparent - /// file with a spot, and Photoshop's own `[0]` in a file without a transparency plane. - #[test] - fn a_complete_alpha_identifiers_resource_keeps_photoshop_polarity() { - let mut doc = channels_document(SampleType::U8); - doc.layers = vec![Layer::raster("Layer 1", doc.pixel_format())]; - let bytes = as_earlier_photocraft_resaved(&doc, &[0, 3, 4, 5], 3); - let file = PsdFile::from_bytes(&bytes).unwrap(); - assert!(file.merged_has_alpha()); - assert!(!earlier_photocraft_spot_planes(&file)); - assert_eq!(ink(&crate::import("ps.psd", &bytes).unwrap().document), ink(&doc)); - let mut opaque = channels_document(SampleType::U8); - opaque.channels.clear(); - let mut file = PsdFile::from_bytes(&as_earlier_photocraft_resaved(&opaque, &[0], 0)).unwrap(); - file.resources.retain(|r| r.id != crate::channel_map::DISPLAY_INFO); - file.resources.push(ImageResource::new( - crate::channel_map::DISPLAY_INFO, - crate::channel_map::display_info(&channels_document(SampleType::U8).channels.iter().collect::>(), false), - )); - assert_eq!(photoshop_identified_channels(&file), 0, "0 is the transparency's"); - assert!(!earlier_photocraft_spot_planes(&file), "no channel left unlisted"); - } -} +mod tests; diff --git a/crates/io/src/psd_import/tests.rs b/crates/io/src/psd_import/tests.rs new file mode 100644 index 0000000000..66c3bb3cdd --- /dev/null +++ b/crates/io/src/psd_import/tests.rs @@ -0,0 +1,369 @@ +use super::*; +use photocraft_psd::descriptor::UnicodeString; +use photocraft_psd::resources::VersionInfo; +use photocraft_psd::{Compression, ImageData, ImageResource, PsdError, Version, testgen}; + +/// #5200: the Multichannel fallback checks its RGBA output against the budget before +/// allocating it (here a 2x2 image, 16 bytes, against caps of 15 and 16 bytes). +#[test] +fn flat_fallback_refuses_an_output_over_the_cap() { + let file = testgen::merged_only(Version::Psd, PsdMode::Multichannel, 8, Compression::Raw, 2, 2); + assert!(file.composite_rgba8().is_err(), "Multichannel goes through the fallback"); + let merged = file.decode_merged(); + assert!(matches!(flat_composite(&file, Some(&merged), 15), Err(PsdError::LimitExceeded(_)))); + let img = flat_composite(&file, Some(&merged), 16).unwrap(); + assert_eq!(img.data.len(), 16); +} + +/// #5200: a composite over the budget is not retried by the fallback (which allocated the +/// refused buffer: 14.4 GB for this 60000x60000 Bitmap header). +#[test] +fn flat_fallback_does_not_retry_an_over_budget_composite() { + let mut file = testgen::small(Version::Psb, Compression::Raw); + file.header.color_mode = PsdMode::Bitmap; + file.header.depth = 1; + file.header.channels = 1; + file.header.width = 60_000; + file.header.height = 60_000; + let merged = Ok(vec![0u8; 16]); + let cap = photocraft_psd::compression::MAX_DECODED_BYTES; + assert!(matches!(flat_composite(&file, Some(&merged), cap), Err(PsdError::LimitExceeded(_)))); +} + +/// #5202: a hostile name length ends the list instead of overflowing. +#[test] +fn unicode_names_stop_at_a_hostile_length() { + let mut data = 1u32.to_be_bytes().to_vec(); + data.extend([0, b'A']); + data.extend(u32::MAX.to_be_bytes()); + data.extend([0, b'B']); + assert_eq!(unicode_names(&data), ["A"]); +} + +/// Verifies an unreadable layer channel sets the structured damage indicator. +#[test] +fn unreadable_layer_channel_marks_conversion_damaged() { + let mut file = testgen::small(Version::Psd, Compression::Raw); + let channel = file.layers_mut()[0].channels.iter_mut().find(|c| c.id == 0).unwrap(); + channel.data.clear(); + assert!(file.layers()[0].decode_channel(0, file.header.depth, file.header.version).is_err()); + + let (_, warnings, damaged) = psd_to_document_decoded_integrity(&file, &photocraft_raster::Interrupt::NONE, None).unwrap(); + assert!(damaged); + assert!(warnings.iter().any(|w| w.contains("could not be decoded"))); +} + +/// Verifies an unreadable user-mask channel sets the structured damage indicator. +#[test] +fn unreadable_mask_channel_marks_conversion_damaged() { + let mut file = testgen::small(Version::Psd, Compression::Raw); + let channel = file.layers_mut()[0].channels.iter_mut().find(|c| c.id == CHANNEL_USER_MASK).unwrap(); + channel.data.clear(); + + let (_, warnings, damaged) = psd_to_document_decoded_integrity(&file, &photocraft_raster::Interrupt::NONE, None).unwrap(); + assert!(damaged); + assert!(warnings.iter().any(|w| w.contains("could not be decoded"))); +} + +/// A layer whose bounds hold pixels but whose colour and transparency channels are missing +/// lost its pixel data: the open asks before continuing. +#[test] +fn layer_bounds_without_channel_data_mark_conversion_damaged() { + let mut file = testgen::small(Version::Psd, Compression::Raw); + file.layers_mut()[0].channels.retain(|c| c.id == CHANNEL_USER_MASK); + + let (_, warnings, damaged) = psd_to_document_decoded_integrity(&file, &photocraft_raster::Interrupt::NONE, None).unwrap(); + assert!(damaged); + assert!(warnings.iter().any(|w| w.contains("no channel data"))); +} + +/// A layer without pixels (an empty layer, or a text or shape layer written without a +/// pixel cache) has empty bounds: nothing is missing, so the file is not damaged even when +/// it lists no colour or transparency channel. +#[test] +fn empty_layer_without_channel_data_is_not_damaged() { + let mut file = testgen::small(Version::Psd, Compression::Raw); + file.layers_mut()[0].channels.retain(|c| c.id == CHANNEL_USER_MASK); + file.layers_mut()[0].rect = Default::default(); + + let (_, warnings, damaged) = psd_to_document_decoded_integrity(&file, &photocraft_raster::Interrupt::NONE, None).unwrap(); + assert!(!damaged, "an empty layer marked the PSD damaged: {warnings:?}"); +} + +/// Verifies healthy layer channels do not mark the PSD as damaged. +#[test] +fn valid_layer_channels_keep_conversion_editable() { + let file = testgen::small(Version::Psd, Compression::Raw); + let (_, warnings, damaged) = psd_to_document_decoded_integrity(&file, &photocraft_raster::Interrupt::NONE, None).unwrap(); + assert!(!damaged, "unexpectedly marked good PSD damaged: {warnings:?}"); +} + +#[test] +fn merged_plane_checks_offsets() { + let all = [1u8, 2, 3, 4]; + assert_eq!(merged_plane(&all, 1, 2), Some(&[3u8, 4][..])); + assert_eq!(merged_plane(&all, 2, 2), None); + assert_eq!(merged_plane(&all, usize::MAX, 2), None); +} + +/// Resource 1057's data. +fn version_info(writer: UnicodeString, reader: UnicodeString, has_real_merged_data: bool) -> Vec { + VersionInfo { version: 1, has_real_merged_data, writer, reader, file_version: 1 }.to_bytes() +} + +/// The 1057 PhotoCraft 0.1.0 to 0.7.0 wrote: Photoshop CS6's names, NUL-terminated. +fn version_info_cs6(has_real_merged_data: bool) -> Vec { + version_info(UnicodeString::new_nul("Adobe Photoshop"), UnicodeString::new_nul("Adobe Photoshop CS6"), has_real_merged_data) +} + +/// The 1057 PhotoCraft writes since 0.8.2: Photoshop 2026's bytes, no NUL. +fn version_info_2026(has_real_merged_data: bool) -> Vec { + photocraft_psd::resources::version_info_resource(has_real_merged_data).data +} + +/// An opaque 4 × 1 RGB document with the Photoshop spot oracles' channels in their order: +/// "Spot A", "Alpha 1" and "Spot B", each holding 100, 25, 75 and 0 % in four columns. +fn channels_document(depth: SampleType) -> Document { + let mut doc = Document::with_background("old", Size::new(4, 1), ColorMode::Rgb, depth, photocraft_color::Color::rgb(1.0, 1.0, 1.0)); + let gray = PixelFormat::new(ColorMode::Grayscale, depth, false); + let canvas = doc.bounds(); + let channel = |name: &str, spot: Option<(photocraft_color::Color, f32)>| { + let mut s = Surface::new(gray); + s.write_region(canvas, &[1.0, 0.25, 0.75, 0.0]); + AlphaChannel { spot, ..AlphaChannel::new(name, s) } + }; + doc.channels.push(channel("Spot A", Some((photocraft_color::Color::rgb(0.0, 0.627, 1.0), 0.0)))); + doc.channels.push(channel("Alpha 1", None)); + doc.channels.push(channel("Spot B", Some((photocraft_color::Color::rgb(1.0, 0.0, 0.627), 0.5)))); + doc +} + +/// Each channel's values on an 8-bit scale. +fn ink(doc: &Document) -> Vec> { + doc.channels.iter().map(|c| c.surface.read_region(doc.bounds()).iter().map(|v| (v * 255.0).round() as u8).collect()).collect() +} + +fn spots(doc: &Document) -> Vec { + doc.channels.iter().map(|c| c.spot.is_some()).collect() +} + +/// `doc` (opaque, 8 or 16-bit) saved the way PhotoCraft 0.1.0 to 0.16.0 saved it: spot planes +/// straight (the maximum = solid ink), no 1053, and `version_info` as resource 1057. `padded` +/// lays DisplayInfo out in the 14-byte records of 0.1.0 to 0.7.0. +fn as_earlier_photocraft_saved(doc: &Document, version_info: Vec, padded: bool) -> Vec { + let mut file = crate::psd_export::document_to_psd(doc); + assert!(!file.merged_has_alpha()); + file.resources.retain(|r| r.id != crate::channel_map::ALPHA_IDENTIFIERS); + for r in &mut file.resources { + match r.id { + ids::VERSION_INFO => r.data = version_info.clone(), + crate::channel_map::DISPLAY_INFO if padded => { + let (version, records) = r.data.split_at(4); + r.data = version.iter().copied().chain(records.chunks(13).flat_map(|rec| rec.iter().copied().chain([0]))).collect(); + } + _ => {} + } + } + let mut planes = file.decode_merged().unwrap(); + let plane = planes.len() / usize::from(file.header.channels); + for (k, c) in doc.channels.iter().enumerate() { + if c.spot.is_some() { + // At 8 and 16 bits the complement of a sample is that of each of its bytes. + planes[(3 + k) * plane..(4 + k) * plane].iter_mut().for_each(|b| *b = !*b); + } + } + file.image_data = ImageData::encode(Compression::Raw, &planes, &file.header).unwrap(); + file.to_bytes().unwrap() +} + +/// PSDs that PhotoCraft 0.1.0 to 0.16.0 saved with spot channels store them straight. They +/// open with the ink they had in those versions (which read every plane straight), whichever +/// 1057 they carry. Saved again, they get Photoshop's polarity and a 1053, and reopen with the +/// same ink. (A 0.1.0 to 0.7.0 file's padded records misread every channel's options after +/// the first, here Spot B's kind, as those versions' successors always have; its ink is kept.) +#[test] +fn spot_planes_from_earlier_photocraft_keep_their_ink() { + for depth in [SampleType::U8, SampleType::U16] { + let doc = channels_document(depth); + let cases = [ + ("0.1.0 to 0.7.0", version_info_cs6(true), true), + ("0.8.2 on", version_info_2026(true), false), + ("0.8.2 on, Maximize Compatibility off", version_info_2026(false), false), + ("0.1.0 to 0.7.0, 13-byte records", version_info_cs6(true), false), + ]; + for (what, version_info, padded) in cases { + let bytes = as_earlier_photocraft_saved(&doc, version_info, padded); + assert!(earlier_photocraft_spot_planes(&PsdFile::from_bytes(&bytes).unwrap()), "{what}"); + let opened = crate::import("old.psd", &bytes).unwrap().document; + assert_eq!(ink(&opened), ink(&doc), "{depth:?} {what}: the ink earlier versions opened"); + assert!(spots(&opened)[0], "{depth:?} {what}"); + if !padded { + assert_eq!(spots(&opened), spots(&doc), "{depth:?} {what}"); + } + let saved = crate::export(&opened, "old.psd", &crate::ExportOptions::default()).unwrap(); + let file = PsdFile::from_bytes(&saved.bytes).unwrap(); + assert!(file.resource(crate::channel_map::ALPHA_IDENTIFIERS).is_some() && !earlier_photocraft_spot_planes(&file), "{what}"); + let again = crate::import("again.psd", &saved.bytes).unwrap().document; + assert_eq!(ink(&again), ink(&doc), "{depth:?} {what}: saved again"); + assert_eq!(spots(&again), spots(&opened), "{depth:?} {what}: saved again"); + } + } +} + +/// A 0.1.0 to 0.7.0 file whose first extra channel is an alpha channel, spots after it. In its +/// 14-byte DisplayInfo records the spots' kind bytes sit where a 13-byte reader (main's, and +/// this one's) doesn't look, so only the padded reading finds a spot for the rule. Every plane +/// is then read straight, as those versions read it, and keeps its ink. The 13-byte reader +/// opens each channel's options from shifted bytes, as on main: here every channel opens as +/// an alpha channel. A spot of 2 % solidity puts a 2 where that reader looks for the kind, so +/// that channel opens as a spot: without the rule its plane would be inverted. Saved again and +/// reopened, every channel keeps its ink and kind. +#[test] +fn an_early_file_with_an_alpha_channel_first_keeps_its_ink() { + for solidity in [0.0, 0.02] { + let mut doc = channels_document(SampleType::U8); + doc.channels.swap(0, 1); + doc.channels[1].spot = Some((photocraft_color::Color::rgb(0.0, 0.627, 1.0), solidity)); + let names: Vec<&str> = doc.channels.iter().map(|c| c.name.as_str()).collect(); + assert_eq!(names, ["Alpha 1", "Spot A", "Spot B"]); + let bytes = as_earlier_photocraft_saved(&doc, version_info_cs6(true), true); + let file = PsdFile::from_bytes(&bytes).unwrap(); + let info = &file.resource(crate::channel_map::DISPLAY_INFO).unwrap().data; + let misread = solidity > 0.0; + assert_eq!(crate::channel_map::spot_flags(info, true, 0), [false, misread, false], "{solidity}: 13-byte records"); + assert!(earlier_photocraft_spot_planes(&file), "{solidity}: found in the 14-byte records"); + let opened = crate::import("old.psd", &bytes).unwrap().document; + assert_eq!(ink(&opened), ink(&doc), "{solidity}: the ink 0.7.0 opened"); + assert_eq!(spots(&opened), [false, misread, false], "{solidity}: kinds as main reads them"); + let saved = crate::export(&opened, "old.psd", &crate::ExportOptions::default()).unwrap(); + let again = crate::import("again.psd", &saved.bytes).unwrap().document; + assert_eq!(ink(&again), ink(&doc), "{solidity}: saved again"); + assert_eq!(spots(&again), spots(&opened), "{solidity}: saved again"); + } +} + +/// A file with spots and no 1053 that no earlier PhotoCraft wrote is read in Photoshop's +/// polarity (0 = solid ink). psd-tools' `cmyk-spot.psd` is one: its 1057 names psd-tools as +/// writer and reader. So is a file with no 1057, with Photoshop CS6's names without the NUL, +/// or with bytes after PhotoCraft's. +#[test] +fn other_files_without_alpha_identifiers_use_photoshop_polarity() { + let doc = channels_document(SampleType::U8); + let mut trailing = version_info_2026(true); + trailing.extend([0, 0]); + let cases = [ + ("psd-tools", Some(version_info(UnicodeString::new("psd-tools 1.10.0"), UnicodeString::new("psd-tools 1.10.0"), true))), + ("no 1057", None), + ("CS6 without a NUL", Some(version_info(UnicodeString::new("Adobe Photoshop"), UnicodeString::new("Adobe Photoshop CS6"), true))), + ("bytes after PhotoCraft's 1057", Some(trailing)), + ]; + for (what, info) in cases { + // Photoshop's polarity, as this version writes it, without 1053. + let mut file = crate::psd_export::document_to_psd(&doc); + file.resources.retain(|r| r.id != crate::channel_map::ALPHA_IDENTIFIERS && r.id != ids::VERSION_INFO); + file.resources.extend(info.map(|d| ImageResource::new(ids::VERSION_INFO, d))); + let bytes = file.to_bytes().unwrap(); + assert!(!earlier_photocraft_spot_planes(&PsdFile::from_bytes(&bytes).unwrap()), "{what}"); + let opened = crate::import("x.psd", &bytes).unwrap().document; + assert_eq!(ink(&opened), ink(&doc), "{what}"); + assert_eq!(spots(&opened), spots(&doc), "{what}"); + } +} + +/// The rule needs a spot in DisplayInfo and no 1053, besides PhotoCraft's 1057. +#[test] +fn the_earlier_photocraft_rule_needs_a_spot_and_no_alpha_identifiers() { + let mut doc = channels_document(SampleType::U8); + let old = PsdFile::from_bytes(&as_earlier_photocraft_saved(&doc, version_info_2026(true), false)).unwrap(); + assert!(earlier_photocraft_spot_planes(&old)); + let mut with_ids = old.clone(); + with_ids.resources.push(ImageResource::new(crate::channel_map::ALPHA_IDENTIFIERS, crate::channel_map::alpha_identifiers(false, 3))); + assert!(!earlier_photocraft_spot_planes(&with_ids), "a 1053"); + let mut no_info = old.clone(); + no_info.resources.retain(|r| r.id != crate::channel_map::DISPLAY_INFO); + assert!(!earlier_photocraft_spot_planes(&no_info), "no DisplayInfo"); + doc.channels.retain(|c| c.spot.is_none()); + let alpha_only = PsdFile::from_bytes(&as_earlier_photocraft_saved(&doc, version_info_2026(true), false)).unwrap(); + assert!(!earlier_photocraft_spot_planes(&alpha_only), "alpha channels only"); +} + +/// `doc` as an earlier PhotoCraft saved a Photoshop file it had opened with the first `kept` +/// of `doc`'s channels: it wrote back the Photoshop file's 1053, `stale_ids`, unchanged and +/// those channels' planes as Photoshop stored them (it had read and written them straight), +/// and stored the channels added after them straight. +fn as_earlier_photocraft_resaved(doc: &Document, stale_ids: &[u32], kept: usize) -> Vec { + let mut file = crate::psd_export::document_to_psd(doc); + file.resources.retain(|r| r.id != crate::channel_map::ALPHA_IDENTIFIERS && r.id != ids::VERSION_INFO); + file.resources.push(ImageResource::new(crate::channel_map::ALPHA_IDENTIFIERS, stale_ids.iter().flat_map(|id| id.to_be_bytes()).collect())); + file.resources.push(ImageResource::new(ids::VERSION_INFO, version_info_2026(true))); + let mut planes = file.decode_merged().unwrap(); + let plane = planes.len() / usize::from(file.header.channels); + let first = usize::from(file.header.channels) - doc.channels.len(); + for (k, c) in doc.channels.iter().enumerate().skip(kept) { + if c.spot.is_some() { + planes[(first + k) * plane..(first + k + 1) * plane].iter_mut().for_each(|b| *b = !*b); + } + } + file.image_data = ImageData::encode(Compression::Raw, &planes, &file.header).unwrap(); + file.to_bytes().unwrap() +} + +/// An earlier PhotoCraft kept the 1053 of a Photoshop file it opened and wrote it back +/// unchanged, so a spot channel added there sits behind a 1053 that doesn't list it: a +/// transparent Photoshop document's `[0]` (the white plate of a DTF print, added before +/// saving), the `[0, 3]` of one with a spot channel already, or a `[0]` kept through a +/// flatten that removed the transparency. The added spot is stored straight and keeps its +/// ink; the Photoshop file's own spot keeps Photoshop's polarity. Saved again, both reopen +/// the same. +#[test] +fn a_spot_added_behind_a_kept_alpha_identifiers_resource_keeps_its_ink() { + let transparent = |names: &[&str]| { + let mut doc = channels_document(SampleType::U8); + doc.layers = vec![Layer::raster("Layer 1", doc.pixel_format())]; + doc.channels.retain(|c| names.contains(&c.name.as_str())); + doc + }; + let mut flattened = channels_document(SampleType::U8); + flattened.channels.retain(|c| c.name == "Spot A"); + let cases = [ + ("transparent, one spot added", transparent(&["Spot A"]), vec![0], 0), + ("transparent, a Photoshop spot and one added", transparent(&["Spot A", "Spot B"]), vec![0, 3], 1), + ("flattened, one spot added", flattened, vec![0], 0), + ]; + for (what, doc, stale_ids, kept) in cases { + let bytes = as_earlier_photocraft_resaved(&doc, &stale_ids, kept); + let file = PsdFile::from_bytes(&bytes).unwrap(); + assert_eq!(file.merged_has_alpha(), what.starts_with("transparent"), "{what}"); + assert!(earlier_photocraft_spot_planes(&file), "{what}"); + let opened = crate::import("old.psd", &bytes).unwrap().document; + assert_eq!(ink(&opened), ink(&doc), "{what}: the ink earlier versions opened"); + assert_eq!(spots(&opened), spots(&doc), "{what}"); + let saved = crate::export(&opened, "old.psd", &crate::ExportOptions::default()).unwrap(); + let again = crate::import("again.psd", &saved.bytes).unwrap().document; + assert_eq!(ink(&again), ink(&doc), "{what}: saved again"); + } +} + +/// A 1053 that lists every extra channel, as Photoshop and this version write it, keeps the +/// file in Photoshop's polarity, with PhotoCraft's (Photoshop 2026's) 1057 too: a transparent +/// file with a spot, and Photoshop's own `[0]` in a file without a transparency plane. +#[test] +fn a_complete_alpha_identifiers_resource_keeps_photoshop_polarity() { + let mut doc = channels_document(SampleType::U8); + doc.layers = vec![Layer::raster("Layer 1", doc.pixel_format())]; + let bytes = as_earlier_photocraft_resaved(&doc, &[0, 3, 4, 5], 3); + let file = PsdFile::from_bytes(&bytes).unwrap(); + assert!(file.merged_has_alpha()); + assert!(!earlier_photocraft_spot_planes(&file)); + assert_eq!(ink(&crate::import("ps.psd", &bytes).unwrap().document), ink(&doc)); + let mut opaque = channels_document(SampleType::U8); + opaque.channels.clear(); + let mut file = PsdFile::from_bytes(&as_earlier_photocraft_resaved(&opaque, &[0], 0)).unwrap(); + file.resources.retain(|r| r.id != crate::channel_map::DISPLAY_INFO); + file.resources.push(ImageResource::new( + crate::channel_map::DISPLAY_INFO, + crate::channel_map::display_info(&channels_document(SampleType::U8).channels.iter().collect::>(), false), + )); + assert_eq!(photoshop_identified_channels(&file), 0, "0 is the transparency's"); + assert!(!earlier_photocraft_spot_planes(&file), "no channel left unlisted"); +} diff --git a/crates/io/src/smart_map.rs b/crates/io/src/smart_map.rs index fcc9eec3f9..2cf5342980 100644 --- a/crates/io/src/smart_map.rs +++ b/crates/io/src/smart_map.rs @@ -48,6 +48,21 @@ mod perspective_warp; pub use displace::{embed_map as displace_embed_map, embedded_map as displace_embedded_map, without_map as displace_without_map}; +mod export; +mod import; +mod placed; + +use export::{blend_options, is_meta, rgbc, set, unit}; +pub use export::{filter_fx, item_for_filter}; +pub use import::filter_from_item; +#[cfg(test)] +use import::{GALLERY_EFFECTS, LENSES, MEZZOTINT_TYPES, adjustment_list, known_params}; +use import::{code, from_hex, int, to_hex}; +use placed::enumv; +pub use placed::{PlacedSpec, plld_bytes, sold_bytes, stored_size}; +#[cfg(test)] +use placed::{quad_moved, warp_desc}; + /// Command id of a Photoshop smart filter PhotoCraft does not implement. Its params hold the /// filter's name, Photoshop filter id and descriptor (`psd`, hex); it renders as a pass-through. pub const UNSUPPORTED_FILTER: &str = "psd.unsupportedFilter"; @@ -135,1459 +150,6 @@ pub fn filter_stack(fx: &Descriptor) -> FilterStack { } } -// ---------- the filters we model ---------- - -/// Photoshop filter → PhotoCraft command, keyed by the `Fltr` class (and `filterID`). -struct Known { - class: &'static str, - filter_id: i32, - /// `Nm ` as Photoshop writes it (the menu item, with its ellipsis and mnemonic). - name: &'static str, - command: &'static str, -} - -/// A four-character PSD code as the big-endian integer Photoshop stores it as. -const fn code(c: &[u8; 4]) -> i32 { - i32::from_be_bytes(*c) -} - -const KNOWN: [Known; 53] = [ - Known { class: "GsnB", filter_id: code(b"GsnB"), name: "Gaussian Blur...", command: "filter.blur.gaussianBlur" }, - Known { class: "boxblur", filter_id: 840, name: "Box Blur...", command: "filter.blur.boxBlur" }, - Known { class: "MtnB", filter_id: code(b"MtnB"), name: "Motion Blur...", command: "filter.blur.motionBlur" }, - // Surface Blur, Smart Blur and Radial Blur: keys, value types and enums measured in Photoshop. - Known { class: "surfaceBlur", filter_id: 1135, name: "Surface Blur...", command: "filter.blur.surfaceBlur" }, - Known { class: "SmrB", filter_id: code(b"SmrB"), name: "Smart Blur...", command: "filter.blur.smartBlur" }, - // Radial Blur at its defaults stores no `Fltr` (`hasoptions` false); that entry is kept verbatim. - Known { class: "RdlB", filter_id: code(b"RdlB"), name: "Radial Blur...", command: "filter.blur.radialBlur" }, - Known { class: "UnsM", filter_id: code(b"UnsM"), name: "Unsharp Mask...", command: "filter.sharpen.unsharpMask" }, - Known { class: "AdNs", filter_id: code(b"AdNs"), name: "Add Noise...", command: "filter.noise.addNoise" }, - Known { class: "Mdn ", filter_id: code(b"Mdn "), name: "Median...", command: "filter.noise.median" }, - Known { class: "HghP", filter_id: code(b"HghP"), name: "High Pass...", command: "filter.other.highPass" }, - Known { class: "Mxm ", filter_id: code(b"Mxm "), name: "Maximum...", command: "filter.other.maximum" }, - Known { class: "Mnm ", filter_id: code(b"Mnm "), name: "Minimum...", command: "filter.other.minimum" }, - Known { class: "Ofst", filter_id: code(b"Ofst"), name: "Offset...", command: "filter.other.offset" }, - Known { class: "Cstm", filter_id: code(b"Cstm"), name: "Custom...", command: "filter.other.custom" }, - Known { class: "Msc ", filter_id: code(b"Msc "), name: "Mosaic...", command: "filter.pixelate.mosaic" }, - Known { class: "Mztn", filter_id: code(b"Mztn"), name: "Mezzotint...", command: "filter.pixelate.mezzotint" }, - Known { class: "ClrH", filter_id: code(b"ClrH"), name: "Color Halftone...", command: "filter.pixelate.colorHalftone" }, - Known { class: "Embs", filter_id: code(b"Embs"), name: "Emboss...", command: "filter.stylize.emboss" }, - Known { class: "Dfs ", filter_id: code(b"Dfs "), name: "Diffuse...", command: "filter.stylize.diffuse" }, - Known { class: "TrcC", filter_id: code(b"TrcC"), name: "Trace Contour...", command: "filter.stylize.traceContour" }, - Known { class: "Crst", filter_id: code(b"Crst"), name: "Crystallize...", command: "filter.pixelate.crystallize" }, - Known { class: "Pntl", filter_id: code(b"Pntl"), name: "Pointillize...", command: "filter.pixelate.pointillize" }, - Known { class: "Wnd ", filter_id: code(b"Wnd "), name: "Wind...", command: "filter.stylize.wind" }, - Known { class: "Extr", filter_id: code(b"Extr"), name: "Extrude...", command: "filter.stylize.extrude" }, - Known { class: "Tls ", filter_id: code(b"Tls "), name: "Tiles...", command: "filter.stylize.tiles" }, - Known { class: "Lvls", filter_id: code(b"Lvls"), name: "Levels...", command: "image.adjustments.levels" }, - Known { class: "Crvs", filter_id: code(b"Crvs"), name: "Curves...", command: "image.adjustments.curves" }, - // Shadows/Highlights at its defaults stores no `Fltr` (`hasoptions` false). - Known { class: "adaptCorrect", filter_id: 781, name: "Shado&ws/Highlights...", command: "image.adjustments.shadowsHighlights" }, - // Filters without options (measured in Photoshop): `hasoptions` false, no `Fltr`, only the - // four-char `filterID`. The class is that code; see `NO_OPTIONS`. - Known { class: "Blr ", filter_id: code(b"Blr "), name: "Blur", command: "filter.blur.blur" }, - Known { class: "BlrM", filter_id: code(b"BlrM"), name: "Blur More", command: "filter.blur.blurMore" }, - Known { class: "Avrg", filter_id: code(b"Avrg"), name: "Average", command: "filter.blur.average" }, - Known { class: "Dspc", filter_id: code(b"Dspc"), name: "Despeckle", command: "filter.noise.despeckle" }, - Known { class: "FndE", filter_id: code(b"FndE"), name: "Find Edges", command: "filter.stylize.findEdges" }, - Known { class: "Fct ", filter_id: code(b"Fct "), name: "Facet", command: "filter.pixelate.facet" }, - Known { class: "Frgm", filter_id: code(b"Frgm"), name: "Fragment", command: "filter.pixelate.fragment" }, - Known { class: "Shrp", filter_id: code(b"Shrp"), name: "Sharpen", command: "filter.sharpen.sharpen" }, - Known { class: "ShrM", filter_id: code(b"ShrM"), name: "Sharpen More", command: "filter.sharpen.sharpenMore" }, - Known { class: "ShrE", filter_id: code(b"ShrE"), name: "Sharpen Edges", command: "filter.sharpen.sharpenEdges" }, - Known { class: "Slrz", filter_id: code(b"Slrz"), name: "Solarize", command: "filter.stylize.solarize" }, - // Smart Sharpen has a numeric filterID and a stringID class, like Box Blur. - Known { class: SMART_SHARPEN, filter_id: 1131, name: "Smart Sharpen...", command: "filter.sharpen.smartSharpen" }, - Known { class: "DstS", filter_id: code(b"DstS"), name: "Dust & Scratches...", command: "filter.noise.dustAndScratches" }, - // Distort (Photoshop 27, `corpus`-style check: one smart object per filter saved from Photoshop - // and read back). Shear isn't mapped yet: its curve lives on Photoshop's own grid. - Known { class: "Pnch", filter_id: code(b"Pnch"), name: "Pinch...", command: "filter.distort.pinch" }, - Known { class: "Plr ", filter_id: code(b"Plr "), name: "Polar Coordinates...", command: "filter.distort.polarCoordinates" }, - Known { class: "Rple", filter_id: code(b"Rple"), name: "Ripple...", command: "filter.distort.ripple" }, - Known { class: "Sphr", filter_id: code(b"Sphr"), name: "Spherize...", command: "filter.distort.spherize" }, - Known { class: "Twrl", filter_id: code(b"Twrl"), name: "Twirl...", command: "filter.distort.twirl" }, - Known { class: "Wave", filter_id: code(b"Wave"), name: "Wave...", command: "filter.distort.wave" }, - Known { class: "ZgZg", filter_id: code(b"ZgZg"), name: "ZigZag...", command: "filter.distort.zigZag" }, - // Image › Adjustments › Invert on a smart object: no settings, so no `Fltr` (`hasoptions` false). - Known { class: "Invr", filter_id: code(b"Invr"), name: "Invert", command: "image.adjustments.invert" }, - Known { class: "LnsF", filter_id: code(b"LnsF"), name: "Lens Flare...", command: "filter.render.lensFlare" }, - // These three also read the item's foreground and background colours (`coloured_params`). - Known { class: "Fbrs", filter_id: code(b"Fbrs"), name: "Fibers...", command: "filter.render.fibers" }, - Known { class: "Clds", filter_id: code(b"Clds"), name: "Clouds", command: "filter.render.clouds" }, - Known { class: "DfrC", filter_id: code(b"DfrC"), name: "Difference Clouds", command: "filter.render.differenceClouds" }, -]; - -/// Lens Flare's `Lns ` enum and our `lens` values. Photoshop's codes keep the old lens names: -/// Nikon 35 mm and 105 mm primes, a Panavision movie prime. -const LENSES: [(&[u8; 4], &str); 4] = [(b"Zm ", "zoom"), (b"Nkn ", "prime35"), (b"Nkn1", "prime105"), (b"PnVs", "moviePrime")]; - -/// Classes of the filters that have no options: Photoshop stores them without a `Fltr`. -const NO_OPTIONS: [&str; 11] = ["Blr ", "BlrM", "Avrg", "Dspc", "FndE", "Fct ", "Frgm", "Shrp", "ShrM", "ShrE", "Slrz"]; - -// ---------- Smart Sharpen and Dust & Scratches ---------- -// -// Measured in Photoshop (applied through Action Manager to a smart object, saved, `filterFX` read -// back): -// -// ```text -// Smart Sharpen (filterID 1131): smartSharpen { presetKind = presetKindType enum (only on the -// default entry), useLegacy bool, Amnt UntF #Prc, Rds UntF #Pxl, noiseReduction UntF #Prc, -// blur = blurType enum (GsnB | lensBlur | MtnB), Angl long (Motion Blur only) } -// Dust & Scratches (filterID DstS): DstS { Rds long, Thsh long } -// ``` -// -// PhotoCraft's Smart Sharpen removes a Gaussian blur, non-legacy: Lens Blur, Motion Blur, legacy -// mode, Shadow/Highlight settings or any other key keep the whole entry verbatim. `presetKind` -// only names the dialog's preset: it is accepted on open but not kept (the engine takes no such -// parameter) and not written (Photoshop leaves it out of entries with explicit values). - -const SMART_SHARPEN: &str = "smartSharpen"; -const SMART_SHARPEN_KEYS: [&str; 6] = ["presetKind", "useLegacy", "Amnt", "Rds ", "noiseReduction", "blur"]; - -/// A `UntF` value in `unit`, finite and within `lo..=hi`. -fn unit_in(d: &Descriptor, key: &str, u: &[u8; 4], lo: f64, hi: f64) -> Option { - match d.get(key)? { - Value::UnitFloat { unit, value } if unit == u && value.is_finite() && (lo..=hi).contains(value) => Some(*value), - _ => None, - } -} - -/// `filter.sharpen.smartSharpen` params; `None` for a setting PhotoCraft doesn't render. -fn smart_sharpen_params(f: &Descriptor) -> Option { - if f.items.iter().any(|(k, _)| !SMART_SHARPEN_KEYS.iter().any(|x| k.is(x))) { - return None; - } - let Some(Value::Boolean(false)) = f.get("useLegacy") else { return None }; - let Some(Value::Enumerated { type_id, value }) = f.get("blur") else { return None }; - if !type_id.is("blurType") || !value.is("GsnB") { - return None; - } - let mut out = Map::new(); - out.insert("amount".into(), json!(unit_in(f, "Amnt", b"#Prc", 1.0, 500.0)?)); - out.insert("radius".into(), json!(unit_in(f, "Rds ", b"#Pxl", 0.1, 64.0)?)); - out.insert("reduceNoise".into(), json!(unit_in(f, "noiseReduction", b"#Prc", 0.0, 100.0)?)); - match f.get("presetKind") { - None => {} - Some(Value::Enumerated { type_id, .. }) if type_id.is("presetKindType") => {} - Some(_) => return None, - } - Some(J::Object(out)) -} - -/// Photoshop enum codes ↔ PhotoCraft parameter values, per filter setting. -const RIPPLE_SIZE: [(&[u8; 4], &str); 3] = [(b"Sml ", "small"), (b"Mdm ", "medium"), (b"Lrg ", "large")]; -const SPHERIZE_MODE: [(&[u8; 4], &str); 3] = [(b"Nrml", "normal"), (b"HrzO", "horizontalOnly"), (b"VrtO", "verticalOnly")]; -const POLAR_MODE: [(&[u8; 4], &str); 2] = [(b"RctP", "rectangularToPolar"), (b"PlrR", "polarToRectangular")]; -const ZIGZAG_STYLE: [(&[u8; 4], &str); 3] = [(b"PndR", "pondRipples"), (b"OtFr", "outFromCenter"), (b"ArnC", "aroundCenter")]; -const WAVE_TYPE: [(&[u8; 4], &str); 3] = [(b"WvSn", "sine"), (b"WvTr", "triangle"), (b"WvSq", "square")]; -const UNDEFINED_AREAS: [(&[u8; 4], &str); 2] = [(b"WrpA", "wrap"), (b"RptE", "repeat")]; - -/// The PSD filter record that PhotoCraft's `command` is written as, if it has one. -fn known_by_command(command: &str) -> Option<&'static Known> { - KNOWN.iter().find(|k| k.command == command) -} - -/// RGB channel references in Levels/Curves (`Chnl` enum) and their parameter keys ("" = the -/// composite: top-level keys). -const CHANNELS: [(&[u8; 4], &str); 4] = [(b"Cmps", ""), (b"Rd ", "red"), (b"Grn ", "green"), (b"Bl ", "blue")]; - -/// Mezzotint's `MztT` enum codes and our `type` values (measured in Photoshop by rendering each). -const MEZZOTINT_TYPES: [(&[u8; 4], &str); 10] = [ - (b"FnDt", "fineDots"), - (b"MdmD", "mediumDots"), - (b"GrnD", "grainyDots"), - (b"CrsD", "coarseDots"), - (b"ShrL", "shortLines"), - (b"MdmL", "mediumLines"), - (b"LngL", "longLines"), - (b"ShSt", "shortStrokes"), - (b"MdmS", "mediumStrokes"), - (b"LngS", "longStrokes"), -]; - -/// Color Halftone's `Rds ` (max radius) and `Ang1`..`Ang4` (screen angles) longs, read within -/// the dialog's ranges; anything else is kept verbatim. -fn color_halftone_params(f: &Descriptor) -> Option { - if !only_keys(f, &["Rds ", "Ang1", "Ang2", "Ang3", "Ang4"]) { - return None; - } - let radius = int(f, "Rds ").filter(|r| (4..=127).contains(r))?; - let angle = |k: &str| int(f, k).filter(|a| (-360..=360).contains(a)); - Some(json!({"maxRadius": radius, "channel1": angle("Ang1")?, "channel2": angle("Ang2")?, "channel3": angle("Ang3")?, "channel4": angle("Ang4")?})) -} - -/// A numeric descriptor item as a finite number; `None` when it is absent, not a number, or not finite. -fn px(d: &Descriptor, key: &str) -> Option { - num(d.get(key)).filter(|v| v.is_finite()) -} - -/// An integer descriptor item; `None` when it is absent or of another type. -fn int(d: &Descriptor, key: &str) -> Option { - match d.get(key)? { - Value::Integer(i) => Some(*i), - _ => None, - } -} - -/// `v` when it lies in `lo..=hi` (the filter dialog's range); out-of-range settings are not -/// opened as editable filters, so a re-save keeps Photoshop's value instead of a clamped one. -fn in_range(v: f64, lo: f64, hi: f64) -> Option { - (lo..=hi).contains(&v).then_some(v) -} - -/// Integer `key` of `f` when it lies in `lo..=hi`. -fn int_in(f: &Descriptor, key: &str, lo: i32, hi: i32) -> Option { - int(f, key).filter(|v| (lo..=hi).contains(v)) -} - -/// True when `f` holds only the given keys, each at most once. A filter with a setting we don't -/// know about (Radial Blur's off-centre centre, for one) or a repeated one is kept verbatim rather -/// than losing that setting. -fn only_keys(f: &Descriptor, keys: &[&str]) -> bool { - f.items.iter().all(|(k, _)| keys.iter().any(|x| k.is(x))) && keys.iter().all(|key| f.items.iter().filter(|(k, _)| k.is(key)).count() <= 1) -} - -/// Our name for enum `key`'s value in `f` (of enum type `type_id`), from `(PSD value, our name)` -/// pairs. An enum of another type is not one we know, so the filter stays verbatim. -fn enum_name(f: &Descriptor, key: &str, type_id: &str, table: &[(&[u8; 4], &'static str)]) -> Option<&'static str> { - let Some(Value::Enumerated { type_id: t, value }) = f.get(key) else { return None }; - if t.as_bytes() != type_id.as_bytes() { - return None; - } - table.iter().find(|(c, _)| value.as_bytes() == &c[..]).map(|(_, n)| *n) -} - -/// True when `f` holds each of the given keys once and nothing else. -fn exact_keys(f: &Descriptor, keys: &[&str]) -> bool { - only_keys(f, keys) && keys.iter().all(|x| f.items.iter().any(|(k, _)| k.is(x))) -} - -/// Finite `key` of `f` stored as a plain double (the type Photoshop writes and we write back). -fn double(f: &Descriptor, key: &str) -> Option { - match f.get(key)? { - Value::Double(v) if v.is_finite() => Some(*v), - _ => None, - } -} - -/// `p[key]` (`default` when absent) when it is a number in `lo..=hi`, the range the filter opens -/// with; anything else is an error, so a saved filter always opens as the same editable filter. -fn pf_range(p: &J, key: &str, default: f64, lo: f64, hi: f64) -> Result { - match p.get(key) { - None | Some(J::Null) => Ok(default), - Some(v) => v.as_f64().filter(|x| (lo..=hi).contains(x)).ok_or_else(|| format!("setting `{key}` ({v}) is not a number in {lo}..={hi}")), - } -} - -/// Integer `p[key]` (rounded; `default` when absent) in `lo..=hi`, as a PSD long. -fn pi_range(p: &J, key: &str, default: f64, lo: i32, hi: i32) -> Result { - let v = pf_range(p, key, default, f64::from(i32::MIN), f64::from(i32::MAX))?.round(); - let range = f64::from(lo)..=f64::from(hi); - if !range.contains(&v) { - return Err(format!("setting `{key}` ({v}) is not a number in {lo}..={hi}")); - } - Ok(Value::Integer(v as i32)) -} - -/// Enum `type_id` holding the PSD value of our name `p[key]` (`default` when absent). -fn enum_param(p: &J, key: &str, default: &str, type_id: &str, table: &[(&[u8; 4], &'static str)]) -> Result { - let name = match p.get(key) { - None | Some(J::Null) => default, - Some(v) => v.as_str().ok_or_else(|| format!("setting `{key}` is not text"))?, - }; - let code = table.iter().find(|(_, n)| *n == name).map(|(c, _)| **c).ok_or_else(|| format!("{key} `{name}` has no PSD equivalent"))?; - Ok(Value::Enumerated { type_id: Id::new(type_id), value: Id::Code(code) }) -} - -/// Smart Blur `SmBQ` / `SmBM` and Radial Blur `BlrM` / `BlrQ` values (measured in Photoshop). -const SMART_BLUR_QUALITY: [(&[u8; 4], &str); 3] = [(b"SBQL", "low"), (b"SBQM", "medium"), (b"SBQH", "high")]; -const SMART_BLUR_MODE: [(&[u8; 4], &str); 3] = [(b"SBMN", "normal"), (b"SBME", "edgeOnly"), (b"SBMO", "overlayEdge")]; -const RADIAL_METHOD: [(&[u8; 4], &str); 2] = [(b"Spn ", "spin"), (b"Zm ", "zoom")]; -const RADIAL_QUALITY: [(&[u8; 4], &str); 3] = [(b"Drft", "draft"), (b"Gd ", "good"), (b"Bst ", "best")]; - -fn channel_key(d: &Descriptor) -> Option<&'static str> { - let Some(Value::Reference(items)) = d.get("Chnl") else { return None }; - let Some(ReferenceItem::Enumerated { value, .. }) = items.first() else { return None }; - CHANNELS.iter().find(|(c, _)| value.as_bytes() == &c[..]).map(|(_, k)| *k) -} - -fn adjustment_list(d: &Descriptor) -> Option> { - let Some(Value::List(items)) = d.get("Adjs") else { return None }; - items - .iter() - .map(|v| match v { - Value::Descriptor(x) => Some(x), - _ => None, - }) - .collect() -} - -fn levels_params(f: &Descriptor) -> Option { - let mut out = Map::new(); - for a in adjustment_list(f)? { - let key = channel_key(a)?; - let mut o = Map::new(); - let pair = |k: &str| match a.get(k) { - Some(Value::List(v)) if v.len() == 2 => Some((int_value(&v[0])?, int_value(&v[1])?)), - _ => None, - }; - if let Some((lo, hi)) = pair("Inpt") { - o.insert("inBlack".into(), json!(lo)); - o.insert("inWhite".into(), json!(hi)); - } - if let Some(g) = px(a, "Gmm ") { - o.insert("gamma".into(), json!(g)); - } - if let Some((lo, hi)) = pair("Otpt") { - o.insert("outBlack".into(), json!(lo)); - o.insert("outWhite".into(), json!(hi)); - } - if key.is_empty() { - out.extend(o); - } else { - out.insert(key.into(), J::Object(o)); - } - } - Some(J::Object(out)) -} - -fn int_value(v: &Value) -> Option { - match v { - Value::Integer(i) => Some(*i), - _ => None, - } -} - -fn curves_params(f: &Descriptor) -> Option { - let mut out = Map::new(); - for a in adjustment_list(f)? { - let key = channel_key(a)?; - // A pencil-drawn curve is a mapping of 256 output levels (`Mpng`) instead of points. - if let Some(Value::List(map)) = a.get("Mpng") { - let map: Option> = map.iter().map(|v| int_value(v).map(|o| json!(o.clamp(0, 255)))).collect(); - out.insert(if key.is_empty() { "points".into() } else { key.into() }, J::Array(map.filter(|m| m.len() == 256)?)); - out.insert("pencil".into(), J::Bool(true)); - continue; - } - let Some(Value::List(pts)) = a.get("Crv ") else { return None }; - let pts: Option> = pts - .iter() - .map(|p| match p { - Value::Descriptor(p) => Some(json!([px(p, "Hrzn")?, px(p, "Vrtc")?])), - _ => None, - }) - .collect(); - out.insert(if key.is_empty() { "points".into() } else { key.into() }, J::Array(pts?)); - } - Some(J::Object(out)) -} - -/// Diffuse's `Md ` (`DfsM` enum, measured in Photoshop) ↔ our `mode`. -const DIFFUSE_MODES: [(&str, &str); 4] = [("Nrml", "normal"), ("DrkO", "darkenOnly"), ("LghO", "lightenOnly"), ("anisotropic", "anisotropic")]; - -/// Trace Contour's `Edg ` (`CntE` enum, measured in Photoshop) ↔ our `edge`. -const TRACE_EDGES: [(&str, &str); 2] = [("Upr ", "upper"), ("Lwr ", "lower")]; - -/// Our name for the enum value of `key` (of type `type_id`) through `table` (Photoshop's value, ours). -fn enum_from(d: &Descriptor, key: &str, type_id: &str, table: &[(&str, &'static str)]) -> Option<&'static str> { - let Some(Value::Enumerated { type_id: t, value }) = d.get(key) else { return None }; - if t.as_bytes() != type_id.as_bytes() { - return None; - } - table.iter().find(|(psd, _)| value.as_bytes() == psd.as_bytes()).map(|(_, ours)| *ours) -} - -// Wind, Extrude and Tiles, measured in Photoshop (each code changes the rendered result). - -/// Wind's `WndM` (enum `WndM`) ↔ our `method`. -const WIND_METHODS: [(&str, &str); 3] = [("Wnd ", "wind"), ("Blst", "blast"), ("Stgr", "stagger")]; -/// Wind's `Drct` (enum `Drct`) ↔ our `direction`. Photoshop's `Left` streaks extend to the left -/// of an edge, which is our wind from the right. -const WIND_DIRECTIONS: [(&str, &str); 2] = [("Left", "fromRight"), ("Rght", "fromLeft")]; -/// Extrude's `ExtT` (enum `ExtT`) ↔ our `type`. -const EXTRUDE_TYPES: [(&str, &str); 2] = [("Blks", "blocks"), ("Pyrm", "pyramids")]; -/// Extrude's `ExtR` (enum `ExtR`) ↔ our `depthMode`. -const EXTRUDE_DEPTHS: [(&str, &str); 2] = [("Rndm", "random"), ("LvlB", "levelBased")]; -/// Tiles' `FlCl` (enum `FlCl`) ↔ our `fill`. -const TILE_FILLS: [(&str, &str); 4] = [("FlBc", "background"), ("FlFr", "foreground"), ("FlIn", "inverse"), ("FlSm", "unaltered")]; -/// Extrude's size and depth (`ExtS`, `ExtD`) and Tiles' count and offset (`TlNm`, `TlOf`), all -/// `long`s, in the engine's (and Photoshop's dialog) ranges. -const EXTRUDE_SIZE: (i32, i32) = (2, 255); -const EXTRUDE_DEPTH: (i32, i32) = (1, 255); -const TILE_COUNT: (i32, i32) = (1, 99); -const TILE_OFFSET: (i32, i32) = (1, 99); - -/// The `bool` at `key`. -fn bool_at(d: &Descriptor, key: &str) -> Option { - match d.get(key)? { - Value::Boolean(b) => Some(*b), - _ => None, - } -} - -/// Tiles' params; background and foreground fills use the colours the entry carries (`FrgC`, -/// `BckC`). `None` when a setting or a colour that is there can't be read. -fn tiles_params(f: &Descriptor, item: &Descriptor) -> Option { - let mut out = Map::new(); - out.insert("count".into(), json!(int_in(f, "TlNm", TILE_COUNT.0, TILE_COUNT.1)?)); - out.insert("maxOffset".into(), json!(int_in(f, "TlOf", TILE_OFFSET.0, TILE_OFFSET.1)?)); - out.insert("fill".into(), json!(enum_from(f, "FlCl", "FlCl", &TILE_FILLS)?)); - for (psd, ours) in [("FrgC", "foreground"), ("BckC", "background")] { - if item.get(psd).is_some() { - out.insert(ours.into(), get_desc(item, psd).and_then(rgbc_colour)?); - } - } - Some(J::Object(out)) -} - -/// Offset › Undefined Areas: the `FlMd` enum (`Fl `) and our `undefinedAreas`. On a layer -/// Photoshop labels `Bckg` "Set to Transparent"; a smart object is always a layer. -const OFFSET_FILL: [(&str, &str); 3] = [("Wrp ", "wrap"), ("Rpt ", "repeat"), ("Bckg", "transparent")]; - -/// Custom's ranges in Photoshop's dialog: matrix cells, Scale, Offset. -const CUSTOM_CELL: (i32, i32) = (-999, 999); -const CUSTOM_SCALE: (i32, i32) = (1, 9999); -const CUSTOM_OFFSET: (i32, i32) = (-9999, 9999); - -/// `v` when it lies in `lo..=hi`. -fn long_in_range(v: Option, (lo, hi): (i32, i32)) -> Option { - v.filter(|v| (lo..=hi).contains(v)) -} - -/// `filter.other.custom` params for a `Cstm` filter: `Mtrx` is 25 longs, row-major 5 × 5. Values -/// outside Photoshop's ranges are not modelled (the filter stays verbatim). -fn custom_params(f: &Descriptor) -> Option { - if !only_keys(f, &["Mtrx", "Scl ", "Ofst"]) { - return None; - } - let Some(Value::List(m)) = f.get("Mtrx") else { return None }; - if m.len() != 25 { - return None; - } - let kernel: Option> = m.iter().map(|v| long_in_range(int_value(v), CUSTOM_CELL).map(|v| json!(v))).collect(); - let scale = long_in_range(int(f, "Scl "), CUSTOM_SCALE)?; - let offset = long_in_range(int(f, "Ofst"), CUSTOM_OFFSET)?; - Some(json!({"kernel": kernel?, "scale": scale, "offset": offset})) -} - -/// The settings of Photoshop's Wave, as it writes them (and we write them back). -const WAVE_KEYS: [&str; 10] = ["Wvtp", "NmbG", "WLMn", "WLMx", "AmMn", "AmMx", "SclH", "SclV", "UndA", "RndS"]; - -/// Our command and parameters for a known Photoshop filter; `None` when the filter (or one of its -/// settings) is not modelled. `item` is the whole `filterFX` entry (Pointillize reads its `BckC`, -/// Tiles its colours). -fn known_params(class: &str, f: Option<&Descriptor>, item: &Descriptor) -> Option<(&'static str, J)> { - let k = KNOWN.iter().find(|k| k.class == class)?; - let params = match (class, f) { - ("adaptCorrect" | "Invr", None) => json!({}), - (c, None) if NO_OPTIONS.contains(&c) => json!({}), - (_, None) => return None, - // Exactly the settings Photoshop writes (and we write back); an extra or repeated one keeps - // the filter verbatim rather than lose it on save. - ("Pnch", Some(f)) if exact_keys(f, &["Amnt"]) => json!({"amount": int(f, "Amnt")?}), - ("Twrl", Some(f)) if exact_keys(f, &["Angl"]) => json!({"angle": int(f, "Angl")?}), - ("Rple", Some(f)) if exact_keys(f, &["Amnt", "RplS"]) => json!({"amount": int(f, "Amnt")?, "size": enum_name(f, "RplS", "RplS", &RIPPLE_SIZE)?}), - ("Sphr", Some(f)) if exact_keys(f, &["Amnt", "SphM"]) => json!({"amount": int(f, "Amnt")?, "mode": enum_name(f, "SphM", "SphM", &SPHERIZE_MODE)?}), - ("Plr ", Some(f)) if exact_keys(f, &["Cnvr"]) => json!({"mode": enum_name(f, "Cnvr", "Cnvr", &POLAR_MODE)?}), - ("ZgZg", Some(f)) if exact_keys(f, &["Amnt", "NmbR", "ZZTy"]) => { - json!({"amount": int(f, "Amnt")?, "ridges": int(f, "NmbR")?, "style": enum_name(f, "ZZTy", "ZZTy", &ZIGZAG_STYLE)?}) - } - ("Wave", Some(f)) if exact_keys(f, &WAVE_KEYS) => { - // PhotoCraft's Wave has no Scale: a scaled wave stays verbatim rather than lose it. The - // same for more generators than the renderer models, which would draw fewer than - // Photoshop did (and than the file asks for, once its cached pixels are re-rendered). - let generators = int(f, "NmbG")?; - let modelled = u32::try_from(generators).is_ok_and(|g| (1..=photocraft_algo::MAX_WAVE_GENERATORS).contains(&g)); - if int(f, "SclH")? != 100 || int(f, "SclV")? != 100 || !modelled { - return None; - } - json!({ - "type": enum_name(f, "Wvtp", "Wvtp", &WAVE_TYPE)?, - "generators": generators, - "wavelengthMin": int(f, "WLMn")?, - "wavelengthMax": int(f, "WLMx")?, - "amplitudeMin": int(f, "AmMn")?, - "amplitudeMax": int(f, "AmMx")?, - "undefinedAreas": enum_name(f, "UndA", "UndA", &UNDEFINED_AREAS)?, - // `RndS` is a signed long; the seed is its bit pattern. - "seed": (int(f, "RndS")? as u32), - }) - } - ("GsnB" | "boxblur" | "Mdn " | "HghP" | "Mxm " | "Mnm ", Some(f)) => json!({"radius": px(f, "Rds ")?}), - ("MtnB", Some(f)) => json!({"angle": int(f, "Angl")?, "distance": px(f, "Dstn")?}), - ("UnsM", Some(f)) => json!({"amount": px(f, "Amnt")?, "radius": px(f, "Rds ")?, "threshold": int(f, "Thsh")?}), - ("AdNs", Some(f)) => { - let dist = match enum_of(f, "Dstr")? { - b"Unfr" => "uniform", - b"Gsn " => "gaussian", - _ => return None, - }; - let mono = match f.get("Mnch") { - Some(Value::Boolean(b)) => *b, - _ => return None, - }; - json!({"amount": px(f, "Nose")?, "distribution": dist, "monochromatic": mono, "seed": int(f, "FlRs").unwrap_or(0)}) - } - ("surfaceBlur", Some(f)) if only_keys(f, &["Rds ", "Thsh"]) => json!({ - "radius": unit_in(f, "Rds ", b"#Pxl", 1.0, 100.0)?, - "threshold": int_in(f, "Thsh", 2, 255)?, - }), - ("SmrB", Some(f)) if only_keys(f, &["Rds ", "Thsh", "SmBQ", "SmBM"]) => json!({ - "radius": in_range(double(f, "Rds ")?, 0.1, 100.0)?, - "threshold": in_range(double(f, "Thsh")?, 0.1, 100.0)?, - "quality": enum_name(f, "SmBQ", "SmBQ", &SMART_BLUR_QUALITY)?, - "mode": enum_name(f, "SmBM", "SmBM", &SMART_BLUR_MODE)?, - }), - ("RdlB", Some(f)) if only_keys(f, &["Amnt", "BlrM", "BlrQ"]) => json!({ - "amount": int_in(f, "Amnt", 1, 100)?, - "method": enum_name(f, "BlrM", "BlrM", &RADIAL_METHOD)?, - "quality": enum_name(f, "BlrQ", "BlrQ", &RADIAL_QUALITY)?, - }), - ("Msc ", Some(f)) => json!({"cellSize": px(f, "ClSz")?}), - ("Mztn", Some(f)) if only_keys(f, &["MztT"]) => json!({"type": enum_name(f, "MztT", "MztT", &MEZZOTINT_TYPES)?}), - ("ClrH", Some(f)) => color_halftone_params(f)?, - ("Embs", Some(f)) => json!({"angle": int(f, "Angl")?, "height": int(f, "Hght")?, "amount": int(f, "Amnt")?}), - (SMART_SHARPEN, Some(f)) => smart_sharpen_params(f)?, - ("DstS", Some(f)) => { - if f.items.iter().any(|(k, _)| !k.is("Rds ") && !k.is("Thsh")) { - return None; - } - json!({"radius": int_in(f, "Rds ", 1, 500)?, "threshold": int_in(f, "Thsh", 0, 255)?}) - } - ("Dfs ", Some(f)) => json!({"mode": enum_from(f, "Md ", "DfsM", &DIFFUSE_MODES)?}), - ("TrcC", Some(f)) => json!({"level": int_in(f, "Lvl ", 0, 255)?, "edge": enum_from(f, "Edg ", "CntE", &TRACE_EDGES)?}), - ("Crst", Some(f)) => json!({"cellSize": int_in(f, "ClSz", CELL_SIZE.0, CELL_SIZE.1)?}), - ("Pntl", Some(f)) => { - let mut p = json!({"cellSize": int_in(f, "ClSz", CELL_SIZE.0, CELL_SIZE.1)?}); - // Pointillize paints the gaps in the background colour the entry carries. - if item.get("BckC").is_some() { - p["background"] = get_desc(item, "BckC").and_then(rgbc_colour)?; - } - p - } - ("Wnd ", Some(f)) => json!({ - "method": enum_from(f, "WndM", "WndM", &WIND_METHODS)?, - "direction": enum_from(f, "Drct", "Drct", &WIND_DIRECTIONS)?, - }), - ("Extr", Some(f)) => json!({ - "type": enum_from(f, "ExtT", "ExtT", &EXTRUDE_TYPES)?, - "size": int_in(f, "ExtS", EXTRUDE_SIZE.0, EXTRUDE_SIZE.1)?, - "depth": int_in(f, "ExtD", EXTRUDE_DEPTH.0, EXTRUDE_DEPTH.1)?, - "depthMode": enum_from(f, "ExtR", "ExtR", &EXTRUDE_DEPTHS)?, - "solidFrontFaces": bool_at(f, "ExtF")?, - "maskIncompleteBlocks": bool_at(f, "ExtM")?, - }), - ("Tls ", Some(f)) => tiles_params(f, item)?, - ("Ofst", Some(f)) if only_keys(f, &["Hrzn", "Vrtc", "Fl "]) => { - json!({"horizontal": int(f, "Hrzn")?, "vertical": int(f, "Vrtc")?, "undefinedAreas": enum_from(f, "Fl ", "FlMd", &OFFSET_FILL)?}) - } - ("Cstm", Some(f)) => custom_params(f)?, - // Only the settings and value types Photoshop writes (and we write back); anything else - // keeps the filter verbatim. - ("LnsF", Some(f)) if exact_keys(f, &["Brgh", "FlrC", "Lns "]) => { - let centre = get_desc(f, "FlrC").filter(|c| c.class_id.is("Pnt ") && exact_keys(c, &["Hrzn", "Vrtc"]))?; - let lens = enum_name(f, "Lns ", "Lns ", &LENSES)?; - json!({"brightness": int(f, "Brgh")?, "centerX": double(centre, "Hrzn")?, "centerY": double(centre, "Vrtc")?, "lens": lens}) - } - ("Lvls", Some(f)) => levels_params(f)?, - ("Crvs", Some(f)) => curves_params(f)?, - _ => return None, - }; - Some((k.command, params)) -} - -// ---------- Filter Gallery ---------- -// -// Filter › Filter Gallery stores its effect stack in a `GEfc` filter (filterID `GEfc`). Photoshop -// writes a single effect inline; Photopea writes a list (also for one effect): -// -// ```text -// Fltr = GEfc { GEfk = GEft enum (the effect), } (Photoshop) -// Fltr = GEfc { GEfs = [ GEfc { , GEfk = GEft enum, GELv = visible } ] } (Photopea) -// ``` -// -// The list is in application order, like `filter.filterGallery`'s `effects`. The item's -// `FrgC`/`BckC` are the colours the Sketch effects read. Only effects whose settings we know are -// mapped; a stack with any other effect (or setting) stays an [`UNSUPPORTED_FILTER`]. - -const GALLERY_CLASS: &str = "GEfc"; -const GALLERY_COMMAND: &str = "filter.filterGallery"; -const GALLERY_NAME: &str = "Filter Gallery..."; - -/// One gallery effect: our filter key, Photoshop's `GEft` code and its settings (PSD key, our key). -struct GalleryCode { - key: &'static str, - code: &'static str, - settings: &'static [(&'static str, &'static str)], -} - -const GALLERY_EFFECTS: [GalleryCode; 1] = [GalleryCode { key: "chrome", code: "Chrm", settings: &[("Dtl ", "detail"), ("Smth", "smoothness")] }]; - -/// An `RGBC` descriptor (0–255 channels) as straight `[r, g, b, a]`, 0–1. -fn rgbc_colour(d: &Descriptor) -> Option { - let c = |k: &str| px(d, k).map(|v| (v / 255.0).clamp(0.0, 1.0)); - Some(json!([c("Rd ")?, c("Grn ")?, c("Bl ")?, 1.0])) -} - -/// Fibers, Clouds and Difference Clouds draw with the item's foreground and background colours: -/// their params are the `Fltr` settings plus those colours. -fn coloured_params(class: &str, item: &Descriptor, f: &Descriptor) -> Option<(&'static str, J)> { - let k = KNOWN.iter().find(|k| k.class == class)?; - // An `RGBC` of three `doub`s in 0–255, as Photoshop writes it (and we write it back); any - // other colour keeps the filter verbatim. - let colour = |key: &str| { - get_desc(item, key) - .filter(|c| c.class_id.is("RGBC") && exact_keys(c, &["Rd ", "Grn ", "Bl "])) - .filter(|c| ["Rd ", "Grn ", "Bl "].iter().all(|k| double(c, k).is_some_and(|v| (0.0..=255.0).contains(&v)))) - .and_then(rgbc_colour) - }; - // Only the settings Photoshop writes; an extra or repeated one keeps the filter verbatim. - let keys: &[&str] = if class == "Fbrs" { &["Vrnc", "Strg", "RndS"] } else { &["FlRs"] }; - if !exact_keys(f, keys) { - return None; - } - // The seeds (`RndS`, `FlRs`) are signed longs; ours is their bit pattern. - let mut p = match class { - "Fbrs" => json!({"variance": int(f, "Vrnc")?, "strength": int(f, "Strg")?, "seed": int(f, "RndS")? as u32}), - _ => json!({"seed": int(f, "FlRs")? as u32}), - }; - let o = p.as_object_mut()?; - o.insert("foreground".into(), colour("FrgC")?); - o.insert("background".into(), colour("BckC")?); - Some((k.command, p)) -} - -fn seed_param(p: &J) -> Value { - Value::Integer(p.get("seed").and_then(J::as_u64).and_then(|n| u32::try_from(n).ok()).unwrap_or(0) as i32) -} - -/// `filter.filterGallery` params for a `GEfc` filter item; `None` when an effect or setting is -/// not modelled. -fn gallery_params(item: &Descriptor, f: &Descriptor) -> Option { - let list: Vec<&Descriptor> = match f.get("GEfs") { - Some(Value::List(list)) => list - .iter() - .map(|v| match v { - Value::Descriptor(e) => Some(e), - _ => None, - }) - .collect::>()?, - Some(_) => return None, - None if f.get("GEfk").is_some() => vec![f], - None => return None, - }; - let mut effects = Vec::with_capacity(list.len()); - for e in list { - let code = enum_of(e, "GEfk")?; - let g = GALLERY_EFFECTS.iter().find(|g| g.code.as_bytes() == code)?; - let mut params = Map::new(); - for (k, v) in &e.items { - if k.is("GEfk") || k.is("GELv") { - continue; - } - let (_, ours) = g.settings.iter().find(|(psd, _)| k.is(psd))?; - params.insert((*ours).into(), json!(int_value(v)?)); - } - effects.push(json!({"filter": g.key, "params": params, "visible": bool_or(e, "GELv", true)})); - } - if effects.is_empty() { - return None; - } - let mut out = Map::new(); - out.insert("effects".into(), J::Array(effects)); - for (psd, ours) in [("FrgC", "foreground"), ("BckC", "background")] { - if let Some(c) = get_desc(item, psd).and_then(rgbc_colour) { - out.insert(ours.into(), c); - } - } - Some(J::Object(out)) -} - -fn colour_rgb(v: &J) -> Option<[f64; 3]> { - match v { - J::Array(a) => Some([a.first()?.as_f64()?, a.get(1)?.as_f64()?, a.get(2)?.as_f64()?]), - J::String(h) if h.len() == 7 && h.starts_with('#') => { - let ch = |j: usize| h.get(j..j + 2).and_then(|s| u8::from_str_radix(s, 16).ok()).map(|v| f64::from(v) / 255.0); - Some([ch(1)?, ch(3)?, ch(5)?]) - } - _ => None, - } -} - -/// A `[r, g, b(, a)]` (0–1) or `#rrggbb` colour param as an `RGBC` descriptor (0–255). -fn colour_rgbc(v: Option<&J>, default: f64) -> Result { - let Some(v) = v else { return Ok(rgbc(default)) }; - let rgb = colour_rgb(v).filter(|c| c.iter().all(|v| v.is_finite())).ok_or("a colour is not [r, g, b] or #rrggbb")?; - let c = |v: f64| Value::Double(v.clamp(0.0, 1.0) * 255.0); - Ok(Value::Descriptor(Descriptor::new("RGBC").with("Rd ", c(rgb[0])).with("Grn ", c(rgb[1])).with("Bl ", c(rgb[2])))) -} - -/// The `filterFXList` item for a `filter.filterGallery` smart filter. -fn gallery_item(f: &SmartFilter) -> Result { - let p = &f.params; - if let Some(k) = p.as_object().and_then(|o| o.keys().find(|k| !is_meta(k) && !["effects", "foreground", "background"].contains(&k.as_str()))) { - return Err(format!("setting `{k}` has no PSD equivalent")); - } - let list = p.get("effects").and_then(J::as_array).ok_or("it has no effects")?; - let mut out = Vec::with_capacity(list.len()); - for e in list { - let key = e.get("filter").and_then(J::as_str).ok_or("an effect has no `filter`")?; - let g = GALLERY_EFFECTS.iter().find(|g| g.key == key).ok_or_else(|| format!("gallery effect `{key}` has no PSD equivalent"))?; - let params = e.get("params").filter(|v| v.is_object()).unwrap_or(e); - if let Some(k) = params.as_object().and_then(|o| { - o.keys().find(|k| !is_meta(k) && !["filter", "params", "visible"].contains(&k.as_str()) && !g.settings.iter().any(|(_, ours)| ours == k)) - }) { - return Err(format!("gallery setting `{key}.{k}` has no PSD equivalent")); - } - let defaults = photocraft_algo::GalleryFilter::from_key(key).map(photocraft_algo::GalleryEffect::new); - let settings: Vec<(&str, Value)> = - g.settings.iter().map(|(psd, ours)| (*psd, pi(params, ours, defaults.as_ref().map_or(0.0, |x| f64::from(x.get(ours)))))).collect(); - out.push((g.code, settings, e.get("visible").and_then(J::as_bool).unwrap_or(true))); - } - let gallery = || { - let mut d = Descriptor::new(GALLERY_CLASS); - d.name = UnicodeString::new_nul("Filter Gallery"); - d - }; - // One visible effect: inline, as Photoshop writes it. Otherwise the effect list. - let fltr = match out.as_slice() { - [] => return Err("it has no effects".into()), - [(code, settings, true)] => settings.iter().fold(gallery().with("GEfk", enumv("GEft", code)), |d, (k, v)| d.with(k, v.clone())), - _ => { - let list = out - .into_iter() - .map(|(code, settings, visible)| { - let d = settings.into_iter().fold(gallery(), |d, (k, v)| d.with(k, v)); - Value::Descriptor(d.with("GEfk", enumv("GEft", code)).with("GELv", Value::Boolean(visible))) - }) - .collect(); - gallery().with("GEfs", Value::List(list)) - } - }; - Ok(Descriptor::new("filterFX") - .with("Nm ", Value::Text(UnicodeString::new_nul(GALLERY_NAME))) - .with("blendOptions", blend_options(f)) - .with("enab", Value::Boolean(f.visible)) - .with("hasoptions", Value::Boolean(true)) - .with("FrgC", colour_rgbc(p.get("foreground"), 0.0)?) - .with("BckC", colour_rgbc(p.get("background"), 255.0)?) - .with("Fltr", Value::Descriptor(fltr)) - .with("filterID", Value::Integer(code(b"GEfc")))) -} - -/// Lowercase hex of `bytes`. -fn to_hex(bytes: &[u8]) -> String { - const H: &[u8; 16] = b"0123456789abcdef"; - let mut s = String::with_capacity(bytes.len() * 2); - for b in bytes { - s.push(char::from(H[usize::from(b >> 4)])); - s.push(char::from(H[usize::from(b & 15)])); - } - s -} - -fn from_hex(s: &str) -> Option> { - let d = |c: u8| (c as char).to_digit(16).map(|v| v as u8); - let b = s.as_bytes(); - if !b.len().is_multiple_of(2) { - return None; - } - b.as_chunks::<2>().0.iter().map(|c| Some(d(c[0])? << 4 | d(c[1])?)).collect() -} - -/// One `filterFXList` item → [`SmartFilter`] (an [`UNSUPPORTED_FILTER`] when not modelled). -pub fn filter_from_item(item: &Descriptor) -> SmartFilter { - let opts = get_desc(item, "blendOptions"); - let opacity = opts.and_then(|o| px(o, "Opct")).map_or(1.0, |v| (v / 100.0).clamp(0.0, 1.0) as f32); - let blend = opts.and_then(|o| enum_of(o, "Md ")).and_then(crate::effects_map::blend_from_id).unwrap_or(BlendMode::Normal); - let visible = bool_or(item, "enab", true); - let fltr = get_desc(item, "Fltr"); - let class = fltr.map(|f| String::from_utf8_lossy(f.class_id.as_bytes()).into_owned()); - let filter_id = int(item, "filterID").unwrap_or(0); - let class = class.or_else(|| KNOWN.iter().find(|k| k.filter_id == filter_id).map(|k| k.class.to_string())); - let known = match class.as_deref() { - Some(camera_raw::CLASS) => camera_raw::import_params(item).map(|p| (camera_raw::COMMAND, p)), - Some(displace::CLASS) => displace::import_params(item).map(|p| (displace::COMMAND, p)), - Some(hue_sat::CLASS) => fltr.and_then(hue_sat::import_params).map(|p| (hue_sat::COMMAND, p)), - Some(perspective_warp::CLASS) => perspective_warp::import_params(item).map(|p| (perspective_warp::COMMAND, p)), - Some(GALLERY_CLASS) => fltr.and_then(|f| gallery_params(item, f)).map(|p| (GALLERY_COMMAND, p)), - Some(c @ ("Fbrs" | "Clds" | "DfrC")) => fltr.and_then(|f| coloured_params(c, item, f)), - // A `Fltr` that is there but not a descriptor is settings we can't read: kept verbatim - // rather than taken for a filter stored without options (which would drop it on save). - _ if fltr.is_none() && item.get("Fltr").is_some() => None, - c => c.and_then(|c| known_params(c, fltr, item)), - }; - let (command, params) = match known { - Some((c, p)) => (c.to_string(), p), - None => { - let name = text_of(item, "Nm ").unwrap_or_default(); - // The stored descriptor carries neutral blending (the model's own fields replace - // them on export), so hiding or re-blending the filter leaves its params alone. - let mut neutral = item.clone(); - for (k, v) in &mut neutral.items { - if k.is("blendOptions") { - *v = blend_options(&SmartFilter { command: String::new(), params: J::Null, blend: BlendMode::Normal, opacity: 1.0, visible: true }); - } else if k.is("enab") { - *v = Value::Boolean(true); - } - } - (UNSUPPORTED_FILTER.to_string(), json!({"name": name.replace('&', ""), "filterID": filter_id, "psd": to_hex(&neutral.to_bytes())})) - } - }; - SmartFilter { command, params, blend, opacity, visible } -} - -// ---------- writing ---------- - -fn unit(u: &[u8; 4], v: f64) -> Value { - Value::UnitFloat { unit: *u, value: v } -} - -fn rgbc(v: f64) -> Value { - Value::Descriptor(Descriptor::new("RGBC").with("Rd ", Value::Double(v)).with("Grn ", Value::Double(v)).with("Bl ", Value::Double(v))) -} - -fn blend_options(f: &SmartFilter) -> Value { - let opacity = if f.opacity.is_finite() { f64::from(f.opacity.clamp(0.0, 1.0)) * 100.0 } else { 100.0 }; - Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", opacity)).with("Md ", crate::effects_map::blend_long_value(f.blend))) -} - -/// Parameter keys that are bookkeeping, not filter settings. -fn is_meta(k: &str) -> bool { - k == "layer" || k.starts_with("__") -} - -fn pf(p: &J, key: &str, default: f64) -> f64 { - p.get(key).and_then(J::as_f64).filter(|v| v.is_finite()).unwrap_or(default) -} - -fn pi(p: &J, key: &str, default: f64) -> Value { - Value::Integer(pf(p, key, default).round().clamp(f64::from(i32::MIN), f64::from(i32::MAX)) as i32) -} - -/// A whole-number setting as a long, clamped to `range` like the engine clamps it; a fraction -/// has no PSD equivalent (Photoshop stores these as integers). -fn whole(v: f64, (lo, hi): (i32, i32), what: &str) -> Result { - if v.fract() != 0.0 { - return Err(format!("{what} ({v}) is not a whole number")); - } - Ok(Value::Integer(v.clamp(f64::from(lo), f64::from(hi)) as i32)) -} - -fn channel_ref(code: &[u8; 4]) -> Value { - Value::Reference(vec![ReferenceItem::Enumerated { - class: Class { name: UnicodeString::new_nul(""), class_id: Id::new("Chnl") }, - type_id: Id::new("Chnl"), - value: Id::Code(*code), - }]) -} - -/// The `Adjs` entries of a Levels or Curves filter: the composite first, then red, green, blue. -fn adjustments(p: &J, curves: bool) -> Result { - let obj = p.as_object().ok_or("parameters are not an object")?; - let allowed: &[&str] = - if curves { &["points", "red", "green", "blue", "pencil"] } else { &["inBlack", "inWhite", "gamma", "outBlack", "outWhite", "red", "green", "blue"] }; - if let Some(k) = obj.keys().find(|k| !is_meta(k) && !allowed.contains(&k.as_str())) { - return Err(format!("setting `{k}` has no PSD equivalent")); - } - let mut list = Vec::new(); - for (code, key) in CHANNELS { - let o = if key.is_empty() { Some(p) } else { p.get(key) }; - let Some(o) = o else { continue }; - let mut a = Descriptor::new(if curves { "CrvA" } else { "LvlA" }).with("Chnl", channel_ref(code)); - if curves { - let src = if key.is_empty() { p.get("points") } else { Some(o) }; - let Some(pts) = src.and_then(J::as_array) else { continue }; - if p.get("pencil").and_then(J::as_bool) == Some(true) { - let map: Option> = - pts.iter().map(|o| o.as_f64().filter(|o| o.is_finite()).map(|o| Value::Integer(o.round().clamp(0.0, 255.0) as i32))).collect(); - a = a.with("Mpng", Value::List(map.filter(|m| m.len() == 256).ok_or("a pencil-drawn curve is not 256 output levels")?)); - list.push(Value::Descriptor(a)); - continue; - } - let pts: Option> = pts - .iter() - .map(|q| { - let x = q.get(0)?.as_f64().filter(|v| v.is_finite())?; - let y = q.get(1)?.as_f64().filter(|v| v.is_finite())?; - Some(Value::Descriptor(Descriptor::new("Pnt ").with("Hrzn", Value::Double(x)).with("Vrtc", Value::Double(y)))) - }) - .collect(); - a = a.with("Crv ", Value::List(pts.ok_or("a curve point is not [input, output]")?)); - } else { - if key.is_empty() && !["inBlack", "inWhite", "gamma", "outBlack", "outWhite"].iter().any(|k| o.get(k).is_some()) { - continue; - } - a = a.with("Inpt", Value::List(vec![pi(o, "inBlack", 0.0), pi(o, "inWhite", 255.0)])).with("Gmm ", Value::Double(pf(o, "gamma", 1.0))); - if o.get("outBlack").is_some() || o.get("outWhite").is_some() { - a = a.with("Otpt", Value::List(vec![pi(o, "outBlack", 0.0), pi(o, "outWhite", 255.0)])); - } - } - list.push(Value::Descriptor(a)); - } - Ok(Value::List(list)) -} - -/// Crystallize's and Pointillize's cell size range (`ClSz`, a `long`). -const CELL_SIZE: (i32, i32) = (3, 300); - -/// Our `key` (a string) as Photoshop's enum value through `table` (Photoshop's value, ours). -fn enum_out(p: &J, key: &str, default: &str, type_id: &str, table: &[(&str, &str)]) -> Result { - let ours = match p.get(key) { - None => default, - Some(v) => v.as_str().ok_or_else(|| format!("`{key}` is not a string"))?, - }; - let (psd, _) = table.iter().find(|(_, o)| *o == ours).ok_or_else(|| format!("{key} `{ours}` has no PSD equivalent"))?; - Ok(enumv(type_id, psd)) -} - -/// `key` rounded to a `long` in `lo..=hi`. -fn pi_in(p: &J, key: &str, default: f64, lo: i32, hi: i32) -> Value { - Value::Integer(pf(p, key, default).round().clamp(f64::from(lo), f64::from(hi)) as i32) -} - -/// Param `key` as a `bool` (false when absent or not a bool, as the engine reads it). -fn bool_param(p: &J, key: &str) -> Value { - Value::Boolean(p.get(key).and_then(J::as_bool).unwrap_or(false)) -} - -/// The `Fltr` descriptor of a modelled filter (`None` = written without options). -fn fltr_for(k: &Known, p: &J) -> Result, String> { - let d = Descriptor::new(k.class); - Ok(Some(match k.class { - "GsnB" | "boxblur" | "Mdn " | "HghP" | "Mxm " | "Mnm " => { - if p.get("preserve").and_then(J::as_str).is_some_and(|s| s == "roundness") { - return Err("“preserve roundness” has no PSD equivalent".into()); - } - d.with("Rds ", unit(b"#Pxl", pf(p, "radius", 1.0))) - } - "MtnB" => d.with("Angl", pi(p, "angle", 0.0)).with("Dstn", unit(b"#Pxl", pf(p, "distance", 10.0))), - "UnsM" => d.with("Amnt", unit(b"#Prc", pf(p, "amount", 50.0))).with("Rds ", unit(b"#Pxl", pf(p, "radius", 1.0))).with("Thsh", pi(p, "threshold", 0.0)), - "AdNs" => { - let gauss = p.get("distribution").and_then(J::as_str) == Some("gaussian"); - d.with("Dstr", Value::Enumerated { type_id: Id::new("Dstr"), value: Id::new(if gauss { "Gsn " } else { "Unfr" }) }) - .with("Nose", unit(b"#Prc", pf(p, "amount", 12.5))) - .with("Mnch", Value::Boolean(p.get("monochromatic").and_then(J::as_bool).unwrap_or(false))) - .with("FlRs", pi(p, "seed", 0.0)) - } - "surfaceBlur" => d.with("Rds ", unit(b"#Pxl", pf_range(p, "radius", 5.0, 1.0, 100.0)?)).with("Thsh", pi_range(p, "threshold", 15.0, 2, 255)?), - "SmrB" => d - .with("Rds ", Value::Double(pf_range(p, "radius", 3.0, 0.1, 100.0)?)) - .with("Thsh", Value::Double(pf_range(p, "threshold", 25.0, 0.1, 100.0)?)) - .with("SmBQ", enum_param(p, "quality", "high", "SmBQ", &SMART_BLUR_QUALITY)?) - .with("SmBM", enum_param(p, "mode", "normal", "SmBM", &SMART_BLUR_MODE)?), - "RdlB" => { - // Photoshop wrote no centre key for a centred blur; an off-centre one is unmeasured. - for k in ["centerX", "centerY"] { - if (pf_range(p, k, 0.5, 0.0, 1.0)? - 0.5).abs() > 1e-9 { - return Err("an off-centre Radial Blur centre is not written to PSD".into()); - } - } - d.with("Amnt", pi_range(p, "amount", 10.0, 1, 100)?) - .with("BlrM", enum_param(p, "method", "spin", "BlrM", &RADIAL_METHOD)?) - .with("BlrQ", enum_param(p, "quality", "good", "BlrQ", &RADIAL_QUALITY)?) - } - "Msc " => d.with("ClSz", unit(b"#Pxl", pf(p, "cellSize", 10.0))), - // Photoshop's Mezzotint has no seed (it is random on every render), so `seed` is not saved. - "Mztn" => { - let t = p.get("type").and_then(J::as_str).unwrap_or("fineDots"); - let code = MEZZOTINT_TYPES.iter().find(|(_, k)| *k == t).map_or(b"FnDt", |(c, _)| *c); - d.with("MztT", Value::Enumerated { type_id: Id::new("MztT"), value: Id::Code(*code) }) - } - "ClrH" => { - // Longs within the dialog's ranges (what the engine accepts: radius 4..127, angles ±360). - let long = |key: &str, default: f64, lo: f64, hi: f64| Value::Integer(pf(p, key, default).round().clamp(lo, hi) as i32); - d.with("Rds ", long("maxRadius", 8.0, 4.0, 127.0)) - .with("Ang1", long("channel1", 108.0, -360.0, 360.0)) - .with("Ang2", long("channel2", 162.0, -360.0, 360.0)) - .with("Ang3", long("channel3", 90.0, -360.0, 360.0)) - .with("Ang4", long("channel4", 45.0, -360.0, 360.0)) - } - "Embs" => d.with("Angl", pi(p, "angle", 135.0)).with("Hght", pi(p, "height", 3.0)).with("Amnt", pi(p, "amount", 100.0)), - SMART_SHARPEN => { - // The engine's defaults and ranges (it clamps the same way when rendering). - d.with("useLegacy", Value::Boolean(false)) - .with("Amnt", unit(b"#Prc", pf(p, "amount", 100.0).clamp(1.0, 500.0))) - .with("Rds ", unit(b"#Pxl", pf(p, "radius", 1.0).clamp(0.1, 64.0))) - .with("noiseReduction", unit(b"#Prc", pf(p, "reduceNoise", 10.0).clamp(0.0, 100.0))) - .with("blur", enumv("blurType", "GsnB")) - } - // Photoshop stores whole pixels and levels. - "DstS" => { - let whole = |key: &str, default: f64, lo: f64, hi: f64| Value::Integer(pf(p, key, default).round().clamp(lo, hi) as i32); - d.with("Rds ", whole("radius", 1.0, 1.0, 500.0)).with("Thsh", whole("threshold", 0.0, 0.0, 255.0)) - } - // Photoshop stores no random seed for these: `seed` is ours only and is not written. - "Dfs " => d.with("Md ", enum_out(p, "mode", "normal", "DfsM", &DIFFUSE_MODES)?), - "TrcC" => d.with("Lvl ", pi_in(p, "level", 128.0, 0, 255)).with("Edg ", enum_out(p, "edge", "lower", "CntE", &TRACE_EDGES)?), - "Crst" => d.with("ClSz", pi_in(p, "cellSize", 10.0, CELL_SIZE.0, CELL_SIZE.1)), - "Pntl" => d.with("ClSz", pi_in(p, "cellSize", 5.0, CELL_SIZE.0, CELL_SIZE.1)), - // Photoshop stores no random seed for these: our `seed` is not written. - "Wnd " => { - d.with("WndM", enum_out(p, "method", "wind", "WndM", &WIND_METHODS)?).with("Drct", enum_out(p, "direction", "fromRight", "Drct", &WIND_DIRECTIONS)?) - } - "Extr" => d - .with("ExtT", enum_out(p, "type", "blocks", "ExtT", &EXTRUDE_TYPES)?) - .with("ExtS", pi_in(p, "size", 30.0, EXTRUDE_SIZE.0, EXTRUDE_SIZE.1)) - .with("ExtD", pi_in(p, "depth", 30.0, EXTRUDE_DEPTH.0, EXTRUDE_DEPTH.1)) - .with("ExtR", enum_out(p, "depthMode", "random", "ExtR", &EXTRUDE_DEPTHS)?) - .with("ExtF", bool_param(p, "solidFrontFaces")) - .with("ExtM", bool_param(p, "maskIncompleteBlocks")), - "Tls " => d - .with("TlNm", pi_in(p, "count", 10.0, TILE_COUNT.0, TILE_COUNT.1)) - .with("TlOf", pi_in(p, "maxOffset", 10.0, TILE_OFFSET.0, TILE_OFFSET.1)) - .with("FlCl", enum_out(p, "fill", "background", "FlCl", &TILE_FILLS)?), - "Ofst" => { - // As the engine reads it: anything but repeat / transparent wraps. - let ours = p.get("undefinedAreas").and_then(J::as_str).unwrap_or("wrap"); - let fill = OFFSET_FILL.iter().find(|(_, o)| *o == ours).map_or("Wrp ", |(psd, _)| *psd); - d.with("Hrzn", pi(p, "horizontal", 0.0)).with("Vrtc", pi(p, "vertical", 0.0)).with("Fl ", enumv("FlMd", fill)) - } - "Cstm" => { - // The engine's identity kernel when none is given; missing cells are 0. - let kernel = p.get("kernel").and_then(J::as_array); - let cell = |i: usize| match kernel { - Some(a) => a.get(i).and_then(J::as_f64).filter(|v| v.is_finite()).unwrap_or(0.0), - None => f64::from(u8::from(i == 12)), - }; - let m = (0..25).map(|i| whole(cell(i), CUSTOM_CELL, "a kernel value")).collect::, _>>()?; - d.with("Scl ", whole(pf(p, "scale", 1.0), CUSTOM_SCALE, "Scale")?) - .with("Ofst", whole(pf(p, "offset", 0.0), CUSTOM_OFFSET, "Offset")?) - .with("Mtrx", Value::List(m)) - } - "LnsF" => { - let lens = p.get("lens").and_then(J::as_str).unwrap_or("zoom"); - let code = LENSES.iter().find(|(_, l)| *l == lens).ok_or_else(|| format!("lens `{lens}` has no PSD equivalent"))?.0; - let mut centre = Descriptor::new("Pnt ").with("Hrzn", Value::Double(pf(p, "centerX", 0.5))).with("Vrtc", Value::Double(pf(p, "centerY", 0.5))); - centre.name = UnicodeString::new_nul(""); - d.with("Brgh", pi(p, "brightness", 100.0)) - .with("FlrC", Value::Descriptor(centre)) - .with("Lns ", Value::Enumerated { type_id: Id::new("Lns "), value: Id::Code(*code) }) - } - "Fbrs" => d.with("Vrnc", pi(p, "variance", 16.0)).with("Strg", pi(p, "strength", 4.0)).with("RndS", seed_param(p)), - "Clds" | "DfrC" => d.with("FlRs", seed_param(p)), - "Lvls" => d.with("Adjs", adjustments(p, false)?), - "Crvs" => d.with("Adjs", adjustments(p, true)?), - "adaptCorrect" => { - if p.as_object().is_some_and(|o| o.keys().any(|k| !is_meta(k))) { - return Err("only default Shadows/Highlights settings are written to PSD".into()); - } - return Ok(None); - } - // No settings to write; any parameter keys an old record carries have no effect on the - // filter either, so nothing is lost. - c if NO_OPTIONS.contains(&c) => return Ok(None), - // Keys and order as Photoshop writes them. - "Pnch" => d.with("Amnt", pi(p, "amount", 50.0)), - "Twrl" => d.with("Angl", pi(p, "angle", 50.0)), - "Rple" => d.with("Amnt", pi(p, "amount", 100.0)).with("RplS", enum_param(p, "size", "medium", "RplS", &RIPPLE_SIZE)?), - "Sphr" => d.with("Amnt", pi(p, "amount", 100.0)).with("SphM", enum_param(p, "mode", "normal", "SphM", &SPHERIZE_MODE)?), - "Plr " => d.with("Cnvr", enum_param(p, "mode", "rectangularToPolar", "Cnvr", &POLAR_MODE)?), - "ZgZg" => { - d.with("Amnt", pi(p, "amount", 10.0)).with("NmbR", pi(p, "ridges", 5.0)).with("ZZTy", enum_param(p, "style", "pondRipples", "ZZTy", &ZIGZAG_STYLE)?) - } - "Wave" => { - // The seed the renderer draws with (engine `filters::seed`): a u32, else a legacy signed - // or fractional seed, rounded and saturated, as its bit pattern. - let seed = match p.get("seed").and_then(J::as_u64).and_then(|s| u32::try_from(s).ok()) { - Some(s) => Value::Integer(s as i32), - None => pi(p, "seed", 0.0), - }; - // The renderer draws at most MAX_WAVE_GENERATORS: write what PhotoCraft rendered, so - // Photoshop doesn't draw more generators than the user saw. - let generators = pf(p, "generators", 5.0).round().clamp(1.0, f64::from(photocraft_algo::MAX_WAVE_GENERATORS)) as i32; - d.with("Wvtp", enum_param(p, "type", "sine", "Wvtp", &WAVE_TYPE)?) - .with("NmbG", Value::Integer(generators)) - .with("WLMn", pi(p, "wavelengthMin", 10.0)) - .with("WLMx", pi(p, "wavelengthMax", 120.0)) - .with("AmMn", pi(p, "amplitudeMin", 5.0)) - .with("AmMx", pi(p, "amplitudeMax", 35.0)) - .with("SclH", Value::Integer(100)) - .with("SclV", Value::Integer(100)) - .with("UndA", enum_param(p, "undefinedAreas", "wrap", "UndA", &UNDEFINED_AREAS)?) - .with("RndS", seed) - } - "Invr" => return Ok(None), - _ => return Err("not a recognized filter".into()), - })) -} - -/// The `filterFXList` item for one smart filter, or why it can't be written. -pub fn item_for_filter(f: &SmartFilter) -> Result { - if f.command == camera_raw::COMMAND { - let mut d = camera_raw::export_item(&f.params)?; - set(&mut d, "blendOptions", blend_options(f)); - set(&mut d, "enab", Value::Boolean(f.visible)); - return Ok(d); - } - if f.command == displace::COMMAND { - let mut d = displace::export_item(&f.params)?; - set(&mut d, "blendOptions", blend_options(f)); - set(&mut d, "enab", Value::Boolean(f.visible)); - return Ok(d); - } - if f.command == GALLERY_COMMAND { - return gallery_item(f); - } - if f.command == hue_sat::COMMAND { - return hue_sat::export_item(f); - } - if perspective_warp::handles(&f.command) { - return perspective_warp::export_item(f); - } - if f.command == UNSUPPORTED_FILTER { - let raw = f.params.get("psd").and_then(J::as_str).and_then(from_hex).ok_or("its filter data is missing")?; - let mut d = Descriptor::from_bytes(&raw).map_err(|e| format!("its filter data is unreadable ({e})"))?; - set(&mut d, "blendOptions", blend_options(f)); - set(&mut d, "enab", Value::Boolean(f.visible)); - return Ok(d); - } - let k = known_by_command(&f.command).ok_or("this filter has no PSD equivalent")?; - let fltr = fltr_for(k, &f.params)?; - // Pointillize's background, Tiles' colours and the render filters' colours are the entry's; - // the others store Photoshop's defaults. - let (fg, bg) = match k.class { - "Pntl" => (rgbc(0.0), colour_rgbc(f.params.get("background"), 255.0)?), - "Tls " | "Fbrs" | "Clds" | "DfrC" => (colour_rgbc(f.params.get("foreground"), 0.0)?, colour_rgbc(f.params.get("background"), 255.0)?), - _ => (rgbc(0.0), rgbc(255.0)), - }; - // The render filters are written with the descriptor names Photoshop gives them: the filter's - // own name on `Fltr` and empty ones on the colours. - let render = matches!(k.class, "Fbrs" | "Clds" | "DfrC" | "LnsF"); - let (fltr, fg, bg) = if render { (fltr.map(|f| named(f, k.name.trim_end_matches("..."))), named_value(fg), named_value(bg)) } else { (fltr, fg, bg) }; - let mut d = Descriptor::new("filterFX") - .with("Nm ", Value::Text(UnicodeString::new_nul(k.name))) - .with("blendOptions", blend_options(f)) - .with("enab", Value::Boolean(f.visible)) - .with("hasoptions", Value::Boolean(fltr.is_some())) - .with("FrgC", fg) - .with("BckC", bg); - if let Some(x) = fltr { - d = d.with("Fltr", Value::Descriptor(x)); - } - Ok(d.with("filterID", Value::Integer(k.filter_id))) -} - -fn named(mut d: Descriptor, name: &str) -> Descriptor { - d.name = UnicodeString::new_nul(name); - d -} - -fn named_value(v: Value) -> Value { - match v { - Value::Descriptor(d) => Value::Descriptor(named(d, "")), - other => other, - } -} - -/// Builds a `filterFX` object; filters that can't be written are left out, with a message each. -pub fn filter_fx(stack: &FilterStack, layer: &str, warnings: &mut Vec) -> Descriptor { - let mut list = Vec::new(); - for f in &stack.filters { - match item_for_filter(f) { - Ok(d) => list.push(Value::Descriptor(d)), - Err(e) => warnings.push(format!("layer \"{layer}\": smart filter {} was not written to PSD: {e}", f.command)), - } - } - Descriptor::new("filterFXStyle") - .with("enab", Value::Boolean(stack.enabled)) - .with("validAtPosition", Value::Boolean(true)) - .with("filterMaskEnable", Value::Boolean(stack.mask_enabled)) - .with("filterMaskLinked", Value::Boolean(stack.mask_linked)) - .with("filterMaskExtendWithWhite", Value::Boolean(true)) - .with("filterFXList", Value::List(list)) -} - -/// Replaces item `key` in place, or appends it. -fn set(d: &mut Descriptor, key: &str, v: Value) { - match d.items.iter_mut().find(|(k, _)| k.is(key)) { - Some(e) => e.1 = v, - None => d.items.push((Id::new(key), v)), - } -} - -/// Replaces item `key` in place, or inserts it before item `before` (appends it without one). -fn set_before(d: &mut Descriptor, key: &str, v: Value, before: &str) { - if let Some(e) = d.items.iter_mut().find(|(k, _)| k.is(key)) { - e.1 = v; - return; - } - let at = d.items.iter().position(|(k, _)| k.is(before)).unwrap_or(d.items.len()); - d.items.insert(at, (Id::new(key), v)); -} - -/// Everything needed to write the placed-layer blocks of a smart object. -#[derive(Clone, Debug)] -pub struct PlacedSpec<'a> { - pub idnt: &'a str, - pub placed: &'a str, - /// Source pixels → document pixels. - pub transform: Affine, - /// Distort / Perspective: the full projective map (row-major 3×3), overriding `transform`. - pub perspective: Option<[f64; 9]>, - /// Source size in pixels. - pub size: (f64, f64), - /// Source resolution. - pub dpi: f64, - pub warp: Option<&'a Warp>, - /// `filterFX`, when the smart object has filters. - pub filter_fx: Option, -} - -/// Where the frame corners land (top-left, top-right, bottom-right, bottom-left), as x, y pairs. -/// The frame is [`crate::blocks::placed_frame`] of `warp`, the warp the block stores, for an -/// affine placement (the inverse of `parse_smart`), [`crate::blocks::perspective_frame`] of it -/// for a projective one (as `parse_smart_perspective` reads it). -fn quad_points(s: &PlacedSpec<'_>, warp: Option<&Warp>) -> [f64; 8] { - let (w, h) = s.size; - let [a, b, c, d, e, f] = s.transform.m; - let map = |x: f64, y: f64| match &s.perspective { - Some(p) => photocraft_algo::transform::Homography(*p).apply(x, y), - None => (a * x + c * y + e, b * x + d * y + f), - }; - let [x0, y0, x1, y1] = if s.perspective.is_some() { crate::blocks::perspective_frame(warp, w, h) } else { crate::blocks::placed_frame(warp, w, h) }; - let mut out = [0.0; 8]; - for (i, (x, y)) in [(x0, y0), (x1, y0), (x1, y1), (x0, y1)].into_iter().enumerate() { - (out[2 * i], out[2 * i + 1]) = map(x, y); - } - out -} - -/// The transform quad: the source corners (top-left, top-right, bottom-right, bottom-left). -fn quad(s: &PlacedSpec<'_>, warp: Option<&Warp>) -> Value { - Value::List(quad_points(s, warp).into_iter().map(Value::Double).collect()) -} - -/// Has the placement moved from the quad a template descriptor stores (`Trnf`)? -fn quad_moved(template: &Descriptor, s: &PlacedSpec<'_>, warp: Option<&Warp>) -> bool { - let Some(Value::List(pts)) = template.get("Trnf") else { return true }; - let old: Vec = pts.iter().filter_map(|v| crate::blocks::num(Some(v))).collect(); - let new = quad_points(s, warp); - old.len() != 8 || old.iter().zip(new).any(|(a, b)| (a - b).abs() > 1e-6 * (1.0 + a.abs())) -} - -fn enumv(t: &str, v: &str) -> Value { - Value::Enumerated { type_id: Id::new(t), value: Id::new(v) } -} - -/// The mesh of a split warp: a custom warp of more than one patch, which `SoLd` stores as -/// `quiltWarp` and `PlLd` can't store. -fn split_mesh(w: Option<&Warp>) -> Option<&BezierMesh> { - w.filter(|w| w.style == WarpStyle::Custom).and_then(|w| w.mesh.as_ref()).filter(|m| m.points.len() != 16 && m.is_valid()) -} - -/// The warp `SoLd` stores: none, with a message, for a split warp of more patches along a side -/// than a `quiltWarp` is read with, so its corners are framed by the source rect as on reopen. -fn sold_warp<'a>(w: Option<&'a Warp>, warnings: &mut Vec) -> Option<&'a Warp> { - let too_big = split_mesh(w).is_some_and(|m| m.us.len().max(m.vs.len()) > crate::blocks::QUILT_MAX_PATCHES + 1); - if too_big { - warnings.push(format!("a split warp of more than {} patches along a side was written to PSD without its warp", crate::blocks::QUILT_MAX_PATCHES)); - return None; - } - w -} - -/// Style, bend, distortions, axis, bounds and order: the keys a `warp` and a `quiltWarp` -/// descriptor share, in Photoshop's order. -fn warp_head(class: &str, w: &Warp) -> Descriptor { - let [x0, y0, x1, y1] = w.bounds; - let bounds = Descriptor::new("classFloatRect") - .with("Top ", Value::Double(y0)) - .with("Left", Value::Double(x0)) - .with("Btom", Value::Double(y1)) - .with("Rght", Value::Double(x1)); - let d = Descriptor::new(class).with("warpStyle", enumv("warpStyle", w.style.psd_name())).with("warpValue", Value::Double(w.bend)); - // A cylinder is stored as its seven `warpValues` (#4112). - let d = if w.style == WarpStyle::Cylinder { d.with("warpValues", Value::List(w.values.iter().copied().map(Value::Double).collect())) } else { d }; - d.with("warpPerspective", Value::Double(w.h_distort)) - .with("warpPerspectiveOther", Value::Double(w.v_distort)) - .with("warpRotate", enumv("Ornt", if w.vertical { "Vrtc" } else { "Hrzn" })) - .with("bounds", Value::Descriptor(bounds)) - .with("uOrder", Value::Integer(4)) - .with("vOrder", Value::Integer(4)) -} - -/// The control points of a custom warp: an object array of their x and y. -fn mesh_points(m: &BezierMesh) -> Value { - let body = Descriptor::new("rationalPoint") - .with("Hrzn", Value::UnitFloats { unit: *b"#Pxl", values: m.points.iter().map(|p| p[0]).collect() }) - .with("Vrtc", Value::UnitFloats { unit: *b"#Pxl", values: m.points.iter().map(|p| p[1]).collect() }); - Value::ObjectArray(ObjectArray { prefix: m.points.len() as u32, body }) -} - -/// The `warp` descriptor (also the `PlLd` warp). A split warp is written as no warp: `SoLd` -/// keeps it in `quiltWarp` ([`quilt_desc`]), next to this `warpNone`, as Photoshop does. A -/// custom warp without a usable mesh is written as no warp, with a message. A cylinder is -/// written as its seven `warpValues`. -fn warp_desc(w: Option<&Warp>, size: (f64, f64), warnings: &mut Vec) -> Value { - let none = Warp::none([0.0, 0.0, size.0, size.1]); - let mut w = w.unwrap_or(&none).clone(); - let mesh = match (&w.style, &w.mesh) { - (WarpStyle::Custom, Some(m)) if m.points.len() == 16 => Some(m.clone()), - (WarpStyle::Custom, Some(m)) if m.is_valid() => { - w = none.clone(); - None - } - (WarpStyle::Custom, _) => { - warnings.push("a custom warp without a valid mesh was written to PSD without its warp".into()); - w = none.clone(); - None - } - _ => None, - }; - let mut d = warp_head("warp", &w); - if let Some(m) = mesh { - d = d.with("customEnvelopeWarp", Value::Descriptor(Descriptor::new("customEnvelopeWarp").with("meshPoints", mesh_points(&m)))); - } - Value::Descriptor(d) -} - -/// The `quiltWarp` descriptor of a split warp, in Photoshop's layout: `deformNumCols` × -/// `deformNumRows` control points, and the patch boundaries (`quiltSliceX` / `quiltSliceY`) at -/// the knots across the warp's box. The imported `quiltWarp` (`old`) gives its own slices where -/// they still bound the mesh's patches, so their units and padding stay Photoshop's. -fn quilt_desc(w: &Warp, mesh: &BezierMesh, old: Option<&Descriptor>) -> Value { - let old_env = old.and_then(|q| get_desc(q, "customEnvelopeWarp")); - let [x0, y0, x1, y1] = w.bounds; - let slices = |key: &str, knots: &[f64], lo: f64, hi: f64| { - if let Some(env) = old_env - && crate::blocks::quilt_knots(env, key, knots.len() - 1).as_deref() == Some(knots) - && let Some(v) = env.get(key) - { - return v.clone(); - } - let (lo, hi) = if (hi - lo).is_finite() && hi > lo { (lo, hi) } else { (0.0, 1.0) }; - let values: Vec = knots.iter().map(|u| lo + u * (hi - lo)).collect(); - let prefix = values.len() as u32; - Value::ObjectArray(ObjectArray { prefix, body: Descriptor::new("UntF").with(key, Value::UnitFloats { unit: *b"#Pxl", values }) }) - }; - let envelope = Descriptor::new("customEnvelopeWarp") - .with("quiltSliceX", slices("quiltSliceX", &mesh.us, x0, x1)) - .with("quiltSliceY", slices("quiltSliceY", &mesh.vs, y0, y1)) - .with("meshPoints", mesh_points(mesh)); - Value::Descriptor( - warp_head("quiltWarp", w) - .with("deformNumRows", Value::Integer(mesh.ny() as i32)) - .with("deformNumCols", Value::Integer(mesh.nx() as i32)) - .with("customEnvelopeWarp", Value::Descriptor(envelope)), - ) -} - -fn ratio(n: i32, d: i32) -> Value { - Value::Descriptor(Descriptor::new("null").with("numerator", Value::Integer(n)).with("denominator", Value::Integer(d))) -} - -fn pad4(mut v: Vec) -> Vec { - while !v.len().is_multiple_of(4) { - v.push(0); - } - v -} - -/// `SoLd` block data. With `template` (the imported descriptor) every key it has is kept and only -/// the placed id (for a duplicate), transform (when it moved), warp and filter stack are rewritten; -/// otherwise a fresh descriptor in Photoshop's key order. A split warp goes in `quiltWarp`. -pub fn sold_bytes(template: Option<&Descriptor>, s: &PlacedSpec<'_>, warnings: &mut Vec) -> Vec { - let stored = sold_warp(s.warp, warnings); - let warp = warp_desc(stored, s.size, warnings); - let split = stored.zip(split_mesh(stored)); - let d = match template { - Some(t) => { - let mut d = t.clone(); - if text_of(t, "placed").as_deref() != Some(s.placed) { - set(&mut d, "placed", Value::Text(UnicodeString::new_nul(s.placed))); - } - if quad_moved(t, s, stored) { - set(&mut d, "Trnf", quad(s, stored)); - set(&mut d, "nonAffineTransform", quad(s, stored)); - } - set(&mut d, "warp", warp); - // `quiltWarp` is read before `warp`, so the imported one stays only while it still - // says what the layer's warp is (unchanged, or unreadable while the layer has none); - // otherwise it is rewritten, or dropped for a warp that isn't split. - let old = get_desc(t, "quiltWarp"); - let kept = old.is_some_and(|q| match crate::blocks::warp_of(q) { - Some(w) => w.as_ref() == stored, - None => s.warp.is_none(), - }); - if !kept { - match split { - Some((w, m)) => set_before(&mut d, "quiltWarp", quilt_desc(w, m, old), "warp"), - None => d.items.retain(|(k, _)| !k.is("quiltWarp")), - } - } - match &s.filter_fx { - Some(fx) => set(&mut d, "filterFX", Value::Descriptor(fx.clone())), - None => d.items.retain(|(k, _)| !k.is("filterFX")), - } - d - } - None => { - let mut d = Descriptor::new("null") - .with("Idnt", Value::Text(UnicodeString::new_nul(s.idnt))) - .with("placed", Value::Text(UnicodeString::new_nul(s.placed))) - .with("PgNm", Value::Integer(1)) - .with("totalPages", Value::Integer(1)) - .with("Crop", Value::Integer(1)) - .with("frameStep", ratio(0, 600)) - .with("duration", ratio(0, 600)) - .with("frameCount", Value::Integer(1)) - .with("Annt", Value::Integer(16)) - .with("Type", Value::Integer(2)) - .with("Trnf", quad(s, stored)) - .with("nonAffineTransform", quad(s, stored)); - if let Some((w, m)) = split { - d = d.with("quiltWarp", quilt_desc(w, m, None)); - } - let mut d = d - .with("warp", warp) - .with("Sz ", Value::Descriptor(Descriptor::new("Pnt ").with("Wdth", Value::Double(s.size.0)).with("Hght", Value::Double(s.size.1)))) - .with("Rslt", unit(b"#Rsl", s.dpi)); - if let Some(fx) = &s.filter_fx { - d = d.with("filterFX", Value::Descriptor(fx.clone())); - } - d.with("comp", Value::Integer(-1)) - .with("compInfo", Value::Descriptor(Descriptor::new("null").with("compID", Value::Integer(-1)).with("originalCompID", Value::Integer(-1)))) - } - }; - let mut out = b"soLD".to_vec(); - out.extend_from_slice(&4u32.to_be_bytes()); - out.extend(VersionedDescriptor::new(d).to_bytes()); - pad4(out) -} - -/// `PlLd` block data (`plcL` version 3): the legacy placed-layer record Photoshop writes next to -/// `SoLd`. It has no split warp: it stores none, its corners framed by the source rect. -pub fn plld_bytes(s: &PlacedSpec<'_>, warnings: &mut Vec) -> Vec { - let warp = s.warp.filter(|_| split_mesh(s.warp).is_none()); - let mut out = b"plcL".to_vec(); - out.extend_from_slice(&3u32.to_be_bytes()); - let id = s.idnt.as_bytes(); - let n = id.len().min(255); - out.push(n as u8); - out.extend_from_slice(&id[..n]); - for v in [1i32, 1, 16, 2] { - out.extend_from_slice(&v.to_be_bytes()); - } - if let Value::List(q) = quad(s, warp) { - for v in q { - if let Value::Double(x) = v { - out.extend_from_slice(&x.to_be_bytes()); - } - } - } - out.extend_from_slice(&0u32.to_be_bytes()); - let Value::Descriptor(w) = warp_desc(warp, s.size, warnings) else { return pad4(out) }; - out.extend(VersionedDescriptor::new(w).to_bytes()); - pad4(out) -} - -/// The source size a `soLD` descriptor stores (`Sz `). -pub fn stored_size(d: &Descriptor) -> Option<(f64, f64)> { - let sz = get_desc(d, "Sz ")?; - Some((num(sz.get("Wdth"))?, num(sz.get("Hght"))?)).filter(|(w, h)| *w > 0.0 && *h > 0.0) -} - // ---------- the filter mask (`FEid`) ---------- /// The filter mask stored in an `FEid` item, in document coordinates and white beyond its bounds @@ -1748,2323 +310,4 @@ pub fn uuid_from(seed: &[u8]) -> String { } #[cfg(test)] -mod tests { - use super::*; - - fn count(hay: &[u8], needle: &[u8]) -> usize { - hay.windows(needle.len()).filter(|w| *w == needle).count() - } - - /// A freshly built placed layer writes `warp` (key and class) as a length-4 string, as - /// Photoshop does; the code form is a different key to Photoshop. - #[test] - fn fresh_placed_warp_is_a_string_id() { - let spec = - PlacedSpec { idnt: "id", placed: "id", transform: Affine::IDENTITY, perspective: None, size: (10.0, 10.0), dpi: 72.0, warp: None, filter_fx: None }; - let mut warnings = Vec::new(); - let sold = sold_bytes(None, &spec, &mut warnings); - let plld = plld_bytes(&spec, &mut warnings); - // `SoLd`: the `warp` key and the warp descriptor's class; `PlLd`: the descriptor's class. - for (bytes, n) in [(&sold, 2), (&plld, 1)] { - assert_eq!(count(bytes, b"\0\0\0\x04warp"), n); - assert_eq!(count(bytes, b"\0\0\0\0warp"), 0); - } - let d = sold_descriptor(&sold).unwrap(); - assert!(matches!(d.get("warp"), Some(Value::Descriptor(w)) if w.class_id == Id::Str(b"warp".to_vec()))); - } - - fn sf(command: &str, params: J) -> SmartFilter { - SmartFilter { command: command.into(), params, blend: BlendMode::Normal, opacity: 1.0, visible: true } - } - - #[test] - fn modelled_filters_round_trip() { - let filters = vec![ - sf("filter.blur.gaussianBlur", json!({"radius": 4.0})), - sf("filter.blur.boxBlur", json!({"radius": 5.0})), - sf("filter.blur.motionBlur", json!({"angle": -20, "distance": 10.0})), - sf("filter.blur.surfaceBlur", json!({"radius": 12.0, "threshold": 40})), - sf("filter.blur.smartBlur", json!({"radius": 5.0, "threshold": 25.0, "quality": "high", "mode": "normal"})), - sf("filter.blur.smartBlur", json!({"radius": 3.0, "threshold": 30.0, "quality": "medium", "mode": "overlayEdge"})), - sf("filter.blur.smartBlur", json!({"radius": 0.5, "threshold": 0.1, "quality": "low", "mode": "edgeOnly"})), - sf("filter.blur.radialBlur", json!({"amount": 10, "method": "spin", "quality": "draft"})), - sf("filter.blur.radialBlur", json!({"amount": 20, "method": "zoom", "quality": "good"})), - sf("filter.blur.radialBlur", json!({"amount": 100, "method": "spin", "quality": "best"})), - sf("filter.sharpen.unsharpMask", json!({"amount": 150.0, "radius": 2.0, "threshold": 0})), - sf("filter.noise.addNoise", json!({"amount": 12.0, "distribution": "uniform", "monochromatic": false, "seed": 1234})), - sf("filter.noise.median", json!({"radius": 3.0})), - sf("filter.other.highPass", json!({"radius": 3.0})), - sf("filter.other.maximum", json!({"radius": 2.0})), - sf("filter.other.minimum", json!({"radius": 2.0})), - sf("filter.pixelate.mosaic", json!({"cellSize": 8.0})), - sf("filter.pixelate.mezzotint", json!({"type": "mediumStrokes"})), - sf("filter.pixelate.colorHalftone", json!({"maxRadius": 6, "channel1": 10, "channel2": 20, "channel3": 30, "channel4": 40})), - sf("filter.stylize.emboss", json!({"angle": 135, "height": 3, "amount": 100})), - sf("filter.sharpen.smartSharpen", json!({"amount": 120.0, "radius": 2.5, "reduceNoise": 5.0})), - sf("filter.noise.dustAndScratches", json!({"radius": 4, "threshold": 20})), - sf("filter.stylize.diffuse", json!({"mode": "normal"})), - sf("filter.stylize.diffuse", json!({"mode": "darkenOnly"})), - sf("filter.stylize.diffuse", json!({"mode": "lightenOnly"})), - sf("filter.stylize.diffuse", json!({"mode": "anisotropic"})), - sf("filter.stylize.traceContour", json!({"level": 60, "edge": "lower"})), - sf("filter.stylize.traceContour", json!({"level": 128, "edge": "upper"})), - sf("filter.stylize.traceContour", json!({"level": 0, "edge": "upper"})), - sf("filter.stylize.traceContour", json!({"level": 255, "edge": "lower"})), - sf("filter.pixelate.crystallize", json!({"cellSize": 10})), - sf("filter.pixelate.crystallize", json!({"cellSize": 3})), - sf("filter.pixelate.crystallize", json!({"cellSize": 300})), - sf("filter.pixelate.pointillize", json!({"cellSize": 7, "background": [1.0, 1.0, 1.0, 1.0]})), - sf("filter.pixelate.pointillize", json!({"cellSize": 300, "background": [0.0, 0.5, 1.0, 1.0]})), - sf("filter.other.offset", json!({"horizontal": 12, "vertical": -7, "undefinedAreas": "transparent"})), - sf("filter.other.custom", json!({"kernel": SHARPEN, "scale": 1, "offset": 0})), - sf("image.adjustments.levels", json!({"inBlack": 20, "inWhite": 220, "gamma": 1.4, "red": {"inBlack": 0, "inWhite": 255, "gamma": 0.8}})), - sf("image.adjustments.curves", json!({"points": [[0.0, 0.0], [64.0, 40.0], [255.0, 255.0]], "blue": [[0.0, 20.0], [255.0, 235.0]]})), - sf("image.adjustments.shadowsHighlights", json!({})), - sf("filter.sharpen.sharpen", json!({})), - // Photoshop stores Dust & Scratches' radius in whole pixels (a `long`). - sf("filter.noise.dustAndScratches", json!({"radius": 4, "threshold": 12})), - sf( - "image.adjustments.hueSaturation", - json!({"colorize": false, "hue": 10, "saturation": -20, "lightness": 5, "reds": {"hue": 5, "saturation": 0, "lightness": -3, "range": [315, 345, 15, 45]}}), - ), - // A pencil-drawn curve: 256 output levels (`Mpng`). - sf("image.adjustments.curves", json!({"pencil": true, "points": (0..256).rev().collect::>()})), - sf("filter.distort.pinch", json!({"amount": -28})), - sf("filter.distort.polarCoordinates", json!({"mode": "rectangularToPolar"})), - sf("filter.distort.ripple", json!({"amount": 250, "size": "small"})), - sf("filter.distort.spherize", json!({"amount": 60, "mode": "verticalOnly"})), - sf("filter.distort.twirl", json!({"angle": -355})), - sf( - "filter.distort.wave", - json!({"type": "square", "generators": 3, "wavelengthMin": 20, "wavelengthMax": 90, "amplitudeMin": 4, "amplitudeMax": 30, - "undefinedAreas": "repeat", "seed": 4_000_000_000u32}), - ), - sf("filter.distort.zigZag", json!({"amount": 30, "ridges": 7, "style": "aroundCenter"})), - sf("image.adjustments.invert", json!({})), - ]; - for mut f in filters.into_iter().chain(wind_extrude_tiles_settings()) { - f.blend = BlendMode::Overlay; - f.opacity = 0.75; - f.visible = false; - let d = item_for_filter(&f).unwrap(); - let bytes = d.to_bytes(); - let back = filter_from_item(&Descriptor::from_bytes(&bytes).unwrap()); - assert_eq!(back, f, "{}", f.command); - } - } - - /// The filters without options, their measured `filterID`s (as Photoshop wrote them). - const MEASURED_NO_OPTIONS: [(&str, i32); 11] = [ - ("filter.blur.blur", 1114403360), - ("filter.blur.blurMore", 1114403405), - ("filter.blur.average", 1098281575), - ("filter.noise.despeckle", 1148416099), - ("filter.stylize.findEdges", 1181639749), - ("filter.pixelate.facet", 1180922912), - ("filter.pixelate.fragment", 1181902701), - ("filter.sharpen.sharpen", 1399353968), - ("filter.sharpen.sharpenMore", 1399353933), - ("filter.sharpen.sharpenEdges", 1399353925), - ("filter.stylize.solarize", 1399616122), - ]; - - /// A filter without options as Photoshop saves it: `hasoptions` false, no `Fltr`, a localized - /// name and the current colours. - fn photoshop_no_options_item(name: &str, filter_id: Value) -> Descriptor { - let rgb = |r: f64, g: f64, b: f64| { - Value::Descriptor(Descriptor::new("RGBC").with("Rd ", Value::Double(r)).with("Grn ", Value::Double(g)).with("Bl ", Value::Double(b))) - }; - Descriptor::new("filterFX") - .with("Nm ", Value::Text(UnicodeString::new_nul(name))) - .with("blendOptions", Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", 60.0)).with("Md ", enumv("BlnM", "Mltp")))) - .with("enab", Value::Boolean(false)) - .with("hasoptions", Value::Boolean(false)) - .with("FrgC", rgb(167.0, 157.0, 147.0)) - .with("BckC", rgb(255.0, 255.0, 255.0)) - .with("filterID", filter_id) - } - - #[test] - fn filters_without_options_round_trip_in_the_measured_shape() { - let keys = ["Nm ", "blendOptions", "enab", "hasoptions", "FrgC", "BckC", "filterID"]; - for (command, id) in MEASURED_NO_OPTIONS { - let mut f = sf(command, json!({})); - f.blend = BlendMode::Overlay; - f.opacity = 0.75; - f.visible = false; - let d = item_for_filter(&f).unwrap(); - let got: Vec = d.items.iter().map(|(k, _)| String::from_utf8_lossy(k.as_bytes()).into_owned()).collect(); - assert_eq!(got, keys, "{command}"); - assert_eq!(d.get("hasoptions"), Some(&Value::Boolean(false)), "{command}"); - assert_eq!(d.get("filterID"), Some(&Value::Integer(id)), "{command}"); - let back = filter_from_item(&Descriptor::from_bytes(&d.to_bytes()).unwrap()); - assert_eq!(back, f, "{command}"); - // Keys an old record may carry have no effect on these filters: still written. - let extra = item_for_filter(&sf(command, json!({"radius": 3.0, "layer": "L"}))).unwrap(); - assert_eq!(extra.get("filterID"), Some(&Value::Integer(id)), "{command}"); - for p in [json!(null), json!("x"), json!([1, 2])] { - assert!(item_for_filter(&sf(command, p)).is_ok(), "{command}"); - } - } - } - - #[test] - fn photoshop_filters_without_options_open_editable() { - for (command, id) in MEASURED_NO_OPTIONS { - let item = photoshop_no_options_item("Weichzeichnen", Value::Integer(id)); - let f = filter_from_item(&Descriptor::from_bytes(&item.to_bytes()).unwrap()); - assert_eq!(f.command, command); - assert_eq!(f.params, json!({})); - assert_eq!((f.visible, f.blend), (false, BlendMode::Multiply)); - assert!((f.opacity - 0.6).abs() < 1e-6); - } - } - - #[test] - fn malformed_filters_without_options_are_kept_verbatim() { - let blur = code(b"Blr "); - let cases = [ - // An id no filter has, a missing id, ids of the wrong type. - photoshop_no_options_item("X", Value::Integer(code(b"Zzzz"))), - Descriptor::new("filterFX").with("hasoptions", Value::Boolean(false)), - photoshop_no_options_item("X", Value::Double(f64::from(blur))), - photoshop_no_options_item("X", Value::Double(f64::NAN)), - photoshop_no_options_item("X", Value::Text(UnicodeString::new_nul("Blr "))), - photoshop_no_options_item("X", Value::Integer(-1)), - // Settings we don't know of on a filter that has none. - photoshop_no_options_item("X", Value::Integer(blur)).with("Fltr", Value::Descriptor(Descriptor::new("Blr ").with("Amnt", Value::Integer(5)))), - // Settings that aren't a descriptor, on a filter that has none. - photoshop_no_options_item("X", Value::Integer(blur)).with("Fltr", Value::Integer(5)), - photoshop_no_options_item("X", Value::Integer(blur)).with("Fltr", Value::Text(UnicodeString::new_nul("Blr "))), - photoshop_no_options_item("X", Value::Integer(781)).with("Fltr", Value::Integer(5)), - ]; - for item in cases { - let f = filter_from_item(&item); - assert_eq!(f.command, UNSUPPORTED_FILTER, "{item:?}"); - // Written back (a bare item gains blending and visibility) and still not editable. - let written = item_for_filter(&f).unwrap(); - assert_eq!(written.get("Fltr"), item.get("Fltr"), "{item:?}"); - let back = filter_from_item(&written); - assert_eq!((back.command.as_str(), &back.params["filterID"]), (UNSUPPORTED_FILTER, &f.params["filterID"])); - } - } - - /// Smart Sharpen's `Fltr` in the measured shape (no `presetKind`, no `Angl`). - fn smart_sharpen(amount: f64, radius: f64, noise: f64, blur: &str) -> Descriptor { - Descriptor::new("smartSharpen") - .with("useLegacy", Value::Boolean(false)) - .with("Amnt", unit(b"#Prc", amount)) - .with("Rds ", unit(b"#Pxl", radius)) - .with("noiseReduction", unit(b"#Prc", noise)) - .with("blur", enumv("blurType", blur)) - } - - fn dust(radius: i32, threshold: i32) -> Descriptor { - Descriptor::new("DstS").with("Rds ", Value::Integer(radius)).with("Thsh", Value::Integer(threshold)) - } - - /// The `Fltr` descriptor PhotoCraft writes for `f`, after a byte round trip. - fn written_fltr(f: &SmartFilter) -> Descriptor { - let d = Descriptor::from_bytes(&item_for_filter(f).unwrap().to_bytes()).unwrap(); - get_desc(&d, "Fltr").unwrap().clone() - } - - /// Measured in Photoshop: Smart Sharpen 120 %, 2.5 px, noise 5 %, Gaussian Blur - /// (filterID 1131); the default entry adds `presetKind` first, which is not kept. - #[test] - fn smart_sharpen_photoshop_entry_opens_and_writes_back() { - let fltr = smart_sharpen(120.0, 2.5, 5.0, "GsnB"); - let item = ps_item("Smart Sharpen...", fltr.clone(), 1131); - let f = filter_from_item(&Descriptor::from_bytes(&item.to_bytes()).unwrap()); - assert_eq!(f.command, "filter.sharpen.smartSharpen"); - assert_eq!(f.params, json!({"amount": 120.0, "radius": 2.5, "reduceNoise": 5.0})); - assert_eq!(written_fltr(&f), fltr); - let d = item_for_filter(&f).unwrap(); - assert_eq!(int(&d, "filterID"), Some(1131)); - assert_eq!(get_desc(&d, "Fltr").unwrap().class_id, Id::Str(b"smartSharpen".to_vec())); - // The four-character keys and enum values are codes, as Photoshop writes them. - let bytes = d.to_bytes(); - assert_eq!(count(&bytes, b"\0\0\0\0blurenum\0\0\0\x08blurType\0\0\0\0GsnB"), 1); - assert_eq!(count(&bytes, b"\0\0\0\0Rds UntF#Pxl"), 1); - - // With `presetKind` (any value): opens, but the params hold only the engine's own keys - // (it rejects unknown ones), and a re-save leaves it out as Photoshop does for explicit - // values. - for kind in ["presetKindDefault", "presetKindCustom", "Xxxx"] { - let mut with_preset = Descriptor::new("smartSharpen").with("presetKind", enumv("presetKindType", kind)); - with_preset.items.extend(smart_sharpen(200.0, 1.0, 10.0, "GsnB").items); - let f = filter_from_item(&Descriptor::from_bytes(&ps_item("Smart Sharpen...", with_preset, 1131).to_bytes()).unwrap()); - assert_eq!(f.command, "filter.sharpen.smartSharpen"); - let keys: Vec<&str> = f.params.as_object().unwrap().keys().map(String::as_str).collect(); - assert_eq!(keys.len(), 3, "{keys:?}"); - assert!(keys.iter().all(|k| ["amount", "radius", "reduceNoise"].contains(k)), "{keys:?}"); - assert_eq!(f.params, json!({"amount": 200.0, "radius": 1.0, "reduceNoise": 10.0})); - assert_eq!(written_fltr(&f), smart_sharpen(200.0, 1.0, 10.0, "GsnB")); - } - - // Without options PhotoCraft writes the engine's defaults, Gaussian Blur. - assert_eq!(written_fltr(&sf("filter.sharpen.smartSharpen", json!({}))), smart_sharpen(100.0, 1.0, 10.0, "GsnB")); - } - - /// Lens Blur (Photoshop's default), Motion Blur and legacy mode render differently from - /// PhotoCraft's Smart Sharpen, so those entries stay verbatim. - #[test] - fn smart_sharpen_settings_we_dont_render_stay_verbatim() { - let mut default_entry = Descriptor::new("smartSharpen").with("presetKind", enumv("presetKindType", "presetKindDefault")); - default_entry.items.extend(smart_sharpen(200.0, 1.0, 10.0, "lensBlur").items); - let motion = smart_sharpen(80.0, 1.5, 0.0, "MtnB").with("Angl", Value::Integer(30)); - let mut legacy = smart_sharpen(100.0, 1.0, 10.0, "GsnB"); - set(&mut legacy, "useLegacy", Value::Boolean(true)); - for fltr in [default_entry, motion, legacy] { - let item = ps_item("Smart Sharpen...", fltr, 1131); - let f = filter_from_item(&item); - assert_eq!(f.command, UNSUPPORTED_FILTER); - assert_eq!(f.params["filterID"], 1131); - assert_eq!(item_for_filter(&f).unwrap(), item); - } - } - - #[test] - fn malformed_smart_sharpen_is_kept_verbatim() { - let g = || smart_sharpen(100.0, 1.0, 10.0, "GsnB"); - let without = |key: &str| { - let mut d = g(); - d.items.retain(|(k, _)| !k.is(key)); - d - }; - let with = |key: &str, v: Value| { - let mut d = g(); - set(&mut d, key, v); - d - }; - let cases = vec![ - without("useLegacy"), - without("Amnt"), - without("Rds "), - without("noiseReduction"), - without("blur"), - with("Amnt", Value::Double(100.0)), - with("Amnt", unit(b"#Pxl", 100.0)), - with("Rds ", Value::Integer(1)), - with("useLegacy", Value::Integer(0)), - with("Amnt", unit(b"#Prc", 0.0)), - with("Amnt", unit(b"#Prc", 501.0)), - with("Rds ", unit(b"#Pxl", 0.05)), - with("Rds ", unit(b"#Pxl", 65.0)), - with("Rds ", unit(b"#Pxl", f64::NAN)), - with("noiseReduction", unit(b"#Prc", -1.0)), - with("noiseReduction", unit(b"#Prc", f64::INFINITY)), - with("blur", enumv("blurType", "Xxxx")), - with("blur", enumv("BlrM", "GsnB")), - with("blur", Value::Integer(0)), - with("presetKind", Value::Integer(1)), - g().with("Angl", Value::Integer(30)), - g().with("shadowMode", Value::Descriptor(Descriptor::new("adaptCorrectTones"))), - ]; - for fltr in cases { - let item = ps_item("Smart Sharpen...", fltr, 1131); - let f = filter_from_item(&Descriptor::from_bytes(&item.to_bytes()).unwrap()); - assert_eq!(f.command, UNSUPPORTED_FILTER, "{:?}", get_desc(&item, "Fltr")); - assert_eq!(item_for_filter(&f).unwrap().to_bytes(), item.to_bytes()); - } - // No `Fltr` at all (hasoptions false). - let bare = Descriptor::new("filterFX").with("filterID", Value::Integer(1131)); - assert_eq!(filter_from_item(&bare).command, UNSUPPORTED_FILTER); - } - - /// Measured in Photoshop: Dust & Scratches at its defaults (1, 0) and at 4, 20 (filterID - /// `DstS`, 1148417107; both settings `long`). - #[test] - fn dust_and_scratches_photoshop_entry_opens_and_writes_back() { - for (radius, threshold) in [(1, 0), (4, 20), (500, 255)] { - let fltr = dust(radius, threshold); - let item = ps_item("Dust & Scratches...", fltr.clone(), 1_148_417_107); - let f = filter_from_item(&Descriptor::from_bytes(&item.to_bytes()).unwrap()); - assert_eq!(f.command, "filter.noise.dustAndScratches"); - assert_eq!(f.params, json!({"radius": radius, "threshold": threshold})); - assert_eq!(written_fltr(&f), fltr); - assert_eq!(int(&item_for_filter(&f).unwrap(), "filterID"), Some(1_148_417_107)); - } - // No `Fltr` (hasoptions false): kept verbatim. - let bare = Descriptor::new("filterFX").with("filterID", Value::Integer(code(b"DstS"))); - assert_eq!(filter_from_item(&bare).command, UNSUPPORTED_FILTER); - } - - #[test] - fn malformed_dust_and_scratches_is_kept_verbatim() { - let cases = vec![ - Descriptor::new("DstS").with("Thsh", Value::Integer(0)), - Descriptor::new("DstS").with("Rds ", Value::Integer(1)), - Descriptor::new("DstS").with("Rds ", Value::Double(1.0)).with("Thsh", Value::Integer(0)), - Descriptor::new("DstS").with("Rds ", unit(b"#Pxl", 1.0)).with("Thsh", Value::Integer(0)), - Descriptor::new("DstS").with("Rds ", Value::Integer(1)).with("Thsh", Value::Boolean(false)), - dust(0, 0), - dust(501, 0), - dust(1, -1), - dust(1, 256), - dust(i32::MIN, i32::MAX), - dust(1, 0).with("Xtra", Value::Integer(1)), - ]; - for fltr in cases { - let item = ps_item("Dust & Scratches...", fltr, code(b"DstS")); - let f = filter_from_item(&item); - assert_eq!(f.command, UNSUPPORTED_FILTER, "{:?}", get_desc(&item, "Fltr")); - assert_eq!(item_for_filter(&f).unwrap(), item); - } - } - - /// Every option's range ends round trip; hostile params are written in range (the engine - /// clamps the same way), never a panic. - #[test] - fn smart_sharpen_and_dust_option_values_round_trip() { - let mut cases = Vec::new(); - for amount in [1.0, 100.0, 500.0] { - for radius in [0.1, 1.0, 64.0] { - for noise in [0.0, 10.0, 100.0] { - cases.push(sf("filter.sharpen.smartSharpen", json!({"amount": amount, "radius": radius, "reduceNoise": noise}))); - } - } - } - for radius in [1, 2, 100, 500] { - for threshold in [0, 1, 128, 255] { - cases.push(sf("filter.noise.dustAndScratches", json!({"radius": radius, "threshold": threshold}))); - } - } - for f in cases { - let back = filter_from_item(&Descriptor::from_bytes(&item_for_filter(&f).unwrap().to_bytes()).unwrap()); - assert_eq!(back, f); - } - let defaults = json!({"amount": 100.0, "radius": 1.0, "reduceNoise": 10.0}); - for (command, p, want) in [ - ( - "filter.sharpen.smartSharpen", - json!({"amount": 1e9, "radius": -5.0, "reduceNoise": "x"}), - json!({"amount": 500.0, "radius": 0.1, "reduceNoise": 10.0}), - ), - ("filter.sharpen.smartSharpen", json!({"presetKind": "presetKindDefault", "amount": null}), defaults.clone()), - ("filter.sharpen.smartSharpen", json!(null), defaults.clone()), - ("filter.noise.dustAndScratches", json!({"radius": 2.4, "threshold": 1e12}), json!({"radius": 2, "threshold": 255})), - ("filter.noise.dustAndScratches", json!({"radius": -3, "threshold": -3}), json!({"radius": 1, "threshold": 0})), - ("filter.noise.dustAndScratches", json!([]), json!({"radius": 1, "threshold": 0})), - ] { - let back = filter_from_item(&item_for_filter(&sf(command, p.clone())).unwrap()); - assert_eq!((back.command.as_str(), &back.params), (command, &want), "{p}"); - } - } - - /// Every option value of Wind, Extrude and Tiles (and the ends of their ranges). - fn wind_extrude_tiles_settings() -> Vec { - let mut v = Vec::new(); - for method in ["wind", "blast", "stagger"] { - for direction in ["fromRight", "fromLeft"] { - v.push(sf("filter.stylize.wind", json!({"method": method, "direction": direction}))); - } - } - for t in ["blocks", "pyramids"] { - for mode in ["random", "levelBased"] { - for (solid, mask) in [(false, false), (true, false), (false, true), (true, true)] { - v.push(sf( - "filter.stylize.extrude", - json!({"type": t, "size": 7, "depth": 9, "depthMode": mode, "solidFrontFaces": solid, "maskIncompleteBlocks": mask}), - )); - } - } - } - v.push(sf( - "filter.stylize.extrude", - json!({"type": "blocks", "size": 2, "depth": 1, "depthMode": "random", "solidFrontFaces": false, "maskIncompleteBlocks": false}), - )); - v.push(sf( - "filter.stylize.extrude", - json!({"type": "pyramids", "size": 255, "depth": 255, "depthMode": "levelBased", "solidFrontFaces": true, "maskIncompleteBlocks": true}), - )); - for fill in ["background", "foreground", "inverse", "unaltered"] { - v.push(sf( - "filter.stylize.tiles", - json!({"count": 6, "maxOffset": 20, "fill": fill, "foreground": [1.0, 0.0, 0.5, 1.0], "background": [0.0, 0.5, 1.0, 1.0]}), - )); - } - for (count, offset) in [(1, 1), (99, 99)] { - v.push(sf( - "filter.stylize.tiles", - json!({"count": count, "maxOffset": offset, "fill": "background", "foreground": [0.0, 0.0, 0.0, 1.0], "background": [1.0, 1.0, 1.0, 1.0]}), - )); - } - v - } - - /// A `filterFX` entry shaped as Photoshop saves Wind, Extrude and Tiles (measured in Photoshop: - /// applied through Action Manager to a smart object, saved, `filterFX` read back): the item's - /// `FrgC`/`BckC` are the document colours, `Fltr` holds the settings, `filterID` the class code. - fn measured_item(fltr: Descriptor, fg: f64, bg: f64) -> Descriptor { - let id = code(fltr.class_id.as_bytes().try_into().unwrap()); - Descriptor::new("filterFX") - .with("Nm ", Value::Text(UnicodeString::new_nul("Filter..."))) - .with("blendOptions", blend_options(&sf("", J::Null))) - .with("enab", Value::Boolean(true)) - .with("hasoptions", Value::Boolean(true)) - .with("FrgC", rgbc(fg)) - .with("BckC", rgbc(bg)) - .with("Fltr", Value::Descriptor(fltr)) - .with("filterID", Value::Integer(id)) - } - - /// The `Fltr` descriptors Photoshop 27 wrote for these filters (one smart object each, saved as - /// PSD and read back), with the settings PhotoCraft reads from them. - const PHOTOSHOP_FLTR: [(&str, &str, &str); 6] = [ - ("filter.distort.pinch", r#"{"amount":-28}"#, "0000000600500069006e00630068000000000000506e63680000000100000000416d6e746c6f6e67ffffffe4"), - ("filter.distort.twirl", r#"{"angle":-355}"#, "000000060054007700690072006c0000000000005477726c0000000100000000416e676c6c6f6e67fffffe9d"), - ( - "filter.distort.ripple", - r#"{"amount":-273,"size":"large"}"#, - "000000070052006900700070006c006500000000000052706c650000000200000000416d6e746c6f6e67fffffeef0000000052706c53656e756d0000000052706c53000000004c726720", - ), - ( - "filter.distort.spherize", - r#"{"amount":-1,"mode":"horizontalOnly"}"#, - "00000009005300700068006500720069007a0065000000000000537068720000000200000000416d6e746c6f6e67ffffffff000000005370684d656e756d000000005370684d0000000048727a4f", - ), - ( - "filter.distort.polarCoordinates", - r#"{"mode":"polarToRectangular"}"#, - "000000120050006f006c0061007200200043006f006f007200640069006e0061007400650073000000000000506c72200000000100000000436e7672656e756d00000000436e767200000000506c7252", - ), - ( - "filter.distort.zigZag", - r#"{"amount":-42,"ridges":11,"style":"pondRipples"}"#, - "00000007005a00690067005a006100670000000000005a675a670000000300000000416d6e746c6f6e67ffffffd6000000004e6d62526c6f6e670000000b000000005a5a5479656e756d000000005a5a547900000000506e6452", - ), - ]; - - /// Photoshop's Wave with Scale 100% / 28%: PhotoCraft's Wave has no Scale. - const PHOTOSHOP_WAVE: &str = "000000050057006100760065000000000000576176650000000a0000000057767470656e756d00000000577674700000000057765472000000004e6d62476c6f6e670000014c00000000574c4d6e6c6f6e67000000d500000000574c4d786c6f6e67000000d600000000416d4d6e6c6f6e67000000f000000000416d4d786c6f6e67000000f10000000053636c486c6f6e67000000640000000053636c566c6f6e670000001c00000000556e6441656e756d00000000556e6441000000005772704100000000526e64536c6f6e670013624a"; - - /// A `filterFX` list item as Photoshop writes it (enabled, Normal at 100%, with options), wrapping the `Fltr` descriptor `fltr`. - fn photoshop_fltr_item(fltr: Descriptor) -> Descriptor { - let id = code(fltr.class_id.as_bytes().try_into().unwrap()); - Descriptor::new("filterFX") - .with("Nm ", Value::Text(UnicodeString::new_nul("from Photoshop"))) - .with("blendOptions", Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", 100.0)).with("Md ", enumv("BlnM", "normal")))) - .with("enab", Value::Boolean(true)) - .with("hasoptions", Value::Boolean(true)) - .with("Fltr", Value::Descriptor(fltr)) - .with("filterID", Value::Integer(id)) - } - - fn wind(method: &str, direction: &str) -> Descriptor { - Descriptor::new("Wnd ").with("WndM", enumv("WndM", method)).with("Drct", enumv("Drct", direction)) - } - - fn extrude(t: &str, size: Value, depth: Value, mode: &str, solid: Value, mask: Value) -> Descriptor { - Descriptor::new("Extr") - .with("ExtT", enumv("ExtT", t)) - .with("ExtS", size) - .with("ExtD", depth) - .with("ExtR", enumv("ExtR", mode)) - .with("ExtF", solid) - .with("ExtM", mask) - } - - fn tiles(count: Value, offset: Value, fill: &str) -> Descriptor { - Descriptor::new("Tls ").with("TlNm", count).with("TlOf", offset).with("FlCl", enumv("FlCl", fill)) - } - - #[test] - fn wind_extrude_tiles_open_from_photoshop_shapes() { - let (long, yes, no) = (Value::Integer, Value::Boolean(true), Value::Boolean(false)); - let cases = [ - // The measured files. - (wind("Blst", "Left"), "filter.stylize.wind", json!({"method": "blast", "direction": "fromRight"})), - (wind("Stgr", "Rght"), "filter.stylize.wind", json!({"method": "stagger", "direction": "fromLeft"})), - (wind("Wnd ", "Rght"), "filter.stylize.wind", json!({"method": "wind", "direction": "fromLeft"})), - ( - extrude("Blks", long(7), long(9), "Rndm", yes.clone(), no.clone()), - "filter.stylize.extrude", - json!({"type": "blocks", "size": 7, "depth": 9, "depthMode": "random", "solidFrontFaces": true, "maskIncompleteBlocks": false}), - ), - ( - extrude("Pyrm", long(12), long(20), "LvlB", no, yes), - "filter.stylize.extrude", - json!({"type": "pyramids", "size": 12, "depth": 20, "depthMode": "levelBased", "solidFrontFaces": false, "maskIncompleteBlocks": true}), - ), - ( - tiles(long(6), long(20), "FlFr"), - "filter.stylize.tiles", - json!({"count": 6, "maxOffset": 20, "fill": "foreground", "foreground": [0.2, 0.2, 0.2, 1.0], "background": [1.0, 1.0, 1.0, 1.0]}), - ), - ( - tiles(long(4), long(5), "FlIn"), - "filter.stylize.tiles", - json!({"count": 4, "maxOffset": 5, "fill": "inverse", "foreground": [0.2, 0.2, 0.2, 1.0], "background": [1.0, 1.0, 1.0, 1.0]}), - ), - ( - tiles(long(10), long(10), "FlBc"), - "filter.stylize.tiles", - json!({"count": 10, "maxOffset": 10, "fill": "background", "foreground": [0.2, 0.2, 0.2, 1.0], "background": [1.0, 1.0, 1.0, 1.0]}), - ), - ( - tiles(long(99), long(1), "FlSm"), - "filter.stylize.tiles", - json!({"count": 99, "maxOffset": 1, "fill": "unaltered", "foreground": [0.2, 0.2, 0.2, 1.0], "background": [1.0, 1.0, 1.0, 1.0]}), - ), - ]; - for (fltr, command, params) in cases { - let item = measured_item(fltr, 51.0, 255.0); - // Through bytes, as read from a file. - let f = filter_from_item(&Descriptor::from_bytes(&item.to_bytes()).unwrap()); - assert_eq!((f.command.as_str(), &f.params), (command, ¶ms)); - // Written back in the measured shape: same class, keys and their order, value types - // (long, bool, enum with its type), filterID; Tiles also its colours. - let back = item_for_filter(&f).unwrap(); - assert_eq!(get_desc(&back, "Fltr").map(Descriptor::to_bytes), get_desc(&item, "Fltr").map(Descriptor::to_bytes), "{command}"); - assert_eq!(back.get("filterID"), item.get("filterID"), "{command}"); - if command == "filter.stylize.tiles" { - assert_eq!((back.get("FrgC"), back.get("BckC")), (item.get("FrgC"), item.get("BckC"))); - } - } - // The class codes: numeric filterIDs of the four-char classes. - for (c, id) in [("filter.stylize.wind", 1466852384), ("filter.stylize.extrude", 1165522034), ("filter.stylize.tiles", 1416393504)] { - assert_eq!(item_for_filter(&sf(c, json!({}))).unwrap().get("filterID"), Some(&Value::Integer(id))); - } - // A filter found by its filterID alone (no `Fltr` class to go by) still needs its settings. - let bare = Descriptor::new("filterFX").with("hasoptions", Value::Boolean(false)).with("filterID", Value::Integer(1466852384)); - assert_eq!(filter_from_item(&bare).command, UNSUPPORTED_FILTER); - // Only Tiles reads the entry's colours; Wind and Extrude write the defaults. - let f = filter_from_item(&measured_item(wind("Wnd ", "Left"), 51.0, 0.0)); - assert_eq!(f.params, json!({"method": "wind", "direction": "fromRight"})); - let back = item_for_filter(&f).unwrap(); - assert_eq!((back.get("FrgC"), back.get("BckC")), (Some(&rgbc(0.0)), Some(&rgbc(255.0)))); - // Tiles without colours in its params (or the entry) writes the engine's black and white. - let f = filter_from_item(&Descriptor::new("filterFX").with("Fltr", Value::Descriptor(tiles(long(4), long(5), "FlBc")))); - assert_eq!(f.params, json!({"count": 4, "maxOffset": 5, "fill": "background"})); - let back = item_for_filter(&f).unwrap(); - assert_eq!((back.get("FrgC"), back.get("BckC")), (Some(&rgbc(0.0)), Some(&rgbc(255.0)))); - } - - #[test] - fn wind_extrude_tiles_write_defaults_and_photoshop_ranges() { - let fltr = |c: &str, p: J| match item_for_filter(&sf(c, p)).unwrap().get("Fltr") { - Some(Value::Descriptor(d)) => d.clone(), - other => panic!("no Fltr: {other:?}"), - }; - let long = Value::Integer; - let (yes, no) = (Value::Boolean(true), Value::Boolean(false)); - // Defaults are the engine's; our random seed has no PSD key and is not written. - assert_eq!(fltr("filter.stylize.wind", json!({"seed": 9})), wind("Wnd ", "Left")); - assert_eq!(fltr("filter.stylize.extrude", json!({"seed": 9})), extrude("Blks", long(30), long(30), "Rndm", no.clone(), no.clone())); - assert_eq!(fltr("filter.stylize.tiles", json!({"seed": 9})), tiles(long(10), long(10), "FlBc")); - // Out of range, fractional, non-numeric and non-bool values as the engine reads them. - assert_eq!( - fltr("filter.stylize.extrude", json!({"size": 1e12, "depth": -5, "solidFrontFaces": "yes", "maskIncompleteBlocks": true})), - extrude("Blks", long(255), long(1), "Rndm", no.clone(), yes) - ); - assert_eq!(fltr("filter.stylize.tiles", json!({"count": 0, "maxOffset": 12.6})), tiles(long(1), long(13), "FlBc")); - assert_eq!(fltr("filter.stylize.tiles", json!({"count": "many", "maxOffset": 1000})), tiles(long(10), long(99), "FlBc")); - assert_eq!(fltr("filter.stylize.extrude", json!({"size": f64::NAN})), extrude("Blks", long(30), long(30), "Rndm", no.clone(), no)); - } - - #[test] - fn malformed_wind_extrude_tiles_are_kept_verbatim() { - let long = Value::Integer; - let (yes, no) = (Value::Boolean(true), Value::Boolean(false)); - let cases = [ - // Missing keys. - Descriptor::new("Wnd "), - Descriptor::new("Wnd ").with("WndM", enumv("WndM", "Blst")), - Descriptor::new("Wnd ").with("Drct", enumv("Drct", "Left")), - Descriptor::new("Extr").with("ExtT", enumv("ExtT", "Blks")).with("ExtS", long(7)).with("ExtD", long(9)).with("ExtR", enumv("ExtR", "Rndm")), - Descriptor::new("Tls ").with("TlNm", long(6)).with("TlOf", long(20)), - Descriptor::new("Tls ").with("TlNm", long(6)).with("FlCl", enumv("FlCl", "FlFr")), - // Unknown enum values and enum types (Photoshop falls back to a default for these; - // we keep them as they are rather than guess). - wind("Wild", "Left"), - wind("Blst", "Up "), - Descriptor::new("Wnd ").with("WndM", enumv("Drct", "Blst")).with("Drct", enumv("Drct", "Left")), - extrude("Cube", long(7), long(9), "Rndm", yes.clone(), no.clone()), - extrude("Blks", long(7), long(9), "Sine", yes.clone(), no.clone()), - tiles(long(6), long(20), "FlXx"), - Descriptor::new("Tls ").with("TlNm", long(6)).with("TlOf", long(20)).with("FlCl", enumv("BlnM", "FlFr")), - // Wrong types (also NaN). - Descriptor::new("Wnd ").with("WndM", long(1)).with("Drct", enumv("Drct", "Left")), - extrude("Blks", Value::Double(7.0), long(9), "Rndm", yes.clone(), no.clone()), - extrude("Blks", long(7), unit(b"#Pxl", 9.0), "Rndm", yes.clone(), no.clone()), - extrude("Blks", long(7), long(9), "Rndm", long(1), no.clone()), - extrude("Blks", long(7), long(9), "Rndm", yes.clone(), Value::Double(f64::NAN)), - tiles(Value::Double(f64::NAN), long(20), "FlFr"), - tiles(long(6), Value::Text(UnicodeString::new_nul("20")), "FlFr"), - // Out of range. - extrude("Blks", long(1), long(9), "Rndm", yes.clone(), no.clone()), - extrude("Blks", long(256), long(9), "Rndm", yes.clone(), no.clone()), - extrude("Blks", long(7), long(0), "Rndm", yes.clone(), no.clone()), - extrude("Blks", long(7), long(i32::MAX), "Rndm", yes, no), - tiles(long(0), long(20), "FlFr"), - tiles(long(100), long(20), "FlFr"), - tiles(long(6), long(0), "FlFr"), - tiles(long(6), long(i32::MIN), "FlFr"), - ]; - for fltr in cases { - let item = measured_item(fltr, 0.0, 255.0); - let f = filter_from_item(&Descriptor::from_bytes(&item.to_bytes()).unwrap()); - assert_eq!(f.command, UNSUPPORTED_FILTER, "{item:?}"); - assert_eq!(item_for_filter(&f).unwrap().to_bytes(), item.to_bytes()); - } - // A Tiles entry whose colour is unreadable is kept verbatim too. - for (key, bad) in [ - ("FrgC", Value::Integer(3)), - ("BckC", Value::Descriptor(Descriptor::new("RGBC").with("Rd ", Value::Double(0.0)))), - ( - "BckC", - Value::Descriptor( - Descriptor::new("RGBC").with("Rd ", Value::Double(f64::NAN)).with("Grn ", Value::Double(0.0)).with("Bl ", Value::Double(0.0)), - ), - ), - ] { - let mut item = measured_item(tiles(long(6), long(20), "FlFr"), 0.0, 255.0); - set(&mut item, key, bad); - assert_eq!(filter_from_item(&item).command, UNSUPPORTED_FILTER); - } - // Values with no PSD equivalent are reported, not guessed. - for (c, p) in [ - ("filter.stylize.wind", json!({"method": "gale"})), - ("filter.stylize.wind", json!({"direction": "fromTop"})), - ("filter.stylize.wind", json!({"direction": 1})), - ("filter.stylize.extrude", json!({"type": "cubes"})), - ("filter.stylize.extrude", json!({"depthMode": null})), - ("filter.stylize.tiles", json!({"fill": "transparent"})), - ("filter.stylize.tiles", json!({"foreground": "teal"})), - ("filter.stylize.tiles", json!({"background": [1.0]})), - ("filter.stylize.tiles", json!({"background": [f64::NAN, 0.0, 0.0]})), - ] { - assert!(item_for_filter(&sf(c, p.clone())).is_err(), "{c} {p}"); - } - } - - /// Photoshop's default Custom kernel: a 3 × 3 sharpen centred in the 5 × 5. - const SHARPEN: [i32; 25] = [0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, -1, 5, -1, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0]; - - /// A `filterFXList` item as measured in Photoshop (applied through Action Manager to a smart - /// object, saved, `filterFX` read back). - fn measured_named_item(id: &[u8; 4], name: &str, fltr: Descriptor) -> Descriptor { - Descriptor::new("filterFX") - .with("Nm ", Value::Text(UnicodeString::new_nul(name))) - .with("blendOptions", blend_options(&sf("", J::Null))) - .with("enab", Value::Boolean(true)) - .with("hasoptions", Value::Boolean(true)) - .with("FrgC", rgbc(0.0)) - .with("BckC", rgbc(255.0)) - .with("Fltr", Value::Descriptor(fltr)) - .with("filterID", Value::Integer(code(id))) - } - - fn offset_fltr(h: Value, v: Value, fill: Value) -> Descriptor { - Descriptor::new("Ofst").with("Hrzn", h).with("Vrtc", v).with("Fl ", fill) - } - - fn custom_fltr(scale: Value, offset: Value, m: Vec) -> Descriptor { - Descriptor::new("Cstm").with("Scl ", scale).with("Ofst", offset).with("Mtrx", Value::List(m)) - } - - fn longs(m: &[i32]) -> Vec { - m.iter().map(|v| Value::Integer(*v)).collect() - } - - #[test] - fn offset_round_trips_every_fill_mode() { - for (fill, ours) in [("Wrp ", "wrap"), ("Rpt ", "repeat"), ("Bckg", "transparent")] { - for (h, v) in [(0, 0), (12, -7), (5, 3), (i32::MIN, i32::MAX)] { - let f = sf("filter.other.offset", json!({"horizontal": h, "vertical": v, "undefinedAreas": ours})); - let d = item_for_filter(&f).unwrap(); - let fltr = get_desc(&d, "Fltr").unwrap(); - assert_eq!(*fltr, offset_fltr(Value::Integer(h), Value::Integer(v), enumv("FlMd", fill))); - assert_eq!(int(&d, "filterID"), Some(1_332_114_292)); - assert_eq!(filter_from_item(&Descriptor::from_bytes(&d.to_bytes()).unwrap()), f); - } - } - } - - /// The measured descriptors (Wrap 0/0, Set to Background 12/−7, Repeat 5/3) open as Offset. - #[test] - fn offset_measured_descriptors_open_as_offset() { - for (h, v, fill, ours) in [(0, 0, "Wrp ", "wrap"), (12, -7, "Bckg", "transparent"), (5, 3, "Rpt ", "repeat")] { - let item = measured_named_item(b"Ofst", "Offset...", offset_fltr(Value::Integer(h), Value::Integer(v), enumv("FlMd", fill))); - let f = filter_from_item(&item); - assert_eq!(f.command, "filter.other.offset"); - assert_eq!(f.params, json!({"horizontal": h, "vertical": v, "undefinedAreas": ours})); - // Written back exactly as measured. - assert_eq!(item_for_filter(&f).unwrap(), item); - } - } - - #[test] - fn offset_written_with_engine_defaults() { - // No params: 0, 0, Wrap Around (the engine's defaults); fractional pixels round. - let d = item_for_filter(&sf("filter.other.offset", json!({}))).unwrap(); - assert_eq!(*get_desc(&d, "Fltr").unwrap(), offset_fltr(Value::Integer(0), Value::Integer(0), enumv("FlMd", "Wrp "))); - let d = item_for_filter(&sf("filter.other.offset", json!({"horizontal": 2.6, "vertical": 3e12, "undefinedAreas": "bogus"}))).unwrap(); - assert_eq!(*get_desc(&d, "Fltr").unwrap(), offset_fltr(Value::Integer(3), Value::Integer(i32::MAX), enumv("FlMd", "Wrp "))); - } - - #[test] - fn malformed_offset_is_kept_verbatim() { - let i = Value::Integer; - for fltr in [ - offset_fltr(i(1), i(2), enumv("FlMd", "Xxxx")), - offset_fltr(i(1), i(2), Value::Integer(1)), - offset_fltr(Value::Double(1.5), i(2), enumv("FlMd", "Wrp ")), - offset_fltr(i(1), unit(b"#Pxl", f64::NAN), enumv("FlMd", "Wrp ")), - Descriptor::new("Ofst").with("Hrzn", i(1)).with("Fl ", enumv("FlMd", "Wrp ")), - Descriptor::new("Ofst"), - // A mistyped enum, a setting we don't write back and a repeated one. - offset_fltr(i(1), i(2), enumv("Xxxx", "Wrp ")), - offset_fltr(i(1), i(2), enumv("FlMd", "Wrp ")).with("Xtra", i(1)), - offset_fltr(i(1), i(2), enumv("FlMd", "Wrp ")).with("Hrzn", i(3)), - ] { - let item = measured_named_item(b"Ofst", "Offset...", fltr); - let f = filter_from_item(&item); - assert_eq!(f.command, UNSUPPORTED_FILTER, "{item:?}"); - assert_eq!(item_for_filter(&f).unwrap().to_bytes(), item.to_bytes(), "kept byte for byte"); - } - let bare = Descriptor::new("filterFX").with("filterID", Value::Integer(code(b"Ofst"))); - assert_eq!(filter_from_item(&bare).command, UNSUPPORTED_FILTER); - } - - #[test] - fn custom_round_trips() { - let edge: Vec = (0..25) - .map(|i| { - if i == 12 { - 8 - } else if (6..=18).contains(&i) && i % 5 != 0 && i % 5 != 4 { - -1 - } else { - 0 - } - }) - .collect(); - let full: Vec = (0..25).map(|i| i * 83 - 999).collect(); - for (kernel, scale, offset) in [(SHARPEN.to_vec(), 1, 0), (edge, 2, 10), (full, 9999, -9999), (vec![999; 25], 1, 9999)] { - let f = sf("filter.other.custom", json!({"kernel": kernel, "scale": scale, "offset": offset})); - let d = item_for_filter(&f).unwrap(); - assert_eq!(*get_desc(&d, "Fltr").unwrap(), custom_fltr(Value::Integer(scale), Value::Integer(offset), longs(&kernel))); - assert_eq!(int(&d, "filterID"), Some(1_131_639_917)); - assert_eq!(filter_from_item(&Descriptor::from_bytes(&d.to_bytes()).unwrap()), f); - } - } - - /// The measured descriptors (the default sharpen; a blur at Scale 2, Offset 10) open as Custom. - #[test] - fn custom_measured_descriptors_open_as_custom() { - let blur = [0, 0, 0, 0, 0, 0, 1, 2, 1, 0, 0, 2, 4, 2, 0, 0, 1, 2, 1, 0, 0, 0, 0, 0, 0]; - for (kernel, scale, offset) in [(SHARPEN, 1, 0), (blur, 2, 10)] { - let item = measured_named_item(b"Cstm", "Custom...", custom_fltr(Value::Integer(scale), Value::Integer(offset), longs(&kernel))); - let f = filter_from_item(&item); - assert_eq!(f.command, "filter.other.custom"); - assert_eq!(f.params, json!({"kernel": kernel, "scale": scale, "offset": offset})); - assert_eq!(item_for_filter(&f).unwrap(), item); - } - } - - #[test] - fn custom_written_like_the_engine_reads_it() { - let fltr = |p: J| get_desc(&item_for_filter(&sf("filter.other.custom", p)).unwrap(), "Fltr").cloned().unwrap(); - // No kernel: the engine's identity; short kernels pad with 0; out-of-range values clamp. - let mut id = [0; 25]; - id[12] = 1; - assert_eq!(fltr(json!({})), custom_fltr(Value::Integer(1), Value::Integer(0), longs(&id))); - let mut short = [0; 25]; - short[0] = 3; - short[1] = -999; - assert_eq!(fltr(json!({"kernel": [3, -5000], "scale": 0, "offset": 20000})), custom_fltr(Value::Integer(1), Value::Integer(9999), longs(&short))); - // Fractions have no PSD equivalent. - for p in [json!({"kernel": [0.5]}), json!({"scale": 1.5}), json!({"offset": -0.25})] { - assert!(item_for_filter(&sf("filter.other.custom", p.clone())).is_err(), "{p}"); - } - } - - #[test] - fn malformed_custom_is_kept_verbatim() { - let i = Value::Integer; - let mut wrong_type = longs(&SHARPEN); - wrong_type[3] = Value::Double(1.0); - for fltr in [ - custom_fltr(i(1), i(0), longs(&SHARPEN[..24])), - custom_fltr(i(1), i(0), longs(&[0; 26])), - custom_fltr(i(1), i(0), wrong_type), - custom_fltr(i(1), i(0), longs(&[1000; 25])), - custom_fltr(i(0), i(0), longs(&SHARPEN)), - custom_fltr(i(10_000), i(0), longs(&SHARPEN)), - custom_fltr(i(1), i(-10_000), longs(&SHARPEN)), - custom_fltr(Value::Double(f64::NAN), i(0), longs(&SHARPEN)), - custom_fltr(i(1), unit(b"#Pxl", 1.0), longs(&SHARPEN)), - Descriptor::new("Cstm").with("Scl ", i(1)).with("Ofst", i(0)).with("Mtrx", i(5)), - Descriptor::new("Cstm").with("Scl ", i(1)).with("Mtrx", Value::List(longs(&SHARPEN))), - Descriptor::new("Cstm"), - // A setting we don't write back. - custom_fltr(i(1), i(0), longs(&SHARPEN)).with("Xtra", i(1)), - ] { - let item = measured_named_item(b"Cstm", "Custom...", fltr); - let f = filter_from_item(&item); - assert_eq!(f.command, UNSUPPORTED_FILTER, "{item:?}"); - assert_eq!(item_for_filter(&f).unwrap().to_bytes(), item.to_bytes(), "kept byte for byte"); - } - } - - /// A `filterFX` item holding `fltr`, as Photoshop writes a filter with options. - fn pixelate_item(name: &str, fltr: Descriptor, filter_id: i32) -> Descriptor { - Descriptor::new("filterFX") - .with("Nm ", Value::Text(UnicodeString::new_nul(name))) - .with("blendOptions", Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", 100.0)).with("Md ", enumv("BlnM", "Nrml")))) - .with("enab", Value::Boolean(true)) - .with("hasoptions", Value::Boolean(true)) - .with("FrgC", rgbc(0.0)) - .with("BckC", rgbc(255.0)) - .with("Fltr", Value::Descriptor(fltr)) - .with("filterID", Value::Integer(filter_id)) - } - - #[test] - fn mezzotint_round_trips_every_type_and_reads_photoshops_shape() { - for (code, ty) in MEZZOTINT_TYPES { - let f = sf("filter.pixelate.mezzotint", json!({"type": ty})); - let d = item_for_filter(&f).unwrap(); - assert_eq!(int(&d, "filterID"), Some(1_299_870_830)); - let fltr = get_desc(&d, "Fltr").unwrap(); - assert!(fltr.class_id.is("Mztn")); - assert_eq!(enum_of(fltr, "MztT"), Some(&code[..])); - assert!(matches!(fltr.get("MztT"), Some(Value::Enumerated { type_id, .. }) if type_id.is("MztT"))); - assert_eq!(filter_from_item(&Descriptor::from_bytes(&d.to_bytes()).unwrap()), f, "{ty}"); - } - // Measured in Photoshop: `{'_class': 'Mztn', 'MztT': 'MztT.CrsD'}` and `LngS`, filterID 1299870830. - for (code, ty) in [("CrsD", "coarseDots"), ("LngS", "longStrokes")] { - let item = pixelate_item("Mezzotint...", Descriptor::new("Mztn").with("MztT", enumv("MztT", code)), 1_299_870_830); - let f = filter_from_item(&item); - assert_eq!((f.command.as_str(), &f.params), ("filter.pixelate.mezzotint", &json!({"type": ty}))); - } - // No type or an unknown type is Fine Dots, like the engine; the seed - // (PhotoCraft only) is not saved. - for p in [json!({}), json!({"type": "sparkles"}), json!({"type": "fineDots", "seed": 77})] { - let d = item_for_filter(&sf("filter.pixelate.mezzotint", p)).unwrap(); - let fltr = get_desc(&d, "Fltr").unwrap(); - assert_eq!(enum_of(fltr, "MztT"), Some(&b"FnDt"[..])); - assert_eq!(fltr.items.len(), 1); - } - } - - #[test] - fn color_halftone_round_trips_and_reads_photoshops_shape() { - for p in [ - json!({"maxRadius": 8, "channel1": 108, "channel2": 162, "channel3": 90, "channel4": 45}), - json!({"maxRadius": 4, "channel1": -360, "channel2": 0, "channel3": 360, "channel4": -45}), - json!({"maxRadius": 127, "channel1": 1, "channel2": 2, "channel3": 3, "channel4": 4}), - ] { - let f = sf("filter.pixelate.colorHalftone", p); - let d = item_for_filter(&f).unwrap(); - assert_eq!(int(&d, "filterID"), Some(1_131_180_616)); - let fltr = get_desc(&d, "Fltr").unwrap(); - assert!(fltr.class_id.is("ClrH")); - for k in ["Rds ", "Ang1", "Ang2", "Ang3", "Ang4"] { - assert!(matches!(fltr.get(k), Some(Value::Integer(_))), "{k} is a long"); - } - assert_eq!(filter_from_item(&Descriptor::from_bytes(&d.to_bytes()).unwrap()), f); - } - // Measured in Photoshop: `{'_class': 'ClrH', 'Rds ': 6, 'Ang1': 10, 'Ang2': 20, 'Ang3': 30, 'Ang4': 40}`. - let measured = Descriptor::new("ClrH") - .with("Rds ", Value::Integer(6)) - .with("Ang1", Value::Integer(10)) - .with("Ang2", Value::Integer(20)) - .with("Ang3", Value::Integer(30)) - .with("Ang4", Value::Integer(40)); - let item = pixelate_item("Color Halftone...", measured.clone(), 1_131_180_616); - let f = filter_from_item(&item); - assert_eq!(f.command, "filter.pixelate.colorHalftone"); - assert_eq!(f.params, json!({"maxRadius": 6, "channel1": 10, "channel2": 20, "channel3": 30, "channel4": 40})); - assert_eq!(get_desc(&item_for_filter(&f).unwrap(), "Fltr"), Some(&measured)); - // Defaults and hostile values write longs within the dialog's ranges. - let d = item_for_filter(&sf("filter.pixelate.colorHalftone", json!({"maxRadius": f64::NAN, "channel1": 1e12, "channel2": -1e12, "channel3": "x"}))) - .unwrap(); - let fltr = get_desc(&d, "Fltr").unwrap(); - let got: Vec<_> = ["Rds ", "Ang1", "Ang2", "Ang3", "Ang4"].iter().map(|k| int(fltr, k)).collect(); - assert_eq!(got, [Some(8), Some(360), Some(-360), Some(90), Some(45)]); - } - - #[test] - fn malformed_pixelate_filters_stay_verbatim() { - let mz = |v: Value| Descriptor::new("Mztn").with("MztT", v); - let ch = |rds: Value, ang1: Value| { - Descriptor::new("ClrH") - .with("Rds ", rds) - .with("Ang1", ang1) - .with("Ang2", Value::Integer(20)) - .with("Ang3", Value::Integer(30)) - .with("Ang4", Value::Integer(40)) - }; - let cases = [ - pixelate_item("Mezzotint...", Descriptor::new("Mztn"), code(b"Mztn")), - pixelate_item("Mezzotint...", mz(enumv("MztT", "Sprk")), code(b"Mztn")), - pixelate_item("Mezzotint...", mz(Value::Integer(1)), code(b"Mztn")), - pixelate_item("Color Halftone...", Descriptor::new("ClrH"), code(b"ClrH")), - pixelate_item("Color Halftone...", ch(Value::Double(6.0), Value::Integer(10)), code(b"ClrH")), - pixelate_item("Color Halftone...", ch(unit(b"#Pxl", 6.0), Value::Integer(10)), code(b"ClrH")), - pixelate_item("Color Halftone...", ch(Value::Integer(3), Value::Integer(10)), code(b"ClrH")), - pixelate_item("Color Halftone...", ch(Value::Integer(128), Value::Integer(10)), code(b"ClrH")), - pixelate_item("Color Halftone...", ch(Value::Integer(6), Value::Integer(361)), code(b"ClrH")), - pixelate_item("Color Halftone...", ch(Value::Integer(6), Value::Integer(i32::MIN)), code(b"ClrH")), - pixelate_item("Color Halftone...", ch(Value::Integer(6), Value::Double(f64::NAN)), code(b"ClrH")), - // A mistyped enum and settings we don't write back. - pixelate_item("Mezzotint...", mz(enumv("Xxxx", "FnDt")), code(b"Mztn")), - pixelate_item("Mezzotint...", mz(enumv("MztT", "FnDt")).with("Xtra", Value::Integer(1)), code(b"Mztn")), - pixelate_item("Color Halftone...", ch(Value::Integer(6), Value::Integer(10)).with("Xtra", Value::Integer(1)), code(b"ClrH")), - pixelate_item("Color Halftone...", ch(Value::Integer(6), Value::Integer(10)).with("Ang1", Value::Integer(11)), code(b"ClrH")), - ]; - for item in cases { - let f = filter_from_item(&item); - assert_eq!(f.command, UNSUPPORTED_FILTER, "{:?}", get_desc(&item, "Fltr")); - // Written back with its own settings (blending is rewritten from the model). - let back = item_for_filter(&f).unwrap(); - // Compared as bytes: a NaN setting is not equal to itself. - let fltr = |d: &Descriptor| get_desc(d, "Fltr").map(Descriptor::to_bytes); - assert_eq!((fltr(&back), int(&back, "filterID")), (fltr(&item), int(&item, "filterID"))); - } - // Without a `Fltr` the filter has no settings to read: kept verbatim too. - let bare = Descriptor::new("filterFX").with("filterID", Value::Integer(code(b"ClrH"))); - assert_eq!(filter_from_item(&bare).command, UNSUPPORTED_FILTER); - } - - /// Distort smart filters from a Photoshop file open as their PhotoCraft filters, and the ones - /// PhotoCraft writes carry the same settings, keys and order as Photoshop's. - #[test] - fn photoshop_distort_filters_read_and_write_like_photoshop() { - for (command, params, hex) in PHOTOSHOP_FLTR { - let ps = Descriptor::from_bytes(&from_hex(hex).unwrap()).unwrap(); - let f = filter_from_item(&photoshop_fltr_item(ps.clone())); - let want: J = serde_json::from_str(params).unwrap(); - assert_eq!((f.command.as_str(), &f.params), (command, &want), "{command}"); - let ours = match item_for_filter(&f).unwrap().get("Fltr") { - Some(Value::Descriptor(d)) => d.clone(), - other => panic!("{command}: no Fltr ({other:?})"), - }; - assert_eq!((&ours.class_id, &ours.items), (&ps.class_id, &ps.items), "{command}: same keys, values and order"); - } - // A scaled wave can't be modelled, so it stays Photoshop's, unchanged. - let wave = Descriptor::from_bytes(&from_hex(PHOTOSHOP_WAVE).unwrap()).unwrap(); - let item = photoshop_fltr_item(wave); - let f = filter_from_item(&item); - assert_eq!(f.command, UNSUPPORTED_FILTER); - assert_eq!(item_for_filter(&f).unwrap().get("Fltr"), item.get("Fltr")); - // Unscaled, but with 332 generators (the renderer draws 64 at most), it stays Photoshop's too. - let mut unscaled = match item.get("Fltr") { - Some(Value::Descriptor(d)) => d.clone(), - other => panic!("wave: no Fltr ({other:?})"), - }; - set(&mut unscaled, "SclV", Value::Integer(100)); - let item = photoshop_fltr_item(unscaled); - let f = filter_from_item(&item); - assert_eq!(f.command, UNSUPPORTED_FILTER); - assert_eq!(item_for_filter(&f).unwrap().get("Fltr"), item.get("Fltr")); - - // An extra or repeated setting PhotoCraft doesn't model keeps the filter Photoshop's, unchanged. - let mut fltrs: Vec = PHOTOSHOP_FLTR.iter().map(|(_, _, hex)| Descriptor::from_bytes(&from_hex(hex).unwrap()).unwrap()).collect(); - let mut wave = unscaled_wave(); - set(&mut wave, "NmbG", Value::Integer(5)); - assert_eq!(filter_from_item(&photoshop_fltr_item(wave.clone())).command, "filter.distort.wave", "the plain wave maps"); - fltrs.push(wave); - for ps in fltrs { - let name = String::from_utf8_lossy(ps.class_id.as_bytes()).into_owned(); - let mut repeated = ps.clone(); - repeated.items.push(ps.items[0].clone()); - for odd in [ps.clone().with("Xtra", Value::Integer(7)), repeated] { - let item = photoshop_fltr_item(odd); - let f = filter_from_item(&item); - assert_eq!(f.command, UNSUPPORTED_FILTER, "{name}"); - assert_eq!(item_for_filter(&f).unwrap().get("Fltr"), item.get("Fltr"), "{name}: written back unchanged"); - } - } - } - - /// Photoshop's Wave ([`PHOTOSHOP_WAVE`]) at 100% scale both ways. - fn unscaled_wave() -> Descriptor { - let mut wave = Descriptor::from_bytes(&from_hex(PHOTOSHOP_WAVE).unwrap()).unwrap(); - set(&mut wave, "SclV", Value::Integer(100)); - wave - } - - /// An unscaled Wave opens as PhotoCraft's Wave (Triangle, the other settings as stored) up to - /// the generators the renderer models; one more and it stays Photoshop's, unchanged. - #[test] - fn wave_maps_up_to_the_generators_the_renderer_models() { - let max = i32::try_from(photocraft_algo::MAX_WAVE_GENERATORS).unwrap(); - assert_eq!(max, 64); - let mut wave = Descriptor::from_bytes(&from_hex(PHOTOSHOP_WAVE).unwrap()).unwrap(); - set(&mut wave, "SclV", Value::Integer(100)); - for (generators, mapped) in [(1, true), (max, true), (max + 1, false), (999, false), (0, false), (-1, false)] { - set(&mut wave, "NmbG", Value::Integer(generators)); - let item = photoshop_fltr_item(wave.clone()); - let f = filter_from_item(&item); - if mapped { - assert_eq!( - (f.command.as_str(), &f.params), - ( - "filter.distort.wave", - &json!({"type": "triangle", "generators": generators, "wavelengthMin": 213, "wavelengthMax": 214, "amplitudeMin": 240, - "amplitudeMax": 241, "undefinedAreas": "wrap", "seed": 1270346}) - ), - "{generators} generators" - ); - match item_for_filter(&f).unwrap().get("Fltr") { - Some(Value::Descriptor(ours)) => assert_eq!((&ours.class_id, &ours.items), (&wave.class_id, &wave.items), "{generators} generators"), - other => panic!("wave: no Fltr ({other:?})"), - } - } else { - assert_eq!(f.command, UNSUPPORTED_FILTER, "{generators} generators"); - assert_eq!(item_for_filter(&f).unwrap().get("Fltr"), item.get("Fltr"), "{generators} generators"); - } - } - } - - /// PhotoCraft draws at most `MAX_WAVE_GENERATORS` generators, so a Wave edited past that exports - /// the 64 it rendered, and a count below 1 exports 1, instead of Photoshop drawing more. - #[test] - fn wave_export_writes_only_the_generators_the_renderer_draws() { - let max = i32::try_from(photocraft_algo::MAX_WAVE_GENERATORS).unwrap(); - for (stored, written) in [(100, max), (999, max), (max + 1, max), (max, max), (5, 5), (1, 1), (0, 1), (-3, 1)] { - let wave = sf( - "filter.distort.wave", - json!({"type": "sine", "generators": stored, "wavelengthMin": 20, "wavelengthMax": 90, "amplitudeMin": 4, "amplitudeMax": 30}), - ); - let fltr = match item_for_filter(&wave).unwrap().get("Fltr") { - Some(Value::Descriptor(d)) => d.clone(), - other => panic!("wave: no Fltr ({other:?})"), - }; - assert_eq!(int(&fltr, "NmbG"), Some(written), "{stored} generators"); - } - } - - /// `RndS` is the seed the renderer draws with, also for a legacy signed or fractional seed - /// (stored as is by `layer.smartFilter.setParams`), not 0. - #[test] - fn wave_export_writes_the_seed_the_renderer_draws() { - for (stored, written) in [ - (json!(77), 77), - (json!(4_000_000_000u32), -294_967_296), - (json!(-1), -1), - (json!(7.4), 7), - (json!(-2.6), -3), - (json!(1e12), i32::MAX), - (json!("x"), 0), - ] { - let wave = sf("filter.distort.wave", json!({"generators": 3, "seed": stored})); - let fltr = match item_for_filter(&wave).unwrap().get("Fltr") { - Some(Value::Descriptor(d)) => d.clone(), - other => panic!("wave: no Fltr ({other:?})"), - }; - assert_eq!(int(&fltr, "RndS"), Some(written), "seed {stored}"); - // And it reads back as that bit pattern. - assert_eq!(known_params("Wave", Some(&fltr), &Descriptor::new("filterFX")).unwrap().1["seed"], json!(written as u32), "seed {stored}"); - } - } - - /// Invert on a smart object: Photoshop stores no `Fltr`, `hasoptions` false and its filter id. - #[test] - fn invert_smart_filter_reads_and_writes_like_photoshop() { - let item = Descriptor::new("filterFX") - .with("Nm ", Value::Text(UnicodeString::new_nul("Invert"))) - .with("blendOptions", Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", 100.0)).with("Md ", enumv("BlnM", "normal")))) - .with("enab", Value::Boolean(true)) - .with("hasoptions", Value::Boolean(false)) - .with("FrgC", rgbc(255.0)) - .with("BckC", rgbc(0.0)) - .with("filterID", Value::Integer(code(b"Invr"))); - let f = filter_from_item(&item); - assert_eq!((f.command.as_str(), &f.params), ("image.adjustments.invert", &json!({}))); - let back = item_for_filter(&f).unwrap(); - assert_eq!(back.get("Fltr"), None); - assert_eq!(back.get("hasoptions"), Some(&Value::Boolean(false))); - assert_eq!(back.get("filterID"), Some(&Value::Integer(code(b"Invr")))); - assert_eq!(back.get("Nm "), Some(&Value::Text(UnicodeString::new_nul("Invert")))); - } - - /// A filter PhotoCraft doesn't model, or a known one with settings it doesn't, is kept verbatim; only its visibility and blend change. - #[test] - fn photoshop_sharpen_without_fltr_imports_as_sharpen() { - // #6267: Photoshop's Sharpen item holds only its name, blending and `filterID`. - let item = Descriptor::new("filterFX") - .with("Nm ", Value::Text(UnicodeString::new_nul("Sharpen"))) - .with("blendOptions", Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", 100.0)).with("Md ", enumv("BlnM", "normal")))) - .with("enab", Value::Boolean(true)) - .with("hasoptions", Value::Boolean(false)) - .with("filterID", Value::Integer(1_399_353_968)); - let f = filter_from_item(&item); - assert_eq!((f.command.as_str(), &f.params), ("filter.sharpen.sharpen", &json!({}))); - // Hue/Saturation with an unnumbered range and Dust & Scratches with a missing setting fail - // cleanly instead of panicking. - let bad = SmartFilter { - command: "image.adjustments.hueSaturation".into(), - params: json!({"reds": {"range": [1, "x", 3, 4]}}), - blend: BlendMode::Normal, - opacity: 1.0, - visible: true, - }; - assert!(item_for_filter(&bad).is_err()); - let dust = Descriptor::new("filterFX") - .with("Fltr", Value::Descriptor(Descriptor::new("DstS").with("Rds ", Value::Integer(3)))) - .with("filterID", Value::Integer(code(b"DstS"))); - assert_eq!(filter_from_item(&dust).command, UNSUPPORTED_FILTER); - } - - #[test] - fn hue_saturation_ranges_are_not_lost() { - let hue_sat = |params: J| item_for_filter(&sf("image.adjustments.hueSaturation", params)); - // A range that is not an object is an error, not a silently dropped setting. - assert!(hue_sat(json!({"reds": 5})).is_err()); - assert!(hue_sat(json!({"reds": null})).is_ok()); - // Colorize's 25% default is the master saturation's only: a range's stays 0. - let d = hue_sat(json!({"colorize": true, "reds": {"hue": 5}})).unwrap(); - let adjs = adjustment_list(get_desc(&d, "Fltr").unwrap()).unwrap(); - let saturations: Vec<_> = adjs.iter().map(|a| int(a, "Strt")).collect(); - assert_eq!(saturations, [Some(25), Some(0)]); - // A repeated range (or master) would overwrite the first: the filter is kept verbatim. - let entry = |range: Option| { - let e = Descriptor::new("Hst2").with("H ", Value::Integer(0)).with("Strt", Value::Integer(0)).with("Lght", Value::Integer(0)); - let Some(r) = range else { return Value::Descriptor(e) }; - let e = ["BgnR", "BgnS", "EndS", "EndR"].iter().fold(e.with("LclR", Value::Integer(r)), |e, k| e.with(k, Value::Integer(10))); - Value::Descriptor(e) - }; - for adjs in [vec![entry(None), entry(Some(1)), entry(Some(1))], vec![entry(None), entry(None)]] { - let fltr = Descriptor::new("HStr").with("Clrz", Value::Boolean(false)).with("Adjs", Value::List(adjs)); - let item = Descriptor::new("filterFX") - .with("Nm ", Value::Text(UnicodeString::new_nul("Hue/Saturation..."))) - .with( - "blendOptions", - Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", 100.0)).with("Md ", enumv("BlnM", "normal"))), - ) - .with("enab", Value::Boolean(true)) - .with("Fltr", Value::Descriptor(fltr)) - .with("filterID", Value::Integer(code(b"HStr"))); - let f = filter_from_item(&item); - assert_eq!(f.command, UNSUPPORTED_FILTER); - assert_eq!(item_for_filter(&f).unwrap(), item); - } - } - - #[test] - fn unknown_filters_keep_their_descriptor() { - let item = Descriptor::new("filterFX") - .with("Nm ", Value::Text(UnicodeString::new_nul("Shear..."))) - .with("blendOptions", Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", 100.0)).with("Md ", enumv("BlnM", "normal")))) - .with("enab", Value::Boolean(true)) - .with("Fltr", Value::Descriptor(Descriptor::new("Shr ").with("UndA", enumv("UndA", "WrpA")))) - .with("filterID", Value::Integer(code(b"Shr "))); - let f = filter_from_item(&item); - assert_eq!(f.command, UNSUPPORTED_FILTER); - assert_eq!(f.params["name"], "Shear..."); - assert_eq!(item_for_filter(&f).unwrap(), item); - // Hidden and re-blended: only those keys change. - let mut g = f.clone(); - g.visible = false; - g.blend = BlendMode::Screen; - let back = filter_from_item(&item_for_filter(&g).unwrap()); - assert_eq!((back.visible, back.blend, &back.params), (false, BlendMode::Screen, &f.params)); - // A known filter with a setting we don't model is kept verbatim too. - let odd = Descriptor::new("filterFX").with("Fltr", Value::Descriptor(Descriptor::new("GsnB"))).with("filterID", Value::Integer(code(b"GsnB"))); - assert_eq!(filter_from_item(&odd).command, UNSUPPORTED_FILTER); - } - - /// A `filterFXList` item with filter `fltr` and `filterID`, as Photoshop saves it. - fn ps_item(name: &str, fltr: Descriptor, filter_id: i32) -> Descriptor { - Descriptor::new("filterFX") - .with("Nm ", Value::Text(UnicodeString::new_nul(name))) - .with("blendOptions", Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", 100.0)).with("Md ", enumv("BlnM", "normal")))) - .with("enab", Value::Boolean(true)) - .with("hasoptions", Value::Boolean(true)) - .with("FrgC", rgbc(0.0)) - .with("BckC", rgbc(255.0)) - .with("Fltr", Value::Descriptor(fltr)) - .with("filterID", Value::Integer(filter_id)) - } - - fn surface_blur(rds: f64, thsh: i32) -> Descriptor { - Descriptor::new("surfaceBlur").with("Rds ", unit(b"#Pxl", rds)).with("Thsh", Value::Integer(thsh)) - } - - fn smart_blur(rds: f64, thsh: f64, q: &str, m: &str) -> Descriptor { - Descriptor::new("SmrB").with("Rds ", Value::Double(rds)).with("Thsh", Value::Double(thsh)).with("SmBQ", enumv("SmBQ", q)).with("SmBM", enumv("SmBM", m)) - } - - fn radial_blur(amnt: i32, m: &str, q: &str) -> Descriptor { - Descriptor::new("RdlB").with("Amnt", Value::Integer(amnt)).with("BlrM", enumv("BlrM", m)).with("BlrQ", enumv("BlrQ", q)) - } - - /// The `Fltr` shapes measured in Photoshop (each filter applied to a smart object through - /// Action Manager, saved, and `filterFX` read back) open as our filters and are written back - /// with the same keys, value types, units, enums and filter ids. - #[test] - fn blur_family_matches_photoshop_shapes() { - let smart = code(b"SmrB"); - let radial = code(b"RdlB"); - assert_eq!((smart, radial), (1_399_681_602, 1_382_313_026)); - let cases = [ - (surface_blur(5.0, 15), 1135, "filter.blur.surfaceBlur", json!({"radius": 5.0, "threshold": 15})), - (surface_blur(12.0, 40), 1135, "filter.blur.surfaceBlur", json!({"radius": 12.0, "threshold": 40})), - ( - smart_blur(5.0, 25.0, "SBQH", "SBMN"), - smart, - "filter.blur.smartBlur", - json!({"radius": 5.0, "threshold": 25.0, "quality": "high", "mode": "normal"}), - ), - ( - smart_blur(3.0, 30.0, "SBQL", "SBME"), - smart, - "filter.blur.smartBlur", - json!({"radius": 3.0, "threshold": 30.0, "quality": "low", "mode": "edgeOnly"}), - ), - ( - smart_blur(3.0, 30.0, "SBQM", "SBMO"), - smart, - "filter.blur.smartBlur", - json!({"radius": 3.0, "threshold": 30.0, "quality": "medium", "mode": "overlayEdge"}), - ), - (radial_blur(10, "Spn ", "Drft"), radial, "filter.blur.radialBlur", json!({"amount": 10, "method": "spin", "quality": "draft"})), - (radial_blur(20, "Spn ", "Bst "), radial, "filter.blur.radialBlur", json!({"amount": 20, "method": "spin", "quality": "best"})), - (radial_blur(20, "Zm ", "Gd "), radial, "filter.blur.radialBlur", json!({"amount": 20, "method": "zoom", "quality": "good"})), - ]; - for (fltr, id, command, params) in cases { - let item = ps_item("x", fltr.clone(), id); - let f = filter_from_item(&Descriptor::from_bytes(&item.to_bytes()).unwrap()); - assert_eq!((f.command.as_str(), &f.params), (command, ¶ms), "{fltr:?}"); - let out = item_for_filter(&f).unwrap(); - assert_eq!(out.get("filterID"), Some(&Value::Integer(id))); - assert_eq!(out.get("hasoptions"), Some(&Value::Boolean(true))); - // Byte-identical filter descriptor: class id, four-char keys, types, units and enums. - let Some(Value::Descriptor(w)) = out.get("Fltr") else { panic!("no Fltr for {command}") }; - assert_eq!(w.to_bytes(), fltr.to_bytes(), "{command}"); - } - // Surface Blur's class is a string id; Smart Blur's and Radial Blur's are four-char codes. - assert_eq!(surface_blur(1.0, 2).class_id, Id::Str(b"surfaceBlur".to_vec())); - assert_eq!(radial_blur(1, "Spn ", "Gd ").class_id, Id::Code(*b"RdlB")); - // Unset options are written with the dialog defaults. - let fltr = |c: &str, p: J| item_for_filter(&sf(c, p)).unwrap().get("Fltr").cloned(); - assert_eq!(fltr("filter.blur.surfaceBlur", json!({})), Some(Value::Descriptor(surface_blur(5.0, 15)))); - assert_eq!(fltr("filter.blur.smartBlur", json!({})), Some(Value::Descriptor(smart_blur(3.0, 25.0, "SBQH", "SBMN")))); - assert_eq!(fltr("filter.blur.radialBlur", json!({"centerX": 0.5, "centerY": 0.5})), Some(Value::Descriptor(radial_blur(10, "Spn ", "Gd ")))); - } - - /// `d` with `key` set to `v` (replacing the measured value). - fn replaced(mut d: Descriptor, key: &str, v: Value) -> Descriptor { - set(&mut d, key, v); - d - } - - /// Malformed or unmodelled blur descriptors stay verbatim (and are written back unchanged); - /// settings PSD can't hold are reported, never a panic. - #[test] - fn blur_family_malformed_is_kept_verbatim() { - let smart = code(b"SmrB"); - let radial = code(b"RdlB"); - let text = |s: &str| Value::Text(UnicodeString::new_nul(s)); - let bad = [ - // Missing keys. - (Descriptor::new("surfaceBlur").with("Rds ", unit(b"#Pxl", 5.0)), 1135), - (Descriptor::new("SmrB").with("Rds ", Value::Double(3.0)).with("Thsh", Value::Double(25.0)), smart), - (Descriptor::new("RdlB").with("Amnt", Value::Integer(10)).with("BlrM", enumv("BlrM", "Spn ")), radial), - // Wrong types. - (Descriptor::new("surfaceBlur").with("Rds ", unit(b"#Pxl", 5.0)).with("Thsh", Value::Double(15.0)), 1135), - ( - Descriptor::new("SmrB") - .with("Rds ", text("3")) - .with("Thsh", Value::Double(25.0)) - .with("SmBQ", enumv("SmBQ", "SBQH")) - .with("SmBM", enumv("SmBM", "SBMN")), - smart, - ), - (Descriptor::new("RdlB").with("Amnt", text("10")).with("BlrM", enumv("BlrM", "Spn ")).with("BlrQ", enumv("BlrQ", "Gd ")), radial), - (Descriptor::new("RdlB").with("Amnt", Value::Integer(10)).with("BlrM", Value::Integer(1)).with("BlrQ", enumv("BlrQ", "Gd ")), radial), - // Out of range, NaN and infinity. - (surface_blur(0.5, 15), 1135), - (surface_blur(5.0, 300), 1135), - (surface_blur(f64::NAN, 15), 1135), - (smart_blur(f64::INFINITY, 25.0, "SBQH", "SBMN"), smart), - (smart_blur(3.0, 0.0, "SBQH", "SBMN"), smart), - (radial_blur(0, "Spn ", "Gd "), radial), - (radial_blur(101, "Zm ", "Gd "), radial), - // Unknown enum values. - (smart_blur(3.0, 25.0, "SBQX", "SBMN"), smart), - (smart_blur(3.0, 25.0, "Hgh ", "SBMN"), smart), - (radial_blur(10, "Twrl", "Gd "), radial), - (radial_blur(10, "Spn ", "Hgh "), radial), - // A key we don't model (an off-centre Radial Blur would carry one). - (radial_blur(10, "Zm ", "Gd ").with("Cntr", Value::Descriptor(Descriptor::new("Pnt ").with("Hrzn", Value::Double(10.0)))), radial), - (surface_blur(5.0, 15).with("Edg ", Value::Integer(1)), 1135), - // Enums of another type, units and value types we would not write back. - (replaced(smart_blur(3.0, 25.0, "SBQH", "SBMN"), "SmBQ", enumv("Othr", "SBQH")), smart), - (replaced(smart_blur(3.0, 25.0, "SBQH", "SBMN"), "SmBM", enumv("SmBQ", "SBMN")), smart), - (replaced(radial_blur(10, "Spn ", "Gd "), "BlrM", enumv("Othr", "Spn ")), radial), - (replaced(radial_blur(10, "Spn ", "Gd "), "BlrQ", enumv("BlrM", "Gd ")), radial), - (Descriptor::new("surfaceBlur").with("Rds ", unit(b"#Prc", 5.0)).with("Thsh", Value::Integer(15)), 1135), - (Descriptor::new("surfaceBlur").with("Rds ", Value::Double(5.0)).with("Thsh", Value::Integer(15)), 1135), - (replaced(smart_blur(3.0, 25.0, "SBQH", "SBMN"), "Rds ", unit(b"#Pxl", 3.0)), smart), - (replaced(smart_blur(3.0, 25.0, "SBQH", "SBMN"), "Thsh", unit(b"#Prc", 25.0)), smart), - (replaced(smart_blur(3.0, 25.0, "SBQH", "SBMN"), "Thsh", Value::Integer(25)), smart), - ]; - for (fltr, id) in bad { - let item = ps_item("x", fltr.clone(), id); - let f = filter_from_item(&item); - assert_eq!(f.command, UNSUPPORTED_FILTER, "{fltr:?}"); - // Compared as bytes: a NaN setting is not equal to itself. - assert_eq!(item_for_filter(&f).unwrap().to_bytes(), item.to_bytes(), "{fltr:?}"); - } - // Radial Blur at its defaults has no `Fltr` (measured): its values are not stored, so the - // entry stays verbatim instead of guessing them. - let no_opts = Descriptor::new("filterFX").with("hasoptions", Value::Boolean(false)).with("filterID", Value::Integer(radial)); - assert_eq!(filter_from_item(&no_opts).command, UNSUPPORTED_FILTER); - // Settings with no PSD equivalent are errors when writing. - for (command, p) in [ - ("filter.blur.smartBlur", json!({"quality": "ultra"})), - ("filter.blur.smartBlur", json!({"mode": 3})), - ("filter.blur.radialBlur", json!({"method": "twirl"})), - ("filter.blur.radialBlur", json!({"quality": ["best"]})), - ("filter.blur.radialBlur", json!({"centerX": 0.25})), - ("filter.blur.radialBlur", json!({"centerY": 1.0})), - // A centre, or a value, that is there but can't be written as Photoshop would open it. - ("filter.blur.radialBlur", json!({"centerX": "middle"})), - ("filter.blur.radialBlur", json!({"centerY": true})), - ("filter.blur.radialBlur", json!({"amount": 0})), - ("filter.blur.radialBlur", json!({"amount": 101})), - ("filter.blur.radialBlur", json!({"amount": "10"})), - ("filter.blur.surfaceBlur", json!({"radius": 0.5})), - ("filter.blur.surfaceBlur", json!({"radius": 100.5})), - ("filter.blur.surfaceBlur", json!({"threshold": 1})), - ("filter.blur.surfaceBlur", json!({"threshold": 256})), - ("filter.blur.surfaceBlur", json!({"radius": "5"})), - ("filter.blur.smartBlur", json!({"radius": 0.05})), - ("filter.blur.smartBlur", json!({"threshold": 100.5})), - ("filter.blur.smartBlur", json!({"threshold": [25]})), - ] { - assert!(item_for_filter(&sf(command, p.clone())).is_err(), "{command} {p}"); - } - // Every value that is written opens again as the same editable filter (range ends included). - for (command, p) in [ - ("filter.blur.surfaceBlur", json!({"radius": 1.0, "threshold": 2})), - ("filter.blur.surfaceBlur", json!({"radius": 100.0, "threshold": 255})), - ("filter.blur.smartBlur", json!({"radius": 0.1, "threshold": 100.0, "quality": "low", "mode": "edgeOnly"})), - ("filter.blur.radialBlur", json!({"amount": 1, "method": "zoom", "quality": "best", "centerX": 0.5, "centerY": null})), - ("filter.blur.radialBlur", json!({"amount": 100, "method": "spin", "quality": "draft"})), - ] { - let back = filter_from_item(&item_for_filter(&sf(command, p.clone())).unwrap()); - assert_eq!(back.command, command, "{p}"); - } - // Hostile numbers write without panicking. - for p in [json!({"radius": f64::MAX, "threshold": -1e300, "amount": 1e300}), json!({"radius": "x", "threshold": null}), json!(null), json!([1, 2])] { - for command in ["filter.blur.surfaceBlur", "filter.blur.smartBlur", "filter.blur.radialBlur"] { - let _ = item_for_filter(&sf(command, p.clone())); - } - } - } - - /// A `filterFX` entry shaped as Photoshop saves it (measured in Photoshop: the filter applied - /// through Action Manager to a smart object, the PSD saved, `filterFX` read back). - fn photoshop_item(filter_id: &[u8; 4], fltr: Descriptor) -> Descriptor { - Descriptor::new("filterFX") - .with("Nm ", Value::Text(UnicodeString::new_nul("Filter..."))) - .with("blendOptions", blend_options(&sf("", J::Null))) - .with("enab", Value::Boolean(true)) - .with("hasoptions", Value::Boolean(true)) - .with("FrgC", rgbc(0.0)) - .with("BckC", rgbc(255.0)) - .with("Fltr", Value::Descriptor(fltr)) - .with("filterID", Value::Integer(code(filter_id))) - } - - #[test] - fn stylize_and_pixelate_filters_open_from_photoshop_shapes() { - let cases = [ - (b"Dfs ", Descriptor::new("Dfs ").with("Md ", enumv("DfsM", "Nrml")), "filter.stylize.diffuse", json!({"mode": "normal"})), - (b"Dfs ", Descriptor::new("Dfs ").with("Md ", enumv("DfsM", "DrkO")), "filter.stylize.diffuse", json!({"mode": "darkenOnly"})), - (b"Dfs ", Descriptor::new("Dfs ").with("Md ", enumv("DfsM", "LghO")), "filter.stylize.diffuse", json!({"mode": "lightenOnly"})), - (b"Dfs ", Descriptor::new("Dfs ").with("Md ", enumv("DfsM", "anisotropic")), "filter.stylize.diffuse", json!({"mode": "anisotropic"})), - ( - b"TrcC", - Descriptor::new("TrcC").with("Lvl ", Value::Integer(128)).with("Edg ", enumv("CntE", "Upr ")), - "filter.stylize.traceContour", - json!({"level": 128, "edge": "upper"}), - ), - ( - b"TrcC", - Descriptor::new("TrcC").with("Lvl ", Value::Integer(60)).with("Edg ", enumv("CntE", "Lwr ")), - "filter.stylize.traceContour", - json!({"level": 60, "edge": "lower"}), - ), - (b"Crst", Descriptor::new("Crst").with("ClSz", Value::Integer(10)), "filter.pixelate.crystallize", json!({"cellSize": 10})), - ( - b"Pntl", - Descriptor::new("Pntl").with("ClSz", Value::Integer(7)), - "filter.pixelate.pointillize", - json!({"cellSize": 7, "background": [1.0, 1.0, 1.0, 1.0]}), - ), - ]; - for (id, fltr, command, params) in cases { - let item = photoshop_item(id, fltr); - // Through bytes, as read from a file. - let f = filter_from_item(&Descriptor::from_bytes(&item.to_bytes()).unwrap()); - assert_eq!((f.command.as_str(), &f.params), (command, ¶ms)); - // Written back in the measured shape: same class, keys, value types and filterID. - let back = item_for_filter(&f).unwrap(); - for key in ["Fltr", "filterID", "BckC"] { - assert_eq!(back.get(key), item.get(key), "{command} {key}"); - } - } - // The `anisotropic` mode is a long id, as Photoshop writes it. - let d = item_for_filter(&sf("filter.stylize.diffuse", json!({"mode": "anisotropic"}))).unwrap(); - let Some(Value::Descriptor(fltr)) = d.get("Fltr") else { panic!("no Fltr") }; - assert!(matches!(fltr.get("Md "), Some(Value::Enumerated { value: Id::Str(v), .. }) if v == b"anisotropic")); - // Pointillize takes the entry's background colour; the others ignore it. - let mut item = photoshop_item(b"Pntl", Descriptor::new("Pntl").with("ClSz", Value::Integer(7))); - set(&mut item, "BckC", rgbc(51.0)); - let f = filter_from_item(&item); - assert_eq!(f.params["background"], json!([0.2, 0.2, 0.2, 1.0])); - assert_eq!(item_for_filter(&f).unwrap().get("BckC"), Some(&rgbc(51.0))); - let mut item = photoshop_item(b"Crst", Descriptor::new("Crst").with("ClSz", Value::Integer(7))); - set(&mut item, "BckC", rgbc(51.0)); - assert_eq!(filter_from_item(&item).params, json!({"cellSize": 7})); - // Our random seed has no PSD key: it is not written. - let fltr = |c: &str, p: J| item_for_filter(&sf(c, p)).unwrap().get("Fltr").cloned(); - assert_eq!( - fltr("filter.stylize.diffuse", json!({"mode": "normal", "seed": 7})), - Some(Value::Descriptor(Descriptor::new("Dfs ").with("Md ", enumv("DfsM", "Nrml")))) - ); - // Defaults and out-of-range values are written in Photoshop's ranges. - assert_eq!( - fltr("filter.stylize.traceContour", json!({})), - Some(Value::Descriptor(Descriptor::new("TrcC").with("Lvl ", Value::Integer(128)).with("Edg ", enumv("CntE", "Lwr ")))) - ); - assert_eq!(fltr("filter.pixelate.crystallize", json!({})), Some(Value::Descriptor(Descriptor::new("Crst").with("ClSz", Value::Integer(10))))); - assert_eq!(fltr("filter.pixelate.pointillize", json!({})), Some(Value::Descriptor(Descriptor::new("Pntl").with("ClSz", Value::Integer(5))))); - assert_eq!( - fltr("filter.pixelate.crystallize", json!({"cellSize": 1e9})), - Some(Value::Descriptor(Descriptor::new("Crst").with("ClSz", Value::Integer(300)))) - ); - assert_eq!( - fltr("filter.pixelate.pointillize", json!({"cellSize": "big"})), - Some(Value::Descriptor(Descriptor::new("Pntl").with("ClSz", Value::Integer(5)))) - ); - assert_eq!( - fltr("filter.stylize.traceContour", json!({"level": -40, "edge": "upper"})), - Some(Value::Descriptor(Descriptor::new("TrcC").with("Lvl ", Value::Integer(0)).with("Edg ", enumv("CntE", "Upr ")))) - ); - } - - #[test] - fn malformed_stylize_and_pixelate_filters_are_kept_verbatim() { - let long = Value::Integer; - let cases = [ - // Missing keys. - (b"Dfs ", Descriptor::new("Dfs ")), - (b"TrcC", Descriptor::new("TrcC").with("Lvl ", long(60))), - (b"TrcC", Descriptor::new("TrcC").with("Edg ", enumv("CntE", "Upr "))), - (b"Crst", Descriptor::new("Crst")), - (b"Pntl", Descriptor::new("Pntl")), - // Unknown enum values or enum types. - (b"Dfs ", Descriptor::new("Dfs ").with("Md ", enumv("DfsM", "Wild"))), - (b"Dfs ", Descriptor::new("Dfs ").with("Md ", enumv("BlnM", "Nrml"))), - (b"TrcC", Descriptor::new("TrcC").with("Lvl ", long(60)).with("Edg ", enumv("CntE", "Mddl"))), - // Wrong types (also NaN). - (b"Dfs ", Descriptor::new("Dfs ").with("Md ", long(1))), - (b"TrcC", Descriptor::new("TrcC").with("Lvl ", Value::Double(60.0)).with("Edg ", enumv("CntE", "Upr "))), - (b"Crst", Descriptor::new("Crst").with("ClSz", unit(b"#Pxl", 10.0))), - (b"Pntl", Descriptor::new("Pntl").with("ClSz", Value::Double(f64::NAN))), - // Out of range. - (b"TrcC", Descriptor::new("TrcC").with("Lvl ", long(256)).with("Edg ", enumv("CntE", "Upr "))), - (b"TrcC", Descriptor::new("TrcC").with("Lvl ", long(-1)).with("Edg ", enumv("CntE", "Upr "))), - (b"Crst", Descriptor::new("Crst").with("ClSz", long(2))), - (b"Pntl", Descriptor::new("Pntl").with("ClSz", long(i32::MAX))), - ]; - for (id, fltr) in cases { - let item = photoshop_item(id, fltr); - let f = filter_from_item(&Descriptor::from_bytes(&item.to_bytes()).unwrap()); - assert_eq!(f.command, UNSUPPORTED_FILTER, "{item:?}"); - assert_eq!(item_for_filter(&f).unwrap().to_bytes(), item.to_bytes()); - } - // Saved without options (`hasoptions` false, no `Fltr`): kept verbatim. - let bare = Descriptor::new("filterFX").with("hasoptions", Value::Boolean(false)).with("filterID", Value::Integer(code(b"Crst"))); - assert_eq!(filter_from_item(&bare).command, UNSUPPORTED_FILTER); - // A Pointillize entry whose background colour is unreadable is kept verbatim too. - for bad in [Value::Integer(3), Value::Descriptor(Descriptor::new("RGBC").with("Rd ", Value::Double(0.0)))] { - let mut item = photoshop_item(b"Pntl", Descriptor::new("Pntl").with("ClSz", Value::Integer(7))); - set(&mut item, "BckC", bad); - assert_eq!(filter_from_item(&item).command, UNSUPPORTED_FILTER); - } - // Values with no PSD equivalent are reported, not guessed. - for (c, p) in [ - ("filter.stylize.diffuse", json!({"mode": "sideways"})), - ("filter.stylize.diffuse", json!({"mode": 3})), - ("filter.stylize.traceContour", json!({"edge": "middle"})), - ("filter.pixelate.pointillize", json!({"background": "teal"})), - ("filter.pixelate.pointillize", json!({"background": [1.0]})), - ] { - assert!(item_for_filter(&sf(c, p.clone())).is_err(), "{c} {p}"); - } - } - - /// A Filter Gallery item as Photopea writes it (Chrome, Detail 12, Smoothness 4). - fn gallery_item_with(effects: Vec) -> Descriptor { - let rgb = - |v: f64| Value::Descriptor(Descriptor::new("RGBC").with("Rd ", Value::Double(v)).with("Grn ", Value::Double(v)).with("Bl ", Value::Double(v))); - Descriptor::new("filterFX") - .with("Nm ", Value::Text(UnicodeString::new_nul("Filtergalerie"))) - .with("blendOptions", Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", 100.0)).with("Md ", enumv("BlnM", "normal")))) - .with("enab", Value::Boolean(true)) - .with("hasoptions", Value::Boolean(true)) - .with("FrgC", rgb(0.0)) - .with("BckC", rgb(255.0)) - .with("Fltr", Value::Descriptor(Descriptor::new("GEfc").with("GEfs", Value::List(effects.into_iter().map(Value::Descriptor).collect())))) - .with("filterID", Value::Integer(code(b"GEfc"))) - } - - fn chrome(detail: i32, smoothness: i32, visible: bool) -> Descriptor { - Descriptor::new("GEfc") - .with("Dtl ", Value::Integer(detail)) - .with("Smth", Value::Integer(smoothness)) - .with("GEfk", enumv("GEft", "Chrm")) - .with("GELv", Value::Boolean(visible)) - } - - #[test] - fn filter_gallery_chrome_imports_as_editable_gallery() { - let f = filter_from_item(&gallery_item_with(vec![chrome(12, 4, true), chrome(3, 9, false)])); - assert_eq!(f.command, "filter.filterGallery"); - assert_eq!( - f.params, - json!({ - "effects": [ - {"filter": "chrome", "params": {"detail": 12, "smoothness": 4}, "visible": true}, - {"filter": "chrome", "params": {"detail": 3, "smoothness": 9}, "visible": false}, - ], - "foreground": [0.0, 0.0, 0.0, 1.0], - "background": [1.0, 1.0, 1.0, 1.0], - }) - ); - // Written back and read again: unchanged, also when re-blended and hidden. - let mut g = f.clone(); - g.blend = BlendMode::Multiply; - g.opacity = 0.5; - g.visible = false; - let d = item_for_filter(&g).unwrap(); - assert_eq!(filter_from_item(&Descriptor::from_bytes(&d.to_bytes()).unwrap()), g); - let fltr = get_desc(&d, "Fltr").unwrap(); - assert!(fltr.class_id.is("GEfc")); - assert_eq!(int(&d, "filterID"), Some(code(b"GEfc"))); - } - - /// A single effect as Photoshop 27 writes it: inline in `Fltr`, no `GEfs` list or `GELv`. - fn photoshop_chrome(detail: i32, smoothness: i32) -> Descriptor { - let rgb = - |v: f64| Value::Descriptor(Descriptor::new("RGBC").with("Rd ", Value::Double(v)).with("Grn ", Value::Double(v)).with("Bl ", Value::Double(v))); - let mut fltr = - Descriptor::new("GEfc").with("GEfk", enumv("GEft", "Chrm")).with("Dtl ", Value::Integer(detail)).with("Smth", Value::Integer(smoothness)); - fltr.name = UnicodeString::new_nul("Filter Gallery"); - Descriptor::new("filterFX") - .with("Nm ", Value::Text(UnicodeString::new_nul("Filter Gallery..."))) - .with("blendOptions", Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", 100.0)).with("Md ", enumv("BlnM", "Nrml")))) - .with("enab", Value::Boolean(true)) - .with("hasoptions", Value::Boolean(true)) - .with("FrgC", rgb(255.0)) - .with("BckC", rgb(0.0)) - .with("Fltr", Value::Descriptor(fltr)) - .with("filterID", Value::Integer(code(b"GEfc"))) - } - - #[test] - fn filter_gallery_photoshop_inline_effect_imports_and_writes_back_inline() { - let item = photoshop_chrome(10, 4); - let f = filter_from_item(&item); - assert_eq!(f.command, "filter.filterGallery"); - assert_eq!( - f.params, - json!({ - "effects": [{"filter": "chrome", "params": {"detail": 10, "smoothness": 4}, "visible": true}], - "foreground": [1.0, 1.0, 1.0, 1.0], - "background": [0.0, 0.0, 0.0, 1.0], - }) - ); - // Written back in Photoshop's own layout. - let d = item_for_filter(&f).unwrap(); - assert_eq!(get_desc(&d, "Fltr"), get_desc(&item, "Fltr")); - assert_eq!((get_desc(&d, "FrgC"), get_desc(&d, "BckC")), (get_desc(&item, "FrgC"), get_desc(&item, "BckC"))); - assert_eq!(filter_from_item(&Descriptor::from_bytes(&d.to_bytes()).unwrap()), f); - // A hidden single effect needs the list (only it has a visibility flag). - let mut hidden = f.clone(); - hidden.params["effects"][0]["visible"] = json!(false); - let d = item_for_filter(&hidden).unwrap(); - assert!(get_desc(&d, "Fltr").unwrap().get("GEfs").is_some()); - assert_eq!(filter_from_item(&d), hidden); - // Inline effects we don't model stay verbatim. - let mut odd = photoshop_chrome(10, 4); - set(&mut odd, "Fltr", Value::Descriptor(Descriptor::new("GEfc").with("GEfk", enumv("GEft", "Ctot")).with("Dtl ", Value::Integer(1)))); - assert_eq!(filter_from_item(&odd).command, UNSUPPORTED_FILTER); - let mut extra = photoshop_chrome(10, 4); - set(&mut extra, "Fltr", Value::Descriptor(Descriptor::new("GEfc").with("GEfk", enumv("GEft", "Chrm")).with("Xtra", Value::Integer(1)))); - assert_eq!(filter_from_item(&extra).command, UNSUPPORTED_FILTER); - } - - #[test] - fn gallery_table_matches_the_gallery_filters() { - for g in &GALLERY_EFFECTS { - let f = photocraft_algo::GalleryFilter::from_key(g.key).unwrap(); - let keys: Vec<&str> = f.params().iter().map(|p| p.key).collect(); - for (_, ours) in g.settings { - assert!(keys.contains(ours), "{}.{ours}", g.key); - } - } - } - - #[test] - fn filter_gallery_written_with_defaults_and_colours() { - let f = sf("filter.filterGallery", json!({"effects": [{"filter": "chrome"}], "foreground": "#ff0000", "background": [0.0, 0.0, 1.0, 1.0]})); - let back = filter_from_item(&item_for_filter(&f).unwrap()); - assert_eq!(back.params["effects"][0]["params"], json!({"detail": 4, "smoothness": 7})); - assert_eq!(back.params["foreground"], json!([1.0, 0.0, 0.0, 1.0])); - assert_eq!(back.params["background"], json!([0.0, 0.0, 1.0, 1.0])); - } - - #[test] - fn filter_gallery_we_dont_model_is_kept_verbatim() { - // Another effect, an extra setting, a wrong-typed setting, no effects, a non-list. - let other = Descriptor::new("GEfc").with("GEfk", enumv("GEft", "Ctot")).with("GELv", Value::Boolean(true)); - let extra = chrome(4, 7, true).with("Xtra", Value::Integer(1)); - let typed = Descriptor::new("GEfc").with("Dtl ", Value::Double(4.0)).with("GEfk", enumv("GEft", "Chrm")); - for effects in [vec![chrome(4, 7, true), other], vec![extra], vec![typed], vec![]] { - let item = gallery_item_with(effects); - let f = filter_from_item(&item); - assert_eq!(f.command, UNSUPPORTED_FILTER); - assert_eq!(item_for_filter(&f).unwrap(), item); - } - let odd = Descriptor::new("filterFX").with("Fltr", Value::Descriptor(Descriptor::new("GEfc").with("GEfs", Value::Integer(3)))); - assert_eq!(filter_from_item(&odd).command, UNSUPPORTED_FILTER); - let bare = Descriptor::new("filterFX").with("filterID", Value::Integer(code(b"GEfc"))); - assert_eq!(filter_from_item(&bare).command, UNSUPPORTED_FILTER); - } - - #[test] - fn filter_gallery_without_psd_equivalent_is_reported() { - for p in [ - json!({"effects": [{"filter": "cutout"}]}), - json!({"effects": [{"filter": "chrome", "params": {"sparkle": 1}}]}), - json!({"effects": [{"params": {}}]}), - json!({"effects": []}), - json!({}), - json!({"effects": [{"filter": "chrome"}], "list": true}), - json!({"effects": [{"filter": "chrome"}], "foreground": "red"}), - json!(null), - ] { - assert!(item_for_filter(&sf("filter.filterGallery", p.clone())).is_err(), "{p}"); - } - } - - /// Filters with no PSD equivalent are skipped with a warning each, and the writable ones around them still export. - #[test] - fn unwritable_filters_are_reported_not_fatal() { - let stack = FilterStack { - filters: vec![ - // Shear's curve isn't mapped to Photoshop's grid yet. - sf("filter.distort.shear", json!({"amount": 40})), - sf("filter.blur.gaussianBlur", json!({"radius": 2.0})), - sf(UNSUPPORTED_FILTER, json!({"psd": "zz"})), - sf("image.adjustments.levels", json!({"cyan": {"gamma": 2.0}})), - sf("image.adjustments.shadowsHighlights", json!({"shadowAmount": 50})), - ], - ..Default::default() - }; - let mut w = Vec::new(); - let d = filter_fx(&stack, "L", &mut w); - assert_eq!(w.len(), 4, "{w:?}"); - let back = filter_stack(&d); - assert_eq!(back.filters, vec![stack.filters[1].clone()]); - } - - #[test] - fn placed_blocks_parse_back() { - let t = Affine { m: [0.5, 0.1, -0.1, 0.5, 10.0, 20.0] }; - let stack = - FilterStack { enabled: false, filters: vec![sf("filter.blur.gaussianBlur", json!({"radius": 3.0}))], mask_enabled: false, mask_linked: true }; - let mut w = Vec::new(); - let spec = PlacedSpec { - idnt: "id-1", - placed: "pl-2", - transform: t, - perspective: None, - size: (64.0, 32.0), - dpi: 72.0, - warp: None, - filter_fx: Some(filter_fx(&stack, "L", &mut w)), - }; - let sold = sold_bytes(None, &spec, &mut w); - assert!(w.is_empty()); - assert_eq!(sold.len() % 4, 0); - let p = parse_sold(&sold).unwrap(); - assert_eq!((p.idnt.as_str(), p.placed.as_str()), ("id-1", "pl-2")); - for (a, b) in p.transform.m.iter().zip(t.m) { - assert!((a - b).abs() < 1e-9); - } - assert_eq!(p.stack, Some(stack)); - let tb = photocraft_psd::TaggedBlock::new(*b"SoLd", sold.clone()); - tb.check_structure().unwrap(); - let pl = photocraft_psd::TaggedBlock::new(*b"PlLd", plld_bytes(&spec, &mut w)); - pl.check_structure().unwrap(); - // A template keeps its other keys; an unmoved transform keeps its exact quad. - let mut tmpl = sold_descriptor(&sold).unwrap(); - tmpl.items.push((Id::new("extraKey"), Value::Integer(7))); - let again = sold_bytes(Some(&tmpl), &PlacedSpec { filter_fx: None, ..spec }, &mut w); - let d = sold_descriptor(&again).unwrap(); - assert_eq!(d.get("extraKey"), Some(&Value::Integer(7))); - assert!(d.get("filterFX").is_none()); - assert_eq!(d.get("Trnf"), tmpl.get("Trnf")); - } - - /// A Distort / Perspective placement goes out as its four corners (`Trnf`, `nonAffineTransform`) - /// and comes back as the same projective map; an affine one reads back as no perspective. - #[test] - fn perspective_placement_round_trips_through_sold() { - let h = photocraft_algo::transform::Homography::rect_to_quad([0.0, 0.0, 64.0, 32.0], [[10.0, 5.0], [80.0, 8.0], [70.0, 50.0], [12.0, 40.0]]).unwrap(); - let mut w = Vec::new(); - let mut spec = PlacedSpec { - idnt: "id", - placed: "pl", - transform: Affine::IDENTITY, - perspective: Some(h.0), - size: (64.0, 32.0), - dpi: 72.0, - warp: None, - filter_fx: None, - }; - let sold = sold_bytes(None, &spec, &mut w); - let back = crate::blocks::parse_smart_perspective(b"SoLd", &sold).expect("a projective placement"); - let n = |m: [f64; 9]| m.map(|v| v / m[8]); - for (a, b) in n(back).iter().zip(n(h.0)) { - assert!((a - b).abs() < 1e-9 * (1.0 + b.abs()), "{back:?} vs {:?}", h.0); - } - // Affine placements carry no perspective. - spec.perspective = None; - spec.transform = Affine { m: [2.0, 0.0, 0.0, 2.0, 5.0, 7.0] }; - let sold = sold_bytes(None, &spec, &mut w); - assert_eq!(crate::blocks::parse_smart_perspective(b"SoLd", &sold), None); - assert_eq!(crate::blocks::parse_smart_perspective(b"PlLd", &sold), None); - } - - /// `quad_moved` compares the corners a template stores with the placement's: unchanged keeps - /// the template's quad, a moved corner (affine or projective) or a missing quad rewrites it. - #[test] - fn quad_moved_detects_corner_changes() { - let t = Affine { m: [1.0, 0.0, 0.0, 1.0, 3.0, 4.0] }; - let mut w = Vec::new(); - let mut spec = PlacedSpec { idnt: "id", placed: "pl", transform: t, perspective: None, size: (20.0, 10.0), dpi: 72.0, warp: None, filter_fx: None }; - let template = parse_sold(&sold_bytes(None, &spec, &mut w)).expect("parses").descriptor; - assert!(!quad_moved(&template, &spec, spec.warp), "same placement"); - spec.transform = Affine { m: [1.0, 0.0, 0.0, 1.0, 3.5, 4.0] }; - assert!(quad_moved(&template, &spec, spec.warp), "moved half a pixel"); - spec.transform = t; - spec.perspective = - photocraft_algo::transform::Homography::rect_to_quad([0.0, 0.0, 20.0, 10.0], [[3.0, 4.0], [23.0, 4.0], [20.0, 12.0], [3.0, 14.0]]).map(|h| h.0); - assert!(quad_moved(&template, &spec, spec.warp), "one corner moved (Distort)"); - assert!(quad_moved(&Descriptor::new("null"), &spec, spec.warp), "no stored quad"); - } - - /// Corrupted placed-layer data and filter descriptors never panic: they parse to something - /// (unknown filters stay verbatim) or to nothing. - #[test] - fn mutated_placed_data_never_panics() { - let stack = FilterStack { - filters: vec![ - sf("filter.blur.gaussianBlur", json!({"radius": 3.0})), - sf("image.adjustments.curves", json!({"points": [[0.0, 0.0], [255.0, 255.0]]})), - sf("image.adjustments.levels", json!({"inBlack": 3, "inWhite": 250, "gamma": 1.1})), - ], - ..Default::default() - }; - let mut w = Vec::new(); - let spec = PlacedSpec { - idnt: "id", - placed: "pl", - transform: Affine::IDENTITY, - perspective: None, - size: (8.0, 8.0), - dpi: 72.0, - warp: None, - filter_fx: Some(filter_fx(&stack, "L", &mut w)), - }; - let sold = sold_bytes(None, &spec, &mut w); - let mut state = 0x2545_F491_4F6C_DD1Du64; - let mut next = || { - state ^= state << 13; - state ^= state >> 7; - state ^= state << 17; - state - }; - for _ in 0..3000 { - let mut b = sold.clone(); - for _ in 0..1 + next() % 3 { - let i = (next() as usize) % b.len(); - b[i] = next() as u8; - } - if let Some(p) = parse_sold(&b) { - for f in p.stack.iter().flat_map(|s| &s.filters) { - let _ = item_for_filter(f); - } - let _ = sold_bytes(Some(&p.descriptor), &spec, &mut w); - } - } - } - - #[test] - fn warps_are_written_and_read_back() { - use photocraft_geom::warp::BezierMesh; - let bounds = [0.0, 0.0, 60.0, 30.0]; - let mut custom = BezierMesh::identity(bounds, 1, 1); - custom.points[15] = [67.0, 30.0]; - let mut multi = Warp::preset(WarpStyle::Custom, 0.0, bounds); - let mut split = BezierMesh::identity(bounds, 2, 2); - split.points[8][1] += 4.0; - multi.mesh = Some(split); - let mut arc = Warp::preset(WarpStyle::Arc, 40.0, bounds); - arc.vertical = true; - arc.h_distort = 10.0; - let mut c = Warp::preset(WarpStyle::Custom, 0.0, bounds); - c.mesh = Some(custom); - for (w, back) in [(Some(arc.clone()), Some(arc)), (Some(c.clone()), Some(c)), (Some(multi.clone()), Some(multi)), (None, None)] { - let mut warnings = Vec::new(); - let spec = PlacedSpec { - idnt: "i", - placed: "p", - transform: Affine::IDENTITY, - perspective: None, - size: (60.0, 30.0), - dpi: 72.0, - warp: w.as_ref(), - filter_fx: None, - }; - let sold = sold_bytes(None, &spec, &mut warnings); - assert_eq!(crate::blocks::parse_placed_warp(b"SoLd", &sold), back); - assert!(warnings.is_empty(), "{warnings:?}"); - } - } - - /// A placed layer over a 50 × 25 source, at `transform`, with `warp`. - fn placed<'a>(transform: Affine, warp: Option<&'a Warp>) -> PlacedSpec<'a> { - PlacedSpec { idnt: "i", placed: "p", transform, perspective: None, size: (50.0, 25.0), dpi: 72.0, warp, filter_fx: None } - } - - /// A 3 × 2 patch split warp over the 50 × 25 source with one interior control point pulled. - fn split_warp() -> Warp { - use photocraft_geom::warp::BezierMesh; - let mut mesh = BezierMesh::identity([0.0, 0.0, 50.0, 25.0], 3, 2); - mesh.points[10 * 3 + 4][1] += 3.0; - Warp::custom(mesh, [0.0, 0.0, 50.0, 25.0]) - } - - /// An imported `soLD` descriptor holding `warp` as Photoshop writes a split warp: a - /// `quiltWarp` whose outer slices sit 0.6 px past the source, before a `warpNone` `warp`. - fn photoshop_template(warp: &Warp) -> Descriptor { - let mesh = warp.mesh.as_ref().expect("a mesh"); - let slices = |k: &str, knots: &[f64], len: f64| { - let n = knots.len() - 1; - let values = knots - .iter() - .enumerate() - .map(|(i, u)| { - if i == 0 { - -0.6 - } else if i == n { - len + 0.6 - } else { - u * len - } - }) - .collect::>(); - let prefix = values.len() as u32; - Value::ObjectArray(ObjectArray { prefix, body: Descriptor::new("UntF").with(k, Value::UnitFloats { unit: *b"#Pxl", values }) }) - }; - let Value::Descriptor(plain) = warp_desc(None, (50.0, 25.0), &mut Vec::new()) else { panic!("a descriptor") }; - let mut quilt = plain.clone(); - quilt.class_id = Id::new("quiltWarp"); - set(&mut quilt, "warpStyle", enumv("warpStyle", "warpCustom")); - let points = Descriptor::new("rationalPoint") - .with("Hrzn", Value::UnitFloats { unit: *b"#Pxl", values: mesh.points.iter().map(|p| p[0]).collect() }) - .with("Vrtc", Value::UnitFloats { unit: *b"#Pxl", values: mesh.points.iter().map(|p| p[1]).collect() }); - let envelope = Descriptor::new("customEnvelopeWarp") - .with("quiltSliceX", slices("quiltSliceX", &mesh.us, 50.0)) - .with("quiltSliceY", slices("quiltSliceY", &mesh.vs, 25.0)) - .with("meshPoints", Value::ObjectArray(ObjectArray { prefix: mesh.points.len() as u32, body: points })); - quilt = quilt - .with("deformNumRows", Value::Integer(mesh.ny() as i32)) - .with("deformNumCols", Value::Integer(mesh.nx() as i32)) - .with("customEnvelopeWarp", Value::Descriptor(envelope)); - let mut d = sold_descriptor(&sold_bytes(None, &placed(Affine::IDENTITY, None), &mut Vec::new())).expect("a descriptor"); - let at = d.items.iter().position(|(k, _)| k.is("warp")).expect("a warp key"); - d.items.insert(at, (Id::new("quiltWarp"), Value::Descriptor(quilt))); - d - } - - fn sold_of(d: Descriptor) -> Vec { - let mut out = b"soLD".to_vec(); - out.extend_from_slice(&4u32.to_be_bytes()); - out.extend(VersionedDescriptor::new(d).to_bytes()); - out - } - - fn quilt_of(d: &Descriptor) -> Option<&Descriptor> { - get_desc(d, "quiltWarp") - } - - /// A split warp of more patches along a side than a `quiltWarp` is read with (Warp Grid 64, - /// then one more split) is written as no warp, with a message, framed by the source rect, so - /// the layer reopens where it was. Before, its `quiltWarp` was refused on reopen while `Trnf` - /// still framed its control box: the layer came back stretched and shifted. - #[test] - fn a_split_warp_past_the_quilt_limit_keeps_its_placement() { - use photocraft_geom::warp::BezierMesh; - let mut mesh = BezierMesh::identity([0.0, 0.0, 50.0, 25.0], crate::blocks::QUILT_MAX_PATCHES, 1); - assert!(mesh.split_u(0.005)); - mesh.points[0] = [-10.0, -5.0]; - let warp = Warp::custom(mesh, [0.0, 0.0, 50.0, 25.0]); - let transform = Affine { m: [2.0, 0.0, 0.0, 2.0, 120.0, 210.0] }; - let mut warnings = Vec::new(); - let sold = sold_bytes(None, &placed(transform, Some(&warp)), &mut warnings); - assert_eq!(warnings.len(), 1, "{warnings:?}"); - assert_eq!(crate::blocks::parse_smart(b"SoLd", &sold).1, transform); - assert_eq!(crate::blocks::parse_placed_warp(b"SoLd", &sold), None); - assert!(quilt_of(&sold_descriptor(&sold).expect("a descriptor")).is_none()); - // Over an imported split warp, the stale `quiltWarp` goes and the placement holds. - let template = photoshop_template(&split_warp()); - let mut warnings = Vec::new(); - let sold = sold_bytes(Some(&template), &placed(transform, Some(&warp)), &mut warnings); - assert_eq!(warnings.len(), 1, "{warnings:?}"); - assert_eq!(crate::blocks::parse_smart(b"SoLd", &sold).1, transform); - assert!(quilt_of(&sold_descriptor(&sold).expect("a descriptor")).is_none()); - // So does one this reader can't read, which Photoshop would still apply. - let mut template = photoshop_template(&split_warp()); - let Some((_, Value::Descriptor(q))) = template.items.iter_mut().find(|(k, _)| k.is("quiltWarp")) else { panic!("a quiltWarp") }; - set(q, "deformNumRows", Value::Integer(0)); - let sold = sold_bytes(Some(&template), &placed(transform, Some(&warp)), &mut Vec::new()); - assert!(quilt_of(&sold_descriptor(&sold).expect("a descriptor")).is_none()); - // At the limit the split warp is still written. - let mut mesh = BezierMesh::identity([0.0, 0.0, 50.0, 25.0], crate::blocks::QUILT_MAX_PATCHES, 1); - mesh.points[0] = [-10.0, -5.0]; - let warp = Warp::custom(mesh, [0.0, 0.0, 50.0, 25.0]); - let mut warnings = Vec::new(); - let sold = sold_bytes(None, &placed(transform, Some(&warp)), &mut warnings); - assert!(warnings.is_empty(), "{warnings:?}"); - assert_eq!(crate::blocks::parse_smart(b"SoLd", &sold).1, transform); - assert_eq!(crate::blocks::parse_placed_warp(b"SoLd", &sold), Some(warp)); - } - - /// A split (multi-patch) custom warp is written as Photoshop writes it, a `quiltWarp` before a - /// `warpNone` `warp`, and reads back with its mesh and its transform. Before, the warp was - /// written as none while `Trnf` was still the image of its control-point box, so the layer - /// came back stretched and shifted. - #[test] - fn split_warp_round_trips_through_sold() { - use photocraft_geom::warp::BezierMesh; - let mut mesh = BezierMesh::identity([0.0, 0.0, 50.0, 25.0], 2, 1); - mesh.points[0] = [-10.0, -5.0]; - let warp = Warp::custom(mesh, [0.0, 0.0, 50.0, 25.0]); - let transform = Affine { m: [2.0, 0.0, 0.0, 2.0, 120.0, 210.0] }; - let mut warnings = Vec::new(); - let sold = sold_bytes(None, &placed(transform, Some(&warp)), &mut warnings); - assert!(warnings.is_empty(), "{warnings:?}"); - assert_eq!(crate::blocks::parse_smart(b"SoLd", &sold).1, transform); - assert_eq!(crate::blocks::parse_placed_warp(b"SoLd", &sold), Some(warp)); - let d = sold_descriptor(&sold).expect("a descriptor"); - let at = |key: &str| d.items.iter().position(|(k, _)| k.is(key)); - assert!(at("quiltWarp").expect("a quiltWarp") < at("warp").expect("a warp")); - let plain = get_desc(&d, "warp").expect("a warp"); - assert_eq!(enum_of(plain, "warpStyle"), Some(&b"warpNone"[..])); - assert!(plain.get("customEnvelopeWarp").is_none()); - let quilt = quilt_of(&d).expect("a quiltWarp"); - assert!(quilt.class_id.is("quiltWarp")); - assert_eq!((quilt.get("deformNumCols"), quilt.get("deformNumRows")), (Some(&Value::Integer(7)), Some(&Value::Integer(4)))); - let env = get_desc(quilt, "customEnvelopeWarp").expect("an envelope"); - let prefix = |k: &str| match env.get(k) { - Some(Value::ObjectArray(a)) => Some(a.prefix), - _ => None, - }; - assert_eq!((prefix("quiltSliceX"), prefix("quiltSliceY"), prefix("meshPoints")), (Some(3), Some(2), Some(28))); - } - - /// A template's split warp is replaced along with its `warp`: a warp changed to Arc, to none, - /// to one patch or to another mesh reads back as changed, not as the imported split warp. - #[test] - fn a_replaced_split_warp_does_not_come_back() { - use photocraft_geom::warp::BezierMesh; - let bounds = [0.0, 0.0, 50.0, 25.0]; - let split = split_warp(); - let template = photoshop_template(&split); - let arc = Warp::preset(WarpStyle::Arc, 30.0, bounds); - let mut one = BezierMesh::identity(bounds, 1, 1); - one.points[5][0] += 2.0; - let one = Warp::custom(one, bounds); - let mut resplit = BezierMesh::identity(bounds, 2, 2); - resplit.points[8][1] += 4.0; - let resplit = Warp::custom(resplit, bounds); - for w in [Some(arc), None, Some(one), Some(resplit)] { - let mut warnings = Vec::new(); - let sold = sold_bytes(Some(&template), &placed(Affine::IDENTITY, w.as_ref()), &mut warnings); - assert_eq!(crate::blocks::parse_placed_warp(b"SoLd", &sold), w); - let d = sold_descriptor(&sold).expect("a descriptor"); - assert_eq!(quilt_of(&d).is_some(), w.as_ref().is_some_and(|w| w.mesh.as_ref().is_some_and(|m| m.points.len() > 16)), "{w:?}"); - assert!(warnings.is_empty(), "{warnings:?}"); - } - } - - /// An imported split warp that nothing changed keeps Photoshop's `quiltWarp` as stored when - /// the layer is rewritten for something else (here a move); a mesh edited on the same grid - /// keeps Photoshop's slices. - #[test] - fn an_imported_split_warp_keeps_photoshop_s_quilt() { - let template = photoshop_template(&split_warp()); - let read = crate::blocks::parse_placed_warp(b"SoLd", &sold_of(template.clone())).expect("the split warp"); - let moved = Affine { m: [1.0, 0.0, 0.0, 1.0, 4.0, 0.0] }; - let sold = sold_bytes(Some(&template), &placed(moved, Some(&read)), &mut Vec::new()); - let d = sold_descriptor(&sold).expect("a descriptor"); - assert_eq!(d.get("quiltWarp"), template.get("quiltWarp")); - assert_eq!(crate::blocks::parse_smart(b"SoLd", &sold).1, moved); - let mut edited = read.clone(); - if let Some(m) = edited.mesh.as_mut() { - m.points[12][0] += 1.5; - } - let sold = sold_bytes(Some(&template), &placed(Affine::IDENTITY, Some(&edited)), &mut Vec::new()); - assert_eq!(crate::blocks::parse_placed_warp(b"SoLd", &sold), Some(edited)); - let slices = |d: &Descriptor| { - let env = get_desc(quilt_of(d)?, "customEnvelopeWarp")?; - Some((env.get("quiltSliceX").cloned(), env.get("quiltSliceY").cloned())) - }; - assert_eq!(slices(&sold_descriptor(&sold).expect("a descriptor")), slices(&template)); - } - - /// The legacy `PlLd` record has no split warp: it stores none, with its corners framed by the - /// source rect, so a reader of `PlLd` alone places the layer where its transform puts it. - #[test] - fn plld_of_a_split_warp_is_framed_by_the_source() { - let warp = split_warp(); - let transform = Affine { m: [2.0, 0.0, 0.0, 2.0, 120.0, 210.0] }; - let mut warnings = Vec::new(); - let plld = plld_bytes(&placed(transform, Some(&warp)), &mut warnings); - assert!(warnings.is_empty(), "{warnings:?}"); - assert_eq!(crate::blocks::parse_plld_warp(&plld), crate::blocks::PlldWarp::None); - let (_, corners) = crate::blocks::parse_plld(&plld).expect("a record"); - assert_eq!(crate::blocks::plld_transform(&corners, Some((50.0, 25.0)), None).0, transform); - } - - /// Export writes `Trnf` as the image of the custom warp's control-point box, the inverse of - /// import: a spilled mesh comes back with the same transform and the quad Photoshop expects. - #[test] - fn warp_control_box_quad_round_trips() { - use photocraft_geom::warp::BezierMesh; - let mut mesh = BezierMesh::identity([0.0, 0.0, 50.0, 25.0], 1, 1); - mesh.points[0] = [-10.0, -5.0]; - mesh.points[15] = [60.0, 25.0]; - let mut warp = Warp::preset(WarpStyle::Custom, 0.0, [0.0, 0.0, 50.0, 25.0]); - warp.mesh = Some(mesh); - let transform = Affine { m: [2.0, 0.0, 0.0, 2.0, 120.0, 210.0] }; - let spec = PlacedSpec { idnt: "i", placed: "p", transform, perspective: None, size: (50.0, 25.0), dpi: 72.0, warp: Some(&warp), filter_fx: None }; - let sold = sold_bytes(None, &spec, &mut Vec::new()); - let p = parse_sold(&sold).expect("parses"); - let Some(Value::List(q)) = p.descriptor.get("Trnf") else { panic!("no Trnf") }; - let q: Vec = q.iter().filter_map(|v| num(Some(v))).collect(); - assert_eq!(q, [100.0, 200.0, 240.0, 200.0, 240.0, 260.0, 100.0, 260.0]); - assert_eq!(p.transform, transform); - // The imported quad reads as unmoved, so the template's `Trnf` is kept as stored. - assert!(!quad_moved(&p.descriptor, &spec, spec.warp)); - } - - /// #4112: a regenerated `SoLd` (after Replace Contents, a move…) writes a cylinder back as - /// `warpCylinder` and its seven values, not as no warp, and frames its control-point box with - /// the quad, affine or projective, so import places it where it was. - #[test] - fn cylinder_warp_round_trips_through_sold() { - let v = [100.0, 800.0, 900.0, 200.0, 0.3, 0.3, 0.5]; - let warp = Warp::cylinder(&v, [0.0, 0.0, 1000.0, 1000.0]).unwrap(); - let transform = Affine { m: [0.5, 0.0, 0.0, 0.5, 40.0, 30.0] }; - let mut spec = - PlacedSpec { idnt: "i", placed: "p", transform, perspective: None, size: (1000.0, 1000.0), dpi: 72.0, warp: Some(&warp), filter_fx: None }; - let mut warnings = Vec::new(); - let sold = sold_bytes(None, &spec, &mut warnings); - assert!(warnings.is_empty(), "{warnings:?}"); - let p = parse_sold(&sold).expect("parses"); - let Some(Value::Descriptor(w)) = p.descriptor.get("warp") else { panic!("no warp") }; - assert_eq!(crate::blocks::enum_of(w, "warpStyle"), Some(b"warpCylinder".as_slice())); - let Some(Value::List(values)) = w.get("warpValues") else { panic!("no warpValues") }; - assert_eq!(values.iter().filter_map(|x| num(Some(x))).collect::>(), v); - assert!(w.get("customEnvelopeWarp").is_none()); - assert_eq!(crate::blocks::parse_placed_warp(b"SoLd", &sold), Some(warp.clone())); - for (a, b) in p.transform.m.iter().zip(transform.m) { - assert!((a - b).abs() < 1e-9, "{:?}", p.transform); - } - // The quad is the image of the control-point box, not of the source rect. - let cb = warp.mesh.as_ref().unwrap().control_bounds(); - let Some(Value::List(q)) = p.descriptor.get("Trnf") else { panic!("no Trnf") }; - let q: Vec = q.iter().filter_map(|x| num(Some(x))).collect(); - let want = [cb[0], cb[1], cb[2], cb[1], cb[2], cb[3], cb[0], cb[3]].map(|c| 0.5 * c); - for (i, (a, b)) in q.iter().zip(want).enumerate() { - let shift = if i % 2 == 0 { 40.0 } else { 30.0 }; - assert!((a - (b + shift)).abs() < 1e-9, "corner {i}: {q:?}"); - } - assert!(!quad_moved(&p.descriptor, &spec, spec.warp)); - // A projective placement comes back as the same map. - let h = photocraft_algo::transform::Homography::rect_to_quad(cb, [[10.0, 20.0], [410.0, 60.0], [400.0, 480.0], [30.0, 520.0]]).unwrap(); - spec.perspective = Some(h.0); - let sold = sold_bytes(None, &spec, &mut warnings); - let back = crate::blocks::parse_smart_perspective(b"SoLd", &sold).expect("projective"); - let n = |m: [f64; 9]| m.map(|x| x / m[8]); - for (a, b) in n(back).iter().zip(n(h.0)) { - assert!((a - b).abs() < 1e-9 * (1.0 + b.abs()), "{back:?} vs {:?}", h.0); - } - let plld = plld_bytes(&spec, &mut warnings); - assert_eq!(crate::blocks::parse_plld_warp(&plld), crate::blocks::PlldWarp::Warp(warp)); - assert!(warnings.is_empty(), "{warnings:?}"); - } - - #[test] - fn hex_and_uuid() { - assert_eq!(from_hex(&to_hex(&[0, 1, 0xab, 0xff])), Some(vec![0, 1, 0xab, 0xff])); - assert_eq!(from_hex("abc"), None); - assert_eq!(from_hex("zz"), None); - let u = uuid_from(b"x"); - assert_eq!(u.len(), 36); - assert_eq!(u, uuid_from(b"x")); - assert_ne!(u, uuid_from(b"y")); - } - - // Render filters as Photoshop 27 saves them on a smart object (`filterFXList` items, with - // neutral blending): Clouds and Difference Clouds in white on black, Fibers in black on white, - // Lens Flare with the 50-300mm Zoom at 159%. - const PHOTOSHOP_CLOUDS: &str = "0000000100000000000866696c746572465800000008000000004e6d202054455854000000070043006c006f00750064007300000000000c626c656e644f7074696f6e734f626a63000000000000000c626c656e644f7074696f6e7300000002000000004f706374556e7446235072634059000000000000000000004d642020656e756d00000000426c6e4d000000066e6f726d616c00000000656e6162626f6f6c010000000a6861736f7074696f6e73626f6f6c0100000000467267434f626a630000000100000000000052474243000000030000000052642020646f7562406fe000000000000000000047726e20646f7562406fe0000000000000000000426c2020646f7562406fe000000000000000000042636b434f626a630000000100000000000052474243000000030000000052642020646f756200000000000000000000000047726e20646f7562000000000000000000000000426c2020646f7562000000000000000000000000466c74724f626a63000000070043006c006f007500640073000000000000436c64730000000100000000466c52736c6f6e67000049e40000000866696c74657249446c6f6e67436c6473"; - const PHOTOSHOP_DIFFERENCE_CLOUDS: &str = "0000000100000000000866696c746572465800000008000000004e6d202054455854000000120044006900660066006500720065006e0063006500200043006c006f00750064007300000000000c626c656e644f7074696f6e734f626a63000000000000000c626c656e644f7074696f6e7300000002000000004f706374556e7446235072634059000000000000000000004d642020656e756d00000000426c6e4d000000066e6f726d616c00000000656e6162626f6f6c010000000a6861736f7074696f6e73626f6f6c0100000000467267434f626a630000000100000000000052474243000000030000000052642020646f7562406fe000000000000000000047726e20646f7562406fe0000000000000000000426c2020646f7562406fe000000000000000000042636b434f626a630000000100000000000052474243000000030000000052642020646f756200000000000000000000000047726e20646f7562000000000000000000000000426c2020646f7562000000000000000000000000466c74724f626a63000000120044006900660066006500720065006e0063006500200043006c006f007500640073000000000000446672430000000100000000466c52736c6f6e67000057d20000000866696c74657249446c6f6e6744667243"; - const PHOTOSHOP_FIBERS: &str = "0000000100000000000866696c746572465800000008000000004e6d2020544558540000000a004600690062006500720073002e002e002e00000000000c626c656e644f7074696f6e734f626a63000000000000000c626c656e644f7074696f6e7300000002000000004f706374556e7446235072634059000000000000000000004d642020656e756d00000000426c6e4d000000066e6f726d616c00000000656e6162626f6f6c010000000a6861736f7074696f6e73626f6f6c0100000000467267434f626a630000000100000000000052474243000000030000000052642020646f756200000000000000000000000047726e20646f7562000000000000000000000000426c2020646f756200000000000000000000000042636b434f626a630000000100000000000052474243000000030000000052642020646f7562406fe000000000000000000047726e20646f7562406fe0000000000000000000426c2020646f7562406fe0000000000000000000466c74724f626a630000000700460069006200650072007300000000000046627273000000030000000056726e636c6f6e670000001000000000537472676c6f6e670000000400000000526e64536c6f6e67000062f10000000866696c74657249446c6f6e6746627273"; - const PHOTOSHOP_LENS_FLARE: &str = "0000000100000000000866696c746572465800000008000000004e6d2020544558540000000e004c0065006e007300200046006c006100720065002e002e002e00000000000c626c656e644f7074696f6e734f626a63000000000000000c626c656e644f7074696f6e7300000002000000004f706374556e7446235072634059000000000000000000004d642020656e756d00000000426c6e4d000000066e6f726d616c00000000656e6162626f6f6c010000000a6861736f7074696f6e73626f6f6c0100000000467267434f626a630000000100000000000052474243000000030000000052642020646f756200000000000000000000000047726e20646f7562000000000000000000000000426c2020646f756200000000000000000000000042636b434f626a630000000100000000000052474243000000030000000052642020646f7562406fe000000000000000000047726e20646f7562406fe0000000000000000000426c2020646f7562406fe0000000000000000000466c74724f626a630000000b004c0065006e007300200046006c0061007200650000000000004c6e73460000000300000000427267686c6f6e670000009f00000000466c72434f626a6300000001000000000000506e7420000000020000000048727a6e646f75623fe86666600000000000000056727463646f75623fe60b60c0000000000000004c6e7320656e756d000000004c6e7320000000005a6d20200000000866696c74657249446c6f6e674c6e7346"; - - fn photoshop(hex: &str) -> Descriptor { - Descriptor::from_bytes(&from_hex(hex).unwrap()).unwrap() - } - - fn set_lens(item: &mut Descriptor, code: [u8; 4]) { - let Some(Value::Descriptor(fltr)) = item.items.iter_mut().find(|(k, _)| k.is("Fltr")).map(|(_, v)| v) else { panic!("no Fltr") }; - set(fltr, "Lns ", Value::Enumerated { type_id: Id::new("Lns "), value: Id::Code(code) }); - } - - #[test] - fn photoshop_render_filters_read_and_write_like_photoshop() { - let colours = |fg: f64, bg: f64| (json!([fg, fg, fg, 1.0]), json!([bg, bg, bg, 1.0])); - let (white, black) = colours(1.0, 0.0); - let cases = [ - (PHOTOSHOP_CLOUDS, "filter.render.clouds", json!({"seed": 18916, "foreground": white, "background": black})), - (PHOTOSHOP_DIFFERENCE_CLOUDS, "filter.render.differenceClouds", json!({"seed": 22482, "foreground": white, "background": black})), - (PHOTOSHOP_FIBERS, "filter.render.fibers", json!({"variance": 16, "strength": 4, "seed": 25329, "foreground": black, "background": white})), - ( - PHOTOSHOP_LENS_FLARE, - "filter.render.lensFlare", - json!({"brightness": 159, "centerX": 0.762499988079071, "centerY": 0.6888889074325562, "lens": "zoom"}), - ), - ]; - for (hex, command, params) in cases { - let item = photoshop(hex); - let f = filter_from_item(&item); - assert_eq!((f.command.as_str(), &f.params), (command, ¶ms)); - // Written back, it is Photoshop's item again: name, colours, settings and key order. - assert_eq!(item_for_filter(&f).unwrap().items, item.items, "{command}"); - } - } - - #[test] - fn every_lens_flare_lens_round_trips_with_photoshops_code() { - for (code, lens) in LENSES { - let mut item = photoshop(PHOTOSHOP_LENS_FLARE); - set_lens(&mut item, *code); - let f = filter_from_item(&item); - assert_eq!(f.params["lens"], lens); - assert_eq!(item_for_filter(&f).unwrap().items, item.items, "{lens}"); - } - // A lens we don't know keeps the filter verbatim. - let mut item = photoshop(PHOTOSHOP_LENS_FLARE); - set_lens(&mut item, *b"Xxxx"); - assert_eq!(filter_from_item(&item).command, UNSUPPORTED_FILTER); - } - - /// The descriptor at `path` (nested keys) inside `item`, for editing. - fn desc_at<'a>(item: &'a mut Descriptor, path: &[&str]) -> &'a mut Descriptor { - path.iter().fold(item, |d, key| { - let Some(Value::Descriptor(x)) = d.items.iter_mut().find(|(k, _)| k.is(key)).map(|(_, v)| v) else { panic!("no {key}") }; - x - }) - } - - #[test] - fn render_filters_with_settings_we_dont_model_stay_verbatim() { - // Each case changes one thing in a Photoshop item: an extra setting, a repeated one, or a - // value of another type than Photoshop writes. Opened as editable, a re-save would drop the - // extra setting or rewrite the value; kept verbatim, the item is written back byte for byte. - type Edit = Box; - /// A descriptor path in the item (nested keys) and the edit made there. - type Change = (&'static [&'static str], Edit); - let extra: fn(&mut Descriptor) = |d| d.items.push((Id::new("Xtra"), Value::Integer(1))); - let as_double = |key: &'static str| -> Edit { Box::new(move |d| set(d, key, Value::Double(1.0))) }; - let as_long = |key: &'static str| -> Edit { Box::new(move |d| set(d, key, Value::Integer(1))) }; - let repeat = |key: &'static str| -> Edit { - Box::new(move |d| { - let v = d.get(key).cloned().unwrap(); - d.items.push((Id::new(key), v)); - }) - }; - let colour_edits = || -> Vec { - vec![ - (&["FrgC"], Box::new(|d: &mut Descriptor| d.items.push((Id::new("redFloat"), Value::Double(0.5))))), - (&["BckC"], as_long("Grn ")), - (&["FrgC"], Box::new(|d: &mut Descriptor| set(d, "Rd ", Value::Double(300.0)))), - (&["BckC"], Box::new(|d: &mut Descriptor| d.class_id = Id::new("HSBC"))), - ] - }; - let mut cases: Vec<(&str, &'static [&'static str], Edit)> = Vec::new(); - for hex in [PHOTOSHOP_CLOUDS, PHOTOSHOP_DIFFERENCE_CLOUDS] { - cases.push((hex, &["Fltr"], Box::new(extra))); - cases.push((hex, &["Fltr"], repeat("FlRs"))); - cases.push((hex, &["Fltr"], as_double("FlRs"))); - cases.extend(colour_edits().into_iter().map(|(p, e)| (hex, p, e))); - } - cases.push((PHOTOSHOP_FIBERS, &["Fltr"], Box::new(extra))); - cases.push((PHOTOSHOP_FIBERS, &["Fltr"], repeat("Strg"))); - for key in ["Vrnc", "Strg", "RndS"] { - cases.push((PHOTOSHOP_FIBERS, &["Fltr"], as_double(key))); - } - cases.extend(colour_edits().into_iter().map(|(p, e)| (PHOTOSHOP_FIBERS, p, e))); - cases.push((PHOTOSHOP_LENS_FLARE, &["Fltr"], Box::new(extra))); - cases.push((PHOTOSHOP_LENS_FLARE, &["Fltr"], repeat("Brgh"))); - cases.push((PHOTOSHOP_LENS_FLARE, &["Fltr"], as_double("Brgh"))); - cases.push((PHOTOSHOP_LENS_FLARE, &["Fltr"], Box::new(|d| set(d, "Lns ", Value::Enumerated { type_id: Id::new("Xxxx"), value: Id::Code(*b"Zm ") })))); - cases.push((PHOTOSHOP_LENS_FLARE, &["Fltr", "FlrC"], Box::new(extra))); - cases.push((PHOTOSHOP_LENS_FLARE, &["Fltr", "FlrC"], as_long("Hrzn"))); - cases.push((PHOTOSHOP_LENS_FLARE, &["Fltr", "FlrC"], Box::new(|d| set(d, "Vrtc", Value::UnitFloat { unit: *b"#Pxl", value: 0.5 })))); - for (i, (hex, path, edit)) in cases.iter().enumerate() { - let mut item = photoshop(hex); - edit(desc_at(&mut item, path)); - let f = filter_from_item(&item); - assert_eq!(f.command, UNSUPPORTED_FILTER, "case {i} ({path:?}): {:?}", f.params); - assert_eq!(item_for_filter(&f).unwrap().to_bytes(), item.to_bytes(), "case {i} ({path:?})"); - } - } - - #[test] - fn render_filters_made_in_photocraft_are_written() { - // Without colours (an older document or a script), Photoshop's default black and white. - let back = filter_from_item(&item_for_filter(&sf("filter.render.clouds", json!({"seed": 7}))).unwrap()); - assert_eq!(back.params, json!({"seed": 7, "foreground": [0.0, 0.0, 0.0, 1.0], "background": [1.0, 1.0, 1.0, 1.0]})); - // A seed above i32::MAX keeps its bit pattern, and colours may be hex. - let p = json!({"variance": 30, "strength": 10, "seed": 4_000_000_000u32, "foreground": "#ff0000", "background": [0.0, 0.0, 1.0, 1.0]}); - let back = filter_from_item(&item_for_filter(&sf("filter.render.fibers", p)).unwrap()); - assert_eq!( - back.params, - json!({"variance": 30, "strength": 10, "seed": 4_000_000_000u32, "foreground": [1.0, 0.0, 0.0, 1.0], "background": [0.0, 0.0, 1.0, 1.0]}) - ); - let flare = sf("filter.render.lensFlare", json!({"brightness": 120, "centerX": 0.25, "centerY": 0.75, "lens": "moviePrime"})); - assert_eq!(filter_from_item(&item_for_filter(&flare).unwrap()).params, flare.params); - // Lenses and colours we can't write are reported, not guessed. - assert!(item_for_filter(&sf("filter.render.lensFlare", json!({"lens": "fisheye"}))).unwrap_err().contains("fisheye")); - assert!(item_for_filter(&sf("filter.render.clouds", json!({"foreground": "red"}))).is_err()); - } -} +mod tests; diff --git a/crates/io/src/smart_map/export.rs b/crates/io/src/smart_map/export.rs new file mode 100644 index 0000000000..c8159201e4 --- /dev/null +++ b/crates/io/src/smart_map/export.rs @@ -0,0 +1,387 @@ +use super::import::{ + CHANNELS, CUSTOM_CELL, CUSTOM_OFFSET, CUSTOM_SCALE, DIFFUSE_MODES, EXTRUDE_DEPTH, EXTRUDE_DEPTHS, EXTRUDE_SIZE, EXTRUDE_TYPES, GALLERY_COMMAND, Known, + LENSES, MEZZOTINT_TYPES, NO_OPTIONS, OFFSET_FILL, POLAR_MODE, RADIAL_METHOD, RADIAL_QUALITY, RIPPLE_SIZE, SMART_BLUR_MODE, SMART_BLUR_QUALITY, + SMART_SHARPEN, SPHERIZE_MODE, TILE_COUNT, TILE_FILLS, TILE_OFFSET, TRACE_EDGES, UNDEFINED_AREAS, WAVE_TYPE, WIND_DIRECTIONS, WIND_METHODS, ZIGZAG_STYLE, + colour_rgbc, enum_param, from_hex, gallery_item, known_by_command, pf_range, pi_range, seed_param, +}; +use super::placed::enumv; +use super::*; + +// ---------- writing ---------- + +pub(crate) fn unit(u: &[u8; 4], v: f64) -> Value { + Value::UnitFloat { unit: *u, value: v } +} + +pub(crate) fn rgbc(v: f64) -> Value { + Value::Descriptor(Descriptor::new("RGBC").with("Rd ", Value::Double(v)).with("Grn ", Value::Double(v)).with("Bl ", Value::Double(v))) +} + +pub(crate) fn blend_options(f: &SmartFilter) -> Value { + let opacity = if f.opacity.is_finite() { f64::from(f.opacity.clamp(0.0, 1.0)) * 100.0 } else { 100.0 }; + Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", opacity)).with("Md ", crate::effects_map::blend_long_value(f.blend))) +} + +/// Parameter keys that are bookkeeping, not filter settings. +pub(crate) fn is_meta(k: &str) -> bool { + k == "layer" || k.starts_with("__") +} + +fn pf(p: &J, key: &str, default: f64) -> f64 { + p.get(key).and_then(J::as_f64).filter(|v| v.is_finite()).unwrap_or(default) +} + +pub(super) fn pi(p: &J, key: &str, default: f64) -> Value { + Value::Integer(pf(p, key, default).round().clamp(f64::from(i32::MIN), f64::from(i32::MAX)) as i32) +} + +/// A whole-number setting as a long, clamped to `range` like the engine clamps it; a fraction +/// has no PSD equivalent (Photoshop stores these as integers). +fn whole(v: f64, (lo, hi): (i32, i32), what: &str) -> Result { + if v.fract() != 0.0 { + return Err(format!("{what} ({v}) is not a whole number")); + } + Ok(Value::Integer(v.clamp(f64::from(lo), f64::from(hi)) as i32)) +} + +fn channel_ref(code: &[u8; 4]) -> Value { + Value::Reference(vec![ReferenceItem::Enumerated { + class: Class { name: UnicodeString::new_nul(""), class_id: Id::new("Chnl") }, + type_id: Id::new("Chnl"), + value: Id::Code(*code), + }]) +} + +/// The `Adjs` entries of a Levels or Curves filter: the composite first, then red, green, blue. +fn adjustments(p: &J, curves: bool) -> Result { + let obj = p.as_object().ok_or("parameters are not an object")?; + let allowed: &[&str] = + if curves { &["points", "red", "green", "blue", "pencil"] } else { &["inBlack", "inWhite", "gamma", "outBlack", "outWhite", "red", "green", "blue"] }; + if let Some(k) = obj.keys().find(|k| !is_meta(k) && !allowed.contains(&k.as_str())) { + return Err(format!("setting `{k}` has no PSD equivalent")); + } + let mut list = Vec::new(); + for (code, key) in CHANNELS { + let o = if key.is_empty() { Some(p) } else { p.get(key) }; + let Some(o) = o else { continue }; + let mut a = Descriptor::new(if curves { "CrvA" } else { "LvlA" }).with("Chnl", channel_ref(code)); + if curves { + let src = if key.is_empty() { p.get("points") } else { Some(o) }; + let Some(pts) = src.and_then(J::as_array) else { continue }; + if p.get("pencil").and_then(J::as_bool) == Some(true) { + let map: Option> = + pts.iter().map(|o| o.as_f64().filter(|o| o.is_finite()).map(|o| Value::Integer(o.round().clamp(0.0, 255.0) as i32))).collect(); + a = a.with("Mpng", Value::List(map.filter(|m| m.len() == 256).ok_or("a pencil-drawn curve is not 256 output levels")?)); + list.push(Value::Descriptor(a)); + continue; + } + let pts: Option> = pts + .iter() + .map(|q| { + let x = q.get(0)?.as_f64().filter(|v| v.is_finite())?; + let y = q.get(1)?.as_f64().filter(|v| v.is_finite())?; + Some(Value::Descriptor(Descriptor::new("Pnt ").with("Hrzn", Value::Double(x)).with("Vrtc", Value::Double(y)))) + }) + .collect(); + a = a.with("Crv ", Value::List(pts.ok_or("a curve point is not [input, output]")?)); + } else { + if key.is_empty() && !["inBlack", "inWhite", "gamma", "outBlack", "outWhite"].iter().any(|k| o.get(k).is_some()) { + continue; + } + a = a.with("Inpt", Value::List(vec![pi(o, "inBlack", 0.0), pi(o, "inWhite", 255.0)])).with("Gmm ", Value::Double(pf(o, "gamma", 1.0))); + if o.get("outBlack").is_some() || o.get("outWhite").is_some() { + a = a.with("Otpt", Value::List(vec![pi(o, "outBlack", 0.0), pi(o, "outWhite", 255.0)])); + } + } + list.push(Value::Descriptor(a)); + } + Ok(Value::List(list)) +} + +/// Crystallize's and Pointillize's cell size range (`ClSz`, a `long`). +pub(super) const CELL_SIZE: (i32, i32) = (3, 300); + +/// Our `key` (a string) as Photoshop's enum value through `table` (Photoshop's value, ours). +fn enum_out(p: &J, key: &str, default: &str, type_id: &str, table: &[(&str, &str)]) -> Result { + let ours = match p.get(key) { + None => default, + Some(v) => v.as_str().ok_or_else(|| format!("`{key}` is not a string"))?, + }; + let (psd, _) = table.iter().find(|(_, o)| *o == ours).ok_or_else(|| format!("{key} `{ours}` has no PSD equivalent"))?; + Ok(enumv(type_id, psd)) +} + +/// `key` rounded to a `long` in `lo..=hi`. +fn pi_in(p: &J, key: &str, default: f64, lo: i32, hi: i32) -> Value { + Value::Integer(pf(p, key, default).round().clamp(f64::from(lo), f64::from(hi)) as i32) +} + +/// Param `key` as a `bool` (false when absent or not a bool, as the engine reads it). +fn bool_param(p: &J, key: &str) -> Value { + Value::Boolean(p.get(key).and_then(J::as_bool).unwrap_or(false)) +} + +/// The `Fltr` descriptor of a modelled filter (`None` = written without options). +fn fltr_for(k: &Known, p: &J) -> Result, String> { + let d = Descriptor::new(k.class); + Ok(Some(match k.class { + "GsnB" | "boxblur" | "Mdn " | "HghP" | "Mxm " | "Mnm " => { + if p.get("preserve").and_then(J::as_str).is_some_and(|s| s == "roundness") { + return Err("“preserve roundness” has no PSD equivalent".into()); + } + d.with("Rds ", unit(b"#Pxl", pf(p, "radius", 1.0))) + } + "MtnB" => d.with("Angl", pi(p, "angle", 0.0)).with("Dstn", unit(b"#Pxl", pf(p, "distance", 10.0))), + "UnsM" => d.with("Amnt", unit(b"#Prc", pf(p, "amount", 50.0))).with("Rds ", unit(b"#Pxl", pf(p, "radius", 1.0))).with("Thsh", pi(p, "threshold", 0.0)), + "AdNs" => { + let gauss = p.get("distribution").and_then(J::as_str) == Some("gaussian"); + d.with("Dstr", Value::Enumerated { type_id: Id::new("Dstr"), value: Id::new(if gauss { "Gsn " } else { "Unfr" }) }) + .with("Nose", unit(b"#Prc", pf(p, "amount", 12.5))) + .with("Mnch", Value::Boolean(p.get("monochromatic").and_then(J::as_bool).unwrap_or(false))) + .with("FlRs", pi(p, "seed", 0.0)) + } + "surfaceBlur" => d.with("Rds ", unit(b"#Pxl", pf_range(p, "radius", 5.0, 1.0, 100.0)?)).with("Thsh", pi_range(p, "threshold", 15.0, 2, 255)?), + "SmrB" => d + .with("Rds ", Value::Double(pf_range(p, "radius", 3.0, 0.1, 100.0)?)) + .with("Thsh", Value::Double(pf_range(p, "threshold", 25.0, 0.1, 100.0)?)) + .with("SmBQ", enum_param(p, "quality", "high", "SmBQ", &SMART_BLUR_QUALITY)?) + .with("SmBM", enum_param(p, "mode", "normal", "SmBM", &SMART_BLUR_MODE)?), + "RdlB" => { + // Photoshop wrote no centre key for a centred blur; an off-centre one is unmeasured. + for k in ["centerX", "centerY"] { + if (pf_range(p, k, 0.5, 0.0, 1.0)? - 0.5).abs() > 1e-9 { + return Err("an off-centre Radial Blur centre is not written to PSD".into()); + } + } + d.with("Amnt", pi_range(p, "amount", 10.0, 1, 100)?) + .with("BlrM", enum_param(p, "method", "spin", "BlrM", &RADIAL_METHOD)?) + .with("BlrQ", enum_param(p, "quality", "good", "BlrQ", &RADIAL_QUALITY)?) + } + "Msc " => d.with("ClSz", unit(b"#Pxl", pf(p, "cellSize", 10.0))), + // Photoshop's Mezzotint has no seed (it is random on every render), so `seed` is not saved. + "Mztn" => { + let t = p.get("type").and_then(J::as_str).unwrap_or("fineDots"); + let code = MEZZOTINT_TYPES.iter().find(|(_, k)| *k == t).map_or(b"FnDt", |(c, _)| *c); + d.with("MztT", Value::Enumerated { type_id: Id::new("MztT"), value: Id::Code(*code) }) + } + "ClrH" => { + // Longs within the dialog's ranges (what the engine accepts: radius 4..127, angles ±360). + let long = |key: &str, default: f64, lo: f64, hi: f64| Value::Integer(pf(p, key, default).round().clamp(lo, hi) as i32); + d.with("Rds ", long("maxRadius", 8.0, 4.0, 127.0)) + .with("Ang1", long("channel1", 108.0, -360.0, 360.0)) + .with("Ang2", long("channel2", 162.0, -360.0, 360.0)) + .with("Ang3", long("channel3", 90.0, -360.0, 360.0)) + .with("Ang4", long("channel4", 45.0, -360.0, 360.0)) + } + "Embs" => d.with("Angl", pi(p, "angle", 135.0)).with("Hght", pi(p, "height", 3.0)).with("Amnt", pi(p, "amount", 100.0)), + SMART_SHARPEN => { + // The engine's defaults and ranges (it clamps the same way when rendering). + d.with("useLegacy", Value::Boolean(false)) + .with("Amnt", unit(b"#Prc", pf(p, "amount", 100.0).clamp(1.0, 500.0))) + .with("Rds ", unit(b"#Pxl", pf(p, "radius", 1.0).clamp(0.1, 64.0))) + .with("noiseReduction", unit(b"#Prc", pf(p, "reduceNoise", 10.0).clamp(0.0, 100.0))) + .with("blur", enumv("blurType", "GsnB")) + } + // Photoshop stores whole pixels and levels. + "DstS" => { + let whole = |key: &str, default: f64, lo: f64, hi: f64| Value::Integer(pf(p, key, default).round().clamp(lo, hi) as i32); + d.with("Rds ", whole("radius", 1.0, 1.0, 500.0)).with("Thsh", whole("threshold", 0.0, 0.0, 255.0)) + } + // Photoshop stores no random seed for these: `seed` is ours only and is not written. + "Dfs " => d.with("Md ", enum_out(p, "mode", "normal", "DfsM", &DIFFUSE_MODES)?), + "TrcC" => d.with("Lvl ", pi_in(p, "level", 128.0, 0, 255)).with("Edg ", enum_out(p, "edge", "lower", "CntE", &TRACE_EDGES)?), + "Crst" => d.with("ClSz", pi_in(p, "cellSize", 10.0, CELL_SIZE.0, CELL_SIZE.1)), + "Pntl" => d.with("ClSz", pi_in(p, "cellSize", 5.0, CELL_SIZE.0, CELL_SIZE.1)), + // Photoshop stores no random seed for these: our `seed` is not written. + "Wnd " => { + d.with("WndM", enum_out(p, "method", "wind", "WndM", &WIND_METHODS)?).with("Drct", enum_out(p, "direction", "fromRight", "Drct", &WIND_DIRECTIONS)?) + } + "Extr" => d + .with("ExtT", enum_out(p, "type", "blocks", "ExtT", &EXTRUDE_TYPES)?) + .with("ExtS", pi_in(p, "size", 30.0, EXTRUDE_SIZE.0, EXTRUDE_SIZE.1)) + .with("ExtD", pi_in(p, "depth", 30.0, EXTRUDE_DEPTH.0, EXTRUDE_DEPTH.1)) + .with("ExtR", enum_out(p, "depthMode", "random", "ExtR", &EXTRUDE_DEPTHS)?) + .with("ExtF", bool_param(p, "solidFrontFaces")) + .with("ExtM", bool_param(p, "maskIncompleteBlocks")), + "Tls " => d + .with("TlNm", pi_in(p, "count", 10.0, TILE_COUNT.0, TILE_COUNT.1)) + .with("TlOf", pi_in(p, "maxOffset", 10.0, TILE_OFFSET.0, TILE_OFFSET.1)) + .with("FlCl", enum_out(p, "fill", "background", "FlCl", &TILE_FILLS)?), + "Ofst" => { + // As the engine reads it: anything but repeat / transparent wraps. + let ours = p.get("undefinedAreas").and_then(J::as_str).unwrap_or("wrap"); + let fill = OFFSET_FILL.iter().find(|(_, o)| *o == ours).map_or("Wrp ", |(psd, _)| *psd); + d.with("Hrzn", pi(p, "horizontal", 0.0)).with("Vrtc", pi(p, "vertical", 0.0)).with("Fl ", enumv("FlMd", fill)) + } + "Cstm" => { + // The engine's identity kernel when none is given; missing cells are 0. + let kernel = p.get("kernel").and_then(J::as_array); + let cell = |i: usize| match kernel { + Some(a) => a.get(i).and_then(J::as_f64).filter(|v| v.is_finite()).unwrap_or(0.0), + None => f64::from(u8::from(i == 12)), + }; + let m = (0..25).map(|i| whole(cell(i), CUSTOM_CELL, "a kernel value")).collect::, _>>()?; + d.with("Scl ", whole(pf(p, "scale", 1.0), CUSTOM_SCALE, "Scale")?) + .with("Ofst", whole(pf(p, "offset", 0.0), CUSTOM_OFFSET, "Offset")?) + .with("Mtrx", Value::List(m)) + } + "LnsF" => { + let lens = p.get("lens").and_then(J::as_str).unwrap_or("zoom"); + let code = LENSES.iter().find(|(_, l)| *l == lens).ok_or_else(|| format!("lens `{lens}` has no PSD equivalent"))?.0; + let mut centre = Descriptor::new("Pnt ").with("Hrzn", Value::Double(pf(p, "centerX", 0.5))).with("Vrtc", Value::Double(pf(p, "centerY", 0.5))); + centre.name = UnicodeString::new_nul(""); + d.with("Brgh", pi(p, "brightness", 100.0)) + .with("FlrC", Value::Descriptor(centre)) + .with("Lns ", Value::Enumerated { type_id: Id::new("Lns "), value: Id::Code(*code) }) + } + "Fbrs" => d.with("Vrnc", pi(p, "variance", 16.0)).with("Strg", pi(p, "strength", 4.0)).with("RndS", seed_param(p)), + "Clds" | "DfrC" => d.with("FlRs", seed_param(p)), + "Lvls" => d.with("Adjs", adjustments(p, false)?), + "Crvs" => d.with("Adjs", adjustments(p, true)?), + "adaptCorrect" => { + if p.as_object().is_some_and(|o| o.keys().any(|k| !is_meta(k))) { + return Err("only default Shadows/Highlights settings are written to PSD".into()); + } + return Ok(None); + } + // No settings to write; any parameter keys an old record carries have no effect on the + // filter either, so nothing is lost. + c if NO_OPTIONS.contains(&c) => return Ok(None), + // Keys and order as Photoshop writes them. + "Pnch" => d.with("Amnt", pi(p, "amount", 50.0)), + "Twrl" => d.with("Angl", pi(p, "angle", 50.0)), + "Rple" => d.with("Amnt", pi(p, "amount", 100.0)).with("RplS", enum_param(p, "size", "medium", "RplS", &RIPPLE_SIZE)?), + "Sphr" => d.with("Amnt", pi(p, "amount", 100.0)).with("SphM", enum_param(p, "mode", "normal", "SphM", &SPHERIZE_MODE)?), + "Plr " => d.with("Cnvr", enum_param(p, "mode", "rectangularToPolar", "Cnvr", &POLAR_MODE)?), + "ZgZg" => { + d.with("Amnt", pi(p, "amount", 10.0)).with("NmbR", pi(p, "ridges", 5.0)).with("ZZTy", enum_param(p, "style", "pondRipples", "ZZTy", &ZIGZAG_STYLE)?) + } + "Wave" => { + // The seed the renderer draws with (engine `filters::seed`): a u32, else a legacy signed + // or fractional seed, rounded and saturated, as its bit pattern. + let seed = match p.get("seed").and_then(J::as_u64).and_then(|s| u32::try_from(s).ok()) { + Some(s) => Value::Integer(s as i32), + None => pi(p, "seed", 0.0), + }; + // The renderer draws at most MAX_WAVE_GENERATORS: write what PhotoCraft rendered, so + // Photoshop doesn't draw more generators than the user saw. + let generators = pf(p, "generators", 5.0).round().clamp(1.0, f64::from(photocraft_algo::MAX_WAVE_GENERATORS)) as i32; + d.with("Wvtp", enum_param(p, "type", "sine", "Wvtp", &WAVE_TYPE)?) + .with("NmbG", Value::Integer(generators)) + .with("WLMn", pi(p, "wavelengthMin", 10.0)) + .with("WLMx", pi(p, "wavelengthMax", 120.0)) + .with("AmMn", pi(p, "amplitudeMin", 5.0)) + .with("AmMx", pi(p, "amplitudeMax", 35.0)) + .with("SclH", Value::Integer(100)) + .with("SclV", Value::Integer(100)) + .with("UndA", enum_param(p, "undefinedAreas", "wrap", "UndA", &UNDEFINED_AREAS)?) + .with("RndS", seed) + } + "Invr" => return Ok(None), + _ => return Err("not a recognized filter".into()), + })) +} + +/// The `filterFXList` item for one smart filter, or why it can't be written. +pub fn item_for_filter(f: &SmartFilter) -> Result { + if f.command == camera_raw::COMMAND { + let mut d = camera_raw::export_item(&f.params)?; + set(&mut d, "blendOptions", blend_options(f)); + set(&mut d, "enab", Value::Boolean(f.visible)); + return Ok(d); + } + if f.command == displace::COMMAND { + let mut d = displace::export_item(&f.params)?; + set(&mut d, "blendOptions", blend_options(f)); + set(&mut d, "enab", Value::Boolean(f.visible)); + return Ok(d); + } + if f.command == GALLERY_COMMAND { + return gallery_item(f); + } + if f.command == hue_sat::COMMAND { + return hue_sat::export_item(f); + } + if perspective_warp::handles(&f.command) { + return perspective_warp::export_item(f); + } + if f.command == UNSUPPORTED_FILTER { + let raw = f.params.get("psd").and_then(J::as_str).and_then(from_hex).ok_or("its filter data is missing")?; + let mut d = Descriptor::from_bytes(&raw).map_err(|e| format!("its filter data is unreadable ({e})"))?; + set(&mut d, "blendOptions", blend_options(f)); + set(&mut d, "enab", Value::Boolean(f.visible)); + return Ok(d); + } + let k = known_by_command(&f.command).ok_or("this filter has no PSD equivalent")?; + let fltr = fltr_for(k, &f.params)?; + // Pointillize's background, Tiles' colours and the render filters' colours are the entry's; + // the others store Photoshop's defaults. + let (fg, bg) = match k.class { + "Pntl" => (rgbc(0.0), colour_rgbc(f.params.get("background"), 255.0)?), + "Tls " | "Fbrs" | "Clds" | "DfrC" => (colour_rgbc(f.params.get("foreground"), 0.0)?, colour_rgbc(f.params.get("background"), 255.0)?), + _ => (rgbc(0.0), rgbc(255.0)), + }; + // The render filters are written with the descriptor names Photoshop gives them: the filter's + // own name on `Fltr` and empty ones on the colours. + let render = matches!(k.class, "Fbrs" | "Clds" | "DfrC" | "LnsF"); + let (fltr, fg, bg) = if render { (fltr.map(|f| named(f, k.name.trim_end_matches("..."))), named_value(fg), named_value(bg)) } else { (fltr, fg, bg) }; + let mut d = Descriptor::new("filterFX") + .with("Nm ", Value::Text(UnicodeString::new_nul(k.name))) + .with("blendOptions", blend_options(f)) + .with("enab", Value::Boolean(f.visible)) + .with("hasoptions", Value::Boolean(fltr.is_some())) + .with("FrgC", fg) + .with("BckC", bg); + if let Some(x) = fltr { + d = d.with("Fltr", Value::Descriptor(x)); + } + Ok(d.with("filterID", Value::Integer(k.filter_id))) +} + +fn named(mut d: Descriptor, name: &str) -> Descriptor { + d.name = UnicodeString::new_nul(name); + d +} + +fn named_value(v: Value) -> Value { + match v { + Value::Descriptor(d) => Value::Descriptor(named(d, "")), + other => other, + } +} + +/// Builds a `filterFX` object; filters that can't be written are left out, with a message each. +pub fn filter_fx(stack: &FilterStack, layer: &str, warnings: &mut Vec) -> Descriptor { + let mut list = Vec::new(); + for f in &stack.filters { + match item_for_filter(f) { + Ok(d) => list.push(Value::Descriptor(d)), + Err(e) => warnings.push(format!("layer \"{layer}\": smart filter {} was not written to PSD: {e}", f.command)), + } + } + Descriptor::new("filterFXStyle") + .with("enab", Value::Boolean(stack.enabled)) + .with("validAtPosition", Value::Boolean(true)) + .with("filterMaskEnable", Value::Boolean(stack.mask_enabled)) + .with("filterMaskLinked", Value::Boolean(stack.mask_linked)) + .with("filterMaskExtendWithWhite", Value::Boolean(true)) + .with("filterFXList", Value::List(list)) +} + +/// Replaces item `key` in place, or appends it. +pub(crate) fn set(d: &mut Descriptor, key: &str, v: Value) { + match d.items.iter_mut().find(|(k, _)| k.is(key)) { + Some(e) => e.1 = v, + None => d.items.push((Id::new(key), v)), + } +} + +/// Replaces item `key` in place, or inserts it before item `before` (appends it without one). +pub(super) fn set_before(d: &mut Descriptor, key: &str, v: Value, before: &str) { + if let Some(e) = d.items.iter_mut().find(|(k, _)| k.is(key)) { + e.1 = v; + return; + } + let at = d.items.iter().position(|(k, _)| k.is(before)).unwrap_or(d.items.len()); + d.items.insert(at, (Id::new(key), v)); +} diff --git a/crates/io/src/smart_map/import.rs b/crates/io/src/smart_map/import.rs new file mode 100644 index 0000000000..341d1d533e --- /dev/null +++ b/crates/io/src/smart_map/import.rs @@ -0,0 +1,826 @@ +use super::export::{CELL_SIZE, blend_options, is_meta, pi, rgbc}; +use super::placed::enumv; +use super::*; + +// ---------- the filters we model ---------- + +/// Photoshop filter → PhotoCraft command, keyed by the `Fltr` class (and `filterID`). +pub(super) struct Known { + pub(super) class: &'static str, + pub(super) filter_id: i32, + /// `Nm ` as Photoshop writes it (the menu item, with its ellipsis and mnemonic). + pub(super) name: &'static str, + command: &'static str, +} + +/// A four-character PSD code as the big-endian integer Photoshop stores it as. +pub(crate) const fn code(c: &[u8; 4]) -> i32 { + i32::from_be_bytes(*c) +} + +const KNOWN: [Known; 53] = [ + Known { class: "GsnB", filter_id: code(b"GsnB"), name: "Gaussian Blur...", command: "filter.blur.gaussianBlur" }, + Known { class: "boxblur", filter_id: 840, name: "Box Blur...", command: "filter.blur.boxBlur" }, + Known { class: "MtnB", filter_id: code(b"MtnB"), name: "Motion Blur...", command: "filter.blur.motionBlur" }, + // Surface Blur, Smart Blur and Radial Blur: keys, value types and enums measured in Photoshop. + Known { class: "surfaceBlur", filter_id: 1135, name: "Surface Blur...", command: "filter.blur.surfaceBlur" }, + Known { class: "SmrB", filter_id: code(b"SmrB"), name: "Smart Blur...", command: "filter.blur.smartBlur" }, + // Radial Blur at its defaults stores no `Fltr` (`hasoptions` false); that entry is kept verbatim. + Known { class: "RdlB", filter_id: code(b"RdlB"), name: "Radial Blur...", command: "filter.blur.radialBlur" }, + Known { class: "UnsM", filter_id: code(b"UnsM"), name: "Unsharp Mask...", command: "filter.sharpen.unsharpMask" }, + Known { class: "AdNs", filter_id: code(b"AdNs"), name: "Add Noise...", command: "filter.noise.addNoise" }, + Known { class: "Mdn ", filter_id: code(b"Mdn "), name: "Median...", command: "filter.noise.median" }, + Known { class: "HghP", filter_id: code(b"HghP"), name: "High Pass...", command: "filter.other.highPass" }, + Known { class: "Mxm ", filter_id: code(b"Mxm "), name: "Maximum...", command: "filter.other.maximum" }, + Known { class: "Mnm ", filter_id: code(b"Mnm "), name: "Minimum...", command: "filter.other.minimum" }, + Known { class: "Ofst", filter_id: code(b"Ofst"), name: "Offset...", command: "filter.other.offset" }, + Known { class: "Cstm", filter_id: code(b"Cstm"), name: "Custom...", command: "filter.other.custom" }, + Known { class: "Msc ", filter_id: code(b"Msc "), name: "Mosaic...", command: "filter.pixelate.mosaic" }, + Known { class: "Mztn", filter_id: code(b"Mztn"), name: "Mezzotint...", command: "filter.pixelate.mezzotint" }, + Known { class: "ClrH", filter_id: code(b"ClrH"), name: "Color Halftone...", command: "filter.pixelate.colorHalftone" }, + Known { class: "Embs", filter_id: code(b"Embs"), name: "Emboss...", command: "filter.stylize.emboss" }, + Known { class: "Dfs ", filter_id: code(b"Dfs "), name: "Diffuse...", command: "filter.stylize.diffuse" }, + Known { class: "TrcC", filter_id: code(b"TrcC"), name: "Trace Contour...", command: "filter.stylize.traceContour" }, + Known { class: "Crst", filter_id: code(b"Crst"), name: "Crystallize...", command: "filter.pixelate.crystallize" }, + Known { class: "Pntl", filter_id: code(b"Pntl"), name: "Pointillize...", command: "filter.pixelate.pointillize" }, + Known { class: "Wnd ", filter_id: code(b"Wnd "), name: "Wind...", command: "filter.stylize.wind" }, + Known { class: "Extr", filter_id: code(b"Extr"), name: "Extrude...", command: "filter.stylize.extrude" }, + Known { class: "Tls ", filter_id: code(b"Tls "), name: "Tiles...", command: "filter.stylize.tiles" }, + Known { class: "Lvls", filter_id: code(b"Lvls"), name: "Levels...", command: "image.adjustments.levels" }, + Known { class: "Crvs", filter_id: code(b"Crvs"), name: "Curves...", command: "image.adjustments.curves" }, + // Shadows/Highlights at its defaults stores no `Fltr` (`hasoptions` false). + Known { class: "adaptCorrect", filter_id: 781, name: "Shado&ws/Highlights...", command: "image.adjustments.shadowsHighlights" }, + // Filters without options (measured in Photoshop): `hasoptions` false, no `Fltr`, only the + // four-char `filterID`. The class is that code; see `NO_OPTIONS`. + Known { class: "Blr ", filter_id: code(b"Blr "), name: "Blur", command: "filter.blur.blur" }, + Known { class: "BlrM", filter_id: code(b"BlrM"), name: "Blur More", command: "filter.blur.blurMore" }, + Known { class: "Avrg", filter_id: code(b"Avrg"), name: "Average", command: "filter.blur.average" }, + Known { class: "Dspc", filter_id: code(b"Dspc"), name: "Despeckle", command: "filter.noise.despeckle" }, + Known { class: "FndE", filter_id: code(b"FndE"), name: "Find Edges", command: "filter.stylize.findEdges" }, + Known { class: "Fct ", filter_id: code(b"Fct "), name: "Facet", command: "filter.pixelate.facet" }, + Known { class: "Frgm", filter_id: code(b"Frgm"), name: "Fragment", command: "filter.pixelate.fragment" }, + Known { class: "Shrp", filter_id: code(b"Shrp"), name: "Sharpen", command: "filter.sharpen.sharpen" }, + Known { class: "ShrM", filter_id: code(b"ShrM"), name: "Sharpen More", command: "filter.sharpen.sharpenMore" }, + Known { class: "ShrE", filter_id: code(b"ShrE"), name: "Sharpen Edges", command: "filter.sharpen.sharpenEdges" }, + Known { class: "Slrz", filter_id: code(b"Slrz"), name: "Solarize", command: "filter.stylize.solarize" }, + // Smart Sharpen has a numeric filterID and a stringID class, like Box Blur. + Known { class: SMART_SHARPEN, filter_id: 1131, name: "Smart Sharpen...", command: "filter.sharpen.smartSharpen" }, + Known { class: "DstS", filter_id: code(b"DstS"), name: "Dust & Scratches...", command: "filter.noise.dustAndScratches" }, + // Distort (Photoshop 27, `corpus`-style check: one smart object per filter saved from Photoshop + // and read back). Shear isn't mapped yet: its curve lives on Photoshop's own grid. + Known { class: "Pnch", filter_id: code(b"Pnch"), name: "Pinch...", command: "filter.distort.pinch" }, + Known { class: "Plr ", filter_id: code(b"Plr "), name: "Polar Coordinates...", command: "filter.distort.polarCoordinates" }, + Known { class: "Rple", filter_id: code(b"Rple"), name: "Ripple...", command: "filter.distort.ripple" }, + Known { class: "Sphr", filter_id: code(b"Sphr"), name: "Spherize...", command: "filter.distort.spherize" }, + Known { class: "Twrl", filter_id: code(b"Twrl"), name: "Twirl...", command: "filter.distort.twirl" }, + Known { class: "Wave", filter_id: code(b"Wave"), name: "Wave...", command: "filter.distort.wave" }, + Known { class: "ZgZg", filter_id: code(b"ZgZg"), name: "ZigZag...", command: "filter.distort.zigZag" }, + // Image › Adjustments › Invert on a smart object: no settings, so no `Fltr` (`hasoptions` false). + Known { class: "Invr", filter_id: code(b"Invr"), name: "Invert", command: "image.adjustments.invert" }, + Known { class: "LnsF", filter_id: code(b"LnsF"), name: "Lens Flare...", command: "filter.render.lensFlare" }, + // These three also read the item's foreground and background colours (`coloured_params`). + Known { class: "Fbrs", filter_id: code(b"Fbrs"), name: "Fibers...", command: "filter.render.fibers" }, + Known { class: "Clds", filter_id: code(b"Clds"), name: "Clouds", command: "filter.render.clouds" }, + Known { class: "DfrC", filter_id: code(b"DfrC"), name: "Difference Clouds", command: "filter.render.differenceClouds" }, +]; + +/// Lens Flare's `Lns ` enum and our `lens` values. Photoshop's codes keep the old lens names: +/// Nikon 35 mm and 105 mm primes, a Panavision movie prime. +pub(super) const LENSES: [(&[u8; 4], &str); 4] = [(b"Zm ", "zoom"), (b"Nkn ", "prime35"), (b"Nkn1", "prime105"), (b"PnVs", "moviePrime")]; + +/// Classes of the filters that have no options: Photoshop stores them without a `Fltr`. +pub(super) const NO_OPTIONS: [&str; 11] = ["Blr ", "BlrM", "Avrg", "Dspc", "FndE", "Fct ", "Frgm", "Shrp", "ShrM", "ShrE", "Slrz"]; + +// ---------- Smart Sharpen and Dust & Scratches ---------- +// +// Measured in Photoshop (applied through Action Manager to a smart object, saved, `filterFX` read +// back): +// +// ```text +// Smart Sharpen (filterID 1131): smartSharpen { presetKind = presetKindType enum (only on the +// default entry), useLegacy bool, Amnt UntF #Prc, Rds UntF #Pxl, noiseReduction UntF #Prc, +// blur = blurType enum (GsnB | lensBlur | MtnB), Angl long (Motion Blur only) } +// Dust & Scratches (filterID DstS): DstS { Rds long, Thsh long } +// ``` +// +// PhotoCraft's Smart Sharpen removes a Gaussian blur, non-legacy: Lens Blur, Motion Blur, legacy +// mode, Shadow/Highlight settings or any other key keep the whole entry verbatim. `presetKind` +// only names the dialog's preset: it is accepted on open but not kept (the engine takes no such +// parameter) and not written (Photoshop leaves it out of entries with explicit values). + +pub(super) const SMART_SHARPEN: &str = "smartSharpen"; + +const SMART_SHARPEN_KEYS: [&str; 6] = ["presetKind", "useLegacy", "Amnt", "Rds ", "noiseReduction", "blur"]; + +/// A `UntF` value in `unit`, finite and within `lo..=hi`. +fn unit_in(d: &Descriptor, key: &str, u: &[u8; 4], lo: f64, hi: f64) -> Option { + match d.get(key)? { + Value::UnitFloat { unit, value } if unit == u && value.is_finite() && (lo..=hi).contains(value) => Some(*value), + _ => None, + } +} + +/// `filter.sharpen.smartSharpen` params; `None` for a setting PhotoCraft doesn't render. +fn smart_sharpen_params(f: &Descriptor) -> Option { + if f.items.iter().any(|(k, _)| !SMART_SHARPEN_KEYS.iter().any(|x| k.is(x))) { + return None; + } + let Some(Value::Boolean(false)) = f.get("useLegacy") else { return None }; + let Some(Value::Enumerated { type_id, value }) = f.get("blur") else { return None }; + if !type_id.is("blurType") || !value.is("GsnB") { + return None; + } + let mut out = Map::new(); + out.insert("amount".into(), json!(unit_in(f, "Amnt", b"#Prc", 1.0, 500.0)?)); + out.insert("radius".into(), json!(unit_in(f, "Rds ", b"#Pxl", 0.1, 64.0)?)); + out.insert("reduceNoise".into(), json!(unit_in(f, "noiseReduction", b"#Prc", 0.0, 100.0)?)); + match f.get("presetKind") { + None => {} + Some(Value::Enumerated { type_id, .. }) if type_id.is("presetKindType") => {} + Some(_) => return None, + } + Some(J::Object(out)) +} + +/// Photoshop enum codes ↔ PhotoCraft parameter values, per filter setting. +pub(super) const RIPPLE_SIZE: [(&[u8; 4], &str); 3] = [(b"Sml ", "small"), (b"Mdm ", "medium"), (b"Lrg ", "large")]; + +pub(super) const SPHERIZE_MODE: [(&[u8; 4], &str); 3] = [(b"Nrml", "normal"), (b"HrzO", "horizontalOnly"), (b"VrtO", "verticalOnly")]; + +pub(super) const POLAR_MODE: [(&[u8; 4], &str); 2] = [(b"RctP", "rectangularToPolar"), (b"PlrR", "polarToRectangular")]; + +pub(super) const ZIGZAG_STYLE: [(&[u8; 4], &str); 3] = [(b"PndR", "pondRipples"), (b"OtFr", "outFromCenter"), (b"ArnC", "aroundCenter")]; + +pub(super) const WAVE_TYPE: [(&[u8; 4], &str); 3] = [(b"WvSn", "sine"), (b"WvTr", "triangle"), (b"WvSq", "square")]; + +pub(super) const UNDEFINED_AREAS: [(&[u8; 4], &str); 2] = [(b"WrpA", "wrap"), (b"RptE", "repeat")]; + +/// The PSD filter record that PhotoCraft's `command` is written as, if it has one. +pub(super) fn known_by_command(command: &str) -> Option<&'static Known> { + KNOWN.iter().find(|k| k.command == command) +} + +/// RGB channel references in Levels/Curves (`Chnl` enum) and their parameter keys ("" = the +/// composite: top-level keys). +pub(super) const CHANNELS: [(&[u8; 4], &str); 4] = [(b"Cmps", ""), (b"Rd ", "red"), (b"Grn ", "green"), (b"Bl ", "blue")]; + +/// Mezzotint's `MztT` enum codes and our `type` values (measured in Photoshop by rendering each). +pub(super) const MEZZOTINT_TYPES: [(&[u8; 4], &str); 10] = [ + (b"FnDt", "fineDots"), + (b"MdmD", "mediumDots"), + (b"GrnD", "grainyDots"), + (b"CrsD", "coarseDots"), + (b"ShrL", "shortLines"), + (b"MdmL", "mediumLines"), + (b"LngL", "longLines"), + (b"ShSt", "shortStrokes"), + (b"MdmS", "mediumStrokes"), + (b"LngS", "longStrokes"), +]; + +/// Color Halftone's `Rds ` (max radius) and `Ang1`..`Ang4` (screen angles) longs, read within +/// the dialog's ranges; anything else is kept verbatim. +fn color_halftone_params(f: &Descriptor) -> Option { + if !only_keys(f, &["Rds ", "Ang1", "Ang2", "Ang3", "Ang4"]) { + return None; + } + let radius = int(f, "Rds ").filter(|r| (4..=127).contains(r))?; + let angle = |k: &str| int(f, k).filter(|a| (-360..=360).contains(a)); + Some(json!({"maxRadius": radius, "channel1": angle("Ang1")?, "channel2": angle("Ang2")?, "channel3": angle("Ang3")?, "channel4": angle("Ang4")?})) +} + +/// A numeric descriptor item as a finite number; `None` when it is absent, not a number, or not finite. +fn px(d: &Descriptor, key: &str) -> Option { + num(d.get(key)).filter(|v| v.is_finite()) +} + +/// An integer descriptor item; `None` when it is absent or of another type. +pub(crate) fn int(d: &Descriptor, key: &str) -> Option { + match d.get(key)? { + Value::Integer(i) => Some(*i), + _ => None, + } +} + +/// `v` when it lies in `lo..=hi` (the filter dialog's range); out-of-range settings are not +/// opened as editable filters, so a re-save keeps Photoshop's value instead of a clamped one. +fn in_range(v: f64, lo: f64, hi: f64) -> Option { + (lo..=hi).contains(&v).then_some(v) +} + +/// Integer `key` of `f` when it lies in `lo..=hi`. +fn int_in(f: &Descriptor, key: &str, lo: i32, hi: i32) -> Option { + int(f, key).filter(|v| (lo..=hi).contains(v)) +} + +/// True when `f` holds only the given keys, each at most once. A filter with a setting we don't +/// know about (Radial Blur's off-centre centre, for one) or a repeated one is kept verbatim rather +/// than losing that setting. +fn only_keys(f: &Descriptor, keys: &[&str]) -> bool { + f.items.iter().all(|(k, _)| keys.iter().any(|x| k.is(x))) && keys.iter().all(|key| f.items.iter().filter(|(k, _)| k.is(key)).count() <= 1) +} + +/// Our name for enum `key`'s value in `f` (of enum type `type_id`), from `(PSD value, our name)` +/// pairs. An enum of another type is not one we know, so the filter stays verbatim. +fn enum_name(f: &Descriptor, key: &str, type_id: &str, table: &[(&[u8; 4], &'static str)]) -> Option<&'static str> { + let Some(Value::Enumerated { type_id: t, value }) = f.get(key) else { return None }; + if t.as_bytes() != type_id.as_bytes() { + return None; + } + table.iter().find(|(c, _)| value.as_bytes() == &c[..]).map(|(_, n)| *n) +} + +/// True when `f` holds each of the given keys once and nothing else. +fn exact_keys(f: &Descriptor, keys: &[&str]) -> bool { + only_keys(f, keys) && keys.iter().all(|x| f.items.iter().any(|(k, _)| k.is(x))) +} + +/// Finite `key` of `f` stored as a plain double (the type Photoshop writes and we write back). +fn double(f: &Descriptor, key: &str) -> Option { + match f.get(key)? { + Value::Double(v) if v.is_finite() => Some(*v), + _ => None, + } +} + +/// `p[key]` (`default` when absent) when it is a number in `lo..=hi`, the range the filter opens +/// with; anything else is an error, so a saved filter always opens as the same editable filter. +pub(super) fn pf_range(p: &J, key: &str, default: f64, lo: f64, hi: f64) -> Result { + match p.get(key) { + None | Some(J::Null) => Ok(default), + Some(v) => v.as_f64().filter(|x| (lo..=hi).contains(x)).ok_or_else(|| format!("setting `{key}` ({v}) is not a number in {lo}..={hi}")), + } +} + +/// Integer `p[key]` (rounded; `default` when absent) in `lo..=hi`, as a PSD long. +pub(super) fn pi_range(p: &J, key: &str, default: f64, lo: i32, hi: i32) -> Result { + let v = pf_range(p, key, default, f64::from(i32::MIN), f64::from(i32::MAX))?.round(); + let range = f64::from(lo)..=f64::from(hi); + if !range.contains(&v) { + return Err(format!("setting `{key}` ({v}) is not a number in {lo}..={hi}")); + } + Ok(Value::Integer(v as i32)) +} + +/// Enum `type_id` holding the PSD value of our name `p[key]` (`default` when absent). +pub(super) fn enum_param(p: &J, key: &str, default: &str, type_id: &str, table: &[(&[u8; 4], &'static str)]) -> Result { + let name = match p.get(key) { + None | Some(J::Null) => default, + Some(v) => v.as_str().ok_or_else(|| format!("setting `{key}` is not text"))?, + }; + let code = table.iter().find(|(_, n)| *n == name).map(|(c, _)| **c).ok_or_else(|| format!("{key} `{name}` has no PSD equivalent"))?; + Ok(Value::Enumerated { type_id: Id::new(type_id), value: Id::Code(code) }) +} + +/// Smart Blur `SmBQ` / `SmBM` and Radial Blur `BlrM` / `BlrQ` values (measured in Photoshop). +pub(super) const SMART_BLUR_QUALITY: [(&[u8; 4], &str); 3] = [(b"SBQL", "low"), (b"SBQM", "medium"), (b"SBQH", "high")]; + +pub(super) const SMART_BLUR_MODE: [(&[u8; 4], &str); 3] = [(b"SBMN", "normal"), (b"SBME", "edgeOnly"), (b"SBMO", "overlayEdge")]; + +pub(super) const RADIAL_METHOD: [(&[u8; 4], &str); 2] = [(b"Spn ", "spin"), (b"Zm ", "zoom")]; + +pub(super) const RADIAL_QUALITY: [(&[u8; 4], &str); 3] = [(b"Drft", "draft"), (b"Gd ", "good"), (b"Bst ", "best")]; + +fn channel_key(d: &Descriptor) -> Option<&'static str> { + let Some(Value::Reference(items)) = d.get("Chnl") else { return None }; + let Some(ReferenceItem::Enumerated { value, .. }) = items.first() else { return None }; + CHANNELS.iter().find(|(c, _)| value.as_bytes() == &c[..]).map(|(_, k)| *k) +} + +pub(super) fn adjustment_list(d: &Descriptor) -> Option> { + let Some(Value::List(items)) = d.get("Adjs") else { return None }; + items + .iter() + .map(|v| match v { + Value::Descriptor(x) => Some(x), + _ => None, + }) + .collect() +} + +fn levels_params(f: &Descriptor) -> Option { + let mut out = Map::new(); + for a in adjustment_list(f)? { + let key = channel_key(a)?; + let mut o = Map::new(); + let pair = |k: &str| match a.get(k) { + Some(Value::List(v)) if v.len() == 2 => Some((int_value(&v[0])?, int_value(&v[1])?)), + _ => None, + }; + if let Some((lo, hi)) = pair("Inpt") { + o.insert("inBlack".into(), json!(lo)); + o.insert("inWhite".into(), json!(hi)); + } + if let Some(g) = px(a, "Gmm ") { + o.insert("gamma".into(), json!(g)); + } + if let Some((lo, hi)) = pair("Otpt") { + o.insert("outBlack".into(), json!(lo)); + o.insert("outWhite".into(), json!(hi)); + } + if key.is_empty() { + out.extend(o); + } else { + out.insert(key.into(), J::Object(o)); + } + } + Some(J::Object(out)) +} + +fn int_value(v: &Value) -> Option { + match v { + Value::Integer(i) => Some(*i), + _ => None, + } +} + +fn curves_params(f: &Descriptor) -> Option { + let mut out = Map::new(); + for a in adjustment_list(f)? { + let key = channel_key(a)?; + // A pencil-drawn curve is a mapping of 256 output levels (`Mpng`) instead of points. + if let Some(Value::List(map)) = a.get("Mpng") { + let map: Option> = map.iter().map(|v| int_value(v).map(|o| json!(o.clamp(0, 255)))).collect(); + out.insert(if key.is_empty() { "points".into() } else { key.into() }, J::Array(map.filter(|m| m.len() == 256)?)); + out.insert("pencil".into(), J::Bool(true)); + continue; + } + let Some(Value::List(pts)) = a.get("Crv ") else { return None }; + let pts: Option> = pts + .iter() + .map(|p| match p { + Value::Descriptor(p) => Some(json!([px(p, "Hrzn")?, px(p, "Vrtc")?])), + _ => None, + }) + .collect(); + out.insert(if key.is_empty() { "points".into() } else { key.into() }, J::Array(pts?)); + } + Some(J::Object(out)) +} + +/// Diffuse's `Md ` (`DfsM` enum, measured in Photoshop) ↔ our `mode`. +pub(super) const DIFFUSE_MODES: [(&str, &str); 4] = [("Nrml", "normal"), ("DrkO", "darkenOnly"), ("LghO", "lightenOnly"), ("anisotropic", "anisotropic")]; + +/// Trace Contour's `Edg ` (`CntE` enum, measured in Photoshop) ↔ our `edge`. +pub(super) const TRACE_EDGES: [(&str, &str); 2] = [("Upr ", "upper"), ("Lwr ", "lower")]; + +/// Our name for the enum value of `key` (of type `type_id`) through `table` (Photoshop's value, ours). +fn enum_from(d: &Descriptor, key: &str, type_id: &str, table: &[(&str, &'static str)]) -> Option<&'static str> { + let Some(Value::Enumerated { type_id: t, value }) = d.get(key) else { return None }; + if t.as_bytes() != type_id.as_bytes() { + return None; + } + table.iter().find(|(psd, _)| value.as_bytes() == psd.as_bytes()).map(|(_, ours)| *ours) +} + +// Wind, Extrude and Tiles, measured in Photoshop (each code changes the rendered result). + +/// Wind's `WndM` (enum `WndM`) ↔ our `method`. +pub(super) const WIND_METHODS: [(&str, &str); 3] = [("Wnd ", "wind"), ("Blst", "blast"), ("Stgr", "stagger")]; + +/// Wind's `Drct` (enum `Drct`) ↔ our `direction`. Photoshop's `Left` streaks extend to the left +/// of an edge, which is our wind from the right. +pub(super) const WIND_DIRECTIONS: [(&str, &str); 2] = [("Left", "fromRight"), ("Rght", "fromLeft")]; + +/// Extrude's `ExtT` (enum `ExtT`) ↔ our `type`. +pub(super) const EXTRUDE_TYPES: [(&str, &str); 2] = [("Blks", "blocks"), ("Pyrm", "pyramids")]; + +/// Extrude's `ExtR` (enum `ExtR`) ↔ our `depthMode`. +pub(super) const EXTRUDE_DEPTHS: [(&str, &str); 2] = [("Rndm", "random"), ("LvlB", "levelBased")]; + +/// Tiles' `FlCl` (enum `FlCl`) ↔ our `fill`. +pub(super) const TILE_FILLS: [(&str, &str); 4] = [("FlBc", "background"), ("FlFr", "foreground"), ("FlIn", "inverse"), ("FlSm", "unaltered")]; + +/// Extrude's size and depth (`ExtS`, `ExtD`) and Tiles' count and offset (`TlNm`, `TlOf`), all +/// `long`s, in the engine's (and Photoshop's dialog) ranges. +pub(super) const EXTRUDE_SIZE: (i32, i32) = (2, 255); + +pub(super) const EXTRUDE_DEPTH: (i32, i32) = (1, 255); + +pub(super) const TILE_COUNT: (i32, i32) = (1, 99); + +pub(super) const TILE_OFFSET: (i32, i32) = (1, 99); + +/// The `bool` at `key`. +fn bool_at(d: &Descriptor, key: &str) -> Option { + match d.get(key)? { + Value::Boolean(b) => Some(*b), + _ => None, + } +} + +/// Tiles' params; background and foreground fills use the colours the entry carries (`FrgC`, +/// `BckC`). `None` when a setting or a colour that is there can't be read. +fn tiles_params(f: &Descriptor, item: &Descriptor) -> Option { + let mut out = Map::new(); + out.insert("count".into(), json!(int_in(f, "TlNm", TILE_COUNT.0, TILE_COUNT.1)?)); + out.insert("maxOffset".into(), json!(int_in(f, "TlOf", TILE_OFFSET.0, TILE_OFFSET.1)?)); + out.insert("fill".into(), json!(enum_from(f, "FlCl", "FlCl", &TILE_FILLS)?)); + for (psd, ours) in [("FrgC", "foreground"), ("BckC", "background")] { + if item.get(psd).is_some() { + out.insert(ours.into(), get_desc(item, psd).and_then(rgbc_colour)?); + } + } + Some(J::Object(out)) +} + +/// Offset › Undefined Areas: the `FlMd` enum (`Fl `) and our `undefinedAreas`. On a layer +/// Photoshop labels `Bckg` "Set to Transparent"; a smart object is always a layer. +pub(super) const OFFSET_FILL: [(&str, &str); 3] = [("Wrp ", "wrap"), ("Rpt ", "repeat"), ("Bckg", "transparent")]; + +/// Custom's ranges in Photoshop's dialog: matrix cells, Scale, Offset. +pub(super) const CUSTOM_CELL: (i32, i32) = (-999, 999); + +pub(super) const CUSTOM_SCALE: (i32, i32) = (1, 9999); + +pub(super) const CUSTOM_OFFSET: (i32, i32) = (-9999, 9999); + +/// `v` when it lies in `lo..=hi`. +fn long_in_range(v: Option, (lo, hi): (i32, i32)) -> Option { + v.filter(|v| (lo..=hi).contains(v)) +} + +/// `filter.other.custom` params for a `Cstm` filter: `Mtrx` is 25 longs, row-major 5 × 5. Values +/// outside Photoshop's ranges are not modelled (the filter stays verbatim). +fn custom_params(f: &Descriptor) -> Option { + if !only_keys(f, &["Mtrx", "Scl ", "Ofst"]) { + return None; + } + let Some(Value::List(m)) = f.get("Mtrx") else { return None }; + if m.len() != 25 { + return None; + } + let kernel: Option> = m.iter().map(|v| long_in_range(int_value(v), CUSTOM_CELL).map(|v| json!(v))).collect(); + let scale = long_in_range(int(f, "Scl "), CUSTOM_SCALE)?; + let offset = long_in_range(int(f, "Ofst"), CUSTOM_OFFSET)?; + Some(json!({"kernel": kernel?, "scale": scale, "offset": offset})) +} + +/// The settings of Photoshop's Wave, as it writes them (and we write them back). +const WAVE_KEYS: [&str; 10] = ["Wvtp", "NmbG", "WLMn", "WLMx", "AmMn", "AmMx", "SclH", "SclV", "UndA", "RndS"]; + +/// Our command and parameters for a known Photoshop filter; `None` when the filter (or one of its +/// settings) is not modelled. `item` is the whole `filterFX` entry (Pointillize reads its `BckC`, +/// Tiles its colours). +pub(super) fn known_params(class: &str, f: Option<&Descriptor>, item: &Descriptor) -> Option<(&'static str, J)> { + let k = KNOWN.iter().find(|k| k.class == class)?; + let params = match (class, f) { + ("adaptCorrect" | "Invr", None) => json!({}), + (c, None) if NO_OPTIONS.contains(&c) => json!({}), + (_, None) => return None, + // Exactly the settings Photoshop writes (and we write back); an extra or repeated one keeps + // the filter verbatim rather than lose it on save. + ("Pnch", Some(f)) if exact_keys(f, &["Amnt"]) => json!({"amount": int(f, "Amnt")?}), + ("Twrl", Some(f)) if exact_keys(f, &["Angl"]) => json!({"angle": int(f, "Angl")?}), + ("Rple", Some(f)) if exact_keys(f, &["Amnt", "RplS"]) => json!({"amount": int(f, "Amnt")?, "size": enum_name(f, "RplS", "RplS", &RIPPLE_SIZE)?}), + ("Sphr", Some(f)) if exact_keys(f, &["Amnt", "SphM"]) => json!({"amount": int(f, "Amnt")?, "mode": enum_name(f, "SphM", "SphM", &SPHERIZE_MODE)?}), + ("Plr ", Some(f)) if exact_keys(f, &["Cnvr"]) => json!({"mode": enum_name(f, "Cnvr", "Cnvr", &POLAR_MODE)?}), + ("ZgZg", Some(f)) if exact_keys(f, &["Amnt", "NmbR", "ZZTy"]) => { + json!({"amount": int(f, "Amnt")?, "ridges": int(f, "NmbR")?, "style": enum_name(f, "ZZTy", "ZZTy", &ZIGZAG_STYLE)?}) + } + ("Wave", Some(f)) if exact_keys(f, &WAVE_KEYS) => { + // PhotoCraft's Wave has no Scale: a scaled wave stays verbatim rather than lose it. The + // same for more generators than the renderer models, which would draw fewer than + // Photoshop did (and than the file asks for, once its cached pixels are re-rendered). + let generators = int(f, "NmbG")?; + let modelled = u32::try_from(generators).is_ok_and(|g| (1..=photocraft_algo::MAX_WAVE_GENERATORS).contains(&g)); + if int(f, "SclH")? != 100 || int(f, "SclV")? != 100 || !modelled { + return None; + } + json!({ + "type": enum_name(f, "Wvtp", "Wvtp", &WAVE_TYPE)?, + "generators": generators, + "wavelengthMin": int(f, "WLMn")?, + "wavelengthMax": int(f, "WLMx")?, + "amplitudeMin": int(f, "AmMn")?, + "amplitudeMax": int(f, "AmMx")?, + "undefinedAreas": enum_name(f, "UndA", "UndA", &UNDEFINED_AREAS)?, + // `RndS` is a signed long; the seed is its bit pattern. + "seed": (int(f, "RndS")? as u32), + }) + } + ("GsnB" | "boxblur" | "Mdn " | "HghP" | "Mxm " | "Mnm ", Some(f)) => json!({"radius": px(f, "Rds ")?}), + ("MtnB", Some(f)) => json!({"angle": int(f, "Angl")?, "distance": px(f, "Dstn")?}), + ("UnsM", Some(f)) => json!({"amount": px(f, "Amnt")?, "radius": px(f, "Rds ")?, "threshold": int(f, "Thsh")?}), + ("AdNs", Some(f)) => { + let dist = match enum_of(f, "Dstr")? { + b"Unfr" => "uniform", + b"Gsn " => "gaussian", + _ => return None, + }; + let mono = match f.get("Mnch") { + Some(Value::Boolean(b)) => *b, + _ => return None, + }; + json!({"amount": px(f, "Nose")?, "distribution": dist, "monochromatic": mono, "seed": int(f, "FlRs").unwrap_or(0)}) + } + ("surfaceBlur", Some(f)) if only_keys(f, &["Rds ", "Thsh"]) => json!({ + "radius": unit_in(f, "Rds ", b"#Pxl", 1.0, 100.0)?, + "threshold": int_in(f, "Thsh", 2, 255)?, + }), + ("SmrB", Some(f)) if only_keys(f, &["Rds ", "Thsh", "SmBQ", "SmBM"]) => json!({ + "radius": in_range(double(f, "Rds ")?, 0.1, 100.0)?, + "threshold": in_range(double(f, "Thsh")?, 0.1, 100.0)?, + "quality": enum_name(f, "SmBQ", "SmBQ", &SMART_BLUR_QUALITY)?, + "mode": enum_name(f, "SmBM", "SmBM", &SMART_BLUR_MODE)?, + }), + ("RdlB", Some(f)) if only_keys(f, &["Amnt", "BlrM", "BlrQ"]) => json!({ + "amount": int_in(f, "Amnt", 1, 100)?, + "method": enum_name(f, "BlrM", "BlrM", &RADIAL_METHOD)?, + "quality": enum_name(f, "BlrQ", "BlrQ", &RADIAL_QUALITY)?, + }), + ("Msc ", Some(f)) => json!({"cellSize": px(f, "ClSz")?}), + ("Mztn", Some(f)) if only_keys(f, &["MztT"]) => json!({"type": enum_name(f, "MztT", "MztT", &MEZZOTINT_TYPES)?}), + ("ClrH", Some(f)) => color_halftone_params(f)?, + ("Embs", Some(f)) => json!({"angle": int(f, "Angl")?, "height": int(f, "Hght")?, "amount": int(f, "Amnt")?}), + (SMART_SHARPEN, Some(f)) => smart_sharpen_params(f)?, + ("DstS", Some(f)) => { + if f.items.iter().any(|(k, _)| !k.is("Rds ") && !k.is("Thsh")) { + return None; + } + json!({"radius": int_in(f, "Rds ", 1, 500)?, "threshold": int_in(f, "Thsh", 0, 255)?}) + } + ("Dfs ", Some(f)) => json!({"mode": enum_from(f, "Md ", "DfsM", &DIFFUSE_MODES)?}), + ("TrcC", Some(f)) => json!({"level": int_in(f, "Lvl ", 0, 255)?, "edge": enum_from(f, "Edg ", "CntE", &TRACE_EDGES)?}), + ("Crst", Some(f)) => json!({"cellSize": int_in(f, "ClSz", CELL_SIZE.0, CELL_SIZE.1)?}), + ("Pntl", Some(f)) => { + let mut p = json!({"cellSize": int_in(f, "ClSz", CELL_SIZE.0, CELL_SIZE.1)?}); + // Pointillize paints the gaps in the background colour the entry carries. + if item.get("BckC").is_some() { + p["background"] = get_desc(item, "BckC").and_then(rgbc_colour)?; + } + p + } + ("Wnd ", Some(f)) => json!({ + "method": enum_from(f, "WndM", "WndM", &WIND_METHODS)?, + "direction": enum_from(f, "Drct", "Drct", &WIND_DIRECTIONS)?, + }), + ("Extr", Some(f)) => json!({ + "type": enum_from(f, "ExtT", "ExtT", &EXTRUDE_TYPES)?, + "size": int_in(f, "ExtS", EXTRUDE_SIZE.0, EXTRUDE_SIZE.1)?, + "depth": int_in(f, "ExtD", EXTRUDE_DEPTH.0, EXTRUDE_DEPTH.1)?, + "depthMode": enum_from(f, "ExtR", "ExtR", &EXTRUDE_DEPTHS)?, + "solidFrontFaces": bool_at(f, "ExtF")?, + "maskIncompleteBlocks": bool_at(f, "ExtM")?, + }), + ("Tls ", Some(f)) => tiles_params(f, item)?, + ("Ofst", Some(f)) if only_keys(f, &["Hrzn", "Vrtc", "Fl "]) => { + json!({"horizontal": int(f, "Hrzn")?, "vertical": int(f, "Vrtc")?, "undefinedAreas": enum_from(f, "Fl ", "FlMd", &OFFSET_FILL)?}) + } + ("Cstm", Some(f)) => custom_params(f)?, + // Only the settings and value types Photoshop writes (and we write back); anything else + // keeps the filter verbatim. + ("LnsF", Some(f)) if exact_keys(f, &["Brgh", "FlrC", "Lns "]) => { + let centre = get_desc(f, "FlrC").filter(|c| c.class_id.is("Pnt ") && exact_keys(c, &["Hrzn", "Vrtc"]))?; + let lens = enum_name(f, "Lns ", "Lns ", &LENSES)?; + json!({"brightness": int(f, "Brgh")?, "centerX": double(centre, "Hrzn")?, "centerY": double(centre, "Vrtc")?, "lens": lens}) + } + ("Lvls", Some(f)) => levels_params(f)?, + ("Crvs", Some(f)) => curves_params(f)?, + _ => return None, + }; + Some((k.command, params)) +} + +// ---------- Filter Gallery ---------- +// +// Filter › Filter Gallery stores its effect stack in a `GEfc` filter (filterID `GEfc`). Photoshop +// writes a single effect inline; Photopea writes a list (also for one effect): +// +// ```text +// Fltr = GEfc { GEfk = GEft enum (the effect), } (Photoshop) +// Fltr = GEfc { GEfs = [ GEfc { , GEfk = GEft enum, GELv = visible } ] } (Photopea) +// ``` +// +// The list is in application order, like `filter.filterGallery`'s `effects`. The item's +// `FrgC`/`BckC` are the colours the Sketch effects read. Only effects whose settings we know are +// mapped; a stack with any other effect (or setting) stays an [`UNSUPPORTED_FILTER`]. + +const GALLERY_CLASS: &str = "GEfc"; + +pub(super) const GALLERY_COMMAND: &str = "filter.filterGallery"; + +const GALLERY_NAME: &str = "Filter Gallery..."; + +/// One gallery effect: our filter key, Photoshop's `GEft` code and its settings (PSD key, our key). +pub(super) struct GalleryCode { + pub(super) key: &'static str, + code: &'static str, + pub(super) settings: &'static [(&'static str, &'static str)], +} + +pub(super) const GALLERY_EFFECTS: [GalleryCode; 1] = [GalleryCode { key: "chrome", code: "Chrm", settings: &[("Dtl ", "detail"), ("Smth", "smoothness")] }]; + +/// An `RGBC` descriptor (0–255 channels) as straight `[r, g, b, a]`, 0–1. +fn rgbc_colour(d: &Descriptor) -> Option { + let c = |k: &str| px(d, k).map(|v| (v / 255.0).clamp(0.0, 1.0)); + Some(json!([c("Rd ")?, c("Grn ")?, c("Bl ")?, 1.0])) +} + +/// Fibers, Clouds and Difference Clouds draw with the item's foreground and background colours: +/// their params are the `Fltr` settings plus those colours. +fn coloured_params(class: &str, item: &Descriptor, f: &Descriptor) -> Option<(&'static str, J)> { + let k = KNOWN.iter().find(|k| k.class == class)?; + // An `RGBC` of three `doub`s in 0–255, as Photoshop writes it (and we write it back); any + // other colour keeps the filter verbatim. + let colour = |key: &str| { + get_desc(item, key) + .filter(|c| c.class_id.is("RGBC") && exact_keys(c, &["Rd ", "Grn ", "Bl "])) + .filter(|c| ["Rd ", "Grn ", "Bl "].iter().all(|k| double(c, k).is_some_and(|v| (0.0..=255.0).contains(&v)))) + .and_then(rgbc_colour) + }; + // Only the settings Photoshop writes; an extra or repeated one keeps the filter verbatim. + let keys: &[&str] = if class == "Fbrs" { &["Vrnc", "Strg", "RndS"] } else { &["FlRs"] }; + if !exact_keys(f, keys) { + return None; + } + // The seeds (`RndS`, `FlRs`) are signed longs; ours is their bit pattern. + let mut p = match class { + "Fbrs" => json!({"variance": int(f, "Vrnc")?, "strength": int(f, "Strg")?, "seed": int(f, "RndS")? as u32}), + _ => json!({"seed": int(f, "FlRs")? as u32}), + }; + let o = p.as_object_mut()?; + o.insert("foreground".into(), colour("FrgC")?); + o.insert("background".into(), colour("BckC")?); + Some((k.command, p)) +} + +pub(super) fn seed_param(p: &J) -> Value { + Value::Integer(p.get("seed").and_then(J::as_u64).and_then(|n| u32::try_from(n).ok()).unwrap_or(0) as i32) +} + +/// `filter.filterGallery` params for a `GEfc` filter item; `None` when an effect or setting is +/// not modelled. +fn gallery_params(item: &Descriptor, f: &Descriptor) -> Option { + let list: Vec<&Descriptor> = match f.get("GEfs") { + Some(Value::List(list)) => list + .iter() + .map(|v| match v { + Value::Descriptor(e) => Some(e), + _ => None, + }) + .collect::>()?, + Some(_) => return None, + None if f.get("GEfk").is_some() => vec![f], + None => return None, + }; + let mut effects = Vec::with_capacity(list.len()); + for e in list { + let code = enum_of(e, "GEfk")?; + let g = GALLERY_EFFECTS.iter().find(|g| g.code.as_bytes() == code)?; + let mut params = Map::new(); + for (k, v) in &e.items { + if k.is("GEfk") || k.is("GELv") { + continue; + } + let (_, ours) = g.settings.iter().find(|(psd, _)| k.is(psd))?; + params.insert((*ours).into(), json!(int_value(v)?)); + } + effects.push(json!({"filter": g.key, "params": params, "visible": bool_or(e, "GELv", true)})); + } + if effects.is_empty() { + return None; + } + let mut out = Map::new(); + out.insert("effects".into(), J::Array(effects)); + for (psd, ours) in [("FrgC", "foreground"), ("BckC", "background")] { + if let Some(c) = get_desc(item, psd).and_then(rgbc_colour) { + out.insert(ours.into(), c); + } + } + Some(J::Object(out)) +} + +fn colour_rgb(v: &J) -> Option<[f64; 3]> { + match v { + J::Array(a) => Some([a.first()?.as_f64()?, a.get(1)?.as_f64()?, a.get(2)?.as_f64()?]), + J::String(h) if h.len() == 7 && h.starts_with('#') => { + let ch = |j: usize| h.get(j..j + 2).and_then(|s| u8::from_str_radix(s, 16).ok()).map(|v| f64::from(v) / 255.0); + Some([ch(1)?, ch(3)?, ch(5)?]) + } + _ => None, + } +} + +/// A `[r, g, b(, a)]` (0–1) or `#rrggbb` colour param as an `RGBC` descriptor (0–255). +pub(super) fn colour_rgbc(v: Option<&J>, default: f64) -> Result { + let Some(v) = v else { return Ok(rgbc(default)) }; + let rgb = colour_rgb(v).filter(|c| c.iter().all(|v| v.is_finite())).ok_or("a colour is not [r, g, b] or #rrggbb")?; + let c = |v: f64| Value::Double(v.clamp(0.0, 1.0) * 255.0); + Ok(Value::Descriptor(Descriptor::new("RGBC").with("Rd ", c(rgb[0])).with("Grn ", c(rgb[1])).with("Bl ", c(rgb[2])))) +} + +/// The `filterFXList` item for a `filter.filterGallery` smart filter. +pub(super) fn gallery_item(f: &SmartFilter) -> Result { + let p = &f.params; + if let Some(k) = p.as_object().and_then(|o| o.keys().find(|k| !is_meta(k) && !["effects", "foreground", "background"].contains(&k.as_str()))) { + return Err(format!("setting `{k}` has no PSD equivalent")); + } + let list = p.get("effects").and_then(J::as_array).ok_or("it has no effects")?; + let mut out = Vec::with_capacity(list.len()); + for e in list { + let key = e.get("filter").and_then(J::as_str).ok_or("an effect has no `filter`")?; + let g = GALLERY_EFFECTS.iter().find(|g| g.key == key).ok_or_else(|| format!("gallery effect `{key}` has no PSD equivalent"))?; + let params = e.get("params").filter(|v| v.is_object()).unwrap_or(e); + if let Some(k) = params.as_object().and_then(|o| { + o.keys().find(|k| !is_meta(k) && !["filter", "params", "visible"].contains(&k.as_str()) && !g.settings.iter().any(|(_, ours)| ours == k)) + }) { + return Err(format!("gallery setting `{key}.{k}` has no PSD equivalent")); + } + let defaults = photocraft_algo::GalleryFilter::from_key(key).map(photocraft_algo::GalleryEffect::new); + let settings: Vec<(&str, Value)> = + g.settings.iter().map(|(psd, ours)| (*psd, pi(params, ours, defaults.as_ref().map_or(0.0, |x| f64::from(x.get(ours)))))).collect(); + out.push((g.code, settings, e.get("visible").and_then(J::as_bool).unwrap_or(true))); + } + let gallery = || { + let mut d = Descriptor::new(GALLERY_CLASS); + d.name = UnicodeString::new_nul("Filter Gallery"); + d + }; + // One visible effect: inline, as Photoshop writes it. Otherwise the effect list. + let fltr = match out.as_slice() { + [] => return Err("it has no effects".into()), + [(code, settings, true)] => settings.iter().fold(gallery().with("GEfk", enumv("GEft", code)), |d, (k, v)| d.with(k, v.clone())), + _ => { + let list = out + .into_iter() + .map(|(code, settings, visible)| { + let d = settings.into_iter().fold(gallery(), |d, (k, v)| d.with(k, v)); + Value::Descriptor(d.with("GEfk", enumv("GEft", code)).with("GELv", Value::Boolean(visible))) + }) + .collect(); + gallery().with("GEfs", Value::List(list)) + } + }; + Ok(Descriptor::new("filterFX") + .with("Nm ", Value::Text(UnicodeString::new_nul(GALLERY_NAME))) + .with("blendOptions", blend_options(f)) + .with("enab", Value::Boolean(f.visible)) + .with("hasoptions", Value::Boolean(true)) + .with("FrgC", colour_rgbc(p.get("foreground"), 0.0)?) + .with("BckC", colour_rgbc(p.get("background"), 255.0)?) + .with("Fltr", Value::Descriptor(fltr)) + .with("filterID", Value::Integer(code(b"GEfc")))) +} + +/// Lowercase hex of `bytes`. +pub(crate) fn to_hex(bytes: &[u8]) -> String { + const H: &[u8; 16] = b"0123456789abcdef"; + let mut s = String::with_capacity(bytes.len() * 2); + for b in bytes { + s.push(char::from(H[usize::from(b >> 4)])); + s.push(char::from(H[usize::from(b & 15)])); + } + s +} + +pub(crate) fn from_hex(s: &str) -> Option> { + let d = |c: u8| (c as char).to_digit(16).map(|v| v as u8); + let b = s.as_bytes(); + if !b.len().is_multiple_of(2) { + return None; + } + b.as_chunks::<2>().0.iter().map(|c| Some(d(c[0])? << 4 | d(c[1])?)).collect() +} + +/// One `filterFXList` item → [`SmartFilter`] (an [`UNSUPPORTED_FILTER`] when not modelled). +pub fn filter_from_item(item: &Descriptor) -> SmartFilter { + let opts = get_desc(item, "blendOptions"); + let opacity = opts.and_then(|o| px(o, "Opct")).map_or(1.0, |v| (v / 100.0).clamp(0.0, 1.0) as f32); + let blend = opts.and_then(|o| enum_of(o, "Md ")).and_then(crate::effects_map::blend_from_id).unwrap_or(BlendMode::Normal); + let visible = bool_or(item, "enab", true); + let fltr = get_desc(item, "Fltr"); + let class = fltr.map(|f| String::from_utf8_lossy(f.class_id.as_bytes()).into_owned()); + let filter_id = int(item, "filterID").unwrap_or(0); + let class = class.or_else(|| KNOWN.iter().find(|k| k.filter_id == filter_id).map(|k| k.class.to_string())); + let known = match class.as_deref() { + Some(camera_raw::CLASS) => camera_raw::import_params(item).map(|p| (camera_raw::COMMAND, p)), + Some(displace::CLASS) => displace::import_params(item).map(|p| (displace::COMMAND, p)), + Some(hue_sat::CLASS) => fltr.and_then(hue_sat::import_params).map(|p| (hue_sat::COMMAND, p)), + Some(perspective_warp::CLASS) => perspective_warp::import_params(item).map(|p| (perspective_warp::COMMAND, p)), + Some(GALLERY_CLASS) => fltr.and_then(|f| gallery_params(item, f)).map(|p| (GALLERY_COMMAND, p)), + Some(c @ ("Fbrs" | "Clds" | "DfrC")) => fltr.and_then(|f| coloured_params(c, item, f)), + // A `Fltr` that is there but not a descriptor is settings we can't read: kept verbatim + // rather than taken for a filter stored without options (which would drop it on save). + _ if fltr.is_none() && item.get("Fltr").is_some() => None, + c => c.and_then(|c| known_params(c, fltr, item)), + }; + let (command, params) = match known { + Some((c, p)) => (c.to_string(), p), + None => { + let name = text_of(item, "Nm ").unwrap_or_default(); + // The stored descriptor carries neutral blending (the model's own fields replace + // them on export), so hiding or re-blending the filter leaves its params alone. + let mut neutral = item.clone(); + for (k, v) in &mut neutral.items { + if k.is("blendOptions") { + *v = blend_options(&SmartFilter { command: String::new(), params: J::Null, blend: BlendMode::Normal, opacity: 1.0, visible: true }); + } else if k.is("enab") { + *v = Value::Boolean(true); + } + } + (UNSUPPORTED_FILTER.to_string(), json!({"name": name.replace('&', ""), "filterID": filter_id, "psd": to_hex(&neutral.to_bytes())})) + } + }; + SmartFilter { command, params, blend, opacity, visible } +} diff --git a/crates/io/src/smart_map/placed.rs b/crates/io/src/smart_map/placed.rs new file mode 100644 index 0000000000..9bdb52bc1c --- /dev/null +++ b/crates/io/src/smart_map/placed.rs @@ -0,0 +1,274 @@ +use super::export::{set, set_before, unit}; +use super::*; + +/// Everything needed to write the placed-layer blocks of a smart object. +#[derive(Clone, Debug)] +pub struct PlacedSpec<'a> { + pub idnt: &'a str, + pub placed: &'a str, + /// Source pixels → document pixels. + pub transform: Affine, + /// Distort / Perspective: the full projective map (row-major 3×3), overriding `transform`. + pub perspective: Option<[f64; 9]>, + /// Source size in pixels. + pub size: (f64, f64), + /// Source resolution. + pub dpi: f64, + pub warp: Option<&'a Warp>, + /// `filterFX`, when the smart object has filters. + pub filter_fx: Option, +} + +/// Where the frame corners land (top-left, top-right, bottom-right, bottom-left), as x, y pairs. +/// The frame is [`crate::blocks::placed_frame`] of `warp`, the warp the block stores, for an +/// affine placement (the inverse of `parse_smart`), [`crate::blocks::perspective_frame`] of it +/// for a projective one (as `parse_smart_perspective` reads it). +fn quad_points(s: &PlacedSpec<'_>, warp: Option<&Warp>) -> [f64; 8] { + let (w, h) = s.size; + let [a, b, c, d, e, f] = s.transform.m; + let map = |x: f64, y: f64| match &s.perspective { + Some(p) => photocraft_algo::transform::Homography(*p).apply(x, y), + None => (a * x + c * y + e, b * x + d * y + f), + }; + let [x0, y0, x1, y1] = if s.perspective.is_some() { crate::blocks::perspective_frame(warp, w, h) } else { crate::blocks::placed_frame(warp, w, h) }; + let mut out = [0.0; 8]; + for (i, (x, y)) in [(x0, y0), (x1, y0), (x1, y1), (x0, y1)].into_iter().enumerate() { + (out[2 * i], out[2 * i + 1]) = map(x, y); + } + out +} + +/// The transform quad: the source corners (top-left, top-right, bottom-right, bottom-left). +fn quad(s: &PlacedSpec<'_>, warp: Option<&Warp>) -> Value { + Value::List(quad_points(s, warp).into_iter().map(Value::Double).collect()) +} + +/// Has the placement moved from the quad a template descriptor stores (`Trnf`)? +pub(super) fn quad_moved(template: &Descriptor, s: &PlacedSpec<'_>, warp: Option<&Warp>) -> bool { + let Some(Value::List(pts)) = template.get("Trnf") else { return true }; + let old: Vec = pts.iter().filter_map(|v| crate::blocks::num(Some(v))).collect(); + let new = quad_points(s, warp); + old.len() != 8 || old.iter().zip(new).any(|(a, b)| (a - b).abs() > 1e-6 * (1.0 + a.abs())) +} + +pub(crate) fn enumv(t: &str, v: &str) -> Value { + Value::Enumerated { type_id: Id::new(t), value: Id::new(v) } +} + +/// The mesh of a split warp: a custom warp of more than one patch, which `SoLd` stores as +/// `quiltWarp` and `PlLd` can't store. +fn split_mesh(w: Option<&Warp>) -> Option<&BezierMesh> { + w.filter(|w| w.style == WarpStyle::Custom).and_then(|w| w.mesh.as_ref()).filter(|m| m.points.len() != 16 && m.is_valid()) +} + +/// The warp `SoLd` stores: none, with a message, for a split warp of more patches along a side +/// than a `quiltWarp` is read with, so its corners are framed by the source rect as on reopen. +fn sold_warp<'a>(w: Option<&'a Warp>, warnings: &mut Vec) -> Option<&'a Warp> { + let too_big = split_mesh(w).is_some_and(|m| m.us.len().max(m.vs.len()) > crate::blocks::QUILT_MAX_PATCHES + 1); + if too_big { + warnings.push(format!("a split warp of more than {} patches along a side was written to PSD without its warp", crate::blocks::QUILT_MAX_PATCHES)); + return None; + } + w +} + +/// Style, bend, distortions, axis, bounds and order: the keys a `warp` and a `quiltWarp` +/// descriptor share, in Photoshop's order. +fn warp_head(class: &str, w: &Warp) -> Descriptor { + let [x0, y0, x1, y1] = w.bounds; + let bounds = Descriptor::new("classFloatRect") + .with("Top ", Value::Double(y0)) + .with("Left", Value::Double(x0)) + .with("Btom", Value::Double(y1)) + .with("Rght", Value::Double(x1)); + let d = Descriptor::new(class).with("warpStyle", enumv("warpStyle", w.style.psd_name())).with("warpValue", Value::Double(w.bend)); + // A cylinder is stored as its seven `warpValues` (#4112). + let d = if w.style == WarpStyle::Cylinder { d.with("warpValues", Value::List(w.values.iter().copied().map(Value::Double).collect())) } else { d }; + d.with("warpPerspective", Value::Double(w.h_distort)) + .with("warpPerspectiveOther", Value::Double(w.v_distort)) + .with("warpRotate", enumv("Ornt", if w.vertical { "Vrtc" } else { "Hrzn" })) + .with("bounds", Value::Descriptor(bounds)) + .with("uOrder", Value::Integer(4)) + .with("vOrder", Value::Integer(4)) +} + +/// The control points of a custom warp: an object array of their x and y. +fn mesh_points(m: &BezierMesh) -> Value { + let body = Descriptor::new("rationalPoint") + .with("Hrzn", Value::UnitFloats { unit: *b"#Pxl", values: m.points.iter().map(|p| p[0]).collect() }) + .with("Vrtc", Value::UnitFloats { unit: *b"#Pxl", values: m.points.iter().map(|p| p[1]).collect() }); + Value::ObjectArray(ObjectArray { prefix: m.points.len() as u32, body }) +} + +/// The `warp` descriptor (also the `PlLd` warp). A split warp is written as no warp: `SoLd` +/// keeps it in `quiltWarp` ([`quilt_desc`]), next to this `warpNone`, as Photoshop does. A +/// custom warp without a usable mesh is written as no warp, with a message. A cylinder is +/// written as its seven `warpValues`. +pub(super) fn warp_desc(w: Option<&Warp>, size: (f64, f64), warnings: &mut Vec) -> Value { + let none = Warp::none([0.0, 0.0, size.0, size.1]); + let mut w = w.unwrap_or(&none).clone(); + let mesh = match (&w.style, &w.mesh) { + (WarpStyle::Custom, Some(m)) if m.points.len() == 16 => Some(m.clone()), + (WarpStyle::Custom, Some(m)) if m.is_valid() => { + w = none.clone(); + None + } + (WarpStyle::Custom, _) => { + warnings.push("a custom warp without a valid mesh was written to PSD without its warp".into()); + w = none.clone(); + None + } + _ => None, + }; + let mut d = warp_head("warp", &w); + if let Some(m) = mesh { + d = d.with("customEnvelopeWarp", Value::Descriptor(Descriptor::new("customEnvelopeWarp").with("meshPoints", mesh_points(&m)))); + } + Value::Descriptor(d) +} + +/// The `quiltWarp` descriptor of a split warp, in Photoshop's layout: `deformNumCols` × +/// `deformNumRows` control points, and the patch boundaries (`quiltSliceX` / `quiltSliceY`) at +/// the knots across the warp's box. The imported `quiltWarp` (`old`) gives its own slices where +/// they still bound the mesh's patches, so their units and padding stay Photoshop's. +fn quilt_desc(w: &Warp, mesh: &BezierMesh, old: Option<&Descriptor>) -> Value { + let old_env = old.and_then(|q| get_desc(q, "customEnvelopeWarp")); + let [x0, y0, x1, y1] = w.bounds; + let slices = |key: &str, knots: &[f64], lo: f64, hi: f64| { + if let Some(env) = old_env + && crate::blocks::quilt_knots(env, key, knots.len() - 1).as_deref() == Some(knots) + && let Some(v) = env.get(key) + { + return v.clone(); + } + let (lo, hi) = if (hi - lo).is_finite() && hi > lo { (lo, hi) } else { (0.0, 1.0) }; + let values: Vec = knots.iter().map(|u| lo + u * (hi - lo)).collect(); + let prefix = values.len() as u32; + Value::ObjectArray(ObjectArray { prefix, body: Descriptor::new("UntF").with(key, Value::UnitFloats { unit: *b"#Pxl", values }) }) + }; + let envelope = Descriptor::new("customEnvelopeWarp") + .with("quiltSliceX", slices("quiltSliceX", &mesh.us, x0, x1)) + .with("quiltSliceY", slices("quiltSliceY", &mesh.vs, y0, y1)) + .with("meshPoints", mesh_points(mesh)); + Value::Descriptor( + warp_head("quiltWarp", w) + .with("deformNumRows", Value::Integer(mesh.ny() as i32)) + .with("deformNumCols", Value::Integer(mesh.nx() as i32)) + .with("customEnvelopeWarp", Value::Descriptor(envelope)), + ) +} + +fn ratio(n: i32, d: i32) -> Value { + Value::Descriptor(Descriptor::new("null").with("numerator", Value::Integer(n)).with("denominator", Value::Integer(d))) +} + +fn pad4(mut v: Vec) -> Vec { + while !v.len().is_multiple_of(4) { + v.push(0); + } + v +} + +/// `SoLd` block data. With `template` (the imported descriptor) every key it has is kept and only +/// the placed id (for a duplicate), transform (when it moved), warp and filter stack are rewritten; +/// otherwise a fresh descriptor in Photoshop's key order. A split warp goes in `quiltWarp`. +pub fn sold_bytes(template: Option<&Descriptor>, s: &PlacedSpec<'_>, warnings: &mut Vec) -> Vec { + let stored = sold_warp(s.warp, warnings); + let warp = warp_desc(stored, s.size, warnings); + let split = stored.zip(split_mesh(stored)); + let d = match template { + Some(t) => { + let mut d = t.clone(); + if text_of(t, "placed").as_deref() != Some(s.placed) { + set(&mut d, "placed", Value::Text(UnicodeString::new_nul(s.placed))); + } + if quad_moved(t, s, stored) { + set(&mut d, "Trnf", quad(s, stored)); + set(&mut d, "nonAffineTransform", quad(s, stored)); + } + set(&mut d, "warp", warp); + // `quiltWarp` is read before `warp`, so the imported one stays only while it still + // says what the layer's warp is (unchanged, or unreadable while the layer has none); + // otherwise it is rewritten, or dropped for a warp that isn't split. + let old = get_desc(t, "quiltWarp"); + let kept = old.is_some_and(|q| match crate::blocks::warp_of(q) { + Some(w) => w.as_ref() == stored, + None => s.warp.is_none(), + }); + if !kept { + match split { + Some((w, m)) => set_before(&mut d, "quiltWarp", quilt_desc(w, m, old), "warp"), + None => d.items.retain(|(k, _)| !k.is("quiltWarp")), + } + } + match &s.filter_fx { + Some(fx) => set(&mut d, "filterFX", Value::Descriptor(fx.clone())), + None => d.items.retain(|(k, _)| !k.is("filterFX")), + } + d + } + None => { + let mut d = Descriptor::new("null") + .with("Idnt", Value::Text(UnicodeString::new_nul(s.idnt))) + .with("placed", Value::Text(UnicodeString::new_nul(s.placed))) + .with("PgNm", Value::Integer(1)) + .with("totalPages", Value::Integer(1)) + .with("Crop", Value::Integer(1)) + .with("frameStep", ratio(0, 600)) + .with("duration", ratio(0, 600)) + .with("frameCount", Value::Integer(1)) + .with("Annt", Value::Integer(16)) + .with("Type", Value::Integer(2)) + .with("Trnf", quad(s, stored)) + .with("nonAffineTransform", quad(s, stored)); + if let Some((w, m)) = split { + d = d.with("quiltWarp", quilt_desc(w, m, None)); + } + let mut d = d + .with("warp", warp) + .with("Sz ", Value::Descriptor(Descriptor::new("Pnt ").with("Wdth", Value::Double(s.size.0)).with("Hght", Value::Double(s.size.1)))) + .with("Rslt", unit(b"#Rsl", s.dpi)); + if let Some(fx) = &s.filter_fx { + d = d.with("filterFX", Value::Descriptor(fx.clone())); + } + d.with("comp", Value::Integer(-1)) + .with("compInfo", Value::Descriptor(Descriptor::new("null").with("compID", Value::Integer(-1)).with("originalCompID", Value::Integer(-1)))) + } + }; + let mut out = b"soLD".to_vec(); + out.extend_from_slice(&4u32.to_be_bytes()); + out.extend(VersionedDescriptor::new(d).to_bytes()); + pad4(out) +} + +/// `PlLd` block data (`plcL` version 3): the legacy placed-layer record Photoshop writes next to +/// `SoLd`. It has no split warp: it stores none, its corners framed by the source rect. +pub fn plld_bytes(s: &PlacedSpec<'_>, warnings: &mut Vec) -> Vec { + let warp = s.warp.filter(|_| split_mesh(s.warp).is_none()); + let mut out = b"plcL".to_vec(); + out.extend_from_slice(&3u32.to_be_bytes()); + let id = s.idnt.as_bytes(); + let n = id.len().min(255); + out.push(n as u8); + out.extend_from_slice(&id[..n]); + for v in [1i32, 1, 16, 2] { + out.extend_from_slice(&v.to_be_bytes()); + } + if let Value::List(q) = quad(s, warp) { + for v in q { + if let Value::Double(x) = v { + out.extend_from_slice(&x.to_be_bytes()); + } + } + } + out.extend_from_slice(&0u32.to_be_bytes()); + let Value::Descriptor(w) = warp_desc(warp, s.size, warnings) else { return pad4(out) }; + out.extend(VersionedDescriptor::new(w).to_bytes()); + pad4(out) +} + +/// The source size a `soLD` descriptor stores (`Sz `). +pub fn stored_size(d: &Descriptor) -> Option<(f64, f64)> { + let sz = get_desc(d, "Sz ")?; + Some((num(sz.get("Wdth"))?, num(sz.get("Hght"))?)).filter(|(w, h)| *w > 0.0 && *h > 0.0) +} diff --git a/crates/io/src/smart_map/tests.rs b/crates/io/src/smart_map/tests.rs new file mode 100644 index 0000000000..1bbd5bd094 --- /dev/null +++ b/crates/io/src/smart_map/tests.rs @@ -0,0 +1,2303 @@ +use super::*; + +fn count(hay: &[u8], needle: &[u8]) -> usize { + hay.windows(needle.len()).filter(|w| *w == needle).count() +} + +/// A freshly built placed layer writes `warp` (key and class) as a length-4 string, as +/// Photoshop does; the code form is a different key to Photoshop. +#[test] +fn fresh_placed_warp_is_a_string_id() { + let spec = + PlacedSpec { idnt: "id", placed: "id", transform: Affine::IDENTITY, perspective: None, size: (10.0, 10.0), dpi: 72.0, warp: None, filter_fx: None }; + let mut warnings = Vec::new(); + let sold = sold_bytes(None, &spec, &mut warnings); + let plld = plld_bytes(&spec, &mut warnings); + // `SoLd`: the `warp` key and the warp descriptor's class; `PlLd`: the descriptor's class. + for (bytes, n) in [(&sold, 2), (&plld, 1)] { + assert_eq!(count(bytes, b"\0\0\0\x04warp"), n); + assert_eq!(count(bytes, b"\0\0\0\0warp"), 0); + } + let d = sold_descriptor(&sold).unwrap(); + assert!(matches!(d.get("warp"), Some(Value::Descriptor(w)) if w.class_id == Id::Str(b"warp".to_vec()))); +} + +fn sf(command: &str, params: J) -> SmartFilter { + SmartFilter { command: command.into(), params, blend: BlendMode::Normal, opacity: 1.0, visible: true } +} + +#[test] +fn modelled_filters_round_trip() { + let filters = vec![ + sf("filter.blur.gaussianBlur", json!({"radius": 4.0})), + sf("filter.blur.boxBlur", json!({"radius": 5.0})), + sf("filter.blur.motionBlur", json!({"angle": -20, "distance": 10.0})), + sf("filter.blur.surfaceBlur", json!({"radius": 12.0, "threshold": 40})), + sf("filter.blur.smartBlur", json!({"radius": 5.0, "threshold": 25.0, "quality": "high", "mode": "normal"})), + sf("filter.blur.smartBlur", json!({"radius": 3.0, "threshold": 30.0, "quality": "medium", "mode": "overlayEdge"})), + sf("filter.blur.smartBlur", json!({"radius": 0.5, "threshold": 0.1, "quality": "low", "mode": "edgeOnly"})), + sf("filter.blur.radialBlur", json!({"amount": 10, "method": "spin", "quality": "draft"})), + sf("filter.blur.radialBlur", json!({"amount": 20, "method": "zoom", "quality": "good"})), + sf("filter.blur.radialBlur", json!({"amount": 100, "method": "spin", "quality": "best"})), + sf("filter.sharpen.unsharpMask", json!({"amount": 150.0, "radius": 2.0, "threshold": 0})), + sf("filter.noise.addNoise", json!({"amount": 12.0, "distribution": "uniform", "monochromatic": false, "seed": 1234})), + sf("filter.noise.median", json!({"radius": 3.0})), + sf("filter.other.highPass", json!({"radius": 3.0})), + sf("filter.other.maximum", json!({"radius": 2.0})), + sf("filter.other.minimum", json!({"radius": 2.0})), + sf("filter.pixelate.mosaic", json!({"cellSize": 8.0})), + sf("filter.pixelate.mezzotint", json!({"type": "mediumStrokes"})), + sf("filter.pixelate.colorHalftone", json!({"maxRadius": 6, "channel1": 10, "channel2": 20, "channel3": 30, "channel4": 40})), + sf("filter.stylize.emboss", json!({"angle": 135, "height": 3, "amount": 100})), + sf("filter.sharpen.smartSharpen", json!({"amount": 120.0, "radius": 2.5, "reduceNoise": 5.0})), + sf("filter.noise.dustAndScratches", json!({"radius": 4, "threshold": 20})), + sf("filter.stylize.diffuse", json!({"mode": "normal"})), + sf("filter.stylize.diffuse", json!({"mode": "darkenOnly"})), + sf("filter.stylize.diffuse", json!({"mode": "lightenOnly"})), + sf("filter.stylize.diffuse", json!({"mode": "anisotropic"})), + sf("filter.stylize.traceContour", json!({"level": 60, "edge": "lower"})), + sf("filter.stylize.traceContour", json!({"level": 128, "edge": "upper"})), + sf("filter.stylize.traceContour", json!({"level": 0, "edge": "upper"})), + sf("filter.stylize.traceContour", json!({"level": 255, "edge": "lower"})), + sf("filter.pixelate.crystallize", json!({"cellSize": 10})), + sf("filter.pixelate.crystallize", json!({"cellSize": 3})), + sf("filter.pixelate.crystallize", json!({"cellSize": 300})), + sf("filter.pixelate.pointillize", json!({"cellSize": 7, "background": [1.0, 1.0, 1.0, 1.0]})), + sf("filter.pixelate.pointillize", json!({"cellSize": 300, "background": [0.0, 0.5, 1.0, 1.0]})), + sf("filter.other.offset", json!({"horizontal": 12, "vertical": -7, "undefinedAreas": "transparent"})), + sf("filter.other.custom", json!({"kernel": SHARPEN, "scale": 1, "offset": 0})), + sf("image.adjustments.levels", json!({"inBlack": 20, "inWhite": 220, "gamma": 1.4, "red": {"inBlack": 0, "inWhite": 255, "gamma": 0.8}})), + sf("image.adjustments.curves", json!({"points": [[0.0, 0.0], [64.0, 40.0], [255.0, 255.0]], "blue": [[0.0, 20.0], [255.0, 235.0]]})), + sf("image.adjustments.shadowsHighlights", json!({})), + sf("filter.sharpen.sharpen", json!({})), + // Photoshop stores Dust & Scratches' radius in whole pixels (a `long`). + sf("filter.noise.dustAndScratches", json!({"radius": 4, "threshold": 12})), + sf( + "image.adjustments.hueSaturation", + json!({"colorize": false, "hue": 10, "saturation": -20, "lightness": 5, "reds": {"hue": 5, "saturation": 0, "lightness": -3, "range": [315, 345, 15, 45]}}), + ), + // A pencil-drawn curve: 256 output levels (`Mpng`). + sf("image.adjustments.curves", json!({"pencil": true, "points": (0..256).rev().collect::>()})), + sf("filter.distort.pinch", json!({"amount": -28})), + sf("filter.distort.polarCoordinates", json!({"mode": "rectangularToPolar"})), + sf("filter.distort.ripple", json!({"amount": 250, "size": "small"})), + sf("filter.distort.spherize", json!({"amount": 60, "mode": "verticalOnly"})), + sf("filter.distort.twirl", json!({"angle": -355})), + sf( + "filter.distort.wave", + json!({"type": "square", "generators": 3, "wavelengthMin": 20, "wavelengthMax": 90, "amplitudeMin": 4, "amplitudeMax": 30, + "undefinedAreas": "repeat", "seed": 4_000_000_000u32}), + ), + sf("filter.distort.zigZag", json!({"amount": 30, "ridges": 7, "style": "aroundCenter"})), + sf("image.adjustments.invert", json!({})), + ]; + for mut f in filters.into_iter().chain(wind_extrude_tiles_settings()) { + f.blend = BlendMode::Overlay; + f.opacity = 0.75; + f.visible = false; + let d = item_for_filter(&f).unwrap(); + let bytes = d.to_bytes(); + let back = filter_from_item(&Descriptor::from_bytes(&bytes).unwrap()); + assert_eq!(back, f, "{}", f.command); + } +} + +/// The filters without options, their measured `filterID`s (as Photoshop wrote them). +const MEASURED_NO_OPTIONS: [(&str, i32); 11] = [ + ("filter.blur.blur", 1114403360), + ("filter.blur.blurMore", 1114403405), + ("filter.blur.average", 1098281575), + ("filter.noise.despeckle", 1148416099), + ("filter.stylize.findEdges", 1181639749), + ("filter.pixelate.facet", 1180922912), + ("filter.pixelate.fragment", 1181902701), + ("filter.sharpen.sharpen", 1399353968), + ("filter.sharpen.sharpenMore", 1399353933), + ("filter.sharpen.sharpenEdges", 1399353925), + ("filter.stylize.solarize", 1399616122), +]; + +/// A filter without options as Photoshop saves it: `hasoptions` false, no `Fltr`, a localized +/// name and the current colours. +fn photoshop_no_options_item(name: &str, filter_id: Value) -> Descriptor { + let rgb = |r: f64, g: f64, b: f64| { + Value::Descriptor(Descriptor::new("RGBC").with("Rd ", Value::Double(r)).with("Grn ", Value::Double(g)).with("Bl ", Value::Double(b))) + }; + Descriptor::new("filterFX") + .with("Nm ", Value::Text(UnicodeString::new_nul(name))) + .with("blendOptions", Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", 60.0)).with("Md ", enumv("BlnM", "Mltp")))) + .with("enab", Value::Boolean(false)) + .with("hasoptions", Value::Boolean(false)) + .with("FrgC", rgb(167.0, 157.0, 147.0)) + .with("BckC", rgb(255.0, 255.0, 255.0)) + .with("filterID", filter_id) +} + +#[test] +fn filters_without_options_round_trip_in_the_measured_shape() { + let keys = ["Nm ", "blendOptions", "enab", "hasoptions", "FrgC", "BckC", "filterID"]; + for (command, id) in MEASURED_NO_OPTIONS { + let mut f = sf(command, json!({})); + f.blend = BlendMode::Overlay; + f.opacity = 0.75; + f.visible = false; + let d = item_for_filter(&f).unwrap(); + let got: Vec = d.items.iter().map(|(k, _)| String::from_utf8_lossy(k.as_bytes()).into_owned()).collect(); + assert_eq!(got, keys, "{command}"); + assert_eq!(d.get("hasoptions"), Some(&Value::Boolean(false)), "{command}"); + assert_eq!(d.get("filterID"), Some(&Value::Integer(id)), "{command}"); + let back = filter_from_item(&Descriptor::from_bytes(&d.to_bytes()).unwrap()); + assert_eq!(back, f, "{command}"); + // Keys an old record may carry have no effect on these filters: still written. + let extra = item_for_filter(&sf(command, json!({"radius": 3.0, "layer": "L"}))).unwrap(); + assert_eq!(extra.get("filterID"), Some(&Value::Integer(id)), "{command}"); + for p in [json!(null), json!("x"), json!([1, 2])] { + assert!(item_for_filter(&sf(command, p)).is_ok(), "{command}"); + } + } +} + +#[test] +fn photoshop_filters_without_options_open_editable() { + for (command, id) in MEASURED_NO_OPTIONS { + let item = photoshop_no_options_item("Weichzeichnen", Value::Integer(id)); + let f = filter_from_item(&Descriptor::from_bytes(&item.to_bytes()).unwrap()); + assert_eq!(f.command, command); + assert_eq!(f.params, json!({})); + assert_eq!((f.visible, f.blend), (false, BlendMode::Multiply)); + assert!((f.opacity - 0.6).abs() < 1e-6); + } +} + +#[test] +fn malformed_filters_without_options_are_kept_verbatim() { + let blur = code(b"Blr "); + let cases = [ + // An id no filter has, a missing id, ids of the wrong type. + photoshop_no_options_item("X", Value::Integer(code(b"Zzzz"))), + Descriptor::new("filterFX").with("hasoptions", Value::Boolean(false)), + photoshop_no_options_item("X", Value::Double(f64::from(blur))), + photoshop_no_options_item("X", Value::Double(f64::NAN)), + photoshop_no_options_item("X", Value::Text(UnicodeString::new_nul("Blr "))), + photoshop_no_options_item("X", Value::Integer(-1)), + // Settings we don't know of on a filter that has none. + photoshop_no_options_item("X", Value::Integer(blur)).with("Fltr", Value::Descriptor(Descriptor::new("Blr ").with("Amnt", Value::Integer(5)))), + // Settings that aren't a descriptor, on a filter that has none. + photoshop_no_options_item("X", Value::Integer(blur)).with("Fltr", Value::Integer(5)), + photoshop_no_options_item("X", Value::Integer(blur)).with("Fltr", Value::Text(UnicodeString::new_nul("Blr "))), + photoshop_no_options_item("X", Value::Integer(781)).with("Fltr", Value::Integer(5)), + ]; + for item in cases { + let f = filter_from_item(&item); + assert_eq!(f.command, UNSUPPORTED_FILTER, "{item:?}"); + // Written back (a bare item gains blending and visibility) and still not editable. + let written = item_for_filter(&f).unwrap(); + assert_eq!(written.get("Fltr"), item.get("Fltr"), "{item:?}"); + let back = filter_from_item(&written); + assert_eq!((back.command.as_str(), &back.params["filterID"]), (UNSUPPORTED_FILTER, &f.params["filterID"])); + } +} + +/// Smart Sharpen's `Fltr` in the measured shape (no `presetKind`, no `Angl`). +fn smart_sharpen(amount: f64, radius: f64, noise: f64, blur: &str) -> Descriptor { + Descriptor::new("smartSharpen") + .with("useLegacy", Value::Boolean(false)) + .with("Amnt", unit(b"#Prc", amount)) + .with("Rds ", unit(b"#Pxl", radius)) + .with("noiseReduction", unit(b"#Prc", noise)) + .with("blur", enumv("blurType", blur)) +} + +fn dust(radius: i32, threshold: i32) -> Descriptor { + Descriptor::new("DstS").with("Rds ", Value::Integer(radius)).with("Thsh", Value::Integer(threshold)) +} + +/// The `Fltr` descriptor PhotoCraft writes for `f`, after a byte round trip. +fn written_fltr(f: &SmartFilter) -> Descriptor { + let d = Descriptor::from_bytes(&item_for_filter(f).unwrap().to_bytes()).unwrap(); + get_desc(&d, "Fltr").unwrap().clone() +} + +/// Measured in Photoshop: Smart Sharpen 120 %, 2.5 px, noise 5 %, Gaussian Blur +/// (filterID 1131); the default entry adds `presetKind` first, which is not kept. +#[test] +fn smart_sharpen_photoshop_entry_opens_and_writes_back() { + let fltr = smart_sharpen(120.0, 2.5, 5.0, "GsnB"); + let item = ps_item("Smart Sharpen...", fltr.clone(), 1131); + let f = filter_from_item(&Descriptor::from_bytes(&item.to_bytes()).unwrap()); + assert_eq!(f.command, "filter.sharpen.smartSharpen"); + assert_eq!(f.params, json!({"amount": 120.0, "radius": 2.5, "reduceNoise": 5.0})); + assert_eq!(written_fltr(&f), fltr); + let d = item_for_filter(&f).unwrap(); + assert_eq!(int(&d, "filterID"), Some(1131)); + assert_eq!(get_desc(&d, "Fltr").unwrap().class_id, Id::Str(b"smartSharpen".to_vec())); + // The four-character keys and enum values are codes, as Photoshop writes them. + let bytes = d.to_bytes(); + assert_eq!(count(&bytes, b"\0\0\0\0blurenum\0\0\0\x08blurType\0\0\0\0GsnB"), 1); + assert_eq!(count(&bytes, b"\0\0\0\0Rds UntF#Pxl"), 1); + + // With `presetKind` (any value): opens, but the params hold only the engine's own keys + // (it rejects unknown ones), and a re-save leaves it out as Photoshop does for explicit + // values. + for kind in ["presetKindDefault", "presetKindCustom", "Xxxx"] { + let mut with_preset = Descriptor::new("smartSharpen").with("presetKind", enumv("presetKindType", kind)); + with_preset.items.extend(smart_sharpen(200.0, 1.0, 10.0, "GsnB").items); + let f = filter_from_item(&Descriptor::from_bytes(&ps_item("Smart Sharpen...", with_preset, 1131).to_bytes()).unwrap()); + assert_eq!(f.command, "filter.sharpen.smartSharpen"); + let keys: Vec<&str> = f.params.as_object().unwrap().keys().map(String::as_str).collect(); + assert_eq!(keys.len(), 3, "{keys:?}"); + assert!(keys.iter().all(|k| ["amount", "radius", "reduceNoise"].contains(k)), "{keys:?}"); + assert_eq!(f.params, json!({"amount": 200.0, "radius": 1.0, "reduceNoise": 10.0})); + assert_eq!(written_fltr(&f), smart_sharpen(200.0, 1.0, 10.0, "GsnB")); + } + + // Without options PhotoCraft writes the engine's defaults, Gaussian Blur. + assert_eq!(written_fltr(&sf("filter.sharpen.smartSharpen", json!({}))), smart_sharpen(100.0, 1.0, 10.0, "GsnB")); +} + +/// Lens Blur (Photoshop's default), Motion Blur and legacy mode render differently from +/// PhotoCraft's Smart Sharpen, so those entries stay verbatim. +#[test] +fn smart_sharpen_settings_we_dont_render_stay_verbatim() { + let mut default_entry = Descriptor::new("smartSharpen").with("presetKind", enumv("presetKindType", "presetKindDefault")); + default_entry.items.extend(smart_sharpen(200.0, 1.0, 10.0, "lensBlur").items); + let motion = smart_sharpen(80.0, 1.5, 0.0, "MtnB").with("Angl", Value::Integer(30)); + let mut legacy = smart_sharpen(100.0, 1.0, 10.0, "GsnB"); + set(&mut legacy, "useLegacy", Value::Boolean(true)); + for fltr in [default_entry, motion, legacy] { + let item = ps_item("Smart Sharpen...", fltr, 1131); + let f = filter_from_item(&item); + assert_eq!(f.command, UNSUPPORTED_FILTER); + assert_eq!(f.params["filterID"], 1131); + assert_eq!(item_for_filter(&f).unwrap(), item); + } +} + +#[test] +fn malformed_smart_sharpen_is_kept_verbatim() { + let g = || smart_sharpen(100.0, 1.0, 10.0, "GsnB"); + let without = |key: &str| { + let mut d = g(); + d.items.retain(|(k, _)| !k.is(key)); + d + }; + let with = |key: &str, v: Value| { + let mut d = g(); + set(&mut d, key, v); + d + }; + let cases = vec![ + without("useLegacy"), + without("Amnt"), + without("Rds "), + without("noiseReduction"), + without("blur"), + with("Amnt", Value::Double(100.0)), + with("Amnt", unit(b"#Pxl", 100.0)), + with("Rds ", Value::Integer(1)), + with("useLegacy", Value::Integer(0)), + with("Amnt", unit(b"#Prc", 0.0)), + with("Amnt", unit(b"#Prc", 501.0)), + with("Rds ", unit(b"#Pxl", 0.05)), + with("Rds ", unit(b"#Pxl", 65.0)), + with("Rds ", unit(b"#Pxl", f64::NAN)), + with("noiseReduction", unit(b"#Prc", -1.0)), + with("noiseReduction", unit(b"#Prc", f64::INFINITY)), + with("blur", enumv("blurType", "Xxxx")), + with("blur", enumv("BlrM", "GsnB")), + with("blur", Value::Integer(0)), + with("presetKind", Value::Integer(1)), + g().with("Angl", Value::Integer(30)), + g().with("shadowMode", Value::Descriptor(Descriptor::new("adaptCorrectTones"))), + ]; + for fltr in cases { + let item = ps_item("Smart Sharpen...", fltr, 1131); + let f = filter_from_item(&Descriptor::from_bytes(&item.to_bytes()).unwrap()); + assert_eq!(f.command, UNSUPPORTED_FILTER, "{:?}", get_desc(&item, "Fltr")); + assert_eq!(item_for_filter(&f).unwrap().to_bytes(), item.to_bytes()); + } + // No `Fltr` at all (hasoptions false). + let bare = Descriptor::new("filterFX").with("filterID", Value::Integer(1131)); + assert_eq!(filter_from_item(&bare).command, UNSUPPORTED_FILTER); +} + +/// Measured in Photoshop: Dust & Scratches at its defaults (1, 0) and at 4, 20 (filterID +/// `DstS`, 1148417107; both settings `long`). +#[test] +fn dust_and_scratches_photoshop_entry_opens_and_writes_back() { + for (radius, threshold) in [(1, 0), (4, 20), (500, 255)] { + let fltr = dust(radius, threshold); + let item = ps_item("Dust & Scratches...", fltr.clone(), 1_148_417_107); + let f = filter_from_item(&Descriptor::from_bytes(&item.to_bytes()).unwrap()); + assert_eq!(f.command, "filter.noise.dustAndScratches"); + assert_eq!(f.params, json!({"radius": radius, "threshold": threshold})); + assert_eq!(written_fltr(&f), fltr); + assert_eq!(int(&item_for_filter(&f).unwrap(), "filterID"), Some(1_148_417_107)); + } + // No `Fltr` (hasoptions false): kept verbatim. + let bare = Descriptor::new("filterFX").with("filterID", Value::Integer(code(b"DstS"))); + assert_eq!(filter_from_item(&bare).command, UNSUPPORTED_FILTER); +} + +#[test] +fn malformed_dust_and_scratches_is_kept_verbatim() { + let cases = vec![ + Descriptor::new("DstS").with("Thsh", Value::Integer(0)), + Descriptor::new("DstS").with("Rds ", Value::Integer(1)), + Descriptor::new("DstS").with("Rds ", Value::Double(1.0)).with("Thsh", Value::Integer(0)), + Descriptor::new("DstS").with("Rds ", unit(b"#Pxl", 1.0)).with("Thsh", Value::Integer(0)), + Descriptor::new("DstS").with("Rds ", Value::Integer(1)).with("Thsh", Value::Boolean(false)), + dust(0, 0), + dust(501, 0), + dust(1, -1), + dust(1, 256), + dust(i32::MIN, i32::MAX), + dust(1, 0).with("Xtra", Value::Integer(1)), + ]; + for fltr in cases { + let item = ps_item("Dust & Scratches...", fltr, code(b"DstS")); + let f = filter_from_item(&item); + assert_eq!(f.command, UNSUPPORTED_FILTER, "{:?}", get_desc(&item, "Fltr")); + assert_eq!(item_for_filter(&f).unwrap(), item); + } +} + +/// Every option's range ends round trip; hostile params are written in range (the engine +/// clamps the same way), never a panic. +#[test] +fn smart_sharpen_and_dust_option_values_round_trip() { + let mut cases = Vec::new(); + for amount in [1.0, 100.0, 500.0] { + for radius in [0.1, 1.0, 64.0] { + for noise in [0.0, 10.0, 100.0] { + cases.push(sf("filter.sharpen.smartSharpen", json!({"amount": amount, "radius": radius, "reduceNoise": noise}))); + } + } + } + for radius in [1, 2, 100, 500] { + for threshold in [0, 1, 128, 255] { + cases.push(sf("filter.noise.dustAndScratches", json!({"radius": radius, "threshold": threshold}))); + } + } + for f in cases { + let back = filter_from_item(&Descriptor::from_bytes(&item_for_filter(&f).unwrap().to_bytes()).unwrap()); + assert_eq!(back, f); + } + let defaults = json!({"amount": 100.0, "radius": 1.0, "reduceNoise": 10.0}); + for (command, p, want) in [ + ( + "filter.sharpen.smartSharpen", + json!({"amount": 1e9, "radius": -5.0, "reduceNoise": "x"}), + json!({"amount": 500.0, "radius": 0.1, "reduceNoise": 10.0}), + ), + ("filter.sharpen.smartSharpen", json!({"presetKind": "presetKindDefault", "amount": null}), defaults.clone()), + ("filter.sharpen.smartSharpen", json!(null), defaults.clone()), + ("filter.noise.dustAndScratches", json!({"radius": 2.4, "threshold": 1e12}), json!({"radius": 2, "threshold": 255})), + ("filter.noise.dustAndScratches", json!({"radius": -3, "threshold": -3}), json!({"radius": 1, "threshold": 0})), + ("filter.noise.dustAndScratches", json!([]), json!({"radius": 1, "threshold": 0})), + ] { + let back = filter_from_item(&item_for_filter(&sf(command, p.clone())).unwrap()); + assert_eq!((back.command.as_str(), &back.params), (command, &want), "{p}"); + } +} + +/// Every option value of Wind, Extrude and Tiles (and the ends of their ranges). +fn wind_extrude_tiles_settings() -> Vec { + let mut v = Vec::new(); + for method in ["wind", "blast", "stagger"] { + for direction in ["fromRight", "fromLeft"] { + v.push(sf("filter.stylize.wind", json!({"method": method, "direction": direction}))); + } + } + for t in ["blocks", "pyramids"] { + for mode in ["random", "levelBased"] { + for (solid, mask) in [(false, false), (true, false), (false, true), (true, true)] { + v.push(sf( + "filter.stylize.extrude", + json!({"type": t, "size": 7, "depth": 9, "depthMode": mode, "solidFrontFaces": solid, "maskIncompleteBlocks": mask}), + )); + } + } + } + v.push(sf( + "filter.stylize.extrude", + json!({"type": "blocks", "size": 2, "depth": 1, "depthMode": "random", "solidFrontFaces": false, "maskIncompleteBlocks": false}), + )); + v.push(sf( + "filter.stylize.extrude", + json!({"type": "pyramids", "size": 255, "depth": 255, "depthMode": "levelBased", "solidFrontFaces": true, "maskIncompleteBlocks": true}), + )); + for fill in ["background", "foreground", "inverse", "unaltered"] { + v.push(sf( + "filter.stylize.tiles", + json!({"count": 6, "maxOffset": 20, "fill": fill, "foreground": [1.0, 0.0, 0.5, 1.0], "background": [0.0, 0.5, 1.0, 1.0]}), + )); + } + for (count, offset) in [(1, 1), (99, 99)] { + v.push(sf( + "filter.stylize.tiles", + json!({"count": count, "maxOffset": offset, "fill": "background", "foreground": [0.0, 0.0, 0.0, 1.0], "background": [1.0, 1.0, 1.0, 1.0]}), + )); + } + v +} + +/// A `filterFX` entry shaped as Photoshop saves Wind, Extrude and Tiles (measured in Photoshop: +/// applied through Action Manager to a smart object, saved, `filterFX` read back): the item's +/// `FrgC`/`BckC` are the document colours, `Fltr` holds the settings, `filterID` the class code. +fn measured_item(fltr: Descriptor, fg: f64, bg: f64) -> Descriptor { + let id = code(fltr.class_id.as_bytes().try_into().unwrap()); + Descriptor::new("filterFX") + .with("Nm ", Value::Text(UnicodeString::new_nul("Filter..."))) + .with("blendOptions", blend_options(&sf("", J::Null))) + .with("enab", Value::Boolean(true)) + .with("hasoptions", Value::Boolean(true)) + .with("FrgC", rgbc(fg)) + .with("BckC", rgbc(bg)) + .with("Fltr", Value::Descriptor(fltr)) + .with("filterID", Value::Integer(id)) +} + +/// The `Fltr` descriptors Photoshop 27 wrote for these filters (one smart object each, saved as +/// PSD and read back), with the settings PhotoCraft reads from them. +const PHOTOSHOP_FLTR: [(&str, &str, &str); 6] = [ + ("filter.distort.pinch", r#"{"amount":-28}"#, "0000000600500069006e00630068000000000000506e63680000000100000000416d6e746c6f6e67ffffffe4"), + ("filter.distort.twirl", r#"{"angle":-355}"#, "000000060054007700690072006c0000000000005477726c0000000100000000416e676c6c6f6e67fffffe9d"), + ( + "filter.distort.ripple", + r#"{"amount":-273,"size":"large"}"#, + "000000070052006900700070006c006500000000000052706c650000000200000000416d6e746c6f6e67fffffeef0000000052706c53656e756d0000000052706c53000000004c726720", + ), + ( + "filter.distort.spherize", + r#"{"amount":-1,"mode":"horizontalOnly"}"#, + "00000009005300700068006500720069007a0065000000000000537068720000000200000000416d6e746c6f6e67ffffffff000000005370684d656e756d000000005370684d0000000048727a4f", + ), + ( + "filter.distort.polarCoordinates", + r#"{"mode":"polarToRectangular"}"#, + "000000120050006f006c0061007200200043006f006f007200640069006e0061007400650073000000000000506c72200000000100000000436e7672656e756d00000000436e767200000000506c7252", + ), + ( + "filter.distort.zigZag", + r#"{"amount":-42,"ridges":11,"style":"pondRipples"}"#, + "00000007005a00690067005a006100670000000000005a675a670000000300000000416d6e746c6f6e67ffffffd6000000004e6d62526c6f6e670000000b000000005a5a5479656e756d000000005a5a547900000000506e6452", + ), +]; + +/// Photoshop's Wave with Scale 100% / 28%: PhotoCraft's Wave has no Scale. +const PHOTOSHOP_WAVE: &str = "000000050057006100760065000000000000576176650000000a0000000057767470656e756d00000000577674700000000057765472000000004e6d62476c6f6e670000014c00000000574c4d6e6c6f6e67000000d500000000574c4d786c6f6e67000000d600000000416d4d6e6c6f6e67000000f000000000416d4d786c6f6e67000000f10000000053636c486c6f6e67000000640000000053636c566c6f6e670000001c00000000556e6441656e756d00000000556e6441000000005772704100000000526e64536c6f6e670013624a"; + +/// A `filterFX` list item as Photoshop writes it (enabled, Normal at 100%, with options), wrapping the `Fltr` descriptor `fltr`. +fn photoshop_fltr_item(fltr: Descriptor) -> Descriptor { + let id = code(fltr.class_id.as_bytes().try_into().unwrap()); + Descriptor::new("filterFX") + .with("Nm ", Value::Text(UnicodeString::new_nul("from Photoshop"))) + .with("blendOptions", Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", 100.0)).with("Md ", enumv("BlnM", "normal")))) + .with("enab", Value::Boolean(true)) + .with("hasoptions", Value::Boolean(true)) + .with("Fltr", Value::Descriptor(fltr)) + .with("filterID", Value::Integer(id)) +} + +fn wind(method: &str, direction: &str) -> Descriptor { + Descriptor::new("Wnd ").with("WndM", enumv("WndM", method)).with("Drct", enumv("Drct", direction)) +} + +fn extrude(t: &str, size: Value, depth: Value, mode: &str, solid: Value, mask: Value) -> Descriptor { + Descriptor::new("Extr") + .with("ExtT", enumv("ExtT", t)) + .with("ExtS", size) + .with("ExtD", depth) + .with("ExtR", enumv("ExtR", mode)) + .with("ExtF", solid) + .with("ExtM", mask) +} + +fn tiles(count: Value, offset: Value, fill: &str) -> Descriptor { + Descriptor::new("Tls ").with("TlNm", count).with("TlOf", offset).with("FlCl", enumv("FlCl", fill)) +} + +#[test] +fn wind_extrude_tiles_open_from_photoshop_shapes() { + let (long, yes, no) = (Value::Integer, Value::Boolean(true), Value::Boolean(false)); + let cases = [ + // The measured files. + (wind("Blst", "Left"), "filter.stylize.wind", json!({"method": "blast", "direction": "fromRight"})), + (wind("Stgr", "Rght"), "filter.stylize.wind", json!({"method": "stagger", "direction": "fromLeft"})), + (wind("Wnd ", "Rght"), "filter.stylize.wind", json!({"method": "wind", "direction": "fromLeft"})), + ( + extrude("Blks", long(7), long(9), "Rndm", yes.clone(), no.clone()), + "filter.stylize.extrude", + json!({"type": "blocks", "size": 7, "depth": 9, "depthMode": "random", "solidFrontFaces": true, "maskIncompleteBlocks": false}), + ), + ( + extrude("Pyrm", long(12), long(20), "LvlB", no, yes), + "filter.stylize.extrude", + json!({"type": "pyramids", "size": 12, "depth": 20, "depthMode": "levelBased", "solidFrontFaces": false, "maskIncompleteBlocks": true}), + ), + ( + tiles(long(6), long(20), "FlFr"), + "filter.stylize.tiles", + json!({"count": 6, "maxOffset": 20, "fill": "foreground", "foreground": [0.2, 0.2, 0.2, 1.0], "background": [1.0, 1.0, 1.0, 1.0]}), + ), + ( + tiles(long(4), long(5), "FlIn"), + "filter.stylize.tiles", + json!({"count": 4, "maxOffset": 5, "fill": "inverse", "foreground": [0.2, 0.2, 0.2, 1.0], "background": [1.0, 1.0, 1.0, 1.0]}), + ), + ( + tiles(long(10), long(10), "FlBc"), + "filter.stylize.tiles", + json!({"count": 10, "maxOffset": 10, "fill": "background", "foreground": [0.2, 0.2, 0.2, 1.0], "background": [1.0, 1.0, 1.0, 1.0]}), + ), + ( + tiles(long(99), long(1), "FlSm"), + "filter.stylize.tiles", + json!({"count": 99, "maxOffset": 1, "fill": "unaltered", "foreground": [0.2, 0.2, 0.2, 1.0], "background": [1.0, 1.0, 1.0, 1.0]}), + ), + ]; + for (fltr, command, params) in cases { + let item = measured_item(fltr, 51.0, 255.0); + // Through bytes, as read from a file. + let f = filter_from_item(&Descriptor::from_bytes(&item.to_bytes()).unwrap()); + assert_eq!((f.command.as_str(), &f.params), (command, ¶ms)); + // Written back in the measured shape: same class, keys and their order, value types + // (long, bool, enum with its type), filterID; Tiles also its colours. + let back = item_for_filter(&f).unwrap(); + assert_eq!(get_desc(&back, "Fltr").map(Descriptor::to_bytes), get_desc(&item, "Fltr").map(Descriptor::to_bytes), "{command}"); + assert_eq!(back.get("filterID"), item.get("filterID"), "{command}"); + if command == "filter.stylize.tiles" { + assert_eq!((back.get("FrgC"), back.get("BckC")), (item.get("FrgC"), item.get("BckC"))); + } + } + // The class codes: numeric filterIDs of the four-char classes. + for (c, id) in [("filter.stylize.wind", 1466852384), ("filter.stylize.extrude", 1165522034), ("filter.stylize.tiles", 1416393504)] { + assert_eq!(item_for_filter(&sf(c, json!({}))).unwrap().get("filterID"), Some(&Value::Integer(id))); + } + // A filter found by its filterID alone (no `Fltr` class to go by) still needs its settings. + let bare = Descriptor::new("filterFX").with("hasoptions", Value::Boolean(false)).with("filterID", Value::Integer(1466852384)); + assert_eq!(filter_from_item(&bare).command, UNSUPPORTED_FILTER); + // Only Tiles reads the entry's colours; Wind and Extrude write the defaults. + let f = filter_from_item(&measured_item(wind("Wnd ", "Left"), 51.0, 0.0)); + assert_eq!(f.params, json!({"method": "wind", "direction": "fromRight"})); + let back = item_for_filter(&f).unwrap(); + assert_eq!((back.get("FrgC"), back.get("BckC")), (Some(&rgbc(0.0)), Some(&rgbc(255.0)))); + // Tiles without colours in its params (or the entry) writes the engine's black and white. + let f = filter_from_item(&Descriptor::new("filterFX").with("Fltr", Value::Descriptor(tiles(long(4), long(5), "FlBc")))); + assert_eq!(f.params, json!({"count": 4, "maxOffset": 5, "fill": "background"})); + let back = item_for_filter(&f).unwrap(); + assert_eq!((back.get("FrgC"), back.get("BckC")), (Some(&rgbc(0.0)), Some(&rgbc(255.0)))); +} + +#[test] +fn wind_extrude_tiles_write_defaults_and_photoshop_ranges() { + let fltr = |c: &str, p: J| match item_for_filter(&sf(c, p)).unwrap().get("Fltr") { + Some(Value::Descriptor(d)) => d.clone(), + other => panic!("no Fltr: {other:?}"), + }; + let long = Value::Integer; + let (yes, no) = (Value::Boolean(true), Value::Boolean(false)); + // Defaults are the engine's; our random seed has no PSD key and is not written. + assert_eq!(fltr("filter.stylize.wind", json!({"seed": 9})), wind("Wnd ", "Left")); + assert_eq!(fltr("filter.stylize.extrude", json!({"seed": 9})), extrude("Blks", long(30), long(30), "Rndm", no.clone(), no.clone())); + assert_eq!(fltr("filter.stylize.tiles", json!({"seed": 9})), tiles(long(10), long(10), "FlBc")); + // Out of range, fractional, non-numeric and non-bool values as the engine reads them. + assert_eq!( + fltr("filter.stylize.extrude", json!({"size": 1e12, "depth": -5, "solidFrontFaces": "yes", "maskIncompleteBlocks": true})), + extrude("Blks", long(255), long(1), "Rndm", no.clone(), yes) + ); + assert_eq!(fltr("filter.stylize.tiles", json!({"count": 0, "maxOffset": 12.6})), tiles(long(1), long(13), "FlBc")); + assert_eq!(fltr("filter.stylize.tiles", json!({"count": "many", "maxOffset": 1000})), tiles(long(10), long(99), "FlBc")); + assert_eq!(fltr("filter.stylize.extrude", json!({"size": f64::NAN})), extrude("Blks", long(30), long(30), "Rndm", no.clone(), no)); +} + +#[test] +fn malformed_wind_extrude_tiles_are_kept_verbatim() { + let long = Value::Integer; + let (yes, no) = (Value::Boolean(true), Value::Boolean(false)); + let cases = [ + // Missing keys. + Descriptor::new("Wnd "), + Descriptor::new("Wnd ").with("WndM", enumv("WndM", "Blst")), + Descriptor::new("Wnd ").with("Drct", enumv("Drct", "Left")), + Descriptor::new("Extr").with("ExtT", enumv("ExtT", "Blks")).with("ExtS", long(7)).with("ExtD", long(9)).with("ExtR", enumv("ExtR", "Rndm")), + Descriptor::new("Tls ").with("TlNm", long(6)).with("TlOf", long(20)), + Descriptor::new("Tls ").with("TlNm", long(6)).with("FlCl", enumv("FlCl", "FlFr")), + // Unknown enum values and enum types (Photoshop falls back to a default for these; + // we keep them as they are rather than guess). + wind("Wild", "Left"), + wind("Blst", "Up "), + Descriptor::new("Wnd ").with("WndM", enumv("Drct", "Blst")).with("Drct", enumv("Drct", "Left")), + extrude("Cube", long(7), long(9), "Rndm", yes.clone(), no.clone()), + extrude("Blks", long(7), long(9), "Sine", yes.clone(), no.clone()), + tiles(long(6), long(20), "FlXx"), + Descriptor::new("Tls ").with("TlNm", long(6)).with("TlOf", long(20)).with("FlCl", enumv("BlnM", "FlFr")), + // Wrong types (also NaN). + Descriptor::new("Wnd ").with("WndM", long(1)).with("Drct", enumv("Drct", "Left")), + extrude("Blks", Value::Double(7.0), long(9), "Rndm", yes.clone(), no.clone()), + extrude("Blks", long(7), unit(b"#Pxl", 9.0), "Rndm", yes.clone(), no.clone()), + extrude("Blks", long(7), long(9), "Rndm", long(1), no.clone()), + extrude("Blks", long(7), long(9), "Rndm", yes.clone(), Value::Double(f64::NAN)), + tiles(Value::Double(f64::NAN), long(20), "FlFr"), + tiles(long(6), Value::Text(UnicodeString::new_nul("20")), "FlFr"), + // Out of range. + extrude("Blks", long(1), long(9), "Rndm", yes.clone(), no.clone()), + extrude("Blks", long(256), long(9), "Rndm", yes.clone(), no.clone()), + extrude("Blks", long(7), long(0), "Rndm", yes.clone(), no.clone()), + extrude("Blks", long(7), long(i32::MAX), "Rndm", yes, no), + tiles(long(0), long(20), "FlFr"), + tiles(long(100), long(20), "FlFr"), + tiles(long(6), long(0), "FlFr"), + tiles(long(6), long(i32::MIN), "FlFr"), + ]; + for fltr in cases { + let item = measured_item(fltr, 0.0, 255.0); + let f = filter_from_item(&Descriptor::from_bytes(&item.to_bytes()).unwrap()); + assert_eq!(f.command, UNSUPPORTED_FILTER, "{item:?}"); + assert_eq!(item_for_filter(&f).unwrap().to_bytes(), item.to_bytes()); + } + // A Tiles entry whose colour is unreadable is kept verbatim too. + for (key, bad) in [ + ("FrgC", Value::Integer(3)), + ("BckC", Value::Descriptor(Descriptor::new("RGBC").with("Rd ", Value::Double(0.0)))), + ( + "BckC", + Value::Descriptor(Descriptor::new("RGBC").with("Rd ", Value::Double(f64::NAN)).with("Grn ", Value::Double(0.0)).with("Bl ", Value::Double(0.0))), + ), + ] { + let mut item = measured_item(tiles(long(6), long(20), "FlFr"), 0.0, 255.0); + set(&mut item, key, bad); + assert_eq!(filter_from_item(&item).command, UNSUPPORTED_FILTER); + } + // Values with no PSD equivalent are reported, not guessed. + for (c, p) in [ + ("filter.stylize.wind", json!({"method": "gale"})), + ("filter.stylize.wind", json!({"direction": "fromTop"})), + ("filter.stylize.wind", json!({"direction": 1})), + ("filter.stylize.extrude", json!({"type": "cubes"})), + ("filter.stylize.extrude", json!({"depthMode": null})), + ("filter.stylize.tiles", json!({"fill": "transparent"})), + ("filter.stylize.tiles", json!({"foreground": "teal"})), + ("filter.stylize.tiles", json!({"background": [1.0]})), + ("filter.stylize.tiles", json!({"background": [f64::NAN, 0.0, 0.0]})), + ] { + assert!(item_for_filter(&sf(c, p.clone())).is_err(), "{c} {p}"); + } +} + +/// Photoshop's default Custom kernel: a 3 × 3 sharpen centred in the 5 × 5. +const SHARPEN: [i32; 25] = [0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, -1, 5, -1, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0]; + +/// A `filterFXList` item as measured in Photoshop (applied through Action Manager to a smart +/// object, saved, `filterFX` read back). +fn measured_named_item(id: &[u8; 4], name: &str, fltr: Descriptor) -> Descriptor { + Descriptor::new("filterFX") + .with("Nm ", Value::Text(UnicodeString::new_nul(name))) + .with("blendOptions", blend_options(&sf("", J::Null))) + .with("enab", Value::Boolean(true)) + .with("hasoptions", Value::Boolean(true)) + .with("FrgC", rgbc(0.0)) + .with("BckC", rgbc(255.0)) + .with("Fltr", Value::Descriptor(fltr)) + .with("filterID", Value::Integer(code(id))) +} + +fn offset_fltr(h: Value, v: Value, fill: Value) -> Descriptor { + Descriptor::new("Ofst").with("Hrzn", h).with("Vrtc", v).with("Fl ", fill) +} + +fn custom_fltr(scale: Value, offset: Value, m: Vec) -> Descriptor { + Descriptor::new("Cstm").with("Scl ", scale).with("Ofst", offset).with("Mtrx", Value::List(m)) +} + +fn longs(m: &[i32]) -> Vec { + m.iter().map(|v| Value::Integer(*v)).collect() +} + +#[test] +fn offset_round_trips_every_fill_mode() { + for (fill, ours) in [("Wrp ", "wrap"), ("Rpt ", "repeat"), ("Bckg", "transparent")] { + for (h, v) in [(0, 0), (12, -7), (5, 3), (i32::MIN, i32::MAX)] { + let f = sf("filter.other.offset", json!({"horizontal": h, "vertical": v, "undefinedAreas": ours})); + let d = item_for_filter(&f).unwrap(); + let fltr = get_desc(&d, "Fltr").unwrap(); + assert_eq!(*fltr, offset_fltr(Value::Integer(h), Value::Integer(v), enumv("FlMd", fill))); + assert_eq!(int(&d, "filterID"), Some(1_332_114_292)); + assert_eq!(filter_from_item(&Descriptor::from_bytes(&d.to_bytes()).unwrap()), f); + } + } +} + +/// The measured descriptors (Wrap 0/0, Set to Background 12/−7, Repeat 5/3) open as Offset. +#[test] +fn offset_measured_descriptors_open_as_offset() { + for (h, v, fill, ours) in [(0, 0, "Wrp ", "wrap"), (12, -7, "Bckg", "transparent"), (5, 3, "Rpt ", "repeat")] { + let item = measured_named_item(b"Ofst", "Offset...", offset_fltr(Value::Integer(h), Value::Integer(v), enumv("FlMd", fill))); + let f = filter_from_item(&item); + assert_eq!(f.command, "filter.other.offset"); + assert_eq!(f.params, json!({"horizontal": h, "vertical": v, "undefinedAreas": ours})); + // Written back exactly as measured. + assert_eq!(item_for_filter(&f).unwrap(), item); + } +} + +#[test] +fn offset_written_with_engine_defaults() { + // No params: 0, 0, Wrap Around (the engine's defaults); fractional pixels round. + let d = item_for_filter(&sf("filter.other.offset", json!({}))).unwrap(); + assert_eq!(*get_desc(&d, "Fltr").unwrap(), offset_fltr(Value::Integer(0), Value::Integer(0), enumv("FlMd", "Wrp "))); + let d = item_for_filter(&sf("filter.other.offset", json!({"horizontal": 2.6, "vertical": 3e12, "undefinedAreas": "bogus"}))).unwrap(); + assert_eq!(*get_desc(&d, "Fltr").unwrap(), offset_fltr(Value::Integer(3), Value::Integer(i32::MAX), enumv("FlMd", "Wrp "))); +} + +#[test] +fn malformed_offset_is_kept_verbatim() { + let i = Value::Integer; + for fltr in [ + offset_fltr(i(1), i(2), enumv("FlMd", "Xxxx")), + offset_fltr(i(1), i(2), Value::Integer(1)), + offset_fltr(Value::Double(1.5), i(2), enumv("FlMd", "Wrp ")), + offset_fltr(i(1), unit(b"#Pxl", f64::NAN), enumv("FlMd", "Wrp ")), + Descriptor::new("Ofst").with("Hrzn", i(1)).with("Fl ", enumv("FlMd", "Wrp ")), + Descriptor::new("Ofst"), + // A mistyped enum, a setting we don't write back and a repeated one. + offset_fltr(i(1), i(2), enumv("Xxxx", "Wrp ")), + offset_fltr(i(1), i(2), enumv("FlMd", "Wrp ")).with("Xtra", i(1)), + offset_fltr(i(1), i(2), enumv("FlMd", "Wrp ")).with("Hrzn", i(3)), + ] { + let item = measured_named_item(b"Ofst", "Offset...", fltr); + let f = filter_from_item(&item); + assert_eq!(f.command, UNSUPPORTED_FILTER, "{item:?}"); + assert_eq!(item_for_filter(&f).unwrap().to_bytes(), item.to_bytes(), "kept byte for byte"); + } + let bare = Descriptor::new("filterFX").with("filterID", Value::Integer(code(b"Ofst"))); + assert_eq!(filter_from_item(&bare).command, UNSUPPORTED_FILTER); +} + +#[test] +fn custom_round_trips() { + let edge: Vec = (0..25) + .map(|i| { + if i == 12 { + 8 + } else if (6..=18).contains(&i) && i % 5 != 0 && i % 5 != 4 { + -1 + } else { + 0 + } + }) + .collect(); + let full: Vec = (0..25).map(|i| i * 83 - 999).collect(); + for (kernel, scale, offset) in [(SHARPEN.to_vec(), 1, 0), (edge, 2, 10), (full, 9999, -9999), (vec![999; 25], 1, 9999)] { + let f = sf("filter.other.custom", json!({"kernel": kernel, "scale": scale, "offset": offset})); + let d = item_for_filter(&f).unwrap(); + assert_eq!(*get_desc(&d, "Fltr").unwrap(), custom_fltr(Value::Integer(scale), Value::Integer(offset), longs(&kernel))); + assert_eq!(int(&d, "filterID"), Some(1_131_639_917)); + assert_eq!(filter_from_item(&Descriptor::from_bytes(&d.to_bytes()).unwrap()), f); + } +} + +/// The measured descriptors (the default sharpen; a blur at Scale 2, Offset 10) open as Custom. +#[test] +fn custom_measured_descriptors_open_as_custom() { + let blur = [0, 0, 0, 0, 0, 0, 1, 2, 1, 0, 0, 2, 4, 2, 0, 0, 1, 2, 1, 0, 0, 0, 0, 0, 0]; + for (kernel, scale, offset) in [(SHARPEN, 1, 0), (blur, 2, 10)] { + let item = measured_named_item(b"Cstm", "Custom...", custom_fltr(Value::Integer(scale), Value::Integer(offset), longs(&kernel))); + let f = filter_from_item(&item); + assert_eq!(f.command, "filter.other.custom"); + assert_eq!(f.params, json!({"kernel": kernel, "scale": scale, "offset": offset})); + assert_eq!(item_for_filter(&f).unwrap(), item); + } +} + +#[test] +fn custom_written_like_the_engine_reads_it() { + let fltr = |p: J| get_desc(&item_for_filter(&sf("filter.other.custom", p)).unwrap(), "Fltr").cloned().unwrap(); + // No kernel: the engine's identity; short kernels pad with 0; out-of-range values clamp. + let mut id = [0; 25]; + id[12] = 1; + assert_eq!(fltr(json!({})), custom_fltr(Value::Integer(1), Value::Integer(0), longs(&id))); + let mut short = [0; 25]; + short[0] = 3; + short[1] = -999; + assert_eq!(fltr(json!({"kernel": [3, -5000], "scale": 0, "offset": 20000})), custom_fltr(Value::Integer(1), Value::Integer(9999), longs(&short))); + // Fractions have no PSD equivalent. + for p in [json!({"kernel": [0.5]}), json!({"scale": 1.5}), json!({"offset": -0.25})] { + assert!(item_for_filter(&sf("filter.other.custom", p.clone())).is_err(), "{p}"); + } +} + +#[test] +fn malformed_custom_is_kept_verbatim() { + let i = Value::Integer; + let mut wrong_type = longs(&SHARPEN); + wrong_type[3] = Value::Double(1.0); + for fltr in [ + custom_fltr(i(1), i(0), longs(&SHARPEN[..24])), + custom_fltr(i(1), i(0), longs(&[0; 26])), + custom_fltr(i(1), i(0), wrong_type), + custom_fltr(i(1), i(0), longs(&[1000; 25])), + custom_fltr(i(0), i(0), longs(&SHARPEN)), + custom_fltr(i(10_000), i(0), longs(&SHARPEN)), + custom_fltr(i(1), i(-10_000), longs(&SHARPEN)), + custom_fltr(Value::Double(f64::NAN), i(0), longs(&SHARPEN)), + custom_fltr(i(1), unit(b"#Pxl", 1.0), longs(&SHARPEN)), + Descriptor::new("Cstm").with("Scl ", i(1)).with("Ofst", i(0)).with("Mtrx", i(5)), + Descriptor::new("Cstm").with("Scl ", i(1)).with("Mtrx", Value::List(longs(&SHARPEN))), + Descriptor::new("Cstm"), + // A setting we don't write back. + custom_fltr(i(1), i(0), longs(&SHARPEN)).with("Xtra", i(1)), + ] { + let item = measured_named_item(b"Cstm", "Custom...", fltr); + let f = filter_from_item(&item); + assert_eq!(f.command, UNSUPPORTED_FILTER, "{item:?}"); + assert_eq!(item_for_filter(&f).unwrap().to_bytes(), item.to_bytes(), "kept byte for byte"); + } +} + +/// A `filterFX` item holding `fltr`, as Photoshop writes a filter with options. +fn pixelate_item(name: &str, fltr: Descriptor, filter_id: i32) -> Descriptor { + Descriptor::new("filterFX") + .with("Nm ", Value::Text(UnicodeString::new_nul(name))) + .with("blendOptions", Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", 100.0)).with("Md ", enumv("BlnM", "Nrml")))) + .with("enab", Value::Boolean(true)) + .with("hasoptions", Value::Boolean(true)) + .with("FrgC", rgbc(0.0)) + .with("BckC", rgbc(255.0)) + .with("Fltr", Value::Descriptor(fltr)) + .with("filterID", Value::Integer(filter_id)) +} + +#[test] +fn mezzotint_round_trips_every_type_and_reads_photoshops_shape() { + for (code, ty) in MEZZOTINT_TYPES { + let f = sf("filter.pixelate.mezzotint", json!({"type": ty})); + let d = item_for_filter(&f).unwrap(); + assert_eq!(int(&d, "filterID"), Some(1_299_870_830)); + let fltr = get_desc(&d, "Fltr").unwrap(); + assert!(fltr.class_id.is("Mztn")); + assert_eq!(enum_of(fltr, "MztT"), Some(&code[..])); + assert!(matches!(fltr.get("MztT"), Some(Value::Enumerated { type_id, .. }) if type_id.is("MztT"))); + assert_eq!(filter_from_item(&Descriptor::from_bytes(&d.to_bytes()).unwrap()), f, "{ty}"); + } + // Measured in Photoshop: `{'_class': 'Mztn', 'MztT': 'MztT.CrsD'}` and `LngS`, filterID 1299870830. + for (code, ty) in [("CrsD", "coarseDots"), ("LngS", "longStrokes")] { + let item = pixelate_item("Mezzotint...", Descriptor::new("Mztn").with("MztT", enumv("MztT", code)), 1_299_870_830); + let f = filter_from_item(&item); + assert_eq!((f.command.as_str(), &f.params), ("filter.pixelate.mezzotint", &json!({"type": ty}))); + } + // No type or an unknown type is Fine Dots, like the engine; the seed + // (PhotoCraft only) is not saved. + for p in [json!({}), json!({"type": "sparkles"}), json!({"type": "fineDots", "seed": 77})] { + let d = item_for_filter(&sf("filter.pixelate.mezzotint", p)).unwrap(); + let fltr = get_desc(&d, "Fltr").unwrap(); + assert_eq!(enum_of(fltr, "MztT"), Some(&b"FnDt"[..])); + assert_eq!(fltr.items.len(), 1); + } +} + +#[test] +fn color_halftone_round_trips_and_reads_photoshops_shape() { + for p in [ + json!({"maxRadius": 8, "channel1": 108, "channel2": 162, "channel3": 90, "channel4": 45}), + json!({"maxRadius": 4, "channel1": -360, "channel2": 0, "channel3": 360, "channel4": -45}), + json!({"maxRadius": 127, "channel1": 1, "channel2": 2, "channel3": 3, "channel4": 4}), + ] { + let f = sf("filter.pixelate.colorHalftone", p); + let d = item_for_filter(&f).unwrap(); + assert_eq!(int(&d, "filterID"), Some(1_131_180_616)); + let fltr = get_desc(&d, "Fltr").unwrap(); + assert!(fltr.class_id.is("ClrH")); + for k in ["Rds ", "Ang1", "Ang2", "Ang3", "Ang4"] { + assert!(matches!(fltr.get(k), Some(Value::Integer(_))), "{k} is a long"); + } + assert_eq!(filter_from_item(&Descriptor::from_bytes(&d.to_bytes()).unwrap()), f); + } + // Measured in Photoshop: `{'_class': 'ClrH', 'Rds ': 6, 'Ang1': 10, 'Ang2': 20, 'Ang3': 30, 'Ang4': 40}`. + let measured = Descriptor::new("ClrH") + .with("Rds ", Value::Integer(6)) + .with("Ang1", Value::Integer(10)) + .with("Ang2", Value::Integer(20)) + .with("Ang3", Value::Integer(30)) + .with("Ang4", Value::Integer(40)); + let item = pixelate_item("Color Halftone...", measured.clone(), 1_131_180_616); + let f = filter_from_item(&item); + assert_eq!(f.command, "filter.pixelate.colorHalftone"); + assert_eq!(f.params, json!({"maxRadius": 6, "channel1": 10, "channel2": 20, "channel3": 30, "channel4": 40})); + assert_eq!(get_desc(&item_for_filter(&f).unwrap(), "Fltr"), Some(&measured)); + // Defaults and hostile values write longs within the dialog's ranges. + let d = + item_for_filter(&sf("filter.pixelate.colorHalftone", json!({"maxRadius": f64::NAN, "channel1": 1e12, "channel2": -1e12, "channel3": "x"}))).unwrap(); + let fltr = get_desc(&d, "Fltr").unwrap(); + let got: Vec<_> = ["Rds ", "Ang1", "Ang2", "Ang3", "Ang4"].iter().map(|k| int(fltr, k)).collect(); + assert_eq!(got, [Some(8), Some(360), Some(-360), Some(90), Some(45)]); +} + +#[test] +fn malformed_pixelate_filters_stay_verbatim() { + let mz = |v: Value| Descriptor::new("Mztn").with("MztT", v); + let ch = |rds: Value, ang1: Value| { + Descriptor::new("ClrH") + .with("Rds ", rds) + .with("Ang1", ang1) + .with("Ang2", Value::Integer(20)) + .with("Ang3", Value::Integer(30)) + .with("Ang4", Value::Integer(40)) + }; + let cases = [ + pixelate_item("Mezzotint...", Descriptor::new("Mztn"), code(b"Mztn")), + pixelate_item("Mezzotint...", mz(enumv("MztT", "Sprk")), code(b"Mztn")), + pixelate_item("Mezzotint...", mz(Value::Integer(1)), code(b"Mztn")), + pixelate_item("Color Halftone...", Descriptor::new("ClrH"), code(b"ClrH")), + pixelate_item("Color Halftone...", ch(Value::Double(6.0), Value::Integer(10)), code(b"ClrH")), + pixelate_item("Color Halftone...", ch(unit(b"#Pxl", 6.0), Value::Integer(10)), code(b"ClrH")), + pixelate_item("Color Halftone...", ch(Value::Integer(3), Value::Integer(10)), code(b"ClrH")), + pixelate_item("Color Halftone...", ch(Value::Integer(128), Value::Integer(10)), code(b"ClrH")), + pixelate_item("Color Halftone...", ch(Value::Integer(6), Value::Integer(361)), code(b"ClrH")), + pixelate_item("Color Halftone...", ch(Value::Integer(6), Value::Integer(i32::MIN)), code(b"ClrH")), + pixelate_item("Color Halftone...", ch(Value::Integer(6), Value::Double(f64::NAN)), code(b"ClrH")), + // A mistyped enum and settings we don't write back. + pixelate_item("Mezzotint...", mz(enumv("Xxxx", "FnDt")), code(b"Mztn")), + pixelate_item("Mezzotint...", mz(enumv("MztT", "FnDt")).with("Xtra", Value::Integer(1)), code(b"Mztn")), + pixelate_item("Color Halftone...", ch(Value::Integer(6), Value::Integer(10)).with("Xtra", Value::Integer(1)), code(b"ClrH")), + pixelate_item("Color Halftone...", ch(Value::Integer(6), Value::Integer(10)).with("Ang1", Value::Integer(11)), code(b"ClrH")), + ]; + for item in cases { + let f = filter_from_item(&item); + assert_eq!(f.command, UNSUPPORTED_FILTER, "{:?}", get_desc(&item, "Fltr")); + // Written back with its own settings (blending is rewritten from the model). + let back = item_for_filter(&f).unwrap(); + // Compared as bytes: a NaN setting is not equal to itself. + let fltr = |d: &Descriptor| get_desc(d, "Fltr").map(Descriptor::to_bytes); + assert_eq!((fltr(&back), int(&back, "filterID")), (fltr(&item), int(&item, "filterID"))); + } + // Without a `Fltr` the filter has no settings to read: kept verbatim too. + let bare = Descriptor::new("filterFX").with("filterID", Value::Integer(code(b"ClrH"))); + assert_eq!(filter_from_item(&bare).command, UNSUPPORTED_FILTER); +} + +/// Distort smart filters from a Photoshop file open as their PhotoCraft filters, and the ones +/// PhotoCraft writes carry the same settings, keys and order as Photoshop's. +#[test] +fn photoshop_distort_filters_read_and_write_like_photoshop() { + for (command, params, hex) in PHOTOSHOP_FLTR { + let ps = Descriptor::from_bytes(&from_hex(hex).unwrap()).unwrap(); + let f = filter_from_item(&photoshop_fltr_item(ps.clone())); + let want: J = serde_json::from_str(params).unwrap(); + assert_eq!((f.command.as_str(), &f.params), (command, &want), "{command}"); + let ours = match item_for_filter(&f).unwrap().get("Fltr") { + Some(Value::Descriptor(d)) => d.clone(), + other => panic!("{command}: no Fltr ({other:?})"), + }; + assert_eq!((&ours.class_id, &ours.items), (&ps.class_id, &ps.items), "{command}: same keys, values and order"); + } + // A scaled wave can't be modelled, so it stays Photoshop's, unchanged. + let wave = Descriptor::from_bytes(&from_hex(PHOTOSHOP_WAVE).unwrap()).unwrap(); + let item = photoshop_fltr_item(wave); + let f = filter_from_item(&item); + assert_eq!(f.command, UNSUPPORTED_FILTER); + assert_eq!(item_for_filter(&f).unwrap().get("Fltr"), item.get("Fltr")); + // Unscaled, but with 332 generators (the renderer draws 64 at most), it stays Photoshop's too. + let mut unscaled = match item.get("Fltr") { + Some(Value::Descriptor(d)) => d.clone(), + other => panic!("wave: no Fltr ({other:?})"), + }; + set(&mut unscaled, "SclV", Value::Integer(100)); + let item = photoshop_fltr_item(unscaled); + let f = filter_from_item(&item); + assert_eq!(f.command, UNSUPPORTED_FILTER); + assert_eq!(item_for_filter(&f).unwrap().get("Fltr"), item.get("Fltr")); + + // An extra or repeated setting PhotoCraft doesn't model keeps the filter Photoshop's, unchanged. + let mut fltrs: Vec = PHOTOSHOP_FLTR.iter().map(|(_, _, hex)| Descriptor::from_bytes(&from_hex(hex).unwrap()).unwrap()).collect(); + let mut wave = unscaled_wave(); + set(&mut wave, "NmbG", Value::Integer(5)); + assert_eq!(filter_from_item(&photoshop_fltr_item(wave.clone())).command, "filter.distort.wave", "the plain wave maps"); + fltrs.push(wave); + for ps in fltrs { + let name = String::from_utf8_lossy(ps.class_id.as_bytes()).into_owned(); + let mut repeated = ps.clone(); + repeated.items.push(ps.items[0].clone()); + for odd in [ps.clone().with("Xtra", Value::Integer(7)), repeated] { + let item = photoshop_fltr_item(odd); + let f = filter_from_item(&item); + assert_eq!(f.command, UNSUPPORTED_FILTER, "{name}"); + assert_eq!(item_for_filter(&f).unwrap().get("Fltr"), item.get("Fltr"), "{name}: written back unchanged"); + } + } +} + +/// Photoshop's Wave ([`PHOTOSHOP_WAVE`]) at 100% scale both ways. +fn unscaled_wave() -> Descriptor { + let mut wave = Descriptor::from_bytes(&from_hex(PHOTOSHOP_WAVE).unwrap()).unwrap(); + set(&mut wave, "SclV", Value::Integer(100)); + wave +} + +/// An unscaled Wave opens as PhotoCraft's Wave (Triangle, the other settings as stored) up to +/// the generators the renderer models; one more and it stays Photoshop's, unchanged. +#[test] +fn wave_maps_up_to_the_generators_the_renderer_models() { + let max = i32::try_from(photocraft_algo::MAX_WAVE_GENERATORS).unwrap(); + assert_eq!(max, 64); + let mut wave = Descriptor::from_bytes(&from_hex(PHOTOSHOP_WAVE).unwrap()).unwrap(); + set(&mut wave, "SclV", Value::Integer(100)); + for (generators, mapped) in [(1, true), (max, true), (max + 1, false), (999, false), (0, false), (-1, false)] { + set(&mut wave, "NmbG", Value::Integer(generators)); + let item = photoshop_fltr_item(wave.clone()); + let f = filter_from_item(&item); + if mapped { + assert_eq!( + (f.command.as_str(), &f.params), + ( + "filter.distort.wave", + &json!({"type": "triangle", "generators": generators, "wavelengthMin": 213, "wavelengthMax": 214, "amplitudeMin": 240, + "amplitudeMax": 241, "undefinedAreas": "wrap", "seed": 1270346}) + ), + "{generators} generators" + ); + match item_for_filter(&f).unwrap().get("Fltr") { + Some(Value::Descriptor(ours)) => assert_eq!((&ours.class_id, &ours.items), (&wave.class_id, &wave.items), "{generators} generators"), + other => panic!("wave: no Fltr ({other:?})"), + } + } else { + assert_eq!(f.command, UNSUPPORTED_FILTER, "{generators} generators"); + assert_eq!(item_for_filter(&f).unwrap().get("Fltr"), item.get("Fltr"), "{generators} generators"); + } + } +} + +/// PhotoCraft draws at most `MAX_WAVE_GENERATORS` generators, so a Wave edited past that exports +/// the 64 it rendered, and a count below 1 exports 1, instead of Photoshop drawing more. +#[test] +fn wave_export_writes_only_the_generators_the_renderer_draws() { + let max = i32::try_from(photocraft_algo::MAX_WAVE_GENERATORS).unwrap(); + for (stored, written) in [(100, max), (999, max), (max + 1, max), (max, max), (5, 5), (1, 1), (0, 1), (-3, 1)] { + let wave = sf( + "filter.distort.wave", + json!({"type": "sine", "generators": stored, "wavelengthMin": 20, "wavelengthMax": 90, "amplitudeMin": 4, "amplitudeMax": 30}), + ); + let fltr = match item_for_filter(&wave).unwrap().get("Fltr") { + Some(Value::Descriptor(d)) => d.clone(), + other => panic!("wave: no Fltr ({other:?})"), + }; + assert_eq!(int(&fltr, "NmbG"), Some(written), "{stored} generators"); + } +} + +/// `RndS` is the seed the renderer draws with, also for a legacy signed or fractional seed +/// (stored as is by `layer.smartFilter.setParams`), not 0. +#[test] +fn wave_export_writes_the_seed_the_renderer_draws() { + for (stored, written) in [ + (json!(77), 77), + (json!(4_000_000_000u32), -294_967_296), + (json!(-1), -1), + (json!(7.4), 7), + (json!(-2.6), -3), + (json!(1e12), i32::MAX), + (json!("x"), 0), + ] { + let wave = sf("filter.distort.wave", json!({"generators": 3, "seed": stored})); + let fltr = match item_for_filter(&wave).unwrap().get("Fltr") { + Some(Value::Descriptor(d)) => d.clone(), + other => panic!("wave: no Fltr ({other:?})"), + }; + assert_eq!(int(&fltr, "RndS"), Some(written), "seed {stored}"); + // And it reads back as that bit pattern. + assert_eq!(known_params("Wave", Some(&fltr), &Descriptor::new("filterFX")).unwrap().1["seed"], json!(written as u32), "seed {stored}"); + } +} + +/// Invert on a smart object: Photoshop stores no `Fltr`, `hasoptions` false and its filter id. +#[test] +fn invert_smart_filter_reads_and_writes_like_photoshop() { + let item = Descriptor::new("filterFX") + .with("Nm ", Value::Text(UnicodeString::new_nul("Invert"))) + .with("blendOptions", Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", 100.0)).with("Md ", enumv("BlnM", "normal")))) + .with("enab", Value::Boolean(true)) + .with("hasoptions", Value::Boolean(false)) + .with("FrgC", rgbc(255.0)) + .with("BckC", rgbc(0.0)) + .with("filterID", Value::Integer(code(b"Invr"))); + let f = filter_from_item(&item); + assert_eq!((f.command.as_str(), &f.params), ("image.adjustments.invert", &json!({}))); + let back = item_for_filter(&f).unwrap(); + assert_eq!(back.get("Fltr"), None); + assert_eq!(back.get("hasoptions"), Some(&Value::Boolean(false))); + assert_eq!(back.get("filterID"), Some(&Value::Integer(code(b"Invr")))); + assert_eq!(back.get("Nm "), Some(&Value::Text(UnicodeString::new_nul("Invert")))); +} + +/// A filter PhotoCraft doesn't model, or a known one with settings it doesn't, is kept verbatim; only its visibility and blend change. +#[test] +fn photoshop_sharpen_without_fltr_imports_as_sharpen() { + // #6267: Photoshop's Sharpen item holds only its name, blending and `filterID`. + let item = Descriptor::new("filterFX") + .with("Nm ", Value::Text(UnicodeString::new_nul("Sharpen"))) + .with("blendOptions", Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", 100.0)).with("Md ", enumv("BlnM", "normal")))) + .with("enab", Value::Boolean(true)) + .with("hasoptions", Value::Boolean(false)) + .with("filterID", Value::Integer(1_399_353_968)); + let f = filter_from_item(&item); + assert_eq!((f.command.as_str(), &f.params), ("filter.sharpen.sharpen", &json!({}))); + // Hue/Saturation with an unnumbered range and Dust & Scratches with a missing setting fail + // cleanly instead of panicking. + let bad = SmartFilter { + command: "image.adjustments.hueSaturation".into(), + params: json!({"reds": {"range": [1, "x", 3, 4]}}), + blend: BlendMode::Normal, + opacity: 1.0, + visible: true, + }; + assert!(item_for_filter(&bad).is_err()); + let dust = Descriptor::new("filterFX") + .with("Fltr", Value::Descriptor(Descriptor::new("DstS").with("Rds ", Value::Integer(3)))) + .with("filterID", Value::Integer(code(b"DstS"))); + assert_eq!(filter_from_item(&dust).command, UNSUPPORTED_FILTER); +} + +#[test] +fn hue_saturation_ranges_are_not_lost() { + let hue_sat = |params: J| item_for_filter(&sf("image.adjustments.hueSaturation", params)); + // A range that is not an object is an error, not a silently dropped setting. + assert!(hue_sat(json!({"reds": 5})).is_err()); + assert!(hue_sat(json!({"reds": null})).is_ok()); + // Colorize's 25% default is the master saturation's only: a range's stays 0. + let d = hue_sat(json!({"colorize": true, "reds": {"hue": 5}})).unwrap(); + let adjs = adjustment_list(get_desc(&d, "Fltr").unwrap()).unwrap(); + let saturations: Vec<_> = adjs.iter().map(|a| int(a, "Strt")).collect(); + assert_eq!(saturations, [Some(25), Some(0)]); + // A repeated range (or master) would overwrite the first: the filter is kept verbatim. + let entry = |range: Option| { + let e = Descriptor::new("Hst2").with("H ", Value::Integer(0)).with("Strt", Value::Integer(0)).with("Lght", Value::Integer(0)); + let Some(r) = range else { return Value::Descriptor(e) }; + let e = ["BgnR", "BgnS", "EndS", "EndR"].iter().fold(e.with("LclR", Value::Integer(r)), |e, k| e.with(k, Value::Integer(10))); + Value::Descriptor(e) + }; + for adjs in [vec![entry(None), entry(Some(1)), entry(Some(1))], vec![entry(None), entry(None)]] { + let fltr = Descriptor::new("HStr").with("Clrz", Value::Boolean(false)).with("Adjs", Value::List(adjs)); + let item = Descriptor::new("filterFX") + .with("Nm ", Value::Text(UnicodeString::new_nul("Hue/Saturation..."))) + .with("blendOptions", Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", 100.0)).with("Md ", enumv("BlnM", "normal")))) + .with("enab", Value::Boolean(true)) + .with("Fltr", Value::Descriptor(fltr)) + .with("filterID", Value::Integer(code(b"HStr"))); + let f = filter_from_item(&item); + assert_eq!(f.command, UNSUPPORTED_FILTER); + assert_eq!(item_for_filter(&f).unwrap(), item); + } +} + +#[test] +fn unknown_filters_keep_their_descriptor() { + let item = Descriptor::new("filterFX") + .with("Nm ", Value::Text(UnicodeString::new_nul("Shear..."))) + .with("blendOptions", Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", 100.0)).with("Md ", enumv("BlnM", "normal")))) + .with("enab", Value::Boolean(true)) + .with("Fltr", Value::Descriptor(Descriptor::new("Shr ").with("UndA", enumv("UndA", "WrpA")))) + .with("filterID", Value::Integer(code(b"Shr "))); + let f = filter_from_item(&item); + assert_eq!(f.command, UNSUPPORTED_FILTER); + assert_eq!(f.params["name"], "Shear..."); + assert_eq!(item_for_filter(&f).unwrap(), item); + // Hidden and re-blended: only those keys change. + let mut g = f.clone(); + g.visible = false; + g.blend = BlendMode::Screen; + let back = filter_from_item(&item_for_filter(&g).unwrap()); + assert_eq!((back.visible, back.blend, &back.params), (false, BlendMode::Screen, &f.params)); + // A known filter with a setting we don't model is kept verbatim too. + let odd = Descriptor::new("filterFX").with("Fltr", Value::Descriptor(Descriptor::new("GsnB"))).with("filterID", Value::Integer(code(b"GsnB"))); + assert_eq!(filter_from_item(&odd).command, UNSUPPORTED_FILTER); +} + +/// A `filterFXList` item with filter `fltr` and `filterID`, as Photoshop saves it. +fn ps_item(name: &str, fltr: Descriptor, filter_id: i32) -> Descriptor { + Descriptor::new("filterFX") + .with("Nm ", Value::Text(UnicodeString::new_nul(name))) + .with("blendOptions", Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", 100.0)).with("Md ", enumv("BlnM", "normal")))) + .with("enab", Value::Boolean(true)) + .with("hasoptions", Value::Boolean(true)) + .with("FrgC", rgbc(0.0)) + .with("BckC", rgbc(255.0)) + .with("Fltr", Value::Descriptor(fltr)) + .with("filterID", Value::Integer(filter_id)) +} + +fn surface_blur(rds: f64, thsh: i32) -> Descriptor { + Descriptor::new("surfaceBlur").with("Rds ", unit(b"#Pxl", rds)).with("Thsh", Value::Integer(thsh)) +} + +fn smart_blur(rds: f64, thsh: f64, q: &str, m: &str) -> Descriptor { + Descriptor::new("SmrB").with("Rds ", Value::Double(rds)).with("Thsh", Value::Double(thsh)).with("SmBQ", enumv("SmBQ", q)).with("SmBM", enumv("SmBM", m)) +} + +fn radial_blur(amnt: i32, m: &str, q: &str) -> Descriptor { + Descriptor::new("RdlB").with("Amnt", Value::Integer(amnt)).with("BlrM", enumv("BlrM", m)).with("BlrQ", enumv("BlrQ", q)) +} + +/// The `Fltr` shapes measured in Photoshop (each filter applied to a smart object through +/// Action Manager, saved, and `filterFX` read back) open as our filters and are written back +/// with the same keys, value types, units, enums and filter ids. +#[test] +fn blur_family_matches_photoshop_shapes() { + let smart = code(b"SmrB"); + let radial = code(b"RdlB"); + assert_eq!((smart, radial), (1_399_681_602, 1_382_313_026)); + let cases = [ + (surface_blur(5.0, 15), 1135, "filter.blur.surfaceBlur", json!({"radius": 5.0, "threshold": 15})), + (surface_blur(12.0, 40), 1135, "filter.blur.surfaceBlur", json!({"radius": 12.0, "threshold": 40})), + (smart_blur(5.0, 25.0, "SBQH", "SBMN"), smart, "filter.blur.smartBlur", json!({"radius": 5.0, "threshold": 25.0, "quality": "high", "mode": "normal"})), + ( + smart_blur(3.0, 30.0, "SBQL", "SBME"), + smart, + "filter.blur.smartBlur", + json!({"radius": 3.0, "threshold": 30.0, "quality": "low", "mode": "edgeOnly"}), + ), + ( + smart_blur(3.0, 30.0, "SBQM", "SBMO"), + smart, + "filter.blur.smartBlur", + json!({"radius": 3.0, "threshold": 30.0, "quality": "medium", "mode": "overlayEdge"}), + ), + (radial_blur(10, "Spn ", "Drft"), radial, "filter.blur.radialBlur", json!({"amount": 10, "method": "spin", "quality": "draft"})), + (radial_blur(20, "Spn ", "Bst "), radial, "filter.blur.radialBlur", json!({"amount": 20, "method": "spin", "quality": "best"})), + (radial_blur(20, "Zm ", "Gd "), radial, "filter.blur.radialBlur", json!({"amount": 20, "method": "zoom", "quality": "good"})), + ]; + for (fltr, id, command, params) in cases { + let item = ps_item("x", fltr.clone(), id); + let f = filter_from_item(&Descriptor::from_bytes(&item.to_bytes()).unwrap()); + assert_eq!((f.command.as_str(), &f.params), (command, ¶ms), "{fltr:?}"); + let out = item_for_filter(&f).unwrap(); + assert_eq!(out.get("filterID"), Some(&Value::Integer(id))); + assert_eq!(out.get("hasoptions"), Some(&Value::Boolean(true))); + // Byte-identical filter descriptor: class id, four-char keys, types, units and enums. + let Some(Value::Descriptor(w)) = out.get("Fltr") else { panic!("no Fltr for {command}") }; + assert_eq!(w.to_bytes(), fltr.to_bytes(), "{command}"); + } + // Surface Blur's class is a string id; Smart Blur's and Radial Blur's are four-char codes. + assert_eq!(surface_blur(1.0, 2).class_id, Id::Str(b"surfaceBlur".to_vec())); + assert_eq!(radial_blur(1, "Spn ", "Gd ").class_id, Id::Code(*b"RdlB")); + // Unset options are written with the dialog defaults. + let fltr = |c: &str, p: J| item_for_filter(&sf(c, p)).unwrap().get("Fltr").cloned(); + assert_eq!(fltr("filter.blur.surfaceBlur", json!({})), Some(Value::Descriptor(surface_blur(5.0, 15)))); + assert_eq!(fltr("filter.blur.smartBlur", json!({})), Some(Value::Descriptor(smart_blur(3.0, 25.0, "SBQH", "SBMN")))); + assert_eq!(fltr("filter.blur.radialBlur", json!({"centerX": 0.5, "centerY": 0.5})), Some(Value::Descriptor(radial_blur(10, "Spn ", "Gd ")))); +} + +/// `d` with `key` set to `v` (replacing the measured value). +fn replaced(mut d: Descriptor, key: &str, v: Value) -> Descriptor { + set(&mut d, key, v); + d +} + +/// Malformed or unmodelled blur descriptors stay verbatim (and are written back unchanged); +/// settings PSD can't hold are reported, never a panic. +#[test] +fn blur_family_malformed_is_kept_verbatim() { + let smart = code(b"SmrB"); + let radial = code(b"RdlB"); + let text = |s: &str| Value::Text(UnicodeString::new_nul(s)); + let bad = [ + // Missing keys. + (Descriptor::new("surfaceBlur").with("Rds ", unit(b"#Pxl", 5.0)), 1135), + (Descriptor::new("SmrB").with("Rds ", Value::Double(3.0)).with("Thsh", Value::Double(25.0)), smart), + (Descriptor::new("RdlB").with("Amnt", Value::Integer(10)).with("BlrM", enumv("BlrM", "Spn ")), radial), + // Wrong types. + (Descriptor::new("surfaceBlur").with("Rds ", unit(b"#Pxl", 5.0)).with("Thsh", Value::Double(15.0)), 1135), + ( + Descriptor::new("SmrB") + .with("Rds ", text("3")) + .with("Thsh", Value::Double(25.0)) + .with("SmBQ", enumv("SmBQ", "SBQH")) + .with("SmBM", enumv("SmBM", "SBMN")), + smart, + ), + (Descriptor::new("RdlB").with("Amnt", text("10")).with("BlrM", enumv("BlrM", "Spn ")).with("BlrQ", enumv("BlrQ", "Gd ")), radial), + (Descriptor::new("RdlB").with("Amnt", Value::Integer(10)).with("BlrM", Value::Integer(1)).with("BlrQ", enumv("BlrQ", "Gd ")), radial), + // Out of range, NaN and infinity. + (surface_blur(0.5, 15), 1135), + (surface_blur(5.0, 300), 1135), + (surface_blur(f64::NAN, 15), 1135), + (smart_blur(f64::INFINITY, 25.0, "SBQH", "SBMN"), smart), + (smart_blur(3.0, 0.0, "SBQH", "SBMN"), smart), + (radial_blur(0, "Spn ", "Gd "), radial), + (radial_blur(101, "Zm ", "Gd "), radial), + // Unknown enum values. + (smart_blur(3.0, 25.0, "SBQX", "SBMN"), smart), + (smart_blur(3.0, 25.0, "Hgh ", "SBMN"), smart), + (radial_blur(10, "Twrl", "Gd "), radial), + (radial_blur(10, "Spn ", "Hgh "), radial), + // A key we don't model (an off-centre Radial Blur would carry one). + (radial_blur(10, "Zm ", "Gd ").with("Cntr", Value::Descriptor(Descriptor::new("Pnt ").with("Hrzn", Value::Double(10.0)))), radial), + (surface_blur(5.0, 15).with("Edg ", Value::Integer(1)), 1135), + // Enums of another type, units and value types we would not write back. + (replaced(smart_blur(3.0, 25.0, "SBQH", "SBMN"), "SmBQ", enumv("Othr", "SBQH")), smart), + (replaced(smart_blur(3.0, 25.0, "SBQH", "SBMN"), "SmBM", enumv("SmBQ", "SBMN")), smart), + (replaced(radial_blur(10, "Spn ", "Gd "), "BlrM", enumv("Othr", "Spn ")), radial), + (replaced(radial_blur(10, "Spn ", "Gd "), "BlrQ", enumv("BlrM", "Gd ")), radial), + (Descriptor::new("surfaceBlur").with("Rds ", unit(b"#Prc", 5.0)).with("Thsh", Value::Integer(15)), 1135), + (Descriptor::new("surfaceBlur").with("Rds ", Value::Double(5.0)).with("Thsh", Value::Integer(15)), 1135), + (replaced(smart_blur(3.0, 25.0, "SBQH", "SBMN"), "Rds ", unit(b"#Pxl", 3.0)), smart), + (replaced(smart_blur(3.0, 25.0, "SBQH", "SBMN"), "Thsh", unit(b"#Prc", 25.0)), smart), + (replaced(smart_blur(3.0, 25.0, "SBQH", "SBMN"), "Thsh", Value::Integer(25)), smart), + ]; + for (fltr, id) in bad { + let item = ps_item("x", fltr.clone(), id); + let f = filter_from_item(&item); + assert_eq!(f.command, UNSUPPORTED_FILTER, "{fltr:?}"); + // Compared as bytes: a NaN setting is not equal to itself. + assert_eq!(item_for_filter(&f).unwrap().to_bytes(), item.to_bytes(), "{fltr:?}"); + } + // Radial Blur at its defaults has no `Fltr` (measured): its values are not stored, so the + // entry stays verbatim instead of guessing them. + let no_opts = Descriptor::new("filterFX").with("hasoptions", Value::Boolean(false)).with("filterID", Value::Integer(radial)); + assert_eq!(filter_from_item(&no_opts).command, UNSUPPORTED_FILTER); + // Settings with no PSD equivalent are errors when writing. + for (command, p) in [ + ("filter.blur.smartBlur", json!({"quality": "ultra"})), + ("filter.blur.smartBlur", json!({"mode": 3})), + ("filter.blur.radialBlur", json!({"method": "twirl"})), + ("filter.blur.radialBlur", json!({"quality": ["best"]})), + ("filter.blur.radialBlur", json!({"centerX": 0.25})), + ("filter.blur.radialBlur", json!({"centerY": 1.0})), + // A centre, or a value, that is there but can't be written as Photoshop would open it. + ("filter.blur.radialBlur", json!({"centerX": "middle"})), + ("filter.blur.radialBlur", json!({"centerY": true})), + ("filter.blur.radialBlur", json!({"amount": 0})), + ("filter.blur.radialBlur", json!({"amount": 101})), + ("filter.blur.radialBlur", json!({"amount": "10"})), + ("filter.blur.surfaceBlur", json!({"radius": 0.5})), + ("filter.blur.surfaceBlur", json!({"radius": 100.5})), + ("filter.blur.surfaceBlur", json!({"threshold": 1})), + ("filter.blur.surfaceBlur", json!({"threshold": 256})), + ("filter.blur.surfaceBlur", json!({"radius": "5"})), + ("filter.blur.smartBlur", json!({"radius": 0.05})), + ("filter.blur.smartBlur", json!({"threshold": 100.5})), + ("filter.blur.smartBlur", json!({"threshold": [25]})), + ] { + assert!(item_for_filter(&sf(command, p.clone())).is_err(), "{command} {p}"); + } + // Every value that is written opens again as the same editable filter (range ends included). + for (command, p) in [ + ("filter.blur.surfaceBlur", json!({"radius": 1.0, "threshold": 2})), + ("filter.blur.surfaceBlur", json!({"radius": 100.0, "threshold": 255})), + ("filter.blur.smartBlur", json!({"radius": 0.1, "threshold": 100.0, "quality": "low", "mode": "edgeOnly"})), + ("filter.blur.radialBlur", json!({"amount": 1, "method": "zoom", "quality": "best", "centerX": 0.5, "centerY": null})), + ("filter.blur.radialBlur", json!({"amount": 100, "method": "spin", "quality": "draft"})), + ] { + let back = filter_from_item(&item_for_filter(&sf(command, p.clone())).unwrap()); + assert_eq!(back.command, command, "{p}"); + } + // Hostile numbers write without panicking. + for p in [json!({"radius": f64::MAX, "threshold": -1e300, "amount": 1e300}), json!({"radius": "x", "threshold": null}), json!(null), json!([1, 2])] { + for command in ["filter.blur.surfaceBlur", "filter.blur.smartBlur", "filter.blur.radialBlur"] { + let _ = item_for_filter(&sf(command, p.clone())); + } + } +} + +/// A `filterFX` entry shaped as Photoshop saves it (measured in Photoshop: the filter applied +/// through Action Manager to a smart object, the PSD saved, `filterFX` read back). +fn photoshop_item(filter_id: &[u8; 4], fltr: Descriptor) -> Descriptor { + Descriptor::new("filterFX") + .with("Nm ", Value::Text(UnicodeString::new_nul("Filter..."))) + .with("blendOptions", blend_options(&sf("", J::Null))) + .with("enab", Value::Boolean(true)) + .with("hasoptions", Value::Boolean(true)) + .with("FrgC", rgbc(0.0)) + .with("BckC", rgbc(255.0)) + .with("Fltr", Value::Descriptor(fltr)) + .with("filterID", Value::Integer(code(filter_id))) +} + +#[test] +fn stylize_and_pixelate_filters_open_from_photoshop_shapes() { + let cases = [ + (b"Dfs ", Descriptor::new("Dfs ").with("Md ", enumv("DfsM", "Nrml")), "filter.stylize.diffuse", json!({"mode": "normal"})), + (b"Dfs ", Descriptor::new("Dfs ").with("Md ", enumv("DfsM", "DrkO")), "filter.stylize.diffuse", json!({"mode": "darkenOnly"})), + (b"Dfs ", Descriptor::new("Dfs ").with("Md ", enumv("DfsM", "LghO")), "filter.stylize.diffuse", json!({"mode": "lightenOnly"})), + (b"Dfs ", Descriptor::new("Dfs ").with("Md ", enumv("DfsM", "anisotropic")), "filter.stylize.diffuse", json!({"mode": "anisotropic"})), + ( + b"TrcC", + Descriptor::new("TrcC").with("Lvl ", Value::Integer(128)).with("Edg ", enumv("CntE", "Upr ")), + "filter.stylize.traceContour", + json!({"level": 128, "edge": "upper"}), + ), + ( + b"TrcC", + Descriptor::new("TrcC").with("Lvl ", Value::Integer(60)).with("Edg ", enumv("CntE", "Lwr ")), + "filter.stylize.traceContour", + json!({"level": 60, "edge": "lower"}), + ), + (b"Crst", Descriptor::new("Crst").with("ClSz", Value::Integer(10)), "filter.pixelate.crystallize", json!({"cellSize": 10})), + ( + b"Pntl", + Descriptor::new("Pntl").with("ClSz", Value::Integer(7)), + "filter.pixelate.pointillize", + json!({"cellSize": 7, "background": [1.0, 1.0, 1.0, 1.0]}), + ), + ]; + for (id, fltr, command, params) in cases { + let item = photoshop_item(id, fltr); + // Through bytes, as read from a file. + let f = filter_from_item(&Descriptor::from_bytes(&item.to_bytes()).unwrap()); + assert_eq!((f.command.as_str(), &f.params), (command, ¶ms)); + // Written back in the measured shape: same class, keys, value types and filterID. + let back = item_for_filter(&f).unwrap(); + for key in ["Fltr", "filterID", "BckC"] { + assert_eq!(back.get(key), item.get(key), "{command} {key}"); + } + } + // The `anisotropic` mode is a long id, as Photoshop writes it. + let d = item_for_filter(&sf("filter.stylize.diffuse", json!({"mode": "anisotropic"}))).unwrap(); + let Some(Value::Descriptor(fltr)) = d.get("Fltr") else { panic!("no Fltr") }; + assert!(matches!(fltr.get("Md "), Some(Value::Enumerated { value: Id::Str(v), .. }) if v == b"anisotropic")); + // Pointillize takes the entry's background colour; the others ignore it. + let mut item = photoshop_item(b"Pntl", Descriptor::new("Pntl").with("ClSz", Value::Integer(7))); + set(&mut item, "BckC", rgbc(51.0)); + let f = filter_from_item(&item); + assert_eq!(f.params["background"], json!([0.2, 0.2, 0.2, 1.0])); + assert_eq!(item_for_filter(&f).unwrap().get("BckC"), Some(&rgbc(51.0))); + let mut item = photoshop_item(b"Crst", Descriptor::new("Crst").with("ClSz", Value::Integer(7))); + set(&mut item, "BckC", rgbc(51.0)); + assert_eq!(filter_from_item(&item).params, json!({"cellSize": 7})); + // Our random seed has no PSD key: it is not written. + let fltr = |c: &str, p: J| item_for_filter(&sf(c, p)).unwrap().get("Fltr").cloned(); + assert_eq!( + fltr("filter.stylize.diffuse", json!({"mode": "normal", "seed": 7})), + Some(Value::Descriptor(Descriptor::new("Dfs ").with("Md ", enumv("DfsM", "Nrml")))) + ); + // Defaults and out-of-range values are written in Photoshop's ranges. + assert_eq!( + fltr("filter.stylize.traceContour", json!({})), + Some(Value::Descriptor(Descriptor::new("TrcC").with("Lvl ", Value::Integer(128)).with("Edg ", enumv("CntE", "Lwr ")))) + ); + assert_eq!(fltr("filter.pixelate.crystallize", json!({})), Some(Value::Descriptor(Descriptor::new("Crst").with("ClSz", Value::Integer(10))))); + assert_eq!(fltr("filter.pixelate.pointillize", json!({})), Some(Value::Descriptor(Descriptor::new("Pntl").with("ClSz", Value::Integer(5))))); + assert_eq!( + fltr("filter.pixelate.crystallize", json!({"cellSize": 1e9})), + Some(Value::Descriptor(Descriptor::new("Crst").with("ClSz", Value::Integer(300)))) + ); + assert_eq!( + fltr("filter.pixelate.pointillize", json!({"cellSize": "big"})), + Some(Value::Descriptor(Descriptor::new("Pntl").with("ClSz", Value::Integer(5)))) + ); + assert_eq!( + fltr("filter.stylize.traceContour", json!({"level": -40, "edge": "upper"})), + Some(Value::Descriptor(Descriptor::new("TrcC").with("Lvl ", Value::Integer(0)).with("Edg ", enumv("CntE", "Upr ")))) + ); +} + +#[test] +fn malformed_stylize_and_pixelate_filters_are_kept_verbatim() { + let long = Value::Integer; + let cases = [ + // Missing keys. + (b"Dfs ", Descriptor::new("Dfs ")), + (b"TrcC", Descriptor::new("TrcC").with("Lvl ", long(60))), + (b"TrcC", Descriptor::new("TrcC").with("Edg ", enumv("CntE", "Upr "))), + (b"Crst", Descriptor::new("Crst")), + (b"Pntl", Descriptor::new("Pntl")), + // Unknown enum values or enum types. + (b"Dfs ", Descriptor::new("Dfs ").with("Md ", enumv("DfsM", "Wild"))), + (b"Dfs ", Descriptor::new("Dfs ").with("Md ", enumv("BlnM", "Nrml"))), + (b"TrcC", Descriptor::new("TrcC").with("Lvl ", long(60)).with("Edg ", enumv("CntE", "Mddl"))), + // Wrong types (also NaN). + (b"Dfs ", Descriptor::new("Dfs ").with("Md ", long(1))), + (b"TrcC", Descriptor::new("TrcC").with("Lvl ", Value::Double(60.0)).with("Edg ", enumv("CntE", "Upr "))), + (b"Crst", Descriptor::new("Crst").with("ClSz", unit(b"#Pxl", 10.0))), + (b"Pntl", Descriptor::new("Pntl").with("ClSz", Value::Double(f64::NAN))), + // Out of range. + (b"TrcC", Descriptor::new("TrcC").with("Lvl ", long(256)).with("Edg ", enumv("CntE", "Upr "))), + (b"TrcC", Descriptor::new("TrcC").with("Lvl ", long(-1)).with("Edg ", enumv("CntE", "Upr "))), + (b"Crst", Descriptor::new("Crst").with("ClSz", long(2))), + (b"Pntl", Descriptor::new("Pntl").with("ClSz", long(i32::MAX))), + ]; + for (id, fltr) in cases { + let item = photoshop_item(id, fltr); + let f = filter_from_item(&Descriptor::from_bytes(&item.to_bytes()).unwrap()); + assert_eq!(f.command, UNSUPPORTED_FILTER, "{item:?}"); + assert_eq!(item_for_filter(&f).unwrap().to_bytes(), item.to_bytes()); + } + // Saved without options (`hasoptions` false, no `Fltr`): kept verbatim. + let bare = Descriptor::new("filterFX").with("hasoptions", Value::Boolean(false)).with("filterID", Value::Integer(code(b"Crst"))); + assert_eq!(filter_from_item(&bare).command, UNSUPPORTED_FILTER); + // A Pointillize entry whose background colour is unreadable is kept verbatim too. + for bad in [Value::Integer(3), Value::Descriptor(Descriptor::new("RGBC").with("Rd ", Value::Double(0.0)))] { + let mut item = photoshop_item(b"Pntl", Descriptor::new("Pntl").with("ClSz", Value::Integer(7))); + set(&mut item, "BckC", bad); + assert_eq!(filter_from_item(&item).command, UNSUPPORTED_FILTER); + } + // Values with no PSD equivalent are reported, not guessed. + for (c, p) in [ + ("filter.stylize.diffuse", json!({"mode": "sideways"})), + ("filter.stylize.diffuse", json!({"mode": 3})), + ("filter.stylize.traceContour", json!({"edge": "middle"})), + ("filter.pixelate.pointillize", json!({"background": "teal"})), + ("filter.pixelate.pointillize", json!({"background": [1.0]})), + ] { + assert!(item_for_filter(&sf(c, p.clone())).is_err(), "{c} {p}"); + } +} + +/// A Filter Gallery item as Photopea writes it (Chrome, Detail 12, Smoothness 4). +fn gallery_item_with(effects: Vec) -> Descriptor { + let rgb = |v: f64| Value::Descriptor(Descriptor::new("RGBC").with("Rd ", Value::Double(v)).with("Grn ", Value::Double(v)).with("Bl ", Value::Double(v))); + Descriptor::new("filterFX") + .with("Nm ", Value::Text(UnicodeString::new_nul("Filtergalerie"))) + .with("blendOptions", Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", 100.0)).with("Md ", enumv("BlnM", "normal")))) + .with("enab", Value::Boolean(true)) + .with("hasoptions", Value::Boolean(true)) + .with("FrgC", rgb(0.0)) + .with("BckC", rgb(255.0)) + .with("Fltr", Value::Descriptor(Descriptor::new("GEfc").with("GEfs", Value::List(effects.into_iter().map(Value::Descriptor).collect())))) + .with("filterID", Value::Integer(code(b"GEfc"))) +} + +fn chrome(detail: i32, smoothness: i32, visible: bool) -> Descriptor { + Descriptor::new("GEfc") + .with("Dtl ", Value::Integer(detail)) + .with("Smth", Value::Integer(smoothness)) + .with("GEfk", enumv("GEft", "Chrm")) + .with("GELv", Value::Boolean(visible)) +} + +#[test] +fn filter_gallery_chrome_imports_as_editable_gallery() { + let f = filter_from_item(&gallery_item_with(vec![chrome(12, 4, true), chrome(3, 9, false)])); + assert_eq!(f.command, "filter.filterGallery"); + assert_eq!( + f.params, + json!({ + "effects": [ + {"filter": "chrome", "params": {"detail": 12, "smoothness": 4}, "visible": true}, + {"filter": "chrome", "params": {"detail": 3, "smoothness": 9}, "visible": false}, + ], + "foreground": [0.0, 0.0, 0.0, 1.0], + "background": [1.0, 1.0, 1.0, 1.0], + }) + ); + // Written back and read again: unchanged, also when re-blended and hidden. + let mut g = f.clone(); + g.blend = BlendMode::Multiply; + g.opacity = 0.5; + g.visible = false; + let d = item_for_filter(&g).unwrap(); + assert_eq!(filter_from_item(&Descriptor::from_bytes(&d.to_bytes()).unwrap()), g); + let fltr = get_desc(&d, "Fltr").unwrap(); + assert!(fltr.class_id.is("GEfc")); + assert_eq!(int(&d, "filterID"), Some(code(b"GEfc"))); +} + +/// A single effect as Photoshop 27 writes it: inline in `Fltr`, no `GEfs` list or `GELv`. +fn photoshop_chrome(detail: i32, smoothness: i32) -> Descriptor { + let rgb = |v: f64| Value::Descriptor(Descriptor::new("RGBC").with("Rd ", Value::Double(v)).with("Grn ", Value::Double(v)).with("Bl ", Value::Double(v))); + let mut fltr = Descriptor::new("GEfc").with("GEfk", enumv("GEft", "Chrm")).with("Dtl ", Value::Integer(detail)).with("Smth", Value::Integer(smoothness)); + fltr.name = UnicodeString::new_nul("Filter Gallery"); + Descriptor::new("filterFX") + .with("Nm ", Value::Text(UnicodeString::new_nul("Filter Gallery..."))) + .with("blendOptions", Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", 100.0)).with("Md ", enumv("BlnM", "Nrml")))) + .with("enab", Value::Boolean(true)) + .with("hasoptions", Value::Boolean(true)) + .with("FrgC", rgb(255.0)) + .with("BckC", rgb(0.0)) + .with("Fltr", Value::Descriptor(fltr)) + .with("filterID", Value::Integer(code(b"GEfc"))) +} + +#[test] +fn filter_gallery_photoshop_inline_effect_imports_and_writes_back_inline() { + let item = photoshop_chrome(10, 4); + let f = filter_from_item(&item); + assert_eq!(f.command, "filter.filterGallery"); + assert_eq!( + f.params, + json!({ + "effects": [{"filter": "chrome", "params": {"detail": 10, "smoothness": 4}, "visible": true}], + "foreground": [1.0, 1.0, 1.0, 1.0], + "background": [0.0, 0.0, 0.0, 1.0], + }) + ); + // Written back in Photoshop's own layout. + let d = item_for_filter(&f).unwrap(); + assert_eq!(get_desc(&d, "Fltr"), get_desc(&item, "Fltr")); + assert_eq!((get_desc(&d, "FrgC"), get_desc(&d, "BckC")), (get_desc(&item, "FrgC"), get_desc(&item, "BckC"))); + assert_eq!(filter_from_item(&Descriptor::from_bytes(&d.to_bytes()).unwrap()), f); + // A hidden single effect needs the list (only it has a visibility flag). + let mut hidden = f.clone(); + hidden.params["effects"][0]["visible"] = json!(false); + let d = item_for_filter(&hidden).unwrap(); + assert!(get_desc(&d, "Fltr").unwrap().get("GEfs").is_some()); + assert_eq!(filter_from_item(&d), hidden); + // Inline effects we don't model stay verbatim. + let mut odd = photoshop_chrome(10, 4); + set(&mut odd, "Fltr", Value::Descriptor(Descriptor::new("GEfc").with("GEfk", enumv("GEft", "Ctot")).with("Dtl ", Value::Integer(1)))); + assert_eq!(filter_from_item(&odd).command, UNSUPPORTED_FILTER); + let mut extra = photoshop_chrome(10, 4); + set(&mut extra, "Fltr", Value::Descriptor(Descriptor::new("GEfc").with("GEfk", enumv("GEft", "Chrm")).with("Xtra", Value::Integer(1)))); + assert_eq!(filter_from_item(&extra).command, UNSUPPORTED_FILTER); +} + +#[test] +fn gallery_table_matches_the_gallery_filters() { + for g in &GALLERY_EFFECTS { + let f = photocraft_algo::GalleryFilter::from_key(g.key).unwrap(); + let keys: Vec<&str> = f.params().iter().map(|p| p.key).collect(); + for (_, ours) in g.settings { + assert!(keys.contains(ours), "{}.{ours}", g.key); + } + } +} + +#[test] +fn filter_gallery_written_with_defaults_and_colours() { + let f = sf("filter.filterGallery", json!({"effects": [{"filter": "chrome"}], "foreground": "#ff0000", "background": [0.0, 0.0, 1.0, 1.0]})); + let back = filter_from_item(&item_for_filter(&f).unwrap()); + assert_eq!(back.params["effects"][0]["params"], json!({"detail": 4, "smoothness": 7})); + assert_eq!(back.params["foreground"], json!([1.0, 0.0, 0.0, 1.0])); + assert_eq!(back.params["background"], json!([0.0, 0.0, 1.0, 1.0])); +} + +#[test] +fn filter_gallery_we_dont_model_is_kept_verbatim() { + // Another effect, an extra setting, a wrong-typed setting, no effects, a non-list. + let other = Descriptor::new("GEfc").with("GEfk", enumv("GEft", "Ctot")).with("GELv", Value::Boolean(true)); + let extra = chrome(4, 7, true).with("Xtra", Value::Integer(1)); + let typed = Descriptor::new("GEfc").with("Dtl ", Value::Double(4.0)).with("GEfk", enumv("GEft", "Chrm")); + for effects in [vec![chrome(4, 7, true), other], vec![extra], vec![typed], vec![]] { + let item = gallery_item_with(effects); + let f = filter_from_item(&item); + assert_eq!(f.command, UNSUPPORTED_FILTER); + assert_eq!(item_for_filter(&f).unwrap(), item); + } + let odd = Descriptor::new("filterFX").with("Fltr", Value::Descriptor(Descriptor::new("GEfc").with("GEfs", Value::Integer(3)))); + assert_eq!(filter_from_item(&odd).command, UNSUPPORTED_FILTER); + let bare = Descriptor::new("filterFX").with("filterID", Value::Integer(code(b"GEfc"))); + assert_eq!(filter_from_item(&bare).command, UNSUPPORTED_FILTER); +} + +#[test] +fn filter_gallery_without_psd_equivalent_is_reported() { + for p in [ + json!({"effects": [{"filter": "cutout"}]}), + json!({"effects": [{"filter": "chrome", "params": {"sparkle": 1}}]}), + json!({"effects": [{"params": {}}]}), + json!({"effects": []}), + json!({}), + json!({"effects": [{"filter": "chrome"}], "list": true}), + json!({"effects": [{"filter": "chrome"}], "foreground": "red"}), + json!(null), + ] { + assert!(item_for_filter(&sf("filter.filterGallery", p.clone())).is_err(), "{p}"); + } +} + +/// Filters with no PSD equivalent are skipped with a warning each, and the writable ones around them still export. +#[test] +fn unwritable_filters_are_reported_not_fatal() { + let stack = FilterStack { + filters: vec![ + // Shear's curve isn't mapped to Photoshop's grid yet. + sf("filter.distort.shear", json!({"amount": 40})), + sf("filter.blur.gaussianBlur", json!({"radius": 2.0})), + sf(UNSUPPORTED_FILTER, json!({"psd": "zz"})), + sf("image.adjustments.levels", json!({"cyan": {"gamma": 2.0}})), + sf("image.adjustments.shadowsHighlights", json!({"shadowAmount": 50})), + ], + ..Default::default() + }; + let mut w = Vec::new(); + let d = filter_fx(&stack, "L", &mut w); + assert_eq!(w.len(), 4, "{w:?}"); + let back = filter_stack(&d); + assert_eq!(back.filters, vec![stack.filters[1].clone()]); +} + +#[test] +fn placed_blocks_parse_back() { + let t = Affine { m: [0.5, 0.1, -0.1, 0.5, 10.0, 20.0] }; + let stack = FilterStack { enabled: false, filters: vec![sf("filter.blur.gaussianBlur", json!({"radius": 3.0}))], mask_enabled: false, mask_linked: true }; + let mut w = Vec::new(); + let spec = PlacedSpec { + idnt: "id-1", + placed: "pl-2", + transform: t, + perspective: None, + size: (64.0, 32.0), + dpi: 72.0, + warp: None, + filter_fx: Some(filter_fx(&stack, "L", &mut w)), + }; + let sold = sold_bytes(None, &spec, &mut w); + assert!(w.is_empty()); + assert_eq!(sold.len() % 4, 0); + let p = parse_sold(&sold).unwrap(); + assert_eq!((p.idnt.as_str(), p.placed.as_str()), ("id-1", "pl-2")); + for (a, b) in p.transform.m.iter().zip(t.m) { + assert!((a - b).abs() < 1e-9); + } + assert_eq!(p.stack, Some(stack)); + let tb = photocraft_psd::TaggedBlock::new(*b"SoLd", sold.clone()); + tb.check_structure().unwrap(); + let pl = photocraft_psd::TaggedBlock::new(*b"PlLd", plld_bytes(&spec, &mut w)); + pl.check_structure().unwrap(); + // A template keeps its other keys; an unmoved transform keeps its exact quad. + let mut tmpl = sold_descriptor(&sold).unwrap(); + tmpl.items.push((Id::new("extraKey"), Value::Integer(7))); + let again = sold_bytes(Some(&tmpl), &PlacedSpec { filter_fx: None, ..spec }, &mut w); + let d = sold_descriptor(&again).unwrap(); + assert_eq!(d.get("extraKey"), Some(&Value::Integer(7))); + assert!(d.get("filterFX").is_none()); + assert_eq!(d.get("Trnf"), tmpl.get("Trnf")); +} + +/// A Distort / Perspective placement goes out as its four corners (`Trnf`, `nonAffineTransform`) +/// and comes back as the same projective map; an affine one reads back as no perspective. +#[test] +fn perspective_placement_round_trips_through_sold() { + let h = photocraft_algo::transform::Homography::rect_to_quad([0.0, 0.0, 64.0, 32.0], [[10.0, 5.0], [80.0, 8.0], [70.0, 50.0], [12.0, 40.0]]).unwrap(); + let mut w = Vec::new(); + let mut spec = PlacedSpec { + idnt: "id", + placed: "pl", + transform: Affine::IDENTITY, + perspective: Some(h.0), + size: (64.0, 32.0), + dpi: 72.0, + warp: None, + filter_fx: None, + }; + let sold = sold_bytes(None, &spec, &mut w); + let back = crate::blocks::parse_smart_perspective(b"SoLd", &sold).expect("a projective placement"); + let n = |m: [f64; 9]| m.map(|v| v / m[8]); + for (a, b) in n(back).iter().zip(n(h.0)) { + assert!((a - b).abs() < 1e-9 * (1.0 + b.abs()), "{back:?} vs {:?}", h.0); + } + // Affine placements carry no perspective. + spec.perspective = None; + spec.transform = Affine { m: [2.0, 0.0, 0.0, 2.0, 5.0, 7.0] }; + let sold = sold_bytes(None, &spec, &mut w); + assert_eq!(crate::blocks::parse_smart_perspective(b"SoLd", &sold), None); + assert_eq!(crate::blocks::parse_smart_perspective(b"PlLd", &sold), None); +} + +/// `quad_moved` compares the corners a template stores with the placement's: unchanged keeps +/// the template's quad, a moved corner (affine or projective) or a missing quad rewrites it. +#[test] +fn quad_moved_detects_corner_changes() { + let t = Affine { m: [1.0, 0.0, 0.0, 1.0, 3.0, 4.0] }; + let mut w = Vec::new(); + let mut spec = PlacedSpec { idnt: "id", placed: "pl", transform: t, perspective: None, size: (20.0, 10.0), dpi: 72.0, warp: None, filter_fx: None }; + let template = parse_sold(&sold_bytes(None, &spec, &mut w)).expect("parses").descriptor; + assert!(!quad_moved(&template, &spec, spec.warp), "same placement"); + spec.transform = Affine { m: [1.0, 0.0, 0.0, 1.0, 3.5, 4.0] }; + assert!(quad_moved(&template, &spec, spec.warp), "moved half a pixel"); + spec.transform = t; + spec.perspective = + photocraft_algo::transform::Homography::rect_to_quad([0.0, 0.0, 20.0, 10.0], [[3.0, 4.0], [23.0, 4.0], [20.0, 12.0], [3.0, 14.0]]).map(|h| h.0); + assert!(quad_moved(&template, &spec, spec.warp), "one corner moved (Distort)"); + assert!(quad_moved(&Descriptor::new("null"), &spec, spec.warp), "no stored quad"); +} + +/// Corrupted placed-layer data and filter descriptors never panic: they parse to something +/// (unknown filters stay verbatim) or to nothing. +#[test] +fn mutated_placed_data_never_panics() { + let stack = FilterStack { + filters: vec![ + sf("filter.blur.gaussianBlur", json!({"radius": 3.0})), + sf("image.adjustments.curves", json!({"points": [[0.0, 0.0], [255.0, 255.0]]})), + sf("image.adjustments.levels", json!({"inBlack": 3, "inWhite": 250, "gamma": 1.1})), + ], + ..Default::default() + }; + let mut w = Vec::new(); + let spec = PlacedSpec { + idnt: "id", + placed: "pl", + transform: Affine::IDENTITY, + perspective: None, + size: (8.0, 8.0), + dpi: 72.0, + warp: None, + filter_fx: Some(filter_fx(&stack, "L", &mut w)), + }; + let sold = sold_bytes(None, &spec, &mut w); + let mut state = 0x2545_F491_4F6C_DD1Du64; + let mut next = || { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state + }; + for _ in 0..3000 { + let mut b = sold.clone(); + for _ in 0..1 + next() % 3 { + let i = (next() as usize) % b.len(); + b[i] = next() as u8; + } + if let Some(p) = parse_sold(&b) { + for f in p.stack.iter().flat_map(|s| &s.filters) { + let _ = item_for_filter(f); + } + let _ = sold_bytes(Some(&p.descriptor), &spec, &mut w); + } + } +} + +#[test] +fn warps_are_written_and_read_back() { + use photocraft_geom::warp::BezierMesh; + let bounds = [0.0, 0.0, 60.0, 30.0]; + let mut custom = BezierMesh::identity(bounds, 1, 1); + custom.points[15] = [67.0, 30.0]; + let mut multi = Warp::preset(WarpStyle::Custom, 0.0, bounds); + let mut split = BezierMesh::identity(bounds, 2, 2); + split.points[8][1] += 4.0; + multi.mesh = Some(split); + let mut arc = Warp::preset(WarpStyle::Arc, 40.0, bounds); + arc.vertical = true; + arc.h_distort = 10.0; + let mut c = Warp::preset(WarpStyle::Custom, 0.0, bounds); + c.mesh = Some(custom); + for (w, back) in [(Some(arc.clone()), Some(arc)), (Some(c.clone()), Some(c)), (Some(multi.clone()), Some(multi)), (None, None)] { + let mut warnings = Vec::new(); + let spec = PlacedSpec { + idnt: "i", + placed: "p", + transform: Affine::IDENTITY, + perspective: None, + size: (60.0, 30.0), + dpi: 72.0, + warp: w.as_ref(), + filter_fx: None, + }; + let sold = sold_bytes(None, &spec, &mut warnings); + assert_eq!(crate::blocks::parse_placed_warp(b"SoLd", &sold), back); + assert!(warnings.is_empty(), "{warnings:?}"); + } +} + +/// A placed layer over a 50 × 25 source, at `transform`, with `warp`. +fn placed<'a>(transform: Affine, warp: Option<&'a Warp>) -> PlacedSpec<'a> { + PlacedSpec { idnt: "i", placed: "p", transform, perspective: None, size: (50.0, 25.0), dpi: 72.0, warp, filter_fx: None } +} + +/// A 3 × 2 patch split warp over the 50 × 25 source with one interior control point pulled. +fn split_warp() -> Warp { + use photocraft_geom::warp::BezierMesh; + let mut mesh = BezierMesh::identity([0.0, 0.0, 50.0, 25.0], 3, 2); + mesh.points[10 * 3 + 4][1] += 3.0; + Warp::custom(mesh, [0.0, 0.0, 50.0, 25.0]) +} + +/// An imported `soLD` descriptor holding `warp` as Photoshop writes a split warp: a +/// `quiltWarp` whose outer slices sit 0.6 px past the source, before a `warpNone` `warp`. +fn photoshop_template(warp: &Warp) -> Descriptor { + let mesh = warp.mesh.as_ref().expect("a mesh"); + let slices = |k: &str, knots: &[f64], len: f64| { + let n = knots.len() - 1; + let values = knots + .iter() + .enumerate() + .map(|(i, u)| { + if i == 0 { + -0.6 + } else if i == n { + len + 0.6 + } else { + u * len + } + }) + .collect::>(); + let prefix = values.len() as u32; + Value::ObjectArray(ObjectArray { prefix, body: Descriptor::new("UntF").with(k, Value::UnitFloats { unit: *b"#Pxl", values }) }) + }; + let Value::Descriptor(plain) = warp_desc(None, (50.0, 25.0), &mut Vec::new()) else { panic!("a descriptor") }; + let mut quilt = plain.clone(); + quilt.class_id = Id::new("quiltWarp"); + set(&mut quilt, "warpStyle", enumv("warpStyle", "warpCustom")); + let points = Descriptor::new("rationalPoint") + .with("Hrzn", Value::UnitFloats { unit: *b"#Pxl", values: mesh.points.iter().map(|p| p[0]).collect() }) + .with("Vrtc", Value::UnitFloats { unit: *b"#Pxl", values: mesh.points.iter().map(|p| p[1]).collect() }); + let envelope = Descriptor::new("customEnvelopeWarp") + .with("quiltSliceX", slices("quiltSliceX", &mesh.us, 50.0)) + .with("quiltSliceY", slices("quiltSliceY", &mesh.vs, 25.0)) + .with("meshPoints", Value::ObjectArray(ObjectArray { prefix: mesh.points.len() as u32, body: points })); + quilt = quilt + .with("deformNumRows", Value::Integer(mesh.ny() as i32)) + .with("deformNumCols", Value::Integer(mesh.nx() as i32)) + .with("customEnvelopeWarp", Value::Descriptor(envelope)); + let mut d = sold_descriptor(&sold_bytes(None, &placed(Affine::IDENTITY, None), &mut Vec::new())).expect("a descriptor"); + let at = d.items.iter().position(|(k, _)| k.is("warp")).expect("a warp key"); + d.items.insert(at, (Id::new("quiltWarp"), Value::Descriptor(quilt))); + d +} + +fn sold_of(d: Descriptor) -> Vec { + let mut out = b"soLD".to_vec(); + out.extend_from_slice(&4u32.to_be_bytes()); + out.extend(VersionedDescriptor::new(d).to_bytes()); + out +} + +fn quilt_of(d: &Descriptor) -> Option<&Descriptor> { + get_desc(d, "quiltWarp") +} + +/// A split warp of more patches along a side than a `quiltWarp` is read with (Warp Grid 64, +/// then one more split) is written as no warp, with a message, framed by the source rect, so +/// the layer reopens where it was. Before, its `quiltWarp` was refused on reopen while `Trnf` +/// still framed its control box: the layer came back stretched and shifted. +#[test] +fn a_split_warp_past_the_quilt_limit_keeps_its_placement() { + use photocraft_geom::warp::BezierMesh; + let mut mesh = BezierMesh::identity([0.0, 0.0, 50.0, 25.0], crate::blocks::QUILT_MAX_PATCHES, 1); + assert!(mesh.split_u(0.005)); + mesh.points[0] = [-10.0, -5.0]; + let warp = Warp::custom(mesh, [0.0, 0.0, 50.0, 25.0]); + let transform = Affine { m: [2.0, 0.0, 0.0, 2.0, 120.0, 210.0] }; + let mut warnings = Vec::new(); + let sold = sold_bytes(None, &placed(transform, Some(&warp)), &mut warnings); + assert_eq!(warnings.len(), 1, "{warnings:?}"); + assert_eq!(crate::blocks::parse_smart(b"SoLd", &sold).1, transform); + assert_eq!(crate::blocks::parse_placed_warp(b"SoLd", &sold), None); + assert!(quilt_of(&sold_descriptor(&sold).expect("a descriptor")).is_none()); + // Over an imported split warp, the stale `quiltWarp` goes and the placement holds. + let template = photoshop_template(&split_warp()); + let mut warnings = Vec::new(); + let sold = sold_bytes(Some(&template), &placed(transform, Some(&warp)), &mut warnings); + assert_eq!(warnings.len(), 1, "{warnings:?}"); + assert_eq!(crate::blocks::parse_smart(b"SoLd", &sold).1, transform); + assert!(quilt_of(&sold_descriptor(&sold).expect("a descriptor")).is_none()); + // So does one this reader can't read, which Photoshop would still apply. + let mut template = photoshop_template(&split_warp()); + let Some((_, Value::Descriptor(q))) = template.items.iter_mut().find(|(k, _)| k.is("quiltWarp")) else { panic!("a quiltWarp") }; + set(q, "deformNumRows", Value::Integer(0)); + let sold = sold_bytes(Some(&template), &placed(transform, Some(&warp)), &mut Vec::new()); + assert!(quilt_of(&sold_descriptor(&sold).expect("a descriptor")).is_none()); + // At the limit the split warp is still written. + let mut mesh = BezierMesh::identity([0.0, 0.0, 50.0, 25.0], crate::blocks::QUILT_MAX_PATCHES, 1); + mesh.points[0] = [-10.0, -5.0]; + let warp = Warp::custom(mesh, [0.0, 0.0, 50.0, 25.0]); + let mut warnings = Vec::new(); + let sold = sold_bytes(None, &placed(transform, Some(&warp)), &mut warnings); + assert!(warnings.is_empty(), "{warnings:?}"); + assert_eq!(crate::blocks::parse_smart(b"SoLd", &sold).1, transform); + assert_eq!(crate::blocks::parse_placed_warp(b"SoLd", &sold), Some(warp)); +} + +/// A split (multi-patch) custom warp is written as Photoshop writes it, a `quiltWarp` before a +/// `warpNone` `warp`, and reads back with its mesh and its transform. Before, the warp was +/// written as none while `Trnf` was still the image of its control-point box, so the layer +/// came back stretched and shifted. +#[test] +fn split_warp_round_trips_through_sold() { + use photocraft_geom::warp::BezierMesh; + let mut mesh = BezierMesh::identity([0.0, 0.0, 50.0, 25.0], 2, 1); + mesh.points[0] = [-10.0, -5.0]; + let warp = Warp::custom(mesh, [0.0, 0.0, 50.0, 25.0]); + let transform = Affine { m: [2.0, 0.0, 0.0, 2.0, 120.0, 210.0] }; + let mut warnings = Vec::new(); + let sold = sold_bytes(None, &placed(transform, Some(&warp)), &mut warnings); + assert!(warnings.is_empty(), "{warnings:?}"); + assert_eq!(crate::blocks::parse_smart(b"SoLd", &sold).1, transform); + assert_eq!(crate::blocks::parse_placed_warp(b"SoLd", &sold), Some(warp)); + let d = sold_descriptor(&sold).expect("a descriptor"); + let at = |key: &str| d.items.iter().position(|(k, _)| k.is(key)); + assert!(at("quiltWarp").expect("a quiltWarp") < at("warp").expect("a warp")); + let plain = get_desc(&d, "warp").expect("a warp"); + assert_eq!(enum_of(plain, "warpStyle"), Some(&b"warpNone"[..])); + assert!(plain.get("customEnvelopeWarp").is_none()); + let quilt = quilt_of(&d).expect("a quiltWarp"); + assert!(quilt.class_id.is("quiltWarp")); + assert_eq!((quilt.get("deformNumCols"), quilt.get("deformNumRows")), (Some(&Value::Integer(7)), Some(&Value::Integer(4)))); + let env = get_desc(quilt, "customEnvelopeWarp").expect("an envelope"); + let prefix = |k: &str| match env.get(k) { + Some(Value::ObjectArray(a)) => Some(a.prefix), + _ => None, + }; + assert_eq!((prefix("quiltSliceX"), prefix("quiltSliceY"), prefix("meshPoints")), (Some(3), Some(2), Some(28))); +} + +/// A template's split warp is replaced along with its `warp`: a warp changed to Arc, to none, +/// to one patch or to another mesh reads back as changed, not as the imported split warp. +#[test] +fn a_replaced_split_warp_does_not_come_back() { + use photocraft_geom::warp::BezierMesh; + let bounds = [0.0, 0.0, 50.0, 25.0]; + let split = split_warp(); + let template = photoshop_template(&split); + let arc = Warp::preset(WarpStyle::Arc, 30.0, bounds); + let mut one = BezierMesh::identity(bounds, 1, 1); + one.points[5][0] += 2.0; + let one = Warp::custom(one, bounds); + let mut resplit = BezierMesh::identity(bounds, 2, 2); + resplit.points[8][1] += 4.0; + let resplit = Warp::custom(resplit, bounds); + for w in [Some(arc), None, Some(one), Some(resplit)] { + let mut warnings = Vec::new(); + let sold = sold_bytes(Some(&template), &placed(Affine::IDENTITY, w.as_ref()), &mut warnings); + assert_eq!(crate::blocks::parse_placed_warp(b"SoLd", &sold), w); + let d = sold_descriptor(&sold).expect("a descriptor"); + assert_eq!(quilt_of(&d).is_some(), w.as_ref().is_some_and(|w| w.mesh.as_ref().is_some_and(|m| m.points.len() > 16)), "{w:?}"); + assert!(warnings.is_empty(), "{warnings:?}"); + } +} + +/// An imported split warp that nothing changed keeps Photoshop's `quiltWarp` as stored when +/// the layer is rewritten for something else (here a move); a mesh edited on the same grid +/// keeps Photoshop's slices. +#[test] +fn an_imported_split_warp_keeps_photoshop_s_quilt() { + let template = photoshop_template(&split_warp()); + let read = crate::blocks::parse_placed_warp(b"SoLd", &sold_of(template.clone())).expect("the split warp"); + let moved = Affine { m: [1.0, 0.0, 0.0, 1.0, 4.0, 0.0] }; + let sold = sold_bytes(Some(&template), &placed(moved, Some(&read)), &mut Vec::new()); + let d = sold_descriptor(&sold).expect("a descriptor"); + assert_eq!(d.get("quiltWarp"), template.get("quiltWarp")); + assert_eq!(crate::blocks::parse_smart(b"SoLd", &sold).1, moved); + let mut edited = read.clone(); + if let Some(m) = edited.mesh.as_mut() { + m.points[12][0] += 1.5; + } + let sold = sold_bytes(Some(&template), &placed(Affine::IDENTITY, Some(&edited)), &mut Vec::new()); + assert_eq!(crate::blocks::parse_placed_warp(b"SoLd", &sold), Some(edited)); + let slices = |d: &Descriptor| { + let env = get_desc(quilt_of(d)?, "customEnvelopeWarp")?; + Some((env.get("quiltSliceX").cloned(), env.get("quiltSliceY").cloned())) + }; + assert_eq!(slices(&sold_descriptor(&sold).expect("a descriptor")), slices(&template)); +} + +/// The legacy `PlLd` record has no split warp: it stores none, with its corners framed by the +/// source rect, so a reader of `PlLd` alone places the layer where its transform puts it. +#[test] +fn plld_of_a_split_warp_is_framed_by_the_source() { + let warp = split_warp(); + let transform = Affine { m: [2.0, 0.0, 0.0, 2.0, 120.0, 210.0] }; + let mut warnings = Vec::new(); + let plld = plld_bytes(&placed(transform, Some(&warp)), &mut warnings); + assert!(warnings.is_empty(), "{warnings:?}"); + assert_eq!(crate::blocks::parse_plld_warp(&plld), crate::blocks::PlldWarp::None); + let (_, corners) = crate::blocks::parse_plld(&plld).expect("a record"); + assert_eq!(crate::blocks::plld_transform(&corners, Some((50.0, 25.0)), None).0, transform); +} + +/// Export writes `Trnf` as the image of the custom warp's control-point box, the inverse of +/// import: a spilled mesh comes back with the same transform and the quad Photoshop expects. +#[test] +fn warp_control_box_quad_round_trips() { + use photocraft_geom::warp::BezierMesh; + let mut mesh = BezierMesh::identity([0.0, 0.0, 50.0, 25.0], 1, 1); + mesh.points[0] = [-10.0, -5.0]; + mesh.points[15] = [60.0, 25.0]; + let mut warp = Warp::preset(WarpStyle::Custom, 0.0, [0.0, 0.0, 50.0, 25.0]); + warp.mesh = Some(mesh); + let transform = Affine { m: [2.0, 0.0, 0.0, 2.0, 120.0, 210.0] }; + let spec = PlacedSpec { idnt: "i", placed: "p", transform, perspective: None, size: (50.0, 25.0), dpi: 72.0, warp: Some(&warp), filter_fx: None }; + let sold = sold_bytes(None, &spec, &mut Vec::new()); + let p = parse_sold(&sold).expect("parses"); + let Some(Value::List(q)) = p.descriptor.get("Trnf") else { panic!("no Trnf") }; + let q: Vec = q.iter().filter_map(|v| num(Some(v))).collect(); + assert_eq!(q, [100.0, 200.0, 240.0, 200.0, 240.0, 260.0, 100.0, 260.0]); + assert_eq!(p.transform, transform); + // The imported quad reads as unmoved, so the template's `Trnf` is kept as stored. + assert!(!quad_moved(&p.descriptor, &spec, spec.warp)); +} + +/// #4112: a regenerated `SoLd` (after Replace Contents, a move…) writes a cylinder back as +/// `warpCylinder` and its seven values, not as no warp, and frames its control-point box with +/// the quad, affine or projective, so import places it where it was. +#[test] +fn cylinder_warp_round_trips_through_sold() { + let v = [100.0, 800.0, 900.0, 200.0, 0.3, 0.3, 0.5]; + let warp = Warp::cylinder(&v, [0.0, 0.0, 1000.0, 1000.0]).unwrap(); + let transform = Affine { m: [0.5, 0.0, 0.0, 0.5, 40.0, 30.0] }; + let mut spec = PlacedSpec { idnt: "i", placed: "p", transform, perspective: None, size: (1000.0, 1000.0), dpi: 72.0, warp: Some(&warp), filter_fx: None }; + let mut warnings = Vec::new(); + let sold = sold_bytes(None, &spec, &mut warnings); + assert!(warnings.is_empty(), "{warnings:?}"); + let p = parse_sold(&sold).expect("parses"); + let Some(Value::Descriptor(w)) = p.descriptor.get("warp") else { panic!("no warp") }; + assert_eq!(crate::blocks::enum_of(w, "warpStyle"), Some(b"warpCylinder".as_slice())); + let Some(Value::List(values)) = w.get("warpValues") else { panic!("no warpValues") }; + assert_eq!(values.iter().filter_map(|x| num(Some(x))).collect::>(), v); + assert!(w.get("customEnvelopeWarp").is_none()); + assert_eq!(crate::blocks::parse_placed_warp(b"SoLd", &sold), Some(warp.clone())); + for (a, b) in p.transform.m.iter().zip(transform.m) { + assert!((a - b).abs() < 1e-9, "{:?}", p.transform); + } + // The quad is the image of the control-point box, not of the source rect. + let cb = warp.mesh.as_ref().unwrap().control_bounds(); + let Some(Value::List(q)) = p.descriptor.get("Trnf") else { panic!("no Trnf") }; + let q: Vec = q.iter().filter_map(|x| num(Some(x))).collect(); + let want = [cb[0], cb[1], cb[2], cb[1], cb[2], cb[3], cb[0], cb[3]].map(|c| 0.5 * c); + for (i, (a, b)) in q.iter().zip(want).enumerate() { + let shift = if i % 2 == 0 { 40.0 } else { 30.0 }; + assert!((a - (b + shift)).abs() < 1e-9, "corner {i}: {q:?}"); + } + assert!(!quad_moved(&p.descriptor, &spec, spec.warp)); + // A projective placement comes back as the same map. + let h = photocraft_algo::transform::Homography::rect_to_quad(cb, [[10.0, 20.0], [410.0, 60.0], [400.0, 480.0], [30.0, 520.0]]).unwrap(); + spec.perspective = Some(h.0); + let sold = sold_bytes(None, &spec, &mut warnings); + let back = crate::blocks::parse_smart_perspective(b"SoLd", &sold).expect("projective"); + let n = |m: [f64; 9]| m.map(|x| x / m[8]); + for (a, b) in n(back).iter().zip(n(h.0)) { + assert!((a - b).abs() < 1e-9 * (1.0 + b.abs()), "{back:?} vs {:?}", h.0); + } + let plld = plld_bytes(&spec, &mut warnings); + assert_eq!(crate::blocks::parse_plld_warp(&plld), crate::blocks::PlldWarp::Warp(warp)); + assert!(warnings.is_empty(), "{warnings:?}"); +} + +#[test] +fn hex_and_uuid() { + assert_eq!(from_hex(&to_hex(&[0, 1, 0xab, 0xff])), Some(vec![0, 1, 0xab, 0xff])); + assert_eq!(from_hex("abc"), None); + assert_eq!(from_hex("zz"), None); + let u = uuid_from(b"x"); + assert_eq!(u.len(), 36); + assert_eq!(u, uuid_from(b"x")); + assert_ne!(u, uuid_from(b"y")); +} + +// Render filters as Photoshop 27 saves them on a smart object (`filterFXList` items, with +// neutral blending): Clouds and Difference Clouds in white on black, Fibers in black on white, +// Lens Flare with the 50-300mm Zoom at 159%. +const PHOTOSHOP_CLOUDS: &str = "0000000100000000000866696c746572465800000008000000004e6d202054455854000000070043006c006f00750064007300000000000c626c656e644f7074696f6e734f626a63000000000000000c626c656e644f7074696f6e7300000002000000004f706374556e7446235072634059000000000000000000004d642020656e756d00000000426c6e4d000000066e6f726d616c00000000656e6162626f6f6c010000000a6861736f7074696f6e73626f6f6c0100000000467267434f626a630000000100000000000052474243000000030000000052642020646f7562406fe000000000000000000047726e20646f7562406fe0000000000000000000426c2020646f7562406fe000000000000000000042636b434f626a630000000100000000000052474243000000030000000052642020646f756200000000000000000000000047726e20646f7562000000000000000000000000426c2020646f7562000000000000000000000000466c74724f626a63000000070043006c006f007500640073000000000000436c64730000000100000000466c52736c6f6e67000049e40000000866696c74657249446c6f6e67436c6473"; +const PHOTOSHOP_DIFFERENCE_CLOUDS: &str = "0000000100000000000866696c746572465800000008000000004e6d202054455854000000120044006900660066006500720065006e0063006500200043006c006f00750064007300000000000c626c656e644f7074696f6e734f626a63000000000000000c626c656e644f7074696f6e7300000002000000004f706374556e7446235072634059000000000000000000004d642020656e756d00000000426c6e4d000000066e6f726d616c00000000656e6162626f6f6c010000000a6861736f7074696f6e73626f6f6c0100000000467267434f626a630000000100000000000052474243000000030000000052642020646f7562406fe000000000000000000047726e20646f7562406fe0000000000000000000426c2020646f7562406fe000000000000000000042636b434f626a630000000100000000000052474243000000030000000052642020646f756200000000000000000000000047726e20646f7562000000000000000000000000426c2020646f7562000000000000000000000000466c74724f626a63000000120044006900660066006500720065006e0063006500200043006c006f007500640073000000000000446672430000000100000000466c52736c6f6e67000057d20000000866696c74657249446c6f6e6744667243"; +const PHOTOSHOP_FIBERS: &str = "0000000100000000000866696c746572465800000008000000004e6d2020544558540000000a004600690062006500720073002e002e002e00000000000c626c656e644f7074696f6e734f626a63000000000000000c626c656e644f7074696f6e7300000002000000004f706374556e7446235072634059000000000000000000004d642020656e756d00000000426c6e4d000000066e6f726d616c00000000656e6162626f6f6c010000000a6861736f7074696f6e73626f6f6c0100000000467267434f626a630000000100000000000052474243000000030000000052642020646f756200000000000000000000000047726e20646f7562000000000000000000000000426c2020646f756200000000000000000000000042636b434f626a630000000100000000000052474243000000030000000052642020646f7562406fe000000000000000000047726e20646f7562406fe0000000000000000000426c2020646f7562406fe0000000000000000000466c74724f626a630000000700460069006200650072007300000000000046627273000000030000000056726e636c6f6e670000001000000000537472676c6f6e670000000400000000526e64536c6f6e67000062f10000000866696c74657249446c6f6e6746627273"; +const PHOTOSHOP_LENS_FLARE: &str = "0000000100000000000866696c746572465800000008000000004e6d2020544558540000000e004c0065006e007300200046006c006100720065002e002e002e00000000000c626c656e644f7074696f6e734f626a63000000000000000c626c656e644f7074696f6e7300000002000000004f706374556e7446235072634059000000000000000000004d642020656e756d00000000426c6e4d000000066e6f726d616c00000000656e6162626f6f6c010000000a6861736f7074696f6e73626f6f6c0100000000467267434f626a630000000100000000000052474243000000030000000052642020646f756200000000000000000000000047726e20646f7562000000000000000000000000426c2020646f756200000000000000000000000042636b434f626a630000000100000000000052474243000000030000000052642020646f7562406fe000000000000000000047726e20646f7562406fe0000000000000000000426c2020646f7562406fe0000000000000000000466c74724f626a630000000b004c0065006e007300200046006c0061007200650000000000004c6e73460000000300000000427267686c6f6e670000009f00000000466c72434f626a6300000001000000000000506e7420000000020000000048727a6e646f75623fe86666600000000000000056727463646f75623fe60b60c0000000000000004c6e7320656e756d000000004c6e7320000000005a6d20200000000866696c74657249446c6f6e674c6e7346"; + +fn photoshop(hex: &str) -> Descriptor { + Descriptor::from_bytes(&from_hex(hex).unwrap()).unwrap() +} + +fn set_lens(item: &mut Descriptor, code: [u8; 4]) { + let Some(Value::Descriptor(fltr)) = item.items.iter_mut().find(|(k, _)| k.is("Fltr")).map(|(_, v)| v) else { panic!("no Fltr") }; + set(fltr, "Lns ", Value::Enumerated { type_id: Id::new("Lns "), value: Id::Code(code) }); +} + +#[test] +fn photoshop_render_filters_read_and_write_like_photoshop() { + let colours = |fg: f64, bg: f64| (json!([fg, fg, fg, 1.0]), json!([bg, bg, bg, 1.0])); + let (white, black) = colours(1.0, 0.0); + let cases = [ + (PHOTOSHOP_CLOUDS, "filter.render.clouds", json!({"seed": 18916, "foreground": white, "background": black})), + (PHOTOSHOP_DIFFERENCE_CLOUDS, "filter.render.differenceClouds", json!({"seed": 22482, "foreground": white, "background": black})), + (PHOTOSHOP_FIBERS, "filter.render.fibers", json!({"variance": 16, "strength": 4, "seed": 25329, "foreground": black, "background": white})), + ( + PHOTOSHOP_LENS_FLARE, + "filter.render.lensFlare", + json!({"brightness": 159, "centerX": 0.762499988079071, "centerY": 0.6888889074325562, "lens": "zoom"}), + ), + ]; + for (hex, command, params) in cases { + let item = photoshop(hex); + let f = filter_from_item(&item); + assert_eq!((f.command.as_str(), &f.params), (command, ¶ms)); + // Written back, it is Photoshop's item again: name, colours, settings and key order. + assert_eq!(item_for_filter(&f).unwrap().items, item.items, "{command}"); + } +} + +#[test] +fn every_lens_flare_lens_round_trips_with_photoshops_code() { + for (code, lens) in LENSES { + let mut item = photoshop(PHOTOSHOP_LENS_FLARE); + set_lens(&mut item, *code); + let f = filter_from_item(&item); + assert_eq!(f.params["lens"], lens); + assert_eq!(item_for_filter(&f).unwrap().items, item.items, "{lens}"); + } + // A lens we don't know keeps the filter verbatim. + let mut item = photoshop(PHOTOSHOP_LENS_FLARE); + set_lens(&mut item, *b"Xxxx"); + assert_eq!(filter_from_item(&item).command, UNSUPPORTED_FILTER); +} + +/// The descriptor at `path` (nested keys) inside `item`, for editing. +fn desc_at<'a>(item: &'a mut Descriptor, path: &[&str]) -> &'a mut Descriptor { + path.iter().fold(item, |d, key| { + let Some(Value::Descriptor(x)) = d.items.iter_mut().find(|(k, _)| k.is(key)).map(|(_, v)| v) else { panic!("no {key}") }; + x + }) +} + +#[test] +fn render_filters_with_settings_we_dont_model_stay_verbatim() { + // Each case changes one thing in a Photoshop item: an extra setting, a repeated one, or a + // value of another type than Photoshop writes. Opened as editable, a re-save would drop the + // extra setting or rewrite the value; kept verbatim, the item is written back byte for byte. + type Edit = Box; + /// A descriptor path in the item (nested keys) and the edit made there. + type Change = (&'static [&'static str], Edit); + let extra: fn(&mut Descriptor) = |d| d.items.push((Id::new("Xtra"), Value::Integer(1))); + let as_double = |key: &'static str| -> Edit { Box::new(move |d| set(d, key, Value::Double(1.0))) }; + let as_long = |key: &'static str| -> Edit { Box::new(move |d| set(d, key, Value::Integer(1))) }; + let repeat = |key: &'static str| -> Edit { + Box::new(move |d| { + let v = d.get(key).cloned().unwrap(); + d.items.push((Id::new(key), v)); + }) + }; + let colour_edits = || -> Vec { + vec![ + (&["FrgC"], Box::new(|d: &mut Descriptor| d.items.push((Id::new("redFloat"), Value::Double(0.5))))), + (&["BckC"], as_long("Grn ")), + (&["FrgC"], Box::new(|d: &mut Descriptor| set(d, "Rd ", Value::Double(300.0)))), + (&["BckC"], Box::new(|d: &mut Descriptor| d.class_id = Id::new("HSBC"))), + ] + }; + let mut cases: Vec<(&str, &'static [&'static str], Edit)> = Vec::new(); + for hex in [PHOTOSHOP_CLOUDS, PHOTOSHOP_DIFFERENCE_CLOUDS] { + cases.push((hex, &["Fltr"], Box::new(extra))); + cases.push((hex, &["Fltr"], repeat("FlRs"))); + cases.push((hex, &["Fltr"], as_double("FlRs"))); + cases.extend(colour_edits().into_iter().map(|(p, e)| (hex, p, e))); + } + cases.push((PHOTOSHOP_FIBERS, &["Fltr"], Box::new(extra))); + cases.push((PHOTOSHOP_FIBERS, &["Fltr"], repeat("Strg"))); + for key in ["Vrnc", "Strg", "RndS"] { + cases.push((PHOTOSHOP_FIBERS, &["Fltr"], as_double(key))); + } + cases.extend(colour_edits().into_iter().map(|(p, e)| (PHOTOSHOP_FIBERS, p, e))); + cases.push((PHOTOSHOP_LENS_FLARE, &["Fltr"], Box::new(extra))); + cases.push((PHOTOSHOP_LENS_FLARE, &["Fltr"], repeat("Brgh"))); + cases.push((PHOTOSHOP_LENS_FLARE, &["Fltr"], as_double("Brgh"))); + cases.push((PHOTOSHOP_LENS_FLARE, &["Fltr"], Box::new(|d| set(d, "Lns ", Value::Enumerated { type_id: Id::new("Xxxx"), value: Id::Code(*b"Zm ") })))); + cases.push((PHOTOSHOP_LENS_FLARE, &["Fltr", "FlrC"], Box::new(extra))); + cases.push((PHOTOSHOP_LENS_FLARE, &["Fltr", "FlrC"], as_long("Hrzn"))); + cases.push((PHOTOSHOP_LENS_FLARE, &["Fltr", "FlrC"], Box::new(|d| set(d, "Vrtc", Value::UnitFloat { unit: *b"#Pxl", value: 0.5 })))); + for (i, (hex, path, edit)) in cases.iter().enumerate() { + let mut item = photoshop(hex); + edit(desc_at(&mut item, path)); + let f = filter_from_item(&item); + assert_eq!(f.command, UNSUPPORTED_FILTER, "case {i} ({path:?}): {:?}", f.params); + assert_eq!(item_for_filter(&f).unwrap().to_bytes(), item.to_bytes(), "case {i} ({path:?})"); + } +} + +#[test] +fn render_filters_made_in_photocraft_are_written() { + // Without colours (an older document or a script), Photoshop's default black and white. + let back = filter_from_item(&item_for_filter(&sf("filter.render.clouds", json!({"seed": 7}))).unwrap()); + assert_eq!(back.params, json!({"seed": 7, "foreground": [0.0, 0.0, 0.0, 1.0], "background": [1.0, 1.0, 1.0, 1.0]})); + // A seed above i32::MAX keeps its bit pattern, and colours may be hex. + let p = json!({"variance": 30, "strength": 10, "seed": 4_000_000_000u32, "foreground": "#ff0000", "background": [0.0, 0.0, 1.0, 1.0]}); + let back = filter_from_item(&item_for_filter(&sf("filter.render.fibers", p)).unwrap()); + assert_eq!( + back.params, + json!({"variance": 30, "strength": 10, "seed": 4_000_000_000u32, "foreground": [1.0, 0.0, 0.0, 1.0], "background": [0.0, 0.0, 1.0, 1.0]}) + ); + let flare = sf("filter.render.lensFlare", json!({"brightness": 120, "centerX": 0.25, "centerY": 0.75, "lens": "moviePrime"})); + assert_eq!(filter_from_item(&item_for_filter(&flare).unwrap()).params, flare.params); + // Lenses and colours we can't write are reported, not guessed. + assert!(item_for_filter(&sf("filter.render.lensFlare", json!({"lens": "fisheye"}))).unwrap_err().contains("fisheye")); + assert!(item_for_filter(&sf("filter.render.clouds", json!({"foreground": "red"}))).is_err()); +} diff --git a/crates/io/src/svg.rs b/crates/io/src/svg.rs index 7ff563d466..98161732de 100644 --- a/crates/io/src/svg.rs +++ b/crates/io/src/svg.rs @@ -987,484 +987,4 @@ fn knots(path: &tiny_skia::Path) -> Vec { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn sniffing_accepts_svg_and_rejects_other_xml() { - assert!(is_svg(b"")); - assert!(is_svg("\u{feff}\n\n".as_bytes())); - assert!(is_svg(b"")); - assert!(!is_svg(b"")); - assert!(!is_svg(b"\x89PNG\r\n")); - assert!(!is_svg(b"")); - } - - #[test] - fn quadratics_become_cubics_and_closing_merges_the_start_knot() { - let mut pb = tiny_skia::PathBuilder::new(); - pb.move_to(0.0, 0.0); - pb.quad_to(5.0, 10.0, 10.0, 0.0); - pb.line_to(0.0, 0.0); - pb.close(); - pb.move_to(20.0, 20.0); - pb.line_to(30.0, 20.0); - let path = pb.finish().unwrap(); - let sp = knots(&path); - assert_eq!(sp.len(), 2); - assert!(sp[0].closed && !sp[1].closed); - // The explicit line back to the start was merged into the first knot. - assert_eq!(sp[0].knots.len(), 2); - let (a, b) = (&sp[0].knots[0], &sp[0].knots[1]); - assert!((a.out_ctrl.x - 10.0 / 3.0).abs() < 1e-9 && (a.out_ctrl.y - 20.0 / 3.0).abs() < 1e-9); - assert!((b.in_ctrl.x - 20.0 / 3.0).abs() < 1e-9 && (b.in_ctrl.y - 20.0 / 3.0).abs() < 1e-9); - assert_eq!(b.anchor, Point::new(10.0, 0.0)); - assert_eq!(sp[1].knots.len(), 2); - } - - #[test] - fn text_without_any_font_is_reported_not_silently_dropped() { - // No font at all (a bare CI image): usvg drops the while parsing, so nothing - // reaches the conversion; the reader still has to say why the text is missing. - fn no_fonts() -> Arc { - Arc::new(usvg::fontdb::Database::new()) - } - let svg = b"II"; - let parsed = parse_with(svg, no_fonts).unwrap(); - assert!(parsed.fontless_text); - let r = import_parsed("t", parsed, MAX_GROUP_DEPTH).unwrap(); - assert!(r.document.layers.is_empty()); - assert!(r.warnings.iter().any(|w| w.contains("font")), "{:?}", r.warnings); - // A drawing without text never loads or misses fonts. - let parsed = - parse_with(b"", no_fonts).unwrap(); - assert!(!parsed.fontless_text); - let r = import_parsed("t", parsed, MAX_GROUP_DEPTH).unwrap(); - assert!(r.warnings.iter().all(|w| !w.contains("font")), "{:?}", r.warnings); - } - - /// #4806: text placed by a `transform` (Illustrator writes `matrix(1 0 0 1 x y)` on every text - /// element), on the text or on a group around it, lands where resvg draws it. usvg leaves the - /// glyph outlines' absolute transforms at identity, so reading them dropped the transform: the - /// text went off the canvas or kept its untransformed place and size. - /// - /// Shaped with the bundled Inter alone, never a system font: on a machine without fonts (a - /// bare CI image or VM) the test would otherwise have nothing to check, and the drawing and - /// its reference come from the same parse, so both use that face. - #[test] - fn transformed_text_lands_where_resvg_draws_it() { - fn inter() -> Arc { - let mut db = usvg::fontdb::Database::new(); - db.load_font_data(photocraft_text::fonts::INTER_REGULAR.to_vec()); - Arc::new(db) - } - assert!(inter().faces().next().is_some(), "the bundled Inter loads"); - let font = r#"font-size="24" font-family="Inter" fill="black""#; - let cases = [ - format!(r#"IHI"#), - format!(r#"IHI"#), - format!(r#"IHI"#), - format!(r#"IHI"#), - format!(r#"IHI"#), - format!(r#"IHI"#), - ]; - for c in cases { - let svg = format!(r#"{c}"#); - let parsed = parse_with(svg.as_bytes(), inter).unwrap(); - assert!(!parsed.fontless_text, "{c}"); - let mut reference = tiny_skia::Pixmap::new(120, 60).unwrap(); - resvg::render(&parsed.tree, tiny_skia::Transform::default(), &mut reference.as_mut()); - let r = import_parsed("t", parsed, MAX_GROUP_DEPTH).unwrap(); - let [layer] = r.document.layers.as_slice() else { panic!("one text layer, got {}: {c}", r.document.layers.len()) }; - assert!(matches!(layer.content, LayerContent::Group(_)), "text stays outline shapes: {c}"); - let imported = photocraft_compose::flatten(&r.document); - let (mut both, mut either) = (0usize, 0usize); - let (mut a_box, mut b_box) = ([i32::MAX, i32::MAX, i32::MIN, i32::MIN], [i32::MAX, i32::MAX, i32::MIN, i32::MIN]); - let grow = |bx: &mut [i32; 4], x: i32, y: i32| *bx = [bx[0].min(x), bx[1].min(y), bx[2].max(x), bx[3].max(y)]; - for (i, px) in reference.pixels().iter().enumerate() { - let (x, y) = ((i % 120) as i32, (i / 120) as i32); - let (a, b) = (imported.get(x, y)[3] > 0.5, px.alpha() > 127); - if a { - grow(&mut a_box, x, y); - } - if b { - grow(&mut b_box, x, y); - } - both += usize::from(a && b); - either += usize::from(a || b); - } - assert!(either > 50, "resvg draws the text on the canvas: {c}"); - // Same place and size to the pixel; the outlines are filled by a different rasteriser, - // so the edges of thin stems may differ by half a pixel. - assert!(a_box.iter().zip(b_box).all(|(a, b)| (a - b).abs() <= 1), "imported {a_box:?}, resvg {b_box:?}: {c}"); - assert!(both * 10 >= either * 7, "imported glyphs cover what resvg draws ({both} of {either} px): {c}"); - } - } - - /// #4266: a group clipped by one path (the PhotoCraft icon's rounded square) stays editable - /// shapes with the clip as its vector mask, and looks as resvg draws the drawing; a clip of - /// two shapes is still rasterised, with the warning. - #[test] - fn a_single_path_clip_becomes_the_groups_vector_mask() { - let svg = br##" - - - - - "##; - let r = import_svg("t", svg).unwrap(); - assert!(r.warnings.iter().all(|w| !w.contains("clip-path")), "{:?}", r.warnings); - let [group] = r.document.layers.as_slice() else { panic!("one group: {:?}", r.document.layers.len()) }; - let LayerContent::Group(g) = &group.content else { panic!("a group") }; - assert_eq!(g.children.len(), 2); - assert!(g.children.iter().all(|c| matches!(c.content, LayerContent::Shape(_))), "editable shapes"); - let mask = group.vector_mask.as_ref().expect("the clip as a vector mask"); - let xs: Vec = mask.path.subpaths.iter().flat_map(|s| s.knots.iter().map(|k| k.anchor.x)).collect(); - let (lo, hi) = (xs.iter().copied().fold(f64::MAX, f64::min), xs.iter().copied().fold(f64::MIN, f64::max)); - assert!((lo - 12.0).abs() < 1e-3 && (hi - 52.0).abs() < 1e-3, "in the group's space: {lo}..{hi}"); - // Pixel for pixel what resvg draws, but for anti-aliasing along the edges. - let ours = photocraft_compose::flatten(&r.document).to_rgba8().pixels; - let tree = parse(svg).unwrap().tree; - let mut pm = tiny_skia::Pixmap::new(64, 64).unwrap(); - resvg::render(&tree, tiny_skia::Transform::default(), &mut pm.as_mut()); - let theirs: Vec = pm - .pixels() - .iter() - .flat_map(|p| { - let c = p.demultiply(); - [c.red(), c.green(), c.blue(), c.alpha()] - }) - .collect(); - let off = ours.chunks(4).zip(theirs.chunks(4)).filter(|(a, b)| a.iter().zip(*b).any(|(x, y)| x.abs_diff(*y) > 48)).count(); - assert!(off < 64, "{off} pixels differ"); - // The report's file: PhotoCraft's own icon opens without the clip-path warning. - let icon = import_svg("photocraft.svg", include_bytes!("../../../assets/app-icon/photocraft.svg")).unwrap(); - assert!(icon.warnings.iter().all(|w| !w.contains("clip-path")), "{:?}", icon.warnings); - assert!(icon.document.layers.iter().any(|l| l.vector_mask.is_some()), "its rounded square is a vector mask"); - // Two shapes in the clip: rasterised, and said so. - let two = br##" - - "##; - let r = import_svg("t", two).unwrap(); - assert!(r.warnings.iter().any(|w| w.contains("clip-path")), "{:?}", r.warnings); - } - - /// A database with the bundled Inter alone, generics resolved without Fontconfig: none of - /// fontdb's Windows defaults (Arial, Times New Roman, Courier New) is in it. - fn inter_only() -> Arc { - let mut db = usvg::fontdb::Database::new(); - db.load_font_data(include_bytes!("../../../assets/fonts/Inter-Regular.ttf").to_vec()); - resolve_generic_families(&mut db, |_| None); - Arc::new(db) - } - - /// Text asking for fonts that aren't installed (`Arial, Helvetica, sans-serif` on a Linux - /// without them) is set in an installed font, as a browser does, instead of being dropped. - #[test] - fn text_in_missing_fonts_falls_back_to_an_installed_one() { - for family in ["Arial, Helvetica, sans-serif", "Times New Roman", "Courier New, monospace", "cursive", "fantasy"] { - let svg = format!( - "II" - ); - let parsed = parse_with(svg.as_bytes(), inter_only).unwrap(); - assert!(!parsed.fontless_text); - let r = import_parsed("t", parsed, MAX_GROUP_DEPTH).unwrap(); - assert_eq!(r.document.layers.first().map(|l| l.name.as_str()), Some("II"), "{family}: {:?}", r.warnings); - } - } - - /// #9406: a font installed on disk (how the system fonts load) is read once, not once per - /// glyph: fontdb re-reads a file source's whole font on every glyph it outlines, about a - /// millisecond a character. The face text is set in comes from memory, and the outlines - /// match the same font loaded from memory in the first place. - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn text_in_a_font_on_disk_is_set_from_memory() { - fn inter_on_disk() -> Arc { - let mut db = usvg::fontdb::Database::new(); - let _ = db.load_font_file(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/fonts/Inter-Regular.ttf")); - Arc::new(db) - } - assert!(inter_on_disk().faces().all(|f| matches!(f.source, usvg::fontdb::Source::File(_)))); - let svg = b"IHI"; - let parsed = parse_with(svg, inter_on_disk).unwrap(); - let faces: Vec<_> = parsed.tree.fontdb().faces().map(|f| matches!(f.source, usvg::fontdb::Source::Binary(_))).collect(); - assert_eq!(faces, [true], "the face text was set in is held in memory"); - let on_disk = import_parsed("t", parsed, MAX_GROUP_DEPTH).unwrap(); - let in_memory = import_parsed("t", parse_with(svg, inter_only).unwrap(), MAX_GROUP_DEPTH).unwrap(); - assert_eq!(on_disk.document.layers.first().map(|l| l.name.as_str()), Some("IHI")); - let outlines = |r: &ImportResult| { - let groups = r.document.layers.iter().filter_map(|l| if let LayerContent::Group(g) = &l.content { Some(g) } else { None }); - groups - .flat_map(|g| &g.children) - .filter_map(|l| if let LayerContent::Shape(s) = &l.content { Some(s.path.clone()) } else { None }) - .collect::>() - }; - assert!(outlines(&on_disk).iter().any(|p| !p.subpaths.is_empty()), "the text has outlines"); - assert_eq!(outlines(&on_disk), outlines(&in_memory)); - } - - /// A font file that no longer loads (replaced or cut short since fontdb indexed it) keeps its - /// faces in the database and isn't remembered: once the file is whole again, text is set - /// from it. - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn a_font_file_gone_bad_since_indexing_is_not_cached() { - use std::sync::atomic::{AtomicBool, Ordering}; - static BAD: AtomicBool = AtomicBool::new(true); - fn indexed_then_overwritten() -> Arc { - let path = std::env::temp_dir().join(format!("photocraft-svg-test-bad-{}.ttf", std::process::id())); - std::fs::write(&path, include_bytes!("../../../assets/fonts/Inter-Regular.ttf")).unwrap(); - let mut db = usvg::fontdb::Database::new(); - db.load_font_file(&path).unwrap(); - if BAD.load(Ordering::SeqCst) { - std::fs::write(&path, b"not a font any more").unwrap(); - } - Arc::new(db) - } - let svg = b"IHI"; - let parsed = parse_with(svg, indexed_then_overwritten).unwrap(); - let sources: Vec<_> = parsed.tree.fontdb().faces().map(|f| matches!(f.source, usvg::fontdb::Source::File(_))).collect(); - assert_eq!(sources, [true], "the face stays in the database, on disk"); - BAD.store(false, Ordering::SeqCst); - let parsed = parse_with(svg, indexed_then_overwritten).unwrap(); - let sources: Vec<_> = parsed.tree.fontdb().faces().map(|f| matches!(f.source, usvg::fontdb::Source::Binary(_))).collect(); - assert_eq!(sources, [true], "the whole file is read into memory now"); - let layers = import_parsed("t", parsed, MAX_GROUP_DEPTH).unwrap().document.layers; - assert_eq!(layers.first().map(|l| l.name.as_str()), Some("IHI")); - assert!( - layers.iter().any(|l| matches!(&l.content, LayerContent::Group(g) if g.children.iter().any(|c| matches!(&c.content, LayerContent::Shape(s) if !s.path.subpaths.is_empty())))), - "the text has outlines" - ); - } - - /// Imports that miss the cache for the same file at once read it once: every one sets its - /// text from the same bytes, not a copy of its own next to the kept one. - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn imports_missing_the_same_font_at_once_share_one_read() { - use std::sync::atomic::{AtomicUsize, Ordering}; - static ROUND: AtomicUsize = AtomicUsize::new(0); - fn fresh_file() -> Arc { - let round = ROUND.load(Ordering::SeqCst); - let path = std::env::temp_dir().join(format!("photocraft-svg-test-shared-{}-{round}.ttf", std::process::id())); - let mut db = usvg::fontdb::Database::new(); - db.load_font_file(&path).unwrap(); - Arc::new(db) - } - let svg = b"IHI"; - for round in 0..5 { - ROUND.store(round, Ordering::SeqCst); - let path = std::env::temp_dir().join(format!("photocraft-svg-test-shared-{}-{round}.ttf", std::process::id())); - std::fs::write(&path, include_bytes!("../../../assets/fonts/Inter-Regular.ttf")).unwrap(); - let start = Arc::new(std::sync::Barrier::new(8)); - let threads: Vec<_> = (0..8) - .map(|_| { - let start = start.clone(); - std::thread::spawn(move || { - start.wait(); - let parsed = parse_with(svg, fresh_file).unwrap(); - let bytes: Vec<_> = parsed - .tree - .fontdb() - .faces() - .filter_map(|f| if let usvg::fontdb::Source::Binary(b) = &f.source { Some(Arc::as_ptr(b).cast::() as usize) } else { None }) - .collect(); - bytes - }) - }) - .collect(); - let bytes: Vec<_> = threads.into_iter().flat_map(|t| t.join().unwrap()).collect(); - assert_eq!(bytes.len(), 8, "every import set its text from memory"); - assert!(bytes.iter().all(|&b| b == bytes[0]), "round {round}: {bytes:x?}"); - let _ = std::fs::remove_file(&path); - } - } - - /// #9406: moving a font collection into memory keeps its faces in their order, so the - /// fallback search for a later text still finds the face it found on disk first. - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn a_collection_in_memory_keeps_its_face_order() { - fn collection_on_disk() -> Arc { - // A two-face .ttc of the bundled Inter Regular and SemiBold: the `ttcf` header, then - // each font with its table offsets moved by where it starts. - let fonts: [&[u8]; 2] = [include_bytes!("../../../assets/fonts/Inter-Regular.ttf"), include_bytes!("../../../assets/fonts/Inter-SemiBold.ttf")]; - let mut ttc = b"ttcf������".to_vec(); - let mut start = 20; - let mut body = Vec::new(); - for f in fonts { - ttc.extend_from_slice(&u32::try_from(start).unwrap().to_be_bytes()); - let mut font = f.to_vec(); - for t in 0..usize::from(u16::from_be_bytes([font[4], font[5]])) { - let at = 12 + t * 16 + 8; - let off = u32::from_be_bytes(font[at..at + 4].try_into().unwrap()) + u32::try_from(start).unwrap(); - font[at..at + 4].copy_from_slice(&off.to_be_bytes()); - } - font.resize(font.len().next_multiple_of(4), 0); - start += font.len(); - body.extend(font); - } - ttc.extend(body); - let path = std::env::temp_dir().join(format!("photocraft-svg-test-{}.ttc", std::process::id())); - std::fs::write(&path, ttc).unwrap(); - let mut db = usvg::fontdb::Database::new(); - db.load_font_file(&path).unwrap(); - Arc::new(db) - } - let order = |db: &usvg::fontdb::Database| db.faces().map(|f| (f.index, f.weight.0)).collect::>(); - assert_eq!(order(&collection_on_disk()), [(0, 400), (1, 600)]); - let svg = b"IHI"; - let parsed = parse_with(svg, collection_on_disk).unwrap(); - let db = parsed.tree.fontdb(); - assert!(db.faces().all(|f| matches!(f.source, usvg::fontdb::Source::Binary(_))), "both faces of the file are in memory"); - assert_eq!(order(db), [(0, 400), (1, 600)]); - } - - #[test] - fn generic_families_point_at_installed_fonts() { - use usvg::fontdb::Family; - let db = inter_only(); - for g in [Family::SansSerif, Family::Serif, Family::Monospace, Family::Cursive, Family::Fantasy] { - assert_eq!(db.family_name(&g), "Inter", "{g:?}"); - } - // The system's choice wins when installed; a generic whose font is installed stays. - let mut db = usvg::fontdb::Database::new(); - db.load_font_data(include_bytes!("../../../assets/fonts/Inter-Regular.ttf").to_vec()); - db.load_font_data(include_bytes!("../../../assets/fonts/JetBrainsMono-Regular.ttf").to_vec()); - db.set_cursive_family("Inter"); - resolve_generic_families(&mut db, |g| Some(if g == "serif" { "JetBrains Mono" } else { "Not Installed" }.to_string())); - assert_eq!(db.family_name(&Family::Serif), "JetBrains Mono"); - assert_eq!(db.family_name(&Family::Monospace), "JetBrains Mono", "the bundled mono stand-in"); - assert_eq!(db.family_name(&Family::SansSerif), "Inter"); - assert_eq!(db.family_name(&Family::Cursive), "Inter"); - // An empty database is left alone. - let mut empty = usvg::fontdb::Database::new(); - resolve_generic_families(&mut empty, |_| Some("Inter".into())); - assert_eq!(empty.family_name(&Family::SansSerif), "Arial"); - } - - #[test] - fn rasterized_groups_stop_at_the_aggregate_pixel_budget() { - let mut svg = String::from(""); - svg.push_str(""); - for i in 0..8 { - svg.push_str(&format!("")); - } - svg.push_str(""); - // Enough for one retained 256×256 RGBA8 surface, not eight of them. - let budget = 256u64 * 256 * 4; - let result = import_parsed_with_budget("budget", parse(svg.as_bytes()).unwrap(), MAX_GROUP_DEPTH, budget).unwrap(); - assert_eq!(result.document.layers.len(), 1, "one U8 surface fills the retained-byte allowance"); - assert_eq!(result.document.layers[0].name, "g0"); - assert!(result.warnings.iter().any(|warning| warning.contains("pixel memory")), "{:?}", result.warnings); - } - - #[test] - fn oversized_raster_does_not_consume_budget_for_later_layers() { - let svg = br##" - - - - - - - - - - - "##; - let result = import_parsed_with_budget("budget", parse(svg).unwrap(), MAX_GROUP_DEPTH, 64 * 64 * 4).unwrap(); - assert_eq!(result.document.layers.len(), 1, "the oversized group must not debit the budget"); - assert_eq!(result.document.layers[0].name, "small"); - assert!(result.warnings.iter().any(|w| w.contains("too large to rasterise")), "{:?}", result.warnings); - assert!(!result.warnings.iter().any(|w| w.contains("pixel memory budget")), "{:?}", result.warnings); - } - - #[test] - fn skipped_expensive_raster_does_not_hide_a_smaller_one() { - let svg = br##" - - - - - - - "##; - let result = import_parsed_with_budget("budget", parse(svg).unwrap(), MAX_GROUP_DEPTH, 32 * 32 * 4).unwrap(); - assert_eq!(result.document.layers.len(), 1); - assert_eq!(result.document.layers[0].name, "small"); - assert!(result.warnings.iter().any(|w| w.contains("some rasterised elements were omitted")), "{:?}", result.warnings); - } - - #[test] - fn huge_drawings_scale_to_the_side_limit() { - let tree = parse(b"").unwrap().tree; - let mut w = Vec::new(); - let cv = canvas(&tree, &mut w); - assert_eq!((cv.size.width, cv.size.height), (MAX_SIDE, MAX_SIDE / 2)); - assert_eq!(w.len(), 1); - } - - #[test] - fn resolve_data_rejects_oversized_and_malformed_embedded_png_and_webp() { - let opt = options(Arc::new(usvg::fontdb::Database::new())); - let resolve = &opt.image_href_resolver.resolve_data; - let img = photocraft_codecs::Image::from_u8(2, 2, photocraft_codecs::ChannelLayout::Rgb, vec![255; 12]).unwrap(); - let valid_png = photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap(); - assert!(resolve("image/png", Arc::new(valid_png.clone()), &opt).is_some()); - assert!(resolve("text/plain", Arc::new(valid_png.clone()), &opt).is_some()); - - let mut huge_png = valid_png; - huge_png[16..20].copy_from_slice(&40_000u32.to_be_bytes()); - huge_png[20..24].copy_from_slice(&40_000u32.to_be_bytes()); - assert!(resolve("image/png", Arc::new(huge_png.clone()), &opt).is_none(), "oversized PNG rejected before decode"); - assert!(resolve("text/plain", Arc::new(huge_png), &opt).is_none(), "oversized mime-less PNG rejected before decode"); - - // Malformed WebP header under image/webp or text/plain must be rejected at the probe step. - let bad_webp = b"RIFF\x10\x00\x00\x00WEBPVP8 ".to_vec(); - assert!(resolve("image/webp", Arc::new(bad_webp.clone()), &opt).is_none()); - assert!(resolve("text/plain", Arc::new(bad_webp), &opt).is_none()); - } - - #[test] - fn jpeg_dimensions_come_from_the_frame_header_and_oversized_jpegs_are_refused() { - // SOI, an APP0 segment of length 4, then SOF0 (length 11): 8 bits, height 40000, width 30000. - let jpeg = |h: u16, w: u16| { - let mut v = vec![0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x04, 0, 0, 0xFF, 0xC0, 0x00, 0x0B, 8]; - v.extend(h.to_be_bytes()); - v.extend(w.to_be_bytes()); - v.extend([1, 1, 0x11, 0]); - v - }; - assert_eq!(jpeg_dimensions(&jpeg(40_000, 30_000)), Some((30_000, 40_000))); - assert_eq!(jpeg_dimensions(&[0xFF, 0xD8, 0xFF, 0xDA, 0, 2]), None); - assert_eq!(jpeg_dimensions(&[0xFF, 0xD8]), None); - let opt = options(Arc::new(usvg::fontdb::Database::new())); - let resolve = &opt.image_href_resolver.resolve_data; - // 1.2 billion pixels would be 4.8 GB of RGBA before resvg scaled anything down. - assert!(resolve("image/jpeg", Arc::new(jpeg(40_000, 30_000)), &opt).is_none()); - assert!(resolve("text/plain", Arc::new(jpeg(40_000, 30_000)), &opt).is_none()); - } - - #[test] - fn resolve_data_rejects_nested_gzip_and_handles_text_plain_svgz() { - use std::io::Write; - fn gz(bytes: &[u8]) -> Vec { - let mut e = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast()); - e.write_all(bytes).unwrap(); - e.finish().unwrap() - } - let opt = options(Arc::new(usvg::fontdb::Database::new())); - let resolve = &opt.image_href_resolver.resolve_data; - let svg = b""; - let once = gz(svg); - assert!(resolve("image/svg+xml", Arc::new(once.clone()), &opt).is_some()); - assert!(resolve("text/plain", Arc::new(once.clone()), &opt).is_some()); - - // Doubly gzip-compressed payload must be rejected rather than decompressed a second time by usvg. - let twice = gz(&once); - assert!(resolve("image/svg+xml", Arc::new(twice.clone()), &opt).is_none()); - assert!(resolve("text/plain", Arc::new(twice), &opt).is_none()); - } -} +mod tests; diff --git a/crates/io/src/svg/tests.rs b/crates/io/src/svg/tests.rs new file mode 100644 index 0000000000..7127738daa --- /dev/null +++ b/crates/io/src/svg/tests.rs @@ -0,0 +1,477 @@ +use super::*; + +#[test] +fn sniffing_accepts_svg_and_rejects_other_xml() { + assert!(is_svg(b"")); + assert!(is_svg("\u{feff}\n\n".as_bytes())); + assert!(is_svg(b"")); + assert!(!is_svg(b"")); + assert!(!is_svg(b"\x89PNG\r\n")); + assert!(!is_svg(b"")); +} + +#[test] +fn quadratics_become_cubics_and_closing_merges_the_start_knot() { + let mut pb = tiny_skia::PathBuilder::new(); + pb.move_to(0.0, 0.0); + pb.quad_to(5.0, 10.0, 10.0, 0.0); + pb.line_to(0.0, 0.0); + pb.close(); + pb.move_to(20.0, 20.0); + pb.line_to(30.0, 20.0); + let path = pb.finish().unwrap(); + let sp = knots(&path); + assert_eq!(sp.len(), 2); + assert!(sp[0].closed && !sp[1].closed); + // The explicit line back to the start was merged into the first knot. + assert_eq!(sp[0].knots.len(), 2); + let (a, b) = (&sp[0].knots[0], &sp[0].knots[1]); + assert!((a.out_ctrl.x - 10.0 / 3.0).abs() < 1e-9 && (a.out_ctrl.y - 20.0 / 3.0).abs() < 1e-9); + assert!((b.in_ctrl.x - 20.0 / 3.0).abs() < 1e-9 && (b.in_ctrl.y - 20.0 / 3.0).abs() < 1e-9); + assert_eq!(b.anchor, Point::new(10.0, 0.0)); + assert_eq!(sp[1].knots.len(), 2); +} + +#[test] +fn text_without_any_font_is_reported_not_silently_dropped() { + // No font at all (a bare CI image): usvg drops the while parsing, so nothing + // reaches the conversion; the reader still has to say why the text is missing. + fn no_fonts() -> Arc { + Arc::new(usvg::fontdb::Database::new()) + } + let svg = b"II"; + let parsed = parse_with(svg, no_fonts).unwrap(); + assert!(parsed.fontless_text); + let r = import_parsed("t", parsed, MAX_GROUP_DEPTH).unwrap(); + assert!(r.document.layers.is_empty()); + assert!(r.warnings.iter().any(|w| w.contains("font")), "{:?}", r.warnings); + // A drawing without text never loads or misses fonts. + let parsed = + parse_with(b"", no_fonts).unwrap(); + assert!(!parsed.fontless_text); + let r = import_parsed("t", parsed, MAX_GROUP_DEPTH).unwrap(); + assert!(r.warnings.iter().all(|w| !w.contains("font")), "{:?}", r.warnings); +} + +/// #4806: text placed by a `transform` (Illustrator writes `matrix(1 0 0 1 x y)` on every text +/// element), on the text or on a group around it, lands where resvg draws it. usvg leaves the +/// glyph outlines' absolute transforms at identity, so reading them dropped the transform: the +/// text went off the canvas or kept its untransformed place and size. +/// +/// Shaped with the bundled Inter alone, never a system font: on a machine without fonts (a +/// bare CI image or VM) the test would otherwise have nothing to check, and the drawing and +/// its reference come from the same parse, so both use that face. +#[test] +fn transformed_text_lands_where_resvg_draws_it() { + fn inter() -> Arc { + let mut db = usvg::fontdb::Database::new(); + db.load_font_data(photocraft_text::fonts::INTER_REGULAR.to_vec()); + Arc::new(db) + } + assert!(inter().faces().next().is_some(), "the bundled Inter loads"); + let font = r#"font-size="24" font-family="Inter" fill="black""#; + let cases = [ + format!(r#"IHI"#), + format!(r#"IHI"#), + format!(r#"IHI"#), + format!(r#"IHI"#), + format!(r#"IHI"#), + format!(r#"IHI"#), + ]; + for c in cases { + let svg = format!(r#"{c}"#); + let parsed = parse_with(svg.as_bytes(), inter).unwrap(); + assert!(!parsed.fontless_text, "{c}"); + let mut reference = tiny_skia::Pixmap::new(120, 60).unwrap(); + resvg::render(&parsed.tree, tiny_skia::Transform::default(), &mut reference.as_mut()); + let r = import_parsed("t", parsed, MAX_GROUP_DEPTH).unwrap(); + let [layer] = r.document.layers.as_slice() else { panic!("one text layer, got {}: {c}", r.document.layers.len()) }; + assert!(matches!(layer.content, LayerContent::Group(_)), "text stays outline shapes: {c}"); + let imported = photocraft_compose::flatten(&r.document); + let (mut both, mut either) = (0usize, 0usize); + let (mut a_box, mut b_box) = ([i32::MAX, i32::MAX, i32::MIN, i32::MIN], [i32::MAX, i32::MAX, i32::MIN, i32::MIN]); + let grow = |bx: &mut [i32; 4], x: i32, y: i32| *bx = [bx[0].min(x), bx[1].min(y), bx[2].max(x), bx[3].max(y)]; + for (i, px) in reference.pixels().iter().enumerate() { + let (x, y) = ((i % 120) as i32, (i / 120) as i32); + let (a, b) = (imported.get(x, y)[3] > 0.5, px.alpha() > 127); + if a { + grow(&mut a_box, x, y); + } + if b { + grow(&mut b_box, x, y); + } + both += usize::from(a && b); + either += usize::from(a || b); + } + assert!(either > 50, "resvg draws the text on the canvas: {c}"); + // Same place and size to the pixel; the outlines are filled by a different rasteriser, + // so the edges of thin stems may differ by half a pixel. + assert!(a_box.iter().zip(b_box).all(|(a, b)| (a - b).abs() <= 1), "imported {a_box:?}, resvg {b_box:?}: {c}"); + assert!(both * 10 >= either * 7, "imported glyphs cover what resvg draws ({both} of {either} px): {c}"); + } +} + +/// #4266: a group clipped by one path (the PhotoCraft icon's rounded square) stays editable +/// shapes with the clip as its vector mask, and looks as resvg draws the drawing; a clip of +/// two shapes is still rasterised, with the warning. +#[test] +fn a_single_path_clip_becomes_the_groups_vector_mask() { + let svg = br##" + + + + + "##; + let r = import_svg("t", svg).unwrap(); + assert!(r.warnings.iter().all(|w| !w.contains("clip-path")), "{:?}", r.warnings); + let [group] = r.document.layers.as_slice() else { panic!("one group: {:?}", r.document.layers.len()) }; + let LayerContent::Group(g) = &group.content else { panic!("a group") }; + assert_eq!(g.children.len(), 2); + assert!(g.children.iter().all(|c| matches!(c.content, LayerContent::Shape(_))), "editable shapes"); + let mask = group.vector_mask.as_ref().expect("the clip as a vector mask"); + let xs: Vec = mask.path.subpaths.iter().flat_map(|s| s.knots.iter().map(|k| k.anchor.x)).collect(); + let (lo, hi) = (xs.iter().copied().fold(f64::MAX, f64::min), xs.iter().copied().fold(f64::MIN, f64::max)); + assert!((lo - 12.0).abs() < 1e-3 && (hi - 52.0).abs() < 1e-3, "in the group's space: {lo}..{hi}"); + // Pixel for pixel what resvg draws, but for anti-aliasing along the edges. + let ours = photocraft_compose::flatten(&r.document).to_rgba8().pixels; + let tree = parse(svg).unwrap().tree; + let mut pm = tiny_skia::Pixmap::new(64, 64).unwrap(); + resvg::render(&tree, tiny_skia::Transform::default(), &mut pm.as_mut()); + let theirs: Vec = pm + .pixels() + .iter() + .flat_map(|p| { + let c = p.demultiply(); + [c.red(), c.green(), c.blue(), c.alpha()] + }) + .collect(); + let off = ours.chunks(4).zip(theirs.chunks(4)).filter(|(a, b)| a.iter().zip(*b).any(|(x, y)| x.abs_diff(*y) > 48)).count(); + assert!(off < 64, "{off} pixels differ"); + // The report's file: PhotoCraft's own icon opens without the clip-path warning. + let icon = import_svg("photocraft.svg", include_bytes!("../../../../assets/app-icon/photocraft.svg")).unwrap(); + assert!(icon.warnings.iter().all(|w| !w.contains("clip-path")), "{:?}", icon.warnings); + assert!(icon.document.layers.iter().any(|l| l.vector_mask.is_some()), "its rounded square is a vector mask"); + // Two shapes in the clip: rasterised, and said so. + let two = br##" + + "##; + let r = import_svg("t", two).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("clip-path")), "{:?}", r.warnings); +} + +/// A database with the bundled Inter alone, generics resolved without Fontconfig: none of +/// fontdb's Windows defaults (Arial, Times New Roman, Courier New) is in it. +fn inter_only() -> Arc { + let mut db = usvg::fontdb::Database::new(); + db.load_font_data(include_bytes!("../../../../assets/fonts/Inter-Regular.ttf").to_vec()); + resolve_generic_families(&mut db, |_| None); + Arc::new(db) +} + +/// Text asking for fonts that aren't installed (`Arial, Helvetica, sans-serif` on a Linux +/// without them) is set in an installed font, as a browser does, instead of being dropped. +#[test] +fn text_in_missing_fonts_falls_back_to_an_installed_one() { + for family in ["Arial, Helvetica, sans-serif", "Times New Roman", "Courier New, monospace", "cursive", "fantasy"] { + let svg = format!( + "II" + ); + let parsed = parse_with(svg.as_bytes(), inter_only).unwrap(); + assert!(!parsed.fontless_text); + let r = import_parsed("t", parsed, MAX_GROUP_DEPTH).unwrap(); + assert_eq!(r.document.layers.first().map(|l| l.name.as_str()), Some("II"), "{family}: {:?}", r.warnings); + } +} + +/// #9406: a font installed on disk (how the system fonts load) is read once, not once per +/// glyph: fontdb re-reads a file source's whole font on every glyph it outlines, about a +/// millisecond a character. The face text is set in comes from memory, and the outlines +/// match the same font loaded from memory in the first place. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn text_in_a_font_on_disk_is_set_from_memory() { + fn inter_on_disk() -> Arc { + let mut db = usvg::fontdb::Database::new(); + let _ = db.load_font_file(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/fonts/Inter-Regular.ttf")); + Arc::new(db) + } + assert!(inter_on_disk().faces().all(|f| matches!(f.source, usvg::fontdb::Source::File(_)))); + let svg = + b"IHI"; + let parsed = parse_with(svg, inter_on_disk).unwrap(); + let faces: Vec<_> = parsed.tree.fontdb().faces().map(|f| matches!(f.source, usvg::fontdb::Source::Binary(_))).collect(); + assert_eq!(faces, [true], "the face text was set in is held in memory"); + let on_disk = import_parsed("t", parsed, MAX_GROUP_DEPTH).unwrap(); + let in_memory = import_parsed("t", parse_with(svg, inter_only).unwrap(), MAX_GROUP_DEPTH).unwrap(); + assert_eq!(on_disk.document.layers.first().map(|l| l.name.as_str()), Some("IHI")); + let outlines = |r: &ImportResult| { + let groups = r.document.layers.iter().filter_map(|l| if let LayerContent::Group(g) = &l.content { Some(g) } else { None }); + groups.flat_map(|g| &g.children).filter_map(|l| if let LayerContent::Shape(s) = &l.content { Some(s.path.clone()) } else { None }).collect::>() + }; + assert!(outlines(&on_disk).iter().any(|p| !p.subpaths.is_empty()), "the text has outlines"); + assert_eq!(outlines(&on_disk), outlines(&in_memory)); +} + +/// A font file that no longer loads (replaced or cut short since fontdb indexed it) keeps its +/// faces in the database and isn't remembered: once the file is whole again, text is set +/// from it. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_font_file_gone_bad_since_indexing_is_not_cached() { + use std::sync::atomic::{AtomicBool, Ordering}; + static BAD: AtomicBool = AtomicBool::new(true); + fn indexed_then_overwritten() -> Arc { + let path = std::env::temp_dir().join(format!("photocraft-svg-test-bad-{}.ttf", std::process::id())); + std::fs::write(&path, include_bytes!("../../../../assets/fonts/Inter-Regular.ttf")).unwrap(); + let mut db = usvg::fontdb::Database::new(); + db.load_font_file(&path).unwrap(); + if BAD.load(Ordering::SeqCst) { + std::fs::write(&path, b"not a font any more").unwrap(); + } + Arc::new(db) + } + let svg = b"IHI"; + let parsed = parse_with(svg, indexed_then_overwritten).unwrap(); + let sources: Vec<_> = parsed.tree.fontdb().faces().map(|f| matches!(f.source, usvg::fontdb::Source::File(_))).collect(); + assert_eq!(sources, [true], "the face stays in the database, on disk"); + BAD.store(false, Ordering::SeqCst); + let parsed = parse_with(svg, indexed_then_overwritten).unwrap(); + let sources: Vec<_> = parsed.tree.fontdb().faces().map(|f| matches!(f.source, usvg::fontdb::Source::Binary(_))).collect(); + assert_eq!(sources, [true], "the whole file is read into memory now"); + let layers = import_parsed("t", parsed, MAX_GROUP_DEPTH).unwrap().document.layers; + assert_eq!(layers.first().map(|l| l.name.as_str()), Some("IHI")); + assert!( + layers.iter().any(|l| matches!(&l.content, LayerContent::Group(g) if g.children.iter().any(|c| matches!(&c.content, LayerContent::Shape(s) if !s.path.subpaths.is_empty())))), + "the text has outlines" + ); +} + +/// Imports that miss the cache for the same file at once read it once: every one sets its +/// text from the same bytes, not a copy of its own next to the kept one. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn imports_missing_the_same_font_at_once_share_one_read() { + use std::sync::atomic::{AtomicUsize, Ordering}; + static ROUND: AtomicUsize = AtomicUsize::new(0); + fn fresh_file() -> Arc { + let round = ROUND.load(Ordering::SeqCst); + let path = std::env::temp_dir().join(format!("photocraft-svg-test-shared-{}-{round}.ttf", std::process::id())); + let mut db = usvg::fontdb::Database::new(); + db.load_font_file(&path).unwrap(); + Arc::new(db) + } + let svg = b"IHI"; + for round in 0..5 { + ROUND.store(round, Ordering::SeqCst); + let path = std::env::temp_dir().join(format!("photocraft-svg-test-shared-{}-{round}.ttf", std::process::id())); + std::fs::write(&path, include_bytes!("../../../../assets/fonts/Inter-Regular.ttf")).unwrap(); + let start = Arc::new(std::sync::Barrier::new(8)); + let threads: Vec<_> = (0..8) + .map(|_| { + let start = start.clone(); + std::thread::spawn(move || { + start.wait(); + let parsed = parse_with(svg, fresh_file).unwrap(); + let bytes: Vec<_> = parsed + .tree + .fontdb() + .faces() + .filter_map(|f| if let usvg::fontdb::Source::Binary(b) = &f.source { Some(Arc::as_ptr(b).cast::() as usize) } else { None }) + .collect(); + bytes + }) + }) + .collect(); + let bytes: Vec<_> = threads.into_iter().flat_map(|t| t.join().unwrap()).collect(); + assert_eq!(bytes.len(), 8, "every import set its text from memory"); + assert!(bytes.iter().all(|&b| b == bytes[0]), "round {round}: {bytes:x?}"); + let _ = std::fs::remove_file(&path); + } +} + +/// #9406: moving a font collection into memory keeps its faces in their order, so the +/// fallback search for a later text still finds the face it found on disk first. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_collection_in_memory_keeps_its_face_order() { + fn collection_on_disk() -> Arc { + // A two-face .ttc of the bundled Inter Regular and SemiBold: the `ttcf` header, then + // each font with its table offsets moved by where it starts. + let fonts: [&[u8]; 2] = [include_bytes!("../../../../assets/fonts/Inter-Regular.ttf"), include_bytes!("../../../../assets/fonts/Inter-SemiBold.ttf")]; + let mut ttc = b"ttcf������".to_vec(); + let mut start = 20; + let mut body = Vec::new(); + for f in fonts { + ttc.extend_from_slice(&u32::try_from(start).unwrap().to_be_bytes()); + let mut font = f.to_vec(); + for t in 0..usize::from(u16::from_be_bytes([font[4], font[5]])) { + let at = 12 + t * 16 + 8; + let off = u32::from_be_bytes(font[at..at + 4].try_into().unwrap()) + u32::try_from(start).unwrap(); + font[at..at + 4].copy_from_slice(&off.to_be_bytes()); + } + font.resize(font.len().next_multiple_of(4), 0); + start += font.len(); + body.extend(font); + } + ttc.extend(body); + let path = std::env::temp_dir().join(format!("photocraft-svg-test-{}.ttc", std::process::id())); + std::fs::write(&path, ttc).unwrap(); + let mut db = usvg::fontdb::Database::new(); + db.load_font_file(&path).unwrap(); + Arc::new(db) + } + let order = |db: &usvg::fontdb::Database| db.faces().map(|f| (f.index, f.weight.0)).collect::>(); + assert_eq!(order(&collection_on_disk()), [(0, 400), (1, 600)]); + let svg = b"IHI"; + let parsed = parse_with(svg, collection_on_disk).unwrap(); + let db = parsed.tree.fontdb(); + assert!(db.faces().all(|f| matches!(f.source, usvg::fontdb::Source::Binary(_))), "both faces of the file are in memory"); + assert_eq!(order(db), [(0, 400), (1, 600)]); +} + +#[test] +fn generic_families_point_at_installed_fonts() { + use usvg::fontdb::Family; + let db = inter_only(); + for g in [Family::SansSerif, Family::Serif, Family::Monospace, Family::Cursive, Family::Fantasy] { + assert_eq!(db.family_name(&g), "Inter", "{g:?}"); + } + // The system's choice wins when installed; a generic whose font is installed stays. + let mut db = usvg::fontdb::Database::new(); + db.load_font_data(include_bytes!("../../../../assets/fonts/Inter-Regular.ttf").to_vec()); + db.load_font_data(include_bytes!("../../../../assets/fonts/JetBrainsMono-Regular.ttf").to_vec()); + db.set_cursive_family("Inter"); + resolve_generic_families(&mut db, |g| Some(if g == "serif" { "JetBrains Mono" } else { "Not Installed" }.to_string())); + assert_eq!(db.family_name(&Family::Serif), "JetBrains Mono"); + assert_eq!(db.family_name(&Family::Monospace), "JetBrains Mono", "the bundled mono stand-in"); + assert_eq!(db.family_name(&Family::SansSerif), "Inter"); + assert_eq!(db.family_name(&Family::Cursive), "Inter"); + // An empty database is left alone. + let mut empty = usvg::fontdb::Database::new(); + resolve_generic_families(&mut empty, |_| Some("Inter".into())); + assert_eq!(empty.family_name(&Family::SansSerif), "Arial"); +} + +#[test] +fn rasterized_groups_stop_at_the_aggregate_pixel_budget() { + let mut svg = String::from(""); + svg.push_str(""); + for i in 0..8 { + svg.push_str(&format!("")); + } + svg.push_str(""); + // Enough for one retained 256×256 RGBA8 surface, not eight of them. + let budget = 256u64 * 256 * 4; + let result = import_parsed_with_budget("budget", parse(svg.as_bytes()).unwrap(), MAX_GROUP_DEPTH, budget).unwrap(); + assert_eq!(result.document.layers.len(), 1, "one U8 surface fills the retained-byte allowance"); + assert_eq!(result.document.layers[0].name, "g0"); + assert!(result.warnings.iter().any(|warning| warning.contains("pixel memory")), "{:?}", result.warnings); +} + +#[test] +fn oversized_raster_does_not_consume_budget_for_later_layers() { + let svg = br##" + + + + + + + + + + + "##; + let result = import_parsed_with_budget("budget", parse(svg).unwrap(), MAX_GROUP_DEPTH, 64 * 64 * 4).unwrap(); + assert_eq!(result.document.layers.len(), 1, "the oversized group must not debit the budget"); + assert_eq!(result.document.layers[0].name, "small"); + assert!(result.warnings.iter().any(|w| w.contains("too large to rasterise")), "{:?}", result.warnings); + assert!(!result.warnings.iter().any(|w| w.contains("pixel memory budget")), "{:?}", result.warnings); +} + +#[test] +fn skipped_expensive_raster_does_not_hide_a_smaller_one() { + let svg = br##" + + + + + + + "##; + let result = import_parsed_with_budget("budget", parse(svg).unwrap(), MAX_GROUP_DEPTH, 32 * 32 * 4).unwrap(); + assert_eq!(result.document.layers.len(), 1); + assert_eq!(result.document.layers[0].name, "small"); + assert!(result.warnings.iter().any(|w| w.contains("some rasterised elements were omitted")), "{:?}", result.warnings); +} + +#[test] +fn huge_drawings_scale_to_the_side_limit() { + let tree = parse(b"").unwrap().tree; + let mut w = Vec::new(); + let cv = canvas(&tree, &mut w); + assert_eq!((cv.size.width, cv.size.height), (MAX_SIDE, MAX_SIDE / 2)); + assert_eq!(w.len(), 1); +} + +#[test] +fn resolve_data_rejects_oversized_and_malformed_embedded_png_and_webp() { + let opt = options(Arc::new(usvg::fontdb::Database::new())); + let resolve = &opt.image_href_resolver.resolve_data; + let img = photocraft_codecs::Image::from_u8(2, 2, photocraft_codecs::ChannelLayout::Rgb, vec![255; 12]).unwrap(); + let valid_png = photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap(); + assert!(resolve("image/png", Arc::new(valid_png.clone()), &opt).is_some()); + assert!(resolve("text/plain", Arc::new(valid_png.clone()), &opt).is_some()); + + let mut huge_png = valid_png; + huge_png[16..20].copy_from_slice(&40_000u32.to_be_bytes()); + huge_png[20..24].copy_from_slice(&40_000u32.to_be_bytes()); + assert!(resolve("image/png", Arc::new(huge_png.clone()), &opt).is_none(), "oversized PNG rejected before decode"); + assert!(resolve("text/plain", Arc::new(huge_png), &opt).is_none(), "oversized mime-less PNG rejected before decode"); + + // Malformed WebP header under image/webp or text/plain must be rejected at the probe step. + let bad_webp = b"RIFF\x10\x00\x00\x00WEBPVP8 ".to_vec(); + assert!(resolve("image/webp", Arc::new(bad_webp.clone()), &opt).is_none()); + assert!(resolve("text/plain", Arc::new(bad_webp), &opt).is_none()); +} + +#[test] +fn jpeg_dimensions_come_from_the_frame_header_and_oversized_jpegs_are_refused() { + // SOI, an APP0 segment of length 4, then SOF0 (length 11): 8 bits, height 40000, width 30000. + let jpeg = |h: u16, w: u16| { + let mut v = vec![0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x04, 0, 0, 0xFF, 0xC0, 0x00, 0x0B, 8]; + v.extend(h.to_be_bytes()); + v.extend(w.to_be_bytes()); + v.extend([1, 1, 0x11, 0]); + v + }; + assert_eq!(jpeg_dimensions(&jpeg(40_000, 30_000)), Some((30_000, 40_000))); + assert_eq!(jpeg_dimensions(&[0xFF, 0xD8, 0xFF, 0xDA, 0, 2]), None); + assert_eq!(jpeg_dimensions(&[0xFF, 0xD8]), None); + let opt = options(Arc::new(usvg::fontdb::Database::new())); + let resolve = &opt.image_href_resolver.resolve_data; + // 1.2 billion pixels would be 4.8 GB of RGBA before resvg scaled anything down. + assert!(resolve("image/jpeg", Arc::new(jpeg(40_000, 30_000)), &opt).is_none()); + assert!(resolve("text/plain", Arc::new(jpeg(40_000, 30_000)), &opt).is_none()); +} + +#[test] +fn resolve_data_rejects_nested_gzip_and_handles_text_plain_svgz() { + use std::io::Write; + fn gz(bytes: &[u8]) -> Vec { + let mut e = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast()); + e.write_all(bytes).unwrap(); + e.finish().unwrap() + } + let opt = options(Arc::new(usvg::fontdb::Database::new())); + let resolve = &opt.image_href_resolver.resolve_data; + let svg = b""; + let once = gz(svg); + assert!(resolve("image/svg+xml", Arc::new(once.clone()), &opt).is_some()); + assert!(resolve("text/plain", Arc::new(once.clone()), &opt).is_some()); + + // Doubly gzip-compressed payload must be rejected rather than decompressed a second time by usvg. + let twice = gz(&once); + assert!(resolve("image/svg+xml", Arc::new(twice.clone()), &opt).is_none()); + assert!(resolve("text/plain", Arc::new(twice), &opt).is_none()); +} diff --git a/crates/ops/src/lib.rs b/crates/ops/src/lib.rs index 498c1deb8e..06d24e35ed 100644 --- a/crates/ops/src/lib.rs +++ b/crates/ops/src/lib.rs @@ -483,754 +483,4 @@ fn tile_bytes(doc: &Document, seen: &mut HashSet) -> usize { } #[cfg(test)] -mod tests { - use super::*; - use photocraft_doc::{Color, ColorMode, Layer, SampleType, Size}; - - fn base() -> Document { - Document::with_background("h", Size::new(64, 64), ColorMode::Rgb, SampleType::U8, Color::WHITE) - } - - /// Apply an edit the way the engine does: snapshot, mutate a clone, record. - fn edit(h: &mut History, cur: &mut Arc, label: &str, f: impl FnOnce(&mut Document)) { - let before = cur.clone(); - let mut d = (**cur).clone(); - f(&mut d); - *cur = Arc::new(d); - h.record(label, before, LayerTarget::default()); - } - - #[test] - fn undo_redo_cycle() { - let mut h = History::default(); - let mut cur = Arc::new(base()); - edit(&mut h, &mut cur, "New Layer", |d| { - d.insert_above(None, Layer::raster("L", d.pixel_format())); - }); - assert_eq!(cur.layers.len(), 2); - assert_eq!(h.undo_label(), Some("New Layer")); - cur = h.undo(cur).unwrap().0; - assert_eq!(cur.layers.len(), 1); - assert_eq!(h.redo_label(), Some("New Layer")); - cur = h.redo(cur).unwrap().0; - assert_eq!(cur.layers.len(), 2); - assert!(h.redo(cur.clone()).is_none()); - } - - #[test] - fn undo_and_redo_return_the_layers_each_state_targeted_when_created() { - let mut h = History::default(); - let open = Arc::new(base()); - let bg = open.layers[0].id; - let target = |id: LayerId| LayerTarget { active: Some(id), selected: vec![id] }; - h.set_current_layers(target(bg)); - // New Layer targets the new layer; the background is then selected (not a step) and filled. - let mut d = (*open).clone(); - let new = d.insert_above(None, Layer::raster("L", d.pixel_format())); - let layered = Arc::new(d); - h.record("New Layer", open, target(new)); - let mut d = (*layered).clone(); - d.name = "filled".into(); - h.record("Fill", layered, target(bg)); - let (d, layers) = h.undo(Arc::new(d)).unwrap(); - assert_eq!(layers, target(new), "New Layer's state targeted the new layer when created"); - let (d, layers) = h.undo(d).unwrap(); - assert_eq!(layers, target(bg), "the opened document's target"); - let (d, layers) = h.redo(d).unwrap(); - assert_eq!(layers, target(new)); - let (_, layers) = h.redo(d).unwrap(); - assert_eq!(layers, target(bg), "Fill's state targeted the background"); - } - - #[test] - fn state_accessor_matches_entries() { - let mut h = History::default(); - let mut cur = Arc::new(base()); - let open = cur.clone(); - edit(&mut h, &mut cur, "A", |d| d.name = "a".into()); - edit(&mut h, &mut cur, "B", |d| d.name = "b".into()); - assert_eq!(h.entries().len(), h.past_len() + 1); - assert!(Arc::ptr_eq(&h.state(0).unwrap(), &open)); - assert_eq!(h.state(1).unwrap().name, "a"); - assert!(h.state(2).is_none(), "the current document is not held"); - cur = h.undo(cur).unwrap().0; - h.undo(cur).unwrap(); - assert_eq!(h.redo_labels().collect::>(), ["A", "B"], "next redo first"); - } - - /// The History Brush source is a state, not an index: it stays on its state through undo, - /// redo and older states falling off, is kept when it would fall off itself, and is gone - /// (no source) once a new step discards it. - #[test] - fn brush_source_follows_its_state() { - let mut h = History::new(3); - let mut cur = Arc::new(base()); - assert_eq!(h.brush_source(), Some(0), "default: the oldest state"); - assert!(!h.set_brush_source(1), "no such row yet"); - edit(&mut h, &mut cur, "A", |d| d.name = "a".into()); - edit(&mut h, &mut cur, "B", |d| d.name = "b".into()); - assert!(h.set_brush_source(1)); - assert_eq!(h.row_doc(1, &cur).unwrap().name, "a"); - // Undo / redo: the rows stay put, and A's state is still row 1. - cur = h.undo(cur).unwrap().0; - assert_eq!((h.brush_source(), h.row_doc(1, &cur).unwrap().name.as_str()), (Some(1), "a")); - assert_eq!(h.row_doc(2, &cur).unwrap().name, "b", "a redo row"); - cur = h.redo(cur).unwrap().0; - // Open falls off the 3-state limit: A's state moves up to row 0 and stays the source. - edit(&mut h, &mut cur, "C", |d| d.name = "c".into()); - edit(&mut h, &mut cur, "D", |d| d.name = "d".into()); - assert_eq!(h.entries(), ["A", "B", "C", "D"]); - assert_eq!(h.brush_source(), Some(0)); - // A would fall off next: it is kept, and the states after it fall off instead. - edit(&mut h, &mut cur, "E", |d| d.name = "e".into()); - edit(&mut h, &mut cur, "F", |d| d.name = "f".into()); - assert_eq!(h.entries(), ["A", "D", "E", "F"]); - assert_eq!((h.brush_source(), h.row_doc(0, &cur).unwrap().name.as_str()), (Some(0), "a")); - // A redo state as the source, discarded by a new step: no source until one is set. - cur = h.undo(cur).unwrap().0; - assert!(h.set_brush_source(3), "the greyed F row"); - assert_eq!((h.brush_source(), h.row_doc(3, &cur).unwrap().name.as_str()), (Some(3), "f")); - assert!(h.row_doc(4, &cur).is_none() && h.row_id(4).is_none()); - edit(&mut h, &mut cur, "G", |d| d.name = "g".into()); - assert_eq!(h.brush_source(), None); - // The current state as the source keeps it once it becomes a past state; once it is no - // longer the source, it falls off as usual. - assert!(h.set_brush_source(3)); - edit(&mut h, &mut cur, "H", |d| d.name = "h".into()); - assert_eq!((h.brush_source(), h.row_doc(2, &cur).unwrap().name.as_str()), (Some(2), "g")); - assert!(h.set_brush_source(1)); - edit(&mut h, &mut cur, "I", |d| d.name = "i".into()); - assert_eq!(h.entries(), ["E", "G", "H", "I"]); - } - - #[test] - fn byte_budget_keeps_the_brush_source() { - let mut h = History::new(50); - let mut cur = Arc::new(base()); - for i in 0..5 { - edit(&mut h, &mut cur, &format!("paint {i}"), |d| { - let id = d.layers[0].id; - d.layer_mut(id).unwrap().surface_mut().unwrap().write_pixel(1, 1, &[i as f32 / 8.0, 0.0, 0.0, 1.0]); - }); - } - assert!(h.set_brush_source(1)); - h.max_bytes = 1; - let dropped = h.trim(&cur); - assert_eq!(h.entries(), ["paint 0", "paint 3", "paint 4"], "the source is kept with the last step"); - assert_eq!(dropped, 3); - assert_eq!(h.brush_source(), Some(0)); - } - - /// The pinned source counts against the byte budget: with room for three states, the - /// source and the two newest are kept, never more than the budget (#3536 review). - #[test] - fn byte_budget_counts_the_brush_source_first() { - let mut h = History::new(50); - let mut cur = Arc::new(base()); - let tile = h.pixel_bytes(&cur); - assert!(tile > 0); - for i in 0..5 { - edit(&mut h, &mut cur, &format!("paint {i}"), |d| { - let id = d.layers[0].id; - d.layer_mut(id).unwrap().surface_mut().unwrap().write_pixel(1, 1, &[i as f32 / 8.0, 0.0, 0.0, 1.0]); - }); - } - // Every state holds one tile of its own; the source is the oldest (Open). - assert!(h.set_brush_source(0)); - h.max_bytes = tile * 4; - assert_eq!(h.trim(&cur), 2); - assert_eq!(h.entries(), ["Open", "paint 2", "paint 3", "paint 4"]); - assert!(h.pixel_bytes(&cur) <= h.max_bytes, "{} > {}", h.pixel_bytes(&cur), h.max_bytes); - assert_eq!(h.trim(&cur), 0, "it fits now"); - // A new step trims to the budget again, still keeping the source. - edit(&mut h, &mut cur, "paint 5", |d| { - let id = d.layers[0].id; - d.layer_mut(id).unwrap().surface_mut().unwrap().write_pixel(1, 1, &[1.0, 0.0, 0.0, 1.0]); - }); - assert_eq!(h.trim(&cur), 1); - assert_eq!(h.entries(), ["Open", "paint 3", "paint 4", "paint 5"]); - assert!(h.pixel_bytes(&cur) <= h.max_bytes); - assert_eq!(h.brush_source(), Some(0)); - } - - /// Edit › Purge › Histories clears every state: a source set on one of them goes back to the - /// default (the oldest state held) instead of leaving no source (#3536 review). - #[test] - fn clear_resets_the_brush_source() { - let mut h = History::new(50); - let mut cur = Arc::new(base()); - edit(&mut h, &mut cur, "A", |d| d.name = "a".into()); - edit(&mut h, &mut cur, "B", |d| d.name = "b".into()); - assert!(h.set_brush_source(1)); - h.clear(); - assert_eq!(h.brush_source(), Some(0)); - assert_eq!(h.row_doc(0, &cur).unwrap().name, "b"); - } - - /// History panel › Clear History leaves a usable (default) source, and its undo restores the - /// source set on a past state. - #[test] - fn clear_states_resets_the_brush_source_until_undo() { - let mut h = History::new(50); - let mut cur = Arc::new(base()); - edit(&mut h, &mut cur, "A", |d| d.name = "a".into()); - edit(&mut h, &mut cur, "B", |d| d.name = "b".into()); - assert!(h.set_brush_source(1)); - assert!(h.clear_states()); - assert_eq!(h.brush_source(), Some(0)); - assert_eq!(h.row_doc(0, &cur).unwrap().name, "b"); - cur = h.undo(cur).unwrap().0; - assert_eq!((h.brush_source(), h.row_doc(1, &cur).unwrap().name.as_str()), (Some(1), "a")); - } - - #[test] - fn new_edit_clears_redo() { - let mut h = History::default(); - let mut cur = Arc::new(base()); - edit(&mut h, &mut cur, "A", |d| d.name = "a".into()); - cur = h.undo(cur).unwrap().0; - edit(&mut h, &mut cur, "B", |d| d.name = "b".into()); - assert!(!h.can_redo()); - assert_eq!(h.entries(), vec!["Open".to_string(), "B".to_string()]); - } - - #[test] - fn max_states_bound() { - let mut h = History::new(3); - let mut cur = Arc::new(base()); - for i in 0..10 { - edit(&mut h, &mut cur, &format!("step {i}"), |d| d.name = format!("{i}")); - } - let mut n = 0; - while let Some((d, _)) = h.undo(cur.clone()) { - cur = d; - n += 1; - } - assert_eq!(n, 3); - assert_eq!(cur.name, "6"); - } - - #[test] - fn byte_budget_drops_oldest_states_but_keeps_one() { - let mut h = History::new(50); - let mut cur = Arc::new(base()); - let tile = 256 * 256 * 4; - // Each step repaints the background's tile: one unique tile per state. - for i in 0..6 { - edit(&mut h, &mut cur, &format!("paint {i}"), |d| { - let id = d.layers[0].id; - d.layer_mut(id).unwrap().surface_mut().unwrap().write_pixel(1, 1, &[i as f32 / 8.0, 0.0, 0.0, 1.0]); - }); - } - assert_eq!(h.trim(&cur), 0, "unlimited by default"); - assert_eq!(h.past_len(), 6); - // The current tile plus three history tiles fit. - h.max_bytes = 4 * tile; - assert_eq!(h.trim(&cur), 3); - assert_eq!(h.past_len(), 3); - assert_eq!(h.unique_bytes(&cur), 3 * tile); - assert_eq!(h.pixel_bytes(&cur), 4 * tile, "the current tile plus history's"); - assert_eq!(h.entries()[0], "paint 2"); - // A budget smaller than one state still keeps the last step undoable. - h.max_bytes = 1; - h.trim(&cur); - assert_eq!(h.past_len(), 1); - assert!(h.undo(cur.clone()).is_some()); - } - - /// Snapshot-only tiles count against the budget (#4530); tiles a snapshot shares with the - /// document or a state count once, and a purge frees only what no snapshot keeps. - #[test] - fn snapshot_tiles_count_against_the_budget() { - let mut h = History::new(50); - let mut cur = Arc::new(base()); - let tile = 256 * 256 * 4; - let paint = |d: &mut Document, v: f32| { - let id = d.layers[0].id; - d.layer_mut(id).unwrap().surface_mut().unwrap().write_pixel(1, 1, &[v, 0.0, 0.0, 1.0]); - }; - // A snapshot holding a tile nothing else does, then one sharing the first state's tile. - let mut own = (*cur).clone(); - paint(&mut own, 0.9); - edit(&mut h, &mut cur, "paint 0", |d| paint(d, 0.1)); - let shared = h.state(0).unwrap(); - for i in 1..6 { - edit(&mut h, &mut cur, &format!("paint {i}"), |d| paint(d, i as f32 / 8.0)); - } - let snaps = [&own, &*shared]; - assert_eq!(h.extra_bytes(&cur, &snaps), tile, "the shared tile is history's"); - assert_eq!(h.extra_bytes(&cur, &[]), 0); - assert_eq!(h.unique_bytes(&cur), 6 * tile); - assert_eq!(h.unique_bytes_besides(&cur, &snaps), 5 * tile, "clearing keeps the shared tile"); - // Both snapshot tiles stay whatever is trimmed (the shared one too), so beside the - // current tile they leave room for two history tiles; without them, four would fit. - h.max_bytes = 5 * tile; - assert_eq!(h.trim_with(&cur, &snaps), 4); - assert_eq!(h.past_len(), 2); - assert_eq!(h.pixel_bytes(&cur) + h.extra_bytes(&cur, &snaps), 5 * tile); - // Still keeps the last step undoable. - h.max_bytes = 1; - h.trim_with(&cur, &snaps); - assert_eq!(h.past_len(), 1); - } - - #[test] - fn history_shares_untouched_tiles() { - let mut h = History::default(); - let mut cur = Arc::new(base()); - assert_eq!(h.unique_bytes(&cur), 0); - // rename only: no pixel changes, history holds no unique tiles - edit(&mut h, &mut cur, "Rename", |d| d.name = "x".into()); - assert_eq!(h.unique_bytes(&cur), 0); - // paint one pixel: exactly one tile becomes unique to history - edit(&mut h, &mut cur, "Paint", |d| { - let id = d.layers[0].id; - d.layer_mut(id).unwrap().surface_mut().unwrap().write_pixel(1, 1, &[0.0, 0.0, 0.0, 1.0]); - }); - assert_eq!(h.unique_bytes(&cur), 256 * 256 * 4); - } - - #[test] - fn fill_caches_and_smart_filter_masks_count_toward_history_bytes() { - use photocraft_doc::{Affine, Fill, FillCache, LayerContent, LayerMask, PixelFormat, SmartObject, SmartSource, Surface}; - let mut doc = Document::new("fills", Size::new(64, 64), ColorMode::Rgb, SampleType::U8); - let mut fill = Layer::new("Fill", LayerContent::Fill(Fill::Solid(Color::WHITE))); - let mut cache = Surface::new(PixelFormat::GRAY8); - cache.write_pixel(1, 1, &[1.0]); - fill.fill_cache = Some(FillCache { fill: Fill::Solid(Color::WHITE), surface: cache }); - doc.insert_above(None, fill); - let mut smart_obj = SmartObject::new(SmartSource::Linked { path: "a.png".into() }, Affine::IDENTITY, None); - let mut mask = LayerMask::reveal_all(); - mask.surface.write_pixel(1, 1, &[0.5]); - smart_obj.filter_mask = Some(mask); - doc.insert_above(None, Layer::new("Smart", LayerContent::Smart(smart_obj))); - let tile = 256 * 256; - let mut cur = Arc::new(doc); - let mut h = History { max_bytes: usize::MAX, ..History::default() }; - assert_eq!(h.pixel_bytes(&cur), 2 * tile, "fill cache and smart filter mask are counted"); - edit(&mut h, &mut cur, "Rename", |doc| doc.name = "renamed".into()); - assert_eq!(h.pixel_bytes(&cur), 2 * tile, "shared tiles count once"); - edit(&mut h, &mut cur, "Fill cache", |doc| { - let id = doc.layers[0].id; - if let Some(cache) = doc.layer_mut(id).and_then(|l| l.fill_cache.as_mut()) { - cache.surface.write_pixel(1, 1, &[0.0]); - } - }); - assert_eq!(h.pixel_bytes(&cur), 3 * tile, "the copied fill cache tile is history-only"); - assert_eq!(h.unique_bytes(&cur), tile); - h.trim(&cur); - assert_counter(&h, &cur); - h.max_bytes = 2 * tile; - assert_eq!(h.trim(&cur), 1, "the copied fill cache tile pushes history over budget"); - assert_eq!(h.pixel_bytes(&cur), 3 * tile, "the most recent undo state is always kept"); - assert_counter(&h, &cur); - } - - #[test] - fn selection_tiles_count_current_and_history_without_double_counting() { - use photocraft_doc::{PixelFormat, Surface}; - for depth in SampleType::ALL { - let mut doc = Document::new("selection", Size::new(300, 64), ColorMode::Rgb, depth); - let mut selection = Surface::new(PixelFormat::new(ColorMode::Grayscale, depth, false)); - selection.write_pixel(1, 1, &[1.0]); - selection.write_pixel(257, 1, &[1.0]); - doc.selection = Some(selection); - let mut cur = Arc::new(doc); - let tile = match depth { - SampleType::U8 => 65_536, - SampleType::U16 => 131_072, - SampleType::F32 => 262_144, - }; - let mut h = History { max_bytes: usize::MAX, ..History::default() }; - assert_eq!(h.pixel_bytes(&cur), 2 * tile, "current selection counts without any history"); - assert_eq!(h.unique_bytes(&cur), 0); - edit(&mut h, &mut cur, "Rename", |doc| doc.name = "renamed".into()); - assert_eq!(h.pixel_bytes(&cur), 2 * tile, "the shared selection tiles count once"); - edit(&mut h, &mut cur, "Selection", |doc| { - doc.selection.as_mut().unwrap().write_pixel(1, 1, &[0.5]); - }); - assert_eq!(h.pixel_bytes(&cur), 3 * tile, "only the changed selection tile is copied"); - assert_eq!(h.unique_bytes(&cur), tile); - h.trim(&cur); - assert_counter(&h, &cur); - let selected_value = cur.selection.as_ref().unwrap().sample_channel(1, 1, 0); - edit(&mut h, &mut cur, "Deselect", |doc| doc.selection = None); - assert_eq!(h.pixel_bytes(&cur), 3 * tile, "deselecting leaves the previous masks in history"); - assert_eq!(h.unique_bytes(&cur), 3 * tile); - assert_counter(&h, &cur); - cur = h.undo(cur).unwrap().0; - assert_eq!(cur.selection.as_ref().unwrap().sample_channel(1, 1, 0), selected_value); - assert_eq!(h.pixel_bytes(&cur), 3 * tile); - assert_eq!(h.unique_bytes(&cur), tile); - assert_counter(&h, &cur); - // Coalescing can change the current mask without recording another state. - Arc::make_mut(&mut cur).selection.as_mut().unwrap().write_pixel(257, 1, &[0.25]); - assert_eq!(h.pixel_bytes(&cur), 4 * tile); - assert_eq!(h.trim(&cur), 0); - assert_counter(&h, &cur); - cur = h.redo(cur).unwrap().0; - assert!(cur.selection.is_none()); - assert_eq!(h.pixel_bytes(&cur), 4 * tile); - assert_counter(&h, &cur); - } - } - - #[test] - fn selection_byte_budget_drops_old_masks_and_keeps_the_last_undo() { - use photocraft_doc::{PixelFormat, Surface}; - for depth in SampleType::ALL { - let mut doc = Document::new("selection", Size::new(64, 64), ColorMode::Rgb, depth); - doc.selection = Some(Surface::new(PixelFormat::new(ColorMode::Grayscale, depth, false))); - let mut cur = Arc::new(doc); - let tile = 256 * 256 * depth.bytes(); - let mut h = History::default(); - for i in 1..=6 { - edit(&mut h, &mut cur, "Selection", |doc| { - doc.selection.as_mut().unwrap().write_pixel(1, 1, &[i as f32 / 8.0]); - }); - } - assert_eq!(h.pixel_bytes(&cur), 6 * tile); - h.max_bytes = 3 * tile; - assert_eq!(h.trim(&cur), 4); - assert_eq!(h.past_len(), 2); - assert_eq!(h.pixel_bytes(&cur), 3 * tile); - assert_eq!(h.unique_bytes(&cur), 2 * tile); - assert_counter(&h, &cur); - h.max_bytes = 1; - assert_eq!(h.trim(&cur), 1); - assert_eq!(h.past_len(), 1, "the most recent undo survives even below one mask's size"); - assert_eq!(h.pixel_bytes(&cur), 2 * tile); - cur = h.undo(cur).unwrap().0; - assert_counter(&h, &cur); - } - } - - fn assert_counter(h: &History, current: &Document) { - let counter = h.tiles.as_ref().expect("budget initializes the counter"); - let total = tile_bytes(current, &mut HashSet::new()).saturating_add(h.unique_bytes(current)); - assert_eq!(counter.bytes_with(current), total as u128); - assert_eq!(h.pixel_bytes(current), total); - let mut seen = HashSet::new(); - let retained: usize = h.held_states().map(|s| tile_bytes(&s.doc, &mut seen)).sum(); - let empty = Document::new("empty", Size::new(1, 1), ColorMode::Rgb, SampleType::U8); - assert_eq!(counter.bytes_with(&empty), retained as u128); - } - - fn video_document(depth: SampleType, frames: usize) -> Document { - let mut doc = Document::new("video", Size::new(64, 64), ColorMode::Rgb, depth); - let mut layer = Layer::raster("Video", doc.pixel_format()); - let footage: Vec<_> = (0..frames) - .map(|i| { - let mut surface = photocraft_doc::Surface::new(doc.pixel_format()); - surface.write_pixel(1, 1, &[i as f32 / frames as f32, 0.0, 0.0, 1.0]); - surface - }) - .collect(); - layer.content = photocraft_doc::LayerContent::Raster(footage[0].clone()); - layer.video = Some(photocraft_doc::VideoData::new(footage, 24.0)); - doc.layers.push(layer); - doc - } - - #[test] - fn video_memory_counts_originals_and_deduplicates_displayed_frames() { - for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { - let mut doc = video_document(depth, 3); - let tile = doc.layers[0].surface().unwrap().tiles().next().unwrap().1.bytes().len(); - let video = doc.layers[0].video.as_mut().unwrap(); - video.original_frames = Some(video.frames.clone()); - // Original footage and the displayed frame alias the stack, except this painted frame. - video.frames[2].write_pixel(1, 1, &[0.0, 1.0, 0.0, 1.0]); - let mut cur = Arc::new(doc); - let mut h = History { max_bytes: usize::MAX, ..History::default() }; - assert_eq!(h.pixel_bytes(&cur), 4 * tile); - for name in ["A", "B"] { - edit(&mut h, &mut cur, "Rename", |doc| doc.name = name.into()); - h.trim(&cur); - } - assert_counter(&h, &cur); - assert_eq!(h.pixel_bytes(&cur), 4 * tile); - assert_eq!(h.unique_bytes(&cur), 0); - // Rasterizing keeps the displayed frame; the rest of the clip survives only in undo. - edit(&mut h, &mut cur, "Rasterize", |doc| doc.layers[0].video = None); - assert_eq!(h.unique_bytes(&cur), 3 * tile); - assert_eq!(h.pixel_bytes(&cur), 4 * tile); - assert_counter(&h, &cur); - cur = h.undo(cur).unwrap().0; - assert_eq!(h.unique_bytes(&cur), 0); - assert_counter(&h, &cur); - cur = h.redo(cur).unwrap().0; - assert_eq!(h.unique_bytes(&cur), 3 * tile); - assert_counter(&h, &cur); - h.clear(); - assert_eq!(h.pixel_bytes(&cur), tile); - } - } - - #[test] - fn video_memory_budget_evicts_deleted_off_playhead_frames() { - for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { - let mut cur = Arc::new(video_document(depth, 6)); - let tile = cur.layers[0].surface().unwrap().tiles().next().unwrap().1.bytes().len(); - let mut h = History::default(); - for _ in 0..4 { - edit(&mut h, &mut cur, "Delete Frame", |doc| { - doc.layers[0].video.as_mut().unwrap().frames.remove(1); - }); - } - assert_eq!(h.pixel_bytes(&cur), 6 * tile); - assert_eq!(h.unique_bytes(&cur), 4 * tile); - h.max_bytes = 3 * tile; - assert_eq!(h.trim(&cur), 3); - assert_eq!(h.past_len(), 1); - assert_eq!(h.pixel_bytes(&cur), 3 * tile); - assert_eq!(h.unique_bytes(&cur), tile); - assert_counter(&h, &cur); - cur = h.undo(cur).unwrap().0; - assert_eq!(cur.layers[0].video.as_ref().unwrap().frames.len(), 3); - assert_counter(&h, &cur); - cur = h.redo(cur).unwrap().0; - assert_eq!(cur.layers[0].video.as_ref().unwrap().frames.len(), 2); - assert_counter(&h, &cur); - // A budget below the remaining clip still keeps the latest step undoable. - h.max_bytes = 1; - assert_eq!(h.trim(&cur), 0); - assert!(h.can_undo()); - } - } - - /// A pattern fill or layer style copies its pattern into the document, so the pattern's tiles - /// count like layer pixels, shared ones once; undoing that step leaves them to the redo states. - #[test] - fn document_patterns_count_as_document_pixels() { - use photocraft_doc::{Pattern, Surface}; - for depth in SampleType::ALL { - let tile = 4 * 256 * 256 * depth.bytes(); - let mut cur = Arc::new(Document::new("patterns", Size::new(64, 64), ColorMode::Rgb, depth)); - let mut h = History { max_bytes: usize::MAX, ..History::default() }; - for name in ["A", "B"] { - edit(&mut h, &mut cur, "Rename", |doc| doc.name = name.into()); - h.trim(&cur); - } - let mut surface = Surface::new(cur.pixel_format()); - surface.write_pixel(1, 1, &[0.0, 0.0, 1.0, 1.0]); - let pattern = Pattern::new("Pattern", surface, 4, 4); - edit(&mut h, &mut cur, "Pattern Fill", |doc| doc.patterns.push(pattern)); - assert_eq!(h.pixel_bytes(&cur), tile, "the document's pattern"); - assert_eq!(h.unique_bytes(&cur), 0); - assert_counter(&h, &cur); - edit(&mut h, &mut cur, "Rename", |doc| doc.name = "C".into()); - assert_eq!(h.pixel_bytes(&cur), tile, "shared with history, it counts once"); - assert_counter(&h, &cur); - for _ in 0..2 { - cur = h.undo(cur).unwrap().0; - assert_counter(&h, &cur); - } - assert!(cur.patterns.is_empty()); - assert_eq!(h.unique_bytes(&cur), tile, "only the redo states hold the pattern"); - assert_eq!(h.pixel_bytes(&cur), tile); - cur = h.redo(cur).unwrap().0; - assert_eq!(h.unique_bytes(&cur), 0); - assert_counter(&h, &cur); - h.clear(); - assert_eq!(h.pixel_bytes(&cur), tile); - } - } - - #[test] - fn counter_tracks_eviction_undo_redo_branching_purge_and_clones() { - for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { - let mut cur = Arc::new(Document::with_background("h", Size::new(300, 64), ColorMode::Rgb, depth, Color::WHITE)); - Arc::make_mut(&mut cur).selection = Some(photocraft_doc::Surface::new(photocraft_doc::PixelFormat::GRAY8)); - let mut h = History::new(4); - h.max_bytes = usize::MAX; - for i in 0..8 { - edit(&mut h, &mut cur, "Paint", |doc| { - doc.layers[0].surface_mut().unwrap().write_pixel(1, 1, &[i as f32 / 10.0, 0.0, 0.0, 1.0]); - doc.selection.as_mut().unwrap().write_pixel(1, 1, &[i as f32 / 10.0]); - }); - h.trim(&cur); - if i >= 1 { - assert_counter(&h, &cur); - } - } - cur = h.undo(cur).unwrap().0; - assert_counter(&h, &cur); - cur = h.undo(cur).unwrap().0; - assert_counter(&h, &cur); - cur = h.redo(cur).unwrap().0; - assert_counter(&h, &cur); - let copy = h.clone(); - edit(&mut h, &mut cur, "Branch", |doc| doc.name = "branch".into()); - assert!(!h.can_redo()); - assert_counter(&h, &cur); - assert_counter(©, &cur); - cur = h.undo(cur).unwrap().0; - h.clear_redo(); - assert_counter(&h, &cur); - h.purge_last(); - assert_counter(&h, &cur); - h.clear(); - assert!(h.tiles.is_none()); - assert_eq!(h.pixel_bytes(&cur), tile_bytes(&cur, &mut HashSet::new())); - } - } - - #[test] - fn shared_masks_channels_and_repeated_snapshot_references_count_once() { - use photocraft_doc::{AlphaChannel, LayerMask, PixelFormat, Surface}; - let mut doc = base(); - let mut gray = Surface::new(PixelFormat::GRAY8); - gray.write_pixel(1, 1, &[1.0]); - doc.layers[0].mask = Some(LayerMask { surface: gray.clone(), ..LayerMask::reveal_all() }); - doc.channels.push(AlphaChannel::new("alpha", gray.clone())); - doc.selection = Some(gray.clone()); - doc.quick_mask = Some(AlphaChannel::new("quick", gray)); - doc.layers.push(doc.layers[0].clone()); - let mut cur = Arc::new(doc); - let bytes = tile_bytes(&cur, &mut HashSet::new()); - let mut h = History::new(50); - // Counting current separately would double count its tiles; the exact union fits. - h.max_bytes = bytes; - for _ in 0..6 { - h.record("Same", cur.clone(), LayerTarget::default()); - assert_eq!(h.trim(&cur), 0); - } - assert_counter(&h, &cur); - for _ in 0..3 { - cur = h.undo(cur).unwrap().0; - assert_counter(&h, &cur); - } - h.clear_redo(); - h.purge_last(); - assert_counter(&h, &cur); - assert_eq!(h.pixel_bytes(&cur), bytes); - } - - #[test] - fn threshold_rechecks_coalesced_current_and_changed_budget() { - let mut h = History::new(50); - let mut cur = Arc::new(base()); - h.max_bytes = usize::MAX; - for i in 0..6 { - edit(&mut h, &mut cur, "Paint", |doc| { - doc.layers[0].surface_mut().unwrap().write_pixel(1, 1, &[i as f32 / 10.0, 0.0, 0.0, 1.0]); - }); - h.trim(&cur); - } - // A coalesced edit may change current without recording another history state. - Arc::make_mut(&mut cur).layers[0].surface_mut().unwrap().write_pixel(300, 1, &[1.0; 4]); - let tile = 256 * 256 * 4; - h.max_bytes = 4 * tile; - assert_eq!(h.trim(&cur), 4); - assert_eq!(h.past_len(), 2); - assert_counter(&h, &cur); - cur = h.undo(cur).unwrap().0; - assert_counter(&h, &cur); - h.max_bytes = 0; - edit(&mut h, &mut cur, "Unlimited", |doc| doc.name = "u".into()); - assert!(h.tiles.is_none()); - h.max_bytes = 1; - h.trim(&cur); - assert_eq!(h.past_len(), 1, "always retain the most recent undo"); - assert_counter(&h, &cur); - } - - #[test] - fn transferred_tiles_cannot_make_the_budget_check_underestimate_current() { - use photocraft_doc::{PixelFormat, Surface}; - let before = Arc::new(base()); - let mut current = (*before).clone(); - let mut large = Surface::new(PixelFormat::new(ColorMode::Cmyk, SampleType::F32, true)); - large.write_pixel(256, 0, &[1.0; 5]); - current.layers[0].surface_mut().unwrap().put_tiles(large.take_tiles(photocraft_doc::Rect::from_xywh(256, 0, 1, 1))); - let mut h = History::new(50); - h.max_bytes = tile_bytes(¤t, &mut HashSet::new()) - 1; - h.record("A", before.clone(), LayerTarget::default()); - h.record("B", before, LayerTarget::default()); - assert_eq!(h.trim(¤t), 1, "current alone exceeds the budget; only the mandatory undo survives"); - assert_counter(&h, ¤t); - } - - #[test] - fn clear_states_keeps_the_document_and_undo_brings_the_list_back() { - let mut h = History::new(10); - let mut cur = Arc::new(base()); - edit(&mut h, &mut cur, "A", |d| d.name = "a".into()); - edit(&mut h, &mut cur, "B", |d| d.name = "b".into()); - edit(&mut h, &mut cur, "C", |d| d.name = "c".into()); - let (d, _) = h.undo(cur.clone()).unwrap(); - cur = d; - let entries = h.entries(); - assert_eq!(entries, ["Open", "A", "B"]); - assert!(h.clear_states()); - assert_eq!(h.entries(), ["B"], "only the current state is left"); - assert!(!h.can_redo() && h.can_undo() && h.is_cleared()); - assert_eq!(h.undo_label(), Some(CLEAR_HISTORY_LABEL)); - assert!(!h.clear_states(), "nothing left to clear"); - assert!(h.is_cleared(), "and the cleared states are still held"); - let (d, _) = h.undo(cur.clone()).unwrap(); - assert!(Arc::ptr_eq(&d, &cur), "undoing Clear History doesn't change the document"); - assert_eq!(h.entries(), entries); - assert_eq!(h.redo_labels().collect::>(), ["C"], "the redo state is back too"); - assert!(!h.is_cleared()); - } - - #[test] - fn cleared_states_still_count_in_the_memory_figures_and_the_budget() { - let mut h = History::new(50); - let mut cur = Arc::new(base()); - let tile = 256 * 256 * 4; - for i in 0..5 { - edit(&mut h, &mut cur, &format!("paint {i}"), |d| { - let id = d.layers[0].id; - d.layer_mut(id).unwrap().surface_mut().unwrap().write_pixel(1, 1, &[i as f32 / 8.0, 0.0, 0.0, 1.0]); - }); - } - cur = h.undo(cur).unwrap().0; - let (unique, pixels) = (h.unique_bytes(&cur), h.pixel_bytes(&cur)); - assert_eq!(unique, 5 * tile, "four undo states and one redo state"); - assert!(h.clear_states()); - assert_eq!(h.unique_bytes(&cur), unique, "Clear History frees nothing while it can be undone"); - assert_eq!(h.pixel_bytes(&cur), pixels); - assert_eq!(h.extra_bytes(&cur, &[&base()]), tile, "a snapshot's own tile, not the cleared states'"); - assert_eq!(h.unique_bytes_besides(&cur, &[]), unique); - // The budget counts them too: the oldest cleared states go first. - h.max_bytes = 4 * tile; - assert_eq!(h.trim(&cur), 2); - assert_counter(&h, &cur); - assert_eq!(h.pixel_bytes(&cur), 4 * tile); - assert!(h.is_cleared() && h.past_len() == 0, "the list stays cleared"); - h.undo(cur.clone()).unwrap(); - assert_eq!(h.entries(), ["paint 1", "paint 2", "paint 3"], "undo brings back what the budget kept"); - assert_eq!(h.redo_labels().collect::>(), ["paint 4"]); - // A new step after Clear History forgets the cleared states, and the counter with them. - assert!(h.clear_states()); - h.trim(&cur); - edit(&mut h, &mut cur, "paint 5", |d| { - let id = d.layers[0].id; - d.layer_mut(id).unwrap().surface_mut().unwrap().write_pixel(1, 1, &[1.0, 0.0, 0.0, 1.0]); - }); - assert_eq!(h.unique_bytes(&cur), tile, "only the state before the new step"); - assert_eq!(h.pixel_bytes(&cur), 2 * tile); - } - - #[test] - fn a_new_step_or_purge_forgets_the_cleared_states() { - let mut h = History::new(10); - let mut cur = Arc::new(base()); - edit(&mut h, &mut cur, "A", |d| d.name = "a".into()); - assert!(h.clear_states()); - edit(&mut h, &mut cur, "B", |d| d.name = "b".into()); - assert_eq!(h.entries(), ["A", "B"]); - assert!(!h.is_cleared()); - assert!(h.undo(cur.clone()).is_some()); - assert!(!h.can_undo(), "the cleared states are gone"); - let mut h = History::new(10); - edit(&mut h, &mut cur, "A", |d| d.name = "a".into()); - assert!(h.clear_states()); - assert!(h.purge_last()); - assert!(!h.can_undo() && !h.is_cleared()); - assert!(!h.clear_states(), "a single state can't be cleared"); - } -} +mod tests; diff --git a/crates/ops/src/tests.rs b/crates/ops/src/tests.rs new file mode 100644 index 0000000000..1ac12b2885 --- /dev/null +++ b/crates/ops/src/tests.rs @@ -0,0 +1,749 @@ +use super::*; +use photocraft_doc::{Color, ColorMode, Layer, SampleType, Size}; + +fn base() -> Document { + Document::with_background("h", Size::new(64, 64), ColorMode::Rgb, SampleType::U8, Color::WHITE) +} + +/// Apply an edit the way the engine does: snapshot, mutate a clone, record. +fn edit(h: &mut History, cur: &mut Arc, label: &str, f: impl FnOnce(&mut Document)) { + let before = cur.clone(); + let mut d = (**cur).clone(); + f(&mut d); + *cur = Arc::new(d); + h.record(label, before, LayerTarget::default()); +} + +#[test] +fn undo_redo_cycle() { + let mut h = History::default(); + let mut cur = Arc::new(base()); + edit(&mut h, &mut cur, "New Layer", |d| { + d.insert_above(None, Layer::raster("L", d.pixel_format())); + }); + assert_eq!(cur.layers.len(), 2); + assert_eq!(h.undo_label(), Some("New Layer")); + cur = h.undo(cur).unwrap().0; + assert_eq!(cur.layers.len(), 1); + assert_eq!(h.redo_label(), Some("New Layer")); + cur = h.redo(cur).unwrap().0; + assert_eq!(cur.layers.len(), 2); + assert!(h.redo(cur.clone()).is_none()); +} + +#[test] +fn undo_and_redo_return_the_layers_each_state_targeted_when_created() { + let mut h = History::default(); + let open = Arc::new(base()); + let bg = open.layers[0].id; + let target = |id: LayerId| LayerTarget { active: Some(id), selected: vec![id] }; + h.set_current_layers(target(bg)); + // New Layer targets the new layer; the background is then selected (not a step) and filled. + let mut d = (*open).clone(); + let new = d.insert_above(None, Layer::raster("L", d.pixel_format())); + let layered = Arc::new(d); + h.record("New Layer", open, target(new)); + let mut d = (*layered).clone(); + d.name = "filled".into(); + h.record("Fill", layered, target(bg)); + let (d, layers) = h.undo(Arc::new(d)).unwrap(); + assert_eq!(layers, target(new), "New Layer's state targeted the new layer when created"); + let (d, layers) = h.undo(d).unwrap(); + assert_eq!(layers, target(bg), "the opened document's target"); + let (d, layers) = h.redo(d).unwrap(); + assert_eq!(layers, target(new)); + let (_, layers) = h.redo(d).unwrap(); + assert_eq!(layers, target(bg), "Fill's state targeted the background"); +} + +#[test] +fn state_accessor_matches_entries() { + let mut h = History::default(); + let mut cur = Arc::new(base()); + let open = cur.clone(); + edit(&mut h, &mut cur, "A", |d| d.name = "a".into()); + edit(&mut h, &mut cur, "B", |d| d.name = "b".into()); + assert_eq!(h.entries().len(), h.past_len() + 1); + assert!(Arc::ptr_eq(&h.state(0).unwrap(), &open)); + assert_eq!(h.state(1).unwrap().name, "a"); + assert!(h.state(2).is_none(), "the current document is not held"); + cur = h.undo(cur).unwrap().0; + h.undo(cur).unwrap(); + assert_eq!(h.redo_labels().collect::>(), ["A", "B"], "next redo first"); +} + +/// The History Brush source is a state, not an index: it stays on its state through undo, +/// redo and older states falling off, is kept when it would fall off itself, and is gone +/// (no source) once a new step discards it. +#[test] +fn brush_source_follows_its_state() { + let mut h = History::new(3); + let mut cur = Arc::new(base()); + assert_eq!(h.brush_source(), Some(0), "default: the oldest state"); + assert!(!h.set_brush_source(1), "no such row yet"); + edit(&mut h, &mut cur, "A", |d| d.name = "a".into()); + edit(&mut h, &mut cur, "B", |d| d.name = "b".into()); + assert!(h.set_brush_source(1)); + assert_eq!(h.row_doc(1, &cur).unwrap().name, "a"); + // Undo / redo: the rows stay put, and A's state is still row 1. + cur = h.undo(cur).unwrap().0; + assert_eq!((h.brush_source(), h.row_doc(1, &cur).unwrap().name.as_str()), (Some(1), "a")); + assert_eq!(h.row_doc(2, &cur).unwrap().name, "b", "a redo row"); + cur = h.redo(cur).unwrap().0; + // Open falls off the 3-state limit: A's state moves up to row 0 and stays the source. + edit(&mut h, &mut cur, "C", |d| d.name = "c".into()); + edit(&mut h, &mut cur, "D", |d| d.name = "d".into()); + assert_eq!(h.entries(), ["A", "B", "C", "D"]); + assert_eq!(h.brush_source(), Some(0)); + // A would fall off next: it is kept, and the states after it fall off instead. + edit(&mut h, &mut cur, "E", |d| d.name = "e".into()); + edit(&mut h, &mut cur, "F", |d| d.name = "f".into()); + assert_eq!(h.entries(), ["A", "D", "E", "F"]); + assert_eq!((h.brush_source(), h.row_doc(0, &cur).unwrap().name.as_str()), (Some(0), "a")); + // A redo state as the source, discarded by a new step: no source until one is set. + cur = h.undo(cur).unwrap().0; + assert!(h.set_brush_source(3), "the greyed F row"); + assert_eq!((h.brush_source(), h.row_doc(3, &cur).unwrap().name.as_str()), (Some(3), "f")); + assert!(h.row_doc(4, &cur).is_none() && h.row_id(4).is_none()); + edit(&mut h, &mut cur, "G", |d| d.name = "g".into()); + assert_eq!(h.brush_source(), None); + // The current state as the source keeps it once it becomes a past state; once it is no + // longer the source, it falls off as usual. + assert!(h.set_brush_source(3)); + edit(&mut h, &mut cur, "H", |d| d.name = "h".into()); + assert_eq!((h.brush_source(), h.row_doc(2, &cur).unwrap().name.as_str()), (Some(2), "g")); + assert!(h.set_brush_source(1)); + edit(&mut h, &mut cur, "I", |d| d.name = "i".into()); + assert_eq!(h.entries(), ["E", "G", "H", "I"]); +} + +#[test] +fn byte_budget_keeps_the_brush_source() { + let mut h = History::new(50); + let mut cur = Arc::new(base()); + for i in 0..5 { + edit(&mut h, &mut cur, &format!("paint {i}"), |d| { + let id = d.layers[0].id; + d.layer_mut(id).unwrap().surface_mut().unwrap().write_pixel(1, 1, &[i as f32 / 8.0, 0.0, 0.0, 1.0]); + }); + } + assert!(h.set_brush_source(1)); + h.max_bytes = 1; + let dropped = h.trim(&cur); + assert_eq!(h.entries(), ["paint 0", "paint 3", "paint 4"], "the source is kept with the last step"); + assert_eq!(dropped, 3); + assert_eq!(h.brush_source(), Some(0)); +} + +/// The pinned source counts against the byte budget: with room for three states, the +/// source and the two newest are kept, never more than the budget (#3536 review). +#[test] +fn byte_budget_counts_the_brush_source_first() { + let mut h = History::new(50); + let mut cur = Arc::new(base()); + let tile = h.pixel_bytes(&cur); + assert!(tile > 0); + for i in 0..5 { + edit(&mut h, &mut cur, &format!("paint {i}"), |d| { + let id = d.layers[0].id; + d.layer_mut(id).unwrap().surface_mut().unwrap().write_pixel(1, 1, &[i as f32 / 8.0, 0.0, 0.0, 1.0]); + }); + } + // Every state holds one tile of its own; the source is the oldest (Open). + assert!(h.set_brush_source(0)); + h.max_bytes = tile * 4; + assert_eq!(h.trim(&cur), 2); + assert_eq!(h.entries(), ["Open", "paint 2", "paint 3", "paint 4"]); + assert!(h.pixel_bytes(&cur) <= h.max_bytes, "{} > {}", h.pixel_bytes(&cur), h.max_bytes); + assert_eq!(h.trim(&cur), 0, "it fits now"); + // A new step trims to the budget again, still keeping the source. + edit(&mut h, &mut cur, "paint 5", |d| { + let id = d.layers[0].id; + d.layer_mut(id).unwrap().surface_mut().unwrap().write_pixel(1, 1, &[1.0, 0.0, 0.0, 1.0]); + }); + assert_eq!(h.trim(&cur), 1); + assert_eq!(h.entries(), ["Open", "paint 3", "paint 4", "paint 5"]); + assert!(h.pixel_bytes(&cur) <= h.max_bytes); + assert_eq!(h.brush_source(), Some(0)); +} + +/// Edit › Purge › Histories clears every state: a source set on one of them goes back to the +/// default (the oldest state held) instead of leaving no source (#3536 review). +#[test] +fn clear_resets_the_brush_source() { + let mut h = History::new(50); + let mut cur = Arc::new(base()); + edit(&mut h, &mut cur, "A", |d| d.name = "a".into()); + edit(&mut h, &mut cur, "B", |d| d.name = "b".into()); + assert!(h.set_brush_source(1)); + h.clear(); + assert_eq!(h.brush_source(), Some(0)); + assert_eq!(h.row_doc(0, &cur).unwrap().name, "b"); +} + +/// History panel › Clear History leaves a usable (default) source, and its undo restores the +/// source set on a past state. +#[test] +fn clear_states_resets_the_brush_source_until_undo() { + let mut h = History::new(50); + let mut cur = Arc::new(base()); + edit(&mut h, &mut cur, "A", |d| d.name = "a".into()); + edit(&mut h, &mut cur, "B", |d| d.name = "b".into()); + assert!(h.set_brush_source(1)); + assert!(h.clear_states()); + assert_eq!(h.brush_source(), Some(0)); + assert_eq!(h.row_doc(0, &cur).unwrap().name, "b"); + cur = h.undo(cur).unwrap().0; + assert_eq!((h.brush_source(), h.row_doc(1, &cur).unwrap().name.as_str()), (Some(1), "a")); +} + +#[test] +fn new_edit_clears_redo() { + let mut h = History::default(); + let mut cur = Arc::new(base()); + edit(&mut h, &mut cur, "A", |d| d.name = "a".into()); + cur = h.undo(cur).unwrap().0; + edit(&mut h, &mut cur, "B", |d| d.name = "b".into()); + assert!(!h.can_redo()); + assert_eq!(h.entries(), vec!["Open".to_string(), "B".to_string()]); +} + +#[test] +fn max_states_bound() { + let mut h = History::new(3); + let mut cur = Arc::new(base()); + for i in 0..10 { + edit(&mut h, &mut cur, &format!("step {i}"), |d| d.name = format!("{i}")); + } + let mut n = 0; + while let Some((d, _)) = h.undo(cur.clone()) { + cur = d; + n += 1; + } + assert_eq!(n, 3); + assert_eq!(cur.name, "6"); +} + +#[test] +fn byte_budget_drops_oldest_states_but_keeps_one() { + let mut h = History::new(50); + let mut cur = Arc::new(base()); + let tile = 256 * 256 * 4; + // Each step repaints the background's tile: one unique tile per state. + for i in 0..6 { + edit(&mut h, &mut cur, &format!("paint {i}"), |d| { + let id = d.layers[0].id; + d.layer_mut(id).unwrap().surface_mut().unwrap().write_pixel(1, 1, &[i as f32 / 8.0, 0.0, 0.0, 1.0]); + }); + } + assert_eq!(h.trim(&cur), 0, "unlimited by default"); + assert_eq!(h.past_len(), 6); + // The current tile plus three history tiles fit. + h.max_bytes = 4 * tile; + assert_eq!(h.trim(&cur), 3); + assert_eq!(h.past_len(), 3); + assert_eq!(h.unique_bytes(&cur), 3 * tile); + assert_eq!(h.pixel_bytes(&cur), 4 * tile, "the current tile plus history's"); + assert_eq!(h.entries()[0], "paint 2"); + // A budget smaller than one state still keeps the last step undoable. + h.max_bytes = 1; + h.trim(&cur); + assert_eq!(h.past_len(), 1); + assert!(h.undo(cur.clone()).is_some()); +} + +/// Snapshot-only tiles count against the budget (#4530); tiles a snapshot shares with the +/// document or a state count once, and a purge frees only what no snapshot keeps. +#[test] +fn snapshot_tiles_count_against_the_budget() { + let mut h = History::new(50); + let mut cur = Arc::new(base()); + let tile = 256 * 256 * 4; + let paint = |d: &mut Document, v: f32| { + let id = d.layers[0].id; + d.layer_mut(id).unwrap().surface_mut().unwrap().write_pixel(1, 1, &[v, 0.0, 0.0, 1.0]); + }; + // A snapshot holding a tile nothing else does, then one sharing the first state's tile. + let mut own = (*cur).clone(); + paint(&mut own, 0.9); + edit(&mut h, &mut cur, "paint 0", |d| paint(d, 0.1)); + let shared = h.state(0).unwrap(); + for i in 1..6 { + edit(&mut h, &mut cur, &format!("paint {i}"), |d| paint(d, i as f32 / 8.0)); + } + let snaps = [&own, &*shared]; + assert_eq!(h.extra_bytes(&cur, &snaps), tile, "the shared tile is history's"); + assert_eq!(h.extra_bytes(&cur, &[]), 0); + assert_eq!(h.unique_bytes(&cur), 6 * tile); + assert_eq!(h.unique_bytes_besides(&cur, &snaps), 5 * tile, "clearing keeps the shared tile"); + // Both snapshot tiles stay whatever is trimmed (the shared one too), so beside the + // current tile they leave room for two history tiles; without them, four would fit. + h.max_bytes = 5 * tile; + assert_eq!(h.trim_with(&cur, &snaps), 4); + assert_eq!(h.past_len(), 2); + assert_eq!(h.pixel_bytes(&cur) + h.extra_bytes(&cur, &snaps), 5 * tile); + // Still keeps the last step undoable. + h.max_bytes = 1; + h.trim_with(&cur, &snaps); + assert_eq!(h.past_len(), 1); +} + +#[test] +fn history_shares_untouched_tiles() { + let mut h = History::default(); + let mut cur = Arc::new(base()); + assert_eq!(h.unique_bytes(&cur), 0); + // rename only: no pixel changes, history holds no unique tiles + edit(&mut h, &mut cur, "Rename", |d| d.name = "x".into()); + assert_eq!(h.unique_bytes(&cur), 0); + // paint one pixel: exactly one tile becomes unique to history + edit(&mut h, &mut cur, "Paint", |d| { + let id = d.layers[0].id; + d.layer_mut(id).unwrap().surface_mut().unwrap().write_pixel(1, 1, &[0.0, 0.0, 0.0, 1.0]); + }); + assert_eq!(h.unique_bytes(&cur), 256 * 256 * 4); +} + +#[test] +fn fill_caches_and_smart_filter_masks_count_toward_history_bytes() { + use photocraft_doc::{Affine, Fill, FillCache, LayerContent, LayerMask, PixelFormat, SmartObject, SmartSource, Surface}; + let mut doc = Document::new("fills", Size::new(64, 64), ColorMode::Rgb, SampleType::U8); + let mut fill = Layer::new("Fill", LayerContent::Fill(Fill::Solid(Color::WHITE))); + let mut cache = Surface::new(PixelFormat::GRAY8); + cache.write_pixel(1, 1, &[1.0]); + fill.fill_cache = Some(FillCache { fill: Fill::Solid(Color::WHITE), surface: cache }); + doc.insert_above(None, fill); + let mut smart_obj = SmartObject::new(SmartSource::Linked { path: "a.png".into() }, Affine::IDENTITY, None); + let mut mask = LayerMask::reveal_all(); + mask.surface.write_pixel(1, 1, &[0.5]); + smart_obj.filter_mask = Some(mask); + doc.insert_above(None, Layer::new("Smart", LayerContent::Smart(smart_obj))); + let tile = 256 * 256; + let mut cur = Arc::new(doc); + let mut h = History { max_bytes: usize::MAX, ..History::default() }; + assert_eq!(h.pixel_bytes(&cur), 2 * tile, "fill cache and smart filter mask are counted"); + edit(&mut h, &mut cur, "Rename", |doc| doc.name = "renamed".into()); + assert_eq!(h.pixel_bytes(&cur), 2 * tile, "shared tiles count once"); + edit(&mut h, &mut cur, "Fill cache", |doc| { + let id = doc.layers[0].id; + if let Some(cache) = doc.layer_mut(id).and_then(|l| l.fill_cache.as_mut()) { + cache.surface.write_pixel(1, 1, &[0.0]); + } + }); + assert_eq!(h.pixel_bytes(&cur), 3 * tile, "the copied fill cache tile is history-only"); + assert_eq!(h.unique_bytes(&cur), tile); + h.trim(&cur); + assert_counter(&h, &cur); + h.max_bytes = 2 * tile; + assert_eq!(h.trim(&cur), 1, "the copied fill cache tile pushes history over budget"); + assert_eq!(h.pixel_bytes(&cur), 3 * tile, "the most recent undo state is always kept"); + assert_counter(&h, &cur); +} + +#[test] +fn selection_tiles_count_current_and_history_without_double_counting() { + use photocraft_doc::{PixelFormat, Surface}; + for depth in SampleType::ALL { + let mut doc = Document::new("selection", Size::new(300, 64), ColorMode::Rgb, depth); + let mut selection = Surface::new(PixelFormat::new(ColorMode::Grayscale, depth, false)); + selection.write_pixel(1, 1, &[1.0]); + selection.write_pixel(257, 1, &[1.0]); + doc.selection = Some(selection); + let mut cur = Arc::new(doc); + let tile = match depth { + SampleType::U8 => 65_536, + SampleType::U16 => 131_072, + SampleType::F32 => 262_144, + }; + let mut h = History { max_bytes: usize::MAX, ..History::default() }; + assert_eq!(h.pixel_bytes(&cur), 2 * tile, "current selection counts without any history"); + assert_eq!(h.unique_bytes(&cur), 0); + edit(&mut h, &mut cur, "Rename", |doc| doc.name = "renamed".into()); + assert_eq!(h.pixel_bytes(&cur), 2 * tile, "the shared selection tiles count once"); + edit(&mut h, &mut cur, "Selection", |doc| { + doc.selection.as_mut().unwrap().write_pixel(1, 1, &[0.5]); + }); + assert_eq!(h.pixel_bytes(&cur), 3 * tile, "only the changed selection tile is copied"); + assert_eq!(h.unique_bytes(&cur), tile); + h.trim(&cur); + assert_counter(&h, &cur); + let selected_value = cur.selection.as_ref().unwrap().sample_channel(1, 1, 0); + edit(&mut h, &mut cur, "Deselect", |doc| doc.selection = None); + assert_eq!(h.pixel_bytes(&cur), 3 * tile, "deselecting leaves the previous masks in history"); + assert_eq!(h.unique_bytes(&cur), 3 * tile); + assert_counter(&h, &cur); + cur = h.undo(cur).unwrap().0; + assert_eq!(cur.selection.as_ref().unwrap().sample_channel(1, 1, 0), selected_value); + assert_eq!(h.pixel_bytes(&cur), 3 * tile); + assert_eq!(h.unique_bytes(&cur), tile); + assert_counter(&h, &cur); + // Coalescing can change the current mask without recording another state. + Arc::make_mut(&mut cur).selection.as_mut().unwrap().write_pixel(257, 1, &[0.25]); + assert_eq!(h.pixel_bytes(&cur), 4 * tile); + assert_eq!(h.trim(&cur), 0); + assert_counter(&h, &cur); + cur = h.redo(cur).unwrap().0; + assert!(cur.selection.is_none()); + assert_eq!(h.pixel_bytes(&cur), 4 * tile); + assert_counter(&h, &cur); + } +} + +#[test] +fn selection_byte_budget_drops_old_masks_and_keeps_the_last_undo() { + use photocraft_doc::{PixelFormat, Surface}; + for depth in SampleType::ALL { + let mut doc = Document::new("selection", Size::new(64, 64), ColorMode::Rgb, depth); + doc.selection = Some(Surface::new(PixelFormat::new(ColorMode::Grayscale, depth, false))); + let mut cur = Arc::new(doc); + let tile = 256 * 256 * depth.bytes(); + let mut h = History::default(); + for i in 1..=6 { + edit(&mut h, &mut cur, "Selection", |doc| { + doc.selection.as_mut().unwrap().write_pixel(1, 1, &[i as f32 / 8.0]); + }); + } + assert_eq!(h.pixel_bytes(&cur), 6 * tile); + h.max_bytes = 3 * tile; + assert_eq!(h.trim(&cur), 4); + assert_eq!(h.past_len(), 2); + assert_eq!(h.pixel_bytes(&cur), 3 * tile); + assert_eq!(h.unique_bytes(&cur), 2 * tile); + assert_counter(&h, &cur); + h.max_bytes = 1; + assert_eq!(h.trim(&cur), 1); + assert_eq!(h.past_len(), 1, "the most recent undo survives even below one mask's size"); + assert_eq!(h.pixel_bytes(&cur), 2 * tile); + cur = h.undo(cur).unwrap().0; + assert_counter(&h, &cur); + } +} + +fn assert_counter(h: &History, current: &Document) { + let counter = h.tiles.as_ref().expect("budget initializes the counter"); + let total = tile_bytes(current, &mut HashSet::new()).saturating_add(h.unique_bytes(current)); + assert_eq!(counter.bytes_with(current), total as u128); + assert_eq!(h.pixel_bytes(current), total); + let mut seen = HashSet::new(); + let retained: usize = h.held_states().map(|s| tile_bytes(&s.doc, &mut seen)).sum(); + let empty = Document::new("empty", Size::new(1, 1), ColorMode::Rgb, SampleType::U8); + assert_eq!(counter.bytes_with(&empty), retained as u128); +} + +fn video_document(depth: SampleType, frames: usize) -> Document { + let mut doc = Document::new("video", Size::new(64, 64), ColorMode::Rgb, depth); + let mut layer = Layer::raster("Video", doc.pixel_format()); + let footage: Vec<_> = (0..frames) + .map(|i| { + let mut surface = photocraft_doc::Surface::new(doc.pixel_format()); + surface.write_pixel(1, 1, &[i as f32 / frames as f32, 0.0, 0.0, 1.0]); + surface + }) + .collect(); + layer.content = photocraft_doc::LayerContent::Raster(footage[0].clone()); + layer.video = Some(photocraft_doc::VideoData::new(footage, 24.0)); + doc.layers.push(layer); + doc +} + +#[test] +fn video_memory_counts_originals_and_deduplicates_displayed_frames() { + for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + let mut doc = video_document(depth, 3); + let tile = doc.layers[0].surface().unwrap().tiles().next().unwrap().1.bytes().len(); + let video = doc.layers[0].video.as_mut().unwrap(); + video.original_frames = Some(video.frames.clone()); + // Original footage and the displayed frame alias the stack, except this painted frame. + video.frames[2].write_pixel(1, 1, &[0.0, 1.0, 0.0, 1.0]); + let mut cur = Arc::new(doc); + let mut h = History { max_bytes: usize::MAX, ..History::default() }; + assert_eq!(h.pixel_bytes(&cur), 4 * tile); + for name in ["A", "B"] { + edit(&mut h, &mut cur, "Rename", |doc| doc.name = name.into()); + h.trim(&cur); + } + assert_counter(&h, &cur); + assert_eq!(h.pixel_bytes(&cur), 4 * tile); + assert_eq!(h.unique_bytes(&cur), 0); + // Rasterizing keeps the displayed frame; the rest of the clip survives only in undo. + edit(&mut h, &mut cur, "Rasterize", |doc| doc.layers[0].video = None); + assert_eq!(h.unique_bytes(&cur), 3 * tile); + assert_eq!(h.pixel_bytes(&cur), 4 * tile); + assert_counter(&h, &cur); + cur = h.undo(cur).unwrap().0; + assert_eq!(h.unique_bytes(&cur), 0); + assert_counter(&h, &cur); + cur = h.redo(cur).unwrap().0; + assert_eq!(h.unique_bytes(&cur), 3 * tile); + assert_counter(&h, &cur); + h.clear(); + assert_eq!(h.pixel_bytes(&cur), tile); + } +} + +#[test] +fn video_memory_budget_evicts_deleted_off_playhead_frames() { + for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + let mut cur = Arc::new(video_document(depth, 6)); + let tile = cur.layers[0].surface().unwrap().tiles().next().unwrap().1.bytes().len(); + let mut h = History::default(); + for _ in 0..4 { + edit(&mut h, &mut cur, "Delete Frame", |doc| { + doc.layers[0].video.as_mut().unwrap().frames.remove(1); + }); + } + assert_eq!(h.pixel_bytes(&cur), 6 * tile); + assert_eq!(h.unique_bytes(&cur), 4 * tile); + h.max_bytes = 3 * tile; + assert_eq!(h.trim(&cur), 3); + assert_eq!(h.past_len(), 1); + assert_eq!(h.pixel_bytes(&cur), 3 * tile); + assert_eq!(h.unique_bytes(&cur), tile); + assert_counter(&h, &cur); + cur = h.undo(cur).unwrap().0; + assert_eq!(cur.layers[0].video.as_ref().unwrap().frames.len(), 3); + assert_counter(&h, &cur); + cur = h.redo(cur).unwrap().0; + assert_eq!(cur.layers[0].video.as_ref().unwrap().frames.len(), 2); + assert_counter(&h, &cur); + // A budget below the remaining clip still keeps the latest step undoable. + h.max_bytes = 1; + assert_eq!(h.trim(&cur), 0); + assert!(h.can_undo()); + } +} + +/// A pattern fill or layer style copies its pattern into the document, so the pattern's tiles +/// count like layer pixels, shared ones once; undoing that step leaves them to the redo states. +#[test] +fn document_patterns_count_as_document_pixels() { + use photocraft_doc::{Pattern, Surface}; + for depth in SampleType::ALL { + let tile = 4 * 256 * 256 * depth.bytes(); + let mut cur = Arc::new(Document::new("patterns", Size::new(64, 64), ColorMode::Rgb, depth)); + let mut h = History { max_bytes: usize::MAX, ..History::default() }; + for name in ["A", "B"] { + edit(&mut h, &mut cur, "Rename", |doc| doc.name = name.into()); + h.trim(&cur); + } + let mut surface = Surface::new(cur.pixel_format()); + surface.write_pixel(1, 1, &[0.0, 0.0, 1.0, 1.0]); + let pattern = Pattern::new("Pattern", surface, 4, 4); + edit(&mut h, &mut cur, "Pattern Fill", |doc| doc.patterns.push(pattern)); + assert_eq!(h.pixel_bytes(&cur), tile, "the document's pattern"); + assert_eq!(h.unique_bytes(&cur), 0); + assert_counter(&h, &cur); + edit(&mut h, &mut cur, "Rename", |doc| doc.name = "C".into()); + assert_eq!(h.pixel_bytes(&cur), tile, "shared with history, it counts once"); + assert_counter(&h, &cur); + for _ in 0..2 { + cur = h.undo(cur).unwrap().0; + assert_counter(&h, &cur); + } + assert!(cur.patterns.is_empty()); + assert_eq!(h.unique_bytes(&cur), tile, "only the redo states hold the pattern"); + assert_eq!(h.pixel_bytes(&cur), tile); + cur = h.redo(cur).unwrap().0; + assert_eq!(h.unique_bytes(&cur), 0); + assert_counter(&h, &cur); + h.clear(); + assert_eq!(h.pixel_bytes(&cur), tile); + } +} + +#[test] +fn counter_tracks_eviction_undo_redo_branching_purge_and_clones() { + for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + let mut cur = Arc::new(Document::with_background("h", Size::new(300, 64), ColorMode::Rgb, depth, Color::WHITE)); + Arc::make_mut(&mut cur).selection = Some(photocraft_doc::Surface::new(photocraft_doc::PixelFormat::GRAY8)); + let mut h = History::new(4); + h.max_bytes = usize::MAX; + for i in 0..8 { + edit(&mut h, &mut cur, "Paint", |doc| { + doc.layers[0].surface_mut().unwrap().write_pixel(1, 1, &[i as f32 / 10.0, 0.0, 0.0, 1.0]); + doc.selection.as_mut().unwrap().write_pixel(1, 1, &[i as f32 / 10.0]); + }); + h.trim(&cur); + if i >= 1 { + assert_counter(&h, &cur); + } + } + cur = h.undo(cur).unwrap().0; + assert_counter(&h, &cur); + cur = h.undo(cur).unwrap().0; + assert_counter(&h, &cur); + cur = h.redo(cur).unwrap().0; + assert_counter(&h, &cur); + let copy = h.clone(); + edit(&mut h, &mut cur, "Branch", |doc| doc.name = "branch".into()); + assert!(!h.can_redo()); + assert_counter(&h, &cur); + assert_counter(©, &cur); + cur = h.undo(cur).unwrap().0; + h.clear_redo(); + assert_counter(&h, &cur); + h.purge_last(); + assert_counter(&h, &cur); + h.clear(); + assert!(h.tiles.is_none()); + assert_eq!(h.pixel_bytes(&cur), tile_bytes(&cur, &mut HashSet::new())); + } +} + +#[test] +fn shared_masks_channels_and_repeated_snapshot_references_count_once() { + use photocraft_doc::{AlphaChannel, LayerMask, PixelFormat, Surface}; + let mut doc = base(); + let mut gray = Surface::new(PixelFormat::GRAY8); + gray.write_pixel(1, 1, &[1.0]); + doc.layers[0].mask = Some(LayerMask { surface: gray.clone(), ..LayerMask::reveal_all() }); + doc.channels.push(AlphaChannel::new("alpha", gray.clone())); + doc.selection = Some(gray.clone()); + doc.quick_mask = Some(AlphaChannel::new("quick", gray)); + doc.layers.push(doc.layers[0].clone()); + let mut cur = Arc::new(doc); + let bytes = tile_bytes(&cur, &mut HashSet::new()); + let mut h = History::new(50); + // Counting current separately would double count its tiles; the exact union fits. + h.max_bytes = bytes; + for _ in 0..6 { + h.record("Same", cur.clone(), LayerTarget::default()); + assert_eq!(h.trim(&cur), 0); + } + assert_counter(&h, &cur); + for _ in 0..3 { + cur = h.undo(cur).unwrap().0; + assert_counter(&h, &cur); + } + h.clear_redo(); + h.purge_last(); + assert_counter(&h, &cur); + assert_eq!(h.pixel_bytes(&cur), bytes); +} + +#[test] +fn threshold_rechecks_coalesced_current_and_changed_budget() { + let mut h = History::new(50); + let mut cur = Arc::new(base()); + h.max_bytes = usize::MAX; + for i in 0..6 { + edit(&mut h, &mut cur, "Paint", |doc| { + doc.layers[0].surface_mut().unwrap().write_pixel(1, 1, &[i as f32 / 10.0, 0.0, 0.0, 1.0]); + }); + h.trim(&cur); + } + // A coalesced edit may change current without recording another history state. + Arc::make_mut(&mut cur).layers[0].surface_mut().unwrap().write_pixel(300, 1, &[1.0; 4]); + let tile = 256 * 256 * 4; + h.max_bytes = 4 * tile; + assert_eq!(h.trim(&cur), 4); + assert_eq!(h.past_len(), 2); + assert_counter(&h, &cur); + cur = h.undo(cur).unwrap().0; + assert_counter(&h, &cur); + h.max_bytes = 0; + edit(&mut h, &mut cur, "Unlimited", |doc| doc.name = "u".into()); + assert!(h.tiles.is_none()); + h.max_bytes = 1; + h.trim(&cur); + assert_eq!(h.past_len(), 1, "always retain the most recent undo"); + assert_counter(&h, &cur); +} + +#[test] +fn transferred_tiles_cannot_make_the_budget_check_underestimate_current() { + use photocraft_doc::{PixelFormat, Surface}; + let before = Arc::new(base()); + let mut current = (*before).clone(); + let mut large = Surface::new(PixelFormat::new(ColorMode::Cmyk, SampleType::F32, true)); + large.write_pixel(256, 0, &[1.0; 5]); + current.layers[0].surface_mut().unwrap().put_tiles(large.take_tiles(photocraft_doc::Rect::from_xywh(256, 0, 1, 1))); + let mut h = History::new(50); + h.max_bytes = tile_bytes(¤t, &mut HashSet::new()) - 1; + h.record("A", before.clone(), LayerTarget::default()); + h.record("B", before, LayerTarget::default()); + assert_eq!(h.trim(¤t), 1, "current alone exceeds the budget; only the mandatory undo survives"); + assert_counter(&h, ¤t); +} + +#[test] +fn clear_states_keeps_the_document_and_undo_brings_the_list_back() { + let mut h = History::new(10); + let mut cur = Arc::new(base()); + edit(&mut h, &mut cur, "A", |d| d.name = "a".into()); + edit(&mut h, &mut cur, "B", |d| d.name = "b".into()); + edit(&mut h, &mut cur, "C", |d| d.name = "c".into()); + let (d, _) = h.undo(cur.clone()).unwrap(); + cur = d; + let entries = h.entries(); + assert_eq!(entries, ["Open", "A", "B"]); + assert!(h.clear_states()); + assert_eq!(h.entries(), ["B"], "only the current state is left"); + assert!(!h.can_redo() && h.can_undo() && h.is_cleared()); + assert_eq!(h.undo_label(), Some(CLEAR_HISTORY_LABEL)); + assert!(!h.clear_states(), "nothing left to clear"); + assert!(h.is_cleared(), "and the cleared states are still held"); + let (d, _) = h.undo(cur.clone()).unwrap(); + assert!(Arc::ptr_eq(&d, &cur), "undoing Clear History doesn't change the document"); + assert_eq!(h.entries(), entries); + assert_eq!(h.redo_labels().collect::>(), ["C"], "the redo state is back too"); + assert!(!h.is_cleared()); +} + +#[test] +fn cleared_states_still_count_in_the_memory_figures_and_the_budget() { + let mut h = History::new(50); + let mut cur = Arc::new(base()); + let tile = 256 * 256 * 4; + for i in 0..5 { + edit(&mut h, &mut cur, &format!("paint {i}"), |d| { + let id = d.layers[0].id; + d.layer_mut(id).unwrap().surface_mut().unwrap().write_pixel(1, 1, &[i as f32 / 8.0, 0.0, 0.0, 1.0]); + }); + } + cur = h.undo(cur).unwrap().0; + let (unique, pixels) = (h.unique_bytes(&cur), h.pixel_bytes(&cur)); + assert_eq!(unique, 5 * tile, "four undo states and one redo state"); + assert!(h.clear_states()); + assert_eq!(h.unique_bytes(&cur), unique, "Clear History frees nothing while it can be undone"); + assert_eq!(h.pixel_bytes(&cur), pixels); + assert_eq!(h.extra_bytes(&cur, &[&base()]), tile, "a snapshot's own tile, not the cleared states'"); + assert_eq!(h.unique_bytes_besides(&cur, &[]), unique); + // The budget counts them too: the oldest cleared states go first. + h.max_bytes = 4 * tile; + assert_eq!(h.trim(&cur), 2); + assert_counter(&h, &cur); + assert_eq!(h.pixel_bytes(&cur), 4 * tile); + assert!(h.is_cleared() && h.past_len() == 0, "the list stays cleared"); + h.undo(cur.clone()).unwrap(); + assert_eq!(h.entries(), ["paint 1", "paint 2", "paint 3"], "undo brings back what the budget kept"); + assert_eq!(h.redo_labels().collect::>(), ["paint 4"]); + // A new step after Clear History forgets the cleared states, and the counter with them. + assert!(h.clear_states()); + h.trim(&cur); + edit(&mut h, &mut cur, "paint 5", |d| { + let id = d.layers[0].id; + d.layer_mut(id).unwrap().surface_mut().unwrap().write_pixel(1, 1, &[1.0, 0.0, 0.0, 1.0]); + }); + assert_eq!(h.unique_bytes(&cur), tile, "only the state before the new step"); + assert_eq!(h.pixel_bytes(&cur), 2 * tile); +} + +#[test] +fn a_new_step_or_purge_forgets_the_cleared_states() { + let mut h = History::new(10); + let mut cur = Arc::new(base()); + edit(&mut h, &mut cur, "A", |d| d.name = "a".into()); + assert!(h.clear_states()); + edit(&mut h, &mut cur, "B", |d| d.name = "b".into()); + assert_eq!(h.entries(), ["A", "B"]); + assert!(!h.is_cleared()); + assert!(h.undo(cur.clone()).is_some()); + assert!(!h.can_undo(), "the cleared states are gone"); + let mut h = History::new(10); + edit(&mut h, &mut cur, "A", |d| d.name = "a".into()); + assert!(h.clear_states()); + assert!(h.purge_last()); + assert!(!h.can_undo() && !h.is_cleared()); + assert!(!h.clear_states(), "a single state can't be cleared"); +} diff --git a/crates/paint/src/mixer.rs b/crates/paint/src/mixer.rs index f620520b9b..32b4c265ea 100644 --- a/crates/paint/src/mixer.rs +++ b/crates/paint/src/mixer.rs @@ -440,5 +440,4 @@ mod tests { } #[cfg(test)] -#[path = "mixer_reference_tests.rs"] mod reference_tests; diff --git a/crates/paint/src/mixer_reference_tests.rs b/crates/paint/src/mixer/reference_tests.rs similarity index 100% rename from crates/paint/src/mixer_reference_tests.rs rename to crates/paint/src/mixer/reference_tests.rs diff --git a/crates/paint/src/render.rs b/crates/paint/src/render.rs index b3246f1f57..cf0835d2dd 100644 --- a/crates/paint/src/render.rs +++ b/crates/paint/src/render.rs @@ -1293,5 +1293,4 @@ impl RoundTip { } #[cfg(test)] -#[path = "render_reference.rs"] mod reference; diff --git a/crates/paint/src/render_reference.rs b/crates/paint/src/render/reference.rs similarity index 100% rename from crates/paint/src/render_reference.rs rename to crates/paint/src/render/reference.rs diff --git a/crates/psd/src/abr.rs b/crates/psd/src/abr.rs index 6a9f0806c5..35f4135a53 100644 --- a/crates/psd/src/abr.rs +++ b/crates/psd/src/abr.rs @@ -673,303 +673,4 @@ pub fn write_v6_folders( } #[cfg(test)] -mod tests { - use super::*; - use crate::descriptor::UnicodeString; - - fn sample(id: &str, w: u32, h: u32, depth: u16) -> AbrSample { - let bpp = usize::from(depth / 8); - let data = (0..w as usize * h as usize * bpp).map(|i| if (i / bpp) % 3 == 0 { 255 } else { (i % 7) as u8 * 30 }).collect(); - AbrSample { id: id.into(), width: w, height: h, depth, data } - } - - #[test] - fn embedded_patterns_spend_the_samples_budget() { - let p = PsdPattern { - mode: 3, - width: 5, - height: 3, - name: "p".into(), - id: "id".into(), - palette: None, - depth: 8, - channels: vec![vec![1; 15], vec![2; 15], vec![3; 15]], - alpha: None, - }; - let abr = write_v6(2, &[sample("s", 10, 10, 8)], &[p.clone(), p], &[], true).unwrap(); - let parse_within = |left: usize| { - let mut out = AbrFile::default(); - let mut budget = Budget(left); - parse_v6_within(&mut Rd::new(&abr[2..]), &mut out, &mut budget).unwrap(); - (out, budget.0) - }; - // 100 sample bytes plus two 45-byte patterns. - let (out, left) = parse_within(190); - assert_eq!((out.samples.len(), out.patterns.len(), left), (1, 2, 0)); - // One byte short: the patterns no longer fit after the sample (they used not to count). - let (out, left) = parse_within(189); - assert_eq!((out.samples.len(), out.patterns.len(), left), (1, 0, 14)); - assert!(out.warnings.iter().any(|w| w.contains("embedded patterns unreadable")), "{:?}", out.warnings); - } - - #[test] - fn failed_pattern_section_does_not_refund_budget_to_later_sections() { - let p = PsdPattern { - mode: 3, - width: 5, - height: 3, - name: "p".into(), - id: "id".into(), - palette: None, - depth: 8, - channels: vec![vec![1; 15], vec![2; 15], vec![3; 15]], - alpha: None, - }; - let valid = write_pattern_block(std::slice::from_ref(&p)).unwrap(); - let mut malformed = valid.clone(); - malformed.extend_from_slice(&100u32.to_be_bytes()); - - let mut body = 2u16.to_be_bytes().to_vec(); - section(&mut body, b"patt", &malformed); - section(&mut body, b"patt", &valid); - let mut out = AbrFile::default(); - let mut budget = Budget(60); - parse_v6_within(&mut Rd::new(&body), &mut out, &mut budget).unwrap(); - - assert!(out.patterns.is_empty(), "a failed block is discarded atomically"); - assert_eq!(budget.0, 0, "the failed block's first 45 bytes and later partial 15-byte charge are retained"); - assert_eq!(out.warnings.iter().filter(|w| w.contains("embedded patterns unreadable")).count(), 2); - } - - #[test] - fn v1_v2_round_trip_raw_and_rle() { - for version in [1u16, 2] { - for rle in [false, true] { - let brushes = vec![ - LegacyBrush { - name: String::new(), - spacing: 25, - anti_alias: true, - tip: LegacyTip::Computed { diameter: 19, hardness: 80, angle: -30, roundness: 50 }, - }, - LegacyBrush { - name: if version == 2 { "Leaf ✓".into() } else { String::new() }, - spacing: 40, - anti_alias: false, - tip: LegacyTip::Sampled(sample("", 13, 9, 8)), - }, - LegacyBrush { name: String::new(), spacing: 10, anti_alias: true, tip: LegacyTip::Sampled(sample("", 4, 6, 16)) }, - ]; - let bytes = write_v12(version, &brushes, rle).unwrap(); - let f = parse(&bytes).unwrap(); - assert_eq!(f.version, version); - assert_eq!(f.legacy, brushes, "v{version} rle={rle}"); - assert!(f.warnings.is_empty(), "{:?}", f.warnings); - } - } - } - - #[test] - fn v6_round_trip_both_subversions() { - let samples = vec![sample("$abc", 20, 11, 8), sample("$def", 5, 5, 16)]; - let preset = Descriptor::new("brushPreset") - .with("Nm ", Value::Text(UnicodeString::new_nul("Grass"))) - .with("Brsh", Value::Descriptor(Descriptor::new("sampledBrush").with("sampledData", Value::Text(UnicodeString::new_nul("$abc"))))); - for sub in [1u16, 2] { - for rle in [false, true] { - let bytes = write_v6(sub, &samples, &[], std::slice::from_ref(&preset), rle).unwrap(); - let f = parse(&bytes).unwrap(); - assert_eq!((f.version, f.subversion), (6, sub)); - assert_eq!(f.samples, samples); - assert_eq!(f.presets, vec![preset.clone()]); - assert!(f.warnings.is_empty(), "{:?}", f.warnings); - } - } - assert_eq!(samples[1].to_unit().len(), 25); - } - - #[test] - fn hostile_input_errors_without_panicking() { - assert!(parse(&[]).is_err()); - assert!(parse(&[0, 3, 0, 0]).is_err()); - assert!(parse(&[0, 6, 0, 9]).is_err()); - // Absurd sample bounds. - let mut s = sample("", 2, 2, 8); - s.width = MAX_EDGE + 1; - assert!(write_v12(1, &[LegacyBrush { name: String::new(), spacing: 1, anti_alias: true, tip: LegacyTip::Sampled(s) }], false).is_err()); - let good = write_v6(2, &[sample("$a", 30, 30, 8)], &[], &[Descriptor::new("brushPreset")], true).unwrap(); - for cut in 0..good.len() { - let _ = parse(&good[..cut]); - } - let v2 = write_v12(2, &[LegacyBrush { name: "x".into(), spacing: 1, anti_alias: true, tip: LegacyTip::Sampled(sample("", 9, 9, 16)) }], true).unwrap(); - for cut in 0..v2.len() { - let _ = parse(&v2[..cut]); - } - // Flip every byte once: never panics. - for i in 0..good.len() { - let mut b = good.clone(); - b[i] ^= 0xa5; - let _ = parse(&b); - } - // A huge declared count with no data is an error, not an allocation. - assert!(parse(&[0, 2, 0xff, 0xff]).is_err()); - } - - fn named(n: &str) -> Descriptor { - Descriptor::new("brushPreset").with("Nm ", Value::Text(UnicodeString::new_nul(n))) - } - - /// Hierarchy tokens: `G(name)` opens, `P` is a preset, `E` closes. - enum Tok<'a> { - G(&'a str), - P, - E, - } - - /// A v6 file with `n` presets and a hand-made `phry` token stream. - fn with_phry(n: usize, toks: &[Tok]) -> Vec { - let presets: Vec = (0..n).map(|i| named(&format!("B{i}"))).collect(); - let mut bytes = write_v6(2, &[], &[], &presets, false).unwrap(); - section(&mut bytes, b"phry", &phry_bytes(toks)); - bytes - } - - /// A `phry` section body holding `toks`. - fn phry_bytes(toks: &[Tok]) -> Vec { - let items = toks - .iter() - .map(|t| { - Value::Descriptor(match t { - Tok::G(name) => Descriptor::new("Grup") - .with("Nm ", Value::Text(UnicodeString::new_nul(name))) - .with("zuid", Value::Text(UnicodeString::new_nul("c9ee8fd5-eb7d-924c-9e95-ddc98e40bb6c"))), - Tok::P => Descriptor::new("preset"), - Tok::E => Descriptor::new("groupEnd"), - }) - }) - .collect(); - VersionedDescriptor::new(Descriptor::new("null").with("hierarchy", Value::List(items))).to_bytes() - } - - fn path(p: &[&str]) -> Vec { - p.iter().map(|s| s.to_string()).collect() - } - - #[test] - fn phry_flat_folders_like_photoshop_25() { - // The layout of Photoshop 25.1's default brushes: four folders, every preset in one. - use Tok::*; - let f = parse(&with_phry(5, &[G("General"), P, P, E, G("Dry Media"), P, E, G("Wet Media"), P, E, G("Special Effects"), P, E])).unwrap(); - assert_eq!(f.folders, vec![path(&["General"]), path(&["General"]), path(&["Dry Media"]), path(&["Wet Media"]), path(&["Special Effects"])]); - assert!(f.warnings.is_empty(), "{:?}", f.warnings); - } - - #[test] - fn phry_nested_folders_and_top_level_presets() { - use Tok::*; - let f = parse(&with_phry(5, &[P, G("Animals"), G("Birds"), P, E, P, G("Fish"), P, E, E, P])).unwrap(); - assert_eq!(f.folders, vec![path(&[]), path(&["Animals", "Birds"]), path(&["Animals"]), path(&["Animals", "Fish"]), path(&[])]); - assert!(f.warnings.is_empty(), "{:?}", f.warnings); - // No folder at all: no hierarchy. - let f = parse(&with_phry(2, &[P, P])).unwrap(); - assert!(f.folders.is_empty()); - } - - #[test] - fn phry_mismatches_become_warnings() { - use Tok::*; - // A stray groupEnd is ignored; an unclosed folder still holds its presets. - let f = parse(&with_phry(2, &[E, G("A"), P, E, E, G("B"), P])).unwrap(); - assert_eq!(f.folders, vec![path(&["A"]), path(&["B"])]); - assert!(f.warnings.iter().any(|w| w.contains("folder end")), "{:?}", f.warnings); - // Fewer preset tokens than presets: the rest are at the top level. - let f = parse(&with_phry(3, &[G("A"), P, E])).unwrap(); - assert_eq!(f.folders, vec![path(&["A"]), path(&[]), path(&[])]); - assert!(f.warnings.iter().any(|w| w.contains("list 1 brushes but the file holds 3")), "{:?}", f.warnings); - // More preset tokens than presets: extras ignored. - let f = parse(&with_phry(1, &[G("A"), P, P, P, E])).unwrap(); - assert_eq!(f.folders, vec![path(&["A"])]); - assert_eq!(f.presets.len(), 1); - assert!(!f.warnings.is_empty()); - // A depth bomb: folders deeper than the limit merge into their ancestor at the limit. - let mut toks: Vec = (0..10_000).map(|_| G("deep")).collect(); - toks.push(P); - toks.extend((0..10_000).map(|_| E)); - toks.extend([G("next"), P, E]); - let f = parse(&with_phry(2, &toks)).unwrap(); - assert_eq!(f.folders[0].len(), MAX_FOLDER_DEPTH); - assert_eq!(f.folders[1], path(&["next"])); - assert!(f.warnings.iter().any(|w| w.contains("deeper")), "{:?}", f.warnings); - // An unreadable hierarchy: imported flat, with a warning. - let mut bytes = write_v6(2, &[], &[], &[named("x")], false).unwrap(); - section(&mut bytes, b"phry", &[0, 0, 0, 16, 0xff, 0xff]); - let f = parse(&bytes).unwrap(); - assert!(f.folders.is_empty() && f.presets.len() == 1); - assert!(f.warnings.iter().any(|w| w.contains("phry")), "{:?}", f.warnings); - // Truncations and bit flips of a file with a hierarchy never panic. - let good = with_phry(3, &[G("A"), P, G("B"), P, E, E, P]); - for cut in 0..good.len() { - let _ = parse(&good[..cut]); - } - for i in 0..good.len() { - let mut b = good.clone(); - b[i] ^= 0x5a; - let _ = parse(&b); - } - } - - #[test] - fn phry_builds_paths_only_for_the_files_presets() { - use Tok::*; - // A few-KB section listing 100,000 deep presets for a file with 2: two paths are built. - let mut toks: Vec = (0..MAX_FOLDER_DEPTH).map(|_| G("folder")).collect(); - toks.extend((0..100_000).map(|_| P)); - let mut warnings = Vec::new(); - let folders = read_phry(&phry_bytes(&toks), 2, &mut warnings).unwrap(); - assert_eq!(folders.len(), 2); - assert_eq!(folders.capacity(), 2); - assert_eq!(folders[1].len(), MAX_FOLDER_DEPTH); - assert!(warnings.iter().any(|w| w.contains("list 100000 brushes but the file holds 2")), "{warnings:?}"); - // `phry` before `desc` still pairs with the file's presets. - let mut bytes = write_v6(2, &[], &[], &[named("a"), named("b")], false).unwrap(); - let at = bytes.windows(8).position(|w| w == b"8BIMdesc").unwrap(); - let mut phry = Vec::new(); - section(&mut phry, b"phry", &phry_bytes(&[G("A"), P, E, P])); - bytes.splice(at..at, phry); - let f = parse(&bytes).unwrap(); - assert_eq!(f.folders, vec![path(&["A"]), path(&[])]); - assert!(f.warnings.is_empty(), "{:?}", f.warnings); - } - - #[test] - fn phry_folder_paths_stay_within_their_byte_budget() { - use Tok::*; - // Thousands of presets under 32 folders of 255-character names would need ~27 MB of paths. - let long = "x".repeat(MAX_FOLDER_NAME); - let mut toks: Vec = (0..MAX_FOLDER_DEPTH).map(|_| G(&long)).collect(); - toks.extend((0..3_000).map(|_| P)); - let mut warnings = Vec::new(); - let folders = read_phry(&phry_bytes(&toks), 3_000, &mut warnings).unwrap(); - assert_eq!(folders.len(), 3_000); - let held: usize = folders.iter().flatten().map(|n| n.len() + size_of::()).sum(); - assert!(held <= MAX_FOLDER_BYTES, "{held}"); - assert_eq!(folders[0].len(), MAX_FOLDER_DEPTH); - assert!(folders[2_999].is_empty(), "past the budget: top level"); - assert!(warnings.iter().any(|w| w.contains("too large")), "{warnings:?}"); - } - - #[test] - fn phry_round_trips_through_the_writer() { - let presets: Vec = (0..6).map(|i| named(&format!("B{i}"))).collect(); - let folders = vec![path(&[]), path(&["Set", "Ink"]), path(&["Set", "Ink"]), path(&["Set"]), path(&["Other"]), path(&["Set", "Ink"])]; - let bytes = write_v6_folders(2, &[], &[], &presets, &folders, true).unwrap(); - let f = parse(&bytes).unwrap(); - assert_eq!(f.presets, presets); - assert_eq!(f.folders, folders); - assert!(f.warnings.is_empty(), "{:?}", f.warnings); - // No folders: no phry section, same bytes as write_v6. - assert_eq!(write_v6_folders(2, &[], &[], &presets, &vec![Vec::new(); 6], true).unwrap(), write_v6(2, &[], &[], &presets, true).unwrap()); - // Mismatched lengths are an error. - assert!(write_v6_folders(2, &[], &[], &presets, &folders[..2], true).is_err()); - } -} +mod tests; diff --git a/crates/psd/src/abr/tests.rs b/crates/psd/src/abr/tests.rs new file mode 100644 index 0000000000..29ed91ec6e --- /dev/null +++ b/crates/psd/src/abr/tests.rs @@ -0,0 +1,298 @@ +use super::*; +use crate::descriptor::UnicodeString; + +fn sample(id: &str, w: u32, h: u32, depth: u16) -> AbrSample { + let bpp = usize::from(depth / 8); + let data = (0..w as usize * h as usize * bpp).map(|i| if (i / bpp) % 3 == 0 { 255 } else { (i % 7) as u8 * 30 }).collect(); + AbrSample { id: id.into(), width: w, height: h, depth, data } +} + +#[test] +fn embedded_patterns_spend_the_samples_budget() { + let p = PsdPattern { + mode: 3, + width: 5, + height: 3, + name: "p".into(), + id: "id".into(), + palette: None, + depth: 8, + channels: vec![vec![1; 15], vec![2; 15], vec![3; 15]], + alpha: None, + }; + let abr = write_v6(2, &[sample("s", 10, 10, 8)], &[p.clone(), p], &[], true).unwrap(); + let parse_within = |left: usize| { + let mut out = AbrFile::default(); + let mut budget = Budget(left); + parse_v6_within(&mut Rd::new(&abr[2..]), &mut out, &mut budget).unwrap(); + (out, budget.0) + }; + // 100 sample bytes plus two 45-byte patterns. + let (out, left) = parse_within(190); + assert_eq!((out.samples.len(), out.patterns.len(), left), (1, 2, 0)); + // One byte short: the patterns no longer fit after the sample (they used not to count). + let (out, left) = parse_within(189); + assert_eq!((out.samples.len(), out.patterns.len(), left), (1, 0, 14)); + assert!(out.warnings.iter().any(|w| w.contains("embedded patterns unreadable")), "{:?}", out.warnings); +} + +#[test] +fn failed_pattern_section_does_not_refund_budget_to_later_sections() { + let p = PsdPattern { + mode: 3, + width: 5, + height: 3, + name: "p".into(), + id: "id".into(), + palette: None, + depth: 8, + channels: vec![vec![1; 15], vec![2; 15], vec![3; 15]], + alpha: None, + }; + let valid = write_pattern_block(std::slice::from_ref(&p)).unwrap(); + let mut malformed = valid.clone(); + malformed.extend_from_slice(&100u32.to_be_bytes()); + + let mut body = 2u16.to_be_bytes().to_vec(); + section(&mut body, b"patt", &malformed); + section(&mut body, b"patt", &valid); + let mut out = AbrFile::default(); + let mut budget = Budget(60); + parse_v6_within(&mut Rd::new(&body), &mut out, &mut budget).unwrap(); + + assert!(out.patterns.is_empty(), "a failed block is discarded atomically"); + assert_eq!(budget.0, 0, "the failed block's first 45 bytes and later partial 15-byte charge are retained"); + assert_eq!(out.warnings.iter().filter(|w| w.contains("embedded patterns unreadable")).count(), 2); +} + +#[test] +fn v1_v2_round_trip_raw_and_rle() { + for version in [1u16, 2] { + for rle in [false, true] { + let brushes = vec![ + LegacyBrush { + name: String::new(), + spacing: 25, + anti_alias: true, + tip: LegacyTip::Computed { diameter: 19, hardness: 80, angle: -30, roundness: 50 }, + }, + LegacyBrush { + name: if version == 2 { "Leaf ✓".into() } else { String::new() }, + spacing: 40, + anti_alias: false, + tip: LegacyTip::Sampled(sample("", 13, 9, 8)), + }, + LegacyBrush { name: String::new(), spacing: 10, anti_alias: true, tip: LegacyTip::Sampled(sample("", 4, 6, 16)) }, + ]; + let bytes = write_v12(version, &brushes, rle).unwrap(); + let f = parse(&bytes).unwrap(); + assert_eq!(f.version, version); + assert_eq!(f.legacy, brushes, "v{version} rle={rle}"); + assert!(f.warnings.is_empty(), "{:?}", f.warnings); + } + } +} + +#[test] +fn v6_round_trip_both_subversions() { + let samples = vec![sample("$abc", 20, 11, 8), sample("$def", 5, 5, 16)]; + let preset = Descriptor::new("brushPreset") + .with("Nm ", Value::Text(UnicodeString::new_nul("Grass"))) + .with("Brsh", Value::Descriptor(Descriptor::new("sampledBrush").with("sampledData", Value::Text(UnicodeString::new_nul("$abc"))))); + for sub in [1u16, 2] { + for rle in [false, true] { + let bytes = write_v6(sub, &samples, &[], std::slice::from_ref(&preset), rle).unwrap(); + let f = parse(&bytes).unwrap(); + assert_eq!((f.version, f.subversion), (6, sub)); + assert_eq!(f.samples, samples); + assert_eq!(f.presets, vec![preset.clone()]); + assert!(f.warnings.is_empty(), "{:?}", f.warnings); + } + } + assert_eq!(samples[1].to_unit().len(), 25); +} + +#[test] +fn hostile_input_errors_without_panicking() { + assert!(parse(&[]).is_err()); + assert!(parse(&[0, 3, 0, 0]).is_err()); + assert!(parse(&[0, 6, 0, 9]).is_err()); + // Absurd sample bounds. + let mut s = sample("", 2, 2, 8); + s.width = MAX_EDGE + 1; + assert!(write_v12(1, &[LegacyBrush { name: String::new(), spacing: 1, anti_alias: true, tip: LegacyTip::Sampled(s) }], false).is_err()); + let good = write_v6(2, &[sample("$a", 30, 30, 8)], &[], &[Descriptor::new("brushPreset")], true).unwrap(); + for cut in 0..good.len() { + let _ = parse(&good[..cut]); + } + let v2 = write_v12(2, &[LegacyBrush { name: "x".into(), spacing: 1, anti_alias: true, tip: LegacyTip::Sampled(sample("", 9, 9, 16)) }], true).unwrap(); + for cut in 0..v2.len() { + let _ = parse(&v2[..cut]); + } + // Flip every byte once: never panics. + for i in 0..good.len() { + let mut b = good.clone(); + b[i] ^= 0xa5; + let _ = parse(&b); + } + // A huge declared count with no data is an error, not an allocation. + assert!(parse(&[0, 2, 0xff, 0xff]).is_err()); +} + +fn named(n: &str) -> Descriptor { + Descriptor::new("brushPreset").with("Nm ", Value::Text(UnicodeString::new_nul(n))) +} + +/// Hierarchy tokens: `G(name)` opens, `P` is a preset, `E` closes. +enum Tok<'a> { + G(&'a str), + P, + E, +} + +/// A v6 file with `n` presets and a hand-made `phry` token stream. +fn with_phry(n: usize, toks: &[Tok]) -> Vec { + let presets: Vec = (0..n).map(|i| named(&format!("B{i}"))).collect(); + let mut bytes = write_v6(2, &[], &[], &presets, false).unwrap(); + section(&mut bytes, b"phry", &phry_bytes(toks)); + bytes +} + +/// A `phry` section body holding `toks`. +fn phry_bytes(toks: &[Tok]) -> Vec { + let items = toks + .iter() + .map(|t| { + Value::Descriptor(match t { + Tok::G(name) => Descriptor::new("Grup") + .with("Nm ", Value::Text(UnicodeString::new_nul(name))) + .with("zuid", Value::Text(UnicodeString::new_nul("c9ee8fd5-eb7d-924c-9e95-ddc98e40bb6c"))), + Tok::P => Descriptor::new("preset"), + Tok::E => Descriptor::new("groupEnd"), + }) + }) + .collect(); + VersionedDescriptor::new(Descriptor::new("null").with("hierarchy", Value::List(items))).to_bytes() +} + +fn path(p: &[&str]) -> Vec { + p.iter().map(|s| s.to_string()).collect() +} + +#[test] +fn phry_flat_folders_like_photoshop_25() { + // The layout of Photoshop 25.1's default brushes: four folders, every preset in one. + use Tok::*; + let f = parse(&with_phry(5, &[G("General"), P, P, E, G("Dry Media"), P, E, G("Wet Media"), P, E, G("Special Effects"), P, E])).unwrap(); + assert_eq!(f.folders, vec![path(&["General"]), path(&["General"]), path(&["Dry Media"]), path(&["Wet Media"]), path(&["Special Effects"])]); + assert!(f.warnings.is_empty(), "{:?}", f.warnings); +} + +#[test] +fn phry_nested_folders_and_top_level_presets() { + use Tok::*; + let f = parse(&with_phry(5, &[P, G("Animals"), G("Birds"), P, E, P, G("Fish"), P, E, E, P])).unwrap(); + assert_eq!(f.folders, vec![path(&[]), path(&["Animals", "Birds"]), path(&["Animals"]), path(&["Animals", "Fish"]), path(&[])]); + assert!(f.warnings.is_empty(), "{:?}", f.warnings); + // No folder at all: no hierarchy. + let f = parse(&with_phry(2, &[P, P])).unwrap(); + assert!(f.folders.is_empty()); +} + +#[test] +fn phry_mismatches_become_warnings() { + use Tok::*; + // A stray groupEnd is ignored; an unclosed folder still holds its presets. + let f = parse(&with_phry(2, &[E, G("A"), P, E, E, G("B"), P])).unwrap(); + assert_eq!(f.folders, vec![path(&["A"]), path(&["B"])]); + assert!(f.warnings.iter().any(|w| w.contains("folder end")), "{:?}", f.warnings); + // Fewer preset tokens than presets: the rest are at the top level. + let f = parse(&with_phry(3, &[G("A"), P, E])).unwrap(); + assert_eq!(f.folders, vec![path(&["A"]), path(&[]), path(&[])]); + assert!(f.warnings.iter().any(|w| w.contains("list 1 brushes but the file holds 3")), "{:?}", f.warnings); + // More preset tokens than presets: extras ignored. + let f = parse(&with_phry(1, &[G("A"), P, P, P, E])).unwrap(); + assert_eq!(f.folders, vec![path(&["A"])]); + assert_eq!(f.presets.len(), 1); + assert!(!f.warnings.is_empty()); + // A depth bomb: folders deeper than the limit merge into their ancestor at the limit. + let mut toks: Vec = (0..10_000).map(|_| G("deep")).collect(); + toks.push(P); + toks.extend((0..10_000).map(|_| E)); + toks.extend([G("next"), P, E]); + let f = parse(&with_phry(2, &toks)).unwrap(); + assert_eq!(f.folders[0].len(), MAX_FOLDER_DEPTH); + assert_eq!(f.folders[1], path(&["next"])); + assert!(f.warnings.iter().any(|w| w.contains("deeper")), "{:?}", f.warnings); + // An unreadable hierarchy: imported flat, with a warning. + let mut bytes = write_v6(2, &[], &[], &[named("x")], false).unwrap(); + section(&mut bytes, b"phry", &[0, 0, 0, 16, 0xff, 0xff]); + let f = parse(&bytes).unwrap(); + assert!(f.folders.is_empty() && f.presets.len() == 1); + assert!(f.warnings.iter().any(|w| w.contains("phry")), "{:?}", f.warnings); + // Truncations and bit flips of a file with a hierarchy never panic. + let good = with_phry(3, &[G("A"), P, G("B"), P, E, E, P]); + for cut in 0..good.len() { + let _ = parse(&good[..cut]); + } + for i in 0..good.len() { + let mut b = good.clone(); + b[i] ^= 0x5a; + let _ = parse(&b); + } +} + +#[test] +fn phry_builds_paths_only_for_the_files_presets() { + use Tok::*; + // A few-KB section listing 100,000 deep presets for a file with 2: two paths are built. + let mut toks: Vec = (0..MAX_FOLDER_DEPTH).map(|_| G("folder")).collect(); + toks.extend((0..100_000).map(|_| P)); + let mut warnings = Vec::new(); + let folders = read_phry(&phry_bytes(&toks), 2, &mut warnings).unwrap(); + assert_eq!(folders.len(), 2); + assert_eq!(folders.capacity(), 2); + assert_eq!(folders[1].len(), MAX_FOLDER_DEPTH); + assert!(warnings.iter().any(|w| w.contains("list 100000 brushes but the file holds 2")), "{warnings:?}"); + // `phry` before `desc` still pairs with the file's presets. + let mut bytes = write_v6(2, &[], &[], &[named("a"), named("b")], false).unwrap(); + let at = bytes.windows(8).position(|w| w == b"8BIMdesc").unwrap(); + let mut phry = Vec::new(); + section(&mut phry, b"phry", &phry_bytes(&[G("A"), P, E, P])); + bytes.splice(at..at, phry); + let f = parse(&bytes).unwrap(); + assert_eq!(f.folders, vec![path(&["A"]), path(&[])]); + assert!(f.warnings.is_empty(), "{:?}", f.warnings); +} + +#[test] +fn phry_folder_paths_stay_within_their_byte_budget() { + use Tok::*; + // Thousands of presets under 32 folders of 255-character names would need ~27 MB of paths. + let long = "x".repeat(MAX_FOLDER_NAME); + let mut toks: Vec = (0..MAX_FOLDER_DEPTH).map(|_| G(&long)).collect(); + toks.extend((0..3_000).map(|_| P)); + let mut warnings = Vec::new(); + let folders = read_phry(&phry_bytes(&toks), 3_000, &mut warnings).unwrap(); + assert_eq!(folders.len(), 3_000); + let held: usize = folders.iter().flatten().map(|n| n.len() + size_of::()).sum(); + assert!(held <= MAX_FOLDER_BYTES, "{held}"); + assert_eq!(folders[0].len(), MAX_FOLDER_DEPTH); + assert!(folders[2_999].is_empty(), "past the budget: top level"); + assert!(warnings.iter().any(|w| w.contains("too large")), "{warnings:?}"); +} + +#[test] +fn phry_round_trips_through_the_writer() { + let presets: Vec = (0..6).map(|i| named(&format!("B{i}"))).collect(); + let folders = vec![path(&[]), path(&["Set", "Ink"]), path(&["Set", "Ink"]), path(&["Set"]), path(&["Other"]), path(&["Set", "Ink"])]; + let bytes = write_v6_folders(2, &[], &[], &presets, &folders, true).unwrap(); + let f = parse(&bytes).unwrap(); + assert_eq!(f.presets, presets); + assert_eq!(f.folders, folders); + assert!(f.warnings.is_empty(), "{:?}", f.warnings); + // No folders: no phry section, same bytes as write_v6. + assert_eq!(write_v6_folders(2, &[], &[], &presets, &vec![Vec::new(); 6], true).unwrap(), write_v6(2, &[], &[], &presets, true).unwrap()); + // Mismatched lengths are an error. + assert!(write_v6_folders(2, &[], &[], &presets, &folders[..2], true).is_err()); +} diff --git a/crates/psd/src/compression.rs b/crates/psd/src/compression.rs index 68782464ad..3ec7d64bb8 100644 --- a/crates/psd/src/compression.rs +++ b/crates/psd/src/compression.rs @@ -539,361 +539,7 @@ pub fn unpredict(buf: &mut [u8], layout: &PlaneLayout) -> Result<()> { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn checked_zip_validates_trailer_size_and_padding_budget() { - let layout = PlaneLayout { planes: 1, width: 3, height: 1, depth: 8, version: Version::Psd }; - for compression in [Compression::Zip, Compression::ZipPrediction] { - let data = encode_planes(compression, &[1, 2, 3], &layout).unwrap(); - for cut in 0..data.len() { - assert!(decode_planes(compression, &data[..cut], &layout).is_err(), "cut {cut}"); - assert!(validate_planes(compression, &data[..cut], &layout).is_err()); - } - let mut corrupt = data; - *corrupt.last_mut().unwrap() ^= 1; - assert!(decode_planes(compression, &corrupt, &layout).is_err()); - assert!(validate_planes(compression, &corrupt, &layout).is_err()); - } - let padded = zip_compress(&[1, 2, 3, 0]); - assert_eq!(decode_planes(Compression::Zip, &padded, &layout).unwrap(), [1, 2, 3]); - let bomb = zip_compress(&vec![0; (1 << 20) + 4]); - assert!(decode_planes(Compression::Zip, &bomb, &layout).is_err()); - assert!(validate_planes(Compression::Zip, &bomb, &layout).is_err()); - } - - fn layout(planes: usize, width: usize, height: usize, depth: u16, version: Version) -> PlaneLayout { - PlaneLayout { planes, width, height, depth, version } - } - - fn pb_roundtrip(src: &[u8]) -> Vec { - let enc = packbits::encode_vec(src); - let dec = packbits::decode(&enc, src.len()).unwrap(); - assert_eq!(dec, src, "encoded: {enc:?}"); - enc - } - - #[test] - fn zip_absurd_declared_size_is_an_error() { - let z = zip_compress(&[7u8; 64]); - for expected in [1usize << 40, usize::MAX / 2, usize::MAX] { - assert!(zip_decompress(&z, expected).is_err(), "expected {expected}"); - } - // Through decode_planes: a tiny ZIP channel claiming a huge (but capped) plane. - let l = layout(1, 1 << 16, 1 << 15, 8, Version::Psb); - assert!(decode_planes(Compression::Zip, &z, &l).is_err()); - assert!(decode_planes(Compression::ZipPrediction, &z, &l).is_err()); - // Past MAX_DECODED_BYTES. - let l = layout(4, 1 << 20, 1 << 20, 32, Version::Psb); - assert!(decode_planes(Compression::Zip, &z, &l).is_err()); - // Garbage that is not zlib at all. - assert!(zip_decompress(&[0xff; 16], 1 << 30).is_err()); - } - - #[test] - fn zip_decompress_exact_and_truncated() { - let src: Vec = (0..3_000_000u32).map(|i| (i % 251) as u8).collect(); - let z = zip_compress(&src); - assert_eq!(zip_decompress(&z, src.len()).unwrap(), src); - // Asking for fewer bytes returns exactly that many. - assert_eq!(zip_decompress(&z, 1000).unwrap(), &src[..1000]); - assert!(zip_decompress(&z, src.len() + 1).is_err()); - assert!(zip_decompress(&z, 0).unwrap().is_empty()); - } - - #[test] - fn packbits_empty() { - assert!(pb_roundtrip(&[]).is_empty()); - } - - #[test] - fn packbits_single() { - assert_eq!(pb_roundtrip(&[7]), vec![0, 7]); - } - - #[test] - fn packbits_run_of_two() { - assert_eq!(pb_roundtrip(&[5, 5]), vec![0xff, 5]); - } - - #[test] - fn packbits_run_128() { - let src = vec![9u8; 128]; - assert_eq!(pb_roundtrip(&src), vec![0x81, 9]); - } - - #[test] - fn packbits_run_129() { - let src = vec![9u8; 129]; - assert_eq!(pb_roundtrip(&src), vec![0x81, 9, 0, 9]); - } - - #[test] - fn packbits_run_130_and_256() { - pb_roundtrip(&[1u8; 130]); - let enc = pb_roundtrip(&[1u8; 256]); - assert_eq!(enc, vec![0x81, 1, 0x81, 1]); - } - - #[test] - fn packbits_literal_128_and_129() { - let src: Vec = (0..128u32).map(|i| i as u8).collect(); - let enc = pb_roundtrip(&src); - assert_eq!(enc[0], 127); - assert_eq!(enc.len(), 129); - let src: Vec = (0..129u32).map(|i| i as u8).collect(); - let enc = pb_roundtrip(&src); - assert_eq!(enc[0], 127); - assert_eq!(enc[129], 0); - assert_eq!(enc.len(), 131); - } - - #[test] - fn packbits_literal_run_boundary() { - pb_roundtrip(&[1, 2, 3, 3, 3, 3, 4, 5]); - pb_roundtrip(&[1, 1, 2, 2, 3, 3]); - pb_roundtrip(&[1, 2, 2, 3]); - pb_roundtrip(&[0, 0, 0, 1, 0, 0, 0]); - let enc = pb_roundtrip(&[1, 2, 3, 3, 3]); - assert_eq!(enc, vec![1, 1, 2, 0xfe, 3]); - } - - #[test] - fn packbits_never_emits_noop() { - for n in 0..300usize { - let src: Vec = (0..n).map(|i| ((i / 3) % 5) as u8).collect(); - let enc = pb_roundtrip(&src); - // Walk the packets to find headers. - let mut i = 0; - while i < enc.len() { - let h = enc[i] as i8; - assert_ne!(h, -128); - i += if h >= 0 { h as usize + 2 } else { 2 }; - } - } - } - - #[test] - fn packbits_decode_noop_skipped() { - assert_eq!(packbits::decode(&[0x80, 0, 42], 1).unwrap(), vec![42]); - } - - #[test] - fn packbits_decode_errors() { - assert!(packbits::decode(&[], 1).is_err()); - assert!(packbits::decode(&[2, 1, 2], 3).is_err()); // literal truncated - assert!(packbits::decode(&[0xfe], 3).is_err()); // run truncated - assert!(packbits::decode(&[0xfd, 1], 3).is_err()); // run overflows (4 > 3) - assert!(packbits::decode(&[3, 1, 2, 3, 4], 3).is_err()); // literal overflows - } - - /// `out.len() + expected` past `usize::MAX` used to panic in debug builds and, in release, - /// wrap and return `Ok` having decoded nothing. - #[test] - fn packbits_decode_into_output_length_overflow_is_an_error() { - let mut out = vec![7u8]; - let r = packbits::decode_into(&[0x00, 0xaa], usize::MAX, &mut out); - assert!(matches!(r, Err(PsdError::LimitExceeded(_))), "{r:?}"); - assert_eq!(out, [7]); - // The largest `expected` that fits still decodes up to the input, then reports it short. - let r = packbits::decode_into(&[0x00, 0xaa], usize::MAX - 1, &mut out); - assert!(matches!(r, Err(PsdError::Decompress(_))), "{r:?}"); - assert_eq!(out, [7, 0xaa]); - } - - #[test] - fn packbits_zero_expected_ignores_input() { - assert_eq!(packbits::decode(&[0xff, 1], 0).unwrap(), Vec::::new()); - } - - #[test] - fn compression_values() { - for v in 0..6 { - assert_eq!(Compression::from_u16(v).as_u16(), v); - } - assert_eq!(Compression::from_u16(9), Compression::Unknown(9)); - } - - fn sample_data(l: &PlaneLayout) -> Vec { - let n = l.decoded_len().unwrap(); - (0..n).map(|i| ((i * 7 + i / 5) % 251) as u8).collect() - } - - #[test] - fn all_codecs_roundtrip_all_depths() { - for version in [Version::Psd, Version::Psb] { - for depth in [1u16, 8, 16, 32] { - for (w, h) in [(0, 0), (1, 1), (3, 2), (17, 5), (0, 3), (4, 0)] { - for planes in [1, 3] { - let l = layout(planes, w, h, depth, version); - let data = sample_data(&l); - for c in Compression::ALL { - let enc = encode_planes(c, &data, &l).unwrap(); - validate_planes(c, &enc, &l).unwrap(); - let dec = decode_planes(c, &enc, &l).unwrap(); - assert_eq!(dec, data, "{c:?} {depth} {w}x{h} {version:?}"); - } - } - } - } - } - } - - #[test] - fn rle_count_width_psd_vs_psb() { - let data = vec![0u8; 4]; - let psd = encode_planes(Compression::Rle, &data, &layout(1, 2, 2, 8, Version::Psd)).unwrap(); - let psb = encode_planes(Compression::Rle, &data, &layout(1, 2, 2, 8, Version::Psb)).unwrap(); - assert_eq!(psd, vec![0, 2, 0, 2, 0xff, 0, 0xff, 0]); - assert_eq!(psb, vec![0, 0, 0, 2, 0, 0, 0, 2, 0xff, 0, 0xff, 0]); - assert!(decode_planes(Compression::Rle, &psd, &layout(1, 2, 2, 8, Version::Psb)).is_err()); - } - - #[test] - fn rle_odd_width() { - let l = layout(1, 7, 3, 16, Version::Psd); - let data = sample_data(&l); - let enc = encode_planes(Compression::Rle, &data, &l).unwrap(); - assert_eq!(decode_planes(Compression::Rle, &enc, &l).unwrap(), data); - } - - #[test] - fn rle_truncated_fails() { - let l = layout(1, 10, 10, 8, Version::Psd); - let data = sample_data(&l); - let enc = encode_planes(Compression::Rle, &data, &l).unwrap(); - for cut in 0..enc.len() { - assert!(decode_planes(Compression::Rle, &enc[..cut], &l).is_err(), "cut {cut}"); - assert!(validate_planes(Compression::Rle, &enc[..cut], &l).is_err(), "cut {cut}"); - } - } - - #[test] - fn zip_truncated_fails() { - let l = layout(1, 10, 10, 8, Version::Psd); - let data = sample_data(&l); - let enc = encode_planes(Compression::Zip, &data, &l).unwrap(); - for cut in 0..enc.len() - 4 { - assert!(decode_planes(Compression::Zip, &enc[..cut], &l).is_err(), "cut {cut}"); - assert!(validate_planes(Compression::Zip, &enc[..cut], &l).is_err(), "cut {cut}"); - } - } - - /// #2926: a ZIP stream declaring more than `MAX_DECODED_BYTES` is not inflated at parse - /// time. Garbage zlib data proves it: decompressing it would fail, skipping it passes, and - /// decoding the layout still reports the size limit. - #[test] - fn zip_over_budget_is_not_decompressed_at_parse() { - let l = layout(4, 300_000, 300_000, 8, Version::Psb); - assert!(l.total_bytes().unwrap() > MAX_DECODED_BYTES); - let garbage = [0xde, 0xad, 0xbe, 0xef, 0x01, 0x02, 0x03]; - for c in [Compression::Zip, Compression::ZipPrediction] { - validate_planes(c, &garbage, &l).unwrap(); - assert!(matches!(decode_planes(c, &garbage, &l), Err(PsdError::LimitExceeded(_))), "{c:?}"); - } - // Within the budget the stream is still checked. - let small = layout(1, 4, 4, 8, Version::Psd); - assert!(validate_planes(Compression::Zip, &garbage, &small).is_err()); - } - - #[test] - fn raw_short_fails() { - let l = layout(2, 3, 3, 8, Version::Psd); - assert!(decode_planes(Compression::Raw, &[0; 17], &l).is_err()); - assert!(decode_planes(Compression::Raw, &[0; 18], &l).is_ok()); - } - - #[test] - fn unknown_compression_errors() { - let l = layout(1, 1, 1, 8, Version::Psd); - assert!(decode_planes(Compression::Unknown(7), &[0], &l).is_err()); - assert!(encode_planes(Compression::Unknown(7), &[0], &l).is_err()); - } - - #[test] - fn encode_rejects_wrong_size() { - let l = layout(1, 2, 2, 8, Version::Psd); - assert!(encode_planes(Compression::Raw, &[0; 3], &l).is_err()); - } - - #[test] - fn decoded_len_limits() { - let l = layout(56, 300_000, 300_000, 32, Version::Psb); - assert!(matches!(l.decoded_len(), Err(PsdError::LimitExceeded(_)))); - assert!(decode_planes(Compression::Rle, &[0; 16], &l).is_err()); - } - - /// Real PSBs go past 2 GiB in one decode (#375): a 30000² RGB merged image and a 33000² - /// 16-bit layer channel. Only checks the limit, so nothing is allocated. - #[test] - #[cfg(target_pointer_width = "64")] - fn decoded_len_allows_large_psb_planes() { - assert_eq!(layout(3, 30_000, 30_000, 8, Version::Psb).decoded_len().unwrap(), 2_700_000_000); - assert_eq!(layout(1, 33_000, 33_000, 16, Version::Psb).decoded_len().unwrap(), 2_178_000_000); - assert!(layout(4, 40_000, 40_000, 16, Version::Psb).decoded_len().is_err()); - } - - #[test] - fn prediction_8bit_known_vector() { - let l = layout(1, 4, 1, 8, Version::Psd); - let mut v = vec![10, 12, 11, 255]; - predict(&mut v, &l).unwrap(); - assert_eq!(v, vec![10, 2, 255, 244]); - unpredict(&mut v, &l).unwrap(); - assert_eq!(v, vec![10, 12, 11, 255]); - } - - #[test] - fn prediction_16bit_known_vector() { - let l = layout(1, 3, 1, 16, Version::Psd); - let mut v = vec![0x01, 0x00, 0x01, 0x05, 0x00, 0x00]; - predict(&mut v, &l).unwrap(); - assert_eq!(v, vec![0x01, 0x00, 0x00, 0x05, 0xfe, 0xfb]); - unpredict(&mut v, &l).unwrap(); - assert_eq!(v, vec![0x01, 0x00, 0x01, 0x05, 0x00, 0x00]); - } - - #[test] - fn prediction_32bit_plane_shuffle() { - // Two samples: AABBCCDD and 11223344 → planes [AA,11][BB,22][CC,33][DD,44] - let l = layout(1, 2, 1, 32, Version::Psd); - let orig = vec![0xAA, 0xBB, 0xCC, 0xDD, 0x11, 0x22, 0x33, 0x44]; - let mut v = orig.clone(); - predict(&mut v, &l).unwrap(); - let planes = [0xAAu8, 0x11, 0xBB, 0x22, 0xCC, 0x33, 0xDD, 0x44]; - let mut expect = planes; - for i in (1..8).rev() { - expect[i] = expect[i].wrapping_sub(expect[i - 1]); - } - assert_eq!(v, expect); - unpredict(&mut v, &l).unwrap(); - assert_eq!(v, orig); - } - - #[test] - fn prediction_32bit_floats_roundtrip() { - let l = layout(1, 5, 2, 32, Version::Psd); - let mut v = Vec::new(); - for i in 0..10 { - v.extend_from_slice(&(i as f32 * 0.37 - 1.0).to_be_bytes()); - } - let enc = encode_planes(Compression::ZipPrediction, &v, &l).unwrap(); - assert_eq!(decode_planes(Compression::ZipPrediction, &enc, &l).unwrap(), v); - } - - #[test] - fn zip_bomb_is_bounded() { - let big = zip_compress(&vec![0u8; 1 << 20]); - let out = zip_decompress(&big, 10).unwrap(); - assert_eq!(out.len(), 10); - } - - #[test] - fn zip_garbage_errors() { - assert!(zip_decompress(&[1, 2, 3, 4], 4).is_err()); - } -} +mod tests; #[cfg(test)] mod parallel_rle_equivalence { diff --git a/crates/psd/src/compression/tests.rs b/crates/psd/src/compression/tests.rs new file mode 100644 index 0000000000..a9700ded31 --- /dev/null +++ b/crates/psd/src/compression/tests.rs @@ -0,0 +1,353 @@ +use super::*; + +#[test] +fn checked_zip_validates_trailer_size_and_padding_budget() { + let layout = PlaneLayout { planes: 1, width: 3, height: 1, depth: 8, version: Version::Psd }; + for compression in [Compression::Zip, Compression::ZipPrediction] { + let data = encode_planes(compression, &[1, 2, 3], &layout).unwrap(); + for cut in 0..data.len() { + assert!(decode_planes(compression, &data[..cut], &layout).is_err(), "cut {cut}"); + assert!(validate_planes(compression, &data[..cut], &layout).is_err()); + } + let mut corrupt = data; + *corrupt.last_mut().unwrap() ^= 1; + assert!(decode_planes(compression, &corrupt, &layout).is_err()); + assert!(validate_planes(compression, &corrupt, &layout).is_err()); + } + let padded = zip_compress(&[1, 2, 3, 0]); + assert_eq!(decode_planes(Compression::Zip, &padded, &layout).unwrap(), [1, 2, 3]); + let bomb = zip_compress(&vec![0; (1 << 20) + 4]); + assert!(decode_planes(Compression::Zip, &bomb, &layout).is_err()); + assert!(validate_planes(Compression::Zip, &bomb, &layout).is_err()); +} + +fn layout(planes: usize, width: usize, height: usize, depth: u16, version: Version) -> PlaneLayout { + PlaneLayout { planes, width, height, depth, version } +} + +fn pb_roundtrip(src: &[u8]) -> Vec { + let enc = packbits::encode_vec(src); + let dec = packbits::decode(&enc, src.len()).unwrap(); + assert_eq!(dec, src, "encoded: {enc:?}"); + enc +} + +#[test] +fn zip_absurd_declared_size_is_an_error() { + let z = zip_compress(&[7u8; 64]); + for expected in [1usize << 40, usize::MAX / 2, usize::MAX] { + assert!(zip_decompress(&z, expected).is_err(), "expected {expected}"); + } + // Through decode_planes: a tiny ZIP channel claiming a huge (but capped) plane. + let l = layout(1, 1 << 16, 1 << 15, 8, Version::Psb); + assert!(decode_planes(Compression::Zip, &z, &l).is_err()); + assert!(decode_planes(Compression::ZipPrediction, &z, &l).is_err()); + // Past MAX_DECODED_BYTES. + let l = layout(4, 1 << 20, 1 << 20, 32, Version::Psb); + assert!(decode_planes(Compression::Zip, &z, &l).is_err()); + // Garbage that is not zlib at all. + assert!(zip_decompress(&[0xff; 16], 1 << 30).is_err()); +} + +#[test] +fn zip_decompress_exact_and_truncated() { + let src: Vec = (0..3_000_000u32).map(|i| (i % 251) as u8).collect(); + let z = zip_compress(&src); + assert_eq!(zip_decompress(&z, src.len()).unwrap(), src); + // Asking for fewer bytes returns exactly that many. + assert_eq!(zip_decompress(&z, 1000).unwrap(), &src[..1000]); + assert!(zip_decompress(&z, src.len() + 1).is_err()); + assert!(zip_decompress(&z, 0).unwrap().is_empty()); +} + +#[test] +fn packbits_empty() { + assert!(pb_roundtrip(&[]).is_empty()); +} + +#[test] +fn packbits_single() { + assert_eq!(pb_roundtrip(&[7]), vec![0, 7]); +} + +#[test] +fn packbits_run_of_two() { + assert_eq!(pb_roundtrip(&[5, 5]), vec![0xff, 5]); +} + +#[test] +fn packbits_run_128() { + let src = vec![9u8; 128]; + assert_eq!(pb_roundtrip(&src), vec![0x81, 9]); +} + +#[test] +fn packbits_run_129() { + let src = vec![9u8; 129]; + assert_eq!(pb_roundtrip(&src), vec![0x81, 9, 0, 9]); +} + +#[test] +fn packbits_run_130_and_256() { + pb_roundtrip(&[1u8; 130]); + let enc = pb_roundtrip(&[1u8; 256]); + assert_eq!(enc, vec![0x81, 1, 0x81, 1]); +} + +#[test] +fn packbits_literal_128_and_129() { + let src: Vec = (0..128u32).map(|i| i as u8).collect(); + let enc = pb_roundtrip(&src); + assert_eq!(enc[0], 127); + assert_eq!(enc.len(), 129); + let src: Vec = (0..129u32).map(|i| i as u8).collect(); + let enc = pb_roundtrip(&src); + assert_eq!(enc[0], 127); + assert_eq!(enc[129], 0); + assert_eq!(enc.len(), 131); +} + +#[test] +fn packbits_literal_run_boundary() { + pb_roundtrip(&[1, 2, 3, 3, 3, 3, 4, 5]); + pb_roundtrip(&[1, 1, 2, 2, 3, 3]); + pb_roundtrip(&[1, 2, 2, 3]); + pb_roundtrip(&[0, 0, 0, 1, 0, 0, 0]); + let enc = pb_roundtrip(&[1, 2, 3, 3, 3]); + assert_eq!(enc, vec![1, 1, 2, 0xfe, 3]); +} + +#[test] +fn packbits_never_emits_noop() { + for n in 0..300usize { + let src: Vec = (0..n).map(|i| ((i / 3) % 5) as u8).collect(); + let enc = pb_roundtrip(&src); + // Walk the packets to find headers. + let mut i = 0; + while i < enc.len() { + let h = enc[i] as i8; + assert_ne!(h, -128); + i += if h >= 0 { h as usize + 2 } else { 2 }; + } + } +} + +#[test] +fn packbits_decode_noop_skipped() { + assert_eq!(packbits::decode(&[0x80, 0, 42], 1).unwrap(), vec![42]); +} + +#[test] +fn packbits_decode_errors() { + assert!(packbits::decode(&[], 1).is_err()); + assert!(packbits::decode(&[2, 1, 2], 3).is_err()); // literal truncated + assert!(packbits::decode(&[0xfe], 3).is_err()); // run truncated + assert!(packbits::decode(&[0xfd, 1], 3).is_err()); // run overflows (4 > 3) + assert!(packbits::decode(&[3, 1, 2, 3, 4], 3).is_err()); // literal overflows +} + +/// `out.len() + expected` past `usize::MAX` used to panic in debug builds and, in release, +/// wrap and return `Ok` having decoded nothing. +#[test] +fn packbits_decode_into_output_length_overflow_is_an_error() { + let mut out = vec![7u8]; + let r = packbits::decode_into(&[0x00, 0xaa], usize::MAX, &mut out); + assert!(matches!(r, Err(PsdError::LimitExceeded(_))), "{r:?}"); + assert_eq!(out, [7]); + // The largest `expected` that fits still decodes up to the input, then reports it short. + let r = packbits::decode_into(&[0x00, 0xaa], usize::MAX - 1, &mut out); + assert!(matches!(r, Err(PsdError::Decompress(_))), "{r:?}"); + assert_eq!(out, [7, 0xaa]); +} + +#[test] +fn packbits_zero_expected_ignores_input() { + assert_eq!(packbits::decode(&[0xff, 1], 0).unwrap(), Vec::::new()); +} + +#[test] +fn compression_values() { + for v in 0..6 { + assert_eq!(Compression::from_u16(v).as_u16(), v); + } + assert_eq!(Compression::from_u16(9), Compression::Unknown(9)); +} + +fn sample_data(l: &PlaneLayout) -> Vec { + let n = l.decoded_len().unwrap(); + (0..n).map(|i| ((i * 7 + i / 5) % 251) as u8).collect() +} + +#[test] +fn all_codecs_roundtrip_all_depths() { + for version in [Version::Psd, Version::Psb] { + for depth in [1u16, 8, 16, 32] { + for (w, h) in [(0, 0), (1, 1), (3, 2), (17, 5), (0, 3), (4, 0)] { + for planes in [1, 3] { + let l = layout(planes, w, h, depth, version); + let data = sample_data(&l); + for c in Compression::ALL { + let enc = encode_planes(c, &data, &l).unwrap(); + validate_planes(c, &enc, &l).unwrap(); + let dec = decode_planes(c, &enc, &l).unwrap(); + assert_eq!(dec, data, "{c:?} {depth} {w}x{h} {version:?}"); + } + } + } + } + } +} + +#[test] +fn rle_count_width_psd_vs_psb() { + let data = vec![0u8; 4]; + let psd = encode_planes(Compression::Rle, &data, &layout(1, 2, 2, 8, Version::Psd)).unwrap(); + let psb = encode_planes(Compression::Rle, &data, &layout(1, 2, 2, 8, Version::Psb)).unwrap(); + assert_eq!(psd, vec![0, 2, 0, 2, 0xff, 0, 0xff, 0]); + assert_eq!(psb, vec![0, 0, 0, 2, 0, 0, 0, 2, 0xff, 0, 0xff, 0]); + assert!(decode_planes(Compression::Rle, &psd, &layout(1, 2, 2, 8, Version::Psb)).is_err()); +} + +#[test] +fn rle_odd_width() { + let l = layout(1, 7, 3, 16, Version::Psd); + let data = sample_data(&l); + let enc = encode_planes(Compression::Rle, &data, &l).unwrap(); + assert_eq!(decode_planes(Compression::Rle, &enc, &l).unwrap(), data); +} + +#[test] +fn rle_truncated_fails() { + let l = layout(1, 10, 10, 8, Version::Psd); + let data = sample_data(&l); + let enc = encode_planes(Compression::Rle, &data, &l).unwrap(); + for cut in 0..enc.len() { + assert!(decode_planes(Compression::Rle, &enc[..cut], &l).is_err(), "cut {cut}"); + assert!(validate_planes(Compression::Rle, &enc[..cut], &l).is_err(), "cut {cut}"); + } +} + +#[test] +fn zip_truncated_fails() { + let l = layout(1, 10, 10, 8, Version::Psd); + let data = sample_data(&l); + let enc = encode_planes(Compression::Zip, &data, &l).unwrap(); + for cut in 0..enc.len() - 4 { + assert!(decode_planes(Compression::Zip, &enc[..cut], &l).is_err(), "cut {cut}"); + assert!(validate_planes(Compression::Zip, &enc[..cut], &l).is_err(), "cut {cut}"); + } +} + +/// #2926: a ZIP stream declaring more than `MAX_DECODED_BYTES` is not inflated at parse +/// time. Garbage zlib data proves it: decompressing it would fail, skipping it passes, and +/// decoding the layout still reports the size limit. +#[test] +fn zip_over_budget_is_not_decompressed_at_parse() { + let l = layout(4, 300_000, 300_000, 8, Version::Psb); + assert!(l.total_bytes().unwrap() > MAX_DECODED_BYTES); + let garbage = [0xde, 0xad, 0xbe, 0xef, 0x01, 0x02, 0x03]; + for c in [Compression::Zip, Compression::ZipPrediction] { + validate_planes(c, &garbage, &l).unwrap(); + assert!(matches!(decode_planes(c, &garbage, &l), Err(PsdError::LimitExceeded(_))), "{c:?}"); + } + // Within the budget the stream is still checked. + let small = layout(1, 4, 4, 8, Version::Psd); + assert!(validate_planes(Compression::Zip, &garbage, &small).is_err()); +} + +#[test] +fn raw_short_fails() { + let l = layout(2, 3, 3, 8, Version::Psd); + assert!(decode_planes(Compression::Raw, &[0; 17], &l).is_err()); + assert!(decode_planes(Compression::Raw, &[0; 18], &l).is_ok()); +} + +#[test] +fn unknown_compression_errors() { + let l = layout(1, 1, 1, 8, Version::Psd); + assert!(decode_planes(Compression::Unknown(7), &[0], &l).is_err()); + assert!(encode_planes(Compression::Unknown(7), &[0], &l).is_err()); +} + +#[test] +fn encode_rejects_wrong_size() { + let l = layout(1, 2, 2, 8, Version::Psd); + assert!(encode_planes(Compression::Raw, &[0; 3], &l).is_err()); +} + +#[test] +fn decoded_len_limits() { + let l = layout(56, 300_000, 300_000, 32, Version::Psb); + assert!(matches!(l.decoded_len(), Err(PsdError::LimitExceeded(_)))); + assert!(decode_planes(Compression::Rle, &[0; 16], &l).is_err()); +} + +/// Real PSBs go past 2 GiB in one decode (#375): a 30000² RGB merged image and a 33000² +/// 16-bit layer channel. Only checks the limit, so nothing is allocated. +#[test] +#[cfg(target_pointer_width = "64")] +fn decoded_len_allows_large_psb_planes() { + assert_eq!(layout(3, 30_000, 30_000, 8, Version::Psb).decoded_len().unwrap(), 2_700_000_000); + assert_eq!(layout(1, 33_000, 33_000, 16, Version::Psb).decoded_len().unwrap(), 2_178_000_000); + assert!(layout(4, 40_000, 40_000, 16, Version::Psb).decoded_len().is_err()); +} + +#[test] +fn prediction_8bit_known_vector() { + let l = layout(1, 4, 1, 8, Version::Psd); + let mut v = vec![10, 12, 11, 255]; + predict(&mut v, &l).unwrap(); + assert_eq!(v, vec![10, 2, 255, 244]); + unpredict(&mut v, &l).unwrap(); + assert_eq!(v, vec![10, 12, 11, 255]); +} + +#[test] +fn prediction_16bit_known_vector() { + let l = layout(1, 3, 1, 16, Version::Psd); + let mut v = vec![0x01, 0x00, 0x01, 0x05, 0x00, 0x00]; + predict(&mut v, &l).unwrap(); + assert_eq!(v, vec![0x01, 0x00, 0x00, 0x05, 0xfe, 0xfb]); + unpredict(&mut v, &l).unwrap(); + assert_eq!(v, vec![0x01, 0x00, 0x01, 0x05, 0x00, 0x00]); +} + +#[test] +fn prediction_32bit_plane_shuffle() { + // Two samples: AABBCCDD and 11223344 → planes [AA,11][BB,22][CC,33][DD,44] + let l = layout(1, 2, 1, 32, Version::Psd); + let orig = vec![0xAA, 0xBB, 0xCC, 0xDD, 0x11, 0x22, 0x33, 0x44]; + let mut v = orig.clone(); + predict(&mut v, &l).unwrap(); + let planes = [0xAAu8, 0x11, 0xBB, 0x22, 0xCC, 0x33, 0xDD, 0x44]; + let mut expect = planes; + for i in (1..8).rev() { + expect[i] = expect[i].wrapping_sub(expect[i - 1]); + } + assert_eq!(v, expect); + unpredict(&mut v, &l).unwrap(); + assert_eq!(v, orig); +} + +#[test] +fn prediction_32bit_floats_roundtrip() { + let l = layout(1, 5, 2, 32, Version::Psd); + let mut v = Vec::new(); + for i in 0..10 { + v.extend_from_slice(&(i as f32 * 0.37 - 1.0).to_be_bytes()); + } + let enc = encode_planes(Compression::ZipPrediction, &v, &l).unwrap(); + assert_eq!(decode_planes(Compression::ZipPrediction, &enc, &l).unwrap(), v); +} + +#[test] +fn zip_bomb_is_bounded() { + let big = zip_compress(&vec![0u8; 1 << 20]); + let out = zip_decompress(&big, 10).unwrap(); + assert_eq!(out.len(), 10); +} + +#[test] +fn zip_garbage_errors() { + assert!(zip_decompress(&[1, 2, 3, 4], 4).is_err()); +} diff --git a/crates/psd/src/layer.rs b/crates/psd/src/layer.rs index 5b11411dfb..1b5c241191 100644 --- a/crates/psd/src/layer.rs +++ b/crates/psd/src/layer.rs @@ -778,384 +778,4 @@ impl LayerInfo { } #[cfg(test)] -mod tests { - use super::*; - - fn sample_record(version: Version) -> LayerRecord { - let rect = Rect::from_xywh(-3, 2, 5, 4); - let px: Vec = (0..20).collect(); - let mut channels = Vec::new(); - for (id, comp) in [(-1, Compression::Rle), (0, Compression::Raw), (1, Compression::Zip), (2, Compression::ZipPrediction)] { - channels.push(ChannelData::encode(id, comp, &px, 5, 4, 8, version).unwrap()); - } - let mask = LayerMask::new(Rect::from_xywh(0, 0, 2, 2), 255, LayerMask::FLAG_RELATIVE); - channels.push(ChannelData::encode(-2, Compression::Rle, &[1, 2, 3, 4], 2, 2, 8, version).unwrap()); - LayerRecord { - rect, - channels, - blend_mode: BlendMode::Screen, - opacity: 200, - clipping: 1, - flags: LayerFlags(LayerFlags::HIDDEN), - mask: MaskData::Mask(mask), - blending_ranges: BlendingRanges::full(3), - name: b"abc".to_vec(), - blocks: vec![TaggedBlock::unicode_name("\u{e4}bc"), TaggedBlock::layer_id(5)], - ..Default::default() - } - } - - fn rt(info: &LayerInfo, version: Version) -> Vec { - let mut out = Vec::new(); - info.write_body(&mut out, version).unwrap(); - let back = LayerInfo::read_body(&out, version).unwrap(); - assert_eq!(&back, info); - let mut again = Vec::new(); - back.write_body(&mut again, version).unwrap(); - assert_eq!(again, out); - out - } - - #[test] - fn empty_layer_info() { - let out = rt(&LayerInfo::default(), Version::Psd); - assert_eq!(out, vec![0, 0]); - } - - #[test] - fn record_roundtrip_psd_psb() { - for v in [Version::Psd, Version::Psb] { - let info = LayerInfo { merged_alpha: true, layers: vec![sample_record(v), LayerRecord::default()], padding: None }; - let out = rt(&info, v); - assert_eq!(out.len() % 2, 0); - assert_eq!(&out[..2], &(-2i16).to_be_bytes()); - } - } - - #[test] - fn psb_channel_lengths_are_8_bytes() { - let mut rec = LayerRecord::default(); - rec.channels.push(ChannelData { id: 0, compression: Some(Compression::Raw), data: vec![] }); - let info = LayerInfo { layers: vec![rec], ..Default::default() }; - let psd = rt(&info, Version::Psd); - let psb = rt(&info, Version::Psb); - assert_eq!(psb.len(), psd.len() + 4); - } - - #[test] - fn channel_decode_via_record() { - let rec = sample_record(Version::Psd); - let px: Vec = (0..20).collect(); - for id in [-1, 0, 1, 2] { - assert_eq!(rec.decode_channel(id, 8, Version::Psd).unwrap(), px); - } - assert_eq!(rec.decode_channel(-2, 8, Version::Psd).unwrap(), vec![1, 2, 3, 4]); - assert!(rec.decode_channel(7, 8, Version::Psd).is_err()); - } - - #[test] - fn record_accessors() { - let rec = sample_record(Version::Psd); - assert_eq!(rec.name(), "\u{e4}bc"); - assert!(!rec.is_visible()); - assert_eq!(rec.layer_id(), Some(5)); - assert_eq!(rec.fill_opacity(), 255); - assert_eq!(rec.section_type(), SectionType::Other); - assert!(rec.layer_mask().is_some()); - assert_eq!(rec.channel_rect(-2), Rect::from_xywh(0, 0, 2, 2)); - assert_eq!(rec.channel_rect(0), rec.rect); - let mut plain = LayerRecord { name: b"legacy".to_vec(), ..Default::default() }; - assert_eq!(plain.name(), "legacy"); - plain.blocks.push(TaggedBlock::fill_opacity(10)); - assert_eq!(plain.fill_opacity(), 10); - plain.block_mut(b"iOpa").unwrap().data[0] = 11; - assert_eq!(plain.fill_opacity(), 11); - } - - #[test] - fn mask_variants_roundtrip() { - let base = LayerMask::new(Rect::from_xywh(1, 2, 3, 4), 0, 0); - let with_real = LayerMask { real: Some(RealMask { flags: 1, background: 255, rect: Rect::from_xywh(0, 0, 9, 9) }), trailing: vec![], ..base.clone() }; - let with_params = LayerMask { - flags: LayerMask::FLAG_PARAMETERS, - parameters: Some(MaskParameters { - flags: 0b1111, - user_density: Some(128), - user_feather: Some(2.5), - vector_density: Some(64), - vector_feather: Some(0.5), - }), - real: Some(RealMask::default()), - trailing: vec![0, 0], - ..base.clone() - }; - let partial_params = LayerMask { - flags: LayerMask::FLAG_PARAMETERS, - parameters: Some(MaskParameters { flags: 0b0010, user_feather: Some(1.0), ..Default::default() }), - trailing: vec![], - ..base.clone() - }; - for m in [base, with_real, with_params, partial_params] { - let mut out = Vec::new(); - m.write(&mut out); - assert_eq!(LayerMask::parse(&out).unwrap(), m); - } - } - - /// Photoshop stores the real-mask fields before the mask parameters (psd-tools - /// mask-density-layervectormask.psd): user + vector mask with both densities set. - #[test] - fn real_mask_before_parameters_photoshop_layout() { - let mut d = Vec::new(); - Rect::from_xywh(15, -1, 18, 10).write(&mut d); - d.extend([0, LayerMask::FLAG_PARAMETERS | 8]); - d.extend([0, 255]); - Rect::from_xywh(0, 0, 32, 8).write(&mut d); - d.extend([0b0101, 64, 64, 0]); - let m = LayerMask::parse(&d).unwrap(); - assert_eq!(m.real.map(|r| r.rect), Some(Rect::from_xywh(0, 0, 32, 8))); - assert_eq!(m.real.map(|r| r.background), Some(255)); - let p = m.parameters.unwrap(); - assert_eq!((p.user_density, p.vector_density), (Some(64), Some(64))); - assert_eq!(m.trailing, vec![0]); - assert!(m.real_first); - let mut out = Vec::new(); - m.write(&mut out); - assert_eq!(out, d); - } - - /// A density-only record in the spec's order (#949): the parameter flags byte at 18 says one - /// value byte, so the spec's reading excludes the 38-byte length only if the real mask is - /// ignored, while byte 36 (inside the real rectangle's `right`) is 0 and makes Photoshop's - /// reading fit too. Photoshop's reading puts the density (64) where a 0-or-255 background - /// belongs, so the spec's order wins and the density survives. - #[test] - fn density_only_spec_layout_is_not_read_as_photoshop_order() { - for (density, right) in [(64u8, 1u32), (200, 1), (64, 300), (1, 7)] { - let mut d = Vec::new(); - Rect::from_xywh(0, 0, 1, 1).write(&mut d); - d.extend([255, LayerMask::FLAG_PARAMETERS]); - d.extend([0b0001, density]); - d.extend([0, 0]); - Rect::from_xywh(0, 0, right, 1).write(&mut d); - let m = LayerMask::parse(&d).unwrap(); - assert!(!m.real_first, "density {density}, right {right}: {m:?}"); - assert_eq!(m.parameters.unwrap().user_density, Some(density)); - assert_eq!(m.real, Some(RealMask { flags: 0, background: 0, rect: Rect::from_xywh(0, 0, right, 1) })); - assert!(m.trailing.is_empty()); - let mut out = Vec::new(); - m.write(&mut out); - assert_eq!(out, d); - } - // Photoshop's order with the same lengths still reads as Photoshop's order. - let mut d = Vec::new(); - Rect::from_xywh(0, 0, 1, 1).write(&mut d); - d.extend([255, LayerMask::FLAG_PARAMETERS]); - d.extend([0, 255]); - Rect::from_xywh(0, 0, 1, 1).write(&mut d); - d.extend([0b0001, 64]); - let m = LayerMask::parse(&d).unwrap(); - assert!(m.real_first, "{m:?}"); - assert_eq!(m.parameters.unwrap().user_density, Some(64)); - assert_eq!(m.real.map(|r| r.background), Some(255)); - let mut out = Vec::new(); - m.write(&mut out); - assert_eq!(out, d); - } - - /// The spec's order (parameters, then real fields) still parses and stays byte-stable. - #[test] - fn real_mask_after_parameters_spec_layout() { - let mut d = Vec::new(); - Rect::from_xywh(1, 2, 3, 4).write(&mut d); - d.extend([255, LayerMask::FLAG_PARAMETERS]); - d.extend([0b0011, 200]); - d.extend(1.5f64.to_be_bytes()); - d.extend([0, 255]); - Rect::from_xywh(0, 0, 3, 3).write(&mut d); - let m = LayerMask::parse(&d).unwrap(); - assert!(!m.real_first); - assert_eq!(m.real.map(|r| r.rect), Some(Rect::from_xywh(0, 0, 3, 3))); - assert_eq!(m.parameters.unwrap().user_feather, Some(1.5)); - let mut out = Vec::new(); - m.write(&mut out); - assert_eq!(out, d); - // Parameters alone (no real mask) keep reading in the spec's order. - let mut d = Vec::new(); - Rect::from_xywh(1, 2, 3, 4).write(&mut d); - d.extend([255, LayerMask::FLAG_PARAMETERS, 0b1010]); - d.extend(1.0f64.to_be_bytes()); - d.extend(2.0f64.to_be_bytes()); - d.extend([0, 0]); - let m = LayerMask::parse(&d).unwrap(); - assert_eq!(m.real, None); - assert_eq!(m.parameters.map(|p| (p.user_feather, p.vector_feather)), Some((Some(1.0), Some(2.0)))); - } - - #[test] - fn mask_sizes() { - let mut out = Vec::new(); - LayerMask::new(Rect::default(), 0, 0).write(&mut out); - assert_eq!(out.len(), 20); - let m = LayerMask { real: Some(RealMask::default()), trailing: vec![], ..LayerMask::new(Rect::default(), 0, 0) }; - let mut out = Vec::new(); - m.write(&mut out); - assert_eq!(out.len(), 36); - } - - #[test] - fn short_mask_kept_raw() { - let mut rec = LayerRecord { mask: MaskData::Raw(vec![1, 2, 3]), ..Default::default() }; - rec.channels.clear(); - let info = LayerInfo { layers: vec![rec], ..Default::default() }; - rt(&info, Version::Psd); - } - - #[test] - fn flags_helpers() { - let mut f = LayerFlags::default(); - f.set_hidden(true); - f.set_transparency_protected(true); - assert!(f.hidden() && f.transparency_protected()); - f.set_pixel_data_irrelevant(true); - assert!(f.bit4_useful() && f.pixel_data_irrelevant()); - f.set_hidden(false); - assert!(!f.hidden()); - } - - #[test] - fn blending_ranges_parse() { - let br = BlendingRanges::full(3); - assert_eq!(br.data.len(), 32); - let r = br.ranges(); - assert_eq!(r.len(), 4); - assert_eq!(r[0].source, [0, 0, 255, 255]); - } - - #[test] - fn rect_helpers() { - let r = Rect::from_xywh(-5, -6, 10, 3); - assert_eq!((r.width(), r.height()), (10, 3)); - assert_eq!(r.size().unwrap(), (10, 3)); - assert!(!r.is_empty()); - let bad = Rect { top: 5, left: 0, bottom: 0, right: 1 }; - assert!(bad.size().is_err()); - assert!(bad.is_empty()); - let huge = Rect { top: 0, left: i32::MIN, bottom: 1, right: i32::MAX }; - assert!(huge.size().is_err()); - } - - #[test] - fn truncation_errors() { - let info = LayerInfo { layers: vec![sample_record(Version::Psd)], ..Default::default() }; - let mut out = Vec::new(); - info.write_body(&mut out, Version::Psd).unwrap(); - // The final byte may be the (optional) even padding; stop before it. - for cut in 0..out.len() - 1 { - assert!(LayerInfo::read_body(&out[..cut], Version::Psd).is_err(), "cut {cut}"); - } - } - - #[test] - fn bad_blend_signature() { - let info = LayerInfo { layers: vec![LayerRecord::default()], ..Default::default() }; - let mut out = Vec::new(); - info.write_body(&mut out, Version::Psd).unwrap(); - // count(2) + rect(16) + nch(2) = 20 → signature - out[20] = b'X'; - assert!(matches!(LayerInfo::read_body(&out, Version::Psd), Err(PsdError::InvalidSignature { .. }))); - } - - #[test] - fn too_many_layers_rejected() { - let out = 1000i16.to_be_bytes(); - assert!(LayerInfo::read_body(&out, Version::Psd).is_err()); - } - - #[test] - fn zero_length_channel() { - let mut rec = LayerRecord::default(); - rec.channels.push(ChannelData { id: 0, compression: None, data: vec![] }); - let info = LayerInfo { layers: vec![rec], ..Default::default() }; - rt(&info, Version::Psd); - assert_eq!(info.layers[0].decode_channel(0, 8, Version::Psd).unwrap(), Vec::::new()); - } - - /// The computed length matches the bytes written for every mask form, long names, custom block - /// padding, long-length blocks and trailing bytes. - #[test] - fn unpadded_len_matches_the_written_body() { - for version in [Version::Psd, Version::Psb] { - let mut layers = vec![sample_record(version), LayerRecord::default()]; - for (params, real, real_first) in [(true, true, true), (true, true, false), (true, false, true), (false, true, true)] { - let mut mask = LayerMask::new(Rect::from_xywh(1, 2, 3, 4), 0, LayerMask::FLAG_PARAMETERS); - mask.parameters = params.then_some(MaskParameters { - flags: 0x0f, - user_density: Some(1), - user_feather: Some(2.5), - vector_density: Some(3), - vector_feather: None, - }); - mask.real = real.then_some(RealMask { flags: 0, background: 255, rect: Rect::from_xywh(0, 0, 1, 1) }); - mask.real_first = real_first; - mask.trailing = vec![0; 3]; - let mut rec = sample_record(version); - rec.mask = MaskData::Mask(mask); - rec.name = vec![b'n'; 300]; - rec.blocks.push(TaggedBlock { signature: *b"8BIM", key: *b"lsct", data: vec![1; 5], padding: Some(vec![0; 3]) }); - rec.blocks.push(TaggedBlock { signature: *b"8BIM", key: *b"Lr16", data: vec![2; 7], padding: None }); - rec.extra_trailing = vec![9; 2]; - layers.push(rec); - } - layers.push(LayerRecord { mask: MaskData::Raw(vec![5; 11]), name: b"ab".to_vec(), ..Default::default() }); - let info = LayerInfo { layers, ..Default::default() }; - let mut out = Vec::new(); - info.write_unpadded(&mut out, version).unwrap(); - assert_eq!(info.unpadded_len(version).unwrap(), out.len() as u64, "{version:?}"); - } - } - - /// Padding without cloning the layers writes the same bytes as `pad_to` on a clone, and the - /// channel data length hint is exact. - #[test] - fn unpadded_write_matches_pad_to_on_a_clone() { - use crate::{ColorMode, Compression, testgen}; - for version in [Version::Psd, Version::Psb] { - for depth in [8u16, 16, 32] { - for compression in [Compression::Raw, Compression::Rle] { - let file = testgen::layered(version, ColorMode::Rgb, depth, compression); - let mut info = file.layer_info.clone().unwrap(); - for align in [1u64, 2, 4, 8] { - let mut cloned = info.clone(); - cloned.pad_to(version, align).unwrap(); - let mut want = Vec::new(); - cloned.write_body(&mut want, version).unwrap(); - let pad = info.pad_len(version, align).unwrap(); - let mut got = Vec::new(); - info.write_unpadded(&mut got, version).unwrap(); - assert!(got.len() >= info.channel_data_len()); - got.resize(got.len() + pad, 0); - assert_eq!(got, want, "{version:?} {depth} {compression:?} align {align}"); - } - info.padding = Some(vec![7, 7]); - let mut with_padding = Vec::new(); - info.write_body(&mut with_padding, version).unwrap(); - assert!(with_padding.ends_with(&[7, 7])); - } - } - } - } - - #[test] - fn nondefault_padding_kept() { - let info = LayerInfo { padding: Some(vec![0, 0]), ..Default::default() }; - let out = rt(&info, Version::Psd); - assert_eq!(out.len(), 4); - } - - #[test] - fn unknown_blend_and_blocks_passthrough() { - let rec = LayerRecord { blend_mode: BlendMode::Unknown(*b"wxyz"), blocks: vec![TaggedBlock::new(*b"Zzzz", vec![1, 2, 3, 4, 5])], ..Default::default() }; - rt(&LayerInfo { layers: vec![rec], ..Default::default() }, Version::Psd); - } -} +mod tests; diff --git a/crates/psd/src/layer/tests.rs b/crates/psd/src/layer/tests.rs new file mode 100644 index 0000000000..a5ad06efbb --- /dev/null +++ b/crates/psd/src/layer/tests.rs @@ -0,0 +1,374 @@ +use super::*; + +fn sample_record(version: Version) -> LayerRecord { + let rect = Rect::from_xywh(-3, 2, 5, 4); + let px: Vec = (0..20).collect(); + let mut channels = Vec::new(); + for (id, comp) in [(-1, Compression::Rle), (0, Compression::Raw), (1, Compression::Zip), (2, Compression::ZipPrediction)] { + channels.push(ChannelData::encode(id, comp, &px, 5, 4, 8, version).unwrap()); + } + let mask = LayerMask::new(Rect::from_xywh(0, 0, 2, 2), 255, LayerMask::FLAG_RELATIVE); + channels.push(ChannelData::encode(-2, Compression::Rle, &[1, 2, 3, 4], 2, 2, 8, version).unwrap()); + LayerRecord { + rect, + channels, + blend_mode: BlendMode::Screen, + opacity: 200, + clipping: 1, + flags: LayerFlags(LayerFlags::HIDDEN), + mask: MaskData::Mask(mask), + blending_ranges: BlendingRanges::full(3), + name: b"abc".to_vec(), + blocks: vec![TaggedBlock::unicode_name("\u{e4}bc"), TaggedBlock::layer_id(5)], + ..Default::default() + } +} + +fn rt(info: &LayerInfo, version: Version) -> Vec { + let mut out = Vec::new(); + info.write_body(&mut out, version).unwrap(); + let back = LayerInfo::read_body(&out, version).unwrap(); + assert_eq!(&back, info); + let mut again = Vec::new(); + back.write_body(&mut again, version).unwrap(); + assert_eq!(again, out); + out +} + +#[test] +fn empty_layer_info() { + let out = rt(&LayerInfo::default(), Version::Psd); + assert_eq!(out, vec![0, 0]); +} + +#[test] +fn record_roundtrip_psd_psb() { + for v in [Version::Psd, Version::Psb] { + let info = LayerInfo { merged_alpha: true, layers: vec![sample_record(v), LayerRecord::default()], padding: None }; + let out = rt(&info, v); + assert_eq!(out.len() % 2, 0); + assert_eq!(&out[..2], &(-2i16).to_be_bytes()); + } +} + +#[test] +fn psb_channel_lengths_are_8_bytes() { + let mut rec = LayerRecord::default(); + rec.channels.push(ChannelData { id: 0, compression: Some(Compression::Raw), data: vec![] }); + let info = LayerInfo { layers: vec![rec], ..Default::default() }; + let psd = rt(&info, Version::Psd); + let psb = rt(&info, Version::Psb); + assert_eq!(psb.len(), psd.len() + 4); +} + +#[test] +fn channel_decode_via_record() { + let rec = sample_record(Version::Psd); + let px: Vec = (0..20).collect(); + for id in [-1, 0, 1, 2] { + assert_eq!(rec.decode_channel(id, 8, Version::Psd).unwrap(), px); + } + assert_eq!(rec.decode_channel(-2, 8, Version::Psd).unwrap(), vec![1, 2, 3, 4]); + assert!(rec.decode_channel(7, 8, Version::Psd).is_err()); +} + +#[test] +fn record_accessors() { + let rec = sample_record(Version::Psd); + assert_eq!(rec.name(), "\u{e4}bc"); + assert!(!rec.is_visible()); + assert_eq!(rec.layer_id(), Some(5)); + assert_eq!(rec.fill_opacity(), 255); + assert_eq!(rec.section_type(), SectionType::Other); + assert!(rec.layer_mask().is_some()); + assert_eq!(rec.channel_rect(-2), Rect::from_xywh(0, 0, 2, 2)); + assert_eq!(rec.channel_rect(0), rec.rect); + let mut plain = LayerRecord { name: b"legacy".to_vec(), ..Default::default() }; + assert_eq!(plain.name(), "legacy"); + plain.blocks.push(TaggedBlock::fill_opacity(10)); + assert_eq!(plain.fill_opacity(), 10); + plain.block_mut(b"iOpa").unwrap().data[0] = 11; + assert_eq!(plain.fill_opacity(), 11); +} + +#[test] +fn mask_variants_roundtrip() { + let base = LayerMask::new(Rect::from_xywh(1, 2, 3, 4), 0, 0); + let with_real = LayerMask { real: Some(RealMask { flags: 1, background: 255, rect: Rect::from_xywh(0, 0, 9, 9) }), trailing: vec![], ..base.clone() }; + let with_params = LayerMask { + flags: LayerMask::FLAG_PARAMETERS, + parameters: Some(MaskParameters { + flags: 0b1111, + user_density: Some(128), + user_feather: Some(2.5), + vector_density: Some(64), + vector_feather: Some(0.5), + }), + real: Some(RealMask::default()), + trailing: vec![0, 0], + ..base.clone() + }; + let partial_params = LayerMask { + flags: LayerMask::FLAG_PARAMETERS, + parameters: Some(MaskParameters { flags: 0b0010, user_feather: Some(1.0), ..Default::default() }), + trailing: vec![], + ..base.clone() + }; + for m in [base, with_real, with_params, partial_params] { + let mut out = Vec::new(); + m.write(&mut out); + assert_eq!(LayerMask::parse(&out).unwrap(), m); + } +} + +/// Photoshop stores the real-mask fields before the mask parameters (psd-tools +/// mask-density-layervectormask.psd): user + vector mask with both densities set. +#[test] +fn real_mask_before_parameters_photoshop_layout() { + let mut d = Vec::new(); + Rect::from_xywh(15, -1, 18, 10).write(&mut d); + d.extend([0, LayerMask::FLAG_PARAMETERS | 8]); + d.extend([0, 255]); + Rect::from_xywh(0, 0, 32, 8).write(&mut d); + d.extend([0b0101, 64, 64, 0]); + let m = LayerMask::parse(&d).unwrap(); + assert_eq!(m.real.map(|r| r.rect), Some(Rect::from_xywh(0, 0, 32, 8))); + assert_eq!(m.real.map(|r| r.background), Some(255)); + let p = m.parameters.unwrap(); + assert_eq!((p.user_density, p.vector_density), (Some(64), Some(64))); + assert_eq!(m.trailing, vec![0]); + assert!(m.real_first); + let mut out = Vec::new(); + m.write(&mut out); + assert_eq!(out, d); +} + +/// A density-only record in the spec's order (#949): the parameter flags byte at 18 says one +/// value byte, so the spec's reading excludes the 38-byte length only if the real mask is +/// ignored, while byte 36 (inside the real rectangle's `right`) is 0 and makes Photoshop's +/// reading fit too. Photoshop's reading puts the density (64) where a 0-or-255 background +/// belongs, so the spec's order wins and the density survives. +#[test] +fn density_only_spec_layout_is_not_read_as_photoshop_order() { + for (density, right) in [(64u8, 1u32), (200, 1), (64, 300), (1, 7)] { + let mut d = Vec::new(); + Rect::from_xywh(0, 0, 1, 1).write(&mut d); + d.extend([255, LayerMask::FLAG_PARAMETERS]); + d.extend([0b0001, density]); + d.extend([0, 0]); + Rect::from_xywh(0, 0, right, 1).write(&mut d); + let m = LayerMask::parse(&d).unwrap(); + assert!(!m.real_first, "density {density}, right {right}: {m:?}"); + assert_eq!(m.parameters.unwrap().user_density, Some(density)); + assert_eq!(m.real, Some(RealMask { flags: 0, background: 0, rect: Rect::from_xywh(0, 0, right, 1) })); + assert!(m.trailing.is_empty()); + let mut out = Vec::new(); + m.write(&mut out); + assert_eq!(out, d); + } + // Photoshop's order with the same lengths still reads as Photoshop's order. + let mut d = Vec::new(); + Rect::from_xywh(0, 0, 1, 1).write(&mut d); + d.extend([255, LayerMask::FLAG_PARAMETERS]); + d.extend([0, 255]); + Rect::from_xywh(0, 0, 1, 1).write(&mut d); + d.extend([0b0001, 64]); + let m = LayerMask::parse(&d).unwrap(); + assert!(m.real_first, "{m:?}"); + assert_eq!(m.parameters.unwrap().user_density, Some(64)); + assert_eq!(m.real.map(|r| r.background), Some(255)); + let mut out = Vec::new(); + m.write(&mut out); + assert_eq!(out, d); +} + +/// The spec's order (parameters, then real fields) still parses and stays byte-stable. +#[test] +fn real_mask_after_parameters_spec_layout() { + let mut d = Vec::new(); + Rect::from_xywh(1, 2, 3, 4).write(&mut d); + d.extend([255, LayerMask::FLAG_PARAMETERS]); + d.extend([0b0011, 200]); + d.extend(1.5f64.to_be_bytes()); + d.extend([0, 255]); + Rect::from_xywh(0, 0, 3, 3).write(&mut d); + let m = LayerMask::parse(&d).unwrap(); + assert!(!m.real_first); + assert_eq!(m.real.map(|r| r.rect), Some(Rect::from_xywh(0, 0, 3, 3))); + assert_eq!(m.parameters.unwrap().user_feather, Some(1.5)); + let mut out = Vec::new(); + m.write(&mut out); + assert_eq!(out, d); + // Parameters alone (no real mask) keep reading in the spec's order. + let mut d = Vec::new(); + Rect::from_xywh(1, 2, 3, 4).write(&mut d); + d.extend([255, LayerMask::FLAG_PARAMETERS, 0b1010]); + d.extend(1.0f64.to_be_bytes()); + d.extend(2.0f64.to_be_bytes()); + d.extend([0, 0]); + let m = LayerMask::parse(&d).unwrap(); + assert_eq!(m.real, None); + assert_eq!(m.parameters.map(|p| (p.user_feather, p.vector_feather)), Some((Some(1.0), Some(2.0)))); +} + +#[test] +fn mask_sizes() { + let mut out = Vec::new(); + LayerMask::new(Rect::default(), 0, 0).write(&mut out); + assert_eq!(out.len(), 20); + let m = LayerMask { real: Some(RealMask::default()), trailing: vec![], ..LayerMask::new(Rect::default(), 0, 0) }; + let mut out = Vec::new(); + m.write(&mut out); + assert_eq!(out.len(), 36); +} + +#[test] +fn short_mask_kept_raw() { + let mut rec = LayerRecord { mask: MaskData::Raw(vec![1, 2, 3]), ..Default::default() }; + rec.channels.clear(); + let info = LayerInfo { layers: vec![rec], ..Default::default() }; + rt(&info, Version::Psd); +} + +#[test] +fn flags_helpers() { + let mut f = LayerFlags::default(); + f.set_hidden(true); + f.set_transparency_protected(true); + assert!(f.hidden() && f.transparency_protected()); + f.set_pixel_data_irrelevant(true); + assert!(f.bit4_useful() && f.pixel_data_irrelevant()); + f.set_hidden(false); + assert!(!f.hidden()); +} + +#[test] +fn blending_ranges_parse() { + let br = BlendingRanges::full(3); + assert_eq!(br.data.len(), 32); + let r = br.ranges(); + assert_eq!(r.len(), 4); + assert_eq!(r[0].source, [0, 0, 255, 255]); +} + +#[test] +fn rect_helpers() { + let r = Rect::from_xywh(-5, -6, 10, 3); + assert_eq!((r.width(), r.height()), (10, 3)); + assert_eq!(r.size().unwrap(), (10, 3)); + assert!(!r.is_empty()); + let bad = Rect { top: 5, left: 0, bottom: 0, right: 1 }; + assert!(bad.size().is_err()); + assert!(bad.is_empty()); + let huge = Rect { top: 0, left: i32::MIN, bottom: 1, right: i32::MAX }; + assert!(huge.size().is_err()); +} + +#[test] +fn truncation_errors() { + let info = LayerInfo { layers: vec![sample_record(Version::Psd)], ..Default::default() }; + let mut out = Vec::new(); + info.write_body(&mut out, Version::Psd).unwrap(); + // The final byte may be the (optional) even padding; stop before it. + for cut in 0..out.len() - 1 { + assert!(LayerInfo::read_body(&out[..cut], Version::Psd).is_err(), "cut {cut}"); + } +} + +#[test] +fn bad_blend_signature() { + let info = LayerInfo { layers: vec![LayerRecord::default()], ..Default::default() }; + let mut out = Vec::new(); + info.write_body(&mut out, Version::Psd).unwrap(); + // count(2) + rect(16) + nch(2) = 20 → signature + out[20] = b'X'; + assert!(matches!(LayerInfo::read_body(&out, Version::Psd), Err(PsdError::InvalidSignature { .. }))); +} + +#[test] +fn too_many_layers_rejected() { + let out = 1000i16.to_be_bytes(); + assert!(LayerInfo::read_body(&out, Version::Psd).is_err()); +} + +#[test] +fn zero_length_channel() { + let mut rec = LayerRecord::default(); + rec.channels.push(ChannelData { id: 0, compression: None, data: vec![] }); + let info = LayerInfo { layers: vec![rec], ..Default::default() }; + rt(&info, Version::Psd); + assert_eq!(info.layers[0].decode_channel(0, 8, Version::Psd).unwrap(), Vec::::new()); +} + +/// The computed length matches the bytes written for every mask form, long names, custom block +/// padding, long-length blocks and trailing bytes. +#[test] +fn unpadded_len_matches_the_written_body() { + for version in [Version::Psd, Version::Psb] { + let mut layers = vec![sample_record(version), LayerRecord::default()]; + for (params, real, real_first) in [(true, true, true), (true, true, false), (true, false, true), (false, true, true)] { + let mut mask = LayerMask::new(Rect::from_xywh(1, 2, 3, 4), 0, LayerMask::FLAG_PARAMETERS); + mask.parameters = + params.then_some(MaskParameters { flags: 0x0f, user_density: Some(1), user_feather: Some(2.5), vector_density: Some(3), vector_feather: None }); + mask.real = real.then_some(RealMask { flags: 0, background: 255, rect: Rect::from_xywh(0, 0, 1, 1) }); + mask.real_first = real_first; + mask.trailing = vec![0; 3]; + let mut rec = sample_record(version); + rec.mask = MaskData::Mask(mask); + rec.name = vec![b'n'; 300]; + rec.blocks.push(TaggedBlock { signature: *b"8BIM", key: *b"lsct", data: vec![1; 5], padding: Some(vec![0; 3]) }); + rec.blocks.push(TaggedBlock { signature: *b"8BIM", key: *b"Lr16", data: vec![2; 7], padding: None }); + rec.extra_trailing = vec![9; 2]; + layers.push(rec); + } + layers.push(LayerRecord { mask: MaskData::Raw(vec![5; 11]), name: b"ab".to_vec(), ..Default::default() }); + let info = LayerInfo { layers, ..Default::default() }; + let mut out = Vec::new(); + info.write_unpadded(&mut out, version).unwrap(); + assert_eq!(info.unpadded_len(version).unwrap(), out.len() as u64, "{version:?}"); + } +} + +/// Padding without cloning the layers writes the same bytes as `pad_to` on a clone, and the +/// channel data length hint is exact. +#[test] +fn unpadded_write_matches_pad_to_on_a_clone() { + use crate::{ColorMode, Compression, testgen}; + for version in [Version::Psd, Version::Psb] { + for depth in [8u16, 16, 32] { + for compression in [Compression::Raw, Compression::Rle] { + let file = testgen::layered(version, ColorMode::Rgb, depth, compression); + let mut info = file.layer_info.clone().unwrap(); + for align in [1u64, 2, 4, 8] { + let mut cloned = info.clone(); + cloned.pad_to(version, align).unwrap(); + let mut want = Vec::new(); + cloned.write_body(&mut want, version).unwrap(); + let pad = info.pad_len(version, align).unwrap(); + let mut got = Vec::new(); + info.write_unpadded(&mut got, version).unwrap(); + assert!(got.len() >= info.channel_data_len()); + got.resize(got.len() + pad, 0); + assert_eq!(got, want, "{version:?} {depth} {compression:?} align {align}"); + } + info.padding = Some(vec![7, 7]); + let mut with_padding = Vec::new(); + info.write_body(&mut with_padding, version).unwrap(); + assert!(with_padding.ends_with(&[7, 7])); + } + } + } +} + +#[test] +fn nondefault_padding_kept() { + let info = LayerInfo { padding: Some(vec![0, 0]), ..Default::default() }; + let out = rt(&info, Version::Psd); + assert_eq!(out.len(), 4); +} + +#[test] +fn unknown_blend_and_blocks_passthrough() { + let rec = LayerRecord { blend_mode: BlendMode::Unknown(*b"wxyz"), blocks: vec![TaggedBlock::new(*b"Zzzz", vec![1, 2, 3, 4, 5])], ..Default::default() }; + rt(&LayerInfo { layers: vec![rec], ..Default::default() }, Version::Psd); +} diff --git a/crates/psd/src/patterns.rs b/crates/psd/src/patterns.rs index 85bf285db9..af4afea0a2 100644 --- a/crates/psd/src/patterns.rs +++ b/crates/psd/src/patterns.rs @@ -575,357 +575,4 @@ pub fn write_pat_file(patterns: &[PsdPattern]) -> Result> { } #[cfg(test)] -mod tests { - use super::*; - - fn pat(depth: u16, alpha: bool) -> PsdPattern { - let (w, h) = (5u32, 3u32); - let bpp = usize::from(depth / 8); - let plane = |s: u8| (0..w as usize * h as usize * bpp).map(|i| (i as u8).wrapping_mul(7).wrapping_add(s)).collect::>(); - PsdPattern { - mode: 3, - width: w, - height: h, - name: "Test ✓".into(), - id: "0bd2d3ba-1234-11d4-8f8f-aabbccddeeff".into(), - palette: None, - depth, - channels: vec![plane(1), plane(2), plane(3)], - alpha: alpha.then(|| plane(9)), - } - } - - /// #9318 review: a name the reader refuses (more than 65,536 UTF-16 units with its NUL) is - /// refused on write, so a saved library can't become a file that loads nothing. - #[test] - fn a_name_the_reader_refuses_is_refused_on_write() { - let long = PsdPattern { name: "a".repeat(65_536), ..pat(8, false) }; - assert!(matches!(write_pat_file(&[long]), Err(PsdError::LimitExceeded(_)))); - let longest = PsdPattern { name: "a".repeat(65_535), ..pat(8, false) }; - assert_eq!(parse_pat_file(&write_pat_file(std::slice::from_ref(&longest)).unwrap()).unwrap(), [longest]); - } - - /// #9318 review: more patterns than a `.pat` holds are refused on write, and a file claiming - /// more is refused on read rather than silently cut to the first 100,000. - #[test] - fn more_patterns_than_a_pat_file_holds_are_refused() { - let many = vec![pat(8, false); MAX_PAT_PATTERNS + 1]; - assert!(matches!(write_pat_file(&many), Err(PsdError::LimitExceeded(_)))); - let mut header = b"8BPT".to_vec(); - header.extend_from_slice(&1u16.to_be_bytes()); - header.extend_from_slice(&(MAX_PAT_PATTERNS as u32 + 1).to_be_bytes()); - assert!(matches!(parse_pat_file(&header), Err(PsdError::LimitExceeded(_)))); - } - - #[test] - fn block_and_pat_file_round_trip_at_every_depth() { - for depth in [8, 16, 32] { - for alpha in [false, true] { - let ps = vec![pat(depth, alpha), PsdPattern { name: "Second".into(), ..pat(depth, false) }]; - let blk = write_pattern_block(&ps).unwrap(); - assert_eq!(blk.len() % 4, 0); - assert_eq!(parse_pattern_block(&blk).unwrap(), ps); - let f = write_pat_file(&ps).unwrap(); - assert_eq!(parse_pat_file(&f).unwrap(), ps); - // Re-serialising is byte-stable. - assert_eq!(write_pattern_block(&parse_pattern_block(&blk).unwrap()).unwrap(), blk); - } - } - } - - /// Offsets of the virtual memory arrays of a one-pattern block (each at its "written" flag), - /// with whether each is written, and the end of the array list. - fn vma_slots(block: &[u8], p: &PsdPattern) -> (Vec<(usize, bool)>, usize) { - let rect = pattern_vma_rect_offset(4, p); - let end = rect + u32::from_be_bytes(block[rect - 4..rect].try_into().unwrap()) as usize; - let (mut at, mut slots) = (rect + 20, Vec::new()); - while at < end { - let written = u32::from_be_bytes(block[at..at + 4].try_into().unwrap()) != 0; - slots.push((at, written)); - at += 4; - if written { - at += 4 + u32::from_be_bytes(block[at..at + 4].try_into().unwrap()) as usize; - } - } - (slots, end) - } - - #[test] - fn transparency_goes_in_the_sheet_mask_array_like_photoshop() { - // #8054: transparency in the user mask array (slot 24) made Photoshop refuse the file; - // Photoshop keeps it in the sheet mask array (slot 25). - for depth in [8, 16, 32] { - let p = pat(depth, true); - let mut block = write_pattern_block(std::slice::from_ref(&p)).unwrap(); - let (slots, end) = vma_slots(&block, &p); - let written: Vec = slots.iter().enumerate().filter(|(_, s)| s.1).map(|(i, _)| i).collect(); - assert_eq!((slots.len(), written), (26, vec![0, 1, 2, 25]), "{depth}-bit"); - assert!(!block_has_user_mask(&block)); - // The layout older PhotoCraft builds wrote still opens, and is detected. - block[slots[24].0..end].rotate_left(4); - let (slots, _) = vma_slots(&block, &p); - assert!(slots[24].1 && !slots[25].1); - assert!(block_has_user_mask(&block)); - assert_eq!(parse_pattern_block(&block).unwrap(), vec![p]); - } - assert!(!block_has_user_mask(&write_pattern_block(&[pat(8, false)]).unwrap())); - for junk in [&[][..], &[0, 0, 0, 9, 1], &[0xff; 64]] { - assert!(!block_has_user_mask(junk)); - } - } - - #[test] - fn malformed_input_errors_without_panicking() { - let blk = write_pattern_block(&[pat(8, true)]).unwrap(); - for cut in [3, 10, 40, blk.len() - 5] { - let _ = parse_pattern_block(&blk[..cut]); - } - assert!(parse_pat_file(b"8BPS\0\x01").is_err()); - assert!(parse_pattern_block(&[]).unwrap().is_empty()); - } - - fn pattern_vma_rect_offset(pattern_start: usize, p: &PsdPattern) -> usize { - let name_units = p.name.encode_utf16().count() + 1; - pattern_start + 16 + name_units * 2 + 1 + p.id.len() + if p.mode == 2 { 768 } else { 0 } + 8 - } - - fn set_i32(bytes: &mut [u8], offset: usize, value: i32) { - bytes[offset..offset + 4].copy_from_slice(&value.to_be_bytes()); - } - - #[test] - fn hostile_pattern_rectangles_are_rejected_through_all_import_routes() { - let p = pat(8, false); - - // A subtraction of the hostile endpoints overflowed before rectangle validation. - let mut global = write_pattern_block(std::slice::from_ref(&p)).unwrap(); - let vma = pattern_vma_rect_offset(4, &p); - set_i32(&mut global, vma + 4, i32::MIN); - set_i32(&mut global, vma + 12, i32::MAX); - assert!(parse_pattern_block(&global).is_err()); - - let mut standalone = write_pat_file(std::slice::from_ref(&p)).unwrap(); - let vma = pattern_vma_rect_offset(10, &p); - set_i32(&mut standalone, vma + 4, i32::MIN); - set_i32(&mut standalone, vma + 12, i32::MAX); - assert!(parse_pat_file(&standalone).is_err()); - - let mut abr = crate::abr::write_v6( - 1, - &[crate::abr::AbrSample { id: String::new(), width: 1, height: 1, depth: 8, data: vec![0] }], - std::slice::from_ref(&p), - &[], - true, - ) - .unwrap(); - let section = abr.windows(4).position(|w| w == b"patt").unwrap(); - let vma = pattern_vma_rect_offset(section + 8, &p) + 4; - set_i32(&mut abr, vma + 4, i32::MIN); - set_i32(&mut abr, vma + 12, i32::MAX); - let parsed = crate::abr::parse(&abr).unwrap(); - assert!(parsed.patterns.is_empty()); - assert!(parsed.warnings.iter().any(|warning| warning.contains("embedded patterns unreadable"))); - } - - #[test] - fn huge_pattern_rect_with_tiny_channel_payload_is_rejected() { - // RGB32 needs 10.8 GB; CMYK16 plus alpha needs 9 GB. Both exceed the - // existing pattern budget, but their first plane fits on 64-bit targets. - // The complete metadata must be checked before allocating that first plane. - huge_pattern_rect_is_rejected(pat(32, false)); - let mut cmyk = pat(16, true); - cmyk.mode = 4; - cmyk.channels.push(vec![0; 5 * 3 * 2]); - huge_pattern_rect_is_rejected(cmyk); - } - - fn huge_pattern_rect_is_rejected(p: PsdPattern) { - let mut global = write_pattern_block(std::slice::from_ref(&p)).unwrap(); - let vma = pattern_vma_rect_offset(4, &p); - set_i32(&mut global, vma + 8, 30_000); - set_i32(&mut global, vma + 12, 30_000); - assert!(matches!(parse_pattern_block(&global), Err(PsdError::LimitExceeded(_)))); - - let mut standalone = write_pat_file(std::slice::from_ref(&p)).unwrap(); - let vma = pattern_vma_rect_offset(10, &p); - set_i32(&mut standalone, vma + 8, 30_000); - set_i32(&mut standalone, vma + 12, 30_000); - assert!(matches!(parse_pat_file(&standalone), Err(PsdError::LimitExceeded(_)))); - - let mut abr = crate::abr::write_v6( - 1, - &[crate::abr::AbrSample { id: String::new(), width: 1, height: 1, depth: 8, data: vec![0] }], - std::slice::from_ref(&p), - &[], - true, - ) - .unwrap(); - let section = abr.windows(4).position(|w| w == b"patt").unwrap(); - let vma = pattern_vma_rect_offset(section + 8, &p) + 4; - set_i32(&mut abr, vma + 8, 30_000); - set_i32(&mut abr, vma + 12, 30_000); - let parsed = crate::abr::parse(&abr).unwrap(); - assert!(parsed.patterns.is_empty()); - assert!(parsed.warnings.iter().any(|warning| warning.contains("embedded patterns unreadable"))); - } - - #[test] - fn offset_channel_rectangles_are_placed_inside_the_pattern() { - for depth in [8, 16, 32] { - let original = pat(depth, true); - let mut block = write_pattern_block(std::slice::from_ref(&original)).unwrap(); - let vma = pattern_vma_rect_offset(4, &original); - set_i32(&mut block, vma, -2); - set_i32(&mut block, vma + 4, -3); - set_i32(&mut block, vma + 8, 4); - set_i32(&mut block, vma + 12, 5); - - let parsed = parse_pattern_block(&block).unwrap(); - let parsed = parsed.first().unwrap(); - assert_eq!((parsed.width, parsed.height), (8, 6)); - let bytes_per_sample = usize::from(depth / 8); - for (actual, expected) in parsed.channels.iter().zip(&original.channels).chain(parsed.alpha.iter().zip(original.alpha.iter())) { - for y in 0..6usize { - for x in 0..8usize { - let at = (y * 8 + x) * bytes_per_sample; - let actual_sample = actual.get(at..at + bytes_per_sample).unwrap(); - if (2..5).contains(&y) && (3..8).contains(&x) { - let source_at = ((y - 2) * 5 + (x - 3)) * bytes_per_sample; - assert_eq!(actual_sample, expected.get(source_at..source_at + bytes_per_sample).unwrap()); - } else { - assert!(actual_sample.iter().all(|&sample| sample == 0)); - } - } - } - } - } - } - - #[test] - fn one_bit_offset_channel_placement_preserves_msb_first_pixels() { - let source = PlaneLayout { planes: 1, width: 5, height: 2, depth: 1, version: Version::Psd }; - let destination = PlaneLayout { planes: 1, width: 8, height: 4, depth: 1, version: Version::Psd }; - let placed = place_channel_plane(vec![0b1010_1000, 0b0101_0000], &source, 2, 1, &destination).unwrap(); - assert_eq!(placed, [0, 0b0010_1010, 0b0001_0100, 0]); - } - - #[test] - fn full_size_channels_reuse_the_decoded_allocation() { - for depth in [1, 8, 16, 32] { - let layout = PlaneLayout { planes: 1, width: 5, height: 3, depth, version: Version::Psd }; - let plane = vec![0x55; layout.decoded_len().unwrap()]; - let original = plane.as_ptr(); - let placed = place_channel_plane(plane, &layout, 0, 0, &layout).unwrap(); - assert_eq!(placed.as_ptr(), original); - let expected = if depth == 1 { 0x50 } else { 0x55 }; - assert!(placed.iter().all(|&byte| byte == expected)); - } - } - - #[test] - fn large_channel_padding_within_the_existing_budget_is_allowed() { - let mut p = pat(8, false); - p.mode = 1; - let mut block = write_pattern_block(std::slice::from_ref(&p)).unwrap(); - let vma = pattern_vma_rect_offset(4, &p); - // More than 64 MiB of implicit padding is valid: the fix must not introduce - // a smaller, padding-specific format limit to avoid the oversized RGB case. - set_i32(&mut block, vma + 8, 8193); - set_i32(&mut block, vma + 12, 8193); - let parsed = parse_pattern_block(&block).unwrap(); - let plane = &parsed[0].channels[0]; - assert_eq!(plane.len(), 8193 * 8193); - for y in 0..3 { - assert_eq!(&plane[y * 8193..y * 8193 + 5], &p.channels[0][y * 5..y * 5 + 5]); - } - assert_eq!(plane[5], 0); - assert_eq!(plane[plane.len() - 1], 0); - } - - #[test] - fn padded_plane_allocation_failure_is_an_error() { - // Capacity overflow is deterministic and never asks the OS for huge memory. - assert!(matches!(zeroed_pattern_plane(usize::MAX), Err(PsdError::LimitExceeded("not enough memory for the padded pattern channel")))); - } - - #[test] - fn tiny_channels_in_a_huge_pattern_rect_are_not_zero_padded_without_bound() { - // 3 channels of 5x3 padded to 30000x30000 would allocate 2.7 GB of zeros. - let p = pat(8, false); - let mut global = write_pattern_block(std::slice::from_ref(&p)).unwrap(); - let vma = pattern_vma_rect_offset(4, &p); - set_i32(&mut global, vma + 8, 30_000); - set_i32(&mut global, vma + 12, 30_000); - assert!(matches!(parse_pattern_block(&global), Err(PsdError::LimitExceeded("padded pattern channels exceed MAX_PADDED_PATTERN_BYTES")))); - } - - /// A one-channel gray pattern whose 5x3 channel is padded into a `size`x`size` rectangle. - fn padded_gray_block(size: i32) -> Vec { - let mut p = pat(8, false); - p.mode = 1; - p.channels.truncate(1); - let mut block = write_pattern_block(std::slice::from_ref(&p)).unwrap(); - let vma = pattern_vma_rect_offset(4, &p); - set_i32(&mut block, vma + 8, size); - set_i32(&mut block, vma + 12, size); - block - } - - #[test] - fn failed_pattern_block_keeps_partial_charge_for_the_next_block() { - let one = padded_gray_block(100); - let mut malformed = one.clone(); - malformed.extend_from_slice(&100u32.to_be_bytes()); - let mut budget = PatternBudget::with_decoded_limit(15_000); - assert!(parse_pattern_block_with(&malformed, &mut budget).is_err()); - assert_eq!(budget.decoded_left(), 5_000); - assert!(parse_pattern_block_with(&one, &mut budget).is_err()); - assert_eq!(budget.decoded_left(), 5_000); - } - - #[test] - fn padding_budget_is_shared_by_every_pattern_of_a_parse() { - // Each pattern pads 100x100 = 10000 bytes; a 15000-byte budget fits one, not two. Before - // the fix each pattern got a fresh allowance, so N tiny patterns committed N times the cap. - let one = padded_gray_block(100); - let mut budget = PatternBudget::with_decoded_limit(15_000); - assert_eq!(parse_pattern_block_with(&one, &mut budget).unwrap().len(), 1); - assert_eq!(budget.decoded_left(), 5_000); - - let two = [one.clone(), one.clone()].concat(); - let mut budget = PatternBudget::with_decoded_limit(15_000); - assert!(matches!(parse_pattern_block_with(&two, &mut budget), Err(PsdError::LimitExceeded(_)))); - // Charges are monotonic: the first pattern's 10000 bytes stay charged even when the second - // record fails. - assert_eq!(budget.decoded_left(), 5_000); - - // Two blocks of one document share a budget too. - let mut budget = PatternBudget::with_decoded_limit(15_000); - assert!(parse_pattern_block_with(&one, &mut budget).is_ok()); - assert!(parse_pattern_block_with(&one, &mut budget).is_err()); - } - - #[test] - fn channels_at_different_depths_are_rejected() { - // The second colour channel claims 8 bits in a 16-bit pattern. It used to be accepted with - // the pattern's depth taken from the last channel, so the result couldn't be written back. - let p = pat(16, false); - let mut block = write_pattern_block(std::slice::from_ref(&p)).unwrap(); - let first = pattern_vma_rect_offset(4, &p) + 20; - let first_len = u32::from_be_bytes(block[first + 4..first + 8].try_into().unwrap()) as usize; - let second = first + 8 + first_len; - block[second + 8..second + 12].copy_from_slice(&8u32.to_be_bytes()); - block[second + 28..second + 30].copy_from_slice(&8u16.to_be_bytes()); - let err = parse_pattern_block(&block).unwrap_err().to_string(); - assert!(err.contains("different depths"), "{err}"); - } - - #[test] - fn zero_size_pattern_rectangles_are_rejected() { - let p = pat(8, false); - let mut block = write_pattern_block(std::slice::from_ref(&p)).unwrap(); - let vma = pattern_vma_rect_offset(4, &p); - set_i32(&mut block, vma + 8, 0); - assert!(parse_pattern_block(&block).is_err()); - } -} +mod tests; diff --git a/crates/psd/src/patterns/tests.rs b/crates/psd/src/patterns/tests.rs new file mode 100644 index 0000000000..c66c8189d4 --- /dev/null +++ b/crates/psd/src/patterns/tests.rs @@ -0,0 +1,352 @@ +use super::*; + +fn pat(depth: u16, alpha: bool) -> PsdPattern { + let (w, h) = (5u32, 3u32); + let bpp = usize::from(depth / 8); + let plane = |s: u8| (0..w as usize * h as usize * bpp).map(|i| (i as u8).wrapping_mul(7).wrapping_add(s)).collect::>(); + PsdPattern { + mode: 3, + width: w, + height: h, + name: "Test ✓".into(), + id: "0bd2d3ba-1234-11d4-8f8f-aabbccddeeff".into(), + palette: None, + depth, + channels: vec![plane(1), plane(2), plane(3)], + alpha: alpha.then(|| plane(9)), + } +} + +/// #9318 review: a name the reader refuses (more than 65,536 UTF-16 units with its NUL) is +/// refused on write, so a saved library can't become a file that loads nothing. +#[test] +fn a_name_the_reader_refuses_is_refused_on_write() { + let long = PsdPattern { name: "a".repeat(65_536), ..pat(8, false) }; + assert!(matches!(write_pat_file(&[long]), Err(PsdError::LimitExceeded(_)))); + let longest = PsdPattern { name: "a".repeat(65_535), ..pat(8, false) }; + assert_eq!(parse_pat_file(&write_pat_file(std::slice::from_ref(&longest)).unwrap()).unwrap(), [longest]); +} + +/// #9318 review: more patterns than a `.pat` holds are refused on write, and a file claiming +/// more is refused on read rather than silently cut to the first 100,000. +#[test] +fn more_patterns_than_a_pat_file_holds_are_refused() { + let many = vec![pat(8, false); MAX_PAT_PATTERNS + 1]; + assert!(matches!(write_pat_file(&many), Err(PsdError::LimitExceeded(_)))); + let mut header = b"8BPT".to_vec(); + header.extend_from_slice(&1u16.to_be_bytes()); + header.extend_from_slice(&(MAX_PAT_PATTERNS as u32 + 1).to_be_bytes()); + assert!(matches!(parse_pat_file(&header), Err(PsdError::LimitExceeded(_)))); +} + +#[test] +fn block_and_pat_file_round_trip_at_every_depth() { + for depth in [8, 16, 32] { + for alpha in [false, true] { + let ps = vec![pat(depth, alpha), PsdPattern { name: "Second".into(), ..pat(depth, false) }]; + let blk = write_pattern_block(&ps).unwrap(); + assert_eq!(blk.len() % 4, 0); + assert_eq!(parse_pattern_block(&blk).unwrap(), ps); + let f = write_pat_file(&ps).unwrap(); + assert_eq!(parse_pat_file(&f).unwrap(), ps); + // Re-serialising is byte-stable. + assert_eq!(write_pattern_block(&parse_pattern_block(&blk).unwrap()).unwrap(), blk); + } + } +} + +/// Offsets of the virtual memory arrays of a one-pattern block (each at its "written" flag), +/// with whether each is written, and the end of the array list. +fn vma_slots(block: &[u8], p: &PsdPattern) -> (Vec<(usize, bool)>, usize) { + let rect = pattern_vma_rect_offset(4, p); + let end = rect + u32::from_be_bytes(block[rect - 4..rect].try_into().unwrap()) as usize; + let (mut at, mut slots) = (rect + 20, Vec::new()); + while at < end { + let written = u32::from_be_bytes(block[at..at + 4].try_into().unwrap()) != 0; + slots.push((at, written)); + at += 4; + if written { + at += 4 + u32::from_be_bytes(block[at..at + 4].try_into().unwrap()) as usize; + } + } + (slots, end) +} + +#[test] +fn transparency_goes_in_the_sheet_mask_array_like_photoshop() { + // #8054: transparency in the user mask array (slot 24) made Photoshop refuse the file; + // Photoshop keeps it in the sheet mask array (slot 25). + for depth in [8, 16, 32] { + let p = pat(depth, true); + let mut block = write_pattern_block(std::slice::from_ref(&p)).unwrap(); + let (slots, end) = vma_slots(&block, &p); + let written: Vec = slots.iter().enumerate().filter(|(_, s)| s.1).map(|(i, _)| i).collect(); + assert_eq!((slots.len(), written), (26, vec![0, 1, 2, 25]), "{depth}-bit"); + assert!(!block_has_user_mask(&block)); + // The layout older PhotoCraft builds wrote still opens, and is detected. + block[slots[24].0..end].rotate_left(4); + let (slots, _) = vma_slots(&block, &p); + assert!(slots[24].1 && !slots[25].1); + assert!(block_has_user_mask(&block)); + assert_eq!(parse_pattern_block(&block).unwrap(), vec![p]); + } + assert!(!block_has_user_mask(&write_pattern_block(&[pat(8, false)]).unwrap())); + for junk in [&[][..], &[0, 0, 0, 9, 1], &[0xff; 64]] { + assert!(!block_has_user_mask(junk)); + } +} + +#[test] +fn malformed_input_errors_without_panicking() { + let blk = write_pattern_block(&[pat(8, true)]).unwrap(); + for cut in [3, 10, 40, blk.len() - 5] { + let _ = parse_pattern_block(&blk[..cut]); + } + assert!(parse_pat_file(b"8BPS\0\x01").is_err()); + assert!(parse_pattern_block(&[]).unwrap().is_empty()); +} + +fn pattern_vma_rect_offset(pattern_start: usize, p: &PsdPattern) -> usize { + let name_units = p.name.encode_utf16().count() + 1; + pattern_start + 16 + name_units * 2 + 1 + p.id.len() + if p.mode == 2 { 768 } else { 0 } + 8 +} + +fn set_i32(bytes: &mut [u8], offset: usize, value: i32) { + bytes[offset..offset + 4].copy_from_slice(&value.to_be_bytes()); +} + +#[test] +fn hostile_pattern_rectangles_are_rejected_through_all_import_routes() { + let p = pat(8, false); + + // A subtraction of the hostile endpoints overflowed before rectangle validation. + let mut global = write_pattern_block(std::slice::from_ref(&p)).unwrap(); + let vma = pattern_vma_rect_offset(4, &p); + set_i32(&mut global, vma + 4, i32::MIN); + set_i32(&mut global, vma + 12, i32::MAX); + assert!(parse_pattern_block(&global).is_err()); + + let mut standalone = write_pat_file(std::slice::from_ref(&p)).unwrap(); + let vma = pattern_vma_rect_offset(10, &p); + set_i32(&mut standalone, vma + 4, i32::MIN); + set_i32(&mut standalone, vma + 12, i32::MAX); + assert!(parse_pat_file(&standalone).is_err()); + + let mut abr = crate::abr::write_v6( + 1, + &[crate::abr::AbrSample { id: String::new(), width: 1, height: 1, depth: 8, data: vec![0] }], + std::slice::from_ref(&p), + &[], + true, + ) + .unwrap(); + let section = abr.windows(4).position(|w| w == b"patt").unwrap(); + let vma = pattern_vma_rect_offset(section + 8, &p) + 4; + set_i32(&mut abr, vma + 4, i32::MIN); + set_i32(&mut abr, vma + 12, i32::MAX); + let parsed = crate::abr::parse(&abr).unwrap(); + assert!(parsed.patterns.is_empty()); + assert!(parsed.warnings.iter().any(|warning| warning.contains("embedded patterns unreadable"))); +} + +#[test] +fn huge_pattern_rect_with_tiny_channel_payload_is_rejected() { + // RGB32 needs 10.8 GB; CMYK16 plus alpha needs 9 GB. Both exceed the + // existing pattern budget, but their first plane fits on 64-bit targets. + // The complete metadata must be checked before allocating that first plane. + huge_pattern_rect_is_rejected(pat(32, false)); + let mut cmyk = pat(16, true); + cmyk.mode = 4; + cmyk.channels.push(vec![0; 5 * 3 * 2]); + huge_pattern_rect_is_rejected(cmyk); +} + +fn huge_pattern_rect_is_rejected(p: PsdPattern) { + let mut global = write_pattern_block(std::slice::from_ref(&p)).unwrap(); + let vma = pattern_vma_rect_offset(4, &p); + set_i32(&mut global, vma + 8, 30_000); + set_i32(&mut global, vma + 12, 30_000); + assert!(matches!(parse_pattern_block(&global), Err(PsdError::LimitExceeded(_)))); + + let mut standalone = write_pat_file(std::slice::from_ref(&p)).unwrap(); + let vma = pattern_vma_rect_offset(10, &p); + set_i32(&mut standalone, vma + 8, 30_000); + set_i32(&mut standalone, vma + 12, 30_000); + assert!(matches!(parse_pat_file(&standalone), Err(PsdError::LimitExceeded(_)))); + + let mut abr = crate::abr::write_v6( + 1, + &[crate::abr::AbrSample { id: String::new(), width: 1, height: 1, depth: 8, data: vec![0] }], + std::slice::from_ref(&p), + &[], + true, + ) + .unwrap(); + let section = abr.windows(4).position(|w| w == b"patt").unwrap(); + let vma = pattern_vma_rect_offset(section + 8, &p) + 4; + set_i32(&mut abr, vma + 8, 30_000); + set_i32(&mut abr, vma + 12, 30_000); + let parsed = crate::abr::parse(&abr).unwrap(); + assert!(parsed.patterns.is_empty()); + assert!(parsed.warnings.iter().any(|warning| warning.contains("embedded patterns unreadable"))); +} + +#[test] +fn offset_channel_rectangles_are_placed_inside_the_pattern() { + for depth in [8, 16, 32] { + let original = pat(depth, true); + let mut block = write_pattern_block(std::slice::from_ref(&original)).unwrap(); + let vma = pattern_vma_rect_offset(4, &original); + set_i32(&mut block, vma, -2); + set_i32(&mut block, vma + 4, -3); + set_i32(&mut block, vma + 8, 4); + set_i32(&mut block, vma + 12, 5); + + let parsed = parse_pattern_block(&block).unwrap(); + let parsed = parsed.first().unwrap(); + assert_eq!((parsed.width, parsed.height), (8, 6)); + let bytes_per_sample = usize::from(depth / 8); + for (actual, expected) in parsed.channels.iter().zip(&original.channels).chain(parsed.alpha.iter().zip(original.alpha.iter())) { + for y in 0..6usize { + for x in 0..8usize { + let at = (y * 8 + x) * bytes_per_sample; + let actual_sample = actual.get(at..at + bytes_per_sample).unwrap(); + if (2..5).contains(&y) && (3..8).contains(&x) { + let source_at = ((y - 2) * 5 + (x - 3)) * bytes_per_sample; + assert_eq!(actual_sample, expected.get(source_at..source_at + bytes_per_sample).unwrap()); + } else { + assert!(actual_sample.iter().all(|&sample| sample == 0)); + } + } + } + } + } +} + +#[test] +fn one_bit_offset_channel_placement_preserves_msb_first_pixels() { + let source = PlaneLayout { planes: 1, width: 5, height: 2, depth: 1, version: Version::Psd }; + let destination = PlaneLayout { planes: 1, width: 8, height: 4, depth: 1, version: Version::Psd }; + let placed = place_channel_plane(vec![0b1010_1000, 0b0101_0000], &source, 2, 1, &destination).unwrap(); + assert_eq!(placed, [0, 0b0010_1010, 0b0001_0100, 0]); +} + +#[test] +fn full_size_channels_reuse_the_decoded_allocation() { + for depth in [1, 8, 16, 32] { + let layout = PlaneLayout { planes: 1, width: 5, height: 3, depth, version: Version::Psd }; + let plane = vec![0x55; layout.decoded_len().unwrap()]; + let original = plane.as_ptr(); + let placed = place_channel_plane(plane, &layout, 0, 0, &layout).unwrap(); + assert_eq!(placed.as_ptr(), original); + let expected = if depth == 1 { 0x50 } else { 0x55 }; + assert!(placed.iter().all(|&byte| byte == expected)); + } +} + +#[test] +fn large_channel_padding_within_the_existing_budget_is_allowed() { + let mut p = pat(8, false); + p.mode = 1; + let mut block = write_pattern_block(std::slice::from_ref(&p)).unwrap(); + let vma = pattern_vma_rect_offset(4, &p); + // More than 64 MiB of implicit padding is valid: the fix must not introduce + // a smaller, padding-specific format limit to avoid the oversized RGB case. + set_i32(&mut block, vma + 8, 8193); + set_i32(&mut block, vma + 12, 8193); + let parsed = parse_pattern_block(&block).unwrap(); + let plane = &parsed[0].channels[0]; + assert_eq!(plane.len(), 8193 * 8193); + for y in 0..3 { + assert_eq!(&plane[y * 8193..y * 8193 + 5], &p.channels[0][y * 5..y * 5 + 5]); + } + assert_eq!(plane[5], 0); + assert_eq!(plane[plane.len() - 1], 0); +} + +#[test] +fn padded_plane_allocation_failure_is_an_error() { + // Capacity overflow is deterministic and never asks the OS for huge memory. + assert!(matches!(zeroed_pattern_plane(usize::MAX), Err(PsdError::LimitExceeded("not enough memory for the padded pattern channel")))); +} + +#[test] +fn tiny_channels_in_a_huge_pattern_rect_are_not_zero_padded_without_bound() { + // 3 channels of 5x3 padded to 30000x30000 would allocate 2.7 GB of zeros. + let p = pat(8, false); + let mut global = write_pattern_block(std::slice::from_ref(&p)).unwrap(); + let vma = pattern_vma_rect_offset(4, &p); + set_i32(&mut global, vma + 8, 30_000); + set_i32(&mut global, vma + 12, 30_000); + assert!(matches!(parse_pattern_block(&global), Err(PsdError::LimitExceeded("padded pattern channels exceed MAX_PADDED_PATTERN_BYTES")))); +} + +/// A one-channel gray pattern whose 5x3 channel is padded into a `size`x`size` rectangle. +fn padded_gray_block(size: i32) -> Vec { + let mut p = pat(8, false); + p.mode = 1; + p.channels.truncate(1); + let mut block = write_pattern_block(std::slice::from_ref(&p)).unwrap(); + let vma = pattern_vma_rect_offset(4, &p); + set_i32(&mut block, vma + 8, size); + set_i32(&mut block, vma + 12, size); + block +} + +#[test] +fn failed_pattern_block_keeps_partial_charge_for_the_next_block() { + let one = padded_gray_block(100); + let mut malformed = one.clone(); + malformed.extend_from_slice(&100u32.to_be_bytes()); + let mut budget = PatternBudget::with_decoded_limit(15_000); + assert!(parse_pattern_block_with(&malformed, &mut budget).is_err()); + assert_eq!(budget.decoded_left(), 5_000); + assert!(parse_pattern_block_with(&one, &mut budget).is_err()); + assert_eq!(budget.decoded_left(), 5_000); +} + +#[test] +fn padding_budget_is_shared_by_every_pattern_of_a_parse() { + // Each pattern pads 100x100 = 10000 bytes; a 15000-byte budget fits one, not two. Before + // the fix each pattern got a fresh allowance, so N tiny patterns committed N times the cap. + let one = padded_gray_block(100); + let mut budget = PatternBudget::with_decoded_limit(15_000); + assert_eq!(parse_pattern_block_with(&one, &mut budget).unwrap().len(), 1); + assert_eq!(budget.decoded_left(), 5_000); + + let two = [one.clone(), one.clone()].concat(); + let mut budget = PatternBudget::with_decoded_limit(15_000); + assert!(matches!(parse_pattern_block_with(&two, &mut budget), Err(PsdError::LimitExceeded(_)))); + // Charges are monotonic: the first pattern's 10000 bytes stay charged even when the second + // record fails. + assert_eq!(budget.decoded_left(), 5_000); + + // Two blocks of one document share a budget too. + let mut budget = PatternBudget::with_decoded_limit(15_000); + assert!(parse_pattern_block_with(&one, &mut budget).is_ok()); + assert!(parse_pattern_block_with(&one, &mut budget).is_err()); +} + +#[test] +fn channels_at_different_depths_are_rejected() { + // The second colour channel claims 8 bits in a 16-bit pattern. It used to be accepted with + // the pattern's depth taken from the last channel, so the result couldn't be written back. + let p = pat(16, false); + let mut block = write_pattern_block(std::slice::from_ref(&p)).unwrap(); + let first = pattern_vma_rect_offset(4, &p) + 20; + let first_len = u32::from_be_bytes(block[first + 4..first + 8].try_into().unwrap()) as usize; + let second = first + 8 + first_len; + block[second + 8..second + 12].copy_from_slice(&8u32.to_be_bytes()); + block[second + 28..second + 30].copy_from_slice(&8u16.to_be_bytes()); + let err = parse_pattern_block(&block).unwrap_err().to_string(); + assert!(err.contains("different depths"), "{err}"); +} + +#[test] +fn zero_size_pattern_rectangles_are_rejected() { + let p = pat(8, false); + let mut block = write_pattern_block(std::slice::from_ref(&p)).unwrap(); + let vma = pattern_vma_rect_offset(4, &p); + set_i32(&mut block, vma + 8, 0); + assert!(parse_pattern_block(&block).is_err()); +} diff --git a/crates/psd/src/tiff.rs b/crates/psd/src/tiff.rs index 8b11a6b61e..86373f2ed3 100644 --- a/crates/psd/src/tiff.rs +++ b/crates/psd/src/tiff.rs @@ -268,2405 +268,7 @@ pub fn resources_to_bytes(resources: &[ImageResource]) -> Result> { /// so output lengths equal input lengths and every length field stays valid. Layouts follow the /// Adobe PSD specification; the walker only needs to know where the integers, doubles and /// four-character keys are, not what they mean. -pub mod transcode { - use super::*; - - /// Converts the tagged blocks after the 37724 header string from `from` to `to`. - pub fn transcode_blocks(data: &[u8], version: Version, from: ByteOrder, to: ByteOrder) -> Result<(Vec, Vec)> { - let mut t = Tx::new(data, version, from, to); - t.blocks()?; - Ok(t.finish()) - } - - /// Converts a layer-info body (the data of a `Layr` / `Lr16` / `Lr32` block) between orders. - pub fn transcode_layer_info(data: &[u8], version: Version, from: ByteOrder, to: ByteOrder) -> Result<(Vec, Vec)> { - let mut t = Tx::new(data, version, from, to); - t.layer_info()?; - Ok(t.finish()) - } - - /// Converts image-resource blocks (a 34377 tag) between orders. - pub fn transcode_resources(data: &[u8], from: ByteOrder, to: ByteOrder) -> Result<(Vec, Vec)> { - let mut t = Tx::new(data, Version::Psd, from, to); - t.resources()?; - Ok(t.finish()) - } - - /// A block signature as stored in `little` or big-endian data. Big-endian data (the model) - /// also carries the `MIB8` / `46B8` markers of blocks kept from a little-endian file. - fn is_sig(b: &[u8], little: bool) -> bool { - if little { - b.starts_with(b"MIB8") || b.starts_with(b"46B8") - } else { - b.starts_with(b"8BIM") || b.starts_with(b"8B64") || TaggedBlock::is_foreign_order_signature(b) - } - } - - fn height(top: i32, bottom: i32) -> usize { - usize::try_from(bottom.saturating_sub(top)).unwrap_or(0) - } - - /// Per layer record: the channel (id, length) list and the heights of the layer, mask and - /// real-mask rects. - type RecordShape = (Vec<(i16, u64)>, [usize; 3]); - - struct Tx<'a> { - r: Reader<'a>, - out: Vec, - from: ByteOrder, - to: ByteOrder, - version: Version, - warnings: Vec, - depth: usize, - } - - macro_rules! copy_int { - ($name:ident, $ty:ty) => { - fn $name(&mut self) -> Result<$ty> { - let v = self.r.$name()?; - self.out.extend_from_slice(&if self.to.is_little() { v.to_le_bytes() } else { v.to_be_bytes() }); - Ok(v) - } - }; - } - - impl<'a> Tx<'a> { - fn new(data: &'a [u8], version: Version, from: ByteOrder, to: ByteOrder) -> Self { - let r = if from.is_little() { Reader::new_little(data) } else { Reader::new(data) }; - Tx { r, out: Vec::with_capacity(data.len()), from, to, version, warnings: Vec::new(), depth: 0 } - } - - fn finish(self) -> (Vec, Vec) { - (self.out, self.warnings) - } - - /// A walker over `data` (a nested structure) that writes into this walker's output: it - /// takes the buffer, so a nested structure is written once, not copied up per level. Hand - /// the buffer back with [`Self::adopt`] before returning, error or not. - fn nested<'b>(&mut self, data: &'b [u8], depth: usize) -> Tx<'b> { - let r = if self.from.is_little() { Reader::new_little(data) } else { Reader::new(data) }; - Tx { r, out: std::mem::take(&mut self.out), from: self.from, to: self.to, version: self.version, warnings: Vec::new(), depth } - } - - /// Takes the output buffer back from a [`Self::nested`] walker. - fn adopt(&mut self, child: &mut Tx<'_>) { - self.out = std::mem::take(&mut child.out); - } - - fn same_order(&self) -> bool { - self.from == self.to - } - - fn remaining(&self) -> usize { - self.r.remaining() - } - - copy_int!(u16, u16); - copy_int!(i16, i16); - copy_int!(u32, u32); - copy_int!(i32, i32); - copy_int!(u64, u64); - copy_int!(i64, i64); - copy_int!(f64, f64); - - fn u8(&mut self) -> Result { - let v = self.r.u8()?; - self.out.push(v); - Ok(v) - } - - fn f32(&mut self) -> Result<()> { - let b = self.r.array::<4>()?; - let v = if self.from.is_little() { f32::from_le_bytes(b) } else { f32::from_be_bytes(b) }; - self.out.extend_from_slice(&if self.to.is_little() { v.to_le_bytes() } else { v.to_be_bytes() }); - Ok(()) - } - - /// Bytes copied as they are. - fn raw(&mut self, n: usize) -> Result<()> { - let b = self.r.bytes(n)?; - self.out.extend_from_slice(b); - Ok(()) - } - - fn rest(&mut self) -> Result<()> { - let n = self.remaining(); - self.raw(n) - } - - /// A four-character signature or key: stored reversed in little-endian data. Returns the - /// canonical (big-endian) spelling. - fn key(&mut self) -> Result<[u8; 4]> { - let mut k = self.r.array::<4>()?; - if self.from.is_little() { - k.reverse(); - } - let mut w = k; - if self.to.is_little() { - w.reverse(); - } - self.out.extend_from_slice(&w); - Ok(k) - } - - fn len(&mut self, long: bool) -> Result { - if long { self.u64() } else { Ok(u64::from(self.u32()?)) } - } - - fn u16s(&mut self, n: usize) -> Result<()> { - for _ in 0..n { - self.u16()?; - } - Ok(()) - } - - /// Up to `n` `u16`s: a block shorter than its full layout keeps what it has. - fn u16s_upto(&mut self, n: usize) -> Result<()> { - for _ in 0..n { - if self.remaining() < 2 { - break; - } - self.u16()?; - } - Ok(()) - } - - fn i32s(&mut self, n: usize) -> Result<()> { - for _ in 0..n { - self.i32()?; - } - Ok(()) - } - - fn f64s(&mut self, n: usize) -> Result<()> { - for _ in 0..n { - self.f64()?; - } - Ok(()) - } - - /// `u16`s to the end (a lone odd byte is copied). - fn u16s_to_end(&mut self) -> Result<()> { - while self.remaining() >= 2 { - self.u16()?; - } - self.rest() - } - - fn u32s_to_end(&mut self) -> Result<()> { - while self.remaining() >= 4 { - self.u32()?; - } - self.rest() - } - - /// A Photoshop Unicode string: u32 count + UTF-16 units. - fn unicode(&mut self) -> Result<()> { - let n = self.u32()?; - self.r.check_count(u64::from(n), 2)?; - self.u16s(n as usize) - } - - /// A Pascal string padded to `align`. - fn pascal(&mut self, align: usize) -> Result<()> { - let n = usize::from(self.u8()?); - self.raw(n)?; - let total = 1 + n; - self.raw((align - total % align) % align) - } - - /// Transcodes the next `len` bytes with `f`; whatever `f` leaves is copied verbatim. - fn region(&mut self, len: u64, f: impl FnOnce(&mut Tx<'_>) -> Result<()>) -> Result<()> { - let data = self.r.bytes_u64(len)?; - let start = self.out.len(); - let mut child = self.nested(data, self.depth); - let res = f(&mut child).and_then(|()| child.rest()); - self.adopt(&mut child); - res?; - if self.out.len() - start != data.len() { - return Err(PsdError::invalid("byte-order conversion changed a structure's length")); - } - self.warnings.append(&mut child.warnings); - Ok(()) - } - - /// Reads a length field (4 bytes, or 8 when `long`), transcodes that many bytes with `f` - /// and writes the length of the result: blocks dropped inside shrink the field. - fn sized_region(&mut self, long: bool, f: impl FnOnce(&mut Tx<'_>) -> Result<()>) -> Result<()> { - self.sized_region_counting(long, false, f) - } - - /// [`Self::sized_region`] for a u32 length that counts its own 4 bytes. - fn sized_region_inclusive(&mut self, f: impl FnOnce(&mut Tx<'_>) -> Result<()>) -> Result<()> { - self.sized_region_counting(false, true, f) - } - - fn sized_region_counting(&mut self, long: bool, inclusive: bool, f: impl FnOnce(&mut Tx<'_>) -> Result<()>) -> Result<()> { - let mut len = self.r.len_field(long)?; - let at = self.out.len(); - self.out.extend_from_slice(if long { &[0u8; 8] } else { &[0u8; 4] }); - if inclusive { - len = len.checked_sub(4).ok_or_else(|| PsdError::invalid("length shorter than its own field"))?; - } - let data = self.r.bytes_u64(len)?; - let start = self.out.len(); - let mut child = self.nested(data, self.depth); - let res = f(&mut child).and_then(|()| child.rest()); - self.adopt(&mut child); - res?; - self.warnings.append(&mut child.warnings); - self.patch_len(at, long, (self.out.len() - start) as u64 + if inclusive { 4 } else { 0 })?; - Ok(()) - } - - /// Tries `f` on the rest of the data; it counts as a match only when at most three - /// trailing zero bytes are left. On a miss nothing is consumed or written. - fn attempt(&mut self, f: impl FnOnce(&mut Tx<'_>) -> Result<()>) -> bool { - let (reader, written) = (self.r.clone(), self.out.len()); - let ok = f(self).is_ok() && self.remaining() <= 3 && self.r.peek_rest().iter().all(|&b| b == 0); - if !ok { - self.r = reader; - self.out.truncate(written); - } - ok - } - - /// Blocks whose layout is not known by key are very often a versioned descriptor, - /// optionally behind a u32 version (every Photoshop block introduced since CS6 is): - /// recognized by parsing to the end. - fn descriptor_shaped(&mut self) -> bool { - self.attempt(|t| t.versioned_descriptor()) - || self.attempt(|t| { - t.u32()?; - t.versioned_descriptor() - }) - } - - /// Writes `n` into the length placeholder at `at`. - fn patch_len(&mut self, at: usize, long: bool, n: u64) -> Result<()> { - if long { - let b = if self.to.is_little() { n.to_le_bytes() } else { n.to_be_bytes() }; - if let Some(slot) = self.out.get_mut(at..at + 8) { - slot.copy_from_slice(&b); - } - } else { - let n = u32::try_from(n).map_err(|_| PsdError::LimitExceeded("structure too large for a 32-bit length"))?; - let b = if self.to.is_little() { n.to_le_bytes() } else { n.to_be_bytes() }; - if let Some(slot) = self.out.get_mut(at..at + 4) { - slot.copy_from_slice(&b); - } - } - Ok(()) - } - - /// An RLE row-count table (`rows` entries of 2 bytes, 4 in PSB data). - fn rle_counts(&mut self, rows: usize) -> Result<()> { - for _ in 0..rows { - if self.version.is_psb() { - if self.remaining() < 4 { - break; - } - self.u32()?; - } else { - if self.remaining() < 2 { - break; - } - self.u16()?; - } - } - Ok(()) - } - - /// Encoded channel data for a plane of `rows` rows: the compression field, then the RLE - /// row counts (container order) and the samples (always big-endian: copied). - fn channel_data(&mut self, rows: usize, long_counts: bool) -> Result<()> { - let saved = self.version; - if long_counts { - self.version = Version::Psb; - } - let compression = self.u16()?; - let res = if compression == 1 { self.rle_counts(rows) } else { Ok(()) }; - self.version = saved; - res?; - self.rest() - } - - // ---- image resources (34377) ---- - - fn resources(&mut self) -> Result<()> { - while self.remaining() >= 12 && is_sig(self.r.peek_rest(), self.from.is_little()) { - self.key()?; - let id = self.u16()?; - self.pascal(2)?; - let odd = self.r.clone().u32()? % 2 == 1; - self.sized_region(false, |t| t.resource_data(id))?; - if odd && self.remaining() > 0 { - self.raw(1)?; - } - } - self.rest() - } - - /// Typed numeric resources; every other payload is a byte blob (ICC, XMP, EXIF, …) or - /// unknown and is copied as stored. - fn resource_data(&mut self, id: u16) -> Result<()> { - match id { - // Resolution info: fixed 16.16 h res, u16 unit, u16 width unit, then the same for v. - 1005 => { - self.u32()?; - self.u16()?; - self.u16()?; - self.u32()?; - self.u16()?; - self.u16()?; - } - // Layer state (u16 target), layer group info (u16 per layer). - 1024 | 1026 => self.u16s_to_end()?, - // Global angle / altitude. - 1037 | 1049 => { - self.u32()?; - } - // Layer selection ids: u16 count + u32 ids. - 1069 => { - self.u16()?; - self.u32s_to_end()?; - } - // Version info: u32 version, u8 has real merged data, two Unicode strings, u32. - 1057 => { - self.u32()?; - self.u8()?; - self.unicode()?; - self.unicode()?; - self.u32()?; - } - // Grid and guides: u32 version, 2 × u32 grid, u32 count, (u32 location, u8 direction)… - 1032 => { - self.u32()?; - self.u32()?; - self.u32()?; - let n = self.u32()?; - for _ in 0..n { - if self.remaining() < 5 { - break; - } - self.u32()?; - self.u8()?; - } - } - // Path resources: 26-byte records. - 2000..=2997 | 2999 => self.path_records()?, - _ => {} - } - Ok(()) - } - - // ---- tagged blocks ---- - - /// Tagged blocks to the end; bytes that do not form a block are copied. - fn blocks(&mut self) -> Result<()> { - loop { - let rest = self.r.peek_rest(); - if rest.len() < 12 || !is_sig(rest, self.from.is_little()) { - return self.rest(); - } - self.block()?; - } - } - - fn block(&mut self) -> Result<()> { - let before = self.out.len(); - // A `MIB8` / `46B8` marker in big-endian data: a block kept verbatim from a - // little-endian file. Written back as it was into little-endian output (its `8BIM` - // signature reversed, as every signature there), copied as is otherwise. - if !self.from.is_little() && TaggedBlock::is_foreign_order_signature(self.r.peek_rest()) { - let sig = self.r.array::<4>()?; - let mut key = self.r.array::<4>()?; - // Only reached with `from == Big`: the key is canonical here whatever the - // target order. `TaggedBlock::write` sizes the length field from that same key. - // Reversing it for the target order before the check - // asked about a key `PSB_LONG_KEYS` never contains, so a PSB long key's 8-byte - // length was read as 4 and every later block was copied unconverted. - let long = uses_long_length(self.version, &key); - let len = self.r.len_field(long)?; - let data = self.r.bytes_u64(len)?; - if self.to.is_little() { - key.reverse(); - } - self.out.extend_from_slice(&sig); - self.out.extend_from_slice(&key); - let n = self.out.len(); - self.out.extend_from_slice(if long { &[0u8; 8] } else { &[0u8; 4] }); - self.patch_len(n, long, len)?; - self.out.extend_from_slice(data); - let rest = self.r.peek_rest(); - let pad = (0..=3usize).find(|&k| k == rest.len() || (k < rest.len() && is_sig(&rest[k..], self.from.is_little()))).unwrap_or(0); - let pad_bytes = self.r.bytes(pad)?; - self.out.extend_from_slice(pad_bytes); - return Ok(()); - } - let sig_at = self.out.len(); - let sig = self.key()?; - let key = self.key()?; - let long = uses_long_length(self.version, &key); - let len = self.r.len_field(long)?; - let len_at = self.out.len(); - self.out.extend_from_slice(if long { &[0u8; 8] } else { &[0u8; 4] }); - let data = self.r.bytes_u64(len)?; - // The body is transcoded straight into this output, after the length placeholder. - let data_at = self.out.len(); - let mut child = self.nested(data, self.depth + 1); - let handled = if child.depth > MAX_DEPTH { - Err(PsdError::LimitExceeded("tagged block nesting too deep")) - } else if data.is_empty() { - Ok(true) - } else { - child.block_body(&key) - }; - let rest = if matches!(handled, Ok(true)) { child.rest() } else { Ok(()) }; - self.adopt(&mut child); - rest?; - if !matches!(handled, Ok(true)) { - // A body that was not transcoded leaves nothing: it is copied as stored or dropped. - self.out.truncate(data_at); - } - // Padding: the smallest k in 0..=3 after which the next block (or the end) starts. - let rest = self.r.peek_rest(); - let pad = (0..=3usize).find(|&k| k == rest.len() || (k < rest.len() && is_sig(&rest[k..], self.from.is_little()))).unwrap_or(0); - let pad_bytes = self.r.bytes(pad)?; - match handled { - Ok(true) => { - self.warnings.append(&mut child.warnings); - self.patch_len(len_at, long, (self.out.len() - data_at) as u64)?; - self.out.extend_from_slice(pad_bytes); - } - Ok(false) if self.same_order() => { - self.patch_len(len_at, long, data.len() as u64)?; - self.out.extend_from_slice(data); - self.out.extend_from_slice(pad_bytes); - } - // Little-endian in, big-endian model: keep the bytes as they are, marked. - Ok(false) if self.from.is_little() => { - let marker: &[u8; 4] = if &sig == b"8B64" { b"46B8" } else { b"MIB8" }; - self.out[sig_at..sig_at + 4].copy_from_slice(marker); - self.patch_len(len_at, long, data.len() as u64)?; - self.out.extend_from_slice(data); - self.out.extend_from_slice(pad_bytes); - } - Ok(false) => { - self.out.truncate(before); - self.warnings.push(format!( - "{} block ({} bytes) dropped: its layout is unknown and cannot be converted to the file's byte order", - String::from_utf8_lossy(&key), - data.len() - )); - } - Err(e) if self.same_order() => return Err(PsdError::invalid(format!("{} block: {e}", String::from_utf8_lossy(&key)))), - Err(e) if self.from.is_little() => { - let marker: &[u8; 4] = if &sig == b"8B64" { b"46B8" } else { b"MIB8" }; - self.out[sig_at..sig_at + 4].copy_from_slice(marker); - self.patch_len(len_at, long, data.len() as u64)?; - self.out.extend_from_slice(data); - self.out.extend_from_slice(pad_bytes); - self.warnings.push(format!("{} block ({} bytes) kept as stored, in little-endian layout: {e}", String::from_utf8_lossy(&key), data.len())); - } - Err(e) => { - self.out.truncate(before); - self.warnings.push(format!("{} block ({} bytes) dropped: {e}", String::from_utf8_lossy(&key), data.len())); - } - } - Ok(()) - } - - /// Transcodes a block's data by key. `Ok(false)` for keys without a known layout. - fn block_body(&mut self, key: &[u8; 4]) -> Result { - match key { - b"Layr" | b"Lr16" | b"Lr32" => self.layer_info()?, - b"luni" => self.unicode()?, - b"lsct" | b"lsdk" => { - self.u32()?; - if self.remaining() >= 8 { - self.key()?; - self.key()?; - } - if self.remaining() >= 4 { - self.u32()?; - } - } - // lyvr layer version, sn2P and vowv (shape and vector flags). - b"lyid" | b"lspf" | b"lyvr" | b"sn2P" | b"vowv" => { - self.u32()?; - } - // Text-engine global data: a textual structure, no byte order. - b"Txt2" => self.rest()?, - b"lnsr" => { - self.key()?; - } - // Advanced Blending flags and fill opacity: one byte, then padding (Adobe spec, - // "Additional Layer Information"; `lmgm`/`vmgm` = layer/vector mask hides effects). - b"clbl" | b"infx" | b"knko" | b"tsly" | b"lmgm" | b"vmgm" | b"iOpa" => { - self.u8()?; - } - b"lclr" => self.u16s_upto(4)?, - b"fxrp" => { - while self.remaining() >= 8 { - self.f64()?; - } - } - b"brst" => self.u32s_to_end()?, - b"LMsk" => self.u16s_upto(6)?, - b"FMsk" => self.u16s_to_end()?, - b"shmd" => self.metadata_setting()?, - // Effects (lfxs: the effects as applied to a group), content credentials (CAI). - b"lfx2" | b"lmfx" | b"lfxs" | b"CAI " => { - self.u32()?; - self.versioned_descriptor()?; - } - b"SoCo" | b"GdFl" | b"PtFl" | b"vstk" | b"blwh" | b"vibA" | b"CgEd" | b"artb" | b"artd" | b"cinf" | b"cust" | b"PxSD" | b"GenI" | b"OCIO" - | b"extn" | b"pths" => { - self.versioned_descriptor()?; - } - // Color Lookup: u16 version, then the descriptor. - b"clrL" => { - self.u16()?; - self.versioned_descriptor()?; - } - b"lnk2" | b"lnk3" | b"lnkD" | b"lnkE" => self.linked_layers()?, - b"Anno" => self.annotations()?, - b"vogk" => { - self.u32()?; - self.versioned_descriptor()?; - } - b"vscg" => { - self.key()?; - self.versioned_descriptor()?; - } - b"SoLd" | b"SoLE" => { - self.key()?; - self.u32()?; - self.versioned_descriptor()?; - } - b"PlLd" => { - self.key()?; - self.u32()?; - self.pascal(1)?; - for _ in 0..4 { - self.u32()?; - } - self.f64s(8)?; - self.u32()?; - self.versioned_descriptor()?; - } - // Type: version, transform, text version + descriptor, warp version + descriptor, - // and the bounds as four 32-bit values (the specification says doubles; Photoshop - // writes 16 bytes). - b"TySh" => self.type_layer()?, - b"vmsk" | b"vsms" => { - self.u32()?; - self.u32()?; - self.path_records()?; - } - b"Patt" | b"Pat2" | b"Pat3" => { - while self.remaining() >= 4 { - let len = self.r.clone().u32()?; - if len == 0 { - self.u32()?; - continue; - } - self.sized_region(false, Tx::pattern)?; - // Each pattern is padded to a multiple of 4. - let pad = ((4 - len % 4) % 4) as usize; - self.raw(pad.min(self.remaining()))?; - } - } - b"FEid" | b"FXid" => self.filter_effects()?, - b"lrFX" => self.legacy_effects()?, - b"levl" => { - self.u16()?; - for _ in 0..29 * 5 { - if self.remaining() < 2 { - break; - } - self.u16()?; - } - if self.remaining() >= 4 { - self.key()?; - } - self.u16s_to_end()?; - } - b"curv" => self.curves()?, - b"hue2" => { - self.u16()?; - self.u8()?; - self.u8()?; - self.u16s_to_end()?; - } - b"brit" => self.u16s_upto(3)?, - b"thrs" | b"post" => { - self.u16()?; - } - b"nvrt" => {} - b"expA" => { - self.u16()?; - for _ in 0..3 { - self.f32()?; - } - } - b"blnc" => self.u16s_upto(9)?, - b"mixr" | b"selc" => self.u16s_to_end()?, - b"phfl" => match self.u16()? { - 2 => { - self.u16s(5)?; - self.u32()?; - self.u8()?; - } - 3 => { - for _ in 0..4 { - self.u32()?; - } - self.u8()?; - } - v => return Err(PsdError::Unsupported(format!("photo filter version {v}"))), - }, - b"grdm" => self.gradient_map()?, - _ if !self.same_order() => return Ok(self.descriptor_shaped()), - _ => return Ok(false), - } - Ok(true) - } - - /// `lnk2` / `lnk3` / `lnkD` / `lnkE` (linked and embedded smart-object files): items of - /// u64 length + data, each padded to 4. Item: type (`liFD` embedded, `liFE` external, - /// `liFA` alias), version 1–7, Pascal uuid, Unicode name, file type and creator keys, u64 - /// data length, open-descriptor flag (+ descriptor), per-type fields, the file bytes for - /// `liFD`, then the fields later versions added. - fn linked_layers(&mut self) -> Result<()> { - while self.remaining() >= 8 { - let len = self.r.clone().u64()?; - self.sized_region(true, |t| { - let kind = t.key()?; - let version = t.u32()?; - t.pascal(1)?; - t.unicode()?; - t.key()?; - t.key()?; - let data_len = t.u64()?; - if t.u8()? != 0 { - t.versioned_descriptor()?; - } - if &kind == b"liFE" && version > 3 { - t.i32()?; - for _ in 0..4 { - t.u8()?; - } - t.f64()?; - } - if &kind == b"liFE" { - t.u64()?; - } - if &kind == b"liFA" { - t.raw(8)?; - } - let data_len = usize::try_from(data_len).map_err(|_| PsdError::LimitExceeded("linked file length"))?; - if &kind == b"liFD" { - t.raw(data_len)?; - } - if version >= 5 { - t.unicode()?; - } - if version >= 6 { - t.f64()?; - } - if version >= 7 { - t.u8()?; - } - if &kind == b"liFE" && version == 2 { - t.raw(data_len)?; - } - Ok(()) - })?; - let pad = ((4 - len % 4) % 4) as usize; - self.raw(pad.min(self.remaining()))?; - } - Ok(()) - } - - /// `Anno`: u16 major, u16 minor, u32 count, then per annotation a self-counting u32 - /// length, type key, open and flags bytes, u16 optional blocks, icon and popup rects, a - /// colour, three even-padded Pascal strings, and a self-counting data block (key, u32 - /// size, text with its own byte-order mark). - fn annotations(&mut self) -> Result<()> { - self.u16()?; - self.u16()?; - let n = self.u32()?; - for _ in 0..n { - if self.remaining() < 4 { - break; - } - self.sized_region_inclusive(|t| { - t.key()?; - t.u8()?; - t.u8()?; - t.u16()?; - t.i32s(8)?; - t.u16s(5)?; - t.pascal(2)?; - t.pascal(2)?; - t.pascal(2)?; - t.sized_region_inclusive(|d| { - d.key()?; - d.u32()?; - Ok(()) - }) - })?; - } - Ok(()) - } - - // ---- layer info ---- - - fn layer_info(&mut self) -> Result<()> { - let count = self.i16()?; - let n = usize::from(count.unsigned_abs()); - self.r.check_count(n as u64, 34)?; - // Per layer: the channel ids and lengths, and the heights of the layer, mask and - // real-mask rects (what each channel's RLE count table spans). - let mut records: Vec = Vec::with_capacity(n); - for _ in 0..n { - let top = self.i32()?; - self.i32()?; - let bottom = self.i32()?; - self.i32()?; - let nch = self.u16()?; - if nch > crate::layer::MAX_LAYER_CHANNELS { - return Err(PsdError::LimitExceeded("too many channels in layer")); - } - let mut chans = Vec::with_capacity(usize::from(nch)); - let psb = self.version.is_psb(); - for _ in 0..nch { - let id = self.i16()?; - let len = self.len(psb)?; - chans.push((id, len)); - } - let sig = self.key()?; - if &sig != b"8BIM" { - return Err(PsdError::InvalidSignature { expected: "8BIM (layer blend mode)", found: sig }); - } - self.key()?; - for _ in 0..4 { - self.u8()?; - } - let mut heights = [height(top, bottom), 0, 0]; - let mut mask_heights = (0usize, 0usize); - self.sized_region(false, |t| { - let mut mh = (0, 0); - t.sized_region(false, |m| { - mh = m.mask()?; - Ok(()) - })?; - mask_heights = mh; - // Blending ranges are bytes (black low/high, white low/high per channel), so - // Photoshop stores them in the same order in either byte order: an Intel-order - // layered TIFF holds the default ranges as `00 00 ff ff`. Swapping them as u32s - // turned every range into `ff ff 00 00`, which hides every pixel of the layer. - t.sized_region(false, |x| x.rest())?; - t.pascal(4)?; - t.blocks() - })?; - heights[1] = mask_heights.0; - heights[2] = mask_heights.1; - records.push((chans, heights)); - } - for (chans, heights) in &records { - for &(id, len) in chans { - if len == 0 { - continue; - } - if len == 1 { - return Err(PsdError::invalid("channel data length 1")); - } - let rows = match id { - -2 => heights[1], - -3 => heights[2], - _ => heights[0], - }; - self.region(len, |t| t.channel_data(rows, false))?; - } - } - self.rest() - } - - /// A layer mask record. Returns the heights of the mask and real-mask rects. - fn mask(&mut self) -> Result<(usize, usize)> { - let whole = self.r.peek_rest(); - if whole.is_empty() { - return Ok((0, 0)); - } - let top = self.i32()?; - self.i32()?; - let bottom = self.i32()?; - self.i32()?; - self.u8()?; - let flags = self.u8()?; - let mut real_h = 0; - if self.remaining() <= 2 { - return Ok((height(top, bottom), 0)); - } - let has_parameters = flags & LayerMask::FLAG_PARAMETERS != 0; - // The helper only looks at lengths and the parameter-flags byte, so it reads the - // same in either order. - let real_first = has_parameters && LayerMask::real_before_parameters(whole); - let mut read_real = |t: &mut Tx<'_>| -> Result<()> { - if t.remaining() >= 18 { - t.u8()?; - t.u8()?; - let rt = t.i32()?; - t.i32()?; - let rb = t.i32()?; - t.i32()?; - real_h = height(rt, rb); - } - Ok(()) - }; - if real_first { - read_real(self)?; - } - if has_parameters { - let pf = self.u8()?; - let need = mask_parameter_bytes(pf); - if need > self.remaining() { - return Err(PsdError::UnexpectedEof { offset: self.r.pos(), needed: need - self.remaining() }); - } - if pf & 1 != 0 { - self.u8()?; - } - if pf & 2 != 0 { - self.f64()?; - } - if pf & 4 != 0 { - self.u8()?; - } - if pf & 8 != 0 { - self.f64()?; - } - } - if !real_first { - read_real(self)?; - } - Ok((height(top, bottom), real_h)) - } - - // ---- descriptors ---- - - /// Photoshop's Intel-order TIFF type blocks can use PSD byte order for the - /// text descriptor, then container order again for warp and bounds (#4758). - fn type_layer(&mut self) -> Result<()> { - self.u16()?; - self.f64s(6)?; - self.type_descriptor(50, ByteOrder::Big)?; - self.type_descriptor(1, self.to)?; - self.i32s(4) - } - - fn type_descriptor(&mut self, version: u16, to: ByteOrder) -> Result<()> { - let [hi, lo] = version.to_be_bytes(); - let from = if self.from.is_little() && self.r.peek_rest().starts_with(&[hi, lo, 0, 0, 0, 16]) { ByteOrder::Big } else { self.from }; - let data = self.r.peek_rest(); - let mut descriptor = Tx::new(data, self.version, from, to); - descriptor.depth = self.depth; - descriptor.u16()?; - descriptor.versioned_descriptor()?; - let used = data.len() - descriptor.remaining(); - self.r.bytes(used)?; - self.warnings.append(&mut descriptor.warnings); - self.out.extend_from_slice(&descriptor.out); - Ok(()) - } - - fn versioned_descriptor(&mut self) -> Result<()> { - self.u32()?; - self.descriptor() - } - - fn descriptor(&mut self) -> Result<()> { - if self.depth > MAX_DEPTH { - return Err(PsdError::LimitExceeded("descriptor nesting too deep")); - } - self.depth += 1; - self.unicode()?; - self.id()?; - let n = self.u32()?; - self.r.check_count(u64::from(n), 10)?; - for _ in 0..n { - self.id()?; - self.value()?; - } - self.depth -= 1; - Ok(()) - } - - fn id(&mut self) -> Result<()> { - let n = self.u32()?; - if n == 0 { - self.key()?; - } else { - self.raw(usize::try_from(n).map_err(|_| PsdError::LimitExceeded("id length"))?)?; - } - Ok(()) - } - - fn class(&mut self) -> Result<()> { - self.unicode()?; - self.id() - } - - fn value(&mut self) -> Result<()> { - if self.depth > MAX_DEPTH { - return Err(PsdError::LimitExceeded("descriptor nesting too deep")); - } - let ty = self.key()?; - match &ty { - b"obj " => { - let n = self.u32()?; - self.r.check_count(u64::from(n), 8)?; - for _ in 0..n { - self.reference_item()?; - } - } - b"Objc" | b"GlbO" => self.descriptor()?, - b"VlLs" => { - let n = self.u32()?; - self.r.check_count(u64::from(n), 4)?; - self.depth += 1; - for _ in 0..n { - self.value()?; - } - self.depth -= 1; - } - b"doub" => { - self.f64()?; - } - b"UntF" => { - self.key()?; - self.f64()?; - } - b"UnFl" => { - self.key()?; - let n = self.u32()?; - self.r.check_count(u64::from(n), 8)?; - self.f64s(n as usize)?; - } - b"TEXT" => self.unicode()?, - b"enum" => { - self.id()?; - self.id()?; - } - b"long" => { - self.i32()?; - } - b"comp" => { - self.i64()?; - } - b"bool" => { - self.u8()?; - } - b"type" | b"GlbC" => self.class()?, - b"alis" | b"Pth " | b"tdta" => { - let n = self.u32()?; - self.raw(usize::try_from(n).map_err(|_| PsdError::LimitExceeded("descriptor data length"))?)?; - } - b"ObAr" => { - self.u32()?; - self.descriptor()?; - } - other => return Err(PsdError::Unsupported(format!("descriptor OSType {:?}", String::from_utf8_lossy(other)))), - } - Ok(()) - } - - fn reference_item(&mut self) -> Result<()> { - let ty = self.key()?; - match &ty { - b"prop" => { - self.class()?; - self.id()?; - } - b"Clss" => self.class()?, - b"Enmr" => { - self.class()?; - self.id()?; - self.id()?; - } - b"rele" => { - self.class()?; - self.i32()?; - } - b"Idnt" | b"indx" => { - self.class()?; - self.u32()?; - } - b"name" => { - self.class()?; - self.unicode()?; - } - other => return Err(PsdError::Unsupported(format!("reference item type {:?}", String::from_utf8_lossy(other)))), - } - Ok(()) - } - - // ---- other block layouts ---- - - /// `shmd`: u32 count, then per item signature, key, copy flag, 3 bytes, u32 length, data. - /// An item whose layout is unknown is dropped on its own (and the count patched) rather - /// than taking the whole block with it. - fn metadata_setting(&mut self) -> Result<()> { - let n = self.r.u32()?; - self.r.check_count(u64::from(n), 16)?; - let count_at = self.out.len(); - self.out.extend_from_slice(&[0; 4]); - let mut kept = 0u32; - for _ in 0..n { - let before = self.out.len(); - self.key()?; - let key = self.key()?; - self.u8()?; - self.raw(3)?; - let same = self.same_order(); - let res = self.sized_region(false, |t| match &key { - b"cmls" | b"mlst" | b"cust" | b"tmln" | b"sgrp" | b"cinf" => t.versioned_descriptor(), - // mdyn (dynamic metadata) is one u32. - b"mdyn" => t.u32s_to_end(), - _ if same => Ok(()), - _ if t.descriptor_shaped() => Ok(()), - _ => Err(PsdError::Unsupported(format!("metadata item {:?}", String::from_utf8_lossy(&key)))), - }); - match res { - Ok(()) => kept += 1, - Err(e) if same => return Err(e), - Err(e) => { - self.out.truncate(before); - self.warnings.push(format!("shmd item {} dropped: {e}", String::from_utf8_lossy(&key))); - } - } - } - self.patch_len(count_at, false, u64::from(kept)) - } - - /// 26-byte path records: a u16 selector then, for knots, six fixed-point coordinates. - fn path_records(&mut self) -> Result<()> { - while self.remaining() >= 26 { - let selector = self.u16()?; - match selector { - 1 | 2 | 4 | 5 => self.i32s(6)?, - // Length records: knot count, path operation, then fields Photoshop writes as - // 16-bit values (zero in practice). - 0 | 3 => self.u16s(12)?, - // Clipboard: four fixed-point coordinates and a resolution. - 7 => { - self.i32s(5)?; - self.raw(4)?; - } - 8 => { - self.u16()?; - self.raw(22)?; - } - _ => self.raw(24)?, - } - } - Ok(()) - } - - /// One pattern of a `Patt` block (the data after its u32 length). - fn pattern(t: &mut Tx<'_>) -> Result<()> { - t.u32()?; - let mode = t.u32()?; - t.u16()?; - t.u16()?; - t.unicode()?; - t.pascal(1)?; - if mode == 2 { - t.raw(768)?; - // Some writers follow the palette with 4 extra bytes before the array list version. - let next_is_version = t.r.clone().u32().is_ok_and(|v| v == 3); - if !next_is_version && t.remaining() >= 4 { - t.raw(4)?; - } - } - t.u32()?; - t.sized_region(false, |v| { - v.i32s(4)?; - let count = v.u32()?; - for _ in 0..count.saturating_add(2) { - if v.remaining() < 4 { - break; - } - if v.u32()? == 0 { - continue; - } - if v.r.clone().u32()? == 0 { - v.u32()?; - continue; - } - v.sized_region(false, |c| { - c.u32()?; - let ct = c.i32()?; - c.i32()?; - let cb = c.i32()?; - c.i32()?; - c.u16()?; - let comp = c.u8()?; - if comp == 1 { - let saved = c.version; - c.version = Version::Psd; - let res = c.rle_counts(height(ct, cb)); - c.version = saved; - res?; - } - Ok(()) - })?; - } - Ok(()) - }) - } - - /// `FEid` / `FXid`: version, then one section per smart object (u64 length, items with - /// per-channel planes and 4-byte RLE counts), each padded to 4 bytes. - fn filter_effects(&mut self) -> Result<()> { - self.u32()?; - loop { - let len = self.r.clone().len_field(true)?; - self.filter_effects_section()?; - // Mirrors `FilterEffects::parse`: the last section's padding may be cut short. - let pad = usize::try_from((4 - len % 4) % 4).unwrap_or(0).min(self.remaining()); - self.raw(pad)?; - let rest = self.r.peek_rest(); - if rest.len() <= 3 && rest.iter().all(|&b| b == 0) { - return Ok(()); - } - if rest.len() < 8 { - return Err(PsdError::invalid(format!("filter effects: {} unexpected bytes after the data", rest.len()))); - } - } - } - - fn filter_effects_section(&mut self) -> Result<()> { - self.sized_region(true, |t| { - while !t.r.is_empty() { - t.pascal(1)?; - t.u32()?; - t.sized_region(true, |it| { - let top = it.i32()?; - it.i32()?; - let bottom = it.i32()?; - it.i32()?; - let rect_h = height(top, bottom); - it.u32()?; - let max = it.u32()?; - if max > crate::filter_effects::MAX_SLOTS { - return Err(PsdError::LimitExceeded("filter effects: too many channels")); - } - for _ in 0..max + 2 { - if it.u32()? != 0 { - it.effects_plane(rect_h)?; - } - } - Ok(()) - })?; - if !t.r.is_empty() && t.u8()? != 0 { - let top = t.i32()?; - t.i32()?; - let bottom = t.i32()?; - t.i32()?; - t.effects_plane(height(top, bottom))?; - } - } - Ok(()) - }) - } - - fn effects_plane(&mut self, rows: usize) -> Result<()> { - self.sized_region(true, |p| p.channel_data(rows, true)) - } - - /// `lrFX`: version, count, then effects (`cmnS`, `dsdw`, `isdw`, `oglw`, `iglw`, `bevl`, - /// `sofi`), each a signature, key, u32 size and fixed fields. - fn legacy_effects(&mut self) -> Result<()> { - self.u16()?; - let n = self.u16()?; - for _ in 0..n { - if self.remaining() < 12 { - break; - } - self.key()?; - let key = self.key()?; - self.sized_region(false, |t| { - // A colour: u16 space + 4 × u16 components. - let colour = |t: &mut Tx<'_>| t.u16s(5); - let blend = |t: &mut Tx<'_>| -> Result<()> { - t.key()?; - t.key()?; - Ok(()) - }; - match &key { - b"cmnS" => { - t.u32()?; - t.u8()?; - t.u16()?; - } - b"dsdw" | b"isdw" => { - t.u32()?; - t.i32s(4)?; - colour(t)?; - blend(t)?; - t.u8()?; - t.u8()?; - t.u8()?; - if t.remaining() >= 10 { - colour(t)?; - } - } - b"oglw" => { - t.u32()?; - t.i32s(2)?; - colour(t)?; - blend(t)?; - t.u8()?; - t.u8()?; - if t.remaining() >= 10 { - colour(t)?; - } - } - b"iglw" => { - t.u32()?; - t.i32s(2)?; - colour(t)?; - blend(t)?; - t.u8()?; - t.u8()?; - if t.remaining() >= 11 { - t.u8()?; - colour(t)?; - } - } - b"bevl" => { - t.u32()?; - t.i32s(3)?; - blend(t)?; - blend(t)?; - colour(t)?; - colour(t)?; - for _ in 0..6 { - t.u8()?; - } - if t.remaining() >= 20 { - colour(t)?; - colour(t)?; - } - } - b"sofi" => { - t.u32()?; - blend(t)?; - colour(t)?; - t.u8()?; - t.u8()?; - if t.remaining() >= 10 { - colour(t)?; - } - } - _ => {} - } - Ok(()) - })?; - } - Ok(()) - } - - /// `curv`: pad byte, version, channel bitmap, per set bit a point list; then an optional - /// `Crv ` extension with per-channel point lists. - fn curves(&mut self) -> Result<()> { - self.u8()?; - self.u16()?; - let bits = self.u32()?; - for bit in 0..32 { - if bits & (1 << bit) == 0 { - continue; - } - if self.remaining() < 2 { - break; - } - let n = self.u16()?; - self.u16s(usize::from(n) * 2)?; - } - if self.remaining() >= 10 { - self.key()?; - self.u16()?; - let n = self.u32()?; - for _ in 0..n { - if self.remaining() < 4 { - break; - } - self.u16()?; - let pts = self.u16()?; - self.u16s(usize::from(pts) * 2)?; - } - } - Ok(()) - } - - /// `grdm`: version, reverse, dither, [method key], name, colour stops, transparency - /// stops, then the noise-gradient fields (a u32 seed among u16s). - fn gradient_map(&mut self) -> Result<()> { - let version = self.u16()?; - self.u8()?; - self.u8()?; - if version == 3 { - self.key()?; - } - self.unicode()?; - let n = self.u16()?; - for _ in 0..n { - if self.remaining() < 20 { - break; - } - self.u32()?; - self.u32()?; - self.u16s(6)?; - } - let nt = self.u16()?; - for _ in 0..nt { - if self.remaining() < 10 { - break; - } - self.u32()?; - self.u32()?; - self.u16()?; - } - // expansion, interpolation, length, mode, u32 seed, then u16 fields. - for _ in 0..4 { - if self.remaining() < 2 { - return Ok(()); - } - self.u16()?; - } - if self.remaining() >= 4 { - self.u32()?; - } - self.u16s_to_end() - } - } -} +pub mod transcode; #[cfg(test)] -mod tests { - use super::transcode::*; - use super::*; - use crate::compression::Compression; - use crate::descriptor::{Descriptor, Id, UnicodeString, Value, VersionedDescriptor}; - use crate::header::ColorMode; - use crate::testgen; - - /// Keys the generator plants that the transcoder (rightly) does not know. - const UNKNOWN: [&[u8; 4]; 3] = [b"zOdd", b"zNop", b"Txt2"]; - - /// `d` without the blocks a little-endian round trip drops, and without the layer-info - /// padding (which follows the body length, so it changes when blocks are dropped). - fn known(d: &ImageSourceData) -> ImageSourceData { - let mut d = d.clone(); - d.byte_order = ByteOrder::Big; - d.global_blocks.retain(|b| !UNKNOWN.contains(&&b.key)); - if d.layer_info.is_none() { - d.layer_info_key = *b"Layr"; - } - if let Some(info) = &mut d.layer_info { - info.padding = None; - for l in &mut info.layers { - l.blocks.retain(|b| !UNKNOWN.contains(&&b.key)); - } - } - d - } - - fn roundtrip(d: &ImageSourceData) -> ImageSourceData { - let (big, w) = d.to_bytes(ByteOrder::Big).unwrap(); - assert!(w.is_empty(), "{w:?}"); - let (little, w) = d.to_bytes(ByteOrder::Little).unwrap(); - assert!(w.iter().all(|w| UNKNOWN.iter().any(|k| w.starts_with(std::str::from_utf8(*k).unwrap()))), "{w:?}"); - if w.is_empty() { - assert_eq!(big.len(), little.len()); - } - if big.len() > 36 { - assert_ne!(big, little); - assert!(little[36..].starts_with(b"MIB8")); - } - let (back_big, w) = ImageSourceData::from_bytes(&big).unwrap(); - assert!(w.is_empty(), "{w:?}"); - let (back_little, w) = ImageSourceData::from_bytes(&little).unwrap(); - assert!(w.is_empty(), "{w:?}"); - if little.len() > 36 { - assert_eq!(back_little.byte_order, ByteOrder::Little); - } - assert_eq!(known(&back_little), known(&back_big)); - // The little-endian bytes are a fixed point (from the second generation on when blocks - // were dropped, since the layer-info padding then follows the shorter body). - let (little2, _) = back_little.to_bytes(ByteOrder::Little).unwrap(); - let little3 = ImageSourceData::from_bytes(&little2).unwrap().0.to_bytes(ByteOrder::Little).unwrap().0; - assert_eq!(little3, little2); - back_big - } - - #[test] - fn generated_files_survive_both_orders() { - for case in testgen::all_cases() { - let d = ImageSourceData::from_psd(&case.file); - let back = roundtrip(&d); - assert_eq!(back.version, d.version, "{}", case.name); - assert_eq!(known(&back), known(&d), "{}", case.name); - // Nothing but the planted unknown blocks is lost on the little-endian path. - let (little, _) = d.to_bytes(ByteOrder::Little).unwrap(); - let (back, _) = ImageSourceData::from_bytes(&little).unwrap(); - assert_eq!(known(&back), known(&d), "{}", case.name); - } - } - - #[test] - fn same_order_transcoding_is_the_identity() { - for case in testgen::all_cases() { - let d = ImageSourceData::from_psd(&case.file); - let (big, _) = d.to_bytes(ByteOrder::Big).unwrap(); - let (same, w) = transcode_blocks(&big[36..], d.version, ByteOrder::Big, ByteOrder::Big).unwrap(); - assert!(w.is_empty()); - assert_eq!(same, big[36..].to_vec(), "{}", case.name); - } - } - - fn sample_layers() -> ImageSourceData { - let file = testgen::layered(Version::Psd, ColorMode::Rgb, 8, Compression::Rle); - ImageSourceData::from_psd(&file) - } - - #[test] - fn signature_selects_the_version() { - let mut d = sample_layers(); - let (b, _) = d.to_bytes(ByteOrder::Big).unwrap(); - assert!(b.starts_with(SIGNATURE)); - d.version = Version::Psb; - let (b, _) = d.to_bytes(ByteOrder::Big).unwrap(); - assert!(b.starts_with(SIGNATURE_PSB)); - assert_eq!(ImageSourceData::from_bytes(&b).unwrap().0.version, Version::Psb); - roundtrip(&d); - } - - #[test] - fn layer_key_follows_depth() { - assert_eq!(layer_info_key(8), *b"Layr"); - assert_eq!(layer_info_key(16), *b"Lr16"); - assert_eq!(layer_info_key(32), *b"Lr32"); - for (depth, comp) in [(16, Compression::ZipPrediction), (32, Compression::ZipPrediction), (16, Compression::Rle)] { - let file = testgen::layered(Version::Psd, ColorMode::Rgb, depth, comp); - let d = ImageSourceData::from_psd(&file); - assert_eq!(d.layer_info_key, layer_info_key(depth)); - let back = roundtrip(&d); - assert_eq!(back.layer_info_key, d.layer_info_key); - // The 16/32-bit model goes back into a PSD as a global block, like Photoshop's. - let psd = back.into_psd(file.header.clone(), file.resources.clone(), file.image_data.clone()); - assert!(matches!(psd.layer_info_placement, LayerInfoPlacement::GlobalBlock { .. })); - let again = PsdFile::from_bytes(&psd.to_bytes().unwrap()).unwrap(); - assert_eq!(known(&ImageSourceData::from_psd(&again)).layer_info, known(&d).layer_info); - let (little, _) = d.to_bytes(ByteOrder::Little).unwrap(); - let (back, _) = ImageSourceData::from_bytes(&little).unwrap(); - assert_eq!(known(&back).layer_info, known(&d).layer_info, "depth {depth}"); - } - } - - #[test] - fn blocks_are_padded_to_four() { - let d = sample_layers(); - let (b, _) = d.to_bytes(ByteOrder::Big).unwrap(); - let mut at = 36; - while at < b.len() { - assert_eq!(&b[at..at + 4], b"8BIM"); - let len = u32::from_be_bytes(b[at + 8..at + 12].try_into().unwrap()) as usize; - at += 12 + len; - at += (4 - at % 4) % 4; - } - assert_eq!(at, b.len()); - } - - fn block_rt(key: [u8; 4], data: Vec) -> (Vec, Vec) { - let d = ImageSourceData { global_blocks: vec![TaggedBlock::new(key, data.clone())], ..Default::default() }; - let (big, _) = d.to_bytes(ByteOrder::Big).unwrap(); - let (little, w) = d.to_bytes(ByteOrder::Little).unwrap(); - assert!(w.is_empty(), "{w:?}"); - let (back, w) = ImageSourceData::from_bytes(&little).unwrap(); - assert!(w.is_empty(), "{w:?}"); - assert_eq!(back.global_blocks[0].data, data); - assert_eq!(back.to_bytes(ByteOrder::Big).unwrap().0, big); - (big, little) - } - - #[test] - fn descriptor_blocks_swap_keys_and_numbers() { - let mut desc = Descriptor::new("null"); - desc.items.push((Id::new("Opct"), Value::UnitFloat { unit: *b"#Prc", value: 75.5 })); - desc.items.push((Id::new("Nm "), Value::Text(UnicodeString::new_nul("Drop Shadow")))); - desc.items.push((Id::new("enab"), Value::Boolean(true))); - desc.items.push((Id::new("Md "), Value::Enumerated { type_id: Id::new("BlnM"), value: Id::new("Mltp") })); - desc.items.push((Id::new("list"), Value::List(vec![Value::Integer(-3), Value::Double(1.5), Value::LargeInteger(7)]))); - desc.items.push((Id::new("longKeyName"), Value::Descriptor(Descriptor::new("innr")))); - let mut data = 0u32.to_be_bytes().to_vec(); - data.extend(VersionedDescriptor::new(desc).to_bytes()); - let (big, little) = block_rt(*b"lfx2", data); - // Keys are reversed and the version field swapped in the little-endian bytes. - assert!(little[36..].starts_with(b"MIB82xfl")); - let body_at = 48; - assert_eq!(&little[body_at..body_at + 4], &[0, 0, 0, 0]); - assert_eq!(&little[body_at + 4..body_at + 8], &[16, 0, 0, 0]); - assert_eq!(&big[body_at + 4..body_at + 8], &[0, 0, 0, 16]); - assert!(little.windows(4).any(|w| w == b"crP#"), "unit key reversed"); - assert!(little.windows(11).any(|w| w == b"longKeyName"), "string ids are not reversed"); - } - - #[test] - fn descriptor_references_by_identifier_and_index_keep_their_class() { - use crate::descriptor::{Class, ReferenceItem}; - let class = || Class { name: UnicodeString::new(""), class_id: Id::new("Lyr ") }; - let desc = Descriptor::new("null") - .with("null", Value::Reference(vec![ReferenceItem::Identifier { class: class(), id: 7 }, ReferenceItem::Index { class: class(), index: 2 }])); - let mut data = 0u32.to_be_bytes().to_vec(); - data.extend(VersionedDescriptor::new(desc).to_bytes()); - block_rt(*b"lfx2", data); - } - - fn type_layer_data() -> Vec { - let mut data = Vec::new(); - data.put_u16(1); - for value in [1.5, 0.0, -0.25, 1.75, 12.5, -3.25] { - data.put_f64(value); - } - data.put_u16(50); - let text = Descriptor::new("TxLr").with("Txt ", Value::Text(UnicodeString::new_nul("Synthetic Ω 🦀"))); - data.extend(VersionedDescriptor::new(text).to_bytes()); - data.put_u16(1); - data.extend(VersionedDescriptor::new(Descriptor::new("warp")).to_bytes()); - for value in [11, -22, 333, 4_444] { - data.put_i32(value); - } - data - } - - fn tagged_payload<'a>(bytes: &'a [u8], signature_and_key: &[u8; 8], little: bool) -> &'a [u8] { - let block_at = bytes.windows(8).position(|window| window == signature_and_key).expect("tagged block"); - let length_at = block_at + 8; - let length_bytes: [u8; 4] = bytes.get(length_at..length_at + 4).expect("tagged block length").try_into().expect("four-byte length"); - let length = if little { u32::from_le_bytes(length_bytes) } else { u32::from_be_bytes(length_bytes) }; - let data_at = length_at + 4; - let data_end = data_at + usize::try_from(length).expect("test block length fits usize"); - bytes.get(data_at..data_end).expect("tagged block payload") - } - - fn legacy_little_endian_type_block() -> Vec { - let mut tysh = Vec::new(); - tysh.extend_from_slice(&1u16.to_le_bytes()); - for value in [1.5f64, 0.0, -0.25, 1.75, 12.5, -3.25] { - tysh.extend_from_slice(&value.to_le_bytes()); - } - tysh.extend_from_slice(&50u16.to_le_bytes()); - // Independently encode a little-endian `VersionedDescriptor` with a single TEXT value. - tysh.extend_from_slice(&16u32.to_le_bytes()); - tysh.extend_from_slice(&0u32.to_le_bytes()); // empty descriptor name - tysh.extend_from_slice(&0u32.to_le_bytes()); // four-character class id - tysh.extend_from_slice(b"rLxT"); // little-endian four-character class id - tysh.extend_from_slice(&1u32.to_le_bytes()); // one item - tysh.extend_from_slice(&0u32.to_le_bytes()); // four-character key - tysh.extend_from_slice(b" txT"); // little-endian four-character key - tysh.extend_from_slice(b"TXET"); // little-endian OSType - let mut units: Vec = "Synthetic Ω 🦀".encode_utf16().collect(); - units.push(0); // `new_nul`, matching the canonical fixture - tysh.extend_from_slice(&u32::try_from(units.len()).expect("short test string").to_le_bytes()); - for unit in units { - tysh.extend_from_slice(&unit.to_le_bytes()); - } - tysh.extend_from_slice(&1u16.to_le_bytes()); - // Empty warp descriptor, also encoded independently in little-endian order. - tysh.extend_from_slice(&16u32.to_le_bytes()); - tysh.extend_from_slice(&0u32.to_le_bytes()); // empty descriptor name - tysh.extend_from_slice(&4u32.to_le_bytes()); // `warp` is a four-byte string id - tysh.extend_from_slice(b"warp"); - tysh.extend_from_slice(&0u32.to_le_bytes()); // no items - for value in [11i32, -22, 333, 4_444] { - tysh.extend_from_slice(&value.to_le_bytes()); - } - - let mut image_source = super::SIGNATURE.to_vec(); - image_source.extend_from_slice(b"MIB8hSyT"); - image_source.extend_from_slice(&u32::try_from(tysh.len()).expect("short test block").to_le_bytes()); - image_source.extend_from_slice(&tysh); - let padding = (4 - tysh.len() % 4) % 4; - image_source.resize(image_source.len() + padding, 0); - image_source - } - - #[test] - fn type_block_write_keeps_text_descriptor_in_psd_order() { - let canonical = type_layer_data(); - let source = ImageSourceData { global_blocks: vec![TaggedBlock::new(*b"TySh", canonical.clone())], ..Default::default() }; - - let (little, warnings) = source.to_bytes(ByteOrder::Little).unwrap(); - assert!(warnings.is_empty(), "{warnings:?}"); - let payload = tagged_payload(&little, b"MIB8hSyT", true); - assert_eq!(payload.get(..2), Some(&[1, 0][..]), "TySh header stays in TIFF order"); - for (index, expected) in [1.5f64, 0.0, -0.25, 1.75, 12.5, -3.25].into_iter().enumerate() { - let start = 2 + index * 8; - let bytes: [u8; 8] = payload.get(start..start + 8).unwrap().try_into().unwrap(); - assert_eq!(f64::from_le_bytes(bytes), expected, "matrix element {index}"); - } - - let (text_descriptor, descriptor_len) = VersionedDescriptor::parse_prefix(canonical.get(52..).unwrap()).unwrap(); - let text_section_len = 2 + descriptor_len; - assert_eq!(payload.get(50..52), Some(&50u16.to_be_bytes()[..])); - assert_eq!(payload.get(52..56), Some(&16u32.to_be_bytes()[..])); - assert_eq!(payload.get(50..50 + text_section_len), canonical.get(50..50 + text_section_len)); - assert!(matches!(text_descriptor.descriptor.get("Txt "), Some(Value::Text(value)) if value.to_string_lossy() == "Synthetic Ω 🦀")); - let text_descriptor_from_output = VersionedDescriptor::parse_prefix(payload.get(52..).unwrap()).unwrap().0; - assert!(matches!(text_descriptor_from_output.descriptor.get("Txt "), Some(Value::Text(value)) if value.to_string_lossy() == "Synthetic Ω 🦀")); - - let warp_at = 50 + text_section_len; - assert_eq!(payload.get(warp_at..warp_at + 2), Some(&1u16.to_le_bytes()[..])); - let (_, warp_len) = VersionedDescriptor::parse_prefix(canonical.get(warp_at + 2..).unwrap()).unwrap(); - let warp_descriptor_at = warp_at + 2; - assert_eq!(payload.get(warp_descriptor_at..warp_descriptor_at + 4), Some(&16u32.to_le_bytes()[..])); - assert_eq!(payload.get(warp_descriptor_at + 4..warp_descriptor_at + 8), Some(&0u32.to_le_bytes()[..])); - assert_eq!(payload.get(warp_descriptor_at + 8..warp_descriptor_at + 12), Some(&4u32.to_le_bytes()[..])); - assert_eq!(payload.get(warp_descriptor_at + 12..warp_descriptor_at + 16), Some(b"warp".as_slice())); - assert_eq!(payload.get(warp_descriptor_at + 16..warp_descriptor_at + 20), Some(&0u32.to_le_bytes()[..])); - let bounds_at = warp_descriptor_at + warp_len; - for (index, expected) in [11i32, -22, 333, 4_444].into_iter().enumerate() { - let start = bounds_at + index * 4; - assert_eq!(payload.get(start..start + 4), Some(&expected.to_le_bytes()[..]), "bound {index}"); - } - - let (big, warnings) = source.to_bytes(ByteOrder::Big).unwrap(); - assert!(warnings.is_empty(), "{warnings:?}"); - assert_eq!(tagged_payload(&big, b"8BIMTySh", false), canonical); - - let (reopened, warnings) = ImageSourceData::from_bytes(&little).unwrap(); - assert!(warnings.is_empty(), "{warnings:?}"); - assert_eq!(reopened.global_blocks[0].data, canonical); - assert_eq!(reopened.to_bytes(ByteOrder::Big).unwrap().0, big); - } - - #[test] - fn legacy_little_endian_type_descriptor_still_imports() { - let input = legacy_little_endian_type_block(); - let (reopened, warnings) = ImageSourceData::from_bytes(&input).unwrap(); - assert!(warnings.is_empty(), "{warnings:?}"); - assert_eq!(reopened.global_blocks[0].data, type_layer_data()); - } - - #[test] - fn type_block_layout() { - let mut data = Vec::new(); - data.put_u16(1); - for v in [1.0, 0.0, 0.0, 1.0, 12.5, -3.0] { - data.put_f64(v); - } - data.put_u16(50); - data.extend(VersionedDescriptor::new(Descriptor::new("TxLr")).to_bytes()); - data.put_u16(1); - data.extend(VersionedDescriptor::new(Descriptor::new("warp")).to_bytes()); - for v in [0.0, 0.0, 100.0, 20.0] { - data.put_f64(v); - } - let (_, little) = block_rt(*b"TySh", data); - assert!(little[48..].starts_with(&[1, 0])); - assert_eq!(&little[50..58], &1.0f64.to_le_bytes()); - } - - #[test] - fn photoshop_type_block_switches_to_big_endian_after_its_matrix() { - let mut data = Vec::new(); - data.put_u16(1); - for v in [1.8054202887117468, 0.0, -0.143, 1.8063853899082987, 247.25, 2864.5] { - data.put_f64(v); - } - data.put_u16(50); - let text = Descriptor::new("TxLr").with("Txt ", Value::Text(UnicodeString::new_nul("Synthetic headline"))); - data.extend(VersionedDescriptor::new(text).to_bytes()); - data.put_u16(1); - data.extend(VersionedDescriptor::new(Descriptor::new("warp")).to_bytes()); - for v in [0, 0, 120, 30] { - data.put_i32(v); - } - let (_, mut little) = block_rt(*b"TySh", data.clone()); - // Photoshop uses big-endian text but returns to little-endian for warp/bounds. - let (_, used) = VersionedDescriptor::parse_prefix(&data[52..]).unwrap(); - little[98..100 + used].copy_from_slice(&data[50..52 + used]); - let (back, warnings) = ImageSourceData::from_bytes(&little).unwrap(); - assert!(warnings.is_empty(), "{warnings:?}"); - assert!(!back.global_blocks[0].is_foreign_order()); - assert_eq!(back.global_blocks[0].data, data); - // The normalized model remains writable in either order. - for order in [ByteOrder::Big, ByteOrder::Little] { - let (bytes, warnings) = back.to_bytes(order).unwrap(); - assert!(warnings.is_empty()); - let (again, warnings) = ImageSourceData::from_bytes(&bytes).unwrap(); - assert!(warnings.is_empty()); - assert_eq!(again.global_blocks[0].data, data); - } - } - - #[test] - fn legacy_effects_and_adjustments() { - // lrFX with a drop shadow and a solid fill. - let mut fx = Vec::new(); - fx.put_u16(0); - fx.put_u16(3); - fx.put(b"8BIMcmnS"); - fx.put_u32(7); - fx.put_u32(0); - fx.put_u8(1); - fx.put_u16(0); - fx.put(b"8BIMdsdw"); - let mut sh = Vec::new(); - sh.put_u32(2); - for v in [5 << 16, 75 << 16, 120 << 16, 7 << 16] { - sh.put_i32(v); - } - for _ in 0..5 { - sh.put_u16(0); - } - sh.put(b"8BIMmul "); - sh.put_u8(1); - sh.put_u8(1); - sh.put_u8(191); - sh.put_u16(0); - sh.put_u16(0x1234); - sh.put_u16(0); - sh.put_u16(0); - sh.put_u16(0); - fx.put_u32(sh.len() as u32); - fx.put(&sh); - fx.put(b"8BIMsofi"); - let mut so = Vec::new(); - so.put_u32(2); - so.put(b"8BIMnorm"); - so.put_u16(0); - so.put_u16(0xffff); - so.put_u16(0); - so.put_u16(0); - so.put_u16(0); - so.put_u8(255); - so.put_u8(1); - so.put_u16(0); - so.put_u16(0xffff); - so.put_u16(0); - so.put_u16(0); - so.put_u16(0); - fx.put_u32(so.len() as u32); - fx.put(&so); - let (_, little) = block_rt(*b"lrFX", fx); - assert!(little.windows(8).any(|w| w == b"MIB8wdsd"), "effect keys reversed"); - assert!(little.windows(2).any(|w| w == [0x34, 0x12]), "colour component swapped"); - - // levl: version + 29 records + the Lvls extension. - let mut lv = Vec::new(); - lv.put_u16(2); - for i in 0..29 * 5 { - lv.put_u16(i as u16); - } - lv.put(b"Lvls"); - lv.put_u16(3); - lv.put_u16(33); - for i in 0..4 * 5 { - lv.put_u16(1000 + i as u16); - } - let (_, little) = block_rt(*b"levl", lv); - assert!(little.windows(4).any(|w| w == b"slvL")); - - // curv with the Crv extension. - let mut cv = vec![0u8]; - cv.put_u16(1); - cv.put_u32(0b101); - cv.put_u16(2); - cv.put_u16(0); - cv.put_u16(0); - cv.put_u16(255); - cv.put_u16(255); - cv.put_u16(1); - cv.put_u16(128); - cv.put_u16(100); - cv.put(b"Crv "); - cv.put_u16(4); - cv.put_u32(1); - cv.put_u16(2); - cv.put_u16(1); - cv.put_u16(7); - cv.put_u16(9); - block_rt(*b"curv", cv); - - for (key, data) in [ - (*b"hue2", vec![0, 2, 0, 0, 0, 10, 0, 20, 0, 30, 0, 40, 0, 50, 0, 60]), - (*b"brit", vec![0, 10, 0, 20, 0, 30, 1, 0]), - (*b"thrs", vec![0, 128, 0, 0]), - (*b"post", vec![0, 4, 0, 0]), - (*b"nvrt", vec![]), - (*b"expA", [1u16.to_be_bytes().to_vec(), 0.5f32.to_be_bytes().to_vec(), 0.0f32.to_be_bytes().to_vec(), 1.0f32.to_be_bytes().to_vec()].concat()), - (*b"blnc", vec![0; 20]), - (*b"mixr", vec![0, 1, 0, 0, 0, 100, 0, 0, 0, 0, 0, 0, 0, 0]), - (*b"selc", vec![0, 1, 0, 0, 0, 5, 0, 6, 0, 7, 0, 8]), - (*b"phfl", vec![0, 3, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 25, 1, 0]), - (*b"phfl", vec![0, 2, 0, 0, 1, 0, 2, 0, 3, 0, 4, 0, 0, 0, 25, 1, 0]), - (*b"lclr", vec![0, 1, 0, 0, 0, 0, 0, 0]), - (*b"fxrp", [1.5f64.to_be_bytes().to_vec(), 2.5f64.to_be_bytes().to_vec()].concat()), - (*b"brst", vec![0, 0, 0, 1, 0, 0, 0, 2]), - (*b"FMsk", vec![0, 0, 255, 255, 0, 0, 0, 0, 0, 0, 0, 50]), - (*b"lsct", [3u32.to_be_bytes().to_vec(), b"8BIMpass".to_vec()].concat()), - (*b"lspf", vec![0, 0, 0, 5]), - (*b"lnsr", b"layr".to_vec()), - (*b"knko", vec![1, 0, 0, 0]), - (*b"knko", vec![2, 0, 0, 0]), - (*b"infx", vec![1, 0, 0, 0]), - (*b"clbl", vec![0, 0, 0, 0]), - (*b"tsly", vec![0, 0, 0, 0]), - (*b"lmgm", vec![1, 0, 0, 0]), - (*b"vmgm", vec![1, 0, 0, 0]), - (*b"iOpa", vec![128, 0, 0, 0]), - ] { - let (big, little) = block_rt(key, data.clone()); - if data.len() >= 2 && key != *b"nvrt" { - assert_ne!(big, little, "{}", String::from_utf8_lossy(&key)); - } - } - } - - #[test] - fn global_layer_mask_block() { - let d = ImageSourceData { global_layer_mask: Some(GlobalLayerMask { data: vec![0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 50, 128, 0] }), ..Default::default() }; - let (little, w) = d.to_bytes(ByteOrder::Little).unwrap(); - assert!(w.is_empty()); - assert!(little[36..].starts_with(b"MIB8ksML")); - let (back, _) = ImageSourceData::from_bytes(&little).unwrap(); - assert_eq!(back.global_layer_mask, d.global_layer_mask); - assert_eq!(back.global_layer_mask.unwrap().opacity(), Some(50)); - } - - #[test] - fn gradient_map_layout() { - let mut g = Vec::new(); - g.put_u16(3); - g.put_u8(0); - g.put_u8(1); - g.put(b"Lnr "); - g.put_u32(2); - g.put_u16(u16::from(b'a')); - g.put_u16(0); - g.put_u16(2); - for (loc, mid) in [(0u32, 50u32), (4096, 50)] { - g.put_u32(loc); - g.put_u32(mid); - g.put_u16(0); - g.put_u16(0x1111); - g.put_u16(0x2222); - g.put_u16(0x3333); - g.put_u16(0); - g.put_u16(0); - } - g.put_u16(2); - for loc in [0u32, 4096] { - g.put_u32(loc); - g.put_u32(50); - g.put_u16(100); - } - g.put_u16(2); - g.put_u16(1); - g.put_u16(32); - g.put_u16(0); - g.put_u32(0xdead_beef); - for _ in 0..12 { - g.put_u16(0); - } - let (_, little) = block_rt(*b"grdm", g); - assert!(little.windows(4).any(|w| w == 0xdead_beefu32.to_le_bytes())); - assert!(little.windows(4).any(|w| w == b" rnL")); - } - - #[test] - fn vector_mask_records() { - let mut v = Vec::new(); - v.put_u32(3); - v.put_u32(0); - // Closed length record, then two linked knots. - v.put_u16(0); - v.put_u16(2); - v.put_i16(1); - v.put(&[0; 20]); - for sel in [1u16, 1] { - v.put_u16(sel); - for i in 0..6 { - v.put_i32((i + 1) * 0x0010_0000); - } - } - let (_, little) = block_rt(*b"vmsk", v); - assert!(little.windows(4).any(|w| w == [0, 0, 0x10, 0]), "fixed-point coordinate swapped"); - } - - #[test] - fn pattern_block() { - let plane: Vec = (0..16u8).collect(); - let p = crate::patterns::PsdPattern { - mode: 3, - width: 4, - height: 4, - name: "dots".into(), - id: "abc".into(), - palette: None, - depth: 8, - channels: vec![plane.clone(), plane.clone(), plane.clone()], - alpha: Some(plane), - }; - let data = crate::patterns::write_pattern_block(std::slice::from_ref(&p)).unwrap(); - block_rt(*b"Patt", data.clone()); - // Little-endian pattern data parses back into the same pattern. - let d = ImageSourceData { global_blocks: vec![TaggedBlock::new(*b"Patt", data)], ..Default::default() }; - let (little, _) = d.to_bytes(ByteOrder::Little).unwrap(); - let (back, _) = ImageSourceData::from_bytes(&little).unwrap(); - assert_eq!(crate::patterns::parse_pattern_block(&back.global_blocks[0].data).unwrap(), vec![p]); - } - - #[test] - fn filter_effects_block() { - use crate::filter_effects::{EffectsPlane, FilterEffects, FilterEffectsItem}; - let plane = EffectsPlane::encode(Compression::Rle, &[1, 2, 3, 4, 5, 6], 3, 2, 8).unwrap(); - let mask = EffectsPlane::encode(Compression::Raw, &[9; 6], 3, 2, 8).unwrap(); - let rect = crate::layer::Rect { top: 0, left: 0, bottom: 2, right: 3 }; - let fx = FilterEffects { - version: 1, - items: vec![FilterEffectsItem { - id: "x".into(), - version: 1, - rect, - depth: 8, - max_channels: 1, - slots: vec![Some(plane.clone()), None, Some(plane)], - mask: Some((rect, mask)), - }], - }; - let data = fx.to_bytes(); - block_rt(*b"FEid", data.clone()); - let d = ImageSourceData { global_blocks: vec![TaggedBlock::new(*b"FEid", data)], ..Default::default() }; - let (little, _) = d.to_bytes(ByteOrder::Little).unwrap(); - let (back, _) = ImageSourceData::from_bytes(&little).unwrap(); - assert_eq!(FilterEffects::parse(&back.global_blocks[0].data).unwrap(), fx); - } - - /// Photoshop writes one `FEid` section per smart object: every section's lengths and - /// numbers are swapped, not only the first one's. - #[test] - fn filter_effects_block_swaps_every_section() { - use crate::filter_effects::{EffectsPlane, FilterEffects, FilterEffectsItem}; - let rect = crate::layer::Rect { top: 0, left: 0, bottom: 2, right: 3 }; - let item = |id: &str, v: u8| FilterEffectsItem { - id: id.into(), - version: 1, - rect, - depth: 8, - max_channels: 1, - slots: vec![Some(EffectsPlane::encode(Compression::Raw, &[v; 6], 3, 2, 8).unwrap()), None, None], - mask: None, - }; - let fx = FilterEffects { version: 1, items: vec![item("first", 1), item("second-object", 2)] }; - let data = fx.to_bytes(); - let len1 = u64::from_be_bytes(data[4..12].try_into().unwrap()) as usize; - let second = 12 + len1 + (4 - len1 % 4) % 4; - let len2 = &data[second..second + 8]; - block_rt(*b"FEid", data.clone()); - let d = ImageSourceData { global_blocks: vec![TaggedBlock::new(*b"FEid", data.clone())], ..Default::default() }; - let (little, _) = d.to_bytes(ByteOrder::Little).unwrap(); - // 36-byte signature, then `MIB8`, the reversed key and a u32 length: the block data. - let body = &little[36 + 12..]; - let mut swapped = len2.to_vec(); - swapped.reverse(); - assert_eq!(&body[second..second + 8], &swapped[..], "second section's length is little-endian"); - let (back, w) = ImageSourceData::from_bytes(&little).unwrap(); - assert!(w.is_empty(), "{w:?}"); - assert_eq!(FilterEffects::parse(&back.global_blocks[0].data).unwrap(), fx); - } - - #[test] - fn metadata_setting_items() { - let desc = VersionedDescriptor::new(Descriptor::new("null")).to_bytes(); - let items = vec![crate::metadata::MetadataItem::new(*b"cmls", desc)]; - block_rt(*b"shmd", crate::metadata::write_shmd(&items)); - // An unknown item cannot be converted: it is dropped on its own, the rest stays. - let items = vec![ - crate::metadata::MetadataItem::new(*b"zzzz", vec![1, 2, 3, 4, 5, 6, 7, 8]), - crate::metadata::MetadataItem::new(*b"mdyn", vec![0, 0, 0, 1]), - crate::metadata::MetadataItem::new(*b"cmls", VersionedDescriptor::new(Descriptor::new("null")).to_bytes()), - ]; - let d = ImageSourceData { global_blocks: vec![TaggedBlock::new(*b"shmd", crate::metadata::write_shmd(&items))], ..Default::default() }; - let (little, w) = d.to_bytes(ByteOrder::Little).unwrap(); - assert_eq!(w.len(), 1, "{w:?}"); - assert!(w[0].starts_with("shmd item zzzz dropped"), "{}", w[0]); - let (back, w) = ImageSourceData::from_bytes(&little).unwrap(); - assert!(w.is_empty()); - let back_items = crate::metadata::parse_shmd(&back.global_blocks[0].data).unwrap(); - assert_eq!(back_items, items[1..].to_vec()); - } - - #[test] - fn unknown_descriptor_shaped_blocks_are_converted() { - // A key the transcoder has never heard of, holding a versioned descriptor (as every - // block Photoshop added since CS6 does): converted, not dropped. - let mut desc = Descriptor::new("null"); - desc.items.push((Id::new("Nm "), Value::Text(UnicodeString::new_nul("x")))); - let data = VersionedDescriptor::new(desc.clone()).to_bytes(); - block_rt(*b"Qqqq", data); - let mut with_version = 3u32.to_be_bytes().to_vec(); - with_version.extend(VersionedDescriptor::new(desc).to_bytes()); - block_rt(*b"Qqqq", with_version); - // Empty data needs no conversion either. - block_rt(*b"Mt32", Vec::new()); - } - - #[test] - fn linked_layer_items() { - // One embedded file (liFD, version 7) as photocraft-io writes it. - let mut item = Vec::new(); - item.put(b"liFD"); - item.put_u32(7); - item.put_u8(4); - item.put(b"uuid"); - let units: Vec = "a.png\0".encode_utf16().collect(); - item.put_u32(units.len() as u32); - for u in units { - item.put_u16(u); - } - item.put(b"png "); - item.put(b"8BIM"); - let bytes = [0x89, b'P', b'N', b'G', 1, 2, 3]; - item.put_u64(bytes.len() as u64); - item.put_u8(0); - item.put(&bytes); - item.put_u32(0); - item.put_f64(0.0); - item.put_u8(0); - let mut data = (item.len() as u64).to_be_bytes().to_vec(); - data.put(&item); - while !data.len().is_multiple_of(4) { - data.push(0); - } - let (_, little) = block_rt(*b"lnk2", data); - assert!(little.windows(4).any(|w| w == b"DFil"), "item type key reversed"); - assert!(little.windows(7).any(|w| w == bytes), "file bytes untouched"); - } - - #[test] - fn annotation_block() { - let mut a = Vec::new(); - a.put_u16(2); - a.put_u16(1); - a.put_u32(1); - let mut item = Vec::new(); - item.put(b"txtA"); - item.put_u8(0); - item.put_u8(1); - item.put_u16(0); - for v in [10, 20, 30, 40, 50, 60, 70, 80] { - item.put_i32(v); - } - item.put_u16(0); - for v in [0xffff, 0, 0, 0] { - item.put_u16(v); - } - for s in [&b"me"[..], b"note", b"2026"] { - item.put_u8(s.len() as u8); - item.put(s); - if (1 + s.len()) % 2 == 1 { - item.put_u8(0); - } - } - let text = [0xfe, 0xff, 0, b'h', 0, b'i']; - let mut d = Vec::new(); - d.put(b"txtC"); - d.put_u32(text.len() as u32); - d.put(&text); - item.put_u32(d.len() as u32 + 4); - item.put(&d); - a.put_u32(item.len() as u32 + 4); - a.put(&item); - let (_, little) = block_rt(*b"Anno", a); - assert!(little.windows(4).any(|w| w == b"Atxt")); - assert!(little.windows(6).any(|w| w == text), "text kept as stored"); - } - - #[test] - fn unknown_blocks_kept_in_big_dropped_in_little() { - let mut d = sample_layers(); - d.global_blocks.push(TaggedBlock::new(*b"Zzzz", vec![1, 2, 3, 4, 5])); - let (big, w) = d.to_bytes(ByteOrder::Big).unwrap(); - assert!(w.is_empty()); - let (back, w) = ImageSourceData::from_bytes(&big).unwrap(); - assert!(w.is_empty()); - assert_eq!(back.global_blocks, d.global_blocks); - // Big-endian data of unknown layout cannot go into a little-endian file. - let (little, w) = d.to_bytes(ByteOrder::Little).unwrap(); - assert_eq!(w.iter().filter(|w| w.starts_with("Zzzz block (5 bytes) dropped")).count(), 1, "{w:?}"); - let (back, w) = ImageSourceData::from_bytes(&little).unwrap(); - assert!(w.is_empty()); - assert_eq!(back.global_blocks.iter().map(|b| b.key).collect::>(), vec![*b"Patt", *b"FMsk"]); - assert_eq!(known(&back).layer_info, known(&d).layer_info); - } - - #[test] - fn unknown_blocks_from_a_little_endian_file_are_kept_with_their_byte_order() { - let d = sample_layers(); - let (little, _) = d.to_bytes(ByteOrder::Little).unwrap(); - // A little-endian file with a block of unknown layout, among known ones. - let mut raw = little.clone(); - raw.extend_from_slice(b"MIB8zzzZ"); - raw.extend_from_slice(&6u32.to_le_bytes()); - raw.extend_from_slice(&[9, 8, 7, 6, 5, 4, 0, 0]); - raw.extend_from_slice(b"MIB8diyl"); - raw.extend_from_slice(&4u32.to_le_bytes()); - raw.extend_from_slice(&7u32.to_le_bytes()); - let (back, w) = ImageSourceData::from_bytes(&raw).unwrap(); - assert!(w.is_empty(), "{w:?}"); - assert_eq!(known(&back).layer_info, known(&d).layer_info); - let kept = back.global_blocks.iter().find(|b| &b.key == b"Zzzz").expect("kept"); - assert!(kept.is_foreign_order()); - assert_eq!(kept.signature, *b"MIB8"); - assert_eq!(kept.data, [9, 8, 7, 6, 5, 4]); - // The known block after it was still converted. - assert_eq!(back.global_blocks.iter().find(|b| &b.key == b"lyid").unwrap().data, 7u32.to_be_bytes()); - // Written back to a little-endian TIFF, the bytes are exactly what was read. - let (again, w) = back.to_bytes(ByteOrder::Little).unwrap(); - assert!(w.is_empty(), "{w:?}"); - let tail = &raw[raw.len() - 18 - 16..]; - assert!(again.windows(tail.len()).any(|x| x == tail), "foreign-order block restored verbatim"); - assert_eq!(ImageSourceData::from_bytes(&again).unwrap().0.global_blocks, back.global_blocks); - // The big-endian (PSD) model keeps the marker, so a PSD writer can tell it apart. - let (big, _) = back.to_bytes(ByteOrder::Big).unwrap(); - assert!(big.windows(8).any(|x| x == b"MIB8Zzzz")); - assert_eq!(ImageSourceData::from_bytes(&big).unwrap().0.global_blocks, back.global_blocks); - } - - /// A PSB keeps `Mt16`/`Mt32`/`Mtrn`/`Alph` blocks of unknown layout verbatim, and their - /// length field is 8 bytes (a PSB long key). Writing them into a little-endian TIFF must - /// read that width; the old code looked the key up after reversing it for the target - /// order, which never matches `PSB_LONG_KEYS`. - #[test] - fn psb_foreign_order_long_key_roundtrips() { - let d = ImageSourceData { - version: Version::Psb, - byte_order: ByteOrder::Little, - global_blocks: vec![TaggedBlock { signature: *b"MIB8", key: *b"Mt16", data: vec![9, 8, 7, 6, 5, 4], padding: None }], - ..Default::default() - }; - let (little, w) = d.to_bytes(ByteOrder::Little).unwrap(); - assert!(w.is_empty(), "{w:?}"); - let (back, w) = ImageSourceData::from_bytes(&little).unwrap(); - assert!(w.is_empty(), "{w:?}"); - assert_eq!(back.global_blocks, d.global_blocks, "the 8-byte length and the bytes survive"); - } - - #[test] - fn rle_counts_follow_the_container_and_samples_do_not() { - let file = testgen::layered(Version::Psd, ColorMode::Rgb, 16, Compression::Rle); - let d = ImageSourceData::from_psd(&file); - let (big, _) = d.to_bytes(ByteOrder::Big).unwrap(); - let (little, _) = d.to_bytes(ByteOrder::Little).unwrap(); - let (back, _) = ImageSourceData::from_bytes(&little).unwrap(); - let d = known(&d); - let (a, b) = (d.layer_info.as_ref().unwrap(), back.layer_info.as_ref().unwrap()); - for (la, lb) in a.layers.iter().zip(&b.layers) { - for (ca, cb) in la.channels.iter().zip(&lb.channels) { - assert_eq!(ca, cb); - let (w, h) = la.channel_rect(ca.id).size().unwrap(); - assert_eq!(ca.decode(w, h, 16, Version::Psd).unwrap(), cb.decode(w, h, 16, Version::Psd).unwrap()); - } - } - // The encoded samples (after the count table) are identical bytes in both files, while - // the count table itself is swapped. - let (rec, ch) = a - .layers - .iter() - .flat_map(|l| l.channels.iter().filter(|c| c.id >= -1 && c.compression == Some(Compression::Rle)).map(move |c| (l, c))) - .find(|(l, c)| l.rect.height() > 1 && c.data.len() > l.rect.height() as usize * 2 + 8) - .unwrap(); - let table = rec.rect.height() as usize * 2; - let samples = &ch.data[table..]; - assert!(big.windows(samples.len()).any(|w| w == samples)); - assert!(little.windows(samples.len()).any(|w| w == samples)); - let counts = &ch.data[..table]; - let swapped: Vec = counts.chunks(2).flat_map(|c| [c[1], c[0]]).collect(); - assert!(little.windows(table + samples.len()).any(|w| w[..table] == swapped[..] && w[table..] == *samples)); - } - - #[test] - fn blending_ranges_are_bytes_in_either_order() { - let mut file = testgen::layered(Version::Psd, ColorMode::Rgb, 8, Compression::Rle); - let ranges: Vec = [0u8, 0, 255, 255].repeat(10); - let marked: Vec = (1u8..=40).collect(); - for (i, l) in file.layer_info.as_mut().unwrap().layers.iter_mut().enumerate() { - l.blending_ranges.data = if i == 0 { marked.clone() } else { ranges.clone() }; - } - let d = ImageSourceData::from_psd(&file); - let (little, _) = d.to_bytes(ByteOrder::Little).unwrap(); - // Written verbatim (what Photoshop writes in an `II` TIFF), not swapped per u32. - assert!(little.windows(marked.len()).any(|w| w == marked)); - let (back, _) = ImageSourceData::from_bytes(&little).unwrap(); - for (a, b) in d.layer_info.as_ref().unwrap().layers.iter().zip(&back.layer_info.as_ref().unwrap().layers) { - assert_eq!(a.blending_ranges, b.blending_ranges); - } - } - - #[test] - fn psb_sized_data_uses_long_lengths_and_counts() { - let file = testgen::layered(Version::Psb, ColorMode::Cmyk, 8, Compression::Rle); - let d = ImageSourceData::from_psd(&file); - assert_eq!(d.version, Version::Psb); - let back = roundtrip(&d); - assert_eq!(back.layer_info, d.layer_info); - let (little, _) = d.to_bytes(ByteOrder::Little).unwrap(); - assert!(little[36..].starts_with(b"MIB8")); - let (back, _) = ImageSourceData::from_bytes(&little).unwrap(); - assert_eq!(known(&back).layer_info, known(&d).layer_info); - } - - #[test] - fn resources_both_orders() { - let res = vec![ - ImageResource::new(1005, vec![0, 72, 0, 0, 0, 1, 0, 1, 0, 72, 0, 0, 0, 1, 0, 1]), - ImageResource::new(1037, vec![0, 0, 0, 120]), - ImageResource::new(1039, vec![1, 2, 3]), - ImageResource { signature: *b"8BIM", id: 1026, name: b"grp".to_vec(), data: vec![0, 1, 0, 1, 0, 0] }, - ]; - let big = resources_to_bytes(&res).unwrap(); - let (back, w) = resources_from_bytes(&big).unwrap(); - assert!(w.is_empty()); - assert_eq!(back, res); - let (little, w) = transcode_resources(&big, ByteOrder::Big, ByteOrder::Little).unwrap(); - assert!(w.is_empty()); - assert!(little.starts_with(b"MIB8")); - assert_eq!(little.len(), big.len()); - assert_eq!(&little[4..6], &[0xed, 3]); - let (back, w) = resources_from_bytes(&little).unwrap(); - assert!(w.is_empty()); - assert_eq!(back, res); - // The ICC blob is untouched by the swap. - assert!(little.windows(3).any(|w| w == [1, 2, 3])); - // An odd trailing pad byte is tolerated. - let mut padded = big.clone(); - padded.push(0); - assert_eq!(resources_from_bytes(&padded).unwrap().0, res); - } - - #[test] - fn malformed_input_errors_without_panicking() { - assert!(ImageSourceData::from_bytes(b"").is_err()); - assert!(ImageSourceData::from_bytes(b"Adobe Photoshop Document Data Block").is_err()); - let mut bad = SIGNATURE.to_vec(); - bad.extend_from_slice(b"XXXXLayr"); - assert!(ImageSourceData::from_bytes(&bad).is_err()); - let d = sample_layers(); - for order in [ByteOrder::Big, ByteOrder::Little] { - let (bytes, _) = d.to_bytes(order).unwrap(); - for cut in (0..bytes.len()).step_by(7).chain(bytes.len().saturating_sub(8)..bytes.len()) { - let _ = ImageSourceData::from_bytes(&bytes[..cut]); - } - // Bit flips in the structure (not the signature). - for i in (36..bytes.len()).step_by(13) { - let mut b = bytes.clone(); - b[i] ^= 0x5a; - let _ = ImageSourceData::from_bytes(&b); - } - } - // A block that claims more data than exists. - let mut huge = SIGNATURE.to_vec(); - huge.extend_from_slice(b"8BIMluni"); - huge.extend_from_slice(&u32::MAX.to_be_bytes()); - assert!(ImageSourceData::from_bytes(&huge).is_err()); - assert!(resources_from_bytes(b"8BIM\x03\xed\x00").is_err()); - } - - #[test] - fn into_psd_roundtrips_through_the_psd_writer() { - let file = testgen::layered(Version::Psd, ColorMode::Grayscale, 8, Compression::Zip); - let d = ImageSourceData::from_psd(&file); - let (little, _) = d.to_bytes(ByteOrder::Little).unwrap(); - let (back, _) = ImageSourceData::from_bytes(&little).unwrap(); - let psd = back.into_psd(file.header.clone(), file.resources.clone(), file.image_data.clone()); - let bytes = psd.to_bytes().unwrap(); - let again = PsdFile::from_bytes(&bytes).unwrap(); - let expected = known(&ImageSourceData::from_psd(&file)); - assert_eq!(known(&ImageSourceData::from_psd(&again)).layer_info, expected.layer_info); - assert_eq!(again.global_blocks, expected.global_blocks); - assert_eq!(again.layer_tree().len(), file.layer_tree().len()); - } - - /// Global blocks are padded as they are written, not on a copy: the bytes are those of the - /// former path (each block cloned with explicit padding to 4, written with `write_blocks`). - #[test] - fn global_blocks_written_without_copies_keep_their_bytes() { - for version in [Version::Psd, Version::Psb] { - let mut d = ImageSourceData { version, global_layer_mask: Some(GlobalLayerMask { data: vec![0, 1, 0, 2, 0, 3, 0, 4, 9] }), ..Default::default() }; - for n in 0..8u8 { - d.global_blocks.push(TaggedBlock::new(*b"FMsk", (0..n).collect())); - } - let mut explicit = TaggedBlock::new(*b"FMsk", vec![1, 2, 3]); - explicit.padding = Some(vec![]); - d.global_blocks.push(explicit); - let mut odd = TaggedBlock::new(*b"FMsk", vec![1, 2]); - odd.padding = Some(vec![0, 0, 0, 0, 0]); - d.global_blocks.push(odd); - let mut copies = vec![padded_block(*b"LMsk", d.global_layer_mask.as_ref().unwrap().data.clone())]; - for b in &d.global_blocks { - let mut b = b.clone(); - if b.padding.is_none() { - b.padding = Some(vec![0; (4 - b.data.len() % 4) % 4]); - } - copies.push(b); - } - let mut body = Vec::new(); - crate::tagged::write_blocks(&mut body, &copies, version, 2).unwrap(); - let signature = if version.is_psb() { SIGNATURE_PSB } else { SIGNATURE }; - assert_eq!(d.to_bytes(ByteOrder::Big).unwrap().0, [signature, &body[..]].concat()); - let (little, _) = transcode_blocks(&body, version, ByteOrder::Big, ByteOrder::Little).unwrap(); - assert_eq!(d.to_bytes(ByteOrder::Little).unwrap().0, [signature, &little[..]].concat()); - } - } - - /// Nested structures are transcoded into one shared buffer. A block whose body fails - /// part-way leaves no partial bytes: dropped on the way out (with the enclosing lengths - /// patched as if it had never been there), or kept exactly as stored on the way in. - #[test] - fn a_nested_block_that_fails_part_way_leaves_nothing_behind() { - let clean = sample_layers(); - let mut fx = Vec::new(); - fx.put_u32(0); - fx.extend_from_slice(&VersionedDescriptor::new(Descriptor::new("null").with("Opct", Value::Double(1.0))).to_bytes()); - // A whole number of 4-byte units, so dropping it cannot change any padding. - fx.resize(fx.len().next_multiple_of(4), 0); - let mut d = clean.clone(); - d.layer_info.as_mut().unwrap().layers[0].blocks.insert(0, TaggedBlock::new(*b"lfx2", fx.clone())); - let (mut little, w) = d.to_bytes(ByteOrder::Little).unwrap(); - assert!(!w.iter().any(|w| w.starts_with("lfx2")), "{w:?}"); - // An unknown value type after the descriptor's header: parsing fails part-way. - let at = little.windows(4).position(|w| w == b"buod").unwrap(); - little[at..at + 4].copy_from_slice(b"????"); - let (back, w) = ImageSourceData::from_bytes(&little).unwrap(); - assert_eq!(w.iter().filter(|w| w.starts_with("lfx2 block")).count(), 1, "{w:?}"); - let kept = &back.layer_info.as_ref().unwrap().layers[0].blocks[0]; - assert!(kept.is_foreign_order()); - let stored = little.windows(4).position(|w| w == b"2xfl").unwrap() + 8; - assert_eq!(kept.data, little[stored..stored + fx.len()]); - // Big-endian data that fails part-way cannot go into a little-endian file: dropped. - let mut big_bad = d.clone(); - let mut broken = fx.clone(); - let at = broken.windows(4).position(|w| w == b"doub").unwrap(); - broken[at..at + 4].copy_from_slice(b"????"); - big_bad.layer_info.as_mut().unwrap().layers[0].blocks[0].data = broken; - let (little, w) = big_bad.to_bytes(ByteOrder::Little).unwrap(); - assert_eq!(w.iter().filter(|w| w.starts_with("lfx2 block")).count(), 1, "{w:?}"); - assert_eq!(little, clean.to_bytes(ByteOrder::Little).unwrap().0); - } -} +mod tests; diff --git a/crates/psd/src/tiff/tests.rs b/crates/psd/src/tiff/tests.rs new file mode 100644 index 0000000000..3836822bf4 --- /dev/null +++ b/crates/psd/src/tiff/tests.rs @@ -0,0 +1,1012 @@ +use super::transcode::*; +use super::*; +use crate::compression::Compression; +use crate::descriptor::{Descriptor, Id, UnicodeString, Value, VersionedDescriptor}; +use crate::header::ColorMode; +use crate::testgen; + +/// Keys the generator plants that the transcoder (rightly) does not know. +const UNKNOWN: [&[u8; 4]; 3] = [b"zOdd", b"zNop", b"Txt2"]; + +/// `d` without the blocks a little-endian round trip drops, and without the layer-info +/// padding (which follows the body length, so it changes when blocks are dropped). +fn known(d: &ImageSourceData) -> ImageSourceData { + let mut d = d.clone(); + d.byte_order = ByteOrder::Big; + d.global_blocks.retain(|b| !UNKNOWN.contains(&&b.key)); + if d.layer_info.is_none() { + d.layer_info_key = *b"Layr"; + } + if let Some(info) = &mut d.layer_info { + info.padding = None; + for l in &mut info.layers { + l.blocks.retain(|b| !UNKNOWN.contains(&&b.key)); + } + } + d +} + +fn roundtrip(d: &ImageSourceData) -> ImageSourceData { + let (big, w) = d.to_bytes(ByteOrder::Big).unwrap(); + assert!(w.is_empty(), "{w:?}"); + let (little, w) = d.to_bytes(ByteOrder::Little).unwrap(); + assert!(w.iter().all(|w| UNKNOWN.iter().any(|k| w.starts_with(std::str::from_utf8(*k).unwrap()))), "{w:?}"); + if w.is_empty() { + assert_eq!(big.len(), little.len()); + } + if big.len() > 36 { + assert_ne!(big, little); + assert!(little[36..].starts_with(b"MIB8")); + } + let (back_big, w) = ImageSourceData::from_bytes(&big).unwrap(); + assert!(w.is_empty(), "{w:?}"); + let (back_little, w) = ImageSourceData::from_bytes(&little).unwrap(); + assert!(w.is_empty(), "{w:?}"); + if little.len() > 36 { + assert_eq!(back_little.byte_order, ByteOrder::Little); + } + assert_eq!(known(&back_little), known(&back_big)); + // The little-endian bytes are a fixed point (from the second generation on when blocks + // were dropped, since the layer-info padding then follows the shorter body). + let (little2, _) = back_little.to_bytes(ByteOrder::Little).unwrap(); + let little3 = ImageSourceData::from_bytes(&little2).unwrap().0.to_bytes(ByteOrder::Little).unwrap().0; + assert_eq!(little3, little2); + back_big +} + +#[test] +fn generated_files_survive_both_orders() { + for case in testgen::all_cases() { + let d = ImageSourceData::from_psd(&case.file); + let back = roundtrip(&d); + assert_eq!(back.version, d.version, "{}", case.name); + assert_eq!(known(&back), known(&d), "{}", case.name); + // Nothing but the planted unknown blocks is lost on the little-endian path. + let (little, _) = d.to_bytes(ByteOrder::Little).unwrap(); + let (back, _) = ImageSourceData::from_bytes(&little).unwrap(); + assert_eq!(known(&back), known(&d), "{}", case.name); + } +} + +#[test] +fn same_order_transcoding_is_the_identity() { + for case in testgen::all_cases() { + let d = ImageSourceData::from_psd(&case.file); + let (big, _) = d.to_bytes(ByteOrder::Big).unwrap(); + let (same, w) = transcode_blocks(&big[36..], d.version, ByteOrder::Big, ByteOrder::Big).unwrap(); + assert!(w.is_empty()); + assert_eq!(same, big[36..].to_vec(), "{}", case.name); + } +} + +fn sample_layers() -> ImageSourceData { + let file = testgen::layered(Version::Psd, ColorMode::Rgb, 8, Compression::Rle); + ImageSourceData::from_psd(&file) +} + +#[test] +fn signature_selects_the_version() { + let mut d = sample_layers(); + let (b, _) = d.to_bytes(ByteOrder::Big).unwrap(); + assert!(b.starts_with(SIGNATURE)); + d.version = Version::Psb; + let (b, _) = d.to_bytes(ByteOrder::Big).unwrap(); + assert!(b.starts_with(SIGNATURE_PSB)); + assert_eq!(ImageSourceData::from_bytes(&b).unwrap().0.version, Version::Psb); + roundtrip(&d); +} + +#[test] +fn layer_key_follows_depth() { + assert_eq!(layer_info_key(8), *b"Layr"); + assert_eq!(layer_info_key(16), *b"Lr16"); + assert_eq!(layer_info_key(32), *b"Lr32"); + for (depth, comp) in [(16, Compression::ZipPrediction), (32, Compression::ZipPrediction), (16, Compression::Rle)] { + let file = testgen::layered(Version::Psd, ColorMode::Rgb, depth, comp); + let d = ImageSourceData::from_psd(&file); + assert_eq!(d.layer_info_key, layer_info_key(depth)); + let back = roundtrip(&d); + assert_eq!(back.layer_info_key, d.layer_info_key); + // The 16/32-bit model goes back into a PSD as a global block, like Photoshop's. + let psd = back.into_psd(file.header.clone(), file.resources.clone(), file.image_data.clone()); + assert!(matches!(psd.layer_info_placement, LayerInfoPlacement::GlobalBlock { .. })); + let again = PsdFile::from_bytes(&psd.to_bytes().unwrap()).unwrap(); + assert_eq!(known(&ImageSourceData::from_psd(&again)).layer_info, known(&d).layer_info); + let (little, _) = d.to_bytes(ByteOrder::Little).unwrap(); + let (back, _) = ImageSourceData::from_bytes(&little).unwrap(); + assert_eq!(known(&back).layer_info, known(&d).layer_info, "depth {depth}"); + } +} + +#[test] +fn blocks_are_padded_to_four() { + let d = sample_layers(); + let (b, _) = d.to_bytes(ByteOrder::Big).unwrap(); + let mut at = 36; + while at < b.len() { + assert_eq!(&b[at..at + 4], b"8BIM"); + let len = u32::from_be_bytes(b[at + 8..at + 12].try_into().unwrap()) as usize; + at += 12 + len; + at += (4 - at % 4) % 4; + } + assert_eq!(at, b.len()); +} + +fn block_rt(key: [u8; 4], data: Vec) -> (Vec, Vec) { + let d = ImageSourceData { global_blocks: vec![TaggedBlock::new(key, data.clone())], ..Default::default() }; + let (big, _) = d.to_bytes(ByteOrder::Big).unwrap(); + let (little, w) = d.to_bytes(ByteOrder::Little).unwrap(); + assert!(w.is_empty(), "{w:?}"); + let (back, w) = ImageSourceData::from_bytes(&little).unwrap(); + assert!(w.is_empty(), "{w:?}"); + assert_eq!(back.global_blocks[0].data, data); + assert_eq!(back.to_bytes(ByteOrder::Big).unwrap().0, big); + (big, little) +} + +#[test] +fn descriptor_blocks_swap_keys_and_numbers() { + let mut desc = Descriptor::new("null"); + desc.items.push((Id::new("Opct"), Value::UnitFloat { unit: *b"#Prc", value: 75.5 })); + desc.items.push((Id::new("Nm "), Value::Text(UnicodeString::new_nul("Drop Shadow")))); + desc.items.push((Id::new("enab"), Value::Boolean(true))); + desc.items.push((Id::new("Md "), Value::Enumerated { type_id: Id::new("BlnM"), value: Id::new("Mltp") })); + desc.items.push((Id::new("list"), Value::List(vec![Value::Integer(-3), Value::Double(1.5), Value::LargeInteger(7)]))); + desc.items.push((Id::new("longKeyName"), Value::Descriptor(Descriptor::new("innr")))); + let mut data = 0u32.to_be_bytes().to_vec(); + data.extend(VersionedDescriptor::new(desc).to_bytes()); + let (big, little) = block_rt(*b"lfx2", data); + // Keys are reversed and the version field swapped in the little-endian bytes. + assert!(little[36..].starts_with(b"MIB82xfl")); + let body_at = 48; + assert_eq!(&little[body_at..body_at + 4], &[0, 0, 0, 0]); + assert_eq!(&little[body_at + 4..body_at + 8], &[16, 0, 0, 0]); + assert_eq!(&big[body_at + 4..body_at + 8], &[0, 0, 0, 16]); + assert!(little.windows(4).any(|w| w == b"crP#"), "unit key reversed"); + assert!(little.windows(11).any(|w| w == b"longKeyName"), "string ids are not reversed"); +} + +#[test] +fn descriptor_references_by_identifier_and_index_keep_their_class() { + use crate::descriptor::{Class, ReferenceItem}; + let class = || Class { name: UnicodeString::new(""), class_id: Id::new("Lyr ") }; + let desc = Descriptor::new("null") + .with("null", Value::Reference(vec![ReferenceItem::Identifier { class: class(), id: 7 }, ReferenceItem::Index { class: class(), index: 2 }])); + let mut data = 0u32.to_be_bytes().to_vec(); + data.extend(VersionedDescriptor::new(desc).to_bytes()); + block_rt(*b"lfx2", data); +} + +fn type_layer_data() -> Vec { + let mut data = Vec::new(); + data.put_u16(1); + for value in [1.5, 0.0, -0.25, 1.75, 12.5, -3.25] { + data.put_f64(value); + } + data.put_u16(50); + let text = Descriptor::new("TxLr").with("Txt ", Value::Text(UnicodeString::new_nul("Synthetic Ω 🦀"))); + data.extend(VersionedDescriptor::new(text).to_bytes()); + data.put_u16(1); + data.extend(VersionedDescriptor::new(Descriptor::new("warp")).to_bytes()); + for value in [11, -22, 333, 4_444] { + data.put_i32(value); + } + data +} + +fn tagged_payload<'a>(bytes: &'a [u8], signature_and_key: &[u8; 8], little: bool) -> &'a [u8] { + let block_at = bytes.windows(8).position(|window| window == signature_and_key).expect("tagged block"); + let length_at = block_at + 8; + let length_bytes: [u8; 4] = bytes.get(length_at..length_at + 4).expect("tagged block length").try_into().expect("four-byte length"); + let length = if little { u32::from_le_bytes(length_bytes) } else { u32::from_be_bytes(length_bytes) }; + let data_at = length_at + 4; + let data_end = data_at + usize::try_from(length).expect("test block length fits usize"); + bytes.get(data_at..data_end).expect("tagged block payload") +} + +fn legacy_little_endian_type_block() -> Vec { + let mut tysh = Vec::new(); + tysh.extend_from_slice(&1u16.to_le_bytes()); + for value in [1.5f64, 0.0, -0.25, 1.75, 12.5, -3.25] { + tysh.extend_from_slice(&value.to_le_bytes()); + } + tysh.extend_from_slice(&50u16.to_le_bytes()); + // Independently encode a little-endian `VersionedDescriptor` with a single TEXT value. + tysh.extend_from_slice(&16u32.to_le_bytes()); + tysh.extend_from_slice(&0u32.to_le_bytes()); // empty descriptor name + tysh.extend_from_slice(&0u32.to_le_bytes()); // four-character class id + tysh.extend_from_slice(b"rLxT"); // little-endian four-character class id + tysh.extend_from_slice(&1u32.to_le_bytes()); // one item + tysh.extend_from_slice(&0u32.to_le_bytes()); // four-character key + tysh.extend_from_slice(b" txT"); // little-endian four-character key + tysh.extend_from_slice(b"TXET"); // little-endian OSType + let mut units: Vec = "Synthetic Ω 🦀".encode_utf16().collect(); + units.push(0); // `new_nul`, matching the canonical fixture + tysh.extend_from_slice(&u32::try_from(units.len()).expect("short test string").to_le_bytes()); + for unit in units { + tysh.extend_from_slice(&unit.to_le_bytes()); + } + tysh.extend_from_slice(&1u16.to_le_bytes()); + // Empty warp descriptor, also encoded independently in little-endian order. + tysh.extend_from_slice(&16u32.to_le_bytes()); + tysh.extend_from_slice(&0u32.to_le_bytes()); // empty descriptor name + tysh.extend_from_slice(&4u32.to_le_bytes()); // `warp` is a four-byte string id + tysh.extend_from_slice(b"warp"); + tysh.extend_from_slice(&0u32.to_le_bytes()); // no items + for value in [11i32, -22, 333, 4_444] { + tysh.extend_from_slice(&value.to_le_bytes()); + } + + let mut image_source = super::SIGNATURE.to_vec(); + image_source.extend_from_slice(b"MIB8hSyT"); + image_source.extend_from_slice(&u32::try_from(tysh.len()).expect("short test block").to_le_bytes()); + image_source.extend_from_slice(&tysh); + let padding = (4 - tysh.len() % 4) % 4; + image_source.resize(image_source.len() + padding, 0); + image_source +} + +#[test] +fn type_block_write_keeps_text_descriptor_in_psd_order() { + let canonical = type_layer_data(); + let source = ImageSourceData { global_blocks: vec![TaggedBlock::new(*b"TySh", canonical.clone())], ..Default::default() }; + + let (little, warnings) = source.to_bytes(ByteOrder::Little).unwrap(); + assert!(warnings.is_empty(), "{warnings:?}"); + let payload = tagged_payload(&little, b"MIB8hSyT", true); + assert_eq!(payload.get(..2), Some(&[1, 0][..]), "TySh header stays in TIFF order"); + for (index, expected) in [1.5f64, 0.0, -0.25, 1.75, 12.5, -3.25].into_iter().enumerate() { + let start = 2 + index * 8; + let bytes: [u8; 8] = payload.get(start..start + 8).unwrap().try_into().unwrap(); + assert_eq!(f64::from_le_bytes(bytes), expected, "matrix element {index}"); + } + + let (text_descriptor, descriptor_len) = VersionedDescriptor::parse_prefix(canonical.get(52..).unwrap()).unwrap(); + let text_section_len = 2 + descriptor_len; + assert_eq!(payload.get(50..52), Some(&50u16.to_be_bytes()[..])); + assert_eq!(payload.get(52..56), Some(&16u32.to_be_bytes()[..])); + assert_eq!(payload.get(50..50 + text_section_len), canonical.get(50..50 + text_section_len)); + assert!(matches!(text_descriptor.descriptor.get("Txt "), Some(Value::Text(value)) if value.to_string_lossy() == "Synthetic Ω 🦀")); + let text_descriptor_from_output = VersionedDescriptor::parse_prefix(payload.get(52..).unwrap()).unwrap().0; + assert!(matches!(text_descriptor_from_output.descriptor.get("Txt "), Some(Value::Text(value)) if value.to_string_lossy() == "Synthetic Ω 🦀")); + + let warp_at = 50 + text_section_len; + assert_eq!(payload.get(warp_at..warp_at + 2), Some(&1u16.to_le_bytes()[..])); + let (_, warp_len) = VersionedDescriptor::parse_prefix(canonical.get(warp_at + 2..).unwrap()).unwrap(); + let warp_descriptor_at = warp_at + 2; + assert_eq!(payload.get(warp_descriptor_at..warp_descriptor_at + 4), Some(&16u32.to_le_bytes()[..])); + assert_eq!(payload.get(warp_descriptor_at + 4..warp_descriptor_at + 8), Some(&0u32.to_le_bytes()[..])); + assert_eq!(payload.get(warp_descriptor_at + 8..warp_descriptor_at + 12), Some(&4u32.to_le_bytes()[..])); + assert_eq!(payload.get(warp_descriptor_at + 12..warp_descriptor_at + 16), Some(b"warp".as_slice())); + assert_eq!(payload.get(warp_descriptor_at + 16..warp_descriptor_at + 20), Some(&0u32.to_le_bytes()[..])); + let bounds_at = warp_descriptor_at + warp_len; + for (index, expected) in [11i32, -22, 333, 4_444].into_iter().enumerate() { + let start = bounds_at + index * 4; + assert_eq!(payload.get(start..start + 4), Some(&expected.to_le_bytes()[..]), "bound {index}"); + } + + let (big, warnings) = source.to_bytes(ByteOrder::Big).unwrap(); + assert!(warnings.is_empty(), "{warnings:?}"); + assert_eq!(tagged_payload(&big, b"8BIMTySh", false), canonical); + + let (reopened, warnings) = ImageSourceData::from_bytes(&little).unwrap(); + assert!(warnings.is_empty(), "{warnings:?}"); + assert_eq!(reopened.global_blocks[0].data, canonical); + assert_eq!(reopened.to_bytes(ByteOrder::Big).unwrap().0, big); +} + +#[test] +fn legacy_little_endian_type_descriptor_still_imports() { + let input = legacy_little_endian_type_block(); + let (reopened, warnings) = ImageSourceData::from_bytes(&input).unwrap(); + assert!(warnings.is_empty(), "{warnings:?}"); + assert_eq!(reopened.global_blocks[0].data, type_layer_data()); +} + +#[test] +fn type_block_layout() { + let mut data = Vec::new(); + data.put_u16(1); + for v in [1.0, 0.0, 0.0, 1.0, 12.5, -3.0] { + data.put_f64(v); + } + data.put_u16(50); + data.extend(VersionedDescriptor::new(Descriptor::new("TxLr")).to_bytes()); + data.put_u16(1); + data.extend(VersionedDescriptor::new(Descriptor::new("warp")).to_bytes()); + for v in [0.0, 0.0, 100.0, 20.0] { + data.put_f64(v); + } + let (_, little) = block_rt(*b"TySh", data); + assert!(little[48..].starts_with(&[1, 0])); + assert_eq!(&little[50..58], &1.0f64.to_le_bytes()); +} + +#[test] +fn photoshop_type_block_switches_to_big_endian_after_its_matrix() { + let mut data = Vec::new(); + data.put_u16(1); + for v in [1.8054202887117468, 0.0, -0.143, 1.8063853899082987, 247.25, 2864.5] { + data.put_f64(v); + } + data.put_u16(50); + let text = Descriptor::new("TxLr").with("Txt ", Value::Text(UnicodeString::new_nul("Synthetic headline"))); + data.extend(VersionedDescriptor::new(text).to_bytes()); + data.put_u16(1); + data.extend(VersionedDescriptor::new(Descriptor::new("warp")).to_bytes()); + for v in [0, 0, 120, 30] { + data.put_i32(v); + } + let (_, mut little) = block_rt(*b"TySh", data.clone()); + // Photoshop uses big-endian text but returns to little-endian for warp/bounds. + let (_, used) = VersionedDescriptor::parse_prefix(&data[52..]).unwrap(); + little[98..100 + used].copy_from_slice(&data[50..52 + used]); + let (back, warnings) = ImageSourceData::from_bytes(&little).unwrap(); + assert!(warnings.is_empty(), "{warnings:?}"); + assert!(!back.global_blocks[0].is_foreign_order()); + assert_eq!(back.global_blocks[0].data, data); + // The normalized model remains writable in either order. + for order in [ByteOrder::Big, ByteOrder::Little] { + let (bytes, warnings) = back.to_bytes(order).unwrap(); + assert!(warnings.is_empty()); + let (again, warnings) = ImageSourceData::from_bytes(&bytes).unwrap(); + assert!(warnings.is_empty()); + assert_eq!(again.global_blocks[0].data, data); + } +} + +#[test] +fn legacy_effects_and_adjustments() { + // lrFX with a drop shadow and a solid fill. + let mut fx = Vec::new(); + fx.put_u16(0); + fx.put_u16(3); + fx.put(b"8BIMcmnS"); + fx.put_u32(7); + fx.put_u32(0); + fx.put_u8(1); + fx.put_u16(0); + fx.put(b"8BIMdsdw"); + let mut sh = Vec::new(); + sh.put_u32(2); + for v in [5 << 16, 75 << 16, 120 << 16, 7 << 16] { + sh.put_i32(v); + } + for _ in 0..5 { + sh.put_u16(0); + } + sh.put(b"8BIMmul "); + sh.put_u8(1); + sh.put_u8(1); + sh.put_u8(191); + sh.put_u16(0); + sh.put_u16(0x1234); + sh.put_u16(0); + sh.put_u16(0); + sh.put_u16(0); + fx.put_u32(sh.len() as u32); + fx.put(&sh); + fx.put(b"8BIMsofi"); + let mut so = Vec::new(); + so.put_u32(2); + so.put(b"8BIMnorm"); + so.put_u16(0); + so.put_u16(0xffff); + so.put_u16(0); + so.put_u16(0); + so.put_u16(0); + so.put_u8(255); + so.put_u8(1); + so.put_u16(0); + so.put_u16(0xffff); + so.put_u16(0); + so.put_u16(0); + so.put_u16(0); + fx.put_u32(so.len() as u32); + fx.put(&so); + let (_, little) = block_rt(*b"lrFX", fx); + assert!(little.windows(8).any(|w| w == b"MIB8wdsd"), "effect keys reversed"); + assert!(little.windows(2).any(|w| w == [0x34, 0x12]), "colour component swapped"); + + // levl: version + 29 records + the Lvls extension. + let mut lv = Vec::new(); + lv.put_u16(2); + for i in 0..29 * 5 { + lv.put_u16(i as u16); + } + lv.put(b"Lvls"); + lv.put_u16(3); + lv.put_u16(33); + for i in 0..4 * 5 { + lv.put_u16(1000 + i as u16); + } + let (_, little) = block_rt(*b"levl", lv); + assert!(little.windows(4).any(|w| w == b"slvL")); + + // curv with the Crv extension. + let mut cv = vec![0u8]; + cv.put_u16(1); + cv.put_u32(0b101); + cv.put_u16(2); + cv.put_u16(0); + cv.put_u16(0); + cv.put_u16(255); + cv.put_u16(255); + cv.put_u16(1); + cv.put_u16(128); + cv.put_u16(100); + cv.put(b"Crv "); + cv.put_u16(4); + cv.put_u32(1); + cv.put_u16(2); + cv.put_u16(1); + cv.put_u16(7); + cv.put_u16(9); + block_rt(*b"curv", cv); + + for (key, data) in [ + (*b"hue2", vec![0, 2, 0, 0, 0, 10, 0, 20, 0, 30, 0, 40, 0, 50, 0, 60]), + (*b"brit", vec![0, 10, 0, 20, 0, 30, 1, 0]), + (*b"thrs", vec![0, 128, 0, 0]), + (*b"post", vec![0, 4, 0, 0]), + (*b"nvrt", vec![]), + (*b"expA", [1u16.to_be_bytes().to_vec(), 0.5f32.to_be_bytes().to_vec(), 0.0f32.to_be_bytes().to_vec(), 1.0f32.to_be_bytes().to_vec()].concat()), + (*b"blnc", vec![0; 20]), + (*b"mixr", vec![0, 1, 0, 0, 0, 100, 0, 0, 0, 0, 0, 0, 0, 0]), + (*b"selc", vec![0, 1, 0, 0, 0, 5, 0, 6, 0, 7, 0, 8]), + (*b"phfl", vec![0, 3, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 25, 1, 0]), + (*b"phfl", vec![0, 2, 0, 0, 1, 0, 2, 0, 3, 0, 4, 0, 0, 0, 25, 1, 0]), + (*b"lclr", vec![0, 1, 0, 0, 0, 0, 0, 0]), + (*b"fxrp", [1.5f64.to_be_bytes().to_vec(), 2.5f64.to_be_bytes().to_vec()].concat()), + (*b"brst", vec![0, 0, 0, 1, 0, 0, 0, 2]), + (*b"FMsk", vec![0, 0, 255, 255, 0, 0, 0, 0, 0, 0, 0, 50]), + (*b"lsct", [3u32.to_be_bytes().to_vec(), b"8BIMpass".to_vec()].concat()), + (*b"lspf", vec![0, 0, 0, 5]), + (*b"lnsr", b"layr".to_vec()), + (*b"knko", vec![1, 0, 0, 0]), + (*b"knko", vec![2, 0, 0, 0]), + (*b"infx", vec![1, 0, 0, 0]), + (*b"clbl", vec![0, 0, 0, 0]), + (*b"tsly", vec![0, 0, 0, 0]), + (*b"lmgm", vec![1, 0, 0, 0]), + (*b"vmgm", vec![1, 0, 0, 0]), + (*b"iOpa", vec![128, 0, 0, 0]), + ] { + let (big, little) = block_rt(key, data.clone()); + if data.len() >= 2 && key != *b"nvrt" { + assert_ne!(big, little, "{}", String::from_utf8_lossy(&key)); + } + } +} + +#[test] +fn global_layer_mask_block() { + let d = ImageSourceData { global_layer_mask: Some(GlobalLayerMask { data: vec![0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 50, 128, 0] }), ..Default::default() }; + let (little, w) = d.to_bytes(ByteOrder::Little).unwrap(); + assert!(w.is_empty()); + assert!(little[36..].starts_with(b"MIB8ksML")); + let (back, _) = ImageSourceData::from_bytes(&little).unwrap(); + assert_eq!(back.global_layer_mask, d.global_layer_mask); + assert_eq!(back.global_layer_mask.unwrap().opacity(), Some(50)); +} + +#[test] +fn gradient_map_layout() { + let mut g = Vec::new(); + g.put_u16(3); + g.put_u8(0); + g.put_u8(1); + g.put(b"Lnr "); + g.put_u32(2); + g.put_u16(u16::from(b'a')); + g.put_u16(0); + g.put_u16(2); + for (loc, mid) in [(0u32, 50u32), (4096, 50)] { + g.put_u32(loc); + g.put_u32(mid); + g.put_u16(0); + g.put_u16(0x1111); + g.put_u16(0x2222); + g.put_u16(0x3333); + g.put_u16(0); + g.put_u16(0); + } + g.put_u16(2); + for loc in [0u32, 4096] { + g.put_u32(loc); + g.put_u32(50); + g.put_u16(100); + } + g.put_u16(2); + g.put_u16(1); + g.put_u16(32); + g.put_u16(0); + g.put_u32(0xdead_beef); + for _ in 0..12 { + g.put_u16(0); + } + let (_, little) = block_rt(*b"grdm", g); + assert!(little.windows(4).any(|w| w == 0xdead_beefu32.to_le_bytes())); + assert!(little.windows(4).any(|w| w == b" rnL")); +} + +#[test] +fn vector_mask_records() { + let mut v = Vec::new(); + v.put_u32(3); + v.put_u32(0); + // Closed length record, then two linked knots. + v.put_u16(0); + v.put_u16(2); + v.put_i16(1); + v.put(&[0; 20]); + for sel in [1u16, 1] { + v.put_u16(sel); + for i in 0..6 { + v.put_i32((i + 1) * 0x0010_0000); + } + } + let (_, little) = block_rt(*b"vmsk", v); + assert!(little.windows(4).any(|w| w == [0, 0, 0x10, 0]), "fixed-point coordinate swapped"); +} + +#[test] +fn pattern_block() { + let plane: Vec = (0..16u8).collect(); + let p = crate::patterns::PsdPattern { + mode: 3, + width: 4, + height: 4, + name: "dots".into(), + id: "abc".into(), + palette: None, + depth: 8, + channels: vec![plane.clone(), plane.clone(), plane.clone()], + alpha: Some(plane), + }; + let data = crate::patterns::write_pattern_block(std::slice::from_ref(&p)).unwrap(); + block_rt(*b"Patt", data.clone()); + // Little-endian pattern data parses back into the same pattern. + let d = ImageSourceData { global_blocks: vec![TaggedBlock::new(*b"Patt", data)], ..Default::default() }; + let (little, _) = d.to_bytes(ByteOrder::Little).unwrap(); + let (back, _) = ImageSourceData::from_bytes(&little).unwrap(); + assert_eq!(crate::patterns::parse_pattern_block(&back.global_blocks[0].data).unwrap(), vec![p]); +} + +#[test] +fn filter_effects_block() { + use crate::filter_effects::{EffectsPlane, FilterEffects, FilterEffectsItem}; + let plane = EffectsPlane::encode(Compression::Rle, &[1, 2, 3, 4, 5, 6], 3, 2, 8).unwrap(); + let mask = EffectsPlane::encode(Compression::Raw, &[9; 6], 3, 2, 8).unwrap(); + let rect = crate::layer::Rect { top: 0, left: 0, bottom: 2, right: 3 }; + let fx = FilterEffects { + version: 1, + items: vec![FilterEffectsItem { + id: "x".into(), + version: 1, + rect, + depth: 8, + max_channels: 1, + slots: vec![Some(plane.clone()), None, Some(plane)], + mask: Some((rect, mask)), + }], + }; + let data = fx.to_bytes(); + block_rt(*b"FEid", data.clone()); + let d = ImageSourceData { global_blocks: vec![TaggedBlock::new(*b"FEid", data)], ..Default::default() }; + let (little, _) = d.to_bytes(ByteOrder::Little).unwrap(); + let (back, _) = ImageSourceData::from_bytes(&little).unwrap(); + assert_eq!(FilterEffects::parse(&back.global_blocks[0].data).unwrap(), fx); +} + +/// Photoshop writes one `FEid` section per smart object: every section's lengths and +/// numbers are swapped, not only the first one's. +#[test] +fn filter_effects_block_swaps_every_section() { + use crate::filter_effects::{EffectsPlane, FilterEffects, FilterEffectsItem}; + let rect = crate::layer::Rect { top: 0, left: 0, bottom: 2, right: 3 }; + let item = |id: &str, v: u8| FilterEffectsItem { + id: id.into(), + version: 1, + rect, + depth: 8, + max_channels: 1, + slots: vec![Some(EffectsPlane::encode(Compression::Raw, &[v; 6], 3, 2, 8).unwrap()), None, None], + mask: None, + }; + let fx = FilterEffects { version: 1, items: vec![item("first", 1), item("second-object", 2)] }; + let data = fx.to_bytes(); + let len1 = u64::from_be_bytes(data[4..12].try_into().unwrap()) as usize; + let second = 12 + len1 + (4 - len1 % 4) % 4; + let len2 = &data[second..second + 8]; + block_rt(*b"FEid", data.clone()); + let d = ImageSourceData { global_blocks: vec![TaggedBlock::new(*b"FEid", data.clone())], ..Default::default() }; + let (little, _) = d.to_bytes(ByteOrder::Little).unwrap(); + // 36-byte signature, then `MIB8`, the reversed key and a u32 length: the block data. + let body = &little[36 + 12..]; + let mut swapped = len2.to_vec(); + swapped.reverse(); + assert_eq!(&body[second..second + 8], &swapped[..], "second section's length is little-endian"); + let (back, w) = ImageSourceData::from_bytes(&little).unwrap(); + assert!(w.is_empty(), "{w:?}"); + assert_eq!(FilterEffects::parse(&back.global_blocks[0].data).unwrap(), fx); +} + +#[test] +fn metadata_setting_items() { + let desc = VersionedDescriptor::new(Descriptor::new("null")).to_bytes(); + let items = vec![crate::metadata::MetadataItem::new(*b"cmls", desc)]; + block_rt(*b"shmd", crate::metadata::write_shmd(&items)); + // An unknown item cannot be converted: it is dropped on its own, the rest stays. + let items = vec![ + crate::metadata::MetadataItem::new(*b"zzzz", vec![1, 2, 3, 4, 5, 6, 7, 8]), + crate::metadata::MetadataItem::new(*b"mdyn", vec![0, 0, 0, 1]), + crate::metadata::MetadataItem::new(*b"cmls", VersionedDescriptor::new(Descriptor::new("null")).to_bytes()), + ]; + let d = ImageSourceData { global_blocks: vec![TaggedBlock::new(*b"shmd", crate::metadata::write_shmd(&items))], ..Default::default() }; + let (little, w) = d.to_bytes(ByteOrder::Little).unwrap(); + assert_eq!(w.len(), 1, "{w:?}"); + assert!(w[0].starts_with("shmd item zzzz dropped"), "{}", w[0]); + let (back, w) = ImageSourceData::from_bytes(&little).unwrap(); + assert!(w.is_empty()); + let back_items = crate::metadata::parse_shmd(&back.global_blocks[0].data).unwrap(); + assert_eq!(back_items, items[1..].to_vec()); +} + +#[test] +fn unknown_descriptor_shaped_blocks_are_converted() { + // A key the transcoder has never heard of, holding a versioned descriptor (as every + // block Photoshop added since CS6 does): converted, not dropped. + let mut desc = Descriptor::new("null"); + desc.items.push((Id::new("Nm "), Value::Text(UnicodeString::new_nul("x")))); + let data = VersionedDescriptor::new(desc.clone()).to_bytes(); + block_rt(*b"Qqqq", data); + let mut with_version = 3u32.to_be_bytes().to_vec(); + with_version.extend(VersionedDescriptor::new(desc).to_bytes()); + block_rt(*b"Qqqq", with_version); + // Empty data needs no conversion either. + block_rt(*b"Mt32", Vec::new()); +} + +#[test] +fn linked_layer_items() { + // One embedded file (liFD, version 7) as photocraft-io writes it. + let mut item = Vec::new(); + item.put(b"liFD"); + item.put_u32(7); + item.put_u8(4); + item.put(b"uuid"); + let units: Vec = "a.png\0".encode_utf16().collect(); + item.put_u32(units.len() as u32); + for u in units { + item.put_u16(u); + } + item.put(b"png "); + item.put(b"8BIM"); + let bytes = [0x89, b'P', b'N', b'G', 1, 2, 3]; + item.put_u64(bytes.len() as u64); + item.put_u8(0); + item.put(&bytes); + item.put_u32(0); + item.put_f64(0.0); + item.put_u8(0); + let mut data = (item.len() as u64).to_be_bytes().to_vec(); + data.put(&item); + while !data.len().is_multiple_of(4) { + data.push(0); + } + let (_, little) = block_rt(*b"lnk2", data); + assert!(little.windows(4).any(|w| w == b"DFil"), "item type key reversed"); + assert!(little.windows(7).any(|w| w == bytes), "file bytes untouched"); +} + +#[test] +fn annotation_block() { + let mut a = Vec::new(); + a.put_u16(2); + a.put_u16(1); + a.put_u32(1); + let mut item = Vec::new(); + item.put(b"txtA"); + item.put_u8(0); + item.put_u8(1); + item.put_u16(0); + for v in [10, 20, 30, 40, 50, 60, 70, 80] { + item.put_i32(v); + } + item.put_u16(0); + for v in [0xffff, 0, 0, 0] { + item.put_u16(v); + } + for s in [&b"me"[..], b"note", b"2026"] { + item.put_u8(s.len() as u8); + item.put(s); + if (1 + s.len()) % 2 == 1 { + item.put_u8(0); + } + } + let text = [0xfe, 0xff, 0, b'h', 0, b'i']; + let mut d = Vec::new(); + d.put(b"txtC"); + d.put_u32(text.len() as u32); + d.put(&text); + item.put_u32(d.len() as u32 + 4); + item.put(&d); + a.put_u32(item.len() as u32 + 4); + a.put(&item); + let (_, little) = block_rt(*b"Anno", a); + assert!(little.windows(4).any(|w| w == b"Atxt")); + assert!(little.windows(6).any(|w| w == text), "text kept as stored"); +} + +#[test] +fn unknown_blocks_kept_in_big_dropped_in_little() { + let mut d = sample_layers(); + d.global_blocks.push(TaggedBlock::new(*b"Zzzz", vec![1, 2, 3, 4, 5])); + let (big, w) = d.to_bytes(ByteOrder::Big).unwrap(); + assert!(w.is_empty()); + let (back, w) = ImageSourceData::from_bytes(&big).unwrap(); + assert!(w.is_empty()); + assert_eq!(back.global_blocks, d.global_blocks); + // Big-endian data of unknown layout cannot go into a little-endian file. + let (little, w) = d.to_bytes(ByteOrder::Little).unwrap(); + assert_eq!(w.iter().filter(|w| w.starts_with("Zzzz block (5 bytes) dropped")).count(), 1, "{w:?}"); + let (back, w) = ImageSourceData::from_bytes(&little).unwrap(); + assert!(w.is_empty()); + assert_eq!(back.global_blocks.iter().map(|b| b.key).collect::>(), vec![*b"Patt", *b"FMsk"]); + assert_eq!(known(&back).layer_info, known(&d).layer_info); +} + +#[test] +fn unknown_blocks_from_a_little_endian_file_are_kept_with_their_byte_order() { + let d = sample_layers(); + let (little, _) = d.to_bytes(ByteOrder::Little).unwrap(); + // A little-endian file with a block of unknown layout, among known ones. + let mut raw = little.clone(); + raw.extend_from_slice(b"MIB8zzzZ"); + raw.extend_from_slice(&6u32.to_le_bytes()); + raw.extend_from_slice(&[9, 8, 7, 6, 5, 4, 0, 0]); + raw.extend_from_slice(b"MIB8diyl"); + raw.extend_from_slice(&4u32.to_le_bytes()); + raw.extend_from_slice(&7u32.to_le_bytes()); + let (back, w) = ImageSourceData::from_bytes(&raw).unwrap(); + assert!(w.is_empty(), "{w:?}"); + assert_eq!(known(&back).layer_info, known(&d).layer_info); + let kept = back.global_blocks.iter().find(|b| &b.key == b"Zzzz").expect("kept"); + assert!(kept.is_foreign_order()); + assert_eq!(kept.signature, *b"MIB8"); + assert_eq!(kept.data, [9, 8, 7, 6, 5, 4]); + // The known block after it was still converted. + assert_eq!(back.global_blocks.iter().find(|b| &b.key == b"lyid").unwrap().data, 7u32.to_be_bytes()); + // Written back to a little-endian TIFF, the bytes are exactly what was read. + let (again, w) = back.to_bytes(ByteOrder::Little).unwrap(); + assert!(w.is_empty(), "{w:?}"); + let tail = &raw[raw.len() - 18 - 16..]; + assert!(again.windows(tail.len()).any(|x| x == tail), "foreign-order block restored verbatim"); + assert_eq!(ImageSourceData::from_bytes(&again).unwrap().0.global_blocks, back.global_blocks); + // The big-endian (PSD) model keeps the marker, so a PSD writer can tell it apart. + let (big, _) = back.to_bytes(ByteOrder::Big).unwrap(); + assert!(big.windows(8).any(|x| x == b"MIB8Zzzz")); + assert_eq!(ImageSourceData::from_bytes(&big).unwrap().0.global_blocks, back.global_blocks); +} + +/// A PSB keeps `Mt16`/`Mt32`/`Mtrn`/`Alph` blocks of unknown layout verbatim, and their +/// length field is 8 bytes (a PSB long key). Writing them into a little-endian TIFF must +/// read that width; the old code looked the key up after reversing it for the target +/// order, which never matches `PSB_LONG_KEYS`. +#[test] +fn psb_foreign_order_long_key_roundtrips() { + let d = ImageSourceData { + version: Version::Psb, + byte_order: ByteOrder::Little, + global_blocks: vec![TaggedBlock { signature: *b"MIB8", key: *b"Mt16", data: vec![9, 8, 7, 6, 5, 4], padding: None }], + ..Default::default() + }; + let (little, w) = d.to_bytes(ByteOrder::Little).unwrap(); + assert!(w.is_empty(), "{w:?}"); + let (back, w) = ImageSourceData::from_bytes(&little).unwrap(); + assert!(w.is_empty(), "{w:?}"); + assert_eq!(back.global_blocks, d.global_blocks, "the 8-byte length and the bytes survive"); +} + +#[test] +fn rle_counts_follow_the_container_and_samples_do_not() { + let file = testgen::layered(Version::Psd, ColorMode::Rgb, 16, Compression::Rle); + let d = ImageSourceData::from_psd(&file); + let (big, _) = d.to_bytes(ByteOrder::Big).unwrap(); + let (little, _) = d.to_bytes(ByteOrder::Little).unwrap(); + let (back, _) = ImageSourceData::from_bytes(&little).unwrap(); + let d = known(&d); + let (a, b) = (d.layer_info.as_ref().unwrap(), back.layer_info.as_ref().unwrap()); + for (la, lb) in a.layers.iter().zip(&b.layers) { + for (ca, cb) in la.channels.iter().zip(&lb.channels) { + assert_eq!(ca, cb); + let (w, h) = la.channel_rect(ca.id).size().unwrap(); + assert_eq!(ca.decode(w, h, 16, Version::Psd).unwrap(), cb.decode(w, h, 16, Version::Psd).unwrap()); + } + } + // The encoded samples (after the count table) are identical bytes in both files, while + // the count table itself is swapped. + let (rec, ch) = a + .layers + .iter() + .flat_map(|l| l.channels.iter().filter(|c| c.id >= -1 && c.compression == Some(Compression::Rle)).map(move |c| (l, c))) + .find(|(l, c)| l.rect.height() > 1 && c.data.len() > l.rect.height() as usize * 2 + 8) + .unwrap(); + let table = rec.rect.height() as usize * 2; + let samples = &ch.data[table..]; + assert!(big.windows(samples.len()).any(|w| w == samples)); + assert!(little.windows(samples.len()).any(|w| w == samples)); + let counts = &ch.data[..table]; + let swapped: Vec = counts.chunks(2).flat_map(|c| [c[1], c[0]]).collect(); + assert!(little.windows(table + samples.len()).any(|w| w[..table] == swapped[..] && w[table..] == *samples)); +} + +#[test] +fn blending_ranges_are_bytes_in_either_order() { + let mut file = testgen::layered(Version::Psd, ColorMode::Rgb, 8, Compression::Rle); + let ranges: Vec = [0u8, 0, 255, 255].repeat(10); + let marked: Vec = (1u8..=40).collect(); + for (i, l) in file.layer_info.as_mut().unwrap().layers.iter_mut().enumerate() { + l.blending_ranges.data = if i == 0 { marked.clone() } else { ranges.clone() }; + } + let d = ImageSourceData::from_psd(&file); + let (little, _) = d.to_bytes(ByteOrder::Little).unwrap(); + // Written verbatim (what Photoshop writes in an `II` TIFF), not swapped per u32. + assert!(little.windows(marked.len()).any(|w| w == marked)); + let (back, _) = ImageSourceData::from_bytes(&little).unwrap(); + for (a, b) in d.layer_info.as_ref().unwrap().layers.iter().zip(&back.layer_info.as_ref().unwrap().layers) { + assert_eq!(a.blending_ranges, b.blending_ranges); + } +} + +#[test] +fn psb_sized_data_uses_long_lengths_and_counts() { + let file = testgen::layered(Version::Psb, ColorMode::Cmyk, 8, Compression::Rle); + let d = ImageSourceData::from_psd(&file); + assert_eq!(d.version, Version::Psb); + let back = roundtrip(&d); + assert_eq!(back.layer_info, d.layer_info); + let (little, _) = d.to_bytes(ByteOrder::Little).unwrap(); + assert!(little[36..].starts_with(b"MIB8")); + let (back, _) = ImageSourceData::from_bytes(&little).unwrap(); + assert_eq!(known(&back).layer_info, known(&d).layer_info); +} + +#[test] +fn resources_both_orders() { + let res = vec![ + ImageResource::new(1005, vec![0, 72, 0, 0, 0, 1, 0, 1, 0, 72, 0, 0, 0, 1, 0, 1]), + ImageResource::new(1037, vec![0, 0, 0, 120]), + ImageResource::new(1039, vec![1, 2, 3]), + ImageResource { signature: *b"8BIM", id: 1026, name: b"grp".to_vec(), data: vec![0, 1, 0, 1, 0, 0] }, + ]; + let big = resources_to_bytes(&res).unwrap(); + let (back, w) = resources_from_bytes(&big).unwrap(); + assert!(w.is_empty()); + assert_eq!(back, res); + let (little, w) = transcode_resources(&big, ByteOrder::Big, ByteOrder::Little).unwrap(); + assert!(w.is_empty()); + assert!(little.starts_with(b"MIB8")); + assert_eq!(little.len(), big.len()); + assert_eq!(&little[4..6], &[0xed, 3]); + let (back, w) = resources_from_bytes(&little).unwrap(); + assert!(w.is_empty()); + assert_eq!(back, res); + // The ICC blob is untouched by the swap. + assert!(little.windows(3).any(|w| w == [1, 2, 3])); + // An odd trailing pad byte is tolerated. + let mut padded = big.clone(); + padded.push(0); + assert_eq!(resources_from_bytes(&padded).unwrap().0, res); +} + +#[test] +fn malformed_input_errors_without_panicking() { + assert!(ImageSourceData::from_bytes(b"").is_err()); + assert!(ImageSourceData::from_bytes(b"Adobe Photoshop Document Data Block").is_err()); + let mut bad = SIGNATURE.to_vec(); + bad.extend_from_slice(b"XXXXLayr"); + assert!(ImageSourceData::from_bytes(&bad).is_err()); + let d = sample_layers(); + for order in [ByteOrder::Big, ByteOrder::Little] { + let (bytes, _) = d.to_bytes(order).unwrap(); + for cut in (0..bytes.len()).step_by(7).chain(bytes.len().saturating_sub(8)..bytes.len()) { + let _ = ImageSourceData::from_bytes(&bytes[..cut]); + } + // Bit flips in the structure (not the signature). + for i in (36..bytes.len()).step_by(13) { + let mut b = bytes.clone(); + b[i] ^= 0x5a; + let _ = ImageSourceData::from_bytes(&b); + } + } + // A block that claims more data than exists. + let mut huge = SIGNATURE.to_vec(); + huge.extend_from_slice(b"8BIMluni"); + huge.extend_from_slice(&u32::MAX.to_be_bytes()); + assert!(ImageSourceData::from_bytes(&huge).is_err()); + assert!(resources_from_bytes(b"8BIM\x03\xed\x00").is_err()); +} + +#[test] +fn into_psd_roundtrips_through_the_psd_writer() { + let file = testgen::layered(Version::Psd, ColorMode::Grayscale, 8, Compression::Zip); + let d = ImageSourceData::from_psd(&file); + let (little, _) = d.to_bytes(ByteOrder::Little).unwrap(); + let (back, _) = ImageSourceData::from_bytes(&little).unwrap(); + let psd = back.into_psd(file.header.clone(), file.resources.clone(), file.image_data.clone()); + let bytes = psd.to_bytes().unwrap(); + let again = PsdFile::from_bytes(&bytes).unwrap(); + let expected = known(&ImageSourceData::from_psd(&file)); + assert_eq!(known(&ImageSourceData::from_psd(&again)).layer_info, expected.layer_info); + assert_eq!(again.global_blocks, expected.global_blocks); + assert_eq!(again.layer_tree().len(), file.layer_tree().len()); +} + +/// Global blocks are padded as they are written, not on a copy: the bytes are those of the +/// former path (each block cloned with explicit padding to 4, written with `write_blocks`). +#[test] +fn global_blocks_written_without_copies_keep_their_bytes() { + for version in [Version::Psd, Version::Psb] { + let mut d = ImageSourceData { version, global_layer_mask: Some(GlobalLayerMask { data: vec![0, 1, 0, 2, 0, 3, 0, 4, 9] }), ..Default::default() }; + for n in 0..8u8 { + d.global_blocks.push(TaggedBlock::new(*b"FMsk", (0..n).collect())); + } + let mut explicit = TaggedBlock::new(*b"FMsk", vec![1, 2, 3]); + explicit.padding = Some(vec![]); + d.global_blocks.push(explicit); + let mut odd = TaggedBlock::new(*b"FMsk", vec![1, 2]); + odd.padding = Some(vec![0, 0, 0, 0, 0]); + d.global_blocks.push(odd); + let mut copies = vec![padded_block(*b"LMsk", d.global_layer_mask.as_ref().unwrap().data.clone())]; + for b in &d.global_blocks { + let mut b = b.clone(); + if b.padding.is_none() { + b.padding = Some(vec![0; (4 - b.data.len() % 4) % 4]); + } + copies.push(b); + } + let mut body = Vec::new(); + crate::tagged::write_blocks(&mut body, &copies, version, 2).unwrap(); + let signature = if version.is_psb() { SIGNATURE_PSB } else { SIGNATURE }; + assert_eq!(d.to_bytes(ByteOrder::Big).unwrap().0, [signature, &body[..]].concat()); + let (little, _) = transcode_blocks(&body, version, ByteOrder::Big, ByteOrder::Little).unwrap(); + assert_eq!(d.to_bytes(ByteOrder::Little).unwrap().0, [signature, &little[..]].concat()); + } +} + +/// Nested structures are transcoded into one shared buffer. A block whose body fails +/// part-way leaves no partial bytes: dropped on the way out (with the enclosing lengths +/// patched as if it had never been there), or kept exactly as stored on the way in. +#[test] +fn a_nested_block_that_fails_part_way_leaves_nothing_behind() { + let clean = sample_layers(); + let mut fx = Vec::new(); + fx.put_u32(0); + fx.extend_from_slice(&VersionedDescriptor::new(Descriptor::new("null").with("Opct", Value::Double(1.0))).to_bytes()); + // A whole number of 4-byte units, so dropping it cannot change any padding. + fx.resize(fx.len().next_multiple_of(4), 0); + let mut d = clean.clone(); + d.layer_info.as_mut().unwrap().layers[0].blocks.insert(0, TaggedBlock::new(*b"lfx2", fx.clone())); + let (mut little, w) = d.to_bytes(ByteOrder::Little).unwrap(); + assert!(!w.iter().any(|w| w.starts_with("lfx2")), "{w:?}"); + // An unknown value type after the descriptor's header: parsing fails part-way. + let at = little.windows(4).position(|w| w == b"buod").unwrap(); + little[at..at + 4].copy_from_slice(b"????"); + let (back, w) = ImageSourceData::from_bytes(&little).unwrap(); + assert_eq!(w.iter().filter(|w| w.starts_with("lfx2 block")).count(), 1, "{w:?}"); + let kept = &back.layer_info.as_ref().unwrap().layers[0].blocks[0]; + assert!(kept.is_foreign_order()); + let stored = little.windows(4).position(|w| w == b"2xfl").unwrap() + 8; + assert_eq!(kept.data, little[stored..stored + fx.len()]); + // Big-endian data that fails part-way cannot go into a little-endian file: dropped. + let mut big_bad = d.clone(); + let mut broken = fx.clone(); + let at = broken.windows(4).position(|w| w == b"doub").unwrap(); + broken[at..at + 4].copy_from_slice(b"????"); + big_bad.layer_info.as_mut().unwrap().layers[0].blocks[0].data = broken; + let (little, w) = big_bad.to_bytes(ByteOrder::Little).unwrap(); + assert_eq!(w.iter().filter(|w| w.starts_with("lfx2 block")).count(), 1, "{w:?}"); + assert_eq!(little, clean.to_bytes(ByteOrder::Little).unwrap().0); +} diff --git a/crates/psd/src/tiff/transcode.rs b/crates/psd/src/tiff/transcode.rs new file mode 100644 index 0000000000..c006dc4fa0 --- /dev/null +++ b/crates/psd/src/tiff/transcode.rs @@ -0,0 +1,1384 @@ +use super::*; + +/// Converts the tagged blocks after the 37724 header string from `from` to `to`. +pub fn transcode_blocks(data: &[u8], version: Version, from: ByteOrder, to: ByteOrder) -> Result<(Vec, Vec)> { + let mut t = Tx::new(data, version, from, to); + t.blocks()?; + Ok(t.finish()) +} + +/// Converts a layer-info body (the data of a `Layr` / `Lr16` / `Lr32` block) between orders. +pub fn transcode_layer_info(data: &[u8], version: Version, from: ByteOrder, to: ByteOrder) -> Result<(Vec, Vec)> { + let mut t = Tx::new(data, version, from, to); + t.layer_info()?; + Ok(t.finish()) +} + +/// Converts image-resource blocks (a 34377 tag) between orders. +pub fn transcode_resources(data: &[u8], from: ByteOrder, to: ByteOrder) -> Result<(Vec, Vec)> { + let mut t = Tx::new(data, Version::Psd, from, to); + t.resources()?; + Ok(t.finish()) +} + +/// A block signature as stored in `little` or big-endian data. Big-endian data (the model) +/// also carries the `MIB8` / `46B8` markers of blocks kept from a little-endian file. +fn is_sig(b: &[u8], little: bool) -> bool { + if little { + b.starts_with(b"MIB8") || b.starts_with(b"46B8") + } else { + b.starts_with(b"8BIM") || b.starts_with(b"8B64") || TaggedBlock::is_foreign_order_signature(b) + } +} + +fn height(top: i32, bottom: i32) -> usize { + usize::try_from(bottom.saturating_sub(top)).unwrap_or(0) +} + +/// Per layer record: the channel (id, length) list and the heights of the layer, mask and +/// real-mask rects. +type RecordShape = (Vec<(i16, u64)>, [usize; 3]); + +struct Tx<'a> { + r: Reader<'a>, + out: Vec, + from: ByteOrder, + to: ByteOrder, + version: Version, + warnings: Vec, + depth: usize, +} + +macro_rules! copy_int { + ($name:ident, $ty:ty) => { + fn $name(&mut self) -> Result<$ty> { + let v = self.r.$name()?; + self.out.extend_from_slice(&if self.to.is_little() { v.to_le_bytes() } else { v.to_be_bytes() }); + Ok(v) + } + }; +} + +impl<'a> Tx<'a> { + fn new(data: &'a [u8], version: Version, from: ByteOrder, to: ByteOrder) -> Self { + let r = if from.is_little() { Reader::new_little(data) } else { Reader::new(data) }; + Tx { r, out: Vec::with_capacity(data.len()), from, to, version, warnings: Vec::new(), depth: 0 } + } + + fn finish(self) -> (Vec, Vec) { + (self.out, self.warnings) + } + + /// A walker over `data` (a nested structure) that writes into this walker's output: it + /// takes the buffer, so a nested structure is written once, not copied up per level. Hand + /// the buffer back with [`Self::adopt`] before returning, error or not. + fn nested<'b>(&mut self, data: &'b [u8], depth: usize) -> Tx<'b> { + let r = if self.from.is_little() { Reader::new_little(data) } else { Reader::new(data) }; + Tx { r, out: std::mem::take(&mut self.out), from: self.from, to: self.to, version: self.version, warnings: Vec::new(), depth } + } + + /// Takes the output buffer back from a [`Self::nested`] walker. + fn adopt(&mut self, child: &mut Tx<'_>) { + self.out = std::mem::take(&mut child.out); + } + + fn same_order(&self) -> bool { + self.from == self.to + } + + fn remaining(&self) -> usize { + self.r.remaining() + } + + copy_int!(u16, u16); + copy_int!(i16, i16); + copy_int!(u32, u32); + copy_int!(i32, i32); + copy_int!(u64, u64); + copy_int!(i64, i64); + copy_int!(f64, f64); + + fn u8(&mut self) -> Result { + let v = self.r.u8()?; + self.out.push(v); + Ok(v) + } + + fn f32(&mut self) -> Result<()> { + let b = self.r.array::<4>()?; + let v = if self.from.is_little() { f32::from_le_bytes(b) } else { f32::from_be_bytes(b) }; + self.out.extend_from_slice(&if self.to.is_little() { v.to_le_bytes() } else { v.to_be_bytes() }); + Ok(()) + } + + /// Bytes copied as they are. + fn raw(&mut self, n: usize) -> Result<()> { + let b = self.r.bytes(n)?; + self.out.extend_from_slice(b); + Ok(()) + } + + fn rest(&mut self) -> Result<()> { + let n = self.remaining(); + self.raw(n) + } + + /// A four-character signature or key: stored reversed in little-endian data. Returns the + /// canonical (big-endian) spelling. + fn key(&mut self) -> Result<[u8; 4]> { + let mut k = self.r.array::<4>()?; + if self.from.is_little() { + k.reverse(); + } + let mut w = k; + if self.to.is_little() { + w.reverse(); + } + self.out.extend_from_slice(&w); + Ok(k) + } + + fn len(&mut self, long: bool) -> Result { + if long { self.u64() } else { Ok(u64::from(self.u32()?)) } + } + + fn u16s(&mut self, n: usize) -> Result<()> { + for _ in 0..n { + self.u16()?; + } + Ok(()) + } + + /// Up to `n` `u16`s: a block shorter than its full layout keeps what it has. + fn u16s_upto(&mut self, n: usize) -> Result<()> { + for _ in 0..n { + if self.remaining() < 2 { + break; + } + self.u16()?; + } + Ok(()) + } + + fn i32s(&mut self, n: usize) -> Result<()> { + for _ in 0..n { + self.i32()?; + } + Ok(()) + } + + fn f64s(&mut self, n: usize) -> Result<()> { + for _ in 0..n { + self.f64()?; + } + Ok(()) + } + + /// `u16`s to the end (a lone odd byte is copied). + fn u16s_to_end(&mut self) -> Result<()> { + while self.remaining() >= 2 { + self.u16()?; + } + self.rest() + } + + fn u32s_to_end(&mut self) -> Result<()> { + while self.remaining() >= 4 { + self.u32()?; + } + self.rest() + } + + /// A Photoshop Unicode string: u32 count + UTF-16 units. + fn unicode(&mut self) -> Result<()> { + let n = self.u32()?; + self.r.check_count(u64::from(n), 2)?; + self.u16s(n as usize) + } + + /// A Pascal string padded to `align`. + fn pascal(&mut self, align: usize) -> Result<()> { + let n = usize::from(self.u8()?); + self.raw(n)?; + let total = 1 + n; + self.raw((align - total % align) % align) + } + + /// Transcodes the next `len` bytes with `f`; whatever `f` leaves is copied verbatim. + fn region(&mut self, len: u64, f: impl FnOnce(&mut Tx<'_>) -> Result<()>) -> Result<()> { + let data = self.r.bytes_u64(len)?; + let start = self.out.len(); + let mut child = self.nested(data, self.depth); + let res = f(&mut child).and_then(|()| child.rest()); + self.adopt(&mut child); + res?; + if self.out.len() - start != data.len() { + return Err(PsdError::invalid("byte-order conversion changed a structure's length")); + } + self.warnings.append(&mut child.warnings); + Ok(()) + } + + /// Reads a length field (4 bytes, or 8 when `long`), transcodes that many bytes with `f` + /// and writes the length of the result: blocks dropped inside shrink the field. + fn sized_region(&mut self, long: bool, f: impl FnOnce(&mut Tx<'_>) -> Result<()>) -> Result<()> { + self.sized_region_counting(long, false, f) + } + + /// [`Self::sized_region`] for a u32 length that counts its own 4 bytes. + fn sized_region_inclusive(&mut self, f: impl FnOnce(&mut Tx<'_>) -> Result<()>) -> Result<()> { + self.sized_region_counting(false, true, f) + } + + fn sized_region_counting(&mut self, long: bool, inclusive: bool, f: impl FnOnce(&mut Tx<'_>) -> Result<()>) -> Result<()> { + let mut len = self.r.len_field(long)?; + let at = self.out.len(); + self.out.extend_from_slice(if long { &[0u8; 8] } else { &[0u8; 4] }); + if inclusive { + len = len.checked_sub(4).ok_or_else(|| PsdError::invalid("length shorter than its own field"))?; + } + let data = self.r.bytes_u64(len)?; + let start = self.out.len(); + let mut child = self.nested(data, self.depth); + let res = f(&mut child).and_then(|()| child.rest()); + self.adopt(&mut child); + res?; + self.warnings.append(&mut child.warnings); + self.patch_len(at, long, (self.out.len() - start) as u64 + if inclusive { 4 } else { 0 })?; + Ok(()) + } + + /// Tries `f` on the rest of the data; it counts as a match only when at most three + /// trailing zero bytes are left. On a miss nothing is consumed or written. + fn attempt(&mut self, f: impl FnOnce(&mut Tx<'_>) -> Result<()>) -> bool { + let (reader, written) = (self.r.clone(), self.out.len()); + let ok = f(self).is_ok() && self.remaining() <= 3 && self.r.peek_rest().iter().all(|&b| b == 0); + if !ok { + self.r = reader; + self.out.truncate(written); + } + ok + } + + /// Blocks whose layout is not known by key are very often a versioned descriptor, + /// optionally behind a u32 version (every Photoshop block introduced since CS6 is): + /// recognized by parsing to the end. + fn descriptor_shaped(&mut self) -> bool { + self.attempt(|t| t.versioned_descriptor()) + || self.attempt(|t| { + t.u32()?; + t.versioned_descriptor() + }) + } + + /// Writes `n` into the length placeholder at `at`. + fn patch_len(&mut self, at: usize, long: bool, n: u64) -> Result<()> { + if long { + let b = if self.to.is_little() { n.to_le_bytes() } else { n.to_be_bytes() }; + if let Some(slot) = self.out.get_mut(at..at + 8) { + slot.copy_from_slice(&b); + } + } else { + let n = u32::try_from(n).map_err(|_| PsdError::LimitExceeded("structure too large for a 32-bit length"))?; + let b = if self.to.is_little() { n.to_le_bytes() } else { n.to_be_bytes() }; + if let Some(slot) = self.out.get_mut(at..at + 4) { + slot.copy_from_slice(&b); + } + } + Ok(()) + } + + /// An RLE row-count table (`rows` entries of 2 bytes, 4 in PSB data). + fn rle_counts(&mut self, rows: usize) -> Result<()> { + for _ in 0..rows { + if self.version.is_psb() { + if self.remaining() < 4 { + break; + } + self.u32()?; + } else { + if self.remaining() < 2 { + break; + } + self.u16()?; + } + } + Ok(()) + } + + /// Encoded channel data for a plane of `rows` rows: the compression field, then the RLE + /// row counts (container order) and the samples (always big-endian: copied). + fn channel_data(&mut self, rows: usize, long_counts: bool) -> Result<()> { + let saved = self.version; + if long_counts { + self.version = Version::Psb; + } + let compression = self.u16()?; + let res = if compression == 1 { self.rle_counts(rows) } else { Ok(()) }; + self.version = saved; + res?; + self.rest() + } + + // ---- image resources (34377) ---- + + fn resources(&mut self) -> Result<()> { + while self.remaining() >= 12 && is_sig(self.r.peek_rest(), self.from.is_little()) { + self.key()?; + let id = self.u16()?; + self.pascal(2)?; + let odd = self.r.clone().u32()? % 2 == 1; + self.sized_region(false, |t| t.resource_data(id))?; + if odd && self.remaining() > 0 { + self.raw(1)?; + } + } + self.rest() + } + + /// Typed numeric resources; every other payload is a byte blob (ICC, XMP, EXIF, …) or + /// unknown and is copied as stored. + fn resource_data(&mut self, id: u16) -> Result<()> { + match id { + // Resolution info: fixed 16.16 h res, u16 unit, u16 width unit, then the same for v. + 1005 => { + self.u32()?; + self.u16()?; + self.u16()?; + self.u32()?; + self.u16()?; + self.u16()?; + } + // Layer state (u16 target), layer group info (u16 per layer). + 1024 | 1026 => self.u16s_to_end()?, + // Global angle / altitude. + 1037 | 1049 => { + self.u32()?; + } + // Layer selection ids: u16 count + u32 ids. + 1069 => { + self.u16()?; + self.u32s_to_end()?; + } + // Version info: u32 version, u8 has real merged data, two Unicode strings, u32. + 1057 => { + self.u32()?; + self.u8()?; + self.unicode()?; + self.unicode()?; + self.u32()?; + } + // Grid and guides: u32 version, 2 × u32 grid, u32 count, (u32 location, u8 direction)… + 1032 => { + self.u32()?; + self.u32()?; + self.u32()?; + let n = self.u32()?; + for _ in 0..n { + if self.remaining() < 5 { + break; + } + self.u32()?; + self.u8()?; + } + } + // Path resources: 26-byte records. + 2000..=2997 | 2999 => self.path_records()?, + _ => {} + } + Ok(()) + } + + // ---- tagged blocks ---- + + /// Tagged blocks to the end; bytes that do not form a block are copied. + fn blocks(&mut self) -> Result<()> { + loop { + let rest = self.r.peek_rest(); + if rest.len() < 12 || !is_sig(rest, self.from.is_little()) { + return self.rest(); + } + self.block()?; + } + } + + fn block(&mut self) -> Result<()> { + let before = self.out.len(); + // A `MIB8` / `46B8` marker in big-endian data: a block kept verbatim from a + // little-endian file. Written back as it was into little-endian output (its `8BIM` + // signature reversed, as every signature there), copied as is otherwise. + if !self.from.is_little() && TaggedBlock::is_foreign_order_signature(self.r.peek_rest()) { + let sig = self.r.array::<4>()?; + let mut key = self.r.array::<4>()?; + // Only reached with `from == Big`: the key is canonical here whatever the + // target order. `TaggedBlock::write` sizes the length field from that same key. + // Reversing it for the target order before the check + // asked about a key `PSB_LONG_KEYS` never contains, so a PSB long key's 8-byte + // length was read as 4 and every later block was copied unconverted. + let long = uses_long_length(self.version, &key); + let len = self.r.len_field(long)?; + let data = self.r.bytes_u64(len)?; + if self.to.is_little() { + key.reverse(); + } + self.out.extend_from_slice(&sig); + self.out.extend_from_slice(&key); + let n = self.out.len(); + self.out.extend_from_slice(if long { &[0u8; 8] } else { &[0u8; 4] }); + self.patch_len(n, long, len)?; + self.out.extend_from_slice(data); + let rest = self.r.peek_rest(); + let pad = (0..=3usize).find(|&k| k == rest.len() || (k < rest.len() && is_sig(&rest[k..], self.from.is_little()))).unwrap_or(0); + let pad_bytes = self.r.bytes(pad)?; + self.out.extend_from_slice(pad_bytes); + return Ok(()); + } + let sig_at = self.out.len(); + let sig = self.key()?; + let key = self.key()?; + let long = uses_long_length(self.version, &key); + let len = self.r.len_field(long)?; + let len_at = self.out.len(); + self.out.extend_from_slice(if long { &[0u8; 8] } else { &[0u8; 4] }); + let data = self.r.bytes_u64(len)?; + // The body is transcoded straight into this output, after the length placeholder. + let data_at = self.out.len(); + let mut child = self.nested(data, self.depth + 1); + let handled = if child.depth > MAX_DEPTH { + Err(PsdError::LimitExceeded("tagged block nesting too deep")) + } else if data.is_empty() { + Ok(true) + } else { + child.block_body(&key) + }; + let rest = if matches!(handled, Ok(true)) { child.rest() } else { Ok(()) }; + self.adopt(&mut child); + rest?; + if !matches!(handled, Ok(true)) { + // A body that was not transcoded leaves nothing: it is copied as stored or dropped. + self.out.truncate(data_at); + } + // Padding: the smallest k in 0..=3 after which the next block (or the end) starts. + let rest = self.r.peek_rest(); + let pad = (0..=3usize).find(|&k| k == rest.len() || (k < rest.len() && is_sig(&rest[k..], self.from.is_little()))).unwrap_or(0); + let pad_bytes = self.r.bytes(pad)?; + match handled { + Ok(true) => { + self.warnings.append(&mut child.warnings); + self.patch_len(len_at, long, (self.out.len() - data_at) as u64)?; + self.out.extend_from_slice(pad_bytes); + } + Ok(false) if self.same_order() => { + self.patch_len(len_at, long, data.len() as u64)?; + self.out.extend_from_slice(data); + self.out.extend_from_slice(pad_bytes); + } + // Little-endian in, big-endian model: keep the bytes as they are, marked. + Ok(false) if self.from.is_little() => { + let marker: &[u8; 4] = if &sig == b"8B64" { b"46B8" } else { b"MIB8" }; + self.out[sig_at..sig_at + 4].copy_from_slice(marker); + self.patch_len(len_at, long, data.len() as u64)?; + self.out.extend_from_slice(data); + self.out.extend_from_slice(pad_bytes); + } + Ok(false) => { + self.out.truncate(before); + self.warnings.push(format!( + "{} block ({} bytes) dropped: its layout is unknown and cannot be converted to the file's byte order", + String::from_utf8_lossy(&key), + data.len() + )); + } + Err(e) if self.same_order() => return Err(PsdError::invalid(format!("{} block: {e}", String::from_utf8_lossy(&key)))), + Err(e) if self.from.is_little() => { + let marker: &[u8; 4] = if &sig == b"8B64" { b"46B8" } else { b"MIB8" }; + self.out[sig_at..sig_at + 4].copy_from_slice(marker); + self.patch_len(len_at, long, data.len() as u64)?; + self.out.extend_from_slice(data); + self.out.extend_from_slice(pad_bytes); + self.warnings.push(format!("{} block ({} bytes) kept as stored, in little-endian layout: {e}", String::from_utf8_lossy(&key), data.len())); + } + Err(e) => { + self.out.truncate(before); + self.warnings.push(format!("{} block ({} bytes) dropped: {e}", String::from_utf8_lossy(&key), data.len())); + } + } + Ok(()) + } + + /// Transcodes a block's data by key. `Ok(false)` for keys without a known layout. + fn block_body(&mut self, key: &[u8; 4]) -> Result { + match key { + b"Layr" | b"Lr16" | b"Lr32" => self.layer_info()?, + b"luni" => self.unicode()?, + b"lsct" | b"lsdk" => { + self.u32()?; + if self.remaining() >= 8 { + self.key()?; + self.key()?; + } + if self.remaining() >= 4 { + self.u32()?; + } + } + // lyvr layer version, sn2P and vowv (shape and vector flags). + b"lyid" | b"lspf" | b"lyvr" | b"sn2P" | b"vowv" => { + self.u32()?; + } + // Text-engine global data: a textual structure, no byte order. + b"Txt2" => self.rest()?, + b"lnsr" => { + self.key()?; + } + // Advanced Blending flags and fill opacity: one byte, then padding (Adobe spec, + // "Additional Layer Information"; `lmgm`/`vmgm` = layer/vector mask hides effects). + b"clbl" | b"infx" | b"knko" | b"tsly" | b"lmgm" | b"vmgm" | b"iOpa" => { + self.u8()?; + } + b"lclr" => self.u16s_upto(4)?, + b"fxrp" => { + while self.remaining() >= 8 { + self.f64()?; + } + } + b"brst" => self.u32s_to_end()?, + b"LMsk" => self.u16s_upto(6)?, + b"FMsk" => self.u16s_to_end()?, + b"shmd" => self.metadata_setting()?, + // Effects (lfxs: the effects as applied to a group), content credentials (CAI). + b"lfx2" | b"lmfx" | b"lfxs" | b"CAI " => { + self.u32()?; + self.versioned_descriptor()?; + } + b"SoCo" | b"GdFl" | b"PtFl" | b"vstk" | b"blwh" | b"vibA" | b"CgEd" | b"artb" | b"artd" | b"cinf" | b"cust" | b"PxSD" | b"GenI" | b"OCIO" + | b"extn" | b"pths" => { + self.versioned_descriptor()?; + } + // Color Lookup: u16 version, then the descriptor. + b"clrL" => { + self.u16()?; + self.versioned_descriptor()?; + } + b"lnk2" | b"lnk3" | b"lnkD" | b"lnkE" => self.linked_layers()?, + b"Anno" => self.annotations()?, + b"vogk" => { + self.u32()?; + self.versioned_descriptor()?; + } + b"vscg" => { + self.key()?; + self.versioned_descriptor()?; + } + b"SoLd" | b"SoLE" => { + self.key()?; + self.u32()?; + self.versioned_descriptor()?; + } + b"PlLd" => { + self.key()?; + self.u32()?; + self.pascal(1)?; + for _ in 0..4 { + self.u32()?; + } + self.f64s(8)?; + self.u32()?; + self.versioned_descriptor()?; + } + // Type: version, transform, text version + descriptor, warp version + descriptor, + // and the bounds as four 32-bit values (the specification says doubles; Photoshop + // writes 16 bytes). + b"TySh" => self.type_layer()?, + b"vmsk" | b"vsms" => { + self.u32()?; + self.u32()?; + self.path_records()?; + } + b"Patt" | b"Pat2" | b"Pat3" => { + while self.remaining() >= 4 { + let len = self.r.clone().u32()?; + if len == 0 { + self.u32()?; + continue; + } + self.sized_region(false, Tx::pattern)?; + // Each pattern is padded to a multiple of 4. + let pad = ((4 - len % 4) % 4) as usize; + self.raw(pad.min(self.remaining()))?; + } + } + b"FEid" | b"FXid" => self.filter_effects()?, + b"lrFX" => self.legacy_effects()?, + b"levl" => { + self.u16()?; + for _ in 0..29 * 5 { + if self.remaining() < 2 { + break; + } + self.u16()?; + } + if self.remaining() >= 4 { + self.key()?; + } + self.u16s_to_end()?; + } + b"curv" => self.curves()?, + b"hue2" => { + self.u16()?; + self.u8()?; + self.u8()?; + self.u16s_to_end()?; + } + b"brit" => self.u16s_upto(3)?, + b"thrs" | b"post" => { + self.u16()?; + } + b"nvrt" => {} + b"expA" => { + self.u16()?; + for _ in 0..3 { + self.f32()?; + } + } + b"blnc" => self.u16s_upto(9)?, + b"mixr" | b"selc" => self.u16s_to_end()?, + b"phfl" => match self.u16()? { + 2 => { + self.u16s(5)?; + self.u32()?; + self.u8()?; + } + 3 => { + for _ in 0..4 { + self.u32()?; + } + self.u8()?; + } + v => return Err(PsdError::Unsupported(format!("photo filter version {v}"))), + }, + b"grdm" => self.gradient_map()?, + _ if !self.same_order() => return Ok(self.descriptor_shaped()), + _ => return Ok(false), + } + Ok(true) + } + + /// `lnk2` / `lnk3` / `lnkD` / `lnkE` (linked and embedded smart-object files): items of + /// u64 length + data, each padded to 4. Item: type (`liFD` embedded, `liFE` external, + /// `liFA` alias), version 1–7, Pascal uuid, Unicode name, file type and creator keys, u64 + /// data length, open-descriptor flag (+ descriptor), per-type fields, the file bytes for + /// `liFD`, then the fields later versions added. + fn linked_layers(&mut self) -> Result<()> { + while self.remaining() >= 8 { + let len = self.r.clone().u64()?; + self.sized_region(true, |t| { + let kind = t.key()?; + let version = t.u32()?; + t.pascal(1)?; + t.unicode()?; + t.key()?; + t.key()?; + let data_len = t.u64()?; + if t.u8()? != 0 { + t.versioned_descriptor()?; + } + if &kind == b"liFE" && version > 3 { + t.i32()?; + for _ in 0..4 { + t.u8()?; + } + t.f64()?; + } + if &kind == b"liFE" { + t.u64()?; + } + if &kind == b"liFA" { + t.raw(8)?; + } + let data_len = usize::try_from(data_len).map_err(|_| PsdError::LimitExceeded("linked file length"))?; + if &kind == b"liFD" { + t.raw(data_len)?; + } + if version >= 5 { + t.unicode()?; + } + if version >= 6 { + t.f64()?; + } + if version >= 7 { + t.u8()?; + } + if &kind == b"liFE" && version == 2 { + t.raw(data_len)?; + } + Ok(()) + })?; + let pad = ((4 - len % 4) % 4) as usize; + self.raw(pad.min(self.remaining()))?; + } + Ok(()) + } + + /// `Anno`: u16 major, u16 minor, u32 count, then per annotation a self-counting u32 + /// length, type key, open and flags bytes, u16 optional blocks, icon and popup rects, a + /// colour, three even-padded Pascal strings, and a self-counting data block (key, u32 + /// size, text with its own byte-order mark). + fn annotations(&mut self) -> Result<()> { + self.u16()?; + self.u16()?; + let n = self.u32()?; + for _ in 0..n { + if self.remaining() < 4 { + break; + } + self.sized_region_inclusive(|t| { + t.key()?; + t.u8()?; + t.u8()?; + t.u16()?; + t.i32s(8)?; + t.u16s(5)?; + t.pascal(2)?; + t.pascal(2)?; + t.pascal(2)?; + t.sized_region_inclusive(|d| { + d.key()?; + d.u32()?; + Ok(()) + }) + })?; + } + Ok(()) + } + + // ---- layer info ---- + + fn layer_info(&mut self) -> Result<()> { + let count = self.i16()?; + let n = usize::from(count.unsigned_abs()); + self.r.check_count(n as u64, 34)?; + // Per layer: the channel ids and lengths, and the heights of the layer, mask and + // real-mask rects (what each channel's RLE count table spans). + let mut records: Vec = Vec::with_capacity(n); + for _ in 0..n { + let top = self.i32()?; + self.i32()?; + let bottom = self.i32()?; + self.i32()?; + let nch = self.u16()?; + if nch > crate::layer::MAX_LAYER_CHANNELS { + return Err(PsdError::LimitExceeded("too many channels in layer")); + } + let mut chans = Vec::with_capacity(usize::from(nch)); + let psb = self.version.is_psb(); + for _ in 0..nch { + let id = self.i16()?; + let len = self.len(psb)?; + chans.push((id, len)); + } + let sig = self.key()?; + if &sig != b"8BIM" { + return Err(PsdError::InvalidSignature { expected: "8BIM (layer blend mode)", found: sig }); + } + self.key()?; + for _ in 0..4 { + self.u8()?; + } + let mut heights = [height(top, bottom), 0, 0]; + let mut mask_heights = (0usize, 0usize); + self.sized_region(false, |t| { + let mut mh = (0, 0); + t.sized_region(false, |m| { + mh = m.mask()?; + Ok(()) + })?; + mask_heights = mh; + // Blending ranges are bytes (black low/high, white low/high per channel), so + // Photoshop stores them in the same order in either byte order: an Intel-order + // layered TIFF holds the default ranges as `00 00 ff ff`. Swapping them as u32s + // turned every range into `ff ff 00 00`, which hides every pixel of the layer. + t.sized_region(false, |x| x.rest())?; + t.pascal(4)?; + t.blocks() + })?; + heights[1] = mask_heights.0; + heights[2] = mask_heights.1; + records.push((chans, heights)); + } + for (chans, heights) in &records { + for &(id, len) in chans { + if len == 0 { + continue; + } + if len == 1 { + return Err(PsdError::invalid("channel data length 1")); + } + let rows = match id { + -2 => heights[1], + -3 => heights[2], + _ => heights[0], + }; + self.region(len, |t| t.channel_data(rows, false))?; + } + } + self.rest() + } + + /// A layer mask record. Returns the heights of the mask and real-mask rects. + fn mask(&mut self) -> Result<(usize, usize)> { + let whole = self.r.peek_rest(); + if whole.is_empty() { + return Ok((0, 0)); + } + let top = self.i32()?; + self.i32()?; + let bottom = self.i32()?; + self.i32()?; + self.u8()?; + let flags = self.u8()?; + let mut real_h = 0; + if self.remaining() <= 2 { + return Ok((height(top, bottom), 0)); + } + let has_parameters = flags & LayerMask::FLAG_PARAMETERS != 0; + // The helper only looks at lengths and the parameter-flags byte, so it reads the + // same in either order. + let real_first = has_parameters && LayerMask::real_before_parameters(whole); + let mut read_real = |t: &mut Tx<'_>| -> Result<()> { + if t.remaining() >= 18 { + t.u8()?; + t.u8()?; + let rt = t.i32()?; + t.i32()?; + let rb = t.i32()?; + t.i32()?; + real_h = height(rt, rb); + } + Ok(()) + }; + if real_first { + read_real(self)?; + } + if has_parameters { + let pf = self.u8()?; + let need = mask_parameter_bytes(pf); + if need > self.remaining() { + return Err(PsdError::UnexpectedEof { offset: self.r.pos(), needed: need - self.remaining() }); + } + if pf & 1 != 0 { + self.u8()?; + } + if pf & 2 != 0 { + self.f64()?; + } + if pf & 4 != 0 { + self.u8()?; + } + if pf & 8 != 0 { + self.f64()?; + } + } + if !real_first { + read_real(self)?; + } + Ok((height(top, bottom), real_h)) + } + + // ---- descriptors ---- + + /// Photoshop's Intel-order TIFF type blocks can use PSD byte order for the + /// text descriptor, then container order again for warp and bounds (#4758). + fn type_layer(&mut self) -> Result<()> { + self.u16()?; + self.f64s(6)?; + self.type_descriptor(50, ByteOrder::Big)?; + self.type_descriptor(1, self.to)?; + self.i32s(4) + } + + fn type_descriptor(&mut self, version: u16, to: ByteOrder) -> Result<()> { + let [hi, lo] = version.to_be_bytes(); + let from = if self.from.is_little() && self.r.peek_rest().starts_with(&[hi, lo, 0, 0, 0, 16]) { ByteOrder::Big } else { self.from }; + let data = self.r.peek_rest(); + let mut descriptor = Tx::new(data, self.version, from, to); + descriptor.depth = self.depth; + descriptor.u16()?; + descriptor.versioned_descriptor()?; + let used = data.len() - descriptor.remaining(); + self.r.bytes(used)?; + self.warnings.append(&mut descriptor.warnings); + self.out.extend_from_slice(&descriptor.out); + Ok(()) + } + + fn versioned_descriptor(&mut self) -> Result<()> { + self.u32()?; + self.descriptor() + } + + fn descriptor(&mut self) -> Result<()> { + if self.depth > MAX_DEPTH { + return Err(PsdError::LimitExceeded("descriptor nesting too deep")); + } + self.depth += 1; + self.unicode()?; + self.id()?; + let n = self.u32()?; + self.r.check_count(u64::from(n), 10)?; + for _ in 0..n { + self.id()?; + self.value()?; + } + self.depth -= 1; + Ok(()) + } + + fn id(&mut self) -> Result<()> { + let n = self.u32()?; + if n == 0 { + self.key()?; + } else { + self.raw(usize::try_from(n).map_err(|_| PsdError::LimitExceeded("id length"))?)?; + } + Ok(()) + } + + fn class(&mut self) -> Result<()> { + self.unicode()?; + self.id() + } + + fn value(&mut self) -> Result<()> { + if self.depth > MAX_DEPTH { + return Err(PsdError::LimitExceeded("descriptor nesting too deep")); + } + let ty = self.key()?; + match &ty { + b"obj " => { + let n = self.u32()?; + self.r.check_count(u64::from(n), 8)?; + for _ in 0..n { + self.reference_item()?; + } + } + b"Objc" | b"GlbO" => self.descriptor()?, + b"VlLs" => { + let n = self.u32()?; + self.r.check_count(u64::from(n), 4)?; + self.depth += 1; + for _ in 0..n { + self.value()?; + } + self.depth -= 1; + } + b"doub" => { + self.f64()?; + } + b"UntF" => { + self.key()?; + self.f64()?; + } + b"UnFl" => { + self.key()?; + let n = self.u32()?; + self.r.check_count(u64::from(n), 8)?; + self.f64s(n as usize)?; + } + b"TEXT" => self.unicode()?, + b"enum" => { + self.id()?; + self.id()?; + } + b"long" => { + self.i32()?; + } + b"comp" => { + self.i64()?; + } + b"bool" => { + self.u8()?; + } + b"type" | b"GlbC" => self.class()?, + b"alis" | b"Pth " | b"tdta" => { + let n = self.u32()?; + self.raw(usize::try_from(n).map_err(|_| PsdError::LimitExceeded("descriptor data length"))?)?; + } + b"ObAr" => { + self.u32()?; + self.descriptor()?; + } + other => return Err(PsdError::Unsupported(format!("descriptor OSType {:?}", String::from_utf8_lossy(other)))), + } + Ok(()) + } + + fn reference_item(&mut self) -> Result<()> { + let ty = self.key()?; + match &ty { + b"prop" => { + self.class()?; + self.id()?; + } + b"Clss" => self.class()?, + b"Enmr" => { + self.class()?; + self.id()?; + self.id()?; + } + b"rele" => { + self.class()?; + self.i32()?; + } + b"Idnt" | b"indx" => { + self.class()?; + self.u32()?; + } + b"name" => { + self.class()?; + self.unicode()?; + } + other => return Err(PsdError::Unsupported(format!("reference item type {:?}", String::from_utf8_lossy(other)))), + } + Ok(()) + } + + // ---- other block layouts ---- + + /// `shmd`: u32 count, then per item signature, key, copy flag, 3 bytes, u32 length, data. + /// An item whose layout is unknown is dropped on its own (and the count patched) rather + /// than taking the whole block with it. + fn metadata_setting(&mut self) -> Result<()> { + let n = self.r.u32()?; + self.r.check_count(u64::from(n), 16)?; + let count_at = self.out.len(); + self.out.extend_from_slice(&[0; 4]); + let mut kept = 0u32; + for _ in 0..n { + let before = self.out.len(); + self.key()?; + let key = self.key()?; + self.u8()?; + self.raw(3)?; + let same = self.same_order(); + let res = self.sized_region(false, |t| match &key { + b"cmls" | b"mlst" | b"cust" | b"tmln" | b"sgrp" | b"cinf" => t.versioned_descriptor(), + // mdyn (dynamic metadata) is one u32. + b"mdyn" => t.u32s_to_end(), + _ if same => Ok(()), + _ if t.descriptor_shaped() => Ok(()), + _ => Err(PsdError::Unsupported(format!("metadata item {:?}", String::from_utf8_lossy(&key)))), + }); + match res { + Ok(()) => kept += 1, + Err(e) if same => return Err(e), + Err(e) => { + self.out.truncate(before); + self.warnings.push(format!("shmd item {} dropped: {e}", String::from_utf8_lossy(&key))); + } + } + } + self.patch_len(count_at, false, u64::from(kept)) + } + + /// 26-byte path records: a u16 selector then, for knots, six fixed-point coordinates. + fn path_records(&mut self) -> Result<()> { + while self.remaining() >= 26 { + let selector = self.u16()?; + match selector { + 1 | 2 | 4 | 5 => self.i32s(6)?, + // Length records: knot count, path operation, then fields Photoshop writes as + // 16-bit values (zero in practice). + 0 | 3 => self.u16s(12)?, + // Clipboard: four fixed-point coordinates and a resolution. + 7 => { + self.i32s(5)?; + self.raw(4)?; + } + 8 => { + self.u16()?; + self.raw(22)?; + } + _ => self.raw(24)?, + } + } + Ok(()) + } + + /// One pattern of a `Patt` block (the data after its u32 length). + fn pattern(t: &mut Tx<'_>) -> Result<()> { + t.u32()?; + let mode = t.u32()?; + t.u16()?; + t.u16()?; + t.unicode()?; + t.pascal(1)?; + if mode == 2 { + t.raw(768)?; + // Some writers follow the palette with 4 extra bytes before the array list version. + let next_is_version = t.r.clone().u32().is_ok_and(|v| v == 3); + if !next_is_version && t.remaining() >= 4 { + t.raw(4)?; + } + } + t.u32()?; + t.sized_region(false, |v| { + v.i32s(4)?; + let count = v.u32()?; + for _ in 0..count.saturating_add(2) { + if v.remaining() < 4 { + break; + } + if v.u32()? == 0 { + continue; + } + if v.r.clone().u32()? == 0 { + v.u32()?; + continue; + } + v.sized_region(false, |c| { + c.u32()?; + let ct = c.i32()?; + c.i32()?; + let cb = c.i32()?; + c.i32()?; + c.u16()?; + let comp = c.u8()?; + if comp == 1 { + let saved = c.version; + c.version = Version::Psd; + let res = c.rle_counts(height(ct, cb)); + c.version = saved; + res?; + } + Ok(()) + })?; + } + Ok(()) + }) + } + + /// `FEid` / `FXid`: version, then one section per smart object (u64 length, items with + /// per-channel planes and 4-byte RLE counts), each padded to 4 bytes. + fn filter_effects(&mut self) -> Result<()> { + self.u32()?; + loop { + let len = self.r.clone().len_field(true)?; + self.filter_effects_section()?; + // Mirrors `FilterEffects::parse`: the last section's padding may be cut short. + let pad = usize::try_from((4 - len % 4) % 4).unwrap_or(0).min(self.remaining()); + self.raw(pad)?; + let rest = self.r.peek_rest(); + if rest.len() <= 3 && rest.iter().all(|&b| b == 0) { + return Ok(()); + } + if rest.len() < 8 { + return Err(PsdError::invalid(format!("filter effects: {} unexpected bytes after the data", rest.len()))); + } + } + } + + fn filter_effects_section(&mut self) -> Result<()> { + self.sized_region(true, |t| { + while !t.r.is_empty() { + t.pascal(1)?; + t.u32()?; + t.sized_region(true, |it| { + let top = it.i32()?; + it.i32()?; + let bottom = it.i32()?; + it.i32()?; + let rect_h = height(top, bottom); + it.u32()?; + let max = it.u32()?; + if max > crate::filter_effects::MAX_SLOTS { + return Err(PsdError::LimitExceeded("filter effects: too many channels")); + } + for _ in 0..max + 2 { + if it.u32()? != 0 { + it.effects_plane(rect_h)?; + } + } + Ok(()) + })?; + if !t.r.is_empty() && t.u8()? != 0 { + let top = t.i32()?; + t.i32()?; + let bottom = t.i32()?; + t.i32()?; + t.effects_plane(height(top, bottom))?; + } + } + Ok(()) + }) + } + + fn effects_plane(&mut self, rows: usize) -> Result<()> { + self.sized_region(true, |p| p.channel_data(rows, true)) + } + + /// `lrFX`: version, count, then effects (`cmnS`, `dsdw`, `isdw`, `oglw`, `iglw`, `bevl`, + /// `sofi`), each a signature, key, u32 size and fixed fields. + fn legacy_effects(&mut self) -> Result<()> { + self.u16()?; + let n = self.u16()?; + for _ in 0..n { + if self.remaining() < 12 { + break; + } + self.key()?; + let key = self.key()?; + self.sized_region(false, |t| { + // A colour: u16 space + 4 × u16 components. + let colour = |t: &mut Tx<'_>| t.u16s(5); + let blend = |t: &mut Tx<'_>| -> Result<()> { + t.key()?; + t.key()?; + Ok(()) + }; + match &key { + b"cmnS" => { + t.u32()?; + t.u8()?; + t.u16()?; + } + b"dsdw" | b"isdw" => { + t.u32()?; + t.i32s(4)?; + colour(t)?; + blend(t)?; + t.u8()?; + t.u8()?; + t.u8()?; + if t.remaining() >= 10 { + colour(t)?; + } + } + b"oglw" => { + t.u32()?; + t.i32s(2)?; + colour(t)?; + blend(t)?; + t.u8()?; + t.u8()?; + if t.remaining() >= 10 { + colour(t)?; + } + } + b"iglw" => { + t.u32()?; + t.i32s(2)?; + colour(t)?; + blend(t)?; + t.u8()?; + t.u8()?; + if t.remaining() >= 11 { + t.u8()?; + colour(t)?; + } + } + b"bevl" => { + t.u32()?; + t.i32s(3)?; + blend(t)?; + blend(t)?; + colour(t)?; + colour(t)?; + for _ in 0..6 { + t.u8()?; + } + if t.remaining() >= 20 { + colour(t)?; + colour(t)?; + } + } + b"sofi" => { + t.u32()?; + blend(t)?; + colour(t)?; + t.u8()?; + t.u8()?; + if t.remaining() >= 10 { + colour(t)?; + } + } + _ => {} + } + Ok(()) + })?; + } + Ok(()) + } + + /// `curv`: pad byte, version, channel bitmap, per set bit a point list; then an optional + /// `Crv ` extension with per-channel point lists. + fn curves(&mut self) -> Result<()> { + self.u8()?; + self.u16()?; + let bits = self.u32()?; + for bit in 0..32 { + if bits & (1 << bit) == 0 { + continue; + } + if self.remaining() < 2 { + break; + } + let n = self.u16()?; + self.u16s(usize::from(n) * 2)?; + } + if self.remaining() >= 10 { + self.key()?; + self.u16()?; + let n = self.u32()?; + for _ in 0..n { + if self.remaining() < 4 { + break; + } + self.u16()?; + let pts = self.u16()?; + self.u16s(usize::from(pts) * 2)?; + } + } + Ok(()) + } + + /// `grdm`: version, reverse, dither, [method key], name, colour stops, transparency + /// stops, then the noise-gradient fields (a u32 seed among u16s). + fn gradient_map(&mut self) -> Result<()> { + let version = self.u16()?; + self.u8()?; + self.u8()?; + if version == 3 { + self.key()?; + } + self.unicode()?; + let n = self.u16()?; + for _ in 0..n { + if self.remaining() < 20 { + break; + } + self.u32()?; + self.u32()?; + self.u16s(6)?; + } + let nt = self.u16()?; + for _ in 0..nt { + if self.remaining() < 10 { + break; + } + self.u32()?; + self.u32()?; + self.u16()?; + } + // expansion, interpolation, length, mode, u32 seed, then u16 fields. + for _ in 0..4 { + if self.remaining() < 2 { + return Ok(()); + } + self.u16()?; + } + if self.remaining() >= 4 { + self.u32()?; + } + self.u16s_to_end() + } +} diff --git a/crates/raster/src/lib.rs b/crates/raster/src/lib.rs index ce70830f37..4aa50c5a60 100644 --- a/crates/raster/src/lib.rs +++ b/crates/raster/src/lib.rs @@ -1237,790 +1237,7 @@ pub fn is_hdr(sample: SampleType) -> bool { } #[cfg(test)] -mod tests { - - /// Manually compare allocating reads with the previous implementation. - #[test] - #[ignore = "manual 24 MP release benchmark"] - fn benchmark_sparse_reads() { - use std::{hint::black_box, time::Instant}; - let rect = Rect::new(0, 0, 6000, 4000); - for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { - for default in [0.0, 0.25] { - let mut s = Surface::with_default(PixelFormat::GRAY8.with_sample(depth), &[default]); - s.fill_rect(Rect::new(257, 257, 266, 266), &[0.75]); - assert_eq!(s.read_region(rect), previous_read_region(&s, rect)); - for trial in 0..6 { - let mut paths = [("main", previous_read_region as fn(&Surface, Rect) -> Vec), ("split", Surface::read_region)]; - if trial % 2 == 1 { - paths.reverse(); - } - for (name, path) in paths { - let t = Instant::now(); - let out = black_box(path)(&s, rect); - let elapsed = t.elapsed().as_secs_f64() * 1000.0; - black_box(&out); - println!("sparse,{depth:?}-{default},{trial},{name},{elapsed:.6}"); - } - } - } - } - } - /// Previous allocating read path, retained as the bitwise-equivalence oracle. - fn previous_read_region(surface: &Surface, r: Rect) -> Vec { - let n = surface.channels(); - let w = r.width() as usize; - let mut out = vec![0.0f32; w * r.height() as usize * n]; - let dp = surface.default_pixel(); - for tc in r.tiles() { - let tr = tc.rect().intersect(&r); - let tile = surface.tiles.get(&tc); - for y in tr.y0..tr.y1 { - for x in tr.x0..tr.x1 { - let o = (((y - r.y0) as usize) * w + (x - r.x0) as usize) * n; - match tile { - Some(t) => { - let base = (((y - tc.ty * TILE_SIZE) as usize) * TILE_SIZE as usize + (x - tc.tx * TILE_SIZE) as usize) * n; - for i in 0..n { - out[o + i] = read_sample(&t.data, surface.format.sample, base + i); - } - } - None => out[o..o + n].copy_from_slice(&dp), - } - } - } - } - out - } - /// Distinct tile allocations in `s`. - fn distinct_tiles(s: &Surface) -> usize { - let mut seen: Vec<*const Tile> = s.tiles().map(|(_, t)| Arc::as_ptr(t)).collect(); - seen.sort(); - seen.dedup(); - seen.len() - } - - /// Converting or tone-mapping a surface keeps a shared tile shared (#4531) and gives the - /// same pixels as converting each pixel: a filled background is one tile across the grid, - /// plus some distinct tiles. - #[test] - fn conversion_keeps_shared_tiles_shared() { - let mut s = Surface::new(PixelFormat::RGBA8); - s.fill_rect(Rect::new(0, 0, 2048, 1024), &[0.9, 0.5, 0.2, 1.0]); - s.fill_rect(Rect::new(10, 10, 20, 20), &[0.1, 0.2, 0.3, 0.5]); - let shared_before = distinct_tiles(&s); - assert!(shared_before <= 2 && s.tile_count() == 32, "{shared_before} distinct of {}", s.tile_count()); - let r = Rect::new(0, 0, 2048, 1024); - for to in [PixelFormat::RGBA16, PixelFormat::RGBA32F] { - for out in [s.convert(to), s.try_convert(to).expect("memory")] { - assert_eq!(distinct_tiles(&out), shared_before, "{to:?}: still shared"); - assert_eq!(out.tile_count(), 32); - let (a, b) = (out.read_region(r), s.read_region(r)); - for (pa, pb) in a.as_chunks::<4>().0.iter().zip(b.as_chunks::<4>().0) { - let want = convert_pixel(&s.format(), &to, pb); - assert!(pa.iter().zip(&want).all(|(x, y)| (x - y).abs() < 1e-6), "{to:?}: {pa:?} vs {want:?}"); - } - } - } - let mut m = s.clone(); - m.map_color(|v| v * 0.5); - assert_eq!(distinct_tiles(&m), shared_before, "map_color keeps it shared"); - assert!((m.pixel(1000, 500)[0] - s.pixel(1000, 500)[0] * 0.5).abs() < 1.0 / 255.0); - assert_eq!(s.pixel(1000, 500), vec![s.pixel(1000, 500)[0], s.pixel(1000, 500)[1], s.pixel(1000, 500)[2], 1.0], "the source is untouched"); - } - - use super::*; - use photocraft_color::PixelFormat; - use proptest::prelude::*; - - fn write_region_reference(surface: &mut Surface, r: Rect, data: &[f32]) { - let n = surface.channels(); - let w = r.width() as usize; - assert_eq!(data.len(), w * r.height() as usize * n, "region data length mismatch"); - let sample = surface.format.sample; - for tc in r.tiles() { - let tr = tc.rect().intersect(&r); - let t = surface.tile_mut(tc); - for y in tr.y0..tr.y1 { - for x in tr.x0..tr.x1 { - let o = (((y - r.y0) as usize) * w + (x - r.x0) as usize) * n; - let base = (((y - tc.ty * TILE_SIZE) as usize) * TILE_SIZE as usize + (x - tc.tx * TILE_SIZE) as usize) * n; - for i in 0..n { - write_sample(&mut t.data, sample, base + i, data[o + i]); - } - } - } - } - } - - #[test] - fn region_writes_match_scalar_bytes_for_every_format() { - let special = [ - 0.0, - -0.0, - 1.0, - -1.0, - 2.0, - f32::INFINITY, - f32::NEG_INFINITY, - f32::NAN, - f32::from_bits(0x7fc12345), - f32::from_bits(0xffc12345), - f32::MIN_POSITIVE, - f32::from_bits(1), - 0.5 / 255.0, - 0.5 / 65535.0, - ]; - for mode in [ - ColorMode::Bitmap, - ColorMode::Grayscale, - ColorMode::Indexed, - ColorMode::Rgb, - ColorMode::Cmyk, - ColorMode::Lab, - ColorMode::Multichannel, - ColorMode::Duotone, - ] { - for sample in SampleType::ALL { - for alpha in [false, true] { - let fmt = PixelFormat::new(mode, sample, alpha); - let mut actual = Surface::with_default(fmt, &vec![0.25; fmt.channels()]); - actual.write_pixel(900, 900, &vec![0.75; fmt.channels()]); - let mut expected = actual.clone(); - for rect in - [Rect::EMPTY, Rect::new(-270, -2, 270, 3), Rect::new(256, 256, 512, 257), Rect::new(-64, -64, 0, 0), Rect::new(255, 250, 258, 270)] - { - let data: Vec<_> = (0..rect.width() as usize * rect.height() as usize * fmt.channels()) - .map(|i| { - if i % 3 == 0 { - special[i / 3 % special.len()] - } else { - // Integer rounding boundaries and deterministic arbitrary f32 bit patterns. - let bits = (i as u32).wrapping_mul(2654435761); - if i % 3 == 1 { ((bits % 65536) as f32 + 0.5) / 65535.0 } else { f32::from_bits(bits) } - } - }) - .collect(); - let snapshot = actual.clone(); - let snapshot_bytes = snapshot.to_interleaved(rect.inflate(1)); - let mut par = actual.clone(); - actual.write_region(rect, &data); - par.write_region_par(rect, &data); - write_region_reference(&mut expected, rect, &data); - assert_eq!(actual, expected, "{fmt:?}, {rect:?}"); - assert_eq!(par, expected, "parallel {fmt:?}, {rect:?}"); - assert_eq!(snapshot.to_interleaved(rect.inflate(1)), snapshot_bytes, "COW snapshot changed"); - // Repeat against already materialised, unshared tiles too. - actual.write_region(rect, &data); - par.write_region_par(rect, &data); - assert_eq!(actual, expected); - assert_eq!(par, expected); - } - } - } - } - } - - /// Mask builds call `write_region` inside a `OnceLock` initializer, where entering Rayon can - /// run another tile's job that waits on the same lock. With every global worker held, a write - /// that queued work on Rayon could not finish. - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn write_region_does_not_enter_rayon() { - use std::sync::{Barrier, mpsc}; - let workers = rayon::current_num_threads(); - let held = Arc::new(Barrier::new(workers + 1)); - let release = Arc::new(Barrier::new(workers + 1)); - let (h, rel) = (held.clone(), release.clone()); - rayon::spawn_broadcast(move |_| { - h.wait(); - rel.wait(); - }); - held.wait(); - let (tx, rx) = mpsc::channel(); - std::thread::spawn(move || { - let r = Rect::new(0, 0, 2 * TILE_SIZE, 2 * TILE_SIZE); - let mut s = Surface::new(PixelFormat::RGBA8); - s.write_region(r, &vec![0.5; (r.width() * r.height() * 4) as usize]); - tx.send(()).ok(); - }); - let done = rx.recv_timeout(std::time::Duration::from_secs(5)).is_ok(); - release.wait(); - assert!(done, "write_region waited on the Rayon pool"); - } - - #[test] - fn from_rgba_into_matches_from_rgba() { - for fmt in [PixelFormat::RGBA8, PixelFormat::GRAY8, PixelFormat::GRAYA8, PixelFormat::CMYKA8, PixelFormat::new(ColorMode::Lab, SampleType::F32, true)] { - let mut buf = [0.0f32; 8]; - let n = from_rgba_into(&fmt, [0.2, 0.5, 0.7, 0.4], &mut buf); - assert_eq!(&buf[..n], &from_rgba(&fmt, [0.2, 0.5, 0.7, 0.4])[..]); - } - } - - /// Sample counts above the stack capacity use writable storage without truncating channels. - #[test] - fn sample_buffer_keeps_stack_fast_path_and_supports_dynamic_channels() { - for channels in [1, 8, 9, 32] { - let mut stack = [0.0; 8]; - let mut heap = Vec::new(); - let samples = sample_buffer(channels, &mut stack, &mut heap); - assert_eq!(samples.len(), channels); - samples.fill(0.25); - if channels <= stack.len() { - assert!(heap.is_empty()); - assert_eq!(&stack[..channels], vec![0.25; channels]); - } else { - assert_eq!(heap, vec![0.25; channels]); - } - } - } - - /// Compare sparse reads and converted accessors with the previous allocating path. - #[test] - fn zero_alloc_accessors_match_read_region() { - for (fmt, default) in [ - PixelFormat::RGBA8, - PixelFormat::RGBA16, - PixelFormat::RGBA32F, - PixelFormat::GRAYA8, - PixelFormat::CMYKA8, - PixelFormat::GRAY8, - PixelFormat::GRAY8.with_sample(SampleType::F32), - PixelFormat::new(ColorMode::Lab, SampleType::U16, true), - ] - .into_iter() - .flat_map(|fmt| [0.0, 0.25, -0.0].map(|default| (fmt, default))) - { - let mut s = Surface::with_default(fmt, &vec![default; fmt.channels()]); - let mut stack = [0.0; 8]; - let mut heap = Vec::new(); - for capacity in [0, stack.len()] { - let decoded = s.default_samples(&mut stack[..capacity], &mut heap); - assert!(decoded.iter().map(|v| v.to_bits()).eq(s.default_pixel().into_iter().map(f32::to_bits))); - } - let r = Rect::new(-300, -20, 300, 40); - for (i, (x, y)) in [(-299, -19), (0, 0), (255, 39), (256, 10), (299, 0)].into_iter().enumerate() { - let px: Vec = (0..fmt.channels()).map(|c| ((i * 3 + c) % 5) as f32 / 4.0).collect(); - s.write_pixel(x, y, &px); - } - let region = s.read_region(r); - assert!(region.iter().map(|v| v.to_bits()).eq(previous_read_region(&s, r).into_iter().map(f32::to_bits))); - let mut into = vec![9.0; 3]; - s.read_region_into(r, &mut into); - assert_eq!(region, into); - let mut rgba = vec![[0.0; 4]; (r.width() * r.height()) as usize]; - s.read_rgba_into(r, &mut rgba); - let mut rgba8 = vec![[0; 4]; rgba.len()]; - s.read_rgba8_into(r, &mut rgba8); - let n = fmt.channels(); - for (i, p) in region.chunks_exact(n).enumerate() { - let want = to_rgba(&fmt, p); - assert_eq!(rgba8[i], want.map(|v| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8)); - for c in 0..4 { - assert!((rgba[i][c] - want[c]).abs() < 1e-6, "{fmt:?} px {i}"); - } - let (x, y) = (r.x0 + (i % r.width() as usize) as i32, r.y0 + (i / r.width() as usize) as i32); - for c in 0..n { - let bits = s.sample_channel(x, y, c).to_bits(); - assert_eq!(bits, p[c].to_bits()); - assert_eq!(bits, into[i * n + c].to_bits()); - } - } - assert!(s.has_tiles_in(Rect::new(0, 0, 1, 1))); - assert!(!s.has_tiles_in(Rect::new(1000, 1000, 1001, 1001))); - } - } - - #[test] - fn fallible_region_reads_report_size_overflow() { - let surface = Surface::new(PixelFormat::RGBA8); - let huge = Rect::new(i32::MIN, i32::MIN, i32::MAX, i32::MAX); - assert_eq!(surface.try_read_region(huge), Err(AllocationError::SizeOverflow)); - assert_eq!(surface.try_to_interleaved(huge), Err(AllocationError::SizeOverflow)); - } - - #[test] - fn fallible_region_write_rejects_bad_input_without_mutating_surface() { - let mut surface = Surface::new(PixelFormat::RGBA8); - let before = surface.clone(); - assert_eq!(surface.try_write_region(Rect::new(0, 0, 2, 2), &[1.0]), Err(AllocationError::SizeOverflow)); - assert_eq!(surface, before); - } - - #[test] - fn fallible_tile_edits_move_weakly_cached_pixels_and_copy_shared_pixels() { - for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA16, PixelFormat::RGBA32F] { - let mut surface = Surface::new(fmt); - let coord = TileCoord::new(0, 0); - let pixels = surface.try_tile_mut(coord).unwrap().bytes().as_ptr(); - let weak = Arc::downgrade(surface.tile(coord).unwrap()); - let tile = surface.try_tile_mut(coord).unwrap(); - assert_eq!(tile.bytes().as_ptr(), pixels); - assert!(weak.upgrade().is_none()); - let snapshot = surface.clone(); - surface.try_write_region(Rect::new(0, 0, 1, 1), &[1.0; 4]).unwrap(); - assert_eq!(snapshot.pixel(0, 0), vec![0.0; 4]); - assert_eq!(surface.pixel(0, 0), vec![1.0; 4]); - } - } - - #[test] - fn fill_rect_shares_covered_tiles_and_edits_stay_local() { - // A 300000² background used to materialize ~360 GB of tiles (#705). - let mut s = Surface::new(PixelFormat::RGBA8); - s.fill_rect(Rect::new(0, 0, 300_000, 300_000), &[1.0, 0.5, 0.0, 1.0]); - let t = |s: &Surface, x, y| s.tile(TileCoord::new(x, y)).unwrap().clone(); - assert!(Arc::ptr_eq(&t(&s, 0, 0), &t(&s, 1000, 900))); - // 300000 is not a multiple of 256: the edge tile is partial and stays its own. - let edge = 300_000 / TILE_SIZE; - assert!(!Arc::ptr_eq(&t(&s, 0, 0), &t(&s, edge, 0))); - assert_eq!(s.pixel(299_999, 299_999), vec![1.0, 128.0 / 255.0, 0.0, 1.0]); - assert_eq!(s.pixel(300_000, 0), vec![0.0; 4]); - s.write_pixel(5, 5, &[0.0, 0.0, 1.0, 1.0]); - assert_eq!(s.pixel(5, 5), vec![0.0, 0.0, 1.0, 1.0]); - assert_eq!(s.pixel(300, 5), vec![1.0, 128.0 / 255.0, 0.0, 1.0]); - assert!(!Arc::ptr_eq(&t(&s, 0, 0), &t(&s, 1, 0))); - } - - #[test] - fn empty_surface_reads_default() { - let s = Surface::new(PixelFormat::RGBA8); - assert_eq!(s.pixel(10, -500), vec![0.0; 4]); - let m = Surface::with_default(PixelFormat::GRAY8, &[1.0]); - assert_eq!(m.pixel(123_456, -9), vec![1.0]); - assert_eq!(m.tile_count(), 0); - } - - #[test] - fn write_read_pixel_every_depth() { - for sample in SampleType::ALL { - let f = PixelFormat::RGBA8.with_sample(sample); - let mut s = Surface::new(f); - s.write_pixel(-3, 700, &[0.2, 0.4, 0.6, 1.0]); - let p = s.pixel(-3, 700); - for (a, b) in p.iter().zip([0.2, 0.4, 0.6, 1.0]) { - assert!((a - b).abs() <= 1.0 / 255.0, "{sample:?}"); - } - assert_eq!(s.tile_count(), 1); - assert_eq!(s.tile_bounds(), TileCoord::containing(-3, 700).rect()); - } - } - - #[test] - fn copy_on_write_shares_untouched_tiles() { - let mut a = Surface::new(PixelFormat::RGBA8); - a.fill_rect(Rect::new(0, 0, 512, 512), &[1.0, 0.0, 0.0, 1.0]); - let mut b = a.clone(); - b.write_pixel(10, 10, &[0.0, 1.0, 0.0, 1.0]); - // a unchanged - assert_eq!(a.pixel(10, 10), vec![1.0, 0.0, 0.0, 1.0]); - assert_eq!(b.pixel(10, 10), vec![0.0, 1.0, 0.0, 1.0]); - // only tile (0,0) was copied - let shared = a.tiles().filter(|(c, t)| Arc::ptr_eq(t, b.tile(**c).unwrap())).count(); - assert_eq!(shared, 3); - } - - #[test] - fn content_bounds_and_prune() { - let mut s = Surface::new(PixelFormat::RGBA8); - s.fill_rect(Rect::new(300, 10, 310, 20), &[1.0, 1.0, 1.0, 1.0]); - s.write_pixel(-5, -5, &[0.0, 0.0, 0.0, 1.0]); - assert_eq!(s.content_bounds(), Rect::new(-5, -5, 310, 20)); - // erase the single pixel -> its tile becomes default and is pruned - s.write_pixel(-5, -5, &[0.0, 0.0, 0.0, 0.0]); - s.prune(); - assert_eq!(s.tile_count(), 1); - assert_eq!(s.content_bounds(), Rect::new(300, 10, 310, 20)); - } - - #[test] - fn interleaved_roundtrip_crossing_tiles() { - let r = Rect::new(-20, 250, 280, 262); - let bpp = PixelFormat::RGBA16.bytes_per_pixel(); - let bytes: Vec = (0..r.width() as usize * r.height() as usize * bpp).map(|i| (i * 31 % 251) as u8).collect(); - let s = Surface::from_interleaved(PixelFormat::RGBA16, r, &bytes); - assert_eq!(s.to_interleaved(r), bytes); - assert_eq!(s.tile_count(), 6); // x tiles -1..=1, y tiles 0..=1 - } - - #[test] - fn region_outside_reads_default() { - let s = Surface::with_default(PixelFormat::GRAY8, &[1.0]); - let v = s.read_region(Rect::new(0, 0, 3, 3)); - assert_eq!(v, vec![1.0; 9]); - } - - #[test] - fn convert_depths_and_models() { - let mut s = Surface::new(PixelFormat::RGBA8); - s.write_pixel(1, 1, &[1.0, 1.0, 1.0, 1.0]); - let g = s.convert(PixelFormat::GRAYA8); - assert!((g.pixel(1, 1)[0] - 1.0).abs() < 1e-2); - let f = s.convert(PixelFormat::RGBA32F); - assert_eq!(f.pixel(1, 1), vec![1.0, 1.0, 1.0, 1.0]); - let c = s.convert(PixelFormat::CMYKA8); - let p = c.pixel(1, 1); - assert!(p[3] < 0.01 && (p[4] - 1.0).abs() < 1e-6); - let back = c.convert(PixelFormat::RGBA8); - assert_eq!(back.pixel(1, 1), vec![1.0, 1.0, 1.0, 1.0]); - } - - #[test] - fn rgba_from_gray_and_cmyk() { - let mut g = Surface::new(PixelFormat::GRAYA8); - g.write_pixel(0, 0, &[0.5, 1.0]); - let v = g.rgba(0, 0); - assert!((v[0] - v[2]).abs() < 1e-6 && (v[3] - 1.0).abs() < 1e-6); - } - - #[test] - fn repeated_cmyk_reads_match_individual_pixels_bitwise() { - let rect = Rect::new(-2, -1, 515, 2); - for depth in SampleType::ALL { - for alpha in [false, true] { - let fmt = PixelFormat::new(ColorMode::Cmyk, depth, alpha); - let mut s = Surface::with_default(fmt, &[0.2, 0.4, 0.6, 0.3, 0.7]); - for (i, x) in (-1..514).enumerate() { - let c = if i / 2 % 256 == 0 { -0.0 } else { (i / 2 % 256) as f32 / 255.0 }; - s.write_pixel(x, 0, &[c, 0.4, 0.6, 0.3, (i % 9) as f32 / 8.0]); - } - let mut out = vec![[0.0; 4]; (rect.width() * rect.height()) as usize]; - s.read_rgba_into(rect, &mut out); - for (i, actual) in out.iter().enumerate() { - let expected = s.rgba(rect.x0 + (i % rect.width() as usize) as i32, rect.y0 + (i / rect.width() as usize) as i32); - assert_eq!(actual.map(f32::to_bits), expected.map(f32::to_bits), "{depth:?}, alpha={alpha}, pixel={i}"); - } - } - } - } - - #[test] - fn rgba_reads_match_individual_pixels_bitwise_in_every_model_and_depth() { - // Across tile edges and a missing tile; float samples include -0, out-of-range and NaN. - let rect = Rect::new(-3, -1, 300, 2); - for mode in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Lab, ColorMode::Cmyk] { - for depth in SampleType::ALL { - for alpha in [false, true] { - let fmt = PixelFormat::new(mode, depth, alpha); - let mut s = Surface::with_default(fmt, &vec![0.25; fmt.channels()]); - let values = [-0.0, 0.1, 0.5, 1.0, 1.5, -0.25, f32::NAN, 0.75]; - for (i, x) in (-2..260).enumerate() { - let px: Vec = (0..fmt.channels()).map(|c| values[(i + c * 3) % values.len()]).collect(); - s.write_pixel(x, 0, &px); - } - let mut out = vec![[0.0; 4]; (rect.width() * rect.height()) as usize]; - s.read_rgba_into(rect, &mut out); - for (i, actual) in out.iter().enumerate() { - let expected = s.rgba(rect.x0 + (i % rect.width() as usize) as i32, rect.y0 + (i / rect.width() as usize) as i32); - assert_eq!(actual.map(f32::to_bits), expected.map(f32::to_bits), "{fmt:?}, pixel={i}"); - } - } - } - } - } - - #[test] - fn tile_content_bounds_scans_against_the_given_pixel() { - let mut s = Surface::new(PixelFormat::GRAY8); - s.write_pixel(3, 4, &[1.0]); - s.write_pixel(200, 9, &[1.0]); - let t = s.tile(TileCoord::new(0, 0)).expect("written tile"); - assert_eq!(t.content_bounds(&[0]), Some((3, 4, 201, 10))); - assert_eq!(t.content_bounds(&[255]).map(|b| (b.0, b.1)), Some((0, 0))); - // A malformed pixel is no content, not a panic. - assert_eq!(t.content_bounds(&[]), None); - } - - #[test] - fn tile_content_bounds_match_a_per_pixel_scan() { - // One differing byte at each position of a pixel, at and around the compare-block - // boundaries, in every pixel size; and a pixel that differs from `dp` in every byte. - fn per_pixel(t: &Tile, dp: &[u8]) -> Option<(u16, u16, u16, u16)> { - let (bpp, ts) = (dp.len(), TILE_SIZE as usize); - let mut b: Option<(usize, usize, usize, usize)> = None; - for (i, px) in t.bytes().chunks_exact(bpp).enumerate() { - if px != dp { - let (x, y) = (i % ts, i / ts); - let (x0, y0, x1, y1) = b.unwrap_or((x, y, x, y)); - b = Some((x0.min(x), y0.min(y), x1.max(x), y1.max(y))); - } - } - b.map(|(x0, y0, x1, y1)| (x0 as u16, y0 as u16, x1 as u16 + 1, y1 as u16 + 1)) - } - for bpp in [1, 2, 3, 4, 6, 8, 16] { - let dp: Vec = (0..bpp).map(|i| (i * 37 + 5) as u8).collect(); - let row = TILE_SIZE as usize * bpp; - for spots in [vec![], vec![0], vec![row - 1], vec![63, 64], vec![row * 7 + 127, row * 7 + 128, row * 200 + 5], vec![row * 255 + row / 2]] { - for byte in 0..bpp { - let mut data = dp.repeat(TILE_SIZE as usize * TILE_SIZE as usize); - for &s in &spots { - data[s - s % bpp + byte] ^= 0x5a; - } - let t = Tile { data: data.into_boxed_slice() }; - assert_eq!(t.content_bounds(&dp), per_pixel(&t, &dp), "bpp {bpp}, spots {spots:?}, byte {byte}"); - } - } - let mut data = dp.repeat(TILE_SIZE as usize * TILE_SIZE as usize); - data[row * 3 + 9 * bpp..row * 3 + 10 * bpp].iter_mut().for_each(|b| *b = !*b); - let t = Tile { data: data.into_boxed_slice() }; - assert_eq!(t.content_bounds(&dp), Some((9, 3, 10, 4)), "bpp {bpp}"); - } - } - - #[test] - fn translated_matches_reading_the_moved_pixels() { - // Any offset (whole tiles, negative, across tile edges), every depth, a non-zero default. - for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA16, PixelFormat::RGBA32F, PixelFormat::GRAY8] { - let mut s = Surface::with_default(fmt, &vec![0.25; fmt.channels()]); - let r = Rect::new(-37, 200, 530, 300); - let v: Vec = (0..r.width() * r.height() * fmt.channels() as u32).map(|i| (i % 251) as f32 / 250.0).collect(); - s.write_region(r, &v); - for (dx, dy) in [(0, 0), (256, -512), (1, 0), (-3, 7), (300, -257), (-1000, 999)] { - let t = s.translated(dx, dy, s.content_bounds()); - let moved = r.translate(dx, dy).inflate(3); - assert_eq!(t.read_region(moved), s.read_region(moved.translate(-dx, -dy)), "{fmt:?} by ({dx}, {dy})"); - assert_eq!(t.default_pixel(), s.default_pixel()); - assert_eq!(t.to_interleaved(r.translate(dx, dy)), s.to_interleaved(r), "{fmt:?} by ({dx}, {dy}): not an exact copy"); - } - // Whole tiles: the tiles are shared, not copied. - let t = s.translated(512, -256, s.content_bounds()); - assert!(s.tiles().zip(t.tiles()).all(|((_, a), (_, b))| Arc::ptr_eq(a, b))); - // Tiles without content (allocated, default pixels) are left behind. - let mut padded = s.clone(); - padded.fill_rect(Rect::new(2000, 2000, 2100, 2100), &s.default_pixel()); - assert_eq!(padded.translated(5, 5, s.content_bounds()).tile_count(), s.translated(5, 5, s.content_bounds()).tile_count()); - } - // A solid fill moved off the tile grid keeps sharing its one tile inside, at every depth - // and over a non-zero default pixel, and reads exactly like the copied pixels. - for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA16, PixelFormat::RGBA32F, PixelFormat::GRAY8] { - let mut s = Surface::with_default(fmt, &vec![0.25; fmt.channels()]); - let r = Rect::new(-300, -10, 1300, 1030); - s.fill_rect(r, &vec![0.75; fmt.channels()]); - let fill = s.tile(TileCoord::new(1, 1)).cloned().expect("an inner fill tile"); - for (dx, dy) in [(10, 7), (-1, 0), (0, 300), (-257, 513)] { - let t = s.translated(dx, dy, s.content_bounds()); - let moved = r.translate(dx, dy); - assert_eq!(t.read_region(moved.inflate(3)), s.read_region(moved.inflate(3).translate(-dx, -dy)), "{fmt:?} by ({dx}, {dy})"); - // Targets read only from the fill's whole tiles (x -256..1280, y 0..1024). - let whole = Rect::new(-256, 0, 1280, 1024).translate(dx, dy); - let inner: Vec<_> = t.tiles().filter(|(c, _)| whole.contains_rect(&c.rect())).collect(); - assert!(!inner.is_empty() && inner.iter().all(|(_, a)| Arc::ptr_eq(a, &fill)), "{fmt:?} by ({dx}, {dy}): inner tiles copied"); - } - // Nudged back and forth, the inside keeps sharing one tile (copies of uniform edge - // tiles count as that value too) and the pixels stay exact. - let mut t = s.clone(); - for k in 0..8 { - let d = if k % 2 == 0 { 10 } else { -10 }; - t = t.translated(d, d / 2, t.content_bounds()); - } - // (Targets whose last window read uniform tiles only: one tile in from the fill's whole - // tiles on the sides the last move came from.) - let inner: Vec<_> = t.tiles().filter(|(c, _)| Rect::new(-256, 0, 1024, 768).contains_rect(&c.rect())).map(|(_, a)| a).collect(); - assert!(inner.len() >= 4 && inner.iter().all(|a| Arc::ptr_eq(a, inner[0])), "{fmt:?}: repeated moves copied the inside"); - assert_eq!(t.read_region(r.inflate(3)), s.read_region(r.inflate(3)), "{fmt:?}: back where it started"); - } - // Two solid fills of different values side by side: windows across the seam are - // copied (each tile is uniform, but not with the same value), the rest shared. - for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA32F] { - let mut s = Surface::new(fmt); - s.fill_rect(Rect::new(0, 0, 1024, 768), &vec![0.2; fmt.channels()]); - s.fill_rect(Rect::new(1024, 0, 2048, 768), &vec![0.9; fmt.channels()]); - let t = s.translated(10, 7, s.content_bounds()); - let all = Rect::new(-20, -20, 2100, 800); - assert_eq!(t.read_region(all), s.read_region(all.translate(-10, -7)), "{fmt:?}: two fills"); - let seam = t.tile(TileCoord::new(4, 1)).expect("seam tile"); - let (left, right) = (t.tile(TileCoord::new(2, 1)).expect("left"), t.tile(TileCoord::new(6, 1)).expect("right")); - assert!(!Arc::ptr_eq(seam, left) && !Arc::ptr_eq(seam, right) && !Arc::ptr_eq(left, right), "{fmt:?}: seam aliased"); - } - // An offset of i32::MIN saturates its negation, so the source window isn't the exact - // preimage: no shortcut may apply (a zero pre-fill would leak into the output). - let mut s = Surface::with_default(PixelFormat::GRAY8, &[0.5]); - s.fill_rect(Rect::new(i32::MAX - 1024, 0, i32::MAX - 512, 512), &[0.25]); - let (fill, default) = (s.sample_channel(i32::MAX - 600, 10, 0), s.default_pixel()[0]); - for (dx, dy) in [(i32::MIN, 1), (1, i32::MIN), (i32::MIN, 0)] { - let t = s.translated(dx, dy, s.content_bounds()); - for (c, _) in t.tiles() { - assert!(t.read_region(c.rect()).iter().all(|v| *v == fill || *v == default), "({dx}, {dy}): tile {c:?} holds a pre-fill"); - } - } - // One tile shared but not uniform: each target is copied, not aliased. - let mut s = Surface::new(PixelFormat::GRAY8); - s.write_pixel(3, 4, &[1.0]); - let odd = s.tile(TileCoord::new(0, 0)).cloned().expect("written tile"); - let grid: Vec<_> = (0..9).map(|i| (TileCoord::new(i % 3, i / 3), odd.clone())).collect(); - s.put_tiles(grid); - let t = s.translated(10, 7, s.content_bounds()); - let all = Rect::new(-20, -20, 800, 800); - assert_eq!(t.read_region(all), s.read_region(all.translate(-10, -7))); - assert!(t.tiles().all(|(_, a)| !Arc::ptr_eq(a, &odd))); - // Offsets at the limits don't panic. - let mut s = Surface::new(PixelFormat::GRAY8); - s.write_pixel(5, 5, &[1.0]); - let all = Rect::new(i32::MIN, i32::MIN, i32::MAX, i32::MAX); - let _ = s.translated(i32::MAX, i32::MIN, all); - let _ = s.translated(i32::MIN + 1, 3, all); - } - - /// Many references to one payload, moved off the tile grid: the rebuilt tiles that read the - /// same source tiles at the same offset are one tile, not a copy each. - #[test] - fn translated_shares_tiles_rebuilt_from_shared_sources() { - let fmt = PixelFormat::RGBA8; - let mut one = Surface::new(fmt); - let r = Rect::new(0, 0, TILE_SIZE, TILE_SIZE); - let px: Vec = (0..r.width() * r.height()).flat_map(|i| [(i % 251) as f32 / 255.0, (i % 7) as f32 / 7.0, 0.5, 1.0]).collect(); - one.write_region(r, &px); - let payload = Arc::clone(one.tile(TileCoord::new(0, 0)).unwrap()); - let mut s = Surface::new(fmt); - s.put_tiles((0..16).flat_map(|ty| (0..16).map(move |tx| TileCoord::new(tx, ty))).map(|c| (c, Arc::clone(&payload)))); - let moved = s.translated(7, 5, s.content_bounds()); - let distinct: std::collections::HashSet<_> = moved.tiles().map(|(_, t)| Arc::as_ptr(t)).collect(); - // The 15 × 15 interior tiles read the same four source tiles at the same offset, so they are - // one tile, however many threads build them; only the 64 border tiles (cut by the - // content's edge) are built one by one. - assert!(moved.tile_count() == 289 && distinct.len() == 64 + 1, "{} tiles, {} distinct", moved.tile_count(), distinct.len()); - let all = Rect::new(-50, -50, 16 * TILE_SIZE + 50, 16 * TILE_SIZE + 50); - assert_eq!(moved.read_region(all), s.read_region(all.translate(-7, -5))); - } - - #[test] - fn a_surface_bounds_tile_count_is_counted_not_walked() { - let mut s = Surface::new(PixelFormat::RGBA8); - let far = Rect::new(0, 0, i32::MAX, i32::MAX); - assert_eq!(far.tile_count(), u64::from(i32::MAX as u32 / TILE_SIZE as u32 + 1).pow(2)); - // Not allocated: 2^46 entries is far past any reservation. - assert!(s.try_take_tiles(far).is_err()); - } - - #[test] - fn translated_stores_no_tiles_of_only_the_default_pixel() { - let only_default = |t: &Surface| { - let dp = t.default_pixel(); - t.tiles().filter(|(c, _)| t.read_region(c.rect()).chunks_exact(dp.len()).all(|p| p == dp.as_slice())).count() - }; - // Two blocks a few tiles apart, moved off the tile grid and back: the default-pixel edges - // of their tiles land on tiles of their own, which aren't stored. - for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA16, PixelFormat::RGBA32F, PixelFormat::GRAY8] { - for default in [0.0, 0.25] { - let mut s = Surface::with_default(fmt, &vec![default; fmt.channels()]); - s.fill_rect(Rect::new(0, 0, 300, 300), &vec![1.0; fmt.channels()]); - s.fill_rect(Rect::new(2000, 1000, 2300, 1300), &vec![0.5; fmt.channels()]); - let all = Rect::new(-600, -600, 3000, 2000); - let mut t = s.clone(); - for (dx, dy) in [(100, 56), (-100, -56), (10, 7), (-3, 40), (130, -90), (-137, 43)] { - let moved = t.translated(dx, dy, t.content_bounds()); - assert_eq!(moved.read_region(all), t.read_region(all.translate(-dx, -dy)), "{fmt:?} over {default} by ({dx}, {dy})"); - assert_eq!(only_default(&moved), 0, "{fmt:?} over {default} by ({dx}, {dy})"); - t = moved; - } - assert_eq!(t.read_region(all), s.read_region(all), "{fmt:?} over {default}: back where it started"); - assert_eq!(t.tile_count(), s.tile_count(), "{fmt:?} over {default}: back where it started"); - } - } - // Stored tiles of the default pixel inside `content`: the targets that would share one of - // them (#4414's uniform windows) are left out too. - let mut s = Surface::with_default(PixelFormat::GRAY8, &[0.25]); - s.fill_rect(Rect::new(0, 0, 1024, 1024), &[0.25]); - s.write_pixel(600, 600, &[1.0]); - let content = Rect::new(0, 0, 1024, 1024); - let t = s.translated(10, 7, content); - assert_eq!(only_default(&t), 0); - assert_eq!(t.tile_count(), 1); - assert_eq!(t.read_region(Rect::new(-20, -20, 1100, 1100)), s.read_region(Rect::new(-30, -27, 1090, 1093))); - } - - proptest! { - #[test] - fn region_write_read_roundtrip(x in -600i32..600, y in -600i32..600, w in 1u32..90, h in 1u32..90, seed in any::()) { - let r = Rect::from_xywh(x, y, w, h); - let n = 4usize; - let data: Vec = (0..(w * h) as usize * n).map(|i| ((i as u32).wrapping_mul(2654435761).wrapping_add(seed) % 256) as f32 / 255.0).collect(); - let mut s = Surface::new(PixelFormat::RGBA8); - s.write_region(r, &data); - let back = s.read_region(r); - for (a, b) in back.iter().zip(&data) { - prop_assert!((a - b).abs() < 1e-6); - } - prop_assert_eq!(s.content_bounds().union(&r), r); - } - - #[test] - fn clone_mutation_isolated(x in -300i32..300, y in -300i32..300) { - let mut a = Surface::new(PixelFormat::RGBA8); - a.fill_rect(Rect::new(-256, -256, 256, 256), &[0.5, 0.5, 0.5, 1.0]); - let snapshot = a.clone(); - a.write_pixel(x, y, &[1.0, 0.0, 0.0, 1.0]); - let expect = if Rect::new(-256, -256, 256, 256).contains(x, y) { vec![0.5f32, 0.5, 0.5, 1.0] } else { vec![0.0; 4] }; - let got = snapshot.pixel(x, y); - for (g, e) in got.iter().zip(&expect) { - prop_assert!((g - e).abs() <= 1.0 / 255.0); - } - } - } - - #[test] - fn strided_row_sampling_handles_extreme_coordinates_and_steps() { - for sample in SampleType::ALL { - let mut s = Surface::with_default(PixelFormat::new(ColorMode::Grayscale, sample, false), &[0.25]); - for (x, value) in [(i32::MIN, 0.1), (-1, 0.3), (0, 0.4), (i32::MAX - 1, 0.6), (i32::MAX, 0.9)] { - s.write_pixel(x, 0, &[value]); - } - for y in [0, 256] { - for (x0, step, len) in [(i32::MAX, 1, 1), (i32::MIN, i32::MAX, 3), (0, i32::MAX, 2), (i32::MAX - 1, 1, 2), (i32::MAX, i32::MAX, 0)] { - let mut out = vec![0.0; len]; - s.sample_row_strided(y, x0, step, 0, &mut out); - for (i, &got) in out.iter().enumerate() { - let x = i32::try_from(i64::from(x0) + i as i64 * i64::from(step)).unwrap(); - assert_eq!(got, s.sample_channel(x, y, 0), "{sample:?} y={y} x0={x0} step={step} i={i}"); - } - } - } - } - } - - #[test] - fn strided_row_sampling_uses_default_past_coordinate_range() { - for sample in SampleType::ALL { - let mut s = Surface::with_default(PixelFormat::new(ColorMode::Grayscale, sample, false), &[0.25]); - s.write_pixel(i32::MAX, 0, &[0.75]); - s.write_pixel(i32::MIN, 0, &[1.0]); - for step in [1, i32::MAX] { - let mut out = [0.0; 4]; - s.sample_row_strided(0, i32::MAX, step, 0, &mut out); - assert_eq!(out, [s.sample_channel(i32::MAX, 0, 0), s.default_pixel()[0], s.default_pixel()[0], s.default_pixel()[0]]); - } - } - } - - #[test] - fn strided_row_sampling_matches_sample_channel() { - let mut s = Surface::with_default(PixelFormat::GRAY8, &[0.25]); - s.fill_rect(Rect::new(-300, 10, 200, 40), &[1.0]); - s.fill_rect(Rect::new(250, 10, 700, 20), &[0.5]); - for (y, x0, step) in [(15, -520, 7), (15, -1, 1), (30, 3, 64), (500, 0, 9)] { - let mut out = vec![0.0; 120]; - s.sample_row_strided(y, x0, step, 0, &mut out); - for (i, v) in out.iter().enumerate() { - assert_eq!(*v, s.sample_channel(x0 + i as i32 * step, y, 0), "y={y} x0={x0} step={step} i={i}"); - } - } - } - - #[test] - fn content_bounds_with_tile_skipping() { - // Interior content only; ring tiles present but all-default (unpruned). - let mut s = Surface::new(PixelFormat::GRAY8); - s.fill_rect(Rect::new(0, 0, 1024, 1024), &[0.0]); - s.fill_rect(Rect::new(300, 310, 700, 720), &[1.0]); - assert_eq!(s.content_bounds(), Rect::new(300, 310, 700, 720)); - // Full-canvas content plus a far-away speck. - let mut s = Surface::new(PixelFormat::GRAY8); - s.fill_rect(Rect::new(0, 0, 2000, 1500), &[1.0]); - s.fill_rect(Rect::new(-700, 4000, -699, 4001), &[0.5]); - assert_eq!(s.content_bounds(), Rect::new(-700, 0, 2000, 4001)); - } -} +mod tests; #[cfg(test)] mod echelon_case { diff --git a/crates/raster/src/tests.rs b/crates/raster/src/tests.rs new file mode 100644 index 0000000000..1e8cf30ec7 --- /dev/null +++ b/crates/raster/src/tests.rs @@ -0,0 +1,780 @@ +/// Manually compare allocating reads with the previous implementation. +#[test] +#[ignore = "manual 24 MP release benchmark"] +fn benchmark_sparse_reads() { + use std::{hint::black_box, time::Instant}; + let rect = Rect::new(0, 0, 6000, 4000); + for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + for default in [0.0, 0.25] { + let mut s = Surface::with_default(PixelFormat::GRAY8.with_sample(depth), &[default]); + s.fill_rect(Rect::new(257, 257, 266, 266), &[0.75]); + assert_eq!(s.read_region(rect), previous_read_region(&s, rect)); + for trial in 0..6 { + let mut paths = [("main", previous_read_region as fn(&Surface, Rect) -> Vec), ("split", Surface::read_region)]; + if trial % 2 == 1 { + paths.reverse(); + } + for (name, path) in paths { + let t = Instant::now(); + let out = black_box(path)(&s, rect); + let elapsed = t.elapsed().as_secs_f64() * 1000.0; + black_box(&out); + println!("sparse,{depth:?}-{default},{trial},{name},{elapsed:.6}"); + } + } + } + } +} +/// Previous allocating read path, retained as the bitwise-equivalence oracle. +fn previous_read_region(surface: &Surface, r: Rect) -> Vec { + let n = surface.channels(); + let w = r.width() as usize; + let mut out = vec![0.0f32; w * r.height() as usize * n]; + let dp = surface.default_pixel(); + for tc in r.tiles() { + let tr = tc.rect().intersect(&r); + let tile = surface.tiles.get(&tc); + for y in tr.y0..tr.y1 { + for x in tr.x0..tr.x1 { + let o = (((y - r.y0) as usize) * w + (x - r.x0) as usize) * n; + match tile { + Some(t) => { + let base = (((y - tc.ty * TILE_SIZE) as usize) * TILE_SIZE as usize + (x - tc.tx * TILE_SIZE) as usize) * n; + for i in 0..n { + out[o + i] = read_sample(&t.data, surface.format.sample, base + i); + } + } + None => out[o..o + n].copy_from_slice(&dp), + } + } + } + } + out +} +/// Distinct tile allocations in `s`. +fn distinct_tiles(s: &Surface) -> usize { + let mut seen: Vec<*const Tile> = s.tiles().map(|(_, t)| Arc::as_ptr(t)).collect(); + seen.sort(); + seen.dedup(); + seen.len() +} + +/// Converting or tone-mapping a surface keeps a shared tile shared (#4531) and gives the +/// same pixels as converting each pixel: a filled background is one tile across the grid, +/// plus some distinct tiles. +#[test] +fn conversion_keeps_shared_tiles_shared() { + let mut s = Surface::new(PixelFormat::RGBA8); + s.fill_rect(Rect::new(0, 0, 2048, 1024), &[0.9, 0.5, 0.2, 1.0]); + s.fill_rect(Rect::new(10, 10, 20, 20), &[0.1, 0.2, 0.3, 0.5]); + let shared_before = distinct_tiles(&s); + assert!(shared_before <= 2 && s.tile_count() == 32, "{shared_before} distinct of {}", s.tile_count()); + let r = Rect::new(0, 0, 2048, 1024); + for to in [PixelFormat::RGBA16, PixelFormat::RGBA32F] { + for out in [s.convert(to), s.try_convert(to).expect("memory")] { + assert_eq!(distinct_tiles(&out), shared_before, "{to:?}: still shared"); + assert_eq!(out.tile_count(), 32); + let (a, b) = (out.read_region(r), s.read_region(r)); + for (pa, pb) in a.as_chunks::<4>().0.iter().zip(b.as_chunks::<4>().0) { + let want = convert_pixel(&s.format(), &to, pb); + assert!(pa.iter().zip(&want).all(|(x, y)| (x - y).abs() < 1e-6), "{to:?}: {pa:?} vs {want:?}"); + } + } + } + let mut m = s.clone(); + m.map_color(|v| v * 0.5); + assert_eq!(distinct_tiles(&m), shared_before, "map_color keeps it shared"); + assert!((m.pixel(1000, 500)[0] - s.pixel(1000, 500)[0] * 0.5).abs() < 1.0 / 255.0); + assert_eq!(s.pixel(1000, 500), vec![s.pixel(1000, 500)[0], s.pixel(1000, 500)[1], s.pixel(1000, 500)[2], 1.0], "the source is untouched"); +} + +use super::*; +use photocraft_color::PixelFormat; +use proptest::prelude::*; + +fn write_region_reference(surface: &mut Surface, r: Rect, data: &[f32]) { + let n = surface.channels(); + let w = r.width() as usize; + assert_eq!(data.len(), w * r.height() as usize * n, "region data length mismatch"); + let sample = surface.format.sample; + for tc in r.tiles() { + let tr = tc.rect().intersect(&r); + let t = surface.tile_mut(tc); + for y in tr.y0..tr.y1 { + for x in tr.x0..tr.x1 { + let o = (((y - r.y0) as usize) * w + (x - r.x0) as usize) * n; + let base = (((y - tc.ty * TILE_SIZE) as usize) * TILE_SIZE as usize + (x - tc.tx * TILE_SIZE) as usize) * n; + for i in 0..n { + write_sample(&mut t.data, sample, base + i, data[o + i]); + } + } + } + } +} + +#[test] +fn region_writes_match_scalar_bytes_for_every_format() { + let special = [ + 0.0, + -0.0, + 1.0, + -1.0, + 2.0, + f32::INFINITY, + f32::NEG_INFINITY, + f32::NAN, + f32::from_bits(0x7fc12345), + f32::from_bits(0xffc12345), + f32::MIN_POSITIVE, + f32::from_bits(1), + 0.5 / 255.0, + 0.5 / 65535.0, + ]; + for mode in [ + ColorMode::Bitmap, + ColorMode::Grayscale, + ColorMode::Indexed, + ColorMode::Rgb, + ColorMode::Cmyk, + ColorMode::Lab, + ColorMode::Multichannel, + ColorMode::Duotone, + ] { + for sample in SampleType::ALL { + for alpha in [false, true] { + let fmt = PixelFormat::new(mode, sample, alpha); + let mut actual = Surface::with_default(fmt, &vec![0.25; fmt.channels()]); + actual.write_pixel(900, 900, &vec![0.75; fmt.channels()]); + let mut expected = actual.clone(); + for rect in [Rect::EMPTY, Rect::new(-270, -2, 270, 3), Rect::new(256, 256, 512, 257), Rect::new(-64, -64, 0, 0), Rect::new(255, 250, 258, 270)] + { + let data: Vec<_> = (0..rect.width() as usize * rect.height() as usize * fmt.channels()) + .map(|i| { + if i % 3 == 0 { + special[i / 3 % special.len()] + } else { + // Integer rounding boundaries and deterministic arbitrary f32 bit patterns. + let bits = (i as u32).wrapping_mul(2654435761); + if i % 3 == 1 { ((bits % 65536) as f32 + 0.5) / 65535.0 } else { f32::from_bits(bits) } + } + }) + .collect(); + let snapshot = actual.clone(); + let snapshot_bytes = snapshot.to_interleaved(rect.inflate(1)); + let mut par = actual.clone(); + actual.write_region(rect, &data); + par.write_region_par(rect, &data); + write_region_reference(&mut expected, rect, &data); + assert_eq!(actual, expected, "{fmt:?}, {rect:?}"); + assert_eq!(par, expected, "parallel {fmt:?}, {rect:?}"); + assert_eq!(snapshot.to_interleaved(rect.inflate(1)), snapshot_bytes, "COW snapshot changed"); + // Repeat against already materialised, unshared tiles too. + actual.write_region(rect, &data); + par.write_region_par(rect, &data); + assert_eq!(actual, expected); + assert_eq!(par, expected); + } + } + } + } +} + +/// Mask builds call `write_region` inside a `OnceLock` initializer, where entering Rayon can +/// run another tile's job that waits on the same lock. With every global worker held, a write +/// that queued work on Rayon could not finish. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn write_region_does_not_enter_rayon() { + use std::sync::{Barrier, mpsc}; + let workers = rayon::current_num_threads(); + let held = Arc::new(Barrier::new(workers + 1)); + let release = Arc::new(Barrier::new(workers + 1)); + let (h, rel) = (held.clone(), release.clone()); + rayon::spawn_broadcast(move |_| { + h.wait(); + rel.wait(); + }); + held.wait(); + let (tx, rx) = mpsc::channel(); + std::thread::spawn(move || { + let r = Rect::new(0, 0, 2 * TILE_SIZE, 2 * TILE_SIZE); + let mut s = Surface::new(PixelFormat::RGBA8); + s.write_region(r, &vec![0.5; (r.width() * r.height() * 4) as usize]); + tx.send(()).ok(); + }); + let done = rx.recv_timeout(std::time::Duration::from_secs(5)).is_ok(); + release.wait(); + assert!(done, "write_region waited on the Rayon pool"); +} + +#[test] +fn from_rgba_into_matches_from_rgba() { + for fmt in [PixelFormat::RGBA8, PixelFormat::GRAY8, PixelFormat::GRAYA8, PixelFormat::CMYKA8, PixelFormat::new(ColorMode::Lab, SampleType::F32, true)] { + let mut buf = [0.0f32; 8]; + let n = from_rgba_into(&fmt, [0.2, 0.5, 0.7, 0.4], &mut buf); + assert_eq!(&buf[..n], &from_rgba(&fmt, [0.2, 0.5, 0.7, 0.4])[..]); + } +} + +/// Sample counts above the stack capacity use writable storage without truncating channels. +#[test] +fn sample_buffer_keeps_stack_fast_path_and_supports_dynamic_channels() { + for channels in [1, 8, 9, 32] { + let mut stack = [0.0; 8]; + let mut heap = Vec::new(); + let samples = sample_buffer(channels, &mut stack, &mut heap); + assert_eq!(samples.len(), channels); + samples.fill(0.25); + if channels <= stack.len() { + assert!(heap.is_empty()); + assert_eq!(&stack[..channels], vec![0.25; channels]); + } else { + assert_eq!(heap, vec![0.25; channels]); + } + } +} + +/// Compare sparse reads and converted accessors with the previous allocating path. +#[test] +fn zero_alloc_accessors_match_read_region() { + for (fmt, default) in [ + PixelFormat::RGBA8, + PixelFormat::RGBA16, + PixelFormat::RGBA32F, + PixelFormat::GRAYA8, + PixelFormat::CMYKA8, + PixelFormat::GRAY8, + PixelFormat::GRAY8.with_sample(SampleType::F32), + PixelFormat::new(ColorMode::Lab, SampleType::U16, true), + ] + .into_iter() + .flat_map(|fmt| [0.0, 0.25, -0.0].map(|default| (fmt, default))) + { + let mut s = Surface::with_default(fmt, &vec![default; fmt.channels()]); + let mut stack = [0.0; 8]; + let mut heap = Vec::new(); + for capacity in [0, stack.len()] { + let decoded = s.default_samples(&mut stack[..capacity], &mut heap); + assert!(decoded.iter().map(|v| v.to_bits()).eq(s.default_pixel().into_iter().map(f32::to_bits))); + } + let r = Rect::new(-300, -20, 300, 40); + for (i, (x, y)) in [(-299, -19), (0, 0), (255, 39), (256, 10), (299, 0)].into_iter().enumerate() { + let px: Vec = (0..fmt.channels()).map(|c| ((i * 3 + c) % 5) as f32 / 4.0).collect(); + s.write_pixel(x, y, &px); + } + let region = s.read_region(r); + assert!(region.iter().map(|v| v.to_bits()).eq(previous_read_region(&s, r).into_iter().map(f32::to_bits))); + let mut into = vec![9.0; 3]; + s.read_region_into(r, &mut into); + assert_eq!(region, into); + let mut rgba = vec![[0.0; 4]; (r.width() * r.height()) as usize]; + s.read_rgba_into(r, &mut rgba); + let mut rgba8 = vec![[0; 4]; rgba.len()]; + s.read_rgba8_into(r, &mut rgba8); + let n = fmt.channels(); + for (i, p) in region.chunks_exact(n).enumerate() { + let want = to_rgba(&fmt, p); + assert_eq!(rgba8[i], want.map(|v| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8)); + for c in 0..4 { + assert!((rgba[i][c] - want[c]).abs() < 1e-6, "{fmt:?} px {i}"); + } + let (x, y) = (r.x0 + (i % r.width() as usize) as i32, r.y0 + (i / r.width() as usize) as i32); + for c in 0..n { + let bits = s.sample_channel(x, y, c).to_bits(); + assert_eq!(bits, p[c].to_bits()); + assert_eq!(bits, into[i * n + c].to_bits()); + } + } + assert!(s.has_tiles_in(Rect::new(0, 0, 1, 1))); + assert!(!s.has_tiles_in(Rect::new(1000, 1000, 1001, 1001))); + } +} + +#[test] +fn fallible_region_reads_report_size_overflow() { + let surface = Surface::new(PixelFormat::RGBA8); + let huge = Rect::new(i32::MIN, i32::MIN, i32::MAX, i32::MAX); + assert_eq!(surface.try_read_region(huge), Err(AllocationError::SizeOverflow)); + assert_eq!(surface.try_to_interleaved(huge), Err(AllocationError::SizeOverflow)); +} + +#[test] +fn fallible_region_write_rejects_bad_input_without_mutating_surface() { + let mut surface = Surface::new(PixelFormat::RGBA8); + let before = surface.clone(); + assert_eq!(surface.try_write_region(Rect::new(0, 0, 2, 2), &[1.0]), Err(AllocationError::SizeOverflow)); + assert_eq!(surface, before); +} + +#[test] +fn fallible_tile_edits_move_weakly_cached_pixels_and_copy_shared_pixels() { + for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA16, PixelFormat::RGBA32F] { + let mut surface = Surface::new(fmt); + let coord = TileCoord::new(0, 0); + let pixels = surface.try_tile_mut(coord).unwrap().bytes().as_ptr(); + let weak = Arc::downgrade(surface.tile(coord).unwrap()); + let tile = surface.try_tile_mut(coord).unwrap(); + assert_eq!(tile.bytes().as_ptr(), pixels); + assert!(weak.upgrade().is_none()); + let snapshot = surface.clone(); + surface.try_write_region(Rect::new(0, 0, 1, 1), &[1.0; 4]).unwrap(); + assert_eq!(snapshot.pixel(0, 0), vec![0.0; 4]); + assert_eq!(surface.pixel(0, 0), vec![1.0; 4]); + } +} + +#[test] +fn fill_rect_shares_covered_tiles_and_edits_stay_local() { + // A 300000² background used to materialize ~360 GB of tiles (#705). + let mut s = Surface::new(PixelFormat::RGBA8); + s.fill_rect(Rect::new(0, 0, 300_000, 300_000), &[1.0, 0.5, 0.0, 1.0]); + let t = |s: &Surface, x, y| s.tile(TileCoord::new(x, y)).unwrap().clone(); + assert!(Arc::ptr_eq(&t(&s, 0, 0), &t(&s, 1000, 900))); + // 300000 is not a multiple of 256: the edge tile is partial and stays its own. + let edge = 300_000 / TILE_SIZE; + assert!(!Arc::ptr_eq(&t(&s, 0, 0), &t(&s, edge, 0))); + assert_eq!(s.pixel(299_999, 299_999), vec![1.0, 128.0 / 255.0, 0.0, 1.0]); + assert_eq!(s.pixel(300_000, 0), vec![0.0; 4]); + s.write_pixel(5, 5, &[0.0, 0.0, 1.0, 1.0]); + assert_eq!(s.pixel(5, 5), vec![0.0, 0.0, 1.0, 1.0]); + assert_eq!(s.pixel(300, 5), vec![1.0, 128.0 / 255.0, 0.0, 1.0]); + assert!(!Arc::ptr_eq(&t(&s, 0, 0), &t(&s, 1, 0))); +} + +#[test] +fn empty_surface_reads_default() { + let s = Surface::new(PixelFormat::RGBA8); + assert_eq!(s.pixel(10, -500), vec![0.0; 4]); + let m = Surface::with_default(PixelFormat::GRAY8, &[1.0]); + assert_eq!(m.pixel(123_456, -9), vec![1.0]); + assert_eq!(m.tile_count(), 0); +} + +#[test] +fn write_read_pixel_every_depth() { + for sample in SampleType::ALL { + let f = PixelFormat::RGBA8.with_sample(sample); + let mut s = Surface::new(f); + s.write_pixel(-3, 700, &[0.2, 0.4, 0.6, 1.0]); + let p = s.pixel(-3, 700); + for (a, b) in p.iter().zip([0.2, 0.4, 0.6, 1.0]) { + assert!((a - b).abs() <= 1.0 / 255.0, "{sample:?}"); + } + assert_eq!(s.tile_count(), 1); + assert_eq!(s.tile_bounds(), TileCoord::containing(-3, 700).rect()); + } +} + +#[test] +fn copy_on_write_shares_untouched_tiles() { + let mut a = Surface::new(PixelFormat::RGBA8); + a.fill_rect(Rect::new(0, 0, 512, 512), &[1.0, 0.0, 0.0, 1.0]); + let mut b = a.clone(); + b.write_pixel(10, 10, &[0.0, 1.0, 0.0, 1.0]); + // a unchanged + assert_eq!(a.pixel(10, 10), vec![1.0, 0.0, 0.0, 1.0]); + assert_eq!(b.pixel(10, 10), vec![0.0, 1.0, 0.0, 1.0]); + // only tile (0,0) was copied + let shared = a.tiles().filter(|(c, t)| Arc::ptr_eq(t, b.tile(**c).unwrap())).count(); + assert_eq!(shared, 3); +} + +#[test] +fn content_bounds_and_prune() { + let mut s = Surface::new(PixelFormat::RGBA8); + s.fill_rect(Rect::new(300, 10, 310, 20), &[1.0, 1.0, 1.0, 1.0]); + s.write_pixel(-5, -5, &[0.0, 0.0, 0.0, 1.0]); + assert_eq!(s.content_bounds(), Rect::new(-5, -5, 310, 20)); + // erase the single pixel -> its tile becomes default and is pruned + s.write_pixel(-5, -5, &[0.0, 0.0, 0.0, 0.0]); + s.prune(); + assert_eq!(s.tile_count(), 1); + assert_eq!(s.content_bounds(), Rect::new(300, 10, 310, 20)); +} + +#[test] +fn interleaved_roundtrip_crossing_tiles() { + let r = Rect::new(-20, 250, 280, 262); + let bpp = PixelFormat::RGBA16.bytes_per_pixel(); + let bytes: Vec = (0..r.width() as usize * r.height() as usize * bpp).map(|i| (i * 31 % 251) as u8).collect(); + let s = Surface::from_interleaved(PixelFormat::RGBA16, r, &bytes); + assert_eq!(s.to_interleaved(r), bytes); + assert_eq!(s.tile_count(), 6); // x tiles -1..=1, y tiles 0..=1 +} + +#[test] +fn region_outside_reads_default() { + let s = Surface::with_default(PixelFormat::GRAY8, &[1.0]); + let v = s.read_region(Rect::new(0, 0, 3, 3)); + assert_eq!(v, vec![1.0; 9]); +} + +#[test] +fn convert_depths_and_models() { + let mut s = Surface::new(PixelFormat::RGBA8); + s.write_pixel(1, 1, &[1.0, 1.0, 1.0, 1.0]); + let g = s.convert(PixelFormat::GRAYA8); + assert!((g.pixel(1, 1)[0] - 1.0).abs() < 1e-2); + let f = s.convert(PixelFormat::RGBA32F); + assert_eq!(f.pixel(1, 1), vec![1.0, 1.0, 1.0, 1.0]); + let c = s.convert(PixelFormat::CMYKA8); + let p = c.pixel(1, 1); + assert!(p[3] < 0.01 && (p[4] - 1.0).abs() < 1e-6); + let back = c.convert(PixelFormat::RGBA8); + assert_eq!(back.pixel(1, 1), vec![1.0, 1.0, 1.0, 1.0]); +} + +#[test] +fn rgba_from_gray_and_cmyk() { + let mut g = Surface::new(PixelFormat::GRAYA8); + g.write_pixel(0, 0, &[0.5, 1.0]); + let v = g.rgba(0, 0); + assert!((v[0] - v[2]).abs() < 1e-6 && (v[3] - 1.0).abs() < 1e-6); +} + +#[test] +fn repeated_cmyk_reads_match_individual_pixels_bitwise() { + let rect = Rect::new(-2, -1, 515, 2); + for depth in SampleType::ALL { + for alpha in [false, true] { + let fmt = PixelFormat::new(ColorMode::Cmyk, depth, alpha); + let mut s = Surface::with_default(fmt, &[0.2, 0.4, 0.6, 0.3, 0.7]); + for (i, x) in (-1..514).enumerate() { + let c = if i / 2 % 256 == 0 { -0.0 } else { (i / 2 % 256) as f32 / 255.0 }; + s.write_pixel(x, 0, &[c, 0.4, 0.6, 0.3, (i % 9) as f32 / 8.0]); + } + let mut out = vec![[0.0; 4]; (rect.width() * rect.height()) as usize]; + s.read_rgba_into(rect, &mut out); + for (i, actual) in out.iter().enumerate() { + let expected = s.rgba(rect.x0 + (i % rect.width() as usize) as i32, rect.y0 + (i / rect.width() as usize) as i32); + assert_eq!(actual.map(f32::to_bits), expected.map(f32::to_bits), "{depth:?}, alpha={alpha}, pixel={i}"); + } + } + } +} + +#[test] +fn rgba_reads_match_individual_pixels_bitwise_in_every_model_and_depth() { + // Across tile edges and a missing tile; float samples include -0, out-of-range and NaN. + let rect = Rect::new(-3, -1, 300, 2); + for mode in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Lab, ColorMode::Cmyk] { + for depth in SampleType::ALL { + for alpha in [false, true] { + let fmt = PixelFormat::new(mode, depth, alpha); + let mut s = Surface::with_default(fmt, &vec![0.25; fmt.channels()]); + let values = [-0.0, 0.1, 0.5, 1.0, 1.5, -0.25, f32::NAN, 0.75]; + for (i, x) in (-2..260).enumerate() { + let px: Vec = (0..fmt.channels()).map(|c| values[(i + c * 3) % values.len()]).collect(); + s.write_pixel(x, 0, &px); + } + let mut out = vec![[0.0; 4]; (rect.width() * rect.height()) as usize]; + s.read_rgba_into(rect, &mut out); + for (i, actual) in out.iter().enumerate() { + let expected = s.rgba(rect.x0 + (i % rect.width() as usize) as i32, rect.y0 + (i / rect.width() as usize) as i32); + assert_eq!(actual.map(f32::to_bits), expected.map(f32::to_bits), "{fmt:?}, pixel={i}"); + } + } + } + } +} + +#[test] +fn tile_content_bounds_scans_against_the_given_pixel() { + let mut s = Surface::new(PixelFormat::GRAY8); + s.write_pixel(3, 4, &[1.0]); + s.write_pixel(200, 9, &[1.0]); + let t = s.tile(TileCoord::new(0, 0)).expect("written tile"); + assert_eq!(t.content_bounds(&[0]), Some((3, 4, 201, 10))); + assert_eq!(t.content_bounds(&[255]).map(|b| (b.0, b.1)), Some((0, 0))); + // A malformed pixel is no content, not a panic. + assert_eq!(t.content_bounds(&[]), None); +} + +#[test] +fn tile_content_bounds_match_a_per_pixel_scan() { + // One differing byte at each position of a pixel, at and around the compare-block + // boundaries, in every pixel size; and a pixel that differs from `dp` in every byte. + fn per_pixel(t: &Tile, dp: &[u8]) -> Option<(u16, u16, u16, u16)> { + let (bpp, ts) = (dp.len(), TILE_SIZE as usize); + let mut b: Option<(usize, usize, usize, usize)> = None; + for (i, px) in t.bytes().chunks_exact(bpp).enumerate() { + if px != dp { + let (x, y) = (i % ts, i / ts); + let (x0, y0, x1, y1) = b.unwrap_or((x, y, x, y)); + b = Some((x0.min(x), y0.min(y), x1.max(x), y1.max(y))); + } + } + b.map(|(x0, y0, x1, y1)| (x0 as u16, y0 as u16, x1 as u16 + 1, y1 as u16 + 1)) + } + for bpp in [1, 2, 3, 4, 6, 8, 16] { + let dp: Vec = (0..bpp).map(|i| (i * 37 + 5) as u8).collect(); + let row = TILE_SIZE as usize * bpp; + for spots in [vec![], vec![0], vec![row - 1], vec![63, 64], vec![row * 7 + 127, row * 7 + 128, row * 200 + 5], vec![row * 255 + row / 2]] { + for byte in 0..bpp { + let mut data = dp.repeat(TILE_SIZE as usize * TILE_SIZE as usize); + for &s in &spots { + data[s - s % bpp + byte] ^= 0x5a; + } + let t = Tile { data: data.into_boxed_slice() }; + assert_eq!(t.content_bounds(&dp), per_pixel(&t, &dp), "bpp {bpp}, spots {spots:?}, byte {byte}"); + } + } + let mut data = dp.repeat(TILE_SIZE as usize * TILE_SIZE as usize); + data[row * 3 + 9 * bpp..row * 3 + 10 * bpp].iter_mut().for_each(|b| *b = !*b); + let t = Tile { data: data.into_boxed_slice() }; + assert_eq!(t.content_bounds(&dp), Some((9, 3, 10, 4)), "bpp {bpp}"); + } +} + +#[test] +fn translated_matches_reading_the_moved_pixels() { + // Any offset (whole tiles, negative, across tile edges), every depth, a non-zero default. + for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA16, PixelFormat::RGBA32F, PixelFormat::GRAY8] { + let mut s = Surface::with_default(fmt, &vec![0.25; fmt.channels()]); + let r = Rect::new(-37, 200, 530, 300); + let v: Vec = (0..r.width() * r.height() * fmt.channels() as u32).map(|i| (i % 251) as f32 / 250.0).collect(); + s.write_region(r, &v); + for (dx, dy) in [(0, 0), (256, -512), (1, 0), (-3, 7), (300, -257), (-1000, 999)] { + let t = s.translated(dx, dy, s.content_bounds()); + let moved = r.translate(dx, dy).inflate(3); + assert_eq!(t.read_region(moved), s.read_region(moved.translate(-dx, -dy)), "{fmt:?} by ({dx}, {dy})"); + assert_eq!(t.default_pixel(), s.default_pixel()); + assert_eq!(t.to_interleaved(r.translate(dx, dy)), s.to_interleaved(r), "{fmt:?} by ({dx}, {dy}): not an exact copy"); + } + // Whole tiles: the tiles are shared, not copied. + let t = s.translated(512, -256, s.content_bounds()); + assert!(s.tiles().zip(t.tiles()).all(|((_, a), (_, b))| Arc::ptr_eq(a, b))); + // Tiles without content (allocated, default pixels) are left behind. + let mut padded = s.clone(); + padded.fill_rect(Rect::new(2000, 2000, 2100, 2100), &s.default_pixel()); + assert_eq!(padded.translated(5, 5, s.content_bounds()).tile_count(), s.translated(5, 5, s.content_bounds()).tile_count()); + } + // A solid fill moved off the tile grid keeps sharing its one tile inside, at every depth + // and over a non-zero default pixel, and reads exactly like the copied pixels. + for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA16, PixelFormat::RGBA32F, PixelFormat::GRAY8] { + let mut s = Surface::with_default(fmt, &vec![0.25; fmt.channels()]); + let r = Rect::new(-300, -10, 1300, 1030); + s.fill_rect(r, &vec![0.75; fmt.channels()]); + let fill = s.tile(TileCoord::new(1, 1)).cloned().expect("an inner fill tile"); + for (dx, dy) in [(10, 7), (-1, 0), (0, 300), (-257, 513)] { + let t = s.translated(dx, dy, s.content_bounds()); + let moved = r.translate(dx, dy); + assert_eq!(t.read_region(moved.inflate(3)), s.read_region(moved.inflate(3).translate(-dx, -dy)), "{fmt:?} by ({dx}, {dy})"); + // Targets read only from the fill's whole tiles (x -256..1280, y 0..1024). + let whole = Rect::new(-256, 0, 1280, 1024).translate(dx, dy); + let inner: Vec<_> = t.tiles().filter(|(c, _)| whole.contains_rect(&c.rect())).collect(); + assert!(!inner.is_empty() && inner.iter().all(|(_, a)| Arc::ptr_eq(a, &fill)), "{fmt:?} by ({dx}, {dy}): inner tiles copied"); + } + // Nudged back and forth, the inside keeps sharing one tile (copies of uniform edge + // tiles count as that value too) and the pixels stay exact. + let mut t = s.clone(); + for k in 0..8 { + let d = if k % 2 == 0 { 10 } else { -10 }; + t = t.translated(d, d / 2, t.content_bounds()); + } + // (Targets whose last window read uniform tiles only: one tile in from the fill's whole + // tiles on the sides the last move came from.) + let inner: Vec<_> = t.tiles().filter(|(c, _)| Rect::new(-256, 0, 1024, 768).contains_rect(&c.rect())).map(|(_, a)| a).collect(); + assert!(inner.len() >= 4 && inner.iter().all(|a| Arc::ptr_eq(a, inner[0])), "{fmt:?}: repeated moves copied the inside"); + assert_eq!(t.read_region(r.inflate(3)), s.read_region(r.inflate(3)), "{fmt:?}: back where it started"); + } + // Two solid fills of different values side by side: windows across the seam are + // copied (each tile is uniform, but not with the same value), the rest shared. + for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA32F] { + let mut s = Surface::new(fmt); + s.fill_rect(Rect::new(0, 0, 1024, 768), &vec![0.2; fmt.channels()]); + s.fill_rect(Rect::new(1024, 0, 2048, 768), &vec![0.9; fmt.channels()]); + let t = s.translated(10, 7, s.content_bounds()); + let all = Rect::new(-20, -20, 2100, 800); + assert_eq!(t.read_region(all), s.read_region(all.translate(-10, -7)), "{fmt:?}: two fills"); + let seam = t.tile(TileCoord::new(4, 1)).expect("seam tile"); + let (left, right) = (t.tile(TileCoord::new(2, 1)).expect("left"), t.tile(TileCoord::new(6, 1)).expect("right")); + assert!(!Arc::ptr_eq(seam, left) && !Arc::ptr_eq(seam, right) && !Arc::ptr_eq(left, right), "{fmt:?}: seam aliased"); + } + // An offset of i32::MIN saturates its negation, so the source window isn't the exact + // preimage: no shortcut may apply (a zero pre-fill would leak into the output). + let mut s = Surface::with_default(PixelFormat::GRAY8, &[0.5]); + s.fill_rect(Rect::new(i32::MAX - 1024, 0, i32::MAX - 512, 512), &[0.25]); + let (fill, default) = (s.sample_channel(i32::MAX - 600, 10, 0), s.default_pixel()[0]); + for (dx, dy) in [(i32::MIN, 1), (1, i32::MIN), (i32::MIN, 0)] { + let t = s.translated(dx, dy, s.content_bounds()); + for (c, _) in t.tiles() { + assert!(t.read_region(c.rect()).iter().all(|v| *v == fill || *v == default), "({dx}, {dy}): tile {c:?} holds a pre-fill"); + } + } + // One tile shared but not uniform: each target is copied, not aliased. + let mut s = Surface::new(PixelFormat::GRAY8); + s.write_pixel(3, 4, &[1.0]); + let odd = s.tile(TileCoord::new(0, 0)).cloned().expect("written tile"); + let grid: Vec<_> = (0..9).map(|i| (TileCoord::new(i % 3, i / 3), odd.clone())).collect(); + s.put_tiles(grid); + let t = s.translated(10, 7, s.content_bounds()); + let all = Rect::new(-20, -20, 800, 800); + assert_eq!(t.read_region(all), s.read_region(all.translate(-10, -7))); + assert!(t.tiles().all(|(_, a)| !Arc::ptr_eq(a, &odd))); + // Offsets at the limits don't panic. + let mut s = Surface::new(PixelFormat::GRAY8); + s.write_pixel(5, 5, &[1.0]); + let all = Rect::new(i32::MIN, i32::MIN, i32::MAX, i32::MAX); + let _ = s.translated(i32::MAX, i32::MIN, all); + let _ = s.translated(i32::MIN + 1, 3, all); +} + +/// Many references to one payload, moved off the tile grid: the rebuilt tiles that read the +/// same source tiles at the same offset are one tile, not a copy each. +#[test] +fn translated_shares_tiles_rebuilt_from_shared_sources() { + let fmt = PixelFormat::RGBA8; + let mut one = Surface::new(fmt); + let r = Rect::new(0, 0, TILE_SIZE, TILE_SIZE); + let px: Vec = (0..r.width() * r.height()).flat_map(|i| [(i % 251) as f32 / 255.0, (i % 7) as f32 / 7.0, 0.5, 1.0]).collect(); + one.write_region(r, &px); + let payload = Arc::clone(one.tile(TileCoord::new(0, 0)).unwrap()); + let mut s = Surface::new(fmt); + s.put_tiles((0..16).flat_map(|ty| (0..16).map(move |tx| TileCoord::new(tx, ty))).map(|c| (c, Arc::clone(&payload)))); + let moved = s.translated(7, 5, s.content_bounds()); + let distinct: std::collections::HashSet<_> = moved.tiles().map(|(_, t)| Arc::as_ptr(t)).collect(); + // The 15 × 15 interior tiles read the same four source tiles at the same offset, so they are + // one tile, however many threads build them; only the 64 border tiles (cut by the + // content's edge) are built one by one. + assert!(moved.tile_count() == 289 && distinct.len() == 64 + 1, "{} tiles, {} distinct", moved.tile_count(), distinct.len()); + let all = Rect::new(-50, -50, 16 * TILE_SIZE + 50, 16 * TILE_SIZE + 50); + assert_eq!(moved.read_region(all), s.read_region(all.translate(-7, -5))); +} + +#[test] +fn a_surface_bounds_tile_count_is_counted_not_walked() { + let mut s = Surface::new(PixelFormat::RGBA8); + let far = Rect::new(0, 0, i32::MAX, i32::MAX); + assert_eq!(far.tile_count(), u64::from(i32::MAX as u32 / TILE_SIZE as u32 + 1).pow(2)); + // Not allocated: 2^46 entries is far past any reservation. + assert!(s.try_take_tiles(far).is_err()); +} + +#[test] +fn translated_stores_no_tiles_of_only_the_default_pixel() { + let only_default = |t: &Surface| { + let dp = t.default_pixel(); + t.tiles().filter(|(c, _)| t.read_region(c.rect()).chunks_exact(dp.len()).all(|p| p == dp.as_slice())).count() + }; + // Two blocks a few tiles apart, moved off the tile grid and back: the default-pixel edges + // of their tiles land on tiles of their own, which aren't stored. + for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA16, PixelFormat::RGBA32F, PixelFormat::GRAY8] { + for default in [0.0, 0.25] { + let mut s = Surface::with_default(fmt, &vec![default; fmt.channels()]); + s.fill_rect(Rect::new(0, 0, 300, 300), &vec![1.0; fmt.channels()]); + s.fill_rect(Rect::new(2000, 1000, 2300, 1300), &vec![0.5; fmt.channels()]); + let all = Rect::new(-600, -600, 3000, 2000); + let mut t = s.clone(); + for (dx, dy) in [(100, 56), (-100, -56), (10, 7), (-3, 40), (130, -90), (-137, 43)] { + let moved = t.translated(dx, dy, t.content_bounds()); + assert_eq!(moved.read_region(all), t.read_region(all.translate(-dx, -dy)), "{fmt:?} over {default} by ({dx}, {dy})"); + assert_eq!(only_default(&moved), 0, "{fmt:?} over {default} by ({dx}, {dy})"); + t = moved; + } + assert_eq!(t.read_region(all), s.read_region(all), "{fmt:?} over {default}: back where it started"); + assert_eq!(t.tile_count(), s.tile_count(), "{fmt:?} over {default}: back where it started"); + } + } + // Stored tiles of the default pixel inside `content`: the targets that would share one of + // them (#4414's uniform windows) are left out too. + let mut s = Surface::with_default(PixelFormat::GRAY8, &[0.25]); + s.fill_rect(Rect::new(0, 0, 1024, 1024), &[0.25]); + s.write_pixel(600, 600, &[1.0]); + let content = Rect::new(0, 0, 1024, 1024); + let t = s.translated(10, 7, content); + assert_eq!(only_default(&t), 0); + assert_eq!(t.tile_count(), 1); + assert_eq!(t.read_region(Rect::new(-20, -20, 1100, 1100)), s.read_region(Rect::new(-30, -27, 1090, 1093))); +} + +proptest! { + #[test] + fn region_write_read_roundtrip(x in -600i32..600, y in -600i32..600, w in 1u32..90, h in 1u32..90, seed in any::()) { + let r = Rect::from_xywh(x, y, w, h); + let n = 4usize; + let data: Vec = (0..(w * h) as usize * n).map(|i| ((i as u32).wrapping_mul(2654435761).wrapping_add(seed) % 256) as f32 / 255.0).collect(); + let mut s = Surface::new(PixelFormat::RGBA8); + s.write_region(r, &data); + let back = s.read_region(r); + for (a, b) in back.iter().zip(&data) { + prop_assert!((a - b).abs() < 1e-6); + } + prop_assert_eq!(s.content_bounds().union(&r), r); + } + + #[test] + fn clone_mutation_isolated(x in -300i32..300, y in -300i32..300) { + let mut a = Surface::new(PixelFormat::RGBA8); + a.fill_rect(Rect::new(-256, -256, 256, 256), &[0.5, 0.5, 0.5, 1.0]); + let snapshot = a.clone(); + a.write_pixel(x, y, &[1.0, 0.0, 0.0, 1.0]); + let expect = if Rect::new(-256, -256, 256, 256).contains(x, y) { vec![0.5f32, 0.5, 0.5, 1.0] } else { vec![0.0; 4] }; + let got = snapshot.pixel(x, y); + for (g, e) in got.iter().zip(&expect) { + prop_assert!((g - e).abs() <= 1.0 / 255.0); + } + } +} + +#[test] +fn strided_row_sampling_handles_extreme_coordinates_and_steps() { + for sample in SampleType::ALL { + let mut s = Surface::with_default(PixelFormat::new(ColorMode::Grayscale, sample, false), &[0.25]); + for (x, value) in [(i32::MIN, 0.1), (-1, 0.3), (0, 0.4), (i32::MAX - 1, 0.6), (i32::MAX, 0.9)] { + s.write_pixel(x, 0, &[value]); + } + for y in [0, 256] { + for (x0, step, len) in [(i32::MAX, 1, 1), (i32::MIN, i32::MAX, 3), (0, i32::MAX, 2), (i32::MAX - 1, 1, 2), (i32::MAX, i32::MAX, 0)] { + let mut out = vec![0.0; len]; + s.sample_row_strided(y, x0, step, 0, &mut out); + for (i, &got) in out.iter().enumerate() { + let x = i32::try_from(i64::from(x0) + i as i64 * i64::from(step)).unwrap(); + assert_eq!(got, s.sample_channel(x, y, 0), "{sample:?} y={y} x0={x0} step={step} i={i}"); + } + } + } + } +} + +#[test] +fn strided_row_sampling_uses_default_past_coordinate_range() { + for sample in SampleType::ALL { + let mut s = Surface::with_default(PixelFormat::new(ColorMode::Grayscale, sample, false), &[0.25]); + s.write_pixel(i32::MAX, 0, &[0.75]); + s.write_pixel(i32::MIN, 0, &[1.0]); + for step in [1, i32::MAX] { + let mut out = [0.0; 4]; + s.sample_row_strided(0, i32::MAX, step, 0, &mut out); + assert_eq!(out, [s.sample_channel(i32::MAX, 0, 0), s.default_pixel()[0], s.default_pixel()[0], s.default_pixel()[0]]); + } + } +} + +#[test] +fn strided_row_sampling_matches_sample_channel() { + let mut s = Surface::with_default(PixelFormat::GRAY8, &[0.25]); + s.fill_rect(Rect::new(-300, 10, 200, 40), &[1.0]); + s.fill_rect(Rect::new(250, 10, 700, 20), &[0.5]); + for (y, x0, step) in [(15, -520, 7), (15, -1, 1), (30, 3, 64), (500, 0, 9)] { + let mut out = vec![0.0; 120]; + s.sample_row_strided(y, x0, step, 0, &mut out); + for (i, v) in out.iter().enumerate() { + assert_eq!(*v, s.sample_channel(x0 + i as i32 * step, y, 0), "y={y} x0={x0} step={step} i={i}"); + } + } +} + +#[test] +fn content_bounds_with_tile_skipping() { + // Interior content only; ring tiles present but all-default (unpruned). + let mut s = Surface::new(PixelFormat::GRAY8); + s.fill_rect(Rect::new(0, 0, 1024, 1024), &[0.0]); + s.fill_rect(Rect::new(300, 310, 700, 720), &[1.0]); + assert_eq!(s.content_bounds(), Rect::new(300, 310, 700, 720)); + // Full-canvas content plus a far-away speck. + let mut s = Surface::new(PixelFormat::GRAY8); + s.fill_rect(Rect::new(0, 0, 2000, 1500), &[1.0]); + s.fill_rect(Rect::new(-700, 4000, -699, 4001), &[0.5]); + assert_eq!(s.content_bounds(), Rect::new(-700, 0, 2000, 4001)); +} diff --git a/crates/raw/src/nefc.rs b/crates/raw/src/nefc.rs index 2ae312917d..e09d934b4b 100644 --- a/crates/raw/src/nefc.rs +++ b/crates/raw/src/nefc.rs @@ -381,311 +381,4 @@ pub(crate) fn read_compressed(t: &Tiff, raw: &Ifd, note: Option<&(Tiff, Ifd)>, l } #[cfg(test)] -mod tests { - use super::*; - - /// MSB-first bit writer for the test encoder. - #[derive(Default)] - struct Writer { - out: Vec, - acc: u64, - n: u32, - } - - impl Writer { - fn put(&mut self, v: u32, len: u32) { - for i in (0..len).rev() { - self.acc = (self.acc << 1) | u64::from((v >> i) & 1); - self.n += 1; - if self.n == 8 { - self.out.push(self.acc as u8); - self.acc = 0; - self.n = 0; - } - } - } - fn finish(mut self) -> Vec { - if self.n > 0 { - self.out.push((self.acc << (8 - self.n)) as u8); - } - self.out.extend_from_slice(&[0; 4]); - self.out - } - } - - /// `(code, length)` per category, from the canonical table. - fn codes(t: &Table) -> Vec<(u32, u32)> { - let mut out = vec![(0, 0); 17]; - let mut code = 0u32; - let mut symbols = t.symbols.iter(); - for (i, &n) in t.counts.iter().enumerate() { - for _ in 0..n { - let s = *symbols.next().unwrap(); - if s != UNSEEN { - out[s as usize] = (code, i as u32 + 1); - } - code += 1; - } - code <<= 1; - } - out - } - - /// Encodes `values` (samples or curve indices) the way the camera does. - fn encode(values: &[i32], w: usize, t: &Table, seeds: [[i32; 2]; 2]) -> Vec { - let codes = codes(t); - let mut wr = Writer::default(); - let mut vpred = seeds; - for (y, row) in values.chunks(w).enumerate() { - for (x, &v) in row.iter().enumerate() { - let pred = if x < 2 { vpred[y & 1][x] } else { row[x - 2] }; - if x < 2 { - vpred[y & 1][x] = v; - } - let d = v - pred; - let k = 32 - d.unsigned_abs().leading_zeros(); - let (code, len) = codes[k as usize]; - assert!(len > 0, "no code for category {k}"); - wr.put(code, len); - wr.put(if d < 0 { (d + (1 << k) - 1) as u32 } else { d as u32 }, k); - } - } - wr.finish() - } - - /// Smooth gradient + texture + hard edges, within `0..=max`. - fn image(w: usize, h: usize, max: i32, seed: u32) -> Vec { - let mut s = seed; - (0..w * h) - .map(|i| { - let (x, y) = ((i % w) as i32, (i / w) as i32); - s = s.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); - let noise = (s >> 24) as i32 % 9 - 4; - let base = (x * 37 + y * 11) % (max / 2) + if (x / 7 + y / 5) % 3 == 0 { max / 3 } else { 0 }; - (base + noise).clamp(0, max) - }) - .collect() - } - - fn lossless(bits: u32) -> DecodeTable { - let s = 1 << (bits - 3); - DecodeTable { encoding: Encoding::Lossless, seeds: [[s, s], [s, s]] } - } - - fn lossy_table(bits: u32, le: bool) -> Vec { - let mut t = vec![0x44, 0x20]; - let put = |t: &mut Vec, v: u16| t.extend_from_slice(&if le { v.to_le_bytes() } else { v.to_be_bytes() }); - for _ in 0..4 { - put(&mut t, 300); - } - put(&mut t, 257); - let max = f64::from((1u32 << bits) - 1); - for i in 0..257u32 { - put(&mut t, (max * (f64::from(i) / 64.0).min(1.0).sqrt()) as u16); - } - t.resize(624, 0); - t - } - - #[test] - fn tables_are_prefix_codes() { - for t in [LOSSLESS_12, LOSSLESS_14, LOSSY_12, LOSSY_14] { - assert_eq!(t.counts.iter().map(|&c| c as usize).sum::(), t.symbols.len()); - let kraft: f64 = t.counts.iter().enumerate().map(|(i, &c)| f64::from(c) / f64::from(1u32 << (i + 1))).sum(); - assert!(kraft <= 1.0); - assert!(Huffman::new(&t).is_ok()); - } - } - - #[test] - fn lossless_round_trip_12_and_14() { - for (bits, t) in [(12, LOSSLESS_12), (14, LOSSLESS_14)] { - let (w, h) = (64, 9); - let max = (1 << bits) - 1; - let mut img = image(w, h, max, bits); - img[5] = 0; - img[7] = max; - img[w + 9] = max; - let table = lossless(bits); - let out = decode(&encode(&img, w, &t, table.seeds), w, h, bits, &table).unwrap(); - assert_eq!(out, img.iter().map(|&v| v as u16).collect::>(), "{bits}-bit"); - } - } - - #[test] - fn lossy_type2_curve_and_round_trip() { - for (bits, t) in [(12u32, LOSSY_12), (14, LOSSY_14)] { - for le in [false, true] { - let table = parse_table(&lossy_table(bits, le), le, bits).unwrap(); - assert_eq!(table.seeds, [[300, 300], [300, 300]]); - let Encoding::Lossy(curve) = &table.encoding else { panic!() }; - let step = (1usize << bits) / 256; - assert_eq!(curve.len(), (1 << bits) + 1); - assert_eq!(curve[64 * step], (1 << bits) - 1); - assert!(curve.windows(2).all(|p| p[0] <= p[1])); - let (w, h) = (48, 7); - let img = image(w, h, 64 * step as i32 - 1, 7); - let out = decode(&encode(&img, w, &t, table.seeds), w, h, bits, &table).unwrap(); - assert_eq!(out, img.iter().map(|&v| curve[v as usize]).collect::>()); - } - } - } - - #[test] - fn lossy_type1_full_curve() { - let mut t = vec![0x44, 0x10, 0, 10, 0, 10, 0, 10, 0, 10, 0, 5]; - for v in [0u16, 100, 400, 900, 1600] { - t.extend_from_slice(&v.to_be_bytes()); - } - let table = parse_table(&t, false, 12).unwrap(); - assert_eq!(table.encoding, Encoding::Lossy(vec![0, 100, 400, 900, 1600])); - let img = vec![0, 4, 1, 3, 2, 2, 4, 0]; - assert_eq!(decode(&encode(&img, 4, &LOSSY_12, table.seeds), 4, 2, 12, &table).unwrap(), vec![0, 1600, 100, 900, 400, 400, 1600, 0]); - } - - #[test] - fn unsupported_and_malformed_tables() { - let unsupported = |r: Result| matches!(r, Err(RawError::Unsupported(_))); - let malformed = |r: Result| matches!(r, Err(RawError::Malformed(_))); - let mut split = lossy_table(12, false); - split[562..564].copy_from_slice(&345u16.to_be_bytes()); - assert!(unsupported(parse_table(&split, false, 12))); - assert!(unsupported(parse_table(&[0x49, 0x30, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], false, 12))); - assert!(unsupported(parse_table(&lossy_table(12, false), false, 16))); - assert!(malformed(parse_table(&[], false, 12))); - assert!(malformed(parse_table(&[0x46, 0x30, 8], false, 14))); - assert!(malformed(parse_table(&lossy_table(12, false)[..100], false, 12))); - let mut odd = lossy_table(12, false); - odd[10..12].copy_from_slice(&300u16.to_be_bytes()); - assert!(parse_table(&odd, false, 12).is_err()); - assert!(parse_table(&[0x44, 0x20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], false, 12).is_err()); - } - - #[test] - fn modern_lossy_curve_preserves_sensor_adus_at_both_depths() { - for bits in [12u32, 14] { - for le in [false, true] { - let put = |v: u16| if le { v.to_le_bytes() } else { v.to_be_bytes() }; - let mut t = vec![0x44, 0x40]; - for _ in 0..4 { - t.extend(put(256)); - } - t.extend(put(257)); - let white = (1u16 << bits) - 1; - for i in 0..=256u32 { - t.extend(put(((i * 64).min(u32::from(white))) as u16)); - } - t.resize(624, 0); - let parsed = parse_table(&t, le, bits).unwrap(); - let Encoding::Lossy(curve) = &parsed.encoding else { panic!() }; - let range = 1usize << (bits - 2); - assert_eq!(curve.len(), range + 1); - assert_eq!(curve[range], white); - // Stored point 16 is 1024 ADU. It belongs to encoded code 256 - // at 14 bits, code 64 at 12 bits, independent of end-point clipping. - assert_eq!(curve[range / 16], 1024.min(white)); - let indices = vec![0, (range / 16) as i32, (range / 8) as i32, (range / 32) as i32]; - let huffman = if bits == 12 { &LOSSY_12 } else { &LOSSY_14 }; - let src = encode(&indices, 2, huffman, parsed.seeds); - assert_eq!(decode(&src, 2, 2, bits, &parsed).unwrap(), vec![0, 1024, 2048, 512]); - } - } - } - - /// A 14-bit lossless table (version 0x46) with the given seeds. - fn lossless_table(seed: u16, le: bool) -> Vec { - let mut t = vec![0x46, 0x30]; - for _ in 0..4 { - t.extend_from_slice(&if le { seed.to_le_bytes() } else { seed.to_be_bytes() }); - } - t.resize(46, 0); - t - } - - #[test] - fn decodes_through_the_nef_container() { - use crate::testgen::{Val, nef_compressed}; - use crate::{Limits, RawFormat, identify}; - let (w, h) = (40usize, 6usize); - // lossless 14-bit, big-endian maker note, with a BlackLevel tag - let img = image(w, h, 16383, 11); - let src = encode(&img, w, &LOSSLESS_14, [[2048; 2]; 2]); - let note = vec![(0x0096, Val::Undefined(lossless_table(2048, false))), (0x003d, Val::Short(vec![600, 600, 600, 600]))]; - let b = nef_compressed(w, h, 14, src, [0, 1, 1, 2], true, note); - assert_eq!(identify(&b), Some(RawFormat::Nef)); - let s = crate::decode(&b, &Limits::default()).unwrap(); - assert_eq!(s.data, img.iter().map(|&v| v as u16).collect::>()); - assert_eq!(s.black.values, vec![600.0; 4]); - // lossy 12-bit type 2, little-endian maker note (newer bodies); the - // 12-bit BlackLevel is scaled from 14-bit units - let table = lossy_table(12, true); - let t = parse_table(&table, true, 12).unwrap(); - let Encoding::Lossy(curve) = &t.encoding else { panic!() }; - let img = image(w, h, 1023, 5); - let src = encode(&img, w, &LOSSY_12, t.seeds); - let note = vec![(0x0096, Val::Undefined(table.clone())), (0x003d, Val::Short(vec![600, 600, 600, 600]))]; - let s = crate::decode(&nef_compressed(w, h, 12, src.clone(), [2, 1, 1, 0], false, note), &Limits::default()).unwrap(); - assert_eq!(s.data, img.iter().map(|&v| curve[v as usize]).collect::>()); - assert_eq!(s.black.values, vec![150.0; 4]); - assert!(crate::develop_sensor(&s, &crate::DevelopOptions::default()).is_ok()); - // "lossy after split" and a missing table stay unsupported (preview fallback) - let mut split = table; - split[562..564].copy_from_slice(&3u16.to_le_bytes()); - let e = crate::decode(&nef_compressed(w, h, 12, src.clone(), [2, 1, 1, 0], false, vec![(0x0096, Val::Undefined(split))]), &Limits::default()); - assert!(matches!(e, Err(RawError::Unsupported(_))), "{e:?}"); - let e = crate::decode(&nef_compressed(w, h, 12, src, [2, 1, 1, 0], false, vec![(0x0001, Val::Short(vec![0]))]), &Limits::default()); - assert!(matches!(&e, Err(RawError::Unsupported(m)) if m.contains("Nikon compressed NEF")), "{e:?}"); - } - - #[test] - fn nikon_without_black_level_tag_is_black_subtracted() { - use crate::testgen::{Val, nef_compressed}; - let (w, h) = (32usize, 8usize); - let img = image(w, h, 16383, 4); - let src = encode(&img, w, &LOSSLESS_14, [[2048; 2]; 2]); - let b = nef_compressed(w, h, 14, src, [0, 1, 1, 2], true, vec![(0x0096, Val::Undefined(lossless_table(2048, false)))]); - let s = crate::decode(&b, &crate::Limits::default()).unwrap(); - assert_eq!(s.black.values, vec![0.0]); - assert!(!s.warnings.iter().any(|w| w.contains("black level")), "{:?}", s.warnings); - } - - #[test] - fn truncated_container_never_panics() { - use crate::testgen::{Val, nef_compressed}; - let (w, h) = (32usize, 8usize); - let img = image(w, h, 16383, 2); - let src = encode(&img, w, &LOSSLESS_14, [[2048; 2]; 2]); - let b = nef_compressed(w, h, 14, src, [0, 1, 1, 2], true, vec![(0x0096, Val::Undefined(lossless_table(2048, false)))]); - for n in 0..b.len() { - let _ = crate::decode(&b[..n], &crate::Limits::default()); - } - } - - #[test] - fn truncated_and_corrupt_streams_error_never_panic() { - let (w, h) = (64, 16); - let table = lossless(14); - let img = image(w, h, 16383, 3); - let src = encode(&img, w, &LOSSLESS_14, table.seeds); - for cut in [0, 1, 10, src.len() / 2, src.len() - 40] { - assert!(decode(&src[..cut], w, h, 14, &table).is_err(), "cut {cut}"); - } - let mut s = 12345u32; - for i in 0..200 { - let mut bad = src.clone(); - for _ in 0..1 + i % 8 { - s = s.wrapping_mul(1_103_515_245).wrapping_add(12345); - let at = (s >> 8) as usize % bad.len(); - bad[at] ^= 1 << (s % 8); - } - let _ = decode(&bad, w, h, 14, &table); - let noise: Vec = (0..src.len()).map(|k| ((k as u32).wrapping_mul(2_654_435_761) >> (i % 24)) as u8).collect(); - let _ = decode(&noise, w, h, 14, &table); - let _ = decode(&noise, w, h, 12, &lossless(12)); - } - let lossy = parse_table(&lossy_table(12, false), false, 12).unwrap(); - assert!(decode(&[0xff; 64], 8, 8, 12, &lossy).is_err()); - assert!(decode(&src, usize::MAX, 2, 14, &table).is_err()); - assert!(decode(&src, 0, 2, 14, &table).is_err()); - } -} +mod tests; diff --git a/crates/raw/src/nefc/tests.rs b/crates/raw/src/nefc/tests.rs new file mode 100644 index 0000000000..296f850093 --- /dev/null +++ b/crates/raw/src/nefc/tests.rs @@ -0,0 +1,306 @@ +use super::*; + +/// MSB-first bit writer for the test encoder. +#[derive(Default)] +struct Writer { + out: Vec, + acc: u64, + n: u32, +} + +impl Writer { + fn put(&mut self, v: u32, len: u32) { + for i in (0..len).rev() { + self.acc = (self.acc << 1) | u64::from((v >> i) & 1); + self.n += 1; + if self.n == 8 { + self.out.push(self.acc as u8); + self.acc = 0; + self.n = 0; + } + } + } + fn finish(mut self) -> Vec { + if self.n > 0 { + self.out.push((self.acc << (8 - self.n)) as u8); + } + self.out.extend_from_slice(&[0; 4]); + self.out + } +} + +/// `(code, length)` per category, from the canonical table. +fn codes(t: &Table) -> Vec<(u32, u32)> { + let mut out = vec![(0, 0); 17]; + let mut code = 0u32; + let mut symbols = t.symbols.iter(); + for (i, &n) in t.counts.iter().enumerate() { + for _ in 0..n { + let s = *symbols.next().unwrap(); + if s != UNSEEN { + out[s as usize] = (code, i as u32 + 1); + } + code += 1; + } + code <<= 1; + } + out +} + +/// Encodes `values` (samples or curve indices) the way the camera does. +fn encode(values: &[i32], w: usize, t: &Table, seeds: [[i32; 2]; 2]) -> Vec { + let codes = codes(t); + let mut wr = Writer::default(); + let mut vpred = seeds; + for (y, row) in values.chunks(w).enumerate() { + for (x, &v) in row.iter().enumerate() { + let pred = if x < 2 { vpred[y & 1][x] } else { row[x - 2] }; + if x < 2 { + vpred[y & 1][x] = v; + } + let d = v - pred; + let k = 32 - d.unsigned_abs().leading_zeros(); + let (code, len) = codes[k as usize]; + assert!(len > 0, "no code for category {k}"); + wr.put(code, len); + wr.put(if d < 0 { (d + (1 << k) - 1) as u32 } else { d as u32 }, k); + } + } + wr.finish() +} + +/// Smooth gradient + texture + hard edges, within `0..=max`. +fn image(w: usize, h: usize, max: i32, seed: u32) -> Vec { + let mut s = seed; + (0..w * h) + .map(|i| { + let (x, y) = ((i % w) as i32, (i / w) as i32); + s = s.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + let noise = (s >> 24) as i32 % 9 - 4; + let base = (x * 37 + y * 11) % (max / 2) + if (x / 7 + y / 5) % 3 == 0 { max / 3 } else { 0 }; + (base + noise).clamp(0, max) + }) + .collect() +} + +fn lossless(bits: u32) -> DecodeTable { + let s = 1 << (bits - 3); + DecodeTable { encoding: Encoding::Lossless, seeds: [[s, s], [s, s]] } +} + +fn lossy_table(bits: u32, le: bool) -> Vec { + let mut t = vec![0x44, 0x20]; + let put = |t: &mut Vec, v: u16| t.extend_from_slice(&if le { v.to_le_bytes() } else { v.to_be_bytes() }); + for _ in 0..4 { + put(&mut t, 300); + } + put(&mut t, 257); + let max = f64::from((1u32 << bits) - 1); + for i in 0..257u32 { + put(&mut t, (max * (f64::from(i) / 64.0).min(1.0).sqrt()) as u16); + } + t.resize(624, 0); + t +} + +#[test] +fn tables_are_prefix_codes() { + for t in [LOSSLESS_12, LOSSLESS_14, LOSSY_12, LOSSY_14] { + assert_eq!(t.counts.iter().map(|&c| c as usize).sum::(), t.symbols.len()); + let kraft: f64 = t.counts.iter().enumerate().map(|(i, &c)| f64::from(c) / f64::from(1u32 << (i + 1))).sum(); + assert!(kraft <= 1.0); + assert!(Huffman::new(&t).is_ok()); + } +} + +#[test] +fn lossless_round_trip_12_and_14() { + for (bits, t) in [(12, LOSSLESS_12), (14, LOSSLESS_14)] { + let (w, h) = (64, 9); + let max = (1 << bits) - 1; + let mut img = image(w, h, max, bits); + img[5] = 0; + img[7] = max; + img[w + 9] = max; + let table = lossless(bits); + let out = decode(&encode(&img, w, &t, table.seeds), w, h, bits, &table).unwrap(); + assert_eq!(out, img.iter().map(|&v| v as u16).collect::>(), "{bits}-bit"); + } +} + +#[test] +fn lossy_type2_curve_and_round_trip() { + for (bits, t) in [(12u32, LOSSY_12), (14, LOSSY_14)] { + for le in [false, true] { + let table = parse_table(&lossy_table(bits, le), le, bits).unwrap(); + assert_eq!(table.seeds, [[300, 300], [300, 300]]); + let Encoding::Lossy(curve) = &table.encoding else { panic!() }; + let step = (1usize << bits) / 256; + assert_eq!(curve.len(), (1 << bits) + 1); + assert_eq!(curve[64 * step], (1 << bits) - 1); + assert!(curve.windows(2).all(|p| p[0] <= p[1])); + let (w, h) = (48, 7); + let img = image(w, h, 64 * step as i32 - 1, 7); + let out = decode(&encode(&img, w, &t, table.seeds), w, h, bits, &table).unwrap(); + assert_eq!(out, img.iter().map(|&v| curve[v as usize]).collect::>()); + } + } +} + +#[test] +fn lossy_type1_full_curve() { + let mut t = vec![0x44, 0x10, 0, 10, 0, 10, 0, 10, 0, 10, 0, 5]; + for v in [0u16, 100, 400, 900, 1600] { + t.extend_from_slice(&v.to_be_bytes()); + } + let table = parse_table(&t, false, 12).unwrap(); + assert_eq!(table.encoding, Encoding::Lossy(vec![0, 100, 400, 900, 1600])); + let img = vec![0, 4, 1, 3, 2, 2, 4, 0]; + assert_eq!(decode(&encode(&img, 4, &LOSSY_12, table.seeds), 4, 2, 12, &table).unwrap(), vec![0, 1600, 100, 900, 400, 400, 1600, 0]); +} + +#[test] +fn unsupported_and_malformed_tables() { + let unsupported = |r: Result| matches!(r, Err(RawError::Unsupported(_))); + let malformed = |r: Result| matches!(r, Err(RawError::Malformed(_))); + let mut split = lossy_table(12, false); + split[562..564].copy_from_slice(&345u16.to_be_bytes()); + assert!(unsupported(parse_table(&split, false, 12))); + assert!(unsupported(parse_table(&[0x49, 0x30, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], false, 12))); + assert!(unsupported(parse_table(&lossy_table(12, false), false, 16))); + assert!(malformed(parse_table(&[], false, 12))); + assert!(malformed(parse_table(&[0x46, 0x30, 8], false, 14))); + assert!(malformed(parse_table(&lossy_table(12, false)[..100], false, 12))); + let mut odd = lossy_table(12, false); + odd[10..12].copy_from_slice(&300u16.to_be_bytes()); + assert!(parse_table(&odd, false, 12).is_err()); + assert!(parse_table(&[0x44, 0x20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], false, 12).is_err()); +} + +#[test] +fn modern_lossy_curve_preserves_sensor_adus_at_both_depths() { + for bits in [12u32, 14] { + for le in [false, true] { + let put = |v: u16| if le { v.to_le_bytes() } else { v.to_be_bytes() }; + let mut t = vec![0x44, 0x40]; + for _ in 0..4 { + t.extend(put(256)); + } + t.extend(put(257)); + let white = (1u16 << bits) - 1; + for i in 0..=256u32 { + t.extend(put(((i * 64).min(u32::from(white))) as u16)); + } + t.resize(624, 0); + let parsed = parse_table(&t, le, bits).unwrap(); + let Encoding::Lossy(curve) = &parsed.encoding else { panic!() }; + let range = 1usize << (bits - 2); + assert_eq!(curve.len(), range + 1); + assert_eq!(curve[range], white); + // Stored point 16 is 1024 ADU. It belongs to encoded code 256 + // at 14 bits, code 64 at 12 bits, independent of end-point clipping. + assert_eq!(curve[range / 16], 1024.min(white)); + let indices = vec![0, (range / 16) as i32, (range / 8) as i32, (range / 32) as i32]; + let huffman = if bits == 12 { &LOSSY_12 } else { &LOSSY_14 }; + let src = encode(&indices, 2, huffman, parsed.seeds); + assert_eq!(decode(&src, 2, 2, bits, &parsed).unwrap(), vec![0, 1024, 2048, 512]); + } + } +} + +/// A 14-bit lossless table (version 0x46) with the given seeds. +fn lossless_table(seed: u16, le: bool) -> Vec { + let mut t = vec![0x46, 0x30]; + for _ in 0..4 { + t.extend_from_slice(&if le { seed.to_le_bytes() } else { seed.to_be_bytes() }); + } + t.resize(46, 0); + t +} + +#[test] +fn decodes_through_the_nef_container() { + use crate::testgen::{Val, nef_compressed}; + use crate::{Limits, RawFormat, identify}; + let (w, h) = (40usize, 6usize); + // lossless 14-bit, big-endian maker note, with a BlackLevel tag + let img = image(w, h, 16383, 11); + let src = encode(&img, w, &LOSSLESS_14, [[2048; 2]; 2]); + let note = vec![(0x0096, Val::Undefined(lossless_table(2048, false))), (0x003d, Val::Short(vec![600, 600, 600, 600]))]; + let b = nef_compressed(w, h, 14, src, [0, 1, 1, 2], true, note); + assert_eq!(identify(&b), Some(RawFormat::Nef)); + let s = crate::decode(&b, &Limits::default()).unwrap(); + assert_eq!(s.data, img.iter().map(|&v| v as u16).collect::>()); + assert_eq!(s.black.values, vec![600.0; 4]); + // lossy 12-bit type 2, little-endian maker note (newer bodies); the + // 12-bit BlackLevel is scaled from 14-bit units + let table = lossy_table(12, true); + let t = parse_table(&table, true, 12).unwrap(); + let Encoding::Lossy(curve) = &t.encoding else { panic!() }; + let img = image(w, h, 1023, 5); + let src = encode(&img, w, &LOSSY_12, t.seeds); + let note = vec![(0x0096, Val::Undefined(table.clone())), (0x003d, Val::Short(vec![600, 600, 600, 600]))]; + let s = crate::decode(&nef_compressed(w, h, 12, src.clone(), [2, 1, 1, 0], false, note), &Limits::default()).unwrap(); + assert_eq!(s.data, img.iter().map(|&v| curve[v as usize]).collect::>()); + assert_eq!(s.black.values, vec![150.0; 4]); + assert!(crate::develop_sensor(&s, &crate::DevelopOptions::default()).is_ok()); + // "lossy after split" and a missing table stay unsupported (preview fallback) + let mut split = table; + split[562..564].copy_from_slice(&3u16.to_le_bytes()); + let e = crate::decode(&nef_compressed(w, h, 12, src.clone(), [2, 1, 1, 0], false, vec![(0x0096, Val::Undefined(split))]), &Limits::default()); + assert!(matches!(e, Err(RawError::Unsupported(_))), "{e:?}"); + let e = crate::decode(&nef_compressed(w, h, 12, src, [2, 1, 1, 0], false, vec![(0x0001, Val::Short(vec![0]))]), &Limits::default()); + assert!(matches!(&e, Err(RawError::Unsupported(m)) if m.contains("Nikon compressed NEF")), "{e:?}"); +} + +#[test] +fn nikon_without_black_level_tag_is_black_subtracted() { + use crate::testgen::{Val, nef_compressed}; + let (w, h) = (32usize, 8usize); + let img = image(w, h, 16383, 4); + let src = encode(&img, w, &LOSSLESS_14, [[2048; 2]; 2]); + let b = nef_compressed(w, h, 14, src, [0, 1, 1, 2], true, vec![(0x0096, Val::Undefined(lossless_table(2048, false)))]); + let s = crate::decode(&b, &crate::Limits::default()).unwrap(); + assert_eq!(s.black.values, vec![0.0]); + assert!(!s.warnings.iter().any(|w| w.contains("black level")), "{:?}", s.warnings); +} + +#[test] +fn truncated_container_never_panics() { + use crate::testgen::{Val, nef_compressed}; + let (w, h) = (32usize, 8usize); + let img = image(w, h, 16383, 2); + let src = encode(&img, w, &LOSSLESS_14, [[2048; 2]; 2]); + let b = nef_compressed(w, h, 14, src, [0, 1, 1, 2], true, vec![(0x0096, Val::Undefined(lossless_table(2048, false)))]); + for n in 0..b.len() { + let _ = crate::decode(&b[..n], &crate::Limits::default()); + } +} + +#[test] +fn truncated_and_corrupt_streams_error_never_panic() { + let (w, h) = (64, 16); + let table = lossless(14); + let img = image(w, h, 16383, 3); + let src = encode(&img, w, &LOSSLESS_14, table.seeds); + for cut in [0, 1, 10, src.len() / 2, src.len() - 40] { + assert!(decode(&src[..cut], w, h, 14, &table).is_err(), "cut {cut}"); + } + let mut s = 12345u32; + for i in 0..200 { + let mut bad = src.clone(); + for _ in 0..1 + i % 8 { + s = s.wrapping_mul(1_103_515_245).wrapping_add(12345); + let at = (s >> 8) as usize % bad.len(); + bad[at] ^= 1 << (s % 8); + } + let _ = decode(&bad, w, h, 14, &table); + let noise: Vec = (0..src.len()).map(|k| ((k as u32).wrapping_mul(2_654_435_761) >> (i % 24)) as u8).collect(); + let _ = decode(&noise, w, h, 14, &table); + let _ = decode(&noise, w, h, 12, &lossless(12)); + } + let lossy = parse_table(&lossy_table(12, false), false, 12).unwrap(); + assert!(decode(&[0xff; 64], 8, 8, 12, &lossy).is_err()); + assert!(decode(&src, usize::MAX, 2, 14, &table).is_err()); + assert!(decode(&src, 0, 2, 14, &table).is_err()); +} diff --git a/crates/raw/src/testgen.rs b/crates/raw/src/testgen.rs index 02ea402161..b5df57e3c0 100644 --- a/crates/raw/src/testgen.rs +++ b/crates/raw/src/testgen.rs @@ -7,6 +7,22 @@ // ---------------------------------------------------------------- lossless JPEG +mod canon; +mod dng; +mod lj92; +mod orf; +mod raf; +mod rw2; +mod tiff; + +pub use canon::{Cr2Spec, craw_block, craw_encode, nef_compressed, sony_craw, tiff_ep}; +pub use dng::{DngSpec, DngStorage, baseline_jpeg, gain_map_opcode_list, map_polynomial_opcode_list}; +pub use lj92::{lj92_encode, lj92_encode_tables}; +pub use orf::orf; +pub use raf::{RafPacking, RafSpec, XTRANS, mosaic, mosaic_cfa, scene}; +pub use rw2::{rw2, rw2_format4, rw2_pack, rw2_v4_pack}; +pub use tiff::{TiffBuilder, Val}; + /// A CR3 container holding one JPEG track and CMT1 orientation. It deliberately /// contains no CRX data: used to test explicit preview fallback and BMFF bounds. pub fn cr3_preview(jpeg: &[u8], orientation: u16) -> Vec { @@ -41,1662 +57,3 @@ pub fn cr3_preview(jpeg: &[u8], orientation: u16) -> Vec { let offset = ftyp.len() + header.len() + 8; [ftyp, moov(jpeg.len(), offset as u64, orientation), bx(b"mdat", jpeg)].concat() } - -/// Huffman code lengths assigned to categories in decreasing frequency -/// order. Kraft sum < 1 and no code is all ones. -const LENGTHS: [u8; 17] = [2, 3, 3, 3, 4, 4, 5, 5, 6, 6, 7, 8, 9, 10, 11, 12, 13]; - -fn category(d: i32) -> u32 { - if d == 0 { - 0 - } else if d == 32768 { - 16 - } else { - 32 - d.unsigned_abs().leading_zeros() - } -} - -struct BitWriter { - out: Vec, - acc: u32, - n: u32, -} - -impl BitWriter { - fn put(&mut self, v: u32, bits: u32) { - for i in (0..bits).rev() { - self.acc = (self.acc << 1) | ((v >> i) & 1); - self.n += 1; - if self.n == 8 { - let b = self.acc as u8; - self.out.push(b); - if b == 0xFF { - self.out.push(0); - } - self.acc = 0; - self.n = 0; - } - } - } - fn flush(&mut self) { - if self.n > 0 { - let pad = 8 - self.n; - self.put((1 << pad) - 1, pad); - } - } -} - -/// Encodes `samples` (raster order, `components` interleaved, values below -/// `2^precision`) as a lossless JPEG with the given predictor (1–7) and an -/// optional restart interval in rows. All components share one Huffman table. -pub fn lj92_encode(samples: &[u16], width: usize, height: usize, components: usize, precision: u8, predictor: u8, restart_rows: Option) -> Vec { - lj92_encode_tables(samples, width, height, &vec![0; components], precision, predictor, restart_rows) -} - -/// Like [`lj92_encode`], but component `c` uses Huffman table `table_of[c]` -/// (0–3; the component count is `table_of.len()`), one DHT per table id as -/// CR2 writes them. Table `t` assigns its code lengths rotated by `t`, so the -/// tables differ even when their statistics match. -pub fn lj92_encode_tables(samples: &[u16], width: usize, height: usize, table_of: &[u8], precision: u8, predictor: u8, restart_rows: Option) -> Vec { - let components = table_of.len(); - assert_eq!(samples.len(), width * height * components); - assert!(table_of.iter().all(|&t| t < 4)); - let row = width * components; - let interval = restart_rows.unwrap_or(usize::MAX); - // Differences per sample, following T.81 H.1.2.1 prediction rules. - let mut diffs = Vec::with_capacity(samples.len()); - let initial = 1i32 << (precision - 1); - for y in 0..height { - let first_line = y % interval == 0; - for x in 0..width { - for c in 0..components { - let i = y * row + x * components + c; - let px = if x == 0 { - if first_line { initial } else { i32::from(samples[i - row]) } - } else if first_line { - i32::from(samples[i - components]) - } else { - let ra = i32::from(samples[i - components]); - let rb = i32::from(samples[i - row]); - let rc = i32::from(samples[i - row - components]); - match predictor { - 1 => ra, - 2 => rb, - 3 => rc, - 4 => ra + rb - rc, - 5 => ra + ((rb - rc) >> 1), - 6 => rb + ((ra - rc) >> 1), - _ => (ra + rb) >> 1, - } - }; - let mut d = (i32::from(samples[i]) - px) & 0xFFFF; - if d > 32768 { - d -= 65536; - } - diffs.push(d); - } - } - } - // Tables: categories ordered by frequency get increasing code lengths. - let mut ids: Vec = table_of.to_vec(); - ids.sort_unstable(); - ids.dedup(); - let mut code_of = [[(0u32, 0u32); 17]; 4]; - let mut dhts = Vec::new(); - for &t in &ids { - let mut freq = [0usize; 17]; - for (i, &d) in diffs.iter().enumerate() { - if table_of[i % components] == t { - freq[category(d) as usize] += 1; - } - } - let mut order: Vec = (0..17).collect(); - order.sort_by_key(|&c| std::cmp::Reverse(freq[c])); - order.rotate_left(usize::from(t)); - let mut len_of = [0u8; 17]; - for (rank, &c) in order.iter().enumerate() { - len_of[c] = LENGTHS[rank]; - } - let mut counts = [0u8; 16]; - let mut vals: Vec = Vec::new(); - let mut code = 0u32; - for len in 1..=16u8 { - for c in 0..17 { - if len_of[c] == len { - counts[len as usize - 1] += 1; - vals.push(c as u8); - code_of[usize::from(t)][c] = (code, u32::from(len)); - code += 1; - } - } - code <<= 1; - } - dhts.push((t, counts, vals)); - } - let mut out = vec![0xFF, 0xD8]; - // SOF3 - out.extend_from_slice(&[0xFF, 0xC3]); - out.extend_from_slice(&((8 + 3 * components) as u16).to_be_bytes()); - out.push(precision); - out.extend_from_slice(&(height as u16).to_be_bytes()); - out.extend_from_slice(&(width as u16).to_be_bytes()); - out.push(components as u8); - for c in 0..components { - out.extend_from_slice(&[c as u8 + 1, 0x11, 0]); - } - // DHT, one per table id - for (t, counts, vals) in &dhts { - out.extend_from_slice(&[0xFF, 0xC4]); - out.extend_from_slice(&((2 + 17 + vals.len()) as u16).to_be_bytes()); - out.push(*t); - out.extend_from_slice(counts); - out.extend_from_slice(vals); - } - if let Some(r) = restart_rows { - out.extend_from_slice(&[0xFF, 0xDD, 0, 4]); - out.extend_from_slice(&((r * width) as u16).to_be_bytes()); - } - // SOS - out.extend_from_slice(&[0xFF, 0xDA]); - out.extend_from_slice(&((6 + 2 * components) as u16).to_be_bytes()); - out.push(components as u8); - for (c, &t) in table_of.iter().enumerate() { - out.extend_from_slice(&[c as u8 + 1, t << 4]); - } - out.extend_from_slice(&[predictor, 0, 0]); - let mut w = BitWriter { out, acc: 0, n: 0 }; - let mut rst = 0u8; - for (i, &d) in diffs.iter().enumerate() { - if i > 0 && i % (interval.saturating_mul(row)) == 0 { - w.flush(); - w.out.extend_from_slice(&[0xFF, 0xD0 + rst]); - rst = (rst + 1) % 8; - } - let s = category(d); - let (c, l) = code_of[usize::from(table_of[i % components])][s as usize]; - w.put(c, l); - if (1..16).contains(&s) { - let extra = if d < 0 { (d - 1) as u32 & ((1 << s) - 1) } else { d as u32 }; - w.put(extra, s); - } - } - w.flush(); - let mut out = w.out; - out.extend_from_slice(&[0xFF, 0xD9]); - out -} - -// ---------------------------------------------------------------- TIFF writer - -/// A TIFF entry value. -#[derive(Debug, Clone)] -pub enum Val { - Byte(Vec), - Ascii(String), - Short(Vec), - Long(Vec), - Double(Vec), - Rational(Vec<(u32, u32)>), - SRational(Vec<(i32, i32)>), - Undefined(Vec), - /// Offsets of these blobs (LONG). - Blobs(Vec), - /// Offsets of these IFDs (LONG), for SubIFDs / EXIF. - Ifds(Vec), - /// An UNDEFINED value whose bytes are this IFD (a maker note). - IfdBytes(usize), -} - -/// A TIFF file under construction. -#[derive(Debug, Clone, Default)] -pub struct TiffBuilder { - pub big_endian: bool, - /// Entries per IFD (sorted by tag on write). - pub ifds: Vec>, - /// The main IFD chain, by index into `ifds`. - pub chain: Vec, - pub blobs: Vec>, - /// Write a CR2 header pointing at this IFD as the raw IFD. - pub cr2_raw_ifd: Option, -} - -impl TiffBuilder { - pub fn ifd(&mut self, entries: Vec<(u16, Val)>) -> usize { - self.ifds.push(entries); - self.ifds.len() - 1 - } - - pub fn blob(&mut self, data: Vec) -> usize { - self.blobs.push(data); - self.blobs.len() - 1 - } - - fn val_size(&self, v: &Val) -> usize { - match v { - Val::Byte(b) | Val::Undefined(b) => b.len(), - Val::Ascii(s) => s.len() + 1, - Val::Short(s) => 2 * s.len(), - Val::Long(l) => 4 * l.len(), - Val::Double(d) => 8 * d.len(), - Val::Rational(r) => 8 * r.len(), - Val::SRational(r) => 8 * r.len(), - Val::Blobs(b) => 4 * b.len(), - Val::Ifds(i) => 4 * i.len(), - Val::IfdBytes(i) => self.ifd_size(*i), - } - } - - fn ifd_size(&self, i: usize) -> usize { - 2 + 12 * self.ifds[i].len() + 4 - } - - pub fn build(&self) -> Vec { - let header = if self.cr2_raw_ifd.is_some() { 16 } else { 8 }; - // Layout: each IFD, then its overflow values; then the blobs. - let mut pos = header; - let mut ifd_pos = vec![0usize; self.ifds.len()]; - let mut val_pos: Vec> = vec![Vec::new(); self.ifds.len()]; - // Maker-note IFDs are written inside their owner's value area. - let embedded: Vec = self.ifds.iter().flatten().filter_map(|(_, v)| if let Val::IfdBytes(i) = v { Some(*i) } else { None }).collect(); - for i in 0..self.ifds.len() { - if embedded.contains(&i) { - continue; - } - ifd_pos[i] = pos; - pos += self.ifd_size(i); - let mut vp = Vec::new(); - for (_, v) in self.sorted(i) { - let size = self.val_size(&v); - if size > 4 { - vp.push(pos); - if let Val::IfdBytes(e) = v { - ifd_pos[e] = pos; - // The embedded IFD's own values follow it. - let inner = pos + self.ifd_size(e); - let mut ip = Vec::new(); - let mut q = inner; - for (_, iv) in self.sorted(e) { - let s = self.val_size(&iv); - if s > 4 { - ip.push(q); - q += s + (s & 1); - } else { - ip.push(0); - } - } - val_pos[e] = ip; - pos = q; - } else { - pos += size + (size & 1); - } - } else { - vp.push(0); - } - } - val_pos[i] = vp; - } - let mut blob_pos = Vec::new(); - for b in &self.blobs { - blob_pos.push(pos); - pos += b.len() + (b.len() & 1); - } - let mut out = vec![0u8; pos]; - let be = self.big_endian; - let w16 = |o: &mut [u8], at: usize, v: u16| o[at..at + 2].copy_from_slice(&if be { v.to_be_bytes() } else { v.to_le_bytes() }); - let w32 = |o: &mut [u8], at: usize, v: u32| o[at..at + 4].copy_from_slice(&if be { v.to_be_bytes() } else { v.to_le_bytes() }); - out[0..4].copy_from_slice(if be { b"MM\0*" } else { b"II*\0" }); - w32(&mut out, 4, ifd_pos[self.chain[0]] as u32); - if let Some(r) = self.cr2_raw_ifd { - out[8..12].copy_from_slice(b"CR\x02\0"); - w32(&mut out, 12, ifd_pos[r] as u32); - } - for i in 0..self.ifds.len() { - let at = ifd_pos[i]; - let entries = self.sorted(i); - w16(&mut out, at, entries.len() as u16); - for (k, (tag, v)) in entries.iter().enumerate() { - let e = at + 2 + 12 * k; - let (typ, count, bytes) = self.encode(v, &blob_pos, &ifd_pos); - w16(&mut out, e, *tag); - w16(&mut out, e + 2, typ); - w32(&mut out, e + 4, count); - if bytes.len() <= 4 { - out[e + 8..e + 8 + bytes.len()].copy_from_slice(&bytes); - } else { - let vp = val_pos[i][k]; - w32(&mut out, e + 8, vp as u32); - if !matches!(v, Val::IfdBytes(_)) { - out[vp..vp + bytes.len()].copy_from_slice(&bytes); - } - } - } - let next = self.chain.iter().position(|&c| c == i).and_then(|p| self.chain.get(p + 1)).map(|&n| ifd_pos[n]).unwrap_or(0); - w32(&mut out, at + 2 + 12 * entries.len(), next as u32); - } - for (b, &p) in self.blobs.iter().zip(&blob_pos) { - out[p..p + b.len()].copy_from_slice(b); - } - out - } - - fn sorted(&self, i: usize) -> Vec<(u16, Val)> { - let mut e = self.ifds[i].clone(); - e.sort_by_key(|(t, _)| *t); - e - } - - fn encode(&self, v: &Val, blob_pos: &[usize], ifd_pos: &[usize]) -> (u16, u32, Vec) { - let be = self.big_endian; - let b16 = |v: u16| if be { v.to_be_bytes() } else { v.to_le_bytes() }; - let b32 = |v: u32| if be { v.to_be_bytes() } else { v.to_le_bytes() }; - let b64 = |v: u64| if be { v.to_be_bytes() } else { v.to_le_bytes() }; - match v { - Val::Byte(b) => (1, b.len() as u32, b.clone()), - Val::Undefined(b) => (7, b.len() as u32, b.clone()), - Val::Ascii(s) => { - let mut b = s.as_bytes().to_vec(); - b.push(0); - (2, b.len() as u32, b) - } - Val::Short(s) => (3, s.len() as u32, s.iter().flat_map(|&v| b16(v)).collect()), - Val::Long(l) => (4, l.len() as u32, l.iter().flat_map(|&v| b32(v)).collect()), - Val::Double(d) => (12, d.len() as u32, d.iter().flat_map(|v| b64(v.to_bits())).collect()), - Val::Rational(r) => (5, r.len() as u32, r.iter().flat_map(|&(n, d)| [b32(n), b32(d)].concat()).collect()), - Val::SRational(r) => (10, r.len() as u32, r.iter().flat_map(|&(n, d)| [b32(n as u32), b32(d as u32)].concat()).collect()), - Val::Blobs(b) => (4, b.len() as u32, b.iter().flat_map(|&i| b32(blob_pos[i] as u32)).collect()), - Val::Ifds(i) => (4, i.len() as u32, i.iter().flat_map(|&k| b32(ifd_pos[k] as u32)).collect()), - Val::IfdBytes(i) => (7, self.ifd_size(*i) as u32, vec![0; 8]), - } - } -} - -fn srat(v: f64) -> (i32, i32) { - ((v * 10000.0).round() as i32, 10000) -} - -fn urat(v: f64) -> (u32, u32) { - ((v * 10000.0).round() as u32, 10000) -} - -// ---------------------------------------------------------------- DNG - -/// Encodes 8-bit samples (1 gray or 3 RGB per pixel, row-major) as a baseline JPEG at -/// quality 60, the way a lossy DNG segment is stored (an RGB segment is coded as YCbCr). -pub fn baseline_jpeg(samples: &[u8], width: usize, height: usize, per_pixel: usize) -> Vec { - use image::ImageEncoder as _; - let colour = if per_pixel == 3 { image::ExtendedColorType::Rgb8 } else { image::ExtendedColorType::L8 }; - let mut j = Vec::new(); - let enc = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut j, 60); - enc.write_image(samples, width as u32, height as u32, colour).expect("jpeg segment"); - j -} - -/// How the DNG stores its raw data. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum DngStorage { - /// One strip per `rows` rows, uncompressed at `bits` per sample (8, 12, 16…). - Strips { rows: usize }, - /// Adobe DNG compression 34892: baseline JPEG tiles at tile size (edge tiles padded), one - /// gray component for CFA and monochrome data, three (YCbCr-coded RGB) for LinearRaw. The - /// spec's `bits` should be 8 (the DNG spec's depth for lossy JPEG; the reader rejects others); - /// wider samples are written as their top 8 bits. Quality 60 leaves visible-but-mild artifacts. - LossyJpegTiles { width: usize, height: usize }, - /// Adobe DNG compression 34892 in strips of this many rows: each strip is a baseline JPEG - /// of the image width by the strip's own row count (the last strip is shorter). - LossyJpegStrips { rows: usize }, - /// Adobe DNG compression 8: zlib streams with the TIFF predictor (1 = none, 2 = horizontal - /// differencing) applied before compressing. - DeflateStrips { rows: usize, predictor: u16 }, - /// Lossless-JPEG tiles of this size (2 components per JPEG row, as Adobe writes CFA tiles). - Lj92Tiles { width: usize, height: usize }, - /// Lossless-JPEG strips of this many rows, 1 component. - Lj92Strips { rows: usize }, - /// JPEG XL strips of this many rows (Compression 52546): one codestream per strip, taken from - /// [`DngSpec::jxl_segments`] (the tests encode them; this crate has no JPEG XL encoder). - JxlStrips { rows: usize }, - /// JPEG XL tiles of this size, one codestream per tile in row-major order from - /// [`DngSpec::jxl_segments`]. - JxlTiles { width: usize, height: usize }, -} - -/// A synthetic DNG. -#[derive(Debug, Clone)] -pub struct DngSpec { - pub width: usize, - pub height: usize, - /// 1 (CFA, or monochrome LinearRaw with `monochrome`) or 3 (LinearRaw). - pub samples: usize, - /// With `samples` 1: a monochrome LinearRaw image (no CFA tags) instead of CFA data. - pub monochrome: bool, - /// Row-major samples (`width * height * samples`). - pub data: Vec, - pub bits: u16, - pub cfa: [u8; 4], - pub storage: DngStorage, - pub big_endian: bool, - pub black: Vec, - pub black_repeat: (u16, u16), - /// WhiteLevel; 0 leaves the tag out (the reader then defaults to the bit depth's maximum). - pub white: u32, - /// top, left, bottom, right - pub active_area: Option<[u32; 4]>, - /// origin (x, y), size (w, h), relative to the active area - pub default_crop: Option<([u32; 2], [u32; 2])>, - /// Double-precision origin override for malformed-metadata regression tests. - pub default_crop_origin_double: Option<[f64; 2]>, - /// A DefaultCropSize with no DefaultCropOrigin (`default_crop` must be `None`). - pub default_crop_size_only: Option<[u32; 2]>, - pub linearization: Option>, - /// (illuminant code, ColorMatrix row-major) - pub color_matrix1: Option<(u16, [f64; 9])>, - pub color_matrix2: Option<(u16, [f64; 9])>, - pub forward_matrix1: Option<[f64; 9]>, - pub forward_matrix2: Option<[f64; 9]>, - pub as_shot_neutral: Option<[f64; 3]>, - pub baseline_exposure: Option, - /// Raw OpcodeList2 bytes (see [`gain_map_opcode_list`]). - pub opcode_list2: Option>, - /// Encoded segments for [`DngStorage::JxlStrips`] / [`DngStorage::JxlTiles`]. - pub jxl_segments: Vec>, - /// Pre-encoded segments for [`DngStorage::LossyJpegTiles`] / [`DngStorage::LossyJpegStrips`] - /// (row-major), used instead of encoding `data` where present: for tiles that disagree with - /// the IFD (hostile-input tests). - pub lossy_segments: Vec>, - /// Raw ProfileGainTableMap bytes, written to IFD0 (contents are not interpreted). - pub profile_gain_table_map: Option>, - pub orientation: u16, - pub make: String, - pub model: String, - /// Extra IFD0 entries, written after the generated ones (e.g. malformed colour tags). - pub ifd0_extra: Vec<(u16, Val)>, - /// Extra raw-IFD entries, written after the generated ones (e.g. SampleFormat). - pub raw_extra: Vec<(u16, Val)>, -} - -impl DngSpec { - /// A CFA DNG with default metadata around `data` (RGGB, 16-bit, one strip). - pub fn cfa(width: usize, height: usize, data: Vec) -> Self { - DngSpec { - width, - height, - samples: 1, - monochrome: false, - data, - bits: 16, - cfa: [0, 1, 1, 2], - storage: DngStorage::Strips { rows: height }, - big_endian: false, - black: vec![0], - black_repeat: (1, 1), - white: 65535, - active_area: None, - default_crop: None, - default_crop_origin_double: None, - default_crop_size_only: None, - linearization: None, - color_matrix1: None, - color_matrix2: None, - forward_matrix1: None, - forward_matrix2: None, - as_shot_neutral: None, - baseline_exposure: None, - orientation: 1, - opcode_list2: None, - jxl_segments: Vec::new(), - lossy_segments: Vec::new(), - profile_gain_table_map: None, - make: "Photocraft".into(), - model: "Synthetic".into(), - ifd0_extra: Vec::new(), - raw_extra: Vec::new(), - } - } - - /// A monochrome (one-sample LinearRaw) DNG around `data`, as monochrome cameras and film - /// scanners write them: no CFA tags and no colour matrices. - pub fn monochrome(width: usize, height: usize, data: Vec) -> Self { - DngSpec { monochrome: true, ..Self::cfa(width, height, data) } - } - - fn is_cfa(&self) -> bool { - self.samples == 1 && !self.monochrome - } - - /// The 8-bit sample a lossy JPEG segment stores for `v`: the value itself at 8 bits, else - /// its top 8 bits. - fn sample8(&self, v: u16) -> u8 { - (v >> self.bits.saturating_sub(8)) as u8 - } - - fn pack(&self, rows: std::ops::Range) -> Vec { - let n = self.width * self.samples; - let vals = &self.data[rows.start * n..rows.end * n]; - match self.bits { - 8 => vals.iter().map(|&v| v as u8).collect(), - 16 => vals.iter().flat_map(|&v| if self.big_endian { v.to_be_bytes() } else { v.to_le_bytes() }).collect(), - b => { - // MSB-first bit packing, each row padded to a byte. - let mut out = Vec::new(); - for row in vals.chunks(n) { - let mut acc: u64 = 0; - let mut have = 0u32; - for &v in row { - acc = (acc << b) | u64::from(v); - have += u32::from(b); - while have >= 8 { - have -= 8; - out.push((acc >> have) as u8); - } - } - if have > 0 { - out.push((acc << (8 - have)) as u8); - } - } - out - } - } - } - - pub fn build(&self) -> Vec { - let mut t = TiffBuilder { big_endian: self.big_endian, ..Default::default() }; - let mut raw: Vec<(u16, Val)> = vec![ - (254, Val::Long(vec![0])), - (256, Val::Long(vec![self.width as u32])), - (257, Val::Long(vec![self.height as u32])), - (258, Val::Short(vec![self.bits; self.samples])), - (262, Val::Short(vec![if self.is_cfa() { 32803 } else { 34892 }])), - (277, Val::Short(vec![self.samples as u16])), - (284, Val::Short(vec![1])), - (50713, Val::Short(vec![self.black_repeat.0, self.black_repeat.1])), - (50714, Val::Long(self.black.clone())), - ]; - if self.white != 0 { - raw.push((50717, Val::Long(vec![self.white; self.samples]))); - } - if self.is_cfa() { - raw.push((33421, Val::Short(vec![2, 2]))); - raw.push((33422, Val::Byte(self.cfa.to_vec()))); - raw.push((50710, Val::Byte(vec![0, 1, 2]))); - raw.push((50711, Val::Short(vec![1]))); - } - match self.storage { - DngStorage::DeflateStrips { rows, predictor } => { - use std::io::Write; - let mut offs = Vec::new(); - let mut lens = Vec::new(); - for y in (0..self.height).step_by(rows) { - let r = (y + rows).min(self.height) - y; - let n = self.width * self.samples; - let mut v: Vec = self.data[y * n..(y + r) * n].to_vec(); - if predictor == 2 { - // Horizontal differencing on the sample values, before byte packing - // (the reader undoes predictor after unpacking, per row, per channel). - let plane = if self.samples.is_multiple_of(3) { 3 } else { 1 }; - for row in v.chunks_mut(n) { - for i in (plane..row.len()).rev() { - row[i] = row[i].wrapping_sub(row[i - plane]); - } - } - } - // Pack the delta'd values with the file's byte order and bit depth. - let bytes: Vec = match self.bits { - 8 => v.iter().map(|&x| x as u8).collect(), - 16 => v.iter().flat_map(|&x| if self.big_endian { x.to_be_bytes() } else { x.to_le_bytes() }).collect(), - _ => v.iter().flat_map(|x| x.to_le_bytes()).collect(), - }; - let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default()); - e.write_all(&bytes).expect("zlib"); - let z = e.finish().expect("zlib"); - lens.push(z.len() as u32); - offs.push(t.blob(z)); - } - raw.push((259, Val::Short(vec![8]))); - raw.push((317, Val::Short(vec![predictor]))); - raw.push((278, Val::Long(vec![rows as u32]))); - raw.push((273, Val::Blobs(offs))); - raw.push((279, Val::Long(lens))); - } - DngStorage::Strips { rows } => { - let mut offs = Vec::new(); - let mut lens = Vec::new(); - for y in (0..self.height).step_by(rows) { - let b = self.pack(y..(y + rows).min(self.height)); - lens.push(b.len() as u32); - offs.push(t.blob(b)); - } - raw.push((259, Val::Short(vec![1]))); - raw.push((278, Val::Long(vec![rows as u32]))); - raw.push((273, Val::Blobs(offs))); - raw.push((279, Val::Long(lens))); - } - DngStorage::LossyJpegTiles { width: tw, height: th } => { - let mut offs = Vec::new(); - let mut lens = Vec::new(); - let s = self.samples; - for ty in (0..self.height).step_by(th) { - for tx in (0..self.width).step_by(tw) { - // Edge tiles are padded by repeating the last row / column. - let mut tile = vec![0u8; tw * th * s]; - for y in 0..th { - for x in 0..tw { - let sy = (ty + y).min(self.height - 1); - let sx = (tx + x).min(self.width - 1); - for c in 0..s { - tile[(y * tw + x) * s + c] = self.sample8(self.data[(sy * self.width + sx) * s + c]); - } - } - } - let j = self.lossy_segments.get(offs.len()).cloned().unwrap_or_else(|| baseline_jpeg(&tile, tw, th, s)); - lens.push(j.len() as u32); - offs.push(t.blob(j)); - } - } - raw.push((259, Val::Short(vec![34892]))); - raw.push((322, Val::Long(vec![tw as u32]))); - raw.push((323, Val::Long(vec![th as u32]))); - raw.push((324, Val::Blobs(offs))); - raw.push((325, Val::Long(lens))); - } - DngStorage::LossyJpegStrips { rows } => { - let mut offs = Vec::new(); - let mut lens = Vec::new(); - let n = self.width * self.samples; - for y in (0..self.height).step_by(rows) { - let r = (y + rows).min(self.height) - y; - let strip: Vec = self.data[y * n..(y + r) * n].iter().map(|&v| self.sample8(v)).collect(); - let j = self.lossy_segments.get(offs.len()).cloned().unwrap_or_else(|| baseline_jpeg(&strip, self.width, r, self.samples)); - lens.push(j.len() as u32); - offs.push(t.blob(j)); - } - raw.push((259, Val::Short(vec![34892]))); - raw.push((278, Val::Long(vec![rows as u32]))); - raw.push((273, Val::Blobs(offs))); - raw.push((279, Val::Long(lens))); - } - DngStorage::Lj92Strips { rows } => { - let mut offs = Vec::new(); - let mut lens = Vec::new(); - for y in (0..self.height).step_by(rows) { - let r = (y + rows).min(self.height) - y; - let n = self.width * self.samples; - let j = lj92_encode(&self.data[y * n..(y + r) * n], self.width, r, self.samples, self.bits as u8, 1, None); - lens.push(j.len() as u32); - offs.push(t.blob(j)); - } - raw.push((259, Val::Short(vec![7]))); - raw.push((278, Val::Long(vec![rows as u32]))); - raw.push((273, Val::Blobs(offs))); - raw.push((279, Val::Long(lens))); - } - DngStorage::Lj92Tiles { width: tw, height: th } => { - let mut offs = Vec::new(); - let mut lens = Vec::new(); - let s = self.samples; - for ty in (0..self.height).step_by(th) { - for tx in (0..self.width).step_by(tw) { - // Edge tiles are padded by repeating the last row / column. - let mut tile = vec![0u16; tw * th * s]; - for y in 0..th { - for x in 0..tw { - let sy = (ty + y).min(self.height - 1); - let sx = (tx + x).min(self.width - 1); - for c in 0..s { - tile[(y * tw + x) * s + c] = self.data[(sy * self.width + sx) * s + c]; - } - } - } - // CFA tiles as Adobe writes them: half width, 2 components. - let j = if s == 1 && tw % 2 == 0 { - lj92_encode(&tile, tw / 2, th, 2, self.bits as u8, 1, None) - } else { - lj92_encode(&tile, tw, th, s, self.bits as u8, 1, None) - }; - lens.push(j.len() as u32); - offs.push(t.blob(j)); - } - } - raw.push((259, Val::Short(vec![7]))); - raw.push((322, Val::Long(vec![tw as u32]))); - raw.push((323, Val::Long(vec![th as u32]))); - raw.push((324, Val::Blobs(offs))); - raw.push((325, Val::Long(lens))); - } - DngStorage::JxlStrips { rows } => { - let lens = self.jxl_segments.iter().map(|j| j.len() as u32).collect(); - let offs = self.jxl_segments.iter().map(|j| t.blob(j.clone())).collect(); - raw.push((259, Val::Short(vec![52546]))); - raw.push((278, Val::Long(vec![rows as u32]))); - raw.push((273, Val::Blobs(offs))); - raw.push((279, Val::Long(lens))); - } - DngStorage::JxlTiles { width: tw, height: th } => { - let lens = self.jxl_segments.iter().map(|j| j.len() as u32).collect(); - let offs = self.jxl_segments.iter().map(|j| t.blob(j.clone())).collect(); - raw.push((259, Val::Short(vec![52546]))); - raw.push((322, Val::Long(vec![tw as u32]))); - raw.push((323, Val::Long(vec![th as u32]))); - raw.push((324, Val::Blobs(offs))); - raw.push((325, Val::Long(lens))); - } - } - if let Some(a) = self.active_area { - raw.push((50829, Val::Long(a.to_vec()))); - } - if let Some((o, s)) = self.default_crop { - let origin = self.default_crop_origin_double.map(|d| Val::Double(d.to_vec())).unwrap_or_else(|| Val::Long(o.to_vec())); - raw.push((50719, origin)); - raw.push((50720, Val::Long(s.to_vec()))); - } else if let Some(origin) = self.default_crop_origin_double { - raw.push((50719, Val::Double(origin.to_vec()))); - } else if let Some(size) = self.default_crop_size_only { - raw.push((50720, Val::Long(size.to_vec()))); - } - if let Some(o) = &self.opcode_list2 { - raw.push((51009, Val::Undefined(o.clone()))); - } - if let Some(l) = &self.linearization { - raw.push((50712, Val::Short(l.clone()))); - } - raw.extend(self.raw_extra.iter().cloned()); - let raw_ifd = t.ifd(raw); - // IFD0: a tiny RGB thumbnail plus the DNG metadata. - let thumb = t.blob(vec![128; 3 * 4]); - let mut ifd0: Vec<(u16, Val)> = vec![ - (254, Val::Long(vec![1])), - (256, Val::Long(vec![2])), - (257, Val::Long(vec![2])), - (258, Val::Short(vec![8, 8, 8])), - (259, Val::Short(vec![1])), - (262, Val::Short(vec![2])), - (271, Val::Ascii(self.make.clone())), - (272, Val::Ascii(self.model.clone())), - (273, Val::Blobs(vec![thumb])), - (274, Val::Short(vec![self.orientation])), - (277, Val::Short(vec![3])), - (278, Val::Long(vec![2])), - (279, Val::Long(vec![12])), - (330, Val::Ifds(vec![raw_ifd])), - (50706, Val::Byte(vec![1, 4, 0, 0])), - (50708, Val::Ascii(format!("{} {}", self.make, self.model))), - ]; - let m = |v: &[f64; 9]| Val::SRational(v.iter().map(|&x| srat(x)).collect()); - if let Some((ill, cm)) = &self.color_matrix1 { - ifd0.push((50721, m(cm))); - ifd0.push((50778, Val::Short(vec![*ill]))); - } - if let Some((ill, cm)) = &self.color_matrix2 { - ifd0.push((50722, m(cm))); - ifd0.push((50779, Val::Short(vec![*ill]))); - } - if let Some(f) = &self.forward_matrix1 { - ifd0.push((50964, m(f))); - } - if let Some(f) = &self.forward_matrix2 { - ifd0.push((50965, m(f))); - } - if let Some(n) = self.as_shot_neutral { - ifd0.push((50728, Val::Rational(n.iter().map(|&v| urat(v)).collect()))); - } - if let Some(b) = self.baseline_exposure { - ifd0.push((50730, Val::SRational(vec![srat(b)]))); - } - if let Some(m) = &self.profile_gain_table_map { - ifd0.push((52525, Val::Undefined(m.clone()))); - } - ifd0.extend(self.ifd0_extra.iter().cloned()); - let i0 = t.ifd(ifd0); - t.chain = vec![i0]; - t.build() - } -} - -/// An OpcodeList2 with one GainMap over active-area rectangle `area` (top, -/// left, bottom, right), every `pitch` rows and columns, from a 2×2 grid of -/// gains spanning the image (relative coordinates 0..1). -pub fn gain_map_opcode_list(area: [u32; 4], pitch: u32, gains: [[f32; 2]; 2]) -> Vec { - let mut p = Vec::new(); - for v in [area[0], area[1], area[2], area[3], 0, 1, pitch, pitch, 2, 2] { - p.extend_from_slice(&v.to_be_bytes()); - } - for v in [1.0f64, 1.0, 0.0, 0.0] { - p.extend_from_slice(&v.to_be_bytes()); - } - p.extend_from_slice(&1u32.to_be_bytes()); - for g in gains.iter().flatten() { - p.extend_from_slice(&g.to_bits().to_be_bytes()); - } - let mut b = 1u32.to_be_bytes().to_vec(); - for v in [9u32, 0x0103_0000, 1, p.len() as u32] { - b.extend_from_slice(&v.to_be_bytes()); - } - b.extend_from_slice(&p); - b -} - -/// An opcode list of MapPolynomial opcodes (ID 8), one per `(plane, coefficients)`, each over -/// `area` (top, left, bottom, right) at pitch 1. -pub fn map_polynomial_opcode_list(area: [u32; 4], planes: &[(u32, Vec)]) -> Vec { - let mut b = (planes.len() as u32).to_be_bytes().to_vec(); - for (plane, coefficients) in planes { - let mut p = Vec::new(); - let degree = coefficients.len().saturating_sub(1) as u32; - for v in [area[0], area[1], area[2], area[3], *plane, 1, 1, 1, degree] { - p.extend_from_slice(&v.to_be_bytes()); - } - for c in coefficients { - p.extend_from_slice(&c.to_be_bytes()); - } - for v in [8u32, 0x0103_0000, 0, p.len() as u32] { - b.extend_from_slice(&v.to_be_bytes()); - } - b.extend_from_slice(&p); - } - b -} - -// ---------------------------------------------------------------- CR2 - -/// A synthetic CR2: one lossless JPEG with `components` components, cut into -/// vertical slices, plus a Canon maker note with SensorInfo and ColorData. -#[derive(Debug, Clone)] -pub struct Cr2Spec { - pub width: usize, - pub height: usize, - /// Sensor samples, row-major. - pub data: Vec, - pub precision: u8, - pub components: usize, - /// Slice widths (all but the last equal); empty = no slice tag. - pub slices: Vec, - /// Image borders: left, top, right, bottom (inclusive), as in SensorInfo. - pub borders: Option<[u16; 4]>, - /// As-shot RGGB levels written to ColorData at word offset 0x47 (the PowerShot version). - pub wb_rggb: Option<[u16; 4]>, - pub orientation: u16, - /// Canon model ID written to MakerNote tag 0x0010. - pub model_id: Option, -} - -impl Cr2Spec { - pub fn build(&self) -> Vec { - let (w, h) = (self.width, self.height); - // Slice the sensor data into the JPEG sample order. - let widths: Vec = if self.slices.is_empty() { vec![w] } else { self.slices.clone() }; - assert_eq!(widths.iter().sum::(), w); - let mut seq = Vec::with_capacity(w * h); - let mut x0 = 0; - for &sw in &widths { - for y in 0..h { - seq.extend_from_slice(&self.data[y * w + x0..y * w + x0 + sw]); - } - x0 += sw; - } - let c = self.components; - assert_eq!(w % c, 0); - let jpeg = lj92_encode(&seq, w / c, h, c, self.precision, 1, None); - let mut t = TiffBuilder::default(); - let jb = t.blob(jpeg.clone()); - let mut raw = vec![(259, Val::Short(vec![6])), (273, Val::Blobs(vec![jb])), (279, Val::Long(vec![jpeg.len() as u32]))]; - if !self.slices.is_empty() { - let n = widths.len() - 1; - raw.push((50752, Val::Short(vec![n as u16, widths[0] as u16, widths[n] as u16]))); - } - let raw_ifd = t.ifd(raw); - let mut mn: Vec<(u16, Val)> = Vec::new(); - if let Some(id) = self.model_id { - mn.push((0x0010, Val::Long(vec![id]))); - } - if let Some([l, tp, r, b]) = self.borders { - mn.push((0x00E0, Val::Short(vec![34, w as u16, h as u16, 0, 0, l, tp, r, b, 0, 0, 0, 0, 0, 0, 0, 0]))); - } - if let Some(wb) = self.wb_rggb { - // Canon writes ColorData (0x4001) as UNDEFINED bytes that are 16-bit words; the - // WB_RGGBLevelsAsShot of the PowerShot version sits at word offset 0x47 (the EOS - // versions use 0x3F — see as_shot_wb). - let mut cd = vec![0u8; 2 * 1273]; - for (i, v) in wb.iter().enumerate() { - cd[2 * (0x47 + i)..2 * (0x47 + i) + 2].copy_from_slice(&v.to_le_bytes()); - } - mn.push((0x4001, Val::Undefined(cd))); - } - let mut exif: Vec<(u16, Val)> = vec![(33434, Val::Rational(vec![(1, 100)]))]; - if !mn.is_empty() { - let mi = t.ifd(mn); - exif.push((37500, Val::IfdBytes(mi))); - } - let exif_ifd = t.ifd(exif); - let thumb = t.blob(vec![128; 12]); - let ifd0 = t.ifd(vec![ - (256, Val::Long(vec![2])), - (257, Val::Long(vec![2])), - (259, Val::Short(vec![1])), - (262, Val::Short(vec![2])), - (271, Val::Ascii("Canon".into())), - (272, Val::Ascii("Canon EOS Synthetic".into())), - (273, Val::Blobs(vec![thumb])), - (274, Val::Short(vec![self.orientation])), - (277, Val::Short(vec![3])), - (279, Val::Long(vec![12])), - (34665, Val::Ifds(vec![exif_ifd])), - ]); - let ifd1 = t.ifd(vec![(256, Val::Long(vec![1]))]); - let ifd2 = t.ifd(vec![(256, Val::Long(vec![1]))]); - t.chain = vec![ifd0, ifd1, ifd2, raw_ifd]; - t.cr2_raw_ifd = Some(raw_ifd); - t.build() - } -} - -// ---------------------------------------------------------------- TIFF/EP - -/// A synthetic uncompressed TIFF/EP raw (NEF / ARW-like): IFD0 with Make, the -/// CFA image in a SubIFD with 16-bit samples. -pub fn tiff_ep(make: &str, width: usize, height: usize, data: &[u16], cfa: [u8; 4], bits: u16, extra_raw_tags: Vec<(u16, Val)>) -> Vec { - let mut t = TiffBuilder::default(); - let strip = t.blob(data.iter().flat_map(|v| v.to_le_bytes()).collect()); - let mut raw = vec![ - (254, Val::Long(vec![0])), - (256, Val::Long(vec![width as u32])), - (257, Val::Long(vec![height as u32])), - (258, Val::Short(vec![bits])), - (259, Val::Short(vec![1])), - (262, Val::Short(vec![32803])), - (273, Val::Blobs(vec![strip])), - (277, Val::Short(vec![1])), - (278, Val::Long(vec![height as u32])), - (279, Val::Long(vec![(data.len() * 2) as u32])), - (33421, Val::Short(vec![2, 2])), - (33422, Val::Byte(cfa.to_vec())), - ]; - raw.extend(extra_raw_tags); - let raw_ifd = t.ifd(raw); - let thumb = t.blob(vec![128; 12]); - let ifd0 = t.ifd(vec![ - (254, Val::Long(vec![1])), - (256, Val::Long(vec![2])), - (257, Val::Long(vec![2])), - (259, Val::Short(vec![1])), - (262, Val::Short(vec![2])), - (271, Val::Ascii(make.into())), - (273, Val::Blobs(vec![thumb])), - (277, Val::Short(vec![3])), - (279, Val::Long(vec![12])), - (330, Val::Ifds(vec![raw_ifd])), - ]); - t.chain = vec![ifd0]; - t.build() -} - -/// A synthetic Nikon NEF with a Huffman-compressed (34713) strip: IFD0 with -/// Make and an EXIF IFD whose maker note (`Nikon\0`, version 2.10, then an -/// embedded TIFF in the given byte order) holds `note_tags` (for example -/// `0x0096`, the decode table, and `0x003d`, BlackLevel). -pub fn nef_compressed(width: usize, height: usize, bits: u16, strip: Vec, cfa: [u8; 4], note_big_endian: bool, note_tags: Vec<(u16, Val)>) -> Vec { - let mut note = TiffBuilder { big_endian: note_big_endian, ..Default::default() }; - let n = note.ifd(note_tags); - note.chain = vec![n]; - let mut maker = b"Nikon\0\x02\x10\0\0".to_vec(); - maker.extend(note.build()); - let mut t = TiffBuilder::default(); - let len = strip.len(); - let strip = t.blob(strip); - let raw_ifd = t.ifd(vec![ - (254, Val::Long(vec![0])), - (256, Val::Long(vec![width as u32])), - (257, Val::Long(vec![height as u32])), - (258, Val::Short(vec![bits])), - (259, Val::Short(vec![34713])), - (262, Val::Short(vec![32803])), - (273, Val::Blobs(vec![strip])), - (277, Val::Short(vec![1])), - (278, Val::Long(vec![height as u32])), - (279, Val::Long(vec![len as u32])), - (33421, Val::Short(vec![2, 2])), - (33422, Val::Byte(cfa.to_vec())), - ]); - let exif = t.ifd(vec![(37500, Val::Undefined(maker))]); - let ifd0 = t.ifd(vec![(271, Val::Ascii("NIKON CORPORATION".into())), (330, Val::Ifds(vec![raw_ifd])), (34665, Val::Ifds(vec![exif]))]); - t.chain = vec![ifd0]; - t.build() -} - -// ---------------------------------------------------------------- Sony cRAW - -/// Encodes 16 same-colour 11-bit codes as one cRAW block (see the decoder in -/// `sony.rs`): maximum, minimum, their positions, then 7-bit deltas at the -/// smallest power-of-two step that covers the range (rounded down). -pub fn craw_block(codes: &[u16; 16]) -> [u8; 16] { - let max = *codes.iter().max().unwrap(); - let min = *codes.iter().min().unwrap(); - let imax = codes.iter().position(|&c| c == max).unwrap(); - let mut imin = codes.iter().position(|&c| c == min).unwrap(); - if imin == imax { - imin = (imax + 1) % 16; - } - let mut sh = 0; - while (128u16 << sh) <= max - min { - sh += 1; - } - let mut v: u128 = u128::from(max) | u128::from(min) << 11 | (imax as u128) << 22 | (imin as u128) << 26; - let mut at = 30; - for (i, &c) in codes.iter().enumerate() { - if i != imax && i != imin { - v |= u128::from(((c - min) >> sh).min(127)) << at; - at += 7; - } - } - v.to_le_bytes() -} - -/// Encodes a mosaic of 11-bit codes (`width` a multiple of 32) as cRAW rows. -pub fn craw_encode(codes: &[u16], width: usize, height: usize) -> Vec { - assert_eq!(width % 32, 0); - let mut out = Vec::with_capacity(width * height); - for row in codes.chunks_exact(width).take(height) { - for g in row.as_chunks::<32>().0 { - for parity in 0..2 { - let seq: [u16; 16] = std::array::from_fn(|i| g[2 * i + parity].min(2047)); - out.extend_from_slice(&craw_block(&seq)); - } - } - } - out -} - -/// A synthetic Sony compressed ARW: IFD0 with Make, the cRAW image in a -/// SubIFD with SonyRawFileType 2, the tone curve (0x7010), black (0x7310), -/// white (50717) and WB_RGGBLevels (0x7313). -pub fn sony_craw(width: usize, height: usize, codes: &[u16], curve: [u16; 4]) -> Vec { - let bytes = craw_encode(codes, width, height); - let mut t = TiffBuilder::default(); - let n = bytes.len(); - let strip = t.blob(bytes); - let raw_ifd = t.ifd(vec![ - (254, Val::Long(vec![0])), - (256, Val::Long(vec![width as u32])), - (257, Val::Long(vec![height as u32])), - (258, Val::Short(vec![12])), - (259, Val::Short(vec![32767])), - (262, Val::Short(vec![32803])), - (273, Val::Blobs(vec![strip])), - (277, Val::Short(vec![1])), - (278, Val::Long(vec![height as u32])), - (279, Val::Long(vec![n as u32])), - (33421, Val::Short(vec![2, 2])), - (33422, Val::Byte(vec![0, 1, 1, 2])), - (0x7000, Val::Short(vec![2])), - (0x7010, Val::Short(curve.to_vec())), - (0x7310, Val::Short(vec![512; 4])), - (0x7313, Val::Short(vec![2048, 1024, 1024, 1536])), - (50717, Val::Short(vec![16383])), - ]); - let ifd0 = t.ifd(vec![(271, Val::Ascii("SONY".into())), (272, Val::Ascii("ILCE-Synthetic".into())), (330, Val::Ifds(vec![raw_ifd]))]); - t.chain = vec![ifd0]; - t.build() -} - -// ---------------------------------------------------------------- Panasonic RW2 - -/// Page size and split point of the RW2 stream (see `rw2.rs`). -const RW2_PAGE: usize = 0x4000; -const RW2_SPLIT: usize = 0x1FF8; - -/// Packs `bits`-bit samples (12: 10 per block, 14: 9 per block) into the RW2 -/// RawFormat 5 layout: 16-byte little-endian blocks, stored in 0x4000-byte -/// pages split at 0x1FF8. -pub fn rw2_pack(data: &[u16], width: usize, bits: u32) -> Vec { - let ppb = if bits == 14 { 9 } else { 10 }; - assert_eq!(width % ppb, 0); - let mut logical = Vec::new(); - for px in data.chunks_exact(ppb) { - let mut v: u128 = 0; - for (i, &p) in px.iter().enumerate() { - v |= u128::from(p & ((1 << bits) - 1)) << (bits as usize * i); - } - logical.extend_from_slice(&v.to_le_bytes()); - } - logical.resize(logical.len().div_ceil(RW2_PAGE) * RW2_PAGE, 0); - let mut out = vec![0u8; logical.len()]; - for (i, &b) in logical.iter().enumerate() { - let page = i - i % RW2_PAGE; - out[page + (i % RW2_PAGE + RW2_SPLIT) % RW2_PAGE] = b; - } - out -} - -/// A synthetic Panasonic RW2 (RawFormat 5) with an RGGB sensor, a 2-pixel -/// border on every side, black levels 128 / 129 / 130 and WB levels -/// 512 / 256 / 384. -pub fn rw2(width: usize, height: usize, data: &[u16], bits: u32) -> Vec { - let mut t = TiffBuilder::default(); - let raw = t.blob(rw2_pack(data, width, bits)); - let white = ((1u32 << bits) - 1) as u16; - let ifd0 = t.ifd(vec![ - (0x0002, Val::Short(vec![width as u16])), - (0x0003, Val::Short(vec![height as u16])), - (0x0004, Val::Short(vec![2])), - (0x0005, Val::Short(vec![2])), - (0x0006, Val::Short(vec![height as u16 - 2])), - (0x0007, Val::Short(vec![width as u16 - 2])), - (0x0009, Val::Short(vec![1])), - (0x000A, Val::Short(vec![bits as u16])), - (0x000E, Val::Short(vec![white])), - (0x000F, Val::Short(vec![white])), - (0x0010, Val::Short(vec![white])), - (0x001C, Val::Short(vec![128])), - (0x001D, Val::Short(vec![129])), - (0x001E, Val::Short(vec![130])), - (0x0024, Val::Short(vec![512])), - (0x0025, Val::Short(vec![256])), - (0x0026, Val::Short(vec![384])), - (0x002D, Val::Short(vec![5])), - (0x010F, Val::Ascii("Panasonic".into())), - (0x0110, Val::Ascii("DC-Synthetic".into())), - (0x0112, Val::Short(vec![1])), - (0x0118, Val::Blobs(vec![raw])), - ]); - t.chain = vec![ifd0]; - let mut b = t.build(); - b[2..4].copy_from_slice(b"U\0"); - b -} - -/// Byte split of the vendor-compressed (RawFormat 3/4) stream (see `rw2.rs`). -const RW2_COMPRESSED_SPLIT: usize = 0x2008; - -/// Writer for the vendor-compressed RW2 stream: mirrors the decoder's cursor -/// (page addressing, downward field order) and deposits every field where the -/// reader will pick it up. -struct V4Writer<'a> { - buf: &'a mut [u8], - base: usize, - pos: usize, - nbits: u32, -} - -impl V4Writer<'_> { - /// Consumes one byte of the row seek (the decoder reads 8-bit fields). - fn skip_byte(&mut self) { - if 8 > self.nbits { - self.nbits += (RW2_PAGE as u32) * 8; - self.pos += RW2_PAGE; - } - self.nbits -= 8; - } - - fn put(&mut self, v: u32, num: u32) { - if num > self.nbits { - self.nbits += (RW2_PAGE as u32) * 8; - self.pos += RW2_PAGE; - } - let mut at = ((self.nbits - num) >> 3) as usize ^ 0x3FF0; - at = (at + RW2_PAGE - RW2_COMPRESSED_SPLIT) % RW2_PAGE; - let at = self.base + at + self.pos - RW2_PAGE; - self.nbits -= num; - let cur = u32::from(self.buf[at]) | (u32::from(self.buf[at + 1]) << 8); - let cur = cur | ((v & ((1 << num) - 1)) << (self.nbits & 7)); - self.buf[at] = cur as u8; - self.buf[at + 1] = (cur >> 8) as u8; - } - - /// Encodes one row as 14-pixel groups: the scale selector is always 0 and - /// the two first pixels of each group are absolute (8 + 4 bits); later - /// pixels use the 8-bit delta path. Callers keep values inside 16..4096 - /// and stepping by at most ±127 between pixels of the same parity. - fn row(&mut self, pixels: &[u16]) { - for group in pixels.as_chunks::<14>().0 { - let mut pred = [0i32; 2]; - let mut nonz = [0i32; 2]; - for (i, &px) in group.iter().enumerate() { - if i % 3 == 2 { - self.put(0, 2); // sh = 0 - } - let p = i & 1; - let t = i32::from(px); - if nonz[p] == 0 { - let nz = (t >> 4) & 0xFF; - self.put(nz as u32, 8); - if nz != 0 || i > 11 { - self.put((t & 0xF) as u32, 4); - pred[p] = t; - } else { - pred[p] = 0; - } - nonz[p] = nz; - } else { - let q = (pred[p] - 0x80).max(0); - let j = t - q; - assert!((1..=0xFF).contains(&j), "{t} is not encodable from {}", pred[p]); - self.put(j as u32, 8); - pred[p] = q + j; - } - assert_eq!(pred[p], t); - } - } - } -} - -/// The vendor-compressed (RawFormat 3/4) stream of a whole image; see -/// [`V4Writer::row`] for the value constraints. -pub fn rw2_v4_pack(data: &[u16], width: usize) -> Vec { - assert_eq!(width % 14, 0); - let height = data.len() / width; - assert_eq!(data.len(), width * height); - let row_bytes = width / 14 * 16; - let mut buf = vec![0u8; row_bytes * height + 2 * RW2_PAGE]; - for (row, pixels) in data.chunks_exact(width).enumerate() { - let skip = row_bytes * row; - let mut w = V4Writer { buf: &mut buf, base: skip / RW2_PAGE * RW2_PAGE, pos: 0, nbits: 0 }; - for _ in 0..(skip % RW2_PAGE) { - w.skip_byte(); - } - w.row(pixels); - } - buf -} - -/// A synthetic Panasonic RW2 (RawFormat 4, vendor-compressed) with an RGGB -/// sensor, a 2-pixel border on every side, black levels 128 / 129 / 130 and -/// WB levels 512 / 256 / 384; see [`V4Writer::row`] for the pixel constraints. -pub fn rw2_format4(width: usize, height: usize, data: &[u16]) -> Vec { - let mut t = TiffBuilder::default(); - let raw = t.blob(rw2_v4_pack(data, width)); - let ifd0 = t.ifd(vec![ - (0x0002, Val::Short(vec![width as u16])), - (0x0003, Val::Short(vec![height as u16])), - (0x0004, Val::Short(vec![2])), - (0x0005, Val::Short(vec![2])), - (0x0006, Val::Short(vec![height as u16 - 2])), - (0x0007, Val::Short(vec![width as u16 - 2])), - (0x0009, Val::Short(vec![1])), - (0x000A, Val::Short(vec![12])), - (0x000E, Val::Short(vec![4095])), - (0x000F, Val::Short(vec![4095])), - (0x0010, Val::Short(vec![4095])), - (0x001C, Val::Short(vec![128])), - (0x001D, Val::Short(vec![129])), - (0x001E, Val::Short(vec![130])), - (0x0024, Val::Short(vec![512])), - (0x0025, Val::Short(vec![256])), - (0x0026, Val::Short(vec![384])), - (0x002D, Val::Short(vec![4])), - (0x010F, Val::Ascii("Panasonic".into())), - (0x0110, Val::Ascii("DC-Synthetic".into())), - (0x0112, Val::Short(vec![1])), - (0x0118, Val::Blobs(vec![raw])), - ]); - t.chain = vec![ifd0]; - let mut b = t.build(); - b[2..4].copy_from_slice(b"U\0"); - b -} - -// ---------------------------------------------------------------- Olympus ORF - -/// A little-endian IFD whose value offsets are relative to `base` (the IFD -/// itself sits at `base_offset` from that base). Entries: (tag, type, count, -/// value bytes). -fn relative_ifd(entries: &[(u16, u16, u32, Vec)], base_offset: usize) -> Vec { - let head = 2 + 12 * entries.len() + 4; - let mut out = Vec::new(); - let mut extra = Vec::new(); - out.extend_from_slice(&(entries.len() as u16).to_le_bytes()); - for (tag, typ, count, bytes) in entries { - out.extend_from_slice(&tag.to_le_bytes()); - out.extend_from_slice(&typ.to_le_bytes()); - out.extend_from_slice(&count.to_le_bytes()); - if bytes.len() <= 4 { - let mut v = bytes.clone(); - v.resize(4, 0); - out.extend_from_slice(&v); - } else { - out.extend_from_slice(&((base_offset + head + extra.len()) as u32).to_le_bytes()); - extra.extend_from_slice(bytes); - } - } - out.extend_from_slice(&0u32.to_le_bytes()); - out.extend_from_slice(&extra); - out -} - -fn shorts(v: &[u16]) -> Vec { - v.iter().flat_map(|x| x.to_le_bytes()).collect() -} - -/// A synthetic uncompressed Olympus ORF (`IIRO`): 12-bit `data` stored -/// left-justified in 16-bit samples, a GRBG EXIF CFAPattern and a new-style -/// maker note with ImageProcessing levels (black 64, WB 2.0 / 1.5, crop of a -/// 2-pixel border) and CameraSettings pointing at a tiny preview JPEG. -pub fn orf(width: usize, height: usize, data: &[u16]) -> Vec { - let ip = relative_ifd( - &[ - (0x0100, 3, 2, shorts(&[512, 384])), - (0x011F, 3, 1, shorts(&[256])), - (0x0600, 3, 4, shorts(&[64, 64, 64, 64])), - (0x0611, 3, 2, shorts(&[12, 0])), - (0x0612, 3, 2, shorts(&[2, 0])), - (0x0613, 3, 2, shorts(&[2, 0])), - (0x0614, 4, 1, ((width - 4) as u32).to_le_bytes().to_vec()), - (0x0615, 4, 1, ((height - 4) as u32).to_le_bytes().to_vec()), - ], - 64, - ); - // CameraSettings with a preview JPEG (SOI, SOF0 16×8, EOI) right after it. - let jpeg = [0xFF, 0xD8, 0xFF, 0xC0, 0x00, 0x0B, 8, 0x00, 0x08, 0x00, 0x10, 1, 1, 0x11, 0, 0xFF, 0xD9]; - let cs_at = 64 + ip.len().next_multiple_of(4); - let cs_len = 2 + 12 * 3 + 4; - let cs = relative_ifd( - &[ - (0x0100, 4, 1, 1u32.to_le_bytes().to_vec()), - (0x0101, 4, 1, ((cs_at + cs_len) as u32).to_le_bytes().to_vec()), - (0x0102, 4, 1, (jpeg.len() as u32).to_le_bytes().to_vec()), - ], - cs_at, - ); - let mut note = b"OLYMPUS\0II\x03\0".to_vec(); - note.extend_from_slice(&relative_ifd(&[(0x2020, 13, 1, (cs_at as u32).to_le_bytes().to_vec()), (0x2040, 13, 1, 64u32.to_le_bytes().to_vec())], 12)); - note.resize(64, 0); - note.extend_from_slice(&ip); - note.resize(cs_at, 0); - note.extend_from_slice(&cs); - note.extend_from_slice(&jpeg); - let mut t = TiffBuilder::default(); - let strip = t.blob(data.iter().flat_map(|v| (v << 4).to_le_bytes()).collect()); - let exif = t.ifd(vec![(37500, Val::Undefined(note)), (41730, Val::Undefined(vec![2, 0, 2, 0, 1, 0, 2, 1]))]); - let ifd0 = t.ifd(vec![ - (256, Val::Long(vec![width as u32])), - (257, Val::Long(vec![height as u32])), - (258, Val::Short(vec![16])), - (259, Val::Short(vec![1])), - (262, Val::Short(vec![1])), - (271, Val::Ascii("OLYMPUS IMAGING CORP.".into())), - (272, Val::Ascii("E-Synthetic".into())), - (273, Val::Blobs(vec![strip])), - (277, Val::Short(vec![1])), - (278, Val::Long(vec![height as u32])), - (279, Val::Long(vec![(data.len() * 2) as u32])), - (34665, Val::Ifds(vec![exif])), - ]); - t.chain = vec![ifd0]; - let mut b = t.build(); - b[2..4].copy_from_slice(b"RO"); - b -} - -// ---------------------------------------------------------------- Fujifilm RAF - -/// How a synthetic RAF stores its samples (see `raf.rs`). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum RafPacking { - /// 16-bit containers; little-endian (`II`) or big-endian (`MM`) CFA TIFF. - U16 { le: bool }, - /// 12-bit, little-endian bit stream, least significant bit first. - Lsb12, - /// 14-bit, most significant bit first in little-endian 32-bit words. - Words14, - /// A short `IS…` strip standing in for Fujifilm's compressed data. - Compressed, -} - -/// The X-Trans repeat at the data origin, as observed (row major, 0 = R, 1 = G, 2 = B). -pub const XTRANS: [u8; 36] = [ - 1, 1, 0, 1, 1, 2, // - 1, 1, 2, 1, 1, 0, // - 2, 0, 1, 0, 2, 1, // - 1, 1, 2, 1, 1, 0, // - 1, 1, 0, 1, 1, 2, // - 0, 2, 1, 2, 0, 1, -]; - -/// A synthetic Fujifilm RAF. -#[derive(Debug, Clone)] -pub struct RafSpec { - pub width: usize, - pub height: usize, - pub data: Vec, - pub bits: u32, - pub packing: RafPacking, - /// CFA colours at the data origin: 36 (X-Trans, 6×6) or 4 (Bayer, 2×2), row major. - pub cfa: Vec, - /// RawImageCropTopLeft / RawImageCroppedSize: top, left, height, width. - pub crop: Option<[u16; 4]>, - pub black: Vec, - /// WB_GRBLevels: G, R, B. - pub wb_grb: Option<[u32; 3]>, - /// RawExposureBias as numerator / denominator. - pub exposure_bias: Option<(i16, i16)>, - /// EXIF orientation of the preview JPEG. - pub orientation: u16, - /// `false` writes an early-FinePix-style file without the CFA TIFF. - pub cfa_tiff: bool, -} - -impl RafSpec { - pub fn new(width: usize, height: usize, data: Vec, cfa: Vec) -> Self { - RafSpec { - width, - height, - data, - bits: 14, - packing: RafPacking::U16 { le: true }, - cfa, - crop: None, - black: vec![1024], - wb_grb: Some([302, 604, 453]), - exposure_bias: None, - orientation: 1, - cfa_tiff: true, - } - } - - /// The samples as stored. - fn strip(&self) -> Vec { - match self.packing { - RafPacking::U16 { le } => self.data.iter().flat_map(|v| if le { v.to_le_bytes() } else { v.to_be_bytes() }).collect(), - RafPacking::Lsb12 => { - let (mut out, mut acc, mut n) = (Vec::new(), 0u64, 0u32); - for &v in &self.data { - acc |= u64::from(v & 0xFFF) << n; - n += 12; - while n >= 8 { - out.push(acc as u8); - acc >>= 8; - n -= 8; - } - } - if n > 0 { - out.push(acc as u8); - } - out - } - RafPacking::Words14 => { - let (mut logical, mut acc, mut n) = (Vec::new(), 0u64, 0u32); - for &v in &self.data { - acc = (acc << 14) | u64::from(v & 0x3FFF); - n += 14; - while n >= 8 { - logical.push((acc >> (n - 8)) as u8); - n -= 8; - } - } - if n > 0 { - logical.push((acc << (8 - n)) as u8); - } - logical.resize(logical.len().next_multiple_of(4), 0); - logical.chunks(4).flat_map(|w| w.iter().rev().copied().collect::>()).collect() - } - RafPacking::Compressed => { - let mut v = b"IS\x01\x00".to_vec(); - v.resize(self.width * self.height / 2, 0x5A); - v - } - } - } - - /// The CFA region: a TIFF whose IFD0 points (0xF000) at the Fuji raw IFD. - fn cfa_region(&self) -> Vec { - let le = !matches!(self.packing, RafPacking::U16 { le: false }); - let u16b = |v: u16| if le { v.to_le_bytes() } else { v.to_be_bytes() }; - let u32b = |v: u32| if le { v.to_le_bytes() } else { v.to_be_bytes() }; - let strip = self.strip(); - let strip_at = 2048u32; - let entries: Vec<(u16, Vec)> = vec![ - (0xF001, vec![self.width as u32]), - (0xF002, vec![self.height as u32]), - (0xF003, vec![self.bits]), - (0xF007, vec![strip_at]), - (0xF008, vec![strip.len() as u32]), - (0xF00A, self.black.clone()), - ] - .into_iter() - .chain(self.wb_grb.map(|w| (0xF00E, w.to_vec()))) - .collect(); - let mut out = if le { b"II*\0".to_vec() } else { b"MM\0*".to_vec() }; - out.extend_from_slice(&u32b(8)); - // IFD0: one entry, 0xF000 (type IFD) → the Fuji IFD at 26. - out.extend_from_slice(&u16b(1)); - out.extend_from_slice(&u16b(0xF000)); - out.extend_from_slice(&u16b(13)); - out.extend_from_slice(&u32b(1)); - out.extend_from_slice(&u32b(26)); - out.extend_from_slice(&u32b(0)); - let fuji_at = out.len(); - let mut extra_at = fuji_at + 2 + 12 * entries.len() + 4; - let mut extra = Vec::new(); - out.extend_from_slice(&u16b(entries.len() as u16)); - for (tag, vals) in &entries { - out.extend_from_slice(&u16b(*tag)); - out.extend_from_slice(&u16b(4)); - out.extend_from_slice(&u32b(vals.len() as u32)); - if vals.len() == 1 { - out.extend_from_slice(&u32b(vals[0])); - } else { - out.extend_from_slice(&u32b(extra_at as u32)); - for v in vals { - extra.extend_from_slice(&u32b(*v)); - } - extra_at += 4 * vals.len(); - } - } - out.extend_from_slice(&u32b(0)); - out.extend_from_slice(&extra); - assert!(out.len() <= strip_at as usize); - out.resize(strip_at as usize, 0); - out.extend_from_slice(&strip); - out - } - - /// A tiny baseline-JPEG preview (APP1 EXIF with make, model and - /// orientation; SOF0 32×24; EOI). - fn preview(&self) -> Vec { - let mut t = TiffBuilder::default(); - let ifd0 = t.ifd(vec![(271, Val::Ascii("FUJIFILM".into())), (272, Val::Ascii("X-Synthetic".into())), (274, Val::Short(vec![self.orientation]))]); - t.chain = vec![ifd0]; - let mut app1 = b"Exif\0\0".to_vec(); - app1.extend_from_slice(&t.build()); - let mut j = vec![0xFF, 0xD8, 0xFF, 0xE1]; - j.extend_from_slice(&((app1.len() + 2) as u16).to_be_bytes()); - j.extend_from_slice(&app1); - j.extend_from_slice(&[0xFF, 0xC0, 0x00, 0x0B, 8, 0x00, 24, 0x00, 32, 1, 1, 0x11, 0, 0xFF, 0xD9]); - j - } - - /// The metadata directory. - fn meta(&self) -> Vec { - let mut recs: Vec<(u16, Vec)> = Vec::new(); - if let Some([top, left, h, w]) = self.crop { - recs.push((0x0110, [top.to_be_bytes(), left.to_be_bytes()].concat())); - recs.push((0x0111, [h.to_be_bytes(), w.to_be_bytes()].concat())); - } - if self.cfa.len() == 36 { - recs.push((0x0130, vec![0x0C; 4])); - recs.push((0x0131, self.cfa.iter().rev().copied().collect())); - } else { - // Bayer: reversed, colour in the low two bits, the second green as 3. - let mut greens = 0; - let codes: Vec = self - .cfa - .iter() - .map(|&c| { - if c == 1 { - greens += 1; - if greens == 1 { 0x09 } else { 0x0B } - } else { - 0x08 | c - } - }) - .collect(); - recs.push((0x0130, codes.into_iter().rev().collect())); - } - if let Some((n, d)) = self.exposure_bias { - recs.push((0x9650, [n.to_be_bytes(), d.to_be_bytes()].concat())); - } - let mut out = (recs.len() as u32).to_be_bytes().to_vec(); - for (tag, d) in recs { - out.extend_from_slice(&tag.to_be_bytes()); - out.extend_from_slice(&(d.len() as u16).to_be_bytes()); - out.extend_from_slice(&d); - } - out - } - - pub fn build(&self) -> Vec { - let mut b = b"FUJIFILMCCD-RAW 0201FF000000".to_vec(); - b.extend_from_slice(b"X-Synthetic"); - b.resize(60, 0); - b.extend_from_slice(b"0100"); - b.resize(160, 0); - let preview = self.preview(); - let meta = self.meta(); - let region = if self.cfa_tiff { self.cfa_region() } else { self.strip() }; - let (p_at, m_at) = (b.len(), b.len() + preview.len()); - let c_at = m_at + meta.len(); - for (at, v) in [(84, p_at), (88, preview.len()), (92, m_at), (96, meta.len()), (100, c_at), (104, region.len())] { - b[at..at + 4].copy_from_slice(&(v as u32).to_be_bytes()); - } - b.extend_from_slice(&preview); - b.extend_from_slice(&meta); - b.extend_from_slice(®ion); - b - } -} - -/// Mosaics linear RGB through any CFA repeat (`cfa`: `cfa_w` colours per -/// row) anchored at (0, 0), like [`mosaic`]. -pub fn mosaic_cfa(rgb: &[[f32; 3]], width: usize, cfa: &[u8], cfa_w: usize, black: u16, white: u16) -> Vec { - let cfa_h = cfa.len() / cfa_w; - rgb.iter() - .enumerate() - .map(|(i, p)| { - let (x, y) = (i % width, i / width); - let c = cfa[(y % cfa_h) * cfa_w + x % cfa_w] as usize; - (f32::from(black) + p[c].clamp(0.0, 1.0) * f32::from(white - black)).round() as u16 - }) - .collect() -} - -// ---------------------------------------------------------------- scenes - -/// A smooth, colourful synthetic scene as linear RGB in 0..1. -pub fn scene(width: usize, height: usize) -> Vec<[f32; 3]> { - (0..width * height) - .map(|i| { - let (x, y) = ((i % width) as f32 / width.max(1) as f32, (i / width) as f32 / height.max(1) as f32); - [0.1 + 0.7 * x, 0.15 + 0.5 * (1.0 - y) * x + 0.2 * y, 0.6 - 0.4 * y + 0.2 * x] - }) - .collect() -} - -/// Mosaics linear RGB through a 2×2 CFA (`cfa` row-major colours) into -/// sensor values `black + v * (white - black)`. -pub fn mosaic(rgb: &[[f32; 3]], width: usize, cfa: [u8; 4], black: u16, white: u16) -> Vec { - rgb.iter() - .enumerate() - .map(|(i, p)| { - let (x, y) = (i % width, i / width); - let c = cfa[(y & 1) * 2 + (x & 1)] as usize; - let v = p[c].clamp(0.0, 1.0); - (f32::from(black) + v * f32::from(white - black)).round() as u16 - }) - .collect() -} diff --git a/crates/raw/src/testgen/canon.rs b/crates/raw/src/testgen/canon.rs new file mode 100644 index 0000000000..33a28d057d --- /dev/null +++ b/crates/raw/src/testgen/canon.rs @@ -0,0 +1,243 @@ +use super::lj92::lj92_encode; +use super::tiff::{TiffBuilder, Val}; + +// ---------------------------------------------------------------- CR2 + +/// A synthetic CR2: one lossless JPEG with `components` components, cut into +/// vertical slices, plus a Canon maker note with SensorInfo and ColorData. +#[derive(Debug, Clone)] +pub struct Cr2Spec { + pub width: usize, + pub height: usize, + /// Sensor samples, row-major. + pub data: Vec, + pub precision: u8, + pub components: usize, + /// Slice widths (all but the last equal); empty = no slice tag. + pub slices: Vec, + /// Image borders: left, top, right, bottom (inclusive), as in SensorInfo. + pub borders: Option<[u16; 4]>, + /// As-shot RGGB levels written to ColorData at word offset 0x47 (the PowerShot version). + pub wb_rggb: Option<[u16; 4]>, + pub orientation: u16, + /// Canon model ID written to MakerNote tag 0x0010. + pub model_id: Option, +} + +impl Cr2Spec { + pub fn build(&self) -> Vec { + let (w, h) = (self.width, self.height); + // Slice the sensor data into the JPEG sample order. + let widths: Vec = if self.slices.is_empty() { vec![w] } else { self.slices.clone() }; + assert_eq!(widths.iter().sum::(), w); + let mut seq = Vec::with_capacity(w * h); + let mut x0 = 0; + for &sw in &widths { + for y in 0..h { + seq.extend_from_slice(&self.data[y * w + x0..y * w + x0 + sw]); + } + x0 += sw; + } + let c = self.components; + assert_eq!(w % c, 0); + let jpeg = lj92_encode(&seq, w / c, h, c, self.precision, 1, None); + let mut t = TiffBuilder::default(); + let jb = t.blob(jpeg.clone()); + let mut raw = vec![(259, Val::Short(vec![6])), (273, Val::Blobs(vec![jb])), (279, Val::Long(vec![jpeg.len() as u32]))]; + if !self.slices.is_empty() { + let n = widths.len() - 1; + raw.push((50752, Val::Short(vec![n as u16, widths[0] as u16, widths[n] as u16]))); + } + let raw_ifd = t.ifd(raw); + let mut mn: Vec<(u16, Val)> = Vec::new(); + if let Some(id) = self.model_id { + mn.push((0x0010, Val::Long(vec![id]))); + } + if let Some([l, tp, r, b]) = self.borders { + mn.push((0x00E0, Val::Short(vec![34, w as u16, h as u16, 0, 0, l, tp, r, b, 0, 0, 0, 0, 0, 0, 0, 0]))); + } + if let Some(wb) = self.wb_rggb { + // Canon writes ColorData (0x4001) as UNDEFINED bytes that are 16-bit words; the + // WB_RGGBLevelsAsShot of the PowerShot version sits at word offset 0x47 (the EOS + // versions use 0x3F — see as_shot_wb). + let mut cd = vec![0u8; 2 * 1273]; + for (i, v) in wb.iter().enumerate() { + cd[2 * (0x47 + i)..2 * (0x47 + i) + 2].copy_from_slice(&v.to_le_bytes()); + } + mn.push((0x4001, Val::Undefined(cd))); + } + let mut exif: Vec<(u16, Val)> = vec![(33434, Val::Rational(vec![(1, 100)]))]; + if !mn.is_empty() { + let mi = t.ifd(mn); + exif.push((37500, Val::IfdBytes(mi))); + } + let exif_ifd = t.ifd(exif); + let thumb = t.blob(vec![128; 12]); + let ifd0 = t.ifd(vec![ + (256, Val::Long(vec![2])), + (257, Val::Long(vec![2])), + (259, Val::Short(vec![1])), + (262, Val::Short(vec![2])), + (271, Val::Ascii("Canon".into())), + (272, Val::Ascii("Canon EOS Synthetic".into())), + (273, Val::Blobs(vec![thumb])), + (274, Val::Short(vec![self.orientation])), + (277, Val::Short(vec![3])), + (279, Val::Long(vec![12])), + (34665, Val::Ifds(vec![exif_ifd])), + ]); + let ifd1 = t.ifd(vec![(256, Val::Long(vec![1]))]); + let ifd2 = t.ifd(vec![(256, Val::Long(vec![1]))]); + t.chain = vec![ifd0, ifd1, ifd2, raw_ifd]; + t.cr2_raw_ifd = Some(raw_ifd); + t.build() + } +} + +// ---------------------------------------------------------------- TIFF/EP + +/// A synthetic uncompressed TIFF/EP raw (NEF / ARW-like): IFD0 with Make, the +/// CFA image in a SubIFD with 16-bit samples. +pub fn tiff_ep(make: &str, width: usize, height: usize, data: &[u16], cfa: [u8; 4], bits: u16, extra_raw_tags: Vec<(u16, Val)>) -> Vec { + let mut t = TiffBuilder::default(); + let strip = t.blob(data.iter().flat_map(|v| v.to_le_bytes()).collect()); + let mut raw = vec![ + (254, Val::Long(vec![0])), + (256, Val::Long(vec![width as u32])), + (257, Val::Long(vec![height as u32])), + (258, Val::Short(vec![bits])), + (259, Val::Short(vec![1])), + (262, Val::Short(vec![32803])), + (273, Val::Blobs(vec![strip])), + (277, Val::Short(vec![1])), + (278, Val::Long(vec![height as u32])), + (279, Val::Long(vec![(data.len() * 2) as u32])), + (33421, Val::Short(vec![2, 2])), + (33422, Val::Byte(cfa.to_vec())), + ]; + raw.extend(extra_raw_tags); + let raw_ifd = t.ifd(raw); + let thumb = t.blob(vec![128; 12]); + let ifd0 = t.ifd(vec![ + (254, Val::Long(vec![1])), + (256, Val::Long(vec![2])), + (257, Val::Long(vec![2])), + (259, Val::Short(vec![1])), + (262, Val::Short(vec![2])), + (271, Val::Ascii(make.into())), + (273, Val::Blobs(vec![thumb])), + (277, Val::Short(vec![3])), + (279, Val::Long(vec![12])), + (330, Val::Ifds(vec![raw_ifd])), + ]); + t.chain = vec![ifd0]; + t.build() +} + +/// A synthetic Nikon NEF with a Huffman-compressed (34713) strip: IFD0 with +/// Make and an EXIF IFD whose maker note (`Nikon\0`, version 2.10, then an +/// embedded TIFF in the given byte order) holds `note_tags` (for example +/// `0x0096`, the decode table, and `0x003d`, BlackLevel). +pub fn nef_compressed(width: usize, height: usize, bits: u16, strip: Vec, cfa: [u8; 4], note_big_endian: bool, note_tags: Vec<(u16, Val)>) -> Vec { + let mut note = TiffBuilder { big_endian: note_big_endian, ..Default::default() }; + let n = note.ifd(note_tags); + note.chain = vec![n]; + let mut maker = b"Nikon\0\x02\x10\0\0".to_vec(); + maker.extend(note.build()); + let mut t = TiffBuilder::default(); + let len = strip.len(); + let strip = t.blob(strip); + let raw_ifd = t.ifd(vec![ + (254, Val::Long(vec![0])), + (256, Val::Long(vec![width as u32])), + (257, Val::Long(vec![height as u32])), + (258, Val::Short(vec![bits])), + (259, Val::Short(vec![34713])), + (262, Val::Short(vec![32803])), + (273, Val::Blobs(vec![strip])), + (277, Val::Short(vec![1])), + (278, Val::Long(vec![height as u32])), + (279, Val::Long(vec![len as u32])), + (33421, Val::Short(vec![2, 2])), + (33422, Val::Byte(cfa.to_vec())), + ]); + let exif = t.ifd(vec![(37500, Val::Undefined(maker))]); + let ifd0 = t.ifd(vec![(271, Val::Ascii("NIKON CORPORATION".into())), (330, Val::Ifds(vec![raw_ifd])), (34665, Val::Ifds(vec![exif]))]); + t.chain = vec![ifd0]; + t.build() +} + +// ---------------------------------------------------------------- Sony cRAW + +/// Encodes 16 same-colour 11-bit codes as one cRAW block (see the decoder in +/// `sony.rs`): maximum, minimum, their positions, then 7-bit deltas at the +/// smallest power-of-two step that covers the range (rounded down). +pub fn craw_block(codes: &[u16; 16]) -> [u8; 16] { + let max = *codes.iter().max().unwrap(); + let min = *codes.iter().min().unwrap(); + let imax = codes.iter().position(|&c| c == max).unwrap(); + let mut imin = codes.iter().position(|&c| c == min).unwrap(); + if imin == imax { + imin = (imax + 1) % 16; + } + let mut sh = 0; + while (128u16 << sh) <= max - min { + sh += 1; + } + let mut v: u128 = u128::from(max) | u128::from(min) << 11 | (imax as u128) << 22 | (imin as u128) << 26; + let mut at = 30; + for (i, &c) in codes.iter().enumerate() { + if i != imax && i != imin { + v |= u128::from(((c - min) >> sh).min(127)) << at; + at += 7; + } + } + v.to_le_bytes() +} + +/// Encodes a mosaic of 11-bit codes (`width` a multiple of 32) as cRAW rows. +pub fn craw_encode(codes: &[u16], width: usize, height: usize) -> Vec { + assert_eq!(width % 32, 0); + let mut out = Vec::with_capacity(width * height); + for row in codes.chunks_exact(width).take(height) { + for g in row.as_chunks::<32>().0 { + for parity in 0..2 { + let seq: [u16; 16] = std::array::from_fn(|i| g[2 * i + parity].min(2047)); + out.extend_from_slice(&craw_block(&seq)); + } + } + } + out +} + +/// A synthetic Sony compressed ARW: IFD0 with Make, the cRAW image in a +/// SubIFD with SonyRawFileType 2, the tone curve (0x7010), black (0x7310), +/// white (50717) and WB_RGGBLevels (0x7313). +pub fn sony_craw(width: usize, height: usize, codes: &[u16], curve: [u16; 4]) -> Vec { + let bytes = craw_encode(codes, width, height); + let mut t = TiffBuilder::default(); + let n = bytes.len(); + let strip = t.blob(bytes); + let raw_ifd = t.ifd(vec![ + (254, Val::Long(vec![0])), + (256, Val::Long(vec![width as u32])), + (257, Val::Long(vec![height as u32])), + (258, Val::Short(vec![12])), + (259, Val::Short(vec![32767])), + (262, Val::Short(vec![32803])), + (273, Val::Blobs(vec![strip])), + (277, Val::Short(vec![1])), + (278, Val::Long(vec![height as u32])), + (279, Val::Long(vec![n as u32])), + (33421, Val::Short(vec![2, 2])), + (33422, Val::Byte(vec![0, 1, 1, 2])), + (0x7000, Val::Short(vec![2])), + (0x7010, Val::Short(curve.to_vec())), + (0x7310, Val::Short(vec![512; 4])), + (0x7313, Val::Short(vec![2048, 1024, 1024, 1536])), + (50717, Val::Short(vec![16383])), + ]); + let ifd0 = t.ifd(vec![(271, Val::Ascii("SONY".into())), (272, Val::Ascii("ILCE-Synthetic".into())), (330, Val::Ifds(vec![raw_ifd]))]); + t.chain = vec![ifd0]; + t.build() +} diff --git a/crates/raw/src/testgen/dng.rs b/crates/raw/src/testgen/dng.rs new file mode 100644 index 0000000000..02a8d7b621 --- /dev/null +++ b/crates/raw/src/testgen/dng.rs @@ -0,0 +1,478 @@ +use super::lj92::lj92_encode; +use super::tiff::{TiffBuilder, Val, srat, urat}; + +// ---------------------------------------------------------------- DNG + +/// Encodes 8-bit samples (1 gray or 3 RGB per pixel, row-major) as a baseline JPEG at +/// quality 60, the way a lossy DNG segment is stored (an RGB segment is coded as YCbCr). +pub fn baseline_jpeg(samples: &[u8], width: usize, height: usize, per_pixel: usize) -> Vec { + use image::ImageEncoder as _; + let colour = if per_pixel == 3 { image::ExtendedColorType::Rgb8 } else { image::ExtendedColorType::L8 }; + let mut j = Vec::new(); + let enc = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut j, 60); + enc.write_image(samples, width as u32, height as u32, colour).expect("jpeg segment"); + j +} + +/// How the DNG stores its raw data. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DngStorage { + /// One strip per `rows` rows, uncompressed at `bits` per sample (8, 12, 16…). + Strips { rows: usize }, + /// Adobe DNG compression 34892: baseline JPEG tiles at tile size (edge tiles padded), one + /// gray component for CFA and monochrome data, three (YCbCr-coded RGB) for LinearRaw. The + /// spec's `bits` should be 8 (the DNG spec's depth for lossy JPEG; the reader rejects others); + /// wider samples are written as their top 8 bits. Quality 60 leaves visible-but-mild artifacts. + LossyJpegTiles { width: usize, height: usize }, + /// Adobe DNG compression 34892 in strips of this many rows: each strip is a baseline JPEG + /// of the image width by the strip's own row count (the last strip is shorter). + LossyJpegStrips { rows: usize }, + /// Adobe DNG compression 8: zlib streams with the TIFF predictor (1 = none, 2 = horizontal + /// differencing) applied before compressing. + DeflateStrips { rows: usize, predictor: u16 }, + /// Lossless-JPEG tiles of this size (2 components per JPEG row, as Adobe writes CFA tiles). + Lj92Tiles { width: usize, height: usize }, + /// Lossless-JPEG strips of this many rows, 1 component. + Lj92Strips { rows: usize }, + /// JPEG XL strips of this many rows (Compression 52546): one codestream per strip, taken from + /// [`DngSpec::jxl_segments`] (the tests encode them; this crate has no JPEG XL encoder). + JxlStrips { rows: usize }, + /// JPEG XL tiles of this size, one codestream per tile in row-major order from + /// [`DngSpec::jxl_segments`]. + JxlTiles { width: usize, height: usize }, +} + +/// A synthetic DNG. +#[derive(Debug, Clone)] +pub struct DngSpec { + pub width: usize, + pub height: usize, + /// 1 (CFA, or monochrome LinearRaw with `monochrome`) or 3 (LinearRaw). + pub samples: usize, + /// With `samples` 1: a monochrome LinearRaw image (no CFA tags) instead of CFA data. + pub monochrome: bool, + /// Row-major samples (`width * height * samples`). + pub data: Vec, + pub bits: u16, + pub cfa: [u8; 4], + pub storage: DngStorage, + pub big_endian: bool, + pub black: Vec, + pub black_repeat: (u16, u16), + /// WhiteLevel; 0 leaves the tag out (the reader then defaults to the bit depth's maximum). + pub white: u32, + /// top, left, bottom, right + pub active_area: Option<[u32; 4]>, + /// origin (x, y), size (w, h), relative to the active area + pub default_crop: Option<([u32; 2], [u32; 2])>, + /// Double-precision origin override for malformed-metadata regression tests. + pub default_crop_origin_double: Option<[f64; 2]>, + /// A DefaultCropSize with no DefaultCropOrigin (`default_crop` must be `None`). + pub default_crop_size_only: Option<[u32; 2]>, + pub linearization: Option>, + /// (illuminant code, ColorMatrix row-major) + pub color_matrix1: Option<(u16, [f64; 9])>, + pub color_matrix2: Option<(u16, [f64; 9])>, + pub forward_matrix1: Option<[f64; 9]>, + pub forward_matrix2: Option<[f64; 9]>, + pub as_shot_neutral: Option<[f64; 3]>, + pub baseline_exposure: Option, + /// Raw OpcodeList2 bytes (see [`gain_map_opcode_list`]). + pub opcode_list2: Option>, + /// Encoded segments for [`DngStorage::JxlStrips`] / [`DngStorage::JxlTiles`]. + pub jxl_segments: Vec>, + /// Pre-encoded segments for [`DngStorage::LossyJpegTiles`] / [`DngStorage::LossyJpegStrips`] + /// (row-major), used instead of encoding `data` where present: for tiles that disagree with + /// the IFD (hostile-input tests). + pub lossy_segments: Vec>, + /// Raw ProfileGainTableMap bytes, written to IFD0 (contents are not interpreted). + pub profile_gain_table_map: Option>, + pub orientation: u16, + pub make: String, + pub model: String, + /// Extra IFD0 entries, written after the generated ones (e.g. malformed colour tags). + pub ifd0_extra: Vec<(u16, Val)>, + /// Extra raw-IFD entries, written after the generated ones (e.g. SampleFormat). + pub raw_extra: Vec<(u16, Val)>, +} + +impl DngSpec { + /// A CFA DNG with default metadata around `data` (RGGB, 16-bit, one strip). + pub fn cfa(width: usize, height: usize, data: Vec) -> Self { + DngSpec { + width, + height, + samples: 1, + monochrome: false, + data, + bits: 16, + cfa: [0, 1, 1, 2], + storage: DngStorage::Strips { rows: height }, + big_endian: false, + black: vec![0], + black_repeat: (1, 1), + white: 65535, + active_area: None, + default_crop: None, + default_crop_origin_double: None, + default_crop_size_only: None, + linearization: None, + color_matrix1: None, + color_matrix2: None, + forward_matrix1: None, + forward_matrix2: None, + as_shot_neutral: None, + baseline_exposure: None, + orientation: 1, + opcode_list2: None, + jxl_segments: Vec::new(), + lossy_segments: Vec::new(), + profile_gain_table_map: None, + make: "Photocraft".into(), + model: "Synthetic".into(), + ifd0_extra: Vec::new(), + raw_extra: Vec::new(), + } + } + + /// A monochrome (one-sample LinearRaw) DNG around `data`, as monochrome cameras and film + /// scanners write them: no CFA tags and no colour matrices. + pub fn monochrome(width: usize, height: usize, data: Vec) -> Self { + DngSpec { monochrome: true, ..Self::cfa(width, height, data) } + } + + fn is_cfa(&self) -> bool { + self.samples == 1 && !self.monochrome + } + + /// The 8-bit sample a lossy JPEG segment stores for `v`: the value itself at 8 bits, else + /// its top 8 bits. + fn sample8(&self, v: u16) -> u8 { + (v >> self.bits.saturating_sub(8)) as u8 + } + + fn pack(&self, rows: std::ops::Range) -> Vec { + let n = self.width * self.samples; + let vals = &self.data[rows.start * n..rows.end * n]; + match self.bits { + 8 => vals.iter().map(|&v| v as u8).collect(), + 16 => vals.iter().flat_map(|&v| if self.big_endian { v.to_be_bytes() } else { v.to_le_bytes() }).collect(), + b => { + // MSB-first bit packing, each row padded to a byte. + let mut out = Vec::new(); + for row in vals.chunks(n) { + let mut acc: u64 = 0; + let mut have = 0u32; + for &v in row { + acc = (acc << b) | u64::from(v); + have += u32::from(b); + while have >= 8 { + have -= 8; + out.push((acc >> have) as u8); + } + } + if have > 0 { + out.push((acc << (8 - have)) as u8); + } + } + out + } + } + } + + pub fn build(&self) -> Vec { + let mut t = TiffBuilder { big_endian: self.big_endian, ..Default::default() }; + let mut raw: Vec<(u16, Val)> = vec![ + (254, Val::Long(vec![0])), + (256, Val::Long(vec![self.width as u32])), + (257, Val::Long(vec![self.height as u32])), + (258, Val::Short(vec![self.bits; self.samples])), + (262, Val::Short(vec![if self.is_cfa() { 32803 } else { 34892 }])), + (277, Val::Short(vec![self.samples as u16])), + (284, Val::Short(vec![1])), + (50713, Val::Short(vec![self.black_repeat.0, self.black_repeat.1])), + (50714, Val::Long(self.black.clone())), + ]; + if self.white != 0 { + raw.push((50717, Val::Long(vec![self.white; self.samples]))); + } + if self.is_cfa() { + raw.push((33421, Val::Short(vec![2, 2]))); + raw.push((33422, Val::Byte(self.cfa.to_vec()))); + raw.push((50710, Val::Byte(vec![0, 1, 2]))); + raw.push((50711, Val::Short(vec![1]))); + } + match self.storage { + DngStorage::DeflateStrips { rows, predictor } => { + use std::io::Write; + let mut offs = Vec::new(); + let mut lens = Vec::new(); + for y in (0..self.height).step_by(rows) { + let r = (y + rows).min(self.height) - y; + let n = self.width * self.samples; + let mut v: Vec = self.data[y * n..(y + r) * n].to_vec(); + if predictor == 2 { + // Horizontal differencing on the sample values, before byte packing + // (the reader undoes predictor after unpacking, per row, per channel). + let plane = if self.samples.is_multiple_of(3) { 3 } else { 1 }; + for row in v.chunks_mut(n) { + for i in (plane..row.len()).rev() { + row[i] = row[i].wrapping_sub(row[i - plane]); + } + } + } + // Pack the delta'd values with the file's byte order and bit depth. + let bytes: Vec = match self.bits { + 8 => v.iter().map(|&x| x as u8).collect(), + 16 => v.iter().flat_map(|&x| if self.big_endian { x.to_be_bytes() } else { x.to_le_bytes() }).collect(), + _ => v.iter().flat_map(|x| x.to_le_bytes()).collect(), + }; + let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default()); + e.write_all(&bytes).expect("zlib"); + let z = e.finish().expect("zlib"); + lens.push(z.len() as u32); + offs.push(t.blob(z)); + } + raw.push((259, Val::Short(vec![8]))); + raw.push((317, Val::Short(vec![predictor]))); + raw.push((278, Val::Long(vec![rows as u32]))); + raw.push((273, Val::Blobs(offs))); + raw.push((279, Val::Long(lens))); + } + DngStorage::Strips { rows } => { + let mut offs = Vec::new(); + let mut lens = Vec::new(); + for y in (0..self.height).step_by(rows) { + let b = self.pack(y..(y + rows).min(self.height)); + lens.push(b.len() as u32); + offs.push(t.blob(b)); + } + raw.push((259, Val::Short(vec![1]))); + raw.push((278, Val::Long(vec![rows as u32]))); + raw.push((273, Val::Blobs(offs))); + raw.push((279, Val::Long(lens))); + } + DngStorage::LossyJpegTiles { width: tw, height: th } => { + let mut offs = Vec::new(); + let mut lens = Vec::new(); + let s = self.samples; + for ty in (0..self.height).step_by(th) { + for tx in (0..self.width).step_by(tw) { + // Edge tiles are padded by repeating the last row / column. + let mut tile = vec![0u8; tw * th * s]; + for y in 0..th { + for x in 0..tw { + let sy = (ty + y).min(self.height - 1); + let sx = (tx + x).min(self.width - 1); + for c in 0..s { + tile[(y * tw + x) * s + c] = self.sample8(self.data[(sy * self.width + sx) * s + c]); + } + } + } + let j = self.lossy_segments.get(offs.len()).cloned().unwrap_or_else(|| baseline_jpeg(&tile, tw, th, s)); + lens.push(j.len() as u32); + offs.push(t.blob(j)); + } + } + raw.push((259, Val::Short(vec![34892]))); + raw.push((322, Val::Long(vec![tw as u32]))); + raw.push((323, Val::Long(vec![th as u32]))); + raw.push((324, Val::Blobs(offs))); + raw.push((325, Val::Long(lens))); + } + DngStorage::LossyJpegStrips { rows } => { + let mut offs = Vec::new(); + let mut lens = Vec::new(); + let n = self.width * self.samples; + for y in (0..self.height).step_by(rows) { + let r = (y + rows).min(self.height) - y; + let strip: Vec = self.data[y * n..(y + r) * n].iter().map(|&v| self.sample8(v)).collect(); + let j = self.lossy_segments.get(offs.len()).cloned().unwrap_or_else(|| baseline_jpeg(&strip, self.width, r, self.samples)); + lens.push(j.len() as u32); + offs.push(t.blob(j)); + } + raw.push((259, Val::Short(vec![34892]))); + raw.push((278, Val::Long(vec![rows as u32]))); + raw.push((273, Val::Blobs(offs))); + raw.push((279, Val::Long(lens))); + } + DngStorage::Lj92Strips { rows } => { + let mut offs = Vec::new(); + let mut lens = Vec::new(); + for y in (0..self.height).step_by(rows) { + let r = (y + rows).min(self.height) - y; + let n = self.width * self.samples; + let j = lj92_encode(&self.data[y * n..(y + r) * n], self.width, r, self.samples, self.bits as u8, 1, None); + lens.push(j.len() as u32); + offs.push(t.blob(j)); + } + raw.push((259, Val::Short(vec![7]))); + raw.push((278, Val::Long(vec![rows as u32]))); + raw.push((273, Val::Blobs(offs))); + raw.push((279, Val::Long(lens))); + } + DngStorage::Lj92Tiles { width: tw, height: th } => { + let mut offs = Vec::new(); + let mut lens = Vec::new(); + let s = self.samples; + for ty in (0..self.height).step_by(th) { + for tx in (0..self.width).step_by(tw) { + // Edge tiles are padded by repeating the last row / column. + let mut tile = vec![0u16; tw * th * s]; + for y in 0..th { + for x in 0..tw { + let sy = (ty + y).min(self.height - 1); + let sx = (tx + x).min(self.width - 1); + for c in 0..s { + tile[(y * tw + x) * s + c] = self.data[(sy * self.width + sx) * s + c]; + } + } + } + // CFA tiles as Adobe writes them: half width, 2 components. + let j = if s == 1 && tw % 2 == 0 { + lj92_encode(&tile, tw / 2, th, 2, self.bits as u8, 1, None) + } else { + lj92_encode(&tile, tw, th, s, self.bits as u8, 1, None) + }; + lens.push(j.len() as u32); + offs.push(t.blob(j)); + } + } + raw.push((259, Val::Short(vec![7]))); + raw.push((322, Val::Long(vec![tw as u32]))); + raw.push((323, Val::Long(vec![th as u32]))); + raw.push((324, Val::Blobs(offs))); + raw.push((325, Val::Long(lens))); + } + DngStorage::JxlStrips { rows } => { + let lens = self.jxl_segments.iter().map(|j| j.len() as u32).collect(); + let offs = self.jxl_segments.iter().map(|j| t.blob(j.clone())).collect(); + raw.push((259, Val::Short(vec![52546]))); + raw.push((278, Val::Long(vec![rows as u32]))); + raw.push((273, Val::Blobs(offs))); + raw.push((279, Val::Long(lens))); + } + DngStorage::JxlTiles { width: tw, height: th } => { + let lens = self.jxl_segments.iter().map(|j| j.len() as u32).collect(); + let offs = self.jxl_segments.iter().map(|j| t.blob(j.clone())).collect(); + raw.push((259, Val::Short(vec![52546]))); + raw.push((322, Val::Long(vec![tw as u32]))); + raw.push((323, Val::Long(vec![th as u32]))); + raw.push((324, Val::Blobs(offs))); + raw.push((325, Val::Long(lens))); + } + } + if let Some(a) = self.active_area { + raw.push((50829, Val::Long(a.to_vec()))); + } + if let Some((o, s)) = self.default_crop { + let origin = self.default_crop_origin_double.map(|d| Val::Double(d.to_vec())).unwrap_or_else(|| Val::Long(o.to_vec())); + raw.push((50719, origin)); + raw.push((50720, Val::Long(s.to_vec()))); + } else if let Some(origin) = self.default_crop_origin_double { + raw.push((50719, Val::Double(origin.to_vec()))); + } else if let Some(size) = self.default_crop_size_only { + raw.push((50720, Val::Long(size.to_vec()))); + } + if let Some(o) = &self.opcode_list2 { + raw.push((51009, Val::Undefined(o.clone()))); + } + if let Some(l) = &self.linearization { + raw.push((50712, Val::Short(l.clone()))); + } + raw.extend(self.raw_extra.iter().cloned()); + let raw_ifd = t.ifd(raw); + // IFD0: a tiny RGB thumbnail plus the DNG metadata. + let thumb = t.blob(vec![128; 3 * 4]); + let mut ifd0: Vec<(u16, Val)> = vec![ + (254, Val::Long(vec![1])), + (256, Val::Long(vec![2])), + (257, Val::Long(vec![2])), + (258, Val::Short(vec![8, 8, 8])), + (259, Val::Short(vec![1])), + (262, Val::Short(vec![2])), + (271, Val::Ascii(self.make.clone())), + (272, Val::Ascii(self.model.clone())), + (273, Val::Blobs(vec![thumb])), + (274, Val::Short(vec![self.orientation])), + (277, Val::Short(vec![3])), + (278, Val::Long(vec![2])), + (279, Val::Long(vec![12])), + (330, Val::Ifds(vec![raw_ifd])), + (50706, Val::Byte(vec![1, 4, 0, 0])), + (50708, Val::Ascii(format!("{} {}", self.make, self.model))), + ]; + let m = |v: &[f64; 9]| Val::SRational(v.iter().map(|&x| srat(x)).collect()); + if let Some((ill, cm)) = &self.color_matrix1 { + ifd0.push((50721, m(cm))); + ifd0.push((50778, Val::Short(vec![*ill]))); + } + if let Some((ill, cm)) = &self.color_matrix2 { + ifd0.push((50722, m(cm))); + ifd0.push((50779, Val::Short(vec![*ill]))); + } + if let Some(f) = &self.forward_matrix1 { + ifd0.push((50964, m(f))); + } + if let Some(f) = &self.forward_matrix2 { + ifd0.push((50965, m(f))); + } + if let Some(n) = self.as_shot_neutral { + ifd0.push((50728, Val::Rational(n.iter().map(|&v| urat(v)).collect()))); + } + if let Some(b) = self.baseline_exposure { + ifd0.push((50730, Val::SRational(vec![srat(b)]))); + } + if let Some(m) = &self.profile_gain_table_map { + ifd0.push((52525, Val::Undefined(m.clone()))); + } + ifd0.extend(self.ifd0_extra.iter().cloned()); + let i0 = t.ifd(ifd0); + t.chain = vec![i0]; + t.build() + } +} + +/// An OpcodeList2 with one GainMap over active-area rectangle `area` (top, +/// left, bottom, right), every `pitch` rows and columns, from a 2×2 grid of +/// gains spanning the image (relative coordinates 0..1). +pub fn gain_map_opcode_list(area: [u32; 4], pitch: u32, gains: [[f32; 2]; 2]) -> Vec { + let mut p = Vec::new(); + for v in [area[0], area[1], area[2], area[3], 0, 1, pitch, pitch, 2, 2] { + p.extend_from_slice(&v.to_be_bytes()); + } + for v in [1.0f64, 1.0, 0.0, 0.0] { + p.extend_from_slice(&v.to_be_bytes()); + } + p.extend_from_slice(&1u32.to_be_bytes()); + for g in gains.iter().flatten() { + p.extend_from_slice(&g.to_bits().to_be_bytes()); + } + let mut b = 1u32.to_be_bytes().to_vec(); + for v in [9u32, 0x0103_0000, 1, p.len() as u32] { + b.extend_from_slice(&v.to_be_bytes()); + } + b.extend_from_slice(&p); + b +} + +/// An opcode list of MapPolynomial opcodes (ID 8), one per `(plane, coefficients)`, each over +/// `area` (top, left, bottom, right) at pitch 1. +pub fn map_polynomial_opcode_list(area: [u32; 4], planes: &[(u32, Vec)]) -> Vec { + let mut b = (planes.len() as u32).to_be_bytes().to_vec(); + for (plane, coefficients) in planes { + let mut p = Vec::new(); + let degree = coefficients.len().saturating_sub(1) as u32; + for v in [area[0], area[1], area[2], area[3], *plane, 1, 1, 1, degree] { + p.extend_from_slice(&v.to_be_bytes()); + } + for c in coefficients { + p.extend_from_slice(&c.to_be_bytes()); + } + for v in [8u32, 0x0103_0000, 0, p.len() as u32] { + b.extend_from_slice(&v.to_be_bytes()); + } + b.extend_from_slice(&p); + } + b +} diff --git a/crates/raw/src/testgen/lj92.rs b/crates/raw/src/testgen/lj92.rs new file mode 100644 index 0000000000..379d8dfdd0 --- /dev/null +++ b/crates/raw/src/testgen/lj92.rs @@ -0,0 +1,183 @@ +/// Huffman code lengths assigned to categories in decreasing frequency +/// order. Kraft sum < 1 and no code is all ones. +const LENGTHS: [u8; 17] = [2, 3, 3, 3, 4, 4, 5, 5, 6, 6, 7, 8, 9, 10, 11, 12, 13]; + +fn category(d: i32) -> u32 { + if d == 0 { + 0 + } else if d == 32768 { + 16 + } else { + 32 - d.unsigned_abs().leading_zeros() + } +} + +struct BitWriter { + out: Vec, + acc: u32, + n: u32, +} + +impl BitWriter { + fn put(&mut self, v: u32, bits: u32) { + for i in (0..bits).rev() { + self.acc = (self.acc << 1) | ((v >> i) & 1); + self.n += 1; + if self.n == 8 { + let b = self.acc as u8; + self.out.push(b); + if b == 0xFF { + self.out.push(0); + } + self.acc = 0; + self.n = 0; + } + } + } + fn flush(&mut self) { + if self.n > 0 { + let pad = 8 - self.n; + self.put((1 << pad) - 1, pad); + } + } +} + +/// Encodes `samples` (raster order, `components` interleaved, values below +/// `2^precision`) as a lossless JPEG with the given predictor (1–7) and an +/// optional restart interval in rows. All components share one Huffman table. +pub fn lj92_encode(samples: &[u16], width: usize, height: usize, components: usize, precision: u8, predictor: u8, restart_rows: Option) -> Vec { + lj92_encode_tables(samples, width, height, &vec![0; components], precision, predictor, restart_rows) +} + +/// Like [`lj92_encode`], but component `c` uses Huffman table `table_of[c]` +/// (0–3; the component count is `table_of.len()`), one DHT per table id as +/// CR2 writes them. Table `t` assigns its code lengths rotated by `t`, so the +/// tables differ even when their statistics match. +pub fn lj92_encode_tables(samples: &[u16], width: usize, height: usize, table_of: &[u8], precision: u8, predictor: u8, restart_rows: Option) -> Vec { + let components = table_of.len(); + assert_eq!(samples.len(), width * height * components); + assert!(table_of.iter().all(|&t| t < 4)); + let row = width * components; + let interval = restart_rows.unwrap_or(usize::MAX); + // Differences per sample, following T.81 H.1.2.1 prediction rules. + let mut diffs = Vec::with_capacity(samples.len()); + let initial = 1i32 << (precision - 1); + for y in 0..height { + let first_line = y % interval == 0; + for x in 0..width { + for c in 0..components { + let i = y * row + x * components + c; + let px = if x == 0 { + if first_line { initial } else { i32::from(samples[i - row]) } + } else if first_line { + i32::from(samples[i - components]) + } else { + let ra = i32::from(samples[i - components]); + let rb = i32::from(samples[i - row]); + let rc = i32::from(samples[i - row - components]); + match predictor { + 1 => ra, + 2 => rb, + 3 => rc, + 4 => ra + rb - rc, + 5 => ra + ((rb - rc) >> 1), + 6 => rb + ((ra - rc) >> 1), + _ => (ra + rb) >> 1, + } + }; + let mut d = (i32::from(samples[i]) - px) & 0xFFFF; + if d > 32768 { + d -= 65536; + } + diffs.push(d); + } + } + } + // Tables: categories ordered by frequency get increasing code lengths. + let mut ids: Vec = table_of.to_vec(); + ids.sort_unstable(); + ids.dedup(); + let mut code_of = [[(0u32, 0u32); 17]; 4]; + let mut dhts = Vec::new(); + for &t in &ids { + let mut freq = [0usize; 17]; + for (i, &d) in diffs.iter().enumerate() { + if table_of[i % components] == t { + freq[category(d) as usize] += 1; + } + } + let mut order: Vec = (0..17).collect(); + order.sort_by_key(|&c| std::cmp::Reverse(freq[c])); + order.rotate_left(usize::from(t)); + let mut len_of = [0u8; 17]; + for (rank, &c) in order.iter().enumerate() { + len_of[c] = LENGTHS[rank]; + } + let mut counts = [0u8; 16]; + let mut vals: Vec = Vec::new(); + let mut code = 0u32; + for len in 1..=16u8 { + for c in 0..17 { + if len_of[c] == len { + counts[len as usize - 1] += 1; + vals.push(c as u8); + code_of[usize::from(t)][c] = (code, u32::from(len)); + code += 1; + } + } + code <<= 1; + } + dhts.push((t, counts, vals)); + } + let mut out = vec![0xFF, 0xD8]; + // SOF3 + out.extend_from_slice(&[0xFF, 0xC3]); + out.extend_from_slice(&((8 + 3 * components) as u16).to_be_bytes()); + out.push(precision); + out.extend_from_slice(&(height as u16).to_be_bytes()); + out.extend_from_slice(&(width as u16).to_be_bytes()); + out.push(components as u8); + for c in 0..components { + out.extend_from_slice(&[c as u8 + 1, 0x11, 0]); + } + // DHT, one per table id + for (t, counts, vals) in &dhts { + out.extend_from_slice(&[0xFF, 0xC4]); + out.extend_from_slice(&((2 + 17 + vals.len()) as u16).to_be_bytes()); + out.push(*t); + out.extend_from_slice(counts); + out.extend_from_slice(vals); + } + if let Some(r) = restart_rows { + out.extend_from_slice(&[0xFF, 0xDD, 0, 4]); + out.extend_from_slice(&((r * width) as u16).to_be_bytes()); + } + // SOS + out.extend_from_slice(&[0xFF, 0xDA]); + out.extend_from_slice(&((6 + 2 * components) as u16).to_be_bytes()); + out.push(components as u8); + for (c, &t) in table_of.iter().enumerate() { + out.extend_from_slice(&[c as u8 + 1, t << 4]); + } + out.extend_from_slice(&[predictor, 0, 0]); + let mut w = BitWriter { out, acc: 0, n: 0 }; + let mut rst = 0u8; + for (i, &d) in diffs.iter().enumerate() { + if i > 0 && i % (interval.saturating_mul(row)) == 0 { + w.flush(); + w.out.extend_from_slice(&[0xFF, 0xD0 + rst]); + rst = (rst + 1) % 8; + } + let s = category(d); + let (c, l) = code_of[usize::from(table_of[i % components])][s as usize]; + w.put(c, l); + if (1..16).contains(&s) { + let extra = if d < 0 { (d - 1) as u32 & ((1 << s) - 1) } else { d as u32 }; + w.put(extra, s); + } + } + w.flush(); + let mut out = w.out; + out.extend_from_slice(&[0xFF, 0xD9]); + out +} diff --git a/crates/raw/src/testgen/orf.rs b/crates/raw/src/testgen/orf.rs new file mode 100644 index 0000000000..1c056ade63 --- /dev/null +++ b/crates/raw/src/testgen/orf.rs @@ -0,0 +1,93 @@ +use super::tiff::{TiffBuilder, Val}; + +// ---------------------------------------------------------------- Olympus ORF + +/// A little-endian IFD whose value offsets are relative to `base` (the IFD +/// itself sits at `base_offset` from that base). Entries: (tag, type, count, +/// value bytes). +fn relative_ifd(entries: &[(u16, u16, u32, Vec)], base_offset: usize) -> Vec { + let head = 2 + 12 * entries.len() + 4; + let mut out = Vec::new(); + let mut extra = Vec::new(); + out.extend_from_slice(&(entries.len() as u16).to_le_bytes()); + for (tag, typ, count, bytes) in entries { + out.extend_from_slice(&tag.to_le_bytes()); + out.extend_from_slice(&typ.to_le_bytes()); + out.extend_from_slice(&count.to_le_bytes()); + if bytes.len() <= 4 { + let mut v = bytes.clone(); + v.resize(4, 0); + out.extend_from_slice(&v); + } else { + out.extend_from_slice(&((base_offset + head + extra.len()) as u32).to_le_bytes()); + extra.extend_from_slice(bytes); + } + } + out.extend_from_slice(&0u32.to_le_bytes()); + out.extend_from_slice(&extra); + out +} + +fn shorts(v: &[u16]) -> Vec { + v.iter().flat_map(|x| x.to_le_bytes()).collect() +} + +/// A synthetic uncompressed Olympus ORF (`IIRO`): 12-bit `data` stored +/// left-justified in 16-bit samples, a GRBG EXIF CFAPattern and a new-style +/// maker note with ImageProcessing levels (black 64, WB 2.0 / 1.5, crop of a +/// 2-pixel border) and CameraSettings pointing at a tiny preview JPEG. +pub fn orf(width: usize, height: usize, data: &[u16]) -> Vec { + let ip = relative_ifd( + &[ + (0x0100, 3, 2, shorts(&[512, 384])), + (0x011F, 3, 1, shorts(&[256])), + (0x0600, 3, 4, shorts(&[64, 64, 64, 64])), + (0x0611, 3, 2, shorts(&[12, 0])), + (0x0612, 3, 2, shorts(&[2, 0])), + (0x0613, 3, 2, shorts(&[2, 0])), + (0x0614, 4, 1, ((width - 4) as u32).to_le_bytes().to_vec()), + (0x0615, 4, 1, ((height - 4) as u32).to_le_bytes().to_vec()), + ], + 64, + ); + // CameraSettings with a preview JPEG (SOI, SOF0 16×8, EOI) right after it. + let jpeg = [0xFF, 0xD8, 0xFF, 0xC0, 0x00, 0x0B, 8, 0x00, 0x08, 0x00, 0x10, 1, 1, 0x11, 0, 0xFF, 0xD9]; + let cs_at = 64 + ip.len().next_multiple_of(4); + let cs_len = 2 + 12 * 3 + 4; + let cs = relative_ifd( + &[ + (0x0100, 4, 1, 1u32.to_le_bytes().to_vec()), + (0x0101, 4, 1, ((cs_at + cs_len) as u32).to_le_bytes().to_vec()), + (0x0102, 4, 1, (jpeg.len() as u32).to_le_bytes().to_vec()), + ], + cs_at, + ); + let mut note = b"OLYMPUS\0II\x03\0".to_vec(); + note.extend_from_slice(&relative_ifd(&[(0x2020, 13, 1, (cs_at as u32).to_le_bytes().to_vec()), (0x2040, 13, 1, 64u32.to_le_bytes().to_vec())], 12)); + note.resize(64, 0); + note.extend_from_slice(&ip); + note.resize(cs_at, 0); + note.extend_from_slice(&cs); + note.extend_from_slice(&jpeg); + let mut t = TiffBuilder::default(); + let strip = t.blob(data.iter().flat_map(|v| (v << 4).to_le_bytes()).collect()); + let exif = t.ifd(vec![(37500, Val::Undefined(note)), (41730, Val::Undefined(vec![2, 0, 2, 0, 1, 0, 2, 1]))]); + let ifd0 = t.ifd(vec![ + (256, Val::Long(vec![width as u32])), + (257, Val::Long(vec![height as u32])), + (258, Val::Short(vec![16])), + (259, Val::Short(vec![1])), + (262, Val::Short(vec![1])), + (271, Val::Ascii("OLYMPUS IMAGING CORP.".into())), + (272, Val::Ascii("E-Synthetic".into())), + (273, Val::Blobs(vec![strip])), + (277, Val::Short(vec![1])), + (278, Val::Long(vec![height as u32])), + (279, Val::Long(vec![(data.len() * 2) as u32])), + (34665, Val::Ifds(vec![exif])), + ]); + t.chain = vec![ifd0]; + let mut b = t.build(); + b[2..4].copy_from_slice(b"RO"); + b +} diff --git a/crates/raw/src/testgen/raf.rs b/crates/raw/src/testgen/raf.rs new file mode 100644 index 0000000000..d680a1db7c --- /dev/null +++ b/crates/raw/src/testgen/raf.rs @@ -0,0 +1,279 @@ +use super::tiff::{TiffBuilder, Val}; + +// ---------------------------------------------------------------- Fujifilm RAF + +/// How a synthetic RAF stores its samples (see `raf.rs`). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RafPacking { + /// 16-bit containers; little-endian (`II`) or big-endian (`MM`) CFA TIFF. + U16 { le: bool }, + /// 12-bit, little-endian bit stream, least significant bit first. + Lsb12, + /// 14-bit, most significant bit first in little-endian 32-bit words. + Words14, + /// A short `IS…` strip standing in for Fujifilm's compressed data. + Compressed, +} + +/// The X-Trans repeat at the data origin, as observed (row major, 0 = R, 1 = G, 2 = B). +pub const XTRANS: [u8; 36] = [ + 1, 1, 0, 1, 1, 2, // + 1, 1, 2, 1, 1, 0, // + 2, 0, 1, 0, 2, 1, // + 1, 1, 2, 1, 1, 0, // + 1, 1, 0, 1, 1, 2, // + 0, 2, 1, 2, 0, 1, +]; + +/// A synthetic Fujifilm RAF. +#[derive(Debug, Clone)] +pub struct RafSpec { + pub width: usize, + pub height: usize, + pub data: Vec, + pub bits: u32, + pub packing: RafPacking, + /// CFA colours at the data origin: 36 (X-Trans, 6×6) or 4 (Bayer, 2×2), row major. + pub cfa: Vec, + /// RawImageCropTopLeft / RawImageCroppedSize: top, left, height, width. + pub crop: Option<[u16; 4]>, + pub black: Vec, + /// WB_GRBLevels: G, R, B. + pub wb_grb: Option<[u32; 3]>, + /// RawExposureBias as numerator / denominator. + pub exposure_bias: Option<(i16, i16)>, + /// EXIF orientation of the preview JPEG. + pub orientation: u16, + /// `false` writes an early-FinePix-style file without the CFA TIFF. + pub cfa_tiff: bool, +} + +impl RafSpec { + pub fn new(width: usize, height: usize, data: Vec, cfa: Vec) -> Self { + RafSpec { + width, + height, + data, + bits: 14, + packing: RafPacking::U16 { le: true }, + cfa, + crop: None, + black: vec![1024], + wb_grb: Some([302, 604, 453]), + exposure_bias: None, + orientation: 1, + cfa_tiff: true, + } + } + + /// The samples as stored. + fn strip(&self) -> Vec { + match self.packing { + RafPacking::U16 { le } => self.data.iter().flat_map(|v| if le { v.to_le_bytes() } else { v.to_be_bytes() }).collect(), + RafPacking::Lsb12 => { + let (mut out, mut acc, mut n) = (Vec::new(), 0u64, 0u32); + for &v in &self.data { + acc |= u64::from(v & 0xFFF) << n; + n += 12; + while n >= 8 { + out.push(acc as u8); + acc >>= 8; + n -= 8; + } + } + if n > 0 { + out.push(acc as u8); + } + out + } + RafPacking::Words14 => { + let (mut logical, mut acc, mut n) = (Vec::new(), 0u64, 0u32); + for &v in &self.data { + acc = (acc << 14) | u64::from(v & 0x3FFF); + n += 14; + while n >= 8 { + logical.push((acc >> (n - 8)) as u8); + n -= 8; + } + } + if n > 0 { + logical.push((acc << (8 - n)) as u8); + } + logical.resize(logical.len().next_multiple_of(4), 0); + logical.chunks(4).flat_map(|w| w.iter().rev().copied().collect::>()).collect() + } + RafPacking::Compressed => { + let mut v = b"IS\x01\x00".to_vec(); + v.resize(self.width * self.height / 2, 0x5A); + v + } + } + } + + /// The CFA region: a TIFF whose IFD0 points (0xF000) at the Fuji raw IFD. + fn cfa_region(&self) -> Vec { + let le = !matches!(self.packing, RafPacking::U16 { le: false }); + let u16b = |v: u16| if le { v.to_le_bytes() } else { v.to_be_bytes() }; + let u32b = |v: u32| if le { v.to_le_bytes() } else { v.to_be_bytes() }; + let strip = self.strip(); + let strip_at = 2048u32; + let entries: Vec<(u16, Vec)> = vec![ + (0xF001, vec![self.width as u32]), + (0xF002, vec![self.height as u32]), + (0xF003, vec![self.bits]), + (0xF007, vec![strip_at]), + (0xF008, vec![strip.len() as u32]), + (0xF00A, self.black.clone()), + ] + .into_iter() + .chain(self.wb_grb.map(|w| (0xF00E, w.to_vec()))) + .collect(); + let mut out = if le { b"II*\0".to_vec() } else { b"MM\0*".to_vec() }; + out.extend_from_slice(&u32b(8)); + // IFD0: one entry, 0xF000 (type IFD) → the Fuji IFD at 26. + out.extend_from_slice(&u16b(1)); + out.extend_from_slice(&u16b(0xF000)); + out.extend_from_slice(&u16b(13)); + out.extend_from_slice(&u32b(1)); + out.extend_from_slice(&u32b(26)); + out.extend_from_slice(&u32b(0)); + let fuji_at = out.len(); + let mut extra_at = fuji_at + 2 + 12 * entries.len() + 4; + let mut extra = Vec::new(); + out.extend_from_slice(&u16b(entries.len() as u16)); + for (tag, vals) in &entries { + out.extend_from_slice(&u16b(*tag)); + out.extend_from_slice(&u16b(4)); + out.extend_from_slice(&u32b(vals.len() as u32)); + if vals.len() == 1 { + out.extend_from_slice(&u32b(vals[0])); + } else { + out.extend_from_slice(&u32b(extra_at as u32)); + for v in vals { + extra.extend_from_slice(&u32b(*v)); + } + extra_at += 4 * vals.len(); + } + } + out.extend_from_slice(&u32b(0)); + out.extend_from_slice(&extra); + assert!(out.len() <= strip_at as usize); + out.resize(strip_at as usize, 0); + out.extend_from_slice(&strip); + out + } + + /// A tiny baseline-JPEG preview (APP1 EXIF with make, model and + /// orientation; SOF0 32×24; EOI). + fn preview(&self) -> Vec { + let mut t = TiffBuilder::default(); + let ifd0 = t.ifd(vec![(271, Val::Ascii("FUJIFILM".into())), (272, Val::Ascii("X-Synthetic".into())), (274, Val::Short(vec![self.orientation]))]); + t.chain = vec![ifd0]; + let mut app1 = b"Exif\0\0".to_vec(); + app1.extend_from_slice(&t.build()); + let mut j = vec![0xFF, 0xD8, 0xFF, 0xE1]; + j.extend_from_slice(&((app1.len() + 2) as u16).to_be_bytes()); + j.extend_from_slice(&app1); + j.extend_from_slice(&[0xFF, 0xC0, 0x00, 0x0B, 8, 0x00, 24, 0x00, 32, 1, 1, 0x11, 0, 0xFF, 0xD9]); + j + } + + /// The metadata directory. + fn meta(&self) -> Vec { + let mut recs: Vec<(u16, Vec)> = Vec::new(); + if let Some([top, left, h, w]) = self.crop { + recs.push((0x0110, [top.to_be_bytes(), left.to_be_bytes()].concat())); + recs.push((0x0111, [h.to_be_bytes(), w.to_be_bytes()].concat())); + } + if self.cfa.len() == 36 { + recs.push((0x0130, vec![0x0C; 4])); + recs.push((0x0131, self.cfa.iter().rev().copied().collect())); + } else { + // Bayer: reversed, colour in the low two bits, the second green as 3. + let mut greens = 0; + let codes: Vec = self + .cfa + .iter() + .map(|&c| { + if c == 1 { + greens += 1; + if greens == 1 { 0x09 } else { 0x0B } + } else { + 0x08 | c + } + }) + .collect(); + recs.push((0x0130, codes.into_iter().rev().collect())); + } + if let Some((n, d)) = self.exposure_bias { + recs.push((0x9650, [n.to_be_bytes(), d.to_be_bytes()].concat())); + } + let mut out = (recs.len() as u32).to_be_bytes().to_vec(); + for (tag, d) in recs { + out.extend_from_slice(&tag.to_be_bytes()); + out.extend_from_slice(&(d.len() as u16).to_be_bytes()); + out.extend_from_slice(&d); + } + out + } + + pub fn build(&self) -> Vec { + let mut b = b"FUJIFILMCCD-RAW 0201FF000000".to_vec(); + b.extend_from_slice(b"X-Synthetic"); + b.resize(60, 0); + b.extend_from_slice(b"0100"); + b.resize(160, 0); + let preview = self.preview(); + let meta = self.meta(); + let region = if self.cfa_tiff { self.cfa_region() } else { self.strip() }; + let (p_at, m_at) = (b.len(), b.len() + preview.len()); + let c_at = m_at + meta.len(); + for (at, v) in [(84, p_at), (88, preview.len()), (92, m_at), (96, meta.len()), (100, c_at), (104, region.len())] { + b[at..at + 4].copy_from_slice(&(v as u32).to_be_bytes()); + } + b.extend_from_slice(&preview); + b.extend_from_slice(&meta); + b.extend_from_slice(®ion); + b + } +} + +/// Mosaics linear RGB through any CFA repeat (`cfa`: `cfa_w` colours per +/// row) anchored at (0, 0), like [`mosaic`]. +pub fn mosaic_cfa(rgb: &[[f32; 3]], width: usize, cfa: &[u8], cfa_w: usize, black: u16, white: u16) -> Vec { + let cfa_h = cfa.len() / cfa_w; + rgb.iter() + .enumerate() + .map(|(i, p)| { + let (x, y) = (i % width, i / width); + let c = cfa[(y % cfa_h) * cfa_w + x % cfa_w] as usize; + (f32::from(black) + p[c].clamp(0.0, 1.0) * f32::from(white - black)).round() as u16 + }) + .collect() +} + +// ---------------------------------------------------------------- scenes + +/// A smooth, colourful synthetic scene as linear RGB in 0..1. +pub fn scene(width: usize, height: usize) -> Vec<[f32; 3]> { + (0..width * height) + .map(|i| { + let (x, y) = ((i % width) as f32 / width.max(1) as f32, (i / width) as f32 / height.max(1) as f32); + [0.1 + 0.7 * x, 0.15 + 0.5 * (1.0 - y) * x + 0.2 * y, 0.6 - 0.4 * y + 0.2 * x] + }) + .collect() +} + +/// Mosaics linear RGB through a 2×2 CFA (`cfa` row-major colours) into +/// sensor values `black + v * (white - black)`. +pub fn mosaic(rgb: &[[f32; 3]], width: usize, cfa: [u8; 4], black: u16, white: u16) -> Vec { + rgb.iter() + .enumerate() + .map(|(i, p)| { + let (x, y) = (i % width, i / width); + let c = cfa[(y & 1) * 2 + (x & 1)] as usize; + let v = p[c].clamp(0.0, 1.0); + (f32::from(black) + v * f32::from(white - black)).round() as u16 + }) + .collect() +} diff --git a/crates/raw/src/testgen/rw2.rs b/crates/raw/src/testgen/rw2.rs new file mode 100644 index 0000000000..8dedfad007 --- /dev/null +++ b/crates/raw/src/testgen/rw2.rs @@ -0,0 +1,198 @@ +use super::tiff::{TiffBuilder, Val}; + +// ---------------------------------------------------------------- Panasonic RW2 + +/// Page size and split point of the RW2 stream (see `rw2.rs`). +const RW2_PAGE: usize = 0x4000; + +const RW2_SPLIT: usize = 0x1FF8; + +/// Packs `bits`-bit samples (12: 10 per block, 14: 9 per block) into the RW2 +/// RawFormat 5 layout: 16-byte little-endian blocks, stored in 0x4000-byte +/// pages split at 0x1FF8. +pub fn rw2_pack(data: &[u16], width: usize, bits: u32) -> Vec { + let ppb = if bits == 14 { 9 } else { 10 }; + assert_eq!(width % ppb, 0); + let mut logical = Vec::new(); + for px in data.chunks_exact(ppb) { + let mut v: u128 = 0; + for (i, &p) in px.iter().enumerate() { + v |= u128::from(p & ((1 << bits) - 1)) << (bits as usize * i); + } + logical.extend_from_slice(&v.to_le_bytes()); + } + logical.resize(logical.len().div_ceil(RW2_PAGE) * RW2_PAGE, 0); + let mut out = vec![0u8; logical.len()]; + for (i, &b) in logical.iter().enumerate() { + let page = i - i % RW2_PAGE; + out[page + (i % RW2_PAGE + RW2_SPLIT) % RW2_PAGE] = b; + } + out +} + +/// A synthetic Panasonic RW2 (RawFormat 5) with an RGGB sensor, a 2-pixel +/// border on every side, black levels 128 / 129 / 130 and WB levels +/// 512 / 256 / 384. +pub fn rw2(width: usize, height: usize, data: &[u16], bits: u32) -> Vec { + let mut t = TiffBuilder::default(); + let raw = t.blob(rw2_pack(data, width, bits)); + let white = ((1u32 << bits) - 1) as u16; + let ifd0 = t.ifd(vec![ + (0x0002, Val::Short(vec![width as u16])), + (0x0003, Val::Short(vec![height as u16])), + (0x0004, Val::Short(vec![2])), + (0x0005, Val::Short(vec![2])), + (0x0006, Val::Short(vec![height as u16 - 2])), + (0x0007, Val::Short(vec![width as u16 - 2])), + (0x0009, Val::Short(vec![1])), + (0x000A, Val::Short(vec![bits as u16])), + (0x000E, Val::Short(vec![white])), + (0x000F, Val::Short(vec![white])), + (0x0010, Val::Short(vec![white])), + (0x001C, Val::Short(vec![128])), + (0x001D, Val::Short(vec![129])), + (0x001E, Val::Short(vec![130])), + (0x0024, Val::Short(vec![512])), + (0x0025, Val::Short(vec![256])), + (0x0026, Val::Short(vec![384])), + (0x002D, Val::Short(vec![5])), + (0x010F, Val::Ascii("Panasonic".into())), + (0x0110, Val::Ascii("DC-Synthetic".into())), + (0x0112, Val::Short(vec![1])), + (0x0118, Val::Blobs(vec![raw])), + ]); + t.chain = vec![ifd0]; + let mut b = t.build(); + b[2..4].copy_from_slice(b"U\0"); + b +} + +/// Byte split of the vendor-compressed (RawFormat 3/4) stream (see `rw2.rs`). +const RW2_COMPRESSED_SPLIT: usize = 0x2008; + +/// Writer for the vendor-compressed RW2 stream: mirrors the decoder's cursor +/// (page addressing, downward field order) and deposits every field where the +/// reader will pick it up. +struct V4Writer<'a> { + buf: &'a mut [u8], + base: usize, + pos: usize, + nbits: u32, +} + +impl V4Writer<'_> { + /// Consumes one byte of the row seek (the decoder reads 8-bit fields). + fn skip_byte(&mut self) { + if 8 > self.nbits { + self.nbits += (RW2_PAGE as u32) * 8; + self.pos += RW2_PAGE; + } + self.nbits -= 8; + } + + fn put(&mut self, v: u32, num: u32) { + if num > self.nbits { + self.nbits += (RW2_PAGE as u32) * 8; + self.pos += RW2_PAGE; + } + let mut at = ((self.nbits - num) >> 3) as usize ^ 0x3FF0; + at = (at + RW2_PAGE - RW2_COMPRESSED_SPLIT) % RW2_PAGE; + let at = self.base + at + self.pos - RW2_PAGE; + self.nbits -= num; + let cur = u32::from(self.buf[at]) | (u32::from(self.buf[at + 1]) << 8); + let cur = cur | ((v & ((1 << num) - 1)) << (self.nbits & 7)); + self.buf[at] = cur as u8; + self.buf[at + 1] = (cur >> 8) as u8; + } + + /// Encodes one row as 14-pixel groups: the scale selector is always 0 and + /// the two first pixels of each group are absolute (8 + 4 bits); later + /// pixels use the 8-bit delta path. Callers keep values inside 16..4096 + /// and stepping by at most ±127 between pixels of the same parity. + fn row(&mut self, pixels: &[u16]) { + for group in pixels.as_chunks::<14>().0 { + let mut pred = [0i32; 2]; + let mut nonz = [0i32; 2]; + for (i, &px) in group.iter().enumerate() { + if i % 3 == 2 { + self.put(0, 2); // sh = 0 + } + let p = i & 1; + let t = i32::from(px); + if nonz[p] == 0 { + let nz = (t >> 4) & 0xFF; + self.put(nz as u32, 8); + if nz != 0 || i > 11 { + self.put((t & 0xF) as u32, 4); + pred[p] = t; + } else { + pred[p] = 0; + } + nonz[p] = nz; + } else { + let q = (pred[p] - 0x80).max(0); + let j = t - q; + assert!((1..=0xFF).contains(&j), "{t} is not encodable from {}", pred[p]); + self.put(j as u32, 8); + pred[p] = q + j; + } + assert_eq!(pred[p], t); + } + } + } +} + +/// The vendor-compressed (RawFormat 3/4) stream of a whole image; see +/// [`V4Writer::row`] for the value constraints. +pub fn rw2_v4_pack(data: &[u16], width: usize) -> Vec { + assert_eq!(width % 14, 0); + let height = data.len() / width; + assert_eq!(data.len(), width * height); + let row_bytes = width / 14 * 16; + let mut buf = vec![0u8; row_bytes * height + 2 * RW2_PAGE]; + for (row, pixels) in data.chunks_exact(width).enumerate() { + let skip = row_bytes * row; + let mut w = V4Writer { buf: &mut buf, base: skip / RW2_PAGE * RW2_PAGE, pos: 0, nbits: 0 }; + for _ in 0..(skip % RW2_PAGE) { + w.skip_byte(); + } + w.row(pixels); + } + buf +} + +/// A synthetic Panasonic RW2 (RawFormat 4, vendor-compressed) with an RGGB +/// sensor, a 2-pixel border on every side, black levels 128 / 129 / 130 and +/// WB levels 512 / 256 / 384; see [`V4Writer::row`] for the pixel constraints. +pub fn rw2_format4(width: usize, height: usize, data: &[u16]) -> Vec { + let mut t = TiffBuilder::default(); + let raw = t.blob(rw2_v4_pack(data, width)); + let ifd0 = t.ifd(vec![ + (0x0002, Val::Short(vec![width as u16])), + (0x0003, Val::Short(vec![height as u16])), + (0x0004, Val::Short(vec![2])), + (0x0005, Val::Short(vec![2])), + (0x0006, Val::Short(vec![height as u16 - 2])), + (0x0007, Val::Short(vec![width as u16 - 2])), + (0x0009, Val::Short(vec![1])), + (0x000A, Val::Short(vec![12])), + (0x000E, Val::Short(vec![4095])), + (0x000F, Val::Short(vec![4095])), + (0x0010, Val::Short(vec![4095])), + (0x001C, Val::Short(vec![128])), + (0x001D, Val::Short(vec![129])), + (0x001E, Val::Short(vec![130])), + (0x0024, Val::Short(vec![512])), + (0x0025, Val::Short(vec![256])), + (0x0026, Val::Short(vec![384])), + (0x002D, Val::Short(vec![4])), + (0x010F, Val::Ascii("Panasonic".into())), + (0x0110, Val::Ascii("DC-Synthetic".into())), + (0x0112, Val::Short(vec![1])), + (0x0118, Val::Blobs(vec![raw])), + ]); + t.chain = vec![ifd0]; + let mut b = t.build(); + b[2..4].copy_from_slice(b"U\0"); + b +} diff --git a/crates/raw/src/testgen/tiff.rs b/crates/raw/src/testgen/tiff.rs new file mode 100644 index 0000000000..9298b2ab87 --- /dev/null +++ b/crates/raw/src/testgen/tiff.rs @@ -0,0 +1,191 @@ +// ---------------------------------------------------------------- TIFF writer + +/// A TIFF entry value. +#[derive(Debug, Clone)] +pub enum Val { + Byte(Vec), + Ascii(String), + Short(Vec), + Long(Vec), + Double(Vec), + Rational(Vec<(u32, u32)>), + SRational(Vec<(i32, i32)>), + Undefined(Vec), + /// Offsets of these blobs (LONG). + Blobs(Vec), + /// Offsets of these IFDs (LONG), for SubIFDs / EXIF. + Ifds(Vec), + /// An UNDEFINED value whose bytes are this IFD (a maker note). + IfdBytes(usize), +} + +/// A TIFF file under construction. +#[derive(Debug, Clone, Default)] +pub struct TiffBuilder { + pub big_endian: bool, + /// Entries per IFD (sorted by tag on write). + pub ifds: Vec>, + /// The main IFD chain, by index into `ifds`. + pub chain: Vec, + pub blobs: Vec>, + /// Write a CR2 header pointing at this IFD as the raw IFD. + pub cr2_raw_ifd: Option, +} + +impl TiffBuilder { + pub fn ifd(&mut self, entries: Vec<(u16, Val)>) -> usize { + self.ifds.push(entries); + self.ifds.len() - 1 + } + + pub fn blob(&mut self, data: Vec) -> usize { + self.blobs.push(data); + self.blobs.len() - 1 + } + + fn val_size(&self, v: &Val) -> usize { + match v { + Val::Byte(b) | Val::Undefined(b) => b.len(), + Val::Ascii(s) => s.len() + 1, + Val::Short(s) => 2 * s.len(), + Val::Long(l) => 4 * l.len(), + Val::Double(d) => 8 * d.len(), + Val::Rational(r) => 8 * r.len(), + Val::SRational(r) => 8 * r.len(), + Val::Blobs(b) => 4 * b.len(), + Val::Ifds(i) => 4 * i.len(), + Val::IfdBytes(i) => self.ifd_size(*i), + } + } + + fn ifd_size(&self, i: usize) -> usize { + 2 + 12 * self.ifds[i].len() + 4 + } + + pub fn build(&self) -> Vec { + let header = if self.cr2_raw_ifd.is_some() { 16 } else { 8 }; + // Layout: each IFD, then its overflow values; then the blobs. + let mut pos = header; + let mut ifd_pos = vec![0usize; self.ifds.len()]; + let mut val_pos: Vec> = vec![Vec::new(); self.ifds.len()]; + // Maker-note IFDs are written inside their owner's value area. + let embedded: Vec = self.ifds.iter().flatten().filter_map(|(_, v)| if let Val::IfdBytes(i) = v { Some(*i) } else { None }).collect(); + for i in 0..self.ifds.len() { + if embedded.contains(&i) { + continue; + } + ifd_pos[i] = pos; + pos += self.ifd_size(i); + let mut vp = Vec::new(); + for (_, v) in self.sorted(i) { + let size = self.val_size(&v); + if size > 4 { + vp.push(pos); + if let Val::IfdBytes(e) = v { + ifd_pos[e] = pos; + // The embedded IFD's own values follow it. + let inner = pos + self.ifd_size(e); + let mut ip = Vec::new(); + let mut q = inner; + for (_, iv) in self.sorted(e) { + let s = self.val_size(&iv); + if s > 4 { + ip.push(q); + q += s + (s & 1); + } else { + ip.push(0); + } + } + val_pos[e] = ip; + pos = q; + } else { + pos += size + (size & 1); + } + } else { + vp.push(0); + } + } + val_pos[i] = vp; + } + let mut blob_pos = Vec::new(); + for b in &self.blobs { + blob_pos.push(pos); + pos += b.len() + (b.len() & 1); + } + let mut out = vec![0u8; pos]; + let be = self.big_endian; + let w16 = |o: &mut [u8], at: usize, v: u16| o[at..at + 2].copy_from_slice(&if be { v.to_be_bytes() } else { v.to_le_bytes() }); + let w32 = |o: &mut [u8], at: usize, v: u32| o[at..at + 4].copy_from_slice(&if be { v.to_be_bytes() } else { v.to_le_bytes() }); + out[0..4].copy_from_slice(if be { b"MM\0*" } else { b"II*\0" }); + w32(&mut out, 4, ifd_pos[self.chain[0]] as u32); + if let Some(r) = self.cr2_raw_ifd { + out[8..12].copy_from_slice(b"CR\x02\0"); + w32(&mut out, 12, ifd_pos[r] as u32); + } + for i in 0..self.ifds.len() { + let at = ifd_pos[i]; + let entries = self.sorted(i); + w16(&mut out, at, entries.len() as u16); + for (k, (tag, v)) in entries.iter().enumerate() { + let e = at + 2 + 12 * k; + let (typ, count, bytes) = self.encode(v, &blob_pos, &ifd_pos); + w16(&mut out, e, *tag); + w16(&mut out, e + 2, typ); + w32(&mut out, e + 4, count); + if bytes.len() <= 4 { + out[e + 8..e + 8 + bytes.len()].copy_from_slice(&bytes); + } else { + let vp = val_pos[i][k]; + w32(&mut out, e + 8, vp as u32); + if !matches!(v, Val::IfdBytes(_)) { + out[vp..vp + bytes.len()].copy_from_slice(&bytes); + } + } + } + let next = self.chain.iter().position(|&c| c == i).and_then(|p| self.chain.get(p + 1)).map(|&n| ifd_pos[n]).unwrap_or(0); + w32(&mut out, at + 2 + 12 * entries.len(), next as u32); + } + for (b, &p) in self.blobs.iter().zip(&blob_pos) { + out[p..p + b.len()].copy_from_slice(b); + } + out + } + + fn sorted(&self, i: usize) -> Vec<(u16, Val)> { + let mut e = self.ifds[i].clone(); + e.sort_by_key(|(t, _)| *t); + e + } + + fn encode(&self, v: &Val, blob_pos: &[usize], ifd_pos: &[usize]) -> (u16, u32, Vec) { + let be = self.big_endian; + let b16 = |v: u16| if be { v.to_be_bytes() } else { v.to_le_bytes() }; + let b32 = |v: u32| if be { v.to_be_bytes() } else { v.to_le_bytes() }; + let b64 = |v: u64| if be { v.to_be_bytes() } else { v.to_le_bytes() }; + match v { + Val::Byte(b) => (1, b.len() as u32, b.clone()), + Val::Undefined(b) => (7, b.len() as u32, b.clone()), + Val::Ascii(s) => { + let mut b = s.as_bytes().to_vec(); + b.push(0); + (2, b.len() as u32, b) + } + Val::Short(s) => (3, s.len() as u32, s.iter().flat_map(|&v| b16(v)).collect()), + Val::Long(l) => (4, l.len() as u32, l.iter().flat_map(|&v| b32(v)).collect()), + Val::Double(d) => (12, d.len() as u32, d.iter().flat_map(|v| b64(v.to_bits())).collect()), + Val::Rational(r) => (5, r.len() as u32, r.iter().flat_map(|&(n, d)| [b32(n), b32(d)].concat()).collect()), + Val::SRational(r) => (10, r.len() as u32, r.iter().flat_map(|&(n, d)| [b32(n as u32), b32(d as u32)].concat()).collect()), + Val::Blobs(b) => (4, b.len() as u32, b.iter().flat_map(|&i| b32(blob_pos[i] as u32)).collect()), + Val::Ifds(i) => (4, i.len() as u32, i.iter().flat_map(|&k| b32(ifd_pos[k] as u32)).collect()), + Val::IfdBytes(i) => (7, self.ifd_size(*i) as u32, vec![0; 8]), + } + } +} + +pub(super) fn srat(v: f64) -> (i32, i32) { + ((v * 10000.0).round() as i32, 10000) +} + +pub(super) fn urat(v: f64) -> (u32, u32) { + ((v * 10000.0).round() as u32, 10000) +} diff --git a/crates/text/src/fonts.rs b/crates/text/src/fonts.rs index a0b64f4e3b..506f83dacd 100644 --- a/crates/text/src/fonts.rs +++ b/crates/text/src/fonts.rs @@ -1147,5 +1147,4 @@ mod tests { } #[cfg(test)] -#[path = "font_names_tests.rs"] mod font_names_tests; diff --git a/crates/text/src/font_names_tests.rs b/crates/text/src/fonts/font_names_tests.rs similarity index 100% rename from crates/text/src/font_names_tests.rs rename to crates/text/src/fonts/font_names_tests.rs diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rs index 4936b33c63..7dadaf1bd5 100644 --- a/crates/text/src/layout.rs +++ b/crates/text/src/layout.rs @@ -27,38 +27,26 @@ use skrifa::raw::types::Tag; use crate::fonts::FontDb; -/// Photoshop synthesizes small caps for faces without an OpenType `smcp` table. Keep the same -/// readable hierarchy for every font instead of silently rendering lowercase text unchanged. -const SYNTHETIC_SMALL_CAPS_SCALE: f32 = 0.7; +mod area; +mod navigate; +mod paragraphs; +mod style; +mod vertical; -/// Photoshop's default superscript / subscript size and position (Type preferences, stored in a -/// PSD's text resources as `SuperscriptSize` .583, `SuperscriptPosition` .333 and their -/// `Subscript` twins): the run is drawn at 58.3% of its size and moved by 33.3% of its size. -const SCRIPT_SIZE: f32 = 0.583; -const SCRIPT_POSITION: f32 = 0.333; - -/// The style a run is drawn with: superscript and subscript shrink it and shift its baseline. -fn drawn_style(s: &mut CharStyle) { - let dir = match s.baseline { - FontBaseline::Normal => return, - FontBaseline::Superscript => 1.0, - FontBaseline::Subscript => -1.0, - }; - s.baseline_shift_pt += dir * SCRIPT_POSITION * s.size_pt; - s.size_pt *= SCRIPT_SIZE; -} - -/// Photoshop's default tab stops: every half inch, measured from the anchor of point text or the -/// left edge of a paragraph box. PSD type carries no custom tab stops, so these are the only ones. -pub const DEFAULT_TAB_STOP_PT: f32 = 36.0; - -/// The rendering path for a `SmallCaps` character style. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum SmallCapsMode { - None, - OpenType, - Synthetic, -} +#[cfg(test)] +pub(crate) use area::AREA_PASSES; +use area::{LineMetrics, MAX_AREA_PASSES, area_metrics, break_area, line_metrics}; +pub use navigate::{byte_index, char_index, hit_char, line_edge, line_index, line_step, text_point_inside, word_boundary}; +pub use paragraphs::{DEFAULT_TAB_STOP_PT, split_paragraphs}; +use paragraphs::{next_tab_stop, strip_break, tab_widths}; +#[cfg(test)] +use style::{SMCP_PROBES, variation_list}; +use style::{ + SYNTHETIC_SMALL_CAPS_SCALE, SmallCapsMode, drawn_style, effective_horizontal_scale, feature_list, first_ascent, probe_smcp, small_caps_mode, style_props, +}; +pub(crate) use style::{hangul_runs, squeeze_punctuation, synthetic_bold}; +pub use vertical::{VClass, vertical_class}; +use vertical::{VGlyph, VMetrics}; /// Index of the run containing byte offset `off`, given each run's start offset (non-decreasing): /// the last run starting at or before `off`, or 0 when none does. Binary search, so a layer with @@ -67,83 +55,11 @@ fn run_index_at(run_starts: &[usize], off: usize) -> usize { run_starts.partition_point(|&s| s <= off).saturating_sub(1) } -/// Whether the style's selected face has an `smcp` feature (a font load and GSUB parse). -fn probe_smcp(fonts: &mut FontDb, style: &CharStyle) -> bool { - #[cfg(test)] - SMCP_PROBES.with(|c| c.set(c.get() + 1)); - fonts.selected_face_has_feature(&style.font_family, style.weight, style.italic, Tag::new(b"smcp")) -} - -#[cfg(test)] -thread_local! { - static SMCP_PROBES: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -fn small_caps_mode(caps: Caps, face_has_smcp: bool) -> SmallCapsMode { - match caps { - Caps::SmallCaps if face_has_smcp => SmallCapsMode::OpenType, - Caps::SmallCaps => SmallCapsMode::Synthetic, - _ => SmallCapsMode::None, - } -} - /// Index of the character run whose style a glyph uses, plus the vertical-type class of its /// characters ([`VClass`] as `u8`; always 0 in horizontal type). #[derive(Clone, Copy, Debug, Default, PartialEq)] pub struct RunBrush(pub u32, pub u8); -/// How a character is set in vertical type (a simplification of Unicode's -/// `Vertical_Orientation`, UAX #50). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum VClass { - /// Rotated 90° clockwise (Latin, digits, most symbols). - Rotate = 0, - /// Upright (ideographs, kana, Hangul, full-width forms, CJK punctuation such as 、。), - /// using a vertical alternate when the font has one. - Upright = 1, - /// Upright through its vertical alternate (brackets, the long-vowel mark, dashes); rotated - /// when the font has none. - AlternateOrRotate = 2, -} - -/// The vertical-type class of a character. -pub fn vertical_class(c: char) -> VClass { - let u = c as u32; - let alt = matches!( - u, - 0x2014..=0x2016 - | 0x2025 - | 0x2026 - | 0x2329 - | 0x232A - | 0x3008..=0x3011 - | 0x3014..=0x301F - | 0x3030 - | 0x30A0 - | 0x30FC - | 0xFE59..=0xFE5E - | 0xFF08 - | 0xFF09 - | 0xFF0D - | 0xFF1A..=0xFF1E - | 0xFF3B - | 0xFF3D - | 0xFF3F - | 0xFF5B..=0xFF60 - | 0xFFE3 - ); - if alt { - return VClass::AlternateOrRotate; - } - // Half-width katakana and Hangul rotate like other half-width text. - if (0xFF61..=0xFFDC).contains(&u) { - return VClass::Rotate; - } - let upright = crate::cjk::classify(c).is_some() - || matches!(u, 0xA7 | 0xA9 | 0xAE | 0xB1 | 0xBC..=0xBE | 0xD7 | 0xF7 | 0x2E80..=0x2EFF | 0xFE10..=0xFE1F | 0xFE30..=0xFE4F | 0x1F000..=0x1FAFF); - if upright { VClass::Upright } else { VClass::Rotate } -} - /// How a placed glyph's outline is oriented in text space. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum GlyphOrient { @@ -344,96 +260,6 @@ impl TextLayout { } } -/// Byte offset of character `index` (the text length when `index` is past the end). -pub fn byte_index(text: &str, index: usize) -> usize { - text.char_indices().nth(index).map_or(text.len(), |(b, _)| b) -} - -/// Character index of byte `byte`, floored to a char boundary so a bad offset never panics. -pub fn char_index(text: &str, byte: usize) -> usize { - let mut byte = byte.min(text.len()); - while byte > 0 && !text.is_char_boundary(byte) { - byte -= 1; - } - text[..byte].chars().count() -} - -/// Line containing a byte offset. At a shared wrap boundary the caret belongs to -/// the following line, while an offset at the end of the text stays on the last. -pub fn line_index(layout: &TextLayout, byte: usize) -> usize { - layout.lines.iter().rposition(|ln| byte >= ln.range.start && byte <= ln.range.end).unwrap_or_else(|| layout.lines.len().saturating_sub(1)) -} - -/// Nearest caret to a text-space point: character index and the line it sits on. -pub fn hit_char(layout: &TextLayout, text: &str, x: f32, y: f32) -> (usize, usize) { - let byte = layout.hit_test(x, y); - // At a soft-wrap boundary either visual line can share this byte offset. The - // pointer's line, not the caret's preferred (following) line, is authoritative. - let (_, line_y) = layout.to_line(x, y); - let line = layout.closest_line(line_y).map_or_else(|| line_index(layout, byte), |(index, _)| index); - (char_index(text, byte), line) -} - -/// Text-space point inside the laid-out line boxes, expanded by `slop` px on every side. -pub fn text_point_inside(layout: &TextLayout, x: f32, y: f32, slop: f32) -> bool { - let slop = if slop.is_finite() { slop.max(0.0) } else { 0.0 }; - layout.bounds().is_some_and(|b| x >= b[0] - slop && x <= b[2] + slop && y >= b[1] - slop && y <= b[3] + slop) -} - -/// Character index of the word boundary before (`forward` is false) or after `idx`. -/// -/// A word is a run of alphanumeric characters, the rule the Type tool has always used. -pub fn word_boundary(text: &str, idx: usize, forward: bool) -> usize { - let chars: Vec = text.chars().collect(); - let mut i = idx.min(chars.len()); - if forward { - while i < chars.len() && !chars[i].is_alphanumeric() { - i += 1; - } - while i < chars.len() && chars[i].is_alphanumeric() { - i += 1; - } - } else { - while i > 0 && !chars[i - 1].is_alphanumeric() { - i -= 1; - } - while i > 0 && chars[i - 1].is_alphanumeric() { - i -= 1; - } - } - i -} - -/// Caret on the neighbouring line (`dir` < 0 previous, otherwise next), keeping `x` -/// (line space: the position along the line). Past the first or last line the caret -/// goes to the start or end of the text. Line space is the same for both orientations, -/// so a column of vertical type steps the same way a line of horizontal type does. -pub fn line_step(layout: &TextLayout, text: &str, idx: usize, x: f32, dir: i32) -> usize { - let n = text.chars().count(); - let idx = idx.min(n); - if layout.lines.is_empty() { - return idx; - } - let current_line = line_index(layout, byte_index(text, idx)); - let target_line = if dir < 0 { - let Some(target) = current_line.checked_sub(1) else { return 0 }; - target - } else { - let Some(target) = current_line.checked_add(1).filter(|target| *target < layout.lines.len()) else { return n }; - target - }; - char_index(text, layout.hit_test_x_on_line(target_line, x)) -} - -/// Line start (`end` false) or end for the line containing `idx`, as a character index. -pub fn line_edge(layout: &TextLayout, text: &str, idx: usize, end: bool) -> usize { - let n = text.chars().count(); - let idx = idx.min(n); - let byte = byte_index(text, idx); - let line = layout.lines.get(line_index(layout, byte)); - line.map_or(idx, |ln| char_index(text, if end { ln.range.end } else { ln.range.start })) -} - const LRM: &str = "\u{200E}"; const RLM: &str = "\u{200F}"; /// A line break inside a paragraph (Shift+Return), stored as U+0003 in PSD type. @@ -1119,16 +945,6 @@ impl Layouter { } } -/// A style's horizontal scale; unset (zero or negative) is 100%. -fn effective_horizontal_scale(st: &CharStyle) -> f32 { - if st.horizontal_scale > 0.0 && st.horizontal_scale.is_finite() { st.horizontal_scale } else { 1.0 } -} - -/// The first tab stop after `pos` (px from the anchor or box edge); stops are `interval` apart. -fn next_tab_stop(pos: f32, interval: f32) -> f32 { - if interval > 0.0 && pos.is_finite() { ((pos + 1e-3) / interval).floor() * interval + interval } else { pos } -} - /// Where one line of area type goes: its baseline, the left edge of its span, and the width /// it may fill (the span less the paragraph's indents), plus the row and span it came from. #[derive(Clone, Copy, Debug, PartialEq)] @@ -1140,579 +956,6 @@ struct Slot { span: usize, } -/// A line's ascent, descent and leading (px); for area type, the largest over a paragraph. -#[derive(Clone, Copy, Debug)] -struct LineMetrics { - ascent: f32, - descent: f32, - leading: f32, -} - -/// Most line-breaking passes area type makes for one paragraph, over all its plans (each span -/// left empty for a word that doesn't fit costs a pass). Past it, words overflow their spans. -const MAX_AREA_PASSES: usize = 32; -/// Most rows one area paragraph is planned on. -const MAX_AREA_ROWS: usize = 4096; - -#[cfg(test)] -thread_local! { - /// Area line-breaking passes made on this thread, for tests. - pub(crate) static AREA_PASSES: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// The rows an area paragraph's lines go on: baselines from `next` down, one leading apart, -/// each with its spans left to right. They don't depend on the text, so they are found once -/// (lazily) and shared by every pass. -struct AreaRows<'a> { - area: &'a crate::area::AreaShape, - m: LineMetrics, - min_width: f32, - /// Where the search for the next row starts. - next: f32, - rows: Vec<(f32, Vec<(f32, f32)>)>, - done: bool, -} - -impl AreaRows<'_> { - /// Row `i`: its baseline and spans; `None` past the shape. - fn get(&mut self, i: usize) -> Option<&(f32, Vec<(f32, f32)>)> { - while self.rows.len() <= i && !self.done { - match self.area.next_row(self.next, self.m.ascent, self.m.descent, self.min_width) { - Some((b, spans)) if self.rows.len() < MAX_AREA_ROWS => { - self.next = b + self.m.leading; - self.rows.push((b, spans)); - } - _ => self.done = true, - } - } - self.rows.get(i) - } - - /// The first span, from span `span` of row `row` on, that leaves at least `width` once - /// `inset` (the paragraph's indents) is taken off: its row and span. - fn first_fit(&mut self, row: usize, span: usize, width: f32, inset: f32) -> Option<(usize, usize)> { - let (mut r, mut first) = (row, span); - while let Some((_, spans)) = self.get(r) { - if let Some(j) = spans.iter().skip(first).position(|&(x0, x1)| x1 - x0 - inset + 0.5 >= width) { - return Some((r, first + j)); - } - r += 1; - first = 0; - } - None - } -} - -/// A line wider than the span it fell in, that a later span can hold: the line's index in the -/// paragraph, where its text starts, and its width. -#[derive(Clone, Copy, Debug)] -struct Need { - line: usize, - start: usize, - width: f32, -} - -/// Breaks one paragraph of area type a line at a time, each line as wide as the next span the -/// shape leaves (rows from `from` down, spans left to right). Returns each line's slot and -/// whether text was left over because the shape ran out (hidden, like box overflow). -/// -/// A span too narrow for the word that would start it (the narrow top of an ellipse) is left -/// empty and the word goes to the first later span that holds it, as Photoshop does. A word no -/// later span holds but another span of the shape would means the shape is full: it and the rest are -/// hidden. Only a word no span holds overflows its span. Parley doesn't report a line's -/// trailing whitespace while breaking, so overflowing lines are found after a pass and the -/// paragraph broken again; `budget` (shared by the paragraph's calls) bounds the passes. -/// -/// Horizontal scale applies after shaping, so each line breaks at its span width divided by -/// `scale`; widths compared with spans are the scaled ones. -#[allow(clippy::too_many_arguments)] -fn break_area( - layout: &mut Layout, - area: &crate::area::AreaShape, - from: f32, - m: LineMetrics, - indents: (f32, f32), - min_width: f32, - scale: f32, - budget: &std::cell::Cell, -) -> (Vec, bool) { - let inset = indents.0 + indents.1; - let mut rows = AreaRows { area, m, min_width, next: from, rows: Vec::new(), done: false }; - // Every row of the shape from its top, whatever paragraph came before (found lazily). - let mut shape_rows = AreaRows { area, m, min_width, next: area.bounds[1], rows: Vec::new(), done: false }; - let mut needs: Vec = Vec::new(); - loop { - let (slots, overflow) = break_area_pass(layout, &mut rows, inset, scale, &needs); - budget.set(budget.get().saturating_sub(1)); - // Each line's text start and scaled width without its trailing whitespace. - let lines: Vec<(usize, f32)> = layout - .lines() - .map(|l| { - let lm = l.metrics(); - (l.text_range().start, (lm.advance - lm.trailing_whitespace) * scale) - }) - .collect(); - // A line still wider than its span that some span of the shape would hold: the shape ran - // out of room for it (the narrow bottom of a full bubble). It and the rest are hidden, as - // overflow; only a word no span holds overflows its span. - let mut ran_out = |slots: Vec, overflow: bool| match lines - .iter() - .zip(&slots) - .position(|(&(_, width), s)| width > s.width + 0.5 && shape_rows.first_fit(0, 0, width, inset).is_some()) - { - Some(li) => (slots.into_iter().take(li).collect(), true), - None => (slots, overflow), - }; - if budget.get() == 0 { - return ran_out(slots, overflow); - } - // A line that now starts elsewhere (an earlier line changed) no longer needs its span. - let kept = needs.len(); - needs.retain(|n| lines.get(n.line).is_some_and(|l| l.0 == n.start)); - if needs.len() != kept { - continue; - } - let mut new = None; - for (li, (&(start, width), s)) in lines.iter().zip(&slots).enumerate() { - if width > s.width + 0.5 && !needs.iter().any(|n| n.line == li) && rows.first_fit(s.row, s.span + 1, width, inset).is_some() { - new = Some(Need { line: li, start, width }); - break; - } - } - if let Some(n) = new { - needs.push(n); - continue; - } - return ran_out(slots, overflow); - } -} - -/// One pass of [`break_area`]: each line in the next span, skipping spans too narrow for a -/// line in `needs` when a later span holds it. -fn break_area_pass(layout: &mut Layout, rows: &mut AreaRows<'_>, inset: f32, scale: f32, needs: &[Need]) -> (Vec, bool) { - #[cfg(test)] - AREA_PASSES.with(|c| c.set(c.get() + 1)); - let mut slots: Vec = Vec::new(); - let mut br = layout.break_lines(); - // Per-line widths below are never wider than this, as parley requires. - br.state_mut().set_layout_max_advance(f32::INFINITY); - let (mut row, mut span) = (0, 0); - let mut overflow = false; - while !br.is_done() { - let Some((baseline, spans)) = rows.get(row) else { - overflow = true; - break; - }; - let baseline = *baseline; - let Some(&(x0, x1)) = spans.get(span) else { - row += 1; - span = 0; - continue; - }; - let width = (x1 - x0 - inset).max(1.0); - // A line known to be too wide here moves on to the first span that holds it. - if let Some(w) = needs.iter().find(|n| n.line == slots.len()).map(|n| n.width) - && w > width + 0.5 - && let Some((r, j)) = rows.first_fit(row, span + 1, w, inset) - { - (row, span) = (r, j); - continue; - } - br.state_mut().set_line_max_advance(width / scale); - if br.break_next().is_none() { - break; - } - // Parley aligns each line within the width it was broken at. - br.set_prior_line_width(width / scale); - slots.push(Slot { baseline, x: x0, width, row, span }); - span += 1; - } - br.finish(); - (slots, overflow) -} - -/// One laid-out line's ascent, descent and leading, as the line loop stacks it. `fallback` is -/// the paragraph's first style, used for a line with no glyph runs. -fn line_metrics(line: &parley::Line<'_, RunBrush>, styles: &[CharStyle], ps: &ParagraphStyle, k: f32, fallback: &CharStyle, vertical: bool) -> LineMetrics { - let first_px = fallback.size_pt * k; - let m = line.metrics(); - // Largest leading among the glyph runs, and half the largest em (a vertical column's half width). - let mut leading = 0.0f32; - let mut half = 0.0f32; - for item in line.items() { - if let PositionedLayoutItem::GlyphRun(gr) = item { - let px = gr.run().font_size(); - half = half.max(px * 0.5); - let lp = styles.get(gr.style().brush.0 as usize).and_then(|st| st.leading_pt); - leading = leading.max(lp.map_or(ps.auto_leading * px, |l| l * k)); - } - } - if leading == 0.0 { - leading = fallback.leading_pt.map_or(ps.auto_leading * first_px, |l| l * k); - } - let (ascent, descent) = if vertical { - let h = if half > 0.0 { half } else { first_px * 0.5 }; - (h, h) - } else if m.ascent > 0.0 || m.descent > 0.0 { - (m.ascent, m.descent) - } else { - (first_px * 0.8, first_px * 0.2) - }; - LineMetrics { ascent, descent, leading } -} - -/// Largest ascent, descent and leading over the lines of a broken paragraph, by -/// [`line_metrics`], so an area paragraph's rows are planned with the metrics it is stacked with. -fn area_metrics(layout: &Layout, styles: &[CharStyle], ps: &ParagraphStyle, k: f32, fallback: &CharStyle, vertical: bool) -> LineMetrics { - layout.lines().map(|line| line_metrics(&line, styles, ps, k, fallback, vertical)).fold(LineMetrics { ascent: 0.0, descent: 0.0, leading: 0.0 }, |a, b| { - LineMetrics { ascent: a.ascent.max(b.ascent), descent: a.descent.max(b.descent), leading: a.leading.max(b.leading) } - }) -} - -/// A tab as line breaking saw it: its shaped advance (before horizontal scale), the horizontal -/// scale, and the width that takes it to its tab stop on its line. -struct TabWidth { - advance: f32, - scale: f32, - width: f32, -} - -/// The width of each tab (offsets `tabs` in the paragraph text) on the broken lines of `layout`, -/// before kerning and alignment. -fn tab_widths(layout: &Layout, tabs: &[usize], styles: &[CharStyle], indent: f32, first_indent: f32, interval: f32) -> Vec { - let mut out: Vec = tabs.iter().map(|_| TabWidth { advance: interval, scale: 1.0, width: interval }).collect(); - for (li, line) in layout.lines().enumerate() { - let mut pos = indent + if li == 0 { first_indent } else { 0.0 }; - let mut seen: Vec = Vec::new(); - for item in line.items() { - let PositionedLayoutItem::GlyphRun(gr) = item else { - continue; - }; - let run = gr.run(); - if seen.contains(&run.index()) { - continue; - } - seen.push(run.index()); - let scale = styles.get(gr.style().brush.0 as usize).map_or(1.0, |st| if st.horizontal_scale > 0.0 { st.horizontal_scale } else { 1.0 }); - for c in run.visual_clusters() { - let advance = c.advance(); - match tabs.binary_search(&c.text_range().start).ok().and_then(|i| out.get_mut(i)) { - Some(t) => { - let stop = next_tab_stop(pos, interval); - *t = TabWidth { advance, scale, width: stop - pos }; - pos = stop; - } - None => pos += advance * scale, - } - } - } - } - out -} - -/// Byte ranges of paragraphs (each including its `\r`, `\n` or `\r\n` terminator). Text ending -/// with a break yields a final empty paragraph, like Photoshop's trailing empty line. -pub fn split_paragraphs(text: &str) -> Vec> { - let b = text.as_bytes(); - let mut v = Vec::new(); - let mut start = 0; - let mut i = 0; - while i < b.len() { - match b[i] { - b'\r' => { - let end = if b.get(i + 1) == Some(&b'\n') { i + 2 } else { i + 1 }; - v.push(start..end); - start = end; - i = end; - } - b'\n' => { - v.push(start..i + 1); - start = i + 1; - i += 1; - } - _ => i += 1, - } - } - v.push(start..b.len()); - v -} - -fn strip_break(text: &str, r: &Range) -> usize { - let s = &text[r.clone()]; - r.start + s.trim_end_matches(['\r', '\n']).len() -} - -fn quote(s: &str) -> String { - format!("\"{}\"", s.replace(['\\', '"'], "")) -} - -/// Placement data of one vertical-type glyph (before mapping to text space). -struct VGlyph { - upright: bool, - /// Advance along the column (px). - advance: f32, - /// Upright: distance from the top of the glyph's cell down to its baseline (px). - origin: f32, - /// Rotated: distance from the column centre line to the glyph's baseline (px). - centre: f32, -} - -/// Vertical metrics of a font instance: `VORG`, `vhea`/`vmtx`, else the ideographic em box. -struct VMetrics<'a> { - font: Option>, - coords: Vec, - /// px per font unit. - scale: f32, - /// Em-box fallback origin (px below the cell top). - em_origin: f32, -} - -impl<'a> VMetrics<'a> { - fn new(fd: &'a FontData, coords: &[i16], size: f32) -> Self { - use skrifa::MetadataProvider; - let font = skrifa::FontRef::from_index(fd.data.as_ref(), fd.index).ok(); - let coords: Vec = coords.iter().map(|&c| skrifa::instance::NormalizedCoord::from_bits(c)).collect(); - let (scale, em_origin) = match &font { - Some(f) => { - let m = f.metrics(skrifa::instance::Size::unscaled(), skrifa::instance::LocationRef::new(&coords)); - let upem = f32::from(m.units_per_em).max(1.0); - let (asc, desc) = (m.ascent, -m.descent); - // Ideographic em box: the em centred on the font's ascent/descent span. - let r = if asc + desc > 0.0 && asc.is_finite() && desc.is_finite() { (asc / (asc + desc)).clamp(0.0, 1.0) } else { 0.88 }; - (size / upem, size * r) - } - None => (0.0, size * 0.88), - }; - Self { font, coords, scale, em_origin } - } - - fn cmap(&self, c: char) -> Option { - use skrifa::MetadataProvider; - self.font.as_ref()?.charmap().map(c).map(|g| g.to_u32()) - } - - /// Distance from the top of an upright glyph's cell to its baseline (px). - fn origin(&self, gid: u32) -> f32 { - self.vertical_origin(gid).filter(|v| v.is_finite()).unwrap_or(self.em_origin) - } - - fn vertical_origin(&self, gid: u32) -> Option { - use skrifa::MetadataProvider; - use skrifa::raw::TableProvider; - let f = self.font.as_ref()?; - let g = skrifa::GlyphId::new(gid); - if let Ok(vorg) = f.vorg() { - return Some(f32::from(vorg.vertical_origin_y(g)) * self.scale); - } - let tsb = f.vmtx().ok()?.side_bearing(g)?; - // Top of the outline (font units), from the outline itself (glyf and CFF alike). - let outline = f.outline_glyphs().get(g)?; - let mut pen = YMax(None); - let settings = skrifa::outline::DrawSettings::unhinted(skrifa::instance::Size::unscaled(), skrifa::instance::LocationRef::new(&self.coords)); - outline.draw(settings, &mut pen).ok()?; - Some((pen.0? + f32::from(tsb)) * self.scale) - } -} - -/// Outline pen recording the largest y. -struct YMax(Option); - -impl YMax { - fn add(&mut self, y: f32) { - self.0 = Some(self.0.map_or(y, |m| m.max(y))); - } -} - -impl skrifa::outline::OutlinePen for YMax { - fn move_to(&mut self, _x: f32, y: f32) { - self.add(y); - } - fn line_to(&mut self, _x: f32, y: f32) { - self.add(y); - } - fn quad_to(&mut self, _cx0: f32, cy0: f32, _x: f32, y: f32) { - self.add(cy0); - self.add(y); - } - fn curve_to(&mut self, _cx0: f32, cy0: f32, _cx1: f32, cy1: f32, _x: f32, y: f32) { - self.add(cy0); - self.add(cy1); - self.add(y); - } - fn close(&mut self) {} -} - -/// OpenType feature settings of a character style (CSS `font-feature-settings` items). -fn feature_list(st: &CharStyle, small_caps: SmallCapsMode) -> Vec { - let mut feats: Vec = Vec::new(); - // Optical and manual kerning replace the font's kerning table; a character with a manual - // kern is manually kerned whatever its mode (as in Photoshop). - if st.kerning != Kerning::Metrics || st.kern != 0.0 { - feats.push("\"kern\" 0".into()); - } - if !st.ligatures { - feats.push("\"liga\" 0".into()); - feats.push("\"clig\" 0".into()); - } - if st.discretionary_ligatures { - feats.push("\"dlig\" 1".into()); - } - if small_caps == SmallCapsMode::OpenType { - feats.push("\"smcp\" 1".into()); - } - for f in &st.features { - if f.tag.len() == 4 && f.tag.is_ascii() { - feats.push(format!("\"{}\" {}", f.tag, f.value)); - } - } - feats -} - -/// The font variations for a run: the explicit axis values, plus `opsz` at the type size when the -/// style doesn't set it (as CSS `font-optical-sizing: auto`). A font without an `opsz` axis -/// ignores it. -fn variation_list(st: &CharStyle) -> Vec { - let mut vars: Vec = - st.variations.iter().filter(|v| v.axis.len() == 4 && v.axis.is_ascii() && v.value.is_finite()).map(|v| format!("\"{}\" {}", v.axis, v.value)).collect(); - if st.size_pt.is_finite() && !st.variations.iter().any(|v| v.axis == "opsz") { - vars.push(format!("\"opsz\" {}", st.size_pt.max(0.01))); - } - vars -} - -fn style_props(st: &CharStyle, k: f32, fallback: &[String], idx: u32, small_caps: SmallCapsMode) -> Vec> { - let px = (st.size_pt * k).max(0.01); - let mut fam: Vec = Vec::new(); - if !st.font_family.is_empty() { - fam.push(quote(&st.font_family)); - } - // Serif runs fall back to a Mincho face for Japanese (craft-fonts), others to a Gothic one. - if crate::craft_fonts::is_serif_family(&st.font_family) { - fam.extend(crate::craft_fonts::mincho_first(fallback).iter().map(|f| quote(f))); - } else { - fam.extend(fallback.iter().map(|f| quote(f))); - } - fam.push("sans-serif".into()); - let feats = feature_list(st, small_caps); - let vars = variation_list(st); - vec![ - StyleProperty::FontFamily(FontFamily::Source(Cow::Owned(fam.join(", ")))), - StyleProperty::FontSize(px), - StyleProperty::FontWeight(FontWeight::new(st.weight.clamp(1, 1000) as f32)), - StyleProperty::FontStyle(if st.italic { FontStyle::Italic } else { FontStyle::Normal }), - StyleProperty::FontFeatures(FontFeatures::Source(Cow::Owned(feats.join(", ")))), - StyleProperty::FontVariations(FontVariations::Source(Cow::Owned(vars.join(", ")))), - StyleProperty::LetterSpacing(st.tracking / 1000.0 * px), - StyleProperty::Underline(st.underline), - StyleProperty::Strikethrough(st.strikethrough), - StyleProperty::Brush(RunBrush(idx, 0)), - StyleProperty::Locale(st.language.as_deref().and_then(|l| parley::fontique::Language::parse(l).ok())), - ] -} - -/// Closing CJK punctuation: its full-width cell has blank space after the mark. -fn is_closing(c: char) -> bool { - matches!(c, '、' | '。' | ',' | '.' | '」' | '』' | ')' | '〕' | '】' | '〉' | '》' | '〙' | '〗' | ']' | '}') -} - -/// Opening CJK brackets: blank space before the mark. -fn is_opening(c: char) -> bool { - matches!(c, '「' | '『' | '(' | '〔' | '【' | '〈' | '《' | '〘' | '〖' | '[' | '{') -} - -/// Basic Japanese punctuation squeeze (JIS X 4051 style) for one line in line space: between a -/// closing mark and a following opening or closing mark, the closing mark's trailing half-em -/// blank is removed; between two opening brackets, the second one's leading half-em. Clusters and -/// glyphs from the squeezed point on move back. Returns the total length removed. -pub(crate) fn squeeze_punctuation(text: &str, clusters: &mut [ClusterInfo], glyphs: &mut [PlacedGlyph]) -> f32 { - let first = |c: &ClusterInfo| text.get(c.range.clone()).and_then(|s| s.chars().next()); - let last = |c: &ClusterInfo| text.get(c.range.clone()).and_then(|s| s.chars().next_back()); - // Shift to apply from each cluster on. - let mut shifts = vec![0.0f32; clusters.len()]; - let mut total = 0.0f32; - for i in 1..clusters.len() { - let (Some(prev), Some(cur)) = (clusters.get(i - 1), clusters.get(i)) else { continue }; - if prev.rtl || cur.rtl { - continue; - } - let (Some(a), Some(b)) = (last(prev), first(cur)) else { continue }; - let cut = if is_closing(a) && (is_opening(b) || is_closing(b)) { - prev.advance * 0.5 - } else if is_opening(a) && is_opening(b) { - cur.advance * 0.5 - } else { - 0.0 - }; - if cut.is_finite() && cut > 0.0 { - total += cut; - } - if let Some(s) = shifts.get_mut(i) { - *s = total; - } - } - if total <= 0.0 { - return 0.0; - } - let starts: Vec = clusters.iter().map(|c| c.x).collect(); - for (c, s) in clusters.iter_mut().zip(&shifts) { - c.x -= s; - } - for g in glyphs.iter_mut() { - let i = starts.iter().rposition(|&s| s <= g.x + 1e-3).unwrap_or(0); - g.x -= shifts.get(i).copied().unwrap_or(0.0); - } - total -} - -/// Whether to embolden a face synthetically. Font matching (fontique) asks for it whenever the -/// requested weight is above the face's, so Regular (400) from a family with only W3 (300) and W6 -/// (600), like Hiragino Mincho ProN, came out as a smeared bold W3. Like Photoshop and CSS, only -/// a bold request (≥ 600) on a face that isn't bold (≤ 500) is emboldened; anything else uses the -/// nearest face as it is (Faux Bold stays a separate, explicit style). -pub(crate) fn synthetic_bold(matcher_says: bool, requested: u16, face_weight: f32) -> bool { - matcher_says && requested >= 600 && face_weight <= 500.0 -} - -/// Height of the lowercase ascender ('d') of the tallest run on the line. -fn first_ascent(line: &parley::Line<'_, RunBrush>) -> Option { - use skrifa::MetadataProvider; - let mut best: Option = None; - for run in line.runs() { - let fd = run.font(); - let Ok(font) = skrifa::FontRef::from_index(fd.data.as_ref(), fd.index) else { - continue; - }; - let coords: Vec = run.normalized_coords().iter().map(|&c| skrifa::instance::NormalizedCoord::from_bits(c)).collect(); - let loc = skrifa::instance::LocationRef::new(&coords); - let size = skrifa::instance::Size::new(run.font_size()); - let h = font.charmap().map('d').and_then(|g| font.glyph_metrics(size, loc).bounds(g)).map(|b| b.y_max).or_else(|| { - let m = font.metrics(size, loc); - m.cap_height.or(Some(m.ascent * 0.75)) - }); - if let Some(h) = h { - best = Some(best.map_or(h, |b: f32| b.max(h))); - } - } - best -} - -/// Hangul (syllables and jamo). -fn is_hangul(c: char) -> bool { - matches!(c, '\u{1100}'..='\u{11FF}' | '\u{3130}'..='\u{318F}' | '\u{A960}'..='\u{A97F}' | '\u{AC00}'..='\u{D7AF}' | '\u{D7B0}'..='\u{D7FF}') -} - -/// The byte ranges of `text` made of Hangul, each as long as it runs. -pub(crate) fn hangul_runs(text: &str) -> Vec> { - let mut runs: Vec> = Vec::new(); - for (i, c) in text.char_indices().filter(|&(_, c)| is_hangul(c)) { - match runs.last_mut() { - Some(r) if r.end == i => r.end = i + c.len_utf8(), - _ => runs.push(i..i + c.len_utf8()), - } - } - runs -} - #[cfg(test)] mod tests { use super::{SmallCapsMode, feature_list, small_caps_mode, variation_list}; diff --git a/crates/text/src/layout/area.rs b/crates/text/src/layout/area.rs new file mode 100644 index 0000000000..d91d497e26 --- /dev/null +++ b/crates/text/src/layout/area.rs @@ -0,0 +1,238 @@ +use super::*; + +/// A line's ascent, descent and leading (px); for area type, the largest over a paragraph. +#[derive(Clone, Copy, Debug)] +pub(super) struct LineMetrics { + pub(super) ascent: f32, + pub(super) descent: f32, + pub(super) leading: f32, +} + +/// Most line-breaking passes area type makes for one paragraph, over all its plans (each span +/// left empty for a word that doesn't fit costs a pass). Past it, words overflow their spans. +pub(super) const MAX_AREA_PASSES: usize = 32; + +/// Most rows one area paragraph is planned on. +const MAX_AREA_ROWS: usize = 4096; + +#[cfg(test)] +thread_local! { + /// Area line-breaking passes made on this thread, for tests. + pub(crate) static AREA_PASSES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The rows an area paragraph's lines go on: baselines from `next` down, one leading apart, +/// each with its spans left to right. They don't depend on the text, so they are found once +/// (lazily) and shared by every pass. +struct AreaRows<'a> { + area: &'a crate::area::AreaShape, + m: LineMetrics, + min_width: f32, + /// Where the search for the next row starts. + next: f32, + rows: Vec<(f32, Vec<(f32, f32)>)>, + done: bool, +} + +impl AreaRows<'_> { + /// Row `i`: its baseline and spans; `None` past the shape. + fn get(&mut self, i: usize) -> Option<&(f32, Vec<(f32, f32)>)> { + while self.rows.len() <= i && !self.done { + match self.area.next_row(self.next, self.m.ascent, self.m.descent, self.min_width) { + Some((b, spans)) if self.rows.len() < MAX_AREA_ROWS => { + self.next = b + self.m.leading; + self.rows.push((b, spans)); + } + _ => self.done = true, + } + } + self.rows.get(i) + } + + /// The first span, from span `span` of row `row` on, that leaves at least `width` once + /// `inset` (the paragraph's indents) is taken off: its row and span. + fn first_fit(&mut self, row: usize, span: usize, width: f32, inset: f32) -> Option<(usize, usize)> { + let (mut r, mut first) = (row, span); + while let Some((_, spans)) = self.get(r) { + if let Some(j) = spans.iter().skip(first).position(|&(x0, x1)| x1 - x0 - inset + 0.5 >= width) { + return Some((r, first + j)); + } + r += 1; + first = 0; + } + None + } +} + +/// A line wider than the span it fell in, that a later span can hold: the line's index in the +/// paragraph, where its text starts, and its width. +#[derive(Clone, Copy, Debug)] +struct Need { + line: usize, + start: usize, + width: f32, +} + +/// Breaks one paragraph of area type a line at a time, each line as wide as the next span the +/// shape leaves (rows from `from` down, spans left to right). Returns each line's slot and +/// whether text was left over because the shape ran out (hidden, like box overflow). +/// +/// A span too narrow for the word that would start it (the narrow top of an ellipse) is left +/// empty and the word goes to the first later span that holds it, as Photoshop does. A word no +/// later span holds but another span of the shape would means the shape is full: it and the rest are +/// hidden. Only a word no span holds overflows its span. Parley doesn't report a line's +/// trailing whitespace while breaking, so overflowing lines are found after a pass and the +/// paragraph broken again; `budget` (shared by the paragraph's calls) bounds the passes. +/// +/// Horizontal scale applies after shaping, so each line breaks at its span width divided by +/// `scale`; widths compared with spans are the scaled ones. +#[allow(clippy::too_many_arguments)] +pub(super) fn break_area( + layout: &mut Layout, + area: &crate::area::AreaShape, + from: f32, + m: LineMetrics, + indents: (f32, f32), + min_width: f32, + scale: f32, + budget: &std::cell::Cell, +) -> (Vec, bool) { + let inset = indents.0 + indents.1; + let mut rows = AreaRows { area, m, min_width, next: from, rows: Vec::new(), done: false }; + // Every row of the shape from its top, whatever paragraph came before (found lazily). + let mut shape_rows = AreaRows { area, m, min_width, next: area.bounds[1], rows: Vec::new(), done: false }; + let mut needs: Vec = Vec::new(); + loop { + let (slots, overflow) = break_area_pass(layout, &mut rows, inset, scale, &needs); + budget.set(budget.get().saturating_sub(1)); + // Each line's text start and scaled width without its trailing whitespace. + let lines: Vec<(usize, f32)> = layout + .lines() + .map(|l| { + let lm = l.metrics(); + (l.text_range().start, (lm.advance - lm.trailing_whitespace) * scale) + }) + .collect(); + // A line still wider than its span that some span of the shape would hold: the shape ran + // out of room for it (the narrow bottom of a full bubble). It and the rest are hidden, as + // overflow; only a word no span holds overflows its span. + let mut ran_out = |slots: Vec, overflow: bool| match lines + .iter() + .zip(&slots) + .position(|(&(_, width), s)| width > s.width + 0.5 && shape_rows.first_fit(0, 0, width, inset).is_some()) + { + Some(li) => (slots.into_iter().take(li).collect(), true), + None => (slots, overflow), + }; + if budget.get() == 0 { + return ran_out(slots, overflow); + } + // A line that now starts elsewhere (an earlier line changed) no longer needs its span. + let kept = needs.len(); + needs.retain(|n| lines.get(n.line).is_some_and(|l| l.0 == n.start)); + if needs.len() != kept { + continue; + } + let mut new = None; + for (li, (&(start, width), s)) in lines.iter().zip(&slots).enumerate() { + if width > s.width + 0.5 && !needs.iter().any(|n| n.line == li) && rows.first_fit(s.row, s.span + 1, width, inset).is_some() { + new = Some(Need { line: li, start, width }); + break; + } + } + if let Some(n) = new { + needs.push(n); + continue; + } + return ran_out(slots, overflow); + } +} + +/// One pass of [`break_area`]: each line in the next span, skipping spans too narrow for a +/// line in `needs` when a later span holds it. +fn break_area_pass(layout: &mut Layout, rows: &mut AreaRows<'_>, inset: f32, scale: f32, needs: &[Need]) -> (Vec, bool) { + #[cfg(test)] + AREA_PASSES.with(|c| c.set(c.get() + 1)); + let mut slots: Vec = Vec::new(); + let mut br = layout.break_lines(); + // Per-line widths below are never wider than this, as parley requires. + br.state_mut().set_layout_max_advance(f32::INFINITY); + let (mut row, mut span) = (0, 0); + let mut overflow = false; + while !br.is_done() { + let Some((baseline, spans)) = rows.get(row) else { + overflow = true; + break; + }; + let baseline = *baseline; + let Some(&(x0, x1)) = spans.get(span) else { + row += 1; + span = 0; + continue; + }; + let width = (x1 - x0 - inset).max(1.0); + // A line known to be too wide here moves on to the first span that holds it. + if let Some(w) = needs.iter().find(|n| n.line == slots.len()).map(|n| n.width) + && w > width + 0.5 + && let Some((r, j)) = rows.first_fit(row, span + 1, w, inset) + { + (row, span) = (r, j); + continue; + } + br.state_mut().set_line_max_advance(width / scale); + if br.break_next().is_none() { + break; + } + // Parley aligns each line within the width it was broken at. + br.set_prior_line_width(width / scale); + slots.push(Slot { baseline, x: x0, width, row, span }); + span += 1; + } + br.finish(); + (slots, overflow) +} + +/// One laid-out line's ascent, descent and leading, as the line loop stacks it. `fallback` is +/// the paragraph's first style, used for a line with no glyph runs. +pub(super) fn line_metrics( + line: &parley::Line<'_, RunBrush>, + styles: &[CharStyle], + ps: &ParagraphStyle, + k: f32, + fallback: &CharStyle, + vertical: bool, +) -> LineMetrics { + let first_px = fallback.size_pt * k; + let m = line.metrics(); + // Largest leading among the glyph runs, and half the largest em (a vertical column's half width). + let mut leading = 0.0f32; + let mut half = 0.0f32; + for item in line.items() { + if let PositionedLayoutItem::GlyphRun(gr) = item { + let px = gr.run().font_size(); + half = half.max(px * 0.5); + let lp = styles.get(gr.style().brush.0 as usize).and_then(|st| st.leading_pt); + leading = leading.max(lp.map_or(ps.auto_leading * px, |l| l * k)); + } + } + if leading == 0.0 { + leading = fallback.leading_pt.map_or(ps.auto_leading * first_px, |l| l * k); + } + let (ascent, descent) = if vertical { + let h = if half > 0.0 { half } else { first_px * 0.5 }; + (h, h) + } else if m.ascent > 0.0 || m.descent > 0.0 { + (m.ascent, m.descent) + } else { + (first_px * 0.8, first_px * 0.2) + }; + LineMetrics { ascent, descent, leading } +} + +/// Largest ascent, descent and leading over the lines of a broken paragraph, by +/// [`line_metrics`], so an area paragraph's rows are planned with the metrics it is stacked with. +pub(super) fn area_metrics(layout: &Layout, styles: &[CharStyle], ps: &ParagraphStyle, k: f32, fallback: &CharStyle, vertical: bool) -> LineMetrics { + layout.lines().map(|line| line_metrics(&line, styles, ps, k, fallback, vertical)).fold(LineMetrics { ascent: 0.0, descent: 0.0, leading: 0.0 }, |a, b| { + LineMetrics { ascent: a.ascent.max(b.ascent), descent: a.descent.max(b.descent), leading: a.leading.max(b.leading) } + }) +} diff --git a/crates/text/src/layout/navigate.rs b/crates/text/src/layout/navigate.rs new file mode 100644 index 0000000000..e7d9c00333 --- /dev/null +++ b/crates/text/src/layout/navigate.rs @@ -0,0 +1,91 @@ +use super::*; + +/// Byte offset of character `index` (the text length when `index` is past the end). +pub fn byte_index(text: &str, index: usize) -> usize { + text.char_indices().nth(index).map_or(text.len(), |(b, _)| b) +} + +/// Character index of byte `byte`, floored to a char boundary so a bad offset never panics. +pub fn char_index(text: &str, byte: usize) -> usize { + let mut byte = byte.min(text.len()); + while byte > 0 && !text.is_char_boundary(byte) { + byte -= 1; + } + text[..byte].chars().count() +} + +/// Line containing a byte offset. At a shared wrap boundary the caret belongs to +/// the following line, while an offset at the end of the text stays on the last. +pub fn line_index(layout: &TextLayout, byte: usize) -> usize { + layout.lines.iter().rposition(|ln| byte >= ln.range.start && byte <= ln.range.end).unwrap_or_else(|| layout.lines.len().saturating_sub(1)) +} + +/// Nearest caret to a text-space point: character index and the line it sits on. +pub fn hit_char(layout: &TextLayout, text: &str, x: f32, y: f32) -> (usize, usize) { + let byte = layout.hit_test(x, y); + // At a soft-wrap boundary either visual line can share this byte offset. The + // pointer's line, not the caret's preferred (following) line, is authoritative. + let (_, line_y) = layout.to_line(x, y); + let line = layout.closest_line(line_y).map_or_else(|| line_index(layout, byte), |(index, _)| index); + (char_index(text, byte), line) +} + +/// Text-space point inside the laid-out line boxes, expanded by `slop` px on every side. +pub fn text_point_inside(layout: &TextLayout, x: f32, y: f32, slop: f32) -> bool { + let slop = if slop.is_finite() { slop.max(0.0) } else { 0.0 }; + layout.bounds().is_some_and(|b| x >= b[0] - slop && x <= b[2] + slop && y >= b[1] - slop && y <= b[3] + slop) +} + +/// Character index of the word boundary before (`forward` is false) or after `idx`. +/// +/// A word is a run of alphanumeric characters, the rule the Type tool has always used. +pub fn word_boundary(text: &str, idx: usize, forward: bool) -> usize { + let chars: Vec = text.chars().collect(); + let mut i = idx.min(chars.len()); + if forward { + while i < chars.len() && !chars[i].is_alphanumeric() { + i += 1; + } + while i < chars.len() && chars[i].is_alphanumeric() { + i += 1; + } + } else { + while i > 0 && !chars[i - 1].is_alphanumeric() { + i -= 1; + } + while i > 0 && chars[i - 1].is_alphanumeric() { + i -= 1; + } + } + i +} + +/// Caret on the neighbouring line (`dir` < 0 previous, otherwise next), keeping `x` +/// (line space: the position along the line). Past the first or last line the caret +/// goes to the start or end of the text. Line space is the same for both orientations, +/// so a column of vertical type steps the same way a line of horizontal type does. +pub fn line_step(layout: &TextLayout, text: &str, idx: usize, x: f32, dir: i32) -> usize { + let n = text.chars().count(); + let idx = idx.min(n); + if layout.lines.is_empty() { + return idx; + } + let current_line = line_index(layout, byte_index(text, idx)); + let target_line = if dir < 0 { + let Some(target) = current_line.checked_sub(1) else { return 0 }; + target + } else { + let Some(target) = current_line.checked_add(1).filter(|target| *target < layout.lines.len()) else { return n }; + target + }; + char_index(text, layout.hit_test_x_on_line(target_line, x)) +} + +/// Line start (`end` false) or end for the line containing `idx`, as a character index. +pub fn line_edge(layout: &TextLayout, text: &str, idx: usize, end: bool) -> usize { + let n = text.chars().count(); + let idx = idx.min(n); + let byte = byte_index(text, idx); + let line = layout.lines.get(line_index(layout, byte)); + line.map_or(idx, |ln| char_index(text, if end { ln.range.end } else { ln.range.start })) +} diff --git a/crates/text/src/layout/paragraphs.rs b/crates/text/src/layout/paragraphs.rs new file mode 100644 index 0000000000..2be1fbbc5a --- /dev/null +++ b/crates/text/src/layout/paragraphs.rs @@ -0,0 +1,87 @@ +use super::*; + +/// Photoshop's default tab stops: every half inch, measured from the anchor of point text or the +/// left edge of a paragraph box. PSD type carries no custom tab stops, so these are the only ones. +pub const DEFAULT_TAB_STOP_PT: f32 = 36.0; + +/// The first tab stop after `pos` (px from the anchor or box edge); stops are `interval` apart. +pub(super) fn next_tab_stop(pos: f32, interval: f32) -> f32 { + if interval > 0.0 && pos.is_finite() { ((pos + 1e-3) / interval).floor() * interval + interval } else { pos } +} + +/// A tab as line breaking saw it: its shaped advance (before horizontal scale), the horizontal +/// scale, and the width that takes it to its tab stop on its line. +pub(super) struct TabWidth { + pub(super) advance: f32, + pub(super) scale: f32, + pub(super) width: f32, +} + +/// The width of each tab (offsets `tabs` in the paragraph text) on the broken lines of `layout`, +/// before kerning and alignment. +pub(super) fn tab_widths(layout: &Layout, tabs: &[usize], styles: &[CharStyle], indent: f32, first_indent: f32, interval: f32) -> Vec { + let mut out: Vec = tabs.iter().map(|_| TabWidth { advance: interval, scale: 1.0, width: interval }).collect(); + for (li, line) in layout.lines().enumerate() { + let mut pos = indent + if li == 0 { first_indent } else { 0.0 }; + let mut seen: Vec = Vec::new(); + for item in line.items() { + let PositionedLayoutItem::GlyphRun(gr) = item else { + continue; + }; + let run = gr.run(); + if seen.contains(&run.index()) { + continue; + } + seen.push(run.index()); + let scale = styles.get(gr.style().brush.0 as usize).map_or(1.0, |st| if st.horizontal_scale > 0.0 { st.horizontal_scale } else { 1.0 }); + for c in run.visual_clusters() { + let advance = c.advance(); + match tabs.binary_search(&c.text_range().start).ok().and_then(|i| out.get_mut(i)) { + Some(t) => { + let stop = next_tab_stop(pos, interval); + *t = TabWidth { advance, scale, width: stop - pos }; + pos = stop; + } + None => pos += advance * scale, + } + } + } + } + out +} + +/// Byte ranges of paragraphs (each including its `\r`, `\n` or `\r\n` terminator). Text ending +/// with a break yields a final empty paragraph, like Photoshop's trailing empty line. +pub fn split_paragraphs(text: &str) -> Vec> { + let b = text.as_bytes(); + let mut v = Vec::new(); + let mut start = 0; + let mut i = 0; + while i < b.len() { + match b[i] { + b'\r' => { + let end = if b.get(i + 1) == Some(&b'\n') { i + 2 } else { i + 1 }; + v.push(start..end); + start = end; + i = end; + } + b'\n' => { + v.push(start..i + 1); + start = i + 1; + i += 1; + } + _ => i += 1, + } + } + v.push(start..b.len()); + v +} + +pub(super) fn strip_break(text: &str, r: &Range) -> usize { + let s = &text[r.clone()]; + r.start + s.trim_end_matches(['\r', '\n']).len() +} + +pub(super) fn quote(s: &str) -> String { + format!("\"{}\"", s.replace(['\\', '"'], "")) +} diff --git a/crates/text/src/layout/style.rs b/crates/text/src/layout/style.rs new file mode 100644 index 0000000000..fc5b775a7d --- /dev/null +++ b/crates/text/src/layout/style.rs @@ -0,0 +1,228 @@ +use super::paragraphs::quote; +use super::*; + +/// Photoshop synthesizes small caps for faces without an OpenType `smcp` table. Keep the same +/// readable hierarchy for every font instead of silently rendering lowercase text unchanged. +pub(super) const SYNTHETIC_SMALL_CAPS_SCALE: f32 = 0.7; + +/// Photoshop's default superscript / subscript size and position (Type preferences, stored in a +/// PSD's text resources as `SuperscriptSize` .583, `SuperscriptPosition` .333 and their +/// `Subscript` twins): the run is drawn at 58.3% of its size and moved by 33.3% of its size. +const SCRIPT_SIZE: f32 = 0.583; + +const SCRIPT_POSITION: f32 = 0.333; + +/// The style a run is drawn with: superscript and subscript shrink it and shift its baseline. +pub(super) fn drawn_style(s: &mut CharStyle) { + let dir = match s.baseline { + FontBaseline::Normal => return, + FontBaseline::Superscript => 1.0, + FontBaseline::Subscript => -1.0, + }; + s.baseline_shift_pt += dir * SCRIPT_POSITION * s.size_pt; + s.size_pt *= SCRIPT_SIZE; +} + +/// The rendering path for a `SmallCaps` character style. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum SmallCapsMode { + None, + OpenType, + Synthetic, +} + +/// Whether the style's selected face has an `smcp` feature (a font load and GSUB parse). +pub(super) fn probe_smcp(fonts: &mut FontDb, style: &CharStyle) -> bool { + #[cfg(test)] + SMCP_PROBES.with(|c| c.set(c.get() + 1)); + fonts.selected_face_has_feature(&style.font_family, style.weight, style.italic, Tag::new(b"smcp")) +} + +#[cfg(test)] +thread_local! { + pub(super) static SMCP_PROBES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +pub(super) fn small_caps_mode(caps: Caps, face_has_smcp: bool) -> SmallCapsMode { + match caps { + Caps::SmallCaps if face_has_smcp => SmallCapsMode::OpenType, + Caps::SmallCaps => SmallCapsMode::Synthetic, + _ => SmallCapsMode::None, + } +} + +/// A style's horizontal scale; unset (zero or negative) is 100%. +pub(super) fn effective_horizontal_scale(st: &CharStyle) -> f32 { + if st.horizontal_scale > 0.0 && st.horizontal_scale.is_finite() { st.horizontal_scale } else { 1.0 } +} + +/// OpenType feature settings of a character style (CSS `font-feature-settings` items). +pub(super) fn feature_list(st: &CharStyle, small_caps: SmallCapsMode) -> Vec { + let mut feats: Vec = Vec::new(); + // Optical and manual kerning replace the font's kerning table; a character with a manual + // kern is manually kerned whatever its mode (as in Photoshop). + if st.kerning != Kerning::Metrics || st.kern != 0.0 { + feats.push("\"kern\" 0".into()); + } + if !st.ligatures { + feats.push("\"liga\" 0".into()); + feats.push("\"clig\" 0".into()); + } + if st.discretionary_ligatures { + feats.push("\"dlig\" 1".into()); + } + if small_caps == SmallCapsMode::OpenType { + feats.push("\"smcp\" 1".into()); + } + for f in &st.features { + if f.tag.len() == 4 && f.tag.is_ascii() { + feats.push(format!("\"{}\" {}", f.tag, f.value)); + } + } + feats +} + +/// The font variations for a run: the explicit axis values, plus `opsz` at the type size when the +/// style doesn't set it (as CSS `font-optical-sizing: auto`). A font without an `opsz` axis +/// ignores it. +pub(super) fn variation_list(st: &CharStyle) -> Vec { + let mut vars: Vec = + st.variations.iter().filter(|v| v.axis.len() == 4 && v.axis.is_ascii() && v.value.is_finite()).map(|v| format!("\"{}\" {}", v.axis, v.value)).collect(); + if st.size_pt.is_finite() && !st.variations.iter().any(|v| v.axis == "opsz") { + vars.push(format!("\"opsz\" {}", st.size_pt.max(0.01))); + } + vars +} + +pub(super) fn style_props(st: &CharStyle, k: f32, fallback: &[String], idx: u32, small_caps: SmallCapsMode) -> Vec> { + let px = (st.size_pt * k).max(0.01); + let mut fam: Vec = Vec::new(); + if !st.font_family.is_empty() { + fam.push(quote(&st.font_family)); + } + // Serif runs fall back to a Mincho face for Japanese (craft-fonts), others to a Gothic one. + if crate::craft_fonts::is_serif_family(&st.font_family) { + fam.extend(crate::craft_fonts::mincho_first(fallback).iter().map(|f| quote(f))); + } else { + fam.extend(fallback.iter().map(|f| quote(f))); + } + fam.push("sans-serif".into()); + let feats = feature_list(st, small_caps); + let vars = variation_list(st); + vec![ + StyleProperty::FontFamily(FontFamily::Source(Cow::Owned(fam.join(", ")))), + StyleProperty::FontSize(px), + StyleProperty::FontWeight(FontWeight::new(st.weight.clamp(1, 1000) as f32)), + StyleProperty::FontStyle(if st.italic { FontStyle::Italic } else { FontStyle::Normal }), + StyleProperty::FontFeatures(FontFeatures::Source(Cow::Owned(feats.join(", ")))), + StyleProperty::FontVariations(FontVariations::Source(Cow::Owned(vars.join(", ")))), + StyleProperty::LetterSpacing(st.tracking / 1000.0 * px), + StyleProperty::Underline(st.underline), + StyleProperty::Strikethrough(st.strikethrough), + StyleProperty::Brush(RunBrush(idx, 0)), + StyleProperty::Locale(st.language.as_deref().and_then(|l| parley::fontique::Language::parse(l).ok())), + ] +} + +/// Closing CJK punctuation: its full-width cell has blank space after the mark. +fn is_closing(c: char) -> bool { + matches!(c, '、' | '。' | ',' | '.' | '」' | '』' | ')' | '〕' | '】' | '〉' | '》' | '〙' | '〗' | ']' | '}') +} + +/// Opening CJK brackets: blank space before the mark. +fn is_opening(c: char) -> bool { + matches!(c, '「' | '『' | '(' | '〔' | '【' | '〈' | '《' | '〘' | '〖' | '[' | '{') +} + +/// Basic Japanese punctuation squeeze (JIS X 4051 style) for one line in line space: between a +/// closing mark and a following opening or closing mark, the closing mark's trailing half-em +/// blank is removed; between two opening brackets, the second one's leading half-em. Clusters and +/// glyphs from the squeezed point on move back. Returns the total length removed. +pub(crate) fn squeeze_punctuation(text: &str, clusters: &mut [ClusterInfo], glyphs: &mut [PlacedGlyph]) -> f32 { + let first = |c: &ClusterInfo| text.get(c.range.clone()).and_then(|s| s.chars().next()); + let last = |c: &ClusterInfo| text.get(c.range.clone()).and_then(|s| s.chars().next_back()); + // Shift to apply from each cluster on. + let mut shifts = vec![0.0f32; clusters.len()]; + let mut total = 0.0f32; + for i in 1..clusters.len() { + let (Some(prev), Some(cur)) = (clusters.get(i - 1), clusters.get(i)) else { continue }; + if prev.rtl || cur.rtl { + continue; + } + let (Some(a), Some(b)) = (last(prev), first(cur)) else { continue }; + let cut = if is_closing(a) && (is_opening(b) || is_closing(b)) { + prev.advance * 0.5 + } else if is_opening(a) && is_opening(b) { + cur.advance * 0.5 + } else { + 0.0 + }; + if cut.is_finite() && cut > 0.0 { + total += cut; + } + if let Some(s) = shifts.get_mut(i) { + *s = total; + } + } + if total <= 0.0 { + return 0.0; + } + let starts: Vec = clusters.iter().map(|c| c.x).collect(); + for (c, s) in clusters.iter_mut().zip(&shifts) { + c.x -= s; + } + for g in glyphs.iter_mut() { + let i = starts.iter().rposition(|&s| s <= g.x + 1e-3).unwrap_or(0); + g.x -= shifts.get(i).copied().unwrap_or(0.0); + } + total +} + +/// Whether to embolden a face synthetically. Font matching (fontique) asks for it whenever the +/// requested weight is above the face's, so Regular (400) from a family with only W3 (300) and W6 +/// (600), like Hiragino Mincho ProN, came out as a smeared bold W3. Like Photoshop and CSS, only +/// a bold request (≥ 600) on a face that isn't bold (≤ 500) is emboldened; anything else uses the +/// nearest face as it is (Faux Bold stays a separate, explicit style). +pub(crate) fn synthetic_bold(matcher_says: bool, requested: u16, face_weight: f32) -> bool { + matcher_says && requested >= 600 && face_weight <= 500.0 +} + +/// Height of the lowercase ascender ('d') of the tallest run on the line. +pub(super) fn first_ascent(line: &parley::Line<'_, RunBrush>) -> Option { + use skrifa::MetadataProvider; + let mut best: Option = None; + for run in line.runs() { + let fd = run.font(); + let Ok(font) = skrifa::FontRef::from_index(fd.data.as_ref(), fd.index) else { + continue; + }; + let coords: Vec = run.normalized_coords().iter().map(|&c| skrifa::instance::NormalizedCoord::from_bits(c)).collect(); + let loc = skrifa::instance::LocationRef::new(&coords); + let size = skrifa::instance::Size::new(run.font_size()); + let h = font.charmap().map('d').and_then(|g| font.glyph_metrics(size, loc).bounds(g)).map(|b| b.y_max).or_else(|| { + let m = font.metrics(size, loc); + m.cap_height.or(Some(m.ascent * 0.75)) + }); + if let Some(h) = h { + best = Some(best.map_or(h, |b: f32| b.max(h))); + } + } + best +} + +/// Hangul (syllables and jamo). +fn is_hangul(c: char) -> bool { + matches!(c, '\u{1100}'..='\u{11FF}' | '\u{3130}'..='\u{318F}' | '\u{A960}'..='\u{A97F}' | '\u{AC00}'..='\u{D7AF}' | '\u{D7B0}'..='\u{D7FF}') +} + +/// The byte ranges of `text` made of Hangul, each as long as it runs. +pub(crate) fn hangul_runs(text: &str) -> Vec> { + let mut runs: Vec> = Vec::new(); + for (i, c) in text.char_indices().filter(|&(_, c)| is_hangul(c)) { + match runs.last_mut() { + Some(r) if r.end == i => r.end = i + c.len_utf8(), + _ => runs.push(i..i + c.len_utf8()), + } + } + runs +} diff --git a/crates/text/src/layout/vertical.rs b/crates/text/src/layout/vertical.rs new file mode 100644 index 0000000000..beabcfbf05 --- /dev/null +++ b/crates/text/src/layout/vertical.rs @@ -0,0 +1,149 @@ +use super::*; + +/// How a character is set in vertical type (a simplification of Unicode's +/// `Vertical_Orientation`, UAX #50). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum VClass { + /// Rotated 90° clockwise (Latin, digits, most symbols). + Rotate = 0, + /// Upright (ideographs, kana, Hangul, full-width forms, CJK punctuation such as 、。), + /// using a vertical alternate when the font has one. + Upright = 1, + /// Upright through its vertical alternate (brackets, the long-vowel mark, dashes); rotated + /// when the font has none. + AlternateOrRotate = 2, +} + +/// The vertical-type class of a character. +pub fn vertical_class(c: char) -> VClass { + let u = c as u32; + let alt = matches!( + u, + 0x2014..=0x2016 + | 0x2025 + | 0x2026 + | 0x2329 + | 0x232A + | 0x3008..=0x3011 + | 0x3014..=0x301F + | 0x3030 + | 0x30A0 + | 0x30FC + | 0xFE59..=0xFE5E + | 0xFF08 + | 0xFF09 + | 0xFF0D + | 0xFF1A..=0xFF1E + | 0xFF3B + | 0xFF3D + | 0xFF3F + | 0xFF5B..=0xFF60 + | 0xFFE3 + ); + if alt { + return VClass::AlternateOrRotate; + } + // Half-width katakana and Hangul rotate like other half-width text. + if (0xFF61..=0xFFDC).contains(&u) { + return VClass::Rotate; + } + let upright = crate::cjk::classify(c).is_some() + || matches!(u, 0xA7 | 0xA9 | 0xAE | 0xB1 | 0xBC..=0xBE | 0xD7 | 0xF7 | 0x2E80..=0x2EFF | 0xFE10..=0xFE1F | 0xFE30..=0xFE4F | 0x1F000..=0x1FAFF); + if upright { VClass::Upright } else { VClass::Rotate } +} + +/// Placement data of one vertical-type glyph (before mapping to text space). +pub(super) struct VGlyph { + pub(super) upright: bool, + /// Advance along the column (px). + pub(super) advance: f32, + /// Upright: distance from the top of the glyph's cell down to its baseline (px). + pub(super) origin: f32, + /// Rotated: distance from the column centre line to the glyph's baseline (px). + pub(super) centre: f32, +} + +/// Vertical metrics of a font instance: `VORG`, `vhea`/`vmtx`, else the ideographic em box. +pub(super) struct VMetrics<'a> { + font: Option>, + coords: Vec, + /// px per font unit. + scale: f32, + /// Em-box fallback origin (px below the cell top). + em_origin: f32, +} + +impl<'a> VMetrics<'a> { + pub(super) fn new(fd: &'a FontData, coords: &[i16], size: f32) -> Self { + use skrifa::MetadataProvider; + let font = skrifa::FontRef::from_index(fd.data.as_ref(), fd.index).ok(); + let coords: Vec = coords.iter().map(|&c| skrifa::instance::NormalizedCoord::from_bits(c)).collect(); + let (scale, em_origin) = match &font { + Some(f) => { + let m = f.metrics(skrifa::instance::Size::unscaled(), skrifa::instance::LocationRef::new(&coords)); + let upem = f32::from(m.units_per_em).max(1.0); + let (asc, desc) = (m.ascent, -m.descent); + // Ideographic em box: the em centred on the font's ascent/descent span. + let r = if asc + desc > 0.0 && asc.is_finite() && desc.is_finite() { (asc / (asc + desc)).clamp(0.0, 1.0) } else { 0.88 }; + (size / upem, size * r) + } + None => (0.0, size * 0.88), + }; + Self { font, coords, scale, em_origin } + } + + pub(super) fn cmap(&self, c: char) -> Option { + use skrifa::MetadataProvider; + self.font.as_ref()?.charmap().map(c).map(|g| g.to_u32()) + } + + /// Distance from the top of an upright glyph's cell to its baseline (px). + pub(super) fn origin(&self, gid: u32) -> f32 { + self.vertical_origin(gid).filter(|v| v.is_finite()).unwrap_or(self.em_origin) + } + + fn vertical_origin(&self, gid: u32) -> Option { + use skrifa::MetadataProvider; + use skrifa::raw::TableProvider; + let f = self.font.as_ref()?; + let g = skrifa::GlyphId::new(gid); + if let Ok(vorg) = f.vorg() { + return Some(f32::from(vorg.vertical_origin_y(g)) * self.scale); + } + let tsb = f.vmtx().ok()?.side_bearing(g)?; + // Top of the outline (font units), from the outline itself (glyf and CFF alike). + let outline = f.outline_glyphs().get(g)?; + let mut pen = YMax(None); + let settings = skrifa::outline::DrawSettings::unhinted(skrifa::instance::Size::unscaled(), skrifa::instance::LocationRef::new(&self.coords)); + outline.draw(settings, &mut pen).ok()?; + Some((pen.0? + f32::from(tsb)) * self.scale) + } +} + +/// Outline pen recording the largest y. +struct YMax(Option); + +impl YMax { + fn add(&mut self, y: f32) { + self.0 = Some(self.0.map_or(y, |m| m.max(y))); + } +} + +impl skrifa::outline::OutlinePen for YMax { + fn move_to(&mut self, _x: f32, y: f32) { + self.add(y); + } + fn line_to(&mut self, _x: f32, y: f32) { + self.add(y); + } + fn quad_to(&mut self, _cx0: f32, cy0: f32, _x: f32, y: f32) { + self.add(cy0); + self.add(y); + } + fn curve_to(&mut self, _cx0: f32, cy0: f32, _cx1: f32, cy1: f32, _x: f32, y: f32) { + self.add(cy0); + self.add(cy1); + self.add(y); + } + fn close(&mut self) {} +} diff --git a/crates/text/src/psd.rs b/crates/text/src/psd.rs index 4f3f54c367..7c51759482 100644 --- a/crates/text/src/psd.rs +++ b/crates/text/src/psd.rs @@ -20,6 +20,23 @@ use photocraft_psd::descriptor::{Descriptor, Id, UnicodeString, Value as D, Vers use crate::engine_data::{self as ed, Value as E}; use crate::fonts::guess_from_postscript; +mod build; +mod edit; +mod import; + +#[cfg(test)] +pub(crate) use build::font_entry; +pub use build::{MAX_TEXT_INDEX, build_engine_data, build_txt2, build_txt2_at, build_tysh, needs_txt2}; +pub(crate) use build::{font_set, paragraph_properties, style_sheet_data}; +pub use edit::{set_text_index, text_index, txt2_object_count}; +#[cfg(test)] +use import::MAX_ENGINE_RUNS; +pub use import::{ + OPENTYPE_KEYS, TXT2_FEATURES, TXT2_STYLISTIC_SETS, apply_txt2, apply_txt2_frame, apply_txt2_path, parse_txt2, refine_legacy_point_origin, + text_layer_from_tysh, +}; +pub(crate) use import::{arr_f, char_style, para_style, postscript_for, utf16_to_byte_lengths}; + /// Parsed `TySh` contents. #[derive(Clone, Debug, PartialEq)] pub struct TySh { @@ -141,1813 +158,6 @@ pub fn engine_text_is_blank(tysh: &[u8]) -> bool { .unwrap_or(false) } -/// Parses the document's `Txt2` block (Photoshop's text engine data for all type layers). -pub fn parse_txt2(data: &[u8]) -> Option { - // Txt2 is a bare sequence of `/key value` pairs (no enclosing `<< >>`). - let mut wrapped = Vec::with_capacity(data.len() + 4); - wrapped.extend_from_slice(b"<<"); - wrapped.extend_from_slice(data); - wrapped.extend_from_slice(b">>"); - ed::parse(&wrapped).ok().filter(|v| matches!(v, E::Dict(_))) -} - -/// Applies what Photoshop keeps only in `Txt2` to `layer`, read from `tysh`: the automatic -/// kerning modes (EngineData writes Optical and "0" alike as `AutoKerning true`) and the -/// OpenType settings besides (discretionary) ligatures: stylistic sets, contextual alternates, -/// swashes and the rest ([`TXT2_FEATURES`]), which Photoshop leaves out of EngineData. Only when -/// the layer's `TextIndex` entry still holds the layer's text (an edit elsewhere leaves `Txt2` -/// stale). -/// -/// Observed layout: `Txt2 /1` is the list of text objects; an object's `/0` is its text model -/// with `/0` the text (`\r` breaks, trailing `\r`) and `/6 /0` its style runs, each -/// `<< /0 << /0 << … /6 < = Option<(S, S)>; + +/// Right-click while transforming, in Photoshop's order: what the box's handles do, then Rotate +/// and Flip, which turn the open box without committing it (`transform_tool::intercept`). +/// Content-Aware Scale and Puppet Warp are greyed while a box is open. +pub const TRANSFORM_MENU: &[Row] = &[ + Some(("Free Transform", "edit.freeTransform")), + Some(("Scale", "edit.transform.scale")), + Some(("Rotate", "edit.transform.rotate")), + Some(("Skew", "edit.transform.skew")), + Some(("Distort", "edit.transform.distort")), + Some(("Perspective", "edit.transform.perspective")), + Some(("Warp", "edit.transform.warp")), + None, + Some(("Content-Aware Scale", "edit.contentAwareScale")), + Some(("Puppet Warp", "edit.puppetWarp")), + None, + Some(("Rotate 180°", "edit.transform.rotate180")), + Some(("Rotate 90° Clockwise", "edit.transform.rotate90Cw")), + Some(("Rotate 90° Counter Clockwise", "edit.transform.rotate90Ccw")), + None, + Some(("Flip Horizontal", "edit.transform.flipHorizontal")), + Some(("Flip Vertical", "edit.transform.flipVertical")), +]; + +/// Photoshop's pasteboard menu (right-click outside the image): the pasteboard colour, the choice +/// Preferences › Interface also offers. The ids are this menu's own: [`choose`] turns them into +/// `prefs.set` (`pasteboard.`) or opens the Color Picker. +pub const PASTEBOARD_MENU: &[Row] = &[ + Some(("Default", "pasteboard.default")), + Some(("Black", "pasteboard.black")), + Some(("Dark Gray", "pasteboard.darkGray")), + Some(("Medium Gray", "pasteboard.mediumGray")), + Some(("Light Gray", "pasteboard.lightGray")), + Some(("Custom", "pasteboard.custom")), + None, + Some(("Select Custom Color…", PASTEBOARD_PICK)), +]; + +/// Photoshop's right-click menu inside text being edited: the edit rows act on the text (its +/// selection, the OS clipboard), the type rows on the layer, as the Type menu's do. Faux Bold and +/// Faux Italic are the Character panel's toggles (this menu's own ids, run as `type.setStyle`). +/// Convert to Paragraph Text and Convert to Point Text are both listed; the one that doesn't apply +/// greys out. The exact Photoshop placement is inferred (docs/context-menu-parity.md). +pub const TYPE_EDIT_MENU: &[Row] = &[ + Some(("Undo", "edit.undo")), + None, + Some(("Cut", "edit.cut")), + Some(("Copy", "edit.copy")), + Some(("Paste", "edit.paste")), + Some(("Select All", "select.all")), + None, + Some(("Check Spelling…", "edit.checkSpelling")), + Some(("Find and Replace Text…", "edit.findAndReplaceText")), + None, + Some(("Faux Bold", FAUX_BOLD)), + Some(("Faux Italic", FAUX_ITALIC)), + None, + Some(("Rasterize Type", "type.rasterizeTypeLayer")), + Some(("Create Work Path", "type.createWorkPath")), + Some(("Convert to Shape", "type.convertToShape")), + None, + Some(("Horizontal", "type.orientation.horizontal")), + Some(("Vertical", "type.orientation.vertical")), + None, + Some(("None", "type.antiAlias.none")), + Some(("Sharp", "type.antiAlias.sharp")), + Some(("Crisp", "type.antiAlias.crisp")), + Some(("Strong", "type.antiAlias.strong")), + Some(("Smooth", "type.antiAlias.smooth")), + Some(("Windows LCD", "type.antiAlias.windowsLcd")), + Some(("Windows", "type.antiAlias.windows")), + None, + Some(("Convert to Paragraph Text", "type.convertToParagraphText")), + Some(("Convert to Point Text", "type.convertToPointText")), + Some(("Warp Text…", "type.warpText")), +]; + +/// Right-click with a Type tool over type that isn't being edited (#7324): the type edit menu's +/// layer rows. Its edit rows would act on the document instead of the text, and Faux Bold/Italic +/// on characters being edited, so they are left out. +pub const TYPE_LAYER_MENU: &[Row] = &[ + Some(("Check Spelling…", "edit.checkSpelling")), + Some(("Find and Replace Text…", "edit.findAndReplaceText")), + None, + Some(("Rasterize Type", "type.rasterizeTypeLayer")), + Some(("Create Work Path", "type.createWorkPath")), + Some(("Convert to Shape", "type.convertToShape")), + None, + Some(("Horizontal", "type.orientation.horizontal")), + Some(("Vertical", "type.orientation.vertical")), + None, + Some(("None", "type.antiAlias.none")), + Some(("Sharp", "type.antiAlias.sharp")), + Some(("Crisp", "type.antiAlias.crisp")), + Some(("Strong", "type.antiAlias.strong")), + Some(("Smooth", "type.antiAlias.smooth")), + Some(("Windows LCD", "type.antiAlias.windowsLcd")), + Some(("Windows", "type.antiAlias.windows")), + None, + Some(("Convert to Paragraph Text", "type.convertToParagraphText")), + Some(("Convert to Point Text", "type.convertToPointText")), + Some(("Warp Text…", "type.warpText")), +]; + +/// The type edit menu's Faux Bold and Faux Italic rows. +pub const FAUX_BOLD: &str = "type.fauxBold"; +pub const FAUX_ITALIC: &str = "type.fauxItalic"; + +/// Type edit rows that act on the whole layer (it may stop being type): the edit ends first. +const ENDS_TYPE_EDIT: [&str; 5] = + ["type.rasterizeTypeLayer", "type.createWorkPath", "type.convertToShape", "type.convertToParagraphText", "type.convertToPointText"]; + +/// The pasteboard menu's Select Custom Color… row. +pub const PASTEBOARD_PICK: &str = "pasteboard.selectCustomColor"; + +/// The guide menu's Edit Selected Guides row: New Guide's dialog on the selected guide. +pub const GUIDE_EDIT: &str = "guides.editSelected"; +/// The guide menu's Clear Selected Guides row. +pub const GUIDE_CLEAR: &str = "guides.clearSelected"; + +/// Photoshop's guide menu (right-click on a guide), in its order. Its two Selected Guides rows act +/// on the guide the right-click selected; the rest are the View menu's. +pub const GUIDE_MENU: &[Row] = &[ + Some(("Edit Selected Guides", GUIDE_EDIT)), + None, + Some(("Lock Guides", "view.lockGuides")), + Some(("Clear Guides", "view.clearGuides")), + Some(("Clear Canvas Guides", "view.clearCanvasGuides")), + Some(("Clear Selected Guides", GUIDE_CLEAR)), + Some(("Clear Selected Artboard Guides", "view.clearSelectedArtboardGuides")), +]; + +/// The crop menu's row ids. A ratio row is `crop.ratio.`, the options bar's preset dropdown +/// key (`crop_size::dropdown_options`); a saved preset is `crop.preset.`, the n-th name the menu +/// opened with; an overlay row is `crop.overlay.` or `crop.overlayShow.`. +const CROP_RATIO: &str = "crop.ratio."; +const CROP_PRESET: &str = "crop.preset."; +const CROP_OVERLAY: &str = "crop.overlay."; +const CROP_SHOW: &str = "crop.overlayShow."; +pub const CROP_CLEAR: &str = "crop.clear"; +pub const CROP_NEW: &str = "crop.newPreset"; +pub const CROP_DELETE: &str = "crop.deletePreset"; +pub const CROP_CANCEL: &str = "crop.cancel"; +pub const CROP_COMMIT: &str = "crop.commit"; + +/// The crop menu (right-click on a pending crop, #6561): the options bar's preset dropdown, in its +/// order, and its Clear; the overlay and when it shows; then Cancel and Crop, the bar's ⊘ and ✓. +/// Built from the bar's own lists, so the two cannot disagree. Empty for any other menu. +pub fn crop_rows(menu: &CanvasToolMenu) -> Vec> { + use crate::crop_overlay::{CropOverlay, OverlayShow}; + let Some(users) = menu.crop.as_ref() else { return Vec::new() }; + let ratio = |(k, l): &(String, &str)| Some((l.to_string(), format!("{CROP_RATIO}{k}"))); + let (before, after): (Vec<_>, Vec<_>) = crate::crop_size::dropdown_options().into_iter().partition(|(k, _)| k != crate::crop_size::FRONT); + let mut rows: Vec> = before.iter().map(ratio).collect(); + rows.extend(users.iter().enumerate().map(|(i, name)| Some((name.clone(), format!("{CROP_PRESET}{i}"))))); + rows.extend(after.iter().map(ratio)); + rows.push(Some(("Clear".into(), CROP_CLEAR.into()))); + rows.push(None); + rows.push(Some(("New Crop Preset…".into(), CROP_NEW.into()))); + rows.push(Some(("Delete Crop Preset…".into(), CROP_DELETE.into()))); + rows.push(None); + rows.extend(CropOverlay::ALL.iter().map(|k| Some((k.label().to_string(), format!("{CROP_OVERLAY}{}", k.id()))))); + rows.push(None); + rows.extend(OverlayShow::ALL.iter().map(|k| Some((k.label().to_string(), format!("{CROP_SHOW}{}", k.id()))))); + rows.push(None); + rows.push(Some(("Cancel".into(), CROP_CANCEL.into()))); + rows.push(Some(("Crop".into(), CROP_COMMIT.into()))); + rows +} + +/// Is a crop row's label UI text (translated), rather than a saved preset's name? +pub fn crop_label_is_ui(id: &str) -> bool { + !id.starts_with(CROP_PRESET) +} + +/// Is `command` one of the crop menu's rows? +fn is_crop(menu: &CanvasToolMenu, command: &str) -> bool { + crop_rows(menu).iter().flatten().any(|(_, id)| id == command) +} + +/// The saved crop preset a `crop.preset.` row picks. +fn crop_preset<'a>(menu: &'a CanvasToolMenu, command: &str) -> Option<&'a String> { + let n = command.strip_prefix(CROP_PRESET)?.parse::().ok()?; + menu.crop.as_ref()?.get(n) +} + +/// The crop menu's checkmarks, as the options bar shows them: the dropdown's entry (a saved +/// preset the fields hold, else the mode or ratio, so a size preset checks W x H x Resolution), +/// the overlay and when it shows. +fn crop_checked(app: &PhotocraftApp, menu: &CanvasToolMenu, command: &str) -> bool { + let o = &app.ui.tool_options; + let user = crate::crop_presets::current_user(app); + if let Some(k) = command.strip_prefix(CROP_RATIO) { + return user.is_none() && k == o.crop_ratio; + } + if command.starts_with(CROP_PRESET) { + return user.is_some() && crop_preset(menu, command) == user.as_ref(); + } + if let Some(k) = command.strip_prefix(CROP_OVERLAY) { + return k == o.crop_overlay.id(); + } + command.strip_prefix(CROP_SHOW).is_some_and(|k| k == o.crop_overlay_show.id()) +} + +fn crop_enabled(app: &PhotocraftApp, menu: &CanvasToolMenu, command: &str) -> bool { + match command { + CROP_NEW => crate::crop_presets::savable(&app.ui.tool_options).is_some(), + CROP_DELETE => menu.crop.as_ref().is_some_and(|u| !u.is_empty()), + c => is_crop(menu, c), + } +} + +/// Right-click with `tool` on a pending crop: the crop menu at screen point `pos`. Only the Crop +/// tool itself, not one held over it (Space's Hand). +pub fn open_crop(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, pos: [f32; 2]) -> bool { + if tool != Tool::Crop || !crate::crop_ui::pending(app) || !pos.iter().all(|v| v.is_finite()) { + return false; + } + app.ui.brush_picker = None; + app.ui.layer_menu = None; + let users = crate::crop_presets::user_presets(app).into_iter().map(|(name, _)| name).collect(); + app.ui.canvas_tool_menu = Some(CanvasToolMenu { + pos, + tool, + has_selection: false, + has_path: false, + path_name: None, + transform: false, + pasteboard: false, + anchor: None, + text: false, + type_layer: false, + guide: false, + spelling: None, + crop: Some(users), + }); + crate::canvas_popup::mark_open(ctx, menu_id()); + true +} + +/// A crop row: each runs what its options-bar twin runs. +fn choose_crop(app: &mut PhotocraftApp, menu: &CanvasToolMenu, command: &str) -> Result<(), String> { + use crate::crop_overlay::{CropOverlay, OverlayShow}; + use crate::crop_presets::{Choice, apply_choice}; + match command { + CROP_CANCEL => crate::crop_ui::cancel(app), + CROP_COMMIT => crate::canvas::commit_crop(app), + CROP_NEW => apply_choice(app, Choice::New), + CROP_DELETE => apply_choice(app, Choice::Delete), + _ => { + let before = crate::crop_ui::preset_ratio(app); + if let Some(k) = command.strip_prefix(CROP_RATIO) { + apply_choice(app, Choice::Builtin(k.to_string())); + } else if let Some(name) = crop_preset(menu, command) { + apply_choice(app, Choice::User(name.clone())); + } else if command == CROP_CLEAR { + crate::crop_size::clear_ratio(&mut app.ui.tool_options); + } else if let Some(k) = command.strip_prefix(CROP_OVERLAY).and_then(CropOverlay::from_id) { + crate::crop_overlay::set_overlay(&mut app.ui.tool_options, k); + } else if let Some(k) = command.strip_prefix(CROP_SHOW).and_then(OverlayShow::from_id) { + app.ui.tool_options.crop_overlay_show = k; + } + // As the options bar does: a saved preset or Clear changes the ratio without refitting + // the frame, so refit it when the ratio (or W x H) the frame follows changed. + if crate::crop_ui::preset_ratio(app) != before { + crate::crop_ui::apply_ratio(app); + } + } + } + Ok(()) +} + +/// The pasteboard colours in the menu's order, which Space+F steps through. +const CANVAS_COLORS: [CanvasColor; 6] = + [CanvasColor::Default, CanvasColor::Black, CanvasColor::DarkGray, CanvasColor::MediumGray, CanvasColor::LightGray, CanvasColor::Custom]; + +/// Photoshop's Space+F (⇧Space+F backwards): the next pasteboard colour, round and round. Saved +/// like a choice in the pasteboard menu (`interface.canvasColor`). +pub fn cycle_canvas_color(app: &mut PhotocraftApp, backward: bool) -> Result<(), String> { + let n = CANVAS_COLORS.len(); + let at = CANVAS_COLORS.iter().position(|c| *c == app.session.prefs().interface.canvas_color).unwrap_or(0); + let next = if backward { (at + n - 1) % n } else { (at + 1) % n }; + let name = CANVAS_COLORS.get(next).map_or("default", |c| c.name()); + app.run("prefs.set", json!({"values": {"interface.canvasColor": name}})).map(|_| ()) +} + +/// The Zoom and Hand tools' context menu: the fixed zooms of the View menu (plus the Hand tool's +/// Fill Screen), then the zoom steps last, in Photoshop's order (#6005). +pub const VIEW_MENU: &[Row] = &[ + Some(("Fit on Screen", "view.fitOnScreen")), + Some(("Fill Screen", FILL_SCREEN)), + Some(("100%", "view.actualPixels")), + Some(("200%", "view.twoHundredPercent")), + Some(("Print Size", "view.printSize")), + None, + Some(("Zoom In", "view.zoomIn")), + Some(("Zoom Out", "view.zoomOut")), +]; + +/// The view menu's Fill Screen row. Photoshop has no View menu command for it, so the menu sets +/// the view itself. +pub const FILL_SCREEN: &str = "view.fillScreen"; + +/// Photoshop's selection-tool context menu with an active selection, in its order. Its Generative +/// Fill row has no PhotoCraft command and is left out. Rows stay visible and grey out exactly like +/// their menu-bar twins. +pub const SELECTION_MENU: &[Row] = &[ + Some(("Deselect", "select.deselect")), + Some(("Select Inverse", "select.inverse")), + Some(("Feather…", "select.modify.feather")), + Some(("Select and Mask…", "select.selectAndMask")), + None, + Some(("Save Selection…", "select.saveSelection")), + Some(("Make Work Path…", "select.toWorkPath")), + None, + Some(("Layer via Copy", "layer.new.layerViaCopy")), + Some(("Layer via Cut", "layer.new.layerViaCut")), + Some(("New Layer…", "layer.new.layer")), + None, + Some(("Free Transform", "edit.freeTransform")), + Some(("Transform Selection", "select.transformSelection")), + Some(("Distort", "edit.transform.distort")), + Some(("Perspective", "edit.transform.perspective")), + None, + Some(("Delete and Fill Selection", "edit.deleteAndFillSelection")), + Some(("Fill…", "edit.fill")), + Some(("Stroke…", "edit.stroke")), + Some(("Content-Aware Fill…", "edit.contentAwareFill")), + None, + Some(("Last Filter", "filter.lastFilter")), + None, + Some(("Fade…", "edit.fade")), +]; + +/// The selection tools' context menu with nothing selected: making a selection. +pub const NO_SELECTION_MENU: &[Row] = &[ + Some(("Select All", "select.all")), + Some(("Reselect", "select.reselect")), + Some(("Color Range…", "select.colorRange")), + None, + Some(("Load Selection…", "select.loadSelection")), +]; + +/// Photoshop's Pen context menu order. Rows whose operation is not applicable to the current +/// path or layer stay visible and disabled. +pub const PEN_MENU: &[Row] = &[ + Some(("Create Vector Mask", "layer.vectorMask.fromPath")), + Some(("Delete Path", "path.delete")), + None, + Some(("Define Custom Shape…", "edit.defineCustomShape")), + None, + Some(("Make Selection…", "path.toSelection")), + Some(("New Guides From Shape", "view.newGuidesFromShape")), + Some(("Fill Path…", "path.fill")), + Some(("Stroke Path…", "path.stroke")), + None, + Some(("Clipping Path…", "path.clippingPath.set")), + None, + Some(("Free Transform Path", "path.transform")), + None, + Some(("Unite Shapes", "layer.combineShapes.unite")), + Some(("Subtract Front Shape", "layer.combineShapes.subtractFrontShape")), + Some(("Unite Shapes at Overlap", "layer.combineShapes.intersectShapeAreas")), + Some(("Subtract Shapes at Overlap", "layer.combineShapes.excludeOverlappingShapes")), + None, + Some(("Copy Fill", "path.style.copyFill")), + Some(("Copy Complete Stroke", "path.style.copyStroke")), + None, + Some(("Paste Fill", "path.style.pasteFill")), + Some(("Paste Complete Stroke", "path.style.pasteStroke")), + None, + Some(("Isolate Layers", "select.isolateLayers")), + None, + Some(("Make Symmetry Path", "paint.symmetryFromPath")), + Some(("Disable Symmetry Path", "paint.symmetryDisable")), +]; + +/// Tools whose plain canvas right-click offers selection actions. +pub fn applies(tool: Tool) -> bool { + matches!( + tool, + Tool::RectMarquee + | Tool::EllipseMarquee + | Tool::SingleRowMarquee + | Tool::SingleColumnMarquee + | Tool::Lasso + | Tool::PolygonLasso + | Tool::MagneticLasso + | Tool::MagicWand + | Tool::ObjectSelection + // Its brush is set from the options bar's chip; the canvas right-click is the + // selection menu, as in Photoshop (#7268). + | Tool::QuickSelection + ) || path_menu(tool) +} + +/// Tools whose canvas right-click opens the path menu ([`PEN_MENU`]): the Pen, and the Path +/// Selection and Direct Selection tools, whose Photoshop menu offers the same whole-path actions +/// for the selected path (#1056). +pub fn path_menu(tool: Tool) -> bool { + matches!(tool, Tool::Pen | Tool::PathSelection | Tool::DirectSelection) +} + +/// Tools whose plain canvas right-click offers the view menu. +pub fn is_view_tool(tool: Tool) -> bool { + matches!(tool, Tool::Zoom | Tool::Hand) +} + +/// The selection tools' rows, with or without an active selection. +pub fn selection_rows(has_selection: bool) -> &'static [Row] { + if has_selection { SELECTION_MENU } else { NO_SELECTION_MENU } +} + +/// The rows of an open menu. +pub fn rows(menu: &CanvasToolMenu) -> &'static [Row] { + if menu.crop.is_some() { + // Built per menu: [`crop_rows`]. + &[] + } else if menu.guide { + GUIDE_MENU + } else if menu.pasteboard { + PASTEBOARD_MENU + } else if menu.transform { + TRANSFORM_MENU + } else if menu.anchor.is_some() { + VIEW_MENU + } else if menu.text { + TYPE_EDIT_MENU + } else if menu.type_layer { + TYPE_LAYER_MENU + } else if path_menu(menu.tool) { + PEN_MENU + } else { + selection_rows(menu.has_selection) + } +} + +/// Is `command` one of the open menu's rows, and enabled? +pub fn available(app: &PhotocraftApp, menu: &CanvasToolMenu, command: &str) -> bool { + (rows(menu).iter().flatten().any(|(_, id)| *id == command) || is_spelling(menu, command) || is_crop(menu, command)) && entry_enabled(app, menu, command) +} + +/// Is `command` the transform box's current mode (checked in the transform menu)? +/// Scale stays Free Transform's mode (only Free Transform is checked). Rotate is its own mode. +/// Warp is not a box mode (it is its own session), and `for_command` would read it as Free. +pub(crate) fn mode_checked(app: &PhotocraftApp, menu: &CanvasToolMenu, command: &str) -> bool { + if menu.crop.is_some() { + return crop_checked(app, menu, command); + } + if menu.guide { + return command == "view.lockGuides" && app.ui.extras.lock_guides; + } + if menu.pasteboard { + return pasteboard_choice(command) == Some(app.session.prefs().interface.canvas_color); + } + if menu.text || menu.type_layer { + return type_checked(app, command); + } + menu.transform + && matches!(command, "edit.freeTransform" | "edit.transform.rotate" | "edit.transform.skew" | "edit.transform.distort" | "edit.transform.perspective") + && app.ui.transform.as_ref().is_some_and(|t| t.mode == crate::state::TransformMode::for_command(command)) +} + +/// The type edit menu's checkmarks: the faux styles at the selection, the layer's orientation and +/// anti-aliasing. +fn type_checked(app: &PhotocraftApp, command: &str) -> bool { + use photocraft_doc::text::Orientation; + let Some(t) = crate::type_tool::target_text(app) else { return false }; + match command { + FAUX_BOLD | FAUX_ITALIC => crate::type_tool::styles_at(app).is_some_and(|(c, _)| if command == FAUX_BOLD { c.faux_bold } else { c.faux_italic }), + "type.orientation.horizontal" => t.orientation == Orientation::Horizontal, + "type.orientation.vertical" => t.orientation == Orientation::Vertical, + c => c.strip_prefix("type.antiAlias.") == Some(photocraft_engine::type_extra_cmds::aa_name(t.antialias)), + } +} + +/// Is the Type tool editing text, so that a right-click opens the type edit menu? +pub fn editing_text(app: &PhotocraftApp, tool: Tool) -> bool { + tool.is_type() && app.ui.text_edit.is_some() +} + +/// The committed type layer under document point `doc` when a right-click there with a Type tool +/// opens the type layer menu (#7324). The Type Mask tools are left out: to them existing type is +/// just pixels. +pub fn type_layer_at(app: &mut PhotocraftApp, tool: Tool, doc: [f64; 2]) -> Option { + if !tool.is_type() || tool.is_type_mask() || app.ui.text_edit.is_some() || !doc.iter().all(|v| v.is_finite()) { + return None; + } + crate::type_tool::hit_layer(app, doc[0], doc[1]) +} + +/// Make the right-clicked type layer `id` the active layer, which the structural rows (Rasterize +/// Type, Convert to Shape…) act on and the checks show. Inside a multiselection the selection stays, +/// so the formatting rows still act on every selected type layer, as the Type menu's do; outside it +/// the type replaces the selection, as a click with the Type tool does. +fn target_type_layer(app: &mut PhotocraftApp, id: photocraft_doc::LayerId) -> bool { + let Some(st) = app.session.active() else { return false }; + let selected = st.selected_layers(); + if st.active_layer == Some(id) { + true + } else if selected.contains(&id) { + photocraft_engine::layer_multi_cmds::set_selection(&mut app.session, selected, Some(id), Some(id)).is_ok() + } else { + app.session.select_layer(id).is_ok() + } +} + +/// The misspelled word of the edited text under document point `doc`, with its suggestions. +fn spelling_at(app: &mut PhotocraftApp, doc: [f64; 2]) -> Option { + let layer = app.ui.text_edit.as_ref()?.layer; + if !doc.iter().all(|v| v.is_finite()) { + return None; + } + let at = crate::type_tool::offset_at(app, photocraft_doc::LayerId(layer), doc[0], doc[1]); + let found = app.session.execute("edit.checkSpelling", json!({"action": "list", "layer": layer, "suggestions": MAX_SUGGESTIONS})).ok()?; + let hit = found["misspellings"].as_array()?.iter().find(|m| { + let (a, b) = (m["start"].as_u64().unwrap_or(u64::MAX) as usize, m["end"].as_u64().unwrap_or(0) as usize); + a <= at && at <= b + })?; + Some(Spelling { + layer, + start: hit["start"].as_u64()? as usize, + end: hit["end"].as_u64()? as usize, + word: hit["word"].as_str()?.to_string(), + suggestions: hit["suggestions"].as_array()?.iter().filter_map(|s| s.as_str().map(str::to_string)).take(MAX_SUGGESTIONS).collect(), + }) +} + +/// The spelling rows heading the type edit menu (label, id): the suggestions, or a greyed note +/// when there are none, then Add to Dictionary. Empty away from a misspelled word. +pub fn spelling_rows(menu: &CanvasToolMenu) -> Vec<(String, String)> { + let Some(sp) = menu.spelling.as_ref().filter(|_| menu.text) else { return Vec::new() }; + let mut rows: Vec<(String, String)> = sp.suggestions.iter().enumerate().map(|(i, s)| (s.clone(), format!("{SPELLING_REPLACE}{i}"))).collect(); + if rows.is_empty() { + rows.push(("No Spelling Suggestions".into(), SPELLING_NONE.into())); + } + rows.push(("Add to Dictionary".into(), SPELLING_ADD.into())); + rows +} + +/// Is `command` one of the menu's spelling rows? +fn is_spelling(menu: &CanvasToolMenu, command: &str) -> bool { + spelling_rows(menu).iter().any(|(_, id)| id == command) +} + +/// Does a spelling row's label come from the UI (translated) rather than from the dictionary? +pub fn spelling_label_is_ui(id: &str) -> bool { + matches!(id, SPELLING_NONE | SPELLING_ADD) +} + +/// Right-click over a Free Transform box: its modes. +pub fn open_transform(app: &mut PhotocraftApp, ctx: &Context, pos: [f32; 2]) -> bool { + if !pos.iter().all(|v| v.is_finite()) { + return false; + } + app.ui.brush_picker = None; + app.ui.layer_menu = None; + app.ui.canvas_tool_menu = Some(CanvasToolMenu { + pos, + tool: app.ui.tool, + has_selection: false, + has_path: false, + path_name: None, + transform: true, + pasteboard: false, + anchor: None, + text: false, + type_layer: false, + guide: false, + spelling: None, + crop: None, + }); + crate::canvas_popup::mark_open(ctx, menu_id()); + true +} + +/// The pasteboard colour a pasteboard menu row picks (`None` for Select Custom Color… or a row +/// of another menu). +fn pasteboard_choice(command: &str) -> Option { + command.strip_prefix("pasteboard.").and_then(CanvasColor::parse) +} + +/// The engine command (and params) a pasteboard row runs, for the automation policy: every row +/// changes a preference. +pub fn engine_call(app: &PhotocraftApp, menu: &CanvasToolMenu, command: &str) -> (String, Value) { + if menu.crop.is_some() && command == CROP_COMMIT { + return ("image.crop".into(), json!({})); + } + if menu.guide { + let selected = crate::guide_select::selected(app); + return match command { + GUIDE_EDIT => ("view.editGuide".into(), json!({})), + GUIDE_CLEAR => ("view.deleteGuide".into(), selected.map_or(json!({}), |(v, i)| crate::guide_select::delete_params(v, i))), + _ => (command.into(), json!({})), + }; + } + match pasteboard_choice(command) { + Some(c) if menu.pasteboard => ("prefs.set".into(), json!({"values": {"interface.canvasColor": c.name()}})), + _ if menu.pasteboard => ("prefs.set".into(), json!({})), + _ if menu.text && matches!(command, FAUX_BOLD | FAUX_ITALIC) => ("type.setStyle".into(), json!({})), + _ if is_spelling(menu, command) => spelling_call(menu, command), + _ => (command.into(), json!({})), + } +} + +/// The `edit.checkSpelling` call a spelling row makes: replace the word with a suggestion, or add +/// it to the user dictionary. +fn spelling_call(menu: &CanvasToolMenu, command: &str) -> (String, Value) { + let Some(sp) = menu.spelling.as_ref() else { return ("edit.checkSpelling".into(), json!({})) }; + let replace = command.strip_prefix(SPELLING_REPLACE).and_then(|n| n.parse::().ok()).and_then(|n| sp.suggestions.get(n)); + match replace { + Some(to) => { + ("edit.checkSpelling".into(), json!({"action": "change", "layer": sp.layer, "start": sp.start, "end": sp.end, "word": sp.word, "replace": to})) + } + None => ("edit.checkSpelling".into(), json!({"action": "addToDictionary", "word": sp.word})), + } +} + +/// Does a right-click with `tool` at document point `doc` open the pasteboard menu? Outside the +/// image, for the tools whose right-click has no job there: not the painting tools (their Brush +/// Preset picker or right-button erase), the Pen (its path menu) or text being edited. +pub fn pasteboard_at(app: &PhotocraftApp, tool: Tool, doc: [f64; 2]) -> bool { + let Some(st) = app.session.active() else { return false }; + let (w, h) = (f64::from(st.doc.size.width), f64::from(st.doc.size.height)); + let outside = doc.iter().all(|v| v.is_finite()) && (doc[0] < 0.0 || doc[1] < 0.0 || doc[0] >= w || doc[1] >= h); + outside && !path_menu(tool) && !crate::paint_mouse::has_brush_picker(tool) && !crate::paint_mouse::right_erases(app, tool) && app.ui.text_edit.is_none() +} + +/// Right-click on the pasteboard: its colour menu at screen point `pos`. +pub fn open_pasteboard(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, pos: [f32; 2]) -> bool { + if !pos.iter().all(|v| v.is_finite()) { + return false; + } + app.ui.brush_picker = None; + app.ui.layer_menu = None; + app.ui.canvas_tool_menu = Some(CanvasToolMenu { + pos, + tool, + has_selection: false, + has_path: false, + path_name: None, + transform: false, + pasteboard: true, + anchor: None, + text: false, + type_layer: false, + guide: false, + spelling: None, + crop: None, + }); + crate::canvas_popup::mark_open(ctx, menu_id()); + true +} + +/// Right-click at document point `doc` on a guide that `tool` could drag (the Move tool, or ⌘ with +/// a tool on which ⌘ moves guides, `canvas::command_guide_at`): select the guide and open the guide +/// menu at screen point `pos`. +pub fn open_guide(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, mods: egui::Modifiers, pos: [f32; 2], doc: [f64; 2]) -> bool { + if !pos.iter().all(|v| v.is_finite()) || !doc.iter().all(|v| v.is_finite()) { + return false; + } + let hit = if tool == Tool::Move { crate::rulers::guide_at(app, doc[0], doc[1]) } else { crate::canvas::command_guide_at(app, tool, doc, mods) }; + let Some((vertical, index)) = hit else { return false }; + crate::guide_select::select(app, vertical, index); + app.ui.brush_picker = None; + app.ui.layer_menu = None; + app.ui.canvas_tool_menu = Some(CanvasToolMenu { + pos, + tool, + has_selection: false, + has_path: false, + path_name: None, + transform: false, + pasteboard: false, + anchor: None, + text: false, + type_layer: false, + guide: true, + spelling: None, + crop: None, + }); + crate::canvas_popup::mark_open(ctx, menu_id()); + true +} + +/// A guide row: the two Selected Guides rows act on the selected guide; the rest are the View +/// menu's commands. +fn choose_guide(app: &mut PhotocraftApp, ctx: &Context, command: &str) -> Result<(), String> { + match command { + GUIDE_EDIT => crate::new_guide_ui::open_edit(app).map(|_| ()), + GUIDE_CLEAR => crate::guide_select::delete_selected(app).map(|_| ()), + _ => crate::menus::invoke(app, ctx, command, json!({})).map(|_| ()), + } +} + +/// A pasteboard row: set the colour, or open the Color Picker on the custom one. +fn choose_pasteboard(app: &mut PhotocraftApp, menu: &CanvasToolMenu, command: &str) -> Result<(), String> { + if command == PASTEBOARD_PICK { + let rgb = prefs::parse_hex(&app.session.prefs().interface.canvas_custom_color).map_or([0.5; 3], |c| c.map(|v| f32::from(v) / 255.0)); + crate::color_picker_ui::open_for_target(app, "pasteboard", "Color Picker (Custom Canvas Color)", rgb); + return Ok(()); + } + let (command, params) = engine_call(app, menu, command); + app.run(&command, params).map(|_| ()) +} + +pub fn entry_enabled(app: &PhotocraftApp, menu: &CanvasToolMenu, command: &str) -> bool { + if menu.crop.is_some() { + return crop_enabled(app, menu, command); + } + if menu.guide { + return match command { + GUIDE_EDIT | GUIDE_CLEAR => crate::guide_select::selected(app).is_some(), + _ => GUIDE_MENU.iter().flatten().any(|(_, id)| *id == command) && crate::menus::is_enabled(app, command), + }; + } + if menu.pasteboard { + return PASTEBOARD_MENU.iter().flatten().any(|(_, id)| *id == command); + } + // Warp needs a layer, selection or path box: a lone mask or channel keeps the plain box. + if menu.transform && command == "edit.transform.warp" { + return app.ui.transform.as_ref().is_some_and(|t| t.warp.is_none() && t.target.is_none()); + } + if menu.anchor.is_some() && command == FILL_SCREEN { + return app.session.active().is_some(); + } + if menu.text { + return match command { + SPELLING_NONE => false, + c if is_spelling(menu, c) => app.ui.text_edit.is_some(), + FAUX_BOLD | FAUX_ITALIC => app.ui.text_edit.is_some(), + c => TYPE_EDIT_MENU.iter().flatten().any(|(_, id)| *id == c) && crate::menus::is_enabled(app, c), + }; + } + if menu.type_layer { + return TYPE_LAYER_MENU.iter().flatten().any(|(_, id)| *id == command) && crate::menus::is_enabled(app, command); + } + if menu.transform || !path_menu(menu.tool) { + return crate::menus::is_enabled(app, command); + } + let Some(st) = app.session.active() else { return false }; + let layer = st.active_layer.and_then(|id| st.doc.layer(id)); + let locked = layer.is_some_and(|l| st.doc.effective_locks(l.id).all); + let can_paint = layer.is_some_and(|l| matches!(l.content, LayerContent::Raster(_))) && !locked; + let shape_layer = layer.and_then(|l| match &l.content { + LayerContent::Shape(sh) => Some(sh), + _ => None, + }); + let shape = shape_layer.is_some(); + let can_mask = layer.is_some_and(|l| !matches!(l.content, LayerContent::Shape(_))) && !locked; + let saved = menu.path_name.as_deref().is_some_and(|n| n != "work" && n != "layer"); + let has_path = menu.has_path; + let pending = app.ui.pen.as_ref().is_some_and(|p| p.knots.len() >= 2); + let pending_layer = pending && (app.ui.tool_options.vector_mode == "shape" || app.ui.vector_mask_target); + match command { + "layer.vectorMask.fromPath" => has_path && can_mask && !pending_layer, + "path.delete" => has_path && !pending_layer && (pending || menu.path_name.as_deref() != Some("layer")), + "edit.defineCustomShape" | "path.toSelection" | "path.transform" | "paint.symmetryFromPath" => has_path, + "view.newGuidesFromShape" => shape && !pending, + "path.fill" | "path.stroke" => has_path && can_paint && !pending_layer, + "path.clippingPath.set" => saved && !pending, + "layer.combineShapes.unite" + | "layer.combineShapes.subtractFrontShape" + | "layer.combineShapes.intersectShapeAreas" + | "layer.combineShapes.excludeOverlappingShapes" => !pending && shape_layer.is_some_and(|sh| sh.path.subpaths.len() > 1), + "path.style.copyFill" => !pending && shape_layer.is_some_and(|sh| sh.fill.is_some()), + "path.style.copyStroke" => !pending && shape_layer.is_some_and(|sh| sh.stroke.is_some()), + "path.style.pasteFill" => !pending && shape && app.session.path_fill_clipboard.is_some(), + "path.style.pasteStroke" => !pending && shape && app.session.path_stroke_clipboard.is_some(), + "select.isolateLayers" => layer.is_some(), + "paint.symmetryDisable" => st.symmetry.is_some(), + _ => false, + } +} + +pub fn open(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, pos: [f32; 2]) -> bool { + open_at(app, ctx, tool, pos, None) +} + +/// [`open`] for a right-click at document point `doc`: over a misspelled word of the text being +/// edited, the menu starts with its spelling suggestions; over committed type with a Type tool, the +/// type layer menu. +pub fn open_at(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, pos: [f32; 2], doc: Option<[f64; 2]>) -> bool { + let text = editing_text(app, tool); + if !pos.iter().all(|v| v.is_finite()) { + return false; + } + let type_layer = !text && doc.and_then(|d| type_layer_at(app, tool, d)).is_some_and(|id| target_type_layer(app, id)); + if !(applies(tool) || text || type_layer) { + return false; + } + app.ui.brush_picker = None; + app.ui.layer_menu = None; + let has_selection = app.session.active().is_some_and(|s| s.doc.selection.is_some()); + let has_path = crate::vector_ui::active_path_name(app).is_some() || app.ui.pen.as_ref().is_some_and(|p| p.knots.len() >= 2); + let path_name = crate::vector_ui::active_path_name(app); + let spelling = if text { doc.and_then(|d| spelling_at(app, d)) } else { None }; + app.ui.canvas_tool_menu = Some(CanvasToolMenu { + pos, + tool, + has_selection, + has_path, + path_name, + transform: false, + pasteboard: false, + anchor: None, + text, + type_layer, + guide: false, + spelling, + crop: None, + }); + crate::canvas_popup::mark_open(ctx, menu_id()); + true +} + +/// Right-click with the Zoom or Hand tool at screen point `pos`, over document point `doc`: the +/// view menu. +pub fn open_view(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, pos: [f32; 2], doc: [f64; 2]) -> bool { + if !is_view_tool(tool) || !pos.iter().all(|v| v.is_finite()) || !doc.iter().all(|v| v.is_finite()) { + return false; + } + app.ui.brush_picker = None; + app.ui.layer_menu = None; + app.ui.canvas_tool_menu = Some(CanvasToolMenu { + pos, + tool, + has_selection: false, + has_path: false, + path_name: None, + transform: false, + pasteboard: false, + anchor: Some(doc), + text: false, + type_layer: false, + guide: false, + spelling: None, + crop: None, + }); + crate::canvas_popup::mark_open(ctx, menu_id()); + true +} + +/// A view menu row. Zoom In and Zoom Out step about the right-clicked point, as a Zoom tool click +/// does; the other rows run their View menu command. +fn choose_view(app: &mut PhotocraftApp, ctx: &Context, menu: &CanvasToolMenu, command: &str) -> Result<(), String> { + let i = app.session.active_index().ok_or("no document")?; + if command == FILL_SCREEN { + let v = app.ui.views.get_mut(i).ok_or("no document view")?; + v.fit_pending = false; + v.fill_pending = true; + v.request_zoom_animation(app.session.prefs().general.animated_zoom); + v.zoom_anchor = None; + return Ok(()); + } + let before = app.ui.views.get(i).map(|v| (v.zoom, v.center)); + crate::menus::invoke(app, ctx, command, json!({}))?; + if !matches!(command, "view.zoomIn" | "view.zoomOut") { + return Ok(()); + } + let (Some((zoom0, c)), Some(d)) = (before, menu.anchor) else { return Ok(()) }; + let center_on_point = app.session.prefs().tools.zoom_clicked_point_to_center; + let Some(v) = app.ui.views.get_mut(i) else { return Ok(()) }; + let d = [d[0] as f32, d[1] as f32]; + // The view scales about the centre, so the point keeps its screen position when its offset + // from the centre shrinks (or grows) by the zoom ratio, whatever the rotation or flip. + let ratio = zoom0 / v.zoom; + v.center = if center_on_point || !ratio.is_finite() { d } else { [d[0] - (d[0] - c[0]) * ratio, d[1] - (d[1] - c[1]) * ratio] }; + v.zoom_anchor = (v.zoom_animating && !center_on_point).then_some(([d[0] as f64, d[1] as f64], menu.pos)); + Ok(()) +} + +pub fn choose(app: &mut PhotocraftApp, ctx: &Context, command: &str) { + let Some(menu) = app.ui.canvas_tool_menu.take() else { return }; + if !available(app, &menu, command) { + return; + } + let result = if menu.crop.is_some() { + choose_crop(app, &menu, command) + } else if menu.guide { + choose_guide(app, ctx, command) + } else if menu.pasteboard { + choose_pasteboard(app, &menu, command) + } else if menu.anchor.is_some() { + choose_view(app, ctx, &menu, command) + } else if menu.text && is_spelling(&menu, command) { + choose_spelling(app, &menu, command) + } else if menu.text || menu.type_layer { + choose_type(app, ctx, command) + } else if path_menu(menu.tool) && !menu.transform { + choose_pen(app, ctx, &menu, command) + } else if command == "select.toWorkPath" { + // Photoshop's Make Work Path… asks for the tolerance first. + spec_dialog(app, command, "Make Work Path", r##"{"tolerance":0.5..10=2}"##, serde_json::Map::new()); + Ok(()) + } else { + crate::menus::invoke(app, ctx, command, json!({})).map(|_| ()) + }; + if let Err(e) = result { + app.ui.status = e; + app.ui.status_error = true; + } +} + +/// A spelling row: replace the word under the pointer (the caret lands after the replacement), or +/// add it to the user dictionary. +fn choose_spelling(app: &mut PhotocraftApp, menu: &CanvasToolMenu, command: &str) -> Result<(), String> { + let (id, params) = engine_call(app, menu, command); + let result = app.run(&id, params)?; + if let Some(end) = result["end"].as_u64().map(|e| e as usize) + && let Some(e) = app.ui.text_edit.as_mut() + { + (e.caret, e.anchor) = (end, end); + } + Ok(()) +} + +/// A type edit row. Undo, Cut, Copy, Paste and Select All run as their Edit and Select menu items, +/// which act on the text while it is being edited (Paste asks the window for the clipboard text). +fn choose_type(app: &mut PhotocraftApp, ctx: &Context, command: &str) -> Result<(), String> { + match command { + FAUX_BOLD | FAUX_ITALIC => { + let bold = command == FAUX_BOLD; + let on = !type_checked(app, command); + let mut p = crate::type_tool::formatting_params(app).ok_or("No type is being edited")?; + p[if bold { "fauxBold" } else { "fauxItalic" }] = json!(on); + app.run("type.setStyle", p)?; + } + _ => { + if ENDS_TYPE_EDIT.contains(&command) { + crate::type_tool::commit(app); + } + crate::menus::invoke(app, ctx, command, json!({}))?; + } + } + Ok(()) +} + +/// A parameter dialog for `command` following `spec` (registry notation), prefilled with `fields`. +fn spec_dialog(app: &mut PhotocraftApp, command: &str, label: &str, spec: &str, mut fields: serde_json::Map) { + fields.insert("__command".into(), json!(command)); + fields.insert("__label".into(), json!(label)); + fields.insert("__filter".into(), json!(true)); + fields.insert("__spec".into(), json!(spec)); + app.ui.open_dialog(crate::state::DialogKind::Command, fields); +} + +/// Photoshop's Stroke Path dialog: the brush-based tool to stroke with (painting with that tool's +/// current options) and Simulate Pressure (#2978). +const STROKE_PATH_SPEC: &str = r##"{"tool":"brush|pencil|eraser|backgroundEraser|cloneStamp|patternStamp|healingBrush|spotHealingBrush|historyBrush|blur|sharpen|smudge|dodge|burn|sponge|colorReplacement|mixerBrush"="brush","simulatePressure":bool=false}"##; + +/// The Stroke Path dialog for the path `name` (Paths panel menu, Alt-click on its Stroke button). +pub(crate) fn stroke_path_dialog(app: &mut PhotocraftApp, name: &str) { + pen_dialog(app, "path.stroke", "Stroke Path…", name); +} + +fn pen_dialog(app: &mut PhotocraftApp, command: &str, label: &str, name: &str) { + let spec = match command { + "edit.defineCustomShape" => r##"{"name":text}"##, + "path.toSelection" => r##"{"feather":0..250=0,"antiAlias":bool=true,"mode":"replace|add|subtract|intersect"="replace"}"##, + "path.fill" => r##"{"color":text,"opacity":0..100=100,"feather":0..250=0,"antiAlias":bool=true}"##, + "path.stroke" => STROKE_PATH_SPEC, + "path.clippingPath.set" => r##"{"flatness":0..100=0}"##, + "path.transform" => r##"{"translateX":-30000..30000=0,"translateY":-30000..30000=0,"scaleX":0.01..100=1,"scaleY":0.01..100=1,"angle":-360..360=0}"##, + _ => "{}", + }; + let mut fields = serde_json::Map::new(); + if command == "edit.defineCustomShape" { + fields.insert("path".into(), json!(name)); + fields.insert("name".into(), json!("")); + } else { + fields.insert("name".into(), json!(name)); + } + if command == "path.fill" { + let fg = app.session.tools.foreground; + let byte = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; + fields.insert("color".into(), json!(format!("#{:02x}{:02x}{:02x}", byte(fg[0]), byte(fg[1]), byte(fg[2])))); + } + if command == "path.transform" { + for (key, value) in [("translateX", 0.0), ("translateY", 0.0), ("scaleX", 1.0), ("scaleY", 1.0), ("angle", 0.0)] { + fields.insert(key.into(), json!(value)); + } + } + spec_dialog(app, command, label, spec, fields); +} + +/// The Pen options bar's Make Selection (Path mode, #5703): the canvas menu's Make Selection… +/// dialog for the path being drawn (committed first, as the menu does) or the active path. +pub(crate) fn make_selection(app: &mut PhotocraftApp) -> Result<(), String> { + let pending = app.ui.pen.as_ref().is_some_and(|p| p.knots.len() >= 2); + // Where `pen_commit` puts the path being drawn: a shape layer or the targeted vector mask, + // else the Paths panel path it adds to (a selected saved path, or the Work Path), which it + // selects so it is the active path. + let pending_layer = pending && (app.ui.tool_options.vector_mode == "shape" || crate::vector_ui::targeted_vector_mask(app).is_some()); + if pending { + crate::vector_ui::pen_commit(app, false); + } + let name = if pending_layer { Some("layer".to_string()) } else { crate::vector_ui::active_path_name(app) } + .ok_or_else(|| "No path is available for this action".to_string())?; + pen_dialog(app, "path.toSelection", "Make Selection…", &name); + Ok(()) +} + +fn choose_pen(app: &mut PhotocraftApp, ctx: &Context, menu: &CanvasToolMenu, command: &str) -> Result<(), String> { + if command == "select.isolateLayers" { + crate::menus::invoke(app, ctx, command, json!({}))?; + return Ok(()); + } + if command == "paint.symmetryDisable" { + app.run(command, json!({}))?; + return Ok(()); + } + let pending = app.ui.pen.as_ref().is_some_and(|p| p.knots.len() >= 2); + let pending_layer = pending && (app.ui.tool_options.vector_mode == "shape" || app.ui.vector_mask_target); + if pending { + crate::vector_ui::pen_commit(app, false); + } + let name = if pending { Some(if pending_layer { "layer" } else { "work" }.to_string()) } else { menu.path_name.clone() } + .ok_or_else(|| "No path is available for this action".to_string())?; + match command { + "edit.defineCustomShape" | "path.toSelection" | "path.fill" | "path.stroke" | "path.clippingPath.set" | "path.transform" => { + let label = PEN_MENU.iter().flatten().find(|(_, id)| *id == command).map_or(command, |(label, _)| *label); + pen_dialog(app, command, label, &name); + } + _ => { + app.run(command, json!({"name": name}))?; + } + } + Ok(()) +} + +fn menu_id() -> egui::Id { + egui::Id::unique("canvas-selection-menu") +} + +pub fn show(app: &mut PhotocraftApp, ctx: &Context) { + let Some(menu) = app.ui.canvas_tool_menu.clone() else { return }; + if ctx.input(|i| i.key_pressed(egui::Key::Escape)) + || app.ui.tool != menu.tool + || (menu.transform && app.ui.transform.is_none()) + || (menu.text && app.ui.text_edit.is_none()) + || (menu.type_layer && app.ui.text_edit.is_some()) + || (menu.crop.is_some() && !crate::crop_ui::pending(app)) + { + app.ui.canvas_tool_menu = None; + return; + } + let id = menu_id(); + let screen = ctx.content_rect(); + let size = ctx.memory(|m| m.area_rect(id)).map_or(egui::vec2(210.0, 140.0), |r| r.size()); + let pos = egui::pos2(menu.pos[0].min(screen.right() - size.x).max(screen.left()), menu.pos[1].min(screen.bottom() - size.y).max(screen.top())); + let mut selected = None; + let area = egui::Area::new(id).order(egui::Order::Foreground).fixed_pos(pos).show(ctx, |ui| { + egui::Frame::menu(ui.style()).show(ui, |ui| { + let t = crate::theme::Tokens::get(ui.ctx()); + let v = &mut ui.style_mut().visuals; + v.widgets.inactive.weak_bg_fill = egui::Color32::TRANSPARENT; + v.widgets.inactive.bg_stroke = egui::Stroke::NONE; + v.widgets.hovered.weak_bg_fill = t.accent; + v.widgets.hovered.bg_fill = t.accent; + v.widgets.hovered.bg_stroke = egui::Stroke::NONE; + v.widgets.hovered.fg_stroke = egui::Stroke::new(1.0, egui::Color32::WHITE); + v.widgets.hovered.corner_radius = egui::CornerRadius::same(3); + ui.spacing_mut().item_spacing.y = 0.0; + ui.set_width(200.0); + crate::widgets::menu_scroll(ui, |ui| { + let spelling = spelling_rows(&menu); + for (label, command) in &spelling { + let text = if spelling_label_is_ui(command) { tl!(label).to_string() } else { label.clone() }; + let item = egui::Button::new(text).min_size(egui::vec2(200.0, 20.0)); + if ui.add_enabled(entry_enabled(app, &menu, command), item).clicked() { + selected = Some(command.clone()); + } + } + if !spelling.is_empty() { + ui.separator(); + } + for row in crop_rows(&menu) { + let Some((label, command)) = row else { + ui.separator(); + continue; + }; + let text = if crop_label_is_ui(&command) { tl!(&label).to_string() } else { label }; + let item = egui::Button::selectable(mode_checked(app, &menu, &command), text).min_size(egui::vec2(200.0, 20.0)); + if ui.add_enabled(entry_enabled(app, &menu, &command), item).clicked() { + selected = Some(command); + } + } + for row in rows(&menu) { + let Some((label, command)) = *row else { + ui.separator(); + continue; + }; + let item = egui::Button::selectable(mode_checked(app, &menu, command), tl!(label)).min_size(egui::vec2(200.0, 20.0)); + if ui.add_enabled(entry_enabled(app, &menu, command), item).clicked() { + selected = Some((*command).to_string()); + } + } + }); + }); + }); + if let Some(command) = selected { + choose(app, ctx, &command); + } else if crate::canvas_popup::outside_pressed(ctx, id, area.response.rect) { + app.ui.canvas_tool_menu = None; + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/canvas/canvas_tool_menu/tests.rs b/crates/ui-egui/src/canvas/canvas_tool_menu/tests.rs new file mode 100644 index 0000000000..eb9147a7a5 --- /dev/null +++ b/crates/ui-egui/src/canvas/canvas_tool_menu/tests.rs @@ -0,0 +1,1206 @@ +use super::*; +use egui::{Modifiers, PointerButton, Pos2, vec2}; +use egui_kittest::{Harness, kittest::Queryable}; + +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); + app +} + +fn work_path(app: &mut PhotocraftApp) { + app.run( + "path.set", + json!({"name": "work", "path": {"subpaths": [{"closed": true, "knots": [ + {"anchor": [2, 2], "in": [2, 2], "out": [2, 2]}, + {"anchor": [20, 2], "in": [20, 2], "out": [20, 2]}, + {"anchor": [20, 20], "in": [20, 20], "out": [20, 20]} + ]}]}}), + ) + .unwrap(); +} + +fn choose_open(app: &mut PhotocraftApp, command: &str) { + assert!(open(app, &Context::default(), Tool::Pen, [10.0, 10.0])); + choose(app, &Context::default(), command); +} + +fn harness(mut app: PhotocraftApp) -> Harness<'static, PhotocraftApp> { + app.sync_views(); + let mut h = Harness::builder().with_size(vec2(1000.0, 700.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let ctx = ui.ctx().clone(); + if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::default()); + h.run_steps(4); + h +} + +fn right_click(h: &mut Harness<'static, PhotocraftApp>, p: Pos2, modifiers: Modifiers) { + h.event(egui::Event::ModifiersChanged(modifiers)); + h.event(egui::Event::PointerMoved(p)); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Secondary, pressed: true, modifiers }); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Secondary, pressed: false, modifiers }); + h.event(egui::Event::ModifiersChanged(Modifiers::NONE)); + h.run_steps(2); +} + +#[test] +fn canvas_gesture_preserves_selection_and_command_override() { + let mut app = app(); + app.ui.tool = Tool::Lasso; + app.run("select.rect", json!({"x": 1, "y": 1, "width": 8, "height": 8})).unwrap(); + let mut h = harness(app); + let center = h.state().last_canvas_rect.center(); + let revision = h.state().session.active().unwrap().revision; + right_click(&mut h, center, Modifiers::NONE); + assert!(h.state().ui.canvas_tool_menu.is_some()); + assert_eq!(h.state().session.active().unwrap().revision, revision, "right-click cannot alter selection"); + h.key_press(egui::Key::Escape); + h.run_steps(2); + assert!(h.state().ui.canvas_tool_menu.is_none()); + right_click(&mut h, center, Modifiers::COMMAND); + assert!(h.state().ui.canvas_tool_menu.is_none(), "command right-click belongs to layer picker"); +} + +/// A type layer reading "Hello", being edited with every character selected. +fn editing_type(app: &mut PhotocraftApp) -> u64 { + app.ui.tool = Tool::Type; + let id = app.run("type.create", json!({"text": "Hello", "size": 12, "x": 4, "y": 20})).unwrap()["layer"].as_u64().unwrap(); + crate::menus::invoke(app, &Context::default(), "type.editText", json!({})).unwrap(); + id +} + +fn text_of(app: &PhotocraftApp, id: u64) -> Option { + match &app.session.active().unwrap().doc.layer(photocraft_doc::LayerId(id)).unwrap().content { + LayerContent::Text(t) => Some(t.clone()), + _ => None, + } +} + +#[test] +fn right_click_while_typing_opens_the_type_edit_menu_and_esc_keeps_the_edit() { + let mut app = app(); + editing_type(&mut app); + app.sync_views(); + let mut h = Harness::builder().with_size(vec2(1000.0, 700.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let ctx = ui.ctx().clone(); + if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + // The app's order: shortcuts (inline type's keys among them), then the canvas. + crate::shortcuts::handle(app, &ctx); + egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::default()); + h.run_steps(4); + let center = h.state().last_canvas_rect.center(); + right_click(&mut h, center, Modifiers::NONE); + let menu = h.state().ui.canvas_tool_menu.clone().expect("right-click in a type edit opens a menu"); + assert!(menu.text && !menu.pasteboard && !menu.transform); + assert_eq!(rows(&menu), TYPE_EDIT_MENU); + let edit = h.state().ui.text_edit.clone().expect("the edit goes on under the menu"); + assert_eq!((edit.anchor, edit.caret), (0, 5), "the right-click keeps the selection for Cut and Copy"); + h.key_press(egui::Key::Escape); + h.run_steps(2); + assert!(h.state().ui.canvas_tool_menu.is_none(), "Esc closes the menu"); + assert!(h.state().ui.text_edit.is_some(), "and only the menu: the edit isn't committed"); +} + +#[test] +fn type_edit_menu_rows_act_on_the_text_and_the_layer() { + let mut app = app(); + let id = editing_type(&mut app); + let ctx = Context::default(); + let reopen = |app: &mut PhotocraftApp| assert!(open(app, &Context::default(), Tool::Type, [10.0, 10.0])); + // Faux Bold toggles the style of the selected characters, and shows checked. + reopen(&mut app); + let menu = app.ui.canvas_tool_menu.clone().unwrap(); + assert!(!mode_checked(&app, &menu, FAUX_BOLD) && mode_checked(&app, &menu, "type.antiAlias.smooth")); + choose(&mut app, &ctx, FAUX_BOLD); + assert!(text_of(&app, id).unwrap().char_runs().iter().all(|r| r.style.faux_bold)); + assert!(mode_checked(&app, &menu, FAUX_BOLD)); + // Cut takes the selection out of the text; with nothing selected Copy and Cut grey out. + reopen(&mut app); + choose(&mut app, &ctx, "edit.cut"); + assert_eq!(text_of(&app, id).unwrap().text, ""); + reopen(&mut app); + let menu = app.ui.canvas_tool_menu.clone().unwrap(); + assert!(!entry_enabled(&app, &menu, "edit.copy") && !entry_enabled(&app, &menu, "edit.cut")); + app.ui.canvas_tool_menu = None; + crate::menus::invoke(&mut app, &ctx, "edit.undo", json!({})).unwrap(); + assert_eq!(text_of(&app, id).unwrap().text, "Hello"); + // Select All selects every character, not the canvas. + reopen(&mut app); + choose(&mut app, &ctx, "select.all"); + let edit = app.ui.text_edit.clone().unwrap(); + assert_eq!((edit.anchor, edit.caret), (0, 5)); + assert!(app.session.active().unwrap().doc.selection.is_none()); + // Warp Text… opens its dialog; Rasterize Type ends the edit and rasterizes the layer. + reopen(&mut app); + choose(&mut app, &ctx, "type.warpText"); + assert!(!app.ui.dialogs.is_empty(), "Warp Text… asks for its settings"); + app.ui.dialogs.clear(); + reopen(&mut app); + choose(&mut app, &ctx, "type.rasterizeTypeLayer"); + assert!(app.ui.text_edit.is_none() && text_of(&app, id).is_none(), "the type layer is pixels now"); +} + +/// A committed type layer reading "Hello" over the middle of the canvas, no edit running. +fn committed_type(app: &mut PhotocraftApp) -> u64 { + app.ui.tool = Tool::Type; + let id = app.run("type.create", json!({"text": "Hello", "size": 14, "x": 1, "y": 22})).unwrap()["layer"].as_u64().unwrap(); + assert!(app.ui.text_edit.is_none()); + id +} + +#[test] +fn right_click_on_committed_type_opens_the_type_layer_menu() { + use photocraft_doc::text::Orientation; + let mut app = app(); + let id = committed_type(&mut app); + assert_eq!(crate::type_tool::hit_layer(&mut app, 16.0, 16.0).map(|l| l.0), Some(id), "the canvas centre is on the type"); + let mut h = harness(app); + let center = h.state().last_canvas_rect.center(); + right_click(&mut h, center, Modifiers::NONE); + let menu = h.state().ui.canvas_tool_menu.clone().expect("right-click on committed type opens a menu (#7324)"); + assert!(menu.type_layer && !menu.text && !menu.pasteboard); + assert_eq!(rows(&menu), TYPE_LAYER_MENU); + assert!(h.state().ui.text_edit.is_none(), "the right-click doesn't start an edit"); + h.run_steps(2); + assert!(h.state().ui.canvas_tool_menu.is_some(), "the menu stays open without an edit"); + // An edit started some other way (here, as an agent's Type › Edit Text would) closes the + // menu, which has no text edit rows. + crate::menus::invoke(h.state_mut(), &Context::default(), "type.editText", json!({})).unwrap(); + h.run_steps(2); + assert!(h.state().ui.canvas_tool_menu.is_none(), "an edit closes the type layer menu"); + crate::type_tool::commit(h.state_mut()); + right_click(&mut h, center, Modifiers::NONE); + let menu = h.state().ui.canvas_tool_menu.clone().expect("committed again, the menu opens again"); + assert!(menu.type_layer && mode_checked(h.state(), &menu, "type.orientation.horizontal")); + choose(h.state_mut(), &Context::default(), "type.orientation.vertical"); + assert_eq!(text_of(h.state(), id).unwrap().orientation, Orientation::Vertical); +} + +#[test] +fn type_layer_menu_targets_the_type_under_the_pointer() { + let mut app = app(); + let id = committed_type(&mut app); + app.run("layer.new.layer", json!({})).unwrap(); + let ctx = Context::default(); + let active = |app: &PhotocraftApp| app.session.active().unwrap().active_layer.map(|l| l.0); + assert_ne!(active(&app), Some(id)); + // Away from the type, or with a Type Mask tool, nothing opens and nothing is selected. + assert!(!open_at(&mut app, &ctx, Tool::Type, [10.0, 10.0], Some([30.0, 2.0]))); + assert!(!open_at(&mut app, &ctx, Tool::HorizontalTypeMask, [10.0, 10.0], Some([16.0, 16.0]))); + assert!(!open_at(&mut app, &ctx, Tool::Type, [10.0, 10.0], Some([f64::NAN, 16.0]))); + assert_ne!(active(&app), Some(id)); + // Over the type: its layer becomes the target, and the menu has no text edit rows. + assert!(open_at(&mut app, &ctx, Tool::Type, [10.0, 10.0], Some([16.0, 16.0]))); + assert_eq!(active(&app), Some(id)); + let menu = app.ui.canvas_tool_menu.clone().unwrap(); + for edit_row in ["edit.undo", "edit.cut", "edit.copy", "edit.paste", "select.all", FAUX_BOLD, FAUX_ITALIC] { + assert!(!available(&app, &menu, edit_row), "{edit_row} belongs to the edit menu only"); + } + assert!(entry_enabled(&app, &menu, "type.convertToParagraphText") && !entry_enabled(&app, &menu, "type.convertToPointText")); + choose(&mut app, &ctx, "type.rasterizeTypeLayer"); + assert!(text_of(&app, id).is_none(), "the type layer is pixels now"); + assert!(app.ui.text_edit.is_none()); +} + +/// Two selected type layers: the one right-clicked becomes active, and the selection stays. +#[test] +fn type_layer_menu_in_a_multiselection_acts_on_the_clicked_type() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.ui.tool = Tool::Type; + let top = app.run("type.create", json!({"text": "Top", "size": 30, "x": 10, "y": 40})).unwrap()["layer"].as_u64().unwrap(); + let bottom = app.run("type.create", json!({"text": "Low", "size": 30, "x": 10, "y": 90})).unwrap()["layer"].as_u64().unwrap(); + app.run("layer.select", json!({"layer": bottom})).unwrap(); + app.run("layer.select", json!({"layer": top, "mode": "add"})).unwrap(); + let at = [25.0, 80.0]; + assert_eq!(crate::type_tool::hit_layer(&mut app, at[0], at[1]).map(|l| l.0), Some(bottom)); + assert_eq!(app.session.active().unwrap().active_layer.map(|l| l.0), Some(top)); + let ctx = Context::default(); + assert!(open_at(&mut app, &ctx, Tool::Type, [10.0, 10.0], Some(at))); + let st = app.session.active().unwrap(); + assert_eq!(st.active_layer.map(|l| l.0), Some(bottom), "the clicked type is the target"); + assert_eq!(st.selected_layers().len(), 2, "the multiselection stays"); + choose(&mut app, &ctx, "type.rasterizeTypeLayer"); + assert!(text_of(&app, bottom).is_none(), "the clicked type is rasterized"); + assert!(text_of(&app, top).is_some(), "not the other selected type"); +} + +#[test] +fn type_edit_menu_lists_spelling_suggestions_for_the_word_under_the_pointer() { + let mut app = app(); + app.ui.tool = Tool::Type; + let id = app.run("type.create", json!({"text": "Teh cat", "size": 12, "x": 4, "y": 20})).unwrap()["layer"].as_u64().unwrap(); + let ctx = Context::default(); + crate::menus::invoke(&mut app, &ctx, "type.editText", json!({})).unwrap(); + // Away from the misspelling (past the end of the line): no spelling rows. + assert!(open_at(&mut app, &ctx, Tool::Type, [10.0, 10.0], Some([600.0, 15.0]))); + assert!(spelling_rows(app.ui.canvas_tool_menu.as_ref().unwrap()).is_empty()); + // Over "Teh": its suggestions head the menu, then Add to Dictionary. + assert!(open_at(&mut app, &ctx, Tool::Type, [10.0, 10.0], Some([5.0, 15.0]))); + let menu = app.ui.canvas_tool_menu.clone().unwrap(); + let rows = spelling_rows(&menu); + assert!(rows.iter().any(|(l, _)| l == "The"), "{rows:?}"); + assert_eq!(rows.last().map(|(_, id)| id.as_str()), Some(SPELLING_ADD)); + assert!(rows.len() <= MAX_SUGGESTIONS + 1, "at most {MAX_SUGGESTIONS} suggestions and Add to Dictionary: {rows:?}"); + assert!(available(&app, &menu, &rows[0].1)); + let pick = rows.iter().find(|(l, _)| l == "The").unwrap().1.clone(); + choose(&mut app, &ctx, &pick); + assert_eq!(text_of(&app, id).unwrap().text, "The cat"); + assert_eq!(app.ui.text_edit.as_ref().map(|e| (e.caret, e.anchor)), Some((3, 3)), "the caret lands after the replacement"); + // Add to Dictionary stops flagging a word. + app.run("type.insertText", json!({"layer": id, "text": " Zqx"})).unwrap(); + assert!(open_at(&mut app, &ctx, Tool::Type, [10.0, 10.0], Some([600.0, 15.0]))); + let menu = app.ui.canvas_tool_menu.clone().unwrap(); + assert!(menu.spelling.as_ref().is_some_and(|s| s.word == "Zqx")); + choose(&mut app, &ctx, SPELLING_ADD); + assert!(app.session.prefs().user_dictionary.iter().any(|w| w == "Zqx")); +} + +#[test] +fn right_click_outside_the_image_picks_the_pasteboard_color() { + let mut app = app(); + app.ui.tool = Tool::RectMarquee; + let mut h = harness(app); + let rect = h.state().last_canvas_rect; + let outside = rect.min + vec2(5.0, 5.0); + right_click(&mut h, rect.center(), Modifiers::NONE); + assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| !m.pasteboard), "inside: the tool's own menu"); + h.state_mut().ui.canvas_tool_menu = None; + right_click(&mut h, outside, Modifiers::NONE); + let menu = h.state().ui.canvas_tool_menu.clone().unwrap(); + assert!(menu.pasteboard && rows(&menu) == PASTEBOARD_MENU, "outside: the pasteboard menu"); + let ctx = h.ctx.clone(); + choose(h.state_mut(), &ctx, "pasteboard.black"); + assert_eq!(crate::prefs_ui::pasteboard_color(h.state()), Some(egui::Color32::BLACK)); + // Select Custom Color… opens the Color Picker; OK makes its colour the custom pasteboard. + right_click(&mut h, outside, Modifiers::NONE); + choose(h.state_mut(), &ctx, PASTEBOARD_PICK); + let mut f = h.state().ui.dialogs.last().unwrap().fields.clone(); + f.insert("color".into(), json!("#123456")); + crate::color_picker_ui::confirm(h.state_mut(), &f).unwrap(); + assert_eq!(crate::prefs_ui::pasteboard_color(h.state()), Some(egui::Color32::from_rgb(0x12, 0x34, 0x56))); + // A painting tool keeps its Brush Preset picker there. + h.state_mut().ui.tool = Tool::Brush; + h.run_steps(2); + right_click(&mut h, outside, Modifiers::NONE); + assert!(h.state().ui.canvas_tool_menu.is_none() && h.state().ui.brush_picker.is_some()); +} + +/// #2832: right-click over an open Free Transform box: Photoshop's transform menu. Skew +/// switches the box's mode; Rotate and Flip turn the box about its reference point without +/// committing it; Content-Aware Scale and Puppet Warp are greyed. +#[test] +fn right_click_during_free_transform_switches_modes_rotates_and_flips_the_box() { + let mut app = app(); + app.ui.tool = Tool::RectMarquee; + app.run("layer.new.layer", json!({})).unwrap(); + app.run("select.rect", json!({"x": 4, "y": 6, "width": 10, "height": 8})).unwrap(); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + let mut h = harness(app); + let ctx = h.ctx.clone(); + crate::menus::invoke(h.state_mut(), &ctx, "edit.freeTransform", json!({})).unwrap(); + h.run_steps(2); + let center = h.state().last_canvas_rect.center(); + let (revision, journal) = (h.state().session.active().unwrap().revision, h.state().session.journal.len()); + right_click(&mut h, center, Modifiers::NONE); + let menu = h.state().ui.canvas_tool_menu.clone().expect("the transform menu"); + assert!(menu.transform && rows(&menu) == TRANSFORM_MENU); + for (id, on) in [("edit.contentAwareScale", false), ("edit.puppetWarp", false), ("edit.transform.rotate90Cw", true), ("edit.transform.flipVertical", true)] + { + assert_eq!(entry_enabled(h.state(), &menu, id), on, "{id}"); + } + choose(h.state_mut(), &ctx, "edit.transform.skew"); + assert_eq!(h.state().ui.transform.as_ref().unwrap().mode, crate::state::TransformMode::Skew); + let t = h.state().ui.transform.clone().unwrap(); + let (q0, c) = (t.quad, t.pivot); + right_click(&mut h, center, Modifiers::NONE); + choose(h.state_mut(), &ctx, "edit.transform.flipHorizontal"); + let q = h.state().ui.transform.as_ref().expect("the box stays open").quad; + for (a, b) in q.iter().zip(q0) { + assert!((a[0] - (2.0 * c[0] - b[0])).abs() < 1e-9 && (a[1] - b[1]).abs() < 1e-9, "mirrored about the reference point: {q0:?} -> {q:?}"); + } + right_click(&mut h, center, Modifiers::NONE); + choose(h.state_mut(), &ctx, "edit.transform.rotate180"); + let q = h.state().ui.transform.as_ref().unwrap().quad; + for (a, b) in q.iter().zip(q0) { + assert!((a[1] - (2.0 * c[1] - b[1])).abs() < 1e-9 && (a[0] - b[0]).abs() < 1e-9, "flipped then turned 180°: {q0:?} -> {q:?}"); + } + let st = h.state().session.active().unwrap(); + assert_eq!((st.revision, h.state().session.journal.len()), (revision, journal), "nothing is committed"); +} + +#[test] +fn transform_menu_follows_photoshop_order() { + assert_eq!( + labels(TRANSFORM_MENU), + vec![ + Some("Free Transform"), + Some("Scale"), + Some("Rotate"), + Some("Skew"), + Some("Distort"), + Some("Perspective"), + Some("Warp"), + None, + Some("Content-Aware Scale"), + Some("Puppet Warp"), + None, + Some("Rotate 180°"), + Some("Rotate 90° Clockwise"), + Some("Rotate 90° Counter Clockwise"), + None, + Some("Flip Horizontal"), + Some("Flip Vertical"), + ] + ); + // Over a box on editable type, Distort and Perspective are greyed (#2630). + let mut app = app(); + app.run("type.create", json!({"x": 2, "y": 20, "text": "Hi", "size": 16})).unwrap(); + crate::transform_tool::begin(&mut app, &Context::default()).unwrap(); + assert!(open_transform(&mut app, &Context::default(), [10.0, 10.0])); + let menu = app.ui.canvas_tool_menu.clone().unwrap(); + for (id, on) in [("edit.transform.skew", true), ("edit.transform.distort", false), ("edit.transform.perspective", false)] { + assert_eq!(entry_enabled(&app, &menu, id), on, "{id}"); + } +} + +fn labels(rows: &[Row]) -> Vec> { + rows.iter().map(|row| row.map(|(label, _)| label)).collect() +} + +#[test] +fn selection_menus_follow_photoshop_order() { + assert_eq!( + labels(SELECTION_MENU), + vec![ + Some("Deselect"), + Some("Select Inverse"), + Some("Feather…"), + Some("Select and Mask…"), + None, + Some("Save Selection…"), + Some("Make Work Path…"), + None, + Some("Layer via Copy"), + Some("Layer via Cut"), + Some("New Layer…"), + None, + Some("Free Transform"), + Some("Transform Selection"), + Some("Distort"), + Some("Perspective"), + None, + Some("Delete and Fill Selection"), + Some("Fill…"), + Some("Stroke…"), + Some("Content-Aware Fill…"), + None, + Some("Last Filter"), + None, + Some("Fade…"), + ] + ); + assert_eq!(labels(NO_SELECTION_MENU), vec![Some("Select All"), Some("Reselect"), Some("Color Range…"), None, Some("Load Selection…")]); + // Every row runs a real command: one the menu bar has, or an engine command. + let app = app(); + let items = crate::menus::menu_items(&app); + for (label, id) in [SELECTION_MENU, NO_SELECTION_MENU, PEN_MENU, TRANSFORM_MENU].into_iter().flatten().flatten() { + assert!(items.iter().any(|i| i.id == *id) || photocraft_engine::commands::find(id).is_some(), "{label}: unknown command {id}"); + } +} + +#[test] +fn selection_menu_routes_actions_through_commands() { + let mut app = app(); + app.ui.tool = Tool::RectMarquee; + app.run("select.rect", json!({"x": 1, "y": 1, "width": 8, "height": 8})).unwrap(); + assert!(open(&mut app, &Context::default(), Tool::RectMarquee, [10.0, 10.0])); + assert_eq!(rows(app.ui.canvas_tool_menu.as_ref().unwrap()), SELECTION_MENU); + let before = app.session.journal.len(); + choose(&mut app, &Context::default(), "select.inverse"); + assert!(app.ui.canvas_tool_menu.is_none()); + assert!(app.session.journal[before..].iter().any(|(id, _)| id == "select.inverse")); + let before = app.session.journal.len(); + assert!(open(&mut app, &Context::default(), Tool::RectMarquee, [10.0, 10.0])); + choose(&mut app, &Context::default(), "select.deselect"); + assert!(app.session.active().unwrap().doc.selection.is_none()); + assert!(app.session.journal[before..].iter().any(|(id, _)| id == "select.deselect")); + // Nothing selected: the menu that makes a selection. + assert!(open(&mut app, &Context::default(), Tool::RectMarquee, [10.0, 10.0])); + assert_eq!(rows(app.ui.canvas_tool_menu.as_ref().unwrap()), NO_SELECTION_MENU); + choose(&mut app, &Context::default(), "select.reselect"); + assert!(app.session.active().unwrap().doc.selection.is_some()); + assert!(app.session.journal.iter().any(|(id, _)| id == "select.reselect")); + app.run("select.deselect", json!({})).unwrap(); + assert!(open(&mut app, &Context::default(), Tool::Lasso, [10.0, 10.0])); + choose(&mut app, &Context::default(), "select.all"); + assert!(app.session.active().unwrap().doc.selection.is_some()); +} + +#[test] +fn selection_menu_layer_and_path_actions() { + let mut app = app(); + app.ui.tool = Tool::EllipseMarquee; + app.run("layer.new.layer", json!({})).unwrap(); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.run("select.rect", json!({"x": 4, "y": 4, "width": 10, "height": 10})).unwrap(); + let layers = app.session.active().unwrap().doc.layers.len(); + assert!(open(&mut app, &Context::default(), Tool::EllipseMarquee, [10.0, 10.0])); + choose(&mut app, &Context::default(), "layer.new.layerViaCopy"); + assert_eq!(app.session.active().unwrap().doc.layers.len(), layers + 1, "Layer via Copy adds a layer"); + assert_eq!(app.session.journal.last().map(|(id, _)| id.as_str()), Some("layer.new.layerViaCopy")); + // Make Work Path… asks for the tolerance, then traces the selection. + app.run("select.rect", json!({"x": 4, "y": 4, "width": 10, "height": 10})).unwrap(); + assert!(open(&mut app, &Context::default(), Tool::EllipseMarquee, [10.0, 10.0])); + choose(&mut app, &Context::default(), "select.toWorkPath"); + let dialog = app.ui.dialogs.last().map(|d| d.id).expect("tolerance dialog"); + assert!(app.session.active().unwrap().doc.work_path.is_none(), "nothing happens before OK"); + crate::dialogs::confirm(&mut app, dialog).unwrap(); + assert!(app.session.active().unwrap().doc.work_path.is_some()); + assert_eq!(app.session.journal.last().map(|(id, _)| id.as_str()), Some("select.toWorkPath")); +} + +#[test] +fn disabled_selection_rows_do_nothing() { + let mut app = app(); + app.ui.tool = Tool::MagicWand; + app.run("select.rect", json!({"x": 1, "y": 1, "width": 8, "height": 8})).unwrap(); + assert!(open(&mut app, &Context::default(), Tool::MagicWand, [10.0, 10.0])); + let menu = app.ui.canvas_tool_menu.clone().unwrap(); + // No filter has run and nothing can be faded yet. + for id in ["filter.lastFilter", "edit.fade"] { + assert!(!entry_enabled(&app, &menu, id), "{id} is greyed out"); + } + let before = app.session.journal.len(); + choose(&mut app, &Context::default(), "edit.fade"); + assert_eq!(app.session.journal.len(), before); + assert!(app.ui.dialogs.is_empty()); + // Rows of the other variant are not part of this menu. + assert!(open(&mut app, &Context::default(), Tool::MagicWand, [10.0, 10.0])); + choose(&mut app, &Context::default(), "select.all"); + assert_eq!(app.session.journal.len(), before); +} + +/// Photoshop's Zoom tool menu is Fit on Screen, 100%, 200%, Print Size, then Zoom In and Zoom +/// Out after a separator (#6005); Fill Screen (the Hand tool's) keeps its place by Fit on Screen. +#[test] +fn view_menu_follows_photoshop_order() { + assert_eq!( + labels(VIEW_MENU), + vec![Some("Fit on Screen"), Some("Fill Screen"), Some("100%"), Some("200%"), Some("Print Size"), None, Some("Zoom In"), Some("Zoom Out")] + ); + // Every row but Fill Screen (the Hand tool's options-bar button) is a View menu command. + let app = app(); + let items = crate::menus::menu_items(&app); + for (label, id) in VIEW_MENU.iter().flatten().filter(|(_, id)| *id != FILL_SCREEN) { + assert!(items.iter().any(|i| i.id == *id), "{label}: unknown command {id}"); + } +} + +fn zoom_app(w: u32, h: u32) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": w, "height": h})).unwrap(); + app +} + +fn screen_of(app: &PhotocraftApp, doc: [f32; 2]) -> Pos2 { + crate::canvas::ViewXform::active(app).unwrap().to_screen(doc[0], doc[1]) +} + +#[test] +fn zoom_and_hand_right_click_opens_the_view_menu() { + for tool in [Tool::Zoom, Tool::Hand] { + let mut app = zoom_app(400, 300); + app.ui.tool = tool; + let mut h = harness(app); + let zoom = h.state().ui.views[0].zoom; + let inside = screen_of(h.state(), [300.0, 100.0]); + right_click(&mut h, inside, Modifiers::NONE); + let menu = h.state().ui.canvas_tool_menu.clone().unwrap_or_else(|| panic!("{tool:?}: right-click opens no menu")); + assert!(rows(&menu) == VIEW_MENU, "{tool:?}: the view menu"); + assert_eq!(h.state().ui.views[0].zoom, zoom, "{tool:?}: the right-click alone does not zoom"); + assert!(entry_enabled(h.state(), &menu, FILL_SCREEN) && entry_enabled(h.state(), &menu, "view.printSize")); + // Outside the image the pasteboard colour menu wins, as for the other tools. + h.state_mut().ui.canvas_tool_menu = None; + let outside = h.state().last_canvas_rect.min + vec2(5.0, 5.0); + right_click(&mut h, outside, Modifiers::NONE); + assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.pasteboard), "{tool:?}: pasteboard menu outside"); + } +} + +#[test] +fn view_menu_zoom_in_keeps_the_clicked_point_under_the_pointer() { + let mut app = zoom_app(400, 300); + app.ui.tool = Tool::Zoom; + let mut h = harness(app); + let zoom = h.state().ui.views[0].zoom; + let doc = [300.0, 100.0]; + let p = screen_of(h.state(), doc); + right_click(&mut h, p, Modifiers::NONE); + // Chosen in the menu itself: the canvas frame that draws the menu must keep the new view. + h.get_by_label("Zoom In").click(); + h.run_steps(3); + assert!(h.state().ui.canvas_tool_menu.is_none()); + let after = h.state().ui.views[0].zoom; + assert_eq!(after, crate::zoom_levels::step(zoom, 1, [400, 300]), "one Zoom In step"); + let s = screen_of(h.state(), doc); + assert!((s - p).length() < 1.0, "the right-clicked point stays put: {s:?} vs {p:?}"); + assert_eq!(h.state().session.journal.last().map(|(id, _)| id.as_str()), Some("view.zoomIn")); + // Zoom Out returns to where it was. + right_click(&mut h, p, Modifiers::NONE); + h.get_by_label("Zoom Out").click(); + h.run_steps(3); + assert_eq!(h.state().ui.views[0].zoom, zoom); + assert!((screen_of(h.state(), doc) - p).length() < 1.0); +} + +#[test] +fn animated_zoom_off_view_menu_keeps_the_anchor_without_a_transition() { + for command in ["view.zoomIn", "view.zoomOut", FILL_SCREEN] { + let mut app = zoom_app(400, 300); + app.ui.tool = Tool::Zoom; + app.run("prefs.set", json!({"values": {"general.animatedZoom": false, "tools.zoomClickedPointToCenter": false}})).unwrap(); + let mut h = harness(app); + let doc = [300.0, 100.0]; + let p = screen_of(h.state(), doc); + right_click(&mut h, p, Modifiers::NONE); + let ctx = h.ctx.clone(); + choose(h.state_mut(), &ctx, command); + assert!(!h.state().ui.views[0].zoom_animating, "{command}"); + h.step(); + let v = &h.state().ui.views[0]; + let xf = crate::canvas::ViewXform::active(h.state()).unwrap(); + assert_eq!((xf.zoom, xf.center), (v.zoom, v.center), "{command}"); + assert!(v.zoom_anchor.is_none() && v.zoom_transition.is_none(), "{command}"); + if command != FILL_SCREEN { + assert!(screen_of(h.state(), doc).distance(p) < 1.0, "{command}: preserve the clicked point"); + } + } +} + +#[test] +fn view_menu_zoom_keeps_its_anchor_during_the_animation() { + let mut app = zoom_app(400, 300); + app.ui.tool = Tool::Zoom; + let mut h = harness(app); + let zoom = h.state().ui.views[0].zoom; + let doc = [300.0, 100.0]; + let p = screen_of(h.state(), doc); + right_click(&mut h, p, Modifiers::NONE); + let ctx = h.ctx.clone(); + // Choose without the widget click helper, which runs repaint frames until settled. + choose(h.state_mut(), &ctx, "view.zoomIn"); + h.step(); + h.input_mut().time = Some(ctx.input(|i| i.time) + 0.11); + h.step(); + let displayed = crate::canvas::ViewXform::active(h.state()).unwrap(); + assert!(displayed.zoom > zoom && displayed.zoom < h.state().ui.views[0].zoom); + assert!(displayed.to_screen(doc[0], doc[1]).distance(p) < 1.0); + h.input_mut().time = Some(ctx.input(|i| i.time) + 0.3); + h.step(); + assert!(!h.state().ui.views[0].zoom_animating); +} + +#[test] +fn view_menu_zoom_in_centres_the_clicked_point_with_the_preference() { + let mut app = zoom_app(400, 300); + app.ui.tool = Tool::Hand; + app.run("prefs.set", json!({"path": "tools.zoomClickedPointToCenter", "value": true})).unwrap(); + let mut h = harness(app); + let doc = [300.0, 100.0]; + let p = screen_of(h.state(), doc); + right_click(&mut h, p, Modifiers::NONE); + h.get_by_label("Zoom In").click(); + h.run_steps(3); + assert_eq!(h.state().ui.views[0].center, doc); +} + +#[test] +fn view_menu_fits_fills_and_sets_fixed_zooms() { + let mut app = zoom_app(400, 300); + app.ui.tool = Tool::Zoom; + let mut h = harness(app); + let p = screen_of(h.state(), [200.0, 150.0]); + let area = crate::rulers::content_rect(h.state(), h.state().last_canvas_rect).size(); + let ppp = h.state().canvas_ppp(); + let pick = |h: &mut Harness<'static, PhotocraftApp>, label: &str| { + right_click(h, p, Modifiers::NONE); + h.get_by_label(label).click(); + h.run_steps(3); + h.state().ui.views[0].zoom + }; + assert_eq!(pick(&mut h, "200%"), 2.0); + // Fill Screen: the image covers the whole canvas (one axis can overflow). + let fill = pick(&mut h, "Fill Screen") / ppp; + assert!(400.0 * fill >= area.x - 1.0 && 300.0 * fill >= area.y - 1.0, "fill {fill} for {area:?}"); + assert!(400.0 * fill <= area.x + 1.0 || 300.0 * fill <= area.y + 1.0, "fill {fill} for {area:?}"); + assert_eq!(h.state().ui.views[0].center, [200.0, 150.0]); + // Fit on Screen: back to the whole image (capped at 100%, as on open). + let fit = pick(&mut h, "Fit on Screen") / ppp; + assert!(400.0 * fit <= area.x && 300.0 * fit <= area.y && fit < fill, "fit {fit} fill {fill}"); +} + +#[test] +fn view_menu_needs_finite_points_and_a_view_tool() { + let mut app = app(); + assert!(!open_view(&mut app, &Context::default(), Tool::Brush, [1.0, 1.0], [1.0, 1.0])); + assert!(!open_view(&mut app, &Context::default(), Tool::Zoom, [f32::NAN, 1.0], [1.0, 1.0])); + assert!(!open_view(&mut app, &Context::default(), Tool::Zoom, [1.0, 1.0], [f64::INFINITY, 1.0])); + assert!(app.ui.canvas_tool_menu.is_none()); + assert!(open_view(&mut app, &Context::default(), Tool::Zoom, [1.0, 1.0], [1.0, 1.0])); + let before = app.session.journal.len(); + choose(&mut app, &Context::default(), "select.all"); + assert_eq!(app.session.journal.len(), before, "the view menu cannot run another menu's row"); + // With no document every row is greyed out and choosing one does nothing. + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + assert!(open_view(&mut app, &Context::default(), Tool::Hand, [1.0, 1.0], [1.0, 1.0])); + let menu = app.ui.canvas_tool_menu.clone().unwrap(); + for (_, id) in VIEW_MENU.iter().flatten() { + assert!(!entry_enabled(&app, &menu, id), "{id} is greyed out with no document"); + } + choose(&mut app, &Context::default(), FILL_SCREEN); + choose(&mut app, &Context::default(), "view.zoomIn"); +} + +#[test] +fn unsupported_tools_and_nonfinite_positions_do_not_open_menu() { + let mut app = app(); + assert!(!open(&mut app, &Context::default(), Tool::Brush, [1.0, 1.0])); + assert!(!open(&mut app, &Context::default(), Tool::Lasso, [f32::NAN, 1.0])); + assert!(app.ui.canvas_tool_menu.is_none()); + assert!(open(&mut app, &Context::default(), Tool::MagicWand, [1.0, 1.0])); + let before = app.session.journal.len(); + choose(&mut app, &Context::default(), "file.new"); + assert_eq!(app.session.journal.len(), before, "context menu cannot invoke an unrelated command"); +} + +#[test] +fn completed_pen_path_right_click_makes_selection() { + let mut app = app(); + app.ui.tool = Tool::Pen; + for (x, y) in [(2.0, 2.0), (20.0, 2.0), (20.0, 20.0)] { + crate::vector_ui::pen_down(&mut app, x, y, false); + crate::vector_ui::pen_up(&mut app); + } + crate::vector_ui::pen_commit(&mut app, true); + assert!(app.session.active().unwrap().doc.work_path.is_some()); + let mut h = harness(app); + let center = h.state().last_canvas_rect.center(); + right_click(&mut h, center, Modifiers::NONE); + assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.tool == Tool::Pen && m.has_path)); + let ctx = h.ctx.clone(); + choose(h.state_mut(), &ctx, "path.toSelection"); + let dialog = h.state().ui.dialogs.last().map(|d| d.id).unwrap(); + crate::dialogs::confirm(h.state_mut(), dialog).unwrap(); + assert!(h.state().session.active().unwrap().doc.selection.is_some()); + assert_eq!(h.state().session.journal.last().map(|(id, _)| id.as_str()), Some("path.toSelection")); +} + +#[test] +fn pen_menu_finishes_in_progress_path_before_selection() { + let mut app = app(); + app.ui.tool = Tool::Pen; + for (x, y) in [(2.0, 2.0), (20.0, 2.0), (20.0, 20.0)] { + crate::vector_ui::pen_down(&mut app, x, y, false); + crate::vector_ui::pen_up(&mut app); + } + assert!(app.session.active().unwrap().doc.work_path.is_none()); + assert!(open(&mut app, &Context::default(), Tool::Pen, [10.0, 10.0])); + let menu = app.ui.canvas_tool_menu.as_ref().unwrap(); + assert!(entry_enabled(&app, menu, "path.toSelection")); + choose(&mut app, &Context::default(), "path.toSelection"); + let dialog = app.ui.dialogs.last().map(|d| d.id).unwrap(); + crate::dialogs::confirm(&mut app, dialog).unwrap(); + assert!(app.session.active().unwrap().doc.work_path.is_some()); + assert!(app.session.active().unwrap().doc.selection.is_some()); +} + +/// #5703: the Pen options bar's Make Selection (Path mode) opens the same dialog for the path +/// being drawn (finished into the Work Path first), and OK selects inside it; with no path at +/// all it reports that instead. +#[test] +fn pen_options_bar_makes_a_selection_from_the_path() { + let mut app = app(); + app.ui.tool = Tool::Pen; + assert!(make_selection(&mut app).is_err(), "no path yet"); + assert!(app.ui.dialogs.is_empty()); + for (x, y) in [(2.0, 2.0), (20.0, 2.0), (20.0, 20.0)] { + crate::vector_ui::pen_down(&mut app, x, y, false); + crate::vector_ui::pen_up(&mut app); + } + make_selection(&mut app).unwrap(); + let dialog = app.ui.dialogs.last().map(|d| d.id).unwrap(); + crate::dialogs::confirm(&mut app, dialog).unwrap(); + let st = app.session.active().unwrap(); + assert!(st.doc.work_path.is_some() && st.doc.selection.is_some()); + // The active (Work) path again, with no pen path in progress. + app.run("select.deselect", json!({})).unwrap(); + make_selection(&mut app).unwrap(); + let dialog = app.ui.dialogs.last().map(|d| d.id).unwrap(); + crate::dialogs::confirm(&mut app, dialog).unwrap(); + assert!(app.session.active().unwrap().doc.selection.is_some()); + // Drawn with a saved path selected, the path is added to that one (#4721): the dialog is + // for it, not for a Work Path. + app.run("path.rename", json!({"name": "work", "to": "Cutout"})).unwrap(); + app.ui.selected_path = Some("Cutout".into()); + for (x, y) in [(4.0, 24.0), (12.0, 24.0), (12.0, 30.0)] { + crate::vector_ui::pen_down(&mut app, x, y, false); + crate::vector_ui::pen_up(&mut app); + } + make_selection(&mut app).unwrap(); + assert_eq!(app.ui.dialogs.last().and_then(|d| d.fields.get("name")), Some(&json!("Cutout"))); +} + +/// #1056: the Path Selection and Direct Selection tools' right-click opens the path menu for +/// the selected path, as the Pen's does, instead of nothing. +#[test] +fn path_selection_tools_open_the_path_menu() { + for tool in [Tool::PathSelection, Tool::DirectSelection] { + let mut app = app(); + app.ui.tool = Tool::Pen; + for (x, y) in [(2.0, 2.0), (20.0, 2.0), (20.0, 20.0)] { + crate::vector_ui::pen_down(&mut app, x, y, false); + crate::vector_ui::pen_up(&mut app); + } + crate::vector_ui::pen_commit(&mut app, false); + assert!(app.session.active().unwrap().doc.work_path.is_some()); + app.ui.tool = tool; + assert!(applies(tool)); + assert!(open(&mut app, &Context::default(), tool, [10.0, 10.0]), "{tool:?}"); + let menu = app.ui.canvas_tool_menu.clone().unwrap(); + assert_eq!(rows(&menu), PEN_MENU, "{tool:?}"); + assert!(menu.has_path && entry_enabled(&app, &menu, "path.toSelection"), "{tool:?}"); + choose(&mut app, &Context::default(), "path.toSelection"); + let dialog = app.ui.dialogs.last().map(|d| d.id).unwrap(); + crate::dialogs::confirm(&mut app, dialog).unwrap(); + assert!(app.session.active().unwrap().doc.selection.is_some(), "{tool:?}: Make Selection made one"); + } +} + +#[test] +fn pen_menu_has_all_reference_rows_in_order_and_guards_unavailable_actions() { + let labels: Vec<_> = PEN_MENU.iter().map(|row| row.map(|(label, _)| label)).collect(); + assert_eq!( + labels, + vec![ + Some("Create Vector Mask"), + Some("Delete Path"), + None, + Some("Define Custom Shape…"), + None, + Some("Make Selection…"), + Some("New Guides From Shape"), + Some("Fill Path…"), + Some("Stroke Path…"), + None, + Some("Clipping Path…"), + None, + Some("Free Transform Path"), + None, + Some("Unite Shapes"), + Some("Subtract Front Shape"), + Some("Unite Shapes at Overlap"), + Some("Subtract Shapes at Overlap"), + None, + Some("Copy Fill"), + Some("Copy Complete Stroke"), + None, + Some("Paste Fill"), + Some("Paste Complete Stroke"), + None, + Some("Isolate Layers"), + None, + Some("Make Symmetry Path"), + Some("Disable Symmetry Path"), + ] + ); + let mut app = app(); + app.ui.tool = Tool::Pen; + assert!(open(&mut app, &Context::default(), Tool::Pen, [10.0, 10.0])); + let menu = app.ui.canvas_tool_menu.as_ref().unwrap(); + assert!(!entry_enabled(&app, menu, "path.toSelection")); + let before = app.session.journal.len(); + choose(&mut app, &Context::default(), "path.toSelection"); + assert_eq!(app.session.journal.len(), before); + assert!(app.ui.dialogs.is_empty()); +} + +#[test] +fn pen_menu_creates_mask_deletes_path_and_opens_named_path_dialogs() { + let mut app = app(); + app.ui.tool = Tool::Pen; + work_path(&mut app); + choose_open(&mut app, "layer.vectorMask.fromPath"); + let st = app.session.active().unwrap(); + assert!(st.active_layer.and_then(|id| st.doc.layer(id)).is_some_and(|l| l.vector_mask.is_some())); + // The new vector mask's path becomes the active one (#4728); pick the Work Path again. + assert_eq!(app.ui.selected_path.as_deref(), Some("layer")); + app.ui.selected_path = Some("work".into()); + choose_open(&mut app, "edit.defineCustomShape"); + let id = app.ui.dialogs.last().map(|d| d.id).unwrap(); + let fields = &app.ui.dialogs.last().unwrap().fields; + assert_eq!(fields.get("path"), Some(&json!("work"))); + app.ui.dialog_mut(id).unwrap().fields.insert("name".into(), json!("Menu Shape")); + crate::dialogs::confirm(&mut app, id).unwrap(); + assert!(app.session.edit_state.custom_shapes.iter().any(|s| s.name == "Menu Shape")); + choose_open(&mut app, "path.fill"); + let id = app.ui.dialogs.last().map(|d| d.id).unwrap(); + assert_eq!(app.ui.dialogs.last().unwrap().fields.get("name"), Some(&json!("work"))); + crate::dialogs::confirm(&mut app, id).unwrap(); + assert_eq!(app.session.journal.last().map(|(id, _)| id.as_str()), Some("path.fill")); + choose_open(&mut app, "path.delete"); + assert!(app.session.active().unwrap().doc.work_path.is_none()); +} + +#[test] +fn pen_menu_saved_path_clipping_and_numeric_transform() { + let mut app = app(); + app.ui.tool = Tool::Pen; + work_path(&mut app); + app.run("path.rename", json!({"name": "work", "to": "Cutout"})).unwrap(); + app.ui.selected_path = Some("Cutout".into()); + assert!(open(&mut app, &Context::default(), Tool::Pen, [10.0, 10.0])); + assert!(entry_enabled(&app, app.ui.canvas_tool_menu.as_ref().unwrap(), "path.clippingPath.set")); + choose(&mut app, &Context::default(), "path.clippingPath.set"); + let id = app.ui.dialogs.last().map(|d| d.id).unwrap(); + app.ui.dialog_mut(id).unwrap().fields.insert("flatness".into(), json!(2.0)); + crate::dialogs::confirm(&mut app, id).unwrap(); + assert_eq!(app.session.active().unwrap().doc.clipping_path.as_ref().map(|p| p.name.as_str()), Some("Cutout")); + choose_open(&mut app, "path.transform"); + let id = app.ui.dialogs.last().map(|d| d.id).unwrap(); + app.ui.dialog_mut(id).unwrap().fields.insert("translateX".into(), json!(5.0)); + crate::dialogs::confirm(&mut app, id).unwrap(); + assert_eq!(app.session.journal.last().map(|(id, _)| id.as_str()), Some("path.transform")); +} + +#[test] +fn pen_shape_menu_enables_shape_ops_and_style_copy_only_when_applicable() { + let mut app = app(); + app.ui.tool = Tool::Pen; + app.run( + "shape.create", + json!({"kind":"path", "path":{"subpaths":[ + {"closed":true,"knots":[[2,2],[20,2],[20,20]]}, + {"closed":true,"knots":[[5,5],[10,5],[10,10]]} + ]}, "fill":"#ff0000", "stroke":{"width":2,"color":"#000000"}}), + ) + .unwrap(); + assert!(open(&mut app, &Context::default(), Tool::Pen, [10.0, 10.0])); + let menu = app.ui.canvas_tool_menu.as_ref().unwrap(); + assert!(entry_enabled(&app, menu, "layer.combineShapes.unite")); + assert!(entry_enabled(&app, menu, "path.style.copyFill")); + assert!(!entry_enabled(&app, menu, "path.style.pasteFill")); + assert!(!entry_enabled(&app, menu, "path.fill")); + choose(&mut app, &Context::default(), "path.style.copyFill"); + assert!(app.session.path_fill_clipboard.is_some()); + assert!(open(&mut app, &Context::default(), Tool::Pen, [10.0, 10.0])); + assert!(entry_enabled(&app, app.ui.canvas_tool_menu.as_ref().unwrap(), "path.style.pasteFill")); +} + +#[test] +fn unfinished_shape_path_disables_actions_that_would_target_the_previous_layer() { + let mut app = app(); + app.ui.tool = Tool::Pen; + app.ui.tool_options.vector_mode = "shape".into(); + for (x, y) in [(2.0, 2.0), (20.0, 2.0), (20.0, 20.0)] { + crate::vector_ui::pen_down(&mut app, x, y, false); + crate::vector_ui::pen_up(&mut app); + } + assert!(open(&mut app, &Context::default(), Tool::Pen, [10.0, 10.0])); + let menu = app.ui.canvas_tool_menu.as_ref().unwrap(); + for id in ["layer.vectorMask.fromPath", "path.delete", "path.fill", "path.stroke", "path.clippingPath.set", "view.newGuidesFromShape"] { + assert!(!entry_enabled(&app, menu, id), "{id} must not act on the layer replaced by the pending shape"); + } + assert!(entry_enabled(&app, menu, "path.toSelection")); +} + +/// A 32 × 32 document with the Crop tool picked (Classic Mode, so the view stays put) and its +/// untouched default frame. +fn crop_app() -> PhotocraftApp { + let mut app = app(); + app.ui.tool = Tool::Crop; + app.ui.tool_options.crop_shield.classic_mode = true; + app.ui.extras.snap = false; + crate::crop_ui::ensure_frame(&mut app); + app +} + +/// Draws a crop frame from (4, 4) to (28, 28): a pending crop. Returns the frame. +fn draw_crop(app: &mut PhotocraftApp) -> [f64; 4] { + use crate::canvas::{ToolEvent, tool_event}; + tool_event(app, ToolEvent::Down { x: 4.0, y: 4.0, pressure: 1.0 }, Modifiers::NONE); + tool_event(app, ToolEvent::Move { x: 16.0, y: 16.0, pressure: 1.0 }, Modifiers::NONE); + tool_event(app, ToolEvent::Move { x: 28.0, y: 28.0, pressure: 1.0 }, Modifiers::NONE); + tool_event(app, ToolEvent::Up { x: 28.0, y: 28.0 }, Modifiers::NONE); + assert!(crate::crop_ui::pending(app), "the drag draws a pending frame"); + app.ui.crop_rect.unwrap() +} + +fn aspect(r: [f64; 4]) -> f64 { + (r[2] - r[0]) / (r[3] - r[1]) +} + +/// #6561: right-click on a pending crop opens its menu without touching the frame, and a ratio +/// row refits the frame as the options bar's dropdown does. +#[test] +fn right_click_on_a_pending_crop_opens_the_crop_menu_and_a_ratio_refits_the_frame() { + let mut app = crop_app(); + let frame = draw_crop(&mut app); + let mut h = harness(app); + let center = h.state().last_canvas_rect.center(); + right_click(&mut h, center, Modifiers::NONE); + let menu = h.state().ui.canvas_tool_menu.clone().expect("right-click on a pending crop opens a menu"); + assert_eq!(h.state().ui.crop_rect, Some(frame), "the right-click leaves the frame alone"); + assert!(available(h.state(), &menu, "crop.ratio.16:9"), "the menu lists the options bar's ratios"); + let ctx = h.ctx.clone(); + choose(h.state_mut(), &ctx, "crop.ratio.16:9"); + assert_eq!(h.state().ui.tool_options.crop_ratio, "16:9"); + let r = h.state().ui.crop_rect.unwrap(); + assert!((aspect(r) - 16.0 / 9.0).abs() < 1e-9, "the frame is 16 : 9 now: {r:?}"); + assert!(r[0] >= frame[0] && r[1] >= frame[1] && r[2] <= frame[2] && r[3] <= frame[3], "fitted inside the old frame: {r:?}"); + assert!(h.state().ui.canvas_tool_menu.is_none()); +} + +#[test] +fn untouched_crop_frame_has_no_menu_and_a_pending_one_wins_over_the_pasteboard() { + let mut h = harness(crop_app()); + let rect = h.state().last_canvas_rect; + let outside = rect.min + vec2(5.0, 5.0); + right_click(&mut h, rect.center(), Modifiers::NONE); + assert!(h.state().ui.canvas_tool_menu.is_none(), "the tool's untouched frame is no crop in progress"); + right_click(&mut h, outside, Modifiers::NONE); + assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.pasteboard), "outside: the pasteboard menu, as before"); + h.state_mut().ui.canvas_tool_menu = None; + draw_crop(h.state_mut()); + h.run_steps(2); + right_click(&mut h, outside, Modifiers::NONE); + let menu = h.state().ui.canvas_tool_menu.clone().unwrap(); + assert!(menu.crop.is_some() && !menu.pasteboard, "with a crop pending, its menu also outside the image"); +} + +/// A harness in the app's order: shortcuts (the crop's Esc and ↵ among them), then the canvas. +fn shortcut_harness(mut app: PhotocraftApp) -> Harness<'static, PhotocraftApp> { + app.sync_views(); + let mut h = Harness::builder().with_size(vec2(1000.0, 700.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let ctx = ui.ctx().clone(); + if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + crate::shortcuts::handle(app, &ctx); + egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::default()); + h.run_steps(4); + h +} + +#[test] +fn esc_closes_only_the_crop_menu() { + let mut app = crop_app(); + let frame = draw_crop(&mut app); + let mut h = shortcut_harness(app); + let center = h.state().last_canvas_rect.center(); + right_click(&mut h, center, Modifiers::NONE); + assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.crop.is_some())); + h.key_press(egui::Key::Escape); + h.run_steps(2); + assert!(h.state().ui.canvas_tool_menu.is_none(), "Esc closes the menu"); + assert_eq!(h.state().ui.crop_rect, Some(frame), "and only the menu: the crop is not cancelled"); + assert!(crate::crop_ui::pending(h.state())); +} + +/// ↵ under the open crop menu doesn't commit the crop beneath it. +#[test] +fn enter_under_the_crop_menu_does_not_crop() { + let mut app = crop_app(); + let frame = draw_crop(&mut app); + let mut h = shortcut_harness(app); + let size = h.state().session.active().map(|s| s.doc.size); + let center = h.state().last_canvas_rect.center(); + right_click(&mut h, center, Modifiers::NONE); + assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.crop.is_some())); + h.key_press(egui::Key::Enter); + h.run_steps(2); + assert_eq!(h.state().session.active().map(|s| s.doc.size), size, "↵ under the menu doesn't crop"); + assert_eq!(h.state().ui.crop_rect, Some(frame)); + assert!(crate::crop_ui::pending(h.state())); +} + +/// A right-click while the left button drags the crop frame opens no menu over the drag, on +/// the image or outside it (no pasteboard menu either), and the menu opens again once the left +/// button is up, though egui ended that drag without a release of its own. +#[test] +fn no_crop_menu_while_the_left_button_drags_the_frame() { + let mut app = crop_app(); + draw_crop(&mut app); + let mut h = harness(app); + let rect = h.state().last_canvas_rect; + let (center, outside) = (rect.center(), rect.min + vec2(5.0, 5.0)); + let left = |pos, pressed| egui::Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + h.event(egui::Event::PointerMoved(center)); + h.run_steps(1); + h.event(left(center, true)); + h.run_steps(1); + for k in 1..=4 { + h.event(egui::Event::PointerMoved(center + vec2(8.0 * k as f32, 0.0))); + h.run_steps(1); + } + assert!(h.state().crop.drag.is_some(), "the left button drags the frame"); + let held = center + vec2(32.0, 0.0); + right_click(&mut h, held, Modifiers::NONE); + assert!(h.state().ui.canvas_tool_menu.is_none(), "no crop menu over the drag"); + right_click(&mut h, outside, Modifiers::NONE); + assert!(h.state().ui.canvas_tool_menu.is_none(), "nor the pasteboard menu outside the image"); + h.event(egui::Event::PointerMoved(held)); + h.event(left(held, false)); + h.run_steps(2); + right_click(&mut h, center, Modifiers::NONE); + assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.crop.is_some()), "with the button up the menu opens"); +} + +/// The left button down with no crop gesture under way (a press egui doesn't take for a drag +/// yet, or one whose release was lost to an Alt+Tab or a cancelled touch) doesn't keep the +/// crop menu shut. +#[test] +fn a_left_button_down_without_a_crop_drag_keeps_the_crop_menu() { + let mut app = crop_app(); + draw_crop(&mut app); + let mut h = harness(app); + let center = h.state().last_canvas_rect.center(); + h.event(egui::Event::PointerMoved(center)); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: center, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + assert!(h.ctx.input(|i| i.pointer.primary_down()) && h.state().crop.drag.is_none(), "down, dragging nothing"); + right_click(&mut h, center, Modifiers::NONE); + assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.crop.is_some()), "the crop menu opens"); +} + +/// Nor does a right-click open a menu over a Straighten line the left button still draws. +#[test] +fn no_crop_menu_while_the_left_button_draws_a_straighten_line() { + let mut app = crop_app(); + draw_crop(&mut app); + crate::crop_straighten::toggle(&mut app); + let mut h = harness(app); + let center = h.state().last_canvas_rect.center(); + let left = |pos, pressed| egui::Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + h.event(egui::Event::PointerMoved(center)); + h.run_steps(1); + h.event(left(center, true)); + h.run_steps(1); + for k in 1..=4 { + h.event(egui::Event::PointerMoved(center + vec2(8.0 * k as f32, 4.0))); + h.run_steps(1); + } + assert!(h.state().crop.straighten.line.is_some() && h.state().crop.drag.is_none(), "the left button draws a Straighten line"); + right_click(&mut h, center + vec2(32.0, 4.0), Modifiers::NONE); + assert!(h.state().ui.canvas_tool_menu.is_none(), "no menu over the line"); +} + +/// A finger held still on a pending crop (a touch screen's press-and-hold right-click) opens +/// the crop menu, though the touch counts as the primary button down. +#[test] +fn a_finger_held_on_a_pending_crop_opens_the_crop_menu() { + let mut app = crop_app(); + let frame = draw_crop(&mut app); + let mut h = harness(app); + let at = h.state().last_canvas_rect.center(); + let touch = |phase| egui::Event::Touch { device_id: egui::TouchDeviceId(1), id: egui::TouchId(1), phase, pos: at, force: None }; + let button = |pressed| egui::Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + h.input_mut().events.extend([egui::Event::PointerMoved(at), touch(egui::TouchPhase::Start), button(true)]); + h.step(); + // Held past egui's max_click_duration (0.8 s) without moving. + for _ in 0..120 { + if h.state().ui.canvas_tool_menu.is_some() { + break; + } + h.step(); + } + assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.crop.is_some()), "the held finger opens the crop menu"); + h.input_mut().events.extend([touch(egui::TouchPhase::End), button(false)]); + h.run_steps(2); + assert_eq!(h.state().ui.crop_rect, Some(frame), "the hold leaves the frame alone"); +} + +#[test] +fn crop_menu_rows_act_like_the_options_bar() { + use crate::crop_overlay::{CropOverlay, OverlayShow}; + let ctx = Context::default(); + let mut app = crop_app(); + draw_crop(&mut app); + // Space's Hand held over the Crop tool keeps its own right-click. + assert!(!open_crop(&mut app, &ctx, Tool::Hand, [10.0, 10.0])); + let reopen = |app: &mut PhotocraftApp| { + assert!(open_crop(app, &Context::default(), Tool::Crop, [10.0, 10.0])); + app.ui.canvas_tool_menu.clone().unwrap() + }; + // Nothing to save with a free ratio, nothing to delete without saved presets. + let menu = reopen(&mut app); + assert!(!entry_enabled(&app, &menu, CROP_NEW) && !entry_enabled(&app, &menu, CROP_DELETE)); + assert!(mode_checked(&app, &menu, "crop.ratio."), "free Ratio is checked, as in the dropdown"); + // A size preset fills W x H x Resolution, which the menu checks, as the dropdown does. + choose(&mut app, &ctx, "crop.ratio.preset:4x5in"); + let menu = reopen(&mut app); + assert!(mode_checked(&app, &menu, "crop.ratio.whr") && !mode_checked(&app, &menu, "crop.ratio.preset:4x5in")); + assert!((aspect(app.ui.crop_rect.unwrap()) - 0.8).abs() < 1e-9); + assert!(entry_enabled(&app, &menu, CROP_NEW)); + // Clear empties W x H x Resolution, as the bar's Clear. + choose(&mut app, &ctx, CROP_CLEAR); + assert_eq!(app.ui.tool_options.crop_width, ""); + // Overlays: another overlay starts at its first orientation; when it shows. + app.ui.tool_options.crop_overlay = CropOverlay::GoldenSpiral; + app.ui.tool_options.crop_overlay_orientation = 2; + reopen(&mut app); + choose(&mut app, &ctx, "crop.overlay.triangle"); + assert_eq!((app.ui.tool_options.crop_overlay, app.ui.tool_options.crop_overlay_orientation), (CropOverlay::Triangle, 0)); + reopen(&mut app); + choose(&mut app, &ctx, "crop.overlayShow.never"); + assert_eq!(app.ui.tool_options.crop_overlay_show, OverlayShow::Never); + let menu = reopen(&mut app); + assert!(mode_checked(&app, &menu, "crop.overlay.triangle") && mode_checked(&app, &menu, "crop.overlayShow.never")); + // A saved preset is listed by name; picking it refits the frame to its W x H, though the + // ratio key is "whr" before and after. + app.ui.canvas_tool_menu = None; + app.ui.tool_options.crop_ratio = crate::crop_size::WHR.into(); + let saved = json!({"crop_ratio": "whr", "crop_width": "300 px", "crop_height": "100 px", "crop_resolution": "72", "crop_resolution_unit": "px/in"}); + app.run("tool.presets.new", json!({"name": "Banner", "tool": "crop", "options": {"toolOptions": saved}})).unwrap(); + let menu = reopen(&mut app); + let banner = crop_rows(&menu).into_iter().flatten().find(|(l, _)| l == "Banner").expect("the saved preset is a row").1; + assert!(entry_enabled(&app, &menu, CROP_DELETE)); + choose(&mut app, &ctx, &banner); + assert_eq!(app.ui.tool_options.crop_width, "300 px"); + assert!((aspect(app.ui.crop_rect.unwrap()) - 3.0).abs() < 1e-9, "the frame follows the preset: {:?}", app.ui.crop_rect); + let menu = reopen(&mut app); + assert!(mode_checked(&app, &menu, &banner)); + // Crop commits as ↵ does: the preset's size. + choose(&mut app, &ctx, CROP_COMMIT); + let size = app.session.active().unwrap().doc.size; + assert_eq!((size.width, size.height), (300, 100)); + // Cancel drops a pending crop. + draw_crop(&mut app); + reopen(&mut app); + choose(&mut app, &ctx, CROP_CANCEL); + assert!(!crate::crop_ui::pending(&app)); +} diff --git a/crates/ui-egui/src/canvas/channel_view.rs b/crates/ui-egui/src/canvas/channel_view.rs new file mode 100644 index 0000000000..4d7602e4a1 --- /dev/null +++ b/crates/ui-egui/src/canvas/channel_view.rs @@ -0,0 +1,390 @@ +//! Channel display on the canvas: alpha / spot / Quick Mask colour overlays, single colour +//! channel views (grayscale) and hidden colour channels. +//! +//! The document composite (GPU or CPU) is untouched. When the Channels panel shows anything other +//! than the plain composite, one extra texture is drawn over it: transparent overlay pixels when +//! the composite stays visible, an opaque picture otherwise. The texture is keyed by document +//! revision and view state and updated per damage rectangle while painting, so nothing is +//! recomposited per frame. + +use egui::{Color32, TextureOptions}; +use photocraft_doc::{AlphaChannel, ColorMode, Document}; +use photocraft_engine::channel_cmds::{ChannelView, color_count}; +use photocraft_engine::mask_view_cmds::MaskViewMode; +use photocraft_geom::Rect; +use photocraft_raster::{Surface, from_rgba, to_rgba}; + +use crate::PhotocraftApp; + +/// Largest overlay texture side; bigger documents show a downsampled overlay. +const MAX_SIDE: u32 = 4096; +/// Limit the sampled float composite to 128 MiB across open documents. +const MAX_COMPOSITE_CACHE_PIXELS: usize = 8 * 1024 * 1024; + +struct SampledComposite { + revision: u64, + /// `revision` minus the view-only part: what the pixels depend on. + content: u64, + preview_key: u64, + factor: u32, + pixels: Vec<[f32; 4]>, +} + +struct CompositeSource<'a> { + cached: Option<&'a [[f32; 4]]>, + fresh: &'a mut Option>, +} + +pub struct Cache { + revision: u64, + key: u64, + /// The canvas document shown by a live stroke (0 is the committed document). + pub(crate) preview_key: u64, + factor: u32, + /// False while the plain composite shows: the texture is kept (so toggling a view back on + /// reuses its allocation) but its pixels are stale. + valid: bool, + tex: egui::TextureHandle, + source: Option, +} + +fn sample(s: &Surface, r: Rect, factor: u32) -> Vec { + let (w, h) = (r.width().div_ceil(factor), r.height().div_ceil(factor)); + if factor == 1 { + let mut v = Vec::new(); + s.read_region_into(r, &mut v); + let ch = s.channels(); + return if ch > 1 { v.chunks_exact(ch).map(|p| p[0]).collect() } else { v }; + } + let mut out = Vec::with_capacity((w * h) as usize); + let mut row = vec![0.0f32; w as usize]; + for y in 0..h { + s.sample_row_strided(r.y0 + (y * factor) as i32, r.x0, factor as i32, 0, &mut row); + out.extend_from_slice(&row); + } + out +} + +/// How the view draws what it shows. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Look { + /// Single colour channels tinted instead of grayscale (Photoshop's "Show Channels in Color"). + pub in_color: bool, + /// The layer mask rubylith's colour and opacity (0..1): Layer Mask Display Options. + pub mask_rgb: [f32; 3], + pub mask_opacity: f32, +} + +impl Default for Look { + /// Photoshop's: grayscale channels, a red rubylith at 50 %. + fn default() -> Self { + Self { in_color: false, mask_rgb: AlphaChannel::DEFAULT_COLOR.to_rgb(), mask_opacity: 0.5 } + } +} + +impl Look { + /// The current preferences of `s`. + pub fn of(s: &photocraft_engine::Session) -> Self { + let p = s.prefs(); + Self { in_color: p.interface.show_channels_in_color, mask_rgb: p.layer_mask_overlay.rgb(), mask_opacity: p.layer_mask_overlay.alpha() } + } +} + +/// Composite RGBA (over white, like Photoshop's channel views) at `factor` stride. +/// Render in bands instead of allocating a full-resolution float composite to sample a preview. +fn composite(doc: &Document, r: Rect, factor: u32) -> Vec<[f32; 4]> { + let (w, h) = (r.width().div_ceil(factor), r.height().div_ceil(factor)); + let mut out = Vec::with_capacity((w * h) as usize); + let f = factor as i32; + let _ = photocraft_compose::render_bands(doc, r, 0, |band| -> Result<(), ()> { + let first = band.rect.y0 + (r.y0 - band.rect.y0).rem_euclid(f); + for y in (first..band.rect.y1).step_by(factor as usize) { + for x in (r.x0..r.x1).step_by(factor as usize) { + let p = band.get(x, y); + let a = p[3].clamp(0.0, 1.0); + out.push([p[0] * a + 1.0 - a, p[1] * a + 1.0 - a, p[2] * a + 1.0 - a, 1.0]); + } + } + Ok(()) + }); + out +} + +/// The channel view of `r` (document pixels, sampled every `factor` px) as premultiplied pixels, +/// or `None` when the plain composite is all there is to show. +pub fn render(doc: &Document, v: &ChannelView, r: Rect, factor: u32, look: Look, active: Option) -> Option> { + let mut unused = None; + render_with_source(doc, v, r, factor, look, active, CompositeSource { cached: None, fresh: &mut unused }) +} + +fn render_with_source( + doc: &Document, + v: &ChannelView, + r: Rect, + factor: u32, + look: Look, + active: Option, + source: CompositeSource<'_>, +) -> Option> { + if v.is_plain(doc) || r.is_empty() { + return None; + } + let in_color = look.in_color; + let (mask_rgb, mask_opacity) = (look.mask_rgb, look.mask_opacity.clamp(0.0, 1.0)); + let layer_mask = v.shown_layer_mask(doc); + // ⌥-click mask view (#196): the pixel mask alone, in grayscale (white reveals); ⇧⌥ with + // nothing else shown: just the rubylith. Use the compositor's cached feather for the pixel + // mask, but leave vector masks out: this view targets the pixel mask channel by itself. + let feathered_mask = v + .layer_mask + .and_then(|view| doc.layer(view.layer)) + .filter(|layer| layer.mask.as_ref().is_some_and(|mask| mask.enabled && photocraft_compose::masks::feather_sigma(mask.feather) > 0.0)) + .and_then(|layer| { + let mut pixel_mask_layer = layer.clone(); + pixel_mask_layer.vector_mask = None; + photocraft_compose::masks::combined_mask(&pixel_mask_layer, doc.bounds()) + }); + let shown_mask = layer_mask.map(|(m, mode)| (feathered_mask.as_ref().unwrap_or(&m.surface), mode)); + let only_mask = ChannelView { layer_mask: None, ..v.clone() }.is_plain(doc); + match shown_mask { + Some((m, MaskViewMode::Gray)) => return Some(mask_px(m, r, factor, |g| Color32::from_gray(q(g)))), + Some((m, MaskViewMode::Overlay)) if only_mask => { + let c = mask_rgb; + return Some(mask_px(m, r, factor, |g| { + let a = mask_opacity * (1.0 - g.clamp(0.0, 1.0)); + Color32::from_rgba_premultiplied(q(c[0] * a), q(c[1] * a), q(c[2] * a), q(a)) + })); + } + _ => {} + } + let colors = color_count(doc); + let vis = v.visible_colors(colors); + let (w, h) = (r.width().div_ceil(factor), r.height().div_ceil(factor)); + let n = (w * h) as usize; + let mut overlays: Vec<&AlphaChannel> = (0..doc.channels.len()).filter(|i| v.alpha_shown(*i)).map(|i| &doc.channels[i]).collect(); + let gray = |s: &Surface| sample(s, r, factor).into_iter().map(|g| [g, g, g, 1.0]).collect(); + // Premultiplied RGBA accumulator. With no colour channel left, the channel being edited + // (alpha, Quick Mask, or layer mask) is the picture — grayscale, not a rubylith over nothing. + let mut solo_quick = false; + let mut solo_mask = false; + let mut out: Vec<[f32; 4]> = if vis == 0 { + if !overlays.is_empty() { + let first = overlays.remove(0); + gray(&first.surface) + } else if let Some(q) = doc.quick_mask.as_ref().filter(|_| !v.quick_mask_hidden) { + solo_quick = true; + gray(&q.surface) + } else if let Some((m, _)) = shown_mask { + solo_mask = true; + gray(m) + } else { + let m = active.and_then(|id| doc.layer(id)).and_then(|l| l.mask.as_ref())?; + solo_mask = true; + gray(&m.surface) + } + } else if vis < colors { + let fmt = doc.pixel_format(); + let mode = fmt.mode; + let shown: Vec = (0..colors).filter(|k| v.color_visible(*k)).collect(); + let computed = if source.cached.is_some_and(|px| px.len() == n) { None } else { Some(composite(doc, r, factor)) }; + let pixels = source.cached.filter(|px| px.len() == n).or(computed.as_deref())?; + let converted = pixels + .iter() + .copied() + .map(|rgba| { + let mut native = from_rgba(&fmt, rgba); + if shown.len() == 1 && !in_color { + let x = native[shown[0]]; + // Ink channels read dark where there is ink. + let g = if mode == ColorMode::Cmyk { 1.0 - x } else { x }; + return [g, g, g, 1.0]; + } + for (k, x) in native[..colors].iter_mut().enumerate() { + if !v.color_visible(k) { + // Hidden channels contribute nothing (Lab: neutral a/b, and a neutral + // Lightness under Show Channels in Color, so an isolated a/b channel + // tints over mid gray instead of black, as Photoshop does). + *x = if mode == ColorMode::Lab && (k > 0 || in_color) { 0.5 } else { 0.0 }; + } + } + let c = to_rgba(&fmt, &native); + [c[0], c[1], c[2], 1.0] + }) + .collect(); + if n <= MAX_COMPOSITE_CACHE_PIXELS { + *source.fresh = computed; + } + converted + } else { + vec![[0.0; 4]; n] + }; + // Rubylith: `color` at `opacity` × coverage over the accumulated pixels. + let mut tint = |values: Vec, color: photocraft_color::Color, opacity: f32, coverage: &dyn Fn(f32) -> f32| { + let c = color.to_rgb(); + for (o, val) in out.iter_mut().zip(values) { + let a = (coverage(val.clamp(0.0, 1.0)) * opacity).clamp(0.0, 1.0); + for j in 0..3 { + o[j] = c[j] * a + o[j] * (1.0 - a); + } + o[3] = a + o[3] * (1.0 - a); + } + }; + let quick = doc.quick_mask.as_ref().filter(|_| !v.quick_mask_hidden && !solo_quick); + for ch in overlays.into_iter().chain(quick) { + let (color, opacity) = match ch.spot { + // Spot inks show more solid as solidity rises. + Some((ink, solidity)) => (ink, 0.5 + 0.5 * solidity), + None => (ch.color, ch.opacity), + }; + tint(sample(&ch.surface, r, factor), color, opacity, &|x| ch.overlay_coverage(x)); + } + // ⇧⌥-click mask view (#196): the layer mask tinted over the hidden areas in the Layer Mask + // Display Options colour and opacity (red at 50 % unless set). + if !solo_mask && let Some((m, MaskViewMode::Overlay)) = shown_mask { + let [cr, cg, cb] = mask_rgb; + tint(sample(m, r, factor), photocraft_color::Color::rgb(cr, cg, cb), mask_opacity, &|x| 1.0 - x); + } + Some(out.into_iter().map(|p| Color32::from_rgba_premultiplied(q(p[0]), q(p[1]), q(p[2]), q(p[3]))).collect()) +} + +/// `r` of a one-channel surface sampled every `factor` px, mapped to colours row by row (in +/// parallel off the web). +fn mask_px(s: &Surface, r: Rect, factor: u32, color: impl Fn(f32) -> Color32 + Sync) -> Vec { + let (w, h) = (r.width().div_ceil(factor) as usize, r.height().div_ceil(factor) as usize); + let mut px = vec![Color32::TRANSPARENT; w * h]; + let row = |y: usize, out: &mut [Color32]| { + let mut vals = vec![0.0f32; out.len()]; + s.sample_row_strided(r.y0 + (y as u32 * factor) as i32, r.x0, factor as i32, 0, &mut vals); + for (o, v) in out.iter_mut().zip(vals) { + *o = color(v); + } + }; + if w == 0 { + return px; + } + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + px.par_chunks_mut(w).enumerate().for_each(|(y, out)| row(y, out)); + } + #[cfg(target_arch = "wasm32")] + for (y, out) in px.chunks_mut(w).enumerate() { + row(y, out); + } + px +} + +/// A float in 0..=1 as an 8-bit channel value. +fn q(x: f32) -> u8 { + (x.clamp(0.0, 1.0) * 255.0 + 0.5) as u8 +} + +fn view_key(v: &ChannelView, look: Look) -> u64 { + let s = serde_json::to_string(&(v, look.mask_rgb, look.mask_opacity)).unwrap_or_default(); + s.bytes().fold(look.in_color as u64 + 1, |h, b| h.wrapping_mul(1_099_511_628_211).wrapping_add(b as u64)) +} + +/// Make the channel-view texture of document `idx` current; `None` = nothing to draw. +pub fn ensure(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usize) -> Option { + let st = app.session.documents().get(idx)?; + let view = st.channel_view.clone(); + let active = st.active_layer; + let (revision, last_damage) = (st.revision, st.last_damage); + let content = revision.wrapping_sub(st.view_revision); + let id = st.doc.id.0; + if view.is_plain(&st.doc) { + if let Some(c) = app.channel_views.get_mut(&id) { + c.valid = false; + } + return None; + } + // Mask and channel views are drawn over the canvas: show the same live document, + // otherwise an opaque grayscale mask hides the stroke until it is committed (#2078). + // The plain-composite path above needs no preview work. + let (doc, preview_key) = crate::canvas::filter_channel_preview(app, idx, ctx).unwrap_or_else(|| crate::canvas::display_doc(app, idx)); + // Interface ▸ Show Channels in Color tints single colour channel views on the canvas too, + // not just the panel thumbnails (#2385). The view key carries the flag and the Layer Mask + // Display Options, so changing them rebuilds the texture. + let look = Look::of(&app.session); + let key = view_key(&view, look); + // Never exceed what the GPU accepts (egui panics on oversized textures). + let max_side = (ctx.input(|i| i.max_texture_side) as u32).clamp(256, MAX_SIDE); + let factor = doc.size.width.max(doc.size.height).div_ceil(max_side).max(1); + // A live preview can mutate the same Arc in place. Content revision and preview_key, not + // pointer identity, determine whether these flattened pixels are still current. + if let Some(c) = app.channel_views.get_mut(&id) { + if let Some(s) = c.source.as_mut().filter(|s| s.factor == factor && s.content == content && s.preview_key == preview_key) { + s.revision = revision; + } else { + c.source = None; + } + } + if let Some(c) = app.channel_views.get(&id) + && c.key == key + && c.factor == factor + && c.valid + && c.revision == revision + && c.preview_key == preview_key + { + return Some(c.tex.id()); + } + let damage = + app.channel_views.get(&id).and_then(|c| crate::canvas::damage_since(app, idx, (c.revision, c.preview_key), (revision, preview_key), 0, last_damage)); + if let Some(c) = app.channel_views.get_mut(&id) + && c.key == key + && c.factor == factor + && c.valid + && let Some(d) = damage + { + // Re-render just the damage, snapped to the sampling grid so a downsampled texture + // (big documents) updates in place too. + let f = factor as i32; + let d = d.intersect(&doc.bounds()); + let r = Rect::new(d.x0.div_euclid(f) * f, d.y0.div_euclid(f) * f, d.x1, d.y1).intersect(&doc.bounds()); + if !r.is_empty() + && let Some(px) = render(&doc, &view, r, factor, look, active) + { + let img = egui::ColorImage::new([r.width().div_ceil(factor) as usize, r.height().div_ceil(factor) as usize], px); + c.tex.set_partial([(r.x0 / f) as usize, (r.y0 / f) as usize], img, TextureOptions::LINEAR); + } + c.revision = revision; + c.preview_key = preview_key; + return Some(c.tex.id()); + } + let b = doc.bounds(); + let cached = app.channel_views.get(&id).and_then(|c| c.source.as_ref()).map(|s| s.pixels.as_slice()); + let mut fresh = None; + let px = render_with_source(&doc, &view, b, factor, look, active, CompositeSource { cached, fresh: &mut fresh })?; + let new_source = fresh.is_some(); + let size = [b.width().div_ceil(factor) as usize, b.height().div_ceil(factor) as usize]; + let img = egui::ColorImage::new(size, px); + match app.channel_views.get_mut(&id) { + Some(c) if c.tex.size() == size => { + c.tex.set(img, TextureOptions::LINEAR); + c.revision = revision; + c.preview_key = preview_key; + c.key = key; + c.factor = factor; + c.valid = true; + if let Some(pixels) = fresh.take() { + c.source = Some(SampledComposite { revision, content, preview_key, factor, pixels }); + } + } + _ => { + let tex = ctx.load_texture(format!("channel-view-{id}"), img, TextureOptions::LINEAR); + let source = fresh.map(|pixels| SampledComposite { revision, content, preview_key, factor, pixels }); + app.channel_views.insert(id, Cache { revision, key, preview_key, factor, valid: true, tex, source }); + } + } + if new_source { + for (other_id, c) in &mut app.channel_views { + if *other_id != id { + c.source = None; + } + } + } + app.channel_views.get(&id).map(|c| c.tex.id()) +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/canvas/channel_view/tests.rs b/crates/ui-egui/src/canvas/channel_view/tests.rs new file mode 100644 index 0000000000..d8581ebbbb --- /dev/null +++ b/crates/ui-egui/src/canvas/channel_view/tests.rs @@ -0,0 +1,351 @@ +use super::*; +use photocraft_engine::Session; +use photocraft_engine::channel_cmds::ChannelTarget; +use serde_json::json; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 4})).unwrap(); + s +} + +#[test] +fn composite_bands_keep_the_downsample_grid() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 41, "height": 700})).unwrap(); + s.execute("edit.fill", json!({"color": "#398db2"})).unwrap(); + let doc = &s.active().unwrap().doc; + let rect = doc.bounds(); + let full = photocraft_compose::render(doc, rect); + let full_ref = &full; + for factor in [1, 2, 3, 5] { + let expected: Vec<_> = (0..rect.height()) + .step_by(factor as usize) + .flat_map(|y| { + (0..rect.width()).step_by(factor as usize).map(move |x| { + let p = full_ref.get(rect.x0 + x as i32, rect.y0 + y as i32); + let a = p[3].clamp(0.0, 1.0); + [p[0] * a + 1.0 - a, p[1] * a + 1.0 - a, p[2] * a + 1.0 - a, 1.0] + }) + }) + .collect(); + assert_eq!(composite(doc, rect, factor), expected, "factor {factor}"); + } +} + +#[test] +fn channel_eyes_reuse_composite_until_pixels_change() { + let mut app = PhotocraftApp::new(Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 64, "height": 32})).unwrap(); + app.run("edit.fill", json!({"color": "#4080c0"})).unwrap(); + app.sync_views(); + let ctx = egui::Context::default(); + app.run("channel.setVisible", json!({"channel": "red", "visible": false})).unwrap(); + assert!(ensure(&mut app, &ctx, 0).is_some()); + let id = app.session.active().unwrap().doc.id.0; + let first = app.channel_views.get_mut(&id).unwrap().source.as_mut().unwrap(); + let original_sample = first.pixels[0]; + // Mark the cache: a recomposite overwrites it, while a freed buffer's address can come back. + first.pixels[0] = [0.0, 1.0, 0.0, 1.0]; + + app.run("channel.setVisible", json!({"channel": "green", "visible": false})).unwrap(); + assert!(ensure(&mut app, &ctx, 0).is_some()); + let reused = app.channel_views.get(&id).unwrap().source.as_ref().unwrap(); + assert_eq!(reused.pixels[0], [0.0, 1.0, 0.0, 1.0], "visibility does not recompose the pixels"); + + app.run("edit.fill", json!({"color": "#e02010"})).unwrap(); + assert!(ensure(&mut app, &ctx, 0).is_some()); + // A partial damage upload discards the source; a full redraw may replace it. + // In either case, cached samples must never refer to the pre-edit pixels. + if let Some(source) = app.channel_views.get(&id).unwrap().source.as_ref() { + assert_ne!(source.pixels[0], original_sample, "a full redraw replaces stale pixels"); + } + app.run("channel.setVisible", json!({"channel": "red", "visible": true})).unwrap(); + assert!(ensure(&mut app, &ctx, 0).is_some()); + let refreshed = app.channel_views.get(&id).unwrap().source.as_ref().unwrap(); + let st = app.session.active().unwrap(); + assert_eq!(refreshed.revision, st.revision); + assert_ne!(refreshed.pixels[0], original_sample, "new pixels must be recomposited"); + let expected = render(&st.doc, &st.channel_view, st.doc.bounds(), 1, Look::default(), st.active_layer).unwrap(); + let mut unused = None; + let actual = render_with_source( + &st.doc, + &st.channel_view, + st.doc.bounds(), + 1, + Look::default(), + st.active_layer, + CompositeSource { cached: Some(&refreshed.pixels), fresh: &mut unused }, + ) + .unwrap(); + assert_eq!(actual, expected, "reused pixels must preserve channel colours"); + assert!(unused.is_none(), "reuse must not create a second composite"); +} + +#[test] +fn plain_composite_draws_nothing() { + let s = session(); + let st = s.active().unwrap(); + assert!(render(&st.doc, &st.channel_view, st.doc.bounds(), 1, Look::default(), st.active_layer).is_none()); +} + +#[test] +fn quick_mask_overlay_is_red_over_masked_areas() { + let mut s = session(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 4, "height": 4})).unwrap(); + s.execute("select.editInQuickMaskMode", json!({})).unwrap(); + let st = s.active().unwrap(); + let px = render(&st.doc, &st.channel_view, st.doc.bounds(), 1, Look::default(), st.active_layer).unwrap(); + assert_eq!(px[0], Color32::TRANSPARENT, "selected: no overlay"); + assert_eq!(px[6], Color32::from_rgba_premultiplied(128, 0, 0, 128), "masked: 50% red"); +} + +#[test] +fn quick_mask_without_selection_shows_no_overlay_in_either_mode() { + // #2743: nothing selected is a colourless mask, whichever way the colour reads. + for (before, after) in [(None, Some("selected")), (Some("selected"), None), (Some("selected"), Some("masked"))] { + let mut s = session(); + if let Some(i) = before { + s.execute("channel.options", json!({"channel": "quickMask", "indicates": i})).unwrap(); + } + s.execute("select.editInQuickMaskMode", json!({})).unwrap(); + let st = s.active().unwrap(); + let px = render(&st.doc, &st.channel_view, st.doc.bounds(), 1, Look::default(), st.active_layer).unwrap(); + assert!(px.iter().all(|p| *p == Color32::TRANSPARENT), "{before:?}"); + if let Some(i) = after { + s.execute("channel.options", json!({"channel": "quickMask", "indicates": i})).unwrap(); + let st = s.active().unwrap(); + let px = render(&st.doc, &st.channel_view, st.doc.bounds(), 1, Look::default(), st.active_layer).unwrap(); + assert!(px.iter().all(|p| *p == Color32::TRANSPARENT), "{before:?} → {i}"); + } + } + // Selected Areas with Select All: the whole canvas is coloured. + let mut s = session(); + s.execute("channel.options", json!({"channel": "quickMask", "indicates": "selected"})).unwrap(); + s.execute("select.all", json!({})).unwrap(); + s.execute("select.editInQuickMaskMode", json!({})).unwrap(); + let st = s.active().unwrap(); + let px = render(&st.doc, &st.channel_view, st.doc.bounds(), 1, Look::default(), st.active_layer).unwrap(); + assert!(px.iter().all(|p| *p == Color32::from_rgba_premultiplied(128, 0, 0, 128))); +} + +#[test] +fn layer_mask_views_and_damage_on_the_downsampled_grid() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 37, "height": 21})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap(); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + s.execute("paint.gradient", json!({"from": [0, 0], "to": [37, 0], "colors": ["#000000", "#ffffff"], "target": "mask"})).unwrap(); + s.execute("view.layerMask", json!({"mode": "gray"})).unwrap(); + let st = s.active().unwrap(); + let b = st.doc.bounds(); + let full = render(&st.doc, &st.channel_view, b, 1, Look::default(), st.active_layer).unwrap(); + assert!(full[0].r() < 10 && full[36].r() > 245 && full[0].a() == 255, "opaque grayscale ramp"); + // A sub-rect starting on the factor grid matches the same pixels of the full render. + for f in [1u32, 2, 3] { + let all = render(&st.doc, &st.channel_view, b, f, Look::default(), st.active_layer).unwrap(); + let w = b.width().div_ceil(f) as usize; + let r = Rect::new(3 * f as i32, 2 * f as i32, 30, 19); + let part = render(&st.doc, &st.channel_view, r, f, Look::default(), st.active_layer).unwrap(); + let pw = r.width().div_ceil(f) as usize; + for (i, p) in part.iter().enumerate() { + assert_eq!(*p, all[(i / pw + 2) * w + i % pw + 3], "factor {f}, pixel {i}"); + } + } + s.execute("view.layerMask", json!({"mode": "overlay"})).unwrap(); + let st = s.active().unwrap(); + let px = render(&st.doc, &st.channel_view, b, 1, Look::default(), st.active_layer).unwrap(); + assert!(px[0].r() >= 124 && px[0].g() == 0 && px[0].a() >= 124, "about 50% red over the hidden end: {:?}", px[0]); + assert!(px[36].a() <= 4, "next to nothing over the revealed end: {:?}", px[36]); +} + +#[test] +fn layer_mask_views_show_the_feathered_mask() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 37, "height": 21})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + s.execute("paint.gradient", json!({"from": [0, 0], "to": [37, 0], "colors": ["#000000", "#ffffff"], "target": "mask"})).unwrap(); + s.execute("layer.layerMask.edit", json!({"feather": 4})).unwrap(); + s.execute("view.layerMask", json!({"mode": "gray"})).unwrap(); + + let st = s.active().unwrap(); + let bounds = st.doc.bounds(); + let layer = st.doc.layer(st.active_layer.unwrap()).unwrap(); + let raw = layer.mask.as_ref().unwrap().surface.sample_channel(0, 0, 0); + let effective = photocraft_compose::masks::combined_mask(layer, bounds).unwrap(); + let softened = effective.sample_channel(0, 0, 0); + assert!((softened - raw).abs() > 0.01, "the fixture has a visible feather at its edge"); + + let gray = render(&st.doc, &st.channel_view, bounds, 1, Look::default(), st.active_layer).unwrap(); + assert_eq!(gray[0], Color32::from_gray(q(softened)), "gray view uses the compositor's feathered mask"); + + s.execute("view.layerMask", json!({"mode": "overlay"})).unwrap(); + let st = s.active().unwrap(); + let overlay = render(&st.doc, &st.channel_view, bounds, 1, Look::default(), st.active_layer).unwrap(); + let alpha = 0.5 * (1.0 - softened); + let red = AlphaChannel::DEFAULT_COLOR.to_rgb(); + assert_eq!(overlay[0], Color32::from_rgba_premultiplied(q(red[0] * alpha), q(red[1] * alpha), q(red[2] * alpha), q(alpha))); +} + +/// Layer Mask Display Options: the rubylith takes their colour and opacity, alone over the +/// composite and with a colour channel hidden. +#[test] +fn layer_mask_overlay_takes_its_display_options() { + let mut s = session(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap(); + s.execute("layer.layerMask.hideAll", json!({})).unwrap(); + s.execute("view.layerMask", json!({"mode": "overlay"})).unwrap(); + let green = Look { mask_rgb: [0.0, 1.0, 0.0], mask_opacity: 0.25, ..Look::default() }; + let st = s.active().unwrap(); + let b = st.doc.bounds(); + assert_eq!(render(&st.doc, &st.channel_view, b, 1, Look::default(), st.active_layer).unwrap()[0], Color32::from_rgba_premultiplied(128, 0, 0, 128)); + assert_eq!(render(&st.doc, &st.channel_view, b, 1, green, st.active_layer).unwrap()[0], Color32::from_rgba_premultiplied(0, 64, 0, 64)); + // Red hidden: the white picture shows cyan, then green at 25 % over it. + s.execute("channel.setVisible", json!({"channel": "red", "visible": false})).unwrap(); + let st = s.active().unwrap(); + assert_eq!(render(&st.doc, &st.channel_view, b, 1, green, st.active_layer).unwrap()[0], Color32::from_rgb(0, 255, 191)); +} + +/// `cargo test --release -p photocraft-ui-egui --lib mask_view_switch_24mp -- --ignored --nocapture` +#[test] +#[ignore = "benchmark"] +fn mask_view_switch_24mp() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 6000, "height": 4000})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("edit.fill", json!({"color": "#d0402b"})).unwrap(); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + s.execute("paint.gradient", json!({"from": [0, 0], "to": [6000, 0], "colors": ["#000000", "#ffffff"], "target": "mask"})).unwrap(); + let factor = 6000u32.div_ceil(MAX_SIDE); + for mode in ["gray", "overlay"] { + s.execute("view.layerMask", json!({"mode": mode})).unwrap(); + let st = s.active().unwrap(); + let mut best = f64::MAX; + for _ in 0..8 { + let t = std::time::Instant::now(); + let px = render(&st.doc, &st.channel_view, st.doc.bounds(), factor, Look::default(), st.active_layer).unwrap(); + let img = egui::ColorImage::new([3000, 2000], px); + std::hint::black_box(img); + best = best.min(t.elapsed().as_secs_f64() * 1000.0); + } + println!("24 MP mask view {mode}: {best:.1} ms (render at 1/{factor})"); + } +} + +/// Interface ▸ Show Channels in Color (#2385): a solo RGB / CMYK channel tints the canvas +/// instead of staying gray, like the panel thumbnails wired in #1986. +#[test] +fn show_channels_in_color_tints_the_canvas() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 4, "height": 4, "mode": "rgb"})).unwrap(); + s.execute("edit.fill", json!({"color": "#4080c0"})).unwrap(); + s.execute("channel.target", json!({"channel": "green"})).unwrap(); + let st = s.active().unwrap(); + let b = st.doc.bounds(); + assert_eq!(render(&st.doc, &st.channel_view, b, 1, Look::default(), st.active_layer).unwrap()[0], Color32::from_gray(128)); + assert_eq!(render(&st.doc, &st.channel_view, b, 1, Look { in_color: true, ..Look::default() }, st.active_layer).unwrap()[0], Color32::from_rgb(0, 128, 0)); + + let mut s = Session::new(); + s.execute("file.new", json!({"width": 4, "height": 4, "mode": "cmyk"})).unwrap(); + s.execute("edit.fill", json!({"color": "#4080c0"})).unwrap(); + s.execute("channel.target", json!({"channel": "cyan"})).unwrap(); + let st = s.active().unwrap(); + let px = render(&st.doc, &st.channel_view, st.doc.bounds(), 1, Look { in_color: true, ..Look::default() }, st.active_layer).unwrap()[0]; + assert!(px.r() < 100 && px.g() > 150 && px.b() > 150, "cyan ink, not gray: {px:?}"); + let gray = render(&st.doc, &st.channel_view, st.doc.bounds(), 1, Look::default(), st.active_layer).unwrap()[0]; + assert_eq!(gray.r(), gray.g(), "off stays grayscale"); +} + +/// Lab: a and b tint over a neutral Lightness; Lightness itself stays gray (Adobe's exception). +#[test] +fn show_channels_in_color_lab_lightness_stays_gray() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 4, "height": 4, "mode": "lab"})).unwrap(); + s.execute("edit.fill", json!({"color": "#4080c0"})).unwrap(); + let b = s.active().unwrap().doc.bounds(); + s.execute("channel.target", json!({"channel": {"color": 0}})).unwrap(); + let st = s.active().unwrap(); + let px = render(&st.doc, &st.channel_view, b, 1, Look { in_color: true, ..Look::default() }, st.active_layer).unwrap()[0]; + let spread = px.r().max(px.g().max(px.b())) as i32 - px.r().min(px.g().min(px.b())) as i32; + assert!(spread <= 3, "Lightness stays gray: {px:?}"); + s.execute("channel.target", json!({"channel": {"color": 1}})).unwrap(); + let st = s.active().unwrap(); + let px = render(&st.doc, &st.channel_view, b, 1, Look { in_color: true, ..Look::default() }, st.active_layer).unwrap()[0]; + assert!(px.r() != px.g() || px.g() != px.b(), "a channel is tinted, not gray: {px:?}"); +} + +/// The canvas texture cache is keyed by the preference, so toggling it rebuilds the view. +#[test] +fn ensure_honours_show_channels_in_color() { + let mut app = PhotocraftApp::new(Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + app.sync_views(); + app.run("channel.target", json!({"channel": "green"})).unwrap(); + let ctx = egui::Context::default(); + assert!(ensure(&mut app, &ctx, 0).is_some()); + let key_off = app.channel_views.values().next().unwrap().key; + app.session.execute("prefs.set", json!({"values": {"interface.showChannelsInColor": true}})).unwrap(); + assert!(ensure(&mut app, &ctx, 0).is_some()); + let key_on = app.channel_views.values().next().unwrap().key; + assert_ne!(key_off, key_on, "the preference changes the cached view key"); + // So do the Layer Mask Display Options. + app.session.execute("channel.options", json!({"channel": "mask", "color": "#00ff00", "opacity": 70})).unwrap(); + assert!(ensure(&mut app, &ctx, 0).is_some()); + assert_ne!(app.channel_views.values().next().unwrap().key, key_on, "the overlay options change the cached view key"); +} + +#[test] +fn solo_alpha_is_grayscale_and_colour_channels_split() { + let mut s = session(); + s.execute("edit.fill", json!({"color": "#ff8000"})).unwrap(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 2, "height": 4})).unwrap(); + s.execute("channel.new", json!({"fill": "selection"})).unwrap(); + let st = s.active().unwrap(); + assert_eq!(st.channel_view.target, ChannelTarget::Alpha(0)); + let px = render(&st.doc, &st.channel_view, st.doc.bounds(), 1, Look::default(), st.active_layer).unwrap(); + assert_eq!((px[0], px[5]), (Color32::WHITE, Color32::BLACK)); + // Green alone: grayscale of the green channel; with blue hidden only. + s.execute("channel.target", json!({"channel": "green"})).unwrap(); + let st = s.active().unwrap(); + let px = render(&st.doc, &st.channel_view, st.doc.bounds(), 1, Look::default(), st.active_layer).unwrap(); + assert_eq!(px[0], Color32::from_gray(128)); + s.execute("channel.target", json!({"channel": "composite"})).unwrap(); + s.execute("channel.setVisible", json!({"channel": "red", "visible": false})).unwrap(); + let st = s.active().unwrap(); + let px = render(&st.doc, &st.channel_view, st.doc.bounds(), 2, Look::default(), st.active_layer).unwrap(); + assert_eq!(px.len(), 4 * 2); + assert_eq!(px[0], Color32::from_rgb(0, 128, 0)); +} + +#[test] +fn rgb_off_shows_alpha_quick_mask_or_the_layer_mask() { + let mut s = session(); + s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + s.execute("channel.new", json!({"fill": "white"})).unwrap(); + s.execute("channel.setVisible", json!({"channel": "composite", "visible": true})).unwrap(); + s.execute("channel.setVisible", json!({"channel": "composite", "visible": false})).unwrap(); + let st = s.active().unwrap(); + let px = render(&st.doc, &st.channel_view, st.doc.bounds(), 1, Look::default(), st.active_layer).unwrap(); + assert_eq!(px[0], Color32::WHITE, "Alpha alone is the channel, not the red image"); + + let mut q = session(); + q.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + q.execute("select.editInQuickMaskMode", json!({})).unwrap(); + q.execute("channel.setVisible", json!({"channel": "composite", "visible": false})).unwrap(); + let st = q.active().unwrap(); + let px = render(&st.doc, &st.channel_view, st.doc.bounds(), 1, Look::default(), st.active_layer).unwrap(); + assert_eq!(px[0], Color32::WHITE, "Quick Mask alone is grayscale, not the red composite"); + + let mut m = session(); + m.execute("layer.new.layer", json!({})).unwrap(); + m.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + m.execute("layer.layerMask.hideAll", json!({})).unwrap(); + m.execute("channel.setVisible", json!({"channel": "composite", "visible": false})).unwrap(); + let st = m.active().unwrap(); + assert_eq!(st.channel_view.visible_colors(3), 0); + let px = render(&st.doc, &st.channel_view, st.doc.bounds(), 1, Look::default(), st.active_layer).unwrap(); + assert_eq!(px[0], Color32::BLACK, "the hidden mask reads black, not the red layer"); +} diff --git a/crates/ui-egui/src/canvas_cpu_background_tests.rs b/crates/ui-egui/src/canvas/cpu_background_tests.rs similarity index 100% rename from crates/ui-egui/src/canvas_cpu_background_tests.rs rename to crates/ui-egui/src/canvas/cpu_background_tests.rs diff --git a/crates/ui-egui/src/canvas/cursors.rs b/crates/ui-egui/src/canvas/cursors.rs new file mode 100644 index 0000000000..a7048ea3c5 --- /dev/null +++ b/crates/ui-egui/src/canvas/cursors.rs @@ -0,0 +1,209 @@ +use super::tool_input::ToolEvent; +use super::view_xform::ViewXform; +use super::*; + +/// Windows' crosshair cursor inverts the pixels under it, so over mid-grey (the pasteboard, many +/// photos) it vanishes (#737), and the Linux themes' and macOS's differ. Use the same black-and-white +/// bitmap on every desktop platform, carried by the OS so its movement does not wait for the canvas +/// to render (#1343). +pub(super) fn visible_crosshair(icon: egui::CursorIcon, painter: &egui::Painter, p: Pos2, draw: bool) -> egui::CursorIcon { + if !draw || icon != egui::CursorIcon::Crosshair { + return icon; + } + crate::tool_cursor::crosshair(painter, p, 8.0, 2.0) +} + +/// The Pencil's cursor at `doc` (document pixels): the whole-pixel square its dab fills +/// (`paint::grid_square`), in screen points with its edges on physical pixels (`ppp` = pixels +/// per point), so it lines up with the pixel grid at any zoom. +pub(crate) fn pencil_cursor_rect(xf: &ViewXform, doc: [f64; 2], size: f32, ppp: f32) -> Rect { + let [x0, y0, x1, y1] = photocraft_engine::paint::grid_square(doc[0], doc[1], size); + let r = Rect::from_two_pos(xf.to_screen(x0 as f32, y0 as f32), xf.to_screen(x1 as f32, y1 as f32)); + let ppp = if ppp.is_finite() && ppp > 0.0 { ppp } else { 1.0 }; + let snap = |v: f32| (v * ppp).round() / ppp; + Rect::from_min_max(pos2(snap(r.min.x), snap(r.min.y)), pos2(snap(r.max.x), snap(r.max.y))) +} + +/// Whether an aliased (Pencil) dab of `size` pixels is round rather than its whole +/// [`pencil_cursor_rect`] square. The dab fills the pixels whose centres lie within its radius of +/// the grid centre (`paint::grid_center`), so up to 3 px the corner pixels are in and the dab is +/// a square; from 4 px on they fall outside and it is a disc (#2662). +pub(crate) fn pencil_tip_is_round(size: f32) -> bool { + let n = if size.is_finite() { size.round().clamp(1.0, 100_000.0) } else { 1.0 }; + let h = n / 2.0; + (h - 0.5) * std::f32::consts::SQRT_2 > h +} + +/// Whether a brush-tip circle draws its centre mark. +/// Clone Stamp and Healing Brush stay an empty circle until Option is held, the source-point +/// cursor. Other brushes follow Preferences › Cursors › Show Crosshair in Brush Tip, as in +/// Photoshop; the Background Eraser always shows its sampling hotspot. +pub(super) fn brush_tip_centre(tool: Tool, option: bool, show_crosshair: bool) -> bool { + if tool == Tool::QuickSelection { + return false; + } + if matches!(tool, Tool::CloneStamp | Tool::Healing) { + return option || show_crosshair; + } + show_crosshair || tool == Tool::BackgroundEraser +} + +/// The display colour of an RGB triple (0..1 per channel) as an egui colour. +fn display_color(c: [f32; 3]) -> Color32 { + let b = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; + Color32::from_rgb(b(c[0]), b(c[1]), b(c[2])) +} + +/// The Eyedropper ring's two colours at document point (x, y): the colour under the pointer +/// (what a click would pick) and the current foreground, or `None` where there is no colour +/// to sample (#213). +pub(crate) fn eyedropper_ring_colors(app: &mut PhotocraftApp, x: f64, y: f64) -> Option<(Color32, Color32)> { + let new = eyedropper_color(app, x, y)?; + let fg = app.session.tools.foreground; + Some((display_color(new), display_color([fg[0], fg[1], fg[2]]))) +} + +/// Draw the Eyedropper's comparison ring at `p`: an opaque neutral grey band around the +/// pointer with the sampled colour on its upper half and the current one on the lower, +/// framed by thin dark and light hairlines so every edge reads on any image, and the +/// pipette at its centre marking the sampled pixel (#213, #6973). Like Photoshop it shows +/// only while the mouse button is held (`held`): hovering shows the plain pipette and +/// samples nothing. `None` when not held, there is nothing to sample, or the Precise-cursor +/// preference wants the plain crosshair. +pub(super) fn eyedropper_ring(app: &mut PhotocraftApp, painter: &egui::Painter, xf: &ViewXform, p: Pos2, held: bool) -> Option { + // The options bar's Show Sampling Ring turns it off (#1649). + if !held || !app.ui.tool_options.eyedropper_ring || app.session.prefs().cursors.other == photocraft_engine::prefs::OtherCursor::Precise { + return None; + } + let [x, y] = xf.to_doc(p); + let (new, current) = eyedropper_ring_colors(app, x, y)?; + // Photoshop's proportions (#6973): a ring about 210 pt across whose opaque grey outer + // band and coloured inner band are each about 17 pt wide, over a transparent centre. + // In points, so the ring scales with Interface › UI Scale like the rest of the cursor. + let (r_out, band) = (105.0_f32, 17.0_f32); + let r_in = r_out - 2.0 * band; + // Screen y grows down, so PI..TAU is the upper half (the sampled colour) and 0..PI the + // lower (the current one); the halves meet at 3 and 9 o'clock, as in Photoshop. + use std::f32::consts::{PI, TAU}; + let upper: Vec = (0..=48) + .map(|i| { + let a = PI + (TAU - PI) * i as f32 / 48.0; + p + vec2(a.cos(), a.sin()) * (r_in + band / 2.0) + }) + .collect(); + // `circle_stroke` paints its stroke outside the radius, `Shape::line` centres it. + painter.circle_stroke(p, r_in, Stroke::new(band, current)); + painter.add(egui::Shape::line(upper, Stroke::new(band, new))); + painter.circle_stroke(p, r_in + band, Stroke::new(band, RING_GREY)); + // Thin dark and light hairlines on the ring's two edges, one physical pixel wide, so it + // reads on any colour including a flat mid-grey that matches the band itself (#6973). + let px = 1.0 / painter.ctx().pixels_per_point().max(1.0); + let (dark, light) = (Stroke::new(px, Color32::from_black_alpha(160)), Stroke::new(px, Color32::from_white_alpha(160))); + painter.circle_stroke(p, r_out, dark); + painter.circle_stroke(p, r_out + px, light); + painter.circle_stroke(p, r_in - px, dark); + painter.circle_stroke(p, r_in - 2.0 * px, light); + // Photoshop keeps the pipette visible at the centre, its tip on the sampled pixel; a + // ring this size says nothing about where it samples without it. + Some(pipette_cursor(painter.ctx(), p)) +} + +/// The Eyedropper ring's opaque neutral grey, as Photoshop measures it (#6973). +const RING_GREY: Color32 = Color32::from_gray(127); + +/// Tools on which holding ⌥ (Alt) switches to the Eyedropper: a click or drag sets the +/// foreground colour, as with the Eyedropper itself (#417). +pub(crate) fn alt_samples(tool: Tool, mods: egui::Modifiers) -> bool { + // Control+Alt is the brush-resize drag (`brush_resize`), not sampling. + mods.alt && !mods.ctrl && matches!(tool, Tool::Brush | Tool::Pencil | Tool::Gradient | Tool::PaintBucket) +} + +/// Preferences › Cursors › Other Cursors asks for the precise crosshair, or Caps Lock swaps the +/// standard cursor for it (and back), as in Photoshop (#4639). +pub(super) fn precise_other_cursor(app: &PhotocraftApp) -> bool { + (app.session.prefs().cursors.other == photocraft_engine::prefs::OtherCursor::Precise) != app.caps_lock +} + +/// A pen tool's standard cursor: its toolbar icon with the nib (the Convert Point tool: the +/// anchor) on `p`. Draws it at `p` and returns the OS cursor to set (hidden). +pub(crate) fn pen_cursor(ctx: &egui::Context, tool: Tool, p: Pos2) -> egui::CursorIcon { + // Where each icon's point is in its 24-unit box: the full-size pen's nib at (2.3, 2.3); the + // Freeform and Curvature pens draw it at 0.68 × from (7, 7); Convert Point's apex anchor. + let hot = match tool { + Tool::FreeformPen | Tool::CurvaturePen => vec2(8.56, 8.56), + Tool::ConvertPoint => vec2(12.0, 7.0), + _ => vec2(2.3, 2.3), + }; + crate::icons::cursor(ctx, crate::icons::tool_icon(tool), p, hot / 24.0, 22.0); + egui::CursorIcon::None +} + +/// The sampling cursor: a pipette whose tip is the sampled pixel. Draws it at `p` and returns the +/// OS cursor to set (hidden). +pub(crate) fn pipette_cursor(ctx: &egui::Context, p: Pos2) -> egui::CursorIcon { + // The tip of the icon's pipette is at (2, 22) of its 24-unit box. + crate::icons::cursor(ctx, "pipette", p, vec2(2.0, 22.0) / 24.0, 20.0); + egui::CursorIcon::None +} + +/// The Paint Bucket's cursor: a bucket whose pouring corner is the filled pixel. Draws it at `p` +/// and returns the OS cursor to set (hidden). +pub(crate) fn paint_bucket_cursor(ctx: &egui::Context, p: Pos2) -> egui::CursorIcon { + // The left corner of the icon's bucket is at (2, 12) of its 24-unit box. + crate::icons::cursor(ctx, "paint-bucket", p, vec2(2.0, 12.0) / 24.0, 22.0); + egui::CursorIcon::None +} + +/// Decided when the press starts, so ⌥ pressed or released mid-stroke never switches between +/// painting and sampling. +pub(super) fn alt_eyedropper(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> bool { + if matches!(ev, ToolEvent::Down { .. }) { + let physical_right = app.services.right_button_down.as_ref().is_some_and(|f| f()); + app.alt_sampling = !physical_right && alt_samples(app.active_tool(), mods); + } + if !app.alt_sampling { + return false; + } + match ev { + // Without ⌥: the sample sets the foreground colour, whatever the Eyedropper would do. + ToolEvent::Down { x, y, .. } | ToolEvent::Move { x, y, .. } => sample_eyedropper(app, x, y, egui::Modifiers::NONE), + ToolEvent::Up { .. } => app.alt_sampling = false, + } + true +} + +pub(super) fn sample_eyedropper(app: &mut PhotocraftApp, x: f64, y: f64, mods: egui::Modifiers) { + if let Some([r, g, b]) = eyedropper_color(app, x, y) { + let key = if mods.alt { "background" } else { "foreground" }; + let _ = app.run("tools.setColors", json!({ key: [r, g, b, 1.0] })); + } +} + +/// The colour at document point (x, y) with the Eyedropper's Sample Size (the composite pixel, +/// or the average of the square around it) from the layers `sample_layer` names (`document.sampleColor`). +/// `None` off the image or over transparency. +fn sample_color(app: &mut PhotocraftApp, x: f64, y: f64, sample_layer: &str) -> Option<[f32; 3]> { + if !(x.is_finite() && y.is_finite()) { + return None; + } + let size = app.ui.tool_options.eyedropper_size; + let v = app.run("document.sampleColor", json!({"x": x, "y": y, "size": size, "sampleLayer": sample_layer})).ok()?; + match serde_json::from_value::>(v).ok()?[..] { + [r, g, b, a] if a > 0.0 => Some([r, g, b]), + _ => None, + } +} + +/// What the Eyedropper tool (and a painting tool's ⌥-click) picks at document point (x, y): its +/// options bar's Sample Size and Sample (#1649). +pub(crate) fn eyedropper_color(app: &mut PhotocraftApp, x: f64, y: f64) -> Option<[f32; 3]> { + let layers = app.ui.tool_options.eyedropper_sample.clone(); + sample_color(app, x, y, &layers) +} + +/// The active document's composite colour at document point (x, y), averaged over the +/// Eyedropper's Sample Size as Photoshop's dialog eyedroppers (Curves, Color Picker) do. +/// `None` off the image or over transparency. +pub(crate) fn composite_color(app: &mut PhotocraftApp, x: f64, y: f64) -> Option<[f32; 3]> { + sample_color(app, x, y, "all") +} diff --git a/crates/ui-egui/src/canvas/display.rs b/crates/ui-egui/src/canvas/display.rs new file mode 100644 index 0000000000..1cfae7a46d --- /dev/null +++ b/crates/ui-egui/src/canvas/display.rs @@ -0,0 +1,300 @@ +use super::strokes::live_stroke; +use super::*; + +pub(super) fn checker(app: &mut PhotocraftApp, ctx: &egui::Context) -> egui::TextureId { + // Preferences › Transparency & Gamut colours (the texture is rebuilt when they change). + let [ca, cb] = app.session.prefs().transparency_and_gamut.colors(); + if app.prefs_rt.checker_key != Some([ca, cb]) { + app.prefs_rt.checker_key = Some([ca, cb]); + app.checker = None; + } + app.checker + .get_or_insert_with(|| { + let (a, b) = (Color32::from_rgb(ca[0], ca[1], ca[2]), Color32::from_rgb(cb[0], cb[1], cb[2])); + let img = egui::ColorImage::new([2, 2], vec![a, b, b, a]); + let opts = TextureOptions { + magnification: egui::TextureFilter::Nearest, + minification: egui::TextureFilter::Nearest, + wrap_mode: egui::TextureWrapMode::Repeat, + mipmap_mode: None, + }; + ctx.load_texture("checker", img, opts) + }) + .id() +} + +fn buffer_to_image(buf: &photocraft_compose::Buffer) -> egui::ColorImage { + // `buf.to_rgba8()` then `color_image`, fused: one parallel pass, no intermediate image. + let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; + let mut pixels = vec![egui::Color32::TRANSPARENT; buf.px.len()]; + let convert = |out: &mut [egui::Color32], src: &[[f32; 4]]| { + for (o, p) in out.iter_mut().zip(src) { + *o = egui::Color32::from_rgba_unmultiplied(q(p[0]), q(p[1]), q(p[2]), q(p[3])); + } + }; + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + pixels.par_chunks_mut(16 * 1024).zip(buf.px.par_chunks(16 * 1024)).for_each(|(o, s)| convert(o, s)); + } + #[cfg(target_arch = "wasm32")] + convert(&mut pixels, &buf.px); + egui::ColorImage::new([buf.rect.width() as usize, buf.rect.height() as usize], pixels) +} + +/// `img` as an egui image: `ColorImage::from_rgba_unmultiplied`, in parallel off wasm. egui's own +/// conversion runs on one thread and took 37 ms of a 24 MP canvas or preview update, three times +/// the quantize before it. +fn color_image(img: &photocraft_raster::Rgba8Image) -> egui::ColorImage { + let size = [img.width as usize, img.height as usize]; + let src = img.pixels.as_chunks::<4>().0; + let mut pixels = vec![egui::Color32::TRANSPARENT; src.len()]; + let convert = |out: &mut [egui::Color32], src: &[[u8; 4]]| { + for (o, &[r, g, b, a]) in out.iter_mut().zip(src) { + *o = egui::Color32::from_rgba_unmultiplied(r, g, b, a); + } + }; + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + pixels.par_chunks_mut(16 * 1024).zip(src.par_chunks(16 * 1024)).for_each(|(o, s)| convert(o, s)); + } + #[cfg(target_arch = "wasm32")] + convert(&mut pixels, src); + egui::ColorImage::new(size, pixels) +} + +/// A composite as monitor pixels: document profile → monitor profile (nothing to do in the +/// common sRGB-on-sRGB case). +pub(crate) fn display_image(display: Option<&photocraft_engine::display_color::CanvasDisplay>, buf: &photocraft_compose::Buffer) -> egui::ColorImage { + match display { + Some(d) if !d.is_identity() => color_image(&d.to_rgba8(buf)), + _ => buffer_to_image(buf), + } +} + +/// The canvas display of `doc` on `display` (`None`: the main window's) and a key that changes +/// with it (folded into the canvas caches' preview keys, so a monitor or profile change +/// re-renders). +pub(crate) fn canvas_display( + app: &PhotocraftApp, + doc: &Document, + display: Option, +) -> (Option>, u64) { + match app.session.color.canvas_display_for(doc, display.or(app.session.color.main_display)) { + Ok(d) => { + let k = d.key; + (Some(d), k) + } + Err(_) => (None, 0), + } +} + +/// [`canvas_display`]'s key for the GPU canvas texture: what the texture stores, the same on +/// every display (the display LUT holds the monitor profile). +pub(super) fn texture_key(display: Option<&photocraft_engine::display_color::CanvasDisplay>) -> u64 { + display.map_or(0, |d| d.texture_key) +} + +/// `app.canvases` key: CPU canvas textures are per document and display (they hold monitor +/// values); the GPU canvas state uses [`GPU_OUTPUT`]. +pub(crate) fn cache_key(doc: photocraft_doc::DocId, display: Option) -> (photocraft_doc::DocId, u32) { + (doc, display.unwrap_or(0)) +} + +/// `app.canvases` output of the GPU canvas state (one texture per document for all displays). +pub(crate) const GPU_OUTPUT: u32 = u32::MAX; + +/// The document to render: the committed one, or a clone with the live adjustment preview applied. +pub(crate) fn display_doc(app: &mut PhotocraftApp, idx: usize) -> (std::sync::Arc, u64) { + if let Some(shown) = crate::type_panels_ui::color_picker::display_doc(app, idx) { + return shown; + } + if let Some(shown) = crate::solid_fill_ui::display_doc(app, idx) { + return shown; + } + if let Some(shown) = crate::pattern_fill_ui::display_doc(app, idx) { + return shown; + } + if let Some(shown) = crate::shape_fill_ui::display_doc(app, idx) { + return shown; + } + if let Some(shown) = crate::type_transform::display_doc(app, idx) { + return shown; + } + if let Some(shown) = crate::type_font_preview::display_doc(app, idx) { + return shown; + } + // Vanishing Point's strokes over the document as it is now (the Layers panel may have + // changed it since the options bar synced them this frame). + crate::vp_ui::sync_preview(app); + // Puppet / Perspective Warp previews hide the layer they draw on a mesh. + if let Some(shown) = crate::distort_ui::display_doc(app, idx) { + return shown; + } + // Image › Adjustments dialog: a temporary adjustment layer clipped to the target. + if let Some(shown) = crate::adjust_preview::display_doc(app, idx) { + return shown; + } + // Gradient tool (live) drag, or a stop dragged in the Properties panel. + if let Some(shown) = crate::gradient_ui::display_doc(app, idx) { + return shown; + } + // Move tool drag: the moving layers at the pointer. + if let Some(shown) = crate::move_ui::display_doc(app, idx) { + return shown; + } + // Patch Tool drag: the selection healed from where the pointer is. + if let Some(shown) = crate::patch_preview::display_doc(app, idx) { + return shown; + } + // Content-Aware Move drag or box: the result, once computed in the background. It comes + // before the reorder preview, which is built from the session document and would drop it. + if let Some(shown) = crate::cam_preview::display_doc(app, idx) { + return shown; + } + // Live Layers-panel reorder previews the actual composite before mouse release. + if let Some(shown) = crate::layers_panel_ui::display_reorder(app, idx) { + return shown; + } + // A blend mode hovered in the Layers panel. + if let Some(shown) = crate::blend_preview::display_doc(app, idx) { + return shown; + } + crate::transform_tool::follow_edits(app); + let st = &app.session.documents()[idx]; + if let Some(l) = live_stroke(app, idx) { + return (l.stroke.doc().clone(), l.display_key()); + } + if let (Some(t), Some(pv)) = (&app.ui.transform, &app.transform_preview) + && app.session.active_index() == Some(idx) + && pv.doc.id == st.doc.id + && st.doc.layer(photocraft_doc::LayerId(t.layer)).is_some() + { + return (pv.doc.clone(), (1 << 40) + pv.session); + } + // Layer Style dialog: show its effects live (Cancel just drops the preview). + let style = app.ui.dialogs.iter().find(|d| d.kind == crate::state::DialogKind::LayerStyle); + // The Preview checkbox off shows the document as it was when the dialog opened; + // edits still land in the dialog state and OK applies them whatever it says. + let preview_on = style.and_then(|d| d.fields.get("preview")).and_then(serde_json::Value::as_bool).unwrap_or(true); + if style.is_none() || !preview_on { + app.style_preview = None; + } + if let Some(d) = style.filter(|_| preview_on) + && app.session.active_index() == Some(idx) + { + let fields = crate::layer_style::color_picker::preview_fields(app, d.id, &d.fields); + let key = (crate::layer_style::preview_hash(&fields) ^ st.revision.wrapping_mul(0x9e37_79b9_7f4a_7c15)) | 1 << 63; + if app.style_preview.as_ref().map(|p| p.0) != Some(key) { + let shown = crate::layer_style::preview_document(&st.doc, &app.session.patterns, &fields).map(std::sync::Arc::new); + if let Err(error) = &shown { + log::warn!("Layer Style preview: {error}"); + } + app.style_preview = Some((key, shown)); + } + if let Some((_, Ok(doc))) = &app.style_preview { + return (doc.clone(), key); + } + } + let revision = st.revision; + let snapshot = st.doc.clone(); + if let Some((layer, params)) = app.live_adjust.clone() + && let Some(l) = snapshot.layer(layer) + && let LayerContent::Adjustment(a) = &l.content + { + let key = crate::adjust_preview::live_key(app, &snapshot, revision, layer, ¶ms); + let shown = memo_display(app, &snapshot, key, || { + let kind = photocraft_engine::commands::adjustment_kind(a); + let preview = photocraft_engine::adjust_params::from_params(kind, ¶ms, Some(a), snapshot.mode).unwrap_or_else(|_| a.clone()); + let mut doc = (*snapshot).clone(); + if let Some(lm) = doc.layer_mut(layer) { + lm.content = LayerContent::Adjustment(preview); + } + Some(doc) + }); + if let Some(doc) = shown { + return (doc, key); + } + } + // Duotone documents display through their inks. + if let Some(shown) = memo_display(app, &snapshot, 1 << 41, || photocraft_engine::mode_cmds::display_document(&snapshot)) { + return (shown, 1 << 41); + } + (snapshot, 0) +} + +/// `display_doc`'s live-adjust and Duotone documents, built once per document snapshot and key +/// rather than on each of its 3–4 calls a frame (#4527): each build clones the whole document. +fn memo_display( + app: &mut PhotocraftApp, + snapshot: &std::sync::Arc, + key: u64, + build: impl FnOnce() -> Option, +) -> Option> { + let id = snapshot.id; + if let Some((doc, k, shown)) = app.display_memo.get(&id) + && *k == key + && doc.ptr_eq(&std::sync::Arc::downgrade(snapshot)) + { + return Some(shown.clone()); + } + let Some(shown) = build().map(std::sync::Arc::new) else { + app.display_memo.remove(&id); + return None; + }; + // Entries of closed documents go when another is stored. + app.display_memo.retain(|_, (doc, _, _)| doc.strong_count() > 0); + app.display_memo.insert(id, (std::sync::Arc::downgrade(snapshot), key, shown.clone())); + Some(shown) +} + +/// Lattice size of the canvas display LUT (colour management, Proof Colors, Gamut Warning). +const DISPLAY_LUT: usize = 33; + +/// Keep the GPU display LUT under `key` (the document's texture or a preview of it) in step with +/// `doc`'s colour management: document → monitor profile and View › Proof Colors / Gamut +/// Warning (the 32-bit preview is applied by the canvas shader, see [`hdr_preview`]). Returns the canvas `display` mode (0 none — the identity, e.g. sRGB on +/// an sRGB monitor —, 1 LUT, 2 LUT + gamut warning, 3 matrix/shaper). +pub(super) fn sync_display_lut(app: &mut PhotocraftApp, doc: &photocraft_doc::Document, key: u64, display: Option) -> u8 { + let Some(gpu) = app.gpu.clone() else { return 0 }; + let output = display.unwrap_or(0); + // Rebuild only when anything feeding the LUT changes. + let sig = app.session.color.display_signature_for(doc, display); + if let Some((s, mode)) = gpu.display_lut_signature(key, output) + && s == sig + { + return mode; + } + // Keep the curve/matrix/curve stages separate: interpolating a finished display + // transform on a 33³ lattice crushes shadows when the monitor curve is steep near zero. + if let Ok(Some(shaper)) = app.session.color.gpu_canvas_matrix_shaper_for(doc, display) { + gpu.set_display_matrix_shaper(key, output, &shaper); + gpu.cache_display_lut_signature(key, output, sig, 3); + return 3; + } + let gamut = app.session.color.proof(doc.id).gamut_warning; + let mode = match app.session.color.gpu_canvas_lut_for(doc, DISPLAY_LUT, display) { + Ok(Some(bytes)) => { + gpu.set_display_lut(key, output, DISPLAY_LUT as u32, Some(&bytes)); + if gamut { 2 } else { 1 } + } + Ok(None) => { + gpu.set_display_lut(key, output, DISPLAY_LUT as u32, None); + 0 + } + Err(e) => { + let template = "Color management: {error}"; + app.ui.status = crate::i18n::fmt(tl!(template), &[("error", &e.to_string())]); + gpu.set_display_lut(key, output, DISPLAY_LUT as u32, None); + 0 + } + }; + gpu.cache_display_lut_signature(key, output, sig, mode); + mode +} + +/// View › 32-bit Preview Options for the GPU canvas shader: (exposure, gamma) when active. +pub(super) fn hdr_preview(app: &PhotocraftApp, doc: &photocraft_doc::Document) -> Option<[f32; 2]> { + app.session.color.hdr_preview(doc).map(|h| [h.exposure, h.gamma]) +} diff --git a/crates/ui-egui/src/canvas_display_memo_tests.rs b/crates/ui-egui/src/canvas/display_memo_tests.rs similarity index 100% rename from crates/ui-egui/src/canvas_display_memo_tests.rs rename to crates/ui-egui/src/canvas/display_memo_tests.rs diff --git a/crates/ui-egui/src/canvas/drag.rs b/crates/ui-egui/src/canvas/drag.rs new file mode 100644 index 0000000000..a58e8db11b --- /dev/null +++ b/crates/ui-egui/src/canvas/drag.rs @@ -0,0 +1,328 @@ +use super::view_xform::ViewXform; +use super::*; + +/// An in-progress pointer gesture on the canvas. +#[derive(Clone, Debug)] +pub struct Drag { + pub tool: Tool, + pub start: [f64; 2], + pub points: Vec<[f64; 3]>, + pub modifiers: egui::Modifiers, + /// A Brush/Eraser stroke that erases: the Eraser, or a right-button Brush drag with + /// Preferences › Tools › Right-click with painting tools set to Erase. + pub erase: bool, + /// A Brush or Pencil stroke in Photoshop's Clear mode (`paint_mouse::clears`, #3439): it + /// erases, sent as `"mode": "clear"` so History names the tool rather than the Eraser. + pub clear: bool, + /// ⇧ constraint of a painting stroke (stroke_constraint.rs). + pub constrain: Option, + /// Modifiers held now (updated on every pointer event of the gesture). + pub live: egui::Modifiers, + /// Which of the modifiers held at the press have been released since. + pub released: egui::Modifiers, + /// The reposition key (Space) is held: pointer moves move the whole gesture instead of + /// sizing it (marquees, lasso, shapes; `hold_keys`). + pub reposition: bool, + /// A marquee or lasso drag that started inside the selection moves it instead of drawing: + /// `Some(false)` moves the outline, `Some(true)` moves the floating piece (`select.float`), as + /// every Move-tool drag with a selection does (`move_ui::moves_selected_pixels_with`). + pub sel_move: Option, + /// The last ⇧-locked offset of a selection-tool drag of the selection (`move_mods`, #6231); + /// keeps the locked direction stable between events. The Move tool's own drags use `move_mods`. + pub sel_axis: Option<[f64; 2]>, + pub lasso: Option, +} + +impl Drag { + pub fn new(tool: Tool, start: [f64; 2], points: Vec<[f64; 3]>, modifiers: egui::Modifiers, erase: bool) -> Self { + Self { + tool, + start, + points, + modifiers, + erase, + clear: false, + constrain: None, + live: modifiers, + released: egui::Modifiers::NONE, + reposition: false, + sel_move: None, + sel_axis: None, + lasso: None, + } + } + + /// Reposition: move the start and every point so the last one lands on `to` (same size). + pub fn shift_to(&mut self, to: [f64; 2]) { + let last = self.points.last().map_or(self.start, |p| [p[0], p[1]]); + let (dx, dy) = (to[0] - last[0], to[1] - last[1]); + if !(dx.is_finite() && dy.is_finite()) { + return; + } + self.start = [self.start[0] + dx, self.start[1] + dy]; + for p in &mut self.points { + p[0] += dx; + p[1] += dy; + } + if self.points.is_empty() { + self.points.push([to[0], to[1], 1.0]); + } + } + + /// Record the modifiers of a pointer event. + pub(crate) fn track(&mut self, mods: egui::Modifiers) { + self.live = mods; + self.released.shift |= !mods.shift; + self.released.alt |= !mods.alt; + } + + /// ⇧ (square / circle) and ⌥ (from the centre) for a marquee drag. A modifier held at the press + /// picks the selection mode instead (add / subtract, #188) until it is released and pressed + /// again, as in Photoshop. + pub fn marquee_mods(&self) -> (bool, bool) { + let fresh = |now: bool, at_press: bool, released: bool| now && (!at_press || released); + (fresh(self.live.shift, self.modifiers.shift, self.released.shift), fresh(self.live.alt, self.modifiers.alt, self.released.alt)) + } +} + +/// The marquee dragged from `d.start` to `end` as two document-space corners: the options-bar +/// style (fixed ratio / fixed size), ⇧ for a square or circle, ⌥ to draw from the centre. +pub fn marquee_corners(o: &crate::state::ToolOptions, d: &Drag, end: [f64; 2]) -> ([f64; 2], [f64; 2]) { + let (shift, alt) = d.marquee_mods(); + if o.marquee_style == "fixedSize" { + // A fixed box is positioned, not sized, by the drag. Using the press plus the drag's + // sign pinned it there and flipped it by its full width/height when the pointer crossed + // the press. The preview and release both follow the current pointer instead. + let (w, h) = (f64::from(o.marquee_width).max(1.0), f64::from(o.marquee_height).max(1.0)); + let a = if alt { [end[0] - w / 2.0, end[1] - h / 2.0] } else { end }; + return (a, [a[0] + w, a[1] + h]); + } + let e = crate::chrome_ui::marquee_end(&o.marquee_style, o.marquee_width as f64, o.marquee_height as f64, shift, d.start, end); + if !alt { + return (d.start, e); + } + let (dx, dy) = (e[0] - d.start[0], e[1] - d.start[1]); + // For a sized marquee the drag is the half extent when drawing from the centre. + ([d.start[0] - dx, d.start[1] - dy], [d.start[0] + dx, d.start[1] + dy]) +} + +/// The pixel rectangle a Rectangular/Elliptical Marquee drag selects so far: shown live (ants +/// and readout) exactly as the release commits it, on whole pixel edges as in Photoshop. `None` +/// while the gesture is still a click (it never left the press point by more than a few screen +/// pixels at `zoom`, points per document pixel) or the rectangle has no area: a release then +/// deselects. A one-pixel row or column is a selection (#2391). With the Fixed Size style a +/// click places the selection, as in Photoshop. +pub(crate) fn marquee_preview_px(o: &crate::state::ToolOptions, d: &Drag, zoom: f32) -> Option<[f64; 4]> { + let fixed = o.marquee_style == "fixedSize"; + if !matches!(d.tool, Tool::RectMarquee | Tool::EllipseMarquee) || (!fixed && crate::shape_dialog::is_click(d.start, &d.points, zoom)) { + return None; + } + let last = d.points.last().map_or(d.start, |p| [p[0], p[1]]); + let (a, b) = marquee_corners(o, d, last); + let mut r = if fixed { fixed_size_px(a, b, o.marquee_width, o.marquee_height) } else { marquee_px(a, b) }; + if marquee_is_square(o, d) { + r = square_px(r, d.start, last); + } + (r[2] > r[0] && r[3] > r[1]).then_some(r) +} + +/// The pixel rectangle `[x0, y0, x1, y1]` a marquee between two corners selects. +pub fn marquee_px(a: [f64; 2], b: [f64; 2]) -> [f64; 4] { + [a[0].min(b[0]).floor(), a[1].min(b[1]).floor(), a[0].max(b[0]).ceil(), a[1].max(b[1]).ceil()] +} + +/// The pixel rectangle of a Fixed Size marquee between the corners `a` and `b`: exactly `w` × `h` +/// whole pixels. Snapping both edges outwards (`marquee_px`) added a pixel to each side whenever +/// the press point sat between pixels, so 10 × 10 selected 11 × 11 (#6015). The near edge goes +/// to the closest pixel edge and the far one is the size away. +pub fn fixed_size_px(a: [f64; 2], b: [f64; 2], w: f32, h: f32) -> [f64; 4] { + let (w, h) = (f64::from(w).round().max(1.0), f64::from(h).round().max(1.0)); + let (x0, y0) = (a[0].min(b[0]).round(), a[1].min(b[1]).round()); + [x0, y0, x0 + w, y0 + h] +} + +/// Whether the marquee drag `d` is constrained to a square (or circle): ⇧ during the drag with +/// the Normal style, or a Fixed Ratio of 1:1. Mirrors the branches of `chrome_ui::marquee_end`. +fn marquee_is_square(o: &crate::state::ToolOptions, d: &Drag) -> bool { + let (w, h) = (f64::from(o.marquee_width), f64::from(o.marquee_height)); + match o.marquee_style.as_str() { + "fixedSize" => false, + "fixedRatio" if w > 0.0 && h > 0.0 => w == h, + _ => d.marquee_mods().0, + } +} + +/// A constrained square `r` (`marquee_px` of its corners) with equal sides on whole pixels. +/// +/// The square is built in continuous coordinates, and snapping each axis to the pixel grid on +/// its own (floor the near edge, ceil the far one) made one side a pixel longer than the other +/// whenever the press point sat between pixels: a ⇧ drag read 101 × 102 (#5472). The shorter +/// side grows to the longer one, away from the press point (`start`, towards `end`), so the +/// square still covers every pixel the drag touched. +pub fn square_px(r: [f64; 4], start: [f64; 2], end: [f64; 2]) -> [f64; 4] { + let [x0, y0, x1, y1] = r; + let (w, h) = (x1 - x0, y1 - y0); + let n = w.max(h); + let grow = |lo: f64, hi: f64, extent: f64, from: f64, to: f64| { + let d = (n - extent).max(0.0); + if to < from { (lo - d, hi) } else { (lo, hi + d) } + }; + let (x0, x1) = grow(x0, x1, w, start[0], end[0]); + let (y0, y1) = grow(y0, y1, h, start[1], end[1]); + [x0, y0, x1, y1] +} + +/// The one-pixel line `[x0, y0, x1, y1]` a Single Row (Single Column) Marquee at `p` selects: the +/// pixel row (column) under `p`, kept on the canvas, across the whole `size`. `None` for other +/// tools, an empty canvas or a point that is not a number. +pub(crate) fn single_line_px(tool: Tool, size: [u32; 2], p: [f64; 2]) -> Option<[f64; 4]> { + let [w, h] = size.map(f64::from); + if w < 1.0 || h < 1.0 || !p[0].is_finite() || !p[1].is_finite() { + return None; + } + match tool { + Tool::SingleRowMarquee => { + let y = p[1].floor().clamp(0.0, h - 1.0); + Some([0.0, y, w, y + 1.0]) + } + Tool::SingleColumnMarquee => { + let x = p[0].floor().clamp(0.0, w - 1.0); + Some([x, 0.0, x + 1.0, h]) + } + _ => None, + } +} + +/// The line a Single Row / Single Column Marquee gesture `d` selects so far: it follows the +/// pointer until the release. +pub(super) fn single_line_drag_px(app: &PhotocraftApp, d: &Drag) -> Option<[f64; 4]> { + let st = app.session.active()?; + let last = d.points.last().map_or(d.start, |p| [p[0], p[1]]); + single_line_px(d.tool, [st.doc.size.width, st.doc.size.height], last) +} + +/// The marching ants of a marquee drag: its rectangle, or the ellipse inscribed in it, built in +/// document space and mapped point by point through the view, so the hinting lands where the +/// release commits the selection. +/// +/// A rotated view projects the rectangle onto a rotated one, and an axis-aligned screen box +/// through two of its corners is a different shape in a different place: the commit was always +/// right, only the hinting was drawn elsewhere (#2512). The points are not snapped: the ants snap +/// straight edges to device pixels as they draw them (`crate::ants`), like every other outline, so +/// the lines stay crisp at any zoom (#172) and display scale (#7489). +pub(crate) fn marquee_ants(xf: &ViewXform, tool: Tool, a: [f64; 2], b: [f64; 2]) -> Vec { + let (x0, x1) = (a[0].min(b[0]), a[0].max(b[0])); + let (y0, y1) = (a[1].min(b[1]), a[1].max(b[1])); + let at = |x: f64, y: f64| xf.to_screen(x as f32, y as f32); + if tool != Tool::EllipseMarquee { + return vec![at(x0, y0), at(x1, y0), at(x1, y1), at(x0, y1)]; + } + // An axis-aligned view (rotation a multiple of 90 degrees) maps the ellipse onto the one + // inscribed in the screen box of two opposite corners. The ants draw its vertices where they + // are: snapping each on its own turns the nearly flat arcs at the edge midpoints into 1 px + // stairs, whose antialiased steps wash the ants out to grey on white and black. + let quarter = xf.rotation.rem_euclid(90.0); + if quarter < 1e-4 || 90.0 - quarter < 1e-4 { + let r = Rect::from_two_pos(at(x0, y0), at(x1, y1)); + return crate::tool_feedback::ellipse_points(r); + } + // As many vertices as the same ellipse would get drawn on screen (`ellipse_points`). + let scr = Rect::from_points(&[xf.to_screen(x0 as f32, y0 as f32), xf.to_screen(x1 as f32, y1 as f32)]); + let n = (((scr.width() + scr.height()) * 0.25) as usize).clamp(16, 256); + let (cx, cy, rx, ry) = ((x0 + x1) * 0.5, (y0 + y1) * 0.5, (x1 - x0) * 0.5, (y1 - y0) * 0.5); + (0..n) + .map(|i| { + let t = i as f64 / n as f64 * std::f64::consts::TAU; + at(cx + rx * t.cos(), cy + ry * t.sin()) + }) + .collect() +} + +/// The ants of the marquee being drawn: `marquee` when the drag has one (the options-bar style +/// and the modifiers applied), the raw press and pointer corners otherwise. This is the whole of +/// what the hinting draws for the selection tools, so the test in `marquee_tests` checks it +/// against the selection the release commits (#2512). +pub(crate) fn marquee_drag_ants(d: &Drag, xf: &ViewXform, marquee: Option<[f64; 4]>) -> Vec { + let last = d.points.last().map_or(d.start, |p| [p[0], p[1]]); + let (a, b) = marquee.map_or((d.start, last), |[x0, y0, x1, y1]| ([x0, y0], [x1, y1])); + marquee_ants(xf, d.tool, a, b) +} + +/// The size readout shown beside the cursor while dragging a marquee: the width and height values. +pub fn marquee_readout(r: [f64; 4]) -> [String; 2] { + [format!("{} px", r[2] - r[0]), format!("{} px", r[3] - r[1])] +} + +/// [`marquee_readout`] in the Units & Rulers unit, as Photoshop shows it (cm when the rulers are in +/// centimeters), from the active document's resolution; pixels without a document. +pub fn size_readout(app: &PhotocraftApp, r: [f64; 4]) -> [String; 2] { + let Some(d) = app.session.active() else { return marquee_readout(r) }; + let (dpi, size) = (f64::from(d.doc.resolution_dpi), d.doc.size); + readout_in(&app.session.prefs().units_and_rulers, dpi, [size.width as f64, size.height as f64], r) +} + +/// `r`'s width and height formatted in `ur`'s ruler unit at `dpi` (percent of `extent`). +pub fn readout_in(ur: &photocraft_engine::prefs::UnitsAndRulers, dpi: f64, extent: [f64; 2], r: [f64; 4]) -> [String; 2] { + let s = ur.rulers.suffix(); + [format!("{} {s}", ur.format(r[2] - r[0], dpi, extent[0])), format!("{} {s}", ur.format(r[3] - r[1], dpi, extent[1]))] +} + +/// Draw the marquee size readout below-right of the cursor (kept on screen), like Photoshop's: +/// two rows, `W:` / `H:` labels on the left and the values right-aligned. +pub(super) fn draw_marquee_readout(app: &PhotocraftApp, ctx: &egui::Context, cursor: Pos2, values: [String; 2]) { + draw_value_readout(app, ctx, "marquee-readout", cursor, ["W:", "H:"], values); +} + +/// A turn of `deg` degrees as the readout beside the pointer shows it, to 0.1° in (-180, 180]. +/// Rounded first so a hair below zero never reads "-0.0°" and a hair above -180 reads "180.0°". +pub(crate) fn angle_readout(deg: f64) -> String { + let d = (deg * 10.0).round() / 10.0; + let d = if d == 0.0 { + 0.0 + } else if d == -180.0 { + 180.0 + } else { + d + }; + format!("{d:.1}°") +} + +/// A transformation-values readout beside the pointer (a marquee's or the crop frame's size, an +/// angle), unless Preferences › Tools › Show Transformation Values is off, as in Photoshop (#204). +/// The brush HUD isn't one: Show Transformation Values doesn't hide it, so it calls [`draw_readout`]. +pub(crate) fn draw_value_readout(app: &PhotocraftApp, ctx: &egui::Context, id: &str, cursor: Pos2, labels: [&str; N], values: [String; N]) { + if app.session.prefs().tools.show_transformation_values { + draw_readout(ctx, id, cursor, labels, values); + } +} + +/// A readout of `N` rows beside the pointer (labels left, values right-aligned), above everything. +pub(crate) fn draw_readout(ctx: &egui::Context, id: &str, cursor: Pos2, labels: [&str; N], values: [String; N]) { + let t = crate::theme::Tokens::get(ctx); + let font = egui::FontId::proportional(11.5); + let width = |text: &str| ctx.fonts_mut(|f| f.layout_no_wrap(text.to_owned(), font.clone(), t.text).size().x); + let labels = labels.map(|label| tl!(label)); + let (lw, vw) = (labels.map(width), values.each_ref().map(|v| width(v))); + let (label_col, value_col) = (lw.iter().fold(0.0f32, |a, &b| a.max(b)), vw.iter().fold(0.0f32, |a, &b| a.max(b))); + egui::Area::new(egui::Id::unique(id)).order(egui::Order::Tooltip).fixed_pos(cursor + vec2(16.0, 18.0)).interactable(false).constrain(true).show( + ctx, + |ui| { + egui::Frame::new() + .fill(t.card) + .stroke(Stroke::new(1.0, t.card_border)) + .corner_radius(t.radius_sm) + .inner_margin(egui::Margin::symmetric(7, 4)) + .show(ui, |ui| { + ui.spacing_mut().item_spacing = vec2(0.0, 1.0); + for (i, value) in values.into_iter().enumerate() { + // Labels left, values right-aligned on one edge, sharing a baseline. + ui.horizontal(|ui| { + ui.add(egui::Label::new(egui::RichText::new(labels[i]).font(font.clone()).color(t.text_dim)).extend()); + ui.add_space(label_col - lw[i] + 12.0 + value_col - vw[i]); + ui.add(egui::Label::new(egui::RichText::new(value).font(font.clone()).color(t.text)).extend()); + }); + } + }); + }, + ); +} diff --git a/crates/ui-egui/src/canvas/filter_preview.rs b/crates/ui-egui/src/canvas/filter_preview.rs new file mode 100644 index 0000000000..6940b7b720 --- /dev/null +++ b/crates/ui-egui/src/canvas/filter_preview.rs @@ -0,0 +1,308 @@ +use super::display::canvas_display; +use super::textures::texture_buffer; +use super::*; + +/// The proxy factor of a live preview of filter `cmd` with `params` on `doc`, the active document: +/// reduced on a large document (Preferences › Performance › Low Resolution Previews), except for +/// filters whose features don't scale with a proxy (#2063), and never coarser than the active view, +/// so at 100 % the preview shows every pixel instead of k-pixel blocks (#6326, as adjustment +/// previews have since #5764). Zoomed out, the proxy keeps previews of large documents fast. +/// +/// The in-dialog preview window ([`crate::filter_preview_ui`]) sizes its own textures from this +/// too, so the canvas and the window never disagree about the factor. +/// +/// Full resolution costs a whole filter per parameter change, which only the background worker +/// absorbs. The web build has no worker and computes the preview inline on the UI thread (#1676), +/// where that would freeze the page: there the document's proxy stands. The test and +/// `PHOTOCRAFT_INLINE_JOBS` inline paths keep the cap deliberately, because `background_jobs` is +/// flipped mid-session (a shell save during `actions.play`): a factor that followed it would change +/// [`crate::filter_dialog::FilterPreviewKey`] under a finished preview and recompute it inline, +/// the very stall this avoids. +pub(crate) fn filter_preview_factor(app: &PhotocraftApp, doc: &Document, cmd: &str, params: &serde_json::Value) -> u32 { + // A smart filter edit re-renders the whole stack: every stage constrains the factor. + let k = crate::filter_dialog::smart_preview_factor(doc, cmd, params, crate::proxy::preview_factor(doc, crate::proxy::reduced_previews(app))); + if cfg!(target_arch = "wasm32") { k } else { crate::proxy::view_factor(k, app.current_zoom()) } +} + +/// Live preview for an open filter dialog: run the filter on the proxy and upload it. With +/// background jobs (the desktop app) it computes on one background worker +/// (`filter_preview_worker`); otherwise (web, tests, `PHOTOCRAFT_INLINE_JOBS`) it keeps the +/// deterministic inline path (#1676), which also lets headless/CPU tests inspect previews +/// without a GPU texture. +pub(crate) fn ensure_filter_preview(app: &mut PhotocraftApp, idx: usize, ctx: &egui::Context) -> Option<(u32, u64, [u32; 2])> { + if let Some(held) = committed_filter_preview(app, idx) { + return held; + } + // Command dialogs always edit the active document. Never show their preview in another tab. + if app.session.active_index() != Some(idx) { + return None; + } + if crate::adjust_preview::on_layer(app, idx) { + return None; + } + let d = app.ui.dialogs.iter().find(|d| d.fields.contains_key("__filter"))?; + if d.fields.get("__preview").and_then(serde_json::Value::as_bool) != Some(true) { + return None; + } + let cmd = d.fields.get("__command")?.as_str()?.to_string(); + // Previews edit what the command will: a targeted layer mask included (#780). + let (cmd, mut params) = if d.fields.contains_key("__smartFilter") { + crate::smart_filter_dialog::edit_command(app, &d.fields).ok()? + } else { + (cmd.clone(), app.with_mask_target(&cmd, crate::filter_dialog::params_of(&d.fields))) + }; + // Select and Mask previews in its view mode; holding X shows the image without one. + if crate::select_mask_view::owns(&d.fields) { + if crate::select_mask_view::hides_view(&d.fields) { + return None; + } + params = crate::select_mask_view::request_params(&d.fields, params); + } + let st = app.session.documents().get(idx)?; + let k = filter_preview_factor(app, &st.doc, &cmd, ¶ms); + let request = crate::filter_dialog::FilterPreviewKey { + doc: st.doc.id, + revision: st.revision, + dialog: d.id, + active: st.active_layer, + target: st.channel_view.target, + command: cmd, + params, + k, + }; + let key = request.doc.0 ^ (1u64 << 61); + // Every filter's preview computes off the UI thread in the desktop app: Gaussian Blur at + // 1000 px takes long enough to freeze the window. Once the slider settles, a preview still + // running for an older value is cancelled. + #[cfg(not(target_arch = "wasm32"))] + if app.background_jobs { + app.filter_preview_worker.supersede(&request, crate::gpu_canvas::now_ms()); + if let Some((finished, computed)) = app.filter_preview_worker.poll() { + match computed { + // The dialog still holds these exact parameters. Publish as before, including an + // empty result: that is how a filter which no longer applies clears the canvas. + Ok(computed) if finished == request => publish_filter_preview(app, idx, finished, computed.result, computed.ms), + // Mid-drag, a frame for the value the pointer has just left is what makes the + // canvas follow the drag. Three things have to hold for it: it belongs to this + // preview, it has a frame to show (an empty one would blank a good preview), and + // it must not displace a frame that is already exact for the dialog, which is + // what a slider dragged out and back would otherwise make the canvas do. + Ok(computed) + if finished.same_target(&request) && computed.result.is_some() && !app.filter_preview.as_ref().is_some_and(|p| p.key == request) => + { + publish_filter_preview(app, idx, finished, computed.result, computed.ms); + } + Ok(_) => {} + // Errors stay on the exact request: a value the pointer has already dragged past + // must not raise a notice, and a still one will raise it when it is recomputed. + Err(error) if finished == request => { + app.filter_preview = Some(crate::filter_dialog::FilterPreview { key: finished, result: None, committing: false }); + crate::notices::error(app, error); + } + Err(_) => {} + } + } + let fresh = app.filter_preview.as_ref().is_some_and(|p| p.key == request); + if !fresh && !app.filter_preview_worker.busy() { + let doc = app.session.documents().get(idx)?.doc.clone(); + let documents: Vec<_> = app.session.documents().iter().map(|d| d.doc.clone()).collect(); + let color = app.session.color.settings.clone(); + let task = request.clone(); + if let Err(error) = app.filter_preview_worker.start(request.clone(), ctx.clone(), move |cancel| { + let t0 = crate::gpu_canvas::now_ms(); + let result = crate::filter_dialog::preview_document_for_target( + &doc, + task.active, + &task.command, + &task.params, + task.k, + Some(cancel), + task.target, + &documents, + &color, + ) + .map(|doc| { + let buffer = photocraft_compose::flatten(&doc); + (std::sync::Arc::new(doc), buffer) + }); + crate::filter_preview_worker::Computed { result, ms: crate::gpu_canvas::now_ms() - t0 } + }) { + app.filter_preview = Some(crate::filter_dialog::FilterPreview { key: request.clone(), result: None, committing: false }); + crate::notices::error(app, error); + } + } + if app.filter_preview_worker.busy() { + ctx.request_repaint_after(std::time::Duration::from_millis(16)); + } + let preview = app.filter_preview.as_ref()?; + // Keep the last preview during a drag, but never one from another source or dialog. + if !preview.key.same_target(&request) { + return None; + } + let result = preview.result.as_ref()?; + return Some((preview.key.k, key, [result.size.width, result.size.height])); + } + // Web and explicitly inline sessions keep the deterministic synchronous path (#1676): + // computed inline, uploaded when a GPU texture exists, still inspectable without one. + // Flattened once, as the background worker does; `publish_filter_preview` uploads it (#7490). + let _ = ctx; + if app.filter_preview.as_ref().is_none_or(|p| p.key != request) { + let doc = app.session.documents().get(idx)?.doc.clone(); + let documents: Vec<_> = app.session.documents().iter().map(|d| d.doc.clone()).collect(); + let t0 = crate::gpu_canvas::now_ms(); + let computed = crate::filter_dialog::preview_document_for_target( + &doc, + request.active, + &request.command, + &request.params, + request.k, + None, + request.target, + &documents, + &app.session.color.settings, + ) + .map(|doc| { + let buffer = photocraft_compose::flatten(&doc); + (std::sync::Arc::new(doc), buffer) + }); + publish_filter_preview(app, idx, request, computed, crate::gpu_canvas::now_ms() - t0); + } + let preview = app.filter_preview.as_ref()?; + let result = preview.result.as_ref()?; + Some((preview.key.k, key, [result.size.width, result.size.height])) +} + +/// Channel overlays must use the filter's current proxy too, including on the CPU canvas. +/// The cache key changes with the completed request; unchanged frames reuse the overlay texture. +pub(crate) fn filter_channel_preview(app: &mut PhotocraftApp, idx: usize, ctx: &egui::Context) -> Option<(std::sync::Arc, u64)> { + use std::hash::{Hash, Hasher}; + ensure_filter_preview(app, idx, ctx)?; + let preview = app.filter_preview.as_ref()?; + let doc = preview.result.as_ref()?.clone(); + let mut key = std::collections::hash_map::DefaultHasher::new(); + format!("{:?}", preview.key).hash(&mut key); + Some((doc, key.finish() | (1 << 59))) +} + +fn publish_filter_preview( + app: &mut PhotocraftApp, + idx: usize, + request: crate::filter_dialog::FilterPreviewKey, + computed: Option<(std::sync::Arc, photocraft_compose::Buffer)>, + ms: f64, +) { + let result = computed.and_then(|(result, buffer)| { + let t0 = crate::gpu_canvas::now_ms(); + let doc = app.session.documents().get(idx)?.doc.clone(); + // Shown through the preview's own colour management, as the result will be: Assign and + // Convert to Profile change the profile (and Convert the mode), not just the pixels. + let (display, _) = canvas_display(app, &result, None); + // A GPU texture is an optimisation: headless/CPU tests must still see the preview. + if let Some(gpu) = app.gpu.as_ref() { + gpu.upload_buffer_full(request.doc.0 ^ (1u64 << 61), &texture_buffer(display.as_deref(), &buffer), doc.depth); + } + app.perf.record("filter-preview", result.size.area(), ms, crate::gpu_canvas::now_ms() - t0); + Some(result) + }); + app.filter_preview = Some(crate::filter_dialog::FilterPreview { key: request, result, committing: false }); +} + +/// The document whose colour management the canvas texture under `key` is shown through: a filter +/// preview's own result (it keeps the document's id, so Proof Colors still apply), else `doc`. +/// Assign Profile changes only the profile, so through `doc`'s its preview looked unchanged. +pub(super) fn filter_preview_display_doc(app: &PhotocraftApp, doc: &std::sync::Arc, key: u64) -> std::sync::Arc { + if key != doc.id.0 ^ (1u64 << 61) { + return doc.clone(); + } + app.filter_preview.as_ref().and_then(|p| p.result.clone()).filter(|r| r.id == doc.id).unwrap_or_else(|| doc.clone()) +} + +/// After a filter dialog's OK: `Some(shown)` while its preview stands in for the background job +/// that commits it (the document unchanged and the job still running, for this document's views), +/// `None` otherwise (other documents' views included). A job that lands, fails or is cancelled +/// drops it. +pub(crate) fn committed_filter_preview(app: &mut PhotocraftApp, idx: usize) -> Option> { + let p = app.filter_preview.as_ref().filter(|p| p.committing)?; + let st = app.session.documents().get(idx)?; + if st.doc.id != p.key.doc { + return None; + } + let size = p.result.as_ref().map(|r| [r.size.width, r.size.height]); + if let Some(size) = size + && st.revision == p.key.revision + && app.session.job_on(p.key.doc).is_some() + { + return Some(Some((p.key.k, p.key.doc.0 ^ (1u64 << 61), size))); + } + app.filter_preview = None; + Some(None) +} + +/// Zoomed-out Image › Adjustments preview on a large document: the wgpu compositor renders the +/// reduced preview document (`adjust_preview::gpu_proxy`) into its own texture, over the target's +/// area after the first frame. Returns (factor, gpu key, dimensions) to draw. +pub(super) fn ensure_adjust_proxy(app: &mut PhotocraftApp, idx: usize, zoom: f32) -> Option<(u32, u64, [u32; 2])> { + let frame = crate::adjust_preview::gpu_proxy(app, idx, zoom)?; + let key = frame.doc.id.0; + let size = [frame.doc.size.width, frame.doc.size.height]; + let gpu = app.gpu.clone()?; + if frame.stale || !gpu.has(key, size) { + let doc = app.session.documents().get(idx)?.doc.clone(); + let (display, _) = canvas_display(app, &doc, None); + let r = gpu.refresh(key, &frame.doc, frame.damage, display.as_deref()); + app.perf.record(if r.kind.starts_with("gpu") { "gpu-adjust-proxy" } else { "adjust-proxy" }, r.px, r.composite_ms, r.upload_ms); + if let Some(t) = r.gpu { + app.perf.record_gpu(t); + } + crate::adjust_preview::proxy_drawn(app, &frame); + } + Some((frame.k, key, size)) +} + +/// If a live adjustment preview is active on a large document, composite it on the proxy and upload +/// it under its own GPU key. Returns (factor, gpu key, dimensions) when the proxy should be drawn. +/// `zoom` is the view's (physical screen pixels per document pixel). +pub(super) fn ensure_proxy_preview(app: &mut PhotocraftApp, idx: usize, zoom: f32) -> Option<(u32, u64, [u32; 2])> { + let (layer, params) = app.live_adjust.clone()?; + let (doc_id, revision, doc) = { + let st = app.session.documents().get(idx)?; + (st.doc.id, st.revision, st.doc.clone()) + }; + // Low-resolution previews off: k is 1 and the canvas shows `display_doc` (full size). + let mut k = crate::proxy::preview_factor(&doc, crate::proxy::reduced_previews(app)); + // Zoomed in, a proxy coarser than the screen showed the drag in k-pixel blocks (#5764): when + // the wgpu compositor draws the full-size document, use a proxy only as coarse as the screen + // (none at 50 % and closer). Otherwise the full size would be a CPU composite per change. + let fine = crate::proxy::view_factor(k, zoom); + if fine < k && app.gpu.as_ref().is_some_and(|g| g.supports(&doc)) { + k = fine; + } + if k <= 1 { + return None; + } + let fresh = matches!(&app.proxy, Some((d, r, kk, _)) if *d == doc_id && *r == revision && *kk == k); + if !fresh { + app.proxy = Some((doc_id, revision, k, std::sync::Arc::new(crate::proxy::proxy_document(&doc, k)))); + } + let proxy = app.proxy.as_ref()?.3.clone(); + let key = doc_id.0 ^ (1u64 << 62); + let hash = params.to_string().bytes().fold(k as u64, |h, b| h.wrapping_mul(31).wrapping_add(b as u64)); + if app.proxy_uploaded != Some((doc_id, hash)) { + let l = proxy.layer(layer)?; + let LayerContent::Adjustment(a) = &l.content else { return None }; + let kind = photocraft_engine::commands::adjustment_kind(a); + let preview = photocraft_engine::adjust_params::from_params(kind, ¶ms, Some(a), proxy.mode).unwrap_or_else(|_| a.clone()); + let mut p = (*proxy).clone(); + if let Some(lm) = p.layer_mut(layer) { + lm.content = LayerContent::Adjustment(preview); + } + let t0 = crate::gpu_canvas::now_ms(); + let buf = photocraft_compose::flatten(&p); + let t1 = crate::gpu_canvas::now_ms(); + let (display, _) = canvas_display(app, &doc, None); + app.gpu.as_ref()?.upload_buffer_full(key, &texture_buffer(display.as_deref(), &buf), doc.depth); + app.perf.record("proxy", p.size.area(), t1 - t0, crate::gpu_canvas::now_ms() - t1); + app.proxy_uploaded = Some((doc_id, hash)); + } + Some((k, key, [proxy.size.width, proxy.size.height])) +} diff --git a/crates/ui-egui/src/canvas/gesture.rs b/crates/ui-egui/src/canvas/gesture.rs new file mode 100644 index 0000000000..81c0b231a4 --- /dev/null +++ b/crates/ui-egui/src/canvas/gesture.rs @@ -0,0 +1,286 @@ +use super::drag::{Drag, marquee_preview_px, single_line_drag_px}; +use super::selection::finish_selection_drag; +use super::strokes::{ + EngineStroke, commit_brush_stroke, feed_live_stroke, live_retouch_command, offer_live_retouch, paint_target, snap_aliased_tip, stroke_params, +}; +use super::textures::shown_as_document; +use super::*; + +pub(crate) fn finish_gesture(app: &mut PhotocraftApp, d: Drag) { + // Control can select a different tool and release before the next frame cancels the drag. + // Cancel before even recording a Shift-stroke anchor, including the preview fallback paths. + if d.tool == Tool::MixerBrush && app.ui.tool != Tool::MixerBrush { + app.live_stroke = None; + return; + } + let mut end = d.points.last().copied().unwrap_or([d.start[0], d.start[1], 1.0]); + let (sx, sy) = snap_aliased_tip(app, d.tool, end[0], end[1]); + end[0] = sx; + end[1] = sy; + if let Some(floating) = d.sel_move { + finish_selection_drag(app, floating, d.start, [end[0], end[1]]); + return; + } + // Where the next ⇧-click line starts. + if crate::stroke_constraint::connects(d.tool) + && let Some(st) = app.session.active() + { + app.last_stroke_end = Some((st.doc.id, end)); + } + if d.tool == Tool::MixerBrush { + // The release can carry a new endpoint, including moves deferred in this frame. + // Feed those samples before offering the already-rendered document for commit. + app.drag = Some(d); + let deferred = std::mem::replace(&mut app.defer_live_stroke, false); + feed_live_stroke(app); + app.defer_live_stroke = deferred; + let Some(d) = app.drag.take() else { return }; + let live = app.live_stroke.take(); + if let Some(l) = live { + let (doc, key, steps) = (l.doc, l.key, l.damage.len() as u64); + if let EngineStroke::Mixer(mixer) = l.stroke { + if l.preview_failed { + let mut p = stroke_params(app, &d, &app.stylus.stroke_points(&d.points)); + p["seed"] = json!(mixer.seed); + drop(mixer); + let _ = app.run("paint.mixerBrush", p); + return; + } + match mixer.prepare_commit(&mut app.session) { + Ok(p) => { + if app.run("paint.mixerBrush", p).is_ok() { + shown_as_document(app, doc, |k| k == 0 || (key..=key + steps).contains(&k)); + } + } + Err(e) => { + app.ui.status = e.to_string(); + app.ui.status_error = true; + } + } + } + } else { + // No preview (a tip above its size): render the whole stroke now. + let p = stroke_params(app, &d, &app.stylus.stroke_points(&d.points)); + let _ = app.run("paint.mixerBrush", p); + } + return; + } + // A live retouching preview ends here; the commit below replaces it (the Clone Stamp's, + // History Brush's and sequential-dab tools' with the pixels it already drew). + offer_live_retouch(app, &d); + if live_retouch_command(d.tool).is_some() || crate::retouch_ui::dab_params(app, d.tool).is_some() || d.tool == Tool::ColorReplacement { + app.live_stroke = None; + } + let finished = crate::eraser_ui::finish_stroke(app, d.tool, &d.points) || crate::retouch_ui::finish_stroke(app, d.tool, &d.points, d.modifiers); + app.session.clear_live_stroke(); + if finished { + return; + } + match d.tool { + Tool::ObjectSelection => crate::retouch_ui::finish_object_selection(app, d.start, [end[0], end[1]], d.modifiers), + Tool::FreeformPen => crate::vector_ui::freeform_finish(app, &d.points, d.lasso.as_ref().map_or(&[], |l| l.straight())), + // Photoshop: a click without dragging opens Create Rectangle / Ellipse / … instead. + t if crate::vector_ui::is_shape_tool(t) + && crate::shape_dialog::is_click(d.start, &d.points, app.point_zoom()) + && crate::shape_dialog::open(app, t, d.start).is_some() => {} + t if crate::vector_ui::is_shape_tool(t) => crate::vector_ui::finish_shape(app, t, d.start, [end[0], end[1]], d.live), + Tool::PathSelection => crate::vector_ui::path_selection_finish(app, d.start, [end[0], end[1]]), + Tool::Type | Tool::VerticalType | Tool::HorizontalTypeMask | Tool::VerticalTypeMask => crate::type_tool::pointer_up(app, d.start, [end[0], end[1]]), + Tool::Brush | Tool::Pencil | Tool::Eraser => commit_brush_stroke(app, &d), + Tool::RectMarquee | Tool::EllipseMarquee => { + // Exactly what the drag showed (`marquee_preview_px`); a click deselects. + let Some([x0, y0, x1, y1]) = marquee_preview_px(&app.ui.tool_options, &d, app.point_zoom()) else { + if app.session.is_enabled("select.deselect") { + let _ = app.run("select.deselect", json!({})); + } + return; + }; + let mode = selection_mode(app, d.modifiers); + let (aa, feather) = (app.ui.tool_options.anti_alias, app.ui.tool_options.feather); + let _ = app.run("select.rect", json!({"x": x0, "y": y0, "width": x1 - x0, "height": y1 - y0, "mode": mode, "ellipse": d.tool == Tool::EllipseMarquee, "antiAlias": aa, "feather": feather})); + } + // A click (or the end of a drag) selects the line under the pointer, never deselects. + Tool::SingleRowMarquee | Tool::SingleColumnMarquee => { + let Some([x0, y0, x1, y1]) = single_line_drag_px(app, &d) else { return }; + let mode = selection_mode(app, d.modifiers); + let feather = app.ui.tool_options.feather; + // `line` names the History step after the tool (Single Row / Single Column Marquee). + let line = if d.tool == Tool::SingleRowMarquee { "row" } else { "column" }; + let _ = app.run( + "select.rect", + json!({"x": x0, "y": y0, "width": x1 - x0, "height": y1 - y0, "mode": mode, "line": line, "antiAlias": false, "feather": feather}), + ); + } + Tool::Patch if crate::retouch_ui::patch_drags_selection(app, d.start, d.modifiers) => crate::retouch_ui::finish_patch(app, d.start, [end[0], end[1]]), + Tool::ContentAwareMove if crate::retouch_ui::patch_drags_selection(app, d.start, d.modifiers) => { + crate::retouch_ui::finish_content_aware_move(app, d.start, [end[0], end[1]]) + } + Tool::Lasso | Tool::Patch | Tool::ContentAwareMove => { + let pts: Vec<[f64; 2]> = d.points.iter().map(|p| [p[0], p[1]]).collect(); + if pts.len() >= 3 { + let mode = selection_mode(app, d.modifiers); + let o = &app.ui.tool_options; + // The Patch and Content-Aware Move tools have no Feather in their options bar. + let feather = if d.tool == Tool::Lasso { o.feather } else { 0.0 }; + let made = app.run("select.lasso", json!({"points": pts, "mode": mode, "antiAlias": o.anti_alias, "feather": feather})); + // The lasso only outlines the patch; say that it is dragged next (#1715). + if made.is_ok() && d.tool != Tool::Lasso { + crate::retouch_ui::patch_hint(app); + } + } else if app.session.is_enabled("select.deselect") { + let _ = app.run("select.deselect", json!({})); + } + } + Tool::Gradient if (end[0] - d.start[0]).abs() + (end[1] - d.start[1]).abs() >= 2.0 => { + let o = app.ui.tool_options.clone(); + let _ = app.run( + "paint.gradient", + json!({"from": [d.start[0], d.start[1]], "to": [end[0], end[1]], "style": o.gradient_style, "reverse": o.gradient_reverse, "dither": o.gradient_dither, "opacity": o.fill_opacity, "mode": o.gradient_blend_mode.label(), "target": paint_target(app)}), + ); + } + Tool::Move => { + let (dx, dy) = ((end[0] - d.start[0]).round(), (end[1] - d.start[1]).round()); + crate::move_ui::finish(app, dx, dy); + } + _ => {} + } +} + +/// Selection mode from the options bar, overridden by modifier keys (⇧ add, ⌥ subtract, ⇧⌥ intersect). +/// The cursor badge announces the same mode (`tool_feedback`). +pub(crate) fn selection_mode(app: &PhotocraftApp, m: egui::Modifiers) -> &'static str { + crate::tool_feedback::document_selection_mode(app, Tool::Lasso, m) +} + +/// Shift constrains a Polygonal Lasso segment to Photoshop's 45° directions. +/// Work in document coordinates so zoom, view rotation and mirroring cannot skew it. +pub(crate) fn constrained_polygon_point(from: [f64; 2], point: [f64; 2]) -> [f64; 2] { + let dx = point[0] - from[0]; + let dy = point[1] - from[1]; + if !dx.is_finite() || !dy.is_finite() { + return point; + } + let length = dx.hypot(dy); + if length == 0.0 { + return point; + } + let angle = (dy.atan2(dx) / std::f64::consts::FRAC_PI_4).round() * std::f64::consts::FRAC_PI_4; + [from[0] + length * angle.cos(), from[1] + length * angle.sin()] +} + +/// A polygonal lasso click adds a vertex; clicking near the first vertex closes the polygon. The +/// first click fixes the selection mode; a new-selection polygon hides the old outline while it is +/// drawn, and replaces it in one history step when it closes. +pub(super) fn polygon_click(app: &mut PhotocraftApp, x: f64, y: f64, mods: egui::Modifiers) { + let close = app + .ui + .polygon + .first() + .is_some_and(|p0| app.ui.polygon.len() >= 3 && ((p0[0] - x).powi(2) + (p0[1] - y).powi(2)).sqrt() < 8.0 / app.point_zoom().max(0.01) as f64); + if close { + commit_polygon(app); + return; + } + if app.ui.polygon.is_empty() { + app.ui.polygon_doc = app.session.active().map(|st| st.doc.id); + // ⌥ with nothing selected draws freehand; there is nothing to subtract from. + let nothing_selected = app.session.active().is_none_or(|st| st.doc.selection.is_none()); + let intent = if nothing_selected { egui::Modifiers { alt: false, ..mods } } else { mods }; + app.ui.polygon_mode = selection_mode(app, intent).into(); + } + // Only constrain segments after the first vertex; the first click still sets selection intent. + // Alt-drag is freehand and must not snap to an angle. + let point = if mods.shift && !mods.alt { app.ui.polygon.last().copied().map_or([x, y], |last| constrained_polygon_point(last, [x, y])) } else { [x, y] }; + app.ui.polygon.push(point); +} + +/// Remove the Polygonal Lasso's last vertex (⌫, Delete or a right-click while drawing, #1229); +/// removing the only one cancels the polygon. False when no polygon is being drawn. +pub fn polygon_retract(app: &mut PhotocraftApp) -> bool { + if app.ui.polygon.pop().is_none() { + return false; + } + if app.ui.polygon.is_empty() { + app.ui.polygon_mode.clear(); + } + true +} + +/// The polygon in progress belongs to the document it was started on (`UiState::polygon_doc`): +/// once another document becomes active it is dropped, so its outline doesn't show on (or get +/// committed to) the other document, and the selection it would have replaced is shown again. +/// Switching tools is handled in `PhotocraftApp::sync_views`. Like the Lasso's +/// ([`crate::lasso_ui::cancel_stale`]) and the Magnetic Lasso's ([`crate::magnetic_lasso_ui::frame`]). +pub fn polygon_cancel_stale(app: &mut PhotocraftApp) { + let active = app.session.active().map(|st| st.doc.id); + if app.ui.polygon.is_empty() { + app.ui.polygon_doc = None; + } else if app.ui.polygon_doc.is_some_and(|d| Some(d) != active) { + app.ui.polygon.clear(); + app.ui.polygon_mode.clear(); + app.ui.polygon_doc = None; + } +} + +/// A new-selection polygonal (or magnetic) lasso is being drawn, so the selection it will replace +/// is hidden. +pub fn polygon_replaces_selection(app: &PhotocraftApp) -> bool { + (!app.ui.polygon.is_empty() && app.ui.polygon_mode == "replace") || crate::magnetic_lasso_ui::replaces_selection(app) +} + +/// Close the polygonal lasso and make the selection in the mode it started in. +pub fn commit_polygon(app: &mut PhotocraftApp) { + let pts = std::mem::take(&mut app.ui.polygon); + let mode = std::mem::take(&mut app.ui.polygon_mode); + if pts.len() >= 3 { + let mode = if mode.is_empty() { selection_mode(app, egui::Modifiers::NONE).to_owned() } else { mode }; + let o = &app.ui.tool_options; + let _ = app.run("select.lasso", json!({"points": pts, "mode": mode, "antiAlias": o.anti_alias, "feather": o.feather})); + } +} + +/// Apply the crop tool's rectangle. When `image.crop` refuses it (the error is in the status bar), +/// the frame, its turn and its box Undo stay for fixing. +pub fn commit_crop(app: &mut PhotocraftApp) { + // Never another document's frame (#1918). + crate::crop_ui::cancel_stale(app); + let kept = crate::crop_ui::keep(app); + // Committing ends the box's own Undo/Redo: from here Edit › Undo reverts the document. + crate::crop_ui::clear_history(app); + // ↵ during a drag ends it: the release must not bring back the old document's frame. + app.crop.drag = None; + let Some(r) = app.ui.crop_rect.take() else { return }; + // The crop's default mode leaves the view upright (`crop_mode`). + crate::crop_mode::upright(app); + // The untouched default frame around the whole canvas crops nothing (Photoshop's ↵ on it does + // nothing); one framing the selection's bounds crops to them (#1789). + if std::mem::take(&mut app.crop.default_frame) { + let whole = app.session.active().map(|st| st.doc.bounds()).map(|b| [f64::from(b.x0), f64::from(b.y0), f64::from(b.x1), f64::from(b.y1)]); + if whole.is_none_or(|b| b == r) { + return; + } + } + let (x, y) = (r[0].round(), r[1].round()); + let (w, h) = ((r[2] - r[0]).round().max(1.0), (r[3] - r[1]).round().max(1.0)); + let delete = app.ui.tool_options.crop_delete; + let mut p = json!({"x": x, "y": y, "width": w, "height": h, "deleteCroppedPixels": delete}); + // Fill › Content-Aware Fill (#3823): what a turned or extending frame uncovers is filled from + // its surroundings instead of the background colour. + if app.ui.tool_options.crop_content_aware { + p["contentAware"] = json!(true); + } + // A turned frame (#1792): the document turns with it, then is cropped to it. (The untouched + // default frame above is never turned: turning it makes it a real frame.) + let angle = crate::crop_ui::angle(app); + app.ui.crop_angle = 0.0; + if angle != 0.0 { + p["angle"] = json!(angle); + } + // W x H x Resolution (#2443): resample to that size and set the resolution. + crate::crop_size::commit_params(app, &mut p); + if app.run("image.crop", p).is_err() { + crate::crop_ui::restore(app, kept); + } else if let Some(i) = app.session.active_index() { + app.ui.views[i].fit_pending = true; + } +} diff --git a/crates/ui-egui/src/canvas/gpu_canvas.rs b/crates/ui-egui/src/canvas/gpu_canvas.rs new file mode 100644 index 0000000000..7f16afd5ce --- /dev/null +++ b/crates/ui-egui/src/canvas/gpu_canvas.rs @@ -0,0 +1,960 @@ +//! GPU document canvas: an `egui_wgpu` paint callback that draws one document view with a custom +//! WGSL shader. +//! +//! The document's composite lives on the GPU as one or more mipmapped textures (premultiplied +//! alpha, sRGB-encoded values, matching how the CPU path and egui blend): `Rgba8Unorm` for 8-bit +//! documents, `Rgba16Float` for 16- and 32-bit documents when the adapter can render to and +//! filter it (so smooth gradients don't band and 32-bit values above 1.0 survive for the 32-bit +//! preview), within [`F16_BUDGET_PX`]; larger high-bit documents fall back to `Rgba8Unorm`. +//! Uploads are either full (new document, size change, re-render) or a damage rect (brush +//! strokes); after an upload only the affected region of each mip level is regenerated by a +//! render-pass blit chain. Documents larger than the device's maximum texture size are split +//! into tiles. +//! +//! Per frame the shader draws, in *device pixels*: +//! - a soft analytic drop shadow around the document on the pasteboard (erf-blurred box), +//! - a transparency checkerboard (8 pt squares, grays 255/204, the same size at every zoom) +//! under the document, anchored to the document's top-left corner so it moves with the image, +//! - the document itself, sampled trilinearly when zoomed out, bilinearly between 1× and 2×, and +//! with an anti-aliased "sharp nearest" filter at integer scales and ≥ 2×, +//! - a one-device-pixel pixel grid above 500% zoom, over pixels with content only. +//! +//! GPU resources live in the renderer's `callback_resources` type map; the per-frame callback only +//! carries plain view parameters, so it is `Send + Sync` on every target (including wasm). +//! +//! The document pixels still come from the CPU compositor (`photocraft-compose`) for now; the wgpu +//! compositor (M5) will render straight into these tiles. + +use std::collections::HashMap; +use std::num::NonZeroU64; +use std::sync::atomic::Ordering; + +use eframe::egui_wgpu::{self, CallbackResources, CallbackTrait, RenderState, ScreenDescriptor}; +use eframe::wgpu; + +pub use photocraft_gpu::{DeviceHealth, Fault}; + +mod budget; +mod callback; +mod doc_textures; +mod perf; +mod resources; +mod setup; +mod shaders; +mod texels; + +#[cfg(test)] +use budget::drm_video_memory; +pub use budget::{ + DEFER_PX, MIN_GPU_BUDGET, OVER_BUDGET, OVER_CANVAS_BUDGET, REFRESH_DEFERRED, REFRESH_OVER_BUDGET, canvas_budget, canvas_texture_bytes, memory_budget, + physical_memory, video_memory, vram_share, +}; +#[cfg(all(test, windows))] +use budget::{detect_physical_memory, detect_video_memory}; +use callback::CanvasCallback; +#[cfg(test)] +use callback::{filter_mode, map_doc_px, tile_screen_aabb}; +use doc_textures::init_buffer; +#[cfg(test)] +use doc_textures::{mip_count, mip_damage}; +pub use perf::{GpuInfo, Perf, backend_name, now_ms}; +pub use resources::CanvasStyle; +use resources::{DocTextures, Resources, identity_lut_bytes, lut_bind_group}; +#[cfg(test)] +use setup::device_limits_for; +use setup::texture_buffer; +pub use setup::{Refresh, device_descriptor, device_limits, display_texels, timing_features, use_adapter_limits, use_adapter_limits_with, wgpu_setup}; +#[cfg(test)] +use shaders::{CANVAS_WGSL, ENCODE_WGSL, MIP_WGSL}; +#[cfg(not(target_arch = "wasm32"))] +use texels::texel_to_f32; +pub use texels::{LayerFit, premultiply_rgba8, premultiply_rgba16f}; +#[cfg(test)] +use texels::{f16_to_f32, f32_to_f16}; +use texels::{texel_bytes, texels, texels_into}; + +/// Default tile side; documents up to this size (and the device limit) use a single texture. +pub const DEFAULT_TILE: u32 = 8192; +/// Mip levels no larger than this on either side are redrawn whole on every edit rather than +/// just their damage (see [`mip_damage`], #6418). Every corrupted level measured was at most +/// 64 px; this leaves a factor of two. +const WHOLE_MIP_SIDE: u32 = 128; +const FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm; +/// Canvas texture format of high-bit documents (see [`GpuCanvas::format_for`]). +const FORMAT_HIGH: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float; +/// Largest high-bit document (in pixels) given an `Rgba16Float` canvas texture: 100 MP is +/// 800 MB at level 0, about 1.07 GB with mips (twice the `Rgba8Unorm` cost). Bigger 16/32-bit +/// documents (a 14000² one would need 2.1 GB) use `Rgba8Unorm`, so they stay on the GPU like +/// 8-bit ones. `PHOTOCRAFT_CANVAS_F16=0` turns the float canvas off, `=1` ignores this budget. +pub const F16_BUDGET_PX: u64 = 100_000_000; +const VIEW_UNIFORM_SIZE: u64 = 128; +const VIEW_FLOATS: usize = 32; +const TILE_UNIFORM_SIZE: u64 = 16; + +/// Whether this view can use the GPU canvas. Flip and non-square pixel aspect correction are +/// still CPU blits (the shader's filtering assumes square pixels); rotation is a shader uniform. +pub fn gpu_view_ok(flip: bool, _rotation: f32, aspect: f32) -> bool { + !flip && (aspect - 1.0).abs() < 1e-6 +} + +/// Parameters for drawing one document view. Positions are in egui points. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ViewParams { + /// Document key used with [`GpuCanvas::upload_full`]. + pub doc: u64, + /// Document size in pixels. + pub doc_size: [u32; 2], + /// Screen points per document pixel. + pub zoom: f32, + /// Document point shown at the centre of the canvas rect. + pub center: [f32; 2], + /// Camera rotation in radians, clockwise in Y-down screen space. Rotate around [`Self::center`] + /// before sampling. Flip stays on the CPU path. + pub rotation: f32, + /// Draw the drop shadow on the pasteboard. + pub shadow: bool, + /// Draw the pixel grid at high zoom. + pub pixel_grid: bool, + /// Distinguishes views painted in the same frame (main canvas, extra windows). + pub view_key: u64, + /// Display transform: 0 none, 1 the document's display LUT (document → monitor profile, + /// Proof Colors), 2 LUT plus the gamut warning, 3 matrix/shaper (see [`GpuCanvas::set_display_lut`]). + pub display: u8, + /// The display the view is on (its LUT is per document and display, #569; 0 = unknown). + pub output: u32, + /// View › 32-bit Preview Options (exposure in stops, gamma), applied to the texture values + /// before the display LUT; `None` when off. The display LUT must then leave it out + /// (`ColorState::gpu_canvas_lut`). + pub hdr: Option<[f32; 2]>, + /// Where this draw puts the document, in document pixels from its own place: `[0, 0]` for the + /// document, a whole number of widths and heights for a View › Pattern Preview copy (#1067). + /// A copy samples the same texture, so nothing is composited again. + pub offset: [f32; 2], +} + +/// When high-bit documents get an `Rgba16Float` canvas texture. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum HighPolicy { + /// The adapter can't render to or filter `Rgba16Float`, or `PHOTOCRAFT_CANVAS_F16=0`. + Off, + /// Up to [`F16_BUDGET_PX`]. + Budget, + /// Always (`PHOTOCRAFT_CANVAS_F16=1`). + Always, +} + +/// Uploads documents to the GPU and paints them. Cheap to clone. +/// +/// Once the device is lost or reports an uncaptured error (see [`GpuCanvas::fault`]), every +/// method is a no-op or an `Err`, so nothing reaches the GPU again; the app then switches to the +/// CPU canvas (#243). +#[derive(Clone)] +pub struct GpuCanvas { + rs: RenderState, + tile: u32, + high: HighPolicy, + health: photocraft_gpu::DeviceHealth, + /// [`video_memory`] of the adapter, detected once. + vram: Option, + /// [`canvas_budget`], shared with the paint callback's resources: [`GpuCanvas::format_for`] + /// reads it while the renderer is locked. + canvas_budget: std::sync::Arc, + /// Camera Raw's preview pass, built the first time the dialog asks (#6419). + camera_raw: crate::camera_raw_gpu::Slot, + camera_raw_started: std::sync::Arc, +} + +/// Whether `regenerate_mips` builds each level in a scratch texture and copies it back: on +/// Intel adapters under DX12 only, where some drivers corrupt reduced previews when a pass +/// samples one mip level and renders into another of the same texture (#892, Intel UHD 620). +/// Everywhere else it renders straight into the level: on an NVIDIA DX12 adapter the scratch +/// textures, created per level on every refresh, cost about 1 ms of CPU time per brush dab +/// (#4515). `PHOTOCRAFT_SEPARATE_MIPS` (`setting`) forces it on (`1`) or off (`0`). +pub fn separate_mip_targets(backend: wgpu::Backend, vendor: u32, setting: Option<&str>) -> bool { + const INTEL: u32 = 0x8086; + match setting.map(str::trim) { + Some("1") => true, + Some("0") => false, + _ => backend == wgpu::Backend::Dx12 && vendor == INTEL, + } +} + +/// Can `adapter` use `Rgba16Float` as a sampled, filtered, render-target and copy texture? +/// (Core WebGPU guarantees it; WebGL2 needs `EXT_color_buffer_float`, and some drivers lack it.) +pub fn supports_f16_canvas(adapter: &wgpu::Adapter) -> bool { + let f = adapter.get_texture_format_features(FORMAT_HIGH); + let usages = wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::COPY_SRC; + f.allowed_usages.contains(usages) && f.flags.contains(wgpu::TextureFormatFeatureFlags::FILTERABLE) +} + +impl GpuCanvas { + /// Create pipelines and register resources with the egui renderer. + pub fn new(rs: &RenderState) -> Self { + Self::with_tile(rs, None) + } + + /// Like [`GpuCanvas::new`] with a preferred texture tile side (`PHOTOCRAFT_GPU_TILE` wins). + pub fn with_tile(rs: &RenderState, tile: Option) -> Self { + let max = rs.device.limits().max_texture_dimension_2d; + let env_tile = std::env::var("PHOTOCRAFT_GPU_TILE").ok().and_then(|v| v.parse::().ok()); + let tile = env_tile.or(tile).unwrap_or(DEFAULT_TILE).clamp(64, max); + let high = match std::env::var("PHOTOCRAFT_CANVAS_F16").ok().as_deref() { + _ if !supports_f16_canvas(&rs.adapter) => HighPolicy::Off, + Some("0") => HighPolicy::Off, + Some("1") => HighPolicy::Always, + _ => HighPolicy::Budget, + }; + // Device loss and uncaptured errors mark this flag instead of panicking (#243). + let health = photocraft_gpu::DeviceHealth::watch(&rs.device); + let mut res = Resources::new(&rs.device, &rs.queue, rs.target_format, high != HighPolicy::Off); + res.health = health.clone(); + let info = rs.adapter.get_info(); + res.separate_mip_targets = separate_mip_targets(info.backend, info.vendor, std::env::var("PHOTOCRAFT_SEPARATE_MIPS").ok().as_deref()); + let vram = video_memory(&info); + res.canvas_budget.store(canvas_budget(physical_memory(), vram), Ordering::Relaxed); + let budget = res.canvas_budget.clone(); + rs.renderer.write().callback_resources.insert(res); + log::info!( + "gpu canvas: target {:?}, max texture {max}, tile {tile}, 16F canvas {high:?}, video memory {}", + rs.target_format, + vram.map_or_else(|| "unknown".to_owned(), |b| format!("{} MB", b >> 20)) + ); + Self { rs: rs.clone(), tile, high, health, vram, canvas_budget: budget, camera_raw: Default::default(), camera_raw_started: Default::default() } + } + + /// The device's health flag (shared with the wgpu compositor and the paint callback). + pub fn health(&self) -> &photocraft_gpu::DeviceHealth { + &self.health + } + + /// Camera Raw's GPU preview develop on this device; the first call starts building its + /// pipeline. `None` on a software adapter, without `Rgba32Float` render targets, after a + /// fault, or when the driver couldn't build the pipeline; the dialog then develops on the CPU. + pub(crate) fn camera_raw(&self) -> Option { + if self.fault().is_some() { + return None; + } + if !self.camera_raw_started.swap(true, Ordering::AcqRel) { + crate::camera_raw_gpu::Pass::start(&self.rs.adapter, &self.rs.device, &self.camera_raw); + } + if matches!(self.camera_raw.get(), Some(None)) { + return None; + } + Some(crate::camera_raw_gpu::CameraRawGpu::new(self.rs.device.clone(), self.rs.queue.clone(), self.health.clone(), self.camera_raw.clone())) + } + + /// Whether [`Self::camera_raw`] started building the pass. + #[cfg(test)] + pub(crate) fn camera_raw_started(&self) -> bool { + self.camera_raw_started.load(Ordering::Acquire) + } + + /// Waits until the pass is built or refused. + #[cfg(test)] + pub(crate) fn wait_camera_raw_pass(&self) { + let _ = self.camera_raw.wait(); + } + + /// Builds Camera Raw's pass even where [`Self::camera_raw`] wouldn't (egui_kittest's software + /// adapter), so tests drive the GPU develop. + #[cfg(test)] + pub(crate) fn force_camera_raw_pass(&self) { + self.camera_raw_started.store(true, Ordering::Release); + let _ = self.camera_raw.set(crate::camera_raw_gpu::Pass::build_on(&self.rs.device)); + } + + /// Why the GPU can't be used any more (`None` while it can). + pub fn fault(&self) -> Option { + self.health.fault() + } + + /// Free every GPU resource the canvas holds (compositor pages, document textures, LUTs) after + /// a fault; the paint callback draws nothing from then on. + pub fn release(&self) { + let mut r = self.rs.renderer.write(); + if let Some(res) = r.callback_resources.get_mut::() { + res.compositor = None; + res.compositor_failed = Some(photocraft_gpu::Unsupported(self.fault().map_or_else(|| "GPU canvas released".into(), |f| f.to_string()))); + res.docs.clear(); + res.luts.clear(); + res.display_lut_signatures.clear(); + res.views.clear(); + } + } + + /// The adapter this canvas renders with. + pub fn adapter_info(&self) -> wgpu::AdapterInfo { + self.rs.adapter.get_info() + } + + /// The adapter's own memory where it has one and the platform reports it (see + /// [`video_memory`]); it caps [`memory_budget`] and [`canvas_budget`]. + pub fn video_memory(&self) -> Option { + self.vram + } + + /// The canvas texture format for a document of `depth` and `size`: `Rgba16Float` for 16/32-bit + /// documents when the adapter supports it and the document fits [`F16_BUDGET_PX`], else + /// `Rgba8Unorm`. + /// The device's largest 2D texture side (egui textures can use it too). + pub fn max_texture_side(&self) -> usize { + self.rs.device.limits().max_texture_dimension_2d as usize + } + + pub fn format_for(&self, depth: photocraft_doc::SampleType, size: [u32; 2]) -> wgpu::TextureFormat { + let px = size[0] as u64 * size[1] as u64; + let high = match self.high { + HighPolicy::Off => false, + // Within the canvas budget too: a 16-bit canvas a small card can't hold as floats + // stays on the GPU as `Rgba8Unorm` rather than falling back to the CPU canvas. + HighPolicy::Budget => { + px <= F16_BUDGET_PX && canvas_texture_bytes(size, self.tile, texel_bytes(FORMAT_HIGH)) <= self.canvas_budget.load(Ordering::Relaxed) + } + HighPolicy::Always => true, + }; + if high && depth != photocraft_doc::SampleType::U8 { FORMAT_HIGH } else { FORMAT } + } + + /// Format and GPU bytes (all tiles, all mip levels) of document `key`'s canvas texture. + pub fn texture_info(&self, key: u64) -> Option<(wgpu::TextureFormat, u64)> { + let r = self.rs.renderer.read(); + let d = r.callback_resources.get::()?.docs.get(&key)?; + let bpp = texel_bytes(d.format); + let bytes = d + .tiles + .iter() + .map(|t| (0..t.levels.len() as u32).map(|l| ((t.rect[2] >> l).max(1) as u64) * ((t.rect[3] >> l).max(1) as u64) * bpp).sum::()) + .sum(); + Some((d.format, bytes)) + } + + /// Set the GPU memory the wgpu compositor may hold for layer pages and caches (see + /// [`memory_budget`]); pages beyond it are evicted least recently used first. + pub fn set_memory_budget(&self, bytes: u64) { + let mut r = self.rs.renderer.write(); + if let Some(res) = r.callback_resources.get_mut::() { + res.compositor_budget = Some(bytes); + } + } + + /// The compositor's memory budget (`None` until [`GpuCanvas::set_memory_budget`]). + pub fn memory_budget(&self) -> Option { + let r = self.rs.renderer.read(); + r.callback_resources.get::()?.compositor_budget + } + + /// Set the GPU bytes one document's display texture set may take (see [`canvas_budget`]). + pub fn set_canvas_budget(&self, bytes: u64) { + self.canvas_budget.store(bytes, Ordering::Relaxed); + } + + /// Whether `doc`'s display textures fit [`canvas_budget`]; when they don't, nothing is + /// created for it and it is drawn on the CPU canvas. + pub fn fits_canvas(&self, doc: &photocraft_doc::Document) -> bool { + let size = [doc.size.width, doc.size.height]; + let bytes = canvas_texture_bytes(size, self.tile, texel_bytes(self.format_for(doc.depth, size))); + let r = self.rs.renderer.read(); + r.callback_resources.get::().is_some_and(|res| bytes <= res.canvas_budget.load(Ordering::Relaxed)) + } + + /// Cap lower-stack composite reuse; zero disables it for profiling the uncached path. + pub fn set_composite_cache_budget(&self, bytes: u64) { + let mut r = self.rs.renderer.write(); + if let Some(res) = r.callback_resources.get_mut::() { + res.compositor_cache_budget = Some(bytes); + if let Some(comp) = &mut res.compositor { + comp.set_composite_cache_budget(bytes); + } + } + } + + /// The document area the view shows: full refreshes composite it last, so its layer pages + /// are the ones still resident for the edits that follow. + pub fn set_focus(&self, focus: Option) { + let mut r = self.rs.renderer.write(); + if let Some(res) = r.callback_resources.get_mut::() { + res.compositor_focus = focus; + } + } + + /// Take any GPU measurement that has landed since the last call, without compositing + /// anything. [`Compositor::render`] carries measurements out in its stats, but a refresh is + /// the only thing that collects them, so the last refresh before the app goes idle would + /// never be reported. The frame loop calls this so it is. + pub fn take_gpu_timing(&self) -> Option { + let mut r = self.rs.renderer.write(); + r.callback_resources.get_mut::()?.compositor.as_mut()?.take_gpu_timing() + } + + /// GPU bytes the wgpu compositor holds: resident layer pages and caches (effect maps and + /// lower-stack chunks). Keep the scorecard's memory measurements inclusive of reuse. + pub fn compositor_bytes(&self) -> Option<(u64, usize)> { + let r = self.rs.renderer.read(); + let c = r.callback_resources.get::()?.compositor.as_ref()?; + Some((c.resident_bytes(), c.fx_cache_bytes().saturating_add(usize::try_from(c.composite_cache_bytes()).unwrap_or(usize::MAX)))) + } + + /// Whether `doc`'s layers fit the budget as it now stands, measured without a refresh (a GPU + /// Memory change shows in the status bar at once). `None` before the compositor exists. + pub fn measure_fit(&self, doc: &photocraft_doc::Document) -> Option { + let mut r = self.rs.renderer.write(); + let res = r.callback_resources.get_mut::()?; + let budget = res.compositor_budget; + let comp = res.compositor.as_mut()?; + if let Some(b) = budget { + comp.set_memory_budget(b); + } + let needed = comp.working_set(doc, doc.bounds()); + let fit = LayerFit { doc: doc.id.0, needed, budget: comp.fit_layers(needed, true) }; + res.layer_fit = Some(fit); + Some(fit) + } + + /// Whether the layers of the last full (or large) refresh fit the GPU memory budget, and by + /// how much (`None` before the first one). + pub fn layer_fit(&self) -> Option { + let r = self.rs.renderer.read(); + r.callback_resources.get::()?.layer_fit + } + + /// Set the checkerboard and gamut warning colours. + pub fn set_style(&self, style: CanvasStyle) { + let mut r = self.rs.renderer.write(); + if let Some(res) = r.callback_resources.get_mut::() { + res.style = style; + } + } + + /// Whether document `doc` has been uploaded with this size. + pub fn has(&self, doc: u64, size: [u32; 2]) -> bool { + let r = self.rs.renderer.read(); + r.callback_resources.get::().and_then(|res| res.docs.get(&doc)).is_some_and(|d| d.size == size) + } + + /// Whether [`GpuCanvas::composite`] would draw `doc` with the wgpu compositor (rather than + /// fall back to the CPU compositor). + pub fn supports(&self, doc: &photocraft_doc::Document) -> bool { + if std::env::var_os("PHOTOCRAFT_CPU_COMPOSE").is_some() || doc.size.width == 0 || doc.size.height == 0 { + return false; + } + let r = self.rs.renderer.read(); + let Some(res) = r.callback_resources.get::() else { return false }; + if res.compositor_failed.is_some() { + return false; + } + match &res.compositor { + Some(c) => c.supports(doc).is_ok(), + // Layers larger than the texture limit are stored in pages, so any size qualifies. + None => photocraft_gpu::plan(doc).is_ok(), + } + } + + /// Replace the whole document image with an `Rgba8Unorm` texture. `rgba` is premultiplied + /// RGBA8, `size[0] * size[1] * 4` bytes (anything else is ignored). + pub fn upload_full(&self, doc: u64, size: [u32; 2], rgba: &[u8]) { + self.upload_full_as(doc, size, FORMAT, rgba); + } + + /// Replace the whole document image with a `format` texture of premultiplied `texels`. + fn upload_full_as(&self, doc: u64, size: [u32; 2], format: wgpu::TextureFormat, texels: &[u8]) { + if size[0] == 0 || size[1] == 0 || texels.len() as u64 != size[0] as u64 * size[1] as u64 * texel_bytes(format) || !self.health.is_ok() { + return; + } + let (device, queue) = (&self.rs.device, &self.rs.queue); + let mut renderer = self.rs.renderer.write(); + let Some(res) = renderer.callback_resources.get_mut::() else { return }; + if res.docs.get(&doc).is_none_or(|d| d.size != size || d.format != format) { + let Some(tex) = DocTextures::new(device, res, size, self.tile, format) else { + res.docs.remove(&doc); + return; + }; + res.docs.insert(doc, tex); + } + let Some(d) = res.docs.get(&doc) else { return }; + d.write(queue, [0, 0], size, size[0], texels); + d.regenerate_mips(device, queue, res, [0, 0, size[0], size[1]]); + } + + /// Replace a rectangle `origin..origin+size` of an uploaded document with premultiplied texels + /// in its texture format (`size[0] * size[1]` texels: RGBA8 or RGBA16F). Returns false if the + /// document isn't uploaded, the rectangle doesn't fit or the buffer has the wrong size. + pub fn upload_rect(&self, doc: u64, origin: [u32; 2], size: [u32; 2], texels: &[u8]) -> bool { + if !self.health.is_ok() { + return false; + } + let (device, queue) = (&self.rs.device, &self.rs.queue); + let mut renderer = self.rs.renderer.write(); + let Some(res) = renderer.callback_resources.get_mut::() else { return false }; + let Some(d) = res.docs.get(&doc) else { return false }; + if texels.len() as u64 != size[0] as u64 * size[1] as u64 * texel_bytes(d.format) + || origin[0].saturating_add(size[0]) > d.size[0] + || origin[1].saturating_add(size[1]) > d.size[1] + { + return false; + } + if size[0] == 0 || size[1] == 0 { + return true; + } + d.write(queue, origin, size, size[0], texels); + d.regenerate_mips(device, queue, res, [origin[0], origin[1], origin[0] + size[0], origin[1] + size[1]]); + true + } + + /// The texture format of uploaded document `doc`. + fn format_of(&self, doc: u64) -> Option { + let r = self.rs.renderer.read(); + r.callback_resources.get::().and_then(|res| res.docs.get(&doc)).map(|d| d.format) + } + + /// Upload a CPU composite covering the whole document (a preview of a document of `depth`: + /// see [`GpuCanvas::format_for`]). + pub fn upload_buffer_full(&self, doc: u64, buf: &photocraft_compose::Buffer, depth: photocraft_doc::SampleType) { + let size = [buf.rect.width(), buf.rect.height()]; + let format = self.format_for(depth, size); + self.upload_full_as(doc, size, format, &texels(format, &buf.px)); + } + + /// Upload a CPU composite of a sub-rectangle (in document pixels, `buf.rect`). + pub fn upload_buffer_rect(&self, doc: u64, buf: &photocraft_compose::Buffer) -> bool { + let r = buf.rect; + let Some(format) = self.format_of(doc) else { return false }; + if r.x0 < 0 || r.y0 < 0 { + return false; + } + self.upload_rect(doc, [r.x0 as u32, r.y0 as u32], [r.width(), r.height()], &texels(format, &buf.px)) + } + + /// Composite `region` of `doc` with the wgpu compositor straight into its display texture + /// (no CPU pixels, no upload of the composite). `encode_srgb` stores the sRGB encoding of the + /// composite (linear documents, see `photocraft_engine::display_color`). Returns `Err` when the + /// document uses features the GPU compositor doesn't cover yet; the caller then falls back to + /// the CPU compositor. + pub fn composite( + &self, + doc: &photocraft_doc::Document, + region: photocraft_geom::Rect, + encode_srgb: bool, + ) -> Result { + let (device, queue) = (&self.rs.device, &self.rs.queue); + let size = [doc.size.width, doc.size.height]; + if size[0] == 0 || size[1] == 0 { + return Err(photocraft_gpu::Unsupported("empty document".into())); + } + if std::env::var_os("PHOTOCRAFT_CPU_COMPOSE").is_some() { + return Err(photocraft_gpu::Unsupported("disabled by PHOTOCRAFT_CPU_COMPOSE".into())); + } + if let Some(f) = self.fault() { + return Err(photocraft_gpu::Unsupported(f.to_string())); + } + let mut renderer = self.rs.renderer.write(); + let Some(res) = renderer.callback_resources.get_mut::() else { return Err(photocraft_gpu::Unsupported("no GPU canvas".into())) }; + // A driver that couldn't build the pipelines once won't later: stay on the CPU compositor. + if let Some(e) = &res.compositor_failed { + return Err(e.clone()); + } + let mut comp = match res.compositor.take() { + Some(c) => c, + None => match photocraft_gpu::Compositor::try_new_with_format(device, photocraft_gpu::Compositor::preferred_acc_format(&self.rs.adapter)) { + Ok(c) => c, + Err(e) => { + log::warn!("{e}; using the CPU compositor"); + res.compositor_failed = Some(e.clone()); + return Err(e); + } + }, + }; + comp.set_health(self.health.clone()); + // Measured, not waited for: the timestamps come back a frame or two later. + comp.measure_gpu_time(device, queue); + if let Some(b) = res.compositor_budget { + comp.set_memory_budget(b); + } + if let Some(b) = res.compositor_cache_budget { + comp.set_composite_cache_budget(b); + } + comp.set_focus(res.compositor_focus); + let key = doc.id.0; + let format = self.format_for(doc.depth, size); + let fresh = res.docs.get(&key).is_none_or(|d| d.size != size || d.format != format); + let region = if fresh { doc.bounds() } else { region.intersect(&doc.bounds()) }; + // Checked before allocating a new canvas texture only: `render` plans (and refuses) itself. + if fresh && let Err(e) = comp.supports(doc) { + res.compositor = Some(comp); + return Err(e); + } + // A full refresh whose layer pages don't fit the memory budget would re-upload the + // evicted ones every time (no faster than the CPU, and more memory): the banded CPU + // compositor does it (in the background on desktop). So does a large damage rect, such + // as hiding a big layer (#4024); small edits in the view stay on the GPU. + let large = region.width() as u64 * region.height() as u64 >= DEFER_PX; + if region == doc.bounds() || large { + let needed = comp.working_set(doc, region); + let fit = LayerFit { doc: doc.id.0, needed, budget: comp.fit_layers(needed, region == doc.bounds()) }; + res.layer_fit = Some(fit); + if !fit.fits() { + res.compositor = Some(comp); + return Err(photocraft_gpu::Unsupported(OVER_BUDGET.into())); + } + } + if fresh { + let Some(tex) = DocTextures::new(device, res, size, self.tile, format) else { + res.docs.remove(&key); + res.compositor = Some(comp); + return Err(photocraft_gpu::Unsupported(OVER_CANVAS_BUDGET.into())); + }; + res.docs.insert(key, tex); + } + let (Some(pipe), Some(d)) = (res.encode_pipeline(format), res.docs.get(&key)) else { + res.compositor = Some(comp); + return Err(photocraft_gpu::Unsupported(format!("no {format:?} canvas texture or pipeline"))); + }; + let bgl = &res.encode_bgl; + // A float canvas keeps values above 1.0 (32-bit documents, for the 32-bit preview). + let keep_hdr = i32::from(format == FORMAT_HIGH); + // Last-resort guard: a wgpu panic (e.g. polling a device lost mid-refresh) marks the + // device lost instead of taking the app and its documents down. + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + comp.render(device, queue, doc, region, |enc, out| { + for t in &d.tiles { + let [tx, ty, tw, th] = t.rect.map(|v| v as i32); + let r = out.rect.intersect(&photocraft_geom::Rect::from_xywh(tx, ty, tw as u32, th as u32)); + if r.is_empty() { + continue; + } + let offset = [out.rect.x0 - tx, out.rect.y0 - ty, i32::from(encode_srgb), keep_hdr]; + let ubuf = init_buffer(device, "pc_encode", &offset.iter().flat_map(|v| v.to_le_bytes()).collect::>(), wgpu::BufferUsages::UNIFORM); + let bg = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("pc_encode"), + layout: bgl, + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(out.view) }, + wgpu::BindGroupEntry { binding: 1, resource: ubuf.as_entire_binding() }, + ], + }); + let mut pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("pc_encode"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &t.levels[0], + resolve_target: None, + depth_slice: None, + ops: wgpu::Operations { load: wgpu::LoadOp::Load, store: wgpu::StoreOp::Store }, + })], + depth_stencil_attachment: None, + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); + pass.set_pipeline(pipe); + pass.set_bind_group(0, &bg, &[]); + pass.set_scissor_rect((r.x0 - tx) as u32, (r.y0 - ty) as u32, r.width(), r.height()); + pass.draw(0..3, 0..1); + } + }) + })); + let Ok(result) = result else { + self.health.mark(photocraft_gpu::Fault::Lost("the GPU compositor stopped (internal error)".into())); + res.docs.remove(&key); + return Err(photocraft_gpu::Unsupported("GPU device lost".into())); + }; + // Lost during the refresh: its output can't be trusted. + let result = match self.fault() { + Some(f) => Err(photocraft_gpu::Unsupported(f.to_string())), + None => result, + }; + if result.is_ok() { + d.regenerate_mips(device, queue, res, [region.x0 as u32, region.y0 as u32, region.x1 as u32, region.y1 as u32]); + if std::env::var_os("PHOTOCRAFT_GPU_SYNC").is_some() { + // Benchmarking: wait for the GPU so callers can time the whole refresh. + #[cfg(not(target_arch = "wasm32"))] + self.health.wait(device, None); + } + } else if fresh { + res.docs.remove(&key); + } + res.compositor = Some(comp); + result + } + + /// Bring document `key`'s display texture up to date with `doc`: only `damage` when given (a + /// brush stroke on an already uploaded document), else everything. The wgpu compositor renders + /// straight into the texture when it supports the document; otherwise the CPU compositor does. + /// `display` is the canvas colour transform: the GPU path stores the sRGB encoding when it + /// asks for it, and every CPU band or rect goes through its `texture_buffer`. + pub fn refresh( + &self, + key: u64, + doc: &photocraft_doc::Document, + damage: Option, + display: Option<&photocraft_engine::display_color::CanvasDisplay>, + ) -> Refresh { + self.refresh_with(key, doc, damage, display, false) + } + + /// [`GpuCanvas::refresh`], except that with `defer`, a refresh of at least [`DEFER_PX`] the + /// CPU compositor would draw is left to the caller (`background_redraw`): the texture is made + /// ready (keeping what it shows when it already fits) and the kind is [`REFRESH_DEFERRED`]. + pub fn refresh_with( + &self, + key: u64, + doc: &photocraft_doc::Document, + damage: Option, + display: Option<&photocraft_engine::display_color::CanvasDisplay>, + defer: bool, + ) -> Refresh { + if let Some(f) = self.fault() { + // Nothing reaches the GPU any more; the app switches to the CPU canvas. + return Refresh { kind: "lost", fallback: Some(f.to_string()), ..Default::default() }; + } + if !self.fits_canvas(doc) { + // Neither compositor can fill textures that are never created: the CPU canvas draws + // it. A set left from before the canvas grew is stale, so it goes too. + if let Some(res) = self.rs.renderer.write().callback_resources.get_mut::() { + res.docs.remove(&key); + } + return Refresh { kind: REFRESH_OVER_BUDGET, fallback: Some(OVER_CANVAS_BUDGET.into()), ..Default::default() }; + } + let bounds = doc.bounds(); + let size = [doc.size.width, doc.size.height]; + let format = self.format_for(doc.depth, size); + let damage = damage.filter(|_| self.has(key, size) && self.format_of(key) == Some(format)).map(|r| r.intersect(&bounds)); + let t0 = now_ms(); + let mut out = Refresh::default(); + if damage.is_some_and(|r| r.is_empty()) { + // Nothing changed on the canvas (selecting a layer, say): don't even plan. + out.kind = "rect"; + return out; + } + let region = damage.unwrap_or(bounds); + let encode_srgb = display.is_some_and(|d| d.encode_srgb); + let gpu = if key == doc.id.0 { self.composite(doc, region, encode_srgb) } else { Err(photocraft_gpu::Unsupported("preview texture".into())) }; + match gpu { + Ok(stats) => { + out.kind = if damage.is_some() { "gpu-rect" } else { "gpu-full" }; + out.px = region.width() as u64 * region.height() as u64; + // Encoding and submitting only: the GPU is still running this work. + out.composite_ms = now_ms() - t0; + out.uploads = stats.tiles_uploaded as u64; + out.gpu = stats.gpu_time; + return out; + } + Err(e) => out.fallback = Some(e.0), + } + let px = region.width() as u64 * region.height() as u64; + if defer && px >= DEFER_PX && self.prepare_texture(key, doc).is_some() { + out.kind = REFRESH_DEFERRED; + out.px = px; + return out; + } + if let Some(r) = damage { + if r.is_empty() { + out.kind = "rect"; + return out; + } + let buf = photocraft_compose::render(doc, r); + let t1 = now_ms(); + if self.upload_buffer_rect(key, &texture_buffer(display, &buf)) { + out.kind = "rect"; + out.px = r.width() as u64 * r.height() as u64; + out.composite_ms = t1 - t0; + out.upload_ms = now_ms() - t1; + return out; + } + } + self.upload_composite(key, doc, display); + out.kind = "full"; + out.px = bounds.width() as u64 * bounds.height() as u64; + out.composite_ms = now_ms() - t0; + out + } + + /// Composite the whole of `doc` with the CPU compositor into document `key`'s texture, band by + /// band (each band converted and uploaded before the next is rendered), so a huge document + /// never needs a full-size float composite or texture-format copy in memory. + pub fn upload_composite(&self, key: u64, doc: &photocraft_doc::Document, display: Option<&photocraft_engine::display_color::CanvasDisplay>) { + let size = [doc.size.width, doc.size.height]; + let Some(format) = self.prepare_texture(key, doc) else { return }; + let (device, queue) = (&self.rs.device, &self.rs.queue); + let mut rgba = Vec::new(); + let _ = photocraft_compose::render_bands(doc, doc.bounds(), 0, |band| -> Result<(), ()> { + if !self.health.is_ok() { + return Err(()); + } + texels_into(format, &texture_buffer(display, &band).px, &mut rgba); + let renderer = self.rs.renderer.read(); + let d = renderer.callback_resources.get::().and_then(|r| r.docs.get(&key)).ok_or(())?; + d.write(queue, [0, band.rect.y0 as u32], [size[0], band.rect.height()], size[0], &rgba); + drop(renderer); + // Flush the staged band so its staging memory is reclaimed while the next renders. + queue.submit(std::iter::empty::()); + self.health.poll(device); + Ok(()) + }); + if !self.health.is_ok() { + return; + } + let mut renderer = self.rs.renderer.write(); + if let Some(res) = renderer.callback_resources.get_mut::() + && let Some(d) = res.docs.get(&key) + { + d.regenerate_mips(device, queue, res, [0, 0, size[0], size[1]]); + } + } + + /// Make sure document `key` has a display texture of `doc`'s size and format, keeping the one + /// it has when that fits. Returns its format, or `None` when it can't be created. + pub fn prepare_texture(&self, key: u64, doc: &photocraft_doc::Document) -> Option { + let size = [doc.size.width, doc.size.height]; + if size[0] == 0 || size[1] == 0 || !self.health.is_ok() { + return None; + } + let format = self.format_for(doc.depth, size); + let mut renderer = self.rs.renderer.write(); + let res = renderer.callback_resources.get_mut::()?; + if res.docs.get(&key).is_none_or(|d| d.size != size || d.format != format) { + let Some(tex) = DocTextures::new(&self.rs.device, res, size, self.tile, format) else { + res.docs.remove(&key); + return None; + }; + res.docs.insert(key, tex); + } + Some(format) + } + + /// Free textures, display LUTs and their signatures for documents not in `live`. + pub fn retain(&self, live: &[u64]) { + let mut renderer = self.rs.renderer.write(); + let Some(res) = renderer.callback_resources.get_mut::() else { return }; + if res.docs.keys().any(|k| !live.contains(k)) { + res.docs.retain(|k, _| live.contains(k)); + } + // Everything the compositor holds for documents that aren't open, also when their + // texture entry was dropped earlier (over budget, a failed render), which used to leave + // their pages and effect maps resident after closing (#4529). + if let Some(c) = res.compositor.as_mut() { + c.retain_docs(|d| live.contains(&d.0)); + } + // LUTs and identity-transform signatures can outlive document textures. Prune both, + // or a preserved-ID reopen can skip rebuilding a missing LUT. + res.luts.retain(|k, _| live.contains(&k.0)); + res.display_lut_signatures.retain(|k, _| live.contains(&k.0)); + } + + pub(crate) fn display_lut_signature(&self, doc: u64, output: u32) -> Option<(u64, u8)> { + let renderer = self.rs.renderer.read(); + renderer.callback_resources.get::()?.display_lut_signatures.get(&(doc, output)).copied() + } + + /// Whether document `doc` has a display LUT for display `output` (tests). + #[cfg(test)] + pub(crate) fn has_display_lut(&self, doc: u64, output: u32) -> bool { + let renderer = self.rs.renderer.read(); + renderer.callback_resources.get::().is_some_and(|r| r.luts.contains_key(&(doc, output))) + } + + pub(crate) fn cache_display_lut_signature(&self, doc: u64, output: u32, signature: u64, mode: u8) { + let mut renderer = self.rs.renderer.write(); + if let Some(res) = renderer.callback_resources.get_mut::() { + res.display_lut_signatures.insert((doc, output), (signature, mode)); + } + } + + /// Set (or clear with `None`) the display LUT of document `doc` on display `output`: + /// `size`³ RGBA8 texels, red fastest. RGB is the display colour for each lattice input; + /// alpha 255 marks out-of-gamut colours for the gamut warning. + pub fn set_display_lut(&self, doc: u64, output: u32, size: u32, rgba: Option<&[u8]>) { + if !self.health.is_ok() { + return; + } + let (device, queue) = (&self.rs.device, &self.rs.queue); + let mut renderer = self.rs.renderer.write(); + let Some(res) = renderer.callback_resources.get_mut::() else { return }; + res.display_lut_signatures.remove(&(doc, output)); + match rgba { + None => { + res.luts.remove(&(doc, output)); + } + Some(bytes) => { + if size < 2 || bytes.len() as u64 != (size as u64).pow(3) * 4 { + log::warn!("set_display_lut: {} bytes for a {size}³ LUT; ignored", bytes.len()); + return; + } + let bg = lut_bind_group(device, queue, &res.lut_bgl, size, bytes, None); + res.luts.insert((doc, output), bg); + } + } + } + + /// Set a separately sampled curve/matrix/curve display transform. CMS validates this + /// representation and provides bounded tables; no profile interpretation lives in the UI. + pub fn set_display_matrix_shaper(&self, doc: u64, output: u32, shaper: &photocraft_cms::GpuMatrixShaper) { + if !self.health.is_ok() { + return; + } + let mut renderer = self.rs.renderer.write(); + let Some(res) = renderer.callback_resources.get_mut::() else { return }; + let bg = lut_bind_group(&self.rs.device, &self.rs.queue, &res.lut_bgl, 2, &identity_lut_bytes(), Some(shaper)); + res.display_lut_signatures.remove(&(doc, output)); + res.luts.insert((doc, output), bg); + } + + /// Read back level 0 of document `key`'s canvas texture: its format, size and the stored + /// (premultiplied) texels as `f32` RGBA, row-major. Waits for the GPU; for tests, benchmarks + /// and debugging. + #[cfg(not(target_arch = "wasm32"))] + pub fn read_texels(&self, key: u64) -> Option<(wgpu::TextureFormat, [u32; 2], Vec<[f32; 4]>)> { + if !self.health.is_ok() { + return None; + } + let (device, queue) = (&self.rs.device, &self.rs.queue); + let renderer = self.rs.renderer.read(); + let d = renderer.callback_resources.get::()?.docs.get(&key)?; + let bpp = texel_bytes(d.format); + let (w, h) = (d.size[0] as usize, d.size[1] as usize); + let mut out = vec![[0.0f32; 4]; w.checked_mul(h)?]; + for t in &d.tiles { + let [tx, ty, tw, th] = t.rect; + let row = (tw as u64 * bpp).next_multiple_of(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT as u64); + let buf = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("pc_canvas_readback"), + size: row * th as u64, + usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, + mapped_at_creation: false, + }); + let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("pc_canvas_readback") }); + enc.copy_texture_to_buffer( + t.texture.as_image_copy(), + wgpu::TexelCopyBufferInfo { + buffer: &buf, + layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(row as u32), rows_per_image: Some(th) }, + }, + wgpu::Extent3d { width: tw, height: th, depth_or_array_layers: 1 }, + ); + queue.submit([enc.finish()]); + let slice = buf.slice(..); + slice.map_async(wgpu::MapMode::Read, |_| {}); + if !self.health.wait(device, None) { + return None; + } + let data = slice.get_mapped_range().ok()?; + for y in 0..th as usize { + let src = data.get(y * row as usize..)?; + for x in 0..tw as usize { + let o = out.get_mut((ty as usize + y) * w + tx as usize + x)?; + *o = texel_to_f32(d.format, src.get(x * bpp as usize..(x + 1) * bpp as usize)?); + } + } + } + Some((d.format, d.size, out)) + } + + /// Add the paint callback drawing `params` into `rect` (clipped by the painter's clip rect). + pub fn paint(painter: &egui::Painter, rect: egui::Rect, params: ViewParams) { + painter.add(egui_wgpu::Callback::new_paint_callback(rect, CanvasCallback { rect, params })); + } +} + +#[cfg(test)] +mod mip_tests; + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/canvas/gpu_canvas/budget.rs b/crates/ui-egui/src/canvas/gpu_canvas/budget.rs new file mode 100644 index 0000000000..c98870130f --- /dev/null +++ b/crates/ui-egui/src/canvas/gpu_canvas/budget.rs @@ -0,0 +1,184 @@ +use super::doc_textures::mip_count; +use super::*; + +/// Floor of the compositor's memory budget: enough for a viewport's pages of a dozen layers. +pub const MIN_GPU_BUDGET: u64 = 512 << 20; + +/// Why a full refresh whose layer pages don't fit [`memory_budget`] (or GPU memory) goes to the +/// CPU compositor. +pub const OVER_BUDGET: &str = photocraft_gpu::OVER_BUDGET; + +/// GPU memory the wgpu compositor may hold for layer pages and effect maps. +/// +/// `fixed` (Preferences › Performance › GPU Memory, bytes) sets it when it isn't 0, within +/// [`vram_share`] of a discrete GPU's own memory (`vram`, from [`video_memory`]). Otherwise it is +/// Memory Usage (`allowance`) within a quarter of physical memory (`ram`; 16 GB assumed when +/// unknown) and the VRAM share. The document's pixels and History (`pixels`) come off Memory Usage +/// unless the card's own memory is known: a discrete card doesn't hold them, while integrated and +/// software adapters (and a card whose memory can't be read) share the system's. Never below +/// [`MIN_GPU_BUDGET`]. Layers beyond it redraw full refreshes on the CPU ([`OVER_BUDGET`]). +pub fn memory_budget(allowance: u64, pixels: u64, ram: Option, vram: Option, fixed: u64) -> u64 { + let card = vram.map_or(u64::MAX, vram_share); + if fixed > 0 { + return fixed.min(card).max(MIN_GPU_BUDGET); + } + let ram = ram.unwrap_or(16 << 30); + let charged = if vram.is_some() { 0 } else { pixels }; + allowance.saturating_sub(charged).min(ram / 4).min(card).max(MIN_GPU_BUDGET) +} + +/// The share of a discrete GPU's memory each of [`memory_budget`] and [`canvas_budget`] may +/// plan for: three eighths, so the two together leave a quarter of the card to the window's +/// swapchain, egui and other applications instead of over-committing it and letting the driver +/// page (#4536). +pub fn vram_share(vram: u64) -> u64 { + vram / 8 * 3 +} + +/// Why a document whose display textures don't fit [`canvas_budget`] is drawn on the CPU canvas. +pub const OVER_CANVAS_BUDGET: &str = "the canvas exceeds the GPU texture budget; drawing it on the CPU canvas"; + +/// [`Refresh::kind`] when the document's display textures don't fit [`canvas_budget`]: nothing +/// was created, and the caller draws the CPU canvas instead. +pub const REFRESH_OVER_BUDGET: &str = "over-budget"; + +/// [`Refresh::kind`] of a CPU refresh left to the caller ([`GpuCanvas::refresh_with`]). +pub const REFRESH_DEFERRED: &str = "deferred"; + +/// The smallest CPU refresh (pixels) [`GpuCanvas::refresh_with`] defers: below it, the +/// synchronous composite takes a fraction of a second even with many layers. +pub const DEFER_PX: u64 = 1 << 22; + +/// GPU bytes one document's display texture set (every tile and mip level) may take: a quarter +/// of physical memory (`ram`; 16 GB assumed when unknown) and at most [`vram_share`] of a +/// discrete GPU's own memory (`vram`), at least [`MIN_GPU_BUDGET`]. The set covers the whole +/// canvas at full resolution, so its size follows the declared canvas, not the layer pixels; a +/// larger canvas is drawn on the (reduced) CPU canvas instead (#2934). +pub fn canvas_budget(ram: Option, vram: Option) -> u64 { + (ram.unwrap_or(16 << 30) / 4).min(vram.map_or(u64::MAX, vram_share)).max(MIN_GPU_BUDGET) +} + +/// GPU bytes of a display texture set for a `size` canvas in `tile`-sided tiles of `bpp` bytes +/// per texel, with every mip level (what [`GpuCanvas::texture_info`] reports once it exists). +/// Closed form over the (at most four) distinct tile shapes, so any size is cheap to price. +pub fn canvas_texture_bytes(size: [u32; 2], tile: u32, bpp: u64) -> u64 { + let tile = tile.max(1); + // (how many tiles, their side) along one axis: whole tiles, then the remainder. + let spans = |n: u32| [(n / tile, tile), (u32::from(!n.is_multiple_of(tile)), n % tile)]; + let mut total = 0u64; + for (nx, w) in spans(size[0]) { + for (ny, h) in spans(size[1]) { + if nx == 0 || ny == 0 { + continue; + } + let one = (0..mip_count(w, h)).map(|l| u64::from((w >> l).max(1)) * u64::from((h >> l).max(1)) * bpp).fold(0, u64::saturating_add); + total = total.saturating_add(one.saturating_mul(u64::from(nx) * u64::from(ny))); + } + } + total +} + +/// Physical memory of this machine in bytes, if known. `PHOTOCRAFT_RAM_MB` overrides it (to +/// simulate a smaller machine). +pub fn physical_memory() -> Option { + static RAM: std::sync::OnceLock> = std::sync::OnceLock::new(); + *RAM.get_or_init(|| { + if let Some(mb) = std::env::var("PHOTOCRAFT_RAM_MB").ok().and_then(|v| v.trim().parse::().ok()) { + return mb.checked_mul(1 << 20); + } + detect_physical_memory() + }) +} + +#[cfg(target_os = "macos")] +fn detect_physical_memory() -> Option { + let out = std::process::Command::new("/usr/sbin/sysctl").args(["-n", "hw.memsize"]).output().ok()?; + String::from_utf8(out.stdout).ok()?.trim().parse().ok() +} + +#[cfg(target_os = "linux")] +fn detect_physical_memory() -> Option { + let info = std::fs::read_to_string("/proc/meminfo").ok()?; + let kb: u64 = info.lines().find_map(|l| l.strip_prefix("MemTotal:"))?.trim().trim_end_matches("kB").trim().parse().ok()?; + kb.checked_mul(1024) +} + +#[cfg(target_os = "freebsd")] +fn detect_physical_memory() -> Option { + let out = std::process::Command::new("/sbin/sysctl").args(["-n", "hw.physmem"]).output().ok()?; + String::from_utf8(out.stdout).ok()?.trim().parse().ok() +} + +#[cfg(windows)] +pub(super) fn detect_physical_memory() -> Option { + winsafe::GlobalMemoryStatusEx().map(|m| m.ullTotalPhys).ok().filter(|b| *b > 0) +} + +#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "freebsd", windows)))] +fn detect_physical_memory() -> Option { + None +} + +/// The memory of `adapter` itself, in bytes, when it is a discrete GPU and the platform reports +/// it: DXGI's dedicated video memory on Windows, amdgpu's VRAM size on Linux. `None` for +/// integrated and software adapters, whose textures live in system memory (the RAM-based +/// budgets already cover them), and where nothing reports it. `PHOTOCRAFT_VRAM_MB` overrides it +/// for any adapter, simulating a discrete card of that size: on an integrated GPU the budget then +/// stops charging the document's pixels too, as for a real card (a development switch). +pub fn video_memory(adapter: &wgpu::AdapterInfo) -> Option { + if let Some(mb) = std::env::var("PHOTOCRAFT_VRAM_MB").ok().and_then(|v| v.trim().parse::().ok()) { + return mb.checked_mul(1 << 20).filter(|b| *b > 0); + } + if adapter.device_type != wgpu::DeviceType::DiscreteGpu { + return None; + } + // Detected once per adapter, as `physical_memory` is: on Windows each detection builds a + // DXGI factory, and startup asks three times. Keyed by the adapter, since a GPU retry can + // pick another one. + /// (vendor, device) ids and the memory found for them. + type Seen = Vec<((u32, u32), Option)>; + static SEEN: std::sync::Mutex = std::sync::Mutex::new(Vec::new()); + let key = (adapter.vendor, adapter.device); + let mut seen = SEEN.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + if let Some((_, bytes)) = seen.iter().find(|(k, _)| *k == key) { + return *bytes; + } + let bytes = detect_video_memory(key.0, key.1).filter(|b| *b > 0); + seen.push((key, bytes)); + bytes +} + +#[cfg(windows)] +pub(super) fn detect_video_memory(vendor: u32, device: u32) -> Option { + use winsafe::prelude::*; + let factory = winsafe::CreateDXGIFactory1().ok()?; + factory + .EnumAdapters1() + .filter_map(|a| a.ok()?.GetDesc1().ok()) + .find(|d| d.VendorId == vendor && d.DeviceId == device) + .and_then(|d| u64::try_from(d.DedicatedVideoMemory).ok()) +} + +#[cfg(target_os = "linux")] +fn detect_video_memory(vendor: u32, device: u32) -> Option { + drm_video_memory(std::path::Path::new("/sys/class/drm"), vendor, device) +} + +/// amdgpu's VRAM size (`/device/mem_info_vram_total`, bytes) of the card under `drm` (the +/// sysfs `/sys/class/drm` folder) whose PCI `vendor` and `device` ids (hex files beside it) match. +#[cfg(any(target_os = "linux", test))] +pub(super) fn drm_video_memory(drm: &std::path::Path, vendor: u32, device: u32) -> Option { + let hex = |p: std::path::PathBuf| u32::from_str_radix(std::fs::read_to_string(p).ok()?.trim().trim_start_matches("0x"), 16).ok(); + std::fs::read_dir(drm).ok()?.flatten().find_map(|card| { + let dev = card.path().join("device"); + if hex(dev.join("vendor"))? != vendor || hex(dev.join("device"))? != device { + return None; + } + std::fs::read_to_string(dev.join("mem_info_vram_total")).ok()?.trim().parse().ok() + }) +} + +#[cfg(not(any(target_os = "linux", windows)))] +fn detect_video_memory(_vendor: u32, _device: u32) -> Option { + None +} diff --git a/crates/ui-egui/src/canvas/gpu_canvas/callback.rs b/crates/ui-egui/src/canvas/gpu_canvas/callback.rs new file mode 100644 index 0000000000..c128a8f297 --- /dev/null +++ b/crates/ui-egui/src/canvas/gpu_canvas/callback.rs @@ -0,0 +1,207 @@ +use super::resources::{CanvasStyle, Resources, ViewGpu, f32_bytes}; +use super::*; + +// --------------------------------------------------------------------------------------------- +// Per-frame callback + +pub(super) struct CanvasCallback { + pub(super) rect: egui::Rect, + pub(super) params: ViewParams, +} + +/// Sampling mode: 0 trilinear, 1 bilinear, 2 anti-aliased nearest. +pub(super) fn filter_mode(scale: f32) -> (f32, f32) { + if scale < 0.999 { + (0.0, (-scale.log2()).max(0.0)) + } else if (scale - scale.round()).abs() < 1e-3 || scale >= 2.0 { + (2.0, 0.0) + } else { + (1.0, 0.0) + } +} + +pub(super) fn map_doc_px(origin: [f32; 2], scale: f32, center: [f32; 2], cos: f32, sin: f32, x: f32, y: f32) -> [f32; 2] { + let dx = x - center[0]; + let dy = y - center[1]; + let rx = dx * cos - dy * sin; + let ry = dx * sin + dy * cos; + [origin[0] + center[0] * scale + rx * scale, origin[1] + center[1] * scale + ry * scale] +} + +pub(super) fn tile_screen_aabb(origin: [f32; 2], scale: f32, center: [f32; 2], cos: f32, sin: f32, tile: [f32; 4]) -> (f32, f32, f32, f32) { + let [tx, ty, tw, th] = tile; + if sin.abs() < 1e-8 && (cos - 1.0).abs() < 1e-8 { + let x0 = origin[0] + tx * scale; + let y0 = origin[1] + ty * scale; + return (x0, y0, x0 + tw * scale, y0 + th * scale); + } + let pts = [ + map_doc_px(origin, scale, center, cos, sin, tx, ty), + map_doc_px(origin, scale, center, cos, sin, tx + tw, ty), + map_doc_px(origin, scale, center, cos, sin, tx + tw, ty + th), + map_doc_px(origin, scale, center, cos, sin, tx, ty + th), + ]; + let mut x0 = pts[0][0]; + let mut y0 = pts[0][1]; + let mut x1 = x0; + let mut y1 = y0; + for p in pts { + x0 = x0.min(p[0]); + y0 = y0.min(p[1]); + x1 = x1.max(p[0]); + y1 = y1.max(p[1]); + } + (x0, y0, x1, y1) +} + +impl CanvasCallback { + /// Screen-pixel origin of document (0, 0) (snapped to whole pixels) and device px per doc px. + fn placement(&self, ppp: f32) -> ([f32; 2], f32) { + let p = &self.params; + let scale = p.zoom * ppp; + let c = self.rect.center(); + let ox = (c.x * ppp - p.center[0] * scale).round(); + let oy = (c.y * ppp - p.center[1] * scale).round(); + ([ox, oy], scale) + } + + fn uniforms(&self, screen: [u32; 2], ppp: f32, out_linear: bool, style: &CanvasStyle) -> [f32; VIEW_FLOATS] { + let p = &self.params; + let (origin, scale) = self.placement(ppp); + let (mode, lod) = filter_mode(scale); + // The pixel grid shows above 500% (the constants are shared with the CPU path, + // pixel_grid.rs). `p.zoom` is screen points per document pixel; the shared threshold is + // in device pixels, so scale by the display's pixels per point. + let grid = if p.pixel_grid && crate::pixel_grid::shows_at(p.zoom * ppp) { crate::pixel_grid::STRENGTH } else { 0.0 }; + let square = if style.checker_square > 0.0 { (style.checker_square * ppp).round().max(1.0) } else { 0.0 }; + let (l, d, g) = (style.checker_light, style.checker_dark, style.gamut_color); + // 32-bit preview: linear-light gain 2^exposure (0 = off) and 1 / gamma. + let (gain, inv_gamma) = match p.hdr { + Some([e, gm]) if e.is_finite() && gm.is_finite() && gm > 0.0 => (2f32.powf(e.clamp(-20.0, 20.0)), 1.0 / gm.max(0.01)), + _ => (0.0, 1.0), + }; + [ + screen[0] as f32, + screen[1] as f32, + scale, + ppp, + origin[0], + origin[1], + p.doc_size[0] as f32, + p.doc_size[1] as f32, + mode, + lod, + grid, + square, + if p.offset[0].is_finite() { p.offset[0] } else { 0.0 }, + if p.offset[1].is_finite() { p.offset[1] } else { 0.0 }, + p.display as f32, + if out_linear { 1.0 } else { 0.0 }, + l[0], + l[1], + l[2], + style.gamut_opacity, + d[0], + d[1], + d[2], + gain, + g[0], + g[1], + g[2], + inv_gamma, + { + let r = if p.rotation.is_finite() { p.rotation } else { 0.0 }; + if r.abs() < 1e-8 { 1.0 } else { r.cos() } + }, + { + let r = if p.rotation.is_finite() { p.rotation } else { 0.0 }; + if r.abs() < 1e-8 { 0.0 } else { r.sin() } + }, + p.center[0], + p.center[1], + ] + } +} + +impl CallbackTrait for CanvasCallback { + fn prepare( + &self, + device: &wgpu::Device, + queue: &wgpu::Queue, + screen: &ScreenDescriptor, + _encoder: &mut wgpu::CommandEncoder, + resources: &mut CallbackResources, + ) -> Vec { + let Some(res) = resources.get_mut::() else { return Vec::new() }; + if !res.health.is_ok() { + return Vec::new(); + } + let data = self.uniforms(screen.size_in_pixels, screen.pixels_per_point, res.out_linear, &res.style); + let (bgl, sampler) = (&res.view_bgl, &res.sampler); + let v = res.views.entry(self.params.view_key).or_insert_with(|| { + let buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("pc_canvas_view"), + size: VIEW_UNIFORM_SIZE, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("pc_canvas_view"), + layout: bgl, + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: buffer.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Sampler(sampler) }, + ], + }); + ViewGpu { buffer, bind_group, frame_data: [f32::NAN; VIEW_FLOATS] } + }); + if v.frame_data != data { + queue.write_buffer(&v.buffer, 0, &f32_bytes(&data)); + v.frame_data = data; + } + Vec::new() + } + + fn paint(&self, info: egui::PaintCallbackInfo, pass: &mut wgpu::RenderPass<'static>, resources: &CallbackResources) { + let Some(res) = resources.get::() else { return }; + if !res.health.is_ok() { + return; + } + let Some(view) = res.views.get(&self.params.view_key) else { return }; + let [sw, sh] = info.screen_size_px; + let clip = info.clip_rect_in_pixels(); + if clip.width_px <= 0 || clip.height_px <= 0 || sw == 0 || sh == 0 { + return; + } + // Work in whole-screen pixel coordinates; the scissor does the clipping. + pass.set_viewport(0.0, 0.0, sw as f32, sh as f32, 0.0, 1.0); + pass.set_scissor_rect(clip.left_px.max(0) as u32, clip.top_px.max(0) as u32, clip.width_px as u32, clip.height_px as u32); + pass.set_bind_group(0, &view.bind_group, &[]); + if self.params.shadow { + pass.set_pipeline(&res.shadow_pipeline); + pass.draw(0..6, 0..1); + } + let Some(doc) = res.docs.get(&self.params.doc) else { return }; + if doc.size != self.params.doc_size { + return; + } + let (origin, scale) = self.placement(info.pixels_per_point); + let (cx0, cy0) = (clip.left_px as f32, clip.top_px as f32); + let (cx1, cy1) = (cx0 + clip.width_px as f32, cy0 + clip.height_px as f32); + let rot = if self.params.rotation.is_finite() { self.params.rotation } else { 0.0 }; + let (cos, sin) = if rot.abs() < 1e-8 { (1.0, 0.0) } else { (rot.cos(), rot.sin()) }; + let cen = self.params.center; + let [ox, oy] = self.params.offset.map(|v| if v.is_finite() { v } else { 0.0 }); + pass.set_pipeline(&res.tile_pipeline); + pass.set_bind_group(2, res.luts.get(&(self.params.doc, self.params.output)).unwrap_or(&res.identity_lut), &[]); + for t in &doc.tiles { + let [tx, ty, tw, th] = t.rect.map(|v| v as f32); + let (x0, y0, x1, y1) = tile_screen_aabb(origin, scale, cen, cos, sin, [tx + ox, ty + oy, tw, th]); + if x1 < cx0 || y1 < cy0 || x0 > cx1 || y0 > cy1 { + continue; + } + pass.set_bind_group(1, &t.bind_group, &[]); + pass.draw(0..6, 0..1); + } + } +} diff --git a/crates/ui-egui/src/canvas/gpu_canvas/doc_textures.rs b/crates/ui-egui/src/canvas/gpu_canvas/doc_textures.rs new file mode 100644 index 0000000000..05a40faa1a --- /dev/null +++ b/crates/ui-egui/src/canvas/gpu_canvas/doc_textures.rs @@ -0,0 +1,206 @@ +use super::budget::canvas_texture_bytes; +use super::resources::{DocTextures, Resources, Tile, f32_bytes}; +use super::texels::texel_bytes; +use super::*; + +pub(super) fn mip_count(w: u32, h: u32) -> u32 { + 32 - w.max(h).max(1).leading_zeros() +} + +/// The rect (x0, y0, x1, y1) of a `lw`×`lh` mip level to redraw when `prev` changed in the level +/// above: that damage halved and padded by one texel for odd-size rounding, or the whole level +/// when it is at most [`WHOLE_MIP_SIDE`] on either side. On AMD's Vulkan driver a pass that draws +/// only part of a level of 64 px or less corrupts texels outside its scissor, at the level's +/// top-left (#6418: RX 6900 XT, driver 26.8.1; DX12 on the same card is fine). Such a level costs +/// next to nothing to redraw, so this holds for every adapter; the levels after it are smaller +/// still, so the rest of the chain is redrawn whole too. +pub(super) fn mip_damage([x0, y0, x1, y1]: [u32; 4], lw: u32, lh: u32) -> [u32; 4] { + if lw.max(lh) <= WHOLE_MIP_SIDE { + return [0, 0, lw, lh]; + } + [(x0 / 2).saturating_sub(1), (y0 / 2).saturating_sub(1), (x1.div_ceil(2) + 1).min(lw), (y1.div_ceil(2) + 1).min(lh)] +} + +/// A buffer holding `contents`, like `DeviceExt::create_buffer_init` but without its panic when +/// the device was lost (an invalid buffer has no mapped range): the buffer is then just invalid. +pub(super) fn init_buffer(device: &wgpu::Device, label: &str, contents: &[u8], usage: wgpu::BufferUsages) -> wgpu::Buffer { + let size = (contents.len() as u64).next_multiple_of(wgpu::COPY_BUFFER_ALIGNMENT).max(wgpu::COPY_BUFFER_ALIGNMENT); + let buffer = device.create_buffer(&wgpu::BufferDescriptor { label: Some(label), size, usage, mapped_at_creation: true }); + if let Ok(mut view) = buffer.slice(..).get_mapped_range_mut() + && view.len() >= contents.len() + { + view.slice(..contents.len()).copy_from_slice(contents); + } + buffer.unmap(); + buffer +} + +impl DocTextures { + /// The texture set for a `size` canvas, or `None` (nothing created) when it doesn't fit + /// the canvas budget or the GPU's memory. A set the GPU can't hold (a 3 GP canvas is 16 GB + /// of textures, #4017) lowers the budget below it, so that canvas and larger ones are drawn + /// on the CPU canvas instead of the out-of-memory error disabling the GPU for the session. + pub(super) fn new(device: &wgpu::Device, res: &Resources, size: [u32; 2], tile: u32, format: wgpu::TextureFormat) -> Option { + let bytes = canvas_texture_bytes(size, tile, texel_bytes(format)); + if bytes > res.canvas_budget.load(Ordering::Relaxed) { + return None; + } + let validation = device.push_error_scope(wgpu::ErrorFilter::Validation); + let memory = device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); + let set = Self::create(device, res, size, tile, format); + // Native wgpu reports these synchronously; where they arrive later (WebGPU) none is seen. + let mut cx = std::task::Context::from_waker(std::task::Waker::noop()); + let mut error = None; + for pop in [memory.pop(), validation.pop()] { + if let std::task::Poll::Ready(Some(e)) = std::pin::pin!(pop).poll(&mut cx) { + error.get_or_insert(e); + } + } + if let Some(e) = error { + log::warn!("{} MB of canvas textures failed ({e}); larger canvases are drawn on the CPU", bytes >> 20); + res.canvas_budget.fetch_min(bytes.saturating_sub(1), Ordering::Relaxed); + return None; + } + Some(set) + } + + fn create(device: &wgpu::Device, res: &Resources, size: [u32; 2], tile: u32, format: wgpu::TextureFormat) -> Self { + let mut tiles = Vec::new(); + for ty in (0..size[1]).step_by(tile as usize) { + for tx in (0..size[0]).step_by(tile as usize) { + let (w, h) = (tile.min(size[0] - tx), tile.min(size[1] - ty)); + let levels_n = mip_count(w, h); + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: Some("pc_canvas_tile"), + size: wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }, + mip_level_count: levels_n, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format, + usage: wgpu::TextureUsages::TEXTURE_BINDING + | wgpu::TextureUsages::COPY_DST + | wgpu::TextureUsages::COPY_SRC + | wgpu::TextureUsages::RENDER_ATTACHMENT, + view_formats: &[], + }); + let levels = (0..levels_n) + .map(|l| texture.create_view(&wgpu::TextureViewDescriptor { base_mip_level: l, mip_level_count: Some(1), ..Default::default() })) + .collect(); + let full = texture.create_view(&wgpu::TextureViewDescriptor::default()); + let uniform = init_buffer(device, "pc_canvas_tile", &f32_bytes(&[tx as f32, ty as f32, w as f32, h as f32]), wgpu::BufferUsages::UNIFORM); + let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("pc_canvas_tile"), + layout: &res.tile_bgl, + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&full) }, + wgpu::BindGroupEntry { binding: 1, resource: uniform.as_entire_binding() }, + ], + }); + tiles.push(Tile { rect: [tx, ty, w, h], texture, levels, bind_group, _uniform: uniform }); + } + } + Self { size, format, tiles } + } + + /// Write `size` pixels at document `origin` from `texels` (in the texture format, row stride + /// `stride` pixels) into every overlapping tile's level 0. + pub(super) fn write(&self, queue: &wgpu::Queue, origin: [u32; 2], size: [u32; 2], stride: u32, texels: &[u8]) { + let bpp = texel_bytes(self.format); + let (x0, y0, x1, y1) = (origin[0], origin[1], origin[0] + size[0], origin[1] + size[1]); + for t in &self.tiles { + let [tx, ty, tw, th] = t.rect; + let (ix0, iy0, ix1, iy1) = (x0.max(tx), y0.max(ty), x1.min(tx + tw), y1.min(ty + th)); + if ix0 >= ix1 || iy0 >= iy1 { + continue; + } + let offset = ((iy0 - y0) as u64 * stride as u64 + (ix0 - x0) as u64) * bpp; + queue.write_texture( + wgpu::TexelCopyTextureInfo { + texture: &t.texture, + mip_level: 0, + origin: wgpu::Origin3d { x: ix0 - tx, y: iy0 - ty, z: 0 }, + aspect: wgpu::TextureAspect::All, + }, + texels, + wgpu::TexelCopyBufferLayout { offset, bytes_per_row: Some(stride * bpp as u32), rows_per_image: Some(iy1 - iy0) }, + wgpu::Extent3d { width: ix1 - ix0, height: iy1 - iy0, depth_or_array_layers: 1 }, + ); + } + } + + /// Rebuild the mip chain inside document rect `r` (x0, y0, x1, y1) with 2×2 box filtering. + pub(super) fn regenerate_mips(&self, device: &wgpu::Device, queue: &wgpu::Queue, res: &Resources, r: [u32; 4]) { + let Some(mip_pipeline) = res.mip_pipeline(self.format) else { return }; + let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("pc_mips") }); + for t in &self.tiles { + let [tx, ty, tw, th] = t.rect; + let (mut x0, mut y0, mut x1, mut y1) = (r[0].max(tx), r[1].max(ty), r[2].min(tx + tw), r[3].min(ty + th)); + if x0 >= x1 || y0 >= y1 { + continue; + } + (x0, y0, x1, y1) = (x0 - tx, y0 - ty, x1 - tx, y1 - ty); + for level in 1..t.levels.len() { + let (lw, lh) = ((tw >> level).max(1), (th >> level).max(1)); + [x0, y0, x1, y1] = mip_damage([x0, y0, x1, y1], lw, lh); + let bg = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("pc_mip"), + layout: &res.mip_bgl, + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&t.levels[level - 1]) }, + wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Sampler(&res.mip_sampler) }, + ], + }); + // Keep the sampled source and render attachment in separate resources on Intel + // DX12 adapters ([`separate_mip_targets`]): some of their drivers corrupt reduced + // previews when both are mip levels of the same texture, even though the + // subresources do not overlap. Elsewhere render straight into the level, which + // spares a scratch texture and a copy per level on every edit. + let scratch = res.separate_mip_targets.then(|| { + let scratch = device.create_texture(&wgpu::TextureDescriptor { + label: Some("pc_mip_scratch"), + size: wgpu::Extent3d { width: lw, height: lh, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: self.format, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC, + view_formats: &[], + }); + let view = scratch.create_view(&Default::default()); + (scratch, view) + }); + let (target, load) = match &scratch { + Some((_, view)) => (view, wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT)), + None => (&t.levels[level], wgpu::LoadOp::Load), + }; + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("pc_mip"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: target, + resolve_target: None, + depth_slice: None, + ops: wgpu::Operations { load, store: wgpu::StoreOp::Store }, + })], + depth_stencil_attachment: None, + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); + pass.set_pipeline(mip_pipeline); + pass.set_bind_group(0, &bg, &[]); + pass.set_scissor_rect(x0, y0, x1 - x0, y1 - y0); + pass.draw(0..3, 0..1); + drop(pass); + if let Some((scratch, _)) = &scratch { + let origin = wgpu::Origin3d { x: x0, y: y0, z: 0 }; + encoder.copy_texture_to_texture( + wgpu::TexelCopyTextureInfo { texture: scratch, mip_level: 0, origin, aspect: wgpu::TextureAspect::All }, + wgpu::TexelCopyTextureInfo { texture: &t.texture, mip_level: level as u32, origin, aspect: wgpu::TextureAspect::All }, + wgpu::Extent3d { width: x1 - x0, height: y1 - y0, depth_or_array_layers: 1 }, + ); + } + } + } + queue.submit([encoder.finish()]); + } +} diff --git a/crates/ui-egui/src/gpu_canvas_mip_tests.rs b/crates/ui-egui/src/canvas/gpu_canvas/mip_tests.rs similarity index 100% rename from crates/ui-egui/src/gpu_canvas_mip_tests.rs rename to crates/ui-egui/src/canvas/gpu_canvas/mip_tests.rs diff --git a/crates/ui-egui/src/canvas/gpu_canvas/perf.rs b/crates/ui-egui/src/canvas/gpu_canvas/perf.rs new file mode 100644 index 0000000000..8c22dfbf89 --- /dev/null +++ b/crates/ui-egui/src/canvas/gpu_canvas/perf.rs @@ -0,0 +1,256 @@ +use super::budget::video_memory; +use super::setup::Refresh; +use super::texels::LayerFit; +use super::*; + +/// Milliseconds since the process (or page) started, from a monotonic clock. +/// +/// `web_time::Instant` is `std::time::Instant` natively and `performance.now()` on wasm, so frame +/// caps, autosave intervals, preference retry backoff, stroke traces and screenshot deadlines all +/// measure durations the same way on both. The old wasm value was a constant 0, which made every +/// interval comparison (`now >= deadline`) permanently false on the web. +pub fn now_ms() -> f64 { + static START: std::sync::OnceLock = std::sync::OnceLock::new(); + START.get_or_init(web_time::Instant::now).elapsed().as_secs_f64() * 1000.0 +} + +/// UI-thread timings (CPU side), exponentially smoothed. +#[derive(Clone, Debug, Default, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Perf { + /// Average CPU time building the UI per frame (ms). + pub ui_ms: f64, + /// Worst UI frame of the last ~second (ms). + pub ui_max_ms: f64, + /// Last canvas refresh, CPU side (ms): the CPU composite on the CPU path, and on the GPU + /// path the cost of *encoding and submitting* the composite — not of running it, which is + /// `gpu_ms`. + pub composite_ms: f64, + /// Last canvas refresh: conversion + upload (ms). + pub upload_ms: f64, + /// Last canvas refresh kind: "full", "rect" or "none". + pub last_refresh: &'static str, + /// Pixels in the last refresh. + pub last_refresh_px: u64, + /// Whether the GPU canvas path is active. + pub gpu: bool, + /// Layer tiles uploaded by the last GPU composite. + pub gpu_uploads: u64, + /// How long the GPU spent executing a recent composite (ms), from timestamp queries read + /// back after the fact. `None` on the CPU compositor, on a device without timestamp queries + /// and on wasm — there is then no honest number to report, and `composite_ms` is not one. + /// Excludes layer-tile uploads and end-of-batch work (see `photocraft_gpu::timing`), so it + /// is a few per cent under the GPU's full share of a warm refresh and further under a cold + /// one. + pub gpu_ms: Option, + /// Pixels of the refresh `gpu_ms` measured, which is a frame or two behind + /// `last_refresh_px` and may be a different size. + pub gpu_ms_px: u64, + /// Why the last refresh fell back to the CPU compositor (None = GPU composited). + pub gpu_fallback: Option, + /// Adapter, backend, driver and fallback state (Help › System Info). + pub gpu_info: GpuInfo, + /// GPU memory the compositor may hold for layer pages and effect maps (MB; see + /// [`memory_budget`]). + pub gpu_budget_mb: u64, + /// The Memory Usage allowance and the GPU Memory preference (bytes) `gpu_budget_mb` was + /// computed from. + #[serde(skip)] + pub gpu_budget_allowance: (u64, u64), + /// The layer pages the last full refresh needed against the part of the budget they may + /// hold; when they don't fit, edits that redraw the whole document do it on the CPU. + pub gpu_layer_fit: Option, + /// Last command run through the app and its duration (ms). + pub last_command: String, + pub command_ms: f64, + /// Most recent cost of occasional UI work (outline tracing, thumbnails, …), in ms. + pub spans: std::collections::BTreeMap<&'static str, f64>, + #[serde(skip)] + max_decay: f64, + /// Composite and upload time of this frame's canvas refreshes, in ms (the stroke trace). + #[serde(skip)] + pub(crate) frame_refresh_ms: f64, +} + +/// What the app renders with and why (Help › System Info, Preferences › Performance, the `perf` +/// control-channel output). +#[derive(Clone, Debug, Default, PartialEq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct GpuInfo { + /// Adapter name ("" before the window opens). + pub adapter: String, + /// wgpu backend of the window's device ("vulkan", "dx12", "metal", "gl", …). + pub backend: String, + /// Device type ("discreteGpu", "integratedGpu", "cpu", …). + pub device_type: String, + /// Driver name and version as the driver reports them. + pub driver: String, + /// The adapter's own memory in MB ([`video_memory`]): discrete GPUs where the platform + /// reports it. It caps the GPU memory budgets. + pub video_memory_mb: Option, + /// `performance.gpuBackend` at launch. + pub preference: String, + /// Every graphics adapter the window could have used, by name (Preferences › Performance › + /// Graphics Adapter lists them). Empty in hosts that don't set it. + pub adapters: Vec, + /// The backend startup chose ("auto", "dx12", "cpu", …, or "env" for `WGPU_BACKEND`). + pub selected: String, + /// Why startup didn't use the preference as is (previous start crashed, `--safe-gpu`, + /// `WGPU_BACKEND`, Intel on Windows). + pub fallback: Option, + /// "gpu" (wgpu canvas and compositor) or "cpu" (CPU compositor, egui textures). + pub canvas: String, + /// Why the GPU canvas was dropped during this session (device lost or a GPU error). + pub lost: Option, + /// Present mode and frame latency ("fifo, latency 2"; launch overrides marked, see the + /// app's `presentation`). Empty in hosts that don't set it. + pub present: String, +} + +impl GpuInfo { + /// Record the adapters the instance found, without duplicates (one GPU shows up once per backend). + pub fn set_available(&mut self, adapters: &[wgpu::Adapter]) { + self.adapters.clear(); + for a in adapters { + let name = a.get_info().name; + if !name.is_empty() && !self.adapters.contains(&name) { + self.adapters.push(name); + } + } + } + + /// Fill the adapter fields from `info`. + pub fn set_adapter(&mut self, info: &wgpu::AdapterInfo) { + self.adapter = info.name.clone(); + self.backend = backend_name(info.backend).to_string(); + self.device_type = match info.device_type { + wgpu::DeviceType::DiscreteGpu => "discreteGpu", + wgpu::DeviceType::IntegratedGpu => "integratedGpu", + wgpu::DeviceType::VirtualGpu => "virtualGpu", + wgpu::DeviceType::Cpu => "cpu", + wgpu::DeviceType::Other => "other", + } + .to_string(); + self.driver = [info.driver.as_str(), info.driver_info.as_str()].iter().filter(|s| !s.is_empty()).copied().collect::>().join(" "); + self.video_memory_mb = video_memory(info).map(|b| b >> 20); + } + + /// Human-readable lines for Help › System Info. + pub fn lines(&self) -> Vec { + let or = |s: &str, d: &str| if s.is_empty() || (s == "auto" && d == "auto") { tl!(d).to_string() } else { s.to_string() }; + let mut v = vec![ + { + let template = "Graphics adapter: {adapter}"; + crate::i18n::fmt(tl!(template), &[("adapter", &or(&self.adapter, "unknown"))]) + }, + { + let template = "Backend: {backend} ({type})"; + crate::i18n::fmt(tl!(template), &[("backend", &or(&self.backend, "unknown")), ("type", &or(&self.device_type, "unknown type"))]) + }, + { + let template = "Driver: {driver}"; + crate::i18n::fmt(tl!(template), &[("driver", &or(&self.driver, "unknown"))]) + }, + ]; + // The card's own memory caps the GPU budgets, so it explains a huge canvas falling back + // to the CPU. Only discrete cards report one (integrated GPUs share system memory). + if let Some(mb) = self.video_memory_mb { + let template = "Graphics memory: {size}"; + v.push(crate::i18n::fmt(tl!(template), &[("size", &crate::chrome_ui::fmt_bytes(mb.saturating_mul(1 << 20)))])); + } + v.extend([ + { + let template = "GPU backend preference: {backend}"; + crate::i18n::fmt(tl!(template), &[("backend", &or(&self.preference, "auto"))]) + }, + { + let template = "Selected at launch: {backend}"; + crate::i18n::fmt(tl!(template), &[("backend", &or(&self.selected, "auto"))]) + }, + { + let template = "Image compositor: {processor}"; + crate::i18n::fmt(tl!(template), &[("processor", if self.canvas == "gpu" { "GPU" } else { "CPU" })]) + }, + { + let template = "Window renderer: {renderer}"; + let renderer = if self.device_type == "cpu" { + "Software adapter" + } else if self.adapter.is_empty() { + "Unknown" + } else { + "Graphics adapter" + }; + crate::i18n::fmt(tl!(template), &[("renderer", tl!(renderer))]) + }, + ]); + if let Some(f) = &self.fallback { + v.push({ + let template = "Fallback: {reason}"; + crate::i18n::fmt(tl!(template), &[("reason", f)]) + }); + } + if let Some(l) = &self.lost { + v.push({ + let template = "This session: {reason}"; + crate::i18n::fmt(tl!(template), &[("reason", l)]) + }); + } + v + } +} + +/// The preference name of a wgpu backend. +pub fn backend_name(b: wgpu::Backend) -> &'static str { + match b { + wgpu::Backend::Vulkan => "vulkan", + wgpu::Backend::Dx12 => "dx12", + wgpu::Backend::Metal => "metal", + wgpu::Backend::Gl => "gl", + wgpu::Backend::BrowserWebGpu => "webgpu", + wgpu::Backend::Noop => "noop", + } +} + +impl Perf { + pub fn record(&mut self, kind: &'static str, px: u64, composite_ms: f64, upload_ms: f64) { + self.frame_refresh_ms += composite_ms + upload_ms; + self.last_refresh = kind; + self.last_refresh_px = px; + self.composite_ms = composite_ms; + self.upload_ms = upload_ms; + if !kind.starts_with("gpu") { + self.gpu_uploads = 0; + // The CPU compositor did this one: there is no GPU time, and the last GPU + // refresh's would be read as this refresh's. + self.gpu_ms = None; + self.gpu_ms_px = 0; + } else { + self.gpu_fallback = None; + } + } + + /// Record a canvas refresh and any GPU measurement that came back with it. + pub fn record_refresh(&mut self, r: &Refresh) { + self.record(r.kind, r.px, r.composite_ms, r.upload_ms); + if let Some(t) = r.gpu { + self.record_gpu(t); + } + } + + /// Record a GPU composite measurement that came back (see [`photocraft_gpu::GpuTiming`]). + pub fn record_gpu(&mut self, t: photocraft_gpu::GpuTiming) { + self.gpu_ms = Some(t.ms); + self.gpu_ms_px = t.px; + } + pub fn span(&mut self, name: &'static str, ms: f64) { + self.spans.insert(name, (ms * 100.0).round() / 100.0); + } + pub fn frame(&mut self, ms: f64) { + self.ui_ms = if self.ui_ms == 0.0 { ms } else { self.ui_ms * 0.9 + ms * 0.1 }; + self.max_decay += 1.0; + if ms > self.ui_max_ms || self.max_decay > 60.0 { + self.ui_max_ms = ms; + self.max_decay = 0.0; + } + } +} diff --git a/crates/ui-egui/src/canvas/gpu_canvas/resources.rs b/crates/ui-egui/src/canvas/gpu_canvas/resources.rs new file mode 100644 index 0000000000..27606b7c05 --- /dev/null +++ b/crates/ui-egui/src/canvas/gpu_canvas/resources.rs @@ -0,0 +1,383 @@ +use super::budget::{canvas_budget, physical_memory}; +use super::doc_textures::init_buffer; +use super::shaders::{CANVAS_WGSL, ENCODE_WGSL, MIP_WGSL}; +use super::texels::LayerFit; +use super::*; + +pub(super) struct Resources { + pub(super) view_bgl: wgpu::BindGroupLayout, + pub(super) tile_bgl: wgpu::BindGroupLayout, + pub(super) shadow_pipeline: wgpu::RenderPipeline, + pub(super) tile_pipeline: wgpu::RenderPipeline, + pub(super) sampler: wgpu::Sampler, + pub(super) mip_bgl: wgpu::BindGroupLayout, + mip_pipeline: wgpu::RenderPipeline, + /// `mip_pipeline` and `encode_pipeline` for `Rgba16Float` tiles (when the adapter supports them). + mip_pipeline_high: Option, + encode_pipeline_high: Option, + pub(super) mip_sampler: wgpu::Sampler, + pub(super) docs: HashMap, + pub(super) views: HashMap, + pub(super) out_linear: bool, + /// Build each mip level in a scratch texture and copy it back instead of rendering into + /// the level directly (see [`separate_mip_targets`]). + pub(super) separate_mip_targets: bool, + /// The wgpu layer compositor (created on first use). + pub(super) compositor: Option, + /// Why the wgpu compositor couldn't be created (then the CPU compositor is used). + pub(super) compositor_failed: Option, + /// The device's health: the paint callback issues no GPU work once it's lost. + pub(super) health: photocraft_gpu::DeviceHealth, + /// GPU memory the compositor may hold (`None`: its default), and the document area the + /// view shows; applied before every composite. + pub(super) compositor_budget: Option, + /// The layer pages the last full (or large) refresh needed and the budget they had to fit + /// (bytes): when they don't fit, full refreshes go to the CPU ([`OVER_BUDGET`]). + pub(super) layer_fit: Option, + pub(super) compositor_cache_budget: Option, + pub(super) compositor_focus: Option, + /// GPU bytes one document's display texture set may take (see [`canvas_budget`]). + pub(super) canvas_budget: std::sync::Arc, + pub(super) encode_bgl: wgpu::BindGroupLayout, + encode_pipeline: wgpu::RenderPipeline, + pub(super) lut_bgl: wgpu::BindGroupLayout, + /// Display LUTs per (document, display) (monitor profile, Proof Colors / Gamut Warning); + /// `identity_lut` otherwise. + pub(super) luts: HashMap<(u64, u32), wgpu::BindGroup>, + /// Signatures belong to their renderer resources, including identity transforms (mode 0). + pub(super) display_lut_signatures: HashMap<(u64, u32), (u64, u8)>, + pub(super) identity_lut: wgpu::BindGroup, + /// Transparency checkerboard and gamut warning colours (Preferences › Transparency & Gamut). + pub(super) style: CanvasStyle, +} + +/// Canvas colours from Preferences › Transparency & Gamut. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct CanvasStyle { + /// Checker square side in points (0 = no checkerboard: transparency shows white). + pub checker_square: f32, + pub checker_light: [f32; 3], + pub checker_dark: [f32; 3], + pub gamut_color: [f32; 3], + /// Gamut warning opacity 0..1. + pub gamut_opacity: f32, +} + +impl Default for CanvasStyle { + fn default() -> Self { + Self { checker_square: 8.0, checker_light: [1.0; 3], checker_dark: [0.8; 3], gamut_color: [0.5; 3], gamut_opacity: 1.0 } + } +} + +/// A display transform: either the existing 3D LUT or separate full-float shapers and +/// matrix. Pack curves into short rows to stay within WebGL2's texture-size limits. +pub(super) fn lut_bind_group( + device: &wgpu::Device, + queue: &wgpu::Queue, + bgl: &wgpu::BindGroupLayout, + size: u32, + bytes: &[u8], + shaper: Option<&photocraft_cms::GpuMatrixShaper>, +) -> wgpu::BindGroup { + let extent = wgpu::Extent3d { width: size, height: size, depth_or_array_layers: size }; + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: Some("pc_display_lut"), + size: extent, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D3, + format: FORMAT, + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }); + queue.write_texture( + wgpu::TexelCopyTextureInfo { texture: &texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, + bytes, + wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(size * 4), rows_per_image: Some(size) }, + extent, + ); + let view = texture.create_view(&wgpu::TextureViewDescriptor::default()); + let (width, height, curves, matrix) = if let Some(s) = shaper { + let width = 1024usize; + let count = s.input_table().len() + s.output_table().len(); + let height = count.div_ceil(width); + let mut curves = Vec::with_capacity(width * height * 16); + for value in s.input_table().iter().chain(s.output_table()).flatten() { + curves.extend_from_slice(&value.to_le_bytes()); + } + curves.resize(width * height * 16, 0); + (width as u32, height as u32, curves, s.matrix_rows()) + } else { + (1, 1, vec![0; 16], [[0.0; 4]; 3]) + }; + let extent = wgpu::Extent3d { width, height, depth_or_array_layers: 1 }; + let curves_texture = device.create_texture(&wgpu::TextureDescriptor { + label: Some("pc_display_shapers"), + size: extent, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + // textureLoad + explicit interpolation needs no optional float-filtering feature. + format: wgpu::TextureFormat::Rgba32Float, + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }); + queue.write_texture( + wgpu::TexelCopyTextureInfo { texture: &curves_texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, + &curves, + wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(width * 16), rows_per_image: Some(height) }, + extent, + ); + let curves_view = curves_texture.create_view(&wgpu::TextureViewDescriptor::default()); + let matrix_bytes: Vec = matrix.iter().flatten().flat_map(|v| v.to_le_bytes()).collect(); + let matrix_buffer = init_buffer(device, "pc_display_matrix", &matrix_bytes, wgpu::BufferUsages::UNIFORM); + device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("pc_display_lut"), + layout: bgl, + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&view) }, + wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(&curves_view) }, + wgpu::BindGroupEntry { binding: 2, resource: matrix_buffer.as_entire_binding() }, + ], + }) +} + +/// The 2³ identity LUT (unused unless a document has none and `display` is set). +pub(super) fn identity_lut_bytes() -> Vec { + (0..8).flat_map(|i| [if i & 1 != 0 { 255 } else { 0 }, if i & 2 != 0 { 255 } else { 0 }, if i & 4 != 0 { 255 } else { 0 }, 0]).collect() +} + +pub(super) struct ViewGpu { + pub(super) buffer: wgpu::Buffer, + pub(super) bind_group: wgpu::BindGroup, + pub(super) frame_data: [f32; VIEW_FLOATS], +} + +pub(super) struct DocTextures { + pub(super) size: [u32; 2], + pub(super) format: wgpu::TextureFormat, + pub(super) tiles: Vec, +} + +pub(super) struct Tile { + /// Document-pixel rect: x, y, w, h. + pub(super) rect: [u32; 4], + pub(super) texture: wgpu::Texture, + pub(super) levels: Vec, + pub(super) bind_group: wgpu::BindGroup, + pub(super) _uniform: wgpu::Buffer, +} + +fn uniform_entry(binding: u32, size: u64, vis: wgpu::ShaderStages) -> wgpu::BindGroupLayoutEntry { + wgpu::BindGroupLayoutEntry { + binding, + visibility: vis, + ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: NonZeroU64::new(size) }, + count: None, + } +} + +fn texture_entry(binding: u32) -> wgpu::BindGroupLayoutEntry { + wgpu::BindGroupLayoutEntry { + binding, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + multisampled: false, + sample_type: wgpu::TextureSampleType::Float { filterable: true }, + view_dimension: wgpu::TextureViewDimension::D2, + }, + count: None, + } +} + +fn sampler_entry(binding: u32) -> wgpu::BindGroupLayoutEntry { + wgpu::BindGroupLayoutEntry { + binding, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), + count: None, + } +} + +pub(super) fn f32_bytes(v: &[f32]) -> Vec { + v.iter().flat_map(|f| f.to_ne_bytes()).collect() +} + +fn pipeline( + device: &wgpu::Device, + label: &str, + layout: &wgpu::PipelineLayout, + module: &wgpu::ShaderModule, + (vs, fs): (&str, &str), + format: wgpu::TextureFormat, + blend: Option, +) -> wgpu::RenderPipeline { + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some(label), + layout: Some(layout), + vertex: wgpu::VertexState { module, entry_point: Some(vs), buffers: &[], compilation_options: Default::default() }, + primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() }, + depth_stencil: None, + multisample: wgpu::MultisampleState { count: 1, mask: !0, alpha_to_coverage_enabled: false }, + fragment: Some(wgpu::FragmentState { + module, + entry_point: Some(fs), + targets: &[Some(wgpu::ColorTargetState { format, blend, write_mask: wgpu::ColorWrites::ALL })], + compilation_options: Default::default(), + }), + multiview_mask: None, + cache: None, + }) +} + +impl Resources { + pub(super) fn new(device: &wgpu::Device, queue: &wgpu::Queue, target: wgpu::TextureFormat, high: bool) -> Self { + let module = + device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("pc_canvas"), source: wgpu::ShaderSource::Wgsl(CANVAS_WGSL.into()) }); + let vis = wgpu::ShaderStages::VERTEX | wgpu::ShaderStages::FRAGMENT; + let view_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("pc_canvas_view"), + entries: &[uniform_entry(0, VIEW_UNIFORM_SIZE, vis), sampler_entry(1)], + }); + let tile_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("pc_canvas_tile"), + entries: &[texture_entry(0), uniform_entry(1, TILE_UNIFORM_SIZE, vis)], + }); + let lut_entry = wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + multisampled: false, + sample_type: wgpu::TextureSampleType::Float { filterable: true }, + view_dimension: wgpu::TextureViewDimension::D3, + }, + count: None, + }; + let curves_entry = wgpu::BindGroupLayoutEntry { + binding: 1, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + multisampled: false, + sample_type: wgpu::TextureSampleType::Float { filterable: false }, + view_dimension: wgpu::TextureViewDimension::D2, + }, + count: None, + }; + let lut_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("pc_display_lut"), + entries: &[lut_entry, curves_entry, uniform_entry(2, 48, wgpu::ShaderStages::FRAGMENT)], + }); + let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("pc_canvas"), + bind_group_layouts: &[Some(&view_bgl), Some(&tile_bgl), Some(&lut_bgl)], + immediate_size: 0, + }); + let shadow_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("pc_canvas_shadow"), + bind_group_layouts: &[Some(&view_bgl)], + immediate_size: 0, + }); + // Premultiplied "over", with egui's alpha rule (keeps a transparent window's alpha sane). + let blend = wgpu::BlendState { + color: wgpu::BlendComponent { + src_factor: wgpu::BlendFactor::One, + dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha, + operation: wgpu::BlendOperation::Add, + }, + alpha: wgpu::BlendComponent { + src_factor: wgpu::BlendFactor::OneMinusDstAlpha, + dst_factor: wgpu::BlendFactor::One, + operation: wgpu::BlendOperation::Add, + }, + }; + let shadow_pipeline = pipeline(device, "pc_canvas_shadow", &shadow_layout, &module, ("vs_shadow", "fs_shadow"), target, Some(blend)); + let tile_pipeline = pipeline(device, "pc_canvas_tile", &layout, &module, ("vs_tile", "fs_tile"), target, Some(blend)); + let sampler = device.create_sampler(&wgpu::SamplerDescriptor { + label: Some("pc_canvas_trilinear"), + mag_filter: wgpu::FilterMode::Linear, + min_filter: wgpu::FilterMode::Linear, + mipmap_filter: wgpu::MipmapFilterMode::Linear, + ..Default::default() + }); + + let mip_module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("pc_mip"), source: wgpu::ShaderSource::Wgsl(MIP_WGSL.into()) }); + let mip_bgl = + device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("pc_mip"), entries: &[texture_entry(0), sampler_entry(1)] }); + let mip_layout = + device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("pc_mip"), bind_group_layouts: &[Some(&mip_bgl)], immediate_size: 0 }); + let mip_pipeline = pipeline(device, "pc_mip", &mip_layout, &mip_module, ("vs", "fs"), FORMAT, None); + let mip_pipeline_high = high.then(|| pipeline(device, "pc_mip_16f", &mip_layout, &mip_module, ("vs", "fs"), FORMAT_HIGH, None)); + let mip_sampler = device.create_sampler(&wgpu::SamplerDescriptor { + label: Some("pc_mip"), + mag_filter: wgpu::FilterMode::Linear, + min_filter: wgpu::FilterMode::Linear, + ..Default::default() + }); + // Compositor output (straight RGBA32F chunk) -> premultiplied RGBA8 display tile. + let encode_module = + device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("pc_encode"), source: wgpu::ShaderSource::Wgsl(ENCODE_WGSL.into()) }); + let unfilterable = wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + multisampled: false, + sample_type: wgpu::TextureSampleType::Float { filterable: false }, + view_dimension: wgpu::TextureViewDimension::D2, + }, + count: None, + }; + let encode_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("pc_encode"), + entries: &[unfilterable, uniform_entry(1, 16, wgpu::ShaderStages::FRAGMENT)], + }); + let encode_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("pc_encode"), + bind_group_layouts: &[Some(&encode_bgl)], + immediate_size: 0, + }); + let encode_pipeline = pipeline(device, "pc_encode", &encode_layout, &encode_module, ("vs", "fs"), FORMAT, None); + let encode_pipeline_high = high.then(|| pipeline(device, "pc_encode_16f", &encode_layout, &encode_module, ("vs", "fs"), FORMAT_HIGH, None)); + let identity_lut = lut_bind_group(device, queue, &lut_bgl, 2, &identity_lut_bytes(), None); + Self { + lut_bgl, + luts: HashMap::new(), + display_lut_signatures: HashMap::new(), + identity_lut, + style: CanvasStyle::default(), + view_bgl, + tile_bgl, + shadow_pipeline, + tile_pipeline, + sampler, + mip_bgl, + mip_pipeline, + mip_pipeline_high, + encode_pipeline_high, + mip_sampler, + docs: HashMap::new(), + views: HashMap::new(), + out_linear: target.is_srgb(), + separate_mip_targets: false, + compositor: None, + compositor_failed: None, + health: photocraft_gpu::DeviceHealth::new(), + compositor_budget: None, + layer_fit: None, + compositor_cache_budget: None, + compositor_focus: None, + canvas_budget: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(canvas_budget(physical_memory(), None))), + encode_bgl, + encode_pipeline, + } + } + + /// The pipeline encoding compositor output into a `format` tile. + pub(super) fn encode_pipeline(&self, format: wgpu::TextureFormat) -> Option<&wgpu::RenderPipeline> { + if format == FORMAT_HIGH { self.encode_pipeline_high.as_ref() } else { Some(&self.encode_pipeline) } + } + + /// The mip-chain pipeline for `format` tiles. + pub(super) fn mip_pipeline(&self, format: wgpu::TextureFormat) -> Option<&wgpu::RenderPipeline> { + if format == FORMAT_HIGH { self.mip_pipeline_high.as_ref() } else { Some(&self.mip_pipeline) } + } +} diff --git a/crates/ui-egui/src/canvas/gpu_canvas/setup.rs b/crates/ui-egui/src/canvas/gpu_canvas/setup.rs new file mode 100644 index 0000000000..8195148a45 --- /dev/null +++ b/crates/ui-egui/src/canvas/gpu_canvas/setup.rs @@ -0,0 +1,117 @@ +use super::texels::texels; +use super::*; + +/// A CPU composite as the canvas texture stores it (`display`'s encoding; as is without one). +pub(super) fn texture_buffer<'a>( + display: Option<&photocraft_engine::display_color::CanvasDisplay>, + buf: &'a photocraft_compose::Buffer, +) -> std::borrow::Cow<'a, photocraft_compose::Buffer> { + match display { + Some(d) => d.texture_buffer(buf), + None => std::borrow::Cow::Borrowed(buf), + } +} + +/// A CPU composite `buf` as texels of a `format` canvas texture, in `display`'s encoding: what +/// [`GpuCanvas::upload_rect`] takes. Runs anywhere (a redraw's worker converts its own pieces). +pub fn display_texels( + format: wgpu::TextureFormat, + display: Option<&photocraft_engine::display_color::CanvasDisplay>, + buf: &photocraft_compose::Buffer, +) -> Vec { + texels(format, &texture_buffer(display, buf).px) +} + +/// What a [`GpuCanvas::refresh`] did. +#[derive(Clone, Debug, Default)] +pub struct Refresh { + /// "gpu-rect", "gpu-full" (wgpu compositor), "rect" or "full" (CPU compositor); "lost" or + /// [`REFRESH_OVER_BUDGET`] when nothing was drawn and the caller should use the CPU canvas. + pub kind: &'static str, + /// Pixels refreshed. + pub px: u64, + pub composite_ms: f64, + pub upload_ms: f64, + /// Layer tiles the wgpu compositor uploaded. + pub uploads: u64, + /// How long the GPU spent executing a recent wgpu composite, once its timestamps came back + /// (a frame or two after that refresh, so usually an earlier one than this). It carries its + /// own pixel count and is never this refresh's unless they match. `None` when the device has + /// no timestamp queries, on the CPU compositor, and on wasm: no number at all is reported + /// rather than `composite_ms`, which measures encoding and submitting, not executing. It + /// leaves out layer-tile uploads (`uploads` above counts them), so a first refresh of a + /// document under-reports by more than the few per cent of a warm one. + pub gpu: Option, + /// Why the wgpu compositor wasn't used. + pub fallback: Option, +} + +/// How the app creates its wgpu device: egui's defaults clamped to the adapter's supported limits, +/// with the adapter's own texture and buffer sizes rather than egui's 8192 px cap, so large +/// documents stay on the GPU compositor. +pub fn wgpu_setup() -> egui_wgpu::WgpuSetup { + let mut setup = egui_wgpu::WgpuSetup::without_display_handle(); + use_adapter_limits(&mut setup); + setup +} + +/// Make `setup` request the adapter's own texture and buffer size limits instead of egui's +/// default 8192 px cap (which sent every document wider or taller than 8192 px to the CPU +/// compositor). Other limits use egui's defaults (WebGL2's on GL), clamped to adapter support; +/// features stay egui's default. +pub fn use_adapter_limits(setup: &mut egui_wgpu::WgpuSetup) { + use_adapter_limits_with(setup, |_| {}); +} + +/// [`use_adapter_limits`], calling `on_adapter` with the chosen adapter just before the device +/// is requested (the desktop app records it in its crash-safe startup marker). +pub fn use_adapter_limits_with(setup: &mut egui_wgpu::WgpuSetup, on_adapter: impl Fn(&wgpu::Adapter) + Send + Sync + 'static) { + if let egui_wgpu::WgpuSetup::CreateNew(create) = setup { + create.device_descriptor = std::sync::Arc::new(move |adapter| { + on_adapter(adapter); + device_descriptor(adapter) + }); + } +} + +/// How the app asks for its device: egui's defaults, the adapter's texture and buffer size +/// limits ([`device_limits`]), and timestamp queries where the adapter has them, so the canvas +/// can report how long the GPU actually spends compositing ([`photocraft_gpu::GpuTimer`]). +/// A bench or test that builds its own device should use this rather than [`device_limits`] +/// alone, or it measures a device the app never creates. (`bevel_bench`, `fx_bench` and +/// `interactive_bench` still call [`device_limits`] directly and so report no GPU time.) +pub fn device_descriptor(adapter: &wgpu::Adapter) -> wgpu::DeviceDescriptor<'static> { + wgpu::DeviceDescriptor { + label: Some("photocraft wgpu device"), + required_limits: device_limits(adapter), + required_features: timing_features(adapter), + ..Default::default() + } +} + +/// The timestamp-query features when the adapter supports all of them, else none: asking for a +/// feature an adapter lacks fails device creation, and a canvas without GPU timing is far better +/// than no canvas. +/// +/// `PHOTOCRAFT_NO_GPU_TIMING` suppresses the request as well as the timer +/// ([`photocraft_gpu::Compositor::measure_gpu_time`]), so the variable also rescues a driver +/// that advertises the features and then fails or misbehaves on device creation — not only one +/// whose timestamps come back wrong. +pub fn timing_features(adapter: &wgpu::Adapter) -> wgpu::Features { + let want = photocraft_gpu::timing::FEATURES; + if std::env::var_os("PHOTOCRAFT_NO_GPU_TIMING").is_some() { + return wgpu::Features::empty(); + } + if adapter.features().contains(want) { want } else { wgpu::Features::empty() } +} + +/// egui's base limits (WebGL2's on GL), clamped to adapter support, with its maximum texture and buffer sizes. +pub fn device_limits(adapter: &wgpu::Adapter) -> wgpu::Limits { + device_limits_for(adapter.get_info().backend, adapter.limits()) +} + +pub(super) fn device_limits_for(backend: wgpu::Backend, supported: wgpu::Limits) -> wgpu::Limits { + let base = if backend == wgpu::Backend::Gl { wgpu::Limits::downlevel_webgl2_defaults() } else { wgpu::Limits::default() }; + let base = base.or_worse_values_from(&supported); + wgpu::Limits { max_texture_dimension_2d: supported.max_texture_dimension_2d, max_buffer_size: supported.max_buffer_size, ..base } +} diff --git a/crates/ui-egui/src/canvas/gpu_canvas/shaders.rs b/crates/ui-egui/src/canvas/gpu_canvas/shaders.rs new file mode 100644 index 0000000000..c29376a936 --- /dev/null +++ b/crates/ui-egui/src/canvas/gpu_canvas/shaders.rs @@ -0,0 +1,273 @@ +pub(super) const CANVAS_WGSL: &str = r#" +struct View { + a: vec4, // screen_w, screen_h, scale (device px per doc px), pixels_per_point + b: vec4, // doc origin x, y (device px), doc w, h (doc px) + c: vec4, // filter mode, lod, grid alpha, checker square (device px) + d: vec4, // pattern preview offset x, y (doc px), display (0 none, 1 LUT, 2 LUT + gamut, 3 matrix/shaper), output linear + e: vec4, // checker light rgb, gamut warning opacity + f: vec4, // checker dark rgb, 32-bit preview gain (2^exposure; 0 = off) + g: vec4, // gamut warning rgb, 32-bit preview 1 / gamma + h: vec4, // cos, sin, center_doc_x, center_doc_y +}; +struct Tile { r: vec4 }; // x, y, w, h in doc px + +@group(0) @binding(0) var view: View; +@group(0) @binding(1) var samp: sampler; +@group(1) @binding(0) var tex: texture_2d; +@group(1) @binding(1) var tile: Tile; +@group(2) @binding(0) var lut: texture_3d; +@group(2) @binding(1) var display_curves: texture_2d; +struct DisplayMatrix { r: vec4, g: vec4, b: vec4 }; +@group(2) @binding(2) var display_matrix: DisplayMatrix; + +fn curve_entry(index: u32) -> vec3 { + let width = textureDimensions(display_curves).x; + return textureLoad(display_curves, vec2(i32(index % width), i32(index / width)), 0).rgb; +} + +fn display_curve(c: vec3, offset: u32, intervals: f32) -> vec3 { + let p = clamp(c, vec3(0.0), vec3(1.0)) * intervals; + let lo = vec3(floor(p)); + let hi = min(lo + vec3(1u), vec3(u32(intervals))); + let f = fract(p); + return vec3( + mix(curve_entry(offset + lo.r).r, curve_entry(offset + hi.r).r, f.r), + mix(curve_entry(offset + lo.g).g, curve_entry(offset + hi.g).g, f.g), + mix(curve_entry(offset + lo.b).b, curve_entry(offset + hi.b).b, f.b) + ); +} + +fn matrix_display(c: vec3) -> vec3 { + // Layout matches cms::GpuMatrixShaper: 4097 input entries, then 4096 inverse-curve + // entries indexed by the fourth root. This preserves near-black precision without + // interpolating across clipped corners of a coarse RGB cube. + let v = vec4(display_curve(c, 0u, 4096.0), 1.0); + let linear = vec3(dot(display_matrix.r, v), dot(display_matrix.g, v), dot(display_matrix.b, v)); + let u = sqrt(sqrt(clamp(linear, vec3(0.0), vec3(1.0)))); + return display_curve(u, 4097u, 4095.0); +} + +struct VOut { @builtin(position) pos: vec4 }; + +fn corner(i: u32) -> vec2 { + var c = array, 6>(vec2(0.0, 0.0), vec2(1.0, 0.0), vec2(0.0, 1.0), vec2(0.0, 1.0), vec2(1.0, 0.0), vec2(1.0, 1.0)); + return c[i]; +} + +fn px_to_clip(p: vec2) -> vec4 { + let n = p / view.a.xy * 2.0 - 1.0; + return vec4(n.x, -n.y, 0.0, 1.0); +} + +fn screen_center() -> vec2 { + return view.b.xy + view.h.zw * view.a.z; +} + +fn doc_to_px(d: vec2) -> vec2 { + let cs = view.h.xy; + let q = d - view.h.zw; + let r = vec2(q.x * cs.x - q.y * cs.y, q.x * cs.y + q.y * cs.x); + return screen_center() + r * view.a.z; +} + +fn px_to_doc(p: vec2) -> vec2 { + let cs = view.h.xy; + let q = (p - screen_center()) / view.a.z; + return vec2(q.x * cs.x + q.y * cs.y, -q.x * cs.y + q.y * cs.x) + view.h.zw; +} + +fn doc_min() -> vec2 { return view.b.xy; } +fn doc_max() -> vec2 { return view.b.xy + view.b.zw * view.a.z; } + +fn srgb_to_linear(c: vec3) -> vec3 { + let lo = c / 12.92; + let hi = pow((c + 0.055) / 1.055, vec3(2.4)); + return select(hi, lo, c <= vec3(0.04045)); +} + +fn linear_to_srgb(c: vec3) -> vec3 { + let hi = 1.055 * pow(max(c, vec3(1e-12)), vec3(1.0 / 2.4)) - 0.055; + return select(hi, c * 12.92, c <= vec3(0.0031308)); +} + +// --- drop shadow --------------------------------------------------------------------------- + +fn erf2(x: vec2) -> vec2 { + let s = sign(x); + let a = abs(x); + var t = 1.0 + (0.278393 + (0.230389 + 0.078108 * (a * a)) * a) * a; + t = t * t; + return s - s / (t * t); +} + +// Coverage of the box [lo, hi] blurred by a Gaussian of std-dev `sigma`, at point p. +fn box_blur(p: vec2, lo: vec2, hi: vec2, sigma: f32) -> f32 { + let k = 0.70710678 / sigma; + let q = (erf2((p - lo) * k) - erf2((p - hi) * k)) * 0.5; + return q.x * q.y; +} + +@vertex +fn vs_shadow(@builtin(vertex_index) vi: u32) -> VOut { + let pad = 64.0 * view.a.w; + let c0 = doc_to_px(vec2(0.0, 0.0)); + let c1 = doc_to_px(vec2(view.b.z, 0.0)); + let c2 = doc_to_px(vec2(view.b.z, view.b.w)); + let c3 = doc_to_px(vec2(0.0, view.b.w)); + let lo = min(min(c0, c1), min(c2, c3)) - vec2(pad); + let hi = max(max(c0, c1), max(c2, c3)) + vec2(pad); + let p = mix(lo, hi, corner(vi)); + return VOut(px_to_clip(p)); +} + +@fragment +fn fs_shadow(in: VOut) -> @location(0) vec4 { + let p = in.pos.xy; + let d = px_to_doc(p); + if (all(d >= vec2(0.0)) && all(d < view.b.zw)) { + discard; + } + let p_align = view.b.xy + d * view.a.z; + let lo = doc_min(); + let hi = doc_max(); + let u = view.a.w; + let ambient = box_blur(p_align - vec2(0.0, 7.0 * u), lo, hi, 16.0 * u) * 0.40; + let contact = box_blur(p_align - vec2(0.0, 0.75 * u), lo, hi, 1.25 * u) * 0.30; + let a = 1.0 - (1.0 - ambient) * (1.0 - contact); + return vec4(0.0, 0.0, 0.0, a); +} + +// --- document tiles ------------------------------------------------------------------------ + +@vertex +fn vs_tile(@builtin(vertex_index) vi: u32) -> VOut { + // A View › Pattern Preview copy sits a whole number of document sizes away (view.d.xy). + let p = doc_to_px(view.d.xy + tile.r.xy + tile.r.zw * corner(vi)); + return VOut(px_to_clip(p)); +} + +// Cells are screen-sized (view.c.w device px) but anchored to the document's top-left corner, so +// the pattern moves with the image as it is panned or zoomed. `d` is in document pixels (each +// Pattern Preview copy has the same cells). +fn checker(d: vec2) -> vec3 { + if (view.c.w <= 0.0) { + return vec3(1.0); + } + let c = floor(d * view.a.z / view.c.w); + let odd = fract((c.x + c.y) * 0.5) > 0.25; + return select(view.e.xyz, view.f.xyz, odd); +} + +@fragment +fn fs_tile(in: VOut) -> @location(0) vec4 { + let p = in.pos.xy; + let scale = view.a.z; + let d = px_to_doc(p) - view.d.xy; // document pixel coordinates (within this copy) + let size = tile.r.zw; + let t = d - tile.r.xy; // texel coordinates within this tile + let mode = view.c.x; + var col: vec4; + if (mode < 0.5) { + // Zoomed out: trilinear through the mip chain. + col = textureSampleLevel(tex, samp, t / size, view.c.y); + } else if (mode < 1.5) { + col = textureSampleLevel(tex, samp, t / size, 0.0); + } else { + // Crisp texels with a one-device-pixel anti-aliased edge ("sharp bilinear"). + let tt = t - 0.5; + let i = floor(tt); + let f = clamp((tt - i - 0.5) * scale + 0.5, vec2(0.0), vec2(1.0)); + col = textureSampleLevel(tex, samp, (i + 0.5 + f) / size, 0.0); + } + if (view.f.w > 0.0 && col.a > 0.0) { + // View › 32-bit Preview Options: exposure and gamma in linear light on the sRGB-encoded + // texture value, before the display LUT. A float canvas keeps values above 1.0, so they + // are brought into range by the exposure instead of clipped. + let lin = srgb_to_linear(max(col.rgb / col.a, vec3(0.0))) * view.f.w; + let v = linear_to_srgb(min(pow(max(lin, vec3(1e-12)), vec3(view.g.w)), vec3(1.0))); + col = vec4(v * col.a, col.a); + } + if (view.d.z > 0.5 && col.a > 0.0) { + // Colour management, Proof Colors, Gamut Warning: the document's display LUT (alpha flags + // out-of-gamut colours). + let c = clamp(col.rgb / col.a, vec3(0.0), vec3(1.0)); + var shown: vec3; + if (view.d.z > 2.5) { + shown = matrix_display(c); + } else { + let n = f32(textureDimensions(lut).x); + let l = textureSampleLevel(lut, samp, (c * (n - 1.0) + 0.5) / n, 0.0); + shown = select(l.rgb, mix(l.rgb, view.g.xyz, view.e.w), view.d.z > 1.5 && l.a > 0.5); + } + col = vec4(shown * col.a, col.a); + } + var rgb = col.rgb + checker(d) * (1.0 - col.a); + // The pixel grid is drawn over pixels with content, not over empty checker. + let grid = view.c.z * col.a; + if (grid > 0.0) { + let e = fract(d) * scale; + if (e.x < 1.0 || e.y < 1.0) { + // White over dark pixels, a weaker black over light ones, cross-faded by luma so a + // mid-tone image never flips line colour from one cell to the next (pixel_grid.rs + // `light_share`: same band, same numbers). + let t = smoothstep(0.35, 0.75, dot(rgb, vec3(0.299, 0.587, 0.114))); + let white = grid * (1.0 - t); + let black = grid * 0.64 * t; + rgb = rgb * (1.0 - white - black) + vec3(white); + } + } + if (view.d.w > 0.5) { + rgb = srgb_to_linear(rgb); + } + return vec4(rgb, 1.0); +} +"#; + +pub(super) const ENCODE_WGSL: &str = r#" +@group(0) @binding(0) var acc: texture_2d; +@group(0) @binding(1) var offset: vec4; // x, y, encode sRGB, keep values above 1.0 + +@vertex +fn vs(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 { + let uv = vec2(f32((vi << 1u) & 2u), f32(vi & 2u)); + return vec4(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, 0.0, 1.0); +} + +fn srgb_encode(c: vec3) -> vec3 { + return select(1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, c * 12.92, c <= vec3(0.0031308)); +} + +@fragment +fn fs(@builtin(position) pos: vec4) -> @location(0) vec4 { + let c = textureLoad(acc, vec2(floor(pos.xy)) - offset.xy, 0); + let a = clamp(c.a, 0.0, 1.0); + var rgb = max(c.rgb, vec3(0.0)); + if (offset.w == 0) { + rgb = min(rgb, vec3(1.0)); + } + if (offset.z != 0) { + // Linear composite: store its sRGB encoding (8-bit precision where it matters). + rgb = srgb_encode(rgb); + } + return vec4(rgb * a, a); +} +"#; + +pub(super) const MIP_WGSL: &str = r#" +@group(0) @binding(0) var src: texture_2d; +@group(0) @binding(1) var samp: sampler; + +struct V { @builtin(position) pos: vec4, @location(0) uv: vec2 }; + +@vertex +fn vs(@builtin(vertex_index) vi: u32) -> V { + let uv = vec2(f32((vi << 1u) & 2u), f32(vi & 2u)); + return V(vec4(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, 0.0, 1.0), uv); +} + +@fragment +fn fs(in: V) -> @location(0) vec4 { + // A bilinear tap at the destination texel centre averages the 2×2 source block. + return textureSampleLevel(src, samp, in.uv, 0.0); +} +"#; diff --git a/crates/ui-egui/src/canvas/gpu_canvas/tests.rs b/crates/ui-egui/src/canvas/gpu_canvas/tests.rs new file mode 100644 index 0000000000..7402f5026f --- /dev/null +++ b/crates/ui-egui/src/canvas/gpu_canvas/tests.rs @@ -0,0 +1,319 @@ +use super::*; + +/// A GPU measurement arrives a frame or two after its refresh, so most GPU refreshes carry +/// none; the last one reported must stand until a newer one lands. A CPU refresh is +/// different: there is no GPU time at all then, and keeping the old number would show it as +/// this refresh's. Runs anywhere — the GPU timing tests need hardware and CI has none. +#[test] +fn a_gpu_measurement_stands_until_replaced_and_a_cpu_refresh_clears_it() { + let timing = |ms, px| photocraft_gpu::GpuTiming { ms, px, spans: 1 }; + let refresh = |kind, gpu| Refresh { kind, gpu, ..Default::default() }; + let mut perf = Perf::default(); + assert_eq!(perf.gpu_ms, None, "nothing is reported before a measurement"); + + perf.record_refresh(&refresh("gpu-full", Some(timing(83.9, 24_000_000)))); + assert_eq!((perf.gpu_ms, perf.gpu_ms_px), (Some(83.9), 24_000_000)); + + // The common case: a GPU refresh whose own measurement has not come back yet. + perf.record_refresh(&refresh("gpu-rect", None)); + assert_eq!((perf.gpu_ms, perf.gpu_ms_px), (Some(83.9), 24_000_000), "the last measurement stands"); + + perf.record_refresh(&refresh("gpu-rect", Some(timing(11.2, 1_098_640)))); + assert_eq!((perf.gpu_ms, perf.gpu_ms_px), (Some(11.2), 1_098_640), "a newer measurement replaces it"); + + // The CPU compositor did this one: the GPU number belongs to no refresh on screen. + perf.record_refresh(&refresh("full", None)); + assert_eq!((perf.gpu_ms, perf.gpu_ms_px), (None, 0), "a CPU refresh clears it rather than showing a stale one"); + + // And it comes back on the next GPU refresh that carries one. + perf.record_refresh(&refresh("gpu-full", Some(timing(42.0, 6_000_000)))); + assert_eq!((perf.gpu_ms, perf.gpu_ms_px), (Some(42.0), 6_000_000)); +} + +#[test] +fn device_limits_support_v3d_shader_variable_limit() { + let supported = wgpu::Limits { max_texture_dimension_2d: 7680, max_inter_stage_shader_variables: 15, ..wgpu::Limits::default() }; + let requested = device_limits_for(wgpu::Backend::Vulkan, supported.clone()); + assert_eq!(requested.max_inter_stage_shader_variables, 15); + assert!(requested.check_limits(&supported)); + assert_eq!(requested.max_texture_dimension_2d, 7680); + assert_eq!(requested.max_buffer_size, supported.max_buffer_size); +} + +#[test] +fn device_limits_support_weaker_gl_adapters() { + let supported = wgpu::Limits { + max_texture_dimension_2d: 1024, + max_texture_dimension_3d: 128, + max_bind_groups: 2, + max_buffer_size: 128 << 20, + ..wgpu::Limits::downlevel_webgl2_defaults() + }; + let requested = device_limits_for(wgpu::Backend::Gl, supported.clone()); + assert!(requested.check_limits(&supported)); + assert_eq!(requested, supported); +} + +#[test] +fn device_limits_preserve_backend_defaults_on_capable_adapters() { + let supported = wgpu::Limits { + max_texture_dimension_2d: 16_384, + max_buffer_size: 1 << 30, + max_bind_groups: 8, + max_inter_stage_shader_variables: 32, + min_uniform_buffer_offset_alignment: 64, + min_storage_buffer_offset_alignment: 64, + ..wgpu::Limits::default() + }; + for (backend, base) in [ + (wgpu::Backend::Vulkan, wgpu::Limits::default()), + (wgpu::Backend::Dx12, wgpu::Limits::default()), + (wgpu::Backend::Metal, wgpu::Limits::default()), + (wgpu::Backend::Gl, wgpu::Limits::downlevel_webgl2_defaults()), + ] { + let requested = device_limits_for(backend, supported.clone()); + assert!(requested.check_limits(&supported)); + assert_eq!(requested, wgpu::Limits { max_texture_dimension_2d: 16_384, max_buffer_size: 1 << 30, ..base }, "{backend:?}"); + } +} + +#[test] +fn device_limits_support_larger_minimum_alignments() { + let supported = wgpu::Limits { min_uniform_buffer_offset_alignment: 512, min_storage_buffer_offset_alignment: 1024, ..wgpu::Limits::default() }; + for backend in [wgpu::Backend::Vulkan, wgpu::Backend::Gl] { + let requested = device_limits_for(backend, supported.clone()); + assert!(requested.check_limits(&supported)); + assert_eq!(requested.min_uniform_buffer_offset_alignment, 512); + assert_eq!(requested.min_storage_buffer_offset_alignment, 1024); + } +} + +/// The scratch-texture workaround is for Intel's DX12 drivers (#892); other DX12 adapters +/// render straight into the level like every other backend (#4515). +#[test] +fn separate_mip_targets_only_for_intel_on_dx12() { + use wgpu::Backend::{Dx12, Metal, Vulkan}; + let (intel, nvidia, amd) = (0x8086, 0x10de, 0x1002); + assert!(separate_mip_targets(Dx12, intel, None)); + assert!(!separate_mip_targets(Dx12, nvidia, None)); + assert!(!separate_mip_targets(Dx12, amd, None)); + assert!(!separate_mip_targets(Vulkan, intel, None)); + assert!(!separate_mip_targets(Metal, 0, None)); + // PHOTOCRAFT_SEPARATE_MIPS forces either way; anything else leaves the default. + assert!(separate_mip_targets(Dx12, nvidia, Some("1"))); + assert!(!separate_mip_targets(Dx12, intel, Some(" 0 "))); + assert!(separate_mip_targets(Dx12, intel, Some("yes"))); +} + +/// #6418: levels of at most WHOLE_MIP_SIDE are redrawn whole; larger ones keep the damage. +#[test] +fn small_mip_levels_are_redrawn_whole() { + // A 3 × 3 dab at (800, 500) of a 1791 × 1083 tile, at mip 1 (895 × 541): halved and padded. + assert_eq!(mip_damage([800, 500, 803, 503], 895, 541), [399, 249, 403, 253]); + // At most 128 px on either side: the whole level, wherever the damage is. + assert_eq!(mip_damage([100, 60, 102, 63], 111, 67), [0, 0, 111, 67]); + assert_eq!(mip_damage([0, 0, 1, 1], 128, 2), [0, 0, 128, 2]); + assert_eq!(mip_damage([0, 0, 1, 1], 129, 2), [0, 0, 2, 2]); +} + +#[test] +fn gpu_budget_follows_memory_usage_and_ram() { + const G: u64 = 1 << 30; + // Card memory unknown (integrated, software, or unreadable): what Memory Usage leaves + // after the document, within a quarter of RAM. + assert_eq!(memory_budget(8 * G, 3 * G, Some(48 * G), None, 0), 5 * G); + assert_eq!(memory_budget(8 * G, 3 * G, Some(16 * G), None, 0), 4 * G); + assert_eq!(memory_budget(64 * G, 3 * G, Some(16 * G), None, 0), 4 * G); + // Never below the floor, even with nothing left; 16 GB assumed when RAM is unknown. + assert_eq!(memory_budget(8 * G, 10 * G, Some(48 * G), None, 0), MIN_GPU_BUDGET); + assert_eq!(memory_budget(64 * G, 0, None, None, 0), 4 * G); + // A card's own memory, known, doesn't hold the document's pixels: 10 GB of layers no + // longer squeeze the budget, which stays within 3/8 of the card (#4536). + assert_eq!(memory_budget(8 * G, 10 * G, Some(32 * G), Some(32 * G), 0), 8 * G); + assert_eq!(memory_budget(8 * G, 10 * G, Some(32 * G), Some(16 * G), 0), 6 * G); + assert_eq!(memory_budget(8 * G, 10 * G, Some(16 * G), Some(32 * G), 0), 4 * G); + // GPU Memory set: that much, within the card's share, above the floor. + assert_eq!(memory_budget(8 * G, 10 * G, Some(16 * G), None, 12 * G), 12 * G); + assert_eq!(memory_budget(8 * G, 10 * G, Some(16 * G), Some(16 * G), 12 * G), 6 * G); + assert_eq!(memory_budget(8 * G, 0, None, Some(32 * G), 1 << 20), MIN_GPU_BUDGET); + assert!(physical_memory().is_none_or(|b| b >= 256 << 20)); +} + +/// An 8 GB card in a 64 GB machine: both budgets used to plan for 16 GB, twice the card (#4536). +#[test] +fn gpu_budgets_fit_a_discrete_gpus_own_memory() { + const G: u64 = 1 << 30; + let (ram, vram) = (Some(64 * G), Some(8 * G)); + assert_eq!(memory_budget(64 * G, 3 * G, ram, vram, 0), 3 * G); + assert_eq!(canvas_budget(ram, vram), 3 * G); + assert!(memory_budget(64 * G, 0, ram, vram, 0) + canvas_budget(ram, vram) <= 6 * G, "a quarter of the card stays free"); + // A card larger than a quarter of RAM caps nothing (its own memory isn't charged for the + // document's 3 GB); a tiny one keeps the floor. + assert_eq!(memory_budget(8 * G, 3 * G, Some(48 * G), Some(24 * G), 0), 8 * G); + assert_eq!(canvas_budget(Some(16 * G), Some(24 * G)), 4 * G); + assert_eq!(memory_budget(64 * G, 0, ram, Some(G), 0), MIN_GPU_BUDGET); + assert_eq!(canvas_budget(ram, Some(G)), MIN_GPU_BUDGET); +} + +/// DXGI reports each adapter's dedicated memory, found by the vendor and device ids wgpu gives. +#[cfg(windows)] +#[test] +fn windows_reports_the_adapters_own_memory() { + use winsafe::prelude::*; + let descs: Vec<_> = winsafe::CreateDXGIFactory1().unwrap().EnumAdapters1().map(|a| a.unwrap().GetDesc1().unwrap()).collect(); + assert!(!descs.is_empty(), "DXGI lists at least its software adapter"); + for d in descs.iter().filter(|d| d.DedicatedVideoMemory > 0) { + // The first adapter with these ids is the one matched. + let first = descs.iter().find(|e| e.VendorId == d.VendorId && e.DeviceId == d.DeviceId).unwrap(); + assert_eq!(detect_video_memory(d.VendorId, d.DeviceId), Some(first.DedicatedVideoMemory as u64)); + } + assert_eq!(detect_video_memory(0xdead, 0xbeef), None, "no such adapter"); +} + +/// System Info names the card's own memory, after the driver, when the card reports one; an +/// integrated GPU or an unknown card shows no such line. +#[test] +fn system_info_shows_the_cards_memory() { + let info = GpuInfo { adapter: "Card".into(), driver: "Driver 1".into(), video_memory_mb: Some(8192), ..Default::default() }; + let lines = info.lines(); + assert_eq!(lines.get(2).map(String::as_str), Some("Driver: Driver 1")); + assert_eq!(lines.get(3).map(String::as_str), Some("Graphics memory: 8.0G")); + let none = GpuInfo { video_memory_mb: None, ..info }.lines(); + assert!(none.iter().all(|l| !l.starts_with("Graphics memory")), "{none:?}"); + assert_eq!(none.len() + 1, lines.len()); +} + +/// The Linux reader finds the card by its PCI ids in a `/sys/class/drm`-shaped folder and reads +/// amdgpu's VRAM size; a card without one, unreadable ids or a malformed size give nothing. +#[test] +fn drm_video_memory_reads_the_matching_cards_vram() { + let drm = std::env::temp_dir().join(format!("pc-drm-{}", std::process::id())); + let card = |name: &str, vendor: &str, device: &str, vram: Option<&str>| { + let dev = drm.join(name).join("device"); + std::fs::create_dir_all(&dev).unwrap(); + std::fs::write(dev.join("vendor"), vendor).unwrap(); + std::fs::write(dev.join("device"), device).unwrap(); + if let Some(v) = vram { + std::fs::write(dev.join("mem_info_vram_total"), v).unwrap(); + } + }; + // An Intel iGPU (no VRAM file), an AMD card, and an entry with garbage ids. + card("card0", "0x8086\n", "0x9a49\n", None); + card("card1", "0x1002\n", "0x73bf\n", Some("17163091968\n")); + card("card2", "not hex\n", "0x73bf\n", Some("1\n")); + card("card3", "0x10de\n", "0x2684\n", Some("lots\n")); + assert_eq!(drm_video_memory(&drm, 0x1002, 0x73bf), Some(17_163_091_968)); + assert_eq!(drm_video_memory(&drm, 0x8086, 0x9a49), None, "no amdgpu VRAM file"); + assert_eq!(drm_video_memory(&drm, 0x10de, 0x2684), None, "a malformed size"); + assert_eq!(drm_video_memory(&drm, 0xdead, 0xbeef), None, "no such card"); + assert_eq!(drm_video_memory(&drm.join("missing"), 0x1002, 0x73bf), None, "no drm folder"); + std::fs::remove_dir_all(&drm).unwrap(); +} + +/// Windows used to report no RAM at all, so the budget assumed 16 GB on every machine. +#[cfg(windows)] +#[test] +fn windows_reports_installed_ram() { + let ram = detect_physical_memory().unwrap_or(0); + assert!(ram >= 256 << 20, "{ram} bytes"); + assert!(ram < 1 << 50, "{ram} bytes"); +} + +#[test] +fn canvas_texture_bytes_price_every_tile_and_mip_level() { + // The same sum DocTextures builds tile by tile (and texture_info reports). + let brute = |size: [u32; 2], tile: u32, bpp: u64| -> u64 { + let mut total = 0; + for ty in (0..size[1]).step_by(tile as usize) { + for tx in (0..size[0]).step_by(tile as usize) { + let (w, h) = (tile.min(size[0] - tx), tile.min(size[1] - ty)); + total += (0..mip_count(w, h)).map(|l| u64::from((w >> l).max(1)) * u64::from((h >> l).max(1)) * bpp).sum::(); + } + } + total + }; + for (size, tile) in [([1, 1], 64), ([300, 200], 64), ([128, 64], 64), ([1000, 7], 256), ([8192, 8193], 8192), ([20_000, 9_000], 8192)] { + for bpp in [4, 8] { + assert_eq!(canvas_texture_bytes(size, tile, bpp), brute(size, tile, bpp), "{size:?} tile {tile}"); + } + } + assert_eq!(canvas_texture_bytes([0, 500], 64, 4), 0); + // A canvas declared in a few bytes of a file is priced without building (or looping over) it. + let huge = canvas_texture_bytes([300_000, 300_000], 8192, 4); + assert!(huge > 300_000u64 * 300_000 * 4 && huge > canvas_budget(Some(1 << 40), None)); + assert_eq!(canvas_texture_bytes([u32::MAX, u32::MAX], 64, 8), u64::MAX, "saturates"); + // A quarter of RAM (16 GB assumed), never below the compositor's floor. + assert_eq!(canvas_budget(None, None), 4 << 30); + assert_eq!(canvas_budget(Some(1 << 30), None), MIN_GPU_BUDGET); + assert!(canvas_texture_bytes([12_000, 8_000], DEFAULT_TILE, 8) < canvas_budget(None, None), "a 96 MP 16-bit canvas stays on the GPU"); +} + +#[test] +fn view_uniform_packs_rotation() { + assert_eq!(VIEW_FLOATS, 32); + assert_eq!(VIEW_UNIFORM_SIZE, 128); + assert_eq!(VIEW_FLOATS * 4, VIEW_UNIFORM_SIZE as usize); + assert!(gpu_view_ok(false, 0.0, 1.0)); + assert!(gpu_view_ok(false, 45.0_f32.to_radians(), 1.0)); + assert!(!gpu_view_ok(true, 45.0_f32.to_radians(), 1.0)); + assert!(!gpu_view_ok(false, 0.0, 2.0), "pixel aspect correction draws on the CPU"); + // Identity packing: rotation 0 matches the unrotated origin + scale map. + let origin = [10.0, 20.0]; + let (scale, center) = (2.0, [40.0, 8.0]); + let a = map_doc_px(origin, scale, center, 1.0, 0.0, 5.0, 9.0); + assert!((a[0] - (origin[0] + 5.0 * scale)).abs() < 1e-4); + assert!((a[1] - (origin[1] + 9.0 * scale)).abs() < 1e-4); + let (x0, y0, x1, y1) = tile_screen_aabb(origin, scale, center, 1.0, 0.0, [0.0, 0.0, 10.0, 4.0]); + assert!((x0 - origin[0]).abs() < 1e-4 && (y0 - origin[1]).abs() < 1e-4); + assert!((x1 - (origin[0] + 20.0)).abs() < 1e-4 && (y1 - (origin[1] + 8.0)).abs() < 1e-4); +} + +#[test] +fn filter_modes() { + assert_eq!(filter_mode(0.25), (0.0, 2.0)); + assert_eq!(filter_mode(1.0).0, 2.0); + assert_eq!(filter_mode(1.5).0, 1.0); + assert_eq!(filter_mode(3.3).0, 2.0); +} + +#[test] +fn mips_and_premultiply() { + assert_eq!(mip_count(1, 1), 1); + assert_eq!(mip_count(4096, 100), 13); + assert_eq!(mip_count(5, 3), 3); + assert_eq!(premultiply_rgba8(&[[1.0, 0.5, 0.0, 0.5]]), vec![128, 64, 0, 128]); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn half_floats() { + // Every finite half survives the round trip; ties round to even; overflow saturates. + for h in 0..=u16::MAX { + if h & 0x7c00 != 0x7c00 && h != 0x8000 { + assert_eq!(f32_to_f16(f16_to_f32(h)), h, "{h:#06x}"); + } + } + assert_eq!(f32_to_f16(1.0), 0x3c00); + assert_eq!(f32_to_f16(1.0 + 2f32.powi(-11)), 0x3c00); + assert_eq!(f32_to_f16(1.0 + 3.0 * 2f32.powi(-11)), 0x3c02); + assert_eq!(f32_to_f16(2f32.powi(-24)), 1); + assert_eq!(f32_to_f16(2f32.powi(-26)), 0); + assert_eq!(f32_to_f16(65504.0), 0x7bff); + assert_eq!(f32_to_f16(1e9), 0x7bff); + assert_eq!(f32_to_f16(f32::INFINITY), 0x7bff); + assert_eq!(f32_to_f16(f32::NAN), 0); + assert_eq!(f32_to_f16(-2.0), 0xc000); + assert_eq!(premultiply_rgba16f(&[[2.0, -1.0, f32::NAN, 0.5]]), [0x00, 0x3c, 0, 0, 0, 0, 0x00, 0x38]); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn shaders_validate() { + use wgpu::naga; + for (name, src) in [("canvas", CANVAS_WGSL), ("mip", MIP_WGSL), ("encode", ENCODE_WGSL)] { + let module = naga::front::wgsl::parse_str(src).unwrap_or_else(|e| panic!("{name}: {}", e.emit_to_string(src))); + naga::valid::Validator::new(naga::valid::ValidationFlags::all(), naga::valid::Capabilities::empty()) + .validate(&module) + .unwrap_or_else(|e| panic!("{name}: {e:?}")); + } +} diff --git a/crates/ui-egui/src/canvas/gpu_canvas/texels.rs b/crates/ui-egui/src/canvas/gpu_canvas/texels.rs new file mode 100644 index 0000000000..966b23c40c --- /dev/null +++ b/crates/ui-egui/src/canvas/gpu_canvas/texels.rs @@ -0,0 +1,145 @@ +use super::*; + +/// Straight-alpha f32 RGBA (sRGB-encoded) → premultiplied RGBA8, split across threads on native. +pub fn premultiply_rgba8(px: &[[f32; 4]]) -> Vec { + let mut out = Vec::new(); + texels_into(FORMAT, px, &mut out); + out +} + +/// Straight-alpha f32 RGBA (sRGB-encoded) → premultiplied RGBA16F (little-endian), split across +/// threads on native. Colour values above 1.0 are kept (32-bit documents); negatives and NaN +/// become 0. +pub fn premultiply_rgba16f(px: &[[f32; 4]]) -> Vec { + let mut out = Vec::new(); + texels_into(FORMAT_HIGH, px, &mut out); + out +} + +/// Bytes per texel of a canvas texture format. +pub(super) fn texel_bytes(format: wgpu::TextureFormat) -> u64 { + if format == FORMAT_HIGH { 8 } else { 4 } +} + +/// Straight-alpha f32 RGBA → premultiplied texels of `format`. +pub(super) fn texels(format: wgpu::TextureFormat, px: &[[f32; 4]]) -> Vec { + let mut out = Vec::new(); + texels_into(format, px, &mut out); + out +} + +/// [`texels`] into `out` (resized; reusing it across bands saves page-faulting a fresh buffer). +pub(super) fn texels_into(format: wgpu::TextureFormat, px: &[[f32; 4]], out: &mut Vec) { + fn rgba8(src: &[[f32; 4]], dst: &mut [u8]) { + for (o, p) in dst.as_chunks_mut::<4>().0.iter_mut().zip(src) { + let a = p[3].clamp(0.0, 1.0); + o[0] = (p[0].clamp(0.0, 1.0) * a * 255.0 + 0.5) as u8; + o[1] = (p[1].clamp(0.0, 1.0) * a * 255.0 + 0.5) as u8; + o[2] = (p[2].clamp(0.0, 1.0) * a * 255.0 + 0.5) as u8; + o[3] = (a * 255.0 + 0.5) as u8; + } + } + fn rgba16f(src: &[[f32; 4]], dst: &mut [u8]) { + for (o, p) in dst.as_chunks_mut::<8>().0.iter_mut().zip(src) { + let a = if p[3].is_nan() { 0.0 } else { p[3].clamp(0.0, 1.0) }; + let [r, g, b, a] = [p[0].max(0.0) * a, p[1].max(0.0) * a, p[2].max(0.0) * a, a].map(|v| f32_to_f16(v).to_le_bytes()); + *o = [r[0], r[1], g[0], g[1], b[0], b[1], a[0], a[1]]; + } + } + let bpp = texel_bytes(format) as usize; + let convert = if format == FORMAT_HIGH { rgba16f } else { rgba8 }; + out.clear(); + out.resize(px.len() * bpp, 0); + #[cfg(not(target_arch = "wasm32"))] + if px.len() > 1 << 18 { + let threads = std::thread::available_parallelism().map_or(4, |n| n.get()).min(16); + let chunk = px.len().div_ceil(threads); + std::thread::scope(|s| { + for (src, dst) in px.chunks(chunk).zip(out.chunks_mut(chunk * bpp)) { + s.spawn(move || convert(src, dst)); + } + }); + return; + } + convert(px, out); +} + +/// IEEE 754 binary32 → binary16, round to nearest even; overflow saturates to the largest +/// finite half (65504) so HDR values never become infinite, NaN becomes 0. Branch-light: the +/// rounding is done with integer adds on the f32 bits (and an f32 add for subnormals). +pub(super) fn f32_to_f16(v: f32) -> u16 { + // 2^-14: the smallest normal half; below it the result is subnormal (or zero). + const MIN_NORMAL: u32 = 113 << 23; + // 2^16: halves overflow from here (65520 and up round to infinity; saturate instead). + const OVERFLOW: u32 = 143 << 23; + // Adding 0.5 (as f32) shifts a subnormal half's bits to the bottom of the mantissa. + const DENORM_MAGIC: u32 = 126 << 23; + let bits = v.to_bits(); + let sign = ((bits >> 16) & 0x8000) as u16; + let a = bits & 0x7fff_ffff; + if a > 0x7f80_0000 { + return 0; + } + let h = if a >= OVERFLOW { + 0x7bff + } else if a < MIN_NORMAL { + (f32::from_bits(a) + f32::from_bits(DENORM_MAGIC)).to_bits().wrapping_sub(DENORM_MAGIC) as u16 + } else { + // Rebias the exponent and round the 13 dropped mantissa bits to nearest even. + let odd = (a >> 13) & 1; + (((a.wrapping_add(0xc800_0fff).wrapping_add(odd)) >> 13).min(0x7bff)) as u16 + }; + sign | h +} + +/// IEEE 754 binary16 → binary32. +#[cfg(not(target_arch = "wasm32"))] +pub(super) fn f16_to_f32(h: u16) -> f32 { + let sign = if h & 0x8000 != 0 { -1.0 } else { 1.0 }; + let exp = i32::from((h >> 10) & 0x1f); + let man = f32::from(h & 0x3ff); + sign * match exp { + 0 => man * 2f32.powi(-24), + 0x1f => { + if man == 0.0 { + f32::INFINITY + } else { + f32::NAN + } + } + e => (1.0 + man / 1024.0) * 2f32.powi(e - 15), + } +} + +/// One stored texel of `format` as f32 RGBA. +#[cfg(not(target_arch = "wasm32"))] +pub(super) fn texel_to_f32(format: wgpu::TextureFormat, b: &[u8]) -> [f32; 4] { + let mut o = [0.0f32; 4]; + for (i, v) in o.iter_mut().enumerate() { + *v = if format == FORMAT_HIGH { + f16_to_f32(u16::from_le_bytes([b.get(i * 2).copied().unwrap_or(0), b.get(i * 2 + 1).copied().unwrap_or(0)])) + } else { + f32::from(b.get(i).copied().unwrap_or(0)) / 255.0 + }; + } + o +} + +// --------------------------------------------------------------------------------------------- +// GPU resources + +/// The GPU memory a refresh's layer pages need against what they may hold (bytes). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct LayerFit { + /// The document refreshed. + pub doc: u64, + pub needed: u64, + pub budget: u64, +} + +impl LayerFit { + pub fn fits(&self) -> bool { + self.needed <= self.budget + } +} diff --git a/crates/ui-egui/src/guide_select.rs b/crates/ui-egui/src/canvas/guide_select.rs similarity index 100% rename from crates/ui-egui/src/guide_select.rs rename to crates/ui-egui/src/canvas/guide_select.rs diff --git a/crates/ui-egui/src/guide_select/tests.rs b/crates/ui-egui/src/canvas/guide_select/tests.rs similarity index 100% rename from crates/ui-egui/src/guide_select/tests.rs rename to crates/ui-egui/src/canvas/guide_select/tests.rs diff --git a/crates/ui-egui/src/layer_pick_ui.rs b/crates/ui-egui/src/canvas/layer_pick_ui.rs similarity index 100% rename from crates/ui-egui/src/layer_pick_ui.rs rename to crates/ui-egui/src/canvas/layer_pick_ui.rs diff --git a/crates/ui-egui/src/canvas/move_ui.rs b/crates/ui-egui/src/canvas/move_ui.rs new file mode 100644 index 0000000000..29920474f7 --- /dev/null +++ b/crates/ui-egui/src/canvas/move_ui.rs @@ -0,0 +1,301 @@ +//! Move tool drags shown live (#128): while the pointer drags, the canvas shows the document with +//! the moving layers already at the pointer, exactly as `layer.translate` will leave them, and +//! recomposites only where they were and where they are. Releasing commits one `layer.translate` +//! (one history step) whose damage rect refreshes the same area. +//! +//! With a selection, the Move tool drags the selected pixels instead (#578): they float +//! (`select.float`, the canvas shows the piece at the pointer) until ↩, Deselect or any other +//! command drops them, as one "Move" history step. + +use std::sync::Arc; + +use photocraft_doc::{DocId, Document, LayerId}; +use photocraft_geom::Rect; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::state::Tool; + +/// Does the Move tool drag (and do the arrow keys nudge) the selected pixels of the active layer +/// rather than the whole layer, with `tool` in effect? With a selection, as in Photoshop; a layer +/// whose pixels can't float (type, shape, Smart Object, group, position-locked), a hidden layer or +/// several selected layers still move whole, as without one. The canvas cursor asks before the +/// press, and a pointer event passes `canvas::event_tool`, which also sees a ⌘ sent with the event +/// (#2768). +pub(crate) fn moves_selected_pixels_with(app: &PhotocraftApp, tool: Tool) -> bool { + let Some(st) = app.session.active() else { return false }; + tool == Tool::Move + && app.ui.transform.is_none() + && st.doc.selection.is_some() + && st.selected_layers().len() <= 1 + && st.active_layer.and_then(|id| st.doc.layer(id)).is_some_and(|l| l.visible) + && app.session.is_enabled("select.float") +} + +/// Floats the selected pixels and moves them by (dx, dy) (`select.float`): cuts them the first +/// time, or with `copy` (⌥) floats a duplicate and leaves them; `copy` on a piece already floating +/// drops it where it is and floats a copy of it. False when it failed (reported in the status bar). +pub(crate) fn float_selected(app: &mut PhotocraftApp, copy: bool, dx: f64, dy: f64) -> bool { + let floating = app.session.active().is_some_and(|st| photocraft_engine::float_cmds::floating(st).is_some()); + let dropped = if copy && floating { app.run("select.drop", json!({})) } else { Ok(json!(null)) }; + match dropped.and_then(|_| app.run("select.float", json!({"dx": dx, "dy": dy, "copy": copy}))) { + Ok(_) => { + crate::snap_ui::follow_cut(app); + true + } + Err(e) => { + app.ui.status = e; + app.ui.status_error = true; + false + } + } +} + +/// Preview keys of move drags: `BASE + n`, one per offset shown (see `canvas::display_doc`). +const BASE: u64 = 1 << 39; + +pub(crate) struct MovePreview { + doc: DocId, + revision: u64, + /// Layers that move ([`photocraft_engine::layer_multi_cmds::move_targets`]). + ids: Vec, + /// `ids` and every layer inside them: the layers shown at the drag's offset. + moving: Vec, + /// What moving them can change at offset (0, 0), not clipped to the canvas: a layer larger + /// than the canvas brings its pixels from beyond the edge into view (`None` = anything). + bounds: Option, + canvas: Rect, + /// Offsets shown so far, by preview key (`BASE + index`). + offsets: Vec<(i32, i32)>, + /// The document at the latest offset. + shown: Option>, + /// Shows a floating selection (`select.float`): offsets are the piece's, from where it was cut. + floating: bool, +} + +impl MovePreview { + fn key(&self) -> u64 { + BASE + self.offsets.len() as u64 + } + fn offset_of(&self, key: u64) -> Option<(i32, i32)> { + if key == 0 { + return Some((0, 0)); + } + let i = usize::try_from(key.checked_sub(BASE + 1)?).ok()?; + self.offsets.get(i).copied() + } + fn area(&self, d: (i32, i32)) -> Option { + let b = self.bounds?; + Some(if b.is_empty() { b } else { b.translate(d.0, d.1).inflate(1).intersect(&self.canvas) }) + } +} + +/// The whole-pixel offset of the current Move drag on document `idx`, if one is under way. +fn drag_offset(app: &PhotocraftApp) -> Option<(i32, i32)> { + let d = app.drag.as_ref().filter(|d| d.tool == Tool::Move)?; + let end = d.points.last().map_or(d.start, |p| [p[0], p[1]]); + let dx = (end[0] - d.start[0]).round().clamp(-1e7, 1e7) as i32; + let dy = (end[1] - d.start[1]).round().clamp(-1e7, 1e7) as i32; + Some((dx, dy)) +} + +/// The ΔX/ΔY values shown beside the pointer while the Move tool drags layers or selected pixels, +/// as in Photoshop (#5727): the whole pixels the release will move them. Free Transform shows its +/// own (`transform_tool::live_readout`). `None` until the pointer moves. +pub(crate) fn offset_readout(app: &PhotocraftApp) -> Option<[String; 2]> { + app.drag.as_ref().filter(|d| d.points.len() > 1)?; + let (dx, dy) = drag_offset(app)?; + Some([dx, dy].map(|v| format!("{v} px"))) +} + +/// The document to show while a Move drag is under way on document `idx`: the moving layers at +/// the pointer. `None` without a drag (or when the layers can't move: locked, say; the drag then +/// shows its arrow and the release reports why). +pub(crate) fn display_doc(app: &mut PhotocraftApp, idx: usize) -> Option<(Arc, u64)> { + if app.session.active_index() == Some(idx) + && let Some(st) = app.session.documents().get(idx) + && photocraft_engine::float_cmds::floating(st).is_some() + { + return floating_doc(app, idx); + } + // Preferences › Interface › Show bounding box when dragging layer: outline and arrow only. + if app.session.active_index() != Some(idx) || app.session.prefs().interface.show_bounding_box_when_dragging_layer { + return None; + } + let Some(offset) = drag_offset(app) else { + app.move_preview = None; + return None; + }; + let mask_target = app.layer_mask_targeted(); + let st = app.session.documents().get(idx)?; + let (doc_id, revision, doc) = (st.doc.id, st.revision, st.doc.clone()); + let fresh = app.move_preview.as_ref().is_some_and(|p| p.doc == doc_id && p.revision == revision); + if !fresh { + let ids = photocraft_engine::layer_multi_cmds::move_targets(&doc, &st.selected_layers()); + if ids.is_empty() { + return None; + } + let all = Rect::new(i32::MIN / 2, i32::MIN / 2, i32::MAX / 2, i32::MAX / 2); + let bounds = ids.iter().try_fold(Rect::EMPTY, |acc, id| Some(acc.union(&photocraft_compose::change_bounds(doc.layer(*id)?, all)?))); + let canvas = doc.bounds(); + let moving = with_descendants(&doc, &ids); + let bounds = bounds.map(|b| moving.iter().filter_map(|id| shape_reach(doc.layer(*id)?, canvas)).fold(b, |acc, r| acc.union(&r))); + app.move_preview = Some(MovePreview { doc: doc_id, revision, ids, moving, bounds, canvas, offsets: Vec::new(), shown: None, floating: false }); + } + let p = app.move_preview.as_mut()?; + if offset == (0, 0) && p.offsets.is_empty() { + return None; + } + if p.offsets.last() != Some(&offset) { + let t0 = crate::gpu_canvas::now_ms(); + match photocraft_engine::layer_multi_cmds::moved_target(&doc, &p.ids, offset.0, offset.1, mask_target) { + Ok(d) => { + // Duotone documents display through their inks. + let d = photocraft_engine::mode_cmds::display_document(&d).unwrap_or(d); + p.shown = Some(Arc::new(d)); + p.offsets.push(offset); + } + Err(_) => { + p.shown = None; + return None; + } + } + app.perf.span("move preview", crate::gpu_canvas::now_ms() - t0); + } + let p = app.move_preview.as_ref()?; + Some((p.shown.clone()?, p.key())) +} + +/// Where shape layer `l` paints, effects included, not cut at the canvas as its rendered pixels +/// are: a drag brings the rest of it into view (#3946). `None` for other layers. +fn shape_reach(l: &photocraft_doc::Layer, canvas: Rect) -> Option { + let photocraft_doc::LayerContent::Shape(sh) = &l.content else { return None }; + let b = photocraft_vector::CompiledShape::new(sh, photocraft_vector::DEFAULT_TOLERANCE, canvas).bounds()?; + let m = if photocraft_compose::effects::has_effects(l) { photocraft_compose::effects::margin(l) } else { 0 }; + Some(b.inflate(m)) +} + +/// `ids` and every layer inside them (groups move their contents). +fn with_descendants(doc: &Document, ids: &[LayerId]) -> Vec { + let walk = doc.walk(); + let roots: Vec<_> = walk.iter().filter(|(_, _, l)| ids.contains(&l.id)).map(|(p, _, _)| p.as_slice()).collect(); + walk.iter().filter(|(p, _, _)| roots.iter().any(|r| p.starts_with(r))).map(|(_, _, l)| l.id).collect() +} + +/// Where the canvas shows layer `id` of document `doc` at `revision` relative to where it is: the +/// offset of the latest Move drag frame drawn ([`display_doc`]) when the layer moves with the drag, +/// so its Layer Edges outline moves in lockstep with its pixels (#2413). `None` when it shows +/// where it is. +pub(crate) fn shown_layer_offset(app: &PhotocraftApp, doc: DocId, revision: u64, id: LayerId) -> Option<(i32, i32)> { + let p = app.move_preview.as_ref().filter(|p| p.doc == doc && p.revision == revision && !p.floating && p.shown.is_some())?; + if !p.moving.contains(&id) { + return None; + } + p.offsets.last().copied() +} + +/// A floating selection's offset plus a drag of it in progress (`canvas::selection_drag_delta`). +pub(crate) fn floating_offset(app: &PhotocraftApp) -> Option<(i32, i32)> { + let f = photocraft_engine::float_cmds::floating(app.session.active()?)?; + let d = crate::canvas::selection_drag_delta(app).unwrap_or((0, 0)); + Some((f.offset.0 + d.0, f.offset.1 + d.1)) +} + +/// The document shown while a selection floats: the cut piece at its offset, over the cut-out +/// layer. Only the piece's area changes between offsets, so each move costs the piece, not the +/// layer. +fn floating_doc(app: &mut PhotocraftApp, idx: usize) -> Option<(Arc, u64)> { + let offset = floating_offset(app)?; + let st = app.session.documents().get(idx)?; + let f = photocraft_engine::float_cmds::floating(st)?; + let (doc_id, revision) = (st.doc.id, st.revision); + let fresh = app.move_preview.as_ref().is_some_and(|p| p.doc == doc_id && p.revision == revision && p.floating); + if !fresh { + let bounds = st.doc.selection.as_ref().map(|s| s.content_bounds()); + let canvas = st.doc.bounds(); + app.move_preview = Some(MovePreview { + doc: doc_id, + revision, + ids: vec![f.layer], + moving: Vec::new(), + bounds, + canvas, + offsets: Vec::new(), + shown: None, + floating: true, + }); + } + if offset == (0, 0) && app.move_preview.as_ref().is_none_or(|p| p.offsets.is_empty()) { + return None; + } + let st = app.session.documents().get(idx)?; + let shown = app.move_preview.as_ref()?.offsets.last() != Some(&offset); + if shown { + let t0 = crate::gpu_canvas::now_ms(); + let d = photocraft_engine::float_cmds::displayed(st, crate::canvas::selection_drag_delta(app).unwrap_or((0, 0)))?; + let d = photocraft_engine::mode_cmds::display_document(&d).unwrap_or(d); + let p = app.move_preview.as_mut()?; + p.shown = Some(Arc::new(d)); + p.offsets.push(offset); + app.perf.span("floating preview", crate::gpu_canvas::now_ms() - t0); + } + let p = app.move_preview.as_ref()?; + Some((p.shown.clone()?, p.key())) +} + +/// What changed between preview (or document) key `seen` and `now` of the current Move drag on +/// document `doc` at `revision`: where the moving layers were in both. `None` when either key +/// isn't one of this drag's (the canvas then recomposites everything). +pub(crate) fn damage(app: &PhotocraftApp, doc: DocId, revision: u64, seen: u64, now: u64) -> Option { + let p = app.move_preview.as_ref().filter(|p| p.doc == doc && p.revision == revision)?; + if seen == now || (seen < BASE && seen != 0) || (now < BASE && now != 0) { + return None; + } + let (a, b) = (p.area(p.offset_of(seen)?)?, p.area(p.offset_of(now)?)?); + Some(if a.is_empty() { + b + } else if b.is_empty() { + a + } else { + a.union(&b) + }) +} + +/// Whether the canvas shows a Move drag's layers at the pointer. +pub(crate) fn showing(app: &PhotocraftApp) -> bool { + app.move_preview.as_ref().is_some_and(|p| p.shown.is_some()) +} + +/// Whether `key` is a Move drag preview key. +pub(crate) fn is_preview_key(key: u64) -> bool { + key > BASE && key < BASE << 1 +} + +/// Does a Move drag of whole layers take the selection along? With several layers selected, as +/// in Photoshop (#7538): their selected pixels can't float, so the layers move and the marching +/// ants follow them. +pub(crate) fn carries_selection(app: &PhotocraftApp) -> bool { + app.session.active().is_some_and(|st| st.doc.selection.is_some() && st.selected_layers().len() > 1) +} + +/// Release: one `layer.translate` by the drag's offset. The canvas already shows the result, so +/// its caches are told it showed the document: the command's damage rect refreshes that area. +pub(crate) fn finish(app: &mut PhotocraftApp, dx: f64, dy: f64) { + // Within the range the preview and the ΔX/ΔY readout show (`drag_offset`), so the release + // commits the offset they showed even at the lowest zoom of a huge document. + let (dx, dy) = (dx.clamp(-1e7, 1e7), dy.clamp(-1e7, 1e7)); + // Only when the canvas shows this very offset (else it recomposites everything once). + let at = (dx as i32, dy as i32); + let shown = app.move_preview.take().filter(|p| p.shown.is_some() && p.offsets.last() == Some(&at)); + if dx == 0.0 && dy == 0.0 { + return; + } + if app.run("layer.translate", json!({"dx": dx, "dy": dy, "selection": carries_selection(app)})).is_err() { + return; + } + let Some(p) = shown else { return }; + crate::canvas::shown_as_document(app, p.doc, is_preview_key); +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/canvas/move_ui/tests.rs b/crates/ui-egui/src/canvas/move_ui/tests.rs new file mode 100644 index 0000000000..80bea71dc2 --- /dev/null +++ b/crates/ui-egui/src/canvas/move_ui/tests.rs @@ -0,0 +1,345 @@ +use photocraft_geom::Rect; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::canvas::ToolEvent; +use crate::state::Tool; + +#[test] +fn dragging_a_layer_larger_than_the_canvas_redraws_what_comes_in_from_beyond_the_edge() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); + app.sync_views(); + app.session.execute("layer.new.layer", json!({})).unwrap(); + app.session + .edit("paint", |doc, a| { + doc.layer_mut(a.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(-32, -32, 96, 96), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + app.ui.tool = Tool::Move; + app.ui.extras.snap = false; + app.ui.view.show.smart_guides = false; + let m = egui::Modifiers::NONE; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 32.0, y: 32.0, pressure: 1.0 }, m); + let mut keys = Vec::new(); + for x in [42.0, 52.0] { + crate::canvas::tool_event(&mut app, ToolEvent::Move { x, y: 32.0, pressure: 1.0 }, m); + keys.push(super::display_doc(&mut app, 0).unwrap().1); + } + let st = app.session.active().unwrap(); + // From +10 to +20 the strip x 0..10 shows pixels that were off the canvas a frame ago. + let r = super::damage(&app, st.doc.id, st.revision, keys[0], keys[1]).unwrap(); + assert_eq!(r, Rect::new(0, 0, 64, 64)); +} + +/// The Move tool shows how far it has moved the layer, ΔX/ΔY in whole pixels, as Photoshop +/// and Free Transform do (#5727): once the pointer moves, until the release. +#[test] +fn a_move_drag_reads_out_the_offset_it_will_commit() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); + app.sync_views(); + app.session.execute("layer.new.layer", json!({})).unwrap(); + app.session + .edit("paint", |doc, a| { + doc.layer_mut(a.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(16, 16, 32, 32), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + app.ui.tool = Tool::Move; + app.ui.extras.snap = false; + app.ui.view.show.smart_guides = false; + let m = egui::Modifiers::NONE; + assert_eq!(super::offset_readout(&app), None, "no drag"); + // Pressed on the red square (16..32): with Auto-Select (on by default) an empty spot would + // start the layer marquee instead of a move. + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 24.0, y: 24.0, pressure: 1.0 }, m); + assert_eq!(super::offset_readout(&app), None, "pressed, not moved yet"); + crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 34.4, y: 20.8, pressure: 1.0 }, m); + assert_eq!(super::offset_readout(&app), Some(["10 px".to_string(), "-3 px".to_string()])); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 34.4, y: 20.8 }, m); + assert_eq!(super::offset_readout(&app), None, "released"); +} + +/// A release past the ±10,000,000 px the preview and the readout show commits the offset they +/// showed, not the raw pointer distance. +#[test] +fn a_release_commits_the_offset_the_readout_caps_at() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 64, "height": 64, "background": "transparent"})).unwrap(); + app.sync_views(); + app.session.execute("layer.new.layer", json!({})).unwrap(); + app.session.execute("select.rect", json!({"x": 8, "y": 8, "width": 16, "height": 16})).unwrap(); + app.session.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.session.execute("select.deselect", json!({})).unwrap(); + super::finish(&mut app, 2.5e7, -2.5e7); + let st = app.session.active().unwrap(); + let s = st.active_layer.and_then(|id| st.doc.layer(id)).and_then(|l| l.surface()).unwrap(); + assert!(s.pixel(16 + 10_000_000, 16 - 10_000_000)[3] > 0.5, "moved by the capped offset"); +} + +/// A shape reaching past the canvas edge renders cut at the canvas, but its path goes on: a +/// drag frame must redraw where the rest of it was, or the cut edge stays behind (#3946). +#[test] +fn dragging_a_shape_past_the_canvas_edge_leaves_no_trail() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 64, "height": 64, "background": "transparent"})).unwrap(); + app.sync_views(); + let id = app.session.execute("shape.create", json!({"kind": "rect", "rect": [40, 16, 50, 32], "fill": "#ff0000"})).unwrap()["layer"].as_u64().unwrap(); + let id = photocraft_doc::LayerId(id); + app.ui.tool = Tool::Move; + app.ui.extras.snap = false; + app.ui.view.show.smart_guides = false; + let m = egui::Modifiers::NONE; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 50.0, y: 32.0, pressure: 1.0 }, m); + let mut frames = Vec::new(); + for x in [40.0, 10.0] { + crate::canvas::tool_event(&mut app, ToolEvent::Move { x, y: 32.0, pressure: 1.0 }, m); + frames.push(super::display_doc(&mut app, 0).unwrap()); + } + let st = app.session.active().unwrap(); + let r = super::damage(&app, st.doc.id, st.revision, frames[0].1, frames[1].1).unwrap(); + let alpha = |d: &photocraft_doc::Document, x, y| d.layer(id).and_then(|l| l.surface()).map_or(0.0, |s| s.pixel(x, y)[3]); + for y in 0..64 { + for x in 0..64 { + if alpha(&frames[0].0, x, y) != alpha(&frames[1].0, x, y) { + assert!(r.contains(x, y), "({x}, {y}) changed outside the redrawn {r:?}"); + } + } + } +} + +/// Dragging with an unlinked mask targeted moves the mask alone, shown live and committed; +/// with the mask linked (or the pixels targeted) the layer moves. +#[test] +fn dragging_with_an_unlinked_mask_targeted_moves_the_mask_alone() { + for (linked, mask_target) in [(false, true), (false, false), (true, true)] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 64, "height": 64, "background": "transparent"})).unwrap(); + app.sync_views(); + app.session.execute("layer.new.layer", json!({})).unwrap(); + app.session.execute("select.rect", json!({"x": 8, "y": 8, "width": 16, "height": 16})).unwrap(); + app.session.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.session.execute("select.deselect", json!({})).unwrap(); + app.session.execute("layer.layerMask.revealAll", json!({})).unwrap(); + app.session.execute("layer.layerMask.linked", json!({"linked": linked})).unwrap(); + app.ui.mask_target = mask_target; + app.ui.tool = Tool::Move; + app.ui.extras.snap = false; + app.ui.view.show.smart_guides = false; + let m = egui::Modifiers::NONE; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 16.0, y: 16.0, pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 36.0, y: 16.0, pressure: 1.0 }, m); + let shown = super::display_doc(&mut app, 0).unwrap().0; + let id = app.session.active().unwrap().active_layer.unwrap(); + let layer_moved = |d: &photocraft_doc::Document| d.layer(id).and_then(|l| l.surface()).is_some_and(|s| s.pixel(28, 16)[3] > 0.5); + let alone = !linked && mask_target; + assert_eq!(layer_moved(&shown), !alone, "preview, linked {linked} mask target {mask_target}"); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 36.0, y: 16.0 }, m); + let d = &app.session.active().unwrap().doc; + assert_eq!(layer_moved(d), !alone, "commit, linked {linked} mask target {mask_target}"); + } +} + +/// Mid-drag on a painted layer: is the layer shown at the pointer? +fn live(outline: bool) -> bool { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); + app.sync_views(); + app.session.execute("layer.new.layer", json!({})).unwrap(); + app.session.execute("select.rect", json!({"x": 8, "y": 8, "width": 16, "height": 16})).unwrap(); + app.session.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.session.execute("select.deselect", json!({})).unwrap(); + app.session.edit_prefs(|p| p.interface.show_bounding_box_when_dragging_layer = outline); + app.ui.tool = Tool::Move; + let m = egui::Modifiers::NONE; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 16.0, y: 16.0, pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 30.0, y: 20.0, pressure: 1.0 }, m); + let shown = super::display_doc(&mut app, 0).is_some(); + assert_eq!(shown, super::showing(&app)); + shown +} + +#[test] +fn bounding_box_preference_turns_the_live_drag_off() { + assert!(live(false), "by default the layer follows the pointer"); + assert!(!live(true), "with the preference on, only the outline and arrow move"); +} + +/// A `depth`-bit transparent document whose layer holds a red square (8..24)² and a blue one +/// (40..56)×(8..24), the red one selected; the Move tool with Auto-Select on. +fn selected_pixels(depth: u32) -> (PhotocraftApp, photocraft_doc::LayerId) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 64, "height": 64, "background": "transparent", "depth": depth})).unwrap(); + app.sync_views(); + for (x, color) in [(40, "#0000ff"), (8, "#ff0000")] { + app.session.execute("select.rect", json!({"x": x, "y": 8, "width": 16, "height": 16})).unwrap(); + app.session.execute("edit.fill", json!({"color": color})).unwrap(); + } + app.ui.tool = Tool::Move; + app.ui.tool_options.move_auto_select = true; + app.ui.extras.snap = false; + app.ui.view.show.smart_guides = false; + let id = app.session.active().unwrap().active_layer.unwrap(); + (app, id) +} + +fn alpha(app: &PhotocraftApp, id: photocraft_doc::LayerId, x: i32, y: i32) -> f32 { + app.session.active().unwrap().doc.layer(id).unwrap().surface().unwrap().rgba(x, y)[3] +} + +fn offset(app: &PhotocraftApp) -> Option<(i32, i32)> { + photocraft_engine::float_cmds::floating(app.session.active().unwrap()).map(|f| f.offset) +} + +fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2], m: egui::Modifiers) { + crate::canvas::tool_event(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, m); + crate::canvas::tool_event(app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }, m); + crate::canvas::tool_event(app, ToolEvent::Up { x: to[0], y: to[1] }, m); +} + +/// ↩ through the app's key handling. +fn enter(app: &mut PhotocraftApp) { + let ctx = egui::Context::default(); + let key = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + let input = egui::RawInput { events: vec![key], ..Default::default() }; + ctx.run_ui(input, |ui| crate::shortcuts::handle(app, ui.ctx())).textures_delta.clear(); +} + +/// #578: with a selection the Move tool drags the selected pixels (from anywhere, without an +/// Auto-Select pick), not the layer; ↩ drops them as one "Move" step that one undo takes back. +#[test] +fn with_a_selection_the_move_tool_moves_only_the_selected_pixels() { + for depth in [8, 16, 32] { + let (mut app, id) = selected_pixels(depth); + let steps = app.session.active().unwrap().history.past_len(); + drag(&mut app, [50.0, 40.0], [60.0, 45.0], egui::Modifiers::NONE); + assert_eq!(offset(&app), Some((10, 5)), "{depth}-bit: floating"); + let shown = super::display_doc(&mut app, 0).unwrap().0; + let shown_alpha = |x, y| shown.layer(id).unwrap().surface().unwrap().rgba(x, y)[3]; + assert!(shown_alpha(10, 10) == 0.0 && shown_alpha(30, 25) == 1.0, "{depth}-bit: shown moved"); + enter(&mut app); + assert_eq!(offset(&app), None, "{depth}-bit: ↩ dropped it"); + assert_eq!(alpha(&app, id, 10, 10), 0.0, "{depth}-bit: the hole is transparent"); + assert_eq!(alpha(&app, id, 30, 25), 1.0, "{depth}-bit: the red square moved"); + assert_eq!(alpha(&app, id, 48, 16), 1.0, "{depth}-bit: the unselected blue one stayed"); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.selection.as_ref().unwrap().content_bounds(), Rect::new(18, 13, 34, 29), "{depth}-bit"); + assert_eq!((st.history.past_len(), st.history.undo_label()), (steps + 1, Some("Move")), "{depth}-bit"); + assert!(app.session.undo()); + assert!(alpha(&app, id, 10, 10) == 1.0 && alpha(&app, id, 30, 25) == 0.0, "{depth}-bit: undone"); + } +} + +/// ⌥ copies the selected pixels (no layer copy), ⇧ locks the drag to multiples of 45°. +#[test] +fn alt_copies_and_shift_constrains_the_selected_pixels() { + for depth in [8, 16, 32] { + let (mut app, id) = selected_pixels(depth); + let layers = app.session.active().unwrap().doc.layers.len(); + drag(&mut app, [16.0, 16.0], [30.0, 28.0], egui::Modifiers::ALT | egui::Modifiers::SHIFT); + assert_eq!(offset(&app), Some((13, 13)), "{depth}-bit: 45°"); + app.run("select.drop", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().doc.layers.len(), layers, "{depth}-bit: no layer copy"); + assert!(alpha(&app, id, 10, 10) == 1.0 && alpha(&app, id, 35, 35) == 1.0, "{depth}-bit: original and copy"); + assert!(app.session.undo()); + assert_eq!(alpha(&app, id, 35, 35), 0.0, "{depth}-bit: undone"); + } +} + +/// #7538: a loose marquee round the red square shrinks to it as the drag starts: the canvas +/// outlines the moved pixels while they float, and the dropped selection is theirs. Alt-drag +/// (a copy) too. +#[test] +fn dragging_selected_pixels_shrinks_the_ants_to_them() { + for depth in [8, 16, 32] { + for m in [egui::Modifiers::NONE, egui::Modifiers::ALT] { + let (mut app, _) = selected_pixels(depth); + app.session.execute("select.rect", json!({"x": 2, "y": 2, "width": 30, "height": 30})).unwrap(); + drag(&mut app, [16.0, 16.0], [26.0, 21.0], m); + assert_eq!(offset(&app), Some((10, 5)), "{depth}-bit, {m:?}: floating"); + let ants = crate::canvas::floating_outline(&app, 0).map(|s| s.content_bounds()); + assert_eq!(ants, Some(Rect::new(8, 8, 24, 24)), "{depth}-bit, {m:?}: the ants hug the red square"); + assert!(crate::canvas::floating_outline(&app, 1).is_none(), "only the active document's"); + app.run("select.drop", json!({})).unwrap(); + let sel = app.session.active().unwrap().doc.selection.as_ref().map(|s| s.content_bounds()); + assert_eq!(sel, Some(Rect::new(18, 13, 34, 29)), "{depth}-bit, {m:?}: dropped"); + assert!(crate::canvas::floating_outline(&app, 0).is_none(), "nothing floats"); + } + } +} + +/// ⌘-drag with a painting tool drags the selected pixels as the Move tool does, also when ⌘ +/// comes with the event (control channel, MCP) rather than as the held-key override. +#[test] +fn command_drag_with_a_painting_tool_moves_only_the_selected_pixels() { + let (mut app, id) = selected_pixels(8); + app.ui.tool = Tool::Brush; + app.ui.tool_options.move_auto_select = false; + let cmd = egui::Modifiers { mac_cmd: true, command: true, ..Default::default() }; + drag(&mut app, [50.0, 40.0], [60.0, 45.0], cmd); + assert_eq!(offset(&app), Some((10, 5)), "the selected pixels float"); + drag(&mut app, [50.0, 40.0], [60.0, 45.0], cmd); + assert_eq!(offset(&app), Some((20, 10)), "a second drag moves the same floating piece"); + app.run("select.drop", json!({})).unwrap(); + assert!(alpha(&app, id, 10, 10) == 0.0 && alpha(&app, id, 40, 30) == 1.0, "the red square moved"); + assert_eq!(alpha(&app, id, 48, 16), 1.0, "the unselected blue one stayed"); +} + +/// A click moves nothing and leaves nothing floating (Undo isn't spent putting it back). +#[test] +fn a_click_with_a_selection_moves_nothing() { + let (mut app, id) = selected_pixels(8); + let steps = app.session.active().unwrap().history.past_len(); + drag(&mut app, [16.0, 16.0], [16.0, 16.0], egui::Modifiers::NONE); + assert_eq!(offset(&app), None); + assert_eq!(app.session.active().unwrap().history.past_len(), steps); + assert!(alpha(&app, id, 10, 10) == 1.0 && alpha(&app, id, 48, 16) == 1.0); +} + +#[test] +fn arrow_keys_nudge_the_selected_pixels() { + let (mut app, id) = selected_pixels(16); + crate::move_mods::nudge(&mut app, 10.0, 0.0, false); + crate::move_mods::nudge(&mut app, 0.0, 1.0, false); + assert_eq!(offset(&app), Some((10, 1))); + // ⌥ leaves the piece where it is and nudges a copy of it. + crate::move_mods::nudge(&mut app, 1.0, 0.0, true); + assert_eq!(offset(&app), Some((1, 0))); + app.run("select.drop", json!({})).unwrap(); + assert!(alpha(&app, id, 10, 10) == 0.0 && alpha(&app, id, 18, 20) == 1.0 && alpha(&app, id, 34, 20) == 1.0); + assert_eq!(alpha(&app, id, 48, 16), 1.0, "the layer itself didn't move"); +} + +/// Without floatable pixels (a position-locked layer) the Move tool behaves as without a +/// selection: it moves the layer, which the lock refuses. +#[test] +fn a_layer_that_cannot_float_moves_whole_as_before() { + let (mut app, id) = selected_pixels(8); + app.session.execute("layer.lockLayers", json!({"position": true})).unwrap(); + drag(&mut app, [16.0, 16.0], [26.0, 16.0], egui::Modifiers::NONE); + assert_eq!(offset(&app), None); + assert!(alpha(&app, id, 10, 10) == 1.0 && alpha(&app, id, 30, 16) == 0.0, "nothing moved"); + // Without a selection the layer moves whole. + app.session.execute("layer.lockLayers", json!({"position": false})).unwrap(); + app.session.execute("select.deselect", json!({})).unwrap(); + drag(&mut app, [16.0, 16.0], [26.0, 16.0], egui::Modifiers::NONE); + assert!(alpha(&app, id, 10, 10) == 0.0 && alpha(&app, id, 58, 16) == 1.0, "the whole layer moved"); +} + +#[test] +fn floating_selection_does_not_snap_to_its_own_starting_outline_or_preview_at_zero() { + let (mut app, _id) = selected_pixels(8); + app.ui.extras.snap = true; + app.ui.view.snap_to.document_bounds = false; + let m = egui::Modifiers::NONE; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 16.0, y: 16.0, pressure: 1.0 }, m); + assert!(super::display_doc(&mut app, 0).is_none(), "no preview composite at offset (0, 0) before the pointer moves"); + // A small 2 px move within the snap radius must move immediately instead of snapping back to (0, 0). + crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 18.0, y: 17.0, pressure: 1.0 }, m); + assert_eq!(super::floating_offset(&app), Some((2, 1)), "small drag moves without snapping to own selection bounds"); + assert!(super::display_doc(&mut app, 0).is_some(), "preview is shown once offset is non-zero"); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 18.0, y: 17.0 }, m); + assert_eq!(offset(&app), Some((2, 1))); +} diff --git a/crates/ui-egui/src/canvas/navigator.rs b/crates/ui-egui/src/canvas/navigator.rs new file mode 100644 index 0000000000..d95c9a20ec --- /dev/null +++ b/crates/ui-egui/src/canvas/navigator.rs @@ -0,0 +1,138 @@ +use super::display::{canvas_display, display_doc, display_image}; +use super::strokes::live_stroke; +use super::textures::{effect_reach, ensure_texture}; +use super::*; + +/// Longest side of the Navigator panel's image (about twice the panel's width, for HiDPI). +pub const NAVIGATOR_SIDE: u32 = 512; + +/// The navigator image of a document: its snapshot, preview key and revision, and the texture. +pub(crate) type NavigatorCache = (std::sync::Weak, u64, u64, egui::TextureHandle); + +/// How long adjustment-dialog settings must stay unchanged before the navigator shows them. +const NAVIGATOR_SETTLE_MS: f64 = 200.0; + +/// While a Move or Patch drag or a live paint stroke is under way, the navigator keeps its image +/// of document `idx` and catches up on release: each step of the drag is a new preview, and a +/// thumbnail composite of the whole document per step makes painting lag on large images. +pub(super) fn navigator_waits_for_drag(app: &PhotocraftApp, idx: usize) -> bool { + crate::move_ui::showing(app) || crate::patch_preview::showing(app) || crate::cam_preview::showing(app) || live_stroke(app, idx).is_some() +} + +/// The Navigator panel's image of document `idx`. With the CPU canvas that is the canvas texture +/// itself; with the GPU canvas a thumbnail cached per revision, so an edit to a huge document +/// doesn't also pay a full-resolution CPU composite for the navigator. +/// The Navigator's preview from the GPU canvas (#4518): the main canvas's texture of the +/// document, drawn at `rect` with its own mip chain, so an edit costs no CPU composite. `None` +/// while the canvas isn't showing the plain document on the GPU (the CPU thumbnail then). +pub fn navigator_gpu_view(app: &PhotocraftApp, idx: usize, rect: Rect, ctx: &egui::Context) -> Option { + app.gpu.as_ref()?; + let st = app.session.documents().get(idx)?; + let params = *app.navigator_gpu.get(&st.doc.id)?; + let [w, h] = params.doc_size; + if w == 0 || h == 0 || !rect.is_positive() || [st.doc.size.width, st.doc.size.height] != params.doc_size { + return None; + } + Some(crate::gpu_canvas::ViewParams { + zoom: rect.width() / w as f32, + center: [w as f32 / 2.0, h as f32 / 2.0], + rotation: 0.0, + shadow: false, + pixel_grid: false, + view_key: egui::Id::unique(("pc-navigator", ctx.viewport_id(), idx)).value(), + offset: [0.0, 0.0], + ..params + }) +} + +/// Frames the Navigator waits for the GPU canvas to draw a document it hasn't drawn yet, rather +/// than build a CPU thumbnail it would only use once (a full composite on a large document). +const NAVIGATOR_WAIT_FRAMES: u32 = 3; + +/// Whether the Navigator should wait a frame for the GPU canvas (#4518): the GPU canvas is on but +/// hasn't drawn document `idx` yet (the Navigator can draw before the canvas in a frame). After +/// [`NAVIGATOR_WAIT_FRAMES`] it stops waiting, so it never stays empty. +pub fn navigator_waits_for_gpu(app: &PhotocraftApp, idx: usize, ctx: &egui::Context) -> bool { + if app.gpu.is_none() { + return false; + } + let Some(id) = app.session.documents().get(idx).map(|st| st.doc.id) else { return false }; + if app.canvases.keys().any(|(d, _)| *d == id) { + return false; + } + let key = egui::Id::unique(("navigator-waits", id.0)); + let waited = ctx.data(|d| d.get_temp::(key)).unwrap_or(0); + if waited >= NAVIGATOR_WAIT_FRAMES { + return false; + } + ctx.data_mut(|d| d.insert_temp(key, waited + 1)); + ctx.request_repaint(); + true +} + +pub fn navigator_texture(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usize) -> Option { + if app.gpu.is_none() { + return ensure_texture(app, ctx, idx, app.session.color.main_display).map(|(t, _)| t); + } + // Keyed by the document snapshot, not its revision: selecting a layer changes no pixels. + let (snapshot, id, revision, last_damage) = + app.session.documents().get(idx).map(|st| (std::sync::Arc::downgrade(&st.doc), st.doc.id, st.revision, st.last_damage))?; + let (doc, preview_key) = display_doc(app, idx); + let (display, display_key) = canvas_display(app, &doc, None); + let preview_key = preview_key ^ display_key; + let cached = app.navigator_textures.get(&id).cloned(); + if let Some((r, p, _, t)) = &cached + && r.ptr_eq(&snapshot) + && *p == preview_key + { + return Some(t.id()); + } + if let Some((_, _, _, t)) = &cached + && navigator_waits_for_drag(app, idx) + { + return Some(t.id()); + } + // While an adjustment dialog's settings are changing, the navigator keeps its image and + // catches up once they settle (a thumbnail composite per change would cost more than the canvas). + if let Some((r, _, _, t)) = &cached + && r.ptr_eq(&snapshot) + && crate::adjust_preview::settling(app, NAVIGATOR_SETTLE_MS) + { + ctx.request_repaint_after(std::time::Duration::from_millis(NAVIGATOR_SETTLE_MS as u64)); + return Some(t.id()); + } + let t0 = crate::gpu_canvas::now_ms(); + // One edit since the cached image, with the area it changed: update just that part (nothing + // for a rename, a selection or a new empty layer). A thumbnail composite of the whole + // document on every edit cost a full-resolution CPU composite on the UI thread. + let size = photocraft_compose::thumbnail_size(&doc, NAVIGATOR_SIDE); + if let Some((_, p, rev, t)) = &cached + && *p == preview_key + && rev.checked_add(1) == Some(revision) + && let Some(d) = last_damage + && t.size() == [size.0 as usize, size.1 as usize] + { + let mut t = t.clone(); + if !d.is_empty() { + let buf = photocraft_compose::render_reduced_damage(&doc, size.0, size.1, d.inflate(effect_reach(&doc.layers))); + let r = buf.rect; + if !r.is_empty() { + t.set_partial([r.x0 as usize, r.y0 as usize], display_image(display.as_deref(), &buf), TextureOptions::LINEAR); + } + } + app.perf.span("navigator", crate::gpu_canvas::now_ms() - t0); + app.navigator_textures.insert(id, (snapshot, preview_key, revision, t.clone())); + return Some(t.id()); + } + let image = display_image(display.as_deref(), &photocraft_compose::thumbnail_buffer(&doc, NAVIGATOR_SIDE)); + let tex = match cached { + Some((_, _, _, mut t)) => { + t.set(image, TextureOptions::LINEAR); + t + } + None => ctx.load_texture(format!("navigator-{}", id.0), image, TextureOptions::LINEAR), + }; + app.perf.span("navigator", crate::gpu_canvas::now_ms() - t0); + app.navigator_textures.insert(id, (snapshot, preview_key, revision, tex.clone())); + Some(tex.id()) +} diff --git a/crates/ui-egui/src/outline.rs b/crates/ui-egui/src/canvas/outline.rs similarity index 100% rename from crates/ui-egui/src/outline.rs rename to crates/ui-egui/src/canvas/outline.rs diff --git a/crates/ui-egui/src/canvas/paint.rs b/crates/ui-egui/src/canvas/paint.rs new file mode 100644 index 0000000000..bcec552b4d --- /dev/null +++ b/crates/ui-egui/src/canvas/paint.rs @@ -0,0 +1,610 @@ +use super::display::{canvas_display, checker, display_doc, display_image}; +use super::drag::{ + angle_readout, draw_marquee_readout, draw_value_readout, marquee_ants, marquee_drag_ants, marquee_preview_px, single_line_drag_px, size_readout, +}; +use super::gesture::constrained_polygon_point; +use super::strokes::{EngineStroke, SPOT_HEALING_TRAIL, draw_smoothing_string, strokes_live}; +use super::textures::texture_side; +use super::view_xform::ViewXform; +use super::*; + +/// A texture mapped over the `size` document area starting at `origin` (follows a rotated view). +pub(super) fn paint_mapped_image_at(painter: &egui::Painter, xf: &ViewXform, tex: egui::TextureId, uv: Rect, origin: [f32; 2], size: [f32; 2], tint: Color32) { + let ([x, y], [w, h]) = (origin, size); + let pts = [xf.to_screen(x, y), xf.to_screen(x + w, y), xf.to_screen(x + w, y + h), xf.to_screen(x, y + h)]; + let uvs = [uv.min, pos2(uv.max.x, uv.min.y), uv.max, pos2(uv.min.x, uv.max.y)]; + let mut mesh = Mesh::with_texture(tex); + for i in 0..4 { + mesh.vertices.push(egui::epaint::Vertex { pos: pts[i], uv: uvs[i], color: tint }); + } + mesh.add_triangle(0, 1, 2); + mesh.add_triangle(0, 2, 3); + painter.add(egui::Shape::mesh(mesh)); +} + +/// The GPU canvas view, then its View › Pattern Preview copies (#1067): the same texture drawn +/// again whole document sizes away, each with its own view uniform and no shadow. +pub(super) fn paint_gpu_view(painter: &egui::Painter, rect: Rect, params: crate::gpu_canvas::ViewParams, copies: &[[i32; 2]]) { + crate::gpu_canvas::GpuCanvas::paint(painter, rect, params); + for (k, &c) in copies.iter().enumerate() { + let copy = crate::gpu_canvas::ViewParams { + offset: crate::pattern_preview::offset(c, params.doc_size), + shadow: false, + // Keyed by slot, not by tile index, so panning reuses the same few uniform buffers. + view_key: egui::Id::unique((params.view_key, "pattern", k)).value(), + ..params + }; + crate::gpu_canvas::GpuCanvas::paint(painter, rect, copy); + } +} + +/// The mapping that draws Pattern Preview copy `c` of a `size` document where it sits next to +/// the document: the same view, looking the matching number of document sizes back. +pub(super) fn pattern_xf(xf: &ViewXform, c: [i32; 2], size: [u32; 2]) -> ViewXform { + let [ox, oy] = crate::pattern_preview::offset(c, size); + ViewXform { center: [xf.center[0] - ox, xf.center[1] - oy], ..*xf } +} + +/// CPU canvas: the transparency checkerboard (or white) and the display texture, for the +/// document or one of its Pattern Preview copies (`xf` from [`pattern_xf`]). +pub(super) fn paint_cpu_document( + painter: &egui::Painter, + xf: &ViewXform, + bounds: DRect, + rotated: bool, + checker: Option<(egui::TextureId, f32)>, + tex: Option, + opaque: bool, +) { + let size = [bounds.width() as f32, bounds.height() as f32]; + let origin = [bounds.x0 as f32, bounds.y0 as f32]; + let img_rect = xf.doc_rect(bounds); + match checker { + Some((checker_id, square)) if !opaque || tex.is_none() => { + if rotated { + let tiles = vec2(size[0], size[1]) / (2.0 * square); + paint_mapped_image_at(painter, xf, checker_id, Rect::from_min_max(Pos2::ZERO, pos2(tiles.x, tiles.y)), origin, size, Color32::WHITE); + } else { + let tiles = img_rect.size() / (2.0 * square); + painter.image(checker_id, img_rect, Rect::from_min_max(Pos2::ZERO, pos2(tiles.x, tiles.y)), Color32::WHITE); + } + } + // On software window adapters this hidden full-canvas pass is CPU rasterization too. + // Keep the white-background branch unchanged (its antialiased outer edge is visible). + Some(_) => {} + None => { + if rotated { + paint_mapped_quad(painter, xf, origin, size, Color32::WHITE); + } else { + painter.rect_filled(img_rect, 0.0, Color32::WHITE); + } + } + } + if let Some(tex) = tex { + if rotated { + paint_mapped_image_at(painter, xf, tex, Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), origin, size, Color32::WHITE); + } else { + let uv = if xf.flip { Rect::from_min_max(pos2(1.0, 0.0), pos2(0.0, 1.0)) } else { Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)) }; + painter.image(tex, img_rect, uv, Color32::WHITE); + } + } +} + +/// [`ensure_texture_in_view`]'s detail texture over document area `area` (x0, y0, x1, y1), on its +/// own checkerboard (or white), so the reduced texture under it doesn't show through where the +/// image is transparent. The checkerboard keeps [`paint_cpu_document`]'s phase. +pub(super) fn paint_cpu_detail( + painter: &egui::Painter, + xf: &ViewXform, + bounds: DRect, + rotated: bool, + checker: Option<(egui::TextureId, f32)>, + tex: egui::TextureId, + area: [f32; 4], +) { + let [x0, y0, x1, y1] = area; + let corners = [[x0, y0], [x1, y0], [x1, y1], [x0, y1]]; + let pts = corners.map(|[x, y]| xf.to_screen(x, y)); + let quad = |tex: egui::TextureId, uvs: [Pos2; 4]| { + let mut mesh = Mesh::with_texture(tex); + for (pos, uv) in pts.into_iter().zip(uvs) { + mesh.vertices.push(egui::epaint::Vertex { pos, uv, color: Color32::WHITE }); + } + mesh.add_triangle(0, 1, 2); + mesh.add_triangle(0, 2, 3); + painter.add(egui::Shape::mesh(mesh)); + }; + match checker { + Some((checker_id, square)) => { + let tile = 2.0 * square; + let uvs = if rotated { + corners.map(|[x, y]| pos2(x / tile, y / tile)) + } else { + let min = xf.doc_rect(bounds).min; + pts.map(|p| ((p - min) / tile).to_pos2()) + }; + quad(checker_id, uvs); + } + None => { + painter.add(egui::Shape::convex_polygon(pts.to_vec(), Color32::WHITE, Stroke::NONE)); + } + } + quad(tex, [pos2(0.0, 0.0), pos2(1.0, 0.0), pos2(1.0, 1.0), pos2(0.0, 1.0)]); +} + +fn paint_mapped_quad(painter: &egui::Painter, xf: &ViewXform, origin: [f32; 2], size: [f32; 2], color: Color32) { + let ([x, y], [w, h]) = (origin, size); + let pts = vec![xf.to_screen(x, y), xf.to_screen(x + w, y), xf.to_screen(x + w, y + h), xf.to_screen(x, y + h)]; + painter.add(egui::Shape::convex_polygon(pts, color, Stroke::NONE)); +} + +/// Draw boundary segments as marching ants: white base, black dashes phased along x + y. +pub(super) fn marching_ants_segments(painter: &egui::Painter, xf: &ViewXform, segs: &[crate::outline::Segment], time: f64) { + marching_ants_mapped(painter, segs, time, |p| xf.to_screen(p[0] as f32, p[1] as f32)); +} + +/// [`marching_ants_segments`] with each outline point placed on screen by `to_screen` (a +/// transformed outline: Content-Aware Move's Transform On Drop). +pub(crate) fn marching_ants_mapped(painter: &egui::Painter, segs: &[crate::outline::Segment], time: f64, to_screen: impl Fn([i32; 2]) -> Pos2) { + marching_ants_lines(painter, segs.iter().map(|(a, b)| (to_screen(*a), to_screen(*b))), time); +} + +/// The part of the line `a`–`b` inside `r` (Liang–Barsky), if any. +pub(crate) fn clip_line(r: Rect, a: Pos2, b: Pos2) -> Option<(Pos2, Pos2)> { + // Perspective can put endpoints billions of pixels away. f32 subtraction/interpolation + // loses viewport-sized differences there, clipping visible ants to the wrong endpoints. + let (ax, ay) = (f64::from(a.x), f64::from(a.y)); + let (dx, dy) = (f64::from(b.x) - ax, f64::from(b.y) - ay); + let (mut t0, mut t1) = (0.0f64, 1.0f64); + for (p, q) in [(-dx, ax - f64::from(r.min.x)), (dx, f64::from(r.max.x) - ax), (-dy, ay - f64::from(r.min.y)), (dy, f64::from(r.max.y) - ay)] { + if p == 0.0 { + if q < 0.0 { + return None; + } + } else if p < 0.0 { + t0 = t0.max(q / p); + } else { + t1 = t1.min(q / p); + } + } + let at = |t: f64| pos2((ax + dx * t) as f32, (ay + dy * t) as f32); + (t0 <= t1).then(|| (at(t0), at(t1))) +} + +/// Marching ants along lines already placed on screen (a warped outline is a run of short ones), +/// in device pixels like Photoshop's (`crate::ants`, #7489). +pub(crate) fn marching_ants_lines(painter: &egui::Painter, lines: impl Iterator, time: f64) { + crate::ants::draw(painter, lines, time, true); +} + +/// Photoshop crop overlay: the `shield` outside (`crop_shield::fill`; none when disabled), bright +/// frame, the composition `guides` (unit-square polylines, `crop_overlay::guides`), corner and +/// edge handles. +fn crop_overlay(painter: &egui::Painter, r: Rect, shield: Option, guides: &[crate::crop_overlay::Polyline]) { + let clip = painter.clip_rect(); + if let Some(dim) = shield { + for band in [ + Rect::from_min_max(clip.min, egui::pos2(clip.max.x, r.min.y)), + Rect::from_min_max(egui::pos2(clip.min.x, r.max.y), clip.max), + Rect::from_min_max(egui::pos2(clip.min.x, r.min.y), egui::pos2(r.min.x, r.max.y)), + Rect::from_min_max(egui::pos2(r.max.x, r.min.y), egui::pos2(clip.max.x, r.max.y)), + ] { + painter.rect_filled(band, 0.0, dim); + } + } + painter.rect_stroke(r, 0.0, Stroke::new(1.0, Color32::WHITE), egui::StrokeKind::Middle); + draw_crop_guides(painter, guides, |a, b| r.min + r.size() * vec2(a, b)); + let h = Stroke::new(3.0, Color32::WHITE); + let l = 14.0f32.min(r.width() / 3.0).min(r.height() / 3.0); + for (c, dx, dy) in [(r.left_top(), 1.0, 1.0), (r.right_top(), -1.0, 1.0), (r.left_bottom(), 1.0, -1.0), (r.right_bottom(), -1.0, -1.0)] { + painter.line_segment([c, c + vec2(l * dx, 0.0)], h); + painter.line_segment([c, c + vec2(0.0, l * dy)], h); + } + // Edge handles: short bars at the middle of each side. + let (lx, ly) = (l.min(r.width() / 4.0) / 2.0, l.min(r.height() / 4.0) / 2.0); + for (c, horizontal) in [(r.center_top(), true), (r.center_bottom(), true), (r.left_center(), false), (r.right_center(), false)] { + let e = if horizontal { vec2(lx, 0.0) } else { vec2(0.0, ly) }; + painter.line_segment([c - e, c + e], h); + } +} + +/// [`crop_overlay`] for a turned frame (or a rotated view): `q` is the frame's top-left, top-right, +/// bottom-right and bottom-left corner on screen, a parallelogram. +fn crop_overlay_turned(painter: &egui::Painter, q: [Pos2; 4], shield: Option, guides: &[crate::crop_overlay::Polyline]) { + let (u, v) = (q[1] - q[0], q[3] - q[0]); + let (lu, lv) = (u.length(), v.length()); + if !(lu.is_finite() && lv.is_finite()) || lu < 1e-3 || lv < 1e-3 { + return; + } + let at = |a: f32, b: f32| q[0] + u * a + v * b; + // The shield: four trapezoids from the frame out to the frame grown past the whole view. + let clip = painter.clip_rect(); + let reach = clip.size().length() + (clip.center() - at(0.5, 0.5)).length(); + let (eu, ev) = (reach / lu, reach / lv); + let outer = [at(-eu, -ev), at(1.0 + eu, -ev), at(1.0 + eu, 1.0 + ev), at(-eu, 1.0 + ev)]; + if let Some(dim) = shield { + let mut mesh = egui::Mesh::default(); + for p in q.iter().chain(outer.iter()) { + mesh.colored_vertex(*p, dim); + } + for i in 0..4u32 { + let j = (i + 1) % 4; + mesh.add_triangle(i, j, 4 + j); + mesh.add_triangle(i, 4 + j, 4 + i); + } + painter.add(egui::Shape::mesh(mesh)); + } + painter.add(egui::Shape::closed_line(q.to_vec(), Stroke::new(1.0, Color32::WHITE))); + draw_crop_guides(painter, guides, at); + let h = Stroke::new(3.0, Color32::WHITE); + let l = 14.0f32.min(lu / 3.0).min(lv / 3.0); + let (du, dv) = (u / lu, v / lv); + for (c, su, sv) in [(q[0], 1.0, 1.0), (q[1], -1.0, 1.0), (q[3], 1.0, -1.0), (q[2], -1.0, -1.0)] { + painter.line_segment([c, c + du * (l * su)], h); + painter.line_segment([c, c + dv * (l * sv)], h); + } + // Edge handles: short bars at the middle of each side, along it. + let (lx, ly) = (l.min(lu / 4.0) / 2.0, l.min(lv / 4.0) / 2.0); + for (c, e) in [(at(0.5, 0.0), du * lx), (at(0.5, 1.0), du * lx), (at(0.0, 0.5), dv * ly), (at(1.0, 0.5), dv * ly)] { + painter.line_segment([c - e, c + e], h); + } +} + +/// The crop overlay's guides, each unit-square point placed on screen by `at`. +fn draw_crop_guides(painter: &egui::Painter, guides: &[crate::crop_overlay::Polyline], at: impl Fn(f32, f32) -> Pos2) { + let thin = Stroke::new(1.0, Color32::from_white_alpha(90)); + for l in guides { + painter.add(egui::Shape::line(l.iter().map(|p| at(p[0], p[1])).collect(), thin)); + } +} + +/// What the Crop tool shows past the canvas, cached per document state ([`draw_beyond_canvas`]). +#[derive(Clone)] +struct BeyondCanvas { + snapshot: std::sync::Weak, + key: u64, + /// Every layer's pixels and the canvas (`extra_cmds::reveal_all_bounds`). + extent: DRect, + /// The composite around the canvas: each band, the area its texture covers, the texture. + bands: Vec<(DRect, DRect, egui::TextureHandle)>, +} + +/// Band `r` around the canvas `c` (on screen) pushed a point under the canvas's edge, so that the +/// edge's anti-aliased pixels blend with the band rather than with the pasteboard. +fn under_canvas(mut r: Rect, c: Rect) -> Rect { + let near = |a: f32, b: f32| (a - b).abs() < 0.01; + if near(r.max.y, c.min.y) { + r.max.y += 1.0; + } + if near(r.min.y, c.max.y) { + r.min.y -= 1.0; + } + if near(r.max.x, c.min.x) { + r.max.x += 1.0; + } + if near(r.min.x, c.max.x) { + r.min.x -= 1.0; + } + r +} + +/// `outer` minus `inner`: the bands above, below, left and right of it (empty ones dropped). +fn ring(outer: DRect, inner: DRect) -> Vec { + let i = inner.intersect(&outer); + if i.is_empty() { + return if outer.is_empty() { Vec::new() } else { vec![outer] }; + } + [ + DRect::new(outer.x0, outer.y0, outer.x1, i.y0), + DRect::new(outer.x0, i.y1, outer.x1, outer.y1), + DRect::new(outer.x0, i.y0, i.x0, i.y1), + DRect::new(i.x1, i.y0, outer.x1, i.y1), + ] + .into_iter() + .filter(|r| !r.is_empty()) + .collect() +} + +/// Crop tool, while a frame is edited (`crop_ui::shows_beyond_canvas`): like Photoshop's crop +/// preview, the canvas grows to every layer's pixels (a crop with Delete Cropped Pixels off keeps +/// them; a moved layer reaches past the edges) and to the frame, transparency drawn as the +/// checkerboard, all under the shield `crop_overlay` adds. Only the ring around the canvas is +/// composited, on the CPU, once per document state: at most `MAX_TEXTURE` texels per side, from a +/// downsampled proxy past that (so a far-off layer costs no more than a 16 MP composite). +/// Drawn before the canvas, each band reaching a point under its edge. Returns whether anything +/// past the canvas was drawn. +pub(super) fn draw_beyond_canvas(app: &mut PhotocraftApp, painter: &egui::Painter, xf: &ViewXform, idx: usize, output: Option) -> bool { + let ctx = painter.ctx().clone(); + let Some((snapshot, id)) = app.session.documents().get(idx).map(|st| (std::sync::Arc::downgrade(&st.doc), st.doc.id)) else { return false }; + let key = egui::Id::unique(("crop-beyond-canvas", id.0, output)); + let frame = + app.ui.crop_rect.filter(|f| f.iter().all(|v| v.is_finite()) && app.session.active_index() == Some(idx) && crate::crop_ui::shows_beyond_canvas(app)); + let Some(f) = frame else { + ctx.data_mut(|d| d.remove::(key)); + return false; + }; + let (doc, preview_key) = display_doc(app, idx); + if doc.has_artboards() { + return false; + } + let (display, display_key) = canvas_display(app, &doc, output); + let doc_key = preview_key ^ display_key; + let cached: Option = ctx.data(|d| d.get_temp(key)); + let c = match cached.filter(|c| c.snapshot.ptr_eq(&snapshot) && c.key == doc_key) { + Some(c) => c, + None => { + let t0 = crate::gpu_canvas::now_ms(); + let extent = photocraft_engine::extra_cmds::reveal_all_bounds(&doc); + // One texel per `k` document pixels keeps every texture within the device's side. + let k = extent.width().max(extent.height()).div_ceil(texture_side(&ctx)).max(1); + let proxy = (k > 1).then(|| photocraft_compose::proxy::proxy_document(&doc, k)); + let src = proxy.as_ref().unwrap_or(&*doc); + let k = k as i32; + let opts = TextureOptions { magnification: egui::TextureFilter::Nearest, ..TextureOptions::LINEAR }; + let bands = ring(extent, doc.bounds()) + .into_iter() + .map(|b| { + // The proxy pixels over `b`: document pixels / k, rounded outwards. + let up = |v: i32| v.div_euclid(k) + i32::from(v.rem_euclid(k) != 0); + let p = DRect::new(b.x0.div_euclid(k), b.y0.div_euclid(k), up(b.x1), up(b.y1)); + let buf = photocraft_compose::render_reduced_rect(src, p, p.width(), p.height()); + let tex = ctx.load_texture("crop-beyond-canvas", display_image(display.as_deref(), &buf), opts); + (b, DRect::new(p.x0.saturating_mul(k), p.y0.saturating_mul(k), p.x1.saturating_mul(k), p.y1.saturating_mul(k)), tex) + }) + .collect(); + app.perf.span("crop-beyond-canvas", crate::gpu_canvas::now_ms() - t0); + let c = BeyondCanvas { snapshot, key: doc_key, extent, bands }; + ctx.data_mut(|d| d.insert_temp(key, c.clone())); + c + } + }; + // Transparency out to the frame, in phase with the canvas's own checkerboard. + let canvas = xf.doc_rect(doc.bounds()); + // A turned frame reaches as far as its corners. + let f = crate::crop_ui::turned_bounds(f, crate::crop_ui::angle(app)); + let fr = DRect::new(f[0].floor() as i32, f[1].floor() as i32, f[2].ceil() as i32, f[3].ceil() as i32); + let square = app.session.prefs().transparency_and_gamut.square(); + let checker_id = square.map(|_| checker(app, &ctx)); + let around = ring(c.extent.union(&fr), doc.bounds()); + // A turned view (Rotate View, or the Crop tool's default mode turning the image behind its + // box) draws each band as its turned quad: its screen bounding box would stretch the band's + // texture and spread the checkerboard past the band. + let turned = xf.rotation != 0.0; + let checker_uv = |p: Pos2, sq: f32| ((p - canvas.min) / (2.0 * sq)).to_pos2(); + for &b in &around { + if turned { + let q = doc_quad(xf, b); + match square.zip(checker_id) { + Some((sq, id)) => textured_quad(painter, id, q, q.map(|p| checker_uv(p, sq))), + None => { + painter.add(egui::Shape::convex_polygon(q.to_vec(), Color32::WHITE, Stroke::NONE)); + } + } + continue; + } + let r = under_canvas(xf.doc_rect(b), canvas); + match square.zip(checker_id) { + Some((sq, id)) => { + let uv = Rect::from_min_max(checker_uv(r.min, sq), checker_uv(r.max, sq)); + painter.image(id, r, uv, Color32::WHITE); + } + None => { + painter.rect_filled(r, 0.0, Color32::WHITE); + } + } + } + for (b, t, tex) in &c.bands { + let part = |a: i32, o: i32, len: u32| (i64::from(a) - i64::from(o)) as f32 / len.max(1) as f32; + let (mut u0, mut u1) = (part(b.x0, t.x0, t.width()), part(b.x1, t.x0, t.width())); + if turned { + // The quad's corners are the band's own (flip included), so no swap. + let (v0, v1) = (part(b.y0, t.y0, t.height()), part(b.y1, t.y0, t.height())); + textured_quad(painter, tex.id(), doc_quad(xf, *b), [pos2(u0, v0), pos2(u1, v0), pos2(u1, v1), pos2(u0, v1)]); + continue; + } + if xf.flip { + (u0, u1) = (u1, u0); + } + let uv = Rect::from_min_max(pos2(u0, part(b.y0, t.y0, t.height())), pos2(u1, part(b.y1, t.y0, t.height()))); + // The texture's edge texels stretch over the point under the canvas. + let (r, e) = (xf.doc_rect(*b), under_canvas(xf.doc_rect(*b), canvas)); + let at = |p: Pos2| uv.min + (p - r.min) / r.size() * uv.size(); + painter.image(tex.id(), e, Rect::from_min_max(at(e.min), at(e.max)), Color32::WHITE); + } + !around.is_empty() +} + +/// Document rect `b`'s corners on screen, clockwise from its top-left (a parallelogram in a turned +/// view). +fn doc_quad(xf: &ViewXform, b: DRect) -> [Pos2; 4] { + [(b.x0, b.y0), (b.x1, b.y0), (b.x1, b.y1), (b.x0, b.y1)].map(|(x, y)| xf.to_screen(x as f32, y as f32)) +} + +/// Texture `tex` drawn over the quad `q`, `uv` at its corners. +fn textured_quad(painter: &egui::Painter, tex: egui::TextureId, q: [Pos2; 4], uv: [Pos2; 4]) { + if !q.iter().chain(uv.iter()).all(|p| p.x.is_finite() && p.y.is_finite()) { + return; + } + let mut mesh = egui::Mesh::with_texture(tex); + for (pos, uv) in q.into_iter().zip(uv) { + mesh.vertices.push(egui::epaint::Vertex { pos, uv, color: Color32::WHITE }); + } + mesh.add_triangle(0, 1, 2); + mesh.add_triangle(0, 2, 3); + painter.add(egui::Shape::mesh(mesh)); +} + +/// Overlays that persist between gestures: polygonal or magnetic lasso in progress, pending crop box. +pub(super) fn draw_tool_state(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform, hover: Option) { + crate::magnetic_lasso_ui::draw(app, painter, xf, hover); + if !app.ui.polygon.is_empty() { + let mut pts: Vec = app.ui.polygon.iter().map(|p| xf.to_screen(p[0] as f32, p[1] as f32)).collect(); + if let Some(h) = hover { + // The rubber-band preview must use the same constrained point as the click, + // including when the canvas is zoomed, rotated or flipped. + let mods = painter.ctx().input(|i| i.modifiers); + if app.ui.tool == Tool::PolygonLasso && mods.shift && !mods.alt { + let raw = xf.to_doc(h); + let last = app.ui.polygon.last().copied().unwrap_or(raw); + let snapped = constrained_polygon_point(last, raw); + pts.push(xf.to_screen(snapped[0] as f32, snapped[1] as f32)); + } else { + pts.push(h); + } + } + // Just the outline and its rubber band (the vertices aren't handles to grab), solid until + // the selection is made (#7495). + crate::tool_feedback::draw_solid_path(painter, &pts, false); + } + crate::crop_straighten::draw(app, painter, |p| xf.to_screen(p[0] as f32, p[1] as f32), hover); + crate::blur_pins::draw(app, painter, xf); + if let Some(c) = app.ui.crop_rect { + let deg = crate::crop_ui::angle(app); + let shield = crate::crop_shield::current(app, painter.ctx()); + if deg == 0.0 && xf.rotation == 0.0 { + let r = Rect::from_two_pos(xf.to_screen(c[0] as f32, c[1] as f32), xf.to_screen(c[2] as f32, c[3] as f32)); + crop_overlay(painter, r, shield, &crate::crop_overlay::current_guides(app, r.width(), r.height())); + } else { + let q = crate::crop_ui::corners(c, deg).map(|p| xf.to_screen(p[0] as f32, p[1] as f32)); + crop_overlay_turned(painter, q, shield, &crate::crop_overlay::current_guides(app, q[0].distance(q[1]), q[0].distance(q[3]))); + } + // The frame's angle beside the pointer while it turns (#1792). + if let (Some(a), Some(h)) = (crate::crop_ui::turning(app), hover) { + draw_value_readout(app, painter.ctx(), "crop-angle-readout", h, ["Angle:"], [angle_readout(a)]); + } else if let (Some([w, h]), Some(at)) = (crate::crop_ui::sizing(app), hover) { + // Its W × H while it is drawn or resized (#1919), like the marquee's. + draw_marquee_readout(app, painter.ctx(), at, size_readout(app, [0.0, 0.0, w, h])); + } + } +} + +pub(super) fn draw_drag_preview(app: &mut PhotocraftApp, painter: &egui::Painter, xf: &ViewXform) { + draw_tool_state(app, painter, xf, painter.ctx().input(|i| i.pointer.hover_pos())); + // Remove strokes waiting for ↩ stay tinted between drags. + crate::retouch_ui::draw_remove_pending(app, painter, xf); + let Some(d) = &app.drag else { + app.trail = None; + return; + }; + // The Move tool's ΔX/ΔY beside the pointer, for layers and selected pixels alike (#5727). + if let Some(values) = crate::move_ui::offset_readout(app) { + let at = d.points.last().map_or(d.start, |p| [p[0], p[1]]); + draw_value_readout(app, painter.ctx(), "move-readout", xf.to_screen(at[0] as f32, at[1] as f32), ["ΔX:", "ΔY:"], values); + } + // Dragging the selection: its own ants follow the pointer (`selection_shown_offset`). + if d.sel_move.is_some() { + return; + } + let last = d.points.last().map(|p| [p[0], p[1]]).unwrap_or(d.start); + let marquee = marquee_preview_px(&app.ui.tool_options, d, app.point_zoom()); + if let Some(r) = marquee { + draw_marquee_readout(app, painter.ctx(), xf.to_screen(last[0] as f32, last[1] as f32), size_readout(app, r)); + } + match d.tool { + // The canvas shows the live stroke itself (`LiveStroke`); a stroke that couldn't start one + // (Sample All Layers, say) keeps the trail. + t if strokes_live(t) && app.live_stroke.is_some() => { + // Smoothing holds the brush back from the pointer: draw the string between them. + if let Some(EngineStroke::Brush(l)) = app.live_stroke.as_ref().map(|l| &l.stroke) + && let Some(s) = l.smoothing_string() + { + draw_smoothing_string(painter, xf, s); + } + } + t if t.is_brushlike() || t == Tool::QuickSelection => { + // Retouching strokes preview as a translucent trail of the brush footprint: a mask, + // not a brush-wide egui polyline (which zoomed in tessellates into wedges, #189). + let col = match t { + Tool::QuickSelection => Color32::from_white_alpha(40), + // The Remove Tool tints what it will remove, like Photoshop's. + Tool::Remove => crate::theme::Tokens::get(painter.ctx()).danger.gamma_multiply(0.45), + // Photoshop paints the area to heal in half-opaque dark grey while dragging; a faint + // white trail barely showed on light pixels (#7342). The heal itself is computed on + // release. + Tool::SpotHealing => SPOT_HEALING_TRAIL, + _ => Color32::from_white_alpha(60), + }; + let Some(st) = app.session.active() else { return }; + let size = [st.doc.size.width, st.doc.size.height]; + let doc_rect = xf.doc_rect(st.doc.bounds()); + let trail = app.trail.get_or_insert_with(|| crate::stroke_trail::Trail::new(size)); + if t == Tool::SpotHealing { + // What the heal covers, dab by dab: soft edges, pressure and shape dynamics (#2364). + trail.feed_dabs(&d.points, || photocraft_engine::retouch_cmds::stroke_brush(&app.session.tools.brush, &json!({}))); + } else { + trail.feed(&d.points, app.session.tools.brush.size); + } + trail.draw(painter, doc_rect, xf.flip, col); + } + t if crate::vector_ui::is_shape_tool(t) => crate::vector_ui::draw_shape_preview(app, painter, xf, t, d.start, last, d.live), + Tool::SingleRowMarquee | Tool::SingleColumnMarquee => { + // Mapped corner by corner like the other marquees, so a rotated view shows the line + // where the release commits it (#2512). + if let Some([x0, y0, x1, y1]) = single_line_drag_px(app, d) { + crate::tool_feedback::draw_ants(painter, &marquee_ants(xf, d.tool, [x0, y0], [x1, y1]), true); + } + } + // Nothing selected yet: no outline, as the release would deselect. + Tool::RectMarquee | Tool::EllipseMarquee if marquee.is_none() => {} + Tool::RectMarquee | Tool::EllipseMarquee | Tool::ObjectSelection => { + // Marching ants, visible on any pixels (#172): built in document space and mapped + // corner by corner, so a rotated view shows them where the release commits (#2512). + let pts = marquee_drag_ants(d, xf, marquee); + crate::tool_feedback::draw_ants(painter, &pts, true); + } + // Patch / Content-Aware Move dragging the selection: its outline follows the pointer. + Tool::Patch | Tool::ContentAwareMove if crate::retouch_ui::patch_drags_selection(app, d.start, d.modifiers) => { + let start = d.start; + let [dx, dy] = crate::retouch_ui::patch_offset(app, start, last); + if let Some((_, _, segs)) = &app.outline_cache { + let moved: Vec = segs.iter().map(|(a, b)| ([a[0] + dx, a[1] + dy], [b[0] + dx, b[1] + dy])).collect(); + marching_ants_segments(painter, xf, &moved, painter.ctx().input(|i| i.time)); + } + } + Tool::FreeformPen => { + let mut pts: Vec = d.points.iter().map(|p| xf.to_screen(p[0] as f32, p[1] as f32)).collect(); + // Between ⌥-clicks: the straight segment the next click makes. + if let Some(lasso) = &d.lasso { + pts.push(xf.to_screen(lasso.cursor[0] as f32, lasso.cursor[1] as f32)); + } + painter.add(egui::Shape::line(pts, Stroke::new(1.5, crate::theme::Tokens::get(painter.ctx()).accent))); + } + Tool::Lasso | Tool::Patch | Tool::ContentAwareMove => { + let mut pts: Vec = d.points.iter().map(|p| xf.to_screen(p[0] as f32, p[1] as f32)).collect(); + if let Some(lasso) = &d.lasso { + pts.push(xf.to_screen(lasso.cursor[0] as f32, lasso.cursor[1] as f32)); + } + // The Lasso's outline is solid until the release makes the selection (#7495); a Patch + // or Content-Aware Move area keeps its ants. + if d.tool == Tool::Lasso { + // On pixel centres, so a 1 pt line stays crisp wherever the canvas sits (a pixel + // edge would blur it to grey). + let pts: Vec = pts.into_iter().map(|p| p.round() + vec2(0.5, 0.5)).collect(); + crate::tool_feedback::draw_solid_path(painter, &pts, false); + } else { + crate::tool_feedback::draw_ants(painter, &pts, false); + } + } + Tool::Gradient => { + let a = xf.to_screen(d.start[0] as f32, d.start[1] as f32); + let b = xf.to_screen(last[0] as f32, last[1] as f32); + painter.line_segment([a, b], Stroke::new(3.0, Color32::from_black_alpha(140))); + painter.line_segment([a, b], Stroke::new(1.0, Color32::WHITE)); + painter.circle_filled(a, 3.0, Color32::WHITE); + painter.circle_filled(b, 3.0, Color32::WHITE); + } + Tool::Type | Tool::VerticalType | Tool::HorizontalTypeMask | Tool::VerticalTypeMask => { + let r = Rect::from_two_pos(xf.to_screen(d.start[0] as f32, d.start[1] as f32), xf.to_screen(last[0] as f32, last[1] as f32)); + let pts = [r.left_top(), r.right_top(), r.right_bottom(), r.left_bottom(), r.left_top()]; + painter.add(egui::Shape::line(pts.to_vec(), Stroke::new(1.0, Color32::WHITE))); + painter.add(egui::Shape::dashed_line(&pts, Stroke::new(1.0, Color32::BLACK), 3.0, 3.0)); + } + // The layers themselves follow the pointer (`move_ui`); the arrow only when they can't. + Tool::Move if !crate::move_ui::showing(app) => { + let from = xf.to_screen(d.start[0] as f32, d.start[1] as f32); + let off = xf.to_screen(last[0] as f32, last[1] as f32) - from; + painter.arrow(from, off, Stroke::new(2.0, crate::theme::Tokens::get(painter.ctx()).accent)); + } + _ => {} + } +} diff --git a/crates/ui-egui/src/canvas/paint_mouse.rs b/crates/ui-egui/src/canvas/paint_mouse.rs new file mode 100644 index 0000000000..dc64d34312 --- /dev/null +++ b/crates/ui-egui/src/canvas/paint_mouse.rs @@ -0,0 +1,239 @@ +//! Mouse buttons on the canvas. Tools follow the left button. The right button never paints with +//! the tool: with a painting tool it opens the Brush Preset picker at the pointer (Photoshop), or, +//! with Preferences › Tools › Right-click with painting tools set to Erase, a right drag with the +//! Brush erases with the current brush (Krita, Paint). Each right stroke is one `paint.stroke` +//! with `"erase": true`, so one undo step, with the pen pressure and tilt of a normal stroke. + +use egui::{PointerButton, Response}; +use photocraft_engine::BrushSettings; +use photocraft_engine::prefs::RightClickPaint; + +use crate::PhotocraftApp; +use crate::state::Tool; + +/// The brush is a tool option, kept per tool like Photoshop's options bar: switching from the +/// Brush to the Eraser saves the session brush for the old tool and loads the new tool's, so each +/// keeps its own size, hardness, mode, opacity, dynamics and smoothing. A tool seen for the +/// first time takes what the brush already has, at Photoshop's 10 % smoothing. Other tools leave +/// the brush alone. +/// +/// The foreground and background colours, the erase flag and the stroke seed belong to the +/// session rather than to the tool, so a swap never carries them between tools: picking a colour +/// or painting with the Eraser works with any tool's brush. +pub fn sync_tool_brush(app: &mut PhotocraftApp) { + let tool = app.ui.tool; + if !has_brush_picker(tool) || app.ui.brush_tool == tool { + return; + } + // The live brush is the outgoing tool's, so save it there before the new one takes over: any + // edit it made since it was last active is in it, so its copy never goes stale. + let current = app.session.tools.brush.clone(); + save_brush(app, app.ui.brush_tool, current.clone()); + app.session.tools.brush = match app.ui.tool_brushes.iter().find(|(t, _)| *t == tool) { + Some((_, b)) => { + // A brush remembered from the previous run holds its stored tips as references: + // load their full bitmaps (a missing one keeps painting with its preview). + let mut b = session_fields(¤t, b); + let _ = app.session.load_brush_tips(&mut b); + b + } + // A tool seen for the first time takes what the brush has, at Photoshop's smoothing, but + // in Normal mode: each tool's Mode starts at Normal, so a Multiply Brush doesn't make the + // first Clone Stamp stroke multiply (or give Healing a mode its menu doesn't have). + None => BrushSettings { smoothing: first_smoothing(), mode: photocraft_color::BlendMode::Normal, ..current }, + }; + // The picked preset was the outgoing tool's brush: forget it, so Update Brush can't overwrite + // that preset with this tool's brush. + app.session.tools.current_preset = None; + app.session.tools.brush_changed(); + app.ui.brush_tool = tool; +} + +/// The brush `tool` had when it was last active. +fn save_brush(app: &mut PhotocraftApp, tool: Tool, brush: BrushSettings) { + match app.ui.tool_brushes.iter_mut().find(|(t, _)| *t == tool) { + Some(e) => e.1 = brush, + None => app.ui.tool_brushes.push((tool, brush)), + } +} + +/// The session's own brush fields, which a tool swap never carries: the colours, the erase flag +/// and the stroke seed (a stroke's replay seed is the command's, not the tool's). +fn session_fields(current: &BrushSettings, brush: &BrushSettings) -> BrushSettings { + BrushSettings { color: current.color, background: current.background, erase: current.erase, seed: current.seed, ..brush.clone() } +} + +/// A tool's brush as it starts out (Reset Tool, #2825): the default brush at Photoshop's +/// smoothing, with the session's own fields of `current`. +pub(crate) fn fresh_brush(current: &BrushSettings) -> BrushSettings { + session_fields(current, &BrushSettings { smoothing: first_smoothing(), ..BrushSettings::default() }) +} + +/// Photoshop's 10 % stroke smoothing, what a tool's brush starts at. +fn first_smoothing() -> photocraft_engine::paint::brush::Smoothing { + photocraft_engine::paint::brush::Smoothing { amount: 0.1, ..Default::default() } +} + +/// Does a stroke with `tool` starting now paint in Photoshop's Clear mode, erasing with its own +/// brush (#3439)? Clear chosen in its Mode dropdown, or `~` held (`hold_keys::erase_held`). +pub fn clears(app: &PhotocraftApp, tool: Tool) -> bool { + let chosen = match tool { + Tool::Brush => app.ui.tool_options.brush_clear, + Tool::Pencil => app.ui.tool_options.pencil_clear, + _ => false, + }; + crate::hold_keys::erases_while_held(tool) && (chosen || app.held_erase) +} + +/// Which tool events this frame's canvas response produces. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Buttons { + pub started: bool, + pub dragged: bool, + pub stopped: bool, + pub clicked: bool, +} + +/// Tools with the options-bar brush chip, which opens the Brush Preset picker. +pub fn has_brush_picker(tool: Tool) -> bool { + tool.is_brushlike() || tool == Tool::QuickSelection +} + +/// Tools whose canvas right-click opens the Brush Preset picker: the painting tools. The Quick +/// Selection tool has the picker too, but its right-click opens the selection menu (#7268). +pub fn right_click_picker(tool: Tool) -> bool { + has_brush_picker(tool) && !crate::canvas_tool_menu::applies(tool) +} + +/// Does a right-button drag with `tool` erase (rather than open the picker)? +pub fn right_erases(app: &PhotocraftApp, tool: Tool) -> bool { + matches!(tool, Tool::Brush | Tool::Eraser) && app.session.prefs().tools.right_click_with_painting_tools == RightClickPaint::Erase +} + +/// Route the canvas response's buttons: the left one drives the tool; the right one resizes the +/// brush with Alt held (#297), erases (Erase preference) or opens the Brush Preset picker. Arms +/// `secondary_erase` or `brush_resize_armed` for this frame's `Down`. +pub fn canvas_buttons(app: &mut PhotocraftApp, response: &Response, tool: Tool) -> Buttons { + let physical_right = app.services.right_button_down.as_ref().is_some_and(|f| f()); + let (mods, mut right_down) = response.ctx.input(|i| (i.modifiers, i.pointer.secondary_down())); + right_down |= physical_right; + let right_started = response.drag_started_by(PointerButton::Secondary) || (physical_right && response.drag_started()); + let right_dragged = response.dragged_by(PointerButton::Secondary) || (physical_right && response.dragged()); + let resizing = app.brush_resize.is_some_and(|r| r.secondary); + let right_stopped = response.drag_stopped_by(PointerButton::Secondary) || (resizing && response.drag_stopped()); + + if physical_right && crate::brush_resize::is_right_gesture(crate::workspace_ui::sticky_mods(app, mods)) { + app.alt_sampling = false; + } + + // Alt+right-drag resizes the brush (brush_resize.rs); its events reach `tool_event` like a + // left drag's, and nothing paints. A resize whose release was missed ends here. + crate::brush_resize::release_stale(app, right_down || response.drag_stopped_by(PointerButton::Secondary) || response.drag_stopped()); + let resize_start = crate::brush_resize::applies(tool) + && app.drag.is_none() + && crate::brush_resize::is_right_gesture(crate::workspace_ui::sticky_mods(app, mods)) + && (right_started || (physical_right && response.dragged() && app.brush_resize.is_none())); + let resizing = app.brush_resize.is_some_and(|r| r.secondary); + app.brush_resize_armed = resize_start || (physical_right && resizing); + // ⌘/Ctrl+right-click lists the layers under the pointer instead (layer_pick_ui.rs, #307). + let layer_menu = crate::layer_pick_ui::is_gesture(tool, mods); + let erase = right_erases(app, tool) && !resize_start && !resizing && !layer_menu; + let right_stroke = erase && app.drag.is_some(); + let right_start = erase && right_started; + let right_click = response.secondary_clicked(); + if right_click + && !erase + && !layer_menu + && right_click_picker(tool) + && let Some(p) = response.interact_pointer_pos() + { + crate::brush_picker::open(&mut app.ui, &response.ctx, [p.x, p.y]); + } + let erase_click = erase && right_click; + app.secondary_erase = right_start || erase_click; + let right_drag = right_stroke || resizing; + Buttons { + started: response.drag_started_by(PointerButton::Primary) || right_start || resize_start, + dragged: response.dragged_by(PointerButton::Primary) || (right_drag && right_dragged), + stopped: response.drag_stopped_by(PointerButton::Primary) || (right_drag && right_stopped), + clicked: response.clicked() || erase_click, + } +} + +/// `ui.pointer` with `"button": "secondary"`: true when its events should reach the tool (an +/// Alt+right-drag brush resize, `brush_resize_armed` for its `Down`; or an erasing right stroke, +/// `secondary_erase` armed for its `Down`). Otherwise a right-click with a painting tool opens +/// the Brush Preset picker at screen point `at`, and nothing paints. +pub fn pointer_secondary(app: &mut PhotocraftApp, ctx: &egui::Context, down: bool, mods: egui::Modifiers, at: [f32; 2]) -> bool { + let tool = app.ui.tool; + if crate::brush_resize::applies(tool) && (crate::brush_resize::is_right_gesture(mods) || app.brush_resize.is_some_and(|r| r.secondary)) { + app.brush_resize_armed = down && app.drag.is_none(); + return true; + } + if right_erases(app, tool) { + app.secondary_erase = down; + return true; + } + if down && right_click_picker(tool) { + crate::brush_picker::open(&mut app.ui, ctx, at); + } + false +} + +/// The Brush Preset picker a right-click or the options-bar brush chip opened, at the pointer. It +/// edits the session brush like the Brushes panel; a press outside, Escape, Enter or a +/// double-click on a preset closes it. +pub fn show_picker(app: &mut PhotocraftApp, ctx: &egui::Context) { + let Some([x, y]) = app.ui.brush_picker else { return }; + if !has_brush_picker(app.ui.tool) { + app.ui.brush_picker = None; + return; + } + // Escape and Enter close it once this frame's edits are in (a typed size applies), unless they + // end a rename in its rename bar. + let key_close = app.ui.brush_picker_list.renaming.is_none() && ctx.input(|i| i.key_pressed(egui::Key::Escape) || i.key_pressed(egui::Key::Enter)); + let screen = ctx.content_rect(); + // The picker's content size: the one its grip was dragged to, or the one it last closed with + // (kept in egui's own memory, which outlives the app's), or the default. The frame's chrome + // sits around it, and together they keep the whole picker on screen. + let id = crate::brush_picker::picker_id(); + let size_id = id.with("content-size"); + let content = app.ui.brush_picker_size.or_else(|| ctx.data_mut(|d| d.get_persisted::<[f32; 2]>(size_id))).map_or_else( + || egui::vec2(crate::brush_picker::DEFAULT_SIZE[0], crate::brush_picker::DEFAULT_SIZE[1]), + |s| crate::brush_picker::clamp_size(s, screen.size()), + ); + // Remember it for the picker's next open, and — egui's memory being saved — the next run. + ctx.data_mut(|d| d.insert_persisted(size_id, [content.x, content.y])); + let style = ctx.global_style(); + let size = content + style.spacing.menu_margin.sum() + egui::Vec2::splat(2.0 * style.visuals.window_stroke().width); + let pos = egui::pos2(x.min(screen.right() - size.x).max(screen.left()), y.min(screen.bottom() - size.y).max(screen.top())); + let area = egui::Area::new(id).order(egui::Order::Foreground).fixed_pos(pos).show(ctx, |ui| { + let before = app.session.tools.brush.clone(); + let mut b = before.clone(); + let list = &mut app.ui.brush_picker_list; + let frame = egui::Frame::popup(ui.style()) + .show(ui, |ui| crate::brush_picker::body(ui, &mut b, &app.session.tools.presets, app.session.tools.current_preset.as_deref(), list, content)); + let picks = frame.inner; + // The corner grip resizes the picker, and the size is remembered across opens. + if let Some(new) = crate::brush_picker::resize_grip(ui, frame.response.rect, content) { + app.ui.brush_picker_size = Some([new.x, new.y]); + } + crate::brush_panel::commit_gesture(app, ui.ctx(), &before, &b); + let closes = picks.iter().any(crate::brush_picker::Pick::closes); + crate::brush_picker::apply(app, ui.ctx(), picks); + closes + }); + // Not a press on a menu the picker opened (the gear, a preset's context menu), nor on the + // options-bar chip, whose click toggles the picker. A menu floats over the picker in the + // foreground order, so the press is told apart by the layer it lands on, not by any popup + // just being open: a press elsewhere closes the picker in the same click that closes the menu. + let press = ctx.input(|i| i.pointer.any_pressed().then(|| i.pointer.interact_pos()).flatten()); + let on_menu = press.is_some_and(|p| ctx.layer_id_at(p).is_some_and(|l| l.order == egui::Order::Foreground)); + let outside = crate::canvas_popup::outside_pressed(ctx, id, area.response.rect) && press.is_some_and(|p| !crate::brush_picker::on_chip(ctx, p)) && !on_menu; + if outside || key_close || area.inner { + crate::brush_picker::close(&mut app.ui); + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/canvas/paint_mouse/tests.rs b/crates/ui-egui/src/canvas/paint_mouse/tests.rs new file mode 100644 index 0000000000..4b54a1ce98 --- /dev/null +++ b/crates/ui-egui/src/canvas/paint_mouse/tests.rs @@ -0,0 +1,481 @@ +use egui::{Modifiers, PointerButton, Pos2, vec2}; +use egui_kittest::Harness; +use serde_json::json; + +use super::*; +use crate::canvas::{ToolEvent, tool_event}; + +fn harness(prefs: Option<&str>) -> Harness<'static, PhotocraftApp> { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("tools.setColors", json!({"foreground": "#0000ff"})).unwrap(); + app.run("tools.setBrush", json!({"brush": {"size": 20, "hardness": 1.0}})).unwrap(); + if let Some(v) = prefs { + app.run("prefs.set", json!({"path": "tools.rightClickWithPaintingTools", "value": v})).unwrap(); + } + app.ui.tool = Tool::Brush; + app.sync_views(); + let mut h = Harness::builder().with_size(vec2(1200.0, 800.0)).with_step_dt(1.0 / 60.0).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let ctx = ui.ctx().clone(); + if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(4); + h +} + +fn press(h: &mut Harness<'static, PhotocraftApp>, pos: Pos2, button: PointerButton, pressed: bool) { + h.event(egui::Event::PointerButton { pos, button, pressed, modifiers: Modifiers::NONE }); + h.run_steps(2); +} + +/// Drag across the canvas centre with `button`; returns the document points it covered. +fn drag(h: &mut Harness<'static, PhotocraftApp>, button: PointerButton) -> (Pos2, Pos2) { + let c = h.state().last_canvas_rect.center(); + let (a, b) = (c - vec2(80.0, 0.0), c + vec2(80.0, 0.0)); + h.event(egui::Event::PointerMoved(a)); + h.run_steps(1); + press(h, a, button, true); + for i in 1..=8 { + h.event(egui::Event::PointerMoved(a + (b - a) * (i as f32 / 8.0))); + h.run_steps(1); + } + press(h, b, button, false); + (a, b) +} + +fn alpha_at(h: &Harness<'static, PhotocraftApp>, screen: Pos2) -> f32 { + let app = h.state(); + let v = app.ui.views[0].clone(); + let r = app.last_canvas_rect; + let d = (screen - r.center()) / v.zoom; + let (x, y) = ((d.x + v.center[0]) as i32, (d.y + v.center[1]) as i32); + let st = app.session.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().rgba(x, y)[3] +} + +fn strokes(h: &Harness<'static, PhotocraftApp>) -> Vec { + h.state().session.journal.iter().filter(|(id, _)| id == "paint.stroke").map(|(_, p)| p.clone()).collect() +} + +#[test] +fn left_drag_paints() { + let mut h = harness(None); + let (a, b) = drag(&mut h, PointerButton::Primary); + assert_eq!(strokes(&h).len(), 1); + assert!(alpha_at(&h, a + (b - a) * 0.5) > 0.9); +} + +#[test] +fn shift_click_connects_to_the_previous_brush_stroke() { + use egui::{Event, Modifiers}; + + let mut h = harness(None); + let (_, end) = drag(&mut h, PointerButton::Primary); + let previous = h + .state() + .session + .journal + .iter() + .rev() + .find(|(id, _)| id == "paint.stroke") + .map(|(_, p)| p["points"].as_array().unwrap().last().unwrap().clone()) + .unwrap(); + let target = end + vec2(120.0, 80.0); + h.event(Event::PointerMoved(target)); + h.run_steps(1); + for pressed in [true, false] { + h.event(Event::PointerButton { pos: target, button: PointerButton::Primary, pressed, modifiers: Modifiers::SHIFT }); + h.run_steps(2); + } + + let strokes = strokes(&h); + assert_eq!(strokes.len(), 2, "a Shift-click commits one connected stroke"); + let points = strokes[1]["points"].as_array().unwrap(); + // The previous endpoint, then the clicked one. While the button is held, smoothing that is + // still catching up repeats the clicked point with later times. + assert_eq!(points[0][0], previous[0]); + assert_eq!(points[0][1], previous[1]); + let clicked = &points[1]; + assert!(points[1..].iter().all(|p| p[0] == clicked[0] && p[1] == clicked[1]), "{points:?}"); + assert!(alpha_at(&h, end + vec2(60.0, 40.0)) > 0.9, "the segment between the strokes is painted"); +} + +#[test] +fn right_click_opens_the_brush_picker_and_never_paints() { + let mut h = harness(None); + let undo = h.state().session.active().unwrap().history.past_len(); + let c = h.state().last_canvas_rect.center(); + h.event(egui::Event::PointerMoved(c)); + h.run_steps(1); + press(&mut h, c, PointerButton::Secondary, true); + press(&mut h, c, PointerButton::Secondary, false); + assert_eq!(h.state().ui.brush_picker, Some([c.x, c.y]), "opened at the pointer"); + assert!(strokes(&h).is_empty()); + // The picker shows over the canvas at the pointer, moved up just enough to stay on screen. + h.run_steps(2); + let shown = h.ctx.memory(|m| m.area_rect(egui::Id::unique("canvas-brush-picker"))).expect("picker shown"); + let screen = h.ctx.content_rect(); + assert!((shown.min.x - c.x).abs() < 1.0 && shown.min.y <= c.y + 1.0, "{shown:?}"); + assert!(screen.contains_rect(shown.shrink(0.5)) && shown.width() > 250.0 && shown.height() > 150.0, "{shown:?}"); + // It is the real preset library, not a fixed set of round tips (#258). + let names: Vec = h.state().session.tools.presets.iter().take(3).map(|p| p.name.clone()).collect(); + { + use egui_kittest::kittest::Queryable; + for n in &names { + assert!(h.query_by_label(n).is_some(), "{n} listed"); + } + } + // A right drag doesn't paint either. + drag(&mut h, PointerButton::Secondary); + assert!(strokes(&h).is_empty(), "right-drag never paints with the brush picker preference"); + assert_eq!(h.state().session.active().unwrap().history.past_len(), undo, "no edit"); + // Escape closes it. + h.state_mut().ui.brush_picker = Some([c.x, c.y]); + h.run_steps(1); + h.key_press(egui::Key::Escape); + h.run_steps(2); + assert_eq!(h.state().ui.brush_picker, None); +} + +#[test] +fn click_outside_closes_the_picker() { + let mut h = harness(None); + let c = h.state().last_canvas_rect.center(); + h.state_mut().ui.brush_picker = Some([c.x, c.y]); + h.run_steps(2); + let far = c - vec2(300.0, 200.0); + h.event(egui::Event::PointerMoved(far)); + press(&mut h, far, PointerButton::Primary, true); + press(&mut h, far, PointerButton::Primary, false); + assert_eq!(h.state().ui.brush_picker, None); +} + +/// #1031: the right-click picker picks brushes, not just the size. A click picks a preset and +/// keeps the picker open, a double-click picks one and closes it, and Enter applies a typed +/// size before it closes the picker. +#[test] +fn picker_click_picks_a_preset_and_double_click_closes_it() { + use egui_kittest::kittest::Queryable; + let mut h = harness(None); + let c = h.state().last_canvas_rect.center(); + h.event(egui::Event::PointerMoved(c)); + h.run_steps(1); + press(&mut h, c, PointerButton::Secondary, true); + press(&mut h, c, PointerButton::Secondary, false); + h.run_steps(2); + let names: Vec = h.state().session.tools.presets.iter().skip(1).take(2).map(|p| p.name.clone()).collect(); + let picks = |h: &Harness<'static, PhotocraftApp>, name: &str| { + h.state().session.journal.iter().filter(|(id, p)| id == "tools.setBrush" && *p == json!({ "preset": name })).count() + }; + h.get_by_label(&names[0]).click(); + h.run_steps(3); + assert_eq!(picks(&h, &names[0]), 1); + assert!(h.state().ui.brush_picker.is_some(), "a click keeps the picker open"); + let at = h.get_by_label(&names[1]).rect().center(); + h.event(egui::Event::PointerMoved(at)); + h.run_steps(1); + // Two clicks 2 frames apart; well after the first click, so not a triple click. + h.run_steps(40); + for pressed in [true, false, true, false] { + h.event(egui::Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.step(); + } + h.run_steps(2); + assert_eq!(picks(&h, &names[1]), 1, "picked once: the second click only closes"); + assert_eq!(h.state().ui.brush_picker, None, "a double-click closes the picker"); + assert!(strokes(&h).is_empty(), "nothing painted under the picker"); + // Enter applies the typed size, then closes the picker. + h.state_mut().ui.brush_picker = Some([c.x, c.y]); + h.run_steps(2); + h.get_all_by_role(egui::accesskit::Role::SpinButton).next().expect("the Size field").click(); + h.run_steps(1); + h.event(egui::Event::Text("30*2".into())); + h.run_steps(1); + h.key_press(egui::Key::Enter); + h.run_steps(2); + assert_eq!((h.state().session.tools.brush.size, h.state().ui.brush_picker), (60.0, None)); +} + +/// A sampled tip has no hardness: the picker shows only its size (Photoshop). +#[test] +fn picker_shows_hardness_only_for_round_tips() { + use egui_kittest::kittest::Queryable; + let mut h = harness(None); + let c = h.state().last_canvas_rect.center(); + h.state_mut().ui.brush_picker = Some([c.x, c.y]); + h.run_steps(2); + assert!(h.query_all_by_label("Hardness").next().is_some()); + let sampled = h.state().session.tools.presets.iter().find(|p| p.brush.tip != photocraft_engine::paint::TipShape::Round).map(|p| p.name.clone()); + h.state_mut().run("tools.setBrush", json!({ "preset": sampled.expect("a sampled preset") })).unwrap(); + h.run_steps(2); + assert!(h.query_all_by_label("Hardness").next().is_none()); + assert!(h.state().ui.brush_picker.is_some()); +} + +/// The gear menu's New Brush Preset… opens the New Brush Preset dialog (#4490), which saves +/// the preset under the typed name on OK. +#[test] +fn picker_gear_menu_saves_and_names_a_new_preset() { + use egui_kittest::kittest::Queryable; + let mut h = harness(None); + let c = h.state().last_canvas_rect.center(); + h.state_mut().ui.brush_picker = Some([c.x, c.y]); + h.run_steps(2); + h.get_by_label("Brush Preset Options").click(); + h.run_steps(2); + let before = h.state().session.tools.presets.len(); + h.get_by_label("New Brush Preset…").click(); + h.run_steps(3); + let dialog = h.state().ui.dialogs.iter().find(|d| crate::brush_preset_dialog::owns(&d.fields)).map(|d| d.id).expect("the dialog asks for a name"); + assert_eq!(h.state().session.tools.presets.len(), before, "nothing is saved before OK"); + assert!(h.state().ui.brush_picker.is_none(), "the dialog takes the picker's place"); + // This harness draws the canvas only: OK as automation does (the dialog's own tests type). + h.state_mut().ui.dialog_mut(dialog).unwrap().fields.insert("name".into(), json!("Inky")); + crate::dialogs::confirm(h.state_mut(), dialog).unwrap(); + h.run_steps(2); + assert!(h.state().session.tools.presets.iter().any(|p| p.name == "Inky"), "saved under the typed name"); + assert_eq!(h.state().session.tools.current_preset.as_deref(), Some("Inky")); + h.state_mut().ui.brush_picker = Some([c.x, c.y]); + h.run_steps(2); + // The gear's boxes pick the card parts; the last one on can't be turned off. + h.get_by_label("Brush Preset Options").click(); + h.run_steps(2); + h.get_by_label("Brush Tip").click(); + h.run_steps(2); + assert!(!h.state().ui.brush_picker_list.show_tip); + h.get_by_label("Brush Stroke").click(); + h.run_steps(2); + h.get_by_label("Brush Name").click(); + h.run_steps(2); + assert!(h.state().ui.brush_picker_list.show_name, "the last part on stays on"); + assert!(!h.state().ui.brush_picker_list.show_stroke && !h.state().ui.brush_picker_list.show_tip); + assert!(h.state().ui.brush_picker.is_some()); + // A rename left open goes with the picker. + h.state_mut().ui.brush_picker_list.renaming = + Some(crate::brush_panel::Renaming { group: false, name: "Inky".into(), folder: Vec::new(), text: String::new() }); + h.run_steps(2); + let far = c - vec2(300.0, 200.0); + h.event(egui::Event::PointerMoved(far)); + press(&mut h, far, PointerButton::Primary, true); + press(&mut h, far, PointerButton::Primary, false); + assert!(h.state().ui.brush_picker.is_none() && h.state().ui.brush_picker_list.renaming.is_none()); +} + +#[test] +fn right_drag_erases_with_the_erase_preference() { + let mut h = harness(Some("erase")); + let (a, b) = drag(&mut h, PointerButton::Primary); + let mid = a + (b - a) * 0.5; + assert!(alpha_at(&h, mid) > 0.9); + let undo = h.state().session.active().unwrap().history.past_len(); + drag(&mut h, PointerButton::Secondary); + let s = strokes(&h); + assert_eq!(s.len(), 2); + assert_eq!(s[1]["erase"], json!(true), "the right stroke erases"); + assert_eq!(alpha_at(&h, mid), 0.0, "erased to transparency"); + assert_eq!(h.state().session.active().unwrap().history.past_len(), undo + 1, "one undo step"); + assert_eq!(h.state().ui.brush_picker, None, "no picker in erase mode"); + // The next left stroke paints again. + drag(&mut h, PointerButton::Primary); + assert_eq!(strokes(&h)[2]["erase"], json!(false)); + assert!(alpha_at(&h, mid) > 0.9); +} + +#[test] +fn right_stroke_erases_with_pen_pressure_through_the_control_channel_path() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 120, "height": 80})).unwrap(); + app.run("prefs.set", json!({"path": "tools.rightClickWithPaintingTools", "value": "erase"})).unwrap(); + app.ui.tool = Tool::Brush; + let m = Modifiers::NONE; + assert!(pointer_secondary(&mut app, &egui::Context::default(), true, egui::Modifiers::NONE, [0.0, 0.0])); + tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 40.0, pressure: 0.4 }, m); + assert!(!app.secondary_erase, "armed for one stroke only"); + tool_event(&mut app, ToolEvent::Move { x: 100.0, y: 40.0, pressure: 0.8 }, m); + tool_event(&mut app, ToolEvent::Up { x: 100.0, y: 40.0 }, m); + let p = app.session.journal.iter().rev().find(|(id, _)| id == "paint.stroke").map(|(_, p)| p.clone()).unwrap(); + assert_eq!(p["erase"], json!(true)); + assert_eq!(p["points"][0], json!([10.0, 40.0, 0.4f32 as f64]), "pressure reaches the erasing stroke"); + // On the Background the erasing stroke paints the background colour (#76). + let st = app.session.active().unwrap(); + assert_eq!(st.doc.layers[0].surface().unwrap().rgba(50, 40), [1.0, 1.0, 1.0, 1.0]); + // With the default preference the right button opens the picker and nothing paints. + app.run("prefs.set", json!({"path": "tools.rightClickWithPaintingTools", "value": "brushPicker"})).unwrap(); + assert!(!pointer_secondary(&mut app, &egui::Context::default(), true, egui::Modifiers::NONE, [0.0, 0.0])); + assert!(app.ui.brush_picker.is_some() && !app.secondary_erase); +} + +#[test] +fn the_brush_is_a_per_tool_option_that_presets_keep() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); + let amount = |app: &PhotocraftApp| app.session.tools.brush.smoothing.amount; + app.ui.tool = Tool::Brush; + sync_tool_brush(&mut app); + assert_eq!(amount(&app), 0.1, "Photoshop's default"); + // Picking a preset (whose own smoothing is 0) keeps the tool's smoothing. + let preset = app.session.tools.presets.iter().find(|p| p.brush.smoothing.amount == 0.0).map(|p| p.name.clone()).unwrap(); + app.run("tools.setBrush", json!({"preset": preset})).unwrap(); + assert_eq!(amount(&app), 0.1); + // A user value (the options-bar field) survives a preset too, mode included. + app.session.tools.brush.smoothing.amount = 0.42; + app.session.tools.brush.smoothing.pulled_string = true; + app.run("tools.setBrush", json!({"preset": preset})).unwrap(); + assert_eq!((amount(&app), app.session.tools.brush.smoothing.pulled_string), (0.42, true)); + // The Eraser has its own (10 % at first); switching back restores the Brush's. + app.ui.tool = Tool::Eraser; + sync_tool_brush(&mut app); + assert_eq!(amount(&app), 0.1); + app.session.tools.brush.smoothing.amount = 0.0; + app.ui.tool = Tool::Brush; + sync_tool_brush(&mut app); + assert_eq!((amount(&app), app.session.tools.brush.smoothing.pulled_string), (0.42, true)); + // Other tools leave it alone; the Eraser kept its 0 %. + app.ui.tool = Tool::Move; + sync_tool_brush(&mut app); + assert_eq!(amount(&app), 0.42); + app.ui.tool = Tool::Eraser; + // A stroke picks up the tool's brush even without a frame in between. + tool_event(&mut app, ToolEvent::Down { x: 5.0, y: 5.0, pressure: 1.0 }, Modifiers::NONE); + assert_eq!(amount(&app), 0.0); + tool_event(&mut app, ToolEvent::Up { x: 30.0, y: 5.0 }, Modifiers::NONE); +} + +/// #218: Photoshop keeps a brush per painting tool, so the size, hardness, mode, opacity and +/// dynamics of one tool never leak into another's, and each tool gets its own back. +#[test] +fn each_tool_keeps_its_own_brush() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); + let brush = |app: &PhotocraftApp| app.session.tools.brush.clone(); + let size = |b: &BrushSettings| b.size; + let hardness = |b: &BrushSettings| b.hardness; + let opacity = |b: &BrushSettings| b.opacity; + let mode = |b: &BrushSettings| b.mode; + + app.ui.tool = Tool::Brush; + sync_tool_brush(&mut app); + app.run("tools.setBrush", json!({"brush": {"size": 40, "hardness": 0.2, "opacity": 0.7, "mode": "Multiply"}})).unwrap(); + assert_eq!(size(&brush(&app)), 40.0); + + // A tool seen for the first time starts from the brush the old tool left (Photoshop's + // 10 % smoothing), so nothing is lost by switching. + app.ui.tool = Tool::Eraser; + sync_tool_brush(&mut app); + assert_eq!(size(&brush(&app)), 40.0, "a new tool inherits the current brush"); + + // The Eraser edits its own size; the Brush keeps 40 px. + app.run("tools.setBrush", json!({"brush": {"size": 8, "hardness": 1.0}})).unwrap(); + app.ui.tool = Tool::Brush; + sync_tool_brush(&mut app); + assert_eq!(size(&brush(&app)), 40.0, "the Brush keeps its own size"); + assert_eq!(hardness(&brush(&app)), 0.2, "and its hardness"); + app.ui.tool = Tool::Eraser; + sync_tool_brush(&mut app); + assert_eq!(size(&brush(&app)), 8.0, "the Eraser keeps its own size"); + assert_eq!(hardness(&brush(&app)), 1.0, "and its hardness"); + + // Mode, opacity, flow and the dynamics sections are per tool too. + app.ui.tool = Tool::CloneStamp; + sync_tool_brush(&mut app); + assert_eq!(mode(&brush(&app)), photocraft_color::BlendMode::Normal, "a new tool starts in Normal, not the Brush's Multiply"); + app.run("tools.setBrush", json!({"brush": {"mode": "Screen", "opacity": 0.3}})).unwrap(); + app.ui.tool = Tool::Brush; + sync_tool_brush(&mut app); + assert_eq!((mode(&brush(&app)), opacity(&brush(&app))), (photocraft_color::BlendMode::Multiply, 0.7), "the Brush's own mode and opacity"); + app.ui.tool = Tool::CloneStamp; + sync_tool_brush(&mut app); + assert_eq!((mode(&brush(&app)), opacity(&brush(&app))), (photocraft_color::BlendMode::Screen, 0.3), "the Clone Stamp keeps its own"); + + // The colours, the erase flag and the seed belong to the session, so a swap keeps what is + // live now instead of restoring another tool's copy (a picked colour reaches every tool). + app.run("tools.setBrush", json!({"brush": {"color": [0.0, 1.0, 0.0, 1.0], "background": [1.0, 0.0, 1.0, 1.0], "erase": true, "seed": 42}})).unwrap(); + app.ui.tool = Tool::Brush; + sync_tool_brush(&mut app); + let b = brush(&app); + assert_eq!( + (b.color, b.background, b.erase, b.seed), + ([0.0, 1.0, 0.0, 1.0], [1.0, 0.0, 1.0, 1.0], true, 42), + "the session's own brush fields survive the swap" + ); + + // Tools with no brush of their own (the Move) leave the brush alone. + let before = brush(&app); + app.ui.tool = Tool::Move; + sync_tool_brush(&mut app); + assert_eq!(brush(&app), before); +} + +#[test] +fn eraser_tool_on_the_background_paints_the_background_colour() { + // #76: the Eraser on the Background (locked transparency) paints the background colour. + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 120, "height": 80})).unwrap(); + app.run("tools.setColors", json!({"background": "#ff0000"})).unwrap(); + app.run("tools.setBrush", json!({"brush": {"size": 12, "hardness": 1.0}})).unwrap(); + app.ui.tool = Tool::Eraser; + let m = Modifiers::NONE; + tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 40.0, pressure: 1.0 }, m); + tool_event(&mut app, ToolEvent::Move { x: 100.0, y: 40.0, pressure: 1.0 }, m); + tool_event(&mut app, ToolEvent::Up { x: 100.0, y: 40.0 }, m); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.layers[0].name, "Background"); + assert_eq!(st.doc.layers[0].surface().unwrap().rgba(50, 40), [1.0, 0.0, 0.0, 1.0]); + assert_eq!(st.history.undo_label(), Some("Eraser")); + assert!(!app.ui.status_error, "{}", app.ui.status); +} + +/// Assert the one committed stroke contains a point at each queued screen position. +fn assert_committed_points(h: &Harness<'static, PhotocraftApp>, queued: &[Pos2]) { + let s = strokes(h); + assert_eq!(s.len(), 1); + let points = s[0]["points"].as_array().unwrap(); + let app = h.state(); + let v = app.ui.views[0].clone(); + let r = app.last_canvas_rect; + for p in queued { + let d = (*p - r.center()) / v.zoom; + let want = [d.x as f64 + v.center[0] as f64, d.y as f64 + v.center[1] as f64]; + assert!( + points.iter().any(|q| { + let q = q.as_array().unwrap(); + (q[0].as_f64().unwrap() - want[0]).abs() < 1.0 && (q[1].as_f64().unwrap() - want[1]).abs() < 1.0 + }), + "queued move {want:?} missing from {points:?}" + ); + } +} + +#[test] +fn one_frame_feeds_every_pointer_move_not_just_the_latest() { + // Fast strokes used to lose the moves between two frames: the canvas read only + // `interact_pointer_pos()` once per frame, so the stroke was a coarse polyline. Every + // `PointerMoved` egui-winit delivered in one frame must now reach the stroke. + let mut h = harness(None); + let c = h.state().last_canvas_rect.center(); + let a = c - vec2(90.0, 0.0); + h.event(egui::Event::PointerMoved(a)); + h.run_steps(1); + press(&mut h, a, PointerButton::Primary, true); + // Cross egui's drag threshold on its own frame. + h.event(egui::Event::PointerMoved(a + vec2(20.0, 0.0))); + h.run_steps(1); + // Several moves in ONE frame: `Harness::event` would make one frame per event, so push + // them straight into the next frame's input. All of them must reach the committed stroke. + let queued: Vec = (1..=6).map(|i| a + vec2(20.0 + i as f32 * 8.0, 0.0)).collect(); + for p in &queued { + h.input_mut().events.push(egui::Event::PointerMoved(*p)); + } + h.run_steps(1); + let end = *queued.last().unwrap(); + press(&mut h, end, PointerButton::Primary, false); + assert_committed_points(&h, &queued); +} diff --git a/crates/ui-egui/src/patch_preview.rs b/crates/ui-egui/src/canvas/patch_preview.rs similarity index 100% rename from crates/ui-egui/src/patch_preview.rs rename to crates/ui-egui/src/canvas/patch_preview.rs diff --git a/crates/ui-egui/src/pattern_preview.rs b/crates/ui-egui/src/canvas/pattern_preview.rs similarity index 100% rename from crates/ui-egui/src/pattern_preview.rs rename to crates/ui-egui/src/canvas/pattern_preview.rs diff --git a/crates/ui-egui/src/pixel_grid.rs b/crates/ui-egui/src/canvas/pixel_grid.rs similarity index 100% rename from crates/ui-egui/src/pixel_grid.rs rename to crates/ui-egui/src/canvas/pixel_grid.rs diff --git a/crates/ui-egui/src/quick_pick.rs b/crates/ui-egui/src/canvas/quick_pick.rs similarity index 100% rename from crates/ui-egui/src/quick_pick.rs rename to crates/ui-egui/src/canvas/quick_pick.rs diff --git a/crates/ui-egui/src/canvas/rotate_view.rs b/crates/ui-egui/src/canvas/rotate_view.rs new file mode 100644 index 0000000000..8b6706327f --- /dev/null +++ b/crates/ui-egui/src/canvas/rotate_view.rs @@ -0,0 +1,273 @@ +//! Rotate View tool: turn the canvas camera around its centre without rewriting pixels. +//! +//! Drag around the view centre: the image follows the pointer (clockwise increases the angle, or +//! decreases it in a flipped view). Shift snaps to 15°. Reset View, +//! Escape, a double-click, or the on-canvas compass put the angle back to 0. History is not +//! recorded. Trackpad rotate is gated by Preferences › Enhanced Controls › Rotate View with +//! Trackpad; a two-finger twist on a touch screen also needs Enable Gestures (#204). + +use egui::{Align2, Pos2, Rect, Stroke, pos2, vec2}; +use serde_json::{Value, json}; + +use crate::PhotocraftApp; +use crate::canvas::ViewXform; +use crate::paint_mouse::Buttons; +use crate::state::View; +use crate::theme::Tokens; + +/// Snap increment, in degrees, while Shift is held. +pub const SNAP_DEG: f32 = 15.0; + +/// A Rotate View drag in progress. +#[derive(Clone, Copy, Debug, PartialEq)] +struct RotateDrag { + /// Screen point of the view centre when the drag began. + pivot: Pos2, + /// Pointer angle, in degrees, at the press (atan2, Y-down: clockwise is positive). + start_pointer: f32, + /// View rotation, in degrees, at the press. + start_rotation: f32, +} + +fn id() -> egui::Id { + egui::Id::unique("pc-rotate-view-drag") +} + +fn compass_id() -> egui::Id { + egui::Id::unique("pc-rotate-view-compass") +} + +/// Wrap `a` degrees into (−180, 180]. Non-finite values become 0 so a hostile angle never +/// propagates into the camera. +pub fn wrap_deg(a: f32) -> f32 { + if !a.is_finite() { + return 0.0; + } + let mut x = f64::from(a) % 360.0; + if x > 180.0 { + x -= 360.0; + } else if x <= -180.0 { + x += 360.0; + } + x as f32 +} + +/// Nearest multiple of `step` degrees, wrapped. A non-positive or non-finite step is ignored. +pub fn snap_deg(a: f32, step: f32) -> f32 { + if !(step.is_finite() && step > 0.0) { + return wrap_deg(a); + } + wrap_deg((a / step).round() * step) +} + +/// Turn a pointer or trackpad angle change (screen degrees, clockwise positive) into a change of +/// `View::rotation`. [`ViewXform::to_screen`] mirrors x after rotating, so in a flipped view a +/// larger angle turns the image the other way on screen; negating keeps it under the pointer. +pub fn screen_delta(delta: f32, flip: bool) -> f32 { + let d = wrap_deg(delta); + if flip { wrap_deg(-d) } else { d } +} + +/// Pointer angle in degrees around `pivot` (Y-down, so clockwise is positive). +pub fn pointer_deg(p: Pos2, pivot: Pos2) -> f32 { + let d = p - pivot; + if !(d.x.is_finite() && d.y.is_finite()) || d.length_sq() < 1e-8 { + return 0.0; + } + d.y.atan2(d.x).to_degrees() +} + +fn finite_number(p: &Value, key: &str) -> Result, String> { + match p.get(key) { + None => Ok(None), + Some(v) => v + .as_f64() + .filter(|n| n.is_finite() && n.abs() <= f64::from(f32::MAX)) + .map(|n| Some(n as f32)) + .ok_or_else(|| format!("{key} must be a finite number representable as f32")), + } +} + +/// Apply `view.rotateView` params to `current`. Empty params, a non-object, or a missing +/// `angle`/`delta`/`reset` are errors (never a silent no-op). +pub fn apply_params(current: f32, p: &Value) -> Result { + let obj = p.as_object().ok_or("params must be an object")?; + for k in obj.keys() { + if !matches!(k.as_str(), "angle" | "delta" | "reset") { + return Err(format!("unknown field `{k}`")); + } + } + let reset = match obj.get("reset") { + None => false, + Some(v) => v.as_bool().ok_or_else(|| "reset must be a boolean".to_string())?, + }; + let angle = finite_number(p, "angle")?; + let delta = finite_number(p, "delta")?; + if !reset && angle.is_none() && delta.is_none() { + return Err("expected angle, delta, or reset".into()); + } + if reset { + return Ok(0.0); + } + let mut r = angle.unwrap_or(current); + if let Some(d) = delta { + r += d; + if !r.is_finite() { + return Err("delta overflowed the angle".into()); + } + } + Ok(wrap_deg(r)) +} + +/// Trackpad rotate: `delta_rad` is egui's rotation delta (radians, same sign as [`wrap_deg`]). +/// Returns the new angle when the preference is on and the delta is a finite non-zero value. +pub fn apply_trackpad(current: f32, enabled: bool, delta_rad: f32) -> Option { + if !enabled || !delta_rad.is_finite() || delta_rad == 0.0 { + return None; + } + let deg = delta_rad.to_degrees(); + if !deg.is_finite() { + return None; + } + let next = current + deg; + if !next.is_finite() { + return None; + } + Some(wrap_deg(next)) +} + +/// This frame's trackpad rotation in degrees, if the preference is on and egui reported a delta. +/// The trackpad's own `Rotate` events always count; a touch screen's two-finger twist (egui's +/// multi-touch rotation) only while `touch_gestures` (Enhanced Controls › Enable Gestures) is on. +pub fn trackpad_delta(ctx: &egui::Context, enabled: bool, touch_gestures: bool) -> Option { + if !enabled { + return None; + } + let rad = ctx.input(|i| { + let from_events: f32 = i + .events + .iter() + .filter_map(|e| match e { + egui::Event::Rotate(r) if r.is_finite() => Some(*r), + _ => None, + }) + .sum(); + if from_events != 0.0 { + from_events + } else if touch_gestures { + i.rotation_delta() + } else { + 0.0 + } + }); + apply_trackpad(0.0, true, rad).filter(|_| rad != 0.0) +} + +/// `view.rotateView`: set or add degrees on the active document's camera. +pub fn command(app: &mut PhotocraftApp, p: &Value) -> Result { + let i = app.session.active_index().ok_or("no document open")?; + let current = app.ui.views.get(i).map(|v| v.rotation).ok_or("no document open")?; + let rotation = apply_params(current, p)?; + let v = app.ui.views.get_mut(i).ok_or("no document open")?; + v.rotation = rotation; + Ok(json!({"rotation": v.rotation})) +} + +/// `view.resetView`: angle 0, zoom and centre unchanged. +pub fn reset(app: &mut PhotocraftApp) -> Result { + let i = app.session.active_index().ok_or("no document open")?; + let v = app.ui.views.get_mut(i).ok_or("no document open")?; + v.rotation = 0.0; + Ok(json!({"rotation": 0.0, "zoom": v.zoom, "center": v.center})) +} + +/// Route canvas buttons for Rotate View. Returns true when the drag is owned (the canvas then +/// ignores the tool underneath). +pub fn drag(ctx: &egui::Context, view: &mut View, xf: &ViewXform, b: &Buttons, pointer: Option) -> bool { + if b.started { + let pivot = xf.rect.center(); + let origin = ctx.input(|i| i.pointer.press_origin()).filter(|p| xf.rect.contains(*p)).or(pointer); + if let Some(p) = origin { + ctx.data_mut(|d| { + d.insert_temp(id(), RotateDrag { pivot, start_pointer: pointer_deg(p, pivot), start_rotation: view.rotation }); + }); + } + } + let Some(z) = ctx.data(|d| d.get_temp::(id())) else { + return b.started || b.dragged || b.stopped; + }; + if let Some(p) = pointer.filter(|_| b.dragged || b.stopped) { + let delta = screen_delta(pointer_deg(p, z.pivot) - z.start_pointer, xf.flip); + let mut angle = z.start_rotation + delta; + if !angle.is_finite() { + angle = z.start_rotation; + } + if ctx.input(|i| i.modifiers.shift) { + angle = snap_deg(angle, SNAP_DEG); + } + view.rotation = wrap_deg(angle); + } + if b.stopped { + ctx.data_mut(|d| d.remove::(id())); + } + true +} + +/// Compass in the top-right of the canvas (north = document up). Hidden at 0°. +pub fn compass_rect(canvas: Rect) -> Rect { + const S: f32 = 36.0; + const M: f32 = 10.0; + Rect::from_min_size(pos2(canvas.right() - M - S, canvas.top() + M), vec2(S, S)) +} + +/// True when the compass is showing (angle is not ~0). +pub fn compass_visible(rotation: f32) -> bool { + rotation.is_finite() && rotation.abs() > 0.05 +} + +/// Draw the compass and handle a click / Escape / double-click reset. Returns true when the +/// pointer over the compass should not start a rotate drag. +pub fn overlay(app: &PhotocraftApp, ctx: &egui::Context, painter: &egui::Painter, xf: &ViewXform, view: &mut View, response: &egui::Response) -> bool { + if app.ui.tool == crate::state::Tool::RotateView && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) && view.rotation != 0.0 { + view.rotation = 0.0; + ctx.data_mut(|d| d.remove::(id())); + } + if app.ui.tool == crate::state::Tool::RotateView && (response.double_clicked() || response.triple_clicked()) { + view.rotation = 0.0; + ctx.data_mut(|d| d.remove::(id())); + } + if !compass_visible(view.rotation) { + ctx.data_mut(|d| d.remove::(compass_id())); + return false; + } + let r = compass_rect(xf.rect); + ctx.data_mut(|d| d.insert_temp(compass_id(), r)); + let t = Tokens::get(ctx); + let hover = response.hover_pos().is_some_and(|p| r.contains(p)); + painter.circle_filled(r.center(), r.width() * 0.5, if hover { t.hover } else { t.chrome }); + painter.circle_stroke(r.center(), r.width() * 0.5 - 0.5, Stroke::new(1.0, t.separator)); + // Document up: (0, −1) in document space, rotated then flipped like [`ViewXform::to_screen`]. + let rad = view.rotation.to_radians(); + let (c, s) = if view.rotation.abs() < 1e-6 { (1.0, 0.0) } else { (rad.cos(), rad.sin()) }; + let (rx, ry) = (s, -c); + let sx = if xf.flip { -1.0 } else { 1.0 }; + let needle = vec2(rx * sx, ry) * (r.width() * 0.32); + let tip = r.center() + needle; + painter.line_segment([r.center(), tip], Stroke::new(2.0, t.accent)); + painter.circle_filled(tip, 2.5, t.accent); + painter.text(r.center() + vec2(0.0, r.width() * 0.18), Align2::CENTER_CENTER, "N", egui::FontId::proportional(9.0), t.text_faint); + if response.clicked() && response.interact_pointer_pos().is_some_and(|p| r.contains(p)) { + view.rotation = 0.0; + ctx.data_mut(|d| d.remove::(id())); + return true; + } + hover +} + +/// Cursor for the Rotate View tool. +pub fn cursor(dragged: bool) -> egui::CursorIcon { + if dragged { egui::CursorIcon::Grabbing } else { egui::CursorIcon::Grab } +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/canvas/rotate_view/tests.rs b/crates/ui-egui/src/canvas/rotate_view/tests.rs new file mode 100644 index 0000000000..2705c28ac9 --- /dev/null +++ b/crates/ui-egui/src/canvas/rotate_view/tests.rs @@ -0,0 +1,369 @@ +use super::*; +use egui::{Event, PointerButton, pos2}; +use egui_kittest::Harness; +use serde_json::json; + +#[test] +fn wrap_deg_folds_huge_and_hostile_angles() { + assert_eq!(wrap_deg(0.0), 0.0); + assert_eq!(wrap_deg(180.0), 180.0); + assert_eq!(wrap_deg(-180.0), 180.0); + assert!((wrap_deg(190.0) + 170.0).abs() < 1e-4); + assert!((wrap_deg(-190.0) - 170.0).abs() < 1e-4); + assert!((wrap_deg(360.0)).abs() < 1e-4); + assert!((wrap_deg(1.0e10)).abs() <= 180.0); + assert_eq!(wrap_deg(f32::NAN), 0.0); + assert_eq!(wrap_deg(f32::INFINITY), 0.0); + assert_eq!(wrap_deg(f32::NEG_INFINITY), 0.0); +} + +#[test] +fn snap_deg_lands_on_fifteens() { + assert_eq!(snap_deg(0.0, SNAP_DEG), 0.0); + assert_eq!(snap_deg(7.0, SNAP_DEG), 0.0); + assert_eq!(snap_deg(8.0, SNAP_DEG), 15.0); + assert_eq!(snap_deg(-7.0, SNAP_DEG), 0.0); + assert_eq!(snap_deg(-8.0, SNAP_DEG), -15.0); + assert_eq!(snap_deg(40.0, SNAP_DEG), 45.0); + assert_eq!(snap_deg(f32::NAN, SNAP_DEG), 0.0); + assert_eq!(snap_deg(40.0, 0.0), wrap_deg(40.0)); + assert_eq!(snap_deg(40.0, f32::NAN), wrap_deg(40.0)); +} + +#[test] +fn apply_params_sets_adds_resets_and_rejects() { + assert_eq!(apply_params(0.0, &json!({"angle": 30.0})).unwrap(), 30.0); + assert_eq!(apply_params(30.0, &json!({"delta": 15.0})).unwrap(), 45.0); + assert_eq!(apply_params(45.0, &json!({"reset": true})).unwrap(), 0.0); + assert_eq!(apply_params(170.0, &json!({"delta": 20.0})).unwrap(), -170.0); + assert!(apply_params(0.0, &json!({})).is_err()); + assert!(apply_params(0.0, &Value::Null).is_err()); + assert!(apply_params(0.0, &json!("30")).is_err()); + assert!(apply_params(0.0, &json!({"angle": f64::NAN})).is_err()); + assert!(apply_params(0.0, &json!({"angle": f64::INFINITY})).is_err()); + assert!(apply_params(0.0, &json!({"delta": f64::INFINITY})).is_err()); + // JSON can contain finite f64 values whose f32 conversion overflows to infinity. + // Silently wrapping infinity to 0 would reset a rotated view. + assert!(apply_params(32.0, &json!({"angle": 1.0e100})).is_err()); + assert!(apply_params(32.0, &json!({"delta": -1.0e100})).is_err()); + assert!(apply_params(0.0, &json!({"reset": "yes"})).is_err()); + assert!(apply_params(0.0, &json!({"zoom": 1})).is_err()); + let huge = apply_params(0.0, &json!({"angle": 1.0e20})).unwrap(); + assert!(huge.is_finite() && huge.abs() <= 180.0); +} + +#[test] +fn native_rotate_event_reaches_canvas_when_trackpad_rotation_is_enabled() { + let ctx = egui::Context::default(); + let mut enabled = None; + let mut disabled = None; + let raw = egui::RawInput { events: vec![Event::Rotate(std::f32::consts::FRAC_PI_6)], ..Default::default() }; + let mut output = ctx.run_ui(raw, |ui| { + enabled = trackpad_delta(ui.ctx(), true, true); + disabled = trackpad_delta(ui.ctx(), false, true); + }); + output.textures_delta.clear(); + + assert!(enabled.is_some_and(|degrees| (degrees - 30.0).abs() < 1e-3), "{enabled:?}"); + assert_eq!(disabled, None); +} + +/// Preferences › Enhanced Controls › Enable Gestures (#204): off, a two-finger twist on a +/// touch screen doesn't turn the view; the trackpad's `Rotate` event still does. +#[test] +fn enable_gestures_switches_touch_screen_rotation() { + use egui::TouchPhase::{Move, Start}; + let touch = |id: u64, phase, pos| Event::Touch { device_id: egui::TouchDeviceId(1), id: egui::TouchId(id), phase, pos, force: None }; + let twist = |touch_gestures: bool, extra: Vec| { + let ctx = egui::Context::default(); + let frames = [ + // egui only starts a multi-touch gesture once it knows where the pointer is. + vec![Event::PointerMoved(pos2(50.0, 50.0))], + vec![touch(1, Start, pos2(40.0, 50.0)), touch(2, Start, pos2(60.0, 50.0))], + // A quarter turn about the centre between the fingers. + [vec![touch(1, Move, pos2(50.0, 40.0)), touch(2, Move, pos2(50.0, 60.0))], extra].concat(), + ]; + let mut last = None; + for (n, events) in (0u32..).zip(frames) { + let raw = egui::RawInput { time: Some(f64::from(n) / 60.0), events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| last = trackpad_delta(ui.ctx(), true, touch_gestures)); + out.textures_delta.clear(); + } + last + }; + let on = twist(true, Vec::new()); + assert!(on.is_some_and(|d| (d.abs() - 90.0).abs() < 1e-3), "on: the fingers turn the view: {on:?}"); + assert_eq!(twist(false, Vec::new()), None, "off: the fingers don't"); + let trackpad = twist(false, vec![Event::Rotate(std::f32::consts::FRAC_PI_6)]); + assert!(trackpad.is_some_and(|d| (d - 30.0).abs() < 1e-3), "off: a trackpad rotate still turns: {trackpad:?}"); +} + +#[test] +fn trackpad_pref_gates_rotation() { + assert_eq!(apply_trackpad(10.0, false, 0.5), None); + assert_eq!(apply_trackpad(10.0, true, 0.0), None); + assert_eq!(apply_trackpad(10.0, true, f32::NAN), None); + assert_eq!(apply_trackpad(10.0, true, f32::INFINITY), None); + let a = apply_trackpad(10.0, true, std::f32::consts::FRAC_PI_2).expect("finite delta"); + assert!((a - 100.0).abs() < 0.05, "{a}"); +} + +#[test] +fn view_xform_identity_matches_unrotated_mapping() { + for zoom in [0.5, 1.0, 2.5] { + for center in [[0.0, 0.0], [320.0, 240.0], [10.0, -4.0]] { + for flip in [false, true] { + let rect = Rect::from_min_size(pos2(100.0, 50.0), vec2(800.0, 600.0)); + let a = ViewXform { rect, zoom, center, flip, rotation: 0.0, aspect: 1.0 }; + let sx = if flip { -1.0 } else { 1.0 }; + let want = rect.center() + vec2((10.0 - center[0]) * zoom * sx, (20.0 - center[1]) * zoom); + let got = a.to_screen(10.0, 20.0); + assert!((got.x - want.x).abs() < 1e-4 && (got.y - want.y).abs() < 1e-4, "{got:?} vs {want:?}"); + } + } + } +} + +#[test] +fn view_xform_roundtrip_and_ninety_degrees() { + let rect = Rect::from_min_size(pos2(0.0, 0.0), vec2(400.0, 300.0)); + for rot in [15.0, 90.0, -45.0, 180.0] { + for flip in [false, true] { + let xf = ViewXform { rect, zoom: 2.0, center: [80.0, 40.0], flip, rotation: rot, aspect: 1.0 }; + let s = xf.to_screen(10.0, 20.0); + let d = xf.to_doc(s); + assert!((d[0] - 10.0).abs() < 1e-3 && (d[1] - 20.0).abs() < 1e-3, "rot={rot} flip={flip} {d:?}"); + } + } + // 90°: a point on +X in document space lands on +Y on screen (Y-down = clockwise). + let xf = ViewXform { rect, zoom: 1.0, center: [0.0, 0.0], flip: false, rotation: 90.0, aspect: 1.0 }; + let s = xf.to_screen(1.0, 0.0); + let c = rect.center(); + assert!((s.x - c.x).abs() < 1e-3 && (s.y - (c.y + 1.0)).abs() < 1e-3, "{s:?} vs {c:?}"); + // Flip after rotate: 0° +X goes left. + let xf = ViewXform { rect, zoom: 1.0, center: [0.0, 0.0], flip: true, rotation: 0.0, aspect: 1.0 }; + assert!(xf.to_screen(1.0, 0.0).x < rect.center().x); + let xf = ViewXform { rect, zoom: 1.0, center: [0.0, 0.0], flip: true, rotation: 90.0, aspect: 1.0 }; + let s = xf.to_screen(1.0, 0.0); + assert!((s.x - c.x).abs() < 1e-3 && (s.y - (c.y + 1.0)).abs() < 1e-3, "flip then rotate {s:?}"); +} + +/// Screen angle, about the canvas centre, of the document point that was under `p0` at the press. +fn followed_angle(h: &Harness<'static, PhotocraftApp>, p0: Pos2, start_rotation: f32) -> f32 { + let st = h.state(); + let (rect, v, flip) = (st.last_canvas_rect, &st.ui.views[0], st.ui.view.flip_horizontal); + let before = ViewXform { rect, zoom: 1.0, center: v.center, flip, rotation: start_rotation, aspect: 1.0 }; + let d = before.to_doc(p0); + let after = ViewXform { rotation: v.rotation, ..before }; + let s = after.to_screen(d[0] as f32, d[1] as f32) - rect.center(); + wrap_deg(s.y.atan2(s.x).to_degrees() - pointer_deg(p0, rect.center())) +} + +#[test] +fn drag_follows_the_pointer_in_a_flipped_view() { + for flip in [false, true] { + let mut h = harness(); + h.state_mut().ui.view.flip_horizontal = flip; + h.run_steps(2); + let c = h.state().last_canvas_rect.center(); + let p0 = c + vec2(120.0, 0.0); + h.event(Event::PointerMoved(p0)); + h.step(); + press(&mut h, p0, true, false); + // 30° clockwise about the pivot: the image turns 30° clockwise on screen. + let p1 = c + vec2(120.0 * 30f32.to_radians().cos(), 120.0 * 30f32.to_radians().sin()); + h.event(Event::PointerMoved(p1)); + h.step(); + let got = followed_angle(&h, p0, 0.0); + assert!((got - 30.0).abs() < 0.75, "flip={flip}: the image turned {got}°, the pointer 30°"); + press(&mut h, p1, false, false); + } +} + +#[test] +fn screen_delta_mirrors_only_in_a_flipped_view() { + assert_eq!(screen_delta(12.5, false), 12.5); + assert_eq!(screen_delta(12.5, true), -12.5); + assert_eq!(screen_delta(-180.0, true), 180.0); + assert_eq!(screen_delta(f32::NAN, true), 0.0); + assert_eq!(screen_delta(f32::INFINITY, false), 0.0); + // A flipped view still lands on the snapped angle with Shift. + assert_eq!(snap_deg(0.0 + screen_delta(-40.0, true), SNAP_DEG), 45.0); +} + +fn app_docs(n: usize) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + for i in 0..n { + app.run("file.new", json!({"width": 200 + i as u32 * 10, "height": 100})).unwrap(); + } + app.sync_views(); + app +} + +#[test] +fn commands_rotate_reset_and_reject_without_a_document() { + let ctx = egui::Context::default(); + let mut empty = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + assert_eq!(crate::menus::invoke(&mut empty, &ctx, "view.rotateView", json!({"angle": 30})).unwrap_err(), "no document open"); + assert_eq!(crate::menus::invoke(&mut empty, &ctx, "view.resetView", json!({})).unwrap_err(), "no document open"); + + let mut app = app_docs(1); + let r = crate::menus::invoke(&mut app, &ctx, "view.rotateView", json!({"angle": 30})).unwrap(); + assert_eq!(r["rotation"], 30.0); + assert_eq!(app.ui.views[0].rotation, 30.0); + let r = crate::menus::invoke(&mut app, &ctx, "view.rotateView", json!({"delta": 15})).unwrap(); + assert_eq!(r["rotation"], 45.0); + let z = app.ui.views[0].zoom; + let c = app.ui.views[0].center; + let r = crate::menus::invoke(&mut app, &ctx, "view.resetView", json!({})).unwrap(); + assert_eq!(r["rotation"], 0.0); + assert_eq!(app.ui.views[0].rotation, 0.0); + assert_eq!(app.ui.views[0].zoom, z); + assert_eq!(app.ui.views[0].center, c); + assert!(crate::menus::invoke(&mut app, &ctx, "view.rotateView", json!({})).is_err()); + assert!(crate::menus::invoke(&mut app, &ctx, "view.rotateView", json!({"angle": f64::NAN})).is_err()); + assert_eq!(app.ui.views[0].rotation, 0.0); + assert_eq!(app.session.documents()[0].history.past_len(), 0); +} + +#[test] +fn ui_set_selects_the_tool_and_sets_rotation() { + let ctx = egui::Context::default(); + let mut app = app_docs(1); + let (req, _) = crate::control::ControlRequest::new("ui.set", json!({"tool": "RotateView", "rotation": 30})); + let out = crate::control::handle(&mut app, &ctx, &req); + let crate::control::Outcome::Done(v) = out else { panic!("done") }; + assert_eq!(v["ok"], true, "{v}"); + assert_eq!(app.ui.tool, crate::state::Tool::RotateView); + assert_eq!(app.ui.views[0].rotation, 30.0); + let (req, _) = crate::control::ControlRequest::new("ui.inspect", json!({})); + let crate::control::Outcome::Done(ins) = crate::control::handle(&mut app, &ctx, &req) else { panic!("inspect") }; + assert_eq!(ins["result"]["tool"], "RotateView"); + assert_eq!(ins["result"]["views"][0]["rotation"], 30.0); + let (req, _) = crate::control::ControlRequest::new("ui.set", json!({"rotation": f64::NAN})); + let crate::control::Outcome::Done(bad) = crate::control::handle(&mut app, &ctx, &req) else { panic!("nan") }; + assert_eq!(bad["ok"], false); + assert_eq!(app.ui.views[0].rotation, 30.0); + let mut empty = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let (req, _) = crate::control::ControlRequest::new("ui.set", json!({"tool": "RotateView"})); + let crate::control::Outcome::Done(ok) = crate::control::handle(&mut empty, &ctx, &req) else { panic!("tool") }; + assert_eq!(ok["ok"], true, "{ok}"); + assert_eq!(empty.ui.tool, crate::state::Tool::RotateView); + let (req, _) = crate::control::ControlRequest::new("ui.set", json!({"rotation": 15})); + let crate::control::Outcome::Done(err) = crate::control::handle(&mut empty, &ctx, &req) else { panic!("no doc") }; + assert_eq!(err["ok"], false); + assert!(err["error"].as_str().unwrap().contains("no document open"), "{err}"); +} + +#[test] +fn match_rotation_copies_the_angle_and_needs_two_documents() { + let ctx = egui::Context::default(); + let one = app_docs(1); + assert_eq!(crate::view_cmds::is_enabled(&one, "window.arrange.matchRotation"), Some(false)); + let mut app = app_docs(2); + assert_eq!(crate::view_cmds::is_enabled(&app, "window.arrange.matchRotation"), Some(true)); + app.ui.views[1].rotation = 30.0; + let r = crate::menus::invoke(&mut app, &ctx, "window.arrange.matchRotation", json!({})).unwrap(); + assert_eq!(r["rotation"], 30.0); + assert!(app.ui.views.iter().all(|v| (v.rotation - 30.0).abs() < 1e-4)); + app.ui.views[1].rotation = 12.0; + app.ui.views[1].zoom = 2.0; + crate::menus::invoke(&mut app, &ctx, "window.arrange.matchAll", json!({})).unwrap(); + assert!(app.ui.views.iter().all(|v| (v.rotation - 12.0).abs() < 1e-4 && (v.zoom - 2.0).abs() < 1e-4)); +} + +fn harness() -> Harness<'static, PhotocraftApp> { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.sync_views(); + app.ui.extras.rulers = false; + app.ui.tool = crate::state::Tool::RotateView; + let mut h = Harness::builder().with_size(vec2(1000.0, 700.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(4); + h +} + +fn press(h: &mut Harness<'static, PhotocraftApp>, p: Pos2, pressed: bool, shift: bool) { + let modifiers = egui::Modifiers { shift, ..Default::default() }; + h.event(Event::PointerButton { pos: p, button: PointerButton::Primary, pressed, modifiers }); + h.step(); +} + +#[test] +fn shift_drag_snaps_to_fifteen_degrees() { + let mut h = harness(); + let r = h.state().last_canvas_rect; + let c = r.center(); + let p0 = c + vec2(120.0, 0.0); + h.event(Event::PointerMoved(p0)); + h.step(); + h.event(Event::ModifiersChanged(egui::Modifiers::SHIFT)); + h.step(); + press(&mut h, p0, true, true); + // ~40° clockwise: Shift rounds to 45°. + let p1 = c + vec2(120.0 * 40f32.to_radians().cos(), 120.0 * 40f32.to_radians().sin()); + h.event(Event::PointerMoved(p1)); + h.step(); + let rot = h.state().ui.views[0].rotation; + assert!((rot - 45.0).abs() < 0.75, "{rot}"); + press(&mut h, p1, false, true); + h.run_steps(2); + assert_eq!(h.state().session.documents()[0].history.past_len(), 0); + assert_eq!(crate::state::Tool::from_name("RotateView"), Some(crate::state::Tool::RotateView)); + assert_eq!(crate::state::Tool::RotateView.key(), 'R'); +} + +#[test] +fn escape_and_reset_zero_the_angle_without_history() { + let ctx = egui::Context::default(); + let mut app = app_docs(1); + crate::menus::invoke(&mut app, &ctx, "view.rotateView", json!({"angle": 33})).unwrap(); + assert_eq!(app.session.documents()[0].history.past_len(), 0); + crate::menus::invoke(&mut app, &ctx, "view.resetView", json!({})).unwrap(); + assert_eq!(app.ui.views[0].rotation, 0.0); + assert_eq!(app.session.documents()[0].history.past_len(), 0); + + let mut h = harness(); + h.state_mut().ui.views[0].rotation = 40.0; + h.event(Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }); + h.step(); + h.run_steps(2); + assert!((h.state().ui.views[0].rotation).abs() < 0.05, "{}", h.state().ui.views[0].rotation); + assert_eq!(h.state().session.documents()[0].history.past_len(), 0); +} + +#[test] +fn rotated_view_keeps_engine_selection_in_document_space() { + let mut app = app_docs(1); + app.ui.views[0].rotation = 30.0; + app.run("select.rect", json!({"x": 10, "y": 20, "width": 40, "height": 10})).unwrap(); + let st = app.session.active().unwrap(); + let b = st.doc.selection.as_ref().and_then(|s| photocraft_compose::bounds::content_bounds(s).into()).expect("selection"); + // Axis-aligned in the file: the outline is drawn rotated via ViewXform. + assert!(b.width() >= 40 && b.height() >= 10, "{b:?}"); + let xf = + ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)), zoom: 1.0, center: [100.0, 50.0], flip: false, rotation: 30.0, aspect: 1.0 }; + let a = xf.to_screen(10.0, 20.0); + let c = xf.to_screen(50.0, 20.0); + let v = c - a; + let ang = v.y.atan2(v.x).to_degrees(); + assert!((wrap_deg(ang) - 30.0).abs() < 0.5, "{ang}"); + assert_eq!(st.history.past_len(), 1, "only the selection is a history step"); +} + +#[test] +fn gpu_path_stays_on_with_rotation() { + // Flip is the only CPU-blit fallback; rotation is a shader uniform. + assert!(crate::gpu_canvas::gpu_view_ok(false, 45.0, 1.0)); + assert!(!crate::gpu_canvas::gpu_view_ok(true, 45.0, 1.0)); + assert!(crate::gpu_canvas::gpu_view_ok(false, 0.0, 1.0)); +} diff --git a/crates/ui-egui/src/canvas/rulers.rs b/crates/ui-egui/src/canvas/rulers.rs new file mode 100644 index 0000000000..923e81140a --- /dev/null +++ b/crates/ui-egui/src/canvas/rulers.rs @@ -0,0 +1,579 @@ +//! View extras: rulers (⌘R), grid (⌘'), guides (⌘;). Guides are dragged out of the rulers and +//! moved with the Move tool (drag one off the canvas or onto a ruler to delete it), all through +//! undoable engine commands (`view.newGuide` / `view.moveGuide` / `view.deleteGuide`). + +use egui::{Align2, Color32, Pos2, Rect, Sense, Stroke, pos2, vec2}; +use photocraft_doc::Document; +use photocraft_engine::prefs::{GuidesGridAndSlices, Unit}; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::canvas::ViewXform; +use crate::theme::Tokens; + +pub const RULER: f32 = 16.0; + +/// A `#rrggbb` preference colour. +fn pref_color(s: &str, fallback: Color32) -> Color32 { + photocraft_engine::prefs::parse_hex(s).map_or(fallback, |c| Color32::from_rgb(c[0], c[1], c[2])) +} + +/// Draw a line in a Guides/Grid preference style (lines, dashed lines, dots). +fn styled_line(painter: &egui::Painter, a: Pos2, b: Pos2, stroke: Stroke, style: photocraft_engine::prefs::LineStyle) { + use photocraft_engine::prefs::LineStyle; + match style { + LineStyle::Lines => { + painter.line_segment([a, b], stroke); + } + LineStyle::Dashed => { + painter.extend(egui::Shape::dashed_line(&[a, b], stroke, 4.0, 3.0)); + } + LineStyle::Dots => { + painter.extend(egui::Shape::dotted_line(&[a, b], stroke.color, 3.0, 0.6)); + } + } +} + +/// Ruler step in units so labelled ticks are at least `min` units apart: …0.1, 0.25, 0.5, 1, 2, 5, +/// 10… (whole steps only for pixels). +fn nice_step(min: f64, whole: bool) -> f64 { + let mut step = if whole { 1.0 } else { 0.001 }; + loop { + for m in [1.0, 2.0, 2.5, 5.0] { + if (m != 2.5 || !whole) && step * m >= min { + return step * m; + } + } + step *= 10.0; + } +} + +/// English display name for a length unit, as shown in Preferences › Units & Rulers. +fn unit_label(u: Unit) -> &'static str { + match u { + Unit::Pixels => "Pixels", + Unit::Inches => "Inches", + Unit::Centimeters => "Centimeters", + Unit::Millimeters => "Millimeters", + Unit::Points => "Points", + Unit::Picas => "Picas", + Unit::Percent => "Percent", + } +} + +/// Every length unit, in the Preferences › Units & Rulers order. +const UNITS: [Unit; 7] = [Unit::Pixels, Unit::Inches, Unit::Centimeters, Unit::Millimeters, Unit::Points, Unit::Picas, Unit::Percent]; + +/// The units Photoshop's Create Rectangle (and the other shape dialogs) offer on a right-click of +/// Width or Height: the lengths, without Percent. +pub(crate) const LENGTH_UNITS: [Unit; 6] = [Unit::Pixels, Unit::Inches, Unit::Centimeters, Unit::Millimeters, Unit::Points, Unit::Picas]; + +/// The ruler right-click menu: every unit of `units` with its (translated) label and whether it's +/// the one in effect. Picking one changes the ruler unit exactly as the preference pane does. +fn unit_menu_items(current: Unit, units: &[Unit]) -> Vec<(String, &'static str, bool)> { + units.iter().map(|&u| (tl!(unit_label(u)).to_string(), u.name(), u == current)).collect() +} + +/// The length units menu that right-clicking a ruler (or Free Transform's W and H fields) opens; +/// the chosen unit's name is returned (`None` if the menu is dismissed without a pick). +pub(crate) fn unit_menu(ui: &mut egui::Ui, current: Unit) -> Option<&'static str> { + unit_menu_of(ui, current, &UNITS) +} + +/// [`unit_menu`] with only `units` in it. +pub(crate) fn unit_menu_of(ui: &mut egui::Ui, current: Unit, units: &[Unit]) -> Option<&'static str> { + crate::widgets::menu_scroll(ui, |ui| { + ui.set_min_width(150.0); + let mut chosen = None; + for (label, name, checked) in unit_menu_items(current, units) { + let label = if checked { format!("✓ {label}") } else { label }; + if ui.button(label).clicked() { + ui.close(); + chosen = Some(name); + } + } + chosen + }) +} + +/// A guide being dragged: from a ruler (new) or an existing one (index). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct GuideDrag { + pub vertical: bool, + pub index: Option, + pub pos: f64, + /// Where the pointer went down, on the guide's axis: released there, an existing guide is + /// clicked (selected), not moved. + pub press: f64, + /// Whether the pointer was over a ruler when the guide was let go (#6286): a guide released + /// there is removed, whatever its own axis reads. + pub over_ruler: bool, +} + +impl GuideDrag { + /// An existing guide taken at document point `p`. + pub fn existing(vertical: bool, index: usize, p: [f64; 2]) -> Self { + let at = if vertical { p[0] } else { p[1] }; + Self { vertical, index: Some(index), pos: at, press: at, over_ruler: false } + } +} + +/// Canvas area left after the rulers. +pub fn content_rect(app: &PhotocraftApp, rect: Rect) -> Rect { + if app.ui.extras.rulers { Rect::from_min_max(rect.min + vec2(RULER, RULER), rect.max) } else { rect } +} + +/// Whether the screen point `p` is over a ruler, inside the full canvas rect `full`. A guide let go +/// there is removed, as in Photoshop, and either ruler removes it (#6286): the top ruler measures +/// document x and the left one y, so the ruler the guide was not dragged out of can lie over a +/// coordinate that is still inside the document on the guide's own axis. +pub(crate) fn dropped_on_a_ruler(app: &PhotocraftApp, full: Rect, p: Pos2) -> bool { + if !app.ui.extras.rulers { + return false; + } + // The rulers take the strips [`content_rect`] trims off the canvas rect, and nothing else: a + // canvas point on the boundary is canvas. + let content = content_rect(app, full); + full.contains(p) && (p.x < content.min.x || p.y < content.min.y) +} + +/// Tick step (document px) so major ticks are at least ~60 screen px apart: 1, 2, 5, 10, 20, 50… +#[cfg(test)] +fn tick_step(zoom: f32) -> f64 { + nice_step(60.0 / zoom.max(1e-4) as f64, true) +} + +/// Grid spacing in document pixels. Percentages use each axis's own extent. +pub(crate) fn grid_major_px(g: &GuidesGridAndSlices, dpi: f64, size: [f64; 2], ppi: f64) -> [f64; 2] { + size.map(|extent| g.major_px(dpi, extent, ppi)) +} + +/// View › Show › Grid, from Preferences › Guides, Grid & Slices (spacing, subdivisions, colour, +/// style). Photoshop's default is a gridline every inch with 4 subdivisions. +pub fn draw_grid(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform, doc: &Document) { + let g = &app.session.prefs().guides_grid_and_slices; + let ppi = app.session.prefs().units_and_rulers.point_size.per_inch(); + let (w, h) = (doc.size.width as f64, doc.size.height as f64); + let major = grid_major_px(g, doc.resolution_dpi.max(1.0) as f64, [w, h], ppi); + let minor = major.map(|step| step / g.subdivisions.max(1) as f64); + let base = pref_color(&g.grid_color, Color32::from_gray(140)); + for (steps, alpha) in [(minor, 0.45f32), (major, 1.0)] { + if alpha < 1.0 && g.subdivisions <= 1 { + continue; + } + let st = Stroke::new(1.0, base.gamma_multiply(alpha)); + let [step_x, step_y] = steps; + if step_x * (xf.zoom_x() as f64) >= 6.0 { + let mut x = step_x; + while x < w { + styled_line(painter, xf.to_screen(x as f32, 0.0), xf.to_screen(x as f32, h as f32), st, g.grid_style); + x += step_x; + } + } + if step_y * (xf.zoom as f64) >= 6.0 { + let mut y = step_y; + while y < h { + styled_line(painter, xf.to_screen(0.0, y as f32), xf.to_screen(w as f32, y as f32), st, g.grid_style); + y += step_y; + } + } + } +} + +/// Screen end points of a guide across `clip`: the document line x = `pos` (vertical) or +/// y = `pos`, spanning every document point the clip rect shows. Guides belong to the document, +/// so on a rotated view they turn with the image (#3277); unrotated this is the clip's full +/// height (or width). +fn guide_segment(xf: &ViewXform, clip: Rect, vertical: bool, pos: f64) -> [Pos2; 2] { + let axis = usize::from(vertical); + let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY); + for c in [clip.left_top(), clip.right_top(), clip.right_bottom(), clip.left_bottom()] { + let d = xf.to_doc(c)[axis]; + lo = lo.min(d); + hi = hi.max(d); + } + let (pos, lo, hi) = (pos as f32, lo as f32, hi as f32); + if vertical { [xf.to_screen(pos, lo), xf.to_screen(pos, hi)] } else { [xf.to_screen(lo, pos), xf.to_screen(hi, pos)] } +} + +/// The cursor over a guide: the arrow across it as the view shows it. A vertical guide moves left +/// and right in the document; a rotated view turns that, as it turns the guide (#3277). +pub fn guide_cursor(xf: &ViewXform, vertical: bool) -> egui::CursorIcon { + crate::tool_cursor::resize(if vertical { [1.0, 0.0] } else { [0.0, 1.0] }, xf) +} + +pub fn draw_guides(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform, doc: &Document) { + let clip = painter.clip_rect(); + let drag = app.guide_drag; + let g = &app.session.prefs().guides_grid_and_slices; + let preview = crate::guide_layout_ui::preview(app, doc); + let guides = preview.as_ref().map(|(guides, _)| guides).unwrap_or(&doc.guides); + let (guide, style) = + (preview.as_ref().map(|(_, color)| *color).unwrap_or_else(|| pref_color(&g.guide_color, Color32::from_rgb(74, 255, 255))), g.guide_style); + let line = |vertical: bool, pos: f64, color: Color32| { + let [a, b] = guide_segment(xf, clip, vertical, pos); + styled_line(painter, a, b, Stroke::new(1.0, color), style); + }; + // A guide given a colour in New Guide keeps it; the rest use the preference colour (or, while + // New Guide Layout previews, the colour it will set). The selected guide is Photoshop's blue. + let own = |vertical: bool, p: f64| { + if crate::guide_select::is_selected(app, vertical, p) { + return crate::guide_select::SELECTED_COLOR; + } + guides.color(vertical, p).map_or(guide, |[r, g, b]| Color32::from_rgb(r, g, b)) + }; + if app.ui.extras.guides || preview.is_some() { + for (vertical, list) in [(true, &guides.vertical), (false, &guides.horizontal)] { + for (i, p) in list.iter().enumerate() { + if drag.is_some_and(|d| d.vertical == vertical && d.index == Some(i)) { + continue; + } + line(vertical, *p, own(vertical, *p)); + } + } + } + if let Some(d) = drag { + // A guide being moved shows its own colour; a new one dragged from a ruler the preference's. + let list = if d.vertical { &doc.guides.vertical } else { &doc.guides.horizontal }; + line(d.vertical, d.pos, d.index.and_then(|i| list.get(i)).map_or(guide, |p| own(d.vertical, *p))); + } +} + +/// The position readout of a guide being dragged: `X:` for a vertical guide, `Y:` for a horizontal +/// one, measured from the ruler zero point in the ruler unit. Pixels keep one decimal, as +/// Photoshop's "X: 103.2 px". +pub fn guide_drag_readout(app: &PhotocraftApp, d: GuideDrag) -> Option<(&'static str, String)> { + let doc = &app.session.active()?.doc; + let ur = &app.session.prefs().units_and_rulers; + let axis = usize::from(!d.vertical); + let px = d.pos - doc.ruler_origin.get(axis).copied().unwrap_or(0.0); + let extent = if d.vertical { doc.size.width } else { doc.size.height } as f64; + let value = match ur.rulers { + Unit::Pixels => photocraft_engine::prefs::fmt_decimals(px, 1), + _ => ur.format(px, f64::from(doc.resolution_dpi), extent), + }; + Some((if d.vertical { "X:" } else { "Y:" }, format!("{value} {}", ur.rulers.suffix()))) +} + +/// Draw [`guide_drag_readout`] beside the pointer while a guide is dragged. +pub fn draw_guide_drag_readout(app: &PhotocraftApp, ctx: &egui::Context) { + let (Some(d), Some(at)) = (app.guide_drag, ctx.pointer_latest_pos()) else { return }; + if let Some((label, value)) = guide_drag_readout(app, d) { + crate::canvas::draw_value_readout(app, ctx, "guide-drag-readout", at, [label], [value]); + } +} + +/// Existing guide under a document point (within 4 screen px). +pub fn guide_at(app: &PhotocraftApp, x: f64, y: f64) -> Option<(bool, usize)> { + // Hidden canvas guides are not interactive: the Move tool must reach the layer below. + // Keep hit testing consistent with the visibility gate in canvas::draw. + if !app.ui.extras.guides || !app.ui.view.shows(app.ui.view.show.canvas_guides) || app.ui.extras.lock_guides { + return None; + } + let doc = &app.session.active()?.doc; + let tol = 4.0 / app.point_zoom().max(0.01) as f64; + for (i, g) in doc.guides.vertical.iter().enumerate() { + if (*g - x).abs() <= tol { + return Some((true, i)); + } + } + for (i, g) in doc.guides.horizontal.iter().enumerate() { + if (*g - y).abs() <= tol { + return Some((false, i)); + } + } + None +} + +/// Finish a guide drag: create, move, or delete (dropped outside the canvas or on a ruler). An +/// existing guide released where it was pressed is a click: it's selected and stays put, as in +/// Photoshop; a moved one stays selected. +pub fn finish_drag(app: &mut PhotocraftApp, d: GuideDrag) { + let Some(size) = app.session.active().map(|s| s.doc.size) else { return }; + // A drop on a ruler removes the guide even when the drag held its own axis, which otherwise + // reads as a click: dragged sideways onto the left ruler, a horizontal guide never moves in y. + if let Some(i) = d.index + && !d.over_ruler + && (d.pos - d.press).abs() * f64::from(app.point_zoom().max(0.01)) < 0.5 + { + crate::guide_select::select(app, d.vertical, i); + return; + } + let extent = if d.vertical { size.width } else { size.height } as f64; + let orientation = if d.vertical { "vertical" } else { "horizontal" }; + let inside = !d.over_ruler && d.pos >= 0.0 && d.pos <= extent; + let pos = (d.pos * 1000.0).round() / 1000.0; + let _ = match (d.index, inside) { + (None, true) => app.run("view.newGuide", json!({"orientation": orientation, "position": pos})), + (Some(i), true) => app + .run("view.moveGuide", json!({"orientation": orientation, "index": i, "position": pos})) + .inspect(|_| crate::guide_select::select(app, d.vertical, i)), + (Some(i), false) => app.run("view.deleteGuide", json!({"orientation": orientation, "index": i})), + (None, false) => Ok(serde_json::Value::Null), + }; + if d.index.is_none() && inside { + app.ui.extras.guides = true; + } +} + +/// The mapping the rulers measure with. Rulers are screen chrome that stays level while +/// View › Rotate View turns the canvas, so they use the view without its rotation: the same zoom, +/// flip and pixel aspect (ticks never stretch), anchored so that 0 sits at the screen position of +/// the document origin as the rotated view draws it, as in Photoshop. Tilted guides then meet the +/// rulers near their numbers. Measuring along the rotated axes instead squeezed the ticks into a +/// few pixels (or none at 90°) and left the rest of the ruler empty (#3233). +/// +/// The returned mapping measures from the rulers' zero point `zero` (document px, #2955): its +/// document coordinates are distances from `zero`, and 0 sits where the canvas draws `zero`. +fn ruler_xform(xf: &ViewXform, zero: [f64; 2]) -> ViewXform { + let level = ViewXform { rotation: 0.0, ..*xf }; + let (zx, zy) = (zero[0] as f32, zero[1] as f32); + // The level view is an axis-aligned scale, so moving the zero point by `shift` on screen moves + // every point by it: re-centre on the document point that sat `shift` before the centre, then + // count from the zero point. + let shift = xf.to_screen(zx, zy) - level.to_screen(zx, zy); + let center = level.to_doc(xf.rect.center() - shift); + let center = [center[0] as f32 - zx, center[1] as f32 - zy]; + if !(center[0].is_finite() && center[1].is_finite()) { + return level; + } + ViewXform { center, ..level } +} + +/// Visible ruler range in ruler units, normalised to `(min, max)` so the tick loop runs for +/// flipped views too (#1814), measured from the zero point `zero`. `xf` is the canvas mapping; +/// rotation is ignored (see [`ruler_xform`]). Shared by the renderer and its tests. +fn ruler_range(xf: &ViewXform, a: Pos2, b: Pos2, axis: usize, px_per_unit: f64, zero: [f64; 2]) -> (f64, f64) { + let rxf = ruler_xform(xf, zero); + let d0 = rxf.to_doc(a)[axis]; + let d1 = rxf.to_doc(b)[axis]; + let (u0, u1) = (d0 / px_per_unit, d1 / px_per_unit); + (u0.min(u1), u0.max(u1)) +} + +/// Snap a document position to the nearest ruler tick, measured from the zero point `origin` +/// (`tick` px apart). Shift-dragging the zero point lands it on a tick, as in Photoshop. +fn snap_px_to_tick(px: f64, origin: f64, tick: f64) -> f64 { + if !(tick.is_finite() && tick > 0.0) { + return px; + } + origin + ((px - origin) / tick).round() * tick +} + +/// Where a zero-point drag from the ruler corner lands for the pointer at document `d`: on the +/// nearest ruler tick (`ticks`, px per axis) with Shift, else View › Snap To targets. +fn origin_drop(app: &mut PhotocraftApp, d: [f64; 2], shift: bool, origin: [f64; 2], ticks: [f64; 2]) -> [f64; 2] { + if shift { + [snap_px_to_tick(d[0], origin[0], ticks[0]), snap_px_to_tick(d[1], origin[1], ticks[1])] + } else { + [crate::snap_ui::snap_guide(app, true, d[0]), crate::snap_ui::snap_guide(app, false, d[1])] + } +} + +/// Screen coordinate along the ruler (x for the top ruler, y for the left one) of the value `u` +/// in ruler units from the zero point `zero`. The inverse of [`ruler_range`]'s mapping. +fn ruler_pos(xf: &ViewXform, vertical: bool, u: f64, px_per_unit: f64, zero: [f64; 2]) -> f32 { + let px = (u * px_per_unit) as f32; + let rxf = ruler_xform(xf, zero); + if vertical { rxf.to_screen(0.0, px).y } else { rxf.to_screen(px, 0.0).x } +} + +/// Document pixels per ruler unit and the labelled tick step (in ruler units) of the top ruler +/// (`y_axis` false) or the left one, from Preferences › Units & Rulers and the zoom. Minor ticks +/// sit at tenths of the step. +fn ruler_scale(app: &PhotocraftApp, xf: &ViewXform, y_axis: bool) -> (f64, f64) { + ruler_scale_of(app, app.session.active().map(|d| &*d.doc), xf, y_axis) +} + +/// [`ruler_scale`] for the view of `doc`. +fn ruler_scale_of(app: &PhotocraftApp, doc: Option<&photocraft_doc::Document>, xf: &ViewXform, y_axis: bool) -> (f64, f64) { + let ur = &app.session.prefs().units_and_rulers; + let (unit, ppi) = (ur.rulers, ur.point_size.per_inch()); + let (dpi, size) = doc.map_or((72.0, [1.0, 1.0]), |d| (d.resolution_dpi.max(1.0) as f64, [d.size.width as f64, d.size.height as f64])); + let px_per_unit = unit.to_px(1.0, dpi, if y_axis { size[1] } else { size[0] }, ppi).max(1e-9); + // The top ruler runs along document x, which pixel aspect correction stretches. + let zoom = if y_axis { xf.zoom } else { xf.zoom_x() }; + (px_per_unit, nice_step(60.0 / (zoom as f64 * px_per_unit).max(1e-6), unit == Unit::Pixels)) +} + +/// `pos` (document px) moved to the nearest tick mark the ruler draws (counted from the zero point): where a guide lands when +/// Shift is held while dragging it out of a ruler, as in Photoshop (#3770). +fn snap_to_tick(app: &PhotocraftApp, xf: &ViewXform, vertical: bool, pos: f64) -> f64 { + // A vertical guide sits at an x position, which the top ruler measures. + let (px_per_unit, step) = ruler_scale(app, xf, !vertical); + // Ticks count from the zero point (#2955), which a vertical guide measures along x. + let origin = app.session.active().map_or(0.0, |d| d.doc.ruler_origin[usize::from(!vertical)]); + snap_px_to_tick(pos, origin, step / 10.0 * px_per_unit) +} + +/// The number a ruler prints at the tick `v` (in ruler units). Like Photoshop, rulers show the +/// distance from the origin, so values left of / above it read without a minus sign. +fn ruler_label(v: f64, step: f64, whole: bool) -> String { + let v = v.abs(); + if step >= 1.0 || whole { format!("{}", v.round() as i64) } else { crate::widgets::fmt_num2(v) } +} + +/// The rulers of `doc`'s view in `full`: background, ticks and labels from its zero point. +/// Returns the top, left and corner rects, the painter, the zero point and the minor tick sizes. +#[allow(clippy::type_complexity)] +fn paint( + app: &PhotocraftApp, + ui: &egui::Ui, + full: Rect, + xf: &ViewXform, + doc: &photocraft_doc::Document, +) -> (Rect, Rect, Rect, egui::Painter, [f64; 2], [f64; 2]) { + let t = Tokens::get(ui.ctx()); + let top = Rect::from_min_max(pos2(full.left() + RULER, full.top()), pos2(full.right(), full.top() + RULER)); + let left = Rect::from_min_max(pos2(full.left(), full.top() + RULER), pos2(full.left() + RULER, full.bottom())); + let corner = Rect::from_min_size(full.min, vec2(RULER, RULER)); + let p = ui.painter_at(full); + let bg = t.chrome; + for r in [top, left, corner] { + p.rect_filled(r, 0.0, bg); + } + p.line_segment([top.left_bottom(), top.right_bottom()], Stroke::new(1.0, t.separator)); + p.line_segment([left.right_top(), left.right_bottom()], Stroke::new(1.0, t.separator)); + let font = egui::FontId::proportional(9.0); + let tick = Stroke::new(1.0, t.text_faint); + // Preferences › Units & Rulers: labels in the ruler unit (percent of the document's side). + let unit = app.session.prefs().units_and_rulers.rulers; + let whole = unit == Unit::Pixels; + // The zero point (#2955): rulers read 0 there and count the distance from it. + let origin = doc.ruler_origin; + let mut ticks = [1.0; 2]; + for vertical in [false, true] { + let p = p.with_clip_rect(if vertical { left } else { top }); + let (px_per_unit, step) = ruler_scale_of(app, Some(doc), xf, vertical); + ticks[usize::from(vertical)] = step * px_per_unit / 10.0; + let (u0, u1) = if vertical { + ruler_range(xf, left.left_top(), left.left_bottom(), 1, px_per_unit, origin) + } else { + ruler_range(xf, top.left_top(), top.right_top(), 0, px_per_unit, origin) + }; + let mut v = (u0 / step).floor() * step; + while v <= u1 { + let at = |u: f64| -> f32 { ruler_pos(xf, vertical, u, px_per_unit, origin) }; + let c = at(v); + if vertical { + p.line_segment([pos2(left.right() - RULER, c), pos2(left.right(), c)], tick); + // Labels stacked, as in Photoshop, each character centred in the ruler's width + // (a narrow "1" used to hug the left edge while a "0" filled the strip). + for (i, ch) in ruler_label(v, step, whole).chars().enumerate() { + p.text(pos2(left.left() + RULER * 0.5, c + 2.0 + i as f32 * 8.5), Align2::CENTER_TOP, ch, font.clone(), t.text_dim); + } + } else { + p.line_segment([pos2(c, top.bottom() - RULER), pos2(c, top.bottom())], tick); + p.text(pos2(c + 2.0, top.top() + 1.0), Align2::LEFT_TOP, ruler_label(v, step, whole), font.clone(), t.text_dim); + } + for k in 1..10 { + let m = at(v + step * k as f64 / 10.0); + let len = if k == 5 { 6.0 } else { 3.0 }; + if vertical { + p.line_segment([pos2(left.right() - len, m), pos2(left.right(), m)], tick); + } else { + p.line_segment([pos2(m, top.bottom() - len), pos2(m, top.bottom())], tick); + } + } + v += step; + } + } + (top, left, corner, p, origin, ticks) +} + +/// Rulers for a document view that isn't the active one (another tile of Window › Arrange, a +/// floating window): shown as the active view's are, but guides and the zero point are dragged +/// in the active view (#6017). +pub fn paint_rulers(app: &PhotocraftApp, ui: &egui::Ui, full: Rect, xf: &ViewXform, doc: &photocraft_doc::Document) { + paint(app, ui, full, xf, doc); +} + +/// Rulers along the top and left of `full` (the canvas rect before `content_rect`), with the +/// pointer position marked; dragging out of a ruler creates a guide. +pub fn draw_rulers(app: &mut PhotocraftApp, ui: &mut egui::Ui, full: Rect, xf: &ViewXform) { + let Some(doc) = app.session.active().map(|d| d.doc.clone()) else { return }; + let (top, left, corner, p, origin, ticks) = paint(app, ui, full, xf, &doc); + let t = Tokens::get(ui.ctx()); + let unit = app.session.prefs().units_and_rulers.rulers; + // Pointer position markers. + if let Some(h) = ui.ctx().pointer_hover_pos().filter(|h| full.contains(*h)) { + let m = Stroke::new(1.0, t.text); + p.with_clip_rect(top).line_segment([pos2(h.x, top.top()), pos2(h.x, top.bottom())], m); + p.with_clip_rect(left).line_segment([pos2(left.left(), h.y), pos2(left.right(), h.y)], m); + } + // Drag a new guide out of a ruler; right-click to switch the ruler unit. + let mut chosen_unit: Option<&'static str> = None; + for (r, vertical, salt) in [(top, false, "ruler-top"), (left, true, "ruler-left"), (corner, false, "ruler-corner")] { + // Guides drag out of the top/left rulers and the zero point out of the corner; all three + // sense clicks so the right-click unit menu opens anywhere on the ruler. + let resp = ui.interact(r, ui.scope_id().with(salt), Sense::click_and_drag()); + if salt == "ruler-corner" { + corner_origin(app, ui, &resp, &p, xf, origin, ticks); + } else if resp.hovered() { + ui.ctx().set_cursor_icon(if vertical { egui::CursorIcon::ResizeHorizontal } else { egui::CursorIcon::ResizeVertical }); + } + if let Some(pos) = resp.interact_pointer_pos().filter(|_| salt != "ruler-corner" && (resp.dragged() || resp.drag_started())) { + // ⌥/Alt turns the guide the other way, as in Photoshop: a vertical guide out of the top + // ruler, a horizontal one out of the left (#5698), switching as Alt goes up and down. + let vertical = vertical != ui.input(|i| i.modifiers.alt); + let d = xf.to_doc(pos); + let along = if vertical { d[0] } else { d[1] }; + let pos = if ui.input(|i| i.modifiers.shift) { snap_to_tick(app, xf, vertical, along) } else { crate::snap_ui::snap_guide(app, vertical, along) }; + app.guide_drag = Some(GuideDrag { vertical, index: None, pos, press: pos, over_ruler: false }); + } + if resp.drag_stopped() + && let Some(mut d) = app.guide_drag.take() + { + // Let go over a ruler (the other one, say) the drag is discarded, not placed (#6286). + d.over_ruler = resp.interact_pointer_pos().is_some_and(|p| dropped_on_a_ruler(app, full, p)); + finish_drag(app, d); + } + resp.context_menu(|ui| { + if let Some(name) = unit_menu(ui, unit) { + chosen_unit = Some(name); + } + }); + } + if let Some(name) = chosen_unit { + let _ = app.run("prefs.set", json!({"path": "unitsAndRulers.rulers", "value": name})); + } + let _ = Pos2::ZERO; +} + +/// The ruler corner: drag the zero point out of it (cross hairs mark where it lands; Shift snaps +/// to the ruler ticks), double-click it to put the zero point back at the image's top-left. +fn corner_origin(app: &mut PhotocraftApp, ui: &egui::Ui, resp: &egui::Response, p: &egui::Painter, xf: &ViewXform, origin: [f64; 2], ticks: [f64; 2]) { + let id = resp.id.with("origin-drag"); + if resp.hovered() || resp.dragged() { + ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair); + } + if resp.double_clicked() { + let _ = app.run("view.resetRulerOrigin", json!({})); + return; + } + // Dropped back on the corner (or a slow click), the zero point stays where it was. + if let Some(pos) = resp.interact_pointer_pos().filter(|_| resp.dragged() || resp.drag_started()) { + if resp.rect.contains(pos) { + ui.data_mut(|d| d.remove_temp::<[f64; 2]>(id)); + return; + } + let shift = ui.input(|i| i.modifiers.shift); + let at = origin_drop(app, xf.to_doc(pos), shift, origin, ticks); + ui.data_mut(|d| d.insert_temp(id, at)); + // Cross hairs along the document axes through the new zero point, drawn like guides so + // they turn with a rotated view. + let t = Tokens::get(ui.ctx()); + for (vertical, pos) in [(true, at[0]), (false, at[1])] { + p.line_segment(guide_segment(xf, p.clip_rect(), vertical, pos), Stroke::new(1.0, t.text)); + } + } + if resp.drag_stopped() + && let Some(at) = ui.data_mut(|d| d.remove_temp::<[f64; 2]>(id)) + { + let round = |v: f64| (v * 1000.0).round() / 1000.0; + let _ = app.run("view.setRulerOrigin", json!({"x": round(at[0]), "y": round(at[1])})); + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/canvas/rulers/tests.rs b/crates/ui-egui/src/canvas/rulers/tests.rs new file mode 100644 index 0000000000..33684c9b7f --- /dev/null +++ b/crates/ui-egui/src/canvas/rulers/tests.rs @@ -0,0 +1,868 @@ +use super::*; + +#[test] +fn ruler_ticks_labels_and_pointer_stay_out_of_the_origin_corner() { + let mut failures = Vec::new(); + for theme in crate::theme::ThemeKind::ALL { + for (zoom, flip, rotation, width) in [(1.0, false, 0.0, 560.0), (1.0, false, 0.0, 800.0), (0.25, true, 0.0, 560.0), (2.0, false, 30.0, 560.0)] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 256, "height": 128})).unwrap(); + let full = Rect::from_min_size(pos2(32.0, 32.0), vec2(width - 80.0, 320.0)); + let corner = Rect::from_min_size(full.min, vec2(RULER, RULER)); + let builder = egui_kittest::Harness::builder().with_size(vec2(width, 400.0)); + let mut h = builder.build_ui_state( + move |ui, app| { + let rect = Rect::from_min_max(full.min + vec2(RULER, RULER), full.max); + let xf = ViewXform { rect, zoom, center: [(width - 80.0) / 2.0, 160.0], flip, rotation, aspect: 1.0 }; + draw_rulers(app, ui, full, &xf); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, theme); + h.event(egui::Event::PointerMoved(corner.center())); + h.run_steps(4); + let mut ticks = 0; + let mut labels = 0; + for shape in &h.output().shapes { + if matches!(shape.shape, egui::Shape::LineSegment { .. } | egui::Shape::Text(_)) { + ticks += usize::from(matches!(shape.shape, egui::Shape::LineSegment { .. })); + labels += usize::from(matches!(shape.shape, egui::Shape::Text(_))); + let visible = shape.shape.visual_bounding_rect().intersect(shape.clip_rect); + if visible.intersect(corner.shrink(0.5)).is_positive() { + failures.push(format!("{theme:?}: zoom={zoom}, flip={flip}, rotation={rotation}, {visible:?}")); + } + } + } + assert!(ticks > 2 && labels > 0, "rulers still draw ticks and labels"); + } + } + assert!(failures.is_empty(), "ruler drawing overlaps the origin corner: {failures:?}"); +} + +/// #7314: the stacked characters of the left ruler's labels are centred on the strip, so a +/// narrow "1" lines up with a wide "0". +#[test] +fn left_ruler_label_characters_are_centred() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 256, "height": 128})).unwrap(); + let (mut h, full, _) = ruler_harness(app); + h.run_steps(2); + let centres: Vec = h + .output() + .shapes + .iter() + .filter_map(|s| if let egui::Shape::Text(t) = &s.shape { Some(t) } else { None }) + .filter(|t| t.pos.x < full.min.x + RULER && t.pos.y > full.min.y + RULER) + .map(|t| t.pos.x + t.galley.size().x * 0.5) + .collect(); + assert!(centres.len() > 2, "the left ruler draws labels: {centres:?}"); + for c in ¢res { + assert!((c - (full.min.x + RULER * 0.5)).abs() < 0.01, "character centre {c} in {centres:?}"); + } +} + +#[test] +fn shift_snaps_the_zero_point_to_ruler_ticks_from_the_current_origin() { + assert_eq!(snap_px_to_tick(47.0, 0.0, 10.0), 50.0); + assert_eq!(snap_px_to_tick(44.9, 0.0, 10.0), 40.0); + // Ticks run from the current zero point, so they sit at 3 + 10k. + assert_eq!(snap_px_to_tick(47.0, 3.0, 10.0), 43.0); + assert_eq!(snap_px_to_tick(-8.0, 3.0, 10.0), -7.0); + // A degenerate tick never panics or moves the point. + for tick in [0.0, -1.0, f64::NAN, f64::INFINITY] { + assert_eq!(snap_px_to_tick(47.5, 3.0, tick), 47.5); + } +} + +/// Rulers alone in a 400×300 frame at 100 %, centred on a 256×128 document. +fn ruler_harness(app: PhotocraftApp) -> (egui_kittest::Harness<'static, PhotocraftApp>, Rect, ViewXform) { + let full = Rect::from_min_size(pos2(0.0, 0.0), vec2(400.0, 300.0)); + let rect = Rect::from_min_max(full.min + vec2(RULER, RULER), full.max); + let xf = ViewXform { rect, zoom: 1.0, center: [128.0, 64.0], flip: false, rotation: 0.0, aspect: 1.0 }; + let h = egui_kittest::Harness::builder() + .with_size(vec2(400.0, 300.0)) + .with_step_dt(1.0 / 60.0) + .build_ui_state(move |ui, app| draw_rulers(app, ui, full, &xf), app); + (h, full, xf) +} + +fn press(h: &mut egui_kittest::Harness<'static, PhotocraftApp>, pos: Pos2, pressed: bool, modifiers: egui::Modifiers) { + h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers }); + h.run_steps(2); +} + +fn drag_corner_to(h: &mut egui_kittest::Harness<'static, PhotocraftApp>, full: Rect, to: Pos2, modifiers: egui::Modifiers) { + let corner = Rect::from_min_size(full.min, vec2(RULER, RULER)).center(); + h.event(egui::Event::ModifiersChanged(modifiers)); + h.event(egui::Event::PointerMoved(corner)); + h.run_steps(1); + press(h, corner, true, modifiers); + for p in [corner + vec2(10.0, 10.0), to] { + h.event(egui::Event::PointerMoved(p)); + h.run_steps(2); + } + press(h, to, false, modifiers); + h.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE)); + h.run_steps(1); +} + +fn origin(h: &egui_kittest::Harness<'static, PhotocraftApp>) -> [f64; 2] { + h.state().session.active().unwrap().doc.ruler_origin +} + +/// #2955: dragging out of the ruler corner sets the zero point (cross hairs while dragging), +/// the rulers then read 0 there, Shift snaps it to a tick, and double-clicking the corner +/// resets it. +#[test] +fn dragging_the_ruler_corner_sets_the_zero_point_and_double_click_resets_it() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 256, "height": 128})).unwrap(); + app.ui.extras.snap = false; + let (mut h, full, xf) = ruler_harness(app); + h.run_steps(2); + let target = xf.to_screen(100.0, 40.0); + drag_corner_to(&mut h, full, target, egui::Modifiers::NONE); + let o = origin(&h); + assert!((o[0] - 100.0).abs() < 0.01 && (o[1] - 40.0).abs() < 0.01, "zero point lands under the pointer: {o:?}"); + // The top ruler's "0" now sits at the new zero point, "100" (a distance, unsigned as in + // Photoshop) at the image's left edge. + h.run_steps(2); + let labels: Vec<(String, f32)> = h + .output() + .shapes + .iter() + .filter_map(|s| if let egui::Shape::Text(t) = &s.shape { Some((t.galley.text().to_string(), t.pos.x)) } else { None }) + .collect(); + let near = |text: &str, x: f32| labels.iter().any(|(t, lx)| t == text && (lx - (x + 2.0)).abs() < 1.0); + assert!(near("0", target.x), "a 0 label at the zero point: {labels:?}"); + assert!(near("100", xf.to_screen(0.0, 0.0).x), "100 at the image's left edge: {labels:?}"); + + // Mid-drag, cross hairs run through the pointer across the canvas. + let corner = Rect::from_min_size(full.min, vec2(RULER, RULER)).center(); + let mid = xf.to_screen(150.0, 90.0); + press(&mut h, corner, true, egui::Modifiers::NONE); + for p in [corner + vec2(10.0, 10.0), mid] { + h.event(egui::Event::PointerMoved(p)); + h.run_steps(2); + } + let crosshair = h.output().shapes.iter().any(|s| { + matches!(s.shape, egui::Shape::LineSegment { points: [a, b], .. } if (a.x - mid.x).abs() < 0.5 && (b.x - mid.x).abs() < 0.5 && (b.y - a.y).abs() > 200.0) + }); + assert!(crosshair, "a vertical cross-hair line through the pointer while dragging"); + assert_eq!(origin(&h), o, "the zero point moves on release only"); + press(&mut h, mid, false, egui::Modifiers::NONE); + assert_eq!(origin(&h), [150.0, 90.0]); + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert_eq!(origin(&h), o, "setting the zero point is undoable"); + + // A drag dropped back on the corner leaves it alone. + drag_corner_to(&mut h, full, full.min + vec2(4.0, 4.0), egui::Modifiers::NONE); + assert_eq!(origin(&h), o); + + // Shift: ticks are 10 px apart at 100 %, measured from the current zero point (100, 40). + drag_corner_to(&mut h, full, xf.to_screen(123.0, 57.0), egui::Modifiers::SHIFT); + assert_eq!(origin(&h), [120.0, 60.0]); + + for _ in 0..40 { + h.step(); + } + let corner = Rect::from_min_size(full.min, vec2(RULER, RULER)).center(); + h.event(egui::Event::PointerMoved(corner)); + h.step(); + for _ in 0..2 { + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: corner, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }); + h.step(); + } + } + h.run_steps(2); + assert_eq!(origin(&h), [0.0, 0.0], "double-clicking the corner resets the zero point"); +} + +/// #2955: the Info panel's X/Y are measured from the rulers' zero point. +#[test] +fn info_panel_position_reads_from_the_zero_point() { + use egui_kittest::kittest::Queryable; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run("view.setRulerOrigin", json!({"x": 20, "y": 5})).unwrap(); + app.hover_doc = Some([50.5, 20.5]); + let mut h = egui_kittest::Harness::builder() + .with_size(vec2(260.0, 240.0)) + .build_ui_state(|ui, app| crate::panels::dock_body(app, ui, crate::dock::Group::Navigator, 2), app); + h.run_steps(2); + assert!(h.query_by_label("30").is_some() && h.query_by_label("15").is_some(), "X 30, Y 15 from the zero point at (20, 5)"); + assert!(h.query_by_label("50").is_none(), "not the raw image x"); +} + +/// #5728: dragging a guide shows its coordinate in the Info panel on one axis only. +#[test] +fn info_panel_shows_guide_drag_position_outside_canvas() { + use egui_kittest::kittest::Queryable; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.hover_doc = None; + app.guide_drag = Some(GuideDrag { vertical: true, index: None, pos: 42.0, press: 42.0, over_ruler: false }); + let mut h = egui_kittest::Harness::builder() + .with_size(vec2(260.0, 240.0)) + .build_ui_state(|ui, app| crate::panels::dock_body(app, ui, crate::dock::Group::Navigator, 2), app); + h.run_steps(2); + assert!(h.query_by_label("42").is_some(), "vertical guide: X readout"); + h.state_mut().guide_drag = Some(GuideDrag { vertical: false, index: None, pos: 17.0, press: 17.0, over_ruler: false }); + h.run_steps(2); + assert!(h.query_by_label("17").is_some(), "horizontal guide: Y readout"); +} + +/// A dragged guide shows its position beside the pointer: X for a vertical guide, Y for a +/// horizontal one, from the zero point, in the ruler unit (pixels to one decimal). +#[test] +fn guide_drag_shows_its_position_beside_the_pointer() { + use egui_kittest::kittest::Queryable; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let v = GuideDrag { vertical: true, index: Some(0), pos: 103.24, press: 50.0, over_ruler: false }; + assert_eq!(guide_drag_readout(&app, v), Some(("X:", "103.2 px".to_owned()))); + let h = GuideDrag { vertical: false, index: None, pos: 40.0, press: 40.0, over_ruler: false }; + assert_eq!(guide_drag_readout(&app, h), Some(("Y:", "40 px".to_owned()))); + app.run("view.setRulerOrigin", json!({"x": 3.0, "y": 10.0})).unwrap(); + assert_eq!(guide_drag_readout(&app, h), Some(("Y:", "30 px".to_owned())), "from the zero point"); + app.run("view.resetRulerOrigin", json!({})).unwrap(); + app.run("prefs.set", json!({"path": "unitsAndRulers.rulers", "value": "percent"})).unwrap(); + assert_eq!(guide_drag_readout(&app, GuideDrag { vertical: true, index: None, pos: 103.0, press: 0.0, over_ruler: false }).map(|r| r.0), Some("X:")); + app.run("prefs.set", json!({"path": "unitsAndRulers.rulers", "value": "pixels"})).unwrap(); + + app.guide_drag = Some(v); + let mut h = egui_kittest::Harness::builder().with_size(vec2(300.0, 200.0)).build_ui_state(|ui, app| draw_guide_drag_readout(app, ui.ctx()), app); + h.event(egui::Event::PointerMoved(pos2(50.0, 50.0))); + h.run_steps(2); + assert!(h.query_by_label("X:").is_some() && h.query_by_label("103.2 px").is_some()); + h.state_mut().guide_drag = None; + h.run_steps(2); + assert!(h.query_by_label("X:").is_none(), "no readout once the drag ends"); +} + +type AppHarness = egui_kittest::Harness<'static, PhotocraftApp>; + +/// The real canvas on a 400 × 300 document with a horizontal guide at y = 100, at 100 %, +/// with the Move tool and snapping off. +fn canvas_harness(rulers: bool) -> AppHarness { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("view.newGuide", json!({"orientation": "horizontal", "position": 100})).unwrap(); + app.sync_views(); + app.ui.extras.rulers = rulers; + app.ui.extras.snap = false; + app.ui.tool = crate::state::Tool::Move; + let mut h = egui_kittest::Harness::builder().with_size(vec2(800.0, 600.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(4); + let v = &mut h.state_mut().ui.views[0]; + (v.zoom, v.center, v.fit_pending) = (1.0, [200.0, 150.0], false); + h.run_steps(2); + h +} + +/// Screen point of document point `(x, y)` in [`canvas_harness`]. +fn canvas_at(h: &AppHarness, x: f32, y: f32) -> Pos2 { + let app = h.state(); + let v = &app.ui.views[0]; + let rect = content_rect(app, app.last_canvas_rect); + ViewXform { rect, zoom: v.zoom, center: v.center, flip: false, rotation: 0.0, aspect: 1.0 }.to_screen(x, y) +} + +/// Moving a horizontal guide with the Move tool on the real canvas: `Y:` follows the pointer. +#[test] +fn moving_a_guide_on_the_canvas_shows_its_y() { + use egui_kittest::kittest::Queryable; + let mut h = canvas_harness(false); + let at = canvas_at; + let press = at(&h, 200.0, 100.0); + h.event(egui::Event::PointerMoved(press)); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: press, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); + h.run_steps(1); + for y in [110.0, 125.0, 140.0] { + h.event(egui::Event::PointerMoved(at(&h, 210.0, y))); + h.run_steps(2); + } + assert!(h.state().guide_drag.is_some_and(|d| !d.vertical), "a horizontal guide is being dragged"); + assert!(h.query_by_label("Y:").is_some() && h.query_by_label("140 px").is_some(), "Y readout at the guide"); + assert!(h.query_by_label("X:").is_none()); + let up = at(&h, 210.0, 140.0); + h.event(egui::Event::PointerButton { pos: up, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); + h.run_steps(2); + assert_eq!(h.state().session.active().unwrap().doc.guides.horizontal, vec![140.0]); + assert!(h.query_by_label("Y:").is_none(), "gone after the drop"); +} + +/// A guide dragged out of the top ruler: in each frame the readout shows where the guide is +/// after that frame's pointer move (the ruler handles the drag after the canvas is drawn), and +/// the frame that drops it shows none. +#[test] +fn ruler_drag_readout_is_current_every_frame() { + use egui_kittest::kittest::Queryable; + let mut h = canvas_harness(true); + let from = pos2(canvas_at(&h, 200.0, 0.0).x, h.state().last_canvas_rect.top() + RULER / 2.0); + h.event(egui::Event::PointerMoved(from)); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); + h.run_steps(1); + for y in [40.0, 60.0, 75.0] { + h.event(egui::Event::PointerMoved(canvas_at(&h, 200.0, y))); + // egui 0.37 lays an Area's contents out a pass after it is shown; step to the settled + // frame with the pointer still at `y` (readout included) rather than the first pass. + h.run_steps(2); + let pos = h.state().guide_drag.map(|d| d.pos); + assert_eq!(pos, Some(f64::from(y)), "the drag follows the pointer"); + assert!(h.query_by_label(&format!("{y} px")).is_some(), "readout at {y} in the same frame"); + } + let up = canvas_at(&h, 200.0, 75.0); + h.event(egui::Event::PointerButton { pos: up, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); + h.run_steps(2); + assert!(h.state().guide_drag.is_none()); + assert!(h.query_by_label("Y:").is_none(), "no readout in the frame that drops the guide"); + assert!(h.state().session.active().unwrap().doc.guides.horizontal.contains(&75.0), "the guide lands at y = 75"); +} + +#[test] +fn percentage_grid_spacing_uses_both_canvas_dimensions() { + let mut g = GuidesGridAndSlices { grid_unit: Unit::Percent, gridline_every: 20.0, subdivisions: 2, ..Default::default() }; + assert_eq!(grid_major_px(&g, 72.0, [1280.0, 720.0], 72.0), [256.0, 144.0]); + // Absolute units remain equal on both axes, irrespective of aspect ratio. + g.grid_unit = Unit::Pixels; + g.gridline_every = 100.0; + assert_eq!(grid_major_px(&g, 72.0, [1280.0, 720.0], 72.0), [100.0, 100.0]); +} + +#[test] +fn unit_steps_allow_fractions() { + assert_eq!(nice_step(0.3, false), 0.5); + assert_eq!(nice_step(0.2, false), 0.2); + assert_eq!(nice_step(0.22, false), 0.25); + assert_eq!(nice_step(0.3, true), 1.0); + assert_eq!(nice_step(23.0, true), 50.0); +} + +#[test] +fn ticks_follow_1_2_5_series() { + assert_eq!(tick_step(1.0), 100.0); + assert_eq!(tick_step(0.1), 1000.0); + assert_eq!(tick_step(4.0), 20.0); + assert_eq!(tick_step(64.0), 1.0); + assert_eq!(tick_step(0.25), 500.0); +} + +#[test] +fn hidden_guides_are_not_hit_tested() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.sync_views(); + app.session.execute("view.newGuide", json!({"orientation": "vertical", "position": 50})).unwrap(); + app.session.execute("view.newGuide", json!({"orientation": "horizontal", "position": 25})).unwrap(); + let positions = app.session.active().unwrap().doc.guides.clone(); + + // Visible, unlocked guides remain interactive in either orientation. + assert_eq!(guide_at(&app, 50.0, 10.0), Some((true, 0))); + assert_eq!(guide_at(&app, 10.0, 25.0), Some((false, 0))); + + // All ways to hide the canvas guides must also disable hit testing. + app.ui.extras.guides = false; + assert_eq!(guide_at(&app, 50.0, 10.0), None); + assert_eq!(guide_at(&app, 10.0, 25.0), None); + app.ui.extras.guides = true; + + app.ui.view.show.canvas_guides = false; + assert_eq!(guide_at(&app, 50.0, 10.0), None); + assert_eq!(guide_at(&app, 10.0, 25.0), None); + app.ui.view.show.canvas_guides = true; + + app.ui.view.extras = false; + assert_eq!(guide_at(&app, 50.0, 10.0), None); + assert_eq!(guide_at(&app, 10.0, 25.0), None); + app.ui.view.extras = true; + + // Hiding/showing must not change the stored guide positions. + assert_eq!(app.session.active().unwrap().doc.guides, positions); + assert_eq!(guide_at(&app, 50.0, 10.0), Some((true, 0))); + assert_eq!(guide_at(&app, 10.0, 25.0), Some((false, 0))); + + app.ui.extras.lock_guides = true; + assert_eq!(guide_at(&app, 50.0, 10.0), None); + assert_eq!(guide_at(&app, 10.0, 25.0), None); +} + +#[test] +fn unit_menu_lists_every_unit_with_the_current_one_checked() { + let items = unit_menu_items(Unit::Inches, &UNITS); + assert_eq!(items.len(), Unit::NAMES.len()); + // Every unit is offered, labelled, and in the preference's order. + assert_eq!(items[0], ("Pixels".to_string(), "pixels", false)); + assert_eq!(items.iter().find(|(_, name, _)| *name == "cm").unwrap().0, "Centimeters"); + // Exactly the current unit is checked. + let checked: Vec<_> = items.iter().filter(|(_, _, c)| *c).map(|(_, name, _)| *name).collect(); + assert_eq!(checked, vec!["inches"]); +} + +#[test] +fn picking_a_ruler_unit_changes_the_preference() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + assert_eq!(app.session.prefs().units_and_rulers.rulers, Unit::Pixels); + // The context menu applies its pick exactly as the preference pane does. + app.run("prefs.set", json!({"path": "unitsAndRulers.rulers", "value": "cm"})).unwrap(); + assert_eq!(app.session.prefs().units_and_rulers.rulers, Unit::Centimeters); +} + +/// View › Rulers is remembered: the next launch, and every document created or opened in it, +/// shows the rulers as last set, on or off (#2918). +#[test] +fn rulers_open_as_last_set_after_a_restart() { + use std::{cell::RefCell, rc::Rc}; + let saved = Rc::new(RefCell::new(None::)); + let launch = |saved: &Rc>>| { + let (load, store) = (saved.clone(), saved.clone()); + PhotocraftApp::new( + photocraft_engine::Session::new(), + crate::Services { + load_prefs: Some(Box::new(move || load.borrow().clone())), + save_prefs: Some(Box::new(move |text| { + *store.borrow_mut() = Some(text.to_string()); + Ok(()) + })), + ..Default::default() + }, + ) + }; + for on in [true, false] { + let mut app = launch(&saved); + assert_eq!(crate::menus::invoke(&mut app, &egui::Context::default(), "view.rulers", json!({})).unwrap(), json!(on)); + crate::prefs_ui::save_preferences(&mut app).unwrap(); + let mut next = launch(&saved); + next.session.execute("file.new", json!({"width": 20, "height": 10})).unwrap(); + next.sync_views(); + assert_eq!(next.ui.extras.rulers, on, "a new document after a restart shows the rulers as last set"); + } +} + +#[test] +fn guide_drags_create_move_and_delete() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.sync_views(); + finish_drag(&mut app, GuideDrag { vertical: true, index: None, pos: 50.0, press: 50.0, over_ruler: false }); + finish_drag(&mut app, GuideDrag { vertical: false, index: None, pos: 500.0, press: 500.0, over_ruler: false }); // off canvas: ignored + assert_eq!(app.session.active().unwrap().doc.guides.vertical, vec![50.0]); + assert!(app.session.active().unwrap().doc.guides.horizontal.is_empty()); + assert_eq!(guide_at(&app, 51.0, 10.0), Some((true, 0))); + finish_drag(&mut app, GuideDrag { vertical: true, index: Some(0), pos: 120.0, press: 50.0, over_ruler: false }); + assert_eq!(app.session.active().unwrap().doc.guides.vertical, vec![120.0]); + finish_drag(&mut app, GuideDrag { vertical: true, index: Some(0), pos: -30.0, press: 120.0, over_ruler: false }); + assert!(app.session.active().unwrap().doc.guides.vertical.is_empty()); + app.ui.extras.lock_guides = true; + assert_eq!(guide_at(&app, 0.0, 0.0), None); +} + +/// ⌘ is the Move tool with any tool, so a ⌘-drag over a guide moves the guide, never the layer +/// (#2690); with Lock Guides a ⌘-drag with a marquee moves the layer as before. +#[test] +fn command_drag_over_a_guide_moves_the_guide_with_any_tool() { + use crate::canvas::{ToolEvent, tool_event}; + use crate::state::Tool; + for (tool, locked) in [ + (Tool::Brush, false), + (Tool::Eraser, false), + (Tool::Gradient, false), + (Tool::Frame, false), + (Tool::Artboard, false), + (Tool::RectMarquee, false), + (Tool::Lasso, false), + (Tool::MagicWand, false), + (Tool::RectMarquee, true), + ] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 80, "height": 60, "background": "transparent"})).unwrap(); + app.sync_views(); + app.ui.tool = tool; + app.ui.extras.lock_guides = locked; + let layer = app.session.active().unwrap().active_layer.unwrap(); + app.session + .edit("paint", |doc, _| { + doc.layer_mut(layer).unwrap().surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(10, 10, 30, 30), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + app.run("view.newGuide", json!({"orientation": "vertical", "position": 50})).unwrap(); + let cmd = egui::Modifiers::COMMAND; + tool_event(&mut app, ToolEvent::Down { x: 50.0, y: 40.0, pressure: 1.0 }, cmd); + tool_event(&mut app, ToolEvent::Move { x: 65.0, y: 40.0, pressure: 1.0 }, cmd); + tool_event(&mut app, ToolEvent::Up { x: 65.0, y: 40.0 }, cmd); + let doc = &app.session.active().unwrap().doc; + let moved = doc.layer(layer).unwrap().surface().unwrap().rgba(12, 12)[3] == 0.0; + if locked { + assert_eq!((doc.guides.vertical.clone(), moved), (vec![50.0], true), "{tool:?}, guides locked: the layer moves"); + } else { + assert_eq!((doc.guides.vertical.clone(), moved), (vec![65.0], false), "{tool:?}: the guide moves, the layer stays"); + } + } +} + +/// #3233: a rotated view keeps the rulers level and fully ticked at zoom scale. The top ruler +/// spans the same number of document pixels as the unrotated view, the ticks map back onto +/// its ends, and both rulers read 0 at the screen position of the (rotated) document origin, +/// as Photoshop does. +#[test] +fn rotated_view_keeps_full_rulers() { + let rect = Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0)); + let (a, b) = (rect.left_top(), rect.right_top()); + for rotation in [0.0f32, 30.0, 45.0, 90.0, -119.0, 180.0] { + for flip in [false, true] { + let xf = ViewXform { rect, zoom: 0.5, center: [1000.0, 700.0], flip, rotation, aspect: 1.0 }; + let (u0, u1) = ruler_range(&xf, a, b, 0, 1.0, [0.0; 2]); + assert!((u1 - u0 - 1600.0).abs() < 1e-2, "rotation {rotation}: top ruler covers {u0}..{u1}"); + let (first, last) = if flip { (u1, u0) } else { (u0, u1) }; + assert!((ruler_pos(&xf, false, first, 1.0, [0.0; 2]) - a.x).abs() < 1e-2, "rotation {rotation}: first tick"); + assert!((ruler_pos(&xf, false, last, 1.0, [0.0; 2]) - b.x).abs() < 1e-2, "rotation {rotation}: last tick"); + // 0 at the projected origin, 500 document px = 500 × zoom screen px further on. + let origin = xf.to_screen(0.0, 0.0); + assert!((ruler_pos(&xf, false, 0.0, 1.0, [0.0; 2]) - origin.x).abs() < 1e-2, "rotation {rotation}: top ruler 0"); + assert!((ruler_pos(&xf, true, 0.0, 1.0, [0.0; 2]) - origin.y).abs() < 1e-2, "rotation {rotation}: left ruler 0"); + let dir = if flip { -1.0 } else { 1.0 }; + assert!((ruler_pos(&xf, false, 500.0, 1.0, [0.0; 2]) - origin.x - dir * 250.0).abs() < 1e-2, "rotation {rotation}: top scale"); + assert!((ruler_pos(&xf, true, 500.0, 1.0, [0.0; 2]) - origin.y - 250.0).abs() < 1e-2, "rotation {rotation}: left scale"); + } + } + // Distances left of / above the origin read without a minus sign, as in Photoshop. + let xf = ViewXform { rect, zoom: 0.5, center: [0.0, 0.0], flip: false, rotation: 0.0, aspect: 1.0 }; + let (u0, u1) = ruler_range(&xf, a, b, 0, 1.0, [0.0; 2]); + assert!(u0 < -500.0 && u1 > 500.0, "the view spans the origin: {u0}..{u1}"); + for (step, whole) in [(100.0, true), (100.0, false), (0.25, false)] { + let mut v = (u0 / step).floor() * step; + while v <= u1 { + let s = ruler_label(v, step, whole); + assert!(!s.contains('-'), "tick {v} (step {step}) is labelled {s:?}"); + v += step; + } + } + assert_eq!(ruler_label(-500.0, 100.0, true), "500"); + assert_eq!(ruler_label(-0.25, 0.25, false), "0.25"); +} + +/// #2955 with #3233: a zero point moved off the image's top-left reads 0 where the canvas draws +/// it, also on a rotated or flipped view, and the ruler keeps its full length and scale. +#[test] +fn rulers_count_from_the_zero_point_on_a_rotated_view() { + let rect = Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0)); + let (a, b) = (rect.left_top(), rect.right_top()); + let zero = [300.0, 120.0]; + for rotation in [0.0f32, 30.0, 90.0, -119.0] { + for flip in [false, true] { + let xf = ViewXform { rect, zoom: 0.5, center: [1000.0, 700.0], flip, rotation, aspect: 1.0 }; + let at = xf.to_screen(zero[0] as f32, zero[1] as f32); + assert!((ruler_pos(&xf, false, 0.0, 1.0, zero) - at.x).abs() < 1e-2, "rotation {rotation}: top ruler 0"); + assert!((ruler_pos(&xf, true, 0.0, 1.0, zero) - at.y).abs() < 1e-2, "rotation {rotation}: left ruler 0"); + let (u0, u1) = ruler_range(&xf, a, b, 0, 1.0, zero); + assert!((u1 - u0 - 1600.0).abs() < 1e-2, "rotation {rotation}: top ruler covers {u0}..{u1}"); + let dir = if flip { -1.0 } else { 1.0 }; + assert!((ruler_pos(&xf, false, 500.0, 1.0, zero) - at.x - dir * 250.0).abs() < 1e-2, "rotation {rotation}: top scale"); + } + } + // Unrotated, ruler value u sits over document x = zero + u. + let xf = ViewXform { rect, zoom: 0.5, center: [1000.0, 700.0], flip: false, rotation: 0.0, aspect: 1.0 }; + assert!((ruler_pos(&xf, false, -300.0, 1.0, zero) - xf.to_screen(0.0, 0.0).x).abs() < 1e-2); + assert!((ruler_pos(&xf, true, 80.0, 1.0, zero) - xf.to_screen(0.0, 200.0).y).abs() < 1e-2); +} + +/// #3277: guides belong to the document, so a rotated view draws them along the document +/// line; unrotated they still span the whole clip rect. +#[test] +fn guides_turn_with_a_rotated_view() { + let rect = Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0)); + let level = ViewXform { rect, zoom: 0.5, center: [1000.0, 700.0], flip: false, rotation: 0.0, aspect: 1.0 }; + let [a, b] = guide_segment(&level, rect, true, 500.0); + assert!((a.x - b.x).abs() < 1e-3 && (a.y - rect.top()).abs() < 1e-3 && (b.y - rect.bottom()).abs() < 1e-3, "{a:?} {b:?}"); + for rotation in [30.0f32, 90.0, -119.0] { + let xf = ViewXform { rotation, ..level }; + for (vertical, pos) in [(true, 500.0), (false, 900.0)] { + for end in guide_segment(&xf, rect, vertical, pos) { + let d = xf.to_doc(end); + let on_line = if vertical { d[0] } else { d[1] }; + assert!((on_line - pos).abs() < 1e-2, "rotation {rotation}: {end:?} maps to {d:?}, off the guide at {pos}"); + } + } + } +} + +/// The cursor over a guide turns with the view as the guide does: on a view turned 90°, a +/// vertical guide shows as a horizontal line and moves up and down. +#[test] +fn guide_cursors_turn_with_a_rotated_view() { + use egui::CursorIcon::{ResizeHorizontal as H, ResizeNeSw as NeSw, ResizeNwSe as NwSe, ResizeVertical as V}; + let rect = Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0)); + let level = ViewXform { rect, zoom: 1.0, center: [400.0, 300.0], flip: false, rotation: 0.0, aspect: 1.0 }; + // View rotation, flip → the cursor over a vertical guide, over a horizontal guide. + for (rotation, flip, want) in [(0.0, false, [H, V]), (90.0, false, [V, H]), (45.0, false, [NwSe, NeSw]), (0.0, true, [H, V])] { + let xf = ViewXform { rotation, flip, ..level }; + assert_eq!([guide_cursor(&xf, true), guide_cursor(&xf, false)], want, "view turned {rotation}°, flip {flip}"); + } +} + +#[test] +fn ruler_range_is_normalised_when_flipped() { + // #1814: with View > Flip Horizontal, `to_doc` negates x, so the raw + // (d0, d1) comes out reversed. ruler_range must normalise to (min, max) + // so the tick loop still runs. Exercises the production helper. + let rect = Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0)); + let top = Rect::from_min_size(rect.min, vec2(rect.width(), RULER)); + for flip in [false, true] { + let xf = ViewXform { rect, zoom: 1.0, center: [400.0, 300.0], flip, rotation: 0.0, aspect: 1.0 }; + let (u0, u1) = ruler_range(&xf, top.left_top(), top.right_top(), 0, 1.0, [0.0; 2]); + assert!(u0 <= u1, "flip={flip}: u0 ({u0}) must be <= u1 ({u1})"); + assert!(u1 - u0 > 0.0, "flip={flip}: range is empty"); + } +} + +/// #5698: as in Photoshop, an Alt-drag out of the top ruler makes a vertical guide and one out +/// of the left ruler a horizontal guide; without Alt each ruler makes its own kind. +#[test] +fn alt_drags_a_guide_of_the_other_orientation_out_of_a_ruler() { + let full = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)); + let rect = Rect::from_min_max(full.min + vec2(RULER, RULER), full.max); + let xf = ViewXform { rect, zoom: 1.0, center: [128.0, 64.0], flip: false, rotation: 0.0, aspect: 1.0 }; + let drag = |from: Pos2, modifiers: egui::Modifiers| { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 256, "height": 128})).unwrap(); + let mut h = egui_kittest::Harness::builder().with_size(vec2(400.0, 300.0)).build_ui_state(move |ui, app| draw_rulers(app, ui, full, &xf), app); + let to = xf.to_screen(37.0, 90.0); + h.event_modifiers(egui::Event::PointerMoved(from), modifiers); + h.event_modifiers(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers }, modifiers); + h.run_steps(1); + h.event_modifiers(egui::Event::PointerMoved(to), modifiers); + h.run_steps(1); + h.event_modifiers(egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers }, modifiers); + h.run_steps(2); + let g = &h.state().session.active().unwrap().doc.guides; + (g.vertical.clone(), g.horizontal.clone()) + }; + let (top, left) = (pos2(200.0, RULER / 2.0), pos2(RULER / 2.0, 150.0)); + assert_eq!(drag(top, egui::Modifiers::NONE), (vec![], vec![90.0]), "top ruler: horizontal"); + assert_eq!(drag(left, egui::Modifiers::NONE), (vec![37.0], vec![]), "left ruler: vertical"); + assert_eq!(drag(top, egui::Modifiers::ALT), (vec![37.0], vec![]), "Alt from the top ruler: vertical"); + assert_eq!(drag(left, egui::Modifiers::ALT), (vec![], vec![90.0]), "Alt from the left ruler: horizontal"); +} + +/// #6286: a guide let go over a ruler is removed, whichever ruler it is. The top ruler measures +/// document x and the left one y, so a horizontal guide released on the left ruler is still +/// inside the document on its own axis, and used to be placed instead of discarded. +#[test] +fn a_guide_dropped_on_either_ruler_is_removed() { + let new_app = || { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 256, "height": 128})).unwrap(); + app.ui.extras.rulers = true; + // No snapping, so a guide that is kept lands exactly where it is let go. + app.ui.extras.snap = false; + app + }; + let drag = |from: Pos2, to: Pos2| { + let (mut h, _, _) = ruler_harness(new_app()); + h.event(egui::Event::PointerMoved(from)); + press(&mut h, from, true, egui::Modifiers::NONE); + h.event(egui::Event::PointerMoved(to)); + h.run_steps(1); + press(&mut h, to, false, egui::Modifiers::NONE); + let g = &h.state().session.active().unwrap().doc.guides; + (g.vertical.clone(), g.horizontal.clone()) + }; + // #5698: out of the top ruler is a horizontal guide, out of the left one a vertical guide. + let (top, left) = (pos2(200.0, RULER / 2.0), pos2(RULER / 2.0, 150.0)); + assert_eq!(drag(top, left), (vec![], vec![]), "out of the top ruler, released on the left ruler"); + assert_eq!(drag(left, top), (vec![], vec![]), "out of the left ruler, released on the top ruler"); + // Released on the canvas the guide lands where it was let go, as before. + assert_eq!(drag(top, pos2(200.0, 150.0)), (vec![], vec![56.0]), "released on the canvas"); + assert_eq!(drag(left, pos2(120.0, 150.0)), (vec![40.0], vec![]), "released on the canvas"); +} + +/// #6286: the guide is removed when it is let go over a ruler, and moved when it is not. The +/// release can be inside the document on the guide's own axis and still be a ruler drop, so the +/// two are told apart by where the pointer is, not by the position it reads. +#[test] +fn a_guide_let_go_on_a_ruler_is_removed_not_moved() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.sync_views(); + let horizontal = |app: &PhotocraftApp| app.session.active().unwrap().doc.guides.horizontal.clone(); + for drag in [ + GuideDrag { vertical: false, index: Some(0), pos: 50.0, press: 10.0, over_ruler: true }, + // Dragged sideways onto the left ruler, a horizontal guide holds its y, which on its own + // reads as a click: the ruler still removes it. + GuideDrag { vertical: false, index: Some(0), pos: 50.0, press: 50.0, over_ruler: true }, + ] { + app.run("view.newGuide", json!({"orientation": "horizontal", "position": 50})).unwrap(); + finish_drag(&mut app, drag); + assert!(horizontal(&app).is_empty(), "let go on a ruler: removed, {drag:?}"); + } + app.run("view.newGuide", json!({"orientation": "horizontal", "position": 50})).unwrap(); + finish_drag(&mut app, GuideDrag { vertical: false, index: Some(0), pos: 80.0, press: 10.0, over_ruler: false }); + assert_eq!(horizontal(&app), vec![80.0], "let go on the canvas: moved"); + // Clicked where it was pressed, on the canvas: selected and kept, as before. + finish_drag(&mut app, GuideDrag { vertical: false, index: Some(0), pos: 80.0, press: 80.0, over_ruler: false }); + assert_eq!(horizontal(&app), vec![80.0], "clicked on the canvas: kept"); + assert!(app.ui.selected_guide.is_some(), "clicked on the canvas: selected"); +} + +/// The ruler bands are the strips the rulers take off the canvas rect, and only while the rulers +/// are shown: with them hidden the whole canvas rect is canvas (#6286). +#[test] +fn only_the_ruler_bands_count_as_a_ruler() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let full = Rect::from_min_size(pos2(16.0, 42.0), vec2(968.0, 642.0)); + let content = Rect::from_min_size(pos2(32.0, 58.0), vec2(952.0, 626.0)); + app.ui.extras.rulers = true; + assert!(dropped_on_a_ruler(&app, full, pos2(full.min.x + RULER / 2.0, 371.0)), "the left ruler"); + assert!(dropped_on_a_ruler(&app, full, pos2(508.0, full.min.y + RULER / 2.0)), "the top ruler"); + assert!(dropped_on_a_ruler(&app, full, full.min), "the ruler corner"); + assert!(!dropped_on_a_ruler(&app, full, pos2(508.0, 371.0)), "the canvas"); + assert!(!dropped_on_a_ruler(&app, full, content.min), "the canvas' own top-left corner"); + assert!(!dropped_on_a_ruler(&app, full, pos2(content.min.x + 0.5, 371.0)), "the first canvas column"); + assert!(!dropped_on_a_ruler(&app, full, pos2(508.0, content.min.y + 0.5)), "the first canvas row"); + assert!(!dropped_on_a_ruler(&app, full, pos2(full.min.x - 1.0, 371.0)), "outside the canvas rect"); + app.ui.extras.rulers = false; + for p in [pos2(full.min.x + RULER / 2.0, 371.0), pos2(508.0, full.min.y + RULER / 2.0), full.min] { + assert!(!dropped_on_a_ruler(&app, full, p), "rulers hidden: no band at {p:?}"); + } +} + +/// The canvas the guides live on, rulers on, at 100 %. +fn tool_canvas_harness(tool: crate::state::Tool) -> egui_kittest::Harness<'static, PhotocraftApp> { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.sync_views(); + app.ui.extras.rulers = true; + app.ui.extras.snap = false; + app.ui.tool = tool; + let mut h = egui_kittest::Harness::builder().with_size(vec2(1000.0, 700.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let ctx = ui.ctx().clone(); + if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + crate::shortcuts::handle(app, &ctx); + egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(4); + let v = &mut h.state_mut().ui.views[0]; + v.zoom = 1.0; + v.center = [200.0, 150.0]; + v.fit_pending = false; + h.run_steps(2); + h +} + +/// #6286: an existing guide dragged onto a ruler with the Move tool is deleted, though the +/// release is inside the document on the guide's own axis: the left ruler measures y, so a +/// horizontal guide let go there still reads a y inside the canvas and used to be moved. Held +/// level, that release reads as a click on the guide, which a ruler drop also outranks. +#[test] +fn a_guide_dragged_onto_a_ruler_is_deleted_through_the_canvas() { + for below in [50.0f32, 0.0] { + let mut h = tool_canvas_harness(crate::state::Tool::Move); + h.state_mut().run("view.newGuide", json!({"orientation": "horizontal", "position": 150})).unwrap(); + h.run_steps(1); + let at = |h: &egui_kittest::Harness<'static, PhotocraftApp>, x: f32, y: f32| { + let app = h.state(); + let v = &app.ui.views[0]; + let xf = ViewXform { + rect: content_rect(app, app.last_canvas_rect), + zoom: v.zoom, + center: v.center, + flip: app.ui.view.flip_horizontal, + rotation: v.rotation, + aspect: app.ui.view.display_aspect(), + }; + xf.to_screen(x, y) + }; + let on_the_guide = at(&h, 200.0, 150.0); + // In the left ruler's band, `below` document px under the press: inside the canvas on the + // guide's own axis, which is where the old code moved the guide instead of removing it. + let canvas = h.state().last_canvas_rect; + let onto_the_left_ruler = pos2(canvas.min.x + RULER / 2.0, on_the_guide.y + below); + // Along the guide, so a held-level release keeps its y, the way a sideways drag does. + let dragged = pos2(on_the_guide.x - 12.0, on_the_guide.y); + h.event(egui::Event::PointerMoved(on_the_guide)); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: on_the_guide, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); + h.run_steps(1); + // Past egui's click distance, so the drag starts at the press, on the guide. + h.event(egui::Event::PointerMoved(dragged)); + h.run_steps(2); + assert!(h.state().guide_drag.is_some(), "the Move tool takes the guide"); + h.event(egui::Event::PointerMoved(onto_the_left_ruler)); + h.run_steps(1); + h.event(egui::Event::PointerButton { + pos: onto_the_left_ruler, + button: egui::PointerButton::Primary, + pressed: false, + modifiers: egui::Modifiers::NONE, + }); + h.run_steps(2); + let g = &h.state().session.active().unwrap().doc.guides; + assert!(g.horizontal.is_empty(), "{below} px below the press, released on the left ruler: got {:?}", g.horizontal); + assert!(h.state().guide_drag.is_none(), "the drag is over"); + } +} + +/// #3770: a guide Shift-dragged out of a ruler lands on the nearest tick the ruler draws +/// (tenths of the labelled step, in the ruler unit); without Shift it lands where it's dropped. +#[test] +fn shift_dragged_guides_land_on_ruler_ticks() { + let full = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)); + let rect = Rect::from_min_max(full.min + vec2(RULER, RULER), full.max); + let xf = ViewXform { rect, zoom: 1.0, center: [128.0, 64.0], flip: false, rotation: 0.0, aspect: 1.0 }; + let new_app = || { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 256, "height": 128})).unwrap(); + app + }; + let drag_guide = |modifiers: egui::Modifiers| { + let builder = egui_kittest::Harness::builder().with_size(vec2(400.0, 300.0)); + let mut h = builder.build_ui_state(move |ui, app| draw_rulers(app, ui, full, &xf), new_app()); + // Out of the left ruler: a vertical guide, dropped at document x = 37. + let (from, to) = (pos2(RULER / 2.0, 100.0), xf.to_screen(37.0, 64.0)); + h.event_modifiers(egui::Event::PointerMoved(from), modifiers); + h.event_modifiers(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers }, modifiers); + h.run_steps(1); + h.event_modifiers(egui::Event::PointerMoved(to), modifiers); + h.run_steps(1); + h.event_modifiers(egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers }, modifiers); + h.run_steps(2); + h.state().session.active().unwrap().doc.guides.vertical.clone() + }; + assert_eq!(drag_guide(egui::Modifiers::NONE), vec![37.0]); + // #5698: Alt turns it into a horizontal guide (at the drop's y, the document's centre). + assert_eq!(drag_guide(egui::Modifiers::ALT), Vec::::new(), "no vertical guide with Alt"); + // Pixels at 100%: labels every 100 px, ticks every 10 px. + assert_eq!(drag_guide(egui::Modifiers::SHIFT), vec![40.0]); + + let mut app = new_app(); + // At 200% the labels are every 50 px, so the ticks every 5 px. + assert_eq!(snap_to_tick(&app, &ViewXform { zoom: 2.0, ..xf }, true, 37.0), 35.0); + // Percent of each side: ticks every 2.5% of 256 px across, every 5% of 128 px down. + app.run("prefs.set", json!({"path": "unitsAndRulers.rulers", "value": "percent"})).unwrap(); + assert!((snap_to_tick(&app, &xf, true, 37.0) - 38.4).abs() < 1e-9); + assert!((snap_to_tick(&app, &xf, false, 37.0) - 38.4).abs() < 1e-9); + // Ticks count from the zero point (#2955): a vertical guide follows the x origin only. + let mut app = new_app(); + app.run("view.setRulerOrigin", json!({"x": 3, "y": 0})).unwrap(); + assert_eq!(snap_to_tick(&app, &xf, true, 37.0), 33.0); + assert_eq!(snap_to_tick(&app, &xf, false, 37.0), 40.0); +} diff --git a/crates/ui-egui/src/scrollbars.rs b/crates/ui-egui/src/canvas/scrollbars.rs similarity index 100% rename from crates/ui-egui/src/scrollbars.rs rename to crates/ui-egui/src/canvas/scrollbars.rs diff --git a/crates/ui-egui/src/select_mask_view.rs b/crates/ui-egui/src/canvas/select_mask_view.rs similarity index 100% rename from crates/ui-egui/src/select_mask_view.rs rename to crates/ui-egui/src/canvas/select_mask_view.rs diff --git a/crates/ui-egui/src/canvas/selection.rs b/crates/ui-egui/src/canvas/selection.rs new file mode 100644 index 0000000000..fe096f1159 --- /dev/null +++ b/crates/ui-egui/src/canvas/selection.rs @@ -0,0 +1,105 @@ +use super::tool_input::selection_drag_kind; +use super::*; + +/// Photoshop's cursor over a selection: what a press (or the drag under way) would do. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SelCursor { + /// A marquee or lasso inside the selection moves the outline (the move cursor, #1428), also + /// while it is being dragged. + Outline, + /// Arrow with scissors: the Move tool (⌘ with a marquee) cuts and moves the selected pixels. + Cut, + /// Arrow with a second arrow: ⌥ lifts a copy of them instead. + Copy, + /// Plain arrow: a floating piece, moved again by a plain drag until it is dropped. + Piece, + /// Hollow arrowhead: the selected pixels are being dragged. + Dragging, +} + +/// The cursor at document point `p` with `tool` in effect and `mods` held (`None`: not over a +/// selection the press would move). The Move tool moves the selected pixels from anywhere +/// (`move_ui::moves_selected_pixels_with`); a selection tool from inside the selection, or on the +/// floating piece (`selection_drag_kind`). +pub fn selection_cursor(app: &PhotocraftApp, tool: Tool, p: [f64; 2], mods: egui::Modifiers) -> Option { + if let Some(d) = &app.drag { + return match d.sel_move { + Some(true) => Some(SelCursor::Dragging), + Some(false) => Some(SelCursor::Outline), + None => None, + }; + } + let floating = app.session.active().and_then(photocraft_engine::float_cmds::floating).is_some(); + let pixels = if tool == Tool::Move { + crate::move_ui::moves_selected_pixels_with(app, tool) + } else { + match selection_drag_kind(app, tool, p, mods)? { + false => return Some(SelCursor::Outline), + true => true, + } + }; + if !pixels { + return None; + } + // ⌥ (⌘⌥ with a selection tool) floats a copy, of the layer's pixels or of the piece. + let copy = mods.alt && (tool == Tool::Move || mods.command); + Some(match (floating, copy) { + (_, true) => SelCursor::Copy, + (true, false) => SelCursor::Piece, + (false, false) => SelCursor::Cut, + }) +} + +/// Whole-pixel offset of a selection drag in progress (`Drag::sel_move`). +pub(crate) fn selection_drag_delta(app: &PhotocraftApp) -> Option<(i32, i32)> { + let d = app.drag.as_ref().filter(|d| d.sel_move.is_some())?; + let end = d.points.last().map_or(d.start, |p| [p[0], p[1]]); + Some(((end[0] - d.start[0]).round().clamp(-1e7, 1e7) as i32, (end[1] - d.start[1]).round().clamp(-1e7, 1e7) as i32)) +} + +/// The selection a floating piece on document `idx` shows its ants for, before its offset: the +/// moved pixels' outline, as in Photoshop (#7538); `None` outlines the document's selection. The +/// surface's tiles are shared, so the clone is cheap. +pub(crate) fn floating_outline(app: &PhotocraftApp, idx: usize) -> Option { + if app.session.active_index() != Some(idx) { + return None; + } + photocraft_engine::float_cmds::floating(app.session.active()?)?.parts.outline().cloned() +} + +/// Where the selection is drawn relative to where it is: a floating piece's offset plus a drag +/// in progress. +pub(super) fn selection_shown_offset(app: &PhotocraftApp) -> Option<(i32, i32)> { + crate::move_ui::floating_offset(app).or_else(|| selection_drag_delta(app)).or_else(|| carried_selection_delta(app)) +} + +/// Whole-pixel offset of a Move drag of several layers, which carries the selection along +/// (`move_ui::carries_selection`): their ants follow the layers while they move (#7538). +fn carried_selection_delta(app: &PhotocraftApp) -> Option<(i32, i32)> { + let d = app.drag.as_ref().filter(|d| d.tool == Tool::Move && d.sel_move.is_none())?; + if !crate::move_ui::carries_selection(app) { + return None; + } + let end = d.points.last().map_or(d.start, |p| [p[0], p[1]]); + Some(((end[0] - d.start[0]).round().clamp(-1e7, 1e7) as i32, (end[1] - d.start[1]).round().clamp(-1e7, 1e7) as i32)) +} + +/// End of a selection drag: move the outline, or the floating piece. A click without moving +/// deselects, like a marquee click (a click on a floating piece leaves it floating, unless it never +/// moved: then it is put back, so Undo isn't spent on it). +pub(super) fn finish_selection_drag(app: &mut PhotocraftApp, floating: bool, start: [f64; 2], end: [f64; 2]) { + let (dx, dy) = ((end[0] - start[0]).round(), (end[1] - start[1]).round()); + let unmoved = app.session.active().and_then(photocraft_engine::float_cmds::floating).is_some_and(|f| f.offset == (0, 0)); + let r = match (floating, dx == 0.0 && dy == 0.0) { + (true, true) if unmoved => app.run("select.drop", json!({})), + (true, true) => return, + (false, true) if app.session.is_enabled("select.deselect") => app.run("select.deselect", json!({})), + (false, true) => return, + (true, false) => app.run("select.float", json!({"dx": dx, "dy": dy})), + (false, false) => app.run("select.transformSelection", json!({"dx": dx, "dy": dy})), + }; + if let Err(e) = r { + app.ui.status = e; + app.ui.status_error = true; + } +} diff --git a/crates/ui-egui/src/canvas/snap_ui.rs b/crates/ui-egui/src/canvas/snap_ui.rs new file mode 100644 index 0000000000..05365dab54 --- /dev/null +++ b/crates/ui-egui/src/canvas/snap_ui.rs @@ -0,0 +1,605 @@ +//! Snapping in the shell: builds [`photocraft_engine::snap`] targets from View › Snap To and the +//! document, snaps tool gestures (Move tool, marquees, crop, shapes, pen anchors, Free Transform +//! handles and guides), and draws smart guides (magenta alignment lines) while layers move. +//! +//! Snapping is on when View › Snap (⇧⌘;) is; holding Ctrl while dragging turns it off, except when +//! Ctrl is the corner-distortion modifier. Smart guides follow View › Show › Smart Guides and also snap the Move +//! tool to other layers' edges and centres. The threshold is 8 screen pixels at the current zoom. + +use egui::{Color32, Stroke, pos2}; +use photocraft_doc::LayerId; +use photocraft_engine::snap::{SnapKind, SnapLine, SnapOptions, SnapTargets, layer_rect, union}; + +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, ViewXform}; +use crate::state::Tool; + +/// Snap distance in screen pixels. +pub const SNAP_PX: f64 = 8.0; + +/// What the current drag snaps. +#[derive(Clone, Debug, PartialEq)] +pub enum Gesture { + /// A point (marquee corner, crop or shape corner, pen anchor, transform handle). + Point, + /// A transform corner: distortion snaps the corner itself, keeping the handle grab offset. + TransformCorner { index: usize, point: [f64; 2] }, + /// Layers being moved: their bounds at the start of the drag. + Move { rect: [f64; 4] }, + /// Free Transform box dragged from inside: its bounds at the start of the drag. + TransformMove { rect: [f64; 4] }, + /// A selection outline (or its floating piece) dragged with a selection tool: its bounds at + /// the start of the drag. + SelectionMove { rect: [f64; 4] }, + /// A marquee, Object Selection box or shape being drawn, repositioned with Space held + /// (`hold_keys`): its bounds when Space went down. + DrawMove { rect: [f64; 4] }, + /// A guide being moved with the Move tool. + Guide, + /// Default crop mode, a drag inside an upright box: the image moves under it, so the frame + /// moves the other way over the document and its edges and centre snap ([`crop_image`]). + CropImage, +} + +/// Snapping state of the drag in progress. +#[derive(Clone, Debug)] +pub struct ActiveSnap { + pub gesture: Gesture, + pub start: [f64; 2], + pub targets: SnapTargets, + /// Layer alignments only (smart guides), when View › Snap and Smart Guides are on. + pub smart: SnapTargets, + pub disabled: bool, +} + +/// Snap To options from the View menu and the Guides/Grid preferences. +pub fn options(app: &PhotocraftApp) -> SnapOptions { + let st = &app.ui.view.snap_to; + let e = &app.ui.extras; + let grid_step = app.session.active().map_or([18.0; 2], |d| { + let g = &app.session.prefs().guides_grid_and_slices; + let ppi = app.session.prefs().units_and_rulers.point_size.per_inch(); + crate::rulers::grid_major_px(g, d.doc.resolution_dpi.max(1.0) as f64, [d.doc.size.width as f64, d.doc.size.height as f64], ppi) + .map(|step| step / g.subdivisions.max(1) as f64) + }); + SnapOptions { + guides: st.guides && e.guides && app.ui.view.shows(app.ui.view.show.canvas_guides), + grid: st.grid && e.grid, + layers: st.layers, + document: st.document_bounds, + selection: true, + grid_step, + } +} + +/// Snap tolerance in document pixels at the current zoom. +pub fn tolerance(app: &PhotocraftApp) -> f64 { + SNAP_PX / app.point_zoom().max(0.01) as f64 +} + +fn smart_on(app: &PhotocraftApp) -> bool { + app.ui.view.shows(app.ui.view.show.smart_guides) +} + +fn snap_on(app: &PhotocraftApp) -> bool { + app.ui.extras.snap +} + +/// Targets of the active document (smart = layer alignments only). +fn build(app: &PhotocraftApp, exclude: &[LayerId], smart: bool) -> SnapTargets { + let Some(st) = app.session.active() else { return SnapTargets::default() }; + let opts = + if smart { SnapOptions { guides: false, grid: false, layers: true, document: true, selection: false, grid_step: [0.0; 2] } } else { options(app) }; + let t = SnapTargets::from_document(&st.doc, &opts, exclude); + if smart { t.filtered(SnapKind::is_smart) } else { t } +} + +/// What a move with `tool` in effect drags: the selection's bounds where its pixels float +/// (`move_ui`), else the union of the selected layers' bounds. +fn moving_rect(app: &PhotocraftApp, tool: Tool) -> Option<[f64; 4]> { + let st = app.session.active()?; + if crate::move_ui::moves_selected_pixels_with(app, tool) { + return selection_rect(app); + } + union(st.selected_layers().into_iter().filter_map(|id| layer_rect(&st.doc, id))) +} + +/// The bounds of the pixels a selection moves, where they are shown: its floating piece's outline +/// at its offset (#7538), else (nothing cut yet, or a mask or empty piece) the selection's bounds. +fn selection_rect(app: &PhotocraftApp) -> Option<[f64; 4]> { + let st = app.session.active()?; + let sel = st.doc.selection.as_ref()?; + let r = match photocraft_engine::float_cmds::floating(st) { + Some(f) => f.parts.outline().unwrap_or(sel).content_bounds().translate(f.offset.0, f.offset.1), + None => sel.content_bounds(), + }; + (!r.is_empty()).then(|| [r.x0, r.y0, r.x1, r.y1].map(f64::from)) +} + +/// A press cut the selected pixels after snapping began (`filter_event` runs before the tools): +/// the move now snaps the cut piece's outline, not the selection it was cut with (#7538). +pub(crate) fn follow_cut(app: &mut PhotocraftApp) { + let Some(rect) = selection_rect(app) else { return }; + if let Some(snap) = app.prefs_rt.snap.as_mut() { + match &mut snap.gesture { + Gesture::Move { rect: r } | Gesture::SelectionMove { rect: r } => *r = rect, + _ => {} + } + } +} + +fn is_point_tool(t: Tool) -> bool { + matches!( + t, + Tool::RectMarquee + | Tool::EllipseMarquee + | Tool::SingleRowMarquee + | Tool::SingleColumnMarquee + | Tool::Crop + | Tool::ObjectSelection + | Tool::Pen + | Tool::CurvaturePen + | Tool::Rectangle + | Tool::EllipseShape + | Tool::Triangle + | Tool::Polygon + | Tool::Line + | Tool::Type + | Tool::VerticalType + | Tool::HorizontalTypeMask + | Tool::VerticalTypeMask + ) +} + +fn quad_rect(q: &[[f64; 2]; 4]) -> [f64; 4] { + let xs = q.iter().map(|p| p[0]); + let ys = q.iter().map(|p| p[1]); + [xs.clone().fold(f64::MAX, f64::min), ys.clone().fold(f64::MAX, f64::min), xs.fold(f64::MIN, f64::max), ys.fold(f64::MIN, f64::max)] +} + +/// Is `p` inside the quad (even-odd)? +fn in_quad(q: &[[f64; 2]; 4], p: [f64; 2]) -> bool { + let mut inside = false; + for i in 0..4 { + let (a, b) = (q[i], q[(i + 3) % 4]); + if (a[1] > p[1]) != (b[1] > p[1]) && p[0] < (b[0] - a[0]) * (p[1] - a[1]) / (b[1] - a[1]) + a[0] { + inside = !inside; + } + } + inside +} + +/// Near a Free Transform corner or edge handle (within its grab radius)? +fn near_handle(q: &[[f64; 2]; 4], p: [f64; 2], tol: f64) -> bool { + (0..4).any(|i| { + let (a, b) = (q[i], q[(i + 1) % 4]); + let mid = [(a[0] + b[0]) / 2.0, (a[1] + b[1]) / 2.0]; + [a, mid].iter().any(|h| (h[0] - p[0]).hypot(h[1] - p[1]) <= tol) + }) +} + +/// Photoshop: holding Ctrl (Windows) / Control (macOS) *during* a drag temporarily turns snapping +/// off. Only the held state while dragging counts: Ctrl at the press belongs to the tool (Ctrl-click +/// auto-selects with the Move tool), and ⌘ on the Mac never overrides snapping. +fn override_held(mods: egui::Modifiers) -> bool { + mods.ctrl && !mods.mac_cmd +} + +fn corner_distorts(app: &PhotocraftApp, gesture: &Gesture, mods: egui::Modifiers) -> bool { + matches!(gesture, Gesture::TransformCorner { index, .. } if crate::transform_tool::corner_distorts(app, *index, mods)) +} + +fn override_for_gesture(app: &PhotocraftApp, mods: egui::Modifiers) -> bool { + override_held(mods) && !(mods.command && app.prefs_rt.snap.as_ref().is_some_and(|s| corner_distorts(app, &s.gesture, mods))) +} + +/// The Move tool's press at `p` picked other layers (Auto-Select): the drag moves those, so its +/// box, what it snaps and what it leaves out of the targets are theirs, not the ones selected +/// before (a group or an empty layer selected before had no box at all). +pub(crate) fn retarget_move(app: &mut PhotocraftApp, p: [f64; 2], mods: egui::Modifiers) { + begin(app, p, mods); +} + +/// Start snapping for a drag beginning at `p` with `mods` held (called on pointer down). +fn begin(app: &mut PhotocraftApp, p: [f64; 2], mods: egui::Modifiers) { + app.prefs_rt.snap = None; + app.prefs_rt.snap_lines.clear(); + // Puppet Warp's pins and Perspective Warp's quads go where they are dragged, as in Photoshop: + // the press is theirs, not the tool's (with the Move tool it took a layer move's Smart Guides). + if app.session.active().is_none() || app.distort.active() { + return; + } + // The tool the press acts as: ⌘ makes a painting tool the Move tool, and a selection tool + // outside the selection moves the layer as the Move tool does (#2681). + let tool = crate::canvas::event_tool(app, mods); + let moves_layer = crate::canvas::command_moves_layer(app, tool, p, mods); + let crop_tol = crate::crop_ui::tolerance(app); + let gesture = if let Some(t) = &app.ui.transform { + let corner = match crate::transform_tool::hit(t, p, crate::transform_tool::handle_tolerance(app)) { + crate::transform_tool::Hit::Corner(index) => t.quad.get(index).map(|&point| (Gesture::TransformCorner { index, point }, vec![LayerId(t.layer)])), + _ => None, + }; + if t.mode == crate::state::TransformMode::Distort { + corner + } else if near_handle(&t.quad, p, crate::transform_tool::handle_tolerance(app)) { + corner.or_else(|| Some((Gesture::Point, vec![LayerId(t.layer)]))) + } else if in_quad(&t.quad, p) { + Some((Gesture::TransformMove { rect: quad_rect(&t.quad) }, vec![LayerId(t.layer)])) + } else { + None + } + } else if tool == Tool::Move && crate::rulers::guide_at(app, p[0], p[1]).is_some() { + Some((Gesture::Guide, Vec::new())) + } else if tool == Tool::Move || moves_layer { + let exclude = app.session.active().map(|s| s.selected_layers()).unwrap_or_default(); + moving_rect(app, tool).map(|rect| (Gesture::Move { rect }, exclude)) + } else if tool == Tool::Crop + && (crate::crop_mode::classic(app) || app.crop.default_frame) + && let Some(rect) = + app.ui.crop_rect.filter(|r| crate::crop_ui::angle(app) == 0.0 && crate::crop_ui::hit(*r, p, crop_tol) == crate::crop_ui::Hit::Inside) + { + // Inside the untouched default frame draws a new crop (in both modes): snap its corner, not + // the old canvas-sized frame's bounds. An edited Classic Mode frame still moves and snaps + // its edges. + let gesture = if app.crop.default_frame { Gesture::Point } else { Gesture::Move { rect } }; + Some((gesture, Vec::new())) + } else if tool == Tool::Crop + && crate::crop_mode::moves_image(app) + && !app.crop.default_frame + && crate::crop_ui::angle(app) == 0.0 + && app.ui.crop_rect.is_some_and(|r| crate::crop_ui::hit(r, p, crop_tol) == crate::crop_ui::Hit::Inside) + { + // The default mode moves the image under an upright box: the frame's edges and centre + // snap, as an edited Classic Mode frame's do, so content can be centred in it (#8580). + Some((Gesture::CropImage, Vec::new())) + } else if tool == Tool::Crop + && (crate::crop_ui::turns_at(app, p) + || app.ui.crop_rect.is_some_and(|r| crate::crop_ui::hit_turned(r, crate::crop_ui::angle(app), p, crop_tol) == crate::crop_ui::Hit::Inside)) + { + // Turning the frame, moving a turned one (its edges don't line up with anything), or in + // the default mode turning the image or moving it under a turned box: no snapping. + None + } else if let Some(cut) = crate::canvas::selection_drag_kind(app, tool, p, mods) { + // A marquee or lasso inside the selection moves the outline (⌘: cuts its pixels into a + // floating piece): its bounds snap, as the Move tool's do, not the pointer. A cut piece + // doesn't snap to its own layer. + let exclude = if cut { app.session.active().map(|s| s.selected_layers()).unwrap_or_default() } else { Vec::new() }; + selection_rect(app).map(|rect| (Gesture::SelectionMove { rect }, exclude)) + } else if tool.is_type() + && let Some(layer) = app.ui.text_edit.as_ref().map(|e| LayerId(e.layer)) + { + // Editing type: a paragraph-box handle drag snaps to guides and other layers, not to the + // text being resized; a press in the text places the caret where it is (#6819). + crate::type_tool::box_handle_at(app, layer, p[0], p[1]).map(|_| (Gesture::Point, vec![layer])) + } else if is_point_tool(tool) { + Some((Gesture::Point, Vec::new())) + } else { + None + }; + let Some((gesture, exclude)) = gesture else { return }; + let mut targets = if snap_on(app) { build(app, &exclude, false) } else { SnapTargets::default() }; + if app.ui.transform.as_ref().is_some_and(|t| t.mode == crate::state::TransformMode::Distort) { + // Explicit Distort fits corners to guides; preserve free placement near layer edges. + targets = targets.filtered(|k| k == SnapKind::Guide); + } + if gesture == Gesture::Guide { + // A guide never snaps to itself (or other guides). + targets = targets.filtered(|k| k != SnapKind::Guide); + } + if matches!(gesture, Gesture::SelectionMove { .. }) || (matches!(gesture, Gesture::Move { .. }) && crate::move_ui::moves_selected_pixels_with(app, tool)) { + // A moving selection never snaps back to where it started. + targets = targets.filtered(|k| k != SnapKind::Selection); + } + let smart = if snap_on(app) && matches!(gesture, Gesture::Move { .. } | Gesture::CropImage) && smart_on(app) { + build(app, &exclude, true) + } else { + SnapTargets::default() + }; + app.prefs_rt.snap = Some(ActiveSnap { gesture, start: p, targets, smart, disabled: false }); +} + +/// Snap a guide drag that ⌘ with a selection tool starts at `p` (`canvas::command_guide_at`, +/// #2690) as the Move tool's guide drag: never to guides, so not back onto itself. +pub fn begin_guide(app: &mut PhotocraftApp, p: [f64; 2]) { + app.prefs_rt.snap_lines.clear(); + let targets = if snap_on(app) { build(app, &[], false).filtered(|k| k != SnapKind::Guide) } else { SnapTargets::default() }; + app.prefs_rt.snap = Some(ActiveSnap { gesture: Gesture::Guide, start: p, targets, smart: SnapTargets::default(), disabled: false }); +} + +/// Round to whole pixels when Preferences › Tools asks vector tools and transforms to snap to +/// the pixel grid. +fn pixel_round(app: &PhotocraftApp, p: [f64; 2]) -> [f64; 2] { + if app.session.prefs().tools.snap_vector_tools_and_transforms_to_pixel_grid + && matches!(app.ui.tool, Tool::Pen | Tool::CurvaturePen | Tool::Rectangle | Tool::EllipseShape | Tool::Triangle | Tool::Polygon | Tool::Line) + { + [p[0].round(), p[1].round()] + } else { + p + } +} + +/// Snap one pointer position for the active gesture; records the alignment lines. +fn apply(app: &mut PhotocraftApp, p: [f64; 2], mods: egui::Modifiers) -> [f64; 2] { + let tol = tolerance(app); + let Some(snap) = app.prefs_rt.snap.as_ref() else { return p }; + if !snap_on(app) || snap.disabled { + app.prefs_rt.snap_lines.clear(); + return p; + } + let (out, lines) = match &snap.gesture { + Gesture::Point => crop_handle(app, p, mods, &snap.targets, tol).unwrap_or_else(|| snap.targets.snap_point(p, tol)), + Gesture::TransformCorner { point, .. } if corner_distorts(app, &snap.gesture, mods) => { + let proposed = [point[0] + p[0] - snap.start[0], point[1] + p[1] - snap.start[1]]; + let (corner, lines) = snap.targets.snap_point(proposed, tol); + ([p[0] + corner[0] - proposed[0], p[1] + corner[1] - proposed[1]], lines) + } + Gesture::TransformCorner { .. } => snap.targets.snap_point(p, tol), + Gesture::Guide => snap.targets.snap_point(p, tol), + Gesture::Move { rect } | Gesture::TransformMove { rect } | Gesture::SelectionMove { rect } | Gesture::DrawMove { rect } => { + let d = [p[0] - snap.start[0], p[1] - snap.start[1]]; + let moved = [rect[0] + d[0], rect[1] + d[1], rect[2] + d[0], rect[3] + d[1]]; + let set = if snap.targets.is_empty() { &snap.smart } else { &snap.targets }; + let (adj, lines) = set.snap_rect(moved, tol); + ([p[0] + adj[0], p[1] + adj[1]], lines) + } + Gesture::CropImage => { + // Smart guides still snap when nothing in View › Snap To is within reach: the + // document's bounds alone keep `targets` from ever being empty. + let snapped = |set| crop_image(app, p, set, tol).filter(|(_, lines)| !lines.is_empty()); + snapped(&snap.targets).or_else(|| snapped(&snap.smart)).unwrap_or((p, Vec::new())) + } + }; + app.prefs_rt.snap_lines = lines; + out +} + +/// A corner stopped by the transform's convexity constraint is not aligned to the proposed +/// target. Keep only the lines the final corner actually reaches, after the transform applies. +pub(crate) fn retain_transform_lines(app: &mut PhotocraftApp, mods: egui::Modifiers) { + let Some(snap) = app.prefs_rt.snap.as_ref() else { return }; + let Gesture::TransformCorner { index, .. } = snap.gesture else { return }; + if !corner_distorts(app, &snap.gesture, mods) { + return; + } + let Some(point) = app.ui.transform.as_ref().and_then(|t| t.quad.get(index)).copied() else { return }; + app.prefs_rt.snap_lines.retain(|line| (if line.vertical { point[0] } else { point[1] } - line.pos).abs() < 1e-6); +} + +/// Snap a crop handle being dragged: the handle itself (the frame's edge or corner), not the +/// pointer, which grabbed it up to the grab radius away (#1919: snapping the pointer left a strip +/// as wide as that offset between the frame and the edge it showed as snapped to). With Auto +/// Center Preview the handle is found on the image, calculated from the original camera: snapping +/// the pointer in the moving camera feeds the previous frame's pan back into the resize and makes +/// a stationary pointer oscillate near the canvas edges. +fn crop_handle(app: &PhotocraftApp, p: [f64; 2], mods: egui::Modifiers, targets: &SnapTargets, tol: f64) -> Option<([f64; 2], Vec)> { + if app.ui.tool != Tool::Crop { + return None; + } + let crate::crop_ui::CropDrag::Resize { hx, hy, start, rect, view } = app.crop.drag? else { return None }; + let deg = crate::crop_ui::angle(app); + let ratio = crate::crop_ui::resize_ratio(app, rect, mods); + let q = view.map_or(p, |view| crate::crop_mode::to_press(app, Some(view), p)); + // The frame for the pointer at `q`, as `crop_ui` resizes it. + let frame_at = |q: [f64; 2]| match view { + Some(_) => crate::crop_mode::resized_frame(crate::crop_mode::LiveResize { rect, deg, hx, hy, start, q, ratio, alt: mods.alt }).map(|(f, _)| f), + None => Some(crate::crop_ui::resized_turned(rect, deg, hx, hy, [q[0] - start[0], q[1] - start[1]], ratio, mods.alt)), + }; + let frame = frame_at(q)?; + let at = |r: [f64; 4]| { + let c = crate::crop_ui::center(r); + crate::crop_ui::turn([c[0] + f64::from(hx) * (r[2] - r[0]) / 2.0, c[1] + f64::from(hy) * (r[3] - r[1]) / 2.0], c, deg) + }; + let handle = at(frame); + let (snapped, mut lines) = targets.snap_point(handle, tol); + let mut d = crate::crop_ui::turn([snapped[0] - handle[0], snapped[1] - handle[1]], [0.0, 0.0], -deg); + // An edge handle controls only its own axis, not the midpoint along the other one. + if hx == 0 { + d[0] = 0.0; + } + if hy == 0 { + d[1] = 0.0; + } + if deg == 0.0 { + lines.retain(|line| if line.vertical { hx != 0 } else { hy != 0 }); + } + if lines.is_empty() { + return Some((p, lines)); + } + // Auto Center Preview moves both screen edges. On the image the opposite edge stays put, + // so the grabbed edge travels twice as far as the pointer (once with Alt). Without it the + // handle follows the pointer. + let scale = if view.is_some() && !mods.alt { 2.0 } else { 1.0 }; + // How much the frame's extent grows per unit of pointer travel: both sides with Auto Center + // Preview or Alt, else the grabbed one. + let grow = if view.is_some() || mods.alt { 2.0 } else { 1.0 }; + let original = at(rect); + let travel = crate::crop_ui::turn([handle[0] - original[0], handle[1] - original[1]], [0.0, 0.0], -deg); + let mut local = [(travel[0] + d[0]) / scale, (travel[1] + d[1]) / scale]; + if deg == 0.0 + && hx != 0 + && hy != 0 + && let Some(k) = ratio + { + // A corner with a ratio has one degree of freedom. Put the other axis on the same + // ratio, rather than letting the raw pointer's unused axis override the snapped edge. + if lines.iter().any(|line| line.vertical) { + local[1] = f64::from(hy) * ((rect[2] - rect[0] + grow * f64::from(hx) * local[0]) / k - (rect[3] - rect[1])) / grow; + } else { + local[0] = f64::from(hx) * ((rect[3] - rect[1] + grow * f64::from(hy) * local[1]) * k - (rect[2] - rect[0])) / grow; + } + } + let d = crate::crop_ui::turn(local, [0.0, 0.0], deg); + let q = [start[0] + d[0], start[1] + d[1]]; + if let Some(snapped_frame) = frame_at(q) { + let h = at(snapped_frame); + lines.retain(|line| (if line.vertical { h[0] } else { h[1] } - line.pos).abs() < 1e-3); + } + Some((view.map_or(q, |view| crate::crop_mode::from_press(app, view, q)), lines)) +} + +/// Snap the image being moved under the crop box (default mode): the frame moves by the image's +/// travel the other way over the document, so its edges and centre snap and the pointer moves by +/// the frame's correction the other way too (#8580). As `crop_ui` reads this drag, the pointer is +/// read in the camera at the press, since the view pans with the frame meanwhile. +fn crop_image(app: &PhotocraftApp, p: [f64; 2], targets: &SnapTargets, tol: f64) -> Option<([f64; 2], Vec)> { + let crate::crop_ui::CropDrag::MoveImage { start, rect, view } = app.crop.drag? else { return None }; + let q = crate::crop_mode::to_press(app, view, p); + let d = [q[0] - start[0], q[1] - start[1]]; + let (adj, lines) = targets.snap_rect([rect[0] - d[0], rect[1] - d[1], rect[2] - d[0], rect[3] - d[1]], tol); + if adj == [0.0, 0.0] { + return Some((p, lines)); + } + let q = [q[0] - adj[0], q[1] - adj[1]]; + Some((view.map_or(q, |view| crate::crop_mode::from_press(app, view, q)), lines)) +} + +/// The bounds `[x0, y0, x1, y1]` of what drag `d` draws so far, for the tools whose drag Space +/// repositions and that snap (`None` for the rest, or a shape still too small to draw). +fn drawn_rect(app: &PhotocraftApp, d: &crate::canvas::Drag) -> Option<[f64; 4]> { + let last = d.points.last().map_or(d.start, |p| [p[0], p[1]]); + let (a, b) = match d.tool { + Tool::RectMarquee | Tool::EllipseMarquee => crate::canvas::marquee_corners(&app.ui.tool_options, d, last), + Tool::ObjectSelection => (d.start, last), + t if crate::vector_ui::is_shape_tool(t) => return crate::vector_ui::shape_bounds(&app.ui.tool_options, t, d.start, last, d.live), + _ => return None, + }; + Some([a[0].min(b[0]), a[1].min(b[1]), a[0].max(b[0]), a[1].max(b[1])]) +} + +/// Space held while a marquee, Object Selection box or shape is drawn moves the whole of it +/// (`hold_keys`): its edges and centre snap, as a moved selection's do, not just the corner under +/// the pointer. Releasing Space goes back to snapping that corner. +fn follow_reposition(app: &mut PhotocraftApp) { + let Some(d) = app.drag.as_ref() else { return }; + let Some(snap) = app.prefs_rt.snap.as_ref() else { return }; + let gesture = match (&snap.gesture, d.reposition) { + (Gesture::Point, true) => match drawn_rect(app, d) { + Some(rect) => Gesture::DrawMove { rect }, + None => return, + }, + (Gesture::DrawMove { .. }, false) => Gesture::Point, + _ => return, + }; + let last = d.points.last().map_or(d.start, |p| [p[0], p[1]]); + if let Some(snap) = app.prefs_rt.snap.as_mut() { + snap.gesture = gesture; + snap.start = last; + } +} + +/// Snap a tool event's coordinates (called by `canvas::tool_event` before the tools see it). +pub fn filter_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> ToolEvent { + match ev { + ToolEvent::Down { x, y, pressure } => { + begin(app, [x, y], mods); + // Moves snap their delta, which is zero at the start: keep the press point. + let p = match app.prefs_rt.snap.as_ref().map(|s| &s.gesture) { + Some(Gesture::Point) + if !(app.ui.tool == Tool::Crop + && app.ui.crop_rect.is_some_and(|r| { + matches!( + crate::crop_ui::hit_turned(r, crate::crop_ui::angle(app), [x, y], crate::crop_ui::tolerance(app)), + crate::crop_ui::Hit::Handle(..) + ) + })) => + { + let q = apply(app, [x, y], mods); + pixel_round(app, q) + } + _ => [x, y], + }; + ToolEvent::Down { x: p[0], y: p[1], pressure } + } + ToolEvent::Move { x, y, pressure } => { + if app.prefs_rt.snap.is_none() { + return ev; + } + follow_reposition(app); + let disabled = override_for_gesture(app, mods); + if let Some(s) = app.prefs_rt.snap.as_mut() { + s.disabled = disabled; + } + let q = apply(app, [x, y], mods); + let p = pixel_round(app, q); + ToolEvent::Move { x: p[0], y: p[1], pressure } + } + ToolEvent::Up { x, y } => { + if app.prefs_rt.snap.is_none() { + return ev; + } + follow_reposition(app); + let disabled = override_for_gesture(app, mods); + if let Some(s) = app.prefs_rt.snap.as_mut() { + s.disabled = disabled; + } + let q = apply(app, [x, y], mods); + let p = pixel_round(app, q); + app.prefs_rt.snap = None; + app.prefs_rt.snap_lines.clear(); + ToolEvent::Up { x: p[0], y: p[1] } + } + } +} + +/// Snap a guide being dragged out of a ruler (`vertical` guides snap their x). +pub fn snap_guide(app: &mut PhotocraftApp, vertical: bool, pos: f64) -> f64 { + if !snap_on(app) { + return pos; + } + let Some(st) = app.session.active() else { return pos }; + // The Snap To options (grid, layers, document bounds, grid step) change the targets too. + let key = (st.doc.id, st.revision, options(app)); + if app.prefs_rt.guide_targets.as_ref().is_none_or(|(k, _)| *k != key) { + let t = build(app, &[], false).filtered(|k| k != SnapKind::Guide); + app.prefs_rt.guide_targets = Some((key, t)); + } + let tol = tolerance(app); + let t = app.prefs_rt.guide_targets.as_ref().map(|(_, t)| t); + t.and_then(|t| t.nearest(vertical, pos, tol)).map_or(pos, |t| t.pos) +} + +fn hex_color(s: &str, fallback: Color32) -> Color32 { + photocraft_engine::prefs::parse_hex(s).map_or(fallback, |c| Color32::from_rgb(c[0], c[1], c[2])) +} + +/// The Smart Guides colour from Preferences › Guides, Grid & Slices (magenta by default). +pub(crate) fn smart_color(app: &PhotocraftApp) -> Color32 { + hex_color(&app.session.prefs().guides_grid_and_slices.smart_guide_color, Color32::from_rgb(255, 0, 255)) +} + +/// Draw smart guides (and the moving bounds) for the drag in progress. +pub fn draw(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform) { + let Some(snap) = &app.prefs_rt.snap else { return }; + let smart_color = smart_color(app); + // The moved layers' bounds follow the Move tool (Free Transform draws its own box). + if let (Gesture::Move { rect }, Some(d)) = + (&snap.gesture, app.drag.as_ref().and_then(|d| d.points.last()).map(|p| [p[0] - snap.start[0], p[1] - snap.start[1]])) + { + let r = egui::Rect::from_two_pos( + xf.to_screen((rect[0] + d[0]) as f32, (rect[1] + d[1]) as f32), + xf.to_screen((rect[2] + d[0]) as f32, (rect[3] + d[1]) as f32), + ); + painter.rect_stroke(r, 0.0, Stroke::new(1.0, crate::theme::Tokens::get(painter.ctx()).accent), egui::StrokeKind::Middle); + } + if !smart_on(app) { + return; + } + for l in &app.prefs_rt.snap_lines { + if !l.kind.is_smart() { + continue; + } + draw_line(painter, xf, l, smart_color); + } +} + +fn draw_line(painter: &egui::Painter, xf: &ViewXform, l: &SnapLine, color: Color32) { + let (a, b) = if l.vertical { + (xf.to_screen(l.pos as f32, l.from as f32), xf.to_screen(l.pos as f32, l.to as f32)) + } else { + (xf.to_screen(l.from as f32, l.pos as f32), xf.to_screen(l.to as f32, l.pos as f32)) + }; + painter.line_segment([pos2(a.x.round() + 0.5, a.y.round() + 0.5), pos2(b.x.round() + 0.5, b.y.round() + 0.5)], Stroke::new(1.0, color)); +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/canvas/snap_ui/tests.rs b/crates/ui-egui/src/canvas/snap_ui/tests.rs new file mode 100644 index 0000000000..56617d906e --- /dev/null +++ b/crates/ui-egui/src/canvas/snap_ui/tests.rs @@ -0,0 +1,756 @@ +use super::*; +use serde_json::json; + +fn app_with_box() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.sync_views(); + app.ui.views[0].zoom = 1.0; + app.ui.views[0].fit_pending = false; + // Two boxes: a target at (300..350, 200..260) and the moving one at (40..90, 40..80). + app.run("layer.new.layer", json!({"name": "target"})).unwrap(); + app.run("select.rect", json!({"x": 300, "y": 200, "width": 50, "height": 60})).unwrap(); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.run("layer.new.layer", json!({"name": "mover"})).unwrap(); + app.run("select.rect", json!({"x": 40, "y": 40, "width": 50, "height": 40})).unwrap(); + app.run("edit.fill", json!({"color": "#0000ff"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + app +} + +/// #7538: moving selected pixels snaps (and frames) the pixels, not a loose marquee round them. +/// Snapping starts before the press cuts them, so the cut retargets it to their outline. +#[test] +fn moving_selected_pixels_snaps_their_bounds_not_the_marquee() { + for alt in [false, true] { + let mut app = app_with_box(); + app.ui.tool = Tool::Move; + app.run("select.rect", json!({"x": 20, "y": 20, "width": 100, "height": 90})).unwrap(); + let m = egui::Modifiers { alt, ..Default::default() }; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, m); + let gesture = app.prefs_rt.snap.as_ref().map(|s| s.gesture.clone()); + assert_eq!(gesture, Some(Gesture::Move { rect: [40.0, 40.0, 90.0, 80.0] }), "alt {alt}: the blue box, not the marquee"); + // 263 px right puts the box's left edge 3 px from the target's (the marquee's 20 px off). + crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 323.0, y: 100.0, pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 323.0, y: 100.0 }, m); + app.run("select.drop", json!({})).unwrap(); + let sel = app.session.active().unwrap().doc.selection.as_ref().map(|s| s.content_bounds().x0); + assert_eq!(sel, Some(300), "alt {alt}: snapped to the target's edge"); + } + // A marquee's ⌘-drag cuts them the same way. + let mut app = app_with_box(); + app.ui.tool = Tool::RectMarquee; + app.run("select.rect", json!({"x": 20, "y": 20, "width": 100, "height": 90})).unwrap(); + let cmd = egui::Modifiers { mac_cmd: true, command: true, ..Default::default() }; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, cmd); + let gesture = app.prefs_rt.snap.as_ref().map(|s| s.gesture.clone()); + assert_eq!(gesture, Some(Gesture::SelectionMove { rect: [40.0, 40.0, 90.0, 80.0] }), "⌘-drag with the marquee"); + // The Background has no transparency to shrink to. + let mut app = app_with_box(); + app.ui.tool = Tool::Move; + app.run("layer.select", json!({"name": "Background"})).unwrap(); + app.run("select.rect", json!({"x": 20, "y": 20, "width": 100, "height": 90})).unwrap(); + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, egui::Modifiers::NONE); + let gesture = app.prefs_rt.snap.as_ref().map(|s| s.gesture.clone()); + assert_eq!(gesture, Some(Gesture::Move { rect: [20.0, 20.0, 120.0, 110.0] }), "the Background"); +} + +fn mover_bounds(app: &PhotocraftApp) -> photocraft_geom::Rect { + let st = app.session.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds() +} + +#[test] +fn drawing_a_new_crop_snaps_its_corner_not_the_default_frame() { + // In both crop modes: the default mode draws a new box inside the untouched frame too. + for (classic, snap, end) in [(true, false, [300.0, 220.0]), (true, true, [294.0, 217.0]), (false, false, [300.0, 220.0]), (false, true, [294.0, 217.0])] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 640, "height": 480, "background": "white"})).unwrap(); + app.run("shape.create", json!({"kind": "rect", "rect": [100, 80, 200, 140], "fill": "#d59b40"})).unwrap(); + app.sync_views(); + app.ppp = 2.0; + app.ui.views[0].zoom = 1.0; + app.ui.views[0].fit_pending = false; + app.ui.tool = Tool::Crop; + app.ui.tool_options.crop_shield.classic_mode = classic; + app.ui.extras.snap = snap; + app.ui.view.show.smart_guides = true; + crate::crop_ui::ensure_frame(&mut app); + let view = app.ui.views[0].clone(); + let history = app.session.active().unwrap().history.past_len(); + let m = egui::Modifiers::NONE; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 100.0, y: 80.0, pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Move { x: end[0], y: end[1], pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: end[0], y: end[1] }, m); + // Smart Guides must not snap the old canvas-sized frame as if it were moving. + // With View Snap on, the new corner still snaps to the nearby shape's edges. + assert_eq!(app.ui.crop_rect, Some([100.0, 80.0, 300.0, 220.0]), "Classic Mode: {classic}, View Snap: {snap}"); + // The default mode's Auto Center Preview re-centres the drawn box; Classic Mode keeps the view. + if classic { + assert_eq!(app.ui.views[0], view); + } + assert_eq!(app.session.active().unwrap().history.past_len(), history); + } +} + +#[test] +fn move_tool_snaps_to_other_layer_edges_with_smart_guides() { + let mut app = app_with_box(); + app.ui.tool = Tool::Move; + let m = egui::Modifiers::NONE; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, m); + // Drag so the mover's left edge lands 3 px right of the target's (x = 303). + crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 323.0, y: 100.0, pressure: 1.0 }, m); + assert!(app.prefs_rt.snap_lines.iter().any(|l| l.vertical && l.pos == 300.0 && l.kind.is_smart()), "{:?}", app.prefs_rt.snap_lines); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 323.0, y: 100.0 }, m); + assert_eq!(mover_bounds(&app).x0, 300); + assert!(app.prefs_rt.snap.is_none()); +} + +/// Puppet Warp's pins go where they are dragged: they don't snap, with View › Snap on or +/// off, whatever tool was active when it started. With the Move tool a pin drag took the +/// layer move's Smart Guides and jumped to the other layer's edges. +#[test] +fn puppet_warp_pins_never_snap() { + for (tool, snap) in [(Tool::Move, false), (Tool::Move, true), (Tool::RectMarquee, true), (Tool::Brush, false)] { + let mut app = app_with_box(); + app.ui.tool = tool; + app.ui.extras.snap = snap; + app.ui.view.show.smart_guides = true; + app.run("view.newGuide", json!({"orientation": "vertical", "position": 321})).unwrap(); + let ctx = egui::Context::default(); + crate::distort_ui::menu(&mut app, &ctx, "edit.puppetWarp", &json!({})).unwrap().unwrap(); + let m = egui::Modifiers::NONE; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, m); + // The mover's left edge 3 px right of the target's, the pin 2 px from the guide. + crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 323.0, y: 100.0, pressure: 1.0 }, m); + assert!(app.prefs_rt.snap_lines.is_empty(), "{tool:?}, snap {snap}: {:?}", app.prefs_rt.snap_lines); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 323.0, y: 100.0 }, m); + let pins = &app.distort.puppet.as_ref().unwrap().warp.pins; + assert_eq!(pins.iter().map(|p| p.dst).collect::>(), vec![[323.0, 100.0]], "{tool:?}, snap {snap}"); + } +} + +/// ⌘ turns a painting tool, or a marquee outside the selection, into the Move tool for the +/// drag: it gets the Move tool's box and smart-guide snapping, not the selected tool's. +#[test] +fn command_drag_temporary_move_snaps_like_the_move_tool() { + for tool in [Tool::Brush, Tool::RectMarquee] { + let mut app = app_with_box(); + app.ui.tool = tool; + let cmd = egui::Modifiers { mac_cmd: true, command: true, ..Default::default() }; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, cmd); + let gesture = app.prefs_rt.snap.as_ref().map(|s| s.gesture.clone()); + assert_eq!(gesture, Some(Gesture::Move { rect: [40.0, 40.0, 90.0, 80.0] }), "{tool:?}: the mover's box"); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 323.0, y: 100.0 }, cmd); + assert_eq!(mover_bounds(&app).x0, 300, "{tool:?}: snapped to the target's edge"); + } +} + +/// The drag's box and snapping belong to the layer Auto-Select picks on the press, not to the +/// one selected before: another layer (its box would move instead), or an empty layer (no box, +/// no snapping at all). +#[test] +fn move_tool_box_and_snapping_follow_the_auto_selected_layer() { + for before in ["target", "empty"] { + let mut app = app_with_box(); + let mover = app.session.active().unwrap().active_layer.unwrap(); + if before == "empty" { + app.run("layer.new.layer", json!({"name": "empty"})).unwrap(); + } else { + let st = app.session.active().unwrap(); + let target = st.doc.walk().into_iter().find(|(_, _, l)| l.name == "target").unwrap().2.id; + app.run("layer.select", json!({"layer": target.0})).unwrap(); + } + app.ui.tool = Tool::Move; + app.ui.tool_options.move_auto_select = true; + let m = egui::Modifiers::NONE; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, m); + assert_eq!(app.session.active().unwrap().active_layer, Some(mover), "{before}: Auto-Select picked the mover"); + let gesture = app.prefs_rt.snap.as_ref().map(|s| s.gesture.clone()); + assert_eq!(gesture, Some(Gesture::Move { rect: [40.0, 40.0, 90.0, 80.0] }), "{before}: the box is the mover's"); + // The mover's left edge lands 3 px right of the target's and snaps to it. + crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 323.0, y: 100.0, pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 323.0, y: 100.0 }, m); + assert_eq!(mover_bounds(&app).x0, 300, "{before}: snapped to the target's edge"); + } +} + +#[test] +fn view_snap_off_blocks_smart_guide_snapping() { + let mut app = app_with_box(); + app.ui.tool = Tool::Move; + app.ui.view.show.smart_guides = true; + app.ui.extras.snap = false; + app.ui.tool_options.move_auto_select = false; + let m = egui::Modifiers::NONE; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 323.0, y: 100.0 }, m); + assert_eq!(mover_bounds(&app).x0, 303, "View › Snap off must not snap via smart guides"); +} + +#[test] +fn ctrl_or_snap_off_disables_snapping() { + let mut app = app_with_box(); + app.ui.tool = Tool::Move; + app.ui.view.show.smart_guides = false; + app.ui.extras.snap = false; + // The presses land beside the moved layer: keep moving it (no Auto-Select pick). + app.ui.tool_options.move_auto_select = false; + let m = egui::Modifiers::NONE; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 323.0, y: 100.0 }, m); + assert_eq!(mover_bounds(&app).x0, 303); + app.ui.extras.snap = true; + let ctrl = egui::Modifiers { ctrl: true, ..Default::default() }; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 62.0, y: 60.0 }, ctrl); + assert_eq!(mover_bounds(&app).x0, 305, "no snap to the target's right edge at 350? (moved freely)"); + // Ctrl only at the press (Ctrl-click auto-select) doesn't turn snapping off for the drag. + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, ctrl); + crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 61.0, y: 60.0, pressure: 1.0 }, m); + assert!(!app.prefs_rt.snap.as_ref().is_some_and(|s| s.disabled)); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 61.0, y: 60.0 }, m); + // ⌘ on the Mac is not the override. + let cmd = egui::Modifiers { mac_cmd: true, command: true, ..Default::default() }; + assert!(!override_held(cmd) && override_held(ctrl)); +} + +#[test] +fn snap_off_disables_all_snapping_even_with_smart_guides() { + let mut app = app_with_box(); + app.ui.tool = Tool::Move; + assert!(app.ui.view.show.smart_guides); + app.ui.extras.snap = false; + app.ui.tool_options.move_auto_select = false; + let m = egui::Modifiers::NONE; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 323.0, y: 100.0 }, m); + assert_eq!(mover_bounds(&app).x0, 303); + assert!(app.prefs_rt.snap_lines.is_empty()); +} + +#[test] +fn marquee_corner_snaps_to_guides_and_document_edges() { + let mut app = app_with_box(); + app.run("view.newGuide", json!({"orientation": "vertical", "position": 120})).unwrap(); + app.ui.tool = Tool::RectMarquee; + let m = egui::Modifiers::NONE; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 3.0, y: 2.0, pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 116.0, y: 50.0 }, m); + let sel = app.session.active().unwrap().doc.selection.as_ref().unwrap().content_bounds(); + assert_eq!((sel.x0, sel.y0, sel.x1), (0, 0, 120)); + // Zoomed in to 800%, 4 px is beyond the 1 px threshold: no snap. + app.ui.views[0].zoom = 8.0; + // (Deselect first: a drag starting inside the selection would move it.) + app.run("select.deselect", json!({})).unwrap(); + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 10.0, pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 116.0, y: 50.0 }, m); + let sel = app.session.active().unwrap().doc.selection.as_ref().unwrap().content_bounds(); + assert_eq!(sel.x1, 116); +} + +/// Space while drawing a marquee, Object Selection box or shape moves it: its edges snap, not +/// only the corner under the pointer; with Space released the corner snaps again. +#[test] +fn drawing_repositioned_with_space_snaps_its_edges() { + for tool in [Tool::RectMarquee, Tool::EllipseMarquee, Tool::ObjectSelection, Tool::Rectangle, Tool::Line] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.sync_views(); + app.ui.views[0].zoom = 1.0; + app.ui.views[0].fit_pending = false; + app.run("view.newGuide", json!({"orientation": "vertical", "position": 220})).unwrap(); + app.ui.tool = tool; + let m = egui::Modifiers::NONE; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 100.0, y: 100.0, pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 150.0, y: 140.0, pressure: 1.0 }, m); + // Space down: the 50 × 40 box moves so its left edge lands 4 px short of the guide; + // the pointer corner (x = 266) is near nothing. + app.drag.as_mut().unwrap().reposition = true; + crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 266.0, y: 140.0, pressure: 1.0 }, m); + assert_eq!(app.drag.as_ref().unwrap().start, [220.0, 100.0], "{tool:?}"); + if tool != Tool::RectMarquee { + continue; + } + // Space up: sizing resumes and the corner snaps to the document's right edge. + app.drag.as_mut().unwrap().reposition = false; + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 397.0, y: 140.0 }, m); + let sel = app.session.active().unwrap().doc.selection.as_ref().unwrap().content_bounds(); + assert_eq!((sel.x0, sel.y0, sel.x1, sel.y1), (220, 100, 400, 140)); + } +} + +/// Dragging inside a selection with a marquee or lasso moves the outline (⌘ cuts the pixels +/// into a floating piece): its bounds snap, not the pointer. +#[test] +fn selection_drag_snaps_the_selection_bounds() { + for (tool, cut) in [(Tool::RectMarquee, false), (Tool::Lasso, false), (Tool::RectMarquee, true)] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 300, "background": "white"})).unwrap(); + app.sync_views(); + app.ui.views[0].zoom = 1.0; + app.ui.views[0].fit_pending = false; + app.run("view.newGuide", json!({"orientation": "vertical", "position": 220})).unwrap(); + app.run("select.rect", json!({"x": 100, "y": 100, "width": 50, "height": 40})).unwrap(); + app.ui.tool = tool; + let m = if cut { egui::Modifiers { mac_cmd: true, command: true, ..Default::default() } } else { egui::Modifiers::NONE }; + // The outline's right edge lands 2 px short of the guide (x = 218); the pointer ends + // 7 px from the document centre (x = 200), which it must not snap to. + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 125.0, y: 117.0, pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 193.0, y: 117.0, pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 193.0, y: 117.0 }, m); + let st = app.session.active().unwrap(); + let off = photocraft_engine::float_cmds::floating(st).map_or((0, 0), |f| f.offset); + let sel = st.doc.selection.as_ref().unwrap().content_bounds().translate(off.0, off.1); + assert_eq!((sel.x0, sel.y0, sel.x1, sel.y1), (170, 100, 220, 140), "{tool:?} cut: {cut}"); + } +} + +#[test] +fn distort_corner_snaps_from_positive_grab_offset() { + distort_corner_snaps_from_grab_offset([4.0, 3.0]); +} + +#[test] +fn distort_corner_snaps_from_negative_grab_offset() { + distort_corner_snaps_from_grab_offset([-4.0, -3.0]); +} + +fn distort_corner_snaps_from_grab_offset(offset: [f64; 2]) { + let mut app = app_with_box(); + app.run("view.newGuide", json!({"orientation": "vertical", "position": 110})).unwrap(); + app.run("view.newGuide", json!({"orientation": "horizontal", "position": 30})).unwrap(); + let ctx = egui::Context::default(); + crate::menus::invoke(&mut app, &ctx, "edit.transform.distort", json!({})).unwrap(); + let before = app.ui.transform.as_ref().unwrap().quad; + let press = [before[1][0] + offset[0], before[1][1] + offset[1]]; + // The proposed corner is (108, 32); the pointer keeps its original grab offset. + let release = [108.0 + offset[0], 32.0 + offset[1]]; + let m = egui::Modifiers::NONE; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: press[0], y: press[1], pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Move { x: release[0], y: release[1], pressure: 1.0 }, m); + let moved = app.ui.transform.as_ref().unwrap().quad; + assert_eq!(moved[1], [110.0, 30.0], "grab offset {offset:?}"); + assert_eq!([moved[0], moved[2], moved[3]], [before[0], before[2], before[3]]); + assert!(app.prefs_rt.snap_lines.iter().any(|l| l.vertical && l.pos == 110.0 && l.kind == SnapKind::Guide)); + assert!(app.prefs_rt.snap_lines.iter().any(|l| !l.vertical && l.pos == 30.0 && l.kind == SnapKind::Guide)); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: release[0], y: release[1] }, m); + assert_eq!(app.ui.transform.as_ref().unwrap().quad, moved); + assert!(app.prefs_rt.snap.is_none() && app.prefs_rt.snap_lines.is_empty()); +} + +fn app_with_corner_guides(menu: &str) -> PhotocraftApp { + let mut app = app_with_box(); + app.run("view.newGuide", json!({"orientation": "vertical", "position": 110})).unwrap(); + app.run("view.newGuide", json!({"orientation": "horizontal", "position": 30})).unwrap(); + crate::menus::invoke(&mut app, &egui::Context::default(), menu, json!({})).unwrap(); + app +} + +fn move_corner(app: &mut PhotocraftApp, index: usize, offset: [f64; 2], end: [f64; 2], down: egui::Modifiers, moving: egui::Modifiers) { + let corner = app.ui.transform.as_ref().unwrap().quad[index]; + crate::canvas::tool_event(app, ToolEvent::Down { x: corner[0] + offset[0], y: corner[1] + offset[1], pressure: 1.0 }, down); + crate::canvas::tool_event(app, ToolEvent::Move { x: end[0] + offset[0], y: end[1] + offset[1], pressure: 1.0 }, moving); +} + +#[test] +fn distort_corner_respects_guide_axes_tolerance_and_toggles() { + for (snap, shown, guides, end, expected) in [ + (true, true, true, [108.0, 20.0], [110.0, 20.0]), + (true, true, true, [100.0, 32.0], [100.0, 30.0]), + (true, true, true, [100.0, 20.0], [100.0, 20.0]), + (false, true, true, [108.0, 32.0], [108.0, 32.0]), + (true, false, true, [108.0, 32.0], [108.0, 32.0]), + (true, true, false, [108.0, 32.0], [108.0, 32.0]), + ] { + let mut app = app_with_corner_guides("edit.transform.distort"); + app.ui.extras.snap = snap; + app.ui.extras.guides = shown; + app.ui.view.snap_to.guides = guides; + move_corner(&mut app, 1, [4.0, 3.0], end, egui::Modifiers::NONE, egui::Modifiers::NONE); + assert_eq!(app.ui.transform.as_ref().unwrap().quad[1], expected, "Snap: {snap}, shown: {shown}, guides: {guides}, proposed: {end:?}"); + assert!(app.prefs_rt.snap_lines.iter().all(|line| (if line.vertical { expected[0] } else { expected[1] } - line.pos).abs() < 1e-6)); + } +} + +#[test] +fn free_transform_command_corner_snaps_with_the_real_grab_offset() { + let windows = egui::Modifiers { command: true, ctrl: true, ..egui::Modifiers::NONE }; + let mac = egui::Modifiers { command: true, mac_cmd: true, ..egui::Modifiers::NONE }; + for m in [windows, mac] { + for offset in [[4.0, 3.0], [-4.0, -3.0], [0.0, 0.0]] { + for down in [m, egui::Modifiers::NONE] { + let mut app = app_with_corner_guides("edit.freeTransform"); + let before = app.ui.transform.as_ref().unwrap().quad; + move_corner(&mut app, 1, offset, [108.0, 32.0], down, m); + let moved = app.ui.transform.as_ref().unwrap().quad; + assert_eq!(moved[1], [110.0, 30.0], "{m:?}, press {down:?}, offset {offset:?}"); + assert_eq!([moved[0], moved[2], moved[3]], [before[0], before[2], before[3]]); + assert_eq!(app.prefs_rt.snap_lines.len(), 2); + assert!(!app.prefs_rt.snap.as_ref().unwrap().disabled); + } + } + } +} + +#[test] +fn control_alone_still_disables_snapping_in_menu_distort() { + let mut app = app_with_corner_guides("edit.transform.distort"); + let ctrl = egui::Modifiers { ctrl: true, ..egui::Modifiers::NONE }; + move_corner(&mut app, 1, [4.0, 3.0], [108.0, 32.0], ctrl, ctrl); + assert_eq!(app.ui.transform.as_ref().unwrap().quad[1], [108.0, 32.0]); + assert!(app.prefs_rt.snap.as_ref().unwrap().disabled); + assert!(app.prefs_rt.snap_lines.is_empty()); +} + +#[test] +fn skew_control_corner_keeps_its_axis_instead_of_snapping_as_distort() { + let ctrl = egui::Modifiers { command: true, ctrl: true, ..egui::Modifiers::NONE }; + for legacy in [false, true] { + for (menu, expected, snapping) in [ + ("edit.transform.skew", [[40.0, 40.0], [108.0, 40.0], [90.0, 80.0], [40.0, 80.0]], false), + ("edit.transform.distort", [[40.0, 40.0], [110.0, 30.0], [90.0, 80.0], [40.0, 80.0]], true), + ("edit.transform.perspective", [[22.0, 40.0], [108.0, 40.0], [90.0, 80.0], [40.0, 80.0]], false), + ] { + let mut app = app_with_corner_guides(menu); + app.run("prefs.set", json!({"path": "general.useLegacyFreeTransform", "value": legacy})).unwrap(); + let doc = app.session.active().unwrap().doc.clone(); + let past = app.session.active().unwrap().history.past_len(); + let prefs = serde_json::to_value(app.session.prefs()).unwrap(); + // Ctrl arrives after the raw, off-centre press, as on the actual canvas path. + move_corner(&mut app, 1, [4.0, 3.0], [108.0, 32.0], egui::Modifiers::NONE, ctrl); + assert_eq!(app.ui.transform.as_ref().unwrap().quad, expected, "{menu}, legacy {legacy}"); + assert_eq!(!app.prefs_rt.snap.as_ref().unwrap().disabled, snapping, "{menu}"); + assert_eq!(app.prefs_rt.snap_lines.len(), if snapping { 2 } else { 0 }, "{menu}"); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 112.0, y: 35.0 }, ctrl); + assert_eq!(app.ui.transform.as_ref().unwrap().quad, expected, "release preserves {menu}"); + crate::transform_tool::cancel(&mut app); + assert!(app.ui.transform.is_none() && app.prefs_rt.snap.is_none() && app.prefs_rt.snap_lines.is_empty()); + assert!(std::sync::Arc::ptr_eq(&app.session.active().unwrap().doc, &doc), "cancel preserves {menu}'s document"); + assert_eq!(app.session.active().unwrap().history.past_len(), past, "cancel preserves {menu}'s history"); + assert_eq!(serde_json::to_value(app.session.prefs()).unwrap(), prefs, "{menu} does not change preferences"); + } + } +} + +#[test] +fn skew_control_corner_on_editable_type_slides_the_whole_edge() { + let ctrl = egui::Modifiers { command: true, ctrl: true, ..egui::Modifiers::NONE }; + for legacy in [false, true] { + let mut app = app_with_box(); + app.run("type.create", json!({"x": 40, "y": 60, "text": "Hello"})).unwrap(); + app.run("prefs.set", json!({"path": "general.useLegacyFreeTransform", "value": legacy})).unwrap(); + crate::menus::invoke(&mut app, &egui::Context::default(), "edit.transform.skew", json!({})).unwrap(); + let before = app.ui.transform.as_ref().unwrap().quad; + let end = [before[1][0] + 18.0, before[1][1] - 8.0]; + let doc = app.session.active().unwrap().doc.clone(); + let past = app.session.active().unwrap().history.past_len(); + move_corner(&mut app, 1, [2.0, 1.0], end, egui::Modifiers::NONE, ctrl); + let mut expected = before; + expected[0][0] += 18.0; + expected[1][0] += 18.0; + assert_eq!(app.ui.transform.as_ref().unwrap().quad, expected, "type remains affine, legacy {legacy}"); + assert!(app.prefs_rt.snap.as_ref().unwrap().disabled && app.prefs_rt.snap_lines.is_empty()); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: end[0] + 2.0, y: end[1] + 1.0 }, ctrl); + assert_eq!(app.ui.transform.as_ref().unwrap().quad, expected, "release preserves the type's edge"); + crate::transform_tool::cancel(&mut app); + assert!(std::sync::Arc::ptr_eq(&app.session.active().unwrap().doc, &doc)); + assert_eq!(app.session.active().unwrap().history.past_len(), past); + } +} + +#[test] +fn transform_non_distortion_gestures_keep_control_snap_override() { + let ctrl = egui::Modifiers { command: true, ctrl: true, ..egui::Modifiers::NONE }; + let perspective = egui::Modifiers { alt: true, shift: true, ..ctrl }; + for (menu, press, m) in [ + ("edit.freeTransform", [65.0, 40.0], ctrl), // edge + ("edit.freeTransform", [65.0, 60.0], ctrl), // pivot + ("edit.freeTransform", [55.0, 52.0], ctrl), // inside + ("edit.freeTransform", [90.0, 40.0], perspective), + ("edit.transform.perspective", [90.0, 40.0], ctrl), + ("edit.transform.warp", [90.0, 40.0], ctrl), + ("edit.contentAwareScale", [90.0, 40.0], ctrl), + ] { + let mut app = app_with_corner_guides(menu); + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: press[0], y: press[1], pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 108.0, y: 32.0, pressure: 1.0 }, m); + assert!(app.prefs_rt.snap.as_ref().unwrap().disabled, "{menu}, {press:?}, {m:?}"); + assert!(app.prefs_rt.snap_lines.is_empty(), "{menu}, {press:?}"); + } +} + +#[test] +fn editable_type_refusal_keeps_control_snap_override() { + let mut app = app_with_box(); + app.run("type.create", json!({"x": 40, "y": 60, "text": "Hello"})).unwrap(); + crate::menus::invoke(&mut app, &egui::Context::default(), "edit.freeTransform", json!({})).unwrap(); + let corner = app.ui.transform.as_ref().unwrap().quad[1]; + app.run("view.newGuide", json!({"orientation": "vertical", "position": corner[0] + 20.0})).unwrap(); + app.run("view.newGuide", json!({"orientation": "horizontal", "position": corner[1] - 10.0})).unwrap(); + let ctrl = egui::Modifiers { command: true, ctrl: true, ..egui::Modifiers::NONE }; + move_corner(&mut app, 1, [0.0, 0.0], [corner[0] + 18.0, corner[1] - 8.0], ctrl, ctrl); + assert!(app.prefs_rt.snap.as_ref().unwrap().disabled); + assert!(app.prefs_rt.snap_lines.is_empty()); + let q = app.ui.transform.as_ref().unwrap().quad; + assert_eq!(q[0][1], q[1][1], "editable type still scales, rather than distorting"); +} + +#[test] +fn a_foldover_constraint_never_claims_a_guide_alignment() { + let mut app = app_with_corner_guides("edit.transform.distort"); + app.run("view.newGuide", json!({"orientation": "horizontal", "position": 100})).unwrap(); + let before = app.ui.transform.as_ref().unwrap().quad; + move_corner(&mut app, 0, [4.0, 3.0], [108.0, 98.0], egui::Modifiers::NONE, egui::Modifiers::NONE); + let q = app.ui.transform.as_ref().unwrap().quad; + assert_ne!(q[0], [110.0, 100.0], "the guide intersection would fold the quad"); + assert_eq!([q[1], q[2], q[3]], [before[1], before[2], before[3]]); + for i in 0..4 { + let (a, b, c) = (q[i], q[(i + 1) % 4], q[(i + 2) % 4]); + assert!((b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0]) > 0.0, "still convex: {q:?}"); + } + assert!(app.prefs_rt.snap_lines.is_empty(), "{:?}", app.prefs_rt.snap_lines); +} + +#[test] +fn a_snapped_distort_commits_one_undoable_transform() { + let mut app = app_with_corner_guides("edit.transform.distort"); + let before_doc = app.session.active().unwrap().doc.clone(); + let before_bounds = mover_bounds(&app); + let past = app.session.active().unwrap().history.past_len(); + move_corner(&mut app, 1, [4.0, 3.0], [108.0, 32.0], egui::Modifiers::NONE, egui::Modifiers::NONE); + assert!(std::sync::Arc::ptr_eq(&app.session.active().unwrap().doc, &before_doc), "preview does not edit the document"); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 112.0, y: 35.0 }, egui::Modifiers::NONE); + crate::transform_tool::commit(&mut app); + assert!(!app.ui.status_error, "{}", app.ui.status); + let after_bounds = mover_bounds(&app); + assert_ne!(after_bounds, before_bounds); + assert_eq!(app.session.active().unwrap().history.past_len(), past + 1); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(mover_bounds(&app), before_bounds); + app.run("edit.redo", json!({})).unwrap(); + assert_eq!(mover_bounds(&app), after_bounds); +} + +#[test] +fn transform_corner_press_is_not_adjusted_near_an_original_guide() { + for menu in ["edit.transform.distort", "edit.freeTransform"] { + let mut app = app_with_corner_guides(menu); + app.run("view.newGuide", json!({"orientation": "vertical", "position": 95})).unwrap(); + app.run("view.newGuide", json!({"orientation": "horizontal", "position": 45})).unwrap(); + let raw = ToolEvent::Down { x: 94.0, y: 43.0, pressure: 1.0 }; + let ToolEvent::Down { x, y, .. } = filter_event(&mut app, raw, egui::Modifiers::NONE) else { panic!("still a press") }; + assert_eq!([x, y], [94.0, 43.0], "{menu}: filtering must preserve the handle press"); + } +} + +#[test] +fn corner_near_original_guides_keeps_the_raw_press_in_the_canvas_path() { + for (menu, m) in + [("edit.transform.distort", egui::Modifiers::NONE), ("edit.freeTransform", egui::Modifiers { command: true, ctrl: true, ..egui::Modifiers::NONE })] + { + let mut app = app_with_corner_guides(menu); + app.run("view.newGuide", json!({"orientation": "vertical", "position": 95})).unwrap(); + app.run("view.newGuide", json!({"orientation": "horizontal", "position": 45})).unwrap(); + let before = app.ui.transform.as_ref().unwrap().quad; + // The command modifier is added after Down, including in Free Transform. + move_corner(&mut app, 1, [4.0, 3.0], [93.0, 43.0], egui::Modifiers::NONE, m); + let q = app.ui.transform.as_ref().unwrap().quad; + assert_eq!(q[1], [95.0, 45.0], "{menu}"); + assert_eq!([q[0], q[2], q[3]], [before[0], before[2], before[3]]); + } +} + +#[test] +fn corner_distortion_does_not_snap_to_guides_hidden_by_view_flags() { + for menu in ["edit.transform.distort", "edit.freeTransform"] { + for hide_extras in [false, true] { + let mut app = app_with_corner_guides(menu); + if hide_extras { + app.ui.view.extras = false; + } else { + app.ui.view.show.canvas_guides = false; + } + let m = egui::Modifiers { command: true, ctrl: true, ..egui::Modifiers::NONE }; + move_corner(&mut app, 1, [4.0, 3.0], [108.0, 32.0], m, m); + assert_eq!(app.ui.transform.as_ref().unwrap().quad[1], [108.0, 32.0], "{menu}, hide Extras: {hide_extras}"); + assert!(app.prefs_rt.snap_lines.is_empty()); + } + } +} + +#[test] +fn marquee_and_corner_snapping_share_the_canvas_guide_visibility() { + for (extras, canvas_guides, shown) in [(true, true, true), (false, true, false), (true, false, false)] { + let mut app = app_with_box(); + app.run("view.newGuide", json!({"orientation": "vertical", "position": 110})).unwrap(); + app.run("view.newGuide", json!({"orientation": "horizontal", "position": 30})).unwrap(); + app.ui.tool = Tool::RectMarquee; + // Isolate guides: the mover's y=40 edge would otherwise be a valid fallback target. + app.ui.view.snap_to.layers = false; + app.ui.view.snap_to.document_bounds = false; + app.ui.view.snap_to.grid = false; + app.ui.view.extras = extras; + app.ui.view.show.canvas_guides = canvas_guides; + let m = egui::Modifiers::NONE; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 12.0, y: 12.0, pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 108.0, y: 32.0 }, m); + let rect = app.session.active().unwrap().doc.selection.as_ref().unwrap().content_bounds(); + assert_eq!((rect.x0, rect.y0), (12, 12)); + assert_eq!((rect.x1, rect.y1), if shown { (110, 30) } else { (108, 32) }, "Extras: {extras}, Canvas Guides: {canvas_guides}"); + } +} + +#[test] +fn distort_corner_does_not_snap_to_layer_edges() { + let mut app = app_with_box(); + let ctx = egui::Context::default(); + crate::menus::invoke(&mut app, &ctx, "edit.transform.distort", json!({})).unwrap(); + let q = app.ui.transform.as_ref().unwrap().quad; + let m = egui::Modifiers::NONE; + // Drag the top-right corner to 2 px short of the target's right edge (x = 350). + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: q[1][0], y: q[1][1], pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 348.0, y: q[1][1] }, m); + let q = app.ui.transform.as_ref().unwrap().quad; + assert_eq!(q[1][0], 348.0, "the corner stays where it was dropped"); + assert!(app.prefs_rt.snap_lines.is_empty()); +} + +#[test] +fn free_transform_drags_and_handles_snap() { + let mut app = app_with_box(); + let ctx = egui::Context::default(); + crate::menus::invoke(&mut app, &ctx, "edit.freeTransform", json!({})).unwrap(); + assert!(app.ui.transform.is_some()); + let m = egui::Modifiers::NONE; + // Drag from inside the box (40..90 × 40..80) so its left edge lands 2 px from x = 300. + // (Away from the centre, which holds the reference point.) + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 50.0, y: 50.0, pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 312.0, y: 50.0 }, m); + let q = app.ui.transform.as_ref().unwrap().quad; + assert!((q[0][0] - 300.0).abs() < 1e-6, "{q:?}"); + // The right-edge handle snaps to the target's right edge (x = 350). + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: q[1][0], y: (q[1][1] + q[2][1]) / 2.0, pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 353.0, y: 60.0 }, m); + let q = app.ui.transform.as_ref().unwrap().quad; + assert!((q[1][0] - 350.0).abs() < 1e-6, "{q:?}"); + crate::transform_tool::commit(&mut app); + assert_eq!(mover_bounds(&app).x0, 300); +} + +/// #5751: a Rectangle drawn on a 1080 px canvas, then resized with Free Transform under the +/// Move tool. With Snap Vector Tools and Transforms to Pixel Grid on (the default) the box's +/// edges stay on whole pixels: the grab offset and a proportional scale used to leave them at +/// 20.6 and 1040.4. Off, the box follows the pointer exactly. +#[test] +fn free_transform_of_a_shape_keeps_whole_pixels() { + for grid in [true, false] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 1080, "height": 1080, "resolution": 72})).unwrap(); + app.run("prefs.set", json!({"path": "tools.snapVectorToolsAndTransformsToPixelGrid", "value": grid})).unwrap(); + app.sync_views(); + app.ui.views[0].zoom = 0.6; + app.ui.views[0].fit_pending = false; + app.ui.tool = Tool::Rectangle; + let m = egui::Modifiers::NONE; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 40.0, y: 31.0, pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 300.0, y: 700.0, pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 481.0, y: 1000.0 }, m); + app.ui.tool = Tool::Move; + crate::menus::invoke(&mut app, &egui::Context::default(), "edit.freeTransform", json!({})).unwrap(); + let whole = |q: [[f64; 2]; 4]| q.iter().flatten().all(|v| v.fract() == 0.0); + // The left edge handle, grabbed 1.3 px inside, dropped away from any snap target. + let q = app.ui.transform.as_ref().unwrap().quad; + let mid_y = (q[0][1] + q[3][1]) / 2.0; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: q[0][0] + 1.3, y: mid_y, pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 60.0, y: mid_y, pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 80.6, y: mid_y }, m); + let q = app.ui.transform.as_ref().unwrap().quad; + assert_eq!(whole(q), grid, "grid {grid}: left edge {q:?}"); + // The bottom-right corner scaled proportionally (the default), off any snap target. + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: q[2][0], y: q[2][1], pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 450.4, y: 900.1 }, m); + let q = app.ui.transform.as_ref().unwrap().quad; + assert_eq!(whole(q), grid, "grid {grid}: corner {q:?}"); + crate::transform_tool::commit(&mut app); + let st = app.session.active().unwrap(); + let photocraft_doc::LayerContent::Shape(sh) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!("a shape layer") }; + let (x0, y0, x1, y1) = sh.path.control_bounds().unwrap(); + if grid { + for v in [x0, y0, x1, y1] { + assert!((v - v.round()).abs() < 1e-6, "committed shape {:?}", (x0, y0, x1, y1)); + } + } + } +} + +#[test] +fn guides_snap_to_layer_edges() { + let mut app = app_with_box(); + assert_eq!(snap_guide(&mut app, true, 297.0), 300.0); + assert_eq!(snap_guide(&mut app, false, 150.0), 150.0, "document centre"); + assert_eq!(snap_guide(&mut app, false, 170.0), 170.0); + // Dragging an existing guide with the Move tool while a selection is active still snaps to the selection. + app.run("view.newGuide", json!({"orientation": "vertical", "position": 10})).unwrap(); + app.run("select.rect", json!({"x": 100, "y": 100, "width": 50, "height": 40})).unwrap(); + app.ui.tool = Tool::Move; + begin(&mut app, [10.0, 50.0], egui::Modifiers::NONE); + assert_eq!(apply(&mut app, [98.0, 50.0], egui::Modifiers::NONE)[0], 100.0); + app.ui.extras.snap = false; + assert_eq!(snap_guide(&mut app, true, 297.0), 297.0); +} + +/// The cached ruler-guide targets follow the Snap To options, not just document edits. +#[test] +fn guide_targets_follow_snap_to_options() { + let mut app = app_with_box(); + app.run( + "prefs.set", + json!({"values": {"guidesGridAndSlices.gridlineEvery": 100, "guidesGridAndSlices.gridUnit": "pixels", "guidesGridAndSlices.subdivisions": 4}}), + ) + .unwrap(); + app.ui.extras.grid = false; + assert_eq!(snap_guide(&mut app, true, 23.0), 23.0, "grid hidden"); + app.ui.extras.grid = true; + app.ui.view.snap_to.grid = true; + assert_eq!(snap_guide(&mut app, true, 23.0), 25.0, "grid shown"); + app.ui.extras.grid = false; + app.ui.view.snap_to.layers = false; + assert_eq!(snap_guide(&mut app, true, 297.0), 297.0, "Snap To Layers off"); +} + +#[test] +fn percentage_grid_snaps_at_separate_axis_intervals() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 1280, "height": 720})).unwrap(); + app.ui.extras.grid = true; + app.ui.view.snap_to.grid = true; + app.run( + "prefs.set", + json!({"values": {"guidesGridAndSlices.gridlineEvery": 20, "guidesGridAndSlices.gridUnit": "percent", "guidesGridAndSlices.subdivisions": 2}}), + ) + .unwrap(); + let opts = options(&app); + assert_eq!(opts.grid_step, [128.0, 72.0]); + let targets = SnapTargets::from_document(&app.session.active().unwrap().doc, &opts, &[]); + assert_eq!(targets.snap_point([127.0, 71.0], 2.0).0, [128.0, 72.0]); +} + +#[test] +fn grid_snapping_uses_preferences() { + let mut app = app_with_box(); + app.ui.extras.grid = true; + app.run( + "prefs.set", + json!({"values": {"guidesGridAndSlices.gridlineEvery": 100, "guidesGridAndSlices.gridUnit": "pixels", "guidesGridAndSlices.subdivisions": 4}}), + ) + .unwrap(); + assert_eq!(options(&app).grid_step, [25.0; 2]); + app.ui.tool = Tool::RectMarquee; + let m = egui::Modifiers::NONE; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 152.0, y: 127.0, pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 199.0, y: 176.0 }, m); + let sel = app.session.active().unwrap().doc.selection.as_ref().unwrap().content_bounds(); + assert_eq!((sel.x0, sel.y0, sel.x1, sel.y1), (150, 125, 200, 175)); +} diff --git a/crates/ui-egui/src/canvas/start_screen.rs b/crates/ui-egui/src/canvas/start_screen.rs new file mode 100644 index 0000000000..d22295886c --- /dev/null +++ b/crates/ui-egui/src/canvas/start_screen.rs @@ -0,0 +1,177 @@ +use super::tabs::{open_on_double_click, paint_dots}; +use super::*; + +/// The Home screen's card is this wide when the canvas has room, and as wide as the canvas when it doesn't. +const HOME_CARD_WIDTH: f32 = 460.0; + +/// Least width of each of the Home screen's New document and Open buttons. +const HOME_BUTTON_WIDTH: f32 = 190.0; + +/// Space between the Home screen's two buttons. +const HOME_BUTTON_GAP: f32 = 12.0; + +pub(super) fn start_screen(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + let t = crate::theme::Tokens::get(ui.ctx()); + let area = ui.available_rect_before_wrap(); + paint_dots(ui, area, app.session.prefs().interface.show_canvas_dots); + open_on_double_click(app, ui, area); + // File › Open Recent, newest first (on the web there are no paths to reopen). + let show_recent = app.session.prefs().interface.show_home_recent_files; + let recent: Vec = + if cfg!(target_arch = "wasm32") || !show_recent { Vec::new() } else { app.ui.recent_files.iter().take(HOME_RECENT).cloned().collect() }; + let recent_h = if recent.is_empty() { 0.0 } else { 34.0 + recent.len() as f32 * HOME_RECENT_ROW }; + // A tiling window manager can give the canvas less room than the card wants: shrink the card + // to fit, and stack the buttons when they don't fit side by side. + let new_label = crate::shortcuts::command_label(app, "New document…", "file.new"); + let open_label = crate::shortcuts::command_label(app, "Open…", "file.open"); + let card_width = HOME_CARD_WIDTH.min(area.width()); + let button_width = HOME_BUTTON_WIDTH.max(crate::widgets::button_width(ui, &[&new_label, &open_label])); + let side_by_side = 2.0 * button_width + HOME_BUTTON_GAP <= card_width; + // Stacked buttons take one more row. + let stacked_h = if side_by_side { 0.0 } else { 44.0 }; + let card = Rect::from_center_size(area.center(), egui::vec2(card_width, 330.0 + recent_h + stacked_h)); + ui.scope_builder(egui::UiBuilder::new().max_rect(card), |ui| { + ui.vertical_centered(|ui| { + ui.horizontal(|ui| { + let title = ui.painter().layout_no_wrap(tl!("PhotoCraft").into(), crate::theme::semibold(38.0), t.text); + let by = ui.painter().layout_no_wrap(tl!("open source").into(), egui::FontId::proportional(13.0), t.text_faint); + let total = title.size().x + by.size().x + 10.0; + ui.add_space(((card.width() - total) / 2.0).max(0.0)); + let (r, _) = ui.allocate_exact_size(title.size(), Sense::hover()); + ui.painter().galley(r.min, title, t.text); + let (r2, _) = ui.allocate_exact_size(egui::vec2(by.size().x + 10.0, r.height()), Sense::hover()); + ui.painter().galley(egui::pos2(r2.left() + 10.0, r.bottom() - by.size().y - 8.0), by, t.text_faint); + }); + ui.add_space(6.0); + ui.label(egui::RichText::new(tl!("Create a new document or open an existing file.")).color(t.text_dim).size(14.0)); + ui.add_space(22.0); + let (mut new_clicked, mut open_clicked) = (false, false); + if side_by_side { + ui.horizontal(|ui| { + ui.add_space(((card.width() - 2.0 * button_width - HOME_BUTTON_GAP) / 2.0).max(0.0)); + ui.spacing_mut().item_spacing.x = HOME_BUTTON_GAP; + new_clicked = crate::widgets::primary_button(ui, &new_label, button_width).clicked(); + open_clicked = crate::widgets::secondary_button(ui, &open_label, button_width).clicked(); + }); + } else { + new_clicked = crate::widgets::primary_button(ui, &new_label, button_width).clicked(); + ui.add_space(HOME_BUTTON_GAP); + open_clicked = crate::widgets::secondary_button(ui, &open_label, button_width).clicked(); + } + if new_clicked { + let fields = app.new_document_fields(); + app.ui.open_dialog(crate::state::DialogKind::NewDocument, fields); + } + if open_clicked { + let _ = app.open_dialog_file(); + } + ui.add_space(22.0); + ui.horizontal(|ui| { + let msg = start_screen_drop_hint(app); + let g = ui.painter().layout_no_wrap(msg.to_string(), egui::FontId::proportional(12.5), t.text_faint); + ui.add_space(((card.width() - g.size().x - 24.0) / 2.0).max(0.0)); + let (r, _) = ui.allocate_exact_size(egui::vec2(18.0, 18.0), Sense::hover()); + crate::icons::paint(ui, r, "image", 15.0, t.text_faint); + ui.label(egui::RichText::new(msg).color(t.text_faint)); + }); + if !recent.is_empty() { + ui.add_space(22.0); + home_recent(app, ui, &recent); + } + ui.add_space(26.0); + crate::links::discord_button(app, ui, 190.0); + ui.add_space(10.0); + crate::links::link_row(app, ui); + }); + }); +} + +/// Wayland has no native file drops (winit 0.30, #386), so the hint offers File › Open and paste. +pub(super) fn start_screen_drop_hint(app: &PhotocraftApp) -> std::borrow::Cow<'static, str> { + if app.services.is_wayland { + crate::i18n::fmt(tl!("Use File › Open, or paste a copied image with {paste}."), &[("paste", &crate::notices::paste_hint(app))]).into() + } else { + tl!("Drop an image or PSD anywhere to open it.").into() + } +} + +/// Recent files listed on the Home screen. +const HOME_RECENT: usize = 6; + +/// Height of one Home-screen recent-file row. +const HOME_RECENT_ROW: f32 = 30.0; + +/// The Home screen's "Recent" list: file name, its folder on the right, click to open. The +/// hovered row shows a × that takes it off the list, and right-click offers Remove from Recent +/// and Clear Recent Files (#2691). +fn home_recent(app: &mut PhotocraftApp, ui: &mut egui::Ui, recent: &[String]) { + let t = crate::theme::Tokens::get(ui.ctx()); + let width = 380.0; + ui.horizontal(|ui| { + // Line the heading up with the file icons. + ui.add_space(((ui.available_width() - width) / 2.0).max(0.0) + 8.0); + ui.label(egui::RichText::new(tl!("Recent")).font(crate::theme::semibold(12.5)).color(t.text_dim)); + }); + ui.add_space(4.0); + let mut open = None; + let mut remove = None; + let mut clear = false; + for path in recent { + let name = crate::file_open::display_name(path); + let folder = std::path::Path::new(path).parent().map(|d| d.to_string_lossy().into_owned()).unwrap_or_default(); + let (row, resp) = ui.allocate_exact_size(egui::vec2(width, HOME_RECENT_ROW), Sense::click()); + // The × sits on top of the row, so the row counts as hovered while the pointer is on it. + let hovered = ui.rect_contains_pointer(row); + if hovered { + ui.painter().rect_filled(row, t.radius_sm, t.hover); + } + let close = Rect::from_center_size(egui::pos2(row.right() - 16.0, row.center().y), egui::vec2(22.0, 22.0)); + let right = if hovered { close.left() - 4.0 } else { row.right() - 10.0 }; + let icon = Rect::from_center_size(egui::pos2(row.left() + 16.0, row.center().y), egui::vec2(16.0, 16.0)); + crate::icons::paint(ui, icon, "file", 14.0, t.text_dim); + let x = row.left() + 32.0; + let name_g = crate::tab_strip::elided(ui, &name, egui::FontId::proportional(12.5), t.text, 170.0); + let name_w = name_g.size().x; + ui.painter().galley(egui::pos2(x, row.center().y - name_g.size().y / 2.0), name_g, t.text); + let folder_max = (right - (x + name_w + 14.0)).max(0.0); + if folder_max > 20.0 && !folder.is_empty() { + let fg = crate::tab_strip::elided(ui, &folder, egui::FontId::proportional(11.5), t.text_faint, folder_max); + ui.painter().galley(egui::pos2(right - fg.size().x, row.center().y - fg.size().y / 2.0), fg, t.text_faint); + } + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &name)); + let resp = resp.on_hover_text(path).on_hover_cursor(egui::CursorIcon::PointingHand); + if hovered { + let x = ui.interact(close, resp.id.with("remove"), Sense::click()); + let label = crate::i18n::fmt(tl!("Remove {name} from Recent"), &[("name", &name)]); + x.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &label)); + let color = crate::icons::button_chrome(ui, close, false, x.hovered()); + crate::icons::paint(ui, close, "x", 12.0, color); + if x.on_hover_text(tl!("Remove from Recent")).clicked() { + remove = Some(path.clone()); + } + } + if resp.clicked() && remove.is_none() { + open = Some(path.clone()); + } + resp.context_menu(|ui| { + if ui.button(tl!("Remove from Recent")).clicked() { + remove = Some(path.clone()); + ui.close(); + } + if ui.button(tl!("Clear Recent Files")).clicked() { + clear = true; + ui.close(); + } + }); + } + if clear { + app.clear_recent(); + } else if let Some(path) = remove { + app.remove_recent(&path); + } + if let Some(path) = open + && let Err(e) = app.open_path(&path) + { + app.open_failed(&crate::file_open::display_name(&path), &e); + } +} diff --git a/crates/ui-egui/src/canvas/strokes.rs b/crates/ui-egui/src/canvas/strokes.rs new file mode 100644 index 0000000000..c970c39a20 --- /dev/null +++ b/crates/ui-egui/src/canvas/strokes.rs @@ -0,0 +1,655 @@ +use super::display::{canvas_display, display_image}; +use super::drag::Drag; +use super::textures::{canvas_texture_options, shown_as_document}; +use super::view_xform::ViewXform; +use super::*; + +pub(crate) struct ClonePreviewCache { + pub(super) key: String, + texture: egui::TextureHandle, +} + +/// A transient source image beneath the brush outline; never part of the document render. +pub(super) fn draw_clone_preview(app: &mut PhotocraftApp, painter: &egui::Painter, xf: &ViewXform, at: [f64; 2], output: Option) { + use photocraft_engine::presets::clone_source::{Mapping, overlay_blend, transform_matrix}; + let overlay = app.session.presets.clone.overlay.clone(); + if app.ui.tool != Tool::CloneStamp || !overlay.show || (overlay.auto_hide && app.drag.is_some()) { + return; + } + let slot = app.session.presets.clone.active().clone(); + let Some(source) = slot.source else { return }; + let radius = f64::from(app.session.tools.brush.size) / 2.0; + if !radius.is_finite() || radius <= 0.0 || radius > 500.0 || !at.iter().all(|v| v.is_finite() && v.abs() < 1_000_000.0) { + return; + } + let stroke_start = app.drag.as_ref().map(|d| d.start); + let anchor = if app.ui.tool_options.clone_aligned { slot.anchor.or(stroke_start) } else { stroke_start }.unwrap_or(at); + let map = + Mapping { source: (source[0], source[1]), anchor: (anchor[0], anchor[1]), m: transform_matrix(slot.scale, slot.rotation, slot.flip_h, slot.flip_v) }; + let rect = DRect::new((at[0] - radius).floor() as i32, (at[1] - radius).floor() as i32, (at[0] + radius).ceil() as i32, (at[1] + radius).ceil() as i32); + let Some(st) = app.session.active() else { return }; + let (display, display_key) = canvas_display(app, &st.doc, output); + // A shaped tip (sampled bitmap, or a rotated / flattened round one) clips the overlay to its + // outline instead of a circle, as Photoshop does with Clipped on. + let tip_rings = if overlay.clipped { crate::brush_cursor::rings(painter.ctx(), &app.session.tools.brush, true) } else { None }; + let tip_key = tip_rings.as_ref().map(|r| { + use std::hash::{Hash, Hasher}; + let mut h = std::collections::hash_map::DefaultHasher::new(); + r.iter().flatten().for_each(|p| (p[0].to_bits(), p[1].to_bits()).hash(&mut h)); + (h.finish(), radius.to_bits(), at.map(f64::to_bits)) + }); + let key = format!( + "{:?}:{}:{:?}:{rect:?}:{map:?}:{}:{}:{}:{}:{}:{tip_key:?}", + st.doc.id, st.revision, st.active_layer, app.ui.tool_options.clone_sample, display_key, overlay.invert, overlay.blend, app.ui.view.pattern_preview + ); + if app.clone_preview.as_ref().is_none_or(|c| c.key != key) { + let Ok(mut buf) = + photocraft_engine::retouch_cmds::clone_preview_periodic(&app.session, rect, &map, &app.ui.tool_options.clone_sample, app.ui.view.pattern_preview) + else { + return; + }; + if overlay.invert { + for px in &mut buf.px { + for c in px.iter_mut().take(3) { + *c = 1.0 - *c; + } + } + } + // Darken, Lighten and Difference mix the source with the image under the brush (the + // composite, whatever Sample reads), so Difference turns black where they line up. + if overlay.blend != "normal" { + let here = Mapping { source: (0.0, 0.0), anchor: (0.0, 0.0), m: [1.0, 0.0, 0.0, 1.0] }; + let Ok(under) = photocraft_engine::retouch_cmds::clone_preview_periodic(&app.session, rect, &here, "all", app.ui.view.pattern_preview) else { + return; + }; + for (px, d) in buf.px.iter_mut().zip(&under.px) { + *px = overlay_blend(&overlay.blend, *px, *d); + } + } + if let Some(rings) = &tip_rings { + let mask = crate::brush_cursor::tip_mask(rings, at, radius, [rect.x0, rect.y0, rect.x1, rect.y1]); + for (px, inside) in buf.px.iter_mut().zip(mask) { + if !inside { + *px = [0.0; 4]; + } + } + } + let image = display_image(display.as_deref(), &buf); + match app.clone_preview.as_mut() { + Some(cache) => { + cache.texture.set(image, canvas_texture_options(1)); + cache.key = key; + } + None => app.clone_preview = Some(ClonePreviewCache { key, texture: painter.ctx().load_texture("clone-preview", image, canvas_texture_options(1)) }), + } + } + let Some(cache) = &app.clone_preview else { return }; + let tint = Color32::from_white_alpha((overlay.opacity.clamp(0.0, 100.0) * 2.55).round() as u8); + // A textured triangle fan provides a circular clip, including mirrored canvas views. + let mut mesh = egui::Mesh::with_texture(cache.texture.id()); + let vertex = |x: f64, y: f64| egui::epaint::Vertex { + pos: xf.to_screen(x as f32, y as f32), + uv: pos2((x - f64::from(rect.x0)) as f32 / rect.width() as f32, (y - f64::from(rect.y0)) as f32 / rect.height() as f32), + color: tint, + }; + if !overlay.clipped || tip_rings.is_some() { + for (x, y) in [(rect.x0, rect.y0), (rect.x1, rect.y0), (rect.x1, rect.y1), (rect.x0, rect.y1)] { + mesh.vertices.push(vertex(f64::from(x), f64::from(y))); + } + mesh.indices.extend_from_slice(&[0, 1, 2, 0, 2, 3]); + painter.add(egui::Shape::mesh(mesh)); + return; + } + mesh.vertices.push(vertex(at[0], at[1])); + for i in 0..=64 { + let angle = f64::from(i) * std::f64::consts::TAU / 64.0; + mesh.vertices.push(vertex(at[0] + radius * angle.cos(), at[1] + radius * angle.sin())); + } + for i in 1..=64 { + mesh.indices.extend_from_slice(&[0, i, i + 1]); + } + painter.add(egui::Shape::mesh(mesh)); +} + +/// The engine's live stroke of a tool: the Brush, Pencil and Eraser paint dabs; the Clone Stamp, +/// Healing Brush and History Brush composite their source. +pub(super) enum EngineStroke { + Brush(Box), + Retouch(photocraft_engine::retouch_cmds::LiveRetouch), + Dab(photocraft_engine::retouch_cmds::LiveDab), + Mixer(Box), +} + +impl EngineStroke { + /// The brush engine's strokes can change while the pointer is held still (see + /// `LiveStroke::wants_time`); the retouch strokes don't. + pub(super) fn wants_time(&self) -> bool { + match self { + EngineStroke::Brush(l) => l.wants_time(), + EngineStroke::Mixer(l) => l.wants_time(), + EngineStroke::Retouch(_) | EngineStroke::Dab(_) => false, + } + } + + pub(super) fn doc(&self) -> &std::sync::Arc { + match self { + Self::Brush(s) => &s.doc, + Self::Retouch(s) => &s.doc, + Self::Dab(s) => &s.doc, + Self::Mixer(s) => &s.doc, + } + } + fn bounds(&self) -> DRect { + match self { + Self::Brush(s) => s.bounds(), + Self::Retouch(s) => s.bounds(), + Self::Dab(s) => s.bounds(), + Self::Mixer(s) => s.bounds(), + } + } + fn push(&mut self, pts: &[photocraft_engine::paint::StrokePoint]) -> photocraft_engine::Result { + match self { + Self::Brush(s) => s.push(pts), + Self::Retouch(s) => s.push(pts), + Self::Dab(s) => s.push(pts), + Self::Mixer(s) => s.push(pts), + } + } + /// The jitter seed the commit must reuse (the Clone Stamp's comes from the session brush). + fn seed(&self) -> Option { + match self { + Self::Brush(s) => Some(s.seed), + Self::Mixer(s) => Some(s.seed), + Self::Retouch(_) => None, + Self::Dab(_) => None, + } + } +} + +/// A stroke shown while it is drawn: the engine renders the real result onto a copy of the +/// document, and the canvas redraws only what each step changed. +pub(crate) struct LiveStroke { + pub(super) preview_failed: bool, + pub(super) stroke: EngineStroke, + pub(super) doc: photocraft_doc::DocId, + revision: u64, + /// Preview key of the stroke; step `n` displays as `key + n`. + pub(super) key: u64, + /// Damage of each step (step 0 = the document before the stroke). + pub(super) damage: Vec, + /// Drag points rendered so far. + fed: usize, +} + +impl LiveStroke { + pub(super) fn display_key(&self) -> u64 { + self.key + self.damage.len() as u64 + } + + /// What changed since the canvas showed preview `key` (0 = the document before the stroke). + pub(super) fn since(&self, key: u64) -> Option { + let seen = if key == 0 { 0 } else { usize::try_from(key.checked_sub(self.key)?).ok()? }; + Some(self.damage.get(seen..)?.iter().fold(DRect::EMPTY, |a, r| a.union(r))) + } +} + +/// A live stroke whose pixels its commit took over (`"fromLive"`): document `doc` at `revision` +/// holds exactly the live stroke's last step, so a cache that showed step `n` of it only misses +/// the steps after `n` (step 0 = the document before the stroke: everything). +pub(crate) struct CommittedStroke { + pub(crate) doc: photocraft_doc::DocId, + pub(crate) revision: u64, + key: u64, + damage: Vec, + /// What the commit repaints beyond the stroke whatever a cache showed: the layer's whole + /// composite when effects laid out over its frame moved with it (a Gradient Overlay spans the + /// grown layer, #4053; `photocraft_compose::relayout_damage`). + pub(super) relayout: DRect, +} + +impl CommittedStroke { + #[cfg(test)] + pub(crate) fn for_test(key: u64, damage: Vec) -> Self { + Self { doc: photocraft_doc::DocId(0), revision: 0, key, damage, relayout: DRect::EMPTY } + } + + /// The raw preview key of the live stroke's last step: what a cache showed at release. + #[cfg(test)] + pub(crate) fn last_key(&self) -> u64 { + self.key + self.damage.len() as u64 + } + + /// What a cache that showed raw preview `key` of this stroke at the revision before misses. + pub(crate) fn since(&self, key: u64) -> Option { + let seen = if key == 0 { 0 } else { usize::try_from(key.checked_sub(self.key)?).ok()? }; + Some(self.damage.get(seen..)?.iter().fold(DRect::EMPTY, |a, r| a.union(r))) + } +} + +/// The live stroke on document `idx`, while it is current. +pub(super) fn live_stroke(app: &PhotocraftApp, idx: usize) -> Option<&LiveStroke> { + let st = app.session.documents().get(idx)?; + app.live_stroke.as_ref().filter(|l| app.drag.is_some() && l.doc == st.doc.id && l.revision == st.revision) +} + +/// `paint.stroke` params for a Brush/Eraser drag (shared by the live preview and the commit). The +/// stroke smoothing is the session brush's (the options bar's Smoothing %). +pub(super) fn stroke_params(app: &PhotocraftApp, d: &Drag, points: &[Vec]) -> serde_json::Value { + let tool = d.tool; + let mut p = json!({ "points": points, "erase": d.erase, "zoom": app.point_zoom(), "target": paint_target(app) }); + if d.clear { + p["mode"] = json!("clear"); + } + if tool == Tool::Pencil { + p["autoErase"] = json!(app.ui.tool_options.pencil_auto_erase); + } + // Block mode: the engine sizes the square from the stroke's zoom (16 / zoom px, #2770). + if crate::eraser_ui::block_mode(app, tool) { + p["block"] = json!(true); + } + p +} + +/// Tools whose strokes the engine renders while they are drawn (`LiveStroke`). +pub(crate) fn strokes_live(tool: Tool) -> bool { + matches!( + tool, + Tool::Brush + | Tool::Pencil + | Tool::MixerBrush + | Tool::Eraser + | Tool::ColorReplacement + | Tool::Blur + | Tool::Sharpen + | Tool::Smudge + | Tool::Dodge + | Tool::Burn + | Tool::Sponge + ) || live_retouch_command(tool).is_some() +} + +/// The Spot Healing Brush's stroke while dragging: Photoshop shows the area it will heal as a +/// semi-opaque dark overlay (an image overlay, the same in every UI theme) and heals on release. +pub(crate) const SPOT_HEALING_TRAIL: Color32 = Color32::from_black_alpha(128); + +/// The retouching tools drawn live (`LiveRetouch`; the Background Eraser's and an Impressionist +/// Pattern Stamp's dabs are laid one by one, `LiveDab`), by the command their live stroke +/// previews. The Healing Brush shows its texture while drawing; the blend comes on release. +pub(super) fn live_retouch_command(tool: Tool) -> Option<&'static str> { + match tool { + Tool::CloneStamp => Some("paint.cloneStamp"), + Tool::Healing => Some("paint.healingBrush"), + Tool::HistoryBrush => Some("paint.historyBrush"), + Tool::PatternStamp => Some("paint.patternStamp"), + Tool::BackgroundEraser => Some("paint.backgroundEraser"), + _ => None, + } +} + +/// The command a live-stroking tool commits: the Pencil's (and the Pencil- or Block-mode +/// Eraser's) `paint.pencil`, else `paint.stroke`. +pub(crate) fn stroke_command(app: &PhotocraftApp, tool: Tool) -> &'static str { + if tool == Tool::Pencil || crate::eraser_ui::pencil_mode(app, tool) || crate::eraser_ui::block_mode(app, tool) { "paint.pencil" } else { "paint.stroke" } +} + +pub(super) fn begin_live_stroke(app: &PhotocraftApp) -> Option { + static STROKES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let st = app.session.active()?; + let d = app.drag.as_ref()?; + let stroke = if d.tool == Tool::MixerBrush { + let points = app.stylus.stroke_points(&d.points); + let p = stroke_params(app, d, points.get(..1)?); + EngineStroke::Mixer(Box::new(photocraft_engine::brush_cmds::mixer_live::LiveMixer::begin(&app.session, &p).ok()?)) + } else if d.tool == Tool::ColorReplacement { + // The params `retouch_ui::finish_stroke` commits. + let mut p = crate::retouch_ui::color_replacement_params(app); + p["points"] = json!(d.points); + EngineStroke::Dab(photocraft_engine::brush_cmds::live_color_replacement(&app.session, &p).ok()?) + } else if let Some((cmd, mut p)) = crate::retouch_ui::dab_params(app, d.tool) { + // The params `retouch_ui::finish_stroke` commits; Sample All Layers isn't previewed. + p["points"] = json!(d.points); + p["target"] = paint_target(app); + EngineStroke::Dab(photocraft_engine::retouch_cmds::LiveDab::begin(&app.session, cmd, &p).ok()?) + } else if d.tool == Tool::PatternStamp { + // The params `retouch_ui::finish_stroke` commits. + let mut p = crate::retouch_ui::pattern_stamp_params(app, &d.points); + p["points"] = json!(d.points); + p["target"] = paint_target(app); + if app.ui.tool_options.pattern_stamp_impressionist { + EngineStroke::Dab(photocraft_engine::retouch_cmds::live_pattern_impressionist(&app.session, &p).ok()?) + } else { + EngineStroke::Retouch(photocraft_engine::retouch_cmds::LiveRetouch::begin(&app.session, "paint.patternStamp", &p).ok()?) + } + } else if d.tool == Tool::BackgroundEraser { + // The params `eraser_ui::finish_stroke` commits (layer pixels only). + let p = crate::eraser_ui::background_eraser_params(app, &d.points); + EngineStroke::Dab(photocraft_engine::eraser_cmds::live_background_eraser(&app.session, &p).ok()?) + } else if let Some(cmd) = live_retouch_command(d.tool) { + // The params `retouch_ui::finish_stroke` commits. + let mut p = if d.tool == Tool::HistoryBrush { crate::retouch_ui::history_brush_params(app) } else { crate::retouch_ui::clone_params(app)? }; + p["points"] = json!(d.points); + p["target"] = paint_target(app); + EngineStroke::Retouch(photocraft_engine::retouch_cmds::LiveRetouch::begin(&app.session, cmd, &p).ok()?) + } else { + let p = stroke_params(app, d, &app.stylus.stroke_points(&d.points)); + EngineStroke::Brush(Box::new(photocraft_engine::brush_cmds::LiveStroke::begin_with(&app.session, stroke_command(app, d.tool), &p).ok()?)) + }; + let n = STROKES.fetch_add(1, std::sync::atomic::Ordering::Relaxed) & 0xff_ffff; + let damage = vec![stroke.bounds()]; + Some(LiveStroke { + stroke, + doc: st.doc.id, + revision: st.revision, + key: (1 << 44) | (n << 20), + damage, + fed: if d.tool == Tool::MixerBrush { 1 } else { d.points.len() }, + preview_failed: false, + }) +} + +/// Cancel uncommitted mixer paint when its document, tool or input context goes away. +pub(crate) fn cancel_mixer_on_context_change(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { + if !app.drag.as_ref().is_some_and(|drag| drag.tool == Tool::MixerBrush) { + return false; + } + let changed = app.ui.tool != Tool::MixerBrush + || app.live_stroke.as_ref().is_some_and(|live| !app.session.active().is_some_and(|st| st.doc.id == live.doc && st.revision == live.revision)); + if changed || ctx.input_mut(|input| input.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) { + app.drag = None; + app.live_stroke = None; + return true; + } + false +} + +/// Render the drag points the live stroke hasn't seen yet, with the pen pressure, tilt and +/// rotation the commit's `paint.stroke` gets for them. +pub(super) fn feed_live_stroke(app: &mut PhotocraftApp) { + // A batched move replays several samples in one frame and calls this once at the end, so the + // per-sample calls from `tool_event` are skipped (see `canvas_view`). + if app.defer_live_stroke { + return; + } + let (Some(l), Some(d)) = (app.live_stroke.as_mut(), app.drag.as_ref()) else { return }; + if l.preview_failed { + return; + } + let pose = &app.stylus.stroke; + // The same times `stroke_points` gives the commit (from the drag's first point). + let t0 = app.stylus.point_ms(0); + let pts: Vec<_> = (l.fed..d.points.len()) + .filter_map(|i| { + let p = d.points.get(i)?; + let t = pose.get(i).or(pose.last()).copied().unwrap_or_default(); + let mut sp = photocraft_engine::paint::StrokePoint::new(p[0], p[1], p[2] as f32); + (sp.tilt_x, sp.tilt_y, sp.rotation) = (t[0], t[1], t[2]); + sp.time = app.stylus.point_ms(i) - t0; + Some(sp) + }) + .collect(); + if pts.is_empty() { + return; + } + l.fed = d.points.len(); + let started = crate::gpu_canvas::now_ms(); + match l.stroke.push(&pts) { + Ok(r) => l.damage.push(r), + Err(e) => { + if d.tool == Tool::MixerBrush { + // Keep the last valid preview and its document/revision guard. All input + // stays in the drag; release replays it without the preview tile budget. + l.preview_failed = true; + app.ui.status = e.to_string(); + app.ui.status_error = true; + } else { + app.live_stroke = None; + } + } + } + app.stroke_trace.stroke(crate::gpu_canvas::now_ms() - started); +} + +/// The points the live retouching stroke has rendered. +#[cfg(test)] +pub(crate) fn live_retouch_points(app: &PhotocraftApp) -> Option> { + match &app.live_stroke.as_ref()?.stroke { + EngineStroke::Retouch(l) => Some(l.points().to_vec()), + _ => None, + } +} + +/// Offer the Clone Stamp's or History Brush's live stroke, or a Dodge, Burn, Sponge, Blur, Sharpen +/// or Smudge one, with the drag points it hasn't rendered yet, to the command +/// `retouch_ui::finish_stroke` commits, which then takes its pixels instead of rendering the +/// stroke again. +pub(super) fn offer_live_retouch(app: &mut PhotocraftApp, d: &Drag) { + let dab = crate::retouch_ui::dab_params(app, d.tool).is_some(); + if !dab && !matches!(d.tool, Tool::CloneStamp | Tool::HistoryBrush) { + return; + } + let Some(LiveStroke { stroke, fed, .. }) = app.live_stroke.take() else { return }; + let rest: Vec<_> = d.points.get(fed..).unwrap_or_default().iter().map(|q| photocraft_engine::paint::StrokePoint::new(q[0], q[1], q[2] as f32)).collect(); + // A refused offer (the brush changed mid-stroke, say) leaves the commit to render the stroke. + match stroke { + EngineStroke::Retouch(mut live) if !dab => { + if rest.is_empty() || live.push(&rest).is_ok() { + let _ = app.session.offer_live_retouch(live); + } + } + EngineStroke::Dab(mut live) if dab => { + if rest.is_empty() || live.push(&rest).is_ok() { + let _ = app.session.offer_live_dab(live); + } + } + _ => {} + } +} + +/// A pen tap (a drag still at its one press point when released) paints its dab at the highest +/// pressure the pen reached during the contact, not just the first sample's (#1798). A mouse is +/// unchanged at full pressure. +pub(super) fn tap_at_peak_pressure(app: &mut PhotocraftApp) { + if app.stylus.sample().is_none() { + return; + } + let peak = f64::from(app.stylus.tap_pressure()); + let mut refresh_mixer = false; + if let Some(d) = app.drag.as_mut().filter(|d| d.points.len() == 1) + && let Some(p) = d.points.first_mut() + { + refresh_mixer = d.tool == Tool::MixerBrush && peak > p[2]; + p[2] = p[2].max(peak); + } + if refresh_mixer { + app.live_stroke = begin_live_stroke(app); + } +} + +/// While a stroke is held still, its point repeats this often (in ms) so time-based brush +/// features (airbrush build-up, smoothing catch-up) keep going, as when the pen moves. +pub(super) const HOLD_REPEAT_MS: f64 = 16.0; + +/// Is the live stroke one that changes while the pointer is held still (airbrush Build-up, or +/// smoothing catching up)? Only then does a held pointer repeat its point and keep repainting. +pub(super) fn stroke_wants_time(app: &PhotocraftApp) -> bool { + app.live_stroke.as_ref().is_some_and(|l| l.stroke.wants_time()) +} + +/// Time of sample `k` of the `n` samples a frame delivered, spread evenly after `base` (the +/// previous point) up to `now` (this frame): egui's pointer events carry no timestamps. +pub(crate) fn spread_ms(base: f64, now: f64, k: usize, n: usize) -> f64 { + // Not after `base` (or not comparable, NaN): every sample takes the frame time. + if n == 0 || now.partial_cmp(&base) != Some(std::cmp::Ordering::Greater) { + return now; + } + base + (now - base) * (k + 1) as f64 / n as f64 +} + +/// Tools whose gesture follows a freehand path (a polyline of the input points), so every pointer +/// sample the OS delivered improves the result. Other tools are driven by the pointer's latest +/// position (endpoints, anchors, guides), so feeding them a whole frame's moves only repeats work. +pub(crate) fn freehand_tool(tool: Tool) -> bool { + matches!( + tool, + Tool::Brush + | Tool::Pencil + | Tool::MixerBrush + | Tool::ColorReplacement + | Tool::Eraser + | Tool::BackgroundEraser + | Tool::HistoryBrush + | Tool::Remove + | Tool::ArtHistoryBrush + | Tool::SpotHealing + | Tool::Healing + | Tool::CloneStamp + | Tool::PatternStamp + | Tool::Blur + | Tool::Sharpen + | Tool::Smudge + | Tool::Dodge + | Tool::Burn + | Tool::Sponge + | Tool::Lasso + | Tool::MagneticLasso + | Tool::Patch + | Tool::ContentAwareMove + | Tool::QuickSelection + | Tool::FreeformPen + ) +} + +/// The pointer moves this frame delivered while `button` was held, in order. `down_at_start` is +/// whether the button was already down when the frame began. A move before a press or after a +/// release in the same frame is dropped, so a gesture never picks up input from outside its own +/// press..release interval. +pub(super) fn pointer_moves(events: &[egui::Event], button: egui::PointerButton, down_at_start: bool) -> Vec { + let mut down = down_at_start; + let mut out = Vec::new(); + for e in events { + match e { + egui::Event::PointerButton { button: b, pressed, .. } if *b == button => down = *pressed, + egui::Event::PointerMoved(p) if down => out.push(*p), + _ => {} + } + } + out +} + +/// Modifiers attached to the pointer event itself. Some input sources provide these without a +/// separate `ModifiersChanged` event, so use them for click gestures before falling back to the +/// frame-wide modifier state. +pub(super) fn pointer_button_modifiers(events: &[egui::Event], button: egui::PointerButton) -> Option { + events.iter().rev().find_map(|e| match e { + egui::Event::PointerButton { button: b, modifiers, .. } if *b == button => Some(*modifiers), + _ => None, + }) +} + +/// The line from the brush to the pointer while stroke smoothing lags (Pulled String Mode and +/// Stroke Catch-up, #3479): a dark underlay and a light line stay visible on any pixels, and a dot +/// marks the brush end. +pub(super) fn draw_smoothing_string(painter: &egui::Painter, xf: &ViewXform, (brush, pointer): ([f64; 2], [f64; 2])) { + let (a, b) = (xf.to_screen(brush[0] as f32, brush[1] as f32), xf.to_screen(pointer[0] as f32, pointer[1] as f32)); + if a.distance(b) < 2.0 { + return; + } + painter.line_segment([a, b], Stroke::new(3.0, Color32::from_black_alpha(110))); + painter.line_segment([a, b], Stroke::new(1.0, Color32::WHITE)); + painter.circle_filled(a, 2.5, Color32::WHITE); +} + +/// Commit a Brush, Pencil or Eraser drag. The live stroke already rendered it: its pixels are +/// offered to the commit (`Session::offer_live_stroke`), so release costs no second render, and +/// the canvas then refreshes only what it hadn't shown yet (`CommittedStroke`). +pub(super) fn commit_brush_stroke(app: &mut PhotocraftApp, d: &Drag) { + let live = app.live_stroke.take(); + let mut p = stroke_params(app, d, &app.stylus.stroke_points(&d.points)); + if let Some(seed) = live.as_ref().and_then(|l| l.stroke.seed()) { + p["seed"] = json!(seed); + } + let Some(mut l) = live else { + let _ = app.run(stroke_command(app, d.tool), p); + return; + }; + // Points the live stroke hasn't rendered yet (the release frame's last moves). + let t0 = app.stylus.point_ms(0); + let rest: Vec<_> = (l.fed..d.points.len()) + .filter_map(|i| { + let q = d.points.get(i)?; + let t = app.stylus.stroke.get(i).or(app.stylus.stroke.last()).copied().unwrap_or_default(); + let mut sp = photocraft_engine::paint::StrokePoint::new(q[0], q[1], q[2] as f32); + (sp.tilt_x, sp.tilt_y, sp.rotation) = (t[0], t[1], t[2]); + sp.time = app.stylus.point_ms(i) - t0; + Some(sp) + }) + .collect(); + if !rest.is_empty() { + match l.stroke.push(&rest) { + Ok(r) => l.damage.push(r), + // The live stroke can't show these points: the commit renders the stroke itself. + Err(_) => { + let _ = app.run(stroke_command(app, d.tool), p); + return; + } + } + } + let LiveStroke { stroke, doc, key, damage, .. } = l; + let before = app.session.documents().iter().find(|st| st.doc.id == doc).map(|st| st.doc.clone()); + if let EngineStroke::Brush(stroke) = stroke + && app.session.offer_live_stroke(*stroke).is_err() + { + app.session.clear_live_stroke(); + } + let started = crate::gpu_canvas::now_ms(); + let result = app.run(stroke_command(app, d.tool), p); + app.stroke_trace.stroke(crate::gpu_canvas::now_ms() - started); + app.session.clear_live_stroke(); + let Ok(r) = result else { return }; + let after = app.session.documents().iter().find(|st| st.doc.id == doc).map(|st| (st.revision, st.doc.clone())); + if r.get("fromLive").and_then(serde_json::Value::as_bool) == Some(true) + && let Some((revision, after)) = after + { + let relayout = before.map_or(DRect::EMPTY, |b| photocraft_compose::relayout_damage(&b, &after)); + app.committed_stroke = Some(CommittedStroke { doc, revision, key, damage, relayout }); + } else { + // Rendered again from scratch: the commit's damage rect refreshes the stroke. + let shown = CommittedStroke { doc, revision: 0, key, damage, relayout: DRect::EMPTY }; + // Raw preview key 0 = the document itself (its colour display folded in). + shown_as_document(app, doc, |k| shown.since(k).is_some()); + } +} + +/// Pencil (and a Pencil-mode Eraser) dabs sit on the pixel grid. Clicks anywhere inside one +/// pixel must produce the same point, or a ⇧-click line changes with the sub-pixel position. +pub(super) fn snap_aliased_tip(app: &PhotocraftApp, tool: Tool, x: f64, y: f64) -> (f64, f64) { + let pencil = tool == Tool::Pencil || crate::eraser_ui::pencil_mode(app, tool); + if !pencil { + return (x, y); + } + let (cx, cy) = photocraft_engine::paint::grid_center(x, y, app.session.tools.brush.size); + (f64::from(cx), f64::from(cy)) +} + +/// "mask" when the Layers panel targets (or the canvas shows) the active layer's mask, or the layer +/// is an adjustment layer with one (it has no pixels: #4298), else "pixels". +pub fn paint_target(app: &PhotocraftApp) -> serde_json::Value { + use photocraft_engine::channel_cmds::ChannelTarget; + let Some(st) = app.session.active() else { return json!("pixels") }; + // A targeted alpha channel (Channels panel) or Quick Mask mode wins over the layer. + match st.channel_view.target { + ChannelTarget::Alpha(i) if i < st.doc.channels.len() => return json!({ "channel": i }), + ChannelTarget::Composite if st.doc.quick_mask.is_some() => return json!("quickMask"), + ChannelTarget::LayerMask => return json!("mask"), + _ => {} + } + // A smart object's targeted (or shown) filter mask takes the paint (FILE-215-3). + if app.filter_mask_targeted() { + return json!("filterMask"); + } + let has_mask = st.active_layer.and_then(|id| st.doc.layer(id)).is_some_and(|l| l.mask.is_some()); + // Viewing the mask (⌥-click its thumbnail, #196) paints the mask. + let viewing = photocraft_engine::mask_view_cmds::current(st).is_some_and(|v| !v.filter); + let mask = app.ui.mask_target || viewing || crate::adjustment_layer_active(st); + json!(if mask && has_mask { "mask" } else { "pixels" }) +} diff --git a/crates/ui-egui/src/canvas/tabs.rs b/crates/ui-egui/src/canvas/tabs.rs new file mode 100644 index 0000000000..5f59f3c028 --- /dev/null +++ b/crates/ui-egui/src/canvas/tabs.rs @@ -0,0 +1,732 @@ +use super::start_screen::start_screen; +use super::textures::retain_gpu_documents; +use super::*; + +/// Tabs + canvas for the active document, or the start screen; then drops layers dragged onto +/// another document (`layer_transfer`). +pub fn document_area(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + crate::distort_ui::drop_foreign(app); + documents(app, ui); + crate::layer_transfer::finish(app, ui.ctx()); + // Once a frame, not per document view: the right-click or options-bar Brush Preset picker. + crate::paint_mouse::show_picker(app, ui.ctx()); +} + +/// Window › Arrange tiles: each document shown with its tile in `rect`, or `None` when the +/// active document fills the area. +pub(crate) fn arranged_cells(app: &PhotocraftApp, rect: Rect) -> Option> { + let idx = app.session.active_index()?; + let n = app.session.documents().len(); + let cells = crate::view_cmds::cells(&app.ui.view.arrange, rect, n)?; + // Each document keeps its tile: a click into another one activates it where it is (#6017; it + // used to move to the first tile). With more documents than tiles, the shown run stays put + // while the active document is in it, and otherwise slides only as far as it must. + let start = app.arrange_start.min(n.saturating_sub(cells.len())); + let start = if idx < start { idx } else { start.max((idx + 1).saturating_sub(cells.len())) }; + Some((start..n).zip(cells).collect()) +} + +fn documents(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + app.drop_canvas_rect = None; + app.tab_strip = None; + retain_gpu_documents(app); + crate::transform_tool::track_steps(app, ui.ctx()); + crate::cas_transform::tick(app, ui.ctx()); + crate::symmetry_ui::track(app, ui.ctx()); + let n = app.session.documents().len(); + // Files opening in the background (#210) have tabs before they have documents. + let opening = !app.jobs.opens.is_empty(); + if !opening && app.ui.chrome.shows_home(n, app.session.prefs().general.auto_show_home_screen) { + start_screen(app, ui); + return; + } + if n == 0 && !opening { + // Auto show the Home Screen is off: an empty workspace, like Photoshop. + let area = ui.available_rect_before_wrap(); + paint_dots(ui, area, app.session.prefs().interface.show_canvas_dots); + open_on_double_click(app, ui, area); + return; + } + if !app.ui.view.hides_tabs() || opening { + // Flat Spectrum tabs sit directly against the canvas. The parent's default vertical + // item spacing would otherwise leave a visible gap below the tab strip (#2188). + let spacing = ui.spacing().item_spacing.y; + if crate::theme::Tokens::get(ui.ctx()).pro { + ui.spacing_mut().item_spacing.y = 0.0; + } + app.tab_strip = Some(tabs(app, ui)); + ui.spacing_mut().item_spacing.y = spacing; + drop_slot_line(app, ui); + } + if let Some(job) = app.jobs.focus.or_else(|| (n == 0).then(|| app.jobs.opens.last().map(|o| o.job)).flatten()) { + crate::jobs_ui::open_card(app, ui, job); + return; + } + let Some(idx) = app.session.active_index() else { return }; + let rect = ui.available_rect_before_wrap(); + app.last_canvas_rect = rect; + app.drop_canvas_rect = Some(rect); + // Window › Arrange: tiled / n-up layouts show several documents side by side; the active one + // takes input, a click elsewhere activates that document. + if let Some(shown) = arranged_cells(app, rect) { + app.arrange_start = shown.first().map_or(0, |(d, _)| *d); + let t = crate::theme::Tokens::get(ui.ctx()); + for (d, cell) in shown { + let cell = cell.shrink(1.0); + let view = app.ui.views[d].clone(); + let v = canvas_view(app, ui, d, cell, view, d == idx); + if d != idx { + app.ui.views[d] = v; + if ui.input(|i| i.pointer.primary_pressed() && i.pointer.interact_pos().is_some_and(|p| cell.contains(p))) { + app.session.set_active(d); + } + } + let stroke = if d == idx { Stroke::new(1.5, t.accent) } else { Stroke::new(1.0, Color32::from_black_alpha(160)) }; + ui.painter().rect_stroke(cell, 0, stroke, egui::StrokeKind::Inside); + } + return; + } + let view = app.ui.views[idx].clone(); + canvas_view(app, ui, idx, rect, view, true); +} + +/// The tab strip; returns where its document tabs are. +pub(super) fn tabs(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> TabStrip { + let t = crate::theme::Tokens::get(ui.ctx()); + if t.pro { + return pro_tabs(app, ui); + } + let active = app.session.active_index(); + let tab_count = app.session.documents().len(); + let mut doc_tabs = Vec::with_capacity(tab_count); + let mut activate = None; + let mut close = None; + let mut tab_action = None; + let mut tab_move = None; + let mut tear_off = None; + let (mut focus_open, mut cancel_open) = (None, None); + let focused_open = app.jobs.focus.is_some(); + // Layers dragged over a tab show its document (`layer_transfer`). + let dragging = crate::layer_transfer::pointer_if_armed(app, ui.ctx()); + let mut drag_over = None; + let large_tabs = app.session.prefs().workspace.large_tabs; + let tab_h = if large_tabs { 34.0 } else { 26.0 }; + let font = crate::theme::medium(if large_tabs { 14.0 } else { 12.5 }); + let meta_font = egui::FontId::proportional(if large_tabs { 12.0 } else { 10.5 }); + // Files opening in the background (#210) are tabs too; they share the fit's index space, + // after the documents. + let opening = crate::jobs_ui::open_tabs(app); + // Every tab's natural width, whether or not it stays on the strip. + let natural: Vec = app + .session + .documents() + .iter() + .map(|st| { + let name = studio_tab_name(app, st); + ui.painter().layout_no_wrap(name, font.clone(), t.text).size().x + + ui.painter().layout_no_wrap(format!("{}/{}", mode_label(&st.doc), st.doc.depth.bits()), meta_font.clone(), t.text_faint).size().x + + STUDIO_TAB_PAD + }) + .chain(opening.iter().map(|(_, name, frac)| { + ui.painter().layout_no_wrap(name.clone(), font.clone(), t.text).size().x + + ui.painter().layout_no_wrap(format!("{:.0}%", frac * 100.0), meta_font.clone(), t.text_faint).size().x + + STUDIO_TAB_PAD + })) + .collect(); + let selected = app + .jobs + .focus + .and_then(|job| opening.iter().position(|(open, _, _)| *open == job)) + .map_or_else(|| app.session.active_index().unwrap_or(0), |p| tab_count + p); + let frame = egui::Frame::NONE.fill(t.canvas).inner_margin(egui::Margin { left: 8, right: 8, top: 6, bottom: 4 }).show(ui, |ui| { + let (row, _) = ui.allocate_exact_size(egui::vec2(ui.available_width(), tab_h), Sense::hover()); + let f = fit_doc_tabs(&natural, selected, row.width()); + let mut x = row.left(); + let mut placed: Vec<(usize, Rect)> = Vec::with_capacity(f.shown.len()); + for &(i, w) in &f.shown { + // The old horizontal layout put 4 pt between tabs; `w` carries it, the tab doesn't. + let r = Rect::from_min_size(egui::pos2(x, row.top()), egui::vec2((w - STUDIO_TAB_GAP).max(8.0), row.height())); + placed.push((i, r)); + x = r.right() + STUDIO_TAB_GAP; + } + for &(i, r) in placed.iter().filter(|(i, _)| *i < tab_count) { + let Some(st) = app.session.documents().get(i) else { continue }; + let sel = Some(i) == active && !focused_open; + let name = studio_tab_name(app, st); + let meta = format!("{}/{}", mode_label(&st.doc), st.doc.depth.bits()); + let natural_w = natural.get(i).copied().unwrap_or(0.0); + let meta_g = ui.painter().layout_no_wrap(meta, meta_font.clone(), t.text_faint); + let name_max = (r.width() - STUDIO_TAB_PAD + STUDIO_TAB_GAP - meta_g.size().x).max(1.0); + let name_g = crate::tab_strip::elided(ui, &name, font.clone(), t.text, name_max); + // The title was cut: the tooltip has the rest of it. + let cut = name_g.size().x + 0.5 < natural_w - STUDIO_TAB_PAD + STUDIO_TAB_GAP - meta_g.size().x; + let resp = ui.interact(r, ui.scope_id().with(("dtab", i)), Sense::click_and_drag()); + let saving = crate::jobs_ui::save_progress(app, st.doc.id); + resp.widget_info(|| { + let label = saving.as_ref().map_or_else(|| st.doc.name.clone(), |s| format!("{} - {s}", st.doc.name)); + egui::WidgetInfo::selected(egui::Role::Button, true, sel, label) + }); + doc_tabs.push((i, r)); + if sel { + ui.painter().rect_filled(r, t.radius_sm, t.card); + ui.painter().rect_stroke(r, t.radius_sm, Stroke::new(1.0, t.card_border), egui::StrokeKind::Inside); + } else if resp.hovered() { + ui.painter().rect_filled(r, t.radius_sm, t.hover.gamma_multiply(0.5)); + } + if dragging.is_some_and(|p| r.contains(p)) { + drag_over = Some(i); + ui.painter().rect_stroke(r, t.radius_sm, Stroke::new(1.5, t.accent), egui::StrokeKind::Inside); + } + let color = if sel { t.text } else { t.text_dim }; + let ny = r.center().y - name_g.size().y / 2.0; + ui.painter().galley_with_override_text_color(egui::pos2(r.left() + 10.0, ny), name_g.clone(), color); + ui.painter().galley(egui::pos2(r.left() + 16.0 + name_g.size().x, r.center().y - meta_g.size().y / 2.0), meta_g, t.text_faint); + let xr = Rect::from_center_size(egui::pos2(r.right() - 12.0, r.center().y), egui::vec2(16.0, 16.0)); + let xresp = ui.interact(xr, ui.scope_id().with(("dtabx", i)), Sense::click()); + if xresp.hovered() { + ui.painter().rect_filled(xr, 4.0, t.hover); + } + crate::icons::paint(ui, xr, "x", 11.0, if xresp.hovered() { t.text } else { t.text_faint }); + let resp = if cut { resp.on_hover_text(name) } else { resp }; + if tab_close_clicked(&resp, &xresp) { + close = Some(i); + } else if resp.clicked() { + activate = Some(i); + } + match tab_drag(ui, &resp, i, r, row, &placed, &t) { + Some(TabDrop::Move(to)) => tab_move = Some((i, to)), + Some(TabDrop::Float(at)) => tear_off = Some((i, at)), + None => {} + } + let has_path = st.path.is_some(); + resp.context_menu(|ui| { + tab_action = tab_context_menu(ui, i, tab_count, has_path); + }); + } + // Files opening in the background: a tab with a progress underline; × cancels. + for &(i, r) in placed.iter().filter(|(i, _)| *i >= tab_count) { + let Some((job, name, frac)) = opening.get(i - tab_count) else { continue }; + let sel = app.jobs.focus == Some(*job); + let meta_g = ui.painter().layout_no_wrap(format!("{:.0}%", frac * 100.0), meta_font.clone(), t.text_faint); + let name_g = crate::tab_strip::elided(ui, name, font.clone(), t.text, (r.width() - STUDIO_TAB_PAD + STUDIO_TAB_GAP - meta_g.size().x).max(1.0)); + let resp = ui.interact(r, ui.scope_id().with(("dtabjob", job.0)), Sense::click()); + if sel { + ui.painter().rect_filled(r, t.radius_sm, t.card); + ui.painter().rect_stroke(r, t.radius_sm, Stroke::new(1.0, t.card_border), egui::StrokeKind::Inside); + } else if resp.hovered() { + ui.painter().rect_filled(r, t.radius_sm, t.hover.gamma_multiply(0.5)); + } + let ny = r.center().y - name_g.size().y / 2.0; + ui.painter().galley_with_override_text_color(egui::pos2(r.left() + 10.0, ny), name_g.clone(), if sel { t.text } else { t.text_dim }); + ui.painter().galley(egui::pos2(r.left() + 16.0 + name_g.size().x, r.center().y - meta_g.size().y / 2.0), meta_g, t.text_faint); + crate::jobs_ui::tab_underline(ui, r, *frac, &t); + let xr = Rect::from_center_size(egui::pos2(r.right() - 12.0, r.center().y), egui::vec2(16.0, 16.0)); + let xresp = ui.interact(xr, ui.scope_id().with(("dtabjobx", job.0)), Sense::click()); + if xresp.hovered() { + ui.painter().rect_filled(xr, 4.0, t.hover); + } + crate::icons::paint(ui, xr, "x", 11.0, if xresp.hovered() { t.text } else { t.text_faint }); + if xresp.on_hover_text(tl!("Cancel opening")).clicked() { + cancel_open = Some(*job); + } else if resp.clicked() { + focus_open = Some(*job); + } + } + if !f.overflow.is_empty() { + // Pinned to the strip's right end, as Photoshop's is, not after the last tab (#8290). + let left = (row.right() - crate::tab_strip::CHEVRON_W).max(row.left()); + let r = Rect::from_min_size(egui::pos2(left, row.top()), egui::vec2(crate::tab_strip::CHEVRON_W, row.height())); + let labels: Vec<&str> = + app.session.documents().iter().map(|st| st.doc.name.as_str()).chain(opening.iter().map(|(_, name, _)| name.as_str())).collect(); + let mut picked = None; + // Like Photoshop's, the menu lists every open document, not only the hidden ones, and checks + // the active one (#4487). + let every: Vec = (0..labels.len()).collect(); + crate::tab_strip::overflow_button(ui, ui.scope_id().with("dtab-overflow"), r, tl!("More documents"), &labels, &every, Some(selected), &mut picked); + match picked { + Some(i) if i < tab_count => activate = Some(i), + Some(i) => focus_open = opening.get(i - tab_count).map(|(job, _, _)| *job).or(focus_open), + None => {} + } + } + }); + open_tab_clicks(app, activate, focus_open, cancel_open); + if let Some(i) = drag_over { + crate::layer_transfer::over_tab(app, ui.ctx(), i); + } + if let Some(i) = close { + let _ = crate::menus::invoke(app, ui.ctx(), "file.close", json!({"document": i})); + } + if let Some((from, to)) = tab_move + && let Err(e) = crate::menus::invoke(app, ui.ctx(), "document.move", json!({"document": from, "to": to})) + { + app.ui.status = e; + app.ui.status_error = true; + } + float_torn_off(app, ui.ctx(), tear_off); + if let Some((id, params)) = tab_action + && let Err(e) = crate::menus::invoke(app, ui.ctx(), id, params) + { + app.ui.status = e; + app.ui.status_error = true; + } + TabStrip { rect: frame.response.rect, tabs: doc_tabs } +} + +/// Whether a document tab was asked to close: its × was clicked (#619), or the tab was clicked +/// with the middle button (#2570), as in a browser. A middle click over the × counts too, so the +/// whole tab behaves the same way. Both strips share this rule; the caller routes it through the +/// guarded `file.close`, so a document with unsaved changes still gets the save prompt. +fn tab_close_clicked(resp: &egui::Response, xresp: &egui::Response) -> bool { + xresp.clicked() || xresp.middle_clicked() || resp.middle_clicked() +} + +/// All tab actions go through the same guarded File commands as the menu bar, including the +/// unsaved-changes prompt. The clicked tab is explicit even when another document is active. +pub(super) fn tab_context_items(index: usize, count: usize, has_path: bool) -> [(&'static str, &'static str, serde_json::Value, bool); 4] { + [ + ("Close", "file.close", json!({"document": index}), true), + ("Close Others", "file.closeOthers", json!({"document": index}), count > 1), + ("Close All", "file.closeAll", json!({}), true), + (crate::menus::reveal_label(), "file.revealInFinder", json!({"document": index}), has_path), + ] +} + +fn tab_context_menu(ui: &mut egui::Ui, index: usize, count: usize, has_path: bool) -> Option<(&'static str, serde_json::Value)> { + crate::widgets::menu_scroll(ui, |ui| { + ui.set_min_width(170.0); + for (label, id, params, enabled) in tab_context_items(index, count, has_path) { + if ui.add_enabled(enabled, egui::Button::new(tl!(label))).clicked() { + ui.close(); + return Some((id, params)); + } + } + None + }) +} + +/// Where a tab dragged to `x` would land: before the first shown tab whose middle is right of +/// `x`, else after the last shown tab (its document index + 1), like [`TabStrip::slot`]. +/// How far (points) above or below the tab strip a dragged tab must be to tear off (#3733). +pub(super) const TEAR_OFF: f32 = 24.0; + +/// Whether a tab dragged to `p` has left the strip and floats into its own window, as in +/// Photoshop; sideways drags along the strip still reorder (#217). +pub(super) fn torn_off(strip: Rect, p: egui::Pos2) -> bool { + p.y > strip.bottom() + TEAR_OFF || p.y < strip.top() - TEAR_OFF +} + +/// What a finished document-tab drag asks for. +#[derive(Clone, Copy, Debug, PartialEq)] +enum TabDrop { + /// Reorder the tab to this index. + Move(usize), + /// Float the document in its own OS window at this screen position (points), when known. + Float(Option<[f32; 2]>), +} + +/// Drag a document tab: along the strip it reorders (a line shows where it will land); off the +/// strip it tears off into a floating window that can go anywhere, other screens included +/// (an outline under the pointer shows it). Returns the drop once the drag ends. +fn tab_drag(ui: &egui::Ui, resp: &egui::Response, i: usize, r: Rect, strip: Rect, placed: &[(usize, Rect)], t: &crate::theme::Tokens) -> Option { + if resp.dragged() + && let Some(p) = resp.interact_pointer_pos() + { + if torn_off(strip, p) { + let ghost = Rect::from_min_size(p - egui::vec2(40.0, 12.0), egui::vec2(240.0, 160.0)); + let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Tooltip, ui.scope_id().with("tab-tear-off"))); + painter.rect_filled(ghost, t.radius_sm, t.accent.gamma_multiply(0.12)); + painter.rect_stroke(ghost, t.radius_sm, Stroke::new(1.5, t.accent), egui::StrokeKind::Inside); + } else { + tab_drop_line(ui, placed, p.x, t); + } + } + if !resp.drag_stopped() { + return None; + } + let p = resp.interact_pointer_pos().or_else(|| ui.input(|i| i.pointer.interact_pos())); + if let Some(p) = p.filter(|&p| torn_off(strip, p)) { + // The pointer is in this window's points; the OS wants screen coordinates. Keep the new + // window's title bar under the pointer, as the ghost showed. + let at = ui.ctx().input(|i| i.viewport().inner_rect).map(|inner| { + let s = inner.min + p.to_vec2() - egui::vec2(40.0, 12.0); + [s.x, s.y] + }); + return Some(TabDrop::Float(at)); + } + let to = tab_move_target(i, tab_drop_index(placed, p.map_or(r.center().x, |p| p.x))); + (to != i).then_some(TabDrop::Move(to)) +} + +/// Float a torn-off tab's document in its own window (`window.arrange.floatInWindow`). +fn float_torn_off(app: &mut PhotocraftApp, ctx: &egui::Context, tear_off: Option<(usize, Option<[f32; 2]>)>) { + let Some((doc, at)) = tear_off else { return }; + let params = match at { + Some(at) => json!({"document": doc, "position": at}), + None => json!({"document": doc}), + }; + if let Err(e) = crate::menus::invoke(app, ctx, "window.arrange.floatInWindow", params) { + app.ui.status = e; + app.ui.status_error = true; + } +} + +pub(super) fn tab_drop_index(placed: &[(usize, Rect)], x: f32) -> usize { + match placed.iter().find(|(_, r)| r.center().x >= x) { + Some(&(i, _)) => i, + None => placed.last().map_or(0, |&(i, _)| i.saturating_add(1)), + } +} + +/// The `document.move` target for dropping the tab at `from` at insertion index `k`: the slot +/// shifts down when the dragged tab itself is removed first; next to itself it stays put. +pub(super) fn tab_move_target(from: usize, k: usize) -> usize { + if k > from { k - 1 } else { k } +} + +/// The insertion line shown while a tab is dragged to reorder it. +fn tab_drop_line(ui: &egui::Ui, placed: &[(usize, Rect)], x: f32, t: &crate::theme::Tokens) { + match placed.iter().find(|(_, r)| r.center().x >= x) { + Some(&(_, r)) => crate::widgets::drop_line(ui, r, false, true, t), + None => { + if let Some(&(_, r)) = placed.last() { + crate::widgets::drop_line(ui, r, true, true, t); + } + } + } +} + +/// Apply tab-strip clicks: a document tab shows that document, an opening tab its progress, and +/// an opening tab's × cancels the open (closing the half-open tab). +fn open_tab_clicks( + app: &mut PhotocraftApp, + activate: Option, + focus_open: Option, + cancel_open: Option, +) { + if let Some(i) = activate { + app.session.set_active(i); + app.jobs.focus = None; + } + if let Some(job) = focus_open { + app.jobs.focus = Some(job); + } + if let Some(job) = cancel_open { + crate::jobs_ui::cancel(app, job); + } +} + +/// Document tabs: the chrome around a title (the × and its gaps). +const DOC_TAB_PAD: f32 = 42.0; + +/// The Studio strip's tabs carried 4 pt of spacing between them and 44 pt of chrome; `fit` sees +/// one number per tab, so the gap rides in the natural width and comes back out when painted. +const STUDIO_TAB_PAD: f32 = 48.0; + +const STUDIO_TAB_GAP: f32 = 4.0; + +/// Fit document tabs as Photoshop does (#4487): a tab never shrinks below its whole title, so the +/// tabs that don't fit move into the » menu instead. Only the active tab, when it alone is wider +/// than the strip, is cut. +fn fit_doc_tabs(natural: &[f32], selected: usize, avail: f32) -> crate::tab_strip::TabFit { + let widest = natural.iter().copied().filter(|w| w.is_finite()).fold(0.0, f32::max); + crate::tab_strip::fit(natural, selected, avail, widest, crate::tab_strip::CHEVRON_W) +} + +/// Photoshop's tab title: "name @ 50% (Layer 1, RGB/8)", "(Layer 1, Layer Mask/8)" when the mask +/// is targeted, "(Quick Mask/8)" in Quick Mask mode; the Background layer's name is omitted. +pub(super) fn pro_tab_title(app: &PhotocraftApp, i: usize) -> String { + use photocraft_engine::channel_cmds::ChannelTarget; + let Some(st) = app.session.documents().get(i) else { return String::new() }; + let zoom = app.ui.views.get(i).map_or(100.0, |v| v.zoom * 100.0); + // Quick Mask mode targets the mask, not the layer (see `paint_target`): painting and Free + // Transform change the red overlay, so the tab says so, as Photoshop's does. + let quick_mask = st.doc.quick_mask.is_some() && st.channel_view.target == ChannelTarget::Composite; + let active_layer = st.active_layer.and_then(|id| st.doc.layer(id)).filter(|l| !quick_mask && !st.doc.is_background(l.id)); + let mask = app.session.active_index() == Some(i) && app.ui.mask_target && active_layer.is_some_and(|l| l.mask.is_some()); + let model = if quick_mask { + tl!("Quick Mask").to_string() + } else if mask { + tl!("Layer Mask").to_string() + } else { + mode_label(&st.doc).to_string() + }; + let layer = active_layer.map(|l| format!("{}, ", l.name)).unwrap_or_default(); + // A save in progress: "name @ 100% (Layer 1, RGB/16) - Saving 45%", as Photoshop does (#3389). + let saving = crate::jobs_ui::save_progress(app, st.doc.id).map(|s| format!(" - {s}")).unwrap_or_default(); + format!("{} @ {}% ({layer}{model}/{}){}{saving}", st.doc.name, fmt_zoom(zoom), st.doc.depth.bits(), if st.is_dirty() { "*" } else { "" }) +} + +/// The Studio strip's tab name: "name *" when unsaved, "name * - Saving 45%" while it saves (#3389). +fn studio_tab_name(app: &PhotocraftApp, st: &photocraft_engine::DocState) -> String { + let saving = crate::jobs_ui::save_progress(app, st.doc.id).map(|s| format!(" - {s}")).unwrap_or_default(); + format!("{}{}{saving}", st.doc.name, if st.is_dirty() { " *" } else { "" }) +} + +/// Photoshop document tabs: "name @ 33.3% (RGB/8)" on a dark strip; active tab matches panels. +/// Tabs keep their whole titles, and the ones that don't fit move into a » menu at the end of the +/// strip; the active document's tab always stays on the strip (#1276, #4487). +fn pro_tabs(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> TabStrip { + let t = crate::theme::Tokens::get(ui.ctx()); + let active = app.session.active_index().filter(|_| app.jobs.focus.is_none()); + let (mut activate, mut close) = (None, None); + let mut tab_action = None; + let mut tab_move = None; + let mut tear_off = None; + let tab_count = app.session.documents().len(); + let dragging = crate::layer_transfer::pointer_if_armed(app, ui.ctx()); + let mut drag_over = None; + let mac = ui.ctx().os() == egui::os::OperatingSystem::Mac; + let large_tabs = app.session.prefs().workspace.large_tabs; + let font = egui::FontId::proportional(if large_tabs { 13.0 } else { 11.5 }); + let tab_h = if large_tabs { 34.0 } else { 26.0 }; + let (strip, _) = ui.allocate_exact_size(egui::vec2(ui.available_width(), tab_h), Sense::hover()); + ui.painter().rect_filled(strip, 0.0, t.tab_strip); + // Files opening in the background (#210) are tabs too ("name (Opening… 45%)" with a progress + // underline); they share the fit's index space, after the documents. + let opening = crate::jobs_ui::open_tabs(app); + let mut titles: Vec = (0..tab_count).map(|i| pro_tab_title(app, i)).collect(); + titles.extend(opening.iter().map(|(_, name, frac)| format!("{name} ({} {:.0}%)", tl!("Opening…"), frac * 100.0))); + // Every tab's natural width, whether or not it stays on the strip. + let natural: Vec = titles.iter().map(|title| ui.painter().layout_no_wrap(title.clone(), font.clone(), t.text).size().x + DOC_TAB_PAD).collect(); + let selected = app + .jobs + .focus + .and_then(|job| opening.iter().position(|(open, _, _)| *open == job)) + .map_or_else(|| app.session.active_index().unwrap_or(0), |p| tab_count + p); + let f = fit_doc_tabs(&natural, selected, strip.width()); + let mut x = strip.left(); + let mut placed: Vec<(usize, Rect)> = Vec::with_capacity(f.shown.len()); + for &(i, w) in &f.shown { + let r = Rect::from_min_size(egui::pos2(x, strip.top()), egui::vec2(w, strip.height())); + placed.push((i, r)); + x = r.right(); + } + let mut doc_tabs = Vec::with_capacity(tab_count); + let (mut focus_open, mut cancel_open) = (None, None); + for &(i, r) in placed.iter().filter(|(i, _)| *i < tab_count) { + let Some(title) = titles.get(i) else { continue }; + let g = crate::tab_strip::elided(ui, title, font.clone(), t.text, (r.width() - DOC_TAB_PAD).max(1.0)); + let resp = ui.interact(r, ui.scope_id().with(("ptab", i)), Sense::click_and_drag()); + let sel = Some(i) == active; + if sel { + ui.painter().rect_filled(r, 0.0, t.chrome); + } else if resp.hovered() { + ui.painter().rect_filled(r, 0.0, t.hover.gamma_multiply(0.35)); + } + if dragging.is_some_and(|p| r.contains(p)) { + drag_over = Some(i); + ui.painter().rect_stroke(r, 0.0, Stroke::new(1.5, t.accent), egui::StrokeKind::Inside); + } + ui.painter().line_segment([r.right_top(), r.right_bottom()], Stroke::new(1.0, t.separator)); + let (xr, at) = pro_tab_layout(r, g.size().y, mac); + let xresp = ui.interact(xr, ui.scope_id().with(("ptabx", i)), Sense::click()); + // Painted: name the tab and its × for accessibility (and so tests and agents can find them). + resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, sel, g.text())); + xresp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!("Close"))); + crate::icons::paint(ui, xr, "x", 10.0, if xresp.hovered() { t.text } else { t.text_faint }); + ui.painter().galley_with_override_text_color(at, g, if sel { t.text } else { t.text_faint }); + let cut = natural.get(i).copied().unwrap_or(0.0) > r.width() + 0.5; + let resp = if cut { resp.on_hover_text(title.as_str()) } else { resp }; + if tab_close_clicked(&resp, &xresp) { + close = Some(i); + } else if resp.clicked() { + activate = Some(i); + } + match tab_drag(ui, &resp, i, r, strip, &placed, &t) { + Some(TabDrop::Move(to)) => tab_move = Some((i, to)), + Some(TabDrop::Float(at)) => tear_off = Some((i, at)), + None => {} + } + let has_path = app.session.documents().get(i).is_some_and(|d| d.path.is_some()); + resp.context_menu(|ui| { + tab_action = tab_context_menu(ui, i, tab_count, has_path); + }); + doc_tabs.push((i, r)); + } + for &(i, r) in placed.iter().filter(|(i, _)| *i >= tab_count) { + let Some((job, _, frac)) = opening.get(i - tab_count) else { continue }; + let Some(title) = titles.get(i) else { continue }; + let g = crate::tab_strip::elided(ui, title, font.clone(), t.text, (r.width() - DOC_TAB_PAD).max(1.0)); + let resp = ui.interact(r, ui.scope_id().with(("ptabjob", job.0)), Sense::click()); + let sel = app.jobs.focus == Some(*job); + if sel { + ui.painter().rect_filled(r, 0.0, t.chrome); + } else if resp.hovered() { + ui.painter().rect_filled(r, 0.0, t.hover.gamma_multiply(0.35)); + } + ui.painter().line_segment([r.right_top(), r.right_bottom()], Stroke::new(1.0, t.separator)); + crate::jobs_ui::tab_underline(ui, r, *frac, &t); + let (xr, at) = pro_tab_layout(r, g.size().y, mac); + let xresp = ui.interact(xr, ui.scope_id().with(("ptabjobx", job.0)), Sense::click()); + xresp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!("Close"))); + crate::icons::paint(ui, xr, "x", 10.0, if xresp.hovered() { t.text } else { t.text_faint }); + ui.painter().galley_with_override_text_color(at, g, if sel { t.text } else { t.text_faint }); + if xresp.on_hover_text(tl!("Cancel opening")).clicked() { + cancel_open = Some(*job); + } else if resp.clicked() { + focus_open = Some(*job); + } + } + if !f.overflow.is_empty() { + // Pinned to the strip's right end, as Photoshop's is, not after the last tab (#8290). + let left = (strip.right() - crate::tab_strip::CHEVRON_W).max(strip.left()); + let r = Rect::from_min_size(egui::pos2(left, strip.top()), egui::vec2(crate::tab_strip::CHEVRON_W, strip.height())); + let labels: Vec<&str> = titles.iter().map(String::as_str).collect(); + let mut picked = None; + // Like Photoshop's, the menu lists every open document, not only the hidden ones, and checks + // the active one (#4487). + let every: Vec = (0..labels.len()).collect(); + crate::tab_strip::overflow_button(ui, ui.scope_id().with("ptab-overflow"), r, tl!("More documents"), &labels, &every, Some(selected), &mut picked); + match picked { + Some(i) if i < tab_count => activate = Some(i), + Some(i) => focus_open = opening.get(i - tab_count).map(|(job, _, _)| *job).or(focus_open), + None => {} + } + } + open_tab_clicks(app, activate, focus_open, cancel_open); + if let Some(i) = drag_over { + crate::layer_transfer::over_tab(app, ui.ctx(), i); + } + if let Some(i) = close { + let _ = crate::menus::invoke(app, ui.ctx(), "file.close", json!({"document": i})); + } + if let Some((from, to)) = tab_move + && let Err(e) = crate::menus::invoke(app, ui.ctx(), "document.move", json!({"document": from, "to": to})) + { + app.ui.status = e; + app.ui.status_error = true; + } + float_torn_off(app, ui.ctx(), tear_off); + if let Some((id, params)) = tab_action + && let Err(e) = crate::menus::invoke(app, ui.ctx(), id, params) + { + app.ui.status = e; + app.ui.status_error = true; + } + TabStrip { rect: strip, tabs: doc_tabs } +} + +/// Where the document tabs were drawn (opening files' tabs aren't slots): a file dropped on the +/// strip opens at the slot under the pointer. +#[derive(Clone, Debug, PartialEq)] +pub struct TabStrip { + pub rect: Rect, + /// The document tabs shown, left to right, with their document index. When the tabs overflow + /// into the » menu, some documents have no tab here. + pub tabs: Vec<(usize, Rect)>, +} + +impl TabStrip { + /// The document position a drop at `x` opens at: before the first shown tab whose middle is + /// right of it, else after the last shown tab. + pub fn slot(&self, x: f32) -> usize { + match self.tabs.iter().find(|(_, r)| r.center().x >= x) { + Some(&(i, _)) => i, + None => self.tabs.last().map_or(0, |&(i, _)| i.saturating_add(1)), + } + } +} + +/// While files are dragged over the tab strip, an insertion line where they would open. +fn drop_slot_line(app: &mut PhotocraftApp, ui: &egui::Ui) { + if ui.input(|i| i.raw.hovered_files.is_empty()) { + return; + } + let at = app.services.cursor_pos.as_mut().and_then(|f| f(ui.ctx())); + let crate::file_open::DropTarget::Tabs(slot) = app.drop_target(ui.ctx(), at) else { return }; + let Some(tabs) = app.tab_strip.as_ref().map(|s| &s.tabs) else { return }; + let Some((r, after)) = tabs.iter().find(|(i, _)| *i == slot).map(|&(_, r)| (r, false)).or_else(|| tabs.last().map(|&(_, r)| (r, true))) else { + return; + }; + crate::widgets::drop_line(ui, r, after, true, &crate::theme::Tokens::get(ui.ctx())); +} + +/// A Photoshop-style tab's close button and where its title starts. Photoshop puts the × after the +/// title on Windows (and so Linux) and before it on macOS (#619). +fn pro_tab_layout(tab: Rect, title_height: f32, mac: bool) -> (Rect, egui::Pos2) { + let (x, title) = if mac { (tab.left() + 13.0, tab.left() + 26.0) } else { (tab.right() - 13.0, tab.left() + 16.0) }; + (Rect::from_center_size(egui::pos2(x, tab.center().y), egui::vec2(14.0, 14.0)), egui::pos2(title, tab.center().y - title_height / 2.0)) +} + +/// Repeating dot-grid texture for the canvas surround. A theme whose dots are its canvas colour +/// has no pattern to show, so it gets no texture at all rather than an invisible one (#4542). +pub(super) fn dots(ctx: &egui::Context, t: &crate::theme::Tokens) -> Option { + if t.bevel || t.canvas_dot == t.canvas { + return None; + } + let key = egui::Id::unique(("canvas-dots", format!("{:?}", t.kind))); + if let Some(tex) = ctx.data(|d| d.get_temp::(key)) { + return Some(tex.id()); + } + let n = 22usize; + let mut px = vec![Color32::TRANSPARENT; n * n]; + for (dx, dy, a) in [(0usize, 0usize, 255u8), (1, 0, 110), (0, 1, 110), (1, 1, 60)] { + let c = t.canvas_dot; + px[(n / 2 + dy) * n + n / 2 + dx] = Color32::from_rgba_unmultiplied(c.r(), c.g(), c.b(), a); + } + let opts = TextureOptions { + magnification: egui::TextureFilter::Linear, + minification: egui::TextureFilter::Linear, + wrap_mode: egui::TextureWrapMode::Repeat, + mipmap_mode: None, + }; + let tex = ctx.load_texture("canvas-dots", egui::ColorImage::new([n, n], px), opts); + let id = tex.id(); + ctx.data_mut(|d| d.insert_temp(key, tex)); + Some(id) +} + +pub(super) fn paint_dots(ui: &egui::Ui, rect: Rect, enabled: bool) { + if !enabled { + return; + } + let t = crate::theme::Tokens::get(ui.ctx()); + if let Some(id) = dots(ui.ctx(), &t) { + let uv = Rect::from_min_max(Pos2::ZERO, pos2(rect.width() / 22.0, rect.height() / 22.0)); + ui.painter_at(rect).image(id, rect, uv, Color32::WHITE); + } +} + +/// With no document open, double-clicking the empty workspace shows File › Open, as in Photoshop +/// (#5367), and so does the Home screen's blank background. Registered before anything drawn over +/// `area`, so the buttons and links there keep their own clicks; not a keyboard focus stop. +pub(super) fn open_on_double_click(app: &mut PhotocraftApp, ui: &egui::Ui, area: Rect) { + if app.session.documents().is_empty() && ui.interact(area, ui.scope_id().with("empty-workspace"), Sense::CLICK).double_clicked() { + let _ = app.open_dialog_file(); + } +} + +/// Extra OS windows showing documents (multi-window / multi-monitor). +pub fn extra_windows(app: &mut PhotocraftApp, ctx: &egui::Context) { + let wins = app.ui.windows.clone(); + for w in wins.into_iter().filter(|w| w.open) { + let Some(st) = app.session.documents().get(w.document) else { continue }; + let title = format!("{} — window {}", st.doc.name, w.id); + let vid = egui::ViewportId::from_hash_of(("docwin", w.id)); + let mut builder = egui::ViewportBuilder::default().with_title(title).with_inner_size([800.0, 600.0]); + if let Some([x, y]) = w.position { + builder = builder.with_position([x, y]); + } + let mut view = w.view.clone(); + let mut close = false; + ctx.show_viewport_immediate(vid, builder, |ui, class| { + if ui.ctx().input(|i| i.viewport().close_requested()) { + close = true; + } + egui::CentralPanel::default().frame(egui::Frame::NONE.fill(crate::theme::Tokens::get(ui.ctx()).canvas)).show(ui, |ui| { + let rect = ui.available_rect_before_wrap(); + view = canvas_view(app, ui, w.document, rect, view.clone(), false); + // Preferences › Zoom Resizes Windows: a zoom wraps the window around the image. + crate::zoom_window_fit::follow(app, ui.ctx(), class, vid, &w, &mut view, rect); + }); + }); + if let Some(win) = app.ui.windows.iter_mut().find(|x| x.id == w.id) { + win.view = view; + if close { + win.open = false; + } + } + } + app.ui.windows.retain(|w| w.open); +} diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs new file mode 100644 index 0000000000..a2ec365f80 --- /dev/null +++ b/crates/ui-egui/src/canvas/tests.rs @@ -0,0 +1,2887 @@ +/// #5472: a ⇧ square pressed between pixels snapped to 101 × 102; the short side grows to +/// match, on the side the drag points to. +#[test] +fn square_px_equalises_the_sides_away_from_the_press_point() { + use super::{marquee_px, square_px}; + // Down-right drag: the continuous square (50.3, 50.7)..(150.8, 151.2) snaps unevenly. + let r = marquee_px([50.3, 50.7], [150.8, 151.2]); + assert_eq!(r, [50.0, 50.0, 151.0, 152.0], "uneven before the fix"); + assert_eq!(square_px(r, [50.3, 50.7], [150.8, 90.0]), [50.0, 50.0, 152.0, 152.0]); + // Up-left drag: the short side grows towards lower coordinates. + let r = marquee_px([150.8, 151.2], [50.3, 50.7]); + assert_eq!(square_px(r, [150.8, 151.2], [60.0, 50.7]), [49.0, 50.0, 151.0, 152.0]); + // Already square: unchanged. + assert_eq!(square_px([10.0, 20.0, 30.0, 40.0], [10.0, 20.0], [30.0, 40.0]), [10.0, 20.0, 30.0, 40.0]); +} + +/// #6015: a Fixed Size marquee pressed between pixels selected one pixel more on each side. +#[test] +fn fixed_size_px_is_exactly_the_size() { + use super::fixed_size_px; + // Down-right from (10.4, 20.6): 10 × 10 from the closest pixel edges. + assert_eq!(fixed_size_px([10.4, 20.6], [20.4, 30.6], 10.0, 10.0), [10.0, 21.0, 20.0, 31.0]); + // Up-left: the far corner is the low one; still exactly the size. + assert_eq!(fixed_size_px([10.4, 20.6], [-53.6, -11.4], 64.0, 32.0), [-54.0, -11.0, 10.0, 21.0]); + // 1 × 1 is one pixel, and a fractional size rounds to whole pixels. + assert_eq!(fixed_size_px([3.5, 3.5], [4.5, 4.5], 1.0, 1.0), [4.0, 4.0, 5.0, 5.0]); + assert_eq!(fixed_size_px([0.0, 0.0], [2.6, 2.4], 2.6, 2.4), [0.0, 0.0, 3.0, 2.0]); +} + +#[test] +fn display_image_matches_egui_unmultiplied_conversion() { + // Several parallel pieces and a ragged one; translucent, out-of-range and NaN values. + let n: usize = 3 * 16 * 1024 + 77; + let px: Vec<[f32; 4]> = (0..n) + .map(|i| { + let v = match i % 9 { + 0 => f32::NAN, + 1 => -0.5, + 2 => 3.25, + _ => (i % 1001) as f32 / 1000.0, + }; + [v, (i % 257) as f32 / 256.0, 1.0 - (i % 113) as f32 / 112.0, (i % 6) as f32 / 5.0] + }) + .collect(); + let buf = photocraft_compose::Buffer { rect: photocraft_geom::Rect::new(0, 0, n as i32, 1), px }; + let reference = |img: photocraft_raster::Rgba8Image| egui::ColorImage::from_rgba_unmultiplied([img.width as usize, img.height as usize], &img.pixels); + assert_eq!(super::display_image(None, &buf).pixels, reference(buf.to_rgba8()).pixels); + let mut doc = photocraft_doc::Document::new("t", photocraft_geom::Size::new(1, 1), photocraft_doc::ColorMode::Rgb, photocraft_doc::SampleType::U8); + doc.icc_profile = Some(photocraft_cms::Builtin::AdobeRgbCompat.profile().to_bytes()); + let mut color = photocraft_engine::color_cmds::ColorState::default(); + color.settings.monitor_profile = "srgb".into(); + let d = color.canvas_display(&doc).unwrap(); + assert!(!d.is_identity()); + assert_eq!(super::display_image(Some(&d), &buf).pixels, reference(d.to_rgba8(&buf)).pixels); +} + +/// #7490: the inline (web) preview path composites and uploads each changed preview once, as +/// the background worker does. It used to flatten and upload it twice and record it twice, +/// so the frame's refresh time counted the preview twice. +/// The CPU canvas (no usable GPU; a flipped or pixel-aspect-corrected view, or a GPU fallback, +/// on a GPU machine) shows a filter dialog's live preview. It showed the document unfiltered. +#[test] +fn the_cpu_canvas_shows_a_filter_dialogs_preview() { + let pixels = |ctx: &egui::Context, id: egui::TextureId| { + let mut delta = ctx.tex_manager().write().take_delta(); + let egui::ImageData::Color(image) = &delta.set.get(&id).and_then(|d| d.last()).expect("the canvas texture was written").image; + let (size, px) = (image.size, image.pixels.clone()); + delta.clear(); + (size, px) + }; + for (size, zoom) in [([64u32, 48u32], 1.0f32), ([2400, 2200], 0.25)] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.background_jobs = false; + app.run("file.new", json!({"width": size[0], "height": size[1], "background": "white"})).unwrap(); + app.run("edit.fill", json!({"color": "#3399cc"})).unwrap(); + app.ui.views.get_mut(0).expect("the view").zoom = zoom; + let ctx = egui::Context::default(); + let (tex, _) = ensure_texture(&mut app, &ctx, 0, None).unwrap(); + let (_, plain) = pixels(&ctx, tex); + crate::filter_dialog::open(&mut app, "filter.stylize.solarize").unwrap(); + let (tex, _) = ensure_texture(&mut app, &ctx, 0, None).unwrap(); + let (tex_size, shown) = pixels(&ctx, tex); + let preview = app.filter_preview.as_ref().and_then(|p| p.result.clone()).expect("the dialog's preview"); + let (display, _) = canvas_display(&app, &preview, None); + let expected = display_image(display.as_deref(), &photocraft_compose::flatten(&preview)); + assert_eq!(tex_size, expected.size, "{size:?}: the preview's own size (a proxy when zoomed out)"); + assert_eq!(shown, expected.pixels, "{size:?}: the canvas shows the preview"); + assert_ne!(shown.first(), plain.first(), "{size:?}: not the unfiltered document"); + } + // A preview that changes the canvas's dimensions covers its own area, centred on the + // document's (as the GPU canvas centres it), rather than being stretched over it. + let size = |w, h| photocraft_geom::Size::new(w, h); + assert_eq!(preview_bounds(size(64, 32), size(64, 32), 1), DRect::new(0, 0, 64, 32)); + assert_eq!(preview_bounds(size(2401, 2200), size(1201, 1100), 2), DRect::new(0, 0, 2401, 2200), "a proxy"); + assert_eq!(preview_bounds(size(64, 32), size(32, 64), 1), DRect::new(16, -16, 48, 48), "rotated"); + assert_eq!(preview_bounds(size(64, 32), size(80, 40), 1), DRect::new(-8, -4, 72, 36), "canvas grown"); + assert_eq!(preview_bounds(size(4000, 2000), size(1000, 2000), 2), DRect::new(1000, -1000, 3000, 3000), "a rotated proxy"); + + // Image › Image Rotation › Arbitrary 90° on a 64×32 document: its 32×64 preview is drawn over + // the centred 32×64 area. + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.background_jobs = false; + app.run("file.new", json!({"width": 64, "height": 32, "background": "white"})).unwrap(); + let id = crate::filter_dialog::open(&mut app, "image.rotation.arbitrary").unwrap(); + let d = app.ui.dialogs.iter_mut().find(|d| d.id == id).unwrap(); + d.fields.insert("angle".into(), json!(90.0)); + d.fields.insert("__preview".into(), json!(true)); + let ctx = egui::Context::default(); + let t = ensure_texture_in_view(&mut app, &ctx, 0, None, None).unwrap(); + let (size, _) = pixels(&ctx, t.texture); + assert_eq!(size, [32, 64], "the rotated preview's texture"); + assert_eq!(t.bounds, DRect::new(16, -16, 48, 48), "centred on the document"); + let centre = |r: DRect| (r.x0 + r.x1, r.y0 + r.y1); + assert_eq!(centre(t.bounds), centre(app.session.active().unwrap().doc.bounds()), "the same centre, so the view's pan holds"); + // Preview off, then Cancel: the document again, unchanged. + let revision = app.session.active().unwrap().revision; + app.ui.dialogs.iter_mut().find(|d| d.id == id).unwrap().fields.insert("__preview".into(), json!(false)); + let t = ensure_texture_in_view(&mut app, &ctx, 0, None, None).unwrap(); + assert_eq!(t.bounds, DRect::new(0, 0, 64, 32), "Preview off"); + crate::dialogs::cancel(&mut app, id).unwrap(); + let t = ensure_texture_in_view(&mut app, &ctx, 0, None, None).unwrap(); + assert_eq!(t.bounds, DRect::new(0, 0, 64, 32), "after Cancel"); + assert_eq!(app.session.active().unwrap().revision, revision, "the document untouched"); + assert_eq!(app.session.active().unwrap().doc.size, photocraft_geom::Size::new(64, 32)); +} + +/// A channel overlay drawn from a size-changing preview covers the preview's own area, as the +/// image does, not the document's: a 90° rotation of a 64×32 document shows a 32×64 overlay. +#[test] +fn a_channel_overlay_follows_a_size_changing_preview() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.background_jobs = false; + app.run("file.new", json!({"width": 64, "height": 32, "background": "white"})).unwrap(); + app.run("channel.new", json!({"name": "Alpha", "fill": "black"})).unwrap(); + let id = crate::filter_dialog::open(&mut app, "image.rotation.arbitrary").unwrap(); + let d = app.ui.dialogs.iter_mut().find(|d| d.id == id).unwrap(); + d.fields.insert("angle".into(), json!(90.0)); + d.fields.insert("__preview".into(), json!(true)); + let ctx = egui::Context::default(); + for rotation in [0.0f32, 30.0] { + let view = View { zoom: 4.0, center: [32.0, 16.0], rotation, ..app.ui.views[0].clone() }; + let mut output = ctx.run_ui(Default::default(), |ui| { + canvas_view(&mut app, ui, 0, Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)), view.clone(), true); + }); + output.textures_delta.clear(); + let overlay = crate::channel_view::ensure(&mut app, &ctx, 0).expect("the channel overlay"); + let mesh = output + .shapes + .iter() + .find_map(|s| match &s.shape { + egui::Shape::Mesh(m) if m.texture_id == overlay => Some(m.clone()), + _ => None, + }) + .expect("the overlay is painted"); + // The quad's sides, in screen points: the two shortest distances from a corner (the + // third is the diagonal; a rotated view turns the quad, not its side lengths). + let v: Vec = mesh.vertices.iter().map(|v| v.pos).collect(); + let mut d: Vec = v[1..4].iter().map(|p| v[0].distance(*p)).collect(); + d.sort_by(f32::total_cmp); + let (short, long) = (d[0], d[1]); + // Which side is the width: the one along the view's x axis turned by the rotation. + let along = |p: Pos2| { + let r = rotation.to_radians(); + ((p - v[0]).x * r.cos() + (p - v[0]).y * r.sin()).abs() + }; + let width = v[1..4].iter().map(|p| along(*p)).fold(0.0f32, f32::max); + assert!((long / short - 2.0).abs() < 0.01, "rotation {rotation}: sides {short}×{long}, the preview's 1:2"); + assert!((width - short).abs() < 0.5, "rotation {rotation}: the short side ({short}) runs across the view (width {width})"); + } +} + +#[test] +fn inline_filter_preview_is_composited_and_recorded_once() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.background_jobs = false; + app.run("file.new", json!({"width": 320, "height": 240})).unwrap(); + crate::filter_dialog::open(&mut app, "filter.stylize.solarize").unwrap(); + app.perf.frame_refresh_ms = 0.0; + let (_, _, size) = ensure_filter_preview(&mut app, 0, &egui::Context::default()).expect("a preview"); + assert_eq!(size, [320, 240]); + assert_eq!(app.perf.last_refresh, "filter-preview"); + assert_eq!(app.perf.last_refresh_px, 320 * 240); + assert_eq!(app.perf.frame_refresh_ms, app.perf.composite_ms + app.perf.upload_ms, "one record per preview"); + // Unchanged request: nothing is recomputed or recorded again. + ensure_filter_preview(&mut app, 0, &egui::Context::default()).expect("the same preview"); + assert_eq!(app.perf.frame_refresh_ms, app.perf.composite_ms + app.perf.upload_ms); +} + +/// #6326: a filter's live preview is never coarser than the screen. On a document big enough +/// for a reduced proxy, the view at 100 % previews at full resolution, and only a view zoomed +/// out far enough uses the proxy. Through `ensure_filter_preview`, so the factor the canvas +/// actually requests is the one under test. +#[test] +fn filter_preview_at_100_percent_is_full_resolution() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.background_jobs = false; + app.run("file.new", json!({"width": 2400, "height": 2200})).unwrap(); + assert_eq!(crate::proxy::preview_factor(&app.session.active().unwrap().doc, true), 2, "big enough for a proxy"); + crate::filter_dialog::open(&mut app, "filter.stylize.solarize").unwrap(); + let ctx = egui::Context::default(); + let preview_at = |app: &mut PhotocraftApp, zoom: f32| { + app.ui.views.get_mut(0).expect("the new document's view").zoom = zoom; + assert_eq!(app.current_zoom(), zoom); + let (k, _, size) = ensure_filter_preview(app, 0, &ctx).expect("a preview"); + (k, size) + }; + assert_eq!(preview_at(&mut app, 1.0), (1, [2400, 2200]), "100 %: every pixel"); + assert_eq!(preview_at(&mut app, 0.25), (2, [1200, 1100]), "zoomed out: the document's proxy"); + // Low Resolution Previews off: full resolution at any zoom, exactly as before #6326. + app.run("prefs.set", json!({"path": "performance.lowResolutionPreviews", "value": false})).unwrap(); + assert_eq!(preview_at(&mut app, 0.25), (1, [2400, 2200]), "the preference still decides"); +} + +/// The factor itself over the zoom range, and that Preferences › Performance › Low +/// Resolution Previews still decides whether there is a proxy at all (#6326). +#[test] +fn filter_preview_factor_caps_at_the_view_without_overriding_the_preference() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + // 9 MP: reduced previews halve it (empty tiles, so nothing is allocated). + app.run("file.new", json!({"width": 3000, "height": 3000, "background": "transparent"})).unwrap(); + let doc = app.session.active().unwrap().doc.clone(); + let params = json!({"amount": 100, "radius": 4.0, "threshold": 0}); + let k = |app: &mut PhotocraftApp, zoom: f32| { + app.ui.views.get_mut(0).expect("the new document's view").zoom = zoom; + super::filter_preview_factor(app, &doc, "filter.sharpen.unsharpMask", ¶ms) + }; + assert_eq!(k(&mut app, 0.25), 2, "zoomed out the preview stays reduced"); + assert_eq!(k(&mut app, 0.5), 2); + assert_eq!(k(&mut app, 0.75), 1, "past the proxy's resolution it shows every pixel"); + assert_eq!(k(&mut app, 1.0), 1); + assert_eq!(k(&mut app, 4.0), 1); + // A corrupt or unset zoom must not pick a coarser proxy than the document's own. + assert_eq!(k(&mut app, f32::NAN), 1); + assert_eq!(k(&mut app, 0.0), 1); + // Low Resolution Previews off: full resolution at any zoom, the cap a no-op. + app.run("prefs.set", json!({"path": "performance.lowResolutionPreviews", "value": false})).unwrap(); + for zoom in [0.1, 0.25, 1.0, 4.0] { + assert_eq!(k(&mut app, zoom), 1, "zoom {zoom}"); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn every_filter_previews_off_the_ui_thread_and_a_newer_value_cancels_the_old() { + // Dragging Gaussian Blur's radius to 1000 px froze the window: the preview ran inline in + // the frame, and every slider step waited for the previous blur to finish. + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); + app.background_jobs = true; + crate::filter_dialog::open(&mut app, "filter.blur.gaussianBlur").unwrap(); + let ctx = egui::Context::default(); + let wait_for = |app: &mut PhotocraftApp, radius: f64| { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + while app.filter_preview.as_ref().is_none_or(|p| p.key.params["radius"].as_f64() != Some(radius)) { + assert!(std::time::Instant::now() < deadline, "no preview for radius {radius}"); + ensure_filter_preview(app, 0, &ctx); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + }; + // The first frame hands the blur to the worker and returns. + assert!(ensure_filter_preview(&mut app, 0, &ctx).is_none()); + assert!(app.filter_preview_worker.busy(), "the preview computes on the worker"); + let first = app.ui.dialogs[0].fields["radius"].as_f64().unwrap(); + wait_for(&mut app, first); + assert!(app.filter_preview.as_ref().unwrap().result.is_some()); + + // A preview for old values occupies the worker until it is cancelled. + let st = app.session.active().unwrap(); + let d = &app.ui.dialogs[0]; + let stale = crate::filter_dialog::FilterPreviewKey { + doc: st.doc.id, + revision: st.revision, + dialog: d.id, + active: st.active_layer, + target: st.channel_view.target, + command: "filter.blur.gaussianBlur".into(), + params: json!({"radius": 999.0}), + k: 1, + }; + let (told, cancelled) = std::sync::mpsc::channel(); + app.filter_preview_worker + .start(stale, ctx.clone(), move |job| { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + while !job.cancelled() && std::time::Instant::now() < deadline { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + let _ = told.send(job.cancelled()); + crate::filter_preview_worker::Computed { result: None, ms: 0.0 } + }) + .unwrap(); + // The slider moves on and stops: once the value settles, the stale preview is cancelled + // instead of being waited out. + app.ui.dialogs[0].fields.insert("radius".into(), json!(12.0)); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + let was_cancelled = loop { + ensure_filter_preview(&mut app, 0, &ctx); + if let Ok(c) = cancelled.try_recv() { + break c; + } + assert!(std::time::Instant::now() < deadline, "the stale preview was never cancelled"); + std::thread::sleep(std::time::Duration::from_millis(5)); + }; + assert!(was_cancelled, "the stale preview stopped because it was cancelled, not by timing out"); + wait_for(&mut app, 12.0); + assert!(app.filter_preview.as_ref().unwrap().result.is_some()); +} + +// Starts a worker job that computes a real preview for the dialog as it stands, but only +// finishes when the returned sender is signalled. Gating it here keeps these tests off the +// clock: `supersede` cancels a running job once the values have been still for SETTLE_MS, so a +// test that relies on a real blur beating a 150 ms timer is a test that fails on a loaded box. +#[cfg(not(target_arch = "wasm32"))] +fn gated_blur_preview(app: &mut PhotocraftApp, ctx: &egui::Context) -> (std::sync::mpsc::Sender<()>, f64) { + let d = app.ui.dialogs.first().expect("a dialog is open"); + let st = app.session.active().expect("a document is active"); + let command = "filter.blur.gaussianBlur"; + let params = app.with_mask_target(command, crate::filter_dialog::params_of(&d.fields)); + assert_eq!( + crate::filter_dialog::preview_factor(command, ¶ms, 1), + 1, + "a 64x48 document previews at full resolution, and these tests rely on k staying 1" + ); + let key = crate::filter_dialog::FilterPreviewKey { + doc: st.doc.id, + revision: st.revision, + dialog: d.id, + active: st.active_layer, + target: st.channel_view.target, + command: command.into(), + params, + k: 1, + }; + let doc = app.session.documents()[0].doc.clone(); + let documents: Vec<_> = app.session.documents().iter().map(|d| d.doc.clone()).collect(); + let radius = key.params["radius"].as_f64().expect("the dialog seeds a radius"); + let (release, wait) = std::sync::mpsc::channel::<()>(); + app.filter_preview_worker + .start(key.clone(), ctx.clone(), move |_| { + wait.recv_timeout(std::time::Duration::from_secs(60)).expect("the test releases the job"); + let result = crate::filter_dialog::preview_document_for_target( + &doc, + key.active, + &key.command, + &key.params, + key.k, + None, + key.target, + &documents, + &Default::default(), + ) + .map(|d| { + let buffer = photocraft_compose::flatten(&d); + (std::sync::Arc::new(d), buffer) + }); + crate::filter_preview_worker::Computed { result, ms: 0.0 } + }) + .expect("the worker starts"); + (release, radius) +} + +// The worker hands its result to the channel only after `compute` returns, so a signal sent +// from inside `compute` would still race that send. These tests drive the canvas until the +// state they need appears instead of assuming a timing. +#[cfg(not(target_arch = "wasm32"))] +fn drive_until(app: &mut PhotocraftApp, ctx: &egui::Context, what: &str, done: impl Fn(&PhotocraftApp) -> bool) { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60); + while !done(app) { + assert!(std::time::Instant::now() < deadline, "timed out waiting for {what}"); + ensure_filter_preview(app, 0, ctx); + std::thread::sleep(std::time::Duration::from_millis(1)); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_preview_computed_mid_drag_reaches_the_canvas_and_then_converges() { + // A drag used to paint nothing at all: every completion was dropped for carrying stale + // parameters, so the canvas only ever showed an effect once the pointer had come to rest. + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); + app.background_jobs = true; + crate::filter_dialog::open(&mut app, "filter.blur.gaussianBlur").unwrap(); + let ctx = egui::Context::default(); + let (release, first) = gated_blur_preview(&mut app, &ctx); + + // The pointer moves on before the frame lands. + let moved = first + 4.0; + app.ui.dialogs[0].fields.insert("radius".into(), json!(moved)); + release.send(()).expect("released"); + drive_until(&mut app, &ctx, "the mid-drag frame", |a| a.filter_preview.is_some()); + + // The finished frame is painted even though the dialog has moved on. + let shown = app.filter_preview.as_ref().expect("the mid-drag frame was published"); + assert_eq!(shown.key.params["radius"].as_f64(), Some(first), "the frame is the one the worker finished"); + assert!(shown.result.is_some()); + assert_eq!(app.ui.dialogs[0].fields["radius"].as_f64(), Some(moved), "the slider kept moving"); + // The display gate lets it through, so the canvas has something to draw: this is what + // re-adding `params` to that gate would break. + assert!(ensure_filter_preview(&mut app, 0, &ctx).is_some(), "the canvas draws the mid-drag frame"); + + // And the preview still converges on the value the dialog holds. `fresh` has to stay an + // exact match for that: relaxed, the canvas would believe it already had the current + // request after the first frame of a drag and never compute again. + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + while app.filter_preview.as_ref().is_none_or(|p| p.key.params["radius"].as_f64() != Some(moved)) { + assert!(std::time::Instant::now() < deadline, "the preview never converged on the current radius"); + ensure_filter_preview(&mut app, 0, &ctx); + std::thread::sleep(std::time::Duration::from_millis(1)); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_mid_drag_frame_does_not_replace_a_frame_that_is_already_exact() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); + app.background_jobs = true; + crate::filter_dialog::open(&mut app, "filter.blur.gaussianBlur").unwrap(); + let ctx = egui::Context::default(); + + // A frame for the radius the dialog holds right now reaches the canvas. This also proves + // the hand-built key is the one the canvas builds: it can only be published by the exact + // arm, which requires `finished == request`. + let (release, first) = gated_blur_preview(&mut app, &ctx); + release.send(()).expect("released"); + drive_until(&mut app, &ctx, "the first frame", |a| a.filter_preview.is_some()); + assert_eq!(app.filter_preview.as_ref().expect("published").key.params["radius"].as_f64(), Some(first)); + + // The slider moves away and a frame for the new radius is computed... + let moved = first + 4.0; + app.ui.dialogs[0].fields.insert("radius".into(), json!(moved)); + let (release_moved, _) = gated_blur_preview(&mut app, &ctx); + // ...and back to `first` before that frame lands. + app.ui.dialogs[0].fields.insert("radius".into(), json!(first)); + release_moved.send(()).expect("released"); + + // The frame for `moved` arrives late. It belongs to this preview, but the frame on screen + // is already exact for the dialog, so it must never be shown in place of it. Checked on + // every pass: a wrong frame published and then overwritten before the loop ends would + // otherwise never be seen. + drive_until(&mut app, &ctx, "the late frame to arrive", |a| { + if let Some(shown) = &a.filter_preview { + assert_ne!(shown.key.params["radius"].as_f64(), Some(moved), "a late frame replaced an exact one"); + } + !a.filter_preview_worker.busy() + }); + let shown = app.filter_preview.as_ref().expect("a frame is on screen"); + assert_eq!(shown.key.params["radius"].as_f64(), Some(first), "a late frame replaced an exact one"); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_mid_drag_empty_result_leaves_the_preview_alone() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); + app.background_jobs = true; + crate::filter_dialog::open(&mut app, "filter.blur.gaussianBlur").unwrap(); + let ctx = egui::Context::default(); + + let (release, first) = gated_blur_preview(&mut app, &ctx); + release.send(()).expect("released"); + drive_until(&mut app, &ctx, "the first frame", |a| a.filter_preview.is_some()); + assert!(app.filter_preview.as_ref().expect("published").result.is_some()); + + // The slider moves and a job for the new radius is started, then the slider moves again + // before that job lands: its result is stale by the time it arrives. + let moved = first + 4.0; + app.ui.dialogs[0].fields.insert("radius".into(), json!(moved)); + let d = app.ui.dialogs.first().expect("a dialog is open"); + let st = app.session.active().expect("a document is active"); + let key = crate::filter_dialog::FilterPreviewKey { + doc: st.doc.id, + revision: st.revision, + dialog: d.id, + active: st.active_layer, + target: st.channel_view.target, + command: "filter.blur.gaussianBlur".into(), + params: json!({"radius": moved}), + k: 1, + }; + let (release_empty, wait) = std::sync::mpsc::channel::<()>(); + app.filter_preview_worker + .start(key, ctx.clone(), move |_| { + wait.recv_timeout(std::time::Duration::from_secs(60)).expect("released"); + crate::filter_preview_worker::Computed { result: None, ms: 0.0 } + }) + .expect("the worker starts"); + app.ui.dialogs[0].fields.insert("radius".into(), json!(moved + 4.0)); + release_empty.send(()).expect("released"); + + // Storing an empty result here would drop the canvas back to the unfiltered layer for a + // frame. The exact request may still store one; a stale one may not. Checked on every + // pass, because the reopened preview that follows would otherwise repair the symptom. + drive_until(&mut app, &ctx, "the empty frame to arrive", |a| { + if let Some(shown) = &a.filter_preview { + assert!(shown.result.is_some(), "an empty mid-drag result blanked the canvas"); + } + !a.filter_preview_worker.busy() + }); + assert!(app.filter_preview.as_ref().expect("a preview is still shown").result.is_some(), "an empty mid-drag result blanked the canvas"); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_reopened_dialog_never_paints_the_previous_dialogs_preview() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); + app.background_jobs = true; + crate::filter_dialog::open(&mut app, "filter.blur.gaussianBlur").unwrap(); + let ctx = egui::Context::default(); + let first_dialog = app.ui.dialogs.first().expect("a dialog is open").id; + let (release, _) = gated_blur_preview(&mut app, &ctx); + + // Close that dialog and open another one for the same layer and the same command. Only the + // dialog id differs, which is exactly what `same_target` has to notice. + app.ui.dialogs.clear(); + crate::filter_dialog::open(&mut app, "filter.blur.gaussianBlur").unwrap(); + let second_dialog = app.ui.dialogs.first().expect("a dialog is open").id; + assert_ne!(second_dialog, first_dialog, "a reopened dialog gets a new id"); + release.send(()).expect("released"); + + // The first dialog's frame arrives late and must not be painted under the second one. + // `discard_closed` usually reclaims it a frame earlier, which is why this drives the gate + // directly: the id check is the part that has to hold when that cleanup misses. The + // invariant is checked on every pass, not only at the end, because a wrongly published + // frame can still be replaced by the reopened dialog's own preview before we stop. + drive_until(&mut app, &ctx, "the first dialog's frame to arrive", |a| { + if let Some(preview) = &a.filter_preview { + assert_ne!(preview.key.dialog, first_dialog, "a reopened dialog painted the previous dialog's preview"); + } + !a.filter_preview_worker.busy() + }); +} + +#[test] +fn windows_uses_a_visible_crosshair() { + // #737: Windows' inverting crosshair vanishes over mid-grey; use a black/white glyph. + let ctx = egui::Context::default(); + let painter = egui::Painter::new(ctx, egui::LayerId::background(), egui::Rect::EVERYTHING); + let p = egui::pos2(10.0, 10.0); + assert_eq!(super::visible_crosshair(egui::CursorIcon::Crosshair, &painter, p, true), egui::CursorIcon::None); + assert_eq!(super::visible_crosshair(egui::CursorIcon::Crosshair, &painter, p, false), egui::CursorIcon::Crosshair); + assert_eq!(super::visible_crosshair(egui::CursorIcon::Move, &painter, p, true), egui::CursorIcon::Move); +} + +use super::*; + +/// #569: displays 1 (sRGB) and 4 (Display P3) side by side, and a document filled with an +/// sRGB colour. +fn app_on_two_displays() -> PhotocraftApp { + use photocraft_engine::color_cmds::resolve_profile; + use photocraft_engine::display_color::Display; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); + app.run("edit.fill", json!({"color": "#cc8040"})).unwrap(); + let icc = |id: &str| Some(resolve_profile(id, None, None).unwrap().to_bytes()); + app.session.color.set_displays(Ok(vec![ + Display { id: 1, name: "A".into(), frame: [0.0, 0.0, 100.0, 100.0], profile_name: None, icc: icc("srgb") }, + Display { id: 4, name: "B".into(), frame: [100.0, 0.0, 100.0, 100.0], profile_name: None, icc: icc("display-p3") }, + ])); + app +} + +#[test] +#[ignore = "manual texture-retention measurement on six 6 MP documents"] +fn closed_canvas_memory_measurement() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + ctx.input_mut(|i| i.max_texture_side = 8192); + for cycle in 1..=6 { + app.run("file.new", json!({"width":3000,"height":2000})).unwrap(); + ensure_texture(&mut app, &ctx, 0, None).unwrap(); + // Drain uploaded image deltas just as a renderer does; count live texture owners. + ctx.tex_manager().write().take_delta().clear(); + app.run("file.close", json!({})).unwrap(); + let bytes: usize = ctx.tex_manager().read().allocated().map(|(_, m)| m.bytes_used()).sum(); + println!("closed cycle={cycle} texture_bytes={bytes} rss={:?}", photocraft_testkit::perf::current_rss_bytes()); + } +} + +#[test] +fn closed_documents_release_navigator_but_keep_open_document_textures() { + let mut app = app_on_two_displays(); + let ctx = egui::Context::default(); + let first = app.session.active().unwrap().doc.clone(); + let a = ensure_texture(&mut app, &ctx, 0, Some(1)).unwrap().0; + // The same handle ownership as navigator_texture, without requiring a GPU adapter. + let tex = ctx.load_texture("navigator-test", egui::ColorImage::filled([64, 64], egui::Color32::WHITE), TextureOptions::LINEAR); + let nav = tex.id(); + app.navigator_textures.insert(first.id, (std::sync::Arc::downgrade(&first), 0, 0, tex)); + app.run("file.new", json!({"width":32,"height":32})).unwrap(); + let other = app.session.active().unwrap().doc.id; + let b = ensure_texture(&mut app, &ctx, 1, Some(1)).unwrap().0; + drop(app.session.close(0)); + app.sync_views(); + assert!(ctx.tex_manager().read().meta(a).is_none()); + assert!(ctx.tex_manager().read().meta(nav).is_none()); + assert!(ctx.tex_manager().read().meta(b).is_some()); + assert!(app.canvases.keys().all(|(id, _)| *id == other)); + assert!(app.navigator_textures.is_empty()); + app.session.add_document((*first).clone(), None); + app.sync_views(); + assert_ne!(ensure_texture(&mut app, &ctx, 1, Some(1)).unwrap().0, a, "reopening a preserved ID creates a fresh texture"); +} + +#[test] +fn only_themes_with_a_dot_pattern_tile_the_canvas_surround() { + // #4542: switching to Pro filled the empty workspace with red blocks on one GPU. Pro's + // dots are its canvas colour, so the tiled texture had nothing to show in the first place. + use crate::theme::ThemeKind; + let tiles = |ctx: &egui::Context, kind: ThemeKind| { + crate::theme::apply(ctx, kind); + let mut output = ctx.run_ui(Default::default(), |ui| paint_dots(ui, ui.max_rect(), true)); + output.textures_delta.clear(); + output.shapes.iter().any(|s| matches!(s.shape, egui::Shape::Mesh(_))) + }; + let uploaded = |ctx: &egui::Context| ctx.tex_manager().read().allocated().filter(|(_, meta)| meta.name == "canvas-dots").count(); + for kind in ThemeKind::ALL { + let ctx = egui::Context::default(); + let dotted = matches!(kind, ThemeKind::Studio | ThemeKind::StudioLight | ThemeKind::SolarizedDark); + assert_eq!(tiles(&ctx, kind), dotted, "{kind:?}"); + assert_eq!(uploaded(&ctx), usize::from(dotted), "{kind:?}"); + } + // The reported switch: a dotted theme, then Pro. + let ctx = egui::Context::default(); + assert!(tiles(&ctx, ThemeKind::Studio)); + assert!(!tiles(&ctx, ThemeKind::Pro)); + assert!(!tiles(&ctx, ThemeKind::ProMedium)); + assert_eq!(uploaded(&ctx), 1, "only Studio's dots were uploaded"); +} + +#[test] +fn closed_documents_release_cpu_canvas_textures() { + let mut app = app_on_two_displays(); + let ctx = egui::Context::default(); + let original = app.session.active().unwrap().doc.clone(); + for cycle in 0..12 { + if cycle > 0 { + app.session.add_document((*original).clone(), None); + app.sync_views(); + } + let a = ensure_texture(&mut app, &ctx, 0, Some(1)).unwrap().0; + let b = ensure_texture(&mut app, &ctx, 0, Some(4)).unwrap().0; + assert_ne!(a, b); + app.run("file.close", json!({})).unwrap(); + assert!(app.canvases.is_empty(), "closed canvas metadata retained at cycle {cycle}"); + assert!(ctx.tex_manager().read().meta(a).is_none(), "first display texture retained"); + assert!(ctx.tex_manager().read().meta(b).is_none(), "second display texture retained"); + } +} + +#[test] +fn cpu_canvas_textures_are_per_display() { + // Two windows of one document on different displays: each has its own texture of + // monitor values, and drawing them in turn re-renders neither. + let mut app = app_on_two_displays(); + let ctx = egui::Context::default(); + let id = app.session.documents()[0].doc.id; + let a = ensure_texture(&mut app, &ctx, 0, Some(1)).unwrap().0; + let b = ensure_texture(&mut app, &ctx, 0, Some(4)).unwrap().0; + assert_ne!(a, b); + app.perf.last_refresh = ""; + for _ in 0..3 { + assert_eq!(ensure_texture(&mut app, &ctx, 0, Some(1)).unwrap().0, a); + assert_eq!(ensure_texture(&mut app, &ctx, 0, Some(4)).unwrap().0, b); + } + assert_eq!(app.perf.last_refresh, "", "no re-render"); + let doc = app.session.documents()[0].doc.clone(); + assert!(canvas_display(&app, &doc, Some(1)).0.unwrap().is_identity()); + assert!(!canvas_display(&app, &doc, Some(4)).0.unwrap().is_identity()); + assert_ne!(app.canvases[&(id, 1)].tex_preview_key, app.canvases[&(id, 4)].tex_preview_key); + // An edit updates both. + app.run("edit.fill", json!({"color": "#2060c0"})).unwrap(); + ensure_texture(&mut app, &ctx, 0, Some(1)); + ensure_texture(&mut app, &ctx, 0, Some(4)); + let rev = app.session.documents()[0].revision; + assert_eq!((app.canvases[&(id, 1)].tex_revision, app.canvases[&(id, 4)].tex_revision), (rev, rev)); +} + +#[test] +fn cpu_canvas_shows_crisp_pixels_when_zoomed_in() { + // #4810: above 100% the CPU canvas shows each pixel as a square, like the GPU canvas's + // sharp nearest filter; below 100% it still filters. Both the first upload and a + // damage-rect update carry the sampling, since the renderer takes it from each delta. + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 2, "height": 2})).unwrap(); + let ctx = egui::Context::default(); + let tex = ensure_texture(&mut app, &ctx, 0, None).unwrap().0; + let uploads = |ctx: &egui::Context| { + let mut delta = ctx.tex_manager().write().take_delta(); + let seen = delta.set.get(&tex).into_iter().flatten().map(|d| (d.pos.is_some(), d.options)).collect::>(); + delta.clear(); + seen + }; + let crisp = TextureOptions { magnification: egui::TextureFilter::Nearest, ..TextureOptions::LINEAR }; + assert_eq!(uploads(&ctx), vec![(false, crisp)]); + app.run("select.rect", json!({"x": 0, "y": 0, "width": 1, "height": 1})).unwrap(); + ensure_texture(&mut app, &ctx, 0, None).unwrap(); + uploads(&ctx); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + assert_eq!(ensure_texture(&mut app, &ctx, 0, None).unwrap().0, tex); + assert_eq!(uploads(&ctx), vec![(true, crisp)], "a partial update keeps the crisp sampling"); +} + +/// A device that allows smaller textures than MAX_TEXTURE (2048 on some older GPUs and WebGL +/// contexts, and on the fallback adapter the GPU tests sometimes get under load): the canvas +/// texture is reduced to fit it. A 2600 px document was uploaded at full size, which egui +/// asserts on and the backend can't create. +#[test] +fn cpu_canvas_texture_fits_the_device_limit() { + for (side, (w, h), want) in [(2048, (2600, 1700), [1300, 850]), (2048, (5000, 2000), [1666, 666]), (8192, (5000, 2000), [2500, 1000])] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": w, "height": h})).unwrap(); + let ctx = egui::Context::default(); + ctx.input_mut(|i| i.max_texture_side = side); + let (tex, _) = ensure_texture(&mut app, &ctx, 0, None).unwrap(); + let mut delta = ctx.tex_manager().write().take_delta(); + let sizes: Vec<_> = delta.set.get(&tex).into_iter().flatten().map(|d| d.image.size()).collect(); + delta.clear(); + assert_eq!(sizes, vec![want], "{w}x{h} on a {side} px device"); + } +} + +#[test] +fn cpu_canvas_of_a_reduced_document_stays_bilinear() { + // Over MAX_TEXTURE the texture holds one texel per `factor` pixels: a texel is not a + // document pixel, so showing it as a square would draw blocks that aren't in the image. + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": MAX_TEXTURE + 1, "height": 2})).unwrap(); + let ctx = egui::Context::default(); + let (tex, scale) = ensure_texture(&mut app, &ctx, 0, None).unwrap(); + assert!(scale < 1.0); + let mut delta = ctx.tex_manager().write().take_delta(); + let uploads: Vec<_> = delta.set.get(&tex).into_iter().flatten().map(|d| d.options).collect(); + delta.clear(); + assert_eq!(uploads, vec![TextureOptions::LINEAR]); +} + +/// #7568: a document over the texture limit was drawn from one reduced texture, so at 100 % +/// it was magnified and blurred. The view now gets the part in sight at one texel per +/// document pixel, about the window's size, whatever the device's limit. +#[test] +fn cpu_canvas_detail_plan_shows_large_documents_at_full_resolution() { + let size = [12000, 8000]; + // A 1920×1080 view in the middle (`visible_doc_rect` adds 2 px around it). + let screen = DRect::new(4998, 2998, 6922, 4082); + for limit in [16384, 8192, 4096, 2048] { + let side = clamp_texture_side(limit); + assert!(texture_factor(size, side) > 1, "the whole document is reduced on a {limit} px device"); + for zoom in [1.0, 2.0, 8.0] { + let plan = detail_plan(size, side, zoom, screen).unwrap_or_else(|| panic!("{limit} px device at {zoom}")); + assert_eq!(plan.factor, 1, "one texel per document pixel at {zoom} on a {limit} px device"); + assert!(plan.region.contains_rect(&screen), "{plan:?}"); + assert!(plan.region.width() <= 1924 + 2 * 256 && plan.region.height() <= 1084 + 2 * 256, "about the view's size: {plan:?}"); + assert!(plan.region.width() < side && plan.region.height() < side, "{plan:?}"); + } + } + // A small pan reuses the region (no new composite). + assert_eq!(detail_plan(size, 4096, 1.0, screen), detail_plan(size, 4096, 1.0, screen.translate(8, -8))); + // A window wider than a small device's limit coarsens rather than exceed it. + let wide = DRect::new(0, 0, 3000, 2000); + let plan = detail_plan(size, 2048, 1.0, wide).unwrap(); + assert_eq!(plan.factor, 2); + assert!(plan.region.width() / 2 < 2048 && plan.region.contains_rect(&wide), "{plan:?}"); + // Zoomed out a little: finer than the reduced whole, as fine as the screen. + let plan = detail_plan(size, 4096, 0.4, DRect::new(0, 0, 4800, 2700)).unwrap(); + assert_eq!(plan.factor, 2); + // Zoomed out far enough, the reduced whole is as fine as the screen: nothing to add. + let whole = DRect::new(0, 0, 12000, 8000); + assert_eq!(detail_plan(size, 4096, 0.25, whole), None); + assert_eq!(detail_plan(size, 4096, 1.0 / 3.0, whole), None, "a detail as large as the document would not fit"); + // A document that fits is uploaded whole at full resolution. + assert_eq!(detail_plan([4000, 3000], 4096, 1.0, screen), None); + // Nothing of the document in view, or a broken zoom. + assert_eq!(detail_plan(size, 4096, 1.0, DRect::new(-500, -500, -10, -10)), None); + for zoom in [0.0, -1.0, f32::NAN, f32::INFINITY] { + assert_eq!(detail_plan(size, 4096, zoom, screen), None, "{zoom}"); + } + assert_eq!(detail_plan([0, 0], 4096, 1.0, screen), None); + assert_eq!(detail_plan([u32::MAX, 8], 4096, 1.0, screen), None); +} + +#[test] +fn cpu_canvas_detail_shows_a_large_documents_own_pixels_at_100_percent() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 3 * MAX_TEXTURE, "height": 8})).unwrap(); + app.run("select.rect", json!({"x": 101, "y": 0, "width": 1, "height": 8})).unwrap(); + app.run("edit.fill", json!({"color": "#000000"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + let ctx = egui::Context::default(); + ctx.input_mut(|i| i.max_texture_side = 16384); + let uploads = |ctx: &egui::Context, tex: egui::TextureId| { + let mut delta = ctx.tex_manager().write().take_delta(); + let seen: Vec<_> = delta.set.get(&tex).into_iter().flatten().map(|d| (d.pos, d.options, d.image.clone())).collect(); + delta.clear(); + seen + }; + let row = |image: &egui::ImageData| { + let egui::ImageData::Color(image) = image; + (image.size, image.pixels.clone()) + }; + let view = InView { visible: DRect::new(0, 0, 1000, 8), zoom: 1.0, key: 1 }; + let t = ensure_texture_in_view(&mut app, &ctx, 0, None, Some(view)).unwrap(); + assert!(t.scale < 1.0, "the whole document is reduced"); + let (detail, area) = t.detail.expect("a detail texture at 100 %"); + assert_eq!(area, [0.0, 0.0, 1024.0, 8.0]); + let crisp = TextureOptions { magnification: egui::TextureFilter::Nearest, ..TextureOptions::LINEAR }; + let up = uploads(&ctx, detail); + assert_eq!(up.len(), 1); + let (pos, options, image) = &up[0]; + assert_eq!((*pos, *options), (None, crisp)); + let (size, px) = row(image); + assert_eq!(size, [1024, 8]); + assert_eq!((px[100], px[101], px[102]), (Color32::WHITE, Color32::BLACK, Color32::WHITE), "the 1 px line stays 1 px"); + // Unchanged: nothing is composited again, and a small pan keeps the region. + let panned = InView { visible: DRect::new(4, 0, 1004, 8), ..view }; + assert_eq!(ensure_texture_in_view(&mut app, &ctx, 0, None, Some(panned)).unwrap().detail, Some((detail, area))); + assert!(uploads(&ctx, detail).is_empty()); + // The Navigator's call (no view) leaves the view's detail alone. + ensure_texture(&mut app, &ctx, 0, None).unwrap(); + assert_eq!(app.canvases.values().map(|c| c.detail.len()).sum::(), 1); + // An edit in view updates just its texels. + app.run("select.rect", json!({"x": 300, "y": 0, "width": 1, "height": 8})).unwrap(); + ensure_texture_in_view(&mut app, &ctx, 0, None, Some(view)).unwrap(); + uploads(&ctx, detail); + app.run("edit.fill", json!({"color": "#000000"})).unwrap(); + assert_eq!(ensure_texture_in_view(&mut app, &ctx, 0, None, Some(view)).unwrap().detail.map(|d| d.0), Some(detail)); + let up = uploads(&ctx, detail); + assert_eq!(up.len(), 1); + let (pos, options, image) = &up[0]; + assert_eq!(*options, crisp); + let [x, y] = pos.expect("a partial update"); + let (size, px) = row(image); + assert!(y == 0 && x < 300 && x + size[0] > 300, "the edit's texels: {x} {size:?}"); + assert_eq!((px[299 - x], px[300 - x]), (Color32::WHITE, Color32::BLACK)); + // Zoomed out, the reduced texture is enough: the detail goes. + let far = InView { zoom: 0.25, ..view }; + assert!(ensure_texture_in_view(&mut app, &ctx, 0, None, Some(far)).unwrap().detail.is_none()); + assert!(app.canvases.values().all(|c| c.detail.is_empty())); +} + +#[test] +fn gpu_display_luts_are_per_display() { + let _gpu = photocraft_testkit::gpu_lock(); + let Ok(rs) = std::panic::catch_unwind(|| egui_kittest::wgpu::create_render_state(crate::gpu_canvas::wgpu_setup(), Default::default())) else { + eprintln!("skipping: no GPU adapter"); + return; + }; + let mut app = app_on_two_displays(); + app.set_wgpu(rs); + let doc = app.session.documents()[0].doc.clone(); + let key = doc.id.0; + // sRGB on the sRGB display needs no LUT; on the P3 display it does. + assert_eq!(sync_display_lut(&mut app, &doc, key, Some(1)), 0); + assert_eq!(sync_display_lut(&mut app, &doc, key, Some(4)), 3); + let gpu = app.gpu.clone().unwrap(); + let (s1, s4) = (gpu.display_lut_signature(key, 1).unwrap(), gpu.display_lut_signature(key, 4).unwrap()); + assert_ne!(s1.0, s4.0); + assert!(gpu.has_display_lut(key, 4) && !gpu.has_display_lut(key, 1)); + // Drawing one window leaves the other's LUT alone. + for _ in 0..3 { + assert_eq!(sync_display_lut(&mut app, &doc, key, Some(1)), 0); + assert_eq!(sync_display_lut(&mut app, &doc, key, Some(4)), 3); + } + assert_eq!((gpu.display_lut_signature(key, 1), gpu.display_lut_signature(key, 4)), (Some(s1), Some(s4))); + assert!(gpu.has_display_lut(key, 4)); + // The shared texture's key is the same for both displays. + assert_eq!(texture_key(canvas_display(&app, &doc, Some(1)).0.as_deref()), texture_key(canvas_display(&app, &doc, Some(4)).0.as_deref())); +} + +/// The navigator's update after an edit (its image with the edit's damage, grown by the +/// effect reach, rendered over it) equals a new thumbnail of the edited document. +#[test] +fn navigator_damage_updates_match_a_full_thumbnail() { + use photocraft_compose::{render_reduced_damage, thumbnail_buffer, thumbnail_size}; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 1500, "height": 900, "background": "white"})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("select.rect", json!({"x": 200, "y": 150, "width": 300, "height": 200})).unwrap(); + app.run("edit.fill", json!({"color": "#3070a0"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + app.run("layer.layerStyle.dropShadow", json!({"distance": 30, "size": 20})).unwrap(); + let steps = [ + ("layer.translate", json!({"dx": 37, "dy": -11})), + ("layer.setProps", json!({"opacity": 0.4})), + ("paint.stroke", json!({"points": [[700, 500], [900, 520]], "size": 25})), + ("layer.setProps", json!({"blend": "Multiply"})), + ("layer.new.layer", json!({})), + ]; + for (id, p) in steps { + let before = app.session.active().unwrap().doc.clone(); + app.run(id, p).unwrap(); + let st = app.session.active().unwrap(); + let d = st.last_damage.unwrap_or_else(|| panic!("{id}: a bounded damage")); + let (w, h) = thumbnail_size(&st.doc, NAVIGATOR_SIDE); + let mut shown = thumbnail_buffer(&before, NAVIGATOR_SIDE); + assert_eq!((shown.rect.width(), shown.rect.height()), (w, h)); + if !d.is_empty() { + let patch = render_reduced_damage(&st.doc, w, h, d.inflate(effect_reach(&st.doc.layers))); + let r = patch.rect; + for y in 0..r.height() as usize { + let at = (r.y0 as usize + y) * w as usize + r.x0 as usize; + shown.px[at..at + r.width() as usize].copy_from_slice(&patch.px[y * r.width() as usize..][..r.width() as usize]); + } + } + assert!(shown.px == thumbnail_buffer(&st.doc, NAVIGATOR_SIDE).px, "{id}: the updated navigator differs from a new thumbnail"); + } +} + +#[test] +fn tab_context_uses_clicked_document_and_existing_close_commands() { + let items = tab_context_items(2, 3, true); + assert_eq!(items.iter().map(|(_, id, _, _)| *id).collect::>(), ["file.close", "file.closeOthers", "file.closeAll", "file.revealInFinder"]); + assert_eq!(items[0].2, json!({"document": 2})); + assert_eq!(items[1].2, json!({"document": 2})); + assert_eq!(items[2].2, json!({})); + assert_eq!(items[3].2, json!({"document": 2})); + assert!(items[3].3, "a saved document can be revealed in the file manager"); + assert!(!tab_context_items(2, 3, false)[3].3, "an unsaved document cannot"); + assert!(!tab_context_items(0, 1, false)[1].3); + assert!(items.iter().all(|(_, id, _, _)| photocraft_engine::commands::find(id).is_some())); +} + +#[test] +fn tab_context_reveal_names_the_platform_file_manager() { + let (label, id, _, _) = &tab_context_items(0, 1, true)[3]; + assert_eq!((*label, *id), (crate::menus::reveal_label(), "file.revealInFinder")); +} + +/// Photoshop's document tab × is after the title on Windows and Linux, before it on macOS (#619). +#[test] +fn document_tab_close_button_sits_on_the_platform_side() { + use egui::os::OperatingSystem as Os; + use egui_kittest::kittest::Queryable; + for (os, after_title) in [(Os::Windows, true), (Os::Nix, true), (Os::Mac, false)] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + app.sync_views(); + // Drawn from the second frame, once the Pro theme is set. + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(600.0, 40.0)).build_ui_state( + |ui, (app, ready): &mut (PhotocraftApp, bool)| { + if *ready { + tabs(app, ui); + } + }, + (app, false), + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Pro); + h.ctx.set_os(os); + h.state_mut().1 = true; + h.run_steps(2); + let tab = h.get_by_label_contains("Untitled @").rect(); + let x = h.get_by_label("Close").rect(); + assert!(tab.contains_rect(x), "{os:?}: the × is inside its tab"); + assert_eq!(x.center().x > tab.center().x, after_title, "{os:?}: × at {x:?} in tab {tab:?}"); + h.get_by_label("Close").click(); + h.run_steps(2); + assert!(h.state().0.session.documents().is_empty(), "{os:?}: the × closes the document"); + } +} + +/// Middle-clicking a document tab closes it (#2570), in both tab strips, and the tab under the +/// pointer is the one that goes even when another document is active. +#[test] +fn middle_clicking_a_tab_closes_that_document() { + use egui_kittest::kittest::Queryable; + for kind in [crate::theme::ThemeKind::Studio, crate::theme::ThemeKind::Pro] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + for name in ["keep", "doomed", "active"] { + app.run("file.new", json!({"width": 8, "height": 8, "name": name})).unwrap(); + } + app.sync_views(); + assert_eq!(app.session.active_index(), Some(2)); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(700.0, 40.0)).build_ui_state( + |ui, (app, ready): &mut (PhotocraftApp, bool)| { + if *ready { + tabs(app, ui); + } + }, + (app, false), + ); + PhotocraftApp::setup_context(&h.ctx, kind); + h.state_mut().1 = true; + h.run_steps(2); + h.get_by_label_contains("doomed").click_button(egui::PointerButton::Middle); + h.run_steps(2); + let names: Vec = h.state().0.session.documents().iter().map(|d| d.doc.name.clone()).collect(); + assert_eq!(names, ["keep", "active"], "{kind:?}: the middle-clicked tab closed"); + // A clean document closes straight away; a dirty one would park in `discard`. + assert!(h.state().0.discard.is_none(), "{kind:?}: nothing to prompt about"); + } +} + +/// A middle click goes through the same guarded `file.close` as the ×, so unsaved changes +/// still get the Save / Don’t Save / Cancel prompt instead of being thrown away (#2570). +#[test] +fn middle_clicking_an_edited_tab_prompts_instead_of_discarding() { + use egui_kittest::kittest::Queryable; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 8, "height": 8, "name": "edited"})).unwrap(); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.sync_views(); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(700.0, 40.0)).build_ui_state( + |ui, (app, ready): &mut (PhotocraftApp, bool)| { + if *ready { + tabs(app, ui); + } + }, + (app, false), + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Pro); + h.state_mut().1 = true; + h.run_steps(2); + h.get_by_label_contains("edited").click_button(egui::PointerButton::Middle); + h.run_steps(2); + assert!(h.state().0.discard.is_some(), "the unsaved-changes prompt must come up"); + assert_eq!(h.state().0.session.documents().len(), 1, "and the document is still open"); +} + +#[test] +fn spectrum_document_tabs_meet_canvas_without_a_gap() { + for kind in [crate::theme::ThemeKind::Pro, crate::theme::ThemeKind::ProMedium] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 80, "height": 60})).unwrap(); + app.sync_views(); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(680.0, 480.0)).build_ui_state( + |ui, (app, ready): &mut (PhotocraftApp, bool)| { + if *ready { + egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| document_area(app, ui)); + } + }, + (app, false), + ); + PhotocraftApp::setup_context(&h.ctx, kind); + h.state_mut().1 = true; + h.run_steps(3); + let app = &h.state().0; + let strip = app.tab_strip.as_ref().expect("a document opens with tabs").rect; + let gap = app.last_canvas_rect.top() - strip.bottom(); + assert!(gap.abs() < 0.1, "{kind:?}: document strip should touch canvas, got {gap} pt"); + } +} + +#[test] +fn large_tabs_preference_increases_tab_strip_height() { + use egui_kittest::kittest::Queryable; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + app.sync_views(); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(600.0, 60.0)).build_ui_state( + |ui, (app, ready): &mut (PhotocraftApp, bool)| { + if *ready { + tabs(app, ui); + } + }, + (app, false), + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Pro); + h.state_mut().1 = true; + h.run_steps(2); + let normal_h = h.get_by_label_contains("Untitled @").rect().height(); + assert_eq!(normal_h, 26.0); + + h.state_mut().0.session.execute("prefs.set", json!({"values": {"workspace.largeTabs": true}})).unwrap(); + h.run_steps(2); + let large_h = h.get_by_label_contains("Untitled @").rect().height(); + assert_eq!(large_h, 34.0); +} + +#[test] +fn tab_close_others_prompts_for_unsaved_nonactive_document() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 8, "height": 8, "name": "Keep"})).unwrap(); + app.run("file.new", json!({"width": 8, "height": 8, "name": "Edited"})).unwrap(); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + assert_eq!(app.session.active_index(), Some(1)); + let (_, id, params, _) = tab_context_items(0, 2, false)[1].clone(); + crate::menus::invoke(&mut app, &egui::Context::default(), id, params).unwrap(); + assert!(app.discard.is_some(), "close others must ask before discarding the edited tab"); + assert_eq!(app.session.documents().len(), 2); +} + +/// The pure half of tab drag-to-reorder (UI-217-6): where a drop lands and which +/// `document.move` target that is. +#[test] +fn tab_drop_index_and_move_target_cover_reorder_drops() { + let r = |x: f32| Rect::from_min_size(egui::pos2(x, 0.0), egui::vec2(100.0, 26.0)); + let placed = vec![(0, r(0.0)), (1, r(100.0)), (2, r(200.0))]; + assert_eq!(tab_drop_index(&placed, 10.0), 0); + assert_eq!(tab_drop_index(&placed, 160.0), 2); + assert_eq!(tab_drop_index(&placed, 350.0), 3, "past the end lands after the last shown tab"); + assert_eq!(tab_move_target(0, 3), 2); + assert_eq!(tab_move_target(2, 0), 0); + assert_eq!(tab_move_target(1, 1), 1, "before itself: no move"); + assert_eq!(tab_move_target(1, 2), 1, "just after itself: no move"); + assert_eq!(tab_move_target(0, 1), 0); +} + +/// Dragging a tab onto another's slot reorders the open documents (UI-217-6), in both the +/// studio and the Photoshop-style strips. +#[test] +fn dragging_a_tab_reorders_the_documents() { + use egui_kittest::kittest::Queryable; + for kind in [crate::theme::ThemeKind::Studio, crate::theme::ThemeKind::Pro] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + for name in ["a", "b", "c"] { + app.run("file.new", json!({"width": 8, "height": 8, "name": name})).unwrap(); + } + app.sync_views(); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(700.0, 40.0)).build_ui_state( + |ui, (app, ready): &mut (PhotocraftApp, bool)| { + if *ready { + tabs(app, ui); + } + }, + (app, false), + ); + PhotocraftApp::setup_context(&h.ctx, kind); + h.state_mut().1 = true; + h.run_steps(2); + let b = h.get_by_label_contains("b").rect(); + let a = h.get_by_label_contains("a").rect(); + let target = egui::pos2(a.left() + 2.0, a.center().y); + h.drag_at(b.center()); + h.run_steps(1); + h.hover_at(target); + h.run_steps(1); + h.drop_at(target); + h.run_steps(2); + let names: Vec = h.state().0.session.documents().iter().map(|d| d.doc.name.clone()).collect(); + assert_eq!(names, ["b", "a", "c"], "{kind:?}: the dragged tab took the dropped slot"); + } +} + +/// Dragging a tab off the strip floats its document in its own OS window instead of +/// reordering (#3733), in both strips; a short wobble below the strip still reorders. +#[test] +fn dragging_a_tab_off_the_strip_floats_it_in_a_window() { + use egui_kittest::kittest::Queryable; + let strip = Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(700.0, 26.0)); + assert!(!torn_off(strip, egui::pos2(50.0, 13.0))); + assert!(!torn_off(strip, egui::pos2(50.0, 26.0 + TEAR_OFF - 1.0)), "a wobble below the strip still reorders"); + assert!(torn_off(strip, egui::pos2(50.0, 26.0 + TEAR_OFF + 1.0))); + assert!(torn_off(strip, egui::pos2(50.0, -TEAR_OFF - 1.0)), "dragged up, off the window's top"); + for kind in [crate::theme::ThemeKind::Studio, crate::theme::ThemeKind::Pro] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + for name in ["a", "b", "c"] { + app.run("file.new", json!({"width": 8, "height": 8, "name": name})).unwrap(); + } + app.sync_views(); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(700.0, 300.0)).build_ui_state( + |ui, (app, ready): &mut (PhotocraftApp, bool)| { + if *ready { + tabs(app, ui); + } + }, + (app, false), + ); + PhotocraftApp::setup_context(&h.ctx, kind); + h.state_mut().1 = true; + h.run_steps(2); + let b = h.get_by_label_contains("b").rect(); + let target = egui::pos2(b.center().x, b.bottom() + 150.0); + h.drag_at(b.center()); + h.run_steps(1); + h.hover_at(target); + h.run_steps(1); + h.drop_at(target); + h.run_steps(2); + let app = &h.state().0; + let names: Vec<&str> = app.session.documents().iter().map(|d| d.doc.name.as_str()).collect(); + assert_eq!(names, ["a", "b", "c"], "{kind:?}: tearing off doesn't reorder"); + assert_eq!(app.ui.windows.iter().map(|w| w.document).collect::>(), [1], "{kind:?}: b floats in its own window"); + assert_eq!(app.session.active_index(), Some(1), "{kind:?}: the floated document is active"); + } +} + +#[test] +fn clone_overlay_is_circular_and_respects_visibility() { + let ctx = egui::Context::default(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); + app.run("cloneSource.set", json!({"source": [16,16]})).unwrap(); + app.ui.tool = Tool::CloneStamp; + app.session.tools.brush.size = 20.0; + let xf = ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(100.0, 100.0)), zoom: 1.0, center: [32.0, 32.0], flip: false, rotation: 0.0, aspect: 1.0 }; + let revision = app.session.active().unwrap().revision; + let mut output = ctx.run_ui(Default::default(), |ui| { + let ctx = ui.ctx(); + let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::unique("clone-test"))); + draw_clone_preview(&mut app, &painter, &xf, [32.0, 32.0], None); + }); + output.textures_delta.clear(); + let mesh = output + .shapes + .iter() + .find_map(|s| match &s.shape { + egui::Shape::Mesh(m) => Some(m), + _ => None, + }) + .unwrap(); + assert_eq!(mesh.indices.len(), 64 * 3); + let center = xf.to_screen(32.0, 32.0); + assert!(mesh.vertices.iter().all(|v| v.pos.distance(center) <= 10.01)); + assert_eq!(app.session.active().unwrap().revision, revision); + assert!(app.session.presets.clone.active().anchor.is_none()); + let ordinary_key = app.clone_preview.as_ref().unwrap().key.clone(); + app.ui.view.pattern_preview = true; + let mut periodic_output = ctx.run_ui(Default::default(), |ui| { + let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::unique("clone-test"))); + draw_clone_preview(&mut app, &painter, &xf, [32.0, 32.0], None); + }); + assert_ne!(app.clone_preview.as_ref().unwrap().key, ordinary_key, "toggling Pattern Preview invalidates source pixels"); + assert!(!periodic_output.textures_delta.set.is_empty(), "the overlay texture is refreshed without a document edit"); + periodic_output.textures_delta.clear(); + assert_eq!(app.session.active().unwrap().revision, revision); + app.session.presets.clone.overlay.show = false; + let mut output = ctx.run_ui(Default::default(), |ui| { + let ctx = ui.ctx(); + let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::unique("clone-test"))); + draw_clone_preview(&mut app, &painter, &xf, [32.0, 32.0], None); + }); + output.textures_delta.clear(); + assert!(output.shapes.iter().all(|s| !matches!(s.shape, egui::Shape::Mesh(_)))); +} + +#[test] +fn clone_overlay_keeps_magnified_pixels_crisp_on_upload_and_refresh() { + let ctx = egui::Context::default(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); + app.run("cloneSource.set", json!({"source": [16, 16]})).unwrap(); + app.ui.tool = Tool::CloneStamp; + app.session.tools.brush.size = 20.0; + let xf = ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(200.0, 200.0)), zoom: 4.0, center: [32.0, 32.0], flip: false, rotation: 0.0, aspect: 1.0 }; + for invert in [false, true] { + app.session.presets.clone.overlay.invert = invert; + let mut output = ctx.run_ui(Default::default(), |ui| { + draw_clone_preview(&mut app, ui.painter(), &xf, [32.0, 32.0], None); + }); + let upload = output.textures_delta.set.values().flatten().find(|d| d.image.size() == [20, 20]).expect("clone overlay upload"); + let options = upload.options; + output.textures_delta.clear(); + assert_eq!(options.magnification, egui::TextureFilter::Nearest, "invert={invert}"); + assert_eq!(options.minification, egui::TextureFilter::Linear, "zoomed-out previews remain filtered"); + } +} + +#[test] +fn clone_overlay_blend_mode_mixes_with_the_image_under_the_brush() { + let ctx = egui::Context::default(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); + app.run("cloneSource.set", json!({"source": [16,16]})).unwrap(); + app.ui.tool = Tool::CloneStamp; + app.session.tools.brush.size = 20.0; + let xf = ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(100.0, 100.0)), zoom: 1.0, center: [32.0, 32.0], flip: false, rotation: 0.0, aspect: 1.0 }; + // The centre texel of the overlay texture uploaded for `mode`. + let mut centre = |mode: &str| { + app.run("cloneSource.overlay", json!({"blend": mode})).unwrap(); + let mut output = ctx.run_ui(Default::default(), |ui| { + let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::unique("clone-test"))); + draw_clone_preview(&mut app, &painter, &xf, [32.0, 32.0], None); + }); + // The brush's 20 × 20 px square (the font atlas may upload too). + let image = output.textures_delta.set.values().flatten().find_map(|d| match &d.image { + egui::ImageData::Color(c) if c.size == [20, 20] => Some(c.clone()), + _ => None, + }); + output.textures_delta.clear(); + let image = image.expect("the overlay uploads a texture"); + image.pixels[image.width() * (image.height() / 2) + image.width() / 2] + }; + // A white source over the white image: Normal shows white, Difference black. + assert_eq!(centre("normal"), Color32::WHITE); + assert_eq!(centre("difference"), Color32::BLACK, "Difference turns black where source and image match"); + assert_eq!(centre("lighten"), Color32::WHITE); +} + +/// A shaped tip clips the Clone Source overlay to its outline, not to the brush circle. +#[test] +fn clone_overlay_is_clipped_to_a_shaped_tip() { + let ctx = egui::Context::default(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); + app.run("cloneSource.set", json!({"source": [16,16]})).unwrap(); + app.ui.tool = Tool::CloneStamp; + app.session.tools.brush.size = 20.0; + app.session.tools.brush.roundness = 0.25; + let xf = ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(100.0, 100.0)), zoom: 1.0, center: [32.0, 32.0], flip: false, rotation: 0.0, aspect: 1.0 }; + let mut output = ctx.run_ui(Default::default(), |ui| { + let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::unique("clone-test"))); + draw_clone_preview(&mut app, &painter, &xf, [32.0, 32.0], None); + }); + let image = output + .textures_delta + .set + .values() + .flatten() + .find_map(|d| match &d.image { + egui::ImageData::Color(c) if c.size == [20, 20] => Some(c.clone()), + _ => None, + }) + .expect("the overlay uploads a texture"); + output.textures_delta.clear(); + let alpha = |x: usize, y: usize| image.pixels[y * image.width() + x].a(); + assert_eq!(alpha(10, 10), 255, "the tip's centre shows the source"); + assert_eq!(alpha(10, 2), 0, "inside the circle but outside the flat tip: clipped"); + assert_eq!(alpha(1, 10), 255, "the tip's long axis stays"); +} + +#[test] +fn wayland_start_screen_hint_does_not_claim_file_drop_works() { + let x11 = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + let wayland = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services { is_wayland: true, ..Default::default() }); + assert!(start_screen_drop_hint(&x11).starts_with("Drop")); + // Pasting a copied image file works on Wayland (#338): the hint says how. + let hint = start_screen_drop_hint(&wayland); + assert!(!hint.contains("Drop"), "{hint}"); + assert!(hint.ends_with(&format!("paste a copied image with {}.", crate::notices::paste_hint(&wayland))), "{hint}"); +} + +/// A tiling window manager can hand PhotoCraft a canvas narrower than the Home card (460 +/// points): the two buttons must stay inside the window instead of being clipped at its edges. +#[test] +fn start_screen_buttons_stay_inside_a_narrow_canvas() { + use egui_kittest::kittest::Queryable; + for width in [390.0, 420.0, 520.0] { + let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(width, 760.0)).build_ui_state( + |ui, (app, ready): &mut (PhotocraftApp, bool)| { + if *ready { + egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| document_area(app, ui)); + } + }, + (app, false), + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::default()); + h.state_mut().1 = true; + h.run_steps(3); + for label in ["New document", "Join us on Discord"] { + for node in h.query_all_by_label_contains(label) { + let r = node.rect(); + assert!(r.left() >= 0.0 && r.right() <= width, "`{label}` is clipped in a {width}-point-wide canvas: {r:?}"); + } + } + } +} + +/// #4382: Interface › Show home recent files off hides the Home screen's list, not the recents. +#[test] +fn home_recent_list_hides_when_the_preference_is_off() { + use egui_kittest::kittest::Queryable; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.push_recent("/tmp/photocraft-217/hidden.psd"); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 760.0)).build_ui_state( + |ui, (app, ready): &mut (PhotocraftApp, bool)| { + if *ready { + egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| document_area(app, ui)); + } + }, + (app, false), + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::default()); + h.state_mut().1 = true; + h.run_steps(3); + assert!(h.query_by_label("hidden.psd").is_some(), "listed by default"); + h.state_mut().0.run("prefs.set", serde_json::json!({"values": {"interface.showHomeRecentFiles": false}})).unwrap(); + h.run_steps(3); + assert!(h.query_by_label("hidden.psd").is_none(), "hidden when off"); + assert_eq!(h.state().0.ui.recent_files.len(), 1, "the list itself is kept"); +} + +/// The Home screen's × takes a file off Recent without opening it, and its right-click menu +/// removes one entry or clears the list; the preferences keep the change (#2691). +#[test] +fn home_recent_entries_can_be_removed() { + use egui_kittest::kittest::Queryable; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + for name in ["c.tif", "b.psd", "a.png"] { + app.push_recent(&format!("/tmp/photocraft-2691/{name}")); + } + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 760.0)).build_ui_state( + |ui, (app, ready): &mut (PhotocraftApp, bool)| { + if *ready { + egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| document_area(app, ui)); + } + }, + (app, false), + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::default()); + h.state_mut().1 = true; + h.run_steps(3); + let listed = |h: &egui_kittest::Harness<'_, (PhotocraftApp, bool)>| { + let app = &h.state().0; + assert_eq!(app.session.prefs().file_handling.recent_files, app.ui.recent_files, "stored in the preferences"); + app.ui.recent_files.iter().map(|p| crate::file_open::display_name(p)).collect::>() + }; + assert_eq!(listed(&h), ["a.png", "b.psd", "c.tif"]); + assert!(h.query_by_label("Remove b.psd from Recent").is_none(), "the × shows on the hovered row only"); + + h.get_by_label("b.psd").hover(); + h.run_steps(2); + h.get_by_label("Remove b.psd from Recent").click(); + h.run_steps(2); + assert_eq!(listed(&h), ["a.png", "c.tif"]); + assert!(h.state().0.session.documents().is_empty(), "the file was not opened"); + + h.get_by_label("c.tif").click_secondary(); + h.run_steps(2); + h.get_by_label("Remove from Recent").click(); + h.run_steps(2); + assert_eq!(listed(&h), ["a.png"]); + + h.get_by_label("a.png").click_secondary(); + h.run_steps(2); + h.get_by_label("Clear Recent Files").click(); + h.run_steps(2); + assert!(listed(&h).is_empty()); + assert!(h.state().0.session.documents().is_empty()); +} + +#[test] +fn pointer_moves_are_bounded_by_the_press_and_release() { + use egui::{Event, PointerButton, pos2}; + let button = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + let events = [ + Event::PointerMoved(pos2(1.0, 0.0)), + button(pos2(2.0, 0.0), true), + Event::PointerMoved(pos2(3.0, 0.0)), + Event::PointerMoved(pos2(4.0, 0.0)), + button(pos2(5.0, 0.0), false), + Event::PointerMoved(pos2(6.0, 0.0)), + ]; + // The press is in this frame: only the moves between press and release count. + assert_eq!(pointer_moves(&events, PointerButton::Primary, false), vec![pos2(3.0, 0.0), pos2(4.0, 0.0)]); + // The button was already down when the frame began: the move before the release counts, + // the one after it does not. + assert_eq!(pointer_moves(&events, PointerButton::Primary, true), vec![pos2(1.0, 0.0), pos2(3.0, 0.0), pos2(4.0, 0.0)]); +} + +#[test] +fn freehand_tools_are_the_ones_that_follow_a_path() { + for t in [ + Tool::Brush, + Tool::Pencil, + Tool::MixerBrush, + Tool::ColorReplacement, + Tool::Eraser, + Tool::BackgroundEraser, + Tool::CloneStamp, + Tool::PatternStamp, + Tool::Smudge, + Tool::Dodge, + Tool::Lasso, + Tool::QuickSelection, + ] { + assert!(freehand_tool(t), "{t:?} paints or retouches along a path"); + } + for t in [Tool::Move, Tool::Eyedropper, Tool::Gradient, Tool::Crop, Tool::RectMarquee, Tool::Type, Tool::Hand] { + assert!(!freehand_tool(t), "{t:?} is driven by the pointer's latest position"); + } +} + +#[test] +fn clone_stamp_centre_appears_only_with_option() { + assert!(!brush_tip_centre(Tool::CloneStamp, false, false)); + assert!(brush_tip_centre(Tool::CloneStamp, true, false)); + assert!(brush_tip_centre(Tool::Healing, true, false)); + assert!(!brush_tip_centre(Tool::Healing, false, false)); + assert!(brush_tip_centre(Tool::CloneStamp, false, true)); + assert!(!brush_tip_centre(Tool::PatternStamp, true, false), "Pattern Stamp keeps the brush cursor; Option does not switch it to a clone-source mark"); + assert!(!brush_tip_centre(Tool::QuickSelection, false, true)); + assert!(brush_tip_centre(Tool::BackgroundEraser, false, false)); +} + +#[test] +fn brush_tip_centre_follows_the_crosshair_preference_at_any_size() { + // A large tip used to show the centre mark whatever Show Crosshair in Brush Tip said. + for tool in [Tool::Brush, Tool::Eraser, Tool::PatternStamp, Tool::Dodge] { + assert!(!brush_tip_centre(tool, false, false), "{tool:?}: off"); + assert!(brush_tip_centre(tool, false, true), "{tool:?}: on"); + } +} + +#[test] +fn view_transform_roundtrip() { + for flip in [false, true] { + let xf = + ViewXform { rect: Rect::from_min_size(pos2(100.0, 50.0), vec2(800.0, 600.0)), zoom: 2.5, center: [320.0, 240.0], flip, rotation: 0.0, aspect: 1.0 }; + let s = xf.to_screen(10.0, 20.0); + let d = xf.to_doc(s); + assert!((d[0] - 10.0).abs() < 1e-3 && (d[1] - 20.0).abs() < 1e-3); + assert_eq!(xf.to_screen(320.0, 240.0), xf.rect.center()); + // Flipped, document x grows to the left. + assert_eq!(xf.to_screen(330.0, 240.0).x > xf.rect.center().x, !flip); + let r = xf.doc_rect(DRect::new(0, 0, 10, 10)); + assert!(r.width() > 0.0 && r.height() > 0.0); + } +} + +#[test] +fn eyedropper_ring_colors_pair_the_sampled_and_current_colours() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 40, "height": 20, "background": "transparent"})).unwrap(); + app.run("shape.create", json!({"kind": "rect", "rect": [0, 0, 20, 20], "fill": "#ff0000"})).unwrap(); + app.run("tools.setColors", json!({"foreground": [0.0, 0.2, 1.0, 1.0]})).unwrap(); + let (new, current) = super::eyedropper_ring_colors(&mut app, 10.0, 10.0).expect("over the red square"); + let near = |c: egui::Color32, r: u8, g: u8, b: u8| { + let d = |a: u8, b: u8| i32::from(a).abs_diff(i32::from(b)); + d(c.r(), r) <= 1 && d(c.g(), g) <= 1 && d(c.b(), b) <= 1 + }; + assert!(near(new, 255, 0, 0), "{new:?}"); + assert!(near(current, 0, 51, 255), "{current:?}"); + // Transparency and points outside the canvas have nothing to compare. + assert!(super::eyedropper_ring_colors(&mut app, 30.0, 10.0).is_none()); + assert!(super::eyedropper_ring_colors(&mut app, -1.0, 10.0).is_none()); +} + +#[test] +fn eyedropper_drag_updates_the_sampled_colour() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 40, "height": 20, "background": "transparent"})).unwrap(); + app.run("shape.create", json!({"kind": "rect", "rect": [0, 0, 20, 20], "fill": "#ff0000"})).unwrap(); + app.run("shape.create", json!({"kind": "rect", "rect": [20, 0, 20, 20], "fill": "#00ff00"})).unwrap(); + app.ui.tool = Tool::Eyedropper; + + tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 10.0, pressure: 1.0 }, egui::Modifiers::NONE); + assert!(app.session.tools.foreground[0] > 0.99 && app.session.tools.foreground[1] < 0.01); + + tool_event(&mut app, ToolEvent::Move { x: 30.0, y: 10.0, pressure: 1.0 }, egui::Modifiers::NONE); + assert!(app.session.tools.foreground[1] > 0.99 && app.session.tools.foreground[0] < 0.01); +} + +/// #4298: an adjustment layer has no pixels, so after its icon thumbnail is clicked (the +/// Layers panel no longer targets the mask) Fill, the fill keys and the Paint Bucket still +/// edit its mask, as in Photoshop, instead of failing with "not a pixel layer". +#[test] +fn fills_on_an_adjustment_layer_edit_its_mask_when_the_icon_is_targeted() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 40, "height": 20, "background": "white"})).unwrap(); + app.run("layer.newAdjustmentLayer.curves", json!({})).unwrap(); + // Click the Curves icon thumbnail: the panel targets the layer, not its mask. + app.ui.mask_target = false; + app.sync_mask_targets(); + assert!(!app.ui.mask_target, "the panel's target is the icon"); + let mask_at = |app: &PhotocraftApp| { + let st = app.session.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().mask.as_ref().unwrap().surface.sample_channel(10, 10, 0) + }; + assert_eq!(paint_target(&app), json!("mask")); + assert!(crate::menus::is_enabled(&app, "edit.fill"), "Edit > Fill (⇧F5) is enabled"); + assert!(crate::menus::is_enabled(&app, "edit.fillForeground")); + app.ui.tool = Tool::PaintBucket; + app.run("tools.setColors", json!({"foreground": [0.0, 0.0, 0.0, 1.0], "background": [1.0, 1.0, 1.0, 1.0]})).unwrap(); + tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 10.0, pressure: 1.0 }, egui::Modifiers::NONE); + tool_event(&mut app, ToolEvent::Up { x: 10.0, y: 10.0 }, egui::Modifiers::NONE); + assert_eq!(mask_at(&app), 0.0, "the Paint Bucket filled the mask black"); + app.run("edit.fill", json!({"contents": "white"})).unwrap(); + assert_eq!(mask_at(&app), 1.0, "Edit > Fill filled the mask white"); + assert!(!app.ui.mask_target, "filling doesn't move the panel's target"); + // A pixel layer with an untargeted mask still paints its pixels. + app.run("layer.new.layer", json!({})).unwrap(); + app.run("layer.layerMask.revealAll", json!({})).unwrap(); + app.ui.mask_target = false; + assert_eq!(paint_target(&app), json!("pixels")); + assert!(!app.layer_mask_targeted()); +} + +#[test] +fn alt_with_a_painting_tool_samples_the_foreground_instead_of_painting() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 40, "height": 20, "background": "transparent"})).unwrap(); + app.run("shape.create", json!({"kind": "rect", "rect": [0, 0, 20, 20], "fill": "#ff0000"})).unwrap(); + app.run("shape.create", json!({"kind": "rect", "rect": [20, 0, 20, 20], "fill": "#00ff00"})).unwrap(); + let alt = egui::Modifiers::ALT; + for tool in [Tool::Brush, Tool::Pencil, Tool::Gradient, Tool::PaintBucket] { + app.ui.tool = tool; + app.run("tools.setColors", json!({"foreground": [0.0, 0.0, 1.0, 1.0], "background": [1.0, 1.0, 1.0, 1.0]})).unwrap(); + let rev = app.session.active().unwrap().revision; + tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 10.0, pressure: 1.0 }, alt); + assert_eq!(app.session.tools.foreground, [1.0, 0.0, 0.0, 1.0], "{tool:?}: ⌥-click sets the foreground"); + // A drag keeps sampling, even after ⌥ is let go; the background is untouched. + tool_event(&mut app, ToolEvent::Move { x: 30.0, y: 10.0, pressure: 1.0 }, egui::Modifiers::NONE); + assert_eq!(app.session.tools.foreground, [0.0, 1.0, 0.0, 1.0], "{tool:?}"); + tool_event(&mut app, ToolEvent::Up { x: 30.0, y: 10.0 }, egui::Modifiers::NONE); + assert_eq!(app.session.tools.background, [1.0, 1.0, 1.0, 1.0]); + assert_eq!(app.session.active().unwrap().revision, rev, "{tool:?}: sampling must not edit the document"); + assert!(app.drag.is_none() && !app.alt_sampling); + } + // Agents get the same through `ui.pointer` (MCP `ui_pointer`). + app.ui.tool = Tool::Brush; + let ctx = egui::Context::default(); + let events = json!([{"kind": "down", "x": 10, "y": 10}, {"kind": "up", "x": 10, "y": 10}]); + let (req, _rx) = crate::control::ControlRequest::new("ui.pointer", json!({"modifiers": {"alt": true}, "events": events})); + let _ = crate::control::handle(&mut app, &ctx, &req); + assert_eq!(app.session.tools.foreground, [1.0, 0.0, 0.0, 1.0]); + app.run("tools.setColors", json!({"foreground": [0.0, 1.0, 0.0, 1.0]})).unwrap(); + // Without ⌥ the Brush paints again, and ⌥ pressed mid-stroke doesn't switch to sampling. + app.run("layer.new.layer", json!({})).unwrap(); + let rev = app.session.active().unwrap().revision; + tool_event(&mut app, ToolEvent::Down { x: 5.0, y: 5.0, pressure: 1.0 }, egui::Modifiers::NONE); + tool_event(&mut app, ToolEvent::Move { x: 30.0, y: 5.0, pressure: 1.0 }, alt); + tool_event(&mut app, ToolEvent::Up { x: 30.0, y: 5.0 }, alt); + assert_eq!(app.session.tools.foreground, [0.0, 1.0, 0.0, 1.0]); + assert!(app.session.active().unwrap().revision > rev, "the stroke was painted"); + // Control+Alt stays the brush-resize gesture, never a sample. + assert!(!alt_samples(Tool::Brush, egui::Modifiers { alt: true, ctrl: true, ..Default::default() })); + assert!(!alt_samples(Tool::Eraser, alt), "⌥ with the Eraser is not the Eyedropper"); +} + +/// #2078: the opaque mask-view texture must show the live stroke, not cover it with +/// the committed mask until the mouse is released. +#[test] +fn mask_view_uploads_each_live_stroke_before_release() { + for depth in [8, 16, 32] { + for mode in ["gray", "overlay"] { + for (width, factor) in [(120u32, 1u32), (513, 3)] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": width, "height": 60, "depth": depth})).unwrap(); + app.run("layer.layerMask.revealAll", json!({})).unwrap(); + app.run("view.layerMask", json!({"mode": mode})).unwrap(); + app.run("tools.setColors", json!({"foreground": [0.0, 0.0, 0.0, 1.0]})).unwrap(); + app.run("tools.setBrush", json!({"brush": {"size": 12, "hardness": 1.0, "smoothing": {"amount": 0.0}}})).unwrap(); + app.ui.tool = Tool::Brush; + let ctx = egui::Context::default(); + ctx.input_mut(|i| i.max_texture_side = 256); + let tex = crate::channel_view::ensure(&mut app, &ctx, 0).unwrap(); + ctx.tex_manager().write().take_delta().clear(); + let revision = app.session.documents()[0].revision; + let steps = app.session.documents()[0].history.past_len(); + let layer = app.session.documents()[0].active_layer.unwrap(); + let original = app.session.documents()[0].doc.layer(layer).unwrap().clone(); + tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE); + for x in [30.0, 50.0, 70.0] { + tool_event(&mut app, ToolEvent::Move { x, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE); + let shown = display_doc(&mut app, 0).0; + assert!(shown.layer(layer).unwrap().mask.as_ref().unwrap().value(x as i32, 30) < 0.1); + assert_eq!(crate::channel_view::ensure(&mut app, &ctx, 0), Some(tex)); + let mut delta = ctx.tex_manager().write().take_delta(); + let uploads = delta.set.get(&tex).unwrap_or_else(|| panic!("{depth}-bit {mode}: live mask texture must upload before release at {x}")); + assert_eq!(uploads.len(), 1); + let upload = &uploads[0]; + let pos = upload.pos.expect("only the damaged region is uploaded"); + let egui::ImageData::Color(image) = &upload.image; + assert!(image.pixels.len() < (width.div_ceil(factor) * 60u32.div_ceil(factor)) as usize, "the whole mask is not uploaded"); + let f = factor as i32; + let r = DRect::new(pos[0] as i32 * f, pos[1] as i32 * f, (pos[0] + image.size[0]) as i32 * f, (pos[1] + image.size[1]) as i32 * f) + .intersect(&shown.bounds()); + let expected = crate::channel_view::render( + &shown, + &app.session.documents()[0].channel_view, + r, + factor, + crate::channel_view::Look::default(), + app.session.documents()[0].active_layer, + ) + .unwrap(); + assert_eq!(image.pixels, expected, "uploaded mask values match the live stroke"); + delta.clear(); + assert_eq!(app.session.documents()[0].revision, revision); + assert_eq!(app.session.documents()[0].history.past_len(), steps); + assert_eq!(app.session.documents()[0].doc.layer(layer).unwrap(), &original); + crate::channel_view::ensure(&mut app, &ctx, 0); + assert!(ctx.tex_manager().write().take_delta().set.is_empty(), "idle frame does not upload"); + } + tool_event(&mut app, ToolEvent::Up { x: 70.0, y: 30.0 }, egui::Modifiers::NONE); + let st = &app.session.documents()[0]; + assert_eq!(st.history.past_len(), steps + 1); + assert!(st.doc.layer(layer).unwrap().mask.as_ref().unwrap().value(50, 30) < 0.1); + assert_eq!(st.doc.layer(layer).unwrap().content, original.content); + crate::channel_view::ensure(&mut app, &ctx, 0); + let mut delta = ctx.tex_manager().write().take_delta(); + // The commit takes the live stroke's pixels, which the texture already shows: at + // most a partial upload, never the whole mask again. + assert!(delta.set.get(&tex).is_none_or(|u| u.iter().all(|u| u.pos.is_some())), "commit keeps its partial upload"); + delta.clear(); + app.session.undo(); + assert_eq!(app.session.documents()[0].doc.layer(layer).unwrap(), &original); + crate::channel_view::ensure(&mut app, &ctx, 0); + let mut delta = ctx.tex_manager().write().take_delta(); + let egui::ImageData::Color(image) = &delta.set.get(&tex).unwrap()[0].image; + let st = &app.session.documents()[0]; + assert_eq!( + image.pixels, + crate::channel_view::render(&st.doc, &st.channel_view, st.doc.bounds(), factor, crate::channel_view::Look::default(), st.active_layer) + .unwrap(), + "undo restores the shown mask" + ); + delta.clear(); + } + } + } +} + +#[test] +fn channel_views_show_live_targets_and_discarded_strokes() { + for target in ["quickMask", "alpha", "red"] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 120, "height": 60})).unwrap(); + match target { + "quickMask" => { + app.run("select.rect", json!({"x": 0, "y": 0, "width": 120, "height": 60})).unwrap(); + app.run("select.editInQuickMaskMode", json!({})).unwrap(); + } + "alpha" => { + app.run("channel.new", json!({"fill": "white"})).unwrap(); + } + _ => { + app.run("channel.target", json!({"channel": "red"})).unwrap(); + } + } + app.run("tools.setColors", json!({"foreground": [0.0, 0.0, 0.0, 1.0]})).unwrap(); + app.run("tools.setBrush", json!({"brush": {"size": 12, "hardness": 1.0, "smoothing": {"amount": 0.0}}})).unwrap(); + app.ui.tool = Tool::Brush; + let ctx = egui::Context::default(); + let tex = crate::channel_view::ensure(&mut app, &ctx, 0).unwrap(); + ctx.tex_manager().write().take_delta().clear(); + let original = app.session.documents()[0].doc.clone(); + let steps = app.session.documents()[0].history.past_len(); + tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE); + tool_event(&mut app, ToolEvent::Move { x: 50.0, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE); + let shown = display_doc(&mut app, 0).0; + crate::channel_view::ensure(&mut app, &ctx, 0); + let mut delta = ctx.tex_manager().write().take_delta(); + let upload = &delta.set.get(&tex).expect("live channel upload")[0]; + let pos = upload.pos.expect("partial channel upload"); + let egui::ImageData::Color(image) = &upload.image; + let r = DRect::new(pos[0] as i32, pos[1] as i32, (pos[0] + image.size[0]) as i32, (pos[1] + image.size[1]) as i32); + assert_eq!( + image.pixels, + crate::channel_view::render( + &shown, + &app.session.documents()[0].channel_view, + r, + 1, + crate::channel_view::Look::default(), + app.session.documents()[0].active_layer + ) + .unwrap(), + "{target}" + ); + assert_ne!( + image.pixels, + crate::channel_view::render( + &original, + &app.session.documents()[0].channel_view, + r, + 1, + crate::channel_view::Look::default(), + app.session.documents()[0].active_layer + ) + .unwrap(), + "target was painted" + ); + delta.clear(); + assert_eq!(app.session.documents()[0].history.past_len(), steps); + assert!(std::sync::Arc::ptr_eq(&original, &app.session.documents()[0].doc)); + // Dropping a preview without committing must restore its texture, even though the + // document revision did not change. There is no committed damage rectangle to use. + app.drag = None; + app.live_stroke = None; + crate::channel_view::ensure(&mut app, &ctx, 0); + let mut delta = ctx.tex_manager().write().take_delta(); + let upload = &delta.set.get(&tex).unwrap()[0]; + assert!(upload.pos.is_none(), "discarding a preview refreshes the view"); + let egui::ImageData::Color(image) = &upload.image; + assert_eq!( + image.pixels, + crate::channel_view::render( + &original, + &app.session.documents()[0].channel_view, + original.bounds(), + 1, + crate::channel_view::Look::default(), + app.session.documents()[0].active_layer + ) + .unwrap() + ); + delta.clear(); + } +} + +/// The held drag shows true mixed paint while Alt sampling remains separate from painting. +#[test] +fn mixer_drag_shows_actual_mixed_paint_before_release_and_alt_never_paints() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width":120,"height":60,"background":"#00ff00"})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("tools.setColors", json!({"foreground":"#ff0000"})).unwrap(); + app.run("tools.setBrush", json!({"brush":{"size":16,"mixer":{"wet":1.0,"mix":0.7,"sampleAllLayers":true},"smoothing":{"amount":0.0}}})).unwrap(); + app.ui.tool = Tool::MixerBrush; + let before = app.session.active().unwrap().doc.clone(); + let count = app.session.active().unwrap().history.past_len(); + let alt = egui::Modifiers { alt: true, ..Default::default() }; + tool_event(&mut app, ToolEvent::Down { x: 30.0, y: 30.0, pressure: 1.0 }, alt); + tool_event(&mut app, ToolEvent::Move { x: 35.0, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE); + tool_event(&mut app, ToolEvent::Up { x: 35.0, y: 30.0 }, egui::Modifiers::NONE); + assert!(app.drag.is_none()); + assert!(app.session.tools.mixer.spatial.is_some()); + assert!(std::sync::Arc::ptr_eq(&before, &app.session.active().unwrap().doc)); + app.run("brush.mixer.load", json!({})).unwrap(); + tool_event(&mut app, ToolEvent::Down { x: 20.0, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE); + tool_event(&mut app, ToolEvent::Move { x: 70.0, y: 30.0, pressure: 0.6 }, egui::Modifiers::NONE); + assert!(app.live_stroke.is_some()); + let shown = display_doc(&mut app, 0).0; + let id = app.session.active().unwrap().active_layer.unwrap(); + let pixel = shown.layer(id).unwrap().surface().unwrap().rgba(45, 30); + assert!(pixel[0] > 0.0 && pixel[1] > 0.0 && pixel[3] > 0.0, "actual red/green mixture {pixel:?}"); + assert!(std::sync::Arc::ptr_eq(&before, &app.session.active().unwrap().doc)); + assert_eq!(app.session.active().unwrap().history.past_len(), count); + tool_event(&mut app, ToolEvent::Up { x: 70.0, y: 30.0 }, egui::Modifiers::NONE); + let st = app.session.active().unwrap(); + assert_eq!(st.history.past_len(), count + 1); + assert_eq!( + shown.layer(id).unwrap().surface().unwrap().read_region(before.bounds()), + st.doc.layer(id).unwrap().surface().unwrap().read_region(before.bounds()) + ); + app.session.undo(); + assert_eq!(app.session.active().unwrap().doc.layer(id).unwrap().surface().unwrap().rgba(45, 30)[3], 0.0); +} + +/// Release incorporates its final endpoint and deferred samples in both live and fallback paths. +#[test] +fn mixer_release_includes_a_new_endpoint_and_deferred_frame_samples() { + for (deferred, failed) in [(false, false), (true, false), (false, true)] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width":120,"height":60,"background":"#00ff00"})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("tools.setBrush", json!({"size":12,"pressureSize":false})).unwrap(); + app.ui.tool = Tool::MixerBrush; + let before = app.session.active().unwrap().doc.clone(); + let m = egui::Modifiers::NONE; + tool_event(&mut app, ToolEvent::Down { x: 20.0, y: 30.0, pressure: 1.0 }, m); + app.defer_live_stroke = deferred; + if failed { + app.live_stroke.as_mut().unwrap().preview_failed = true; + } + tool_event(&mut app, ToolEvent::Move { x: 50.0, y: 30.0, pressure: 1.0 }, m); + tool_event(&mut app, ToolEvent::Up { x: 95.0, y: 30.0 }, m); + let doc = app.session.active().unwrap().doc.clone(); + let id = app.session.active().unwrap().active_layer.unwrap(); + assert!(doc.layer(id).unwrap().surface().unwrap().rgba(92, 30)[3] > 0.0); + let params = app.session.journal.iter().rev().find(|(name, _)| name == "paint.mixerBrush").unwrap().1.clone(); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(*app.session.active().unwrap().doc, *before); + app.run("paint.mixerBrush", params).unwrap(); + assert_eq!(*app.session.active().unwrap().doc, *doc); + } +} + +/// Reproduce a tool change and release in one control call, before a UI frame can cancel the old gesture. +#[test] +fn mixer_control_tool_switch_before_release_cancels_every_preview_path() { + for preview in 0..3 { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width":120,"height":60,"background":"#00ff00"})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("tools.setBrush", json!({"size":12,"pressureSize":false})).unwrap(); + let before = app.session.active().unwrap().doc.clone(); + let steps = app.session.active().unwrap().history.past_len(); + let anchor = app.last_stroke_end; + let ctx = egui::Context::default(); + let (request, _reply) = crate::control::ControlRequest::new( + "ui.pointer", + json!({"tool":"mixerBrush","events":[{"kind":"down","x":20,"y":30},{"kind":"move","x":50,"y":30}]}), + ); + let _ = crate::control::handle(&mut app, &ctx, &request); + assert!(app.drag.is_some() && app.live_stroke.is_some()); + if preview == 1 { + app.live_stroke.as_mut().unwrap().preview_failed = true; + } else if preview == 2 { + app.live_stroke = None; + } + // No intervening UI frame: control selects the new tool before dispatching Up. + let (request, _reply) = crate::control::ControlRequest::new("ui.pointer", json!({"tool":"brush","events":[{"kind":"up","x":95,"y":30}]})); + let _ = crate::control::handle(&mut app, &ctx, &request); + assert_eq!(app.ui.tool, Tool::Brush); + assert!(app.drag.is_none() && app.live_stroke.is_none()); + assert!(std::sync::Arc::ptr_eq(&before, &app.session.active().unwrap().doc)); + assert_eq!(app.session.active().unwrap().history.past_len(), steps); + assert_eq!(app.last_stroke_end, anchor); + assert!(!app.session.journal.iter().any(|(id, _)| id == "paint.mixerBrush")); + } +} + +/// Escape and tool changes cancel both ordinary previews and failed-preview fallback gestures. +#[test] +fn mixer_escape_and_tool_switch_cancel_without_an_edit() { + for mode in 0..4 { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width":120,"height":60,"background":"#00ff00"})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.ui.tool = Tool::MixerBrush; + let before = app.session.active().unwrap().doc.clone(); + let steps = app.session.active().unwrap().history.past_len(); + tool_event(&mut app, ToolEvent::Down { x: 30.0, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE); + assert!(app.live_stroke.is_some()); + if mode >= 2 { + app.live_stroke.as_mut().unwrap().preview_failed = true; + } + let mode = mode % 2; + let ctx = egui::Context::default(); + let mut raw = egui::RawInput { focused: true, ..Default::default() }; + if mode == 0 { + raw.events.push(egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }); + } + if mode == 1 { + app.ui.tool = Tool::Brush; + } + ctx.begin_pass(raw); + assert!(cancel_mixer_on_context_change(&mut app, &ctx)); + let mut output = ctx.end_pass(); + output.textures_delta.clear(); + tool_event(&mut app, ToolEvent::Up { x: 30.0, y: 30.0 }, egui::Modifiers::NONE); + assert!(app.drag.is_none() && app.live_stroke.is_none()); + assert!(std::sync::Arc::ptr_eq(&before, &app.session.active().unwrap().doc)); + assert_eq!(app.session.active().unwrap().history.past_len(), steps); + } +} + +/// Control-driven strokes remain live in a background window, matching the ordinary Brush. +#[test] +fn mixer_background_window_keeps_and_commits_control_strokes() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width":120,"height":60,"background":"transparent"})).unwrap(); + app.run("tools.setBrush", json!({"brush":{"size":12,"pressureSize":false}})).unwrap(); + let steps = app.session.active().unwrap().history.past_len(); + let ctx = egui::Context::default(); + ctx.begin_pass(egui::RawInput { focused: false, ..Default::default() }); + let (request, _reply) = + crate::control::ControlRequest::new("ui.pointer", json!({"tool":"mixerBrush","events":[{"kind":"down","x":20,"y":30},{"kind":"move","x":60,"y":30}]})); + let _ = crate::control::handle(&mut app, &ctx, &request); + assert!(!cancel_mixer_on_context_change(&mut app, &ctx)); + assert!(app.drag.is_some()); + let (request, _reply) = crate::control::ControlRequest::new("ui.pointer", json!({"tool":"mixerBrush","events":[{"kind":"up","x":95,"y":30}]})); + let _ = crate::control::handle(&mut app, &ctx, &request); + let mut output = ctx.end_pass(); + output.textures_delta.clear(); + assert_eq!(app.session.active().unwrap().history.past_len(), steps + 1); + assert!(app.session.journal.iter().any(|(id, _)| id == "paint.mixerBrush")); + let st = app.session.active().unwrap(); + assert!(st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().rgba(60, 30)[3] > 0.0); +} + +/// A tip above the live preview's 1024 px paints on release, as main and Photoshop paint it +/// up to 5000 px; a stroke that can't paint at all is still refused on press. +#[test] +fn mixer_drag_above_the_preview_size_paints_on_release() { + for locked in [false, true] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width":120,"height":60,"background":"#00ff00"})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + if locked { + app.run("layer.lockLayers", json!({"pixels": true})).unwrap(); + } + app.run("tools.setColors", json!({"foreground":"#ff0000"})).unwrap(); + app.run("tools.setBrush", json!({"brush":{"size":2000,"hardness":1.0,"pressureSize":false,"mixer":{"wet":0.0,"mix":0.0}}})).unwrap(); + app.ui.tool = Tool::MixerBrush; + let steps = app.session.active().unwrap().history.past_len(); + let m = egui::Modifiers::NONE; + tool_event(&mut app, ToolEvent::Down { x: 20.0, y: 30.0, pressure: 1.0 }, m); + assert!(app.live_stroke.is_none(), "no live preview above 1024 px"); + assert_eq!(app.drag.is_some(), !locked, "a valid 2000 px stroke is kept for release"); + assert_eq!(app.ui.status_error, locked, "{}", app.ui.status); + tool_event(&mut app, ToolEvent::Move { x: 50.0, y: 30.0, pressure: 1.0 }, m); + tool_event(&mut app, ToolEvent::Up { x: 50.0, y: 30.0 }, m); + let st = app.session.active().unwrap(); + assert_eq!(st.history.past_len(), steps + usize::from(!locked)); + let pixel = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().rgba(60, 30); + assert_eq!(pixel[0] > 0.9 && pixel[3] > 0.9, !locked, "{pixel:?}"); + } +} + +/// ⌥ with a held temporary tool (macOS ⌘ = Move) is that tool's, not a Mixer Brush paint load. +#[test] +fn mixer_alt_with_a_held_temporary_tool_does_not_load_paint() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width":120,"height":60,"background":"#00ff00"})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.ui.tool = Tool::MixerBrush; + app.tool_override = Some(Tool::Move); + let alt = egui::Modifiers { alt: true, ..Default::default() }; + tool_event(&mut app, ToolEvent::Down { x: 30.0, y: 30.0, pressure: 1.0 }, alt); + tool_event(&mut app, ToolEvent::Up { x: 30.0, y: 30.0 }, alt); + assert!(app.session.tools.mixer.spatial.is_none(), "the held Move tool doesn't sample"); + app.tool_override = None; + tool_event(&mut app, ToolEvent::Down { x: 30.0, y: 30.0, pressure: 1.0 }, alt); + assert!(app.session.tools.mixer.spatial.is_some(), "⌥ with the Mixer Brush itself samples"); +} + +#[test] +fn brush_drag_shows_the_real_stroke_and_commits_it() { + // The drag used to draw a hard, flat stand-in and only showed the soft brush on release. + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 120, "height": 60, "background": "transparent"})).unwrap(); + app.run("tools.setBrush", json!({"brush": {"size": 20, "hardness": 0.0}})).unwrap(); + app.ui.tool = Tool::Brush; + let m = egui::Modifiers::NONE; + let alpha = |d: &Document, x, y| d.layers[0].surface().unwrap().rgba(x, y)[3]; + let rev = app.session.documents()[0].revision; + tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 30.0, pressure: 1.0 }, m); + for x in [40.0, 70.0, 100.0] { + tool_event(&mut app, ToolEvent::Move { x, y: 30.0, pressure: 1.0 }, m); + } + let (shown, key) = display_doc(&mut app, 0); + assert_ne!(key, 0); + // A partial value two thirds of the way out: the soft tip, not a hard flat stand-in. + assert!(alpha(&shown, 40, 30) > 0.5 && (0.01..0.95).contains(&alpha(&shown, 40, 36)), "soft stroke while drawing"); + assert_eq!(alpha(&app.session.documents()[0].doc, 40, 30), 0.0, "not committed yet"); + // The canvas redraws only what the stroke touched. + let dk = canvas_display(&app, &app.session.documents()[0].doc, None).1; + let d = damage_since(&app, 0, (rev, dk), (rev, key), dk, None).unwrap(); + assert!(d.contains(40, 30) && !d.contains(40, 2) && d.height() < 60, "{d:?}"); + tool_event(&mut app, ToolEvent::Up { x: 100.0, y: 30.0 }, m); + let doc = app.session.documents()[0].doc.clone(); + assert!(app.live_stroke.is_none() && display_doc(&mut app, 0).1 == 0); + assert_eq!((alpha(&doc, 40, 30), alpha(&doc, 40, 38)), (alpha(&shown, 40, 30), alpha(&shown, 40, 38)), "commit matches the preview"); +} + +#[test] +fn live_stroke_uses_pen_tilt_and_updates_a_reduced_texture_partially() { + // Pen tilt drives the size; the preview must use the tilt the commit gets. The document + // is wider than MAX_TEXTURE, so the CPU texture is reduced (factor 2) and each step + // must update only the reduced pixels it touched. + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + ctx.input_mut(|i| i.max_texture_side = 8192); + app.run("file.new", json!({"width": 4097, "height": 90, "background": "transparent"})).unwrap(); + let tilt = json!({"size": 30, "hardness": 1.0, "spacing": 0.05, "shapeDynamics": {"enabled": true, "size": {"control": "penTilt"}}}); + app.run("tools.setBrush", json!({ "brush": tilt })).unwrap(); + app.ui.tool = Tool::Brush; + assert_eq!(ensure_texture(&mut app, &ctx, 0, None).map(|t| t.1), Some(0.5)); + let m = egui::Modifiers::NONE; + app.stylus.feed.set(Some(crate::stylus::PenSample { pressure: 1.0, tilt_x: 60.0, tilt_y: 0.0, rotation: 0.0, eraser: false })); + tool_event(&mut app, ToolEvent::Down { x: 100.0, y: 45.0, pressure: 1.0 }, m); + for x in [300.0, 600.0, 900.0] { + tool_event(&mut app, ToolEvent::Move { x, y: 45.0, pressure: 1.0 }, m); + ensure_texture(&mut app, &ctx, 0, None); + assert_eq!(app.perf.last_refresh, "rect"); + assert!(app.perf.last_refresh_px < 4097 * 90 / 4, "{}", app.perf.last_refresh_px); + } + let shown = display_doc(&mut app, 0).0; + tool_event(&mut app, ToolEvent::Up { x: 900.0, y: 45.0 }, m); + ensure_texture(&mut app, &ctx, 0, None); + assert_eq!(app.perf.last_refresh, "rect", "the commit refreshes only the stroke"); + let doc = app.session.documents()[0].doc.clone(); + let (a, b) = (doc.layers[0].surface().unwrap(), shown.layers[0].surface().unwrap()); + // 60° tilt shrinks the dab well below 30 px: the preview shows that size, as committed. + assert!(a.rgba(500, 45)[3] > 0.5 && a.rgba(500, 45 + 12)[3] == 0.0); + // (The smoothed tail catches up to the end point only when the stroke finishes.) + assert!((0..90).all(|y| (0..700).all(|x| a.rgba(x, y) == b.rgba(x, y))), "commit matches the preview"); +} + +/// Brush drag along y = 40 with one canvas frame per pointer move; returns the document the +/// canvas showed at the last move, the committed one, and whether the release refreshed only +/// the stroke's rectangle. +fn drag_frames(smoothing: f32, xs: &[f64]) -> (std::sync::Arc, std::sync::Arc, bool, PhotocraftApp) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 200, "height": 80, "background": "transparent"})).unwrap(); + app.run("tools.setBrush", json!({"brush": {"size": 16, "hardness": 0.5}})).unwrap(); + // What the options bar's Smoothing field writes. + app.session.tools.brush.smoothing.amount = smoothing; + app.ui.tool = Tool::Brush; + ensure_texture(&mut app, &ctx, 0, None); + let m = egui::Modifiers::NONE; + tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 40.0, pressure: 1.0 }, m); + for &x in xs { + tool_event(&mut app, ToolEvent::Move { x, y: 40.0 + (x / 7.0).sin() * 8.0, pressure: 1.0 }, m); + ensure_texture(&mut app, &ctx, 0, None); + } + let live = display_doc(&mut app, 0).0; + let last = *xs.last().unwrap(); + tool_event(&mut app, ToolEvent::Up { x: last, y: 40.0 + (last / 7.0).sin() * 8.0 }, m); + let (next, key) = display_doc(&mut app, 0); + assert_eq!(key, 0, "the frame after release shows the committed document"); + ensure_texture(&mut app, &ctx, 0, None); + let partial = app.perf.last_refresh == "rect"; + (live, next, partial, app) +} + +fn same_pixels(a: &Document, b: &Document) -> bool { + let (a, b) = (a.layers[0].surface().unwrap(), b.layers[0].surface().unwrap()); + (0..80).all(|y| (0..200).all(|x| a.rgba(x, y) == b.rgba(x, y))) +} + +#[test] +fn release_shows_nothing_new_without_smoothing() { + // #73: at 0 % the stroke follows the pointer; the last frame drawn while dragging is + // exactly the committed stroke, so release changes nothing on screen. + let (live, done, partial, app) = drag_frames(0.0, &[40.0, 70.0, 100.0, 130.0, 160.0]); + assert!(same_pixels(&live, &done), "preview at the last move = committed stroke"); + assert!(partial, "the handover refreshes only the stroke"); + let p = app.session.journal.iter().rev().find(|(id, _)| id == "paint.stroke").map(|(_, p)| p.clone()).unwrap(); + assert!(p.get("smoothing").is_none(), "the commit uses the session brush's smoothing, not a hard-coded one"); +} + +#[test] +fn navigator_keeps_its_image_during_a_live_brush_stroke() { + // #1631: every step of a live stroke is a new preview key, so a navigator keyed by it + // re-composited the whole document per frame while painting. It waits for the release. + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 80, "background": "transparent"})).unwrap(); + app.ui.tool = Tool::Brush; + let m = egui::Modifiers::NONE; + assert!(!navigator_waits_for_drag(&app, 0)); + tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 40.0, pressure: 1.0 }, m); + let mut keys = Vec::new(); + for x in [40.0, 70.0, 100.0] { + tool_event(&mut app, ToolEvent::Move { x, y: 40.0, pressure: 1.0 }, m); + keys.push(display_doc(&mut app, 0).1); + assert!(navigator_waits_for_drag(&app, 0), "painting at x = {x}"); + } + assert!(keys.windows(2).all(|k| k[0] != k[1]), "each step is a new preview: {keys:?}"); + tool_event(&mut app, ToolEvent::Up { x: 100.0, y: 40.0 }, m); + assert!(!navigator_waits_for_drag(&app, 0), "the navigator catches up on release"); +} + +#[test] +fn smoothed_stroke_shows_its_catch_up_tail_while_drawing() { + // #73: with smoothing the brush lags behind the pointer and catches up at the end; the + // preview draws that tail live, so no frame after release is missing the end. + let xs = [30.0, 50.0, 70.0, 90.0, 110.0, 130.0, 150.0, 170.0]; + let (live, done, partial, _) = drag_frames(0.5, &xs); + assert!(same_pixels(&live, &done), "preview at the last move = committed stroke, tail included"); + assert!(partial); + let end = |d: &Document| (0..200).rev().find(|&x| (0..80).any(|y| d.layers[0].surface().unwrap().rgba(x, y)[3] > 0.0)).unwrap(); + assert!(end(&live) >= 170, "the end reaches the pointer while drawing ({})", end(&live)); + // The options-bar value reaches the stroke: 50 % smooths the wiggle, 0 % doesn't. + let (_, rough, _, _) = drag_frames(0.0, &xs); + assert!(!same_pixels(&rough, &done), "smoothing changes the stroke"); + // And the commit is what `paint.stroke` gives with that smoothing. + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 200, "height": 80, "background": "transparent"})).unwrap(); + s.execute("tools.setBrush", json!({"brush": {"size": 16, "hardness": 0.5, "smoothing": {"amount": 0.5}}})).unwrap(); + let mut pts = vec![json!([10.0, 40.0, 1.0])]; + pts.extend(xs.iter().map(|&x| json!([x, 40.0 + (x / 7.0).sin() * 8.0, 1.0]))); + // (Round tips without dynamics draw the same for any seed.) + s.execute("paint.stroke", json!({"points": pts, "seed": 0})).unwrap(); + assert!(same_pixels(&s.active().unwrap().doc, &done)); +} + +#[test] +fn smoothing_preview_redraws_the_tail_each_step() { + // The tail drawn at one step must not linger once the brush moves on: a sharp turn would + // leave a stale tail behind if it weren't restored. + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 120, "background": "transparent"})).unwrap(); + app.run("tools.setBrush", json!({"brush": {"size": 10, "hardness": 1.0, "smoothing": {"amount": 0.6}}})).unwrap(); + app.ui.tool = Tool::Brush; + let m = egui::Modifiers::NONE; + tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 20.0, pressure: 1.0 }, m); + for (x, y) in [(60.0, 20.0), (110.0, 20.0), (110.0, 70.0), (110.0, 110.0), (60.0, 110.0)] { + tool_event(&mut app, ToolEvent::Move { x, y, pressure: 1.0 }, m); + } + let live = display_doc(&mut app, 0).0; + tool_event(&mut app, ToolEvent::Up { x: 60.0, y: 110.0 }, m); + let done = app.session.documents()[0].doc.clone(); + let (a, b) = (live.layers[0].surface().unwrap(), done.layers[0].surface().unwrap()); + assert!((0..120).all(|y| (0..200).all(|x| a.rgba(x, y) == b.rgba(x, y))), "no stale tails in the preview"); +} + +/// Shapes the drag preview paints for `app` this frame. +fn drag_preview_shapes(app: &mut PhotocraftApp, ctx: &egui::Context, zoom: f32) -> Vec { + let out = ctx.run_ui(egui::RawInput::default(), |ui| { + let ctx = ui.ctx(); + let rect = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)); + let painter = ctx.layer_painter(egui::LayerId::background()).with_clip_rect(rect); + let xf = ViewXform { rect, zoom, center: [60.0, 30.0], flip: false, rotation: 0.0, aspect: 1.0 }; + draw_drag_preview(app, &painter, &xf); + }); + let egui::FullOutput { mut textures_delta, shapes, .. } = out; + textures_delta.clear(); + shapes +} + +#[test] +fn a_huge_view_centre_draws_the_selection_outline_without_overflow() { + // #980: `ui.set` takes any finite centre, and the outline's visible region was quantised + // with unchecked i32 arithmetic: the frame panicked ("attempt to multiply/subtract with + // overflow") and release builds wrapped to an inverted region. + let ctx = egui::Context::default(); + // Zoomed far out the quantisation step, and so the padding, is largest (64 · 256 px). + let cases = [([1e30, 1e30], false), ([-1e30, -1e30], false), ([3e9, -3e9], false), ([512.0, 512.0], true)]; + for ((centre, traced), zoom) in cases.into_iter().flat_map(|c| [(c, 1.0), (c, 1.0 / 64.0)]) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 1024, "height": 1024})).unwrap(); + app.run("select.rect", json!({"x": 0, "y": 0, "width": 512, "height": 512})).unwrap(); + app.sync_views(); + let (req, _rx) = crate::control::ControlRequest::new("ui.set", json!({ "center": centre, "zoom": zoom })); + let _ = crate::control::handle(&mut app, &ctx, &req); + let view = app.ui.views[0].clone(); + assert_eq!(view.zoom, zoom, "ui.set applied the zoom"); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + canvas_view(&mut app, ui, 0, Rect::from_min_size(Pos2::ZERO, vec2(200.0, 200.0)), view.clone(), false); + }); + out.textures_delta.clear(); + // Control: a centre on the selection's corner still traces the outline (the selection + // spans several 64 px trace cells even zoomed out). + let segs = app.outline_cache.as_ref().map_or(0, |(_, _, s)| s.len()); + assert_eq!(segs > 0, traced, "{centre:?} at zoom {zoom}"); + } +} + +#[test] +fn a_one_pixel_selection_traces_at_hundred_percent_on_a_scaled_display() { + // #1943 review: the outline step is display resolution in device pixels, not points, so a + // 1 px selection still traces at 100 % on a 2x display (a points-based step sampled every + // second pixel and lost it: zero segments). + let ctx = egui::Context::default(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("select.rect", json!({"x": 50, "y": 50, "width": 1, "height": 100})).unwrap(); + app.run("view.actualPixels", json!({})).unwrap(); + app.sync_views(); + let view = app.ui.views[0].clone(); + let mut input = egui::RawInput::default(); + input.viewports.entry(egui::ViewportId::ROOT).or_default().native_pixels_per_point = Some(2.0); + let mut out = ctx.run_ui(input, |ui| { + canvas_view(&mut app, ui, 0, Rect::from_min_size(Pos2::ZERO, vec2(200.0, 200.0)), view.clone(), true); + }); + out.textures_delta.clear(); + assert_eq!(app.ppp, 2.0, "the primary canvas records the display scale"); + let segs = app.outline_cache.as_ref().map_or(0, |(_, _, s)| s.len()); + assert!(segs > 0, "a 1 px selection traces at 100 % on a 2x display"); +} + +#[test] +fn a_secondary_canvas_does_not_overwrite_the_main_canvas_scale() { + // #1943 review: a document window can sit on a display with another scale; only the + // primary canvas records `app.ppp`, so the main mapping doesn't change under it. + let ctx = egui::Context::default(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("view.actualPixels", json!({})).unwrap(); + app.sync_views(); + let view = app.ui.views[0].clone(); + let frame = |app: &mut PhotocraftApp, ppp: f32, primary: bool| { + let mut input = egui::RawInput::default(); + input.viewports.entry(egui::ViewportId::ROOT).or_default().native_pixels_per_point = Some(ppp); + let mut out = ctx.run_ui(input, |ui| { + canvas_view(app, ui, 0, Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)), view.clone(), primary); + }); + out.textures_delta.clear(); + }; + frame(&mut app, 2.0, true); + assert_eq!(app.ppp, 2.0); + frame(&mut app, 1.0, false); + assert_eq!(app.ppp, 2.0, "a secondary window's scale doesn't replace the main canvas's"); + // The main canvas mapping still uses its own scale: 100 % is 1 doc px per physical px. + let xf = ViewXform::active(&app).unwrap(); + let step = xf.to_screen(1.0, 0.0) - xf.to_screen(0.0, 0.0); + assert!((step.x - 0.5).abs() < 1e-3, "{step:?}"); +} + +#[test] +fn a_flicked_hand_drag_glides_on_only_with_flick_panning() { + // #204: Preferences › Tools › Enable Flick Panning. A fast Hand drag let go while moving + // keeps the view gliding for a while; off, the view stops where the drag ended. + for flick in [true, false] { + let ctx = egui::Context::default(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 2000, "height": 1500})).unwrap(); + app.run("prefs.set", json!({"path": "tools.enableFlickPanning", "value": flick})).unwrap(); + app.ui.tool = Tool::Hand; + app.sync_views(); + let mut view = app.ui.views[0].clone(); + view.zoom = 1.0; + view.center = [1000.0, 750.0]; + view.fit_pending = false; + view.fill_pending = false; + let rect = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)); + let mut frame = |app: &mut PhotocraftApp, events: Vec| -> View { + let input = egui::RawInput { screen_rect: Some(rect), events, ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + view = canvas_view(app, ui, 0, rect, view.clone(), true); + }); + out.textures_delta.clear(); + view.clone() + }; + let start = Pos2::new(200.0, 150.0); + let press = + |pos: Pos2, pressed: bool| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + frame(&mut app, vec![egui::Event::PointerMoved(start)]); + frame(&mut app, vec![press(start, true)]); + let mut end = start; + for i in 1..=8 { + end = start + vec2(-20.0 * i as f32, 0.0); + frame(&mut app, vec![egui::Event::PointerMoved(end)]); + } + let released = frame(&mut app, vec![press(end, false)]).center; + let mut centers = vec![released]; + for _ in 0..5 { + centers.push(frame(&mut app, vec![]).center); + } + if flick { + // Dragged left: the image follows the pointer, the view keeps moving right. + for w in centers.windows(2) { + assert!(w[1][0] > w[0][0], "glides on: {centers:?}"); + } + // ...and comes to rest. + let mut last = *centers.last().unwrap(); + for _ in 0..120 { + last = frame(&mut app, vec![]).center; + } + assert_eq!(frame(&mut app, vec![]).center, last, "the glide stops"); + } else { + assert!(centers.iter().all(|c| *c == released), "no glide when off: {centers:?}"); + } + } +} + +#[test] +fn a_secondary_canvas_hand_pans_while_a_transform_is_open() { + // #2302 review: `app.ui.transform` is global, but only the primary canvas draws and drives + // the box. A secondary window's Hand must still pan while the main window transforms. + let ctx = egui::Context::default(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("select.rect", json!({"x": 100, "y": 100, "width": 100, "height": 60})).unwrap(); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + app.run("view.actualPixels", json!({})).unwrap(); + app.ui.tool = Tool::Hand; + app.sync_views(); + crate::transform_tool::begin(&mut app, &ctx).expect("a transform starts"); + let mut view0 = app.ui.views[0].clone(); + view0.zoom = 1.0; + view0.center = [200.0, 150.0]; + view0.fit_pending = false; + view0.fill_pending = false; + let center0 = view0.center; + let rect = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)); + let frame = |app: &mut PhotocraftApp, events: Vec| -> View { + let input = egui::RawInput { screen_rect: Some(rect), events, ..Default::default() }; + let mut seen = view0.clone(); + let mut out = ctx.run_ui(input, |ui| { + seen = canvas_view(app, ui, 0, rect, view0.clone(), false); + }); + out.textures_delta.clear(); + seen + }; + let start = Pos2::new(200.0, 150.0); + let press = |pos: Pos2, pressed: bool| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + frame(&mut app, vec![egui::Event::PointerMoved(start)]); + frame(&mut app, vec![press(start, true)]); + for dx in [10.0, 20.0, 40.0] { + frame(&mut app, vec![egui::Event::PointerMoved(start + vec2(dx, 0.0))]); + } + let dragged = frame(&mut app, vec![egui::Event::PointerMoved(start + vec2(60.0, 0.0))]); + frame(&mut app, vec![press(start + vec2(60.0, 0.0), false)]); + assert_ne!(dragged.center, center0, "a secondary window's Hand pans while transforming"); +} + +#[test] +fn letting_go_of_alt_during_an_alt_sample_press_does_not_paint() { + // #7802: Alt-pressing with the Brush samples a colour on the press. If Alt was let go + // before egui recognised the drag, that drag started a stroke from the sampled point. + let ctx = egui::Context::default(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300, "background": "white"})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("view.actualPixels", json!({})).unwrap(); + app.ui.tool = Tool::Brush; + app.sync_views(); + let mut view = app.ui.views[0].clone(); + view.zoom = 1.0; + view.center = [200.0, 150.0]; + view.fit_pending = false; + view.fill_pending = false; + let rect = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)); + let frame = |app: &mut PhotocraftApp, events: Vec| { + let input = egui::RawInput { screen_rect: Some(rect), events, ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + canvas_view(app, ui, 0, rect, view.clone(), true); + }); + out.textures_delta.clear(); + }; + let alt = egui::Modifiers::ALT; + let none = egui::Modifiers::NONE; + let start = Pos2::new(200.0, 150.0); + let press = + |pos: Pos2, pressed: bool, modifiers: egui::Modifiers| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers }; + // Alt released mid-press, and Alt held throughout: both only sample. + for release_alt in [true, false] { + app.run("tools.setColors", json!({"foreground": [0.0, 0.0, 1.0, 1.0]})).unwrap(); + let rev = app.session.active().unwrap().revision; + frame(&mut app, vec![egui::Event::ModifiersChanged(alt), egui::Event::PointerMoved(start)]); + frame(&mut app, vec![press(start, true, alt)]); + assert_eq!(app.session.tools.foreground, [1.0, 1.0, 1.0, 1.0], "the press sampled the white canvas"); + let later = if release_alt { none } else { alt }; + let end = start + vec2(20.0, 0.0); + frame(&mut app, vec![egui::Event::ModifiersChanged(later), egui::Event::PointerMoved(end)]); + frame(&mut app, vec![press(end, false, later)]); + frame(&mut app, vec![egui::Event::ModifiersChanged(none)]); + assert_eq!(app.session.active().unwrap().revision, rev, "release_alt={release_alt}: an Alt-sample press must not paint"); + assert!(app.drag.is_none() && !app.alt_sampling, "release_alt={release_alt}"); + } + // Without Alt the same gesture paints. + let rev = app.session.active().unwrap().revision; + frame(&mut app, vec![egui::Event::PointerMoved(start)]); + frame(&mut app, vec![press(start, true, none)]); + frame(&mut app, vec![egui::Event::PointerMoved(start + vec2(20.0, 0.0))]); + frame(&mut app, vec![press(start + vec2(20.0, 0.0), false, none)]); + assert!(app.session.active().unwrap().revision > rev, "a plain drag paints"); +} + +#[test] +fn letting_go_of_alt_during_a_mixer_brush_sample_press_does_not_paint() { + // As #7802 for the Brush: an Alt-press with the Mixer Brush loads paint from the canvas. + // If Alt was let go before egui recognised the drag, that drag started a Mixer stroke. + let ctx = egui::Context::default(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300, "background": "white"})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("view.actualPixels", json!({})).unwrap(); + app.ui.tool = Tool::MixerBrush; + app.sync_views(); + let mut view = app.ui.views[0].clone(); + view.zoom = 1.0; + view.center = [200.0, 150.0]; + view.fit_pending = false; + view.fill_pending = false; + let rect = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)); + let frame = |app: &mut PhotocraftApp, events: Vec| { + let input = egui::RawInput { screen_rect: Some(rect), events, ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + canvas_view(app, ui, 0, rect, view.clone(), true); + }); + out.textures_delta.clear(); + }; + let (alt, none) = (egui::Modifiers::ALT, egui::Modifiers::NONE); + let start = Pos2::new(200.0, 150.0); + let press = + |pos: Pos2, pressed: bool, modifiers: egui::Modifiers| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers }; + // Alt released mid-press, and Alt held throughout: both only load paint. + for release_alt in [true, false] { + let rev = app.session.active().unwrap().revision; + frame(&mut app, vec![egui::Event::ModifiersChanged(alt), egui::Event::PointerMoved(start)]); + frame(&mut app, vec![press(start, true, alt)]); + let later = if release_alt { none } else { alt }; + let end = start + vec2(20.0, 0.0); + frame(&mut app, vec![egui::Event::ModifiersChanged(later), egui::Event::PointerMoved(end)]); + frame(&mut app, vec![press(end, false, later)]); + frame(&mut app, vec![egui::Event::ModifiersChanged(none)]); + assert_eq!(app.session.active().unwrap().revision, rev, "release_alt={release_alt}: an Alt-sample press must not paint"); + assert!(app.drag.is_none() && !app.mixer_sampling, "release_alt={release_alt}"); + } + // Without Alt the same gesture paints. + let rev = app.session.active().unwrap().revision; + frame(&mut app, vec![egui::Event::PointerMoved(start)]); + frame(&mut app, vec![press(start, true, none)]); + frame(&mut app, vec![egui::Event::PointerMoved(start + vec2(20.0, 0.0))]); + frame(&mut app, vec![press(start + vec2(20.0, 0.0), false, none)]); + assert!(app.session.active().unwrap().revision > rev, "a plain drag paints"); +} + +#[test] +fn guides_draw_over_the_transform_preview_and_under_its_box() { + // #5086: a guide crossing a layer under Free Transform was hidden behind the preview of + // the moving pixels. The preview is image content, drawn before the grid and guides like + // the document is; the box and handles still go over them, as in Photoshop. + let ctx = egui::Context::default(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("select.rect", json!({"x": 100, "y": 100, "width": 100, "height": 60})).unwrap(); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + app.run("view.newGuide", json!({"orientation": "vertical", "position": 150})).unwrap(); + app.ui.extras.guides = true; + app.ui.extras.rulers = false; + app.sync_views(); + crate::transform_tool::begin(&mut app, &ctx).expect("a transform starts"); + let mut view = app.ui.views[0].clone(); + view.zoom = 1.0; + view.center = [200.0, 150.0]; + view.fit_pending = false; + view.fill_pending = false; + let rect = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)); + let input = egui::RawInput { screen_rect: Some(rect), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + canvas_view(&mut app, ui, 0, rect, view.clone(), true); + }); + out.textures_delta.clear(); + // At 100 % centred on the document, screen and document coordinates coincide. + let layer = Rect::from_min_max(pos2(100.0, 100.0), pos2(200.0, 160.0)); + let near = |r: Rect| (r.min - layer.min).length() < 1.0 && (r.max - layer.max).length() < 1.0; + let position = |pred: &dyn Fn(&egui::Shape) -> bool| out.shapes.iter().position(|s| pred(&s.shape)); + // The moving pixels: the mesh that spans the layer's box. + let preview = position(&|s| matches!(s, egui::Shape::Mesh(m) if near(m.calc_bounds()))); + // The guide: a vertical line at x = 150. + let guide = position(&|s| matches!(s, egui::Shape::LineSegment { points, .. } if points.iter().all(|p| (p.x - 150.0).abs() < 0.01))); + // The box: the closed four-point outline round the layer. + let frame = position(&|s| matches!(s, egui::Shape::Path(p) if p.closed && p.points.len() == 4 && near(Rect::from_points(&p.points)))); + let (Some(preview), Some(guide), Some(frame)) = (preview, guide, frame) else { + panic!("all painted: preview {preview:?}, guide {guide:?}, box {frame:?}"); + }; + assert!(preview < guide, "the guide ({guide}) draws over the transform preview ({preview})"); + assert!(guide < frame, "the box ({frame}) draws over the guide ({guide})"); +} + +#[test] +fn guides_draw_over_the_puppet_perspective_and_vanishing_point_previews() { + // #7781: like Free Transform's (#5086), the warped pixels of Puppet Warp and Perspective + // Warp and Vanishing Point's paste are image content. They were drawn with their pins and + // planes, after the guides, hiding every guide across them; the guides now go over them, + // the mesh lines, pins and planes over the guides, as in Photoshop. + for command in ["edit.puppetWarp", "edit.perspectiveWarp", photocraft_engine::vp_cmds::VP] { + let ctx = egui::Context::default(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("select.rect", json!({"x": 100, "y": 100, "width": 100, "height": 60})).unwrap(); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + if command == photocraft_engine::vp_cmds::VP { + app.run("edit.copy", json!({})).unwrap(); + } + app.run("select.deselect", json!({})).unwrap(); + app.run("view.newGuide", json!({"orientation": "vertical", "position": 150})).unwrap(); + app.ui.extras.guides = true; + app.ui.extras.rulers = false; + app.sync_views(); + crate::distort_ui::menu(&mut app, &ctx, command, &json!({})).expect("an on-canvas mode").expect("it starts"); + if command == photocraft_engine::vp_cmds::VP { + // A plane over the document; the clipboard pastes onto it. + for (x, y) in [(20.0, 280.0), (380.0, 280.0), (300.0, 40.0), (100.0, 40.0)] { + crate::distort_ui::pointer(&mut app, ToolEvent::Down { x, y, pressure: 1.0 }, egui::Modifiers::NONE); + crate::distort_ui::pointer(&mut app, ToolEvent::Up { x, y }, egui::Modifiers::NONE); + } + } else if command == "edit.perspectiveWarp" { + // One plane, dragged out across the guide. + crate::distort_ui::pointer(&mut app, ToolEvent::Down { x: 60.0, y: 70.0, pressure: 1.0 }, egui::Modifiers::NONE); + crate::distort_ui::pointer(&mut app, ToolEvent::Move { x: 240.0, y: 190.0, pressure: 1.0 }, egui::Modifiers::NONE); + crate::distort_ui::pointer(&mut app, ToolEvent::Up { x: 240.0, y: 190.0 }, egui::Modifiers::NONE); + assert_eq!(app.distort.perspective.as_ref().map(|s| s.planes.len()), Some(1), "the drag makes a plane"); + } + let mut view = app.ui.views[0].clone(); + view.zoom = 1.0; + view.center = [200.0, 150.0]; + view.fit_pending = false; + view.fill_pending = false; + let rect = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)); + let input = egui::RawInput { screen_rect: Some(rect), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + canvas_view(&mut app, ui, 0, rect, view.clone(), true); + }); + out.textures_delta.clear(); + // At 100 % centred on the document, screen and document coordinates coincide. + let layer = Rect::from_min_max(pos2(100.0, 100.0), pos2(200.0, 160.0)); + // Puppet Warp's mesh reaches its Expansion (2 px) past the pixels. + let near = |r: Rect| (r.min - layer.min).length() < 4.0 && (r.max - layer.max).length() < 4.0; + let shapes: Vec<&egui::Shape> = out.shapes.iter().map(|s| &s.shape).collect(); + // The warped pixels (or the paste): a textured mesh over the layer (or on the plane, + // well inside the document, unlike the checkerboard and document image). + let preview = shapes.iter().position(|s| match s { + egui::Shape::Mesh(m) if m.texture_id != egui::TextureId::default() => { + let r = m.calc_bounds(); + if command == photocraft_engine::vp_cmds::VP { r.width() > 10.0 && r.width() < 300.0 && r.min.x < 150.0 && r.max.x > 150.0 } else { near(r) } + } + _ => false, + }); + // The guide: a vertical line at x = 150 across the whole view. + let is_guide = |s: &egui::Shape| matches!(s, egui::Shape::LineSegment { points, .. } if points.iter().all(|p| (p.x - 150.0).abs() < 0.01) && (points[1].y - points[0].y).abs() > 200.0); + let guide = shapes.iter().position(|s| is_guide(s)); + // Over the guide: Puppet Warp's mesh lines, the Vanishing Point plane's outline, the + // Perspective Warp plane's outline (exactly the dragged rectangle). + let plane = Rect::from_min_max(pos2(60.0, 70.0), pos2(240.0, 190.0)); + let overlay = shapes.iter().position(|s| match s { + egui::Shape::LineSegment { points, .. } => { + command != "edit.perspectiveWarp" && !is_guide(s) && points.iter().all(|p| layer.expand(3.0).contains(*p)) + } + egui::Shape::Path(p) => { + p.closed + && p.points.len() == 4 + && (command != "edit.perspectiveWarp" + || (Rect::from_points(&p.points).min - plane.min).length() + (Rect::from_points(&p.points).max - plane.max).length() < 0.5) + } + _ => false, + }); + let (Some(preview), Some(guide)) = (preview, guide) else { + panic!("{command}: all painted: preview {preview:?}, guide {guide:?}"); + }; + assert!(preview < guide, "{command}: the guide ({guide}) draws over the warped pixels ({preview})"); + let Some(overlay) = overlay else { panic!("{command}: its mesh or plane is drawn") }; + assert!(guide < overlay, "{command}: the mesh or plane ({overlay}) draws over the guide ({guide})"); + } +} + +#[test] +fn brush_drags_paint_no_stand_in_shape_over_the_canvas() { + // #189: v0.1 drew the stroke being dragged as a foreground-coloured egui polyline as wide + // as the brush; zoomed in, egui tessellated it into hard black wedges fanning out from the + // start. The canvas shows the real stroke (`LiveStroke`) and nothing is drawn over it. + let ctx = egui::Context::default(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 120, "height": 60})).unwrap(); + app.run("tools.setBrush", json!({"brush": {"size": 30, "hardness": 0.0}})).unwrap(); + // A smoothed stroke also draws its string line (see + // `smoothed_brush_drag_draws_the_string_from_brush_to_pointer`): that is no stand-in shape. + let overlay = |app: &mut PhotocraftApp, ctx: &egui::Context| { + drag_preview_shapes(app, ctx, 12.0).iter().filter(|s| !matches!(s.shape, egui::Shape::LineSegment { .. } | egui::Shape::Circle(_))).count() + }; + for tool in [Tool::Brush, Tool::Eraser] { + app.ui.tool = tool; + let idle = overlay(&mut app, &ctx); + tool_event(&mut app, ToolEvent::Down { x: 20.0, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE); + for i in 1..40 { + let t = f64::from(i); + tool_event(&mut app, ToolEvent::Move { x: 20.0 + t, y: 30.0 + (t / 3.0).sin() * 4.0, pressure: 1.0 }, egui::Modifiers::NONE); + } + assert!(app.live_stroke.is_some(), "{tool:?}: the canvas shows the live stroke"); + assert_eq!(overlay(&mut app, &ctx), idle, "{tool:?}: no overlay while dragging"); + tool_event(&mut app, ToolEvent::Up { x: 59.0, y: 30.0 }, egui::Modifiers::NONE); + } +} + +#[test] +fn smoothed_brush_drag_draws_the_string_from_brush_to_pointer() { + // #3479: with smoothing the brush lags behind the pointer; a line joins them while drawing. + let ctx = egui::Context::default(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 120, "height": 60})).unwrap(); + app.ui.tool = Tool::Brush; + let lines = |app: &mut PhotocraftApp| drag_preview_shapes(app, &ctx, 4.0).iter().filter(|s| matches!(s.shape, egui::Shape::LineSegment { .. })).count(); + for (amount, string) in [(0.0, false), (0.8, true)] { + app.run("tools.setBrush", json!({"brush": {"size": 10, "smoothing": {"amount": amount}}})).unwrap(); + tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE); + for x in [30.0, 60.0, 90.0] { + tool_event(&mut app, ToolEvent::Move { x, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE); + } + assert_eq!(lines(&mut app) > 0, string, "smoothing {amount}"); + tool_event(&mut app, ToolEvent::Up { x: 90.0, y: 30.0 }, egui::Modifiers::NONE); + } +} + +#[test] +fn retouch_drags_show_the_footprint_without_wedges() { + // The retouching tools' trail was the same brush-wide polyline (#189): now a mask of the + // footprint, with nothing outside the brush radius of the path, however small the steps. + let ctx = egui::Context::default(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 120, "height": 60})).unwrap(); + app.run("tools.setBrush", json!({"brush": {"size": 30}})).unwrap(); + // Remove: the dab tools draw their stroke live instead of a trail, and Spot Healing's + // trail is its dabs' coverage. + app.ui.tool = Tool::Remove; + tool_event(&mut app, ToolEvent::Down { x: 20.0, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE); + let mut pts = vec![[20.0, 30.0]]; + for i in 1..80 { + let t = f64::from(i) * 0.5; + let p = [20.0 + t, 30.0 + (t / 2.0).sin() * 3.0]; + tool_event(&mut app, ToolEvent::Move { x: p[0], y: p[1], pressure: 1.0 }, egui::Modifiers::NONE); + pts.push(p); + if i % 20 == 0 { + // One mesh for the trail, however long the drag. + let shapes = drag_preview_shapes(&mut app, &ctx, 12.0); + assert!(!shapes.iter().any(|s| matches!(s.shape, egui::Shape::Path(_))), "no polyline"); + } + } + drag_preview_shapes(&mut app, &ctx, 12.0); + let trail = app.trail.as_ref().unwrap(); + assert_eq!(trail.scale(), 1.0); + for y in 0..60 { + for x in 0..120 { + let d = pts.iter().map(|p| (x as f64 + 0.5 - p[0]).hypot(y as f64 + 0.5 - p[1])).fold(f64::MAX, f64::min); + if d < 14.0 { + assert_eq!(trail.coverage(x, y), 255, "({x}, {y}) inside the footprint"); + } else if d > 16.0 { + assert_eq!(trail.coverage(x, y), 0, "({x}, {y}) outside the footprint"); + } + } + } + tool_event(&mut app, ToolEvent::Up { x: 59.5, y: 30.0 }, egui::Modifiers::NONE); + drag_preview_shapes(&mut app, &ctx, 12.0); + assert!(app.trail.is_none(), "the trail ends with the drag"); +} + +#[test] +fn spot_healing_trail_is_the_coverage_the_heal_uses() { + // #2364: a soft brush with pen-pressure size showed as a hard footprint at full size. + let ctx = egui::Context::default(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 120, "height": 60})).unwrap(); + let brush = json!({"size": 30, "hardness": 0.0, "shapeDynamics": {"enabled": true, "size": {"control": "penPressure"}}}); + app.run("tools.setBrush", json!({ "brush": brush })).unwrap(); + app.ui.tool = Tool::SpotHealing; + tool_event(&mut app, ToolEvent::Down { x: 20.0, y: 30.0, pressure: 0.5 }, egui::Modifiers::NONE); + for x in [40.0, 60.0, 80.0] { + tool_event(&mut app, ToolEvent::Move { x, y: 30.0, pressure: 0.5 }, egui::Modifiers::NONE); + drag_preview_shapes(&mut app, &ctx, 12.0); + } + // The stroke the heal gets on release, and its coverage. + let points = app.drag.as_ref().unwrap().points.iter().map(|p| photocraft_paint::StrokePoint::new(p[0], p[1], p[2] as f32)).collect(); + let brush = photocraft_engine::retouch_cmds::stroke_brush(&app.session.tools.brush, &json!({})); + let (b, cov) = photocraft_paint::retouch::stroke_coverage(&photocraft_paint::Stroke { brush, points }); + let trail = app.trail.as_ref().unwrap(); + let mut soft = 0; + for y in 0..60 { + for x in 0..120 { + let want = if b.contains(x, y) { cov[(y - b.y0) as usize * b.width() as usize + (x - b.x0) as usize] } else { 0.0 }; + let got = trail.coverage(x as usize, y as usize); + assert!((f32::from(got) - want * 255.0).abs() <= 1.0, "({x}, {y}): trail {got}, heal {want}"); + soft += usize::from(got > 0 && got < 200); + } + } + assert!(soft > 50, "a soft brush shows a soft edge"); + // Half pressure halves the 30 px tip: nothing past its (soft) reach. + let reach = photocraft_paint::tip_reach(7.5, app.session.tools.brush.hardness).ceil() as usize + 2; + assert_eq!(trail.coverage(50, 30 + reach), 0, "half pressure halves the 30 px tip"); +} + +#[test] +fn layer_style_dialog_previews_live_and_cancel_restores() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 16, "height": 16})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + let fx = |d: &Document| d.layers.iter().map(|l| l.effects.items.len()).sum::(); + let id = crate::layer_style::open(&mut app, Some("colorOverlay")).unwrap(); + let (shown, key) = display_doc(&mut app, 0); + assert_eq!((fx(&shown), fx(&app.session.documents()[0].doc)), (1, 0), "previewed, not committed"); + // Adding a stroke through the dialog's instance list re-renders the canvas. + if let Some(d) = app.ui.dialog_mut(id) { + d.fields["effects"].as_array_mut().unwrap().push(json!({"id": "fx9", "kind": "stroke", "on": true, "params": {"size": 3}})); + } + let (shown, key2) = display_doc(&mut app, 0); + assert_eq!(fx(&shown), 2); + assert_ne!(key, key2, "an edit re-renders the canvas"); + app.ui.close_dialog(id); + let (shown, key) = display_doc(&mut app, 0); + assert_eq!((fx(&shown), key), (0, 0)); + assert!(app.style_preview.is_none()); +} + +/// Layer Style opened while Free Transform is open applies the box first, as Photoshop does, +/// so the dialog previews on the transformed layer (#4821): a dropped file (placed in the box, +/// untouched) and a box opened by hand and moved. +#[test] +fn layer_style_opened_during_free_transform_applies_the_box_and_previews() { + for placed in [true, false] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("select.rect", json!({"x": 8, "y": 8, "width": 16, "height": 16})).unwrap(); + app.run("edit.fill", json!({"color": "#0000ff"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + app.sync_views(); + let ctx = egui::Context::default(); + let dx = if placed { + crate::transform_tool::begin_placed(&mut app, &ctx).unwrap(); + 0 + } else { + crate::transform_tool::begin(&mut app, &ctx).unwrap(); + app.ui.transform.as_mut().unwrap().quad = [[28.0, 8.0], [44.0, 8.0], [44.0, 24.0], [28.0, 24.0]]; + 20 + }; + crate::layer_style::open(&mut app, Some("dropShadow")).unwrap(); + assert!(app.ui.transform.is_none() && app.transform_preview.is_none(), "placed {placed}: the box is applied"); + let (shown, _) = display_doc(&mut app, 0); + let rect = photocraft_geom::Rect::new(0, 0, 64, 64); + let with = photocraft_compose::render(&shown, rect); + let without = photocraft_compose::render(&app.session.documents()[0].doc, rect); + assert!( + with.get(16 + dx, 16)[0] < 0.1 && with.get(16 + dx, 16)[2] > 0.9, + "placed {placed}: the blue block where the box left it, not the white under it" + ); + // The shadow darkens the white around the block, which the document doesn't have yet. + let block = |x: i32, y: i32| (8 + dx..24 + dx).contains(&x) && (8..24).contains(&y); + let shadow = + (0..64).flat_map(|y| (0..64).map(move |x| (x, y))).filter(|&(x, y)| !block(x, y) && without.get(x, y)[0] - with.get(x, y)[0] > 0.05).count(); + assert!(shadow > 20, "placed {placed}: the Drop Shadow is previewed ({shadow} px)"); + } +} + +#[test] +fn fill_view_covers_the_canvas_and_centres_the_document() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + let doc = app.session.active().unwrap().doc.clone(); + let mut view = View { fill_pending: true, ..View::default() }; + + fill_view(&mut view, &doc, vec2(600.0, 600.0), 1.0, 1.0); + + assert_eq!(view.zoom, 3.0, "the short edge fills the available height"); + assert_eq!(view.center, [200.0, 100.0]); + assert!(!view.fill_pending); + + // A scaled display stores the physical factor: the same point zoom is 2× the device px. + let mut view = View { fill_pending: true, ..View::default() }; + fill_view(&mut view, &doc, vec2(600.0, 600.0), 2.0, 1.0); + assert_eq!(view.zoom, 6.0); + + // Fit never magnifies past 100% = one image pixel per physical pixel, at any display + // scale (it used to cap at one per *point*, so a 150% display opened images at 150%). + for ppp in [1.0f32, 1.5, 2.0] { + let mut view = View { fit_pending: true, ..View::default() }; + fit_view(&mut view, &doc, vec2(600.0, 600.0), ppp, 1.0); + assert_eq!(view.zoom, 1.0, "ppp {ppp}: a small image opens at 100%"); + } + // A large image still shrinks to fit: 1000×500 into 440 points is 0.44 pt/px, so 0.66 + // physical at ppp 1.5. + let big = { + app.run("file.new", json!({"width": 1000, "height": 500})).unwrap(); + app.session.active().unwrap().doc.clone() + }; + let mut view = View { fit_pending: true, ..View::default() }; + fit_view(&mut view, &big, vec2(480.0, 480.0), 1.5, 1.0); + assert!((view.zoom - 0.66).abs() < 1e-5, "{}", view.zoom); +} + +#[test] +fn a_hundred_percent_is_one_physical_pixel_per_document_pixel() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + app.sync_views(); + for ppp in [1.0f32, 1.25, 2.0] { + app.ppp = ppp; + let xf = ViewXform::active(&app).unwrap(); + // 100% zoom: one document pixel is one physical pixel, i.e. 1/ppp egui points. + let step = xf.to_screen(1.0, 0.0) - xf.to_screen(0.0, 0.0); + // `to_screen` differences around the view centre cancel in f32; 1e-3 is still exact + // enough to see a wrong ppp factor (which would be a 20–100% error). + assert!((step.x - 1.0 / ppp).abs() < 1e-3, "ppp {ppp}: {step:?} want {:?}", 1.0 / ppp); + assert!((app.point_zoom() - 1.0 / ppp).abs() < 1e-5, "ppp {ppp}: {}", app.point_zoom()); + // Screen ↔ document stays an exact round trip. + let back = xf.to_doc(xf.to_screen(123.0, 45.0)); + assert!((back[0] - 123.0).abs() < 1e-3 && (back[1] - 45.0).abs() < 1e-3, "ppp {ppp}: {back:?}"); + } +} + +#[test] +fn wheel_anchor_is_the_pointer_over_the_image_and_the_nearest_image_point_off_it() { + let rect = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)); + for (rotation, flip) in [(0.0, false), (30.0, false), (90.0, true)] { + let xf = ViewXform { rect, zoom: 0.5, center: [400.0, 300.0], flip, rotation, aspect: 1.0 }; + let inside = xf.to_screen(100.0, 200.0); + assert_eq!(wheel_anchor(&xf, inside, [800, 600]), inside); + for (p, want) in [((-300.0, -200.0), [0.0, 0.0]), ((1200.0, 300.0), [800.0, 300.0]), ((400.0, 900.0), [400.0, 600.0])] { + let a = xf.to_doc(wheel_anchor(&xf, xf.to_screen(p.0, p.1), [800, 600])); + assert!((a[0] - want[0]).abs() < 0.01 && (a[1] - want[1]).abs() < 0.01, "rot {rotation}: {p:?} -> {a:?}"); + } + } + let p = pos2(5.0, 5.0); + let xf = ViewXform { rect, zoom: 1.0, center: [400.0, 300.0], flip: false, rotation: 0.0, aspect: 1.0 }; + assert_eq!(wheel_anchor(&xf, p, [0, 0]), p, "no document: the pointer"); +} + +#[test] +fn zoom_about_centres_the_clicked_point_with_the_preference() { + let rect = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)); + let p = pos2(600.0, 200.0); + for ppp in [1.0f32, 2.0] { + // `View::zoom` is physical; the transform works in points. + let xf = ViewXform { rect, zoom: 1.0 / ppp, center: [400.0, 300.0], flip: false, rotation: 0.0, aspect: 1.0 }; + let doc = xf.to_doc(p); + // Off: the document point under the pointer stays under it. + let mut view = View { zoom: 1.0, center: [400.0, 300.0], ..Default::default() }; + zoom_about(&mut view, &xf, p, 2.0, false, ppp); + let after = ViewXform { rect, zoom: 2.0 / ppp, center: view.center, flip: false, rotation: 0.0, aspect: 1.0 }; + let s = after.to_screen(doc[0] as f32, doc[1] as f32); + assert!((s - p).length() < 0.5, "ppp {ppp}: {s:?} vs {p:?}"); + // On: the clicked point is the view centre. + let mut view = View { zoom: 1.0, center: [400.0, 300.0], ..Default::default() }; + zoom_about(&mut view, &xf, p, 2.0, true, ppp); + assert!((view.center[0] - doc[0] as f32).abs() < 0.5, "ppp {ppp}: {:?}", view.center); + assert!((view.center[1] - doc[1] as f32).abs() < 0.5, "ppp {ppp}: {:?}", view.center); + } +} + +#[test] +fn damage_grows_by_nested_effect_reach() { + use photocraft_doc::{Effect, Layer}; + let fmt = photocraft_color::PixelFormat::RGBA8; + assert_eq!(effect_reach(&[Layer::raster("plain", fmt)]), 0); + let mut inner = Layer::raster("inner", fmt); + inner.effects.items.push(Effect::default_drop_shadow()); + let m = photocraft_compose::effects::margin(&inner); + let mut group = Layer::group("g", vec![inner.clone()]); + group.effects.items.push(Effect::default_drop_shadow()); + assert_eq!(effect_reach(std::slice::from_ref(&inner)), m); + // A child's edit moves the group's shape, whose effects reach further. + assert_eq!(effect_reach(&[group.clone()]), 2 * m); + group.visible = false; + assert_eq!(effect_reach(&[group]), 0); +} diff --git a/crates/ui-egui/src/canvas/textures.rs b/crates/ui-egui/src/canvas/textures.rs new file mode 100644 index 0000000000..17b6f1bf26 --- /dev/null +++ b/crates/ui-egui/src/canvas/textures.rs @@ -0,0 +1,681 @@ +use super::display::{GPU_OUTPUT, cache_key, canvas_display, display_doc, display_image, texture_key}; +use super::filter_preview::filter_channel_preview; +use super::navigator::navigator_waits_for_drag; +use super::strokes::live_stroke; +use super::view_xform::ViewXform; +use super::*; + +/// Largest texture side we upload; bigger documents are uploaded downsampled, with the part in +/// view added at the screen's resolution when zoomed in (`detail_plan`). +pub const MAX_TEXTURE: u32 = 4096; + +/// The largest texture side to upload on this device: [`MAX_TEXTURE`], or less where the GPU +/// allows less (2048 on some older or low-end GPUs and WebGL contexts). Past the device's limit +/// egui asserts and the backend fails to create the texture. +pub(super) fn texture_side(ctx: &egui::Context) -> u32 { + clamp_texture_side(ctx.input(|i| i.max_texture_side)) +} + +/// [`texture_side`] for a device whose largest texture side is `max_texture_side`. +pub(super) fn clamp_texture_side(max_texture_side: usize) -> u32 { + u32::try_from(max_texture_side).unwrap_or(MAX_TEXTURE).clamp(1, MAX_TEXTURE) +} + +/// How many document pixels per side one texel of the CPU canvas texture of a `size` document +/// holds when textures are at most `side` texels per side: 1 (full resolution) when it fits. +pub(super) fn texture_factor(size: [u32; 2], side: u32) -> u32 { + size[0].max(size[1]).div_ceil(side.max(1)).max(1) +} + +/// What the CPU canvas draws over its reduced texture so a large document shows its own pixels +/// at 100 % (#7568): the part of the document in view (`region`, document pixels) composited at +/// one texel per `factor` pixels, a power of two no coarser than the screen. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct DetailPlan { + pub factor: u32, + pub region: DRect, +} + +/// The detail region snaps outward to multiples of this many texels, so a small pan reuses it. +const DETAIL_QUANTUM: i32 = 256; + +/// The detail texture a CPU canvas view of a `size` document needs, at `zoom` physical pixels +/// per document pixel over `visible` (document pixels), with textures at most `side` texels per +/// side: `None` when the whole-document texture is already as fine as the screen (a document +/// that fits, or a view zoomed out far enough), or nothing of the document is in view. +/// +/// A document over `side` (4096 px, or the device's smaller limit) is uploaded reduced, so at +/// 100 % it was drawn magnified and blurred. The detail costs what the window shows, not what the +/// document holds: its side is capped by `side` like any texture, coarsening by powers of two. +pub(crate) fn detail_plan(size: [u32; 2], side: u32, zoom: f32, visible: DRect) -> Option { + if !zoom.is_finite() || zoom <= 0.0 { + return None; + } + let base = texture_factor(size, side); + let mut factor = crate::adjust_preview::proxy_factor(zoom); + let bounds = DRect::new(0, 0, i32::try_from(size[0]).ok()?, i32::try_from(size[1]).ok()?); + let v = visible.intersect(&bounds); + if v.is_empty() { + return None; + } + while factor < base { + let q = DETAIL_QUANTUM.saturating_mul(i32::try_from(factor).unwrap_or(i32::MAX)); + let up = |x: i32| x.div_euclid(q).saturating_add(i32::from(x.rem_euclid(q) != 0)).saturating_mul(q); + let region = DRect::new(v.x0.div_euclid(q).saturating_mul(q), v.y0.div_euclid(q).saturating_mul(q), up(v.x1), up(v.y1)).intersect(&bounds); + // A reduced region's texel count can round one up (`render_reduced_damage`'s cells). + let fits = |n: u32| n.div_ceil(factor).saturating_add(1) <= side; + // Snapped when that fits, else just what is in view (a window near the device's limit). + for region in [region, v] { + if !region.is_empty() && fits(region.width()) && fits(region.height()) { + return Some(DetailPlan { factor, region }); + } + } + factor = factor.saturating_mul(2); + } + None +} + +/// The CPU canvas texture's sampling (#4810). Zoomed in, a full-resolution texture shows each +/// document pixel as a crisp square, as the GPU canvas's sharp nearest filter and Photoshop do; +/// zoomed out it is still filtered. A reduced texture (`factor` > 1) stays bilinear: its texels +/// are averages of several pixels, and squares of them would be blocks the image doesn't have. +pub(super) fn canvas_texture_options(factor: u32) -> TextureOptions { + if factor > 1 { TextureOptions::LINEAR } else { TextureOptions { magnification: egui::TextureFilter::Nearest, ..TextureOptions::LINEAR } } +} + +/// Make sure the canvas texture for document `idx` on `display` is current; returns (texture +/// id, scale). +pub fn ensure_texture(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usize, display: Option) -> Option<(egui::TextureId, f32)> { + ensure_texture_in_view(app, ctx, idx, display, None).map(|t| (t.texture, t.scale)) +} + +/// The document area a filter preview of `preview` size covers, for a `doc` sized document +/// previewed at proxy factor `k`: the document's bounds when it is the document's size (reduced by +/// `k`), else its own size (times `k`) centred on the document's centre, as the GPU canvas centres +/// a size-changing preview (Image › Rotation). +pub(super) fn preview_bounds(doc: photocraft_geom::Size, preview: photocraft_geom::Size, k: u32) -> DRect { + let k = k.max(1); + let full = DRect::from_size(doc); + if doc.width.div_ceil(k) == preview.width && doc.height.div_ceil(k) == preview.height { + return full; + } + let side = |p: u32, d: u32| { + let covered = i64::from(p) * i64::from(k); + let x0 = (i64::from(d) - covered).div_euclid(2); + let clamp = |v: i64| v.clamp(i64::from(i32::MIN), i64::from(i32::MAX)) as i32; + (clamp(x0), clamp(x0 + covered)) + }; + let (x0, x1) = side(preview.width, doc.width); + let (y0, y1) = side(preview.height, doc.height); + DRect::new(x0, y0, x1, y1) +} + +/// [`ensure_texture`], and for a canvas showing `view` of a document too large for one +/// full-resolution texture, the detail texture of the part in view ([`detail_plan`], #7568). +pub(crate) fn ensure_texture_in_view( + app: &mut PhotocraftApp, + ctx: &egui::Context, + idx: usize, + display: Option, + view: Option, +) -> Option { + let output = display; + let (revision, last_damage, id) = { + let st = app.session.documents().get(idx)?; + (st.revision, st.last_damage.map(|r| if r.is_empty() { r } else { r.inflate(effect_reach(&st.doc.layers)) }), st.doc.id) + }; + let (mut doc, mut preview_key) = display_doc(app, idx); + // A filter dialog's live preview: the GPU canvas draws it from its own texture, but this CPU + // canvas (no usable GPU, a flipped or pixel-aspect-corrected view, a GPU fallback) showed the + // document unfiltered. Its result is drawn here instead, as the channel views draw it. + // A preview reduced for a zoomed-out view (a proxy, factor `k`) covers the whole document at + // its own size. One whose dimensions change otherwise (Image › Rotation) covers its own area, + // centred on the document's, as the GPU canvas draws it (`preview_bounds`). + let committed = app.session.documents().get(idx).map(|st| st.doc.bounds()).unwrap_or(doc.bounds()); + let mut bounds = committed; + let mut reduced = false; + if let Some((preview, key)) = filter_channel_preview(app, idx, ctx) { + let k = app.filter_preview.as_ref().map_or(1, |p| p.key.k.max(1)); + bounds = preview_bounds(committed.size(), preview.size, k); + (doc, preview_key, reduced) = (preview, key, k > 1); + } + // Detail textures and partial redraws work in the document's own pixels. + let reduced = reduced || bounds != committed; + let view = view.filter(|_| !reduced); + // A flipped view draws a GPU machine's canvas through here: an adjustment dialog's preview of + // a large document (taken by the GPU path) would cost a full-size CPU composite per change. + if crate::adjust_preview::shown_key(app) == Some(preview_key) + && let Some(st) = app.session.documents().get(idx) + && crate::proxy::preview_factor(&st.doc, crate::proxy::reduced_previews(app)) > 1 + { + (doc, preview_key) = (st.doc.clone(), 0); + } + let (display, display_key) = canvas_display(app, &doc, output); + let seen = app.canvases.get(&cache_key(id, output)).map(|c| (c.tex_revision, c.tex_preview_key)); + let damage = seen.and_then(|seen| damage_since(app, idx, seen, (revision, preview_key), display_key, last_damage)).filter(|_| !reduced); + // The detail texture can lag the whole-document one (made or moved later): its own damage. + let detail_seen = view.and_then(|v| { + let c = app.canvases.get(&cache_key(id, output))?; + c.detail.iter().find(|(k, _)| *k == v.key).map(|(_, d)| (d.revision, d.preview_key)) + }); + let detail_damage = match detail_seen { + Some(s) if Some(s) == seen => damage, + Some(s) => damage_since(app, idx, s, (revision, preview_key), display_key, last_damage), + None => None, + }; + let preview_key = preview_key ^ display_key; + let cache = app.canvases.entry(cache_key(id, output)).or_insert(CanvasCache { + revision: 0, + texture: None, + scale: 1.0, + preview_key: 0, + on_gpu: false, + tex_revision: 0, + tex_preview_key: 0, + texture_opaque: false, + grid: None, + detail: Vec::new(), + }); + if cache.tex_revision != revision || cache.texture.is_none() || cache.tex_preview_key != preview_key { + let t0 = crate::gpu_canvas::now_ms(); + let factor = texture_factor([doc.size.width, doc.size.height], texture_side(ctx)); + let (w, h) = ((doc.size.width / factor).max(1), (doc.size.height / factor).max(1)); + let current = cache.texture.as_mut().filter(|t| t.size() == [w as usize, h as usize]); + if let (Some(d), Some(t)) = (damage, current) { + // Only what the edit or stroke touched: the reduced texture's pixels over it, with the + // values the whole reduction gives them (factor 1 is the plain composite of `d`). + let buf = photocraft_compose::render_reduced_damage(&doc, w, h, d); + let r = buf.rect; + if !r.is_empty() { + let t1 = crate::gpu_canvas::now_ms(); + let image = display_image(display.as_deref(), &buf); + // Partial uploads can disprove opacity. Once transparent, conservatively keep + // the checker until a full upload proves the whole texture opaque again. + cache.texture_opaque &= image.pixels.iter().all(|p| p.is_opaque()); + t.set_partial([r.x0 as usize, r.y0 as usize], image, canvas_texture_options(factor)); + let px = (r.width() as u64 * r.height() as u64).saturating_mul(u64::from(factor).pow(2)); + app.perf.record("rect", px, t1 - t0, crate::gpu_canvas::now_ms() - t1); + } + } else { + // Reduced in bands straight from the compositor: no full-size composite in memory. + let full = photocraft_compose::render_reduced(&doc, w, h); + let t1 = crate::gpu_canvas::now_ms(); + let (img, scale) = (display_image(display.as_deref(), &full), 1.0 / factor as f32); + cache.texture_opaque = img.pixels.iter().all(|p| p.is_opaque()); + match cache.texture.as_mut() { + Some(t) if t.size() == img.size => t.set(img, canvas_texture_options(factor)), + _ => cache.texture = Some(ctx.load_texture(format!("canvas-{}-{}", id.0, cache_key(id, output).1), img, canvas_texture_options(factor))), + } + cache.scale = scale; + app.perf.record("full", doc.size.width as u64 * doc.size.height as u64, t1 - t0, crate::gpu_canvas::now_ms() - t1); + } + cache.tex_revision = revision; + cache.tex_preview_key = preview_key; + } + let texture = cache.texture.as_ref()?.id(); + let scale = cache.scale; + // Without a view (the Navigator's call) the views' detail textures stay as they are. + let Some(view) = view else { return Some(CpuTextures { texture, scale, bounds, detail: None }) }; + let old = cache.detail.iter().position(|(k, _)| *k == view.key).map(|i| cache.detail.remove(i).1); + let Some(plan) = detail_plan([doc.size.width, doc.size.height], texture_side(ctx), view.zoom, view.visible) else { + return Some(CpuTextures { texture, scale, bounds, detail: None }); + }; + let t0 = crate::gpu_canvas::now_ms(); + let name = format!("canvas-detail-{}-{}", id.0, cache_key(id, output).1); + let detail = update_detail(ctx, &doc, display.as_deref(), name, plan, old, detail_damage, (revision, preview_key)); + if detail.as_ref().is_some_and(|d| d.rendered) { + app.perf.span("canvas detail", crate::gpu_canvas::now_ms() - t0); + } + let Some(mut detail) = detail else { return Some(CpuTextures { texture, scale, bounds, detail: None }) }; + detail.rendered = false; + // Where its texels lie in the document: reduced texel t covers [t·W/w, (t+1)·W/w). + let (w, h) = ((doc.size.width / plan.factor).max(1), (doc.size.height / plan.factor).max(1)); + let (sx, sy) = (doc.size.width as f32 / w as f32, doc.size.height as f32 / h as f32); + let out = detail.out; + let shown = (detail.texture.id(), [out.x0 as f32 * sx, out.y0 as f32 * sy, out.x1 as f32 * sx, out.y1 as f32 * sy]); + cache.detail.push((view.key, detail)); + // Views that stopped asking (a closed window, a zoom out) give theirs up past a few. + if cache.detail.len() > MAX_DETAIL_VIEWS { + cache.detail.remove(0); + } + Some(CpuTextures { texture, scale, bounds, detail: Some(shown) }) +} + +/// Most CPU canvas views of one document on one display that keep a detail texture. +const MAX_DETAIL_VIEWS: usize = 4; + +/// The detail texture for `plan` at document state `now` (revision, preview key with the display +/// key folded in): `old` as it is when current, updated over `damage` when only that changed +/// within the same region, or rendered again. `None` when the region holds no texels. +#[allow(clippy::too_many_arguments)] +fn update_detail( + ctx: &egui::Context, + doc: &Document, + display: Option<&photocraft_engine::display_color::CanvasDisplay>, + name: String, + plan: DetailPlan, + old: Option, + damage: Option, + now: (u64, u64), +) -> Option { + let (w, h) = ((doc.size.width / plan.factor).max(1), (doc.size.height / plan.factor).max(1)); + let options = canvas_texture_options(plan.factor); + let (kept, spare) = match old { + Some(d) if d.plan == plan => (Some(d), None), + d => (None, d.map(|d| d.texture)), + }; + if let Some(mut d) = kept { + if (d.revision, d.preview_key) == now { + return Some(d); + } + // An edit or a stroke step in view: only the texels it touched. + if let Some(dmg) = damage { + let dmg = dmg.intersect(&plan.region); + let buf = (!dmg.is_empty()).then(|| photocraft_compose::render_reduced_damage(doc, w, h, dmg)); + let fits = buf.as_ref().is_none_or(|b| d.out.contains_rect(&b.rect)); + if fits { + if let Some(b) = buf.filter(|b| !b.rect.is_empty()) { + let at = [b.rect.x0.abs_diff(d.out.x0) as usize, b.rect.y0.abs_diff(d.out.y0) as usize]; + d.texture.set_partial(at, display_image(display, &b), options); + d.rendered = true; + } + (d.revision, d.preview_key) = now; + return Some(d); + } + } + return render_detail(ctx, doc, display, name, plan, Some(d.texture), now); + } + render_detail(ctx, doc, display, name, plan, spare, now) +} + +/// [`update_detail`]'s whole render of `plan`'s region, into `texture` when it is the same size. +fn render_detail( + ctx: &egui::Context, + doc: &Document, + display: Option<&photocraft_engine::display_color::CanvasDisplay>, + name: String, + plan: DetailPlan, + texture: Option, + now: (u64, u64), +) -> Option { + let (w, h) = ((doc.size.width / plan.factor).max(1), (doc.size.height / plan.factor).max(1)); + let options = canvas_texture_options(plan.factor); + let buf = photocraft_compose::render_reduced_damage(doc, w, h, plan.region); + let out = buf.rect; + if out.is_empty() { + return None; + } + let img = display_image(display, &buf); + let texture = match texture { + Some(mut t) if t.size() == img.size => { + t.set(img, options); + t + } + _ => ctx.load_texture(name, img, options), + }; + Some(DetailTexture { texture, plan, out, revision: now.0, preview_key: now.1, rendered: true }) +} + +/// What changed since a canvas cache showed (`revision`, `preview key`) `seen`, when only a +/// rectangle did: the last edit's damage, or the live stroke's dabs since then. Cached keys have +/// the colour display's key folded in (`^ display_key`); `now`'s is still raw. +pub(crate) fn damage_since(app: &PhotocraftApp, idx: usize, seen: (u64, u64), now: (u64, u64), display_key: u64, last_damage: Option) -> Option { + // A brush stroke committed with the pixels its live preview already showed: only the steps + // this cache hadn't shown yet (usually nothing), not the stroke's whole bounding box. + if seen.0 + 1 == now.0 + && let Some(st) = app.session.documents().get(idx) + && let Some(c) = app.committed_stroke.as_ref().filter(|c| c.doc == st.doc.id && c.revision == now.0) + && let Some(r) = c.since(seen.1 ^ display_key) + { + let r = if c.relayout.is_empty() { + r + } else if r.is_empty() { + c.relayout + } else { + r.union(&c.relayout) + }; + return Some(if r.is_empty() { r } else { r.inflate(effect_reach(&st.doc.layers)) }); + } + if seen.1 == now.1 ^ display_key && seen.0 + 1 == now.0 { + return last_damage; + } + if seen.0 == now.0 + && let Some(st) = app.session.documents().get(idx) + && let Some(r) = crate::type_transform::damage(app, st.doc.id, now.0, seen.1 ^ display_key, now.1) + { + return Some(if r.is_empty() { r } else { r.inflate(effect_reach(&st.doc.layers)) }); + } + // Between an adjustment dialog's previews (and the document): the target's area. + if seen.0 == now.0 + && let Some(st) = app.session.documents().get(idx) + && let Some(r) = crate::adjust_preview::switch_region(app, st.doc.id, now.0, seen.1 ^ display_key, now.1) + { + return Some(r); + } + // Between a Properties-panel adjustment-layer drag's previews (and the document): the + // layer's area. Without this every parameter value recomposited the whole document (#6839). + if seen.0 == now.0 + && let Some(st) = app.session.documents().get(idx) + && let Some(r) = crate::adjust_preview::live_switch_region(app, st.doc.id, now.0, seen.1 ^ display_key, now.1) + { + return Some(r); + } + // Between a Move drag's offsets: where the moving layers were and are (Auto-Select's pick + // at the press changes no pixels). + if (seen.0 == now.0 || (seen.0 + 1 == now.0 && last_damage.is_some_and(|r| r.is_empty()))) + && let Some(st) = app.session.documents().get(idx) + && let Some(r) = crate::move_ui::damage(app, st.doc.id, now.0, seen.1 ^ display_key, now.1) + { + return Some(if r.is_empty() { r } else { r.inflate(effect_reach(&st.doc.layers)) }); + } + // Between a Patch drag's previews: the areas they healed. + if seen.0 == now.0 + && let Some(st) = app.session.documents().get(idx) + && let Some(r) = crate::patch_preview::damage(app, st.doc.id, now.0, seen.1 ^ display_key, now.1) + { + return Some(if r.is_empty() { r } else { r.inflate(effect_reach(&st.doc.layers)) }); + } + // Between Vanishing Point stamp previews (and the document): the areas the strokes painted. + if seen.0 == now.0 + && let Some(st) = app.session.documents().get(idx) + && let Some(r) = crate::vp_ui::damage(app, st.doc.id, now.0, seen.1 ^ display_key, now.1) + { + return Some(if r.is_empty() { r } else { r.inflate(effect_reach(&st.doc.layers)) }); + } + // Between hovered blend modes (and the document): where the layer's blending shows. + if seen.0 == now.0 + && let Some(st) = app.session.documents().get(idx) + && let Some(r) = crate::blend_preview::damage(app, st.doc.id, now.0, seen.1 ^ display_key, now.1) + { + return Some(if r.is_empty() { r } else { r.inflate(effect_reach(&st.doc.layers)) }); + } + // Between hovered fonts (and the document): the text layer's old/new ink bounds. + if seen.0 == now.0 + && let Some(st) = app.session.documents().get(idx) + && let Some(r) = crate::type_font_preview::damage(app, st.doc.id, now.0, seen.1 ^ display_key, now.1) + { + return Some(if r.is_empty() { r } else { r.inflate(effect_reach(&st.doc.layers)) }); + } + let l = live_stroke(app, idx).filter(|l| seen.0 == now.0 && l.display_key() == now.1)?; + let r = l.since(seen.1 ^ display_key)?; + Some(if r.is_empty() { r } else { r.inflate(effect_reach(&l.stroke.doc().layers)) }) +} + +/// Document `doc`'s canvas caches showed a preview that the edit just committed reproduces +/// (`was_preview` tells its keys): count it as the document itself, so the commit's damage rect +/// refreshes only that area instead of everything. +pub(crate) fn shown_as_document(app: &mut PhotocraftApp, doc: photocraft_doc::DocId, was_preview: impl Fn(u64) -> bool) { + let Some(d) = app.session.documents().iter().find(|st| st.doc.id == doc).map(|st| st.doc.clone()) else { return }; + if let Some(c) = app.channel_views.get_mut(&doc.0) + && was_preview(c.preview_key) + { + c.preview_key = 0; + } + // Every display's cache of the document: the GPU state folds in the texture key, CPU + // textures their display's key. + let outputs: Vec = app.canvases.keys().filter(|k| k.0 == doc).map(|k| k.1).collect(); + for out in outputs { + let (display, key) = canvas_display(app, &d, (out != 0 && out != GPU_OUTPUT).then_some(out)); + let gpu_key = texture_key(display.as_deref()); + let Some(c) = app.canvases.get_mut(&(doc, out)) else { continue }; + if was_preview(c.preview_key ^ gpu_key) { + c.preview_key = gpu_key; + } + if was_preview(c.tex_preview_key ^ key) { + c.tex_preview_key = key; + } + } +} + +/// How far beyond an edit's damage rect the composite can change: layer effects (shadows, glows, +/// strokes, …) on the edited layer and on the groups around it reach that far. +pub(crate) fn effect_reach(layers: &[photocraft_doc::Layer]) -> i32 { + layers + .iter() + .filter(|l| l.visible) + .map(|l| { + let own = if photocraft_compose::effects::has_effects(l) { photocraft_compose::effects::margin(l) } else { 0 }; + let inner = match &l.content { + LayerContent::Group(g) => effect_reach(&g.children), + _ => 0, + }; + own + inner + }) + .max() + .unwrap_or(0) +} + +/// GPU path: make sure document `idx` is current in the GPU canvas. Edits draw their damage; +/// unchanged lower-stack composites can be reused by the compositor inside that region. +/// Returns false if there is no GPU canvas. +pub(super) fn ensure_gpu(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usize, visible: DRect) -> bool { + let Some(gpu) = app.gpu.clone() else { return false }; + let Some((revision, last_damage, id)) = app + .session + .documents() + .get(idx) + .map(|st| (st.revision, st.last_damage.map(|r| if r.is_empty() { r } else { r.inflate(effect_reach(&st.doc.layers)) }), st.doc.id)) + else { + return false; + }; + let (doc, raw_key) = display_doc(app, idx); + let (display, _) = canvas_display(app, &doc, None); + // Repeated pattern tiles sample the same texture, including pixels outside the unwrapped + // viewport. Refresh the affected document region while Pattern Preview is enabled. + let blend_visible = if app.ui.view.pattern_preview { doc.bounds() } else { visible }; + // The texture is shared by every display: only what it stores counts, not the monitor. + let display_key = texture_key(display.as_deref()); + let seen = app.canvases.get(&(id, GPU_OUTPUT)).map(|c| (c.revision, c.preview_key)); + let mut damage = seen.and_then(|seen| damage_since(app, idx, seen, (revision, raw_key), display_key, last_damage)); + if let Some(region) = damage { + damage = Some(crate::blend_preview::clip_damage(app, id, revision, raw_key, region, blend_visible)); + } + // To an adjustment dialog's preview: only what the view shows now (the rest as it moves there). + if damage.is_some() + && let Some(r) = seen.filter(|s| s.0 == revision).and_then(|s| crate::adjust_preview::switch_region(app, id, revision, s.1 ^ display_key, raw_key)) + { + damage = Some(crate::adjust_preview::switch_damage(app, raw_key, r, visible)); + } + // The same for a Properties-panel drag's previews. + if damage.is_some() + && let Some(r) = seen.filter(|s| s.0 == revision).and_then(|s| crate::adjust_preview::live_switch_region(app, id, revision, s.1 ^ display_key, raw_key)) + { + damage = Some(crate::adjust_preview::live_switch_damage(app, raw_key, r, visible)); + } + let preview_key = raw_key ^ display_key; + // The Navigator may draw this texture while it holds the plain document or a drag preview + // that updates the full texture (not an adjustment preview composited only where the view is). + if raw_key == 0 || navigator_waits_for_drag(app, idx) { + app.navigator_plain.insert(id); + } else { + app.navigator_plain.remove(&id); + app.navigator_gpu.remove(&id); + } + let size = [doc.size.width, doc.size.height]; + // A full CPU redraw running in the background: show the blocks it has finished. + crate::background_redraw::poll(app, &gpu, id); + let cache = app.canvases.entry((id, GPU_OUTPUT)).or_insert(CanvasCache { + revision: 0, + texture: None, + scale: 1.0, + preview_key: 0, + on_gpu: false, + tex_revision: 0, + tex_preview_key: 0, + texture_opaque: false, + grid: None, + detail: Vec::new(), + }); + let present = cache.on_gpu && gpu.has(id.0, size); + let current = cache.revision == revision && cache.preview_key == preview_key; + // GPU Memory or Memory Usage changed with nothing to redraw: the new budget, and whether the + // layers fit it, show at once (the status bar's GPU Memory Full). + if present && app.perf.gpu_budget_allowance != budget_allowance(app) { + gpu_budget(app, &gpu, idx, false, visible); + } + // Switched to a document whose canvas is already current: size the budget for it and measure + // whether its layers fit, so GPU Memory Full shows (or clears) at once rather than at its + // next full refresh. Once per switch: the fit then names this document. + if present && app.perf.gpu_layer_fit.is_none_or(|f| f.doc != id.0) { + gpu_budget(app, &gpu, idx, false, visible); + let fit = gpu.measure_fit(&doc).unwrap_or(crate::gpu_canvas::LayerFit { doc: id.0, needed: 0, budget: 0 }); + app.perf.gpu_layer_fit = Some(fit); + } + if present && current { + // An adjustment preview composited where the view was: catch up where it moved to. + if let Some(r) = crate::adjust_preview::uncovered(app, id, raw_key, visible) { + let r = gpu.refresh(id.0, &doc, Some(r), display.as_deref()); + app.perf.record_refresh(&r); + } + if let Some(r) = crate::adjust_preview::live_uncovered(app, id, raw_key, visible) { + let r = gpu.refresh(id.0, &doc, Some(r), display.as_deref()); + app.perf.record_refresh(&r); + } + // Blend previews keep offscreen pixels untouched until the view reaches them. + // Use the normal refresh path so CPU fallback and pending redraws stay synchronized. + damage = crate::blend_preview::uncovered(app, id, revision, raw_key, blend_visible); + if damage.is_none() { + return true; + } + } + // Display textures for a canvas this large would not fit the GPU: the reduced CPU canvas + // draws it (checked before the memory budget, which walks the history, every frame). + if !gpu.fits_canvas(&doc) { + crate::background_redraw::cancel(app, id); + // Drawn on the CPU canvas: no layer budget applies to it. + if app.perf.gpu_layer_fit.is_some_and(|f| f.doc == id.0) { + app.perf.gpu_layer_fit = None; + } + return false; + } + let partial = present && damage.is_some(); + gpu_budget(app, &gpu, idx, partial, visible); + let defer = crate::background_redraw::enabled(app); + let r = gpu.refresh_with(id.0, &doc, if partial { damage } else { None }, display.as_deref(), defer); + app.perf.gpu_layer_fit = gpu.layer_fit(); + if r.kind == "lost" || r.kind == crate::gpu_canvas::REFRESH_OVER_BUDGET { + // The device is gone (`gpu_status` then drops the GPU canvas) or the canvas is over the + // texture budget: draw this frame on the CPU path. + crate::background_redraw::cancel(app, id); + return false; + } + if r.kind == crate::gpu_canvas::REFRESH_DEFERRED { + // Composited off the UI thread, the visible part first (#4024). + let region = if partial { damage.unwrap_or(doc.bounds()) } else { doc.bounds() }; + crate::background_redraw::start(app, ctx, &gpu, doc.clone(), display.clone(), visible, region, r.fallback.clone()); + } else if partial { + // The edit drew its damage; blocks of a running redraw still to come follow the edit. + crate::background_redraw::restart(app, ctx, &gpu, doc.clone(), display.clone(), visible); + } else { + crate::background_redraw::cancel(app, id); + } + if let Some(e) = &r.fallback + && app.perf.gpu_fallback.as_deref() != Some(e.as_str()) + { + log::info!("{e}; using the CPU compositor"); + } + if r.kind != crate::gpu_canvas::REFRESH_DEFERRED { + app.perf.record_refresh(&r); + } + if r.kind == "full" { + crate::notices::slow_cpu_refresh(app, id.0, r.composite_ms + r.upload_ms, r.fallback.as_deref()); + } + if r.kind.starts_with("gpu") { + app.perf.gpu_uploads = r.uploads; + } else { + app.perf.gpu_fallback = r.fallback; + } + let Some(cache) = app.canvases.get_mut(&(id, GPU_OUTPUT)) else { return true }; + cache.revision = revision; + cache.preview_key = preview_key; + cache.on_gpu = true; + cache.texture = None; + true +} + +/// Point the wgpu compositor at what the view shows, and size its memory budget from GPU Memory, +/// or Memory Usage, the document's pixels and History (charged where the GPU shares the system's +/// memory), physical memory and the GPU's own: on full refreshes (pixels counted once per +/// structural change, not per brush dab) and whenever either preference changes. +fn gpu_budget(app: &mut PhotocraftApp, gpu: &crate::gpu_canvas::GpuCanvas, idx: usize, partial: bool, visible: DRect) { + gpu.set_focus(Some(visible)); + let allowance = budget_allowance(app); + let changed = app.perf.gpu_budget_allowance != allowance; + if partial && !changed && gpu.memory_budget().is_some() { + return; + } + let Some(st) = app.session.documents().get(idx) else { return }; + let pixels = st.memory_bytes() as u64; + let budget = crate::gpu_canvas::memory_budget(allowance.0, pixels, crate::gpu_canvas::physical_memory(), gpu.video_memory(), allowance.1); + gpu.set_memory_budget(budget); + app.perf.gpu_budget_mb = budget >> 20; + app.perf.gpu_budget_allowance = allowance; + if changed && let Some(fit) = gpu.measure_fit(&st.doc) { + app.perf.gpu_layer_fit = Some(fit); + } +} + +/// Memory Usage and GPU Memory (Preferences › Performance), in bytes. +fn budget_allowance(app: &PhotocraftApp) -> (u64, u64) { + let performance = &app.session.prefs().performance; + (u64::from(performance.memory_usage_mb).saturating_mul(1 << 20), u64::from(performance.gpu_memory_mb).saturating_mul(1 << 20)) +} + +/// The document pixels a view shows, with a margin for filtering. Uses all four canvas corners +/// so a rotated camera still covers the visible tiles. +pub(super) fn visible_doc_rect(xf: &ViewXform) -> DRect { + let r = xf.rect; + let docs = [xf.to_doc(r.min), xf.to_doc(pos2(r.max.x, r.min.y)), xf.to_doc(r.max), xf.to_doc(pos2(r.min.x, r.max.y))]; + let mut x0 = docs[0][0]; + let mut y0 = docs[0][1]; + let mut x1 = x0; + let mut y1 = y0; + for d in docs { + x0 = x0.min(d[0]); + y0 = y0.min(d[1]); + x1 = x1.max(d[0]); + y1 = y1.max(d[1]); + } + let c = |v: f64| v.clamp(-1e9, 1e9) as i32; + DRect::new(c(x0.floor()) - 2, c(y0.floor()) - 2, c(x1.ceil()) + 2, c(y1.ceil()) + 2) +} + +/// Prioritize deferred redraw blocks visible at either the target or the animated display camera. +/// The displayed camera may still show old texture contents outside the target's visible area. +pub(super) fn redraw_focus(target: &ViewXform, displayed: &ViewXform) -> DRect { + visible_doc_rect(target).union(&visible_doc_rect(displayed)) +} + +/// A CPU composite as the GPU canvas texture stores it (sRGB-encoded for linear documents). +pub(super) fn texture_buffer<'a>( + display: Option<&photocraft_engine::display_color::CanvasDisplay>, + buf: &'a photocraft_compose::Buffer, +) -> std::borrow::Cow<'a, photocraft_compose::Buffer> { + match display { + Some(d) => d.texture_buffer(buf), + None => std::borrow::Cow::Borrowed(buf), + } +} + +pub(crate) fn retain_gpu_documents(app: &mut PhotocraftApp) { + // Remove a closed adjustment owner's proxy before collecting its live GPU keys. + crate::adjust_preview::retain_documents(app); + if let Some(gpu) = &app.gpu { + // Keep each document's texture plus its preview textures (filter preview, adjustment proxy); + // retaining only document ids freed the previews every frame (blank canvas while previewing). + let mut live: Vec = app.session.documents().iter().flat_map(|st| [st.doc.id.0, st.doc.id.0 ^ (1u64 << 61), st.doc.id.0 ^ (1u64 << 62)]).collect(); + live.extend(crate::adjust_preview::gpu_keys(app)); + gpu.retain(&live); + } + crate::background_redraw::retain(app); + // Upload markers must not outlive the resources they describe: native reopen can reuse + // both the document ID and revision before the next frame while a preview dialog stays open. + let documents = app.session.documents(); + if app.filter_preview.as_ref().is_some_and(|preview| !documents.iter().any(|st| st.doc.id == preview.key.doc)) { + app.filter_preview = None; + } + if app.proxy_uploaded.is_some_and(|(doc, _)| !documents.iter().any(|st| st.doc.id == doc)) { + app.proxy_uploaded = None; + app.proxy = None; + } +} diff --git a/crates/ui-egui/src/tile_overlay.rs b/crates/ui-egui/src/canvas/tile_overlay.rs similarity index 100% rename from crates/ui-egui/src/tile_overlay.rs rename to crates/ui-egui/src/canvas/tile_overlay.rs diff --git a/crates/ui-egui/src/tool_cursor.rs b/crates/ui-egui/src/canvas/tool_cursor.rs similarity index 100% rename from crates/ui-egui/src/tool_cursor.rs rename to crates/ui-egui/src/canvas/tool_cursor.rs diff --git a/crates/ui-egui/src/tool_cursor/hand.rs b/crates/ui-egui/src/canvas/tool_cursor/hand.rs similarity index 100% rename from crates/ui-egui/src/tool_cursor/hand.rs rename to crates/ui-egui/src/canvas/tool_cursor/hand.rs diff --git a/crates/ui-egui/src/tool_cursor/tests.rs b/crates/ui-egui/src/canvas/tool_cursor/tests.rs similarity index 100% rename from crates/ui-egui/src/tool_cursor/tests.rs rename to crates/ui-egui/src/canvas/tool_cursor/tests.rs diff --git a/crates/ui-egui/src/tool_cursor/zoom.rs b/crates/ui-egui/src/canvas/tool_cursor/zoom.rs similarity index 100% rename from crates/ui-egui/src/tool_cursor/zoom.rs rename to crates/ui-egui/src/canvas/tool_cursor/zoom.rs diff --git a/crates/ui-egui/src/tool_feedback.rs b/crates/ui-egui/src/canvas/tool_feedback.rs similarity index 100% rename from crates/ui-egui/src/tool_feedback.rs rename to crates/ui-egui/src/canvas/tool_feedback.rs diff --git a/crates/ui-egui/src/canvas/tool_input.rs b/crates/ui-egui/src/canvas/tool_input.rs new file mode 100644 index 0000000000..a58555037a --- /dev/null +++ b/crates/ui-egui/src/canvas/tool_input.rs @@ -0,0 +1,626 @@ +use super::cursors::{alt_eyedropper, sample_eyedropper}; +use super::drag::Drag; +use super::gesture::{finish_gesture, polygon_click, selection_mode}; +use super::selection::finish_selection_drag; +use super::strokes::{HOLD_REPEAT_MS, begin_live_stroke, feed_live_stroke, paint_target, snap_aliased_tip, stroke_params, strokes_live}; +use super::*; + +/// Abstract tool event, produced by the mouse or by automation (`ui.pointer`). +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum ToolEvent { + Down { x: f64, y: f64, pressure: f32 }, + Move { x: f64, y: f64, pressure: f32 }, + Up { x: f64, y: f64 }, +} + +/// The body of a `Move` for every tool: tracked position, ⇧ constraint, the moving layer, and so +/// on. It does not feed the live stroke, so the canvas can push a whole frame's recovered samples +/// and update the live stroke once (see `canvas_view`). +fn tool_move(app: &mut PhotocraftApp, x: f64, y: f64, pressure: f32, mods: egui::Modifiers) { + let tool = app.active_tool(); + if tool.is_type() && app.drag.is_none() { + crate::type_tool::pointer_move(app, x, y, mods); + } + if tool == Tool::Pen && mods.alt { + crate::vector_ui::pen_break_handle(app); + } + if tool == Tool::Pen { + crate::vector_ui::pen_move(app, x, y, mods.shift); + } else if tool == Tool::CurvaturePen { + crate::vector_ui::curvature_move(app, x, y); + } + let zoom = app.point_zoom(); + if let Some(d) = app.drag.as_mut().filter(|d| d.reposition) { + d.track(mods); + d.shift_to([x, y]); + } else if let Some(d) = &mut app.drag { + d.track(mods); + // ⇧: straight 0/45/90° strokes, 45° gradient angles (stroke_constraint.rs). + let last = d.points.last().map_or(d.start, |p| [p[0], p[1]]); + let [x, y] = crate::stroke_constraint::constrain(d.tool, &mut d.constrain, d.start, last, [x, y], mods.shift, zoom); + // ⇧: a selection-tool drag of the selection locks to multiples of 45° (#6231). The Move + // tool's own drags were already locked by `move_mods::filter_event`. + let [x, y] = crate::move_mods::selection_drag_to(d, [x, y], mods.shift && tool != Tool::Move); + let moved = d.points.last().is_none_or(|p| (p[0] - x).abs() + (p[1] - y).abs() > 0.25); + // A held pen repeats its point now and then, so the stroke's time keeps advancing. + let held = app.stylus.last_point_ms().is_some_and(|t| app.stylus.clock_ms - t >= HOLD_REPEAT_MS) + && app.live_stroke.as_ref().is_some_and(|l| l.stroke.wants_time()); + if moved || held { + d.points.push([x, y, pressure as f64]); + app.stylus.record_point(); + } + } +} + +/// Tool state machine. Shared by mouse input and automation. +pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) { + // A press anywhere but on a guide deselects the selected guide (`guide_select`). + if let ToolEvent::Down { x, y, .. } = ev + && app.ui.selected_guide.is_some() + && crate::rulers::guide_at(app, x, y).is_none() + { + crate::guide_select::clear(app); + } + if crate::symmetry_ui::pointer(app, ev, crate::workspace_ui::sticky_mods(app, mods)) { + return; + } + // An Alt+right-drag armed for this press (`paint_mouse`): taken before anything else can + // consume the event, so it never outlives the press it was armed for (#297). + let armed = std::mem::take(&mut app.brush_resize_armed); + crate::transform_tool::end_if_left(app); + let mods = crate::workspace_ui::sticky_mods(app, mods); + if app.ui.transform.is_none() && crate::type_transform::pointer(app, ev, mods) { + return; + } + // Content-Aware Move's Transform On Drop box takes every press until ↩ or Esc. + if crate::cam_transform::pointer(app, ev, mods) { + return; + } + // A Mixer Brush press that loaded paint stays a sample press until it is released, with ⌥ + // let go or not (`mixer_sampling`; `canvas_view` holds back egui's later drag start too). + match ev { + ToolEvent::Down { .. } => app.mixer_sampling = false, + ToolEvent::Up { .. } if app.mixer_sampling => { + app.mixer_sampling = false; + return; + } + _ if app.mixer_sampling => return, + _ => {} + } + // The tool in use, so a held temporary tool (⌘ = Move) with ⌥ doesn't load paint. + if app.active_tool() == Tool::MixerBrush && mods.alt && !mods.ctrl && app.drag.is_none() && !armed && app.brush_resize.is_none() { + if let ToolEvent::Down { x, y, pressure } = ev { + app.mixer_sampling = true; + let pen = app.stylus.sample().unwrap_or_default(); + let p = json!({"points":[[x,y,pressure,pen.tilt_x,pen.tilt_y,pen.rotation]],"target":paint_target(app)}); + if let Err(e) = app.run("brush.mixer.sample", p) { + app.ui.status = e; + app.ui.status_error = true; + } + } + return; + } + // View › Snap / Snap To and smart guides (snap_ui.rs). + let raw = ev; + // The Move tool's marquee selecting layers takes its moves and release unsnapped (move_box.rs). + if crate::move_box::pointer(app, raw) { + return; + } + // A press anywhere but on the floating piece (or with ⇧ / ⌥, to draw) drops it first; the + // Move tool (⌘ with a painting tool too, `event_tool`) drags it from anywhere. + if let ToolEvent::Down { x, y, .. } = raw + && app.session.active().is_some_and(|st| photocraft_engine::float_cmds::floating(st).is_some()) + && !crate::move_ui::moves_selected_pixels_with(app, event_tool(app, mods)) + && selection_drag_kind(app, app.ui.tool, [x, y], mods) != Some(true) + { + let _ = app.run("select.drop", json!({})); + } + let ev = crate::snap_ui::filter_event(app, ev, mods); + // Free Transform picks the handle under the press where the user clicked: the snapped press + // can land outside the corner's grab area and turn a corner drag into a move of the whole box. + let transform_ev = if matches!(raw, ToolEvent::Down { .. }) { raw } else { ev }; + if crate::transform_tool::pointer(app, transform_ev, mods) { + return; + } + if crate::distort_ui::pointer(app, ev, mods) { + return; + } + if crate::perspective_crop_ui::pointer(app, ev) { + return; + } + // Window › Modifier Keys: sticky Shift/⌘/⌥ act as held keys. + let mods = crate::workspace_ui::sticky_mods(app, mods); + // ⌘⌥⌃-click with any tool selects the topmost layer with pixels there (quick_pick.rs); it + // must run before the ⌃⌥ brush resize below, which the same keys would trigger. + if crate::quick_pick::pointer(app, ev, mods) { + return; + } + // Control+Alt-drag or Alt+right-drag with a painting tool resizes the brush instead of + // painting (#231, #297). + if crate::brush_resize::pointer(app, ev, mods, armed) { + return; + } + // ⌥ (Alt) with a painting tool is the Eyedropper for that press. + if alt_eyedropper(app, ev, mods) { + return; + } + // Move tool: ⇧ locks the axis, ⌥ duplicates (move_mods.rs). + let ev = crate::move_mods::filter_event(app, ev, mods); + // A live shape's corner radius widgets (Path Selection, the shape tools, Move with its + // transform controls). Unsnapped, as Free Transform's handles: snapping would pull the press + // off a widget onto a nearby vertex or guide, and the shape tool would draw a new shape. + if crate::corner_radius::pointer(app, raw, mods) { + return; + } + // Direct Selection, and the Pen's ⌘ (Direct Selection) and ⌥ (Convert Point) modes (#790). + if crate::direct_select::pointer(app, ev, mods) { + return; + } + // Add / Delete Anchor Point tools (#1044). + if crate::anchor_tools::pointer(app, ev, mods) { + return; + } + // Ruler, Count and Note tools. + if crate::analysis_ui::pointer(app, ev, mods) { + return; + } + // Slice and Slice Select tools. + if crate::slice_ui::pointer(app, ev, mods) { + return; + } + // Frame tool: draw rectangular and elliptical frames. + if crate::frame_tool::pointer(app, ev, mods) { + return; + } + // Artboard tool: draw, select, move and resize boards. + if crate::artboard_tool::pointer(app, ev, mods) { + return; + } + // Crop tool: draw, move and resize the frame. + if crate::crop_ui::pointer(app, ev, mods) { + return; + } + // Gradient tool, live mode: draw and edit Gradient Fill layers. + if crate::gradient_ui::pointer(app, ev, mods) { + return; + } + // ⌘ over a guide takes the guide (#2690, #6288); the guide drag below moves it. + if let ToolEvent::Down { x, y, .. } = raw + && let Some((vertical, i)) = command_guide_at(app, app.active_tool(), [x, y], mods) + { + app.guide_drag = Some(crate::rulers::GuideDrag::existing(vertical, i, [x, y])); + crate::snap_ui::begin_guide(app, [x, y]); + return; + } + if crate::lasso_ui::pointer(app, ev, mods) { + return; + } + // Magnetic Lasso: fastening points and the border following the pointer. + if crate::magnetic_lasso_ui::pointer(app, ev, mods) { + return; + } + let tool = event_tool(app, mods); + if tool == Tool::Eyedropper { + match ev { + ToolEvent::Down { x, y, .. } | ToolEvent::Move { x, y, .. } => { + sample_eyedropper(app, x, y, mods); + return; + } + ToolEvent::Up { .. } => return, + } + } + // A locked layer (the Background without a selection, say): no drag, and Photoshop's message + // once the pointer moves (a click says nothing). ⌘ with a selection tool here (#896); the Move + // tool below, once Auto-Select has picked the layer. + match ev { + ToolEvent::Down { x, y, .. } if tool != Tool::Move && app.ui.transform.is_none() && crate::move_lock::blocked(app, tool, [x, y], mods) => { + app.move_blocked = true; + return; + } + ToolEvent::Move { .. } if app.move_blocked => { + app.move_blocked = false; + crate::move_lock::prompt(app); + return; + } + ToolEvent::Up { .. } if app.move_blocked => { + app.move_blocked = false; + return; + } + _ => {} + } + // Move tool over a guide drags the guide (off the canvas deletes it). + match ev { + ToolEvent::Down { x, y, pressure } if tool == Tool::Move => { + if let Some((vertical, i)) = crate::rulers::guide_at(app, x, y) { + // ⌥-click turns the guide, through the point clicked, as in Photoshop. + if mods.alt && !mods.shift && !mods.command { + crate::guide_select::flip(app, vertical, i, [x, y]); + return; + } + app.guide_drag = Some(crate::rulers::GuideDrag::existing(vertical, i, [x, y])); + return; + } + // Auto-Select (or ⌘-click while it is off) picks the layer under the pointer first + // (not when the selected pixels move: those are the active layer's). + if !crate::move_ui::moves_selected_pixels_with(app, tool) && app.ui.tool_options.move_auto_select != mods.command { + let target = app.ui.tool_options.move_target.clone(); + let mode = if mods.shift { "add" } else { "replace" }; + let before = app.session.active().map(|st| st.selected_layers()); + // A locked layer under the pointer (the Background) can't move. Photoshop draws + // the layer marquee instead of reporting the lock (#4058). Probe without + // selecting so a locked hit doesn't become the selection first. + let probe = app.run("layer.pickAt", json!({"x": x, "y": y, "target": target, "select": false})); + let locked_hit = probe.as_ref().ok().and_then(|v| v["layer"].as_u64()).is_some_and(|id| { + app.session.active().is_some_and(|st| { + let id = photocraft_doc::LayerId(id); + let locks = st.doc.effective_locks(id); + locks.position || locks.all || st.doc.is_background(id) + }) + }); + if locked_hit || (probe.as_ref().is_ok_and(|v| v["layer"].is_null()) && crate::move_box::empty_at(app, [x, y])) { + if locked_hit { + // A click still selects the locked layer, as in Photoshop; a drag's + // marquee then replaces that selection on release. + let _ = app.run("layer.pickAt", json!({"x": x, "y": y, "target": target, "mode": mode})); + } + crate::move_box::begin(app, [x, y], mods.shift); + return; + } + let picked = app.run("layer.pickAt", json!({"x": x, "y": y, "target": target, "mode": mode})); + // No pixels there at all (an empty spot, or off the canvas): drag a marquee that + // selects the layers it touches instead (move_box.rs). + if picked.is_ok_and(|v| v["layer"].is_null()) && crate::move_box::empty_at(app, [x, y]) { + crate::move_box::begin(app, [x, y], mods.shift); + return; + } + // Snapping (and the drag's box) started before the pick: point it at what moves. + if app.session.active().map(|st| st.selected_layers()) != before { + crate::snap_ui::retarget_move(app, [x, y], mods); + } + } + // A locked layer: no drag, and Photoshop's message once the pointer moves (`move_lock`). + if crate::move_lock::blocked(app, tool, [x, y], mods) { + app.move_blocked = true; + return; + } + // With a selection: cut the selected pixels (⌥ copies them) and drag them as a floating + // piece, from anywhere, as a marquee ⌘-drag does. + if crate::move_ui::moves_selected_pixels_with(app, tool) { + if crate::move_ui::float_selected(app, mods.alt, 0.0, 0.0) { + let mut d = Drag::new(tool, [x, y], vec![[x, y, pressure as f64]], mods, false); + d.sel_move = Some(true); + app.drag = Some(d); + } + return; + } + } + ToolEvent::Move { x, y, .. } => { + if let Some(d) = app.guide_drag.as_mut().filter(|d| d.index.is_some()) { + d.pos = if d.vertical { x } else { y }; + return; + } + } + ToolEvent::Up { x, y } => { + if let Some(mut d) = app.guide_drag.filter(|d| d.index.is_some()) { + app.guide_drag = None; + d.pos = if d.vertical { x } else { y }; + crate::rulers::finish_drag(app, d); + return; + } + } + _ => {} + } + match ev { + ToolEvent::Down { x, y, pressure } => { + // Painting a type, shape, Smart Object or fill layer asks to rasterize it first + // (⌥-click with the Clone Stamp or Healing Brush only sets the source). + let sets_source = matches!(tool, Tool::CloneStamp | Tool::Healing) && mods.alt; + // Painting on or moving a hidden layer is refused at the press, as in Photoshop (#571). + if !sets_source && let Some(why) = hidden_target(app, tool) { + app.ui.status = why.into(); + app.ui.status_error = true; + return; + } + if !sets_source && crate::rasterize_prompt::intercept(app, tool, x, y, pressure) { + return; + } + // ⌘ with a selection tool is the Move tool for the drag: outside the selection (or + // without one) it moves the whole layer, ⌘⌥ a duplicate of it. It never combines + // selections. + if command_moves_layer(app, tool, [x, y], mods) { + if mods.alt + && let Err(e) = app.run("layer.duplicate", json!({"inPlace": true})) + { + app.ui.status = e; + app.ui.status_error = true; + return; + } + app.drag = Some(Drag::new(Tool::Move, [x, y], vec![[x, y, pressure as f64]], mods, false)); + return; + } + // Marquee / lasso inside the selection: drag the outline, or ⌘-drag to cut the selected + // pixels into a floating piece (`select.float`) and drag that. + if let Some(cut) = selection_drag_kind(app, tool, [x, y], mods) { + // ⌘⌥ on a floating piece leaves it where it is and drags a copy of it. + if cut + && mods.alt + && mods.command + && app.session.active().is_some_and(|st| photocraft_engine::float_cmds::floating(st).is_some()) + && let Err(e) = app.run("select.drop", json!({})) + { + app.ui.status = e; + app.ui.status_error = true; + return; + } + if cut + && app.session.active().is_some_and(|st| photocraft_engine::float_cmds::floating(st).is_none()) + && let Err(e) = app.run("select.float", json!({"dx": 0, "dy": 0, "copy": mods.alt})) + { + app.ui.status = e; + app.ui.status_error = true; + return; + } + crate::snap_ui::follow_cut(app); + let mut d = Drag::new(tool, [x, y], vec![[x, y, pressure as f64]], mods, false); + d.sel_move = Some(cut); + app.drag = Some(d); + return; + } + match tool { + Tool::PathSelection => { + let tol = 6.0 / f64::from(app.point_zoom().max(0.01)); + if let Some(st) = app.session.active() + && let Some(id) = crate::vector_ui::pick_shape_at(&st.doc, [x, y], tol) + { + let _ = app.run("layer.select", json!({"layer": id.0})); + } + } + Tool::Pen => { + if !(mods.alt && crate::vector_ui::pen_grab_handle(app, x, y)) { + crate::vector_ui::pen_down(app, x, y, mods.shift); + } + return; + } + Tool::CurvaturePen => { + crate::vector_ui::curvature_down(app, x, y); + return; + } + Tool::CloneStamp | Tool::Healing if mods.alt => { + crate::retouch_ui::set_source(app, x, y); + return; + } + Tool::MagicWand => { + let o = app.ui.tool_options.clone(); + let mode = selection_mode(app, mods); + let _ = app.run("select.magicWand", json!({"x": x.floor(), "y": y.floor(), "tolerance": o.tolerance, "contiguous": o.contiguous, "antiAlias": o.anti_alias, "sampleAllLayers": o.sample_all.magic_wand, "mode": mode})); + return; + } + Tool::MagicEraser => { + crate::eraser_ui::click(app, tool, x, y); + return; + } + Tool::PaintBucket => { + let o = app.ui.tool_options.clone(); + let contents = if o.bucket_fill_pattern { "pattern" } else { "foreground" }; + let mode = if o.bucket_clear { "clear" } else { o.bucket_blend_mode.label() }; + let _ = app.run("paint.bucket", json!({"x": x.floor(), "y": y.floor(), "tolerance": o.tolerance, "contiguous": o.contiguous, "antiAlias": o.anti_alias, "sampleAllLayers": o.sample_all.paint_bucket, "opacity": o.fill_opacity, "contents": contents, "mode": mode, "target": paint_target(app)})); + return; + } + Tool::RedEye => { + let o = app.ui.tool_options.clone(); + let _ = app.run( + "paint.redEye", + json!({ + "x": x.floor(), + "y": y.floor(), + "pupilSize": o.red_eye_pupil_size.clamp(1.0, 100.0), + "darken": o.red_eye_darken.clamp(0.0, 100.0), + "target": paint_target(app), + }), + ); + return; + } + Tool::PolygonLasso => { + polygon_click(app, x, y, mods); + return; + } + // The Type tools pick the box handle or glyph under the press where the user + // clicked: the snapped press can land off an edge handle's grab area (#6819). + Tool::Type | Tool::VerticalType | Tool::HorizontalTypeMask | Tool::VerticalTypeMask + if { + let [px, py] = if let ToolEvent::Down { x, y, .. } = raw { [x, y] } else { [x, y] }; + crate::type_tool::pointer_down(app, px, py, mods) + } => + { + return; + } + _ => {} + } + crate::paint_mouse::sync_tool_brush(app); + // Clear mode (`~` held, or chosen in the options bar) erases with the tool's own brush. + let clear = crate::paint_mouse::clears(app, tool); + let erase = std::mem::take(&mut app.secondary_erase) || tool == Tool::Eraser || clear; + // A 1 px pencil line depends on the pixels, not where inside the pixel the click + // landed (#4071). Snap both ends of the stroke to the aliased tip's grid. + let (x, y) = snap_aliased_tip(app, tool, x, y); + // ⇧-click connects to the last endpoint, including its pen pressure (#2827), so + // the renderer interpolates size and opacity across the segment. + let active = app.session.active().map(|st| st.doc.id); + let from = app.last_stroke_end.filter(|(doc, _)| mods.shift && crate::stroke_constraint::connects(tool) && Some(*doc) == active).map(|(_, p)| { + let (sx, sy) = snap_aliased_tip(app, tool, p[0], p[1]); + [sx, sy, p[2]] + }); + let mut points = vec![[x, y, pressure as f64]]; + if let Some(p) = from { + points.insert(0, p); + } + // ⌥ flips Dodge/Burn and Blur/Sharpen for this stroke. + let tool = crate::retouch_ui::alt_flipped(tool, mods.alt); + app.drag = Some(Drag { clear, ..Drag::new(tool, from.map_or([x, y], |p| [p[0], p[1]]), points, mods, erase) }); + app.trail = None; + app.stylus.begin_stroke(); + if from.is_some() { + app.stylus.record_point(); + } + app.live_stroke = if strokes_live(tool) { begin_live_stroke(app) } else { None }; + if tool == Tool::MixerBrush && app.live_stroke.is_none() { + use photocraft_engine::brush_cmds::mixer_live::LiveMixer; + let p = app.drag.as_ref().map(|d| stroke_params(app, d, &app.stylus.stroke_points(&d.points))); + // A tip above the preview size keeps the drag: `finish_gesture` renders it on release. + // Otherwise the first dab itself is invalid. Do not queue an unexpected release edit. + if let Some(p) = p + && !LiveMixer::defers_to_release(&app.session, &p).is_ok_and(|deferred| deferred) + { + if let Err(e) = LiveMixer::begin(&app.session, &p) { + app.ui.status = e.to_string(); + app.ui.status_error = true; + } + app.drag = None; + } + } else if tool == Tool::MixerBrush { + feed_live_stroke(app); + } + } + ToolEvent::Move { x, y, pressure } => { + // Polygonal Lasso: ⌥ held while the button is down draws freehand into the polygon; + // releasing ⌥ goes back to straight segments (the polygon stays open). + if tool == Tool::PolygonLasso && mods.alt && app.drag.is_none() && !app.ui.polygon.is_empty() { + if app.ui.polygon.last().is_none_or(|l| (l[0] - x).hypot(l[1] - y) >= 1.0) { + app.ui.polygon.push([x, y]); + } + return; + } + tool_move(app, x, y, pressure, mods); + feed_live_stroke(app); + } + ToolEvent::Up { x, y } => { + if tool.is_type() + && let Some(e) = app.ui.text_edit.as_mut() + { + e.dragging = false; + e.resize = None; + app.ui.caret_blink_time = app.last_frame_time; + } + if tool == Tool::Pen { + crate::vector_ui::pen_up(app); + } else if tool == Tool::CurvaturePen { + crate::vector_ui::curvature_up(app); + } + let zoom = app.point_zoom(); + let Some(mut d) = app.drag.take() else { return }; + d.track(mods); + if d.reposition { + d.shift_to([x, y]); + } + let last = d.points.last().map_or(d.start, |p| [p[0], p[1]]); + let [x, y] = crate::stroke_constraint::constrain(d.tool, &mut d.constrain, d.start, last, [x, y], mods.shift, zoom); + let [x, y] = crate::move_mods::selection_drag_to(&mut d, [x, y], mods.shift && app.active_tool() != Tool::Move); + // A Move-tool click (released where it was pressed) selects, it never moves: snapping + // the release point would otherwise nudge the layer onto a nearby edge. + if d.tool == Tool::Move && d.points.len() < 2 && matches!(raw, ToolEvent::Up { x, y } if [x, y] == d.start) { + app.move_preview = None; + crate::move_mods::finish(app); + if d.sel_move.is_some() { + finish_selection_drag(app, true, d.start, d.start); + } + return; + } + if d.points.last().is_none_or(|p| p[0] != x || p[1] != y) { + d.points.push([x, y, d.points.last().map_or(1.0, |p| p[2])]); + app.stylus.record_point(); + } + finish_gesture(app, d); + crate::move_mods::finish(app); + } + } +} + +/// Why a press with `tool` must not start: it would paint on or move a hidden target layer (the +/// engine refuses the command; refusing the press keeps the live stroke from drawing first). +fn hidden_target(app: &PhotocraftApp, tool: Tool) -> Option<&'static str> { + let cmd = match tool { + Tool::Move => "layer.translate", + // The live Gradient makes a new Gradient Fill layer above the target, which Photoshop + // allows over a hidden layer; only the classic one paints the target itself. + Tool::Gradient if !app.ui.tool_options.gradient_classic => return None, + // Every painting command follows the same target (layer, mask or channel) as a stroke. + t if t.is_brushlike() || matches!(t, Tool::Gradient | Tool::PaintBucket | Tool::MagicEraser) => "paint.stroke", + _ => return None, + }; + photocraft_engine::hidden_target::refusal(&app.session, cmd, &json!({})) +} + +/// Is document point `p` inside the active document's selection? +fn inside_selection(app: &PhotocraftApp, p: [f64; 2]) -> bool { + app.session.active().and_then(|st| st.doc.selection.as_ref()).is_some_and(|sel| covers(sel, p)) +} + +/// Does selection surface `sel` cover document point `p`? +fn covers(sel: &photocraft_raster::Surface, p: [f64; 2]) -> bool { + let mut v = [0.0f32]; + sel.read_pixel(p[0].floor() as i32, p[1].floor() as i32, &mut v); + v[0] > 0.0 +} + +/// Does a press with `tool` at `p` drag the selection rather than draw a new one? `Some(true)` +/// moves the floating piece (⌘ cuts one first, ⌘⌥ copies; a floating piece moves with a plain +/// drag; the Polygonal Lasso and Magic Wand need ⌘, as a plain press there places or samples), +/// `Some(false)` just the outline (no ⇧ / ⌥ and the options bar on New Selection, so a combining +/// drag still draws). +pub fn selection_drag_kind(app: &PhotocraftApp, tool: Tool, p: [f64; 2], mods: egui::Modifiers) -> Option { + // Click-driven selection tools (a press places a point or samples): only ⌘ drags the + // selection, and not while a polygon is being drawn. + let clicky = matches!(tool, Tool::PolygonLasso | Tool::MagicWand); + if !(clicky || matches!(tool, Tool::RectMarquee | Tool::EllipseMarquee | Tool::Lasso)) || (clicky && !app.ui.polygon.is_empty()) { + return None; + } + // ⌘ cuts, ⌘⌥ copies (`select.float`'s `copy`). + let cut = mods.command && !mods.shift; + if let Some(f) = app.session.active().and_then(photocraft_engine::float_cmds::floating) { + // A press on the piece's outline (where its ants are) drags it; one in the margin the cut + // left of the selection starts a new selection (#7538). + let at = [p[0] - f64::from(f.offset.0), p[1] - f64::from(f.offset.1)]; + let on = f.parts.outline().map_or_else(|| inside_selection(app, at), |o| covers(o, at)); + return (on && !mods.shift && (!mods.alt || mods.command) && (cut || !clicky)).then_some(true); + } + if !inside_selection(app, p) { + return None; + } + if cut { + return Some(true); + } + (!clicky && !mods.command && selection_mode(app, mods) == "replace").then_some(false) +} + +/// The tool a pointer event with `mods` goes to: ⌘ held is the Move tool (`hold_keys::cmd_moves`). +/// The canvas resolves the held key before the event (`tool_override`); automation and tests send +/// the modifier with the event. +pub(crate) fn event_tool(app: &PhotocraftApp, mods: egui::Modifiers) -> Tool { + match app.active_tool() { + t if app.tool_override.is_none() && mods.command && crate::hold_keys::cmd_moves(t) && app.ui.transform.is_none() && app.ui.text_edit.is_none() => { + Tool::Move + } + t => t, + } +} + +/// Does a ⌘ (⌘⌥) press with selection tool `tool` at `p` move the whole layer (a duplicate with +/// ⌥), as the Move tool would? Outside the selection or without one; inside it, ⌘ drags the +/// selected pixels instead (`selection_drag_kind`). +pub(crate) fn command_moves_layer(app: &PhotocraftApp, tool: Tool, p: [f64; 2], mods: egui::Modifiers) -> bool { + let selection_tool = matches!(tool, Tool::RectMarquee | Tool::EllipseMarquee | Tool::Lasso | Tool::PolygonLasso | Tool::MagicWand); + let floating = app.session.active().is_some_and(|st| photocraft_engine::float_cmds::floating(st).is_some()); + selection_tool && mods.command && !mods.shift && !floating && app.ui.polygon.is_empty() && !inside_selection(app, p) +} + +/// The guide a ⌘ press with `tool` at `p` drags (vertical?, index), as the Move tool's press +/// would (#2690): ⌘ is the Move tool, and a guide under the pointer comes before the layer or the +/// selected pixels. The selection tools, and every tool on which ⌘ is the Move tool +/// (`hold_keys::cmd_moves`, #6288); the canvas shows the guide cursor where this finds a guide. +/// Not while a polygon or lasso outline, a stroke, Free Transform or type editing is under way. +pub(crate) fn command_guide_at(app: &PhotocraftApp, tool: Tool, p: [f64; 2], mods: egui::Modifiers) -> Option<(bool, usize)> { + let selection_tool = matches!(tool, Tool::RectMarquee | Tool::EllipseMarquee | Tool::Lasso | Tool::PolygonLasso | Tool::MagicWand); + let moves = selection_tool || crate::hold_keys::cmd_moves(tool); + let idle = app.ui.polygon.is_empty() && !crate::lasso_ui::active(app) && app.ui.transform.is_none() && app.ui.text_edit.is_none() && app.drag.is_none(); + (moves && mods.command && idle).then(|| crate::rulers::guide_at(app, p[0], p[1])).flatten() +} diff --git a/crates/ui-egui/src/canvas/transform_controls.rs b/crates/ui-egui/src/canvas/transform_controls.rs new file mode 100644 index 0000000000..9d583cd604 --- /dev/null +++ b/crates/ui-egui/src/canvas/transform_controls.rs @@ -0,0 +1,151 @@ +use super::selection::floating_outline; +use super::view_xform::ViewXform; +use super::*; + +/// View › Show › Layer Edges: the colour of the active layer's outline. +pub(crate) const LAYER_EDGES: Color32 = Color32::from_rgb(0x2d, 0x8c, 0xeb); + +/// View › Show › Layer Edges: the active layer's content bounds (cached per tile) where the canvas +/// shows them. During a Move drag that is at the offset the image was drawn with this frame, so +/// the outline moves in lockstep with the layer's pixels (#2413). +pub(crate) fn layer_edges_rect(app: &PhotocraftApp, idx: usize) -> Option { + if !app.ui.view.shows(app.ui.view.show.layer_edges) { + return None; + } + let st = app.session.documents().get(idx)?; + let id = st.active_layer?; + let b = st.doc.layer(id)?.surface().map(photocraft_compose::bounds::content_bounds)?; + if b.is_empty() { + return None; + } + let (dx, dy) = crate::move_ui::shown_layer_offset(app, st.doc.id, st.revision, id).unwrap_or((0, 0)); + Some(b.translate(dx, dy)) +} + +/// The layers Move › Show Transform Controls frames: every selected layer but the Background. +/// A corner radius drag hides the box, as in Photoshop. So does View › Extras (⌘H, #6699): the +/// controls are an Extra, hidden and inert until Extras comes back, while Show Transform Controls +/// keeps its setting. +pub(super) fn transform_controls_layers(app: &PhotocraftApp) -> Vec<&photocraft_doc::Layer> { + if app.ui.tool != Tool::Move + || !app.ui.tool_options.move_show_transform + || !app.ui.view.extras + || app.ui.transform.is_some() + || app.drag.is_some() + || app.ui.corner_radius.is_some() + { + return Vec::new(); + } + let Some(st) = app.session.active() else { return Vec::new() }; + st.selected_layers().into_iter().filter_map(|id| st.doc.layer(id)).filter(|l| !crate::doc_props_ui::is_background(&st.doc, l)).collect() +} + +/// Several layers are selected: Show Transform Controls frames them all, as Photoshop does, but +/// Free Transform works on one layer, so the frame has no handles to scale or rotate them. +pub(super) fn transform_controls_several(app: &PhotocraftApp) -> bool { + transform_controls_layers(app).len() > 1 +} + +/// Move tool › Show Transform Controls: the boxes Free Transform would open on the selected +/// layers, joined into one. +pub(super) fn transform_controls_rect(app: &PhotocraftApp, xf: &ViewXform) -> Option { + let st = app.session.active()?; + let layers = transform_controls_layers(app); + let b = layers.iter().map(|l| photocraft_engine::transform_cmds::transform_frame(&st.doc, l)).filter(|b| !b.is_empty()).reduce(|a, b| a.union(&b))?; + // Floating selected pixels are framed by their outline, as their ants are (#7538), not by the + // selection they were cut with; a frame round other selected layers too keeps them all. + let alone = matches!(layers.as_slice(), [l] if photocraft_engine::float_cmds::floating(st).is_some_and(|f| f.layer == l.id)); + let b = app.session.active_index().filter(|_| alone).and_then(|idx| floating_outline(app, idx)).map_or(b, |o| o.content_bounds()); + let (dx, dy) = crate::move_ui::floating_offset(app).unwrap_or((0, 0)); + let b = b.translate(dx, dy); + if b.is_empty() { + return None; + } + Some(Rect::from_two_pos(xf.to_screen(b.x0 as f32, b.y0 as f32), xf.to_screen(b.x1 as f32, b.y1 as f32))) +} + +/// The Move tool shows transform handles even before a Free Transform session exists. +/// Use the same hit areas for pointer-down and hover, so a control never behaves like +/// resize/rotate while showing the ordinary four-arrow Move cursor (#2871). +pub(super) fn transform_controls_cursor(r: Rect, p: Pos2) -> Option { + let handles = [r.left_top(), r.center_top(), r.right_top(), r.right_center(), r.right_bottom(), r.center_bottom(), r.left_bottom(), r.left_center()]; + let grab = crate::transform_tool::HANDLE_PX as f32; + for (i, handle) in handles.into_iter().enumerate() { + if handle.distance(p) <= grab { + return Some(match i { + 0 | 4 => egui::CursorIcon::ResizeNwSe, + 2 | 6 => egui::CursorIcon::ResizeNeSw, + 1 | 5 => egui::CursorIcon::ResizeVertical, + _ => egui::CursorIcon::ResizeHorizontal, + }); + } + } + // The rotation band: the pointer gives way to the curved rotate arrow (`transform_controls_turn`). + in_rotation_band(r, p).then_some(egui::CursorIcon::None) +} + +fn in_rotation_band(r: Rect, p: Pos2) -> bool { + r.expand(18.0).contains(p) && !r.expand(5.0).contains(p) +} + +/// In the rotation band just outside the Move tool's transform controls, the screen direction the +/// curved rotate arrow bends round: into the box along the nearest corner's bisector, as Free +/// Transform draws it (#4658). Before, the band showed a plain alias pointer, so nothing said a +/// drag there rotates. +pub(super) fn transform_controls_turn(r: Rect, p: Pos2) -> Option { + if !in_rotation_band(r, p) + || [r.left_top(), r.center_top(), r.right_top(), r.right_center(), r.right_bottom(), r.center_bottom(), r.left_bottom(), r.left_center()] + .into_iter() + .any(|h| h.distance(p) <= crate::transform_tool::HANDLE_PX as f32) + { + return None; + } + let corner = pos2(if p.x < r.center().x { r.left() } else { r.right() }, if p.y < r.center().y { r.top() } else { r.bottom() }); + Some(vec2((r.center().x - corner.x).signum(), (r.center().y - corner.y).signum()).normalized() * 16.0) +} + +/// A visible handle starts scaling; the narrow band just outside the box starts rotation. +/// The interior stays the normal Move-tool drag target. +pub(super) fn transform_controls_hit(r: Rect, p: Pos2) -> bool { + transform_controls_cursor(r, p).is_some() +} + +/// Enter the existing Free Transform session when a Move-tool transform control is pressed. +pub(super) fn begin_transform_controls_at(app: &mut PhotocraftApp, ctx: &egui::Context, xf: &ViewXform, p: Pos2) -> bool { + if transform_controls_several(app) { + return false; + } + let Some(r) = transform_controls_rect(app, xf) else { return false }; + if !transform_controls_hit(r, p) { + return false; + } + match crate::transform_tool::begin(app, ctx) { + Ok(()) => true, + Err(e) => { + app.ui.status = e; + false + } + } +} + +/// Move tool › Show Transform Controls: the selected layers' bounding box, with its eight handles +/// for one layer, and the outline of every selected shape layer, as in Photoshop. +pub(super) fn draw_transform_controls(app: &mut PhotocraftApp, painter: &egui::Painter, xf: &ViewXform) { + let Some(r) = transform_controls_rect(app, xf) else { return }; + let accent = crate::theme::Tokens::get(painter.ctx()).accent; + let to_scr = |q: [f64; 2]| xf.to_screen(q[0] as f32, q[1] as f32); + for l in transform_controls_layers(app) { + if let LayerContent::Shape(sh) = &l.content { + crate::vector_ui::draw_outline(painter, &sh.path, &to_scr, accent); + } + } + painter.rect_stroke(r, 0.0, Stroke::new(1.0, accent), egui::StrokeKind::Middle); + if transform_controls_several(app) { + return; + } + for p in [r.left_top(), r.center_top(), r.right_top(), r.right_center(), r.right_bottom(), r.center_bottom(), r.left_bottom(), r.left_center()] { + let h = Rect::from_center_size(p, vec2(7.0, 7.0)); + painter.rect_filled(h, 0.0, Color32::WHITE); + painter.rect_stroke(h, 0.0, Stroke::new(1.0, accent), egui::StrokeKind::Inside); + } +} diff --git a/crates/ui-egui/src/canvas/transform_controls_tests.rs b/crates/ui-egui/src/canvas/transform_controls_tests.rs new file mode 100644 index 0000000000..957ae3589d --- /dev/null +++ b/crates/ui-egui/src/canvas/transform_controls_tests.rs @@ -0,0 +1,357 @@ +use super::*; +use serde_json::json; + +/// #7538: as in Photoshop, the box frames a loose selection until its pixels are moved, then +/// the pixels themselves, while they float and once dropped. +#[test] +fn transform_controls_frame_the_moved_pixels_not_the_marquee() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 200, "height": 200, "background": "transparent"})).unwrap(); + app.session.execute("select.rect", json!({"x": 40, "y": 40, "width": 50, "height": 40})).unwrap(); + app.session.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.session.execute("select.rect", json!({"x": 20, "y": 20, "width": 100, "height": 90})).unwrap(); + app.sync_views(); + app.ui.tool = Tool::Move; + app.ui.tool_options.move_show_transform = true; + let xf = + ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(200.0, 200.0)), zoom: 1.0, center: [100.0, 100.0], flip: false, rotation: 0.0, aspect: 1.0 }; + let frame = |app: &PhotocraftApp| { + let r = transform_controls_rect(app, &xf).unwrap(); + let (lt, rb) = (xf.to_doc(r.left_top()), xf.to_doc(r.right_bottom())); + [lt[0], lt[1], rb[0], rb[1]].map(|v| v.round() as i32) + }; + assert_eq!(frame(&app), [20, 20, 120, 110], "the selection, before anything moves"); + app.run("select.float", json!({"dx": 10, "dy": 5})).unwrap(); + assert_eq!(frame(&app), [50, 45, 100, 85], "the floating pixels"); + app.run("select.drop", json!({})).unwrap(); + assert_eq!(frame(&app), [50, 45, 100, 85], "dropped"); +} + +/// #7538: with several layers selected the Move tool moves them whole, and the selection goes +/// with them, as in Photoshop: its ants follow the drag and it lands with them in one step. +#[test] +fn moving_several_layers_carries_the_selection() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 200, "height": 200, "background": "transparent"})).unwrap(); + let a = app.session.active().unwrap().active_layer.unwrap(); + app.session.execute("select.rect", json!({"x": 40, "y": 40, "width": 50, "height": 40})).unwrap(); + app.session.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.session.execute("layer.new.layer", json!({})).unwrap(); + app.session.execute("select.rect", json!({"x": 120, "y": 120, "width": 30, "height": 30})).unwrap(); + app.session.execute("edit.fill", json!({"color": "#0000ff"})).unwrap(); + app.session.execute("layer.select", json!({"layer": a.0, "mode": "add"})).unwrap(); + app.session.execute("select.rect", json!({"x": 20, "y": 20, "width": 100, "height": 90})).unwrap(); + app.sync_views(); + app.ui.tool = Tool::Move; + app.ui.tool_options.move_auto_select = false; + app.ui.extras.snap = false; + app.ui.view.show.smart_guides = false; + let steps = app.session.active().unwrap().history.past_len(); + let m = egui::Modifiers::NONE; + tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, m); + tool_event(&mut app, ToolEvent::Move { x: 72.0, y: 68.0, pressure: 1.0 }, m); + assert_eq!(selection_shown_offset(&app), Some((12, 8)), "the ants follow the layers"); + tool_event(&mut app, ToolEvent::Up { x: 72.0, y: 68.0 }, m); + let st = app.session.active().unwrap(); + assert!(photocraft_engine::float_cmds::floating(st).is_none(), "whole layers moved, nothing floats"); + assert_eq!(st.doc.selection.as_ref().map(|s| s.content_bounds()), Some(photocraft_geom::Rect::new(32, 28, 132, 118))); + assert_eq!(st.doc.layer(a).unwrap().surface().unwrap().content_bounds(), photocraft_geom::Rect::new(52, 48, 102, 88)); + assert_eq!(st.history.past_len(), steps + 1, "one Move step"); + assert!(app.session.undo()); + let sel = app.session.active().unwrap().doc.selection.as_ref().map(|s| s.content_bounds()); + assert_eq!(sel, Some(photocraft_geom::Rect::new(20, 20, 120, 110)), "Undo takes the selection back too"); + + // A piece floating (a marquee ⌘-drag with both selected) when the layers are dragged: the + // press drops it first, so the ants follow the drag from where it was dropped. + app.run("select.float", json!({"dx": 10, "dy": 5})).unwrap(); + let outline = photocraft_engine::float_cmds::floating(app.session.active().unwrap()).unwrap().parts.outline().unwrap().content_bounds(); + tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, m); + let st = app.session.active().unwrap(); + assert!(photocraft_engine::float_cmds::floating(st).is_none(), "the press dropped the piece"); + assert_eq!(st.doc.selection.as_ref().map(|s| s.content_bounds()), Some(outline.translate(10, 5)), "at its offset"); + tool_event(&mut app, ToolEvent::Move { x: 72.0, y: 68.0, pressure: 1.0 }, m); + assert_eq!(selection_shown_offset(&app), Some((12, 8)), "then the ants follow the drag"); + tool_event(&mut app, ToolEvent::Up { x: 72.0, y: 68.0 }, m); + let sel = app.session.active().unwrap().doc.selection.as_ref().map(|s| s.content_bounds()); + assert_eq!(sel, Some(outline.translate(22, 13)), "released where the ants were"); +} + +/// A transparent 200² document: a red square (40..90, 40..80) on its layer, a loose marquee +/// (20..120, 20..110) round it, cut and floated 10, 5 to the right and down. +fn floating_square() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 200, "height": 200, "background": "transparent"})).unwrap(); + app.session.execute("select.rect", json!({"x": 40, "y": 40, "width": 50, "height": 40})).unwrap(); + app.session.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.session.execute("select.rect", json!({"x": 20, "y": 20, "width": 100, "height": 90})).unwrap(); + app.sync_views(); + app.session.execute("select.float", json!({"dx": 10, "dy": 5})).unwrap(); + app +} + +/// #7538: a selection tool's press on a floating piece's ants drags it; one in the margin its +/// cut left of the loose marquee draws a new selection, as the ants say. +#[test] +fn a_press_in_the_margin_of_a_floating_piece_starts_a_new_selection() { + let app = floating_square(); + let none = egui::Modifiers::NONE; + for tool in [Tool::RectMarquee, Tool::Lasso] { + assert_eq!(selection_drag_kind(&app, tool, [70.0, 60.0], none), Some(true), "{tool:?}: on the square drags it"); + assert_eq!(selection_drag_kind(&app, tool, [33.0, 28.0], none), None, "{tool:?}: in the old marquee's margin"); + } +} + +/// Several selected layers keep one frame round them all while the active one's pixels float: +/// the piece's outline frames it only when it is the only layer framed. +#[test] +fn a_floating_piece_among_several_selected_layers_keeps_the_shared_frame() { + let mut app = floating_square(); + app.session.execute("select.drop", json!({})).unwrap(); + let a = app.session.active().unwrap().active_layer.unwrap(); + app.session.execute("layer.new.layer", json!({})).unwrap(); + app.session.execute("select.rect", json!({"x": 150, "y": 150, "width": 20, "height": 20})).unwrap(); + app.session.execute("edit.fill", json!({"color": "#0000ff"})).unwrap(); + app.session.execute("layer.select", json!({"layer": a.0, "mode": "add"})).unwrap(); + app.session.execute("select.rect", json!({"x": 20, "y": 20, "width": 100, "height": 90})).unwrap(); + app.ui.tool = Tool::Move; + app.ui.tool_options.move_show_transform = true; + assert!(transform_controls_several(&app), "two layers framed"); + app.session.execute("select.float", json!({"dx": 5, "dy": 0})).unwrap(); + assert!(photocraft_engine::float_cmds::floating(app.session.active().unwrap()).is_some()); + let xf = + ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(200.0, 200.0)), zoom: 1.0, center: [100.0, 100.0], flip: false, rotation: 0.0, aspect: 1.0 }; + let r = transform_controls_rect(&app, &xf).unwrap(); + let (lt, rb) = (xf.to_doc(r.left_top()), xf.to_doc(r.right_bottom())); + assert!(rb[0] - lt[0] > 60.0 && rb[1] - lt[1] > 60.0, "the frame isn't shrunk to the one piece: {lt:?} {rb:?}"); +} + +#[test] +fn several_selected_layers_share_one_frame_without_handles() { + // As in Photoshop: Show Transform Controls frames every selected layer. Free Transform + // works on one layer, so the shared frame doesn't start it. + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.session.execute("shape.create", json!({"kind": "rect", "rect": [20, 30, 40, 40], "fill": "#ff0000"})).unwrap(); + let a = app.session.active().unwrap().active_layer.unwrap(); + app.session.execute("shape.create", json!({"kind": "rect", "rect": [100, 120, 50, 30], "fill": "#ff0000"})).unwrap(); + app.sync_views(); + app.ui.tool = Tool::Move; + app.ui.tool_options.move_show_transform = true; + let xf = + ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(200.0, 200.0)), zoom: 1.0, center: [100.0, 100.0], flip: false, rotation: 0.0, aspect: 1.0 }; + let one = transform_controls_rect(&app, &xf).unwrap(); + assert!(!transform_controls_several(&app)); + app.session.execute("layer.select", json!({"layer": a.0, "mode": "add"})).unwrap(); + assert!(transform_controls_several(&app)); + let both = transform_controls_rect(&app, &xf).unwrap(); + assert!(both.contains_rect(one) && both.width() > one.width() && both.height() > one.height(), "{both:?} frames both"); + let (lt, rb) = (xf.to_doc(both.left_top()), xf.to_doc(both.right_bottom())); + assert!((lt[0] - 20.0).abs() < 1e-3 && (lt[1] - 30.0).abs() < 1e-3 && (rb[0] - 150.0).abs() < 1e-3 && (rb[1] - 150.0).abs() < 1e-3, "{lt:?} {rb:?}"); + let ctx = egui::Context::default(); + assert!(!begin_transform_controls_at(&mut app, &ctx, &xf, both.right_bottom())); + assert!(app.ui.transform.is_none()); + // The Background never joins the frame. + let bg = app.session.active().unwrap().doc.layers[0].id; + app.session.execute("layer.select", json!({"layer": bg.0, "mode": "add"})).unwrap(); + assert_eq!(transform_controls_layers(&app).len(), 2); +} + +#[test] +fn move_transform_controls_start_free_transform_for_vector_shapes() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.session.execute("shape.create", json!({"kind": "rect", "rect": [20, 30, 80, 40], "fill": "#ff0000"})).unwrap(); + app.sync_views(); + app.ui.tool = Tool::Move; + app.ui.tool_options.move_show_transform = true; + + let xf = + ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(200.0, 200.0)), zoom: 1.0, center: [100.0, 100.0], flip: false, rotation: 0.0, aspect: 1.0 }; + let r = transform_controls_rect(&app, &xf).expect("shape layers have transform bounds"); + assert!(transform_controls_hit(r, r.right_bottom())); + + let ctx = egui::Context::default(); + assert!(begin_transform_controls_at(&mut app, &ctx, &xf, r.right_bottom())); + let t = app.ui.transform.as_ref().expect("control press starts Free Transform"); + assert_eq!(t.rect, [20.0, 30.0, 100.0, 70.0]); +} + +#[test] +fn hiding_extras_hides_the_move_transform_controls() { + // #6699: as in Photoshop, View › Extras (⌘H) hides the Move tool's transform box and + // handles; again brings them back. Show Transform Controls and the layer stay as they were. + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.session.execute("shape.create", json!({"kind": "rect", "rect": [20, 30, 80, 40], "fill": "#ff0000"})).unwrap(); + app.sync_views(); + app.ui.tool = Tool::Move; + app.ui.tool_options.move_show_transform = true; + let xf = + ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(200.0, 200.0)), zoom: 1.0, center: [100.0, 100.0], flip: false, rotation: 0.0, aspect: 1.0 }; + let ctx = egui::Context::default(); + let shown = transform_controls_rect(&app, &xf).expect("the box shows with Extras on"); + let layer = app.session.active().unwrap().doc.layers.clone(); + let painted = |app: &mut PhotocraftApp| { + let out = ctx.run_ui(egui::RawInput::default(), |ui| { + let painter = ui.ctx().layer_painter(egui::LayerId::background()); + draw_transform_controls(app, &painter, &xf); + }); + let egui::FullOutput { mut textures_delta, shapes, .. } = out; + textures_delta.clear(); + shapes.len() + }; + // The shape's outline, the box and its eight handles. + assert!(painted(&mut app) > 8, "the box and handles are drawn"); + + crate::menus::invoke(&mut app, &ctx, "view.extras", json!({})).unwrap(); + assert!(!app.ui.view.extras); + assert!(transform_controls_rect(&app, &xf).is_none(), "no box with Extras hidden"); + assert_eq!(painted(&mut app), 0, "nothing is drawn"); + // Hidden handles don't act: a press on a corner doesn't start Free Transform. + assert!(!begin_transform_controls_at(&mut app, &ctx, &xf, shown.right_bottom())); + assert!(app.ui.transform.is_none()); + assert!(app.ui.tool_options.move_show_transform, "Show Transform Controls is unchanged"); + assert_eq!(app.session.active().unwrap().doc.layers, layer, "the layer is unchanged"); + + crate::menus::invoke(&mut app, &ctx, "view.extras", json!({})).unwrap(); + assert!(app.ui.view.extras); + assert_eq!(transform_controls_rect(&app, &xf), Some(shown), "⌘H again restores the box"); +} + +#[test] +fn move_transform_controls_follow_floating_selected_pixels() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("select.rect", json!({"x": 100, "y": 100, "width": 100, "height": 60})).unwrap(); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.ui.tool = Tool::Move; + app.ui.tool_options.move_show_transform = true; + assert!(crate::move_ui::float_selected(&mut app, false, 100.0, 50.0)); + let xf = + ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)), zoom: 1.0, center: [200.0, 150.0], flip: false, rotation: 0.0, aspect: 1.0 }; + let r = transform_controls_rect(&app, &xf).unwrap(); + assert_eq!(r, Rect::from_min_max(pos2(200.0, 150.0), pos2(300.0, 210.0))); + let ctx = egui::Context::default(); + assert!(begin_transform_controls_at(&mut app, &ctx, &xf, r.right_bottom())); + assert_eq!(app.ui.transform.as_ref().unwrap().rect, [200.0, 150.0, 300.0, 210.0]); +} + +/// #5297: with a selection the Move tool's transform controls are the selection's rectangle, +/// though the layer fills only part of it, and a press on them opens that box. +#[test] +fn move_transform_controls_frame_the_selection() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("select.rect", json!({"x": 100, "y": 100, "width": 100, "height": 60})).unwrap(); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.run("select.rect", json!({"x": 60, "y": 80, "width": 100, "height": 120})).unwrap(); + app.ui.tool = Tool::Move; + app.ui.tool_options.move_show_transform = true; + let xf = + ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)), zoom: 1.0, center: [200.0, 150.0], flip: false, rotation: 0.0, aspect: 1.0 }; + let r = transform_controls_rect(&app, &xf).unwrap(); + assert_eq!(r, Rect::from_min_max(pos2(60.0, 80.0), pos2(160.0, 200.0))); + let ctx = egui::Context::default(); + assert!(begin_transform_controls_at(&mut app, &ctx, &xf, r.right_bottom())); + assert_eq!(app.ui.transform.as_ref().unwrap().rect, [60.0, 80.0, 160.0, 200.0]); +} + +/// #2585: Free Transform on a position-locked layer is refused before the box opens, with +/// Photoshop's alert, from ⌘T and from the Move tool's transform controls alike. It used to +/// open, preview every drag and fail only at commit. +#[test] +fn free_transform_on_a_locked_layer_is_refused_up_front() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.session.execute("shape.create", json!({"kind": "rect", "rect": [20, 30, 80, 40], "fill": "#ff0000"})).unwrap(); + app.session + .edit("lock", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().locks.position = true; + Ok(()) + }) + .unwrap(); + app.sync_views(); + let errors = |app: &PhotocraftApp| -> Vec { + app.ui + .dialogs + .iter() + .filter(|d| d.kind == crate::state::DialogKind::Error) + .filter_map(|d| d.fields.get("message")?.as_str().map(String::from)) + .collect() + }; + let ctx = egui::Context::default(); + // ⌘T. + let r = crate::menus::invoke(&mut app, &ctx, "edit.freeTransform", json!({})); + assert_eq!(r, Err(crate::transform_tool::LOCKED.to_string())); + assert!(app.ui.transform.is_none() && app.transform_preview.is_none(), "no box opened"); + assert_eq!(errors(&app), [crate::transform_tool::LOCKED]); + app.ui.dialogs.clear(); + // The Move tool's transform controls. + app.ui.tool = Tool::Move; + app.ui.tool_options.move_show_transform = true; + let xf = + ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(200.0, 200.0)), zoom: 1.0, center: [100.0, 100.0], flip: false, rotation: 0.0, aspect: 1.0 }; + let r = transform_controls_rect(&app, &xf).unwrap(); + assert!(!begin_transform_controls_at(&mut app, &ctx, &xf, r.right_bottom())); + assert!(app.ui.transform.is_none()); + assert_eq!(errors(&app), [crate::transform_tool::LOCKED]); +} + +#[test] +fn move_transform_controls_show_resize_and_rotate_cursors_before_first_interaction() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.session.execute("shape.create", json!({"kind": "rect", "rect": [20, 30, 80, 40], "fill": "#ff0000"})).unwrap(); + app.sync_views(); + app.ui.tool = Tool::Move; + app.ui.tool_options.move_show_transform = true; + let xf = + ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(200.0, 200.0)), zoom: 1.0, center: [100.0, 100.0], flip: false, rotation: 0.0, aspect: 1.0 }; + + let r = transform_controls_rect(&app, &xf).expect("visible shape controls"); + assert!(app.ui.transform.is_none(), "no transform session is needed for hover"); + for (p, expected) in [ + (r.left_top(), egui::CursorIcon::ResizeNwSe), + (r.right_bottom(), egui::CursorIcon::ResizeNwSe), + (r.right_top(), egui::CursorIcon::ResizeNeSw), + (r.left_bottom(), egui::CursorIcon::ResizeNeSw), + (r.center_top(), egui::CursorIcon::ResizeVertical), + (r.center_bottom(), egui::CursorIcon::ResizeVertical), + (r.right_center(), egui::CursorIcon::ResizeHorizontal), + (r.left_center(), egui::CursorIcon::ResizeHorizontal), + // Between handles: the rotation band (a point above the top-centre handle is that handle), + // where the curved rotate arrow replaces the pointer (#4658). + (pos2(r.left() + r.width() * 0.25, r.top() - 12.0), egui::CursorIcon::None), + ] { + assert_eq!(transform_controls_cursor(r, p), Some(expected), "hover at {p:?}"); + assert!(transform_controls_hit(r, p), "same region must start a transform"); + } + assert_eq!(transform_controls_cursor(r, r.center()), None, "interior stays Move"); + assert_eq!(transform_controls_cursor(r, pos2(r.center().x, r.top() - 30.0)), None); + // The rotate arrow bends round the nearest corner, pointing into the box; handles and the + // interior have none. + let into = |p: Pos2| transform_controls_turn(r, p).map(|v| (v.x.signum(), v.y.signum())); + assert_eq!(into(pos2(r.left() + r.width() * 0.25, r.top() - 12.0)), Some((1.0, 1.0)), "top left"); + assert_eq!(into(pos2(r.right() + 12.0, r.bottom() - r.height() * 0.25)), Some((-1.0, -1.0)), "bottom right"); + assert_eq!(into(pos2(r.left() - 12.0, r.bottom() + 12.0)), Some((1.0, -1.0)), "beyond the bottom-left corner"); + assert_eq!(into(r.left_top()), None); + assert_eq!(into(r.center()), None); + + // Changing the active shape changes the hover bounds without requiring a drag first. + app.session.execute("shape.create", json!({"kind": "rect", "rect": [120, 100, 40, 50], "fill": "#00ff00"})).unwrap(); + let next = transform_controls_rect(&app, &xf).expect("new active shape controls"); + assert_ne!(r, next); + assert_eq!(transform_controls_cursor(next, next.right_bottom()), Some(egui::CursorIcon::ResizeNwSe)); + assert_eq!(transform_controls_cursor(next, next.center()), None); +} + +#[test] +fn transform_control_hit_keeps_move_interior_free_and_has_rotation_band() { + let r = Rect::from_min_max(pos2(20.0, 30.0), pos2(100.0, 70.0)); + assert!(transform_controls_hit(r, r.left_top())); + assert!(transform_controls_hit(r, pos2(60.0, 18.0))); + assert!(!transform_controls_hit(r, r.center())); + assert!(!transform_controls_hit(r, pos2(60.0, 4.0))); +} diff --git a/crates/ui-egui/src/canvas/view_xform.rs b/crates/ui-egui/src/canvas/view_xform.rs new file mode 100644 index 0000000000..ec3df91d13 --- /dev/null +++ b/crates/ui-egui/src/canvas/view_xform.rs @@ -0,0 +1,262 @@ +use super::*; + +/// Document ↔ screen mapping for a canvas rect and a view. +#[derive(Clone, Copy, Debug)] +pub struct ViewXform { + pub rect: Rect, + pub zoom: f32, + pub center: [f32; 2], + /// View › Flip Horizontal: the view is mirrored left-right (the document is not). + pub flip: bool, + /// Camera rotation in degrees around [`Self::center`]. Clockwise (Y-down) is positive; applied + /// before flip. + pub rotation: f32, + /// View › Pixel Aspect Ratio Correction: a document pixel is drawn this many times wider than + /// tall (1 = square). Applied in document space, before rotation, so a rotated view still + /// shows the stretched image turned as a whole. + pub aspect: f32, +} + +impl ViewXform { + /// The main canvas's mapping for the active document as last laid out (inside the rulers). + pub fn active(app: &PhotocraftApp) -> Option { + let v = app.ui.views.get(app.session.active_index()?)?; + let (zoom, center) = + if v.zoom_animating && app.session.prefs().general.animated_zoom { v.display_camera.unwrap_or((v.zoom, v.center)) } else { (v.zoom, v.center) }; + Some( + Self { + rect: crate::rulers::content_rect(app, app.last_canvas_rect), + zoom: zoom / app.canvas_ppp(), + center, + flip: app.ui.view.flip_horizontal, + rotation: v.rotation, + aspect: app.ui.view.display_aspect(), + } + .pixel_aligned_for(app, app.canvas_ppp()), + ) + } + + pub(super) fn pixel_aligned_for(self, app: &PhotocraftApp, ppp: f32) -> Self { + // Default Crop counter-moves the frame and camera with fractional pointer deltas. + // Preserve that continuous mapping so its fixed frame does not wobble during a drag. + if crate::crop_mode::moves_image(app) { self } else { self.pixel_aligned(ppp) } + } + + /// At integer physical magnifications, texel edges must land on display pixel edges. + /// Keep this derived camera shared by images, overlays and input without changing the saved pan. + pub(super) fn pixel_aligned(mut self, ppp: f32) -> Self { + if !ppp.is_finite() || ppp <= 0.0 || !self.zoom.is_finite() || self.zoom <= 0.0 || !self.rotation.is_finite() || self.rotation.abs() >= 1e-8 { + return self; + } + let scale = vec2(self.zoom_x(), self.zoom) * ppp; + if !scale.is_finite() + || scale.x.round() < 1.0 + || scale.y.round() < 1.0 + || (scale.x - scale.x.round()).abs() > 1e-5 + || (scale.y - scale.y.round()).abs() > 1e-5 + { + return self; + } + let origin = self.to_screen(0.0, 0.0); + let physical = origin * ppp; + if !physical.is_finite() { + return self; + } + let aligned = pos2(physical.x.round(), physical.y.round()) / ppp; + let offset = self.unmap_vec((aligned - origin) / self.zoom); + let center = [self.center[0] - offset.x, self.center[1] - offset.y]; + if center.iter().all(|v| v.is_finite()) { + self.center = center; + } + self + } + + fn sincos(self) -> (f32, f32) { + if self.rotation.abs() < 1e-8 { + (1.0, 0.0) + } else { + let r = self.rotation.to_radians(); + (r.cos(), r.sin()) + } + } + + /// Document pixel width over height on screen: [`Self::aspect`], or 1 when it is unusable. + fn sx(self) -> f32 { + if self.aspect.is_finite() && self.aspect > 0.0 { self.aspect } else { 1.0 } + } + + /// Screen points per document pixel along the document's x axis. + pub fn zoom_x(&self) -> f32 { + self.zoom * self.sx() + } + + /// Unflip, unrotate and unstretch a screen-space vector (no zoom). Hand pan and zoom-about + /// use this. + pub fn unmap_vec(self, d: Vec2) -> Vec2 { + let d = if self.flip { vec2(-d.x, d.y) } else { d }; + let (c, s) = self.sincos(); + vec2((d.x * c + d.y * s) / self.sx(), -d.x * s + d.y * c) + } + + /// A document-space vector on screen: stretched, rotated, flipped and zoomed as the view + /// draws it (the inverse of [`Self::unmap_vec`], with the zoom). + pub fn map_vec(self, d: Vec2) -> Vec2 { + let (c, s) = self.sincos(); + let dx = d.x * self.sx(); + let v = vec2(dx * c - d.y * s, dx * s + d.y * c) * self.zoom; + if self.flip { vec2(-v.x, v.y) } else { v } + } + + pub fn to_screen(&self, x: f32, y: f32) -> Pos2 { + let (c, s) = self.sincos(); + let dx = (x - self.center[0]) * self.sx(); + let dy = y - self.center[1]; + let rx = dx * c - dy * s; + let ry = dx * s + dy * c; + let sx = if self.flip { -1.0 } else { 1.0 }; + self.rect.center() + vec2(rx * self.zoom * sx, ry * self.zoom) + } + pub fn to_doc(&self, p: Pos2) -> [f64; 2] { + let d = (p - self.rect.center()) / self.zoom; + let u = self.unmap_vec(d); + [(u.x + self.center[0]) as f64, (u.y + self.center[1]) as f64] + } + /// On-screen bounds of the image, including camera rotation and pixel aspect correction. + pub fn image_bounds(self, size: [u32; 2]) -> Rect { + let (c, s) = self.sincos(); + let w = size[0] as f32 * self.sx() * self.zoom; + let h = size[1] as f32 * self.zoom; + let center = self.to_screen(size[0] as f32 / 2.0, size[1] as f32 / 2.0); + Rect::from_center_size(center, vec2(c.abs() * w + s.abs() * h, s.abs() * w + c.abs() * h)) + } + pub fn doc_rect(&self, r: DRect) -> Rect { + let pts = [ + self.to_screen(r.x0 as f32, r.y0 as f32), + self.to_screen(r.x1 as f32, r.y0 as f32), + self.to_screen(r.x1 as f32, r.y1 as f32), + self.to_screen(r.x0 as f32, r.y1 as f32), + ]; + let mut min = pts[0]; + let mut max = pts[0]; + for p in pts { + min = min.min(p); + max = max.max(p); + } + Rect::from_min_max(min, max) + } +} + +/// Document point under a screen position on the main canvas, or `None` when the position is +/// outside it: the rulers are not part of the canvas, so drops on the ruler strip are not +/// canvas drops. Preset-panel drops and drag-and-drop placement share this so both land exactly +/// where the canvas draws. +pub fn doc_point_at(app: &PhotocraftApp, pos: Pos2) -> Option<[f64; 2]> { + let xf = ViewXform::active(app)?; + xf.rect.contains(pos).then(|| xf.to_doc(pos)) +} + +/// Fit the document into `area` (egui points) for a display with `ppp` physical pixels per +/// point; `View::zoom` is stored in physical pixels per document pixel. `aspect` is the +/// displayed pixel aspect ratio ([`ViewXform::aspect`]): the image is that much wider on screen. +pub fn fit_view(view: &mut View, doc: &Document, area: Vec2, ppp: f32, aspect: f32) { + let (w, h) = (doc.size.width as f32, doc.size.height as f32); + let shown_w = w * if aspect.is_finite() && aspect > 0.0 { aspect } else { 1.0 }; + // Fit never magnifies past 100%: one image pixel per *physical* pixel, so the cap applies + // after the points → device pixels conversion (a 150% display would otherwise open at 150%). + let fit = ((area.x - 40.0) / shown_w).min((area.y - 40.0) / h) * ppp; + let zoom = crate::zoom_levels::clamp(fit.min(1.0), [doc.size.width, doc.size.height]); + view.zoom = zoom; + view.center = [w / 2.0, h / 2.0]; + view.fit_pending = false; + view.fill_pending = false; +} + +/// Ease a transient presentation camera over 220 ms without changing the requested camera. +pub(super) fn animated_view(view: &mut View, xf: ViewXform, ppp: f32, animated_zoom: bool, time: f64) -> View { + if !animated_zoom { + view.request_zoom_animation(false); + } + let target = (view.zoom, view.center); + // Clamping, a canvas resize, or another camera command can make the original anchor + // incompatible with the requested camera. The target must always win. + if let Some((doc, screen)) = view.zoom_anchor { + let offset = xf.unmap_vec((pos2(screen[0], screen[1]) - xf.rect.center()) / (view.zoom / ppp)); + if (doc[0] as f32 - offset.x - view.center[0]).abs() > 0.01 || (doc[1] as f32 - offset.y - view.center[1]).abs() > 0.01 { + view.zoom_anchor = None; + } + } + let mut shown = view.clone(); + if view.zoom_animating { + if view.zoom_transition.is_none_or(|a| a.target != target) { + view.zoom_transition = Some(crate::state::ZoomTransition { from: view.display_camera.unwrap_or(target), target, started: time }); + } + if let Some(a) = view.zoom_transition { + let elapsed = (time - a.started) / 0.22; + let t = if elapsed.is_finite() { elapsed.clamp(0.0, 1.0) as f32 } else { 1.0 }; + let ease = t * t * (3.0 - 2.0 * t); + let lerp = |from: f32, to: f32| from + (to - from) * ease; + shown.zoom = lerp(a.from.0, target.0); + shown.center = [lerp(a.from.1[0], target.1[0]), lerp(a.from.1[1], target.1[1])]; + if let Some((doc, screen)) = view.zoom_anchor { + let zoom = shown.zoom / ppp; + if zoom.is_finite() && zoom > 0.0 { + let offset = xf.unmap_vec((pos2(screen[0], screen[1]) - xf.rect.center()) / zoom); + shown.center = [doc[0] as f32 - offset.x, doc[1] as f32 - offset.y]; + } + } + if t >= 1.0 { + view.zoom_animating = false; + } + } + } + if !view.zoom_animating { + shown.zoom = target.0; + shown.center = target.1; + view.zoom_anchor = None; + view.zoom_transition = None; + } + view.display_camera = Some((shown.zoom, shown.center)); + shown +} + +/// Centre the document and zoom until it fills the canvas. One axis can extend beyond the +/// viewport, matching the Hand tool's Fill Screen action. +pub fn fill_view(view: &mut View, doc: &Document, area: Vec2, ppp: f32, aspect: f32) { + let (w, h) = (doc.size.width as f32, doc.size.height as f32); + let shown_w = w * if aspect.is_finite() && aspect > 0.0 { aspect } else { 1.0 }; + let points = (area.x / shown_w).max(area.y / h); + let zoom = crate::zoom_levels::clamp(points * ppp, [doc.size.width, doc.size.height]); + view.zoom = zoom; + view.center = [w / 2.0, h / 2.0]; + view.fit_pending = false; + view.fill_pending = false; +} + +/// Where a wheel or pinch zoom anchors for a pointer at `p`: the pointer itself over the image, +/// otherwise the nearest point of the image (#3720). Anchoring on a pointer out on the gray +/// pasteboard slid the image away from it, out of the window after a few notches; Photoshop keeps +/// the image in view. Clamped in document space, so a rotated or flipped view behaves the same. +pub(super) fn wheel_anchor(xf: &ViewXform, p: Pos2, doc_size: [u32; 2]) -> Pos2 { + let [w, h] = doc_size; + let d = xf.to_doc(p); + if w == 0 || h == 0 || !(d[0].is_finite() && d[1].is_finite()) { + return p; + } + let c = [d[0].clamp(0.0, f64::from(w)), d[1].clamp(0.0, f64::from(h))]; + if c == d { p } else { xf.to_screen(c[0] as f32, c[1] as f32) } +} + +/// Zoom to `new_zoom` about `p`: keep its document point under the pointer, or move it to the +/// view centre when Zoom Clicked Point to Center (`center_on_point`) is enabled. +pub(super) fn zoom_about(view: &mut View, xf: &ViewXform, p: Pos2, new_zoom: f32, center_on_point: bool, ppp: f32) { + let before = xf.to_doc(p); + view.zoom = new_zoom; + if center_on_point { + view.center = [before[0] as f32, before[1] as f32]; + return; + } + // `new_zoom` is device px per document pixel; the pointer vector is in egui points. + let ppp = if ppp.is_finite() && ppp > 0.0 { ppp } else { 1.0 }; + let u = xf.unmap_vec((p - xf.rect.center()) / (new_zoom / ppp)); + view.center = [before[0] as f32 - u.x, before[1] as f32 - u.y]; +} diff --git a/crates/ui-egui/src/canvas/wheel_nav.rs b/crates/ui-egui/src/canvas/wheel_nav.rs new file mode 100644 index 0000000000..0d190a0633 --- /dev/null +++ b/crates/ui-egui/src/canvas/wheel_nav.rs @@ -0,0 +1,542 @@ +//! Mouse wheel and trackpad navigation over the canvas (#293, #635), as in Photoshop: +//! +//! - The wheel scrolls up and down; ⇧ or ⌘/Ctrl + wheel scrolls sideways. +//! - ⌥/Alt + wheel zooms around the pointer, 10% per wheel notch (eased or instant, see below). +//! ⇧/Shift + ⌥/Alt + wheel snaps to the next zoom ladder level instead. +//! - Preferences › General › Zoom with Scroll Wheel swaps the two: the wheel zooms and +//! ⌥/Alt + wheel scrolls; ⇧/Shift + wheel snaps to the next zoom ladder level. +//! - A trackpad pinch zooms around the pointer, unless Preferences › Enhanced Controls › +//! Zoom with Trackpad Pinch is off (then a pinch does nothing, and Windows' Ctrl + wheel +//! fractions scroll sideways like the wheel, because the fold below is skipped). +//! - A two-finger pinch on a touch screen zooms the same way, unless Preferences › Enhanced +//! Controls › Enable Gestures is off (#204): then the fingers leave the view alone, and a +//! trackpad pinch still zooms ([`pinch_factor`]). +//! +//! [`configure`] makes egui fold ⌘/Ctrl + wheel into a sideways scroll as it does ⇧ + wheel, so +//! only a real pinch (egui's `Event::Zoom`, or a touch screen) reaches `zoom_delta`. macOS and +//! browsers deliver a pinch as its own event, but Windows hands a precision touchpad pinch to apps +//! as Ctrl + wheel in fractions of a notch (also on some Linux Wayland systems): +//! [`fold_legacy_pinch`] turns those back into a pinch +//! before egui sees them, so Ctrl + a notched mouse wheel scrolls sideways and the pinch still +//! zooms. +//! +//! Either way a wheel notch zooms by exactly ×1.1 in total. How that step is spread over frames +//! is set by Preferences › General › Animated Zoom (`general.animatedZoom`, on by default): +//! +//! - On: the zoom is eased over several frames (the curve of egui's wheel smoothing, fed by the zoom +//! notches only), so the factors of the frames of one notch multiply to ×1.1. An unfinished notch +//! is superseded, not carried, when ⇧ snap zoom or a pan takes over or the pointer leaves. +//! - Off: one instant ×1.1 step per notch, applied the frame it arrives with no easing in between +//! (the Photoshop behaviour, measured frame by frame on a screen recording). Zooming reads the +//! wheel events themselves and ignores egui's smoothed tail. +//! +//! In both modes panning keeps the smoothed delta, and ⇧/Shift snap zoom reads the wheel events +//! and stays instant. The Alt state is taken from the wheel events (and the Alt key's own press +//! and release, `wheel_events`) and kept until the next wheel event: releasing Alt while the tail +//! is still settling must not turn it into a pan. + +use egui::{Context, Event, Id, InputState, Key, Modifiers, MouseWheelUnit, RawInput, TouchPhase, Vec2}; + +/// Zoom factor of one wheel notch: every step is exactly ×1.1. +pub const NOTCH: f32 = 1.1; + +/// A Ctrl + wheel event this soon (seconds) after a pinch step still belongs to the pinch, even +/// when it happens to be a whole notch. +const PINCH_GAP: f64 = 0.25; + +/// What the wheel does to the view this frame. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Wheel { + /// Multiply the zoom by this factor around the pointer. + Zoom(f32), + /// Step N rungs on the zoom ladder (positive = in, negative = out). + SnapZoom(i32), + /// Move the image by this many screen points (egui's content direction). + Pan(Vec2), +} + +/// Inputs of one frame's wheel gesture. +#[derive(Clone, Copy, Debug)] +pub struct Input { + /// Smoothed scroll delta (points, content direction); what panning uses. In the animated zoom + /// modes it is the eased zoom delta of that mode's own wheel events only. + pub scroll: Vec2, + /// This frame's wheel events for the gesture in progress, unsmoothed (points, content + /// direction); what the instant zoom and the snap zoom use. + pub raw: Vec2, + /// egui's pinch zoom factor (1 = none). + pub zoom_delta: f32, + /// ⌥/Alt was held for the wheel gesture in progress. + pub alt: bool, + /// ⇧/Shift was held for the wheel gesture in progress (snap zoom). + pub shift: bool, + /// Preferences › General › Zoom with Scroll Wheel. + pub zoom_with_wheel: bool, + /// Preferences › Enhanced Controls › Zoom with Trackpad Pinch. + pub pinch_zooms: bool, + /// Preferences › General › Animated Zoom: the wheel zoom follows the smoothed delta (`scroll`) + /// across frames; off, it is one instant step from this frame's wheel events (`raw`). + pub animated_zoom: bool, + /// Points per wheel notch (egui's `line_scroll_speed`). + pub notch: f32, +} + +/// The view change for one frame of wheel input, if any. +pub fn classify(i: Input) -> Option { + if i.pinch_zooms && i.zoom_delta.is_finite() && i.zoom_delta > 0.0 && i.zoom_delta != 1.0 { + return Some(Wheel::Zoom(i.zoom_delta)); + } + // One notch (`notch` points) is one ×1.1 step. + let step = |dy: f32| { + let notch = if i.notch.is_finite() && i.notch > 0.0 { i.notch } else { 40.0 }; + let f = NOTCH.powf(dy / notch); + (f.is_finite() && f > 0.0 && f != 1.0).then_some(Wheel::Zoom(f)) + }; + let snap = |dy: f32| { + if dy == 0.0 { + return None; + } + let notch = if i.notch.is_finite() && i.notch > 0.0 { i.notch } else { 40.0 }; + let n = dy / notch; + if !n.is_finite() { + return None; + } + let steps = n.clamp(-10.0, 10.0).round() as i32; + if steps == 0 { None } else { Some(Wheel::SnapZoom(steps)) } + }; + let scroll_finite = i.scroll.x.is_finite() && i.scroll.y.is_finite(); + match (i.alt, i.zoom_with_wheel) { + // ⇧ + ⌥ + scroll: snap to the zoom ladder instead of continuous ×1.1. + (true, false) if i.shift => snap(i.raw.y + i.raw.x), + // ⌥ + scroll: continuous ×1.1 zoom. Animated Zoom on: follow the smoothed delta across frames. + (true, false) if i.animated_zoom && scroll_finite => step(i.scroll.y + i.scroll.x), + // Animated Zoom off: one instant step from the wheel events. The smoothed tail is ignored. + (true, false) if !i.animated_zoom => step(i.raw.y + i.raw.x), + // ⇧ + scroll wheel with the preference on: snap to the zoom ladder. + // Some systems deliver Shift+wheel as horizontal (delta in x, y = 0). + (false, true) if i.shift => snap(i.raw.y + i.raw.x), + // ⌘/Ctrl folds the wheel into x: those still scroll sideways. + (false, true) if i.animated_zoom && scroll_finite && i.scroll.y != 0.0 => step(i.scroll.y), + (false, true) if !i.animated_zoom && (i.raw.y != 0.0 || i.scroll.y != 0.0) => step(i.raw.y), + _ if !scroll_finite || i.scroll == Vec2::ZERO => None, + _ => Some(Wheel::Pan(i.scroll)), + } +} + +/// Set egui's wheel modifiers (once, at setup): ⌘/Ctrl + wheel scrolls sideways like ⇧ + wheel +/// instead of zooming, everywhere in the app. +pub fn configure(ctx: &Context) { + ctx.options_mut(|o| { + o.input_options.zoom_modifier = Modifiers::NONE; + o.input_options.horizontal_scroll_modifier = Modifiers::SHIFT | Modifiers::COMMAND; + }); +} + +/// Turn a Windows or Linux touchpad pinch, which arrives as Ctrl + wheel in fractions of a notch or points, into +/// pinch events (`Event::Zoom`) at egui's Ctrl-scroll zoom speed (`notch` points per line, +/// `speed` per point). Ctrl + wheel in whole notches (a mouse wheel) is left to scroll sideways, +/// unless it comes within [`PINCH_GAP`] of a pinch step. `last` is the time of the previous pinch +/// step; returns the time of the latest one. +pub fn legacy_pinch_to_zoom(events: &mut [Event], now: f64, last: Option, notch: f32, speed: f32) -> Option { + let ctrl_wheel = |e: &Event| match e { + Event::MouseWheel { unit: MouseWheelUnit::Line, delta, modifiers, .. } if modifiers.ctrl => Some((*delta, false)), + // Wayland precision touchpads can use point units. These are already actual + // screen points, not line notches; normalize before the exponential below. + Event::MouseWheel { unit: MouseWheelUnit::Point, delta, modifiers, .. } if modifiers.ctrl => Some((*delta / notch.max(1.0), true)), + _ => None, + }; + let fraction = |d: Vec2| d.x.fract() != 0.0 || d.y.fract() != 0.0; + let pinching = + last.is_some_and(|t| (0.0..PINCH_GAP).contains(&(now - t))) || events.iter().filter_map(ctrl_wheel).any(|(d, high_res)| high_res || fraction(d)); + if !pinching { + return last; + } + let mut latest = last; + for e in events.iter_mut() { + if let Some((d, _)) = ctrl_wheel(e) { + let f = (speed * notch * (d.x + d.y)).exp(); + *e = Event::Zoom(if f.is_finite() && f > 0.0 { f } else { 1.0 }); + latest = Some(now); + } + } + latest +} + +fn pinch_id() -> Id { + Id::unique("pc-wheel-legacy-pinch") +} + +/// [`legacy_pinch_to_zoom`] for one frame's raw input (`raw_input_hook`, Windows and Linux). +pub fn fold_legacy_pinch(ctx: &Context, raw: &mut RawInput) { + // Native gesture events already carry their own magnification. Some backends + // also emit a Ctrl-wheel event in the same frame: folding that wheel event + // would apply the same pinch twice. End any legacy continuation as well, + // so a later real Ctrl+wheel notch isn't treated as part of that pinch. + if raw.events.iter().any(|event| matches!(event, Event::Zoom(_))) { + ctx.data_mut(|d| d.remove::(pinch_id())); + return; + } + let (notch, speed) = ctx.options(|o| (o.input_options.line_scroll_speed, o.input_options.scroll_zoom_speed)); + let now = raw.time.unwrap_or_else(|| ctx.input(|i| i.time)); + let last = ctx.data(|d| d.get_temp::(pinch_id())); + let latest = legacy_pinch_to_zoom(&mut raw.events, now, last, notch, speed); + if latest != last + && let Some(t) = latest + { + ctx.data_mut(|d| d.insert_temp(pinch_id(), t)); + } +} + +fn alt_id() -> Id { + Id::unique("pc-wheel-alt") +} + +fn shift_id() -> Id { + Id::unique("pc-wheel-shift") +} + +fn snap_residual_id(owner: Id) -> Id { + Id::unique("pc-wheel-snap-residual").with(owner) +} + +fn snap_time_id(owner: Id) -> Id { + Id::unique("pc-wheel-snap-time").with(owner) +} + +fn snap_frame_result_id(owner: Id) -> Id { + Id::unique("pc-wheel-snap-frame-result").with(owner) +} + +fn active_snap_owner_id() -> Id { + Id::unique("pc-wheel-active-snap-owner") +} + +const SNAP_IDLE_TIMEOUT: f64 = 0.5; + +/// egui's own wheel smoothing (`InputState::begin_pass`): 90 % of a notch is released in 0.1 s. +/// The eased zoom uses the same curve, so it paces like the eased pan. +const EASE_REACH: f32 = 0.90; +const EASE_REACH_SECS: f32 = 0.1; + +/// An unfinished eased notch belongs to the frames that follow it. It is dropped, never carried +/// into a later notch, once its owner was not driven for more than this many passes (the pointer +/// left the viewport, or another gesture took over there)... +const ZOOM_EASE_MAX_GAP_PASSES: u64 = 3; +/// ...or, when at least one pass was skipped, for this long (seconds). A single slow frame is +/// not a gap: the owner was driven in the pass right before it, so the notch still finishes. +const ZOOM_EASE_STALE_SECS: f64 = 0.5; + +#[derive(Clone, Copy)] +struct ZoomEase { + residual: f32, + time: f64, + frame: u64, + released: f32, +} + +fn zoom_ease_id(owner: Id) -> Id { + Id::unique(("wheel-zoom-ease", owner)) +} + +/// Eases `delta` (points of this viewport's zoom-mode wheel events) over the next frames and +/// returns what is released this frame. Same curve as egui's wheel smoothing, but fed by the +/// zoom notches only, so the tail of a pan notch never leaks in. What is released adds up to +/// exactly what was fed. A second call in the same frame returns the cached result. +fn ease_zoom_delta(ctx: &Context, owner: Id, delta: f32) -> f32 { + let id = zoom_ease_id(owner); + let frame = ctx.cumulative_pass_nr(); + let (now, dt) = ctx.input(|i| (i.time, i.stable_dt.min(0.1))); + let prev = ctx.data(|d| d.get_temp::(id)); + if let Some(e) = prev.filter(|e| e.frame == frame) { + return e.released; + } + // Fresh: driven in the previous pass (a slow frame, however long, keeps its notch), or within a + // few passes and a short time (a one-pass hover flicker). Anything older is stale. + let fresh = |e: &ZoomEase| { + let gap = frame.saturating_sub(e.frame); + e.residual.is_finite() && (gap <= 1 || (gap <= ZOOM_EASE_MAX_GAP_PASSES && now - e.time < ZOOM_EASE_STALE_SECS)) + }; + let carried = prev.filter(fresh).map_or(0.0, |e| e.residual); + let mut residual = carried + if delta.is_finite() { delta } else { 0.0 }; + let t = egui::emath::exponential_smooth_factor(EASE_REACH, EASE_REACH_SECS, dt); + let released = if residual.abs() < 1.0 { residual } else { t * residual }; + residual -= released; + ctx.data_mut(|d| d.insert_temp(id, ZoomEase { residual, time: now, frame, released })); + // Callers do not repaint on their own after consuming the zoom: keep frames coming until the + // notch has been fully released, or a reactive UI would stop below ×1.1. + if residual != 0.0 { + ctx.request_repaint(); + } + released +} + +/// A zoom limit stopped the eased zoom of `owner`: drop what is left of the notch. It would no +/// longer zoom, only cancel the first notch back (flick to 12800 %, and the notch back did +/// nothing). This frame's release stays cached, so a second read in the same frame is unchanged. +pub fn settle(ctx: &Context, owner: Id) { + let id = zoom_ease_id(owner); + ctx.data_mut(|d| { + if let Some(e) = d.get_temp::(id) { + d.insert_temp(id, ZoomEase { residual: 0.0, ..e }); + } + }); +} + +/// Whether a trackpad touch is in progress (egui's `InTouch`), at the start and at the end of a +/// frame: the start is kept, so every read in one frame sees the same states. +#[derive(Clone, Copy)] +struct Touch { + frame: u64, + at_start: bool, + at_end: bool, +} + +/// Per viewport, as egui keeps its wheel state per viewport. +fn touch_id(ctx: &Context) -> Id { + Id::unique(("wheel-nav-touch", ctx.viewport_id())) +} + +/// This frame's wheel events (in order) with, for each, whether egui leaves it unsmoothed: during a +/// trackpad touch, or a point delta under 8 points (`WheelState::on_wheel_event`). Those are +/// already smooth, and easing them again would only add latency; the rest (notches, and the +/// big pixel steps browsers report for a mouse wheel) is what Animated Zoom eases. +fn mark_unsmoothed(ctx: &Context, events: Vec<(MouseWheelUnit, Vec2, Modifiers, TouchPhase)>) -> Vec<(MouseWheelUnit, Vec2, Modifiers, bool)> { + let frame = ctx.cumulative_pass_nr(); + let (horizontal, vertical) = ctx.options(|o| (o.input_options.horizontal_scroll_modifier, o.input_options.vertical_scroll_modifier)); + // Not read in the previous pass (no canvas then): a touch could have ended unseen, and a + // stuck one would leave every later notch un-eased. + let id = touch_id(ctx); + let mut touch = match ctx.data(|d| d.get_temp::(id)) { + Some(t) if t.frame == frame => t.at_start, + Some(t) if t.frame.saturating_add(1) == frame => t.at_end, + _ => false, + }; + let at_start = touch; + let mut wheel = Vec::with_capacity(events.len()); + for (unit, delta, modifiers, phase) in events { + match phase { + TouchPhase::Start => touch = true, + TouchPhase::End | TouchPhase::Cancel => touch = false, + TouchPhase::Move => {} + } + // egui folds a scroll onto one axis by its modifiers before it measures the step. + let step = match (modifiers.matches_any(horizontal), modifiers.matches_any(vertical)) { + (true, false) | (false, true) => (delta.x + delta.y).abs(), + _ => delta.length(), + }; + let instant = touch || (unit == MouseWheelUnit::Point && step < 8.0); + wheel.push((unit, delta, modifiers, instant)); + } + ctx.data_mut(|d| d.insert_temp(id, Touch { frame, at_start, at_end: touch })); + wheel +} + +/// Read this frame's wheel input. Call it every frame (hovered or not) so the Alt and Shift +/// states of the gesture follow the latest wheel event. `owner` scopes the snap-zoom +/// accumulator per viewport. `hovered` gates accumulation: only the viewport receiving +/// navigation may add raw input to the snap residual. +pub fn read(ctx: &Context, zoom_with_wheel: bool, pinch_zooms: bool, animated_zoom: bool, owner: Id, hovered: bool) -> Option { + read_with(ctx, zoom_with_wheel, pinch_zooms, animated_zoom, owner, hovered, true, true) +} + +/// [`read`], choosing how a plain wheel scroll pans: `smooth` glides it over a few frames (egui's +/// smoothed delta); off, as with Interface › Enable Animations off, the view moves the whole notch +/// in the frame the wheel turns and stops there (#5721), as scroll areas already do. +/// `touch_gestures` is Preferences › Enhanced Controls › Enable Gestures: off, a touch screen's +/// two-finger pinch doesn't zoom ([`pinch_factor`]). +/// `animated_zoom` is Preferences › General › Animated Zoom: on, the wheel zoom is eased over the +/// frames of a notch; off, a notch is one instant ×1.1 step. +#[allow(clippy::too_many_arguments)] +pub fn read_with( + ctx: &Context, + zoom_with_wheel: bool, + pinch_zooms: bool, + animated_zoom: bool, + owner: Id, + hovered: bool, + smooth: bool, + touch_gestures: bool, +) -> Option { + let notch = ctx.options(|o| o.input_options.line_scroll_speed); + + // --- Modifier tracking (always runs for all callers) --- + let (scroll, zoom_delta, latest_alt, latest_shift, wheel, page) = ctx.input(|i| { + let wheel = wheel_events(i); + let latest_alt = wheel.last().map(|(_, _, m, _)| m.alt && !m.command && !m.ctrl); + let latest_shift = wheel.last().map(|(_, _, m, _)| m.shift && !m.command && !m.ctrl); + (i.smooth_scroll_delta, pinch_factor(i, touch_gestures), latest_alt, latest_shift, wheel, i.content_rect().height()) + }); + let wheel = mark_unsmoothed(ctx, wheel); + let alt = match latest_alt { + Some(a) => { + ctx.data_mut(|d| d.insert_temp(alt_id(), a)); + a + } + None => ctx.data(|d| d.get_temp::(alt_id())).unwrap_or(false), + }; + let shift = match latest_shift { + Some(s) => { + ctx.data_mut(|d| d.insert_temp(shift_id(), s)); + s + } + None => ctx.data(|d| d.get_temp::(shift_id())).unwrap_or(false), + }; + + if !hovered { + return None; + } + + // --- Input classification (hovered viewport only) --- + // The wheel events that belong to the gesture in progress: Shift+Alt (snap zoom), Alt-only + // (continuous zoom), Shift-only (snap zoom with zoom_with_wheel), or plain (scroll/zoom). + // `instant`: the part of `raw` egui leaves unsmoothed (a trackpad; see `wheel_events`). + let (raw, instant) = wheel + .iter() + .filter(|(_, _, m, _)| { + if alt && shift { + m.alt && m.shift && !m.command && !m.ctrl + } else if alt { + m.alt && !m.shift && !m.command && !m.ctrl + } else if shift { + m.shift && !m.alt && !m.command && !m.ctrl + } else { + !m.alt && !m.shift && !m.command && !m.ctrl + } + }) + .fold((Vec2::ZERO, Vec2::ZERO), |(sum, instant), (unit, delta, _, unsmoothed)| { + let d = *delta + * match unit { + MouseWheelUnit::Point => 1.0, + MouseWheelUnit::Line => notch, + MouseWheelUnit::Page => page, + }; + (sum + d, if *unsmoothed { instant + d } else { instant }) + }); + let snap_mode = shift && ((alt && !zoom_with_wheel) || (!alt && zoom_with_wheel)); + let has_pinch = pinch_zooms && zoom_delta.is_finite() && zoom_delta > 0.0 && zoom_delta != 1.0; + + if snap_mode && !has_pinch { + // Shift snap zoom takes over: drop this owner's unfinished eased notch, so a continuous + // zoom started shortly after Shift is released cannot carry its residual. + ctx.data_mut(|d| d.remove::(zoom_ease_id(owner))); + let dy = raw.y + raw.x; + if dy == 0.0 { + return None; + } + + // Per-frame idempotency: a second read in the same frame returns the cached result. + let frame_nr = ctx.cumulative_pass_nr(); + if let Some((cached_frame, cached_steps)) = ctx.data(|d| d.get_temp::<(u64, i32)>(snap_frame_result_id(owner))) + && cached_frame == frame_nr + { + return if cached_steps == 0 { None } else { Some(Wheel::SnapZoom(cached_steps)) }; + } + + // When the receiving viewport changes, clear the old viewport's residual so a + // partial gesture doesn't reappear when returning to it. + let prev_active = ctx.data(|d| d.get_temp::(active_snap_owner_id())); + if let Some(old) = prev_active.filter(|&p| p != owner) { + ctx.data_mut(|d| { + d.remove::(snap_residual_id(old)); + d.remove::(snap_time_id(old)); + }); + } + ctx.data_mut(|d| d.insert_temp(active_snap_owner_id(), owner)); + + let now = ctx.input(|i| i.time); + let last_time = ctx.data(|d| d.get_temp::(snap_time_id(owner))); + let prev = if last_time.is_some_and(|t| now - t < SNAP_IDLE_TIMEOUT && (now - t).is_finite()) { + ctx.data(|d| d.get_temp::(snap_residual_id(owner))).unwrap_or(0.0) + } else { + 0.0 + }; + let notch_val = if notch.is_finite() && notch > 0.0 { notch } else { 40.0 }; + let total = prev + dy; + let n = if total.is_finite() { (total / notch_val).trunc() } else { 0.0 }; + let remainder = total - n * notch_val; + let steps = n.clamp(-10.0, 10.0) as i32; + ctx.data_mut(|d| { + d.insert_temp(snap_residual_id(owner), if remainder.is_finite() { remainder } else { 0.0 }); + d.insert_temp(snap_time_id(owner), now); + d.insert_temp(snap_frame_result_id(owner), (frame_nr, steps)); + }); + if steps == 0 { None } else { Some(Wheel::SnapZoom(steps)) } + } else { + if !snap_mode { + ctx.data_mut(|d| { + d.remove::(snap_residual_id(owner)); + d.remove::(snap_time_id(owner)); + }); + } + // Zoom-mode input: ⌥ + wheel, or the plain wheel with Zoom with Scroll Wheel. With Animated + // Zoom on it eases from this mode's own wheel events: egui's smoothed delta has no notion of + // modifiers, so it would also carry the unfinished tail of a pan notch into the zoom. + let wheel_zooms = !shift && (alt != zoom_with_wheel); + let scroll = if animated_zoom && wheel_zooms { + // Eased as egui eases a wheel: what it leaves unsmoothed (a trackpad) zooms at once. + let along = |v: Vec2| if alt { v.y + v.x } else { v.y }; + let eased = ease_zoom_delta(ctx, owner, along(raw - instant)) + along(instant); + // The plain wheel zooms through `y`; its sideways part (⌘/Ctrl + wheel, a trackpad's + // horizontal scroll) is not a zoom event, so it pans like any scroll: smoothed, or + // with Enable Animations off at once (#5721). + if alt { Vec2::new(0.0, eased) } else { Vec2::new(if smooth { scroll.x } else { raw.x }, eased) } + } else { + ctx.data_mut(|d| d.remove::(zoom_ease_id(owner))); + // Unsmoothed, a plain scroll pans by this frame's own wheel events (none: no tail). + if smooth || alt || shift { scroll } else { raw } + }; + classify(Input { scroll, raw, zoom_delta, alt, shift, zoom_with_wheel, pinch_zooms, animated_zoom, notch }) + } +} + +fn is_alt_key(key: Key) -> bool { + matches!(key, Key::AltLeft | Key::AltRight) +} + +/// This frame's wheel events, in order, with ⌥/Alt added to their modifiers while an Alt key is +/// down (#8049). The modifiers a wheel event carries are the windowing layer's modifier state, +/// which on Windows can miss a held Alt (the wheel then scrolled until another modifier was +/// tapped), while the Alt key's own press and release still arrive; the menu bar follows those +/// too (`menu_keys`). Alt is down from its press until its release, starting from whether it +/// was down before this frame's first Alt key event (egui's `keys_down` when there is none). +fn wheel_events(i: &InputState) -> Vec<(MouseWheelUnit, Vec2, Modifiers, TouchPhase)> { + let first_alt_key = i.events.iter().find_map(|e| match e { + // A repeat means the key was already down; a release means it was down until then. + Event::Key { key, pressed, repeat, .. } if is_alt_key(*key) => Some(!*pressed || *repeat), + _ => None, + }); + let mut alt_key = first_alt_key.unwrap_or_else(|| i.key_down(Key::AltLeft) || i.key_down(Key::AltRight)); + let mut wheel = Vec::new(); + for e in &i.events { + match e { + Event::Key { key, pressed, .. } if is_alt_key(*key) => alt_key = *pressed, + Event::MouseWheel { unit, delta, phase, modifiers, .. } => { + let modifiers = Modifiers { alt: modifiers.alt || alt_key, ..*modifiers }; + wheel.push((*unit, *delta, modifiers, *phase)); + } + _ => {} + } + } + wheel +} + +/// This frame's pinch zoom factor (1 = none). While two fingers are down on a touch screen, egui's +/// `zoom_delta` reports their pinch in place of the trackpad's `Event::Zoom`. With Preferences › +/// Enhanced Controls › Enable Gestures off (`touch_gestures` false) the fingers are ignored and only +/// the trackpad's own pinch events count (Windows' Ctrl + wheel pinch included: [`fold_legacy_pinch`] +/// has already turned it into `Event::Zoom`). +pub fn pinch_factor(i: &InputState, touch_gestures: bool) -> f32 { + if touch_gestures || i.multi_touch().is_none() { + return i.zoom_delta(); + } + i.events + .iter() + .filter_map(|e| match e { + Event::Zoom(f) if f.is_finite() && *f > 0.0 => Some(*f), + _ => None, + }) + .product() +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/canvas/wheel_nav/tests.rs b/crates/ui-egui/src/canvas/wheel_nav/tests.rs new file mode 100644 index 0000000000..d2211a7daa --- /dev/null +++ b/crates/ui-egui/src/canvas/wheel_nav/tests.rs @@ -0,0 +1,1015 @@ +use egui::TouchPhase; + +use super::*; + +fn input(scroll: Vec2, alt: bool) -> Input { + Input { scroll, raw: scroll, zoom_delta: 1.0, alt, shift: false, zoom_with_wheel: false, pinch_zooms: true, animated_zoom: true, notch: 40.0 } +} + +fn wheel(delta: Vec2, modifiers: Modifiers) -> Event { + Event::MouseWheel { source: egui::MouseWheelSource::Unknown, unit: MouseWheelUnit::Line, delta, phase: TouchPhase::Move, modifiers } +} + +const CTRL: Modifiers = Modifiers { ctrl: true, command: true, ..Modifiers::NONE }; +const CMD: Modifiers = Modifiers { mac_cmd: true, command: true, ..Modifiers::NONE }; + +/// Feed `events` through an egui context set up like the app's (`legacy`: the Windows pinch +/// fold on) and add up what the wheel did to the view over the following second. +/// +/// `gesture` runs with Animated Zoom off (a notch is one instant step); see [`gesture_with`]. +fn gesture(frames: Vec>, zoom_with_wheel: bool, legacy: bool) -> (Vec2, f32, i32) { + gesture_with(frames, zoom_with_wheel, legacy, false) +} + +fn gesture_with(frames: Vec>, zoom_with_wheel: bool, legacy: bool, animated_zoom: bool) -> (Vec2, f32, i32) { + let owner = Id::unique("test-gesture"); + let ctx = Context::default(); + configure(&ctx); + let (mut pan, mut zoom, mut snaps) = (Vec2::ZERO, 1.0, 0i32); + let mut frames = frames.into_iter(); + for n in 0..60 { + let mut raw = RawInput { time: Some(f64::from(n) / 60.0), predicted_dt: 1.0 / 60.0, events: frames.next().unwrap_or_default(), ..Default::default() }; + if legacy { + fold_legacy_pinch(&ctx, &mut raw); + } + let mut out = ctx.run_ui(raw, |ui| match read(ui.ctx(), zoom_with_wheel, true, animated_zoom, owner, true) { + Some(Wheel::Pan(d)) => pan += d, + Some(Wheel::Zoom(f)) => zoom *= f, + Some(Wheel::SnapZoom(n)) => snaps += n, + None => {} + }); + out.textures_delta.clear(); + } + (pan, zoom, snaps) +} + +fn wheel_point(delta: Vec2, modifiers: Modifiers) -> Event { + Event::MouseWheel { source: egui::MouseWheelSource::Unknown, unit: MouseWheelUnit::Point, delta, phase: TouchPhase::Move, modifiers } +} + +fn near(a: Vec2, b: Vec2) -> bool { + (a - b).length() < 0.01 +} + +/// #5721: with smoothing off a wheel notch pans the whole notch in the frame it arrives and +/// nothing after; smoothed (the default) it glides, reaching the same total over later frames. +#[test] +fn unsmoothed_wheel_pans_at_once_without_a_glide() { + let pans = |smooth: bool| -> Vec { + let owner = Id::unique("test-unsmoothed"); + let ctx = Context::default(); + configure(&ctx); + (0..30) + .map(|n| { + let events = if n == 0 { vec![wheel(Vec2::new(0.0, -1.0), Modifiers::NONE)] } else { Vec::new() }; + let raw = RawInput { time: Some(f64::from(n) / 60.0), predicted_dt: 1.0 / 60.0, events, ..Default::default() }; + let mut pan = Vec2::ZERO; + let mut out = ctx.run_ui(raw, |ui| { + if let Some(Wheel::Pan(d)) = read_with(ui.ctx(), false, true, true, owner, true, smooth, true) { + pan = d; + } + }); + out.textures_delta.clear(); + pan + }) + .collect() + }; + let notch = { + let ctx = Context::default(); + configure(&ctx); + ctx.options(|o| o.input_options.line_scroll_speed) + }; + let direct = pans(false); + assert!(near(direct[0], Vec2::new(0.0, -notch)), "the whole notch at once: {:?}", direct[0]); + assert!(direct[1..].iter().all(|p| *p == Vec2::ZERO), "no glide after it"); + let smooth = pans(true); + assert!(smooth[0].y.abs() < notch - 0.5, "smoothed, the first frame moves only part of it: {:?}", smooth[0]); + assert!(smooth[1..].iter().any(|p| p.y != 0.0), "and the rest follows"); +} + +/// Interface › Enable Animations off only stops the *pan* gliding. A plain wheel that zooms +/// (Zoom with Scroll Wheel) with Animated Zoom on must still ease over the frames of a notch, +/// exactly as it does with the pan smoothing on. +#[test] +fn animated_wheel_zoom_keeps_its_eased_tail_when_pan_smoothing_is_off() { + let frames = |smooth: bool| -> Vec { + let owner = Id::unique("test-animated-zoom-unsmoothed-pan"); + let ctx = Context::default(); + configure(&ctx); + (0..60) + .map(|n| { + let events = if n == 0 { vec![wheel(Vec2::new(0.0, 1.0), Modifiers::NONE)] } else { Vec::new() }; + let raw = RawInput { time: Some(f64::from(n) / 60.0), predicted_dt: 1.0 / 60.0, events, ..Default::default() }; + let mut factor = 1.0; + let mut out = ctx.run_ui(raw, |ui| { + if let Some(Wheel::Zoom(f)) = read_with(ui.ctx(), true, true, true, owner, true, smooth, true) { + factor = f; + } + }); + out.textures_delta.clear(); + factor + }) + .collect() + }; + let unsmoothed = frames(false); + assert!(unsmoothed[0] > 1.0 && unsmoothed[0] < NOTCH - 1e-3, "the first frame carries only part of it: {:?}", &unsmoothed[..4]); + assert!(unsmoothed[1..].iter().any(|f| *f > 1.0), "and the rest follows: {unsmoothed:?}"); + let product: f32 = unsmoothed.iter().product(); + assert!((product - NOTCH).abs() < 1e-4, "still x1.1 in total: {product}"); + let smoothed = frames(true); + assert!(unsmoothed.iter().zip(&smoothed).all(|(a, b)| (a - b).abs() < 1e-6), "same pacing as with pan smoothing on"); +} + +#[test] +fn plain_scroll_pans() { + assert_eq!(classify(input(Vec2::new(3.0, -40.0), false)), Some(Wheel::Pan(Vec2::new(3.0, -40.0)))); + assert_eq!(classify(input(Vec2::ZERO, false)), None); +} + +#[test] +fn alt_scroll_zooms_ten_percent_per_notch() { + let Some(Wheel::Zoom(f)) = classify(input(Vec2::new(0.0, 40.0), true)) else { panic!("zoom") }; + assert!((f - 1.1).abs() < 1e-5, "{f}"); + let Some(Wheel::Zoom(f)) = classify(input(Vec2::new(0.0, -40.0), true)) else { panic!("zoom") }; + assert!((f - 1.0 / 1.1).abs() < 1e-5, "{f}"); + // Two notches in one frame are two steps, x1.1 each. + let Some(Wheel::Zoom(f)) = classify(input(Vec2::new(0.0, 80.0), true)) else { panic!("zoom") }; + assert!((f - 1.21).abs() < 1e-4, "{f}"); +} + +/// Animated Zoom off: a notch is one instant step, and egui's smoothed tail does nothing. +#[test] +fn a_notch_zooms_the_frame_it_arrives_and_its_smoothed_tail_does_nothing() { + // egui keeps feeding a smoothed delta for several frames after the wheel event. Zooming + // must not follow it (that would ease the zoom), nor turn it into a pan. + let off = |i: Input| Input { animated_zoom: false, ..i }; + let tail = off(Input { raw: Vec2::ZERO, ..input(Vec2::new(0.0, 12.0), true) }); + assert_eq!(classify(tail), None); + let tail = off(Input { raw: Vec2::ZERO, zoom_with_wheel: true, ..input(Vec2::new(0.0, 12.0), false) }); + assert_eq!(classify(tail), None); + // The frame the notch arrives carries it whole, whatever the smoothed delta is. + let arrival = off(Input { scroll: Vec2::new(0.0, 12.0), raw: Vec2::new(0.0, 40.0), ..input(Vec2::ZERO, true) }); + assert!(matches!(classify(arrival), Some(Wheel::Zoom(f)) if (f - 1.1).abs() < 1e-5)); + // Plain scrolling without the preference still pans from the smoothed delta. + let pan = off(Input { raw: Vec2::ZERO, ..input(Vec2::new(0.0, 12.0), false) }); + assert_eq!(classify(pan), Some(Wheel::Pan(Vec2::new(0.0, 12.0)))); +} + +/// Animated Zoom on: the zoom follows egui's smoothed delta over the frames of a notch, and +/// never turns that tail into a pan. +#[test] +fn animated_zoom_follows_the_smoothed_tail_of_a_notch() { + let tail = Input { raw: Vec2::ZERO, ..input(Vec2::new(0.0, 12.0), true) }; + assert!(matches!(classify(tail), Some(Wheel::Zoom(f)) if f > 1.0)); + let tail = Input { raw: Vec2::ZERO, zoom_with_wheel: true, ..input(Vec2::new(0.0, 12.0), false) }; + assert!(matches!(classify(tail), Some(Wheel::Zoom(f)) if f > 1.0)); + // The size of the step comes from the smoothed delta, not the raw one. + let part = Input { scroll: Vec2::new(0.0, 20.0), raw: Vec2::new(0.0, 40.0), ..input(Vec2::ZERO, true) }; + assert!(matches!(classify(part), Some(Wheel::Zoom(f)) if (f - 1.1f32.powf(0.5)).abs() < 1e-5)); + // Plain scrolling without the preference still pans from the smoothed delta. + let pan = Input { raw: Vec2::ZERO, ..input(Vec2::new(0.0, 12.0), false) }; + assert_eq!(classify(pan), Some(Wheel::Pan(Vec2::new(0.0, 12.0)))); + // ⇧ + snap zoom stays on the wheel events and instant, in both modes. + for animated_zoom in [false, true] { + let tail = Input { shift: true, zoom_with_wheel: true, raw: Vec2::ZERO, animated_zoom, ..input(Vec2::new(12.0, 0.0), false) }; + assert_eq!(classify(tail), None, "animated_zoom {animated_zoom}"); + let snap = Input { shift: true, zoom_with_wheel: true, raw: Vec2::new(0.0, 40.0), animated_zoom, ..input(Vec2::new(0.0, 12.0), false) }; + assert_eq!(classify(snap), Some(Wheel::SnapZoom(1)), "animated_zoom {animated_zoom}"); + } +} + +/// The factor of every frame of one notch, through a real egui context (60 frames at 60 fps). +fn zoom_frames(modifiers: Modifiers, zoom_with_wheel: bool, animated_zoom: bool) -> Vec { + let owner = Id::unique("test-zoom-frames"); + let ctx = Context::default(); + configure(&ctx); + (0..60) + .map(|n| { + let events = if n == 0 { vec![wheel(Vec2::new(0.0, 1.0), modifiers)] } else { Vec::new() }; + let raw = RawInput { time: Some(f64::from(n) / 60.0), predicted_dt: 1.0 / 60.0, events, ..Default::default() }; + let mut factor = 1.0; + let mut out = ctx.run_ui(raw, |ui| { + if let Some(Wheel::Zoom(f)) = read(ui.ctx(), zoom_with_wheel, true, animated_zoom, owner, true) { + factor = f; + } + }); + out.textures_delta.clear(); + factor + }) + .collect() +} + +/// The property the eased zoom relies on: however egui spreads a notch over frames, the +/// factors of those frames multiply to exactly ×1.1 (and ×1/1.1 for a notch the other way). +#[test] +fn the_eased_frames_of_one_notch_multiply_to_ten_percent() { + for (modifiers, zoom_with_wheel) in [(Modifiers::ALT, false), (Modifiers::NONE, true)] { + let frames = zoom_frames(modifiers, zoom_with_wheel, true); + assert!(frames.iter().all(|f| f.is_finite() && *f >= 1.0), "{frames:?}"); + assert!(frames.iter().filter(|f| **f != 1.0).count() > 1, "eased over several frames: {frames:?}"); + let product: f32 = frames.iter().product(); + assert!((product - NOTCH).abs() < 1e-4, "{modifiers:?} zoom_with_wheel {zoom_with_wheel}: {product} from {frames:?}"); + } + // The other way round: ×1/1.1. + let owner = Id::unique("test-zoom-frames-out"); + let ctx = Context::default(); + configure(&ctx); + let mut product = 1.0f32; + for n in 0..60 { + let events = if n == 0 { vec![wheel(Vec2::new(0.0, -1.0), Modifiers::ALT)] } else { Vec::new() }; + let raw = RawInput { time: Some(f64::from(n) / 60.0), predicted_dt: 1.0 / 60.0, events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + if let Some(Wheel::Zoom(f)) = read(ui.ctx(), false, true, true, owner, true) { + product *= f; + } + }); + out.textures_delta.clear(); + } + assert!((product - 1.0 / NOTCH).abs() < 1e-4, "{product}"); +} + +/// Animated Zoom changes the pacing of a notch, never its size: off, the whole ×1.1 lands in +/// the frame the notch arrives and nothing follows; on, that frame carries only part of it. +#[test] +fn animated_zoom_changes_the_pacing_of_a_notch_not_its_size() { + for (modifiers, zoom_with_wheel) in [(Modifiers::ALT, false), (Modifiers::NONE, true)] { + let instant = zoom_frames(modifiers, zoom_with_wheel, false); + assert!((instant[0] - NOTCH).abs() < 1e-5, "the whole notch at once: {:?}", &instant[..4]); + assert!(instant[1..].iter().all(|f| *f == 1.0), "no tail after it: {instant:?}"); + let eased = zoom_frames(modifiers, zoom_with_wheel, true); + assert!(eased[0] > 1.0 && eased[0] < NOTCH - 1e-3, "the first frame carries only part of it: {:?}", &eased[..4]); + assert!(eased[1..].iter().any(|f| *f > 1.0), "and the rest follows"); + } +} + +/// Animated Zoom is only about the wheel zoom: ⇧ snap zoom and plain scrolling are the same +/// in both modes. +#[test] +fn animated_zoom_leaves_snap_zoom_and_panning_alone() { + let notch = Vec2::new(0.0, 1.0); + let shift_alt = Modifiers { shift: true, alt: true, ..Modifiers::NONE }; + for animated_zoom in [false, true] { + let (pan, zoom, snaps) = gesture_with(vec![vec![wheel(notch, shift_alt)]], false, false, animated_zoom); + assert!(pan == Vec2::ZERO && zoom == 1.0 && snaps == 1, "⇧ + ⌥: {pan:?} {zoom} {snaps}"); + let (pan, zoom, snaps) = gesture_with(vec![vec![wheel(notch, Modifiers::NONE)]], false, false, animated_zoom); + assert!(near(pan, Vec2::new(0.0, 40.0)) && zoom == 1.0 && snaps == 0, "plain wheel pans: {pan:?} {zoom} {snaps}"); + // A notch zooms ×1.1 in total in either mode. + let (pan, zoom, _) = gesture_with(vec![vec![wheel(notch, Modifiers::ALT)]], false, false, animated_zoom); + assert!(pan == Vec2::ZERO && (zoom - NOTCH).abs() < 1e-4, "animated_zoom {animated_zoom}: {pan:?} {zoom}"); + } +} + +/// A pan notch still gliding when an ⌥ notch arrives (and the same the other way round with +/// Zoom with Scroll Wheel): the zoom is that one notch's ×1.1, not the sum of both tails. +#[test] +fn a_pan_tail_does_not_leak_into_the_animated_zoom() { + let notch = Vec2::new(0.0, 1.0); + // Wheel pans, ⌥ zooms: plain notch, then ⌥ notch one frame later. + let frames = vec![vec![wheel(notch, Modifiers::NONE)], vec![wheel(notch, Modifiers::ALT)]]; + let (pan, zoom, snaps) = gesture_with(frames, false, false, true); + assert!((zoom - NOTCH).abs() < 1e-4, "only the ⌥ notch zooms: {zoom}"); + assert!(pan.y > 0.0 && pan.y < 40.0 && snaps == 0, "the plain notch only panned its first frame: {pan:?} {snaps}"); + // Wheel zooms, ⌥ pans: ⌥ notch, then plain notch. + let frames = vec![vec![wheel(notch, Modifiers::ALT)], vec![wheel(notch, Modifiers::NONE)]]; + let (_, zoom, snaps) = gesture_with(frames, true, false, true); + assert!((zoom - NOTCH).abs() < 1e-4, "only the plain notch zooms: {zoom}"); + assert_eq!(snaps, 0); +} + +/// The zoom factor of each of `frames` frames with Animated Zoom on and ⌥ zooming. `time` gives a +/// frame's timestamp and `hovered` whether the owner is hovered in it. +fn run_zoom(frames: u32, events: impl Fn(u32) -> Vec, time: impl Fn(u32) -> f64, hovered: impl Fn(u32) -> bool) -> Vec { + let owner = Id::unique("test-run-zoom"); + let ctx = Context::default(); + configure(&ctx); + (0..frames) + .map(|n| { + let raw = RawInput { time: Some(time(n)), predicted_dt: 1.0 / 60.0, events: events(n), ..Default::default() }; + let mut factor = 1.0; + let mut out = ctx.run_ui(raw, |ui| { + if let Some(Wheel::Zoom(f)) = read(ui.ctx(), false, true, true, owner, hovered(n)) { + factor = f; + } + }); + out.textures_delta.clear(); + factor + }) + .collect() +} + +/// A slow frame in the middle of an eased notch (a big image redrawing) must not drop what is +/// left of it: the notch still adds up to exactly ×1.1. +#[test] +fn a_slow_frame_does_not_cut_an_eased_notch_short() { + let notch = Vec2::new(0.0, 1.0); + let time = |n: u32| if n == 0 { 0.0 } else { 0.7 + f64::from(n - 1) / 60.0 }; + let frames = run_zoom(60, |n| if n == 0 { vec![wheel(notch, Modifiers::ALT)] } else { Vec::new() }, time, |_| true); + let product: f32 = frames.iter().product(); + assert!((product - NOTCH).abs() < 1e-4, "still x1.1 in total: {product} from {frames:?}"); +} + +/// What is left of an eased notch when the pointer leaves the viewport is dropped: a notch +/// made after it comes back is ×1.1 on its own, not ×1.1 plus the old remainder. +#[test] +fn an_unfinished_notch_is_not_carried_into_a_notch_after_the_pointer_left() { + let notch = Vec2::new(0.0, 1.0); + let events = |n: u32| if n == 0 || n == 40 { vec![wheel(notch, Modifiers::ALT)] } else { Vec::new() }; + let frames = run_zoom(100, events, |n| f64::from(n) / 60.0, |n| !(1..30).contains(&n)); + let first: f32 = frames[..40].iter().product(); + assert!(first > 1.0 && first < NOTCH - 1e-3, "the first notch was left unfinished: {first}"); + let second: f32 = frames[40..].iter().product(); + assert!((second - NOTCH).abs() < 1e-4, "the second notch is ×1.1 on its own: {second}"); +} + +/// Zoom with Scroll Wheel + Animated Zoom (the defaults of both): ⌘/Ctrl + wheel still scrolls +/// sideways, as it does with Animated Zoom off. +#[test] +fn animated_zoom_keeps_ctrl_wheel_sideways_scroll_with_zoom_with_wheel() { + let (pan, zoom, snaps) = gesture_with(vec![vec![wheel(Vec2::new(0.0, 1.0), CTRL)]], true, false, true); + assert!(near(pan, Vec2::new(40.0, 0.0)) && zoom == 1.0 && snaps == 0, "{pan:?} {zoom} {snaps}"); +} + +/// Shift snap zoom interrupting an unfinished animated notch drops that notch's residual: a +/// continuous zoom started right after Shift is released is its own ×1.1 and nothing more. +#[test] +fn shift_snap_zoom_drops_the_unfinished_eased_notch() { + let notch = Vec2::new(0.0, 1.0); + let shift_alt = Modifiers { shift: true, ..Modifiers::ALT }; + let owner = Id::unique("test-snap-interrupts-ease"); + let ctx = Context::default(); + configure(&ctx); + let (mut zoom, mut zoom_after_first, mut snaps) = (1.0f32, 1.0f32, 0i32); + for n in 0..60u32 { + // ⌥ notch (eases), ⇧⌥ notch (snap zoom takes over), then ⌥ notch again within 0.5 s. + let events = match n { + 0 | 2 => vec![wheel(notch, Modifiers::ALT)], + 1 => vec![wheel(notch, shift_alt)], + _ => Vec::new(), + }; + let raw = RawInput { time: Some(f64::from(n) / 60.0), predicted_dt: 1.0 / 60.0, events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| match read(ui.ctx(), false, true, true, owner, true) { + Some(Wheel::Zoom(f)) => zoom *= f, + Some(Wheel::SnapZoom(s)) => snaps += s, + _ => {} + }); + out.textures_delta.clear(); + if n == 0 { + zoom_after_first = zoom; + } + } + assert_eq!(snaps, 1); + let second = zoom / zoom_after_first; + assert!((second - NOTCH).abs() < 1e-4, "the second ⌥ notch zooms ×1.1 on its own: {second}"); +} + +/// A trackpad's ⌥ + two-finger scroll comes in points and is already smooth: egui leaves it +/// unsmoothed because smoothing adds latency, so Animated Zoom must not ease it either. Each +/// frame zooms by its own events, at once. +#[test] +fn animated_zoom_does_not_ease_a_trackpad() { + let frames = run_zoom(30, |n| if n == 0 { vec![wheel_point(Vec2::new(0.0, 4.0), Modifiers::ALT)] } else { Vec::new() }, |n| f64::from(n) / 60.0, |_| true); + assert!((frames[0] - NOTCH.powf(0.1)).abs() < 1e-6, "all of it in the frame it arrives: {:?}", &frames[..4]); + assert!(frames[1..].iter().all(|f| *f == 1.0), "no tail after it: {frames:?}"); +} + +/// Zoom with Scroll Wheel + Animated Zoom with Enable Animations off: the wheel zooms eased, but +/// a sideways wheel still pans without a glide (#5721), all of it in the frame it turns. +#[test] +fn animated_zoom_keeps_the_sideways_wheel_unsmoothed_with_animations_off() { + let owner = Id::unique("test-sideways-unsmoothed"); + let ctx = Context::default(); + configure(&ctx); + let pans: Vec = (0..30) + .map(|n| { + let events = if n == 0 { vec![wheel(Vec2::new(1.0, 0.0), Modifiers::NONE)] } else { Vec::new() }; + let raw = RawInput { time: Some(f64::from(n) / 60.0), predicted_dt: 1.0 / 60.0, events, ..Default::default() }; + let mut pan = Vec2::ZERO; + let mut out = ctx.run_ui(raw, |ui| { + if let Some(Wheel::Pan(d)) = read_with(ui.ctx(), true, true, true, owner, true, false, true) { + pan = d; + } + }); + out.textures_delta.clear(); + pan + }) + .collect(); + assert!(near(pans[0], Vec2::new(40.0, 0.0)), "the whole notch at once: {:?}", &pans[..4]); + assert!(pans[1..].iter().all(|p| *p == Vec2::ZERO), "no glide after it: {pans:?}"); +} + +/// A diagonal point step with ⌥ is measured as egui measures it, folded onto one axis: (5, 5) +/// is a 10-point step, which egui smooths, so Animated Zoom eases it. +#[test] +fn a_diagonal_alt_point_step_is_measured_like_egui() { + let frames = run_zoom(60, |n| if n == 0 { vec![wheel_point(Vec2::new(5.0, 5.0), Modifiers::ALT)] } else { Vec::new() }, |n| f64::from(n) / 60.0, |_| true); + assert!(frames[0] < NOTCH.powf(0.25) - 1e-4 && frames[1] > 1.0, "eased: {:?}", &frames[..4]); +} + +/// A touch whose end nobody read (no canvas in that pass, e.g. the last document closed +/// during a trackpad scroll) must not leave later mouse notches un-eased. +#[test] +fn a_touch_end_nobody_read_does_not_stick() { + let owner = Id::unique("test-touch-unread-end"); + let ctx = Context::default(); + configure(&ctx); + let point = |phase: TouchPhase| Event::MouseWheel { + source: egui::MouseWheelSource::Unknown, + unit: MouseWheelUnit::Point, + delta: Vec2::ZERO, + phase, + modifiers: Modifiers::ALT, + }; + let mut first = 1.0; + for n in 0..10u32 { + let events = match n { + 0 => vec![point(TouchPhase::Start)], + 2 => vec![point(TouchPhase::End)], + 5 => vec![wheel(Vec2::new(0.0, 1.0), Modifiers::ALT)], + _ => Vec::new(), + }; + let raw = RawInput { time: Some(f64::from(n) / 60.0), predicted_dt: 1.0 / 60.0, events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + // Frames 2-3: nothing reads the wheel. + if !(2..4).contains(&n) + && let Some(Wheel::Zoom(f)) = read(ui.ctx(), false, true, true, owner, true) + && n == 5 + { + first = f; + } + }); + out.textures_delta.clear(); + } + assert!(first > 1.0 && first < NOTCH - 1e-3, "the notch is eased: {first}"); +} + +/// Quick back-and-forth wheeling still lands on whole ×1.1 steps: three notches in and one +/// out a frame later is ×1.1², whatever was still easing. +#[test] +fn a_quick_notch_back_nets_out() { + for back_at in [1, 3] { + let events = |n: u32| match n { + 0 => vec![wheel(Vec2::new(0.0, 3.0), Modifiers::ALT)], + n if n == back_at => vec![wheel(Vec2::new(0.0, -1.0), Modifiers::ALT)], + _ => Vec::new(), + }; + let total: f32 = run_zoom(60, events, |n| f64::from(n) / 60.0, |_| true).iter().product(); + assert!((total - NOTCH * NOTCH).abs() < 1e-4, "back at frame {back_at}: {total}"); + } +} + +/// A browser reports a mouse notch as a big pixel step (about 100 points in Chrome), which +/// egui smooths like a notch: Animated Zoom eases it too. Within a trackpad touch (egui's +/// `InTouch`) even big point steps zoom at once. +#[test] +fn animated_zoom_eases_big_pixel_steps_but_not_a_touch() { + let point = |dy: f32, phase: TouchPhase| Event::MouseWheel { + source: egui::MouseWheelSource::Unknown, + unit: MouseWheelUnit::Point, + delta: Vec2::new(0.0, dy), + phase, + modifiers: Modifiers::ALT, + }; + let browser = run_zoom(60, |n| if n == 0 { vec![point(100.0, TouchPhase::Move)] } else { Vec::new() }, |n| f64::from(n) / 60.0, |_| true); + assert!(browser[0] > 1.0 && browser[0] < NOTCH.powf(2.5) - 1e-3, "eased: {:?}", &browser[..4]); + let total: f32 = browser.iter().product(); + assert!((total - NOTCH.powf(2.5)).abs() < 1e-3, "{total}"); + let events = |n: u32| match n { + 0 => vec![point(0.0, TouchPhase::Start)], + 1 => vec![point(20.0, TouchPhase::Move)], + _ => Vec::new(), + }; + let touch = run_zoom(30, events, |n| f64::from(n) / 60.0, |_| true); + assert!((touch[1] - NOTCH.powf(0.5)).abs() < 1e-5, "at once: {:?}", &touch[..4]); + assert!(touch[2..].iter().all(|f| *f == 1.0), "no tail: {touch:?}"); +} + +#[test] +fn pinch_zooms() { + let i = Input { zoom_delta: 1.2, ..input(Vec2::ZERO, false) }; + assert_eq!(classify(i), Some(Wheel::Zoom(1.2))); + // The pinch wins over Alt. + let i = Input { zoom_delta: 0.8, ..input(Vec2::new(0.0, 40.0), true) }; + assert_eq!(classify(i), Some(Wheel::Zoom(0.8))); +} + +/// Preferences › Enhanced Controls › Zoom with Trackpad Pinch off: the pinch is ignored, and +/// a scroll in the same frame pans as it would without a pinch. +#[test] +fn the_pinch_preference_switches_pinch_zooming() { + let i = Input { zoom_delta: 1.2, pinch_zooms: false, ..input(Vec2::ZERO, false) }; + assert_eq!(classify(i), None); + let i = Input { zoom_delta: 1.2, pinch_zooms: false, ..input(Vec2::new(0.0, 12.0), false) }; + assert_eq!(classify(i), Some(Wheel::Pan(Vec2::new(0.0, 12.0)))); + // On (the default) the pinch still zooms. + let i = Input { zoom_delta: 1.2, pinch_zooms: true, ..input(Vec2::ZERO, false) }; + assert_eq!(classify(i), Some(Wheel::Zoom(1.2))); +} + +/// The Windows pinch fold follows the preference too: off, the Ctrl + wheel fractions stay +/// wheel events (which egui folds into a sideways scroll). +#[test] +fn the_windows_pinch_fold_follows_the_preference() { + use eframe::App as _; + if !cfg!(target_os = "windows") { + return; + } + let mut app = crate::PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = Context::default(); + let event = || Event::MouseWheel { + unit: MouseWheelUnit::Line, + delta: egui::vec2(0.0, 0.25), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, + modifiers: Modifiers { ctrl: true, command: true, ..Modifiers::NONE }, + }; + let mut raw = RawInput { time: Some(1.0), events: vec![event()], ..Default::default() }; + app.raw_input_hook(&ctx, &mut raw); + assert!(matches!(raw.events[0], Event::Zoom(_)), "the fraction is a pinch: {:?}", raw.events[0]); + app.run("prefs.set", serde_json::json!({"path": "enhancedControls.zoomWithTrackpadPinch", "value": false})).unwrap(); + let mut raw = RawInput { time: Some(2.0), events: vec![event()], ..Default::default() }; + app.raw_input_hook(&ctx, &mut raw); + assert!(matches!(raw.events[0], Event::MouseWheel { .. }), "off: it stays a wheel event: {:?}", raw.events[0]); +} + +#[test] +fn zoom_with_scroll_wheel_preference_swaps_wheel_and_alt_wheel() { + let pref = |scroll, alt| Input { zoom_with_wheel: true, ..input(scroll, alt) }; + let Some(Wheel::Zoom(f)) = classify(pref(Vec2::new(0.0, 40.0), false)) else { panic!("zoom") }; + assert!((f - 1.1).abs() < 1e-5, "{f}"); + assert_eq!(classify(pref(Vec2::new(0.0, 40.0), true)), Some(Wheel::Pan(Vec2::new(0.0, 40.0))), "⌥ + wheel scrolls"); + assert_eq!(classify(pref(Vec2::new(40.0, 0.0), false)), Some(Wheel::Pan(Vec2::new(40.0, 0.0))), "sideways still scrolls"); +} + +#[test] +fn shift_scroll_snaps_to_zoom_ladder_with_preference() { + let snap = |dy: f32| Input { shift: true, zoom_with_wheel: true, ..input(Vec2::new(0.0, dy), false) }; + assert_eq!(classify(snap(40.0)), Some(Wheel::SnapZoom(1)), "one notch up → +1 step"); + assert_eq!(classify(snap(-40.0)), Some(Wheel::SnapZoom(-1)), "one notch down → −1 step"); + assert_eq!(classify(snap(80.0)), Some(Wheel::SnapZoom(2)), "two notches → +2 steps"); + assert_eq!(classify(snap(0.0)), None, "no scroll → nothing"); + // Some systems deliver Shift+wheel as horizontal (delta in x, y = 0). + let snap_h = |dx: f32| Input { shift: true, zoom_with_wheel: true, raw: Vec2::new(dx, 0.0), ..input(Vec2::new(dx, 0.0), false) }; + assert_eq!(classify(snap_h(40.0)), Some(Wheel::SnapZoom(1)), "horizontal notch → +1 step"); + assert_eq!(classify(snap_h(-40.0)), Some(Wheel::SnapZoom(-1)), "horizontal notch down → −1 step"); +} + +#[test] +fn shift_scroll_tail_does_not_snap_or_pan() { + let tail = Input { shift: true, zoom_with_wheel: true, raw: Vec2::ZERO, ..input(Vec2::new(12.0, 0.0), false) }; + assert_eq!(classify(tail), None, "smoothed tail of ⇧ + scroll produces nothing"); +} + +#[test] +fn shift_alt_scroll_snaps_without_preference() { + let snap = |dy: f32| Input { shift: true, ..input(Vec2::new(0.0, dy), true) }; + assert_eq!(classify(snap(40.0)), Some(Wheel::SnapZoom(1)), "⇧ + ⌥ + notch up → +1 step"); + assert_eq!(classify(snap(-40.0)), Some(Wheel::SnapZoom(-1)), "⇧ + ⌥ + notch down → −1 step"); + assert_eq!(classify(snap(0.0)), None, "no scroll → nothing"); +} + +#[test] +fn shift_only_without_zoom_with_wheel_does_not_snap() { + let i = Input { shift: true, zoom_with_wheel: false, ..input(Vec2::new(0.0, 40.0), false) }; + assert_eq!(classify(i), Some(Wheel::Pan(Vec2::new(0.0, 40.0))), "⇧ alone without the preference: no zoom"); +} + +#[test] +fn shift_scroll_snaps_through_egui_context() { + let notch = Vec2::new(0.0, 1.0); + // Shift + wheel with zoom_with_wheel on. + let (pan, zoom, snaps) = gesture(vec![vec![wheel(notch, Modifiers::SHIFT)]], true, false); + assert_eq!(snaps, 1, "⇧ + wheel with zoom_with_wheel → snap"); + assert!(pan == Vec2::ZERO, "no pan: {pan:?}"); + assert_eq!(zoom, 1.0, "no continuous zoom: {zoom}"); + let (_, _, snaps) = gesture(vec![vec![wheel(-notch, Modifiers::SHIFT)]], true, false); + assert_eq!(snaps, -1, "⇧ + wheel down → snap out"); + // Some systems deliver Shift+wheel as horizontal (delta in x, y = 0). + let h_notch = Vec2::new(1.0, 0.0); + let (pan, zoom, snaps) = gesture(vec![vec![wheel(h_notch, Modifiers::SHIFT)]], true, false); + assert_eq!(snaps, 1, "⇧ + horizontal wheel with zoom_with_wheel → snap"); + assert!(pan == Vec2::ZERO, "no pan: {pan:?}"); + assert_eq!(zoom, 1.0, "no continuous zoom: {zoom}"); + // Shift + Alt + wheel without the preference. + let shift_alt = Modifiers { shift: true, alt: true, ..Modifiers::NONE }; + let (pan, zoom, snaps) = gesture(vec![vec![wheel(notch, shift_alt)]], false, false); + assert_eq!(snaps, 1, "⇧ + ⌥ + wheel → snap"); + assert!(pan == Vec2::ZERO, "no pan: {pan:?}"); + assert_eq!(zoom, 1.0, "no continuous zoom: {zoom}"); +} + +#[test] +fn each_modifier_maps_like_photoshop() { + let notch = Vec2::new(0.0, 1.0); + let one = |m: Modifiers| gesture(vec![vec![wheel(notch, m)]], false, false); + let (pan, zoom, _) = one(Modifiers::NONE); + assert!(near(pan, Vec2::new(0.0, 40.0)) && zoom == 1.0, "wheel scrolls vertically: {pan:?} {zoom}"); + for m in [Modifiers::SHIFT, CTRL, CMD, Modifiers::CTRL] { + let (pan, zoom, _) = one(m); + assert!(near(pan, Vec2::new(40.0, 0.0)) && zoom == 1.0, "{m:?} + wheel scrolls sideways: {pan:?} {zoom}"); + } + let (pan, zoom, _) = one(Modifiers::ALT); + assert!(pan == Vec2::ZERO && (zoom - 1.1).abs() < 1e-4, "⌥ + wheel zooms 10%, at once: {pan:?} {zoom}"); + // Zoom with Scroll Wheel on: swapped. + let (pan, zoom, _) = gesture(vec![vec![wheel(notch, Modifiers::ALT)]], true, false); + assert!(near(pan, Vec2::new(0.0, 40.0)) && zoom == 1.0, "{pan:?} {zoom}"); + let (pan, zoom, _) = gesture(vec![vec![wheel(notch, Modifiers::NONE)]], true, false); + assert!(pan == Vec2::ZERO && (zoom - 1.1).abs() < 1e-4, "{pan:?} {zoom}"); + let (pan, zoom, _) = gesture(vec![vec![wheel(notch, CTRL)]], true, false); + assert!(near(pan, Vec2::new(40.0, 0.0)) && zoom == 1.0, "⌘/Ctrl + wheel still scrolls sideways: {pan:?} {zoom}"); +} + +#[test] +fn pinch_zooms_and_ctrl_wheel_pans() { + // macOS trackpad and browsers: the pinch is its own event. + let (pan, zoom, _) = gesture(vec![vec![Event::Zoom(1.1)], vec![Event::Zoom(1.1)]], false, false); + assert!(pan == Vec2::ZERO && (zoom - 1.21).abs() < 1e-4, "{pan:?} {zoom}"); + // Windows: a touchpad pinch is Ctrl + wheel in fractions of a notch, a mouse wheel whole notches. + let (pan, zoom, _) = gesture(vec![vec![wheel(Vec2::new(0.0, 0.25), CTRL)], vec![wheel(Vec2::new(0.0, 0.5), CTRL)]], false, true); + let speed = egui::InputOptions::default().scroll_zoom_speed; + assert!(pan == Vec2::ZERO && (zoom - (speed * 40.0 * 0.75).exp()).abs() < 1e-4, "the pinch zooms: {pan:?} {zoom}"); + let (pan, zoom, _) = gesture(vec![vec![wheel(Vec2::new(0.0, 1.0), CTRL)]], false, true); + assert!(near(pan, Vec2::new(40.0, 0.0)) && zoom == 1.0, "Ctrl + mouse wheel scrolls sideways: {pan:?} {zoom}"); +} + +#[test] +fn linux_wayland_point_unit_pinch_keeps_mouse_notches_for_sideways_scroll() { + // Some Wayland compositors report fractional Ctrl-wheel pinch steps in points + // rather than line units. The delta must not be multiplied by notch twice. + let mut point = [Event::MouseWheel { + source: egui::MouseWheelSource::Unknown, + unit: MouseWheelUnit::Point, + delta: Vec2::new(0.0, 8.0), + phase: TouchPhase::Move, + modifiers: CTRL, + }]; + assert_eq!(legacy_pinch_to_zoom(&mut point, 1.0, None, 40.0, 0.005), Some(1.0)); + assert!(matches!(point[0], Event::Zoom(f) if (f - (8.0f32 * 0.005).exp()).abs() < 1e-5)); + let mut wheel_only = [wheel(Vec2::new(0.0, 1.0), CTRL)]; + assert_eq!(legacy_pinch_to_zoom(&mut wheel_only, 2.0, Some(1.0), 40.0, 0.005), Some(1.0)); + assert!(matches!(wheel_only[0], Event::MouseWheel { .. }), "whole mouse notch is not a pinch"); +} + +#[test] +fn native_pinch_is_not_zoomed_twice_when_ctrl_wheel_arrives_in_the_same_frame() { + let (_, zoom, _) = gesture(vec![vec![Event::Zoom(1.2), wheel(Vec2::new(0.0, 0.25), CTRL)]], false, true); + assert!((zoom - 1.2).abs() < 1e-4, "native zoom must win over fallback: {zoom}"); +} + +#[test] +fn native_pinch_resets_legacy_gesture_continuation() { + let ctx = Context::default(); + let mut legacy = RawInput { time: Some(1.0), events: vec![wheel(Vec2::new(0.0, 0.25), CTRL)], ..Default::default() }; + fold_legacy_pinch(&ctx, &mut legacy); + assert!(matches!(legacy.events[0], Event::Zoom(_))); + + // Native magnification takes over before the synthetic gesture times out. + let mut native = RawInput { time: Some(1.1), events: vec![Event::Zoom(1.1), wheel(Vec2::new(0.0, 0.25), CTRL)], ..Default::default() }; + fold_legacy_pinch(&ctx, &mut native); + assert!(matches!(native.events[0], Event::Zoom(f) if (f - 1.1).abs() < 1e-5)); + assert!(matches!(native.events[1], Event::MouseWheel { .. })); + + // A notched mouse scroll must no longer inherit the previous pinch. + let mut notch = RawInput { time: Some(1.12), events: vec![wheel(Vec2::new(0.0, 1.0), CTRL)], ..Default::default() }; + fold_legacy_pinch(&ctx, &mut notch); + assert!(matches!(notch.events[0], Event::MouseWheel { .. })); +} + +#[test] +fn a_whole_notch_inside_a_pinch_stays_a_pinch() { + let mut ev = [wheel(Vec2::new(0.0, 0.5), CTRL)]; + let t = legacy_pinch_to_zoom(&mut ev, 1.0, None, 40.0, 0.005); + assert_eq!(t, Some(1.0)); + assert!(matches!(ev[0], Event::Zoom(f) if (f - 0.1f32.exp()).abs() < 1e-5), "{ev:?}"); + // The next step lands on a whole notch: still the pinch. + let mut ev = [wheel(Vec2::new(0.0, -1.0), CTRL)]; + assert_eq!(legacy_pinch_to_zoom(&mut ev, 1.1, t, 40.0, 0.005), Some(1.1)); + assert!(matches!(ev[0], Event::Zoom(f) if f < 1.0), "{ev:?}"); + // Long after: a mouse wheel notch, untouched. + let mut ev = [wheel(Vec2::new(0.0, -1.0), CTRL)]; + assert_eq!(legacy_pinch_to_zoom(&mut ev, 2.0, Some(1.1), 40.0, 0.005), Some(1.1)); + assert!(matches!(ev[0], Event::MouseWheel { .. })); + // Without Ctrl nothing is a pinch. + let mut ev = [wheel(Vec2::new(0.0, 0.5), Modifiers::NONE)]; + assert_eq!(legacy_pinch_to_zoom(&mut ev, 2.0, None, 40.0, 0.005), None); + assert!(matches!(ev[0], Event::MouseWheel { .. })); +} + +#[test] +fn hostile_numbers_never_produce_a_bad_zoom() { + for s in [f32::NAN, f32::INFINITY, -f32::INFINITY, 1e30, -1e30] { + for alt in [false, true] { + for notch in [0.0, -1.0, f32::NAN, 40.0] { + for (zd, animated_zoom) in [f32::NAN, 0.0, -1.0, f32::INFINITY, 1.0].into_iter().flat_map(|zd| [(zd, false), (zd, true)]) { + let i = Input { + scroll: Vec2::new(0.0, s), + raw: Vec2::new(0.0, s), + zoom_delta: zd, + alt, + shift: false, + zoom_with_wheel: !alt, + pinch_zooms: true, + animated_zoom, + notch, + }; + if let Some(Wheel::Zoom(f)) = classify(i) { + assert!(f.is_finite() && f > 0.0, "{f} from {i:?}"); + } + let si = Input { + shift: true, + zoom_with_wheel: true, + ..Input { + scroll: Vec2::new(0.0, s), + raw: Vec2::new(0.0, s), + zoom_delta: zd, + alt: false, + shift: false, + zoom_with_wheel: true, + pinch_zooms: true, + animated_zoom, + notch, + } + }; + if let Some(Wheel::SnapZoom(n)) = classify(si) { + assert!(n.abs() <= 10, "snap steps clamped: {n} from {si:?}"); + } + } + let mut ev = [wheel(Vec2::new(s, 0.5), CTRL)]; + let _ = legacy_pinch_to_zoom(&mut ev, f64::NAN, Some(f64::NAN), notch, 0.005); + let _ = legacy_pinch_to_zoom(&mut ev, 0.0, None, notch, f32::NAN); + if let Event::Zoom(f) = ev[0] { + assert!(f.is_finite() && f > 0.0, "{f}"); + } + } + } + } +} + +/// A gesture helper that runs each frame at 1/60 s spacing with Point-unit events, +/// collecting snaps, and using a specific owner ID. +fn snap_gesture(frames: Vec>, zoom_with_wheel: bool, owner: Id) -> i32 { + let ctx = Context::default(); + configure(&ctx); + let mut snaps = 0i32; + let mut frames = frames.into_iter(); + for n in 0..60 { + let raw = RawInput { time: Some(f64::from(n) / 60.0), predicted_dt: 1.0 / 60.0, events: frames.next().unwrap_or_default(), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + if let Some(Wheel::SnapZoom(s)) = read(ui.ctx(), zoom_with_wheel, true, true, owner, true) { + snaps += s; + } + }); + out.textures_delta.clear(); + } + snaps +} + +#[test] +fn fractional_point_events_accumulate_across_frames() { + let quarter = Vec2::new(0.0, 10.0); + let batched = snap_gesture(vec![vec![wheel_point(Vec2::new(0.0, 40.0), Modifiers::SHIFT)]], true, Id::unique("accum-batched")); + let split = snap_gesture( + vec![ + vec![wheel_point(quarter, Modifiers::SHIFT)], + vec![wheel_point(quarter, Modifiers::SHIFT)], + vec![wheel_point(quarter, Modifiers::SHIFT)], + vec![wheel_point(quarter, Modifiers::SHIFT)], + ], + true, + Id::unique("accum-split"), + ); + assert_eq!(batched, 1, "40 points batched → 1 step"); + assert_eq!(split, 1, "4 × 10 points split → 1 step"); +} + +#[test] +fn fractional_accumulation_negative_and_horizontal() { + let neg_quarter = Vec2::new(0.0, -10.0); + let neg_split = snap_gesture( + vec![ + vec![wheel_point(neg_quarter, Modifiers::SHIFT)], + vec![wheel_point(neg_quarter, Modifiers::SHIFT)], + vec![wheel_point(neg_quarter, Modifiers::SHIFT)], + vec![wheel_point(neg_quarter, Modifiers::SHIFT)], + ], + true, + Id::unique("accum-neg"), + ); + assert_eq!(neg_split, -1, "4 × −10 points → −1 step"); + let h_quarter = Vec2::new(10.0, 0.0); + let h_split = snap_gesture( + vec![ + vec![wheel_point(h_quarter, Modifiers::SHIFT)], + vec![wheel_point(h_quarter, Modifiers::SHIFT)], + vec![wheel_point(h_quarter, Modifiers::SHIFT)], + vec![wheel_point(h_quarter, Modifiers::SHIFT)], + ], + true, + Id::unique("accum-horiz"), + ); + assert_eq!(h_split, 1, "horizontal 4 × 10 → 1 step"); +} + +#[test] +fn accumulation_handles_empty_frames_and_direction_reversal() { + let snaps = snap_gesture( + vec![ + vec![wheel_point(Vec2::new(0.0, 10.0), Modifiers::SHIFT)], + vec![], // empty frame + vec![wheel_point(Vec2::new(0.0, 10.0), Modifiers::SHIFT)], + vec![wheel_point(Vec2::new(0.0, 10.0), Modifiers::SHIFT)], + vec![wheel_point(Vec2::new(0.0, 10.0), Modifiers::SHIFT)], + ], + true, + Id::unique("accum-empty"), + ); + assert_eq!(snaps, 1, "empty frame preserves residual"); + let reversal = snap_gesture( + vec![vec![wheel_point(Vec2::new(0.0, 30.0), Modifiers::SHIFT)], vec![wheel_point(Vec2::new(0.0, -15.0), Modifiers::SHIFT)]], + true, + Id::unique("accum-reversal"), + ); + assert_eq!(reversal, 0, "30 − 15 = 15 points, below 1 notch → 0 steps"); +} + +#[test] +fn accumulation_shift_alt_without_preference() { + let shift_alt = Modifiers { shift: true, alt: true, ..Modifiers::NONE }; + let split = snap_gesture( + vec![ + vec![wheel_point(Vec2::new(0.0, 10.0), shift_alt)], + vec![wheel_point(Vec2::new(0.0, 10.0), shift_alt)], + vec![wheel_point(Vec2::new(0.0, 10.0), shift_alt)], + vec![wheel_point(Vec2::new(0.0, 10.0), shift_alt)], + ], + false, + Id::unique("accum-shift-alt"), + ); + assert_eq!(split, 1, "Shift+Alt 4 × 10 → 1 step without preference"); +} + +#[test] +fn cross_viewport_does_not_leak_residual() { + let owner_a = Id::unique("owner-a"); + let owner_b = Id::unique("owner-b"); + let ctx = Context::default(); + configure(&ctx); + let mut snaps_a = 0i32; + let mut snaps_b = 0i32; + // Frame 0: 30 points over A (hovered), B not hovered. + let raw = RawInput { time: Some(0.0), predicted_dt: 1.0 / 60.0, events: vec![wheel_point(Vec2::new(0.0, 30.0), Modifiers::SHIFT)], ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + if let Some(Wheel::SnapZoom(s)) = read(ui.ctx(), true, true, true, owner_a, true) { + snaps_a += s; + } + if let Some(Wheel::SnapZoom(s)) = read(ui.ctx(), true, true, true, owner_b, false) { + snaps_b += s; + } + }); + out.textures_delta.clear(); + assert_eq!(snaps_a, 0, "A: 30 points, below 1 notch"); + assert_eq!(snaps_b, 0, "B: not hovered, nothing"); + // Frame 1: 10 points, pointer moved to B (B hovered, A not). + let raw = + RawInput { time: Some(1.0 / 60.0), predicted_dt: 1.0 / 60.0, events: vec![wheel_point(Vec2::new(0.0, 10.0), Modifiers::SHIFT)], ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + if let Some(Wheel::SnapZoom(s)) = read(ui.ctx(), true, true, true, owner_a, false) { + snaps_a += s; + } + if let Some(Wheel::SnapZoom(s)) = read(ui.ctx(), true, true, true, owner_b, true) { + snaps_b += s; + } + }); + out.textures_delta.clear(); + assert_eq!(snaps_b, 0, "B: only 10 points of its own, no snap"); + // Frame 2–4: 30 more points over B. + for n in 2..5 { + let raw = RawInput { + time: Some(f64::from(n) / 60.0), + predicted_dt: 1.0 / 60.0, + events: vec![wheel_point(Vec2::new(0.0, 10.0), Modifiers::SHIFT)], + ..Default::default() + }; + let mut out = ctx.run_ui(raw, |ui| { + let _ = read(ui.ctx(), true, true, true, owner_a, false); + if let Some(Wheel::SnapZoom(s)) = read(ui.ctx(), true, true, true, owner_b, true) { + snaps_b += s; + } + }); + out.textures_delta.clear(); + } + assert_eq!(snaps_b, 1, "B: 10+10+10+10 = 40 → 1 step"); + // Frame 5: switch back to A — A's residual was cleared on the viewport switch. + let raw = + RawInput { time: Some(5.0 / 60.0), predicted_dt: 1.0 / 60.0, events: vec![wheel_point(Vec2::new(0.0, 30.0), Modifiers::SHIFT)], ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + if let Some(Wheel::SnapZoom(s)) = read(ui.ctx(), true, true, true, owner_a, true) { + snaps_a += s; + } + let _ = read(ui.ctx(), true, true, true, owner_b, false); + }); + out.textures_delta.clear(); + assert_eq!(snaps_a, 0, "A: fresh start after switch, 30 points, no snap yet"); +} + +#[test] +fn two_reads_same_owner_same_frame_do_not_double_count() { + let owner = Id::unique("same-owner"); + let ctx = Context::default(); + configure(&ctx); + let mut total_snaps = 0i32; + let raw = RawInput { time: Some(0.0), predicted_dt: 1.0 / 60.0, events: vec![wheel_point(Vec2::new(0.0, 20.0), Modifiers::SHIFT)], ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + if let Some(Wheel::SnapZoom(s)) = read(ui.ctx(), true, true, true, owner, true) { + total_snaps += s; + } + if let Some(Wheel::SnapZoom(s)) = read(ui.ctx(), true, true, true, owner, true) { + total_snaps += s; + } + }); + out.textures_delta.clear(); + assert_eq!(total_snaps, 0, "20 points read twice must not become 40"); + // Now add another 20 in the next frame — should snap since accumulated 20+20=40. + let raw = + RawInput { time: Some(1.0 / 60.0), predicted_dt: 1.0 / 60.0, events: vec![wheel_point(Vec2::new(0.0, 20.0), Modifiers::SHIFT)], ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + if let Some(Wheel::SnapZoom(s)) = read(ui.ctx(), true, true, true, owner, true) { + total_snaps += s; + } + }); + out.textures_delta.clear(); + assert_eq!(total_snaps, 1, "20 + 20 across two frames → 1 step"); +} + +#[test] +fn accumulation_hostile_numbers() { + for dy in [1e30, -1e30, 1e-10, -1e-10] { + let snaps = snap_gesture(vec![vec![wheel_point(Vec2::new(0.0, dy), Modifiers::SHIFT)]], true, Id::unique("accum-hostile")); + assert!(snaps.abs() <= 10, "hostile {dy} clamped: {snaps}"); + } +} + +#[test] +fn line_unit_snap_still_works_with_accumulation() { + let (_, _, snaps) = gesture(vec![vec![wheel(Vec2::new(0.0, 1.0), Modifiers::SHIFT)]], true, false); + assert_eq!(snaps, 1, "Line-unit notch produces 1 step"); + let (_, _, snaps) = gesture(vec![vec![wheel(Vec2::new(0.0, -1.0), Modifiers::SHIFT)]], true, false); + assert_eq!(snaps, -1, "Line-unit notch down produces −1 step"); +} + +/// Two fingers on a touch screen: down 20 points apart, spread to 40 (a ×2 pinch), lifted. +fn touch_pinch_frames() -> Vec> { + let touch = |id: u64, phase: TouchPhase, x: f32| Event::Touch { + device_id: egui::TouchDeviceId(1), + id: egui::TouchId(id), + phase, + pos: egui::pos2(x, 50.0), + force: None, + }; + vec![ + // egui only starts a multi-touch gesture once it knows where the pointer is. + vec![Event::PointerMoved(egui::pos2(40.0, 50.0))], + vec![touch(1, TouchPhase::Start, 40.0), touch(2, TouchPhase::Start, 60.0)], + vec![touch(1, TouchPhase::Move, 30.0), touch(2, TouchPhase::Move, 70.0)], + vec![touch(1, TouchPhase::End, 30.0), touch(2, TouchPhase::End, 70.0)], + ] +} + +/// The total zoom [`read_with`] reports over `frames`, Enable Gestures set to `touch_gestures`. +fn touch_zoom(frames: Vec>, touch_gestures: bool) -> f32 { + let owner = Id::unique("test-touch"); + let ctx = Context::default(); + configure(&ctx); + let mut zoom = 1.0; + for (n, events) in (0u32..).zip(frames) { + let raw = RawInput { time: Some(f64::from(n) / 60.0), predicted_dt: 1.0 / 60.0, events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + if let Some(Wheel::Zoom(f)) = read_with(ui.ctx(), false, true, true, owner, true, true, touch_gestures) { + zoom *= f; + } + }); + out.textures_delta.clear(); + } + zoom +} + +/// Preferences › Enhanced Controls › Enable Gestures (#204): on (the default) a two-finger +/// pinch on a touch screen zooms; off, it leaves the view alone. +#[test] +fn enable_gestures_switches_touch_screen_pinch_zoom() { + let on = touch_zoom(touch_pinch_frames(), true); + assert!((on - 2.0).abs() < 1e-4, "on: the fingers zoom ×2: {on}"); + let off = touch_zoom(touch_pinch_frames(), false); + assert_eq!(off, 1.0, "off: the fingers don't zoom"); +} + +/// Enable Gestures off only silences the touch screen: a trackpad pinch still zooms, also in a +/// frame where two fingers rest on the screen (egui's `zoom_delta` would report theirs instead). +#[test] +fn enable_gestures_off_keeps_the_trackpad_pinch() { + let zoom = touch_zoom(vec![vec![Event::Zoom(1.25)]], false); + assert!((zoom - 1.25).abs() < 1e-4, "no fingers down: {zoom}"); + let mut frames = touch_pinch_frames(); + frames[2] = vec![Event::Zoom(1.25)]; + let zoom = touch_zoom(frames, false); + assert!((zoom - 1.25).abs() < 1e-4, "fingers resting: {zoom}"); +} diff --git a/crates/ui-egui/src/zoom_hold.rs b/crates/ui-egui/src/canvas/zoom_hold.rs similarity index 100% rename from crates/ui-egui/src/zoom_hold.rs rename to crates/ui-egui/src/canvas/zoom_hold.rs diff --git a/crates/ui-egui/src/zoom_levels.rs b/crates/ui-egui/src/canvas/zoom_levels.rs similarity index 100% rename from crates/ui-egui/src/zoom_levels.rs rename to crates/ui-egui/src/canvas/zoom_levels.rs diff --git a/crates/ui-egui/src/zoom_window_fit.rs b/crates/ui-egui/src/canvas/zoom_window_fit.rs similarity index 100% rename from crates/ui-egui/src/zoom_window_fit.rs rename to crates/ui-egui/src/canvas/zoom_window_fit.rs diff --git a/crates/ui-egui/src/canvas_tool_menu.rs b/crates/ui-egui/src/canvas_tool_menu.rs deleted file mode 100644 index 1f5ae2e066..0000000000 --- a/crates/ui-egui/src/canvas_tool_menu.rs +++ /dev/null @@ -1,2388 +0,0 @@ -//! Canvas context menus for the selection tools, the Pen, the Zoom and Hand tools, an active Free -//! Transform box, text being edited with a Type tool, committed type under a Type tool, the -//! pasteboard (outside the image), a guide and a pending crop. - -use egui::Context; -use photocraft_doc::LayerContent; -use photocraft_engine::prefs::{self, CanvasColor}; -use serde::{Deserialize, Serialize}; -use serde_json::{Value, json}; - -use crate::{PhotocraftApp, state::Tool}; - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct CanvasToolMenu { - pub pos: [f32; 2], - pub tool: Tool, - pub has_selection: bool, - #[serde(default)] - pub has_path: bool, - #[serde(default)] - pub path_name: Option, - /// Opened over a Free Transform box: its modes instead of the tool's actions. - #[serde(default)] - pub transform: bool, - /// Opened outside the image: the pasteboard colour instead of the tool's actions. - #[serde(default)] - pub pasteboard: bool, - /// The Zoom and Hand tools' view menu: the document point right-clicked, which Zoom In and - /// Zoom Out keep under the pointer. - #[serde(default)] - pub anchor: Option<[f64; 2]>, - /// Opened while a Type tool edits text: the text and type rows instead of the tool's actions. - #[serde(default)] - pub text: bool, - /// Opened with a Type tool over committed type (no edit running): the type layer rows. - #[serde(default)] - pub type_layer: bool, - /// Opened on a guide: the guide menu (`guide_select`) instead of the tool's actions. - #[serde(default)] - pub guide: bool, - /// The misspelled word under the pointer when the type edit menu opened: its suggestions head - /// the menu. - #[serde(default)] - pub spelling: Option, - /// Opened on a pending crop: the crop menu, listing the saved crop presets by the names they - /// had when it opened. - #[serde(default)] - pub crop: Option>, -} - -/// A misspelled word in the type layer being edited (`edit.checkSpelling`'s `list` entry). -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct Spelling { - pub layer: u64, - /// The word's characters `start..end` in the layer's text. - pub start: usize, - pub end: usize, - pub word: String, - pub suggestions: Vec, -} - -/// Most suggestions the type edit menu lists. -const MAX_SUGGESTIONS: usize = 3; -/// The spelling rows' ids: `spelling.replace.` picks the n-th suggestion. -const SPELLING_REPLACE: &str = "spelling.replace."; -const SPELLING_NONE: &str = "spelling.none"; -const SPELLING_ADD: &str = "spelling.add"; - -/// One menu row: label and command id. `None` is a separator. -pub type Row = Option<(S, S)>; - -/// Right-click while transforming, in Photoshop's order: what the box's handles do, then Rotate -/// and Flip, which turn the open box without committing it (`transform_tool::intercept`). -/// Content-Aware Scale and Puppet Warp are greyed while a box is open. -pub const TRANSFORM_MENU: &[Row] = &[ - Some(("Free Transform", "edit.freeTransform")), - Some(("Scale", "edit.transform.scale")), - Some(("Rotate", "edit.transform.rotate")), - Some(("Skew", "edit.transform.skew")), - Some(("Distort", "edit.transform.distort")), - Some(("Perspective", "edit.transform.perspective")), - Some(("Warp", "edit.transform.warp")), - None, - Some(("Content-Aware Scale", "edit.contentAwareScale")), - Some(("Puppet Warp", "edit.puppetWarp")), - None, - Some(("Rotate 180°", "edit.transform.rotate180")), - Some(("Rotate 90° Clockwise", "edit.transform.rotate90Cw")), - Some(("Rotate 90° Counter Clockwise", "edit.transform.rotate90Ccw")), - None, - Some(("Flip Horizontal", "edit.transform.flipHorizontal")), - Some(("Flip Vertical", "edit.transform.flipVertical")), -]; - -/// Photoshop's pasteboard menu (right-click outside the image): the pasteboard colour, the choice -/// Preferences › Interface also offers. The ids are this menu's own: [`choose`] turns them into -/// `prefs.set` (`pasteboard.`) or opens the Color Picker. -pub const PASTEBOARD_MENU: &[Row] = &[ - Some(("Default", "pasteboard.default")), - Some(("Black", "pasteboard.black")), - Some(("Dark Gray", "pasteboard.darkGray")), - Some(("Medium Gray", "pasteboard.mediumGray")), - Some(("Light Gray", "pasteboard.lightGray")), - Some(("Custom", "pasteboard.custom")), - None, - Some(("Select Custom Color…", PASTEBOARD_PICK)), -]; - -/// Photoshop's right-click menu inside text being edited: the edit rows act on the text (its -/// selection, the OS clipboard), the type rows on the layer, as the Type menu's do. Faux Bold and -/// Faux Italic are the Character panel's toggles (this menu's own ids, run as `type.setStyle`). -/// Convert to Paragraph Text and Convert to Point Text are both listed; the one that doesn't apply -/// greys out. The exact Photoshop placement is inferred (docs/context-menu-parity.md). -pub const TYPE_EDIT_MENU: &[Row] = &[ - Some(("Undo", "edit.undo")), - None, - Some(("Cut", "edit.cut")), - Some(("Copy", "edit.copy")), - Some(("Paste", "edit.paste")), - Some(("Select All", "select.all")), - None, - Some(("Check Spelling…", "edit.checkSpelling")), - Some(("Find and Replace Text…", "edit.findAndReplaceText")), - None, - Some(("Faux Bold", FAUX_BOLD)), - Some(("Faux Italic", FAUX_ITALIC)), - None, - Some(("Rasterize Type", "type.rasterizeTypeLayer")), - Some(("Create Work Path", "type.createWorkPath")), - Some(("Convert to Shape", "type.convertToShape")), - None, - Some(("Horizontal", "type.orientation.horizontal")), - Some(("Vertical", "type.orientation.vertical")), - None, - Some(("None", "type.antiAlias.none")), - Some(("Sharp", "type.antiAlias.sharp")), - Some(("Crisp", "type.antiAlias.crisp")), - Some(("Strong", "type.antiAlias.strong")), - Some(("Smooth", "type.antiAlias.smooth")), - Some(("Windows LCD", "type.antiAlias.windowsLcd")), - Some(("Windows", "type.antiAlias.windows")), - None, - Some(("Convert to Paragraph Text", "type.convertToParagraphText")), - Some(("Convert to Point Text", "type.convertToPointText")), - Some(("Warp Text…", "type.warpText")), -]; - -/// Right-click with a Type tool over type that isn't being edited (#7324): the type edit menu's -/// layer rows. Its edit rows would act on the document instead of the text, and Faux Bold/Italic -/// on characters being edited, so they are left out. -pub const TYPE_LAYER_MENU: &[Row] = &[ - Some(("Check Spelling…", "edit.checkSpelling")), - Some(("Find and Replace Text…", "edit.findAndReplaceText")), - None, - Some(("Rasterize Type", "type.rasterizeTypeLayer")), - Some(("Create Work Path", "type.createWorkPath")), - Some(("Convert to Shape", "type.convertToShape")), - None, - Some(("Horizontal", "type.orientation.horizontal")), - Some(("Vertical", "type.orientation.vertical")), - None, - Some(("None", "type.antiAlias.none")), - Some(("Sharp", "type.antiAlias.sharp")), - Some(("Crisp", "type.antiAlias.crisp")), - Some(("Strong", "type.antiAlias.strong")), - Some(("Smooth", "type.antiAlias.smooth")), - Some(("Windows LCD", "type.antiAlias.windowsLcd")), - Some(("Windows", "type.antiAlias.windows")), - None, - Some(("Convert to Paragraph Text", "type.convertToParagraphText")), - Some(("Convert to Point Text", "type.convertToPointText")), - Some(("Warp Text…", "type.warpText")), -]; - -/// The type edit menu's Faux Bold and Faux Italic rows. -pub const FAUX_BOLD: &str = "type.fauxBold"; -pub const FAUX_ITALIC: &str = "type.fauxItalic"; - -/// Type edit rows that act on the whole layer (it may stop being type): the edit ends first. -const ENDS_TYPE_EDIT: [&str; 5] = - ["type.rasterizeTypeLayer", "type.createWorkPath", "type.convertToShape", "type.convertToParagraphText", "type.convertToPointText"]; - -/// The pasteboard menu's Select Custom Color… row. -pub const PASTEBOARD_PICK: &str = "pasteboard.selectCustomColor"; - -/// The guide menu's Edit Selected Guides row: New Guide's dialog on the selected guide. -pub const GUIDE_EDIT: &str = "guides.editSelected"; -/// The guide menu's Clear Selected Guides row. -pub const GUIDE_CLEAR: &str = "guides.clearSelected"; - -/// Photoshop's guide menu (right-click on a guide), in its order. Its two Selected Guides rows act -/// on the guide the right-click selected; the rest are the View menu's. -pub const GUIDE_MENU: &[Row] = &[ - Some(("Edit Selected Guides", GUIDE_EDIT)), - None, - Some(("Lock Guides", "view.lockGuides")), - Some(("Clear Guides", "view.clearGuides")), - Some(("Clear Canvas Guides", "view.clearCanvasGuides")), - Some(("Clear Selected Guides", GUIDE_CLEAR)), - Some(("Clear Selected Artboard Guides", "view.clearSelectedArtboardGuides")), -]; - -/// The crop menu's row ids. A ratio row is `crop.ratio.`, the options bar's preset dropdown -/// key (`crop_size::dropdown_options`); a saved preset is `crop.preset.`, the n-th name the menu -/// opened with; an overlay row is `crop.overlay.` or `crop.overlayShow.`. -const CROP_RATIO: &str = "crop.ratio."; -const CROP_PRESET: &str = "crop.preset."; -const CROP_OVERLAY: &str = "crop.overlay."; -const CROP_SHOW: &str = "crop.overlayShow."; -pub const CROP_CLEAR: &str = "crop.clear"; -pub const CROP_NEW: &str = "crop.newPreset"; -pub const CROP_DELETE: &str = "crop.deletePreset"; -pub const CROP_CANCEL: &str = "crop.cancel"; -pub const CROP_COMMIT: &str = "crop.commit"; - -/// The crop menu (right-click on a pending crop, #6561): the options bar's preset dropdown, in its -/// order, and its Clear; the overlay and when it shows; then Cancel and Crop, the bar's ⊘ and ✓. -/// Built from the bar's own lists, so the two cannot disagree. Empty for any other menu. -pub fn crop_rows(menu: &CanvasToolMenu) -> Vec> { - use crate::crop_overlay::{CropOverlay, OverlayShow}; - let Some(users) = menu.crop.as_ref() else { return Vec::new() }; - let ratio = |(k, l): &(String, &str)| Some((l.to_string(), format!("{CROP_RATIO}{k}"))); - let (before, after): (Vec<_>, Vec<_>) = crate::crop_size::dropdown_options().into_iter().partition(|(k, _)| k != crate::crop_size::FRONT); - let mut rows: Vec> = before.iter().map(ratio).collect(); - rows.extend(users.iter().enumerate().map(|(i, name)| Some((name.clone(), format!("{CROP_PRESET}{i}"))))); - rows.extend(after.iter().map(ratio)); - rows.push(Some(("Clear".into(), CROP_CLEAR.into()))); - rows.push(None); - rows.push(Some(("New Crop Preset…".into(), CROP_NEW.into()))); - rows.push(Some(("Delete Crop Preset…".into(), CROP_DELETE.into()))); - rows.push(None); - rows.extend(CropOverlay::ALL.iter().map(|k| Some((k.label().to_string(), format!("{CROP_OVERLAY}{}", k.id()))))); - rows.push(None); - rows.extend(OverlayShow::ALL.iter().map(|k| Some((k.label().to_string(), format!("{CROP_SHOW}{}", k.id()))))); - rows.push(None); - rows.push(Some(("Cancel".into(), CROP_CANCEL.into()))); - rows.push(Some(("Crop".into(), CROP_COMMIT.into()))); - rows -} - -/// Is a crop row's label UI text (translated), rather than a saved preset's name? -pub fn crop_label_is_ui(id: &str) -> bool { - !id.starts_with(CROP_PRESET) -} - -/// Is `command` one of the crop menu's rows? -fn is_crop(menu: &CanvasToolMenu, command: &str) -> bool { - crop_rows(menu).iter().flatten().any(|(_, id)| id == command) -} - -/// The saved crop preset a `crop.preset.` row picks. -fn crop_preset<'a>(menu: &'a CanvasToolMenu, command: &str) -> Option<&'a String> { - let n = command.strip_prefix(CROP_PRESET)?.parse::().ok()?; - menu.crop.as_ref()?.get(n) -} - -/// The crop menu's checkmarks, as the options bar shows them: the dropdown's entry (a saved -/// preset the fields hold, else the mode or ratio, so a size preset checks W x H x Resolution), -/// the overlay and when it shows. -fn crop_checked(app: &PhotocraftApp, menu: &CanvasToolMenu, command: &str) -> bool { - let o = &app.ui.tool_options; - let user = crate::crop_presets::current_user(app); - if let Some(k) = command.strip_prefix(CROP_RATIO) { - return user.is_none() && k == o.crop_ratio; - } - if command.starts_with(CROP_PRESET) { - return user.is_some() && crop_preset(menu, command) == user.as_ref(); - } - if let Some(k) = command.strip_prefix(CROP_OVERLAY) { - return k == o.crop_overlay.id(); - } - command.strip_prefix(CROP_SHOW).is_some_and(|k| k == o.crop_overlay_show.id()) -} - -fn crop_enabled(app: &PhotocraftApp, menu: &CanvasToolMenu, command: &str) -> bool { - match command { - CROP_NEW => crate::crop_presets::savable(&app.ui.tool_options).is_some(), - CROP_DELETE => menu.crop.as_ref().is_some_and(|u| !u.is_empty()), - c => is_crop(menu, c), - } -} - -/// Right-click with `tool` on a pending crop: the crop menu at screen point `pos`. Only the Crop -/// tool itself, not one held over it (Space's Hand). -pub fn open_crop(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, pos: [f32; 2]) -> bool { - if tool != Tool::Crop || !crate::crop_ui::pending(app) || !pos.iter().all(|v| v.is_finite()) { - return false; - } - app.ui.brush_picker = None; - app.ui.layer_menu = None; - let users = crate::crop_presets::user_presets(app).into_iter().map(|(name, _)| name).collect(); - app.ui.canvas_tool_menu = Some(CanvasToolMenu { - pos, - tool, - has_selection: false, - has_path: false, - path_name: None, - transform: false, - pasteboard: false, - anchor: None, - text: false, - type_layer: false, - guide: false, - spelling: None, - crop: Some(users), - }); - crate::canvas_popup::mark_open(ctx, menu_id()); - true -} - -/// A crop row: each runs what its options-bar twin runs. -fn choose_crop(app: &mut PhotocraftApp, menu: &CanvasToolMenu, command: &str) -> Result<(), String> { - use crate::crop_overlay::{CropOverlay, OverlayShow}; - use crate::crop_presets::{Choice, apply_choice}; - match command { - CROP_CANCEL => crate::crop_ui::cancel(app), - CROP_COMMIT => crate::canvas::commit_crop(app), - CROP_NEW => apply_choice(app, Choice::New), - CROP_DELETE => apply_choice(app, Choice::Delete), - _ => { - let before = crate::crop_ui::preset_ratio(app); - if let Some(k) = command.strip_prefix(CROP_RATIO) { - apply_choice(app, Choice::Builtin(k.to_string())); - } else if let Some(name) = crop_preset(menu, command) { - apply_choice(app, Choice::User(name.clone())); - } else if command == CROP_CLEAR { - crate::crop_size::clear_ratio(&mut app.ui.tool_options); - } else if let Some(k) = command.strip_prefix(CROP_OVERLAY).and_then(CropOverlay::from_id) { - crate::crop_overlay::set_overlay(&mut app.ui.tool_options, k); - } else if let Some(k) = command.strip_prefix(CROP_SHOW).and_then(OverlayShow::from_id) { - app.ui.tool_options.crop_overlay_show = k; - } - // As the options bar does: a saved preset or Clear changes the ratio without refitting - // the frame, so refit it when the ratio (or W x H) the frame follows changed. - if crate::crop_ui::preset_ratio(app) != before { - crate::crop_ui::apply_ratio(app); - } - } - } - Ok(()) -} - -/// The pasteboard colours in the menu's order, which Space+F steps through. -const CANVAS_COLORS: [CanvasColor; 6] = - [CanvasColor::Default, CanvasColor::Black, CanvasColor::DarkGray, CanvasColor::MediumGray, CanvasColor::LightGray, CanvasColor::Custom]; - -/// Photoshop's Space+F (⇧Space+F backwards): the next pasteboard colour, round and round. Saved -/// like a choice in the pasteboard menu (`interface.canvasColor`). -pub fn cycle_canvas_color(app: &mut PhotocraftApp, backward: bool) -> Result<(), String> { - let n = CANVAS_COLORS.len(); - let at = CANVAS_COLORS.iter().position(|c| *c == app.session.prefs().interface.canvas_color).unwrap_or(0); - let next = if backward { (at + n - 1) % n } else { (at + 1) % n }; - let name = CANVAS_COLORS.get(next).map_or("default", |c| c.name()); - app.run("prefs.set", json!({"values": {"interface.canvasColor": name}})).map(|_| ()) -} - -/// The Zoom and Hand tools' context menu: the fixed zooms of the View menu (plus the Hand tool's -/// Fill Screen), then the zoom steps last, in Photoshop's order (#6005). -pub const VIEW_MENU: &[Row] = &[ - Some(("Fit on Screen", "view.fitOnScreen")), - Some(("Fill Screen", FILL_SCREEN)), - Some(("100%", "view.actualPixels")), - Some(("200%", "view.twoHundredPercent")), - Some(("Print Size", "view.printSize")), - None, - Some(("Zoom In", "view.zoomIn")), - Some(("Zoom Out", "view.zoomOut")), -]; - -/// The view menu's Fill Screen row. Photoshop has no View menu command for it, so the menu sets -/// the view itself. -pub const FILL_SCREEN: &str = "view.fillScreen"; - -/// Photoshop's selection-tool context menu with an active selection, in its order. Its Generative -/// Fill row has no PhotoCraft command and is left out. Rows stay visible and grey out exactly like -/// their menu-bar twins. -pub const SELECTION_MENU: &[Row] = &[ - Some(("Deselect", "select.deselect")), - Some(("Select Inverse", "select.inverse")), - Some(("Feather…", "select.modify.feather")), - Some(("Select and Mask…", "select.selectAndMask")), - None, - Some(("Save Selection…", "select.saveSelection")), - Some(("Make Work Path…", "select.toWorkPath")), - None, - Some(("Layer via Copy", "layer.new.layerViaCopy")), - Some(("Layer via Cut", "layer.new.layerViaCut")), - Some(("New Layer…", "layer.new.layer")), - None, - Some(("Free Transform", "edit.freeTransform")), - Some(("Transform Selection", "select.transformSelection")), - Some(("Distort", "edit.transform.distort")), - Some(("Perspective", "edit.transform.perspective")), - None, - Some(("Delete and Fill Selection", "edit.deleteAndFillSelection")), - Some(("Fill…", "edit.fill")), - Some(("Stroke…", "edit.stroke")), - Some(("Content-Aware Fill…", "edit.contentAwareFill")), - None, - Some(("Last Filter", "filter.lastFilter")), - None, - Some(("Fade…", "edit.fade")), -]; - -/// The selection tools' context menu with nothing selected: making a selection. -pub const NO_SELECTION_MENU: &[Row] = &[ - Some(("Select All", "select.all")), - Some(("Reselect", "select.reselect")), - Some(("Color Range…", "select.colorRange")), - None, - Some(("Load Selection…", "select.loadSelection")), -]; - -/// Photoshop's Pen context menu order. Rows whose operation is not applicable to the current -/// path or layer stay visible and disabled. -pub const PEN_MENU: &[Row] = &[ - Some(("Create Vector Mask", "layer.vectorMask.fromPath")), - Some(("Delete Path", "path.delete")), - None, - Some(("Define Custom Shape…", "edit.defineCustomShape")), - None, - Some(("Make Selection…", "path.toSelection")), - Some(("New Guides From Shape", "view.newGuidesFromShape")), - Some(("Fill Path…", "path.fill")), - Some(("Stroke Path…", "path.stroke")), - None, - Some(("Clipping Path…", "path.clippingPath.set")), - None, - Some(("Free Transform Path", "path.transform")), - None, - Some(("Unite Shapes", "layer.combineShapes.unite")), - Some(("Subtract Front Shape", "layer.combineShapes.subtractFrontShape")), - Some(("Unite Shapes at Overlap", "layer.combineShapes.intersectShapeAreas")), - Some(("Subtract Shapes at Overlap", "layer.combineShapes.excludeOverlappingShapes")), - None, - Some(("Copy Fill", "path.style.copyFill")), - Some(("Copy Complete Stroke", "path.style.copyStroke")), - None, - Some(("Paste Fill", "path.style.pasteFill")), - Some(("Paste Complete Stroke", "path.style.pasteStroke")), - None, - Some(("Isolate Layers", "select.isolateLayers")), - None, - Some(("Make Symmetry Path", "paint.symmetryFromPath")), - Some(("Disable Symmetry Path", "paint.symmetryDisable")), -]; - -/// Tools whose plain canvas right-click offers selection actions. -pub fn applies(tool: Tool) -> bool { - matches!( - tool, - Tool::RectMarquee - | Tool::EllipseMarquee - | Tool::SingleRowMarquee - | Tool::SingleColumnMarquee - | Tool::Lasso - | Tool::PolygonLasso - | Tool::MagneticLasso - | Tool::MagicWand - | Tool::ObjectSelection - // Its brush is set from the options bar's chip; the canvas right-click is the - // selection menu, as in Photoshop (#7268). - | Tool::QuickSelection - ) || path_menu(tool) -} - -/// Tools whose canvas right-click opens the path menu ([`PEN_MENU`]): the Pen, and the Path -/// Selection and Direct Selection tools, whose Photoshop menu offers the same whole-path actions -/// for the selected path (#1056). -pub fn path_menu(tool: Tool) -> bool { - matches!(tool, Tool::Pen | Tool::PathSelection | Tool::DirectSelection) -} - -/// Tools whose plain canvas right-click offers the view menu. -pub fn is_view_tool(tool: Tool) -> bool { - matches!(tool, Tool::Zoom | Tool::Hand) -} - -/// The selection tools' rows, with or without an active selection. -pub fn selection_rows(has_selection: bool) -> &'static [Row] { - if has_selection { SELECTION_MENU } else { NO_SELECTION_MENU } -} - -/// The rows of an open menu. -pub fn rows(menu: &CanvasToolMenu) -> &'static [Row] { - if menu.crop.is_some() { - // Built per menu: [`crop_rows`]. - &[] - } else if menu.guide { - GUIDE_MENU - } else if menu.pasteboard { - PASTEBOARD_MENU - } else if menu.transform { - TRANSFORM_MENU - } else if menu.anchor.is_some() { - VIEW_MENU - } else if menu.text { - TYPE_EDIT_MENU - } else if menu.type_layer { - TYPE_LAYER_MENU - } else if path_menu(menu.tool) { - PEN_MENU - } else { - selection_rows(menu.has_selection) - } -} - -/// Is `command` one of the open menu's rows, and enabled? -pub fn available(app: &PhotocraftApp, menu: &CanvasToolMenu, command: &str) -> bool { - (rows(menu).iter().flatten().any(|(_, id)| *id == command) || is_spelling(menu, command) || is_crop(menu, command)) && entry_enabled(app, menu, command) -} - -/// Is `command` the transform box's current mode (checked in the transform menu)? -/// Scale stays Free Transform's mode (only Free Transform is checked). Rotate is its own mode. -/// Warp is not a box mode (it is its own session), and `for_command` would read it as Free. -pub(crate) fn mode_checked(app: &PhotocraftApp, menu: &CanvasToolMenu, command: &str) -> bool { - if menu.crop.is_some() { - return crop_checked(app, menu, command); - } - if menu.guide { - return command == "view.lockGuides" && app.ui.extras.lock_guides; - } - if menu.pasteboard { - return pasteboard_choice(command) == Some(app.session.prefs().interface.canvas_color); - } - if menu.text || menu.type_layer { - return type_checked(app, command); - } - menu.transform - && matches!(command, "edit.freeTransform" | "edit.transform.rotate" | "edit.transform.skew" | "edit.transform.distort" | "edit.transform.perspective") - && app.ui.transform.as_ref().is_some_and(|t| t.mode == crate::state::TransformMode::for_command(command)) -} - -/// The type edit menu's checkmarks: the faux styles at the selection, the layer's orientation and -/// anti-aliasing. -fn type_checked(app: &PhotocraftApp, command: &str) -> bool { - use photocraft_doc::text::Orientation; - let Some(t) = crate::type_tool::target_text(app) else { return false }; - match command { - FAUX_BOLD | FAUX_ITALIC => crate::type_tool::styles_at(app).is_some_and(|(c, _)| if command == FAUX_BOLD { c.faux_bold } else { c.faux_italic }), - "type.orientation.horizontal" => t.orientation == Orientation::Horizontal, - "type.orientation.vertical" => t.orientation == Orientation::Vertical, - c => c.strip_prefix("type.antiAlias.") == Some(photocraft_engine::type_extra_cmds::aa_name(t.antialias)), - } -} - -/// Is the Type tool editing text, so that a right-click opens the type edit menu? -pub fn editing_text(app: &PhotocraftApp, tool: Tool) -> bool { - tool.is_type() && app.ui.text_edit.is_some() -} - -/// The committed type layer under document point `doc` when a right-click there with a Type tool -/// opens the type layer menu (#7324). The Type Mask tools are left out: to them existing type is -/// just pixels. -pub fn type_layer_at(app: &mut PhotocraftApp, tool: Tool, doc: [f64; 2]) -> Option { - if !tool.is_type() || tool.is_type_mask() || app.ui.text_edit.is_some() || !doc.iter().all(|v| v.is_finite()) { - return None; - } - crate::type_tool::hit_layer(app, doc[0], doc[1]) -} - -/// Make the right-clicked type layer `id` the active layer, which the structural rows (Rasterize -/// Type, Convert to Shape…) act on and the checks show. Inside a multiselection the selection stays, -/// so the formatting rows still act on every selected type layer, as the Type menu's do; outside it -/// the type replaces the selection, as a click with the Type tool does. -fn target_type_layer(app: &mut PhotocraftApp, id: photocraft_doc::LayerId) -> bool { - let Some(st) = app.session.active() else { return false }; - let selected = st.selected_layers(); - if st.active_layer == Some(id) { - true - } else if selected.contains(&id) { - photocraft_engine::layer_multi_cmds::set_selection(&mut app.session, selected, Some(id), Some(id)).is_ok() - } else { - app.session.select_layer(id).is_ok() - } -} - -/// The misspelled word of the edited text under document point `doc`, with its suggestions. -fn spelling_at(app: &mut PhotocraftApp, doc: [f64; 2]) -> Option { - let layer = app.ui.text_edit.as_ref()?.layer; - if !doc.iter().all(|v| v.is_finite()) { - return None; - } - let at = crate::type_tool::offset_at(app, photocraft_doc::LayerId(layer), doc[0], doc[1]); - let found = app.session.execute("edit.checkSpelling", json!({"action": "list", "layer": layer, "suggestions": MAX_SUGGESTIONS})).ok()?; - let hit = found["misspellings"].as_array()?.iter().find(|m| { - let (a, b) = (m["start"].as_u64().unwrap_or(u64::MAX) as usize, m["end"].as_u64().unwrap_or(0) as usize); - a <= at && at <= b - })?; - Some(Spelling { - layer, - start: hit["start"].as_u64()? as usize, - end: hit["end"].as_u64()? as usize, - word: hit["word"].as_str()?.to_string(), - suggestions: hit["suggestions"].as_array()?.iter().filter_map(|s| s.as_str().map(str::to_string)).take(MAX_SUGGESTIONS).collect(), - }) -} - -/// The spelling rows heading the type edit menu (label, id): the suggestions, or a greyed note -/// when there are none, then Add to Dictionary. Empty away from a misspelled word. -pub fn spelling_rows(menu: &CanvasToolMenu) -> Vec<(String, String)> { - let Some(sp) = menu.spelling.as_ref().filter(|_| menu.text) else { return Vec::new() }; - let mut rows: Vec<(String, String)> = sp.suggestions.iter().enumerate().map(|(i, s)| (s.clone(), format!("{SPELLING_REPLACE}{i}"))).collect(); - if rows.is_empty() { - rows.push(("No Spelling Suggestions".into(), SPELLING_NONE.into())); - } - rows.push(("Add to Dictionary".into(), SPELLING_ADD.into())); - rows -} - -/// Is `command` one of the menu's spelling rows? -fn is_spelling(menu: &CanvasToolMenu, command: &str) -> bool { - spelling_rows(menu).iter().any(|(_, id)| id == command) -} - -/// Does a spelling row's label come from the UI (translated) rather than from the dictionary? -pub fn spelling_label_is_ui(id: &str) -> bool { - matches!(id, SPELLING_NONE | SPELLING_ADD) -} - -/// Right-click over a Free Transform box: its modes. -pub fn open_transform(app: &mut PhotocraftApp, ctx: &Context, pos: [f32; 2]) -> bool { - if !pos.iter().all(|v| v.is_finite()) { - return false; - } - app.ui.brush_picker = None; - app.ui.layer_menu = None; - app.ui.canvas_tool_menu = Some(CanvasToolMenu { - pos, - tool: app.ui.tool, - has_selection: false, - has_path: false, - path_name: None, - transform: true, - pasteboard: false, - anchor: None, - text: false, - type_layer: false, - guide: false, - spelling: None, - crop: None, - }); - crate::canvas_popup::mark_open(ctx, menu_id()); - true -} - -/// The pasteboard colour a pasteboard menu row picks (`None` for Select Custom Color… or a row -/// of another menu). -fn pasteboard_choice(command: &str) -> Option { - command.strip_prefix("pasteboard.").and_then(CanvasColor::parse) -} - -/// The engine command (and params) a pasteboard row runs, for the automation policy: every row -/// changes a preference. -pub fn engine_call(app: &PhotocraftApp, menu: &CanvasToolMenu, command: &str) -> (String, Value) { - if menu.crop.is_some() && command == CROP_COMMIT { - return ("image.crop".into(), json!({})); - } - if menu.guide { - let selected = crate::guide_select::selected(app); - return match command { - GUIDE_EDIT => ("view.editGuide".into(), json!({})), - GUIDE_CLEAR => ("view.deleteGuide".into(), selected.map_or(json!({}), |(v, i)| crate::guide_select::delete_params(v, i))), - _ => (command.into(), json!({})), - }; - } - match pasteboard_choice(command) { - Some(c) if menu.pasteboard => ("prefs.set".into(), json!({"values": {"interface.canvasColor": c.name()}})), - _ if menu.pasteboard => ("prefs.set".into(), json!({})), - _ if menu.text && matches!(command, FAUX_BOLD | FAUX_ITALIC) => ("type.setStyle".into(), json!({})), - _ if is_spelling(menu, command) => spelling_call(menu, command), - _ => (command.into(), json!({})), - } -} - -/// The `edit.checkSpelling` call a spelling row makes: replace the word with a suggestion, or add -/// it to the user dictionary. -fn spelling_call(menu: &CanvasToolMenu, command: &str) -> (String, Value) { - let Some(sp) = menu.spelling.as_ref() else { return ("edit.checkSpelling".into(), json!({})) }; - let replace = command.strip_prefix(SPELLING_REPLACE).and_then(|n| n.parse::().ok()).and_then(|n| sp.suggestions.get(n)); - match replace { - Some(to) => { - ("edit.checkSpelling".into(), json!({"action": "change", "layer": sp.layer, "start": sp.start, "end": sp.end, "word": sp.word, "replace": to})) - } - None => ("edit.checkSpelling".into(), json!({"action": "addToDictionary", "word": sp.word})), - } -} - -/// Does a right-click with `tool` at document point `doc` open the pasteboard menu? Outside the -/// image, for the tools whose right-click has no job there: not the painting tools (their Brush -/// Preset picker or right-button erase), the Pen (its path menu) or text being edited. -pub fn pasteboard_at(app: &PhotocraftApp, tool: Tool, doc: [f64; 2]) -> bool { - let Some(st) = app.session.active() else { return false }; - let (w, h) = (f64::from(st.doc.size.width), f64::from(st.doc.size.height)); - let outside = doc.iter().all(|v| v.is_finite()) && (doc[0] < 0.0 || doc[1] < 0.0 || doc[0] >= w || doc[1] >= h); - outside && !path_menu(tool) && !crate::paint_mouse::has_brush_picker(tool) && !crate::paint_mouse::right_erases(app, tool) && app.ui.text_edit.is_none() -} - -/// Right-click on the pasteboard: its colour menu at screen point `pos`. -pub fn open_pasteboard(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, pos: [f32; 2]) -> bool { - if !pos.iter().all(|v| v.is_finite()) { - return false; - } - app.ui.brush_picker = None; - app.ui.layer_menu = None; - app.ui.canvas_tool_menu = Some(CanvasToolMenu { - pos, - tool, - has_selection: false, - has_path: false, - path_name: None, - transform: false, - pasteboard: true, - anchor: None, - text: false, - type_layer: false, - guide: false, - spelling: None, - crop: None, - }); - crate::canvas_popup::mark_open(ctx, menu_id()); - true -} - -/// Right-click at document point `doc` on a guide that `tool` could drag (the Move tool, or ⌘ with -/// a tool on which ⌘ moves guides, `canvas::command_guide_at`): select the guide and open the guide -/// menu at screen point `pos`. -pub fn open_guide(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, mods: egui::Modifiers, pos: [f32; 2], doc: [f64; 2]) -> bool { - if !pos.iter().all(|v| v.is_finite()) || !doc.iter().all(|v| v.is_finite()) { - return false; - } - let hit = if tool == Tool::Move { crate::rulers::guide_at(app, doc[0], doc[1]) } else { crate::canvas::command_guide_at(app, tool, doc, mods) }; - let Some((vertical, index)) = hit else { return false }; - crate::guide_select::select(app, vertical, index); - app.ui.brush_picker = None; - app.ui.layer_menu = None; - app.ui.canvas_tool_menu = Some(CanvasToolMenu { - pos, - tool, - has_selection: false, - has_path: false, - path_name: None, - transform: false, - pasteboard: false, - anchor: None, - text: false, - type_layer: false, - guide: true, - spelling: None, - crop: None, - }); - crate::canvas_popup::mark_open(ctx, menu_id()); - true -} - -/// A guide row: the two Selected Guides rows act on the selected guide; the rest are the View -/// menu's commands. -fn choose_guide(app: &mut PhotocraftApp, ctx: &Context, command: &str) -> Result<(), String> { - match command { - GUIDE_EDIT => crate::new_guide_ui::open_edit(app).map(|_| ()), - GUIDE_CLEAR => crate::guide_select::delete_selected(app).map(|_| ()), - _ => crate::menus::invoke(app, ctx, command, json!({})).map(|_| ()), - } -} - -/// A pasteboard row: set the colour, or open the Color Picker on the custom one. -fn choose_pasteboard(app: &mut PhotocraftApp, menu: &CanvasToolMenu, command: &str) -> Result<(), String> { - if command == PASTEBOARD_PICK { - let rgb = prefs::parse_hex(&app.session.prefs().interface.canvas_custom_color).map_or([0.5; 3], |c| c.map(|v| f32::from(v) / 255.0)); - crate::color_picker_ui::open_for_target(app, "pasteboard", "Color Picker (Custom Canvas Color)", rgb); - return Ok(()); - } - let (command, params) = engine_call(app, menu, command); - app.run(&command, params).map(|_| ()) -} - -pub fn entry_enabled(app: &PhotocraftApp, menu: &CanvasToolMenu, command: &str) -> bool { - if menu.crop.is_some() { - return crop_enabled(app, menu, command); - } - if menu.guide { - return match command { - GUIDE_EDIT | GUIDE_CLEAR => crate::guide_select::selected(app).is_some(), - _ => GUIDE_MENU.iter().flatten().any(|(_, id)| *id == command) && crate::menus::is_enabled(app, command), - }; - } - if menu.pasteboard { - return PASTEBOARD_MENU.iter().flatten().any(|(_, id)| *id == command); - } - // Warp needs a layer, selection or path box: a lone mask or channel keeps the plain box. - if menu.transform && command == "edit.transform.warp" { - return app.ui.transform.as_ref().is_some_and(|t| t.warp.is_none() && t.target.is_none()); - } - if menu.anchor.is_some() && command == FILL_SCREEN { - return app.session.active().is_some(); - } - if menu.text { - return match command { - SPELLING_NONE => false, - c if is_spelling(menu, c) => app.ui.text_edit.is_some(), - FAUX_BOLD | FAUX_ITALIC => app.ui.text_edit.is_some(), - c => TYPE_EDIT_MENU.iter().flatten().any(|(_, id)| *id == c) && crate::menus::is_enabled(app, c), - }; - } - if menu.type_layer { - return TYPE_LAYER_MENU.iter().flatten().any(|(_, id)| *id == command) && crate::menus::is_enabled(app, command); - } - if menu.transform || !path_menu(menu.tool) { - return crate::menus::is_enabled(app, command); - } - let Some(st) = app.session.active() else { return false }; - let layer = st.active_layer.and_then(|id| st.doc.layer(id)); - let locked = layer.is_some_and(|l| st.doc.effective_locks(l.id).all); - let can_paint = layer.is_some_and(|l| matches!(l.content, LayerContent::Raster(_))) && !locked; - let shape_layer = layer.and_then(|l| match &l.content { - LayerContent::Shape(sh) => Some(sh), - _ => None, - }); - let shape = shape_layer.is_some(); - let can_mask = layer.is_some_and(|l| !matches!(l.content, LayerContent::Shape(_))) && !locked; - let saved = menu.path_name.as_deref().is_some_and(|n| n != "work" && n != "layer"); - let has_path = menu.has_path; - let pending = app.ui.pen.as_ref().is_some_and(|p| p.knots.len() >= 2); - let pending_layer = pending && (app.ui.tool_options.vector_mode == "shape" || app.ui.vector_mask_target); - match command { - "layer.vectorMask.fromPath" => has_path && can_mask && !pending_layer, - "path.delete" => has_path && !pending_layer && (pending || menu.path_name.as_deref() != Some("layer")), - "edit.defineCustomShape" | "path.toSelection" | "path.transform" | "paint.symmetryFromPath" => has_path, - "view.newGuidesFromShape" => shape && !pending, - "path.fill" | "path.stroke" => has_path && can_paint && !pending_layer, - "path.clippingPath.set" => saved && !pending, - "layer.combineShapes.unite" - | "layer.combineShapes.subtractFrontShape" - | "layer.combineShapes.intersectShapeAreas" - | "layer.combineShapes.excludeOverlappingShapes" => !pending && shape_layer.is_some_and(|sh| sh.path.subpaths.len() > 1), - "path.style.copyFill" => !pending && shape_layer.is_some_and(|sh| sh.fill.is_some()), - "path.style.copyStroke" => !pending && shape_layer.is_some_and(|sh| sh.stroke.is_some()), - "path.style.pasteFill" => !pending && shape && app.session.path_fill_clipboard.is_some(), - "path.style.pasteStroke" => !pending && shape && app.session.path_stroke_clipboard.is_some(), - "select.isolateLayers" => layer.is_some(), - "paint.symmetryDisable" => st.symmetry.is_some(), - _ => false, - } -} - -pub fn open(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, pos: [f32; 2]) -> bool { - open_at(app, ctx, tool, pos, None) -} - -/// [`open`] for a right-click at document point `doc`: over a misspelled word of the text being -/// edited, the menu starts with its spelling suggestions; over committed type with a Type tool, the -/// type layer menu. -pub fn open_at(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, pos: [f32; 2], doc: Option<[f64; 2]>) -> bool { - let text = editing_text(app, tool); - if !pos.iter().all(|v| v.is_finite()) { - return false; - } - let type_layer = !text && doc.and_then(|d| type_layer_at(app, tool, d)).is_some_and(|id| target_type_layer(app, id)); - if !(applies(tool) || text || type_layer) { - return false; - } - app.ui.brush_picker = None; - app.ui.layer_menu = None; - let has_selection = app.session.active().is_some_and(|s| s.doc.selection.is_some()); - let has_path = crate::vector_ui::active_path_name(app).is_some() || app.ui.pen.as_ref().is_some_and(|p| p.knots.len() >= 2); - let path_name = crate::vector_ui::active_path_name(app); - let spelling = if text { doc.and_then(|d| spelling_at(app, d)) } else { None }; - app.ui.canvas_tool_menu = Some(CanvasToolMenu { - pos, - tool, - has_selection, - has_path, - path_name, - transform: false, - pasteboard: false, - anchor: None, - text, - type_layer, - guide: false, - spelling, - crop: None, - }); - crate::canvas_popup::mark_open(ctx, menu_id()); - true -} - -/// Right-click with the Zoom or Hand tool at screen point `pos`, over document point `doc`: the -/// view menu. -pub fn open_view(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, pos: [f32; 2], doc: [f64; 2]) -> bool { - if !is_view_tool(tool) || !pos.iter().all(|v| v.is_finite()) || !doc.iter().all(|v| v.is_finite()) { - return false; - } - app.ui.brush_picker = None; - app.ui.layer_menu = None; - app.ui.canvas_tool_menu = Some(CanvasToolMenu { - pos, - tool, - has_selection: false, - has_path: false, - path_name: None, - transform: false, - pasteboard: false, - anchor: Some(doc), - text: false, - type_layer: false, - guide: false, - spelling: None, - crop: None, - }); - crate::canvas_popup::mark_open(ctx, menu_id()); - true -} - -/// A view menu row. Zoom In and Zoom Out step about the right-clicked point, as a Zoom tool click -/// does; the other rows run their View menu command. -fn choose_view(app: &mut PhotocraftApp, ctx: &Context, menu: &CanvasToolMenu, command: &str) -> Result<(), String> { - let i = app.session.active_index().ok_or("no document")?; - if command == FILL_SCREEN { - let v = app.ui.views.get_mut(i).ok_or("no document view")?; - v.fit_pending = false; - v.fill_pending = true; - v.request_zoom_animation(app.session.prefs().general.animated_zoom); - v.zoom_anchor = None; - return Ok(()); - } - let before = app.ui.views.get(i).map(|v| (v.zoom, v.center)); - crate::menus::invoke(app, ctx, command, json!({}))?; - if !matches!(command, "view.zoomIn" | "view.zoomOut") { - return Ok(()); - } - let (Some((zoom0, c)), Some(d)) = (before, menu.anchor) else { return Ok(()) }; - let center_on_point = app.session.prefs().tools.zoom_clicked_point_to_center; - let Some(v) = app.ui.views.get_mut(i) else { return Ok(()) }; - let d = [d[0] as f32, d[1] as f32]; - // The view scales about the centre, so the point keeps its screen position when its offset - // from the centre shrinks (or grows) by the zoom ratio, whatever the rotation or flip. - let ratio = zoom0 / v.zoom; - v.center = if center_on_point || !ratio.is_finite() { d } else { [d[0] - (d[0] - c[0]) * ratio, d[1] - (d[1] - c[1]) * ratio] }; - v.zoom_anchor = (v.zoom_animating && !center_on_point).then_some(([d[0] as f64, d[1] as f64], menu.pos)); - Ok(()) -} - -pub fn choose(app: &mut PhotocraftApp, ctx: &Context, command: &str) { - let Some(menu) = app.ui.canvas_tool_menu.take() else { return }; - if !available(app, &menu, command) { - return; - } - let result = if menu.crop.is_some() { - choose_crop(app, &menu, command) - } else if menu.guide { - choose_guide(app, ctx, command) - } else if menu.pasteboard { - choose_pasteboard(app, &menu, command) - } else if menu.anchor.is_some() { - choose_view(app, ctx, &menu, command) - } else if menu.text && is_spelling(&menu, command) { - choose_spelling(app, &menu, command) - } else if menu.text || menu.type_layer { - choose_type(app, ctx, command) - } else if path_menu(menu.tool) && !menu.transform { - choose_pen(app, ctx, &menu, command) - } else if command == "select.toWorkPath" { - // Photoshop's Make Work Path… asks for the tolerance first. - spec_dialog(app, command, "Make Work Path", r##"{"tolerance":0.5..10=2}"##, serde_json::Map::new()); - Ok(()) - } else { - crate::menus::invoke(app, ctx, command, json!({})).map(|_| ()) - }; - if let Err(e) = result { - app.ui.status = e; - app.ui.status_error = true; - } -} - -/// A spelling row: replace the word under the pointer (the caret lands after the replacement), or -/// add it to the user dictionary. -fn choose_spelling(app: &mut PhotocraftApp, menu: &CanvasToolMenu, command: &str) -> Result<(), String> { - let (id, params) = engine_call(app, menu, command); - let result = app.run(&id, params)?; - if let Some(end) = result["end"].as_u64().map(|e| e as usize) - && let Some(e) = app.ui.text_edit.as_mut() - { - (e.caret, e.anchor) = (end, end); - } - Ok(()) -} - -/// A type edit row. Undo, Cut, Copy, Paste and Select All run as their Edit and Select menu items, -/// which act on the text while it is being edited (Paste asks the window for the clipboard text). -fn choose_type(app: &mut PhotocraftApp, ctx: &Context, command: &str) -> Result<(), String> { - match command { - FAUX_BOLD | FAUX_ITALIC => { - let bold = command == FAUX_BOLD; - let on = !type_checked(app, command); - let mut p = crate::type_tool::formatting_params(app).ok_or("No type is being edited")?; - p[if bold { "fauxBold" } else { "fauxItalic" }] = json!(on); - app.run("type.setStyle", p)?; - } - _ => { - if ENDS_TYPE_EDIT.contains(&command) { - crate::type_tool::commit(app); - } - crate::menus::invoke(app, ctx, command, json!({}))?; - } - } - Ok(()) -} - -/// A parameter dialog for `command` following `spec` (registry notation), prefilled with `fields`. -fn spec_dialog(app: &mut PhotocraftApp, command: &str, label: &str, spec: &str, mut fields: serde_json::Map) { - fields.insert("__command".into(), json!(command)); - fields.insert("__label".into(), json!(label)); - fields.insert("__filter".into(), json!(true)); - fields.insert("__spec".into(), json!(spec)); - app.ui.open_dialog(crate::state::DialogKind::Command, fields); -} - -/// Photoshop's Stroke Path dialog: the brush-based tool to stroke with (painting with that tool's -/// current options) and Simulate Pressure (#2978). -const STROKE_PATH_SPEC: &str = r##"{"tool":"brush|pencil|eraser|backgroundEraser|cloneStamp|patternStamp|healingBrush|spotHealingBrush|historyBrush|blur|sharpen|smudge|dodge|burn|sponge|colorReplacement|mixerBrush"="brush","simulatePressure":bool=false}"##; - -/// The Stroke Path dialog for the path `name` (Paths panel menu, Alt-click on its Stroke button). -pub(crate) fn stroke_path_dialog(app: &mut PhotocraftApp, name: &str) { - pen_dialog(app, "path.stroke", "Stroke Path…", name); -} - -fn pen_dialog(app: &mut PhotocraftApp, command: &str, label: &str, name: &str) { - let spec = match command { - "edit.defineCustomShape" => r##"{"name":text}"##, - "path.toSelection" => r##"{"feather":0..250=0,"antiAlias":bool=true,"mode":"replace|add|subtract|intersect"="replace"}"##, - "path.fill" => r##"{"color":text,"opacity":0..100=100,"feather":0..250=0,"antiAlias":bool=true}"##, - "path.stroke" => STROKE_PATH_SPEC, - "path.clippingPath.set" => r##"{"flatness":0..100=0}"##, - "path.transform" => r##"{"translateX":-30000..30000=0,"translateY":-30000..30000=0,"scaleX":0.01..100=1,"scaleY":0.01..100=1,"angle":-360..360=0}"##, - _ => "{}", - }; - let mut fields = serde_json::Map::new(); - if command == "edit.defineCustomShape" { - fields.insert("path".into(), json!(name)); - fields.insert("name".into(), json!("")); - } else { - fields.insert("name".into(), json!(name)); - } - if command == "path.fill" { - let fg = app.session.tools.foreground; - let byte = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; - fields.insert("color".into(), json!(format!("#{:02x}{:02x}{:02x}", byte(fg[0]), byte(fg[1]), byte(fg[2])))); - } - if command == "path.transform" { - for (key, value) in [("translateX", 0.0), ("translateY", 0.0), ("scaleX", 1.0), ("scaleY", 1.0), ("angle", 0.0)] { - fields.insert(key.into(), json!(value)); - } - } - spec_dialog(app, command, label, spec, fields); -} - -/// The Pen options bar's Make Selection (Path mode, #5703): the canvas menu's Make Selection… -/// dialog for the path being drawn (committed first, as the menu does) or the active path. -pub(crate) fn make_selection(app: &mut PhotocraftApp) -> Result<(), String> { - let pending = app.ui.pen.as_ref().is_some_and(|p| p.knots.len() >= 2); - // Where `pen_commit` puts the path being drawn: a shape layer or the targeted vector mask, - // else the Paths panel path it adds to (a selected saved path, or the Work Path), which it - // selects so it is the active path. - let pending_layer = pending && (app.ui.tool_options.vector_mode == "shape" || crate::vector_ui::targeted_vector_mask(app).is_some()); - if pending { - crate::vector_ui::pen_commit(app, false); - } - let name = if pending_layer { Some("layer".to_string()) } else { crate::vector_ui::active_path_name(app) } - .ok_or_else(|| "No path is available for this action".to_string())?; - pen_dialog(app, "path.toSelection", "Make Selection…", &name); - Ok(()) -} - -fn choose_pen(app: &mut PhotocraftApp, ctx: &Context, menu: &CanvasToolMenu, command: &str) -> Result<(), String> { - if command == "select.isolateLayers" { - crate::menus::invoke(app, ctx, command, json!({}))?; - return Ok(()); - } - if command == "paint.symmetryDisable" { - app.run(command, json!({}))?; - return Ok(()); - } - let pending = app.ui.pen.as_ref().is_some_and(|p| p.knots.len() >= 2); - let pending_layer = pending && (app.ui.tool_options.vector_mode == "shape" || app.ui.vector_mask_target); - if pending { - crate::vector_ui::pen_commit(app, false); - } - let name = if pending { Some(if pending_layer { "layer" } else { "work" }.to_string()) } else { menu.path_name.clone() } - .ok_or_else(|| "No path is available for this action".to_string())?; - match command { - "edit.defineCustomShape" | "path.toSelection" | "path.fill" | "path.stroke" | "path.clippingPath.set" | "path.transform" => { - let label = PEN_MENU.iter().flatten().find(|(_, id)| *id == command).map_or(command, |(label, _)| *label); - pen_dialog(app, command, label, &name); - } - _ => { - app.run(command, json!({"name": name}))?; - } - } - Ok(()) -} - -fn menu_id() -> egui::Id { - egui::Id::unique("canvas-selection-menu") -} - -pub fn show(app: &mut PhotocraftApp, ctx: &Context) { - let Some(menu) = app.ui.canvas_tool_menu.clone() else { return }; - if ctx.input(|i| i.key_pressed(egui::Key::Escape)) - || app.ui.tool != menu.tool - || (menu.transform && app.ui.transform.is_none()) - || (menu.text && app.ui.text_edit.is_none()) - || (menu.type_layer && app.ui.text_edit.is_some()) - || (menu.crop.is_some() && !crate::crop_ui::pending(app)) - { - app.ui.canvas_tool_menu = None; - return; - } - let id = menu_id(); - let screen = ctx.content_rect(); - let size = ctx.memory(|m| m.area_rect(id)).map_or(egui::vec2(210.0, 140.0), |r| r.size()); - let pos = egui::pos2(menu.pos[0].min(screen.right() - size.x).max(screen.left()), menu.pos[1].min(screen.bottom() - size.y).max(screen.top())); - let mut selected = None; - let area = egui::Area::new(id).order(egui::Order::Foreground).fixed_pos(pos).show(ctx, |ui| { - egui::Frame::menu(ui.style()).show(ui, |ui| { - let t = crate::theme::Tokens::get(ui.ctx()); - let v = &mut ui.style_mut().visuals; - v.widgets.inactive.weak_bg_fill = egui::Color32::TRANSPARENT; - v.widgets.inactive.bg_stroke = egui::Stroke::NONE; - v.widgets.hovered.weak_bg_fill = t.accent; - v.widgets.hovered.bg_fill = t.accent; - v.widgets.hovered.bg_stroke = egui::Stroke::NONE; - v.widgets.hovered.fg_stroke = egui::Stroke::new(1.0, egui::Color32::WHITE); - v.widgets.hovered.corner_radius = egui::CornerRadius::same(3); - ui.spacing_mut().item_spacing.y = 0.0; - ui.set_width(200.0); - crate::widgets::menu_scroll(ui, |ui| { - let spelling = spelling_rows(&menu); - for (label, command) in &spelling { - let text = if spelling_label_is_ui(command) { tl!(label).to_string() } else { label.clone() }; - let item = egui::Button::new(text).min_size(egui::vec2(200.0, 20.0)); - if ui.add_enabled(entry_enabled(app, &menu, command), item).clicked() { - selected = Some(command.clone()); - } - } - if !spelling.is_empty() { - ui.separator(); - } - for row in crop_rows(&menu) { - let Some((label, command)) = row else { - ui.separator(); - continue; - }; - let text = if crop_label_is_ui(&command) { tl!(&label).to_string() } else { label }; - let item = egui::Button::selectable(mode_checked(app, &menu, &command), text).min_size(egui::vec2(200.0, 20.0)); - if ui.add_enabled(entry_enabled(app, &menu, &command), item).clicked() { - selected = Some(command); - } - } - for row in rows(&menu) { - let Some((label, command)) = *row else { - ui.separator(); - continue; - }; - let item = egui::Button::selectable(mode_checked(app, &menu, command), tl!(label)).min_size(egui::vec2(200.0, 20.0)); - if ui.add_enabled(entry_enabled(app, &menu, command), item).clicked() { - selected = Some((*command).to_string()); - } - } - }); - }); - }); - if let Some(command) = selected { - choose(app, ctx, &command); - } else if crate::canvas_popup::outside_pressed(ctx, id, area.response.rect) { - app.ui.canvas_tool_menu = None; - } -} - -#[cfg(test)] -mod tests { - use super::*; - use egui::{Modifiers, PointerButton, Pos2, vec2}; - use egui_kittest::{Harness, kittest::Queryable}; - - fn app() -> PhotocraftApp { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); - app - } - - fn work_path(app: &mut PhotocraftApp) { - app.run( - "path.set", - json!({"name": "work", "path": {"subpaths": [{"closed": true, "knots": [ - {"anchor": [2, 2], "in": [2, 2], "out": [2, 2]}, - {"anchor": [20, 2], "in": [20, 2], "out": [20, 2]}, - {"anchor": [20, 20], "in": [20, 20], "out": [20, 20]} - ]}]}}), - ) - .unwrap(); - } - - fn choose_open(app: &mut PhotocraftApp, command: &str) { - assert!(open(app, &Context::default(), Tool::Pen, [10.0, 10.0])); - choose(app, &Context::default(), command); - } - - fn harness(mut app: PhotocraftApp) -> Harness<'static, PhotocraftApp> { - app.sync_views(); - let mut h = Harness::builder().with_size(vec2(1000.0, 700.0)).build_ui_state( - |ui, app: &mut PhotocraftApp| { - let ctx = ui.ctx().clone(); - if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { - return; - } - egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); - }, - app, - ); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::default()); - h.run_steps(4); - h - } - - fn right_click(h: &mut Harness<'static, PhotocraftApp>, p: Pos2, modifiers: Modifiers) { - h.event(egui::Event::ModifiersChanged(modifiers)); - h.event(egui::Event::PointerMoved(p)); - h.run_steps(1); - h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Secondary, pressed: true, modifiers }); - h.run_steps(1); - h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Secondary, pressed: false, modifiers }); - h.event(egui::Event::ModifiersChanged(Modifiers::NONE)); - h.run_steps(2); - } - - #[test] - fn canvas_gesture_preserves_selection_and_command_override() { - let mut app = app(); - app.ui.tool = Tool::Lasso; - app.run("select.rect", json!({"x": 1, "y": 1, "width": 8, "height": 8})).unwrap(); - let mut h = harness(app); - let center = h.state().last_canvas_rect.center(); - let revision = h.state().session.active().unwrap().revision; - right_click(&mut h, center, Modifiers::NONE); - assert!(h.state().ui.canvas_tool_menu.is_some()); - assert_eq!(h.state().session.active().unwrap().revision, revision, "right-click cannot alter selection"); - h.key_press(egui::Key::Escape); - h.run_steps(2); - assert!(h.state().ui.canvas_tool_menu.is_none()); - right_click(&mut h, center, Modifiers::COMMAND); - assert!(h.state().ui.canvas_tool_menu.is_none(), "command right-click belongs to layer picker"); - } - - /// A type layer reading "Hello", being edited with every character selected. - fn editing_type(app: &mut PhotocraftApp) -> u64 { - app.ui.tool = Tool::Type; - let id = app.run("type.create", json!({"text": "Hello", "size": 12, "x": 4, "y": 20})).unwrap()["layer"].as_u64().unwrap(); - crate::menus::invoke(app, &Context::default(), "type.editText", json!({})).unwrap(); - id - } - - fn text_of(app: &PhotocraftApp, id: u64) -> Option { - match &app.session.active().unwrap().doc.layer(photocraft_doc::LayerId(id)).unwrap().content { - LayerContent::Text(t) => Some(t.clone()), - _ => None, - } - } - - #[test] - fn right_click_while_typing_opens_the_type_edit_menu_and_esc_keeps_the_edit() { - let mut app = app(); - editing_type(&mut app); - app.sync_views(); - let mut h = Harness::builder().with_size(vec2(1000.0, 700.0)).build_ui_state( - |ui, app: &mut PhotocraftApp| { - let ctx = ui.ctx().clone(); - if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { - return; - } - // The app's order: shortcuts (inline type's keys among them), then the canvas. - crate::shortcuts::handle(app, &ctx); - egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); - }, - app, - ); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::default()); - h.run_steps(4); - let center = h.state().last_canvas_rect.center(); - right_click(&mut h, center, Modifiers::NONE); - let menu = h.state().ui.canvas_tool_menu.clone().expect("right-click in a type edit opens a menu"); - assert!(menu.text && !menu.pasteboard && !menu.transform); - assert_eq!(rows(&menu), TYPE_EDIT_MENU); - let edit = h.state().ui.text_edit.clone().expect("the edit goes on under the menu"); - assert_eq!((edit.anchor, edit.caret), (0, 5), "the right-click keeps the selection for Cut and Copy"); - h.key_press(egui::Key::Escape); - h.run_steps(2); - assert!(h.state().ui.canvas_tool_menu.is_none(), "Esc closes the menu"); - assert!(h.state().ui.text_edit.is_some(), "and only the menu: the edit isn't committed"); - } - - #[test] - fn type_edit_menu_rows_act_on_the_text_and_the_layer() { - let mut app = app(); - let id = editing_type(&mut app); - let ctx = Context::default(); - let reopen = |app: &mut PhotocraftApp| assert!(open(app, &Context::default(), Tool::Type, [10.0, 10.0])); - // Faux Bold toggles the style of the selected characters, and shows checked. - reopen(&mut app); - let menu = app.ui.canvas_tool_menu.clone().unwrap(); - assert!(!mode_checked(&app, &menu, FAUX_BOLD) && mode_checked(&app, &menu, "type.antiAlias.smooth")); - choose(&mut app, &ctx, FAUX_BOLD); - assert!(text_of(&app, id).unwrap().char_runs().iter().all(|r| r.style.faux_bold)); - assert!(mode_checked(&app, &menu, FAUX_BOLD)); - // Cut takes the selection out of the text; with nothing selected Copy and Cut grey out. - reopen(&mut app); - choose(&mut app, &ctx, "edit.cut"); - assert_eq!(text_of(&app, id).unwrap().text, ""); - reopen(&mut app); - let menu = app.ui.canvas_tool_menu.clone().unwrap(); - assert!(!entry_enabled(&app, &menu, "edit.copy") && !entry_enabled(&app, &menu, "edit.cut")); - app.ui.canvas_tool_menu = None; - crate::menus::invoke(&mut app, &ctx, "edit.undo", json!({})).unwrap(); - assert_eq!(text_of(&app, id).unwrap().text, "Hello"); - // Select All selects every character, not the canvas. - reopen(&mut app); - choose(&mut app, &ctx, "select.all"); - let edit = app.ui.text_edit.clone().unwrap(); - assert_eq!((edit.anchor, edit.caret), (0, 5)); - assert!(app.session.active().unwrap().doc.selection.is_none()); - // Warp Text… opens its dialog; Rasterize Type ends the edit and rasterizes the layer. - reopen(&mut app); - choose(&mut app, &ctx, "type.warpText"); - assert!(!app.ui.dialogs.is_empty(), "Warp Text… asks for its settings"); - app.ui.dialogs.clear(); - reopen(&mut app); - choose(&mut app, &ctx, "type.rasterizeTypeLayer"); - assert!(app.ui.text_edit.is_none() && text_of(&app, id).is_none(), "the type layer is pixels now"); - } - - /// A committed type layer reading "Hello" over the middle of the canvas, no edit running. - fn committed_type(app: &mut PhotocraftApp) -> u64 { - app.ui.tool = Tool::Type; - let id = app.run("type.create", json!({"text": "Hello", "size": 14, "x": 1, "y": 22})).unwrap()["layer"].as_u64().unwrap(); - assert!(app.ui.text_edit.is_none()); - id - } - - #[test] - fn right_click_on_committed_type_opens_the_type_layer_menu() { - use photocraft_doc::text::Orientation; - let mut app = app(); - let id = committed_type(&mut app); - assert_eq!(crate::type_tool::hit_layer(&mut app, 16.0, 16.0).map(|l| l.0), Some(id), "the canvas centre is on the type"); - let mut h = harness(app); - let center = h.state().last_canvas_rect.center(); - right_click(&mut h, center, Modifiers::NONE); - let menu = h.state().ui.canvas_tool_menu.clone().expect("right-click on committed type opens a menu (#7324)"); - assert!(menu.type_layer && !menu.text && !menu.pasteboard); - assert_eq!(rows(&menu), TYPE_LAYER_MENU); - assert!(h.state().ui.text_edit.is_none(), "the right-click doesn't start an edit"); - h.run_steps(2); - assert!(h.state().ui.canvas_tool_menu.is_some(), "the menu stays open without an edit"); - // An edit started some other way (here, as an agent's Type › Edit Text would) closes the - // menu, which has no text edit rows. - crate::menus::invoke(h.state_mut(), &Context::default(), "type.editText", json!({})).unwrap(); - h.run_steps(2); - assert!(h.state().ui.canvas_tool_menu.is_none(), "an edit closes the type layer menu"); - crate::type_tool::commit(h.state_mut()); - right_click(&mut h, center, Modifiers::NONE); - let menu = h.state().ui.canvas_tool_menu.clone().expect("committed again, the menu opens again"); - assert!(menu.type_layer && mode_checked(h.state(), &menu, "type.orientation.horizontal")); - choose(h.state_mut(), &Context::default(), "type.orientation.vertical"); - assert_eq!(text_of(h.state(), id).unwrap().orientation, Orientation::Vertical); - } - - #[test] - fn type_layer_menu_targets_the_type_under_the_pointer() { - let mut app = app(); - let id = committed_type(&mut app); - app.run("layer.new.layer", json!({})).unwrap(); - let ctx = Context::default(); - let active = |app: &PhotocraftApp| app.session.active().unwrap().active_layer.map(|l| l.0); - assert_ne!(active(&app), Some(id)); - // Away from the type, or with a Type Mask tool, nothing opens and nothing is selected. - assert!(!open_at(&mut app, &ctx, Tool::Type, [10.0, 10.0], Some([30.0, 2.0]))); - assert!(!open_at(&mut app, &ctx, Tool::HorizontalTypeMask, [10.0, 10.0], Some([16.0, 16.0]))); - assert!(!open_at(&mut app, &ctx, Tool::Type, [10.0, 10.0], Some([f64::NAN, 16.0]))); - assert_ne!(active(&app), Some(id)); - // Over the type: its layer becomes the target, and the menu has no text edit rows. - assert!(open_at(&mut app, &ctx, Tool::Type, [10.0, 10.0], Some([16.0, 16.0]))); - assert_eq!(active(&app), Some(id)); - let menu = app.ui.canvas_tool_menu.clone().unwrap(); - for edit_row in ["edit.undo", "edit.cut", "edit.copy", "edit.paste", "select.all", FAUX_BOLD, FAUX_ITALIC] { - assert!(!available(&app, &menu, edit_row), "{edit_row} belongs to the edit menu only"); - } - assert!(entry_enabled(&app, &menu, "type.convertToParagraphText") && !entry_enabled(&app, &menu, "type.convertToPointText")); - choose(&mut app, &ctx, "type.rasterizeTypeLayer"); - assert!(text_of(&app, id).is_none(), "the type layer is pixels now"); - assert!(app.ui.text_edit.is_none()); - } - - /// Two selected type layers: the one right-clicked becomes active, and the selection stays. - #[test] - fn type_layer_menu_in_a_multiselection_acts_on_the_clicked_type() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); - app.ui.tool = Tool::Type; - let top = app.run("type.create", json!({"text": "Top", "size": 30, "x": 10, "y": 40})).unwrap()["layer"].as_u64().unwrap(); - let bottom = app.run("type.create", json!({"text": "Low", "size": 30, "x": 10, "y": 90})).unwrap()["layer"].as_u64().unwrap(); - app.run("layer.select", json!({"layer": bottom})).unwrap(); - app.run("layer.select", json!({"layer": top, "mode": "add"})).unwrap(); - let at = [25.0, 80.0]; - assert_eq!(crate::type_tool::hit_layer(&mut app, at[0], at[1]).map(|l| l.0), Some(bottom)); - assert_eq!(app.session.active().unwrap().active_layer.map(|l| l.0), Some(top)); - let ctx = Context::default(); - assert!(open_at(&mut app, &ctx, Tool::Type, [10.0, 10.0], Some(at))); - let st = app.session.active().unwrap(); - assert_eq!(st.active_layer.map(|l| l.0), Some(bottom), "the clicked type is the target"); - assert_eq!(st.selected_layers().len(), 2, "the multiselection stays"); - choose(&mut app, &ctx, "type.rasterizeTypeLayer"); - assert!(text_of(&app, bottom).is_none(), "the clicked type is rasterized"); - assert!(text_of(&app, top).is_some(), "not the other selected type"); - } - - #[test] - fn type_edit_menu_lists_spelling_suggestions_for_the_word_under_the_pointer() { - let mut app = app(); - app.ui.tool = Tool::Type; - let id = app.run("type.create", json!({"text": "Teh cat", "size": 12, "x": 4, "y": 20})).unwrap()["layer"].as_u64().unwrap(); - let ctx = Context::default(); - crate::menus::invoke(&mut app, &ctx, "type.editText", json!({})).unwrap(); - // Away from the misspelling (past the end of the line): no spelling rows. - assert!(open_at(&mut app, &ctx, Tool::Type, [10.0, 10.0], Some([600.0, 15.0]))); - assert!(spelling_rows(app.ui.canvas_tool_menu.as_ref().unwrap()).is_empty()); - // Over "Teh": its suggestions head the menu, then Add to Dictionary. - assert!(open_at(&mut app, &ctx, Tool::Type, [10.0, 10.0], Some([5.0, 15.0]))); - let menu = app.ui.canvas_tool_menu.clone().unwrap(); - let rows = spelling_rows(&menu); - assert!(rows.iter().any(|(l, _)| l == "The"), "{rows:?}"); - assert_eq!(rows.last().map(|(_, id)| id.as_str()), Some(SPELLING_ADD)); - assert!(rows.len() <= MAX_SUGGESTIONS + 1, "at most {MAX_SUGGESTIONS} suggestions and Add to Dictionary: {rows:?}"); - assert!(available(&app, &menu, &rows[0].1)); - let pick = rows.iter().find(|(l, _)| l == "The").unwrap().1.clone(); - choose(&mut app, &ctx, &pick); - assert_eq!(text_of(&app, id).unwrap().text, "The cat"); - assert_eq!(app.ui.text_edit.as_ref().map(|e| (e.caret, e.anchor)), Some((3, 3)), "the caret lands after the replacement"); - // Add to Dictionary stops flagging a word. - app.run("type.insertText", json!({"layer": id, "text": " Zqx"})).unwrap(); - assert!(open_at(&mut app, &ctx, Tool::Type, [10.0, 10.0], Some([600.0, 15.0]))); - let menu = app.ui.canvas_tool_menu.clone().unwrap(); - assert!(menu.spelling.as_ref().is_some_and(|s| s.word == "Zqx")); - choose(&mut app, &ctx, SPELLING_ADD); - assert!(app.session.prefs().user_dictionary.iter().any(|w| w == "Zqx")); - } - - #[test] - fn right_click_outside_the_image_picks_the_pasteboard_color() { - let mut app = app(); - app.ui.tool = Tool::RectMarquee; - let mut h = harness(app); - let rect = h.state().last_canvas_rect; - let outside = rect.min + vec2(5.0, 5.0); - right_click(&mut h, rect.center(), Modifiers::NONE); - assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| !m.pasteboard), "inside: the tool's own menu"); - h.state_mut().ui.canvas_tool_menu = None; - right_click(&mut h, outside, Modifiers::NONE); - let menu = h.state().ui.canvas_tool_menu.clone().unwrap(); - assert!(menu.pasteboard && rows(&menu) == PASTEBOARD_MENU, "outside: the pasteboard menu"); - let ctx = h.ctx.clone(); - choose(h.state_mut(), &ctx, "pasteboard.black"); - assert_eq!(crate::prefs_ui::pasteboard_color(h.state()), Some(egui::Color32::BLACK)); - // Select Custom Color… opens the Color Picker; OK makes its colour the custom pasteboard. - right_click(&mut h, outside, Modifiers::NONE); - choose(h.state_mut(), &ctx, PASTEBOARD_PICK); - let mut f = h.state().ui.dialogs.last().unwrap().fields.clone(); - f.insert("color".into(), json!("#123456")); - crate::color_picker_ui::confirm(h.state_mut(), &f).unwrap(); - assert_eq!(crate::prefs_ui::pasteboard_color(h.state()), Some(egui::Color32::from_rgb(0x12, 0x34, 0x56))); - // A painting tool keeps its Brush Preset picker there. - h.state_mut().ui.tool = Tool::Brush; - h.run_steps(2); - right_click(&mut h, outside, Modifiers::NONE); - assert!(h.state().ui.canvas_tool_menu.is_none() && h.state().ui.brush_picker.is_some()); - } - - /// #2832: right-click over an open Free Transform box: Photoshop's transform menu. Skew - /// switches the box's mode; Rotate and Flip turn the box about its reference point without - /// committing it; Content-Aware Scale and Puppet Warp are greyed. - #[test] - fn right_click_during_free_transform_switches_modes_rotates_and_flips_the_box() { - let mut app = app(); - app.ui.tool = Tool::RectMarquee; - app.run("layer.new.layer", json!({})).unwrap(); - app.run("select.rect", json!({"x": 4, "y": 6, "width": 10, "height": 8})).unwrap(); - app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); - app.run("select.deselect", json!({})).unwrap(); - let mut h = harness(app); - let ctx = h.ctx.clone(); - crate::menus::invoke(h.state_mut(), &ctx, "edit.freeTransform", json!({})).unwrap(); - h.run_steps(2); - let center = h.state().last_canvas_rect.center(); - let (revision, journal) = (h.state().session.active().unwrap().revision, h.state().session.journal.len()); - right_click(&mut h, center, Modifiers::NONE); - let menu = h.state().ui.canvas_tool_menu.clone().expect("the transform menu"); - assert!(menu.transform && rows(&menu) == TRANSFORM_MENU); - for (id, on) in - [("edit.contentAwareScale", false), ("edit.puppetWarp", false), ("edit.transform.rotate90Cw", true), ("edit.transform.flipVertical", true)] - { - assert_eq!(entry_enabled(h.state(), &menu, id), on, "{id}"); - } - choose(h.state_mut(), &ctx, "edit.transform.skew"); - assert_eq!(h.state().ui.transform.as_ref().unwrap().mode, crate::state::TransformMode::Skew); - let t = h.state().ui.transform.clone().unwrap(); - let (q0, c) = (t.quad, t.pivot); - right_click(&mut h, center, Modifiers::NONE); - choose(h.state_mut(), &ctx, "edit.transform.flipHorizontal"); - let q = h.state().ui.transform.as_ref().expect("the box stays open").quad; - for (a, b) in q.iter().zip(q0) { - assert!((a[0] - (2.0 * c[0] - b[0])).abs() < 1e-9 && (a[1] - b[1]).abs() < 1e-9, "mirrored about the reference point: {q0:?} -> {q:?}"); - } - right_click(&mut h, center, Modifiers::NONE); - choose(h.state_mut(), &ctx, "edit.transform.rotate180"); - let q = h.state().ui.transform.as_ref().unwrap().quad; - for (a, b) in q.iter().zip(q0) { - assert!((a[1] - (2.0 * c[1] - b[1])).abs() < 1e-9 && (a[0] - b[0]).abs() < 1e-9, "flipped then turned 180°: {q0:?} -> {q:?}"); - } - let st = h.state().session.active().unwrap(); - assert_eq!((st.revision, h.state().session.journal.len()), (revision, journal), "nothing is committed"); - } - - #[test] - fn transform_menu_follows_photoshop_order() { - assert_eq!( - labels(TRANSFORM_MENU), - vec![ - Some("Free Transform"), - Some("Scale"), - Some("Rotate"), - Some("Skew"), - Some("Distort"), - Some("Perspective"), - Some("Warp"), - None, - Some("Content-Aware Scale"), - Some("Puppet Warp"), - None, - Some("Rotate 180°"), - Some("Rotate 90° Clockwise"), - Some("Rotate 90° Counter Clockwise"), - None, - Some("Flip Horizontal"), - Some("Flip Vertical"), - ] - ); - // Over a box on editable type, Distort and Perspective are greyed (#2630). - let mut app = app(); - app.run("type.create", json!({"x": 2, "y": 20, "text": "Hi", "size": 16})).unwrap(); - crate::transform_tool::begin(&mut app, &Context::default()).unwrap(); - assert!(open_transform(&mut app, &Context::default(), [10.0, 10.0])); - let menu = app.ui.canvas_tool_menu.clone().unwrap(); - for (id, on) in [("edit.transform.skew", true), ("edit.transform.distort", false), ("edit.transform.perspective", false)] { - assert_eq!(entry_enabled(&app, &menu, id), on, "{id}"); - } - } - - fn labels(rows: &[Row]) -> Vec> { - rows.iter().map(|row| row.map(|(label, _)| label)).collect() - } - - #[test] - fn selection_menus_follow_photoshop_order() { - assert_eq!( - labels(SELECTION_MENU), - vec![ - Some("Deselect"), - Some("Select Inverse"), - Some("Feather…"), - Some("Select and Mask…"), - None, - Some("Save Selection…"), - Some("Make Work Path…"), - None, - Some("Layer via Copy"), - Some("Layer via Cut"), - Some("New Layer…"), - None, - Some("Free Transform"), - Some("Transform Selection"), - Some("Distort"), - Some("Perspective"), - None, - Some("Delete and Fill Selection"), - Some("Fill…"), - Some("Stroke…"), - Some("Content-Aware Fill…"), - None, - Some("Last Filter"), - None, - Some("Fade…"), - ] - ); - assert_eq!(labels(NO_SELECTION_MENU), vec![Some("Select All"), Some("Reselect"), Some("Color Range…"), None, Some("Load Selection…")]); - // Every row runs a real command: one the menu bar has, or an engine command. - let app = app(); - let items = crate::menus::menu_items(&app); - for (label, id) in [SELECTION_MENU, NO_SELECTION_MENU, PEN_MENU, TRANSFORM_MENU].into_iter().flatten().flatten() { - assert!(items.iter().any(|i| i.id == *id) || photocraft_engine::commands::find(id).is_some(), "{label}: unknown command {id}"); - } - } - - #[test] - fn selection_menu_routes_actions_through_commands() { - let mut app = app(); - app.ui.tool = Tool::RectMarquee; - app.run("select.rect", json!({"x": 1, "y": 1, "width": 8, "height": 8})).unwrap(); - assert!(open(&mut app, &Context::default(), Tool::RectMarquee, [10.0, 10.0])); - assert_eq!(rows(app.ui.canvas_tool_menu.as_ref().unwrap()), SELECTION_MENU); - let before = app.session.journal.len(); - choose(&mut app, &Context::default(), "select.inverse"); - assert!(app.ui.canvas_tool_menu.is_none()); - assert!(app.session.journal[before..].iter().any(|(id, _)| id == "select.inverse")); - let before = app.session.journal.len(); - assert!(open(&mut app, &Context::default(), Tool::RectMarquee, [10.0, 10.0])); - choose(&mut app, &Context::default(), "select.deselect"); - assert!(app.session.active().unwrap().doc.selection.is_none()); - assert!(app.session.journal[before..].iter().any(|(id, _)| id == "select.deselect")); - // Nothing selected: the menu that makes a selection. - assert!(open(&mut app, &Context::default(), Tool::RectMarquee, [10.0, 10.0])); - assert_eq!(rows(app.ui.canvas_tool_menu.as_ref().unwrap()), NO_SELECTION_MENU); - choose(&mut app, &Context::default(), "select.reselect"); - assert!(app.session.active().unwrap().doc.selection.is_some()); - assert!(app.session.journal.iter().any(|(id, _)| id == "select.reselect")); - app.run("select.deselect", json!({})).unwrap(); - assert!(open(&mut app, &Context::default(), Tool::Lasso, [10.0, 10.0])); - choose(&mut app, &Context::default(), "select.all"); - assert!(app.session.active().unwrap().doc.selection.is_some()); - } - - #[test] - fn selection_menu_layer_and_path_actions() { - let mut app = app(); - app.ui.tool = Tool::EllipseMarquee; - app.run("layer.new.layer", json!({})).unwrap(); - app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); - app.run("select.rect", json!({"x": 4, "y": 4, "width": 10, "height": 10})).unwrap(); - let layers = app.session.active().unwrap().doc.layers.len(); - assert!(open(&mut app, &Context::default(), Tool::EllipseMarquee, [10.0, 10.0])); - choose(&mut app, &Context::default(), "layer.new.layerViaCopy"); - assert_eq!(app.session.active().unwrap().doc.layers.len(), layers + 1, "Layer via Copy adds a layer"); - assert_eq!(app.session.journal.last().map(|(id, _)| id.as_str()), Some("layer.new.layerViaCopy")); - // Make Work Path… asks for the tolerance, then traces the selection. - app.run("select.rect", json!({"x": 4, "y": 4, "width": 10, "height": 10})).unwrap(); - assert!(open(&mut app, &Context::default(), Tool::EllipseMarquee, [10.0, 10.0])); - choose(&mut app, &Context::default(), "select.toWorkPath"); - let dialog = app.ui.dialogs.last().map(|d| d.id).expect("tolerance dialog"); - assert!(app.session.active().unwrap().doc.work_path.is_none(), "nothing happens before OK"); - crate::dialogs::confirm(&mut app, dialog).unwrap(); - assert!(app.session.active().unwrap().doc.work_path.is_some()); - assert_eq!(app.session.journal.last().map(|(id, _)| id.as_str()), Some("select.toWorkPath")); - } - - #[test] - fn disabled_selection_rows_do_nothing() { - let mut app = app(); - app.ui.tool = Tool::MagicWand; - app.run("select.rect", json!({"x": 1, "y": 1, "width": 8, "height": 8})).unwrap(); - assert!(open(&mut app, &Context::default(), Tool::MagicWand, [10.0, 10.0])); - let menu = app.ui.canvas_tool_menu.clone().unwrap(); - // No filter has run and nothing can be faded yet. - for id in ["filter.lastFilter", "edit.fade"] { - assert!(!entry_enabled(&app, &menu, id), "{id} is greyed out"); - } - let before = app.session.journal.len(); - choose(&mut app, &Context::default(), "edit.fade"); - assert_eq!(app.session.journal.len(), before); - assert!(app.ui.dialogs.is_empty()); - // Rows of the other variant are not part of this menu. - assert!(open(&mut app, &Context::default(), Tool::MagicWand, [10.0, 10.0])); - choose(&mut app, &Context::default(), "select.all"); - assert_eq!(app.session.journal.len(), before); - } - - /// Photoshop's Zoom tool menu is Fit on Screen, 100%, 200%, Print Size, then Zoom In and Zoom - /// Out after a separator (#6005); Fill Screen (the Hand tool's) keeps its place by Fit on Screen. - #[test] - fn view_menu_follows_photoshop_order() { - assert_eq!( - labels(VIEW_MENU), - vec![Some("Fit on Screen"), Some("Fill Screen"), Some("100%"), Some("200%"), Some("Print Size"), None, Some("Zoom In"), Some("Zoom Out")] - ); - // Every row but Fill Screen (the Hand tool's options-bar button) is a View menu command. - let app = app(); - let items = crate::menus::menu_items(&app); - for (label, id) in VIEW_MENU.iter().flatten().filter(|(_, id)| *id != FILL_SCREEN) { - assert!(items.iter().any(|i| i.id == *id), "{label}: unknown command {id}"); - } - } - - fn zoom_app(w: u32, h: u32) -> PhotocraftApp { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": w, "height": h})).unwrap(); - app - } - - fn screen_of(app: &PhotocraftApp, doc: [f32; 2]) -> Pos2 { - crate::canvas::ViewXform::active(app).unwrap().to_screen(doc[0], doc[1]) - } - - #[test] - fn zoom_and_hand_right_click_opens_the_view_menu() { - for tool in [Tool::Zoom, Tool::Hand] { - let mut app = zoom_app(400, 300); - app.ui.tool = tool; - let mut h = harness(app); - let zoom = h.state().ui.views[0].zoom; - let inside = screen_of(h.state(), [300.0, 100.0]); - right_click(&mut h, inside, Modifiers::NONE); - let menu = h.state().ui.canvas_tool_menu.clone().unwrap_or_else(|| panic!("{tool:?}: right-click opens no menu")); - assert!(rows(&menu) == VIEW_MENU, "{tool:?}: the view menu"); - assert_eq!(h.state().ui.views[0].zoom, zoom, "{tool:?}: the right-click alone does not zoom"); - assert!(entry_enabled(h.state(), &menu, FILL_SCREEN) && entry_enabled(h.state(), &menu, "view.printSize")); - // Outside the image the pasteboard colour menu wins, as for the other tools. - h.state_mut().ui.canvas_tool_menu = None; - let outside = h.state().last_canvas_rect.min + vec2(5.0, 5.0); - right_click(&mut h, outside, Modifiers::NONE); - assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.pasteboard), "{tool:?}: pasteboard menu outside"); - } - } - - #[test] - fn view_menu_zoom_in_keeps_the_clicked_point_under_the_pointer() { - let mut app = zoom_app(400, 300); - app.ui.tool = Tool::Zoom; - let mut h = harness(app); - let zoom = h.state().ui.views[0].zoom; - let doc = [300.0, 100.0]; - let p = screen_of(h.state(), doc); - right_click(&mut h, p, Modifiers::NONE); - // Chosen in the menu itself: the canvas frame that draws the menu must keep the new view. - h.get_by_label("Zoom In").click(); - h.run_steps(3); - assert!(h.state().ui.canvas_tool_menu.is_none()); - let after = h.state().ui.views[0].zoom; - assert_eq!(after, crate::zoom_levels::step(zoom, 1, [400, 300]), "one Zoom In step"); - let s = screen_of(h.state(), doc); - assert!((s - p).length() < 1.0, "the right-clicked point stays put: {s:?} vs {p:?}"); - assert_eq!(h.state().session.journal.last().map(|(id, _)| id.as_str()), Some("view.zoomIn")); - // Zoom Out returns to where it was. - right_click(&mut h, p, Modifiers::NONE); - h.get_by_label("Zoom Out").click(); - h.run_steps(3); - assert_eq!(h.state().ui.views[0].zoom, zoom); - assert!((screen_of(h.state(), doc) - p).length() < 1.0); - } - - #[test] - fn animated_zoom_off_view_menu_keeps_the_anchor_without_a_transition() { - for command in ["view.zoomIn", "view.zoomOut", FILL_SCREEN] { - let mut app = zoom_app(400, 300); - app.ui.tool = Tool::Zoom; - app.run("prefs.set", json!({"values": {"general.animatedZoom": false, "tools.zoomClickedPointToCenter": false}})).unwrap(); - let mut h = harness(app); - let doc = [300.0, 100.0]; - let p = screen_of(h.state(), doc); - right_click(&mut h, p, Modifiers::NONE); - let ctx = h.ctx.clone(); - choose(h.state_mut(), &ctx, command); - assert!(!h.state().ui.views[0].zoom_animating, "{command}"); - h.step(); - let v = &h.state().ui.views[0]; - let xf = crate::canvas::ViewXform::active(h.state()).unwrap(); - assert_eq!((xf.zoom, xf.center), (v.zoom, v.center), "{command}"); - assert!(v.zoom_anchor.is_none() && v.zoom_transition.is_none(), "{command}"); - if command != FILL_SCREEN { - assert!(screen_of(h.state(), doc).distance(p) < 1.0, "{command}: preserve the clicked point"); - } - } - } - - #[test] - fn view_menu_zoom_keeps_its_anchor_during_the_animation() { - let mut app = zoom_app(400, 300); - app.ui.tool = Tool::Zoom; - let mut h = harness(app); - let zoom = h.state().ui.views[0].zoom; - let doc = [300.0, 100.0]; - let p = screen_of(h.state(), doc); - right_click(&mut h, p, Modifiers::NONE); - let ctx = h.ctx.clone(); - // Choose without the widget click helper, which runs repaint frames until settled. - choose(h.state_mut(), &ctx, "view.zoomIn"); - h.step(); - h.input_mut().time = Some(ctx.input(|i| i.time) + 0.11); - h.step(); - let displayed = crate::canvas::ViewXform::active(h.state()).unwrap(); - assert!(displayed.zoom > zoom && displayed.zoom < h.state().ui.views[0].zoom); - assert!(displayed.to_screen(doc[0], doc[1]).distance(p) < 1.0); - h.input_mut().time = Some(ctx.input(|i| i.time) + 0.3); - h.step(); - assert!(!h.state().ui.views[0].zoom_animating); - } - - #[test] - fn view_menu_zoom_in_centres_the_clicked_point_with_the_preference() { - let mut app = zoom_app(400, 300); - app.ui.tool = Tool::Hand; - app.run("prefs.set", json!({"path": "tools.zoomClickedPointToCenter", "value": true})).unwrap(); - let mut h = harness(app); - let doc = [300.0, 100.0]; - let p = screen_of(h.state(), doc); - right_click(&mut h, p, Modifiers::NONE); - h.get_by_label("Zoom In").click(); - h.run_steps(3); - assert_eq!(h.state().ui.views[0].center, doc); - } - - #[test] - fn view_menu_fits_fills_and_sets_fixed_zooms() { - let mut app = zoom_app(400, 300); - app.ui.tool = Tool::Zoom; - let mut h = harness(app); - let p = screen_of(h.state(), [200.0, 150.0]); - let area = crate::rulers::content_rect(h.state(), h.state().last_canvas_rect).size(); - let ppp = h.state().canvas_ppp(); - let pick = |h: &mut Harness<'static, PhotocraftApp>, label: &str| { - right_click(h, p, Modifiers::NONE); - h.get_by_label(label).click(); - h.run_steps(3); - h.state().ui.views[0].zoom - }; - assert_eq!(pick(&mut h, "200%"), 2.0); - // Fill Screen: the image covers the whole canvas (one axis can overflow). - let fill = pick(&mut h, "Fill Screen") / ppp; - assert!(400.0 * fill >= area.x - 1.0 && 300.0 * fill >= area.y - 1.0, "fill {fill} for {area:?}"); - assert!(400.0 * fill <= area.x + 1.0 || 300.0 * fill <= area.y + 1.0, "fill {fill} for {area:?}"); - assert_eq!(h.state().ui.views[0].center, [200.0, 150.0]); - // Fit on Screen: back to the whole image (capped at 100%, as on open). - let fit = pick(&mut h, "Fit on Screen") / ppp; - assert!(400.0 * fit <= area.x && 300.0 * fit <= area.y && fit < fill, "fit {fit} fill {fill}"); - } - - #[test] - fn view_menu_needs_finite_points_and_a_view_tool() { - let mut app = app(); - assert!(!open_view(&mut app, &Context::default(), Tool::Brush, [1.0, 1.0], [1.0, 1.0])); - assert!(!open_view(&mut app, &Context::default(), Tool::Zoom, [f32::NAN, 1.0], [1.0, 1.0])); - assert!(!open_view(&mut app, &Context::default(), Tool::Zoom, [1.0, 1.0], [f64::INFINITY, 1.0])); - assert!(app.ui.canvas_tool_menu.is_none()); - assert!(open_view(&mut app, &Context::default(), Tool::Zoom, [1.0, 1.0], [1.0, 1.0])); - let before = app.session.journal.len(); - choose(&mut app, &Context::default(), "select.all"); - assert_eq!(app.session.journal.len(), before, "the view menu cannot run another menu's row"); - // With no document every row is greyed out and choosing one does nothing. - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - assert!(open_view(&mut app, &Context::default(), Tool::Hand, [1.0, 1.0], [1.0, 1.0])); - let menu = app.ui.canvas_tool_menu.clone().unwrap(); - for (_, id) in VIEW_MENU.iter().flatten() { - assert!(!entry_enabled(&app, &menu, id), "{id} is greyed out with no document"); - } - choose(&mut app, &Context::default(), FILL_SCREEN); - choose(&mut app, &Context::default(), "view.zoomIn"); - } - - #[test] - fn unsupported_tools_and_nonfinite_positions_do_not_open_menu() { - let mut app = app(); - assert!(!open(&mut app, &Context::default(), Tool::Brush, [1.0, 1.0])); - assert!(!open(&mut app, &Context::default(), Tool::Lasso, [f32::NAN, 1.0])); - assert!(app.ui.canvas_tool_menu.is_none()); - assert!(open(&mut app, &Context::default(), Tool::MagicWand, [1.0, 1.0])); - let before = app.session.journal.len(); - choose(&mut app, &Context::default(), "file.new"); - assert_eq!(app.session.journal.len(), before, "context menu cannot invoke an unrelated command"); - } - - #[test] - fn completed_pen_path_right_click_makes_selection() { - let mut app = app(); - app.ui.tool = Tool::Pen; - for (x, y) in [(2.0, 2.0), (20.0, 2.0), (20.0, 20.0)] { - crate::vector_ui::pen_down(&mut app, x, y, false); - crate::vector_ui::pen_up(&mut app); - } - crate::vector_ui::pen_commit(&mut app, true); - assert!(app.session.active().unwrap().doc.work_path.is_some()); - let mut h = harness(app); - let center = h.state().last_canvas_rect.center(); - right_click(&mut h, center, Modifiers::NONE); - assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.tool == Tool::Pen && m.has_path)); - let ctx = h.ctx.clone(); - choose(h.state_mut(), &ctx, "path.toSelection"); - let dialog = h.state().ui.dialogs.last().map(|d| d.id).unwrap(); - crate::dialogs::confirm(h.state_mut(), dialog).unwrap(); - assert!(h.state().session.active().unwrap().doc.selection.is_some()); - assert_eq!(h.state().session.journal.last().map(|(id, _)| id.as_str()), Some("path.toSelection")); - } - - #[test] - fn pen_menu_finishes_in_progress_path_before_selection() { - let mut app = app(); - app.ui.tool = Tool::Pen; - for (x, y) in [(2.0, 2.0), (20.0, 2.0), (20.0, 20.0)] { - crate::vector_ui::pen_down(&mut app, x, y, false); - crate::vector_ui::pen_up(&mut app); - } - assert!(app.session.active().unwrap().doc.work_path.is_none()); - assert!(open(&mut app, &Context::default(), Tool::Pen, [10.0, 10.0])); - let menu = app.ui.canvas_tool_menu.as_ref().unwrap(); - assert!(entry_enabled(&app, menu, "path.toSelection")); - choose(&mut app, &Context::default(), "path.toSelection"); - let dialog = app.ui.dialogs.last().map(|d| d.id).unwrap(); - crate::dialogs::confirm(&mut app, dialog).unwrap(); - assert!(app.session.active().unwrap().doc.work_path.is_some()); - assert!(app.session.active().unwrap().doc.selection.is_some()); - } - - /// #5703: the Pen options bar's Make Selection (Path mode) opens the same dialog for the path - /// being drawn (finished into the Work Path first), and OK selects inside it; with no path at - /// all it reports that instead. - #[test] - fn pen_options_bar_makes_a_selection_from_the_path() { - let mut app = app(); - app.ui.tool = Tool::Pen; - assert!(make_selection(&mut app).is_err(), "no path yet"); - assert!(app.ui.dialogs.is_empty()); - for (x, y) in [(2.0, 2.0), (20.0, 2.0), (20.0, 20.0)] { - crate::vector_ui::pen_down(&mut app, x, y, false); - crate::vector_ui::pen_up(&mut app); - } - make_selection(&mut app).unwrap(); - let dialog = app.ui.dialogs.last().map(|d| d.id).unwrap(); - crate::dialogs::confirm(&mut app, dialog).unwrap(); - let st = app.session.active().unwrap(); - assert!(st.doc.work_path.is_some() && st.doc.selection.is_some()); - // The active (Work) path again, with no pen path in progress. - app.run("select.deselect", json!({})).unwrap(); - make_selection(&mut app).unwrap(); - let dialog = app.ui.dialogs.last().map(|d| d.id).unwrap(); - crate::dialogs::confirm(&mut app, dialog).unwrap(); - assert!(app.session.active().unwrap().doc.selection.is_some()); - // Drawn with a saved path selected, the path is added to that one (#4721): the dialog is - // for it, not for a Work Path. - app.run("path.rename", json!({"name": "work", "to": "Cutout"})).unwrap(); - app.ui.selected_path = Some("Cutout".into()); - for (x, y) in [(4.0, 24.0), (12.0, 24.0), (12.0, 30.0)] { - crate::vector_ui::pen_down(&mut app, x, y, false); - crate::vector_ui::pen_up(&mut app); - } - make_selection(&mut app).unwrap(); - assert_eq!(app.ui.dialogs.last().and_then(|d| d.fields.get("name")), Some(&json!("Cutout"))); - } - - /// #1056: the Path Selection and Direct Selection tools' right-click opens the path menu for - /// the selected path, as the Pen's does, instead of nothing. - #[test] - fn path_selection_tools_open_the_path_menu() { - for tool in [Tool::PathSelection, Tool::DirectSelection] { - let mut app = app(); - app.ui.tool = Tool::Pen; - for (x, y) in [(2.0, 2.0), (20.0, 2.0), (20.0, 20.0)] { - crate::vector_ui::pen_down(&mut app, x, y, false); - crate::vector_ui::pen_up(&mut app); - } - crate::vector_ui::pen_commit(&mut app, false); - assert!(app.session.active().unwrap().doc.work_path.is_some()); - app.ui.tool = tool; - assert!(applies(tool)); - assert!(open(&mut app, &Context::default(), tool, [10.0, 10.0]), "{tool:?}"); - let menu = app.ui.canvas_tool_menu.clone().unwrap(); - assert_eq!(rows(&menu), PEN_MENU, "{tool:?}"); - assert!(menu.has_path && entry_enabled(&app, &menu, "path.toSelection"), "{tool:?}"); - choose(&mut app, &Context::default(), "path.toSelection"); - let dialog = app.ui.dialogs.last().map(|d| d.id).unwrap(); - crate::dialogs::confirm(&mut app, dialog).unwrap(); - assert!(app.session.active().unwrap().doc.selection.is_some(), "{tool:?}: Make Selection made one"); - } - } - - #[test] - fn pen_menu_has_all_reference_rows_in_order_and_guards_unavailable_actions() { - let labels: Vec<_> = PEN_MENU.iter().map(|row| row.map(|(label, _)| label)).collect(); - assert_eq!( - labels, - vec![ - Some("Create Vector Mask"), - Some("Delete Path"), - None, - Some("Define Custom Shape…"), - None, - Some("Make Selection…"), - Some("New Guides From Shape"), - Some("Fill Path…"), - Some("Stroke Path…"), - None, - Some("Clipping Path…"), - None, - Some("Free Transform Path"), - None, - Some("Unite Shapes"), - Some("Subtract Front Shape"), - Some("Unite Shapes at Overlap"), - Some("Subtract Shapes at Overlap"), - None, - Some("Copy Fill"), - Some("Copy Complete Stroke"), - None, - Some("Paste Fill"), - Some("Paste Complete Stroke"), - None, - Some("Isolate Layers"), - None, - Some("Make Symmetry Path"), - Some("Disable Symmetry Path"), - ] - ); - let mut app = app(); - app.ui.tool = Tool::Pen; - assert!(open(&mut app, &Context::default(), Tool::Pen, [10.0, 10.0])); - let menu = app.ui.canvas_tool_menu.as_ref().unwrap(); - assert!(!entry_enabled(&app, menu, "path.toSelection")); - let before = app.session.journal.len(); - choose(&mut app, &Context::default(), "path.toSelection"); - assert_eq!(app.session.journal.len(), before); - assert!(app.ui.dialogs.is_empty()); - } - - #[test] - fn pen_menu_creates_mask_deletes_path_and_opens_named_path_dialogs() { - let mut app = app(); - app.ui.tool = Tool::Pen; - work_path(&mut app); - choose_open(&mut app, "layer.vectorMask.fromPath"); - let st = app.session.active().unwrap(); - assert!(st.active_layer.and_then(|id| st.doc.layer(id)).is_some_and(|l| l.vector_mask.is_some())); - // The new vector mask's path becomes the active one (#4728); pick the Work Path again. - assert_eq!(app.ui.selected_path.as_deref(), Some("layer")); - app.ui.selected_path = Some("work".into()); - choose_open(&mut app, "edit.defineCustomShape"); - let id = app.ui.dialogs.last().map(|d| d.id).unwrap(); - let fields = &app.ui.dialogs.last().unwrap().fields; - assert_eq!(fields.get("path"), Some(&json!("work"))); - app.ui.dialog_mut(id).unwrap().fields.insert("name".into(), json!("Menu Shape")); - crate::dialogs::confirm(&mut app, id).unwrap(); - assert!(app.session.edit_state.custom_shapes.iter().any(|s| s.name == "Menu Shape")); - choose_open(&mut app, "path.fill"); - let id = app.ui.dialogs.last().map(|d| d.id).unwrap(); - assert_eq!(app.ui.dialogs.last().unwrap().fields.get("name"), Some(&json!("work"))); - crate::dialogs::confirm(&mut app, id).unwrap(); - assert_eq!(app.session.journal.last().map(|(id, _)| id.as_str()), Some("path.fill")); - choose_open(&mut app, "path.delete"); - assert!(app.session.active().unwrap().doc.work_path.is_none()); - } - - #[test] - fn pen_menu_saved_path_clipping_and_numeric_transform() { - let mut app = app(); - app.ui.tool = Tool::Pen; - work_path(&mut app); - app.run("path.rename", json!({"name": "work", "to": "Cutout"})).unwrap(); - app.ui.selected_path = Some("Cutout".into()); - assert!(open(&mut app, &Context::default(), Tool::Pen, [10.0, 10.0])); - assert!(entry_enabled(&app, app.ui.canvas_tool_menu.as_ref().unwrap(), "path.clippingPath.set")); - choose(&mut app, &Context::default(), "path.clippingPath.set"); - let id = app.ui.dialogs.last().map(|d| d.id).unwrap(); - app.ui.dialog_mut(id).unwrap().fields.insert("flatness".into(), json!(2.0)); - crate::dialogs::confirm(&mut app, id).unwrap(); - assert_eq!(app.session.active().unwrap().doc.clipping_path.as_ref().map(|p| p.name.as_str()), Some("Cutout")); - choose_open(&mut app, "path.transform"); - let id = app.ui.dialogs.last().map(|d| d.id).unwrap(); - app.ui.dialog_mut(id).unwrap().fields.insert("translateX".into(), json!(5.0)); - crate::dialogs::confirm(&mut app, id).unwrap(); - assert_eq!(app.session.journal.last().map(|(id, _)| id.as_str()), Some("path.transform")); - } - - #[test] - fn pen_shape_menu_enables_shape_ops_and_style_copy_only_when_applicable() { - let mut app = app(); - app.ui.tool = Tool::Pen; - app.run( - "shape.create", - json!({"kind":"path", "path":{"subpaths":[ - {"closed":true,"knots":[[2,2],[20,2],[20,20]]}, - {"closed":true,"knots":[[5,5],[10,5],[10,10]]} - ]}, "fill":"#ff0000", "stroke":{"width":2,"color":"#000000"}}), - ) - .unwrap(); - assert!(open(&mut app, &Context::default(), Tool::Pen, [10.0, 10.0])); - let menu = app.ui.canvas_tool_menu.as_ref().unwrap(); - assert!(entry_enabled(&app, menu, "layer.combineShapes.unite")); - assert!(entry_enabled(&app, menu, "path.style.copyFill")); - assert!(!entry_enabled(&app, menu, "path.style.pasteFill")); - assert!(!entry_enabled(&app, menu, "path.fill")); - choose(&mut app, &Context::default(), "path.style.copyFill"); - assert!(app.session.path_fill_clipboard.is_some()); - assert!(open(&mut app, &Context::default(), Tool::Pen, [10.0, 10.0])); - assert!(entry_enabled(&app, app.ui.canvas_tool_menu.as_ref().unwrap(), "path.style.pasteFill")); - } - - #[test] - fn unfinished_shape_path_disables_actions_that_would_target_the_previous_layer() { - let mut app = app(); - app.ui.tool = Tool::Pen; - app.ui.tool_options.vector_mode = "shape".into(); - for (x, y) in [(2.0, 2.0), (20.0, 2.0), (20.0, 20.0)] { - crate::vector_ui::pen_down(&mut app, x, y, false); - crate::vector_ui::pen_up(&mut app); - } - assert!(open(&mut app, &Context::default(), Tool::Pen, [10.0, 10.0])); - let menu = app.ui.canvas_tool_menu.as_ref().unwrap(); - for id in ["layer.vectorMask.fromPath", "path.delete", "path.fill", "path.stroke", "path.clippingPath.set", "view.newGuidesFromShape"] { - assert!(!entry_enabled(&app, menu, id), "{id} must not act on the layer replaced by the pending shape"); - } - assert!(entry_enabled(&app, menu, "path.toSelection")); - } - - /// A 32 × 32 document with the Crop tool picked (Classic Mode, so the view stays put) and its - /// untouched default frame. - fn crop_app() -> PhotocraftApp { - let mut app = app(); - app.ui.tool = Tool::Crop; - app.ui.tool_options.crop_shield.classic_mode = true; - app.ui.extras.snap = false; - crate::crop_ui::ensure_frame(&mut app); - app - } - - /// Draws a crop frame from (4, 4) to (28, 28): a pending crop. Returns the frame. - fn draw_crop(app: &mut PhotocraftApp) -> [f64; 4] { - use crate::canvas::{ToolEvent, tool_event}; - tool_event(app, ToolEvent::Down { x: 4.0, y: 4.0, pressure: 1.0 }, Modifiers::NONE); - tool_event(app, ToolEvent::Move { x: 16.0, y: 16.0, pressure: 1.0 }, Modifiers::NONE); - tool_event(app, ToolEvent::Move { x: 28.0, y: 28.0, pressure: 1.0 }, Modifiers::NONE); - tool_event(app, ToolEvent::Up { x: 28.0, y: 28.0 }, Modifiers::NONE); - assert!(crate::crop_ui::pending(app), "the drag draws a pending frame"); - app.ui.crop_rect.unwrap() - } - - fn aspect(r: [f64; 4]) -> f64 { - (r[2] - r[0]) / (r[3] - r[1]) - } - - /// #6561: right-click on a pending crop opens its menu without touching the frame, and a ratio - /// row refits the frame as the options bar's dropdown does. - #[test] - fn right_click_on_a_pending_crop_opens_the_crop_menu_and_a_ratio_refits_the_frame() { - let mut app = crop_app(); - let frame = draw_crop(&mut app); - let mut h = harness(app); - let center = h.state().last_canvas_rect.center(); - right_click(&mut h, center, Modifiers::NONE); - let menu = h.state().ui.canvas_tool_menu.clone().expect("right-click on a pending crop opens a menu"); - assert_eq!(h.state().ui.crop_rect, Some(frame), "the right-click leaves the frame alone"); - assert!(available(h.state(), &menu, "crop.ratio.16:9"), "the menu lists the options bar's ratios"); - let ctx = h.ctx.clone(); - choose(h.state_mut(), &ctx, "crop.ratio.16:9"); - assert_eq!(h.state().ui.tool_options.crop_ratio, "16:9"); - let r = h.state().ui.crop_rect.unwrap(); - assert!((aspect(r) - 16.0 / 9.0).abs() < 1e-9, "the frame is 16 : 9 now: {r:?}"); - assert!(r[0] >= frame[0] && r[1] >= frame[1] && r[2] <= frame[2] && r[3] <= frame[3], "fitted inside the old frame: {r:?}"); - assert!(h.state().ui.canvas_tool_menu.is_none()); - } - - #[test] - fn untouched_crop_frame_has_no_menu_and_a_pending_one_wins_over_the_pasteboard() { - let mut h = harness(crop_app()); - let rect = h.state().last_canvas_rect; - let outside = rect.min + vec2(5.0, 5.0); - right_click(&mut h, rect.center(), Modifiers::NONE); - assert!(h.state().ui.canvas_tool_menu.is_none(), "the tool's untouched frame is no crop in progress"); - right_click(&mut h, outside, Modifiers::NONE); - assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.pasteboard), "outside: the pasteboard menu, as before"); - h.state_mut().ui.canvas_tool_menu = None; - draw_crop(h.state_mut()); - h.run_steps(2); - right_click(&mut h, outside, Modifiers::NONE); - let menu = h.state().ui.canvas_tool_menu.clone().unwrap(); - assert!(menu.crop.is_some() && !menu.pasteboard, "with a crop pending, its menu also outside the image"); - } - - /// A harness in the app's order: shortcuts (the crop's Esc and ↵ among them), then the canvas. - fn shortcut_harness(mut app: PhotocraftApp) -> Harness<'static, PhotocraftApp> { - app.sync_views(); - let mut h = Harness::builder().with_size(vec2(1000.0, 700.0)).build_ui_state( - |ui, app: &mut PhotocraftApp| { - let ctx = ui.ctx().clone(); - if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { - return; - } - crate::shortcuts::handle(app, &ctx); - egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); - }, - app, - ); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::default()); - h.run_steps(4); - h - } - - #[test] - fn esc_closes_only_the_crop_menu() { - let mut app = crop_app(); - let frame = draw_crop(&mut app); - let mut h = shortcut_harness(app); - let center = h.state().last_canvas_rect.center(); - right_click(&mut h, center, Modifiers::NONE); - assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.crop.is_some())); - h.key_press(egui::Key::Escape); - h.run_steps(2); - assert!(h.state().ui.canvas_tool_menu.is_none(), "Esc closes the menu"); - assert_eq!(h.state().ui.crop_rect, Some(frame), "and only the menu: the crop is not cancelled"); - assert!(crate::crop_ui::pending(h.state())); - } - - /// ↵ under the open crop menu doesn't commit the crop beneath it. - #[test] - fn enter_under_the_crop_menu_does_not_crop() { - let mut app = crop_app(); - let frame = draw_crop(&mut app); - let mut h = shortcut_harness(app); - let size = h.state().session.active().map(|s| s.doc.size); - let center = h.state().last_canvas_rect.center(); - right_click(&mut h, center, Modifiers::NONE); - assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.crop.is_some())); - h.key_press(egui::Key::Enter); - h.run_steps(2); - assert_eq!(h.state().session.active().map(|s| s.doc.size), size, "↵ under the menu doesn't crop"); - assert_eq!(h.state().ui.crop_rect, Some(frame)); - assert!(crate::crop_ui::pending(h.state())); - } - - /// A right-click while the left button drags the crop frame opens no menu over the drag, on - /// the image or outside it (no pasteboard menu either), and the menu opens again once the left - /// button is up, though egui ended that drag without a release of its own. - #[test] - fn no_crop_menu_while_the_left_button_drags_the_frame() { - let mut app = crop_app(); - draw_crop(&mut app); - let mut h = harness(app); - let rect = h.state().last_canvas_rect; - let (center, outside) = (rect.center(), rect.min + vec2(5.0, 5.0)); - let left = |pos, pressed| egui::Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; - h.event(egui::Event::PointerMoved(center)); - h.run_steps(1); - h.event(left(center, true)); - h.run_steps(1); - for k in 1..=4 { - h.event(egui::Event::PointerMoved(center + vec2(8.0 * k as f32, 0.0))); - h.run_steps(1); - } - assert!(h.state().crop.drag.is_some(), "the left button drags the frame"); - let held = center + vec2(32.0, 0.0); - right_click(&mut h, held, Modifiers::NONE); - assert!(h.state().ui.canvas_tool_menu.is_none(), "no crop menu over the drag"); - right_click(&mut h, outside, Modifiers::NONE); - assert!(h.state().ui.canvas_tool_menu.is_none(), "nor the pasteboard menu outside the image"); - h.event(egui::Event::PointerMoved(held)); - h.event(left(held, false)); - h.run_steps(2); - right_click(&mut h, center, Modifiers::NONE); - assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.crop.is_some()), "with the button up the menu opens"); - } - - /// The left button down with no crop gesture under way (a press egui doesn't take for a drag - /// yet, or one whose release was lost to an Alt+Tab or a cancelled touch) doesn't keep the - /// crop menu shut. - #[test] - fn a_left_button_down_without_a_crop_drag_keeps_the_crop_menu() { - let mut app = crop_app(); - draw_crop(&mut app); - let mut h = harness(app); - let center = h.state().last_canvas_rect.center(); - h.event(egui::Event::PointerMoved(center)); - h.run_steps(1); - h.event(egui::Event::PointerButton { pos: center, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); - h.run_steps(1); - assert!(h.ctx.input(|i| i.pointer.primary_down()) && h.state().crop.drag.is_none(), "down, dragging nothing"); - right_click(&mut h, center, Modifiers::NONE); - assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.crop.is_some()), "the crop menu opens"); - } - - /// Nor does a right-click open a menu over a Straighten line the left button still draws. - #[test] - fn no_crop_menu_while_the_left_button_draws_a_straighten_line() { - let mut app = crop_app(); - draw_crop(&mut app); - crate::crop_straighten::toggle(&mut app); - let mut h = harness(app); - let center = h.state().last_canvas_rect.center(); - let left = |pos, pressed| egui::Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; - h.event(egui::Event::PointerMoved(center)); - h.run_steps(1); - h.event(left(center, true)); - h.run_steps(1); - for k in 1..=4 { - h.event(egui::Event::PointerMoved(center + vec2(8.0 * k as f32, 4.0))); - h.run_steps(1); - } - assert!(h.state().crop.straighten.line.is_some() && h.state().crop.drag.is_none(), "the left button draws a Straighten line"); - right_click(&mut h, center + vec2(32.0, 4.0), Modifiers::NONE); - assert!(h.state().ui.canvas_tool_menu.is_none(), "no menu over the line"); - } - - /// A finger held still on a pending crop (a touch screen's press-and-hold right-click) opens - /// the crop menu, though the touch counts as the primary button down. - #[test] - fn a_finger_held_on_a_pending_crop_opens_the_crop_menu() { - let mut app = crop_app(); - let frame = draw_crop(&mut app); - let mut h = harness(app); - let at = h.state().last_canvas_rect.center(); - let touch = |phase| egui::Event::Touch { device_id: egui::TouchDeviceId(1), id: egui::TouchId(1), phase, pos: at, force: None }; - let button = |pressed| egui::Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; - h.input_mut().events.extend([egui::Event::PointerMoved(at), touch(egui::TouchPhase::Start), button(true)]); - h.step(); - // Held past egui's max_click_duration (0.8 s) without moving. - for _ in 0..120 { - if h.state().ui.canvas_tool_menu.is_some() { - break; - } - h.step(); - } - assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.crop.is_some()), "the held finger opens the crop menu"); - h.input_mut().events.extend([touch(egui::TouchPhase::End), button(false)]); - h.run_steps(2); - assert_eq!(h.state().ui.crop_rect, Some(frame), "the hold leaves the frame alone"); - } - - #[test] - fn crop_menu_rows_act_like_the_options_bar() { - use crate::crop_overlay::{CropOverlay, OverlayShow}; - let ctx = Context::default(); - let mut app = crop_app(); - draw_crop(&mut app); - // Space's Hand held over the Crop tool keeps its own right-click. - assert!(!open_crop(&mut app, &ctx, Tool::Hand, [10.0, 10.0])); - let reopen = |app: &mut PhotocraftApp| { - assert!(open_crop(app, &Context::default(), Tool::Crop, [10.0, 10.0])); - app.ui.canvas_tool_menu.clone().unwrap() - }; - // Nothing to save with a free ratio, nothing to delete without saved presets. - let menu = reopen(&mut app); - assert!(!entry_enabled(&app, &menu, CROP_NEW) && !entry_enabled(&app, &menu, CROP_DELETE)); - assert!(mode_checked(&app, &menu, "crop.ratio."), "free Ratio is checked, as in the dropdown"); - // A size preset fills W x H x Resolution, which the menu checks, as the dropdown does. - choose(&mut app, &ctx, "crop.ratio.preset:4x5in"); - let menu = reopen(&mut app); - assert!(mode_checked(&app, &menu, "crop.ratio.whr") && !mode_checked(&app, &menu, "crop.ratio.preset:4x5in")); - assert!((aspect(app.ui.crop_rect.unwrap()) - 0.8).abs() < 1e-9); - assert!(entry_enabled(&app, &menu, CROP_NEW)); - // Clear empties W x H x Resolution, as the bar's Clear. - choose(&mut app, &ctx, CROP_CLEAR); - assert_eq!(app.ui.tool_options.crop_width, ""); - // Overlays: another overlay starts at its first orientation; when it shows. - app.ui.tool_options.crop_overlay = CropOverlay::GoldenSpiral; - app.ui.tool_options.crop_overlay_orientation = 2; - reopen(&mut app); - choose(&mut app, &ctx, "crop.overlay.triangle"); - assert_eq!((app.ui.tool_options.crop_overlay, app.ui.tool_options.crop_overlay_orientation), (CropOverlay::Triangle, 0)); - reopen(&mut app); - choose(&mut app, &ctx, "crop.overlayShow.never"); - assert_eq!(app.ui.tool_options.crop_overlay_show, OverlayShow::Never); - let menu = reopen(&mut app); - assert!(mode_checked(&app, &menu, "crop.overlay.triangle") && mode_checked(&app, &menu, "crop.overlayShow.never")); - // A saved preset is listed by name; picking it refits the frame to its W x H, though the - // ratio key is "whr" before and after. - app.ui.canvas_tool_menu = None; - app.ui.tool_options.crop_ratio = crate::crop_size::WHR.into(); - let saved = json!({"crop_ratio": "whr", "crop_width": "300 px", "crop_height": "100 px", "crop_resolution": "72", "crop_resolution_unit": "px/in"}); - app.run("tool.presets.new", json!({"name": "Banner", "tool": "crop", "options": {"toolOptions": saved}})).unwrap(); - let menu = reopen(&mut app); - let banner = crop_rows(&menu).into_iter().flatten().find(|(l, _)| l == "Banner").expect("the saved preset is a row").1; - assert!(entry_enabled(&app, &menu, CROP_DELETE)); - choose(&mut app, &ctx, &banner); - assert_eq!(app.ui.tool_options.crop_width, "300 px"); - assert!((aspect(app.ui.crop_rect.unwrap()) - 3.0).abs() < 1e-9, "the frame follows the preset: {:?}", app.ui.crop_rect); - let menu = reopen(&mut app); - assert!(mode_checked(&app, &menu, &banner)); - // Crop commits as ↵ does: the preset's size. - choose(&mut app, &ctx, CROP_COMMIT); - let size = app.session.active().unwrap().doc.size; - assert_eq!((size.width, size.height), (300, 100)); - // Cancel drops a pending crop. - draw_crop(&mut app); - reopen(&mut app); - choose(&mut app, &ctx, CROP_CANCEL); - assert!(!crate::crop_ui::pending(&app)); - } -} diff --git a/crates/ui-egui/src/channel_view.rs b/crates/ui-egui/src/channel_view.rs deleted file mode 100644 index 0a5e1958a3..0000000000 --- a/crates/ui-egui/src/channel_view.rs +++ /dev/null @@ -1,745 +0,0 @@ -//! Channel display on the canvas: alpha / spot / Quick Mask colour overlays, single colour -//! channel views (grayscale) and hidden colour channels. -//! -//! The document composite (GPU or CPU) is untouched. When the Channels panel shows anything other -//! than the plain composite, one extra texture is drawn over it: transparent overlay pixels when -//! the composite stays visible, an opaque picture otherwise. The texture is keyed by document -//! revision and view state and updated per damage rectangle while painting, so nothing is -//! recomposited per frame. - -use egui::{Color32, TextureOptions}; -use photocraft_doc::{AlphaChannel, ColorMode, Document}; -use photocraft_engine::channel_cmds::{ChannelView, color_count}; -use photocraft_engine::mask_view_cmds::MaskViewMode; -use photocraft_geom::Rect; -use photocraft_raster::{Surface, from_rgba, to_rgba}; - -use crate::PhotocraftApp; - -/// Largest overlay texture side; bigger documents show a downsampled overlay. -const MAX_SIDE: u32 = 4096; -/// Limit the sampled float composite to 128 MiB across open documents. -const MAX_COMPOSITE_CACHE_PIXELS: usize = 8 * 1024 * 1024; - -struct SampledComposite { - revision: u64, - /// `revision` minus the view-only part: what the pixels depend on. - content: u64, - preview_key: u64, - factor: u32, - pixels: Vec<[f32; 4]>, -} - -struct CompositeSource<'a> { - cached: Option<&'a [[f32; 4]]>, - fresh: &'a mut Option>, -} - -pub struct Cache { - revision: u64, - key: u64, - /// The canvas document shown by a live stroke (0 is the committed document). - pub(crate) preview_key: u64, - factor: u32, - /// False while the plain composite shows: the texture is kept (so toggling a view back on - /// reuses its allocation) but its pixels are stale. - valid: bool, - tex: egui::TextureHandle, - source: Option, -} - -fn sample(s: &Surface, r: Rect, factor: u32) -> Vec { - let (w, h) = (r.width().div_ceil(factor), r.height().div_ceil(factor)); - if factor == 1 { - let mut v = Vec::new(); - s.read_region_into(r, &mut v); - let ch = s.channels(); - return if ch > 1 { v.chunks_exact(ch).map(|p| p[0]).collect() } else { v }; - } - let mut out = Vec::with_capacity((w * h) as usize); - let mut row = vec![0.0f32; w as usize]; - for y in 0..h { - s.sample_row_strided(r.y0 + (y * factor) as i32, r.x0, factor as i32, 0, &mut row); - out.extend_from_slice(&row); - } - out -} - -/// How the view draws what it shows. -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct Look { - /// Single colour channels tinted instead of grayscale (Photoshop's "Show Channels in Color"). - pub in_color: bool, - /// The layer mask rubylith's colour and opacity (0..1): Layer Mask Display Options. - pub mask_rgb: [f32; 3], - pub mask_opacity: f32, -} - -impl Default for Look { - /// Photoshop's: grayscale channels, a red rubylith at 50 %. - fn default() -> Self { - Self { in_color: false, mask_rgb: AlphaChannel::DEFAULT_COLOR.to_rgb(), mask_opacity: 0.5 } - } -} - -impl Look { - /// The current preferences of `s`. - pub fn of(s: &photocraft_engine::Session) -> Self { - let p = s.prefs(); - Self { in_color: p.interface.show_channels_in_color, mask_rgb: p.layer_mask_overlay.rgb(), mask_opacity: p.layer_mask_overlay.alpha() } - } -} - -/// Composite RGBA (over white, like Photoshop's channel views) at `factor` stride. -/// Render in bands instead of allocating a full-resolution float composite to sample a preview. -fn composite(doc: &Document, r: Rect, factor: u32) -> Vec<[f32; 4]> { - let (w, h) = (r.width().div_ceil(factor), r.height().div_ceil(factor)); - let mut out = Vec::with_capacity((w * h) as usize); - let f = factor as i32; - let _ = photocraft_compose::render_bands(doc, r, 0, |band| -> Result<(), ()> { - let first = band.rect.y0 + (r.y0 - band.rect.y0).rem_euclid(f); - for y in (first..band.rect.y1).step_by(factor as usize) { - for x in (r.x0..r.x1).step_by(factor as usize) { - let p = band.get(x, y); - let a = p[3].clamp(0.0, 1.0); - out.push([p[0] * a + 1.0 - a, p[1] * a + 1.0 - a, p[2] * a + 1.0 - a, 1.0]); - } - } - Ok(()) - }); - out -} - -/// The channel view of `r` (document pixels, sampled every `factor` px) as premultiplied pixels, -/// or `None` when the plain composite is all there is to show. -pub fn render(doc: &Document, v: &ChannelView, r: Rect, factor: u32, look: Look, active: Option) -> Option> { - let mut unused = None; - render_with_source(doc, v, r, factor, look, active, CompositeSource { cached: None, fresh: &mut unused }) -} - -fn render_with_source( - doc: &Document, - v: &ChannelView, - r: Rect, - factor: u32, - look: Look, - active: Option, - source: CompositeSource<'_>, -) -> Option> { - if v.is_plain(doc) || r.is_empty() { - return None; - } - let in_color = look.in_color; - let (mask_rgb, mask_opacity) = (look.mask_rgb, look.mask_opacity.clamp(0.0, 1.0)); - let layer_mask = v.shown_layer_mask(doc); - // ⌥-click mask view (#196): the pixel mask alone, in grayscale (white reveals); ⇧⌥ with - // nothing else shown: just the rubylith. Use the compositor's cached feather for the pixel - // mask, but leave vector masks out: this view targets the pixel mask channel by itself. - let feathered_mask = v - .layer_mask - .and_then(|view| doc.layer(view.layer)) - .filter(|layer| layer.mask.as_ref().is_some_and(|mask| mask.enabled && photocraft_compose::masks::feather_sigma(mask.feather) > 0.0)) - .and_then(|layer| { - let mut pixel_mask_layer = layer.clone(); - pixel_mask_layer.vector_mask = None; - photocraft_compose::masks::combined_mask(&pixel_mask_layer, doc.bounds()) - }); - let shown_mask = layer_mask.map(|(m, mode)| (feathered_mask.as_ref().unwrap_or(&m.surface), mode)); - let only_mask = ChannelView { layer_mask: None, ..v.clone() }.is_plain(doc); - match shown_mask { - Some((m, MaskViewMode::Gray)) => return Some(mask_px(m, r, factor, |g| Color32::from_gray(q(g)))), - Some((m, MaskViewMode::Overlay)) if only_mask => { - let c = mask_rgb; - return Some(mask_px(m, r, factor, |g| { - let a = mask_opacity * (1.0 - g.clamp(0.0, 1.0)); - Color32::from_rgba_premultiplied(q(c[0] * a), q(c[1] * a), q(c[2] * a), q(a)) - })); - } - _ => {} - } - let colors = color_count(doc); - let vis = v.visible_colors(colors); - let (w, h) = (r.width().div_ceil(factor), r.height().div_ceil(factor)); - let n = (w * h) as usize; - let mut overlays: Vec<&AlphaChannel> = (0..doc.channels.len()).filter(|i| v.alpha_shown(*i)).map(|i| &doc.channels[i]).collect(); - let gray = |s: &Surface| sample(s, r, factor).into_iter().map(|g| [g, g, g, 1.0]).collect(); - // Premultiplied RGBA accumulator. With no colour channel left, the channel being edited - // (alpha, Quick Mask, or layer mask) is the picture — grayscale, not a rubylith over nothing. - let mut solo_quick = false; - let mut solo_mask = false; - let mut out: Vec<[f32; 4]> = if vis == 0 { - if !overlays.is_empty() { - let first = overlays.remove(0); - gray(&first.surface) - } else if let Some(q) = doc.quick_mask.as_ref().filter(|_| !v.quick_mask_hidden) { - solo_quick = true; - gray(&q.surface) - } else if let Some((m, _)) = shown_mask { - solo_mask = true; - gray(m) - } else { - let m = active.and_then(|id| doc.layer(id)).and_then(|l| l.mask.as_ref())?; - solo_mask = true; - gray(&m.surface) - } - } else if vis < colors { - let fmt = doc.pixel_format(); - let mode = fmt.mode; - let shown: Vec = (0..colors).filter(|k| v.color_visible(*k)).collect(); - let computed = if source.cached.is_some_and(|px| px.len() == n) { None } else { Some(composite(doc, r, factor)) }; - let pixels = source.cached.filter(|px| px.len() == n).or(computed.as_deref())?; - let converted = pixels - .iter() - .copied() - .map(|rgba| { - let mut native = from_rgba(&fmt, rgba); - if shown.len() == 1 && !in_color { - let x = native[shown[0]]; - // Ink channels read dark where there is ink. - let g = if mode == ColorMode::Cmyk { 1.0 - x } else { x }; - return [g, g, g, 1.0]; - } - for (k, x) in native[..colors].iter_mut().enumerate() { - if !v.color_visible(k) { - // Hidden channels contribute nothing (Lab: neutral a/b, and a neutral - // Lightness under Show Channels in Color, so an isolated a/b channel - // tints over mid gray instead of black, as Photoshop does). - *x = if mode == ColorMode::Lab && (k > 0 || in_color) { 0.5 } else { 0.0 }; - } - } - let c = to_rgba(&fmt, &native); - [c[0], c[1], c[2], 1.0] - }) - .collect(); - if n <= MAX_COMPOSITE_CACHE_PIXELS { - *source.fresh = computed; - } - converted - } else { - vec![[0.0; 4]; n] - }; - // Rubylith: `color` at `opacity` × coverage over the accumulated pixels. - let mut tint = |values: Vec, color: photocraft_color::Color, opacity: f32, coverage: &dyn Fn(f32) -> f32| { - let c = color.to_rgb(); - for (o, val) in out.iter_mut().zip(values) { - let a = (coverage(val.clamp(0.0, 1.0)) * opacity).clamp(0.0, 1.0); - for j in 0..3 { - o[j] = c[j] * a + o[j] * (1.0 - a); - } - o[3] = a + o[3] * (1.0 - a); - } - }; - let quick = doc.quick_mask.as_ref().filter(|_| !v.quick_mask_hidden && !solo_quick); - for ch in overlays.into_iter().chain(quick) { - let (color, opacity) = match ch.spot { - // Spot inks show more solid as solidity rises. - Some((ink, solidity)) => (ink, 0.5 + 0.5 * solidity), - None => (ch.color, ch.opacity), - }; - tint(sample(&ch.surface, r, factor), color, opacity, &|x| ch.overlay_coverage(x)); - } - // ⇧⌥-click mask view (#196): the layer mask tinted over the hidden areas in the Layer Mask - // Display Options colour and opacity (red at 50 % unless set). - if !solo_mask && let Some((m, MaskViewMode::Overlay)) = shown_mask { - let [cr, cg, cb] = mask_rgb; - tint(sample(m, r, factor), photocraft_color::Color::rgb(cr, cg, cb), mask_opacity, &|x| 1.0 - x); - } - Some(out.into_iter().map(|p| Color32::from_rgba_premultiplied(q(p[0]), q(p[1]), q(p[2]), q(p[3]))).collect()) -} - -/// `r` of a one-channel surface sampled every `factor` px, mapped to colours row by row (in -/// parallel off the web). -fn mask_px(s: &Surface, r: Rect, factor: u32, color: impl Fn(f32) -> Color32 + Sync) -> Vec { - let (w, h) = (r.width().div_ceil(factor) as usize, r.height().div_ceil(factor) as usize); - let mut px = vec![Color32::TRANSPARENT; w * h]; - let row = |y: usize, out: &mut [Color32]| { - let mut vals = vec![0.0f32; out.len()]; - s.sample_row_strided(r.y0 + (y as u32 * factor) as i32, r.x0, factor as i32, 0, &mut vals); - for (o, v) in out.iter_mut().zip(vals) { - *o = color(v); - } - }; - if w == 0 { - return px; - } - #[cfg(not(target_arch = "wasm32"))] - { - use rayon::prelude::*; - px.par_chunks_mut(w).enumerate().for_each(|(y, out)| row(y, out)); - } - #[cfg(target_arch = "wasm32")] - for (y, out) in px.chunks_mut(w).enumerate() { - row(y, out); - } - px -} - -/// A float in 0..=1 as an 8-bit channel value. -fn q(x: f32) -> u8 { - (x.clamp(0.0, 1.0) * 255.0 + 0.5) as u8 -} - -fn view_key(v: &ChannelView, look: Look) -> u64 { - let s = serde_json::to_string(&(v, look.mask_rgb, look.mask_opacity)).unwrap_or_default(); - s.bytes().fold(look.in_color as u64 + 1, |h, b| h.wrapping_mul(1_099_511_628_211).wrapping_add(b as u64)) -} - -/// Make the channel-view texture of document `idx` current; `None` = nothing to draw. -pub fn ensure(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usize) -> Option { - let st = app.session.documents().get(idx)?; - let view = st.channel_view.clone(); - let active = st.active_layer; - let (revision, last_damage) = (st.revision, st.last_damage); - let content = revision.wrapping_sub(st.view_revision); - let id = st.doc.id.0; - if view.is_plain(&st.doc) { - if let Some(c) = app.channel_views.get_mut(&id) { - c.valid = false; - } - return None; - } - // Mask and channel views are drawn over the canvas: show the same live document, - // otherwise an opaque grayscale mask hides the stroke until it is committed (#2078). - // The plain-composite path above needs no preview work. - let (doc, preview_key) = crate::canvas::filter_channel_preview(app, idx, ctx).unwrap_or_else(|| crate::canvas::display_doc(app, idx)); - // Interface ▸ Show Channels in Color tints single colour channel views on the canvas too, - // not just the panel thumbnails (#2385). The view key carries the flag and the Layer Mask - // Display Options, so changing them rebuilds the texture. - let look = Look::of(&app.session); - let key = view_key(&view, look); - // Never exceed what the GPU accepts (egui panics on oversized textures). - let max_side = (ctx.input(|i| i.max_texture_side) as u32).clamp(256, MAX_SIDE); - let factor = doc.size.width.max(doc.size.height).div_ceil(max_side).max(1); - // A live preview can mutate the same Arc in place. Content revision and preview_key, not - // pointer identity, determine whether these flattened pixels are still current. - if let Some(c) = app.channel_views.get_mut(&id) { - if let Some(s) = c.source.as_mut().filter(|s| s.factor == factor && s.content == content && s.preview_key == preview_key) { - s.revision = revision; - } else { - c.source = None; - } - } - if let Some(c) = app.channel_views.get(&id) - && c.key == key - && c.factor == factor - && c.valid - && c.revision == revision - && c.preview_key == preview_key - { - return Some(c.tex.id()); - } - let damage = - app.channel_views.get(&id).and_then(|c| crate::canvas::damage_since(app, idx, (c.revision, c.preview_key), (revision, preview_key), 0, last_damage)); - if let Some(c) = app.channel_views.get_mut(&id) - && c.key == key - && c.factor == factor - && c.valid - && let Some(d) = damage - { - // Re-render just the damage, snapped to the sampling grid so a downsampled texture - // (big documents) updates in place too. - let f = factor as i32; - let d = d.intersect(&doc.bounds()); - let r = Rect::new(d.x0.div_euclid(f) * f, d.y0.div_euclid(f) * f, d.x1, d.y1).intersect(&doc.bounds()); - if !r.is_empty() - && let Some(px) = render(&doc, &view, r, factor, look, active) - { - let img = egui::ColorImage::new([r.width().div_ceil(factor) as usize, r.height().div_ceil(factor) as usize], px); - c.tex.set_partial([(r.x0 / f) as usize, (r.y0 / f) as usize], img, TextureOptions::LINEAR); - } - c.revision = revision; - c.preview_key = preview_key; - return Some(c.tex.id()); - } - let b = doc.bounds(); - let cached = app.channel_views.get(&id).and_then(|c| c.source.as_ref()).map(|s| s.pixels.as_slice()); - let mut fresh = None; - let px = render_with_source(&doc, &view, b, factor, look, active, CompositeSource { cached, fresh: &mut fresh })?; - let new_source = fresh.is_some(); - let size = [b.width().div_ceil(factor) as usize, b.height().div_ceil(factor) as usize]; - let img = egui::ColorImage::new(size, px); - match app.channel_views.get_mut(&id) { - Some(c) if c.tex.size() == size => { - c.tex.set(img, TextureOptions::LINEAR); - c.revision = revision; - c.preview_key = preview_key; - c.key = key; - c.factor = factor; - c.valid = true; - if let Some(pixels) = fresh.take() { - c.source = Some(SampledComposite { revision, content, preview_key, factor, pixels }); - } - } - _ => { - let tex = ctx.load_texture(format!("channel-view-{id}"), img, TextureOptions::LINEAR); - let source = fresh.map(|pixels| SampledComposite { revision, content, preview_key, factor, pixels }); - app.channel_views.insert(id, Cache { revision, key, preview_key, factor, valid: true, tex, source }); - } - } - if new_source { - for (other_id, c) in &mut app.channel_views { - if *other_id != id { - c.source = None; - } - } - } - app.channel_views.get(&id).map(|c| c.tex.id()) -} - -#[cfg(test)] -mod tests { - use super::*; - use photocraft_engine::Session; - use photocraft_engine::channel_cmds::ChannelTarget; - use serde_json::json; - - fn session() -> Session { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 8, "height": 4})).unwrap(); - s - } - - #[test] - fn composite_bands_keep_the_downsample_grid() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 41, "height": 700})).unwrap(); - s.execute("edit.fill", json!({"color": "#398db2"})).unwrap(); - let doc = &s.active().unwrap().doc; - let rect = doc.bounds(); - let full = photocraft_compose::render(doc, rect); - let full_ref = &full; - for factor in [1, 2, 3, 5] { - let expected: Vec<_> = (0..rect.height()) - .step_by(factor as usize) - .flat_map(|y| { - (0..rect.width()).step_by(factor as usize).map(move |x| { - let p = full_ref.get(rect.x0 + x as i32, rect.y0 + y as i32); - let a = p[3].clamp(0.0, 1.0); - [p[0] * a + 1.0 - a, p[1] * a + 1.0 - a, p[2] * a + 1.0 - a, 1.0] - }) - }) - .collect(); - assert_eq!(composite(doc, rect, factor), expected, "factor {factor}"); - } - } - - #[test] - fn channel_eyes_reuse_composite_until_pixels_change() { - let mut app = PhotocraftApp::new(Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 64, "height": 32})).unwrap(); - app.run("edit.fill", json!({"color": "#4080c0"})).unwrap(); - app.sync_views(); - let ctx = egui::Context::default(); - app.run("channel.setVisible", json!({"channel": "red", "visible": false})).unwrap(); - assert!(ensure(&mut app, &ctx, 0).is_some()); - let id = app.session.active().unwrap().doc.id.0; - let first = app.channel_views.get_mut(&id).unwrap().source.as_mut().unwrap(); - let original_sample = first.pixels[0]; - // Mark the cache: a recomposite overwrites it, while a freed buffer's address can come back. - first.pixels[0] = [0.0, 1.0, 0.0, 1.0]; - - app.run("channel.setVisible", json!({"channel": "green", "visible": false})).unwrap(); - assert!(ensure(&mut app, &ctx, 0).is_some()); - let reused = app.channel_views.get(&id).unwrap().source.as_ref().unwrap(); - assert_eq!(reused.pixels[0], [0.0, 1.0, 0.0, 1.0], "visibility does not recompose the pixels"); - - app.run("edit.fill", json!({"color": "#e02010"})).unwrap(); - assert!(ensure(&mut app, &ctx, 0).is_some()); - // A partial damage upload discards the source; a full redraw may replace it. - // In either case, cached samples must never refer to the pre-edit pixels. - if let Some(source) = app.channel_views.get(&id).unwrap().source.as_ref() { - assert_ne!(source.pixels[0], original_sample, "a full redraw replaces stale pixels"); - } - app.run("channel.setVisible", json!({"channel": "red", "visible": true})).unwrap(); - assert!(ensure(&mut app, &ctx, 0).is_some()); - let refreshed = app.channel_views.get(&id).unwrap().source.as_ref().unwrap(); - let st = app.session.active().unwrap(); - assert_eq!(refreshed.revision, st.revision); - assert_ne!(refreshed.pixels[0], original_sample, "new pixels must be recomposited"); - let expected = render(&st.doc, &st.channel_view, st.doc.bounds(), 1, Look::default(), st.active_layer).unwrap(); - let mut unused = None; - let actual = render_with_source( - &st.doc, - &st.channel_view, - st.doc.bounds(), - 1, - Look::default(), - st.active_layer, - CompositeSource { cached: Some(&refreshed.pixels), fresh: &mut unused }, - ) - .unwrap(); - assert_eq!(actual, expected, "reused pixels must preserve channel colours"); - assert!(unused.is_none(), "reuse must not create a second composite"); - } - - #[test] - fn plain_composite_draws_nothing() { - let s = session(); - let st = s.active().unwrap(); - assert!(render(&st.doc, &st.channel_view, st.doc.bounds(), 1, Look::default(), st.active_layer).is_none()); - } - - #[test] - fn quick_mask_overlay_is_red_over_masked_areas() { - let mut s = session(); - s.execute("select.rect", json!({"x": 0, "y": 0, "width": 4, "height": 4})).unwrap(); - s.execute("select.editInQuickMaskMode", json!({})).unwrap(); - let st = s.active().unwrap(); - let px = render(&st.doc, &st.channel_view, st.doc.bounds(), 1, Look::default(), st.active_layer).unwrap(); - assert_eq!(px[0], Color32::TRANSPARENT, "selected: no overlay"); - assert_eq!(px[6], Color32::from_rgba_premultiplied(128, 0, 0, 128), "masked: 50% red"); - } - - #[test] - fn quick_mask_without_selection_shows_no_overlay_in_either_mode() { - // #2743: nothing selected is a colourless mask, whichever way the colour reads. - for (before, after) in [(None, Some("selected")), (Some("selected"), None), (Some("selected"), Some("masked"))] { - let mut s = session(); - if let Some(i) = before { - s.execute("channel.options", json!({"channel": "quickMask", "indicates": i})).unwrap(); - } - s.execute("select.editInQuickMaskMode", json!({})).unwrap(); - let st = s.active().unwrap(); - let px = render(&st.doc, &st.channel_view, st.doc.bounds(), 1, Look::default(), st.active_layer).unwrap(); - assert!(px.iter().all(|p| *p == Color32::TRANSPARENT), "{before:?}"); - if let Some(i) = after { - s.execute("channel.options", json!({"channel": "quickMask", "indicates": i})).unwrap(); - let st = s.active().unwrap(); - let px = render(&st.doc, &st.channel_view, st.doc.bounds(), 1, Look::default(), st.active_layer).unwrap(); - assert!(px.iter().all(|p| *p == Color32::TRANSPARENT), "{before:?} → {i}"); - } - } - // Selected Areas with Select All: the whole canvas is coloured. - let mut s = session(); - s.execute("channel.options", json!({"channel": "quickMask", "indicates": "selected"})).unwrap(); - s.execute("select.all", json!({})).unwrap(); - s.execute("select.editInQuickMaskMode", json!({})).unwrap(); - let st = s.active().unwrap(); - let px = render(&st.doc, &st.channel_view, st.doc.bounds(), 1, Look::default(), st.active_layer).unwrap(); - assert!(px.iter().all(|p| *p == Color32::from_rgba_premultiplied(128, 0, 0, 128))); - } - - #[test] - fn layer_mask_views_and_damage_on_the_downsampled_grid() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 37, "height": 21})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap(); - s.execute("layer.layerMask.revealAll", json!({})).unwrap(); - s.execute("paint.gradient", json!({"from": [0, 0], "to": [37, 0], "colors": ["#000000", "#ffffff"], "target": "mask"})).unwrap(); - s.execute("view.layerMask", json!({"mode": "gray"})).unwrap(); - let st = s.active().unwrap(); - let b = st.doc.bounds(); - let full = render(&st.doc, &st.channel_view, b, 1, Look::default(), st.active_layer).unwrap(); - assert!(full[0].r() < 10 && full[36].r() > 245 && full[0].a() == 255, "opaque grayscale ramp"); - // A sub-rect starting on the factor grid matches the same pixels of the full render. - for f in [1u32, 2, 3] { - let all = render(&st.doc, &st.channel_view, b, f, Look::default(), st.active_layer).unwrap(); - let w = b.width().div_ceil(f) as usize; - let r = Rect::new(3 * f as i32, 2 * f as i32, 30, 19); - let part = render(&st.doc, &st.channel_view, r, f, Look::default(), st.active_layer).unwrap(); - let pw = r.width().div_ceil(f) as usize; - for (i, p) in part.iter().enumerate() { - assert_eq!(*p, all[(i / pw + 2) * w + i % pw + 3], "factor {f}, pixel {i}"); - } - } - s.execute("view.layerMask", json!({"mode": "overlay"})).unwrap(); - let st = s.active().unwrap(); - let px = render(&st.doc, &st.channel_view, b, 1, Look::default(), st.active_layer).unwrap(); - assert!(px[0].r() >= 124 && px[0].g() == 0 && px[0].a() >= 124, "about 50% red over the hidden end: {:?}", px[0]); - assert!(px[36].a() <= 4, "next to nothing over the revealed end: {:?}", px[36]); - } - - #[test] - fn layer_mask_views_show_the_feathered_mask() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 37, "height": 21})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.execute("layer.layerMask.revealAll", json!({})).unwrap(); - s.execute("paint.gradient", json!({"from": [0, 0], "to": [37, 0], "colors": ["#000000", "#ffffff"], "target": "mask"})).unwrap(); - s.execute("layer.layerMask.edit", json!({"feather": 4})).unwrap(); - s.execute("view.layerMask", json!({"mode": "gray"})).unwrap(); - - let st = s.active().unwrap(); - let bounds = st.doc.bounds(); - let layer = st.doc.layer(st.active_layer.unwrap()).unwrap(); - let raw = layer.mask.as_ref().unwrap().surface.sample_channel(0, 0, 0); - let effective = photocraft_compose::masks::combined_mask(layer, bounds).unwrap(); - let softened = effective.sample_channel(0, 0, 0); - assert!((softened - raw).abs() > 0.01, "the fixture has a visible feather at its edge"); - - let gray = render(&st.doc, &st.channel_view, bounds, 1, Look::default(), st.active_layer).unwrap(); - assert_eq!(gray[0], Color32::from_gray(q(softened)), "gray view uses the compositor's feathered mask"); - - s.execute("view.layerMask", json!({"mode": "overlay"})).unwrap(); - let st = s.active().unwrap(); - let overlay = render(&st.doc, &st.channel_view, bounds, 1, Look::default(), st.active_layer).unwrap(); - let alpha = 0.5 * (1.0 - softened); - let red = AlphaChannel::DEFAULT_COLOR.to_rgb(); - assert_eq!(overlay[0], Color32::from_rgba_premultiplied(q(red[0] * alpha), q(red[1] * alpha), q(red[2] * alpha), q(alpha))); - } - - /// Layer Mask Display Options: the rubylith takes their colour and opacity, alone over the - /// composite and with a colour channel hidden. - #[test] - fn layer_mask_overlay_takes_its_display_options() { - let mut s = session(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap(); - s.execute("layer.layerMask.hideAll", json!({})).unwrap(); - s.execute("view.layerMask", json!({"mode": "overlay"})).unwrap(); - let green = Look { mask_rgb: [0.0, 1.0, 0.0], mask_opacity: 0.25, ..Look::default() }; - let st = s.active().unwrap(); - let b = st.doc.bounds(); - assert_eq!(render(&st.doc, &st.channel_view, b, 1, Look::default(), st.active_layer).unwrap()[0], Color32::from_rgba_premultiplied(128, 0, 0, 128)); - assert_eq!(render(&st.doc, &st.channel_view, b, 1, green, st.active_layer).unwrap()[0], Color32::from_rgba_premultiplied(0, 64, 0, 64)); - // Red hidden: the white picture shows cyan, then green at 25 % over it. - s.execute("channel.setVisible", json!({"channel": "red", "visible": false})).unwrap(); - let st = s.active().unwrap(); - assert_eq!(render(&st.doc, &st.channel_view, b, 1, green, st.active_layer).unwrap()[0], Color32::from_rgb(0, 255, 191)); - } - - /// `cargo test --release -p photocraft-ui-egui --lib mask_view_switch_24mp -- --ignored --nocapture` - #[test] - #[ignore = "benchmark"] - fn mask_view_switch_24mp() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 6000, "height": 4000})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.execute("edit.fill", json!({"color": "#d0402b"})).unwrap(); - s.execute("layer.layerMask.revealAll", json!({})).unwrap(); - s.execute("paint.gradient", json!({"from": [0, 0], "to": [6000, 0], "colors": ["#000000", "#ffffff"], "target": "mask"})).unwrap(); - let factor = 6000u32.div_ceil(MAX_SIDE); - for mode in ["gray", "overlay"] { - s.execute("view.layerMask", json!({"mode": mode})).unwrap(); - let st = s.active().unwrap(); - let mut best = f64::MAX; - for _ in 0..8 { - let t = std::time::Instant::now(); - let px = render(&st.doc, &st.channel_view, st.doc.bounds(), factor, Look::default(), st.active_layer).unwrap(); - let img = egui::ColorImage::new([3000, 2000], px); - std::hint::black_box(img); - best = best.min(t.elapsed().as_secs_f64() * 1000.0); - } - println!("24 MP mask view {mode}: {best:.1} ms (render at 1/{factor})"); - } - } - - /// Interface ▸ Show Channels in Color (#2385): a solo RGB / CMYK channel tints the canvas - /// instead of staying gray, like the panel thumbnails wired in #1986. - #[test] - fn show_channels_in_color_tints_the_canvas() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 4, "height": 4, "mode": "rgb"})).unwrap(); - s.execute("edit.fill", json!({"color": "#4080c0"})).unwrap(); - s.execute("channel.target", json!({"channel": "green"})).unwrap(); - let st = s.active().unwrap(); - let b = st.doc.bounds(); - assert_eq!(render(&st.doc, &st.channel_view, b, 1, Look::default(), st.active_layer).unwrap()[0], Color32::from_gray(128)); - assert_eq!( - render(&st.doc, &st.channel_view, b, 1, Look { in_color: true, ..Look::default() }, st.active_layer).unwrap()[0], - Color32::from_rgb(0, 128, 0) - ); - - let mut s = Session::new(); - s.execute("file.new", json!({"width": 4, "height": 4, "mode": "cmyk"})).unwrap(); - s.execute("edit.fill", json!({"color": "#4080c0"})).unwrap(); - s.execute("channel.target", json!({"channel": "cyan"})).unwrap(); - let st = s.active().unwrap(); - let px = render(&st.doc, &st.channel_view, st.doc.bounds(), 1, Look { in_color: true, ..Look::default() }, st.active_layer).unwrap()[0]; - assert!(px.r() < 100 && px.g() > 150 && px.b() > 150, "cyan ink, not gray: {px:?}"); - let gray = render(&st.doc, &st.channel_view, st.doc.bounds(), 1, Look::default(), st.active_layer).unwrap()[0]; - assert_eq!(gray.r(), gray.g(), "off stays grayscale"); - } - - /// Lab: a and b tint over a neutral Lightness; Lightness itself stays gray (Adobe's exception). - #[test] - fn show_channels_in_color_lab_lightness_stays_gray() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 4, "height": 4, "mode": "lab"})).unwrap(); - s.execute("edit.fill", json!({"color": "#4080c0"})).unwrap(); - let b = s.active().unwrap().doc.bounds(); - s.execute("channel.target", json!({"channel": {"color": 0}})).unwrap(); - let st = s.active().unwrap(); - let px = render(&st.doc, &st.channel_view, b, 1, Look { in_color: true, ..Look::default() }, st.active_layer).unwrap()[0]; - let spread = px.r().max(px.g().max(px.b())) as i32 - px.r().min(px.g().min(px.b())) as i32; - assert!(spread <= 3, "Lightness stays gray: {px:?}"); - s.execute("channel.target", json!({"channel": {"color": 1}})).unwrap(); - let st = s.active().unwrap(); - let px = render(&st.doc, &st.channel_view, b, 1, Look { in_color: true, ..Look::default() }, st.active_layer).unwrap()[0]; - assert!(px.r() != px.g() || px.g() != px.b(), "a channel is tinted, not gray: {px:?}"); - } - - /// The canvas texture cache is keyed by the preference, so toggling it rebuilds the view. - #[test] - fn ensure_honours_show_channels_in_color() { - let mut app = PhotocraftApp::new(Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); - app.sync_views(); - app.run("channel.target", json!({"channel": "green"})).unwrap(); - let ctx = egui::Context::default(); - assert!(ensure(&mut app, &ctx, 0).is_some()); - let key_off = app.channel_views.values().next().unwrap().key; - app.session.execute("prefs.set", json!({"values": {"interface.showChannelsInColor": true}})).unwrap(); - assert!(ensure(&mut app, &ctx, 0).is_some()); - let key_on = app.channel_views.values().next().unwrap().key; - assert_ne!(key_off, key_on, "the preference changes the cached view key"); - // So do the Layer Mask Display Options. - app.session.execute("channel.options", json!({"channel": "mask", "color": "#00ff00", "opacity": 70})).unwrap(); - assert!(ensure(&mut app, &ctx, 0).is_some()); - assert_ne!(app.channel_views.values().next().unwrap().key, key_on, "the overlay options change the cached view key"); - } - - #[test] - fn solo_alpha_is_grayscale_and_colour_channels_split() { - let mut s = session(); - s.execute("edit.fill", json!({"color": "#ff8000"})).unwrap(); - s.execute("select.rect", json!({"x": 0, "y": 0, "width": 2, "height": 4})).unwrap(); - s.execute("channel.new", json!({"fill": "selection"})).unwrap(); - let st = s.active().unwrap(); - assert_eq!(st.channel_view.target, ChannelTarget::Alpha(0)); - let px = render(&st.doc, &st.channel_view, st.doc.bounds(), 1, Look::default(), st.active_layer).unwrap(); - assert_eq!((px[0], px[5]), (Color32::WHITE, Color32::BLACK)); - // Green alone: grayscale of the green channel; with blue hidden only. - s.execute("channel.target", json!({"channel": "green"})).unwrap(); - let st = s.active().unwrap(); - let px = render(&st.doc, &st.channel_view, st.doc.bounds(), 1, Look::default(), st.active_layer).unwrap(); - assert_eq!(px[0], Color32::from_gray(128)); - s.execute("channel.target", json!({"channel": "composite"})).unwrap(); - s.execute("channel.setVisible", json!({"channel": "red", "visible": false})).unwrap(); - let st = s.active().unwrap(); - let px = render(&st.doc, &st.channel_view, st.doc.bounds(), 2, Look::default(), st.active_layer).unwrap(); - assert_eq!(px.len(), 4 * 2); - assert_eq!(px[0], Color32::from_rgb(0, 128, 0)); - } - - #[test] - fn rgb_off_shows_alpha_quick_mask_or_the_layer_mask() { - let mut s = session(); - s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); - s.execute("channel.new", json!({"fill": "white"})).unwrap(); - s.execute("channel.setVisible", json!({"channel": "composite", "visible": true})).unwrap(); - s.execute("channel.setVisible", json!({"channel": "composite", "visible": false})).unwrap(); - let st = s.active().unwrap(); - let px = render(&st.doc, &st.channel_view, st.doc.bounds(), 1, Look::default(), st.active_layer).unwrap(); - assert_eq!(px[0], Color32::WHITE, "Alpha alone is the channel, not the red image"); - - let mut q = session(); - q.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); - q.execute("select.editInQuickMaskMode", json!({})).unwrap(); - q.execute("channel.setVisible", json!({"channel": "composite", "visible": false})).unwrap(); - let st = q.active().unwrap(); - let px = render(&st.doc, &st.channel_view, st.doc.bounds(), 1, Look::default(), st.active_layer).unwrap(); - assert_eq!(px[0], Color32::WHITE, "Quick Mask alone is grayscale, not the red composite"); - - let mut m = session(); - m.execute("layer.new.layer", json!({})).unwrap(); - m.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); - m.execute("layer.layerMask.hideAll", json!({})).unwrap(); - m.execute("channel.setVisible", json!({"channel": "composite", "visible": false})).unwrap(); - let st = m.active().unwrap(); - assert_eq!(st.channel_view.visible_colors(3), 0); - let px = render(&st.doc, &st.channel_view, st.doc.bounds(), 1, Look::default(), st.active_layer).unwrap(); - assert_eq!(px[0], Color32::BLACK, "the hidden mask reads black, not the red layer"); - } -} diff --git a/crates/ui-egui/src/cjk_fonts.rs b/crates/ui-egui/src/cjk_fonts.rs deleted file mode 100644 index 7dfefbb640..0000000000 --- a/crates/ui-egui/src/cjk_fonts.rs +++ /dev/null @@ -1,2944 +0,0 @@ -//! Lazy CJK and other-script fallback fonts for the UI. -//! -//! The bundled Inter / JetBrains Mono have no Japanese, Chinese or Korean glyphs, and the OS -//! fonts that do are large (Hiragino ~10 MB, Apple SD Gothic Neo 28 MB, PingFang 78 MB, Noto -//! Sans CJK ~20 MB). Instead of reading them at startup, an egui plugin scans each frame's text -//! for CJK characters no registered font covers, and registers the next system font for that -//! character's script (`ctx.add_font`, active from the next frame, which it requests). Fonts are -//! appended at the lowest priority to every family, so Latin text keeps Inter. -//! -//! Other scripts the bundled fonts lack (Thai, Arabic, Hebrew, Devanagari and the other Indic -//! scripts, ...: [`photocraft_text::scripts`]) work the same way, each with its own attempt state, -//! independent of the CJK order: the first installed candidate file whose character map really -//! has the missing character is registered, once per script. egui shapes each font run with -//! HarfRust, so Thai marks and Arabic joining come from the font; it has no bidi reordering yet. -//! -//! Script order follows the effective UI locale ([`photocraft_text::cjk::script_order`]): Kana -//! prefers a Japanese font, Hangul a Korean one, Bopomofo a Traditional Chinese one, and Han the -//! locale's script. The effective locale is the translated UI language when it names -//! ja/ko/zh-Hans/zh-Hant; otherwise it is the OS locale. An English UI on a Japanese, Korean or -//! Chinese OS therefore follows that OS script, not the English baseline. The craft manifest -//! lists Shippori Mincho and BIZ UDPGothic before Noto Sans CJK SC, so a non-CJK/unknown -//! effective locale keeps the migration baseline's first covering face for shared Han and kana -//! (Shippori Mincho Regular); Hangul intentionally uses the Korean face (NanumGothic) instead, -//! because [`CjkChar::preferred`] always prefers Korean, even though the old linear stack would -//! have picked the broad Simplified Chinese face. An explicit zh-Hans/zh-Hant/ja/ko preference -//! selects its own form and keeps the UI-first face for its script (BIZ UDPGothic for Japanese). -//! The lazy loader reads at most one font per frame, each file at most once, and once every -//! script has been tried the scan stops. -//! -//! Builds made with the optional craft-fonts input (`CRAFT_FONTS_DIR`, -//! [`photocraft_text::craft_fonts`]) carry Japanese, Chinese, Korean and other faces. A -//! per-character [`FontProvider`] serves them, and the system font a locale defers to, in the -//! first frame; the lazy loader remains the later fallback. The provider has no lifetime read -//! cap. It retains at most [`MAX_SYSTEM_CACHE_BYTES`] of unique font-file blobs, charging a -//! collection (TTC) once however many faces it selects; a face that cannot be retained is -//! returned transiently for the current request, so a later Fontconfig candidate is never -//! skipped merely because earlier characters read other fonts. -//! Without craft-fonts (and on the web, which never embeds them) nothing changes. - -use egui::epaint::text::{FontInsert, FontPriority, InsertFontFamily}; -use egui::{FallbackRequest, FontData, FontFamily, FontId, FontProvider, Shape}; -use photocraft_text::cjk::{self, CjkChar, CjkScript, FontFile}; -use photocraft_text::craft_fonts::{self, CraftFont}; -use photocraft_text::scripts::{self, Script}; -use std::path::PathBuf; - -/// Skip absurdly large files (a corrupt or non-font path must not eat memory). -pub const MAX_FONT_BYTES: u64 = 128 << 20; -/// At most this many candidate files are read for one non-CJK script by the lazy loader. -const MAX_SCRIPT_READS: usize = 6; -/// Upper bound on the unique font-file blobs the eager provider retains in its own cache. -/// Structurally invalid candidates are not retained at all. A readable file is charged once, -/// whatever number of faces the provider selects from a collection; it is evicted before the -/// budget is exceeded. A file that cannot be retained is still used for the current request and -/// returned transiently to egui (which may own that installed face independently). There is -/// deliberately no lifetime read cap: a valid Fontconfig match appended after many -/// absent/non-covering static paths (or after earlier characters) must still be reached. -const MAX_SYSTEM_CACHE_BYTES: usize = 128 << 20; -/// Remembered face names are tiny but still bounded independently of the blob budget. -const MAX_SYSTEM_FACE_NAMES: usize = 1024; -/// Name prefix of the registered fallback fonts. -pub const FONT_PREFIX: &str = "system-cjk"; - -/// Where fonts come from; swapped out in tests. -#[derive(Clone)] -pub struct Sources { - pub locale: fn() -> Option, - pub files: fn(CjkScript) -> Vec, - pub last_resort: fn() -> Vec, - /// Whether the background Fontconfig CJK lookup is still running. The provider must not fall - /// through to a lower-priority script (for example Simplified Chinese for a Hant character) - /// while the preferred script may still gain a system face. Injectable so tests (and the web - /// build) never depend on timing. - pub pending: fn() -> bool, - /// Candidate files for a non-CJK script, most preferred first; read only when a visible - /// character of that script is missing. - pub scripts: fn(Script) -> Vec, - /// The face of a font file whose character map has the character (`None`: not this file). - pub covers: fn(&[u8], char) -> Option, - /// Embedded craft faces declaring an ISO 15924 script, in the script's own order. The - /// provider and lazy loader both use this injection (tests can therefore pin craft-font - /// selection without depending on the build input). - pub embedded: fn(&'static str) -> Vec<&'static CraftFont>, - /// Install the per-character craft-font provider, so a headless first frame can shape CJK - /// and other scripts before the lazy loader gets a second pass (tests panic on a missing - /// glyph). It selects a face for the character's script instead of putting a broad face into - /// the family stack up front for every later character. - pub eager_craft_fonts: bool, -} - -/// Craft fonts declaring `iso`, Regular first and (for Japanese) the UI face first; empty -/// without craft-fonts. This is the explicit-locale order; a non-CJK/unknown effective locale -/// uses the raw manifest order through [`craft_face_manifest`] instead. -/// -/// The lazy loader tries these before system files for a script, so its fallback order stays -/// `preferred script, then the locale order` even for a character the provider left to it. -pub fn craft_embedded_iso(iso: &'static str) -> Vec<&'static CraftFont> { - craft_faces(iso).into_iter().map(|(_, f)| f).collect() -} - -/// Craft fonts for a CJK script; a convenience wrapper for callers that already hold the enum. -pub fn craft_embedded(script: CjkScript) -> Vec<&'static CraftFont> { - craft_embedded_iso(cjk_iso(script)) -} - -/// No embedded fonts (tests that pin the system-font behaviour). -pub fn no_embedded(_: &'static str) -> Vec<&'static CraftFont> { - Vec::new() -} - -/// Craft fonts chosen per character, the way the lazy loader chooses them for one missing glyph. -/// -/// A single linear font stack cannot express the per-script preference: a broad Noto Sans CJK SC -/// face covers kana and Hangul too, so putting it in the stack would make it win there over the -/// Japanese or Korean face. A [`FontProvider`] is asked per missing character instead, and this -/// one returns the face for that character's script. When the preferred script has no craft face -/// (e.g. Traditional Chinese), it asks the system font for that script first, and only falls -/// through the locale order (so a Simplified Chinese face comes last) when the system has none. -/// -/// egui still resolves a character from an already discovered broad face before asking a -/// provider again; a mixed-script run whose first character discovered SC can therefore serve a -/// later kana/Hangul character from SC. Removing that last ambiguity needs script-aware fallback -/// in epaint (or per-script text runs); this provider fixes the eager-stack case. -struct CraftFontProvider { - locale: fn() -> Option, - files: fn(CjkScript) -> Vec, - last_resort: fn() -> Vec, - pending: fn() -> bool, - scripts: fn(Script) -> Vec, - covers: fn(&[u8], char) -> Option, - embedded: fn(&'static str) -> Vec<&'static CraftFont>, - /// Interface > UI Font Size multiplier for the discovered faces (see `theme::ui_font_scale`). - scale: std::sync::Arc, - /// System files, faces and failed lookups read for characters no craft face covers. - system: std::sync::Mutex, - /// I/O for a candidate path; `read_font` in production, injectable by tests. - reader: fn(&std::path::Path) -> Option>, -} - -/// A readable, structurally valid font file retained as one shared blob, no matter how many -/// faces of it the provider selects. The blob is charged to the byte budget once. -struct CachedFile { - path: PathBuf, - data: FontData, - bytes: usize, -} - -struct SystemCache { - /// Unique retained font blobs, oldest first; evicted when the byte budget is exceeded. - /// A collection's faces share this one entry, so a TTC is not charged per face. - files: Vec, - /// Paths whose read failed (missing, empty, oversized, unreadable): never retry them for - /// each missing character. - failed_reads: std::collections::HashSet, - /// Paths that were readable but structurally not a font (truncated download, unrelated - /// file): negative-cached separately from an I/O failure and from a non-covering face. - invalid_fonts: std::collections::HashSet, - /// Names of faces handed to egui, reusing their name across characters. These carry no font - /// bytes (the blob stays in `files` while retained) and are capped by - /// [`MAX_SYSTEM_FACE_NAMES`]. - faces: Vec, - /// `face_index_for_family_checked` results, including family misses, so a collection's - /// `name`/directory tables are not parsed again for every character. - family_indices: Vec<(PathBuf, String, Option)>, - /// Bytes of the unique blobs in `files`. A selected face adds no bytes: egui's installed copy - /// may outlive the provider's reference, but the provider charges and bounds only its own - /// retained blob. - retained_bytes: usize, - /// Budget for `retained_bytes`; injectable (small) in tests. - max_bytes: usize, - /// Next face name; monotonic so names are never reused for a different face. - next_face_name: usize, - /// Successful I/O reads. Diagnostics/tests only: there is deliberately no lifetime cap. - #[cfg_attr(not(test), allow(dead_code))] - reads: usize, -} - -impl Default for SystemCache { - fn default() -> Self { - Self { - files: Vec::new(), - failed_reads: std::collections::HashSet::new(), - invalid_fonts: std::collections::HashSet::new(), - faces: Vec::new(), - family_indices: Vec::new(), - retained_bytes: 0, - max_bytes: MAX_SYSTEM_CACHE_BYTES, - next_face_name: 0, - reads: 0, - } - } -} - -impl SystemCache { - /// Evict the oldest blobs until `extra` more bytes fit. Returns `false` when even an empty - /// cache cannot hold `extra`; in that case nothing is evicted, because a request that must be - /// transient should not discard useful cached candidates. Face names are not pinned blobs: - /// egui may keep an installed copy, but the provider's own byte cache stays bounded. - fn make_room(&mut self, extra: usize) -> bool { - if extra > self.max_bytes { - return false; - } - while self.retained_bytes.saturating_add(extra) > self.max_bytes { - let Some(file) = self.files.first() else { return false }; - let bytes = file.bytes; - self.files.remove(0); - self.retained_bytes = self.retained_bytes.saturating_sub(bytes); - } - true - } - - /// Remember a face name without retaining font bytes. Names are capped; forgetting an old - /// name only means egui may install a face under a new name later. - fn remember_face(&mut self, path: PathBuf, index: u32, name: String) { - if self.faces.len() >= MAX_SYSTEM_FACE_NAMES { - self.faces.remove(0); - } - self.faces.push(SystemFace { path, index, name }); - } -} - -struct SystemFace { - path: PathBuf, - index: u32, - name: String, -} - -impl CraftFontProvider { - fn new(sources: &Sources, scale: f32) -> Self { - Self { - locale: sources.locale, - files: sources.files, - last_resort: sources.last_resort, - pending: sources.pending, - scripts: sources.scripts, - covers: sources.covers, - embedded: sources.embedded, - scale: std::sync::Arc::new(std::sync::atomic::AtomicU32::new(scale.to_bits())), - system: std::sync::Mutex::new(SystemCache::default()), - reader: read_font, - } - } - - fn scale(&self) -> f32 { - f32::from_bits(self.scale.load(std::sync::atomic::Ordering::Relaxed)) - } - - fn set_scale(&self, scale: f32) { - self.scale.store(scale.to_bits(), std::sync::atomic::Ordering::Relaxed); - } - - /// The bytes of `path`, read at most once while its blob is retained and shared even when a - /// later request wants a different face of the same collection. - /// - /// The whole check/read/insert runs under the cache lock, so concurrent layout threads share - /// one read per path and a success can never be shadowed by another thread's stale failure. - /// Missing/unreadable paths and readable non-font bytes are negative-cached separately. - fn system_source(&self, path: &std::path::Path) -> Option { - let mut cache = self.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - if cache.failed_reads.contains(path) || cache.invalid_fonts.contains(path) { - return None; - } - if let Some(file) = cache.files.iter().find(|file| file.path.as_path() == path) { - return Some(FontData::from_blob(file.data.font.clone(), 0)); - } - let Some(bytes) = (self.reader)(path) else { - cache.failed_reads.insert(path.to_path_buf()); - return None; - }; - cache.reads = cache.reads.saturating_add(1); - if !cjk::font_file_is_readable(&bytes) { - // A readable non-font is an invalid candidate, not a valid face that merely lacks - // this character: remember that separately and never retain its bytes. - cache.invalid_fonts.insert(path.to_path_buf()); - return None; - } - let size = bytes.len(); - let data = FontData::from_owned(bytes); - let source = FontData::from_blob(data.font.clone(), 0); - if cache.make_room(size) { - cache.retained_bytes = cache.retained_bytes.saturating_add(size); - cache.files.push(CachedFile { path: path.to_path_buf(), data, bytes: size }); - } - // If this file alone exceeds the budget, the bytes are still used for this request but - // not retained. egui may keep the installed face; the provider's own cache stays bounded. - Some(source) - } - - /// The (cached) face index whose family name is `family`; `None` is cached as a family miss. - fn checked_face_index(&self, path: &std::path::Path, family: &str, bytes: &[u8]) -> Option { - { - let cache = self.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - if let Some((_, _, index)) = cache.family_indices.iter().find(|(cached, name, _)| cached.as_path() == path && name.as_str() == family) { - return *index; - } - } - let index = cjk::face_index_for_family_checked(bytes, family); - let mut cache = self.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - if !cache.family_indices.iter().any(|(cached, name, _)| cached.as_path() == path && name.as_str() == family) { - cache.family_indices.push((path.to_path_buf(), family.to_owned(), index)); - } - index - } - - /// Register one face of an already-read system file, reusing its name but applying the - /// current UI scale on every return (a cache must never bake the scale in). - /// - /// A face never adds a second charge for its collection's blob. If the blob was not retained - /// (it alone exceeds the budget, or another thread evicted it first), this still returns a - /// complete transient `FontInsert`: egui installs and owns that copy, while the provider's - /// own cache remains within `max_bytes`. - fn system_insert_face(&self, path: PathBuf, index: u32, source: FontData) -> FontInsert { - let mut cache = self.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - let name = match cache.faces.iter().find(|f| f.path == path && f.index == index) { - Some(face) => face.name.clone(), - None => { - let name = format!("craft-system-{}", cache.next_face_name); - cache.next_face_name = cache.next_face_name.saturating_add(1); - cache.remember_face(path, index, name.clone()); - name - } - }; - let mut data = FontData::from_blob(source.font, index); - apply_font_tweaks(&mut data); - font_insert(name, data, self.scale()) - } - - /// The first system face for `script` (or any last-resort face) whose requested family really - /// covers `c`. - /// - /// The lazy loader reads these after the first frame; the provider needs the same source for - /// the first frame, before a headless layout with `MissingGlyphPolicy::Panic` can finish. - /// A non-empty family is resolved by name first, then checked against that exact face: never - /// use the first face of a collection that happens to cover `c`. - fn system_insert_files(&self, files: Vec, c: char) -> Option { - for file in files { - let Some(source) = self.system_source(&file.path) else { continue }; - let index = if file.family.is_empty() { - 0 - } else { - let Some(index) = self.checked_face_index(&file.path, &file.family, source.bytes()) else { continue }; - index - }; - // A readable collection can still hold a malformed selected face whose `cmap` and - // `name` work; do not hand that index to epaint, which panics when it installs a - // configured face it cannot parse. - if !cjk::font_face_is_readable(source.bytes(), index) { - continue; - } - if !scripts::face_covers(source.bytes(), index, c) { - continue; - } - return Some(self.system_insert_face(file.path, index, source)); - } - None - } - - /// The first non-CJK candidate path that maps `c`; these files have no requested family, so - /// the same character-map rule as the lazy loader applies. - fn system_insert_paths(&self, files: Vec, c: char) -> Option { - for path in files { - let Some(source) = self.system_source(&path) else { continue }; - let Some(index) = (self.covers)(source.bytes(), c) else { continue }; - if !cjk::font_face_is_readable(source.bytes(), index) { - continue; - } - return Some(self.system_insert_face(path, index, source)); - } - None - } -} - -impl FontProvider for CraftFontProvider { - fn font_for(&self, request: &FallbackRequest<'_>) -> Option { - let c = request.cluster.chars().next()?; - let locale = (self.locale)(); - let order = cjk::script_order(locale.as_deref()); - // The migration baseline appended every craft face to the family stack in manifest - // order, so a non-CJK/unknown effective locale drew shared Han/kana with the first - // manifest face that covered the character (Shippori Mincho Regular). An explicit - // ja/ko/zh preference is a new choice and keeps the UI-first order for its script. - // `locale` already resolves an English UI on a CJK OS to that OS locale, so this - // baseline does not apply there. - let manifest_baseline = cjk::locale_script(locale.as_deref()).is_none(); - let craft = |iso: &'static str| { - if manifest_baseline { craft_face_manifest(self.embedded, iso, c) } else { craft_face_for(self.embedded, iso, c) } - }; - if let Some(kind) = cjk::classify(c) { - // Han follows the locale's script. For a non-CJK/unknown effective locale, try the - // manifest's Japanese faces first (exactly as the baseline stack did) before the - // SC-first system order. - if kind == cjk::CjkChar::Han - && manifest_baseline - && let Some((index, face)) = craft_face_manifest(self.embedded, "Jpan", c) - { - return Some(craft_insert(index, face, self.scale())); - } - // The same order as `CjkFallback::next_font`: the character's preferred script first, - // then the locale order; craft faces and system files per script. A Traditional - // Chinese locale therefore checks its system Hant font before any Simplified craft - // face, and only falls through when the system has no Hant face either. - // - // While fontconfig is still looking for the preferred script's face, do not cache a - // lower-priority face (SC for a Hant character): egui keeps that wrong choice for the - // installed font chain. Returning `None` lets the next layout retry after the scan. - let mut scripts = vec![kind.preferred(&order)]; - scripts.extend(order); - let mut tried: Vec = Vec::new(); - for script in scripts { - if tried.contains(&script) { - continue; - } - tried.push(script); - if let Some((index, face)) = craft(cjk_iso(script)) { - return Some(craft_insert(index, face, self.scale())); - } - if let Some(insert) = self.system_insert_files((self.files)(script), c) { - return Some(insert); - } - if (self.pending)() { - return None; - } - } - return self.system_insert_files((self.last_resort)(), c); - } - let Some(script) = scripts::classify(c) else { - return craft("Zsym").map(|(index, face)| craft_insert(index, face, self.scale())); - }; - if let Some((index, face)) = craft(script_iso(script)) { - return Some(craft_insert(index, face, self.scale())); - } - if let Some(insert) = self.system_insert_paths((self.scripts)(script), c) { - return Some(insert); - } - // The lazy loader's last-resort list is broad (Arial Unicode, Droid Sans Fallback): it is - // the same final source for non-CJK scripts when no script-specific file is installed. - self.system_insert_files((self.last_resort)(), c) - } -} - -/// Whether `face` really maps `c` in the face [`craft_insert`] would install. -/// -/// `craft_insert` builds `FontData::from_static(face.bytes)`, whose default face index is 0, so -/// testing any face of a collection would select a face whose glyphs egui never uses. Test face -/// 0 here, exactly like the lazy loader's `load_embedded_faces`. -fn craft_face_installs_coverage(face: &CraftFont, c: char) -> bool { - !face.bytes.is_empty() && cjk::font_face_is_readable(face.bytes, 0) && scripts::face_covers(face.bytes, 0, c) -} - -/// The best injected craft face declaring `iso` that really covers `c` in the face -/// [`craft_insert`] installs. -fn craft_face_for(embedded: fn(&'static str) -> Vec<&'static CraftFont>, iso: &'static str, c: char) -> Option<(usize, &'static CraftFont)> { - embedded(iso).into_iter().find_map(|face| { - let index = craft_index(face)?; - craft_face_installs_coverage(face, c).then_some((index, face)) - }) -} - -/// The injected craft face the migration baseline would have used first: the earliest manifest -/// face declaring `iso` that really covers `c` in the face [`craft_insert`] installs. (The -/// baseline appended the whole manifest in order; for Japanese that is Shippori Mincho Regular, -/// not the UI-first BIZ UDPGothic.) -fn craft_face_manifest(embedded: fn(&'static str) -> Vec<&'static CraftFont>, iso: &'static str, c: char) -> Option<(usize, &'static CraftFont)> { - let mut faces = embedded(iso); - // Stable: faces outside the global table (test doubles) keep their injected order. - faces.sort_by_key(|face| craft_index(face).unwrap_or(usize::MAX)); - faces.into_iter().find_map(|face| { - let index = craft_index(face)?; - craft_face_installs_coverage(face, c).then_some((index, face)) - }) -} - -fn cjk_iso(script: CjkScript) -> &'static str { - match script { - CjkScript::Japanese => "Jpan", - CjkScript::SimplifiedChinese => "Hans", - CjkScript::TraditionalChinese => "Hant", - CjkScript::Korean => "Kore", - } -} - -fn script_iso(script: Script) -> &'static str { - use Script::*; - match script { - Thai => "Thai", - Lao => "Laoo", - Khmer => "Khmr", - Myanmar => "Mymr", - Tibetan => "Tibt", - Arabic => "Arab", - Hebrew => "Hebr", - Armenian => "Armn", - Georgian => "Geor", - Ethiopic => "Ethi", - Devanagari => "Deva", - Bengali => "Beng", - Gurmukhi => "Guru", - Gujarati => "Gujr", - Oriya => "Orya", - Tamil => "Taml", - Telugu => "Telu", - Kannada => "Knda", - Malayalam => "Mlym", - Sinhala => "Sinh", - } -} - -/// The manifest index of a craft face (the name suffix of its `FontInsert`). -fn craft_index(face: &CraftFont) -> Option { - craft_fonts::CRAFT_FONTS.iter().position(|candidate| std::ptr::eq(candidate, face)) -} - -/// Craft faces declaring `iso`, Regular first, with the Japanese UI face ahead of the other -/// Japanese faces (the explicit-locale choice; a non-CJK/unknown effective locale keeps the -/// manifest order). -fn craft_faces(iso: &str) -> Vec<(usize, &'static CraftFont)> { - let mut faces: Vec<(usize, &'static CraftFont)> = - craft_fonts::CRAFT_FONTS.iter().enumerate().filter(|(_, f)| !f.bytes.is_empty() && f.scripts.contains(&iso)).collect(); - faces.sort_by_key(|(_, f)| (f.family != craft_fonts::UI_JAPANESE_FAMILY, f.style != "Regular")); - faces -} - -/// Baseline and variable-weight tweaks shared by craft and system fallbacks. -fn apply_font_tweaks(data: &mut FontData) { - let offset = vertical_metrics(data.bytes(), data.index) - .zip(vertical_metrics(photocraft_text::fonts::INTER_REGULAR.as_slice(), 0)) - .map(|(face, primary)| baseline_offset(face, primary)); - let weight = regular_weight(data.bytes(), data.index); - if let Some(offset) = offset { - data.tweak.y_offset_factor = offset; - } - if let Some(weight) = weight { - data.tweak.coords = egui::epaint::text::VariationCoords::new([(b"wght", weight)]); - } -} - -fn font_insert(name: String, mut data: FontData, scale: f32) -> FontInsert { - data.tweak.scale = scale; - let families: Vec = - [FontFamily::Proportional, FontFamily::Monospace].into_iter().map(|family| InsertFontFamily { family, priority: FontPriority::Lowest }).collect(); - FontInsert::new(&name, data, families) -} - -/// One craft face as an egui font, with the same baseline/weight tweaks as a lazy fallback and the -/// current UI font-size multiplier. Added to both UI families: a discovered face is appended to -/// each family that asks for it, and a headless frame may use either. `FontData::from_static` -/// leaves the face index at its default 0; the coverage helpers above test that same face. -fn craft_insert(index: usize, face: &'static CraftFont, scale: f32) -> FontInsert { - let mut data = FontData::from_static(face.bytes); - apply_font_tweaks(&mut data); - font_insert(format!("craft-font-{index}"), data, scale) -} - -fn craft_provider_id() -> egui::Id { - egui::Id::unique("photocraft-craft-font-provider") -} - -/// The effective locale for CJK choice: an explicitly translated UI language -/// (ja/ko/zh-Hans/zh-Hant) wins; otherwise the OS locale, when known. -/// -/// An English UI on a Japanese, Korean or Chinese OS therefore uses that OS script, not the -/// migration baseline's manifest-first face. The baseline applies only when the effective locale -/// is non-CJK or unknown. -fn effective_locale(ui_code: &str, os_locale: Option<&str>) -> Option { - match ui_code { - "ja" | "ko" | "zh-hans" | "zh-hant" => Some(ui_code.to_owned()), - _ => os_locale.map(str::to_owned), - } -} - -impl Sources { - #[cfg(not(target_arch = "wasm32"))] - pub fn system() -> Self { - cjk::start_fontconfig_cjk_scan(); - Self { - locale: || effective_locale(crate::i18n::current().code(), cjk::ui_locale()), - files: cjk::font_files, - last_resort: cjk::last_resort_files, - pending: cjk::fontconfig_cjk_scan_pending, - scripts: scripts::system_candidates, - covers: scripts::covering_face, - embedded: craft_embedded_iso, - eager_craft_fonts: true, - } - } - #[cfg(target_arch = "wasm32")] - pub fn system() -> Self { - Self { - locale: || None, - files: |_| Vec::new(), - last_resort: Vec::new, - pending: || false, - scripts: |_| Vec::new(), - covers: scripts::covering_face, - embedded: craft_embedded_iso, - // The web build embeds no craft fonts; keep its font stack as it was. - eager_craft_fonts: false, - } - } -} - -/// Headless test frame pumps do not wait for `request_repaint_after`, so let the optional -/// Fontconfig worker finish before asserting on installed system fonts. `pub` (rather than -/// `pub(crate)`) so strict-policy integration tests can use the same wait as the unit tests. -/// -/// Returns whether the scan finished; it never panics in production. Test callers assert the -/// result (and choose their own message). -#[cfg(target_os = "linux")] -#[doc(hidden)] -pub fn wait_for_fontconfig_cjk_scan() -> bool { - cjk::start_fontconfig_cjk_scan(); - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); - while cjk::fontconfig_cjk_scan_pending() && std::time::Instant::now() < deadline { - std::thread::sleep(std::time::Duration::from_millis(10)); - } - !cjk::fontconfig_cjk_scan_pending() -} - -/// The lazy loader's state: which scripts were tried and which files were read. -pub struct CjkFallback { - sources: Sources, - /// set_fonts takes effect next pass; do not collide with a previous loader's font names. - defer_after_reset: bool, - order: Option<[CjkScript; 4]>, - tried: Vec, - last_resort_tried: bool, - /// Non-CJK scripts whose candidates were tried (each at most once per install). - scripts_tried: Vec